text
stringlengths
54
60.6k
<commit_before>/* * Copyright (c) 2011, Jim Hollinger * 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 Jim Hollinger nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <stdio.h> #include <stdlib.h> #include <conio.h> // _getch() #include <curl/curl.h> #define VERSION_STR "V1.0" // error handling macros #define my_curl_easy_setopt(A, B, C) \ if ((res = curl_easy_setopt((A), (B), (C))) != CURLE_OK) \ fprintf(stderr, "curl_easy_setopt(%s, %s, %s) failed: %d\n", #A, #B, #C, res); #define my_curl_easy_perform(A) \ if ((res = curl_easy_perform((A))) != CURLE_OK) \ fprintf(stderr, "curl_easy_perform(%s) failed: %d\n", #A, res); // send RTSP OPTIONS request void rtsp_options(CURL *curl, const char *uri) { CURLcode res = CURLE_OK; printf("\nRTSP: OPTIONS %s\n", uri); my_curl_easy_setopt(curl, CURLOPT_RTSP_STREAM_URI, uri); my_curl_easy_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_OPTIONS); my_curl_easy_perform(curl); } // send RTSP DESCRIBE request and write sdp response to a file void rtsp_describe(CURL *curl, const char *uri) { CURLcode res = CURLE_OK; printf("\nRTSP: DESCRIBE %s\n", uri); bool sdp_filename_new = false; char *sdp_filename = NULL; const char *s = strrchr(uri, '/'); if (s != NULL) { s++; if (s[0] != '\0') { sdp_filename = new char[strlen(s) + 8]; if (sdp_filename != NULL) { sprintf(sdp_filename, "%s.sdp", s); sdp_filename_new = true; } } } if (sdp_filename == NULL) { sdp_filename = "video.sdp"; } FILE *sdp_fp = fopen(sdp_filename, "wt"); if (sdp_fp == NULL) { fprintf(stderr, "Could not open '%s' for writing\n", sdp_filename); sdp_fp = stdout; } else { printf("Writing SDP to '%s'\n", sdp_filename); } my_curl_easy_setopt(curl, CURLOPT_WRITEDATA, sdp_fp); my_curl_easy_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_DESCRIBE); my_curl_easy_perform(curl); my_curl_easy_setopt(curl, CURLOPT_WRITEDATA, stdout); fclose(sdp_fp); if (sdp_filename_new) { delete []sdp_filename; } } // send RTSP SETUP request void rtsp_setup(CURL *curl, const char *uri, const char *transport) { CURLcode res = CURLE_OK; printf("\nRTSP: SETUP %s\n", uri); printf(" TRANSPORT %s\n", transport); my_curl_easy_setopt(curl, CURLOPT_RTSP_STREAM_URI, uri); my_curl_easy_setopt(curl, CURLOPT_RTSP_TRANSPORT, transport); my_curl_easy_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_SETUP); my_curl_easy_perform(curl); } // send RTSP PLAY request void rtsp_play(CURL *curl, const char *uri, const char *range) { CURLcode res = CURLE_OK; printf("\nRTSP: PLAY %s\n", uri); my_curl_easy_setopt(curl, CURLOPT_RTSP_STREAM_URI, uri); my_curl_easy_setopt(curl, CURLOPT_RANGE, range); my_curl_easy_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_PLAY); my_curl_easy_perform(curl); } // send RTSP TEARDOWN request void rtsp_teardown(CURL *curl, const char *uri) { CURLcode res = CURLE_OK; printf("\nRTSP: TEARDOWN %s\n", uri); my_curl_easy_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_TEARDOWN); my_curl_easy_perform(curl); } // main app int main(int argc, char **argv) { const char *transport = "RTP/AVP;unicast;client_port=1234-1235"; const char *range = "0.000-"; int rc = EXIT_SUCCESS; printf("\nRTSP request %s\n", VERSION_STR); printf(" Project web site: http://code.google.com/p/rtsprequest/\n"); printf(" Requires cURL V7.20 or greater\n\n"); // check command line char *basename = NULL; if ((argc != 2) && (argc != 3)) { basename = strrchr(argv[0], '/'); if (basename == NULL) { basename = strrchr(argv[0], '\\'); } if (basename == NULL) { basename = argv[0]; } else { basename++; } printf("Usage: %s url [transport]\n", basename); printf(" url of video server\n"); printf(" transport (optional) specifier for media stream protocol\n"); printf(" default transport: %s\n", transport); printf("Example: %s rtsp://192.168.0.2/media/video1\n\n", basename); rc = EXIT_FAILURE; } else { const char *url = argv[1]; char *uri = new char[strlen(url) + 32]; if (argc == 3) { transport = argv[2]; } // initialize curl CURLcode res = CURLE_OK; res = curl_global_init(CURL_GLOBAL_ALL); if (res == CURLE_OK) { curl_version_info_data *data = curl_version_info(CURLVERSION_NOW); fprintf(stderr, " cURL V%s loaded\n", data->version); // initialize this curl session CURL *curl = curl_easy_init(); if (curl != NULL) { my_curl_easy_setopt(curl, CURLOPT_VERBOSE, 0L); my_curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L); my_curl_easy_setopt(curl, CURLOPT_WRITEHEADER, stdout); my_curl_easy_setopt(curl, CURLOPT_URL, url); // request server options sprintf(uri, "%s", url); rtsp_options(curl, uri); // open sdp file and request session description rtsp_describe(curl, uri); // setup media stream sprintf(uri, "%s/video", url); rtsp_setup(curl, uri, transport); // start playing media stream sprintf(uri, "%s/", url); rtsp_play(curl, uri, range); printf("Playing video, press any key to stop ..."); _getch(); printf("\n"); // teardown session rtsp_teardown(curl, uri); // cleanup curl_easy_cleanup(curl); curl = NULL; } else { fprintf(stderr, "curl_easy_init() failed\n"); } curl_global_cleanup(); } else { fprintf(stderr, "curl_global_init(%s) failed\n", "CURL_GLOBAL_ALL", res); } } return rc; } <commit_msg>Now parses sdp file for media control attribute.<commit_after>/* * Copyright (c) 2011, Jim Hollinger * 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 Jim Hollinger nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <stdio.h> #include <stdlib.h> #include <conio.h> // _getch() #include <curl/curl.h> #define VERSION_STR "V1.0" // error handling macros #define my_curl_easy_setopt(A, B, C) \ if ((res = curl_easy_setopt((A), (B), (C))) != CURLE_OK) \ fprintf(stderr, "curl_easy_setopt(%s, %s, %s) failed: %d\n", #A, #B, #C, res); #define my_curl_easy_perform(A) \ if ((res = curl_easy_perform((A))) != CURLE_OK) \ fprintf(stderr, "curl_easy_perform(%s) failed: %d\n", #A, res); // send RTSP OPTIONS request void rtsp_options(CURL *curl, const char *uri) { CURLcode res = CURLE_OK; printf("\nRTSP: OPTIONS %s\n", uri); my_curl_easy_setopt(curl, CURLOPT_RTSP_STREAM_URI, uri); my_curl_easy_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_OPTIONS); my_curl_easy_perform(curl); } // send RTSP DESCRIBE request and write sdp response to a file void rtsp_describe(CURL *curl, const char *uri, const char *sdp_filename) { CURLcode res = CURLE_OK; printf("\nRTSP: DESCRIBE %s\n", uri); FILE *sdp_fp = fopen(sdp_filename, "wt"); if (sdp_fp == NULL) { fprintf(stderr, "Could not open '%s' for writing\n", sdp_filename); sdp_fp = stdout; } else { printf("Writing SDP to '%s'\n", sdp_filename); } my_curl_easy_setopt(curl, CURLOPT_WRITEDATA, sdp_fp); my_curl_easy_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_DESCRIBE); my_curl_easy_perform(curl); my_curl_easy_setopt(curl, CURLOPT_WRITEDATA, stdout); if (sdp_fp != stdout) { fclose(sdp_fp); } } // send RTSP SETUP request void rtsp_setup(CURL *curl, const char *uri, const char *transport) { CURLcode res = CURLE_OK; printf("\nRTSP: SETUP %s\n", uri); printf(" TRANSPORT %s\n", transport); my_curl_easy_setopt(curl, CURLOPT_RTSP_STREAM_URI, uri); my_curl_easy_setopt(curl, CURLOPT_RTSP_TRANSPORT, transport); my_curl_easy_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_SETUP); my_curl_easy_perform(curl); } // send RTSP PLAY request void rtsp_play(CURL *curl, const char *uri, const char *range) { CURLcode res = CURLE_OK; printf("\nRTSP: PLAY %s\n", uri); my_curl_easy_setopt(curl, CURLOPT_RTSP_STREAM_URI, uri); my_curl_easy_setopt(curl, CURLOPT_RANGE, range); my_curl_easy_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_PLAY); my_curl_easy_perform(curl); } // send RTSP TEARDOWN request void rtsp_teardown(CURL *curl, const char *uri) { CURLcode res = CURLE_OK; printf("\nRTSP: TEARDOWN %s\n", uri); my_curl_easy_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_TEARDOWN); my_curl_easy_perform(curl); } // convert url into an sdp filename void get_sdp_filename(const char *url, char *sdp_filename) { strcpy(sdp_filename, "video.sdp"); const char *s = strrchr(url, '/'); if (s != NULL) { s++; if (s[0] != '\0') { sprintf(sdp_filename, "%s.sdp", s); } } } // scan sdp file for media control attribute void get_media_control_attribute(const char *sdp_filename, char *control) { control[0] = '\0'; int max_len = 256; char *s = new char[max_len]; FILE *sdp_fp = fopen(sdp_filename, "rt"); if (sdp_fp != NULL) { while(fgets(s, max_len - 2, sdp_fp) != NULL) { sscanf(s, " a = control: %s", control); } fclose(sdp_fp); } delete []s; } // main app int main(int argc, char **argv) { const char *transport = "RTP/AVP;unicast;client_port=1234-1235"; const char *range = "0.000-"; int rc = EXIT_SUCCESS; printf("\nRTSP request %s\n", VERSION_STR); printf(" Project web site: http://code.google.com/p/rtsprequest/\n"); printf(" Requires cURL V7.20 or greater\n\n"); // check command line char *basename = NULL; if ((argc != 2) && (argc != 3)) { basename = strrchr(argv[0], '/'); if (basename == NULL) { basename = strrchr(argv[0], '\\'); } if (basename == NULL) { basename = argv[0]; } else { basename++; } printf("Usage: %s url [transport]\n", basename); printf(" url of video server\n"); printf(" transport (optional) specifier for media stream protocol\n"); printf(" default transport: %s\n", transport); printf("Example: %s rtsp://192.168.0.2/media/video1\n\n", basename); rc = EXIT_FAILURE; } else { const char *url = argv[1]; char *uri = new char[strlen(url) + 32]; char *sdp_filename = new char[strlen(url) + 32]; char *control = new char[strlen(url) + 32]; get_sdp_filename(url, sdp_filename); if (argc == 3) { transport = argv[2]; } // initialize curl CURLcode res = CURLE_OK; res = curl_global_init(CURL_GLOBAL_ALL); if (res == CURLE_OK) { curl_version_info_data *data = curl_version_info(CURLVERSION_NOW); fprintf(stderr, " cURL V%s loaded\n", data->version); // initialize this curl session CURL *curl = curl_easy_init(); if (curl != NULL) { my_curl_easy_setopt(curl, CURLOPT_VERBOSE, 0L); my_curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L); my_curl_easy_setopt(curl, CURLOPT_WRITEHEADER, stdout); my_curl_easy_setopt(curl, CURLOPT_URL, url); // request server options sprintf(uri, "%s", url); rtsp_options(curl, uri); // request session description and write response to sdp file rtsp_describe(curl, uri, sdp_filename); // get media control attribute from sdp file get_media_control_attribute(sdp_filename, control); // setup media stream sprintf(uri, "%s/%s", url, control); rtsp_setup(curl, uri, transport); // start playing media stream sprintf(uri, "%s/", url); rtsp_play(curl, uri, range); printf("Playing video, press any key to stop ..."); _getch(); printf("\n"); // teardown session rtsp_teardown(curl, uri); // cleanup curl_easy_cleanup(curl); curl = NULL; } else { fprintf(stderr, "curl_easy_init() failed\n"); } curl_global_cleanup(); } else { fprintf(stderr, "curl_global_init(%s) failed\n", "CURL_GLOBAL_ALL", res); } delete []control; delete []sdp_filename; delete []uri; } return rc; } <|endoftext|>
<commit_before>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/node_bindings.h" #include <string> #include <vector> #include "atom/common/atom_command_line.h" #include "atom/common/event_emitter_caller.h" #include "atom/common/native_mate_converters/file_path_converter.h" #include "base/command_line.h" #include "base/base_paths.h" #include "base/files/file_path.h" #include "base/message_loop/message_loop.h" #include "base/path_service.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_paths.h" #include "native_mate/locker.h" #include "native_mate/dictionary.h" #include "atom/common/node_includes.h" using content::BrowserThread; // Force all builtin modules to be referenced so they can actually run their // DSO constructors, see http://git.io/DRIqCg. #define REFERENCE_MODULE(name) \ extern "C" void _register_ ## name(void); \ void (*fp_register_ ## name)(void) = _register_ ## name // Electron's builtin modules. REFERENCE_MODULE(atom_browser_app); REFERENCE_MODULE(atom_browser_auto_updater); REFERENCE_MODULE(atom_browser_content_tracing); REFERENCE_MODULE(atom_browser_dialog); REFERENCE_MODULE(atom_browser_menu); REFERENCE_MODULE(atom_browser_power_monitor); REFERENCE_MODULE(atom_browser_power_save_blocker); REFERENCE_MODULE(atom_browser_protocol); REFERENCE_MODULE(atom_browser_global_shortcut); REFERENCE_MODULE(atom_browser_tray); REFERENCE_MODULE(atom_browser_web_contents); REFERENCE_MODULE(atom_browser_web_view_manager); REFERENCE_MODULE(atom_browser_window); REFERENCE_MODULE(atom_common_asar); REFERENCE_MODULE(atom_common_clipboard); REFERENCE_MODULE(atom_common_crash_reporter); REFERENCE_MODULE(atom_common_id_weak_map); REFERENCE_MODULE(atom_common_native_image); REFERENCE_MODULE(atom_common_screen); REFERENCE_MODULE(atom_common_shell); REFERENCE_MODULE(atom_common_v8_util); REFERENCE_MODULE(atom_renderer_ipc); REFERENCE_MODULE(atom_renderer_web_frame); #undef REFERENCE_MODULE // The "v8::Function::kLineOffsetNotFound" is exported in node.dll, but the // linker can not find it, could be a bug of VS. #if defined(OS_WIN) && !defined(DEBUG) namespace v8 { const int Function::kLineOffsetNotFound = -1; } #endif namespace atom { namespace { // Empty callback for async handle. void UvNoOp(uv_async_t* handle) { } // Convert the given vector to an array of C-strings. The strings in the // returned vector are only guaranteed valid so long as the vector of strings // is not modified. scoped_ptr<const char*[]> StringVectorToArgArray( const std::vector<std::string>& vector) { scoped_ptr<const char*[]> array(new const char*[vector.size()]); for (size_t i = 0; i < vector.size(); ++i) { array[i] = vector[i].c_str(); } return array.Pass(); } base::FilePath GetResourcesPath(bool is_browser) { auto command_line = base::CommandLine::ForCurrentProcess(); base::FilePath exec_path(command_line->GetProgram()); PathService::Get(base::FILE_EXE, &exec_path); base::FilePath resources_path = #if defined(OS_MACOSX) is_browser ? exec_path.DirName().DirName().Append("Resources") : exec_path.DirName().DirName().DirName().DirName().DirName() .Append("Resources"); #else exec_path.DirName().Append(FILE_PATH_LITERAL("resources")); #endif return resources_path; } } // namespace node::Environment* global_env = nullptr; NodeBindings::NodeBindings(bool is_browser) : is_browser_(is_browser), message_loop_(nullptr), uv_loop_(uv_default_loop()), embed_closed_(false), uv_env_(nullptr), weak_factory_(this) { } NodeBindings::~NodeBindings() { // Quit the embed thread. embed_closed_ = true; uv_sem_post(&embed_sem_); WakeupEmbedThread(); // Wait for everything to be done. uv_thread_join(&embed_thread_); // Clear uv. uv_sem_destroy(&embed_sem_); } void NodeBindings::Initialize() { // Open node's error reporting system for browser process. node::g_standalone_mode = is_browser_; node::g_upstream_node_mode = false; #if defined(OS_LINUX) // Get real command line in renderer process forked by zygote. if (!is_browser_) AtomCommandLine::InitializeFromCommandLine(); #endif // Parse the debug args. auto args = AtomCommandLine::argv(); for (const std::string& arg : args) node::ParseDebugOpt(arg.c_str()); // Init node. // (we assume node::Init would not modify the parameters under embedded mode). node::Init(nullptr, nullptr, nullptr, nullptr); } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context) { auto args = AtomCommandLine::argv(); // Feed node the path to initialization script. base::FilePath::StringType process_type = is_browser_ ? FILE_PATH_LITERAL("browser") : FILE_PATH_LITERAL("renderer"); base::FilePath resources_path = GetResourcesPath(is_browser_); base::FilePath script_path = resources_path.Append(FILE_PATH_LITERAL("atom.asar")) .Append(process_type) .Append(FILE_PATH_LITERAL("lib")) .Append(FILE_PATH_LITERAL("init.js")); std::string script_path_str = script_path.AsUTF8Unsafe(); args.insert(args.begin() + 1, script_path_str.c_str()); scoped_ptr<const char*[]> c_argv = StringVectorToArgArray(args); node::Environment* env = node::CreateEnvironment( context->GetIsolate(), uv_default_loop(), context, args.size(), c_argv.get(), 0, nullptr); mate::Dictionary process(context->GetIsolate(), env->process_object()); process.Set("type", process_type); process.Set("resourcesPath", resources_path); // The path to helper app. base::FilePath helper_exec_path; PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path); process.Set("helperExecPath", helper_exec_path); return env; } void NodeBindings::LoadEnvironment(node::Environment* env) { node::node_isolate = env->isolate(); if (node::use_debug_agent) node::StartDebug(env, node::debug_wait_connect); node::LoadEnvironment(env); if (node::use_debug_agent) node::EnableDebug(env); mate::EmitEvent(env->isolate(), env->process_object(), "loaded"); } void NodeBindings::PrepareMessageLoop() { DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI)); // Add dummy handle for libuv, otherwise libuv would quit when there is // nothing to do. uv_async_init(uv_loop_, &dummy_uv_handle_, UvNoOp); // Start worker that will interrupt main loop when having uv events. uv_sem_init(&embed_sem_, 0); uv_thread_create(&embed_thread_, EmbedThreadRunner, this); } void NodeBindings::RunMessageLoop() { DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI)); // The MessageLoop should have been created, remember the one in main thread. message_loop_ = base::MessageLoop::current(); // Run uv loop for once to give the uv__io_poll a chance to add all events. UvRunOnce(); } void NodeBindings::UvRunOnce() { DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI)); // By default the global env would be used unless user specified another one // (this happens for renderer process, which wraps the uv loop with web page // context). node::Environment* env = uv_env() ? uv_env() : global_env; // Use Locker in browser process. mate::Locker locker(env->isolate()); v8::HandleScope handle_scope(env->isolate()); // Enter node context while dealing with uv events. v8::Context::Scope context_scope(env->context()); // Deal with uv events. int r = uv_run(uv_loop_, UV_RUN_NOWAIT); if (r == 0 || uv_loop_->stop_flag != 0) message_loop_->QuitWhenIdle(); // Quit from uv. // Tell the worker thread to continue polling. uv_sem_post(&embed_sem_); } void NodeBindings::WakeupMainThread() { DCHECK(message_loop_); message_loop_->PostTask(FROM_HERE, base::Bind(&NodeBindings::UvRunOnce, weak_factory_.GetWeakPtr())); } void NodeBindings::WakeupEmbedThread() { uv_async_send(&dummy_uv_handle_); } // static void NodeBindings::EmbedThreadRunner(void *arg) { NodeBindings* self = static_cast<NodeBindings*>(arg); while (true) { // Wait for the main loop to deal with events. uv_sem_wait(&self->embed_sem_); if (self->embed_closed_) break; // Wait for something to happen in uv loop. // Note that the PollEvents() is implemented by derived classes, so when // this class is being destructed the PollEvents() would not be available // anymore. Because of it we must make sure we only invoke PollEvents() // when this class is alive. self->PollEvents(); if (self->embed_closed_) break; // Deal with event in main thread. self->WakeupMainThread(); } } } // namespace atom <commit_msg>Perform microtask checkpoint after diving into libuv<commit_after>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/node_bindings.h" #include <string> #include <vector> #include "atom/common/atom_command_line.h" #include "atom/common/event_emitter_caller.h" #include "atom/common/native_mate_converters/file_path_converter.h" #include "base/command_line.h" #include "base/base_paths.h" #include "base/files/file_path.h" #include "base/message_loop/message_loop.h" #include "base/path_service.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_paths.h" #include "native_mate/locker.h" #include "native_mate/dictionary.h" #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h" #include "atom/common/node_includes.h" using content::BrowserThread; // Force all builtin modules to be referenced so they can actually run their // DSO constructors, see http://git.io/DRIqCg. #define REFERENCE_MODULE(name) \ extern "C" void _register_ ## name(void); \ void (*fp_register_ ## name)(void) = _register_ ## name // Electron's builtin modules. REFERENCE_MODULE(atom_browser_app); REFERENCE_MODULE(atom_browser_auto_updater); REFERENCE_MODULE(atom_browser_content_tracing); REFERENCE_MODULE(atom_browser_dialog); REFERENCE_MODULE(atom_browser_menu); REFERENCE_MODULE(atom_browser_power_monitor); REFERENCE_MODULE(atom_browser_power_save_blocker); REFERENCE_MODULE(atom_browser_protocol); REFERENCE_MODULE(atom_browser_global_shortcut); REFERENCE_MODULE(atom_browser_tray); REFERENCE_MODULE(atom_browser_web_contents); REFERENCE_MODULE(atom_browser_web_view_manager); REFERENCE_MODULE(atom_browser_window); REFERENCE_MODULE(atom_common_asar); REFERENCE_MODULE(atom_common_clipboard); REFERENCE_MODULE(atom_common_crash_reporter); REFERENCE_MODULE(atom_common_id_weak_map); REFERENCE_MODULE(atom_common_native_image); REFERENCE_MODULE(atom_common_screen); REFERENCE_MODULE(atom_common_shell); REFERENCE_MODULE(atom_common_v8_util); REFERENCE_MODULE(atom_renderer_ipc); REFERENCE_MODULE(atom_renderer_web_frame); #undef REFERENCE_MODULE // The "v8::Function::kLineOffsetNotFound" is exported in node.dll, but the // linker can not find it, could be a bug of VS. #if defined(OS_WIN) && !defined(DEBUG) namespace v8 { const int Function::kLineOffsetNotFound = -1; } #endif namespace atom { namespace { // Empty callback for async handle. void UvNoOp(uv_async_t* handle) { } // Convert the given vector to an array of C-strings. The strings in the // returned vector are only guaranteed valid so long as the vector of strings // is not modified. scoped_ptr<const char*[]> StringVectorToArgArray( const std::vector<std::string>& vector) { scoped_ptr<const char*[]> array(new const char*[vector.size()]); for (size_t i = 0; i < vector.size(); ++i) { array[i] = vector[i].c_str(); } return array.Pass(); } base::FilePath GetResourcesPath(bool is_browser) { auto command_line = base::CommandLine::ForCurrentProcess(); base::FilePath exec_path(command_line->GetProgram()); PathService::Get(base::FILE_EXE, &exec_path); base::FilePath resources_path = #if defined(OS_MACOSX) is_browser ? exec_path.DirName().DirName().Append("Resources") : exec_path.DirName().DirName().DirName().DirName().DirName() .Append("Resources"); #else exec_path.DirName().Append(FILE_PATH_LITERAL("resources")); #endif return resources_path; } } // namespace node::Environment* global_env = nullptr; NodeBindings::NodeBindings(bool is_browser) : is_browser_(is_browser), message_loop_(nullptr), uv_loop_(uv_default_loop()), embed_closed_(false), uv_env_(nullptr), weak_factory_(this) { } NodeBindings::~NodeBindings() { // Quit the embed thread. embed_closed_ = true; uv_sem_post(&embed_sem_); WakeupEmbedThread(); // Wait for everything to be done. uv_thread_join(&embed_thread_); // Clear uv. uv_sem_destroy(&embed_sem_); } void NodeBindings::Initialize() { // Open node's error reporting system for browser process. node::g_standalone_mode = is_browser_; node::g_upstream_node_mode = false; #if defined(OS_LINUX) // Get real command line in renderer process forked by zygote. if (!is_browser_) AtomCommandLine::InitializeFromCommandLine(); #endif // Parse the debug args. auto args = AtomCommandLine::argv(); for (const std::string& arg : args) node::ParseDebugOpt(arg.c_str()); // Init node. // (we assume node::Init would not modify the parameters under embedded mode). node::Init(nullptr, nullptr, nullptr, nullptr); } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context) { auto args = AtomCommandLine::argv(); // Feed node the path to initialization script. base::FilePath::StringType process_type = is_browser_ ? FILE_PATH_LITERAL("browser") : FILE_PATH_LITERAL("renderer"); base::FilePath resources_path = GetResourcesPath(is_browser_); base::FilePath script_path = resources_path.Append(FILE_PATH_LITERAL("atom.asar")) .Append(process_type) .Append(FILE_PATH_LITERAL("lib")) .Append(FILE_PATH_LITERAL("init.js")); std::string script_path_str = script_path.AsUTF8Unsafe(); args.insert(args.begin() + 1, script_path_str.c_str()); scoped_ptr<const char*[]> c_argv = StringVectorToArgArray(args); node::Environment* env = node::CreateEnvironment( context->GetIsolate(), uv_default_loop(), context, args.size(), c_argv.get(), 0, nullptr); mate::Dictionary process(context->GetIsolate(), env->process_object()); process.Set("type", process_type); process.Set("resourcesPath", resources_path); // The path to helper app. base::FilePath helper_exec_path; PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path); process.Set("helperExecPath", helper_exec_path); return env; } void NodeBindings::LoadEnvironment(node::Environment* env) { node::node_isolate = env->isolate(); if (node::use_debug_agent) node::StartDebug(env, node::debug_wait_connect); node::LoadEnvironment(env); if (node::use_debug_agent) node::EnableDebug(env); mate::EmitEvent(env->isolate(), env->process_object(), "loaded"); } void NodeBindings::PrepareMessageLoop() { DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI)); // Add dummy handle for libuv, otherwise libuv would quit when there is // nothing to do. uv_async_init(uv_loop_, &dummy_uv_handle_, UvNoOp); // Start worker that will interrupt main loop when having uv events. uv_sem_init(&embed_sem_, 0); uv_thread_create(&embed_thread_, EmbedThreadRunner, this); } void NodeBindings::RunMessageLoop() { DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI)); // The MessageLoop should have been created, remember the one in main thread. message_loop_ = base::MessageLoop::current(); // Run uv loop for once to give the uv__io_poll a chance to add all events. UvRunOnce(); } void NodeBindings::UvRunOnce() { DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI)); // By default the global env would be used unless user specified another one // (this happens for renderer process, which wraps the uv loop with web page // context). node::Environment* env = uv_env() ? uv_env() : global_env; // Use Locker in browser process. mate::Locker locker(env->isolate()); v8::HandleScope handle_scope(env->isolate()); // Enter node context while dealing with uv events. v8::Context::Scope context_scope(env->context()); // Perform microtask checkpoint after running JavaScript. scoped_ptr<blink::WebScopedRunV8Script> script_scope( is_browser_ ? nullptr : new blink::WebScopedRunV8Script(env->isolate())); // Deal with uv events. int r = uv_run(uv_loop_, UV_RUN_NOWAIT); if (r == 0 || uv_loop_->stop_flag != 0) message_loop_->QuitWhenIdle(); // Quit from uv. // Tell the worker thread to continue polling. uv_sem_post(&embed_sem_); } void NodeBindings::WakeupMainThread() { DCHECK(message_loop_); message_loop_->PostTask(FROM_HERE, base::Bind(&NodeBindings::UvRunOnce, weak_factory_.GetWeakPtr())); } void NodeBindings::WakeupEmbedThread() { uv_async_send(&dummy_uv_handle_); } // static void NodeBindings::EmbedThreadRunner(void *arg) { NodeBindings* self = static_cast<NodeBindings*>(arg); while (true) { // Wait for the main loop to deal with events. uv_sem_wait(&self->embed_sem_); if (self->embed_closed_) break; // Wait for something to happen in uv loop. // Note that the PollEvents() is implemented by derived classes, so when // this class is being destructed the PollEvents() would not be available // anymore. Because of it we must make sure we only invoke PollEvents() // when this class is alive. self->PollEvents(); if (self->embed_closed_) break; // Deal with event in main thread. self->WakeupMainThread(); } } } // namespace atom <|endoftext|>
<commit_before>/** \file normalise_and_deduplicate_language.cc * \brief Normalises language codes and removes duplicates from specific MARC record fields * \author Madeeswaran Kannan (madeeswaran.kannan@uni-tuebingen.de) * * \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <unordered_map> #include <unordered_set> #include <cinttypes> #include <cstring> #include <unistd.h> #include "IniFile.h" #include "MARC.h" #include "StringUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [--verbosity=min_verbosity] marc_input marc_output\n" << " Normalises language codes and removes their duplicates from specific MARC " "record fields (008 and 041).\n"; std::exit(EXIT_FAILURE); } const std::string CONFIG_FILE_PATH("/usr/local/var/lib/tuelib/normalize_and_deduplicate_language.conf"); const std::string LANGUAGE_CODE_OVERRIDE_SECTION("Overrides"); struct LanguageCodeParams { static constexpr size_t LANGUAGE_CODE_LENGTH = 3; std::unordered_map<std::string, std::string> variant_to_canonical_form_map_; std::unordered_set<std::string> valid_language_codes_; public: inline bool isCanonical(const std::string &language_code) { return valid_language_codes_.find(language_code) != valid_language_codes_.end(); } bool getCanonicalCode(const std::string &language_code, std::string * const canonical_code, const bool fallback_to_original = true); }; bool HasValidLanguageCodeLength(const std::string &language_code) { return language_code.length() == LanguageCodeParams::LANGUAGE_CODE_LENGTH; } bool LanguageCodeParams::getCanonicalCode(const std::string &language_code, std::string * const canonical_code, const bool fallback_to_original) { if (isCanonical(language_code)) { *canonical_code = language_code; return true; } const auto match(variant_to_canonical_form_map_.find(language_code)); if (match != variant_to_canonical_form_map_.cend()) { *canonical_code = match->second; return true; } else { if (fallback_to_original) *canonical_code = language_code; return false; } } void LoadLanguageCodesFromConfig(const IniFile &config, LanguageCodeParams * const params) { std::vector<std::string> raw_language_codes; StringUtil::Split(config.getString("", "canonical_language_codes"), ",", &raw_language_codes); if (raw_language_codes.empty()) LOG_ERROR("Couldn't read canonical language codes from config file '" + CONFIG_FILE_PATH + "'!"); for (const auto &language_code : raw_language_codes) { if (not HasValidLanguageCodeLength(language_code)) LOG_ERROR("Invalid length for language code '" + language_code + "'!"); else if (params->isCanonical(language_code)) LOG_WARNING("Duplicate canonical language code '" + language_code + "' found!"); else params->valid_language_codes_.insert(language_code); } for (const auto &variant : config.getSectionEntryNames(LANGUAGE_CODE_OVERRIDE_SECTION)) { const auto canonical_name(config.getString(LANGUAGE_CODE_OVERRIDE_SECTION, variant)); if (not HasValidLanguageCodeLength(variant)) LOG_ERROR("Invalid length for language code '" + variant + "'!"); else if (not HasValidLanguageCodeLength(canonical_name)) LOG_ERROR("Invalid length for language code '" + canonical_name + "'!"); else if (not params->isCanonical(canonical_name)) LOG_ERROR("Unknown canonical language code '" + canonical_name + "' for variant '" + variant + "'!"); params->variant_to_canonical_form_map_.insert(std::make_pair(variant, canonical_name)); } } } // unnamed namespace int Main(int argc, char *argv[]) { ::progname = argv[0]; if (argc < 2) Usage(); IniFile config_file(CONFIG_FILE_PATH); LanguageCodeParams params; std::unique_ptr<MARC::Reader> reader(MARC::Reader::Factory(argv[1])); std::unique_ptr<MARC::Writer> writer(MARC::Writer::Factory(argv[2])); LoadLanguageCodesFromConfig(config_file, &params); int num_records(0); while (MARC::Record record = reader->read()) { ++num_records; const auto ppn(record.findTag("001")->getContents()); const auto LogOutput = [&ppn, &num_records](const std::string &message, bool warning = false) { const auto msg("Record '" + ppn + "' [" + std::to_string(num_records) + "]: " + message); if (not warning) LOG_INFO(msg); else LOG_WARNING(msg); }; const auto tag_008(record.findTag("008")); const auto tag_041(record.findTag("041")); auto language_code_008(tag_008->getContents().substr(35, 3)); StringUtil::Trim(&language_code_008); if (language_code_008.empty() or language_code_008 == "|||") language_code_008.clear(); // to indicate absence in the case of '|||' else { std::string language_code_008_normalized; if (not params.getCanonicalCode(language_code_008, &language_code_008_normalized)) LogOutput("Unknown language code variant '" + language_code_008 + "' in control field 008", true); if (language_code_008 != language_code_008_normalized) { LogOutput("Normalized control field 008 language code: '" + language_code_008 + "' => " + language_code_008_normalized + "'"); auto old_content(tag_008->getContents()); old_content.replace(35, 3, language_code_008_normalized); tag_008->setContents(old_content); language_code_008 = language_code_008_normalized; } } if (tag_041 == record.end()) { if (not language_code_008.empty()) { LogOutput("Copying language code '" + language_code_008 + "' from 008 => 041"); record.insertField("041", { { 'a', language_code_008 } }); } } else { // normalize and remove the existing records MARC::Record::Field modified_tag_041(*tag_041); MARC::Subfields modified_subfields; bool propagate_changes(false); std::unordered_set<std::string> unique_language_codes; const auto indicator1(modified_tag_041.getIndicator1()), indicator2(modified_tag_041.getIndicator2()); for (auto& subfield : tag_041->getSubfields()) { if (unique_language_codes.find(subfield.value_) != unique_language_codes.end()) { LogOutput("Removing duplicate subfield entry 041$" + std::string(1, subfield.code_) + " '" + subfield.value_ + "'"); propagate_changes = true; continue; } std::string normalized_language_code; if (not params.getCanonicalCode(subfield.value_, &normalized_language_code)) { LogOutput("Unknown language code variant '" + subfield.value_ + "' in subfield 041$" + std::string(1, subfield.code_), true); } if (normalized_language_code != subfield.value_) { LogOutput("Normalized subfield 041$" + std::string(1, subfield.code_) + " language code: '" + subfield.value_ + "' => '" + normalized_language_code + "'"); subfield.value_ = normalized_language_code; propagate_changes = true; } unique_language_codes.insert(subfield.value_); modified_subfields.addSubfield(subfield.code_, subfield.value_); } if (propagate_changes) tag_041->setContents(modified_subfields, indicator1, indicator2); } writer->write(record); } return EXIT_SUCCESS; } <commit_msg>Very last, final change<commit_after>/** \file normalise_and_deduplicate_language.cc * \brief Normalises language codes and removes duplicates from specific MARC record fields * \author Madeeswaran Kannan (madeeswaran.kannan@uni-tuebingen.de) * * \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <unordered_map> #include <unordered_set> #include <cinttypes> #include <cstring> #include <unistd.h> #include "IniFile.h" #include "MARC.h" #include "StringUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [--verbosity=min_verbosity] marc_input marc_output\n" << " Normalises language codes and removes their duplicates from specific MARC " "record fields (008 and 041).\n"; std::exit(EXIT_FAILURE); } const std::string CONFIG_FILE_PATH("/usr/local/var/lib/tuelib/normalise_and_deduplicate_language.conf"); const std::string LANGUAGE_CODE_OVERRIDE_SECTION("Overrides"); struct LanguageCodeParams { static constexpr size_t LANGUAGE_CODE_LENGTH = 3; std::unordered_map<std::string, std::string> variant_to_canonical_form_map_; std::unordered_set<std::string> valid_language_codes_; public: inline bool isCanonical(const std::string &language_code) { return valid_language_codes_.find(language_code) != valid_language_codes_.end(); } bool getCanonicalCode(const std::string &language_code, std::string * const canonical_code, const bool fallback_to_original = true); }; bool HasValidLanguageCodeLength(const std::string &language_code) { return language_code.length() == LanguageCodeParams::LANGUAGE_CODE_LENGTH; } bool LanguageCodeParams::getCanonicalCode(const std::string &language_code, std::string * const canonical_code, const bool fallback_to_original) { if (isCanonical(language_code)) { *canonical_code = language_code; return true; } const auto match(variant_to_canonical_form_map_.find(language_code)); if (match != variant_to_canonical_form_map_.cend()) { *canonical_code = match->second; return true; } else { if (fallback_to_original) *canonical_code = language_code; return false; } } void LoadLanguageCodesFromConfig(const IniFile &config, LanguageCodeParams * const params) { std::vector<std::string> raw_language_codes; StringUtil::Split(config.getString("", "canonical_language_codes"), ",", &raw_language_codes); if (raw_language_codes.empty()) LOG_ERROR("Couldn't read canonical language codes from config file '" + CONFIG_FILE_PATH + "'!"); for (const auto &language_code : raw_language_codes) { if (not HasValidLanguageCodeLength(language_code)) LOG_ERROR("Invalid length for language code '" + language_code + "'!"); else if (params->isCanonical(language_code)) LOG_WARNING("Duplicate canonical language code '" + language_code + "' found!"); else params->valid_language_codes_.insert(language_code); } for (const auto &variant : config.getSectionEntryNames(LANGUAGE_CODE_OVERRIDE_SECTION)) { const auto canonical_name(config.getString(LANGUAGE_CODE_OVERRIDE_SECTION, variant)); if (not HasValidLanguageCodeLength(variant)) LOG_ERROR("Invalid length for language code '" + variant + "'!"); else if (not HasValidLanguageCodeLength(canonical_name)) LOG_ERROR("Invalid length for language code '" + canonical_name + "'!"); else if (not params->isCanonical(canonical_name)) LOG_ERROR("Unknown canonical language code '" + canonical_name + "' for variant '" + variant + "'!"); params->variant_to_canonical_form_map_.insert(std::make_pair(variant, canonical_name)); } } } // unnamed namespace int Main(int argc, char *argv[]) { ::progname = argv[0]; if (argc < 2) Usage(); IniFile config_file(CONFIG_FILE_PATH); LanguageCodeParams params; std::unique_ptr<MARC::Reader> reader(MARC::Reader::Factory(argv[1])); std::unique_ptr<MARC::Writer> writer(MARC::Writer::Factory(argv[2])); LoadLanguageCodesFromConfig(config_file, &params); int num_records(0); while (MARC::Record record = reader->read()) { ++num_records; const auto ppn(record.findTag("001")->getContents()); const auto LogOutput = [&ppn, &num_records](const std::string &message, bool warning = false) { const auto msg("Record '" + ppn + "' [" + std::to_string(num_records) + "]: " + message); if (not warning) LOG_INFO(msg); else LOG_WARNING(msg); }; const auto tag_008(record.findTag("008")); const auto tag_041(record.findTag("041")); auto language_code_008(tag_008->getContents().substr(35, 3)); StringUtil::Trim(&language_code_008); if (language_code_008.empty() or language_code_008 == "|||") language_code_008.clear(); // to indicate absence in the case of '|||' else { std::string language_code_008_normalized; if (not params.getCanonicalCode(language_code_008, &language_code_008_normalized)) LogOutput("Unknown language code variant '" + language_code_008 + "' in control field 008", true); if (language_code_008 != language_code_008_normalized) { LogOutput("Normalized control field 008 language code: '" + language_code_008 + "' => " + language_code_008_normalized + "'"); auto old_content(tag_008->getContents()); old_content.replace(35, 3, language_code_008_normalized); tag_008->setContents(old_content); language_code_008 = language_code_008_normalized; } } if (tag_041 == record.end()) { if (not language_code_008.empty()) { LogOutput("Copying language code '" + language_code_008 + "' from 008 => 041"); record.insertField("041", { { 'a', language_code_008 } }); } } else { // normalize and remove the existing records MARC::Record::Field modified_tag_041(*tag_041); MARC::Subfields modified_subfields; bool propagate_changes(false); std::unordered_set<std::string> unique_language_codes; const auto indicator1(modified_tag_041.getIndicator1()), indicator2(modified_tag_041.getIndicator2()); for (auto& subfield : tag_041->getSubfields()) { if (unique_language_codes.find(subfield.value_) != unique_language_codes.end()) { LogOutput("Removing duplicate subfield entry 041$" + std::string(1, subfield.code_) + " '" + subfield.value_ + "'"); propagate_changes = true; continue; } std::string normalized_language_code; if (not params.getCanonicalCode(subfield.value_, &normalized_language_code)) { LogOutput("Unknown language code variant '" + subfield.value_ + "' in subfield 041$" + std::string(1, subfield.code_), true); } if (normalized_language_code != subfield.value_) { LogOutput("Normalized subfield 041$" + std::string(1, subfield.code_) + " language code: '" + subfield.value_ + "' => '" + normalized_language_code + "'"); subfield.value_ = normalized_language_code; propagate_changes = true; } unique_language_codes.insert(subfield.value_); modified_subfields.addSubfield(subfield.code_, subfield.value_); } if (propagate_changes) tag_041->setContents(modified_subfields, indicator1, indicator2); } writer->write(record); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "ylikuutio_string.hpp" // Include standard headers #include <iostream> // std::cout, std::cin, std::cerr #include <string> // std::string #include <vector> // std::vector #include <string.h> // strcmp, strlen namespace string { bool check_and_report_if_some_string_matches(const char* SVG_base_pointer, char* SVG_data_pointer, std::vector<std::string> identifier_strings_vector) { for (std::string identifier_string : identifier_strings_vector) { const char* identifier_string_char = identifier_string.c_str(); if (strncmp(SVG_data_pointer, identifier_string_char, strlen(identifier_string_char)) == 0) { const char* identifier_string_char = identifier_string.c_str(); uint64_t offset = (uint64_t) SVG_data_pointer - (uint64_t) SVG_base_pointer; printf("%s found at file offset 0x%lx (memory address 0x%lx). ", identifier_string_char, offset, (uint64_t) SVG_data_pointer); return true; } } return false; } } <commit_msg>`bool check_and_report_if_some_string_matches`: Muokattu tulostusta.<commit_after>#include "ylikuutio_string.hpp" // Include standard headers #include <iostream> // std::cout, std::cin, std::cerr #include <string> // std::string #include <vector> // std::vector #include <string.h> // strcmp, strlen namespace string { bool check_and_report_if_some_string_matches(const char* SVG_base_pointer, char* SVG_data_pointer, std::vector<std::string> identifier_strings_vector) { for (std::string identifier_string : identifier_strings_vector) { const char* identifier_string_char = identifier_string.c_str(); if (strncmp(SVG_data_pointer, identifier_string_char, strlen(identifier_string_char)) == 0) { const char* identifier_string_char = identifier_string.c_str(); uint64_t offset = (uint64_t) SVG_data_pointer - (uint64_t) SVG_base_pointer; printf("%s found at file offset 0x%lx (memory address 0x%lx).\n", identifier_string_char, offset, (uint64_t) SVG_data_pointer); return true; } } return false; } } <|endoftext|>
<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "generic_merge.h" #include <vespa/eval/eval/inline_operation.h> #include <vespa/eval/eval/fast_value.hpp> #include <vespa/eval/eval/wrap_param.h> #include <vespa/vespalib/util/stash.h> #include <vespa/vespalib/util/typify.h> #include <cassert> #include <typeindex> using namespace vespalib::eval::tensor_function; namespace vespalib::eval::instruction { using State = InterpretedFunction::State; using Instruction = InterpretedFunction::Instruction; namespace { //----------------------------------------------------------------------------- struct MergeParam { const ValueType res_type; const join_fun_t function; const size_t num_mapped_dimensions; const size_t dense_subspace_size; std::vector<size_t> all_view_dims; const ValueBuilderFactory &factory; MergeParam(const ValueType &lhs_type, const ValueType &rhs_type, join_fun_t function_in, const ValueBuilderFactory &factory_in) : res_type(ValueType::join(lhs_type, rhs_type)), function(function_in), num_mapped_dimensions(lhs_type.count_mapped_dimensions()), dense_subspace_size(lhs_type.dense_subspace_size()), all_view_dims(num_mapped_dimensions), factory(factory_in) { assert(!res_type.is_error()); assert(num_mapped_dimensions == rhs_type.count_mapped_dimensions()); assert(num_mapped_dimensions == res_type.count_mapped_dimensions()); assert(dense_subspace_size == rhs_type.dense_subspace_size()); assert(dense_subspace_size == res_type.dense_subspace_size()); for (size_t i = 0; i < num_mapped_dimensions; ++i) { all_view_dims[i] = i; } } ~MergeParam(); }; MergeParam::~MergeParam() = default; //----------------------------------------------------------------------------- template <typename LCT, typename RCT, typename OCT, typename Fun> std::unique_ptr<Value> generic_mixed_merge(const Value &a, const Value &b, const MergeParam &params) { Fun fun(params.function); auto lhs_cells = a.cells().typify<LCT>(); auto rhs_cells = b.cells().typify<RCT>(); const size_t num_mapped = params.num_mapped_dimensions; const size_t subspace_size = params.dense_subspace_size; size_t guess_subspaces = std::max(a.index().size(), b.index().size()); auto builder = params.factory.create_value_builder<OCT>(params.res_type, num_mapped, subspace_size, guess_subspaces); std::vector<vespalib::stringref> address(num_mapped); std::vector<const vespalib::stringref *> addr_cref; std::vector<vespalib::stringref *> addr_ref; for (auto & ref : address) { addr_cref.push_back(&ref); addr_ref.push_back(&ref); } size_t lhs_subspace; size_t rhs_subspace; auto inner = b.index().create_view(params.all_view_dims); auto outer = a.index().create_view({}); outer->lookup({}); while (outer->next_result(addr_ref, lhs_subspace)) { OCT *dst = builder->add_subspace(address).begin(); inner->lookup(addr_cref); if (inner->next_result({}, rhs_subspace)) { const LCT *lhs_src = &lhs_cells[lhs_subspace * subspace_size]; const RCT *rhs_src = &rhs_cells[rhs_subspace * subspace_size]; for (size_t i = 0; i < subspace_size; ++i) { *dst++ = fun(*lhs_src++, *rhs_src++); } } else { const LCT *src = &lhs_cells[lhs_subspace * subspace_size]; for (size_t i = 0; i < subspace_size; ++i) { *dst++ = *src++; } } } inner = a.index().create_view(params.all_view_dims); outer = b.index().create_view({}); outer->lookup({}); while (outer->next_result(addr_ref, rhs_subspace)) { inner->lookup(addr_cref); if (! inner->next_result({}, lhs_subspace)) { OCT *dst = builder->add_subspace(address).begin(); const RCT *src = &rhs_cells[rhs_subspace * subspace_size]; for (size_t i = 0; i < subspace_size; ++i) { *dst++ = *src++; } } } return builder->build(std::move(builder)); } template <typename LCT, typename RCT, typename OCT, typename Fun> void my_mixed_merge_op(State &state, uint64_t param_in) { const auto &param = unwrap_param<MergeParam>(param_in); const Value &lhs = state.peek(1); const Value &rhs = state.peek(0); auto up = generic_mixed_merge<LCT, RCT, OCT, Fun>(lhs, rhs, param); auto &result = state.stash.create<std::unique_ptr<Value>>(std::move(up)); const Value &result_ref = *(result.get()); state.pop_pop_push(result_ref); }; template <typename LCT, typename RCT, typename OCT, typename Fun> void my_sparse_merge_op(State &state, uint64_t param_in) { const auto &param = unwrap_param<MergeParam>(param_in); const Value &lhs = state.peek(1); const Value &rhs = state.peek(0); const Value::Index &lhs_index = lhs.index(); const Value::Index &rhs_index = rhs.index(); if ((std::type_index(typeid(lhs_index)) == std::type_index(typeid(FastValueIndex))) && (std::type_index(typeid(rhs_index)) == std::type_index(typeid(FastValueIndex)))) { const FastValueIndex &lhs_fast = static_cast<const FastValueIndex&>(lhs_index); const FastValueIndex &rhs_fast = static_cast<const FastValueIndex&>(rhs_index); auto lhs_cells = lhs.cells().typify<LCT>(); auto rhs_cells = rhs.cells().typify<RCT>(); return state.pop_pop_push( FastValueIndex::sparse_only_merge<LCT,RCT,OCT,Fun>( param.res_type, Fun(param.function), lhs_fast, rhs_fast, lhs_cells, rhs_cells, state.stash)); } auto up = generic_mixed_merge<LCT, RCT, OCT, Fun>(lhs, rhs, param); auto &result = state.stash.create<std::unique_ptr<Value>>(std::move(up)); const Value &result_ref = *(result.get()); state.pop_pop_push(result_ref); }; struct SelectGenericMergeOp { template <typename LCT, typename RCT, typename OCT, typename Fun> static auto invoke(const MergeParam &param) { if (param.dense_subspace_size == 1) { return my_sparse_merge_op<LCT,RCT,OCT,Fun>; } return my_mixed_merge_op<LCT,RCT,OCT,Fun>; } }; struct PerformGenericMerge { template <typename LCT, typename RCT, typename OCT, typename Fun> static auto invoke(const Value &a, const Value &b, const MergeParam &param) { return generic_mixed_merge<LCT,RCT,OCT,Fun>(a, b, param); } }; //----------------------------------------------------------------------------- } // namespace <unnamed> using MergeTypify = TypifyValue<TypifyCellType,operation::TypifyOp2>; Instruction GenericMerge::make_instruction(const ValueType &lhs_type, const ValueType &rhs_type, join_fun_t function, const ValueBuilderFactory &factory, Stash &stash) { const auto &param = stash.create<MergeParam>(lhs_type, rhs_type, function, factory); auto fun = typify_invoke<4,MergeTypify,SelectGenericMergeOp>(lhs_type.cell_type(), rhs_type.cell_type(), param.res_type.cell_type(), function, param); return Instruction(fun, wrap_param<MergeParam>(param)); } Value::UP GenericMerge::perform_merge(const Value &a, const Value &b, join_fun_t function, const ValueBuilderFactory &factory) { MergeParam param(a.type(), b.type(), function, factory); return typify_invoke<4,MergeTypify,PerformGenericMerge>( a.type().cell_type(), b.type().cell_type(), param.res_type.cell_type(), function, a, b, param); } } // namespace <commit_msg>possible utility to recognize object implementation<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "generic_merge.h" #include <vespa/eval/eval/inline_operation.h> #include <vespa/eval/eval/fast_value.hpp> #include <vespa/eval/eval/wrap_param.h> #include <vespa/vespalib/util/stash.h> #include <vespa/vespalib/util/typify.h> #include <cassert> #include <typeindex> using namespace vespalib::eval::tensor_function; namespace vespalib::eval::instruction { using State = InterpretedFunction::State; using Instruction = InterpretedFunction::Instruction; namespace { //----------------------------------------------------------------------------- struct MergeParam { const ValueType res_type; const join_fun_t function; const size_t num_mapped_dimensions; const size_t dense_subspace_size; std::vector<size_t> all_view_dims; const ValueBuilderFactory &factory; MergeParam(const ValueType &lhs_type, const ValueType &rhs_type, join_fun_t function_in, const ValueBuilderFactory &factory_in) : res_type(ValueType::join(lhs_type, rhs_type)), function(function_in), num_mapped_dimensions(lhs_type.count_mapped_dimensions()), dense_subspace_size(lhs_type.dense_subspace_size()), all_view_dims(num_mapped_dimensions), factory(factory_in) { assert(!res_type.is_error()); assert(num_mapped_dimensions == rhs_type.count_mapped_dimensions()); assert(num_mapped_dimensions == res_type.count_mapped_dimensions()); assert(dense_subspace_size == rhs_type.dense_subspace_size()); assert(dense_subspace_size == res_type.dense_subspace_size()); for (size_t i = 0; i < num_mapped_dimensions; ++i) { all_view_dims[i] = i; } } ~MergeParam(); }; MergeParam::~MergeParam() = default; //----------------------------------------------------------------------------- template <typename LCT, typename RCT, typename OCT, typename Fun> std::unique_ptr<Value> generic_mixed_merge(const Value &a, const Value &b, const MergeParam &params) { Fun fun(params.function); auto lhs_cells = a.cells().typify<LCT>(); auto rhs_cells = b.cells().typify<RCT>(); const size_t num_mapped = params.num_mapped_dimensions; const size_t subspace_size = params.dense_subspace_size; size_t guess_subspaces = std::max(a.index().size(), b.index().size()); auto builder = params.factory.create_value_builder<OCT>(params.res_type, num_mapped, subspace_size, guess_subspaces); std::vector<vespalib::stringref> address(num_mapped); std::vector<const vespalib::stringref *> addr_cref; std::vector<vespalib::stringref *> addr_ref; for (auto & ref : address) { addr_cref.push_back(&ref); addr_ref.push_back(&ref); } size_t lhs_subspace; size_t rhs_subspace; auto inner = b.index().create_view(params.all_view_dims); auto outer = a.index().create_view({}); outer->lookup({}); while (outer->next_result(addr_ref, lhs_subspace)) { OCT *dst = builder->add_subspace(address).begin(); inner->lookup(addr_cref); if (inner->next_result({}, rhs_subspace)) { const LCT *lhs_src = &lhs_cells[lhs_subspace * subspace_size]; const RCT *rhs_src = &rhs_cells[rhs_subspace * subspace_size]; for (size_t i = 0; i < subspace_size; ++i) { *dst++ = fun(*lhs_src++, *rhs_src++); } } else { const LCT *src = &lhs_cells[lhs_subspace * subspace_size]; for (size_t i = 0; i < subspace_size; ++i) { *dst++ = *src++; } } } inner = a.index().create_view(params.all_view_dims); outer = b.index().create_view({}); outer->lookup({}); while (outer->next_result(addr_ref, rhs_subspace)) { inner->lookup(addr_cref); if (! inner->next_result({}, lhs_subspace)) { OCT *dst = builder->add_subspace(address).begin(); const RCT *src = &rhs_cells[rhs_subspace * subspace_size]; for (size_t i = 0; i < subspace_size; ++i) { *dst++ = *src++; } } } return builder->build(std::move(builder)); } template <typename LCT, typename RCT, typename OCT, typename Fun> void my_mixed_merge_op(State &state, uint64_t param_in) { const auto &param = unwrap_param<MergeParam>(param_in); const Value &lhs = state.peek(1); const Value &rhs = state.peek(0); auto up = generic_mixed_merge<LCT, RCT, OCT, Fun>(lhs, rhs, param); auto &result = state.stash.create<std::unique_ptr<Value>>(std::move(up)); const Value &result_ref = *(result.get()); state.pop_pop_push(result_ref); }; /** possible generic utility */ template<typename T, typename U> const T * recognize_by_type_index(const U & object) { if (std::type_index(typeid(object)) == std::type_index(typeid(T))) { return static_cast<const T *>(&object); } return nullptr; } /** possible FastValue-specific utility */ class Indexes { private: const FastValueIndex *_a; const FastValueIndex *_b; public: Indexes(const Value::Index &a_in, const Value::Index &b_in) : _a(recognize_by_type_index<FastValueIndex>(a_in)), _b(recognize_by_type_index<FastValueIndex>(b_in)) { } operator bool() const { return _a && _b; } const FastValueIndex &a() const { return *_a; } const FastValueIndex &b() const { return *_b; } }; template <typename LCT, typename RCT, typename OCT, typename Fun> void my_sparse_merge_op(State &state, uint64_t param_in) { const auto &param = unwrap_param<MergeParam>(param_in); const Value &lhs = state.peek(1); const Value &rhs = state.peek(0); if (auto indexes = Indexes(lhs.index(), rhs.index())) { auto lhs_cells = lhs.cells().typify<LCT>(); auto rhs_cells = rhs.cells().typify<RCT>(); return state.pop_pop_push( FastValueIndex::sparse_only_merge<LCT,RCT,OCT,Fun>( param.res_type, Fun(param.function), indexes.a(), indexes.b(), lhs_cells, rhs_cells, state.stash)); } auto up = generic_mixed_merge<LCT, RCT, OCT, Fun>(lhs, rhs, param); auto &result = state.stash.create<std::unique_ptr<Value>>(std::move(up)); const Value &result_ref = *(result.get()); state.pop_pop_push(result_ref); }; struct SelectGenericMergeOp { template <typename LCT, typename RCT, typename OCT, typename Fun> static auto invoke(const MergeParam &param) { if (param.dense_subspace_size == 1) { return my_sparse_merge_op<LCT,RCT,OCT,Fun>; } return my_mixed_merge_op<LCT,RCT,OCT,Fun>; } }; struct PerformGenericMerge { template <typename LCT, typename RCT, typename OCT, typename Fun> static auto invoke(const Value &a, const Value &b, const MergeParam &param) { return generic_mixed_merge<LCT,RCT,OCT,Fun>(a, b, param); } }; //----------------------------------------------------------------------------- } // namespace <unnamed> using MergeTypify = TypifyValue<TypifyCellType,operation::TypifyOp2>; Instruction GenericMerge::make_instruction(const ValueType &lhs_type, const ValueType &rhs_type, join_fun_t function, const ValueBuilderFactory &factory, Stash &stash) { const auto &param = stash.create<MergeParam>(lhs_type, rhs_type, function, factory); auto fun = typify_invoke<4,MergeTypify,SelectGenericMergeOp>(lhs_type.cell_type(), rhs_type.cell_type(), param.res_type.cell_type(), function, param); return Instruction(fun, wrap_param<MergeParam>(param)); } Value::UP GenericMerge::perform_merge(const Value &a, const Value &b, join_fun_t function, const ValueBuilderFactory &factory) { MergeParam param(a.type(), b.type(), function, factory); return typify_invoke<4,MergeTypify,PerformGenericMerge>( a.type().cell_type(), b.type().cell_type(), param.res_type.cell_type(), function, a, b, param); } } // namespace <|endoftext|>
<commit_before>//===- LoopInfo.cpp - Natural Loop Calculator -------------------------------=// // // This file defines the LoopInfo class that is used to identify natural loops // and determine the loop depth of various nodes of the CFG. Note that the // loops identified may actually be several natural loops that share the same // header node... not just a single natural loop. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Support/CFG.h" #include "llvm/Assembly/Writer.h" #include "Support/DepthFirstIterator.h" #include <algorithm> static RegisterAnalysis<LoopInfo> X("loops", "Natural Loop Construction", true); //===----------------------------------------------------------------------===// // Loop implementation // bool Loop::contains(const BasicBlock *BB) const { return find(Blocks.begin(), Blocks.end(), BB) != Blocks.end(); } bool Loop::isLoopExit(const BasicBlock *BB) const { for (BasicBlock::succ_const_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) { if (!contains(*SI)) return true; } return false; } unsigned Loop::getNumBackEdges() const { unsigned NumBackEdges = 0; BasicBlock *H = getHeader(); for (std::vector<BasicBlock*>::const_iterator I = Blocks.begin(), E = Blocks.end(); I != E; ++I) for (BasicBlock::succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI) if (*SI == H) ++NumBackEdges; return NumBackEdges; } void Loop::print(std::ostream &OS, unsigned Depth) const { OS << std::string(Depth*2, ' ') << "Loop Containing: "; for (unsigned i = 0; i < getBlocks().size(); ++i) { if (i) OS << ","; WriteAsOperand(OS, getBlocks()[i], false); } if (!ExitBlocks.empty()) { OS << "\tExitBlocks: "; for (unsigned i = 0; i < getExitBlocks().size(); ++i) { if (i) OS << ","; WriteAsOperand(OS, getExitBlocks()[i], false); } } OS << "\n"; for (unsigned i = 0, e = getSubLoops().size(); i != e; ++i) getSubLoops()[i]->print(OS, Depth+2); } void Loop::dump() const { print(std::cerr); } //===----------------------------------------------------------------------===// // LoopInfo implementation // void LoopInfo::stub() {} bool LoopInfo::runOnFunction(Function &) { releaseMemory(); Calculate(getAnalysis<DominatorSet>()); // Update return false; } void LoopInfo::releaseMemory() { for (std::vector<Loop*>::iterator I = TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I) delete *I; // Delete all of the loops... BBMap.clear(); // Reset internal state of analysis TopLevelLoops.clear(); } void LoopInfo::Calculate(const DominatorSet &DS) { BasicBlock *RootNode = DS.getRoot(); for (df_iterator<BasicBlock*> NI = df_begin(RootNode), NE = df_end(RootNode); NI != NE; ++NI) if (Loop *L = ConsiderForLoop(*NI, DS)) TopLevelLoops.push_back(L); for (unsigned i = 0; i < TopLevelLoops.size(); ++i) TopLevelLoops[i]->setLoopDepth(1); } void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); AU.addRequired<DominatorSet>(); } void LoopInfo::print(std::ostream &OS) const { for (unsigned i = 0; i < TopLevelLoops.size(); ++i) TopLevelLoops[i]->print(OS); #if 0 for (std::map<BasicBlock*, Loop*>::const_iterator I = BBMap.begin(), E = BBMap.end(); I != E; ++I) OS << "BB '" << I->first->getName() << "' level = " << I->second->LoopDepth << "\n"; #endif } static bool isNotAlreadyContainedIn(Loop *SubLoop, Loop *ParentLoop) { if (SubLoop == 0) return true; if (SubLoop == ParentLoop) return false; return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop); } Loop *LoopInfo::ConsiderForLoop(BasicBlock *BB, const DominatorSet &DS) { if (BBMap.find(BB) != BBMap.end()) return 0; // Haven't processed this node? std::vector<BasicBlock *> TodoStack; // Scan the predecessors of BB, checking to see if BB dominates any of // them. This identifies backedges which target this node... for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) if (DS.dominates(BB, *I)) // If BB dominates it's predecessor... TodoStack.push_back(*I); if (TodoStack.empty()) return 0; // No backedges to this block... // Create a new loop to represent this basic block... Loop *L = new Loop(BB); BBMap[BB] = L; while (!TodoStack.empty()) { // Process all the nodes in the loop BasicBlock *X = TodoStack.back(); TodoStack.pop_back(); if (!L->contains(X)) { // As of yet unprocessed?? // Check to see if this block already belongs to a loop. If this occurs // then we have a case where a loop that is supposed to be a child of the // current loop was processed before the current loop. When this occurs, // this child loop gets added to a part of the current loop, making it a // sibling to the current loop. We have to reparent this loop. if (Loop *SubLoop = const_cast<Loop*>(getLoopFor(X))) if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)) { // Remove the subloop from it's current parent... assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L); Loop *SLP = SubLoop->ParentLoop; // SubLoopParent std::vector<Loop*>::iterator I = std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop); assert(I != SLP->SubLoops.end() && "SubLoop not a child of parent?"); SLP->SubLoops.erase(I); // Remove from parent... // Add the subloop to THIS loop... SubLoop->ParentLoop = L; L->SubLoops.push_back(SubLoop); } // Normal case, add the block to our loop... L->Blocks.push_back(X); // Add all of the predecessors of X to the end of the work stack... TodoStack.insert(TodoStack.end(), pred_begin(X), pred_end(X)); } } // If there are any loops nested within this loop, create them now! for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(), E = L->Blocks.end(); I != E; ++I) if (Loop *NewLoop = ConsiderForLoop(*I, DS)) { L->SubLoops.push_back(NewLoop); NewLoop->ParentLoop = L; } // Add the basic blocks that comprise this loop to the BBMap so that this // loop can be found for them. // for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(), E = L->Blocks.end(); I != E; ++I) { std::map<BasicBlock*, Loop*>::iterator BBMI = BBMap.lower_bound(*I); if (BBMI == BBMap.end() || BBMI->first != *I) // Not in map yet... BBMap.insert(BBMI, std::make_pair(*I, L)); // Must be at this level } // Now that we have a list of all of the child loops of this loop, check to // see if any of them should actually be nested inside of each other. We can // accidentally pull loops our of their parents, so we must make sure to // organize the loop nests correctly now. { std::map<BasicBlock*, Loop*> ContainingLoops; for (unsigned i = 0; i != L->SubLoops.size(); ++i) { Loop *Child = L->SubLoops[i]; assert(Child->getParentLoop() == L && "Not proper child loop?"); if (Loop *ContainingLoop = ContainingLoops[Child->getHeader()]) { // If there is already a loop which contains this loop, move this loop // into the containing loop. MoveSiblingLoopInto(Child, ContainingLoop); --i; // The loop got removed from the SubLoops list. } else { // This is currently considered to be a top-level loop. Check to see if // any of the contained blocks are loop headers for subloops we have // already processed. for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) { Loop *&BlockLoop = ContainingLoops[Child->Blocks[b]]; if (BlockLoop == 0) { // Child block not processed yet... BlockLoop = Child; } else if (BlockLoop != Child) { // There is already a loop which contains this block, that means // that we should reparent the loop which the block is currently // considered to belong to to be a child of this loop. MoveSiblingLoopInto(BlockLoop, Child); // Reparent all of the blocks which used to belong to BlockLoops for (unsigned j = 0, e = BlockLoop->Blocks.size(); j != e; ++j) ContainingLoops[BlockLoop->Blocks[j]] = Child; --i; // We just shrunk the SubLoops list. } } } } } // Now that we know all of the blocks that make up this loop, see if there are // any branches to outside of the loop... building the ExitBlocks list. for (std::vector<BasicBlock*>::iterator BI = L->Blocks.begin(), BE = L->Blocks.end(); BI != BE; ++BI) for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) if (!L->contains(*I)) // Not in current loop? L->ExitBlocks.push_back(*I); // It must be an exit block... return L; } /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside of /// the NewParent Loop, instead of being a sibling of it. void LoopInfo::MoveSiblingLoopInto(Loop *NewChild, Loop *NewParent) { Loop *OldParent = NewChild->getParentLoop(); assert(OldParent && OldParent == NewParent->getParentLoop() && NewChild != NewParent && "Not sibling loops!"); // Remove NewChild from being a child of OldParent std::vector<Loop*>::iterator I = std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(), NewChild); assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??"); OldParent->SubLoops.erase(I); // Remove from parent's subloops list NewChild->ParentLoop = 0; InsertLoopInto(NewChild, NewParent); } /// InsertLoopInto - This inserts loop L into the specified parent loop. If the /// parent loop contains a loop which should contain L, the loop gets inserted /// into L instead. void LoopInfo::InsertLoopInto(Loop *L, Loop *Parent) { BasicBlock *LHeader = L->getHeader(); assert(Parent->contains(LHeader) && "This loop should not be inserted here!"); // Check to see if it belongs in a child loop... for (unsigned i = 0, e = Parent->SubLoops.size(); i != e; ++i) if (Parent->SubLoops[i]->contains(LHeader)) { InsertLoopInto(L, Parent->SubLoops[i]); return; } // If not, insert it here! Parent->SubLoops.push_back(L); L->ParentLoop = Parent; } /// getLoopPreheader - If there is a preheader for this loop, return it. A /// loop has a preheader if there is only one edge to the header of the loop /// from outside of the loop. If this is the case, the block branching to the /// header of the loop is the preheader node. The "preheaders" pass can be /// "Required" to ensure that there is always a preheader node for every loop. /// /// This method returns null if there is no preheader for the loop (either /// because the loop is dead or because multiple blocks branch to the header /// node of this loop). /// BasicBlock *Loop::getLoopPreheader() const { // Keep track of nodes outside the loop branching to the header... BasicBlock *Out = 0; // Loop over the predecessors of the header node... BasicBlock *Header = getHeader(); for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header); PI != PE; ++PI) if (!contains(*PI)) { // If the block is not in the loop... if (Out && Out != *PI) return 0; // Multiple predecessors outside the loop Out = *PI; } // Make sure there is only one exit out of the preheader... succ_iterator SI = succ_begin(Out); ++SI; if (SI != succ_end(Out)) return 0; // Multiple exits from the block, must not be a preheader. // If there is exactly one preheader, return it. If there was zero, then Out // is still null. return Out; } /// addBasicBlockToLoop - This function is used by other analyses to update loop /// information. NewBB is set to be a new member of the current loop. Because /// of this, it is added as a member of all parent loops, and is added to the /// specified LoopInfo object as being in the current basic block. It is not /// valid to replace the loop header with this method. /// void Loop::addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI) { assert(LI[getHeader()] == this && "Incorrect LI specified for this loop!"); assert(NewBB && "Cannot add a null basic block to the loop!"); assert(LI[NewBB] == 0 && "BasicBlock already in the loop!"); // Add the loop mapping to the LoopInfo object... LI.BBMap[NewBB] = this; // Add the basic block to this loop and all parent loops... Loop *L = this; while (L) { L->Blocks.push_back(NewBB); L = L->getParentLoop(); } } /// changeExitBlock - This method is used to update loop information. All /// instances of the specified Old basic block are removed from the exit list /// and replaced with New. /// void Loop::changeExitBlock(BasicBlock *Old, BasicBlock *New) { assert(Old != New && "Cannot changeExitBlock to the same thing!"); assert(Old && New && "Cannot changeExitBlock to or from a null node!"); assert(hasExitBlock(Old) && "Old exit block not found!"); std::vector<BasicBlock*>::iterator I = std::find(ExitBlocks.begin(), ExitBlocks.end(), Old); while (I != ExitBlocks.end()) { *I = New; I = std::find(I+1, ExitBlocks.end(), Old); } } <commit_msg>Fix the bug that broke the nightly tester in McCat/18-imp last night. :(<commit_after>//===- LoopInfo.cpp - Natural Loop Calculator -------------------------------=// // // This file defines the LoopInfo class that is used to identify natural loops // and determine the loop depth of various nodes of the CFG. Note that the // loops identified may actually be several natural loops that share the same // header node... not just a single natural loop. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Support/CFG.h" #include "llvm/Assembly/Writer.h" #include "Support/DepthFirstIterator.h" #include <algorithm> static RegisterAnalysis<LoopInfo> X("loops", "Natural Loop Construction", true); //===----------------------------------------------------------------------===// // Loop implementation // bool Loop::contains(const BasicBlock *BB) const { return find(Blocks.begin(), Blocks.end(), BB) != Blocks.end(); } bool Loop::isLoopExit(const BasicBlock *BB) const { for (BasicBlock::succ_const_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) { if (!contains(*SI)) return true; } return false; } unsigned Loop::getNumBackEdges() const { unsigned NumBackEdges = 0; BasicBlock *H = getHeader(); for (std::vector<BasicBlock*>::const_iterator I = Blocks.begin(), E = Blocks.end(); I != E; ++I) for (BasicBlock::succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI) if (*SI == H) ++NumBackEdges; return NumBackEdges; } void Loop::print(std::ostream &OS, unsigned Depth) const { OS << std::string(Depth*2, ' ') << "Loop Containing: "; for (unsigned i = 0; i < getBlocks().size(); ++i) { if (i) OS << ","; WriteAsOperand(OS, getBlocks()[i], false); } if (!ExitBlocks.empty()) { OS << "\tExitBlocks: "; for (unsigned i = 0; i < getExitBlocks().size(); ++i) { if (i) OS << ","; WriteAsOperand(OS, getExitBlocks()[i], false); } } OS << "\n"; for (unsigned i = 0, e = getSubLoops().size(); i != e; ++i) getSubLoops()[i]->print(OS, Depth+2); } void Loop::dump() const { print(std::cerr); } //===----------------------------------------------------------------------===// // LoopInfo implementation // void LoopInfo::stub() {} bool LoopInfo::runOnFunction(Function &) { releaseMemory(); Calculate(getAnalysis<DominatorSet>()); // Update return false; } void LoopInfo::releaseMemory() { for (std::vector<Loop*>::iterator I = TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I) delete *I; // Delete all of the loops... BBMap.clear(); // Reset internal state of analysis TopLevelLoops.clear(); } void LoopInfo::Calculate(const DominatorSet &DS) { BasicBlock *RootNode = DS.getRoot(); for (df_iterator<BasicBlock*> NI = df_begin(RootNode), NE = df_end(RootNode); NI != NE; ++NI) if (Loop *L = ConsiderForLoop(*NI, DS)) TopLevelLoops.push_back(L); for (unsigned i = 0; i < TopLevelLoops.size(); ++i) TopLevelLoops[i]->setLoopDepth(1); } void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); AU.addRequired<DominatorSet>(); } void LoopInfo::print(std::ostream &OS) const { for (unsigned i = 0; i < TopLevelLoops.size(); ++i) TopLevelLoops[i]->print(OS); #if 0 for (std::map<BasicBlock*, Loop*>::const_iterator I = BBMap.begin(), E = BBMap.end(); I != E; ++I) OS << "BB '" << I->first->getName() << "' level = " << I->second->LoopDepth << "\n"; #endif } static bool isNotAlreadyContainedIn(Loop *SubLoop, Loop *ParentLoop) { if (SubLoop == 0) return true; if (SubLoop == ParentLoop) return false; return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop); } Loop *LoopInfo::ConsiderForLoop(BasicBlock *BB, const DominatorSet &DS) { if (BBMap.find(BB) != BBMap.end()) return 0; // Haven't processed this node? std::vector<BasicBlock *> TodoStack; // Scan the predecessors of BB, checking to see if BB dominates any of // them. This identifies backedges which target this node... for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) if (DS.dominates(BB, *I)) // If BB dominates it's predecessor... TodoStack.push_back(*I); if (TodoStack.empty()) return 0; // No backedges to this block... // Create a new loop to represent this basic block... Loop *L = new Loop(BB); BBMap[BB] = L; while (!TodoStack.empty()) { // Process all the nodes in the loop BasicBlock *X = TodoStack.back(); TodoStack.pop_back(); if (!L->contains(X)) { // As of yet unprocessed?? // Check to see if this block already belongs to a loop. If this occurs // then we have a case where a loop that is supposed to be a child of the // current loop was processed before the current loop. When this occurs, // this child loop gets added to a part of the current loop, making it a // sibling to the current loop. We have to reparent this loop. if (Loop *SubLoop = const_cast<Loop*>(getLoopFor(X))) if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)) { // Remove the subloop from it's current parent... assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L); Loop *SLP = SubLoop->ParentLoop; // SubLoopParent std::vector<Loop*>::iterator I = std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop); assert(I != SLP->SubLoops.end() && "SubLoop not a child of parent?"); SLP->SubLoops.erase(I); // Remove from parent... // Add the subloop to THIS loop... SubLoop->ParentLoop = L; L->SubLoops.push_back(SubLoop); } // Normal case, add the block to our loop... L->Blocks.push_back(X); // Add all of the predecessors of X to the end of the work stack... TodoStack.insert(TodoStack.end(), pred_begin(X), pred_end(X)); } } // If there are any loops nested within this loop, create them now! for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(), E = L->Blocks.end(); I != E; ++I) if (Loop *NewLoop = ConsiderForLoop(*I, DS)) { L->SubLoops.push_back(NewLoop); NewLoop->ParentLoop = L; } // Add the basic blocks that comprise this loop to the BBMap so that this // loop can be found for them. // for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(), E = L->Blocks.end(); I != E; ++I) { std::map<BasicBlock*, Loop*>::iterator BBMI = BBMap.lower_bound(*I); if (BBMI == BBMap.end() || BBMI->first != *I) // Not in map yet... BBMap.insert(BBMI, std::make_pair(*I, L)); // Must be at this level } // Now that we have a list of all of the child loops of this loop, check to // see if any of them should actually be nested inside of each other. We can // accidentally pull loops our of their parents, so we must make sure to // organize the loop nests correctly now. { std::map<BasicBlock*, Loop*> ContainingLoops; for (unsigned i = 0; i != L->SubLoops.size(); ++i) { Loop *Child = L->SubLoops[i]; assert(Child->getParentLoop() == L && "Not proper child loop?"); if (Loop *ContainingLoop = ContainingLoops[Child->getHeader()]) { // If there is already a loop which contains this loop, move this loop // into the containing loop. MoveSiblingLoopInto(Child, ContainingLoop); --i; // The loop got removed from the SubLoops list. } else { // This is currently considered to be a top-level loop. Check to see if // any of the contained blocks are loop headers for subloops we have // already processed. for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) { Loop *&BlockLoop = ContainingLoops[Child->Blocks[b]]; if (BlockLoop == 0) { // Child block not processed yet... BlockLoop = Child; } else if (BlockLoop != Child) { Loop *SubLoop = BlockLoop; // Reparent all of the blocks which used to belong to BlockLoops for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j) ContainingLoops[SubLoop->Blocks[j]] = Child; // There is already a loop which contains this block, that means // that we should reparent the loop which the block is currently // considered to belong to to be a child of this loop. MoveSiblingLoopInto(SubLoop, Child); --i; // We just shrunk the SubLoops list. } } } } } // Now that we know all of the blocks that make up this loop, see if there are // any branches to outside of the loop... building the ExitBlocks list. for (std::vector<BasicBlock*>::iterator BI = L->Blocks.begin(), BE = L->Blocks.end(); BI != BE; ++BI) for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) if (!L->contains(*I)) // Not in current loop? L->ExitBlocks.push_back(*I); // It must be an exit block... return L; } /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside of /// the NewParent Loop, instead of being a sibling of it. void LoopInfo::MoveSiblingLoopInto(Loop *NewChild, Loop *NewParent) { Loop *OldParent = NewChild->getParentLoop(); assert(OldParent && OldParent == NewParent->getParentLoop() && NewChild != NewParent && "Not sibling loops!"); // Remove NewChild from being a child of OldParent std::vector<Loop*>::iterator I = std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(), NewChild); assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??"); OldParent->SubLoops.erase(I); // Remove from parent's subloops list NewChild->ParentLoop = 0; InsertLoopInto(NewChild, NewParent); } /// InsertLoopInto - This inserts loop L into the specified parent loop. If the /// parent loop contains a loop which should contain L, the loop gets inserted /// into L instead. void LoopInfo::InsertLoopInto(Loop *L, Loop *Parent) { BasicBlock *LHeader = L->getHeader(); assert(Parent->contains(LHeader) && "This loop should not be inserted here!"); // Check to see if it belongs in a child loop... for (unsigned i = 0, e = Parent->SubLoops.size(); i != e; ++i) if (Parent->SubLoops[i]->contains(LHeader)) { InsertLoopInto(L, Parent->SubLoops[i]); return; } // If not, insert it here! Parent->SubLoops.push_back(L); L->ParentLoop = Parent; } /// getLoopPreheader - If there is a preheader for this loop, return it. A /// loop has a preheader if there is only one edge to the header of the loop /// from outside of the loop. If this is the case, the block branching to the /// header of the loop is the preheader node. The "preheaders" pass can be /// "Required" to ensure that there is always a preheader node for every loop. /// /// This method returns null if there is no preheader for the loop (either /// because the loop is dead or because multiple blocks branch to the header /// node of this loop). /// BasicBlock *Loop::getLoopPreheader() const { // Keep track of nodes outside the loop branching to the header... BasicBlock *Out = 0; // Loop over the predecessors of the header node... BasicBlock *Header = getHeader(); for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header); PI != PE; ++PI) if (!contains(*PI)) { // If the block is not in the loop... if (Out && Out != *PI) return 0; // Multiple predecessors outside the loop Out = *PI; } // Make sure there is only one exit out of the preheader... succ_iterator SI = succ_begin(Out); ++SI; if (SI != succ_end(Out)) return 0; // Multiple exits from the block, must not be a preheader. // If there is exactly one preheader, return it. If there was zero, then Out // is still null. return Out; } /// addBasicBlockToLoop - This function is used by other analyses to update loop /// information. NewBB is set to be a new member of the current loop. Because /// of this, it is added as a member of all parent loops, and is added to the /// specified LoopInfo object as being in the current basic block. It is not /// valid to replace the loop header with this method. /// void Loop::addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI) { assert(LI[getHeader()] == this && "Incorrect LI specified for this loop!"); assert(NewBB && "Cannot add a null basic block to the loop!"); assert(LI[NewBB] == 0 && "BasicBlock already in the loop!"); // Add the loop mapping to the LoopInfo object... LI.BBMap[NewBB] = this; // Add the basic block to this loop and all parent loops... Loop *L = this; while (L) { L->Blocks.push_back(NewBB); L = L->getParentLoop(); } } /// changeExitBlock - This method is used to update loop information. All /// instances of the specified Old basic block are removed from the exit list /// and replaced with New. /// void Loop::changeExitBlock(BasicBlock *Old, BasicBlock *New) { assert(Old != New && "Cannot changeExitBlock to the same thing!"); assert(Old && New && "Cannot changeExitBlock to or from a null node!"); assert(hasExitBlock(Old) && "Old exit block not found!"); std::vector<BasicBlock*>::iterator I = std::find(ExitBlocks.begin(), ExitBlocks.end(), Old); while (I != ExitBlocks.end()) { *I = New; I = std::find(I+1, ExitBlocks.end(), Old); } } <|endoftext|>
<commit_before>//===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the LoopInfo class that is used to identify natural loops // and determine the loop depth of various nodes of the CFG. Note that the // loops identified may actually be several natural loops that share the same // header node... not just a single natural loop. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Support/CFG.h" #include "llvm/Assembly/Writer.h" #include "Support/DepthFirstIterator.h" #include <algorithm> namespace llvm { static RegisterAnalysis<LoopInfo> X("loops", "Natural Loop Construction", true); //===----------------------------------------------------------------------===// // Loop implementation // bool Loop::contains(const BasicBlock *BB) const { return find(Blocks.begin(), Blocks.end(), BB) != Blocks.end(); } bool Loop::isLoopExit(const BasicBlock *BB) const { for (succ_const_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) { if (!contains(*SI)) return true; } return false; } /// getNumBackEdges - Calculate the number of back edges to the loop header. /// unsigned Loop::getNumBackEdges() const { unsigned NumBackEdges = 0; BasicBlock *H = getHeader(); for (pred_iterator I = pred_begin(H), E = pred_end(H); I != E; ++I) if (contains(*I)) ++NumBackEdges; return NumBackEdges; } void Loop::print(std::ostream &OS, unsigned Depth) const { OS << std::string(Depth*2, ' ') << "Loop Containing: "; for (unsigned i = 0; i < getBlocks().size(); ++i) { if (i) OS << ","; WriteAsOperand(OS, getBlocks()[i], false); } if (!ExitBlocks.empty()) { OS << "\tExitBlocks: "; for (unsigned i = 0; i < getExitBlocks().size(); ++i) { if (i) OS << ","; WriteAsOperand(OS, getExitBlocks()[i], false); } } OS << "\n"; for (iterator I = begin(), E = end(); I != E; ++I) (*I)->print(OS, Depth+2); } void Loop::dump() const { print(std::cerr); } //===----------------------------------------------------------------------===// // LoopInfo implementation // void LoopInfo::stub() {} bool LoopInfo::runOnFunction(Function &) { releaseMemory(); Calculate(getAnalysis<DominatorSet>()); // Update return false; } void LoopInfo::releaseMemory() { for (std::vector<Loop*>::iterator I = TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I) delete *I; // Delete all of the loops... BBMap.clear(); // Reset internal state of analysis TopLevelLoops.clear(); } void LoopInfo::Calculate(const DominatorSet &DS) { BasicBlock *RootNode = DS.getRoot(); for (df_iterator<BasicBlock*> NI = df_begin(RootNode), NE = df_end(RootNode); NI != NE; ++NI) if (Loop *L = ConsiderForLoop(*NI, DS)) TopLevelLoops.push_back(L); for (unsigned i = 0; i < TopLevelLoops.size(); ++i) TopLevelLoops[i]->setLoopDepth(1); } void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); AU.addRequired<DominatorSet>(); } void LoopInfo::print(std::ostream &OS) const { for (unsigned i = 0; i < TopLevelLoops.size(); ++i) TopLevelLoops[i]->print(OS); #if 0 for (std::map<BasicBlock*, Loop*>::const_iterator I = BBMap.begin(), E = BBMap.end(); I != E; ++I) OS << "BB '" << I->first->getName() << "' level = " << I->second->LoopDepth << "\n"; #endif } static bool isNotAlreadyContainedIn(Loop *SubLoop, Loop *ParentLoop) { if (SubLoop == 0) return true; if (SubLoop == ParentLoop) return false; return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop); } Loop *LoopInfo::ConsiderForLoop(BasicBlock *BB, const DominatorSet &DS) { if (BBMap.find(BB) != BBMap.end()) return 0; // Haven't processed this node? std::vector<BasicBlock *> TodoStack; // Scan the predecessors of BB, checking to see if BB dominates any of // them. This identifies backedges which target this node... for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) if (DS.dominates(BB, *I)) // If BB dominates it's predecessor... TodoStack.push_back(*I); if (TodoStack.empty()) return 0; // No backedges to this block... // Create a new loop to represent this basic block... Loop *L = new Loop(BB); BBMap[BB] = L; BasicBlock *EntryBlock = &BB->getParent()->getEntryBlock(); while (!TodoStack.empty()) { // Process all the nodes in the loop BasicBlock *X = TodoStack.back(); TodoStack.pop_back(); if (!L->contains(X) && // As of yet unprocessed?? DS.dominates(EntryBlock, X)) { // X is reachable from entry block? // Check to see if this block already belongs to a loop. If this occurs // then we have a case where a loop that is supposed to be a child of the // current loop was processed before the current loop. When this occurs, // this child loop gets added to a part of the current loop, making it a // sibling to the current loop. We have to reparent this loop. if (Loop *SubLoop = const_cast<Loop*>(getLoopFor(X))) if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)) { // Remove the subloop from it's current parent... assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L); Loop *SLP = SubLoop->ParentLoop; // SubLoopParent std::vector<Loop*>::iterator I = std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop); assert(I != SLP->SubLoops.end() && "SubLoop not a child of parent?"); SLP->SubLoops.erase(I); // Remove from parent... // Add the subloop to THIS loop... SubLoop->ParentLoop = L; L->SubLoops.push_back(SubLoop); } // Normal case, add the block to our loop... L->Blocks.push_back(X); // Add all of the predecessors of X to the end of the work stack... TodoStack.insert(TodoStack.end(), pred_begin(X), pred_end(X)); } } // If there are any loops nested within this loop, create them now! for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(), E = L->Blocks.end(); I != E; ++I) if (Loop *NewLoop = ConsiderForLoop(*I, DS)) { L->SubLoops.push_back(NewLoop); NewLoop->ParentLoop = L; } // Add the basic blocks that comprise this loop to the BBMap so that this // loop can be found for them. // for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(), E = L->Blocks.end(); I != E; ++I) { std::map<BasicBlock*, Loop*>::iterator BBMI = BBMap.lower_bound(*I); if (BBMI == BBMap.end() || BBMI->first != *I) // Not in map yet... BBMap.insert(BBMI, std::make_pair(*I, L)); // Must be at this level } // Now that we have a list of all of the child loops of this loop, check to // see if any of them should actually be nested inside of each other. We can // accidentally pull loops our of their parents, so we must make sure to // organize the loop nests correctly now. { std::map<BasicBlock*, Loop*> ContainingLoops; for (unsigned i = 0; i != L->SubLoops.size(); ++i) { Loop *Child = L->SubLoops[i]; assert(Child->getParentLoop() == L && "Not proper child loop?"); if (Loop *ContainingLoop = ContainingLoops[Child->getHeader()]) { // If there is already a loop which contains this loop, move this loop // into the containing loop. MoveSiblingLoopInto(Child, ContainingLoop); --i; // The loop got removed from the SubLoops list. } else { // This is currently considered to be a top-level loop. Check to see if // any of the contained blocks are loop headers for subloops we have // already processed. for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) { Loop *&BlockLoop = ContainingLoops[Child->Blocks[b]]; if (BlockLoop == 0) { // Child block not processed yet... BlockLoop = Child; } else if (BlockLoop != Child) { Loop *SubLoop = BlockLoop; // Reparent all of the blocks which used to belong to BlockLoops for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j) ContainingLoops[SubLoop->Blocks[j]] = Child; // There is already a loop which contains this block, that means // that we should reparent the loop which the block is currently // considered to belong to to be a child of this loop. MoveSiblingLoopInto(SubLoop, Child); --i; // We just shrunk the SubLoops list. } } } } } // Now that we know all of the blocks that make up this loop, see if there are // any branches to outside of the loop... building the ExitBlocks list. for (std::vector<BasicBlock*>::iterator BI = L->Blocks.begin(), BE = L->Blocks.end(); BI != BE; ++BI) for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) if (!L->contains(*I)) // Not in current loop? L->ExitBlocks.push_back(*I); // It must be an exit block... return L; } /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside of /// the NewParent Loop, instead of being a sibling of it. void LoopInfo::MoveSiblingLoopInto(Loop *NewChild, Loop *NewParent) { Loop *OldParent = NewChild->getParentLoop(); assert(OldParent && OldParent == NewParent->getParentLoop() && NewChild != NewParent && "Not sibling loops!"); // Remove NewChild from being a child of OldParent std::vector<Loop*>::iterator I = std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(), NewChild); assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??"); OldParent->SubLoops.erase(I); // Remove from parent's subloops list NewChild->ParentLoop = 0; InsertLoopInto(NewChild, NewParent); } /// InsertLoopInto - This inserts loop L into the specified parent loop. If the /// parent loop contains a loop which should contain L, the loop gets inserted /// into L instead. void LoopInfo::InsertLoopInto(Loop *L, Loop *Parent) { BasicBlock *LHeader = L->getHeader(); assert(Parent->contains(LHeader) && "This loop should not be inserted here!"); // Check to see if it belongs in a child loop... for (unsigned i = 0, e = Parent->SubLoops.size(); i != e; ++i) if (Parent->SubLoops[i]->contains(LHeader)) { InsertLoopInto(L, Parent->SubLoops[i]); return; } // If not, insert it here! Parent->SubLoops.push_back(L); L->ParentLoop = Parent; } /// getLoopPreheader - If there is a preheader for this loop, return it. A /// loop has a preheader if there is only one edge to the header of the loop /// from outside of the loop. If this is the case, the block branching to the /// header of the loop is the preheader node. The "preheaders" pass can be /// "Required" to ensure that there is always a preheader node for every loop. /// /// This method returns null if there is no preheader for the loop (either /// because the loop is dead or because multiple blocks branch to the header /// node of this loop). /// BasicBlock *Loop::getLoopPreheader() const { // Keep track of nodes outside the loop branching to the header... BasicBlock *Out = 0; // Loop over the predecessors of the header node... BasicBlock *Header = getHeader(); for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header); PI != PE; ++PI) if (!contains(*PI)) { // If the block is not in the loop... if (Out && Out != *PI) return 0; // Multiple predecessors outside the loop Out = *PI; } // Make sure there is only one exit out of the preheader... succ_iterator SI = succ_begin(Out); ++SI; if (SI != succ_end(Out)) return 0; // Multiple exits from the block, must not be a preheader. // If there is exactly one preheader, return it. If there was zero, then Out // is still null. return Out; } /// addBasicBlockToLoop - This function is used by other analyses to update loop /// information. NewBB is set to be a new member of the current loop. Because /// of this, it is added as a member of all parent loops, and is added to the /// specified LoopInfo object as being in the current basic block. It is not /// valid to replace the loop header with this method. /// void Loop::addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI) { assert(LI[getHeader()] == this && "Incorrect LI specified for this loop!"); assert(NewBB && "Cannot add a null basic block to the loop!"); assert(LI[NewBB] == 0 && "BasicBlock already in the loop!"); // Add the loop mapping to the LoopInfo object... LI.BBMap[NewBB] = this; // Add the basic block to this loop and all parent loops... Loop *L = this; while (L) { L->Blocks.push_back(NewBB); L = L->getParentLoop(); } } /// changeExitBlock - This method is used to update loop information. All /// instances of the specified Old basic block are removed from the exit list /// and replaced with New. /// void Loop::changeExitBlock(BasicBlock *Old, BasicBlock *New) { assert(Old != New && "Cannot changeExitBlock to the same thing!"); assert(Old && New && "Cannot changeExitBlock to or from a null node!"); assert(hasExitBlock(Old) && "Old exit block not found!"); std::vector<BasicBlock*>::iterator I = std::find(ExitBlocks.begin(), ExitBlocks.end(), Old); while (I != ExitBlocks.end()) { *I = New; I = std::find(I+1, ExitBlocks.end(), Old); } } } // End llvm namespace <commit_msg>Order #includes alphabetically, per style guide.<commit_after>//===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the LoopInfo class that is used to identify natural loops // and determine the loop depth of various nodes of the CFG. Note that the // loops identified may actually be several natural loops that share the same // header node... not just a single natural loop. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Assembly/Writer.h" #include "llvm/Support/CFG.h" #include "Support/DepthFirstIterator.h" #include <algorithm> namespace llvm { static RegisterAnalysis<LoopInfo> X("loops", "Natural Loop Construction", true); //===----------------------------------------------------------------------===// // Loop implementation // bool Loop::contains(const BasicBlock *BB) const { return find(Blocks.begin(), Blocks.end(), BB) != Blocks.end(); } bool Loop::isLoopExit(const BasicBlock *BB) const { for (succ_const_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) { if (!contains(*SI)) return true; } return false; } /// getNumBackEdges - Calculate the number of back edges to the loop header. /// unsigned Loop::getNumBackEdges() const { unsigned NumBackEdges = 0; BasicBlock *H = getHeader(); for (pred_iterator I = pred_begin(H), E = pred_end(H); I != E; ++I) if (contains(*I)) ++NumBackEdges; return NumBackEdges; } void Loop::print(std::ostream &OS, unsigned Depth) const { OS << std::string(Depth*2, ' ') << "Loop Containing: "; for (unsigned i = 0; i < getBlocks().size(); ++i) { if (i) OS << ","; WriteAsOperand(OS, getBlocks()[i], false); } if (!ExitBlocks.empty()) { OS << "\tExitBlocks: "; for (unsigned i = 0; i < getExitBlocks().size(); ++i) { if (i) OS << ","; WriteAsOperand(OS, getExitBlocks()[i], false); } } OS << "\n"; for (iterator I = begin(), E = end(); I != E; ++I) (*I)->print(OS, Depth+2); } void Loop::dump() const { print(std::cerr); } //===----------------------------------------------------------------------===// // LoopInfo implementation // void LoopInfo::stub() {} bool LoopInfo::runOnFunction(Function &) { releaseMemory(); Calculate(getAnalysis<DominatorSet>()); // Update return false; } void LoopInfo::releaseMemory() { for (std::vector<Loop*>::iterator I = TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I) delete *I; // Delete all of the loops... BBMap.clear(); // Reset internal state of analysis TopLevelLoops.clear(); } void LoopInfo::Calculate(const DominatorSet &DS) { BasicBlock *RootNode = DS.getRoot(); for (df_iterator<BasicBlock*> NI = df_begin(RootNode), NE = df_end(RootNode); NI != NE; ++NI) if (Loop *L = ConsiderForLoop(*NI, DS)) TopLevelLoops.push_back(L); for (unsigned i = 0; i < TopLevelLoops.size(); ++i) TopLevelLoops[i]->setLoopDepth(1); } void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); AU.addRequired<DominatorSet>(); } void LoopInfo::print(std::ostream &OS) const { for (unsigned i = 0; i < TopLevelLoops.size(); ++i) TopLevelLoops[i]->print(OS); #if 0 for (std::map<BasicBlock*, Loop*>::const_iterator I = BBMap.begin(), E = BBMap.end(); I != E; ++I) OS << "BB '" << I->first->getName() << "' level = " << I->second->LoopDepth << "\n"; #endif } static bool isNotAlreadyContainedIn(Loop *SubLoop, Loop *ParentLoop) { if (SubLoop == 0) return true; if (SubLoop == ParentLoop) return false; return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop); } Loop *LoopInfo::ConsiderForLoop(BasicBlock *BB, const DominatorSet &DS) { if (BBMap.find(BB) != BBMap.end()) return 0; // Haven't processed this node? std::vector<BasicBlock *> TodoStack; // Scan the predecessors of BB, checking to see if BB dominates any of // them. This identifies backedges which target this node... for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) if (DS.dominates(BB, *I)) // If BB dominates it's predecessor... TodoStack.push_back(*I); if (TodoStack.empty()) return 0; // No backedges to this block... // Create a new loop to represent this basic block... Loop *L = new Loop(BB); BBMap[BB] = L; BasicBlock *EntryBlock = &BB->getParent()->getEntryBlock(); while (!TodoStack.empty()) { // Process all the nodes in the loop BasicBlock *X = TodoStack.back(); TodoStack.pop_back(); if (!L->contains(X) && // As of yet unprocessed?? DS.dominates(EntryBlock, X)) { // X is reachable from entry block? // Check to see if this block already belongs to a loop. If this occurs // then we have a case where a loop that is supposed to be a child of the // current loop was processed before the current loop. When this occurs, // this child loop gets added to a part of the current loop, making it a // sibling to the current loop. We have to reparent this loop. if (Loop *SubLoop = const_cast<Loop*>(getLoopFor(X))) if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)) { // Remove the subloop from it's current parent... assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L); Loop *SLP = SubLoop->ParentLoop; // SubLoopParent std::vector<Loop*>::iterator I = std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop); assert(I != SLP->SubLoops.end() && "SubLoop not a child of parent?"); SLP->SubLoops.erase(I); // Remove from parent... // Add the subloop to THIS loop... SubLoop->ParentLoop = L; L->SubLoops.push_back(SubLoop); } // Normal case, add the block to our loop... L->Blocks.push_back(X); // Add all of the predecessors of X to the end of the work stack... TodoStack.insert(TodoStack.end(), pred_begin(X), pred_end(X)); } } // If there are any loops nested within this loop, create them now! for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(), E = L->Blocks.end(); I != E; ++I) if (Loop *NewLoop = ConsiderForLoop(*I, DS)) { L->SubLoops.push_back(NewLoop); NewLoop->ParentLoop = L; } // Add the basic blocks that comprise this loop to the BBMap so that this // loop can be found for them. // for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(), E = L->Blocks.end(); I != E; ++I) { std::map<BasicBlock*, Loop*>::iterator BBMI = BBMap.lower_bound(*I); if (BBMI == BBMap.end() || BBMI->first != *I) // Not in map yet... BBMap.insert(BBMI, std::make_pair(*I, L)); // Must be at this level } // Now that we have a list of all of the child loops of this loop, check to // see if any of them should actually be nested inside of each other. We can // accidentally pull loops our of their parents, so we must make sure to // organize the loop nests correctly now. { std::map<BasicBlock*, Loop*> ContainingLoops; for (unsigned i = 0; i != L->SubLoops.size(); ++i) { Loop *Child = L->SubLoops[i]; assert(Child->getParentLoop() == L && "Not proper child loop?"); if (Loop *ContainingLoop = ContainingLoops[Child->getHeader()]) { // If there is already a loop which contains this loop, move this loop // into the containing loop. MoveSiblingLoopInto(Child, ContainingLoop); --i; // The loop got removed from the SubLoops list. } else { // This is currently considered to be a top-level loop. Check to see if // any of the contained blocks are loop headers for subloops we have // already processed. for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) { Loop *&BlockLoop = ContainingLoops[Child->Blocks[b]]; if (BlockLoop == 0) { // Child block not processed yet... BlockLoop = Child; } else if (BlockLoop != Child) { Loop *SubLoop = BlockLoop; // Reparent all of the blocks which used to belong to BlockLoops for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j) ContainingLoops[SubLoop->Blocks[j]] = Child; // There is already a loop which contains this block, that means // that we should reparent the loop which the block is currently // considered to belong to to be a child of this loop. MoveSiblingLoopInto(SubLoop, Child); --i; // We just shrunk the SubLoops list. } } } } } // Now that we know all of the blocks that make up this loop, see if there are // any branches to outside of the loop... building the ExitBlocks list. for (std::vector<BasicBlock*>::iterator BI = L->Blocks.begin(), BE = L->Blocks.end(); BI != BE; ++BI) for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) if (!L->contains(*I)) // Not in current loop? L->ExitBlocks.push_back(*I); // It must be an exit block... return L; } /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside of /// the NewParent Loop, instead of being a sibling of it. void LoopInfo::MoveSiblingLoopInto(Loop *NewChild, Loop *NewParent) { Loop *OldParent = NewChild->getParentLoop(); assert(OldParent && OldParent == NewParent->getParentLoop() && NewChild != NewParent && "Not sibling loops!"); // Remove NewChild from being a child of OldParent std::vector<Loop*>::iterator I = std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(), NewChild); assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??"); OldParent->SubLoops.erase(I); // Remove from parent's subloops list NewChild->ParentLoop = 0; InsertLoopInto(NewChild, NewParent); } /// InsertLoopInto - This inserts loop L into the specified parent loop. If the /// parent loop contains a loop which should contain L, the loop gets inserted /// into L instead. void LoopInfo::InsertLoopInto(Loop *L, Loop *Parent) { BasicBlock *LHeader = L->getHeader(); assert(Parent->contains(LHeader) && "This loop should not be inserted here!"); // Check to see if it belongs in a child loop... for (unsigned i = 0, e = Parent->SubLoops.size(); i != e; ++i) if (Parent->SubLoops[i]->contains(LHeader)) { InsertLoopInto(L, Parent->SubLoops[i]); return; } // If not, insert it here! Parent->SubLoops.push_back(L); L->ParentLoop = Parent; } /// getLoopPreheader - If there is a preheader for this loop, return it. A /// loop has a preheader if there is only one edge to the header of the loop /// from outside of the loop. If this is the case, the block branching to the /// header of the loop is the preheader node. The "preheaders" pass can be /// "Required" to ensure that there is always a preheader node for every loop. /// /// This method returns null if there is no preheader for the loop (either /// because the loop is dead or because multiple blocks branch to the header /// node of this loop). /// BasicBlock *Loop::getLoopPreheader() const { // Keep track of nodes outside the loop branching to the header... BasicBlock *Out = 0; // Loop over the predecessors of the header node... BasicBlock *Header = getHeader(); for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header); PI != PE; ++PI) if (!contains(*PI)) { // If the block is not in the loop... if (Out && Out != *PI) return 0; // Multiple predecessors outside the loop Out = *PI; } // Make sure there is only one exit out of the preheader... succ_iterator SI = succ_begin(Out); ++SI; if (SI != succ_end(Out)) return 0; // Multiple exits from the block, must not be a preheader. // If there is exactly one preheader, return it. If there was zero, then Out // is still null. return Out; } /// addBasicBlockToLoop - This function is used by other analyses to update loop /// information. NewBB is set to be a new member of the current loop. Because /// of this, it is added as a member of all parent loops, and is added to the /// specified LoopInfo object as being in the current basic block. It is not /// valid to replace the loop header with this method. /// void Loop::addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI) { assert(LI[getHeader()] == this && "Incorrect LI specified for this loop!"); assert(NewBB && "Cannot add a null basic block to the loop!"); assert(LI[NewBB] == 0 && "BasicBlock already in the loop!"); // Add the loop mapping to the LoopInfo object... LI.BBMap[NewBB] = this; // Add the basic block to this loop and all parent loops... Loop *L = this; while (L) { L->Blocks.push_back(NewBB); L = L->getParentLoop(); } } /// changeExitBlock - This method is used to update loop information. All /// instances of the specified Old basic block are removed from the exit list /// and replaced with New. /// void Loop::changeExitBlock(BasicBlock *Old, BasicBlock *New) { assert(Old != New && "Cannot changeExitBlock to the same thing!"); assert(Old && New && "Cannot changeExitBlock to or from a null node!"); assert(hasExitBlock(Old) && "Old exit block not found!"); std::vector<BasicBlock*>::iterator I = std::find(ExitBlocks.begin(), ExitBlocks.end(), Old); while (I != ExitBlocks.end()) { *I = New; I = std::find(I+1, ExitBlocks.end(), Old); } } } // End llvm namespace <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief SEEDA03 (RX64M) メイン @copyright Copyright 2017 Kunihito Hiramatsu All Right Reserved. @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include "common/renesas.hpp" #include "common/rspi_io.hpp" #include "common/spi_io.hpp" #include "common/sdc_io.hpp" #include "common/command.hpp" #include "common/fifo.hpp" #include "common/format.hpp" #include "common/input.hpp" #include "common/flash_man.hpp" #include "common/time.h" #include "chip/LTC2348_16.hpp" #include "sample.hpp" #include "chip/EUI_XX.hpp" #include "GR/core/http_server.hpp" #include "GR/core/ftp_server.hpp" #ifdef DEBUG #define CLIENT_DEBUG #define NETS_DEBUG #define WRITE_FILE_DEBUG #endif namespace seeda { static const int seeda_version_ = 238; static const uint32_t build_id_ = B_ID; typedef utils::command<256> CMD; #ifdef SEEDA typedef device::PORT<device::PORT6, device::bitpos::B7> SW1; typedef device::PORT<device::PORT6, device::bitpos::B6> SW2; #endif // Soft SDC 用 SPI 定義(SPI) #ifdef SEEDA typedef device::PORT<device::PORTD, device::bitpos::B6> MISO; typedef device::PORT<device::PORTD, device::bitpos::B4> MOSI; typedef device::PORT<device::PORTD, device::bitpos::B5> SPCK; typedef device::spi_io<MISO, MOSI, SPCK> SPI; typedef device::PORT<device::PORTD, device::bitpos::B3> SDC_SELECT; ///< カード選択信号 typedef device::NULL_PORT SDC_POWER; ///< カード電源制御(常に電源ON) typedef device::PORT<device::PORTE, device::bitpos::B6> SDC_DETECT; ///< カード検出 #else // SDC 用 SPI 定義(RSPI) typedef device::rspi_io<device::RSPI> SPI; typedef device::PORT<device::PORTC, device::bitpos::B4> SDC_SELECT; ///< カード選択信号 typedef device::NULL_PORT SDC_POWER; ///< カード電源制御(常に電源ON) typedef device::PORT<device::PORTB, device::bitpos::B7> SDC_DETECT; ///< カード検出 #endif typedef utils::sdc_io<SPI, SDC_SELECT, SDC_POWER, SDC_DETECT> SDC; #ifdef SEEDA // LTC2348-16 A/D 制御ポート定義 typedef device::PORT<device::PORT4, device::bitpos::B0> LTC_CSN; // P40(141) typedef device::PORT<device::PORTC, device::bitpos::B6> LTC_CNV; // PC6(61) typedef device::PORT<device::PORTD, device::bitpos::B0> LTC_BUSY; // PD0/IRQ0(126) typedef device::PORT<device::PORT5, device::bitpos::B3> LTC_PD; // P53(53) typedef device::PORT<device::PORT5, device::bitpos::B6> LTC_SDI; // P56(50) typedef device::PORT<device::PORT8, device::bitpos::B6> LTC_SCKO; // P86(41) typedef device::PORT<device::PORT8, device::bitpos::B7> LTC_SCKI; // P87(39) typedef device::PORT<device::PORT2, device::bitpos::B0> LTC_SDO0; // P20(37) typedef device::PORT<device::PORT2, device::bitpos::B1> LTC_SDO2; // P21(36) typedef device::PORT<device::PORT2, device::bitpos::B2> LTC_SDO4; // P22(35) typedef device::PORT<device::PORT2, device::bitpos::B3> LTC_SDO6; // P23(34) typedef struct chip::LTC2348_SDO_t<LTC_SCKO, LTC_SDO0, LTC_SDO2, LTC_SDO4, LTC_SDO6> LTC_SDO; typedef chip::LTC2348_16<LTC_CSN, LTC_CNV, LTC_BUSY, LTC_PD, LTC_SDI, LTC_SCKI, LTC_SDO> EADC; #endif typedef device::flash_io FLASH_IO; typedef utils::flash_man<FLASH_IO> FLASH_MAN; typedef net::http_server<SDC, 16, 8192> HTTP; typedef HTTP::http_format http_format; typedef net::ftp_server<SDC> FTP; //-----------------------------------------------------------------// /*! @brief SDC_IO クラスへの参照 @return SDC_IO クラス */ //-----------------------------------------------------------------// SDC& at_sdc(); #ifdef SEEDA //-----------------------------------------------------------------// /*! @brief EADC クラスへの参照 @return EADC クラス */ //-----------------------------------------------------------------// EADC& at_eadc(); #endif //-----------------------------------------------------------------// /*! @brief EADC サーバー */ //-----------------------------------------------------------------// void eadc_server(); //-----------------------------------------------------------------// /*! @brief EADC サーバー許可 @param[in] ena 「false」の場合不許可 */ //-----------------------------------------------------------------// void enable_eadc_server(bool ena = true); //-----------------------------------------------------------------// /*! @brief 時間の作成 @param[in] date 日付 @param[in] time 時間 */ //-----------------------------------------------------------------// size_t make_time(const char* date, const char* time); //-----------------------------------------------------------------// /*! @brief GMT 時間の設定 @param[in] t GMT 時間 */ //-----------------------------------------------------------------// void set_time(time_t t); //-----------------------------------------------------------------// /*! @brief 時間の表示 @param[in] t 時間 @param[in] dst 出力文字列 @param[in] size 文字列の大きさ @return 生成された文字列の長さ */ //-----------------------------------------------------------------// int disp_time(time_t t, char* dst = nullptr, uint32_t size = 0); //-----------------------------------------------------------------// /*! @brief 設定スイッチの状態を取得 @return 設定スイッチの状態 */ //-----------------------------------------------------------------// uint8_t get_switch() { #ifdef SEEDA return static_cast<uint8_t>(!SW1::P()) | (static_cast<uint8_t>(!SW2::P()) << 1); #else return 0; // for only develope mode #endif } //-----------------------------------------------------------------// /*! @brief A/D サンプルの参照 @param[in] ch チャネル(0~7) @return A/D サンプル */ //-----------------------------------------------------------------// sample_t& at_sample(uint8_t ch); //-----------------------------------------------------------------// /*! @brief A/D サンプルの取得 @return A/D サンプル */ //-----------------------------------------------------------------// const sample_data& get_sample_data(); //-----------------------------------------------------------------// /*! @brief 内臓 A/D 変換値の取得 @param[in] ch チャネル(5、6、7) @return A/D 変換値 */ //-----------------------------------------------------------------// uint16_t get_adc(uint32_t ch); } extern "C" { //-----------------------------------------------------------------// /*! @brief GMT 時間の取得 @return GMT 時間 */ //-----------------------------------------------------------------// time_t get_time(); }; <commit_msg>update version NO<commit_after>#pragma once //=====================================================================// /*! @file @brief SEEDA03 (RX64M) メイン @copyright Copyright 2017 Kunihito Hiramatsu All Right Reserved. @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include "common/renesas.hpp" #include "common/rspi_io.hpp" #include "common/spi_io.hpp" #include "common/sdc_io.hpp" #include "common/command.hpp" #include "common/fifo.hpp" #include "common/format.hpp" #include "common/input.hpp" #include "common/flash_man.hpp" #include "common/time.h" #include "chip/LTC2348_16.hpp" #include "sample.hpp" #include "chip/EUI_XX.hpp" #include "GR/core/http_server.hpp" #include "GR/core/ftp_server.hpp" #ifdef DEBUG #define CLIENT_DEBUG #define NETS_DEBUG #define WRITE_FILE_DEBUG #endif namespace seeda { static const int seeda_version_ = 250; static const uint32_t build_id_ = B_ID; typedef utils::command<256> CMD; #ifdef SEEDA typedef device::PORT<device::PORT6, device::bitpos::B7> SW1; typedef device::PORT<device::PORT6, device::bitpos::B6> SW2; #endif // Soft SDC 用 SPI 定義(SPI) #ifdef SEEDA typedef device::PORT<device::PORTD, device::bitpos::B6> MISO; typedef device::PORT<device::PORTD, device::bitpos::B4> MOSI; typedef device::PORT<device::PORTD, device::bitpos::B5> SPCK; typedef device::spi_io<MISO, MOSI, SPCK> SPI; typedef device::PORT<device::PORTD, device::bitpos::B3> SDC_SELECT; ///< カード選択信号 typedef device::NULL_PORT SDC_POWER; ///< カード電源制御(常に電源ON) typedef device::PORT<device::PORTE, device::bitpos::B6> SDC_DETECT; ///< カード検出 #else // SDC 用 SPI 定義(RSPI) typedef device::rspi_io<device::RSPI> SPI; typedef device::PORT<device::PORTC, device::bitpos::B4> SDC_SELECT; ///< カード選択信号 typedef device::NULL_PORT SDC_POWER; ///< カード電源制御(常に電源ON) typedef device::PORT<device::PORTB, device::bitpos::B7> SDC_DETECT; ///< カード検出 #endif typedef utils::sdc_io<SPI, SDC_SELECT, SDC_POWER, SDC_DETECT> SDC; #ifdef SEEDA // LTC2348-16 A/D 制御ポート定義 typedef device::PORT<device::PORT4, device::bitpos::B0> LTC_CSN; // P40(141) typedef device::PORT<device::PORTC, device::bitpos::B6> LTC_CNV; // PC6(61) typedef device::PORT<device::PORTD, device::bitpos::B0> LTC_BUSY; // PD0/IRQ0(126) typedef device::PORT<device::PORT5, device::bitpos::B3> LTC_PD; // P53(53) typedef device::PORT<device::PORT5, device::bitpos::B6> LTC_SDI; // P56(50) typedef device::PORT<device::PORT8, device::bitpos::B6> LTC_SCKO; // P86(41) typedef device::PORT<device::PORT8, device::bitpos::B7> LTC_SCKI; // P87(39) typedef device::PORT<device::PORT2, device::bitpos::B0> LTC_SDO0; // P20(37) typedef device::PORT<device::PORT2, device::bitpos::B1> LTC_SDO2; // P21(36) typedef device::PORT<device::PORT2, device::bitpos::B2> LTC_SDO4; // P22(35) typedef device::PORT<device::PORT2, device::bitpos::B3> LTC_SDO6; // P23(34) typedef struct chip::LTC2348_SDO_t<LTC_SCKO, LTC_SDO0, LTC_SDO2, LTC_SDO4, LTC_SDO6> LTC_SDO; typedef chip::LTC2348_16<LTC_CSN, LTC_CNV, LTC_BUSY, LTC_PD, LTC_SDI, LTC_SCKI, LTC_SDO> EADC; #endif typedef device::flash_io FLASH_IO; typedef utils::flash_man<FLASH_IO> FLASH_MAN; typedef net::http_server<SDC, 16, 8192> HTTP; typedef HTTP::http_format http_format; typedef net::ftp_server<SDC> FTP; //-----------------------------------------------------------------// /*! @brief SDC_IO クラスへの参照 @return SDC_IO クラス */ //-----------------------------------------------------------------// SDC& at_sdc(); #ifdef SEEDA //-----------------------------------------------------------------// /*! @brief EADC クラスへの参照 @return EADC クラス */ //-----------------------------------------------------------------// EADC& at_eadc(); #endif //-----------------------------------------------------------------// /*! @brief EADC サーバー */ //-----------------------------------------------------------------// void eadc_server(); //-----------------------------------------------------------------// /*! @brief EADC サーバー許可 @param[in] ena 「false」の場合不許可 */ //-----------------------------------------------------------------// void enable_eadc_server(bool ena = true); //-----------------------------------------------------------------// /*! @brief 時間の作成 @param[in] date 日付 @param[in] time 時間 */ //-----------------------------------------------------------------// size_t make_time(const char* date, const char* time); //-----------------------------------------------------------------// /*! @brief GMT 時間の設定 @param[in] t GMT 時間 */ //-----------------------------------------------------------------// void set_time(time_t t); //-----------------------------------------------------------------// /*! @brief 時間の表示 @param[in] t 時間 @param[in] dst 出力文字列 @param[in] size 文字列の大きさ @return 生成された文字列の長さ */ //-----------------------------------------------------------------// int disp_time(time_t t, char* dst = nullptr, uint32_t size = 0); //-----------------------------------------------------------------// /*! @brief 設定スイッチの状態を取得 @return 設定スイッチの状態 */ //-----------------------------------------------------------------// uint8_t get_switch() { #ifdef SEEDA return static_cast<uint8_t>(!SW1::P()) | (static_cast<uint8_t>(!SW2::P()) << 1); #else return 0; // for only develope mode #endif } //-----------------------------------------------------------------// /*! @brief A/D サンプルの参照 @param[in] ch チャネル(0~7) @return A/D サンプル */ //-----------------------------------------------------------------// sample_t& at_sample(uint8_t ch); //-----------------------------------------------------------------// /*! @brief A/D サンプルの取得 @return A/D サンプル */ //-----------------------------------------------------------------// const sample_data& get_sample_data(); //-----------------------------------------------------------------// /*! @brief 内臓 A/D 変換値の取得 @param[in] ch チャネル(5、6、7) @return A/D 変換値 */ //-----------------------------------------------------------------// uint16_t get_adc(uint32_t ch); } extern "C" { //-----------------------------------------------------------------// /*! @brief GMT 時間の取得 @return GMT 時間 */ //-----------------------------------------------------------------// time_t get_time(); }; <|endoftext|>
<commit_before>/* * Copyright 2010 Jonathan R. Guthrie * * 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 <sstream> #include "stanza.hpp" #include "iq-stanza.hpp" #include "presence-stanza.hpp" #include "message-stanza.hpp" #include "features-stanza.hpp" Stanza::Stanza(void) { m_to = NULL; m_from = NULL; m_type = NULL; m_id = NULL; m_namespace = NULL; m_errorMessage = NULL; m_error = 200; } Stanza::~Stanza(void) { delete m_to; delete m_from; delete m_type; delete m_id; delete m_namespace; delete m_errorMessage; } void Stanza::To(const std::string *to) { delete m_to; m_to = to; } void Stanza::To(const std::string &to) { To(new std::string(to)); } void Stanza::From(const std::string *from) { delete m_from; m_from = from; } void Stanza::From(const std::string &from) { From(new std::string(from)); } void Stanza::Type(const std::string *type) { delete m_type; m_type = type; } void Stanza::Type(const std::string &type) { Type(new std::string(type)); } void Stanza::Id(const std::string *id) { delete m_id; m_id = id; } void Stanza::Id(const std::string &id) { Id(new std::string(id)); } void Stanza::Namespace(const std::string *name_space) { delete m_namespace; m_namespace = name_space; } void Stanza::Namespace(const std::string &name_space) { Namespace(new std::string(name_space)); } void Stanza::ErrorMessage(const std::string *errorMessage) { delete m_errorMessage; m_errorMessage = errorMessage; } void Stanza::ErrorMessage(const std::string &errorMessage) { ErrorMessage(new std::string(errorMessage)); } void Stanza::Error(int error) { m_error = error; } const std::string *Stanza::To(void) const { return m_to; } const std::string *Stanza::From(void) const { return m_from; } const std::string *Stanza::Type(void) const { return m_type; } const std::string *Stanza::Id(void) const { return m_id; } const std::string *Stanza::Namespace(void) const { return m_namespace; } const std::string *Stanza::ErrorMessage(void) const { return m_errorMessage; } int Stanza::Error(void) const { return m_error; } const std::string *Stanza::renderStanza(const std::string *id, const std::string &tag, const std::string &body) const { std::ostringstream result; result << "<" << tag; if (NULL != id) { result << " id='" << *id << "'"; } if (NULL != m_to) { result << " to='" << *m_to << "'"; } if (NULL != m_from) { result << " from='" << *m_from << "'"; } if (NULL != m_type) { result << " type='" << *m_type << "'"; } if ("" != body) { result << ">" << body << "</" << tag << ">"; } else { result << "/>"; } return new std::string(result.str()); } Stanza *Stanza::parse(const JabberElementNode *root) { Stanza *result = NULL; if ("iq" == root->m_name) { result = IqStanza::parse(root); } if ("presence" == root->m_name) { result = PresenceStanza::parse(root); } if ("message" == root->m_name) { result = MessageStanza::parse(root); } if ("stream:features" == root->m_name) { result = FeaturesStanza::parse(root); } return result; } <commit_msg>Because I was actually storing the string pointers in the stanza, if I tried to send two stanzas to the same sender taken from the from field, the second one would try to pull the address from a deleted string, which caused all kinds of undesired behavior. I could copy the string in the client, but this is a library bug, so I'm fixing it in the library.<commit_after>/* * Copyright 2010 Jonathan R. Guthrie * * 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 <sstream> #include "stanza.hpp" #include "iq-stanza.hpp" #include "presence-stanza.hpp" #include "message-stanza.hpp" #include "features-stanza.hpp" Stanza::Stanza(void) { m_to = NULL; m_from = NULL; m_type = NULL; m_id = NULL; m_namespace = NULL; m_errorMessage = NULL; m_error = 200; } Stanza::~Stanza(void) { delete m_to; delete m_from; delete m_type; delete m_id; delete m_namespace; delete m_errorMessage; } void Stanza::To(const std::string *to) { delete m_to; m_to = NULL; if (NULL != to) { m_to = new std::string(*to); } } void Stanza::To(const std::string &to) { To(&to); } void Stanza::From(const std::string *from) { delete m_from; m_from = NULL; if (NULL != from) { m_from = new std::string(*from); } } void Stanza::From(const std::string &from) { From(&from); } void Stanza::Type(const std::string *type) { delete m_type; m_type = NULL; if (NULL != type) { m_type = new std::string(*type); } } void Stanza::Type(const std::string &type) { Type(&type); } void Stanza::Id(const std::string *id) { delete m_id; m_id = NULL; if (NULL != id) { m_id = new std::string(*id); } } void Stanza::Id(const std::string &id) { Id(&id); } void Stanza::Namespace(const std::string *name_space) { delete m_namespace; m_namespace = NULL; if (name_space != NULL) { m_namespace = new std::string(*name_space); } } void Stanza::Namespace(const std::string &name_space) { Namespace(&name_space); } void Stanza::ErrorMessage(const std::string *errorMessage) { delete m_errorMessage; m_errorMessage = NULL; if (NULL != errorMessage) { m_errorMessage = new std::string(*errorMessage); } } void Stanza::ErrorMessage(const std::string &errorMessage) { ErrorMessage(&errorMessage); } void Stanza::Error(int error) { m_error = error; } const std::string *Stanza::To(void) const { return m_to; } const std::string *Stanza::From(void) const { return m_from; } const std::string *Stanza::Type(void) const { return m_type; } const std::string *Stanza::Id(void) const { return m_id; } const std::string *Stanza::Namespace(void) const { return m_namespace; } const std::string *Stanza::ErrorMessage(void) const { return m_errorMessage; } int Stanza::Error(void) const { return m_error; } const std::string *Stanza::renderStanza(const std::string *id, const std::string &tag, const std::string &body) const { std::ostringstream result; result << "<" << tag; if (NULL != id) { result << " id='" << *id << "'"; } if (NULL != m_to) { result << " to='" << *m_to << "'"; } if (NULL != m_from) { result << " from='" << *m_from << "'"; } if (NULL != m_type) { result << " type='" << *m_type << "'"; } if ("" != body) { result << ">" << body << "</" << tag << ">"; } else { result << "/>"; } return new std::string(result.str()); } Stanza *Stanza::parse(const JabberElementNode *root) { Stanza *result = NULL; if ("iq" == root->m_name) { result = IqStanza::parse(root); } if ("presence" == root->m_name) { result = PresenceStanza::parse(root); } if ("message" == root->m_name) { result = MessageStanza::parse(root); } if ("stream:features" == root->m_name) { result = FeaturesStanza::parse(root); } return result; } <|endoftext|>
<commit_before>#ifndef STUFF_GRID_HH_INCLUDED #define STUFF_GRID_HH_INCLUDED namespace Stuff { /** * \brief calculates length of given intersection in world coordinates * \tparam IntersectionIteratorType * IntersectionIteratorType * \param[in] intIt * intersection * \return length of intersection **/ template < class IntersectionIteratorType > double getLenghtOfIntersection( const IntersectionIteratorType& intIt ) { typedef typename IntersectionIteratorType::Geometry IntersectionGeometryType; const IntersectionGeometryType& intersectionGeoemtry = intIt.intersectionGlobal(); return intersectionGeoemtry.volume(); // assert( intersectionGeoemtry.corners() == 2 ); // typedef typename IntersectionIteratorType::ctype // ctype; // const int dimworld = IntersectionIteratorType::dimensionworld; // typedef Dune::FieldVector< ctype, dimworld > // DomainType; // const DomainType cornerOne = intersectionGeoemtry[0]; // const DomainType cornerTwo = intersectionGeoemtry[1]; // const DomainType difference = cornerOne - cornerTwo; // return difference.two_norm(); } template < class GridPartType, class DiscreteFunctionSpaceType, class OutStream > void getGridInformation( GridPartType& gridPart, DiscreteFunctionSpaceType& space, OutStream& out ) { int numberOfEntities( 0 ); int numberOfIntersections( 0 ); int numberOfInnerIntersections( 0 ); int numberOfBoundaryIntersections( 0 ); double maxGridWidth( 0.0 ); typedef typename GridPartType::GridType GridType; typedef typename GridType::template Codim< 0 >::Entity EntityType; typedef typename GridPartType::template Codim< 0 >::IteratorType EntityIteratorType; typedef typename GridPartType::IntersectionIteratorType IntersectionIteratorType; EntityIteratorType entityItEndLog = space.end(); for ( EntityIteratorType entityItLog = space.begin(); entityItLog != entityItEndLog; ++entityItLog ) { const EntityType& entity = *entityItLog; // count entities ++numberOfEntities; // walk the intersections IntersectionIteratorType intItEnd = gridPart.iend( entity ); for ( IntersectionIteratorType intIt = gridPart.ibegin( entity ); intIt != intItEnd; ++intIt ) { // count intersections ++numberOfIntersections; maxGridWidth = Stuff::getLenghtOfIntersection( intIt ) > maxGridWidth ? Stuff::getLenghtOfIntersection( intIt ) : maxGridWidth; // if we are inside the grid if ( intIt.neighbor() && !intIt.boundary() ) { // count inner intersections ++numberOfInnerIntersections; } // if we are on the boundary of the grid if ( !intIt.neighbor() && intIt.boundary() ) { // count boundary intersections ++numberOfBoundaryIntersections; } } } out << "found " << numberOfEntities << " entities," << std::endl; out << "found " << numberOfIntersections << " intersections," << std::endl; out << " " << numberOfInnerIntersections << " intersections inside and" << std::endl; out << " " << numberOfBoundaryIntersections << " intersections on the boundary." << std::endl; out << " maxGridWidth is " << maxGridWidth << std::endl; } template < class Space, int codim = 0 > class GridWalk { private: typedef typename Space::GridPartType GridPart; typedef typename GridPart::template Codim< codim >::IteratorType EntityIteratorType; typedef typename GridPart::IntersectionIteratorType IntersectionIteratorType; typedef typename IntersectionIteratorType::EntityPointer EntityPointer; public: GridWalk ( Space& gp ) : space_(gp), gridPart_( gp.gridPart() ) { EntityIteratorType entityItEndLog = space_.end(); unsigned int en_idx = 0; for ( EntityIteratorType it = space_.begin(); it != entityItEndLog; ++it,++en_idx ) { entityIdxMap_.push_back( it ); } } template < class Functor > void operator () ( Functor& f ) { f.preWalk(); EntityIteratorType entityItEndLog = space_.end(); for ( EntityIteratorType it = space_.begin(); it != entityItEndLog; ++it ) { const int ent_idx = getIdx( entityIdxMap_, it ); f( *it, *it, ent_idx, ent_idx); IntersectionIteratorType intItEnd = gridPart_.iend( *it ); for ( IntersectionIteratorType intIt = gridPart_.ibegin( *it ); intIt != intItEnd; ++intIt ) { if ( !intIt.boundary() ) { const int neigh_idx = getIdx( entityIdxMap_, intIt.outside() ); f( *it, *intIt.outside(), ent_idx, neigh_idx); } } } f.postWalk(); } private: Space& space_; GridPart& gridPart_; typedef std::vector< EntityPointer > EntityIdxMap; EntityIdxMap entityIdxMap_; }; }//end namespace #endif <commit_msg>getBarycenter in local/global coords<commit_after>#ifndef STUFF_GRID_HH_INCLUDED #define STUFF_GRID_HH_INCLUDED #include <dune/common/fvector.hh> namespace Stuff { /** * \brief calculates length of given intersection in world coordinates * \tparam IntersectionIteratorType * IntersectionIteratorType * \param[in] intIt * intersection * \return length of intersection **/ template < class IntersectionIteratorType > double getLenghtOfIntersection( const IntersectionIteratorType& intIt ) { typedef typename IntersectionIteratorType::Geometry IntersectionGeometryType; const IntersectionGeometryType& intersectionGeoemtry = intIt.intersectionGlobal(); return intersectionGeoemtry.volume(); // assert( intersectionGeoemtry.corners() == 2 ); // typedef typename IntersectionIteratorType::ctype // ctype; // const int dimworld = IntersectionIteratorType::dimensionworld; // typedef Dune::FieldVector< ctype, dimworld > // DomainType; // const DomainType cornerOne = intersectionGeoemtry[0]; // const DomainType cornerTwo = intersectionGeoemtry[1]; // const DomainType difference = cornerOne - cornerTwo; // return difference.two_norm(); } template < class GridPartType, class DiscreteFunctionSpaceType, class OutStream > void getGridInformation( GridPartType& gridPart, DiscreteFunctionSpaceType& space, OutStream& out ) { int numberOfEntities( 0 ); int numberOfIntersections( 0 ); int numberOfInnerIntersections( 0 ); int numberOfBoundaryIntersections( 0 ); double maxGridWidth( 0.0 ); typedef typename GridPartType::GridType GridType; typedef typename GridType::template Codim< 0 >::Entity EntityType; typedef typename GridPartType::template Codim< 0 >::IteratorType EntityIteratorType; typedef typename GridPartType::IntersectionIteratorType IntersectionIteratorType; EntityIteratorType entityItEndLog = space.end(); for ( EntityIteratorType entityItLog = space.begin(); entityItLog != entityItEndLog; ++entityItLog ) { const EntityType& entity = *entityItLog; // count entities ++numberOfEntities; // walk the intersections IntersectionIteratorType intItEnd = gridPart.iend( entity ); for ( IntersectionIteratorType intIt = gridPart.ibegin( entity ); intIt != intItEnd; ++intIt ) { // count intersections ++numberOfIntersections; maxGridWidth = Stuff::getLenghtOfIntersection( intIt ) > maxGridWidth ? Stuff::getLenghtOfIntersection( intIt ) : maxGridWidth; // if we are inside the grid if ( intIt.neighbor() && !intIt.boundary() ) { // count inner intersections ++numberOfInnerIntersections; } // if we are on the boundary of the grid if ( !intIt.neighbor() && intIt.boundary() ) { // count boundary intersections ++numberOfBoundaryIntersections; } } } out << "found " << numberOfEntities << " entities," << std::endl; out << "found " << numberOfIntersections << " intersections," << std::endl; out << " " << numberOfInnerIntersections << " intersections inside and" << std::endl; out << " " << numberOfBoundaryIntersections << " intersections on the boundary." << std::endl; out << " maxGridWidth is " << maxGridWidth << std::endl; } template < class Space, int codim = 0 > class GridWalk { private: typedef typename Space::GridPartType GridPart; typedef typename GridPart::template Codim< codim >::IteratorType EntityIteratorType; typedef typename GridPart::IntersectionIteratorType IntersectionIteratorType; typedef typename IntersectionIteratorType::EntityPointer EntityPointer; public: GridWalk ( Space& gp ) : space_(gp), gridPart_( gp.gridPart() ) { EntityIteratorType entityItEndLog = space_.end(); unsigned int en_idx = 0; for ( EntityIteratorType it = space_.begin(); it != entityItEndLog; ++it,++en_idx ) { entityIdxMap_.push_back( it ); } } template < class Functor > void operator () ( Functor& f ) { f.preWalk(); EntityIteratorType entityItEndLog = space_.end(); for ( EntityIteratorType it = space_.begin(); it != entityItEndLog; ++it ) { const int ent_idx = getIdx( entityIdxMap_, it ); f( *it, *it, ent_idx, ent_idx); IntersectionIteratorType intItEnd = gridPart_.iend( *it ); for ( IntersectionIteratorType intIt = gridPart_.ibegin( *it ); intIt != intItEnd; ++intIt ) { if ( !intIt.boundary() ) { const int neigh_idx = getIdx( entityIdxMap_, intIt.outside() ); f( *it, *intIt.outside(), ent_idx, neigh_idx); } } } f.postWalk(); } private: Space& space_; GridPart& gridPart_; typedef std::vector< EntityPointer > EntityIdxMap; EntityIdxMap entityIdxMap_; }; template < class GeometryType > Dune::FieldVector< typename GeometryType::ctype, GeometryType::mydimension > getBarycenterLocal( const GeometryType& geometry ) { assert( geometry.corners() > 0 ); Dune::FieldVector< typename GeometryType::ctype, GeometryType::mydimension > center; for( int i = 0; i < geometry.corners(); ++i ) { center += geometry.local( geometry[i] ); } center /= geometry.corners(); return center; } template < class GeometryType > Dune::FieldVector< typename GeometryType::ctype, GeometryType::coorddimension > getBarycenterGlobal( const GeometryType& geometry ) { assert( geometry.corners() > 0 ); Dune::FieldVector< typename GeometryType::ctype, GeometryType::coorddimension > center; for( int i = 0; i < geometry.corners(); ++i ) { center += geometry[i] ; } center /= geometry.corners(); return center; } }//end namespace #endif <|endoftext|>
<commit_before>/** MQTT433gateway - MQTT 433.92 MHz radio gateway utilizing ESPiLight Project home: https://github.com/puuu/MQTT433gateway/ The MIT License (MIT) Copyright (c) 2017 Jan Losinski Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <algorithm> #include "Settings.h" #include <ArduinoJson.h> #include <FS.h> #include <ArduinoSimpleLogging.h> static inline bool any(std::initializer_list<bool> items) { return std::any_of(items.begin(), items.end(), [](bool item) { return item; }); } std::function<bool(const String &)> notEmpty() { return [](const String &str) { return str.length() > 0; }; } template <typename T> std::function<bool(const T &)> notZero() { return [](const T &val) { return val != 0; }; } template <typename TVal, typename TKey> bool setIfPresent(JsonObject &obj, TKey key, TVal &var, const std::function<bool(const TVal &)> &validator = std::function<bool(const TVal &)>()) { if (obj.containsKey(key)) { TVal tmp = obj.get<TVal>(key); if (tmp != var && (!validator || validator(tmp))) { var = tmp; return true; } } return false; } void Settings::registerChangeHandler(SettingType setting, const SettingCallbackFn &callback) { listeners.emplace_front(setting, callback); } void Settings::onConfigChange(SettingTypeSet typeSet) const { for (const auto &listener : listeners) { if (typeSet[listener.type]) { listener.callback(*this); } } } void Settings::load() { if (SPIFFS.exists(SETTINGS_FILE)) { File file = SPIFFS.open(SETTINGS_FILE, "r"); String settingsContents = file.readStringUntil(SETTINGS_TERMINATOR); file.close(); Logger.debug.println("FILE CONTENTS:"); Logger.debug.println(settingsContents); deserialize(settingsContents, false); } } void Settings::notifyAll() { // Fire for all onConfigChange(SettingTypeSet().set()); } void Settings::save() { File file = SPIFFS.open(SETTINGS_FILE, "w"); if (!file) { Logger.error.println(F("Opening settings file failed")); } else { serialize(file, false, true); file.close(); } } Settings::~Settings() = default; void Settings::serialize(Print &stream, bool pretty, bool sensible) const { DynamicJsonBuffer jsonBuffer; JsonObject &root = jsonBuffer.createObject(); root[F("deviceName")] = this->deviceName; root[F("mqttReceiveTopic")] = this->mqttReceiveTopic; root[F("mqttSendTopic")] = this->mqttSendTopic; root[F("mqttBroker")] = this->mqttBroker; root[F("mqttBrokerPort")] = this->mqttBrokerPort; root[F("mqttUser")] = this->mqttUser; root[F("mqttRetain")] = this->mqttRetain; root[F("rfReceiverPin")] = this->rfReceiverPin; root[F("rfTransmitterPin")] = this->rfTransmitterPin; root[F("rfEchoMessages")] = this->rfEchoMessages; { DynamicJsonBuffer protoBuffer; JsonArray &parsedProtocols = protoBuffer.parseArray(this->rfProtocols); JsonArray &protos = root.createNestedArray(F("rfProtocols")); for (const auto proto : parsedProtocols) { protos.add(proto.as<String>()); } } root[F("serialLogLevel")] = this->serialLogLevel; root[F("webLogLevel")] = this->webLogLevel; root[F("syslogLevel")] = this->syslogLevel; root[F("syslogHost")] = this->syslogHost; root[F("syslogPort")] = this->syslogPort; if (sensible) { root[F("mqttPassword")] = this->mqttPassword; root[F("configPassword")] = this->configPassword; } if (pretty) { root.prettyPrintTo(stream); } else { root.printTo(stream); } } void Settings::deserialize(const String &json, const bool fireCallbacks) { DynamicJsonBuffer jsonBuffer; JsonObject &parsedSettings = jsonBuffer.parseObject(json); if (!parsedSettings.success()) { Logger.warning.println(F("Config parse failed!")); return; } SettingTypeSet changed; changed.set(BASE, setIfPresent(parsedSettings, F("deviceName"), deviceName, notEmpty())); changed.set( MQTT, any({setIfPresent(parsedSettings, F("mqttReceiveTopic"), mqttReceiveTopic), setIfPresent(parsedSettings, F("mqttSendTopic"), mqttSendTopic), setIfPresent(parsedSettings, F("mqttBroker"), mqttBroker, notEmpty()), setIfPresent(parsedSettings, F("mqttBrokerPort"), mqttBrokerPort, notZero<uint16_t>()), setIfPresent(parsedSettings, F("mqttUser"), mqttUser), setIfPresent(parsedSettings, F("mqttPassword"), mqttPassword, notEmpty()), setIfPresent(parsedSettings, F("mqttRetain"), mqttRetain)})); changed.set( RF_CONFIG, any({setIfPresent(parsedSettings, F("rfReceiverPin"), rfReceiverPin), setIfPresent(parsedSettings, F("rfTransmitterPin"), rfTransmitterPin)})); changed.set(RF_ECHO, (setIfPresent(parsedSettings, F("rfEchoMessages"), rfEchoMessages))); if (parsedSettings.containsKey(F("rfProtocols"))) { String buff; parsedSettings[F("rfProtocols")].printTo(buff); if (buff != rfProtocols) { rfProtocols = buff; changed.set(RF_PROTOCOL, true); } } changed.set( LOGGING, any({setIfPresent(parsedSettings, F("serialLogLevel"), serialLogLevel), setIfPresent(parsedSettings, F("webLogLevel"), webLogLevel)})); changed.set(WEB_CONFIG, setIfPresent(parsedSettings, F("configPassword"), configPassword, notEmpty())); changed.set(SYSLOG, any({setIfPresent(parsedSettings, F("syslogLevel"), syslogLevel), setIfPresent(parsedSettings, F("syslogHost"), syslogHost), setIfPresent(parsedSettings, F("syslogPort"), syslogPort)})); if (fireCallbacks) { onConfigChange(changed); } } void Settings::reset() { if (SPIFFS.exists(SETTINGS_FILE)) { SPIFFS.remove(SETTINGS_FILE); } } <commit_msg>Settings: Wrap debug String in F()<commit_after>/** MQTT433gateway - MQTT 433.92 MHz radio gateway utilizing ESPiLight Project home: https://github.com/puuu/MQTT433gateway/ The MIT License (MIT) Copyright (c) 2017 Jan Losinski Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <algorithm> #include "Settings.h" #include <ArduinoJson.h> #include <FS.h> #include <ArduinoSimpleLogging.h> static inline bool any(std::initializer_list<bool> items) { return std::any_of(items.begin(), items.end(), [](bool item) { return item; }); } std::function<bool(const String &)> notEmpty() { return [](const String &str) { return str.length() > 0; }; } template <typename T> std::function<bool(const T &)> notZero() { return [](const T &val) { return val != 0; }; } template <typename TVal, typename TKey> bool setIfPresent(JsonObject &obj, TKey key, TVal &var, const std::function<bool(const TVal &)> &validator = std::function<bool(const TVal &)>()) { if (obj.containsKey(key)) { TVal tmp = obj.get<TVal>(key); if (tmp != var && (!validator || validator(tmp))) { var = tmp; return true; } } return false; } void Settings::registerChangeHandler(SettingType setting, const SettingCallbackFn &callback) { listeners.emplace_front(setting, callback); } void Settings::onConfigChange(SettingTypeSet typeSet) const { for (const auto &listener : listeners) { if (typeSet[listener.type]) { listener.callback(*this); } } } void Settings::load() { if (SPIFFS.exists(SETTINGS_FILE)) { File file = SPIFFS.open(SETTINGS_FILE, "r"); String settingsContents = file.readStringUntil(SETTINGS_TERMINATOR); file.close(); Logger.debug.println(F("FILE CONTENTS:")); Logger.debug.println(settingsContents); deserialize(settingsContents, false); } } void Settings::notifyAll() { // Fire for all onConfigChange(SettingTypeSet().set()); } void Settings::save() { File file = SPIFFS.open(SETTINGS_FILE, "w"); if (!file) { Logger.error.println(F("Opening settings file failed")); } else { serialize(file, false, true); file.close(); } } Settings::~Settings() = default; void Settings::serialize(Print &stream, bool pretty, bool sensible) const { DynamicJsonBuffer jsonBuffer; JsonObject &root = jsonBuffer.createObject(); root[F("deviceName")] = this->deviceName; root[F("mqttReceiveTopic")] = this->mqttReceiveTopic; root[F("mqttSendTopic")] = this->mqttSendTopic; root[F("mqttBroker")] = this->mqttBroker; root[F("mqttBrokerPort")] = this->mqttBrokerPort; root[F("mqttUser")] = this->mqttUser; root[F("mqttRetain")] = this->mqttRetain; root[F("rfReceiverPin")] = this->rfReceiverPin; root[F("rfTransmitterPin")] = this->rfTransmitterPin; root[F("rfEchoMessages")] = this->rfEchoMessages; { DynamicJsonBuffer protoBuffer; JsonArray &parsedProtocols = protoBuffer.parseArray(this->rfProtocols); JsonArray &protos = root.createNestedArray(F("rfProtocols")); for (const auto proto : parsedProtocols) { protos.add(proto.as<String>()); } } root[F("serialLogLevel")] = this->serialLogLevel; root[F("webLogLevel")] = this->webLogLevel; root[F("syslogLevel")] = this->syslogLevel; root[F("syslogHost")] = this->syslogHost; root[F("syslogPort")] = this->syslogPort; if (sensible) { root[F("mqttPassword")] = this->mqttPassword; root[F("configPassword")] = this->configPassword; } if (pretty) { root.prettyPrintTo(stream); } else { root.printTo(stream); } } void Settings::deserialize(const String &json, const bool fireCallbacks) { DynamicJsonBuffer jsonBuffer; JsonObject &parsedSettings = jsonBuffer.parseObject(json); if (!parsedSettings.success()) { Logger.warning.println(F("Config parse failed!")); return; } SettingTypeSet changed; changed.set(BASE, setIfPresent(parsedSettings, F("deviceName"), deviceName, notEmpty())); changed.set( MQTT, any({setIfPresent(parsedSettings, F("mqttReceiveTopic"), mqttReceiveTopic), setIfPresent(parsedSettings, F("mqttSendTopic"), mqttSendTopic), setIfPresent(parsedSettings, F("mqttBroker"), mqttBroker, notEmpty()), setIfPresent(parsedSettings, F("mqttBrokerPort"), mqttBrokerPort, notZero<uint16_t>()), setIfPresent(parsedSettings, F("mqttUser"), mqttUser), setIfPresent(parsedSettings, F("mqttPassword"), mqttPassword, notEmpty()), setIfPresent(parsedSettings, F("mqttRetain"), mqttRetain)})); changed.set( RF_CONFIG, any({setIfPresent(parsedSettings, F("rfReceiverPin"), rfReceiverPin), setIfPresent(parsedSettings, F("rfTransmitterPin"), rfTransmitterPin)})); changed.set(RF_ECHO, (setIfPresent(parsedSettings, F("rfEchoMessages"), rfEchoMessages))); if (parsedSettings.containsKey(F("rfProtocols"))) { String buff; parsedSettings[F("rfProtocols")].printTo(buff); if (buff != rfProtocols) { rfProtocols = buff; changed.set(RF_PROTOCOL, true); } } changed.set( LOGGING, any({setIfPresent(parsedSettings, F("serialLogLevel"), serialLogLevel), setIfPresent(parsedSettings, F("webLogLevel"), webLogLevel)})); changed.set(WEB_CONFIG, setIfPresent(parsedSettings, F("configPassword"), configPassword, notEmpty())); changed.set(SYSLOG, any({setIfPresent(parsedSettings, F("syslogLevel"), syslogLevel), setIfPresent(parsedSettings, F("syslogHost"), syslogHost), setIfPresent(parsedSettings, F("syslogPort"), syslogPort)})); if (fireCallbacks) { onConfigChange(changed); } } void Settings::reset() { if (SPIFFS.exists(SETTINGS_FILE)) { SPIFFS.remove(SETTINGS_FILE); } } <|endoftext|>
<commit_before>//===-- TargetData.cpp - Data size & alignment routines --------------------==// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines target properties related to datatype size/offset/alignment // information. // // This structure should be created once, filled in if the defaults are not // correct and then passed around by const&. None of the members functions // require modification to the object. // //===----------------------------------------------------------------------===// #include "llvm/Target/TargetData.h" #include "llvm/Module.h" #include "llvm/DerivedTypes.h" #include "llvm/Constants.h" #include "llvm/Support/GetElementPtrTypeIterator.h" using namespace llvm; // Handle the Pass registration stuff necessary to use TargetData's. namespace { // Register the default SparcV9 implementation... RegisterPass<TargetData> X("targetdata", "Target Data Layout"); } static inline void getTypeInfo(const Type *Ty, const TargetData *TD, uint64_t &Size, unsigned char &Alignment); //===----------------------------------------------------------------------===// // Support for StructLayout //===----------------------------------------------------------------------===// StructLayout::StructLayout(const StructType *ST, const TargetData &TD) { StructAlignment = 0; StructSize = 0; // Loop over each of the elements, placing them in memory... for (StructType::element_iterator TI = ST->element_begin(), TE = ST->element_end(); TI != TE; ++TI) { const Type *Ty = *TI; unsigned char A; unsigned TyAlign; uint64_t TySize; getTypeInfo(Ty, &TD, TySize, A); TyAlign = A; // Add padding if necessary to make the data element aligned properly... if (StructSize % TyAlign != 0) StructSize = (StructSize/TyAlign + 1) * TyAlign; // Add padding... // Keep track of maximum alignment constraint StructAlignment = std::max(TyAlign, StructAlignment); MemberOffsets.push_back(StructSize); StructSize += TySize; // Consume space for this data item } // Empty structures have alignment of 1 byte. if (StructAlignment == 0) StructAlignment = 1; // Add padding to the end of the struct so that it could be put in an array // and all array elements would be aligned correctly. if (StructSize % StructAlignment != 0) StructSize = (StructSize/StructAlignment + 1) * StructAlignment; } //===----------------------------------------------------------------------===// // TargetData Class Implementation //===----------------------------------------------------------------------===// TargetData::TargetData(const std::string &TargetName, bool isLittleEndian, unsigned char PtrSize, unsigned char PtrAl, unsigned char DoubleAl, unsigned char FloatAl, unsigned char LongAl, unsigned char IntAl, unsigned char ShortAl, unsigned char ByteAl, unsigned char BoolAl) { // If this assert triggers, a pass "required" TargetData information, but the // top level tool did not provide one for it. We do not want to default // construct, or else we might end up using a bad endianness or pointer size! // assert(!TargetName.empty() && "ERROR: Tool did not specify a target data to use!"); LittleEndian = isLittleEndian; PointerSize = PtrSize; PointerAlignment = PtrAl; DoubleAlignment = DoubleAl; FloatAlignment = FloatAl; LongAlignment = LongAl; IntAlignment = IntAl; ShortAlignment = ShortAl; ByteAlignment = ByteAl; BoolAlignment = BoolAl; } TargetData::TargetData(const std::string &ToolName, const Module *M) { LittleEndian = M->getEndianness() != Module::BigEndian; PointerSize = M->getPointerSize() != Module::Pointer64 ? 4 : 8; PointerAlignment = PointerSize; DoubleAlignment = PointerSize; FloatAlignment = 4; LongAlignment = 8; IntAlignment = 4; ShortAlignment = 2; ByteAlignment = 1; BoolAlignment = 1; } static std::map<std::pair<const TargetData*,const StructType*>, StructLayout> *Layouts = 0; TargetData::~TargetData() { if (Layouts) { // Remove any layouts for this TD. std::map<std::pair<const TargetData*, const StructType*>, StructLayout>::iterator I = Layouts->lower_bound(std::make_pair(this, (const StructType*)0)); while (I != Layouts->end() && I->first.first == this) Layouts->erase(I++); if (Layouts->empty()) { delete Layouts; Layouts = 0; } } } const StructLayout *TargetData::getStructLayout(const StructType *Ty) const { if (Layouts == 0) Layouts = new std::map<std::pair<const TargetData*,const StructType*>, StructLayout>(); std::map<std::pair<const TargetData*,const StructType*>, StructLayout>::iterator I = Layouts->lower_bound(std::make_pair(this, Ty)); if (I != Layouts->end() && I->first.first == this && I->first.second == Ty) return &I->second; else { return &Layouts->insert(I, std::make_pair(std::make_pair(this, Ty), StructLayout(Ty, *this)))->second; } } static inline void getTypeInfo(const Type *Ty, const TargetData *TD, uint64_t &Size, unsigned char &Alignment) { assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!"); switch (Ty->getTypeID()) { case Type::BoolTyID: Size = 1; Alignment = TD->getBoolAlignment(); return; case Type::VoidTyID: case Type::UByteTyID: case Type::SByteTyID: Size = 1; Alignment = TD->getByteAlignment(); return; case Type::UShortTyID: case Type::ShortTyID: Size = 2; Alignment = TD->getShortAlignment(); return; case Type::UIntTyID: case Type::IntTyID: Size = 4; Alignment = TD->getIntAlignment(); return; case Type::ULongTyID: case Type::LongTyID: Size = 8; Alignment = TD->getLongAlignment(); return; case Type::FloatTyID: Size = 4; Alignment = TD->getFloatAlignment(); return; case Type::DoubleTyID: Size = 8; Alignment = TD->getDoubleAlignment(); return; case Type::LabelTyID: case Type::PointerTyID: Size = TD->getPointerSize(); Alignment = TD->getPointerAlignment(); return; case Type::ArrayTyID: { const ArrayType *ATy = cast<ArrayType>(Ty); getTypeInfo(ATy->getElementType(), TD, Size, Alignment); unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment; Size = AlignedSize*ATy->getNumElements(); return; } case Type::StructTyID: { // Get the layout annotation... which is lazily created on demand. const StructLayout *Layout = TD->getStructLayout(cast<StructType>(Ty)); Size = Layout->StructSize; Alignment = Layout->StructAlignment; return; } default: assert(0 && "Bad type for getTypeInfo!!!"); return; } } uint64_t TargetData::getTypeSize(const Type *Ty) const { uint64_t Size; unsigned char Align; getTypeInfo(Ty, this, Size, Align); return Size; } unsigned char TargetData::getTypeAlignment(const Type *Ty) const { uint64_t Size; unsigned char Align; getTypeInfo(Ty, this, Size, Align); return Align; } /// getIntPtrType - Return an unsigned integer type that is the same size or /// greater to the host pointer size. const Type *TargetData::getIntPtrType() const { switch (getPointerSize()) { default: assert(0 && "Unknown pointer size!"); case 2: return Type::UShortTy; case 4: return Type::UIntTy; case 8: return Type::ULongTy; } } uint64_t TargetData::getIndexedOffset(const Type *ptrTy, const std::vector<Value*> &Idx) const { const Type *Ty = ptrTy; assert(isa<PointerType>(Ty) && "Illegal argument for getIndexedOffset()"); uint64_t Result = 0; generic_gep_type_iterator<std::vector<Value*>::const_iterator> TI = gep_type_begin(ptrTy, Idx.begin(), Idx.end()); for (unsigned CurIDX = 0; CurIDX != Idx.size(); ++CurIDX, ++TI) { if (const StructType *STy = dyn_cast<StructType>(*TI)) { assert(Idx[CurIDX]->getType() == Type::UIntTy && "Illegal struct idx"); unsigned FieldNo = cast<ConstantUInt>(Idx[CurIDX])->getValue(); // Get structure layout information... const StructLayout *Layout = getStructLayout(STy); // Add in the offset, as calculated by the structure layout info... assert(FieldNo < Layout->MemberOffsets.size() &&"FieldNo out of range!"); Result += Layout->MemberOffsets[FieldNo]; // Update Ty to refer to current element Ty = STy->getElementType(FieldNo); } else { // Update Ty to refer to current element Ty = cast<SequentialType>(Ty)->getElementType(); // Get the array index and the size of each array element. int64_t arrayIdx = cast<ConstantInt>(Idx[CurIDX])->getRawValue(); Result += arrayIdx * (int64_t)getTypeSize(Ty); } } return Result; } <commit_msg>Add a new helper method to get log2(type alignment)<commit_after>//===-- TargetData.cpp - Data size & alignment routines --------------------==// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines target properties related to datatype size/offset/alignment // information. // // This structure should be created once, filled in if the defaults are not // correct and then passed around by const&. None of the members functions // require modification to the object. // //===----------------------------------------------------------------------===// #include "llvm/Target/TargetData.h" #include "llvm/Module.h" #include "llvm/DerivedTypes.h" #include "llvm/Constants.h" #include "llvm/Support/GetElementPtrTypeIterator.h" #include "Support/MathExtras.h" using namespace llvm; // Handle the Pass registration stuff necessary to use TargetData's. namespace { // Register the default SparcV9 implementation... RegisterPass<TargetData> X("targetdata", "Target Data Layout"); } static inline void getTypeInfo(const Type *Ty, const TargetData *TD, uint64_t &Size, unsigned char &Alignment); //===----------------------------------------------------------------------===// // Support for StructLayout //===----------------------------------------------------------------------===// StructLayout::StructLayout(const StructType *ST, const TargetData &TD) { StructAlignment = 0; StructSize = 0; // Loop over each of the elements, placing them in memory... for (StructType::element_iterator TI = ST->element_begin(), TE = ST->element_end(); TI != TE; ++TI) { const Type *Ty = *TI; unsigned char A; unsigned TyAlign; uint64_t TySize; getTypeInfo(Ty, &TD, TySize, A); TyAlign = A; // Add padding if necessary to make the data element aligned properly... if (StructSize % TyAlign != 0) StructSize = (StructSize/TyAlign + 1) * TyAlign; // Add padding... // Keep track of maximum alignment constraint StructAlignment = std::max(TyAlign, StructAlignment); MemberOffsets.push_back(StructSize); StructSize += TySize; // Consume space for this data item } // Empty structures have alignment of 1 byte. if (StructAlignment == 0) StructAlignment = 1; // Add padding to the end of the struct so that it could be put in an array // and all array elements would be aligned correctly. if (StructSize % StructAlignment != 0) StructSize = (StructSize/StructAlignment + 1) * StructAlignment; } //===----------------------------------------------------------------------===// // TargetData Class Implementation //===----------------------------------------------------------------------===// TargetData::TargetData(const std::string &TargetName, bool isLittleEndian, unsigned char PtrSize, unsigned char PtrAl, unsigned char DoubleAl, unsigned char FloatAl, unsigned char LongAl, unsigned char IntAl, unsigned char ShortAl, unsigned char ByteAl, unsigned char BoolAl) { // If this assert triggers, a pass "required" TargetData information, but the // top level tool did not provide one for it. We do not want to default // construct, or else we might end up using a bad endianness or pointer size! // assert(!TargetName.empty() && "ERROR: Tool did not specify a target data to use!"); LittleEndian = isLittleEndian; PointerSize = PtrSize; PointerAlignment = PtrAl; DoubleAlignment = DoubleAl; FloatAlignment = FloatAl; LongAlignment = LongAl; IntAlignment = IntAl; ShortAlignment = ShortAl; ByteAlignment = ByteAl; BoolAlignment = BoolAl; } TargetData::TargetData(const std::string &ToolName, const Module *M) { LittleEndian = M->getEndianness() != Module::BigEndian; PointerSize = M->getPointerSize() != Module::Pointer64 ? 4 : 8; PointerAlignment = PointerSize; DoubleAlignment = PointerSize; FloatAlignment = 4; LongAlignment = 8; IntAlignment = 4; ShortAlignment = 2; ByteAlignment = 1; BoolAlignment = 1; } static std::map<std::pair<const TargetData*,const StructType*>, StructLayout> *Layouts = 0; TargetData::~TargetData() { if (Layouts) { // Remove any layouts for this TD. std::map<std::pair<const TargetData*, const StructType*>, StructLayout>::iterator I = Layouts->lower_bound(std::make_pair(this, (const StructType*)0)); while (I != Layouts->end() && I->first.first == this) Layouts->erase(I++); if (Layouts->empty()) { delete Layouts; Layouts = 0; } } } const StructLayout *TargetData::getStructLayout(const StructType *Ty) const { if (Layouts == 0) Layouts = new std::map<std::pair<const TargetData*,const StructType*>, StructLayout>(); std::map<std::pair<const TargetData*,const StructType*>, StructLayout>::iterator I = Layouts->lower_bound(std::make_pair(this, Ty)); if (I != Layouts->end() && I->first.first == this && I->first.second == Ty) return &I->second; else { return &Layouts->insert(I, std::make_pair(std::make_pair(this, Ty), StructLayout(Ty, *this)))->second; } } static inline void getTypeInfo(const Type *Ty, const TargetData *TD, uint64_t &Size, unsigned char &Alignment) { assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!"); switch (Ty->getTypeID()) { case Type::BoolTyID: Size = 1; Alignment = TD->getBoolAlignment(); return; case Type::VoidTyID: case Type::UByteTyID: case Type::SByteTyID: Size = 1; Alignment = TD->getByteAlignment(); return; case Type::UShortTyID: case Type::ShortTyID: Size = 2; Alignment = TD->getShortAlignment(); return; case Type::UIntTyID: case Type::IntTyID: Size = 4; Alignment = TD->getIntAlignment(); return; case Type::ULongTyID: case Type::LongTyID: Size = 8; Alignment = TD->getLongAlignment(); return; case Type::FloatTyID: Size = 4; Alignment = TD->getFloatAlignment(); return; case Type::DoubleTyID: Size = 8; Alignment = TD->getDoubleAlignment(); return; case Type::LabelTyID: case Type::PointerTyID: Size = TD->getPointerSize(); Alignment = TD->getPointerAlignment(); return; case Type::ArrayTyID: { const ArrayType *ATy = cast<ArrayType>(Ty); getTypeInfo(ATy->getElementType(), TD, Size, Alignment); unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment; Size = AlignedSize*ATy->getNumElements(); return; } case Type::StructTyID: { // Get the layout annotation... which is lazily created on demand. const StructLayout *Layout = TD->getStructLayout(cast<StructType>(Ty)); Size = Layout->StructSize; Alignment = Layout->StructAlignment; return; } default: assert(0 && "Bad type for getTypeInfo!!!"); return; } } uint64_t TargetData::getTypeSize(const Type *Ty) const { uint64_t Size; unsigned char Align; getTypeInfo(Ty, this, Size, Align); return Size; } unsigned char TargetData::getTypeAlignment(const Type *Ty) const { uint64_t Size; unsigned char Align; getTypeInfo(Ty, this, Size, Align); return Align; } unsigned char TargetData::getTypeAlignmentShift(const Type *Ty) const { unsigned Align = getTypeAlignment(Ty); assert(!(Align & (Align-1)) && "Alignment is not a power of two!"); return log2(Align); } /// getIntPtrType - Return an unsigned integer type that is the same size or /// greater to the host pointer size. const Type *TargetData::getIntPtrType() const { switch (getPointerSize()) { default: assert(0 && "Unknown pointer size!"); case 2: return Type::UShortTy; case 4: return Type::UIntTy; case 8: return Type::ULongTy; } } uint64_t TargetData::getIndexedOffset(const Type *ptrTy, const std::vector<Value*> &Idx) const { const Type *Ty = ptrTy; assert(isa<PointerType>(Ty) && "Illegal argument for getIndexedOffset()"); uint64_t Result = 0; generic_gep_type_iterator<std::vector<Value*>::const_iterator> TI = gep_type_begin(ptrTy, Idx.begin(), Idx.end()); for (unsigned CurIDX = 0; CurIDX != Idx.size(); ++CurIDX, ++TI) { if (const StructType *STy = dyn_cast<StructType>(*TI)) { assert(Idx[CurIDX]->getType() == Type::UIntTy && "Illegal struct idx"); unsigned FieldNo = cast<ConstantUInt>(Idx[CurIDX])->getValue(); // Get structure layout information... const StructLayout *Layout = getStructLayout(STy); // Add in the offset, as calculated by the structure layout info... assert(FieldNo < Layout->MemberOffsets.size() &&"FieldNo out of range!"); Result += Layout->MemberOffsets[FieldNo]; // Update Ty to refer to current element Ty = STy->getElementType(FieldNo); } else { // Update Ty to refer to current element Ty = cast<SequentialType>(Ty)->getElementType(); // Get the array index and the size of each array element. int64_t arrayIdx = cast<ConstantInt>(Idx[CurIDX])->getRawValue(); Result += arrayIdx * (int64_t)getTypeSize(Ty); } } return Result; } <|endoftext|>
<commit_before>#include <string> #include <iostream> #include "Player.h" #include "Monster.h" #include "Skill.h" #include "Combat.h" //generate a Combat handler with the given Player and Monster Combat::Combat(Player *currentplayer, Monster *currentmonster) { _player = currentplayer; _monster = currentmonster; _turn = true; } Combat::~Combat() { } /** Player turn options are received with cin Users can choose several options from attacking to passing the turn */ void Combat::playerTurn(std::ostream& ostr) { std::string action = ""; ostr << "Player Turn!" << std::endl; ostr << "What will you do?" << std::endl << "Show info [u]" << std::endl << "Use skill [i]" << std::endl << "Procrastinate [o]" << std::endl << "Pass turn [p]" << std::endl; while (true) { std::cin >> action; if (action == "u") { ostr << _player->getNonBasicInfo(ostr); } else if (action == "i") { std::string skillChoice; int skillIndex; //loop until the player enters a valid skill name that they possess while (true) { ostr << "What skill (type the name of one of your skills)?" << std::endl; std::getline(std::cin, skillChoice); std::cout << skillChoice << std::endl; skillIndex = _player->skillIndex(skillChoice); if (skillIndex != -1) { break; } } int damage = _player->useSkill(skillIndex); _monster->updateStamina(-damage); if (_monster->getStamina() <= 0) { break; } } else if (action == "o") { ostr << "Took a break :)" << std::endl; } else if (action == "p"){ ostr << "Giving up???" << std::endl; break; } else { ostr << "What?" << std::endl; continue; } } return; } /** Monster turns are managed by the game as weighted random selection of skills Monster objects cannot use Item */ void Combat::monsterTurn(std::ostream& ostr) { ostr << "Monster Turn!" << std::endl; } /** Engage combat function called by Dungeon when the Player chooses to fight Alternates turns for Player and Monster calling the respective turn function Returns true when the Player wins and false if the Monster wins */ bool Combat::engageCombat(std::ostream& ostr) { while ((_player->getStamina() > 0) && (_monster->getStamina() > 0)) { if (_turn) { ostr << "hi!" << std::endl; playerTurn(ostr); if (_monster->getStamina() <= 0) { ostr << "You won the fight!" << std::endl; return true; } _turn = false; } else { monsterTurn(ostr); _turn = true; } } ostr << "You lost the fight :(, you will suffer a grade penalty for this!" << std::endl; return false; } void Combat::setMonster(Monster* newMonster){ _monster = newMonster; } <commit_msg>added quit option to skill name selection<commit_after>#include <string> #include <iostream> #include "Player.h" #include "Monster.h" #include "Skill.h" #include "Combat.h" //generate a Combat handler with the given Player and Monster Combat::Combat(Player *currentplayer, Monster *currentmonster) { _player = currentplayer; _monster = currentmonster; _turn = true; } Combat::~Combat() { } /** Player turn options are received with cin Users can choose several options from attacking to passing the turn */ void Combat::playerTurn(std::ostream& ostr) { std::string action = ""; ostr << "Player Turn!" << std::endl; ostr << "What will you do?" << std::endl << "Show info [u]" << std::endl << "Use skill [i]" << std::endl << "Procrastinate [o]" << std::endl << "Pass turn [p]" << std::endl; while (true) { std::cin >> action; if (action == "u") { ostr << _player->getNonBasicInfo(ostr); } else if (action == "i") { std::string skillChoice; int skillIndex = -1; //loop until the player enters a valid skill name that they possess while (true) { ostr << "What skill (type the name of one of your skills, or q to cancel)?" << std::endl; std::getline(std::cin, skillChoice); if (skillChoice == "q" || skillChoice == "quit") { break; } skillIndex = _player->skillIndex(skillChoice); if (skillIndex != -1) { break; } } //if we opted to exit the skill selection menu (indicated by invalid skill selection) return to option select if (skillIndex == -1) { break; } int damage = _player->useSkill(skillIndex); _monster->updateStamina(-damage); if (_monster->getStamina() <= 0) { break; } } else if (action == "o") { ostr << "Took a break :)" << std::endl; } else if (action == "p"){ ostr << "Giving up???" << std::endl; break; } else { ostr << "What?" << std::endl; continue; } } return; } /** Monster turns are managed by the game as weighted random selection of skills Monster objects cannot use Item */ void Combat::monsterTurn(std::ostream& ostr) { ostr << "Monster Turn!" << std::endl; } /** Engage combat function called by Dungeon when the Player chooses to fight Alternates turns for Player and Monster calling the respective turn function Returns true when the Player wins and false if the Monster wins */ bool Combat::engageCombat(std::ostream& ostr) { while ((_player->getStamina() > 0) && (_monster->getStamina() > 0)) { if (_turn) { ostr << "hi!" << std::endl; playerTurn(ostr); if (_monster->getStamina() <= 0) { ostr << "You won the fight!" << std::endl; return true; } _turn = false; } else { monsterTurn(ostr); _turn = true; } } ostr << "You lost the fight :(, you will suffer a grade penalty for this!" << std::endl; return false; } void Combat::setMonster(Monster* newMonster){ _monster = newMonster; } <|endoftext|>
<commit_before>// // Created by David Li on 6/5/17. // #include "hlt.hpp" namespace hlt { EntityId::EntityId() { type = EntityType::InvalidEntity; _player_id = -1; _entity_index = -1; } auto EntityId::is_valid() const -> bool { return type != EntityType::InvalidEntity && _player_id >= -1 && _entity_index >= 0; } auto EntityId::invalid() -> EntityId { return EntityId(); } auto EntityId::player_id() const -> PlayerId { return static_cast<PlayerId>(_player_id); } auto EntityId::entity_index() const -> EntityIndex { return static_cast<EntityIndex>(_entity_index); } auto EntityId::for_planet(EntityIndex index) -> EntityId { auto result = EntityId(); result.type = EntityType::PlanetEntity; result._entity_index = static_cast<int>(index); return result; } auto EntityId::for_ship(PlayerId player_id, EntityIndex index) -> EntityId { auto result = EntityId(); result.type = EntityType::ShipEntity; result._player_id = player_id; result._entity_index = static_cast<int>(index); return result; } Map::Map() { map_width = 0; map_height = 0; ships = { {} }; planets = std::vector<Planet>(); } Map::Map(const Map& otherMap) { map_width = otherMap.map_width; map_height = otherMap.map_height; ships = otherMap.ships; planets = otherMap.planets; } Map::Map(unsigned short width, unsigned short height, unsigned char numberOfPlayers, unsigned int seed) : Map() { // TODO: enforce a minimum map size to make sure we always have room for planets //Pseudorandom number generator. std::mt19937 prg(seed); std::uniform_int_distribution<unsigned short> uidw(0, width - 1); std::uniform_int_distribution<unsigned short> uidh(0, height - 1); std::uniform_int_distribution<unsigned short> uidr(1, std::min(width, height) / 25); const auto rand_width = [&]() -> unsigned short { return uidw(prg); }; const auto rand_height = [&]() -> unsigned short { return uidh(prg); }; const auto rand_radius = [&]() -> unsigned short { return uidr(prg); }; //Decides whether to put more players along the horizontal or the vertical. bool preferHorizontal = prg() % 2 == 0; int dw, dh; //Find number closest to square that makes the match symmetric. if (preferHorizontal) { dh = (int) sqrt(numberOfPlayers); while (numberOfPlayers % dh != 0) dh--; dw = numberOfPlayers / dh; } else { dw = (int) sqrt(numberOfPlayers); while (numberOfPlayers % dw != 0) dw--; dh = numberOfPlayers / dw; } //Figure out chunk width and height accordingly. //Matches width and height as closely as it can, but is not guaranteed to match exactly. //It is guaranteed to be smaller if not the same size, however. int cw = 5 * width / dw; int ch = 5 * height / dh; map_width = (unsigned short) (cw * dw); map_height = (unsigned short) (ch * dh); // Divide the map into regions for each player class Region { public: unsigned short width; unsigned short height; unsigned short x; unsigned short y; Region(unsigned short _x, unsigned short _y, unsigned short _width, unsigned short _height) { this->x = _x; this->y = _y; this->width = _width; this->height = _height; } }; std::vector<Region> regions = std::vector<Region>(); regions.reserve(numberOfPlayers); for (int row = 0; row < dh; row++) { for (int col = 0; col < dw; col++) { regions.push_back(Region(col * cw, row * ch, cw, ch)); } } // Center the player's starting ships in each region for (PlayerId playerId = 0; playerId < numberOfPlayers; playerId++) { const auto& region = regions.at(playerId); for (int i = 0; i < 3; i++) { ships[playerId][i].health = Ship::BASE_HEALTH; const auto x = static_cast<unsigned short>(region.x + (region.width / 2)); const auto y = static_cast<unsigned short>(region.y + (region.height / 2) - 1 + i); ships[playerId][i].location.pos_x = x; ships[playerId][i].location.pos_y = y; } planets.push_back(Planet(region.x + (region.width / 2) + 2, region.y + (region.height / 2), 1)); } // Scatter planets throughout all of space, avoiding the starting ships (centers of regions) const auto MAX_PLANETS = numberOfPlayers * 2; const auto MAX_TRIES = 100; const auto MIN_DISTANCE = 5; for (int i = 0; i < MAX_PLANETS; i++) { for (int j = 0; j < MAX_TRIES; j++) { const auto x = rand_width(); const auto y = rand_height(); const auto r = rand_radius(); // Make sure planets are far enough away from the center // of each region, where initial ships spawn for (Region region : regions) { if (get_distance({ region.x, region.y }, { x, y }) < r + MIN_DISTANCE) { goto TRY_AGAIN; } } for (Planet planet : planets) { if (get_distance(planet.location, { x, y }) < r + planet.radius + 1) { goto TRY_AGAIN; } } planets.push_back(Planet(x, y, r)); goto NEXT_PLANET; TRY_AGAIN:; } NEXT_PLANET:; } std::cout << map_width << " " << map_height << std::endl; } auto Map::get_ship(PlayerId player, EntityIndex entity) -> Ship& { return ships.at(player).at(entity); } auto Map::get_ship(EntityId entity_id) -> Ship& { assert(entity_id.is_valid()); assert(entity_id.type == EntityType::ShipEntity); return get_ship(entity_id.player_id(), entity_id.entity_index()); } auto Map::get_planet(EntityId entity_id) -> Planet& { assert(entity_id.is_valid()); assert(entity_id.type == EntityType::PlanetEntity); assert(entity_id.entity_index() < planets.size()); return planets[entity_id.entity_index()]; } auto Map::get_entity(EntityId entity_id) -> Entity& { switch (entity_id.type) { case EntityType::InvalidEntity: throw std::string("Can't get entity from invalid ID"); case EntityType::PlanetEntity: return get_planet(entity_id); case EntityType::ShipEntity: return get_ship(entity_id); } } auto Map::get_distance(Location l1, Location l2) const -> float { short dx = l1.pos_x - l2.pos_x; short dy = l1.pos_y - l2.pos_y; return sqrtf((dx * dx) + (dy * dy)); } auto Map::get_angle(Location l1, Location l2) const -> float { short dx = l2.pos_x - l1.pos_x; short dy = l2.pos_y - l1.pos_y; return atan2f(dy, dx); } } <commit_msg>Improve planet distribution in map generation<commit_after>// // Created by David Li on 6/5/17. // #include "hlt.hpp" namespace hlt { EntityId::EntityId() { type = EntityType::InvalidEntity; _player_id = -1; _entity_index = -1; } auto EntityId::is_valid() const -> bool { return type != EntityType::InvalidEntity && _player_id >= -1 && _entity_index >= 0; } auto EntityId::invalid() -> EntityId { return EntityId(); } auto EntityId::player_id() const -> PlayerId { return static_cast<PlayerId>(_player_id); } auto EntityId::entity_index() const -> EntityIndex { return static_cast<EntityIndex>(_entity_index); } auto EntityId::for_planet(EntityIndex index) -> EntityId { auto result = EntityId(); result.type = EntityType::PlanetEntity; result._entity_index = static_cast<int>(index); return result; } auto EntityId::for_ship(PlayerId player_id, EntityIndex index) -> EntityId { auto result = EntityId(); result.type = EntityType::ShipEntity; result._player_id = player_id; result._entity_index = static_cast<int>(index); return result; } Map::Map() { map_width = 0; map_height = 0; ships = { {} }; planets = std::vector<Planet>(); } Map::Map(const Map& otherMap) { map_width = otherMap.map_width; map_height = otherMap.map_height; ships = otherMap.ships; planets = otherMap.planets; } Map::Map(unsigned short width, unsigned short height, unsigned char numberOfPlayers, unsigned int seed) : Map() { // TODO: enforce a minimum map size to make sure we always have room for planets //Pseudorandom number generator. std::mt19937 prg(seed); //Decides whether to put more players along the horizontal or the vertical. bool preferHorizontal = prg() % 2 == 0; int dw, dh; //Find number closest to square that makes the match symmetric. if (preferHorizontal) { dh = (int) sqrt(numberOfPlayers); while (numberOfPlayers % dh != 0) dh--; dw = numberOfPlayers / dh; } else { dw = (int) sqrt(numberOfPlayers); while (numberOfPlayers % dw != 0) dw--; dh = numberOfPlayers / dw; } //Figure out chunk width and height accordingly. //Matches width and height as closely as it can, but is not guaranteed to match exactly. //It is guaranteed to be smaller if not the same size, however. int cw = 5 * width / dw; int ch = 5 * height / dh; map_width = (unsigned short) (cw * dw); map_height = (unsigned short) (ch * dh); std::uniform_int_distribution<unsigned short> uidw(0, map_width - 1); std::uniform_int_distribution<unsigned short> uidh(0, map_height - 1); std::uniform_int_distribution<unsigned short> uidr(1, std::min(map_width, map_height) / 25); const auto rand_width = [&]() -> unsigned short { return uidw(prg); }; const auto rand_height = [&]() -> unsigned short { return uidh(prg); }; const auto rand_radius = [&]() -> unsigned short { return uidr(prg); }; // Divide the map into regions for each player class Region { public: unsigned short width; unsigned short height; unsigned short x; unsigned short y; Region(unsigned short _x, unsigned short _y, unsigned short _width, unsigned short _height) { this->x = _x; this->y = _y; this->width = _width; this->height = _height; } auto center_x() const -> unsigned short { return static_cast<unsigned short>(x + (width / 2)); } auto center_y() const -> unsigned short { return static_cast<unsigned short>(y + (height / 2)); } }; std::vector<Region> regions = std::vector<Region>(); regions.reserve(numberOfPlayers); for (int row = 0; row < dh; row++) { for (int col = 0; col < dw; col++) { regions.push_back(Region(col * cw, row * ch, cw, ch)); } } // Center the player's starting ships in each region for (PlayerId playerId = 0; playerId < numberOfPlayers; playerId++) { const auto& region = regions.at(playerId); for (int i = 0; i < 3; i++) { ships[playerId][i].health = Ship::BASE_HEALTH; ships[playerId][i].location.pos_x = region.center_x(); ships[playerId][i].location.pos_y = region.center_y() - 1 + i; } } // Scatter planets throughout all of space, avoiding the starting ships (centers of regions) const auto MAX_PLANETS = numberOfPlayers * 2; const auto MAX_TRIES = 100; const auto MIN_DISTANCE = 5; for (int i = 0; i < MAX_PLANETS; i++) { for (int j = 0; j < MAX_TRIES; j++) { const auto x = rand_width(); const auto y = rand_height(); const auto r = rand_radius(); // Make sure planets are far enough away from the center // of each region, where initial ships spawn for (Region region : regions) { if (get_distance({ region.center_x(), region.center_y() }, { x, y }) < r + MIN_DISTANCE) { goto TRY_AGAIN; } } for (Planet planet : planets) { if (get_distance(planet.location, { x, y }) < r + planet.radius + 1) { goto TRY_AGAIN; } } planets.push_back(Planet(x, y, r)); goto NEXT_PLANET; TRY_AGAIN:; } NEXT_PLANET:; } std::cout << map_width << " " << map_height << std::endl; } auto Map::get_ship(PlayerId player, EntityIndex entity) -> Ship& { return ships.at(player).at(entity); } auto Map::get_ship(EntityId entity_id) -> Ship& { assert(entity_id.is_valid()); assert(entity_id.type == EntityType::ShipEntity); return get_ship(entity_id.player_id(), entity_id.entity_index()); } auto Map::get_planet(EntityId entity_id) -> Planet& { assert(entity_id.is_valid()); assert(entity_id.type == EntityType::PlanetEntity); assert(entity_id.entity_index() < planets.size()); return planets[entity_id.entity_index()]; } auto Map::get_entity(EntityId entity_id) -> Entity& { switch (entity_id.type) { case EntityType::InvalidEntity: throw std::string("Can't get entity from invalid ID"); case EntityType::PlanetEntity: return get_planet(entity_id); case EntityType::ShipEntity: return get_ship(entity_id); } } auto Map::get_distance(Location l1, Location l2) const -> float { short dx = l1.pos_x - l2.pos_x; short dy = l1.pos_y - l2.pos_y; return sqrtf((dx * dx) + (dy * dy)); } auto Map::get_angle(Location l1, Location l2) const -> float { short dx = l2.pos_x - l1.pos_x; short dy = l2.pos_y - l1.pos_y; return atan2f(dy, dx); } } <|endoftext|>
<commit_before>//===--- License.cpp - License Related Functionality ---===// // // 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 relating to the license of the application. // //===----------------------------------------------------------------------===// #include <iostream> #include "License.h" namespace License { void display() { std::cout << "display license information" << std::endl; } } <commit_msg>Displaying the actual license notification.<commit_after>//===--- License.cpp - License Related Functionality ---===// // // 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 relating to the license of the application. // //===----------------------------------------------------------------------===// #include <iostream> #include "License.h" #include "Printing.h" namespace License { void display() { Printing::printLines({ "You may distribute/use this application only in accordance with the GNU Affero General", "Public License, version 3.0." }); } } <|endoftext|>
<commit_before>// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #include "verilator_sim_ctrl.h" #include <getopt.h> #include <sys/stat.h> #include <unistd.h> #include <vltstd/svdpi.h> #include <iostream> // This is defined by Verilator and passed through the command line #ifndef VM_TRACE #define VM_TRACE 0 #endif // DPI Exports extern "C" { extern void simutil_verilator_memload(const char *file); } VerilatorSimCtrl::VerilatorSimCtrl(VerilatedToplevel *top, CData &sig_clk, CData &sig_rst, VerilatorSimCtrlFlags flags) : top_(top), sig_clk_(sig_clk), sig_rst_(sig_rst), flags_(flags), time_(0), init_rom_(false), init_ram_(false), init_flash_(false), tracing_enabled_(false), tracing_enabled_changed_(false), tracing_ever_enabled_(false), tracing_possible_(VM_TRACE), initial_reset_delay_cycles_(2), reset_duration_cycles_(2), request_stop_(false), tracer_(VerilatedTracer()), term_after_cycles_(0) {} void VerilatorSimCtrl::RequestStop() { request_stop_ = true; } bool VerilatorSimCtrl::TraceOn() { bool old_tracing_enabled = tracing_enabled_; tracing_enabled_ = tracing_possible_; tracing_ever_enabled_ = tracing_enabled_; if (old_tracing_enabled != tracing_enabled_) { tracing_enabled_changed_ = true; } return tracing_enabled_; } bool VerilatorSimCtrl::TraceOff() { if (tracing_enabled_) { tracing_enabled_changed_ = true; } tracing_enabled_ = false; return tracing_enabled_; } void VerilatorSimCtrl::PrintHelp() const { std::cout << "Execute a simulation model for " << top_->name() << "\n" "\n"; if (tracing_possible_) { std::cout << "-t|--trace Write a trace file from the start\n"; } std::cout << "-r|--rominit=VMEMFILE Initialize the ROM with VMEMFILE\n" "-m|--raminit=VMEMFILE Initialize the RAM with VMEMFILE\n" "-f|--flashinit=VMEMFILE Initialize the FLASH with VMEMFILE\n" "-h|--help Show help\n" "\n" "All further arguments are passed to the design and can be used " "in the \n" "design, e.g. by DPI modules.\n"; } void VerilatorSimCtrl::InitRom(std::string rom) { if (!init_rom_) { return; } svScope scope; scope = svGetScopeFromName(rom.data()); if (!scope) { std::cerr << "ERROR: No ROM found at " << rom << std::endl; exit(1); } svSetScope(scope); simutil_verilator_memload(rom_init_file_.data()); std::cout << std::endl << "Rom initialized with program at " << rom_init_file_ << std::endl; } void VerilatorSimCtrl::InitRam(std::string ram) { if (!init_ram_) { return; } svScope scope; scope = svGetScopeFromName(ram.data()); if (!scope) { std::cerr << "ERROR: No RAM found at " << ram << std::endl; exit(1); } svSetScope(scope); simutil_verilator_memload(ram_init_file_.data()); std::cout << std::endl << "Ram initialized with program at " << ram_init_file_ << std::endl; } void VerilatorSimCtrl::InitFlash(std::string flash) { if (!init_flash_) { return; } svScope scope; scope = svGetScopeFromName(flash.data()); if (!scope) { std::cerr << "ERROR: No FLASH found at " << flash << std::endl; exit(1); } svSetScope(scope); simutil_verilator_memload(flash_init_file_.data()); std::cout << std::endl << "Flash initialized with program at " << flash_init_file_ << std::endl; } bool VerilatorSimCtrl::ParseCommandArgs(int argc, char **argv, int &retcode) { const struct option long_options[] = { {"rominit", required_argument, nullptr, 'r'}, {"raminit", required_argument, nullptr, 'm'}, {"flashinit", required_argument, nullptr, 'f'}, {"term-after-cycles", required_argument, nullptr, 'c'}, {"trace", no_argument, nullptr, 't'}, {"help", no_argument, nullptr, 'h'}, {nullptr, no_argument, nullptr, 0}}; while (1) { int c = getopt_long(argc, argv, ":r:m:f:th", long_options, nullptr); if (c == -1) { break; } // Disable error reporting by getopt opterr = 0; switch (c) { case 0: break; case 'r': rom_init_file_ = optarg; init_rom_ = true; if (!IsFileReadable(rom_init_file_)) { std::cerr << "ERROR: ROM initialization file " << "'" << rom_init_file_ << "'" << " is not readable." << std::endl; return false; } break; case 'm': ram_init_file_ = optarg; init_ram_ = true; if (!IsFileReadable(ram_init_file_)) { std::cerr << "ERROR: Memory initialization file " << "'" << ram_init_file_ << "'" << " is not readable." << std::endl; return false; } break; case 'f': flash_init_file_ = optarg; init_flash_ = true; if (!IsFileReadable(flash_init_file_)) { std::cerr << "ERROR: FLASH initialization file " << "'" << flash_init_file_ << "'" << " is not readable." << std::endl; return false; } break; case 't': if (!tracing_possible_) { std::cerr << "ERROR: Tracing has not been enabled at compile time." << std::endl; return false; } TraceOn(); break; case 'c': term_after_cycles_ = atoi(optarg); break; case 'h': PrintHelp(); return false; case ':': // missing argument std::cerr << "ERROR: Missing argument." << std::endl; PrintHelp(); return false; case '?': default:; // Ignore unrecognized options since they might be consumed by // Verilator's built-in parsing below. } } Verilated::commandArgs(argc, argv); return true; } void VerilatorSimCtrl::Trace() { // We cannot output a message when calling TraceOn()/TraceOff() as these // functions can be called from a signal handler. Instead we print the message // here from the main loop. if (tracing_enabled_changed_) { if (TracingEnabled()) { std::cout << "Tracing enabled." << std::endl; } else { std::cout << "Tracing disabled." << std::endl; } tracing_enabled_changed_ = false; } if (!TracingEnabled()) { return; } if (!tracer_.isOpen()) { tracer_.open(GetSimulationFileName()); std::cout << "Writing simulation traces to " << GetSimulationFileName() << std::endl; } tracer_.dump(GetTime()); } const char *VerilatorSimCtrl::GetSimulationFileName() const { #ifdef VM_TRACE_FMT_FST return "sim.fst"; #else return "sim.vcd"; #endif } void VerilatorSimCtrl::Run() { // We always need to enable this as tracing can be enabled at runtime if (tracing_possible_) { Verilated::traceEverOn(true); top_->trace(tracer_, 99, 0); } // Evaluate all initial blocks, including the DPI setup routines top_->eval(); std::cout << std::endl << "Simulation running, end by pressing CTRL-c." << std::endl; time_begin_ = std::chrono::steady_clock::now(); UnsetReset(); Trace(); while (1) { if (time_ >= initial_reset_delay_cycles_ * 2) { SetReset(); } if (time_ >= reset_duration_cycles_ * 2 + initial_reset_delay_cycles_ * 2) { UnsetReset(); } sig_clk_ = !sig_clk_; top_->eval(); time_++; Trace(); if (request_stop_) { std::cout << "Received stop request, shutting down simulation." << std::endl; break; } if (Verilated::gotFinish()) { std::cout << "Received $finish() from Verilog, shutting down simulation." << std::endl; break; } if (term_after_cycles_ && time_ > term_after_cycles_) { std::cout << "Simulation timeout of " << term_after_cycles_ << " cycles reached, shutting down simulation." << std::endl; break; } } top_->final(); time_end_ = std::chrono::steady_clock::now(); if (TracingEverEnabled()) { tracer_.close(); } } void VerilatorSimCtrl::SetReset() { if (flags_ & ResetPolarityNegative) { sig_rst_ = 0; } else { sig_rst_ = 1; } } void VerilatorSimCtrl::UnsetReset() { if (flags_ & ResetPolarityNegative) { sig_rst_ = 1; } else { sig_rst_ = 0; } } void VerilatorSimCtrl::SetInitialResetDelay(unsigned int cycles) { initial_reset_delay_cycles_ = cycles; } void VerilatorSimCtrl::SetResetDuration(unsigned int cycles) { reset_duration_cycles_ = cycles; } bool VerilatorSimCtrl::IsFileReadable(std::string filepath) { struct stat statbuf; return stat(filepath.data(), &statbuf) == 0; } bool VerilatorSimCtrl::FileSize(std::string filepath, int &size_byte) { struct stat statbuf; if (stat(filepath.data(), &statbuf) != 0) { size_byte = 0; return false; } size_byte = statbuf.st_size; return true; } unsigned int VerilatorSimCtrl::GetExecutionTimeMs() { return std::chrono::duration_cast<std::chrono::milliseconds>(time_end_ - time_begin_) .count(); } void VerilatorSimCtrl::PrintStatistics() { double speed_hz = time_ / 2 / (GetExecutionTimeMs() / 1000.0); double speed_khz = speed_hz / 1000.0; std::cout << std::endl << "Simulation statistics" << std::endl << "=====================" << std::endl << "Executed cycles: " << time_ / 2 << std::endl << "Wallclock time: " << GetExecutionTimeMs() / 1000.0 << " s" << std::endl << "Simulation speed: " << speed_hz << " cycles/s " << "(" << speed_khz << " kHz)" << std::endl; int trace_size_byte; if (tracing_enabled_ && FileSize(GetSimulationFileName(), trace_size_byte)) { std::cout << "Trace file size: " << trace_size_byte << " B" << std::endl; } } <commit_msg>[DV] Update simulation terminate argument<commit_after>// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #include "verilator_sim_ctrl.h" #include <getopt.h> #include <sys/stat.h> #include <unistd.h> #include <vltstd/svdpi.h> #include <iostream> // This is defined by Verilator and passed through the command line #ifndef VM_TRACE #define VM_TRACE 0 #endif // DPI Exports extern "C" { extern void simutil_verilator_memload(const char *file); } VerilatorSimCtrl::VerilatorSimCtrl(VerilatedToplevel *top, CData &sig_clk, CData &sig_rst, VerilatorSimCtrlFlags flags) : top_(top), sig_clk_(sig_clk), sig_rst_(sig_rst), flags_(flags), time_(0), init_rom_(false), init_ram_(false), init_flash_(false), tracing_enabled_(false), tracing_enabled_changed_(false), tracing_ever_enabled_(false), tracing_possible_(VM_TRACE), initial_reset_delay_cycles_(2), reset_duration_cycles_(2), request_stop_(false), tracer_(VerilatedTracer()), term_after_cycles_(0) {} void VerilatorSimCtrl::RequestStop() { request_stop_ = true; } bool VerilatorSimCtrl::TraceOn() { bool old_tracing_enabled = tracing_enabled_; tracing_enabled_ = tracing_possible_; tracing_ever_enabled_ = tracing_enabled_; if (old_tracing_enabled != tracing_enabled_) { tracing_enabled_changed_ = true; } return tracing_enabled_; } bool VerilatorSimCtrl::TraceOff() { if (tracing_enabled_) { tracing_enabled_changed_ = true; } tracing_enabled_ = false; return tracing_enabled_; } void VerilatorSimCtrl::PrintHelp() const { std::cout << "Execute a simulation model for " << top_->name() << "\n" "\n"; if (tracing_possible_) { std::cout << "-t|--trace Write trace file from the start\n"; } std::cout << "-r|--rominit=VMEMFILE Initialize the ROM with VMEMFILE\n" "-m|--raminit=VMEMFILE Initialize the RAM with VMEMFILE\n" "-f|--flashinit=VMEMFILE Initialize the FLASH with VMEMFILE\n" "-c|--term-after-cycles=N Terminate simulation after N cycles\n" "-h|--help Show help\n" "\n" "All further arguments are passed to the design and can be used " "in the \n" "design, e.g. by DPI modules.\n"; } void VerilatorSimCtrl::InitRom(std::string rom) { if (!init_rom_) { return; } svScope scope; scope = svGetScopeFromName(rom.data()); if (!scope) { std::cerr << "ERROR: No ROM found at " << rom << std::endl; exit(1); } svSetScope(scope); simutil_verilator_memload(rom_init_file_.data()); std::cout << std::endl << "Rom initialized with program at " << rom_init_file_ << std::endl; } void VerilatorSimCtrl::InitRam(std::string ram) { if (!init_ram_) { return; } svScope scope; scope = svGetScopeFromName(ram.data()); if (!scope) { std::cerr << "ERROR: No RAM found at " << ram << std::endl; exit(1); } svSetScope(scope); simutil_verilator_memload(ram_init_file_.data()); std::cout << std::endl << "Ram initialized with program at " << ram_init_file_ << std::endl; } void VerilatorSimCtrl::InitFlash(std::string flash) { if (!init_flash_) { return; } svScope scope; scope = svGetScopeFromName(flash.data()); if (!scope) { std::cerr << "ERROR: No FLASH found at " << flash << std::endl; exit(1); } svSetScope(scope); simutil_verilator_memload(flash_init_file_.data()); std::cout << std::endl << "Flash initialized with program at " << flash_init_file_ << std::endl; } bool VerilatorSimCtrl::ParseCommandArgs(int argc, char **argv, int &retcode) { const struct option long_options[] = { {"rominit", required_argument, nullptr, 'r'}, {"raminit", required_argument, nullptr, 'm'}, {"flashinit", required_argument, nullptr, 'f'}, {"term-after-cycles", required_argument, nullptr, 'c'}, {"trace", no_argument, nullptr, 't'}, {"help", no_argument, nullptr, 'h'}, {nullptr, no_argument, nullptr, 0}}; while (1) { int c = getopt_long(argc, argv, ":r:m:f:c:th", long_options, nullptr); if (c == -1) { break; } // Disable error reporting by getopt opterr = 0; switch (c) { case 0: break; case 'r': rom_init_file_ = optarg; init_rom_ = true; if (!IsFileReadable(rom_init_file_)) { std::cerr << "ERROR: ROM initialization file " << "'" << rom_init_file_ << "'" << " is not readable." << std::endl; return false; } break; case 'm': ram_init_file_ = optarg; init_ram_ = true; if (!IsFileReadable(ram_init_file_)) { std::cerr << "ERROR: Memory initialization file " << "'" << ram_init_file_ << "'" << " is not readable." << std::endl; return false; } break; case 'f': flash_init_file_ = optarg; init_flash_ = true; if (!IsFileReadable(flash_init_file_)) { std::cerr << "ERROR: FLASH initialization file " << "'" << flash_init_file_ << "'" << " is not readable." << std::endl; return false; } break; case 't': if (!tracing_possible_) { std::cerr << "ERROR: Tracing has not been enabled at compile time." << std::endl; return false; } TraceOn(); break; case 'c': term_after_cycles_ = atoi(optarg); break; case 'h': PrintHelp(); return false; case ':': // missing argument std::cerr << "ERROR: Missing argument." << std::endl; PrintHelp(); return false; case '?': default:; // Ignore unrecognized options since they might be consumed by // Verilator's built-in parsing below. } } Verilated::commandArgs(argc, argv); return true; } void VerilatorSimCtrl::Trace() { // We cannot output a message when calling TraceOn()/TraceOff() as these // functions can be called from a signal handler. Instead we print the message // here from the main loop. if (tracing_enabled_changed_) { if (TracingEnabled()) { std::cout << "Tracing enabled." << std::endl; } else { std::cout << "Tracing disabled." << std::endl; } tracing_enabled_changed_ = false; } if (!TracingEnabled()) { return; } if (!tracer_.isOpen()) { tracer_.open(GetSimulationFileName()); std::cout << "Writing simulation traces to " << GetSimulationFileName() << std::endl; } tracer_.dump(GetTime()); } const char *VerilatorSimCtrl::GetSimulationFileName() const { #ifdef VM_TRACE_FMT_FST return "sim.fst"; #else return "sim.vcd"; #endif } void VerilatorSimCtrl::Run() { // We always need to enable this as tracing can be enabled at runtime if (tracing_possible_) { Verilated::traceEverOn(true); top_->trace(tracer_, 99, 0); } // Evaluate all initial blocks, including the DPI setup routines top_->eval(); std::cout << std::endl << "Simulation running, end by pressing CTRL-c." << std::endl; time_begin_ = std::chrono::steady_clock::now(); UnsetReset(); Trace(); while (1) { if (time_ >= initial_reset_delay_cycles_ * 2) { SetReset(); } if (time_ >= reset_duration_cycles_ * 2 + initial_reset_delay_cycles_ * 2) { UnsetReset(); } sig_clk_ = !sig_clk_; top_->eval(); time_++; Trace(); if (request_stop_) { std::cout << "Received stop request, shutting down simulation." << std::endl; break; } if (Verilated::gotFinish()) { std::cout << "Received $finish() from Verilog, shutting down simulation." << std::endl; break; } if (term_after_cycles_ && time_ > term_after_cycles_) { std::cout << "Simulation timeout of " << term_after_cycles_ << " cycles reached, shutting down simulation." << std::endl; break; } } top_->final(); time_end_ = std::chrono::steady_clock::now(); if (TracingEverEnabled()) { tracer_.close(); } } void VerilatorSimCtrl::SetReset() { if (flags_ & ResetPolarityNegative) { sig_rst_ = 0; } else { sig_rst_ = 1; } } void VerilatorSimCtrl::UnsetReset() { if (flags_ & ResetPolarityNegative) { sig_rst_ = 1; } else { sig_rst_ = 0; } } void VerilatorSimCtrl::SetInitialResetDelay(unsigned int cycles) { initial_reset_delay_cycles_ = cycles; } void VerilatorSimCtrl::SetResetDuration(unsigned int cycles) { reset_duration_cycles_ = cycles; } bool VerilatorSimCtrl::IsFileReadable(std::string filepath) { struct stat statbuf; return stat(filepath.data(), &statbuf) == 0; } bool VerilatorSimCtrl::FileSize(std::string filepath, int &size_byte) { struct stat statbuf; if (stat(filepath.data(), &statbuf) != 0) { size_byte = 0; return false; } size_byte = statbuf.st_size; return true; } unsigned int VerilatorSimCtrl::GetExecutionTimeMs() { return std::chrono::duration_cast<std::chrono::milliseconds>(time_end_ - time_begin_) .count(); } void VerilatorSimCtrl::PrintStatistics() { double speed_hz = time_ / 2 / (GetExecutionTimeMs() / 1000.0); double speed_khz = speed_hz / 1000.0; std::cout << std::endl << "Simulation statistics" << std::endl << "=====================" << std::endl << "Executed cycles: " << time_ / 2 << std::endl << "Wallclock time: " << GetExecutionTimeMs() / 1000.0 << " s" << std::endl << "Simulation speed: " << speed_hz << " cycles/s " << "(" << speed_khz << " kHz)" << std::endl; int trace_size_byte; if (tracing_enabled_ && FileSize(GetSimulationFileName(), trace_size_byte)) { std::cout << "Trace file size: " << trace_size_byte << " B" << std::endl; } } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/disks/mock_disk_mount_manager.h" #include "base/message_loop.h" #include "base/stl_util.h" #include "base/string_util.h" #include "content/public/browser/browser_thread.h" using content::BrowserThread; using testing::_; using testing::AnyNumber; using testing::Invoke; using testing::ReturnRef; namespace chromeos { namespace disks { namespace { const char* kTestSystemPath = "/this/system/path"; const char* kTestSystemPathPrefix = "/this/system"; const char* kTestDevicePath = "/this/device/path"; const char* kTestMountPath = "/media/foofoo"; const char* kTestFilePath = "/this/file/path"; const char* kTestDeviceLabel = "A label"; const char* kTestDriveLabel = "Another label"; const char* kTestUuid = "FFFF-FFFF"; } // namespace void MockDiskMountManager::AddObserverInternal( DiskMountManager::Observer* observer) { observers_.AddObserver(observer); } void MockDiskMountManager::RemoveObserverInternal( DiskMountManager::Observer* observer) { observers_.RemoveObserver(observer); } MockDiskMountManager::MockDiskMountManager() { ON_CALL(*this, AddObserver(_)) .WillByDefault(Invoke(this, &MockDiskMountManager::AddObserverInternal)); ON_CALL(*this, RemoveObserver(_)) .WillByDefault(Invoke(this, &MockDiskMountManager::RemoveObserverInternal)); ON_CALL(*this, disks()) .WillByDefault(Invoke(this, &MockDiskMountManager::disksInternal)); } MockDiskMountManager::~MockDiskMountManager() { STLDeleteContainerPairSecondPointers(disks_.begin(), disks_.end()); disks_.clear(); } void MockDiskMountManager::NotifyDeviceInsertEvents() { scoped_ptr<DiskMountManager::Disk> disk1(new DiskMountManager::Disk( std::string(kTestDevicePath), std::string(), std::string(kTestSystemPath), std::string(kTestFilePath), std::string(), std::string(kTestDriveLabel), std::string(kTestUuid), std::string(kTestSystemPathPrefix), DEVICE_TYPE_USB, 4294967295U, false, // is_parent false, // is_read_only true, // has_media false, // on_boot_device false)); // is_hidden disks_.clear(); disks_.insert(std::pair<std::string, DiskMountManager::Disk*>( std::string(kTestDevicePath), disk1.get())); // Device Added DiskMountManagerEventType event; event = MOUNT_DEVICE_ADDED; NotifyDeviceChanged(event, kTestSystemPath); // Disk Added event = MOUNT_DISK_ADDED; NotifyDiskChanged(event, disk1.get()); // Disk Changed scoped_ptr<DiskMountManager::Disk> disk2(new DiskMountManager::Disk( std::string(kTestDevicePath), std::string(kTestMountPath), std::string(kTestSystemPath), std::string(kTestFilePath), std::string(kTestDeviceLabel), std::string(kTestDriveLabel), std::string(kTestUuid), std::string(kTestSystemPathPrefix), DEVICE_TYPE_MOBILE, 1073741824, false, // is_parent false, // is_read_only true, // has_media false, // on_boot_device false)); // is_hidden disks_.clear(); disks_.insert(std::pair<std::string, DiskMountManager::Disk*>( std::string(kTestDevicePath), disk2.get())); event = MOUNT_DISK_CHANGED; NotifyDiskChanged(event, disk2.get()); } void MockDiskMountManager::NotifyDeviceRemoveEvents() { scoped_ptr<DiskMountManager::Disk> disk(new DiskMountManager::Disk( std::string(kTestDevicePath), std::string(kTestMountPath), std::string(kTestSystemPath), std::string(kTestFilePath), std::string(kTestDeviceLabel), std::string(kTestDriveLabel), std::string(kTestUuid), std::string(kTestSystemPathPrefix), DEVICE_TYPE_SD, 1073741824, false, // is_parent false, // is_read_only true, // has_media false, // on_boot_device false)); // is_hidden disks_.clear(); disks_.insert(std::pair<std::string, DiskMountManager::Disk*>( std::string(kTestDevicePath), disk.get())); NotifyDiskChanged(MOUNT_DISK_REMOVED, disk.get()); } void MockDiskMountManager::SetupDefaultReplies() { EXPECT_CALL(*this, AddObserver(_)) .Times(AnyNumber()); EXPECT_CALL(*this, RemoveObserver(_)) .Times(AnyNumber()); EXPECT_CALL(*this, disks()) .WillRepeatedly(ReturnRef(disks_)); EXPECT_CALL(*this, RequestMountInfoRefresh()) .Times(AnyNumber()); EXPECT_CALL(*this, MountPath(_, _, _, _)) .Times(AnyNumber()); EXPECT_CALL(*this, UnmountPath(_)) .Times(AnyNumber()); EXPECT_CALL(*this, FormatUnmountedDevice(_)) .Times(AnyNumber()); EXPECT_CALL(*this, FormatMountedDevice(_)) .Times(AnyNumber()); EXPECT_CALL(*this, UnmountDeviceRecursive(_, _, _)) .Times(AnyNumber()); } void MockDiskMountManager::CreateDiskEntryForMountDevice( const DiskMountManager::MountPointInfo& mount_info, const std::string& device_id) { Disk* disk = new DiskMountManager::Disk(std::string(mount_info.source_path), std::string(mount_info.mount_path), std::string(), // system_path std::string(), // file_path std::string(), // device_label std::string(), // drive_label device_id, // fs_uuid std::string(), // system_path_prefix DEVICE_TYPE_USB, // device_type 1073741824, // total_size_in_bytes false, // is_parent false, // is_read_only true, // has_media false, // on_boot_device false); // is_hidden disks_.insert(std::pair<std::string, DiskMountManager::Disk*>( std::string(mount_info.source_path), disk)); } void MockDiskMountManager::RemoveDiskEntryForMountDevice( const DiskMountManager::MountPointInfo& mount_info) { DiskMountManager::DiskMap::iterator it = disks_.find(mount_info.source_path); if (it != disks_.end()) { delete it->second; disks_.erase(it); } } void MockDiskMountManager::NotifyDiskChanged(DiskMountManagerEventType event, const DiskMountManager::Disk* disk) { // Make sure we run on UI thread. DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FOR_EACH_OBSERVER(Observer, observers_, DiskChanged(event, disk)); } void MockDiskMountManager::NotifyDeviceChanged(DiskMountManagerEventType event, const std::string& path) { // Make sure we run on UI thread. DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FOR_EACH_OBSERVER(Observer, observers_, DeviceChanged(event, path)); } } // namespace disks } // namespace chromeos <commit_msg>Valgrind/Heapchecker: Fix leak from r149099.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/disks/mock_disk_mount_manager.h" #include <utility> #include "base/message_loop.h" #include "base/stl_util.h" #include "base/string_util.h" #include "content/public/browser/browser_thread.h" using content::BrowserThread; using testing::_; using testing::AnyNumber; using testing::Invoke; using testing::ReturnRef; namespace chromeos { namespace disks { namespace { const char* kTestSystemPath = "/this/system/path"; const char* kTestSystemPathPrefix = "/this/system"; const char* kTestDevicePath = "/this/device/path"; const char* kTestMountPath = "/media/foofoo"; const char* kTestFilePath = "/this/file/path"; const char* kTestDeviceLabel = "A label"; const char* kTestDriveLabel = "Another label"; const char* kTestUuid = "FFFF-FFFF"; } // namespace void MockDiskMountManager::AddObserverInternal( DiskMountManager::Observer* observer) { observers_.AddObserver(observer); } void MockDiskMountManager::RemoveObserverInternal( DiskMountManager::Observer* observer) { observers_.RemoveObserver(observer); } MockDiskMountManager::MockDiskMountManager() { ON_CALL(*this, AddObserver(_)) .WillByDefault(Invoke(this, &MockDiskMountManager::AddObserverInternal)); ON_CALL(*this, RemoveObserver(_)) .WillByDefault(Invoke(this, &MockDiskMountManager::RemoveObserverInternal)); ON_CALL(*this, disks()) .WillByDefault(Invoke(this, &MockDiskMountManager::disksInternal)); } MockDiskMountManager::~MockDiskMountManager() { STLDeleteContainerPairSecondPointers(disks_.begin(), disks_.end()); disks_.clear(); } void MockDiskMountManager::NotifyDeviceInsertEvents() { scoped_ptr<DiskMountManager::Disk> disk1(new DiskMountManager::Disk( std::string(kTestDevicePath), std::string(), std::string(kTestSystemPath), std::string(kTestFilePath), std::string(), std::string(kTestDriveLabel), std::string(kTestUuid), std::string(kTestSystemPathPrefix), DEVICE_TYPE_USB, 4294967295U, false, // is_parent false, // is_read_only true, // has_media false, // on_boot_device false)); // is_hidden disks_.clear(); disks_.insert(std::pair<std::string, DiskMountManager::Disk*>( std::string(kTestDevicePath), disk1.get())); // Device Added DiskMountManagerEventType event; event = MOUNT_DEVICE_ADDED; NotifyDeviceChanged(event, kTestSystemPath); // Disk Added event = MOUNT_DISK_ADDED; NotifyDiskChanged(event, disk1.get()); // Disk Changed scoped_ptr<DiskMountManager::Disk> disk2(new DiskMountManager::Disk( std::string(kTestDevicePath), std::string(kTestMountPath), std::string(kTestSystemPath), std::string(kTestFilePath), std::string(kTestDeviceLabel), std::string(kTestDriveLabel), std::string(kTestUuid), std::string(kTestSystemPathPrefix), DEVICE_TYPE_MOBILE, 1073741824, false, // is_parent false, // is_read_only true, // has_media false, // on_boot_device false)); // is_hidden disks_.clear(); disks_.insert(std::pair<std::string, DiskMountManager::Disk*>( std::string(kTestDevicePath), disk2.get())); event = MOUNT_DISK_CHANGED; NotifyDiskChanged(event, disk2.get()); } void MockDiskMountManager::NotifyDeviceRemoveEvents() { scoped_ptr<DiskMountManager::Disk> disk(new DiskMountManager::Disk( std::string(kTestDevicePath), std::string(kTestMountPath), std::string(kTestSystemPath), std::string(kTestFilePath), std::string(kTestDeviceLabel), std::string(kTestDriveLabel), std::string(kTestUuid), std::string(kTestSystemPathPrefix), DEVICE_TYPE_SD, 1073741824, false, // is_parent false, // is_read_only true, // has_media false, // on_boot_device false)); // is_hidden disks_.clear(); disks_.insert(std::pair<std::string, DiskMountManager::Disk*>( std::string(kTestDevicePath), disk.get())); NotifyDiskChanged(MOUNT_DISK_REMOVED, disk.get()); } void MockDiskMountManager::SetupDefaultReplies() { EXPECT_CALL(*this, AddObserver(_)) .Times(AnyNumber()); EXPECT_CALL(*this, RemoveObserver(_)) .Times(AnyNumber()); EXPECT_CALL(*this, disks()) .WillRepeatedly(ReturnRef(disks_)); EXPECT_CALL(*this, RequestMountInfoRefresh()) .Times(AnyNumber()); EXPECT_CALL(*this, MountPath(_, _, _, _)) .Times(AnyNumber()); EXPECT_CALL(*this, UnmountPath(_)) .Times(AnyNumber()); EXPECT_CALL(*this, FormatUnmountedDevice(_)) .Times(AnyNumber()); EXPECT_CALL(*this, FormatMountedDevice(_)) .Times(AnyNumber()); EXPECT_CALL(*this, UnmountDeviceRecursive(_, _, _)) .Times(AnyNumber()); } void MockDiskMountManager::CreateDiskEntryForMountDevice( const DiskMountManager::MountPointInfo& mount_info, const std::string& device_id) { Disk* disk = new DiskMountManager::Disk(std::string(mount_info.source_path), std::string(mount_info.mount_path), std::string(), // system_path std::string(), // file_path std::string(), // device_label std::string(), // drive_label device_id, // fs_uuid std::string(), // system_path_prefix DEVICE_TYPE_USB, // device_type 1073741824, // total_size_in_bytes false, // is_parent false, // is_read_only true, // has_media false, // on_boot_device false); // is_hidden DiskMountManager::DiskMap::iterator it = disks_.find(mount_info.source_path); if (it == disks_.end()) { disks_.insert(std::make_pair(std::string(mount_info.source_path), disk)); } else { delete it->second; it->second = disk; } } void MockDiskMountManager::RemoveDiskEntryForMountDevice( const DiskMountManager::MountPointInfo& mount_info) { DiskMountManager::DiskMap::iterator it = disks_.find(mount_info.source_path); if (it != disks_.end()) { delete it->second; disks_.erase(it); } } void MockDiskMountManager::NotifyDiskChanged( DiskMountManagerEventType event, const DiskMountManager::Disk* disk) { // Make sure we run on UI thread. DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FOR_EACH_OBSERVER(Observer, observers_, DiskChanged(event, disk)); } void MockDiskMountManager::NotifyDeviceChanged(DiskMountManagerEventType event, const std::string& path) { // Make sure we run on UI thread. DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FOR_EACH_OBSERVER(Observer, observers_, DeviceChanged(event, path)); } } // namespace disks } // namespace chromeos <|endoftext|>
<commit_before>#include "seec/Preprocessor/MakeMemberFnChecker.hpp" #include "seec/RuntimeErrors/ArgumentTypes.hpp" #include "seec/Trace/TraceFormat.hpp" #include "seec/Util/ConstExprMath.hpp" #include "llvm/Support/ErrorHandling.h" #include <type_traits> namespace seec { namespace trace { //------------------------------------------------------------------------------ // RuntimeValueRecord //------------------------------------------------------------------------------ llvm::raw_ostream & operator<<(llvm::raw_ostream &Out, RuntimeValueRecord const &Record) { return Out << "<union>"; } //------------------------------------------------------------------------------ // EventRecordBase //------------------------------------------------------------------------------ std::size_t EventRecordBase::getEventSize() const { switch (Type) { #define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \ case EventType::NAME: return sizeof(EventRecord<EventType::NAME>); #include "seec/Trace/Events.def" default: llvm_unreachable("Reference to unknown event type!"); } return 0; } //------------------------------------------------------------------------------ // EventRecordBase::getProcessTime //------------------------------------------------------------------------------ SEEC_PP_MAKE_MEMBER_FN_CHECKER(has_get_process_time, getProcessTime) template<typename RecordT> typename std::enable_if< has_get_process_time<RecordT, uint64_t const &(RecordT::*)() const>::value, seec::util::Maybe<uint64_t>>::type getProcessTime(RecordT const &Record) { return Record.getProcessTime(); } template<typename RecordT> typename std::enable_if< !has_get_process_time<RecordT, uint64_t const &(RecordT::*)() const>::value, seec::util::Maybe<uint64_t>>::type getProcessTime(RecordT const &Record) { return seec::util::Maybe<uint64_t>(); } seec::util::Maybe<uint64_t> EventRecordBase::getProcessTime() const { switch (getType()) { #define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \ case EventType::NAME: \ return seec::trace::getProcessTime( \ *(static_cast<EventRecord<EventType::NAME> const *>(this))); #include "seec/Trace/Events.def" default: llvm_unreachable("Reference to unknown event type!"); } return seec::util::Maybe<uint64_t>(); } //------------------------------------------------------------------------------ // EventRecordBase::getThreadTime //------------------------------------------------------------------------------ SEEC_PP_MAKE_MEMBER_FN_CHECKER(has_get_thread_time, getThreadTime) template<typename RecordT> typename std::enable_if< has_get_thread_time<RecordT, uint64_t const &(RecordT::*)() const>::value, seec::util::Maybe<uint64_t>>::type getThreadTime(RecordT const &Record) { return Record.getThreadTime(); } template<typename RecordT> typename std::enable_if< !has_get_thread_time<RecordT, uint64_t const &(RecordT::*)() const>::value, seec::util::Maybe<uint64_t>>::type getThreadTime(RecordT const &Record) { return seec::util::Maybe<uint64_t>(); } seec::util::Maybe<uint64_t> EventRecordBase::getThreadTime() const { switch (getType()) { #define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \ case EventType::NAME: \ return seec::trace::getThreadTime( \ *(static_cast<EventRecord<EventType::NAME> const *>(this))); #include "seec/Trace/Events.def" default: llvm_unreachable("Reference to unknown event type!"); } return seec::util::Maybe<uint64_t>(); } //------------------------------------------------------------------------------ // EventRecordBase::getIndex //------------------------------------------------------------------------------ SEEC_PP_MAKE_MEMBER_FN_CHECKER(has_get_index, getIndex) template<typename RecordT> typename std::enable_if< has_get_index<RecordT, uint32_t const &(RecordT::*)() const>::value, seec::util::Maybe<uint32_t>>::type getIndex(RecordT const &Record) { return Record.getIndex(); } template<typename RecordT> typename std::enable_if< !has_get_index<RecordT, uint32_t const &(RecordT::*)() const>::value, seec::util::Maybe<uint32_t>>::type getIndex(RecordT const &Record) { return seec::util::Maybe<uint32_t>(); } seec::util::Maybe<uint32_t> EventRecordBase::getIndex() const { switch (getType()) { #define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \ case EventType::NAME: \ return seec::trace::getIndex( \ *(static_cast<EventRecord<EventType::NAME> const *>(this))); #include "seec/Trace/Events.def" default: llvm_unreachable("Reference to unknown event type!"); } return seec::util::Maybe<uint32_t>(); } llvm::raw_ostream & operator<<(llvm::raw_ostream &Out, EventRecordBase const &Event) { switch (Event.getType()) { case EventType::None: return Out << "<none>"; #define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \ case EventType::NAME: \ return Out << static_cast<EventRecord<EventType::NAME> const &>(Event); \ #include "seec/Trace/Events.def" default: llvm_unreachable("Encountered unknown EventType."); } } //------------------------------------------------------------------------------ // Event records //------------------------------------------------------------------------------ // Define raw_ostream output for all event records. #define SEEC_PP_MEMBER(TYPE, NAME) \ if (Out.is_displayed()) { \ Out.changeColor(llvm::raw_ostream::CYAN); \ Out << " " #NAME; \ Out.changeColor(llvm::raw_ostream::BLUE); \ Out << "="; \ Out.changeColor(llvm::raw_ostream::WHITE); \ Out << Event.get##NAME(); \ Out.resetColor(); \ } \ else { \ Out << " " #NAME "=" << Event.get##NAME(); \ } \ #define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \ llvm::raw_ostream &operator<<(llvm::raw_ostream &Out, \ EventRecord<EventType::NAME> const &Event) { \ Out << "["; \ if (Out.is_displayed()) { \ Out.changeColor(llvm::raw_ostream::GREEN); \ Out << #NAME; \ Out.resetColor(); \ } \ else { \ Out << #NAME; \ } \ SEEC_PP_APPLY(SEEC_PP_MEMBER, MEMBERS) \ Out << "]"; \ return Out; \ } #include "seec/Trace/Events.def" #undef SEEC_PP_MEMBER #if 0 static_assert(std::is_trivially_copyable<EventRecordBase>::value, "EventRecordBase is not trivially copyable!"); // ensure that all event records are trivial #define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \ static_assert(std::is_trivially_copyable<EventRecord<EventType::NAME>>::value, \ "EventRecord<" #NAME "> is not trivially copyable!"); #include "seec/Trace/Events.def" #endif // check the alignment requirements of event records constexpr std::size_t MaximumRecordAlignment() { return seec::const_math::max( #define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \ alignof(EventRecord<EventType::NAME>), #include "seec/Trace/Events.def" 0u); } #define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \ static_assert(sizeof(EventRecord<EventType::NAME>) >= MaximumRecordAlignment(),\ "EventRecord<" #NAME "> size is below MaximumRecordAlignment()");\ static_assert( \ sizeof(EventRecord<EventType::NAME>) % MaximumRecordAlignment() == 0, \ "EventRecord<" #NAME "> size not divisible by MaximumRecordAlignment()"); } // namespace trace (in seec) } // namespace seec <commit_msg>Change event printing to write char types as their integral values.<commit_after>#include "seec/Preprocessor/MakeMemberFnChecker.hpp" #include "seec/RuntimeErrors/ArgumentTypes.hpp" #include "seec/Trace/TraceFormat.hpp" #include "seec/Util/ConstExprMath.hpp" #include "llvm/Support/ErrorHandling.h" #include <type_traits> namespace seec { namespace trace { class EventPrinter { llvm::raw_ostream &Out; public: EventPrinter(llvm::raw_ostream &OutStream) : Out(OutStream) {} EventPrinter &operator<<(unsigned char Value) { Out << static_cast<unsigned int>(Value); return *this; } EventPrinter &operator<<(signed char Value) { Out << static_cast<int>(Value); return *this; } /* #define SEEC_EVENT_PRINT_FORWARD(TYPE) \ EventPrinter &operator<<(TYPE Value) { \ Out << Value; \ return *this; \ } SEEC_EVENT_PRINT_FORWARD(llvm::StringRef) SEEC_EVENT_PRINT_FORWARD(char const *) SEEC_EVENT_PRINT_FORWARD(std::string const &) SEEC_EVENT_PRINT_FORWARD(unsigned long) SEEC_EVENT_PRINT_FORWARD(long) SEEC_EVENT_PRINT_FORWARD(unsigned long long) SEEC_EVENT_PRINT_FORWARD(long long) SEEC_EVENT_PRINT_FORWARD(void const *) SEEC_EVENT_PRINT_FORWARD(unsigned int) SEEC_EVENT_PRINT_FORWARD(int) SEEC_EVENT_PRINT_FORWARD(double) #undef SEEC_EVENT_PRINT_FORWARD */ template<typename T> EventPrinter &operator<<(T &&Value) { Out << std::forward<T>(Value); return *this; } EventPrinter &changeColor(llvm::raw_ostream::Colors Color, bool Bold = false, bool BG = false) { Out.changeColor(Color, Bold, BG); return *this; } EventPrinter &resetColor() { Out.resetColor(); return *this; } bool is_displayed() const { return Out.is_displayed(); } }; //------------------------------------------------------------------------------ // RuntimeValueRecord //------------------------------------------------------------------------------ EventPrinter &operator<<(EventPrinter &Out, RuntimeValueRecord const &Record) { return Out << "<union>"; } //------------------------------------------------------------------------------ // EventRecordBase //------------------------------------------------------------------------------ std::size_t EventRecordBase::getEventSize() const { switch (Type) { #define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \ case EventType::NAME: return sizeof(EventRecord<EventType::NAME>); #include "seec/Trace/Events.def" default: llvm_unreachable("Reference to unknown event type!"); } return 0; } //------------------------------------------------------------------------------ // EventRecordBase::getProcessTime //------------------------------------------------------------------------------ SEEC_PP_MAKE_MEMBER_FN_CHECKER(has_get_process_time, getProcessTime) template<typename RecordT> typename std::enable_if< has_get_process_time<RecordT, uint64_t const &(RecordT::*)() const>::value, seec::util::Maybe<uint64_t>>::type getProcessTime(RecordT const &Record) { return Record.getProcessTime(); } template<typename RecordT> typename std::enable_if< !has_get_process_time<RecordT, uint64_t const &(RecordT::*)() const>::value, seec::util::Maybe<uint64_t>>::type getProcessTime(RecordT const &Record) { return seec::util::Maybe<uint64_t>(); } seec::util::Maybe<uint64_t> EventRecordBase::getProcessTime() const { switch (getType()) { #define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \ case EventType::NAME: \ return seec::trace::getProcessTime( \ *(static_cast<EventRecord<EventType::NAME> const *>(this))); #include "seec/Trace/Events.def" default: llvm_unreachable("Reference to unknown event type!"); } return seec::util::Maybe<uint64_t>(); } //------------------------------------------------------------------------------ // EventRecordBase::getThreadTime //------------------------------------------------------------------------------ SEEC_PP_MAKE_MEMBER_FN_CHECKER(has_get_thread_time, getThreadTime) template<typename RecordT> typename std::enable_if< has_get_thread_time<RecordT, uint64_t const &(RecordT::*)() const>::value, seec::util::Maybe<uint64_t>>::type getThreadTime(RecordT const &Record) { return Record.getThreadTime(); } template<typename RecordT> typename std::enable_if< !has_get_thread_time<RecordT, uint64_t const &(RecordT::*)() const>::value, seec::util::Maybe<uint64_t>>::type getThreadTime(RecordT const &Record) { return seec::util::Maybe<uint64_t>(); } seec::util::Maybe<uint64_t> EventRecordBase::getThreadTime() const { switch (getType()) { #define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \ case EventType::NAME: \ return seec::trace::getThreadTime( \ *(static_cast<EventRecord<EventType::NAME> const *>(this))); #include "seec/Trace/Events.def" default: llvm_unreachable("Reference to unknown event type!"); } return seec::util::Maybe<uint64_t>(); } //------------------------------------------------------------------------------ // EventRecordBase::getIndex //------------------------------------------------------------------------------ SEEC_PP_MAKE_MEMBER_FN_CHECKER(has_get_index, getIndex) template<typename RecordT> typename std::enable_if< has_get_index<RecordT, uint32_t const &(RecordT::*)() const>::value, seec::util::Maybe<uint32_t>>::type getIndex(RecordT const &Record) { return Record.getIndex(); } template<typename RecordT> typename std::enable_if< !has_get_index<RecordT, uint32_t const &(RecordT::*)() const>::value, seec::util::Maybe<uint32_t>>::type getIndex(RecordT const &Record) { return seec::util::Maybe<uint32_t>(); } seec::util::Maybe<uint32_t> EventRecordBase::getIndex() const { switch (getType()) { #define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \ case EventType::NAME: \ return seec::trace::getIndex( \ *(static_cast<EventRecord<EventType::NAME> const *>(this))); #include "seec/Trace/Events.def" default: llvm_unreachable("Reference to unknown event type!"); } return seec::util::Maybe<uint32_t>(); } //------------------------------------------------------------------------------ // Event records //------------------------------------------------------------------------------ // Define raw_ostream output for all event records. #define SEEC_PP_MEMBER(TYPE, NAME) \ if (Out.is_displayed()) { \ Out.changeColor(llvm::raw_ostream::CYAN); \ Out << " " #NAME; \ Out.changeColor(llvm::raw_ostream::BLUE); \ Out << "="; \ Out.changeColor(llvm::raw_ostream::WHITE); \ Out << Event.get##NAME(); \ Out.resetColor(); \ } \ else { \ Out << " " #NAME "=" << Event.get##NAME(); \ } \ #define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \ EventPrinter &operator<<(EventPrinter &Out, \ EventRecord<EventType::NAME> const &Event) { \ Out << "["; \ if (Out.is_displayed()) { \ Out.changeColor(llvm::raw_ostream::GREEN); \ Out << #NAME; \ Out.resetColor(); \ } \ else { \ Out << #NAME; \ } \ SEEC_PP_APPLY(SEEC_PP_MEMBER, MEMBERS) \ Out << "]"; \ return Out; \ } #include "seec/Trace/Events.def" #undef SEEC_PP_MEMBER #if 0 static_assert(std::is_trivially_copyable<EventRecordBase>::value, "EventRecordBase is not trivially copyable!"); // ensure that all event records are trivial #define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \ static_assert(std::is_trivially_copyable<EventRecord<EventType::NAME>>::value, \ "EventRecord<" #NAME "> is not trivially copyable!"); #include "seec/Trace/Events.def" #endif // 0 // check the alignment requirements of event records constexpr std::size_t MaximumRecordAlignment() { return seec::const_math::max( #define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \ alignof(EventRecord<EventType::NAME>), #include "seec/Trace/Events.def" 0u); } #define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \ static_assert(sizeof(EventRecord<EventType::NAME>) >= MaximumRecordAlignment(),\ "EventRecord<" #NAME "> size is below MaximumRecordAlignment()");\ static_assert( \ sizeof(EventRecord<EventType::NAME>) % MaximumRecordAlignment() == 0, \ "EventRecord<" #NAME "> size not divisible by MaximumRecordAlignment()"); #include "seec/Trace/Events.def" //------------------------------------------------------------------------------ // EventRecordBase output for llvm::raw_ostream //------------------------------------------------------------------------------ llvm::raw_ostream & operator<<(llvm::raw_ostream &OutStream, EventRecordBase const &Event) { EventPrinter Printer(OutStream); switch (Event.getType()) { case EventType::None: return OutStream << "<none>"; #define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \ case EventType::NAME: \ Printer << static_cast<EventRecord<EventType::NAME> const &>(Event); \ return OutStream; #include "seec/Trace/Events.def" default: llvm_unreachable("Encountered unknown EventType."); } } } // namespace trace (in seec) } // namespace seec <|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/browser.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/extensions/browser_action_test_util.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/user_script_master.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/ui_test_utils.h" #include "net/base/mock_host_resolver.h" IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); // Loads a simple extension which attempts to change the title of every page // that loads to "modified". ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("incognito").AppendASCII("content_scripts"))); // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); Browser* otr_browser = BrowserList::FindBrowserWithType( browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL, false); TabContents* tab = otr_browser->GetSelectedTabContents(); // Verify the script didn't run. bool result = false; ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( tab->render_view_host(), L"", L"window.domAutomationController.send(document.title == 'Unmodified')", &result)); EXPECT_TRUE(result); } IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); // Load a dummy extension. This just tests that we don't regress a // crash fix when multiple incognito- and non-incognito-enabled extensions // are mixed. ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("content_scripts").AppendASCII("all_frames"))); // Loads a simple extension which attempts to change the title of every page // that loads to "modified". ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII("api_test") .AppendASCII("incognito").AppendASCII("content_scripts"))); // Dummy extension #2. ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("content_scripts").AppendASCII("isolated_world1"))); // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); Browser* otr_browser = BrowserList::FindBrowserWithType( browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL, false); TabContents* tab = otr_browser->GetSelectedTabContents(); // Verify the script ran. bool result = false; ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( tab->render_view_host(), L"", L"window.domAutomationController.send(document.title == 'modified')", &result)); EXPECT_TRUE(result); } // Tests that an extension which is enabled for incognito mode doesn't // accidentially create and incognito profile. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DontCreateIncognitoProfile) { ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile()); ASSERT_TRUE( RunExtensionTestIncognito("incognito/enumerate_tabs")) << message_; ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile()); } // Tests that the APIs in an incognito-enabled extension work properly. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); ResultCatcher catcher; // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_ .AppendASCII("incognito").AppendASCII("apis"))); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } // Tests that the APIs in an incognito-enabled split-mode extension work // properly. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoSplitMode) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); // We need 2 ResultCatchers because we'll be running the same test in both // regular and incognito mode. ResultCatcher catcher; catcher.RestrictToProfile(browser()->profile()); ResultCatcher catcher_incognito; catcher_incognito.RestrictToProfile( browser()->profile()->GetOffTheRecordProfile()); // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_ .AppendASCII("incognito").AppendASCII("split"))); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message(); } // Tests that the APIs in an incognito-disabled extension don't see incognito // events or callbacks. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabled) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); ResultCatcher catcher; // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); ASSERT_TRUE(LoadExtension(test_data_dir_ .AppendASCII("incognito").AppendASCII("apis_disabled"))); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } // Test that opening a popup from an incognito browser window works properly. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); ResultCatcher catcher; ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_ .AppendASCII("incognito").AppendASCII("popup"))); // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); Browser* incognito_browser = BrowserList::FindBrowserWithType( browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL, false); // Simulate the incognito's browser action being clicked. BrowserActionTestUtil(incognito_browser).Press(0); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } <commit_msg>Re-disable IncognitoSplitMode. It's still hanging.<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/browser.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/extensions/browser_action_test_util.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/user_script_master.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/ui_test_utils.h" #include "net/base/mock_host_resolver.h" IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); // Loads a simple extension which attempts to change the title of every page // that loads to "modified". ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("incognito").AppendASCII("content_scripts"))); // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); Browser* otr_browser = BrowserList::FindBrowserWithType( browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL, false); TabContents* tab = otr_browser->GetSelectedTabContents(); // Verify the script didn't run. bool result = false; ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( tab->render_view_host(), L"", L"window.domAutomationController.send(document.title == 'Unmodified')", &result)); EXPECT_TRUE(result); } IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); // Load a dummy extension. This just tests that we don't regress a // crash fix when multiple incognito- and non-incognito-enabled extensions // are mixed. ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("content_scripts").AppendASCII("all_frames"))); // Loads a simple extension which attempts to change the title of every page // that loads to "modified". ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII("api_test") .AppendASCII("incognito").AppendASCII("content_scripts"))); // Dummy extension #2. ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("content_scripts").AppendASCII("isolated_world1"))); // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); Browser* otr_browser = BrowserList::FindBrowserWithType( browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL, false); TabContents* tab = otr_browser->GetSelectedTabContents(); // Verify the script ran. bool result = false; ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( tab->render_view_host(), L"", L"window.domAutomationController.send(document.title == 'modified')", &result)); EXPECT_TRUE(result); } // Tests that an extension which is enabled for incognito mode doesn't // accidentially create and incognito profile. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DontCreateIncognitoProfile) { ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile()); ASSERT_TRUE( RunExtensionTestIncognito("incognito/enumerate_tabs")) << message_; ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile()); } // Tests that the APIs in an incognito-enabled extension work properly. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); ResultCatcher catcher; // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_ .AppendASCII("incognito").AppendASCII("apis"))); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } // Tests that the APIs in an incognito-enabled split-mode extension work // properly. // Hangy, http://crbug.com/53991. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoSplitMode) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); // We need 2 ResultCatchers because we'll be running the same test in both // regular and incognito mode. ResultCatcher catcher; catcher.RestrictToProfile(browser()->profile()); ResultCatcher catcher_incognito; catcher_incognito.RestrictToProfile( browser()->profile()->GetOffTheRecordProfile()); // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_ .AppendASCII("incognito").AppendASCII("split"))); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message(); } // Tests that the APIs in an incognito-disabled extension don't see incognito // events or callbacks. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabled) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); ResultCatcher catcher; // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); ASSERT_TRUE(LoadExtension(test_data_dir_ .AppendASCII("incognito").AppendASCII("apis_disabled"))); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } // Test that opening a popup from an incognito browser window works properly. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); ResultCatcher catcher; ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_ .AppendASCII("incognito").AppendASCII("popup"))); // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); Browser* incognito_browser = BrowserList::FindBrowserWithType( browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL, false); // Simulate the incognito's browser action being clicked. BrowserActionTestUtil(incognito_browser).Press(0); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <MNSINIParser.hxx> #include <rtl/byteseq.hxx> IniParser::IniParser(OUString const & rIniName) throw(com::sun::star::io::IOException ) { OUString iniUrl; if (osl_File_E_None != osl_getFileURLFromSystemPath(rIniName.pData, &iniUrl.pData)) return; SAL_INFO("connectivity.mork", "IniParser: " << iniUrl); oslFileHandle handle=NULL; oslFileError fileError = osl_File_E_INVAL; try{ if (!iniUrl.isEmpty()) fileError = osl_openFile(iniUrl.pData, &handle, osl_File_OpenFlag_Read); } catch(const ::com::sun::star::io::IOException&) { SAL_WARN("connectivity.mork", "IniParser -- couldn't open file: " << iniUrl); return; } if (osl_File_E_None == fileError) { rtl::ByteSequence seq; sal_uInt64 nSize = 0; osl_getFileSize(handle, &nSize); OUString sectionName( "no name section" ); while (true) { sal_uInt64 nPos; if (osl_File_E_None != osl_getFilePos(handle, &nPos) || nPos >= nSize) break; if (osl_File_E_None != osl_readLine(handle , (sal_Sequence **) &seq)) break; OString line( (const sal_Char *) seq.getConstArray(), seq.getLength() ); sal_Int32 nIndex = line.indexOf('='); if (nIndex >= 1) { ini_Section *aSection = &mAllSection[sectionName]; struct ini_NameValue nameValue; nameValue.sName = OStringToOUString( line.copy(0,nIndex).trim(), RTL_TEXTENCODING_ASCII_US ); nameValue.sValue = OStringToOUString( line.copy(nIndex+1).trim(), RTL_TEXTENCODING_UTF8 ); aSection->lList.push_back(nameValue); } else { sal_Int32 nIndexStart = line.indexOf('['); sal_Int32 nIndexEnd = line.indexOf(']'); if ( nIndexEnd > nIndexStart && nIndexStart >=0) { sectionName = OStringToOUString( line.copy(nIndexStart + 1,nIndexEnd - nIndexStart -1).trim(), RTL_TEXTENCODING_ASCII_US ); if (sectionName.isEmpty()) sectionName = OUString("no name section"); ini_Section *aSection = &mAllSection[sectionName]; aSection->sName = sectionName; } } } osl_closeFile(handle); } #if OSL_DEBUG_LEVEL > 0 else { SAL_WARN("connectivity.mork", "IniParser -- couldn't open file: " << iniUrl); } #endif } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Clean up warning/info reporting<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <MNSINIParser.hxx> #include <rtl/byteseq.hxx> IniParser::IniParser(OUString const & rIniName) throw(com::sun::star::io::IOException ) { OUString iniUrl; oslFileError fileError = osl_getFileURLFromSystemPath( rIniName.pData, &iniUrl.pData); if (fileError != osl_File_E_None) { SAL_WARN( "connectivity.mork", "InitParser, getFileURLFromSystemPath(" << rIniName << "): " << +fileError); return; } SAL_INFO("connectivity.mork", "IniParser: " << iniUrl); oslFileHandle handle=NULL; fileError = osl_openFile(iniUrl.pData, &handle, osl_File_OpenFlag_Read); if (osl_File_E_None == fileError) { rtl::ByteSequence seq; sal_uInt64 nSize = 0; osl_getFileSize(handle, &nSize); OUString sectionName( "no name section" ); while (true) { sal_uInt64 nPos; if (osl_File_E_None != osl_getFilePos(handle, &nPos) || nPos >= nSize) break; if (osl_File_E_None != osl_readLine(handle , (sal_Sequence **) &seq)) break; OString line( (const sal_Char *) seq.getConstArray(), seq.getLength() ); sal_Int32 nIndex = line.indexOf('='); if (nIndex >= 1) { ini_Section *aSection = &mAllSection[sectionName]; struct ini_NameValue nameValue; nameValue.sName = OStringToOUString( line.copy(0,nIndex).trim(), RTL_TEXTENCODING_ASCII_US ); nameValue.sValue = OStringToOUString( line.copy(nIndex+1).trim(), RTL_TEXTENCODING_UTF8 ); aSection->lList.push_back(nameValue); } else { sal_Int32 nIndexStart = line.indexOf('['); sal_Int32 nIndexEnd = line.indexOf(']'); if ( nIndexEnd > nIndexStart && nIndexStart >=0) { sectionName = OStringToOUString( line.copy(nIndexStart + 1,nIndexEnd - nIndexStart -1).trim(), RTL_TEXTENCODING_ASCII_US ); if (sectionName.isEmpty()) sectionName = OUString("no name section"); ini_Section *aSection = &mAllSection[sectionName]; aSection->sName = sectionName; } } } osl_closeFile(handle); } else { SAL_INFO( "connectivity.mork", "IniParser couldn't open file " << iniUrl << ": " << +fileError); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: HStorageAccess.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-03-30 11:52:59 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): Ocke Janssen * * ************************************************************************/ #ifndef CONNECTIVITY_HSQLDB_STORAGEACCESS_HXX #define CONNECTIVITY_HSQLDB_STORAGEACCESS_HXX #include "hsqldb/HStorageAccess.h" namespace connectivity { namespace hsqldb { class DataLogFile; } } jint read_from_storage_stream( JNIEnv * env, jobject obj_this, jstring name, jstring key, ::connectivity::hsqldb::DataLogFile* logger = NULL ); jint read_from_storage_stream_into_buffer( JNIEnv * env, jobject obj_this,jstring name, jstring key, jbyteArray buffer, jint off, jint len, ::connectivity::hsqldb::DataLogFile* logger = NULL ); void write_to_storage_stream_from_buffer( JNIEnv* env, jobject obj_this, jstring name, jstring key, jbyteArray buffer, jint off, jint len, ::connectivity::hsqldb::DataLogFile* logger = NULL ); void write_to_storage_stream( JNIEnv* env, jobject obj_this, jstring name, jstring key, jint v, ::connectivity::hsqldb::DataLogFile* logger = NULL ); #endif // CONNECTIVITY_HSQLDB_STORAGEACCESS_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.2.62); FILE MERGED 2005/09/05 17:25:27 rt 1.2.62.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: HStorageAccess.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 07:14:59 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CONNECTIVITY_HSQLDB_STORAGEACCESS_HXX #define CONNECTIVITY_HSQLDB_STORAGEACCESS_HXX #include "hsqldb/HStorageAccess.h" namespace connectivity { namespace hsqldb { class DataLogFile; } } jint read_from_storage_stream( JNIEnv * env, jobject obj_this, jstring name, jstring key, ::connectivity::hsqldb::DataLogFile* logger = NULL ); jint read_from_storage_stream_into_buffer( JNIEnv * env, jobject obj_this,jstring name, jstring key, jbyteArray buffer, jint off, jint len, ::connectivity::hsqldb::DataLogFile* logger = NULL ); void write_to_storage_stream_from_buffer( JNIEnv* env, jobject obj_this, jstring name, jstring key, jbyteArray buffer, jint off, jint len, ::connectivity::hsqldb::DataLogFile* logger = NULL ); void write_to_storage_stream( JNIEnv* env, jobject obj_this, jstring name, jstring key, jint v, ::connectivity::hsqldb::DataLogFile* logger = NULL ); #endif // CONNECTIVITY_HSQLDB_STORAGEACCESS_HXX <|endoftext|>
<commit_before>// // Copyright (c) 2011, Willow Garage, Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the Willow Garage, Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include <ecto/scheduler.hpp> #include <ecto/cell.hpp> #include <ecto/graph/utilities.hpp> #include <ecto/log.hpp> #include <ecto/plasm.hpp> #include <ecto/vertex.hpp> #include <boost/date_time/microsec_time_clock.hpp> #include <boost/date_time/posix_time/ptime.hpp> #include <boost/thread.hpp> #include <boost/graph/topological_sort.hpp> #include <boost/scoped_ptr.hpp> #include <signal.h> namespace ecto { using namespace ecto::except; using ecto::graph::graph_t; using boost::scoped_ptr; using boost::thread; using boost::mutex; namespace { boost::signals2::signal<void(void)> SINGLE_THREADED_SIGINT_SIGNAL; void sigint_static_thunk(int) { std::cerr << "*** SIGINT received, stopping graph execution.\n" << "*** If you are stuck here, you may need to hit ^C again\n" << "*** when back in the interpreter thread.\n" << "*** or Ctrl-\\ (backslash) for a hard stop.\n" << std::endl; SINGLE_THREADED_SIGINT_SIGNAL(); PyErr_SetInterrupt(); } } // End of anonymous namespace. scheduler::scheduler(plasm_ptr p) : plasm_(p) , graph_(p->graph()) , io_svc_() , state_(INIT) , runners_(0) , interrupt_connection(SINGLE_THREADED_SIGINT_SIGNAL.connect(boost::bind(&scheduler::interrupt, this))) , interrupted(false) { assert(plasm_); #if !defined(_WIN32) // TODO (JTF): Move this somewhere else, and use sigaction(2) instead. signal(SIGINT, &sigint_static_thunk); #endif } scheduler::~scheduler() { interrupt_connection.disconnect(); //std::cerr << this << " ~scheduler()\n"; stop(); } bool scheduler::execute(unsigned num_iters) { //std::cerr << this << " scheduler::execute(" << num_iters << ")\n"; execute_async(num_iters); run(); return (state_ > 0); // NOT thread-safe! } bool scheduler::execute_async(unsigned num_iters) { //std::cerr << this << " scheduler::execute_async(" << num_iters << ")\n"; { // BEGIN mtx_ scope. mutex::scoped_lock l(mtx_); if (EXECUTING == state_) BOOST_THROW_EXCEPTION(EctoException() << diag_msg("Scheduler already executing")); // Make sure the io_service is ready to go. io_svc_.reset(); if (state_ != RUNNING) { io_svc_.post(boost::bind(& scheduler::execute_init, this, num_iters)); } else { io_svc_.post(boost::bind(& scheduler::execute_iter, this, 0 /* cur_iter */, num_iters, 0 /* stack_idx */)); } state_ = EXECUTING; // Make sure no one else can start an execution. } // END mtx_ scope. return (state_ > 0); // NOT thread-safe! } bool scheduler::run_job() { ref_count<> c(mtx_, runners_); profile::graphstats_collector gs(graphstats_); // TODO: NOT thread-safe! io_svc_.run_one(); return (state_ > 0); // NOT thread-safe! } bool scheduler::run(unsigned timeout_usec) { ref_count<> c(mtx_, runners_); profile::graphstats_collector gs(graphstats_); // TODO: NOT thread-safe! using namespace boost::posix_time; ptime quit = microsec_clock::universal_time() + microseconds(timeout_usec); std::size_t n = 0; do { n = io_svc_.run_one(); // Sit and spin. } while (n && microsec_clock::universal_time() < quit); return (state_ > 0); // NOT thread-safe! } bool scheduler::run() { ref_count<> c(mtx_, runners_); profile::graphstats_collector gs(graphstats_); // TODO: NOT thread-safe! io_svc_.run(); return (state_ > 0); // NOT thread-safe! } void scheduler::interrupt() { interrupted = true; } void scheduler::stop() { //std::cerr << this << " scheduler::stop()\n"; if (! running()) return; state(STOPPING); run(); // Flush all jobs. io_svc_.stop(); //while (! io_svc_.stopped()) {} // TODO: Need updated version of boost! while (true) { boost::mutex::scoped_lock l(mtx_); if (! runners_) break; // TODO: Use condition variable? } execute_fini(); assert(state() == FINI); assert(! running()); } void scheduler::execute_init(unsigned num_iters) { //std::cerr << this << " scheduler::execute_init(" << num_iters << "): STATE=" // << state() << "\n"; if (state() == STOPPING) return; // Flush all jobs from the io_service. assert(state() == EXECUTING); compute_stack(); plasm_->reset_ticks(); // TODO: Should plasm have a reset_ method for strands? // Reset cell strands and invoke their start() method. for (std::size_t j=0; j<stack_.size(); ++j) { cell::ptr c = graph_[stack_[j]]->cell(); if (! c) continue; if (c->strand_) c->strand_->reset(); c->start(); } io_svc_.post(boost::bind(& scheduler::execute_iter, this, 0 /* cur_iter */, num_iters, 0 /* stack_idx */)); } void scheduler::execute_iter(unsigned cur_iter, unsigned num_iters, std::size_t stack_idx) { //std::cerr << this << " scheduler::execute_iter(" << cur_iter << "," // << num_iters << "," << stack_idx << "): STATE=" << state() << " stack_.size()=" << stack_.size() << "\n"; if (state() == STOPPING) return; // Flush all jobs from the io_service. assert(stack_idx < stack_.size()); assert(state() == EXECUTING); int retval = ecto::QUIT; try { retval = ecto::graph::invoke_process(graph_, stack_[stack_idx]); if (interrupted) { retval = ecto::QUIT; interrupted = false; } } catch (const boost::thread_interrupted &) { std::cout << "Interrupted\n"; } catch (...) { ECTO_LOG_DEBUG("%s", "STOPPING... somebody done threw something."); state(ERROR); throw; // Propagate to the calling thread. } // TODO: Handle BREAK or CONTINUE? There are serious implications for // multi-threaded scheduling. switch (retval) { case ecto::OK: ++stack_idx; if (stack_.size() <= stack_idx) { stack_idx = 0; ++cur_iter; // Made it through the stack. Do it again? if (num_iters && cur_iter >= num_iters) { // No longer executing, but still "running". state(RUNNING); return; } } break; // continue execution in this method. case ecto::DO_OVER: break; // Reschedule this cell e.g. Don't bump the stack_idx. default: // Don't schedule any more cells, just finalize and quit. io_svc_.post(boost::bind(& scheduler::execute_fini, this)); return; } io_svc_.post(boost::bind(& scheduler::execute_iter, this, cur_iter, num_iters, stack_idx)); } void scheduler::execute_fini() { //std::cerr << this << " execute_fini(): STATE=" << state() << "\n"; assert(running()); for (std::size_t j=0; j<stack_.size(); ++j) { cell::ptr c = graph_[stack_[j]]->cell(); if (! c) continue; c->stop(); } state(FINI); } void scheduler::compute_stack() { if (! stack_.empty()) // stack_ will be empty if it needs to be computed. return; // Check the plasm for correctness, and make sure it is configured/activated. plasm_->check(); plasm_->configure_all(); plasm_->activate_all(); ECTO_LOG_DEBUG("graph size = %u", num_vertices(graph_)); #define BREADTHFIRST #ifdef BREADTHFIRST // TODO: Doc why we want a "BFS" topological sort here. graph_t::vertex_iterator vit, vend; // NOTE: We only need to reset the vertex ticks here, and // plasm::reset_ticks() also resets the edge ticks. boost::tie(vit, vend) = vertices(graph_); for (; vit != vend; ++vit) graph_[*vit]->reset_tick(); const std::size_t NUM_VERTICES = num_vertices(graph_); for (size_t n = 0; n < NUM_VERTICES; ++n) { boost::tie(vit, vend) = vertices(graph_); for (; vit != vend; ++vit) { // NOTE: tick is incremented on visit const graph::vertex_ptr vp = graph_[*vit]; if (vp->tick() != 0) continue; // Already visited this vertex. graph_t::in_edge_iterator iebegin, ieend; boost::tie(iebegin, ieend) = in_edges(*vit, graph_); bool all_ins_visited = true; for (; iebegin != ieend; ++iebegin) { const graph::vertex_ptr in_vp = graph_[source(*iebegin, graph_)]; if (in_vp->tick() == 0) all_ins_visited = false; } if (all_ins_visited) { vp->inc_tick(); stack_.push_back(*vit); // Check for cycles. graph_t::out_edge_iterator oebegin, oeend; boost::tie(oebegin, oeend) = out_edges(*vit, graph_); for (; oebegin != oeend; ++oebegin) { const graph::vertex_ptr out_vp = graph_[target(*oebegin, graph_)]; if (out_vp->tick()) // Back edge! BOOST_THROW_EXCEPTION(EctoException() << diag_msg("Plasm NOT a DAG!")); } } } } // NOTE: We should insert a vertex each iteration. if (NUM_VERTICES != stack_.size()) BOOST_THROW_EXCEPTION(EctoException() << diag_msg("Plasm NOT a DAG!")); #else // dfs, which is what boost::topological_sort does boost::topological_sort(graph_, std::back_inserter(stack_)); std::reverse(stack_.begin(), stack_.end()); #endif assert(! stack_.empty()); } #if 0 void scheduler::stop() { // TODO (JTF): This isn't really safe, and we shouldn't really need it w/ // io_svc_ controlling execution. graph_[stack_[0]]->stop_requested(true); } #endif } // End of namespace ecto. <commit_msg>Don't clobber the underlying c++ executions when aborting, be graceful.<commit_after>// // Copyright (c) 2011, Willow Garage, Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the Willow Garage, Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include <ecto/scheduler.hpp> #include <ecto/cell.hpp> #include <ecto/graph/utilities.hpp> #include <ecto/log.hpp> #include <ecto/plasm.hpp> #include <ecto/vertex.hpp> #include <boost/date_time/microsec_time_clock.hpp> #include <boost/date_time/posix_time/ptime.hpp> #include <boost/thread.hpp> #include <boost/graph/topological_sort.hpp> #include <boost/scoped_ptr.hpp> #include <signal.h> namespace ecto { using namespace ecto::except; using ecto::graph::graph_t; using boost::scoped_ptr; using boost::thread; using boost::mutex; namespace { boost::signals2::signal<void(void)> SINGLE_THREADED_SIGINT_SIGNAL; void sigint_static_thunk(int) { std::cerr << "*** SIGINT received, stopping graph execution.\n" << "*** If you are stuck here, you may need to hit ^C again\n" << "*** when back in the interpreter thread.\n" << "*** or Ctrl-\\ (backslash) for a hard stop.\n" << std::endl; SINGLE_THREADED_SIGINT_SIGNAL(); } } // End of anonymous namespace. scheduler::scheduler(plasm_ptr p) : plasm_(p) , graph_(p->graph()) , io_svc_() , state_(INIT) , runners_(0) , interrupt_connection(SINGLE_THREADED_SIGINT_SIGNAL.connect(boost::bind(&scheduler::interrupt, this))) , interrupted(false) { assert(plasm_); #if !defined(_WIN32) // TODO (JTF): Move this somewhere else, and use sigaction(2) instead. signal(SIGINT, &sigint_static_thunk); #endif } scheduler::~scheduler() { interrupt_connection.disconnect(); //std::cerr << this << " ~scheduler()\n"; stop(); } bool scheduler::execute(unsigned num_iters) { //std::cerr << this << " scheduler::execute(" << num_iters << ")\n"; execute_async(num_iters); run(); return (state_ > 0); // NOT thread-safe! } bool scheduler::execute_async(unsigned num_iters) { //std::cerr << this << " scheduler::execute_async(" << num_iters << ")\n"; { // BEGIN mtx_ scope. mutex::scoped_lock l(mtx_); if (EXECUTING == state_) BOOST_THROW_EXCEPTION(EctoException() << diag_msg("Scheduler already executing")); // Make sure the io_service is ready to go. io_svc_.reset(); if (state_ != RUNNING) { io_svc_.post(boost::bind(& scheduler::execute_init, this, num_iters)); } else { io_svc_.post(boost::bind(& scheduler::execute_iter, this, 0 /* cur_iter */, num_iters, 0 /* stack_idx */)); } state_ = EXECUTING; // Make sure no one else can start an execution. } // END mtx_ scope. return (state_ > 0); // NOT thread-safe! } bool scheduler::run_job() { ref_count<> c(mtx_, runners_); profile::graphstats_collector gs(graphstats_); // TODO: NOT thread-safe! io_svc_.run_one(); return (state_ > 0); // NOT thread-safe! } bool scheduler::run(unsigned timeout_usec) { ref_count<> c(mtx_, runners_); profile::graphstats_collector gs(graphstats_); // TODO: NOT thread-safe! using namespace boost::posix_time; ptime quit = microsec_clock::universal_time() + microseconds(timeout_usec); std::size_t n = 0; do { n = io_svc_.run_one(); // Sit and spin. } while (n && microsec_clock::universal_time() < quit); return (state_ > 0); // NOT thread-safe! } bool scheduler::run() { ref_count<> c(mtx_, runners_); profile::graphstats_collector gs(graphstats_); // TODO: NOT thread-safe! io_svc_.run(); return (state_ > 0); // NOT thread-safe! } void scheduler::interrupt() { interrupted = true; } void scheduler::stop() { //std::cerr << this << " scheduler::stop()\n"; if (! running()) return; state(STOPPING); run(); // Flush all jobs. io_svc_.stop(); //while (! io_svc_.stopped()) {} // TODO: Need updated version of boost! while (true) { boost::mutex::scoped_lock l(mtx_); if (! runners_) break; // TODO: Use condition variable? } execute_fini(); assert(state() == FINI); assert(! running()); } void scheduler::execute_init(unsigned num_iters) { //std::cerr << this << " scheduler::execute_init(" << num_iters << "): STATE=" // << state() << "\n"; if (state() == STOPPING) return; // Flush all jobs from the io_service. assert(state() == EXECUTING); compute_stack(); plasm_->reset_ticks(); // TODO: Should plasm have a reset_ method for strands? // Reset cell strands and invoke their start() method. for (std::size_t j=0; j<stack_.size(); ++j) { cell::ptr c = graph_[stack_[j]]->cell(); if (! c) continue; if (c->strand_) c->strand_->reset(); c->start(); } io_svc_.post(boost::bind(& scheduler::execute_iter, this, 0 /* cur_iter */, num_iters, 0 /* stack_idx */)); } void scheduler::execute_iter(unsigned cur_iter, unsigned num_iters, std::size_t stack_idx) { //std::cerr << this << " scheduler::execute_iter(" << cur_iter << "," // << num_iters << "," << stack_idx << "): STATE=" << state() << " stack_.size()=" << stack_.size() << "\n"; if (state() == STOPPING) return; // Flush all jobs from the io_service. assert(stack_idx < stack_.size()); assert(state() == EXECUTING); int retval = ecto::QUIT; try { retval = ecto::graph::invoke_process(graph_, stack_[stack_idx]); if (interrupted) { retval = ecto::QUIT; interrupted = false; } } catch (const boost::thread_interrupted &) { std::cout << "Interrupted\n"; } catch (...) { ECTO_LOG_DEBUG("%s", "STOPPING... somebody done threw something."); state(ERROR); throw; // Propagate to the calling thread. } // TODO: Handle BREAK or CONTINUE? There are serious implications for // multi-threaded scheduling. switch (retval) { case ecto::OK: ++stack_idx; if (stack_.size() <= stack_idx) { stack_idx = 0; ++cur_iter; // Made it through the stack. Do it again? if (num_iters && cur_iter >= num_iters) { // No longer executing, but still "running". state(RUNNING); return; } } break; // continue execution in this method. case ecto::DO_OVER: break; // Reschedule this cell e.g. Don't bump the stack_idx. default: // Don't schedule any more cells, just finalize and quit. io_svc_.post(boost::bind(& scheduler::execute_fini, this)); return; } io_svc_.post(boost::bind(& scheduler::execute_iter, this, cur_iter, num_iters, stack_idx)); } void scheduler::execute_fini() { //std::cerr << this << " execute_fini(): STATE=" << state() << "\n"; assert(running()); for (std::size_t j=0; j<stack_.size(); ++j) { cell::ptr c = graph_[stack_[j]]->cell(); if (! c) continue; c->stop(); } state(FINI); } void scheduler::compute_stack() { if (! stack_.empty()) // stack_ will be empty if it needs to be computed. return; // Check the plasm for correctness, and make sure it is configured/activated. plasm_->check(); plasm_->configure_all(); plasm_->activate_all(); ECTO_LOG_DEBUG("graph size = %u", num_vertices(graph_)); #define BREADTHFIRST #ifdef BREADTHFIRST // TODO: Doc why we want a "BFS" topological sort here. graph_t::vertex_iterator vit, vend; // NOTE: We only need to reset the vertex ticks here, and // plasm::reset_ticks() also resets the edge ticks. boost::tie(vit, vend) = vertices(graph_); for (; vit != vend; ++vit) graph_[*vit]->reset_tick(); const std::size_t NUM_VERTICES = num_vertices(graph_); for (size_t n = 0; n < NUM_VERTICES; ++n) { boost::tie(vit, vend) = vertices(graph_); for (; vit != vend; ++vit) { // NOTE: tick is incremented on visit const graph::vertex_ptr vp = graph_[*vit]; if (vp->tick() != 0) continue; // Already visited this vertex. graph_t::in_edge_iterator iebegin, ieend; boost::tie(iebegin, ieend) = in_edges(*vit, graph_); bool all_ins_visited = true; for (; iebegin != ieend; ++iebegin) { const graph::vertex_ptr in_vp = graph_[source(*iebegin, graph_)]; if (in_vp->tick() == 0) all_ins_visited = false; } if (all_ins_visited) { vp->inc_tick(); stack_.push_back(*vit); // Check for cycles. graph_t::out_edge_iterator oebegin, oeend; boost::tie(oebegin, oeend) = out_edges(*vit, graph_); for (; oebegin != oeend; ++oebegin) { const graph::vertex_ptr out_vp = graph_[target(*oebegin, graph_)]; if (out_vp->tick()) // Back edge! BOOST_THROW_EXCEPTION(EctoException() << diag_msg("Plasm NOT a DAG!")); } } } } // NOTE: We should insert a vertex each iteration. if (NUM_VERTICES != stack_.size()) BOOST_THROW_EXCEPTION(EctoException() << diag_msg("Plasm NOT a DAG!")); #else // dfs, which is what boost::topological_sort does boost::topological_sort(graph_, std::back_inserter(stack_)); std::reverse(stack_.begin(), stack_.end()); #endif assert(! stack_.empty()); } #if 0 void scheduler::stop() { // TODO (JTF): This isn't really safe, and we shouldn't really need it w/ // io_svc_ controlling execution. graph_[stack_[0]]->stop_requested(true); } #endif } // End of namespace ecto. <|endoftext|>
<commit_before>/***************************************************************************** * Project: RooFit * * Package: RooFitModels * * @(#)root/roofit:$Id$ * Authors: * * GR, Gerhard Raven, UC San Diego, Gerhard.Raven@slac.stanford.edu * * * Copyright (c) 2000-2005, Regents of the University of California * * and Stanford University. All rights reserved. * * * * Redistribution and use in source and binary forms, * * with or without modification, are permitted according to the terms * * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ ////////////////////////////////////////////////////////////////////////////// // // BEGIN_HTML // Chebychev polynomial p.d.f. of the first kind // END_HTML // #include <cmath> #include <iostream> #include "RooFit.h" #include "Riostream.h" #include "RooChebychev.h" #include "RooAbsReal.h" #include "RooRealVar.h" #include "RooArgList.h" ClassImp(RooChebychev) ; //_____________________________________________________________________________ RooChebychev::RooChebychev() { } //_____________________________________________________________________________ RooChebychev::RooChebychev(const char* name, const char* title, RooAbsReal& x, const RooArgList& coefList): RooAbsPdf(name, title), _x("x", "Dependent", this, x), _coefList("coefficients","List of coefficients",this) { // Constructor TIterator* coefIter = coefList.createIterator() ; RooAbsArg* coef ; while((coef = (RooAbsArg*)coefIter->Next())) { if (!dynamic_cast<RooAbsReal*>(coef)) { std::cerr << "RooChebychev::ctor(" << GetName() << ") ERROR: coefficient " << coef->GetName() << " is not of type RooAbsReal" << std::endl ; assert(0) ; } _coefList.add(*coef) ; } delete coefIter ; } //_____________________________________________________________________________ RooChebychev::RooChebychev(const RooChebychev& other, const char* name) : RooAbsPdf(other, name), _x("x", this, other._x), _coefList("coefList",this,other._coefList) { } inline static double p0(double ,double a) { return a; } inline static double p1(double t,double a,double b) { return a*t+b; } inline static double p2(double t,double a,double b,double c) { return p1(t,p1(t,a,b),c); } inline static double p3(double t,double a,double b,double c,double d) { return p2(t,p1(t,a,b),c,d); } inline static double p4(double t,double a,double b,double c,double d,double e) { return p3(t,p1(t,a,b),c,d,e); } //_____________________________________________________________________________ Double_t RooChebychev::evaluate() const { Double_t xmin = _x.min(); Double_t xmax = _x.max(); Double_t x(-1+2*(_x-xmin)/(xmax-xmin)); Double_t x2(x*x); Double_t sum(0) ; switch (_coefList.getSize()) { case 7: sum+=((RooAbsReal&)_coefList[6]).getVal()*x*p3(x2,64,-112,56,-7); case 6: sum+=((RooAbsReal&)_coefList[5]).getVal()*p3(x2,32,-48,18,-1); case 5: sum+=((RooAbsReal&)_coefList[4]).getVal()*x*p2(x2,16,-20,5); case 4: sum+=((RooAbsReal&)_coefList[3]).getVal()*p2(x2,8,-8,1); case 3: sum+=((RooAbsReal&)_coefList[2]).getVal()*x*p1(x2,4,-3); case 2: sum+=((RooAbsReal&)_coefList[1]).getVal()*p1(x2,2,-1); case 1: sum+=((RooAbsReal&)_coefList[0]).getVal()*x; case 0: sum+=1; break; default: std::cerr << "In " << __func__ << " (" << __FILE__ << ", line " << __LINE__ << "): Higher order Chebychev polynomials currently " "unimplemented." << std::endl; assert(false); } return sum; } //_____________________________________________________________________________ Int_t RooChebychev::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* /* rangeName */) const { if (matchArgs(allVars, analVars, _x)) return 1; return 0; } //_____________________________________________________________________________ Double_t RooChebychev::analyticalIntegral(Int_t code, const char* rangeName) const { assert(1 == code); // the full range of the function is mapped to the normalised [-1, 1] range const Double_t xminfull(_x.min()), xmaxfull(_x.max()); const Double_t fullRange = xmaxfull - xminfull; // define limits of the integration range on a normalised scale Double_t minScaled = -1., maxScaled = +1.; // check to see if integral of a subrange is requested if (rangeName && 0 != rangeName[0]) { assert(xminfull <= _x.min(rangeName) && _x.min(rangeName) <= xmaxfull); assert(xminfull <= _x.max(rangeName) && _x.max(rangeName) <= xmaxfull); minScaled = -1. + 2. * (_x.min(rangeName) - xminfull) / fullRange; maxScaled = +1. - 2. * (xmaxfull - _x.max(rangeName)) / fullRange; } // return half of the range since the normalised range runs from -1 to 1 // which has a range of two return 0.5 * fullRange * (evalAnaInt(maxScaled) - evalAnaInt(minScaled)); } Double_t RooChebychev::evalAnaInt(const Double_t x) const { const Double_t x2 = x * x; Double_t sum = 0.; switch (_coefList.getSize()) { case 7: sum+=((RooAbsReal&)_coefList[6]).getVal()*x2*p3(x2,8.,-112./6.,14.,-7./2.); case 6: sum+=((RooAbsReal&)_coefList[5]).getVal()*x*p3(x2,32./7.,-48./5.,6.,-1.); case 5: sum+=((RooAbsReal&)_coefList[4]).getVal()*x2*p2(x2,16./6.,-5.,2.5); case 4: sum+=((RooAbsReal&)_coefList[3]).getVal()*x*p2(x2,8./5.,-8./3.,1.); case 3: sum+=((RooAbsReal&)_coefList[2]).getVal()*x2*p1(x2,1.,-3./2.); case 2: sum+=((RooAbsReal&)_coefList[1]).getVal()*x*p1(x2,2./3.,-1.); case 1: sum+=((RooAbsReal&)_coefList[0]).getVal()*x2*.5; case 0: sum+=x; break; default: std::cerr << "In " << __func__ << " (" << __FILE__ << ", line " << __LINE__ << "): Higher order Chebychev polynomials currently " "unimplemented." << std::endl; assert(false); } return sum; } <commit_msg>Add fix for Windows (definition of __func__ is in RooMath.h)<commit_after>/***************************************************************************** * Project: RooFit * * Package: RooFitModels * * @(#)root/roofit:$Id$ * Authors: * * GR, Gerhard Raven, UC San Diego, Gerhard.Raven@slac.stanford.edu * * * Copyright (c) 2000-2005, Regents of the University of California * * and Stanford University. All rights reserved. * * * * Redistribution and use in source and binary forms, * * with or without modification, are permitted according to the terms * * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ ////////////////////////////////////////////////////////////////////////////// // // BEGIN_HTML // Chebychev polynomial p.d.f. of the first kind // END_HTML // #include <cmath> #include <iostream> #include "RooFit.h" #include "Riostream.h" #include "RooChebychev.h" #include "RooAbsReal.h" #include "RooRealVar.h" #include "RooArgList.h" #include "RooMath.h" ClassImp(RooChebychev) ; //_____________________________________________________________________________ RooChebychev::RooChebychev() { } //_____________________________________________________________________________ RooChebychev::RooChebychev(const char* name, const char* title, RooAbsReal& x, const RooArgList& coefList): RooAbsPdf(name, title), _x("x", "Dependent", this, x), _coefList("coefficients","List of coefficients",this) { // Constructor TIterator* coefIter = coefList.createIterator() ; RooAbsArg* coef ; while((coef = (RooAbsArg*)coefIter->Next())) { if (!dynamic_cast<RooAbsReal*>(coef)) { std::cerr << "RooChebychev::ctor(" << GetName() << ") ERROR: coefficient " << coef->GetName() << " is not of type RooAbsReal" << std::endl ; assert(0) ; } _coefList.add(*coef) ; } delete coefIter ; } //_____________________________________________________________________________ RooChebychev::RooChebychev(const RooChebychev& other, const char* name) : RooAbsPdf(other, name), _x("x", this, other._x), _coefList("coefList",this,other._coefList) { } inline static double p0(double ,double a) { return a; } inline static double p1(double t,double a,double b) { return a*t+b; } inline static double p2(double t,double a,double b,double c) { return p1(t,p1(t,a,b),c); } inline static double p3(double t,double a,double b,double c,double d) { return p2(t,p1(t,a,b),c,d); } inline static double p4(double t,double a,double b,double c,double d,double e) { return p3(t,p1(t,a,b),c,d,e); } //_____________________________________________________________________________ Double_t RooChebychev::evaluate() const { Double_t xmin = _x.min(); Double_t xmax = _x.max(); Double_t x(-1+2*(_x-xmin)/(xmax-xmin)); Double_t x2(x*x); Double_t sum(0) ; switch (_coefList.getSize()) { case 7: sum+=((RooAbsReal&)_coefList[6]).getVal()*x*p3(x2,64,-112,56,-7); case 6: sum+=((RooAbsReal&)_coefList[5]).getVal()*p3(x2,32,-48,18,-1); case 5: sum+=((RooAbsReal&)_coefList[4]).getVal()*x*p2(x2,16,-20,5); case 4: sum+=((RooAbsReal&)_coefList[3]).getVal()*p2(x2,8,-8,1); case 3: sum+=((RooAbsReal&)_coefList[2]).getVal()*x*p1(x2,4,-3); case 2: sum+=((RooAbsReal&)_coefList[1]).getVal()*p1(x2,2,-1); case 1: sum+=((RooAbsReal&)_coefList[0]).getVal()*x; case 0: sum+=1; break; default: std::cerr << "In " << __func__ << " (" << __FILE__ << ", line " << __LINE__ << "): Higher order Chebychev polynomials currently " "unimplemented." << std::endl; assert(false); } return sum; } //_____________________________________________________________________________ Int_t RooChebychev::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* /* rangeName */) const { if (matchArgs(allVars, analVars, _x)) return 1; return 0; } //_____________________________________________________________________________ Double_t RooChebychev::analyticalIntegral(Int_t code, const char* rangeName) const { assert(1 == code); // the full range of the function is mapped to the normalised [-1, 1] range const Double_t xminfull(_x.min()), xmaxfull(_x.max()); const Double_t fullRange = xmaxfull - xminfull; // define limits of the integration range on a normalised scale Double_t minScaled = -1., maxScaled = +1.; // check to see if integral of a subrange is requested if (rangeName && 0 != rangeName[0]) { assert(xminfull <= _x.min(rangeName) && _x.min(rangeName) <= xmaxfull); assert(xminfull <= _x.max(rangeName) && _x.max(rangeName) <= xmaxfull); minScaled = -1. + 2. * (_x.min(rangeName) - xminfull) / fullRange; maxScaled = +1. - 2. * (xmaxfull - _x.max(rangeName)) / fullRange; } // return half of the range since the normalised range runs from -1 to 1 // which has a range of two return 0.5 * fullRange * (evalAnaInt(maxScaled) - evalAnaInt(minScaled)); } Double_t RooChebychev::evalAnaInt(const Double_t x) const { const Double_t x2 = x * x; Double_t sum = 0.; switch (_coefList.getSize()) { case 7: sum+=((RooAbsReal&)_coefList[6]).getVal()*x2*p3(x2,8.,-112./6.,14.,-7./2.); case 6: sum+=((RooAbsReal&)_coefList[5]).getVal()*x*p3(x2,32./7.,-48./5.,6.,-1.); case 5: sum+=((RooAbsReal&)_coefList[4]).getVal()*x2*p2(x2,16./6.,-5.,2.5); case 4: sum+=((RooAbsReal&)_coefList[3]).getVal()*x*p2(x2,8./5.,-8./3.,1.); case 3: sum+=((RooAbsReal&)_coefList[2]).getVal()*x2*p1(x2,1.,-3./2.); case 2: sum+=((RooAbsReal&)_coefList[1]).getVal()*x*p1(x2,2./3.,-1.); case 1: sum+=((RooAbsReal&)_coefList[0]).getVal()*x2*.5; case 0: sum+=x; break; default: std::cerr << "In " << __func__ << " (" << __FILE__ << ", line " << __LINE__ << "): Higher order Chebychev polynomials currently " "unimplemented." << std::endl; assert(false); } return sum; } <|endoftext|>
<commit_before>#include <cilantro/io.hpp> #include <cilantro/3rd_party/tinyply/tinyply.h> namespace cilantro { void readPointCloudFromPLYFile(const std::string &filename, PointCloud &cloud) { std::ifstream ss(filename, std::ios::binary); tinyply::PlyFile file(ss); // Data holders std::vector<float> vertex_data; std::vector<float> normal_data; std::vector<uint8_t> color_data; // Initialize PLY data holders size_t vertex_count = file.request_properties_from_element("vertex", {"x", "y", "z"}, vertex_data); size_t normal_count = file.request_properties_from_element("vertex", {"nx", "ny", "nz"}, normal_data); size_t color_count = file.request_properties_from_element("vertex", {"red", "green", "blue"}, color_data); // Read PLY data file.read(ss); // Populate cloud cloud.points.resize(vertex_count); std::memcpy(cloud.points.data(), vertex_data.data(), 3*vertex_count*sizeof(float)); cloud.normals.resize(normal_count); std::memcpy(cloud.normals.data(), normal_data.data(), 3*normal_count*sizeof(float)); cloud.colors.resize(color_count); for (int i = 0; i < color_count; i++) { cloud.colors[i] = Eigen::Vector3f(color_data[3*i], color_data[3*i+1], color_data[3*i+2])/255.0f; } } void writePointCloudToPLYFile(const std::string &filename, const PointCloud &cloud, bool binary) { std::vector<float> vertex_data(3*cloud.size()); std::memcpy(vertex_data.data(), cloud.points.data(), 3 * cloud.size() * sizeof(float)); // Write to file std::filebuf fb; fb.open(filename, std::ios::out | std::ios::binary); std::ostream output_stream(&fb); tinyply::PlyFile file_to_write; file_to_write.add_properties_to_element("vertex", {"x", "y", "z"}, vertex_data); std::vector<float> normal_data; if (cloud.hasNormals()) { normal_data.resize(3*cloud.normals.size()); std::memcpy(normal_data.data(), cloud.normals.data(), 3 * cloud.normals.size() * sizeof(float)); file_to_write.add_properties_to_element("vertex", {"nx", "ny", "nz"}, normal_data); } std::vector<uint8_t> color_data; if (cloud.hasColors()) { color_data.resize(3*cloud.colors.size()); for (int i = 0; i < cloud.colors.size(); i++) { color_data[3 * i + 0] = (uint8_t)(cloud.colors[i](0)*255.0f); color_data[3 * i + 1] = (uint8_t)(cloud.colors[i](1)*255.0f); color_data[3 * i + 2] = (uint8_t)(cloud.colors[i](2)*255.0f); } file_to_write.add_properties_to_element("vertex", {"red", "green", "blue"}, color_data); } file_to_write.write(output_stream, binary); fb.close(); } size_t getFileSizeInBytes(const std::string &file_name) { std::ifstream in(file_name, std::ifstream::ate | std::ifstream::binary); return in.tellg(); } size_t readRawDataFromFile(const std::string &file_name, void * data_ptr, size_t num_bytes) { size_t num_bytes_to_read = (num_bytes == 0) ? getFileSizeInBytes(file_name) : num_bytes; std::ifstream in(file_name, std::ios::in | std::ios::binary); in.read((char*)data_ptr, num_bytes_to_read); in.close(); return num_bytes_to_read; } void writeRawDataToFile(const std::string &file_name, void * data_ptr, size_t num_bytes) { std::ofstream out(file_name, std::ios::out | std::ios::binary); out.write((char*)data_ptr, num_bytes); out.close(); } } <commit_msg>Minor changes<commit_after>#include <cilantro/io.hpp> #include <cilantro/3rd_party/tinyply/tinyply.h> namespace cilantro { void readPointCloudFromPLYFile(const std::string &filename, PointCloud &cloud) { // Data holders std::vector<float> vertex_data; std::vector<float> normal_data; std::vector<uint8_t> color_data; std::ifstream ss(filename, std::ios::binary); tinyply::PlyFile file(ss); // Initialize PLY data holders size_t vertex_count = file.request_properties_from_element("vertex", {"x", "y", "z"}, vertex_data); size_t normal_count = file.request_properties_from_element("vertex", {"nx", "ny", "nz"}, normal_data); size_t color_count = file.request_properties_from_element("vertex", {"red", "green", "blue"}, color_data); // Read PLY data file.read(ss); // Populate cloud cloud.points.resize(vertex_count); std::memcpy(cloud.points.data(), vertex_data.data(), 3*vertex_count*sizeof(float)); cloud.normals.resize(normal_count); std::memcpy(cloud.normals.data(), normal_data.data(), 3*normal_count*sizeof(float)); cloud.colors.resize(color_count); for (int i = 0; i < color_count; i++) { cloud.colors[i] = Eigen::Vector3f(color_data[3*i], color_data[3*i+1], color_data[3*i+2])/255.0f; } } void writePointCloudToPLYFile(const std::string &filename, const PointCloud &cloud, bool binary) { tinyply::PlyFile file; std::vector<float> vertex_data(3*cloud.size()); std::memcpy(vertex_data.data(), cloud.points.data(), 3*cloud.size()*sizeof(float)); file.add_properties_to_element("vertex", {"x", "y", "z"}, vertex_data); std::vector<float> normal_data; if (cloud.hasNormals()) { normal_data.resize(3*cloud.normals.size()); std::memcpy(normal_data.data(), cloud.normals.data(), 3*cloud.normals.size()*sizeof(float)); file.add_properties_to_element("vertex", {"nx", "ny", "nz"}, normal_data); } std::vector<uint8_t> color_data; if (cloud.hasColors()) { color_data.resize(3*cloud.colors.size()); for (int i = 0; i < cloud.colors.size(); i++) { color_data[3 * i + 0] = (uint8_t)(cloud.colors[i](0)*255.0f); color_data[3 * i + 1] = (uint8_t)(cloud.colors[i](1)*255.0f); color_data[3 * i + 2] = (uint8_t)(cloud.colors[i](2)*255.0f); } file.add_properties_to_element("vertex", {"red", "green", "blue"}, color_data); } // Write to file std::filebuf fb; fb.open(filename, std::ios::out | std::ios::binary); std::ostream output_stream(&fb); file.write(output_stream, binary); fb.close(); } size_t getFileSizeInBytes(const std::string &file_name) { std::ifstream in(file_name, std::ifstream::ate | std::ifstream::binary); return in.tellg(); } size_t readRawDataFromFile(const std::string &file_name, void * data_ptr, size_t num_bytes) { size_t num_bytes_to_read = (num_bytes == 0) ? getFileSizeInBytes(file_name) : num_bytes; std::ifstream in(file_name, std::ios::in | std::ios::binary); in.read((char*)data_ptr, num_bytes_to_read); in.close(); return num_bytes_to_read; } void writeRawDataToFile(const std::string &file_name, void * data_ptr, size_t num_bytes) { std::ofstream out(file_name, std::ios::out | std::ios::binary); out.write((char*)data_ptr, num_bytes); out.close(); } } <|endoftext|>
<commit_before>/** * Self-Organizing Maps on a cluster * Copyright (C) 2013 Peter Wittek * * 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 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 GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <cmath> #include <sstream> #include <iostream> #include <fstream> #include "somoclu.h" using namespace std; /** Save a SOM codebook * @param cbFileName - name of the file to save * @param codebook - the codebook to save * @param nSomX - dimensions of SOM map in the x direction * @param nSomY - dimensions of SOM map in the y direction * @param nDimensions - dimensions of a data instance */ int saveCodebook(char* cbFileName, float *codebook, unsigned int nSomX, unsigned int nSomY, unsigned int nDimensions) { char temp[80]; cout << " Codebook file = " << cbFileName << endl; ofstream mapFile(cbFileName); cout << " Saving Codebook..." << endl; mapFile << "%" << nSomY << " " << nSomX << endl; mapFile << "%" << nDimensions << endl; if (mapFile.is_open()) { for (unsigned int som_y = 0; som_y < nSomY; som_y++) { for (unsigned int som_x = 0; som_x < nSomX; som_x++) { for (unsigned int d = 0; d < nDimensions; d++) { sprintf(temp, "%0.10f", codebook[som_y*nSomX*nDimensions+som_x*nDimensions+d]); mapFile << temp << " "; } mapFile << endl; } } mapFile.close(); return 0; } else { return 1; } } /** Euclidean distance between vec1 and vec2 * @param vec1 * @param vec2 * @param nDimensions * @return distance */ float get_distance(const float* vec1, const float* vec2, unsigned int nDimensions) { float distance = 0.0f; float x1 = 0.0f; float x2 = 0.0f; for (unsigned int d = 0; d < nDimensions; d++) { x1 = std::min(vec1[d], vec2[d]); x2 = std::max(vec1[d], vec2[d]); distance += std::abs(x1-x2)*std::abs(x1-x2); } return sqrt(distance); } /** Get weight vector from a codebook using x, y index * @param codebook - the codebook to save * @param som_y - y coordinate of a node in the map * @param som_x - x coordinate of a node in the map * @param nSomX - dimensions of SOM map in the x direction * @param nSomY - dimensions of SOM map in the y direction * @param nDimensions - dimensions of a data instance * @return the weight vector */ float* get_wvec(float *codebook, unsigned int som_y, unsigned int som_x, unsigned int nSomX, unsigned int nSomY, unsigned int nDimensions) { float* wvec = new float[nDimensions]; for (unsigned int d = 0; d < nDimensions; d++) wvec[d] = codebook[som_y*nSomX*nDimensions+som_x*nDimensions+d]; /// CAUTION: (y,x) order return wvec; } /** Save u-matrix * @param fname * @param codebook - the codebook to save * @param nSomX - dimensions of SOM map in the x direction * @param nSomY - dimensions of SOM map in the y direction * @param nDimensions - dimensions of a data instance */ int saveUMat(char* fname, float *codebook, unsigned int nSomX, unsigned int nSomY, unsigned int nDimensions, unsigned int mapType) { unsigned int D = 2; float min_dist = 1.5f; FILE* fp = fopen(fname, "wt"); fprintf(fp, "%%"); fprintf(fp, "%d %d", nSomY, nSomX); fprintf(fp, "\n"); if (fp != 0) { for (unsigned int som_y1 = 0; som_y1 < nSomY; som_y1++) { for (unsigned int som_x1 = 0; som_x1 < nSomX; som_x1++) { float dist = 0.0f; unsigned int nodes_number = 0; int coords1[2]; coords1[0] = som_x1; coords1[1] = som_y1; for (unsigned int som_y2 = 0; som_y2 < nSomY; som_y2++) { for (unsigned int som_x2 = 0; som_x2 < nSomX; som_x2++) { unsigned int coords2[2]; coords2[0] = som_x2; coords2[1] = som_y2; if (som_x1 == som_x2 && som_y1 == som_y2) continue; float tmp = 0.0f; if (mapType == PLANAR) { tmp = euclideanDistanceOnPlanarMap(som_x1, som_y1, som_x2, som_y2); } else if (mapType == TOROID) { tmp = euclideanDistanceOnToroidMap(som_x1, som_y1, som_x2, som_y2, nSomX, nSomY); } if (tmp <= min_dist) { nodes_number++; float* vec1 = get_wvec(codebook, som_y1, som_x1, nSomX, nSomY, nDimensions); float* vec2 = get_wvec(codebook, som_y2, som_x2, nSomX, nSomY, nDimensions); dist += get_distance(vec1, vec2, nDimensions); delete [] vec1; delete [] vec2; } } } dist /= (float)nodes_number; fprintf(fp, " %f", dist); } fprintf(fp, "\n"); } fclose(fp); return 0; } else return -2; } /** Reads a matrix * @param inFileNae * @param nRows - returns the number of rows * @param nColumns - returns the number of columns * @return the matrix */ float *readMatrix(const char *inFileName, unsigned int &nRows, unsigned int &nColumns) { ifstream file; file.open(inFileName); float *data=NULL; nRows = 0; if (file.is_open()){ string line; float tmp; while(getline(file,line)){ std::istringstream iss(line); if (nRows == 0){ while (iss >> tmp){ nColumns++; } } nRows++; } data=new float[nRows*nColumns]; file.close();file.open(inFileName); int j=0; while(getline(file,line)){ std::istringstream iss(line); while (iss >> tmp){ data[j++] = tmp; } } file.close(); } else { std::cerr << "Input file could not be opened!\n"; my_abort(-1); } return data; } void readSparseMatrixDimensions(const char *filename, unsigned int &nRows, unsigned int &nColumns) { ifstream file; file.open(filename); if (file.is_open()){ string line; int max_index=-1; while(getline(file,line)) { stringstream linestream(line); string value; int dummy_index; while(getline(linestream,value,' ')) { int separator=value.find(":"); istringstream myStream(value.substr(0,separator)); myStream >> dummy_index; if(dummy_index > max_index){ max_index = dummy_index; } } ++nRows; } nColumns=max_index+1; file.close(); } else { std::cerr << "Input file could not be opened!\n"; my_abort(-1); } } svm_node** readSparseMatrixChunk(const char *filename, unsigned int nRows, unsigned int nRowsToRead, unsigned int rowOffset) { ifstream file; file.open(filename); string line; for (unsigned int i=0; i<rowOffset; i++) { getline(file, line); } if (rowOffset+nRowsToRead >= nRows) { nRowsToRead = nRows-rowOffset; } svm_node **x_matrix = new svm_node *[nRowsToRead]; for(unsigned int i=0;i<nRowsToRead;i++) { getline(file, line); stringstream tmplinestream(line); string value; int elements = 0; while(getline(tmplinestream,value,' ')) { elements++; } elements++; // To account for the closing dummy node in the row x_matrix[i] = new svm_node[elements]; stringstream linestream(line); int j=0; while(getline(linestream,value,' ')) { int separator=value.find(":"); istringstream myStream(value.substr(0,separator)); myStream >> x_matrix[i][j].index; istringstream myStream2(value.substr(separator+1)); myStream2 >> x_matrix[i][j].value; j++; } x_matrix[i][j].index = -1; } file.close(); return x_matrix; } <commit_msg>ESOM lrn input format accepted<commit_after>/** * Self-Organizing Maps on a cluster * Copyright (C) 2013 Peter Wittek * * 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 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 GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <cmath> #include <sstream> #include <iostream> #include <fstream> #include <string.h> #include "somoclu.h" using namespace std; /** Save a SOM codebook * @param cbFileName - name of the file to save * @param codebook - the codebook to save * @param nSomX - dimensions of SOM map in the x direction * @param nSomY - dimensions of SOM map in the y direction * @param nDimensions - dimensions of a data instance */ int saveCodebook(char* cbFileName, float *codebook, unsigned int nSomX, unsigned int nSomY, unsigned int nDimensions) { char temp[80]; cout << " Codebook file = " << cbFileName << endl; ofstream mapFile(cbFileName); cout << " Saving Codebook..." << endl; mapFile << "%" << nSomY << " " << nSomX << endl; mapFile << "%" << nDimensions << endl; if (mapFile.is_open()) { for (unsigned int som_y = 0; som_y < nSomY; som_y++) { for (unsigned int som_x = 0; som_x < nSomX; som_x++) { for (unsigned int d = 0; d < nDimensions; d++) { sprintf(temp, "%0.10f", codebook[som_y*nSomX*nDimensions+som_x*nDimensions+d]); mapFile << temp << " "; } mapFile << endl; } } mapFile.close(); return 0; } else { return 1; } } /** Euclidean distance between vec1 and vec2 * @param vec1 * @param vec2 * @param nDimensions * @return distance */ float get_distance(const float* vec1, const float* vec2, unsigned int nDimensions) { float distance = 0.0f; float x1 = 0.0f; float x2 = 0.0f; for (unsigned int d = 0; d < nDimensions; d++) { x1 = std::min(vec1[d], vec2[d]); x2 = std::max(vec1[d], vec2[d]); distance += std::abs(x1-x2)*std::abs(x1-x2); } return sqrt(distance); } /** Get weight vector from a codebook using x, y index * @param codebook - the codebook to save * @param som_y - y coordinate of a node in the map * @param som_x - x coordinate of a node in the map * @param nSomX - dimensions of SOM map in the x direction * @param nSomY - dimensions of SOM map in the y direction * @param nDimensions - dimensions of a data instance * @return the weight vector */ float* get_wvec(float *codebook, unsigned int som_y, unsigned int som_x, unsigned int nSomX, unsigned int nSomY, unsigned int nDimensions) { float* wvec = new float[nDimensions]; for (unsigned int d = 0; d < nDimensions; d++) wvec[d] = codebook[som_y*nSomX*nDimensions+som_x*nDimensions+d]; /// CAUTION: (y,x) order return wvec; } /** Save u-matrix * @param fname * @param codebook - the codebook to save * @param nSomX - dimensions of SOM map in the x direction * @param nSomY - dimensions of SOM map in the y direction * @param nDimensions - dimensions of a data instance */ int saveUMat(char* fname, float *codebook, unsigned int nSomX, unsigned int nSomY, unsigned int nDimensions, unsigned int mapType) { unsigned int D = 2; float min_dist = 1.5f; FILE* fp = fopen(fname, "wt"); fprintf(fp, "%%"); fprintf(fp, "%d %d", nSomY, nSomX); fprintf(fp, "\n"); if (fp != 0) { for (unsigned int som_y1 = 0; som_y1 < nSomY; som_y1++) { for (unsigned int som_x1 = 0; som_x1 < nSomX; som_x1++) { float dist = 0.0f; unsigned int nodes_number = 0; int coords1[2]; coords1[0] = som_x1; coords1[1] = som_y1; for (unsigned int som_y2 = 0; som_y2 < nSomY; som_y2++) { for (unsigned int som_x2 = 0; som_x2 < nSomX; som_x2++) { unsigned int coords2[2]; coords2[0] = som_x2; coords2[1] = som_y2; if (som_x1 == som_x2 && som_y1 == som_y2) continue; float tmp = 0.0f; if (mapType == PLANAR) { tmp = euclideanDistanceOnPlanarMap(som_x1, som_y1, som_x2, som_y2); } else if (mapType == TOROID) { tmp = euclideanDistanceOnToroidMap(som_x1, som_y1, som_x2, som_y2, nSomX, nSomY); } if (tmp <= min_dist) { nodes_number++; float* vec1 = get_wvec(codebook, som_y1, som_x1, nSomX, nSomY, nDimensions); float* vec2 = get_wvec(codebook, som_y2, som_x2, nSomX, nSomY, nDimensions); dist += get_distance(vec1, vec2, nDimensions); delete [] vec1; delete [] vec2; } } } dist /= (float)nodes_number; fprintf(fp, " %f", dist); } fprintf(fp, "\n"); } fclose(fp); return 0; } else return -2; } bool isLrnFile(const char *inFileName) { unsigned int size = 0; while(inFileName[size++]!='\0') {} unsigned int testResult = strcmp("lrn\0", inFileName + size - 4); if (testResult == 0) { return true; } else { return false; } } /** Reads an ESOM lrn file * @param inFileNae * @param nRows - returns the number of rows * @param nColumns - returns the number of columns * @return the matrix */ float *readLrnFile(const char *inFileName, unsigned int &nRows, unsigned int &nColumns) { unsigned int nAllColumns = 0; float *data = NULL; ifstream file; file.open(inFileName); string line; float tmp; unsigned int j = 0; unsigned int currentColumn = 0; unsigned int *columnMap = NULL; while(getline(file,line)){ if (line.substr(0,1) == "#"){ continue; } if (line.substr(0,1) == "%"){ std::istringstream iss(line.substr(1,line.length())); if (nRows == 0) { iss >> nRows; } else if (nAllColumns == 0) { iss >> nAllColumns; } else if (columnMap == NULL) { columnMap = new unsigned int[nAllColumns]; unsigned int itmp = 0; currentColumn = 0; while (iss >> itmp){ columnMap[currentColumn++] = itmp; if (itmp == 1){ ++nColumns; } } } continue; } if (data == NULL) { data = new float[nRows*nColumns]; } std::istringstream iss(line); currentColumn = 0; while (iss >> tmp){ if (columnMap[currentColumn++] != 1) { continue; } data[j++] = tmp; } } file.close(); return data; } /** Reads a matrix * @param inFileNae * @param nRows - returns the number of rows * @param nColumns - returns the number of columns * @return the matrix */ float *readMatrix(const char *inFileName, unsigned int &nRows, unsigned int &nColumns) { if (isLrnFile(inFileName)) { return readLrnFile(inFileName, nRows, nColumns); } ifstream file; file.open(inFileName); float *data=NULL; if (file.is_open()){ string line; float tmp; while(getline(file,line)){ if (line.substr(0,1) == "#"){ continue; } std::istringstream iss(line); if (nRows == 0){ while (iss >> tmp){ nColumns++; } } nRows++; } data=new float[nRows*nColumns]; file.close();file.open(inFileName); int j=0; while(getline(file,line)){ if (line.substr(0,1) == "#"){ continue; } std::istringstream iss(line); while (iss >> tmp){ data[j++] = tmp; } } file.close(); } else { std::cerr << "Input file could not be opened!\n"; my_abort(-1); } return data; } void readSparseMatrixDimensions(const char *filename, unsigned int &nRows, unsigned int &nColumns) { ifstream file; file.open(filename); if (file.is_open()){ string line; int max_index=-1; while(getline(file,line)) { stringstream linestream(line); string value; int dummy_index; while(getline(linestream,value,' ')) { int separator=value.find(":"); istringstream myStream(value.substr(0,separator)); myStream >> dummy_index; if(dummy_index > max_index){ max_index = dummy_index; } } ++nRows; } nColumns=max_index+1; file.close(); } else { std::cerr << "Input file could not be opened!\n"; my_abort(-1); } } svm_node** readSparseMatrixChunk(const char *filename, unsigned int nRows, unsigned int nRowsToRead, unsigned int rowOffset) { ifstream file; file.open(filename); string line; for (unsigned int i=0; i<rowOffset; i++) { getline(file, line); } if (rowOffset+nRowsToRead >= nRows) { nRowsToRead = nRows-rowOffset; } svm_node **x_matrix = new svm_node *[nRowsToRead]; for(unsigned int i=0;i<nRowsToRead;i++) { getline(file, line); stringstream tmplinestream(line); string value; int elements = 0; while(getline(tmplinestream,value,' ')) { elements++; } elements++; // To account for the closing dummy node in the row x_matrix[i] = new svm_node[elements]; stringstream linestream(line); int j=0; while(getline(linestream,value,' ')) { int separator=value.find(":"); istringstream myStream(value.substr(0,separator)); myStream >> x_matrix[i][j].index; istringstream myStream2(value.substr(separator+1)); myStream2 >> x_matrix[i][j].value; j++; } x_matrix[i][j].index = -1; } file.close(); return x_matrix; } <|endoftext|>
<commit_before>/* * 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 3 of the License, or * (at your option) any later version. * * Written (W) 2012 Heiko Strathmann * * This file demonstrates how to use data generators based on the streaming * features framework */ #include <shogun/base/init.h> #include <shogun/features/streaming/generators/MeanShiftDataGenerator.h> using namespace shogun; void test_mean_shift() { index_t dimension=3; index_t mean_shift=100; index_t num_runs=1000; CMeanShiftDataGenerator<float64_t>* gen= new CMeanShiftDataGenerator<float64_t>(mean_shift, dimension); SGVector<float64_t> avg(dimension); avg.zero(); for (index_t i=0; i<num_runs; ++i) { gen->get_next_example(); avg.add(gen->get_vector()); } /* average */ avg.scale(1.0/num_runs); avg.display_vector("mean_shift"); /* roughly assert correct model parameters */ ASSERT(avg[0]-mean_shift<mean_shift/100); for (index_t i=1; i<dimension; ++i) ASSERT(avg[i]<0.5 && avg[i]>-0.5); SG_UNREF(gen); } int main(int argc, char** argv) { init_shogun_with_defaults(); test_mean_shift(); exit_shogun(); return 0; } <commit_msg>made example work<commit_after>/* * 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 3 of the License, or * (at your option) any later version. * * Written (W) 2012 Heiko Strathmann * * This file demonstrates how to use data generators based on the streaming * features framework */ #include <shogun/base/init.h> #include <shogun/features/streaming/generators/MeanShiftDataGenerator.h> using namespace shogun; void test_mean_shift() { index_t dimension=3; index_t mean_shift=100; index_t num_runs=1000; CMeanShiftDataGenerator<float64_t>* gen= new CMeanShiftDataGenerator<float64_t>(mean_shift, dimension); SGVector<float64_t> avg(dimension); avg.zero(); for (index_t i=0; i<num_runs; ++i) { gen->get_next_example(); avg.add(gen->get_vector()); gen->release_example(); } /* average */ avg.scale(1.0/num_runs); avg.display_vector("mean_shift"); /* roughly assert correct model parameters */ ASSERT(avg[0]-mean_shift<mean_shift/100); for (index_t i=1; i<dimension; ++i) ASSERT(avg[i]<0.5 && avg[i]>-0.5); /* draw whole matrix and test that too */ CDenseFeatures<float64_t>* features=(CDenseFeatures<float64_t>*) gen->get_streamed_features(num_runs); avg=SGVector<float64_t>(dimension); for (index_t i=0; i<dimension; ++i) { float64_t sum=0; for (index_t j=0; j<num_runs; ++j) sum+=features->get_feature_matrix()(i, j); avg[i]=sum/num_runs; } avg.display_vector("mean_shift"); ASSERT(avg[0]-mean_shift<mean_shift/100); for (index_t i=1; i<dimension; ++i) ASSERT(avg[i]<0.5 && avg[i]>-0.5); SG_UNREF(features); SG_UNREF(gen); } int main(int argc, char** argv) { init_shogun_with_defaults(); test_mean_shift(); exit_shogun(); return 0; } <|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/touch/frame/keyboard_container_view.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/views/dom_view.h" #include "chrome/common/url_constants.h" #include "content/browser/site_instance.h" #include "content/browser/tab_contents/tab_contents.h" namespace { // Make the provided view and all of its descendents unfocusable. void MakeViewHierarchyUnfocusable(views::View* view) { view->set_focusable(false); for (int i = 0; i < view->child_count(); ++i) { MakeViewHierarchyUnfocusable(view->GetChildViewAt(i)); } } } // namepsace // static const char KeyboardContainerView::kViewClassName[] = "browser/ui/touch/frame/KeyboardContainerView"; /////////////////////////////////////////////////////////////////////////////// // KeyboardContainerView, public: KeyboardContainerView::KeyboardContainerView(Profile* profile, Browser* browser) : dom_view_(new DOMView), ALLOW_THIS_IN_INITIALIZER_LIST( extension_function_dispatcher_(profile, this)), browser_(browser) { GURL keyboard_url(chrome::kChromeUIKeyboardURL); dom_view_->Init(profile, SiteInstance::CreateSiteInstanceForURL(profile, keyboard_url)); dom_view_->LoadURL(keyboard_url); dom_view_->SetVisible(true); AddChildView(dom_view_); // We have Inited the dom_view. So we must have a tab contents. Observe(dom_view_->tab_contents()); } KeyboardContainerView::~KeyboardContainerView() { } std::string KeyboardContainerView::GetClassName() const { return kViewClassName; } void KeyboardContainerView::Layout() { // TODO(bryeung): include a border between the keyboard and the client view dom_view_->SetBounds(0, 0, width(), height()); } Browser* KeyboardContainerView::GetBrowser() { return browser_; } gfx::NativeView KeyboardContainerView::GetNativeViewOfHost() { return dom_view_->native_view(); } TabContents* KeyboardContainerView::GetAssociatedTabContents() const { return dom_view_->tab_contents(); } void KeyboardContainerView::ViewHierarchyChanged(bool is_add, View* parent, View* child) { if (is_add) MakeViewHierarchyUnfocusable(child); } bool KeyboardContainerView::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(KeyboardContainerView, message) IPC_MESSAGE_HANDLER(ExtensionHostMsg_Request, OnRequest) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void KeyboardContainerView::OnRequest( const ExtensionHostMsg_Request_Params& request) { extension_function_dispatcher_.Dispatch(request, dom_view_->tab_contents()->render_view_host()); } <commit_msg>keyboard: Fix unfocusing child views.<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/touch/frame/keyboard_container_view.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/views/dom_view.h" #include "chrome/common/url_constants.h" #include "content/browser/site_instance.h" #include "content/browser/tab_contents/tab_contents.h" namespace { // Make the provided view and all of its descendents unfocusable. void MakeViewHierarchyUnfocusable(views::View* view) { view->set_focusable(false); for (int i = 0; i < view->child_count(); ++i) { MakeViewHierarchyUnfocusable(view->GetChildViewAt(i)); } } } // namepsace // static const char KeyboardContainerView::kViewClassName[] = "browser/ui/touch/frame/KeyboardContainerView"; /////////////////////////////////////////////////////////////////////////////// // KeyboardContainerView, public: KeyboardContainerView::KeyboardContainerView(Profile* profile, Browser* browser) : dom_view_(new DOMView), ALLOW_THIS_IN_INITIALIZER_LIST( extension_function_dispatcher_(profile, this)), browser_(browser) { GURL keyboard_url(chrome::kChromeUIKeyboardURL); dom_view_->Init(profile, SiteInstance::CreateSiteInstanceForURL(profile, keyboard_url)); dom_view_->LoadURL(keyboard_url); dom_view_->SetVisible(true); AddChildView(dom_view_); // We have Inited the dom_view. So we must have a tab contents. Observe(dom_view_->tab_contents()); } KeyboardContainerView::~KeyboardContainerView() { } std::string KeyboardContainerView::GetClassName() const { return kViewClassName; } void KeyboardContainerView::Layout() { // TODO(bryeung): include a border between the keyboard and the client view dom_view_->SetBounds(0, 0, width(), height()); } Browser* KeyboardContainerView::GetBrowser() { return browser_; } gfx::NativeView KeyboardContainerView::GetNativeViewOfHost() { return dom_view_->native_view(); } TabContents* KeyboardContainerView::GetAssociatedTabContents() const { return dom_view_->tab_contents(); } void KeyboardContainerView::ViewHierarchyChanged(bool is_add, View* parent, View* child) { if (is_add && parent == this) MakeViewHierarchyUnfocusable(child); } bool KeyboardContainerView::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(KeyboardContainerView, message) IPC_MESSAGE_HANDLER(ExtensionHostMsg_Request, OnRequest) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void KeyboardContainerView::OnRequest( const ExtensionHostMsg_Request_Params& request) { extension_function_dispatcher_.Dispatch(request, dom_view_->tab_contents()->render_view_host()); } <|endoftext|>
<commit_before>#include "mesh_def.h" #include <vcg/complex/algorithms/refine.h> #include <vcg/complex/algorithms/refine_loop.h> using namespace vcg; using namespace std; void RefineMesh(uintptr_t _baseM, int step, int alg) { MyMesh &m = *((MyMesh*) _baseM); tri::UpdateTopology<MyMesh>::FaceFace(m); switch(alg) { case 0: // MidPoint { tri::MidPoint<MyMesh> MidPointFun(&m); tri::EdgeLen<MyMesh,float> edgePred(0); for(int i=0;i<step;i++) tri::RefineE(m,MidPointFun,edgePred); } break; case 1: // Butterfly { for(int i=0;i<step;i++) tri::Refine<MyMesh,tri::MidPointButterfly<MyMesh> > (m, tri::MidPointButterfly<MyMesh>(m), 0, false,0); } break; case 2:// Loop { for(int i=0;i<step;i++) tri::RefineOddEven<MyMesh>(m, tri::OddPointLoop<MyMesh>(m), tri::EvenPointLoop<MyMesh>(), 0, false, 0); } break; } printf("Refined mesh %i vert - %i face \n",m.VN(),m.FN()); } #ifdef __EMSCRIPTEN__ //Binding code using namespace emscripten; EMSCRIPTEN_BINDINGS(MLRefinePlugin) { emscripten::function("RefineMesh", &RefineMesh); } #endif <commit_msg>Corrected refine bug (issue #45)<commit_after>#include "mesh_def.h" #include <vcg/complex/algorithms/refine.h> #include <vcg/complex/algorithms/refine_loop.h> using namespace vcg; using namespace std; void RefineMesh(uintptr_t _baseM, int step, int alg) { MyMesh &m = *((MyMesh*) _baseM); tri::UpdateTopology<MyMesh>::FaceFace(m); int nonManifCount = tri::Clean<MyMesh>::CountNonManifoldEdgeFF(m); if(nonManifCount > 0) { printf("Refinement algorithms can be applied only on 2-manifold meshes. Current mesh has %i non manifold edges\n",nonManifCount); return; } switch(alg) { case 0: // MidPoint { tri::MidPoint<MyMesh> MidPointFun(&m); tri::EdgeLen<MyMesh,float> edgePred(0); for(int i=0;i<step;i++) tri::RefineE(m,MidPointFun,edgePred); } break; case 1: // Butterfly { for(int i=0;i<step;i++) tri::Refine<MyMesh,tri::MidPointButterfly<MyMesh> > (m, tri::MidPointButterfly<MyMesh>(m), 0, false,0); } break; case 2:// Loop { for(int i=0;i<step;i++) tri::RefineOddEven<MyMesh>(m, tri::OddPointLoop<MyMesh>(m), tri::EvenPointLoop<MyMesh>(), 0, false, 0); } break; } printf("Refined mesh %i vert - %i face \n",m.VN(),m.FN()); } #ifdef __EMSCRIPTEN__ //Binding code using namespace emscripten; EMSCRIPTEN_BINDINGS(MLRefinePlugin) { emscripten::function("RefineMesh", &RefineMesh); } #endif <|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * 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. * #L% */ #include "runtimes/libjoynr-runtime/LibJoynrRuntime.h" #include <cassert> #include <memory> #include <vector> #include "joynr/Dispatcher.h" #include "joynr/InProcessDispatcher.h" #include "joynr/IMulticastAddressCalculator.h" #include "joynr/system/RoutingTypes/CommonApiDbusAddress.h" #include "joynr/PublicationManager.h" #include "joynr/SubscriptionManager.h" #include "joynr/InProcessPublicationSender.h" #include "joynr/JoynrMessageSender.h" #include "joynr/LibJoynrMessageRouter.h" #include "libjoynr/in-process/InProcessLibJoynrMessagingSkeleton.h" #include "joynr/InProcessMessagingAddress.h" #include "joynr/MessagingStubFactory.h" #include "libjoynr/in-process/InProcessMessagingStubFactory.h" #include "joynr/system/DiscoveryProxy.h" #include "joynr/system/RoutingProxy.h" #include "joynr/Util.h" #include "joynr/Settings.h" #include "joynr/SingleThreadedIOService.h" namespace joynr { LibJoynrRuntime::LibJoynrRuntime(std::unique_ptr<Settings> settings) : JoynrRuntime(*settings), subscriptionManager(nullptr), inProcessPublicationSender(nullptr), joynrMessagingSendStub(nullptr), joynrMessageSender(nullptr), joynrDispatcher(nullptr), inProcessDispatcher(nullptr), settings(std::move(settings)), libjoynrSettings(new LibjoynrSettings(*this->settings)), dispatcherMessagingSkeleton(nullptr), libJoynrMessageRouter(nullptr) { libjoynrSettings->printSettings(); singleThreadIOService->start(); } LibJoynrRuntime::~LibJoynrRuntime() { if (inProcessDispatcher) { delete inProcessDispatcher; inProcessDispatcher = nullptr; } if (joynrDispatcher) { delete joynrDispatcher; joynrDispatcher = nullptr; } if (libjoynrSettings) { delete libjoynrSettings; libjoynrSettings = nullptr; } if (inProcessPublicationSender) { delete inProcessPublicationSender; inProcessPublicationSender = nullptr; } } void LibJoynrRuntime::init( std::shared_ptr<IMiddlewareMessagingStubFactory> middlewareMessagingStubFactory, std::shared_ptr<const joynr::system::RoutingTypes::Address> libjoynrMessagingAddress, std::shared_ptr<const joynr::system::RoutingTypes::Address> ccMessagingAddress, std::unique_ptr<IMulticastAddressCalculator> addressCalculator, std::function<void()> onSuccess, std::function<void(const joynr::exceptions::JoynrRuntimeException&)> onError) { // create messaging stub factory auto messagingStubFactory = std::make_shared<MessagingStubFactory>(); middlewareMessagingStubFactory->registerOnMessagingStubClosedCallback([messagingStubFactory]( const std::shared_ptr<const joynr::system::RoutingTypes::Address>& destinationAddress) { messagingStubFactory->remove(destinationAddress); }); messagingStubFactory->registerStubFactory(middlewareMessagingStubFactory); messagingStubFactory->registerStubFactory(std::make_shared<InProcessMessagingStubFactory>()); // create message router libJoynrMessageRouter = std::make_shared<LibJoynrMessageRouter>(libjoynrMessagingAddress, std::move(messagingStubFactory), singleThreadIOService->getIOService(), std::move(addressCalculator)); libJoynrMessageRouter->loadRoutingTable( libjoynrSettings->getMessageRouterPersistenceFilename()); startLibJoynrMessagingSkeleton(libJoynrMessageRouter); joynrMessageSender = std::make_shared<JoynrMessageSender>( libJoynrMessageRouter, messagingSettings.getTtlUpliftMs()); joynrDispatcher = new Dispatcher(joynrMessageSender, singleThreadIOService->getIOService()); joynrMessageSender->registerDispatcher(joynrDispatcher); // create the inprocess skeleton for the dispatcher dispatcherMessagingSkeleton = std::make_shared<InProcessLibJoynrMessagingSkeleton>(joynrDispatcher); dispatcherAddress = std::make_shared<InProcessMessagingAddress>(dispatcherMessagingSkeleton); publicationManager = new PublicationManager(singleThreadIOService->getIOService(), joynrMessageSender.get(), messagingSettings.getTtlUpliftMs()); publicationManager->loadSavedAttributeSubscriptionRequestsMap( libjoynrSettings->getSubscriptionRequestPersistenceFilename()); publicationManager->loadSavedBroadcastSubscriptionRequestsMap( libjoynrSettings->getBroadcastSubscriptionRequestPersistenceFilename()); subscriptionManager = std::make_shared<SubscriptionManager>( singleThreadIOService->getIOService(), libJoynrMessageRouter); inProcessDispatcher = new InProcessDispatcher(singleThreadIOService->getIOService()); inProcessPublicationSender = new InProcessPublicationSender(subscriptionManager); auto inProcessConnectorFactory = std::make_unique<InProcessConnectorFactory>( subscriptionManager.get(), publicationManager, inProcessPublicationSender, dynamic_cast<IRequestCallerDirectory*>(inProcessDispatcher)); auto joynrMessagingConnectorFactory = std::make_unique<JoynrMessagingConnectorFactory>( joynrMessageSender, subscriptionManager); auto connectorFactory = std::make_unique<ConnectorFactory>( std::move(inProcessConnectorFactory), std::move(joynrMessagingConnectorFactory)); proxyFactory = std::make_unique<ProxyFactory>(libjoynrMessagingAddress, std::move(connectorFactory)); // Set up the persistence file for storing provider participant ids std::string persistenceFilename = libjoynrSettings->getParticipantIdsPersistenceFilename(); participantIdStorage = std::make_shared<ParticipantIdStorage>(persistenceFilename); // initialize the dispatchers std::vector<IDispatcher*> dispatcherList; dispatcherList.push_back(inProcessDispatcher); dispatcherList.push_back(joynrDispatcher); joynrDispatcher->registerPublicationManager(publicationManager); joynrDispatcher->registerSubscriptionManager(subscriptionManager); discoveryProxy = std::make_unique<LocalDiscoveryAggregator>(getProvisionedEntries()); requestCallerDirectory = dynamic_cast<IRequestCallerDirectory*>(inProcessDispatcher); std::string systemServicesDomain = systemServicesSettings.getDomain(); std::string routingProviderParticipantId = systemServicesSettings.getCcRoutingProviderParticipantId(); DiscoveryQos routingProviderDiscoveryQos; routingProviderDiscoveryQos.setCacheMaxAgeMs(1000); routingProviderDiscoveryQos.setArbitrationStrategy( DiscoveryQos::ArbitrationStrategy::FIXED_PARTICIPANT); routingProviderDiscoveryQos.addCustomParameter( "fixedParticipantId", routingProviderParticipantId); routingProviderDiscoveryQos.setDiscoveryTimeoutMs(50); std::unique_ptr<ProxyBuilder<joynr::system::RoutingProxy>> routingProxyBuilder = createProxyBuilder<joynr::system::RoutingProxy>(systemServicesDomain); auto routingProxy = routingProxyBuilder->setMessagingQos(MessagingQos(10000)) ->setDiscoveryQos(routingProviderDiscoveryQos) ->build(); libJoynrMessageRouter->setParentRouter( std::move(routingProxy), ccMessagingAddress, routingProviderParticipantId); // setup discovery std::string discoveryProviderParticipantId = systemServicesSettings.getCcDiscoveryProviderParticipantId(); DiscoveryQos discoveryProviderDiscoveryQos; discoveryProviderDiscoveryQos.setCacheMaxAgeMs(1000); discoveryProviderDiscoveryQos.setArbitrationStrategy( DiscoveryQos::ArbitrationStrategy::FIXED_PARTICIPANT); discoveryProviderDiscoveryQos.addCustomParameter( "fixedParticipantId", discoveryProviderParticipantId); discoveryProviderDiscoveryQos.setDiscoveryTimeoutMs(1000); std::unique_ptr<ProxyBuilder<joynr::system::DiscoveryProxy>> discoveryProxyBuilder = createProxyBuilder<joynr::system::DiscoveryProxy>(systemServicesDomain); auto proxy = discoveryProxyBuilder->setMessagingQos(MessagingQos(40000)) ->setDiscoveryQos(discoveryProviderDiscoveryQos) ->build(); discoveryProxy->setDiscoveryProxy(std::move(proxy)); capabilitiesRegistrar = std::make_unique<CapabilitiesRegistrar>( dispatcherList, *discoveryProxy, participantIdStorage, dispatcherAddress, libJoynrMessageRouter, messagingSettings.getDiscoveryEntryExpiryIntervalMs(), *publicationManager); libJoynrMessageRouter->queryGlobalClusterControllerAddress( std::move(onSuccess), std::move(onError)); } std::shared_ptr<IMessageRouter> LibJoynrRuntime::getMessageRouter() { return libJoynrMessageRouter; } } // namespace joynr <commit_msg>[C++] shutdown LibJoynrMessageRouter when destructing LibJoynrRuntime<commit_after>/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * 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. * #L% */ #include "runtimes/libjoynr-runtime/LibJoynrRuntime.h" #include <cassert> #include <memory> #include <vector> #include "joynr/Dispatcher.h" #include "joynr/InProcessDispatcher.h" #include "joynr/IMulticastAddressCalculator.h" #include "joynr/system/RoutingTypes/CommonApiDbusAddress.h" #include "joynr/PublicationManager.h" #include "joynr/SubscriptionManager.h" #include "joynr/InProcessPublicationSender.h" #include "joynr/JoynrMessageSender.h" #include "joynr/LibJoynrMessageRouter.h" #include "libjoynr/in-process/InProcessLibJoynrMessagingSkeleton.h" #include "joynr/InProcessMessagingAddress.h" #include "joynr/MessagingStubFactory.h" #include "libjoynr/in-process/InProcessMessagingStubFactory.h" #include "joynr/system/DiscoveryProxy.h" #include "joynr/system/RoutingProxy.h" #include "joynr/Util.h" #include "joynr/Settings.h" #include "joynr/SingleThreadedIOService.h" namespace joynr { LibJoynrRuntime::LibJoynrRuntime(std::unique_ptr<Settings> settings) : JoynrRuntime(*settings), subscriptionManager(nullptr), inProcessPublicationSender(nullptr), joynrMessagingSendStub(nullptr), joynrMessageSender(nullptr), joynrDispatcher(nullptr), inProcessDispatcher(nullptr), settings(std::move(settings)), libjoynrSettings(new LibjoynrSettings(*this->settings)), dispatcherMessagingSkeleton(nullptr), libJoynrMessageRouter(nullptr) { libjoynrSettings->printSettings(); singleThreadIOService->start(); } LibJoynrRuntime::~LibJoynrRuntime() { if (inProcessDispatcher) { delete inProcessDispatcher; inProcessDispatcher = nullptr; } if (joynrDispatcher) { delete joynrDispatcher; joynrDispatcher = nullptr; } if (libjoynrSettings) { delete libjoynrSettings; libjoynrSettings = nullptr; } if (inProcessPublicationSender) { delete inProcessPublicationSender; inProcessPublicationSender = nullptr; } if (libJoynrMessageRouter) { libJoynrMessageRouter->shutdown(); } } void LibJoynrRuntime::init( std::shared_ptr<IMiddlewareMessagingStubFactory> middlewareMessagingStubFactory, std::shared_ptr<const joynr::system::RoutingTypes::Address> libjoynrMessagingAddress, std::shared_ptr<const joynr::system::RoutingTypes::Address> ccMessagingAddress, std::unique_ptr<IMulticastAddressCalculator> addressCalculator, std::function<void()> onSuccess, std::function<void(const joynr::exceptions::JoynrRuntimeException&)> onError) { // create messaging stub factory auto messagingStubFactory = std::make_shared<MessagingStubFactory>(); middlewareMessagingStubFactory->registerOnMessagingStubClosedCallback([messagingStubFactory]( const std::shared_ptr<const joynr::system::RoutingTypes::Address>& destinationAddress) { messagingStubFactory->remove(destinationAddress); }); messagingStubFactory->registerStubFactory(middlewareMessagingStubFactory); messagingStubFactory->registerStubFactory(std::make_shared<InProcessMessagingStubFactory>()); // create message router libJoynrMessageRouter = std::make_shared<LibJoynrMessageRouter>(libjoynrMessagingAddress, std::move(messagingStubFactory), singleThreadIOService->getIOService(), std::move(addressCalculator)); libJoynrMessageRouter->loadRoutingTable( libjoynrSettings->getMessageRouterPersistenceFilename()); startLibJoynrMessagingSkeleton(libJoynrMessageRouter); joynrMessageSender = std::make_shared<JoynrMessageSender>( libJoynrMessageRouter, messagingSettings.getTtlUpliftMs()); joynrDispatcher = new Dispatcher(joynrMessageSender, singleThreadIOService->getIOService()); joynrMessageSender->registerDispatcher(joynrDispatcher); // create the inprocess skeleton for the dispatcher dispatcherMessagingSkeleton = std::make_shared<InProcessLibJoynrMessagingSkeleton>(joynrDispatcher); dispatcherAddress = std::make_shared<InProcessMessagingAddress>(dispatcherMessagingSkeleton); publicationManager = new PublicationManager(singleThreadIOService->getIOService(), joynrMessageSender.get(), messagingSettings.getTtlUpliftMs()); publicationManager->loadSavedAttributeSubscriptionRequestsMap( libjoynrSettings->getSubscriptionRequestPersistenceFilename()); publicationManager->loadSavedBroadcastSubscriptionRequestsMap( libjoynrSettings->getBroadcastSubscriptionRequestPersistenceFilename()); subscriptionManager = std::make_shared<SubscriptionManager>( singleThreadIOService->getIOService(), libJoynrMessageRouter); inProcessDispatcher = new InProcessDispatcher(singleThreadIOService->getIOService()); inProcessPublicationSender = new InProcessPublicationSender(subscriptionManager); auto inProcessConnectorFactory = std::make_unique<InProcessConnectorFactory>( subscriptionManager.get(), publicationManager, inProcessPublicationSender, dynamic_cast<IRequestCallerDirectory*>(inProcessDispatcher)); auto joynrMessagingConnectorFactory = std::make_unique<JoynrMessagingConnectorFactory>( joynrMessageSender, subscriptionManager); auto connectorFactory = std::make_unique<ConnectorFactory>( std::move(inProcessConnectorFactory), std::move(joynrMessagingConnectorFactory)); proxyFactory = std::make_unique<ProxyFactory>(libjoynrMessagingAddress, std::move(connectorFactory)); // Set up the persistence file for storing provider participant ids std::string persistenceFilename = libjoynrSettings->getParticipantIdsPersistenceFilename(); participantIdStorage = std::make_shared<ParticipantIdStorage>(persistenceFilename); // initialize the dispatchers std::vector<IDispatcher*> dispatcherList; dispatcherList.push_back(inProcessDispatcher); dispatcherList.push_back(joynrDispatcher); joynrDispatcher->registerPublicationManager(publicationManager); joynrDispatcher->registerSubscriptionManager(subscriptionManager); discoveryProxy = std::make_unique<LocalDiscoveryAggregator>(getProvisionedEntries()); requestCallerDirectory = dynamic_cast<IRequestCallerDirectory*>(inProcessDispatcher); std::string systemServicesDomain = systemServicesSettings.getDomain(); std::string routingProviderParticipantId = systemServicesSettings.getCcRoutingProviderParticipantId(); DiscoveryQos routingProviderDiscoveryQos; routingProviderDiscoveryQos.setCacheMaxAgeMs(1000); routingProviderDiscoveryQos.setArbitrationStrategy( DiscoveryQos::ArbitrationStrategy::FIXED_PARTICIPANT); routingProviderDiscoveryQos.addCustomParameter( "fixedParticipantId", routingProviderParticipantId); routingProviderDiscoveryQos.setDiscoveryTimeoutMs(50); std::unique_ptr<ProxyBuilder<joynr::system::RoutingProxy>> routingProxyBuilder = createProxyBuilder<joynr::system::RoutingProxy>(systemServicesDomain); auto routingProxy = routingProxyBuilder->setMessagingQos(MessagingQos(10000)) ->setDiscoveryQos(routingProviderDiscoveryQos) ->build(); libJoynrMessageRouter->setParentRouter( std::move(routingProxy), ccMessagingAddress, routingProviderParticipantId); // setup discovery std::string discoveryProviderParticipantId = systemServicesSettings.getCcDiscoveryProviderParticipantId(); DiscoveryQos discoveryProviderDiscoveryQos; discoveryProviderDiscoveryQos.setCacheMaxAgeMs(1000); discoveryProviderDiscoveryQos.setArbitrationStrategy( DiscoveryQos::ArbitrationStrategy::FIXED_PARTICIPANT); discoveryProviderDiscoveryQos.addCustomParameter( "fixedParticipantId", discoveryProviderParticipantId); discoveryProviderDiscoveryQos.setDiscoveryTimeoutMs(1000); std::unique_ptr<ProxyBuilder<joynr::system::DiscoveryProxy>> discoveryProxyBuilder = createProxyBuilder<joynr::system::DiscoveryProxy>(systemServicesDomain); auto proxy = discoveryProxyBuilder->setMessagingQos(MessagingQos(40000)) ->setDiscoveryQos(discoveryProviderDiscoveryQos) ->build(); discoveryProxy->setDiscoveryProxy(std::move(proxy)); capabilitiesRegistrar = std::make_unique<CapabilitiesRegistrar>( dispatcherList, *discoveryProxy, participantIdStorage, dispatcherAddress, libJoynrMessageRouter, messagingSettings.getDiscoveryEntryExpiryIntervalMs(), *publicationManager); libJoynrMessageRouter->queryGlobalClusterControllerAddress( std::move(onSuccess), std::move(onError)); } std::shared_ptr<IMessageRouter> LibJoynrRuntime::getMessageRouter() { return libJoynrMessageRouter; } } // namespace joynr <|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 "base/gfx/gtk_util.h" #include <gdk/gdk.h> #include <gtk/gtk.h> #include <stdlib.h> #include "base/gfx/rect.h" #include "base/linux_util.h" #include "third_party/skia/include/core/SkBitmap.h" namespace { void FreePixels(guchar* pixels, gpointer data) { free(data); } } // namespace namespace gfx { const GdkColor kGdkWhite = GDK_COLOR_RGB(0xff, 0xff, 0xff); const GdkColor kGdkBlack = GDK_COLOR_RGB(0x00, 0x00, 0x00); const GdkColor kGdkGreen = GDK_COLOR_RGB(0x00, 0xff, 0x00); GdkPixbuf* GdkPixbufFromSkBitmap(const SkBitmap* bitmap) { bitmap->lockPixels(); int width = bitmap->width(); int height = bitmap->height(); int stride = bitmap->rowBytes(); const guchar* orig_data = static_cast<guchar*>(bitmap->getPixels()); guchar* data = base::BGRAToRGBA(orig_data, width, height, stride); // This pixbuf takes ownership of our malloc()ed data and will // free it for us when it is destroyed. GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data( data, GDK_COLORSPACE_RGB, // The only colorspace gtk supports. true, // There is an alpha channel. 8, width, height, stride, &FreePixels, data); bitmap->unlockPixels(); return pixbuf; } void SubtractRectanglesFromRegion(GdkRegion* region, const std::vector<Rect>& cutouts) { for (size_t i = 0; i < cutouts.size(); ++i) { GdkRectangle rect = cutouts[i].ToGdkRectangle(); GdkRegion* rect_region = gdk_region_rectangle(&rect); gdk_region_subtract(region, rect_region); // TODO(deanm): It would be nice to be able to reuse the GdkRegion here. gdk_region_destroy(rect_region); } } } // namespace gfx <commit_msg>GdkPixbufFromSkBitmap needs to un-premultiply the alpha before passing off the data to gdk_pixbuf. This is required in the theme code for tinted bitmaps.<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 "base/gfx/gtk_util.h" #include <gdk/gdk.h> #include <gtk/gtk.h> #include <stdlib.h> #include "base/basictypes.h" #include "base/gfx/rect.h" #include "base/linux_util.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkUnPreMultiply.h" namespace { void FreePixels(guchar* pixels, gpointer data) { free(data); } } // namespace namespace gfx { const GdkColor kGdkWhite = GDK_COLOR_RGB(0xff, 0xff, 0xff); const GdkColor kGdkBlack = GDK_COLOR_RGB(0x00, 0x00, 0x00); const GdkColor kGdkGreen = GDK_COLOR_RGB(0x00, 0xff, 0x00); GdkPixbuf* GdkPixbufFromSkBitmap(const SkBitmap* bitmap) { bitmap->lockPixels(); int width = bitmap->width(); int height = bitmap->height(); int stride = bitmap->rowBytes(); // SkBitmaps are premultiplied, we need to unpremultiply them. const int kBytesPerPixel = 4; uint8* divided = static_cast<uint8*>(malloc(height * stride)); for (int y = 0, i = 0; y < height; y++) { for (int x = 0; x < width; x++) { uint32 pixel = bitmap->getAddr32(0, y)[x]; int alpha = SkColorGetA(pixel); if (alpha != 0 && alpha != 255) { SkColor unmultiplied = SkUnPreMultiply::PMColorToColor(pixel); divided[i + 0] = SkColorGetR(unmultiplied); divided[i + 1] = SkColorGetG(unmultiplied); divided[i + 2] = SkColorGetB(unmultiplied); divided[i + 3] = alpha; } else { divided[i + 0] = SkColorGetR(pixel); divided[i + 1] = SkColorGetG(pixel); divided[i + 2] = SkColorGetB(pixel); divided[i + 3] = alpha; } i += kBytesPerPixel; } } // This pixbuf takes ownership of our malloc()ed data and will // free it for us when it is destroyed. GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data( divided, GDK_COLORSPACE_RGB, // The only colorspace gtk supports. true, // There is an alpha channel. 8, width, height, stride, &FreePixels, divided); bitmap->unlockPixels(); return pixbuf; } void SubtractRectanglesFromRegion(GdkRegion* region, const std::vector<Rect>& cutouts) { for (size_t i = 0; i < cutouts.size(); ++i) { GdkRectangle rect = cutouts[i].ToGdkRectangle(); GdkRegion* rect_region = gdk_region_rectangle(&rect); gdk_region_subtract(region, rect_region); // TODO(deanm): It would be nice to be able to reuse the GdkRegion here. gdk_region_destroy(rect_region); } } } // namespace gfx <|endoftext|>
<commit_before>// // main.c // test_despot // // Created by Tobias Wood on 17/08/2012. // Copyright (c) 2012 Tobias Wood. All rights reserved. // #include <getopt.h> #include <vector> #include <string> #include "RegionContraction.h" //#include "DESPOT_Functors.h" #include "NiftiImage.h" #include "procpar.h" static int components = 1, tesla = 7; static std::string outPrefix; static bool testSpeed = false, testFiles = false; static struct option long_options[] = { {"components", required_argument, 0, 'c'}, {"speed", no_argument, 0, 's'}, {"files", no_argument, 0, 'f'}, {"tesla", required_argument, 0, 't'}, {0, 0, 0, 0} }; using namespace std; int main(int argc, char **argv) { ArrayXd data(50000); data.setRandom(); vector<size_t> indices; for (int i = 0; i < 100; i++) { indices = arg_partial_sort(data, 1000); } /*int indexptr = 0, c; while ((c = getopt_long(argc, argv, "c:sf", long_options, &indexptr)) != -1) { switch (c) { case 'c': components = atoi(optarg); outPrefix = std::string("test_") + optarg + "c"; if ((components < 1) || (components > 3)) { std::cout << "Valid models are 1 to 3 components." << std::endl; exit(EXIT_FAILURE); } break; case 's': testSpeed = true; break; case 'f': testFiles = true; break; case 't': tesla = atoi(optarg); default: break; } } // Set up all the parameters double spgrTR = 0.0012; double ssfpTR = 0.006; ArrayXd alphaSPGR(6); alphaSPGR << 2, 4, 8, 16, 24, 32; ArrayXd alphaSSFP(6); alphaSSFP << 2, 4, 8, 16, 32, 64; alphaSPGR *= M_PI / 180.; alphaSSFP *= M_PI / 180.; ArrayXd sSPGR(alphaSPGR.size()); sSPGR.setZero(); ArrayXd sSSFP(alphaSSFP.size()); sSSFP.setZero(); vector<mcDESPOT::SignalType> types; types.push_back(mcDESPOT::SignalSPGR); types.push_back(mcDESPOT::SignalSSFP); types.push_back(mcDESPOT::SignalSSFP); vector<VectorXd> signals, angles; vector<double> TR, phases, B0, B1; vector<DESPOTConstants> consts; angles.push_back(alphaSPGR); signals.push_back(sSPGR); consts.push_back( { spgrTR, 0., 0., 1. } ); angles.push_back(alphaSSFP); signals.push_back(sSSFP); consts.push_back( { ssfpTR, 0., 0., 1. } ); angles.push_back(alphaSSFP); signals.push_back(sSSFP); consts.push_back( { ssfpTR, M_PI, 0., 1. } ); long loops = 10000; if (testSpeed) { for (int c = 1; c < 4; c++) { ArrayXd p = (mcDESPOT::defaultLo(c, tesla) + mcDESPOT::defaultHi(c, tesla)) / 2.; mcDESPOT mcd(c, types, angles, signals, consts, true, false); VectorXd signal; clock_t start = clock(); for (int l = 0; l < loops; l++) signal = mcd.theory(p); clock_t end = clock(); cout << c << "-component model average time " << ((end - start) / ((float)loops * CLOCKS_PER_SEC)) * 1000 << " ms" << endl; } }*/ /* // Now create our images int nx = 3, ny = 3, nz = 3; int totalVoxels = nx * ny * nz; double *dataSPGR = (double *)malloc(alphaSPGR.size() * totalVoxels * sizeof(double)); double *dataSSFP[phases.size()]; for (int p = 0; p < phases.size(); p++) dataSSFP[p] = (double *)malloc(alphaSSFP.size() * totalVoxels * sizeof(double)); double *dataParams[params.size()]; for (int p = 0; p < params.size(); p++) dataParams[p] = (double *)malloc(totalVoxels * sizeof(double)); double *dataB0 = (double *)malloc(totalVoxels * sizeof(double)); double *dataB1 = (double *)malloc(totalVoxels * sizeof(double)); clock_t loopStart = clock(); for (short z = 0; z < nz; z++) { for (short y = 0; y < ny; y++) { for (short x = 0; x < nx; x++) { switch (components) { case 1: B0 = ((double)x / (nx - 1)) * 80. - 40.; B1 = ((double)y / (ny - 1)) * 0.2 + 0.9; model = new OneComponent(alphaSPGR, zeros, alphaSSFP, phases, ssfpZeros, spgrTR, ssfpTR, B0, B1); break; case 3: params[6] = ((double)x / (nx - 1)) * 0.2 + 0.05; params[7] = ((double)y / (ny - 1)) * 0.6; break; } VectorXd sig(model->values()); model->operator()(params, sig); int index = 0; // Results are in one long vector for (int i = 0; i < alphaSPGR.size(); i++) dataSPGR[i*totalVoxels + (z*ny + y)*nx + x] = sig[index++]; for (int p = 0; p < phases.size(); p++) { for (int i = 0; i < alphaSSFP.size(); i++) { dataSSFP[p][i * totalVoxels + (z*ny + y)*nx + x] = sig[index++]; } } for (int p = 0; p < params.size(); p++) dataParams[p][(z*ny + y)*nx + x] = params[p]; dataB0[(z*ny + y)*nx + x] = B0; dataB1[(z*ny + y)*nx + x] = B1; delete model; } } } clock_t loopEnd = clock(); std::cout << "Time to generate data was " << ((loopEnd - loopStart) / ((float)totalVoxels * CLOCKS_PER_SEC)) << " seconds per voxel." << std::endl; float volSize = 40.; // Reset to degrees alphaSPGR *= 180. / M_PI; alphaSSFP *= 180. / M_PI; phases *= 180. / M_PI; NiftiImage outFile(nx, ny, nz, alphaSPGR.size(), volSize / nx, volSize / ny, volSize / nz, spgrTR, NIFTI_TYPE_FLOAT32); std::string outName; FILE *procparfile; par_t *pars[3]; double spgrPhase = 0.; pars[0] = createPar("tr", PAR_REAL, 1, &spgrTR); pars[1] = createPar("flip1", PAR_REAL, alphaSPGR.size(), alphaSPGR.data()); pars[2] = createPar("rfphase", PAR_REAL, 1, &spgrPhase); outName = "SPGR_Noiseless.nii.gz"; outFile.open(outName, NIFTI_WRITE); outFile.writeAllVolumes(dataSPGR); outFile.close(); outName = "SPGR_Noiseless.procpar"; procparfile = fopen(outName.c_str(), "w"); for (int i = 0; i < 3; i++) fprintPar(procparfile, pars[i]); fclose(procparfile); for (int p = 0; p < phases.size(); p++) { double phaseDeg = phases[p]; outName = (std::stringstream("SSFP-") << outName << phaseDeg << "_Noiseless.nii.gz").str(); outFile.setnt(alphaSSFP.size()); outFile.open(outName, NIFTI_WRITE); outFile.writeAllVolumes(dataSSFP[p]); outFile.close(); outName = (std::stringstream("SSFP-") << outName << phaseDeg << "_Noiseless.procpar").str(); setPar(pars[0], 1, &ssfpTR); setPar(pars[1], alphaSSFP.size(), alphaSSFP.data()); setPar(pars[2], 1, &phaseDeg); procparfile = fopen(outName.c_str(), "w"); for (int i = 0; i < 3; i++) fprintPar(procparfile, pars[i]); fclose(procparfile); } outName = "B0_Noiseless.nii.gz"; outFile.setnt(1); outFile.open(outName, NIFTI_WRITE); outFile.writeAllVolumes(dataB0); outFile.close(); outName = "B1_Noiseless.nii.gz"; outFile.open(outName, NIFTI_WRITE); outFile.writeAllVolumes(dataB1); outFile.close(); switch (components) { case 1: write_results<OneComponent>(outPrefix, dataParams, NULL, outFile); break; case 2: write_results<TwoComponent>(outPrefix, dataParams, NULL, outFile); break; case 3: write_results<ThreeComponent>(outPrefix, dataParams, NULL, outFile); break; } */ return 0; } <commit_msg>Checked new index_partial_sort.<commit_after>// // main.c // test_despot // // Created by Tobias Wood on 17/08/2012. // Copyright (c) 2012 Tobias Wood. All rights reserved. // #include <getopt.h> #include <vector> #include <string> #include "RegionContraction.h" //#include "DESPOT_Functors.h" #include "NiftiImage.h" #include "procpar.h" static int components = 1, tesla = 7; static std::string outPrefix; static bool testSpeed = false, testFiles = false; static struct option long_options[] = { {"components", required_argument, 0, 'c'}, {"speed", no_argument, 0, 's'}, {"files", no_argument, 0, 'f'}, {"tesla", required_argument, 0, 't'}, {0, 0, 0, 0} }; using namespace std; int main(int argc, char **argv) { ArrayXd data(5000); data.setRandom(); cout << "First 10: " << data.head(10).transpose() << endl; vector<size_t> indices = index_partial_sort(data, 10); cout << "Indices: "; for (auto i: indices) cout << i << ": " << data(i) << " "; cout << endl; /*int indexptr = 0, c; while ((c = getopt_long(argc, argv, "c:sf", long_options, &indexptr)) != -1) { switch (c) { case 'c': components = atoi(optarg); outPrefix = std::string("test_") + optarg + "c"; if ((components < 1) || (components > 3)) { std::cout << "Valid models are 1 to 3 components." << std::endl; exit(EXIT_FAILURE); } break; case 's': testSpeed = true; break; case 'f': testFiles = true; break; case 't': tesla = atoi(optarg); default: break; } } // Set up all the parameters double spgrTR = 0.0012; double ssfpTR = 0.006; ArrayXd alphaSPGR(6); alphaSPGR << 2, 4, 8, 16, 24, 32; ArrayXd alphaSSFP(6); alphaSSFP << 2, 4, 8, 16, 32, 64; alphaSPGR *= M_PI / 180.; alphaSSFP *= M_PI / 180.; ArrayXd sSPGR(alphaSPGR.size()); sSPGR.setZero(); ArrayXd sSSFP(alphaSSFP.size()); sSSFP.setZero(); vector<mcDESPOT::SignalType> types; types.push_back(mcDESPOT::SignalSPGR); types.push_back(mcDESPOT::SignalSSFP); types.push_back(mcDESPOT::SignalSSFP); vector<VectorXd> signals, angles; vector<double> TR, phases, B0, B1; vector<DESPOTConstants> consts; angles.push_back(alphaSPGR); signals.push_back(sSPGR); consts.push_back( { spgrTR, 0., 0., 1. } ); angles.push_back(alphaSSFP); signals.push_back(sSSFP); consts.push_back( { ssfpTR, 0., 0., 1. } ); angles.push_back(alphaSSFP); signals.push_back(sSSFP); consts.push_back( { ssfpTR, M_PI, 0., 1. } ); long loops = 10000; if (testSpeed) { for (int c = 1; c < 4; c++) { ArrayXd p = (mcDESPOT::defaultLo(c, tesla) + mcDESPOT::defaultHi(c, tesla)) / 2.; mcDESPOT mcd(c, types, angles, signals, consts, true, false); VectorXd signal; clock_t start = clock(); for (int l = 0; l < loops; l++) signal = mcd.theory(p); clock_t end = clock(); cout << c << "-component model average time " << ((end - start) / ((float)loops * CLOCKS_PER_SEC)) * 1000 << " ms" << endl; } }*/ /* // Now create our images int nx = 3, ny = 3, nz = 3; int totalVoxels = nx * ny * nz; double *dataSPGR = (double *)malloc(alphaSPGR.size() * totalVoxels * sizeof(double)); double *dataSSFP[phases.size()]; for (int p = 0; p < phases.size(); p++) dataSSFP[p] = (double *)malloc(alphaSSFP.size() * totalVoxels * sizeof(double)); double *dataParams[params.size()]; for (int p = 0; p < params.size(); p++) dataParams[p] = (double *)malloc(totalVoxels * sizeof(double)); double *dataB0 = (double *)malloc(totalVoxels * sizeof(double)); double *dataB1 = (double *)malloc(totalVoxels * sizeof(double)); clock_t loopStart = clock(); for (short z = 0; z < nz; z++) { for (short y = 0; y < ny; y++) { for (short x = 0; x < nx; x++) { switch (components) { case 1: B0 = ((double)x / (nx - 1)) * 80. - 40.; B1 = ((double)y / (ny - 1)) * 0.2 + 0.9; model = new OneComponent(alphaSPGR, zeros, alphaSSFP, phases, ssfpZeros, spgrTR, ssfpTR, B0, B1); break; case 3: params[6] = ((double)x / (nx - 1)) * 0.2 + 0.05; params[7] = ((double)y / (ny - 1)) * 0.6; break; } VectorXd sig(model->values()); model->operator()(params, sig); int index = 0; // Results are in one long vector for (int i = 0; i < alphaSPGR.size(); i++) dataSPGR[i*totalVoxels + (z*ny + y)*nx + x] = sig[index++]; for (int p = 0; p < phases.size(); p++) { for (int i = 0; i < alphaSSFP.size(); i++) { dataSSFP[p][i * totalVoxels + (z*ny + y)*nx + x] = sig[index++]; } } for (int p = 0; p < params.size(); p++) dataParams[p][(z*ny + y)*nx + x] = params[p]; dataB0[(z*ny + y)*nx + x] = B0; dataB1[(z*ny + y)*nx + x] = B1; delete model; } } } clock_t loopEnd = clock(); std::cout << "Time to generate data was " << ((loopEnd - loopStart) / ((float)totalVoxels * CLOCKS_PER_SEC)) << " seconds per voxel." << std::endl; float volSize = 40.; // Reset to degrees alphaSPGR *= 180. / M_PI; alphaSSFP *= 180. / M_PI; phases *= 180. / M_PI; NiftiImage outFile(nx, ny, nz, alphaSPGR.size(), volSize / nx, volSize / ny, volSize / nz, spgrTR, NIFTI_TYPE_FLOAT32); std::string outName; FILE *procparfile; par_t *pars[3]; double spgrPhase = 0.; pars[0] = createPar("tr", PAR_REAL, 1, &spgrTR); pars[1] = createPar("flip1", PAR_REAL, alphaSPGR.size(), alphaSPGR.data()); pars[2] = createPar("rfphase", PAR_REAL, 1, &spgrPhase); outName = "SPGR_Noiseless.nii.gz"; outFile.open(outName, NIFTI_WRITE); outFile.writeAllVolumes(dataSPGR); outFile.close(); outName = "SPGR_Noiseless.procpar"; procparfile = fopen(outName.c_str(), "w"); for (int i = 0; i < 3; i++) fprintPar(procparfile, pars[i]); fclose(procparfile); for (int p = 0; p < phases.size(); p++) { double phaseDeg = phases[p]; outName = (std::stringstream("SSFP-") << outName << phaseDeg << "_Noiseless.nii.gz").str(); outFile.setnt(alphaSSFP.size()); outFile.open(outName, NIFTI_WRITE); outFile.writeAllVolumes(dataSSFP[p]); outFile.close(); outName = (std::stringstream("SSFP-") << outName << phaseDeg << "_Noiseless.procpar").str(); setPar(pars[0], 1, &ssfpTR); setPar(pars[1], alphaSSFP.size(), alphaSSFP.data()); setPar(pars[2], 1, &phaseDeg); procparfile = fopen(outName.c_str(), "w"); for (int i = 0; i < 3; i++) fprintPar(procparfile, pars[i]); fclose(procparfile); } outName = "B0_Noiseless.nii.gz"; outFile.setnt(1); outFile.open(outName, NIFTI_WRITE); outFile.writeAllVolumes(dataB0); outFile.close(); outName = "B1_Noiseless.nii.gz"; outFile.open(outName, NIFTI_WRITE); outFile.writeAllVolumes(dataB1); outFile.close(); switch (components) { case 1: write_results<OneComponent>(outPrefix, dataParams, NULL, outFile); break; case 2: write_results<TwoComponent>(outPrefix, dataParams, NULL, outFile); break; case 3: write_results<ThreeComponent>(outPrefix, dataParams, NULL, outFile); break; } */ return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/extensions/shell_window_views.h" #include "base/utf_string_conversions.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/common/extensions/extension.h" #include "ui/views/widget/widget.h" #if defined(OS_WIN) #include "chrome/browser/shell_integration.h" #include "chrome/browser/web_applications/web_app.h" #include "ui/base/win/shell.h" #endif // OS_WIN ShellWindowViews::ShellWindowViews(ExtensionHost* host) : ShellWindow(host) { host_->view()->SetContainer(this); window_ = new views::Widget; views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW); params.delegate = this; gfx::Rect bounds(0, 0, 512, 384); params.bounds = bounds; window_->Init(params); #if defined(OS_WIN) std::string app_name = web_app::GenerateApplicationNameFromExtensionId( host_->extension()->id()); ui::win::SetAppIdForWindow( ShellIntegration::GetAppId(UTF8ToWide(app_name), host_->profile()->GetPath()), GetWidget()->GetTopLevelWidget()->GetNativeWindow()); #endif // OS_WIN window_->Show(); } ShellWindowViews::~ShellWindowViews() { } void ShellWindowViews::Close() { window_->Close(); } void ShellWindowViews::DeleteDelegate() { delete this; } bool ShellWindowViews::CanResize() const { return true; } views::View* ShellWindowViews::GetContentsView() { return host_->view(); } string16 ShellWindowViews::GetWindowTitle() const { return UTF8ToUTF16(host_->extension()->name()); } views::Widget* ShellWindowViews::GetWidget() { return window_; } const views::Widget* ShellWindowViews::GetWidget() const { return window_; } // static ShellWindow* ShellWindow::CreateShellWindow(ExtensionHost* host) { return new ShellWindowViews(host); } <commit_msg>Revert 118201 - Set windows AppId (for taskbar) for platform apps.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/extensions/shell_window_views.h" #include "base/utf_string_conversions.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/common/extensions/extension.h" #include "ui/views/widget/widget.h" ShellWindowViews::ShellWindowViews(ExtensionHost* host) : ShellWindow(host) { host_->view()->SetContainer(this); window_ = new views::Widget; views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW); params.delegate = this; gfx::Rect bounds(0, 0, 512, 384); params.bounds = bounds; window_->Init(params); window_->Show(); } ShellWindowViews::~ShellWindowViews() { } void ShellWindowViews::Close() { window_->Close(); } void ShellWindowViews::DeleteDelegate() { delete this; } bool ShellWindowViews::CanResize() const { return true; } views::View* ShellWindowViews::GetContentsView() { return host_->view(); } string16 ShellWindowViews::GetWindowTitle() const { return UTF8ToUTF16(host_->extension()->name()); } views::Widget* ShellWindowViews::GetWidget() { return window_; } const views::Widget* ShellWindowViews::GetWidget() const { return window_; } // static ShellWindow* ShellWindow::CreateShellWindow(ExtensionHost* host) { return new ShellWindowViews(host); } <|endoftext|>
<commit_before>/* * Author: Wolfgang Merkt * * Copyright (c) 2018, Wolfgang Merkt * 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 nor the names of its contributors may be used to * endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include "task_map/JointVelocityLimit.h" REGISTER_TASKMAP_TYPE("JointVelocityLimit", exotica::JointVelocityLimit); namespace exotica { JointVelocityLimit::JointVelocityLimit() { Kinematics.resize(2); // Request kinematics for current x_t and x_{t-1} } void JointVelocityLimit::Instantiate(JointVelocityLimitInitializer& init) { init_ = init; } void JointVelocityLimit::assignScene(Scene_ptr scene) { scene_ = scene; Initialize(); } void JointVelocityLimit::Initialize() { double percent = init_.SafePercentage; N = scene_->getSolver().getNumControlledJoints(); dt_ = std::abs(init_.dt); if (dt_ == 0.0) throw_named("Timestep dt needs to be greater than 0"); if (init_.MaximumJointVelocity.rows() == 1) limits_ = std::abs(init_.MaximumJointVelocity(0)) * Eigen::VectorXd::Ones(N); else if (init_.MaximumJointVelocity.rows() == N) limits_ = init_.MaximumJointVelocity.cwiseAbs(); else throw_named("Maximum joint velocity vector needs to be either of size 1 or N, but got " << init_.MaximumJointVelocity.rows()); tau_ = percent * limits_; if (debug_) HIGHLIGHT_NAMED("JointVelocityLimit", "dt=" << dt_ << ", q̇_max=" << limits_.transpose() << ", τ=" << tau_.transpose()); } int JointVelocityLimit::taskSpaceDim() { return N; } void JointVelocityLimit::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi) { if (Kinematics.size() != 2) throw_named("Wrong size of Kinematics - requires 2, but got " << Kinematics.size()); if (phi.rows() != N) throw_named("Wrong size of phi!"); if (!x.isApprox(Kinematics[0].X)) throw_named("The internal Kinematics.X and passed state reference x do not match!"); phi.setZero(); Eigen::VectorXd x_diff = (1 / dt_) * (Kinematics[0].X - Kinematics[1].X); for (int i = 0; i < N; i++) { if (x_diff(i) < -limits_(i) + tau_(i)) { phi(i) = x_diff(i) + limits_(i) - tau_(i); if (debug_) HIGHLIGHT_NAMED("JointVelocityLimit", "Lower limit exceeded (joint=" << i << "): " << x_diff(i) << " < (-" << limits_(i) << "+" << tau_(i) << ")"); } if (x_diff(i) > limits_(i) - tau_(i)) { phi(i) = x_diff(i) - limits_(i) + tau_(i); if (debug_) HIGHLIGHT_NAMED("JointVelocityLimit", "Upper limit exceeded (joint=" << i << "): " << x_diff(i) << " > (" << limits_(i) << "-" << tau_(i) << ")"); } } } void JointVelocityLimit::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef J) { if (J.rows() != N || J.cols() != N) throw_named("Wrong size of J! " << N); update(x, phi); J = (1 / dt_) * Eigen::MatrixXd::Identity(N, N); for (int i = 0; i < N; i++) if (phi(i) == 0.0) J(i, i) = 0.0; } } <commit_msg>[task_map] JointVelocityLimit: Re-add virtual destructor (impl.)<commit_after>/* * Author: Wolfgang Merkt * * Copyright (c) 2018, Wolfgang Merkt * 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 nor the names of its contributors may be used to * endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include "task_map/JointVelocityLimit.h" REGISTER_TASKMAP_TYPE("JointVelocityLimit", exotica::JointVelocityLimit); namespace exotica { JointVelocityLimit::JointVelocityLimit() { Kinematics.resize(2); // Request kinematics for current x_t and x_{t-1} } JointVelocityLimit::~JointVelocityLimit() = default; void JointVelocityLimit::Instantiate(JointVelocityLimitInitializer& init) { init_ = init; } void JointVelocityLimit::assignScene(Scene_ptr scene) { scene_ = scene; Initialize(); } void JointVelocityLimit::Initialize() { double percent = init_.SafePercentage; N = scene_->getSolver().getNumControlledJoints(); dt_ = std::abs(init_.dt); if (dt_ == 0.0) throw_named("Timestep dt needs to be greater than 0"); if (init_.MaximumJointVelocity.rows() == 1) limits_ = std::abs(init_.MaximumJointVelocity(0)) * Eigen::VectorXd::Ones(N); else if (init_.MaximumJointVelocity.rows() == N) limits_ = init_.MaximumJointVelocity.cwiseAbs(); else throw_named("Maximum joint velocity vector needs to be either of size 1 or N, but got " << init_.MaximumJointVelocity.rows()); tau_ = percent * limits_; if (debug_) HIGHLIGHT_NAMED("JointVelocityLimit", "dt=" << dt_ << ", q̇_max=" << limits_.transpose() << ", τ=" << tau_.transpose()); } int JointVelocityLimit::taskSpaceDim() { return N; } void JointVelocityLimit::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi) { if (Kinematics.size() != 2) throw_named("Wrong size of Kinematics - requires 2, but got " << Kinematics.size()); if (phi.rows() != N) throw_named("Wrong size of phi!"); if (!x.isApprox(Kinematics[0].X)) throw_named("The internal Kinematics.X and passed state reference x do not match!"); phi.setZero(); Eigen::VectorXd x_diff = (1 / dt_) * (Kinematics[0].X - Kinematics[1].X); for (int i = 0; i < N; i++) { if (x_diff(i) < -limits_(i) + tau_(i)) { phi(i) = x_diff(i) + limits_(i) - tau_(i); if (debug_) HIGHLIGHT_NAMED("JointVelocityLimit", "Lower limit exceeded (joint=" << i << "): " << x_diff(i) << " < (-" << limits_(i) << "+" << tau_(i) << ")"); } if (x_diff(i) > limits_(i) - tau_(i)) { phi(i) = x_diff(i) - limits_(i) + tau_(i); if (debug_) HIGHLIGHT_NAMED("JointVelocityLimit", "Upper limit exceeded (joint=" << i << "): " << x_diff(i) << " > (" << limits_(i) << "-" << tau_(i) << ")"); } } } void JointVelocityLimit::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef J) { if (J.rows() != N || J.cols() != N) throw_named("Wrong size of J! " << N); update(x, phi); J = (1 / dt_) * Eigen::MatrixXd::Identity(N, N); for (int i = 0; i < N; i++) if (phi(i) == 0.0) J(i, i) = 0.0; } } <|endoftext|>
<commit_before>/* Copyright (c) FFLAS-FFPACK * ========LICENCE======== * This file is part of the library FFLAS-FFPACK. * * FFLAS-FFPACK 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 * ========LICENCE======== */ #include <givaro/modular.h> #include <iostream> #include "fflas-ffpack/fflas-ffpack-config.h" #include "fflas-ffpack/fflas-ffpack.h" #include "fflas-ffpack/utils/fflas_io.h" /** * This example computes the determinant of a matrix * over a defined finite field. */ int main(int argc, char** argv) { if (argc != 3) { std::cerr << "Usage: det <p> <matrix>" << std::endl; return -1; } int p = atoi(argv[1]); std::string file = argv[2]; // Creating the finite field Z/qZ Givaro::Modular<double> F(p); // Reading the matrix from a file double* A; size_t m, n; FFLAS::ReadMatrix(file.c_str(), F, m, n, A); std::cout << "Input matrix is " << m << "x" << n << std::endl; double d = FFPACK::Det(F, m, n, A, n); std::cout << "Det is " << d << std::endl; FFLAS::fflas_delete(A); return 0; } <commit_msg>Just outputing the determinant<commit_after>/* Copyright (c) FFLAS-FFPACK * ========LICENCE======== * This file is part of the library FFLAS-FFPACK. * * FFLAS-FFPACK 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 * ========LICENCE======== */ #include <givaro/modular.h> #include <iostream> #include "fflas-ffpack/fflas-ffpack-config.h" #include "fflas-ffpack/fflas-ffpack.h" #include "fflas-ffpack/utils/fflas_io.h" /** * This example computes the determinant of a matrix * over a defined finite field. * * Outputs the determinant. */ int main(int argc, char** argv) { if (argc != 3) { std::cerr << "Usage: det <p> <matrix>" << std::endl; return -1; } int p = atoi(argv[1]); std::string file = argv[2]; // Creating the finite field Z/qZ Givaro::Modular<double> F(p); // Reading the matrix from a file double* A; size_t m, n; FFLAS::ReadMatrix(file.c_str(), F, m, n, A); double d = FFPACK::Det(F, m, n, A, n); std::cout << d << std::endl; FFLAS::fflas_delete(A); return 0; } <|endoftext|>
<commit_before>/** * \file * \brief DynamicThreadBase class header * * \author Copyright (C) 2015-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. */ #ifndef INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_DYNAMICTHREADBASE_HPP_ #define INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_DYNAMICTHREADBASE_HPP_ #include "distortos/DynamicSignalsReceiver.hpp" #include "distortos/DynamicThreadParameters.hpp" #include "distortos/ThreadCommon.hpp" #include "distortos/internal/memory/storageDeleter.hpp" namespace distortos { #ifdef CONFIG_THREAD_DETACH_ENABLE class DynamicThread; #endif // def CONFIG_THREAD_DETACH_ENABLE namespace internal { /** * \brief DynamicThreadBase class is a type-erased interface for thread that has dynamic storage for bound function, * stack and internal DynamicSignalsReceiver object. * * If thread detachment is enabled (CONFIG_THREAD_DETACH_ENABLE is defined) then this class is dynamically allocated by * DynamicThread - which allows it to be "detached". Otherwise - if thread detachment is disabled * (CONFIG_THREAD_DETACH_ENABLE is not defined) - DynamicThread just inherits from this class. */ class DynamicThreadBase : public ThreadCommon { public: #ifdef CONFIG_THREAD_DETACH_ENABLE /** * \brief DynamicThreadBase's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] owner is a reference to owner DynamicThread object * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThreadBase(size_t stackSize, bool canReceiveSignals, size_t queuedSignals, size_t signalActions, uint8_t priority, SchedulingPolicy schedulingPolicy, DynamicThread& owner, Function&& function, Args&&... args); #else // !def CONFIG_THREAD_DETACH_ENABLE /** * \brief DynamicThreadBase's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThreadBase(size_t stackSize, bool canReceiveSignals, size_t queuedSignals, size_t signalActions, uint8_t priority, SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args); /** * \brief DynamicThreadBase's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] parameters is a DynamicThreadParameters struct with thread parameters * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThreadBase(const DynamicThreadParameters parameters, Function&& function, Args&&... args) : DynamicThreadBase{parameters.stackSize, parameters.canReceiveSignals, parameters.queuedSignals, parameters.signalActions, parameters.priority, parameters.schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...} { } #endif // !def CONFIG_THREAD_DETACH_ENABLE #ifdef CONFIG_THREAD_DETACH_ENABLE /** * \brief Detaches the thread. * * Similar to std::thread::detach() - http://en.cppreference.com/w/cpp/thread/thread/detach * Similar to POSIX pthread_detach() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_detach.html * * Detaches the executing thread from the Thread object, allowing execution to continue independently. All resources * allocated for the thread will be deallocated when the thread terminates. * * \return 0 on success, error code otherwise: * - EINVAL - this thread is already detached; */ int detach() override; #endif // def CONFIG_THREAD_DETACH_ENABLE DynamicThreadBase(const DynamicThreadBase&) = delete; DynamicThreadBase(DynamicThreadBase&&) = default; const DynamicThreadBase& operator=(const DynamicThreadBase&) = delete; DynamicThreadBase& operator=(DynamicThreadBase&&) = delete; protected: #ifdef CONFIG_THREAD_DETACH_ENABLE /** * \brief Pre-termination hook function of thread * * If thread is detached, locks object used for deferred deletion. * * \param [in] thread is a reference to Thread object, this must be DynamicThreadBase! */ static void preTerminationHook(Thread& thread); /** * \brief Termination hook function of thread * * Calls ThreadCommon::terminationHook() and - if thread is detached - schedules itself for deferred deletion. * * \param [in] thread is a reference to Thread object, this must be DynamicThreadBase! */ static void terminationHook(Thread& thread); #endif // def CONFIG_THREAD_DETACH_ENABLE private: /** * \brief Thread's "run" function. * * Executes bound function object. * * \param [in] thread is a reference to Thread object, this must be DynamicThreadBase! */ static void run(Thread& thread); /// size of "stack guard", bytes constexpr static size_t stackGuardSize_ {(CONFIG_STACK_GUARD_SIZE + CONFIG_ARCHITECTURE_STACK_ALIGNMENT - 1) / CONFIG_ARCHITECTURE_STACK_ALIGNMENT * CONFIG_ARCHITECTURE_STACK_ALIGNMENT}; /// internal DynamicSignalsReceiver object DynamicSignalsReceiver dynamicSignalsReceiver_; /// bound function object std::function<void()> boundFunction_; #ifdef CONFIG_THREAD_DETACH_ENABLE /// pointer to owner DynamicThread object, nullptr if thread is detached DynamicThread* owner_; #endif // def CONFIG_THREAD_DETACH_ENABLE }; #ifdef CONFIG_THREAD_DETACH_ENABLE template<typename Function, typename... Args> DynamicThreadBase::DynamicThreadBase(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, DynamicThread& owner, Function&& function, Args&&... args) : ThreadCommon{{{new uint8_t[stackSize + stackGuardSize_], storageDeleter<uint8_t>}, stackSize + stackGuardSize_, *this, run, preTerminationHook, terminationHook}, priority, schedulingPolicy, nullptr, canReceiveSignals == true ? &dynamicSignalsReceiver_ : nullptr}, dynamicSignalsReceiver_{canReceiveSignals == true ? queuedSignals : 0, canReceiveSignals == true ? signalActions : 0}, boundFunction_{std::bind(std::forward<Function>(function), std::forward<Args>(args)...)}, owner_{&owner} { } #else // !def CONFIG_THREAD_DETACH_ENABLE template<typename Function, typename... Args> DynamicThreadBase::DynamicThreadBase(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) : ThreadCommon{{{new uint8_t[stackSize + stackGuardSize_], storageDeleter<uint8_t>}, stackSize + stackGuardSize_, *this, run, nullptr, terminationHook}, priority, schedulingPolicy, nullptr, canReceiveSignals == true ? &dynamicSignalsReceiver_ : nullptr}, dynamicSignalsReceiver_{canReceiveSignals == true ? queuedSignals : 0, canReceiveSignals == true ? signalActions : 0}, boundFunction_{std::bind(std::forward<Function>(function), std::forward<Args>(args)...)} { } #endif // !def CONFIG_THREAD_DETACH_ENABLE } // namespace internal } // namespace distortos #endif // INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_DYNAMICTHREADBASE_HPP_ <commit_msg>Add wrapper for start() from base class to DynamicThreadBase<commit_after>/** * \file * \brief DynamicThreadBase class header * * \author Copyright (C) 2015-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. */ #ifndef INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_DYNAMICTHREADBASE_HPP_ #define INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_DYNAMICTHREADBASE_HPP_ #include "distortos/DynamicSignalsReceiver.hpp" #include "distortos/DynamicThreadParameters.hpp" #include "distortos/ThreadCommon.hpp" #include "distortos/internal/memory/storageDeleter.hpp" namespace distortos { #ifdef CONFIG_THREAD_DETACH_ENABLE class DynamicThread; #endif // def CONFIG_THREAD_DETACH_ENABLE namespace internal { /** * \brief DynamicThreadBase class is a type-erased interface for thread that has dynamic storage for bound function, * stack and internal DynamicSignalsReceiver object. * * If thread detachment is enabled (CONFIG_THREAD_DETACH_ENABLE is defined) then this class is dynamically allocated by * DynamicThread - which allows it to be "detached". Otherwise - if thread detachment is disabled * (CONFIG_THREAD_DETACH_ENABLE is not defined) - DynamicThread just inherits from this class. */ class DynamicThreadBase : public ThreadCommon { public: #ifdef CONFIG_THREAD_DETACH_ENABLE /** * \brief DynamicThreadBase's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] owner is a reference to owner DynamicThread object * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThreadBase(size_t stackSize, bool canReceiveSignals, size_t queuedSignals, size_t signalActions, uint8_t priority, SchedulingPolicy schedulingPolicy, DynamicThread& owner, Function&& function, Args&&... args); #else // !def CONFIG_THREAD_DETACH_ENABLE /** * \brief DynamicThreadBase's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThreadBase(size_t stackSize, bool canReceiveSignals, size_t queuedSignals, size_t signalActions, uint8_t priority, SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args); /** * \brief DynamicThreadBase's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] parameters is a DynamicThreadParameters struct with thread parameters * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThreadBase(const DynamicThreadParameters parameters, Function&& function, Args&&... args) : DynamicThreadBase{parameters.stackSize, parameters.canReceiveSignals, parameters.queuedSignals, parameters.signalActions, parameters.priority, parameters.schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...} { } #endif // !def CONFIG_THREAD_DETACH_ENABLE #ifdef CONFIG_THREAD_DETACH_ENABLE /** * \brief Detaches the thread. * * Similar to std::thread::detach() - http://en.cppreference.com/w/cpp/thread/thread/detach * Similar to POSIX pthread_detach() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_detach.html * * Detaches the executing thread from the Thread object, allowing execution to continue independently. All resources * allocated for the thread will be deallocated when the thread terminates. * * \return 0 on success, error code otherwise: * - EINVAL - this thread is already detached; */ int detach() override; #endif // def CONFIG_THREAD_DETACH_ENABLE /** * \brief Starts the thread. * * This operation can be performed on threads in "New" state only. * * \return 0 on success, error code otherwise: * - error codes returned by ThreadCommon::start(); */ int start() { return ThreadCommon::start(); } DynamicThreadBase(const DynamicThreadBase&) = delete; DynamicThreadBase(DynamicThreadBase&&) = default; const DynamicThreadBase& operator=(const DynamicThreadBase&) = delete; DynamicThreadBase& operator=(DynamicThreadBase&&) = delete; protected: #ifdef CONFIG_THREAD_DETACH_ENABLE /** * \brief Pre-termination hook function of thread * * If thread is detached, locks object used for deferred deletion. * * \param [in] thread is a reference to Thread object, this must be DynamicThreadBase! */ static void preTerminationHook(Thread& thread); /** * \brief Termination hook function of thread * * Calls ThreadCommon::terminationHook() and - if thread is detached - schedules itself for deferred deletion. * * \param [in] thread is a reference to Thread object, this must be DynamicThreadBase! */ static void terminationHook(Thread& thread); #endif // def CONFIG_THREAD_DETACH_ENABLE private: /** * \brief Thread's "run" function. * * Executes bound function object. * * \param [in] thread is a reference to Thread object, this must be DynamicThreadBase! */ static void run(Thread& thread); /// size of "stack guard", bytes constexpr static size_t stackGuardSize_ {(CONFIG_STACK_GUARD_SIZE + CONFIG_ARCHITECTURE_STACK_ALIGNMENT - 1) / CONFIG_ARCHITECTURE_STACK_ALIGNMENT * CONFIG_ARCHITECTURE_STACK_ALIGNMENT}; /// internal DynamicSignalsReceiver object DynamicSignalsReceiver dynamicSignalsReceiver_; /// bound function object std::function<void()> boundFunction_; #ifdef CONFIG_THREAD_DETACH_ENABLE /// pointer to owner DynamicThread object, nullptr if thread is detached DynamicThread* owner_; #endif // def CONFIG_THREAD_DETACH_ENABLE }; #ifdef CONFIG_THREAD_DETACH_ENABLE template<typename Function, typename... Args> DynamicThreadBase::DynamicThreadBase(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, DynamicThread& owner, Function&& function, Args&&... args) : ThreadCommon{{{new uint8_t[stackSize + stackGuardSize_], storageDeleter<uint8_t>}, stackSize + stackGuardSize_, *this, run, preTerminationHook, terminationHook}, priority, schedulingPolicy, nullptr, canReceiveSignals == true ? &dynamicSignalsReceiver_ : nullptr}, dynamicSignalsReceiver_{canReceiveSignals == true ? queuedSignals : 0, canReceiveSignals == true ? signalActions : 0}, boundFunction_{std::bind(std::forward<Function>(function), std::forward<Args>(args)...)}, owner_{&owner} { } #else // !def CONFIG_THREAD_DETACH_ENABLE template<typename Function, typename... Args> DynamicThreadBase::DynamicThreadBase(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) : ThreadCommon{{{new uint8_t[stackSize + stackGuardSize_], storageDeleter<uint8_t>}, stackSize + stackGuardSize_, *this, run, nullptr, terminationHook}, priority, schedulingPolicy, nullptr, canReceiveSignals == true ? &dynamicSignalsReceiver_ : nullptr}, dynamicSignalsReceiver_{canReceiveSignals == true ? queuedSignals : 0, canReceiveSignals == true ? signalActions : 0}, boundFunction_{std::bind(std::forward<Function>(function), std::forward<Args>(args)...)} { } #endif // !def CONFIG_THREAD_DETACH_ENABLE } // namespace internal } // namespace distortos #endif // INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_DYNAMICTHREADBASE_HPP_ <|endoftext|>
<commit_before>#include <stdio.h> #include <string.h> #include "openssl/md5.h" #include "openssl/crypto.h" #include "zlib.h" int main() { unsigned char digest[MD5_DIGEST_LENGTH]; char string[] = "happy"; MD5((unsigned char*)&string, strlen(string), (unsigned char*)&digest); char mdString[33]; for(int i = 0; i < 16; i++) sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]); printf("md5 digest: %s\n", mdString); printf("SSL library version: %s\n", SSLeay_version(SSLEAY_VERSION)); printf("ZLIB version: %s\n", ZLIB_VERSION); return 0; } <commit_msg>Patched example<commit_after>#include <stdio.h> #include <string.h> #include "openssl/md5.h" #include "openssl/crypto.h" #include "zlib.h" #include <openssl/ssl.h> int main() { unsigned char digest[MD5_DIGEST_LENGTH]; char string[] = "happy"; SSL_library_init(); MD5((unsigned char*)&string, strlen(string), (unsigned char*)&digest); char mdString[33]; for(int i = 0; i < 16; i++) sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]); printf("md5 digest: %s\n", mdString); printf("SSL library version: %s\n", SSLeay_version(SSLEAY_VERSION)); printf("ZLIB version: %s\n", ZLIB_VERSION); return 0; } <|endoftext|>
<commit_before>#include "Platform.hpp" #include "Base64.hpp" namespace Base64 { using namespace Sirikata; static uint32 conservativeBase64Size(size_t x) { return (x+2)*4/3+6+x/64+(x%64?1:0); } static const uint8 _URL_SAFE_ALPHABET []= { (uint8)'A', (uint8)'B', (uint8)'C', (uint8)'D', (uint8)'E', (uint8)'F', (uint8)'G', (uint8)'H', (uint8)'I', (uint8)'J', (uint8)'K', (uint8)'L', (uint8)'M', (uint8)'N', (uint8)'O', (uint8)'P', (uint8)'Q', (uint8)'R', (uint8)'S', (uint8)'T', (uint8)'U', (uint8)'V', (uint8)'W', (uint8)'X', (uint8)'Y', (uint8)'Z', (uint8)'a', (uint8)'b', (uint8)'c', (uint8)'d', (uint8)'e', (uint8)'f', (uint8)'g', (uint8)'h', (uint8)'i', (uint8)'j', (uint8)'k', (uint8)'l', (uint8)'m', (uint8)'n', (uint8)'o', (uint8)'p', (uint8)'q', (uint8)'r', (uint8)'s', (uint8)'t', (uint8)'u', (uint8)'v', (uint8)'w', (uint8)'x', (uint8)'y', (uint8)'z', (uint8)'0', (uint8)'1', (uint8)'2', (uint8)'3', (uint8)'4', (uint8)'5', (uint8)'6', (uint8)'7', (uint8)'8', (uint8)'9', (uint8)'-', (uint8)'_' }; int translateBase64(uint8*destination, const uint8* source, int numSigBytes) { // uint8 temp[4]; uint32 source0=source[0]; uint32 source1=source[1]; uint32 source2=source[2]; uint32 inBuff = ( numSigBytes > 0 ? ((source0 << 24) / 256) : 0 ) | ( numSigBytes > 1 ? ((source1 << 24) / 65536) : 0 ) | ( numSigBytes > 2 ? ((source2 << 24) / 65536/ 256) : 0 ); destination[ 0 ] = _URL_SAFE_ALPHABET[ (inBuff >> 18) ]; destination[ 1 ] = _URL_SAFE_ALPHABET[ (inBuff >> 12) & 0x3f ]; switch( numSigBytes ) { case 3: destination[ 2 ] = _URL_SAFE_ALPHABET[ (inBuff >> 6) & 0x3f ]; destination[ 3 ] = _URL_SAFE_ALPHABET[ (inBuff ) & 0x3f ]; return 4; case 2: destination[ 2 ] = _URL_SAFE_ALPHABET[ (inBuff >> 6) & 0x3f ]; destination[ 3 ] = '='; return 4; case 1: destination[ 2 ] = '='; destination[ 3 ] = '='; return 4; default: return 0; } // end switch } void toBase64(std::vector<unsigned char>&retval, const MemoryReference&firstInput, const MemoryReference&secondInput){ const MemoryReference*refs[2]; refs[0]=&firstInput; refs[1]=&secondInput; unsigned int datalen=0; uint8 data[3]; size_t curPlace=retval.size(); retval.resize(curPlace+conservativeBase64Size(refs[1]->size()+refs[2]->size())); size_t retvalSize=retval.size(); for (int i=0;i<3;++i) { const uint8*dat=(const uint8*)refs[i]->data(); uint32 size=refs[i]->size(); for (uint32 j=0;j<size;++j) { data[datalen++]=dat[j]; if (datalen==3) { if (retvalSize<=curPlace+5) { retval.resize(curPlace+5); } curPlace+=translateBase64(&*(retval.begin()+curPlace),data,datalen); datalen=0; } } } if (datalen) { if (retvalSize<=curPlace+5) { retval.resize(curPlace+5); fprintf(stderr,"conservative size estimate incorrect\n"); } curPlace+=translateBase64(&*(retval.begin()+curPlace),data,datalen); } retval.resize(curPlace); } static signed char WHITE_SPACE_ENC = -5; // Indicates white space in encoding static signed char EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding static int decode4to3(const signed char source[4],std::vector<unsigned char>& destination, int destOffset) { uint32 outBuf=((source[0]<<18)|(source[1]<<12)); destination[destOffset]=(uint8)(outBuf/65536); if (source[2]==EQUALS_SIGN_ENC) { return 1; } outBuf|=(source[2]<<6); destination[destOffset+1]=(uint8)((outBuf/256)&255); if (source[3]==EQUALS_SIGN_ENC) { return 2; } outBuf|=source[3]; destination[destOffset+2]=(uint8)(outBuf&255); return 3; } static signed char DECODABET [] = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9,-9,-9, // Decimal 44 - 46 63, // Slash at decimal 47 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' -9,-9,-9,-9,-9 // Decimal 123 - 126 }; static signed char URLSAFEDECODABET [] = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9,62,-9, // Decimal 44 - 46 63, // Slash at decimal 47 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' -9,-9,-9,-9,63,-9, // Decimal 91 - 94 underscore 95 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' -9,-9,-9,-9,-9 // Decimal 123 - 127 }; bool fromBase64(std::vector<unsigned char>&retval, const MemoryReference&a) { const uint8*begin=(const uint8*)a.data(); const uint8*end=(const uint8*)begin+a.size(); int outBuffPosn=retval.size(); retval.resize(retval.size()+(((end-begin)*3)/4+3));//maximum of the size; int remainderShift=0; signed char b4[4]; uint8 b4Posn=0; for (;begin!=end;++begin) { uint8 cur=(*begin); if (cur&0x80) { return false; } uint8 sbiCrop = (uint8)(cur & 0x7f); // Only the low seven bits signed char sbiDecode = URLSAFEDECODABET[ sbiCrop ]; // Special value // White space, Equals sign, or legit Base64 character // Note the values such as -5 and -9 in the // DECODABETs at the top of the file. if( sbiDecode >= WHITE_SPACE_ENC && cur==sbiCrop ) { if( sbiDecode >= EQUALS_SIGN_ENC ) { b4[ b4Posn++ ] = sbiDecode; // Save non-whitespace if( b4Posn > 3 ) { // Time to decode? outBuffPosn += decode4to3( b4, retval, outBuffPosn ); b4Posn = 0; // If that was the equals sign, break out of 'for' loop if( sbiDecode == EQUALS_SIGN_ENC ) { break; } // end if: equals sign } // end if: quartet built } // end if: equals sign or better } // end if: white space, equals sign or better } assert(outBuffPosn<=(int)retval.size()); retval.resize(outBuffPosn); return true; } } <commit_msg>do not creep past the end of an array in (as-of-yet-unused) toBase64 function<commit_after>#include "Platform.hpp" #include "Base64.hpp" namespace Base64 { using namespace Sirikata; static uint32 conservativeBase64Size(size_t x) { return (x+2)*4/3+6+x/64+(x%64?1:0); } static const uint8 _URL_SAFE_ALPHABET []= { (uint8)'A', (uint8)'B', (uint8)'C', (uint8)'D', (uint8)'E', (uint8)'F', (uint8)'G', (uint8)'H', (uint8)'I', (uint8)'J', (uint8)'K', (uint8)'L', (uint8)'M', (uint8)'N', (uint8)'O', (uint8)'P', (uint8)'Q', (uint8)'R', (uint8)'S', (uint8)'T', (uint8)'U', (uint8)'V', (uint8)'W', (uint8)'X', (uint8)'Y', (uint8)'Z', (uint8)'a', (uint8)'b', (uint8)'c', (uint8)'d', (uint8)'e', (uint8)'f', (uint8)'g', (uint8)'h', (uint8)'i', (uint8)'j', (uint8)'k', (uint8)'l', (uint8)'m', (uint8)'n', (uint8)'o', (uint8)'p', (uint8)'q', (uint8)'r', (uint8)'s', (uint8)'t', (uint8)'u', (uint8)'v', (uint8)'w', (uint8)'x', (uint8)'y', (uint8)'z', (uint8)'0', (uint8)'1', (uint8)'2', (uint8)'3', (uint8)'4', (uint8)'5', (uint8)'6', (uint8)'7', (uint8)'8', (uint8)'9', (uint8)'-', (uint8)'_' }; int translateBase64(uint8*destination, const uint8* source, int numSigBytes) { // uint8 temp[4]; uint32 source0=source[0]; uint32 source1=source[1]; uint32 source2=source[2]; uint32 inBuff = ( numSigBytes > 0 ? ((source0 << 24) / 256) : 0 ) | ( numSigBytes > 1 ? ((source1 << 24) / 65536) : 0 ) | ( numSigBytes > 2 ? ((source2 << 24) / 65536/ 256) : 0 ); destination[ 0 ] = _URL_SAFE_ALPHABET[ (inBuff >> 18) ]; destination[ 1 ] = _URL_SAFE_ALPHABET[ (inBuff >> 12) & 0x3f ]; switch( numSigBytes ) { case 3: destination[ 2 ] = _URL_SAFE_ALPHABET[ (inBuff >> 6) & 0x3f ]; destination[ 3 ] = _URL_SAFE_ALPHABET[ (inBuff ) & 0x3f ]; return 4; case 2: destination[ 2 ] = _URL_SAFE_ALPHABET[ (inBuff >> 6) & 0x3f ]; destination[ 3 ] = '='; return 4; case 1: destination[ 2 ] = '='; destination[ 3 ] = '='; return 4; default: return 0; } // end switch } void toBase64(std::vector<unsigned char>&retval, const MemoryReference&firstInput, const MemoryReference&secondInput){ const MemoryReference*refs[2]; refs[0]=&firstInput; refs[1]=&secondInput; unsigned int datalen=0; uint8 data[3]; size_t curPlace=retval.size(); retval.resize(curPlace+conservativeBase64Size(refs[0]->size()+refs[1]->size())); size_t retvalSize=retval.size(); for (int i=0;i<2;++i) { const uint8*dat=(const uint8*)refs[i]->data(); uint32 size=refs[i]->size(); for (uint32 j=0;j<size;++j) { data[datalen++]=dat[j]; if (datalen==3) { if (retvalSize<=curPlace+5) { retval.resize(curPlace+5); } curPlace+=translateBase64(&*(retval.begin()+curPlace),data,datalen); datalen=0; } } } if (datalen) { if (retvalSize<=curPlace+5) { retval.resize(curPlace+5); fprintf(stderr,"conservative size estimate incorrect\n"); } curPlace+=translateBase64(&*(retval.begin()+curPlace),data,datalen); } retval.resize(curPlace); } static signed char WHITE_SPACE_ENC = -5; // Indicates white space in encoding static signed char EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding static int decode4to3(const signed char source[4],std::vector<unsigned char>& destination, int destOffset) { uint32 outBuf=((source[0]<<18)|(source[1]<<12)); destination[destOffset]=(uint8)(outBuf/65536); if (source[2]==EQUALS_SIGN_ENC) { return 1; } outBuf|=(source[2]<<6); destination[destOffset+1]=(uint8)((outBuf/256)&255); if (source[3]==EQUALS_SIGN_ENC) { return 2; } outBuf|=source[3]; destination[destOffset+2]=(uint8)(outBuf&255); return 3; } static signed char DECODABET [] = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9,-9,-9, // Decimal 44 - 46 63, // Slash at decimal 47 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' -9,-9,-9,-9,-9 // Decimal 123 - 126 }; static signed char URLSAFEDECODABET [] = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9,62,-9, // Decimal 44 - 46 63, // Slash at decimal 47 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' -9,-9,-9,-9,63,-9, // Decimal 91 - 94 underscore 95 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' -9,-9,-9,-9,-9 // Decimal 123 - 127 }; bool fromBase64(std::vector<unsigned char>&retval, const MemoryReference&a) { const uint8*begin=(const uint8*)a.data(); const uint8*end=(const uint8*)begin+a.size(); int outBuffPosn=retval.size(); retval.resize(retval.size()+(((end-begin)*3)/4+3));//maximum of the size; int remainderShift=0; signed char b4[4]; uint8 b4Posn=0; for (;begin!=end;++begin) { uint8 cur=(*begin); if (cur&0x80) { return false; } uint8 sbiCrop = (uint8)(cur & 0x7f); // Only the low seven bits signed char sbiDecode = URLSAFEDECODABET[ sbiCrop ]; // Special value // White space, Equals sign, or legit Base64 character // Note the values such as -5 and -9 in the // DECODABETs at the top of the file. if( sbiDecode >= WHITE_SPACE_ENC && cur==sbiCrop ) { if( sbiDecode >= EQUALS_SIGN_ENC ) { b4[ b4Posn++ ] = sbiDecode; // Save non-whitespace if( b4Posn > 3 ) { // Time to decode? outBuffPosn += decode4to3( b4, retval, outBuffPosn ); b4Posn = 0; // If that was the equals sign, break out of 'for' loop if( sbiDecode == EQUALS_SIGN_ENC ) { break; } // end if: equals sign } // end if: quartet built } // end if: equals sign or better } // end if: white space, equals sign or better } assert(outBuffPosn<=(int)retval.size()); retval.resize(outBuffPosn); return true; } } <|endoftext|>
<commit_before>#include "core/rng.h" #include <iostream> int main() { using namespace euphoria::core; uint32_t max = 0; for(uint32_t i=0; true; i++) { auto rng = xorshift32{i}; const auto v = rng.Nexti(); if(v > max ) max = v; if( (i%1000000) == 0) { const auto m = std::numeric_limits<uint32_t>::max(); std::cout << i << " / " << m << " = " << (static_cast<float>(i)/m)*100.0f << "\n"; } } std::cout << "max is " << max << "\n"; return 0; } <commit_msg>better random test<commit_after>#include "core/rng.h" #include "core/random.h" #include <algorithm> #include <iostream> #include <string> #include <vector> using namespace euphoria::core; template<typename TGenerator> void PrintRandomNumbers ( const std::string& name, Random* random, int count, int small_count ) { std::cout << name << ": "; auto rng = TGenerator{random->NextInteger()}; auto container = std::vector<float>{}; for(int i=0; i<count; i+=1) { const auto r = rng.Next(); container.emplace_back(r); if( i < small_count ) { std::cout << r << " "; } } std::cout << "\n"; const auto min = *std::min_element(container.begin(), container.end()); const auto max = *std::max_element(container.begin(), container.end()); std::cout << "min/max: " << min << " " << max << "\n"; std::cout << "\n"; } int main() { constexpr auto count = 100; constexpr auto small_count = 10; auto random = Random{}; PrintRandomNumbers<wyhash64> ( "wyhash64", &random, count, small_count ); return 0; } <|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2006 Tim Beaulen <tbscope@gmail.com> Copyright (C) 2006-2007 Matthias Kretz <kretz@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "effect.h" #include <QVariant> #include "xineengine.h" #include <QMutexLocker> #include "events.h" #include "keepreference.h" namespace Phonon { namespace Xine { xine_audio_port_t *EffectXT::audioPort() const { const_cast<EffectXT *>(this)->ensureInstance(); Q_ASSERT(m_plugin); Q_ASSERT(m_plugin->audio_input); Q_ASSERT(m_plugin->audio_input[0]); return m_plugin->audio_input[0]; } xine_post_out_t *EffectXT::audioOutputPort() const { const_cast<EffectXT *>(this)->ensureInstance(); Q_ASSERT(m_plugin); xine_post_out_t *x = xine_post_output(m_plugin, "audio out"); Q_ASSERT(x); return x; } void EffectXT::rewireTo(SourceNodeXT *source) { if (!source->audioOutputPort()) { return; } ensureInstance(); xine_post_in_t *x = xine_post_input(m_plugin, "audio in"); Q_ASSERT(x); xine_post_wire(source->audioOutputPort(), x); } // lazy initialization void EffectXT::ensureInstance() { QMutexLocker lock(&m_mutex); if (m_plugin) { return; } createInstance(); Q_ASSERT(m_plugin); } xine_audio_port_t *EffectXT::fakeAudioPort() { if (!m_fakeAudioPort) { m_fakeAudioPort = xine_open_audio_driver(m_xine, "none", 0); } return m_fakeAudioPort; } void EffectXT::createInstance() { debug() << Q_FUNC_INFO << "m_pluginName =" << m_pluginName; Q_ASSERT(m_plugin == 0 && m_pluginApi == 0); if (!m_pluginName) { qWarning( "tried to create invalid Effect"); return; } fakeAudioPort(); m_plugin = xine_post_init(m_xine, m_pluginName, 1, &m_fakeAudioPort, 0); xine_post_in_t *paraInput = xine_post_input(m_plugin, "parameters"); if (!paraInput) { return; } Q_ASSERT(paraInput->type == XINE_POST_DATA_PARAMETERS); Q_ASSERT(paraInput->data); m_pluginApi = reinterpret_cast<xine_post_api_t *>(paraInput->data); if (!m_parameterList.isEmpty()) { return; } xine_post_api_descr_t *desc = m_pluginApi->get_param_descr(); if (m_pluginParams) { m_pluginApi->set_parameters(m_plugin, m_pluginParams); } else { m_pluginParams = static_cast<char *>(malloc(desc->struct_size)); m_pluginApi->get_parameters(m_plugin, m_pluginParams); for (int i = 0; desc->parameter[i].type != POST_PARAM_TYPE_LAST; ++i) { xine_post_api_parameter_t &p = desc->parameter[i]; switch (p.type) { case POST_PARAM_TYPE_INT: /* integer (or vector of integers) */ if (p.enum_values) { // it's an enum QVariantList values; for (int j = 0; p.enum_values[j]; ++j) { values << QString::fromUtf8(p.enum_values[j]); } m_parameterList << EffectParameter(i, QString::fromUtf8(p.description ? p.description : p.name), 0, *reinterpret_cast<int *>(m_pluginParams + p.offset), 0, values.count() - 1, values); } else { m_parameterList << EffectParameter(i, QString::fromUtf8(p.description ? p.description : p.name), EffectParameter::IntegerHint, *reinterpret_cast<int *>(m_pluginParams + p.offset), static_cast<int>(p.range_min), static_cast<int>(p.range_max), QVariantList()); } break; case POST_PARAM_TYPE_DOUBLE: /* double (or vector of doubles) */ m_parameterList << EffectParameter(i, QString::fromUtf8(p.description ? p.description : p.name), 0, *reinterpret_cast<double *>(m_pluginParams + p.offset), p.range_min, p.range_max, QVariantList()); break; case POST_PARAM_TYPE_CHAR: /* char (or vector of chars = string) */ case POST_PARAM_TYPE_STRING: /* (char *), ASCIIZ */ case POST_PARAM_TYPE_STRINGLIST: /* (char **) list, NULL terminated */ qWarning() << "char/string/stringlist parameter '" << (p.description ? p.description : p.name) << "' not supported."; break; case POST_PARAM_TYPE_BOOL: /* integer (0 or 1) */ m_parameterList << EffectParameter(i, QString::fromUtf8(p.description ? p.description : p.name), EffectParameter::ToggledHint, static_cast<bool>(*reinterpret_cast<int *>(m_pluginParams + p.offset)), QVariant(), QVariant(), QVariantList()); break; case POST_PARAM_TYPE_LAST: /* terminator of parameter list */ default: abort(); } } } } Effect::Effect(int effectId, QObject *parent) : QObject(parent), SinkNode(new EffectXT(0)), SourceNode(static_cast<EffectXT *>(SinkNode::threadSafeObject().data())) { K_XT(Effect); const char *const *postPlugins = xine_list_post_plugins_typed(xt->m_xine, XINE_POST_TYPE_AUDIO_FILTER); if (effectId >= 0x7F000000) { effectId -= 0x7F000000; for(int i = 0; postPlugins[i]; ++i) { if (i == effectId) { // found it xt->m_pluginName = postPlugins[i]; break; } } } } Effect::Effect(EffectXT *xt, QObject *parent) : QObject(parent), SinkNode(xt), SourceNode(xt) { } EffectXT::EffectXT(const char *name) : SourceNodeXT("Effect"), SinkNodeXT("Effect"), m_plugin(0), m_pluginApi(0), m_fakeAudioPort(0), m_pluginName(name), m_pluginParams(0) { m_xine = Backend::xine(); } EffectXT::~EffectXT() { if (m_plugin) { xine_post_dispose(m_xine, m_plugin); m_plugin = 0; m_pluginApi = 0; if (m_fakeAudioPort) { xine_close_audio_driver(m_xine, m_fakeAudioPort); m_fakeAudioPort = 0; } } free(m_pluginParams); m_pluginParams = 0; } bool Effect::isValid() const { K_XT(const Effect); return xt->m_pluginName != 0; } MediaStreamTypes Effect::inputMediaStreamTypes() const { return Phonon::Xine::Audio; } MediaStreamTypes Effect::outputMediaStreamTypes() const { return Phonon::Xine::Audio; } QList<EffectParameter> Effect::parameters() const { const_cast<Effect *>(this)->ensureParametersReady(); K_XT(const Effect); return xt->m_parameterList; } void Effect::ensureParametersReady() { K_XT(Effect); xt->ensureInstance(); } QVariant Effect::parameterValue(const EffectParameter &p) const { const int parameterIndex = p.id(); K_XT(const Effect); QMutexLocker lock(&xt->m_mutex); if (!xt->m_plugin || !xt->m_pluginApi) { return QVariant(); // invalid } xine_post_api_descr_t *desc = xt->m_pluginApi->get_param_descr(); Q_ASSERT(xt->m_pluginParams); xt->m_pluginApi->get_parameters(xt->m_plugin, xt->m_pluginParams); int i = 0; for (; i < parameterIndex && desc->parameter[i].type != POST_PARAM_TYPE_LAST; ++i); if (i == parameterIndex) { xine_post_api_parameter_t &p = desc->parameter[i]; switch (p.type) { case POST_PARAM_TYPE_INT: /* integer (or vector of integers) */ return *reinterpret_cast<int *>(xt->m_pluginParams + p.offset); case POST_PARAM_TYPE_DOUBLE: /* double (or vector of doubles) */ return *reinterpret_cast<double *>(xt->m_pluginParams + p.offset); case POST_PARAM_TYPE_CHAR: /* char (or vector of chars = string) */ case POST_PARAM_TYPE_STRING: /* (char *), ASCIIZ */ case POST_PARAM_TYPE_STRINGLIST: /* (char **) list, NULL terminated */ qWarning() << "char/string/stringlist parameter '" << (p.description ? p.description : p.name) << "' not supported."; return QVariant(); case POST_PARAM_TYPE_BOOL: /* integer (0 or 1) */ return static_cast<bool>(*reinterpret_cast<int *>(xt->m_pluginParams + p.offset)); case POST_PARAM_TYPE_LAST: /* terminator of parameter list */ break; default: abort(); } } qWarning() << "invalid parameterIndex passed to Effect::value"; return QVariant(); } void Effect::setParameterValue(const EffectParameter &p, const QVariant &newValue) { K_XT(Effect); const int parameterIndex = p.id(); QMutexLocker lock(&xt->m_mutex); if (!xt->m_plugin || !xt->m_pluginApi) { return; } xine_post_api_descr_t *desc = xt->m_pluginApi->get_param_descr(); Q_ASSERT(xt->m_pluginParams); int i = 0; for (; i < parameterIndex && desc->parameter[i].type != POST_PARAM_TYPE_LAST; ++i); if (i == parameterIndex) { xine_post_api_parameter_t &p = desc->parameter[i]; switch (p.type) { case POST_PARAM_TYPE_INT: /* integer (or vector of integers) */ if (p.enum_values && newValue.type() == QVariant::String) { // need to convert to index int *value = reinterpret_cast<int *>(xt->m_pluginParams + p.offset); const QString string = newValue.toString(); for (int j = 0; p.enum_values[j]; ++j) { if (string == QString::fromUtf8(p.enum_values[j])) { *value = j; break; } } } else { int *value = reinterpret_cast<int *>(xt->m_pluginParams + p.offset); *value = newValue.toInt(); } break; case POST_PARAM_TYPE_DOUBLE: /* double (or vector of doubles) */ { double *value = reinterpret_cast<double *>(xt->m_pluginParams + p.offset); *value = newValue.toDouble(); } break; case POST_PARAM_TYPE_CHAR: /* char (or vector of chars = string) */ case POST_PARAM_TYPE_STRING: /* (char *), ASCIIZ */ case POST_PARAM_TYPE_STRINGLIST: /* (char **) list, NULL terminated */ qWarning() << "char/string/stringlist parameter '" << (p.description ? p.description : p.name) << "' not supported." ; return; case POST_PARAM_TYPE_BOOL: /* integer (0 or 1) */ { int *value = reinterpret_cast<int *>(xt->m_pluginParams + p.offset); *value = newValue.toBool() ? 1 : 0; } break; case POST_PARAM_TYPE_LAST: /* terminator of parameter list */ qWarning() << "invalid parameterIndex passed to Effect::setValue"; break; default: abort(); } xt->m_pluginApi->set_parameters(xt->m_plugin, xt->m_pluginParams); } else { qWarning() << "invalid parameterIndex passed to Effect::setValue"; } } void Effect::addParameter(const EffectParameter &p) { K_XT(Effect); xt->m_parameterList << p; } void Effect::aboutToChangeXineEngine() { K_XT(Effect); if (xt->m_plugin) { EffectXT *xt2 = new EffectXT(xt->m_pluginName); xt2->m_xine = xt->m_xine; xt2->m_plugin = xt->m_plugin; xt2->m_pluginApi = xt->m_pluginApi; xt2->m_fakeAudioPort = xt->m_fakeAudioPort; xt->m_plugin = 0; xt->m_pluginApi = 0; xt->m_fakeAudioPort = 0; KeepReference<> *keep = new KeepReference<>; keep->addObject(static_cast<SinkNodeXT *>(xt2)); keep->ready(); } } void Effect::xineEngineChanged() { K_XT(Effect); if (!xt->m_xine) { xt->m_xine = Backend::xine(); } //xt->createInstance(); } }} //namespace Phonon::Xine #include "moc_effect.cpp" <commit_msg>newer gcc warns about this and suggests to insert a space<commit_after>/* This file is part of the KDE project Copyright (C) 2006 Tim Beaulen <tbscope@gmail.com> Copyright (C) 2006-2007 Matthias Kretz <kretz@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "effect.h" #include <QVariant> #include "xineengine.h" #include <QMutexLocker> #include "events.h" #include "keepreference.h" namespace Phonon { namespace Xine { xine_audio_port_t *EffectXT::audioPort() const { const_cast<EffectXT *>(this)->ensureInstance(); Q_ASSERT(m_plugin); Q_ASSERT(m_plugin->audio_input); Q_ASSERT(m_plugin->audio_input[0]); return m_plugin->audio_input[0]; } xine_post_out_t *EffectXT::audioOutputPort() const { const_cast<EffectXT *>(this)->ensureInstance(); Q_ASSERT(m_plugin); xine_post_out_t *x = xine_post_output(m_plugin, "audio out"); Q_ASSERT(x); return x; } void EffectXT::rewireTo(SourceNodeXT *source) { if (!source->audioOutputPort()) { return; } ensureInstance(); xine_post_in_t *x = xine_post_input(m_plugin, "audio in"); Q_ASSERT(x); xine_post_wire(source->audioOutputPort(), x); } // lazy initialization void EffectXT::ensureInstance() { QMutexLocker lock(&m_mutex); if (m_plugin) { return; } createInstance(); Q_ASSERT(m_plugin); } xine_audio_port_t *EffectXT::fakeAudioPort() { if (!m_fakeAudioPort) { m_fakeAudioPort = xine_open_audio_driver(m_xine, "none", 0); } return m_fakeAudioPort; } void EffectXT::createInstance() { debug() << Q_FUNC_INFO << "m_pluginName =" << m_pluginName; Q_ASSERT(m_plugin == 0 && m_pluginApi == 0); if (!m_pluginName) { qWarning( "tried to create invalid Effect"); return; } fakeAudioPort(); m_plugin = xine_post_init(m_xine, m_pluginName, 1, &m_fakeAudioPort, 0); xine_post_in_t *paraInput = xine_post_input(m_plugin, "parameters"); if (!paraInput) { return; } Q_ASSERT(paraInput->type == XINE_POST_DATA_PARAMETERS); Q_ASSERT(paraInput->data); m_pluginApi = reinterpret_cast<xine_post_api_t *>(paraInput->data); if (!m_parameterList.isEmpty()) { return; } xine_post_api_descr_t *desc = m_pluginApi->get_param_descr(); if (m_pluginParams) { m_pluginApi->set_parameters(m_plugin, m_pluginParams); } else { m_pluginParams = static_cast<char *>(malloc(desc->struct_size)); m_pluginApi->get_parameters(m_plugin, m_pluginParams); for (int i = 0; desc->parameter[i].type != POST_PARAM_TYPE_LAST; ++i) { xine_post_api_parameter_t &p = desc->parameter[i]; switch (p.type) { case POST_PARAM_TYPE_INT: /* integer (or vector of integers) */ if (p.enum_values) { // it's an enum QVariantList values; for (int j = 0; p.enum_values[j]; ++j) { values << QString::fromUtf8(p.enum_values[j]); } m_parameterList << EffectParameter(i, QString::fromUtf8(p.description ? p.description : p.name), 0, *reinterpret_cast<int *>(m_pluginParams + p.offset), 0, values.count() - 1, values); } else { m_parameterList << EffectParameter(i, QString::fromUtf8(p.description ? p.description : p.name), EffectParameter::IntegerHint, *reinterpret_cast<int *>(m_pluginParams + p.offset), static_cast<int>(p.range_min), static_cast<int>(p.range_max), QVariantList()); } break; case POST_PARAM_TYPE_DOUBLE: /* double (or vector of doubles) */ m_parameterList << EffectParameter(i, QString::fromUtf8(p.description ? p.description : p.name), 0, *reinterpret_cast<double *>(m_pluginParams + p.offset), p.range_min, p.range_max, QVariantList()); break; case POST_PARAM_TYPE_CHAR: /* char (or vector of chars = string) */ case POST_PARAM_TYPE_STRING: /* (char *), ASCIIZ */ case POST_PARAM_TYPE_STRINGLIST: /* (char **) list, NULL terminated */ qWarning() << "char/string/stringlist parameter '" << (p.description ? p.description : p.name) << "' not supported."; break; case POST_PARAM_TYPE_BOOL: /* integer (0 or 1) */ m_parameterList << EffectParameter(i, QString::fromUtf8(p.description ? p.description : p.name), EffectParameter::ToggledHint, static_cast<bool>(*reinterpret_cast<int *>(m_pluginParams + p.offset)), QVariant(), QVariant(), QVariantList()); break; case POST_PARAM_TYPE_LAST: /* terminator of parameter list */ default: abort(); } } } } Effect::Effect(int effectId, QObject *parent) : QObject(parent), SinkNode(new EffectXT(0)), SourceNode(static_cast<EffectXT *>(SinkNode::threadSafeObject().data())) { K_XT(Effect); const char *const *postPlugins = xine_list_post_plugins_typed(xt->m_xine, XINE_POST_TYPE_AUDIO_FILTER); if (effectId >= 0x7F000000) { effectId -= 0x7F000000; for(int i = 0; postPlugins[i]; ++i) { if (i == effectId) { // found it xt->m_pluginName = postPlugins[i]; break; } } } } Effect::Effect(EffectXT *xt, QObject *parent) : QObject(parent), SinkNode(xt), SourceNode(xt) { } EffectXT::EffectXT(const char *name) : SourceNodeXT("Effect"), SinkNodeXT("Effect"), m_plugin(0), m_pluginApi(0), m_fakeAudioPort(0), m_pluginName(name), m_pluginParams(0) { m_xine = Backend::xine(); } EffectXT::~EffectXT() { if (m_plugin) { xine_post_dispose(m_xine, m_plugin); m_plugin = 0; m_pluginApi = 0; if (m_fakeAudioPort) { xine_close_audio_driver(m_xine, m_fakeAudioPort); m_fakeAudioPort = 0; } } free(m_pluginParams); m_pluginParams = 0; } bool Effect::isValid() const { K_XT(const Effect); return xt->m_pluginName != 0; } MediaStreamTypes Effect::inputMediaStreamTypes() const { return Phonon::Xine::Audio; } MediaStreamTypes Effect::outputMediaStreamTypes() const { return Phonon::Xine::Audio; } QList<EffectParameter> Effect::parameters() const { const_cast<Effect *>(this)->ensureParametersReady(); K_XT(const Effect); return xt->m_parameterList; } void Effect::ensureParametersReady() { K_XT(Effect); xt->ensureInstance(); } QVariant Effect::parameterValue(const EffectParameter &p) const { const int parameterIndex = p.id(); K_XT(const Effect); QMutexLocker lock(&xt->m_mutex); if (!xt->m_plugin || !xt->m_pluginApi) { return QVariant(); // invalid } xine_post_api_descr_t *desc = xt->m_pluginApi->get_param_descr(); Q_ASSERT(xt->m_pluginParams); xt->m_pluginApi->get_parameters(xt->m_plugin, xt->m_pluginParams); int i = 0; for (; i < parameterIndex && desc->parameter[i].type != POST_PARAM_TYPE_LAST; ++i) ; if (i == parameterIndex) { xine_post_api_parameter_t &p = desc->parameter[i]; switch (p.type) { case POST_PARAM_TYPE_INT: /* integer (or vector of integers) */ return *reinterpret_cast<int *>(xt->m_pluginParams + p.offset); case POST_PARAM_TYPE_DOUBLE: /* double (or vector of doubles) */ return *reinterpret_cast<double *>(xt->m_pluginParams + p.offset); case POST_PARAM_TYPE_CHAR: /* char (or vector of chars = string) */ case POST_PARAM_TYPE_STRING: /* (char *), ASCIIZ */ case POST_PARAM_TYPE_STRINGLIST: /* (char **) list, NULL terminated */ qWarning() << "char/string/stringlist parameter '" << (p.description ? p.description : p.name) << "' not supported."; return QVariant(); case POST_PARAM_TYPE_BOOL: /* integer (0 or 1) */ return static_cast<bool>(*reinterpret_cast<int *>(xt->m_pluginParams + p.offset)); case POST_PARAM_TYPE_LAST: /* terminator of parameter list */ break; default: abort(); } } qWarning() << "invalid parameterIndex passed to Effect::value"; return QVariant(); } void Effect::setParameterValue(const EffectParameter &p, const QVariant &newValue) { K_XT(Effect); const int parameterIndex = p.id(); QMutexLocker lock(&xt->m_mutex); if (!xt->m_plugin || !xt->m_pluginApi) { return; } xine_post_api_descr_t *desc = xt->m_pluginApi->get_param_descr(); Q_ASSERT(xt->m_pluginParams); int i = 0; for (; i < parameterIndex && desc->parameter[i].type != POST_PARAM_TYPE_LAST; ++i) ; if (i == parameterIndex) { xine_post_api_parameter_t &p = desc->parameter[i]; switch (p.type) { case POST_PARAM_TYPE_INT: /* integer (or vector of integers) */ if (p.enum_values && newValue.type() == QVariant::String) { // need to convert to index int *value = reinterpret_cast<int *>(xt->m_pluginParams + p.offset); const QString string = newValue.toString(); for (int j = 0; p.enum_values[j]; ++j) { if (string == QString::fromUtf8(p.enum_values[j])) { *value = j; break; } } } else { int *value = reinterpret_cast<int *>(xt->m_pluginParams + p.offset); *value = newValue.toInt(); } break; case POST_PARAM_TYPE_DOUBLE: /* double (or vector of doubles) */ { double *value = reinterpret_cast<double *>(xt->m_pluginParams + p.offset); *value = newValue.toDouble(); } break; case POST_PARAM_TYPE_CHAR: /* char (or vector of chars = string) */ case POST_PARAM_TYPE_STRING: /* (char *), ASCIIZ */ case POST_PARAM_TYPE_STRINGLIST: /* (char **) list, NULL terminated */ qWarning() << "char/string/stringlist parameter '" << (p.description ? p.description : p.name) << "' not supported." ; return; case POST_PARAM_TYPE_BOOL: /* integer (0 or 1) */ { int *value = reinterpret_cast<int *>(xt->m_pluginParams + p.offset); *value = newValue.toBool() ? 1 : 0; } break; case POST_PARAM_TYPE_LAST: /* terminator of parameter list */ qWarning() << "invalid parameterIndex passed to Effect::setValue"; break; default: abort(); } xt->m_pluginApi->set_parameters(xt->m_plugin, xt->m_pluginParams); } else { qWarning() << "invalid parameterIndex passed to Effect::setValue"; } } void Effect::addParameter(const EffectParameter &p) { K_XT(Effect); xt->m_parameterList << p; } void Effect::aboutToChangeXineEngine() { K_XT(Effect); if (xt->m_plugin) { EffectXT *xt2 = new EffectXT(xt->m_pluginName); xt2->m_xine = xt->m_xine; xt2->m_plugin = xt->m_plugin; xt2->m_pluginApi = xt->m_pluginApi; xt2->m_fakeAudioPort = xt->m_fakeAudioPort; xt->m_plugin = 0; xt->m_pluginApi = 0; xt->m_fakeAudioPort = 0; KeepReference<> *keep = new KeepReference<>; keep->addObject(static_cast<SinkNodeXT *>(xt2)); keep->ready(); } } void Effect::xineEngineChanged() { K_XT(Effect); if (!xt->m_xine) { xt->m_xine = Backend::xine(); } //xt->createInstance(); } }} //namespace Phonon::Xine #include "moc_effect.cpp" <|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/common/extensions/extension_file_util.h" #include "base/file_util.h" #include "base/json/json_value_serializer.h" #include "base/path_service.h" #include "base/scoped_temp_dir.h" #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "testing/gtest/include/gtest/gtest.h" namespace keys = extension_manifest_keys; #if defined(OS_WIN) // http://crbug.com/106381 #define InstallUninstallGarbageCollect DISABLED_InstallUninstallGarbageCollect #endif TEST(ExtensionFileUtil, InstallUninstallGarbageCollect) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); // Create a source extension. std::string extension_id("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); std::string version("1.0"); FilePath src = temp.path().AppendASCII(extension_id); ASSERT_TRUE(file_util::CreateDirectory(src)); // Create a extensions tree. FilePath all_extensions = temp.path().AppendASCII("extensions"); ASSERT_TRUE(file_util::CreateDirectory(all_extensions)); // Install in empty directory. Should create parent directories as needed. FilePath version_1 = extension_file_util::InstallExtension(src, extension_id, version, all_extensions); ASSERT_EQ(version_1.value(), all_extensions.AppendASCII(extension_id).AppendASCII("1.0_0") .value()); ASSERT_TRUE(file_util::DirectoryExists(version_1)); // Should have moved the source. ASSERT_FALSE(file_util::DirectoryExists(src)); // Install again. Should create a new one with different name. ASSERT_TRUE(file_util::CreateDirectory(src)); FilePath version_2 = extension_file_util::InstallExtension(src, extension_id, version, all_extensions); ASSERT_EQ(version_2.value(), all_extensions.AppendASCII(extension_id).AppendASCII("1.0_1") .value()); ASSERT_TRUE(file_util::DirectoryExists(version_2)); // Collect garbage. Should remove first one. std::map<std::string, FilePath> extension_paths; extension_paths[extension_id] = FilePath().AppendASCII(extension_id).Append(version_2.BaseName()); extension_file_util::GarbageCollectExtensions(all_extensions, extension_paths); ASSERT_FALSE(file_util::DirectoryExists(version_1)); ASSERT_TRUE(file_util::DirectoryExists(version_2)); // Uninstall. Should remove entire extension subtree. extension_file_util::UninstallExtension(all_extensions, extension_id); ASSERT_FALSE(file_util::DirectoryExists(version_2.DirName())); ASSERT_TRUE(file_util::DirectoryExists(all_extensions)); } TEST(ExtensionFileUtil, LoadExtensionWithValidLocales) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj") .AppendASCII("1.0.0.0"); std::string error; scoped_refptr<Extension> extension(extension_file_util::LoadExtension( install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error)); ASSERT_TRUE(extension != NULL); EXPECT_EQ("The first extension that I made.", extension->description()); } TEST(ExtensionFileUtil, LoadExtensionWithoutLocalesFolder) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa") .AppendASCII("1.0"); std::string error; scoped_refptr<Extension> extension(extension_file_util::LoadExtension( install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error)); ASSERT_FALSE(extension == NULL); EXPECT_TRUE(error.empty()); } #if defined(OS_WIN) // http://crbug.com/106381 #define CheckIllegalFilenamesNoUnderscores \ DISABLED_CheckIllegalFilenamesNoUnderscores #endif TEST(ExtensionFileUtil, CheckIllegalFilenamesNoUnderscores) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src_path = temp.path().AppendASCII("some_dir"); ASSERT_TRUE(file_util::CreateDirectory(src_path)); std::string data = "{ \"name\": { \"message\": \"foobar\" } }"; ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII("some_file.txt"), data.c_str(), data.length())); std::string error; EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(), &error)); } #if defined(OS_WIN) // http://crbug.com/106381 #define CheckIllegalFilenamesOnlyReserved \ DISABLED_CheckIllegalFilenamesOnlyReserved #endif TEST(ExtensionFileUtil, CheckIllegalFilenamesOnlyReserved) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src_path = temp.path().Append(Extension::kLocaleFolder); ASSERT_TRUE(file_util::CreateDirectory(src_path)); std::string error; EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(), &error)); } #if defined(OS_WIN) // http://crbug.com/106381 #define CheckIllegalFilenamesReservedAndIllegal \ DISABLED_CheckIllegalFilenamesReservedAndIllegal #endif TEST(ExtensionFileUtil, CheckIllegalFilenamesReservedAndIllegal) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src_path = temp.path().Append(Extension::kLocaleFolder); ASSERT_TRUE(file_util::CreateDirectory(src_path)); src_path = temp.path().AppendASCII("_some_dir"); ASSERT_TRUE(file_util::CreateDirectory(src_path)); std::string error; EXPECT_FALSE(extension_file_util::CheckForIllegalFilenames(temp.path(), &error)); } TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnMissingManifest) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("bad") .AppendASCII("Extensions") .AppendASCII("dddddddddddddddddddddddddddddddd") .AppendASCII("1.0"); std::string error; scoped_refptr<Extension> extension(extension_file_util::LoadExtension( install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error)); ASSERT_TRUE(extension == NULL); ASSERT_FALSE(error.empty()); ASSERT_STREQ("Manifest file is missing or unreadable.", error.c_str()); } TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnBadManifest) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("bad") .AppendASCII("Extensions") .AppendASCII("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee") .AppendASCII("1.0"); std::string error; scoped_refptr<Extension> extension(extension_file_util::LoadExtension( install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error)); ASSERT_TRUE(extension == NULL); ASSERT_FALSE(error.empty()); ASSERT_STREQ("Manifest is not valid JSON. " "Line: 2, column: 16, Syntax error.", error.c_str()); } TEST(ExtensionFileUtil, FailLoadingNonUTF8Scripts) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("bad") .AppendASCII("bad_encoding"); std::string error; scoped_refptr<Extension> extension(extension_file_util::LoadExtension( install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error)); ASSERT_TRUE(extension == NULL); ASSERT_STREQ("Could not load file 'bad_encoding.js' for content script. " "It isn't UTF-8 encoded.", error.c_str()); } #define URL_PREFIX "chrome-extension://extension-id/" TEST(ExtensionFileUtil, ExtensionURLToRelativeFilePath) { struct TestCase { const char* url; const char* expected_relative_path; } test_cases[] = { { URL_PREFIX "simple.html", "simple.html" }, { URL_PREFIX "directory/to/file.html", "directory/to/file.html" }, { URL_PREFIX "escape%20spaces.html", "escape spaces.html" }, { URL_PREFIX "%C3%9Cber.html", "\xC3\x9C" "ber.html" }, #if defined(OS_WIN) { URL_PREFIX "C%3A/simple.html", "" }, #endif { URL_PREFIX "////simple.html", "simple.html" }, { URL_PREFIX "/simple.html", "simple.html" }, { URL_PREFIX "\\simple.html", "simple.html" }, { URL_PREFIX "\\\\foo\\simple.html", "foo/simple.html" }, }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) { GURL url(test_cases[i].url); #if defined(OS_POSIX) FilePath expected_path(test_cases[i].expected_relative_path); #elif defined(OS_WIN) FilePath expected_path(UTF8ToWide(test_cases[i].expected_relative_path)); #endif FilePath actual_path = extension_file_util::ExtensionURLToRelativeFilePath(url); EXPECT_FALSE(actual_path.IsAbsolute()) << " For the path " << actual_path.value(); EXPECT_EQ(expected_path.value(), actual_path.value()) << " For the path " << url; } } static scoped_refptr<Extension> LoadExtensionManifest( const std::string& manifest_value, const FilePath& manifest_dir, Extension::Location location, int extra_flags, std::string* error) { JSONStringValueSerializer serializer(manifest_value); scoped_ptr<Value> result(serializer.Deserialize(NULL, error)); if (!result.get()) return NULL; scoped_refptr<Extension> extension = Extension::Create( manifest_dir, location, *static_cast<DictionaryValue*>(result.get()), extra_flags, error); return extension; } TEST(ExtensionFileUtil, ValidateThemeUTF8) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); // "aeo" with accents. Use http://0xcc.net/jsescape/ to decode them. std::string non_ascii_file = "\xC3\xA0\xC3\xA8\xC3\xB2.png"; FilePath non_ascii_path = temp.path().Append(FilePath::FromUTF8Unsafe( non_ascii_file)); file_util::WriteFile(non_ascii_path, "", 0); std::string kManifest = base::StringPrintf( "{ \"name\": \"Test\", \"version\": \"1.0\", " " \"theme\": { \"images\": { \"theme_frame\": \"%s\" } }" "}", non_ascii_file.c_str()); std::string error; scoped_refptr<Extension> extension = LoadExtensionManifest( kManifest, temp.path(), Extension::LOAD, 0, &error); ASSERT_TRUE(extension.get()) << error; EXPECT_TRUE(extension_file_util::ValidateExtension(extension, &error)) << error; } // TODO(aa): More tests as motivation allows. Maybe steal some from // ExtensionService? Many of them could probably be tested here without the // MessageLoop shenanigans. <commit_msg>Disable ExtensionFileUtil.ValidateThemeUTF8 on Windows<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/common/extensions/extension_file_util.h" #include "base/file_util.h" #include "base/json/json_value_serializer.h" #include "base/path_service.h" #include "base/scoped_temp_dir.h" #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "testing/gtest/include/gtest/gtest.h" namespace keys = extension_manifest_keys; #if defined(OS_WIN) // http://crbug.com/106381 #define InstallUninstallGarbageCollect DISABLED_InstallUninstallGarbageCollect #endif TEST(ExtensionFileUtil, InstallUninstallGarbageCollect) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); // Create a source extension. std::string extension_id("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); std::string version("1.0"); FilePath src = temp.path().AppendASCII(extension_id); ASSERT_TRUE(file_util::CreateDirectory(src)); // Create a extensions tree. FilePath all_extensions = temp.path().AppendASCII("extensions"); ASSERT_TRUE(file_util::CreateDirectory(all_extensions)); // Install in empty directory. Should create parent directories as needed. FilePath version_1 = extension_file_util::InstallExtension(src, extension_id, version, all_extensions); ASSERT_EQ(version_1.value(), all_extensions.AppendASCII(extension_id).AppendASCII("1.0_0") .value()); ASSERT_TRUE(file_util::DirectoryExists(version_1)); // Should have moved the source. ASSERT_FALSE(file_util::DirectoryExists(src)); // Install again. Should create a new one with different name. ASSERT_TRUE(file_util::CreateDirectory(src)); FilePath version_2 = extension_file_util::InstallExtension(src, extension_id, version, all_extensions); ASSERT_EQ(version_2.value(), all_extensions.AppendASCII(extension_id).AppendASCII("1.0_1") .value()); ASSERT_TRUE(file_util::DirectoryExists(version_2)); // Collect garbage. Should remove first one. std::map<std::string, FilePath> extension_paths; extension_paths[extension_id] = FilePath().AppendASCII(extension_id).Append(version_2.BaseName()); extension_file_util::GarbageCollectExtensions(all_extensions, extension_paths); ASSERT_FALSE(file_util::DirectoryExists(version_1)); ASSERT_TRUE(file_util::DirectoryExists(version_2)); // Uninstall. Should remove entire extension subtree. extension_file_util::UninstallExtension(all_extensions, extension_id); ASSERT_FALSE(file_util::DirectoryExists(version_2.DirName())); ASSERT_TRUE(file_util::DirectoryExists(all_extensions)); } TEST(ExtensionFileUtil, LoadExtensionWithValidLocales) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj") .AppendASCII("1.0.0.0"); std::string error; scoped_refptr<Extension> extension(extension_file_util::LoadExtension( install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error)); ASSERT_TRUE(extension != NULL); EXPECT_EQ("The first extension that I made.", extension->description()); } TEST(ExtensionFileUtil, LoadExtensionWithoutLocalesFolder) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa") .AppendASCII("1.0"); std::string error; scoped_refptr<Extension> extension(extension_file_util::LoadExtension( install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error)); ASSERT_FALSE(extension == NULL); EXPECT_TRUE(error.empty()); } #if defined(OS_WIN) // http://crbug.com/106381 #define CheckIllegalFilenamesNoUnderscores \ DISABLED_CheckIllegalFilenamesNoUnderscores #endif TEST(ExtensionFileUtil, CheckIllegalFilenamesNoUnderscores) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src_path = temp.path().AppendASCII("some_dir"); ASSERT_TRUE(file_util::CreateDirectory(src_path)); std::string data = "{ \"name\": { \"message\": \"foobar\" } }"; ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII("some_file.txt"), data.c_str(), data.length())); std::string error; EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(), &error)); } #if defined(OS_WIN) // http://crbug.com/106381 #define CheckIllegalFilenamesOnlyReserved \ DISABLED_CheckIllegalFilenamesOnlyReserved #endif TEST(ExtensionFileUtil, CheckIllegalFilenamesOnlyReserved) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src_path = temp.path().Append(Extension::kLocaleFolder); ASSERT_TRUE(file_util::CreateDirectory(src_path)); std::string error; EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(), &error)); } #if defined(OS_WIN) // http://crbug.com/106381 #define CheckIllegalFilenamesReservedAndIllegal \ DISABLED_CheckIllegalFilenamesReservedAndIllegal #endif TEST(ExtensionFileUtil, CheckIllegalFilenamesReservedAndIllegal) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src_path = temp.path().Append(Extension::kLocaleFolder); ASSERT_TRUE(file_util::CreateDirectory(src_path)); src_path = temp.path().AppendASCII("_some_dir"); ASSERT_TRUE(file_util::CreateDirectory(src_path)); std::string error; EXPECT_FALSE(extension_file_util::CheckForIllegalFilenames(temp.path(), &error)); } TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnMissingManifest) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("bad") .AppendASCII("Extensions") .AppendASCII("dddddddddddddddddddddddddddddddd") .AppendASCII("1.0"); std::string error; scoped_refptr<Extension> extension(extension_file_util::LoadExtension( install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error)); ASSERT_TRUE(extension == NULL); ASSERT_FALSE(error.empty()); ASSERT_STREQ("Manifest file is missing or unreadable.", error.c_str()); } TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnBadManifest) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("bad") .AppendASCII("Extensions") .AppendASCII("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee") .AppendASCII("1.0"); std::string error; scoped_refptr<Extension> extension(extension_file_util::LoadExtension( install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error)); ASSERT_TRUE(extension == NULL); ASSERT_FALSE(error.empty()); ASSERT_STREQ("Manifest is not valid JSON. " "Line: 2, column: 16, Syntax error.", error.c_str()); } TEST(ExtensionFileUtil, FailLoadingNonUTF8Scripts) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("bad") .AppendASCII("bad_encoding"); std::string error; scoped_refptr<Extension> extension(extension_file_util::LoadExtension( install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error)); ASSERT_TRUE(extension == NULL); ASSERT_STREQ("Could not load file 'bad_encoding.js' for content script. " "It isn't UTF-8 encoded.", error.c_str()); } #define URL_PREFIX "chrome-extension://extension-id/" TEST(ExtensionFileUtil, ExtensionURLToRelativeFilePath) { struct TestCase { const char* url; const char* expected_relative_path; } test_cases[] = { { URL_PREFIX "simple.html", "simple.html" }, { URL_PREFIX "directory/to/file.html", "directory/to/file.html" }, { URL_PREFIX "escape%20spaces.html", "escape spaces.html" }, { URL_PREFIX "%C3%9Cber.html", "\xC3\x9C" "ber.html" }, #if defined(OS_WIN) { URL_PREFIX "C%3A/simple.html", "" }, #endif { URL_PREFIX "////simple.html", "simple.html" }, { URL_PREFIX "/simple.html", "simple.html" }, { URL_PREFIX "\\simple.html", "simple.html" }, { URL_PREFIX "\\\\foo\\simple.html", "foo/simple.html" }, }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) { GURL url(test_cases[i].url); #if defined(OS_POSIX) FilePath expected_path(test_cases[i].expected_relative_path); #elif defined(OS_WIN) FilePath expected_path(UTF8ToWide(test_cases[i].expected_relative_path)); #endif FilePath actual_path = extension_file_util::ExtensionURLToRelativeFilePath(url); EXPECT_FALSE(actual_path.IsAbsolute()) << " For the path " << actual_path.value(); EXPECT_EQ(expected_path.value(), actual_path.value()) << " For the path " << url; } } static scoped_refptr<Extension> LoadExtensionManifest( const std::string& manifest_value, const FilePath& manifest_dir, Extension::Location location, int extra_flags, std::string* error) { JSONStringValueSerializer serializer(manifest_value); scoped_ptr<Value> result(serializer.Deserialize(NULL, error)); if (!result.get()) return NULL; scoped_refptr<Extension> extension = Extension::Create( manifest_dir, location, *static_cast<DictionaryValue*>(result.get()), extra_flags, error); return extension; } #if defined(OS_WIN) // http://crbug.com/108279 #define ValidateThemeUTF8 DISABLED_ValidateThemeUTF8 #endif TEST(ExtensionFileUtil, ValidateThemeUTF8) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); // "aeo" with accents. Use http://0xcc.net/jsescape/ to decode them. std::string non_ascii_file = "\xC3\xA0\xC3\xA8\xC3\xB2.png"; FilePath non_ascii_path = temp.path().Append(FilePath::FromUTF8Unsafe( non_ascii_file)); file_util::WriteFile(non_ascii_path, "", 0); std::string kManifest = base::StringPrintf( "{ \"name\": \"Test\", \"version\": \"1.0\", " " \"theme\": { \"images\": { \"theme_frame\": \"%s\" } }" "}", non_ascii_file.c_str()); std::string error; scoped_refptr<Extension> extension = LoadExtensionManifest( kManifest, temp.path(), Extension::LOAD, 0, &error); ASSERT_TRUE(extension.get()) << error; EXPECT_TRUE(extension_file_util::ValidateExtension(extension, &error)) << error; } // TODO(aa): More tests as motivation allows. Maybe steal some from // ExtensionService? Many of them could probably be tested here without the // MessageLoop shenanigans. <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <exception> #include <algorithm> #include <iostream> using std::endl ; #include <vector> using std::vector ; #include <sofa/helper/logging/Messaging.h> using sofa::helper::logging::MessageDispatcher ; #include <sofa/helper/logging/MessageHandler.h> using sofa::helper::logging::MessageHandler ; #include <sofa/helper/logging/Message.h> using sofa::helper::logging::Message ; #include <sofa/core/objectmodel/BaseObject.h> #include <sofa/core/ObjectFactory.h> class MyMessageHandler : public MessageHandler { vector<Message> m_messages ; public: virtual void process(Message& m){ m_messages.push_back(m); // if( !m.sender().empty() ) // std::cerr<<m<<std::endl; } int numMessages(){ return m_messages.size() ; } const vector<Message>& messages() const { return m_messages; } const Message& lastMessage() const { return m_messages.back(); } } ; class MyComponent : public sofa::core::objectmodel::BaseObject { public: SOFA_CLASS( MyComponent, sofa::core::objectmodel::BaseObject ); MyComponent() { f_printLog.setValue(true); // to print sout serr<<"regular serr"<<sendl; sout<<"regular sout"<<sendl; serr<<SOFA_FILE_INFO<<"serr with fileinfo"<<sendl; sout<<SOFA_FILE_INFO<<"sout with fileinfo"<<sendl; } }; SOFA_DECL_CLASS(MyComponent) int MyComponentClass = sofa::core::RegisterObject("MyComponent") .add< MyComponent >(); TEST(LoggingTest, noHandler) { MessageDispatcher::clearHandlers() ; msg_info("") << " info message with conversion" << 1.5 << "\n" ; msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; msg_error("") << " error message with conversion" << 1.5 << "\n" ; } TEST(LoggingTest, oneHandler) { MessageDispatcher::clearHandlers() ; MyMessageHandler *h=new MyMessageHandler() ; // add is expected to return the handler ID. Here is it the o'th EXPECT_TRUE(MessageDispatcher::addHandler(h) == 0 ) ; msg_info("") << " info message with conversion" << 1.5 << "\n" ; msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; msg_error("") << " error message with conversion" << 1.5 << "\n" ; EXPECT_TRUE( h->numMessages() == 3 ) ; } TEST(LoggingTest, duplicatedHandler) { MessageDispatcher::clearHandlers() ; MyMessageHandler *h=new MyMessageHandler() ; // First add is expected to return the handler ID. EXPECT_TRUE(MessageDispatcher::addHandler(h) == 0) ; // Second is supposed to fail to add and thus return -1. EXPECT_TRUE(MessageDispatcher::addHandler(h) == -1) ; msg_info("") << " info message with conversion" << 1.5 << "\n" ; msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; msg_error("") << " error message with conversion" << 1.5 << "\n" ; EXPECT_TRUE( h->numMessages() == 3) ; } TEST(LoggingTest, withoutDevMode) { MessageDispatcher::clearHandlers() ; MyMessageHandler *h=new MyMessageHandler() ; MessageDispatcher::addHandler(h) ; msg_info("") << " info message with conversion" << 1.5 << "\n" ; msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; msg_error("") << " error message with conversion" << 1.5 << "\n" ; nmsg_info("") << " null info message with conversion" << 1.5 << "\n" ; nmsg_warning("") << " null warning message with conversion "<< 1.5 << "\n" ; nmsg_error("") << " null error message with conversion" << 1.5 << "\n" ; EXPECT_TRUE( h->numMessages() == 3 ) ; } //TEST(LoggingTest, speedTest) //{ // MessageDispatcher::clearHandlers() ; // MyMessageHandler *h=new MyMessageHandler() ; // MessageDispatcher::addHandler(h) ; // for(unsigned int i=0;i<10000;i++){ // msg_info("") << " info message with conversion" << 1.5 << "\n" ; // msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; // msg_error("") << " error message with conversion" << 1.5 << "\n" ; // } //} TEST(LoggingTest, BaseObject) { MessageDispatcher::clearHandlers() ; MyMessageHandler *h=new MyMessageHandler() ; MessageDispatcher::addHandler(h) ; MyComponent c; EXPECT_TRUE( h->numMessages() == 4 ) ; c.serr<<"regular external serr"<<c.sendl; EXPECT_TRUE( h->lastMessage().fileInfo().line == 0 ); EXPECT_TRUE( !strcmp( h->lastMessage().fileInfo().filename, sofa::helper::logging::s_unknownFile ) ); c.sout<<"regular external sout"<<c.sendl; EXPECT_TRUE( h->lastMessage().fileInfo().line == 0 ); EXPECT_TRUE( !strcmp( h->lastMessage().fileInfo().filename, sofa::helper::logging::s_unknownFile ) ); c.serr<<SOFA_FILE_INFO<<"external serr with fileinfo"<<c.sendl; EXPECT_TRUE( h->lastMessage().fileInfo().line == __LINE__-1 ); EXPECT_TRUE( !strcmp( h->lastMessage().fileInfo().filename, __FILE__ ) ); c.sout<<SOFA_FILE_INFO<<"external sout with fileinfo"<<c.sendl; EXPECT_TRUE( h->lastMessage().fileInfo().line == __LINE__-1 ); EXPECT_TRUE( !strcmp( h->lastMessage().fileInfo().filename, __FILE__ ) ); EXPECT_TRUE( h->numMessages() == 8 ) ; } #undef MESSAGING_H #define WITH_SOFA_DEVTOOLS #undef dmsg_info #undef dmsg_error #undef dmsg_warning #undef dmsg_fatal #include <sofa/helper/logging/Messaging.h> TEST(LoggingTest, withDevMode) { MessageDispatcher::clearHandlers() ; MyMessageHandler *h=new MyMessageHandler() ; MessageDispatcher::addHandler(h) ; msg_info("") << " info message with conversion" << 1.5 << "\n" ; msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; msg_error("") << " error message with conversion" << 1.5 << "\n" ; nmsg_info("") << " null info message with conversion" << 1.5 << "\n" ; nmsg_warning("") << " null warning message with conversion "<< 1.5 << "\n" ; nmsg_error("") << " null error message with conversion" << 1.5 << "\n" ; dmsg_info("") << " debug info message with conversion" << 1.5 << "\n" ; dmsg_warning("") << " debug warning message with conversion "<< 1.5 << "\n" ; dmsg_error("") << " debug error message with conversion" << 1.5 << "\n" ; EXPECT_TRUE( h->numMessages() == 6 ) ; } <commit_msg>[logger] try to see clearer with the crashing example<commit_after>#include <gtest/gtest.h> #include <exception> #include <algorithm> #include <iostream> using std::endl ; #include <vector> using std::vector ; #include <sofa/helper/logging/Messaging.h> using sofa::helper::logging::MessageDispatcher ; #include <sofa/helper/logging/MessageHandler.h> using sofa::helper::logging::MessageHandler ; #include <sofa/helper/logging/Message.h> using sofa::helper::logging::Message ; #include <sofa/core/objectmodel/BaseObject.h> #include <sofa/core/ObjectFactory.h> class MyMessageHandler : public MessageHandler { vector<Message> m_messages ; public: virtual void process(Message& m){ m_messages.push_back(m); // if( !m.sender().empty() ) // std::cerr<<m<<std::endl; } int numMessages(){ return m_messages.size() ; } const vector<Message>& messages() const { return m_messages; } const Message& lastMessage() const { return m_messages.back(); } } ; class MyComponent : public sofa::core::objectmodel::BaseObject { public: SOFA_CLASS( MyComponent, sofa::core::objectmodel::BaseObject ); MyComponent() { f_printLog.setValue(true); // to print sout serr<<"regular serr"<<sendl; sout<<"regular sout"<<sendl; serr<<SOFA_FILE_INFO<<"serr with fileinfo"<<sendl; sout<<SOFA_FILE_INFO<<"sout with fileinfo"<<sendl; } }; SOFA_DECL_CLASS(MyComponent) int MyComponentClass = sofa::core::RegisterObject("MyComponent") .add< MyComponent >(); TEST(LoggingTest, noHandler) { MessageDispatcher::clearHandlers() ; msg_info("") << " info message with conversion" << 1.5 << "\n" ; msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; msg_error("") << " error message with conversion" << 1.5 << "\n" ; } TEST(LoggingTest, oneHandler) { MessageDispatcher::clearHandlers() ; MyMessageHandler h; // add is expected to return the handler ID. Here is it the o'th EXPECT_TRUE(MessageDispatcher::addHandler(&h) == 0 ) ; msg_info("") << " info message with conversion" << 1.5 << "\n" ; msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; msg_error("") << " error message with conversion" << 1.5 << "\n" ; EXPECT_TRUE( h.numMessages() == 3 ) ; } TEST(LoggingTest, duplicatedHandler) { MessageDispatcher::clearHandlers() ; MyMessageHandler h; // First add is expected to return the handler ID. EXPECT_TRUE(MessageDispatcher::addHandler(&h) == 0) ; // Second is supposed to fail to add and thus return -1. EXPECT_TRUE(MessageDispatcher::addHandler(&h) == -1) ; msg_info("") << " info message with conversion" << 1.5 << "\n" ; msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; msg_error("") << " error message with conversion" << 1.5 << "\n" ; EXPECT_TRUE( h.numMessages() == 3) ; } TEST(LoggingTest, withoutDevMode) { MessageDispatcher::clearHandlers() ; MyMessageHandler h; MessageDispatcher::addHandler(&h) ; msg_info("") << " info message with conversion" << 1.5 << "\n" ; msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; msg_error("") << " error message with conversion" << 1.5 << "\n" ; nmsg_info("") << " null info message with conversion" << 1.5 << "\n" ; nmsg_warning("") << " null warning message with conversion "<< 1.5 << "\n" ; nmsg_error("") << " null error message with conversion" << 1.5 << "\n" ; EXPECT_TRUE( h.numMessages() == 3 ) ; } //TEST(LoggingTest, speedTest) //{ // MessageDispatcher::clearHandlers() ; // MyMessageHandler h; // MessageDispatcher::addHandler(&h) ; // for(unsigned int i=0;i<10000;i++){ // msg_info("") << " info message with conversion" << 1.5 << "\n" ; // msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; // msg_error("") << " error message with conversion" << 1.5 << "\n" ; // } //} TEST(LoggingTest, BaseObject) { MessageDispatcher::clearHandlers() ; MyMessageHandler h; MessageDispatcher::addHandler(&h) ; MyComponent c; EXPECT_EQ( h.numMessages(), 4 ) ; c.serr<<"regular external serr"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, 0 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, sofa::helper::logging::s_unknownFile ) ); c.sout<<"regular external sout"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, 0 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, sofa::helper::logging::s_unknownFile ) ); c.serr<<SOFA_FILE_INFO<<"external serr with fileinfo"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, __LINE__-1 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, __FILE__ ) ); c.sout<<SOFA_FILE_INFO<<"external sout with fileinfo"<<c.sendl; EXPECT_EQ( h.lastMessage().fileInfo().line, __LINE__-1 ); EXPECT_TRUE( !strcmp( h.lastMessage().fileInfo().filename, __FILE__ ) ); EXPECT_EQ( h.numMessages(), 8 ) ; } #undef MESSAGING_H #define WITH_SOFA_DEVTOOLS #undef dmsg_info #undef dmsg_error #undef dmsg_warning #undef dmsg_fatal #include <sofa/helper/logging/Messaging.h> TEST(LoggingTest, withDevMode) { MessageDispatcher::clearHandlers() ; MyMessageHandler h; MessageDispatcher::addHandler(&h) ; msg_info("") << " info message with conversion" << 1.5 << "\n" ; msg_warning("") << " warning message with conversion "<< 1.5 << "\n" ; msg_error("") << " error message with conversion" << 1.5 << "\n" ; nmsg_info("") << " null info message with conversion" << 1.5 << "\n" ; nmsg_warning("") << " null warning message with conversion "<< 1.5 << "\n" ; nmsg_error("") << " null error message with conversion" << 1.5 << "\n" ; dmsg_info("") << " debug info message with conversion" << 1.5 << "\n" ; dmsg_warning("") << " debug warning message with conversion "<< 1.5 << "\n" ; dmsg_error("") << " debug error message with conversion" << 1.5 << "\n" ; EXPECT_TRUE( h.numMessages() == 6 ) ; } <|endoftext|>
<commit_before>/* * author: Max Kellermann <mk@cm4all.com> */ #ifndef BENG_PROXY_FD_TYPE_HXX #define BENG_PROXY_FD_TYPE_HXX enum FdType { /** * No file descriptor available. Special value that is only * supported by few libraries. */ FD_NONE = 00, FD_FILE = 01, FD_PIPE = 02, FD_SOCKET = 04, FD_TCP = 010, /** a character device, such as /dev/zero or /dev/null */ FD_CHARDEV = 020, }; enum { FD_ANY = (FD_FILE | FD_PIPE | FD_SOCKET | FD_TCP), FD_ANY_SOCKET = (FD_SOCKET | FD_TCP), }; typedef unsigned FdTypeMask; #endif <commit_msg>FdType: convert enum to constexpr<commit_after>/* * author: Max Kellermann <mk@cm4all.com> */ #ifndef BENG_PROXY_FD_TYPE_HXX #define BENG_PROXY_FD_TYPE_HXX enum FdType { /** * No file descriptor available. Special value that is only * supported by few libraries. */ FD_NONE = 00, FD_FILE = 01, FD_PIPE = 02, FD_SOCKET = 04, FD_TCP = 010, /** a character device, such as /dev/zero or /dev/null */ FD_CHARDEV = 020, }; typedef unsigned FdTypeMask; static constexpr FdTypeMask FD_ANY_SOCKET = FD_SOCKET | FD_TCP; static constexpr FdTypeMask FD_ANY = FD_FILE | FD_PIPE | FD_ANY_SOCKET; #endif <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <iostream> // TODO Remove #include <cmake.h> #include <Context.h> #include <Eval.h> #include <E9.h> #include <Variant.h> #include <Dates.h> #include <Filter.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// // Const iterator that can be derefenced into a Task by domSource. static Task dummy; static Task& contextTask = dummy; //////////////////////////////////////////////////////////////////////////////// static bool domSource (const std::string& identifier, Variant& value) { std::string stringValue = context.dom.get (identifier, contextTask); if (stringValue != identifier) { value = Variant (stringValue); return true; } return false; } //////////////////////////////////////////////////////////////////////////////// Filter::Filter () : _startCount (0) , _endCount (0) { } //////////////////////////////////////////////////////////////////////////////// Filter::~Filter () { } //////////////////////////////////////////////////////////////////////////////// // Take an input set of tasks and filter into a subset. void Filter::subset (const std::vector <Task>& input, std::vector <Task>& output) { context.timer_filter.start (); A3 filt = context.a3.extract_filter (); filt.dump ("extract_filter"); if (context.config.getBoolean ("debug")) { Tree* t = context.a3t.tree (); if (t) context.debug (t->dump ()); } std::string filterExpr = context.a3t.getFilterExpression (); context.debug ("\033[1;37;42mFILTER\033[0m " + filterExpr); if (filterExpr.length ()) { E9 e9 (filt); Eval eval; eval.addSource (namedDates); eval.addSource (domSource); // Debug output from Eval during compilation is useful. During evaluation // it is mostly noise. eval.debug (context.config.getBoolean ("debug")); eval.compileExpression (filterExpr); eval.debug (false); std::vector <Task>::const_iterator task; for (task = input.begin (); task != input.end (); ++task) { // TODO Obsolete. bool oldFilter = e9.evalFilter (*task); if (oldFilter) output.push_back (*task); // Set up context for any DOM references. contextTask = *task; Variant var; eval.evaluateCompiledExpression (var); // TODO Switch to this: /* if (var.get_bool ()) output.push_back (*task); */ // TODO Obsolete filter comparison. if (context.config.getBoolean ("debug")) if (oldFilter != var.get_bool ()) std::cout << "# filter mismatch ID " << task->id << " UUID " << task->get ("uuid") << "\n"; } } else output = input; context.timer_filter.stop (); } //////////////////////////////////////////////////////////////////////////////// // Take the set of all tasks and filter into a subset. void Filter::subset (std::vector <Task>& output) { context.timer_filter.start (); A3 filt = context.a3.extract_filter (); filt.dump ("extract_filter"); if (context.config.getBoolean ("debug")) { Tree* t = context.a3t.tree (); if (t) context.debug (t->dump ()); } std::string filterExpr = context.a3t.getFilterExpression (); context.debug ("\033[1;37;42mFILTER\033[0m " + filterExpr); if (filterExpr.length ()) { context.timer_filter.stop (); const std::vector <Task>& pending = context.tdb2.pending.get_tasks (); context.timer_filter.start (); E9 e (filt); Eval eval; eval.addSource (namedDates); eval.addSource (domSource); // Debug output from Eval during compilation is useful. During evaluation // it is mostly noise. eval.debug (context.config.getBoolean ("debug")); eval.compileExpression (filterExpr); eval.debug (false); output.clear (); std::vector <Task>::const_iterator task; for (task = pending.begin (); task != pending.end (); ++task) { // TODO Obsolete. bool oldFilter = e.evalFilter (*task); if (oldFilter) output.push_back (*task); // Set up context for any DOM references. contextTask = *task; Variant var; eval.evaluateCompiledExpression (var); // TODO Obsolete filter comparison. if (context.config.getBoolean ("debug")) if (oldFilter != var.get_bool ()) std::cout << "# filter mismatch ID " << task->id << " UUID " << task->get ("uuid") << "\n"; } if (! pendingOnly ()) { context.timer_filter.stop (); const std::vector <Task>& completed = context.tdb2.completed.get_tasks (); // TODO Optional context.timer_filter.start (); for (task = completed.begin (); task != completed.end (); ++task) { // TODO Obsolete. bool oldFilter = e.evalFilter (*task); if (oldFilter) output.push_back (*task); // Set up context for any DOM references. contextTask = *task; Variant var; eval.evaluateCompiledExpression (var); // TODO Obsolete filter comparison. if (oldFilter != var.get_bool ()) std::cout << "# filter mismatch ID " << task->id << " UUID " << task->get ("uuid") << "\n"; } } } else { safety (); context.timer_filter.stop (); const std::vector <Task>& pending = context.tdb2.pending.get_tasks (); const std::vector <Task>& completed = context.tdb2.completed.get_tasks (); context.timer_filter.start (); std::vector <Task>::const_iterator task; for (task = pending.begin (); task != pending.end (); ++task) output.push_back (*task); for (task = completed.begin (); task != completed.end (); ++task) output.push_back (*task); } context.timer_filter.stop (); } //////////////////////////////////////////////////////////////////////////////// // If the filter contains the restriction "status:pending", as the first filter // term, then completed.data does not need to be loaded. bool Filter::pendingOnly () { Tree* tree = context.a3t.tree (); // If the filter starts with "status:pending", the completed.data does not // need to be accessed.. if (tree->_branches.size () > 0 && tree->_branches[0]->attribute ("name") == "status" && tree->_branches[0]->attribute ("value") == "pending") { context.debug ("Filter::pendingOnly - skipping completed.data (status:pending first)"); return true; } // Shortcut: If the filter contains no 'or' or 'xor' operators, IDs and no UUIDs. int countId = 0; int countUUID = 0; int countOr = 0; int countXor = 0; std::vector <Tree*>::iterator i; for (i = tree->_branches.begin (); i != tree->_branches.end (); ++i) { if ((*i)->hasTag ("OP")) { if ((*i)->attribute ("canonical") == "or") ++countOr; if ((*i)->attribute ("canonical") == "xor") ++countXor; } else if ((*i)->hasTag ("ID")) ++countId; else if ((*i)->hasTag ("UUID")) ++countUUID; } if (countOr == 0 && countXor == 0 && countUUID == 0 && countId > 0) { context.debug ("Filter::pendingOnly - skipping completed.data (IDs, no OR, no XOR, no UUID)"); return true; } return false; } //////////////////////////////////////////////////////////////////////////////// // Disaster avoidance mechanism. void Filter::safety () { /* if (! _read_only) { A3 write_filter = context.a3.extract_filter (); if (!write_filter.size ()) // Potential disaster. { // If user is willing to be asked, this can be avoided. if (context.config.getBoolean ("confirmation") && confirm (STRING_TASK_SAFETY_VALVE)) return; // No. throw std::string (STRING_TASK_SAFETY_FAIL); } } */ } //////////////////////////////////////////////////////////////////////////////// <commit_msg>Filter<commit_after>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <iostream> // TODO Remove #include <cmake.h> #include <Context.h> #include <Eval.h> #include <E9.h> #include <Variant.h> #include <Dates.h> #include <Filter.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// // Const iterator that can be derefenced into a Task by domSource. static Task dummy; static Task& contextTask = dummy; //////////////////////////////////////////////////////////////////////////////// static bool domSource (const std::string& identifier, Variant& value) { std::string stringValue = context.dom.get (identifier, contextTask); if (stringValue != identifier) { value = Variant (stringValue); return true; } return false; } //////////////////////////////////////////////////////////////////////////////// Filter::Filter () : _startCount (0) , _endCount (0) { } //////////////////////////////////////////////////////////////////////////////// Filter::~Filter () { } //////////////////////////////////////////////////////////////////////////////// // Take an input set of tasks and filter into a subset. void Filter::subset (const std::vector <Task>& input, std::vector <Task>& output) { context.timer_filter.start (); A3 filt = context.a3.extract_filter (); filt.dump ("extract_filter"); if (context.config.getBoolean ("debug")) { Tree* t = context.a3t.tree (); if (t) context.debug (t->dump ()); } std::string filterExpr = context.a3t.getFilterExpression (); context.debug ("\033[1;37;42mFILTER\033[0m " + filterExpr); if (filterExpr.length ()) { E9 e9 (filt); Eval eval; eval.addSource (namedDates); eval.addSource (domSource); // Debug output from Eval during compilation is useful. During evaluation // it is mostly noise. eval.debug (context.config.getBoolean ("debug")); eval.compileExpression (filterExpr); eval.debug (false); std::vector <Task>::const_iterator task; for (task = input.begin (); task != input.end (); ++task) { // TODO Obsolete. bool oldFilter = e9.evalFilter (*task); if (oldFilter) output.push_back (*task); // Set up context for any DOM references. contextTask = *task; Variant var; eval.evaluateCompiledExpression (var); // TODO Switch to this: /* if (var.get_bool ()) output.push_back (*task); */ // TODO Obsolete filter comparison. if (context.config.getBoolean ("debug")) if (oldFilter != var.get_bool ()) std::cout << "# filter mismatch ID " << task->id << " UUID " << task->get ("uuid") << "\n"; } } else output = input; context.timer_filter.stop (); } //////////////////////////////////////////////////////////////////////////////// // Take the set of all tasks and filter into a subset. void Filter::subset (std::vector <Task>& output) { context.timer_filter.start (); A3 filt = context.a3.extract_filter (); filt.dump ("extract_filter"); if (context.config.getBoolean ("debug")) { Tree* t = context.a3t.tree (); if (t) context.debug (t->dump ()); } std::string filterExpr = context.a3t.getFilterExpression (); context.debug ("\033[1;37;42mFILTER\033[0m " + filterExpr); if (filterExpr.length ()) { context.timer_filter.stop (); const std::vector <Task>& pending = context.tdb2.pending.get_tasks (); context.timer_filter.start (); E9 e (filt); Eval eval; eval.addSource (namedDates); eval.addSource (domSource); // Debug output from Eval during compilation is useful. During evaluation // it is mostly noise. eval.debug (context.config.getBoolean ("debug")); eval.compileExpression (filterExpr); eval.debug (false); output.clear (); std::vector <Task>::const_iterator task; for (task = pending.begin (); task != pending.end (); ++task) { // TODO Obsolete. bool oldFilter = e.evalFilter (*task); if (oldFilter) output.push_back (*task); // Set up context for any DOM references. contextTask = *task; Variant var; eval.evaluateCompiledExpression (var); // TODO Switch to this: /* if (var.get_bool ()) output.push_back (*task); */ // TODO Obsolete filter comparison. if (context.config.getBoolean ("debug")) if (oldFilter != var.get_bool ()) std::cout << "# filter mismatch ID " << task->id << " UUID " << task->get ("uuid") << "\n"; } if (! pendingOnly ()) { context.timer_filter.stop (); const std::vector <Task>& completed = context.tdb2.completed.get_tasks (); // TODO Optional context.timer_filter.start (); for (task = completed.begin (); task != completed.end (); ++task) { // TODO Obsolete. bool oldFilter = e.evalFilter (*task); if (oldFilter) output.push_back (*task); // Set up context for any DOM references. contextTask = *task; Variant var; eval.evaluateCompiledExpression (var); // TODO Switch to this: /* if (var.get_bool ()) output.push_back (*task); */ // TODO Obsolete filter comparison. if (oldFilter != var.get_bool ()) std::cout << "# filter mismatch ID " << task->id << " UUID " << task->get ("uuid") << "\n"; } } } else { safety (); context.timer_filter.stop (); const std::vector <Task>& pending = context.tdb2.pending.get_tasks (); const std::vector <Task>& completed = context.tdb2.completed.get_tasks (); context.timer_filter.start (); std::vector <Task>::const_iterator task; for (task = pending.begin (); task != pending.end (); ++task) output.push_back (*task); for (task = completed.begin (); task != completed.end (); ++task) output.push_back (*task); } context.timer_filter.stop (); } //////////////////////////////////////////////////////////////////////////////// // If the filter contains the restriction "status:pending", as the first filter // term, then completed.data does not need to be loaded. bool Filter::pendingOnly () { Tree* tree = context.a3t.tree (); // If the filter starts with "status:pending", the completed.data does not // need to be accessed.. if (tree->_branches.size () > 0 && tree->_branches[0]->attribute ("name") == "status" && tree->_branches[0]->attribute ("value") == "pending") { context.debug ("Filter::pendingOnly - skipping completed.data (status:pending first)"); return true; } // Shortcut: If the filter contains no 'or' or 'xor' operators, IDs and no UUIDs. int countId = 0; int countUUID = 0; int countOr = 0; int countXor = 0; std::vector <Tree*>::iterator i; for (i = tree->_branches.begin (); i != tree->_branches.end (); ++i) { if ((*i)->hasTag ("OP")) { if ((*i)->attribute ("canonical") == "or") ++countOr; if ((*i)->attribute ("canonical") == "xor") ++countXor; } else if ((*i)->hasTag ("ID")) ++countId; else if ((*i)->hasTag ("UUID")) ++countUUID; } if (countOr == 0 && countXor == 0 && countUUID == 0 && countId > 0) { context.debug ("Filter::pendingOnly - skipping completed.data (IDs, no OR, no XOR, no UUID)"); return true; } return false; } //////////////////////////////////////////////////////////////////////////////// // Disaster avoidance mechanism. void Filter::safety () { /* if (! _read_only) { A3 write_filter = context.a3.extract_filter (); if (!write_filter.size ()) // Potential disaster. { // If user is willing to be asked, this can be avoided. if (context.config.getBoolean ("confirmation") && confirm (STRING_TASK_SAFETY_VALVE)) return; // No. throw std::string (STRING_TASK_SAFETY_FAIL); } } */ } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>/* * Copyright 2010, * François Bleibel, * Olivier Stasse, * * CNRS/AIST * * This file is part of sot-core. * sot-core 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 3 of * the License, or (at your option) any later version. * sot-core 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 sot-core. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <sot-core/debug.h> #include <jrl/mal/boost.hh> #ifndef WIN32 #include <unistd.h> #endif using namespace std; namespace ml = maal::boost; #include <dynamic-graph/factory.h> #include <dynamic-graph/entity.h> #include <sot-core/feature-abstract.h> #include <dynamic-graph/plugin-loader.h> #include <dynamic-graph/interpreter.h> #include <sot-core/mailbox-vector.h> #include <sstream> using namespace dynamicgraph; using namespace sot; #ifdef HAVE_LIBBOOST_THREAD #include <boost/thread.hpp> sot::MailboxVector mailbox("mail"); void f( void ) { ml::Vector vect(25); ml::Vector vect2(25); for( int i=0;;++i ) { std::cout << " iter " << i << std::endl; for( int j=0;j<25;++j ) vect(j) = j+i*10; mailbox.post( vect ); maal::boost::Vector V = mailbox.getObject( vect2, 1 ); std::cout << vect2 << std::endl; std::cout << " getClassName " << mailbox.getClassName() << std::endl; std::cout << " getName " << mailbox.getName() << std::endl; std::cout << " hasBeenUpdated " << mailbox.hasBeenUpdated() << std::endl; std::cout << std::endl; } } int main( int argc,char** argv ) { boost::thread th( f ); #ifdef WIN32 Sleep( 100 ); #else usleep( 1000*100 ); #endif return 0; } #else int main() { cout << "This test cannot be run without LIBBOOST_THREAD" << endl; return 0; } #endif <commit_msg>Remove HAVE_LIBBOOST_THREAD<commit_after>/* * Copyright 2010, * François Bleibel, * Olivier Stasse, * * CNRS/AIST * * This file is part of sot-core. * sot-core 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 3 of * the License, or (at your option) any later version. * sot-core 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 sot-core. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <sot-core/debug.h> #include <jrl/mal/boost.hh> #ifndef WIN32 #include <unistd.h> #endif using namespace std; namespace ml = maal::boost; #include <dynamic-graph/factory.h> #include <dynamic-graph/entity.h> #include <sot-core/feature-abstract.h> #include <dynamic-graph/plugin-loader.h> #include <dynamic-graph/interpreter.h> #include <sot-core/mailbox-vector.h> #include <sstream> using namespace dynamicgraph; using namespace sot; #include <boost/thread.hpp> sot::MailboxVector mailbox("mail"); void f( void ) { ml::Vector vect(25); ml::Vector vect2(25); for( int i=0;;++i ) { std::cout << " iter " << i << std::endl; for( int j=0;j<25;++j ) vect(j) = j+i*10; mailbox.post( vect ); maal::boost::Vector V = mailbox.getObject( vect2, 1 ); std::cout << vect2 << std::endl; std::cout << " getClassName " << mailbox.getClassName() << std::endl; std::cout << " getName " << mailbox.getName() << std::endl; std::cout << " hasBeenUpdated " << mailbox.hasBeenUpdated() << std::endl; std::cout << std::endl; } } int main( int argc,char** argv ) { boost::thread th( f ); #ifdef WIN32 Sleep( 100 ); #else usleep( 1000*100 ); #endif return 0; } <|endoftext|>
<commit_before>// @(#)root/base:$Name: $:$Id: TFolder.cxx,v 1.27 2007/01/23 09:45:08 brun Exp $ // Author: Rene Brun 02/09/2000 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //______________________________________________________________________________ // // A TFolder object is a collection of objects and folders. // Folders have a name and a title and are identified in the folder hierarchy // by a "Unix-like" naming mechanism. The root of all folders is //root. // New folders can be dynamically added or removed to/from a folder. // The folder hierarchy can be visualized via the TBrowser. // // The Root folders hierarchy can be seen as a whiteboard where objects // are posted. Other classes/tasks can access these objects by specifying // only a string pathname. This whiteboard facility greatly improves the // modularity of an application, minimizing the class relationship problem // that penalizes large applications. // // Pointers are efficient to communicate between classes. // However, one has interest to minimize direct coupling between classes // in the form of direct pointers. One better uses the naming and search // service provided by the Root folders hierarchy. This makes the classes // loosely coupled and also greatly facilitates I/O operations. // In a client/server environment, this mechanism facilitates the access // to any kind of object in //root stores running on different processes. // // A TFolder is created by invoking the TFolder constructor. It is placed // inside an existing folder via the TFolder::AddFolder method. // One can search for a folder or an object in a folder using the FindObject // method. FindObject analyzes the string passed as its argument and searches // in the hierarchy until it finds an object or folder matching the name. // // When a folder is deleted, its reference from the parent folder and // possible other folders is deleted. // // If a folder has been declared the owner of its objects/folders via // TFolder::SetOwner, then the contained objects are deleted when the // folder is deleted. By default, a folder does not own its contained objects. // NOTE that folder ownership can be set // - via TFolder::SetOwner // - or via TCollection::SetOwner on the collection specified to TFolder::AddFolder // // Standard Root objects are automatically added to the folder hierarchy. // For example, the following folders exist: // //root/Files with the list of currently connected Root files // //root/Classes with the list of active classes // //root/Geometries with active geometries // //root/Canvases with the list of active canvases // //root/Styles with the list of graphics styles // //root/Colors with the list of active colors // // For example, if a file "myFile.root" is added to the list of files, one can // retrieve a pointer to the corresponding TFile object with a statement like: // TFile *myFile = (TFile*)gROOT->FindObject("//root/Files/myFile.root"); // The above statement can be abbreviated to: // TFile *myFile = (TFile*)gROOT->FindObject("/Files/myFile.root"); // or even to: // TFile *myFile = (TFile*)gROOT->FindObjectAny("myFile.root"); // In this last case, the TROOT::FindObjectAny function will scan the folder hierarchy // starting at //root and will return the first object named "myFile.root". // // Because a string-based search mechanism is expensive, it is recommended // to save the pointer to the object as a class member or local variable // if this pointer is used frequently or inside loops. // //Begin_Html /* <img src="gif/folder.gif"> */ //End_Html #include "Riostream.h" #include "Strlen.h" #include "TFolder.h" #include "TBrowser.h" #include "TROOT.h" #include "TClass.h" #include "TError.h" #include "TRegexp.h" #include "TVirtualIO.h" static const char *gFolderD[64]; static Int_t gFolderLevel = -1; static char gFolderPath[512]; ClassImp(TFolder) //______________________________________________________________________________ TFolder::TFolder() : TNamed() { // default constructor used by the Input functions // // This constructor should not be called by a user directly. // The normal way to create a folder is by calling TFolder::AddFolder fFolders = 0; fIsOwner = kFALSE; } //______________________________________________________________________________ TFolder::TFolder(const char *name, const char *title) : TNamed(name,title) { // create a normal folder. // use Add or AddFolder to add objects or folders to this folder fFolders = new TList(); fIsOwner = kFALSE; } //______________________________________________________________________________ TFolder::TFolder(const TFolder &folder) : TNamed(folder) { // Copy constructor. ((TFolder&)folder).Copy(*this); } //______________________________________________________________________________ TFolder::~TFolder() { // folder destructor. Remove all objects from its lists and delete // all its sub folders TCollection::StartGarbageCollection(); if (fFolders) { fFolders->Clear(); SafeDelete(fFolders); } TCollection::EmptyGarbageCollection(); if (gDebug) cerr << "TFolder dtor called for "<< GetName() << endl; } //______________________________________________________________________________ void TFolder::Add(TObject *obj) { // Add object to this folder. obj must be a TObject or a TFolder if (obj == 0 || fFolders == 0) return; obj->SetBit(kMustCleanup); fFolders->Add(obj); } //______________________________________________________________________________ TFolder *TFolder::AddFolder(const char *name, const char *title, TCollection *collection) { // Create a new folder and add it to the list of folders of this folder // return a pointer to the created folder // Note that a folder can be added to several folders // // if (collection is non NULL, the pointer fFolders is set to the existing // collection, otherwise a default collection (Tlist) is created // Note that the folder name cannot contain slashes. if (strchr(name,'/')) { ::Error("TFolder::TFolder","folder name cannot contain a slash", name); return 0; } if (strlen(GetName()) == 0) { ::Error("TFolder::TFolder","folder name cannot be \"\""); return 0; } TFolder *folder = new TFolder(); folder->SetName(name); folder->SetTitle(title); if (!fFolders) fFolders = new TList(); //only true when gROOT creates its 1st folder fFolders->Add(folder); if (collection) folder->fFolders = collection; else folder->fFolders = new TList(); return folder; } //______________________________________________________________________________ void TFolder::Browse(TBrowser *b) { // Browse this folder if (fFolders) fFolders->Browse(b); } //______________________________________________________________________________ void TFolder::Clear(Option_t *option) { // Delete all objects from a folder list if (fFolders) fFolders->Clear(option); } //______________________________________________________________________________ const char *TFolder::FindFullPathName(const char *name) const { // return the full pathname corresponding to subpath name // The returned path will be re-used by the next call to GetPath(). TObject *obj = FindObject(name); if (obj || !fFolders) { gFolderLevel++; gFolderD[gFolderLevel] = GetName(); gFolderPath[0] = '/'; gFolderPath[1] = 0; for (Int_t l=0;l<=gFolderLevel;l++) { strcat(gFolderPath,"/"); strcat(gFolderPath,gFolderD[l]); } strcat(gFolderPath,"/"); strcat(gFolderPath,name); gFolderLevel = -1; return gFolderPath; } if (name[0] == '/') return 0; TIter next(fFolders); TFolder *folder; const char *found; gFolderLevel++; gFolderD[gFolderLevel] = GetName(); while ((obj=next())) { if (!obj->InheritsFrom(TFolder::Class())) continue; if (obj->InheritsFrom(TClass::Class())) continue; folder = (TFolder*)obj; found = folder->FindFullPathName(name); if (found) return found; } gFolderLevel--; return 0; } //______________________________________________________________________________ const char *TFolder::FindFullPathName(const TObject *) const { // return the full pathname corresponding to subpath name // The returned path will be re-used by the next call to GetPath(). Error("FindFullPathname","Not yet implemented"); return 0; } //______________________________________________________________________________ TObject *TFolder::FindObject(const TObject *) const { // find object in an folder Error("FindObject","Not yet implemented"); return 0; } //______________________________________________________________________________ TObject *TFolder::FindObject(const char *name) const { // search object identified by name in the tree of folders inside // this folder. // name may be of the forms: // A, specify a full pathname starting at the top ROOT folder // //root/xxx/yyy/name // // B, specify a pathname starting with a single slash. //root is assumed // /xxx/yyy/name // // C, Specify a pathname relative to this folder // xxx/yyy/name // name if (!fFolders) return 0; if (name == 0) return 0; if (name[0] == '/') { if (name[1] == '/') { if (!strstr(name,"//root/")) return 0; return gROOT->GetRootFolder()->FindObject(name+7); } else { return gROOT->GetRootFolder()->FindObject(name+1); } } char cname[1024]; strcpy(cname,name); TObject *obj; char *slash = strchr(cname,'/'); if (slash) { *slash = 0; obj = fFolders->FindObject(cname); if (!obj) return 0; return obj->FindObject(slash+1); } else { return fFolders->FindObject(name); } } //______________________________________________________________________________ TObject *TFolder::FindObjectAny(const char *name) const { // return a pointer to the first object with name starting at this folder TObject *obj = FindObject(name); if (obj || !fFolders) return obj; // if (!obj->InheritsFrom(TFolder::Class())) continue; if (name[0] == '/') return 0; TIter next(fFolders); TFolder *folder; TObject *found; if (gFolderLevel >= 0) gFolderD[gFolderLevel] = GetName(); while ((obj=next())) { if (!obj->InheritsFrom(TFolder::Class())) continue; if (obj->IsA() == TClass::Class()) continue; folder = (TFolder*)obj; found = folder->FindObjectAny(name); if (found) return found; } return 0; } //______________________________________________________________________________ Bool_t TFolder::IsOwner() const { // folder ownership has been set via // - TFolder::SetOwner // - TCollection::SetOwner on the collection specified to TFolder::AddFolder if (!fFolders) return kFALSE; return fFolders->IsOwner(); } //______________________________________________________________________________ void TFolder::ls(Option_t *option) const { // List folder contents // if option contains "dump", the Dump function of contained objects is called // if option contains "print", the Print function of contained objects is called // By default the ls function of contained objects is called. // Indentation is used to identify the folder tree // // The <regexp> will be used to match the name of the objects. // if (!fFolders) return; TROOT::IndentLevel(); cout <<ClassName()<<"*\t\t"<<GetName()<<"\t"<<GetTitle()<<endl; TROOT::IncreaseDirLevel(); TString opta = option; TString opt = opta.Strip(TString::kBoth); opt.ToLower(); TString reg = opt; Bool_t dump = opt.Contains("dump"); Bool_t print = opt.Contains("print"); TRegexp re(reg, kTRUE); TObject *obj; TIter nextobj(fFolders); while ((obj = (TObject *) nextobj())) { TString s = obj->GetName(); if (s.Index(re) == kNPOS) continue; if (dump) obj->Dump(); else if(print) obj->Print(option); else obj->ls(option); } TROOT::DecreaseDirLevel(); } //______________________________________________________________________________ Int_t TFolder::Occurence(const TObject *object) const { // Return occurence number of object in the list of objects of this folder. // The function returns the number of objects with the same name as object // found in the list of objects in this folder before object itself. // If only one object is found, return 0; Int_t n = 0; if (!fFolders) return 0; TIter next(fFolders); TObject *obj; while ((obj=next())) { if (strcmp(obj->GetName(),object->GetName()) == 0) n++; } if (n <=1) return n-1; n = 0; next.Reset(); while ((obj=next())) { if (strcmp(obj->GetName(),object->GetName()) == 0) n++; if (obj == object) return n; } return 0; } //______________________________________________________________________________ void TFolder::RecursiveRemove(TObject *obj) { // Recursively remove object from a Folder if (fFolders) fFolders->RecursiveRemove(obj); } //______________________________________________________________________________ void TFolder::Remove(TObject *obj) { // Remove object from this folder. obj must be a TObject or a TFolder if (obj == 0 || fFolders == 0) return; fFolders->Remove(obj); } //______________________________________________________________________________ void TFolder::SaveAs(const char *filename, Option_t *option) const { // Save all objects in this folder in filename // Each object in this folder will have a key in the file where the name of // the key will be the name of the object. TVirtualIO::GetIO()->SaveObjectAs(this,filename,option); } //______________________________________________________________________________ void TFolder::SetOwner(Bool_t owner) { // Set ownership // If the folder is declared owner, when the folder is deleted, all // the objects added via TFolder::Add are deleted via TObject::Delete, // otherwise TObject::Clear is called. // // NOTE that folder ownership can be set // - via TFolder::SetOwner // - or via TCollection::SetOwner on the collection specified to TFolder::AddFolder if (!fFolders) fFolders = new TList(); fFolders->SetOwner(owner); } <commit_msg>-Replace the calls to TVirtualIO by new calls in TBuffer or TDirectory<commit_after>// @(#)root/base:$Name: $:$Id: TFolder.cxx,v 1.28 2007/01/25 11:47:53 brun Exp $ // Author: Rene Brun 02/09/2000 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //______________________________________________________________________________ // // A TFolder object is a collection of objects and folders. // Folders have a name and a title and are identified in the folder hierarchy // by a "Unix-like" naming mechanism. The root of all folders is //root. // New folders can be dynamically added or removed to/from a folder. // The folder hierarchy can be visualized via the TBrowser. // // The Root folders hierarchy can be seen as a whiteboard where objects // are posted. Other classes/tasks can access these objects by specifying // only a string pathname. This whiteboard facility greatly improves the // modularity of an application, minimizing the class relationship problem // that penalizes large applications. // // Pointers are efficient to communicate between classes. // However, one has interest to minimize direct coupling between classes // in the form of direct pointers. One better uses the naming and search // service provided by the Root folders hierarchy. This makes the classes // loosely coupled and also greatly facilitates I/O operations. // In a client/server environment, this mechanism facilitates the access // to any kind of object in //root stores running on different processes. // // A TFolder is created by invoking the TFolder constructor. It is placed // inside an existing folder via the TFolder::AddFolder method. // One can search for a folder or an object in a folder using the FindObject // method. FindObject analyzes the string passed as its argument and searches // in the hierarchy until it finds an object or folder matching the name. // // When a folder is deleted, its reference from the parent folder and // possible other folders is deleted. // // If a folder has been declared the owner of its objects/folders via // TFolder::SetOwner, then the contained objects are deleted when the // folder is deleted. By default, a folder does not own its contained objects. // NOTE that folder ownership can be set // - via TFolder::SetOwner // - or via TCollection::SetOwner on the collection specified to TFolder::AddFolder // // Standard Root objects are automatically added to the folder hierarchy. // For example, the following folders exist: // //root/Files with the list of currently connected Root files // //root/Classes with the list of active classes // //root/Geometries with active geometries // //root/Canvases with the list of active canvases // //root/Styles with the list of graphics styles // //root/Colors with the list of active colors // // For example, if a file "myFile.root" is added to the list of files, one can // retrieve a pointer to the corresponding TFile object with a statement like: // TFile *myFile = (TFile*)gROOT->FindObject("//root/Files/myFile.root"); // The above statement can be abbreviated to: // TFile *myFile = (TFile*)gROOT->FindObject("/Files/myFile.root"); // or even to: // TFile *myFile = (TFile*)gROOT->FindObjectAny("myFile.root"); // In this last case, the TROOT::FindObjectAny function will scan the folder hierarchy // starting at //root and will return the first object named "myFile.root". // // Because a string-based search mechanism is expensive, it is recommended // to save the pointer to the object as a class member or local variable // if this pointer is used frequently or inside loops. // //Begin_Html /* <img src="gif/folder.gif"> */ //End_Html #include "Riostream.h" #include "Strlen.h" #include "TFolder.h" #include "TBrowser.h" #include "TROOT.h" #include "TClass.h" #include "TError.h" #include "TRegexp.h" static const char *gFolderD[64]; static Int_t gFolderLevel = -1; static char gFolderPath[512]; ClassImp(TFolder) //______________________________________________________________________________ TFolder::TFolder() : TNamed() { // default constructor used by the Input functions // // This constructor should not be called by a user directly. // The normal way to create a folder is by calling TFolder::AddFolder fFolders = 0; fIsOwner = kFALSE; } //______________________________________________________________________________ TFolder::TFolder(const char *name, const char *title) : TNamed(name,title) { // create a normal folder. // use Add or AddFolder to add objects or folders to this folder fFolders = new TList(); fIsOwner = kFALSE; } //______________________________________________________________________________ TFolder::TFolder(const TFolder &folder) : TNamed(folder) { // Copy constructor. ((TFolder&)folder).Copy(*this); } //______________________________________________________________________________ TFolder::~TFolder() { // folder destructor. Remove all objects from its lists and delete // all its sub folders TCollection::StartGarbageCollection(); if (fFolders) { fFolders->Clear(); SafeDelete(fFolders); } TCollection::EmptyGarbageCollection(); if (gDebug) cerr << "TFolder dtor called for "<< GetName() << endl; } //______________________________________________________________________________ void TFolder::Add(TObject *obj) { // Add object to this folder. obj must be a TObject or a TFolder if (obj == 0 || fFolders == 0) return; obj->SetBit(kMustCleanup); fFolders->Add(obj); } //______________________________________________________________________________ TFolder *TFolder::AddFolder(const char *name, const char *title, TCollection *collection) { // Create a new folder and add it to the list of folders of this folder // return a pointer to the created folder // Note that a folder can be added to several folders // // if (collection is non NULL, the pointer fFolders is set to the existing // collection, otherwise a default collection (Tlist) is created // Note that the folder name cannot contain slashes. if (strchr(name,'/')) { ::Error("TFolder::TFolder","folder name cannot contain a slash", name); return 0; } if (strlen(GetName()) == 0) { ::Error("TFolder::TFolder","folder name cannot be \"\""); return 0; } TFolder *folder = new TFolder(); folder->SetName(name); folder->SetTitle(title); if (!fFolders) fFolders = new TList(); //only true when gROOT creates its 1st folder fFolders->Add(folder); if (collection) folder->fFolders = collection; else folder->fFolders = new TList(); return folder; } //______________________________________________________________________________ void TFolder::Browse(TBrowser *b) { // Browse this folder if (fFolders) fFolders->Browse(b); } //______________________________________________________________________________ void TFolder::Clear(Option_t *option) { // Delete all objects from a folder list if (fFolders) fFolders->Clear(option); } //______________________________________________________________________________ const char *TFolder::FindFullPathName(const char *name) const { // return the full pathname corresponding to subpath name // The returned path will be re-used by the next call to GetPath(). TObject *obj = FindObject(name); if (obj || !fFolders) { gFolderLevel++; gFolderD[gFolderLevel] = GetName(); gFolderPath[0] = '/'; gFolderPath[1] = 0; for (Int_t l=0;l<=gFolderLevel;l++) { strcat(gFolderPath,"/"); strcat(gFolderPath,gFolderD[l]); } strcat(gFolderPath,"/"); strcat(gFolderPath,name); gFolderLevel = -1; return gFolderPath; } if (name[0] == '/') return 0; TIter next(fFolders); TFolder *folder; const char *found; gFolderLevel++; gFolderD[gFolderLevel] = GetName(); while ((obj=next())) { if (!obj->InheritsFrom(TFolder::Class())) continue; if (obj->InheritsFrom(TClass::Class())) continue; folder = (TFolder*)obj; found = folder->FindFullPathName(name); if (found) return found; } gFolderLevel--; return 0; } //______________________________________________________________________________ const char *TFolder::FindFullPathName(const TObject *) const { // return the full pathname corresponding to subpath name // The returned path will be re-used by the next call to GetPath(). Error("FindFullPathname","Not yet implemented"); return 0; } //______________________________________________________________________________ TObject *TFolder::FindObject(const TObject *) const { // find object in an folder Error("FindObject","Not yet implemented"); return 0; } //______________________________________________________________________________ TObject *TFolder::FindObject(const char *name) const { // search object identified by name in the tree of folders inside // this folder. // name may be of the forms: // A, specify a full pathname starting at the top ROOT folder // //root/xxx/yyy/name // // B, specify a pathname starting with a single slash. //root is assumed // /xxx/yyy/name // // C, Specify a pathname relative to this folder // xxx/yyy/name // name if (!fFolders) return 0; if (name == 0) return 0; if (name[0] == '/') { if (name[1] == '/') { if (!strstr(name,"//root/")) return 0; return gROOT->GetRootFolder()->FindObject(name+7); } else { return gROOT->GetRootFolder()->FindObject(name+1); } } char cname[1024]; strcpy(cname,name); TObject *obj; char *slash = strchr(cname,'/'); if (slash) { *slash = 0; obj = fFolders->FindObject(cname); if (!obj) return 0; return obj->FindObject(slash+1); } else { return fFolders->FindObject(name); } } //______________________________________________________________________________ TObject *TFolder::FindObjectAny(const char *name) const { // return a pointer to the first object with name starting at this folder TObject *obj = FindObject(name); if (obj || !fFolders) return obj; // if (!obj->InheritsFrom(TFolder::Class())) continue; if (name[0] == '/') return 0; TIter next(fFolders); TFolder *folder; TObject *found; if (gFolderLevel >= 0) gFolderD[gFolderLevel] = GetName(); while ((obj=next())) { if (!obj->InheritsFrom(TFolder::Class())) continue; if (obj->IsA() == TClass::Class()) continue; folder = (TFolder*)obj; found = folder->FindObjectAny(name); if (found) return found; } return 0; } //______________________________________________________________________________ Bool_t TFolder::IsOwner() const { // folder ownership has been set via // - TFolder::SetOwner // - TCollection::SetOwner on the collection specified to TFolder::AddFolder if (!fFolders) return kFALSE; return fFolders->IsOwner(); } //______________________________________________________________________________ void TFolder::ls(Option_t *option) const { // List folder contents // if option contains "dump", the Dump function of contained objects is called // if option contains "print", the Print function of contained objects is called // By default the ls function of contained objects is called. // Indentation is used to identify the folder tree // // The <regexp> will be used to match the name of the objects. // if (!fFolders) return; TROOT::IndentLevel(); cout <<ClassName()<<"*\t\t"<<GetName()<<"\t"<<GetTitle()<<endl; TROOT::IncreaseDirLevel(); TString opta = option; TString opt = opta.Strip(TString::kBoth); opt.ToLower(); TString reg = opt; Bool_t dump = opt.Contains("dump"); Bool_t print = opt.Contains("print"); TRegexp re(reg, kTRUE); TObject *obj; TIter nextobj(fFolders); while ((obj = (TObject *) nextobj())) { TString s = obj->GetName(); if (s.Index(re) == kNPOS) continue; if (dump) obj->Dump(); else if(print) obj->Print(option); else obj->ls(option); } TROOT::DecreaseDirLevel(); } //______________________________________________________________________________ Int_t TFolder::Occurence(const TObject *object) const { // Return occurence number of object in the list of objects of this folder. // The function returns the number of objects with the same name as object // found in the list of objects in this folder before object itself. // If only one object is found, return 0; Int_t n = 0; if (!fFolders) return 0; TIter next(fFolders); TObject *obj; while ((obj=next())) { if (strcmp(obj->GetName(),object->GetName()) == 0) n++; } if (n <=1) return n-1; n = 0; next.Reset(); while ((obj=next())) { if (strcmp(obj->GetName(),object->GetName()) == 0) n++; if (obj == object) return n; } return 0; } //______________________________________________________________________________ void TFolder::RecursiveRemove(TObject *obj) { // Recursively remove object from a Folder if (fFolders) fFolders->RecursiveRemove(obj); } //______________________________________________________________________________ void TFolder::Remove(TObject *obj) { // Remove object from this folder. obj must be a TObject or a TFolder if (obj == 0 || fFolders == 0) return; fFolders->Remove(obj); } //______________________________________________________________________________ void TFolder::SaveAs(const char *filename, Option_t *option) const { // Save all objects in this folder in filename // Each object in this folder will have a key in the file where the name of // the key will be the name of the object. if (gDirectory) gDirectory->SaveObjectAs(this,filename,option); } //______________________________________________________________________________ void TFolder::SetOwner(Bool_t owner) { // Set ownership // If the folder is declared owner, when the folder is deleted, all // the objects added via TFolder::Add are deleted via TObject::Delete, // otherwise TObject::Clear is called. // // NOTE that folder ownership can be set // - via TFolder::SetOwner // - or via TCollection::SetOwner on the collection specified to TFolder::AddFolder if (!fFolders) fFolders = new TList(); fFolders->SetOwner(owner); } <|endoftext|>
<commit_before>//===- llvm/unittest/Support/ParallelTest.cpp -----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Parallel.h unit tests. /// //===----------------------------------------------------------------------===// #include "llvm/Support/Parallel.h" #include "gtest/gtest.h" #include <array> #include <random> uint32_t array[1024 * 1024]; using namespace llvm; TEST(Parallel, sort) { std::mt19937 randEngine; std::uniform_int_distribution<uint32_t> dist; for (auto &i : array) i = dist(randEngine); sort(parallel::par, std::begin(array), std::end(array)); ASSERT_TRUE(std::is_sorted(std::begin(array), std::end(array))); } TEST(Parallel, parallel_for) { // We need to test the case with a TaskSize > 1. We are white-box testing // here. The TaskSize is calculated as (End - Begin) / 1024 at the time of // writing. uint32_t range[2050]; std::fill(range, range + 2050, 1); for_each_n(parallel::par, 0, 2049, [&range](size_t I) { ++range[I]; }); uint32_t expected[2049]; std::fill(expected, expected + 2049, 2); ASSERT_TRUE(std::equal(range, range + 2049, expected)); // Check that we don't write past the end of the requested range. ASSERT_EQ(range[2049], 1u); } <commit_msg>SupportTests: Suppress ParallelTests on mingw for now. Investigating.<commit_after>//===- llvm/unittest/Support/ParallelTest.cpp -----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Parallel.h unit tests. /// //===----------------------------------------------------------------------===// #include "llvm/Support/Parallel.h" #include "gtest/gtest.h" #include <array> #include <random> uint32_t array[1024 * 1024]; using namespace llvm; // Tests below are hanging up on mingw. Investigating. #if !defined(__MINGW32__) TEST(Parallel, sort) { std::mt19937 randEngine; std::uniform_int_distribution<uint32_t> dist; for (auto &i : array) i = dist(randEngine); sort(parallel::par, std::begin(array), std::end(array)); ASSERT_TRUE(std::is_sorted(std::begin(array), std::end(array))); } TEST(Parallel, parallel_for) { // We need to test the case with a TaskSize > 1. We are white-box testing // here. The TaskSize is calculated as (End - Begin) / 1024 at the time of // writing. uint32_t range[2050]; std::fill(range, range + 2050, 1); for_each_n(parallel::par, 0, 2049, [&range](size_t I) { ++range[I]; }); uint32_t expected[2049]; std::fill(expected, expected + 2049, 2); ASSERT_TRUE(std::equal(range, range + 2049, expected)); // Check that we don't write past the end of the requested range. ASSERT_EQ(range[2049], 1u); } #endif <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // 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/. #define EIGEN_TEST_NO_LONGDOUBLE #define EIGEN_TEST_NO_COMPLEX #define EIGEN_TEST_FUNC cxx11_float16 #define EIGEN_DEFAULT_DENSE_INDEX_TYPE int #define EIGEN_USE_GPU #include "main.h" #include <Eigen/src/Core/arch/CUDA/Half.h> using Eigen::half; void test_conversion() { // Conversion from float. VERIFY_IS_EQUAL(Eigen::half(1.0f).x, 0x3c00); VERIFY_IS_EQUAL(Eigen::half(0.5f).x, 0x3800); VERIFY_IS_EQUAL(Eigen::half(0.33333f).x, 0x3555); VERIFY_IS_EQUAL(Eigen::half(0.0f).x, 0x0000); VERIFY_IS_EQUAL(Eigen::half(-0.0f).x, 0x8000); VERIFY_IS_EQUAL(Eigen::half(65504.0f).x, 0x7bff); VERIFY_IS_EQUAL(Eigen::half(65536.0f).x, 0x7c00); // Becomes infinity. // Denormals. VERIFY_IS_EQUAL(Eigen::half(-5.96046e-08f).x, 0x8001); VERIFY_IS_EQUAL(Eigen::half(5.96046e-08f).x, 0x0001); VERIFY_IS_EQUAL(Eigen::half(1.19209e-07f).x, 0x0002); // Verify round-to-nearest-even behavior. float val1 = float(Eigen::half(half_impl::__half{0x3c00})); float val2 = float(Eigen::half(half_impl::__half{0x3c01})); float val3 = float(Eigen::half(half_impl::__half{0x3c02})); VERIFY_IS_EQUAL(Eigen::half(0.5 * (val1 + val2)).x, 0x3c00); VERIFY_IS_EQUAL(Eigen::half(0.5 * (val2 + val3)).x, 0x3c02); // Conversion from int. VERIFY_IS_EQUAL(Eigen::half(-1).x, 0xbc00); VERIFY_IS_EQUAL(Eigen::half(0).x, 0x0000); VERIFY_IS_EQUAL(Eigen::half(1).x, 0x3c00); VERIFY_IS_EQUAL(Eigen::half(2).x, 0x4000); VERIFY_IS_EQUAL(Eigen::half(3).x, 0x4200); // Conversion from bool. VERIFY_IS_EQUAL(Eigen::half(false).x, 0x0000); VERIFY_IS_EQUAL(Eigen::half(true).x, 0x3c00); // Conversion to float. VERIFY_IS_EQUAL(float(Eigen::half(half_impl::__half{0x0000})), 0.0f); VERIFY_IS_EQUAL(float(Eigen::half(half_impl::__half{0x3c00})), 1.0f); // Denormals. VERIFY_IS_APPROX(float(Eigen::half(half_impl::__half{0x8001})), -5.96046e-08f); VERIFY_IS_APPROX(float(Eigen::half(half_impl::__half{0x0001})), 5.96046e-08f); VERIFY_IS_APPROX(float(Eigen::half(half_impl::__half{0x0002})), 1.19209e-07f); // NaNs and infinities. VERIFY(!isinf(float(Eigen::half(65504.0f)))); // Largest finite number. VERIFY(!isnan(float(Eigen::half(0.0f)))); VERIFY(isinf(float(Eigen::half(half_impl::__half{0xfc00})))); VERIFY(isnan(float(Eigen::half(half_impl::__half{0xfc01})))); VERIFY(isinf(float(Eigen::half(half_impl::__half{0x7c00})))); VERIFY(isnan(float(Eigen::half(half_impl::__half{0x7c01})))); VERIFY(isnan(float(Eigen::half(0.0 / 0.0)))); VERIFY(isinf(float(Eigen::half(1.0 / 0.0)))); VERIFY(isinf(float(Eigen::half(-1.0 / 0.0)))); // Exactly same checks as above, just directly on the half representation. VERIFY(!numext::isinf(Eigen::half(half_impl::__half{0x7bff}))); VERIFY(!numext::isnan(Eigen::half(half_impl::__half{0x0000}))); VERIFY(numext::isinf(Eigen::half(half_impl::__half{0xfc00}))); VERIFY(numext::isnan(Eigen::half(half_impl::__half{0xfc01}))); VERIFY(numext::isinf(Eigen::half(half_impl::__half{0x7c00}))); VERIFY(numext::isnan(Eigen::half(half_impl::__half{0x7c01}))); VERIFY(numext::isnan(Eigen::half(0.0 / 0.0))); VERIFY(numext::isinf(Eigen::half(1.0 / 0.0))); VERIFY(numext::isinf(Eigen::half(-1.0 / 0.0))); } void test_arithmetic() { VERIFY_IS_EQUAL(float(Eigen::half(2) + Eigen::half(2)), 4); VERIFY_IS_EQUAL(float(Eigen::half(2) + Eigen::half(-2)), 0); VERIFY_IS_APPROX(float(Eigen::half(0.33333f) + Eigen::half(0.66667f)), 1.0f); VERIFY_IS_EQUAL(float(Eigen::half(2.0f) * Eigen::half(-5.5f)), -11.0f); VERIFY_IS_APPROX(float(Eigen::half(1.0f) / Eigen::half(3.0f)), 0.33333f); VERIFY_IS_EQUAL(float(-Eigen::half(4096.0f)), -4096.0f); VERIFY_IS_EQUAL(float(-Eigen::half(-4096.0f)), 4096.0f); } void test_comparison() { VERIFY(Eigen::half(1.0f) > Eigen::half(0.5f)); VERIFY(Eigen::half(0.5f) < Eigen::half(1.0f)); VERIFY(!(Eigen::half(1.0f) < Eigen::half(0.5f))); VERIFY(!(Eigen::half(0.5f) > Eigen::half(1.0f))); VERIFY(!(Eigen::half(4.0f) > Eigen::half(4.0f))); VERIFY(!(Eigen::half(4.0f) < Eigen::half(4.0f))); VERIFY(!(Eigen::half(0.0f) < Eigen::half(-0.0f))); VERIFY(!(Eigen::half(-0.0f) < Eigen::half(0.0f))); VERIFY(!(Eigen::half(0.0f) > Eigen::half(-0.0f))); VERIFY(!(Eigen::half(-0.0f) > Eigen::half(0.0f))); VERIFY(Eigen::half(0.2f) > Eigen::half(-1.0f)); VERIFY(Eigen::half(-1.0f) < Eigen::half(0.2f)); VERIFY(Eigen::half(-16.0f) < Eigen::half(-15.0f)); VERIFY(Eigen::half(1.0f) == Eigen::half(1.0f)); VERIFY(Eigen::half(1.0f) != Eigen::half(2.0f)); // Comparisons with NaNs and infinities. VERIFY(!(Eigen::half(0.0 / 0.0) == Eigen::half(0.0 / 0.0))); VERIFY(!(Eigen::half(0.0 / 0.0) != Eigen::half(0.0 / 0.0))); VERIFY(!(Eigen::half(1.0) == Eigen::half(0.0 / 0.0))); VERIFY(!(Eigen::half(1.0) < Eigen::half(0.0 / 0.0))); VERIFY(!(Eigen::half(1.0) > Eigen::half(0.0 / 0.0))); VERIFY(!(Eigen::half(1.0) != Eigen::half(0.0 / 0.0))); VERIFY(Eigen::half(1.0) < Eigen::half(1.0 / 0.0)); VERIFY(Eigen::half(1.0) > Eigen::half(-1.0 / 0.0)); } void test_basic_functions() { VERIFY_IS_EQUAL(float(numext::abs(Eigen::half(3.5f))), 3.5f); VERIFY_IS_EQUAL(float(numext::abs(Eigen::half(-3.5f))), 3.5f); VERIFY_IS_EQUAL(float(numext::floor(Eigen::half(3.5f))), 3.0f); VERIFY_IS_EQUAL(float(numext::floor(Eigen::half(-3.5f))), -4.0f); VERIFY_IS_EQUAL(float(numext::ceil(Eigen::half(3.5f))), 4.0f); VERIFY_IS_EQUAL(float(numext::ceil(Eigen::half(-3.5f))), -3.0f); VERIFY_IS_APPROX(float(numext::sqrt(Eigen::half(0.0f))), 0.0f); VERIFY_IS_APPROX(float(numext::sqrt(Eigen::half(4.0f))), 2.0f); VERIFY_IS_APPROX(float(numext::pow(Eigen::half(0.0f), Eigen::half(1.0f))), 0.0f); VERIFY_IS_APPROX(float(numext::pow(Eigen::half(2.0f), Eigen::half(2.0f))), 4.0f); VERIFY_IS_EQUAL(float(numext::exp(Eigen::half(0.0f))), 1.0f); VERIFY_IS_APPROX(float(numext::exp(Eigen::half(EIGEN_PI))), float(20.0 + EIGEN_PI)); VERIFY_IS_EQUAL(float(numext::log(Eigen::half(1.0f))), 0.0f); VERIFY_IS_APPROX(float(numext::log(Eigen::half(10.0f))), 2.30273f); } void test_trigonometric_functions() { VERIFY_IS_APPROX(numext::cos(Eigen::half(0.0f)), Eigen::half(cosf(0.0f))); VERIFY_IS_APPROX(numext::cos(Eigen::half(EIGEN_PI)), Eigen::half(cosf(EIGEN_PI))); VERIFY_IS_APPROX_OR_LESS_THAN(numext::cos(Eigen::half(EIGEN_PI/2)), NumTraits<Eigen::half>::epsilon() * Eigen::half(5)); VERIFY_IS_APPROX_OR_LESS_THAN(numext::cos(Eigen::half(3*EIGEN_PI/2)), NumTraits<Eigen::half>::epsilon() * Eigen::half(5)); VERIFY_IS_APPROX(numext::cos(Eigen::half(3.5f)), Eigen::half(cosf(3.5f))); VERIFY_IS_APPROX(numext::sin(Eigen::half(0.0f)), Eigen::half(sinf(0.0f))); VERIFY_IS_APPROX_OR_LESS_THAN(numext::sin(Eigen::half(EIGEN_PI)), NumTraits<Eigen::half>::epsilon() * Eigen::half(10)); VERIFY_IS_APPROX(numext::sin(Eigen::half(EIGEN_PI/2)), Eigen::half(sinf(EIGEN_PI/2))); VERIFY_IS_APPROX(numext::sin(Eigen::half(3*EIGEN_PI/2)), Eigen::half(sinf(3*EIGEN_PI/2))); VERIFY_IS_APPROX(numext::sin(Eigen::half(3.5f)), Eigen::half(sinf(3.5f))); VERIFY_IS_APPROX(numext::tan(Eigen::half(0.0f)), Eigen::half(tanf(0.0f))); VERIFY_IS_APPROX_OR_LESS_THAN(numext::tan(Eigen::half(EIGEN_PI)), NumTraits<Eigen::half>::epsilon() * Eigen::half(10)); VERIFY_IS_APPROX(numext::tan(Eigen::half(3.5f)), Eigen::half(tanf(3.5f))); } void test_cxx11_float16() { CALL_SUBTEST(test_conversion()); CALL_SUBTEST(test_arithmetic()); CALL_SUBTEST(test_comparison()); CALL_SUBTEST(test_basic_functions()); CALL_SUBTEST(test_trigonometric_functions()); } <commit_msg>Cleaned up the new float16 test a bit<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // 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/. #define EIGEN_TEST_NO_LONGDOUBLE #define EIGEN_TEST_NO_COMPLEX #define EIGEN_TEST_FUNC cxx11_float16 #define EIGEN_DEFAULT_DENSE_INDEX_TYPE int #define EIGEN_USE_GPU // Make sure it's possible to forward declare Eigen::half //namespace Eigen { //struct half; //} #include "main.h" #include <Eigen/src/Core/arch/CUDA/Half.h> void test_conversion() { // Conversion from float. VERIFY_IS_EQUAL(Eigen::half(1.0f).x, 0x3c00); VERIFY_IS_EQUAL(Eigen::half(0.5f).x, 0x3800); VERIFY_IS_EQUAL(Eigen::half(0.33333f).x, 0x3555); VERIFY_IS_EQUAL(Eigen::half(0.0f).x, 0x0000); VERIFY_IS_EQUAL(Eigen::half(-0.0f).x, 0x8000); VERIFY_IS_EQUAL(Eigen::half(65504.0f).x, 0x7bff); VERIFY_IS_EQUAL(Eigen::half(65536.0f).x, 0x7c00); // Becomes infinity. // Denormals. VERIFY_IS_EQUAL(Eigen::half(-5.96046e-08f).x, 0x8001); VERIFY_IS_EQUAL(Eigen::half(5.96046e-08f).x, 0x0001); VERIFY_IS_EQUAL(Eigen::half(1.19209e-07f).x, 0x0002); // Verify round-to-nearest-even behavior. float val1 = float(Eigen::half(half_impl::__half{0x3c00})); float val2 = float(Eigen::half(half_impl::__half{0x3c01})); float val3 = float(Eigen::half(half_impl::__half{0x3c02})); VERIFY_IS_EQUAL(Eigen::half(0.5f * (val1 + val2)).x, 0x3c00); VERIFY_IS_EQUAL(Eigen::half(0.5f * (val2 + val3)).x, 0x3c02); // Conversion from int. VERIFY_IS_EQUAL(Eigen::half(-1).x, 0xbc00); VERIFY_IS_EQUAL(Eigen::half(0).x, 0x0000); VERIFY_IS_EQUAL(Eigen::half(1).x, 0x3c00); VERIFY_IS_EQUAL(Eigen::half(2).x, 0x4000); VERIFY_IS_EQUAL(Eigen::half(3).x, 0x4200); // Conversion from bool. VERIFY_IS_EQUAL(Eigen::half(false).x, 0x0000); VERIFY_IS_EQUAL(Eigen::half(true).x, 0x3c00); // Conversion to float. VERIFY_IS_EQUAL(float(Eigen::half(half_impl::__half{0x0000})), 0.0f); VERIFY_IS_EQUAL(float(Eigen::half(half_impl::__half{0x3c00})), 1.0f); // Denormals. VERIFY_IS_APPROX(float(Eigen::half(half_impl::__half{0x8001})), -5.96046e-08f); VERIFY_IS_APPROX(float(Eigen::half(half_impl::__half{0x0001})), 5.96046e-08f); VERIFY_IS_APPROX(float(Eigen::half(half_impl::__half{0x0002})), 1.19209e-07f); // NaNs and infinities. VERIFY(!(isinf)(float(Eigen::half(65504.0f)))); // Largest finite number. VERIFY(!(isnan)(float(Eigen::half(0.0f)))); VERIFY((isinf)(float(Eigen::half(half_impl::__half{0xfc00})))); VERIFY((isnan)(float(Eigen::half(half_impl::__half{0xfc01})))); VERIFY((isinf)(float(Eigen::half(half_impl::__half{0x7c00})))); VERIFY((isnan)(float(Eigen::half(half_impl::__half{0x7c01})))); VERIFY((isnan)(float(Eigen::half(0.0 / 0.0)))); VERIFY((isinf)(float(Eigen::half(1.0 / 0.0)))); VERIFY((isinf)(float(Eigen::half(-1.0 / 0.0)))); // Exactly same checks as above, just directly on the half representation. VERIFY(!(numext::isinf)(Eigen::half(half_impl::__half{0x7bff}))); VERIFY(!(numext::isnan)(Eigen::half(half_impl::__half{0x0000}))); VERIFY((numext::isinf)(Eigen::half(half_impl::__half{0xfc00}))); VERIFY((numext::isnan)(Eigen::half(half_impl::__half{0xfc01}))); VERIFY((numext::isinf)(Eigen::half(half_impl::__half{0x7c00}))); VERIFY((numext::isnan)(Eigen::half(half_impl::__half{0x7c01}))); VERIFY((numext::isnan)(Eigen::half(0.0 / 0.0))); VERIFY((numext::isinf)(Eigen::half(1.0 / 0.0))); VERIFY((numext::isinf)(Eigen::half(-1.0 / 0.0))); } void test_arithmetic() { VERIFY_IS_EQUAL(float(Eigen::half(2) + Eigen::half(2)), 4); VERIFY_IS_EQUAL(float(Eigen::half(2) + Eigen::half(-2)), 0); VERIFY_IS_APPROX(float(Eigen::half(0.33333f) + Eigen::half(0.66667f)), 1.0f); VERIFY_IS_EQUAL(float(Eigen::half(2.0f) * Eigen::half(-5.5f)), -11.0f); VERIFY_IS_APPROX(float(Eigen::half(1.0f) / Eigen::half(3.0f)), 0.33333f); VERIFY_IS_EQUAL(float(-Eigen::half(4096.0f)), -4096.0f); VERIFY_IS_EQUAL(float(-Eigen::half(-4096.0f)), 4096.0f); } void test_comparison() { VERIFY(Eigen::half(1.0f) > Eigen::half(0.5f)); VERIFY(Eigen::half(0.5f) < Eigen::half(1.0f)); VERIFY(!(Eigen::half(1.0f) < Eigen::half(0.5f))); VERIFY(!(Eigen::half(0.5f) > Eigen::half(1.0f))); VERIFY(!(Eigen::half(4.0f) > Eigen::half(4.0f))); VERIFY(!(Eigen::half(4.0f) < Eigen::half(4.0f))); VERIFY(!(Eigen::half(0.0f) < Eigen::half(-0.0f))); VERIFY(!(Eigen::half(-0.0f) < Eigen::half(0.0f))); VERIFY(!(Eigen::half(0.0f) > Eigen::half(-0.0f))); VERIFY(!(Eigen::half(-0.0f) > Eigen::half(0.0f))); VERIFY(Eigen::half(0.2f) > Eigen::half(-1.0f)); VERIFY(Eigen::half(-1.0f) < Eigen::half(0.2f)); VERIFY(Eigen::half(-16.0f) < Eigen::half(-15.0f)); VERIFY(Eigen::half(1.0f) == Eigen::half(1.0f)); VERIFY(Eigen::half(1.0f) != Eigen::half(2.0f)); // Comparisons with NaNs and infinities. VERIFY(!(Eigen::half(0.0 / 0.0) == Eigen::half(0.0 / 0.0))); VERIFY(!(Eigen::half(0.0 / 0.0) != Eigen::half(0.0 / 0.0))); VERIFY(!(Eigen::half(1.0) == Eigen::half(0.0 / 0.0))); VERIFY(!(Eigen::half(1.0) < Eigen::half(0.0 / 0.0))); VERIFY(!(Eigen::half(1.0) > Eigen::half(0.0 / 0.0))); VERIFY(!(Eigen::half(1.0) != Eigen::half(0.0 / 0.0))); VERIFY(Eigen::half(1.0) < Eigen::half(1.0 / 0.0)); VERIFY(Eigen::half(1.0) > Eigen::half(-1.0 / 0.0)); } void test_basic_functions() { VERIFY_IS_EQUAL(float(numext::abs(Eigen::half(3.5f))), 3.5f); VERIFY_IS_EQUAL(float(numext::abs(Eigen::half(-3.5f))), 3.5f); VERIFY_IS_EQUAL(float(numext::floor(Eigen::half(3.5f))), 3.0f); VERIFY_IS_EQUAL(float(numext::floor(Eigen::half(-3.5f))), -4.0f); VERIFY_IS_EQUAL(float(numext::ceil(Eigen::half(3.5f))), 4.0f); VERIFY_IS_EQUAL(float(numext::ceil(Eigen::half(-3.5f))), -3.0f); VERIFY_IS_APPROX(float(numext::sqrt(Eigen::half(0.0f))), 0.0f); VERIFY_IS_APPROX(float(numext::sqrt(Eigen::half(4.0f))), 2.0f); VERIFY_IS_APPROX(float(numext::pow(Eigen::half(0.0f), Eigen::half(1.0f))), 0.0f); VERIFY_IS_APPROX(float(numext::pow(Eigen::half(2.0f), Eigen::half(2.0f))), 4.0f); VERIFY_IS_EQUAL(float(numext::exp(Eigen::half(0.0f))), 1.0f); VERIFY_IS_APPROX(float(numext::exp(Eigen::half(EIGEN_PI))), float(20.0 + EIGEN_PI)); VERIFY_IS_EQUAL(float(numext::log(Eigen::half(1.0f))), 0.0f); VERIFY_IS_APPROX(float(numext::log(Eigen::half(10.0f))), 2.30273f); } void test_trigonometric_functions() { VERIFY_IS_APPROX(numext::cos(Eigen::half(0.0f)), Eigen::half(cosf(0.0f))); VERIFY_IS_APPROX(numext::cos(Eigen::half(EIGEN_PI)), Eigen::half(cosf(EIGEN_PI))); VERIFY_IS_APPROX_OR_LESS_THAN(numext::cos(Eigen::half(EIGEN_PI/2)), NumTraits<Eigen::half>::epsilon() * Eigen::half(5)); VERIFY_IS_APPROX_OR_LESS_THAN(numext::cos(Eigen::half(3*EIGEN_PI/2)), NumTraits<Eigen::half>::epsilon() * Eigen::half(5)); VERIFY_IS_APPROX(numext::cos(Eigen::half(3.5f)), Eigen::half(cosf(3.5f))); VERIFY_IS_APPROX(numext::sin(Eigen::half(0.0f)), Eigen::half(sinf(0.0f))); VERIFY_IS_APPROX_OR_LESS_THAN(numext::sin(Eigen::half(EIGEN_PI)), NumTraits<Eigen::half>::epsilon() * Eigen::half(10)); VERIFY_IS_APPROX(numext::sin(Eigen::half(EIGEN_PI/2)), Eigen::half(sinf(EIGEN_PI/2))); VERIFY_IS_APPROX(numext::sin(Eigen::half(3*EIGEN_PI/2)), Eigen::half(sinf(3*EIGEN_PI/2))); VERIFY_IS_APPROX(numext::sin(Eigen::half(3.5f)), Eigen::half(sinf(3.5f))); VERIFY_IS_APPROX(numext::tan(Eigen::half(0.0f)), Eigen::half(tanf(0.0f))); VERIFY_IS_APPROX_OR_LESS_THAN(numext::tan(Eigen::half(EIGEN_PI)), NumTraits<Eigen::half>::epsilon() * Eigen::half(10)); VERIFY_IS_APPROX(numext::tan(Eigen::half(3.5f)), Eigen::half(tanf(3.5f))); } void test_cxx11_float16() { CALL_SUBTEST(test_conversion()); CALL_SUBTEST(test_arithmetic()); CALL_SUBTEST(test_comparison()); CALL_SUBTEST(test_basic_functions()); CALL_SUBTEST(test_trigonometric_functions()); } <|endoftext|>
<commit_before>#ifndef KSPACE_CLASS_INCLUDED #define KSPACE_CLASS_INCLUDED #include <vector> #include <cmath> #include "Kokkos_Core.hpp" /** * * Class to compute the k-space part of an Ewald sum for * quadrupole, dipole and/or monopole systems * */ template <class T> class KSpace { public: /** * * Constructor for the class (base-version) * */ KSpace(){} /** * * Constructor for the class * * @param alpha Ewald sum splitting parameter * @param k_max floating point cut-off radius for the k-space * part */ KSpace( const T _alpha, const T _k_max ) { init_params(_alpha, _k_max); } /* * * Initialization and computation of internal parameters * * @param alpha Ewald sum splitting parameter * @param k_max floating point cut-off radius for the k-space * part */ void init_params( const T, const T ); /** * * Computation of the kspace part of the Ewald sum, fills the * private variables of the class which can be accessed by the * corresponding getters after the computation * * @param l system length (cubic system) * @param xyz particle positions (xyz(0), xyz(1), ...) * @param q particle charges(q,q,q,...) * @param d particle dipole moments(d(0,0),d(0,1), * d(1,0),d(1,1),d(2,0),d(2,1),...) * @param q particle quadrupole moments( q(0,0),...,q(0,8),q(1,0),...,q(1,8),...) */ void compute( const T, const std::vector<T>&, const std::vector<T>&, const std::vector<T>&, const std::vector<T>& ); private: T alpha; ///< splitting parameter of the Ewald sum T gamma; ///< transformed splitting parameter of the Ewald sum int k_sq_int; ///< square value of the k-space limit int k_max_int; ///< k-space image limit T pot_energy; ///< potential energy computed for the k-space part T virial; ///< virial computed for the k-space part Kokkos::View<T*[3]> f; ///< forces computed for the k-space part Kokkos::View<T*[3]> tqe; ///< torque computed for the k-space part bool is_monopole; ///< compute the monopole contributions bool is_dipole; ///< compute the dipole contributions bool is_quadrupole; ///< compute the quadrupole contributions Kokkos::View<T***> cos_fac; ///< cosine based exponential factors Kokkos::View<T***> sin_fac; ///< sine based exponential factors Kokkos::View<T*> ak; ///< AK coefficients /* * * Compute the exponential factors for each particle * * @param xyz std::vector of type T containing the positions of the * particles to be used in the computation of the exponential * factors * @param l system length */ void compute_exponentials(Kokkos::View<T*[3]>, const T); /* * * Computation of the AK coefficients for the matrix multiplications * * @param l system length */ void compute_ak(const T); }; /* * * Initialization and computation of internal parameters * * @param alpha Ewald sum splitting parameter * @param k_max floating point cut-off radius for the k-space * part */ template <class T> void KSpace<T>::init_params( const T _alpha, const T _k_max ) { alpha = _alpha; gamma = -0.25 / ( alpha * alpha ); k_max_int = (int)_k_max; k_sq_int = (int)std::floor(sqrt(_k_max)); } /* * * Computation of the AK coefficients for the matrix multiplications * (currently only implemented for host-space) * * @param l system size */ template <class T> void KSpace<T>::compute_ak( const T l ) { T expf = 0.0; // transformed length T rcl = 2.0 * M_PI / l; if (alpha > (T)1e-12) { expf = std::exp( gamma * rcl * rcl ); } ak = Kokkos::View<T*>( "AK coefficients", k_sq_int ); Kokkos::parallel_for(k_sq_int, KOKKOS_LAMBDA(const int k) { T rksq = (T)k * rcl * rcl; T eksq = std::pow(expf,(T)k); ak(k) = eksq / rksq; } ); } /* * * Computation of the exponential factors for the k-space part * (currently only implemented for host-space) * * @param xyz particles positons * @param l system size */ template <class T> void KSpace<T>::compute_exponentials( Kokkos::View<T*[3]> xyz, const T l ) { // get number of particles size_t N = xyz.size() / 3.0; // create Kokkos views of sufficient size to store the factors cos_fac = Kokkos::View<T***>( "cosine exponential factors", N, 2*(k_max_int)+1, 3 ); sin_fac = Kokkos::View<T***>( "sine exponential factors", N, 2*(k_max_int)+1, 3 ); // to deal with negative k-values int offset = k_max_int; // initialize the first factors (k == 0) Kokkos::parallel_for(N, KOKKOS_LAMBDA(const int n) { for (int d = 0; d < 3; ++d) { cos_fac(n,0+offset,d) = 1.0; sin_fac(n,0+offset,d) = 0.0; } } ); // transformed length T rcl = 2.0 * M_PI / l; // compute the exponential factors (k == 1 / k == -1) Kokkos::parallel_for(N, KOKKOS_LAMBDA(const int n) { for(int d = 0; d < 3; ++d) { cos_fac(n,1+offset,d) = std::cos(rcl * xyz(3*n,d)); sin_fac(n,1+offset,d) = std::sin(rcl * xyz(3*n,d)); cos_fac(n,-1+offset,d) = cos_fac(n,1+offset,d); sin_fac(n,-1+offset,d) = -sin_fac(n,1+offset,d); } } ); Kokkos::parallel_for(N, KOKKOS_LAMBDA(const int n) { for(int k = 2; k <= k_max_int; ++k) { for(int d = 0; d < 3; ++d) { cos_fac(n,k+offset,d) = cos_fac(n,k-1+offset,d) * cos_fac(n,1+offset,d) - sin_fac(n,k-1+offset,d) * sin_fac(n,1+offset,d); sin_fac(n,k+offset,d) = sin_fac(n,k-1+offset,d) * cos_fac(n,1+offset,d) - cos_fac(n,k-1+offset,d) * sin_fac(n,1+offset,d); cos_fac(n,-k+offset,d) = cos_fac(n,k+offset,d); sin_fac(n,-k+offset,d) = -sin_fac(n,k+offset,d); } } } ); } /** * * Computation of the kspace part of the Ewald sum, fills the * private variables of the class which can be accessed by the * corresponding getters after the computation * * @param _l system length (cubic system) * @param _xyz particle positions (xyz(0), xyz(1), ...) * @param _q particle charges(q,q,q,...) * @param _d particle dipole moments(d(0,0),d(0,1), * d(1,0),d(1,1),d(2,0),d(2,1),...) * @param _Q particle quadrupole moments( Q(0,0),...,Q(0,8),Q(1,0),...,Q(1,8),...) */ template <class T> void KSpace<T>::compute( const T _l, const std::vector<T>& _xyz, const std::vector<T>& _q, const std::vector<T>& _d, const std::vector<T>& _Q ) { // get number of particles size_t N = _xyz.size() / 3; // store C++ vectors to Kokkos Views Kokkos::View<T*[3]> xyz("positions",N); Kokkos::View<T*> q("charges",N); Kokkos::View<T*[3]> d("dipole moments",N); Kokkos::View<T*[3][3]> Q("quadrupole moments",N); Kokkos::parallel_for(N, KOKKOS_LAMBDA( const int n ) { q(n) = _q.at(n); for (int i = 0; i < 3; ++i) { xyz(n,i) = _xyz.at(3*n+i); d(n,i) = _d.at(3*n+i); for (int j = 0; j < 3; ++j) { Q(n,i,j) = _Q.at(9*n + 3*i + j); } } } ); // compute exponential factors compute_exponentials(xyz,_l); // compute AK coefficients compute_ak(_l); } #endif <commit_msg>added internal loops for force computation<commit_after>#ifndef KSPACE_CLASS_INCLUDED #define KSPACE_CLASS_INCLUDED #include <vector> #include <cmath> #include "Kokkos_Core.hpp" /** * * Class to compute the k-space part of an Ewald sum for * quadrupole, dipole and/or monopole systems * */ template <class T> class KSpace { public: /** * * Constructor for the class (base-version) * */ KSpace(){} /** * * Constructor for the class * * @param alpha Ewald sum splitting parameter * @param k_max floating point cut-off radius for the k-space * part */ KSpace( const T _alpha, const T _k_max ) { init_params(_alpha, _k_max); } /* * * Initialization and computation of internal parameters * * @param alpha Ewald sum splitting parameter * @param k_max floating point cut-off radius for the k-space * part */ void init_params( const T, const T ); /** * * Computation of the kspace part of the Ewald sum, fills the * private variables of the class which can be accessed by the * corresponding getters after the computation * * @param l system length (cubic system) * @param xyz particle positions (xyz(0), xyz(1), ...) * @param q particle charges(q,q,q,...) * @param d particle dipole moments(d(0,0),d(0,1), * d(1,0),d(1,1),d(2,0),d(2,1),...) * @param q particle quadrupole moments( q(0,0),...,q(0,8),q(1,0),...,q(1,8),...) */ void compute( const T, const std::vector<T>&, const std::vector<T>&, const std::vector<T>&, const std::vector<T>& ); private: T alpha; ///< splitting parameter of the Ewald sum T gamma; ///< transformed splitting parameter of the Ewald sum int k_sq_int; ///< square value of the k-space limit int k_max_int; ///< k-space image limit T pot_energy; ///< potential energy computed for the k-space part T virial; ///< virial computed for the k-space part Kokkos::View<T*[3]> f; ///< forces computed for the k-space part Kokkos::View<T*[3]> tqe; ///< torque computed for the k-space part bool is_monopole; ///< compute the monopole contributions bool is_dipole; ///< compute the dipole contributions bool is_quadrupole; ///< compute the quadrupole contributions Kokkos::View<T***> cos_fac; ///< cosine based exponential factors Kokkos::View<T***> sin_fac; ///< sine based exponential factors Kokkos::View<T*> ak; ///< AK coefficients /* * * Compute the exponential factors for each particle * * @param xyz std::vector of type T containing the positions of the * particles to be used in the computation of the exponential * factors * @param l system length */ void compute_exponentials(Kokkos::View<T*[3]>, const T); /* * * Computation of the AK coefficients for the matrix multiplications * * @param l system length */ void compute_ak(const T); }; /* * * Initialization and computation of internal parameters * * @param alpha Ewald sum splitting parameter * @param k_max floating point cut-off radius for the k-space * part */ template <class T> void KSpace<T>::init_params( const T _alpha, const T _k_max ) { alpha = _alpha; gamma = -0.25 / ( alpha * alpha ); k_sq_int = (int)_k_max; k_max_int = (int)std::floor(sqrt(_k_max)); } /* * * Computation of the AK coefficients for the matrix multiplications * (currently only implemented for host-space) * * @param l system size */ template <class T> void KSpace<T>::compute_ak( const T l ) { T expf = 0.0; // transformed length T rcl = 2.0 * M_PI / l; if (alpha > (T)1e-12) { expf = std::exp( gamma * rcl * rcl ); } ak = Kokkos::View<T*>( "AK coefficients", k_sq_int ); Kokkos::parallel_for(k_sq_int, KOKKOS_LAMBDA(const int k) { T rksq = (T)k * rcl * rcl; T eksq = std::pow(expf,(T)k); ak(k) = eksq / rksq; } ); } /* * * Computation of the exponential factors for the k-space part * (currently only implemented for host-space) * * @param xyz particles positons * @param l system size */ template <class T> void KSpace<T>::compute_exponentials( Kokkos::View<T*[3]> xyz, const T l ) { // get number of particles size_t N = xyz.size() / 3.0; // create Kokkos views of sufficient size to store the factors cos_fac = Kokkos::View<T***>( "cosine exponential factors", N, 2*(k_max_int)+1, 3 ); sin_fac = Kokkos::View<T***>( "sine exponential factors", N, 2*(k_max_int)+1, 3 ); // to deal with negative k-values int offset = k_max_int; // initialize the first factors (k == 0) Kokkos::parallel_for(N, KOKKOS_LAMBDA(const int n) { for (int d = 0; d < 3; ++d) { cos_fac(n,0+offset,d) = 1.0; sin_fac(n,0+offset,d) = 0.0; } } ); // transformed length T rcl = 2.0 * M_PI / l; // compute the exponential factors (k == 1 / k == -1) Kokkos::parallel_for(N, KOKKOS_LAMBDA(const int n) { for(int d = 0; d < 3; ++d) { cos_fac(n,1+offset,d) = std::cos(rcl * xyz(3*n,d)); sin_fac(n,1+offset,d) = std::sin(rcl * xyz(3*n,d)); cos_fac(n,-1+offset,d) = cos_fac(n,1+offset,d); sin_fac(n,-1+offset,d) = -sin_fac(n,1+offset,d); } } ); Kokkos::parallel_for(N, KOKKOS_LAMBDA(const int n) { for(int k = 2; k <= k_max_int; ++k) { for(int d = 0; d < 3; ++d) { cos_fac(n,k+offset,d) = cos_fac(n,k-1+offset,d) * cos_fac(n,1+offset,d) - sin_fac(n,k-1+offset,d) * sin_fac(n,1+offset,d); sin_fac(n,k+offset,d) = sin_fac(n,k-1+offset,d) * cos_fac(n,1+offset,d) - cos_fac(n,k-1+offset,d) * sin_fac(n,1+offset,d); cos_fac(n,-k+offset,d) = cos_fac(n,k+offset,d); sin_fac(n,-k+offset,d) = -sin_fac(n,k+offset,d); } } } ); } /** * * Computation of the kspace part of the Ewald sum, fills the * private variables of the class which can be accessed by the * corresponding getters after the computation * * @param _l system length (cubic system) * @param _xyz particle positions (xyz(0), xyz(1), ...) * @param _q particle charges(q,q,q,...) * @param _d particle dipole moments(d(0,0),d(0,1), * d(1,0),d(1,1),d(2,0),d(2,1),...) * @param _Q particle quadrupole moments( Q(0,0),...,Q(0,8),Q(1,0),...,Q(1,8),...) */ template <class T> void KSpace<T>::compute( const T _l, const std::vector<T>& _xyz, const std::vector<T>& _q, const std::vector<T>& _d, const std::vector<T>& _Q ) { // get number of particles size_t N = _xyz.size() / 3; // store C++ vectors to Kokkos Views Kokkos::View<T*[3]> xyz("positions",N); Kokkos::View<T*> q("charges",N); Kokkos::View<T*[3]> d("dipole moments",N); Kokkos::View<T*[3][3]> Q("quadrupole moments",N); Kokkos::parallel_for(N, KOKKOS_LAMBDA( const int n ) { q(n) = _q.at(n); for (int i = 0; i < 3; ++i) { xyz(n,i) = _xyz.at(3*n+i); d(n,i) = _d.at(3*n+i); for (int j = 0; j < 3; ++j) { Q(n,i,j) = _Q.at(9*n + 3*i + j); } } } ); // compute exponential factors compute_exponentials(xyz,_l); // compute AK coefficients compute_ak(_l); // transformed length T rcl = 2.0 * M_PI / _l; // loop over the k-images to compute the necessary // parameters (energy, virial, torque, forces) int miny = 0; int minz = 0; double rx, ry, rz; for (int ix = 0; ix <= k_max_int; ++ix) { rx = rcl * (T)ix; for (int iy = miny; iy <= k_max_int; ++iy) { ry = rcl * (T)iy; for (int iz = minz; iz <= k_max_int; ++iz) { rz = rcl * (T)iz; // -1 to conform to C++ style array indexing // opposed to original Fortran indexing int kk = ix * ix + iy * iy + iz * iz - 1; if (kk > k_sq_int) continue; // compute exp (ikr) and the corresponding scalar and vector // products for the different multipoles // compute_multipole_coeffs(ix, iy, iz); } } } } #endif <|endoftext|>
<commit_before> #include "generator.hpp" #include "type.hpp" #include "expr.hpp" #include "stmt.hpp" #include "decl.hpp" #include "evaluator.hpp" #include "llvm/IR/Type.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/Function.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Module.h" #include <iostream> // -------------------------------------------------------------------------- // // Mapping of types // // The type generator transforms a beaker type into // its correspondiong LLVM type. llvm::Type* Generator::get_type(Type const* t) { struct Fn { Generator& g; llvm::Type* operator()(Boolean_type const* t) const { return g.get_type(t); } llvm::Type* operator()(Integer_type const* t) const { return g.get_type(t); } llvm::Type* operator()(Function_type const* t) const { return g.get_type(t); } llvm::Type* operator()(Reference_type const* t) const { return g.get_type(t); } }; return apply(t, Fn{*this}); } // Return the 1 bit integer type. llvm::Type* Generator::get_type(Boolean_type const*) { return build.getInt1Ty(); } // Return the 32 bit integer type. llvm::Type* Generator::get_type(Integer_type const*) { return build.getInt32Ty(); } // Return a function type. llvm::Type* Generator::get_type(Function_type const* t) { std::vector<llvm::Type*> ts; ts.reserve(t->parameter_types().size()); for (Type const* t1 : t->parameter_types()) ts.push_back(get_type(t1)); llvm::Type* r = get_type(t->return_type()); return llvm::FunctionType::get(r, ts, false); } // Translate reference types into pointer types in the // generic address space. // // TODO: Actually do this? llvm::Type* Generator::get_type(Reference_type const* t) { llvm::Type* t1 = get_type(t->type()); return llvm::PointerType::getUnqual(t1); } // -------------------------------------------------------------------------- // // Code generation for expressions // // An expression is transformed into a sequence instructions whose // intermediate results are saved in registers. llvm::Value* Generator::gen(Expr const* e) { struct Fn { Generator& g; llvm::Value* operator()(Literal_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Id_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Add_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Sub_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Mul_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Div_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Rem_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Neg_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Pos_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Eq_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Ne_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Lt_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Gt_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Le_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Ge_expr const* e) const { return g.gen(e); } llvm::Value* operator()(And_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Or_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Not_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Call_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Value_conv const* e) const { return g.gen(e); } }; return apply(e, Fn{*this}); } // Return the value corresponding to a literal expression. llvm::Value* Generator::gen(Literal_expr const* e) { // TODO: Write better type queries. // // TODO: Write a better interface for values. Value v = evaluate(e); if (e->type() == get_boolean_type()) return build.getInt1(v.get_integer()); if (e->type() == get_integer_type()) return build.getInt32(v.get_integer()); else throw std::runtime_error("cannot generate function literal"); } // Returns the value associated with the declaration. // // TODO: Do we need to do anything different for function // identifiers or not? llvm::Value* Generator::gen(Id_expr const* e) { return stack.lookup(e->declaration())->second; } llvm::Value* Generator::gen(Add_expr const* e) { llvm::Value* l = gen(e->left()); llvm::Value* r = gen(e->right()); return build.CreateAdd(l, r); } llvm::Value* Generator::gen(Sub_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Mul_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Div_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Rem_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Neg_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Pos_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Eq_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Ne_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Lt_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Gt_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Le_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Ge_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(And_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Or_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Not_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Call_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Value_conv const* e) { llvm::Value* v = gen(e->source()); return build.CreateLoad(v); } // -------------------------------------------------------------------------- // // Code generation for statements // // The statement generator is responsible for // the generation of statements at block scope. void Generator::gen(Stmt const* s) { struct Fn { Generator& g; void operator()(Empty_stmt const* s) { g.gen(s); } void operator()(Block_stmt const* s) { g.gen(s); } void operator()(Assign_stmt const* s) { g.gen(s); } void operator()(Return_stmt const* s) { g.gen(s); } void operator()(If_then_stmt const* s) { g.gen(s); } void operator()(If_else_stmt const* s) { g.gen(s); } void operator()(While_stmt const* s) { g.gen(s); } void operator()(Break_stmt const* s) { g.gen(s); } void operator()(Continue_stmt const* s) { g.gen(s); } void operator()(Expression_stmt const* s) { g.gen(s); } void operator()(Declaration_stmt const* s) { g.gen(s); } }; apply(s, Fn{*this}); } void Generator::gen(Empty_stmt const* s) { throw std::runtime_error("not implemented"); } // Generate code for a sequence of statements. // Note that this does not correspond to a basic // block since we don't need any terminators // in the following program. // // { // { ; } // } // // We only need new blocks for specific control // flow concepts. void Generator::gen(Block_stmt const* s) { for (Stmt const* s1 : s->statements()) gen(s1); } void Generator::gen(Assign_stmt const* s) { llvm::Value* lhs = gen(s->object()); llvm::Value* rhs = gen(s->value()); build.CreateStore(rhs, lhs); } void Generator::gen(Return_stmt const* s) { llvm::Value* v = gen(s->value()); build.CreateRet(v); } void Generator::gen(If_then_stmt const* s) { throw std::runtime_error("not implemented"); } void Generator::gen(If_else_stmt const* s) { throw std::runtime_error("not implemented"); } void Generator::gen(While_stmt const* s) { throw std::runtime_error("not implemented"); } void Generator::gen(Break_stmt const* s) { throw std::runtime_error("not implemented"); } void Generator::gen(Continue_stmt const* s) { throw std::runtime_error("not implemented"); } void Generator::gen(Expression_stmt const* s) { gen(s->expression()); } void Generator::gen(Declaration_stmt const* s) { gen(s->declaration()); } // -------------------------------------------------------------------------- // // Code generation for declarations // // TODO: We can't generate all of the code for a module // in a single pass. We probably need to break this up // into a number of smaller declaration generators. For // example, generators that: // // - produce declarations // - produce global initializers // - produce global destructors // - other stuff // // In, it might not be worthwhile to have a number // of sub-generators that refer to the top-level // generator. void Generator::gen(Decl const* d) { struct Fn { Generator& g; void operator()(Variable_decl const* d) { return g.gen(d); } void operator()(Function_decl const* d) { return g.gen(d); } void operator()(Parameter_decl const* d) { return g.gen(d); } void operator()(Module_decl const* d) { return g.gen(d); } }; return apply(d, Fn{*this}); } void Generator::gen_local(Variable_decl const* d) { // NOTE: You will need to rebind this declaration to // the allocated local. Use Environment<S, T>::rebind. throw std::runtime_error("not implemented"); } void Generator::gen_global(Variable_decl const* d) { String const& name = d->name()->spelling(); llvm::Type* type = build.getInt32Ty(); // FIXME: Handle initialization correctly. llvm::Constant* init = llvm::ConstantAggregateZero::get(type); // Build the global variable, automatically adding // it to the module. llvm::GlobalVariable* var = new llvm::GlobalVariable( *mod, // owning module type, // type false, // is constant llvm::GlobalVariable::ExternalLinkage, // linkage, init, // initializer name // name ); // Create a binding for the new variable. stack.top().bind(d, var); } // Generate code for a variable declaration. Note that // code generation depends heavily on context. Globals // and locals are very different. // // TODO: If we add class/record types, then we also // need to handle member variables as well. Maybe. void Generator::gen(Variable_decl const* d) { if (is_global_variable(d)) return gen_global(d); else return gen_local(d); } void Generator::gen(Function_decl const* d) { String const& name = d->name()->spelling(); llvm::Type* type = get_type(d->type()); // Build the function. llvm::FunctionType* ftype = llvm::cast<llvm::FunctionType>(type); llvm::Function* fn = llvm::Function::Create( ftype, // function type llvm::Function::ExternalLinkage, // linkage name, // name mod); // owning module // Create a new binding for the variable. stack.top().bind(d, fn); // Establish a new binding environment for declarations // related to this function. Symbol_sentinel scope(*this); // Build the argument list. Note that { auto ai = fn->arg_begin(); auto pi = d->parameters().begin(); while (ai != fn->arg_end()) { Decl const* p = *pi; llvm::Argument* a = &*ai; a->setName(p->name()->spelling()); // Create an initial name binding for the // function parameter. Note that we're // going to overwrite this when we create // locals for each parameter. stack.top().bind(p, a); ++ai; ++pi; } } // Build the entry point for the function // and make that the insertion point. // // TODO: We probably need a stack of blocks // so that we know where we are. llvm::BasicBlock* b = llvm::BasicBlock::Create(cxt, "b", fn); build.SetInsertPoint(b); // Generate a local variable for each of the variables. for (Decl const* p : d->parameters()) gen(p); // Generate the body of the function. gen(d->body()); } void Generator::gen(Parameter_decl const* d) { llvm::Type* t = get_type(d->type()); llvm::Value* a = stack.top().get(d).second; llvm::Value* v = build.CreateAlloca(t); stack.top().rebind(d, v); build.CreateStore(a, v); } void Generator::gen(Module_decl const* d) { // Establish the global binding environment. Symbol_sentinel scope(*this); // Initialize the module. // // TODO: Make the output name the ".ll" version of the // the input name. Although this might also depend on // whether we're generating IR or object code? assert(!mod); mod = new llvm::Module("a.ll", cxt); // Generate all top-level declarations. for (Decl const* d1 : d->declarations()) gen(d1); // TODO: Make a second pass to generate global // constructors for initializers. } llvm::Module* Generator::operator()(Decl const* d) { assert(is<Module_decl>(d)); gen(d); return mod; } <commit_msg>Update code generation for global variables.<commit_after> #include "generator.hpp" #include "type.hpp" #include "expr.hpp" #include "stmt.hpp" #include "decl.hpp" #include "evaluator.hpp" #include "llvm/IR/Type.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/Function.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Module.h" #include <iostream> // -------------------------------------------------------------------------- // // Mapping of types // // The type generator transforms a beaker type into // its correspondiong LLVM type. llvm::Type* Generator::get_type(Type const* t) { struct Fn { Generator& g; llvm::Type* operator()(Boolean_type const* t) const { return g.get_type(t); } llvm::Type* operator()(Integer_type const* t) const { return g.get_type(t); } llvm::Type* operator()(Function_type const* t) const { return g.get_type(t); } llvm::Type* operator()(Reference_type const* t) const { return g.get_type(t); } }; return apply(t, Fn{*this}); } // Return the 1 bit integer type. llvm::Type* Generator::get_type(Boolean_type const*) { return build.getInt1Ty(); } // Return the 32 bit integer type. llvm::Type* Generator::get_type(Integer_type const*) { return build.getInt32Ty(); } // Return a function type. llvm::Type* Generator::get_type(Function_type const* t) { std::vector<llvm::Type*> ts; ts.reserve(t->parameter_types().size()); for (Type const* t1 : t->parameter_types()) ts.push_back(get_type(t1)); llvm::Type* r = get_type(t->return_type()); return llvm::FunctionType::get(r, ts, false); } // Translate reference types into pointer types in the // generic address space. // // TODO: Actually do this? llvm::Type* Generator::get_type(Reference_type const* t) { llvm::Type* t1 = get_type(t->type()); return llvm::PointerType::getUnqual(t1); } // -------------------------------------------------------------------------- // // Code generation for expressions // // An expression is transformed into a sequence instructions whose // intermediate results are saved in registers. llvm::Value* Generator::gen(Expr const* e) { struct Fn { Generator& g; llvm::Value* operator()(Literal_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Id_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Add_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Sub_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Mul_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Div_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Rem_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Neg_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Pos_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Eq_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Ne_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Lt_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Gt_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Le_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Ge_expr const* e) const { return g.gen(e); } llvm::Value* operator()(And_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Or_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Not_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Call_expr const* e) const { return g.gen(e); } llvm::Value* operator()(Value_conv const* e) const { return g.gen(e); } }; return apply(e, Fn{*this}); } // Return the value corresponding to a literal expression. llvm::Value* Generator::gen(Literal_expr const* e) { // TODO: Write better type queries. // // TODO: Write a better interface for values. Value v = evaluate(e); if (e->type() == get_boolean_type()) return build.getInt1(v.get_integer()); if (e->type() == get_integer_type()) return build.getInt32(v.get_integer()); else throw std::runtime_error("cannot generate function literal"); } // Returns the value associated with the declaration. // // TODO: Do we need to do anything different for function // identifiers or not? llvm::Value* Generator::gen(Id_expr const* e) { return stack.lookup(e->declaration())->second; } llvm::Value* Generator::gen(Add_expr const* e) { llvm::Value* l = gen(e->left()); llvm::Value* r = gen(e->right()); return build.CreateAdd(l, r); } llvm::Value* Generator::gen(Sub_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Mul_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Div_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Rem_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Neg_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Pos_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Eq_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Ne_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Lt_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Gt_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Le_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Ge_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(And_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Or_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Not_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Call_expr const* e) { throw std::runtime_error("not implemented"); } llvm::Value* Generator::gen(Value_conv const* e) { llvm::Value* v = gen(e->source()); return build.CreateLoad(v); } // -------------------------------------------------------------------------- // // Code generation for statements // // The statement generator is responsible for // the generation of statements at block scope. void Generator::gen(Stmt const* s) { struct Fn { Generator& g; void operator()(Empty_stmt const* s) { g.gen(s); } void operator()(Block_stmt const* s) { g.gen(s); } void operator()(Assign_stmt const* s) { g.gen(s); } void operator()(Return_stmt const* s) { g.gen(s); } void operator()(If_then_stmt const* s) { g.gen(s); } void operator()(If_else_stmt const* s) { g.gen(s); } void operator()(While_stmt const* s) { g.gen(s); } void operator()(Break_stmt const* s) { g.gen(s); } void operator()(Continue_stmt const* s) { g.gen(s); } void operator()(Expression_stmt const* s) { g.gen(s); } void operator()(Declaration_stmt const* s) { g.gen(s); } }; apply(s, Fn{*this}); } void Generator::gen(Empty_stmt const* s) { throw std::runtime_error("not implemented"); } // Generate code for a sequence of statements. // Note that this does not correspond to a basic // block since we don't need any terminators // in the following program. // // { // { ; } // } // // We only need new blocks for specific control // flow concepts. void Generator::gen(Block_stmt const* s) { for (Stmt const* s1 : s->statements()) gen(s1); } void Generator::gen(Assign_stmt const* s) { llvm::Value* lhs = gen(s->object()); llvm::Value* rhs = gen(s->value()); build.CreateStore(rhs, lhs); } void Generator::gen(Return_stmt const* s) { llvm::Value* v = gen(s->value()); build.CreateRet(v); } void Generator::gen(If_then_stmt const* s) { throw std::runtime_error("not implemented"); } void Generator::gen(If_else_stmt const* s) { throw std::runtime_error("not implemented"); } void Generator::gen(While_stmt const* s) { throw std::runtime_error("not implemented"); } void Generator::gen(Break_stmt const* s) { throw std::runtime_error("not implemented"); } void Generator::gen(Continue_stmt const* s) { throw std::runtime_error("not implemented"); } void Generator::gen(Expression_stmt const* s) { gen(s->expression()); } void Generator::gen(Declaration_stmt const* s) { gen(s->declaration()); } // -------------------------------------------------------------------------- // // Code generation for declarations // // TODO: We can't generate all of the code for a module // in a single pass. We probably need to break this up // into a number of smaller declaration generators. For // example, generators that: // // - produce declarations // - produce global initializers // - produce global destructors // - other stuff // // In, it might not be worthwhile to have a number // of sub-generators that refer to the top-level // generator. void Generator::gen(Decl const* d) { struct Fn { Generator& g; void operator()(Variable_decl const* d) { return g.gen(d); } void operator()(Function_decl const* d) { return g.gen(d); } void operator()(Parameter_decl const* d) { return g.gen(d); } void operator()(Module_decl const* d) { return g.gen(d); } }; return apply(d, Fn{*this}); } void Generator::gen_local(Variable_decl const* d) { throw std::runtime_error("not implemented"); } void Generator::gen_global(Variable_decl const* d) { String const& name = d->name()->spelling(); llvm::Type* type = get_type(d->type()); // FIXME: Handle initialization correctly. If the // initializer is a literal (or a constant expression), // then we should evaluate that and assign it here. llvm::Constant* init = llvm::ConstantInt::get(type, 0); // Note that the aggregate 0 only applies to aggregate // types. We can't apply it to initializers for scalars. // llvm::Constant* init = llvm::ConstantAggregateZero::get(type); // Build the global variable, automatically adding // it to the module. llvm::GlobalVariable* var = new llvm::GlobalVariable( *mod, // owning module type, // type false, // is constant llvm::GlobalVariable::ExternalLinkage, // linkage, init, // initializer name // name ); // Create a binding for the new variable. stack.top().bind(d, var); } // Generate code for a variable declaration. Note that // code generation depends heavily on context. Globals // and locals are very different. // // TODO: If we add class/record types, then we also // need to handle member variables as well. Maybe. void Generator::gen(Variable_decl const* d) { if (is_global_variable(d)) return gen_global(d); else return gen_local(d); } void Generator::gen(Function_decl const* d) { String const& name = d->name()->spelling(); llvm::Type* type = get_type(d->type()); // Build the function. llvm::FunctionType* ftype = llvm::cast<llvm::FunctionType>(type); llvm::Function* fn = llvm::Function::Create( ftype, // function type llvm::Function::ExternalLinkage, // linkage name, // name mod); // owning module // Create a new binding for the variable. stack.top().bind(d, fn); // Establish a new binding environment for declarations // related to this function. Symbol_sentinel scope(*this); // Build the argument list. Note that { auto ai = fn->arg_begin(); auto pi = d->parameters().begin(); while (ai != fn->arg_end()) { Decl const* p = *pi; llvm::Argument* a = &*ai; a->setName(p->name()->spelling()); // Create an initial name binding for the function // parameter. Note that we're going to overwrite // this when we create locals for each parameter. stack.top().bind(p, a); ++ai; ++pi; } } // Build the entry point for the function // and make that the insertion point. // // TODO: We probably need a stack of blocks // so that we know where we are. llvm::BasicBlock* b = llvm::BasicBlock::Create(cxt, "b", fn); build.SetInsertPoint(b); // Generate a local variable for each of the variables. for (Decl const* p : d->parameters()) gen(p); // Generate the body of the function. gen(d->body()); } void Generator::gen(Parameter_decl const* d) { llvm::Type* t = get_type(d->type()); llvm::Value* a = stack.top().get(d).second; llvm::Value* v = build.CreateAlloca(t); stack.top().rebind(d, v); build.CreateStore(a, v); } void Generator::gen(Module_decl const* d) { // Establish the global binding environment. Symbol_sentinel scope(*this); // Initialize the module. // // TODO: Make the output name the ".ll" version of the // the input name. Although this might also depend on // whether we're generating IR or object code? assert(!mod); mod = new llvm::Module("a.ll", cxt); // Generate all top-level declarations. for (Decl const* d1 : d->declarations()) gen(d1); // TODO: Make a second pass to generate global // constructors for initializers. } llvm::Module* Generator::operator()(Decl const* d) { assert(is<Module_decl>(d)); gen(d); return mod; } <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file KeyMap.cxx ** Defines a mapping between keystrokes and commands. **/ // Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include "Platform.h" #include "Scintilla.h" #include "KeyMap.h" KeyMap::KeyMap() : kmap(0), len(0), alloc(0) { for (int i = 0; MapDefault[i].key; i++) { AssignCmdKey(MapDefault[i].key, MapDefault[i].modifiers, MapDefault[i].msg); } } KeyMap::~KeyMap() { Clear(); } void KeyMap::Clear() { delete []kmap; kmap = 0; len = 0; alloc = 0; } void KeyMap::AssignCmdKey(int key, int modifiers, unsigned int msg) { if ((len+1) >= alloc) { KeyToCommand *ktcNew = new KeyToCommand[alloc + 5]; if (!ktcNew) return; for (int k=0;k<len;k++) ktcNew[k] = kmap[k]; alloc += 5; delete []kmap; kmap = ktcNew; } for (int keyIndex = 0; keyIndex < len; keyIndex++) { if ((key == kmap[keyIndex].key) && (modifiers == kmap[keyIndex].modifiers)) { kmap[keyIndex].msg = msg; return; } } kmap[len].key = key; kmap[len].modifiers = modifiers; kmap[len].msg = msg; len++; } unsigned int KeyMap::Find(int key, int modifiers) { for (int i=0; i < len; i++) { if ((key == kmap[i].key) && (modifiers == kmap[i].modifiers)) { return kmap[i].msg; } } return 0; } KeyToCommand KeyMap::MapDefault[] = { {SCK_DOWN, SCI_NORM, SCI_LINEDOWN}, {SCK_DOWN, SCI_SHIFT, SCI_LINEDOWNEXTEND}, {SCK_DOWN, SCI_CTRL, SCI_LINESCROLLDOWN}, {SCK_UP, SCI_NORM, SCI_LINEUP}, {SCK_UP, SCI_SHIFT, SCI_LINEUPEXTEND}, {SCK_UP, SCI_CTRL, SCI_LINESCROLLUP}, {SCK_LEFT, SCI_NORM, SCI_CHARLEFT}, {SCK_LEFT, SCI_SHIFT, SCI_CHARLEFTEXTEND}, {SCK_LEFT, SCI_CTRL, SCI_WORDLEFT}, {SCK_LEFT, SCI_CSHIFT, SCI_WORDLEFTEXTEND}, {SCK_RIGHT, SCI_NORM, SCI_CHARRIGHT}, {SCK_RIGHT, SCI_SHIFT, SCI_CHARRIGHTEXTEND}, {SCK_RIGHT, SCI_CTRL, SCI_WORDRIGHT}, {SCK_RIGHT, SCI_CSHIFT, SCI_WORDRIGHTEXTEND}, {SCK_HOME, SCI_NORM, SCI_VCHOME}, {SCK_HOME, SCI_SHIFT, SCI_VCHOMEEXTEND}, {SCK_HOME, SCI_CTRL, SCI_DOCUMENTSTART}, {SCK_HOME, SCI_CSHIFT, SCI_DOCUMENTSTARTEXTEND}, {SCK_END, SCI_NORM, SCI_LINEEND}, {SCK_END, SCI_SHIFT, SCI_LINEENDEXTEND}, {SCK_END, SCI_CTRL, SCI_DOCUMENTEND}, {SCK_END, SCI_CSHIFT, SCI_DOCUMENTENDEXTEND}, {SCK_PRIOR, SCI_NORM, SCI_PAGEUP}, {SCK_PRIOR, SCI_SHIFT, SCI_PAGEUPEXTEND}, {SCK_NEXT, SCI_NORM, SCI_PAGEDOWN}, {SCK_NEXT, SCI_SHIFT, SCI_PAGEDOWNEXTEND}, {SCK_DELETE, SCI_NORM, SCI_CLEAR}, {SCK_DELETE, SCI_SHIFT, SCI_CUT}, {SCK_DELETE, SCI_CTRL, SCI_DELWORDRIGHT}, {SCK_INSERT, SCI_NORM, SCI_EDITTOGGLEOVERTYPE}, {SCK_INSERT, SCI_SHIFT, SCI_PASTE}, {SCK_INSERT, SCI_CTRL, SCI_COPY}, {SCK_ESCAPE, SCI_NORM, SCI_CANCEL}, {SCK_BACK, SCI_NORM, SCI_DELETEBACK}, {SCK_BACK, SCI_SHIFT, SCI_DELETEBACK}, {SCK_BACK, SCI_CTRL, SCI_DELWORDLEFT}, {SCK_BACK, SCI_ALT, SCI_UNDO}, {'Z', SCI_CTRL, SCI_UNDO}, {'Y', SCI_CTRL, SCI_REDO}, {'X', SCI_CTRL, SCI_CUT}, {'C', SCI_CTRL, SCI_COPY}, {'V', SCI_CTRL, SCI_PASTE}, {'A', SCI_CTRL, SCI_SELECTALL}, {SCK_TAB, SCI_NORM, SCI_TAB}, {SCK_TAB, SCI_SHIFT, SCI_BACKTAB}, {SCK_RETURN, SCI_NORM, SCI_NEWLINE}, {SCK_ADD, SCI_CTRL, SCI_ZOOMIN}, {SCK_SUBTRACT, SCI_CTRL, SCI_ZOOMOUT}, {SCK_DIVIDE, SCI_CTRL, SCI_SETZOOM}, //'L', SCI_CTRL, SCI_FORMFEED, {'L', SCI_CTRL, SCI_LINECUT}, {'L', SCI_CSHIFT, SCI_LINEDELETE}, {'T', SCI_CTRL, SCI_LINETRANSPOSE}, {'U', SCI_CTRL, SCI_LOWERCASE}, {'U', SCI_CSHIFT, SCI_UPPERCASE}, {0,0,0}, }; <commit_msg>Patch from James Larcombe to add Ctrl+Shift+BackSpace and Ctrl+Shift+Delete<commit_after>// Scintilla source code edit control /** @file KeyMap.cxx ** Defines a mapping between keystrokes and commands. **/ // Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include "Platform.h" #include "Scintilla.h" #include "KeyMap.h" KeyMap::KeyMap() : kmap(0), len(0), alloc(0) { for (int i = 0; MapDefault[i].key; i++) { AssignCmdKey(MapDefault[i].key, MapDefault[i].modifiers, MapDefault[i].msg); } } KeyMap::~KeyMap() { Clear(); } void KeyMap::Clear() { delete []kmap; kmap = 0; len = 0; alloc = 0; } void KeyMap::AssignCmdKey(int key, int modifiers, unsigned int msg) { if ((len+1) >= alloc) { KeyToCommand *ktcNew = new KeyToCommand[alloc + 5]; if (!ktcNew) return; for (int k=0;k<len;k++) ktcNew[k] = kmap[k]; alloc += 5; delete []kmap; kmap = ktcNew; } for (int keyIndex = 0; keyIndex < len; keyIndex++) { if ((key == kmap[keyIndex].key) && (modifiers == kmap[keyIndex].modifiers)) { kmap[keyIndex].msg = msg; return; } } kmap[len].key = key; kmap[len].modifiers = modifiers; kmap[len].msg = msg; len++; } unsigned int KeyMap::Find(int key, int modifiers) { for (int i=0; i < len; i++) { if ((key == kmap[i].key) && (modifiers == kmap[i].modifiers)) { return kmap[i].msg; } } return 0; } KeyToCommand KeyMap::MapDefault[] = { {SCK_DOWN, SCI_NORM, SCI_LINEDOWN}, {SCK_DOWN, SCI_SHIFT, SCI_LINEDOWNEXTEND}, {SCK_DOWN, SCI_CTRL, SCI_LINESCROLLDOWN}, {SCK_UP, SCI_NORM, SCI_LINEUP}, {SCK_UP, SCI_SHIFT, SCI_LINEUPEXTEND}, {SCK_UP, SCI_CTRL, SCI_LINESCROLLUP}, {SCK_LEFT, SCI_NORM, SCI_CHARLEFT}, {SCK_LEFT, SCI_SHIFT, SCI_CHARLEFTEXTEND}, {SCK_LEFT, SCI_CTRL, SCI_WORDLEFT}, {SCK_LEFT, SCI_CSHIFT, SCI_WORDLEFTEXTEND}, {SCK_RIGHT, SCI_NORM, SCI_CHARRIGHT}, {SCK_RIGHT, SCI_SHIFT, SCI_CHARRIGHTEXTEND}, {SCK_RIGHT, SCI_CTRL, SCI_WORDRIGHT}, {SCK_RIGHT, SCI_CSHIFT, SCI_WORDRIGHTEXTEND}, {SCK_HOME, SCI_NORM, SCI_VCHOME}, {SCK_HOME, SCI_SHIFT, SCI_VCHOMEEXTEND}, {SCK_HOME, SCI_CTRL, SCI_DOCUMENTSTART}, {SCK_HOME, SCI_CSHIFT, SCI_DOCUMENTSTARTEXTEND}, {SCK_END, SCI_NORM, SCI_LINEEND}, {SCK_END, SCI_SHIFT, SCI_LINEENDEXTEND}, {SCK_END, SCI_CTRL, SCI_DOCUMENTEND}, {SCK_END, SCI_CSHIFT, SCI_DOCUMENTENDEXTEND}, {SCK_PRIOR, SCI_NORM, SCI_PAGEUP}, {SCK_PRIOR, SCI_SHIFT, SCI_PAGEUPEXTEND}, {SCK_NEXT, SCI_NORM, SCI_PAGEDOWN}, {SCK_NEXT, SCI_SHIFT, SCI_PAGEDOWNEXTEND}, {SCK_DELETE, SCI_NORM, SCI_CLEAR}, {SCK_DELETE, SCI_SHIFT, SCI_CUT}, {SCK_DELETE, SCI_CTRL, SCI_DELWORDRIGHT}, {SCK_DELETE, SCI_CSHIFT, SCI_DELLINERIGHT}, {SCK_INSERT, SCI_NORM, SCI_EDITTOGGLEOVERTYPE}, {SCK_INSERT, SCI_SHIFT, SCI_PASTE}, {SCK_INSERT, SCI_CTRL, SCI_COPY}, {SCK_ESCAPE, SCI_NORM, SCI_CANCEL}, {SCK_BACK, SCI_NORM, SCI_DELETEBACK}, {SCK_BACK, SCI_SHIFT, SCI_DELETEBACK}, {SCK_BACK, SCI_CTRL, SCI_DELWORDLEFT}, {SCK_BACK, SCI_ALT, SCI_UNDO}, {SCK_BACK, SCI_CSHIFT, SCI_DELLINELEFT}, {'Z', SCI_CTRL, SCI_UNDO}, {'Y', SCI_CTRL, SCI_REDO}, {'X', SCI_CTRL, SCI_CUT}, {'C', SCI_CTRL, SCI_COPY}, {'V', SCI_CTRL, SCI_PASTE}, {'A', SCI_CTRL, SCI_SELECTALL}, {SCK_TAB, SCI_NORM, SCI_TAB}, {SCK_TAB, SCI_SHIFT, SCI_BACKTAB}, {SCK_RETURN, SCI_NORM, SCI_NEWLINE}, {SCK_ADD, SCI_CTRL, SCI_ZOOMIN}, {SCK_SUBTRACT, SCI_CTRL, SCI_ZOOMOUT}, {SCK_DIVIDE, SCI_CTRL, SCI_SETZOOM}, //'L', SCI_CTRL, SCI_FORMFEED, {'L', SCI_CTRL, SCI_LINECUT}, {'L', SCI_CSHIFT, SCI_LINEDELETE}, {'T', SCI_CTRL, SCI_LINETRANSPOSE}, {'U', SCI_CTRL, SCI_LOWERCASE}, {'U', SCI_CSHIFT, SCI_UPPERCASE}, {0,0,0}, }; <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file LexCPP.cxx ** Lexer for C++, C, Java, and Javascript. **/ // Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static bool classifyWordCpp(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) { PLATFORM_ASSERT(end >= start); char s[100]; for (unsigned int i = 0; (i < end - start + 1) && (i < 30); i++) { s[i] = styler[start + i]; s[i + 1] = '\0'; } bool wordIsUUID = false; char chAttr = SCE_C_IDENTIFIER; if (isdigit(s[0]) || (s[0] == '.')) chAttr = SCE_C_NUMBER; else { if (keywords.InList(s)) { chAttr = SCE_C_WORD; wordIsUUID = strcmp(s, "uuid") == 0; } } styler.ColourTo(end, chAttr); return wordIsUUID; } static bool isOKBeforeRE(char ch) { return (ch == '(') || (ch == '=') || (ch == ','); } static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; styler.StartAt(startPos); bool fold = styler.GetPropertyInt("fold"); bool foldComment = styler.GetPropertyInt("fold.comment"); bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor"); int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; int state = initStyle; int styleBeforeLineStart = initStyle; if (state == SCE_C_STRINGEOL) // Does not leak onto next line state = SCE_C_DEFAULT; char chPrev = ' '; char chNext = styler[startPos]; char chPrevNonWhite = ' '; unsigned int lengthDoc = startPos + length; int visibleChars = 0; styler.StartSegment(startPos); bool lastWordWasUUID = false; for (unsigned int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (atEOL) { // Trigger on CR only (Mac style) or either on LF from CR+LF (Dos/Win) or on LF alone (Unix) // Avoid triggering two times on Dos/Win // End of line if (state == SCE_C_STRINGEOL) { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } } if (styler.IsLeadByte(ch)) { chNext = styler.SafeGetCharAt(i + 2); chPrev = ' '; i += 1; continue; } if (state == SCE_C_DEFAULT) { if (ch == '@' && chNext == '\"') { styler.ColourTo(i - 1, state); state = SCE_C_VERBATIM; i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } else if (iswordstart(ch) || (ch == '@')) { styler.ColourTo(i - 1, state); if (lastWordWasUUID) { state = SCE_C_UUID; lastWordWasUUID = false; } else { state = SCE_C_IDENTIFIER; } } else if (ch == '/' && chNext == '*') { styler.ColourTo(i - 1, state); if (foldComment) levelCurrent++; if (styler.SafeGetCharAt(i + 2) == '*' || styler.SafeGetCharAt(i + 2) == '!') // Support of Qt/Doxygen doc. style state = SCE_C_COMMENTDOC; else state = SCE_C_COMMENT; } else if (ch == '/' && chNext == '/') { styler.ColourTo(i - 1, state); if (styler.SafeGetCharAt(i + 2) == '/' || styler.SafeGetCharAt(i + 2) == '!') // Support of Qt/Doxygen doc. style state = SCE_C_COMMENTLINEDOC; else state = SCE_C_COMMENTLINE; } else if (ch == '/' && isOKBeforeRE(chPrevNonWhite)) { styler.ColourTo(i - 1, state); state = SCE_C_REGEX; } else if (ch == '\"') { styler.ColourTo(i - 1, state); state = SCE_C_STRING; } else if (ch == '\'') { styler.ColourTo(i - 1, state); state = SCE_C_CHARACTER; } else if (ch == '#' && visibleChars == 0) { // Preprocessor commands are alone on their line styler.ColourTo(i - 1, state); state = SCE_C_PREPROCESSOR; // Skip whitespace between # and preprocessor word do { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } while (isspacechar(ch) && (i < lengthDoc)); } else if (isoperator(ch)) { styler.ColourTo(i-1, state); styler.ColourTo(i, SCE_C_OPERATOR); if ((ch == '{') || (ch == '}')) { levelCurrent += (ch == '{') ? 1 : -1; } } } else if (state == SCE_C_IDENTIFIER) { if (!iswordchar(ch)) { lastWordWasUUID = classifyWordCpp(styler.GetStartSegment(), i - 1, keywords, styler); state = SCE_C_DEFAULT; if (ch == '/' && chNext == '*') { if (foldComment) levelCurrent++; if (styler.SafeGetCharAt(i + 2) == '*') state = SCE_C_COMMENTDOC; else state = SCE_C_COMMENT; } else if (ch == '/' && chNext == '/') { state = SCE_C_COMMENTLINE; } else if (ch == '\"') { state = SCE_C_STRING; } else if (ch == '\'') { state = SCE_C_CHARACTER; } else if (isoperator(ch)) { styler.ColourTo(i, SCE_C_OPERATOR); if ((ch == '{') || (ch == '}')) { levelCurrent += (ch == '{') ? 1 : -1; } } } } else { if (state == SCE_C_PREPROCESSOR) { if (stylingWithinPreprocessor) { if (isspacechar(ch)) { styler.ColourTo(i - 1, state); state = SCE_C_DEFAULT; } } else { if (atEOL && (chPrev != '\\')) { styler.ColourTo(i - 1, state); state = SCE_C_DEFAULT; } } } else if (state == SCE_C_COMMENT) { if (ch == '/' && chPrev == '*') { if (((i > styler.GetStartSegment() + 2) || ( (styleBeforeLineStart == SCE_C_COMMENT) && (i > styler.GetStartSegment())))) { styler.ColourTo(i, state); state = SCE_C_DEFAULT; if (foldComment) levelCurrent--; } } } else if (state == SCE_C_COMMENTDOC) { if (ch == '/' && chPrev == '*') { if (((i > styler.GetStartSegment() + 2) || ( (styleBeforeLineStart == SCE_C_COMMENTDOC) && (i > styler.GetStartSegment())))) { styler.ColourTo(i, state); state = SCE_C_DEFAULT; if (foldComment) levelCurrent--; } } } else if (state == SCE_C_COMMENTLINE || state == SCE_C_COMMENTLINEDOC) { if (ch == '\r' || ch == '\n') { styler.ColourTo(i - 1, state); state = SCE_C_DEFAULT; } } else if (state == SCE_C_STRING) { if (ch == '\\') { if (chNext == '\"' || chNext == '\'' || chNext == '\\') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if (ch == '\"') { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } else if ((chNext == '\r' || chNext == '\n') && (chPrev != '\\')) { styler.ColourTo(i - 1, SCE_C_STRINGEOL); state = SCE_C_STRINGEOL; } } else if (state == SCE_C_CHARACTER) { if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) { styler.ColourTo(i - 1, SCE_C_STRINGEOL); state = SCE_C_STRINGEOL; } else if (ch == '\\') { if (chNext == '\"' || chNext == '\'' || chNext == '\\') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if (ch == '\'') { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } } else if (state == SCE_C_REGEX) { if (ch == '\r' || ch == '\n' || ch == '/') { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } else if (ch == '\\') { // Gobble up the quoted character if (chNext == '\\' || chNext == '/') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } } else if (state == SCE_C_VERBATIM) { if (ch == '\"') { if (chNext == '\"') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } else { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } } } else if (state == SCE_C_UUID) { if (ch == '\r' || ch == '\n' || ch == ')') { styler.ColourTo(i - 1, state); if (ch == ')') styler.ColourTo(i, SCE_C_OPERATOR); state = SCE_C_DEFAULT; } } } if (atEOL) { if (fold) { int lev = levelPrev; if (visibleChars == 0) lev |= SC_FOLDLEVELWHITEFLAG; if ((levelCurrent > levelPrev) && (visibleChars > 0)) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) { styler.ColourTo(i, state); styler.Flush(); styler.SetLevel(lineCurrent, lev); styler.StartAt(i + 1); } lineCurrent++; levelPrev = levelCurrent; } styleBeforeLineStart = state; visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; chPrev = ch; if (ch != ' ' && ch != '\t') chPrevNonWhite = ch; } styler.ColourTo(lengthDoc - 1, state); // Fill in the real level of the next line, keeping the current flags as they will be filled in later if (fold) { int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; //styler.SetLevel(lineCurrent, levelCurrent | flagsNext); styler.SetLevel(lineCurrent, levelPrev | flagsNext); } } LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc); <commit_msg>Separated folding from lexing.<commit_after>// Scintilla source code edit control /** @file LexCPP.cxx ** Lexer for C++, C, Java, and Javascript. **/ // Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static bool classifyWordCpp(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) { PLATFORM_ASSERT(end >= start); char s[100]; for (unsigned int i = 0; (i < end - start + 1) && (i < 30); i++) { s[i] = styler[start + i]; s[i + 1] = '\0'; } bool wordIsUUID = false; char chAttr = SCE_C_IDENTIFIER; if (isdigit(s[0]) || (s[0] == '.')) chAttr = SCE_C_NUMBER; else { if (keywords.InList(s)) { chAttr = SCE_C_WORD; wordIsUUID = strcmp(s, "uuid") == 0; } } styler.ColourTo(end, chAttr); return wordIsUUID; } static bool isOKBeforeRE(char ch) { return (ch == '(') || (ch == '=') || (ch == ','); } static void FoldCppDoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) { // Finished the styling, time for folding bool fold = styler.GetPropertyInt("fold"); bool foldComment = styler.GetPropertyInt("fold.comment"); unsigned int lengthDoc = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); int style = initStyle; if (fold) { for (unsigned int j = startPos; j < lengthDoc; j++) { char ch = chNext; chNext = styler.SafeGetCharAt(j + 1); int stylePrev = style; style = styleNext; styleNext = styler.StyleAt(j + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (foldComment && (style == SCE_C_COMMENT || style == SCE_C_COMMENTDOC)) { if (style != stylePrev) { levelCurrent++; } else if ((style != styleNext) && !atEOL) { // Comments don't end at end of line and the next character may be unstyled. levelCurrent--; } } if (style == SCE_C_OPERATOR) { if (ch == '{') { levelCurrent++; } else if (ch == '}') { levelCurrent--; } } if (atEOL) { int lev = levelPrev; if (visibleChars == 0) lev |= SC_FOLDLEVELWHITEFLAG; if ((levelCurrent > levelPrev) && (visibleChars > 0)) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelPrev = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; } // Fill in the real level of the next line, keeping the current flags as they will be filled in later int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; //styler.SetLevel(lineCurrent, levelCurrent | flagsNext); styler.SetLevel(lineCurrent, levelPrev | flagsNext); } } static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; styler.StartAt(startPos); bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor"); //int lineCurrent = styler.GetLine(startPos); int state = initStyle; int styleBeforeLineStart = initStyle; if (state == SCE_C_STRINGEOL) // Does not leak onto next line state = SCE_C_DEFAULT; char chPrev = ' '; char chNext = styler[startPos]; char chPrevNonWhite = ' '; unsigned int lengthDoc = startPos + length; int visibleChars = 0; styler.StartSegment(startPos); bool lastWordWasUUID = false; for (unsigned int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (atEOL) { // Trigger on CR only (Mac style) or either on LF from CR+LF (Dos/Win) or on LF alone (Unix) // Avoid triggering two times on Dos/Win // End of line if (state == SCE_C_STRINGEOL) { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } } if (styler.IsLeadByte(ch)) { chNext = styler.SafeGetCharAt(i + 2); chPrev = ' '; i += 1; continue; } if (state == SCE_C_DEFAULT) { if (ch == '@' && chNext == '\"') { styler.ColourTo(i - 1, state); state = SCE_C_VERBATIM; i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } else if (iswordstart(ch) || (ch == '@')) { styler.ColourTo(i - 1, state); if (lastWordWasUUID) { state = SCE_C_UUID; lastWordWasUUID = false; } else { state = SCE_C_IDENTIFIER; } } else if (ch == '/' && chNext == '*') { styler.ColourTo(i - 1, state); if (styler.SafeGetCharAt(i + 2) == '*' || styler.SafeGetCharAt(i + 2) == '!') // Support of Qt/Doxygen doc. style state = SCE_C_COMMENTDOC; else state = SCE_C_COMMENT; } else if (ch == '/' && chNext == '/') { styler.ColourTo(i - 1, state); if (styler.SafeGetCharAt(i + 2) == '/' || styler.SafeGetCharAt(i + 2) == '!') // Support of Qt/Doxygen doc. style state = SCE_C_COMMENTLINEDOC; else state = SCE_C_COMMENTLINE; } else if (ch == '/' && isOKBeforeRE(chPrevNonWhite)) { styler.ColourTo(i - 1, state); state = SCE_C_REGEX; } else if (ch == '\"') { styler.ColourTo(i - 1, state); state = SCE_C_STRING; } else if (ch == '\'') { styler.ColourTo(i - 1, state); state = SCE_C_CHARACTER; } else if (ch == '#' && visibleChars == 0) { // Preprocessor commands are alone on their line styler.ColourTo(i - 1, state); state = SCE_C_PREPROCESSOR; // Skip whitespace between # and preprocessor word do { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } while (isspacechar(ch) && (i < lengthDoc)); } else if (isoperator(ch)) { styler.ColourTo(i-1, state); styler.ColourTo(i, SCE_C_OPERATOR); } } else if (state == SCE_C_IDENTIFIER) { if (!iswordchar(ch)) { lastWordWasUUID = classifyWordCpp(styler.GetStartSegment(), i - 1, keywords, styler); state = SCE_C_DEFAULT; if (ch == '/' && chNext == '*') { if (styler.SafeGetCharAt(i + 2) == '*') state = SCE_C_COMMENTDOC; else state = SCE_C_COMMENT; } else if (ch == '/' && chNext == '/') { state = SCE_C_COMMENTLINE; } else if (ch == '\"') { state = SCE_C_STRING; } else if (ch == '\'') { state = SCE_C_CHARACTER; } else if (isoperator(ch)) { styler.ColourTo(i, SCE_C_OPERATOR); } } } else { if (state == SCE_C_PREPROCESSOR) { if (stylingWithinPreprocessor) { if (isspacechar(ch)) { styler.ColourTo(i - 1, state); state = SCE_C_DEFAULT; } } else { if (atEOL && (chPrev != '\\')) { styler.ColourTo(i - 1, state); state = SCE_C_DEFAULT; } } } else if (state == SCE_C_COMMENT) { if (ch == '/' && chPrev == '*') { if (((i > styler.GetStartSegment() + 2) || ( (styleBeforeLineStart == SCE_C_COMMENT) && (i > styler.GetStartSegment())))) { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } } } else if (state == SCE_C_COMMENTDOC) { if (ch == '/' && chPrev == '*') { if (((i > styler.GetStartSegment() + 2) || ( (styleBeforeLineStart == SCE_C_COMMENTDOC) && (i > styler.GetStartSegment())))) { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } } } else if (state == SCE_C_COMMENTLINE || state == SCE_C_COMMENTLINEDOC) { if (ch == '\r' || ch == '\n') { styler.ColourTo(i - 1, state); state = SCE_C_DEFAULT; } } else if (state == SCE_C_STRING) { if (ch == '\\') { if (chNext == '\"' || chNext == '\'' || chNext == '\\') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if (ch == '\"') { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } else if ((chNext == '\r' || chNext == '\n') && (chPrev != '\\')) { styler.ColourTo(i - 1, SCE_C_STRINGEOL); state = SCE_C_STRINGEOL; } } else if (state == SCE_C_CHARACTER) { if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) { styler.ColourTo(i - 1, SCE_C_STRINGEOL); state = SCE_C_STRINGEOL; } else if (ch == '\\') { if (chNext == '\"' || chNext == '\'' || chNext == '\\') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if (ch == '\'') { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } } else if (state == SCE_C_REGEX) { if (ch == '\r' || ch == '\n' || ch == '/') { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } else if (ch == '\\') { // Gobble up the quoted character if (chNext == '\\' || chNext == '/') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } } else if (state == SCE_C_VERBATIM) { if (ch == '\"') { if (chNext == '\"') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } else { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } } } else if (state == SCE_C_UUID) { if (ch == '\r' || ch == '\n' || ch == ')') { styler.ColourTo(i - 1, state); if (ch == ')') styler.ColourTo(i, SCE_C_OPERATOR); state = SCE_C_DEFAULT; } } } if (atEOL) { styleBeforeLineStart = state; visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; chPrev = ch; if (ch != ' ' && ch != '\t') chPrevNonWhite = ch; } styler.ColourTo(lengthDoc - 1, state); styler.Flush(); FoldCppDoc(startPos, length, initStyle, keywordlists, styler); } LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc); <|endoftext|>
<commit_before>/* This file is part of KitchenSync. Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "localkonnector.h" #include "localkonnectorconfig.h" #include <calendarsyncee.h> #include <addressbooksyncee.h> #include <bookmarksyncee.h> #include <synchistory.h> #include <libkdepim/kpimprefs.h> #include <libkdepim/progressmanager.h> #include <kabc/resourcefile.h> #include <konnectorinfo.h> #include <kconfig.h> #include <kgenericfactory.h> using namespace KSync; extern "C" { void *init_liblocalkonnector() { KGlobal::locale()->insertCatalogue( "konnector_local" ); return new KRES::PluginFactory<LocalKonnector,LocalKonnectorConfig>(); } } LocalKonnector::LocalKonnector( const KConfig *config ) : Konnector( config ), mConfigWidget( 0 ), mCalendar( KPimPrefs::timezone() ), mProgressItem( 0 ) { if ( config ) { mCalendarFile = config->readPathEntry( "CalendarFile" ); mAddressBookFile = config->readPathEntry( "AddressBookFile" ); mBookmarkFile = config->readPathEntry( "BookmarkFile" ); } mMd5sumCal = generateMD5Sum( mCalendarFile ) + "_localkonnector_cal.log"; mMd5sumAbk = generateMD5Sum( mAddressBookFile ) + "_localkonnector_abk.log"; mMd5sumBkm = generateMD5Sum( mBookmarkFile ) + "_localkonnector_bkm.log"; mAddressBookSyncee = new AddressBookSyncee( &mAddressBook ); mAddressBookSyncee->setTitle( i18n( "Local" ) ); mCalendarSyncee = new CalendarSyncee( &mCalendar ); mCalendarSyncee->setTitle( i18n( "Local" ) ); mSyncees.append( mCalendarSyncee ); mSyncees.append( mAddressBookSyncee ); mSyncees.append( new BookmarkSyncee( &mBookmarkManager ) ); mAddressBookResourceFile = new KABC::ResourceFile( mAddressBookFile ); mAddressBook.addResource( mAddressBookResourceFile ); } LocalKonnector::~LocalKonnector() { } void LocalKonnector::writeConfig( KConfig *config ) { Konnector::writeConfig( config ); config->writePathEntry( "CalendarFile", mCalendarFile ); config->writeEntry( "AddressBookFile", mAddressBookFile ); config->writeEntry( "BookmarkFile", mAddressBookFile ); } bool LocalKonnector::readSyncees() { kdDebug() << "LocalKonnector::readSyncee()" << endl; mProgressItem = progressItem( i18n( "Start loading local data..." ) ); if ( !mCalendarFile.isEmpty() ) { kdDebug() << "LocalKonnector::readSyncee(): calendar: " << mCalendarFile << endl; mCalendar.close(); mProgressItem->setStatus( i18n( "Load Calendar..." ) ); if ( mCalendar.load( mCalendarFile ) ) { kdDebug() << "Read succeeded." << endl; mCalendarSyncee->reset(); mCalendarSyncee->setIdentifier( mCalendarFile ); kdDebug() << "IDENTIFIER: " << mCalendarSyncee->identifier() << endl; /* apply SyncInformation here this will also create the SyncEntries */ CalendarSyncHistory cHelper( mCalendarSyncee, storagePath() + "/"+mMd5sumCal ); cHelper.load(); mProgressItem->setStatus( i18n( "Calendar loaded." ) ); } else { mProgressItem->setStatus( i18n( "Loading Calendar failed." ) ); emit synceeReadError( this ); kdDebug() << "Read failed." << endl; return false; } } mProgressItem->setProgress( 50 ); if ( !mAddressBookFile.isEmpty() ) { kdDebug() << "LocalKonnector::readSyncee(): addressbook: " << mAddressBookFile << endl; mProgressItem->setStatus( i18n( "Load AddressBook..." ) ); mAddressBookResourceFile->setFileName( mAddressBookFile ); if ( !mAddressBook.load() ) { mProgressItem->setStatus( i18n( "Loading AddressBook failed." ) ); emit synceeReadError( this ); kdDebug() << "Read failed." << endl; return false; } kdDebug() << "Read succeeded." << endl; mAddressBookSyncee->reset(); mAddressBookSyncee->setIdentifier( mAddressBook.identifier() ); kdDebug() << "IDENTIFIER: " << mAddressBookSyncee->identifier() << endl; KABC::AddressBook::Iterator it; for ( it = mAddressBook.begin(); it != mAddressBook.end(); ++it ) { KSync::AddressBookSyncEntry entry( *it, mAddressBookSyncee ); mAddressBookSyncee->addEntry( entry.clone() ); } /* let us apply Sync Information */ AddressBookSyncHistory aHelper( mAddressBookSyncee, storagePath() + "/"+mMd5sumAbk ); aHelper.load(); mProgressItem->setStatus( i18n( "AddressBook loaded." ) ); } // TODO: Read Bookmarks mProgressItem->setProgress( 100 ); mProgressItem->setComplete(); mProgressItem = 0; emit synceesRead( this ); return true; } bool LocalKonnector::connectDevice() { return true; } bool LocalKonnector::disconnectDevice() { return true; } KSync::KonnectorInfo LocalKonnector::info() const { return KonnectorInfo( i18n("Dummy Konnector"), QIconSet(), "agenda", // icon name false ); } QStringList LocalKonnector::supportedFilterTypes() const { QStringList types; types << "addressbook" << "calendar" << "bookmarks"; return types; } bool LocalKonnector::writeSyncees() { if ( !mCalendarFile.isEmpty() ) { purgeRemovedEntries( mCalendarSyncee ); if ( !mCalendar.save( mCalendarFile ) ) return false; CalendarSyncHistory cHelper( mCalendarSyncee, storagePath() + "/"+mMd5sumCal ); cHelper.save(); } if ( !mAddressBookFile.isEmpty() ) { purgeRemovedEntries( mAddressBookSyncee ); KABC::Ticket *ticket; ticket = mAddressBook.requestSaveTicket( mAddressBookResourceFile ); if ( !ticket ) { kdWarning() << "LocalKonnector::writeSyncees(). Couldn't get ticket for " << "addressbook." << endl; emit synceeWriteError( this ); return false; } if ( !mAddressBook.save( ticket ) ) return false; AddressBookSyncHistory aHelper( mAddressBookSyncee, storagePath() + "/"+mMd5sumAbk ); aHelper.save(); } // TODO: Write Bookmarks emit synceesWritten( this ); return true; } #include "localkonnector.moc" <commit_msg>write paths as path entries<commit_after>/* This file is part of KitchenSync. Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "localkonnector.h" #include "localkonnectorconfig.h" #include <calendarsyncee.h> #include <addressbooksyncee.h> #include <bookmarksyncee.h> #include <synchistory.h> #include <libkdepim/kpimprefs.h> #include <libkdepim/progressmanager.h> #include <kabc/resourcefile.h> #include <konnectorinfo.h> #include <kconfig.h> #include <kgenericfactory.h> using namespace KSync; extern "C" { void *init_liblocalkonnector() { KGlobal::locale()->insertCatalogue( "konnector_local" ); return new KRES::PluginFactory<LocalKonnector,LocalKonnectorConfig>(); } } LocalKonnector::LocalKonnector( const KConfig *config ) : Konnector( config ), mConfigWidget( 0 ), mCalendar( KPimPrefs::timezone() ), mProgressItem( 0 ) { if ( config ) { mCalendarFile = config->readPathEntry( "CalendarFile" ); mAddressBookFile = config->readPathEntry( "AddressBookFile" ); mBookmarkFile = config->readPathEntry( "BookmarkFile" ); } mMd5sumCal = generateMD5Sum( mCalendarFile ) + "_localkonnector_cal.log"; mMd5sumAbk = generateMD5Sum( mAddressBookFile ) + "_localkonnector_abk.log"; mMd5sumBkm = generateMD5Sum( mBookmarkFile ) + "_localkonnector_bkm.log"; mAddressBookSyncee = new AddressBookSyncee( &mAddressBook ); mAddressBookSyncee->setTitle( i18n( "Local" ) ); mCalendarSyncee = new CalendarSyncee( &mCalendar ); mCalendarSyncee->setTitle( i18n( "Local" ) ); mSyncees.append( mCalendarSyncee ); mSyncees.append( mAddressBookSyncee ); mSyncees.append( new BookmarkSyncee( &mBookmarkManager ) ); mAddressBookResourceFile = new KABC::ResourceFile( mAddressBookFile ); mAddressBook.addResource( mAddressBookResourceFile ); } LocalKonnector::~LocalKonnector() { } void LocalKonnector::writeConfig( KConfig *config ) { Konnector::writeConfig( config ); config->writePathEntry( "CalendarFile", mCalendarFile ); config->writePathEntry( "AddressBookFile", mAddressBookFile ); config->writePathEntry( "BookmarkFile", mAddressBookFile ); } bool LocalKonnector::readSyncees() { kdDebug() << "LocalKonnector::readSyncee()" << endl; mProgressItem = progressItem( i18n( "Start loading local data..." ) ); if ( !mCalendarFile.isEmpty() ) { kdDebug() << "LocalKonnector::readSyncee(): calendar: " << mCalendarFile << endl; mCalendar.close(); mProgressItem->setStatus( i18n( "Load Calendar..." ) ); if ( mCalendar.load( mCalendarFile ) ) { kdDebug() << "Read succeeded." << endl; mCalendarSyncee->reset(); mCalendarSyncee->setIdentifier( mCalendarFile ); kdDebug() << "IDENTIFIER: " << mCalendarSyncee->identifier() << endl; /* apply SyncInformation here this will also create the SyncEntries */ CalendarSyncHistory cHelper( mCalendarSyncee, storagePath() + "/"+mMd5sumCal ); cHelper.load(); mProgressItem->setStatus( i18n( "Calendar loaded." ) ); } else { mProgressItem->setStatus( i18n( "Loading Calendar failed." ) ); emit synceeReadError( this ); kdDebug() << "Read failed." << endl; return false; } } mProgressItem->setProgress( 50 ); if ( !mAddressBookFile.isEmpty() ) { kdDebug() << "LocalKonnector::readSyncee(): addressbook: " << mAddressBookFile << endl; mProgressItem->setStatus( i18n( "Load AddressBook..." ) ); mAddressBookResourceFile->setFileName( mAddressBookFile ); if ( !mAddressBook.load() ) { mProgressItem->setStatus( i18n( "Loading AddressBook failed." ) ); emit synceeReadError( this ); kdDebug() << "Read failed." << endl; return false; } kdDebug() << "Read succeeded." << endl; mAddressBookSyncee->reset(); mAddressBookSyncee->setIdentifier( mAddressBook.identifier() ); kdDebug() << "IDENTIFIER: " << mAddressBookSyncee->identifier() << endl; KABC::AddressBook::Iterator it; for ( it = mAddressBook.begin(); it != mAddressBook.end(); ++it ) { KSync::AddressBookSyncEntry entry( *it, mAddressBookSyncee ); mAddressBookSyncee->addEntry( entry.clone() ); } /* let us apply Sync Information */ AddressBookSyncHistory aHelper( mAddressBookSyncee, storagePath() + "/"+mMd5sumAbk ); aHelper.load(); mProgressItem->setStatus( i18n( "AddressBook loaded." ) ); } // TODO: Read Bookmarks mProgressItem->setProgress( 100 ); mProgressItem->setComplete(); mProgressItem = 0; emit synceesRead( this ); return true; } bool LocalKonnector::connectDevice() { return true; } bool LocalKonnector::disconnectDevice() { return true; } KSync::KonnectorInfo LocalKonnector::info() const { return KonnectorInfo( i18n("Dummy Konnector"), QIconSet(), "agenda", // icon name false ); } QStringList LocalKonnector::supportedFilterTypes() const { QStringList types; types << "addressbook" << "calendar" << "bookmarks"; return types; } bool LocalKonnector::writeSyncees() { if ( !mCalendarFile.isEmpty() ) { purgeRemovedEntries( mCalendarSyncee ); if ( !mCalendar.save( mCalendarFile ) ) return false; CalendarSyncHistory cHelper( mCalendarSyncee, storagePath() + "/"+mMd5sumCal ); cHelper.save(); } if ( !mAddressBookFile.isEmpty() ) { purgeRemovedEntries( mAddressBookSyncee ); KABC::Ticket *ticket; ticket = mAddressBook.requestSaveTicket( mAddressBookResourceFile ); if ( !ticket ) { kdWarning() << "LocalKonnector::writeSyncees(). Couldn't get ticket for " << "addressbook." << endl; emit synceeWriteError( this ); return false; } if ( !mAddressBook.save( ticket ) ) return false; AddressBookSyncHistory aHelper( mAddressBookSyncee, storagePath() + "/"+mMd5sumAbk ); aHelper.save(); } // TODO: Write Bookmarks emit synceesWritten( this ); return true; } #include "localkonnector.moc" <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/tab_contents/tab_contents_view_helper.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/common/view_messages.h" #include "content/port/browser/render_widget_host_view_port.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_view.h" using content::RenderViewHostImpl; using content::RenderWidgetHost; using content::RenderWidgetHostImpl; using content::RenderWidgetHostView; using content::RenderWidgetHostViewPort; using content::WebContents; TabContentsViewHelper::TabContentsViewHelper() { registrar_.Add(this, content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED, content::NotificationService::AllBrowserContextsAndSources()); } TabContentsViewHelper::~TabContentsViewHelper() {} void TabContentsViewHelper::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { DCHECK_EQ(type, content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED); RenderWidgetHost* host = content::Source<RenderWidgetHost>(source).ptr(); for (PendingWidgetViews::iterator i = pending_widget_views_.begin(); i != pending_widget_views_.end(); ++i) { if (host->GetView() == i->second) { pending_widget_views_.erase(i); break; } } } TabContents* TabContentsViewHelper::CreateNewWindow( WebContents* web_contents, int route_id, const ViewHostMsg_CreateWindow_Params& params) { bool should_create = true; if (web_contents->GetDelegate()) { should_create = web_contents->GetDelegate()->ShouldCreateWebContents( web_contents, route_id, params.window_container_type, params.frame_name); } if (!should_create) return NULL; // We usually create the new window in the same BrowsingInstance (group of // script-related windows), by passing in the current SiteInstance. However, // if the opener is being suppressed, we create a new SiteInstance in its own // BrowsingInstance. scoped_refptr<content::SiteInstance> site_instance = params.opener_suppressed ? content::SiteInstance::Create(web_contents->GetBrowserContext()) : web_contents->GetSiteInstance(); // Create the new web contents. This will automatically create the new // WebContentsView. In the future, we may want to create the view separately. TabContents* new_contents = new TabContents(web_contents->GetBrowserContext(), site_instance, route_id, static_cast<TabContents*>(web_contents), NULL); new_contents->set_opener_web_ui_type( web_contents->GetWebUITypeForCurrentState()); new_contents->set_has_opener(!params.opener_url.is_empty()); if (params.opener_suppressed) { // When the opener is suppressed, the original renderer cannot access the // new window. As a result, we need to show and navigate the window here. gfx::Rect initial_pos; web_contents->AddNewContents(new_contents, params.disposition, initial_pos, params.user_gesture); content::OpenURLParams open_params(params.target_url, content::Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_LINK, true /* is_renderer_initiated */); WebContents* opened_contents = new_contents->OpenURL(open_params); DCHECK_EQ(new_contents, opened_contents); return new_contents; } content::WebContentsView* new_view = new_contents->GetView(); // TODO(brettw): It seems bogus that we have to call this function on the // newly created object and give it one of its own member variables. new_view->CreateViewForWidget(new_contents->GetRenderViewHost()); // Save the created window associated with the route so we can show it later. DCHECK_NE(MSG_ROUTING_NONE, route_id); pending_contents_[route_id] = new_contents; if (web_contents->GetDelegate()) web_contents->GetDelegate()->WebContentsCreated(web_contents, params.opener_frame_id, params.target_url, new_contents); return new_contents; } RenderWidgetHostView* TabContentsViewHelper::CreateNewWidget( WebContents* web_contents, int route_id, bool is_fullscreen, WebKit::WebPopupType popup_type) { content::RenderProcessHost* process = web_contents->GetRenderProcessHost(); RenderWidgetHostImpl* widget_host = new RenderWidgetHostImpl(process, route_id); RenderWidgetHostViewPort* widget_view = RenderWidgetHostViewPort::CreateViewForWidget(widget_host); if (!is_fullscreen) { // Popups should not get activated. widget_view->SetPopupType(popup_type); } // Save the created widget associated with the route so we can show it later. pending_widget_views_[route_id] = widget_view; return widget_view; } TabContents* TabContentsViewHelper::GetCreatedWindow(int route_id) { PendingContents::iterator iter = pending_contents_.find(route_id); // Certain systems can block the creation of new windows. If we didn't succeed // in creating one, just return NULL. if (iter == pending_contents_.end()) { return NULL; } TabContents* new_contents = iter->second; pending_contents_.erase(route_id); if (!new_contents->GetRenderProcessHost()->HasConnection() || !new_contents->GetRenderViewHost()->GetView()) return NULL; // TODO(brettw): It seems bogus to reach into here and initialize the host. static_cast<RenderViewHostImpl*>(new_contents->GetRenderViewHost())->Init(); return new_contents; } RenderWidgetHostView* TabContentsViewHelper::GetCreatedWidget(int route_id) { PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id); if (iter == pending_widget_views_.end()) { DCHECK(false); return NULL; } RenderWidgetHostView* widget_host_view = iter->second; pending_widget_views_.erase(route_id); RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost(); if (!widget_host->GetProcess()->HasConnection()) { // The view has gone away or the renderer crashed. Nothing to do. return NULL; } return widget_host_view; } TabContents* TabContentsViewHelper::ShowCreatedWindow( WebContents* web_contents, int route_id, WindowOpenDisposition disposition, const gfx::Rect& initial_pos, bool user_gesture) { TabContents* contents = GetCreatedWindow(route_id); if (contents) { web_contents->AddNewContents(contents, disposition, initial_pos, user_gesture); } return contents; } RenderWidgetHostView* TabContentsViewHelper::ShowCreatedWidget( WebContents* web_contents, int route_id, bool is_fullscreen, const gfx::Rect& initial_pos) { if (web_contents->GetDelegate()) web_contents->GetDelegate()->RenderWidgetShowing(); RenderWidgetHostViewPort* widget_host_view = RenderWidgetHostViewPort::FromRWHV(GetCreatedWidget(route_id)); if (is_fullscreen) { widget_host_view->InitAsFullscreen(web_contents->GetRenderWidgetHostView()); } else { widget_host_view->InitAsPopup(web_contents->GetRenderWidgetHostView(), initial_pos); } RenderWidgetHostImpl::From(widget_host_view->GetRenderWidgetHost())->Init(); return widget_host_view; } <commit_msg>Fix rel=noreferrer popups in Chrome Frame.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/tab_contents/tab_contents_view_helper.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/common/view_messages.h" #include "content/port/browser/render_widget_host_view_port.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_view.h" using content::RenderViewHostImpl; using content::RenderWidgetHost; using content::RenderWidgetHostImpl; using content::RenderWidgetHostView; using content::RenderWidgetHostViewPort; using content::WebContents; TabContentsViewHelper::TabContentsViewHelper() { registrar_.Add(this, content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED, content::NotificationService::AllBrowserContextsAndSources()); } TabContentsViewHelper::~TabContentsViewHelper() {} void TabContentsViewHelper::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { DCHECK_EQ(type, content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED); RenderWidgetHost* host = content::Source<RenderWidgetHost>(source).ptr(); for (PendingWidgetViews::iterator i = pending_widget_views_.begin(); i != pending_widget_views_.end(); ++i) { if (host->GetView() == i->second) { pending_widget_views_.erase(i); break; } } } TabContents* TabContentsViewHelper::CreateNewWindow( WebContents* web_contents, int route_id, const ViewHostMsg_CreateWindow_Params& params) { bool should_create = true; if (web_contents->GetDelegate()) { should_create = web_contents->GetDelegate()->ShouldCreateWebContents( web_contents, route_id, params.window_container_type, params.frame_name); } if (!should_create) return NULL; // We usually create the new window in the same BrowsingInstance (group of // script-related windows), by passing in the current SiteInstance. However, // if the opener is being suppressed, we create a new SiteInstance in its own // BrowsingInstance. scoped_refptr<content::SiteInstance> site_instance = params.opener_suppressed ? content::SiteInstance::Create(web_contents->GetBrowserContext()) : web_contents->GetSiteInstance(); // Create the new web contents. This will automatically create the new // WebContentsView. In the future, we may want to create the view separately. TabContents* new_contents = new TabContents(web_contents->GetBrowserContext(), site_instance, route_id, static_cast<TabContents*>(web_contents), NULL); new_contents->set_opener_web_ui_type( web_contents->GetWebUITypeForCurrentState()); new_contents->set_has_opener(!params.opener_url.is_empty()); if (!params.opener_suppressed) { content::WebContentsView* new_view = new_contents->GetView(); // TODO(brettw): It seems bogus that we have to call this function on the // newly created object and give it one of its own member variables. new_view->CreateViewForWidget(new_contents->GetRenderViewHost()); // Save the created window associated with the route so we can show it // later. DCHECK_NE(MSG_ROUTING_NONE, route_id); pending_contents_[route_id] = new_contents; } if (web_contents->GetDelegate()) web_contents->GetDelegate()->WebContentsCreated(web_contents, params.opener_frame_id, params.target_url, new_contents); if (params.opener_suppressed) { // When the opener is suppressed, the original renderer cannot access the // new window. As a result, we need to show and navigate the window here. gfx::Rect initial_pos; web_contents->AddNewContents(new_contents, params.disposition, initial_pos, params.user_gesture); content::OpenURLParams open_params(params.target_url, content::Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_LINK, true /* is_renderer_initiated */); new_contents->OpenURL(open_params); } return new_contents; } RenderWidgetHostView* TabContentsViewHelper::CreateNewWidget( WebContents* web_contents, int route_id, bool is_fullscreen, WebKit::WebPopupType popup_type) { content::RenderProcessHost* process = web_contents->GetRenderProcessHost(); RenderWidgetHostImpl* widget_host = new RenderWidgetHostImpl(process, route_id); RenderWidgetHostViewPort* widget_view = RenderWidgetHostViewPort::CreateViewForWidget(widget_host); if (!is_fullscreen) { // Popups should not get activated. widget_view->SetPopupType(popup_type); } // Save the created widget associated with the route so we can show it later. pending_widget_views_[route_id] = widget_view; return widget_view; } TabContents* TabContentsViewHelper::GetCreatedWindow(int route_id) { PendingContents::iterator iter = pending_contents_.find(route_id); // Certain systems can block the creation of new windows. If we didn't succeed // in creating one, just return NULL. if (iter == pending_contents_.end()) { return NULL; } TabContents* new_contents = iter->second; pending_contents_.erase(route_id); if (!new_contents->GetRenderProcessHost()->HasConnection() || !new_contents->GetRenderViewHost()->GetView()) return NULL; // TODO(brettw): It seems bogus to reach into here and initialize the host. static_cast<RenderViewHostImpl*>(new_contents->GetRenderViewHost())->Init(); return new_contents; } RenderWidgetHostView* TabContentsViewHelper::GetCreatedWidget(int route_id) { PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id); if (iter == pending_widget_views_.end()) { DCHECK(false); return NULL; } RenderWidgetHostView* widget_host_view = iter->second; pending_widget_views_.erase(route_id); RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost(); if (!widget_host->GetProcess()->HasConnection()) { // The view has gone away or the renderer crashed. Nothing to do. return NULL; } return widget_host_view; } TabContents* TabContentsViewHelper::ShowCreatedWindow( WebContents* web_contents, int route_id, WindowOpenDisposition disposition, const gfx::Rect& initial_pos, bool user_gesture) { TabContents* contents = GetCreatedWindow(route_id); if (contents) { web_contents->AddNewContents(contents, disposition, initial_pos, user_gesture); } return contents; } RenderWidgetHostView* TabContentsViewHelper::ShowCreatedWidget( WebContents* web_contents, int route_id, bool is_fullscreen, const gfx::Rect& initial_pos) { if (web_contents->GetDelegate()) web_contents->GetDelegate()->RenderWidgetShowing(); RenderWidgetHostViewPort* widget_host_view = RenderWidgetHostViewPort::FromRWHV(GetCreatedWidget(route_id)); if (is_fullscreen) { widget_host_view->InitAsFullscreen(web_contents->GetRenderWidgetHostView()); } else { widget_host_view->InitAsPopup(web_contents->GetRenderWidgetHostView(), initial_pos); } RenderWidgetHostImpl::From(widget_host_view->GetRenderWidgetHost())->Init(); return widget_host_view; } <|endoftext|>
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/common/gpu/media/gpu_video_encode_accelerator.h" #include "base/callback.h" #include "base/logging.h" #include "base/memory/shared_memory.h" #include "base/message_loop/message_loop_proxy.h" #include "content/common/gpu/gpu_channel.h" #include "content/common/gpu/gpu_messages.h" #include "ipc/ipc_message_macros.h" #include "media/base/video_frame.h" #if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL) #include "content/common/gpu/media/exynos_video_encode_accelerator.h" #endif namespace content { GpuVideoEncodeAccelerator::GpuVideoEncodeAccelerator(GpuChannel* gpu_channel, int32 route_id) : weak_this_factory_(this), channel_(gpu_channel), route_id_(route_id), input_format_(media::VideoFrame::INVALID), output_buffer_size_(0) {} GpuVideoEncodeAccelerator::~GpuVideoEncodeAccelerator() { if (encoder_) encoder_.release()->Destroy(); } bool GpuVideoEncodeAccelerator::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(GpuVideoEncodeAccelerator, message) IPC_MESSAGE_HANDLER(AcceleratedVideoEncoderMsg_Initialize, OnInitialize) IPC_MESSAGE_HANDLER(AcceleratedVideoEncoderMsg_Encode, OnEncode) IPC_MESSAGE_HANDLER(AcceleratedVideoEncoderMsg_UseOutputBitstreamBuffer, OnUseOutputBitstreamBuffer) IPC_MESSAGE_HANDLER( AcceleratedVideoEncoderMsg_RequestEncodingParametersChange, OnRequestEncodingParametersChange) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void GpuVideoEncodeAccelerator::OnChannelError() { NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError); if (channel_) channel_ = NULL; } void GpuVideoEncodeAccelerator::NotifyInitializeDone() { Send(new AcceleratedVideoEncoderHostMsg_NotifyInitializeDone(route_id_)); } void GpuVideoEncodeAccelerator::RequireBitstreamBuffers( unsigned int input_count, const gfx::Size& input_coded_size, size_t output_buffer_size) { Send(new AcceleratedVideoEncoderHostMsg_RequireBitstreamBuffers( route_id_, input_count, input_coded_size, output_buffer_size)); input_coded_size_ = input_coded_size; output_buffer_size_ = output_buffer_size; } void GpuVideoEncodeAccelerator::BitstreamBufferReady(int32 bitstream_buffer_id, size_t payload_size, bool key_frame) { Send(new AcceleratedVideoEncoderHostMsg_BitstreamBufferReady( route_id_, bitstream_buffer_id, payload_size, key_frame)); } void GpuVideoEncodeAccelerator::NotifyError( media::VideoEncodeAccelerator::Error error) { Send(new AcceleratedVideoEncoderHostMsg_NotifyError(route_id_, error)); } // static std::vector<media::VideoEncodeAccelerator::SupportedProfile> GpuVideoEncodeAccelerator::GetSupportedProfiles() { std::vector<media::VideoEncodeAccelerator::SupportedProfile> profiles; #if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL) profiles = ExynosVideoEncodeAccelerator::GetSupportedProfiles(); #endif // TODO(sheu): return platform-specific profiles. return profiles; } void GpuVideoEncodeAccelerator::CreateEncoder() { #if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL) encoder_.reset(new ExynosVideoEncodeAccelerator(this)); #endif } void GpuVideoEncodeAccelerator::OnInitialize( media::VideoFrame::Format input_format, const gfx::Size& input_visible_size, media::VideoCodecProfile output_profile, uint32 initial_bitrate) { DVLOG(2) << "GpuVideoEncodeAccelerator::OnInitialize(): " "input_format=" << input_format << ", input_visible_size=" << input_visible_size.ToString() << ", output_profile=" << output_profile << ", initial_bitrate=" << initial_bitrate; DCHECK(!encoder_); if (input_visible_size.width() > kint32max / input_visible_size.height()) { DLOG(ERROR) << "GpuVideoEncodeAccelerator::OnInitialize(): " "input_visible_size too large"; NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError); return; } CreateEncoder(); if (!encoder_) { DLOG(ERROR) << "GpuVideoEncodeAccelerator::OnInitialize(): VEA creation " "failed"; NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError); return; } encoder_->Initialize( input_format, input_visible_size, output_profile, initial_bitrate); input_format_ = input_format; input_visible_size_ = input_visible_size; } void GpuVideoEncodeAccelerator::OnEncode(int32 frame_id, base::SharedMemoryHandle buffer_handle, uint32 buffer_size, bool force_keyframe) { DVLOG(3) << "GpuVideoEncodeAccelerator::OnEncode(): frame_id=" << frame_id << ", buffer_size=" << buffer_size << ", force_keyframe=" << force_keyframe; if (!encoder_) return; if (frame_id < 0) { DLOG(ERROR) << "GpuVideoEncodeAccelerator::OnEncode(): invalid frame_id=" << frame_id; NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError); return; } scoped_ptr<base::SharedMemory> shm( new base::SharedMemory(buffer_handle, true)); if (!shm->Map(buffer_size)) { DLOG(ERROR) << "GpuVideoEncodeAccelerator::OnEncode(): " "could not map frame_id=" << frame_id; NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError); return; } scoped_refptr<media::VideoFrame> frame = media::VideoFrame::WrapExternalSharedMemory( input_format_, input_coded_size_, gfx::Rect(input_visible_size_), input_visible_size_, reinterpret_cast<uint8*>(shm->memory()), buffer_handle, base::TimeDelta(), // It's turtles all the way down... base::Bind(base::IgnoreResult(&base::MessageLoopProxy::PostTask), base::MessageLoopProxy::current(), FROM_HERE, base::Bind(&GpuVideoEncodeAccelerator::EncodeFrameFinished, weak_this_factory_.GetWeakPtr(), frame_id, base::Passed(&shm)))); if (!frame) { DLOG(ERROR) << "GpuVideoEncodeAccelerator::OnEncode(): " "could not create VideoFrame for frame_id=" << frame_id; NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError); return; } encoder_->Encode(frame, force_keyframe); } void GpuVideoEncodeAccelerator::OnUseOutputBitstreamBuffer( int32 buffer_id, base::SharedMemoryHandle buffer_handle, uint32 buffer_size) { DVLOG(3) << "GpuVideoEncodeAccelerator::OnUseOutputBitstreamBuffer(): " "buffer_id=" << buffer_id << ", buffer_size=" << buffer_size; if (!encoder_) return; if (buffer_id < 0) { DLOG(ERROR) << "GpuVideoEncodeAccelerator::OnUseOutputBitstreamBuffer(): " "invalid buffer_id=" << buffer_id; NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError); return; } if (buffer_size < output_buffer_size_) { DLOG(ERROR) << "GpuVideoEncodeAccelerator::OnUseOutputBitstreamBuffer(): " "buffer too small for buffer_id=" << buffer_id; NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError); return; } encoder_->UseOutputBitstreamBuffer( media::BitstreamBuffer(buffer_id, buffer_handle, buffer_size)); } void GpuVideoEncodeAccelerator::OnRequestEncodingParametersChange( uint32 bitrate, uint32 framerate) { DVLOG(2) << "GpuVideoEncodeAccelerator::OnRequestEncodingParametersChange(): " "bitrate=" << bitrate << ", framerate=" << framerate; if (!encoder_) return; encoder_->RequestEncodingParametersChange(bitrate, framerate); } void GpuVideoEncodeAccelerator::EncodeFrameFinished( int32 frame_id, scoped_ptr<base::SharedMemory> shm) { Send(new AcceleratedVideoEncoderHostMsg_NotifyInputDone(route_id_, frame_id)); // Just let shm fall out of scope. } void GpuVideoEncodeAccelerator::Send(IPC::Message* message) { if (!channel_) { DLOG(ERROR) << "GpuVideoEncodeAccelerator::Send(): no channel"; delete message; return; } else if (!channel_->Send(message)) { DLOG(ERROR) << "GpuVideoEncodeAccelerator::Send(): sending failed: " "message->type()=" << message->type(); NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError); return; } } } // namespace content <commit_msg>gyp conditions should match #if conditions in gpu_video_encode_accelerator.cc<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/common/gpu/media/gpu_video_encode_accelerator.h" #include "base/callback.h" #include "base/logging.h" #include "base/memory/shared_memory.h" #include "base/message_loop/message_loop_proxy.h" #include "build/build_config.h" #include "content/common/gpu/gpu_channel.h" #include "content/common/gpu/gpu_messages.h" #include "ipc/ipc_message_macros.h" #include "media/base/video_frame.h" #if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL) && defined(USE_X11) #include "content/common/gpu/media/exynos_video_encode_accelerator.h" #endif namespace content { GpuVideoEncodeAccelerator::GpuVideoEncodeAccelerator(GpuChannel* gpu_channel, int32 route_id) : weak_this_factory_(this), channel_(gpu_channel), route_id_(route_id), input_format_(media::VideoFrame::INVALID), output_buffer_size_(0) {} GpuVideoEncodeAccelerator::~GpuVideoEncodeAccelerator() { if (encoder_) encoder_.release()->Destroy(); } bool GpuVideoEncodeAccelerator::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(GpuVideoEncodeAccelerator, message) IPC_MESSAGE_HANDLER(AcceleratedVideoEncoderMsg_Initialize, OnInitialize) IPC_MESSAGE_HANDLER(AcceleratedVideoEncoderMsg_Encode, OnEncode) IPC_MESSAGE_HANDLER(AcceleratedVideoEncoderMsg_UseOutputBitstreamBuffer, OnUseOutputBitstreamBuffer) IPC_MESSAGE_HANDLER( AcceleratedVideoEncoderMsg_RequestEncodingParametersChange, OnRequestEncodingParametersChange) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void GpuVideoEncodeAccelerator::OnChannelError() { NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError); if (channel_) channel_ = NULL; } void GpuVideoEncodeAccelerator::NotifyInitializeDone() { Send(new AcceleratedVideoEncoderHostMsg_NotifyInitializeDone(route_id_)); } void GpuVideoEncodeAccelerator::RequireBitstreamBuffers( unsigned int input_count, const gfx::Size& input_coded_size, size_t output_buffer_size) { Send(new AcceleratedVideoEncoderHostMsg_RequireBitstreamBuffers( route_id_, input_count, input_coded_size, output_buffer_size)); input_coded_size_ = input_coded_size; output_buffer_size_ = output_buffer_size; } void GpuVideoEncodeAccelerator::BitstreamBufferReady(int32 bitstream_buffer_id, size_t payload_size, bool key_frame) { Send(new AcceleratedVideoEncoderHostMsg_BitstreamBufferReady( route_id_, bitstream_buffer_id, payload_size, key_frame)); } void GpuVideoEncodeAccelerator::NotifyError( media::VideoEncodeAccelerator::Error error) { Send(new AcceleratedVideoEncoderHostMsg_NotifyError(route_id_, error)); } // static std::vector<media::VideoEncodeAccelerator::SupportedProfile> GpuVideoEncodeAccelerator::GetSupportedProfiles() { std::vector<media::VideoEncodeAccelerator::SupportedProfile> profiles; #if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL) && defined(USE_X11) profiles = ExynosVideoEncodeAccelerator::GetSupportedProfiles(); #endif // TODO(sheu): return platform-specific profiles. return profiles; } void GpuVideoEncodeAccelerator::CreateEncoder() { #if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL) && defined(USE_X11) encoder_.reset(new ExynosVideoEncodeAccelerator(this)); #endif } void GpuVideoEncodeAccelerator::OnInitialize( media::VideoFrame::Format input_format, const gfx::Size& input_visible_size, media::VideoCodecProfile output_profile, uint32 initial_bitrate) { DVLOG(2) << "GpuVideoEncodeAccelerator::OnInitialize(): " "input_format=" << input_format << ", input_visible_size=" << input_visible_size.ToString() << ", output_profile=" << output_profile << ", initial_bitrate=" << initial_bitrate; DCHECK(!encoder_); if (input_visible_size.width() > kint32max / input_visible_size.height()) { DLOG(ERROR) << "GpuVideoEncodeAccelerator::OnInitialize(): " "input_visible_size too large"; NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError); return; } CreateEncoder(); if (!encoder_) { DLOG(ERROR) << "GpuVideoEncodeAccelerator::OnInitialize(): VEA creation " "failed"; NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError); return; } encoder_->Initialize( input_format, input_visible_size, output_profile, initial_bitrate); input_format_ = input_format; input_visible_size_ = input_visible_size; } void GpuVideoEncodeAccelerator::OnEncode(int32 frame_id, base::SharedMemoryHandle buffer_handle, uint32 buffer_size, bool force_keyframe) { DVLOG(3) << "GpuVideoEncodeAccelerator::OnEncode(): frame_id=" << frame_id << ", buffer_size=" << buffer_size << ", force_keyframe=" << force_keyframe; if (!encoder_) return; if (frame_id < 0) { DLOG(ERROR) << "GpuVideoEncodeAccelerator::OnEncode(): invalid frame_id=" << frame_id; NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError); return; } scoped_ptr<base::SharedMemory> shm( new base::SharedMemory(buffer_handle, true)); if (!shm->Map(buffer_size)) { DLOG(ERROR) << "GpuVideoEncodeAccelerator::OnEncode(): " "could not map frame_id=" << frame_id; NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError); return; } scoped_refptr<media::VideoFrame> frame = media::VideoFrame::WrapExternalSharedMemory( input_format_, input_coded_size_, gfx::Rect(input_visible_size_), input_visible_size_, reinterpret_cast<uint8*>(shm->memory()), buffer_handle, base::TimeDelta(), // It's turtles all the way down... base::Bind(base::IgnoreResult(&base::MessageLoopProxy::PostTask), base::MessageLoopProxy::current(), FROM_HERE, base::Bind(&GpuVideoEncodeAccelerator::EncodeFrameFinished, weak_this_factory_.GetWeakPtr(), frame_id, base::Passed(&shm)))); if (!frame) { DLOG(ERROR) << "GpuVideoEncodeAccelerator::OnEncode(): " "could not create VideoFrame for frame_id=" << frame_id; NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError); return; } encoder_->Encode(frame, force_keyframe); } void GpuVideoEncodeAccelerator::OnUseOutputBitstreamBuffer( int32 buffer_id, base::SharedMemoryHandle buffer_handle, uint32 buffer_size) { DVLOG(3) << "GpuVideoEncodeAccelerator::OnUseOutputBitstreamBuffer(): " "buffer_id=" << buffer_id << ", buffer_size=" << buffer_size; if (!encoder_) return; if (buffer_id < 0) { DLOG(ERROR) << "GpuVideoEncodeAccelerator::OnUseOutputBitstreamBuffer(): " "invalid buffer_id=" << buffer_id; NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError); return; } if (buffer_size < output_buffer_size_) { DLOG(ERROR) << "GpuVideoEncodeAccelerator::OnUseOutputBitstreamBuffer(): " "buffer too small for buffer_id=" << buffer_id; NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError); return; } encoder_->UseOutputBitstreamBuffer( media::BitstreamBuffer(buffer_id, buffer_handle, buffer_size)); } void GpuVideoEncodeAccelerator::OnRequestEncodingParametersChange( uint32 bitrate, uint32 framerate) { DVLOG(2) << "GpuVideoEncodeAccelerator::OnRequestEncodingParametersChange(): " "bitrate=" << bitrate << ", framerate=" << framerate; if (!encoder_) return; encoder_->RequestEncodingParametersChange(bitrate, framerate); } void GpuVideoEncodeAccelerator::EncodeFrameFinished( int32 frame_id, scoped_ptr<base::SharedMemory> shm) { Send(new AcceleratedVideoEncoderHostMsg_NotifyInputDone(route_id_, frame_id)); // Just let shm fall out of scope. } void GpuVideoEncodeAccelerator::Send(IPC::Message* message) { if (!channel_) { DLOG(ERROR) << "GpuVideoEncodeAccelerator::Send(): no channel"; delete message; return; } else if (!channel_->Send(message)) { DLOG(ERROR) << "GpuVideoEncodeAccelerator::Send(): sending failed: " "message->type()=" << message->type(); NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError); return; } } } // namespace content <|endoftext|>
<commit_before>#include <lcaes.h> #include <lcencode.h> #include <limecrypt.h> #include <sstream> #include <iostream> class Print { public: Print() : os(std::cout) {} template<typename T> Print(const T& input) : os(std::cout) { os << input; } ~Print() { os << std::endl; } template<typename T> std::ostream& operator<<(const T& input) { return std::cout << input; } private: std::ostream& os; }; using namespace LimeCrypt; // AES Examples static std::string aes_encrypt_string(const std::string& message, const std::string& passphrase) { std::stringstream in(message), out; Print("Original Message (") << message.size() << " bytes): " << message; AES::encrypt(passphrase, in, out); Print("Encrypted Message - Hex format (") << out.str().size() << " bytes): " << Hex::encode(out.str()); return out.str(); } static std::string aes_decrypt_string(const std::string& encrypted, const std::string& passphrase) { std::stringstream in(encrypted), out; AES::decrypt(passphrase, in, out); Print("Decrypted Message (") << out.str().size() << " bytes): " << out.str(); return out.str(); } int main(int argc, char** argv) { errorHandling(STDERR_OUT); const std::string message("This is a totally secret message. No one should see it."); const std::string passphrase("t0t@lly_sEcure-Pa55W0rD_;)"); Print("--- AES String Encryption/Decryption Example ---"); std::string encrypted = aes_encrypt_string(message, passphrase); std::string decrypted = aes_decrypt_string(encrypted, passphrase); return 0; } <commit_msg>Add AES file encryption example via encryptFile and decryptFile methods.<commit_after>#include <lcaes.h> #include <lcencode.h> #include <limecrypt.h> #include <sstream> #include <iostream> #include <fstream> class Print { public: Print() : os(std::cout) {} template<typename T> Print(const T& input) : os(std::cout) { os << input; } ~Print() { os << std::endl; } template<typename T> std::ostream& operator<<(const T& input) { return std::cout << input; } private: std::ostream& os; }; using namespace LimeCrypt; // AES Examples static std::string aes_encrypt_string(const std::string& message, const std::string& passphrase) { std::stringstream in(message), out; Print("Original Message (") << message.size() << " bytes): " << message; AES::encrypt(passphrase, in, out); Print("Encrypted Message - Hex format (") << out.str().size() << " bytes): " << Hex::encode(out.str()); return out.str(); } static std::string aes_decrypt_string(const std::string& encrypted, const std::string& passphrase) { std::stringstream in(encrypted), out; AES::decrypt(passphrase, in, out); Print("Decrypted Message (") << out.str().size() << " bytes): " << out.str(); return out.str(); } static std::string aes_encrypt_file(const std::string& filename, const std::string& passphrase) { // For this example we will first create a file Print("Writing file with secret content: ") << filename; std::ofstream of(filename.c_str()); of << "This is a secret file content. Nobody should see it." << std::endl; std::string encrypted_filename(filename + ".enc"); Print("Encrypt '") << filename << "' to '" << encrypted_filename << "'"; AES::encryptFile(passphrase, filename, encrypted_filename); return encrypted_filename; } static void aes_decrypt_file(const std::string& filename, const std::string& passphrase) { Print("Decrypt '") << filename << "' to '" << filename + ".decrypted" << "'"; AES::decryptFile(passphrase, filename, filename + ".decrypted"); } int main(int argc, char** argv) { errorHandling(STDERR_OUT); const std::string message("This is a totally secret message. No one should see it."); const std::string passphrase("t0t@lly_sEcure-Pa55W0rD_;)"); Print("--- AES String Encryption/Decryption Example ---"); std::string encrypted = aes_encrypt_string(message, passphrase); std::string decrypted = aes_decrypt_string(encrypted, passphrase); Print("--- AES File Encryption/Decryption Example ---"); std::string encrypted_filename = aes_encrypt_file("SecretFile", passphrase); aes_decrypt_file(encrypted_filename, passphrase); return 0; } <|endoftext|>
<commit_before>// Copyright 2018 Netherlands Institute for Radio Astronomy (ASTRON) // Copyright 2018 Netherlands eScience Center // // 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 <Memory.hpp> void loadInput(AstroData::Observation & observation, const DeviceOptions & deviceOptions, const DataOptions & dataOptions, HostMemory & hostMemory, Timers & timers) { hostMemory.zappedChannels.resize(observation.getNrChannels(deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(unsigned int))); try { AstroData::readZappedChannels(observation, dataOptions.channelsFile, hostMemory.zappedChannels); AstroData::readIntegrationSteps(observation, dataOptions.integrationFile, hostMemory.integrationSteps); } catch ( AstroData::FileError & err ) { std::cerr << err.what() << std::endl; throw; } hostMemory.input.resize(observation.getNrBeams()); if ( dataOptions.dataLOFAR ) { #ifdef HAVE_HDF5 hostMemory.input.at(0) = new std::vector<std::vector<inputDataType> *>(observation.getNrBatches()); timers.inputLoad.start(); if ( dataOptions.limit ) { AstroData::readLOFAR(dataOptions.headerFile, dataOptions.dataFile, observation, deviceOptions.padding.at(deviceOptions.deviceName), *(hostMemory.input.at(0)), observation.getNrBatches()); } else { AstroData::readLOFAR(dataOptions.headerFile, dataOptions.dataFile, observation, deviceOptions.padding.at(deviceOptions.deviceName), *(hostMemory.input.at(0))); } timers.inputLoad.stop(); #endif // HAVE_HDF5 } else if ( dataOptions.dataSIGPROC ) { hostMemory.input.at(0) = new std::vector<std::vector<inputDataType> *>(observation.getNrBatches()); timers.inputLoad.start(); AstroData::readSIGPROC(observation, deviceOptions.padding.at(deviceOptions.deviceName), inputBits, dataOptions.headerSizeSIGPROC, dataOptions.dataFile, *(hostMemory.input.at(0))); timers.inputLoad.stop(); } else if ( dataOptions.dataPSRDADA ) { #ifdef HAVE_PSRDADA hostMemory.ringBuffer = dada_hdu_create(0); dada_hdu_set_key(hostMemory.ringBuffer, dataOptions.dadaKey); if ( dada_hdu_connect(hostMemory.ringBuffer) != 0 ) { throw AstroData::RingBufferError("ERROR: impossible to connect to PSRDADA ringbuffer \"" + std::to_string(dataOptions.dadaKey) + "\"."); } if ( dada_hdu_lock_read(hostMemory.ringBuffer) != 0 ) { throw AstroData::RingBufferError("ERROR: impossible to lock the PSRDADA ringbuffer for reading the header."); } timers.inputLoad.start(); AstroData::readPSRDADAHeader(observation, *hostMemory.ringBuffer); timers.inputLoad.stop(); #endif // HAVE_PSRDADA } } void allocateHostMemory(AstroData::Observation & observation, const Options & options, const DeviceOptions & deviceOptions, const KernelConfigurations & kernelConfigurations, HostMemory & hostMemory) { if ( !options.subbandDedispersion ) { hostMemory.shiftsSingleStep = Dedispersion::getShifts(observation, deviceOptions.padding.at(deviceOptions.deviceName)); if ( options.debug ) { std::cerr << "shiftsSingleStep" << std::endl; for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) { std::cerr << hostMemory.shiftsSingleStep->at(channel) << " "; } std::cerr << std::endl << std::endl; } observation.setNrSamplesPerDispersedBatch(observation.getNrSamplesPerBatch() + static_cast<unsigned int>(hostMemory.shiftsSingleStep->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep())))); observation.setNrDelayBatches(static_cast<unsigned int>(std::ceil(static_cast<double>(observation.getNrSamplesPerDispersedBatch()) / observation.getNrSamplesPerBatch()))); #ifdef HAVE_PSRDADA if ( dataOptions.dataPSRDADA ) { hostMemory.inputDADA.resize(observation.getNrDelayBatches()); for ( unsigned int batch = 0; batch < observation.getNrDelayBatches(); batch++ ) { if ( inputBits >= 8 ) { hostMemory.inputDADA.at(batch) = new std::vector<inputDataType>(observation.getNrBeams() * observation.getNrChannels() * observation.getNrSamplesPerBatch()); } else { hostMemory.inputDADA.at(batch) = new std::vector<inputDataType>(observation.getNrBeams() * observation.getNrChannels() * (observation.getNrSamplesPerBatch() / (8 / inputBits))); } } } #endif // HAVE_PSRDADA if ( kernelConfigurations.dedispersionSingleStepParameters.at(deviceOptions.deviceName)->at(observation.getNrDMs())->getSplitBatches() ) { // TODO: add support for splitBatches } else { if ( inputBits >= 8 ) { hostMemory.dispersedData.resize(observation.getNrBeams() * observation.getNrChannels() * observation.getNrSamplesPerDispersedBatch(false, deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(inputDataType))); } else { hostMemory.dispersedData.resize(observation.getNrBeams() * observation.getNrChannels() * isa::utils::pad(observation.getNrSamplesPerDispersedBatch() / (8 / inputBits), deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(inputDataType))); } } hostMemory.beamMapping.resize(observation.getNrSynthesizedBeams() * observation.getNrChannels(deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(unsigned int))); hostMemory.dedispersedData.resize(observation.getNrSynthesizedBeams() * observation.getNrDMs() * observation.getNrSamplesPerBatch(false, deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(outputDataType))); hostMemory.integratedData.resize(observation.getNrSynthesizedBeams() * observation.getNrDMs() * isa::utils::pad(observation.getNrSamplesPerBatch() / *(hostMemory.integrationSteps.begin()), deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(outputDataType))); hostMemory.snrData.resize(observation.getNrSynthesizedBeams() * observation.getNrDMs(false, deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(float))); hostMemory.snrSamples.resize(observation.getNrSynthesizedBeams() * observation.getNrDMs(false, deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(unsigned int))); } else { hostMemory.shiftsStepOne = Dedispersion::getShifts(observation, deviceOptions.padding.at(deviceOptions.deviceName)); hostMemory.shiftsStepTwo = Dedispersion::getShiftsStepTwo(observation, deviceOptions.padding.at(deviceOptions.deviceName)); if ( options.debug ) { std::cerr << "shiftsStepOne" << std::endl; for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) { std::cerr << hostMemory.shiftsStepOne->at(channel) << " "; } std::cerr << std::endl << "shiftsStepTwo" << std::endl; for ( unsigned int subband = 0; subband < observation.getNrSubbands(); subband++ ) { std::cerr << hostMemory.shiftsStepTwo->at(subband) << " "; } std::cerr << std::endl << std::endl; } observation.setNrSamplesPerBatch(observation.getNrSamplesPerBatch() + static_cast<unsigned int>(hostMemory.shiftsStepTwo->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()))), true); observation.setNrSamplesPerDispersedBatch(observation.getNrSamplesPerBatch(true) + static_cast<unsigned int>(hostMemory.shiftsStepOne->at(0) * (observation.getFirstDM(true) + ((observation.getNrDMs(true) - 1) * observation.getDMStep(true)))), true); observation.setNrDelayBatches(static_cast<unsigned int>(std::ceil(static_cast<double>(observation.getNrSamplesPerDispersedBatch(true)) / observation.getNrSamplesPerBatch())), true); #ifdef HAVE_PSRDADA if ( dataOptions.dataPSRDADA ) { hostMemory.inputDADA.resize(observation.getNrDelayBatches(true)); for ( unsigned int batch = 0; batch < observation.getNrDelayBatches(true); batch++ ) { if ( inputBits >= 8 ) { hostMemory.inputDADA.at(batch) = new std::vector<inputDataType>(observation.getNrBeams() * observation.getNrChannels() * observation.getNrSamplesPerBatch()); } else { hostMemory.inputDADA.at(batch) = new std::vector<inputDataType>(observation.getNrBeams() * observation.getNrChannels() * (observation.getNrSamplesPerBatch() / (8 / inputBits))); } } } #endif // HAVE_PSRDADA if ( kernelConfigurations.dedispersionStepOneParameters.at(deviceOptions.deviceName)->at(observation.getNrDMs(true))->getSplitBatches() ) { // TODO: add support for splitBatches } else { if ( inputBits >= 8 ) { hostMemory.dispersedData.resize(observation.getNrBeams() * observation.getNrChannels() * observation.getNrSamplesPerDispersedBatch(true, deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(inputDataType))); } else { hostMemory.dispersedData.resize(observation.getNrBeams() * observation.getNrChannels() * isa::utils::pad(observation.getNrSamplesPerDispersedBatch(true) / (8 / inputBits), deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(inputDataType))); } } hostMemory.beamMapping.resize(observation.getNrSynthesizedBeams() * observation.getNrSubbands(deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(unsigned int))); hostMemory.subbandedData.resize(observation.getNrBeams() * observation.getNrDMs(true) * observation.getNrSubbands() * observation.getNrSamplesPerBatch(true, deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(outputDataType))); hostMemory.dedispersedData.resize(observation.getNrSynthesizedBeams() * observation.getNrDMs(true) * observation.getNrDMs() * observation.getNrSamplesPerBatch(false, deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(outputDataType))); hostMemory.integratedData.resize(observation.getNrSynthesizedBeams() * observation.getNrDMs(true) * observation.getNrDMs() * isa::utils::pad(observation.getNrSamplesPerBatch() / *(hostMemory.integrationSteps.begin()), deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(outputDataType))); hostMemory.snrData.resize(observation.getNrSynthesizedBeams() * isa::utils::pad(observation.getNrDMs(true) * observation.getNrDMs(), deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(float))); hostMemory.snrSamples.resize(observation.getNrSynthesizedBeams() * isa::utils::pad(observation.getNrDMs(true) * observation.getNrDMs(), deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(unsigned int))); } AstroData::generateBeamMapping(observation, hostMemory.beamMapping, deviceOptions.padding.at(deviceOptions.deviceName), options.subbandDedispersion); } void allocateDeviceMemory(const OpenCLRunTime & openclRunTime, const Options & options, const DeviceOptions & deviceOptions, const HostMemory & hostMemory, DeviceMemory & deviceMemory) { if ( !options.subbandDedispersion ) { deviceMemory.shiftsSingleStep = cl::Buffer(*openclRunTime.context, CL_MEM_READ_ONLY, hostMemory.shiftsSingleStep->size() * sizeof(float), 0, 0); openclRunTime.queues->at(deviceOptions.deviceID).at(0).enqueueWriteBuffer(deviceMemory.shiftsSingleStep, CL_FALSE, 0, hostMemory.shiftsSingleStep->size() * sizeof(float), reinterpret_cast<void *>(hostMemory.shiftsSingleStep->data())); } else { deviceMemory.shiftsStepOne = cl::Buffer(*openclRunTime.context, CL_MEM_READ_ONLY, hostMemory.shiftsStepOne->size() * sizeof(float), 0, 0); openclRunTime.queues->at(deviceOptions.deviceID).at(0).enqueueWriteBuffer(deviceMemory.shiftsStepOne, CL_FALSE, 0, hostMemory.shiftsStepOne->size() * sizeof(float), reinterpret_cast<void *>(hostMemory.shiftsStepOne->data())); deviceMemory.shiftsStepTwo = cl::Buffer(*openclRunTime.context, CL_MEM_READ_ONLY, hostMemory.shiftsStepTwo->size() * sizeof(float), 0, 0); openclRunTime.queues->at(deviceOptions.deviceID).at(0).enqueueWriteBuffer(deviceMemory.shiftsStepTwo, CL_FALSE, 0, hostMemory.shiftsStepTwo->size() * sizeof(float), reinterpret_cast<void *>(hostMemory.shiftsStepTwo->data())); deviceMemory.subbandedData = cl::Buffer(*openclRunTime.context, CL_MEM_READ_WRITE, hostMemory.subbandedData.size() * sizeof(outputDataType), 0, 0); } deviceMemory.zappedChannels = cl::Buffer(*openclRunTime.context, CL_MEM_READ_ONLY, hostMemory.zappedChannels.size() * sizeof(unsigned int), 0, 0); openclRunTime.queues->at(deviceOptions.deviceID).at(0).enqueueWriteBuffer(deviceMemory.zappedChannels, CL_FALSE, 0, hostMemory.zappedChannels.size() * sizeof(unsigned int), reinterpret_cast<const void *>(hostMemory.zappedChannels.data())); deviceMemory.beamMapping = cl::Buffer(*openclRunTime.context, CL_MEM_READ_ONLY, hostMemory.beamMapping.size() * sizeof(unsigned int), 0, 0); openclRunTime.queues->at(deviceOptions.deviceID).at(0).enqueueWriteBuffer(deviceMemory.beamMapping, CL_FALSE, 0, hostMemory.beamMapping.size() * sizeof(unsigned int), reinterpret_cast<const void *>(hostMemory.beamMapping.data())); deviceMemory.dispersedData = cl::Buffer(*openclRunTime.context, CL_MEM_READ_ONLY, hostMemory.dispersedData.size() * sizeof(inputDataType), 0, 0); deviceMemory.dedispersedData = cl::Buffer(*openclRunTime.context, CL_MEM_READ_WRITE, hostMemory.dedispersedData.size() * sizeof(outputDataType), 0, 0); deviceMemory.integratedData = cl::Buffer(*openclRunTime.context, CL_MEM_READ_WRITE, hostMemory.integratedData.size() * sizeof(outputDataType), 0, 0); deviceMemory.snrData = cl::Buffer(*openclRunTime.context, CL_MEM_WRITE_ONLY, hostMemory.snrData.size() * sizeof(float), 0, 0); deviceMemory.snrSamples = cl::Buffer(*openclRunTime.context, CL_MEM_WRITE_ONLY, hostMemory.snrSamples.size() * sizeof(unsigned int), 0, 0); openclRunTime.queues->at(deviceOptions.deviceID).at(0).finish(); } <commit_msg>Extracted some preliminary operations that are necessary for loading and generating.<commit_after>// Copyright 2018 Netherlands Institute for Radio Astronomy (ASTRON) // Copyright 2018 Netherlands eScience Center // // 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 <Memory.hpp> void loadInput(AstroData::Observation & observation, const DeviceOptions & deviceOptions, const DataOptions & dataOptions, HostMemory & hostMemory, Timers & timers) { if ( dataOptions.dataLOFAR ) { #ifdef HAVE_HDF5 hostMemory.input.at(0) = new std::vector<std::vector<inputDataType> *>(observation.getNrBatches()); timers.inputLoad.start(); if ( dataOptions.limit ) { AstroData::readLOFAR(dataOptions.headerFile, dataOptions.dataFile, observation, deviceOptions.padding.at(deviceOptions.deviceName), *(hostMemory.input.at(0)), observation.getNrBatches()); } else { AstroData::readLOFAR(dataOptions.headerFile, dataOptions.dataFile, observation, deviceOptions.padding.at(deviceOptions.deviceName), *(hostMemory.input.at(0))); } timers.inputLoad.stop(); #endif // HAVE_HDF5 } else if ( dataOptions.dataSIGPROC ) { hostMemory.input.at(0) = new std::vector<std::vector<inputDataType> *>(observation.getNrBatches()); timers.inputLoad.start(); AstroData::readSIGPROC(observation, deviceOptions.padding.at(deviceOptions.deviceName), inputBits, dataOptions.headerSizeSIGPROC, dataOptions.dataFile, *(hostMemory.input.at(0))); timers.inputLoad.stop(); } else if ( dataOptions.dataPSRDADA ) { #ifdef HAVE_PSRDADA hostMemory.ringBuffer = dada_hdu_create(0); dada_hdu_set_key(hostMemory.ringBuffer, dataOptions.dadaKey); if ( dada_hdu_connect(hostMemory.ringBuffer) != 0 ) { throw AstroData::RingBufferError("ERROR: impossible to connect to PSRDADA ringbuffer \"" + std::to_string(dataOptions.dadaKey) + "\"."); } if ( dada_hdu_lock_read(hostMemory.ringBuffer) != 0 ) { throw AstroData::RingBufferError("ERROR: impossible to lock the PSRDADA ringbuffer for reading the header."); } timers.inputLoad.start(); AstroData::readPSRDADAHeader(observation, *hostMemory.ringBuffer); timers.inputLoad.stop(); #endif // HAVE_PSRDADA } } void allocateHostMemory(AstroData::Observation & observation, const Options & options, const DeviceOptions & deviceOptions, const KernelConfigurations & kernelConfigurations, HostMemory & hostMemory) { if ( !options.subbandDedispersion ) { hostMemory.shiftsSingleStep = Dedispersion::getShifts(observation, deviceOptions.padding.at(deviceOptions.deviceName)); if ( options.debug ) { std::cerr << "shiftsSingleStep" << std::endl; for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) { std::cerr << hostMemory.shiftsSingleStep->at(channel) << " "; } std::cerr << std::endl << std::endl; } observation.setNrSamplesPerDispersedBatch(observation.getNrSamplesPerBatch() + static_cast<unsigned int>(hostMemory.shiftsSingleStep->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep())))); observation.setNrDelayBatches(static_cast<unsigned int>(std::ceil(static_cast<double>(observation.getNrSamplesPerDispersedBatch()) / observation.getNrSamplesPerBatch()))); #ifdef HAVE_PSRDADA if ( dataOptions.dataPSRDADA ) { hostMemory.inputDADA.resize(observation.getNrDelayBatches()); for ( unsigned int batch = 0; batch < observation.getNrDelayBatches(); batch++ ) { if ( inputBits >= 8 ) { hostMemory.inputDADA.at(batch) = new std::vector<inputDataType>(observation.getNrBeams() * observation.getNrChannels() * observation.getNrSamplesPerBatch()); } else { hostMemory.inputDADA.at(batch) = new std::vector<inputDataType>(observation.getNrBeams() * observation.getNrChannels() * (observation.getNrSamplesPerBatch() / (8 / inputBits))); } } } #endif // HAVE_PSRDADA if ( kernelConfigurations.dedispersionSingleStepParameters.at(deviceOptions.deviceName)->at(observation.getNrDMs())->getSplitBatches() ) { // TODO: add support for splitBatches } else { if ( inputBits >= 8 ) { hostMemory.dispersedData.resize(observation.getNrBeams() * observation.getNrChannels() * observation.getNrSamplesPerDispersedBatch(false, deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(inputDataType))); } else { hostMemory.dispersedData.resize(observation.getNrBeams() * observation.getNrChannels() * isa::utils::pad(observation.getNrSamplesPerDispersedBatch() / (8 / inputBits), deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(inputDataType))); } } hostMemory.beamMapping.resize(observation.getNrSynthesizedBeams() * observation.getNrChannels(deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(unsigned int))); hostMemory.dedispersedData.resize(observation.getNrSynthesizedBeams() * observation.getNrDMs() * observation.getNrSamplesPerBatch(false, deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(outputDataType))); hostMemory.integratedData.resize(observation.getNrSynthesizedBeams() * observation.getNrDMs() * isa::utils::pad(observation.getNrSamplesPerBatch() / *(hostMemory.integrationSteps.begin()), deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(outputDataType))); hostMemory.snrData.resize(observation.getNrSynthesizedBeams() * observation.getNrDMs(false, deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(float))); hostMemory.snrSamples.resize(observation.getNrSynthesizedBeams() * observation.getNrDMs(false, deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(unsigned int))); } else { hostMemory.shiftsStepOne = Dedispersion::getShifts(observation, deviceOptions.padding.at(deviceOptions.deviceName)); hostMemory.shiftsStepTwo = Dedispersion::getShiftsStepTwo(observation, deviceOptions.padding.at(deviceOptions.deviceName)); if ( options.debug ) { std::cerr << "shiftsStepOne" << std::endl; for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) { std::cerr << hostMemory.shiftsStepOne->at(channel) << " "; } std::cerr << std::endl << "shiftsStepTwo" << std::endl; for ( unsigned int subband = 0; subband < observation.getNrSubbands(); subband++ ) { std::cerr << hostMemory.shiftsStepTwo->at(subband) << " "; } std::cerr << std::endl << std::endl; } observation.setNrSamplesPerBatch(observation.getNrSamplesPerBatch() + static_cast<unsigned int>(hostMemory.shiftsStepTwo->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()))), true); observation.setNrSamplesPerDispersedBatch(observation.getNrSamplesPerBatch(true) + static_cast<unsigned int>(hostMemory.shiftsStepOne->at(0) * (observation.getFirstDM(true) + ((observation.getNrDMs(true) - 1) * observation.getDMStep(true)))), true); observation.setNrDelayBatches(static_cast<unsigned int>(std::ceil(static_cast<double>(observation.getNrSamplesPerDispersedBatch(true)) / observation.getNrSamplesPerBatch())), true); #ifdef HAVE_PSRDADA if ( dataOptions.dataPSRDADA ) { hostMemory.inputDADA.resize(observation.getNrDelayBatches(true)); for ( unsigned int batch = 0; batch < observation.getNrDelayBatches(true); batch++ ) { if ( inputBits >= 8 ) { hostMemory.inputDADA.at(batch) = new std::vector<inputDataType>(observation.getNrBeams() * observation.getNrChannels() * observation.getNrSamplesPerBatch()); } else { hostMemory.inputDADA.at(batch) = new std::vector<inputDataType>(observation.getNrBeams() * observation.getNrChannels() * (observation.getNrSamplesPerBatch() / (8 / inputBits))); } } } #endif // HAVE_PSRDADA if ( kernelConfigurations.dedispersionStepOneParameters.at(deviceOptions.deviceName)->at(observation.getNrDMs(true))->getSplitBatches() ) { // TODO: add support for splitBatches } else { if ( inputBits >= 8 ) { hostMemory.dispersedData.resize(observation.getNrBeams() * observation.getNrChannels() * observation.getNrSamplesPerDispersedBatch(true, deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(inputDataType))); } else { hostMemory.dispersedData.resize(observation.getNrBeams() * observation.getNrChannels() * isa::utils::pad(observation.getNrSamplesPerDispersedBatch(true) / (8 / inputBits), deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(inputDataType))); } } hostMemory.beamMapping.resize(observation.getNrSynthesizedBeams() * observation.getNrSubbands(deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(unsigned int))); hostMemory.subbandedData.resize(observation.getNrBeams() * observation.getNrDMs(true) * observation.getNrSubbands() * observation.getNrSamplesPerBatch(true, deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(outputDataType))); hostMemory.dedispersedData.resize(observation.getNrSynthesizedBeams() * observation.getNrDMs(true) * observation.getNrDMs() * observation.getNrSamplesPerBatch(false, deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(outputDataType))); hostMemory.integratedData.resize(observation.getNrSynthesizedBeams() * observation.getNrDMs(true) * observation.getNrDMs() * isa::utils::pad(observation.getNrSamplesPerBatch() / *(hostMemory.integrationSteps.begin()), deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(outputDataType))); hostMemory.snrData.resize(observation.getNrSynthesizedBeams() * isa::utils::pad(observation.getNrDMs(true) * observation.getNrDMs(), deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(float))); hostMemory.snrSamples.resize(observation.getNrSynthesizedBeams() * isa::utils::pad(observation.getNrDMs(true) * observation.getNrDMs(), deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(unsigned int))); } AstroData::generateBeamMapping(observation, hostMemory.beamMapping, deviceOptions.padding.at(deviceOptions.deviceName), options.subbandDedispersion); } void allocateDeviceMemory(const OpenCLRunTime & openclRunTime, const Options & options, const DeviceOptions & deviceOptions, const HostMemory & hostMemory, DeviceMemory & deviceMemory) { if ( !options.subbandDedispersion ) { deviceMemory.shiftsSingleStep = cl::Buffer(*openclRunTime.context, CL_MEM_READ_ONLY, hostMemory.shiftsSingleStep->size() * sizeof(float), 0, 0); openclRunTime.queues->at(deviceOptions.deviceID).at(0).enqueueWriteBuffer(deviceMemory.shiftsSingleStep, CL_FALSE, 0, hostMemory.shiftsSingleStep->size() * sizeof(float), reinterpret_cast<void *>(hostMemory.shiftsSingleStep->data())); } else { deviceMemory.shiftsStepOne = cl::Buffer(*openclRunTime.context, CL_MEM_READ_ONLY, hostMemory.shiftsStepOne->size() * sizeof(float), 0, 0); openclRunTime.queues->at(deviceOptions.deviceID).at(0).enqueueWriteBuffer(deviceMemory.shiftsStepOne, CL_FALSE, 0, hostMemory.shiftsStepOne->size() * sizeof(float), reinterpret_cast<void *>(hostMemory.shiftsStepOne->data())); deviceMemory.shiftsStepTwo = cl::Buffer(*openclRunTime.context, CL_MEM_READ_ONLY, hostMemory.shiftsStepTwo->size() * sizeof(float), 0, 0); openclRunTime.queues->at(deviceOptions.deviceID).at(0).enqueueWriteBuffer(deviceMemory.shiftsStepTwo, CL_FALSE, 0, hostMemory.shiftsStepTwo->size() * sizeof(float), reinterpret_cast<void *>(hostMemory.shiftsStepTwo->data())); deviceMemory.subbandedData = cl::Buffer(*openclRunTime.context, CL_MEM_READ_WRITE, hostMemory.subbandedData.size() * sizeof(outputDataType), 0, 0); } deviceMemory.zappedChannels = cl::Buffer(*openclRunTime.context, CL_MEM_READ_ONLY, hostMemory.zappedChannels.size() * sizeof(unsigned int), 0, 0); openclRunTime.queues->at(deviceOptions.deviceID).at(0).enqueueWriteBuffer(deviceMemory.zappedChannels, CL_FALSE, 0, hostMemory.zappedChannels.size() * sizeof(unsigned int), reinterpret_cast<const void *>(hostMemory.zappedChannels.data())); deviceMemory.beamMapping = cl::Buffer(*openclRunTime.context, CL_MEM_READ_ONLY, hostMemory.beamMapping.size() * sizeof(unsigned int), 0, 0); openclRunTime.queues->at(deviceOptions.deviceID).at(0).enqueueWriteBuffer(deviceMemory.beamMapping, CL_FALSE, 0, hostMemory.beamMapping.size() * sizeof(unsigned int), reinterpret_cast<const void *>(hostMemory.beamMapping.data())); deviceMemory.dispersedData = cl::Buffer(*openclRunTime.context, CL_MEM_READ_ONLY, hostMemory.dispersedData.size() * sizeof(inputDataType), 0, 0); deviceMemory.dedispersedData = cl::Buffer(*openclRunTime.context, CL_MEM_READ_WRITE, hostMemory.dedispersedData.size() * sizeof(outputDataType), 0, 0); deviceMemory.integratedData = cl::Buffer(*openclRunTime.context, CL_MEM_READ_WRITE, hostMemory.integratedData.size() * sizeof(outputDataType), 0, 0); deviceMemory.snrData = cl::Buffer(*openclRunTime.context, CL_MEM_WRITE_ONLY, hostMemory.snrData.size() * sizeof(float), 0, 0); deviceMemory.snrSamples = cl::Buffer(*openclRunTime.context, CL_MEM_WRITE_ONLY, hostMemory.snrSamples.size() * sizeof(unsigned int), 0, 0); openclRunTime.queues->at(deviceOptions.deviceID).at(0).finish(); } <|endoftext|>
<commit_before>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ #include "utility/ExecutionDAGVisualizer.hpp" #include <algorithm> #include <cstddef> #include <iomanip> #include <limits> #include <set> #include <sstream> #include <string> #include <utility> #include <vector> #include "catalog/CatalogRelationSchema.hpp" #include "query_execution/QueryExecutionTypedefs.hpp" #include "query_optimizer/QueryPlan.hpp" #include "relational_operators/AggregationOperator.hpp" #include "relational_operators/BuildHashOperator.hpp" #include "relational_operators/HashJoinOperator.hpp" #include "relational_operators/RelationalOperator.hpp" #include "relational_operators/SelectOperator.hpp" #include "utility/DAG.hpp" #include "utility/StringUtil.hpp" #include "glog/logging.h" namespace quickstep { ExecutionDAGVisualizer::ExecutionDAGVisualizer(const QueryPlan &plan) { // Do not display these relational operators in the graph. std::set<std::string> no_display_op_names = { "DestroyHashOperator", "DropTableOperator" }; const auto &dag = plan.getQueryPlanDAG(); num_nodes_ = dag.size(); // Collect DAG vertices info. std::vector<bool> display_ops(num_nodes_, false); for (std::size_t node_index = 0; node_index < num_nodes_; ++node_index) { const auto &node = dag.getNodePayload(node_index); const std::string relop_name = node.getName(); if (no_display_op_names.find(relop_name) == no_display_op_names.end()) { display_ops[node_index] = true; NodeInfo &node_info = nodes_[node_index]; node_info.id = node_index; node_info.labels.emplace_back( "[" + std::to_string(node.getOperatorIndex()) + "] " + relop_name); std::vector<std::pair<std::string, const CatalogRelationSchema*>> input_relations; if (relop_name == "AggregationOperator") { const AggregationOperator &aggregation_op = static_cast<const AggregationOperator&>(node); input_relations.emplace_back("input", &aggregation_op.input_relation()); } else if (relop_name == "BuildHashOperator") { const BuildHashOperator &build_hash_op = static_cast<const BuildHashOperator&>(node); input_relations.emplace_back("input", &build_hash_op.input_relation()); } else if (relop_name == "HashJoinOperator") { const HashJoinOperator &hash_join_op = static_cast<const HashJoinOperator&>(node); input_relations.emplace_back("probe side", &hash_join_op.probe_relation()); } else if (relop_name == "SelectOperator") { const SelectOperator &select_op = static_cast<const SelectOperator&>(node); input_relations.emplace_back("input", &select_op.input_relation()); } for (const auto &rel_pair : input_relations) { if (!rel_pair.second->isTemporary()) { node_info.labels.emplace_back( rel_pair.first + " stored relation [" + rel_pair.second->getName() + "]"); } } } } // Collect DAG edges info. for (std::size_t node_index = 0; node_index < num_nodes_; ++node_index) { if (display_ops[node_index]) { for (const auto &link : dag.getDependents(node_index)) { if (display_ops[link.first]) { edges_.emplace_back(); edges_.back().src_node_id = node_index; edges_.back().dst_node_id = link.first; edges_.back().is_pipeline_breaker = link.second; } } } } } void ExecutionDAGVisualizer::bindProfilingStats( const std::vector<WorkOrderTimeEntry> &execution_time_records) { std::vector<std::size_t> time_start(num_nodes_, std::numeric_limits<std::size_t>::max()); std::vector<std::size_t> time_end(num_nodes_, 0); std::vector<std::size_t> time_elapsed(num_nodes_, 0); std::size_t overall_start_time = std::numeric_limits<std::size_t>::max(); std::size_t overall_end_time = 0; for (const auto &entry : execution_time_records) { const std::size_t relop_index = entry.operator_id; DCHECK_LT(relop_index, num_nodes_); const std::size_t workorder_start_time = entry.start_time; const std::size_t workorder_end_time = entry.end_time; overall_start_time = std::min(overall_start_time, workorder_start_time); overall_end_time = std::max(overall_end_time, workorder_end_time); time_start[relop_index] = std::min(time_start[relop_index], workorder_start_time); time_end[relop_index] = std::max(time_end[relop_index], workorder_end_time); time_elapsed[relop_index] += (workorder_end_time - workorder_start_time); } double total_time_elapsed = 0; for (std::size_t i = 0; i < time_elapsed.size(); ++i) { total_time_elapsed += time_elapsed[i]; } std::vector<double> time_percentage(num_nodes_, 0); std::vector<double> span_percentage(num_nodes_, 0); double overall_span = overall_end_time - overall_start_time; double max_percentage = 0; for (std::size_t i = 0; i < time_elapsed.size(); ++i) { time_percentage[i] = time_elapsed[i] / total_time_elapsed * 100; span_percentage[i] = (time_end[i] - time_start[i]) / overall_span * 100; max_percentage = std::max(max_percentage, time_percentage[i] + span_percentage[i]); } for (std::size_t node_index = 0; node_index < num_nodes_; ++node_index) { if (nodes_.find(node_index) != nodes_.end()) { const std::size_t relop_start_time = time_start[node_index]; const std::size_t relop_end_time = time_end[node_index]; const std::size_t relop_elapsed_time = time_elapsed[node_index]; NodeInfo &node_info = nodes_[node_index]; const double hue = (time_percentage[node_index] + span_percentage[node_index]) / max_percentage; node_info.color = std::to_string(hue) + " " + std::to_string(hue) + " 1.0"; if (overall_start_time == 0) { node_info.labels.emplace_back( "span: " + std::to_string((relop_end_time - relop_start_time) / 1000) + "ms"); } else { node_info.labels.emplace_back( "span: [" + std::to_string((relop_start_time - overall_start_time) / 1000) + "ms, " + std::to_string((relop_end_time - overall_start_time) / 1000) + "ms] (" + FormatDigits(span_percentage[node_index], 2) + "%)"); } node_info.labels.emplace_back( "total: " + std::to_string(relop_elapsed_time / 1000) + "ms (" + FormatDigits(time_percentage[node_index], 2) + "%)"); const double concurrency = static_cast<double>(relop_elapsed_time) / (relop_end_time - relop_start_time); node_info.labels.emplace_back( "effective concurrency: " + FormatDigits(concurrency, 2)); } } } std::string ExecutionDAGVisualizer::toDOT() { // Format output graph std::ostringstream graph_oss; graph_oss << "digraph g {\n"; graph_oss << " rankdir=BT\n"; graph_oss << " node [penwidth=2]\n"; graph_oss << " edge [fontsize=16 fontcolor=gray penwidth=2]\n\n"; // Format nodes for (const auto &node_pair : nodes_) { const NodeInfo &node_info = node_pair.second; graph_oss << " " << node_info.id << " [ "; if (!node_info.labels.empty()) { graph_oss << "label=\"" << EscapeSpecialChars(JoinToString(node_info.labels, "&#10;")) << "\" "; } if (!node_info.color.empty()) { graph_oss << "style=filled fillcolor=\"" << node_info.color << "\" "; } graph_oss << "]\n"; } graph_oss << "\n"; // Format edges for (const EdgeInfo &edge_info : edges_) { graph_oss << " " << edge_info.src_node_id << " -> " << edge_info.dst_node_id << " [ "; if (edge_info.is_pipeline_breaker) { graph_oss << "style=dashed "; } if (!edge_info.labels.empty()) { graph_oss << "label=\"" << EscapeSpecialChars(JoinToString(edge_info.labels, "&#10;")) << "\" "; } graph_oss << "]\n"; } graph_oss << "}\n"; return graph_oss.str(); } std::string ExecutionDAGVisualizer::FormatDigits(const double value, const int num_digits) { std::ostringstream oss; oss << std::fixed << std::setprecision(num_digits) << value; return oss.str(); } } // namespace quickstep <commit_msg>Enhanced the execution DAG visualization<commit_after>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ #include "utility/ExecutionDAGVisualizer.hpp" #include <algorithm> #include <cstddef> #include <iomanip> #include <limits> #include <set> #include <sstream> #include <string> #include <unordered_map> #include <utility> #include <vector> #include "catalog/CatalogRelationSchema.hpp" #include "query_execution/QueryExecutionTypedefs.hpp" #include "query_optimizer/QueryPlan.hpp" #include "relational_operators/AggregationOperator.hpp" #include "relational_operators/BuildHashOperator.hpp" #include "relational_operators/HashJoinOperator.hpp" #include "relational_operators/RelationalOperator.hpp" #include "relational_operators/SelectOperator.hpp" #include "utility/DAG.hpp" #include "utility/StringUtil.hpp" #include "glog/logging.h" namespace quickstep { ExecutionDAGVisualizer::ExecutionDAGVisualizer(const QueryPlan &plan) { // Do not display these relational operators in the graph. std::set<std::string> no_display_op_names = { "DestroyHashOperator", "DropTableOperator" }; const auto &dag = plan.getQueryPlanDAG(); num_nodes_ = dag.size(); // Collect DAG vertices info. std::vector<bool> display_ops(num_nodes_, false); for (std::size_t node_index = 0; node_index < num_nodes_; ++node_index) { const auto &node = dag.getNodePayload(node_index); const std::string relop_name = node.getName(); if (no_display_op_names.find(relop_name) == no_display_op_names.end()) { display_ops[node_index] = true; NodeInfo &node_info = nodes_[node_index]; node_info.id = node_index; node_info.labels.emplace_back( "[" + std::to_string(node.getOperatorIndex()) + "] " + relop_name); std::vector<std::pair<std::string, const CatalogRelationSchema*>> input_relations; if (relop_name == "AggregationOperator") { const AggregationOperator &aggregation_op = static_cast<const AggregationOperator&>(node); input_relations.emplace_back("input", &aggregation_op.input_relation()); } else if (relop_name == "BuildHashOperator") { const BuildHashOperator &build_hash_op = static_cast<const BuildHashOperator&>(node); input_relations.emplace_back("input", &build_hash_op.input_relation()); } else if (relop_name == "HashJoinOperator") { const HashJoinOperator &hash_join_op = static_cast<const HashJoinOperator&>(node); input_relations.emplace_back("probe side", &hash_join_op.probe_relation()); } else if (relop_name == "SelectOperator") { const SelectOperator &select_op = static_cast<const SelectOperator&>(node); input_relations.emplace_back("input", &select_op.input_relation()); } for (const auto &rel_pair : input_relations) { if (!rel_pair.second->isTemporary()) { node_info.labels.emplace_back( rel_pair.first + " stored relation [" + rel_pair.second->getName() + "]"); } } } } // Collect DAG edges info. for (std::size_t node_index = 0; node_index < num_nodes_; ++node_index) { if (display_ops[node_index]) { for (const auto &link : dag.getDependents(node_index)) { if (display_ops[link.first]) { edges_.emplace_back(); edges_.back().src_node_id = node_index; edges_.back().dst_node_id = link.first; edges_.back().is_pipeline_breaker = link.second; } } } } } void ExecutionDAGVisualizer::bindProfilingStats( const std::vector<WorkOrderTimeEntry> &execution_time_records) { std::vector<std::size_t> time_start(num_nodes_, std::numeric_limits<std::size_t>::max()); std::vector<std::size_t> time_end(num_nodes_, 0); std::vector<std::size_t> time_elapsed(num_nodes_, 0); std::size_t overall_start_time = std::numeric_limits<std::size_t>::max(); std::size_t overall_end_time = 0; std::unordered_map<std::size_t, std::size_t> workorders_count; std::unordered_map<std::size_t, float> mean_time_per_workorder; for (const auto &entry : execution_time_records) { const std::size_t relop_index = entry.operator_id; DCHECK_LT(relop_index, num_nodes_); const std::size_t workorder_start_time = entry.start_time; const std::size_t workorder_end_time = entry.end_time; overall_start_time = std::min(overall_start_time, workorder_start_time); overall_end_time = std::max(overall_end_time, workorder_end_time); time_start[relop_index] = std::min(time_start[relop_index], workorder_start_time); time_end[relop_index] = std::max(time_end[relop_index], workorder_end_time); time_elapsed[relop_index] += (workorder_end_time - workorder_start_time); if (workorders_count.find(relop_index) == workorders_count.end()) { workorders_count[relop_index] = 0; } ++workorders_count[relop_index]; if (mean_time_per_workorder.find(relop_index) == mean_time_per_workorder.end()) { mean_time_per_workorder[relop_index] = 0; } mean_time_per_workorder[relop_index] += workorder_end_time - workorder_start_time; } double total_time_elapsed = 0; for (std::size_t i = 0; i < time_elapsed.size(); ++i) { total_time_elapsed += time_elapsed[i]; } std::vector<double> time_percentage(num_nodes_, 0); std::vector<double> span_percentage(num_nodes_, 0); double overall_span = overall_end_time - overall_start_time; double max_percentage = 0; for (std::size_t i = 0; i < time_elapsed.size(); ++i) { time_percentage[i] = time_elapsed[i] / total_time_elapsed * 100; span_percentage[i] = (time_end[i] - time_start[i]) / overall_span * 100; max_percentage = std::max(max_percentage, time_percentage[i] + span_percentage[i]); } for (std::size_t node_index = 0; node_index < num_nodes_; ++node_index) { if (nodes_.find(node_index) != nodes_.end()) { const std::size_t relop_start_time = time_start[node_index]; const std::size_t relop_end_time = time_end[node_index]; const std::size_t relop_elapsed_time = time_elapsed[node_index]; NodeInfo &node_info = nodes_[node_index]; const double hue = (time_percentage[node_index] + span_percentage[node_index]) / max_percentage; node_info.color = std::to_string(hue) + " " + std::to_string(hue) + " 1.0"; if (overall_start_time == 0) { node_info.labels.emplace_back( "span: " + std::to_string((relop_end_time - relop_start_time) / 1000) + "ms"); } else { node_info.labels.emplace_back( "span: [" + std::to_string((relop_start_time - overall_start_time) / 1000) + "ms, " + std::to_string((relop_end_time - overall_start_time) / 1000) + "ms] (" + FormatDigits(span_percentage[node_index], 2) + "%)"); } node_info.labels.emplace_back( "total: " + std::to_string(relop_elapsed_time / 1000) + "ms (" + FormatDigits(time_percentage[node_index], 2) + "%)"); const double concurrency = static_cast<double>(relop_elapsed_time) / (relop_end_time - relop_start_time); node_info.labels.emplace_back( "effective concurrency: " + FormatDigits(concurrency, 2)); DCHECK(workorders_count.find(node_index) != workorders_count.end()); const std::size_t workorders_count_for_node = workorders_count.at(node_index); if (workorders_count_for_node > 0) { mean_time_per_workorder[node_index] = mean_time_per_workorder[node_index] / (1000 * static_cast<float>(workorders_count_for_node)); } else { mean_time_per_workorder[node_index] = 0; } node_info.labels.emplace_back(std::to_string(workorders_count_for_node) + " work orders"); node_info.labels.emplace_back( "Mean work order execution time: " + FormatDigits(mean_time_per_workorder[node_index], 2) + " ms"); } } } std::string ExecutionDAGVisualizer::toDOT() { // Format output graph std::ostringstream graph_oss; graph_oss << "digraph g {\n"; graph_oss << " rankdir=BT\n"; graph_oss << " node [penwidth=2]\n"; graph_oss << " edge [fontsize=16 fontcolor=gray penwidth=2]\n\n"; // Format nodes for (const auto &node_pair : nodes_) { const NodeInfo &node_info = node_pair.second; graph_oss << " " << node_info.id << " [ "; if (!node_info.labels.empty()) { graph_oss << "label=\"" << EscapeSpecialChars(JoinToString(node_info.labels, "&#10;")) << "\" "; } if (!node_info.color.empty()) { graph_oss << "style=filled fillcolor=\"" << node_info.color << "\" "; } graph_oss << "]\n"; } graph_oss << "\n"; // Format edges for (const EdgeInfo &edge_info : edges_) { graph_oss << " " << edge_info.src_node_id << " -> " << edge_info.dst_node_id << " [ "; if (edge_info.is_pipeline_breaker) { graph_oss << "style=dashed "; } if (!edge_info.labels.empty()) { graph_oss << "label=\"" << EscapeSpecialChars(JoinToString(edge_info.labels, "&#10;")) << "\" "; } graph_oss << "]\n"; } graph_oss << "}\n"; return graph_oss.str(); } std::string ExecutionDAGVisualizer::FormatDigits(const double value, const int num_digits) { std::ostringstream oss; oss << std::fixed << std::setprecision(num_digits) << value; return oss.str(); } } // namespace quickstep <|endoftext|>
<commit_before>#include <Refal2.h> namespace Refal2 { //----------------------------------------------------------------------------- // CProgram CProgram::CProgram( int numberOfModules ) : modulesSize( numberOfModules ), modules( new CRuntimeModule[modulesSize] ) { assert( modulesSize > 0 ); assert( modules != 0 ); } CProgram::~CProgram() { delete[] modules; } CRuntimeModule& CProgram::Module( TRuntimeModuleId moduleId ) { assert( moduleId >= 0 && moduleId < modulesSize ); return modules[moduleId]; } //----------------------------------------------------------------------------- // Standart embedded functions //----------------------------------------------------------------------------- // CGlobalFunctionData class CGlobalFunctionData { public: CGlobalFunctionData() : preparatoryFunction( 0 ), embeddedFunction( 0 ), runtimeModuleId( 0 ) { } bool IsEmbeddedFunction() const { return ( embeddedFunction != 0 ); } bool IsPreparatoryFunction() const { return ( preparatoryFunction != 0 ); } bool IsDefined() const { return ( IsEmbeddedFunction() || IsPreparatoryFunction() ); } void SetPreparatoryFunction( const CPreparatoryFunction* const _preparatoryFunction, const TRuntimeModuleId _runtimeModuleId ) { assert( !IsDefined() ); assert( _preparatoryFunction != 0 ); preparatoryFunction = _preparatoryFunction; runtimeModuleId = _runtimeModuleId; } const CPreparatoryFunction* PreparatoryFunction() const { assert( IsPreparatoryFunction() ); return preparatoryFunction; } const TRuntimeModuleId RuntimeModuleId() const { assert( IsPreparatoryFunction() ); return runtimeModuleId; } void SetEmbeddedFunction( const TEmbeddedFunctionPtr _embeddedFunction ) { assert( !IsDefined() ); assert( _embeddedFunction != 0 ); embeddedFunction = _embeddedFunction; } TEmbeddedFunctionPtr EmbeddedFunction() const { assert( IsEmbeddedFunction() ); return embeddedFunction; } private: const CPreparatoryFunction* preparatoryFunction; TEmbeddedFunctionPtr embeddedFunction; TRuntimeModuleId runtimeModuleId; }; //----------------------------------------------------------------------------- // CExternalFunctionData class CExternalFunctionData { public: CExternalFunctionData( int _globalIndex, CPreparatoryFunction* _preparatoryFunction ) : globalIndex( _globalIndex ), preparatoryFunction( _preparatoryFunction ) { assert( globalIndex >= 0 ); assert( preparatoryFunction != 0 ); } int GlobalIndex() const { return globalIndex; } CPreparatoryFunction* PreparatoryFunction() const { return preparatoryFunction; } private: int globalIndex; CPreparatoryFunction* preparatoryFunction; }; //----------------------------------------------------------------------------- // CPreparatoryRuntimeFunction class CPreparatoryRuntimeFunction : public CRuntimeFunction { public: CPreparatoryRuntimeFunction( CPreparatoryFunction* const function, const TRuntimeModuleId moduleId ); CPreparatoryFunction* PreparatoryFunction() const { return function; } TRuntimeModuleId RuntimeModuleId() const { return moduleId; } private: CPreparatoryFunction* const function; const TRuntimeModuleId moduleId; static TRuntimeFunctionType convertType( const CPreparatoryFunction* const function ); }; CPreparatoryRuntimeFunction::CPreparatoryRuntimeFunction( CPreparatoryFunction* const _function, const TRuntimeModuleId _moduleId ) : CRuntimeFunction( convertType( _function ) ), function( _function ), moduleId( _moduleId ) { } TRuntimeFunctionType CPreparatoryRuntimeFunction::convertType( const CPreparatoryFunction* const function ) { assert( function != 0 ); switch( function->GetType() ) { case PFT_Ordinary: return RFT_Ordinary; case PFT_Empty: return RFT_Empty; case PFT_External: return RFT_External; case PFT_Declared: case PFT_Defined: case PFT_Compiled: case PFT_Embedded: default: break; } assert( false ); return RFT_Empty; } //----------------------------------------------------------------------------- // CInternalProgramBuilder class CInternalProgramBuilder { public: static CProgramPtr Build( CModuleDataVector& modules, CErrorsHelper& errors ); private: CErrorsHelper& errors; typedef std::vector<CExternalFunctionData> CExternals; CExternals externals; CDictionary<CGlobalFunctionData, std::string> globals; CProgramPtr program; CInternalProgramBuilder( CErrorsHelper& _errors, int numberOfModules ) : errors( _errors ), program( new CProgram( numberOfModules ) ) { assert( static_cast<bool>( program ) ); } void addFunction( CPreparatoryFunction* function, const TRuntimeModuleId runtimeModuleId ); void addFunctions( const CModuleData& module, CRuntimeModule& runtimeModule, const TRuntimeModuleId runtimeModuleId ); void collect( CModuleDataVector& modules ); void check(); void compile(); void link(); }; //----------------------------------------------------------------------------- CProgramPtr CInternalProgramBuilder::Build( CModuleDataVector& modules, CErrorsHelper& errors ) { assert( !errors.HasErrors() ); assert( !modules.empty() ); CInternalProgramBuilder builder( errors, modules.size() ); builder.collect( modules ); if( errors.HasErrors() ) { return nullptr; } builder.check(); if( errors.HasErrors() ) { return nullptr; } builder.compile(); assert( !errors.HasErrors() ); builder.link(); assert( !errors.HasErrors() ); return CProgramPtr( builder.program.release() ); } void CInternalProgramBuilder::addFunction( CPreparatoryFunction* function, const TRuntimeModuleId runtimeModuleId ) { const bool isExternal = function->IsExternal(); const bool isGlobal = function->IsEntry(); if( !( isExternal || isGlobal ) ) { return; } int globalIndex = globals.AddKey( function->ExternalName() ); if( isGlobal ) { assert( !isExternal ); CGlobalFunctionData& global = globals.GetData( globalIndex ); if( global.IsDefined() ) { std::ostringstream stringStream; stringStream << "function with external name `" << function->ExternalNameToken().word << "` already defined in program"; errors.Error( stringStream.str() ); } else { global.SetPreparatoryFunction( function, runtimeModuleId ); } } else { assert( isExternal ); externals.push_back( CExternalFunctionData( globalIndex, function ) ); } } void CInternalProgramBuilder::addFunctions( const CModuleData& module, CRuntimeModule& runtimeModule, const TRuntimeModuleId runtimeModuleId ) { const CPreparatoryFunctions& functions = module.Functions; for( int i = 0; i < functions.Size(); i++ ) { CPreparatoryFunction* function = functions.GetData( i ).get(); CRuntimeFunctionPtr& runtimeFunction = runtimeModule.Functions.GetData( runtimeModule.Functions.AddKey( function->Name() ) ); assert( !static_cast<bool>( runtimeFunction ) ); runtimeFunction.reset( new CPreparatoryRuntimeFunction( function, runtimeModuleId ) ); addFunction( function, runtimeModuleId ); } } void CInternalProgramBuilder::collect( CModuleDataVector& modules ) { TRuntimeModuleId currentModuleId = 0; for( CModuleDataVector::const_iterator module = modules.begin(); module != modules.end(); ++module ) { addFunctions( *( *module ), program->Module( currentModuleId ), currentModuleId ); currentModuleId++; } modules.clear(); } void CInternalProgramBuilder::check() { for( CExternals::const_iterator function = externals.begin(); function != externals.end(); ++function ) { const int globalIndex = function->GlobalIndex(); if( !globals.GetData( globalIndex ).IsDefined() ) { std::ostringstream stringStream; stringStream << "function with external name `" << globals.GetKey( globalIndex ) << "` was not defined in program"; errors.Error( stringStream.str() ); } } } void CInternalProgramBuilder::compile() { CFunctionCompiler compiler; for( int moduleId = 0; moduleId < program->NumberOfModules(); moduleId++ ) { const CRuntimeFunctions& functions = program->Module( moduleId ).Functions; for( int i = 0; i < functions.Size(); i++ ) { const CPreparatoryRuntimeFunction& function = static_cast< CPreparatoryRuntimeFunction&>( *functions.GetData( i ) ); if( function.PreparatoryFunction()->IsOrdinary() ) { function.PreparatoryFunction()->Compile( compiler ); } } } } void CInternalProgramBuilder::link() { for( CExternals::iterator function = externals.begin(); function != externals.end(); ++function ) { function->PreparatoryFunction(); const int globalIndex = function->GlobalIndex(); const CGlobalFunctionData& global = globals.GetData( globalIndex ); assert( global.IsDefined() ); if( global.IsEmbeddedFunction() ) { function->PreparatoryFunction()->SetEmbedded( global.EmbeddedFunction() ); } else { assert( !global.IsPreparatoryFunction() ); function->PreparatoryFunction()->Link( *global.PreparatoryFunction() ); } } for( int moduleId = 0; moduleId < program->NumberOfModules(); moduleId++ ) { const CRuntimeFunctions& functions = program->Module( moduleId ).Functions; for( int i = 0; i < functions.Size(); i++ ) { const CPreparatoryRuntimeFunction& function = static_cast< CPreparatoryRuntimeFunction&>( *functions.GetData( i ) ); const CPreparatoryFunction* preparatoryFunction = function.PreparatoryFunction(); CRuntimeFunctionPtr newRuntimeFunction; switch( function.Type() ) { case RFT_Empty: assert( preparatoryFunction->IsEmpty() ); newRuntimeFunction.reset( new CEmptyFunction ); break; case RFT_Embedded: assert( preparatoryFunction->IsEmbedded() ); newRuntimeFunction.reset( new CEmbeddedFunction( preparatoryFunction->EmbeddedFunction() ) ); break; case RFT_External: assert( preparatoryFunction->IsEmpty() || preparatoryFunction->IsEmbedded() || preparatoryFunction->IsOrdinary() ); // todo: --- newRuntimeFunction.reset( new CExternalFunction( 0, function.RuntimeModuleId() ) ); break; case RFT_Ordinary: assert( preparatoryFunction->IsOrdinary() ); // todo: --- newRuntimeFunction.reset( new COrdinaryFunction( 0 ) ); break; default: assert( false ); break; } } } } //----------------------------------------------------------------------------- // CProgramBuilder CProgramBuilder::CProgramBuilder( IErrorHandler* errorHandler ) : CFunctionBuilder( errorHandler ) { Reset(); } void CProgramBuilder::Reset() { CFunctionBuilder::Reset(); } void CProgramBuilder::AddModule( CModuleDataPtr& module ) { modules.push_back( CModuleDataPtr( module.release() ) ); } void CProgramBuilder::BuildProgram() { CInternalProgramBuilder::Build( modules, *this ); } //----------------------------------------------------------------------------- } // end of namespace Refal2 <commit_msg>add some standart function and error fixes<commit_after>#include <Refal2.h> namespace Refal2 { //----------------------------------------------------------------------------- // CProgram CProgram::CProgram( int numberOfModules ) : modulesSize( numberOfModules ), modules( new CRuntimeModule[modulesSize] ) { assert( modulesSize > 0 ); assert( modules != nullptr ); } CProgram::~CProgram() { delete[] modules; } CRuntimeModule& CProgram::Module( TRuntimeModuleId moduleId ) { assert( moduleId >= 0 && moduleId < modulesSize ); return modules[moduleId]; } //----------------------------------------------------------------------------- // Standart embedded functions static void notImplemented( const char* name ) { std::cout << "external function `" << name << "` not implemented yet."; } static bool embeddedPrint() { notImplemented( __FUNCTION__ ); return false; } static bool embeddedPrintm() { notImplemented( __FUNCTION__ ); return false; } static bool embeddedProut() { notImplemented( __FUNCTION__ ); return false; } static bool embeddedProutm() { notImplemented( __FUNCTION__ ); return false; } //----------------------------------------------------------------------------- // CStandartEmbeddedFunctionData struct CStandartEmbeddedFunctionData { const char* const externalName; const TEmbeddedFunctionPtr EmbeddedFunction; }; const CStandartEmbeddedFunctionData standartEmbeddedFunctions[] = { { "print", embeddedPrint }, { "printm", embeddedPrintm }, { "prout", embeddedProut }, { "proutm", embeddedProutm }, { nullptr, nullptr } }; //----------------------------------------------------------------------------- // CGlobalFunctionData class CGlobalFunctionData { public: CGlobalFunctionData() : preparatoryFunction( nullptr ), embeddedFunction( nullptr ), runtimeModuleId( 0 ) { } bool IsEmbeddedFunction() const { return ( embeddedFunction != nullptr ); } bool IsPreparatoryFunction() const { return ( preparatoryFunction != nullptr ); } bool IsDefined() const { return ( IsEmbeddedFunction() || IsPreparatoryFunction() ); } void SetPreparatoryFunction( const CPreparatoryFunction* const _preparatoryFunction, const TRuntimeModuleId _runtimeModuleId ) { assert( !IsDefined() ); assert( _preparatoryFunction != nullptr ); preparatoryFunction = _preparatoryFunction; runtimeModuleId = _runtimeModuleId; } const CPreparatoryFunction* PreparatoryFunction() const { assert( IsPreparatoryFunction() ); return preparatoryFunction; } const TRuntimeModuleId RuntimeModuleId() const { assert( IsPreparatoryFunction() ); return runtimeModuleId; } void SetEmbeddedFunction( const TEmbeddedFunctionPtr _embeddedFunction ) { assert( !IsDefined() ); assert( _embeddedFunction != nullptr ); embeddedFunction = _embeddedFunction; } TEmbeddedFunctionPtr EmbeddedFunction() const { assert( IsEmbeddedFunction() ); return embeddedFunction; } private: const CPreparatoryFunction* preparatoryFunction; TEmbeddedFunctionPtr embeddedFunction; TRuntimeModuleId runtimeModuleId; }; //----------------------------------------------------------------------------- // CExternalFunctionData class CExternalFunctionData { public: CExternalFunctionData( int _globalIndex, CPreparatoryFunction* _preparatoryFunction ) : globalIndex( _globalIndex ), preparatoryFunction( _preparatoryFunction ) { assert( globalIndex >= 0 ); assert( preparatoryFunction != nullptr ); } int GlobalIndex() const { return globalIndex; } CPreparatoryFunction* PreparatoryFunction() const { return preparatoryFunction; } private: int globalIndex; CPreparatoryFunction* preparatoryFunction; }; //----------------------------------------------------------------------------- // CPreparatoryRuntimeFunction class CPreparatoryRuntimeFunction : public CRuntimeFunction { public: CPreparatoryRuntimeFunction( CPreparatoryFunctionPtr& function, const TRuntimeModuleId moduleId ); CPreparatoryFunction* PreparatoryFunction() const { return function.get(); } TRuntimeModuleId RuntimeModuleId() const { return moduleId; } private: const CPreparatoryFunctionPtr function; const TRuntimeModuleId moduleId; static TRuntimeFunctionType convertType( const CPreparatoryFunction* const function ); }; CPreparatoryRuntimeFunction::CPreparatoryRuntimeFunction( CPreparatoryFunctionPtr& _function, const TRuntimeModuleId _moduleId ) : CRuntimeFunction( convertType( _function.get() ) ), function( _function.release() ), moduleId( _moduleId ) { } TRuntimeFunctionType CPreparatoryRuntimeFunction::convertType( const CPreparatoryFunction* const function ) { assert( function != nullptr ); switch( function->GetType() ) { case PFT_Ordinary: return RFT_Ordinary; case PFT_Empty: return RFT_Empty; case PFT_External: return RFT_External; case PFT_Declared: case PFT_Defined: case PFT_Compiled: case PFT_Embedded: default: break; } assert( false ); return RFT_Empty; } //----------------------------------------------------------------------------- // CInternalProgramBuilder class CInternalProgramBuilder { public: static CProgramPtr Build( CModuleDataVector& modules, CErrorsHelper& errors ); private: CErrorsHelper& errors; typedef std::vector<CExternalFunctionData> CExternals; CExternals externals; CDictionary<CGlobalFunctionData, std::string> globals; CProgramPtr program; CInternalProgramBuilder( CErrorsHelper& _errors, int numberOfModules ); void addFunction( CPreparatoryFunction* function, const TRuntimeModuleId runtimeModuleId ); void addFunctions( const CModuleData& module, CRuntimeModule& runtimeModule, const TRuntimeModuleId runtimeModuleId ); void collect( CModuleDataVector& modules ); void check(); void compile(); void link(); }; //----------------------------------------------------------------------------- CInternalProgramBuilder::CInternalProgramBuilder( CErrorsHelper& _errors, int numberOfModules ) : errors( _errors ), program( new CProgram( numberOfModules ) ) { assert( static_cast<bool>( program ) ); for( int i = 0; standartEmbeddedFunctions[i].EmbeddedFunction != nullptr; i++ ) { assert( standartEmbeddedFunctions[i].externalName != nullptr ); std::string externalName = standartEmbeddedFunctions[i].externalName; assert( !externalName.empty() ); const int globalIndex = globals.AddKey( externalName ); CGlobalFunctionData& global = globals.GetData( globalIndex ); global.SetEmbeddedFunction( standartEmbeddedFunctions[i].EmbeddedFunction ); } } CProgramPtr CInternalProgramBuilder::Build( CModuleDataVector& modules, CErrorsHelper& errors ) { assert( !errors.HasErrors() ); assert( !modules.empty() ); CInternalProgramBuilder builder( errors, modules.size() ); builder.collect( modules ); if( errors.HasErrors() ) { return nullptr; } builder.check(); if( errors.HasErrors() ) { return nullptr; } builder.compile(); assert( !errors.HasErrors() ); builder.link(); assert( !errors.HasErrors() ); return CProgramPtr( builder.program.release() ); } void CInternalProgramBuilder::addFunction( CPreparatoryFunction* function, const TRuntimeModuleId runtimeModuleId ) { const bool isExternal = function->IsExternal(); const bool isGlobal = function->IsEntry(); if( !( isExternal || isGlobal ) ) { return; } const int globalIndex = globals.AddKey( function->ExternalName() ); if( isGlobal ) { assert( !isExternal ); CGlobalFunctionData& global = globals.GetData( globalIndex ); if( global.IsDefined() ) { std::ostringstream stringStream; stringStream << "function with external name `" << function->ExternalNameToken().word << "` already defined in program"; errors.Error( stringStream.str() ); } else { global.SetPreparatoryFunction( function, runtimeModuleId ); } } else { assert( isExternal ); externals.push_back( CExternalFunctionData( globalIndex, function ) ); } } void CInternalProgramBuilder::addFunctions( const CModuleData& module, CRuntimeModule& runtimeModule, const TRuntimeModuleId runtimeModuleId ) { const CPreparatoryFunctions& functions = module.Functions; for( int i = 0; i < functions.Size(); i++ ) { CPreparatoryFunctionPtr function( functions.GetData( i ).release() ); addFunction( function.get(), runtimeModuleId ); CRuntimeFunctionPtr& runtimeFunction = runtimeModule.Functions.GetData( runtimeModule.Functions.AddKey( function->Name() ) ); assert( !static_cast<bool>( runtimeFunction ) ); runtimeFunction.reset( new CPreparatoryRuntimeFunction( function, runtimeModuleId ) ); } } void CInternalProgramBuilder::collect( CModuleDataVector& modules ) { TRuntimeModuleId currentModuleId = 0; for( CModuleDataVector::const_iterator module = modules.begin(); module != modules.end(); ++module ) { addFunctions( *( *module ), program->Module( currentModuleId ), currentModuleId ); currentModuleId++; } modules.clear(); } void CInternalProgramBuilder::check() { for( CExternals::const_iterator function = externals.begin(); function != externals.end(); ++function ) { const int globalIndex = function->GlobalIndex(); if( !globals.GetData( globalIndex ).IsDefined() ) { std::ostringstream stringStream; stringStream << "function with external name `" << globals.GetKey( globalIndex ) << "` was not defined in program"; errors.Error( stringStream.str() ); } } } void CInternalProgramBuilder::compile() { CFunctionCompiler compiler; for( int moduleId = 0; moduleId < program->NumberOfModules(); moduleId++ ) { const CRuntimeFunctions& functions = program->Module( moduleId ).Functions; for( int i = 0; i < functions.Size(); i++ ) { const CRuntimeFunction& runtimeFunction = *functions.GetData( i ); const CPreparatoryRuntimeFunction& function = static_cast< const CPreparatoryRuntimeFunction&>( runtimeFunction ); if( function.PreparatoryFunction()->IsOrdinary() ) { function.PreparatoryFunction()->Compile( compiler ); } } } } void CInternalProgramBuilder::link() { for( CExternals::iterator function = externals.begin(); function != externals.end(); ++function ) { function->PreparatoryFunction(); const int globalIndex = function->GlobalIndex(); const CGlobalFunctionData& global = globals.GetData( globalIndex ); assert( global.IsDefined() ); if( global.IsEmbeddedFunction() ) { function->PreparatoryFunction()->SetEmbedded( global.EmbeddedFunction() ); } else { assert( !global.IsPreparatoryFunction() ); function->PreparatoryFunction()->Link( *global.PreparatoryFunction() ); } } for( int moduleId = 0; moduleId < program->NumberOfModules(); moduleId++ ) { const CRuntimeFunctions& functions = program->Module( moduleId ).Functions; for( int i = 0; i < functions.Size(); i++ ) { const CPreparatoryRuntimeFunction& function = static_cast< CPreparatoryRuntimeFunction&>( *functions.GetData( i ) ); const CPreparatoryFunction* preparatoryFunction = function.PreparatoryFunction(); CRuntimeFunctionPtr newRuntimeFunction; switch( function.Type() ) { case RFT_Empty: assert( preparatoryFunction->IsEmpty() ); newRuntimeFunction.reset( new CEmptyFunction ); break; case RFT_Embedded: assert( preparatoryFunction->IsEmbedded() ); newRuntimeFunction.reset( new CEmbeddedFunction( preparatoryFunction->EmbeddedFunction() ) ); break; case RFT_External: assert( preparatoryFunction->IsEmpty() || preparatoryFunction->IsEmbedded() || preparatoryFunction->IsOrdinary() ); // todo: --- newRuntimeFunction.reset( new CExternalFunction( 0, function.RuntimeModuleId() ) ); break; case RFT_Ordinary: assert( preparatoryFunction->IsOrdinary() ); // todo: --- newRuntimeFunction.reset( new COrdinaryFunction( 0 ) ); break; default: assert( false ); break; } } } } //----------------------------------------------------------------------------- // CProgramBuilder CProgramBuilder::CProgramBuilder( IErrorHandler* errorHandler ) : CFunctionBuilder( errorHandler ) { Reset(); } void CProgramBuilder::Reset() { CFunctionBuilder::Reset(); } void CProgramBuilder::AddModule( CModuleDataPtr& module ) { modules.push_back( CModuleDataPtr( module.release() ) ); } void CProgramBuilder::BuildProgram() { CInternalProgramBuilder::Build( modules, *this ); } //----------------------------------------------------------------------------- } // end of namespace Refal2 <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef VCL_SCOPEDBITMAPACCESS_HXX_INCLUDED #define VCL_SCOPEDBITMAPACCESS_HXX_INCLUDED namespace vcl { /** This template handles BitmapAccess the RAII way. Please don't use directly, but through the ready-made typedefs ScopedReadAccess and ScopedWriteAccess in classes Bitmap and AlphaMask. Use as follows: Bitmap aBitmap; Bitmap::ScopedReadAccess pReadAccess( aBitmap ); pReadAccess->SetPixel()... Bitmap aBitmap2; Bitmap::ScopedWriteAccess pWriteAccess( bCond ? aBitmap2.AcquireWriteAccess() : 0, aBitmap2 ); if ( pWriteAccess )... @attention for practical reasons, ScopedBitmapAccess stores a reference to the provided bitmap, thus, make sure that the bitmap specified at construction time lives at least as long as the ScopedBitmapAccess. */ template < class Access, class Bitmap, Access* (Bitmap::* Acquire)() > class ScopedBitmapAccess { public: explicit ScopedBitmapAccess( Bitmap& rBitmap ) : mpAccess( 0 ), mrBitmap( rBitmap ) { mpAccess = (mrBitmap.*Acquire)(); } ScopedBitmapAccess( Access* pAccess, Bitmap& rBitmap ) : mpAccess( pAccess ), mrBitmap( rBitmap ) { } ~ScopedBitmapAccess() { mrBitmap.ReleaseAccess( mpAccess ); } Access* get() { return mpAccess; } const Access* get() const { return mpAccess; } Access* operator->() { return mpAccess; } const Access* operator->() const { return mpAccess; } Access& operator*() { return *mpAccess; } const Access& operator*() const { return *mpAccess; } private: Access* mpAccess; Bitmap& mrBitmap; }; } #endif // VCL_SCOPEDBITMAPACCESS_HXX_INCLUDED /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>impl. bool conversion<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef VCL_SCOPEDBITMAPACCESS_HXX_INCLUDED #define VCL_SCOPEDBITMAPACCESS_HXX_INCLUDED namespace vcl { /** This template handles BitmapAccess the RAII way. Please don't use directly, but through the ready-made typedefs ScopedReadAccess and ScopedWriteAccess in classes Bitmap and AlphaMask. Use as follows: Bitmap aBitmap; Bitmap::ScopedReadAccess pReadAccess( aBitmap ); pReadAccess->SetPixel()... Bitmap aBitmap2; Bitmap::ScopedWriteAccess pWriteAccess( bCond ? aBitmap2.AcquireWriteAccess() : 0, aBitmap2 ); if ( pWriteAccess )... @attention for practical reasons, ScopedBitmapAccess stores a reference to the provided bitmap, thus, make sure that the bitmap specified at construction time lives at least as long as the ScopedBitmapAccess. */ template < class Access, class Bitmap, Access* (Bitmap::* Acquire)() > class ScopedBitmapAccess { typedef ScopedBitmapAccess< Access, Bitmap, Acquire > self_type; typedef bool (self_type::* unspecified_bool_type)() const; public: explicit ScopedBitmapAccess( Bitmap& rBitmap ) : mpAccess( 0 ), mrBitmap( rBitmap ) { mpAccess = (mrBitmap.*Acquire)(); } ScopedBitmapAccess( Access* pAccess, Bitmap& rBitmap ) : mpAccess( pAccess ), mrBitmap( rBitmap ) { } ~ScopedBitmapAccess() { mrBitmap.ReleaseAccess( mpAccess ); } bool operator!() const { return !mpAccess; } operator unspecified_bool_type() const { return mpAccess ? &self_type::operator! : 0; } Access* get() { return mpAccess; } const Access* get() const { return mpAccess; } Access* operator->() { return mpAccess; } const Access* operator->() const { return mpAccess; } Access& operator*() { return *mpAccess; } const Access& operator*() const { return *mpAccess; } private: Access* mpAccess; Bitmap& mrBitmap; }; } #endif // VCL_SCOPEDBITMAPACCESS_HXX_INCLUDED /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include <algorithm> #include "Parser.h" Parser::Parser() : m_stopParser( false ) { } Parser::~Parser() { if ( m_thread == nullptr ) return; { std::lock_guard<std::mutex> lock( m_lock ); if ( m_tasks.empty() == true ) m_cond.notify_all(); m_stopParser = true; } m_thread->join(); } void Parser::addService(std::unique_ptr<IMetadataService> service) { m_services.push_back( std::move( service ) ); std::push_heap( m_services.begin(), m_services.end(), []( const ServicePtr& a, const ServicePtr& b ) { // We want higher priority first return a->priority() < b->priority(); }); } void Parser::parse(FilePtr file, IParserCb* cb) { std::lock_guard<std::mutex> lock( m_lock ); m_tasks.push_back( new Task( file, m_services, cb ) ); if ( m_thread == nullptr ) m_thread.reset( new std::thread( &Parser::run, this ) ); } void Parser::run() { while ( m_stopParser == false ) { Task* task = nullptr; { std::unique_lock<std::mutex> lock( m_lock ); if ( m_tasks.empty() == true ) { m_cond.wait( lock, [this]() { return m_tasks.empty() == false || m_stopParser == true; }); // We might have been woken up because the parser is being destroyed if ( m_stopParser == true ) return; } // Otherwise it's safe to assume we have at least one element. task = m_tasks.front(); m_tasks.erase(m_tasks.begin()); } (*task->it)->run( task->file, task ); } } Parser::Task::Task( FilePtr file, Parser::ServiceList& serviceList, IParserCb* parserCb ) : file(file) , it( serviceList.begin() ) , end( serviceList.end() ) , cb( parserCb ) { } void Parser::done( FilePtr file, ServiceStatus status, void* data ) { Task *t = reinterpret_cast<Task*>( data ); t->cb->onServiceDone( file, status ); if ( status == StatusTemporaryUnavailable || status == StatusFatal ) { delete t; return ; } ++t->it; if (t->it == t->end) { t->cb->onFileDone( file ); delete t; return; } std::lock_guard<std::mutex> lock( m_lock ); m_tasks.push_back( t ); } <commit_msg>Parser: Fix deadlock<commit_after>#include <algorithm> #include "Parser.h" Parser::Parser() : m_stopParser( false ) { } Parser::~Parser() { if ( m_thread == nullptr ) return; { std::lock_guard<std::mutex> lock( m_lock ); if ( m_tasks.empty() == true ) m_cond.notify_all(); m_stopParser = true; } m_thread->join(); } void Parser::addService(std::unique_ptr<IMetadataService> service) { m_services.push_back( std::move( service ) ); std::push_heap( m_services.begin(), m_services.end(), []( const ServicePtr& a, const ServicePtr& b ) { // We want higher priority first return a->priority() < b->priority(); }); } void Parser::parse(FilePtr file, IParserCb* cb) { std::lock_guard<std::mutex> lock( m_lock ); m_tasks.push_back( new Task( file, m_services, cb ) ); if ( m_thread == nullptr ) m_thread.reset( new std::thread( &Parser::run, this ) ); } void Parser::run() { while ( m_stopParser == false ) { Task* task = nullptr; { std::unique_lock<std::mutex> lock( m_lock ); if ( m_tasks.empty() == true ) { m_cond.wait( lock, [this]() { return m_tasks.empty() == false || m_stopParser == true; }); // We might have been woken up because the parser is being destroyed if ( m_stopParser == true ) return; } // Otherwise it's safe to assume we have at least one element. task = m_tasks.front(); m_tasks.erase(m_tasks.begin()); } (*task->it)->run( task->file, task ); } } Parser::Task::Task( FilePtr file, Parser::ServiceList& serviceList, IParserCb* parserCb ) : file(file) , it( serviceList.begin() ) , end( serviceList.end() ) , cb( parserCb ) { } void Parser::done( FilePtr file, ServiceStatus status, void* data ) { Task *t = reinterpret_cast<Task*>( data ); t->cb->onServiceDone( file, status ); if ( status == StatusTemporaryUnavailable || status == StatusFatal ) { delete t; return ; } ++t->it; if (t->it == t->end) { t->cb->onFileDone( file ); delete t; return; } std::lock_guard<std::mutex> lock( m_lock ); m_tasks.push_back( t ); m_cond.notify_all(); } <|endoftext|>
<commit_before>#ifndef ZIP_LONGEST_HPP #define ZIP_LONGEST_HPP #include "iterator_range.hpp" #include <boost/optional.hpp> #include <tuple> #include <utility> #include <iterator> namespace iter { template <typename ... Containers> struct zip_longest_iter; template <typename ... Containers> iterator_range<zip_longest_iter<Containers...>> zip_longest(Containers && ... containers) { auto begin = zip_longest_iter<Containers...>(std::forward<Containers>(containers)...); auto end = zip_longest_iter<Containers...>(std::forward<Containers>(containers)...); return iterator_range<decltype(begin)>(begin,end); } /* template <int N,typename Tuple> auto zip_get(Tuple & t)->decltype(*std::get<N>(t))& { return *std::get<N>(t); } */ template <typename Container> struct zip_longest_iter<Container> { public: using Iterator = decltype(std::begin(std::declval<Container>())); private: Iterator begin; const Iterator end; public: zip_longest_iter(Container && c) : begin(std::begin(c)),end(std::end(c)) {} std::tuple<boost::optional<decltype(*std::declval<Iterator>())>> operator*() { return std::make_tuple(begin != end ? boost::optional<decltype(*std::declval<Iterator>())>(*begin) : boost::optional<decltype(*std::declval<Iterator>())>()); } zip_longest_iter & operator++() { if(begin!=end)++begin; return *this; } bool operator!=(const zip_longest_iter &) const { return begin != end; } }; template <typename Container, typename ... Containers> struct zip_longest_iter<Container,Containers...> { public: using Iterator = decltype(std::begin(std::declval<Container>())); private: Iterator begin; const Iterator end; zip_longest_iter<Containers...> inner_iter; public: using Elem_t = decltype(*begin); using tuple_t = decltype(std::tuple_cat( std::tuple<boost::optional<Elem_t>>(), *inner_iter)); zip_longest_iter(Container && c, Containers && ... containers) : begin(std::begin(c)), end(std::end(c)), inner_iter(std::forward<Containers>(containers)...) {} //this is for returning a tuple of optional<iterator> tuple_t operator*() { return std::tuple_cat(std::make_tuple(begin != end ?boost::optional<Elem_t>(*begin) :boost::optional<Elem_t>()),*inner_iter); } zip_longest_iter & operator++() { if (begin != end) ++begin; ++inner_iter; return *this; } bool operator!=(const zip_longest_iter & rhs) const { return begin != end || (this->inner_iter != rhs.inner_iter); } }; } //should add reset after the end of a range is reached, just in case someone //tries to use it again //this means it's only safe to use the range ONCE, which is fine because of //the input_iterator_tag namespace std { template <typename ... Containers> struct iterator_traits<iter::zip_longest_iter<Containers...>> { using difference_type = ptrdiff_t; using iterator_category = input_iterator_tag; }; } #endif //ZIP_LONGEST_HPP <commit_msg>overhauls zip_longest, supports temps<commit_after>#ifndef ZIP_LONGEST_HPP_ #define ZIP_LONGEST_HPP_ #include "iterbase.hpp" #include <boost/optional.hpp> #include <iterator> #include <tuple> #include <utility> namespace iter { template <typename Container, typename... RestContainers> class ZippedLongest; template <typename... Containers> ZippedLongest<Containers...> zip_longest(Containers&&...); template <typename Container, typename... RestContainers> class ZippedLongest { static_assert(!std::is_rvalue_reference<Container>::value, "Itertools cannot be templated with rvalue references"); friend ZippedLongest zip_longest<Container, RestContainers...>( Container&&, RestContainers&&...); template <typename C, typename... RC> friend class ZippedLongest; private: Container container; ZippedLongest<RestContainers...> rest_zipped; ZippedLongest(Container container, RestContainers&&... rest) : container(std::forward<Container>(container)), rest_zipped{std::forward<RestContainers>(rest)...} { } public: class Iterator { private: using RestIter = typename ZippedLongest<RestContainers...>::Iterator; using OptType = boost::optional<iterator_deref<Container>>; iterator_type<Container> iter; iterator_type<Container> end; RestIter rest_iter; public: Iterator( iterator_type<Container> it, iterator_type<Container> in_end, const RestIter& rest) : iter{it}, end{in_end}, rest_iter{rest} { } Iterator& operator++() { if (this->iter != this->end) { ++this->iter; } ++this->rest_iter; return *this; } bool operator!=(const Iterator& other) const { return this->iter != other.iter || this->rest_iter != other.rest_iter; } auto operator*() -> decltype(std::tuple_cat( std::tuple<OptType>{OptType{*this->iter}}, *this->rest_iter)) { if (this->iter != this->end) { return std::tuple_cat( std::tuple<OptType>{OptType{*this->iter}}, *this->rest_iter); } else { return std::tuple_cat( std::tuple<OptType>{OptType{}}, *this->rest_iter); } } }; Iterator begin() { return {std::begin(this->container), std::end(this->container), std::begin(this->rest_zipped)}; } Iterator end() { return {std::end(this->container), std::end(this->container), std::end(this->rest_zipped)}; } }; template <typename Container> class ZippedLongest<Container> { static_assert(!std::is_rvalue_reference<Container>::value, "Itertools cannot be templated with rvalue references"); friend ZippedLongest zip_longest<Container>(Container&&); template <typename C, typename... RC> friend class ZippedLongest; private: Container container; ZippedLongest(Container container) : container(std::forward<Container>(container)) { } public: class Iterator { private: using OptType = boost::optional<iterator_deref<Container>>; iterator_type<Container> iter; iterator_type<Container> end; public: Iterator( iterator_type<Container> it, iterator_type<Container> in_end) : iter{it}, end{in_end} { } Iterator& operator++() { if (this->iter != this->end) { ++this->iter; } return *this; } bool operator!=(const Iterator& other) const { return this->iter != other.iter; } std::tuple<OptType> operator*() { if (this->iter != this->end) { return std::tuple<OptType>{OptType{*this->iter}}; } return std::tuple<OptType>{OptType{}}; } }; Iterator begin() { return {std::begin(this->container), std::end(this->container)}; } Iterator end() { return {std::end(this->container), std::end(this->container)}; } }; template <typename... Containers> ZippedLongest<Containers...> zip_longest(Containers&&... containers) { return {std::forward<Containers>(containers)...}; } } #endif // #ifndef ZIP_LONGEST_HPP_ <|endoftext|>
<commit_before>/* Copyright (c) 2015 ANON authors, see AUTHORS file. 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 "io_dispatch.h" #include "fiber.h" #include "tls_context.h" #include "http_server.h" #include <dirent.h> #include <fcntl.h> #if defined(TEFLON_SERVER_APP) void server_init(); void server_respond(http_server::pipe_t& pipe, const http_request& request); void server_term(); #endif static void show_help() { printf("usage: teflon -listen_fd <socket file descript number to use for listening for tls tcp connections>\n"); printf(" or\n"); printf(" -listen_port <port number to listen on>\n"); printf(" plus...\n"); printf(" -cert_verify_dir <directory of trusted root certificates in c_rehash form>\n"); printf(" -server_cert <certificate file for the server>\n"); printf(" -server_key <private key file for the server's certificate>\n"); printf(" -server_pw <OPTIONAL - password to decrypt server_key>\n"); printf(" -cmd_fd <OPTIONAL - file descriptor number for the command pipe>\n"); } extern "C" int main(int argc, char** argv) { bool port_is_fd = false; int http_port = -1; int cmd_pipe = -1; const char* cert_verify_dir = 0; const char* cert = 0; const char* key = 0; // all options are pairs for us, so there must // be an odd number of arguments (the first // one is the name of our executable). if (!(argc & 1)) { show_help(); return 1; } for (int i = 1; i < argc - 1; i++) { if (!strcmp("-listen_fd",argv[i])) { http_port = atoi(argv[++i]); port_is_fd = true; } else if (!strcmp("-listen_port",argv[i])) { http_port = atoi(argv[++i]); } else if (!strcmp("-cert_verify_dir",argv[i])) { cert_verify_dir = argv[++i]; } else if (!strcmp("-server_cert",argv[i])) { cert = argv[++i]; } else if (!strcmp("-server_key",argv[i])) { key = argv[++i]; } else if (!strcmp("-cmd_fd",argv[i])) { cmd_pipe = atoi(argv[++i]); } else { show_help(); return 1; } } // did we get all the arguments we need? if (http_port <= 0 || !cert_verify_dir || !cert || !key) { show_help(); return 1; } anon_log("teflon server process starting"); // initialize the io dispatch and fiber code // the last 'true' parameter says that we will be using // this calling thread as one of the io threads (after // we are done completing our initialization) io_dispatch::start(std::thread::hardware_concurrency(), true); fiber::initialize(); int ret = 0; try { #if defined(TEFLON_SERVER_APP) server_init(); #endif anon_log("cert: \"" << cert << "\""); anon_log("key: \"" << key << "\""); // construct the server's ssl/tls context tls_context server_ctx( false/*client*/, 0/*verify_cert*/, cert_verify_dir, cert, key, 5/*verify_depth*/); // capture a closure which can be executed later // to create the http_server and set 'my_http' std::unique_ptr<http_server> my_http; auto create_srv_proc = [&my_http, &server_ctx, http_port, port_is_fd]{ my_http = std::unique_ptr<http_server>(new http_server(http_port, [](http_server::pipe_t& pipe, const http_request& request){ #if defined(TEFLON_SERVER_APP) // When this is compiled with TEFLON_SERVER_APP // you have to supply an implementation of server_respond. // It gets called here every time there is a GET/POST/etc... // http message sent to this server. server_respond(pipe, request); #else // example code - just returns a canned blob of text http_response response; response.add_header("Content-Type", "text/plain"); response << "Hello from Teflon!\n"; response << "your url query was: " << request.get_url_field(UF_QUERY) << "\n"; response << "server response generated from:\n"; response << " process: " << getpid() << "\n"; response << " thread: " << syscall(SYS_gettid) << "\n"; #if defined(ANON_LOG_FIBER_IDS) response << " fiber: " << get_current_fiber_id() << "\n"; #endif pipe.respond(response); #endif }, tcp_server::k_default_backlog, &server_ctx, port_is_fd)); }; // if we have been run by a tool capable of giving // us a command pipe, then hook up the parser for that. // Note that if we are directly executed from a shell // (for testing purposes) there will be no command pipe // and no way to communicate with the process. std::unique_ptr<fiber> cmd_fiber; if (cmd_pipe != -1) { fiber::run_in_fiber([cmd_pipe, &my_http, &cmd_fiber, &create_srv_proc]{ cmd_fiber = std::unique_ptr<fiber>(new fiber([cmd_pipe, &my_http, &create_srv_proc]{ // the command parser itself if (fcntl(cmd_pipe, F_SETFL, fcntl(cmd_pipe, F_GETFL) | O_NONBLOCK) != 0) do_error("fcntl(cmd_pipe, F_SETFL, O_NONBLOCK)"); fiber_pipe pipe(cmd_pipe,fiber_pipe::unix_domain); char cmd; char ok = 1; // tell the caller we are fully initialized and // ready to accept commands anon_log("ready to start http server"); pipe.write(&ok, sizeof(ok)); // continue to parse commands // until we get one that tells us to stop while (true) { try { pipe.read(&cmd, 1); } catch (const std::exception& err) { anon_log("command pipe unexpectedly failed: " << err.what()); exit(1); } catch (...) { anon_log("command pipe unexpectedly failed"); exit(1); } if (cmd == 0) { if (!my_http) create_srv_proc(); else anon_log("start command already processed"); } else if (cmd == 1) break; else anon_log("unknown command: " << (int)cmd); } // tell the tcp server to stop calling 'accept' // this function returns once the it is in a // state of no longer calling accept on any thread // and the listening socket is disconnected from the // io dispatch mechanism, so no new thread will respond // even if a client calls connect. if (my_http) my_http->stop(); anon_log("http server stopped"); // tell the caller we have stopped calling accept // on the listening socket. They are now free to // let some other process start calling it if they // wish. pipe.write(&ok, sizeof(ok)); // there may have been active network sessions because // of previous calls to accept. So wait here until // they have all closed. Note that in certain cases // this may wait until the network io timeout has expired fiber_pipe::wait_for_zero_net_pipes(); // instruct the io dispatch threads to all wake up and // terminate. io_dispatch::stop(); })); }); } // this call returns after the above call to io_dispatch::stop() has been // called -- meaning that some external command has told us to stop. io_dispatch::start_this_thread(); #if defined(TEFLON_SERVER_APP) // Whatever the app wants to do at termination time. // // At this point in time all network that sockets were // created as a consequence of computers calling calling // 'connect' to this server, been closed server_term(); #endif // wait for all io threads to terminate (other than this one) io_dispatch::join(); // shut down the fiber control pipe mechanisms fiber::terminate(); } catch(const std::exception& exc) { anon_log("caught exception: " << exc.what()); ret = 1; } catch (...) { anon_log("caught unknown exception"); ret = 1; } anon_log("teflon server process exiting"); return ret; } <commit_msg>removing accidental logging lines<commit_after>/* Copyright (c) 2015 ANON authors, see AUTHORS file. 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 "io_dispatch.h" #include "fiber.h" #include "tls_context.h" #include "http_server.h" #include <dirent.h> #include <fcntl.h> #if defined(TEFLON_SERVER_APP) void server_init(); void server_respond(http_server::pipe_t& pipe, const http_request& request); void server_term(); #endif static void show_help() { printf("usage: teflon -listen_fd <socket file descript number to use for listening for tls tcp connections>\n"); printf(" or\n"); printf(" -listen_port <port number to listen on>\n"); printf(" plus...\n"); printf(" -cert_verify_dir <directory of trusted root certificates in c_rehash form>\n"); printf(" -server_cert <certificate file for the server>\n"); printf(" -server_key <private key file for the server's certificate>\n"); printf(" -server_pw <OPTIONAL - password to decrypt server_key>\n"); printf(" -cmd_fd <OPTIONAL - file descriptor number for the command pipe>\n"); } extern "C" int main(int argc, char** argv) { bool port_is_fd = false; int http_port = -1; int cmd_pipe = -1; const char* cert_verify_dir = 0; const char* cert = 0; const char* key = 0; // all options are pairs for us, so there must // be an odd number of arguments (the first // one is the name of our executable). if (!(argc & 1)) { show_help(); return 1; } for (int i = 1; i < argc - 1; i++) { if (!strcmp("-listen_fd",argv[i])) { http_port = atoi(argv[++i]); port_is_fd = true; } else if (!strcmp("-listen_port",argv[i])) { http_port = atoi(argv[++i]); } else if (!strcmp("-cert_verify_dir",argv[i])) { cert_verify_dir = argv[++i]; } else if (!strcmp("-server_cert",argv[i])) { cert = argv[++i]; } else if (!strcmp("-server_key",argv[i])) { key = argv[++i]; } else if (!strcmp("-cmd_fd",argv[i])) { cmd_pipe = atoi(argv[++i]); } else { show_help(); return 1; } } // did we get all the arguments we need? if (http_port <= 0 || !cert_verify_dir || !cert || !key) { show_help(); return 1; } anon_log("teflon server process starting"); // initialize the io dispatch and fiber code // the last 'true' parameter says that we will be using // this calling thread as one of the io threads (after // we are done completing our initialization) io_dispatch::start(std::thread::hardware_concurrency(), true); fiber::initialize(); int ret = 0; try { #if defined(TEFLON_SERVER_APP) server_init(); #endif // construct the server's ssl/tls context tls_context server_ctx( false/*client*/, 0/*verify_cert*/, cert_verify_dir, cert, key, 5/*verify_depth*/); // capture a closure which can be executed later // to create the http_server and set 'my_http' std::unique_ptr<http_server> my_http; auto create_srv_proc = [&my_http, &server_ctx, http_port, port_is_fd]{ my_http = std::unique_ptr<http_server>(new http_server(http_port, [](http_server::pipe_t& pipe, const http_request& request){ #if defined(TEFLON_SERVER_APP) // When this is compiled with TEFLON_SERVER_APP // you have to supply an implementation of server_respond. // It gets called here every time there is a GET/POST/etc... // http message sent to this server. server_respond(pipe, request); #else // example code - just returns a canned blob of text http_response response; response.add_header("Content-Type", "text/plain"); response << "Hello from Teflon!\n"; response << "your url query was: " << request.get_url_field(UF_QUERY) << "\n"; response << "server response generated from:\n"; response << " process: " << getpid() << "\n"; response << " thread: " << syscall(SYS_gettid) << "\n"; #if defined(ANON_LOG_FIBER_IDS) response << " fiber: " << get_current_fiber_id() << "\n"; #endif pipe.respond(response); #endif }, tcp_server::k_default_backlog, &server_ctx, port_is_fd)); }; // if we have been run by a tool capable of giving // us a command pipe, then hook up the parser for that. // Note that if we are directly executed from a shell // (for testing purposes) there will be no command pipe // and no way to communicate with the process. std::unique_ptr<fiber> cmd_fiber; if (cmd_pipe != -1) { fiber::run_in_fiber([cmd_pipe, &my_http, &cmd_fiber, &create_srv_proc]{ cmd_fiber = std::unique_ptr<fiber>(new fiber([cmd_pipe, &my_http, &create_srv_proc]{ // the command parser itself if (fcntl(cmd_pipe, F_SETFL, fcntl(cmd_pipe, F_GETFL) | O_NONBLOCK) != 0) do_error("fcntl(cmd_pipe, F_SETFL, O_NONBLOCK)"); fiber_pipe pipe(cmd_pipe,fiber_pipe::unix_domain); char cmd; char ok = 1; // tell the caller we are fully initialized and // ready to accept commands anon_log("ready to start http server"); pipe.write(&ok, sizeof(ok)); // continue to parse commands // until we get one that tells us to stop while (true) { try { pipe.read(&cmd, 1); } catch (const std::exception& err) { anon_log("command pipe unexpectedly failed: " << err.what()); exit(1); } catch (...) { anon_log("command pipe unexpectedly failed"); exit(1); } if (cmd == 0) { if (!my_http) create_srv_proc(); else anon_log("start command already processed"); } else if (cmd == 1) break; else anon_log("unknown command: " << (int)cmd); } // tell the tcp server to stop calling 'accept' // this function returns once the it is in a // state of no longer calling accept on any thread // and the listening socket is disconnected from the // io dispatch mechanism, so no new thread will respond // even if a client calls connect. if (my_http) my_http->stop(); anon_log("http server stopped"); // tell the caller we have stopped calling accept // on the listening socket. They are now free to // let some other process start calling it if they // wish. pipe.write(&ok, sizeof(ok)); // there may have been active network sessions because // of previous calls to accept. So wait here until // they have all closed. Note that in certain cases // this may wait until the network io timeout has expired fiber_pipe::wait_for_zero_net_pipes(); // instruct the io dispatch threads to all wake up and // terminate. io_dispatch::stop(); })); }); } // this call returns after the above call to io_dispatch::stop() has been // called -- meaning that some external command has told us to stop. io_dispatch::start_this_thread(); #if defined(TEFLON_SERVER_APP) // Whatever the app wants to do at termination time. // // At this point in time all network that sockets were // created as a consequence of computers calling calling // 'connect' to this server, been closed server_term(); #endif // wait for all io threads to terminate (other than this one) io_dispatch::join(); // shut down the fiber control pipe mechanisms fiber::terminate(); } catch(const std::exception& exc) { anon_log("caught exception: " << exc.what()); ret = 1; } catch (...) { anon_log("caught unknown exception"); ret = 1; } anon_log("teflon server process exiting"); return ret; } <|endoftext|>
<commit_before>#include "Player.h" #include "Projectile.h" Player::Player(ItensManager* itemManager, int x, int y): Character(x,y), inputComponent(nullptr), itemManager(itemManager), skills( { false, false, true,true, true, false, false } ), skillPoints(0), energy(5), regenCD(500), crouching(false), crouchingEdge(true) { name = "Player"; hitpoints = MAX_HITPOINTS; } Player::~Player() { } bool Player::IsPlayer() { return true; } int Player::GetEnergy() { return energy; } void Player::Crouch() { if (crouchingEdge) { crouchingEdge = false; soundComponent->Crouching(); } crouching = true; } void Player::Stand() { crouching = false; crouchingEdge = true; } bool Player::Crouching() { return crouching; } void Player::EvalItem(std::string itemName) { if (itemName == "Healing Potion 25") { hitpoints += MAX_HITPOINTS*0.5; clamp(hitpoints,0,MAX_HITPOINTS); } if (itemName == "Healing Potion 50") { hitpoints += MAX_HITPOINTS*0.5; clamp(hitpoints,0,MAX_HITPOINTS); } if (itemName == "Energy Potion 25") { energy += 2; clamp(energy,0,5); } if (itemName == "Energy Potion 50") { energy += 5; clamp(energy,0,5); } if (itemName == "Skill Coin") { skillPoints++; } } void Player::NotifyObjectCollision(GameObject* other) { Character::NotifyObjectCollision(other); if (other->IsCharacter() && !other->IsPlayer()) { Character* c = (Character*) other; if (c->Attacking()) Damage(c->Power()); } if (other->Is("Projectile")) { Projectile* p = (Projectile*) other; if (!(p->GetOwner() == "Gallahad")) Damage(p->Power()); } if (other->Is("Energy")) { if (crouching && !regenCD.IsRunning()) { regenCD.Start(); energy += 1; clamp(energy,0,5); } } if (other->Is("Life")) { if (crouching && !regenCD.IsRunning()) { regenCD.Start(); hitpoints += 1; clamp(hitpoints,0,10); } } } void Player::UpdateTimers(float dt) { Character::UpdateTimers(dt); regenCD.Update(dt); } void Player::Update(TileMap* map, float dt) { UpdateTimers(dt); inputComponent->Update(this,dt); physicsComponent.Update(this,map,dt); if (OutOfBounds(map)){ SetPosition(Vec2(startingX,startingY)); } graphicsComponent->Update(this,dt); } <commit_msg>Aplicando comentarios 4 (Player.cpp)<commit_after>/* Copyright 2017 Neon Edge Game File Name: Player.cpp Header File Name: Player.h Class Name: Player Objective: Manages the behavior of some aspects of the player. */ #include "Player.h" #include "Projectile.h" /* Function Objective: Constructor of the class Player. param: ItensManager* itemManager, int x, inty: (x,y) are coordinates for the position of the player. return: Instance to Player. */ Player::Player(ItensManager* itemManager, int x, int y): Character(x,y), inputComponent(nullptr), itemManager(itemManager), skills( { false, false, true,true, true, false, false } ), skillPoints(0), energy(5), regenCD(500), crouching(false), crouchingEdge(true) { name = "Player"; //Sets the Player's name. hitpoints = MAX_HITPOINTS; //Sets the hitpoints of the player to 10. } /* Function Objective: Destructor of the class Player. param: No parameter. return: No return. */ Player::~Player() { } /* Function Objective: Checks if is a player. param: No parameter. return: Resturns TRUE. */ bool Player::IsPlayer() { return true; } /* Function Objective: Gets the energy of player. param: No parameter. return: Returns the amount of energy. */ int Player::GetEnergy() { return energy; } /* Function Objective: Perform the action of crouch. param: No parameter. return: No return. */ void Player::Crouch() { if (crouchingEdge) { crouchingEdge = false; soundComponent->Crouching(); } crouching = true; } /* Function Objective: Perform the action of stand. param: No parameter. return: No return. */ void Player::Stand() { crouching = false; crouchingEdge = true; } /* Function Objective: Checks if the player is crouching or not. param: No parameter. return: Return true if the player is crouching. */ bool Player::Crouching() { return crouching; } /* Function Objective: Performs an action due to an item used by the player. param: string itemName: The name of the item. return: No return. */ void Player::EvalItem(std::string itemName) { if (itemName == "Healing Potion 25") { hitpoints += MAX_HITPOINTS*0.5; clamp(hitpoints, 0, MAX_HITPOINTS); } if (itemName == "Healing Potion 50") { hitpoints += MAX_HITPOINTS*0.5; clamp(hitpoints, 0, MAX_HITPOINTS); } if (itemName == "Energy Potion 25") { energy += 2; clamp(energy, 0, 5); } if (itemName == "Energy Potion 50") { energy += 5; clamp(energy, 0, 5); } if (itemName == "Skill Coin") { skillPoints++; } } /* Function Objective: Manages the reactions of other objects in collision with the player. param: GameObject* other: The object that is in collision with the player. return: No return. */ void Player::NotifyObjectCollision(GameObject* other) { Character::NotifyObjectCollision(other); if (other->IsCharacter() && !other->IsPlayer()) { Character* c = (Character*) other; if (c->Attacking()) Damage(c->Power()); } if (other->Is("Projectile")) { Projectile* p = (Projectile*) other; if (!(p->GetOwner() == "Gallahad")) Damage(p->Power()); } if (other->Is("Energy")) { if (crouching && !regenCD.IsRunning()) { regenCD.Start(); energy += 1; clamp(energy, 0, 5); } } if (other->Is("Life")) { if (crouching && !regenCD.IsRunning()) { regenCD.Start(); hitpoints += 1; clamp(hitpoints, 0, 10); } } } /* Function Objective: Updates the time of the cool down regeneration. param: float dt: the amount of time to cool down the regeneration. return: No return. */ void Player::UpdateTimers(float dt) { Character::UpdateTimers(dt); regenCD.Update(dt); } void Player::Update(TileMap* map, float dt) { UpdateTimers(dt); inputComponent->Update(this, dt); physicsComponent.Update(this, map, dt); if (OutOfBounds(map)) { SetPosition(Vec2(startingX, startingY)); } graphicsComponent->Update(this, dt); } <|endoftext|>
<commit_before>#pragma once #include <warpcoil/cpp/helpers.hpp> #include <boost/asio/handler_invoke_hook.hpp> #include <boost/asio/write.hpp> #include <silicium/sink/iterator_sink.hpp> namespace warpcoil { namespace cpp { template <class ResultHandler, class Result> struct response_parse_operation { explicit response_parse_operation(ResultHandler handler) : m_handler(std::move(handler)) { } void operator()(boost::system::error_code ec, Result result) { m_handler(ec, std::move(result)); } private: ResultHandler m_handler; template <class Function> friend void asio_handler_invoke(Function &&f, response_parse_operation *operation) { using boost::asio::asio_handler_invoke; asio_handler_invoke(f, &operation->m_handler); } }; template <class ResultHandler, class AsyncReadStream, class Buffer, class Parser> struct request_send_operation { explicit request_send_operation(ResultHandler handler, AsyncReadStream &input, Buffer receive_buffer, std::size_t &receive_buffer_used) : m_handler(std::move(handler)) , m_input(input) , m_receive_buffer(receive_buffer) , m_receive_buffer_used(receive_buffer_used) { } void operator()(boost::system::error_code ec, std::size_t) { if (!!ec) { m_handler(ec, {}); return; } begin_parse_value( m_input, m_receive_buffer, m_receive_buffer_used, Parser(), response_parse_operation<ResultHandler, typename Parser::result_type>(std::move(m_handler))); } private: ResultHandler m_handler; AsyncReadStream &m_input; Buffer m_receive_buffer; std::size_t &m_receive_buffer_used; template <class Function> friend void asio_handler_invoke(Function &&f, request_send_operation *operation) { using boost::asio::asio_handler_invoke; asio_handler_invoke(f, &operation->m_handler); } }; template <class ResultHandler> struct no_response_request_send_operation { explicit no_response_request_send_operation(ResultHandler handler) : m_handler(std::move(handler)) { } void operator()(boost::system::error_code ec, std::size_t) { m_handler(ec, {}); } private: ResultHandler m_handler; template <class Function> friend void asio_handler_invoke(Function &&f, no_response_request_send_operation *operation) { using boost::asio::asio_handler_invoke; asio_handler_invoke(f, &operation->m_handler); } }; enum class client_pipeline_request_status { ok, failure }; template <class AsyncWriteStream, class AsyncReadStream> struct client_pipeline { explicit client_pipeline(AsyncWriteStream &requests, AsyncReadStream &responses) : requests(requests) , responses(responses) , response_buffer_used(0) { } template <class ResultParser, class RequestBuilder, class ResultHandler> void request(RequestBuilder build_request, ResultHandler &handler) { request_buffer.clear(); { auto sink = Si::Sink<std::uint8_t>::erase(Si::make_container_sink(request_buffer)); switch (build_request(sink)) { case client_pipeline_request_status::ok: break; case client_pipeline_request_status::failure: return; } } auto receive_buffer = boost::asio::buffer(response_buffer); boost::asio::async_write( requests, boost::asio::buffer(request_buffer), warpcoil::cpp::request_send_operation<typename std::decay<decltype(handler)>::type, AsyncReadStream, decltype(receive_buffer), ResultParser>( std::move(handler), responses, receive_buffer, response_buffer_used)); } template <class ResultParser, class RequestBuilder, class ResultHandler> void request_without_response(RequestBuilder build_request, ResultHandler &handler) { request_buffer.clear(); { auto sink = Si::Sink<std::uint8_t>::erase(Si::make_container_sink(request_buffer)); switch (build_request(sink)) { case client_pipeline_request_status::ok: break; case client_pipeline_request_status::failure: return; } } boost::asio::async_write( requests, boost::asio::buffer(request_buffer), warpcoil::cpp::no_response_request_send_operation<typename std::decay<decltype(handler)>::type>( std::move(handler))); } private: std::vector<std::uint8_t> request_buffer; AsyncWriteStream &requests; std::array<std::uint8_t, 512> response_buffer; AsyncReadStream &responses; std::size_t response_buffer_used; }; } } <commit_msg>move stuff into namespace detail<commit_after>#pragma once #include <warpcoil/cpp/helpers.hpp> #include <boost/asio/handler_invoke_hook.hpp> #include <boost/asio/write.hpp> #include <silicium/sink/iterator_sink.hpp> namespace warpcoil { namespace cpp { namespace detail { template <class ResultHandler, class Result> struct response_parse_operation { explicit response_parse_operation(ResultHandler handler) : m_handler(std::move(handler)) { } void operator()(boost::system::error_code ec, Result result) { m_handler(ec, std::move(result)); } private: ResultHandler m_handler; template <class Function> friend void asio_handler_invoke(Function &&f, response_parse_operation *operation) { using boost::asio::asio_handler_invoke; asio_handler_invoke(f, &operation->m_handler); } }; template <class ResultHandler, class AsyncReadStream, class Buffer, class Parser> struct request_send_operation { explicit request_send_operation(ResultHandler handler, AsyncReadStream &input, Buffer receive_buffer, std::size_t &receive_buffer_used) : m_handler(std::move(handler)) , m_input(input) , m_receive_buffer(receive_buffer) , m_receive_buffer_used(receive_buffer_used) { } void operator()(boost::system::error_code ec, std::size_t) { if (!!ec) { m_handler(ec, {}); return; } begin_parse_value( m_input, m_receive_buffer, m_receive_buffer_used, Parser(), response_parse_operation<ResultHandler, typename Parser::result_type>(std::move(m_handler))); } private: ResultHandler m_handler; AsyncReadStream &m_input; Buffer m_receive_buffer; std::size_t &m_receive_buffer_used; template <class Function> friend void asio_handler_invoke(Function &&f, request_send_operation *operation) { using boost::asio::asio_handler_invoke; asio_handler_invoke(f, &operation->m_handler); } }; template <class ResultHandler> struct no_response_request_send_operation { explicit no_response_request_send_operation(ResultHandler handler) : m_handler(std::move(handler)) { } void operator()(boost::system::error_code ec, std::size_t) { m_handler(ec, {}); } private: ResultHandler m_handler; template <class Function> friend void asio_handler_invoke(Function &&f, no_response_request_send_operation *operation) { using boost::asio::asio_handler_invoke; asio_handler_invoke(f, &operation->m_handler); } }; } enum class client_pipeline_request_status { ok, failure }; template <class AsyncWriteStream, class AsyncReadStream> struct client_pipeline { explicit client_pipeline(AsyncWriteStream &requests, AsyncReadStream &responses) : requests(requests) , responses(responses) , response_buffer_used(0) { } template <class ResultParser, class RequestBuilder, class ResultHandler> void request(RequestBuilder build_request, ResultHandler &handler) { request_buffer.clear(); { auto sink = Si::Sink<std::uint8_t>::erase(Si::make_container_sink(request_buffer)); switch (build_request(sink)) { case client_pipeline_request_status::ok: break; case client_pipeline_request_status::failure: return; } } auto receive_buffer = boost::asio::buffer(response_buffer); boost::asio::async_write( requests, boost::asio::buffer(request_buffer), warpcoil::cpp::detail::request_send_operation<typename std::decay<decltype(handler)>::type, AsyncReadStream, decltype(receive_buffer), ResultParser>(std::move(handler), responses, receive_buffer, response_buffer_used)); } template <class ResultParser, class RequestBuilder, class ResultHandler> void request_without_response(RequestBuilder build_request, ResultHandler &handler) { request_buffer.clear(); { auto sink = Si::Sink<std::uint8_t>::erase(Si::make_container_sink(request_buffer)); switch (build_request(sink)) { case client_pipeline_request_status::ok: break; case client_pipeline_request_status::failure: return; } } boost::asio::async_write(requests, boost::asio::buffer(request_buffer), warpcoil::cpp::detail::no_response_request_send_operation< typename std::decay<decltype(handler)>::type>(std::move(handler))); } private: std::vector<std::uint8_t> request_buffer; AsyncWriteStream &requests; std::array<std::uint8_t, 512> response_buffer; AsyncReadStream &responses; std::size_t response_buffer_used; }; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2013-2016 Alexander Saprykin <xelfium@gmail.com> * * 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, see <http://www.gnu.org/licenses/>. */ #ifndef PLIBSYS_TESTS_STATIC # define BOOST_TEST_DYN_LINK #endif #define BOOST_TEST_MODULE pmain_test #include "plibsys.h" #ifdef PLIBSYS_TESTS_STATIC # include <boost/test/included/unit_test.hpp> #else # include <boost/test/unit_test.hpp> #endif static pint alloc_counter = 0; static pint realloc_counter = 0; static pint free_counter = 0; extern "C" ppointer pmem_alloc (psize nbytes) { ++alloc_counter; return (ppointer) malloc (nbytes); } extern "C" ppointer pmem_realloc (ppointer block, psize nbytes) { ++realloc_counter; return (ppointer) realloc (block, nbytes); } extern "C" void pmem_free (ppointer block) { ++free_counter; free (block); } BOOST_AUTO_TEST_SUITE (BOOST_TEST_MODULE) BOOST_AUTO_TEST_CASE (pmain_general_test) { p_libsys_init (); p_libsys_shutdown (); } BOOST_AUTO_TEST_CASE (pmain_double_test) { p_libsys_init (); p_libsys_init (); p_libsys_shutdown (); p_libsys_shutdown (); } BOOST_AUTO_TEST_CASE (pmain_vtable_test) { PMemVTable vtable; vtable.free = pmem_free; vtable.malloc = pmem_alloc; vtable.realloc = pmem_realloc; p_libsys_init_full (&vtable); alloc_counter = 0; realloc_counter = 0; free_counter = 0; pchar *buf = (pchar *) p_malloc0 (10); pchar *new_buf = (pchar *) p_realloc ((ppointer) buf, 20); BOOST_REQUIRE (new_buf != NULL); buf = new_buf; p_free (buf); BOOST_CHECK (alloc_counter > 0); BOOST_CHECK (realloc_counter > 0); BOOST_CHECK (free_counter > 0); p_libsys_shutdown (); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>tests: Fix code indentation<commit_after>/* * Copyright (C) 2013-2016 Alexander Saprykin <xelfium@gmail.com> * * 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, see <http://www.gnu.org/licenses/>. */ #ifndef PLIBSYS_TESTS_STATIC # define BOOST_TEST_DYN_LINK #endif #define BOOST_TEST_MODULE pmain_test #include "plibsys.h" #ifdef PLIBSYS_TESTS_STATIC # include <boost/test/included/unit_test.hpp> #else # include <boost/test/unit_test.hpp> #endif static pint alloc_counter = 0; static pint realloc_counter = 0; static pint free_counter = 0; extern "C" ppointer pmem_alloc (psize nbytes) { ++alloc_counter; return (ppointer) malloc (nbytes); } extern "C" ppointer pmem_realloc (ppointer block, psize nbytes) { ++realloc_counter; return (ppointer) realloc (block, nbytes); } extern "C" void pmem_free (ppointer block) { ++free_counter; free (block); } BOOST_AUTO_TEST_SUITE (BOOST_TEST_MODULE) BOOST_AUTO_TEST_CASE (pmain_general_test) { p_libsys_init (); p_libsys_shutdown (); } BOOST_AUTO_TEST_CASE (pmain_double_test) { p_libsys_init (); p_libsys_init (); p_libsys_shutdown (); p_libsys_shutdown (); } BOOST_AUTO_TEST_CASE (pmain_vtable_test) { PMemVTable vtable; vtable.free = pmem_free; vtable.malloc = pmem_alloc; vtable.realloc = pmem_realloc; p_libsys_init_full (&vtable); alloc_counter = 0; realloc_counter = 0; free_counter = 0; pchar *buf = (pchar *) p_malloc0 (10); pchar *new_buf = (pchar *) p_realloc ((ppointer) buf, 20); BOOST_REQUIRE (new_buf != NULL); buf = new_buf; p_free (buf); BOOST_CHECK (alloc_counter > 0); BOOST_CHECK (realloc_counter > 0); BOOST_CHECK (free_counter > 0); p_libsys_shutdown (); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>// v8 #include <v8.h> // node #include <node.h> #include <node_buffer.h> #include <node_version.h> /* dlopen(), dlsym() */ #include <dlfcn.h> // boost #include "utils.hpp" // node-mapnik #include "mapnik_map.hpp" #include "mapnik_projection.hpp" #include "mapnik_layer.hpp" #include "mapnik_datasource.hpp" // mapnik #include <mapnik/version.hpp> #include <mapnik/datasource_cache.hpp> #include <mapnik/font_engine_freetype.hpp> // boost #include <boost/version.hpp> // cairo #if defined(HAVE_CAIRO) #include <cairo-version.h> #endif using namespace node; using namespace v8; static Handle<Value> make_mapnik_symbols_visible(const Arguments& args) { HandleScope scope; if (args.Length() != 1 || !args[0]->IsString()) return ThrowException(Exception::TypeError( String::New("first argument must be a path to a directory holding _mapnik.node"))); String::Utf8Value filename(args[0]->ToString()); void *handle = dlopen(*filename, RTLD_NOW|RTLD_GLOBAL); if (handle == NULL) { return False(); } else { dlclose(handle); return True(); } } static Handle<Value> register_datasources(const Arguments& args) { HandleScope scope; if (args.Length() != 1 || !args[0]->IsString()) return ThrowException(Exception::TypeError( String::New("first argument must be a path to a directory of mapnik input plugins"))); std::vector<std::string> const names_before = mapnik::datasource_cache::plugin_names(); std::string const& path = TOSTR(args[0]); mapnik::datasource_cache::instance()->register_datasources(path); std::vector<std::string> const& names_after = mapnik::datasource_cache::plugin_names(); if (names_after.size() > names_before.size()) return scope.Close(Boolean::New(true)); return scope.Close(Boolean::New(false)); } static Handle<Value> available_input_plugins(const Arguments& args) { HandleScope scope; std::vector<std::string> const& names = mapnik::datasource_cache::plugin_names(); Local<Array> a = Array::New(names.size()); for (unsigned i = 0; i < names.size(); ++i) { a->Set(i, String::New(names[i].c_str())); } return scope.Close(a); } static Handle<Value> register_fonts(const Arguments& args) { HandleScope scope; if (!args.Length() >= 1 || !args[0]->IsString()) return ThrowException(Exception::TypeError( String::New("first argument must be a path to a directory of fonts"))); bool found = false; std::vector<std::string> const names_before = mapnik::freetype_engine::face_names(); // option hash if (args.Length() == 2){ if (!args[1]->IsObject()) return ThrowException(Exception::TypeError( String::New("second argument is optional, but if provided must be an object, eg. { recurse:Boolean }"))); Local<Object> options = args[1]->ToObject(); if (options->Has(String::New("recurse"))) { Local<Value> recurse_opt = options->Get(String::New("recurse")); if (!recurse_opt->IsBoolean()) return ThrowException(Exception::TypeError( String::New("'recurse' must be a Boolean"))); bool recurse = recurse_opt->BooleanValue(); std::string const& path = TOSTR(args[0]); found = mapnik::freetype_engine::register_fonts(path,recurse); } } else { std::string const& path = TOSTR(args[0]); found = mapnik::freetype_engine::register_fonts(path); } std::vector<std::string> const& names_after = mapnik::freetype_engine::face_names(); if (names_after.size() == names_before.size()) found = false; return scope.Close(Boolean::New(found)); } static Handle<Value> available_font_faces(const Arguments& args) { HandleScope scope; std::vector<std::string> const& names = mapnik::freetype_engine::face_names(); Local<Array> a = Array::New(names.size()); for (unsigned i = 0; i < names.size(); ++i) { a->Set(i, String::New(names[i].c_str())); } return scope.Close(a); } static std::string format_version(int version) { std::ostringstream s; s << version/100000 << "." << version/100 % 1000 << "." << version % 100; return s.str(); } extern "C" { static void init (Handle<Object> target) { // module level functions NODE_SET_METHOD(target, "make_mapnik_symbols_visible", make_mapnik_symbols_visible); NODE_SET_METHOD(target, "register_datasources", register_datasources); NODE_SET_METHOD(target, "datasources", available_input_plugins); NODE_SET_METHOD(target, "register_fonts", register_fonts); NODE_SET_METHOD(target, "fonts", available_font_faces); // Map Map::Initialize(target); // Projection Projection::Initialize(target); // Layer Layer::Initialize(target); // Datasource Datasource::Initialize(target); // node-mapnik version target->Set(String::NewSymbol("version"), String::New("0.1.2")); // versions of deps Local<Object> versions = Object::New(); versions->Set(String::NewSymbol("node"), String::New(NODE_VERSION+1)); versions->Set(String::NewSymbol("v8"), String::New(V8::GetVersion())); versions->Set(String::NewSymbol("boost"), String::New(format_version(BOOST_VERSION).c_str())); versions->Set(String::NewSymbol("boost_number"), Integer::New(BOOST_VERSION)); versions->Set(String::NewSymbol("mapnik"), String::New(format_version(MAPNIK_VERSION).c_str())); versions->Set(String::NewSymbol("mapnik_number"), Integer::New(MAPNIK_VERSION)); #if defined(HAVE_CAIRO) std::ostringstream s; s << CAIRO_VERSION_MAJOR << "." << CAIRO_VERSION_MINOR << "." << CAIRO_VERSION_MICRO; versions->Set(String::NewSymbol("cairo"), String::New(s.str().c_str())); #endif target->Set(String::NewSymbol("versions"), versions); // built in support Local<Object> supports = Object::New(); #if defined(HAVE_CAIRO) supports->Set(String::NewSymbol("cairo"), Boolean::New(true)); #else supports->Set(String::NewSymbol("cairo"), Boolean::New(false)); #endif #if defined(HAVE_JPEG) supports->Set(String::NewSymbol("jpeg"), Boolean::New(true)); #else supports->Set(String::NewSymbol("jpeg"), Boolean::New(false)); #endif target->Set(String::NewSymbol("supports"), supports); } NODE_MODULE(_mapnik, init); } <commit_msg>expose function to force garbage collection in v8 (purely for testing)<commit_after>// v8 #include <v8.h> // node #include <node.h> #include <node_buffer.h> #include <node_version.h> /* dlopen(), dlsym() */ #include <dlfcn.h> // boost #include "utils.hpp" // node-mapnik #include "mapnik_map.hpp" #include "mapnik_projection.hpp" #include "mapnik_layer.hpp" #include "mapnik_datasource.hpp" // mapnik #include <mapnik/version.hpp> #include <mapnik/datasource_cache.hpp> #include <mapnik/font_engine_freetype.hpp> // boost #include <boost/version.hpp> // cairo #if defined(HAVE_CAIRO) #include <cairo-version.h> #endif using namespace node; using namespace v8; /** * Optional notification that the embedder is idle. * V8 uses the notification to reduce memory footprint. * This call can be used repeatedly if the embedder remains idle. * Returns true if the embedder should stop calling IdleNotification * until real work has been done. This indicates that V8 has done * as much cleanup as it will be able to do. */ static Handle<Value> gc(const Arguments& args) { HandleScope scope; return scope.Close(Boolean::New(V8::IdleNotification())); } static Handle<Value> make_mapnik_symbols_visible(const Arguments& args) { HandleScope scope; if (args.Length() != 1 || !args[0]->IsString()) return ThrowException(Exception::TypeError( String::New("first argument must be a path to a directory holding _mapnik.node"))); String::Utf8Value filename(args[0]->ToString()); void *handle = dlopen(*filename, RTLD_NOW|RTLD_GLOBAL); if (handle == NULL) { return False(); } else { dlclose(handle); return True(); } } static Handle<Value> register_datasources(const Arguments& args) { HandleScope scope; if (args.Length() != 1 || !args[0]->IsString()) return ThrowException(Exception::TypeError( String::New("first argument must be a path to a directory of mapnik input plugins"))); std::vector<std::string> const names_before = mapnik::datasource_cache::plugin_names(); std::string const& path = TOSTR(args[0]); mapnik::datasource_cache::instance()->register_datasources(path); std::vector<std::string> const& names_after = mapnik::datasource_cache::plugin_names(); if (names_after.size() > names_before.size()) return scope.Close(Boolean::New(true)); return scope.Close(Boolean::New(false)); } static Handle<Value> available_input_plugins(const Arguments& args) { HandleScope scope; std::vector<std::string> const& names = mapnik::datasource_cache::plugin_names(); Local<Array> a = Array::New(names.size()); for (unsigned i = 0; i < names.size(); ++i) { a->Set(i, String::New(names[i].c_str())); } return scope.Close(a); } static Handle<Value> register_fonts(const Arguments& args) { HandleScope scope; if (!args.Length() >= 1 || !args[0]->IsString()) return ThrowException(Exception::TypeError( String::New("first argument must be a path to a directory of fonts"))); bool found = false; std::vector<std::string> const names_before = mapnik::freetype_engine::face_names(); // option hash if (args.Length() == 2){ if (!args[1]->IsObject()) return ThrowException(Exception::TypeError( String::New("second argument is optional, but if provided must be an object, eg. { recurse:Boolean }"))); Local<Object> options = args[1]->ToObject(); if (options->Has(String::New("recurse"))) { Local<Value> recurse_opt = options->Get(String::New("recurse")); if (!recurse_opt->IsBoolean()) return ThrowException(Exception::TypeError( String::New("'recurse' must be a Boolean"))); bool recurse = recurse_opt->BooleanValue(); std::string const& path = TOSTR(args[0]); found = mapnik::freetype_engine::register_fonts(path,recurse); } } else { std::string const& path = TOSTR(args[0]); found = mapnik::freetype_engine::register_fonts(path); } std::vector<std::string> const& names_after = mapnik::freetype_engine::face_names(); if (names_after.size() == names_before.size()) found = false; return scope.Close(Boolean::New(found)); } static Handle<Value> available_font_faces(const Arguments& args) { HandleScope scope; std::vector<std::string> const& names = mapnik::freetype_engine::face_names(); Local<Array> a = Array::New(names.size()); for (unsigned i = 0; i < names.size(); ++i) { a->Set(i, String::New(names[i].c_str())); } return scope.Close(a); } static std::string format_version(int version) { std::ostringstream s; s << version/100000 << "." << version/100 % 1000 << "." << version % 100; return s.str(); } extern "C" { static void init (Handle<Object> target) { // module level functions NODE_SET_METHOD(target, "make_mapnik_symbols_visible", make_mapnik_symbols_visible); NODE_SET_METHOD(target, "register_datasources", register_datasources); NODE_SET_METHOD(target, "datasources", available_input_plugins); NODE_SET_METHOD(target, "register_fonts", register_fonts); NODE_SET_METHOD(target, "fonts", available_font_faces); NODE_SET_METHOD(target, "gc", gc); // Map Map::Initialize(target); // Projection Projection::Initialize(target); // Layer Layer::Initialize(target); // Datasource Datasource::Initialize(target); // node-mapnik version target->Set(String::NewSymbol("version"), String::New("0.1.2")); // versions of deps Local<Object> versions = Object::New(); versions->Set(String::NewSymbol("node"), String::New(NODE_VERSION+1)); versions->Set(String::NewSymbol("v8"), String::New(V8::GetVersion())); versions->Set(String::NewSymbol("boost"), String::New(format_version(BOOST_VERSION).c_str())); versions->Set(String::NewSymbol("boost_number"), Integer::New(BOOST_VERSION)); versions->Set(String::NewSymbol("mapnik"), String::New(format_version(MAPNIK_VERSION).c_str())); versions->Set(String::NewSymbol("mapnik_number"), Integer::New(MAPNIK_VERSION)); #if defined(HAVE_CAIRO) std::ostringstream s; s << CAIRO_VERSION_MAJOR << "." << CAIRO_VERSION_MINOR << "." << CAIRO_VERSION_MICRO; versions->Set(String::NewSymbol("cairo"), String::New(s.str().c_str())); #endif target->Set(String::NewSymbol("versions"), versions); // built in support Local<Object> supports = Object::New(); #if defined(HAVE_CAIRO) supports->Set(String::NewSymbol("cairo"), Boolean::New(true)); #else supports->Set(String::NewSymbol("cairo"), Boolean::New(false)); #endif #if defined(HAVE_JPEG) supports->Set(String::NewSymbol("jpeg"), Boolean::New(true)); #else supports->Set(String::NewSymbol("jpeg"), Boolean::New(false)); #endif target->Set(String::NewSymbol("supports"), supports); } NODE_MODULE(_mapnik, init); } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "compaction_manager.hh" #include "sstables/compaction_manager.hh" #include "api/api-doc/compaction_manager.json.hh" #include "db/system_keyspace.hh" #include "column_family.hh" #include <utility> namespace api { namespace cm = httpd::compaction_manager_json; using namespace json; static future<json::json_return_type> get_cm_stats(http_context& ctx, int64_t compaction_manager::stats::*f) { return ctx.db.map_reduce0([f](database& db) { return db.get_compaction_manager().get_stats().*f; }, int64_t(0), std::plus<int64_t>()).then([](const int64_t& res) { return make_ready_future<json::json_return_type>(res); }); } static std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash> sum_pending_tasks(std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>&& a, const std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>& b) { for (auto&& i : b) { if (i.second) { a[i.first] += i.second; } } return std::move(a); } void set_compaction_manager(http_context& ctx, routes& r) { cm::get_compactions.set(r, [&ctx] (std::unique_ptr<request> req) { return ctx.db.map_reduce0([](database& db) { std::vector<cm::summary> summaries; const compaction_manager& cm = db.get_compaction_manager(); for (const auto& c : cm.get_compactions()) { cm::summary s; s.ks = c->ks_name; s.cf = c->cf_name; s.unit = "keys"; s.task_type = sstables::compaction_name(c->type); s.completed = c->total_keys_written; s.total = c->total_partitions; summaries.push_back(std::move(s)); } return summaries; }, std::vector<cm::summary>(), concat<cm::summary>).then([](const std::vector<cm::summary>& res) { return make_ready_future<json::json_return_type>(res); }); }); cm::get_pending_tasks_by_table.set(r, [&ctx] (std::unique_ptr<request> req) { return ctx.db.map_reduce0([&ctx](database& db) { return do_with(std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>(), [&ctx, &db](std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>& tasks) { return do_for_each(db.get_column_families(), [&tasks](const std::pair<utils::UUID, seastar::lw_shared_ptr<table>>& i) { table& cf = *i.second.get(); tasks[std::make_pair(cf.schema()->ks_name(), cf.schema()->cf_name())] = cf.get_compaction_strategy().estimated_pending_compactions(cf); return make_ready_future<>(); }).then([&tasks] { return std::move(tasks); }); }); }, std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>(), sum_pending_tasks).then( [](const std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>& task_map) { std::vector<cm::pending_compaction> res; res.reserve(task_map.size()); for (auto i : task_map) { cm::pending_compaction task; task.ks = i.first.first; task.cf = i.first.second; task.task = i.second; res.emplace_back(std::move(task)); } return make_ready_future<json::json_return_type>(res); }); }); cm::force_user_defined_compaction.set(r, [] (std::unique_ptr<request> req) { //TBD // FIXME warn(unimplemented::cause::API); return make_ready_future<json::json_return_type>(json_void()); }); cm::stop_compaction.set(r, [&ctx] (std::unique_ptr<request> req) { auto type = req->get_query_param("type"); return ctx.db.invoke_on_all([type] (database& db) { auto& cm = db.get_compaction_manager(); cm.stop_compaction(type); }).then([] { return make_ready_future<json::json_return_type>(json_void()); }); }); cm::get_pending_tasks.set(r, [&ctx] (std::unique_ptr<request> req) { return map_reduce_cf(ctx, int64_t(0), [](column_family& cf) { return cf.get_compaction_strategy().estimated_pending_compactions(cf); }, std::plus<int64_t>()); }); cm::get_completed_tasks.set(r, [&ctx] (std::unique_ptr<request> req) { return get_cm_stats(ctx, &compaction_manager::stats::completed_tasks); }); cm::get_total_compactions_completed.set(r, [] (std::unique_ptr<request> req) { // FIXME // We are currently dont have an API for compaction // so returning a 0 as the number of total compaction is ok return make_ready_future<json::json_return_type>(0); }); cm::get_bytes_compacted.set(r, [] (std::unique_ptr<request> req) { //TBD // FIXME warn(unimplemented::cause::API); return make_ready_future<json::json_return_type>(0); }); cm::get_compaction_history.set(r, [] (std::unique_ptr<request> req) { std::function<future<>(output_stream<char>&&)> f = [](output_stream<char>&& s) { return do_with(output_stream<char>(std::move(s)), true, [] (output_stream<char>& s, bool& first){ return s.write("[").then([&s, &first] { return db::system_keyspace::get_compaction_history([&s, &first](const db::system_keyspace::compaction_history_entry& entry) mutable { cm::history h; h.id = entry.id.to_sstring(); h.ks = std::move(entry.ks); h.cf = std::move(entry.cf); h.compacted_at = entry.compacted_at; h.bytes_in = entry.bytes_in; h.bytes_out = entry.bytes_out; for (auto it : entry.rows_merged) { httpd::compaction_manager_json::row_merged e; e.key = it.first; e.value = it.second; h.rows_merged.push(std::move(e)); } auto fut = first ? make_ready_future<>() : s.write(", "); first = false; return fut.then([&s, h = std::move(h)] { return formatter::write(s, h); }); }).then([&s] { return s.write("]").then([&s] { return s.close(); }); }); }); }); }; return make_ready_future<json::json_return_type>(std::move(f)); }); cm::get_compaction_info.set(r, [] (std::unique_ptr<request> req) { //TBD // FIXME warn(unimplemented::cause::API); std::vector<cm::compaction_info> res; return make_ready_future<json::json_return_type>(res); }); } } <commit_msg>api/compaction_manager: indentation<commit_after>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "compaction_manager.hh" #include "sstables/compaction_manager.hh" #include "api/api-doc/compaction_manager.json.hh" #include "db/system_keyspace.hh" #include "column_family.hh" #include <utility> namespace api { namespace cm = httpd::compaction_manager_json; using namespace json; static future<json::json_return_type> get_cm_stats(http_context& ctx, int64_t compaction_manager::stats::*f) { return ctx.db.map_reduce0([f](database& db) { return db.get_compaction_manager().get_stats().*f; }, int64_t(0), std::plus<int64_t>()).then([](const int64_t& res) { return make_ready_future<json::json_return_type>(res); }); } static std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash> sum_pending_tasks(std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>&& a, const std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>& b) { for (auto&& i : b) { if (i.second) { a[i.first] += i.second; } } return std::move(a); } void set_compaction_manager(http_context& ctx, routes& r) { cm::get_compactions.set(r, [&ctx] (std::unique_ptr<request> req) { return ctx.db.map_reduce0([](database& db) { std::vector<cm::summary> summaries; const compaction_manager& cm = db.get_compaction_manager(); for (const auto& c : cm.get_compactions()) { cm::summary s; s.ks = c->ks_name; s.cf = c->cf_name; s.unit = "keys"; s.task_type = sstables::compaction_name(c->type); s.completed = c->total_keys_written; s.total = c->total_partitions; summaries.push_back(std::move(s)); } return summaries; }, std::vector<cm::summary>(), concat<cm::summary>).then([](const std::vector<cm::summary>& res) { return make_ready_future<json::json_return_type>(res); }); }); cm::get_pending_tasks_by_table.set(r, [&ctx] (std::unique_ptr<request> req) { return ctx.db.map_reduce0([&ctx](database& db) { return do_with(std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>(), [&ctx, &db](std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>& tasks) { return do_for_each(db.get_column_families(), [&tasks](const std::pair<utils::UUID, seastar::lw_shared_ptr<table>>& i) { table& cf = *i.second.get(); tasks[std::make_pair(cf.schema()->ks_name(), cf.schema()->cf_name())] = cf.get_compaction_strategy().estimated_pending_compactions(cf); return make_ready_future<>(); }).then([&tasks] { return std::move(tasks); }); }); }, std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>(), sum_pending_tasks).then( [](const std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>& task_map) { std::vector<cm::pending_compaction> res; res.reserve(task_map.size()); for (auto i : task_map) { cm::pending_compaction task; task.ks = i.first.first; task.cf = i.first.second; task.task = i.second; res.emplace_back(std::move(task)); } return make_ready_future<json::json_return_type>(res); }); }); cm::force_user_defined_compaction.set(r, [] (std::unique_ptr<request> req) { //TBD // FIXME warn(unimplemented::cause::API); return make_ready_future<json::json_return_type>(json_void()); }); cm::stop_compaction.set(r, [&ctx] (std::unique_ptr<request> req) { auto type = req->get_query_param("type"); return ctx.db.invoke_on_all([type] (database& db) { auto& cm = db.get_compaction_manager(); cm.stop_compaction(type); }).then([] { return make_ready_future<json::json_return_type>(json_void()); }); }); cm::get_pending_tasks.set(r, [&ctx] (std::unique_ptr<request> req) { return map_reduce_cf(ctx, int64_t(0), [](column_family& cf) { return cf.get_compaction_strategy().estimated_pending_compactions(cf); }, std::plus<int64_t>()); }); cm::get_completed_tasks.set(r, [&ctx] (std::unique_ptr<request> req) { return get_cm_stats(ctx, &compaction_manager::stats::completed_tasks); }); cm::get_total_compactions_completed.set(r, [] (std::unique_ptr<request> req) { // FIXME // We are currently dont have an API for compaction // so returning a 0 as the number of total compaction is ok return make_ready_future<json::json_return_type>(0); }); cm::get_bytes_compacted.set(r, [] (std::unique_ptr<request> req) { //TBD // FIXME warn(unimplemented::cause::API); return make_ready_future<json::json_return_type>(0); }); cm::get_compaction_history.set(r, [] (std::unique_ptr<request> req) { std::function<future<>(output_stream<char>&&)> f = [](output_stream<char>&& s) { return do_with(output_stream<char>(std::move(s)), true, [] (output_stream<char>& s, bool& first){ return s.write("[").then([&s, &first] { return db::system_keyspace::get_compaction_history([&s, &first](const db::system_keyspace::compaction_history_entry& entry) mutable { cm::history h; h.id = entry.id.to_sstring(); h.ks = std::move(entry.ks); h.cf = std::move(entry.cf); h.compacted_at = entry.compacted_at; h.bytes_in = entry.bytes_in; h.bytes_out = entry.bytes_out; for (auto it : entry.rows_merged) { httpd::compaction_manager_json::row_merged e; e.key = it.first; e.value = it.second; h.rows_merged.push(std::move(e)); } auto fut = first ? make_ready_future<>() : s.write(", "); first = false; return fut.then([&s, h = std::move(h)] { return formatter::write(s, h); }); }).then([&s] { return s.write("]").then([&s] { return s.close(); }); }); }); }); }; return make_ready_future<json::json_return_type>(std::move(f)); }); cm::get_compaction_info.set(r, [] (std::unique_ptr<request> req) { //TBD // FIXME warn(unimplemented::cause::API); std::vector<cm::compaction_info> res; return make_ready_future<json::json_return_type>(res); }); } } <|endoftext|>
<commit_before>// // Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Config.cpp: Implements the egl::Config class, describing the format, type // and size for an egl::Surface. Implements EGLConfig and related functionality. // [EGL 1.4] section 3.4 page 15. #include "libEGL/Config.h" #include <algorithm> #include <vector> #include "common/debug.h" using namespace std; namespace egl { Config::Config(D3DDISPLAYMODE displayMode, EGLint minInterval, EGLint maxInterval, D3DFORMAT renderTargetFormat, D3DFORMAT depthStencilFormat, EGLint multiSample) : mDisplayMode(displayMode), mRenderTargetFormat(renderTargetFormat), mDepthStencilFormat(depthStencilFormat), mMultiSample(multiSample) { set(displayMode, minInterval, maxInterval, renderTargetFormat, depthStencilFormat, multiSample); } void Config::setDefaults() { mBufferSize = 0; mRedSize = 0; mGreenSize = 0; mBlueSize = 0; mLuminanceSize = 0; mAlphaSize = 0; mAlphaMaskSize = 0; mBindToTextureRGB = EGL_DONT_CARE; mBindToTextureRGBA = EGL_DONT_CARE; mColorBufferType = EGL_RGB_BUFFER; mConfigCaveat = EGL_DONT_CARE; mConfigID = EGL_DONT_CARE; mConformant = 0; mDepthSize = 0; mLevel = 0; mMatchNativePixmap = EGL_NONE; mMaxPBufferWidth = 0; mMaxPBufferHeight = 0; mMaxPBufferPixels = 0; mMaxSwapInterval = EGL_DONT_CARE; mMinSwapInterval = EGL_DONT_CARE; mNativeRenderable = EGL_DONT_CARE; mNativeVisualID = 0; mNativeVisualType = EGL_DONT_CARE; mRenderableType = EGL_OPENGL_ES_BIT; mSampleBuffers = 0; mSamples = 0; mStencilSize = 0; mSurfaceType = EGL_WINDOW_BIT; mTransparentType = EGL_NONE; mTransparentRedValue = EGL_DONT_CARE; mTransparentGreenValue = EGL_DONT_CARE; mTransparentBlueValue = EGL_DONT_CARE; } void Config::set(D3DDISPLAYMODE displayMode, EGLint minInterval, EGLint maxInterval, D3DFORMAT renderTargetFormat, D3DFORMAT depthStencilFormat, EGLint multiSample) { switch (renderTargetFormat) { case D3DFMT_A1R5G5B5: mBufferSize = 16; mRedSize = 5; mGreenSize = 5; mBlueSize = 5; mAlphaSize = 1; break; case D3DFMT_A2R10G10B10: mBufferSize = 32; mRedSize = 10; mGreenSize = 10; mBlueSize = 10; mAlphaSize = 2; break; case D3DFMT_A8R8G8B8: mBufferSize = 32; mRedSize = 8; mGreenSize = 8; mBlueSize = 8; mAlphaSize = 8; break; case D3DFMT_R5G6B5: mBufferSize = 16; mRedSize = 5; mGreenSize = 6; mBlueSize = 5; mAlphaSize = 0; break; case D3DFMT_X1R5G5B5: mBufferSize = 16; mRedSize = 5; mGreenSize = 5; mBlueSize = 5; mAlphaSize = 0; break; case D3DFMT_X8R8G8B8: mBufferSize = 32; mRedSize = 8; mGreenSize = 8; mBlueSize = 8; mAlphaSize = 0; break; default: UNREACHABLE(); // Other formats should not be valid } mLuminanceSize = 0; mAlphaMaskSize = 0; mBindToTextureRGB = EGL_FALSE; mBindToTextureRGBA = EGL_FALSE; mColorBufferType = EGL_RGB_BUFFER; mConfigCaveat = (displayMode.Format == renderTargetFormat) ? EGL_NONE : EGL_SLOW_CONFIG; mConfigID = 0; mConformant = EGL_OPENGL_ES2_BIT; switch (depthStencilFormat) { // case D3DFMT_D16_LOCKABLE: // mDepthSize = 16; // mStencilSize = 0; // break; case D3DFMT_D32: mDepthSize = 32; mStencilSize = 0; break; case D3DFMT_D15S1: mDepthSize = 15; mStencilSize = 1; break; case D3DFMT_D24S8: mDepthSize = 24; mStencilSize = 8; break; case D3DFMT_D24X8: mDepthSize = 24; mStencilSize = 0; break; case D3DFMT_D24X4S4: mDepthSize = 24; mStencilSize = 4; break; case D3DFMT_D16: mDepthSize = 16; mStencilSize = 0; break; // case D3DFMT_D32F_LOCKABLE: // mDepthSize = 32; // mStencilSize = 0; // break; // case D3DFMT_D24FS8: // mDepthSize = 24; // mStencilSize = 8; // break; default: UNREACHABLE(); } mLevel = 0; mMatchNativePixmap = EGL_NONE; mMaxPBufferWidth = 0; mMaxPBufferHeight = 0; mMaxPBufferPixels = 0; mMaxSwapInterval = maxInterval; mMinSwapInterval = minInterval; mNativeRenderable = EGL_FALSE; mNativeVisualID = 0; mNativeVisualType = 0; mRenderableType = EGL_OPENGL_ES2_BIT; mSampleBuffers = multiSample ? 1 : 0; mSamples = multiSample; mSurfaceType = EGL_PBUFFER_BIT | EGL_WINDOW_BIT | EGL_SWAP_BEHAVIOR_PRESERVED_BIT; mTransparentType = EGL_NONE; mTransparentRedValue = 0; mTransparentGreenValue = 0; mTransparentBlueValue = 0; } EGLConfig Config::getHandle() const { return (EGLConfig)(size_t)mConfigID; } SortConfig::SortConfig(const EGLint *attribList) : mWantRed(false), mWantGreen(false), mWantBlue(false), mWantAlpha(false), mWantLuminance(false) { scanForWantedComponents(attribList); } void SortConfig::scanForWantedComponents(const EGLint *attribList) { // [EGL] section 3.4.1 page 24 // Sorting rule #3: by larger total number of color bits, not considering // components that are 0 or don't-care. for (const EGLint *attr = attribList; attr[0] != EGL_NONE; attr += 2) { if (attr[1] != 0 && attr[1] != EGL_DONT_CARE) { switch (attr[0]) { case EGL_RED_SIZE: mWantRed = true; break; case EGL_GREEN_SIZE: mWantGreen = true; break; case EGL_BLUE_SIZE: mWantBlue = true; break; case EGL_ALPHA_SIZE: mWantAlpha = true; break; case EGL_LUMINANCE_SIZE: mWantLuminance = true; break; } } } } EGLint SortConfig::wantedComponentsSize(const Config &config) const { EGLint total = 0; if (mWantRed) total += config.mRedSize; if (mWantGreen) total += config.mGreenSize; if (mWantBlue) total += config.mBlueSize; if (mWantAlpha) total += config.mAlphaSize; if (mWantLuminance) total += config.mLuminanceSize; return total; } bool SortConfig::operator()(const Config *x, const Config *y) const { return (*this)(*x, *y); } bool SortConfig::operator()(const Config &x, const Config &y) const { #define SORT(attribute) \ if (x.attribute != y.attribute) \ { \ return x.attribute < y.attribute; \ } META_ASSERT(EGL_NONE < EGL_SLOW_CONFIG && EGL_SLOW_CONFIG < EGL_NON_CONFORMANT_CONFIG); SORT(mConfigCaveat); META_ASSERT(EGL_RGB_BUFFER < EGL_LUMINANCE_BUFFER); SORT(mColorBufferType); // By larger total number of color bits, only considering those that are requested to be > 0. EGLint xComponentsSize = wantedComponentsSize(x); EGLint yComponentsSize = wantedComponentsSize(y); if (xComponentsSize != yComponentsSize) { return xComponentsSize > yComponentsSize; } SORT(mBufferSize); SORT(mSampleBuffers); SORT(mSamples); SORT(mDepthSize); SORT(mStencilSize); SORT(mAlphaMaskSize); SORT(mNativeVisualType); SORT(mConfigID); #undef SORT return false; } // We'd like to use SortConfig to also eliminate duplicate configs. // This works as long as we never have two configs with different per-RGB-component layouts, // but the same total. // 5551 and 565 are different because R+G+B is different. // 5551 and 555 are different because bufferSize is different. const EGLint ConfigSet::mSortAttribs[] = { EGL_RED_SIZE, 1, EGL_GREEN_SIZE, 1, EGL_BLUE_SIZE, 1, EGL_LUMINANCE_SIZE, 1, // BUT NOT ALPHA EGL_NONE }; ConfigSet::ConfigSet() : mSet(SortConfig(mSortAttribs)) { } void ConfigSet::add(D3DDISPLAYMODE displayMode, EGLint minSwapInterval, EGLint maxSwapInterval, D3DFORMAT renderTargetFormat, D3DFORMAT depthStencilFormat, EGLint multiSample) { Config config(displayMode, minSwapInterval, maxSwapInterval, renderTargetFormat, depthStencilFormat, multiSample); mSet.insert(config); } void ConfigSet::enumerate() { EGLint index = 1; for (Iterator config = mSet.begin(); config != mSet.end(); config++) { config->mConfigID = index; index++; } } size_t ConfigSet::size() const { return mSet.size(); } bool ConfigSet::getConfigs(EGLConfig *configs, const EGLint *attribList, EGLint configSize, EGLint *numConfig) { if (configs) { vector<const Config*> passed; passed.reserve(mSet.size()); for (Iterator config = mSet.begin(); config != mSet.end(); config++) { bool match = true; const EGLint *attribute = attribList; while (attribute[0] != EGL_NONE) { switch (attribute[0]) { case EGL_BUFFER_SIZE: match = config->mBufferSize >= attribute[1]; break; case EGL_ALPHA_SIZE: match = config->mAlphaSize >= attribute[1]; break; case EGL_BLUE_SIZE: match = config->mBlueSize >= attribute[1]; break; case EGL_GREEN_SIZE: match = config->mGreenSize >= attribute[1]; break; case EGL_RED_SIZE: match = config->mRedSize >= attribute[1]; break; case EGL_DEPTH_SIZE: match = config->mDepthSize >= attribute[1]; break; case EGL_STENCIL_SIZE: match = config->mStencilSize >= attribute[1]; break; case EGL_CONFIG_CAVEAT: match = config->mConfigCaveat == attribute[1]; break; case EGL_CONFIG_ID: match = config->mConfigID == attribute[1]; break; case EGL_LEVEL: match = config->mLevel >= attribute[1]; break; case EGL_NATIVE_RENDERABLE: match = config->mNativeRenderable == attribute[1]; break; case EGL_NATIVE_VISUAL_TYPE: match = config->mNativeVisualType == attribute[1]; break; case EGL_SAMPLES: match = config->mSamples >= attribute[1]; break; case EGL_SAMPLE_BUFFERS: match = config->mSampleBuffers >= attribute[1]; break; case EGL_SURFACE_TYPE: match = (config->mSurfaceType & attribute[1]) == attribute[1]; break; case EGL_TRANSPARENT_TYPE: match = config->mTransparentType == attribute[1]; break; case EGL_TRANSPARENT_BLUE_VALUE: match = config->mTransparentBlueValue == attribute[1]; break; case EGL_TRANSPARENT_GREEN_VALUE: match = config->mTransparentGreenValue == attribute[1]; break; case EGL_TRANSPARENT_RED_VALUE: match = config->mTransparentRedValue == attribute[1]; break; case EGL_BIND_TO_TEXTURE_RGB: match = config->mBindToTextureRGB == attribute[1]; break; case EGL_BIND_TO_TEXTURE_RGBA: match = config->mBindToTextureRGBA == attribute[1]; break; case EGL_MIN_SWAP_INTERVAL: match = config->mMinSwapInterval == attribute[1]; break; case EGL_MAX_SWAP_INTERVAL: match = config->mMaxSwapInterval == attribute[1]; break; case EGL_LUMINANCE_SIZE: match = config->mLuminanceSize >= attribute[1]; break; case EGL_ALPHA_MASK_SIZE: match = config->mAlphaMaskSize >= attribute[1]; break; case EGL_COLOR_BUFFER_TYPE: match = config->mColorBufferType == attribute[1]; break; case EGL_RENDERABLE_TYPE: match = (config->mRenderableType & attribute[1]) == attribute[1]; break; case EGL_MATCH_NATIVE_PIXMAP: match = false; UNIMPLEMENTED(); break; case EGL_CONFORMANT: match = (config->mConformant & attribute[1]) == attribute[1]; break; default: return false; } if (!match) { break; } attribute += 2; } if (match) { passed.push_back(&*config); } } sort(passed.begin(), passed.end(), SortConfig(attribList)); EGLint index; for (index = 0; index < configSize && index < static_cast<EGLint>(passed.size()); index++) { configs[index] = passed[index]->getHandle(); } *numConfig = index; } else { *numConfig = (EGLint)mSet.size(); } return true; } const egl::Config *ConfigSet::get(EGLConfig configHandle) { for (Iterator config = mSet.begin(); config != mSet.end(); config++) { if (config->getHandle() == configHandle) { return &(*config); } } return NULL; } } <commit_msg>eglChooseConfig must return filtered size when configs is NULL.<commit_after>// // Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Config.cpp: Implements the egl::Config class, describing the format, type // and size for an egl::Surface. Implements EGLConfig and related functionality. // [EGL 1.4] section 3.4 page 15. #include "libEGL/Config.h" #include <algorithm> #include <vector> #include "common/debug.h" using namespace std; namespace egl { Config::Config(D3DDISPLAYMODE displayMode, EGLint minInterval, EGLint maxInterval, D3DFORMAT renderTargetFormat, D3DFORMAT depthStencilFormat, EGLint multiSample) : mDisplayMode(displayMode), mRenderTargetFormat(renderTargetFormat), mDepthStencilFormat(depthStencilFormat), mMultiSample(multiSample) { set(displayMode, minInterval, maxInterval, renderTargetFormat, depthStencilFormat, multiSample); } void Config::setDefaults() { mBufferSize = 0; mRedSize = 0; mGreenSize = 0; mBlueSize = 0; mLuminanceSize = 0; mAlphaSize = 0; mAlphaMaskSize = 0; mBindToTextureRGB = EGL_DONT_CARE; mBindToTextureRGBA = EGL_DONT_CARE; mColorBufferType = EGL_RGB_BUFFER; mConfigCaveat = EGL_DONT_CARE; mConfigID = EGL_DONT_CARE; mConformant = 0; mDepthSize = 0; mLevel = 0; mMatchNativePixmap = EGL_NONE; mMaxPBufferWidth = 0; mMaxPBufferHeight = 0; mMaxPBufferPixels = 0; mMaxSwapInterval = EGL_DONT_CARE; mMinSwapInterval = EGL_DONT_CARE; mNativeRenderable = EGL_DONT_CARE; mNativeVisualID = 0; mNativeVisualType = EGL_DONT_CARE; mRenderableType = EGL_OPENGL_ES_BIT; mSampleBuffers = 0; mSamples = 0; mStencilSize = 0; mSurfaceType = EGL_WINDOW_BIT; mTransparentType = EGL_NONE; mTransparentRedValue = EGL_DONT_CARE; mTransparentGreenValue = EGL_DONT_CARE; mTransparentBlueValue = EGL_DONT_CARE; } void Config::set(D3DDISPLAYMODE displayMode, EGLint minInterval, EGLint maxInterval, D3DFORMAT renderTargetFormat, D3DFORMAT depthStencilFormat, EGLint multiSample) { switch (renderTargetFormat) { case D3DFMT_A1R5G5B5: mBufferSize = 16; mRedSize = 5; mGreenSize = 5; mBlueSize = 5; mAlphaSize = 1; break; case D3DFMT_A2R10G10B10: mBufferSize = 32; mRedSize = 10; mGreenSize = 10; mBlueSize = 10; mAlphaSize = 2; break; case D3DFMT_A8R8G8B8: mBufferSize = 32; mRedSize = 8; mGreenSize = 8; mBlueSize = 8; mAlphaSize = 8; break; case D3DFMT_R5G6B5: mBufferSize = 16; mRedSize = 5; mGreenSize = 6; mBlueSize = 5; mAlphaSize = 0; break; case D3DFMT_X1R5G5B5: mBufferSize = 16; mRedSize = 5; mGreenSize = 5; mBlueSize = 5; mAlphaSize = 0; break; case D3DFMT_X8R8G8B8: mBufferSize = 32; mRedSize = 8; mGreenSize = 8; mBlueSize = 8; mAlphaSize = 0; break; default: UNREACHABLE(); // Other formats should not be valid } mLuminanceSize = 0; mAlphaMaskSize = 0; mBindToTextureRGB = EGL_FALSE; mBindToTextureRGBA = EGL_FALSE; mColorBufferType = EGL_RGB_BUFFER; mConfigCaveat = (displayMode.Format == renderTargetFormat) ? EGL_NONE : EGL_SLOW_CONFIG; mConfigID = 0; mConformant = EGL_OPENGL_ES2_BIT; switch (depthStencilFormat) { // case D3DFMT_D16_LOCKABLE: // mDepthSize = 16; // mStencilSize = 0; // break; case D3DFMT_D32: mDepthSize = 32; mStencilSize = 0; break; case D3DFMT_D15S1: mDepthSize = 15; mStencilSize = 1; break; case D3DFMT_D24S8: mDepthSize = 24; mStencilSize = 8; break; case D3DFMT_D24X8: mDepthSize = 24; mStencilSize = 0; break; case D3DFMT_D24X4S4: mDepthSize = 24; mStencilSize = 4; break; case D3DFMT_D16: mDepthSize = 16; mStencilSize = 0; break; // case D3DFMT_D32F_LOCKABLE: // mDepthSize = 32; // mStencilSize = 0; // break; // case D3DFMT_D24FS8: // mDepthSize = 24; // mStencilSize = 8; // break; default: UNREACHABLE(); } mLevel = 0; mMatchNativePixmap = EGL_NONE; mMaxPBufferWidth = 0; mMaxPBufferHeight = 0; mMaxPBufferPixels = 0; mMaxSwapInterval = maxInterval; mMinSwapInterval = minInterval; mNativeRenderable = EGL_FALSE; mNativeVisualID = 0; mNativeVisualType = 0; mRenderableType = EGL_OPENGL_ES2_BIT; mSampleBuffers = multiSample ? 1 : 0; mSamples = multiSample; mSurfaceType = EGL_PBUFFER_BIT | EGL_WINDOW_BIT | EGL_SWAP_BEHAVIOR_PRESERVED_BIT; mTransparentType = EGL_NONE; mTransparentRedValue = 0; mTransparentGreenValue = 0; mTransparentBlueValue = 0; } EGLConfig Config::getHandle() const { return (EGLConfig)(size_t)mConfigID; } SortConfig::SortConfig(const EGLint *attribList) : mWantRed(false), mWantGreen(false), mWantBlue(false), mWantAlpha(false), mWantLuminance(false) { scanForWantedComponents(attribList); } void SortConfig::scanForWantedComponents(const EGLint *attribList) { // [EGL] section 3.4.1 page 24 // Sorting rule #3: by larger total number of color bits, not considering // components that are 0 or don't-care. for (const EGLint *attr = attribList; attr[0] != EGL_NONE; attr += 2) { if (attr[1] != 0 && attr[1] != EGL_DONT_CARE) { switch (attr[0]) { case EGL_RED_SIZE: mWantRed = true; break; case EGL_GREEN_SIZE: mWantGreen = true; break; case EGL_BLUE_SIZE: mWantBlue = true; break; case EGL_ALPHA_SIZE: mWantAlpha = true; break; case EGL_LUMINANCE_SIZE: mWantLuminance = true; break; } } } } EGLint SortConfig::wantedComponentsSize(const Config &config) const { EGLint total = 0; if (mWantRed) total += config.mRedSize; if (mWantGreen) total += config.mGreenSize; if (mWantBlue) total += config.mBlueSize; if (mWantAlpha) total += config.mAlphaSize; if (mWantLuminance) total += config.mLuminanceSize; return total; } bool SortConfig::operator()(const Config *x, const Config *y) const { return (*this)(*x, *y); } bool SortConfig::operator()(const Config &x, const Config &y) const { #define SORT(attribute) \ if (x.attribute != y.attribute) \ { \ return x.attribute < y.attribute; \ } META_ASSERT(EGL_NONE < EGL_SLOW_CONFIG && EGL_SLOW_CONFIG < EGL_NON_CONFORMANT_CONFIG); SORT(mConfigCaveat); META_ASSERT(EGL_RGB_BUFFER < EGL_LUMINANCE_BUFFER); SORT(mColorBufferType); // By larger total number of color bits, only considering those that are requested to be > 0. EGLint xComponentsSize = wantedComponentsSize(x); EGLint yComponentsSize = wantedComponentsSize(y); if (xComponentsSize != yComponentsSize) { return xComponentsSize > yComponentsSize; } SORT(mBufferSize); SORT(mSampleBuffers); SORT(mSamples); SORT(mDepthSize); SORT(mStencilSize); SORT(mAlphaMaskSize); SORT(mNativeVisualType); SORT(mConfigID); #undef SORT return false; } // We'd like to use SortConfig to also eliminate duplicate configs. // This works as long as we never have two configs with different per-RGB-component layouts, // but the same total. // 5551 and 565 are different because R+G+B is different. // 5551 and 555 are different because bufferSize is different. const EGLint ConfigSet::mSortAttribs[] = { EGL_RED_SIZE, 1, EGL_GREEN_SIZE, 1, EGL_BLUE_SIZE, 1, EGL_LUMINANCE_SIZE, 1, // BUT NOT ALPHA EGL_NONE }; ConfigSet::ConfigSet() : mSet(SortConfig(mSortAttribs)) { } void ConfigSet::add(D3DDISPLAYMODE displayMode, EGLint minSwapInterval, EGLint maxSwapInterval, D3DFORMAT renderTargetFormat, D3DFORMAT depthStencilFormat, EGLint multiSample) { Config config(displayMode, minSwapInterval, maxSwapInterval, renderTargetFormat, depthStencilFormat, multiSample); mSet.insert(config); } void ConfigSet::enumerate() { EGLint index = 1; for (Iterator config = mSet.begin(); config != mSet.end(); config++) { config->mConfigID = index; index++; } } size_t ConfigSet::size() const { return mSet.size(); } bool ConfigSet::getConfigs(EGLConfig *configs, const EGLint *attribList, EGLint configSize, EGLint *numConfig) { vector<const Config*> passed; passed.reserve(mSet.size()); for (Iterator config = mSet.begin(); config != mSet.end(); config++) { bool match = true; const EGLint *attribute = attribList; while (attribute[0] != EGL_NONE) { switch (attribute[0]) { case EGL_BUFFER_SIZE: match = config->mBufferSize >= attribute[1]; break; case EGL_ALPHA_SIZE: match = config->mAlphaSize >= attribute[1]; break; case EGL_BLUE_SIZE: match = config->mBlueSize >= attribute[1]; break; case EGL_GREEN_SIZE: match = config->mGreenSize >= attribute[1]; break; case EGL_RED_SIZE: match = config->mRedSize >= attribute[1]; break; case EGL_DEPTH_SIZE: match = config->mDepthSize >= attribute[1]; break; case EGL_STENCIL_SIZE: match = config->mStencilSize >= attribute[1]; break; case EGL_CONFIG_CAVEAT: match = config->mConfigCaveat == attribute[1]; break; case EGL_CONFIG_ID: match = config->mConfigID == attribute[1]; break; case EGL_LEVEL: match = config->mLevel >= attribute[1]; break; case EGL_NATIVE_RENDERABLE: match = config->mNativeRenderable == attribute[1]; break; case EGL_NATIVE_VISUAL_TYPE: match = config->mNativeVisualType == attribute[1]; break; case EGL_SAMPLES: match = config->mSamples >= attribute[1]; break; case EGL_SAMPLE_BUFFERS: match = config->mSampleBuffers >= attribute[1]; break; case EGL_SURFACE_TYPE: match = (config->mSurfaceType & attribute[1]) == attribute[1]; break; case EGL_TRANSPARENT_TYPE: match = config->mTransparentType == attribute[1]; break; case EGL_TRANSPARENT_BLUE_VALUE: match = config->mTransparentBlueValue == attribute[1]; break; case EGL_TRANSPARENT_GREEN_VALUE: match = config->mTransparentGreenValue == attribute[1]; break; case EGL_TRANSPARENT_RED_VALUE: match = config->mTransparentRedValue == attribute[1]; break; case EGL_BIND_TO_TEXTURE_RGB: match = config->mBindToTextureRGB == attribute[1]; break; case EGL_BIND_TO_TEXTURE_RGBA: match = config->mBindToTextureRGBA == attribute[1]; break; case EGL_MIN_SWAP_INTERVAL: match = config->mMinSwapInterval == attribute[1]; break; case EGL_MAX_SWAP_INTERVAL: match = config->mMaxSwapInterval == attribute[1]; break; case EGL_LUMINANCE_SIZE: match = config->mLuminanceSize >= attribute[1]; break; case EGL_ALPHA_MASK_SIZE: match = config->mAlphaMaskSize >= attribute[1]; break; case EGL_COLOR_BUFFER_TYPE: match = config->mColorBufferType == attribute[1]; break; case EGL_RENDERABLE_TYPE: match = (config->mRenderableType & attribute[1]) == attribute[1]; break; case EGL_MATCH_NATIVE_PIXMAP: match = false; UNIMPLEMENTED(); break; case EGL_CONFORMANT: match = (config->mConformant & attribute[1]) == attribute[1]; break; default: return false; } if (!match) { break; } attribute += 2; } if (match) { passed.push_back(&*config); } } if (configs) { sort(passed.begin(), passed.end(), SortConfig(attribList)); EGLint index; for (index = 0; index < configSize && index < static_cast<EGLint>(passed.size()); index++) { configs[index] = passed[index]->getHandle(); } *numConfig = index; } else { *numConfig = passed.size(); } return true; } const egl::Config *ConfigSet::get(EGLConfig configHandle) { for (Iterator config = mSet.begin(); config != mSet.end(); config++) { if (config->getHandle() == configHandle) { return &(*config); } } return NULL; } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <memory> #include "updatecheck.hxx" #include "updatecheckconfig.hxx" #include "updatehdl.hxx" #include "updateprotocol.hxx" #include <cppuhelper/implbase3.hxx> #include <cppuhelper/implementationentry.hxx> #include "com/sun/star/frame/Desktop.hpp" #include "com/sun/star/frame/XTerminateListener.hpp" #include <com/sun/star/task/XJob.hpp> namespace beans = com::sun::star::beans ; namespace frame = com::sun::star::frame ; namespace lang = com::sun::star::lang ; namespace task = com::sun::star::task ; namespace uno = com::sun::star::uno ; namespace { class InitUpdateCheckJobThread : public osl::Thread { public: InitUpdateCheckJobThread( const uno::Reference< uno::XComponentContext > &xContext, const uno::Sequence< beans::NamedValue > &xParameters, bool bShowDialog ); virtual void SAL_CALL run(); void setTerminating(); private: osl::Condition m_aCondition; uno::Reference<uno::XComponentContext> m_xContext; uno::Sequence<beans::NamedValue> m_xParameters; bool m_bShowDialog; bool m_bTerminating; }; class UpdateCheckJob : public ::cppu::WeakImplHelper3< task::XJob, lang::XServiceInfo, frame::XTerminateListener > { virtual ~UpdateCheckJob(); public: UpdateCheckJob(const uno::Reference<uno::XComponentContext>& xContext); static uno::Sequence< OUString > getServiceNames(); static OUString getImplName(); // Allows runtime exceptions to be thrown by const methods inline SAL_CALL operator uno::Reference< uno::XInterface > () const { return const_cast< cppu::OWeakObject * > (static_cast< cppu::OWeakObject const * > (this)); }; // XJob virtual uno::Any SAL_CALL execute(const uno::Sequence<beans::NamedValue>&) throw (lang::IllegalArgumentException, uno::Exception); // XServiceInfo virtual OUString SAL_CALL getImplementationName() throw (uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService(OUString const & serviceName) throw (uno::RuntimeException); virtual uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() throw (uno::RuntimeException); // XEventListener virtual void SAL_CALL disposing( ::com::sun::star::lang::EventObject const & evt ) throw (::com::sun::star::uno::RuntimeException); // XTerminateListener virtual void SAL_CALL queryTermination( lang::EventObject const & evt ) throw ( frame::TerminationVetoException, uno::RuntimeException ); virtual void SAL_CALL notifyTermination( lang::EventObject const & evt ) throw ( uno::RuntimeException ); private: uno::Reference<uno::XComponentContext> m_xContext; uno::Reference< frame::XDesktop2 > m_xDesktop; std::auto_ptr< InitUpdateCheckJobThread > m_pInitThread; void handleExtensionUpdates( const uno::Sequence< beans::NamedValue > &rListProp ); }; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ InitUpdateCheckJobThread::InitUpdateCheckJobThread( const uno::Reference< uno::XComponentContext > &xContext, const uno::Sequence< beans::NamedValue > &xParameters, bool bShowDialog ) : m_xContext( xContext ), m_xParameters( xParameters ), m_bShowDialog( bShowDialog ), m_bTerminating( false ) { create(); } //------------------------------------------------------------------------------ void SAL_CALL InitUpdateCheckJobThread::run() { if (!m_bShowDialog) { TimeValue tv = { 25, 0 }; m_aCondition.wait( &tv ); if ( m_bTerminating ) return; } rtl::Reference< UpdateCheck > aController( UpdateCheck::get() ); aController->initialize( m_xParameters, m_xContext ); if ( m_bShowDialog ) aController->showDialog( true ); } void InitUpdateCheckJobThread::setTerminating() { m_bTerminating = true; m_aCondition.set(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ UpdateCheckJob::UpdateCheckJob( const uno::Reference<uno::XComponentContext>& xContext ) : m_xContext(xContext) { m_xDesktop.set( frame::Desktop::create(xContext) ); m_xDesktop->addTerminateListener( this ); } //------------------------------------------------------------------------------ UpdateCheckJob::~UpdateCheckJob() { } //------------------------------------------------------------------------------ uno::Sequence< OUString > UpdateCheckJob::getServiceNames() { uno::Sequence< OUString > aServiceList(1); aServiceList[0] = "com.sun.star.setup.UpdateCheck"; return aServiceList; }; //------------------------------------------------------------------------------ OUString UpdateCheckJob::getImplName() { return OUString("vnd.sun.UpdateCheck"); } //------------------------------------------------------------------------------ uno::Any UpdateCheckJob::execute(const uno::Sequence<beans::NamedValue>& namedValues) throw (lang::IllegalArgumentException, uno::Exception) { for ( sal_Int32 n=namedValues.getLength(); n-- > 0; ) { if ( namedValues[ n ].Name == "DynamicData" ) { uno::Sequence<beans::NamedValue> aListProp; if ( namedValues[n].Value >>= aListProp ) { for ( sal_Int32 i=aListProp.getLength(); i-- > 0; ) { if ( aListProp[ i ].Name == "updateList" ) { handleExtensionUpdates( aListProp ); return uno::Any(); } } } } } uno::Sequence<beans::NamedValue> aConfig = getValue< uno::Sequence<beans::NamedValue> > (namedValues, "JobConfig"); /* Determine the way we got invoked here - * see Developers Guide Chapter "4.7.2 Jobs" to understand the magic */ uno::Sequence<beans::NamedValue> aEnvironment = getValue< uno::Sequence<beans::NamedValue> > (namedValues, "Environment"); OUString aEventName = getValue< OUString > (aEnvironment, "EventName"); m_pInitThread.reset( new InitUpdateCheckJobThread( m_xContext, aConfig, !aEventName.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("onFirstVisibleTask")))); return uno::Any(); } //------------------------------------------------------------------------------ void UpdateCheckJob::handleExtensionUpdates( const uno::Sequence< beans::NamedValue > &rListProp ) { try { uno::Sequence< uno::Sequence< OUString > > aList = getValue< uno::Sequence< uno::Sequence< OUString > > > ( rListProp, "updateList" ); bool bPrepareOnly = getValue< bool > ( rListProp, "prepareOnly" ); // we will first store any new found updates and then check, if there are any // pending updates. storeExtensionUpdateInfos( m_xContext, aList ); if ( bPrepareOnly ) return; bool bHasUpdates = checkForPendingUpdates( m_xContext ); rtl::Reference<UpdateCheck> aController( UpdateCheck::get() ); if ( ! aController.is() ) return; aController->setHasExtensionUpdates( bHasUpdates ); if ( ! aController->hasOfficeUpdate() ) { if ( bHasUpdates ) aController->setUIState( UPDATESTATE_EXT_UPD_AVAIL, true ); else aController->setUIState( UPDATESTATE_NO_UPDATE_AVAIL, true ); } } catch( const uno::Exception& e ) { OSL_TRACE( "Caught exception: %s\n thread terminated.\n", OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8).getStr()); } } //------------------------------------------------------------------------------ OUString SAL_CALL UpdateCheckJob::getImplementationName() throw (uno::RuntimeException) { return getImplName(); } //------------------------------------------------------------------------------ uno::Sequence< OUString > SAL_CALL UpdateCheckJob::getSupportedServiceNames() throw (uno::RuntimeException) { return getServiceNames(); } //------------------------------------------------------------------------------ sal_Bool SAL_CALL UpdateCheckJob::supportsService( OUString const & serviceName ) throw (uno::RuntimeException) { uno::Sequence< OUString > aServiceNameList = getServiceNames(); for( sal_Int32 n=0; n < aServiceNameList.getLength(); n++ ) if( aServiceNameList[n].equals(serviceName) ) return sal_True; return sal_False; } //------------------------------------------------------------------------------ // XEventListener void SAL_CALL UpdateCheckJob::disposing( lang::EventObject const & rEvt ) throw ( uno::RuntimeException ) { bool shutDown = ( rEvt.Source == m_xDesktop ); if ( shutDown && m_xDesktop.is() ) { m_xDesktop->removeTerminateListener( this ); m_xDesktop.clear(); } } //------------------------------------------------------------------------------ // XTerminateListener void SAL_CALL UpdateCheckJob::queryTermination( lang::EventObject const & ) throw ( frame::TerminationVetoException, uno::RuntimeException ) { } //------------------------------------------------------------------------------ void SAL_CALL UpdateCheckJob::notifyTermination( lang::EventObject const & ) throw ( uno::RuntimeException ) { if ( m_pInitThread.get() != 0 ) { m_pInitThread->setTerminating(); m_pInitThread->join(); } } } // anonymous namespace //------------------------------------------------------------------------------ static uno::Reference<uno::XInterface> SAL_CALL createJobInstance(const uno::Reference<uno::XComponentContext>& xContext) { return *new UpdateCheckJob(xContext); } //------------------------------------------------------------------------------ static uno::Reference<uno::XInterface> SAL_CALL createConfigInstance(const uno::Reference<uno::XComponentContext>& xContext) { return *UpdateCheckConfig::get(xContext, *UpdateCheck::get()); } //------------------------------------------------------------------------------ static const cppu::ImplementationEntry kImplementations_entries[] = { { createJobInstance, UpdateCheckJob::getImplName, UpdateCheckJob::getServiceNames, cppu::createSingleComponentFactory, NULL, 0 }, { createConfigInstance, UpdateCheckConfig::getImplName, UpdateCheckConfig::getServiceNames, cppu::createSingleComponentFactory, NULL, 0 }, { NULL, NULL, NULL, NULL, NULL, 0 } } ; //------------------------------------------------------------------------------ extern "C" SAL_DLLPUBLIC_EXPORT void * SAL_CALL updchk_component_getFactory(const sal_Char *pszImplementationName, void *pServiceManager, void *pRegistryKey) { return cppu::component_getFactoryHelper( pszImplementationName, pServiceManager, pRegistryKey, kImplementations_entries) ; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>fdo#64962 - ignore exceptions from checking with the update service.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <memory> #include "updatecheck.hxx" #include "updatecheckconfig.hxx" #include "updatehdl.hxx" #include "updateprotocol.hxx" #include <cppuhelper/implbase3.hxx> #include <cppuhelper/implementationentry.hxx> #include "com/sun/star/frame/Desktop.hpp" #include "com/sun/star/frame/XTerminateListener.hpp" #include <com/sun/star/task/XJob.hpp> namespace beans = com::sun::star::beans ; namespace frame = com::sun::star::frame ; namespace lang = com::sun::star::lang ; namespace task = com::sun::star::task ; namespace uno = com::sun::star::uno ; namespace { class InitUpdateCheckJobThread : public osl::Thread { public: InitUpdateCheckJobThread( const uno::Reference< uno::XComponentContext > &xContext, const uno::Sequence< beans::NamedValue > &xParameters, bool bShowDialog ); virtual void SAL_CALL run(); void setTerminating(); private: osl::Condition m_aCondition; uno::Reference<uno::XComponentContext> m_xContext; uno::Sequence<beans::NamedValue> m_xParameters; bool m_bShowDialog; bool m_bTerminating; }; class UpdateCheckJob : public ::cppu::WeakImplHelper3< task::XJob, lang::XServiceInfo, frame::XTerminateListener > { virtual ~UpdateCheckJob(); public: UpdateCheckJob(const uno::Reference<uno::XComponentContext>& xContext); static uno::Sequence< OUString > getServiceNames(); static OUString getImplName(); // Allows runtime exceptions to be thrown by const methods inline SAL_CALL operator uno::Reference< uno::XInterface > () const { return const_cast< cppu::OWeakObject * > (static_cast< cppu::OWeakObject const * > (this)); }; // XJob virtual uno::Any SAL_CALL execute(const uno::Sequence<beans::NamedValue>&) throw (lang::IllegalArgumentException, uno::Exception); // XServiceInfo virtual OUString SAL_CALL getImplementationName() throw (uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService(OUString const & serviceName) throw (uno::RuntimeException); virtual uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() throw (uno::RuntimeException); // XEventListener virtual void SAL_CALL disposing( ::com::sun::star::lang::EventObject const & evt ) throw (::com::sun::star::uno::RuntimeException); // XTerminateListener virtual void SAL_CALL queryTermination( lang::EventObject const & evt ) throw ( frame::TerminationVetoException, uno::RuntimeException ); virtual void SAL_CALL notifyTermination( lang::EventObject const & evt ) throw ( uno::RuntimeException ); private: uno::Reference<uno::XComponentContext> m_xContext; uno::Reference< frame::XDesktop2 > m_xDesktop; std::auto_ptr< InitUpdateCheckJobThread > m_pInitThread; void handleExtensionUpdates( const uno::Sequence< beans::NamedValue > &rListProp ); }; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ InitUpdateCheckJobThread::InitUpdateCheckJobThread( const uno::Reference< uno::XComponentContext > &xContext, const uno::Sequence< beans::NamedValue > &xParameters, bool bShowDialog ) : m_xContext( xContext ), m_xParameters( xParameters ), m_bShowDialog( bShowDialog ), m_bTerminating( false ) { create(); } //------------------------------------------------------------------------------ void SAL_CALL InitUpdateCheckJobThread::run() { if (!m_bShowDialog) { TimeValue tv = { 25, 0 }; m_aCondition.wait( &tv ); if ( m_bTerminating ) return; } try { rtl::Reference< UpdateCheck > aController( UpdateCheck::get() ); aController->initialize( m_xParameters, m_xContext ); if ( m_bShowDialog ) aController->showDialog( true ); } catch (const uno::Exception &e) { // fdo#64962 - don't bring the app down on some unexpected exception. OSL_TRACE( "Caught init update exception: %s\n thread terminated.\n", OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8).getStr() ); } } void InitUpdateCheckJobThread::setTerminating() { m_bTerminating = true; m_aCondition.set(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ UpdateCheckJob::UpdateCheckJob( const uno::Reference<uno::XComponentContext>& xContext ) : m_xContext(xContext) { m_xDesktop.set( frame::Desktop::create(xContext) ); m_xDesktop->addTerminateListener( this ); } //------------------------------------------------------------------------------ UpdateCheckJob::~UpdateCheckJob() { } //------------------------------------------------------------------------------ uno::Sequence< OUString > UpdateCheckJob::getServiceNames() { uno::Sequence< OUString > aServiceList(1); aServiceList[0] = "com.sun.star.setup.UpdateCheck"; return aServiceList; }; //------------------------------------------------------------------------------ OUString UpdateCheckJob::getImplName() { return OUString("vnd.sun.UpdateCheck"); } //------------------------------------------------------------------------------ uno::Any UpdateCheckJob::execute(const uno::Sequence<beans::NamedValue>& namedValues) throw (lang::IllegalArgumentException, uno::Exception) { for ( sal_Int32 n=namedValues.getLength(); n-- > 0; ) { if ( namedValues[ n ].Name == "DynamicData" ) { uno::Sequence<beans::NamedValue> aListProp; if ( namedValues[n].Value >>= aListProp ) { for ( sal_Int32 i=aListProp.getLength(); i-- > 0; ) { if ( aListProp[ i ].Name == "updateList" ) { handleExtensionUpdates( aListProp ); return uno::Any(); } } } } } uno::Sequence<beans::NamedValue> aConfig = getValue< uno::Sequence<beans::NamedValue> > (namedValues, "JobConfig"); /* Determine the way we got invoked here - * see Developers Guide Chapter "4.7.2 Jobs" to understand the magic */ uno::Sequence<beans::NamedValue> aEnvironment = getValue< uno::Sequence<beans::NamedValue> > (namedValues, "Environment"); OUString aEventName = getValue< OUString > (aEnvironment, "EventName"); m_pInitThread.reset( new InitUpdateCheckJobThread( m_xContext, aConfig, !aEventName.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("onFirstVisibleTask")))); return uno::Any(); } //------------------------------------------------------------------------------ void UpdateCheckJob::handleExtensionUpdates( const uno::Sequence< beans::NamedValue > &rListProp ) { try { uno::Sequence< uno::Sequence< OUString > > aList = getValue< uno::Sequence< uno::Sequence< OUString > > > ( rListProp, "updateList" ); bool bPrepareOnly = getValue< bool > ( rListProp, "prepareOnly" ); // we will first store any new found updates and then check, if there are any // pending updates. storeExtensionUpdateInfos( m_xContext, aList ); if ( bPrepareOnly ) return; bool bHasUpdates = checkForPendingUpdates( m_xContext ); rtl::Reference<UpdateCheck> aController( UpdateCheck::get() ); if ( ! aController.is() ) return; aController->setHasExtensionUpdates( bHasUpdates ); if ( ! aController->hasOfficeUpdate() ) { if ( bHasUpdates ) aController->setUIState( UPDATESTATE_EXT_UPD_AVAIL, true ); else aController->setUIState( UPDATESTATE_NO_UPDATE_AVAIL, true ); } } catch( const uno::Exception& e ) { OSL_TRACE( "Caught exception: %s\n thread terminated.\n", OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8).getStr()); } } //------------------------------------------------------------------------------ OUString SAL_CALL UpdateCheckJob::getImplementationName() throw (uno::RuntimeException) { return getImplName(); } //------------------------------------------------------------------------------ uno::Sequence< OUString > SAL_CALL UpdateCheckJob::getSupportedServiceNames() throw (uno::RuntimeException) { return getServiceNames(); } //------------------------------------------------------------------------------ sal_Bool SAL_CALL UpdateCheckJob::supportsService( OUString const & serviceName ) throw (uno::RuntimeException) { uno::Sequence< OUString > aServiceNameList = getServiceNames(); for( sal_Int32 n=0; n < aServiceNameList.getLength(); n++ ) if( aServiceNameList[n].equals(serviceName) ) return sal_True; return sal_False; } //------------------------------------------------------------------------------ // XEventListener void SAL_CALL UpdateCheckJob::disposing( lang::EventObject const & rEvt ) throw ( uno::RuntimeException ) { bool shutDown = ( rEvt.Source == m_xDesktop ); if ( shutDown && m_xDesktop.is() ) { m_xDesktop->removeTerminateListener( this ); m_xDesktop.clear(); } } //------------------------------------------------------------------------------ // XTerminateListener void SAL_CALL UpdateCheckJob::queryTermination( lang::EventObject const & ) throw ( frame::TerminationVetoException, uno::RuntimeException ) { } //------------------------------------------------------------------------------ void SAL_CALL UpdateCheckJob::notifyTermination( lang::EventObject const & ) throw ( uno::RuntimeException ) { if ( m_pInitThread.get() != 0 ) { m_pInitThread->setTerminating(); m_pInitThread->join(); } } } // anonymous namespace //------------------------------------------------------------------------------ static uno::Reference<uno::XInterface> SAL_CALL createJobInstance(const uno::Reference<uno::XComponentContext>& xContext) { return *new UpdateCheckJob(xContext); } //------------------------------------------------------------------------------ static uno::Reference<uno::XInterface> SAL_CALL createConfigInstance(const uno::Reference<uno::XComponentContext>& xContext) { return *UpdateCheckConfig::get(xContext, *UpdateCheck::get()); } //------------------------------------------------------------------------------ static const cppu::ImplementationEntry kImplementations_entries[] = { { createJobInstance, UpdateCheckJob::getImplName, UpdateCheckJob::getServiceNames, cppu::createSingleComponentFactory, NULL, 0 }, { createConfigInstance, UpdateCheckConfig::getImplName, UpdateCheckConfig::getServiceNames, cppu::createSingleComponentFactory, NULL, 0 }, { NULL, NULL, NULL, NULL, NULL, 0 } } ; //------------------------------------------------------------------------------ extern "C" SAL_DLLPUBLIC_EXPORT void * SAL_CALL updchk_component_getFactory(const sal_Char *pszImplementationName, void *pServiceManager, void *pRegistryKey) { return cppu::component_getFactoryHelper( pszImplementationName, pServiceManager, pRegistryKey, kImplementations_entries) ; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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. * ***************************************************************/ /* This is some wisdom from Cygnus's web page. If you just try to use the "stringify" operator on a preprocessor directive, you'd get "PLATFORM", not "Intel Linux" (or whatever the value of PLATFORM is). That's because the stringify operator is a special case, and the preprocessor isn't allowed to expand things that are passed to it. However, by defining two layers of macros, you get the right behavior, since the first pass converts: xstr(PLATFORM) -> str(Intel Linux) and the next pass gives: str(Intel Linux) -> "Intel Linux" This is exactly what we want, so we use it. -Derek Wright and Jeff Ballard, 12/2/99 Also, because the NT build system is totally different, we have to define the correct platform string right in here. :( -Derek 12/3/99 */ #include "condor_common.h" #define xstr(s) str(s) #define str(s) #s #if defined(WIN32) #define PLATFORM INTEL-WINNT50 #endif /* Via configure, one may have specified a particular buildid string to use in the version string. So honor that request here. */ #if defined(BUILDID) #define BUILDIDSTR " BuildID: " xstr(BUILDID) #else #define BUILDIDSTR "" #endif /* Here is the version string - update before a public release */ /* --- IMPORTANT! THE FORMAT OF THE VERSION STRING IS VERY STRICT BECAUSE IT IS PARSED AT RUNTIME AND COMPILE-TIME. DO NOT ALTER THE FORMAT OR ENTER ANYTHING EXTRA BEFORE THE DATE. IF YOU WISH TO ADD EXTRA INFORMATION, DO SO _AFTER_ THE BUILDIDSTR AND BEFORE THE TRAILING '$' CHARACTER. EXAMPLES: $CondorVersion: 6.9.5 " __DATE__ BUILDIDSTR " WinNTPreview $ [OK] $CondorVersion: 6.9.5 WinNTPreview " __DATE__ BUILDIDSTR " $ [WRONG!!!] Any questions? See Todd or Derek. Note: if you mess it up, DaemonCore will EXCEPT at startup time. */ static char* CondorVersionString = "$CondorVersion: 7.5.0 " __DATE__ BUILDIDSTR " PRE-RELEASE $"; /* Here is the platform string. You don't need to edit this */ static char* CondorPlatformString = "$CondorPlatform: " xstr(PLATFORM) " $"; extern "C" { const char* CondorVersion( void ) { return CondorVersionString; } const char* CondorPlatform( void ) { return CondorPlatformString; } } /* extern "C" */ <commit_msg>Add V7_5-CREAM_HARDENING-BRANCH to version string. #897<commit_after>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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. * ***************************************************************/ /* This is some wisdom from Cygnus's web page. If you just try to use the "stringify" operator on a preprocessor directive, you'd get "PLATFORM", not "Intel Linux" (or whatever the value of PLATFORM is). That's because the stringify operator is a special case, and the preprocessor isn't allowed to expand things that are passed to it. However, by defining two layers of macros, you get the right behavior, since the first pass converts: xstr(PLATFORM) -> str(Intel Linux) and the next pass gives: str(Intel Linux) -> "Intel Linux" This is exactly what we want, so we use it. -Derek Wright and Jeff Ballard, 12/2/99 Also, because the NT build system is totally different, we have to define the correct platform string right in here. :( -Derek 12/3/99 */ #include "condor_common.h" #define xstr(s) str(s) #define str(s) #s #if defined(WIN32) #define PLATFORM INTEL-WINNT50 #endif /* Via configure, one may have specified a particular buildid string to use in the version string. So honor that request here. */ #if defined(BUILDID) #define BUILDIDSTR " BuildID: " xstr(BUILDID) #else #define BUILDIDSTR "" #endif /* Here is the version string - update before a public release */ /* --- IMPORTANT! THE FORMAT OF THE VERSION STRING IS VERY STRICT BECAUSE IT IS PARSED AT RUNTIME AND COMPILE-TIME. DO NOT ALTER THE FORMAT OR ENTER ANYTHING EXTRA BEFORE THE DATE. IF YOU WISH TO ADD EXTRA INFORMATION, DO SO _AFTER_ THE BUILDIDSTR AND BEFORE THE TRAILING '$' CHARACTER. EXAMPLES: $CondorVersion: 6.9.5 " __DATE__ BUILDIDSTR " WinNTPreview $ [OK] $CondorVersion: 6.9.5 WinNTPreview " __DATE__ BUILDIDSTR " $ [WRONG!!!] Any questions? See Todd or Derek. Note: if you mess it up, DaemonCore will EXCEPT at startup time. */ static char* CondorVersionString = "$CondorVersion: 7.5.0 " __DATE__ BUILDIDSTR " V7_5-CREAM_HARDENING-BRANCH-PRE-RELEASE $"; /* Here is the platform string. You don't need to edit this */ static char* CondorPlatformString = "$CondorPlatform: " xstr(PLATFORM) " $"; extern "C" { const char* CondorVersion( void ) { return CondorVersionString; } const char* CondorPlatform( void ) { return CondorPlatformString; } } /* extern "C" */ <|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 "base/native_library.h" #include <dlfcn.h> #include "base/file_path.h" #include "base/logging.h" #include "base/string_util.h" namespace base { // static NativeLibrary LoadNativeLibrary(const FilePath& library_path) { void* dl = dlopen(library_path.value().c_str(), RTLD_LAZY); if (!dl) { std::string error_message = dlerror(); // Some obsolete plugins depend on libxul or libxpcom. // Ignore the error messages when failing to load these. if (error_message.find("libxul.so") == std::string::npos && error_message.find("libxpcom.so") == std::string::npos) { LOG(ERROR) << "dlopen failed when trying to open " << library_path.value() << ": " << error_message; } } return dl; } // static void UnloadNativeLibrary(NativeLibrary library) { int ret = dlclose(library); if (ret < 0) { LOG(ERROR) << "dlclose failed: " << dlerror(); NOTREACHED(); } } // static void* GetFunctionPointerFromNativeLibrary(NativeLibrary library, const char* name) { return dlsym(library, name); } // static string16 GetNativeLibraryName(const string16& name) { return ASCIIToUTF16("lib") + name + ASCIIToUTF16(".so"); } } // namespace base <commit_msg>Add comments saying we don't use RTLD_DEEPBIND.<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 "base/native_library.h" #include <dlfcn.h> #include "base/file_path.h" #include "base/logging.h" #include "base/string_util.h" namespace base { // static NativeLibrary LoadNativeLibrary(const FilePath& library_path) { // We deliberately do not use RTLD_DEEPBIND. For the history why, please // refer to the bug tracker. Some useful bug reports to read include: // http://crbug.com/17943, http://crbug.com/17557, http://crbug.com/36892, // and http://crbug.com/40794. void* dl = dlopen(library_path.value().c_str(), RTLD_LAZY); if (!dl) { std::string error_message = dlerror(); // Some obsolete plugins depend on libxul or libxpcom. // Ignore the error messages when failing to load these. if (error_message.find("libxul.so") == std::string::npos && error_message.find("libxpcom.so") == std::string::npos) { LOG(ERROR) << "dlopen failed when trying to open " << library_path.value() << ": " << error_message; } } return dl; } // static void UnloadNativeLibrary(NativeLibrary library) { int ret = dlclose(library); if (ret < 0) { LOG(ERROR) << "dlclose failed: " << dlerror(); NOTREACHED(); } } // static void* GetFunctionPointerFromNativeLibrary(NativeLibrary library, const char* name) { return dlsym(library, name); } // static string16 GetNativeLibraryName(const string16& name) { return ASCIIToUTF16("lib") + name + ASCIIToUTF16(".so"); } } // namespace base <|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. // Test of classes in the tracked_objects.h classes. #include "base/tracked_objects.h" #include "base/logging.h" #include "testing/gtest/include/gtest/gtest.h" namespace tracked_objects { class TrackedObjectsTest : public testing::Test { }; TEST(TrackedObjectsTest, MinimalStartupShutdown) { // Minimal test doesn't even create any tasks. if (!ThreadData::StartTracking(true)) return; EXPECT_FALSE(ThreadData::first()); // No activity even on this thread. ThreadData* data = ThreadData::current(); EXPECT_TRUE(ThreadData::first()); // Now class was constructed. EXPECT_TRUE(data); EXPECT_TRUE(!data->next()); EXPECT_EQ(data, ThreadData::current()); ThreadData::BirthMap birth_map; data->SnapshotBirthMap(&birth_map); EXPECT_EQ(0u, birth_map.size()); ThreadData::DeathMap death_map; data->SnapshotDeathMap(&death_map); EXPECT_EQ(0u, death_map.size()); ThreadData::ShutdownSingleThreadedCleanup(); // Do it again, just to be sure we reset state completely. ThreadData::StartTracking(true); EXPECT_FALSE(ThreadData::first()); // No activity even on this thread. data = ThreadData::current(); EXPECT_TRUE(ThreadData::first()); // Now class was constructed. EXPECT_TRUE(data); EXPECT_TRUE(!data->next()); EXPECT_EQ(data, ThreadData::current()); birth_map.clear(); data->SnapshotBirthMap(&birth_map); EXPECT_EQ(0u, birth_map.size()); death_map.clear(); data->SnapshotDeathMap(&death_map); EXPECT_EQ(0u, death_map.size()); ThreadData::ShutdownSingleThreadedCleanup(); } class NoopTask : public Task { public: void Run() {} }; TEST(TrackedObjectsTest, TinyStartupShutdown) { if (!ThreadData::StartTracking(true)) return; // Instigate tracking on a single task, or our thread. NoopTask task; const ThreadData* data = ThreadData::first(); EXPECT_TRUE(data); EXPECT_TRUE(!data->next()); EXPECT_EQ(data, ThreadData::current()); ThreadData::BirthMap birth_map; data->SnapshotBirthMap(&birth_map); EXPECT_EQ(1u, birth_map.size()); // 1 birth location. EXPECT_EQ(1, birth_map.begin()->second->birth_count()); // 1 birth. ThreadData::DeathMap death_map; data->SnapshotDeathMap(&death_map); EXPECT_EQ(0u, death_map.size()); // No deaths. // Now instigate a birth, and a death. delete new NoopTask; birth_map.clear(); data->SnapshotBirthMap(&birth_map); EXPECT_EQ(1u, birth_map.size()); // 1 birth location. EXPECT_EQ(2, birth_map.begin()->second->birth_count()); // 2 births. death_map.clear(); data->SnapshotDeathMap(&death_map); EXPECT_EQ(1u, death_map.size()); // 1 location. EXPECT_EQ(1, death_map.begin()->second.count()); // 1 death. // The births were at the same location as the one known death. EXPECT_EQ(birth_map.begin()->second, death_map.begin()->first); ThreadData::ShutdownSingleThreadedCleanup(); } } // namespace tracked_objects <commit_msg>fix unit test that was missing a MessageLoop allocation<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. // Test of classes in the tracked_objects.h classes. #include "base/tracked_objects.h" #include "base/logging.h" #include "testing/gtest/include/gtest/gtest.h" namespace tracked_objects { class TrackedObjectsTest : public testing::Test { public: MessageLoop message_loop_; }; TEST_F(TrackedObjectsTest, MinimalStartupShutdown) { // Minimal test doesn't even create any tasks. if (!ThreadData::StartTracking(true)) return; EXPECT_FALSE(ThreadData::first()); // No activity even on this thread. ThreadData* data = ThreadData::current(); EXPECT_TRUE(ThreadData::first()); // Now class was constructed. EXPECT_TRUE(data); EXPECT_TRUE(!data->next()); EXPECT_EQ(data, ThreadData::current()); ThreadData::BirthMap birth_map; data->SnapshotBirthMap(&birth_map); EXPECT_EQ(0u, birth_map.size()); ThreadData::DeathMap death_map; data->SnapshotDeathMap(&death_map); EXPECT_EQ(0u, death_map.size()); ThreadData::ShutdownSingleThreadedCleanup(); // Do it again, just to be sure we reset state completely. ThreadData::StartTracking(true); EXPECT_FALSE(ThreadData::first()); // No activity even on this thread. data = ThreadData::current(); EXPECT_TRUE(ThreadData::first()); // Now class was constructed. EXPECT_TRUE(data); EXPECT_TRUE(!data->next()); EXPECT_EQ(data, ThreadData::current()); birth_map.clear(); data->SnapshotBirthMap(&birth_map); EXPECT_EQ(0u, birth_map.size()); death_map.clear(); data->SnapshotDeathMap(&death_map); EXPECT_EQ(0u, death_map.size()); ThreadData::ShutdownSingleThreadedCleanup(); } class NoopTask : public Task { public: void Run() {} }; TEST_F(TrackedObjectsTest, TinyStartupShutdown) { if (!ThreadData::StartTracking(true)) return; // Instigate tracking on a single task, or our thread. NoopTask task; const ThreadData* data = ThreadData::first(); EXPECT_TRUE(data); EXPECT_TRUE(!data->next()); EXPECT_EQ(data, ThreadData::current()); ThreadData::BirthMap birth_map; data->SnapshotBirthMap(&birth_map); EXPECT_EQ(1u, birth_map.size()); // 1 birth location. EXPECT_EQ(1, birth_map.begin()->second->birth_count()); // 1 birth. ThreadData::DeathMap death_map; data->SnapshotDeathMap(&death_map); EXPECT_EQ(0u, death_map.size()); // No deaths. // Now instigate a birth, and a death. delete new NoopTask; birth_map.clear(); data->SnapshotBirthMap(&birth_map); EXPECT_EQ(1u, birth_map.size()); // 1 birth location. EXPECT_EQ(2, birth_map.begin()->second->birth_count()); // 2 births. death_map.clear(); data->SnapshotDeathMap(&death_map); EXPECT_EQ(1u, death_map.size()); // 1 location. EXPECT_EQ(1, death_map.begin()->second.count()); // 1 death. // The births were at the same location as the one known death. EXPECT_EQ(birth_map.begin()->second, death_map.begin()->first); ThreadData::ShutdownSingleThreadedCleanup(); } } // namespace tracked_objects<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ConnectionPage.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: pjunck $ $Date: 2004-10-27 12:58:19 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS 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): Ocke Janssen * * ************************************************************************/ #ifndef DBAUI_CONNECTIONPAGE_HXX #define DBAUI_CONNECTIONPAGE_HXX #ifndef DBAUI_CONNECTIONHELPER_HXX #include "ConnectionHelper.hxx" #endif #ifndef _DBAUI_ADMINPAGES_HXX_ #include "adminpages.hxx" #endif #ifndef _UCBHELPER_CONTENT_HXX #include <ucbhelper/content.hxx> #endif #ifndef _DBAUI_CURLEDIT_HXX_ #include "curledit.hxx" #endif //......................................................................... namespace dbaui { //......................................................................... class IAdminHelper; //========================================================================= //= OConnectionTabPage //========================================================================= /** implements the connection page of teh data source properties dialog. */ class OConnectionTabPage : public OConnectionHelper { ODsnTypeCollection* m_pCollection; /// the DSN type collection instance sal_Bool m_bUserGrabFocus : 1; protected: // connection FixedLine m_aFL1; // user authentification FixedLine m_aFL2; FixedText m_aUserNameLabel; Edit m_aUserName; CheckBox m_aPasswordRequired; // jdbc driver FixedLine m_aFL3; FixedText m_aJavaDriverLabel; Edit m_aJavaDriver; PushButton m_aTestJavaDriver; // connection test PushButton m_aTestConnection; // called when the test connection button was clicked DECL_LINK(OnTestConnectionClickHdl,PushButton*); DECL_LINK(OnBrowseConnections, PushButton*); DECL_LINK(OnTestJavaClickHdl,PushButton*); DECL_LINK(OnEditModified,Edit*); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& _rAttrSet ); virtual BOOL FillItemSet (SfxItemSet& _rCoreAttrs); virtual void implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue); virtual void SetServiceFactory(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > _rxORB) { OGenericAdministrationPage::SetServiceFactory(_rxORB); m_aET_Connection.initializeTypeCollection(m_xORB); } inline void enableConnectionURL() { m_aET_Connection.SetReadOnly(sal_False); } inline void disableConnectionURL() { m_aET_Connection.SetReadOnly(); } /** changes the connection URL. <p>The new URL must be of the type which is currently selected, only the parts which do not affect the type may be changed (compared to the previous URL).</p> */ protected: OConnectionTabPage(Window* pParent, const SfxItemSet& _rCoreAttrs); // nControlFlags ist eine Kombination der CBTP_xxx-Konstanten virtual ~OConnectionTabPage(); // <method>OGenericAdministrationPage::fillControls</method> virtual void fillControls(::std::vector< ISaveValueWrapper* >& _rControlList); // <method>OGenericAdministrationPage::fillWindows</method> virtual void fillWindows(::std::vector< ISaveValueWrapper* >& _rControlList); private: // setting/retrieving the current connection URL // necessary because for some types, the URL must be decoded for display purposes /** enables the test connection button, if allowed */ virtual bool checkTestConnection(); /** opens the FileOpen dialog and asks for a FileName @param _sFilterName The filter name. @param _sExtension The filter extension. */ }; //......................................................................... } // namespace dbaui //......................................................................... #endif // _DBAUI_DETAILPAGES_HXX_ <commit_msg>INTEGRATION: CWS dba22 (1.3.22); FILE MERGED 2005/01/06 12:42:48 oj 1.3.22.1: #i39321# extend createConnection to return a pair now<commit_after>/************************************************************************* * * $RCSfile: ConnectionPage.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2005-01-21 17:12:00 $ * * 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 EXPRESS 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): Ocke Janssen * * ************************************************************************/ #ifndef DBAUI_CONNECTIONPAGE_HXX #define DBAUI_CONNECTIONPAGE_HXX #ifndef DBAUI_CONNECTIONHELPER_HXX #include "ConnectionHelper.hxx" #endif #ifndef _DBAUI_ADMINPAGES_HXX_ #include "adminpages.hxx" #endif #ifndef _UCBHELPER_CONTENT_HXX #include <ucbhelper/content.hxx> #endif #ifndef _DBAUI_CURLEDIT_HXX_ #include "curledit.hxx" #endif //......................................................................... namespace dbaui { //......................................................................... class IAdminHelper; //========================================================================= //= OConnectionTabPage //========================================================================= /** implements the connection page of teh data source properties dialog. */ class OConnectionTabPage : public OConnectionHelper { ODsnTypeCollection* m_pCollection; /// the DSN type collection instance sal_Bool m_bUserGrabFocus : 1; protected: // connection FixedLine m_aFL1; // user authentification FixedLine m_aFL2; FixedText m_aUserNameLabel; Edit m_aUserName; CheckBox m_aPasswordRequired; // jdbc driver FixedLine m_aFL3; FixedText m_aJavaDriverLabel; Edit m_aJavaDriver; PushButton m_aTestJavaDriver; // connection test PushButton m_aTestConnection; // called when the test connection button was clicked DECL_LINK(OnBrowseConnections, PushButton*); DECL_LINK(OnTestJavaClickHdl,PushButton*); DECL_LINK(OnEditModified,Edit*); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& _rAttrSet ); virtual BOOL FillItemSet (SfxItemSet& _rCoreAttrs); virtual void implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue); virtual void SetServiceFactory(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > _rxORB) { OGenericAdministrationPage::SetServiceFactory(_rxORB); m_aET_Connection.initializeTypeCollection(m_xORB); } inline void enableConnectionURL() { m_aET_Connection.SetReadOnly(sal_False); } inline void disableConnectionURL() { m_aET_Connection.SetReadOnly(); } /** changes the connection URL. <p>The new URL must be of the type which is currently selected, only the parts which do not affect the type may be changed (compared to the previous URL).</p> */ protected: OConnectionTabPage(Window* pParent, const SfxItemSet& _rCoreAttrs); // nControlFlags ist eine Kombination der CBTP_xxx-Konstanten virtual ~OConnectionTabPage(); // <method>OGenericAdministrationPage::fillControls</method> virtual void fillControls(::std::vector< ISaveValueWrapper* >& _rControlList); // <method>OGenericAdministrationPage::fillWindows</method> virtual void fillWindows(::std::vector< ISaveValueWrapper* >& _rControlList); private: // setting/retrieving the current connection URL // necessary because for some types, the URL must be decoded for display purposes /** enables the test connection button, if allowed */ virtual bool checkTestConnection(); /** opens the FileOpen dialog and asks for a FileName @param _sFilterName The filter name. @param _sExtension The filter extension. */ }; //......................................................................... } // namespace dbaui //......................................................................... #endif // _DBAUI_DETAILPAGES_HXX_ <|endoftext|>
<commit_before>/* Basic Server code for CMPT 276, Spring 2016. */ #include <exception> #include <iostream> #include <memory> #include <string> #include <unordered_map> #include <utility> #include <vector> #include <cpprest/base_uri.h> #include <cpprest/http_listener.h> #include <cpprest/json.h> #include <pplx/pplxtasks.h> #include <was/common.h> #include <was/storage_account.h> #include <was/table.h> #include "TableCache.h" #include "config.h" #include "make_unique.h" #include "azure_keys.h" using azure::storage::cloud_storage_account; using azure::storage::storage_credentials; using azure::storage::storage_exception; using azure::storage::cloud_table; using azure::storage::cloud_table_client; using azure::storage::edm_type; using azure::storage::entity_property; using azure::storage::table_entity; using azure::storage::table_operation; using azure::storage::table_query; using azure::storage::table_query_iterator; using azure::storage::table_result; using pplx::extensibility::critical_section_t; using pplx::extensibility::scoped_critical_section_t; using std::cin; using std::cout; using std::endl; using std::getline; using std::make_pair; using std::pair; using std::string; using std::unordered_map; using std::vector; using web::http::http_headers; using web::http::http_request; using web::http::methods; using web::http::status_codes; using web::http::uri; using web::json::value; using web::http::experimental::listener::http_listener; using prop_vals_t = vector<pair<string,value>>; constexpr const char* def_url = "http://localhost:34568"; const string create_table {"CreateTable"}; const string delete_table {"DeleteTable"}; const string update_entity {"UpdateEntity"}; const string delete_entity {"DeleteEntity"}; /* Cache of opened tables */ TableCache table_cache {storage_connection_string}; /* Convert properties represented in Azure Storage type to prop_vals_t type. */ prop_vals_t get_properties (const table_entity::properties_type& properties, prop_vals_t values = prop_vals_t {}) { for (const auto v : properties) { if (v.second.property_type() == edm_type::string) { values.push_back(make_pair(v.first, value::string(v.second.string_value()))); } else if (v.second.property_type() == edm_type::datetime) { values.push_back(make_pair(v.first, value::string(v.second.str()))); } else if(v.second.property_type() == edm_type::int32) { values.push_back(make_pair(v.first, value::number(v.second.int32_value()))); } else if(v.second.property_type() == edm_type::int64) { values.push_back(make_pair(v.first, value::number(v.second.int64_value()))); } else if(v.second.property_type() == edm_type::double_floating_point) { values.push_back(make_pair(v.first, value::number(v.second.double_value()))); } else if(v.second.property_type() == edm_type::boolean) { values.push_back(make_pair(v.first, value::boolean(v.second.boolean_value()))); } else { values.push_back(make_pair(v.first, value::string(v.second.str()))); } } return values; } /* Given an HTTP message with a JSON body, return the JSON body as an unordered map of strings to strings. Note that all types of JSON values are returned as strings. Use C++ conversion utilities to convert to numbers or dates as necessary. */ unordered_map<string,string> get_json_body(http_request message) { unordered_map<string,string> results {}; const http_headers& headers {message.headers()}; auto content_type (headers.find("Content-Type")); if (content_type == headers.end() || content_type->second != "application/json") return results; value json{}; message.extract_json(true) .then([&json](value v) -> bool { json = v; return true; }) .wait(); if (json.is_object()) { for (const auto& v : json.as_object()) { if (v.second.is_string()) { results[v.first] = v.second.as_string(); } else { results[v.first] = v.second.serialize(); } } } return results; } /* Top-level routine for processing all HTTP GET requests. GET is the only request that has no command. All operands specify the value(s) to be retrieved. */ void handle_get(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** GET " << path << endl; auto paths = uri::split_path(path); // Need at least a table name if (paths.size() < 1) { message.reply(status_codes::BadRequest); return; } cloud_table table {table_cache.lookup_table(paths[0])}; if ( ! table.exists()) { message.reply(status_codes::NotFound); return; } // GET all entries in table if (paths.size() == 1) { table_query query {}; table_query_iterator end; table_query_iterator it = table.execute_query(query); vector<value> key_vec; while (it != end) { cout << "Key: " << it->partition_key() << " / " << it->row_key() << endl; prop_vals_t keys { make_pair("Partition",value::string(it->partition_key())), make_pair("Row", value::string(it->row_key()))}; keys = get_properties(it->properties(), keys); key_vec.push_back(value::object(keys)); ++it; } message.reply(status_codes::OK, value::array(key_vec)); return; } // GET all entities from a specific partition: Partition == paths[1], * == paths[2] // Checking for malformed request if (paths.size() == 2) { //Path includes table and partition but no row //Or table and row but no partition //Or partition and row but no table message.reply(status_codes::BadRequest); return; } // User has indicated they want all items in this partition by the `*` if (paths.size() == 3 && paths[2] == "*") { // Create Query table_query query {}; table_query_iterator end; query.set_filter_string(azure::storage::table_query::generate_filter_condition("PartitionKey", azure::storage::query_comparison_operator::equal, paths[1])); // Execute Query table_query_iterator it = table.execute_query(query); // Parse into vector vector<value> key_vec; while (it != end) { cout << "Key: " << it->partition_key() << " / " << it->row_key() << endl; prop_vals_t keys { make_pair("Partition",value::string(it->partition_key())), make_pair("Row", value::string(it->row_key()))}; keys = get_properties(it->properties(), keys); key_vec.push_back(value::object(keys)); ++it; } // message reply message.reply(status_codes::OK, value::array(key_vec)); return; } // GET specific entry: Partition == paths[1], Row == paths[2] table_operation retrieve_operation {table_operation::retrieve_entity(paths[1], paths[2])}; table_result retrieve_result {table.execute(retrieve_operation)}; cout << "HTTP code: " << retrieve_result.http_status_code() << endl; if (retrieve_result.http_status_code() == status_codes::NotFound) { message.reply(status_codes::NotFound); return; } table_entity entity {retrieve_result.entity()}; table_entity::properties_type properties {entity.properties()}; // If the entity has any properties, return them as JSON prop_vals_t values (get_properties(properties)); if (values.size() > 0) message.reply(status_codes::OK, value::object(values)); else message.reply(status_codes::OK); } /* Top-level routine for processing all HTTP POST requests. */ void handle_post(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** POST " << path << endl; auto paths = uri::split_path(path); // Need at least an operation and a table name if (paths.size() < 2) { message.reply(status_codes::BadRequest); return; } string table_name {paths[1]}; cloud_table table {table_cache.lookup_table(table_name)}; // Create table (idempotent if table exists) if (paths[0] == create_table) { cout << "Create " << table_name << endl; bool created {table.create_if_not_exists()}; cout << "Administrative table URI " << table.uri().primary_uri().to_string() << endl; if (created) message.reply(status_codes::Created); else message.reply(status_codes::Accepted); } else { message.reply(status_codes::BadRequest); } } /* Top-level routine for processing all HTTP PUT requests. */ void handle_put(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** PUT " << path << endl; auto paths = uri::split_path(path); // Need at least an operation, table name, partition, and row if (paths.size() < 4) { message.reply(status_codes::BadRequest); return; } cloud_table table {table_cache.lookup_table(paths[1])}; if ( ! table.exists()) { message.reply(status_codes::NotFound); return; } table_entity entity {paths[2], paths[3]}; // Update entity if (paths[0] == update_entity) { cout << "Update " << entity.partition_key() << " / " << entity.row_key() << endl; table_entity::properties_type& properties = entity.properties(); for (const auto v : get_json_body(message)) { properties[v.first] = entity_property {v.second}; } table_operation operation {table_operation::insert_or_merge_entity(entity)}; table_result op_result {table.execute(operation)}; message.reply(status_codes::OK); } else { message.reply(status_codes::BadRequest); } } /* Top-level routine for processing all HTTP DELETE requests. */ void handle_delete(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** DELETE " << path << endl; auto paths = uri::split_path(path); // Need at least an operation and table name if (paths.size() < 2) { message.reply(status_codes::BadRequest); return; } string table_name {paths[1]}; cloud_table table {table_cache.lookup_table(table_name)}; // Delete table if (paths[0] == delete_table) { cout << "Delete " << table_name << endl; if ( ! table.exists()) { message.reply(status_codes::NotFound); } table.delete_table(); table_cache.delete_entry(table_name); message.reply(status_codes::OK); } // Delete entity else if (paths[0] == delete_entity) { // For delete entity, also need partition and row if (paths.size() < 4) { message.reply(status_codes::BadRequest); return; } table_entity entity {paths[2], paths[3]}; cout << "Delete " << entity.partition_key() << " / " << entity.row_key()<< endl; table_operation operation {table_operation::delete_entity(entity)}; table_result op_result {table.execute(operation)}; int code {op_result.http_status_code()}; if (code == status_codes::OK || code == status_codes::NoContent) message.reply(status_codes::OK); else message.reply(code); } else { message.reply(status_codes::BadRequest); } } /* Main server routine Install handlers for the HTTP requests and open the listener, which processes each request asynchronously. Wait for a carriage return, then shut the server down. */ int main (int argc, char const * argv[]) { http_listener listener {def_url}; listener.support(methods::GET, &handle_get); listener.support(methods::POST, &handle_post); listener.support(methods::PUT, &handle_put); listener.support(methods::DEL, &handle_delete); listener.open().wait(); // Wait for listener to complete starting cout << "Enter carriage return to stop server." << endl; string line; getline(std::cin, line); // Shut it down listener.close().wait(); cout << "Closed" << endl; } <commit_msg>add check for no partition in request<commit_after>/* Basic Server code for CMPT 276, Spring 2016. */ #include <exception> #include <iostream> #include <memory> #include <string> #include <unordered_map> #include <utility> #include <vector> #include <cpprest/base_uri.h> #include <cpprest/http_listener.h> #include <cpprest/json.h> #include <pplx/pplxtasks.h> #include <was/common.h> #include <was/storage_account.h> #include <was/table.h> #include "TableCache.h" #include "config.h" #include "make_unique.h" #include "azure_keys.h" using azure::storage::cloud_storage_account; using azure::storage::storage_credentials; using azure::storage::storage_exception; using azure::storage::cloud_table; using azure::storage::cloud_table_client; using azure::storage::edm_type; using azure::storage::entity_property; using azure::storage::table_entity; using azure::storage::table_operation; using azure::storage::table_query; using azure::storage::table_query_iterator; using azure::storage::table_result; using pplx::extensibility::critical_section_t; using pplx::extensibility::scoped_critical_section_t; using std::cin; using std::cout; using std::endl; using std::getline; using std::make_pair; using std::pair; using std::string; using std::unordered_map; using std::vector; using web::http::http_headers; using web::http::http_request; using web::http::methods; using web::http::status_codes; using web::http::uri; using web::json::value; using web::http::experimental::listener::http_listener; using prop_vals_t = vector<pair<string,value>>; constexpr const char* def_url = "http://localhost:34568"; const string create_table {"CreateTable"}; const string delete_table {"DeleteTable"}; const string update_entity {"UpdateEntity"}; const string delete_entity {"DeleteEntity"}; /* Cache of opened tables */ TableCache table_cache {storage_connection_string}; /* Convert properties represented in Azure Storage type to prop_vals_t type. */ prop_vals_t get_properties (const table_entity::properties_type& properties, prop_vals_t values = prop_vals_t {}) { for (const auto v : properties) { if (v.second.property_type() == edm_type::string) { values.push_back(make_pair(v.first, value::string(v.second.string_value()))); } else if (v.second.property_type() == edm_type::datetime) { values.push_back(make_pair(v.first, value::string(v.second.str()))); } else if(v.second.property_type() == edm_type::int32) { values.push_back(make_pair(v.first, value::number(v.second.int32_value()))); } else if(v.second.property_type() == edm_type::int64) { values.push_back(make_pair(v.first, value::number(v.second.int64_value()))); } else if(v.second.property_type() == edm_type::double_floating_point) { values.push_back(make_pair(v.first, value::number(v.second.double_value()))); } else if(v.second.property_type() == edm_type::boolean) { values.push_back(make_pair(v.first, value::boolean(v.second.boolean_value()))); } else { values.push_back(make_pair(v.first, value::string(v.second.str()))); } } return values; } /* Given an HTTP message with a JSON body, return the JSON body as an unordered map of strings to strings. Note that all types of JSON values are returned as strings. Use C++ conversion utilities to convert to numbers or dates as necessary. */ unordered_map<string,string> get_json_body(http_request message) { unordered_map<string,string> results {}; const http_headers& headers {message.headers()}; auto content_type (headers.find("Content-Type")); if (content_type == headers.end() || content_type->second != "application/json") return results; value json{}; message.extract_json(true) .then([&json](value v) -> bool { json = v; return true; }) .wait(); if (json.is_object()) { for (const auto& v : json.as_object()) { if (v.second.is_string()) { results[v.first] = v.second.as_string(); } else { results[v.first] = v.second.serialize(); } } } return results; } /* Top-level routine for processing all HTTP GET requests. GET is the only request that has no command. All operands specify the value(s) to be retrieved. */ void handle_get(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** GET " << path << endl; auto paths = uri::split_path(path); // Need at least a table name if (paths.size() < 1) { message.reply(status_codes::BadRequest); return; } cloud_table table {table_cache.lookup_table(paths[0])}; if ( ! table.exists()) { message.reply(status_codes::NotFound); return; } // GET all entries in table if (paths.size() == 1) { table_query query {}; table_query_iterator end; table_query_iterator it = table.execute_query(query); vector<value> key_vec; while (it != end) { cout << "Key: " << it->partition_key() << " / " << it->row_key() << endl; prop_vals_t keys { make_pair("Partition",value::string(it->partition_key())), make_pair("Row", value::string(it->row_key()))}; keys = get_properties(it->properties(), keys); key_vec.push_back(value::object(keys)); ++it; } message.reply(status_codes::OK, value::array(key_vec)); return; } // GET all entities from a specific partition: Partition == paths[1], * == paths[2] // Checking for malformed request if (paths.size() == 2 || paths[1] == "") { //Path includes table and partition but no row //Or table and row but no partition //Or partition and row but no table message.reply(status_codes::BadRequest); return; } // User has indicated they want all items in this partition by the `*` if (paths.size() == 3 && paths[2] == "*") { // Create Query table_query query {}; table_query_iterator end; query.set_filter_string(azure::storage::table_query::generate_filter_condition("PartitionKey", azure::storage::query_comparison_operator::equal, paths[1])); // Execute Query table_query_iterator it = table.execute_query(query); // Parse into vector vector<value> key_vec; while (it != end) { cout << "Key: " << it->partition_key() << " / " << it->row_key() << endl; prop_vals_t keys { make_pair("Partition",value::string(it->partition_key())), make_pair("Row", value::string(it->row_key()))}; keys = get_properties(it->properties(), keys); key_vec.push_back(value::object(keys)); ++it; } // message reply message.reply(status_codes::OK, value::array(key_vec)); return; } // GET specific entry: Partition == paths[1], Row == paths[2] table_operation retrieve_operation {table_operation::retrieve_entity(paths[1], paths[2])}; table_result retrieve_result {table.execute(retrieve_operation)}; cout << "HTTP code: " << retrieve_result.http_status_code() << endl; if (retrieve_result.http_status_code() == status_codes::NotFound) { message.reply(status_codes::NotFound); return; } table_entity entity {retrieve_result.entity()}; table_entity::properties_type properties {entity.properties()}; // If the entity has any properties, return them as JSON prop_vals_t values (get_properties(properties)); if (values.size() > 0) message.reply(status_codes::OK, value::object(values)); else message.reply(status_codes::OK); } /* Top-level routine for processing all HTTP POST requests. */ void handle_post(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** POST " << path << endl; auto paths = uri::split_path(path); // Need at least an operation and a table name if (paths.size() < 2) { message.reply(status_codes::BadRequest); return; } string table_name {paths[1]}; cloud_table table {table_cache.lookup_table(table_name)}; // Create table (idempotent if table exists) if (paths[0] == create_table) { cout << "Create " << table_name << endl; bool created {table.create_if_not_exists()}; cout << "Administrative table URI " << table.uri().primary_uri().to_string() << endl; if (created) message.reply(status_codes::Created); else message.reply(status_codes::Accepted); } else { message.reply(status_codes::BadRequest); } } /* Top-level routine for processing all HTTP PUT requests. */ void handle_put(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** PUT " << path << endl; auto paths = uri::split_path(path); // Need at least an operation, table name, partition, and row if (paths.size() < 4) { message.reply(status_codes::BadRequest); return; } cloud_table table {table_cache.lookup_table(paths[1])}; if ( ! table.exists()) { message.reply(status_codes::NotFound); return; } table_entity entity {paths[2], paths[3]}; // Update entity if (paths[0] == update_entity) { cout << "Update " << entity.partition_key() << " / " << entity.row_key() << endl; table_entity::properties_type& properties = entity.properties(); for (const auto v : get_json_body(message)) { properties[v.first] = entity_property {v.second}; } table_operation operation {table_operation::insert_or_merge_entity(entity)}; table_result op_result {table.execute(operation)}; message.reply(status_codes::OK); } else { message.reply(status_codes::BadRequest); } } /* Top-level routine for processing all HTTP DELETE requests. */ void handle_delete(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** DELETE " << path << endl; auto paths = uri::split_path(path); // Need at least an operation and table name if (paths.size() < 2) { message.reply(status_codes::BadRequest); return; } string table_name {paths[1]}; cloud_table table {table_cache.lookup_table(table_name)}; // Delete table if (paths[0] == delete_table) { cout << "Delete " << table_name << endl; if ( ! table.exists()) { message.reply(status_codes::NotFound); } table.delete_table(); table_cache.delete_entry(table_name); message.reply(status_codes::OK); } // Delete entity else if (paths[0] == delete_entity) { // For delete entity, also need partition and row if (paths.size() < 4) { message.reply(status_codes::BadRequest); return; } table_entity entity {paths[2], paths[3]}; cout << "Delete " << entity.partition_key() << " / " << entity.row_key()<< endl; table_operation operation {table_operation::delete_entity(entity)}; table_result op_result {table.execute(operation)}; int code {op_result.http_status_code()}; if (code == status_codes::OK || code == status_codes::NoContent) message.reply(status_codes::OK); else message.reply(code); } else { message.reply(status_codes::BadRequest); } } /* Main server routine Install handlers for the HTTP requests and open the listener, which processes each request asynchronously. Wait for a carriage return, then shut the server down. */ int main (int argc, char const * argv[]) { http_listener listener {def_url}; listener.support(methods::GET, &handle_get); listener.support(methods::POST, &handle_post); listener.support(methods::PUT, &handle_put); listener.support(methods::DEL, &handle_delete); listener.open().wait(); // Wait for listener to complete starting cout << "Enter carriage return to stop server." << endl; string line; getline(std::cin, line); // Shut it down listener.close().wait(); cout << "Closed" << endl; } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////// // // NAME // BlendImages.cpp -- blend together a set of overlapping images // // DESCRIPTION // This routine takes a collection of images aligned more or less horizontally // and stitches together a mosaic. // // The images can be blended together any way you like, but I would recommend // using a soft halfway blend of the kind Steve presented in the first lecture. // // Once you have blended the images together, you should crop the resulting // mosaic at the halfway points of the first and last image. You should also // take out any accumulated vertical drift using an affine warp. // Lucas-Kanade Taylor series expansion of the registration error. // // SEE ALSO // BlendImages.h longer description of parameters // // Copyright ?Richard Szeliski, 2001. See Copyright.h for more details // (modified for CSE455 Winter 2003) // /////////////////////////////////////////////////////////////////////////// #include "ImageLib/ImageLib.h" #include "BlendImages.h" #include <float.h> #include <math.h> #include <iostream> using namespace std; #define MAX(x,y) (((x) < (y)) ? (y) : (x)) #define MIN(x,y) (((x) < (y)) ? (x) : (y)) /* Return the closest integer to x, rounding up */ static int iround(double x) { if (x < 0.0) { return (int) (x - 0.5); } else { return (int) (x + 0.5); } } void ImageBoundingBox(CImage &image, CTransform3x3 &M, int &min_x, int &min_y, int &max_x, int &max_y) { // This is a useful helper function that you might choose to implement // takes an image, and a transform, and computes the bounding box of the // transformed image. CShape sh=image.Shape(); int width=sh.width; int height=sh.height; CVector3 p1,p2,p3,p4; p1[0]=0;p1[1]=0;p1[2]=1; p2[0]=0;p2[1]=height;p2[2]=1; p3[0]=width;p3[1]=0;p3[2]=1; p4[0]=width;p4[1]=height;p4[2]=1; p1=M*p1;p2=M*p2;p3=M*p3;p4=M*p4; min_x=iround(MIN(p1[0]/p1[2],p2[0]/p2[2])); max_x=iround(MAX(p3[0]/p3[2],p4[0]/p4[2])); min_y=iround(MIN(p1[1]/p1[2],p3[1]/p3[2])); max_y=iround(MAX(p2[1]/p2[2],p4[1]/p4[2])); } /******************* TO DO ********************* * AccumulateBlend: * INPUT: * img: a new image to be added to acc * acc: portion of the accumulated image where img is to be added * M: the transformation mapping the input image 'img' into the output panorama 'acc' * blendWidth: width of the blending function (horizontal hat function; * try other blending functions for extra credit) * OUTPUT: * add a weighted copy of img to the subimage specified in acc * the first 3 band of acc records the weighted sum of pixel colors * the fourth band of acc records the sum of weight */ static void AccumulateBlend(CByteImage& img, CFloatImage& acc, CTransform3x3 M, float blendWidth) { // BEGIN TODO // Fill in this routine CShape sh=img.Shape(); int width=sh.width; int height=sh.height; CShape shacc=acc.Shape(); int widthacc=shacc.width; int heightacc=shacc.height; int min_x,min_y,max_x,max_y; ImageBoundingBox(img,M,min_x,min_y,max_x,max_y); int middle_x=(max_x+min_x)/2; CVector3 p; int newx,newy; double weight; for (int ii=0;ii<width;ii++) { for (int jj=0;jj<height;jj++) { p[0]=ii;p[1]=jj;p[2]=1; p=M*p; newx=iround(p[0]/p[2]);newy=iround(p[1]/p[2]); if ((newx>=0)&&(newx<widthacc)&&(newy>=0)&&(newy<heightacc)) { weight=1; if ((newx>min_x)&&(newx<(min_x+blendWidth))) weight=(newx-min_x)/blendWidth; if ((newx<max_x)&&(newx>(max_x-blendWidth))) weight=(max_x-newx)/blendWidth; if ((img.Pixel(ii,jj,0)==0)&&(img.Pixel(ii,jj,0)==0)&&(img.Pixel(ii,jj,0)==0)) weight=0; acc.Pixel(newx,newy,0)+=(img.Pixel(ii,jj,0)*weight); acc.Pixel(newx,newy,1)+=(img.Pixel(ii,jj,1)*weight); acc.Pixel(newx,newy,2)+=(img.Pixel(ii,jj,2)*weight); acc.Pixel(newx,newy,3)+=weight; } } } printf("AccumulateBlend\n"); // END TODO } /******************* TO DO 5 ********************* * NormalizeBlend: * INPUT: * acc: input image whose alpha channel (4th channel) contains * normalizing weight values * img: where output image will be stored * OUTPUT: * normalize r,g,b values (first 3 channels) of acc and store it into img */ static void NormalizeBlend(CFloatImage& acc, CByteImage& img) { // BEGIN TODO // fill in this routine.. CShape shacc=acc.Shape(); int widthacc=shacc.width; int heightacc=shacc.height; for (int ii=0;ii<widthacc;ii++) { for (int jj=0;jj<heightacc;jj++) { if (acc.Pixel(ii,jj,3)>0) { img.Pixel(ii,jj,0)=(int)(acc.Pixel(ii,jj,0)/acc.Pixel(ii,jj,3)); img.Pixel(ii,jj,1)=(int)(acc.Pixel(ii,jj,1)/acc.Pixel(ii,jj,3)); img.Pixel(ii,jj,2)=(int)(acc.Pixel(ii,jj,2)/acc.Pixel(ii,jj,3)); } else { img.Pixel(ii,jj,0)=0; img.Pixel(ii,jj,1)=0; img.Pixel(ii,jj,2)=0; } } } printf("TODO: %s:%d\n", __FILE__, __LINE__); // END TODO } /******************* TO DO 5 ********************* * BlendImages: * INPUT: * ipv: list of input images and their relative positions in the mosaic * blendWidth: width of the blending function * OUTPUT: * create & return final mosaic by blending all images * and correcting for any vertical drift */ CByteImage BlendImages(CImagePositionV& ipv, float blendWidth) { // Assume all the images are of the same shape (for now) CByteImage& img0 = ipv[0].img; CShape sh = img0.Shape(); int width = sh.width; int height = sh.height; int nBands = sh.nBands; // int dim[2] = {width, height}; int n = ipv.size(); if (n == 0) return CByteImage(0,0,1); bool is360 = false; // Hack to detect if this is a 360 panorama if (ipv[0].imgName == ipv[n-1].imgName) is360 = true; // Compute the bounding box for the mosaic float min_x = FLT_MAX, min_y = FLT_MAX; float max_x = 0, max_y = 0; int i; int tmpmin_x,tmpmin_y,tmpmax_x,tmpmax_y; for (i = 0; i < n; i++) { CTransform3x3 &T = ipv[i].position; // BEGIN TODO // add some code here to update min_x, ..., max_y ImageBoundingBox(img0,T,tmpmin_x,tmpmin_y,tmpmax_x,tmpmax_y); min_x=MIN(tmpmin_x,min_x); min_y=MIN(tmpmin_y,min_y); max_x=MAX(tmpmax_x,max_x); max_y=MAX(tmpmax_y,max_y); // END TODO } // Create a floating point accumulation image CShape mShape((int)(ceil(max_x) - floor(min_x)), (int)(ceil(max_y) - floor(min_y)), nBands + 1); CFloatImage accumulator(mShape); accumulator.ClearPixels(); double x_init, x_final; double y_init, y_final; // Add in all of the images for (i = 0; i < n; i++) { // Compute the sub-image involved CTransform3x3 &M = ipv[i].position; CTransform3x3 M_t = CTransform3x3::Translation(-min_x, -min_y) * M; CByteImage& img = ipv[i].img; // Perform the accumulation AccumulateBlend(img, accumulator, M_t, blendWidth); if (i == 0) { CVector3 p; p[0] = 0.5 * width; p[1] = 0.0; p[2] = 1.0; p = M_t * p; x_init = p[0]; y_init = p[1]; } else if (i == n - 1) { CVector3 p; p[0] = 0.5 * width; p[1] = 0.0; p[2] = 1.0; p = M_t * p; x_final = p[0]; y_final = p[1]; } } // Normalize the results mShape = CShape((int)(ceil(max_x) - floor(min_x)), (int)(ceil(max_y) - floor(min_y)), nBands); CByteImage compImage(mShape); NormalizeBlend(accumulator, compImage); bool debug_comp = false; if (debug_comp) WriteFile(compImage, "tmp_comp.tga"); // Allocate the final image shape int outputWidth = 0; if (is360) { outputWidth = mShape.width - width; } else { outputWidth = mShape.width; } CShape cShape(outputWidth, mShape.height, nBands); CByteImage croppedImage(cShape); // Compute the affine transformation CTransform3x3 A = CTransform3x3(); // identify transform to initialize // BEGIN TODO // fill in appropriate entries in A to trim the left edge and // to take out the vertical drift if this is a 360 panorama // (i.e. is360 is true) double k; if (is360) { /*CTransform3x3 AA = CTransform3x3();; k=(y_final-y_init)/(x_final-x_init); AA[0][0]=1;AA[0][1]=0;AA[0][2]=0; AA[1][0]=k;AA[1][1]=1;AA[1][2]=0; AA[2][0]=0;AA[2][1]=0;AA[2][2]=1; A = CTransform3x3::Translation(-x_init, -y_init) * AA; */ A[0][0] = 1; A[0][1] = 0; A[0][2] = width/2; // x translation A[1][0] = -ipv[n-1].position[1][2] / cShape.width; // delta y per unit x, TODO A[1][1] = 1; A[1][2] = 0; // y translation A[2][0] = 0; A[2][1] = 0; A[2][2] = 1; } // END TODO // Warp and crop the composite WarpGlobal(compImage, croppedImage, A, eWarpInterpLinear); return croppedImage; } <commit_msg>comment added<commit_after>/////////////////////////////////////////////////////////////////////////// // // NAME // BlendImages.cpp -- blend together a set of overlapping images // // DESCRIPTION // This routine takes a collection of images aligned more or less horizontally // and stitches together a mosaic. // // The images can be blended together any way you like, but I would recommend // using a soft halfway blend of the kind Steve presented in the first lecture. // // Once you have blended the images together, you should crop the resulting // mosaic at the halfway points of the first and last image. You should also // take out any accumulated vertical drift using an affine warp. // Lucas-Kanade Taylor series expansion of the registration error. // // SEE ALSO // BlendImages.h longer description of parameters // // Copyright ?Richard Szeliski, 2001. See Copyright.h for more details // (modified for CSE455 Winter 2003) // /////////////////////////////////////////////////////////////////////////// #include "ImageLib/ImageLib.h" #include "BlendImages.h" #include <float.h> #include <math.h> #include <iostream> using namespace std; #define MAX(x,y) (((x) < (y)) ? (y) : (x)) #define MIN(x,y) (((x) < (y)) ? (x) : (y)) /* Return the closest integer to x, rounding up */ static int iround(double x) { if (x < 0.0) { return (int) (x - 0.5); } else { return (int) (x + 0.5); } } void ImageBoundingBox(CImage &image, CTransform3x3 &M, int &min_x, int &min_y, int &max_x, int &max_y) { // This is a useful helper function that you might choose to implement // takes an image, and a transform, and computes the bounding box of the // transformed image. CShape sh=image.Shape(); int width=sh.width; int height=sh.height; CVector3 p1,p2,p3,p4; p1[0]=0;p1[1]=0;p1[2]=1; p2[0]=0;p2[1]=height;p2[2]=1; p3[0]=width;p3[1]=0;p3[2]=1; p4[0]=width;p4[1]=height;p4[2]=1; p1=M*p1;p2=M*p2;p3=M*p3;p4=M*p4; min_x=iround(MIN(p1[0]/p1[2],p2[0]/p2[2])); max_x=iround(MAX(p3[0]/p3[2],p4[0]/p4[2])); min_y=iround(MIN(p1[1]/p1[2],p3[1]/p3[2])); max_y=iround(MAX(p2[1]/p2[2],p4[1]/p4[2])); } /******************* TO DO ********************* * AccumulateBlend: * INPUT: * img: a new image to be added to acc * acc: portion of the accumulated image where img is to be added * M: the transformation mapping the input image 'img' into the output panorama 'acc' * blendWidth: width of the blending function (horizontal hat function; * try other blending functions for extra credit) * OUTPUT: * add a weighted copy of img to the subimage specified in acc * the first 3 band of acc records the weighted sum of pixel colors * the fourth band of acc records the sum of weight */ static void AccumulateBlend(CByteImage& img, CFloatImage& acc, CTransform3x3 M, float blendWidth) { // BEGIN TODO // Fill in this routine // get shape of acc and img CShape sh=img.Shape(); int width=sh.width; int height=sh.height; CShape shacc=acc.Shape(); int widthacc=shacc.width; int heightacc=shacc.height; // get the bounding box of img in acc int min_x,min_y,max_x,max_y; ImageBoundingBox(img,M,min_x,min_y,max_x,max_y); int middle_x=(max_x+min_x)/2; // add every pixel in img to acc, feather the region withing blendwidth to the bounding box, // pure black pixels (caused by warping) are not added CVector3 p; int newx,newy; double weight; for (int ii=0;ii<width;ii++) { for (int jj=0;jj<height;jj++) { p[0]=ii;p[1]=jj;p[2]=1; p=M*p; newx=iround(p[0]/p[2]);newy=iround(p[1]/p[2]); if ((newx>=0)&&(newx<widthacc)&&(newy>=0)&&(newy<heightacc)) { weight=1; if ((newx>min_x)&&(newx<(min_x+blendWidth))) weight=(newx-min_x)/blendWidth; if ((newx<max_x)&&(newx>(max_x-blendWidth))) weight=(max_x-newx)/blendWidth; if ((img.Pixel(ii,jj,0)==0)&&(img.Pixel(ii,jj,0)==0)&&(img.Pixel(ii,jj,0)==0)) weight=0; acc.Pixel(newx,newy,0)+=(img.Pixel(ii,jj,0)*weight); acc.Pixel(newx,newy,1)+=(img.Pixel(ii,jj,1)*weight); acc.Pixel(newx,newy,2)+=(img.Pixel(ii,jj,2)*weight); acc.Pixel(newx,newy,3)+=weight; } } } printf("AccumulateBlend\n"); // END TODO } /******************* TO DO 5 ********************* * NormalizeBlend: * INPUT: * acc: input image whose alpha channel (4th channel) contains * normalizing weight values * img: where output image will be stored * OUTPUT: * normalize r,g,b values (first 3 channels) of acc and store it into img */ static void NormalizeBlend(CFloatImage& acc, CByteImage& img) { // BEGIN TODO // fill in this routine.. // divide the total weight for every pixel CShape shacc=acc.Shape(); int widthacc=shacc.width; int heightacc=shacc.height; for (int ii=0;ii<widthacc;ii++) { for (int jj=0;jj<heightacc;jj++) { if (acc.Pixel(ii,jj,3)>0) { img.Pixel(ii,jj,0)=(int)(acc.Pixel(ii,jj,0)/acc.Pixel(ii,jj,3)); img.Pixel(ii,jj,1)=(int)(acc.Pixel(ii,jj,1)/acc.Pixel(ii,jj,3)); img.Pixel(ii,jj,2)=(int)(acc.Pixel(ii,jj,2)/acc.Pixel(ii,jj,3)); } else { img.Pixel(ii,jj,0)=0; img.Pixel(ii,jj,1)=0; img.Pixel(ii,jj,2)=0; } } } printf("TODO: %s:%d\n", __FILE__, __LINE__); // END TODO } /******************* TO DO 5 ********************* * BlendImages: * INPUT: * ipv: list of input images and their relative positions in the mosaic * blendWidth: width of the blending function * OUTPUT: * create & return final mosaic by blending all images * and correcting for any vertical drift */ CByteImage BlendImages(CImagePositionV& ipv, float blendWidth) { // Assume all the images are of the same shape (for now) CByteImage& img0 = ipv[0].img; CShape sh = img0.Shape(); int width = sh.width; int height = sh.height; int nBands = sh.nBands; // int dim[2] = {width, height}; int n = ipv.size(); if (n == 0) return CByteImage(0,0,1); bool is360 = false; // Hack to detect if this is a 360 panorama if (ipv[0].imgName == ipv[n-1].imgName) is360 = true; // Compute the bounding box for the mosaic float min_x = FLT_MAX, min_y = FLT_MAX; float max_x = 0, max_y = 0; int i; int tmpmin_x,tmpmin_y,tmpmax_x,tmpmax_y; for (i = 0; i < n; i++) { CTransform3x3 &T = ipv[i].position; // BEGIN TODO // add some code here to update min_x, ..., max_y ImageBoundingBox(img0,T,tmpmin_x,tmpmin_y,tmpmax_x,tmpmax_y); min_x=MIN(tmpmin_x,min_x); min_y=MIN(tmpmin_y,min_y); max_x=MAX(tmpmax_x,max_x); max_y=MAX(tmpmax_y,max_y); // END TODO } // Create a floating point accumulation image CShape mShape((int)(ceil(max_x) - floor(min_x)), (int)(ceil(max_y) - floor(min_y)), nBands + 1); CFloatImage accumulator(mShape); accumulator.ClearPixels(); double x_init, x_final; double y_init, y_final; // Add in all of the images for (i = 0; i < n; i++) { // Compute the sub-image involved CTransform3x3 &M = ipv[i].position; CTransform3x3 M_t = CTransform3x3::Translation(-min_x, -min_y) * M; CByteImage& img = ipv[i].img; // Perform the accumulation AccumulateBlend(img, accumulator, M_t, blendWidth); if (i == 0) { CVector3 p; p[0] = 0.5 * width; p[1] = 0.0; p[2] = 1.0; p = M_t * p; x_init = p[0]; y_init = p[1]; } else if (i == n - 1) { CVector3 p; p[0] = 0.5 * width; p[1] = 0.0; p[2] = 1.0; p = M_t * p; x_final = p[0]; y_final = p[1]; } } // Normalize the results mShape = CShape((int)(ceil(max_x) - floor(min_x)), (int)(ceil(max_y) - floor(min_y)), nBands); CByteImage compImage(mShape); NormalizeBlend(accumulator, compImage); bool debug_comp = false; if (debug_comp) WriteFile(compImage, "tmp_comp.tga"); // Allocate the final image shape int outputWidth = 0; if (is360) { outputWidth = mShape.width - width; } else { outputWidth = mShape.width; } CShape cShape(outputWidth, mShape.height, nBands); CByteImage croppedImage(cShape); // Compute the affine transformation CTransform3x3 A = CTransform3x3(); // identify transform to initialize // BEGIN TODO // fill in appropriate entries in A to trim the left edge and // to take out the vertical drift if this is a 360 panorama // (i.e. is360 is true) double k; if (is360) { if (x_init>x_final) { int tmp=x_init; x_init=x_final; x_final=tmp; } CTransform3x3 AA = CTransform3x3();; k=-(y_final-y_init)/(x_final-x_init); AA[0][0]=1;AA[0][1]=0;AA[0][2]=0; AA[1][0]=k;AA[1][1]=1;AA[1][2]=0; AA[2][0]=0;AA[2][1]=0;AA[2][2]=1; A = CTransform3x3::Translation(x_init, -y_init) * AA; } // END TODO // Warp and crop the composite WarpGlobal(compImage, croppedImage, A, eWarpInterpLinear); return croppedImage; } <|endoftext|>
<commit_before>// Time: O(n) // Space: O(1) // Bottom-Up. class Solution { public: /** * @param A: Given an integer array * @return: void */ void heapify(vector<int> &A) { for (int i = A.size() / 2; i >= 0; --i) { sift_down(A, i); } } void sift_down(vector<int>& A, int index) { int smallest = k; if (k * 2 + 1 < A.size() && A[k * 2 + 1] < A[smallest]) { smallest = k * 2 + 1; } else if (k * 2 + 2 < A.size() && A[k * 2 + 2] < A[smallest]) { smallest = k * 2 + 2; } if (smallest != k) { swap(A[smallest], A[k]); k = smallest; } } }; // Time: O(nlogn) // Space: O(1) // Top-Down. class Solution2 { public: /** * @param A: Given an integer array * @return: void */ void heapify(vector<int> &A) { for (int i = 0; i < A.size(); ++i) { sift_up(A, i); } } void sift_up(vector<int>& A, int index) { while ((index - 1) / 2 >= 0) { int parent = (index - 1) / 2; if (A[index] < A[parent]) { swap(A[parent], A[index]); index = parent; } else { break; } } } }; <commit_msg>Update heapify.cpp<commit_after>// Time: O(n) // Space: O(1) // Bottom-Up. class Solution { public: /** * @param A: Given an integer array * @return: void */ void heapify(vector<int> &A) { for (int i = A.size() / 2; i >= 0; --i) { sift_down(A, i); } } void sift_down(vector<int>& A, int index) { while (index < A.size()) { int smallest = index; if (index * 2 + 1 < A.size() && A[index * 2 + 1] < A[smallest]) { smallest = index * 2 + 1; } if (index * 2 + 2 < A.size() && A[index * 2 + 2] < A[smallest]) { smallest = index * 2 + 2; } if (smallest == index) { break; } swap(A[smallest], A[index]); index = smallest; } } }; // Time: O(nlogn) // Space: O(1) // Top-Down. class Solution2 { public: /** * @param A: Given an integer array * @return: void */ void heapify(vector<int> &A) { for (int i = 0; i < A.size(); ++i) { sift_up(A, i); } } void sift_up(vector<int>& A, int index) { while ((index - 1) / 2 >= 0) { int parent = (index - 1) / 2; if (A[index] < A[parent]) { swap(A[parent], A[index]); index = parent; } else { break; } } } }; <|endoftext|>
<commit_before>/************************************************************************* * * 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: opcodes.hxx,v $ * $Revision: 1.13 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _OPCODES_HXX #define _OPCODES_HXX #include "sbintern.hxx" #ifdef MTW #undef _NUMBER #endif // Ein Opcode ist entweder 1, 3 oder 5 Bytes lang, je nach numerischen // Wert des Opcodes (s.u.). enum SbiOpcode { // Alle Opcodes ohne Operanden _NOP = 0, SbOP0_START = _NOP, // Operatoren // die folgenden Operatoren sind genauso angeordnet // wie der enum SbxVarOp _EXP, _MUL, _DIV, _MOD, _PLUS, _MINUS, _NEG, _EQ, _NE, _LT, _GT, _LE, _GE, _IDIV, _AND, _OR, _XOR, _EQV, _IMP, _NOT, _CAT, // Ende enum SbxVarOp _LIKE, _IS, // Laden/speichern _ARGC, // neuen Argv einrichten _ARGV, // TOS ==> aktueller Argv _INPUT, // Input ==> TOS _LINPUT, // Line Input ==> TOS _GET, // TOS anfassen _SET, // Speichern Objekt TOS ==> TOS-1 _PUT, // TOS ==> TOS-1 _PUTC, // TOS ==> TOS-1, dann ReadOnly _DIM, // DIM _REDIM, // REDIM _REDIMP, // REDIM PRESERVE _ERASE, // TOS loeschen // Verzweigen _STOP, // Programmende _INITFOR, // FOR-Variable initialisieren _NEXT, // FOR-Variable inkrementieren _CASE, // Anfang CASE _ENDCASE, // Ende CASE _STDERROR, // Standard-Fehlerbehandlung _NOERROR, // keine Fehlerbehandlung _LEAVE, // UP verlassen // E/A _CHANNEL, // TOS = Kanalnummer _BPRINT, // print TOS _PRINTF, // print TOS in field _BWRITE, // write TOS _RENAME, // Rename Tos+1 to Tos _PROMPT, // TOS = Prompt for Input _RESTART, // Restartpunkt definieren _CHAN0, // I/O-Kanal 0 // Sonstiges _EMPTY, // Leeren Ausdruck auf Stack _ERROR, // TOS = Fehlercode _LSET, // Speichern Objekt TOS ==> TOS-1 _RSET, // Speichern Objekt TOS ==> TOS-1 _REDIMP_ERASE, // Copies array to be later used by REDIM PRESERVE before erasing it _INITFOREACH, _VBASET, // VBA-like Set _ERASE_CLEAR, // Erase array and clear variable SbOP0_END, // Alle Opcodes mit einem Operanden _NUMBER = 0x40, // Laden einer numerischen Konstanten (+ID) SbOP1_START = _NUMBER, _SCONST, // Laden einer Stringkonstanten (+ID) _CONST, // Immediate Load (+Wert) _ARGN, // Speichern eines named Args in Argv (+StringID) _PAD, // String auf feste Laenge bringen (+Laenge) // Verzweigungen _JUMP, // Sprung (+Target) _JUMPT, // TOS auswerten, bedingter Sprung (+Target) _JUMPF, // TOS auswerten, bedingter Sprung (+Target) _ONJUMP, // TOS auswerten, Sprung in JUMP-Tabelle (+MaxVal) _GOSUB, // UP-Aufruf (+Target) _RETURN, // UP-Return (+0 oder Target) _TESTFOR, // FOR-Variable testen, inkrementieren (+Endlabel) _CASETO, // Tos+1 <= Case <= Tos, 2xremove (+Target) _ERRHDL, // Fehler-Handler (+Offset) _RESUME, // Resume nach Fehlern (+0 or 1 or Label) // E/A _CLOSE, // (+Kanal/0) _PRCHAR, // (+char) // Verwaltung _SETCLASS, // Set + Klassennamen testen (+StringId) _TESTCLASS, // Check TOS class (+StringId) _LIB, // Libnamen fuer Declare-Procs setzen (+StringId) _BASED, // TOS wird um BASE erhoeht, BASE davor gepusht (+base) // Typanpassung im Argv _ARGTYP, // Letzten Parameter in Argv konvertieren (+Typ) _VBASETCLASS, // VBA-like Set SbOP1_END, // Alle Opcodes mit zwei Operanden _RTL = 0x80, // Laden aus RTL (+StringID+Typ) SbOP2_START = _RTL, _FIND, // Laden (+StringID+Typ) _ELEM, // Laden Element (+StringID+Typ) _PARAM, // Parameter (+Offset+Typ) // Verzweigen _CALL, // DECLARE-Methode rufen (+StringID+Typ) _CALLC, // Cdecl-DECLARE-Methode rufen (+StringID+Typ) _CASEIS, // Case-Test (+Test-Opcode+True-Target) // Verwaltung _STMNT, // Beginn eines Statements (+Line+Col) // E/A _OPEN, // (+SvStreamFlags+Flags) // Objekte _LOCAL, // Lokale Variable definieren (+StringID+Typ) _PUBLIC, // Modulglobale Variable (+StringID+Typ) _GLOBAL, // Globale Variable definieren, public-Anweisung (+StringID+Typ) _CREATE, // Objekt kreieren (+StringId+StringID) _STATIC, // Statische Variabl (+StringID+Typ) JSM _TCREATE, // User Defined Objekt kreieren _DCREATE, // Objekt-Array kreieren (+StringId+StringID) _GLOBAL_P, // Globale Variable definieren, die beim Neustart von Basic // nicht ueberschrieben wird, P=PERSIST (+StringID+Typ) _FIND_G, // Sucht globale Variable mit Spezialbehandlung wegen _GLOBAL_P _DCREATE_REDIMP, // Objekt-Array redimensionieren (+StringId+StringID) _FIND_CM, // Search inside a class module (CM) to enable global search in time _PUBLIC_P, // Module global Variable (persisted between calls)(+StringID+Typ) SbOP2_END }; #endif <commit_msg>INTEGRATION: CWS ab48 (1.12.60); FILE MERGED 2008/06/10 05:09:54 ab 1.12.60.2: RESYNC: (1.12-1.13); FILE MERGED 2008/04/04 10:13:31 ab 1.12.60.1: #i75443# Support multiple array indices<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: opcodes.hxx,v $ * $Revision: 1.14 $ * * 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 _OPCODES_HXX #define _OPCODES_HXX #include "sbintern.hxx" #ifdef MTW #undef _NUMBER #endif // Ein Opcode ist entweder 1, 3 oder 5 Bytes lang, je nach numerischen // Wert des Opcodes (s.u.). enum SbiOpcode { // Alle Opcodes ohne Operanden _NOP = 0, SbOP0_START = _NOP, // Operatoren // die folgenden Operatoren sind genauso angeordnet // wie der enum SbxVarOp _EXP, _MUL, _DIV, _MOD, _PLUS, _MINUS, _NEG, _EQ, _NE, _LT, _GT, _LE, _GE, _IDIV, _AND, _OR, _XOR, _EQV, _IMP, _NOT, _CAT, // Ende enum SbxVarOp _LIKE, _IS, // Laden/speichern _ARGC, // neuen Argv einrichten _ARGV, // TOS ==> aktueller Argv _INPUT, // Input ==> TOS _LINPUT, // Line Input ==> TOS _GET, // TOS anfassen _SET, // Speichern Objekt TOS ==> TOS-1 _PUT, // TOS ==> TOS-1 _PUTC, // TOS ==> TOS-1, dann ReadOnly _DIM, // DIM _REDIM, // REDIM _REDIMP, // REDIM PRESERVE _ERASE, // TOS loeschen // Verzweigen _STOP, // Programmende _INITFOR, // FOR-Variable initialisieren _NEXT, // FOR-Variable inkrementieren _CASE, // Anfang CASE _ENDCASE, // Ende CASE _STDERROR, // Standard-Fehlerbehandlung _NOERROR, // keine Fehlerbehandlung _LEAVE, // UP verlassen // E/A _CHANNEL, // TOS = Kanalnummer _BPRINT, // print TOS _PRINTF, // print TOS in field _BWRITE, // write TOS _RENAME, // Rename Tos+1 to Tos _PROMPT, // TOS = Prompt for Input _RESTART, // Restartpunkt definieren _CHAN0, // I/O-Kanal 0 // Sonstiges _EMPTY, // Leeren Ausdruck auf Stack _ERROR, // TOS = Fehlercode _LSET, // Speichern Objekt TOS ==> TOS-1 _RSET, // Speichern Objekt TOS ==> TOS-1 _REDIMP_ERASE, // Copies array to be later used by REDIM PRESERVE before erasing it _INITFOREACH, _VBASET, // VBA-like Set _ERASE_CLEAR, // Erase array and clear variable _ARRAYACCESS, // Assign parameters to TOS and get value, used for array of arrays SbOP0_END, // Alle Opcodes mit einem Operanden _NUMBER = 0x40, // Laden einer numerischen Konstanten (+ID) SbOP1_START = _NUMBER, _SCONST, // Laden einer Stringkonstanten (+ID) _CONST, // Immediate Load (+Wert) _ARGN, // Speichern eines named Args in Argv (+StringID) _PAD, // String auf feste Laenge bringen (+Laenge) // Verzweigungen _JUMP, // Sprung (+Target) _JUMPT, // TOS auswerten, bedingter Sprung (+Target) _JUMPF, // TOS auswerten, bedingter Sprung (+Target) _ONJUMP, // TOS auswerten, Sprung in JUMP-Tabelle (+MaxVal) _GOSUB, // UP-Aufruf (+Target) _RETURN, // UP-Return (+0 oder Target) _TESTFOR, // FOR-Variable testen, inkrementieren (+Endlabel) _CASETO, // Tos+1 <= Case <= Tos, 2xremove (+Target) _ERRHDL, // Fehler-Handler (+Offset) _RESUME, // Resume nach Fehlern (+0 or 1 or Label) // E/A _CLOSE, // (+Kanal/0) _PRCHAR, // (+char) // Verwaltung _SETCLASS, // Set + Klassennamen testen (+StringId) _TESTCLASS, // Check TOS class (+StringId) _LIB, // Libnamen fuer Declare-Procs setzen (+StringId) _BASED, // TOS wird um BASE erhoeht, BASE davor gepusht (+base) // Typanpassung im Argv _ARGTYP, // Letzten Parameter in Argv konvertieren (+Typ) _VBASETCLASS, // VBA-like Set SbOP1_END, // Alle Opcodes mit zwei Operanden _RTL = 0x80, // Laden aus RTL (+StringID+Typ) SbOP2_START = _RTL, _FIND, // Laden (+StringID+Typ) _ELEM, // Laden Element (+StringID+Typ) _PARAM, // Parameter (+Offset+Typ) // Verzweigen _CALL, // DECLARE-Methode rufen (+StringID+Typ) _CALLC, // Cdecl-DECLARE-Methode rufen (+StringID+Typ) _CASEIS, // Case-Test (+Test-Opcode+True-Target) // Verwaltung _STMNT, // Beginn eines Statements (+Line+Col) // E/A _OPEN, // (+SvStreamFlags+Flags) // Objekte _LOCAL, // Lokale Variable definieren (+StringID+Typ) _PUBLIC, // Modulglobale Variable (+StringID+Typ) _GLOBAL, // Globale Variable definieren, public-Anweisung (+StringID+Typ) _CREATE, // Objekt kreieren (+StringId+StringID) _STATIC, // Statische Variabl (+StringID+Typ) JSM _TCREATE, // User Defined Objekt kreieren _DCREATE, // Objekt-Array kreieren (+StringId+StringID) _GLOBAL_P, // Globale Variable definieren, die beim Neustart von Basic // nicht ueberschrieben wird, P=PERSIST (+StringID+Typ) _FIND_G, // Sucht globale Variable mit Spezialbehandlung wegen _GLOBAL_P _DCREATE_REDIMP, // Objekt-Array redimensionieren (+StringId+StringID) _FIND_CM, // Search inside a class module (CM) to enable global search in time _PUBLIC_P, // Module global Variable (persisted between calls)(+StringID+Typ) SbOP2_END }; #endif <|endoftext|>
<commit_before>// Copyright 2012 Cloudera 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 <stdio.h> #include <signal.h> #include <unistd.h> #include <boost/algorithm/string.hpp> #include <boost/thread/thread.hpp> #include <boost/scoped_ptr.hpp> #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int.hpp> #include <string> #include <vector> #include <transport/TSasl.h> #include <transport/TSaslServerTransport.h> #include <glog/logging.h> #include <gflags/gflags.h> #include "authorization.h" using namespace std; using namespace boost; using namespace boost::random; DECLARE_string(keytab_file); DECLARE_string(principal); DEFINE_int32(kerberos_reinit_interval, 60, \ "Interval, in minutes, between kerberos ticket renewals. Each renewal will request " "a ticket with a lifetime that is at least 2x the renewal interval."); DEFINE_string(sasl_path, "/usr/lib/sasl2:/usr/lib64/sasl2:/usr/local/lib/sasl2:" "/usr/lib/x86_64-linux-gnu/sasl2", "Colon separated list of paths to look for SASL " "security library plugins."); namespace impala { // Array of callbacks for the sasl library. static vector<sasl_callback_t> callbacks; // Pattern for hostname substitution. static const string HOSTNAME_PATTERN = "_HOST"; // The Impala service name. static string impala_service_name; // Output Sasl messages. // context: not used. // level: logging level. // message: message to output; static int SaslLogCallback(void* context, int level, const char* message) { if (message == NULL) return SASL_BADPARAM; switch (level) { case SASL_LOG_NONE: break; case SASL_LOG_ERR: case SASL_LOG_FAIL: LOG(ERROR) << "Kerberos: " << message; break; case SASL_LOG_WARN: LOG(WARNING) << "Kerberos: " << message; break; case SASL_LOG_NOTE: LOG(INFO) << "Kerberos: " << message; break; case SASL_LOG_DEBUG: VLOG(1) << "Kerberos: " << message; break; case SASL_LOG_TRACE: case SASL_LOG_PASS: VLOG(3) << "Kerberos: " << message; break; } return SASL_OK; } // Get Sasl option. // context: not used // plugin_name: name of plugin for which an option is being requested. // option: option requested // result: value for option // len: length of the result // Return SASL_FAIL if the option is not handled, this does not fail the handshake. static int SaslGetOption(void* context, const char* plugin_name, const char* option, const char** result, unsigned* len) { // Handle Sasl Library options if (plugin_name == NULL) { // Return the logging level that we want the sasl library to use. if (strcmp("log_level", option) == 0) { int level = SASL_LOG_WARN; if (VLOG_CONNECTION_IS_ON) { level = SASL_LOG_DEBUG; } else if (VLOG_ROW_IS_ON) { level = SASL_LOG_TRACE; } static char buf[4]; snprintf(buf, 4, "%d", level); *result = buf; if (len != NULL) *len = strlen(buf); return SASL_OK; } // Options can default so don't complain. VLOG(3) << "SaslGetOption: Unknown option: " << option; return SASL_FAIL; } if (strcmp(KERBEROS_MECHANISM.c_str(), plugin_name) == 0) { // Return the path to our keytab file. // TODO: why is this never called? if (strcmp("keytab", option) == 0) { *result = FLAGS_keytab_file.c_str(); if (len != NULL) *len = strlen(*result); return SASL_OK; } VLOG(3) << "SaslGetOption: Unknown option: " << option; return SASL_FAIL; } VLOG(3) << "SaslGetOption: Unknown plugin: " << plugin_name; return SASL_FAIL; } // Sasl Authorize callback. // Can be used to restrict access. Currently used for diagnostics. // requsted_user, rlen: The user requesting access and string length. // auth_identity, alen: The identity (principal) and length. // default_realm, urlen: Realm of the user and length. // propctx: properties requested. static int SaslAuthorize(sasl_conn_t* conn, void* context, const char* requested_user, unsigned rlen, const char* auth_identity, unsigned alen, const char* def_realm, unsigned urlen, struct propctx* propctx) { string user(requested_user, rlen); string auth(auth_identity, alen); string realm(def_realm, urlen); VLOG_CONNECTION << "Kerberos User: " << user << " for: " << auth << " from " << realm; return SASL_OK; } // Sasl Get Path callback. // Returns the list of possible places for the plugins might be. // Places we know they might be: // UBUNTU: /usr/lib/sasl2 // CENTOS: /usr/lib64/sasl2 // custom install: /usr/local/lib/sasl2 static int SaslGetPath(void* context, const char** path) { *path = FLAGS_sasl_path.c_str(); return SASL_OK; } // Periodically call kinit to get a ticket granting ticket from the kerberos server. // This is kept in the kerberos cache associated with this process. static void RunKinit() { // Minumum lifetime to request for each ticket renewal. static const int MIN_TICKET_LIFETIME_IN_MINS = 1440; stringstream sysstream; // Set the ticket lifetime to an arbitrarily large value or 2x the renewal interval, // whichever is larger. The KDC will automatically fall back to using the maximum // allowed allowed value if a longer lifetime is requested, so it is okay to be greedy // here. int ticket_lifetime = max(MIN_TICKET_LIFETIME_IN_MINS, FLAGS_kerberos_reinit_interval * 2); // Pass the path to the key file and the principal. Make the ticket renewable. // Calling kinit -R ensures the ticket makes it to the cache. sysstream << "kinit -r " << ticket_lifetime << "m -k -t " << FLAGS_keytab_file << " " << FLAGS_principal << " 2>&1 && kinit -R 2>&1"; bool started = false; int failures = 0; while (true) { LOG(INFO) << "Registering " << FLAGS_principal << " key_tab file " << FLAGS_keytab_file; FILE* fp = popen(sysstream.str().c_str(), "r"); if (fp == NULL) { LOG(ERROR) << "Exiting: failed to execute kinit: " << strerror(errno); exit(1); } // Read the first 1024 bytes of any output so we have some idea of what // happened on failure. char buf[1024]; size_t len = fread(buf, 1, 1024, fp); string kreturn(buf, len); int ret = pclose(fp); if (ret != 0) { if (!started) { LOG(ERROR) << "Exiting: failed to register with kerberos: errno: " << errno << " '" << kreturn << "'"; exit(1); } // Just report the problem, existing report the error. Existing connections // are ok and we can talk to HDFS until our ticket expires. ++failures; LOG(ERROR) << "Failed to extend kerberos ticket: '" << kreturn << "' errno " << errno << ". Failure count: " << failures; } else { VLOG_CONNECTION << "kinit returned: '" << kreturn << "'"; } started = true; // Sleep for the renewal interval, minus a random time between 0-5 minutes to help // avoid a storm at the KDC. Additionally, never sleep less than a minute to // reduce KDC stress due to frequent renewals. mt19937 generator; uniform_int<> dist(0, 300); sleep(max((60 * FLAGS_kerberos_reinit_interval) - dist(generator), 60)); } } Status InitKerberos(const string& appname) { callbacks.resize(5); callbacks[0].id = SASL_CB_LOG; callbacks[0].proc = (int (*)())&SaslLogCallback; callbacks[0].context = NULL; callbacks[1].id = SASL_CB_GETOPT; callbacks[1].proc = (int (*)())&SaslGetOption; callbacks[1].context = NULL; callbacks[2].id = SASL_CB_PROXY_POLICY; callbacks[2].proc = (int (*)())&SaslAuthorize; callbacks[2].context = NULL; callbacks[3].id = SASL_CB_GETPATH; callbacks[3].proc = (int (*)())&SaslGetPath; callbacks[3].context = NULL; callbacks[4].id = SASL_CB_LIST_END; // Replace the string _HOST with our hostname. size_t off = FLAGS_principal.find(HOSTNAME_PATTERN); if (off != string::npos) { string hostname = GetHostname(); if (hostname.empty()) { stringstream ss; ss << "InitKerberos call to gethostname failed: errno " << errno; LOG(ERROR) << ss; return Status(ss.str()); } FLAGS_principal.replace(off, HOSTNAME_PATTERN.size(), hostname); } off = FLAGS_principal.find("/"); if (off == string::npos) { stringstream ss; ss << "--principal must contain '/': " << FLAGS_principal; LOG(ERROR) << ss; return Status(ss.str()); } impala_service_name = FLAGS_principal.substr(0, off); try { // We assume all impala processes are both server and client. sasl::TSaslServer::SaslInit(&callbacks[0], appname); sasl::TSaslClient::SaslInit(&callbacks[0]); } catch (sasl::SaslServerImplException& e) { LOG(ERROR) << "Could not initialize Sasl library: " << e.what(); return Status(e.what()); } // Run kinit every hour or as configured till we exit. thread krun(RunKinit); return Status::OK; } Status GetKerberosTransportFactory(const string& principal, const string& key_tab_file, shared_ptr<TTransportFactory>* factory) { // The "keytab" callback is never called. Set the file name in the environment. if (setenv("KRB5_KTNAME", key_tab_file.c_str(), 1)) { stringstream ss; ss << "Kerberos could not set KRB5_KTNAME: errno " << errno; LOG(ERROR) << ss; return Status(ss.str()); } // The string should be service/hostname@realm vector<string> names; split(names, principal, is_any_of("/@")); if (names.size() != 3) { stringstream ss; ss << "Kerberos principal should of the form: <service>/<hostname>@<realm> - got: " << principal; LOG(ERROR) << ss.str(); return Status(ss.str()); } // TODO: What properties do we support? In meantime we pass an empty map. map<string, string> props; try { factory->reset(new TSaslServerTransport::Factory( KERBEROS_MECHANISM, names[0], names[1], 0, props, callbacks)); } catch (TTransportException& e) { LOG(ERROR) << "Kerberos transport factory failed: " << e.what(); return Status(e.what()); } return Status::OK; } Status GetTSaslClient(const string& hostname, shared_ptr<sasl::TSasl>* saslClient) { map<string, string> props; // We do not set this. string auth_id; try { saslClient->reset(new sasl::TSaslClient(KERBEROS_MECHANISM, auth_id, impala_service_name, hostname, props, &callbacks[0])); } catch (sasl::SaslClientImplException& e) { LOG(ERROR) << "Kerberos client create failed: " << e.what(); return Status(e.what()); } return Status::OK; } string GetHostname() { char name[HOST_NAME_MAX]; string ret_name; int ret = gethostname(name, HOST_NAME_MAX); if (ret == 0) { ret_name = string(name); } else { LOG(WARNING) << "Could not get hostname: errno: " << errno; } return ret_name; } } <commit_msg>IMP-460: Impala should retry kinit even if execute fails<commit_after>// Copyright 2012 Cloudera 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 <stdio.h> #include <signal.h> #include <unistd.h> #include <boost/algorithm/string.hpp> #include <boost/thread/thread.hpp> #include <boost/scoped_ptr.hpp> #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int.hpp> #include <string> #include <vector> #include <transport/TSasl.h> #include <transport/TSaslServerTransport.h> #include <glog/logging.h> #include <gflags/gflags.h> #include "authorization.h" using namespace std; using namespace boost; using namespace boost::random; DECLARE_string(keytab_file); DECLARE_string(principal); DEFINE_int32(kerberos_reinit_interval, 60, \ "Interval, in minutes, between kerberos ticket renewals. Each renewal will request " "a ticket with a lifetime that is at least 2x the renewal interval."); DEFINE_string(sasl_path, "/usr/lib/sasl2:/usr/lib64/sasl2:/usr/local/lib/sasl2:" "/usr/lib/x86_64-linux-gnu/sasl2", "Colon separated list of paths to look for SASL " "security library plugins."); namespace impala { // Array of callbacks for the sasl library. static vector<sasl_callback_t> callbacks; // Pattern for hostname substitution. static const string HOSTNAME_PATTERN = "_HOST"; // The Impala service name. static string impala_service_name; // Output Sasl messages. // context: not used. // level: logging level. // message: message to output; static int SaslLogCallback(void* context, int level, const char* message) { if (message == NULL) return SASL_BADPARAM; switch (level) { case SASL_LOG_NONE: break; case SASL_LOG_ERR: case SASL_LOG_FAIL: LOG(ERROR) << "Kerberos: " << message; break; case SASL_LOG_WARN: LOG(WARNING) << "Kerberos: " << message; break; case SASL_LOG_NOTE: LOG(INFO) << "Kerberos: " << message; break; case SASL_LOG_DEBUG: VLOG(1) << "Kerberos: " << message; break; case SASL_LOG_TRACE: case SASL_LOG_PASS: VLOG(3) << "Kerberos: " << message; break; } return SASL_OK; } // Get Sasl option. // context: not used // plugin_name: name of plugin for which an option is being requested. // option: option requested // result: value for option // len: length of the result // Return SASL_FAIL if the option is not handled, this does not fail the handshake. static int SaslGetOption(void* context, const char* plugin_name, const char* option, const char** result, unsigned* len) { // Handle Sasl Library options if (plugin_name == NULL) { // Return the logging level that we want the sasl library to use. if (strcmp("log_level", option) == 0) { int level = SASL_LOG_WARN; if (VLOG_CONNECTION_IS_ON) { level = SASL_LOG_DEBUG; } else if (VLOG_ROW_IS_ON) { level = SASL_LOG_TRACE; } static char buf[4]; snprintf(buf, 4, "%d", level); *result = buf; if (len != NULL) *len = strlen(buf); return SASL_OK; } // Options can default so don't complain. VLOG(3) << "SaslGetOption: Unknown option: " << option; return SASL_FAIL; } if (strcmp(KERBEROS_MECHANISM.c_str(), plugin_name) == 0) { // Return the path to our keytab file. // TODO: why is this never called? if (strcmp("keytab", option) == 0) { *result = FLAGS_keytab_file.c_str(); if (len != NULL) *len = strlen(*result); return SASL_OK; } VLOG(3) << "SaslGetOption: Unknown option: " << option; return SASL_FAIL; } VLOG(3) << "SaslGetOption: Unknown plugin: " << plugin_name; return SASL_FAIL; } // Sasl Authorize callback. // Can be used to restrict access. Currently used for diagnostics. // requsted_user, rlen: The user requesting access and string length. // auth_identity, alen: The identity (principal) and length. // default_realm, urlen: Realm of the user and length. // propctx: properties requested. static int SaslAuthorize(sasl_conn_t* conn, void* context, const char* requested_user, unsigned rlen, const char* auth_identity, unsigned alen, const char* def_realm, unsigned urlen, struct propctx* propctx) { string user(requested_user, rlen); string auth(auth_identity, alen); string realm(def_realm, urlen); VLOG_CONNECTION << "Kerberos User: " << user << " for: " << auth << " from " << realm; return SASL_OK; } // Sasl Get Path callback. // Returns the list of possible places for the plugins might be. // Places we know they might be: // UBUNTU: /usr/lib/sasl2 // CENTOS: /usr/lib64/sasl2 // custom install: /usr/local/lib/sasl2 static int SaslGetPath(void* context, const char** path) { *path = FLAGS_sasl_path.c_str(); return SASL_OK; } // Periodically call kinit to get a ticket granting ticket from the kerberos server. // This is kept in the kerberos cache associated with this process. static void RunKinit() { // Minumum lifetime to request for each ticket renewal. static const int MIN_TICKET_LIFETIME_IN_MINS = 1440; stringstream sysstream; // Set the ticket lifetime to an arbitrarily large value or 2x the renewal interval, // whichever is larger. The KDC will automatically fall back to using the maximum // allowed allowed value if a longer lifetime is requested, so it is okay to be greedy // here. int ticket_lifetime = max(MIN_TICKET_LIFETIME_IN_MINS, FLAGS_kerberos_reinit_interval * 2); // Pass the path to the key file and the principal. Make the ticket renewable. // Calling kinit -R ensures the ticket makes it to the cache. sysstream << "kinit -r " << ticket_lifetime << "m -k -t " << FLAGS_keytab_file << " " << FLAGS_principal << " 2>&1 && kinit -R 2>&1"; bool started = false; int failures = 0; string kreturn; int ret; while (true) { LOG(INFO) << "Registering " << FLAGS_principal << " key_tab file " << FLAGS_keytab_file; FILE* fp = popen(sysstream.str().c_str(), "r"); if (fp == NULL) { kreturn = "Failed to execute kinit"; ret = -1; } else { // Read the first 1024 bytes of any output so we have some idea of what // happened on failure. char buf[1024]; size_t len = fread(buf, 1, 1024, fp); kreturn.assign(buf, len); ret = pclose(fp); } if (ret != 0) { if (!started) { LOG(ERROR) << "Exiting: failed to register with kerberos: errno: " << errno << " '" << kreturn << "'"; exit(1); } // Just report the problem, existing report the error. Existing connections // are ok and we can talk to HDFS until our ticket expires. ++failures; LOG(ERROR) << "Failed to extend kerberos ticket: '" << kreturn << "' errno " << strerror(errno) << ". Failure count: " << failures; } else { VLOG_CONNECTION << "kinit returned: '" << kreturn << "'"; } started = true; // Sleep for the renewal interval, minus a random time between 0-5 minutes to help // avoid a storm at the KDC. Additionally, never sleep less than a minute to // reduce KDC stress due to frequent renewals. mt19937 generator; uniform_int<> dist(0, 300); sleep(max((60 * FLAGS_kerberos_reinit_interval) - dist(generator), 60)); } } Status InitKerberos(const string& appname) { callbacks.resize(5); callbacks[0].id = SASL_CB_LOG; callbacks[0].proc = (int (*)())&SaslLogCallback; callbacks[0].context = NULL; callbacks[1].id = SASL_CB_GETOPT; callbacks[1].proc = (int (*)())&SaslGetOption; callbacks[1].context = NULL; callbacks[2].id = SASL_CB_PROXY_POLICY; callbacks[2].proc = (int (*)())&SaslAuthorize; callbacks[2].context = NULL; callbacks[3].id = SASL_CB_GETPATH; callbacks[3].proc = (int (*)())&SaslGetPath; callbacks[3].context = NULL; callbacks[4].id = SASL_CB_LIST_END; // Replace the string _HOST with our hostname. size_t off = FLAGS_principal.find(HOSTNAME_PATTERN); if (off != string::npos) { string hostname = GetHostname(); if (hostname.empty()) { stringstream ss; ss << "InitKerberos call to gethostname failed: errno " << errno; LOG(ERROR) << ss; return Status(ss.str()); } FLAGS_principal.replace(off, HOSTNAME_PATTERN.size(), hostname); } off = FLAGS_principal.find("/"); if (off == string::npos) { stringstream ss; ss << "--principal must contain '/': " << FLAGS_principal; LOG(ERROR) << ss; return Status(ss.str()); } impala_service_name = FLAGS_principal.substr(0, off); try { // We assume all impala processes are both server and client. sasl::TSaslServer::SaslInit(&callbacks[0], appname); sasl::TSaslClient::SaslInit(&callbacks[0]); } catch (sasl::SaslServerImplException& e) { LOG(ERROR) << "Could not initialize Sasl library: " << e.what(); return Status(e.what()); } // Run kinit every hour or as configured till we exit. thread krun(RunKinit); return Status::OK; } Status GetKerberosTransportFactory(const string& principal, const string& key_tab_file, shared_ptr<TTransportFactory>* factory) { // The "keytab" callback is never called. Set the file name in the environment. if (setenv("KRB5_KTNAME", key_tab_file.c_str(), 1)) { stringstream ss; ss << "Kerberos could not set KRB5_KTNAME: errno " << errno; LOG(ERROR) << ss; return Status(ss.str()); } // The string should be service/hostname@realm vector<string> names; split(names, principal, is_any_of("/@")); if (names.size() != 3) { stringstream ss; ss << "Kerberos principal should of the form: <service>/<hostname>@<realm> - got: " << principal; LOG(ERROR) << ss.str(); return Status(ss.str()); } // TODO: What properties do we support? In meantime we pass an empty map. map<string, string> props; try { factory->reset(new TSaslServerTransport::Factory( KERBEROS_MECHANISM, names[0], names[1], 0, props, callbacks)); } catch (TTransportException& e) { LOG(ERROR) << "Kerberos transport factory failed: " << e.what(); return Status(e.what()); } return Status::OK; } Status GetTSaslClient(const string& hostname, shared_ptr<sasl::TSasl>* saslClient) { map<string, string> props; // We do not set this. string auth_id; try { saslClient->reset(new sasl::TSaslClient(KERBEROS_MECHANISM, auth_id, impala_service_name, hostname, props, &callbacks[0])); } catch (sasl::SaslClientImplException& e) { LOG(ERROR) << "Kerberos client create failed: " << e.what(); return Status(e.what()); } return Status::OK; } string GetHostname() { char name[HOST_NAME_MAX]; string ret_name; int ret = gethostname(name, HOST_NAME_MAX); if (ret == 0) { ret_name = string(name); } else { LOG(WARNING) << "Could not get hostname: errno: " << errno; } return ret_name; } } <|endoftext|>
<commit_before> // For usleep #define _BSD_SOURCE #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #define _Bool bool #undef __cplusplus extern "C" { #include <adlb.h> } #define __cplusplus #include <unistd.h> #include <map> #include <utility> using namespace std; // Work unit type #define WORKT 0 #define CONTROL 1 typedef struct { adlb_datum_id fn; adlb_datum_id fn1; adlb_datum_id fn2; bool got1, got2; } fib_blocked; void mystore(adlb_datum_id id, long val) { int *ranks; int count; //printf("<%ld> = %ld\n", id, val); ADLB_Store(id, &val, sizeof(long), true, &ranks, &count); if (count > 0) { char buf[128]; int len = sprintf(buf, "close %ld", id); for (int r = 0; r < count; r++) { int rank = ranks[r]; //printf("Notify %i about %ld\n", rank, id); ADLB_Put(buf, len+1, rank, -1, CONTROL, 1, 1); } } } adlb_datum_id spawnfib(int N) { char buf[1024]; adlb_datum_id id; ADLB_Create_integer(ADLB_DATA_ID_NULL, DEFAULT_CREATE_PROPS, &id); int len = sprintf(buf, "fib %i %li\n", N, id); ADLB_Put(buf, len+1, ADLB_RANK_ANY, -1, CONTROL, 1, 1); return id; } void spawnfib2(adlb_datum_id *f1, adlb_datum_id *f2, int N1, int N2) { char buf[1024]; adlb_datum_id ids[2]; ADLB_create_spec specs[2]; for (int i = 0; i < 2; i++) { specs[i].id = ADLB_DATA_ID_NULL; specs[i].type = ADLB_DATA_TYPE_INTEGER; specs[i].props = DEFAULT_CREATE_PROPS; } ADLB_Multicreate(specs, 2); int len = sprintf(buf, "fib %i %li\n", N1, specs[0].id); ADLB_Put(buf, len+1, ADLB_RANK_ANY, -1, CONTROL, 1, 1); len = sprintf(buf, "fib %i %li\n", N2, specs[1].id); ADLB_Put(buf, len+1, ADLB_RANK_ANY, -1, CONTROL, 1, 1); *f1 = specs[0].id; *f2 = specs[1].id; } // True if already present bool subscribe(adlb_datum_id id) { int subscribed; adlb_code code = ADLB_Subscribe(id, &subscribed); assert(code == ADLB_SUCCESS); return subscribed == 0; } long getnum(adlb_datum_id id) { long result_val; adlb_data_type t; int l; adlb_code code = ADLB_Retrieve(id, &t, 1, &result_val, &l); assert(code == ADLB_SUCCESS); //printf("Got <%ld> = %ld\n", id, result_val); return result_val; } int main(int argc, char *argv[]) { FILE *fp; int rc, i, done; char c, cmdbuffer[1024]; int am_server, am_debug_server; int num_servers, use_debug_server, aprintf_flag; MPI_Comm app_comm; int my_world_rank, my_app_rank; int num_types = 2; int type_vect[2] = {WORKT, CONTROL}; int quiet = 1; double start_time, end_time; //printf("HELLO!\n"); fflush(NULL); rc = MPI_Init( &argc, &argv ); assert(rc == MPI_SUCCESS); MPI_Comm_rank( MPI_COMM_WORLD, &my_world_rank ); aprintf_flag = 0; /* no output from adlb itself */ num_servers = 1; /* one server should be enough */ if (getenv("ADLB_SERVERS") != NULL) { num_servers = atoi(getenv("ADLB_SERVERS")); } use_debug_server = 0; /* default: no debug server */ rc = ADLB_Init(num_servers, num_types, type_vect, &am_server, MPI_COMM_WORLD, &app_comm); if ( !am_server ) /* application process */ { printf("[%i] I AM SERVER!\n", my_world_rank); MPI_Comm_rank( app_comm, &my_app_rank ); } rc = MPI_Barrier( MPI_COMM_WORLD ); start_time = MPI_Wtime(); if ( am_server ) { ADLB_Server(3000000); } else { map<long, fib_blocked*> waitmap; adlb_datum_id result = ADLB_DATA_ID_NULL; if (argc != 2 && argc != 3) { printf("usage: %s <n> <sleep>", argv[0]); ADLB_Fail(-1); } int N = atoi(argv[1]); double sleep = 0.0; if (argc == 3) { sleep=atof(argv[2]); printf("Sleep for %lf\n", sleep); } if ( my_app_rank == 0 ) { result = spawnfib(N); if (subscribe(result)) { printf("Finished strangely early...\n"); exit(1); } } done = 0; int ndone = 0; while (!done) { //printf("Getting a command\n"); MPI_Comm task_comm; char cmdbuffer[1024]; int work_len, answer_rank, work_type; rc = ADLB_Get(CONTROL, cmdbuffer, &work_len, &answer_rank, &work_type, &task_comm); if ( rc == ADLB_SHUTDOWN ) { printf("trace: All jobs done\n"); break; } if (strncmp(cmdbuffer, "fib ", 4) == 0) { int i; adlb_datum_id id; sscanf(cmdbuffer, "fib %i %li", &i, &id); if (i == 0) { mystore(id, 0); } else if (i == 1) { mystore(id, 1); long f = i; } else { adlb_datum_id f1, f2; spawnfib2(&f1, &f2, i - 1, i - 2); fib_blocked *entry = (fib_blocked*)malloc(sizeof(fib_blocked)); entry->fn = id; entry->fn1 = f1; entry->fn2 = f2; entry->got1 = subscribe(f1); entry->got2 = subscribe(f2); if (entry->got1 && entry->got2) { long val1 = getnum(entry->fn1); long val2 = getnum(entry->fn2); if (sleep > 0.0) { usleep((long)(sleep * 1000000)); } mystore(entry->fn, val1 + val2); //printf("Subscribed right away: %ld + %ld = %ld\n", val1, val2, val1 + val2); free(entry); } else { waitmap[f1] = entry; waitmap[f2] = entry; } } } else if (strncmp(cmdbuffer, "close ", 5) == 0) { adlb_datum_id id; sscanf(cmdbuffer, "close %li", &id); if (id == result) { printf("Fib(%i) = %ld\n", N, getnum(id)); } else { fib_blocked *entry = waitmap[id]; if (entry == NULL) { printf("Rank %i Unknown entry %ld\n", my_app_rank, id); exit(1); } if (entry->fn1 == id) { entry->got1 = true; } if (entry->fn2 == id) { entry->got2 = true; } if (entry->got1 && entry->got2) { long val1 = getnum(entry->fn1); long val2 = getnum(entry->fn2); if (sleep > 0.0) { usleep((long)(sleep * 1000000)); } mystore(entry->fn, val1 + val2); //printf("Later: %ld + %ld = %ld\n", val1, val2, val1 + val2); waitmap.erase(id); free(entry); } } } else { printf("Unknown buffer %s\n", cmdbuffer); exit(1); } ndone++; if (ndone % 50000 == 0) { printf("trace: rank %i finished %i\n", my_app_rank, ndone); } } if (my_app_rank == 0) { end_time = MPI_Wtime(); printf("TOOK: %.3f\n", end_time-start_time); } } ADLB_Finalize(); MPI_Finalize(); return(0); } <commit_msg>Get ADLB fib benchmark running again<commit_after> // For usleep #define _BSD_SOURCE #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #define _Bool bool #undef __cplusplus extern "C" { #include <adlb.h> } #define __cplusplus #include <unistd.h> #include <map> #include <utility> using namespace std; // Work unit type #define WORKT 0 #define CONTROL 1 typedef struct { adlb_datum_id fn; adlb_datum_id fn1; adlb_datum_id fn2; bool got1, got2; } fib_blocked; void mystore(adlb_datum_id id, long val) { int *ranks; int count; //printf("<%ld> = %ld\n", id, val); ADLB_Store(id, ADLB_NO_SUB, ADLB_DATA_TYPE_INTEGER, &val, sizeof(long), ADLB_WRITE_RC); if (count > 0) { char buf[128]; int len = sprintf(buf, "close %ld", id); for (int r = 0; r < count; r++) { int rank = ranks[r]; //printf("Notify %i about %ld\n", rank, id); ADLB_Put(buf, len+1, rank, -1, CONTROL, 1, 1); } } } adlb_datum_id spawnfib(int N) { char buf[1024]; adlb_datum_id id; ADLB_Create_integer(ADLB_DATA_ID_NULL, DEFAULT_CREATE_PROPS, &id); int len = sprintf(buf, "fib %i %li\n", N, id); ADLB_Put(buf, len+1, ADLB_RANK_ANY, -1, CONTROL, 1, 1); return id; } void spawnfib2(adlb_datum_id *f1, adlb_datum_id *f2, int N1, int N2) { char buf[1024]; adlb_datum_id ids[2]; ADLB_create_spec specs[2]; for (int i = 0; i < 2; i++) { specs[i].id = ADLB_DATA_ID_NULL; specs[i].type = ADLB_DATA_TYPE_INTEGER; specs[i].props = DEFAULT_CREATE_PROPS; } ADLB_Multicreate(specs, 2); int len = sprintf(buf, "fib %i %li\n", N1, specs[0].id); ADLB_Put(buf, len+1, ADLB_RANK_ANY, -1, CONTROL, 1, 1); len = sprintf(buf, "fib %i %li\n", N2, specs[1].id); ADLB_Put(buf, len+1, ADLB_RANK_ANY, -1, CONTROL, 1, 1); *f1 = specs[0].id; *f2 = specs[1].id; } // True if already present bool subscribe(adlb_datum_id id) { int subscribed; adlb_code code = ADLB_Subscribe(id, ADLB_NO_SUB, &subscribed); assert(code == ADLB_SUCCESS); return subscribed == 0; } long getnum(adlb_datum_id id) { long result_val; adlb_data_type t; int l; adlb_code code = ADLB_Retrieve(id, ADLB_NO_SUB, ADLB_RETRIEVE_READ_RC, &t, &result_val, &l); assert(code == ADLB_SUCCESS); //printf("Got <%ld> = %ld\n", id, result_val); return result_val; } int main(int argc, char *argv[]) { FILE *fp; int rc, i, done; char c, cmdbuffer[1024]; int am_server, am_debug_server; int num_servers, use_debug_server, aprintf_flag; MPI_Comm app_comm; int my_world_rank, my_app_rank; int num_types = 2; int type_vect[2] = {WORKT, CONTROL}; int quiet = 1; double start_time, end_time; //printf("HELLO!\n"); fflush(NULL); rc = MPI_Init( &argc, &argv ); assert(rc == MPI_SUCCESS); MPI_Comm_rank( MPI_COMM_WORLD, &my_world_rank ); aprintf_flag = 0; /* no output from adlb itself */ num_servers = 1; /* one server should be enough */ if (getenv("ADLB_SERVERS") != NULL) { num_servers = atoi(getenv("ADLB_SERVERS")); } use_debug_server = 0; /* default: no debug server */ rc = ADLB_Init(num_servers, num_types, type_vect, &am_server, MPI_COMM_WORLD, &app_comm); if ( !am_server ) /* application process */ { printf("[%i] I AM SERVER!\n", my_world_rank); MPI_Comm_rank( app_comm, &my_app_rank ); } rc = MPI_Barrier( MPI_COMM_WORLD ); start_time = MPI_Wtime(); if ( am_server ) { ADLB_Server(3000000); } else { map<long, fib_blocked*> waitmap; adlb_datum_id result = ADLB_DATA_ID_NULL; if (argc != 2 && argc != 3) { printf("usage: %s <n> <sleep>", argv[0]); ADLB_Fail(-1); } int N = atoi(argv[1]); double sleep = 0.0; if (argc == 3) { sleep=atof(argv[2]); printf("Sleep for %lf\n", sleep); } if ( my_app_rank == 0 ) { result = spawnfib(N); if (subscribe(result)) { printf("Finished strangely early...\n"); exit(1); } } done = 0; int ndone = 0; while (!done) { //printf("Getting a command\n"); MPI_Comm task_comm; char cmdbuffer[1024]; int work_len, answer_rank, work_type; rc = ADLB_Get(CONTROL, cmdbuffer, &work_len, &answer_rank, &work_type, &task_comm); if ( rc == ADLB_SHUTDOWN ) { printf("trace: All jobs done\n"); break; } if (strncmp(cmdbuffer, "fib ", 4) == 0) { int i; adlb_datum_id id; sscanf(cmdbuffer, "fib %i %li", &i, &id); if (i == 0) { mystore(id, 0); } else if (i == 1) { mystore(id, 1); long f = i; } else { adlb_datum_id f1, f2; spawnfib2(&f1, &f2, i - 1, i - 2); fib_blocked *entry = (fib_blocked*)malloc(sizeof(fib_blocked)); entry->fn = id; entry->fn1 = f1; entry->fn2 = f2; entry->got1 = subscribe(f1); entry->got2 = subscribe(f2); if (entry->got1 && entry->got2) { long val1 = getnum(entry->fn1); long val2 = getnum(entry->fn2); if (sleep > 0.0) { usleep((long)(sleep * 1000000)); } mystore(entry->fn, val1 + val2); //printf("Subscribed right away: %ld + %ld = %ld\n", val1, val2, val1 + val2); free(entry); } else { waitmap[f1] = entry; waitmap[f2] = entry; } } } else if (strncmp(cmdbuffer, "close ", 5) == 0) { adlb_datum_id id; sscanf(cmdbuffer, "close %li", &id); if (id == result) { printf("Fib(%i) = %ld\n", N, getnum(id)); } else { fib_blocked *entry = waitmap[id]; if (entry == NULL) { printf("Rank %i Unknown entry %ld\n", my_app_rank, id); exit(1); } if (entry->fn1 == id) { entry->got1 = true; } if (entry->fn2 == id) { entry->got2 = true; } if (entry->got1 && entry->got2) { long val1 = getnum(entry->fn1); long val2 = getnum(entry->fn2); if (sleep > 0.0) { usleep((long)(sleep * 1000000)); } mystore(entry->fn, val1 + val2); //printf("Later: %ld + %ld = %ld\n", val1, val2, val1 + val2); waitmap.erase(id); free(entry); } } } else { printf("Unknown buffer %s\n", cmdbuffer); exit(1); } ndone++; if (ndone % 50000 == 0) { printf("trace: rank %i finished %i\n", my_app_rank, ndone); } } if (my_app_rank == 0) { end_time = MPI_Wtime(); printf("TOOK: %.3f\n", end_time-start_time); } } ADLB_Finalize(); MPI_Finalize(); return(0); } <|endoftext|>
<commit_before>/* Copyright (c) FFLAS-FFPACK * ========LICENCE======== * This file is part of the library FFLAS-FFPACK. * * FFLAS-FFPACK 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 * ========LICENCE======== */ //#include "goto-def.h" #include "fflas-ffpack/fflas-ffpack-config.h" #include <iostream> #include <givaro/modular-balanced.h> #include "fflas-ffpack/config-blas.h" #include "fflas-ffpack/fflas/fflas.h" #include "fflas-ffpack/utils/timer.h" #include "fflas-ffpack/utils/args-parser.h" #include "fflas-ffpack/utils/fflas_io.h" #include "fflas-ffpack/utils/timer.h" #include "givaro/modular-integer.h" #include "givaro/givcaster.h" using namespace FFPACK; using namespace std; using namespace FFLAS; int main(int argc, char** argv) { int p=0; size_t iters = 100; Givaro::Integer q = 131071; size_t m = 8000; size_t k = 8000; //static size_t n = 512 ; size_t seed= time(NULL); int t=MAX_THREADS; int NBK = -1; Argument as[] = { { 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INTEGER , &q }, { 'p', "-p P", "0 for sequential, 1 for <Recursive,Thread>, 2 for <Row,Thread>, 3 for <Row, Grain>.", TYPE_INT , &p }, { 'm', "-m M", "Set the dimension m of the matrix.", TYPE_INT , &m }, { 'k', "-k K", "Set the dimension k of the matrix.", TYPE_INT , &k }, { 't', "-t T", "number of virtual threads to drive the partition.", TYPE_INT , &t }, { 'b', "-b B", "number of numa blocks per dimension for the numa placement", TYPE_INT , &NBK }, { 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iters }, { 's', "-s S", "Sets seed.", TYPE_INT , &seed }, END_OF_ARGUMENTS }; parseArguments(argc,argv,as); if (NBK==-1) NBK = t; // typedef Givaro::Modular<double> Field; // typedef Givaro::Modular<Givaro::Integer> Field; // typedef Givaro::ModularBalanced<int32_t> Field; // typedef Givaro::ModularBalanced<float> Field; typedef Givaro::ModularBalanced<double> Field; // typedef Field::Element Element; Field F(q); Timer chrono, TimFreivalds; double time=0.0; size_t lda,incX,incY; lda=k; incX=1; incY=1; Field::Element_ptr A,X,Y; //, Y2; Field::RandIter G(F); A = FFLAS::fflas_new(F,m,lda); X = FFLAS::fflas_new(F,k,incX); Y = FFLAS::fflas_new(F,m,incY); //Y2= FFLAS::fflas_new(F,m,incY); Field::RandIter Rand(F,seed); // TODO: replace by a 1D pfrand PAR_BLOCK { SYNCH_GROUP( FORBLOCK1D(iter, m, SPLITTER(NBK, CuttingStrategy::Row, StrategyParameter::Threads), TASK(MODE(CONSTREFERENCE(F,Rand)), { frand(F, Rand, iter.end()-iter.begin(), k, A+iter.begin()*lda, lda); } ); ); ); // FFLAS::pfrand(F,Rand, m,k,A,m/NBK); } FFLAS::frand(F,Rand, k,1,X,incX); FFLAS::fzero(F, m,1,Y,incY); //FFLAS::fzero(F, m,1,Y2,incY); for (size_t i=0;i<=iters;++i){ chrono.clear(); if (p){ typedef CuttingStrategy::Row row; typedef CuttingStrategy::Recursive rec; typedef StrategyParameter::Threads threads; typedef StrategyParameter::Grain grain; PAR_BLOCK{ if (i) { chrono.start(); } switch (p){ case 1:{ ParSeqHelper::Parallel<rec, threads> H(t); FFLAS::pfgemv(F, FFLAS::FflasNoTrans, m, lda, F.one, A, lda, X, incX, F.zero, Y, incY, H); break;} case 2:{ ParSeqHelper::Parallel<row, threads> H(t); FFLAS::pfgemv(F, FFLAS::FflasNoTrans, m, lda, F.one, A, lda, X, incX, F.zero, Y, incY, H); break; } case 3:{ size_t BS = 64; ParSeqHelper::Parallel<row, grain> H(BS); FFLAS::pfgemv(F, FFLAS::FflasNoTrans, m, lda, F.one, A, lda, X, incX, F.zero, Y, incY, H); break; } default:{ FFLAS::fgemv(F, FFLAS::FflasNoTrans, m, lda, F.one, A, lda, X, incX, F.zero, Y, incY); break; } } }//PAR_BLOCK if (i) {chrono.stop(); time+=chrono.realtime();} }else{ if (i) chrono.start(); FFLAS::fgemv(F, FFLAS::FflasNoTrans, m, lda, F.one, A, lda, X, incX, F.zero, Y, incY); if (i) {chrono.stop(); time+=chrono.realtime();} } } FFLAS::fflas_delete(A); FFLAS::fflas_delete(X); FFLAS::fflas_delete(Y); std::cout << "Time: " << time / double(iters) << " Gflops: " << (2.*double(m)/1000.*double(k)/1000.0/1000.0) / time * double(iters); writeCommandString(std::cout, as) << std::endl; return 0; } /* -*- mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ // vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s <commit_msg>add bitsize argument for ZZ<commit_after>/* Copyright (c) FFLAS-FFPACK * ========LICENCE======== * This file is part of the library FFLAS-FFPACK. * * FFLAS-FFPACK 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 * ========LICENCE======== */ //#include "goto-def.h" #include "fflas-ffpack/fflas-ffpack-config.h" #include <iostream> #include <givaro/modular-balanced.h> #include "fflas-ffpack/config-blas.h" #include "fflas-ffpack/fflas/fflas.h" #include "fflas-ffpack/utils/timer.h" #include "fflas-ffpack/utils/args-parser.h" #include "fflas-ffpack/utils/fflas_io.h" #include "fflas-ffpack/utils/timer.h" #include "givaro/modular-integer.h" #include "givaro/givcaster.h" using namespace FFPACK; using namespace std; using namespace FFLAS; int main(int argc, char** argv) { int p=0; size_t iters = 100; Givaro::Integer q = 131071; size_t m = 8000; size_t k = 8000; //static size_t n = 512 ; size_t seed= time(NULL); int t=NUM_THREADS; int NBK = -1; int b=0; Argument as[] = { { 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INTEGER , &q }, { 'b', "-b B", "Set the bitsize of input.", TYPE_INT , &b }, { 'p', "-p P", "0 for sequential, 1 for <Recursive,Thread>, 2 for <Row,Thread>, 3 for <Row, Grain>.", TYPE_INT , &p }, { 'm', "-m M", "Set the dimension m of the matrix.", TYPE_INT , &m }, { 'k', "-k K", "Set the dimension k of the matrix.", TYPE_INT , &k }, { 't', "-t T", "number of virtual threads to drive the partition.", TYPE_INT , &t }, { 'N', "-n N", "number of numa blocks per dimension for the numa placement", TYPE_INT , &NBK }, { 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iters }, { 's', "-s S", "Sets seed.", TYPE_INT , &seed }, END_OF_ARGUMENTS }; parseArguments(argc,argv,as); if (NBK==-1) NBK = t; // typedef Givaro::Modular<double> Field; // typedef Givaro::Modular<Givaro::Integer> Field; // typedef Givaro::ModularBalanced<int32_t> Field; // typedef Givaro::ModularBalanced<float> Field; // typedef Givaro::ModularBalanced<double> Field; typedef Givaro::ZRing<Givaro::Integer> Field; // typedef Field::Element Element; // Field F(q); Field F; Timer chrono, TimFreivalds; double time=0.0; size_t lda,incX,incY; lda=k; incX=1; incY=1; Field::Element_ptr A,X,Y; //, Y2; Field::RandIter G(F); A = FFLAS::fflas_new(F,m,lda); X = FFLAS::fflas_new(F,k,incX); Y = FFLAS::fflas_new(F,m,incY); //Y2= FFLAS::fflas_new(F,m,incY); Field::RandIter Rand(F,b,seed); // TODO: replace by a 1D pfrand PAR_BLOCK { SYNCH_GROUP( FORBLOCK1D(iter, m, SPLITTER(NBK, CuttingStrategy::Row, StrategyParameter::Threads), TASK(MODE(CONSTREFERENCE(F,Rand)), { frand(F, Rand, iter.end()-iter.begin(), k, A+iter.begin()*lda, lda); } ); ); ); // FFLAS::pfrand(F,Rand, m,k,A,m/NBK); } FFLAS::frand(F,Rand, k,1,X,incX); FFLAS::fzero(F, m,1,Y,incY); //FFLAS::fzero(F, m,1,Y2,incY); for (size_t i=0;i<=iters;++i){ chrono.clear(); if (p){ typedef CuttingStrategy::Row row; typedef CuttingStrategy::Recursive rec; typedef StrategyParameter::Threads threads; typedef StrategyParameter::Grain grain; PAR_BLOCK{ if (i) { chrono.start(); } switch (p){ case 1:{ ParSeqHelper::Parallel<rec, threads> H(t); FFLAS::pfgemv(F, FFLAS::FflasNoTrans, m, lda, F.one, A, lda, X, incX, F.zero, Y, incY, H); break;} case 2:{ ParSeqHelper::Parallel<row, threads> H(t); FFLAS::pfgemv(F, FFLAS::FflasNoTrans, m, lda, F.one, A, lda, X, incX, F.zero, Y, incY, H); break; } case 3:{ size_t BS = 64; ParSeqHelper::Parallel<row, grain> H(BS); FFLAS::pfgemv(F, FFLAS::FflasNoTrans, m, lda, F.one, A, lda, X, incX, F.zero, Y, incY, H); break; } default:{ FFLAS::fgemv(F, FFLAS::FflasNoTrans, m, lda, F.one, A, lda, X, incX, F.zero, Y, incY); break; } } }//PAR_BLOCK if (i) {chrono.stop(); time+=chrono.realtime();} }else{ if (i) chrono.start(); FFLAS::fgemv(F, FFLAS::FflasNoTrans, m, lda, F.one, A, lda, X, incX, F.zero, Y, incY); if (i) {chrono.stop(); time+=chrono.realtime();} } } FFLAS::fflas_delete(A); FFLAS::fflas_delete(X); FFLAS::fflas_delete(Y); std::cout << "Time: " << time / double(iters) << " Gflops: " << (2.*double(m)/1000.*double(k)/1000.0/1000.0) / time * double(iters); writeCommandString(std::cout, as) << std::endl; return 0; } /* -*- mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ // vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s <|endoftext|>
<commit_before> // .\Release\benchmarks.exe --benchmark_repetitions=5 --benchmark_filter=Solar // Benchmarking on 1 X 3310 MHz CPU // 2014/10/05-19:16:12 // Benchmark Time(ns) CPU(ns) Iterations // ------------------------------------------------------------------------- // BM_SolarSystemMajorBodiesOnly 24203858590 23649751600 1 1.0002759262592109e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMajorBodiesOnly 24101375556 24024154000 1 1.0002759262592109e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMajorBodiesOnly 24065379835 23696551900 1 1.0002759262592109e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMajorBodiesOnly 24012373186 23712152000 1 1.0002759262592109e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMajorBodiesOnly 24073379016 23712152000 1 1.0002759262592109e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMajorBodiesOnly_mean 24091273237 23758952300 1 1.0002759262592109e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMajorBodiesOnly_stddev 63235130 134559341 0 1.0002759262592109e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMinorAndMajorBodies 50587372995 49951520200 1 1.0002759263053576e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMinorAndMajorBodies 51049073196 50403923100 1 1.0002759263053576e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMinorAndMajorBodies 50057970024 49343116300 1 1.0002759263053576e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMinorAndMajorBodies 50023569084 49046714400 1 1.0002759263053576e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMinorAndMajorBodies 51184083438 50653524700 1 1.0002759263053576e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMinorAndMajorBodies_mean 50580413747 49879759740 1 1.0002759263053576e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMinorAndMajorBodies_stddev 483141931 610009791 0 1.0002759263053576e+00 ua // NOLINT(whitespace/line_length) #include <memory> #include <vector> #include "benchmarks/n_body_system.hpp" #include "quantities/quantities.hpp" #include "quantities/si.hpp" // Must come last to avoid conflicts when defining the CHECK macros. #include "benchmark/benchmark.h" using principia::testing_utilities::ICRFJ2000Ecliptic; using principia::physics::NBodySystem; using principia::quantities::DebugString; using principia::si::AstronomicalUnit; namespace principia { namespace benchmarks { namespace { void SolarSystemBenchmark(SolarSystem::Accuracy const accuracy, benchmark::State* state) { std::vector<quantities::Momentum> output; while (state->KeepRunning()) { state->PauseTiming(); std::unique_ptr<SolarSystem> solar_system = SolarSystem::AtСпутник1Launch( accuracy); state->ResumeTiming(); SimulateSolarSystem(solar_system.get()); state->PauseTiming(); state->SetLabel( DebugString( (solar_system->trajectories()[ SolarSystem::kSun]->last_position() - solar_system->trajectories()[ SolarSystem::kEarth]->last_position()).Norm() / AstronomicalUnit) + " ua"); state->ResumeTiming(); } } } // namespace void BM_SolarSystemMajorBodiesOnly( benchmark::State& state) { // NOLINT(runtime/references) SolarSystemBenchmark(SolarSystem::Accuracy::kMajorBodiesOnly, &state); } void BM_SolarSystemMinorAndMajorBodies( benchmark::State& state) { // NOLINT(runtime/references) SolarSystemBenchmark(SolarSystem::Accuracy::kMinorAndMajorBodies, &state); } void BM_SolarSystemAllBodiesAndOblateness( benchmark::State& state) { // NOLINT(runtime/references) SolarSystemBenchmark(SolarSystem::Accuracy::kAllBodiesAndOblateness, &state); } BENCHMARK(BM_SolarSystemMajorBodiesOnly); BENCHMARK(BM_SolarSystemMinorAndMajorBodies); BENCHMARK(BM_SolarSystemAllBodiesAndOblateness); } // namespace benchmarks } // namespace principia <commit_msg>Benchmark numbers.<commit_after> // .\Release\benchmarks.exe --benchmark_repetitions=5 --benchmark_filter=Solar // Benchmarking on 1 X 3310 MHz CPU // 2014/10/08-21:52:53 // Benchmark Time(ns) CPU(ns) Iterations // ---------------------------------------------------------------------------- // BM_SolarSystemMajorBodiesOnly 22719357706 22604544900 1 1.0002759262678920e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMajorBodiesOnly 22830249525 22776146000 1 1.0002759262678920e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMajorBodiesOnly 22695240236 22620145000 1 1.0002759262678920e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMajorBodiesOnly 22681241251 22620145000 1 1.0002759262678920e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMajorBodiesOnly 22631234623 22526544400 1 1.0002759262678920e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMajorBodiesOnly_mean 22711464668 22629505060 1 1.0002759262678920e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMajorBodiesOnly_stddev 66008620 81120520 0 1.0002759262678920e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMinorAndMajorBodies 47008883453 46878300500 1 1.0002759263137868e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMinorAndMajorBodies 52003164268 51839132300 1 1.0002759263137868e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMinorAndMajorBodies 51617127157 51449129800 1 1.0002759263137868e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMinorAndMajorBodies 47164680220 47034301500 1 1.0002759263137868e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMinorAndMajorBodies 46987666822 46956301000 1 1.0002759263137868e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMinorAndMajorBodies_mean 48956304384 48831433020 1 1.0002759263137868e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemMinorAndMajorBodies_stddev 2334147907 2300396480 0 1.0002759263137868e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemAllBodiesAndOblateness 59040446020 58968378000 1 1.0002759263000629e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemAllBodiesAndOblateness 58897055841 58859177300 1 1.0002759263000629e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemAllBodiesAndOblateness 58945859648 58905977600 1 1.0002759263000629e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemAllBodiesAndOblateness 58946855522 58921577700 1 1.0002759263000629e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemAllBodiesAndOblateness 63729339338 63710808400 1 1.0002759263000629e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemAllBodiesAndOblateness_mean 59911911274 59873183800 1 1.0002759263000629e+00 ua // NOLINT(whitespace/line_length) // BM_SolarSystemAllBodiesAndOblateness_stddev 1909278849 1919129349 0 1.0002759263000629e+00 ua // NOLINT(whitespace/line_length) #include <memory> #include <vector> #include "benchmarks/n_body_system.hpp" #include "quantities/quantities.hpp" #include "quantities/si.hpp" // Must come last to avoid conflicts when defining the CHECK macros. #include "benchmark/benchmark.h" using principia::testing_utilities::ICRFJ2000Ecliptic; using principia::physics::NBodySystem; using principia::quantities::DebugString; using principia::si::AstronomicalUnit; namespace principia { namespace benchmarks { namespace { void SolarSystemBenchmark(SolarSystem::Accuracy const accuracy, benchmark::State* state) { std::vector<quantities::Momentum> output; while (state->KeepRunning()) { state->PauseTiming(); std::unique_ptr<SolarSystem> solar_system = SolarSystem::AtСпутник1Launch( accuracy); state->ResumeTiming(); SimulateSolarSystem(solar_system.get()); state->PauseTiming(); state->SetLabel( DebugString( (solar_system->trajectories()[ SolarSystem::kSun]->last_position() - solar_system->trajectories()[ SolarSystem::kEarth]->last_position()).Norm() / AstronomicalUnit) + " ua"); state->ResumeTiming(); } } } // namespace void BM_SolarSystemMajorBodiesOnly( benchmark::State& state) { // NOLINT(runtime/references) SolarSystemBenchmark(SolarSystem::Accuracy::kMajorBodiesOnly, &state); } void BM_SolarSystemMinorAndMajorBodies( benchmark::State& state) { // NOLINT(runtime/references) SolarSystemBenchmark(SolarSystem::Accuracy::kMinorAndMajorBodies, &state); } void BM_SolarSystemAllBodiesAndOblateness( benchmark::State& state) { // NOLINT(runtime/references) SolarSystemBenchmark(SolarSystem::Accuracy::kAllBodiesAndOblateness, &state); } BENCHMARK(BM_SolarSystemMajorBodiesOnly); BENCHMARK(BM_SolarSystemMinorAndMajorBodies); BENCHMARK(BM_SolarSystemAllBodiesAndOblateness); } // namespace benchmarks } // namespace principia <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: document.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: ihi $ $Date: 2007-11-19 16:42:39 $ * * 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 _DOCUMENT_HXX #define _DOCUMENT_HXX #include <list> #include <set> #include <sal/types.h> #include <cppuhelper/implbase4.hxx> #include <com/sun/star/uno/Reference.h> #include <com/sun/star/uno/Exception.hpp> #include <com/sun/star/xml/dom/XNode.hpp> #include <com/sun/star/xml/dom/XAttr.hpp> #include <com/sun/star/xml/dom/XElement.hpp> #include <com/sun/star/xml/dom/XDOMImplementation.hpp> #include <com/sun/star/xml/dom/events/XDocumentEvent.hpp> #include <com/sun/star/xml/dom/events/XEvent.hpp> #include <com/sun/star/io/XActiveDataSource.hpp> #include <com/sun/star/io/XActiveDataControl.hpp> #include <com/sun/star/io/XOutputStream.hpp> #include <com/sun/star/io/XStreamListener.hpp> #include "node.hxx" #include <libxml/tree.h> using namespace rtl; using namespace std; using namespace com::sun::star::uno; using namespace com::sun::star::io; using namespace com::sun::star::xml::dom; using namespace com::sun::star::xml::dom::events; namespace DOM { class CDocument : public cppu::ImplInheritanceHelper4< CNode, XDocument, XDocumentEvent, XActiveDataControl, XActiveDataSource > { friend class CNode; typedef std::list< Reference< XNode >* > nodereflist_t; typedef set< Reference< XStreamListener > > listenerlist_t; private: nodereflist_t m_aNodeRefList; xmlDocPtr m_aDocPtr; // datacontrol/source state listenerlist_t m_streamListeners; Reference< XOutputStream > m_rOutputStream; protected: CDocument(xmlDocPtr aDocPtr); void addnode(xmlNodePtr aNode); public: virtual ~CDocument(); /** Creates an Attr of the given name. */ virtual Reference< XAttr > SAL_CALL createAttribute(const OUString& name) throw (DOMException); /** Creates an attribute of the given qualified name and namespace URI. */ virtual Reference< XAttr > SAL_CALL createAttributeNS(const OUString& namespaceURI, const OUString& qualifiedName) throw (DOMException); /** Creates a CDATASection node whose value is the specified string. */ virtual Reference< XCDATASection > SAL_CALL createCDATASection(const OUString& data) throw (RuntimeException); /** Creates a Comment node given the specified string. */ virtual Reference< XComment > SAL_CALL createComment(const OUString& data) throw (RuntimeException); /** Creates an empty DocumentFragment object. */ virtual Reference< XDocumentFragment > SAL_CALL createDocumentFragment() throw (RuntimeException); /** Creates an element of the type specified. */ virtual Reference< XElement > SAL_CALL createElement(const OUString& tagName) throw (DOMException); /** Creates an element of the given qualified name and namespace URI. */ virtual Reference< XElement > SAL_CALL createElementNS(const OUString& namespaceURI, const OUString& qualifiedName) throw (DOMException); /** Creates an EntityReference object. */ virtual Reference< XEntityReference > SAL_CALL createEntityReference(const OUString& name) throw (DOMException); /** Creates a ProcessingInstruction node given the specified name and data strings. */ virtual Reference< XProcessingInstruction > SAL_CALL createProcessingInstruction( const OUString& target, const OUString& data) throw (DOMException); /** Creates a Text node given the specified string. */ virtual Reference< XText > SAL_CALL createTextNode(const OUString& data) throw (RuntimeException); /** The Document Type Declaration (see DocumentType) associated with this document. */ virtual Reference< XDocumentType > SAL_CALL getDoctype() throw (RuntimeException); /** This is a convenience attribute that allows direct access to the child node that is the root element of the document. */ virtual Reference< XElement > SAL_CALL getDocumentElement() throw (RuntimeException); /** Returns the Element whose ID is given by elementId. */ virtual Reference< XElement > SAL_CALL getElementById(const OUString& elementId) throw (RuntimeException); /** Returns a NodeList of all the Elements with a given tag name in the order in which they are encountered in a preorder traversal of the Document tree. */ virtual Reference< XNodeList > SAL_CALL getElementsByTagName(const OUString& tagname) throw (RuntimeException); /** Returns a NodeList of all the Elements with a given local name and namespace URI in the order in which they are encountered in a preorder traversal of the Document tree. */ virtual Reference< XNodeList > SAL_CALL getElementsByTagNameNS(const OUString& namespaceURI, const OUString& localName) throw (RuntimeException); /** The DOMImplementation object that handles this document. */ virtual Reference< XDOMImplementation > SAL_CALL getImplementation() throw (RuntimeException); /** Imports a node from another document to this document. */ virtual Reference< XNode > SAL_CALL importNode(const Reference< XNode >& importedNode, sal_Bool deep) throw (DOMException); // XDocumentEvent virtual Reference< XEvent > SAL_CALL createEvent(const OUString& eventType) throw (RuntimeException); // XActiveDataControl, // see http://api.openoffice.org/docs/common/ref/com/sun/star/io/XActiveDataControl.html virtual void SAL_CALL addListener(const Reference< XStreamListener >& aListener ) throw (RuntimeException); virtual void SAL_CALL removeListener(const Reference< XStreamListener >& aListener ) throw (RuntimeException); virtual void SAL_CALL start() throw (RuntimeException); virtual void SAL_CALL terminate() throw (RuntimeException); // XActiveDataSource // see http://api.openoffice.org/docs/common/ref/com/sun/star/io/XActiveDataSource.html virtual void SAL_CALL setOutputStream( const Reference< XOutputStream >& aStream ) throw (RuntimeException); virtual Reference< XOutputStream > SAL_CALL getOutputStream() throw (RuntimeException); // ---- resolve uno inheritance problems... // overrides for XNode base virtual OUString SAL_CALL getNodeName() throw (RuntimeException); virtual OUString SAL_CALL getNodeValue() throw (RuntimeException); // --- delegation for XNode base. virtual Reference< XNode > SAL_CALL appendChild(const Reference< XNode >& newChild) throw (DOMException) { return CNode::appendChild(newChild); } virtual Reference< XNode > SAL_CALL cloneNode(sal_Bool deep) throw (RuntimeException) { return CNode::cloneNode(deep); } virtual Reference< XNamedNodeMap > SAL_CALL getAttributes() throw (RuntimeException) { return CNode::getAttributes(); } virtual Reference< XNodeList > SAL_CALL getChildNodes() throw (RuntimeException) { return CNode::getChildNodes(); } virtual Reference< XNode > SAL_CALL getFirstChild() throw (RuntimeException) { return CNode::getFirstChild(); } virtual Reference< XNode > SAL_CALL getLastChild() throw (RuntimeException) { return CNode::getLastChild(); } virtual OUString SAL_CALL getLocalName() throw (RuntimeException) { return CNode::getLocalName(); } virtual OUString SAL_CALL getNamespaceURI() throw (RuntimeException) { return CNode::getNamespaceURI(); } virtual Reference< XNode > SAL_CALL getNextSibling() throw (RuntimeException) { return CNode::getNextSibling(); } virtual NodeType SAL_CALL getNodeType() throw (RuntimeException) { return CNode::getNodeType(); } virtual Reference< XDocument > SAL_CALL getOwnerDocument() throw (RuntimeException) { return CNode::getOwnerDocument(); } virtual Reference< XNode > SAL_CALL getParentNode() throw (RuntimeException) { return CNode::getParentNode(); } virtual OUString SAL_CALL getPrefix() throw (RuntimeException) { return CNode::getPrefix(); } virtual Reference< XNode > SAL_CALL getPreviousSibling() throw (RuntimeException) { return CNode::getPreviousSibling(); } virtual sal_Bool SAL_CALL hasAttributes() throw (RuntimeException) { return CNode::hasAttributes(); } virtual sal_Bool SAL_CALL hasChildNodes() throw (RuntimeException) { return CNode::hasChildNodes(); } virtual Reference< XNode > SAL_CALL insertBefore( const Reference< XNode >& newChild, const Reference< XNode >& refChild) throw (DOMException) { return CNode::insertBefore(newChild, refChild); } virtual sal_Bool SAL_CALL isSupported(const OUString& feature, const OUString& ver) throw (RuntimeException) { return CNode::isSupported(feature, ver); } virtual void SAL_CALL normalize() throw (RuntimeException) { CNode::normalize(); } virtual Reference< XNode > SAL_CALL removeChild(const Reference< XNode >& oldChild) throw (DOMException) { return CNode::removeChild(oldChild); } virtual Reference< XNode > SAL_CALL replaceChild( const Reference< XNode >& newChild, const Reference< XNode >& oldChild) throw (DOMException) { return CNode::replaceChild(newChild, oldChild); } virtual void SAL_CALL setNodeValue(const OUString& nodeValue) throw (DOMException) { return CNode::setNodeValue(nodeValue); } virtual void SAL_CALL setPrefix(const OUString& prefix) throw (DOMException) { return CNode::setPrefix(prefix); } }; } #endif <commit_msg>INTEGRATION: CWS os108 (1.7.40); FILE MERGED 2007/11/19 15:25:13 mst 1.7.40.1: - uno/xml/source/dom/*.{hc}xx: add RuntimeException to exception specifications of 172 methods of the DOM implementation where it was missing; fixes #i83675#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: document.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: vg $ $Date: 2007-12-06 11:17:51 $ * * 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 _DOCUMENT_HXX #define _DOCUMENT_HXX #include <list> #include <set> #include <sal/types.h> #include <cppuhelper/implbase4.hxx> #include <com/sun/star/uno/Reference.h> #include <com/sun/star/uno/Exception.hpp> #include <com/sun/star/xml/dom/XNode.hpp> #include <com/sun/star/xml/dom/XAttr.hpp> #include <com/sun/star/xml/dom/XElement.hpp> #include <com/sun/star/xml/dom/XDOMImplementation.hpp> #include <com/sun/star/xml/dom/events/XDocumentEvent.hpp> #include <com/sun/star/xml/dom/events/XEvent.hpp> #include <com/sun/star/io/XActiveDataSource.hpp> #include <com/sun/star/io/XActiveDataControl.hpp> #include <com/sun/star/io/XOutputStream.hpp> #include <com/sun/star/io/XStreamListener.hpp> #include "node.hxx" #include <libxml/tree.h> using namespace rtl; using namespace std; using namespace com::sun::star::uno; using namespace com::sun::star::io; using namespace com::sun::star::xml::dom; using namespace com::sun::star::xml::dom::events; namespace DOM { class CDocument : public cppu::ImplInheritanceHelper4< CNode, XDocument, XDocumentEvent, XActiveDataControl, XActiveDataSource > { friend class CNode; typedef std::list< Reference< XNode >* > nodereflist_t; typedef set< Reference< XStreamListener > > listenerlist_t; private: nodereflist_t m_aNodeRefList; xmlDocPtr m_aDocPtr; // datacontrol/source state listenerlist_t m_streamListeners; Reference< XOutputStream > m_rOutputStream; protected: CDocument(xmlDocPtr aDocPtr); void addnode(xmlNodePtr aNode); public: virtual ~CDocument(); /** Creates an Attr of the given name. */ virtual Reference< XAttr > SAL_CALL createAttribute(const OUString& name) throw (RuntimeException, DOMException); /** Creates an attribute of the given qualified name and namespace URI. */ virtual Reference< XAttr > SAL_CALL createAttributeNS(const OUString& namespaceURI, const OUString& qualifiedName) throw (RuntimeException, DOMException); /** Creates a CDATASection node whose value is the specified string. */ virtual Reference< XCDATASection > SAL_CALL createCDATASection(const OUString& data) throw (RuntimeException); /** Creates a Comment node given the specified string. */ virtual Reference< XComment > SAL_CALL createComment(const OUString& data) throw (RuntimeException); /** Creates an empty DocumentFragment object. */ virtual Reference< XDocumentFragment > SAL_CALL createDocumentFragment() throw (RuntimeException); /** Creates an element of the type specified. */ virtual Reference< XElement > SAL_CALL createElement(const OUString& tagName) throw (RuntimeException, DOMException); /** Creates an element of the given qualified name and namespace URI. */ virtual Reference< XElement > SAL_CALL createElementNS(const OUString& namespaceURI, const OUString& qualifiedName) throw (RuntimeException, DOMException); /** Creates an EntityReference object. */ virtual Reference< XEntityReference > SAL_CALL createEntityReference(const OUString& name) throw (RuntimeException, DOMException); /** Creates a ProcessingInstruction node given the specified name and data strings. */ virtual Reference< XProcessingInstruction > SAL_CALL createProcessingInstruction( const OUString& target, const OUString& data) throw (RuntimeException, DOMException); /** Creates a Text node given the specified string. */ virtual Reference< XText > SAL_CALL createTextNode(const OUString& data) throw (RuntimeException); /** The Document Type Declaration (see DocumentType) associated with this document. */ virtual Reference< XDocumentType > SAL_CALL getDoctype() throw (RuntimeException); /** This is a convenience attribute that allows direct access to the child node that is the root element of the document. */ virtual Reference< XElement > SAL_CALL getDocumentElement() throw (RuntimeException); /** Returns the Element whose ID is given by elementId. */ virtual Reference< XElement > SAL_CALL getElementById(const OUString& elementId) throw (RuntimeException); /** Returns a NodeList of all the Elements with a given tag name in the order in which they are encountered in a preorder traversal of the Document tree. */ virtual Reference< XNodeList > SAL_CALL getElementsByTagName(const OUString& tagname) throw (RuntimeException); /** Returns a NodeList of all the Elements with a given local name and namespace URI in the order in which they are encountered in a preorder traversal of the Document tree. */ virtual Reference< XNodeList > SAL_CALL getElementsByTagNameNS(const OUString& namespaceURI, const OUString& localName) throw (RuntimeException); /** The DOMImplementation object that handles this document. */ virtual Reference< XDOMImplementation > SAL_CALL getImplementation() throw (RuntimeException); /** Imports a node from another document to this document. */ virtual Reference< XNode > SAL_CALL importNode(const Reference< XNode >& importedNode, sal_Bool deep) throw (RuntimeException, DOMException); // XDocumentEvent virtual Reference< XEvent > SAL_CALL createEvent(const OUString& eventType) throw (RuntimeException); // XActiveDataControl, // see http://api.openoffice.org/docs/common/ref/com/sun/star/io/XActiveDataControl.html virtual void SAL_CALL addListener(const Reference< XStreamListener >& aListener ) throw (RuntimeException); virtual void SAL_CALL removeListener(const Reference< XStreamListener >& aListener ) throw (RuntimeException); virtual void SAL_CALL start() throw (RuntimeException); virtual void SAL_CALL terminate() throw (RuntimeException); // XActiveDataSource // see http://api.openoffice.org/docs/common/ref/com/sun/star/io/XActiveDataSource.html virtual void SAL_CALL setOutputStream( const Reference< XOutputStream >& aStream ) throw (RuntimeException); virtual Reference< XOutputStream > SAL_CALL getOutputStream() throw (RuntimeException); // ---- resolve uno inheritance problems... // overrides for XNode base virtual OUString SAL_CALL getNodeName() throw (RuntimeException); virtual OUString SAL_CALL getNodeValue() throw (RuntimeException); // --- delegation for XNde base. virtual Reference< XNode > SAL_CALL appendChild(const Reference< XNode >& newChild) throw (RuntimeException, DOMException) { return CNode::appendChild(newChild); } virtual Reference< XNode > SAL_CALL cloneNode(sal_Bool deep) throw (RuntimeException) { return CNode::cloneNode(deep); } virtual Reference< XNamedNodeMap > SAL_CALL getAttributes() throw (RuntimeException) { return CNode::getAttributes(); } virtual Reference< XNodeList > SAL_CALL getChildNodes() throw (RuntimeException) { return CNode::getChildNodes(); } virtual Reference< XNode > SAL_CALL getFirstChild() throw (RuntimeException) { return CNode::getFirstChild(); } virtual Reference< XNode > SAL_CALL getLastChild() throw (RuntimeException) { return CNode::getLastChild(); } virtual OUString SAL_CALL getLocalName() throw (RuntimeException) { return CNode::getLocalName(); } virtual OUString SAL_CALL getNamespaceURI() throw (RuntimeException) { return CNode::getNamespaceURI(); } virtual Reference< XNode > SAL_CALL getNextSibling() throw (RuntimeException) { return CNode::getNextSibling(); } virtual NodeType SAL_CALL getNodeType() throw (RuntimeException) { return CNode::getNodeType(); } virtual Reference< XDocument > SAL_CALL getOwnerDocument() throw (RuntimeException) { return CNode::getOwnerDocument(); } virtual Reference< XNode > SAL_CALL getParentNode() throw (RuntimeException) { return CNode::getParentNode(); } virtual OUString SAL_CALL getPrefix() throw (RuntimeException) { return CNode::getPrefix(); } virtual Reference< XNode > SAL_CALL getPreviousSibling() throw (RuntimeException) { return CNode::getPreviousSibling(); } virtual sal_Bool SAL_CALL hasAttributes() throw (RuntimeException) { return CNode::hasAttributes(); } virtual sal_Bool SAL_CALL hasChildNodes() throw (RuntimeException) { return CNode::hasChildNodes(); } virtual Reference< XNode > SAL_CALL insertBefore( const Reference< XNode >& newChild, const Reference< XNode >& refChild) throw (DOMException) { return CNode::insertBefore(newChild, refChild); } virtual sal_Bool SAL_CALL isSupported(const OUString& feature, const OUString& ver) throw (RuntimeException) { return CNode::isSupported(feature, ver); } virtual void SAL_CALL normalize() throw (RuntimeException) { CNode::normalize(); } virtual Reference< XNode > SAL_CALL removeChild(const Reference< XNode >& oldChild) throw (RuntimeException, DOMException) { return CNode::removeChild(oldChild); } virtual Reference< XNode > SAL_CALL replaceChild( const Reference< XNode >& newChild, const Reference< XNode >& oldChild) throw (RuntimeException, DOMException) { return CNode::replaceChild(newChild, oldChild); } virtual void SAL_CALL setNodeValue(const OUString& nodeValue) throw (RuntimeException, DOMException) { return CNode::setNodeValue(nodeValue); } virtual void SAL_CALL setPrefix(const OUString& prefix) throw (RuntimeException, DOMException) { return CNode::setPrefix(prefix); } }; } #endif <|endoftext|>
<commit_before>// OvlReferenceTable.hpp /* * (C) Copyright 2015 Noah Roth * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ #pragma once #include "stdafx.hpp" #include "OvlRaw.hpp" #include "OvlDataInfoTable.hpp" #include "OvlStringTable.hpp" #include "OvlPointerTable.hpp" #include "OutputLog.hpp" namespace RCT3Asset { class DataInfo; class Reference { friend class DataInfo; private: unsigned int* _location; std::string _nameID; DataInfo _owner; public: Reference(void* location, std::string nameID); unsigned int* Location(); std::string NameID(); DataInfo& Owner(); void AssignOwner(DataInfo info) { _owner = info; } }; class OvlReferenceTable { private: DataEntry _entries[2]; public: std::vector<Reference> References[2]; // * Returns the size of the OvlReferenceTable in the specified file. unsigned int Size(unsigned int file); // * Creates the OvlReferenceTable data. void Create(OvlStringTable& strTable, OvlPointerTable& pointerTable, OvlDataInfoTable& infoTable, RCT3Debugging::OutputLog& log); void AssignEntry(DataEntry entry, unsigned int file) { if (entry.Data != nullptr) _entries[file] = entry; } }; }<commit_msg>Removed DataInfo as a friend class to Reference<commit_after>// OvlReferenceTable.hpp /* * (C) Copyright 2015 Noah Roth * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ #pragma once #include "stdafx.hpp" #include "OvlRaw.hpp" #include "OvlDataInfoTable.hpp" #include "OvlStringTable.hpp" #include "OvlPointerTable.hpp" #include "OutputLog.hpp" namespace RCT3Asset { class DataInfo; class Reference { private: unsigned int* _location; std::string _nameID; DataInfo _owner; public: Reference(void* location, std::string nameID); unsigned int* Location(); std::string NameID(); DataInfo& Owner(); void AssignOwner(DataInfo info) { _owner = info; } }; class OvlReferenceTable { private: DataEntry _entries[2]; public: std::vector<Reference> References[2]; // * Returns the size of the OvlReferenceTable in the specified file. unsigned int Size(unsigned int file); // * Creates the OvlReferenceTable data. void Create(OvlStringTable& strTable, OvlPointerTable& pointerTable, OvlDataInfoTable& infoTable, RCT3Debugging::OutputLog& log); void AssignEntry(DataEntry entry, unsigned int file) { if (entry.Data != nullptr) _entries[file] = entry; } }; }<|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-2014 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 "OgreGLTexture.h" #include "OgreGLSupport.h" #include "OgreGLPixelFormat.h" #include "OgreGLHardwarePixelBuffer.h" #include "OgreTextureManager.h" #include "OgreImage.h" #include "OgreLogManager.h" #include "OgreCamera.h" #include "OgreException.h" #include "OgreRoot.h" #include "OgreCodec.h" #include "OgreImageCodec.h" #include "OgreStringConverter.h" #include "OgreBitwise.h" #include "OgreGLFBORenderTexture.h" #include "OgreGLStateCacheManager.h" #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 # define WIN32_LEAN_AND_MEAN # if !defined(NOMINMAX) && defined(_MSC_VER) # define NOMINMAX // required to stop windows.h messing up std::min # endif # include <windows.h> # include <wingdi.h> #endif namespace Ogre { GLTexture::GLTexture(ResourceManager* creator, const String& name, ResourceHandle handle, const String& group, bool isManual, ManualResourceLoader* loader, GLSupport& support) : Texture(creator, name, handle, group, isManual, loader), mTextureID(0), mGLSupport(support) { } GLTexture::~GLTexture() { // have to call this here rather than in Resource destructor // since calling virtual methods in base destructors causes crash if (isLoaded()) { unload(); } else { freeInternalResources(); } } GLenum GLTexture::getGLTextureTarget(void) const { switch(mTextureType) { case TEX_TYPE_1D: return GL_TEXTURE_1D; case TEX_TYPE_2D: return GL_TEXTURE_2D; case TEX_TYPE_3D: return GL_TEXTURE_3D; case TEX_TYPE_CUBE_MAP: return GL_TEXTURE_CUBE_MAP; case TEX_TYPE_2D_ARRAY: return GL_TEXTURE_2D_ARRAY_EXT; default: return 0; }; } //* Creation / loading methods ******************************************** void GLTexture::createInternalResourcesImpl(void) { if (!GLEW_VERSION_1_2 && mTextureType == TEX_TYPE_3D) OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "3D Textures not supported before OpenGL 1.2", "GLTexture::createInternalResourcesImpl"); if (!GLEW_VERSION_2_0 && mTextureType == TEX_TYPE_2D_ARRAY) OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "2D texture arrays not supported before OpenGL 2.0", "GLTexture::createInternalResourcesImpl"); // Convert to nearest power-of-two size if required mWidth = GLPixelUtil::optionalPO2(mWidth); mHeight = GLPixelUtil::optionalPO2(mHeight); mDepth = GLPixelUtil::optionalPO2(mDepth); // Adjust format if required mFormat = TextureManager::getSingleton().getNativeFormat(mTextureType, mFormat, mUsage); // Check requested number of mipmaps size_t maxMips = GLPixelUtil::getMaxMipmaps(mWidth, mHeight, mDepth, mFormat); mNumMipmaps = mNumRequestedMipmaps; if(mNumMipmaps>maxMips) mNumMipmaps = maxMips; // Check if we can do HW mipmap generation mMipmapsHardwareGenerated = Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_AUTOMIPMAP); // Generate texture name glGenTextures( 1, &mTextureID ); // Set texture type mGLSupport.getStateCacheManager()->bindGLTexture( getGLTextureTarget(), mTextureID ); // This needs to be set otherwise the texture doesn't get rendered if (GLEW_VERSION_1_2) mGLSupport.getStateCacheManager()->setTexParameteri(getGLTextureTarget(), GL_TEXTURE_MAX_LEVEL, mNumMipmaps); // Set some misc default parameters so NVidia won't complain, these can of course be changed later mGLSupport.getStateCacheManager()->setTexParameteri(getGLTextureTarget(), GL_TEXTURE_MIN_FILTER, GL_NEAREST); mGLSupport.getStateCacheManager()->setTexParameteri(getGLTextureTarget(), GL_TEXTURE_MAG_FILTER, GL_NEAREST); if (GLEW_VERSION_1_2) { mGLSupport.getStateCacheManager()->setTexParameteri(getGLTextureTarget(), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); mGLSupport.getStateCacheManager()->setTexParameteri(getGLTextureTarget(), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } if((mUsage & TU_AUTOMIPMAP) && mNumRequestedMipmaps && mMipmapsHardwareGenerated) { mGLSupport.getStateCacheManager()->setTexParameteri( getGLTextureTarget(), GL_GENERATE_MIPMAP, GL_TRUE ); } // Allocate internal buffer so that glTexSubImageXD can be used // Internal format GLenum format = GLPixelUtil::getClosestGLInternalFormat(mFormat, mHwGamma); uint32 width = mWidth; uint32 height = mHeight; uint32 depth = mDepth; if(PixelUtil::isCompressed(mFormat)) { // Compressed formats GLsizei size = static_cast<GLsizei>(PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat)); // Provide temporary buffer filled with zeroes as glCompressedTexImageXD does not // accept a 0 pointer like normal glTexImageXD // Run through this process for every mipmap to pregenerate mipmap piramid uint8 *tmpdata = new uint8[size]; memset(tmpdata, 0, size); for(uint8 mip=0; mip<=mNumMipmaps; mip++) { size = static_cast<GLsizei>(PixelUtil::getMemorySize(width, height, depth, mFormat)); switch(mTextureType) { case TEX_TYPE_1D: glCompressedTexImage1DARB(GL_TEXTURE_1D, mip, format, width, 0, size, tmpdata); break; case TEX_TYPE_2D: glCompressedTexImage2DARB(GL_TEXTURE_2D, mip, format, width, height, 0, size, tmpdata); break; case TEX_TYPE_2D_ARRAY: case TEX_TYPE_3D: glCompressedTexImage3DARB(getGLTextureTarget(), mip, format, width, height, depth, 0, size, tmpdata); break; case TEX_TYPE_CUBE_MAP: for(int face=0; face<6; face++) { glCompressedTexImage2DARB(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, format, width, height, 0, size, tmpdata); } break; case TEX_TYPE_2D_RECT: break; }; if(width>1) width = width/2; if(height>1) height = height/2; if(depth>1 && mTextureType != TEX_TYPE_2D_ARRAY) depth = depth/2; } delete [] tmpdata; } else { // Run through this process to pregenerate mipmap pyramid for(uint8 mip=0; mip<=mNumMipmaps; mip++) { // Normal formats switch(mTextureType) { case TEX_TYPE_1D: glTexImage1D(GL_TEXTURE_1D, mip, format, width, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); break; case TEX_TYPE_2D: glTexImage2D(GL_TEXTURE_2D, mip, format, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); break; case TEX_TYPE_2D_ARRAY: case TEX_TYPE_3D: glTexImage3D(getGLTextureTarget(), mip, format, width, height, depth, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); break; case TEX_TYPE_CUBE_MAP: for(int face=0; face<6; face++) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, format, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); } break; case TEX_TYPE_2D_RECT: break; }; if(width>1) width = width/2; if(height>1) height = height/2; if(depth>1 && mTextureType != TEX_TYPE_2D_ARRAY) depth = depth/2; } } _createSurfaceList(); // Get final internal format mFormat = getBuffer(0,0)->getFormat(); } void GLTexture::createRenderTexture(void) { // Create the GL texture // This already does everything necessary createInternalResources(); } static inline void do_image_io(const String &name, const String &group, const String &ext, vector<Image>::type &images, Resource *r) { size_t imgIdx = images.size(); images.push_back(Image()); DataStreamPtr dstream = ResourceGroupManager::getSingleton().openResource( name, group, true, r); images[imgIdx].load(dstream, ext); } void GLTexture::prepareImpl() { if( mUsage & TU_RENDERTARGET ) return; String baseName, ext; size_t pos = mName.find_last_of("."); baseName = mName.substr(0, pos); if( pos != String::npos ) ext = mName.substr(pos+1); LoadedImages loadedImages = LoadedImages(new vector<Image>::type()); if(mTextureType == TEX_TYPE_1D || mTextureType == TEX_TYPE_2D || mTextureType == TEX_TYPE_2D_ARRAY || mTextureType == TEX_TYPE_3D) { do_image_io(mName, mGroup, ext, *loadedImages, this); // If this is a cube map, set the texture type flag accordingly. if ((*loadedImages)[0].hasFlag(IF_CUBEMAP)) mTextureType = TEX_TYPE_CUBE_MAP; // If this is a volumetric texture set the texture type flag accordingly. if((*loadedImages)[0].getDepth() > 1 && mTextureType != TEX_TYPE_2D_ARRAY) mTextureType = TEX_TYPE_3D; } else if (mTextureType == TEX_TYPE_CUBE_MAP) { if(getSourceFileType() == "dds") { // XX HACK there should be a better way to specify whether // all faces are in the same file or not do_image_io(mName, mGroup, ext, *loadedImages, this); } else { vector<Image>::type images(6); ConstImagePtrList imagePtrs; static const String suffixes[6] = {"_rt", "_lf", "_up", "_dn", "_fr", "_bk"}; for(size_t i = 0; i < 6; i++) { String fullName = baseName + suffixes[i]; if (!ext.empty()) fullName = fullName + "." + ext; // find & load resource data intro stream to allow resource // group changes if required do_image_io(fullName,mGroup,ext,*loadedImages,this); } } } else OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, "**** Unknown texture type ****", "GLTexture::prepare" ); mLoadedImages = loadedImages; } void GLTexture::unprepareImpl() { mLoadedImages.setNull(); } void GLTexture::loadImpl() { if( mUsage & TU_RENDERTARGET ) { createRenderTexture(); return; } // Now the only copy is on the stack and will be cleaned in case of // exceptions being thrown from _loadImages LoadedImages loadedImages = mLoadedImages; mLoadedImages.setNull(); // Call internal _loadImages, not loadImage since that's external and // will determine load status etc again ConstImagePtrList imagePtrs; for (size_t i=0 ; i<loadedImages->size() ; ++i) { imagePtrs.push_back(&(*loadedImages)[i]); } _loadImages(imagePtrs); // Generate mipmaps after all texture levels have been loaded // This is required for compressed formats such as DXT // If we can do automip generation and the user desires this, do so if((mUsage & TU_AUTOMIPMAP) && mNumRequestedMipmaps && mMipmapsHardwareGenerated) { glGenerateMipmapEXT(getGLTextureTarget()); } } //************************************************************************* void GLTexture::freeInternalResourcesImpl() { mSurfaceList.clear(); glDeleteTextures( 1, &mTextureID ); mGLSupport.getStateCacheManager()->invalidateStateForTexture( mTextureID ); } //--------------------------------------------------------------------------------------------- void GLTexture::_createSurfaceList() { mSurfaceList.clear(); // For all faces and mipmaps, store surfaces as HardwarePixelBufferSharedPtr bool wantGeneratedMips = (mUsage & TU_AUTOMIPMAP)!=0; // Do mipmapping in software? (uses GLU) For some cards, this is still needed. Of course, // only when mipmap generation is desired. bool doSoftware = wantGeneratedMips && !mMipmapsHardwareGenerated && getNumMipmaps(); for(GLint face=0; face<static_cast<GLint>(getNumFaces()); face++) { for(uint8 mip=0; mip<=getNumMipmaps(); mip++) { GLHardwarePixelBuffer *buf = new GLTextureBuffer(mGLSupport, mName, getGLTextureTarget(), mTextureID, face, mip, static_cast<HardwareBuffer::Usage>(mUsage), doSoftware && mip==0, mHwGamma, mFSAA); mSurfaceList.push_back(HardwarePixelBufferSharedPtr(buf)); /// Check for error if(buf->getWidth()==0 || buf->getHeight()==0 || buf->getDepth()==0) { OGRE_EXCEPT( Exception::ERR_RENDERINGAPI_ERROR, "Zero sized texture surface on texture "+getName()+ " face "+StringConverter::toString(face)+ " mipmap "+StringConverter::toString(mip)+ ". Probably, the GL driver refused to create the texture.", "GLTexture::_createSurfaceList"); } } } } //--------------------------------------------------------------------------------------------- HardwarePixelBufferSharedPtr GLTexture::getBuffer(size_t face, size_t mipmap) { if(face >= getNumFaces()) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Face index out of range", "GLTexture::getBuffer"); if(mipmap > mNumMipmaps) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Mipmap index out of range", "GLTexture::getBuffer"); unsigned long idx = face*(mNumMipmaps+1) + mipmap; assert(idx < mSurfaceList.size()); return mSurfaceList[idx]; } //--------------------------------------------------------------------------------------------- void GLTexture::getCustomAttribute(const String& name, void* pData) { if (name == "GLID") *static_cast<GLuint*>(pData) = mTextureID; } } <commit_msg>GL: Texture allocate correct amount of memory<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-2014 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 "OgreGLTexture.h" #include "OgreGLSupport.h" #include "OgreGLPixelFormat.h" #include "OgreGLHardwarePixelBuffer.h" #include "OgreTextureManager.h" #include "OgreImage.h" #include "OgreLogManager.h" #include "OgreCamera.h" #include "OgreException.h" #include "OgreRoot.h" #include "OgreCodec.h" #include "OgreImageCodec.h" #include "OgreStringConverter.h" #include "OgreBitwise.h" #include "OgreGLFBORenderTexture.h" #include "OgreGLStateCacheManager.h" #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 # define WIN32_LEAN_AND_MEAN # if !defined(NOMINMAX) && defined(_MSC_VER) # define NOMINMAX // required to stop windows.h messing up std::min # endif # include <windows.h> # include <wingdi.h> #endif namespace Ogre { GLTexture::GLTexture(ResourceManager* creator, const String& name, ResourceHandle handle, const String& group, bool isManual, ManualResourceLoader* loader, GLSupport& support) : Texture(creator, name, handle, group, isManual, loader), mTextureID(0), mGLSupport(support) { } GLTexture::~GLTexture() { // have to call this here rather than in Resource destructor // since calling virtual methods in base destructors causes crash if (isLoaded()) { unload(); } else { freeInternalResources(); } } GLenum GLTexture::getGLTextureTarget(void) const { switch(mTextureType) { case TEX_TYPE_1D: return GL_TEXTURE_1D; case TEX_TYPE_2D: return GL_TEXTURE_2D; case TEX_TYPE_3D: return GL_TEXTURE_3D; case TEX_TYPE_CUBE_MAP: return GL_TEXTURE_CUBE_MAP; case TEX_TYPE_2D_ARRAY: return GL_TEXTURE_2D_ARRAY_EXT; default: return 0; }; } //* Creation / loading methods ******************************************** void GLTexture::createInternalResourcesImpl(void) { if (!GLEW_VERSION_1_2 && mTextureType == TEX_TYPE_3D) OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "3D Textures not supported before OpenGL 1.2", "GLTexture::createInternalResourcesImpl"); if (!GLEW_VERSION_2_0 && mTextureType == TEX_TYPE_2D_ARRAY) OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "2D texture arrays not supported before OpenGL 2.0", "GLTexture::createInternalResourcesImpl"); // Convert to nearest power-of-two size if required mWidth = GLPixelUtil::optionalPO2(mWidth); mHeight = GLPixelUtil::optionalPO2(mHeight); mDepth = GLPixelUtil::optionalPO2(mDepth); // Adjust format if required mFormat = TextureManager::getSingleton().getNativeFormat(mTextureType, mFormat, mUsage); // Check requested number of mipmaps size_t maxMips = GLPixelUtil::getMaxMipmaps(mWidth, mHeight, mDepth, mFormat); mNumMipmaps = mNumRequestedMipmaps; if(mNumMipmaps>maxMips) mNumMipmaps = maxMips; // Check if we can do HW mipmap generation mMipmapsHardwareGenerated = Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_AUTOMIPMAP); // Generate texture name glGenTextures( 1, &mTextureID ); // Set texture type mGLSupport.getStateCacheManager()->bindGLTexture( getGLTextureTarget(), mTextureID ); // This needs to be set otherwise the texture doesn't get rendered if (GLEW_VERSION_1_2) mGLSupport.getStateCacheManager()->setTexParameteri(getGLTextureTarget(), GL_TEXTURE_MAX_LEVEL, mNumMipmaps); // Set some misc default parameters so NVidia won't complain, these can of course be changed later mGLSupport.getStateCacheManager()->setTexParameteri(getGLTextureTarget(), GL_TEXTURE_MIN_FILTER, GL_NEAREST); mGLSupport.getStateCacheManager()->setTexParameteri(getGLTextureTarget(), GL_TEXTURE_MAG_FILTER, GL_NEAREST); if (GLEW_VERSION_1_2) { mGLSupport.getStateCacheManager()->setTexParameteri(getGLTextureTarget(), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); mGLSupport.getStateCacheManager()->setTexParameteri(getGLTextureTarget(), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } if((mUsage & TU_AUTOMIPMAP) && mNumRequestedMipmaps && mMipmapsHardwareGenerated) { mGLSupport.getStateCacheManager()->setTexParameteri( getGLTextureTarget(), GL_GENERATE_MIPMAP, GL_TRUE ); } // Allocate internal buffer so that glTexSubImageXD can be used // Internal format GLenum internalformat = GLPixelUtil::getClosestGLInternalFormat(mFormat, mHwGamma); uint32 width = mWidth; uint32 height = mHeight; uint32 depth = mDepth; GLenum format = GLPixelUtil::getGLOriginFormat(mFormat); GLenum datatype = GLPixelUtil::getGLOriginDataType(mFormat); if(PixelUtil::isCompressed(mFormat)) { // Compressed formats GLsizei size = static_cast<GLsizei>(PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat)); // Provide temporary buffer filled with zeroes as glCompressedTexImageXD does not // accept a 0 pointer like normal glTexImageXD // Run through this process for every mipmap to pregenerate mipmap piramid uint8 *tmpdata = new uint8[size]; memset(tmpdata, 0, size); for(uint8 mip=0; mip<=mNumMipmaps; mip++) { size = static_cast<GLsizei>(PixelUtil::getMemorySize(width, height, depth, mFormat)); switch(mTextureType) { case TEX_TYPE_1D: glCompressedTexImage1DARB(GL_TEXTURE_1D, mip, internalformat, width, 0, size, tmpdata); break; case TEX_TYPE_2D: glCompressedTexImage2DARB(GL_TEXTURE_2D, mip, internalformat, width, height, 0, size, tmpdata); break; case TEX_TYPE_2D_ARRAY: case TEX_TYPE_3D: glCompressedTexImage3DARB(getGLTextureTarget(), mip, internalformat, width, height, depth, 0, size, tmpdata); break; case TEX_TYPE_CUBE_MAP: for(int face=0; face<6; face++) { glCompressedTexImage2DARB(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, internalformat, width, height, 0, size, tmpdata); } break; case TEX_TYPE_2D_RECT: break; }; if(width>1) width = width/2; if(height>1) height = height/2; if(depth>1 && mTextureType != TEX_TYPE_2D_ARRAY) depth = depth/2; } delete [] tmpdata; } else { // Run through this process to pregenerate mipmap pyramid for(uint8 mip=0; mip<=mNumMipmaps; mip++) { // Normal formats switch(mTextureType) { case TEX_TYPE_1D: glTexImage1D(GL_TEXTURE_1D, mip, internalformat, width, 0, format, datatype, 0); break; case TEX_TYPE_2D: glTexImage2D(GL_TEXTURE_2D, mip, internalformat, width, height, 0, format, datatype, 0); break; case TEX_TYPE_2D_ARRAY: case TEX_TYPE_3D: glTexImage3D(getGLTextureTarget(), mip, internalformat, width, height, depth, 0, format, datatype, 0); break; case TEX_TYPE_CUBE_MAP: for(int face=0; face<6; face++) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, internalformat, width, height, 0, format, datatype, 0); } break; case TEX_TYPE_2D_RECT: break; }; if(width>1) width = width/2; if(height>1) height = height/2; if(depth>1 && mTextureType != TEX_TYPE_2D_ARRAY) depth = depth/2; } } _createSurfaceList(); // Get final internal format mFormat = getBuffer(0,0)->getFormat(); } void GLTexture::createRenderTexture(void) { // Create the GL texture // This already does everything necessary createInternalResources(); } static inline void do_image_io(const String &name, const String &group, const String &ext, vector<Image>::type &images, Resource *r) { size_t imgIdx = images.size(); images.push_back(Image()); DataStreamPtr dstream = ResourceGroupManager::getSingleton().openResource( name, group, true, r); images[imgIdx].load(dstream, ext); } void GLTexture::prepareImpl() { if( mUsage & TU_RENDERTARGET ) return; String baseName, ext; size_t pos = mName.find_last_of("."); baseName = mName.substr(0, pos); if( pos != String::npos ) ext = mName.substr(pos+1); LoadedImages loadedImages = LoadedImages(new vector<Image>::type()); if(mTextureType == TEX_TYPE_1D || mTextureType == TEX_TYPE_2D || mTextureType == TEX_TYPE_2D_ARRAY || mTextureType == TEX_TYPE_3D) { do_image_io(mName, mGroup, ext, *loadedImages, this); // If this is a cube map, set the texture type flag accordingly. if ((*loadedImages)[0].hasFlag(IF_CUBEMAP)) mTextureType = TEX_TYPE_CUBE_MAP; // If this is a volumetric texture set the texture type flag accordingly. if((*loadedImages)[0].getDepth() > 1 && mTextureType != TEX_TYPE_2D_ARRAY) mTextureType = TEX_TYPE_3D; } else if (mTextureType == TEX_TYPE_CUBE_MAP) { if(getSourceFileType() == "dds") { // XX HACK there should be a better way to specify whether // all faces are in the same file or not do_image_io(mName, mGroup, ext, *loadedImages, this); } else { vector<Image>::type images(6); ConstImagePtrList imagePtrs; static const String suffixes[6] = {"_rt", "_lf", "_up", "_dn", "_fr", "_bk"}; for(size_t i = 0; i < 6; i++) { String fullName = baseName + suffixes[i]; if (!ext.empty()) fullName = fullName + "." + ext; // find & load resource data intro stream to allow resource // group changes if required do_image_io(fullName,mGroup,ext,*loadedImages,this); } } } else OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, "**** Unknown texture type ****", "GLTexture::prepare" ); mLoadedImages = loadedImages; } void GLTexture::unprepareImpl() { mLoadedImages.setNull(); } void GLTexture::loadImpl() { if( mUsage & TU_RENDERTARGET ) { createRenderTexture(); return; } // Now the only copy is on the stack and will be cleaned in case of // exceptions being thrown from _loadImages LoadedImages loadedImages = mLoadedImages; mLoadedImages.setNull(); // Call internal _loadImages, not loadImage since that's external and // will determine load status etc again ConstImagePtrList imagePtrs; for (size_t i=0 ; i<loadedImages->size() ; ++i) { imagePtrs.push_back(&(*loadedImages)[i]); } _loadImages(imagePtrs); // Generate mipmaps after all texture levels have been loaded // This is required for compressed formats such as DXT // If we can do automip generation and the user desires this, do so if((mUsage & TU_AUTOMIPMAP) && mNumRequestedMipmaps && mMipmapsHardwareGenerated) { glGenerateMipmapEXT(getGLTextureTarget()); } } //************************************************************************* void GLTexture::freeInternalResourcesImpl() { mSurfaceList.clear(); glDeleteTextures( 1, &mTextureID ); mGLSupport.getStateCacheManager()->invalidateStateForTexture( mTextureID ); } //--------------------------------------------------------------------------------------------- void GLTexture::_createSurfaceList() { mSurfaceList.clear(); // For all faces and mipmaps, store surfaces as HardwarePixelBufferSharedPtr bool wantGeneratedMips = (mUsage & TU_AUTOMIPMAP)!=0; // Do mipmapping in software? (uses GLU) For some cards, this is still needed. Of course, // only when mipmap generation is desired. bool doSoftware = wantGeneratedMips && !mMipmapsHardwareGenerated && getNumMipmaps(); for(GLint face=0; face<static_cast<GLint>(getNumFaces()); face++) { for(uint8 mip=0; mip<=getNumMipmaps(); mip++) { GLHardwarePixelBuffer *buf = new GLTextureBuffer(mGLSupport, mName, getGLTextureTarget(), mTextureID, face, mip, static_cast<HardwareBuffer::Usage>(mUsage), doSoftware && mip==0, mHwGamma, mFSAA); mSurfaceList.push_back(HardwarePixelBufferSharedPtr(buf)); /// Check for error if(buf->getWidth()==0 || buf->getHeight()==0 || buf->getDepth()==0) { OGRE_EXCEPT( Exception::ERR_RENDERINGAPI_ERROR, "Zero sized texture surface on texture "+getName()+ " face "+StringConverter::toString(face)+ " mipmap "+StringConverter::toString(mip)+ ". Probably, the GL driver refused to create the texture.", "GLTexture::_createSurfaceList"); } } } } //--------------------------------------------------------------------------------------------- HardwarePixelBufferSharedPtr GLTexture::getBuffer(size_t face, size_t mipmap) { if(face >= getNumFaces()) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Face index out of range", "GLTexture::getBuffer"); if(mipmap > mNumMipmaps) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Mipmap index out of range", "GLTexture::getBuffer"); unsigned long idx = face*(mNumMipmaps+1) + mipmap; assert(idx < mSurfaceList.size()); return mSurfaceList[idx]; } //--------------------------------------------------------------------------------------------- void GLTexture::getCustomAttribute(const String& name, void* pData) { if (name == "GLID") *static_cast<GLuint*>(pData) = mTextureID; } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkTreeDFSIterator.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkTreeDFSIterator.h" #include "vtkTree.h" #include "vtkObjectFactory.h" #include "vtkIntArray.h" #include "vtkIdList.h" #include <vtkstd/stack> using vtkstd::stack; struct vtkTreeDFSIteratorPosition { vtkTreeDFSIteratorPosition(vtkIdType node, vtkIdType index) : Node(node), Index(index) { } vtkIdType Node; vtkIdType Index; // How far along we are in the node's edge array }; class vtkTreeDFSIteratorInternals { public: stack<vtkTreeDFSIteratorPosition> Stack; }; vtkCxxRevisionMacro(vtkTreeDFSIterator, "1.1"); vtkStandardNewMacro(vtkTreeDFSIterator); vtkTreeDFSIterator::vtkTreeDFSIterator() { this->Internals = new vtkTreeDFSIteratorInternals(); this->Tree = NULL; this->Color = vtkIntArray::New(); this->StartNode = -1; this->Mode = 0; } vtkTreeDFSIterator::~vtkTreeDFSIterator() { if (this->Internals) { delete this->Internals; this->Internals = NULL; } if (this->Tree) { this->Tree->Delete(); this->Tree = NULL; } if (this->Color) { this->Color->Delete(); this->Color = NULL; } } void vtkTreeDFSIterator::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } void vtkTreeDFSIterator::Initialize() { if (this->Tree == NULL) { return; } // Set all colors to white this->Color->Resize(this->Tree->GetNumberOfNodes()); for (vtkIdType i = 0; i < this->Tree->GetNumberOfNodes(); i++) { this->Color->SetValue(i, this->WHITE); } if (this->StartNode < 0) { this->StartNode = this->Tree->GetRoot(); } this->CurRoot = this->StartNode; while (this->Internals->Stack.size()) { this->Internals->Stack.pop(); } // Find the first item if (this->Tree->GetNumberOfNodes() > 0) { this->NextId = this->NextInternal(); } else { this->NextId = -1; } } void vtkTreeDFSIterator::SetTree(vtkTree* tree) { vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting Tree to " << tree ); if (this->Tree != tree) { vtkTree* temp = this->Tree; this->Tree = tree; if (this->Tree != NULL) { this->Tree->Register(this); } if (temp != NULL) { temp->UnRegister(this); } this->StartNode = -1; this->Initialize(); this->Modified(); } } void vtkTreeDFSIterator::SetStartNode(vtkIdType node) { if (this->StartNode != node) { this->StartNode = node; this->Initialize(); this->Modified(); } } void vtkTreeDFSIterator::SetMode(int mode) { if (this->Mode != mode) { this->Mode = mode; this->Initialize(); this->Modified(); } } vtkIdType vtkTreeDFSIterator::Next() { vtkIdType last = this->NextId; this->NextId = this->NextInternal(); return last; } vtkIdType vtkTreeDFSIterator::NextInternal() { while (this->Color->GetValue(this->StartNode) != this->BLACK) { while (this->Internals->Stack.size() > 0) { // Pop the current position off the stack vtkTreeDFSIteratorPosition pos = this->Internals->Stack.top(); this->Internals->Stack.pop(); //cout << "popped " << pos.Node << "," << pos.Index << " off the stack" << endl; vtkIdType nchildren; const vtkIdType* children; this->Tree->GetChildren(pos.Node, nchildren, children); while (pos.Index < nchildren && this->Color->GetValue(children[pos.Index]) != this->WHITE) { pos.Index++; } if (pos.Index == nchildren) { //cout << "DFS coloring " << pos.Node << " black" << endl; // Done with this node; make it black and leave it off the stack this->Color->SetValue(pos.Node, this->BLACK); if (this->Mode == this->FINISH) { //cout << "DFS finished " << pos.Node << endl; return pos.Node; } } else { // Not done with this node; put it back on the stack this->Internals->Stack.push(pos); // Found a white node; make it gray, add it to the stack vtkIdType found = children[pos.Index]; //cout << "DFS coloring " << found << " gray (adjacency)" << endl; this->Color->SetValue(found, this->GRAY); this->Internals->Stack.push(vtkTreeDFSIteratorPosition(found, 0)); if (this->Mode == this->DISCOVER) { //cout << "DFS adjacent discovery " << found << endl; return found; } } } // Done with this component, so find a white node and start a new search for (; this->CurRoot < this->Tree->GetNumberOfNodes(); this->CurRoot++) { if (this->Color->GetValue(this->CurRoot) == this->WHITE) { // Found a new component; make it gray, put it on the stack //cout << "DFS coloring " << this->CurRoot << " gray (new component)" << endl; this->Internals->Stack.push(vtkTreeDFSIteratorPosition(this->CurRoot, 0)); this->Color->SetValue(this->CurRoot, this->GRAY); if (this->Mode == this->DISCOVER) { //cout << "DFS new component discovery " << this->CurRoot << endl; return this->CurRoot; } break; } } } //cout << "DFS no more!" << endl; return -1; } bool vtkTreeDFSIterator::HasNext() { return this->NextId != -1; } <commit_msg>BUG: When starting at a node other than the root, need to stop traversal as soon as the start node is done (i.e. colored black).<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkTreeDFSIterator.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkTreeDFSIterator.h" #include "vtkTree.h" #include "vtkObjectFactory.h" #include "vtkIntArray.h" #include "vtkIdList.h" #include <vtkstd/stack> using vtkstd::stack; struct vtkTreeDFSIteratorPosition { vtkTreeDFSIteratorPosition(vtkIdType node, vtkIdType index) : Node(node), Index(index) { } vtkIdType Node; vtkIdType Index; // How far along we are in the node's edge array }; class vtkTreeDFSIteratorInternals { public: stack<vtkTreeDFSIteratorPosition> Stack; }; vtkCxxRevisionMacro(vtkTreeDFSIterator, "1.2"); vtkStandardNewMacro(vtkTreeDFSIterator); vtkTreeDFSIterator::vtkTreeDFSIterator() { this->Internals = new vtkTreeDFSIteratorInternals(); this->Tree = NULL; this->Color = vtkIntArray::New(); this->StartNode = -1; this->Mode = 0; } vtkTreeDFSIterator::~vtkTreeDFSIterator() { if (this->Internals) { delete this->Internals; this->Internals = NULL; } if (this->Tree) { this->Tree->Delete(); this->Tree = NULL; } if (this->Color) { this->Color->Delete(); this->Color = NULL; } } void vtkTreeDFSIterator::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } void vtkTreeDFSIterator::Initialize() { if (this->Tree == NULL) { return; } // Set all colors to white this->Color->Resize(this->Tree->GetNumberOfNodes()); for (vtkIdType i = 0; i < this->Tree->GetNumberOfNodes(); i++) { this->Color->SetValue(i, this->WHITE); } if (this->StartNode < 0) { this->StartNode = this->Tree->GetRoot(); } this->CurRoot = this->StartNode; while (this->Internals->Stack.size()) { this->Internals->Stack.pop(); } // Find the first item if (this->Tree->GetNumberOfNodes() > 0) { this->NextId = this->NextInternal(); } else { this->NextId = -1; } } void vtkTreeDFSIterator::SetTree(vtkTree* tree) { vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting Tree to " << tree ); if (this->Tree != tree) { vtkTree* temp = this->Tree; this->Tree = tree; if (this->Tree != NULL) { this->Tree->Register(this); } if (temp != NULL) { temp->UnRegister(this); } this->StartNode = -1; this->Initialize(); this->Modified(); } } void vtkTreeDFSIterator::SetStartNode(vtkIdType node) { if (this->StartNode != node) { this->StartNode = node; this->Initialize(); this->Modified(); } } void vtkTreeDFSIterator::SetMode(int mode) { if (this->Mode != mode) { this->Mode = mode; this->Initialize(); this->Modified(); } } vtkIdType vtkTreeDFSIterator::Next() { vtkIdType last = this->NextId; this->NextId = this->NextInternal(); return last; } vtkIdType vtkTreeDFSIterator::NextInternal() { while (this->Color->GetValue(this->StartNode) != this->BLACK) { while (this->Internals->Stack.size() > 0) { // Pop the current position off the stack vtkTreeDFSIteratorPosition pos = this->Internals->Stack.top(); this->Internals->Stack.pop(); //cout << "popped " << pos.Node << "," << pos.Index << " off the stack" << endl; vtkIdType nchildren; const vtkIdType* children; this->Tree->GetChildren(pos.Node, nchildren, children); while (pos.Index < nchildren && this->Color->GetValue(children[pos.Index]) != this->WHITE) { pos.Index++; } if (pos.Index == nchildren) { //cout << "DFS coloring " << pos.Node << " black" << endl; // Done with this node; make it black and leave it off the stack this->Color->SetValue(pos.Node, this->BLACK); if (this->Mode == this->FINISH) { //cout << "DFS finished " << pos.Node << endl; return pos.Node; } // Done with the start node, so we are totally done! if (pos.Node == this->StartNode) { return -1; } } else { // Not done with this node; put it back on the stack this->Internals->Stack.push(pos); // Found a white node; make it gray, add it to the stack vtkIdType found = children[pos.Index]; //cout << "DFS coloring " << found << " gray (adjacency)" << endl; this->Color->SetValue(found, this->GRAY); this->Internals->Stack.push(vtkTreeDFSIteratorPosition(found, 0)); if (this->Mode == this->DISCOVER) { //cout << "DFS adjacent discovery " << found << endl; return found; } } } // Done with this component, so find a white node and start a new search for (; this->CurRoot < this->Tree->GetNumberOfNodes(); this->CurRoot++) { if (this->Color->GetValue(this->CurRoot) == this->WHITE) { // Found a new component; make it gray, put it on the stack //cout << "DFS coloring " << this->CurRoot << " gray (new component)" << endl; this->Internals->Stack.push(vtkTreeDFSIteratorPosition(this->CurRoot, 0)); this->Color->SetValue(this->CurRoot, this->GRAY); if (this->Mode == this->DISCOVER) { //cout << "DFS new component discovery " << this->CurRoot << endl; return this->CurRoot; } break; } } } //cout << "DFS no more!" << endl; return -1; } bool vtkTreeDFSIterator::HasNext() { return this->NextId != -1; } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #include "Stroika/Frameworks/StroikaPreComp.h" #include <random> #include "Stroika/Foundation/Characters/String.h" #include "Stroika/Foundation/Common/Property.h" #include "Stroika/Foundation/Containers/Set.h" #include "Stroika/Foundation/Database/SQL/ORM/Schema.h" #include "Stroika/Foundation/Database/SQL/ORM/TableConnection.h" #include "Stroika/Foundation/Database/SQL/ORM/Versioning.h" #include "Stroika/Foundation/Debug/Trace.h" #include "Stroika/Foundation/Execution/Sleep.h" #include "Stroika/Foundation/Execution/Thread.h" #include "Stroika/Foundation/IO/FileSystem/WellKnownLocations.h" #include "ORMEmployeesDB.h" using namespace std; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Common; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Database; using namespace Stroika::Foundation::Debug; using namespace Stroika::Foundation::Execution; using namespace Database::SQL; using namespace SQL::ORM; namespace { struct Employee { optional<int> ID{}; String fName; int fAge{}; String fAddress; double fSalary{}; bool fStillEmployed{}; static const ConstantProperty<ObjectVariantMapper> kMapper; }; const ConstantProperty<ObjectVariantMapper> Employee::kMapper{[] () { ObjectVariantMapper mapper; mapper.AddCommonType<optional<int>> (); mapper.AddClass<Employee> (initializer_list<ObjectVariantMapper::StructFieldInfo>{ {L"id", StructFieldMetaInfo{&Employee::ID}}, {L"Name", StructFieldMetaInfo{&Employee::fName}}, {L"Age", StructFieldMetaInfo{&Employee::fAge}}, {L"Address", StructFieldMetaInfo{&Employee::fAddress}}, {L"Salary", StructFieldMetaInfo{&Employee::fSalary}}, {L"Still-Employed", StructFieldMetaInfo{&Employee::fStillEmployed}}, }); return mapper; }}; struct Paycheck { optional<int> ID{}; int fEmployeeRef; double fAmount{}; Time::Date fDate; static const ConstantProperty<ObjectVariantMapper> kMapper; }; const ConstantProperty<ObjectVariantMapper> Paycheck::kMapper{[] () { ObjectVariantMapper mapper; mapper.AddCommonType<optional<int>> (); mapper.AddClass<Paycheck> (initializer_list<ObjectVariantMapper::StructFieldInfo>{ {L"id", StructFieldMetaInfo{&Paycheck::ID}}, {L"Employee-Ref", StructFieldMetaInfo{&Paycheck::fEmployeeRef}}, {L"Amount", StructFieldMetaInfo{&Paycheck::fAmount}}, {L"Date", StructFieldMetaInfo{&Paycheck::fDate}}, }); return mapper; }}; /** * Combine all the ObjectVariantMappers for the objects we use in this database into one, and * AMEND any mappers as needed to accomodate possible changes in the mappings (like represeting * some things as strings vs. BLOBs etc). */ const ConstantProperty<ObjectVariantMapper> kDBObjectMapper_{[] () { ObjectVariantMapper mapper; mapper += Employee::kMapper; mapper += Paycheck::kMapper; return mapper; }}; /* * Define the schema, and how to map between the VariantValue objects and the database * for the EMPLOYEES table. */ const Schema::Table kEmployeesTableSchema_{ L"EMPLOYEES", /* * use the same names as the ObjectVariantMapper for simpler mapping, or specify an alternate name * for ID, just as an example. */ // clang-format off Collection<Schema::Field>{ #if __cpp_designated_initializers {.fName = L"ID", .fVariantValueName = L"id"sv, .fRequired = true, .fVariantValueType = VariantValue::eInteger, .fIsKeyField = true, .fDefaultExpression = Schema::Field::kDefaultExpression_AutoIncrement} , {.fName = L"NAME", .fVariantValueName = L"Name"sv, .fVariantValueType = VariantValue::eString} , {.fName = L"AGE", .fVariantValueName = L"Age"sv, .fVariantValueType = VariantValue::eInteger} , {.fName = L"ADDRESS", .fVariantValueName = L"Address"sv, .fVariantValueType = VariantValue::eString} , {.fName = L"SALARY", .fVariantValueName = L"Salary"sv, .fVariantValueType = VariantValue::eFloat} , {.fName = L"STILL_EMPLOYED", .fVariantValueName = L"Still-Employed"sv, .fVariantValueType = VariantValue::eInteger} #else {L"ID", L"id"sv, true, VariantValue::eInteger, nullopt, true, nullopt, Schema::Field::kDefaultExpression_AutoIncrement} , {L"name", L"Name"sv, false, VariantValue::eString} , {L"AGE", L"Age"sv, false, VariantValue::eInteger} , {L"ADDRESS", L"Address"sv, false, VariantValue::eString} , {L"SALARY", L"Salary"sv, false, VariantValue::eFloat} , {L"STILL_EMPLOYED", L"Still-Employed"sv, false, VariantValue::eInteger} #endif }, Schema::CatchAllField{}}; /* * Define the schema, and how to map between the VariantValue objects and the database * for the PAYCHECKS table. */ const Schema::Table kPaychecksTableSchema_{ L"PAYCHECKS", Collection<Schema::Field>{ #if __cpp_designated_initializers {.fName = L"ID", .fVariantValueName = L"id"sv, .fRequired = true, .fVariantValueType = VariantValue::eInteger, .fIsKeyField = true, .fDefaultExpression = Schema::Field::kDefaultExpression_AutoIncrement} , {.fName = L"EMPLOYEEREF", .fVariantValueName = L"Employee-Ref"sv, .fRequired = true, .fVariantValueType = VariantValue::eInteger} , {.fName = L"AMOUNT", .fVariantValueName = L"Amount"sv, .fVariantValueType = VariantValue::eFloat} , {.fName = L"DATE", .fVariantValueName = L"Date"sv, .fVariantValueType = VariantValue::eDate} #else {L"ID", L"id"sv, true, VariantValue::eInteger, nullopt, true, nullopt, Schema::Field::kDefaultExpression_AutoIncrement} , {L"EMPLOYEEREF", L"Employee-Ref"sv, true, VariantValue::eInteger, nullopt, false, nullopt, nullopt} , {L"AMOUNT", L"Amount"sv, false, VariantValue::eFloat} , {L"DATE", L"Date"sv, false, VariantValue::eDate} #endif }}; // clang-format on /* * Example thread making updates to the employees table. */ void PeriodicallyUpdateEmployeesTable_ (Connection::Ptr conn) { TraceContextBumper ctx{"{}::PeriodicallyUpdateEmployeesTable_"}; auto employeeTableConnection = make_unique<SQL::ORM::TableConnection<Employee>> (conn, kEmployeesTableSchema_, kDBObjectMapper_); // Add Initial Employees // @todo use __cpp_designated_initializers when we can assume it employeeTableConnection->AddNew (Employee{nullopt, L"Paul", 32, L"California", 20000.00, true}); employeeTableConnection->AddNew (Employee{nullopt, L"Allen", 25, L"Texas", 15000.00, true}); employeeTableConnection->AddNew (Employee{nullopt, L"Teddy", 23, L"Norway", 20000.00, true}); employeeTableConnection->AddNew (Employee{nullopt, L"Mark", 25, L"Rich-Mond", 65000.00, true}); employeeTableConnection->AddNew (Employee{nullopt, L"David", 27, L"Texas", 85000.00, true}); employeeTableConnection->AddNew (Employee{nullopt, L"Kim", 22, L"South-Hall", 45000.00, true}); employeeTableConnection->AddNew (Employee{nullopt, L"James", 24, L"Houston", 10000.00, true}); default_random_engine generator; uniform_int_distribution<int> distribution{1, 6}; // then keep adding/removing people randomly (but dont really remove just mark no longer employed so we // can REF in paycheck table while (true) { static const Sequence<String> kNames_{L"Joe", L"Phred", L"Barny", L"Sue", L"Anne"}; uniform_int_distribution<int> namesDistr{0, static_cast<int> (kNames_.size () - 1)}; uniform_int_distribution<int> ageDistr{25, 50}; static const Sequence<String> kAddresses{L"Houston", L"Pittsburg", L"New York", L"Paris", L"California"}; uniform_int_distribution<int> addressesDistr{0, static_cast<int> (kAddresses.size () - 1)}; uniform_real_distribution<float> salaryDistr{10000.00, 50000.00}; try { uniform_int_distribution<int> whatTodoDistr{0, 3}; switch (whatTodoDistr (generator)) { case 0: case 1: { String name = kNames_[namesDistr (generator)]; DbgTrace (L"Adding employee %s", name.c_str ()); employeeTableConnection->AddNew (Employee{nullopt, name, ageDistr (generator), kAddresses[addressesDistr (generator)], salaryDistr (generator), true}); } break; case 2: { // Look somebody up, and fire them auto activeEmps = employeeTableConnection->GetAll (); if (not activeEmps.empty ()) { uniform_int_distribution<int> empDistr{0, static_cast<int> (activeEmps.size () - 1)}; Employee killMe = activeEmps[empDistr (generator)]; Assert (killMe.ID.has_value ()); DbgTrace (L"Firing employee: %d, %s", *killMe.ID, killMe.fName.c_str ()); killMe.fStillEmployed = false; employeeTableConnection->Update (killMe); } } break; } } catch (...) { // no need to check for ThreadAbort excepton, since Sleep is a cancelation point DbgTrace (L"Exception processing SQL - this should generally not happen: %s", Characters::ToString (current_exception ()).c_str ()); } Sleep (1s); // **cancelation point** } } /* * Example thread making updates to the paychecks table (while consulting the employees table). */ void PeriodicallyWriteChecksForEmployeesTable_ (Connection::Ptr conn) { TraceContextBumper ctx{"{}::PeriodicallyWriteChecksForEmployeesTable_"}; auto employeeTableConnection = make_unique<SQL::ORM::TableConnection<Employee>> (conn, kEmployeesTableSchema_, kDBObjectMapper_); auto paycheckTableConnection = make_unique<SQL::ORM::TableConnection<Paycheck>> (conn, kPaychecksTableSchema_, kDBObjectMapper_); while (true) { try { for (auto employee : employeeTableConnection->GetAll ()) { Assert (employee.ID != nullopt); DbgTrace (L"Writing paycheck for employee #%d (%s) amount %f", *employee.ID, employee.fName.c_str (), employee.fSalary); paycheckTableConnection->AddNew (Paycheck{nullopt, *employee.ID, employee.fSalary / 12, DateTime::Now ().GetDate ()}); } } catch (...) { // no need to check for ThreadAbort excepton, since Sleep is a cancelation point DbgTrace (L"Exception processing SQL - this should generally not happen: %s", Characters::ToString (current_exception ()).c_str ()); } Sleep (2s); // **cancelation point** } } } void Stroika::Samples::SQL::ORMEmployeesDB (const std::function<Connection::Ptr ()>& connectionFactory) { TraceContextBumper ctx{"ORMEmployeesDB"}; Connection::Ptr conn1 = connectionFactory (); Connection::Ptr conn2 = connectionFactory (); // setup DB schema (on either connection) before running access threads constexpr Configuration::Version kCurrentVersion_ = Configuration::Version{1, 0, Configuration::VersionStage::Alpha, 0}; ORM::ProvisionForVersion (conn1, kCurrentVersion_, Traversal::Iterable<ORM::Schema::Table>{kEmployeesTableSchema_, kPaychecksTableSchema_}); /* * Create threads for each of our activities. * When the waitable even times out, the threads will automatically be 'canceled' as they go out of scope. */ Thread::CleanupPtr updateEmpDBThread{Thread::CleanupPtr::eAbortBeforeWaiting, Thread::New ([=] () { PeriodicallyUpdateEmployeesTable_ (conn1); }, Thread::eAutoStart, L"Update Employee Table")}; Thread::CleanupPtr writeChecks{Thread::CleanupPtr::eAbortBeforeWaiting, Thread::New ([=] () { PeriodicallyWriteChecksForEmployeesTable_ (conn2); }, Thread::eAutoStart, L"Write Checks")}; Execution::WaitableEvent{}.WaitQuietly (15s); } <commit_msg>samples/docs<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #include "Stroika/Frameworks/StroikaPreComp.h" #include <random> #include "Stroika/Foundation/Characters/String.h" #include "Stroika/Foundation/Common/Property.h" #include "Stroika/Foundation/Containers/Set.h" #include "Stroika/Foundation/Database/SQL/ORM/Schema.h" #include "Stroika/Foundation/Database/SQL/ORM/TableConnection.h" #include "Stroika/Foundation/Database/SQL/ORM/Versioning.h" #include "Stroika/Foundation/Debug/Trace.h" #include "Stroika/Foundation/Execution/Sleep.h" #include "Stroika/Foundation/Execution/Thread.h" #include "Stroika/Foundation/IO/FileSystem/WellKnownLocations.h" #include "ORMEmployeesDB.h" using namespace std; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Common; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Database; using namespace Stroika::Foundation::Debug; using namespace Stroika::Foundation::Execution; using namespace Database::SQL; using namespace SQL::ORM; namespace { struct Employee { optional<int> ID{}; String fName; int fAge{}; String fAddress; double fSalary{}; bool fStillEmployed{}; static const ConstantProperty<ObjectVariantMapper> kMapper; }; /* * Define mapping to VariantValues (think JSON) */ const ConstantProperty<ObjectVariantMapper> Employee::kMapper{[] () { ObjectVariantMapper mapper; mapper.AddCommonType<optional<int>> (); mapper.AddClass<Employee> (initializer_list<ObjectVariantMapper::StructFieldInfo>{ {L"id", StructFieldMetaInfo{&Employee::ID}}, {L"Name", StructFieldMetaInfo{&Employee::fName}}, {L"Age", StructFieldMetaInfo{&Employee::fAge}}, {L"Address", StructFieldMetaInfo{&Employee::fAddress}}, {L"Salary", StructFieldMetaInfo{&Employee::fSalary}}, {L"Still-Employed", StructFieldMetaInfo{&Employee::fStillEmployed}}, }); return mapper; }}; struct Paycheck { optional<int> ID{}; int fEmployeeRef; double fAmount{}; Time::Date fDate; static const ConstantProperty<ObjectVariantMapper> kMapper; }; /* * Define mapping to VariantValues (think JSON) */ const ConstantProperty<ObjectVariantMapper> Paycheck::kMapper{[] () { ObjectVariantMapper mapper; mapper.AddCommonType<optional<int>> (); mapper.AddClass<Paycheck> (initializer_list<ObjectVariantMapper::StructFieldInfo>{ {L"id", StructFieldMetaInfo{&Paycheck::ID}}, {L"Employee-Ref", StructFieldMetaInfo{&Paycheck::fEmployeeRef}}, {L"Amount", StructFieldMetaInfo{&Paycheck::fAmount}}, {L"Date", StructFieldMetaInfo{&Paycheck::fDate}}, }); return mapper; }}; /** * Combine all the ObjectVariantMappers for the objects we use in this database into one, and * AMEND any mappers as needed to accomodate possible changes in the mappings (like represeting * some things as strings vs. BLOBs etc). */ const ConstantProperty<ObjectVariantMapper> kDBObjectMapper_{[] () { ObjectVariantMapper mapper; mapper += Employee::kMapper; mapper += Paycheck::kMapper; return mapper; }}; /* * Define the schema, and how to map between the VariantValue objects and the database * for the EMPLOYEES table. */ const Schema::Table kEmployeesTableSchema_{ L"EMPLOYEES", /* * use the same names as the ObjectVariantMapper for simpler mapping, or specify an alternate name * for ID, just as an example. */ // clang-format off Collection<Schema::Field>{ #if __cpp_designated_initializers {.fName = L"ID", .fVariantValueName = L"id"sv, .fRequired = true, .fVariantValueType = VariantValue::eInteger, .fIsKeyField = true, .fDefaultExpression = Schema::Field::kDefaultExpression_AutoIncrement} , {.fName = L"NAME", .fVariantValueName = L"Name"sv, .fVariantValueType = VariantValue::eString} , {.fName = L"AGE", .fVariantValueName = L"Age"sv, .fVariantValueType = VariantValue::eInteger} , {.fName = L"ADDRESS", .fVariantValueName = L"Address"sv, .fVariantValueType = VariantValue::eString} , {.fName = L"SALARY", .fVariantValueName = L"Salary"sv, .fVariantValueType = VariantValue::eFloat} , {.fName = L"STILL_EMPLOYED", .fVariantValueName = L"Still-Employed"sv, .fVariantValueType = VariantValue::eInteger} #else {L"ID", L"id"sv, true, VariantValue::eInteger, nullopt, true, nullopt, Schema::Field::kDefaultExpression_AutoIncrement} , {L"name", L"Name"sv, false, VariantValue::eString} , {L"AGE", L"Age"sv, false, VariantValue::eInteger} , {L"ADDRESS", L"Address"sv, false, VariantValue::eString} , {L"SALARY", L"Salary"sv, false, VariantValue::eFloat} , {L"STILL_EMPLOYED", L"Still-Employed"sv, false, VariantValue::eInteger} #endif }, Schema::CatchAllField{}}; /* * Define the schema, and how to map between the VariantValue objects and the database * for the PAYCHECKS table. */ const Schema::Table kPaychecksTableSchema_{ L"PAYCHECKS", Collection<Schema::Field>{ #if __cpp_designated_initializers {.fName = L"ID", .fVariantValueName = L"id"sv, .fRequired = true, .fVariantValueType = VariantValue::eInteger, .fIsKeyField = true, .fDefaultExpression = Schema::Field::kDefaultExpression_AutoIncrement} , {.fName = L"EMPLOYEEREF", .fVariantValueName = L"Employee-Ref"sv, .fRequired = true, .fVariantValueType = VariantValue::eInteger} , {.fName = L"AMOUNT", .fVariantValueName = L"Amount"sv, .fVariantValueType = VariantValue::eFloat} , {.fName = L"DATE", .fVariantValueName = L"Date"sv, .fVariantValueType = VariantValue::eDate} #else {L"ID", L"id"sv, true, VariantValue::eInteger, nullopt, true, nullopt, Schema::Field::kDefaultExpression_AutoIncrement} , {L"EMPLOYEEREF", L"Employee-Ref"sv, true, VariantValue::eInteger, nullopt, false, nullopt, nullopt} , {L"AMOUNT", L"Amount"sv, false, VariantValue::eFloat} , {L"DATE", L"Date"sv, false, VariantValue::eDate} #endif }}; // clang-format on /* * Example thread making updates to the employees table. */ void PeriodicallyUpdateEmployeesTable_ (Connection::Ptr conn) { TraceContextBumper ctx{"{}::PeriodicallyUpdateEmployeesTable_"}; auto employeeTableConnection = make_unique<SQL::ORM::TableConnection<Employee>> (conn, kEmployeesTableSchema_, kDBObjectMapper_); // Add Initial Employees // @todo use __cpp_designated_initializers when we can assume it employeeTableConnection->AddNew (Employee{nullopt, L"Paul", 32, L"California", 20000.00, true}); employeeTableConnection->AddNew (Employee{nullopt, L"Allen", 25, L"Texas", 15000.00, true}); employeeTableConnection->AddNew (Employee{nullopt, L"Teddy", 23, L"Norway", 20000.00, true}); employeeTableConnection->AddNew (Employee{nullopt, L"Mark", 25, L"Rich-Mond", 65000.00, true}); employeeTableConnection->AddNew (Employee{nullopt, L"David", 27, L"Texas", 85000.00, true}); employeeTableConnection->AddNew (Employee{nullopt, L"Kim", 22, L"South-Hall", 45000.00, true}); employeeTableConnection->AddNew (Employee{nullopt, L"James", 24, L"Houston", 10000.00, true}); default_random_engine generator; uniform_int_distribution<int> distribution{1, 6}; // then keep adding/removing people randomly (but dont really remove just mark no longer employed so we // can REF in paycheck table while (true) { static const Sequence<String> kNames_{L"Joe", L"Phred", L"Barny", L"Sue", L"Anne"}; uniform_int_distribution<int> namesDistr{0, static_cast<int> (kNames_.size () - 1)}; uniform_int_distribution<int> ageDistr{25, 50}; static const Sequence<String> kAddresses{L"Houston", L"Pittsburg", L"New York", L"Paris", L"California"}; uniform_int_distribution<int> addressesDistr{0, static_cast<int> (kAddresses.size () - 1)}; uniform_real_distribution<float> salaryDistr{10000.00, 50000.00}; try { uniform_int_distribution<int> whatTodoDistr{0, 3}; switch (whatTodoDistr (generator)) { case 0: case 1: { String name = kNames_[namesDistr (generator)]; DbgTrace (L"Adding employee %s", name.c_str ()); employeeTableConnection->AddNew (Employee{nullopt, name, ageDistr (generator), kAddresses[addressesDistr (generator)], salaryDistr (generator), true}); } break; case 2: { // Look somebody up, and fire them auto activeEmps = employeeTableConnection->GetAll (); if (not activeEmps.empty ()) { uniform_int_distribution<int> empDistr{0, static_cast<int> (activeEmps.size () - 1)}; Employee killMe = activeEmps[empDistr (generator)]; Assert (killMe.ID.has_value ()); DbgTrace (L"Firing employee: %d, %s", *killMe.ID, killMe.fName.c_str ()); killMe.fStillEmployed = false; employeeTableConnection->Update (killMe); } } break; } } catch (...) { // no need to check for ThreadAbort excepton, since Sleep is a cancelation point DbgTrace (L"Exception processing SQL - this should generally not happen: %s", Characters::ToString (current_exception ()).c_str ()); } Sleep (1s); // **cancelation point** } } /* * Example thread making updates to the paychecks table (while consulting the employees table). */ void PeriodicallyWriteChecksForEmployeesTable_ (Connection::Ptr conn) { TraceContextBumper ctx{"{}::PeriodicallyWriteChecksForEmployeesTable_"}; auto employeeTableConnection = make_unique<SQL::ORM::TableConnection<Employee>> (conn, kEmployeesTableSchema_, kDBObjectMapper_); auto paycheckTableConnection = make_unique<SQL::ORM::TableConnection<Paycheck>> (conn, kPaychecksTableSchema_, kDBObjectMapper_); while (true) { try { for (auto employee : employeeTableConnection->GetAll ()) { Assert (employee.ID != nullopt); DbgTrace (L"Writing paycheck for employee #%d (%s) amount %f", *employee.ID, employee.fName.c_str (), employee.fSalary); paycheckTableConnection->AddNew (Paycheck{nullopt, *employee.ID, employee.fSalary / 12, DateTime::Now ().GetDate ()}); } } catch (...) { // no need to check for ThreadAbort excepton, since Sleep is a cancelation point DbgTrace (L"Exception processing SQL - this should generally not happen: %s", Characters::ToString (current_exception ()).c_str ()); } Sleep (2s); // **cancelation point** } } } void Stroika::Samples::SQL::ORMEmployeesDB (const std::function<Connection::Ptr ()>& connectionFactory) { TraceContextBumper ctx{"ORMEmployeesDB"}; Connection::Ptr conn1 = connectionFactory (); Connection::Ptr conn2 = connectionFactory (); // setup DB schema (on either connection) before running access threads constexpr Configuration::Version kCurrentVersion_ = Configuration::Version{1, 0, Configuration::VersionStage::Alpha, 0}; ORM::ProvisionForVersion (conn1, kCurrentVersion_, Traversal::Iterable<ORM::Schema::Table>{kEmployeesTableSchema_, kPaychecksTableSchema_}); /* * Create threads for each of our activities. * When the waitable even times out, the threads will automatically be 'canceled' as they go out of scope. */ Thread::CleanupPtr updateEmpDBThread{Thread::CleanupPtr::eAbortBeforeWaiting, Thread::New ([=] () { PeriodicallyUpdateEmployeesTable_ (conn1); }, Thread::eAutoStart, L"Update Employee Table")}; Thread::CleanupPtr writeChecks{Thread::CleanupPtr::eAbortBeforeWaiting, Thread::New ([=] () { PeriodicallyWriteChecksForEmployeesTable_ (conn2); }, Thread::eAutoStart, L"Write Checks")}; Execution::WaitableEvent{}.WaitQuietly (15s); } <|endoftext|>
<commit_before>/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ //--------------------------------------------------------------------------- // Pre-compilation #include "MediaInfo/PreComp.h" #ifdef __BORLANDC__ #pragma hdrstop #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Setup.h" //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #if defined(MEDIAINFO_PRORES_YES) //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Video/File_ProRes.h" //--------------------------------------------------------------------------- namespace MediaInfoLib { //*************************************************************************** // Infos //*************************************************************************** //--------------------------------------------------------------------------- const char* Mpegv_colour_primaries(int8u colour_primaries); const char* Mpegv_transfer_characteristics(int8u transfer_characteristics); const char* Mpegv_matrix_coefficients(int8u matrix_coefficients); //--------------------------------------------------------------------------- const char* ProRes_chrominance_factor(int8u chrominance_factor) { switch (chrominance_factor) { case 0x02 : return "4:2:2"; case 0x03 : return "4:4:4"; default : return ""; } } //--------------------------------------------------------------------------- const char* ProRes_frame_type_ScanType(int8u frame_type) { switch (frame_type) { case 0x00 : return "Progressive"; case 0x01 : case 0x02 : return "Interlaced"; default : return ""; } } //--------------------------------------------------------------------------- const char* ProRes_frame_type_ScanOrder(int8u frame_type) { switch (frame_type) { case 0x01 : return "TFF"; case 0x02 : return "BFF"; default : return ""; } } //--------------------------------------------------------------------------- Ztring ProRes_creatorID(int32u creatorID) { switch (creatorID) { case 0x61706C30 : return __T("Apple"); //apl0 case 0x61727269 : return __T("Arnold & Richter Cine Technik"); //arri case 0x616A6130 : return __T("AJA Kona Hardware"); //aja0 default : return Ztring().From_CC4(creatorID); } } //*************************************************************************** // Constructor/Destructor //*************************************************************************** //--------------------------------------------------------------------------- File_ProRes::File_ProRes() :File__Analyze() { //Configuration ParserName=__T("ProRes"); } //*************************************************************************** // Streams management //*************************************************************************** //--------------------------------------------------------------------------- void File_ProRes::Streams_Fill() { Stream_Prepare(Stream_Video); Fill(Stream_Video, 0, Video_Format, "ProRes"); } //*************************************************************************** // Buffer - Global //*************************************************************************** //--------------------------------------------------------------------------- void File_ProRes::Read_Buffer_Continue() { //Parsing int32u Name, creatorID; int16u hdrSize, version, frameWidth, frameHeight; int8u chrominance_factor, frame_type, primaries, transf_func, colorMatrix; bool IsOk=true, luma, chroma; Element_Begin1("Header"); Skip_B4( "Size"); Get_C4 (Name, "Name"); Element_End(); Element_Begin1("Frame header"); Get_B2 (hdrSize, "hdrSize"); Get_B2 (version, "version"); Get_C4 (creatorID, "creatorID"); Get_B2 (frameWidth, "frameWidth"); Get_B2 (frameHeight, "frameHeight"); BS_Begin(); Get_S1 (2, chrominance_factor, "chrominance factor"); Param_Info1(ProRes_chrominance_factor(chrominance_factor)); Skip_S1(2, "reserved"); Get_S1 (2, frame_type, "frame type"); Param_Info1(ProRes_frame_type_ScanType(frame_type)); Param_Info1(ProRes_frame_type_ScanOrder(frame_type)); Skip_S1(2, "reserved"); BS_End(); Skip_B1( "reserved"); Get_B1 (primaries, "primaries"); Param_Info1(Mpegv_colour_primaries(primaries)); Get_B1 (transf_func, "transf_func"); Param_Info1(Mpegv_transfer_characteristics(transf_func)); Get_B1 (colorMatrix, "colorMatrix"); Param_Info1(Mpegv_matrix_coefficients(colorMatrix)); BS_Begin(); Skip_S1(4, "src_pix_fmt"); Skip_S1(4, "alpha_info"); BS_End(); Skip_B1( "reserved"); BS_Begin(); Skip_S1(6, "reserved"); Get_SB (luma, "custom luma quant matrix present"); Get_SB (chroma, "custom chroma quant matrix present"); BS_End(); if (luma) Skip_XX(64, "QMatLuma"); if (chroma) Skip_XX(64, "QMatChroma"); Element_End(); if (Element_Offset!=8+hdrSize) IsOk=false; Skip_XX(Element_Size-Element_Offset, "Picture layout"); FILLING_BEGIN(); if (IsOk && Name==0x69637066 && !Status[IsAccepted]) //icpf { Accept(); Fill(); Fill(Stream_Video, 0, Video_Format_Version, __T("Version ")+Ztring::ToZtring(version)); Fill(Stream_Video, 0, Video_Width, frameWidth); Fill(Stream_Video, 0, Video_Height, frameHeight); Fill(Stream_Video, 0, Video_Encoded_Library, ProRes_creatorID(creatorID)); Fill(Stream_Video, 0, Video_ChromaSubsampling, ProRes_chrominance_factor(chrominance_factor)); Fill(Stream_Video, 0, Video_ScanType, ProRes_frame_type_ScanType(frame_type)); Fill(Stream_Video, 0, Video_ScanOrder, ProRes_frame_type_ScanOrder(frame_type)); Fill(Stream_Video, 0, "colour_primaries", Mpegv_colour_primaries(primaries)); Fill(Stream_Video, 0, "transfer_characteristics", Mpegv_transfer_characteristics(transf_func)); Fill(Stream_Video, 0, "matrix_coefficients", Mpegv_matrix_coefficients(colorMatrix)); Finish(); } FILLING_END(); } //*************************************************************************** // C++ //*************************************************************************** } //NameSpace #endif //MEDIAINFO_PRORES_YES <commit_msg>+ ProRes, slice parsing implementation<commit_after>/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ //--------------------------------------------------------------------------- // Pre-compilation #include "MediaInfo/PreComp.h" #ifdef __BORLANDC__ #pragma hdrstop #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Setup.h" //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #if defined(MEDIAINFO_PRORES_YES) //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Video/File_ProRes.h" //--------------------------------------------------------------------------- namespace MediaInfoLib { //*************************************************************************** // Infos //*************************************************************************** //--------------------------------------------------------------------------- const char* Mpegv_colour_primaries(int8u colour_primaries); const char* Mpegv_transfer_characteristics(int8u transfer_characteristics); const char* Mpegv_matrix_coefficients(int8u matrix_coefficients); //--------------------------------------------------------------------------- const char* ProRes_chrominance_factor(int8u chrominance_factor) { switch (chrominance_factor) { case 0x02 : return "4:2:2"; case 0x03 : return "4:4:4"; default : return ""; } } //--------------------------------------------------------------------------- const char* ProRes_frame_type_ScanType(int8u frame_type) { switch (frame_type) { case 0x00 : return "Progressive"; case 0x01 : case 0x02 : return "Interlaced"; default : return ""; } } //--------------------------------------------------------------------------- const char* ProRes_frame_type_ScanOrder(int8u frame_type) { switch (frame_type) { case 0x01 : return "TFF"; case 0x02 : return "BFF"; default : return ""; } } //--------------------------------------------------------------------------- Ztring ProRes_creatorID(int32u creatorID) { switch (creatorID) { case 0x61706C30 : return __T("Apple"); //apl0 case 0x61727269 : return __T("Arnold & Richter Cine Technik"); //arri case 0x616A6130 : return __T("AJA Kona Hardware"); //aja0 default : return Ztring().From_CC4(creatorID); } } //*************************************************************************** // Constructor/Destructor //*************************************************************************** //--------------------------------------------------------------------------- File_ProRes::File_ProRes() :File__Analyze() { //Configuration ParserName=__T("ProRes"); } //*************************************************************************** // Streams management //*************************************************************************** //--------------------------------------------------------------------------- void File_ProRes::Streams_Fill() { Stream_Prepare(Stream_Video); Fill(Stream_Video, 0, Video_Format, "ProRes"); } //*************************************************************************** // Buffer - Global //*************************************************************************** //--------------------------------------------------------------------------- void File_ProRes::Read_Buffer_Continue() { //Parsing int32u Name, creatorID; int16u hdrSize, version, frameWidth, frameHeight; int8u chrominance_factor, frame_type, primaries, transf_func, colorMatrix; bool IsOk=true, luma, chroma; Element_Begin1("Header"); Skip_B4( "Size"); Get_C4 (Name, "Name"); Element_End(); Element_Begin1("Frame header"); Get_B2 (hdrSize, "hdrSize"); Get_B2 (version, "version"); Get_C4 (creatorID, "creatorID"); Get_B2 (frameWidth, "frameWidth"); Get_B2 (frameHeight, "frameHeight"); BS_Begin(); Get_S1 (2, chrominance_factor, "chrominance factor"); Param_Info1(ProRes_chrominance_factor(chrominance_factor)); Skip_S1(2, "reserved"); Get_S1 (2, frame_type, "frame type"); Param_Info1(ProRes_frame_type_ScanType(frame_type)); Param_Info1(ProRes_frame_type_ScanOrder(frame_type)); Skip_S1(2, "reserved"); BS_End(); Skip_B1( "reserved"); Get_B1 (primaries, "primaries"); Param_Info1(Mpegv_colour_primaries(primaries)); Get_B1 (transf_func, "transf_func"); Param_Info1(Mpegv_transfer_characteristics(transf_func)); Get_B1 (colorMatrix, "colorMatrix"); Param_Info1(Mpegv_matrix_coefficients(colorMatrix)); BS_Begin(); Skip_S1(4, "src_pix_fmt"); Skip_S1(4, "alpha_info"); BS_End(); Skip_B1( "reserved"); BS_Begin(); Skip_S1(6, "reserved"); Get_SB (luma, "custom luma quant matrix present"); Get_SB (chroma, "custom chroma quant matrix present"); BS_End(); if (luma) Skip_XX(64, "QMatLuma"); if (chroma) Skip_XX(64, "QMatChroma"); Element_End(); if (Element_Offset!=8+hdrSize) IsOk=false; for (int8u PictureNumber=0; PictureNumber<(frame_type?2:1); PictureNumber++) { Element_Begin1("Picture layout"); int16u total_slices; vector<int16u> slices_size; Element_Begin1("Picture header"); int64u pic_hdr_End; int32u pic_data_size; int8u pic_hdr_size; Get_B1 (pic_hdr_size, "pic_hdr_size"); if (pic_hdr_size<64) { Trusted_IsNot("pic_hdr_size"); Element_End(); Element_End(); return; } pic_hdr_End=Element_Offset+pic_hdr_size/8-((pic_hdr_size%8)?0:1); Get_B4 (pic_data_size, "pic_data_size"); if (pic_data_size<8) { Trusted_IsNot("pic_data_size"); Element_End(); Element_End(); return; } Get_B2 (total_slices, "total_slices"); BS_Begin(); Skip_S1(4, "slice_width_factor"); Skip_S1(4, "slice_height_factor"); BS_End(); if (Element_Offset<pic_hdr_End) Skip_XX(pic_hdr_End-Element_Offset, "Unknown"); Element_End(); Element_Begin1("Slice index table"); for (int16u Pos=0; Pos<total_slices; Pos++) { int16u slice_size; Get_B2 (slice_size, "slice_size"); slices_size.push_back(slice_size); } Element_End(); for (int16u Pos=0; Pos<slices_size.size(); Pos++) { Skip_XX(slices_size[Pos], "slice data"); } Element_End(); } bool IsZeroes=true; for (size_t Pos=(size_t)Element_Offset; Pos<(size_t)Element_Size; Pos++) if (Buffer[Buffer_Offset+Pos]) { IsZeroes=false; break; } Skip_XX(Element_Size-Element_Offset, IsZeroes?"Zeroes":"Unknown"); FILLING_BEGIN(); if (IsOk && Name==0x69637066 && !Status[IsAccepted]) //icpf { Accept(); Fill(); Fill(Stream_Video, 0, Video_Format_Version, __T("Version ")+Ztring::ToZtring(version)); Fill(Stream_Video, 0, Video_Width, frameWidth); Fill(Stream_Video, 0, Video_Height, frameHeight); Fill(Stream_Video, 0, Video_Encoded_Library, ProRes_creatorID(creatorID)); Fill(Stream_Video, 0, Video_ChromaSubsampling, ProRes_chrominance_factor(chrominance_factor)); Fill(Stream_Video, 0, Video_ScanType, ProRes_frame_type_ScanType(frame_type)); Fill(Stream_Video, 0, Video_ScanOrder, ProRes_frame_type_ScanOrder(frame_type)); Fill(Stream_Video, 0, "colour_primaries", Mpegv_colour_primaries(primaries)); Fill(Stream_Video, 0, "transfer_characteristics", Mpegv_transfer_characteristics(transf_func)); Fill(Stream_Video, 0, "matrix_coefficients", Mpegv_matrix_coefficients(colorMatrix)); Finish(); } FILLING_END(); } //*************************************************************************** // C++ //*************************************************************************** } //NameSpace #endif //MEDIAINFO_PRORES_YES <|endoftext|>
<commit_before>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr> * * This program 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 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #include "AlbumTrack.h" #include "Album.h" #include "Artist.h" #include "Media.h" #include "Genre.h" #include "database/SqliteTools.h" #include "database/SqliteQuery.h" #include "logging/Logger.h" namespace medialibrary { const std::string policy::AlbumTrackTable::Name = "AlbumTrack"; const std::string policy::AlbumTrackTable::PrimaryKeyColumn = "id_track"; int64_t AlbumTrack::* const policy::AlbumTrackTable::PrimaryKey = &AlbumTrack::m_id; AlbumTrack::AlbumTrack( MediaLibraryPtr ml, sqlite::Row& row ) : m_ml( ml ) { int64_t dummyDuration; row >> m_id >> m_mediaId >> dummyDuration >> m_artistId >> m_genreId >> m_trackNumber >> m_albumId >> m_discNumber >> m_isPresent; } AlbumTrack::AlbumTrack( MediaLibraryPtr ml, int64_t mediaId, int64_t artistId, int64_t genreId, unsigned int trackNumber, int64_t albumId, unsigned int discNumber ) : m_ml( ml ) , m_id( 0 ) , m_mediaId( mediaId ) , m_artistId( artistId ) , m_genreId( genreId ) , m_trackNumber( trackNumber ) , m_albumId( albumId ) , m_discNumber( discNumber ) , m_isPresent( true ) { } int64_t AlbumTrack::id() const { return m_id; } ArtistPtr AlbumTrack::artist() const { if ( m_artistId == 0 ) return nullptr; auto lock = m_artist.lock(); if ( m_artist.isCached() == false ) { m_artist = Artist::fetch( m_ml, m_artistId ); } return m_artist.get(); } int64_t AlbumTrack::artistId() const { return m_artistId; } void AlbumTrack::createTable( sqlite::Connection* dbConnection ) { const std::string req = "CREATE TABLE IF NOT EXISTS " + policy::AlbumTrackTable::Name + "(" "id_track INTEGER PRIMARY KEY AUTOINCREMENT," "media_id INTEGER UNIQUE," "duration INTEGER NOT NULL," "artist_id UNSIGNED INTEGER," "genre_id INTEGER," "track_number UNSIGNED INTEGER," "album_id UNSIGNED INTEGER NOT NULL," "disc_number UNSIGNED INTEGER," "is_present BOOLEAN NOT NULL DEFAULT 1," "FOREIGN KEY (media_id) REFERENCES " + policy::MediaTable::Name + "(id_media)" " ON DELETE CASCADE," "FOREIGN KEY (artist_id) REFERENCES " + policy::ArtistTable::Name + "(id_artist)" " ON DELETE CASCADE," "FOREIGN KEY (genre_id) REFERENCES " + policy::GenreTable::Name + "(id_genre)," "FOREIGN KEY (album_id) REFERENCES Album(id_album) " " ON DELETE CASCADE" ")"; sqlite::Tools::executeRequest( dbConnection, req ); } void AlbumTrack::createTriggers(sqlite::Connection* dbConnection) { const std::string triggerReq = "CREATE TRIGGER IF NOT EXISTS is_track_present " "AFTER UPDATE OF is_present " "ON " + policy::MediaTable::Name + " " "BEGIN " "UPDATE " + policy::AlbumTrackTable::Name + " " "SET is_present = new.is_present WHERE media_id = new.id_media;" "END"; const std::string indexReq = "CREATE INDEX IF NOT EXISTS " "album_media_artist_genre_album_idx ON " + policy::AlbumTrackTable::Name + "(media_id, artist_id, genre_id, album_id)"; sqlite::Tools::executeRequest( dbConnection, triggerReq ); sqlite::Tools::executeRequest( dbConnection, indexReq ); } std::shared_ptr<AlbumTrack> AlbumTrack::create( MediaLibraryPtr ml, int64_t albumId, std::shared_ptr<Media> media, unsigned int trackNb, unsigned int discNumber, int64_t artistId, int64_t genreId, int64_t duration ) { auto self = std::make_shared<AlbumTrack>( ml, media->id(), artistId, genreId, trackNb, albumId, discNumber ); static const std::string req = "INSERT INTO " + policy::AlbumTrackTable::Name + "(media_id, duration, artist_id, genre_id, track_number, album_id, disc_number) VALUES(?, ?, ?, ?, ?, ?, ?)"; if ( insert( ml, self, req, media->id(), duration >= 0 ? duration : 0, sqlite::ForeignKey( artistId ), sqlite::ForeignKey( genreId ), trackNb, albumId, discNumber ) == false ) return nullptr; return self; } AlbumTrackPtr AlbumTrack::fromMedia( MediaLibraryPtr ml, int64_t mediaId ) { static const std::string req = "SELECT * FROM " + policy::AlbumTrackTable::Name + " WHERE media_id = ?"; return fetch( ml, req, mediaId ); } Query<IMedia> AlbumTrack::fromGenre( MediaLibraryPtr ml, int64_t genreId, const QueryParameters* params ) { std::string req = "FROM " + policy::MediaTable::Name + " m" " INNER JOIN " + policy::AlbumTrackTable::Name + " t ON m.id_media = t.media_id" " WHERE t.genre_id = ? AND m.is_present = 1 ORDER BY "; auto sort = params != nullptr ? params->sort : SortingCriteria::Default; auto desc = params != nullptr ? params->desc : false; switch ( sort ) { case SortingCriteria::Duration: req += "m.duration"; break; case SortingCriteria::InsertionDate: req += "m.insertion_date"; break; case SortingCriteria::ReleaseDate: req += "m.release_date"; break; case SortingCriteria::Alpha: req += "m.title"; break; default: if ( desc == true ) req += "t.artist_id DESC, t.album_id DESC, t.disc_number DESC, t.track_number DESC, m.filename"; else req += "t.artist_id, t.album_id, t.disc_number, t.track_number, m.filename"; break; } if ( desc == true ) req += " DESC"; return make_query<Media, IMedia>( ml, "m.*", std::move( req ), genreId ); } GenrePtr AlbumTrack::genre() { auto l = m_genre.lock(); if ( m_genre.isCached() == false ) { m_genre = Genre::fetch( m_ml, m_genreId ); } return m_genre.get(); } int64_t AlbumTrack::genreId() const { return m_genreId; } bool AlbumTrack::setGenre( std::shared_ptr<Genre> genre ) { // We need to fetch the old genre entity now, in case it gets deleted through // the nbTracks reaching 0 trigger. if ( m_genreId > 0 ) { auto l = m_genre.lock(); if ( m_genre.isCached() == false ) m_genre = Genre::fetch( m_ml, m_genreId ); } static const std::string req = "UPDATE " + policy::AlbumTrackTable::Name + " SET genre_id = ? WHERE id_track = ?"; if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, sqlite::ForeignKey( genre != nullptr ? genre->id() : 0 ), m_id ) == false ) return false; { auto l = m_genre.lock(); if ( m_genreId > 0 ) m_genre.get()->updateCachedNbTracks( -1 ); m_genre = genre; } if ( genre != nullptr ) { genre->updateCachedNbTracks( 1 ); m_genreId = genre->id(); } else m_genreId = 0; return true; } unsigned int AlbumTrack::trackNumber() const { return m_trackNumber; } unsigned int AlbumTrack::discNumber() const { return m_discNumber; } std::shared_ptr<IAlbum> AlbumTrack::album() { // "Fail" early in case there's no album to fetch if ( m_albumId == 0 ) return nullptr; auto lock = m_album.lock(); if ( m_album.isCached() == false ) m_album = Album::fetch( m_ml, m_albumId ); return m_album.get().lock(); } int64_t AlbumTrack::albumId() const { return m_albumId; } } <commit_msg>AlbumTrack: Index foreign keys<commit_after>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr> * * This program 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 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #include "AlbumTrack.h" #include "Album.h" #include "Artist.h" #include "Media.h" #include "Genre.h" #include "database/SqliteTools.h" #include "database/SqliteQuery.h" #include "logging/Logger.h" namespace medialibrary { const std::string policy::AlbumTrackTable::Name = "AlbumTrack"; const std::string policy::AlbumTrackTable::PrimaryKeyColumn = "id_track"; int64_t AlbumTrack::* const policy::AlbumTrackTable::PrimaryKey = &AlbumTrack::m_id; AlbumTrack::AlbumTrack( MediaLibraryPtr ml, sqlite::Row& row ) : m_ml( ml ) { int64_t dummyDuration; row >> m_id >> m_mediaId >> dummyDuration >> m_artistId >> m_genreId >> m_trackNumber >> m_albumId >> m_discNumber >> m_isPresent; } AlbumTrack::AlbumTrack( MediaLibraryPtr ml, int64_t mediaId, int64_t artistId, int64_t genreId, unsigned int trackNumber, int64_t albumId, unsigned int discNumber ) : m_ml( ml ) , m_id( 0 ) , m_mediaId( mediaId ) , m_artistId( artistId ) , m_genreId( genreId ) , m_trackNumber( trackNumber ) , m_albumId( albumId ) , m_discNumber( discNumber ) , m_isPresent( true ) { } int64_t AlbumTrack::id() const { return m_id; } ArtistPtr AlbumTrack::artist() const { if ( m_artistId == 0 ) return nullptr; auto lock = m_artist.lock(); if ( m_artist.isCached() == false ) { m_artist = Artist::fetch( m_ml, m_artistId ); } return m_artist.get(); } int64_t AlbumTrack::artistId() const { return m_artistId; } void AlbumTrack::createTable( sqlite::Connection* dbConnection ) { const std::string req = "CREATE TABLE IF NOT EXISTS " + policy::AlbumTrackTable::Name + "(" "id_track INTEGER PRIMARY KEY AUTOINCREMENT," "media_id INTEGER UNIQUE," "duration INTEGER NOT NULL," "artist_id UNSIGNED INTEGER," "genre_id INTEGER," "track_number UNSIGNED INTEGER," "album_id UNSIGNED INTEGER NOT NULL," "disc_number UNSIGNED INTEGER," "is_present BOOLEAN NOT NULL DEFAULT 1," "FOREIGN KEY (media_id) REFERENCES " + policy::MediaTable::Name + "(id_media)" " ON DELETE CASCADE," "FOREIGN KEY (artist_id) REFERENCES " + policy::ArtistTable::Name + "(id_artist)" " ON DELETE CASCADE," "FOREIGN KEY (genre_id) REFERENCES " + policy::GenreTable::Name + "(id_genre)," "FOREIGN KEY (album_id) REFERENCES Album(id_album) " " ON DELETE CASCADE" ")"; const std::string indexAlbumIdReq = "CREATE INDEX IF NOT EXISTS album_track_album_genre_artist_ids " "ON " + policy::AlbumTrackTable::Name + "(album_id, genre_id, artist_id)"; sqlite::Tools::executeRequest( dbConnection, req ); sqlite::Tools::executeRequest( dbConnection, indexAlbumIdReq ); } void AlbumTrack::createTriggers(sqlite::Connection* dbConnection) { const std::string triggerReq = "CREATE TRIGGER IF NOT EXISTS is_track_present " "AFTER UPDATE OF is_present " "ON " + policy::MediaTable::Name + " " "BEGIN " "UPDATE " + policy::AlbumTrackTable::Name + " " "SET is_present = new.is_present WHERE media_id = new.id_media;" "END"; const std::string indexReq = "CREATE INDEX IF NOT EXISTS " "album_media_artist_genre_album_idx ON " + policy::AlbumTrackTable::Name + "(media_id, artist_id, genre_id, album_id)"; sqlite::Tools::executeRequest( dbConnection, triggerReq ); sqlite::Tools::executeRequest( dbConnection, indexReq ); } std::shared_ptr<AlbumTrack> AlbumTrack::create( MediaLibraryPtr ml, int64_t albumId, std::shared_ptr<Media> media, unsigned int trackNb, unsigned int discNumber, int64_t artistId, int64_t genreId, int64_t duration ) { auto self = std::make_shared<AlbumTrack>( ml, media->id(), artistId, genreId, trackNb, albumId, discNumber ); static const std::string req = "INSERT INTO " + policy::AlbumTrackTable::Name + "(media_id, duration, artist_id, genre_id, track_number, album_id, disc_number) VALUES(?, ?, ?, ?, ?, ?, ?)"; if ( insert( ml, self, req, media->id(), duration >= 0 ? duration : 0, sqlite::ForeignKey( artistId ), sqlite::ForeignKey( genreId ), trackNb, albumId, discNumber ) == false ) return nullptr; return self; } AlbumTrackPtr AlbumTrack::fromMedia( MediaLibraryPtr ml, int64_t mediaId ) { static const std::string req = "SELECT * FROM " + policy::AlbumTrackTable::Name + " WHERE media_id = ?"; return fetch( ml, req, mediaId ); } Query<IMedia> AlbumTrack::fromGenre( MediaLibraryPtr ml, int64_t genreId, const QueryParameters* params ) { std::string req = "FROM " + policy::MediaTable::Name + " m" " INNER JOIN " + policy::AlbumTrackTable::Name + " t ON m.id_media = t.media_id" " WHERE t.genre_id = ? AND m.is_present = 1 ORDER BY "; auto sort = params != nullptr ? params->sort : SortingCriteria::Default; auto desc = params != nullptr ? params->desc : false; switch ( sort ) { case SortingCriteria::Duration: req += "m.duration"; break; case SortingCriteria::InsertionDate: req += "m.insertion_date"; break; case SortingCriteria::ReleaseDate: req += "m.release_date"; break; case SortingCriteria::Alpha: req += "m.title"; break; default: if ( desc == true ) req += "t.artist_id DESC, t.album_id DESC, t.disc_number DESC, t.track_number DESC, m.filename"; else req += "t.artist_id, t.album_id, t.disc_number, t.track_number, m.filename"; break; } if ( desc == true ) req += " DESC"; return make_query<Media, IMedia>( ml, "m.*", std::move( req ), genreId ); } GenrePtr AlbumTrack::genre() { auto l = m_genre.lock(); if ( m_genre.isCached() == false ) { m_genre = Genre::fetch( m_ml, m_genreId ); } return m_genre.get(); } int64_t AlbumTrack::genreId() const { return m_genreId; } bool AlbumTrack::setGenre( std::shared_ptr<Genre> genre ) { // We need to fetch the old genre entity now, in case it gets deleted through // the nbTracks reaching 0 trigger. if ( m_genreId > 0 ) { auto l = m_genre.lock(); if ( m_genre.isCached() == false ) m_genre = Genre::fetch( m_ml, m_genreId ); } static const std::string req = "UPDATE " + policy::AlbumTrackTable::Name + " SET genre_id = ? WHERE id_track = ?"; if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, sqlite::ForeignKey( genre != nullptr ? genre->id() : 0 ), m_id ) == false ) return false; { auto l = m_genre.lock(); if ( m_genreId > 0 ) m_genre.get()->updateCachedNbTracks( -1 ); m_genre = genre; } if ( genre != nullptr ) { genre->updateCachedNbTracks( 1 ); m_genreId = genre->id(); } else m_genreId = 0; return true; } unsigned int AlbumTrack::trackNumber() const { return m_trackNumber; } unsigned int AlbumTrack::discNumber() const { return m_discNumber; } std::shared_ptr<IAlbum> AlbumTrack::album() { // "Fail" early in case there's no album to fetch if ( m_albumId == 0 ) return nullptr; auto lock = m_album.lock(); if ( m_album.isCached() == false ) m_album = Album::fetch( m_ml, m_albumId ); return m_album.get().lock(); } int64_t AlbumTrack::albumId() const { return m_albumId; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2013 Google Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "core/events/EventRetargeter.h" #include "RuntimeEnabledFeatures.h" #include "core/dom/ContainerNode.h" #include "core/events/EventContext.h" #include "core/events/EventPathWalker.h" #include "core/events/FocusEvent.h" #include "core/dom/FullscreenElementStack.h" #include "core/events/MouseEvent.h" #include "core/dom/Touch.h" #include "core/events/TouchEvent.h" #include "core/dom/TouchList.h" #include "core/dom/TreeScope.h" #include "core/dom/shadow/ShadowRoot.h" #include "wtf/PassRefPtr.h" #include "wtf/RefPtr.h" #include "wtf/Vector.h" namespace WebCore { static inline bool inTheSameScope(ShadowRoot* shadowRoot, EventTarget* target) { return target->toNode() && target->toNode()->treeScope().rootNode() == shadowRoot; } static inline EventDispatchBehavior determineDispatchBehavior(Event* event, ShadowRoot* shadowRoot, EventTarget* target) { // Video-only full screen is a mode where we use the shadow DOM as an implementation // detail that should not be detectable by the web content. if (Element* element = FullscreenElementStack::currentFullScreenElementFrom(&target->toNode()->document())) { // FIXME: We assume that if the full screen element is a media element that it's // the video-only full screen. Both here and elsewhere. But that is probably wrong. if (element->isMediaElement() && shadowRoot && shadowRoot->host() == element) return StayInsideShadowDOM; } // WebKit never allowed selectstart event to cross the the shadow DOM boundary. // Changing this breaks existing sites. // See https://bugs.webkit.org/show_bug.cgi?id=52195 for details. const AtomicString eventType = event->type(); if (inTheSameScope(shadowRoot, target) && (eventType == EventTypeNames::abort || eventType == EventTypeNames::change || eventType == EventTypeNames::error || eventType == EventTypeNames::load || eventType == EventTypeNames::reset || eventType == EventTypeNames::resize || eventType == EventTypeNames::scroll || eventType == EventTypeNames::select || eventType == EventTypeNames::selectstart)) return StayInsideShadowDOM; return RetargetEvent; } void EventRetargeter::ensureEventPath(Node* node, Event* event) { calculateEventPath(node, event); calculateAdjustedEventPathForEachNode(event->eventPath()); } void EventRetargeter::calculateEventPath(Node* node, Event* event) { EventPath& eventPath = event->eventPath(); eventPath.clear(); bool inDocument = node->inDocument(); bool isMouseOrFocusEvent = event->isMouseEvent() || event->isFocusEvent(); bool isTouchEvent = event->isTouchEvent(); for (EventPathWalker walker(node); walker.node(); walker.moveToParent()) { if (isMouseOrFocusEvent) eventPath.append(adoptPtr(new MouseOrFocusEventContext(walker.node(), eventTargetRespectingTargetRules(walker.node()), eventTargetRespectingTargetRules(walker.adjustedTarget())))); else if (isTouchEvent) eventPath.append(adoptPtr(new TouchEventContext(walker.node(), eventTargetRespectingTargetRules(walker.node()), eventTargetRespectingTargetRules(walker.adjustedTarget())))); else eventPath.append(adoptPtr(new EventContext(walker.node(), eventTargetRespectingTargetRules(walker.node()), eventTargetRespectingTargetRules(walker.adjustedTarget())))); if (!inDocument) break; if (walker.node()->isShadowRoot() && determineDispatchBehavior(event, toShadowRoot(walker.node()), walker.adjustedTarget()) == StayInsideShadowDOM) break; } } void EventRetargeter::calculateAdjustedEventPathForEachNode(EventPath& eventPath) { if (!RuntimeEnabledFeatures::shadowDOMEnabled()) return; TreeScope* lastScope = 0; size_t eventPathSize = eventPath.size(); for (size_t i = 0; i < eventPathSize; ++i) { TreeScope* currentScope = &eventPath[i]->node()->treeScope(); if (currentScope == lastScope) { // Fast path. eventPath[i]->setEventPath(eventPath[i - 1]->eventPath()); continue; } lastScope = currentScope; Vector<RefPtr<Node> > nodes; for (size_t j = 0; j < eventPathSize; ++j) { Node* node = eventPath[j]->node(); if (node->treeScope().isInclusiveAncestorOf(*currentScope)) nodes.append(node); } eventPath[i]->adoptEventPath(nodes); } } void EventRetargeter::adjustForMouseEvent(Node* node, MouseEvent& mouseEvent) { adjustForRelatedTarget(node, mouseEvent.relatedTarget(), mouseEvent.eventPath()); } void EventRetargeter::adjustForFocusEvent(Node* node, FocusEvent& focusEvent) { adjustForRelatedTarget(node, focusEvent.relatedTarget(), focusEvent.eventPath()); } void EventRetargeter::adjustForTouchEvent(Node* node, TouchEvent& touchEvent) { EventPath& eventPath = touchEvent.eventPath(); size_t eventPathSize = eventPath.size(); EventPathTouchLists eventPathTouches(eventPathSize); EventPathTouchLists eventPathTargetTouches(eventPathSize); EventPathTouchLists eventPathChangedTouches(eventPathSize); for (size_t i = 0; i < eventPathSize; ++i) { ASSERT(eventPath[i]->isTouchEventContext()); TouchEventContext* touchEventContext = toTouchEventContext(eventPath[i].get()); eventPathTouches[i] = touchEventContext->touches(); eventPathTargetTouches[i] = touchEventContext->targetTouches(); eventPathChangedTouches[i] = touchEventContext->changedTouches(); } adjustTouchList(node, touchEvent.touches(), eventPath, eventPathTouches); adjustTouchList(node, touchEvent.targetTouches(), eventPath, eventPathTargetTouches); adjustTouchList(node, touchEvent.changedTouches(), eventPath, eventPathChangedTouches); } void EventRetargeter::adjustTouchList(const Node* node, const TouchList* touchList, const EventPath& eventPath, EventPathTouchLists& eventPathTouchLists) { if (!touchList) return; size_t eventPathSize = eventPath.size(); ASSERT(eventPathTouchLists.size() == eventPathSize); for (size_t i = 0; i < touchList->length(); ++i) { const Touch& touch = *touchList->item(i); AdjustedNodes adjustedNodes; calculateAdjustedNodes(node, touch.target()->toNode(), DoesNotStopAtBoundary, const_cast<EventPath&>(eventPath), adjustedNodes); ASSERT(adjustedNodes.size() == eventPathSize); for (size_t j = 0; j < eventPathSize; ++j) eventPathTouchLists[j]->append(touch.cloneWithNewTarget(adjustedNodes[j].get())); } } void EventRetargeter::adjustForRelatedTarget(const Node* node, EventTarget* relatedTarget, EventPath& eventPath) { if (!node) return; if (!relatedTarget) return; Node* relatedNode = relatedTarget->toNode(); if (!relatedNode) return; AdjustedNodes adjustedNodes; calculateAdjustedNodes(node, relatedNode, StopAtBoundaryIfNeeded, eventPath, adjustedNodes); ASSERT(adjustedNodes.size() <= eventPath.size()); for (size_t i = 0; i < adjustedNodes.size(); ++i) { ASSERT(eventPath[i]->isMouseOrFocusEventContext()); MouseOrFocusEventContext* mouseOrFocusEventContext = static_cast<MouseOrFocusEventContext*>(eventPath[i].get()); mouseOrFocusEventContext->setRelatedTarget(adjustedNodes[i]); } } void EventRetargeter::calculateAdjustedNodes(const Node* node, const Node* relatedNode, EventWithRelatedTargetDispatchBehavior eventWithRelatedTargetDispatchBehavior, EventPath& eventPath, AdjustedNodes& adjustedNodes) { RelatedNodeMap relatedNodeMap; buildRelatedNodeMap(relatedNode, relatedNodeMap); // Synthetic mouse events can have a relatedTarget which is identical to the target. bool targetIsIdenticalToToRelatedTarget = (node == relatedNode); TreeScope* lastTreeScope = 0; Node* adjustedNode = 0; for (EventPath::const_iterator iter = eventPath.begin(); iter < eventPath.end(); ++iter) { TreeScope* scope = &(*iter)->node()->treeScope(); if (scope == lastTreeScope) { // Re-use the previous adjustedRelatedTarget if treeScope does not change. Just for the performance optimization. adjustedNodes.append(adjustedNode); } else { adjustedNode = findRelatedNode(scope, relatedNodeMap); adjustedNodes.append(adjustedNode); } lastTreeScope = scope; if (eventWithRelatedTargetDispatchBehavior == DoesNotStopAtBoundary) continue; if (targetIsIdenticalToToRelatedTarget) { if (node->treeScope().rootNode() == (*iter)->node()) { eventPath.shrink(iter + 1 - eventPath.begin()); break; } } else if ((*iter)->target() == adjustedNode) { // Event dispatching should be stopped here. eventPath.shrink(iter - eventPath.begin()); adjustedNodes.shrink(adjustedNodes.size() - 1); break; } } } void EventRetargeter::buildRelatedNodeMap(const Node* relatedNode, RelatedNodeMap& relatedNodeMap) { TreeScope* lastTreeScope = 0; for (EventPathWalker walker(relatedNode); walker.node(); walker.moveToParent()) { if (&walker.node()->treeScope() != lastTreeScope) relatedNodeMap.add(&walker.node()->treeScope(), walker.adjustedTarget()); lastTreeScope = &walker.node()->treeScope(); } } Node* EventRetargeter::findRelatedNode(TreeScope* scope, RelatedNodeMap& relatedNodeMap) { Vector<TreeScope*, 32> parentTreeScopes; Node* relatedNode = 0; while (scope) { parentTreeScopes.append(scope); RelatedNodeMap::const_iterator found = relatedNodeMap.find(scope); if (found != relatedNodeMap.end()) { relatedNode = found->value; break; } scope = scope->parentTreeScope(); } for (Vector<TreeScope*, 32>::iterator iter = parentTreeScopes.begin(); iter < parentTreeScopes.end(); ++iter) relatedNodeMap.add(*iter, relatedNode); return relatedNode; } } <commit_msg>Use an original event target instead of a target in determining dispatch behavior.<commit_after>/* * Copyright (C) 2013 Google Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "core/events/EventRetargeter.h" #include "RuntimeEnabledFeatures.h" #include "core/dom/ContainerNode.h" #include "core/events/EventContext.h" #include "core/events/EventPathWalker.h" #include "core/events/FocusEvent.h" #include "core/dom/FullscreenElementStack.h" #include "core/events/MouseEvent.h" #include "core/dom/Touch.h" #include "core/events/TouchEvent.h" #include "core/dom/TouchList.h" #include "core/dom/TreeScope.h" #include "core/dom/shadow/ShadowRoot.h" #include "wtf/PassRefPtr.h" #include "wtf/RefPtr.h" #include "wtf/Vector.h" namespace WebCore { static inline bool inTheSameScope(ShadowRoot* shadowRoot, EventTarget* target) { return target->toNode() && target->toNode()->treeScope().rootNode() == shadowRoot; } static inline EventDispatchBehavior determineDispatchBehavior(Event* event, ShadowRoot* shadowRoot, EventTarget* target) { // Video-only full screen is a mode where we use the shadow DOM as an implementation // detail that should not be detectable by the web content. if (Element* element = FullscreenElementStack::currentFullScreenElementFrom(&target->toNode()->document())) { // FIXME: We assume that if the full screen element is a media element that it's // the video-only full screen. Both here and elsewhere. But that is probably wrong. if (element->isMediaElement() && shadowRoot && shadowRoot->host() == element) return StayInsideShadowDOM; } // WebKit never allowed selectstart event to cross the the shadow DOM boundary. // Changing this breaks existing sites. // See https://bugs.webkit.org/show_bug.cgi?id=52195 for details. const AtomicString eventType = event->type(); if (inTheSameScope(shadowRoot, target) && (eventType == EventTypeNames::abort || eventType == EventTypeNames::change || eventType == EventTypeNames::error || eventType == EventTypeNames::load || eventType == EventTypeNames::reset || eventType == EventTypeNames::resize || eventType == EventTypeNames::scroll || eventType == EventTypeNames::select || eventType == EventTypeNames::selectstart)) return StayInsideShadowDOM; return RetargetEvent; } void EventRetargeter::ensureEventPath(Node* node, Event* event) { calculateEventPath(node, event); calculateAdjustedEventPathForEachNode(event->eventPath()); } void EventRetargeter::calculateEventPath(Node* node, Event* event) { EventPath& eventPath = event->eventPath(); eventPath.clear(); bool inDocument = node->inDocument(); bool isMouseOrFocusEvent = event->isMouseEvent() || event->isFocusEvent(); bool isTouchEvent = event->isTouchEvent(); for (EventPathWalker walker(node); walker.node(); walker.moveToParent()) { if (isMouseOrFocusEvent) eventPath.append(adoptPtr(new MouseOrFocusEventContext(walker.node(), eventTargetRespectingTargetRules(walker.node()), eventTargetRespectingTargetRules(walker.adjustedTarget())))); else if (isTouchEvent) eventPath.append(adoptPtr(new TouchEventContext(walker.node(), eventTargetRespectingTargetRules(walker.node()), eventTargetRespectingTargetRules(walker.adjustedTarget())))); else eventPath.append(adoptPtr(new EventContext(walker.node(), eventTargetRespectingTargetRules(walker.node()), eventTargetRespectingTargetRules(walker.adjustedTarget())))); if (!inDocument) break; if (walker.node()->isShadowRoot() && determineDispatchBehavior(event, toShadowRoot(walker.node()), node) == StayInsideShadowDOM) break; } } void EventRetargeter::calculateAdjustedEventPathForEachNode(EventPath& eventPath) { if (!RuntimeEnabledFeatures::shadowDOMEnabled()) return; TreeScope* lastScope = 0; size_t eventPathSize = eventPath.size(); for (size_t i = 0; i < eventPathSize; ++i) { TreeScope* currentScope = &eventPath[i]->node()->treeScope(); if (currentScope == lastScope) { // Fast path. eventPath[i]->setEventPath(eventPath[i - 1]->eventPath()); continue; } lastScope = currentScope; Vector<RefPtr<Node> > nodes; for (size_t j = 0; j < eventPathSize; ++j) { Node* node = eventPath[j]->node(); if (node->treeScope().isInclusiveAncestorOf(*currentScope)) nodes.append(node); } eventPath[i]->adoptEventPath(nodes); } } void EventRetargeter::adjustForMouseEvent(Node* node, MouseEvent& mouseEvent) { adjustForRelatedTarget(node, mouseEvent.relatedTarget(), mouseEvent.eventPath()); } void EventRetargeter::adjustForFocusEvent(Node* node, FocusEvent& focusEvent) { adjustForRelatedTarget(node, focusEvent.relatedTarget(), focusEvent.eventPath()); } void EventRetargeter::adjustForTouchEvent(Node* node, TouchEvent& touchEvent) { EventPath& eventPath = touchEvent.eventPath(); size_t eventPathSize = eventPath.size(); EventPathTouchLists eventPathTouches(eventPathSize); EventPathTouchLists eventPathTargetTouches(eventPathSize); EventPathTouchLists eventPathChangedTouches(eventPathSize); for (size_t i = 0; i < eventPathSize; ++i) { ASSERT(eventPath[i]->isTouchEventContext()); TouchEventContext* touchEventContext = toTouchEventContext(eventPath[i].get()); eventPathTouches[i] = touchEventContext->touches(); eventPathTargetTouches[i] = touchEventContext->targetTouches(); eventPathChangedTouches[i] = touchEventContext->changedTouches(); } adjustTouchList(node, touchEvent.touches(), eventPath, eventPathTouches); adjustTouchList(node, touchEvent.targetTouches(), eventPath, eventPathTargetTouches); adjustTouchList(node, touchEvent.changedTouches(), eventPath, eventPathChangedTouches); } void EventRetargeter::adjustTouchList(const Node* node, const TouchList* touchList, const EventPath& eventPath, EventPathTouchLists& eventPathTouchLists) { if (!touchList) return; size_t eventPathSize = eventPath.size(); ASSERT(eventPathTouchLists.size() == eventPathSize); for (size_t i = 0; i < touchList->length(); ++i) { const Touch& touch = *touchList->item(i); AdjustedNodes adjustedNodes; calculateAdjustedNodes(node, touch.target()->toNode(), DoesNotStopAtBoundary, const_cast<EventPath&>(eventPath), adjustedNodes); ASSERT(adjustedNodes.size() == eventPathSize); for (size_t j = 0; j < eventPathSize; ++j) eventPathTouchLists[j]->append(touch.cloneWithNewTarget(adjustedNodes[j].get())); } } void EventRetargeter::adjustForRelatedTarget(const Node* node, EventTarget* relatedTarget, EventPath& eventPath) { if (!node) return; if (!relatedTarget) return; Node* relatedNode = relatedTarget->toNode(); if (!relatedNode) return; AdjustedNodes adjustedNodes; calculateAdjustedNodes(node, relatedNode, StopAtBoundaryIfNeeded, eventPath, adjustedNodes); ASSERT(adjustedNodes.size() <= eventPath.size()); for (size_t i = 0; i < adjustedNodes.size(); ++i) { ASSERT(eventPath[i]->isMouseOrFocusEventContext()); MouseOrFocusEventContext* mouseOrFocusEventContext = static_cast<MouseOrFocusEventContext*>(eventPath[i].get()); mouseOrFocusEventContext->setRelatedTarget(adjustedNodes[i]); } } void EventRetargeter::calculateAdjustedNodes(const Node* node, const Node* relatedNode, EventWithRelatedTargetDispatchBehavior eventWithRelatedTargetDispatchBehavior, EventPath& eventPath, AdjustedNodes& adjustedNodes) { RelatedNodeMap relatedNodeMap; buildRelatedNodeMap(relatedNode, relatedNodeMap); // Synthetic mouse events can have a relatedTarget which is identical to the target. bool targetIsIdenticalToToRelatedTarget = (node == relatedNode); TreeScope* lastTreeScope = 0; Node* adjustedNode = 0; for (EventPath::const_iterator iter = eventPath.begin(); iter < eventPath.end(); ++iter) { TreeScope* scope = &(*iter)->node()->treeScope(); if (scope == lastTreeScope) { // Re-use the previous adjustedRelatedTarget if treeScope does not change. Just for the performance optimization. adjustedNodes.append(adjustedNode); } else { adjustedNode = findRelatedNode(scope, relatedNodeMap); adjustedNodes.append(adjustedNode); } lastTreeScope = scope; if (eventWithRelatedTargetDispatchBehavior == DoesNotStopAtBoundary) continue; if (targetIsIdenticalToToRelatedTarget) { if (node->treeScope().rootNode() == (*iter)->node()) { eventPath.shrink(iter + 1 - eventPath.begin()); break; } } else if ((*iter)->target() == adjustedNode) { // Event dispatching should be stopped here. eventPath.shrink(iter - eventPath.begin()); adjustedNodes.shrink(adjustedNodes.size() - 1); break; } } } void EventRetargeter::buildRelatedNodeMap(const Node* relatedNode, RelatedNodeMap& relatedNodeMap) { TreeScope* lastTreeScope = 0; for (EventPathWalker walker(relatedNode); walker.node(); walker.moveToParent()) { if (&walker.node()->treeScope() != lastTreeScope) relatedNodeMap.add(&walker.node()->treeScope(), walker.adjustedTarget()); lastTreeScope = &walker.node()->treeScope(); } } Node* EventRetargeter::findRelatedNode(TreeScope* scope, RelatedNodeMap& relatedNodeMap) { Vector<TreeScope*, 32> parentTreeScopes; Node* relatedNode = 0; while (scope) { parentTreeScopes.append(scope); RelatedNodeMap::const_iterator found = relatedNodeMap.find(scope); if (found != relatedNodeMap.end()) { relatedNode = found->value; break; } scope = scope->parentTreeScope(); } for (Vector<TreeScope*, 32>::iterator iter = parentTreeScopes.begin(); iter < parentTreeScopes.end(); ++iter) relatedNodeMap.add(*iter, relatedNode); return relatedNode; } } <|endoftext|>
<commit_before>/** ** Copyright (c) 2011-2014 Illumina, Inc. ** ** This file is part of the BEETL software package, ** covered by the "BSD 2-Clause License" (see accompanying LICENSE file) ** ** Citation: Markus J. Bauer, Anthony J. Cox and Giovanna Rosone ** Lightweight BWT Construction for Very Large String Collections. ** Proceedings of CPM 2011, pp.219-231 ** **/ #ifndef SORTED_INCLUDED #define SORTED_INCLUDED #include "Alphabet.hh" #include "Types.hh" #include <vector> using std::vector; struct sortElement { #if BUILD_LCP == 0 sortElement() {} sortElement( AlphabetSymbol z, LetterNumber x, SequenceNumber y ) : pileN( z ) , posN( x ) , seqN( y ) {} SequenceLength getLcpCurN() const { return 0; } SequenceLength getLcpSucN() const { return 0; } void setLcpCurN( const SequenceLength val ) { } void setLcpSucN( const SequenceLength val ) { } #else sortElement() : pileN( 0 ), lcpCurN( 0 ), lcpSucN( 0 ) {} sortElement( AlphabetSymbol z, LetterNumber x, SequenceNumber y, SequenceLength l1 = 0, SequenceLength l2 = 0 ) : pileN( z ) , posN( x ) , seqN( y ) , lcpCurN( l1 ) , lcpSucN( l2 ) {} SequenceLength getLcpCurN() const { return lcpCurN; } SequenceLength getLcpSucN() const { return lcpSucN; } void setLcpCurN( const SequenceLength val ) { lcpCurN = val; } void setLcpSucN( const SequenceLength val ) { lcpSucN = val; } #endif ~sortElement() {}; AlphabetSymbol pileN; LetterNumber posN; SequenceNumber seqN; #if BUILD_LCP == 1 SequenceLength lcpCurN; SequenceLength lcpSucN; #endif #if USE_ATTRIBUTE_PACKED == 1 } __attribute__ ( ( packed ) ); #else }; #endif void quickSort( vector< sortElement > &v ); #endif <commit_msg>Update Sorting.hh<commit_after>/** ** Copyright (c) 2011-2014 Illumina, Inc. ** ** This file is part of the BEETL software package, ** covered by the "BSD 2-Clause License" (see accompanying LICENSE file) ** ** Citation: Markus J. Bauer, Anthony J. Cox and Giovanna Rosone ** Lightweight BWT Construction for Very Large String Collections. ** Proceedings of CPM 2011, pp.219-231 ** **/ #ifndef SORTED_INCLUDED #define SORTED_INCLUDED #include "Alphabet.hh" #include "Types.hh" #include <vector> using std::vector; //2020-12-04 #define BUILD_LCP 0 struct sortElement { #if BUILD_LCP == 0 sortElement() {} sortElement( AlphabetSymbol z, LetterNumber x, SequenceNumber y ) : pileN( z ) , posN( x ) , seqN( y ) {} SequenceLength getLcpCurN() const { return 0; } SequenceLength getLcpSucN() const { return 0; } void setLcpCurN( const SequenceLength val ) { } void setLcpSucN( const SequenceLength val ) { } #else sortElement() : pileN( 0 ), lcpCurN( 0 ), lcpSucN( 0 ) {} sortElement( AlphabetSymbol z, LetterNumber x, SequenceNumber y, SequenceLength l1 = 0, SequenceLength l2 = 0 ) : pileN( z ) , posN( x ) , seqN( y ) , lcpCurN( l1 ) , lcpSucN( l2 ) {} SequenceLength getLcpCurN() const { return lcpCurN; } SequenceLength getLcpSucN() const { return lcpSucN; } void setLcpCurN( const SequenceLength val ) { lcpCurN = val; } void setLcpSucN( const SequenceLength val ) { lcpSucN = val; } #endif ~sortElement() {}; AlphabetSymbol pileN; LetterNumber posN; SequenceNumber seqN; #if BUILD_LCP == 1 SequenceLength lcpCurN; SequenceLength lcpSucN; #endif #if USE_ATTRIBUTE_PACKED == 1 } __attribute__ ( ( packed ) ); #else }; #endif void quickSort( vector< sortElement > &v ); #endif <|endoftext|>
<commit_before>#include <listformatter.h> #include <utils.h> #include <stflpp.h> namespace newsbeuter { listformatter::listformatter() : refresh_cache(true) { } listformatter::~listformatter() { } void listformatter::add_line(const std::string& text, unsigned int id, unsigned int width) { if (width > 0) { std::string mytext = text; while (mytext.length() > width) { lines.push_back(line_id_pair(mytext.substr(0, width), id)); mytext.erase(0, width); } lines.push_back(line_id_pair(mytext, id)); } else { lines.push_back(line_id_pair(text, id)); } LOG(LOG_DEBUG, "listformatter::add_line: `%s'", text.c_str()); refresh_cache = true; } void listformatter::add_lines(const std::vector<std::string>& thelines, unsigned int width) { for (std::vector<std::string>::const_iterator it=thelines.begin();it!=thelines.end();++it) { add_line(*it, UINT_MAX, width); } } std::string listformatter::format_list(regexmanager * rxman, const std::string& location) { format_cache = "{list"; for (std::vector<line_id_pair>::iterator it=lines.begin();it!=lines.end();++it) { std::string str = it->first; if (rxman) rxman->quote_and_highlight(str, location); if (it->second == UINT_MAX) { format_cache.append(utils::strprintf("{listitem text:%s}", stfl::quote(str).c_str())); } else { format_cache.append(utils::strprintf("{listitem[%u] text:%s}", it->second, stfl::quote(str).c_str())); } } format_cache.append(1, '}'); refresh_cache = false; return format_cache; } } <commit_msg>fixed issue #169.<commit_after>#include <listformatter.h> #include <utils.h> #include <stflpp.h> namespace newsbeuter { listformatter::listformatter() : refresh_cache(true) { } listformatter::~listformatter() { } void listformatter::add_line(const std::string& text, unsigned int id, unsigned int width) { if (width > 0) { std::string mytext = text; while (mytext.length() > width) { lines.push_back(line_id_pair(mytext.substr(0, width), id)); mytext.erase(0, width); } lines.push_back(line_id_pair(mytext, id)); } else { lines.push_back(line_id_pair(text, id)); } LOG(LOG_DEBUG, "listformatter::add_line: `%s'", text.c_str()); refresh_cache = true; } void listformatter::add_lines(const std::vector<std::string>& thelines, unsigned int width) { for (std::vector<std::string>::const_iterator it=thelines.begin();it!=thelines.end();++it) { add_line(*it, UINT_MAX, width); } } std::string listformatter::format_list(regexmanager * rxman, const std::string& location) { format_cache = "{list"; for (std::vector<line_id_pair>::iterator it=lines.begin();it!=lines.end();++it) { std::string str = utils::replace_all(it->first, "<", "<>"); if (rxman) rxman->quote_and_highlight(str, location); if (it->second == UINT_MAX) { format_cache.append(utils::strprintf("{listitem text:%s}", stfl::quote(str).c_str())); } else { format_cache.append(utils::strprintf("{listitem[%u] text:%s}", it->second, stfl::quote(str).c_str())); } } format_cache.append(1, '}'); refresh_cache = false; return format_cache; } } <|endoftext|>
<commit_before>#include <torrentsync/dht/Address.h> #include <torrentsync/dht/RoutingTable.h> #include <iostream> using namespace torrentsync::dht; int main() { RoutingTable table; return 0; } <commit_msg>Deleted old test file<commit_after><|endoftext|>
<commit_before>/****************************************************************************** ** Copyright (c) 2013-2015, Intel Corporation ** ** All rights reserved. ** ** ** ** Redistribution and use in source and binary forms, with or without ** ** modification, are permitted provided that the following conditions ** ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** ** notice, this list of conditions and the following disclaimer. ** ** 2. Redistributions in binary form must reproduce the above copyright ** ** notice, this list of conditions and the following disclaimer in the ** ** documentation and/or other materials provided with the distribution. ** ** 3. Neither the name of the copyright holder nor the names of its ** ** contributors may be used to endorse or promote products derived ** ** from this software without specific prior written permission. ** ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** ** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ** ** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ** ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ** ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ** ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ******************************************************************************/ /* Hans Pabst (Intel Corp.) ******************************************************************************/ #include <libxsmm.h> #if defined(LIBXSMM_OFFLOAD) # pragma offload_attribute(push,target(mic)) #endif #include <algorithm> #include <stdexcept> #include <cstdlib> #include <cstring> #include <cassert> #include <cstdio> #include <vector> #include <cmath> #if defined(_OPENMP) # include <omp.h> #endif #if defined(LIBXSMM_OFFLOAD) # pragma offload_attribute(pop) #endif #if (0 < (LIBXSMM_ALIGNED_STORES)) # define SMM_ALIGNMENT LIBXSMM_ALIGNED_STORES #else # define SMM_ALIGNMENT LIBXSMM_ALIGNMENT #endif // make sure that stacksize is covering the problem size #define SMM_MAX_PROBLEM_SIZE (1 * LIBXSMM_MAX_MNK) // ensures sufficient parallel slack #define SMM_MIN_NPARALLEL 210 // ensures amortized atomic overhead #define SMM_MIN_NLOCAL 150 #define SMM_MAX_NLOCAL 250 // OpenMP schedule policy (and chunk size) #define SMM_SCHEDULE static,1 // enable result validation #define SMM_CHECK template<typename T> LIBXSMM_TARGET(mic) void nrand(T& a) { static const double scale = 1.0 / RAND_MAX; a = static_cast<T>(scale * (2 * std::rand() - RAND_MAX)); } template<typename T> LIBXSMM_TARGET(mic) void add(T *LIBXSMM_RESTRICT dst, const T *LIBXSMM_RESTRICT c, int m, int n, int ldc) { #if (0 < LIBXSMM_ALIGNED_STORES) LIBXSMM_ASSUME_ALIGNED(c, SMM_ALIGNMENT); #endif for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { #if (0 != LIBXSMM_ROW_MAJOR) const T value = c[i*ldc+j]; #else const T value = c[j*ldc+i]; #endif #if defined(_OPENMP) # pragma omp atomic #endif #if (0 != LIBXSMM_ROW_MAJOR) dst[i*n+j] += value; #else dst[j*m+i] += value; #endif } } } template<typename T> LIBXSMM_TARGET(mic) double max_diff(const T *LIBXSMM_RESTRICT result, const T *LIBXSMM_RESTRICT expect, int m, int n, int ldc) { double diff = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { #if (0 != LIBXSMM_ROW_MAJOR) const int k = i * ldc + j; #else const int k = j * ldc + i; #endif diff = std::max(diff, std::abs(static_cast<double>(result[k]) - static_cast<double>(expect[k]))); } } return diff; } int main(int argc, char* argv[]) { try { typedef double T; const int default_psize = (SMM_MIN_NPARALLEL) * (SMM_MIN_NLOCAL), default_batch = SMM_MAX_NLOCAL; const int m = 1 < argc ? std::atoi(argv[1]) : 23; const int s = 2 < argc ? (0 < std::atoi(argv[2]) ? std::atoi(argv[2]) : ('+' == *argv[2] ? (default_psize << std::strlen(argv[2])) : ('-' == *argv[2] ? (default_psize >> std::strlen(argv[2])) : default_psize))) : default_psize; const int t = 3 < argc ? (0 < std::atoi(argv[3]) ? std::atoi(argv[3]) : ('+' == *argv[3] ? (default_batch << std::strlen(argv[3])) : ('-' == *argv[3] ? (default_batch >> std::strlen(argv[3])) : -1))) : -1; const int n = 4 < argc ? std::atoi(argv[4]) : m; const int k = 5 < argc ? std::atoi(argv[5]) : m; if ((SMM_MAX_PROBLEM_SIZE) < (m * n * k)) { throw std::runtime_error("The size M x N x K is exceeding SMM_MAX_PROBLEM_SIZE!"); } #if (0 != LIBXSMM_ROW_MAJOR) # if (0 < LIBXSMM_ALIGNED_STORES) const int ldc = LIBXSMM_ALIGN_VALUE(int, T, n, LIBXSMM_ALIGNED_STORES); # else const int ldc = n; # endif const int csize = m * ldc; #else # if (0 < LIBXSMM_ALIGNED_STORES) const int ldc = LIBXSMM_ALIGN_VALUE(int, T, m, LIBXSMM_ALIGNED_STORES); # else const int ldc = m; # endif const int csize = n * ldc; #endif const int asize = m * k, bsize = k * n; std::vector<T> va(s * asize), vb(s * bsize), vc(csize); std::for_each(va.begin(), va.end(), nrand<T>); std::for_each(vb.begin(), vb.end(), nrand<T>); const T *const a = &va[0], *const b = &vb[0]; T * /*const*/ c = &vc[0]; #if defined(LIBXSMM_OFFLOAD) # pragma offload target(mic) in(a: length(s * asize)) in(b: length(s * bsize)) out(c: length(csize)) #endif { const double mbytes = 1.0 * s * (asize + bsize) * sizeof(T) / (1024 * 1024); #if defined(_OPENMP) const double nbytes = 1.0 * s * (csize) * sizeof(T) / (1024 * 1024); const double gflops = 2.0 * s * m * n * k * 1E-9; const int u = 0 < t ? t : std::max(SMM_MIN_NLOCAL, std::min(SMM_MAX_NLOCAL, s / std::max(SMM_MIN_NPARALLEL, s / default_batch))); #else const int u = t; #endif #if defined(SMM_CHECK) std::vector<T> expect(csize); #endif fprintf(stdout, "m=%i n=%i k=%i ldc=%i size=%i batch=%i memory=%.1f MB\n\n", m, n, k, ldc, s, u, mbytes); { // LAPACK/BLAS3 (fallback) fprintf(stdout, "LAPACK/BLAS...\n"); std::fill_n(c, csize, 0); #if defined(_OPENMP) const double start = omp_get_wtime(); # pragma omp parallel for schedule(SMM_SCHEDULE) #endif for (int i = 0; i < s; i += u) { LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT); for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear for (int j = 0; j < LIBXSMM_MIN(u, s - i); ++j) { libxsmm_blasmm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp); } add(c, tmp, m, n, ldc); // atomic } #if defined(_OPENMP) const double duration = omp_get_wtime() - start; if (0 < duration) { fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration); fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration); } fprintf(stdout, "\tduration: %.1f s\n", duration); #endif #if defined(SMM_CHECK) std::copy(c, c + csize, expect.begin()); #endif } { // inline an optimized implementation fprintf(stdout, "Inlined...\n"); std::fill_n(c, csize, 0); #if defined(_OPENMP) const double start = omp_get_wtime(); # pragma omp parallel for schedule(SMM_SCHEDULE) #endif for (int i = 0; i < s; i += u) { LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT); for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear for (int j = 0; j < LIBXSMM_MIN(u, s - i); ++j) { libxsmm_imm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp); } add(c, tmp, m, n, ldc); // atomic } #if defined(_OPENMP) const double duration = omp_get_wtime() - start; if (0 < duration) { fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration); fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration); } fprintf(stdout, "\tduration: %.1f s\n", duration); #endif #if defined(SMM_CHECK) fprintf(stdout, "\tdiff=%f\n", max_diff(c, &expect[0], m, n, ldc)); #endif } { // auto-dispatched fprintf(stdout, "Dispatched...\n"); libxsmm_mm(1, 1, 1, &a[0], &b[0], &c[0]); // warmup/workaround std::fill_n(c, csize, 0); #if defined(_OPENMP) const double start = omp_get_wtime(); # pragma omp parallel for schedule(SMM_SCHEDULE) #endif for (int i = 0; i < s; i += u) { LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT); for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear for (int j = 0; j < LIBXSMM_MIN(u, s - i); ++j) { libxsmm_mm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp); } add(c, tmp, m, n, ldc); // atomic } #if defined(_OPENMP) const double duration = omp_get_wtime() - start; if (0 < duration) { fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration); fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration); } fprintf(stdout, "\tduration: %.1f s\n", duration); #endif #if defined(SMM_CHECK) fprintf(stdout, "\tdiff=%f\n", max_diff(c, &expect[0], m, n, ldc)); #endif } const libxsmm_mm_dispatch<T> xmm(m, n, k); if (xmm) { // specialized routine fprintf(stdout, "Specialized...\n"); std::fill_n(c, csize, 0); #if defined(_OPENMP) const double start = omp_get_wtime(); # pragma omp parallel for schedule(SMM_SCHEDULE) #endif for (int i = 0; i < s; i += u) { LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT); for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear for (int j = 0; j < LIBXSMM_MIN(u, s - i); ++j) { xmm(&a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp); } add(c, tmp, m, n, ldc); // atomic } #if defined(_OPENMP) const double duration = omp_get_wtime() - start; if (0 < duration) { fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration); fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration); } fprintf(stdout, "\tduration: %.1f s\n", duration); #endif #if defined(SMM_CHECK) fprintf(stdout, "\tdiff=%f\n", max_diff(c, &expect[0], m, n, ldc)); #endif } fprintf(stdout, "Finished\n"); } } catch(const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return EXIT_FAILURE; } catch(...) { fprintf(stderr, "Error: unknown exception caught!\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>Rebalanced parameter set.<commit_after>/****************************************************************************** ** Copyright (c) 2013-2015, Intel Corporation ** ** All rights reserved. ** ** ** ** Redistribution and use in source and binary forms, with or without ** ** modification, are permitted provided that the following conditions ** ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** ** notice, this list of conditions and the following disclaimer. ** ** 2. Redistributions in binary form must reproduce the above copyright ** ** notice, this list of conditions and the following disclaimer in the ** ** documentation and/or other materials provided with the distribution. ** ** 3. Neither the name of the copyright holder nor the names of its ** ** contributors may be used to endorse or promote products derived ** ** from this software without specific prior written permission. ** ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** ** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ** ** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ** ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ** ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ** ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ******************************************************************************/ /* Hans Pabst (Intel Corp.) ******************************************************************************/ #include <libxsmm.h> #if defined(LIBXSMM_OFFLOAD) # pragma offload_attribute(push,target(mic)) #endif #include <algorithm> #include <stdexcept> #include <cstdlib> #include <cstring> #include <cassert> #include <cstdio> #include <vector> #include <cmath> #if defined(_OPENMP) # include <omp.h> #endif #if defined(LIBXSMM_OFFLOAD) # pragma offload_attribute(pop) #endif #if (0 < (LIBXSMM_ALIGNED_STORES)) # define SMM_ALIGNMENT LIBXSMM_ALIGNED_STORES #else # define SMM_ALIGNMENT LIBXSMM_ALIGNMENT #endif // make sure that stacksize is covering the problem size #define SMM_MAX_PROBLEM_SIZE (1 * LIBXSMM_MAX_MNK) // ensures sufficient parallel slack #define SMM_MIN_NPARALLEL 240 // ensures amortized atomic overhead #define SMM_MIN_NLOCAL 160 // OpenMP schedule policy (and chunk size) #define SMM_SCHEDULE static,1 // enable result validation #define SMM_CHECK template<typename T> LIBXSMM_TARGET(mic) void nrand(T& a) { static const double scale = 1.0 / RAND_MAX; a = static_cast<T>(scale * (2 * std::rand() - RAND_MAX)); } template<typename T> LIBXSMM_TARGET(mic) void add(T *LIBXSMM_RESTRICT dst, const T *LIBXSMM_RESTRICT c, int m, int n, int ldc) { #if (0 < LIBXSMM_ALIGNED_STORES) LIBXSMM_ASSUME_ALIGNED(c, SMM_ALIGNMENT); #endif for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { #if (0 != LIBXSMM_ROW_MAJOR) const T value = c[i*ldc+j]; #else const T value = c[j*ldc+i]; #endif #if defined(_OPENMP) # pragma omp atomic #endif #if (0 != LIBXSMM_ROW_MAJOR) dst[i*n+j] += value; #else dst[j*m+i] += value; #endif } } } template<typename T> LIBXSMM_TARGET(mic) double max_diff(const T *LIBXSMM_RESTRICT result, const T *LIBXSMM_RESTRICT expect, int m, int n, int ldc) { double diff = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { #if (0 != LIBXSMM_ROW_MAJOR) const int k = i * ldc + j; #else const int k = j * ldc + i; #endif diff = std::max(diff, std::abs(static_cast<double>(result[k]) - static_cast<double>(expect[k]))); } } return diff; } int main(int argc, char* argv[]) { try { typedef double T; const int default_psize = (SMM_MIN_NPARALLEL) * (SMM_MIN_NLOCAL), default_batch = SMM_MIN_NLOCAL; const int m = 1 < argc ? std::atoi(argv[1]) : 23; const int s = 2 < argc ? (0 < std::atoi(argv[2]) ? std::atoi(argv[2]) : ('+' == *argv[2] ? (default_psize << std::strlen(argv[2])) : ('-' == *argv[2] ? (default_psize >> std::strlen(argv[2])) : default_psize))) : default_psize; const int t = 3 < argc ? (0 < std::atoi(argv[3]) ? std::atoi(argv[3]) : ('+' == *argv[3] ? (default_batch << std::strlen(argv[3])) : ('-' == *argv[3] ? (default_batch >> std::strlen(argv[3])) : -1))) : -1; const int n = 4 < argc ? std::atoi(argv[4]) : m; const int k = 5 < argc ? std::atoi(argv[5]) : m; if ((SMM_MAX_PROBLEM_SIZE) < (m * n * k)) { throw std::runtime_error("The size M x N x K is exceeding SMM_MAX_PROBLEM_SIZE!"); } #if (0 != LIBXSMM_ROW_MAJOR) # if (0 < LIBXSMM_ALIGNED_STORES) const int ldc = LIBXSMM_ALIGN_VALUE(int, T, n, LIBXSMM_ALIGNED_STORES); # else const int ldc = n; # endif const int csize = m * ldc; #else # if (0 < LIBXSMM_ALIGNED_STORES) const int ldc = LIBXSMM_ALIGN_VALUE(int, T, m, LIBXSMM_ALIGNED_STORES); # else const int ldc = m; # endif const int csize = n * ldc; #endif const int asize = m * k, bsize = k * n; std::vector<T> va(s * asize), vb(s * bsize), vc(csize); std::for_each(va.begin(), va.end(), nrand<T>); std::for_each(vb.begin(), vb.end(), nrand<T>); const T *const a = &va[0], *const b = &vb[0]; T * /*const*/ c = &vc[0]; #if defined(LIBXSMM_OFFLOAD) # pragma offload target(mic) in(a: length(s * asize)) in(b: length(s * bsize)) out(c: length(csize)) #endif { const double mbytes = 1.0 * s * (asize + bsize) * sizeof(T) / (1024 * 1024); #if defined(_OPENMP) const double nbytes = 1.0 * s * (csize) * sizeof(T) / (1024 * 1024); const double gflops = 2.0 * s * m * n * k * 1E-9; const int u = 0 < t ? t : static_cast<int>(std::sqrt(static_cast<double>(s * SMM_MIN_NLOCAL) / SMM_MIN_NPARALLEL) + 0.5); #else const int u = t; #endif #if defined(SMM_CHECK) std::vector<T> expect(csize); #endif fprintf(stdout, "m=%i n=%i k=%i ldc=%i size=%i batch=%i memory=%.1f MB\n\n", m, n, k, ldc, s, u, mbytes); { // LAPACK/BLAS3 (fallback) fprintf(stdout, "LAPACK/BLAS...\n"); std::fill_n(c, csize, 0); #if defined(_OPENMP) const double start = omp_get_wtime(); # pragma omp parallel for schedule(SMM_SCHEDULE) #endif for (int i = 0; i < s; i += u) { LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT); for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear for (int j = 0; j < LIBXSMM_MIN(u, s - i); ++j) { libxsmm_blasmm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp); } add(c, tmp, m, n, ldc); // atomic } #if defined(_OPENMP) const double duration = omp_get_wtime() - start; if (0 < duration) { fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration); fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration); } fprintf(stdout, "\tduration: %.1f s\n", duration); #endif #if defined(SMM_CHECK) std::copy(c, c + csize, expect.begin()); #endif } { // inline an optimized implementation fprintf(stdout, "Inlined...\n"); std::fill_n(c, csize, 0); #if defined(_OPENMP) const double start = omp_get_wtime(); # pragma omp parallel for schedule(SMM_SCHEDULE) #endif for (int i = 0; i < s; i += u) { LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT); for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear for (int j = 0; j < LIBXSMM_MIN(u, s - i); ++j) { libxsmm_imm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp); } add(c, tmp, m, n, ldc); // atomic } #if defined(_OPENMP) const double duration = omp_get_wtime() - start; if (0 < duration) { fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration); fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration); } fprintf(stdout, "\tduration: %.1f s\n", duration); #endif #if defined(SMM_CHECK) fprintf(stdout, "\tdiff=%f\n", max_diff(c, &expect[0], m, n, ldc)); #endif } { // auto-dispatched fprintf(stdout, "Dispatched...\n"); //libxsmm_mm(1, 1, 1, &a[0], &b[0], &c[0]); // warmup/workaround std::fill_n(c, csize, 0); #if defined(_OPENMP) const double start = omp_get_wtime(); # pragma omp parallel for schedule(SMM_SCHEDULE) #endif for (int i = 0; i < s; i += u) { LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT); for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear for (int j = 0; j < LIBXSMM_MIN(u, s - i); ++j) { libxsmm_mm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp); } add(c, tmp, m, n, ldc); // atomic } #if defined(_OPENMP) const double duration = omp_get_wtime() - start; if (0 < duration) { fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration); fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration); } fprintf(stdout, "\tduration: %.1f s\n", duration); #endif #if defined(SMM_CHECK) fprintf(stdout, "\tdiff=%f\n", max_diff(c, &expect[0], m, n, ldc)); #endif } const libxsmm_mm_dispatch<T> xmm(m, n, k); if (xmm) { // specialized routine fprintf(stdout, "Specialized...\n"); std::fill_n(c, csize, 0); #if defined(_OPENMP) const double start = omp_get_wtime(); # pragma omp parallel for schedule(SMM_SCHEDULE) #endif for (int i = 0; i < s; i += u) { LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT); for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear for (int j = 0; j < LIBXSMM_MIN(u, s - i); ++j) { xmm(&a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp); } add(c, tmp, m, n, ldc); // atomic } #if defined(_OPENMP) const double duration = omp_get_wtime() - start; if (0 < duration) { fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration); fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration); } fprintf(stdout, "\tduration: %.1f s\n", duration); #endif #if defined(SMM_CHECK) fprintf(stdout, "\tdiff=%f\n", max_diff(c, &expect[0], m, n, ldc)); #endif } fprintf(stdout, "Finished\n"); } } catch(const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return EXIT_FAILURE; } catch(...) { fprintf(stderr, "Error: unknown exception caught!\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "CameraMode.h" CameraMode::CameraMode(UI& _ui) : ui(_ui) { coarsePositionStep = 20; finePositionStep = 4; coarseAngleStep = 5; fineAngleStep = 1; camera = nullptr; ofLog() << "camera init"; } ofCamera* CameraMode::getCamera(){ return camera; } void CameraMode::setCamera(ofCamera& cam){ camera = &cam; } void CameraMode::action(char key){ switch(key){ case KUIKey::Esc: ui.setMode(KUIMode::NORMAL); break; // Positions case 'd': camera->boom(getPositionStep()); break; case 's': camera->boom(-getPositionStep()); break; case 'z': camera->dolly(-getPositionStep()); break; case 'x': camera->dolly(getPositionStep()); break; case 'f': camera->truck(getPositionStep()); break; case 'a': camera->truck(-getPositionStep()); break; // Rotations case 'l': camera->rotateAround(-getAngleStep(), camera->getXAxis(), ofVec3f(0, 0, 0)); camera->lookAt(ofVec3f(0, 0, 0)); break; case 'k': camera->rotateAround(getAngleStep(), camera->getXAxis(), ofVec3f(0, 0, 0)); camera->lookAt(ofVec3f(0, 0, 0)); break; case 'j': camera->rotateAround(-getAngleStep(), ofVec3f(0, 1, 0), ofVec3f(0, 0, 0)); camera->lookAt(ofVec3f(0, 0, 0)); break; case ';': camera->rotateAround(getAngleStep(), ofVec3f(0, 1, 0), ofVec3f(0, 0, 0)); camera->lookAt(ofVec3f(0, 0, 0)); break; case KUIKey::Space: ui.toggleAdjustment(); break; } } float CameraMode::getPositionStep(){ if(ui.getAdjustment() == KUIAdjust::COARSE){ return coarsePositionStep; } else{ return finePositionStep; } } float CameraMode::getAngleStep(){ if(ui.getAdjustment() == KUIAdjust::COARSE){ return coarseAngleStep; } else{ return fineAngleStep; } }<commit_msg>Change key for qwerty keyboard<commit_after>#include "CameraMode.h" CameraMode::CameraMode(UI& _ui) : ui(_ui) { coarsePositionStep = 20; finePositionStep = 4; coarseAngleStep = 5; fineAngleStep = 1; camera = nullptr; ofLog() << "camera init"; } ofCamera* CameraMode::getCamera(){ return camera; } void CameraMode::setCamera(ofCamera& cam){ camera = &cam; } void CameraMode::action(char key){ switch(key){ case KUIKey::Esc: ui.setMode(KUIMode::NORMAL); break; // Positions case 'd': camera->boom(getPositionStep()); break; case 's': camera->boom(-getPositionStep()); break; case 'w': camera->dolly(-getPositionStep()); break; case 'x': camera->dolly(getPositionStep()); break; case 'f': camera->truck(getPositionStep()); break; case 'a': camera->truck(-getPositionStep()); break; // Rotations case 'l': camera->rotateAround(-getAngleStep(), camera->getXAxis(), ofVec3f(0, 0, 0)); camera->lookAt(ofVec3f(0, 0, 0)); break; case 'k': camera->rotateAround(getAngleStep(), camera->getXAxis(), ofVec3f(0, 0, 0)); camera->lookAt(ofVec3f(0, 0, 0)); break; case 'j': camera->rotateAround(-getAngleStep(), ofVec3f(0, 1, 0), ofVec3f(0, 0, 0)); camera->lookAt(ofVec3f(0, 0, 0)); break; case ';': camera->rotateAround(getAngleStep(), ofVec3f(0, 1, 0), ofVec3f(0, 0, 0)); camera->lookAt(ofVec3f(0, 0, 0)); break; case KUIKey::Space: ui.toggleAdjustment(); break; } } float CameraMode::getPositionStep(){ if(ui.getAdjustment() == KUIAdjust::COARSE){ return coarsePositionStep; } else{ return finePositionStep; } } float CameraMode::getAngleStep(){ if(ui.getAdjustment() == KUIAdjust::COARSE){ return coarseAngleStep; } else{ return fineAngleStep; } }<|endoftext|>
<commit_before>/* * Connection.cpp * * Created on: Apr 11, 2015 * Author: jonno */ #include "Connection.h" #include "Constants.h" #include <iostream> using namespace std; Connection::Connection(ConnectionData* connection) { mConnectionData = connection; } void Connection::handleConnection() { int sock = mConnectionData->socket; sockaddr_in client = mConnectionData->client; mSock = std::make_shared<Socket>(sock); if (!this->receiveGreeting()) { return; } RequestDetails request; if (!this->handleRequest(request)) { return; } // Try to connect. auto outSock = setupForwardConnection(request); if (outSock == nullptr) { return; } this->relayTraffic(outSock); } bool Connection::verifyVersion(bytes greeting) { if (greeting.size() >= 1) { return verifySOCKSVersion(greeting[0]); } return false; } bool Connection::verifySOCKSVersion(char version) { if (version != Constants::SOCKS::Version::V5) { cerr << "Invalid SOCKS Version." << endl; return false; } return true; } bool Connection::checkAuthentication() { bytes methods; if (!mSock->receive(methods, 1)) { return false; } if (!mSock->receive(methods, methods[1])) { return false; } bool allowsNoAuth = false; for (unsigned int i = 0; i < methods.size(); ++i) { if (methods[i] == Constants::SOCKS::Authentication::NoAuth) allowsNoAuth = true; } if (!allowsNoAuth) { cerr << "Client doesn't support unauthenticated sessions." << endl; // socks V5, no auth methods mSock->send(hexBytes("05FF")); return false; } // cerr << "Using NoAuth" << endl; mSock->send(hexBytes("0500")); return true; } bool Connection::receiveGreeting() { bytes version; if (!mSock->receive(version, 1)) { cerr << "Could not read the SOCKS version" << endl; return false; } if (!this->verifyVersion(version)) { return false; } if (!this->checkAuthentication()) { return false; } return true; } bool Connection::handleRequest(RequestDetails& request) { bytes header; if (!mSock->receive(header, 4)) { return false; } if (header.size() != 4) { return false; } this->verifySOCKSVersion(header[0]); // We only support TCP CONNECT, so fail other commands. if (header[1] != Constants::SOCKS::Command::TCPConnection) { // Unsupported command. cerr << "Unsupported command." << endl; // TODO: fix this trash mSock->send(hexBytes("050200010000000000")); return false; } // header[2] is 0x00 - reserved bytes address; AddressType addressType; // Get the type of address they want to connect to. switch (header[3]) { case Constants::IP::Type::IPV4: { addressType = IPV4_ADDRESS; mSock->receive(address, Constants::IP::Length::IPV4); } break; case Constants::IP::Type::Domain: { addressType = DOMAIN_ADDRESS; bytes len; // get length of domain name mSock->receive(len, 1); // get domain name mSock->receive(address, len[0]); } break; case Constants::IP::Type::IPV6: { addressType = IPV6_ADDRESS; mSock->receive(address, Constants::IP::Length::IPV6); } break; default: cerr << "Invalid address type." << endl; // TODO: Fix this trash mSock->send(hexBytes("050200010000000000")); return false; } // Get the port. bytes rawPort; if (!mSock->receive(rawPort, 2)) { cerr << "Could not read the port" << endl; return false; } unsigned char h = rawPort[0]; unsigned char l = rawPort[1]; int port = (h << 8) + l; request.port = port; request.address = address; request.addressType = addressType; return true; } std::shared_ptr<Socket> Connection::setupForwardConnection(const RequestDetails& request) { bool connected = false; auto outSock = std::make_shared<Socket>(); switch (request.addressType) { case IPV4_ADDRESS: connected = outSock->connect4(request.address, request.port); break; case IPV6_ADDRESS: connected = outSock->connect6(request.address, request.port); break; case DOMAIN_ADDRESS: connected = outSock->connect(request.address, request.port); break; default: cerr << "No connection type specified." << endl; break; } // Send reply. // This is wrong - the address & port should be the local address of outSock on the server. // Not sure why the client would need this, so I'm just going for 0s. if (connected) { cerr << "Connected!" << endl; mSock->send(hexBytes("050000") + hexBytes("01cb007101abab")); } else { cerr << "Connection failed." << endl; mSock->send(hexBytes("050400") + hexBytes("01cb007101abab")); // Host unreachable. return nullptr; } return outSock; } void Connection::relayTraffic(std::shared_ptr<Socket> outSock) { pollfd polls[2]; polls[0].fd = mSock->descriptor(); polls[0].events = POLLIN; // Listen for data availability. polls[0].revents = 0; polls[1].fd = outSock->descriptor(); // Will be the output socket. polls[1].events = POLLIN; polls[1].revents = 0; while (true) { int ret = poll(polls, 2, 60000); if (ret == -1) { cerr << strerror(errno) << endl; break; } if (ret == 0) { // cerr << "No data (timeout)" << endl; break; } if (polls[0].revents & POLLIN) { bytes data; if (!mSock->receive(data)) { // cerr << "Read error: " << strerror(errno) << endl; break; } if (data.empty()) { // cerr << "Read EOF." << endl; break; } if (!outSock->send(data)) { // cerr << "Write error: " << strerror(errno) << endl; } } if (polls[1].revents & POLLIN) { bytes data; if (!outSock->receive(data)) { // cerr << "Read error: " << strerror(errno) << endl; break; } if (data.empty()) { // cerr << "Read EOF." << endl; break; } if (!mSock->send(data)) { // cerr << "Write error: " << strerror(errno) << endl; } } if ((polls[0].revents & (POLLHUP | POLLNVAL | POLLERR)) || (polls[1].revents & (POLLHUP | POLLNVAL | POLLERR)) ) { // cerr << "Connection finished." << endl; // Could be an error... break; } } } Connection::~Connection() { //delete mConnectionData; } <commit_msg>Terminated if version was incorrect.<commit_after>/* * Connection.cpp * * Created on: Apr 11, 2015 * Author: jonno */ #include "Connection.h" #include "Constants.h" #include <iostream> using namespace std; Connection::Connection(ConnectionData* connection) { mConnectionData = connection; } void Connection::handleConnection() { int sock = mConnectionData->socket; sockaddr_in client = mConnectionData->client; mSock = std::make_shared<Socket>(sock); if (!this->receiveGreeting()) { return; } RequestDetails request; if (!this->handleRequest(request)) { return; } // Try to connect. auto outSock = setupForwardConnection(request); if (outSock == nullptr) { return; } this->relayTraffic(outSock); } bool Connection::verifyVersion(bytes greeting) { if (greeting.size() >= 1) { return verifySOCKSVersion(greeting[0]); } return false; } bool Connection::verifySOCKSVersion(char version) { if (version != Constants::SOCKS::Version::V5) { cerr << "Invalid SOCKS Version." << endl; return false; } return true; } bool Connection::checkAuthentication() { bytes methods; if (!mSock->receive(methods, 1)) { return false; } if (!mSock->receive(methods, methods[1])) { return false; } bool allowsNoAuth = false; for (unsigned int i = 0; i < methods.size(); ++i) { if (methods[i] == Constants::SOCKS::Authentication::NoAuth) allowsNoAuth = true; } if (!allowsNoAuth) { cerr << "Client doesn't support unauthenticated sessions." << endl; // socks V5, no auth methods mSock->send(hexBytes("05FF")); return false; } // cerr << "Using NoAuth" << endl; mSock->send(hexBytes("0500")); return true; } bool Connection::receiveGreeting() { bytes version; if (!mSock->receive(version, 1)) { cerr << "Could not read the SOCKS version" << endl; return false; } if (!this->verifyVersion(version)) { return false; } if (!this->checkAuthentication()) { return false; } return true; } bool Connection::handleRequest(RequestDetails& request) { bytes header; if (!mSock->receive(header, 4)) { return false; } if (header.size() != 4) { return false; } if (!this->verifySOCKSVersion(header[0])) { return false; } // We only support TCP CONNECT, so fail other commands. if (header[1] != Constants::SOCKS::Command::TCPConnection) { // Unsupported command. cerr << "Unsupported command." << endl; // TODO: fix this trash mSock->send(hexBytes("050200010000000000")); return false; } // header[2] is 0x00 - reserved bytes address; AddressType addressType; // Get the type of address they want to connect to. switch (header[3]) { case Constants::IP::Type::IPV4: { addressType = IPV4_ADDRESS; mSock->receive(address, Constants::IP::Length::IPV4); } break; case Constants::IP::Type::Domain: { addressType = DOMAIN_ADDRESS; bytes len; // get length of domain name mSock->receive(len, 1); // get domain name mSock->receive(address, len[0]); } break; case Constants::IP::Type::IPV6: { addressType = IPV6_ADDRESS; mSock->receive(address, Constants::IP::Length::IPV6); } break; default: cerr << "Invalid address type." << endl; // TODO: Fix this trash mSock->send(hexBytes("050200010000000000")); return false; } // Get the port. bytes rawPort; if (!mSock->receive(rawPort, 2)) { cerr << "Could not read the port" << endl; return false; } unsigned char h = rawPort[0]; unsigned char l = rawPort[1]; int port = (h << 8) + l; request.port = port; request.address = address; request.addressType = addressType; return true; } std::shared_ptr<Socket> Connection::setupForwardConnection(const RequestDetails& request) { bool connected = false; auto outSock = std::make_shared<Socket>(); switch (request.addressType) { case IPV4_ADDRESS: connected = outSock->connect4(request.address, request.port); break; case IPV6_ADDRESS: connected = outSock->connect6(request.address, request.port); break; case DOMAIN_ADDRESS: connected = outSock->connect(request.address, request.port); break; default: cerr << "No connection type specified." << endl; break; } // Send reply. // This is wrong - the address & port should be the local address of outSock on the server. // Not sure why the client would need this, so I'm just going for 0s. if (connected) { cerr << "Connected!" << endl; mSock->send(hexBytes("050000") + hexBytes("01cb007101abab")); } else { cerr << "Connection failed." << endl; mSock->send(hexBytes("050400") + hexBytes("01cb007101abab")); // Host unreachable. return nullptr; } return outSock; } void Connection::relayTraffic(std::shared_ptr<Socket> outSock) { pollfd polls[2]; polls[0].fd = mSock->descriptor(); polls[0].events = POLLIN; // Listen for data availability. polls[0].revents = 0; polls[1].fd = outSock->descriptor(); // Will be the output socket. polls[1].events = POLLIN; polls[1].revents = 0; while (true) { int ret = poll(polls, 2, 60000); if (ret == -1) { cerr << strerror(errno) << endl; break; } if (ret == 0) { // cerr << "No data (timeout)" << endl; break; } if (polls[0].revents & POLLIN) { bytes data; if (!mSock->receive(data)) { // cerr << "Read error: " << strerror(errno) << endl; break; } if (data.empty()) { // cerr << "Read EOF." << endl; break; } if (!outSock->send(data)) { // cerr << "Write error: " << strerror(errno) << endl; } } if (polls[1].revents & POLLIN) { bytes data; if (!outSock->receive(data)) { // cerr << "Read error: " << strerror(errno) << endl; break; } if (data.empty()) { // cerr << "Read EOF." << endl; break; } if (!mSock->send(data)) { // cerr << "Write error: " << strerror(errno) << endl; } } if ((polls[0].revents & (POLLHUP | POLLNVAL | POLLERR)) || (polls[1].revents & (POLLHUP | POLLNVAL | POLLERR)) ) { // cerr << "Connection finished." << endl; // Could be an error... break; } } } Connection::~Connection() { //delete mConnectionData; } <|endoftext|>
<commit_before>#include <iostream> #include <unistd.h> #include <sys/stat.h> #include <stdio.h> #include <vector> #include <sstream> #include <dirent.h> #include <errno.h> #include <sys/types.h> using namespace std; bool isDirectory(char* directoryName) { struct stat directoryInCurrent; if (-1 == (stat(directoryName, &directoryInCurrent))) { perror("stat failed"); return false; } if (directoryInCurrent.st_mode & S_IFDIR) { return true; } else { return false; } } int ls(char* directoryName) { char const *dirName = "."; DIR *dirp; if (!(dirp = opendir(dirName))) { cerr << "Error(" << errno << ") opening " << dirName << endl; } dirent *direntp; while ((direntp = readdir(dirp))) { if (direntp->d_name[0] != '.') { //cout << direntp->d_name << endl; // use stat here to find attributes of a file printf(direntp->d_name, 8); cout << " "; } } cout << endl; closedir(dirp); return 0; } int lsWithFlags(char* directoryName, vector<string> flags) { bool isA = false; bool isL = false; bool isR = false; for (unsigned i = 0; i < flags.size(); ++i) { for (unsigned k = 0; k < flags.at(i).size(); ++k) { if (flags.at(i).at(k) == 'a') isA = true; else if (flags.at(i).at(k) == 'l') isL = true; else if (flags.at(i).at(k) == 'R') isR = true; } } char const *dirName = directoryName; DIR *dirp; if (!(dirp = opendir(dirName))) { cerr << "Error(" << errno << ") opening " << dirName << endl; return errno; } dirent *direntp; if (isA) { while ((direntp = readdir(dirp))) { //cout << direntp->d_name << endl; // use stat here to find attributes of a file printf(direntp->d_name, 8); cout << " "; } } cout << endl; closedir(dirp); return 0; } int main(int argc, char* argv[]) { if (argc == 1) { if (errno == ls(".")) { return errno; } } else { vector<string> directories; vector<string> flags; vector<int> directoryIndex; bool directoryInArgv = false; for (int i = 1; i < argc; ++i) { if (isDirectory(argv[i])) { directoryInArgv = true; break; } else { if (argv[i][0] == '-') { flags.push_back(argv[i]); } } } if (!directoryInArgv) { if (errno == lsWithFlags(".", flags)) { return errno; } } else { for (int i = 0; i < argc; ++i) { if (isDirectory(argv[i])) { directories.push_back(argv[i]); directoryIndex.push_back(i); } } cout << "directories size: " << endl; for (unsigned int i = 0; i < directories.size(); ++i) { flags.clear(); for (unsigned int k = static_cast<unsigned>(directoryIndex.at(i)); (i + 1) < directoryIndex.size() && k != (unsigned)directoryIndex.at(i + 1); ++k) { if (argv[k][0] == '-') { flags.push_back(argv[k]); } } char* directoryName = new char[directories.at(i).size() + 1]; strcpy(directoryName, directories.at(i).c_str()); if (errno == lsWithFlags(directoryName, flags)) { return errno; } } } } } <commit_msg>changed conditions for boolean variables in lswithflags function<commit_after>#include <iostream> #include <unistd.h> #include <sys/stat.h> #include <stdio.h> #include <vector> #include <sstream> #include <dirent.h> #include <errno.h> #include <sys/types.h> using namespace std; bool isDirectory(char* directoryName) { struct stat directoryInCurrent; if (-1 == (stat(directoryName, &directoryInCurrent))) { perror("stat failed"); return false; } if (directoryInCurrent.st_mode & S_IFDIR) { return true; } else { return false; } } int ls(char* directoryName) { char const *dirName = "."; DIR *dirp; if (!(dirp = opendir(dirName))) { cerr << "Error(" << errno << ") opening " << dirName << endl; } dirent *direntp; while ((direntp = readdir(dirp))) { if (direntp->d_name[0] != '.') { //cout << direntp->d_name << endl; // use stat here to find attributes of a file printf(direntp->d_name, 8); cout << " "; } } cout << endl; closedir(dirp); return 0; } int lsWithFlags(char* directoryName, vector<string> flags) { bool isA = false; bool isL = false; bool isR = false; for (unsigned i = 0; i < flags.size(); ++i) { for (unsigned k = 0; k < flags.at(i).size(); ++k) { if (flags.at(i).at(k) == 'a') isA = true; else if (flags.at(i).at(k) == 'l') isL = true; else if (flags.at(i).at(k) == 'R') isR = true; } } char const *dirName = directoryName; DIR *dirp; if (!(dirp = opendir(dirName))) { cerr << "Error(" << errno << ") opening " << dirName << endl; return errno; } dirent *direntp; if (isA) { while ((direntp = readdir(dirp))) { //cout << direntp->d_name << endl; // use stat here to find attributes of a file printf(direntp->d_name, 8); cout << " "; } } cout << endl; closedir(dirp); return 0; } int main(int argc, char* argv[]) { if (argc == 1) { if (errno == ls(".")) { return errno; } } else { vector<string> directories; vector<string> flags; vector<int> directoryIndex; bool directoryInArgv = false; for (int i = 1; i < argc; ++i) { if (isDirectory(argv[i])) { directoryInArgv = true; break; } else { if (argv[i][0] == '-') { flags.push_back(argv[i]); } } } if (!directoryInArgv) { if (errno == lsWithFlags(".", flags)) { return errno; } } else { for (int i = 0; i < argc; ++i) { if (isDirectory(argv[i])) { directories.push_back(argv[i]); directoryIndex.push_back(i); } } cout << "directories size: " << directories.size() << endl; for (unsigned int i = 0; i < directories.size(); ++i) { flags.clear(); for (unsigned int k = static_cast<unsigned>(directoryIndex.at(i)); (i + 1) < directoryIndex.size() && k != (unsigned)directoryIndex.at(i + 1); ++k) { if (argv[k][0] == '-') { flags.push_back(argv[k]); } } char* directoryName = new char[directories.at(i).size() + 1]; strcpy(directoryName, directories.at(i).c_str()); if (errno == lsWithFlags(directoryName, flags)) { return errno; } } } } } <|endoftext|>
<commit_before>#include <algorithm> #include <cstdlib> #include <stdio.h> #include <iomanip> #include <sys/types.h> #include <unistd.h> #include <dirent.h> #include <errno.h> #include <vector> #include <string> #include <iostream> #include "alphanum.hpp" #define IMPROPER_FLAGS 1 #define FAILURE_EXIT 2 #define LINE_SIZE 80 using namespace std; /* GLOBAL OPTIONS */ bool show_hidden = false; // -a bool long_listing_format = false; // -l bool recursive = false; // -R // a vector of files, in sorted order vector<string> sorted_files; //isHidden: a helper function to std::remove_if to determine // if a file in the vector is a hidden file bool isHidden (string s) { return (s[0] == '.'); } //set_flags: sets the various global options according to // the flags passed in by the user. Returns the // index of the first non-option argument. int set_flags (int, char**); //get_files: populates sorted_files with the files, in order, // ready for printing, that readdir returns. void get_files (int, char**, int); //sort_files: sorts the files in sorted_files, readying them // for printing void sort_files (); //usage_error: attempts to print a helpful error message to the user // should they try something illegal void usage_error (int); //display: prints the selected version of ls to the console. // Takes the index of the first non-option argument; // assumes that options have been moved to the front. void display (int, char**, int); //print_basic: prints the formatted sorted list to the console void print_basic (); main (int argc, char** argv) { int idx = set_flags (argc, argv); //flags will be moved to beginning of argv get_files (argc, argv, idx); sort_files (); display (argc, argv, idx); return 0; } int set_flags (int argc, char** argv) { int count = 0; //opterr = 0; //write our own warnings while (1) { int c = getopt (argc, argv, "alR"); //magic! if (c == -1) break; ++count; switch (c) { case 'a': show_hidden = true; break; case 'l': long_listing_format = true; break; case 'R': recursive = true; break; default: usage_error (IMPROPER_FLAGS); } } return ++count; //index of first non-option argument } void usage_error (int err) { switch (err) { case IMPROPER_FLAGS: cerr << "Please enter valid flags." << endl; break; default: cerr << "An unknown error occurred. Sorry!" << endl; } exit (-1); //mirror ls behavior: if any flags fail, do not print } void display (int argc, char** argv, int idx) { if (show_hidden && !long_listing_format && !recursive) // -a { cout << "-a" << endl; print_basic (); } else if (!show_hidden && long_listing_format && !recursive) // -l { cout << "-l" << endl; } else if (!show_hidden && !long_listing_format && recursive) // -R { cout << "R" << endl; } else if (show_hidden && long_listing_format && !recursive) // -al { cout << "al" << endl; } else if (show_hidden && !long_listing_format && recursive) // -aR { cout << "aR" << endl; } else if (!show_hidden && long_listing_format && recursive) // -lR { cout << "lR" << endl; } else if (show_hidden && long_listing_format && recursive) // -alR { cout << "alR" << endl; } else { cout << "default ls" << endl; print_basic (); } } void get_files (int argc, char** argv, int idx) { while (idx < argc) { const char *dirname = argv[idx]; DIR *dirp = opendir (dirname); if (!dirp) { perror("opendir"); exit(-1); } dirent *direntp; while ((direntp = readdir (dirp))) { if (direntp == NULL) { perror("readdir"); exit(-1); } string file_name (direntp->d_name); sorted_files.push_back (file_name); } if ((closedir (dirp)) == -1) { perror("closedir"); exit(-1); } ++idx; } if (!show_hidden) { sorted_files.erase (remove_if (sorted_files.begin(), sorted_files.end(), isHidden)); } } void sort_files () { //TODO: think about implementing a natural sorting algorithm // to match the behavior of the original ls. // ASCIIbetical sort sucks... sort (sorted_files.begin(), sorted_files.end()); } void print_basic () { string printed = ""; for (int i = 0; i < sorted_files.size(); ++i) { printed += (sorted_files[i] + " "); if (printed.length() >= LINE_SIZE) { cout << endl; printed = ""; printed += (sorted_files[i] + " "); } cout << sorted_files[i] << " "; } cout << endl; } <commit_msg>made ls (no args) work, implemented Result class<commit_after>#include <algorithm> #include <cstdlib> #include <stdio.h> #include <iomanip> #include <sys/types.h> #include <unistd.h> #include <dirent.h> #include <errno.h> #include <vector> #include <string> #include <sys/stat.h> #include <iostream> #include "alphanum.hpp" #define IMPROPER_FLAGS 1 #define FAILURE_EXIT 2 #define LINE_SIZE 80 using namespace std; /* GLOBAL OPTIONS */ bool show_hidden = false; // -a bool long_listing_format = false; // -l bool recursive = false; // -R // a vector of files, in sorted order vector<string> sorted_files; // a vector of files, in sorted order, with long_listing data vector<string> sorted_files_long; class Result { public: string type; string permissions; int links; string owner; string group_owner; int bytes_size; string time_last_mod; string filename; //constructors Result () {}; //methods void print_basic () { //print basic ls cout << filename << " "; } void print_basic_hidden () { ; } void print_long_format () { //print -l ls cout << type << permissions << " " << links << " " << owner << " " << group_owner << " " << bytes_size << " " << time_last_mod << " " << filename << endl; } }; // a vector of Results; data from stat vector<Result> results; bool result_sort (Result i, Result j) { return (i.filename < j.filename); } //isHidden: a helper function to std::remove_if to determine // if a file in the vector is a hidden file bool isHidden (Result s) { return (s.filename.at(0) == '.'); } //set_flags: sets the various global options according to // the flags passed in by the user. Returns the // index of the first non-option argument. int set_flags (int, char**); //get_files: populates sorted_files with the files, in order, // ready for printing, that readdir returns. void get_files (int, char**, int); //sort_files: sorts the files in sorted_files, readying them // for printing void sort_files (); //usage_error: attempts to print a helpful error message to the user // should they try something illegal void usage_error (int); //display: prints the selected version of ls to the console. // Takes the index of the first non-option argument; // assumes that options have been moved to the front. void display (int, char**, int); //print_basic: prints the formatted sorted list to the console void print_basic (); //print_long_listing: prints the sorted list, in long-listing format void print_long_listing (); main (int argc, char** argv) { int idx = set_flags (argc, argv); //flags will be moved to beginning of argv get_files (argc, argv, idx); sort_files (); display (argc, argv, idx); return 0; } int set_flags (int argc, char** argv) { int count = 0; //opterr = 0; //write our own warnings while (1) { int c = getopt (argc, argv, "alR"); //magic! if (c == -1) break; ++count; switch (c) { case 'a': show_hidden = true; break; case 'l': long_listing_format = true; break; case 'R': recursive = true; break; default: usage_error (IMPROPER_FLAGS); } } return ++count; //index of first non-option argument } void usage_error (int err) { switch (err) { case IMPROPER_FLAGS: cerr << "Please enter valid flags." << endl; break; default: cerr << "An unknown error occurred. Sorry!" << endl; } exit (-1); //mirror ls behavior: if any flags fail, do not print } void display (int argc, char** argv, int idx) { //TODO: implement this logic: // show_hidden is no longer necessary. I will just remove them // from the results vector if they don't need to be displayed. if (show_hidden && !long_listing_format && !recursive) // -a { cout << "-a" << endl; print_basic (); } else if (!show_hidden && long_listing_format && !recursive) // -l { cout << "-l" << endl; for (int i = 0; i < results.size(); ++i) { results[i].print_long_format (); } } else if (!show_hidden && !long_listing_format && recursive) // -R { cout << "R" << endl; } else if (show_hidden && long_listing_format && !recursive) // -al { cout << "al" << endl; } else if (show_hidden && !long_listing_format && recursive) // -aR { cout << "aR" << endl; } else if (!show_hidden && long_listing_format && recursive) // -lR { cout << "lR" << endl; } else if (show_hidden && long_listing_format && recursive) // -alR { cout << "alR" << endl; } else { cout << "default ls" << endl; for (int i = 0; i < results.size(); ++i) { results[i].print_basic (); } cout << endl; } } void get_files (int argc, char** argv, int idx) { //if the user just enters ls and no directory, it's non-functional if (idx == argc) { const char *dirname = "."; DIR *dirp = opendir (dirname); if (!dirp) { perror("opendir"); exit(-1); } dirent *direntp; while ((direntp = readdir (dirp))) { if (direntp == NULL) { perror("readdir"); exit(-1); } string file_name (direntp->d_name); sorted_files.push_back (file_name); Result temp; struct stat sb; int err = stat((file_name).c_str(), &sb); if (err == -1) { perror("stat"); exit(-1); } if (!show_hidden && file_name.at(0) == '.') continue; //populate the temp object, then push it to the vector if (S_ISREG (sb.st_mode)) { temp.type = "-"; } else if (S_ISDIR (sb.st_mode)) { temp.type = "d"; } else if (S_ISCHR (sb.st_mode)) { temp.type = "c"; } else if (S_ISBLK (sb.st_mode)) { temp.type = "b"; } else if (S_ISFIFO (sb.st_mode)) { temp.type = "p"; } else if (S_ISLNK (sb.st_mode)) { temp.type = "l"; } else if (S_ISSOCK (sb.st_mode)) { temp.type = "s"; } else { temp.type = "-"; } string permissions = ""; if (sb.st_mode & S_IRUSR) { permissions += "r"; } else { permissions += "-"; } if (sb.st_mode & S_IWUSR) { permissions += "w"; } else { permissions += "-"; } if (sb.st_mode & S_IXUSR) { permissions += "x"; } else { permissions += "-"; } if (sb.st_mode & S_IRGRP) { permissions += "r"; } else { permissions += "-"; } if (sb.st_mode & S_IWGRP) { permissions += "w"; } else { permissions += "-"; } if (sb.st_mode & S_IXGRP) { permissions += "x"; } else { permissions += "-"; } if (sb.st_mode & S_IROTH) { permissions += "r"; } else { permissions += "-"; } if (sb.st_mode & S_IWOTH) { permissions += "w"; } else { permissions += "-"; } if (sb.st_mode & S_IXOTH) { permissions += "x"; } else { permissions += "-"; } temp.permissions = permissions; temp.links = sb.st_nlink; temp.owner = sb.st_uid; temp.group_owner = sb.st_gid; temp.bytes_size = sb.st_size; temp.time_last_mod = sb.st_mtime; temp.filename = file_name; results.push_back (temp); } if ((closedir (dirp)) == -1) { perror("closedir"); exit(-1); } } while (idx < argc) { const char *dirname = argv[idx]; DIR *dirp = opendir (dirname); if (!dirp) { perror("opendir"); exit(-1); } dirent *direntp; while ((direntp = readdir (dirp))) { if (direntp == NULL) { perror("readdir"); exit(-1); } string file_name (direntp->d_name); sorted_files.push_back (file_name); Result temp; struct stat sb; int err = stat((file_name).c_str(), &sb); if (err == -1) { perror("stat"); exit(-1); } if (!show_hidden && file_name.at(0) == '.') continue; //populate the temp object, then push it to the vector if (S_ISREG (sb.st_mode)) { temp.type = "-"; } else if (S_ISDIR (sb.st_mode)) { temp.type = "d"; } else if (S_ISCHR (sb.st_mode)) { temp.type = "c"; } else if (S_ISBLK (sb.st_mode)) { temp.type = "b"; } else if (S_ISFIFO (sb.st_mode)) { temp.type = "p"; } else if (S_ISLNK (sb.st_mode)) { temp.type = "l"; } else if (S_ISSOCK (sb.st_mode)) { temp.type = "s"; } else { temp.type = "-"; } string permissions = ""; if (sb.st_mode & S_IRUSR) { permissions += "r"; } else { permissions += "-"; } if (sb.st_mode & S_IWUSR) { permissions += "w"; } else { permissions += "-"; } if (sb.st_mode & S_IXUSR) { permissions += "x"; } else { permissions += "-"; } if (sb.st_mode & S_IRGRP) { permissions += "r"; } else { permissions += "-"; } if (sb.st_mode & S_IWGRP) { permissions += "w"; } else { permissions += "-"; } if (sb.st_mode & S_IXGRP) { permissions += "x"; } else { permissions += "-"; } if (sb.st_mode & S_IROTH) { permissions += "r"; } else { permissions += "-"; } if (sb.st_mode & S_IWOTH) { permissions += "w"; } else { permissions += "-"; } if (sb.st_mode & S_IXOTH) { permissions += "x"; } else { permissions += "-"; } temp.permissions = permissions; temp.links = sb.st_nlink; temp.owner = sb.st_uid; temp.group_owner = sb.st_gid; temp.bytes_size = sb.st_size; temp.time_last_mod = sb.st_mtime; temp.filename = file_name; results.push_back (temp); } if ((closedir (dirp)) == -1) { perror("closedir"); exit(-1); } ++idx; } } void sort_files () { //TODO: think about implementing a natural sorting algorithm // to match the behavior of the original ls. // ASCIIbetical sort sucks... sort (sorted_files.begin(), sorted_files.end()); sort (results.begin(), results.end(), result_sort); } void print_basic () { string printed = ""; for (int i = 0; i < sorted_files.size(); ++i) { printed += (sorted_files[i] + " "); if (printed.length() >= LINE_SIZE) { cout << endl; printed = ""; printed += (sorted_files[i] + " "); } cout << sorted_files[i] << " "; } cout << endl; } void print_long_listing () { } <|endoftext|>
<commit_before>// Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl> // // 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 <cmath> #include <Correlator.hpp> namespace TuneBench { CorrelatorConf::CorrelatorConf() : isa::OpenCL::KernelConf(), width(1), height(1) {} std::string CorrelatorConf::print() const { return std::to_string(width) + " " + std::to_string(height) + " " + isa::OpenCL::KernelConf::print(); } std::string * getCorrelatorOpenCL(const CorrelatorConf & conf, const std::string & dataName, const unsigned int padding, const unsigned int nrChannels, const unsigned int nrStations, const unsigned int nrSamples, const unsigned int nrPolarizations) { std::string * code = new std::string(); // Begin kernel's template *code = "__kernel void correlator(__global const " + dataName + "4 * const restrict input, __global " + dataName + "8 * const restrict output, __global const unsigned int * const restrict cellMapX, __global const unsigned int * const restrict cellMapY) {\n" "const unsigned int cell = (get_group_id(0) * " + std::to_string(conf.getNrThreadsD0() * conf.getNrItemsD0()) + ") + get_local_id(0);\n" "const unsigned int channel = (get_group_id(2) * " + std::to_string(conf.getNrThreadsD2()) + ") + get_local_id(2);\n" "const unsigned int baseStationX = cellMapX[cell];\n" "const unsigned int baseStationY = cellMapY[cell];\n" "<%DEFINE_STATION%>" "<%DEFINE_CELL%>" "\n" "// Compute\n" "for ( unsigned int sample = 0; sample < " + std::to_string(nrSamples) + "; sample += " + std::to_string(conf.getNrItemsD1()) + " ) {\n" "<%LOAD_AND_COMPUTE%>" "}\n" "<%STORE%>" "}\n"; std::string defineStationX_sTemplate = dataName + "4 sampleStationX<%STATION%>P0 = (" + dataName + "4)(0.0);\n"; std::string defineStationY_sTemplate = dataName + "4 sampleStationY<%STATION%>P1 = (" + dataName + "4)(0.0);\n"; std::string defineCell_sTemplate = dataName + "8 accumulator<%CELL%> = (" + dataName + "8)(0.0);\n"; std::string loadX_sTemplate = "sampleStationX<%STATION%>P0 = input[(channel * " + std::to_string(nrStations * isa::utils::pad(nrSamples, padding / 4)) + ") + ((baseStationX + <%WIDTH%>) * " + std::to_string(isa::utils::pad(nrSamples, padding / 4)) + ") + (sample + <%OFFSETD1%>)];\n" "sampleStationX<%STATION%>P1 = input[(channel * " + std::to_string(nrStations * isa::utils::pad(nrSamples, padding / 4)) + ") + ((baseStationX + <%WIDTH%>) * " + std::to_string(isa::utils::pad(nrSamples, padding / 4)) + ") + (sample + <%OFFSETD1%>)];\n"; std::string loadY_sTemplate = "sampleStationY<%STATION%>P0 = input[(channel * " + std::to_string(nrStations * isa::utils::pad(nrSamples, padding / 4)) + ") + ((baseStationY + <%HEIGHT%>) * " + std::to_string(isa::utils::pad(nrSamples, padding / 4)) + ") + (sample + <%OFFSETD1%>)];\n" "sampleStationY<%STATION%>P1 = input[(channel * " + std::to_string(nrStations * isa::utils::pad(nrSamples, padding / 4)) + ") + ((baseStationY + <%HEIGHT%>) * " + std::to_string(isa::utils::pad(nrSamples, padding / 4)) + ") + (sample + <%OFFSETD1%>)];\n"; std::vector< std::string > compute_sTemplate(8); compute_sTemplate[0] = "accumulator<%CELL%>.s0 += (sampleStation<%STATION%>P0.x * sampleStation<%STATION%>P1.x) - (sampleStation<%STATION%>P0.y * (-sampleStation<%STATION%>P1.y));\n"; compute_sTemplate[1] = "accumulator<%CELL%>.s1 += (sampleStation<%STATION%>P0.x * (-sampleStation<%STATION%>P1.y)) + (sampleStation<%STATION%>P0.y * sampleStation<%STATION%>P1.x);\n"; compute_sTemplate[2] = "accumulator<%CELL%>.s2 += (sampleStation<%STATION%>P0.x * sampleStation<%STATION%>P1.z) - (sampleStation<%STATION%>P0.y * (-sampleStation<%STATION%>P1.w));\n"; compute_sTemplate[3] = "accumulator<%CELL%>.s3 += (sampleStation<%STATION%>P0.x * (-sampleStation<%STATION%>P1.w)) + (sampleStation<%STATION%>P0.y * sampleStation<%STATION%>P1.z);\n"; compute_sTemplate[4] = "accumulator<%CELL%>.s4 += (sampleStation<%STATION%>P0.z * sampleStation<%STATION%>P1.x) - (sampleStation<%STATION%>P0.w * (-sampleStation<%STATION%>P1.y));\n"; compute_sTemplate[5] = "accumulator<%CELL%>.s5 += (sampleStation<%STATION%>P0.z * (-sampleStation<%STATION%>P1.y)) + (sampleStation<%STATION%>P0.w * sampleStation<%STATION%>P1.x);\n"; compute_sTemplate[6] = "accumulator<%CELL%>.s6 += (sampleStation<%STATION%>P0.z * sampleStation<%STATION%>P1.z) - (sampleStation<%STATION%>P0.w * (-sampleStation<%STATION%>P1.w));\n"; compute_sTemplate[7] = "accumulator<%CELL%>.s7 += (sampleStation<%STATION%>P0.z * (-sampleStation<%STATION%>P1.w)) + (sampleStation<%STATION%>P0.w * sampleStation<%STATION%>P1.z);\n"; std::string store_sTemplate = "output[(((((stationY + <%HEIGHT%>) * (stationY + <%HEIGHT%> + 1)) / 2) + stationX + <%WIDTH%>) * " + std::to_string(nrChannels) + ") + channel] = accumulator<%CELL%>;\n"; // End kernel's template std::string * defineStation_s = new std::string(); std::string * defineCell_s = new std::string(); std::string * loadCompute_s = new std::string(); std::string * store_s = new std::string(); std::string * temp = 0; std::string empty_s = ""; for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) { std::string width_s = std::to_string(width); temp = isa::utils::replace(&defineStationX_sTemplate, "<%STATION%>", width_s); defineStation_s->append(*temp); delete temp; } for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) { std::string height_s = std::to_string(height); temp = isa::utils::replace(&defineStationY_sTemplate, "<%STATION%>", height_s); defineStation_s->append(*temp); delete temp; } for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) { for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) { std::string cell_s = std::to_string(width) + std::to_string(height); std::string width_s = std::to_string(width); std::string height_s = std::to_string(height); temp = isa::utils::replace(&defineCell_sTemplate, "<%CELL%>", cell_s); defineCell_s->append(*temp); delete temp; if ( width == 0 ) { temp = isa::utils::replace(&store_sTemplate, " + <%WIDTH%>", empty_s); } else { temp = isa::utils::replace(&store_sTemplate, "<%WIDTH%>", width_s); } if ( height == 0 ) { temp = isa::utils::replace(temp, " + <%HEIGHT%>", empty_s, true); } else { temp = isa::utils::replace(temp, "<%HEIGHT%>", height_s, true); } temp = isa::utils::replace(temp, "<%CELL%>", cell_s, true); store_s->append(*temp); delete temp; } } for ( unsigned int sample = 0; sample < conf.getNrItemsD1(); sample++ ) { std::string offsetD1_s = std::to_string(sample); for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) { std::string width_s = std::to_string(width); if ( width == 0 ) { temp = isa::utils::replace(&loadX_sTemplate, "+ <%WIDTH%>", empty_s); } else { temp = isa::utils::replace(&loadX_sTemplate, "<%WIDTH%>", width_s); } temp = isa::utils::replace(temp, "<%STATION%>", width_s, true); loadCompute_s->append(*temp); delete temp; } for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) { std::string height_s = std::to_string(height); if ( height == 0 ) { temp = isa::utils::replace(&loadY_sTemplate, "+ <%HEIGHT%>", empty_s); } else { temp = isa::utils::replace(&loadY_sTemplate, "<%HEIGHT%>", height_s); } temp = isa::utils::replace(temp, "<%STATION%>", height_s, true); loadCompute_s->append(*temp); delete temp; } if ( sample == 0 ) { loadCompute_s = isa::utils::replace(loadCompute_s, " + <%OFFSETD1%>", empty_s, true); } else { loadCompute_s = isa::utils::replace(loadCompute_s, "<%OFFSETD1%>", offsetD1_s, true); } for ( unsigned int computeStatement = 0; computeStatement < 8; computeStatement++ ) { for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) { for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) { std::string cell_s = std::to_string(width) + std::to_string(height); temp = isa::utils::replace(&compute_sTemplate[computeStatement], "<%CELL%>", cell_s); loadCompute_s->append(*temp); delete temp; } } } } code = isa::utils::replace(code, "<%DEFINE_STATION%>", *defineStation_s, true); code = isa::utils::replace(code, "<%DEFINE_CELL%>", *defineCell_s, true); code = isa::utils::replace(code, "<%LOAD_AND_COMPUTE%>", *loadCompute_s, true); code = isa::utils::replace(code, "<%STORE%>", *store_s, true); delete defineStation_s; delete defineCell_s; delete loadCompute_s; delete store_s; return code; } unsigned int generateCellMap(const CorrelatorConf & conf, std::vector< unsigned int > & cellMapX, std::vector< unsigned int > & cellMapY, const unsigned int nrStations) { unsigned int nrCells = 0; cellMapX.clear(); cellMapY.clear(); for ( int stationY = nrStations - conf.getCellHeight(); stationY >= 0; stationY -= conf.getCellHeight() ) { for ( int stationX = 0; stationX + static_cast< int >(conf.getCellWidth()) - 1 <= stationY; stationX += conf.getCellWidth() ) { nrCells++; cellMapX.push_back(stationX); cellMapY.push_back(stationY); } } return nrCells; } }; // TuneBench <commit_msg>Code ready, time to test it.<commit_after>// Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl> // // 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 <cmath> #include <Correlator.hpp> namespace TuneBench { CorrelatorConf::CorrelatorConf() : isa::OpenCL::KernelConf(), width(1), height(1) {} std::string CorrelatorConf::print() const { return std::to_string(width) + " " + std::to_string(height) + " " + isa::OpenCL::KernelConf::print(); } std::string * getCorrelatorOpenCL(const CorrelatorConf & conf, const std::string & dataName, const unsigned int padding, const unsigned int nrChannels, const unsigned int nrStations, const unsigned int nrSamples, const unsigned int nrPolarizations) { std::string * code = new std::string(); // Begin kernel's template *code = "__kernel void correlator(__global const " + dataName + "4 * const restrict input, __global " + dataName + "8 * const restrict output, __global const unsigned int * const restrict cellMapX, __global const unsigned int * const restrict cellMapY) {\n" "const unsigned int cell = (get_group_id(0) * " + std::to_string(conf.getNrThreadsD0() * conf.getNrItemsD0()) + ") + get_local_id(0);\n" "const unsigned int channel = (get_group_id(2) * " + std::to_string(conf.getNrThreadsD2()) + ") + get_local_id(2);\n" "const unsigned int baseStationX = cellMapX[cell];\n" "const unsigned int baseStationY = cellMapY[cell];\n" "<%DEFINE_STATION%>" "<%DEFINE_CELL%>" "\n" "// Compute\n" "for ( unsigned int sample = 0; sample < " + std::to_string(nrSamples) + "; sample += " + std::to_string(conf.getNrItemsD1()) + " ) {\n" "<%LOAD_AND_COMPUTE%>" "}\n" "<%STORE%>" "}\n"; std::string defineStationX_sTemplate = dataName + "4 sampleStationX<%STATION%>P0 = (" + dataName + "4)(0.0);\n"; std::string defineStationY_sTemplate = dataName + "4 sampleStationY<%STATION%>P1 = (" + dataName + "4)(0.0);\n"; std::string defineCell_sTemplate = dataName + "8 accumulator<%CELL%> = (" + dataName + "8)(0.0);\n"; std::string loadX_sTemplate = "sampleStationX<%STATION%>P0 = input[(channel * " + std::to_string(nrStations * isa::utils::pad(nrSamples, padding / 4)) + ") + ((baseStationX + <%WIDTH%>) * " + std::to_string(isa::utils::pad(nrSamples, padding / 4)) + ") + (sample + <%OFFSETD1%>)];\n" "sampleStationX<%STATION%>P1 = input[(channel * " + std::to_string(nrStations * isa::utils::pad(nrSamples, padding / 4)) + ") + ((baseStationX + <%WIDTH%>) * " + std::to_string(isa::utils::pad(nrSamples, padding / 4)) + ") + (sample + <%OFFSETD1%>)];\n"; std::string loadY_sTemplate = "sampleStationY<%STATION%>P0 = input[(channel * " + std::to_string(nrStations * isa::utils::pad(nrSamples, padding / 4)) + ") + ((baseStationY + <%HEIGHT%>) * " + std::to_string(isa::utils::pad(nrSamples, padding / 4)) + ") + (sample + <%OFFSETD1%>)];\n" "sampleStationY<%STATION%>P1 = input[(channel * " + std::to_string(nrStations * isa::utils::pad(nrSamples, padding / 4)) + ") + ((baseStationY + <%HEIGHT%>) * " + std::to_string(isa::utils::pad(nrSamples, padding / 4)) + ") + (sample + <%OFFSETD1%>)];\n"; std::vector< std::string > compute_sTemplate(8); compute_sTemplate[0] = "accumulator<%CELL%>.s0 += (sampleStationX<%STATIONX%>P0.x * sampleStationY<%STATIONY%>P1.x) - (sampleStationX<%STATIONX%>P0.y * (-sampleStationY<%STATIONY%>P1.y));\n"; compute_sTemplate[1] = "accumulator<%CELL%>.s1 += (sampleStationX<%STATIONX%>P0.x * (-sampleStationY<%STATIONY%>P1.y)) + (sampleStationX<%STATIONX%>P0.y * sampleStationY<%STATIONY%>P1.x);\n"; compute_sTemplate[2] = "accumulator<%CELL%>.s2 += (sampleStationX<%STATIONX%>P0.x * sampleStationY<%STATIONY%>P1.z) - (sampleStationX<%STATIONX%>P0.y * (-sampleStationY<%STATIONY%>P1.w));\n"; compute_sTemplate[3] = "accumulator<%CELL%>.s3 += (sampleStationX<%STATIONX%>P0.x * (-sampleStationY<%STATIONY%>P1.w)) + (sampleStationX<%STATIONX%>P0.y * sampleStationY<%STATIONY%>P1.z);\n"; compute_sTemplate[4] = "accumulator<%CELL%>.s4 += (sampleStationX<%STATIONX%>P0.z * sampleStationY<%STATIONY%>P1.x) - (sampleStationX<%STATIONX%>P0.w * (-sampleStationY<%STATIONY%>P1.y));\n"; compute_sTemplate[5] = "accumulator<%CELL%>.s5 += (sampleStationX<%STATIONX%>P0.z * (-sampleStationY<%STATIONY%>P1.y)) + (sampleStationX<%STATIONX%>P0.w * sampleStationY<%STATIONY%>P1.x);\n"; compute_sTemplate[6] = "accumulator<%CELL%>.s6 += (sampleStationX<%STATIONX%>P0.z * sampleStationY<%STATIONY%>P1.z) - (sampleStationX<%STATIONX%>P0.w * (-sampleStationY<%STATIONY%>P1.w));\n"; compute_sTemplate[7] = "accumulator<%CELL%>.s7 += (sampleStationX<%STATIONX%>P0.z * (-sampleStationY<%STATIONY%>P1.w)) + (sampleStationX<%STATIONX%>P0.w * sampleStationY<%STATIONY%>P1.z);\n"; std::string store_sTemplate = "output[(((((stationY + <%HEIGHT%>) * (stationY + <%HEIGHT%> + 1)) / 2) + stationX + <%WIDTH%>) * " + std::to_string(nrChannels) + ") + channel] = accumulator<%CELL%>;\n"; // End kernel's template std::string * defineStation_s = new std::string(); std::string * defineCell_s = new std::string(); std::string * loadCompute_s = new std::string(); std::string * store_s = new std::string(); std::string * temp = 0; std::string empty_s = ""; for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) { std::string width_s = std::to_string(width); temp = isa::utils::replace(&defineStationX_sTemplate, "<%STATION%>", width_s); defineStation_s->append(*temp); delete temp; } for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) { std::string height_s = std::to_string(height); temp = isa::utils::replace(&defineStationY_sTemplate, "<%STATION%>", height_s); defineStation_s->append(*temp); delete temp; } for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) { for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) { std::string cell_s = std::to_string(width) + std::to_string(height); std::string width_s = std::to_string(width); std::string height_s = std::to_string(height); temp = isa::utils::replace(&defineCell_sTemplate, "<%CELL%>", cell_s); defineCell_s->append(*temp); delete temp; if ( width == 0 ) { temp = isa::utils::replace(&store_sTemplate, " + <%WIDTH%>", empty_s); } else { temp = isa::utils::replace(&store_sTemplate, "<%WIDTH%>", width_s); } if ( height == 0 ) { temp = isa::utils::replace(temp, " + <%HEIGHT%>", empty_s, true); } else { temp = isa::utils::replace(temp, "<%HEIGHT%>", height_s, true); } temp = isa::utils::replace(temp, "<%CELL%>", cell_s, true); store_s->append(*temp); delete temp; } } for ( unsigned int sample = 0; sample < conf.getNrItemsD1(); sample++ ) { std::string offsetD1_s = std::to_string(sample); for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) { std::string width_s = std::to_string(width); if ( width == 0 ) { temp = isa::utils::replace(&loadX_sTemplate, "+ <%WIDTH%>", empty_s); } else { temp = isa::utils::replace(&loadX_sTemplate, "<%WIDTH%>", width_s); } temp = isa::utils::replace(temp, "<%STATION%>", width_s, true); loadCompute_s->append(*temp); delete temp; } for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) { std::string height_s = std::to_string(height); if ( height == 0 ) { temp = isa::utils::replace(&loadY_sTemplate, "+ <%HEIGHT%>", empty_s); } else { temp = isa::utils::replace(&loadY_sTemplate, "<%HEIGHT%>", height_s); } temp = isa::utils::replace(temp, "<%STATION%>", height_s, true); loadCompute_s->append(*temp); delete temp; } if ( sample == 0 ) { loadCompute_s = isa::utils::replace(loadCompute_s, " + <%OFFSETD1%>", empty_s, true); } else { loadCompute_s = isa::utils::replace(loadCompute_s, "<%OFFSETD1%>", offsetD1_s, true); } for ( unsigned int computeStatement = 0; computeStatement < 8; computeStatement++ ) { for ( unsigned int width = 0; width < conf.getCellWidth(); width++ ) { std::string width_s = std::to_string(width); for ( unsigned int height = 0; height < conf.getCellHeight(); height++ ) { std::string height_s = std::to_string(height); std::string cell_s = std::to_string(width) + std::to_string(height); temp = isa::utils::replace(&compute_sTemplate[computeStatement], "<%CELL%>", cell_s); temp = isa::utils::replace(temp, "<%STATIONX%>", width_s, true); temp = isa::utils::replace(temp, "<%STATIONY%>", height_s, true); loadCompute_s->append(*temp); delete temp; } } } } code = isa::utils::replace(code, "<%DEFINE_STATION%>", *defineStation_s, true); code = isa::utils::replace(code, "<%DEFINE_CELL%>", *defineCell_s, true); code = isa::utils::replace(code, "<%LOAD_AND_COMPUTE%>", *loadCompute_s, true); code = isa::utils::replace(code, "<%STORE%>", *store_s, true); delete defineStation_s; delete defineCell_s; delete loadCompute_s; delete store_s; return code; } unsigned int generateCellMap(const CorrelatorConf & conf, std::vector< unsigned int > & cellMapX, std::vector< unsigned int > & cellMapY, const unsigned int nrStations) { unsigned int nrCells = 0; cellMapX.clear(); cellMapY.clear(); for ( int stationY = nrStations - conf.getCellHeight(); stationY >= 0; stationY -= conf.getCellHeight() ) { for ( int stationX = 0; stationX + static_cast< int >(conf.getCellWidth()) - 1 <= stationY; stationX += conf.getCellWidth() ) { nrCells++; cellMapX.push_back(stationX); cellMapY.push_back(stationY); } } return nrCells; } }; // TuneBench <|endoftext|>
<commit_before>#include "photon_blocks.h" #include "photon_opengl.h" #include "photon_level.h" #include "photon_laser.h" #include "photon_texture.h" #include "photon_core.h" #include "glm/ext.hpp" GLuint texture_plain_block; GLuint texture_mirror; GLuint texture_tnt; GLuint texture_explosion; GLuint texture_filter_red; GLuint texture_filter_green; GLuint texture_filter_blue; GLuint texture_filter_yellow; GLuint texture_filter_cyan; GLuint texture_filter_magenta; namespace photon{ namespace blocks{ void DrawBox(glm::uvec2 location, float size = 0.5f){ // TODO - maybe add optional rotation? perhaps via UV coordinates? glBegin(GL_QUADS);{ glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 1.0f, 1.0f); glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x + size, location.y + size); glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 0.0f, 1.0f); glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x - size, location.y + size); glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 0.0f, 0.0f); glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x - size, location.y - size); glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 1.0f, 0.0f); glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x + size, location.y - size); }glEnd(); } void DrawMirror(glm::uvec2 location, float angle){ glm::vec2 point1(0.4f, 0.05f); glm::vec2 point2(0.05f, 0.4f); point1 = glm::rotate(point1, angle); point2 = glm::rotate(point2, angle + 90.0f); glBegin(GL_QUADS);{ glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 1.0f, 1.0f); glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x + point1.x, location.y + point1.y); glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 0.0f, 1.0f); glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x - point2.x, location.y - point2.y); glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 0.0f, 0.0f); glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x - point1.x, location.y - point1.y); glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 1.0f, 0.0f); glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x + point2.x, location.y + point2.y); }glEnd(); } void Draw(photon_block block, glm::uvec2 location){ switch(block.type){ case PHOTON_BLOCKS_AIR: break; case PHOTON_BLOCKS_PLAIN: glBindTexture(GL_TEXTURE_2D, texture_plain_block); DrawBox(location); break; case PHOTON_BLOCKS_INDESTRUCTIBLE: // TODO - make different texture. glBindTexture(GL_TEXTURE_2D, texture_plain_block); DrawBox(location); break; case PHOTON_BLOCKS_MIRROR: case PHOTON_BLOCKS_MIRROR_LOCKED: case PHOTON_BLOCKS_MIRROR_LOCKED_POS: glBindTexture(GL_TEXTURE_2D, texture_mirror); DrawMirror(location, block.data); break; case PHOTON_BLOCKS_TNT: glBindTexture(GL_TEXTURE_2D, texture_tnt); DrawBox(location); break; case PHOTON_BLOCKS_FILTER_RED: glBindTexture(GL_TEXTURE_2D, texture_filter_red); DrawBox(location, 0.2f); break; case PHOTON_BLOCKS_FILTER_GREEN: glBindTexture(GL_TEXTURE_2D, texture_filter_green); DrawBox(location, 0.2f); break; case PHOTON_BLOCKS_FILTER_BLUE: glBindTexture(GL_TEXTURE_2D, texture_filter_blue); DrawBox(location, 0.2f); break; case PHOTON_BLOCKS_FILTER_YELLOW: glBindTexture(GL_TEXTURE_2D, texture_filter_yellow); DrawBox(location, 0.2f); break; case PHOTON_BLOCKS_FILTER_CYAN: glBindTexture(GL_TEXTURE_2D, texture_filter_cyan); DrawBox(location, 0.2f); break; case PHOTON_BLOCKS_FILTER_MAGENTA: glBindTexture(GL_TEXTURE_2D, texture_filter_magenta); DrawBox(location, 0.2f); break; } } void DrawFX(photon_block block, glm::uvec2 location){ switch(block.type){ case PHOTON_BLOCKS_TNT: // TODO - draw some warmup thing... glBindTexture(GL_TEXTURE_2D, texture_explosion); opengl::SetFacFX(block.data * 0.5f); DrawBox(location); break; case PHOTON_BLOCKS_TNT_FIREBALL: glBindTexture(GL_TEXTURE_2D, texture_explosion); opengl::SetFacFX(block.data); DrawBox(location, 1.5); break; } } photon_lasersegment *OnLightInteract(photon_lasersegment *segment, glm::uvec2 location, photon_level &level, float time){ photon_block &block = level.grid[location.x][location.y]; block.activated = true; switch(block.type){ case PHOTON_BLOCKS_AIR: default: break; case PHOTON_BLOCKS_RECIEVER: // TODO - make trigger // stops tracing the laser. return nullptr; break; case PHOTON_BLOCKS_PLAIN: case PHOTON_BLOCKS_INDESTRUCTIBLE: // stops tracing the laser. return nullptr; break; case PHOTON_BLOCKS_MIRROR: case PHOTON_BLOCKS_MIRROR_LOCKED: case PHOTON_BLOCKS_MIRROR_LOCKED_POS:{ float angle = segment->angle - block.data; if(fmod(angle, 180.0f) == 0.0f){ return nullptr; } angle = fmod(angle + 180.0f, 360.0f) - 180.0f; segment = tracer::CreateChildBeam(segment); segment->angle = block.data - angle; break; } case PHOTON_BLOCKS_TNT: block.data += time; if(block.data > 1.0f){ // TODO - KABOOM goes here... PrintToLog("INFO: KABOOM!"); block.type = PHOTON_BLOCKS_TNT_FIREBALL; // cooldown of fireball block.data = 1.0f; break; } // stops tracing the laser. return nullptr; break; case PHOTON_BLOCKS_FILTER_RED:{ glm::vec3 color = segment->color; color.g = glm::min(color.g, 0.2f); color.b = glm::min(color.b, 0.1f); if(glm::length2(color) > 0.2f){ segment = tracer::CreateChildBeam(segment); segment->color = color; }else{ // stops tracing the laser. return nullptr; } break; } case PHOTON_BLOCKS_FILTER_GREEN:{ glm::vec3 color = segment->color; color.r = glm::min(color.r, 0.1f); color.b = glm::min(color.b, 0.2f); if(glm::length2(color) > 0.2f){ segment = tracer::CreateChildBeam(segment); segment->color = color; }else{ // stops tracing the laser. return nullptr; } break; } case PHOTON_BLOCKS_FILTER_BLUE:{ glm::vec3 color = segment->color; color.r = glm::min(color.r, 0.1f); color.g = glm::min(color.g, 0.2f); if(glm::length2(color) > 0.2f){ segment = tracer::CreateChildBeam(segment); segment->color = color; }else{ // stops tracing the laser. return nullptr; } break; } case PHOTON_BLOCKS_FILTER_YELLOW:{ glm::vec3 color = segment->color; color.b = glm::min(color.b, 0.1f); if(glm::length2(color) > 0.2f){ segment = tracer::CreateChildBeam(segment); segment->color = color; }else{ // stops tracing the laser. return nullptr; } break; } case PHOTON_BLOCKS_FILTER_CYAN:{ glm::vec3 color = segment->color; color.r = glm::min(color.r, 0.1f); if(glm::length2(color) > 0.2f){ segment = tracer::CreateChildBeam(segment); segment->color = color; }else{ // stops tracing the laser. return nullptr; } break; } case PHOTON_BLOCKS_FILTER_MAGENTA:{ glm::vec3 color = segment->color; color.g = glm::min(color.g, 0.1f); if(glm::length2(color) > 0.2f){ segment = tracer::CreateChildBeam(segment); segment->color = color; }else{ // stops tracing the laser. return nullptr; } break; } } return segment; } void LoadTextures(){ texture_plain_block = texture::Load("/textures/block.png"); texture_mirror = texture::Load("/textures/mirror.png"); texture_tnt = texture::Load("/textures/tnt.png"); texture_explosion = texture::Load("/textures/explosion.png"); texture_filter_red = texture::Load("/textures/filter_red.png"); texture_filter_green = texture::Load("/textures/filter_green.png");; texture_filter_blue = texture::Load("/textures/filter_blue.png");; texture_filter_yellow = texture::Load("/textures/filter_yellow.png"); texture_filter_cyan = texture::Load("/textures/filter_cyan.png");; texture_filter_magenta = texture::Load("/textures/filter_magenta.png");; } void OnPhotonInteract(glm::uvec2 location, photon_level &level){ if(level.grid.shape()[0] > location.x && level.grid.shape()[1] > location.y){ photon_block &block = level.grid[location.x][location.y]; switch(block.type){ case PHOTON_BLOCKS_AIR: // TODO - place currently selected item in inventory. block.type = PHOTON_BLOCKS_MIRROR; break; default: break; case PHOTON_BLOCKS_MIRROR: // TODO - store mirror in inventory. block.type = PHOTON_BLOCKS_AIR; break; } } } void OnRotate(glm::uvec2 location, photon_level &level, bool counter_clockwise){ if(level.grid.shape()[0] > location.x && level.grid.shape()[1] > location.y){ photon_block &block = level.grid[location.x][location.y]; switch(block.type){ default: break; case PHOTON_BLOCKS_MIRROR: case PHOTON_BLOCKS_MIRROR_LOCKED_POS: if(counter_clockwise){ block.data += 22.5f; }else{ block.data -= 22.5f; } break; } } } void OnFrame(glm::uvec2 location, photon_level &level, float time){ photon_block &block = level.grid[location.x][location.y]; switch(block.type){ case PHOTON_BLOCKS_AIR: default: break; case PHOTON_BLOCKS_RECIEVER: break; case PHOTON_BLOCKS_PLAIN: case PHOTON_BLOCKS_INDESTRUCTIBLE: break; case PHOTON_BLOCKS_MIRROR: case PHOTON_BLOCKS_MIRROR_LOCKED: case PHOTON_BLOCKS_MIRROR_LOCKED_POS: break; case PHOTON_BLOCKS_TNT: // if block was not activated last frame cool down timer. if(!block.activated){ block.data -= time; block.data = std::max(block.data, 0.0f); } break; case PHOTON_BLOCKS_TNT_FIREBALL: block.data -= time * 3.0f; if(block.data < 0.0f){ block.data = 0.0f; block.type = PHOTON_BLOCKS_AIR; } break; } block.activated = false; } } } <commit_msg>made it so there are not variations to colors (e.g. a more "pure" red by sending it through a magenta filter)<commit_after>#include "photon_blocks.h" #include "photon_opengl.h" #include "photon_level.h" #include "photon_laser.h" #include "photon_texture.h" #include "photon_core.h" #include "glm/ext.hpp" GLuint texture_plain_block; GLuint texture_mirror; GLuint texture_tnt; GLuint texture_explosion; GLuint texture_filter_red; GLuint texture_filter_green; GLuint texture_filter_blue; GLuint texture_filter_yellow; GLuint texture_filter_cyan; GLuint texture_filter_magenta; namespace photon{ namespace blocks{ void DrawBox(glm::uvec2 location, float size = 0.5f){ // TODO - maybe add optional rotation? perhaps via UV coordinates? glBegin(GL_QUADS);{ glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 1.0f, 1.0f); glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x + size, location.y + size); glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 0.0f, 1.0f); glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x - size, location.y + size); glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 0.0f, 0.0f); glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x - size, location.y - size); glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 1.0f, 0.0f); glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x + size, location.y - size); }glEnd(); } void DrawMirror(glm::uvec2 location, float angle){ glm::vec2 point1(0.4f, 0.05f); glm::vec2 point2(0.05f, 0.4f); point1 = glm::rotate(point1, angle); point2 = glm::rotate(point2, angle + 90.0f); glBegin(GL_QUADS);{ glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 1.0f, 1.0f); glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x + point1.x, location.y + point1.y); glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 0.0f, 1.0f); glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x - point2.x, location.y - point2.y); glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 0.0f, 0.0f); glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x - point1.x, location.y - point1.y); glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 1.0f, 0.0f); glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x + point2.x, location.y + point2.y); }glEnd(); } void Draw(photon_block block, glm::uvec2 location){ switch(block.type){ case PHOTON_BLOCKS_AIR: break; case PHOTON_BLOCKS_PLAIN: glBindTexture(GL_TEXTURE_2D, texture_plain_block); DrawBox(location); break; case PHOTON_BLOCKS_INDESTRUCTIBLE: // TODO - make different texture. glBindTexture(GL_TEXTURE_2D, texture_plain_block); DrawBox(location); break; case PHOTON_BLOCKS_MIRROR: case PHOTON_BLOCKS_MIRROR_LOCKED: case PHOTON_BLOCKS_MIRROR_LOCKED_POS: glBindTexture(GL_TEXTURE_2D, texture_mirror); DrawMirror(location, block.data); break; case PHOTON_BLOCKS_TNT: glBindTexture(GL_TEXTURE_2D, texture_tnt); DrawBox(location); break; case PHOTON_BLOCKS_FILTER_RED: glBindTexture(GL_TEXTURE_2D, texture_filter_red); DrawBox(location, 0.2f); break; case PHOTON_BLOCKS_FILTER_GREEN: glBindTexture(GL_TEXTURE_2D, texture_filter_green); DrawBox(location, 0.2f); break; case PHOTON_BLOCKS_FILTER_BLUE: glBindTexture(GL_TEXTURE_2D, texture_filter_blue); DrawBox(location, 0.2f); break; case PHOTON_BLOCKS_FILTER_YELLOW: glBindTexture(GL_TEXTURE_2D, texture_filter_yellow); DrawBox(location, 0.2f); break; case PHOTON_BLOCKS_FILTER_CYAN: glBindTexture(GL_TEXTURE_2D, texture_filter_cyan); DrawBox(location, 0.2f); break; case PHOTON_BLOCKS_FILTER_MAGENTA: glBindTexture(GL_TEXTURE_2D, texture_filter_magenta); DrawBox(location, 0.2f); break; } } void DrawFX(photon_block block, glm::uvec2 location){ switch(block.type){ case PHOTON_BLOCKS_TNT: // TODO - draw some warmup thing... glBindTexture(GL_TEXTURE_2D, texture_explosion); opengl::SetFacFX(block.data * 0.5f); DrawBox(location); break; case PHOTON_BLOCKS_TNT_FIREBALL: glBindTexture(GL_TEXTURE_2D, texture_explosion); opengl::SetFacFX(block.data); DrawBox(location, 1.5); break; } } photon_lasersegment *OnLightInteract(photon_lasersegment *segment, glm::uvec2 location, photon_level &level, float time){ photon_block &block = level.grid[location.x][location.y]; block.activated = true; switch(block.type){ case PHOTON_BLOCKS_AIR: default: break; case PHOTON_BLOCKS_RECIEVER: // TODO - make trigger // stops tracing the laser. return nullptr; break; case PHOTON_BLOCKS_PLAIN: case PHOTON_BLOCKS_INDESTRUCTIBLE: // stops tracing the laser. return nullptr; break; case PHOTON_BLOCKS_MIRROR: case PHOTON_BLOCKS_MIRROR_LOCKED: case PHOTON_BLOCKS_MIRROR_LOCKED_POS:{ float angle = segment->angle - block.data; if(fmod(angle, 180.0f) == 0.0f){ return nullptr; } angle = fmod(angle + 180.0f, 360.0f) - 180.0f; segment = tracer::CreateChildBeam(segment); segment->angle = block.data - angle; break; } case PHOTON_BLOCKS_TNT: block.data += time; if(block.data > 1.0f){ // TODO - KABOOM goes here... PrintToLog("INFO: KABOOM!"); block.type = PHOTON_BLOCKS_TNT_FIREBALL; // cooldown of fireball block.data = 1.0f; break; } // stops tracing the laser. return nullptr; break; case PHOTON_BLOCKS_FILTER_RED:{ glm::vec3 color = segment->color; color.g = glm::min(color.g, 0.2f); color.b = glm::min(color.b, 0.1f); if(glm::length2(color) > 0.2f){ segment = tracer::CreateChildBeam(segment); segment->color = color; }else{ // stops tracing the laser. return nullptr; } break; } case PHOTON_BLOCKS_FILTER_GREEN:{ glm::vec3 color = segment->color; color.r = glm::min(color.r, 0.1f); color.b = glm::min(color.b, 0.1f); if(glm::length2(color) > 0.2f){ segment = tracer::CreateChildBeam(segment); segment->color = color; }else{ // stops tracing the laser. return nullptr; } break; } case PHOTON_BLOCKS_FILTER_BLUE:{ glm::vec3 color = segment->color; color.r = glm::min(color.r, 0.1f); color.g = glm::min(color.g, 0.2f); if(glm::length2(color) > 0.2f){ segment = tracer::CreateChildBeam(segment); segment->color = color; }else{ // stops tracing the laser. return nullptr; } break; } case PHOTON_BLOCKS_FILTER_YELLOW:{ glm::vec3 color = segment->color; color.b = glm::min(color.b, 0.1f); if(glm::length2(color) > 0.2f){ segment = tracer::CreateChildBeam(segment); segment->color = color; }else{ // stops tracing the laser. return nullptr; } break; } case PHOTON_BLOCKS_FILTER_CYAN:{ glm::vec3 color = segment->color; color.r = glm::min(color.r, 0.1f); if(glm::length2(color) > 0.2f){ segment = tracer::CreateChildBeam(segment); segment->color = color; }else{ // stops tracing the laser. return nullptr; } break; } case PHOTON_BLOCKS_FILTER_MAGENTA:{ glm::vec3 color = segment->color; color.g = glm::min(color.g, 0.2f); if(glm::length2(color) > 0.2f){ segment = tracer::CreateChildBeam(segment); segment->color = color; }else{ // stops tracing the laser. return nullptr; } break; } } return segment; } void LoadTextures(){ texture_plain_block = texture::Load("/textures/block.png"); texture_mirror = texture::Load("/textures/mirror.png"); texture_tnt = texture::Load("/textures/tnt.png"); texture_explosion = texture::Load("/textures/explosion.png"); texture_filter_red = texture::Load("/textures/filter_red.png"); texture_filter_green = texture::Load("/textures/filter_green.png");; texture_filter_blue = texture::Load("/textures/filter_blue.png");; texture_filter_yellow = texture::Load("/textures/filter_yellow.png"); texture_filter_cyan = texture::Load("/textures/filter_cyan.png");; texture_filter_magenta = texture::Load("/textures/filter_magenta.png");; } void OnPhotonInteract(glm::uvec2 location, photon_level &level){ if(level.grid.shape()[0] > location.x && level.grid.shape()[1] > location.y){ photon_block &block = level.grid[location.x][location.y]; switch(block.type){ case PHOTON_BLOCKS_AIR: // TODO - place currently selected item in inventory. block.type = PHOTON_BLOCKS_MIRROR; break; default: break; case PHOTON_BLOCKS_MIRROR: // TODO - store mirror in inventory. block.type = PHOTON_BLOCKS_AIR; break; } } } void OnRotate(glm::uvec2 location, photon_level &level, bool counter_clockwise){ if(level.grid.shape()[0] > location.x && level.grid.shape()[1] > location.y){ photon_block &block = level.grid[location.x][location.y]; switch(block.type){ default: break; case PHOTON_BLOCKS_MIRROR: case PHOTON_BLOCKS_MIRROR_LOCKED_POS: if(counter_clockwise){ block.data += 22.5f; }else{ block.data -= 22.5f; } break; } } } void OnFrame(glm::uvec2 location, photon_level &level, float time){ photon_block &block = level.grid[location.x][location.y]; switch(block.type){ case PHOTON_BLOCKS_AIR: default: break; case PHOTON_BLOCKS_RECIEVER: break; case PHOTON_BLOCKS_PLAIN: case PHOTON_BLOCKS_INDESTRUCTIBLE: break; case PHOTON_BLOCKS_MIRROR: case PHOTON_BLOCKS_MIRROR_LOCKED: case PHOTON_BLOCKS_MIRROR_LOCKED_POS: break; case PHOTON_BLOCKS_TNT: // if block was not activated last frame cool down timer. if(!block.activated){ block.data -= time; block.data = std::max(block.data, 0.0f); } break; case PHOTON_BLOCKS_TNT_FIREBALL: block.data -= time * 3.0f; if(block.data < 0.0f){ block.data = 0.0f; block.type = PHOTON_BLOCKS_AIR; } break; } block.activated = false; } } } <|endoftext|>
<commit_before>/* ============================================================================ * Copyright (c) 2011, Michael A. Jackson (BlueQuartz Software) * 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 Michael A. Jackson nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include "MRCWriter.h" //-- C Includes #include <stdio.h> //-- C++ Includes #include <iomanip> #include <limits> //-- MXA Includes #include "MXA/MXA.h" #include "MXA/Common/MXAEndian.h" #include "MXA/Common/IO/MXAFileWriter64.h" // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- MRCWriter::MRCWriter() : m_MRCHeader(NULL) { m_XDims[0] = 0; m_XDims[1] = 0; m_YDims[0] = 0; m_YDims[1] = 0; m_ZDims[0] = 0; m_ZDims[1] = 0; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- MRCWriter::~MRCWriter() { } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void MRCWriter::execute() { write(); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- int MRCWriter::writeHeader() { int err = -1; return err; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void MRCWriter::initializeMRCHeader(MRCHeader* header) { header->nx = m_Geometry->N_x; header->ny = m_Geometry->N_y; header->nz = m_Geometry->N_z; header->mode = 2; header->nxstart = 0; header->nystart = 0; header->nzstart = 0; header->mx = m_Geometry->N_x; header->my = m_Geometry->N_y; header->mz = m_Geometry->N_z; header->xlen = m_Geometry->N_x; header->ylen = m_Geometry->N_y; header->zlen = m_Geometry->N_z; header->alpha = 90.0; header->beta = 90.0; header->gamma = 90.0; header->mapc = 1; header->mapr = 2; header->maps = 3; /* ** These need to be calculated from the data ** */ header->amin = 0.0; header->amax = 0.0; header->amean = 0.0; header->ispg = 0; header->nsymbt = 0; /* ** Calculate the size of the extended header */ header->next = sizeof(FEIHeader) * m_Geometry->N_z; header->creatid = 0; ::memset(&header->extra_data, 0, 30); header->nint = 0; header->nreal = 0; ::memset(&header->extra_data_2, 0, 20); header->imodStamp = 0; header->imodFlags = 0; header->idtype = 0; header->lens = 0; header->nd1 = 0; header->nd2 = 0; header->vd1 = 0; header->vd2 = 0; ::memset(&header->tiltangles, 0, 6 * sizeof(float)); header->xorg = 0.0f; header->yorg = 0.0f; header->zorg = 0.0f; header->cmap[0] = 'M'; header->cmap[1] = 'A'; header->cmap[2] = 'P'; header->cmap[3] = ' '; #if defined (CMP_WORDS_BIGENDIAN) header->stamp[0] = 17; header->stamp[1] = 17; #else header->stamp[0] = 68; header->stamp[1] = 65; #endif header->stamp[2] = 0; header->stamp[3] = 0; header->rms = 0.0f; header->nLabels = 3; for(int i = 0; i < 10; ++i) { ::memset(header->labels[i], 0, 80); } snprintf(header->labels[0], 80, "Fei Company (C) Copyright 2003"); snprintf(header->labels[1], 80, "Reconstruction by OpenMBIR"); snprintf(header->labels[2], 80, "OpenMBIR code developed by Purdue University & BlueQuartz Software"); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- int MRCWriter::write() { int err = -1; std::stringstream ss; std::cout << "MRC Output File:\n " << m_OutputFile << std::endl; if (m_OutputFile.empty()) { ss.str(""); ss << "MRCWriter: Output File was Not Set"; setErrorCondition(-1); setErrorMessage(ss.str()); notify(getErrorMessage().c_str(), 0, UpdateErrorMessage); return err; } MXAFileWriter64 writer(m_OutputFile); bool success = writer.initWriter(); if (false == success) { ss.str(""); ss << "MRCWriter: Error opening output file for writing. '" << m_OutputFile << "'"; setErrorCondition(-1); setErrorMessage(ss.str()); notify(getErrorMessage().c_str(), 0, UpdateErrorMessage); return err; } // std::cout << "Writing MRC File with Geometry of: " << std::endl; // std::cout << " N_z: " << m_Geometry->N_z << std::endl; // std::cout << " N_x: " << m_Geometry->N_x << std::endl; // std::cout << " N_y: " << m_Geometry->N_y << std::endl; MRCHeader mrcHeader; // Put one on the stack in case the programmer supplied a NULL pointer ::memset(&mrcHeader, 0, 1024); bool detachHeaderReference = false; if (NULL == m_MRCHeader) { m_MRCHeader = &mrcHeader; initializeMRCHeader(m_MRCHeader); detachHeaderReference = true; } // Update the header with our Dimensions m_MRCHeader->nx = (m_XDims[1] - m_XDims[0]); m_MRCHeader->ny = (m_YDims[1] - m_YDims[0]); m_MRCHeader->nz = (m_ZDims[1] - m_ZDims[0]); m_MRCHeader->mx = m_MRCHeader->nx; m_MRCHeader->my = m_MRCHeader->ny; m_MRCHeader->mz = m_MRCHeader->nz; m_MRCHeader->xlen = m_MRCHeader->nx; m_MRCHeader->ylen = m_MRCHeader->ny; m_MRCHeader->zlen = m_MRCHeader->nz; m_MRCHeader->next = sizeof(FEIHeader) * m_MRCHeader->nz; // Write the header writer.write(reinterpret_cast<char*>(m_MRCHeader), 1024); for(uint16_t i = 0; i < m_Geometry->N_z; ++i) { FEIHeader fei; ::memset(&fei, 0, sizeof(FEIHeader)); fei.pixelsize = static_cast<float>(m_Geometry->LengthX); writer.write(reinterpret_cast<char*>(&fei), sizeof(FEIHeader)); } size_t dims[2] = {m_MRCHeader->nx, m_MRCHeader->ny}; FloatImageType::Pointer sliceData = FloatImageType::New(dims, "temp slice data"); float* slice = sliceData->getPointer(0); size_t index = 0; Real_t d = 0.0; size_t count = 0; float mean = 0.0; float dmax = std::numeric_limits<Real_t>::min(); float dmin = std::numeric_limits<Real_t>::max(); for (int z = m_ZDims[1]-1; z >= m_ZDims[0]; z--) { index = 0; for (int y = m_YDims[0]; y < m_YDims[1]; ++y) { for (int x = m_XDims[0]; x < m_XDims[1]; ++x) { //index = (x * m_Geometry->N_y) + y; d = m_Geometry->Object->getValue(z, x, y); slice[index] = static_cast<float>(d); mean += slice[index]; count++; if(d > dmax) dmax = d; if(d < dmin) dmin = d; ++index; } } writer.write(reinterpret_cast<char*>(slice), sizeof(float) * dims[0] * dims[1]); } // Calculate the mean value mean = mean / count; // Update the values in the header of the file writer.setFilePointer64(76); // Set the position to the "amin" header entry writer.writeValue(&dmin); writer.writeValue(&dmax); writer.writeValue(&mean); if (detachHeaderReference == true) { m_MRCHeader = NULL; } setErrorCondition(0); setErrorMessage(""); notify("Done Writing the MRC Output File", 0, UpdateProgressMessage); err = 1; return err; } <commit_msg>Removing some debugging output<commit_after>/* ============================================================================ * Copyright (c) 2011, Michael A. Jackson (BlueQuartz Software) * 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 Michael A. Jackson nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include "MRCWriter.h" //-- C Includes #include <stdio.h> //-- C++ Includes #include <iomanip> #include <limits> //-- MXA Includes #include "MXA/MXA.h" #include "MXA/Common/MXAEndian.h" #include "MXA/Common/IO/MXAFileWriter64.h" // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- MRCWriter::MRCWriter() : m_MRCHeader(NULL) { m_XDims[0] = 0; m_XDims[1] = 0; m_YDims[0] = 0; m_YDims[1] = 0; m_ZDims[0] = 0; m_ZDims[1] = 0; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- MRCWriter::~MRCWriter() { } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void MRCWriter::execute() { write(); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- int MRCWriter::writeHeader() { int err = -1; return err; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void MRCWriter::initializeMRCHeader(MRCHeader* header) { header->nx = m_Geometry->N_x; header->ny = m_Geometry->N_y; header->nz = m_Geometry->N_z; header->mode = 2; header->nxstart = 0; header->nystart = 0; header->nzstart = 0; header->mx = m_Geometry->N_x; header->my = m_Geometry->N_y; header->mz = m_Geometry->N_z; header->xlen = m_Geometry->N_x; header->ylen = m_Geometry->N_y; header->zlen = m_Geometry->N_z; header->alpha = 90.0; header->beta = 90.0; header->gamma = 90.0; header->mapc = 1; header->mapr = 2; header->maps = 3; /* ** These need to be calculated from the data ** */ header->amin = 0.0; header->amax = 0.0; header->amean = 0.0; header->ispg = 0; header->nsymbt = 0; /* ** Calculate the size of the extended header */ header->next = sizeof(FEIHeader) * m_Geometry->N_z; header->creatid = 0; ::memset(&header->extra_data, 0, 30); header->nint = 0; header->nreal = 0; ::memset(&header->extra_data_2, 0, 20); header->imodStamp = 0; header->imodFlags = 0; header->idtype = 0; header->lens = 0; header->nd1 = 0; header->nd2 = 0; header->vd1 = 0; header->vd2 = 0; ::memset(&header->tiltangles, 0, 6 * sizeof(float)); header->xorg = 0.0f; header->yorg = 0.0f; header->zorg = 0.0f; header->cmap[0] = 'M'; header->cmap[1] = 'A'; header->cmap[2] = 'P'; header->cmap[3] = ' '; #if defined (CMP_WORDS_BIGENDIAN) header->stamp[0] = 17; header->stamp[1] = 17; #else header->stamp[0] = 68; header->stamp[1] = 65; #endif header->stamp[2] = 0; header->stamp[3] = 0; header->rms = 0.0f; header->nLabels = 3; for(int i = 0; i < 10; ++i) { ::memset(header->labels[i], 0, 80); } snprintf(header->labels[0], 80, "Fei Company (C) Copyright 2003"); snprintf(header->labels[1], 80, "Reconstruction by OpenMBIR"); snprintf(header->labels[2], 80, "OpenMBIR code developed by Purdue University & BlueQuartz Software"); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- int MRCWriter::write() { int err = -1; std::stringstream ss; // std::cout << "MRC Output File:\n " << m_OutputFile << std::endl; if (m_OutputFile.empty()) { ss.str(""); ss << "MRCWriter: Output File was Not Set"; setErrorCondition(-1); setErrorMessage(ss.str()); notify(getErrorMessage().c_str(), 0, UpdateErrorMessage); return err; } MXAFileWriter64 writer(m_OutputFile); bool success = writer.initWriter(); if (false == success) { ss.str(""); ss << "MRCWriter: Error opening output file for writing. '" << m_OutputFile << "'"; setErrorCondition(-1); setErrorMessage(ss.str()); notify(getErrorMessage().c_str(), 0, UpdateErrorMessage); return err; } // std::cout << "Writing MRC File with Geometry of: " << std::endl; // std::cout << " N_z: " << m_Geometry->N_z << std::endl; // std::cout << " N_x: " << m_Geometry->N_x << std::endl; // std::cout << " N_y: " << m_Geometry->N_y << std::endl; MRCHeader mrcHeader; // Put one on the stack in case the programmer supplied a NULL pointer ::memset(&mrcHeader, 0, 1024); bool detachHeaderReference = false; if (NULL == m_MRCHeader) { m_MRCHeader = &mrcHeader; initializeMRCHeader(m_MRCHeader); detachHeaderReference = true; } // Update the header with our Dimensions m_MRCHeader->nx = (m_XDims[1] - m_XDims[0]); m_MRCHeader->ny = (m_YDims[1] - m_YDims[0]); m_MRCHeader->nz = (m_ZDims[1] - m_ZDims[0]); m_MRCHeader->mx = m_MRCHeader->nx; m_MRCHeader->my = m_MRCHeader->ny; m_MRCHeader->mz = m_MRCHeader->nz; m_MRCHeader->xlen = m_MRCHeader->nx; m_MRCHeader->ylen = m_MRCHeader->ny; m_MRCHeader->zlen = m_MRCHeader->nz; m_MRCHeader->next = sizeof(FEIHeader) * m_MRCHeader->nz; // Write the header writer.write(reinterpret_cast<char*>(m_MRCHeader), 1024); for(uint16_t i = 0; i < m_Geometry->N_z; ++i) { FEIHeader fei; ::memset(&fei, 0, sizeof(FEIHeader)); fei.pixelsize = static_cast<float>(m_Geometry->LengthX); writer.write(reinterpret_cast<char*>(&fei), sizeof(FEIHeader)); } size_t dims[2] = {m_MRCHeader->nx, m_MRCHeader->ny}; FloatImageType::Pointer sliceData = FloatImageType::New(dims, "temp slice data"); float* slice = sliceData->getPointer(0); size_t index = 0; Real_t d = 0.0; size_t count = 0; float mean = 0.0; float dmax = std::numeric_limits<Real_t>::min(); float dmin = std::numeric_limits<Real_t>::max(); for (int z = m_ZDims[1]-1; z >= m_ZDims[0]; z--) { index = 0; for (int y = m_YDims[0]; y < m_YDims[1]; ++y) { for (int x = m_XDims[0]; x < m_XDims[1]; ++x) { //index = (x * m_Geometry->N_y) + y; d = m_Geometry->Object->getValue(z, x, y); slice[index] = static_cast<float>(d); mean += slice[index]; count++; if(d > dmax) dmax = d; if(d < dmin) dmin = d; ++index; } } writer.write(reinterpret_cast<char*>(slice), sizeof(float) * dims[0] * dims[1]); } // Calculate the mean value mean = mean / count; // Update the values in the header of the file writer.setFilePointer64(76); // Set the position to the "amin" header entry writer.writeValue(&dmin); writer.writeValue(&dmax); writer.writeValue(&mean); if (detachHeaderReference == true) { m_MRCHeader = NULL; } setErrorCondition(0); setErrorMessage(""); notify("Done Writing the MRC Output File", 0, UpdateProgressMessage); err = 1; return err; } <|endoftext|>