text
stringlengths
54
60.6k
<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/favicon/favicon_util.h" #include "chrome/browser/history/history_types.h" #include "chrome/browser/history/select_favicon_frames.h" #include "content/public/browser/render_view_host.h" #include "googleurl/src/gurl.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/image/image_skia.h" // static std::vector<ui::ScaleFactor> FaviconUtil::GetFaviconScaleFactors() { const float kScale1x = ui::GetScaleFactorScale(ui::SCALE_FACTOR_100P); std::vector<ui::ScaleFactor> favicon_scale_factors = ui::GetSupportedScaleFactors(); // The scale factors returned from ui::GetSupportedScaleFactors() are sorted. // Insert the 1x scale factor such that GetFaviconScaleFactors() is sorted as // well. size_t insert_index = favicon_scale_factors.size(); for (size_t i = 0; i < favicon_scale_factors.size(); ++i) { float scale = ui::GetScaleFactorScale(favicon_scale_factors[i]); if (scale == kScale1x) { return favicon_scale_factors; } else if (scale > kScale1x) { insert_index = i; break; } } favicon_scale_factors.insert(favicon_scale_factors.begin() + insert_index, ui::SCALE_FACTOR_100P); return favicon_scale_factors; } // static gfx::Image FaviconUtil::SelectFaviconFramesFromPNGs( const std::vector<history::FaviconBitmapResult>& png_data, const std::vector<ui::ScaleFactor> scale_factors, int favicon_size) { std::vector<SkBitmap> bitmaps; for (size_t i = 0; i < png_data.size(); ++i) { if (!png_data[i].is_valid()) continue; SkBitmap bitmap; if (gfx::PNGCodec::Decode(png_data[i].bitmap_data->front(), png_data[i].bitmap_data->size(), &bitmap)) { bitmaps.push_back(bitmap); } } if (bitmaps.empty()) return gfx::Image(); gfx::ImageSkia resized_image_skia = SelectFaviconFrames(bitmaps, scale_factors, favicon_size, NULL); return gfx::Image(resized_image_skia); } // static size_t FaviconUtil::SelectBestFaviconFromBitmaps( const std::vector<SkBitmap>& bitmaps, const std::vector<ui::ScaleFactor>& scale_factors, int desired_size) { std::vector<gfx::Size> sizes; for (size_t i = 0; i < bitmaps.size(); ++i) sizes.push_back(gfx::Size(bitmaps[i].width(), bitmaps[i].height())); std::vector<size_t> selected_bitmap_indices; SelectFaviconFrameIndices(sizes, scale_factors, desired_size, &selected_bitmap_indices, NULL); DCHECK_EQ(1u, selected_bitmap_indices.size()); return selected_bitmap_indices[0]; } <commit_msg>Avoid decoding the favicon bytes if unnecessary in SelectFaviconFramesFromPNG().<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/favicon/favicon_util.h" #include "chrome/browser/history/history_types.h" #include "chrome/browser/history/select_favicon_frames.h" #include "content/public/browser/render_view_host.h" #include "googleurl/src/gurl.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/image/image_png_rep.h" #include "ui/gfx/image/image_skia.h" namespace { // Attempts to create a resulting image of DIP size |favicon_size| with // image reps of |scale_factors| without resizing or decoding the bitmap // data. // Returns an empty gfx::Image if the bitmap data must be resized. gfx::Image SelectFaviconFramesFromPNGsWithoutResizing( const std::vector<history::FaviconBitmapResult>& png_data, const std::vector<ui::ScaleFactor> scale_factors, int favicon_size) { if (png_data.size() != scale_factors.size()) return gfx::Image(); // A |favicon_size| of 0 indicates that the largest frame is desired. if (favicon_size == 0 && png_data.size() == 1) { scoped_refptr<base::RefCountedMemory> bitmap_data = png_data[0].bitmap_data; return gfx::Image::CreateFrom1xPNGBytes(bitmap_data->front(), bitmap_data->size()); } // Cache the scale factor for each pixel size as |scale_factors| may contain // any of GetFaviconScaleFactors() which may include scale factors not // supported by the platform. (ui::GetScaleFactorFromScale() cannot be used.) std::map<int, ui::ScaleFactor> desired_pixel_sizes; for (size_t i = 0; i < scale_factors.size(); ++i) { int pixel_size = floor(favicon_size * ui::GetScaleFactorScale(scale_factors[i])); desired_pixel_sizes[pixel_size] = scale_factors[i]; } std::vector<gfx::ImagePNGRep> png_reps; for (size_t i = 0; i < png_data.size(); ++i) { if (!png_data[i].is_valid()) return gfx::Image(); const gfx::Size& pixel_size = png_data[i].pixel_size; if (pixel_size.width() != pixel_size.height()) return gfx::Image(); std::map<int, ui::ScaleFactor>::iterator it = desired_pixel_sizes.find( pixel_size.width()); if (it == desired_pixel_sizes.end()) return gfx::Image(); png_reps.push_back(gfx::ImagePNGRep(png_data[i].bitmap_data, it->second)); } return gfx::Image(png_reps); } } // namespace // static std::vector<ui::ScaleFactor> FaviconUtil::GetFaviconScaleFactors() { const float kScale1x = ui::GetScaleFactorScale(ui::SCALE_FACTOR_100P); std::vector<ui::ScaleFactor> favicon_scale_factors = ui::GetSupportedScaleFactors(); // The scale factors returned from ui::GetSupportedScaleFactors() are sorted. // Insert the 1x scale factor such that GetFaviconScaleFactors() is sorted as // well. size_t insert_index = favicon_scale_factors.size(); for (size_t i = 0; i < favicon_scale_factors.size(); ++i) { float scale = ui::GetScaleFactorScale(favicon_scale_factors[i]); if (scale == kScale1x) { return favicon_scale_factors; } else if (scale > kScale1x) { insert_index = i; break; } } favicon_scale_factors.insert(favicon_scale_factors.begin() + insert_index, ui::SCALE_FACTOR_100P); return favicon_scale_factors; } // static gfx::Image FaviconUtil::SelectFaviconFramesFromPNGs( const std::vector<history::FaviconBitmapResult>& png_data, const std::vector<ui::ScaleFactor> scale_factors, int favicon_size) { // Attempt to create a result image without resizing the bitmap data or // decoding it. FaviconHandler stores already resized favicons into history // so no additional resizing should be needed in the common case. Skipping // decoding to ImageSkia is useful because the ImageSkia representation may // not be needed and because the decoding is done on the UI thread and the // decoding can be a significant performance hit if a user has many bookmarks. // TODO(pkotwicz): Move the decoding off the UI thread. gfx::Image without_resizing = SelectFaviconFramesFromPNGsWithoutResizing( png_data, scale_factors, favicon_size); if (!without_resizing.IsEmpty()) return without_resizing; std::vector<SkBitmap> bitmaps; for (size_t i = 0; i < png_data.size(); ++i) { if (!png_data[i].is_valid()) continue; SkBitmap bitmap; if (gfx::PNGCodec::Decode(png_data[i].bitmap_data->front(), png_data[i].bitmap_data->size(), &bitmap)) { bitmaps.push_back(bitmap); } } if (bitmaps.empty()) return gfx::Image(); gfx::ImageSkia resized_image_skia = SelectFaviconFrames(bitmaps, scale_factors, favicon_size, NULL); return gfx::Image(resized_image_skia); } // static size_t FaviconUtil::SelectBestFaviconFromBitmaps( const std::vector<SkBitmap>& bitmaps, const std::vector<ui::ScaleFactor>& scale_factors, int desired_size) { std::vector<gfx::Size> sizes; for (size_t i = 0; i < bitmaps.size(); ++i) sizes.push_back(gfx::Size(bitmaps[i].width(), bitmaps[i].height())); std::vector<size_t> selected_bitmap_indices; SelectFaviconFrameIndices(sizes, scale_factors, desired_size, &selected_bitmap_indices, NULL); DCHECK_EQ(1u, selected_bitmap_indices.size()); return selected_bitmap_indices[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/favicon/favicon_util.h" #include "chrome/browser/history/select_favicon_frames.h" #include "chrome/common/favicon/favicon_types.h" #include "skia/ext/image_operations.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/favicon_size.h" #include "ui/gfx/image/image_png_rep.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/size.h" #if defined(OS_MACOSX) && !defined(OS_IOS) #include "base/mac/mac_util.h" #endif // defined(OS_MACOSX) && !defined(OS_IOS) namespace { // Creates image reps of DIP size |favicon_size| for the subset of // |scale_factors| for which the image reps can be created without resizing // or decoding the bitmap data. std::vector<gfx::ImagePNGRep> SelectFaviconFramesFromPNGsWithoutResizing( const std::vector<chrome::FaviconBitmapResult>& png_data, const std::vector<ui::ScaleFactor>& scale_factors, int favicon_size) { std::vector<gfx::ImagePNGRep> png_reps; if (png_data.empty()) return png_reps; // A |favicon_size| of 0 indicates that the largest frame is desired. if (favicon_size == 0 && scale_factors.size() == 1) { int maximum_area = 0; scoped_refptr<base::RefCountedMemory> best_candidate; for (size_t i = 0; i < png_data.size(); ++i) { int area = png_data[i].pixel_size.GetArea(); if (area > maximum_area) { maximum_area = area; best_candidate = png_data[i].bitmap_data; } } png_reps.push_back(gfx::ImagePNGRep(best_candidate, scale_factors[0])); return png_reps; } // Cache the scale factor for each pixel size as |scale_factors| may contain // any of GetFaviconScaleFactors() which may include scale factors not // supported by the platform. (ui::GetScaleFactorFromScale() cannot be used.) std::map<int, ui::ScaleFactor> desired_pixel_sizes; for (size_t i = 0; i < scale_factors.size(); ++i) { int pixel_size = floor(favicon_size * ui::GetScaleFactorScale(scale_factors[i])); desired_pixel_sizes[pixel_size] = scale_factors[i]; } for (size_t i = 0; i < png_data.size(); ++i) { if (!png_data[i].is_valid()) continue; const gfx::Size& pixel_size = png_data[i].pixel_size; if (pixel_size.width() != pixel_size.height()) continue; std::map<int, ui::ScaleFactor>::iterator it = desired_pixel_sizes.find( pixel_size.width()); if (it == desired_pixel_sizes.end()) continue; png_reps.push_back(gfx::ImagePNGRep(png_data[i].bitmap_data, it->second)); } return png_reps; } } // namespace // static std::vector<ui::ScaleFactor> FaviconUtil::GetFaviconScaleFactors() { const float kScale1x = ui::GetScaleFactorScale(ui::SCALE_FACTOR_100P); std::vector<ui::ScaleFactor> favicon_scale_factors = ui::GetSupportedScaleFactors(); // The scale factors returned from ui::GetSupportedScaleFactors() are sorted. // Insert the 1x scale factor such that GetFaviconScaleFactors() is sorted as // well. size_t insert_index = favicon_scale_factors.size(); for (size_t i = 0; i < favicon_scale_factors.size(); ++i) { float scale = ui::GetScaleFactorScale(favicon_scale_factors[i]); if (scale == kScale1x) { return favicon_scale_factors; } else if (scale > kScale1x) { insert_index = i; break; } } // TODO(ios): 100p should not be necessary on iOS retina devices. However // the sync service only supports syncing 100p favicons. Until sync supports // other scales 100p is needed in the list of scale factors to retrieve and // store the favicons in both 100p for sync and 200p for display. cr/160503. favicon_scale_factors.insert(favicon_scale_factors.begin() + insert_index, ui::SCALE_FACTOR_100P); return favicon_scale_factors; } // static void FaviconUtil::SetFaviconColorSpace(gfx::Image* image) { #if defined(OS_MACOSX) && !defined(OS_IOS) image->SetSourceColorSpace(base::mac::GetSystemColorSpace()); #endif // defined(OS_MACOSX) && !defined(OS_IOS) } // static gfx::Image FaviconUtil::SelectFaviconFramesFromPNGs( const std::vector<chrome::FaviconBitmapResult>& png_data, const std::vector<ui::ScaleFactor>& scale_factors, int favicon_size) { // Create image reps for as many scale factors as possible without resizing // the bitmap data or decoding it. FaviconHandler stores already resized // favicons into history so no additional resizing should be needed in the // common case. // Creating the gfx::Image from |png_data| without resizing or decoding if // possible is important because: // - Sync does a byte-to-byte comparison of gfx::Image::As1xPNGBytes() to // the data it put into the database in order to determine whether any // updates should be pushed to sync. // - The decoding occurs on the UI thread and the decoding can be a // significant performance hit if a user has many bookmarks. // TODO(pkotwicz): Move the decoding off the UI thread. std::vector<gfx::ImagePNGRep> png_reps = SelectFaviconFramesFromPNGsWithoutResizing(png_data, scale_factors, favicon_size); std::vector<ui::ScaleFactor> scale_factors_to_generate = scale_factors; for (size_t i = 0; i < png_reps.size(); ++i) { std::vector<ui::ScaleFactor>::iterator it = std::find( scale_factors_to_generate.begin(), scale_factors_to_generate.end(), png_reps[i].scale_factor); CHECK(it != scale_factors_to_generate.end()); scale_factors_to_generate.erase(it); } if (scale_factors_to_generate.empty()) return gfx::Image(png_reps); std::vector<SkBitmap> bitmaps; for (size_t i = 0; i < png_data.size(); ++i) { if (!png_data[i].is_valid()) continue; SkBitmap bitmap; if (gfx::PNGCodec::Decode(png_data[i].bitmap_data->front(), png_data[i].bitmap_data->size(), &bitmap)) { bitmaps.push_back(bitmap); } } if (bitmaps.empty()) return gfx::Image(); gfx::ImageSkia resized_image_skia = SelectFaviconFrames(bitmaps, scale_factors_to_generate, favicon_size, NULL); if (png_reps.empty()) return gfx::Image(resized_image_skia); std::vector<gfx::ImageSkiaRep> resized_image_skia_reps = resized_image_skia.image_reps(); for (size_t i = 0; i < resized_image_skia_reps.size(); ++i) { scoped_refptr<base::RefCountedBytes> png_bytes(new base::RefCountedBytes()); if (gfx::PNGCodec::EncodeBGRASkBitmap( resized_image_skia_reps[i].sk_bitmap(), false, &png_bytes->data())) { png_reps.push_back(gfx::ImagePNGRep(png_bytes, resized_image_skia_reps[i].scale_factor())); } } return gfx::Image(png_reps); } // static size_t FaviconUtil::SelectBestFaviconFromBitmaps( const std::vector<SkBitmap>& bitmaps, const std::vector<ui::ScaleFactor>& scale_factors, int desired_size) { std::vector<gfx::Size> sizes; for (size_t i = 0; i < bitmaps.size(); ++i) sizes.push_back(gfx::Size(bitmaps[i].width(), bitmaps[i].height())); std::vector<size_t> selected_bitmap_indices; SelectFaviconFrameIndices(sizes, scale_factors, desired_size, &selected_bitmap_indices, NULL); DCHECK_EQ(1u, selected_bitmap_indices.size()); return selected_bitmap_indices[0]; } <commit_msg>Never decode the favicon in FaviconUtil::SelectFaviconFramesFromPNGs() to SkBitmap when the desired size is 0. The decoding is unnecessary. Giving the largest PNG a scale factor of 100P matches the behavior in SelectFaviconFrames(). This is a corner case that I need to fix in order fix 278457<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/favicon/favicon_util.h" #include "chrome/browser/history/select_favicon_frames.h" #include "chrome/common/favicon/favicon_types.h" #include "skia/ext/image_operations.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/favicon_size.h" #include "ui/gfx/image/image_png_rep.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/size.h" #if defined(OS_MACOSX) && !defined(OS_IOS) #include "base/mac/mac_util.h" #endif // defined(OS_MACOSX) && !defined(OS_IOS) namespace { // Creates image reps of DIP size |favicon_size| for the subset of // |scale_factors| for which the image reps can be created without resizing // or decoding the bitmap data. std::vector<gfx::ImagePNGRep> SelectFaviconFramesFromPNGsWithoutResizing( const std::vector<chrome::FaviconBitmapResult>& png_data, const std::vector<ui::ScaleFactor>& scale_factors, int favicon_size) { std::vector<gfx::ImagePNGRep> png_reps; if (png_data.empty()) return png_reps; // A |favicon_size| of 0 indicates that the largest frame is desired. if (favicon_size == 0) { int maximum_area = 0; scoped_refptr<base::RefCountedMemory> best_candidate; for (size_t i = 0; i < png_data.size(); ++i) { int area = png_data[i].pixel_size.GetArea(); if (area > maximum_area) { maximum_area = area; best_candidate = png_data[i].bitmap_data; } } png_reps.push_back(gfx::ImagePNGRep(best_candidate, ui::SCALE_FACTOR_100P)); return png_reps; } // Cache the scale factor for each pixel size as |scale_factors| may contain // any of GetFaviconScaleFactors() which may include scale factors not // supported by the platform. (ui::GetScaleFactorFromScale() cannot be used.) std::map<int, ui::ScaleFactor> desired_pixel_sizes; for (size_t i = 0; i < scale_factors.size(); ++i) { int pixel_size = floor(favicon_size * ui::GetScaleFactorScale(scale_factors[i])); desired_pixel_sizes[pixel_size] = scale_factors[i]; } for (size_t i = 0; i < png_data.size(); ++i) { if (!png_data[i].is_valid()) continue; const gfx::Size& pixel_size = png_data[i].pixel_size; if (pixel_size.width() != pixel_size.height()) continue; std::map<int, ui::ScaleFactor>::iterator it = desired_pixel_sizes.find( pixel_size.width()); if (it == desired_pixel_sizes.end()) continue; png_reps.push_back(gfx::ImagePNGRep(png_data[i].bitmap_data, it->second)); } return png_reps; } } // namespace // static std::vector<ui::ScaleFactor> FaviconUtil::GetFaviconScaleFactors() { const float kScale1x = ui::GetScaleFactorScale(ui::SCALE_FACTOR_100P); std::vector<ui::ScaleFactor> favicon_scale_factors = ui::GetSupportedScaleFactors(); // The scale factors returned from ui::GetSupportedScaleFactors() are sorted. // Insert the 1x scale factor such that GetFaviconScaleFactors() is sorted as // well. size_t insert_index = favicon_scale_factors.size(); for (size_t i = 0; i < favicon_scale_factors.size(); ++i) { float scale = ui::GetScaleFactorScale(favicon_scale_factors[i]); if (scale == kScale1x) { return favicon_scale_factors; } else if (scale > kScale1x) { insert_index = i; break; } } // TODO(ios): 100p should not be necessary on iOS retina devices. However // the sync service only supports syncing 100p favicons. Until sync supports // other scales 100p is needed in the list of scale factors to retrieve and // store the favicons in both 100p for sync and 200p for display. cr/160503. favicon_scale_factors.insert(favicon_scale_factors.begin() + insert_index, ui::SCALE_FACTOR_100P); return favicon_scale_factors; } // static void FaviconUtil::SetFaviconColorSpace(gfx::Image* image) { #if defined(OS_MACOSX) && !defined(OS_IOS) image->SetSourceColorSpace(base::mac::GetSystemColorSpace()); #endif // defined(OS_MACOSX) && !defined(OS_IOS) } // static gfx::Image FaviconUtil::SelectFaviconFramesFromPNGs( const std::vector<chrome::FaviconBitmapResult>& png_data, const std::vector<ui::ScaleFactor>& scale_factors, int favicon_size) { // Create image reps for as many scale factors as possible without resizing // the bitmap data or decoding it. FaviconHandler stores already resized // favicons into history so no additional resizing should be needed in the // common case. // Creating the gfx::Image from |png_data| without resizing or decoding if // possible is important because: // - Sync does a byte-to-byte comparison of gfx::Image::As1xPNGBytes() to // the data it put into the database in order to determine whether any // updates should be pushed to sync. // - The decoding occurs on the UI thread and the decoding can be a // significant performance hit if a user has many bookmarks. // TODO(pkotwicz): Move the decoding off the UI thread. std::vector<gfx::ImagePNGRep> png_reps = SelectFaviconFramesFromPNGsWithoutResizing(png_data, scale_factors, favicon_size); // SelectFaviconFramesFromPNGsWithoutResizing() should have selected the // largest favicon if |favicon_size| == 0. if (favicon_size == 0) return gfx::Image(png_reps); std::vector<ui::ScaleFactor> scale_factors_to_generate = scale_factors; for (size_t i = 0; i < png_reps.size(); ++i) { std::vector<ui::ScaleFactor>::iterator it = std::find( scale_factors_to_generate.begin(), scale_factors_to_generate.end(), png_reps[i].scale_factor); CHECK(it != scale_factors_to_generate.end()); scale_factors_to_generate.erase(it); } if (scale_factors_to_generate.empty()) return gfx::Image(png_reps); std::vector<SkBitmap> bitmaps; for (size_t i = 0; i < png_data.size(); ++i) { if (!png_data[i].is_valid()) continue; SkBitmap bitmap; if (gfx::PNGCodec::Decode(png_data[i].bitmap_data->front(), png_data[i].bitmap_data->size(), &bitmap)) { bitmaps.push_back(bitmap); } } if (bitmaps.empty()) return gfx::Image(); gfx::ImageSkia resized_image_skia = SelectFaviconFrames(bitmaps, scale_factors_to_generate, favicon_size, NULL); if (png_reps.empty()) return gfx::Image(resized_image_skia); std::vector<gfx::ImageSkiaRep> resized_image_skia_reps = resized_image_skia.image_reps(); for (size_t i = 0; i < resized_image_skia_reps.size(); ++i) { scoped_refptr<base::RefCountedBytes> png_bytes(new base::RefCountedBytes()); if (gfx::PNGCodec::EncodeBGRASkBitmap( resized_image_skia_reps[i].sk_bitmap(), false, &png_bytes->data())) { png_reps.push_back(gfx::ImagePNGRep(png_bytes, resized_image_skia_reps[i].scale_factor())); } } return gfx::Image(png_reps); } // static size_t FaviconUtil::SelectBestFaviconFromBitmaps( const std::vector<SkBitmap>& bitmaps, const std::vector<ui::ScaleFactor>& scale_factors, int desired_size) { std::vector<gfx::Size> sizes; for (size_t i = 0; i < bitmaps.size(); ++i) sizes.push_back(gfx::Size(bitmaps[i].width(), bitmaps[i].height())); std::vector<size_t> selected_bitmap_indices; SelectFaviconFrameIndices(sizes, scale_factors, desired_size, &selected_bitmap_indices, NULL); DCHECK_EQ(1u, selected_bitmap_indices.size()); return selected_bitmap_indices[0]; } <|endoftext|>
<commit_before><commit_msg>CtxBlockOacc: Fix assert in DeclareSharedVar<commit_after><|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/gtk/first_run_dialog.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/message_loop.h" #include "base/utf_string_conversions.h" #include "chrome/browser/gtk/gtk_chrome_link_button.h" #include "chrome/browser/gtk/gtk_floating_container.h" #include "chrome/browser/gtk/gtk_util.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/process_singleton.h" #include "chrome/browser/profile.h" #include "chrome/browser/shell_integration.h" #include "chrome/installer/util/google_update_settings.h" #include "gfx/gtk_util.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" #include "grit/theme_resources.h" #if defined(USE_LINUX_BREAKPAD) #include "chrome/app/breakpad_linux.h" #endif namespace { const gchar* kSearchEngineKey = "template-url-search-engine"; // Height of the label that displays the search engine's logo (in lieu of the // actual logo) in chromium. const int kLogoLabelHeight = 100; // The width of the explanatory label. The 180 is the width of the large images. const int kExplanationWidth = 3 * 180; // Horizontal spacing between search engine choices. const int kSearchEngineSpacing = 6; // Set the (x, y) coordinates of the welcome message (which floats on top of // the omnibox image at the top of the first run dialog). void SetWelcomePosition(GtkFloatingContainer* container, GtkAllocation* allocation, GtkWidget* label) { GValue value = { 0, }; g_value_init(&value, G_TYPE_INT); g_value_set_int(&value, gtk_util::kContentAreaSpacing); gtk_container_child_set_property(GTK_CONTAINER(container), label, "x", &value); GtkRequisition req; gtk_widget_size_request(label, &req); int y = allocation->height / 2 - req.height / 2; g_value_set_int(&value, y); gtk_container_child_set_property(GTK_CONTAINER(container), label, "y", &value); g_value_unset(&value); } } // namespace // static bool FirstRunDialog::Show(Profile* profile, bool randomize_search_engine_order) { int response = -1; // Object deletes itself. new FirstRunDialog(profile, randomize_search_engine_order, response); // TODO(port): it should be sufficient to just run the dialog: // int response = gtk_dialog_run(GTK_DIALOG(dialog)); // but that spins a nested message loop and hoses us. :( // http://code.google.com/p/chromium/issues/detail?id=12552 // Instead, run a loop and extract the response manually. MessageLoop::current()->Run(); return (response == GTK_RESPONSE_ACCEPT); } FirstRunDialog::FirstRunDialog(Profile* profile, bool randomize_search_engine_order, int& response) : search_engine_window_(NULL), dialog_(NULL), report_crashes_(NULL), make_default_(NULL), profile_(profile), chosen_search_engine_(NULL), response_(response) { search_engines_model_ = profile_->GetTemplateURLModel(); ShowSearchEngineWindow(); search_engines_model_->AddObserver(this); if (search_engines_model_->loaded()) OnTemplateURLModelChanged(); else search_engines_model_->Load(); } FirstRunDialog::~FirstRunDialog() { } void FirstRunDialog::ShowSearchEngineWindow() { search_engine_window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title( GTK_WINDOW(search_engine_window_), l10n_util::GetStringUTF8(IDS_FIRSTRUN_DLG_TITLE).c_str()); gtk_window_set_resizable(GTK_WINDOW(search_engine_window_), FALSE); g_signal_connect(search_engine_window_, "destroy", G_CALLBACK(OnSearchEngineWindowDestroyThunk), this); GtkWidget* content_area = gtk_vbox_new(FALSE, 0); gtk_container_add(GTK_CONTAINER(search_engine_window_), content_area); GdkPixbuf* pixbuf = ResourceBundle::GetSharedInstance().GetPixbufNamed( IDR_SEARCH_ENGINE_DIALOG_TOP); GtkWidget* top_image = gtk_image_new_from_pixbuf(pixbuf); // Right align the image. gtk_misc_set_alignment(GTK_MISC(top_image), 1, 0); gtk_widget_set_size_request(top_image, 0, -1); GtkWidget* welcome_message = gtk_util::CreateBoldLabel( l10n_util::GetStringUTF8(IDS_FR_SEARCH_MAIN_LABEL)); GtkWidget* top_area = gtk_floating_container_new(); gtk_container_add(GTK_CONTAINER(top_area), top_image); gtk_floating_container_add_floating(GTK_FLOATING_CONTAINER(top_area), welcome_message); g_signal_connect(top_area, "set-floating-position", G_CALLBACK(SetWelcomePosition), welcome_message); gtk_box_pack_start(GTK_BOX(content_area), top_area, FALSE, FALSE, 0); GtkWidget* bubble_area_background = gtk_event_box_new(); gtk_widget_modify_bg(bubble_area_background, GTK_STATE_NORMAL, &gfx::kGdkWhite); GtkWidget* bubble_area_box = gtk_vbox_new(FALSE, 0); gtk_container_set_border_width(GTK_CONTAINER(bubble_area_box), gtk_util::kContentAreaSpacing); gtk_container_add(GTK_CONTAINER(bubble_area_background), bubble_area_box); GtkWidget* explanation = gtk_label_new( l10n_util::GetStringFUTF8(IDS_FR_SEARCH_TEXT, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)).c_str()); gtk_util::SetLabelColor(explanation, &gfx::kGdkBlack); gtk_label_set_line_wrap(GTK_LABEL(explanation), TRUE); gtk_widget_set_size_request(explanation, kExplanationWidth, -1); gtk_box_pack_start(GTK_BOX(bubble_area_box), explanation, FALSE, FALSE, 0); // We will fill this in after the TemplateURLModel has loaded. search_engine_hbox_ = gtk_hbox_new(FALSE, kSearchEngineSpacing); gtk_box_pack_start(GTK_BOX(bubble_area_box), search_engine_hbox_, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(content_area), bubble_area_background, TRUE, TRUE, 0); gtk_widget_show_all(content_area); gtk_window_present(GTK_WINDOW(search_engine_window_)); } void FirstRunDialog::ShowDialog() { #if defined(GOOGLE_CHROME_BUILD) dialog_ = gtk_dialog_new_with_buttons( l10n_util::GetStringUTF8(IDS_FIRSTRUN_DLG_TITLE).c_str(), NULL, // No parent (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR), GTK_STOCK_QUIT, GTK_RESPONSE_REJECT, NULL); gtk_util::AddButtonToDialog(dialog_, l10n_util::GetStringUTF8(IDS_FIRSTRUN_DLG_OK).c_str(), GTK_STOCK_APPLY, GTK_RESPONSE_ACCEPT); gtk_window_set_resizable(GTK_WINDOW(dialog_), FALSE); g_signal_connect(dialog_, "delete-event", G_CALLBACK(gtk_widget_hide_on_delete), NULL); GtkWidget* content_area = GTK_DIALOG(dialog_)->vbox; GtkWidget* check_label = gtk_label_new( l10n_util::GetStringUTF8(IDS_OPTIONS_ENABLE_LOGGING).c_str()); gtk_label_set_line_wrap(GTK_LABEL(check_label), TRUE); GtkWidget* learn_more_link = gtk_chrome_link_button_new( l10n_util::GetStringUTF8(IDS_LEARN_MORE).c_str()); // Stick it in an hbox so it doesn't expand to the whole width. GtkWidget* learn_more_hbox = gtk_hbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX(learn_more_hbox), gtk_util::IndentWidget(learn_more_link), FALSE, FALSE, 0); g_signal_connect(learn_more_link, "clicked", G_CALLBACK(OnLearnMoreLinkClickedThunk), this); report_crashes_ = gtk_check_button_new(); gtk_container_add(GTK_CONTAINER(report_crashes_), check_label); gtk_box_pack_start(GTK_BOX(content_area), report_crashes_, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(content_area), learn_more_hbox, FALSE, FALSE, 0); make_default_ = gtk_check_button_new_with_label( l10n_util::GetStringUTF8(IDS_FR_CUSTOMIZE_DEFAULT_BROWSER).c_str()); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(make_default_), TRUE); gtk_box_pack_start(GTK_BOX(content_area), make_default_, FALSE, FALSE, 0); g_signal_connect(dialog_, "response", G_CALLBACK(OnResponseDialogThunk), this); gtk_widget_show_all(dialog_); #else // !defined(GOOGLE_CHROME_BUILD) // We don't show the dialog in chromium. Pretend the user accepted. OnResponseDialog(NULL, GTK_RESPONSE_ACCEPT); #endif // !defined(GOOGLE_CHROME_BUILD) } void FirstRunDialog::OnTemplateURLModelChanged() { // We only watch the search engine model change once, on load. Remove // observer so we don't try to redraw if engines change under us. search_engines_model_->RemoveObserver(this); // Add search engines in search_engines_model_ to buttons list. The // first three will always be from prepopulated data. std::vector<const TemplateURL*> template_urls = search_engines_model_->GetTemplateURLs(); std::vector<const TemplateURL*>::iterator search_engine_iter; std::string choose_text = l10n_util::GetStringUTF8(IDS_FR_SEARCH_CHOOSE); for (std::vector<const TemplateURL*>::iterator search_engine_iter = template_urls.begin(); search_engine_iter < template_urls.end() && search_engine_iter < template_urls.begin() + 3; ++search_engine_iter) { // Create a container for the search engine widgets. GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing); // We show text on Chromium and images on Google Chrome. bool show_images = false; #if defined(GOOGLE_CHROME_BUILD) show_images = true; #endif // Create the image (maybe). int logo_id = (*search_engine_iter)->logo_id(); if (show_images && logo_id > 0) { GdkPixbuf* pixbuf = ResourceBundle::GetSharedInstance().GetPixbufNamed(logo_id); GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf); gtk_box_pack_start(GTK_BOX(vbox), image, FALSE, FALSE, 0); } else { GtkWidget* logo_label = gtk_label_new(NULL); char* markup = g_markup_printf_escaped( "<span weight='bold' size='x-large' color='black'>%s</span>", WideToUTF8((*search_engine_iter)->short_name()).c_str()); gtk_label_set_markup(GTK_LABEL(logo_label), markup); g_free(markup); gtk_widget_set_size_request(logo_label, -1, kLogoLabelHeight); gtk_box_pack_start(GTK_BOX(vbox), logo_label, FALSE, FALSE, 0); } // Create the button. GtkWidget* button = gtk_button_new_with_label(choose_text.c_str()); g_signal_connect(button, "clicked", G_CALLBACK(OnSearchEngineButtonClickedThunk), this); g_object_set_data(G_OBJECT(button), kSearchEngineKey, const_cast<TemplateURL*>(*search_engine_iter)); GtkWidget* button_centerer = gtk_hbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX(button_centerer), button, TRUE, FALSE, 0); gtk_box_pack_start(GTK_BOX(vbox), button_centerer, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(search_engine_hbox_), vbox, TRUE, TRUE, 0); gtk_widget_show_all(search_engine_hbox_); } } void FirstRunDialog::OnSearchEngineButtonClicked(GtkWidget* sender) { chosen_search_engine_ = static_cast<TemplateURL*>( g_object_get_data(G_OBJECT(sender), kSearchEngineKey)); gtk_widget_destroy(search_engine_window_); } void FirstRunDialog::OnSearchEngineWindowDestroy(GtkWidget* sender) { search_engine_window_ = NULL; if (chosen_search_engine_) { search_engines_model_->SetDefaultSearchProvider(chosen_search_engine_); ShowDialog(); } else { FirstRunDone(); } } void FirstRunDialog::OnResponseDialog(GtkWidget* widget, int response) { if (dialog_) gtk_widget_hide_all(dialog_); response_ = response; if (response == GTK_RESPONSE_ACCEPT) { // Mark that first run has ran. FirstRun::CreateSentinel(); // Check if user has opted into reporting. if (report_crashes_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(report_crashes_))) { #if defined(USE_LINUX_BREAKPAD) if (GoogleUpdateSettings::SetCollectStatsConsent(true)) { InitCrashReporter(); } #endif } else { GoogleUpdateSettings::SetCollectStatsConsent(false); } // If selected set as default browser. if (make_default_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(make_default_))) { ShellIntegration::SetAsDefaultBrowser(); } } FirstRunDone(); } void FirstRunDialog::OnLearnMoreLinkClicked(GtkButton* button) { platform_util::OpenExternal(GURL( l10n_util::GetStringUTF8(IDS_LEARN_MORE_REPORTING_URL))); } void FirstRunDialog::FirstRunDone() { FirstRun::SetShowWelcomePagePref(); if (dialog_) gtk_widget_destroy(dialog_); MessageLoop::current()->Quit(); delete this; } <commit_msg>[linux] Skip stats question dialog on Linux if managed by policy.<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/gtk/first_run_dialog.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/message_loop.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/gtk/gtk_chrome_link_button.h" #include "chrome/browser/gtk/gtk_floating_container.h" #include "chrome/browser/gtk/gtk_util.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/process_singleton.h" #include "chrome/browser/profile.h" #include "chrome/browser/shell_integration.h" #include "chrome/common/pref_names.h" #include "chrome/installer/util/google_update_settings.h" #include "gfx/gtk_util.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" #include "grit/theme_resources.h" #if defined(USE_LINUX_BREAKPAD) #include "chrome/app/breakpad_linux.h" #endif namespace { const gchar* kSearchEngineKey = "template-url-search-engine"; // Height of the label that displays the search engine's logo (in lieu of the // actual logo) in chromium. const int kLogoLabelHeight = 100; // The width of the explanatory label. The 180 is the width of the large images. const int kExplanationWidth = 3 * 180; // Horizontal spacing between search engine choices. const int kSearchEngineSpacing = 6; // Set the (x, y) coordinates of the welcome message (which floats on top of // the omnibox image at the top of the first run dialog). void SetWelcomePosition(GtkFloatingContainer* container, GtkAllocation* allocation, GtkWidget* label) { GValue value = { 0, }; g_value_init(&value, G_TYPE_INT); g_value_set_int(&value, gtk_util::kContentAreaSpacing); gtk_container_child_set_property(GTK_CONTAINER(container), label, "x", &value); GtkRequisition req; gtk_widget_size_request(label, &req); int y = allocation->height / 2 - req.height / 2; g_value_set_int(&value, y); gtk_container_child_set_property(GTK_CONTAINER(container), label, "y", &value); g_value_unset(&value); } } // namespace // static bool FirstRunDialog::Show(Profile* profile, bool randomize_search_engine_order) { int response = -1; // Object deletes itself. new FirstRunDialog(profile, randomize_search_engine_order, response); // TODO(port): it should be sufficient to just run the dialog: // int response = gtk_dialog_run(GTK_DIALOG(dialog)); // but that spins a nested message loop and hoses us. :( // http://code.google.com/p/chromium/issues/detail?id=12552 // Instead, run a loop and extract the response manually. MessageLoop::current()->Run(); return (response == GTK_RESPONSE_ACCEPT); } FirstRunDialog::FirstRunDialog(Profile* profile, bool randomize_search_engine_order, int& response) : search_engine_window_(NULL), dialog_(NULL), report_crashes_(NULL), make_default_(NULL), profile_(profile), chosen_search_engine_(NULL), response_(response) { search_engines_model_ = profile_->GetTemplateURLModel(); ShowSearchEngineWindow(); search_engines_model_->AddObserver(this); if (search_engines_model_->loaded()) OnTemplateURLModelChanged(); else search_engines_model_->Load(); } FirstRunDialog::~FirstRunDialog() { } void FirstRunDialog::ShowSearchEngineWindow() { search_engine_window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title( GTK_WINDOW(search_engine_window_), l10n_util::GetStringUTF8(IDS_FIRSTRUN_DLG_TITLE).c_str()); gtk_window_set_resizable(GTK_WINDOW(search_engine_window_), FALSE); g_signal_connect(search_engine_window_, "destroy", G_CALLBACK(OnSearchEngineWindowDestroyThunk), this); GtkWidget* content_area = gtk_vbox_new(FALSE, 0); gtk_container_add(GTK_CONTAINER(search_engine_window_), content_area); GdkPixbuf* pixbuf = ResourceBundle::GetSharedInstance().GetPixbufNamed( IDR_SEARCH_ENGINE_DIALOG_TOP); GtkWidget* top_image = gtk_image_new_from_pixbuf(pixbuf); // Right align the image. gtk_misc_set_alignment(GTK_MISC(top_image), 1, 0); gtk_widget_set_size_request(top_image, 0, -1); GtkWidget* welcome_message = gtk_util::CreateBoldLabel( l10n_util::GetStringUTF8(IDS_FR_SEARCH_MAIN_LABEL)); GtkWidget* top_area = gtk_floating_container_new(); gtk_container_add(GTK_CONTAINER(top_area), top_image); gtk_floating_container_add_floating(GTK_FLOATING_CONTAINER(top_area), welcome_message); g_signal_connect(top_area, "set-floating-position", G_CALLBACK(SetWelcomePosition), welcome_message); gtk_box_pack_start(GTK_BOX(content_area), top_area, FALSE, FALSE, 0); GtkWidget* bubble_area_background = gtk_event_box_new(); gtk_widget_modify_bg(bubble_area_background, GTK_STATE_NORMAL, &gfx::kGdkWhite); GtkWidget* bubble_area_box = gtk_vbox_new(FALSE, 0); gtk_container_set_border_width(GTK_CONTAINER(bubble_area_box), gtk_util::kContentAreaSpacing); gtk_container_add(GTK_CONTAINER(bubble_area_background), bubble_area_box); GtkWidget* explanation = gtk_label_new( l10n_util::GetStringFUTF8(IDS_FR_SEARCH_TEXT, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)).c_str()); gtk_util::SetLabelColor(explanation, &gfx::kGdkBlack); gtk_label_set_line_wrap(GTK_LABEL(explanation), TRUE); gtk_widget_set_size_request(explanation, kExplanationWidth, -1); gtk_box_pack_start(GTK_BOX(bubble_area_box), explanation, FALSE, FALSE, 0); // We will fill this in after the TemplateURLModel has loaded. search_engine_hbox_ = gtk_hbox_new(FALSE, kSearchEngineSpacing); gtk_box_pack_start(GTK_BOX(bubble_area_box), search_engine_hbox_, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(content_area), bubble_area_background, TRUE, TRUE, 0); gtk_widget_show_all(content_area); gtk_window_present(GTK_WINDOW(search_engine_window_)); } void FirstRunDialog::ShowDialog() { // The purpose of the dialog is to ask the user to enable stats and crash // reporting. This setting may be controlled through configuration management // in enterprise scenarios. If that is the case, skip the dialog entirely, // it's not worth bothering the user for only the default browser question // (which is likely to be forced in enterprise deployments anyway). const PrefService::Preference* metrics_reporting_pref = g_browser_process->local_state()->FindPreference( prefs::kMetricsReportingEnabled); if (metrics_reporting_pref && metrics_reporting_pref->IsManaged()) { OnResponseDialog(NULL, GTK_RESPONSE_ACCEPT); return; } #if defined(GOOGLE_CHROME_BUILD) dialog_ = gtk_dialog_new_with_buttons( l10n_util::GetStringUTF8(IDS_FIRSTRUN_DLG_TITLE).c_str(), NULL, // No parent (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR), GTK_STOCK_QUIT, GTK_RESPONSE_REJECT, NULL); gtk_util::AddButtonToDialog(dialog_, l10n_util::GetStringUTF8(IDS_FIRSTRUN_DLG_OK).c_str(), GTK_STOCK_APPLY, GTK_RESPONSE_ACCEPT); gtk_window_set_resizable(GTK_WINDOW(dialog_), FALSE); g_signal_connect(dialog_, "delete-event", G_CALLBACK(gtk_widget_hide_on_delete), NULL); GtkWidget* content_area = GTK_DIALOG(dialog_)->vbox; GtkWidget* check_label = gtk_label_new( l10n_util::GetStringUTF8(IDS_OPTIONS_ENABLE_LOGGING).c_str()); gtk_label_set_line_wrap(GTK_LABEL(check_label), TRUE); GtkWidget* learn_more_link = gtk_chrome_link_button_new( l10n_util::GetStringUTF8(IDS_LEARN_MORE).c_str()); // Stick it in an hbox so it doesn't expand to the whole width. GtkWidget* learn_more_hbox = gtk_hbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX(learn_more_hbox), gtk_util::IndentWidget(learn_more_link), FALSE, FALSE, 0); g_signal_connect(learn_more_link, "clicked", G_CALLBACK(OnLearnMoreLinkClickedThunk), this); report_crashes_ = gtk_check_button_new(); gtk_container_add(GTK_CONTAINER(report_crashes_), check_label); gtk_box_pack_start(GTK_BOX(content_area), report_crashes_, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(content_area), learn_more_hbox, FALSE, FALSE, 0); make_default_ = gtk_check_button_new_with_label( l10n_util::GetStringUTF8(IDS_FR_CUSTOMIZE_DEFAULT_BROWSER).c_str()); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(make_default_), TRUE); gtk_box_pack_start(GTK_BOX(content_area), make_default_, FALSE, FALSE, 0); g_signal_connect(dialog_, "response", G_CALLBACK(OnResponseDialogThunk), this); gtk_widget_show_all(dialog_); #else // !defined(GOOGLE_CHROME_BUILD) // We don't show the dialog in chromium. Pretend the user accepted. OnResponseDialog(NULL, GTK_RESPONSE_ACCEPT); #endif // !defined(GOOGLE_CHROME_BUILD) } void FirstRunDialog::OnTemplateURLModelChanged() { // We only watch the search engine model change once, on load. Remove // observer so we don't try to redraw if engines change under us. search_engines_model_->RemoveObserver(this); // Add search engines in search_engines_model_ to buttons list. The // first three will always be from prepopulated data. std::vector<const TemplateURL*> template_urls = search_engines_model_->GetTemplateURLs(); std::vector<const TemplateURL*>::iterator search_engine_iter; std::string choose_text = l10n_util::GetStringUTF8(IDS_FR_SEARCH_CHOOSE); for (std::vector<const TemplateURL*>::iterator search_engine_iter = template_urls.begin(); search_engine_iter < template_urls.end() && search_engine_iter < template_urls.begin() + 3; ++search_engine_iter) { // Create a container for the search engine widgets. GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing); // We show text on Chromium and images on Google Chrome. bool show_images = false; #if defined(GOOGLE_CHROME_BUILD) show_images = true; #endif // Create the image (maybe). int logo_id = (*search_engine_iter)->logo_id(); if (show_images && logo_id > 0) { GdkPixbuf* pixbuf = ResourceBundle::GetSharedInstance().GetPixbufNamed(logo_id); GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf); gtk_box_pack_start(GTK_BOX(vbox), image, FALSE, FALSE, 0); } else { GtkWidget* logo_label = gtk_label_new(NULL); char* markup = g_markup_printf_escaped( "<span weight='bold' size='x-large' color='black'>%s</span>", WideToUTF8((*search_engine_iter)->short_name()).c_str()); gtk_label_set_markup(GTK_LABEL(logo_label), markup); g_free(markup); gtk_widget_set_size_request(logo_label, -1, kLogoLabelHeight); gtk_box_pack_start(GTK_BOX(vbox), logo_label, FALSE, FALSE, 0); } // Create the button. GtkWidget* button = gtk_button_new_with_label(choose_text.c_str()); g_signal_connect(button, "clicked", G_CALLBACK(OnSearchEngineButtonClickedThunk), this); g_object_set_data(G_OBJECT(button), kSearchEngineKey, const_cast<TemplateURL*>(*search_engine_iter)); GtkWidget* button_centerer = gtk_hbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX(button_centerer), button, TRUE, FALSE, 0); gtk_box_pack_start(GTK_BOX(vbox), button_centerer, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(search_engine_hbox_), vbox, TRUE, TRUE, 0); gtk_widget_show_all(search_engine_hbox_); } } void FirstRunDialog::OnSearchEngineButtonClicked(GtkWidget* sender) { chosen_search_engine_ = static_cast<TemplateURL*>( g_object_get_data(G_OBJECT(sender), kSearchEngineKey)); gtk_widget_destroy(search_engine_window_); } void FirstRunDialog::OnSearchEngineWindowDestroy(GtkWidget* sender) { search_engine_window_ = NULL; if (chosen_search_engine_) { search_engines_model_->SetDefaultSearchProvider(chosen_search_engine_); ShowDialog(); } else { FirstRunDone(); } } void FirstRunDialog::OnResponseDialog(GtkWidget* widget, int response) { if (dialog_) gtk_widget_hide_all(dialog_); response_ = response; if (response == GTK_RESPONSE_ACCEPT) { // Mark that first run has ran. FirstRun::CreateSentinel(); // Check if user has opted into reporting. if (report_crashes_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(report_crashes_))) { #if defined(USE_LINUX_BREAKPAD) if (GoogleUpdateSettings::SetCollectStatsConsent(true)) { InitCrashReporter(); } #endif } else { GoogleUpdateSettings::SetCollectStatsConsent(false); } // If selected set as default browser. if (make_default_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(make_default_))) { ShellIntegration::SetAsDefaultBrowser(); } } FirstRunDone(); } void FirstRunDialog::OnLearnMoreLinkClicked(GtkButton* button) { platform_util::OpenExternal(GURL( l10n_util::GetStringUTF8(IDS_LEARN_MORE_REPORTING_URL))); } void FirstRunDialog::FirstRunDone() { FirstRun::SetShowWelcomePagePref(); if (dialog_) gtk_widget_destroy(dialog_); MessageLoop::current()->Quit(); delete this; } <|endoftext|>
<commit_before>// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "chrome/browser/views/first_run_view.h" #include "chrome/app/locales/locale_settings.h" #include "chrome/app/theme/theme_resources.h" #include "chrome/browser/importer.h" #include "chrome/browser/first_run.h" #include "chrome/browser/standard_layout.h" #include "chrome/browser/views/first_run_customize_view.h" #include "chrome/browser/user_metrics.h" #include "chrome/common/l10n_util.h" #include "chrome/common/resource_bundle.h" #include "chrome/views/image_view.h" #include "chrome/views/label.h" #include "chrome/views/throbber.h" #include "chrome/views/separator.h" #include "chrome/views/window.h" #include "generated_resources.h" namespace { // Adds a bullet glyph to a string. std::wstring AddBullet(const std::wstring& text) { std::wstring btext(L" " + text); return btext.insert(0, 1, L'\u2022'); } } // namespace FirstRunView::FirstRunView(Profile* profile) : FirstRunViewBase(profile), welcome_label_(NULL), actions_label_(NULL), actions_import_(NULL), actions_shorcuts_(NULL), customize_link_(NULL), customize_selected_(false) { importer_host_ = new ImporterHost(); SetupControls(); } FirstRunView::~FirstRunView() { FirstRunComplete(); // Exit the message loop we were started with so that startup can continue. MessageLoop::current()->Quit(); } void FirstRunView::SetupControls() { using ChromeViews::Label; using ChromeViews::Link; welcome_label_ = new Label(l10n_util::GetString(IDS_FIRSTRUN_DLG_TEXT)); welcome_label_->SetMultiLine(true); welcome_label_->SetHorizontalAlignment(Label::ALIGN_LEFT); welcome_label_->SizeToFit(0); AddChildView(welcome_label_); actions_label_ = new Label(l10n_util::GetString(IDS_FIRSTRUN_DLG_DETAIL)); actions_label_->SetHorizontalAlignment(Label::ALIGN_LEFT); AddChildView(actions_label_); // The first action label will tell what we are going to import from which // browser, which we obtain from the ImporterHost. We need that the first // browser profile be the default browser. std::wstring label1; if (importer_host_->GetAvailableProfileCount() > 0) { label1 = l10n_util::GetStringF(IDS_FIRSTRUN_DLG_ACTION1, importer_host_->GetSourceProfileNameAt(0)); } else { NOTREACHED(); } actions_import_ = new Label(AddBullet(label1)); actions_import_->SetMultiLine(true); actions_import_->SetHorizontalAlignment(Label::ALIGN_LEFT); AddChildView(actions_import_); std::wstring label2 = l10n_util::GetString(IDS_FIRSTRUN_DLG_ACTION2); actions_shorcuts_ = new Label(AddBullet(label2)); actions_shorcuts_->SetHorizontalAlignment(Label::ALIGN_LEFT); actions_shorcuts_->SetMultiLine(true); AddChildView(actions_shorcuts_); customize_link_ = new Link(l10n_util::GetString(IDS_FIRSTRUN_DLG_OVERRIDE)); customize_link_->SetController(this); AddChildView(customize_link_); } void FirstRunView::GetPreferredSize(CSize *out) { DCHECK(out); *out = ChromeViews::Window::GetLocalizedContentsSize( IDS_FIRSTRUN_DIALOG_WIDTH_CHARS, IDS_FIRSTRUN_DIALOG_HEIGHT_LINES).ToSIZE(); } void FirstRunView::Layout() { FirstRunViewBase::Layout(); const int kVertSpacing = 8; CSize pref_size; welcome_label_->GetPreferredSize(&pref_size); welcome_label_->SetBounds(kPanelHorizMargin, kPanelVertMargin, pref_size.cx, pref_size.cy); AdjustDialogWidth(welcome_label_); int next_v_space = background_image()->GetY() + background_image()->GetHeight() + kPanelVertMargin; actions_label_->GetPreferredSize(&pref_size); actions_label_->SetBounds(kPanelHorizMargin, next_v_space, pref_size.cx, pref_size.cy); AdjustDialogWidth(actions_label_); next_v_space = actions_label_->GetY() + actions_label_->GetHeight() + kVertSpacing; // First give the label some width, so that GetPreferredSize can return us a // reasonable height... actions_import_->SetBounds(0, 0, GetWidth() - kPanelHorizMargin, 0); actions_import_->GetPreferredSize(&pref_size); actions_import_->SetBounds(kPanelHorizMargin, next_v_space, pref_size.cx + 100, pref_size.cy); next_v_space = actions_import_->GetY() + actions_import_->GetHeight() + kVertSpacing; AdjustDialogWidth(actions_import_); actions_shorcuts_->SetBounds(0, 0, GetWidth() - kPanelHorizMargin, 0); actions_shorcuts_->GetPreferredSize(&pref_size); actions_shorcuts_->SetBounds(kPanelHorizMargin, next_v_space, pref_size.cx, pref_size.cy); AdjustDialogWidth(actions_shorcuts_); next_v_space = actions_shorcuts_->GetY() + actions_shorcuts_->GetHeight() + kUnrelatedControlVerticalSpacing; customize_link_->GetPreferredSize(&pref_size); customize_link_->SetBounds(kPanelHorizMargin, next_v_space, pref_size.cx, pref_size.cy); } std::wstring FirstRunView::GetDialogButtonLabel(DialogButton button) const { if (DIALOGBUTTON_OK == button) return l10n_util::GetString(IDS_FIRSTRUN_DLG_OK); // The other buttons get the default text. return std::wstring(); } void FirstRunView::OpenCustomizeDialog() { // The customize dialog now owns the importer host object. ChromeViews::Window::CreateChromeWindow( window()->GetHWND(), gfx::Rect(), new FirstRunCustomizeView(profile_, importer_host_, this))->Show(); } void FirstRunView::LinkActivated(ChromeViews::Link* source, int event_flags) { OpenCustomizeDialog(); } std::wstring FirstRunView::GetWindowTitle() const { return l10n_util::GetString(IDS_FIRSTRUN_DLG_TITLE); } ChromeViews::View* FirstRunView::GetContentsView() { return this; } bool FirstRunView::Accept() { if (!IsDialogButtonEnabled(DIALOGBUTTON_OK)) return false; DisableButtons(); customize_link_->SetEnabled(false); CreateDesktopShortcut(); CreateQuickLaunchShortcut(); // Index 0 is the default browser. FirstRun::ImportSettings(profile_, 0, GetDefaultImportItems(), window()->GetHWND()); UserMetrics::RecordAction(L"FirstRunDef_Accept", profile_); return true; } bool FirstRunView::Cancel() { UserMetrics::RecordAction(L"FirstRunDef_Cancel", profile_); return true; } // Notification from the customize dialog that the user accepted. Since all // the work is done there we got nothing else to do. void FirstRunView::CustomizeAccepted() { window()->Close(); } // Notification from the customize dialog that the user cancelled. void FirstRunView::CustomizeCanceled() { UserMetrics::RecordAction(L"FirstRunCustom_Cancel", profile_); } <commit_msg>Wrap text in the chrome first run dialog.<commit_after>// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "chrome/browser/views/first_run_view.h" #include "chrome/app/locales/locale_settings.h" #include "chrome/app/theme/theme_resources.h" #include "chrome/browser/importer.h" #include "chrome/browser/first_run.h" #include "chrome/browser/standard_layout.h" #include "chrome/browser/views/first_run_customize_view.h" #include "chrome/browser/user_metrics.h" #include "chrome/common/l10n_util.h" #include "chrome/common/resource_bundle.h" #include "chrome/views/image_view.h" #include "chrome/views/label.h" #include "chrome/views/throbber.h" #include "chrome/views/separator.h" #include "chrome/views/window.h" #include "generated_resources.h" namespace { // Adds a bullet glyph to a string. std::wstring AddBullet(const std::wstring& text) { std::wstring btext(L" " + text); return btext.insert(0, 1, L'\u2022'); } } // namespace FirstRunView::FirstRunView(Profile* profile) : FirstRunViewBase(profile), welcome_label_(NULL), actions_label_(NULL), actions_import_(NULL), actions_shorcuts_(NULL), customize_link_(NULL), customize_selected_(false) { importer_host_ = new ImporterHost(); SetupControls(); } FirstRunView::~FirstRunView() { FirstRunComplete(); // Exit the message loop we were started with so that startup can continue. MessageLoop::current()->Quit(); } void FirstRunView::SetupControls() { using ChromeViews::Label; using ChromeViews::Link; welcome_label_ = new Label(l10n_util::GetString(IDS_FIRSTRUN_DLG_TEXT)); welcome_label_->SetMultiLine(true); welcome_label_->SetHorizontalAlignment(Label::ALIGN_LEFT); welcome_label_->SizeToFit(0); AddChildView(welcome_label_); actions_label_ = new Label(l10n_util::GetString(IDS_FIRSTRUN_DLG_DETAIL)); actions_label_->SetHorizontalAlignment(Label::ALIGN_LEFT); AddChildView(actions_label_); // The first action label will tell what we are going to import from which // browser, which we obtain from the ImporterHost. We need that the first // browser profile be the default browser. std::wstring label1; if (importer_host_->GetAvailableProfileCount() > 0) { label1 = l10n_util::GetStringF(IDS_FIRSTRUN_DLG_ACTION1, importer_host_->GetSourceProfileNameAt(0)); } else { NOTREACHED(); } actions_import_ = new Label(AddBullet(label1)); actions_import_->SetMultiLine(true); actions_import_->SetHorizontalAlignment(Label::ALIGN_LEFT); AddChildView(actions_import_); std::wstring label2 = l10n_util::GetString(IDS_FIRSTRUN_DLG_ACTION2); actions_shorcuts_ = new Label(AddBullet(label2)); actions_shorcuts_->SetHorizontalAlignment(Label::ALIGN_LEFT); actions_shorcuts_->SetMultiLine(true); AddChildView(actions_shorcuts_); customize_link_ = new Link(l10n_util::GetString(IDS_FIRSTRUN_DLG_OVERRIDE)); customize_link_->SetController(this); AddChildView(customize_link_); } void FirstRunView::GetPreferredSize(CSize *out) { DCHECK(out); *out = ChromeViews::Window::GetLocalizedContentsSize( IDS_FIRSTRUN_DIALOG_WIDTH_CHARS, IDS_FIRSTRUN_DIALOG_HEIGHT_LINES).ToSIZE(); } void FirstRunView::Layout() { FirstRunViewBase::Layout(); const int kVertSpacing = 8; CSize pref_size; welcome_label_->GetPreferredSize(&pref_size); welcome_label_->SetBounds(kPanelHorizMargin, kPanelVertMargin, pref_size.cx, pref_size.cy); AdjustDialogWidth(welcome_label_); int next_v_space = background_image()->GetY() + background_image()->GetHeight() + kPanelVertMargin; actions_label_->GetPreferredSize(&pref_size); actions_label_->SetBounds(kPanelHorizMargin, next_v_space, pref_size.cx, pref_size.cy); AdjustDialogWidth(actions_label_); next_v_space = actions_label_->GetY() + actions_label_->GetHeight() + kVertSpacing; int label_width = GetWidth() - (2 * kPanelHorizMargin); int label_height = actions_import_->GetHeightForWidth(label_width); actions_import_->SetBounds(kPanelHorizMargin, next_v_space, label_width, label_height); next_v_space = actions_import_->GetY() + actions_import_->GetHeight() + kVertSpacing; AdjustDialogWidth(actions_import_); label_height = actions_shorcuts_->GetHeightForWidth(label_width); actions_shorcuts_->SetBounds(kPanelHorizMargin, next_v_space, label_width, label_height); AdjustDialogWidth(actions_shorcuts_); next_v_space = actions_shorcuts_->GetY() + actions_shorcuts_->GetHeight() + kUnrelatedControlVerticalSpacing; customize_link_->GetPreferredSize(&pref_size); customize_link_->SetBounds(kPanelHorizMargin, next_v_space, pref_size.cx, pref_size.cy); } std::wstring FirstRunView::GetDialogButtonLabel(DialogButton button) const { if (DIALOGBUTTON_OK == button) return l10n_util::GetString(IDS_FIRSTRUN_DLG_OK); // The other buttons get the default text. return std::wstring(); } void FirstRunView::OpenCustomizeDialog() { // The customize dialog now owns the importer host object. ChromeViews::Window::CreateChromeWindow( window()->GetHWND(), gfx::Rect(), new FirstRunCustomizeView(profile_, importer_host_, this))->Show(); } void FirstRunView::LinkActivated(ChromeViews::Link* source, int event_flags) { OpenCustomizeDialog(); } std::wstring FirstRunView::GetWindowTitle() const { return l10n_util::GetString(IDS_FIRSTRUN_DLG_TITLE); } ChromeViews::View* FirstRunView::GetContentsView() { return this; } bool FirstRunView::Accept() { if (!IsDialogButtonEnabled(DIALOGBUTTON_OK)) return false; DisableButtons(); customize_link_->SetEnabled(false); CreateDesktopShortcut(); CreateQuickLaunchShortcut(); // Index 0 is the default browser. FirstRun::ImportSettings(profile_, 0, GetDefaultImportItems(), window()->GetHWND()); UserMetrics::RecordAction(L"FirstRunDef_Accept", profile_); return true; } bool FirstRunView::Cancel() { UserMetrics::RecordAction(L"FirstRunDef_Cancel", profile_); return true; } // Notification from the customize dialog that the user accepted. Since all // the work is done there we got nothing else to do. void FirstRunView::CustomizeAccepted() { window()->Close(); } // Notification from the customize dialog that the user cancelled. void FirstRunView::CustomizeCanceled() { UserMetrics::RecordAction(L"FirstRunCustom_Cancel", profile_); } <|endoftext|>
<commit_before>#include "common.hpp" TEST_XML(xpath_number_number, "<node>123</node>") { xml_node c; xml_node n = doc.child("node").first_child(); // number with 0 arguments CHECK_XPATH_NUMBER_NAN(c, "number()"); CHECK_XPATH_NUMBER(n, "number()", 123); // number with 1 string argument CHECK_XPATH_NUMBER(c, "number(' -123.456 ')", -123.456); CHECK_XPATH_NUMBER(c, "number(' -123.')", -123); CHECK_XPATH_NUMBER(c, "number('123.')", 123); CHECK_XPATH_NUMBER(c, "number('.56')", 0.56); CHECK_XPATH_NUMBER_NAN(c, "number('foobar')"); CHECK_XPATH_NUMBER_NAN(c, "number('f1')"); CHECK_XPATH_NUMBER_NAN(c, "number('1f')"); CHECK_XPATH_NUMBER_NAN(c, "number('1.f')"); CHECK_XPATH_NUMBER_NAN(c, "number('1.0f')"); // number with 1 bool argument CHECK_XPATH_NUMBER(c, "number(true())", 1); CHECK_XPATH_NUMBER(c, "number(false())", 0); // number with 1 node set argument CHECK_XPATH_NUMBER(n, "number(.)", 123); // number with 1 number argument CHECK_XPATH_NUMBER(c, "number(1)", 1); // number with 2 arguments CHECK_XPATH_FAIL("number(1, 2)"); } TEST_XML(xpath_number_sum, "<node>123<child>789</child></node><node/>") { xml_node c; xml_node n = doc.child("node"); // sum with 0 arguments CHECK_XPATH_FAIL("sum()"); // sum with 1 argument CHECK_XPATH_NUMBER(c, "sum(.)", 0); CHECK_XPATH_NUMBER(n, "sum(.)", 123789); // 123 .. 789 CHECK_XPATH_NUMBER(n, "sum(./descendant-or-self::node())", 125490); // node + 123 + child + 789 = 123789 + 123 + 789 + 789 = 125490 CHECK_XPATH_NUMBER_NAN(doc.last_child(), "sum(.)"); // sum with 2 arguments CHECK_XPATH_FAIL("sum(1, 2)"); // sum with 1 non-node-set argument CHECK_XPATH_FAIL("sum(1)"); } TEST(xpath_number_floor) { xml_node c; // floor with 0 arguments CHECK_XPATH_FAIL("floor()"); // floor with 1 argument CHECK_XPATH_NUMBER(c, "floor(1.2)", 1); CHECK_XPATH_NUMBER(c, "floor(1)", 1); CHECK_XPATH_NUMBER(c, "floor(-1.2)", -2); CHECK_XPATH_NUMBER_NAN(c, "floor(string('nan'))"); CHECK_XPATH_STRING(c, "string(floor(1 div 0))", "Infinity"); CHECK_XPATH_STRING(c, "string(floor(-1 div 0))", "-Infinity"); // floor with 2 arguments CHECK_XPATH_FAIL("floor(1, 2)"); } TEST(xpath_number_ceiling) { xml_node c; // ceiling with 0 arguments CHECK_XPATH_FAIL("ceiling()"); // ceiling with 1 argument CHECK_XPATH_NUMBER(c, "ceiling(1.2)", 2); CHECK_XPATH_NUMBER(c, "ceiling(1)", 1); CHECK_XPATH_NUMBER(c, "ceiling(-1.2)", -1); CHECK_XPATH_NUMBER_NAN(c, "ceiling(string('nan'))"); CHECK_XPATH_STRING(c, "string(ceiling(1 div 0))", "Infinity"); CHECK_XPATH_STRING(c, "string(ceiling(-1 div 0))", "-Infinity"); // ceiling with 2 arguments CHECK_XPATH_FAIL("ceiling(1, 2)"); } TEST(xpath_number_round) { xml_node c; // round with 0 arguments CHECK_XPATH_FAIL("round()"); // round with 1 argument CHECK_XPATH_NUMBER(c, "round(1.2)", 1); CHECK_XPATH_NUMBER(c, "round(1.5)", 2); CHECK_XPATH_NUMBER(c, "round(1.8)", 2); CHECK_XPATH_NUMBER(c, "round(1)", 1); CHECK_XPATH_NUMBER(c, "round(-1.2)", -1); CHECK_XPATH_NUMBER(c, "round(-1.5)", -1); CHECK_XPATH_NUMBER(c, "round(-1.6)", -2); CHECK_XPATH_NUMBER_NAN(c, "round(string('nan'))"); CHECK_XPATH_STRING(c, "string(round(1 div 0))", "Infinity"); CHECK_XPATH_STRING(c, "string(round(-1 div 0))", "-Infinity"); // round with 2 arguments CHECK_XPATH_FAIL("round(1, 2)"); // round with negative zero results // $$ CHECK_XPATH_NUMBER(c, "round(-0.3)", -0) // $$ CHECK_XPATH_NUMBER(c, "round(-0)", -0) } TEST_XML(xpath_boolean_boolean, "<node />") { xml_node c; // boolean with 0 arguments CHECK_XPATH_FAIL("boolean()"); // boolean with 1 number argument CHECK_XPATH_BOOLEAN(c, "boolean(0)", false); CHECK_XPATH_BOOLEAN(c, "boolean(1)", true); CHECK_XPATH_BOOLEAN(c, "boolean(-1)", true); CHECK_XPATH_BOOLEAN(c, "boolean(0.1)", true); CHECK_XPATH_BOOLEAN(c, "boolean(number('nan'))", false); // boolean with 1 string argument CHECK_XPATH_BOOLEAN(c, "boolean('x')", true); CHECK_XPATH_BOOLEAN(c, "boolean('')", false); // boolean with 1 node set argument CHECK_XPATH_BOOLEAN(c, "boolean(.)", false); CHECK_XPATH_BOOLEAN(doc, "boolean(.)", true); CHECK_XPATH_BOOLEAN(doc, "boolean(foo)", false); // boolean with 2 arguments CHECK_XPATH_FAIL("boolean(1, 2)"); } TEST(xpath_boolean_not) { xml_node c; // not with 0 arguments CHECK_XPATH_FAIL("not()"); // not with 1 argument CHECK_XPATH_BOOLEAN(c, "not(true())", false); CHECK_XPATH_BOOLEAN(c, "not(false())", true); // boolean with 2 arguments CHECK_XPATH_FAIL("not(1, 2)"); } TEST(xpath_boolean_true) { xml_node c; // true with 0 arguments CHECK_XPATH_BOOLEAN(c, "true()", true); // true with 1 argument CHECK_XPATH_FAIL("true(1)"); } TEST(xpath_boolean_false) { xml_node c; // false with 0 arguments CHECK_XPATH_BOOLEAN(c, "false()", false); // false with 1 argument CHECK_XPATH_FAIL("false(1)"); } TEST_XML(xpath_boolean_lang, "<node xml:lang='en'><child xml:lang='ru-uk'><subchild/></child></node><foo><bar/></foo>") { xml_node c; // lang with 0 arguments CHECK_XPATH_FAIL("lang()"); // lang with 1 argument, no language CHECK_XPATH_BOOLEAN(c, "lang('en')", false); CHECK_XPATH_BOOLEAN(doc.child("foo"), "lang('en')", false); CHECK_XPATH_BOOLEAN(doc.child("foo"), "lang('')", false); CHECK_XPATH_BOOLEAN(doc.child("foo").child("bar"), "lang('en')", false); // lang with 1 argument, same language/prefix CHECK_XPATH_BOOLEAN(doc.child("node"), "lang('en')", true); CHECK_XPATH_BOOLEAN(doc.child("node").child("child"), "lang('ru-uk')", true); CHECK_XPATH_BOOLEAN(doc.child("node").child("child"), "lang('ru')", true); CHECK_XPATH_BOOLEAN(doc.child("node").child("child").child("subchild"), "lang('ru')", true); // lang with 1 argument, different language/prefix CHECK_XPATH_BOOLEAN(doc.child("node"), "lang('')", false); CHECK_XPATH_BOOLEAN(doc.child("node"), "lang('e')", false); CHECK_XPATH_BOOLEAN(doc.child("node").child("child"), "lang('en')", false); CHECK_XPATH_BOOLEAN(doc.child("node").child("child"), "lang('ru-gb')", false); CHECK_XPATH_BOOLEAN(doc.child("node").child("child"), "lang('r')", false); CHECK_XPATH_BOOLEAN(doc.child("node").child("child").child("subchild"), "lang('en')", false); // lang with 2 arguments CHECK_XPATH_FAIL("lang(1, 2)"); } // $$$: string value of <node>123<child>789</child>100</node> should be 123789100 (?) <commit_msg>tests: Added different casing to lang test<commit_after>#include "common.hpp" TEST_XML(xpath_number_number, "<node>123</node>") { xml_node c; xml_node n = doc.child("node").first_child(); // number with 0 arguments CHECK_XPATH_NUMBER_NAN(c, "number()"); CHECK_XPATH_NUMBER(n, "number()", 123); // number with 1 string argument CHECK_XPATH_NUMBER(c, "number(' -123.456 ')", -123.456); CHECK_XPATH_NUMBER(c, "number(' -123.')", -123); CHECK_XPATH_NUMBER(c, "number('123.')", 123); CHECK_XPATH_NUMBER(c, "number('.56')", 0.56); CHECK_XPATH_NUMBER_NAN(c, "number('foobar')"); CHECK_XPATH_NUMBER_NAN(c, "number('f1')"); CHECK_XPATH_NUMBER_NAN(c, "number('1f')"); CHECK_XPATH_NUMBER_NAN(c, "number('1.f')"); CHECK_XPATH_NUMBER_NAN(c, "number('1.0f')"); // number with 1 bool argument CHECK_XPATH_NUMBER(c, "number(true())", 1); CHECK_XPATH_NUMBER(c, "number(false())", 0); // number with 1 node set argument CHECK_XPATH_NUMBER(n, "number(.)", 123); // number with 1 number argument CHECK_XPATH_NUMBER(c, "number(1)", 1); // number with 2 arguments CHECK_XPATH_FAIL("number(1, 2)"); } TEST_XML(xpath_number_sum, "<node>123<child>789</child></node><node/>") { xml_node c; xml_node n = doc.child("node"); // sum with 0 arguments CHECK_XPATH_FAIL("sum()"); // sum with 1 argument CHECK_XPATH_NUMBER(c, "sum(.)", 0); CHECK_XPATH_NUMBER(n, "sum(.)", 123789); // 123 .. 789 CHECK_XPATH_NUMBER(n, "sum(./descendant-or-self::node())", 125490); // node + 123 + child + 789 = 123789 + 123 + 789 + 789 = 125490 CHECK_XPATH_NUMBER_NAN(doc.last_child(), "sum(.)"); // sum with 2 arguments CHECK_XPATH_FAIL("sum(1, 2)"); // sum with 1 non-node-set argument CHECK_XPATH_FAIL("sum(1)"); } TEST(xpath_number_floor) { xml_node c; // floor with 0 arguments CHECK_XPATH_FAIL("floor()"); // floor with 1 argument CHECK_XPATH_NUMBER(c, "floor(1.2)", 1); CHECK_XPATH_NUMBER(c, "floor(1)", 1); CHECK_XPATH_NUMBER(c, "floor(-1.2)", -2); CHECK_XPATH_NUMBER_NAN(c, "floor(string('nan'))"); CHECK_XPATH_STRING(c, "string(floor(1 div 0))", "Infinity"); CHECK_XPATH_STRING(c, "string(floor(-1 div 0))", "-Infinity"); // floor with 2 arguments CHECK_XPATH_FAIL("floor(1, 2)"); } TEST(xpath_number_ceiling) { xml_node c; // ceiling with 0 arguments CHECK_XPATH_FAIL("ceiling()"); // ceiling with 1 argument CHECK_XPATH_NUMBER(c, "ceiling(1.2)", 2); CHECK_XPATH_NUMBER(c, "ceiling(1)", 1); CHECK_XPATH_NUMBER(c, "ceiling(-1.2)", -1); CHECK_XPATH_NUMBER_NAN(c, "ceiling(string('nan'))"); CHECK_XPATH_STRING(c, "string(ceiling(1 div 0))", "Infinity"); CHECK_XPATH_STRING(c, "string(ceiling(-1 div 0))", "-Infinity"); // ceiling with 2 arguments CHECK_XPATH_FAIL("ceiling(1, 2)"); } TEST(xpath_number_round) { xml_node c; // round with 0 arguments CHECK_XPATH_FAIL("round()"); // round with 1 argument CHECK_XPATH_NUMBER(c, "round(1.2)", 1); CHECK_XPATH_NUMBER(c, "round(1.5)", 2); CHECK_XPATH_NUMBER(c, "round(1.8)", 2); CHECK_XPATH_NUMBER(c, "round(1)", 1); CHECK_XPATH_NUMBER(c, "round(-1.2)", -1); CHECK_XPATH_NUMBER(c, "round(-1.5)", -1); CHECK_XPATH_NUMBER(c, "round(-1.6)", -2); CHECK_XPATH_NUMBER_NAN(c, "round(string('nan'))"); CHECK_XPATH_STRING(c, "string(round(1 div 0))", "Infinity"); CHECK_XPATH_STRING(c, "string(round(-1 div 0))", "-Infinity"); // round with 2 arguments CHECK_XPATH_FAIL("round(1, 2)"); // round with negative zero results // $$ CHECK_XPATH_NUMBER(c, "round(-0.3)", -0) // $$ CHECK_XPATH_NUMBER(c, "round(-0)", -0) } TEST_XML(xpath_boolean_boolean, "<node />") { xml_node c; // boolean with 0 arguments CHECK_XPATH_FAIL("boolean()"); // boolean with 1 number argument CHECK_XPATH_BOOLEAN(c, "boolean(0)", false); CHECK_XPATH_BOOLEAN(c, "boolean(1)", true); CHECK_XPATH_BOOLEAN(c, "boolean(-1)", true); CHECK_XPATH_BOOLEAN(c, "boolean(0.1)", true); CHECK_XPATH_BOOLEAN(c, "boolean(number('nan'))", false); // boolean with 1 string argument CHECK_XPATH_BOOLEAN(c, "boolean('x')", true); CHECK_XPATH_BOOLEAN(c, "boolean('')", false); // boolean with 1 node set argument CHECK_XPATH_BOOLEAN(c, "boolean(.)", false); CHECK_XPATH_BOOLEAN(doc, "boolean(.)", true); CHECK_XPATH_BOOLEAN(doc, "boolean(foo)", false); // boolean with 2 arguments CHECK_XPATH_FAIL("boolean(1, 2)"); } TEST(xpath_boolean_not) { xml_node c; // not with 0 arguments CHECK_XPATH_FAIL("not()"); // not with 1 argument CHECK_XPATH_BOOLEAN(c, "not(true())", false); CHECK_XPATH_BOOLEAN(c, "not(false())", true); // boolean with 2 arguments CHECK_XPATH_FAIL("not(1, 2)"); } TEST(xpath_boolean_true) { xml_node c; // true with 0 arguments CHECK_XPATH_BOOLEAN(c, "true()", true); // true with 1 argument CHECK_XPATH_FAIL("true(1)"); } TEST(xpath_boolean_false) { xml_node c; // false with 0 arguments CHECK_XPATH_BOOLEAN(c, "false()", false); // false with 1 argument CHECK_XPATH_FAIL("false(1)"); } TEST_XML(xpath_boolean_lang, "<node xml:lang='en'><child xml:lang='ru-UK'><subchild/></child></node><foo><bar/></foo>") { xml_node c; // lang with 0 arguments CHECK_XPATH_FAIL("lang()"); // lang with 1 argument, no language CHECK_XPATH_BOOLEAN(c, "lang('en')", false); CHECK_XPATH_BOOLEAN(doc.child("foo"), "lang('en')", false); CHECK_XPATH_BOOLEAN(doc.child("foo"), "lang('')", false); CHECK_XPATH_BOOLEAN(doc.child("foo").child("bar"), "lang('en')", false); // lang with 1 argument, same language/prefix CHECK_XPATH_BOOLEAN(doc.child("node"), "lang('en')", true); CHECK_XPATH_BOOLEAN(doc.child("node").child("child"), "lang('ru-uk')", true); CHECK_XPATH_BOOLEAN(doc.child("node").child("child"), "lang('ru')", true); CHECK_XPATH_BOOLEAN(doc.child("node").child("child").child("subchild"), "lang('ru')", true); CHECK_XPATH_BOOLEAN(doc.child("node").child("child").child("subchild"), "lang('RU')", true); // lang with 1 argument, different language/prefix CHECK_XPATH_BOOLEAN(doc.child("node"), "lang('')", false); CHECK_XPATH_BOOLEAN(doc.child("node"), "lang('e')", false); CHECK_XPATH_BOOLEAN(doc.child("node").child("child"), "lang('en')", false); CHECK_XPATH_BOOLEAN(doc.child("node").child("child"), "lang('ru-gb')", false); CHECK_XPATH_BOOLEAN(doc.child("node").child("child"), "lang('r')", false); CHECK_XPATH_BOOLEAN(doc.child("node").child("child").child("subchild"), "lang('en')", false); // lang with 2 arguments CHECK_XPATH_FAIL("lang(1, 2)"); } // $$$: string value of <node>123<child>789</child>100</node> should be 123789100 (?) <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #include "core/thread.hh" #include "core/semaphore.hh" #include "core/app-template.hh" #include "core/do_with.hh" #include "core/distributed.hh" #include "core/sleep.hh" using namespace seastar; using namespace std::chrono_literals; class context_switch_tester { uint64_t _switches{0}; semaphore _s1{0}; semaphore _s2{0}; bool _done1{false}; bool _done2{false}; thread _t1{[this] { main1(); }}; thread _t2{[this] { main2(); }}; private: void main1() { while (!_done1) { _s1.wait().get(); ++_switches; _s2.signal(); } _done2 = true; } void main2() { while (!_done2) { _s2.wait().get(); ++_switches; _s1.signal(); } } public: void begin_measurement() { _s1.signal(); } future<uint64_t> measure() { _done1 = true; return _t1.join().then([this] { return _t2.join(); }).then([this] { return _switches; }); } future<> stop() { return make_ready_future<>(); } }; int main(int ac, char** av) { static const auto test_time = 5s; return app_template().run(ac, av, [] { return do_with(distributed<context_switch_tester>(), [] (distributed<context_switch_tester>& dcst) { return dcst.start().then([&dcst] { return dcst.invoke_on_all(&context_switch_tester::begin_measurement); }).then([] { return sleep(test_time); }).then([&dcst] { return dcst.map_reduce0(std::mem_fn(&context_switch_tester::measure), uint64_t(), std::plus<uint64_t>()); }).then([] (uint64_t switches) { switches /= smp::count; print("context switch time: %5.1f ns\n", double(std::chrono::duration_cast<std::chrono::nanoseconds>(test_time).count()) / switches); }).then([&dcst] { return dcst.stop(); }).then([] { engine_exit(0); }); }); }); } <commit_msg>tests: add missing header<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #include <experimental/optional> #include "core/thread.hh" #include "core/semaphore.hh" #include "core/app-template.hh" #include "core/do_with.hh" #include "core/distributed.hh" #include "core/sleep.hh" using namespace seastar; using namespace std::chrono_literals; class context_switch_tester { uint64_t _switches{0}; semaphore _s1{0}; semaphore _s2{0}; bool _done1{false}; bool _done2{false}; thread _t1{[this] { main1(); }}; thread _t2{[this] { main2(); }}; private: void main1() { while (!_done1) { _s1.wait().get(); ++_switches; _s2.signal(); } _done2 = true; } void main2() { while (!_done2) { _s2.wait().get(); ++_switches; _s1.signal(); } } public: void begin_measurement() { _s1.signal(); } future<uint64_t> measure() { _done1 = true; return _t1.join().then([this] { return _t2.join(); }).then([this] { return _switches; }); } future<> stop() { return make_ready_future<>(); } }; int main(int ac, char** av) { static const auto test_time = 5s; return app_template().run(ac, av, [] { return do_with(distributed<context_switch_tester>(), [] (distributed<context_switch_tester>& dcst) { return dcst.start().then([&dcst] { return dcst.invoke_on_all(&context_switch_tester::begin_measurement); }).then([] { return sleep(test_time); }).then([&dcst] { return dcst.map_reduce0(std::mem_fn(&context_switch_tester::measure), uint64_t(), std::plus<uint64_t>()); }).then([] (uint64_t switches) { switches /= smp::count; print("context switch time: %5.1f ns\n", double(std::chrono::duration_cast<std::chrono::nanoseconds>(test_time).count()) / switches); }).then([&dcst] { return dcst.stop(); }).then([] { engine_exit(0); }); }); }); } <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #include <seastar/testing/test_case.hh> #include <seastar/testing/thread_test_case.hh> #include <seastar/core/distributed.hh> #include <seastar/core/loop.hh> #include <seastar/core/semaphore.hh> #include <seastar/core/sleep.hh> #include <seastar/core/thread.hh> #include <seastar/core/print.hh> #include <seastar/util/defer.hh> #include <seastar/util/closeable.hh> #include <mutex> using namespace seastar; using namespace std::chrono_literals; struct async_service : public seastar::async_sharded_service<async_service> { thread_local static bool deleted; ~async_service() { deleted = true; } void run() { auto ref = shared_from_this(); // Wait a while and check. (void)sleep(std::chrono::milliseconds(100 + 100 * this_shard_id())).then([this, ref] { check(); }); } virtual void check() { assert(!deleted); } future<> stop() { return make_ready_future<>(); } }; thread_local bool async_service::deleted = false; struct X { sstring echo(sstring arg) { return arg; } int cpu_id_squared() const { auto id = this_shard_id(); return id * id; } future<> stop() { return make_ready_future<>(); } }; template <typename T, typename Func> future<> do_with_distributed(Func&& func) { auto x = make_shared<distributed<T>>(); return func(*x).finally([x] { return x->stop(); }).finally([x]{}); } SEASTAR_TEST_CASE(test_that_each_core_gets_the_arguments) { return do_with_distributed<X>([] (auto& x) { return x.start().then([&x] { return x.map_reduce([] (sstring msg){ if (msg != "hello") { throw std::runtime_error("wrong message"); } }, &X::echo, sstring("hello")); }); }); } SEASTAR_TEST_CASE(test_functor_version) { return do_with_distributed<X>([] (auto& x) { return x.start().then([&x] { return x.map_reduce([] (sstring msg){ if (msg != "hello") { throw std::runtime_error("wrong message"); } }, [] (X& x) { return x.echo("hello"); }); }); }); } struct Y { sstring s; Y(sstring s) : s(std::move(s)) {} future<> stop() { return make_ready_future<>(); } }; SEASTAR_TEST_CASE(test_constructor_argument_is_passed_to_each_core) { return do_with_distributed<Y>([] (auto& y) { return y.start(sstring("hello")).then([&y] { return y.invoke_on_all([] (Y& y) { if (y.s != "hello") { throw std::runtime_error(format("expected message mismatch, is \"%s\"", y.s)); } }); }); }); } SEASTAR_TEST_CASE(test_map_reduce) { return do_with_distributed<X>([] (distributed<X>& x) { return x.start().then([&x] { return x.map_reduce0(std::mem_fn(&X::cpu_id_squared), 0, std::plus<int>()).then([] (int result) { int n = smp::count - 1; if (result != (n * (n + 1) * (2*n + 1)) / 6) { throw std::runtime_error("map_reduce failed"); } }); }); }); } SEASTAR_TEST_CASE(test_async) { return do_with_distributed<async_service>([] (distributed<async_service>& x) { return x.start().then([&x] { return x.invoke_on_all(&async_service::run); }); }).then([] { return sleep(std::chrono::milliseconds(100 * (smp::count + 1))); }); } SEASTAR_TEST_CASE(test_invoke_on_others) { return seastar::async([] { struct my_service { int counter = 0; void up() { ++counter; } future<> stop() { return make_ready_future<>(); } }; for (unsigned c = 0; c < smp::count; ++c) { smp::submit_to(c, [c] { return seastar::async([c] { sharded<my_service> s; s.start().get(); s.invoke_on_others([](auto& s) { s.up(); }).get(); if (s.local().counter != 0) { throw std::runtime_error("local modified"); } s.invoke_on_all([c](auto& remote) { if (this_shard_id() != c) { if (remote.counter != 1) { throw std::runtime_error("remote not modified"); } } }).get(); s.stop().get(); }); }).get(); } }); } struct remote_worker { unsigned current = 0; unsigned max_concurrent_observed = 0; unsigned expected_max; semaphore sem{0}; remote_worker(unsigned expected_max) : expected_max(expected_max) { } future<> do_work() { ++current; max_concurrent_observed = std::max(current, max_concurrent_observed); if (max_concurrent_observed >= expected_max && sem.current() == 0) { sem.signal(semaphore::max_counter()); } return sem.wait().then([this] { // Sleep a bit to check if the concurrency goes over the max return sleep(100ms).then([this] { max_concurrent_observed = std::max(current, max_concurrent_observed); --current; }); }); } future<> do_remote_work(shard_id t, smp_service_group ssg) { return smp::submit_to(t, ssg, [this] { return do_work(); }); } }; SEASTAR_TEST_CASE(test_smp_service_groups) { return async([] { smp_service_group_config ssgc1; ssgc1.max_nonlocal_requests = 1; auto ssg1 = create_smp_service_group(ssgc1).get0(); smp_service_group_config ssgc2; ssgc2.max_nonlocal_requests = 1000; auto ssg2 = create_smp_service_group(ssgc2).get0(); shard_id other_shard = smp::count - 1; remote_worker rm1(1); remote_worker rm2(1000); auto bunch1 = parallel_for_each(boost::irange(0, 20), [&] (int ignore) { return rm1.do_remote_work(other_shard, ssg1); }); auto bunch2 = parallel_for_each(boost::irange(0, 2000), [&] (int ignore) { return rm2.do_remote_work(other_shard, ssg2); }); bunch1.get(); bunch2.get(); if (smp::count > 1) { assert(rm1.max_concurrent_observed == 1); assert(rm2.max_concurrent_observed == 1000); } destroy_smp_service_group(ssg1).get(); destroy_smp_service_group(ssg2).get(); }); } SEASTAR_TEST_CASE(test_smp_service_groups_re_construction) { // During development of the feature, we saw a bug where the vector // holding the groups did not expand correctly. This test triggers the // bug. return async([] { auto ssg1 = create_smp_service_group({}).get0(); auto ssg2 = create_smp_service_group({}).get0(); destroy_smp_service_group(ssg1).get(); auto ssg3 = create_smp_service_group({}).get0(); destroy_smp_service_group(ssg2).get(); destroy_smp_service_group(ssg3).get(); }); } SEASTAR_TEST_CASE(test_smp_timeout) { return async([] { smp_service_group_config ssgc1; ssgc1.max_nonlocal_requests = 1; auto ssg1 = create_smp_service_group(ssgc1).get0(); auto _ = defer([ssg1] { destroy_smp_service_group(ssg1).get(); }); const shard_id other_shard = smp::count - 1; // Ugly but beats using sleeps. std::mutex mut; std::unique_lock<std::mutex> lk(mut); // Submitted to the remote shard. auto fut1 = smp::submit_to(other_shard, ssg1, [&mut] { std::cout << "Running request no. 1" << std::endl; std::unique_lock<std::mutex> lk(mut); std::cout << "Request no. 1 done" << std::endl; }); // Consume the only unit from the semaphore. auto fut2 = smp::submit_to(other_shard, ssg1, [] { std::cout << "Running request no. 2 - done" << std::endl; }); auto fut_timedout = smp::submit_to(other_shard, smp_submit_to_options(ssg1, smp_timeout_clock::now() + 10ms), [] { std::cout << "Running timed-out request - done" << std::endl; }); { auto notify = defer([lk = std::move(lk)] { }); try { fut_timedout.get(); throw std::runtime_error("smp::submit_to() didn't timeout as expected"); } catch (semaphore_timed_out& e) { std::cout << "Expected timeout received: " << e.what() << std::endl; } catch (...) { std::throw_with_nested(std::runtime_error("smp::submit_to() failed with unexpected exception")); } } fut1.get(); fut2.get(); }); } SEASTAR_THREAD_TEST_CASE(test_sharded_parameter) { struct dependency { unsigned val = this_shard_id() * 7; }; struct some_service { bool ok = false; some_service(unsigned non_shard_dependent, unsigned shard_dependent, dependency& dep, unsigned shard_dependent_2) { ok = non_shard_dependent == 43 && shard_dependent == this_shard_id() * 3 && dep.val == this_shard_id() * 7 && shard_dependent_2 == -dep.val; } }; sharded<dependency> s_dep; s_dep.start().get(); auto undo1 = deferred_stop(s_dep); sharded<some_service> s_service; s_service.start( 43, // should be copied verbatim sharded_parameter([] { return this_shard_id() * 3; }), std::ref(s_dep), sharded_parameter([] (dependency& d) { return -d.val; }, std::ref(s_dep)) ).get(); auto undo2 = deferred_stop(s_service); auto all_ok = s_service.map_reduce0(std::mem_fn(&some_service::ok), true, std::multiplies<>()).get0(); BOOST_REQUIRE(all_ok); } <commit_msg>tests: distributed_test: mark deferred actions noexcept<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #include <seastar/testing/test_case.hh> #include <seastar/testing/thread_test_case.hh> #include <seastar/core/distributed.hh> #include <seastar/core/loop.hh> #include <seastar/core/semaphore.hh> #include <seastar/core/sleep.hh> #include <seastar/core/thread.hh> #include <seastar/core/print.hh> #include <seastar/util/defer.hh> #include <seastar/util/closeable.hh> #include <mutex> using namespace seastar; using namespace std::chrono_literals; struct async_service : public seastar::async_sharded_service<async_service> { thread_local static bool deleted; ~async_service() { deleted = true; } void run() { auto ref = shared_from_this(); // Wait a while and check. (void)sleep(std::chrono::milliseconds(100 + 100 * this_shard_id())).then([this, ref] { check(); }); } virtual void check() { assert(!deleted); } future<> stop() { return make_ready_future<>(); } }; thread_local bool async_service::deleted = false; struct X { sstring echo(sstring arg) { return arg; } int cpu_id_squared() const { auto id = this_shard_id(); return id * id; } future<> stop() { return make_ready_future<>(); } }; template <typename T, typename Func> future<> do_with_distributed(Func&& func) { auto x = make_shared<distributed<T>>(); return func(*x).finally([x] { return x->stop(); }).finally([x]{}); } SEASTAR_TEST_CASE(test_that_each_core_gets_the_arguments) { return do_with_distributed<X>([] (auto& x) { return x.start().then([&x] { return x.map_reduce([] (sstring msg){ if (msg != "hello") { throw std::runtime_error("wrong message"); } }, &X::echo, sstring("hello")); }); }); } SEASTAR_TEST_CASE(test_functor_version) { return do_with_distributed<X>([] (auto& x) { return x.start().then([&x] { return x.map_reduce([] (sstring msg){ if (msg != "hello") { throw std::runtime_error("wrong message"); } }, [] (X& x) { return x.echo("hello"); }); }); }); } struct Y { sstring s; Y(sstring s) : s(std::move(s)) {} future<> stop() { return make_ready_future<>(); } }; SEASTAR_TEST_CASE(test_constructor_argument_is_passed_to_each_core) { return do_with_distributed<Y>([] (auto& y) { return y.start(sstring("hello")).then([&y] { return y.invoke_on_all([] (Y& y) { if (y.s != "hello") { throw std::runtime_error(format("expected message mismatch, is \"%s\"", y.s)); } }); }); }); } SEASTAR_TEST_CASE(test_map_reduce) { return do_with_distributed<X>([] (distributed<X>& x) { return x.start().then([&x] { return x.map_reduce0(std::mem_fn(&X::cpu_id_squared), 0, std::plus<int>()).then([] (int result) { int n = smp::count - 1; if (result != (n * (n + 1) * (2*n + 1)) / 6) { throw std::runtime_error("map_reduce failed"); } }); }); }); } SEASTAR_TEST_CASE(test_async) { return do_with_distributed<async_service>([] (distributed<async_service>& x) { return x.start().then([&x] { return x.invoke_on_all(&async_service::run); }); }).then([] { return sleep(std::chrono::milliseconds(100 * (smp::count + 1))); }); } SEASTAR_TEST_CASE(test_invoke_on_others) { return seastar::async([] { struct my_service { int counter = 0; void up() { ++counter; } future<> stop() { return make_ready_future<>(); } }; for (unsigned c = 0; c < smp::count; ++c) { smp::submit_to(c, [c] { return seastar::async([c] { sharded<my_service> s; s.start().get(); s.invoke_on_others([](auto& s) { s.up(); }).get(); if (s.local().counter != 0) { throw std::runtime_error("local modified"); } s.invoke_on_all([c](auto& remote) { if (this_shard_id() != c) { if (remote.counter != 1) { throw std::runtime_error("remote not modified"); } } }).get(); s.stop().get(); }); }).get(); } }); } struct remote_worker { unsigned current = 0; unsigned max_concurrent_observed = 0; unsigned expected_max; semaphore sem{0}; remote_worker(unsigned expected_max) : expected_max(expected_max) { } future<> do_work() { ++current; max_concurrent_observed = std::max(current, max_concurrent_observed); if (max_concurrent_observed >= expected_max && sem.current() == 0) { sem.signal(semaphore::max_counter()); } return sem.wait().then([this] { // Sleep a bit to check if the concurrency goes over the max return sleep(100ms).then([this] { max_concurrent_observed = std::max(current, max_concurrent_observed); --current; }); }); } future<> do_remote_work(shard_id t, smp_service_group ssg) { return smp::submit_to(t, ssg, [this] { return do_work(); }); } }; SEASTAR_TEST_CASE(test_smp_service_groups) { return async([] { smp_service_group_config ssgc1; ssgc1.max_nonlocal_requests = 1; auto ssg1 = create_smp_service_group(ssgc1).get0(); smp_service_group_config ssgc2; ssgc2.max_nonlocal_requests = 1000; auto ssg2 = create_smp_service_group(ssgc2).get0(); shard_id other_shard = smp::count - 1; remote_worker rm1(1); remote_worker rm2(1000); auto bunch1 = parallel_for_each(boost::irange(0, 20), [&] (int ignore) { return rm1.do_remote_work(other_shard, ssg1); }); auto bunch2 = parallel_for_each(boost::irange(0, 2000), [&] (int ignore) { return rm2.do_remote_work(other_shard, ssg2); }); bunch1.get(); bunch2.get(); if (smp::count > 1) { assert(rm1.max_concurrent_observed == 1); assert(rm2.max_concurrent_observed == 1000); } destroy_smp_service_group(ssg1).get(); destroy_smp_service_group(ssg2).get(); }); } SEASTAR_TEST_CASE(test_smp_service_groups_re_construction) { // During development of the feature, we saw a bug where the vector // holding the groups did not expand correctly. This test triggers the // bug. return async([] { auto ssg1 = create_smp_service_group({}).get0(); auto ssg2 = create_smp_service_group({}).get0(); destroy_smp_service_group(ssg1).get(); auto ssg3 = create_smp_service_group({}).get0(); destroy_smp_service_group(ssg2).get(); destroy_smp_service_group(ssg3).get(); }); } SEASTAR_TEST_CASE(test_smp_timeout) { return async([] { smp_service_group_config ssgc1; ssgc1.max_nonlocal_requests = 1; auto ssg1 = create_smp_service_group(ssgc1).get0(); auto _ = defer([ssg1] () noexcept { destroy_smp_service_group(ssg1).get(); }); const shard_id other_shard = smp::count - 1; // Ugly but beats using sleeps. std::mutex mut; std::unique_lock<std::mutex> lk(mut); // Submitted to the remote shard. auto fut1 = smp::submit_to(other_shard, ssg1, [&mut] { std::cout << "Running request no. 1" << std::endl; std::unique_lock<std::mutex> lk(mut); std::cout << "Request no. 1 done" << std::endl; }); // Consume the only unit from the semaphore. auto fut2 = smp::submit_to(other_shard, ssg1, [] { std::cout << "Running request no. 2 - done" << std::endl; }); auto fut_timedout = smp::submit_to(other_shard, smp_submit_to_options(ssg1, smp_timeout_clock::now() + 10ms), [] { std::cout << "Running timed-out request - done" << std::endl; }); { auto notify = defer([lk = std::move(lk)] () noexcept { }); try { fut_timedout.get(); throw std::runtime_error("smp::submit_to() didn't timeout as expected"); } catch (semaphore_timed_out& e) { std::cout << "Expected timeout received: " << e.what() << std::endl; } catch (...) { std::throw_with_nested(std::runtime_error("smp::submit_to() failed with unexpected exception")); } } fut1.get(); fut2.get(); }); } SEASTAR_THREAD_TEST_CASE(test_sharded_parameter) { struct dependency { unsigned val = this_shard_id() * 7; }; struct some_service { bool ok = false; some_service(unsigned non_shard_dependent, unsigned shard_dependent, dependency& dep, unsigned shard_dependent_2) { ok = non_shard_dependent == 43 && shard_dependent == this_shard_id() * 3 && dep.val == this_shard_id() * 7 && shard_dependent_2 == -dep.val; } }; sharded<dependency> s_dep; s_dep.start().get(); auto undo1 = deferred_stop(s_dep); sharded<some_service> s_service; s_service.start( 43, // should be copied verbatim sharded_parameter([] { return this_shard_id() * 3; }), std::ref(s_dep), sharded_parameter([] (dependency& d) { return -d.val; }, std::ref(s_dep)) ).get(); auto undo2 = deferred_stop(s_service); auto all_ok = s_service.map_reduce0(std::mem_fn(&some_service::ok), true, std::multiplies<>()).get0(); BOOST_REQUIRE(all_ok); } <|endoftext|>
<commit_before>/** * @file streamingaudio_fmodex.cpp * @brief LLStreamingAudio_FMODEX implementation * * $LicenseInfo:firstyear=2002&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "linden_common.h" #include "llmath.h" #include "fmod.hpp" #include "fmod_errors.h" #include "llstreamingaudio_fmodex.h" class LLAudioStreamManagerFMODEX { public: LLAudioStreamManagerFMODEX(FMOD::System *system, const std::string& url); FMOD::Channel* startStream(); bool stopStream(); // Returns true if the stream was successfully stopped. bool ready(); const std::string& getURL() { return mInternetStreamURL; } FMOD_OPENSTATE getOpenState(unsigned int* percentbuffered=NULL, bool* starving=NULL, bool* diskbusy=NULL); protected: FMOD::System* mSystem; FMOD::Channel* mStreamChannel; FMOD::Sound* mInternetStream; bool mReady; std::string mInternetStreamURL; }; //--------------------------------------------------------------------------- // Internet Streaming //--------------------------------------------------------------------------- LLStreamingAudio_FMODEX::LLStreamingAudio_FMODEX(FMOD::System *system) : mSystem(system), mCurrentInternetStreamp(NULL), mFMODInternetStreamChannelp(NULL), mGain(1.0f) { // Number of milliseconds of audio to buffer for the audio card. // Must be larger than the usual Second Life frame stutter time. const U32 buffer_seconds = 10; //sec const U32 estimated_bitrate = 128; //kbit/sec mSystem->setStreamBufferSize(estimated_bitrate * buffer_seconds * 128/*bytes/kbit*/, FMOD_TIMEUNIT_RAWBYTES); // Here's where we set the size of the network buffer and some buffering // parameters. In this case we want a network buffer of 16k, we want it // to prebuffer 40% of that when we first connect, and we want it // to rebuffer 80% of that whenever we encounter a buffer underrun. // Leave the net buffer properties at the default. //FSOUND_Stream_Net_SetBufferProperties(20000, 40, 80); } LLStreamingAudio_FMODEX::~LLStreamingAudio_FMODEX() { // nothing interesting/safe to do. } void LLStreamingAudio_FMODEX::start(const std::string& url) { //if (!mInited) //{ // llwarns << "startInternetStream before audio initialized" << llendl; // return; //} // "stop" stream but don't clear url, etc. in case url == mInternetStreamURL stop(); if (!url.empty()) { llinfos << "Starting internet stream: " << url << llendl; mCurrentInternetStreamp = new LLAudioStreamManagerFMODEX(mSystem,url); mURL = url; } else { llinfos << "Set internet stream to null" << llendl; mURL.clear(); } } void LLStreamingAudio_FMODEX::update() { // Kill dead internet streams, if possible std::list<LLAudioStreamManagerFMODEX *>::iterator iter; for (iter = mDeadStreams.begin(); iter != mDeadStreams.end();) { LLAudioStreamManagerFMODEX *streamp = *iter; if (streamp->stopStream()) { llinfos << "Closed dead stream" << llendl; delete streamp; mDeadStreams.erase(iter++); } else { iter++; } } // Don't do anything if there are no streams playing if (!mCurrentInternetStreamp) { return; } unsigned int progress; bool starving; bool diskbusy; FMOD_OPENSTATE open_state = mCurrentInternetStreamp->getOpenState(&progress, &starving, &diskbusy); if (open_state == FMOD_OPENSTATE_READY) { // Stream is live // start the stream if it's ready if (!mFMODInternetStreamChannelp && (mFMODInternetStreamChannelp = mCurrentInternetStreamp->startStream())) { // Reset volume to previously set volume setGain(getGain()); mFMODInternetStreamChannelp->setPaused(false); } } else if(open_state == FMOD_OPENSTATE_ERROR) { stop(); return; } if(mFMODInternetStreamChannelp) { FMOD::Sound *sound = NULL; if(mFMODInternetStreamChannelp->getCurrentSound(&sound) == FMOD_OK && sound) { FMOD_TAG tag; S32 tagcount, dirtytagcount; if(sound->getNumTags(&tagcount, &dirtytagcount) == FMOD_OK && dirtytagcount) { for(S32 i = 0; i < tagcount; ++i) { if(sound->getTag(NULL, i, &tag)!=FMOD_OK) continue; if (tag.type == FMOD_TAGTYPE_FMOD) { if (!strcmp(tag.name, "Sample Rate Change")) { llinfos << "Stream forced changing sample rate to " << *((float *)tag.data) << llendl; mFMODInternetStreamChannelp->setFrequency(*((float *)tag.data)); } continue; } } } if(starving) { bool paused = false; mFMODInternetStreamChannelp->getPaused(&paused); if(!paused) { llinfos << "Stream starvation detected! Pausing stream until buffer nearly full." << llendl; llinfos << " (diskbusy="<<diskbusy<<")" << llendl; llinfos << " (progress="<<progress<<")" << llendl; mFMODInternetStreamChannelp->setPaused(true); } } else if(progress > 80) { mFMODInternetStreamChannelp->setPaused(false); } } } } void LLStreamingAudio_FMODEX::stop() { if (mFMODInternetStreamChannelp) { mFMODInternetStreamChannelp->setPaused(true); mFMODInternetStreamChannelp->setPriority(0); mFMODInternetStreamChannelp = NULL; } if (mCurrentInternetStreamp) { llinfos << "Stopping internet stream: " << mCurrentInternetStreamp->getURL() << llendl; if (mCurrentInternetStreamp->stopStream()) { delete mCurrentInternetStreamp; } else { llwarns << "Pushing stream to dead list: " << mCurrentInternetStreamp->getURL() << llendl; mDeadStreams.push_back(mCurrentInternetStreamp); } mCurrentInternetStreamp = NULL; //mURL.clear(); } } void LLStreamingAudio_FMODEX::pause(int pauseopt) { if (pauseopt < 0) { pauseopt = mCurrentInternetStreamp ? 1 : 0; } if (pauseopt) { if (mCurrentInternetStreamp) { stop(); } } else { start(getURL()); } } // A stream is "playing" if it has been requested to start. That // doesn't necessarily mean audio is coming out of the speakers. int LLStreamingAudio_FMODEX::isPlaying() { if (mCurrentInternetStreamp) { return 1; // Active and playing } else if (!mURL.empty()) { return 2; // "Paused" } else { return 0; } } F32 LLStreamingAudio_FMODEX::getGain() { return mGain; } std::string LLStreamingAudio_FMODEX::getURL() { return mURL; } void LLStreamingAudio_FMODEX::setGain(F32 vol) { mGain = vol; if (mFMODInternetStreamChannelp) { vol = llclamp(vol * vol, 0.f, 1.f); //should vol be squared here? mFMODInternetStreamChannelp->setVolume(vol); } } /////////////////////////////////////////////////////// // manager of possibly-multiple internet audio streams LLAudioStreamManagerFMODEX::LLAudioStreamManagerFMODEX(FMOD::System *system, const std::string& url) : mSystem(system), mStreamChannel(NULL), mInternetStream(NULL), mReady(false) { mInternetStreamURL = url; FMOD_RESULT result = mSystem->createStream(url.c_str(), FMOD_2D | FMOD_NONBLOCKING | FMOD_IGNORETAGS, 0, &mInternetStream); if (result!= FMOD_OK) { llwarns << "Couldn't open fmod stream, error " << FMOD_ErrorString(result) << llendl; mReady = false; return; } mReady = true; } FMOD::Channel *LLAudioStreamManagerFMODEX::startStream() { // We need a live and opened stream before we try and play it. if (!mInternetStream || getOpenState() != FMOD_OPENSTATE_READY) { llwarns << "No internet stream to start playing!" << llendl; return NULL; } if(mStreamChannel) return mStreamChannel; //Already have a channel for this stream. mSystem->playSound(FMOD_CHANNEL_FREE, mInternetStream, true, &mStreamChannel); return mStreamChannel; } bool LLAudioStreamManagerFMODEX::stopStream() { if (mInternetStream) { bool close = true; switch (getOpenState()) { case FMOD_OPENSTATE_CONNECTING: close = false; break; default: close = true; } if (close) { mInternetStream->release(); mStreamChannel = NULL; mInternetStream = NULL; return true; } else { return false; } } else { return true; } } FMOD_OPENSTATE LLAudioStreamManagerFMODEX::getOpenState(unsigned int* percentbuffered, bool* starving, bool* diskbusy) { FMOD_OPENSTATE state; mInternetStream->getOpenState(&state, percentbuffered, starving, diskbusy); return state; } void LLStreamingAudio_FMODEX::setBufferSizes(U32 streambuffertime, U32 decodebuffertime) { mSystem->setStreamBufferSize(streambuffertime/1000*128*128, FMOD_TIMEUNIT_RAWBYTES); FMOD_ADVANCEDSETTINGS settings; memset(&settings,0,sizeof(settings)); settings.cbsize=sizeof(settings); settings.defaultDecodeBufferSize = decodebuffertime;//ms mSystem->setAdvancedSettings(&settings); } <commit_msg>MAINT-2849 FIX Certain streams that play with FMod do not play with FModEx<commit_after>/** * @file streamingaudio_fmodex.cpp * @brief LLStreamingAudio_FMODEX implementation * * $LicenseInfo:firstyear=2002&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "linden_common.h" #include "llmath.h" #include "fmod.hpp" #include "fmod_errors.h" #include "llstreamingaudio_fmodex.h" class LLAudioStreamManagerFMODEX { public: LLAudioStreamManagerFMODEX(FMOD::System *system, const std::string& url); FMOD::Channel* startStream(); bool stopStream(); // Returns true if the stream was successfully stopped. bool ready(); const std::string& getURL() { return mInternetStreamURL; } FMOD_OPENSTATE getOpenState(unsigned int* percentbuffered=NULL, bool* starving=NULL, bool* diskbusy=NULL); protected: FMOD::System* mSystem; FMOD::Channel* mStreamChannel; FMOD::Sound* mInternetStream; bool mReady; std::string mInternetStreamURL; }; //--------------------------------------------------------------------------- // Internet Streaming //--------------------------------------------------------------------------- LLStreamingAudio_FMODEX::LLStreamingAudio_FMODEX(FMOD::System *system) : mSystem(system), mCurrentInternetStreamp(NULL), mFMODInternetStreamChannelp(NULL), mGain(1.0f) { // Number of milliseconds of audio to buffer for the audio card. // Must be larger than the usual Second Life frame stutter time. const U32 buffer_seconds = 10; //sec const U32 estimated_bitrate = 128; //kbit/sec mSystem->setStreamBufferSize(estimated_bitrate * buffer_seconds * 128/*bytes/kbit*/, FMOD_TIMEUNIT_RAWBYTES); // Here's where we set the size of the network buffer and some buffering // parameters. In this case we want a network buffer of 16k, we want it // to prebuffer 40% of that when we first connect, and we want it // to rebuffer 80% of that whenever we encounter a buffer underrun. // Leave the net buffer properties at the default. //FSOUND_Stream_Net_SetBufferProperties(20000, 40, 80); } LLStreamingAudio_FMODEX::~LLStreamingAudio_FMODEX() { // nothing interesting/safe to do. } void LLStreamingAudio_FMODEX::start(const std::string& url) { //if (!mInited) //{ // llwarns << "startInternetStream before audio initialized" << llendl; // return; //} // "stop" stream but don't clear url, etc. in case url == mInternetStreamURL stop(); if (!url.empty()) { llinfos << "Starting internet stream: " << url << llendl; mCurrentInternetStreamp = new LLAudioStreamManagerFMODEX(mSystem,url); mURL = url; } else { llinfos << "Set internet stream to null" << llendl; mURL.clear(); } } void LLStreamingAudio_FMODEX::update() { // Kill dead internet streams, if possible std::list<LLAudioStreamManagerFMODEX *>::iterator iter; for (iter = mDeadStreams.begin(); iter != mDeadStreams.end();) { LLAudioStreamManagerFMODEX *streamp = *iter; if (streamp->stopStream()) { llinfos << "Closed dead stream" << llendl; delete streamp; mDeadStreams.erase(iter++); } else { iter++; } } // Don't do anything if there are no streams playing if (!mCurrentInternetStreamp) { return; } unsigned int progress; bool starving; bool diskbusy; FMOD_OPENSTATE open_state = mCurrentInternetStreamp->getOpenState(&progress, &starving, &diskbusy); if (open_state == FMOD_OPENSTATE_READY) { // Stream is live // start the stream if it's ready if (!mFMODInternetStreamChannelp && (mFMODInternetStreamChannelp = mCurrentInternetStreamp->startStream())) { // Reset volume to previously set volume setGain(getGain()); mFMODInternetStreamChannelp->setPaused(false); } } else if(open_state == FMOD_OPENSTATE_ERROR) { stop(); return; } if(mFMODInternetStreamChannelp) { FMOD::Sound *sound = NULL; if(mFMODInternetStreamChannelp->getCurrentSound(&sound) == FMOD_OK && sound) { FMOD_TAG tag; S32 tagcount, dirtytagcount; if(sound->getNumTags(&tagcount, &dirtytagcount) == FMOD_OK && dirtytagcount) { for(S32 i = 0; i < tagcount; ++i) { if(sound->getTag(NULL, i, &tag)!=FMOD_OK) continue; if (tag.type == FMOD_TAGTYPE_FMOD) { if (!strcmp(tag.name, "Sample Rate Change")) { llinfos << "Stream forced changing sample rate to " << *((float *)tag.data) << llendl; mFMODInternetStreamChannelp->setFrequency(*((float *)tag.data)); } continue; } } } if(starving) { bool paused = false; mFMODInternetStreamChannelp->getPaused(&paused); if(!paused) { llinfos << "Stream starvation detected! Pausing stream until buffer nearly full." << llendl; llinfos << " (diskbusy="<<diskbusy<<")" << llendl; llinfos << " (progress="<<progress<<")" << llendl; mFMODInternetStreamChannelp->setPaused(true); } } else if(progress > 80) { mFMODInternetStreamChannelp->setPaused(false); } } } } void LLStreamingAudio_FMODEX::stop() { if (mFMODInternetStreamChannelp) { mFMODInternetStreamChannelp->setPaused(true); mFMODInternetStreamChannelp->setPriority(0); mFMODInternetStreamChannelp = NULL; } if (mCurrentInternetStreamp) { llinfos << "Stopping internet stream: " << mCurrentInternetStreamp->getURL() << llendl; if (mCurrentInternetStreamp->stopStream()) { delete mCurrentInternetStreamp; } else { llwarns << "Pushing stream to dead list: " << mCurrentInternetStreamp->getURL() << llendl; mDeadStreams.push_back(mCurrentInternetStreamp); } mCurrentInternetStreamp = NULL; //mURL.clear(); } } void LLStreamingAudio_FMODEX::pause(int pauseopt) { if (pauseopt < 0) { pauseopt = mCurrentInternetStreamp ? 1 : 0; } if (pauseopt) { if (mCurrentInternetStreamp) { stop(); } } else { start(getURL()); } } // A stream is "playing" if it has been requested to start. That // doesn't necessarily mean audio is coming out of the speakers. int LLStreamingAudio_FMODEX::isPlaying() { if (mCurrentInternetStreamp) { return 1; // Active and playing } else if (!mURL.empty()) { return 2; // "Paused" } else { return 0; } } F32 LLStreamingAudio_FMODEX::getGain() { return mGain; } std::string LLStreamingAudio_FMODEX::getURL() { return mURL; } void LLStreamingAudio_FMODEX::setGain(F32 vol) { mGain = vol; if (mFMODInternetStreamChannelp) { vol = llclamp(vol * vol, 0.f, 1.f); //should vol be squared here? mFMODInternetStreamChannelp->setVolume(vol); } } /////////////////////////////////////////////////////// // manager of possibly-multiple internet audio streams LLAudioStreamManagerFMODEX::LLAudioStreamManagerFMODEX(FMOD::System *system, const std::string& url) : mSystem(system), mStreamChannel(NULL), mInternetStream(NULL), mReady(false) { mInternetStreamURL = url; FMOD_RESULT result = mSystem->createStream(url.c_str(), FMOD_2D | FMOD_NONBLOCKING | FMOD_MPEGSEARCH | FMOD_IGNORETAGS, 0, &mInternetStream); if (result!= FMOD_OK) { llwarns << "Couldn't open fmod stream, error " << FMOD_ErrorString(result) << llendl; mReady = false; return; } mReady = true; } FMOD::Channel *LLAudioStreamManagerFMODEX::startStream() { // We need a live and opened stream before we try and play it. if (!mInternetStream || getOpenState() != FMOD_OPENSTATE_READY) { llwarns << "No internet stream to start playing!" << llendl; return NULL; } if(mStreamChannel) return mStreamChannel; //Already have a channel for this stream. mSystem->playSound(FMOD_CHANNEL_FREE, mInternetStream, true, &mStreamChannel); return mStreamChannel; } bool LLAudioStreamManagerFMODEX::stopStream() { if (mInternetStream) { bool close = true; switch (getOpenState()) { case FMOD_OPENSTATE_CONNECTING: close = false; break; default: close = true; } if (close) { mInternetStream->release(); mStreamChannel = NULL; mInternetStream = NULL; return true; } else { return false; } } else { return true; } } FMOD_OPENSTATE LLAudioStreamManagerFMODEX::getOpenState(unsigned int* percentbuffered, bool* starving, bool* diskbusy) { FMOD_OPENSTATE state; mInternetStream->getOpenState(&state, percentbuffered, starving, diskbusy); return state; } void LLStreamingAudio_FMODEX::setBufferSizes(U32 streambuffertime, U32 decodebuffertime) { mSystem->setStreamBufferSize(streambuffertime/1000*128*128, FMOD_TIMEUNIT_RAWBYTES); FMOD_ADVANCEDSETTINGS settings; memset(&settings,0,sizeof(settings)); settings.cbsize=sizeof(settings); settings.defaultDecodeBufferSize = decodebuffertime;//ms mSystem->setAdvancedSettings(&settings); } <|endoftext|>
<commit_before>#include "plot_view.hpp" #include "plot.hpp" #include <QPainter> #include <QDebug> #include <algorithm> #include <iostream> using namespace std; namespace datavis { PlotView::PlotView(QWidget * parent): QWidget(parent) {} void PlotView::addPlot(Plot * plot) { m_plots.push_back(plot); updatePlotMap(); updateViewMap(); } void PlotView::updateViewMap() { auto size = this->size(); QTransform map; map.translate(0, size.height()); map.scale(size.width(), size.height()); m_view_map = map * m_plot_map; } void PlotView::updatePlotMap() { Plot::Range total_range; { bool first = true; for (auto plot : m_plots) { if (plot->isEmpty()) continue; auto range = plot->range(); if (first) total_range = range; else { double min_x = min(total_range.min.x(), range.min.x()); double min_y = min(total_range.min.y(), range.min.y()); double max_x = max(total_range.max.x(), range.max.x()); double max_y = max(total_range.max.y(), range.max.y()); total_range.min = QPointF(min_x, min_y); total_range.max = QPointF(max_x, max_y); } first = false; } } #if 0 cout << "View range: " << "(" << total_range.min.x() << "," << total_range.max.x() << ")" << " -> " << "(" << total_range.min.y() << "," << total_range.max.y() << ")" << endl; #endif QPointF extent = total_range.max - total_range.min; QPointF offset = total_range.min; //qDebug() << "offset:" << offset; //qDebug() << "extent:" << extent; double x_scale = extent.x() == 0 ? 1 : 1.0 / extent.x(); double y_scale = extent.y() == 0 ? 1 : 1.0 / extent.y(); //qDebug() << "x scale:" << x_scale; //qDebug() << "y scale:" << y_scale; QTransform transform; transform.scale(x_scale, y_scale); transform.translate(offset.x(), -offset.y()); m_plot_map = transform; } void PlotView::resizeEvent(QResizeEvent*) { updateViewMap(); } void PlotView::paintEvent(QPaintEvent* event) { QPainter painter(this); painter.fillRect(rect(), Qt::white); for (auto plot : m_plots) { if (plot->isEmpty()) continue; plot->plot(&painter, m_view_map); } } } <commit_msg>plot view: Add a little margin<commit_after>#include "plot_view.hpp" #include "plot.hpp" #include <QPainter> #include <QDebug> #include <algorithm> #include <iostream> using namespace std; namespace datavis { PlotView::PlotView(QWidget * parent): QWidget(parent) {} void PlotView::addPlot(Plot * plot) { m_plots.push_back(plot); updatePlotMap(); updateViewMap(); } void PlotView::updateViewMap() { auto size = this->size(); int margin = 10; QTransform map; map.translate(margin, size.height() - margin); map.scale(size.width() - 2 * margin, - (size.height() - 2 * margin)); m_view_map = m_plot_map * map; } void PlotView::updatePlotMap() { Plot::Range total_range; { bool first = true; for (auto plot : m_plots) { if (plot->isEmpty()) continue; auto range = plot->range(); if (first) total_range = range; else { double min_x = min(total_range.min.x(), range.min.x()); double min_y = min(total_range.min.y(), range.min.y()); double max_x = max(total_range.max.x(), range.max.x()); double max_y = max(total_range.max.y(), range.max.y()); total_range.min = QPointF(min_x, min_y); total_range.max = QPointF(max_x, max_y); } first = false; } } #if 0 cout << "View range: " << "(" << total_range.min.x() << "," << total_range.max.x() << ")" << " -> " << "(" << total_range.min.y() << "," << total_range.max.y() << ")" << endl; #endif QPointF extent = total_range.max - total_range.min; QPointF offset = total_range.min; //qDebug() << "offset:" << offset; //qDebug() << "extent:" << extent; double x_scale = extent.x() == 0 ? 1 : 1.0 / extent.x(); double y_scale = extent.y() == 0 ? 1 : 1.0 / extent.y(); //qDebug() << "x scale:" << x_scale; //qDebug() << "y scale:" << y_scale; QTransform transform; transform.scale(x_scale, y_scale); transform.translate(offset.x(), -offset.y()); m_plot_map = transform; } void PlotView::resizeEvent(QResizeEvent*) { updateViewMap(); } void PlotView::paintEvent(QPaintEvent* event) { QPainter painter(this); painter.fillRect(rect(), Qt::white); for (auto plot : m_plots) { if (plot->isEmpty()) continue; plot->plot(&painter, m_view_map); } } } <|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 <atlbase.h> #include "base/command_line.h" #include "base/process_util.h" #include "base/test/test_suite.h" #include "base/threading/platform_thread.h" #include "chrome/common/chrome_paths.h" #include "chrome_frame/test/chrome_frame_test_utils.h" #include "chrome_frame/test/chrome_frame_ui_test_utils.h" #include "chrome_frame/test_utils.h" #include "chrome_frame/utils.h" // To enable ATL-based code to run in this module class ChromeFrameUnittestsModule : public CAtlExeModuleT<ChromeFrameUnittestsModule> { public: static HRESULT InitializeCom() { return CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); } }; ChromeFrameUnittestsModule _AtlModule; const char kNoRegistrationSwitch[] = "no-registration"; void PureCall() { __debugbreak(); } int main(int argc, char **argv) { base::EnableTerminationOnHeapCorruption(); base::PlatformThread::SetName("ChromeFrame tests"); _set_purecall_handler(PureCall); TestSuite test_suite(argc, argv); SetConfigBool(kChromeFrameHeadlessMode, true); SetConfigBool(kChromeFrameAccessibleMode, true); base::ProcessHandle crash_service = chrome_frame_test::StartCrashService(); int ret = -1; // If mini_installer is used to register CF, we use the switch // --no-registration to avoid repetitive registration. if (CommandLine::ForCurrentProcess()->HasSwitch(kNoRegistrationSwitch)) { ret = test_suite.Run(); } else { // Register paths needed by the ScopedChromeFrameRegistrar. chrome::RegisterPathProvider(); // This will register the chrome frame in the build directory. It currently // leaves that chrome frame registered once the tests are done. It must be // constructed AFTER the TestSuite is created since TestSuites create THE // AtExitManager. // TODO(robertshield): Make these tests restore the original registration // once done. ScopedChromeFrameRegistrar registrar; // Register IAccessible2 proxy stub DLL, needed for some tests. ScopedChromeFrameRegistrar ia2_registrar( chrome_frame_test::GetIAccessible2ProxyStubPath().value()); ret = test_suite.Run(); } DeleteConfigValue(kChromeFrameHeadlessMode); DeleteConfigValue(kChromeFrameAccessibleMode); if (crash_service) base::KillProcess(crash_service, 0, false); } <commit_msg>Attempt 3 at landing this patch. The previous attempts caused compile failures on the windows builders. The errors were around using __try __except in code which had C++ objects. The latest attempt works around this issue by just handling the exception and returning. The processes are terminated by the caller.<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 <atlbase.h> #include "base/command_line.h" #include "base/process_util.h" #include "base/test/test_suite.h" #include "base/threading/platform_thread.h" #include "chrome/common/chrome_paths.h" #include "chrome_frame/test/chrome_frame_test_utils.h" #include "chrome_frame/test/chrome_frame_ui_test_utils.h" #include "chrome_frame/test_utils.h" #include "chrome_frame/utils.h" // To enable ATL-based code to run in this module class ChromeFrameUnittestsModule : public CAtlExeModuleT<ChromeFrameUnittestsModule> { public: static HRESULT InitializeCom() { return CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); } }; ChromeFrameUnittestsModule _AtlModule; const char kNoRegistrationSwitch[] = "no-registration"; void PureCall() { __debugbreak(); } // This class implements the Run method and registers an exception handler to // ensure that any ChromeFrame processes like IE, Firefox, etc are terminated // if there is a crash in the chrome frame test suite. class ChromeFrameTestSuite : public base::TestSuite { public: ChromeFrameTestSuite(int argc, char** argv) : base::TestSuite(argc, argv) {} int Run() { // Register a stack based exception handler to catch any exceptions which // occur in the course of the test. int ret = -1; __try { ret = base::TestSuite::Run(); } _except(EXCEPTION_EXECUTE_HANDLER) { ret = -1; } return ret; } }; int main(int argc, char **argv) { base::EnableTerminationOnHeapCorruption(); base::PlatformThread::SetName("ChromeFrame tests"); _set_purecall_handler(PureCall); ChromeFrameTestSuite test_suite(argc, argv); SetConfigBool(kChromeFrameHeadlessMode, true); SetConfigBool(kChromeFrameAccessibleMode, true); base::ProcessHandle crash_service = chrome_frame_test::StartCrashService(); int ret = -1; // If mini_installer is used to register CF, we use the switch // --no-registration to avoid repetitive registration. if (CommandLine::ForCurrentProcess()->HasSwitch(kNoRegistrationSwitch)) { ret = test_suite.Run(); } else { // Register paths needed by the ScopedChromeFrameRegistrar. chrome::RegisterPathProvider(); // This will register the chrome frame in the build directory. It currently // leaves that chrome frame registered once the tests are done. It must be // constructed AFTER the TestSuite is created since TestSuites create THE // AtExitManager. // TODO(robertshield): Make these tests restore the original registration // once done. ScopedChromeFrameRegistrar registrar; // Register IAccessible2 proxy stub DLL, needed for some tests. ScopedChromeFrameRegistrar ia2_registrar( chrome_frame_test::GetIAccessible2ProxyStubPath().value()); ret = test_suite.Run(); } if (ret == -1) { LOG(ERROR) << "ChromeFrame tests crashed"; chrome_frame_test::KillProcesses(L"iexplore.exe", 0, false); chrome_frame_test::KillProcesses(L"firefox.exe", 0, false); } DeleteConfigValue(kChromeFrameHeadlessMode); DeleteConfigValue(kChromeFrameAccessibleMode); if (crash_service) base::KillProcess(crash_service, 0, false); } <|endoftext|>
<commit_before>/* * Copyright (c) 2020 Pedro Falcato * This file is part of Onyx, and is released under the terms of the MIT License * check LICENSE at the root directory for more information */ #include <stdio.h> #include "../virtio.hpp" #include <onyx/slice.hpp> #include <onyx/page.h> #include <onyx/net/network.h> #include <onyx/net/ethernet.h> struct page_frag_alloc_info { struct page *page_list; struct page *curr; size_t off; }; struct page_frag_res { struct page *page; size_t off; }; extern "C" struct page_frag_res page_frag_alloc(struct page_frag_alloc_info *inf, size_t size); namespace virtio { void network_vdev::get_mac(cul::slice<uint8_t, 6>& mac_buf) { unsigned int i = 0; for(auto& b : mac_buf) b = read<uint8_t>(network_registers::mac_base + i++); } size_t net_if_getlen(void *info, struct packetbuf_proto **next, void **next_info) { auto vdev = static_cast<network_vdev *>(info); (void) vdev; *next = nullptr; *next_info = info; return sizeof(virtio_net_hdr); } packetbuf_proto net_if_proto = { .name = "virtio_net", .get_len = net_if_getlen }; packetbuf_proto *network_vdev::get_packetbuf_proto(netif *n) { return eth_get_packetbuf_proto(); } int network_vdev::__sendpacket(const void *buffer, uint16_t size, netif *nif) { auto dev = static_cast<network_vdev *>(nif->priv); return dev->send_packet(buffer, size); } static constexpr unsigned int network_receiveq = 0; static constexpr unsigned int network_transmitq = 1; int network_vdev::send_packet(const void *buffer, uint16_t size) { /* TODO: We're casting away const here! Ewwwwwwwwwwww - passing [buffer, size] here * isn't a good idea - I don't like it and it forces us to do this disgusting thing. */ int st = 0; /* This page allocation + copy is ugly, I really really don't like it but the * network stack packet submission is this broken... * TODO: Fix. */ /* The networking subsystem should benefit from something like, for example, a packetbuf struct that holds * a bunch more of packet data and gets passed *everywhere*, including send_packet, instead of being a * glorified buffer allocation system as-is right now. Also, allocating raw pages instead of needing either a copy * or dma_get_ranges */ struct page *p = alloc_page(PAGE_ALLOC_NO_ZERO); if(!p) return -ENOMEM; auto hdr = reinterpret_cast<virtio_net_hdr *>(const_cast<void *>(buffer)); memset(hdr, 0, sizeof(*hdr)); hdr->gso_type = VIRTIO_NET_HDR_GSO_NONE; auto &transmit = virtqueue_list[network_transmitq]; memcpy(PAGE_TO_VIRT(p), buffer, size); virtio_buf_list list{transmit}; if(!list.prepare(PAGE_TO_VIRT(p), size, false)) { st = -EIO; goto out_error; } if(!transmit->allocate_descriptors(list)) { st = -EIO; goto out_error; } if(!transmit->put_buffer(list)) { st = -EIO; goto out_error; } return 0; out_error: free_page(p); return st; } static constexpr unsigned int rx_buf_size = 1526; bool network_vdev::setup_rx() { auto &vq = virtqueue_list[network_receiveq]; auto qsize = vq->get_queue_size(); rx_pages = alloc_pages(vm_size_to_pages(rx_buf_size * qsize), PAGE_ALLOC_NO_ZERO); if(!rx_pages) { return false; } struct page_frag_alloc_info alloc_info; alloc_info.curr = alloc_info.page_list = rx_pages; alloc_info.off = 0; for(unsigned int i = 0; i < qsize; i++) { auto [page, off] = page_frag_alloc(&alloc_info, rx_buf_size); virtio_buf_list l{vq}; if(!l.prepare((char *) PAGE_TO_VIRT(page) + off, rx_buf_size, true)) return false; if(!vq->allocate_descriptors(l)) return false; bool is_last = i == qsize - 1; /* Only notify the buffer if it's the last one, as to avoid redudant notifications */ if(!vq->put_buffer(l, is_last)) return false; } return true; } void network_vdev::handle_used_buffer(const virtq_used_elem &elem, const virtq *vq) { auto nr = vq->get_nr(); if(nr == network_receiveq) { auto [paddr, len] = vq->get_buf_from_id(elem.id); auto packet_base = paddr + PHYS_BASE + sizeof(virtio_net_hdr); network_dispatch_receive((uint8_t *) packet_base, elem.length - sizeof(virtio_net_hdr), nif.get_data()); } else if(nr == network_transmitq) { auto [paddr, len] = vq->get_buf_from_id(elem.id); page *p = phys_to_page(paddr); free_page(p); } } bool network_vdev::perform_subsystem_initialization() { if(raw_has_feature(network_features::mac)) { signal_feature(network_features::mac); } else { /* The device should support the mac address feature */ return false; } if(!do_device_independent_negotiation() || !finish_feature_negotiation()) { set_failure(); return false; } /* TODO: Support VIRTIO_NET_F_MQ */ if(!create_virtqueue(0, get_max_virtq_size(0)) || !create_virtqueue(1, get_max_virtq_size(1)) || !create_virtqueue(2, get_max_virtq_size(2))) { printk("virtio: Failed to create virtqueues\n"); set_failure(); return false; } finalise_driver_init(); if(!setup_rx()) { set_failure(); return false; } nif = make_unique<netif>(); nif->name = "eth0"; nif->flags |= NETIF_LINKUP; nif->priv = this; nif->sendpacket = virtio::network_vdev::__sendpacket; nif->mtu = 1514; nif->if_proto = &virtio::net_if_proto; nif->get_packetbuf_proto = virtio::network_vdev::get_packetbuf_proto; cul::slice<uint8_t, 6> m{nif->mac_address, 6}; get_mac(m); netif_register_if(nif.get_data()); return true; } network_vdev::~network_vdev() { if(rx_pages) free_pages(rx_pages); } } <commit_msg>virtio/network: Fix small possible null deref bug.<commit_after>/* * Copyright (c) 2020 Pedro Falcato * This file is part of Onyx, and is released under the terms of the MIT License * check LICENSE at the root directory for more information */ #include <stdio.h> #include "../virtio.hpp" #include <onyx/slice.hpp> #include <onyx/page.h> #include <onyx/net/network.h> #include <onyx/net/ethernet.h> struct page_frag_alloc_info { struct page *page_list; struct page *curr; size_t off; }; struct page_frag_res { struct page *page; size_t off; }; extern "C" struct page_frag_res page_frag_alloc(struct page_frag_alloc_info *inf, size_t size); namespace virtio { void network_vdev::get_mac(cul::slice<uint8_t, 6>& mac_buf) { unsigned int i = 0; for(auto& b : mac_buf) b = read<uint8_t>(network_registers::mac_base + i++); } size_t net_if_getlen(void *info, struct packetbuf_proto **next, void **next_info) { auto vdev = static_cast<network_vdev *>(info); (void) vdev; *next = nullptr; *next_info = info; return sizeof(virtio_net_hdr); } packetbuf_proto net_if_proto = { .name = "virtio_net", .get_len = net_if_getlen }; packetbuf_proto *network_vdev::get_packetbuf_proto(netif *n) { return eth_get_packetbuf_proto(); } int network_vdev::__sendpacket(const void *buffer, uint16_t size, netif *nif) { auto dev = static_cast<network_vdev *>(nif->priv); return dev->send_packet(buffer, size); } static constexpr unsigned int network_receiveq = 0; static constexpr unsigned int network_transmitq = 1; int network_vdev::send_packet(const void *buffer, uint16_t size) { /* TODO: We're casting away const here! Ewwwwwwwwwwww - passing [buffer, size] here * isn't a good idea - I don't like it and it forces us to do this disgusting thing. */ int st = 0; /* This page allocation + copy is ugly, I really really don't like it but the * network stack packet submission is this broken... * TODO: Fix. */ /* The networking subsystem should benefit from something like, for example, a packetbuf struct that holds * a bunch more of packet data and gets passed *everywhere*, including send_packet, instead of being a * glorified buffer allocation system as-is right now. Also, allocating raw pages instead of needing either a copy * or dma_get_ranges */ struct page *p = alloc_page(PAGE_ALLOC_NO_ZERO); if(!p) return -ENOMEM; auto hdr = reinterpret_cast<virtio_net_hdr *>(const_cast<void *>(buffer)); memset(hdr, 0, sizeof(*hdr)); hdr->gso_type = VIRTIO_NET_HDR_GSO_NONE; auto &transmit = virtqueue_list[network_transmitq]; memcpy(PAGE_TO_VIRT(p), buffer, size); virtio_buf_list list{transmit}; if(!list.prepare(PAGE_TO_VIRT(p), size, false)) { st = -EIO; goto out_error; } if(!transmit->allocate_descriptors(list)) { st = -EIO; goto out_error; } if(!transmit->put_buffer(list)) { st = -EIO; goto out_error; } return 0; out_error: free_page(p); return st; } static constexpr unsigned int rx_buf_size = 1526; bool network_vdev::setup_rx() { auto &vq = virtqueue_list[network_receiveq]; auto qsize = vq->get_queue_size(); rx_pages = alloc_pages(vm_size_to_pages(rx_buf_size * qsize), PAGE_ALLOC_NO_ZERO); if(!rx_pages) { return false; } struct page_frag_alloc_info alloc_info; alloc_info.curr = alloc_info.page_list = rx_pages; alloc_info.off = 0; for(unsigned int i = 0; i < qsize; i++) { auto [page, off] = page_frag_alloc(&alloc_info, rx_buf_size); virtio_buf_list l{vq}; if(!l.prepare((char *) PAGE_TO_VIRT(page) + off, rx_buf_size, true)) return false; if(!vq->allocate_descriptors(l)) return false; bool is_last = i == qsize - 1; /* Only notify the buffer if it's the last one, as to avoid redudant notifications */ if(!vq->put_buffer(l, is_last)) return false; } return true; } void network_vdev::handle_used_buffer(const virtq_used_elem &elem, const virtq *vq) { auto nr = vq->get_nr(); if(nr == network_receiveq) { auto [paddr, len] = vq->get_buf_from_id(elem.id); auto packet_base = paddr + PHYS_BASE + sizeof(virtio_net_hdr); network_dispatch_receive((uint8_t *) packet_base, elem.length - sizeof(virtio_net_hdr), nif.get_data()); } else if(nr == network_transmitq) { auto [paddr, len] = vq->get_buf_from_id(elem.id); page *p = phys_to_page(paddr); free_page(p); } } bool network_vdev::perform_subsystem_initialization() { if(raw_has_feature(network_features::mac)) { signal_feature(network_features::mac); } else { /* The device should support the mac address feature */ return false; } if(!do_device_independent_negotiation() || !finish_feature_negotiation()) { set_failure(); return false; } /* TODO: Support VIRTIO_NET_F_MQ */ if(!create_virtqueue(0, get_max_virtq_size(0)) || !create_virtqueue(1, get_max_virtq_size(1)) || !create_virtqueue(2, get_max_virtq_size(2))) { printk("virtio: Failed to create virtqueues\n"); set_failure(); return false; } finalise_driver_init(); if(!setup_rx()) { set_failure(); return false; } nif = make_unique<netif>(); if(!nif) { set_failure(); return false; } nif->name = "eth0"; nif->flags |= NETIF_LINKUP; nif->priv = this; nif->sendpacket = virtio::network_vdev::__sendpacket; nif->mtu = 1514; nif->if_proto = &virtio::net_if_proto; nif->get_packetbuf_proto = virtio::network_vdev::get_packetbuf_proto; cul::slice<uint8_t, 6> m{nif->mac_address, 6}; get_mac(m); netif_register_if(nif.get_data()); return true; } network_vdev::~network_vdev() { if(rx_pages) free_pages(rx_pages); } } <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2018 Intel Corporation // // // // 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 "instance_intersector.h" #include "../common/scene.h" #include "../common/instance_stack.h" namespace embree { namespace isa { /* Push an instance to the stack. */ RTC_FORCEINLINE bool pushInstance(PointQueryContext* context, unsigned int instanceId, AffineSpace3fa const& w2i, AffineSpace3fa const& i2w) { PointQueryInstanceStack* stack = context->instStack; const size_t stackSize = stack->size; const bool spaceAvailable = context && stackSize < RTC_MAX_INSTANCE_LEVEL_COUNT; assert(spaceAvailable); if (likely(spaceAvailable)) { stack->instID[stackSize] = instanceId; stack->instW2I[stackSize] = w2i; stack->instI2W[stackSize] = i2w; if (unlikely(stackSize > 0)) { stack->instW2I[stackSize] = stack->instW2I[stackSize ] * stack->instW2I[stackSize-1]; stack->instI2W[stackSize] = stack->instI2W[stackSize-1] * stack->instI2W[stackSize ]; } stack->size++; } return spaceAvailable; } /* Pop the last instance pushed to the stack. Do not call on an empty stack. */ RTC_FORCEINLINE void popInstance(PointQueryContext* context) { assert(context && context->instStack->size > 0); context->instStack->instID[--context->instStack->size] = RTC_INVALID_GEOMETRY_ID; } void InstanceIntersector1::intersect(const Precalculations& pre, RayHit& ray, IntersectContext* context, const InstancePrimitive& prim) { const Instance* instance = prim.instance; /* perform ray mask test */ #if defined(EMBREE_RAY_MASK) if ((ray.mask & instance->mask) == 0) return; #endif RTCIntersectContext* user_context = context->user; if (likely(instance_id_stack::push(user_context, instance->geomID))) { const AffineSpace3fa world2local = instance->getWorld2Local(); const Vec3fa ray_org = ray.org; const Vec3fa ray_dir = ray.dir; ray.org = Vec3fa(xfmPoint(world2local, ray_org), ray.tnear()); ray.dir = Vec3fa(xfmVector(world2local, ray_dir), ray.time()); IntersectContext newcontext((Scene*)instance->object, user_context); instance->object->intersectors.intersect((RTCRayHit&)ray, &newcontext); ray.org = ray_org; ray.dir = ray_dir; instance_id_stack::pop(user_context); } } bool InstanceIntersector1::occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const InstancePrimitive& prim) { const Instance* instance = prim.instance; /* perform ray mask test */ #if defined(EMBREE_RAY_MASK) if ((ray.mask & instance->mask) == 0) return false; #endif RTCIntersectContext* user_context = context->user; bool occluded = false; if (likely(instance_id_stack::push(user_context, instance->geomID))) { const AffineSpace3fa world2local = instance->getWorld2Local(); const Vec3fa ray_org = ray.org; const Vec3fa ray_dir = ray.dir; ray.org = Vec3fa(xfmPoint(world2local, ray_org), ray.tnear()); ray.dir = Vec3fa(xfmVector(world2local, ray_dir), ray.time()); IntersectContext newcontext((Scene*)instance->object, user_context); instance->object->intersectors.occluded((RTCRay&)ray, &newcontext); ray.org = ray_org; ray.dir = ray_dir; occluded = ray.tfar < 0.0f; instance_id_stack::pop(user_context); } return occluded; } void InstanceIntersector1::pointQuery(PointQuery* query, PointQueryContext* context, const InstancePrimitive& prim) { const Instance* instance = prim.instance; const AffineSpace3fa local2world = instance->getLocal2World(); const AffineSpace3fa world2local = instance->getWorld2Local(); float similarityScale = 0.f; const bool similtude = context->query_type == POINT_QUERY_TYPE_SPHERE && similarityTransform(world2local, &similarityScale); assert((similtude && similarityScale > 0) || !similtude); if (likely(pushInstance(context, instance->geomID, world2local, local2world))) { PointQuery query_inst; query_inst.time = query->time; query_inst.p = xfmPoint(world2local, query->p); query_inst.radius = query->radius * similarityScale; PointQueryContext context_inst( (Scene*)instance->object, context->query_ws, similtude ? POINT_QUERY_TYPE_SPHERE : POINT_QUERY_TYPE_AABB, context->func, (RTCPointQueryInstanceStack*)context->instStack, similarityScale, context->userPtr); instance->object->intersectors.pointQuery(&query_inst, &context_inst); popInstance(context); } } void InstanceIntersector1MB::intersect(const Precalculations& pre, RayHit& ray, IntersectContext* context, const InstancePrimitive& prim) { const Instance* instance = prim.instance; /* perform ray mask test */ #if defined(EMBREE_RAY_MASK) if ((ray.mask & instance->mask) == 0) return; #endif RTCIntersectContext* user_context = context->user; if (likely(instance_id_stack::push(user_context, instance->geomID))) { const AffineSpace3fa world2local = instance->getWorld2Local(ray.time()); const Vec3fa ray_org = ray.org; const Vec3fa ray_dir = ray.dir; ray.org = Vec3fa(xfmPoint(world2local, ray_org), ray.tnear()); ray.dir = Vec3fa(xfmVector(world2local, ray_dir), ray.time()); IntersectContext newcontext((Scene*)instance->object, user_context); instance->object->intersectors.intersect((RTCRayHit&)ray, &newcontext); ray.org = ray_org; ray.dir = ray_dir; instance_id_stack::pop(user_context); } } bool InstanceIntersector1MB::occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const InstancePrimitive& prim) { const Instance* instance = prim.instance; /* perform ray mask test */ #if defined(EMBREE_RAY_MASK) if ((ray.mask & instance->mask) == 0) return false; #endif RTCIntersectContext* user_context = context->user; bool occluded = false; if (likely(instance_id_stack::push(user_context, instance->geomID))) { const AffineSpace3fa world2local = instance->getWorld2Local(ray.time()); const Vec3fa ray_org = ray.org; const Vec3fa ray_dir = ray.dir; ray.org = Vec3fa(xfmPoint(world2local, ray_org), ray.tnear()); ray.dir = Vec3fa(xfmVector(world2local, ray_dir), ray.time()); IntersectContext newcontext((Scene*)instance->object, user_context); instance->object->intersectors.occluded((RTCRay&)ray, &newcontext); ray.org = ray_org; ray.dir = ray_dir; occluded = ray.tfar < 0.0f; instance_id_stack::pop(user_context); } return occluded; } void InstanceIntersector1MB::pointQuery(PointQuery* query, PointQueryContext* context, const InstancePrimitive& prim) { const Instance* instance = prim.instance; const AffineSpace3fa local2world = instance->getLocal2World(query->time); const AffineSpace3fa world2local = instance->getWorld2Local(query->time); float similarityScale = 0.f; const bool similtude = context->query_type == POINT_QUERY_TYPE_SPHERE && similarityTransform(world2local, &similarityScale); if (likely(pushInstance(context, instance->geomID, world2local, local2world))) { PointQuery query_inst; query_inst.time = query->time; query_inst.p = xfmPoint(world2local, query->p); query_inst.radius = query->radius * similarityScale; PointQueryContext context_inst( (Scene*)instance->object, context->query_ws, similtude ? POINT_QUERY_TYPE_SPHERE : POINT_QUERY_TYPE_AABB, context->func, (RTCPointQueryInstanceStack*)context->instStack, similarityScale, context->userPtr); instance->object->intersectors.pointQuery(&query_inst, &context_inst); popInstance(context); } } template<int K> void InstanceIntersectorK<K>::intersect(const vbool<K>& valid_i, const Precalculations& pre, RayHitK<K>& ray, IntersectContext* context, const InstancePrimitive& prim) { vbool<K> valid = valid_i; const Instance* instance = prim.instance; /* perform ray mask test */ #if defined(EMBREE_RAY_MASK) valid &= (ray.mask & instance->mask) != 0; if (none(valid)) return; #endif RTCIntersectContext* user_context = context->user; if (likely(instance_id_stack::push(user_context, instance->geomID))) { AffineSpace3vf<K> world2local = instance->getWorld2Local(); const Vec3vf<K> ray_org = ray.org; const Vec3vf<K> ray_dir = ray.dir; ray.org = xfmPoint(world2local, ray_org); ray.dir = xfmVector(world2local, ray_dir); IntersectContext newcontext((Scene*)instance->object, user_context); instance->object->intersectors.intersect(valid, ray, &newcontext); ray.org = ray_org; ray.dir = ray_dir; instance_id_stack::pop(user_context); } } template<int K> vbool<K> InstanceIntersectorK<K>::occluded(const vbool<K>& valid_i, const Precalculations& pre, RayK<K>& ray, IntersectContext* context, const InstancePrimitive& prim) { vbool<K> valid = valid_i; const Instance* instance = prim.instance; /* perform ray mask test */ #if defined(EMBREE_RAY_MASK) valid &= (ray.mask & instance->mask) != 0; if (none(valid)) return false; #endif RTCIntersectContext* user_context = context->user; vbool<K> occluded = false; if (likely(instance_id_stack::push(user_context, instance->geomID))) { AffineSpace3vf<K> world2local = instance->getWorld2Local(); const Vec3vf<K> ray_org = ray.org; const Vec3vf<K> ray_dir = ray.dir; ray.org = xfmPoint(world2local, ray_org); ray.dir = xfmVector(world2local, ray_dir); IntersectContext newcontext((Scene*)instance->object, user_context); instance->object->intersectors.occluded(valid, ray, &newcontext); ray.org = ray_org; ray.dir = ray_dir; occluded = ray.tfar < 0.0f; instance_id_stack::pop(user_context); } return occluded; } template<int K> void InstanceIntersectorKMB<K>::intersect(const vbool<K>& valid_i, const Precalculations& pre, RayHitK<K>& ray, IntersectContext* context, const InstancePrimitive& prim) { vbool<K> valid = valid_i; const Instance* instance = prim.instance; /* perform ray mask test */ #if defined(EMBREE_RAY_MASK) valid &= (ray.mask & instance->mask) != 0; if (none(valid)) return; #endif RTCIntersectContext* user_context = context->user; if (likely(instance_id_stack::push(user_context, instance->geomID))) { AffineSpace3vf<K> world2local = instance->getWorld2Local<K>(valid, ray.time()); const Vec3vf<K> ray_org = ray.org; const Vec3vf<K> ray_dir = ray.dir; ray.org = xfmPoint(world2local, ray_org); ray.dir = xfmVector(world2local, ray_dir); IntersectContext newcontext((Scene*)instance->object, user_context); instance->object->intersectors.intersect(valid, ray, &newcontext); ray.org = ray_org; ray.dir = ray_dir; instance_id_stack::pop(user_context); } } template<int K> vbool<K> InstanceIntersectorKMB<K>::occluded(const vbool<K>& valid_i, const Precalculations& pre, RayK<K>& ray, IntersectContext* context, const InstancePrimitive& prim) { vbool<K> valid = valid_i; const Instance* instance = prim.instance; /* perform ray mask test */ #if defined(EMBREE_RAY_MASK) valid &= (ray.mask & instance->mask) != 0; if (none(valid)) return false; #endif RTCIntersectContext* user_context = context->user; vbool<K> occluded = false; if (likely(instance_id_stack::push(user_context, instance->geomID))) { AffineSpace3vf<K> world2local = instance->getWorld2Local<K>(valid, ray.time()); const Vec3vf<K> ray_org = ray.org; const Vec3vf<K> ray_dir = ray.dir; ray.org = xfmPoint(world2local, ray_org); ray.dir = xfmVector(world2local, ray_dir); IntersectContext newcontext((Scene*)instance->object, user_context); instance->object->intersectors.occluded(valid, ray, &newcontext); ray.org = ray_org; ray.dir = ray_dir; occluded = ray.tfar < 0.0f; instance_id_stack::pop(user_context); } return occluded; } #if defined(__SSE__) template struct InstanceIntersectorK<4>; template struct InstanceIntersectorKMB<4>; #endif #if defined(__AVX__) template struct InstanceIntersectorK<8>; template struct InstanceIntersectorKMB<8>; #endif #if defined(__AVX512F__) template struct InstanceIntersectorK<16>; template struct InstanceIntersectorKMB<16>; #endif } } <commit_msg>remove unnecessary checks in pushInstance<commit_after>// ======================================================================== // // Copyright 2009-2018 Intel Corporation // // // // 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 "instance_intersector.h" #include "../common/scene.h" #include "../common/instance_stack.h" namespace embree { namespace isa { /* Push an instance to the stack. */ RTC_FORCEINLINE bool pushInstance(PointQueryContext* context, unsigned int instanceId, AffineSpace3fa const& w2i, AffineSpace3fa const& i2w) { assert(context); PointQueryInstanceStack* stack = context->instStack; const size_t stackSize = stack->size; assert(stackSize < RTC_MAX_INSTANCE_LEVEL_COUNT); stack->instID[stackSize] = instanceId; stack->instW2I[stackSize] = w2i; stack->instI2W[stackSize] = i2w; if (unlikely(stackSize > 0)) { stack->instW2I[stackSize] = stack->instW2I[stackSize ] * stack->instW2I[stackSize-1]; stack->instI2W[stackSize] = stack->instI2W[stackSize-1] * stack->instI2W[stackSize ]; } stack->size++; return true; } /* Pop the last instance pushed to the stack. Do not call on an empty stack. */ RTC_FORCEINLINE void popInstance(PointQueryContext* context) { assert(context && context->instStack->size > 0); context->instStack->instID[--context->instStack->size] = RTC_INVALID_GEOMETRY_ID; } void InstanceIntersector1::intersect(const Precalculations& pre, RayHit& ray, IntersectContext* context, const InstancePrimitive& prim) { const Instance* instance = prim.instance; /* perform ray mask test */ #if defined(EMBREE_RAY_MASK) if ((ray.mask & instance->mask) == 0) return; #endif RTCIntersectContext* user_context = context->user; if (likely(instance_id_stack::push(user_context, instance->geomID))) { const AffineSpace3fa world2local = instance->getWorld2Local(); const Vec3fa ray_org = ray.org; const Vec3fa ray_dir = ray.dir; ray.org = Vec3fa(xfmPoint(world2local, ray_org), ray.tnear()); ray.dir = Vec3fa(xfmVector(world2local, ray_dir), ray.time()); IntersectContext newcontext((Scene*)instance->object, user_context); instance->object->intersectors.intersect((RTCRayHit&)ray, &newcontext); ray.org = ray_org; ray.dir = ray_dir; instance_id_stack::pop(user_context); } } bool InstanceIntersector1::occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const InstancePrimitive& prim) { const Instance* instance = prim.instance; /* perform ray mask test */ #if defined(EMBREE_RAY_MASK) if ((ray.mask & instance->mask) == 0) return false; #endif RTCIntersectContext* user_context = context->user; bool occluded = false; if (likely(instance_id_stack::push(user_context, instance->geomID))) { const AffineSpace3fa world2local = instance->getWorld2Local(); const Vec3fa ray_org = ray.org; const Vec3fa ray_dir = ray.dir; ray.org = Vec3fa(xfmPoint(world2local, ray_org), ray.tnear()); ray.dir = Vec3fa(xfmVector(world2local, ray_dir), ray.time()); IntersectContext newcontext((Scene*)instance->object, user_context); instance->object->intersectors.occluded((RTCRay&)ray, &newcontext); ray.org = ray_org; ray.dir = ray_dir; occluded = ray.tfar < 0.0f; instance_id_stack::pop(user_context); } return occluded; } void InstanceIntersector1::pointQuery(PointQuery* query, PointQueryContext* context, const InstancePrimitive& prim) { const Instance* instance = prim.instance; const AffineSpace3fa local2world = instance->getLocal2World(); const AffineSpace3fa world2local = instance->getWorld2Local(); float similarityScale = 0.f; const bool similtude = context->query_type == POINT_QUERY_TYPE_SPHERE && similarityTransform(world2local, &similarityScale); assert((similtude && similarityScale > 0) || !similtude); if (likely(pushInstance(context, instance->geomID, world2local, local2world))) { PointQuery query_inst; query_inst.time = query->time; query_inst.p = xfmPoint(world2local, query->p); query_inst.radius = query->radius * similarityScale; PointQueryContext context_inst( (Scene*)instance->object, context->query_ws, similtude ? POINT_QUERY_TYPE_SPHERE : POINT_QUERY_TYPE_AABB, context->func, (RTCPointQueryInstanceStack*)context->instStack, similarityScale, context->userPtr); instance->object->intersectors.pointQuery(&query_inst, &context_inst); popInstance(context); } } void InstanceIntersector1MB::intersect(const Precalculations& pre, RayHit& ray, IntersectContext* context, const InstancePrimitive& prim) { const Instance* instance = prim.instance; /* perform ray mask test */ #if defined(EMBREE_RAY_MASK) if ((ray.mask & instance->mask) == 0) return; #endif RTCIntersectContext* user_context = context->user; if (likely(instance_id_stack::push(user_context, instance->geomID))) { const AffineSpace3fa world2local = instance->getWorld2Local(ray.time()); const Vec3fa ray_org = ray.org; const Vec3fa ray_dir = ray.dir; ray.org = Vec3fa(xfmPoint(world2local, ray_org), ray.tnear()); ray.dir = Vec3fa(xfmVector(world2local, ray_dir), ray.time()); IntersectContext newcontext((Scene*)instance->object, user_context); instance->object->intersectors.intersect((RTCRayHit&)ray, &newcontext); ray.org = ray_org; ray.dir = ray_dir; instance_id_stack::pop(user_context); } } bool InstanceIntersector1MB::occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const InstancePrimitive& prim) { const Instance* instance = prim.instance; /* perform ray mask test */ #if defined(EMBREE_RAY_MASK) if ((ray.mask & instance->mask) == 0) return false; #endif RTCIntersectContext* user_context = context->user; bool occluded = false; if (likely(instance_id_stack::push(user_context, instance->geomID))) { const AffineSpace3fa world2local = instance->getWorld2Local(ray.time()); const Vec3fa ray_org = ray.org; const Vec3fa ray_dir = ray.dir; ray.org = Vec3fa(xfmPoint(world2local, ray_org), ray.tnear()); ray.dir = Vec3fa(xfmVector(world2local, ray_dir), ray.time()); IntersectContext newcontext((Scene*)instance->object, user_context); instance->object->intersectors.occluded((RTCRay&)ray, &newcontext); ray.org = ray_org; ray.dir = ray_dir; occluded = ray.tfar < 0.0f; instance_id_stack::pop(user_context); } return occluded; } void InstanceIntersector1MB::pointQuery(PointQuery* query, PointQueryContext* context, const InstancePrimitive& prim) { const Instance* instance = prim.instance; const AffineSpace3fa local2world = instance->getLocal2World(query->time); const AffineSpace3fa world2local = instance->getWorld2Local(query->time); float similarityScale = 0.f; const bool similtude = context->query_type == POINT_QUERY_TYPE_SPHERE && similarityTransform(world2local, &similarityScale); if (likely(pushInstance(context, instance->geomID, world2local, local2world))) { PointQuery query_inst; query_inst.time = query->time; query_inst.p = xfmPoint(world2local, query->p); query_inst.radius = query->radius * similarityScale; PointQueryContext context_inst( (Scene*)instance->object, context->query_ws, similtude ? POINT_QUERY_TYPE_SPHERE : POINT_QUERY_TYPE_AABB, context->func, (RTCPointQueryInstanceStack*)context->instStack, similarityScale, context->userPtr); instance->object->intersectors.pointQuery(&query_inst, &context_inst); popInstance(context); } } template<int K> void InstanceIntersectorK<K>::intersect(const vbool<K>& valid_i, const Precalculations& pre, RayHitK<K>& ray, IntersectContext* context, const InstancePrimitive& prim) { vbool<K> valid = valid_i; const Instance* instance = prim.instance; /* perform ray mask test */ #if defined(EMBREE_RAY_MASK) valid &= (ray.mask & instance->mask) != 0; if (none(valid)) return; #endif RTCIntersectContext* user_context = context->user; if (likely(instance_id_stack::push(user_context, instance->geomID))) { AffineSpace3vf<K> world2local = instance->getWorld2Local(); const Vec3vf<K> ray_org = ray.org; const Vec3vf<K> ray_dir = ray.dir; ray.org = xfmPoint(world2local, ray_org); ray.dir = xfmVector(world2local, ray_dir); IntersectContext newcontext((Scene*)instance->object, user_context); instance->object->intersectors.intersect(valid, ray, &newcontext); ray.org = ray_org; ray.dir = ray_dir; instance_id_stack::pop(user_context); } } template<int K> vbool<K> InstanceIntersectorK<K>::occluded(const vbool<K>& valid_i, const Precalculations& pre, RayK<K>& ray, IntersectContext* context, const InstancePrimitive& prim) { vbool<K> valid = valid_i; const Instance* instance = prim.instance; /* perform ray mask test */ #if defined(EMBREE_RAY_MASK) valid &= (ray.mask & instance->mask) != 0; if (none(valid)) return false; #endif RTCIntersectContext* user_context = context->user; vbool<K> occluded = false; if (likely(instance_id_stack::push(user_context, instance->geomID))) { AffineSpace3vf<K> world2local = instance->getWorld2Local(); const Vec3vf<K> ray_org = ray.org; const Vec3vf<K> ray_dir = ray.dir; ray.org = xfmPoint(world2local, ray_org); ray.dir = xfmVector(world2local, ray_dir); IntersectContext newcontext((Scene*)instance->object, user_context); instance->object->intersectors.occluded(valid, ray, &newcontext); ray.org = ray_org; ray.dir = ray_dir; occluded = ray.tfar < 0.0f; instance_id_stack::pop(user_context); } return occluded; } template<int K> void InstanceIntersectorKMB<K>::intersect(const vbool<K>& valid_i, const Precalculations& pre, RayHitK<K>& ray, IntersectContext* context, const InstancePrimitive& prim) { vbool<K> valid = valid_i; const Instance* instance = prim.instance; /* perform ray mask test */ #if defined(EMBREE_RAY_MASK) valid &= (ray.mask & instance->mask) != 0; if (none(valid)) return; #endif RTCIntersectContext* user_context = context->user; if (likely(instance_id_stack::push(user_context, instance->geomID))) { AffineSpace3vf<K> world2local = instance->getWorld2Local<K>(valid, ray.time()); const Vec3vf<K> ray_org = ray.org; const Vec3vf<K> ray_dir = ray.dir; ray.org = xfmPoint(world2local, ray_org); ray.dir = xfmVector(world2local, ray_dir); IntersectContext newcontext((Scene*)instance->object, user_context); instance->object->intersectors.intersect(valid, ray, &newcontext); ray.org = ray_org; ray.dir = ray_dir; instance_id_stack::pop(user_context); } } template<int K> vbool<K> InstanceIntersectorKMB<K>::occluded(const vbool<K>& valid_i, const Precalculations& pre, RayK<K>& ray, IntersectContext* context, const InstancePrimitive& prim) { vbool<K> valid = valid_i; const Instance* instance = prim.instance; /* perform ray mask test */ #if defined(EMBREE_RAY_MASK) valid &= (ray.mask & instance->mask) != 0; if (none(valid)) return false; #endif RTCIntersectContext* user_context = context->user; vbool<K> occluded = false; if (likely(instance_id_stack::push(user_context, instance->geomID))) { AffineSpace3vf<K> world2local = instance->getWorld2Local<K>(valid, ray.time()); const Vec3vf<K> ray_org = ray.org; const Vec3vf<K> ray_dir = ray.dir; ray.org = xfmPoint(world2local, ray_org); ray.dir = xfmVector(world2local, ray_dir); IntersectContext newcontext((Scene*)instance->object, user_context); instance->object->intersectors.occluded(valid, ray, &newcontext); ray.org = ray_org; ray.dir = ray_dir; occluded = ray.tfar < 0.0f; instance_id_stack::pop(user_context); } return occluded; } #if defined(__SSE__) template struct InstanceIntersectorK<4>; template struct InstanceIntersectorKMB<4>; #endif #if defined(__AVX__) template struct InstanceIntersectorK<8>; template struct InstanceIntersectorKMB<8>; #endif #if defined(__AVX512F__) template struct InstanceIntersectorK<16>; template struct InstanceIntersectorKMB<16>; #endif } } <|endoftext|>
<commit_before>/* * File: log.cpp * $Revision$ * Last edited: $Date $ * Edited by: $Author $ * * Created by: Leonardo Uieda ([email protected]) * * Created on March 11, 2009, 6:40 PM * * Description: * Method implementations for the Log class. */ #include <time.h> #include "headers/log.h" /* FIELDS */ bool Log::started = false; std::vector<std::string>* Log::log = new std::vector<std::string>; /* CONSTRUCTORS AND DESTRUCTOR */ Log::Log() { } Log::~Log() { } /* METHODS */ void Log::start(const char *program_name) { /* ************************************************************************** * Starts the log for all instances of the Log class. Also marks the time when * this happened. If the log has already been started, this command will be * ingnored. **************************************************************************** */ if(Log::started == false) { /* Mark the date and time when the log started */ time_t rawtime; struct tm * timeinfo; time ( &rawtime ); timeinfo = localtime ( &rawtime ); /* Start the log with a nice header */ std::string msg; msg.assign("Hello! This is a log file for program "); msg.append(program_name); msg.append("."); Log::log->push_back(msg); msg.assign(asctime (timeinfo)); Log::log->push_back(msg); msg.assign(""); Log::log->push_back(msg); /* Mark that the log has started */ Log::started = true; } } bool Log::log_started() { /* ************************************************************************** * Returns true if the log was already started and false if it wasn't. **************************************************************************** */ return Log::started; } void Log::append(const char *new_msg) throw (LogNotStartedException) { /* ************************************************************************** * Skips a line and appends new_msg to the log. * Throws a LogNotStartedException if trying to do this before starting the log. **************************************************************************** */ if(Log::started == false) { LogNotStartedException e("append message to"); throw e; } std::string msg(new_msg); Log::log->push_back(msg); } void Log::print(FILE* log_file) throw (LogNotStartedException, InvalidLogFileException) { /* ************************************************************************** * Creates the file file_name and prints the log message to it. * Throws a LogNotStartedException if trying to do this before starting the log. * Throws a InvalidLogFileException when the FILE* passed is NULL. **************************************************************************** */ if(Log::started == false) { LogNotStartedException e("print"); throw e; } /* Check if the FILE* actually points to a file */ if(log_file == NULL) { InvalidLogFileException e; throw e; } /* Print the log to the file */ unsigned int l; /* Line counter */ for(l=0; l < Log::log->size(); l++) { fprintf(log_file, "%s\n", Log::log->at(l).c_str()); } } <commit_msg><commit_after>/* * File: log.cpp * $Revision$ * Last edited: $Date$ * Edited by: $Author$ * * Created by: Leonardo Uieda ([email protected]) * * Created on March 11, 2009, 6:40 PM * * Description: * Method implementations for the Log class. */ #include <time.h> #include "headers/log.h" /* FIELDS */ bool Log::started = false; std::vector<std::string>* Log::log = new std::vector<std::string>; /* CONSTRUCTORS AND DESTRUCTOR */ Log::Log() { } Log::~Log() { } /* METHODS */ void Log::start(const char *program_name) { /* ************************************************************************** * Starts the log for all instances of the Log class. Also marks the time when * this happened. If the log has already been started, this command will be * ingnored. **************************************************************************** */ if(Log::started == false) { /* Mark the date and time when the log started */ time_t rawtime; struct tm * timeinfo; time ( &rawtime ); timeinfo = localtime ( &rawtime ); /* Start the log with a nice header */ std::string msg; msg.assign("Hello! This is a log file for program "); msg.append(program_name); msg.append("."); Log::log->push_back(msg); msg.assign(asctime (timeinfo)); Log::log->push_back(msg); msg.assign(""); Log::log->push_back(msg); /* Mark that the log has started */ Log::started = true; } } bool Log::log_started() { /* ************************************************************************** * Returns true if the log was already started and false if it wasn't. **************************************************************************** */ return Log::started; } void Log::append(const char *new_msg) throw (LogNotStartedException) { /* ************************************************************************** * Skips a line and appends new_msg to the log. * Throws a LogNotStartedException if trying to do this before starting the log. **************************************************************************** */ if(Log::started == false) { LogNotStartedException e("append message to"); throw e; } std::string msg(new_msg); Log::log->push_back(msg); } void Log::print(FILE* log_file) throw (LogNotStartedException, InvalidLogFileException) { /* ************************************************************************** * Creates the file file_name and prints the log message to it. * Throws a LogNotStartedException if trying to do this before starting the log. * Throws a InvalidLogFileException when the FILE* passed is NULL. **************************************************************************** */ if(Log::started == false) { LogNotStartedException e("print"); throw e; } /* Check if the FILE* actually points to a file */ if(log_file == NULL) { InvalidLogFileException e; throw e; } /* Print the log to the file */ unsigned int l; /* Line counter */ for(l=0; l < Log::log->size(); l++) { fprintf(log_file, "%s\n", Log::log->at(l).c_str()); } } <|endoftext|>
<commit_before>/* ************************************************************************ * Copyright (c) 2018 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * ************************************************************************ */ #include "utility.hpp" #include <gtest/gtest.h> #include <stdexcept> /* ===================================================================== Main function: =================================================================== */ int main(int argc, char** argv) { // Print version char version[256]; query_version(version); printf("rocSPARSE version: %s\n", version); // Get device id from command line int device_id = 0; for(int i = 1; i < argc; ++i) { if(strcmp(argv[i], "--device") == 0 && argc > i + 1) { device_id = atoi(argv[i + 1]); } } // Device Query int device_count = query_device_property(); if(device_count <= device_id) { fprintf(stderr, "Error: invalid device ID. There may not be such device ID. Will exit\n"); return -1; } else { set_device(device_id); } ::testing::InitGoogleTest(&argc, argv); int ret = RUN_ALL_TESTS(); hipDeviceReset(); return ret; } <commit_msg>rearranged rocsparse version print<commit_after>/* ************************************************************************ * Copyright (c) 2018 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * ************************************************************************ */ #include "utility.hpp" #include <gtest/gtest.h> #include <stdexcept> /* ===================================================================== Main function: =================================================================== */ int main(int argc, char** argv) { // Get device id from command line int device_id = 0; for(int i = 1; i < argc; ++i) { if(strcmp(argv[i], "--device") == 0 && argc > i + 1) { device_id = atoi(argv[i + 1]); } } // Device Query int device_count = query_device_property(); if(device_count <= device_id) { fprintf(stderr, "Error: invalid device ID. There may not be such device ID. Will exit\n"); return -1; } else { set_device(device_id); } // Print version char version[256]; query_version(version); printf("rocSPARSE version: %s\n", version); ::testing::InitGoogleTest(&argc, argv); int ret = RUN_ALL_TESTS(); hipDeviceReset(); return ret; } <|endoftext|>
<commit_before>//===- ARMInstructionSelector.cpp ----------------------------*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This file implements the targeting of the InstructionSelector class for ARM. /// \todo This should be generated by TableGen. //===----------------------------------------------------------------------===// #include "ARMInstructionSelector.h" #include "ARMRegisterBankInfo.h" #include "ARMSubtarget.h" #include "ARMTargetMachine.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Support/Debug.h" #define DEBUG_TYPE "arm-isel" using namespace llvm; #ifndef LLVM_BUILD_GLOBAL_ISEL #error "You shouldn't build this" #endif ARMInstructionSelector::ARMInstructionSelector(const ARMSubtarget &STI, const ARMRegisterBankInfo &RBI) : InstructionSelector(), TII(*STI.getInstrInfo()), TRI(*STI.getRegisterInfo()), RBI(RBI) {} static bool selectCopy(MachineInstr &I, const TargetInstrInfo &TII, MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI) { unsigned DstReg = I.getOperand(0).getReg(); if (TargetRegisterInfo::isPhysicalRegister(DstReg)) return true; const RegisterBank *RegBank = RBI.getRegBank(DstReg, MRI, TRI); (void)RegBank; assert(RegBank && "Can't get reg bank for virtual register"); const unsigned DstSize = MRI.getType(DstReg).getSizeInBits(); (void)DstSize; unsigned SrcReg = I.getOperand(1).getReg(); const unsigned SrcSize = RBI.getSizeInBits(SrcReg, MRI, TRI); (void)SrcSize; assert((DstSize == SrcSize || // Copies are a means to setup initial types, the number of // bits may not exactly match. (TargetRegisterInfo::isPhysicalRegister(SrcReg) && DstSize <= SrcSize)) && "Copy with different width?!"); assert((RegBank->getID() == ARM::GPRRegBankID || RegBank->getID() == ARM::FPRRegBankID) && "Unsupported reg bank"); const TargetRegisterClass *RC = &ARM::GPRRegClass; if (RegBank->getID() == ARM::FPRRegBankID) { if (DstSize == 32) RC = &ARM::SPRRegClass; else if (DstSize == 64) RC = &ARM::DPRRegClass; else llvm_unreachable("Unsupported destination size"); } // No need to constrain SrcReg. It will get constrained when // we hit another of its uses or its defs. // Copies do not have constraints. if (!RBI.constrainGenericRegister(DstReg, *RC, MRI)) { DEBUG(dbgs() << "Failed to constrain " << TII.getName(I.getOpcode()) << " operand\n"); return false; } return true; } static bool selectFAdd(MachineInstrBuilder &MIB, const ARMBaseInstrInfo &TII, MachineRegisterInfo &MRI) { assert(TII.getSubtarget().hasVFP2() && "Can't select fp add without vfp"); LLT Ty = MRI.getType(MIB->getOperand(0).getReg()); unsigned ValSize = Ty.getSizeInBits(); if (ValSize == 32) { if (TII.getSubtarget().useNEONForSinglePrecisionFP()) return false; MIB->setDesc(TII.get(ARM::VADDS)); } else { assert(ValSize == 64 && "Unsupported size for floating point value"); if (TII.getSubtarget().isFPOnlySP()) return false; MIB->setDesc(TII.get(ARM::VADDD)); } MIB.add(predOps(ARMCC::AL)); return true; } static bool selectSequence(MachineInstrBuilder &MIB, const ARMBaseInstrInfo &TII, MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI) { assert(TII.getSubtarget().hasVFP2() && "Can't select sequence without VFP"); // We only support G_SEQUENCE as a way to stick together two scalar GPRs // into one DPR. unsigned VReg0 = MIB->getOperand(0).getReg(); (void)VReg0; assert(MRI.getType(VReg0).getSizeInBits() == 64 && RBI.getRegBank(VReg0, MRI, TRI)->getID() == ARM::FPRRegBankID && "Unsupported operand for G_SEQUENCE"); unsigned VReg1 = MIB->getOperand(1).getReg(); (void)VReg1; assert(MRI.getType(VReg1).getSizeInBits() == 32 && RBI.getRegBank(VReg1, MRI, TRI)->getID() == ARM::GPRRegBankID && "Unsupported operand for G_SEQUENCE"); unsigned VReg2 = MIB->getOperand(3).getReg(); (void)VReg2; assert(MRI.getType(VReg2).getSizeInBits() == 32 && RBI.getRegBank(VReg2, MRI, TRI)->getID() == ARM::GPRRegBankID && "Unsupported operand for G_SEQUENCE"); // Remove the operands corresponding to the offsets. MIB->RemoveOperand(4); MIB->RemoveOperand(2); MIB->setDesc(TII.get(ARM::VMOVDRR)); MIB.add(predOps(ARMCC::AL)); return true; } static bool selectExtract(MachineInstrBuilder &MIB, const ARMBaseInstrInfo &TII, MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI) { assert(TII.getSubtarget().hasVFP2() && "Can't select extract without VFP"); // We only support G_EXTRACT as a way to break up one DPR into two GPRs. unsigned VReg0 = MIB->getOperand(0).getReg(); (void)VReg0; assert(MRI.getType(VReg0).getSizeInBits() == 32 && RBI.getRegBank(VReg0, MRI, TRI)->getID() == ARM::GPRRegBankID && "Unsupported operand for G_SEQUENCE"); unsigned VReg1 = MIB->getOperand(1).getReg(); (void)VReg1; assert(MRI.getType(VReg1).getSizeInBits() == 32 && RBI.getRegBank(VReg1, MRI, TRI)->getID() == ARM::GPRRegBankID && "Unsupported operand for G_SEQUENCE"); unsigned VReg2 = MIB->getOperand(2).getReg(); (void)VReg2; assert(MRI.getType(VReg2).getSizeInBits() == 64 && RBI.getRegBank(VReg2, MRI, TRI)->getID() == ARM::FPRRegBankID && "Unsupported operand for G_SEQUENCE"); // Remove the operands corresponding to the offsets. MIB->RemoveOperand(4); MIB->RemoveOperand(3); MIB->setDesc(TII.get(ARM::VMOVRRD)); MIB.add(predOps(ARMCC::AL)); return true; } /// Select the opcode for simple extensions (that translate to a single SXT/UXT /// instruction). Extension operations more complicated than that should not /// invoke this. static unsigned selectSimpleExtOpc(unsigned Opc, unsigned Size) { using namespace TargetOpcode; assert((Size == 8 || Size == 16) && "Unsupported size"); if (Opc == G_SEXT) return Size == 8 ? ARM::SXTB : ARM::SXTH; if (Opc == G_ZEXT) return Size == 8 ? ARM::UXTB : ARM::UXTH; llvm_unreachable("Unsupported opcode"); } /// Select the opcode for simple loads. For types smaller than 32 bits, the /// value will be zero extended. static unsigned selectLoadOpCode(unsigned RegBank, unsigned Size) { if (RegBank == ARM::GPRRegBankID) { switch (Size) { case 1: case 8: return ARM::LDRBi12; case 16: return ARM::LDRH; case 32: return ARM::LDRi12; } llvm_unreachable("Unsupported size"); } assert(RegBank == ARM::FPRRegBankID && "Unsupported register bank"); switch (Size) { case 32: return ARM::VLDRS; case 64: return ARM::VLDRD; } llvm_unreachable("Unsupported size"); } bool ARMInstructionSelector::select(MachineInstr &I) const { assert(I.getParent() && "Instruction should be in a basic block!"); assert(I.getParent()->getParent() && "Instruction should be in a function!"); auto &MBB = *I.getParent(); auto &MF = *MBB.getParent(); auto &MRI = MF.getRegInfo(); if (!isPreISelGenericOpcode(I.getOpcode())) { if (I.isCopy()) return selectCopy(I, TII, MRI, TRI, RBI); return true; } MachineInstrBuilder MIB{MF, I}; bool isSExt = false; using namespace TargetOpcode; switch (I.getOpcode()) { case G_SEXT: isSExt = true; LLVM_FALLTHROUGH; case G_ZEXT: { LLT DstTy = MRI.getType(I.getOperand(0).getReg()); // FIXME: Smaller destination sizes coming soon! if (DstTy.getSizeInBits() != 32) { DEBUG(dbgs() << "Unsupported destination size for extension"); return false; } LLT SrcTy = MRI.getType(I.getOperand(1).getReg()); unsigned SrcSize = SrcTy.getSizeInBits(); switch (SrcSize) { case 1: { // ZExt boils down to & 0x1; for SExt we also subtract that from 0 I.setDesc(TII.get(ARM::ANDri)); MIB.addImm(1).add(predOps(ARMCC::AL)).add(condCodeOp()); if (isSExt) { unsigned SExtResult = I.getOperand(0).getReg(); // Use a new virtual register for the result of the AND unsigned AndResult = MRI.createVirtualRegister(&ARM::GPRRegClass); I.getOperand(0).setReg(AndResult); auto InsertBefore = std::next(I.getIterator()); auto SubI = BuildMI(MBB, InsertBefore, I.getDebugLoc(), TII.get(ARM::RSBri)) .addDef(SExtResult) .addUse(AndResult) .addImm(0) .add(predOps(ARMCC::AL)) .add(condCodeOp()); if (!constrainSelectedInstRegOperands(*SubI, TII, TRI, RBI)) return false; } break; } case 8: case 16: { unsigned NewOpc = selectSimpleExtOpc(I.getOpcode(), SrcSize); I.setDesc(TII.get(NewOpc)); MIB.addImm(0).add(predOps(ARMCC::AL)); break; } default: DEBUG(dbgs() << "Unsupported source size for extension"); return false; } break; } case G_ADD: I.setDesc(TII.get(ARM::ADDrr)); MIB.add(predOps(ARMCC::AL)).add(condCodeOp()); break; case G_FADD: if (!selectFAdd(MIB, TII, MRI)) return false; break; case G_FRAME_INDEX: // Add 0 to the given frame index and hope it will eventually be folded into // the user(s). I.setDesc(TII.get(ARM::ADDri)); MIB.addImm(0).add(predOps(ARMCC::AL)).add(condCodeOp()); break; case G_LOAD: { unsigned Reg = I.getOperand(0).getReg(); unsigned RegBank = RBI.getRegBank(Reg, MRI, TRI)->getID(); LLT ValTy = MRI.getType(Reg); const auto ValSize = ValTy.getSizeInBits(); if (ValSize != 64 && ValSize != 32 && ValSize != 16 && ValSize != 8 && ValSize != 1) return false; assert((ValSize != 64 || RegBank == ARM::FPRRegBankID) && "64-bit values should live in the FPR"); assert((ValSize != 64 || TII.getSubtarget().hasVFP2()) && "Don't know how to load 64-bit value without VFP"); const auto NewOpc = selectLoadOpCode(RegBank, ValSize); I.setDesc(TII.get(NewOpc)); if (NewOpc == ARM::LDRH) // LDRH has a funny addressing mode (there's already a FIXME for it). MIB.addReg(0); MIB.addImm(0).add(predOps(ARMCC::AL)); break; } case G_SEQUENCE: { if (!selectSequence(MIB, TII, MRI, TRI, RBI)) return false; break; } case G_EXTRACT: { if (!selectExtract(MIB, TII, MRI, TRI, RBI)) return false; break; } default: return false; } return constrainSelectedInstRegOperands(I, TII, TRI, RBI); } <commit_msg>[ARM] GlobalISel: Clean up some helpers<commit_after>//===- ARMInstructionSelector.cpp ----------------------------*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This file implements the targeting of the InstructionSelector class for ARM. /// \todo This should be generated by TableGen. //===----------------------------------------------------------------------===// #include "ARMInstructionSelector.h" #include "ARMRegisterBankInfo.h" #include "ARMSubtarget.h" #include "ARMTargetMachine.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Support/Debug.h" #define DEBUG_TYPE "arm-isel" using namespace llvm; #ifndef LLVM_BUILD_GLOBAL_ISEL #error "You shouldn't build this" #endif ARMInstructionSelector::ARMInstructionSelector(const ARMSubtarget &STI, const ARMRegisterBankInfo &RBI) : InstructionSelector(), TII(*STI.getInstrInfo()), TRI(*STI.getRegisterInfo()), RBI(RBI) {} static bool selectCopy(MachineInstr &I, const TargetInstrInfo &TII, MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI) { unsigned DstReg = I.getOperand(0).getReg(); if (TargetRegisterInfo::isPhysicalRegister(DstReg)) return true; const RegisterBank *RegBank = RBI.getRegBank(DstReg, MRI, TRI); (void)RegBank; assert(RegBank && "Can't get reg bank for virtual register"); const unsigned DstSize = MRI.getType(DstReg).getSizeInBits(); (void)DstSize; unsigned SrcReg = I.getOperand(1).getReg(); const unsigned SrcSize = RBI.getSizeInBits(SrcReg, MRI, TRI); (void)SrcSize; assert((DstSize == SrcSize || // Copies are a means to setup initial types, the number of // bits may not exactly match. (TargetRegisterInfo::isPhysicalRegister(SrcReg) && DstSize <= SrcSize)) && "Copy with different width?!"); assert((RegBank->getID() == ARM::GPRRegBankID || RegBank->getID() == ARM::FPRRegBankID) && "Unsupported reg bank"); const TargetRegisterClass *RC = &ARM::GPRRegClass; if (RegBank->getID() == ARM::FPRRegBankID) { if (DstSize == 32) RC = &ARM::SPRRegClass; else if (DstSize == 64) RC = &ARM::DPRRegClass; else llvm_unreachable("Unsupported destination size"); } // No need to constrain SrcReg. It will get constrained when // we hit another of its uses or its defs. // Copies do not have constraints. if (!RBI.constrainGenericRegister(DstReg, *RC, MRI)) { DEBUG(dbgs() << "Failed to constrain " << TII.getName(I.getOpcode()) << " operand\n"); return false; } return true; } static bool selectFAdd(MachineInstrBuilder &MIB, const ARMBaseInstrInfo &TII, MachineRegisterInfo &MRI) { assert(TII.getSubtarget().hasVFP2() && "Can't select fp add without vfp"); LLT Ty = MRI.getType(MIB->getOperand(0).getReg()); unsigned ValSize = Ty.getSizeInBits(); if (ValSize == 32) { if (TII.getSubtarget().useNEONForSinglePrecisionFP()) return false; MIB->setDesc(TII.get(ARM::VADDS)); } else { assert(ValSize == 64 && "Unsupported size for floating point value"); if (TII.getSubtarget().isFPOnlySP()) return false; MIB->setDesc(TII.get(ARM::VADDD)); } MIB.add(predOps(ARMCC::AL)); return true; } static bool selectSequence(MachineInstrBuilder &MIB, const ARMBaseInstrInfo &TII, MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI) { assert(TII.getSubtarget().hasVFP2() && "Can't select sequence without VFP"); // We only support G_SEQUENCE as a way to stick together two scalar GPRs // into one DPR. unsigned VReg0 = MIB->getOperand(0).getReg(); (void)VReg0; assert(MRI.getType(VReg0).getSizeInBits() == 64 && RBI.getRegBank(VReg0, MRI, TRI)->getID() == ARM::FPRRegBankID && "Unsupported operand for G_SEQUENCE"); unsigned VReg1 = MIB->getOperand(1).getReg(); (void)VReg1; assert(MRI.getType(VReg1).getSizeInBits() == 32 && RBI.getRegBank(VReg1, MRI, TRI)->getID() == ARM::GPRRegBankID && "Unsupported operand for G_SEQUENCE"); unsigned VReg2 = MIB->getOperand(3).getReg(); (void)VReg2; assert(MRI.getType(VReg2).getSizeInBits() == 32 && RBI.getRegBank(VReg2, MRI, TRI)->getID() == ARM::GPRRegBankID && "Unsupported operand for G_SEQUENCE"); // Remove the operands corresponding to the offsets. MIB->RemoveOperand(4); MIB->RemoveOperand(2); MIB->setDesc(TII.get(ARM::VMOVDRR)); MIB.add(predOps(ARMCC::AL)); return true; } static bool selectExtract(MachineInstrBuilder &MIB, const ARMBaseInstrInfo &TII, MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI) { assert(TII.getSubtarget().hasVFP2() && "Can't select extract without VFP"); // We only support G_EXTRACT as a way to break up one DPR into two GPRs. unsigned VReg0 = MIB->getOperand(0).getReg(); (void)VReg0; assert(MRI.getType(VReg0).getSizeInBits() == 32 && RBI.getRegBank(VReg0, MRI, TRI)->getID() == ARM::GPRRegBankID && "Unsupported operand for G_SEQUENCE"); unsigned VReg1 = MIB->getOperand(1).getReg(); (void)VReg1; assert(MRI.getType(VReg1).getSizeInBits() == 32 && RBI.getRegBank(VReg1, MRI, TRI)->getID() == ARM::GPRRegBankID && "Unsupported operand for G_SEQUENCE"); unsigned VReg2 = MIB->getOperand(2).getReg(); (void)VReg2; assert(MRI.getType(VReg2).getSizeInBits() == 64 && RBI.getRegBank(VReg2, MRI, TRI)->getID() == ARM::FPRRegBankID && "Unsupported operand for G_SEQUENCE"); // Remove the operands corresponding to the offsets. MIB->RemoveOperand(4); MIB->RemoveOperand(3); MIB->setDesc(TII.get(ARM::VMOVRRD)); MIB.add(predOps(ARMCC::AL)); return true; } /// Select the opcode for simple extensions (that translate to a single SXT/UXT /// instruction). Extension operations more complicated than that should not /// invoke this. Returns the original opcode if it doesn't know how to select a /// better one. static unsigned selectSimpleExtOpc(unsigned Opc, unsigned Size) { using namespace TargetOpcode; if (Size != 8 && Size != 16) return Opc; if (Opc == G_SEXT) return Size == 8 ? ARM::SXTB : ARM::SXTH; if (Opc == G_ZEXT) return Size == 8 ? ARM::UXTB : ARM::UXTH; return Opc; } /// Select the opcode for simple loads. For types smaller than 32 bits, the /// value will be zero extended. Returns G_LOAD if it doesn't know how to select /// an opcode. static unsigned selectLoadOpCode(unsigned RegBank, unsigned Size) { if (RegBank == ARM::GPRRegBankID) { switch (Size) { case 1: case 8: return ARM::LDRBi12; case 16: return ARM::LDRH; case 32: return ARM::LDRi12; default: return TargetOpcode::G_LOAD; } } if (RegBank == ARM::FPRRegBankID) { switch (Size) { case 32: return ARM::VLDRS; case 64: return ARM::VLDRD; default: return TargetOpcode::G_LOAD; } } return TargetOpcode::G_LOAD; } bool ARMInstructionSelector::select(MachineInstr &I) const { assert(I.getParent() && "Instruction should be in a basic block!"); assert(I.getParent()->getParent() && "Instruction should be in a function!"); auto &MBB = *I.getParent(); auto &MF = *MBB.getParent(); auto &MRI = MF.getRegInfo(); if (!isPreISelGenericOpcode(I.getOpcode())) { if (I.isCopy()) return selectCopy(I, TII, MRI, TRI, RBI); return true; } MachineInstrBuilder MIB{MF, I}; bool isSExt = false; using namespace TargetOpcode; switch (I.getOpcode()) { case G_SEXT: isSExt = true; LLVM_FALLTHROUGH; case G_ZEXT: { LLT DstTy = MRI.getType(I.getOperand(0).getReg()); // FIXME: Smaller destination sizes coming soon! if (DstTy.getSizeInBits() != 32) { DEBUG(dbgs() << "Unsupported destination size for extension"); return false; } LLT SrcTy = MRI.getType(I.getOperand(1).getReg()); unsigned SrcSize = SrcTy.getSizeInBits(); switch (SrcSize) { case 1: { // ZExt boils down to & 0x1; for SExt we also subtract that from 0 I.setDesc(TII.get(ARM::ANDri)); MIB.addImm(1).add(predOps(ARMCC::AL)).add(condCodeOp()); if (isSExt) { unsigned SExtResult = I.getOperand(0).getReg(); // Use a new virtual register for the result of the AND unsigned AndResult = MRI.createVirtualRegister(&ARM::GPRRegClass); I.getOperand(0).setReg(AndResult); auto InsertBefore = std::next(I.getIterator()); auto SubI = BuildMI(MBB, InsertBefore, I.getDebugLoc(), TII.get(ARM::RSBri)) .addDef(SExtResult) .addUse(AndResult) .addImm(0) .add(predOps(ARMCC::AL)) .add(condCodeOp()); if (!constrainSelectedInstRegOperands(*SubI, TII, TRI, RBI)) return false; } break; } case 8: case 16: { unsigned NewOpc = selectSimpleExtOpc(I.getOpcode(), SrcSize); if (NewOpc == I.getOpcode()) return false; I.setDesc(TII.get(NewOpc)); MIB.addImm(0).add(predOps(ARMCC::AL)); break; } default: DEBUG(dbgs() << "Unsupported source size for extension"); return false; } break; } case G_ADD: I.setDesc(TII.get(ARM::ADDrr)); MIB.add(predOps(ARMCC::AL)).add(condCodeOp()); break; case G_FADD: if (!selectFAdd(MIB, TII, MRI)) return false; break; case G_FRAME_INDEX: // Add 0 to the given frame index and hope it will eventually be folded into // the user(s). I.setDesc(TII.get(ARM::ADDri)); MIB.addImm(0).add(predOps(ARMCC::AL)).add(condCodeOp()); break; case G_LOAD: { unsigned Reg = I.getOperand(0).getReg(); unsigned RegBank = RBI.getRegBank(Reg, MRI, TRI)->getID(); LLT ValTy = MRI.getType(Reg); const auto ValSize = ValTy.getSizeInBits(); assert((ValSize != 64 || TII.getSubtarget().hasVFP2()) && "Don't know how to load 64-bit value without VFP"); const auto NewOpc = selectLoadOpCode(RegBank, ValSize); if (NewOpc == G_LOAD) return false; I.setDesc(TII.get(NewOpc)); if (NewOpc == ARM::LDRH) // LDRH has a funny addressing mode (there's already a FIXME for it). MIB.addReg(0); MIB.addImm(0).add(predOps(ARMCC::AL)); break; } case G_SEQUENCE: { if (!selectSequence(MIB, TII, MRI, TRI, RBI)) return false; break; } case G_EXTRACT: { if (!selectExtract(MIB, TII, MRI, TRI, RBI)) return false; break; } default: return false; } return constrainSelectedInstRegOperands(I, TII, TRI, RBI); } <|endoftext|>
<commit_before>/*============================================================================= Copyright (c) 2012-2013 Richard Otis Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ // definition for Equilibrium constructor and helper functions #include "libgibbs/include/libgibbs_pch.hpp" #include "libgibbs/include/equilibrium.hpp" #include "libtdb/include/database.hpp" #include "libtdb/include/structure.hpp" #include "libtdb/include/exceptions.hpp" #include "libtdb/include/conditions.hpp" #include "libtdb/include/utils/enum_handling.hpp" #include "libtdb/include/logging.hpp" #include "libgibbs/include/optimizer/opt_Gibbs.hpp" #include "external/coin/IpIpoptApplication.hpp" #include "external/coin/IpSolveStatistics.hpp" #include <iostream> #include <fstream> #include <algorithm> #include <sstream> #include <boost/io/ios_state.hpp> using namespace Ipopt; Equilibrium::Equilibrium(const Database &DB, const evalconditions &conds, boost::shared_ptr<IpoptApplication> solver) : sourcename(DB.get_info()), conditions(conds) { logger opt_log(journal::keywords::channel = "optimizer"); Phase_Collection phase_col; for (auto i = DB.get_phase_iterator(); i != DB.get_phase_iterator_end(); ++i) { if (conds.phases.find(i->first) != conds.phases.end()) { if (conds.phases.at(i->first) == PhaseStatus::ENTERED) phase_col[i->first] = i->second; } } const Phase_Collection::const_iterator phase_iter = phase_col.cbegin(); const Phase_Collection::const_iterator phase_end = phase_col.cend(); // TODO: check validity of conditions timer.start(); // Create NLP SmartPtr<TNLP> mynlp = new GibbsOpt(DB, conds); ApplicationReturnStatus status; status = solver->OptimizeTNLP(mynlp); timer.stop(); if (status == Solve_Succeeded || status == Solved_To_Acceptable_Level) { iter_count = solver->Statistics()->IterationCount(); Number final_obj = solver->Statistics()->FinalObjective(); mingibbs = final_obj * conds.statevars.find('N')->second; /* The dynamic_cast allows us to use the get_phase_map() function. * It is not exposed by the TNLP base class. */ GibbsOpt* opt_ptr = dynamic_cast<GibbsOpt*> (Ipopt::GetRawPtr(mynlp)); if (!opt_ptr) { BOOST_LOG_SEV(opt_log, routine) << "Internal memory error from dynamic_cast<GibbsOpt*>"; BOOST_THROW_EXCEPTION(equilibrium_error() << str_errinfo("Internal memory error") << specific_errinfo("dynamic_cast<GibbsOpt*>")); } ph_map = opt_ptr->get_phase_map(); } else { BOOST_LOG_SEV(opt_log, routine) << "Failed to construct Equilibrium object" << std::endl; BOOST_THROW_EXCEPTION(equilibrium_error() << str_errinfo("Solver failed to find equilibrium")); } } double Equilibrium::GibbsEnergy() { return mingibbs; } std::string Equilibrium::print() const { std::stringstream stream; boost::io::ios_flags_saver ifs( stream ); // preserve original state of the stream once we leave scope stream << "Output from LIBGIBBS, equilibrium number = ??" << std::endl; std::string walltime = boost::timer::format(timer.elapsed(), 3, "%w"); stream << "Solved in " << iter_count << " iterations (" << walltime << "secs)" << std::endl; stream << "Conditions:" << std::endl; // We want the individual phase information to appear AFTER // the global system data, but the most efficient ordering // requires us to iterate through all phases first. // The simple solution is to save the output to a temporary // buffer, and then flush it to the output stream later. std::stringstream temp_buf; temp_buf << std::scientific; const auto sv_end = conditions.statevars.cend(); const auto xf_end = conditions.xfrac.cend(); for (auto i = conditions.xfrac.cbegin(); i !=xf_end; ++i) { stream << "X(" << i->first << ")=" << i->second << ", "; } for (auto i = conditions.statevars.cbegin(); i != sv_end; ++i) { stream << i->first << "=" << i->second; // if this isn't the last one, add a comma if (std::distance(i,sv_end) != 1) stream << ", "; } stream << std::endl; // should be c + 2 - conditions, where c is the number of components size_t dof = conditions.elements.size() + 2 - (conditions.xfrac.size()+1) - conditions.statevars.size(); stream << "DEGREES OF FREEDOM " << dof << std::endl; stream << std::endl; double T,P,N; T = conditions.statevars.find('T')->second; P = conditions.statevars.find('P')->second; N = conditions.statevars.find('N')->second; stream << "Temperature " << T << " K (" << (T-273.15) << " C), " << "Pressure " << P << " Pa" << std::endl; stream << std::scientific; // switch to scientific notation for doubles stream << "Number of moles of components " << N << ", Mass ????" << std::endl; stream << "Total Gibbs energy " << mingibbs << " Enthalpy ???? " << "Volume ????" << std::endl; stream << std::endl; const auto ph_end = ph_map.cend(); const auto cond_spec_begin = conditions.elements.cbegin(); const auto cond_spec_end = conditions.elements.cend(); // double/double pair is for separate storage of numerator/denominator pieces of fraction std::map<std::string,std::pair<double,double>> global_comp; for (auto i = ph_map.cbegin(); i != ph_end; ++i) { const auto subl_begin = i->second.second.cbegin(); const auto subl_end = i->second.second.cend(); const double phasefrac = i->second.first; auto statfind = conditions.phases.find(i->first); std::map<std::string,std::pair<double,double>> phase_comp; temp_buf << i->first << "\tStatus " << enumToString(statfind->second) << " Driving force ????" << std::endl; // phase name temp_buf << "Number of moles " << i->second.first * N << ", Mass ???? "; temp_buf << "Mole fractions:" << std::endl; for (auto j = subl_begin; j != subl_end; ++j) { const double stoi_coef = j->first; const double den = stoi_coef; const auto spec_begin = j->second.cbegin(); const auto spec_end = j->second.cend(); const auto vacancy_iterator = (j->second).find("VA"); // this may equal spec_end /* * To make sure all mole fractions sum to 1, * we have to normalize everything using the same * sublattices. That means even species which don't * appear in a given sublattice need to have that * sublattice's coefficient appear in its denominator. * To accomplish this task, we perform two loops in each sublattice: * 1) all species (except VA), to add to the denominator * 2) only species in that sublattice, to add to the numerator * With this method, all mole fractions will sum properly. */ for (auto k = cond_spec_begin; k != cond_spec_end; ++k) { if (*k == "VA") continue; // vacancies don't contribute to mole fractions if (vacancy_iterator != spec_end) { phase_comp[*k].second += den * (1 - vacancy_iterator->second); } else { phase_comp[*k].second += den; } } for (auto k = spec_begin; k != spec_end; ++k) { if (k->first == "VA") continue; // vacancies don't contribute to mole fractions double num = k->second * stoi_coef; phase_comp[k->first].first += num; } } /* We've summed up over all sublattices in this phase. * Now add this phase's contribution to the overall composition. */ for (auto j = cond_spec_begin; j != cond_spec_end; ++j) { if (*j == "VA") continue; // vacancies don't contribute to mole fractions global_comp[*j].first += phasefrac * (phase_comp[*j].first / phase_comp[*j].second); global_comp[*j].second += phasefrac; } const auto cmp_begin = phase_comp.cbegin(); const auto cmp_end = phase_comp.cend(); for (auto g = cmp_begin; g != cmp_end; ++g) { temp_buf << g->first << " " << (g->second.first / g->second.second) << " "; } temp_buf << std::endl << "Constitution:" << std::endl; for (auto j = subl_begin; j != subl_end; ++j) { double stoi_coef = j->first; temp_buf << "Sublattice " << std::distance(subl_begin,j)+1 << ", Number of sites " << stoi_coef << std::endl; const auto spec_begin = j->second.cbegin(); const auto spec_end = j->second.cend(); for (auto k = spec_begin; k != spec_end; ++k) { temp_buf << k->first << " " << k->second << " "; } temp_buf << std::endl; } // if we're at the last phase, don't add an extra newline if (std::distance(i,ph_end) != 1) temp_buf << std::endl; } const auto glob_begin = global_comp.cbegin(); const auto glob_end = global_comp.cend(); stream << "Component\tMoles\tW-Fraction\tActivity\tPotential\tRef.state" << std::endl; for (auto h = glob_begin; h != glob_end; ++h) { double molefrac = h->second.first / h->second.second; stream << h->first << "\t" << molefrac * N << "\t????\t????\t" << "??" << "\tSER" << std::endl; } stream << std::endl; stream << temp_buf.rdbuf(); // include the temporary buffer with all the phase data return (const std::string)stream.str(); } <commit_msg>Change to M-Fraction<commit_after>/*============================================================================= Copyright (c) 2012-2013 Richard Otis Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ // definition for Equilibrium constructor and helper functions #include "libgibbs/include/libgibbs_pch.hpp" #include "libgibbs/include/equilibrium.hpp" #include "libtdb/include/database.hpp" #include "libtdb/include/structure.hpp" #include "libtdb/include/exceptions.hpp" #include "libtdb/include/conditions.hpp" #include "libtdb/include/utils/enum_handling.hpp" #include "libtdb/include/logging.hpp" #include "libgibbs/include/optimizer/opt_Gibbs.hpp" #include "external/coin/IpIpoptApplication.hpp" #include "external/coin/IpSolveStatistics.hpp" #include <iostream> #include <fstream> #include <algorithm> #include <sstream> #include <boost/io/ios_state.hpp> using namespace Ipopt; Equilibrium::Equilibrium(const Database &DB, const evalconditions &conds, boost::shared_ptr<IpoptApplication> solver) : sourcename(DB.get_info()), conditions(conds) { logger opt_log(journal::keywords::channel = "optimizer"); Phase_Collection phase_col; for (auto i = DB.get_phase_iterator(); i != DB.get_phase_iterator_end(); ++i) { if (conds.phases.find(i->first) != conds.phases.end()) { if (conds.phases.at(i->first) == PhaseStatus::ENTERED) phase_col[i->first] = i->second; } } const Phase_Collection::const_iterator phase_iter = phase_col.cbegin(); const Phase_Collection::const_iterator phase_end = phase_col.cend(); // TODO: check validity of conditions timer.start(); // Create NLP SmartPtr<TNLP> mynlp = new GibbsOpt(DB, conds); ApplicationReturnStatus status; status = solver->OptimizeTNLP(mynlp); timer.stop(); if (status == Solve_Succeeded || status == Solved_To_Acceptable_Level) { iter_count = solver->Statistics()->IterationCount(); Number final_obj = solver->Statistics()->FinalObjective(); mingibbs = final_obj * conds.statevars.find('N')->second; /* The dynamic_cast allows us to use the get_phase_map() function. * It is not exposed by the TNLP base class. */ GibbsOpt* opt_ptr = dynamic_cast<GibbsOpt*> (Ipopt::GetRawPtr(mynlp)); if (!opt_ptr) { BOOST_LOG_SEV(opt_log, routine) << "Internal memory error from dynamic_cast<GibbsOpt*>"; BOOST_THROW_EXCEPTION(equilibrium_error() << str_errinfo("Internal memory error") << specific_errinfo("dynamic_cast<GibbsOpt*>")); } ph_map = opt_ptr->get_phase_map(); } else { BOOST_LOG_SEV(opt_log, routine) << "Failed to construct Equilibrium object" << std::endl; BOOST_THROW_EXCEPTION(equilibrium_error() << str_errinfo("Solver failed to find equilibrium")); } } double Equilibrium::GibbsEnergy() { return mingibbs; } std::string Equilibrium::print() const { std::stringstream stream; boost::io::ios_flags_saver ifs( stream ); // preserve original state of the stream once we leave scope stream << "Output from LIBGIBBS, equilibrium number = ??" << std::endl; std::string walltime = boost::timer::format(timer.elapsed(), 3, "%w"); stream << "Solved in " << iter_count << " iterations (" << walltime << "secs)" << std::endl; stream << "Conditions:" << std::endl; // We want the individual phase information to appear AFTER // the global system data, but the most efficient ordering // requires us to iterate through all phases first. // The simple solution is to save the output to a temporary // buffer, and then flush it to the output stream later. std::stringstream temp_buf; temp_buf << std::scientific; const auto sv_end = conditions.statevars.cend(); const auto xf_end = conditions.xfrac.cend(); for (auto i = conditions.xfrac.cbegin(); i !=xf_end; ++i) { stream << "X(" << i->first << ")=" << i->second << ", "; } for (auto i = conditions.statevars.cbegin(); i != sv_end; ++i) { stream << i->first << "=" << i->second; // if this isn't the last one, add a comma if (std::distance(i,sv_end) != 1) stream << ", "; } stream << std::endl; // should be c + 2 - conditions, where c is the number of components size_t dof = conditions.elements.size() + 2 - (conditions.xfrac.size()+1) - conditions.statevars.size(); stream << "DEGREES OF FREEDOM " << dof << std::endl; stream << std::endl; double T,P,N; T = conditions.statevars.find('T')->second; P = conditions.statevars.find('P')->second; N = conditions.statevars.find('N')->second; stream << "Temperature " << T << " K (" << (T-273.15) << " C), " << "Pressure " << P << " Pa" << std::endl; stream << std::scientific; // switch to scientific notation for doubles stream << "Number of moles of components " << N << ", Mass ????" << std::endl; stream << "Total Gibbs energy " << mingibbs << " Enthalpy ???? " << "Volume ????" << std::endl; stream << std::endl; const auto ph_end = ph_map.cend(); const auto cond_spec_begin = conditions.elements.cbegin(); const auto cond_spec_end = conditions.elements.cend(); // double/double pair is for separate storage of numerator/denominator pieces of fraction std::map<std::string,std::pair<double,double>> global_comp; for (auto i = ph_map.cbegin(); i != ph_end; ++i) { const auto subl_begin = i->second.second.cbegin(); const auto subl_end = i->second.second.cend(); const double phasefrac = i->second.first; auto statfind = conditions.phases.find(i->first); std::map<std::string,std::pair<double,double>> phase_comp; temp_buf << i->first << "\tStatus " << enumToString(statfind->second) << " Driving force ????" << std::endl; // phase name temp_buf << "Number of moles " << i->second.first * N << ", Mass ???? "; temp_buf << "Mole fractions:" << std::endl; for (auto j = subl_begin; j != subl_end; ++j) { const double stoi_coef = j->first; const double den = stoi_coef; const auto spec_begin = j->second.cbegin(); const auto spec_end = j->second.cend(); const auto vacancy_iterator = (j->second).find("VA"); // this may equal spec_end /* * To make sure all mole fractions sum to 1, * we have to normalize everything using the same * sublattices. That means even species which don't * appear in a given sublattice need to have that * sublattice's coefficient appear in its denominator. * To accomplish this task, we perform two loops in each sublattice: * 1) all species (except VA), to add to the denominator * 2) only species in that sublattice, to add to the numerator * With this method, all mole fractions will sum properly. */ for (auto k = cond_spec_begin; k != cond_spec_end; ++k) { if (*k == "VA") continue; // vacancies don't contribute to mole fractions if (vacancy_iterator != spec_end) { phase_comp[*k].second += den * (1 - vacancy_iterator->second); } else { phase_comp[*k].second += den; } } for (auto k = spec_begin; k != spec_end; ++k) { if (k->first == "VA") continue; // vacancies don't contribute to mole fractions double num = k->second * stoi_coef; phase_comp[k->first].first += num; } } /* We've summed up over all sublattices in this phase. * Now add this phase's contribution to the overall composition. */ for (auto j = cond_spec_begin; j != cond_spec_end; ++j) { if (*j == "VA") continue; // vacancies don't contribute to mole fractions global_comp[*j].first += phasefrac * (phase_comp[*j].first / phase_comp[*j].second); global_comp[*j].second += phasefrac; } const auto cmp_begin = phase_comp.cbegin(); const auto cmp_end = phase_comp.cend(); for (auto g = cmp_begin; g != cmp_end; ++g) { temp_buf << g->first << " " << (g->second.first / g->second.second) << " "; } temp_buf << std::endl << "Constitution:" << std::endl; for (auto j = subl_begin; j != subl_end; ++j) { double stoi_coef = j->first; temp_buf << "Sublattice " << std::distance(subl_begin,j)+1 << ", Number of sites " << stoi_coef << std::endl; const auto spec_begin = j->second.cbegin(); const auto spec_end = j->second.cend(); for (auto k = spec_begin; k != spec_end; ++k) { temp_buf << k->first << " " << k->second << " "; } temp_buf << std::endl; } // if we're at the last phase, don't add an extra newline if (std::distance(i,ph_end) != 1) temp_buf << std::endl; } const auto glob_begin = global_comp.cbegin(); const auto glob_end = global_comp.cend(); stream << "Component\tMoles\tM-Fraction\tActivity\tPotential\tRef.state" << std::endl; for (auto h = glob_begin; h != glob_end; ++h) { double molefrac = h->second.first / h->second.second; stream << h->first << "\t" << molefrac * N << "\t????\t????\t" << "??" << "\tSER" << std::endl; } stream << std::endl; stream << temp_buf.rdbuf(); // include the temporary buffer with all the phase data return (const std::string)stream.str(); } <|endoftext|>
<commit_before>/* LED bar library V2.0 Copyright (c) 2010 Seeed Technology Inc. Original Author: LG Modify: Loovee, 2014-2-26 User can choose which Io to be used. The MIT License (MIT) Copyright (c) 2013 Seeed Technology Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Grove_LED_Bar.h" Grove_LED_Bar::Grove_LED_Bar(unsigned char pinClock, unsigned char pinData, bool greenToRed) { __pinClock = pinClock; __pinData = pinData; __greenToRed = greenToRed; // ascending or decending for (byte i = 0; i < 10; i++) __state[i] = 0x00; // persist state so individual leds can be toggled pinMode(__pinClock, OUTPUT); pinMode(__pinData, OUTPUT); } // Send the latch command void Grove_LED_Bar::latchData() { digitalWrite(__pinData, LOW); delayMicroseconds(10); for (unsigned char i = 0; i < 4; i++) { digitalWrite(__pinData, HIGH); digitalWrite(__pinData, LOW); } } // Send 16 bits of data void Grove_LED_Bar::sendData(unsigned int data) { for (unsigned char i = 0; i < 16; i++) { unsigned int state = (data & 0x8000) ? HIGH : LOW; digitalWrite(__pinData, state); state = digitalRead(__pinClock) ? LOW : HIGH; digitalWrite(__pinClock, state); data <<= 1; } } // Change the orientation // Green to red, or red to green void Grove_LED_Bar::setGreenToRed(bool greenToRed) { __greenToRed = greenToRed; setData(__state); } // Set level (0-10) // Level 0 means all leds off // Level 10 means all leds on // Level 4.5 means 4 LEDs on and the 5th LED's half on void Grove_LED_Bar::setLevel(float level) { level = max(0, min(10, level)); level *= 8; // there are 8 (noticable) levels of brightness on each segment // Place number of 'level' of 1-bits on __state for (byte i = 0; i < 10; i++) { __state[i] = (level > 8) ? ~0 : (level > 0) ? ~(~0 << byte(level)) : 0; level -= 8; }; setData(__state); } // Set a single led // led (1-10) // brightness (0-1) void Grove_LED_Bar::setLed(unsigned char led, float brightness) { led = max(1, min(10, led)); brightness = max(0, min(brightness, 1)); // Zero based index 0-9 for bitwise operations led--; // 8 (noticable) levels of brightness // 00000000 darkest // 00000011 brighter // ........ // 11111111 brightest __state[led] = ~(~0 << (unsigned char) (brightness*8)); setData(__state); } // Toggle a single led // led (1-10) void Grove_LED_Bar::toggleLed(unsigned char led) { led = max(1, min(10, led)); // Zero based index 0-9 for bitwise operations led--; __state[led] = __state[led] ? 0 : ~0; setData(__state); } // each element in the state will hold the brightness level // 00000000 darkest // 00000011 brighter // ........ // 11111111 brightest void Grove_LED_Bar::setData(unsigned char __state[]) { sendData(GLB_CMDMODE); for (unsigned char i = 0; i < 10; i++) { if (__greenToRed) { // Go backward on __state sendData(__state[10-i-1]); } else { // Go forward on __state sendData(__state[i]); } } // Two extra empty bits for padding the command to the correct length sendData(0x00); sendData(0x00); latchData(); } void Grove_LED_Bar::setBits(unsigned int bits) { for (unsigned char i = 0; i < 10; i++) { if ((bits % 2) == 1) __state[i] = 0xFF; else __state[i] = 0x00; bits /= 2; } setData(__state); } // Return the current bits unsigned int const Grove_LED_Bar::getBits() { unsigned int __bits = 0x00; for (unsigned char i = 0; i < 10; i++) { if (__state[i] != 0x0) __bits |= (0x1 << i); } return __bits; } <commit_msg>Update Grove_LED_Bar.cpp<commit_after>/* LED bar library V2.0 Copyright (c) 2010 Seeed Technology Inc. Original Author: LG Modify: Loovee, 2014-2-26 User can choose which Io to be used. The MIT License (MIT) Copyright (c) 2013 Seeed Technology Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Grove_LED_Bar.h" Grove_LED_Bar::Grove_LED_Bar(unsigned char pinClock, unsigned char pinData, bool greenToRed) { __pinClock = pinClock; __pinData = pinData; __greenToRed = greenToRed; // ascending or decending for (byte i = 0; i < 10; i++) __state[i] = 0x00; // persist state so individual leds can be toggled pinMode(__pinClock, OUTPUT); pinMode(__pinData, OUTPUT); } // Send the latch command void Grove_LED_Bar::latchData() { digitalWrite(__pinData, LOW); delayMicroseconds(10); for (unsigned char i = 0; i < 4; i++) { digitalWrite(__pinData, HIGH); digitalWrite(__pinData, LOW); } } // Send 16 bits of data void Grove_LED_Bar::sendData(unsigned int data) { unisgned int state = 0; for (unsigned char i = 0; i < 16; i++) { unsigned int state1 = (data & 0x8000) ? HIGH : LOW; digitalWrite(__pinData, state1); //state = digitalRead(__pinClock) ? LOW : HIGH; state = 1-state; digitalWrite(__pinClock, state); data <<= 1; } } // Change the orientation // Green to red, or red to green void Grove_LED_Bar::setGreenToRed(bool greenToRed) { __greenToRed = greenToRed; setData(__state); } // Set level (0-10) // Level 0 means all leds off // Level 10 means all leds on // Level 4.5 means 4 LEDs on and the 5th LED's half on void Grove_LED_Bar::setLevel(float level) { level = max(0, min(10, level)); level *= 8; // there are 8 (noticable) levels of brightness on each segment // Place number of 'level' of 1-bits on __state for (byte i = 0; i < 10; i++) { __state[i] = (level > 8) ? ~0 : (level > 0) ? ~(~0 << byte(level)) : 0; level -= 8; }; setData(__state); } // Set a single led // led (1-10) // brightness (0-1) void Grove_LED_Bar::setLed(unsigned char led, float brightness) { led = max(1, min(10, led)); brightness = max(0, min(brightness, 1)); // Zero based index 0-9 for bitwise operations led--; // 8 (noticable) levels of brightness // 00000000 darkest // 00000011 brighter // ........ // 11111111 brightest __state[led] = ~(~0 << (unsigned char) (brightness*8)); setData(__state); } // Toggle a single led // led (1-10) void Grove_LED_Bar::toggleLed(unsigned char led) { led = max(1, min(10, led)); // Zero based index 0-9 for bitwise operations led--; __state[led] = __state[led] ? 0 : ~0; setData(__state); } // each element in the state will hold the brightness level // 00000000 darkest // 00000011 brighter // ........ // 11111111 brightest void Grove_LED_Bar::setData(unsigned char __state[]) { sendData(GLB_CMDMODE); for (unsigned char i = 0; i < 10; i++) { if (__greenToRed) { // Go backward on __state sendData(__state[10-i-1]); } else { // Go forward on __state sendData(__state[i]); } } // Two extra empty bits for padding the command to the correct length sendData(0x00); sendData(0x00); latchData(); } void Grove_LED_Bar::setBits(unsigned int bits) { for (unsigned char i = 0; i < 10; i++) { if ((bits % 2) == 1) __state[i] = 0xFF; else __state[i] = 0x00; bits /= 2; } setData(__state); } // Return the current bits unsigned int const Grove_LED_Bar::getBits() { unsigned int __bits = 0x00; for (unsigned char i = 0; i < 10; i++) { if (__state[i] != 0x0) __bits |= (0x1 << i); } return __bits; } <|endoftext|>
<commit_before>/* * qirois.cpp * * Copyright (c) 2016 Tobias Wood. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ #include <iostream> #include <fstream> #include <string> #include "QI/Types.h" #include "QI/Util.h" #include "QI/Option.h" #include "itkLabelGeometryImageFilter.h" typedef itk::LabelGeometryImageFilter<QI::VolumeI, QI::VolumeF> TLblGeoFilter; const std::string usage{ "Usage is: qirois [options] labelfile\n\ \n\ Calculates volumes of all ROI labels in a file. Uses itkLabelGeometryImageFilter\n" }; int main(int argc, char **argv) { Eigen::initParallel(); QI::OptionList opts(usage); QI::Option<std::string> label_list("",'l',"labels","Specify labels to search for", opts); QI::Switch print_labels('p',"print_labels","Print out label/ROI numbers first", opts); QI::Help help(opts); std::vector<std::string> nonopts = opts.parse(argc, argv); if (nonopts.size() != 1) { std::cerr << opts << std::endl; std::cerr << "No input filename specified." << std::endl; return EXIT_FAILURE; } QI::VolumeI::Pointer label_image = QI::ReadImage<QI::VolumeI>(nonopts[0]); double voxvol = label_image->GetSpacing()[0]; for (int i = 1; i < 3; i++) voxvol *= label_image->GetSpacing()[i]; TLblGeoFilter::Pointer label_filter = TLblGeoFilter::New(); label_filter->SetInput(label_image); label_filter->CalculatePixelIndicesOff(); label_filter->CalculateOrientedBoundingBoxOff(); label_filter->CalculateOrientedLabelRegionsOff(); label_filter->Update(); typename TLblGeoFilter::LabelsType labels; if (label_list.set()) { std::ifstream file(*label_list); std::string line; while (std::getline(file, line)) { std::stringstream linestream(line); int label; linestream >> label; labels.push_back(label); } } else { labels = label_filter->GetLabels(); std::sort(labels.begin(), labels.end()); } for(auto it = labels.begin(); it != labels.end(); it++) { if (*print_labels) std::cout << *it << ","; std::cout << (voxvol * label_filter->GetVolume(*it)) << std::endl; } return EXIT_SUCCESS; } <commit_msg>ENH: Added ignore zero option.<commit_after>/* * qirois.cpp * * Copyright (c) 2016 Tobias Wood. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ #include <iostream> #include <fstream> #include <string> #include "QI/Types.h" #include "QI/Util.h" #include "QI/Option.h" #include "itkLabelGeometryImageFilter.h" typedef itk::LabelGeometryImageFilter<QI::VolumeI, QI::VolumeF> TLblGeoFilter; const std::string usage{ "Usage is: qirois [options] labelfile\n\ \n\ Calculates volumes of all ROI labels in a file. Uses itkLabelGeometryImageFilter\n" }; int main(int argc, char **argv) { Eigen::initParallel(); QI::OptionList opts(usage); QI::Option<std::string> label_list("",'l',"labels","Specify labels to search for", opts); QI::Switch ignore_zero('z',"ignore_zero","Ignore 0 labels (background)", opts); QI::Switch print_labels('p',"print_labels","Print out label/ROI numbers first", opts); QI::Help help(opts); std::vector<std::string> nonopts = opts.parse(argc, argv); if (nonopts.size() != 1) { std::cerr << opts << std::endl; std::cerr << "No input filename specified." << std::endl; return EXIT_FAILURE; } QI::VolumeI::Pointer label_image = QI::ReadImage<QI::VolumeI>(nonopts[0]); double voxvol = label_image->GetSpacing()[0]; for (int i = 1; i < 3; i++) voxvol *= label_image->GetSpacing()[i]; TLblGeoFilter::Pointer label_filter = TLblGeoFilter::New(); label_filter->SetInput(label_image); label_filter->CalculatePixelIndicesOff(); label_filter->CalculateOrientedBoundingBoxOff(); label_filter->CalculateOrientedLabelRegionsOff(); label_filter->Update(); typename TLblGeoFilter::LabelsType labels; if (label_list.set()) { std::ifstream file(*label_list); std::string line; while (std::getline(file, line)) { std::stringstream linestream(line); int label; linestream >> label; labels.push_back(label); } } else { labels = label_filter->GetLabels(); std::sort(labels.begin(), labels.end()); } for(auto it = labels.begin(); it != labels.end(); it++) { if (*ignore_zero && (*it == 0)) { continue; } if (*print_labels) std::cout << *it << ","; std::cout << (voxvol * label_filter->GetVolume(*it)) << std::endl; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// // GameSharing.cpp // PaperChase // // Created by Adrian Dawid on 17.08.14. // // #include "GameSharing.h" USING_NS_CC; bool GameSharing::bIsGPGAvailable = true; bool GameSharing::wasGPGAvailableCalled = false; void GameSharing::SubmitScore(int score) { #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID if(IsGPGAvailable()){ JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t , "org/cocos2dx/cpp.AppActivity" , "submitScoreToLeaderboard" , "(I)V")) { t.env->CallStaticVoidMethod(t.classID, t.methodID, score); // Release t.env->DeleteLocalRef(t.classID); } } #else CCLOG("Submit to Leaderboards"); #endif } void GameSharing::ShowLeaderboards(){ #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID if(IsGPGAvailable()){ JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t , "org/cocos2dx/cpp.AppActivity" , "openLeaderboardUI" , "()V")) { t.env->CallStaticVoidMethod(t.classID, t.methodID); // Release t.env->DeleteLocalRef(t.classID); } } else{ MessageBox("Google Play Games Services are not actvie.", "Error"); } #else CCLOG("Show Leaderboards"); #endif } void GameSharing::UnlockAchivement(int ID) { #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID if(IsGPGAvailable()) { JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t , "org/cocos2dx/cpp.AppActivity" , "openAchievement" , "(I)V")) { t.env->CallStaticVoidMethod(t.classID, t.methodID , ID); // Release t.env->DeleteLocalRef(t.classID); } JniMethodInfo tmp; if (JniHelper::getStaticMethodInfo(tmp , "org/cocos2dx/cpp.AppActivity" , "updateAchievement" , "(I)V")) { tmp.env->CallStaticVoidMethod(tmp.classID, tmp.methodID , 100); // Release tmp.env->DeleteLocalRef(t.classID); } } else{ MessageBox("Google Play Games Services are not actvie.", "Error"); } #else CCLOG("Unlock achivement"); #endif } void GameSharing::ShowAchievementsUI(){ #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID if(IsGPGAvailable()){ JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t , "org/cocos2dx/cpp.AppActivity" , "showAchievements" , "()V")) { t.env->CallStaticVoidMethod(t.classID, t.methodID); // Release t.env->DeleteLocalRef(t.classID); } } else{ MessageBox("Google Play Games Services are not actvie.", "Error"); } #else CCLOG("Unlock achivement"); #endif } bool GameSharing::IsGPGAvailable(){ bool tmp = false; if (!wasGPGAvailableCalled) { #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t , "org/cocos2dx/cpp.AppActivity" , "isGPGSupported" , "()Z")) { tmp = t.env->CallStaticBooleanMethod(t.classID, t.methodID); // Release t.env->DeleteLocalRef(t.classID); } #endif bIsGPGAvailable = tmp; } else{ tmp = bIsGPGAvailable; } wasGPGAvailableCalled = true; return tmp; }<commit_msg>Update GameSharing.cpp<commit_after>// // GameSharing.cpp // Copyright (c) Adrian Dawid 2014 // // Created by Adrian Dawid on 17.08.14. // // #include "GameSharing.h" USING_NS_CC; bool GameSharing::bIsGPGAvailable = true; bool GameSharing::wasGPGAvailableCalled = false; void GameSharing::SubmitScore(int score) { #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID if(IsGPGAvailable()){ JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t , "org/cocos2dx/cpp.AppActivity" , "submitScoreToLeaderboard" , "(I)V")) { t.env->CallStaticVoidMethod(t.classID, t.methodID, score); // Release t.env->DeleteLocalRef(t.classID); } } #else CCLOG("Submit to Leaderboards"); #endif } void GameSharing::ShowLeaderboards(){ #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID if(IsGPGAvailable()){ JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t , "org/cocos2dx/cpp.AppActivity" , "openLeaderboardUI" , "()V")) { t.env->CallStaticVoidMethod(t.classID, t.methodID); // Release t.env->DeleteLocalRef(t.classID); } } else{ MessageBox("Google Play Games Services are not actvie.", "Error"); } #else CCLOG("Show Leaderboards"); #endif } void GameSharing::UnlockAchivement(int ID) { #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID if(IsGPGAvailable()) { JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t , "org/cocos2dx/cpp.AppActivity" , "openAchievement" , "(I)V")) { t.env->CallStaticVoidMethod(t.classID, t.methodID , ID); // Release t.env->DeleteLocalRef(t.classID); } JniMethodInfo tmp; if (JniHelper::getStaticMethodInfo(tmp , "org/cocos2dx/cpp.AppActivity" , "updateAchievement" , "(I)V")) { tmp.env->CallStaticVoidMethod(tmp.classID, tmp.methodID , 100); // Release tmp.env->DeleteLocalRef(t.classID); } } else{ MessageBox("Google Play Games Services are not actvie.", "Error"); } #else CCLOG("Unlock achivement"); #endif } void GameSharing::ShowAchievementsUI(){ #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID if(IsGPGAvailable()){ JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t , "org/cocos2dx/cpp.AppActivity" , "showAchievements" , "()V")) { t.env->CallStaticVoidMethod(t.classID, t.methodID); // Release t.env->DeleteLocalRef(t.classID); } } else{ MessageBox("Google Play Games Services are not actvie.", "Error"); } #else CCLOG("Unlock achivement"); #endif } bool GameSharing::IsGPGAvailable(){ bool tmp = false; if (!wasGPGAvailableCalled) { #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t , "org/cocos2dx/cpp.AppActivity" , "isGPGSupported" , "()Z")) { tmp = t.env->CallStaticBooleanMethod(t.classID, t.methodID); // Release t.env->DeleteLocalRef(t.classID); } #endif bIsGPGAvailable = tmp; } else{ tmp = bIsGPGAvailable; } wasGPGAvailableCalled = true; return tmp; } <|endoftext|>
<commit_before>// Time Complexity: O(mn) // Time Complexity: O(mn) class Solution { public: unordered_map<int, unordered_map<int, int> > hash; int uniquePaths(int m, int n) { if(m == 0 || n == 0) return 0; if(m == 1 || n == 1) return 1; if(hash.find(m) != hash.end() && hash[m].find(n) != hash[m].end()) return hash[m][n]; return hash[m][n] = uniquePaths(m - 1, n) + uniquePaths(m, n - 1); } }; <commit_msg>update uniquePaths.cpp<commit_after>// Time Complexity: O(mn) // Space Complexity: O(mn) class Solution { public: unordered_map<int, unordered_map<int, int> > hash; int uniquePaths(int m, int n) { if(m == 0 || n == 0) return 0; if(m == 1 || n == 1) return 1; if(hash.find(m) != hash.end() && hash[m].find(n) != hash[m].end()) return hash[m][n]; return hash[m][n] = uniquePaths(m - 1, n) + uniquePaths(m, n - 1); } }; <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: popmenu.cxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:44:53 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // System - Includes ----------------------------------------------------- #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop #ifndef PCH #include <segmentc.hxx> #endif // INCLUDE --------------------------------------------------------------- #include "popmenu.hxx" // STATIC DATA ----------------------------------------------------------- SEG_EOFGLOBALS() //------------------------------------------------------------------ #pragma SEG_FUNCDEF(popmenu_01) void __EXPORT ScPopupMenu::Select() { nSel = GetCurItemId(); bHit = TRUE; } /*------------------------------------------------------------------------ $Log: not supported by cvs2svn $ Revision 1.4 2000/09/17 14:08:55 willem.vandorp OpenOffice header added. Revision 1.3 2000/08/31 16:38:19 willem.vandorp Header and footer replaced Revision 1.2 1996/07/31 18:58:38 NN bHit setzen Rev 1.1 31 Jul 1996 20:58:38 NN bHit setzen Rev 1.0 27 Jun 1996 12:41:58 NN Initial revision. ------------------------------------------------------------------------*/ #pragma SEG_EOFMODULE <commit_msg>del: segmentc.hxx<commit_after>/************************************************************************* * * $RCSfile: popmenu.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: mh $ $Date: 2001-10-23 10:42:31 $ * * 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): _______________________________________ * * ************************************************************************/ // System - Includes ----------------------------------------------------- #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #include "popmenu.hxx" //------------------------------------------------------------------ void __EXPORT ScPopupMenu::Select() { nSel = GetCurItemId(); bHit = TRUE; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: colrowba.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: nn $ $Date: 2002-08-30 18:42:35 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #include <svx/svdtrans.hxx> #ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX #include <unotools/localedatawrapper.hxx> #endif #include "colrowba.hxx" #include "document.hxx" #include "scmod.hxx" #include "tabvwsh.hxx" #include "docsh.hxx" #include "appoptio.hxx" #include "globstr.hrc" // STATIC DATA ----------------------------------------------------------- //================================================================== String lcl_MetricString( long nTwips, const String& rText ) { if ( nTwips <= 0 ) return ScGlobal::GetRscString(STR_TIP_HIDE); else { FieldUnit eUserMet = SC_MOD()->GetAppOptions().GetAppMetric(); long nUserVal = MetricField::ConvertValue( nTwips*100, 1, 2, FUNIT_TWIP, eUserMet ); String aStr = rText; aStr += ' '; aStr += ScGlobal::pLocaleData->getNum( nUserVal, 2 ); aStr += ' '; aStr += SdrFormatter::GetUnitStr(eUserMet); return aStr; } } //================================================================== ScColBar::ScColBar( Window* pParent, ScViewData* pData, ScHSplitPos eWhichPos, ScHeaderFunctionSet* pFunc, ScHeaderSelectionEngine* pEng ) : ScHeaderControl( pParent, pEng, MAXCOL+1, HDR_HORIZONTAL ), pViewData( pData ), eWhich( eWhichPos ), pFuncSet( pFunc ), pSelEngine( pEng ) { Show(); } ScColBar::~ScColBar() { } USHORT ScColBar::GetPos() { return pViewData->GetPosX(eWhich); } USHORT ScColBar::GetEntrySize( USHORT nEntryNo ) { ScDocument* pDoc = pViewData->GetDocument(); USHORT nTab = pViewData->GetTabNo(); if ( pDoc->GetColFlags( nEntryNo, nTab ) & CR_HIDDEN ) return 0; else return (USHORT) ScViewData::ToPixel( pDoc->GetColWidth( nEntryNo, nTab ), pViewData->GetPPTX() ); } String ScColBar::GetEntryText( USHORT nEntryNo ) { return ColToAlpha( nEntryNo ); } void ScColBar::SetEntrySize( USHORT nPos, USHORT nNewSize ) { USHORT nSizeTwips; ScSizeMode eMode = SC_SIZE_DIRECT; if (nNewSize>0 && nNewSize<10) nNewSize=10; // (Pixel) if ( nNewSize == HDR_SIZE_OPTIMUM ) { nSizeTwips = STD_EXTRA_WIDTH; eMode = SC_SIZE_OPTIMAL; } else nSizeTwips = (USHORT) ( nNewSize / pViewData->GetPPTX() ); ScMarkData& rMark = pViewData->GetMarkData(); // USHORT nTab = pViewData->GetTabNo(); USHORT* pRanges = new USHORT[MAXCOL+1]; USHORT nRangeCnt = 0; if ( rMark.IsColumnMarked( nPos ) ) { USHORT nStart = 0; while (nStart<=MAXCOL) { while (nStart<MAXCOL && !rMark.IsColumnMarked(nStart)) ++nStart; if (rMark.IsColumnMarked(nStart)) { USHORT nEnd = nStart; while (nEnd<MAXCOL && rMark.IsColumnMarked(nEnd)) ++nEnd; if (!rMark.IsColumnMarked(nEnd)) --nEnd; pRanges[2*nRangeCnt ] = nStart; pRanges[2*nRangeCnt+1] = nEnd; ++nRangeCnt; nStart = nEnd+1; } else nStart = MAXCOL+1; } } else { pRanges[0] = nPos; pRanges[1] = nPos; nRangeCnt = 1; } pViewData->GetView()->SetWidthOrHeight( TRUE, nRangeCnt, pRanges, eMode, nSizeTwips ); delete[] pRanges; } void ScColBar::HideEntries( USHORT nStart, USHORT nEnd ) { USHORT nRange[2]; nRange[0] = nStart; nRange[1] = nEnd; pViewData->GetView()->SetWidthOrHeight( TRUE, 1, nRange, SC_SIZE_DIRECT, 0 ); } void ScColBar::SetMarking( BOOL bSet ) { pViewData->GetMarkData().SetMarking( bSet ); if (!bSet) { pViewData->GetView()->UpdateAutoFillMark(); } } void ScColBar::SelectWindow() { ScTabViewShell* pViewSh = pViewData->GetViewShell(); pViewSh->SetActive(); // Appear und SetViewFrame pViewSh->DrawDeselectAll(); ScSplitPos eActive = pViewData->GetActivePart(); if (eWhich==SC_SPLIT_LEFT) { if (eActive==SC_SPLIT_TOPRIGHT) eActive=SC_SPLIT_TOPLEFT; if (eActive==SC_SPLIT_BOTTOMRIGHT) eActive=SC_SPLIT_BOTTOMLEFT; } else { if (eActive==SC_SPLIT_TOPLEFT) eActive=SC_SPLIT_TOPRIGHT; if (eActive==SC_SPLIT_BOTTOMLEFT) eActive=SC_SPLIT_BOTTOMRIGHT; } pViewSh->ActivatePart( eActive ); pFuncSet->SetColumn( TRUE ); pFuncSet->SetWhich( eActive ); pViewSh->ActiveGrabFocus(); } BOOL ScColBar::IsDisabled() { ScModule* pScMod = SC_MOD(); return pScMod->IsFormulaMode() || pScMod->IsModalMode(); } BOOL ScColBar::ResizeAllowed() { return !pViewData->HasEditView( pViewData->GetActivePart() ) && !pViewData->GetDocShell()->IsReadOnly(); } void ScColBar::DrawInvert( long nDragPos ) { Rectangle aRect( nDragPos,0, nDragPos+HDR_SLIDERSIZE-1,GetOutputSizePixel().Width()-1 ); Update(); Invert(aRect); pViewData->GetView()->InvertVertical(eWhich,nDragPos); } String ScColBar::GetDragHelp( long nVal ) { long nTwips = (long) ( nVal / pViewData->GetPPTX() ); return lcl_MetricString( nTwips, ScGlobal::GetRscString(STR_TIP_WIDTH) ); } //================================================================== ScRowBar::ScRowBar( Window* pParent, ScViewData* pData, ScVSplitPos eWhichPos, ScHeaderFunctionSet* pFunc, ScHeaderSelectionEngine* pEng ) : ScHeaderControl( pParent, pEng, MAXROW+1, HDR_VERTICAL ), pViewData( pData ), eWhich( eWhichPos ), pFuncSet( pFunc ), pSelEngine( pEng ) { Show(); } ScRowBar::~ScRowBar() { } USHORT ScRowBar::GetPos() { return pViewData->GetPosY(eWhich); } USHORT ScRowBar::GetEntrySize( USHORT nEntryNo ) { ScDocument* pDoc = pViewData->GetDocument(); USHORT nTab = pViewData->GetTabNo(); if ( pDoc->GetRowFlags( nEntryNo, nTab ) & CR_HIDDEN ) return 0; else return (USHORT) ScViewData::ToPixel( pDoc->GetRowHeight( nEntryNo, nTab ), pViewData->GetPPTY() ); } String ScRowBar::GetEntryText( USHORT nEntryNo ) { return String::CreateFromInt32( nEntryNo + 1 ); } void ScRowBar::SetEntrySize( USHORT nPos, USHORT nNewSize ) { USHORT nSizeTwips; ScSizeMode eMode = SC_SIZE_DIRECT; if (nNewSize>0 && nNewSize<10) nNewSize=10; // (Pixel) if ( nNewSize == HDR_SIZE_OPTIMUM ) { nSizeTwips = 0; eMode = SC_SIZE_OPTIMAL; } else nSizeTwips = (USHORT) ( nNewSize / pViewData->GetPPTY() ); ScMarkData& rMark = pViewData->GetMarkData(); // USHORT nTab = pViewData->GetTabNo(); USHORT* pRanges = new USHORT[MAXROW+1]; USHORT nRangeCnt = 0; if ( rMark.IsRowMarked( nPos ) ) { USHORT nStart = 0; while (nStart<=MAXROW) { while (nStart<MAXROW && !rMark.IsRowMarked(nStart)) ++nStart; if (rMark.IsRowMarked(nStart)) { USHORT nEnd = nStart; while (nEnd<MAXROW && rMark.IsRowMarked(nEnd)) ++nEnd; if (!rMark.IsRowMarked(nEnd)) --nEnd; pRanges[2*nRangeCnt ] = nStart; pRanges[2*nRangeCnt+1] = nEnd; ++nRangeCnt; nStart = nEnd+1; } else nStart = MAXROW+1; } } else { pRanges[0] = nPos; pRanges[1] = nPos; nRangeCnt = 1; } pViewData->GetView()->SetWidthOrHeight( FALSE, nRangeCnt, pRanges, eMode, nSizeTwips ); delete[] pRanges; } void ScRowBar::HideEntries( USHORT nStart, USHORT nEnd ) { USHORT nRange[2]; nRange[0] = nStart; nRange[1] = nEnd; pViewData->GetView()->SetWidthOrHeight( FALSE, 1, nRange, SC_SIZE_DIRECT, 0 ); } void ScRowBar::SetMarking( BOOL bSet ) { pViewData->GetMarkData().SetMarking( bSet ); if (!bSet) { pViewData->GetView()->UpdateAutoFillMark(); } } void ScRowBar::SelectWindow() { ScTabViewShell* pViewSh = pViewData->GetViewShell(); pViewSh->SetActive(); // Appear und SetViewFrame pViewSh->DrawDeselectAll(); ScSplitPos eActive = pViewData->GetActivePart(); if (eWhich==SC_SPLIT_TOP) { if (eActive==SC_SPLIT_BOTTOMLEFT) eActive=SC_SPLIT_TOPLEFT; if (eActive==SC_SPLIT_BOTTOMRIGHT) eActive=SC_SPLIT_TOPRIGHT; } else { if (eActive==SC_SPLIT_TOPLEFT) eActive=SC_SPLIT_BOTTOMLEFT; if (eActive==SC_SPLIT_TOPRIGHT) eActive=SC_SPLIT_BOTTOMRIGHT; } pViewSh->ActivatePart( eActive ); pFuncSet->SetColumn( FALSE ); pFuncSet->SetWhich( eActive ); pViewSh->ActiveGrabFocus(); } BOOL ScRowBar::IsDisabled() { ScModule* pScMod = SC_MOD(); return pScMod->IsFormulaMode() || pScMod->IsModalMode(); } BOOL ScRowBar::ResizeAllowed() { return !pViewData->HasEditView( pViewData->GetActivePart() ) && !pViewData->GetDocShell()->IsReadOnly(); } void ScRowBar::DrawInvert( long nDragPos ) { Rectangle aRect( 0,nDragPos, GetOutputSizePixel().Width()-1,nDragPos+HDR_SLIDERSIZE-1 ); Update(); Invert(aRect); pViewData->GetView()->InvertHorizontal(eWhich,nDragPos); } String ScRowBar::GetDragHelp( long nVal ) { long nTwips = (long) ( nVal / pViewData->GetPPTY() ); return lcl_MetricString( nTwips, ScGlobal::GetRscString(STR_TIP_HEIGHT) ); } // GetHiddenCount ist nur fuer Zeilen ueberladen USHORT ScRowBar::GetHiddenCount( USHORT nEntryNo ) { ScDocument* pDoc = pViewData->GetDocument(); USHORT nTab = pViewData->GetTabNo(); return pDoc->GetHiddenRowCount( nEntryNo, nTab ); } <commit_msg>INTEGRATION: CWS calcrtl (1.9.86); FILE MERGED 2003/07/11 10:33:37 nn 1.9.86.2: #106948# RTL ordering of view elements 2003/06/30 17:21:39 nn 1.9.86.1: #106948# RTL layout, continued implementation<commit_after>/************************************************************************* * * $RCSfile: colrowba.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2004-02-03 12:51:27 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #include <svx/svdtrans.hxx> #ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX #include <unotools/localedatawrapper.hxx> #endif #include "colrowba.hxx" #include "document.hxx" #include "scmod.hxx" #include "tabvwsh.hxx" #include "docsh.hxx" #include "appoptio.hxx" #include "globstr.hrc" // STATIC DATA ----------------------------------------------------------- //================================================================== String lcl_MetricString( long nTwips, const String& rText ) { if ( nTwips <= 0 ) return ScGlobal::GetRscString(STR_TIP_HIDE); else { FieldUnit eUserMet = SC_MOD()->GetAppOptions().GetAppMetric(); long nUserVal = MetricField::ConvertValue( nTwips*100, 1, 2, FUNIT_TWIP, eUserMet ); String aStr = rText; aStr += ' '; aStr += ScGlobal::pLocaleData->getNum( nUserVal, 2 ); aStr += ' '; aStr += SdrFormatter::GetUnitStr(eUserMet); return aStr; } } //================================================================== ScColBar::ScColBar( Window* pParent, ScViewData* pData, ScHSplitPos eWhichPos, ScHeaderFunctionSet* pFunc, ScHeaderSelectionEngine* pEng ) : ScHeaderControl( pParent, pEng, MAXCOL+1, HDR_HORIZONTAL ), pViewData( pData ), eWhich( eWhichPos ), pFuncSet( pFunc ), pSelEngine( pEng ) { Show(); } ScColBar::~ScColBar() { } USHORT ScColBar::GetPos() { return pViewData->GetPosX(eWhich); } USHORT ScColBar::GetEntrySize( USHORT nEntryNo ) { ScDocument* pDoc = pViewData->GetDocument(); USHORT nTab = pViewData->GetTabNo(); if ( pDoc->GetColFlags( nEntryNo, nTab ) & CR_HIDDEN ) return 0; else return (USHORT) ScViewData::ToPixel( pDoc->GetColWidth( nEntryNo, nTab ), pViewData->GetPPTX() ); } String ScColBar::GetEntryText( USHORT nEntryNo ) { return ColToAlpha( nEntryNo ); } void ScColBar::SetEntrySize( USHORT nPos, USHORT nNewSize ) { USHORT nSizeTwips; ScSizeMode eMode = SC_SIZE_DIRECT; if (nNewSize>0 && nNewSize<10) nNewSize=10; // (Pixel) if ( nNewSize == HDR_SIZE_OPTIMUM ) { nSizeTwips = STD_EXTRA_WIDTH; eMode = SC_SIZE_OPTIMAL; } else nSizeTwips = (USHORT) ( nNewSize / pViewData->GetPPTX() ); ScMarkData& rMark = pViewData->GetMarkData(); // USHORT nTab = pViewData->GetTabNo(); USHORT* pRanges = new USHORT[MAXCOL+1]; USHORT nRangeCnt = 0; if ( rMark.IsColumnMarked( nPos ) ) { USHORT nStart = 0; while (nStart<=MAXCOL) { while (nStart<MAXCOL && !rMark.IsColumnMarked(nStart)) ++nStart; if (rMark.IsColumnMarked(nStart)) { USHORT nEnd = nStart; while (nEnd<MAXCOL && rMark.IsColumnMarked(nEnd)) ++nEnd; if (!rMark.IsColumnMarked(nEnd)) --nEnd; pRanges[2*nRangeCnt ] = nStart; pRanges[2*nRangeCnt+1] = nEnd; ++nRangeCnt; nStart = nEnd+1; } else nStart = MAXCOL+1; } } else { pRanges[0] = nPos; pRanges[1] = nPos; nRangeCnt = 1; } pViewData->GetView()->SetWidthOrHeight( TRUE, nRangeCnt, pRanges, eMode, nSizeTwips ); delete[] pRanges; } void ScColBar::HideEntries( USHORT nStart, USHORT nEnd ) { USHORT nRange[2]; nRange[0] = nStart; nRange[1] = nEnd; pViewData->GetView()->SetWidthOrHeight( TRUE, 1, nRange, SC_SIZE_DIRECT, 0 ); } void ScColBar::SetMarking( BOOL bSet ) { pViewData->GetMarkData().SetMarking( bSet ); if (!bSet) { pViewData->GetView()->UpdateAutoFillMark(); } } void ScColBar::SelectWindow() { ScTabViewShell* pViewSh = pViewData->GetViewShell(); pViewSh->SetActive(); // Appear und SetViewFrame pViewSh->DrawDeselectAll(); ScSplitPos eActive = pViewData->GetActivePart(); if (eWhich==SC_SPLIT_LEFT) { if (eActive==SC_SPLIT_TOPRIGHT) eActive=SC_SPLIT_TOPLEFT; if (eActive==SC_SPLIT_BOTTOMRIGHT) eActive=SC_SPLIT_BOTTOMLEFT; } else { if (eActive==SC_SPLIT_TOPLEFT) eActive=SC_SPLIT_TOPRIGHT; if (eActive==SC_SPLIT_BOTTOMLEFT) eActive=SC_SPLIT_BOTTOMRIGHT; } pViewSh->ActivatePart( eActive ); pFuncSet->SetColumn( TRUE ); pFuncSet->SetWhich( eActive ); pViewSh->ActiveGrabFocus(); } BOOL ScColBar::IsDisabled() { ScModule* pScMod = SC_MOD(); return pScMod->IsFormulaMode() || pScMod->IsModalMode(); } BOOL ScColBar::ResizeAllowed() { return !pViewData->HasEditView( pViewData->GetActivePart() ) && !pViewData->GetDocShell()->IsReadOnly(); } void ScColBar::DrawInvert( long nDragPos ) { Rectangle aRect( nDragPos,0, nDragPos+HDR_SLIDERSIZE-1,GetOutputSizePixel().Width()-1 ); Update(); Invert(aRect); pViewData->GetView()->InvertVertical(eWhich,nDragPos); } String ScColBar::GetDragHelp( long nVal ) { long nTwips = (long) ( nVal / pViewData->GetPPTX() ); return lcl_MetricString( nTwips, ScGlobal::GetRscString(STR_TIP_WIDTH) ); } BOOL ScColBar::IsLayoutRTL() // overloaded only for columns { return pViewData->GetDocument()->IsLayoutRTL( pViewData->GetTabNo() ); } //================================================================== ScRowBar::ScRowBar( Window* pParent, ScViewData* pData, ScVSplitPos eWhichPos, ScHeaderFunctionSet* pFunc, ScHeaderSelectionEngine* pEng ) : ScHeaderControl( pParent, pEng, MAXROW+1, HDR_VERTICAL ), pViewData( pData ), eWhich( eWhichPos ), pFuncSet( pFunc ), pSelEngine( pEng ) { Show(); } ScRowBar::~ScRowBar() { } USHORT ScRowBar::GetPos() { return pViewData->GetPosY(eWhich); } USHORT ScRowBar::GetEntrySize( USHORT nEntryNo ) { ScDocument* pDoc = pViewData->GetDocument(); USHORT nTab = pViewData->GetTabNo(); if ( pDoc->GetRowFlags( nEntryNo, nTab ) & CR_HIDDEN ) return 0; else return (USHORT) ScViewData::ToPixel( pDoc->GetRowHeight( nEntryNo, nTab ), pViewData->GetPPTY() ); } String ScRowBar::GetEntryText( USHORT nEntryNo ) { return String::CreateFromInt32( nEntryNo + 1 ); } void ScRowBar::SetEntrySize( USHORT nPos, USHORT nNewSize ) { USHORT nSizeTwips; ScSizeMode eMode = SC_SIZE_DIRECT; if (nNewSize>0 && nNewSize<10) nNewSize=10; // (Pixel) if ( nNewSize == HDR_SIZE_OPTIMUM ) { nSizeTwips = 0; eMode = SC_SIZE_OPTIMAL; } else nSizeTwips = (USHORT) ( nNewSize / pViewData->GetPPTY() ); ScMarkData& rMark = pViewData->GetMarkData(); // USHORT nTab = pViewData->GetTabNo(); USHORT* pRanges = new USHORT[MAXROW+1]; USHORT nRangeCnt = 0; if ( rMark.IsRowMarked( nPos ) ) { USHORT nStart = 0; while (nStart<=MAXROW) { while (nStart<MAXROW && !rMark.IsRowMarked(nStart)) ++nStart; if (rMark.IsRowMarked(nStart)) { USHORT nEnd = nStart; while (nEnd<MAXROW && rMark.IsRowMarked(nEnd)) ++nEnd; if (!rMark.IsRowMarked(nEnd)) --nEnd; pRanges[2*nRangeCnt ] = nStart; pRanges[2*nRangeCnt+1] = nEnd; ++nRangeCnt; nStart = nEnd+1; } else nStart = MAXROW+1; } } else { pRanges[0] = nPos; pRanges[1] = nPos; nRangeCnt = 1; } pViewData->GetView()->SetWidthOrHeight( FALSE, nRangeCnt, pRanges, eMode, nSizeTwips ); delete[] pRanges; } void ScRowBar::HideEntries( USHORT nStart, USHORT nEnd ) { USHORT nRange[2]; nRange[0] = nStart; nRange[1] = nEnd; pViewData->GetView()->SetWidthOrHeight( FALSE, 1, nRange, SC_SIZE_DIRECT, 0 ); } void ScRowBar::SetMarking( BOOL bSet ) { pViewData->GetMarkData().SetMarking( bSet ); if (!bSet) { pViewData->GetView()->UpdateAutoFillMark(); } } void ScRowBar::SelectWindow() { ScTabViewShell* pViewSh = pViewData->GetViewShell(); pViewSh->SetActive(); // Appear und SetViewFrame pViewSh->DrawDeselectAll(); ScSplitPos eActive = pViewData->GetActivePart(); if (eWhich==SC_SPLIT_TOP) { if (eActive==SC_SPLIT_BOTTOMLEFT) eActive=SC_SPLIT_TOPLEFT; if (eActive==SC_SPLIT_BOTTOMRIGHT) eActive=SC_SPLIT_TOPRIGHT; } else { if (eActive==SC_SPLIT_TOPLEFT) eActive=SC_SPLIT_BOTTOMLEFT; if (eActive==SC_SPLIT_TOPRIGHT) eActive=SC_SPLIT_BOTTOMRIGHT; } pViewSh->ActivatePart( eActive ); pFuncSet->SetColumn( FALSE ); pFuncSet->SetWhich( eActive ); pViewSh->ActiveGrabFocus(); } BOOL ScRowBar::IsDisabled() { ScModule* pScMod = SC_MOD(); return pScMod->IsFormulaMode() || pScMod->IsModalMode(); } BOOL ScRowBar::ResizeAllowed() { return !pViewData->HasEditView( pViewData->GetActivePart() ) && !pViewData->GetDocShell()->IsReadOnly(); } void ScRowBar::DrawInvert( long nDragPos ) { Rectangle aRect( 0,nDragPos, GetOutputSizePixel().Width()-1,nDragPos+HDR_SLIDERSIZE-1 ); Update(); Invert(aRect); pViewData->GetView()->InvertHorizontal(eWhich,nDragPos); } String ScRowBar::GetDragHelp( long nVal ) { long nTwips = (long) ( nVal / pViewData->GetPPTY() ); return lcl_MetricString( nTwips, ScGlobal::GetRscString(STR_TIP_HEIGHT) ); } // GetHiddenCount ist nur fuer Zeilen ueberladen USHORT ScRowBar::GetHiddenCount( USHORT nEntryNo ) { ScDocument* pDoc = pViewData->GetDocument(); USHORT nTab = pViewData->GetTabNo(); return pDoc->GetHiddenRowCount( nEntryNo, nTab ); } BOOL ScRowBar::IsMirrored() // overloaded only for rows { return pViewData->GetDocument()->IsLayoutRTL( pViewData->GetTabNo() ); } <|endoftext|>
<commit_before>//===- BuildSystem.cpp - Utilities for use by build systems ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements various utilities for use by build systems. // //===----------------------------------------------------------------------===// #include "clang-c/BuildSystem.h" #include "CXString.h" #include "clang/Basic/VirtualFileSystem.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/CBindingWrapping.h" #include "llvm/Support/Path.h" #include "llvm/Support/TimeValue.h" #include "llvm/Support/raw_ostream.h" using namespace clang; using namespace llvm::sys; unsigned long long clang_getBuildSessionTimestamp(void) { return llvm::sys::TimeValue::now().toEpochTime(); } DEFINE_SIMPLE_CONVERSION_FUNCTIONS(clang::vfs::YAMLVFSWriter, CXVirtualFileOverlay) CXVirtualFileOverlay clang_VirtualFileOverlay_create(unsigned) { return wrap(new clang::vfs::YAMLVFSWriter()); } enum CXErrorCode clang_VirtualFileOverlay_addFileMapping(CXVirtualFileOverlay VFO, const char *virtualPath, const char *realPath) { if (!VFO || !virtualPath || !realPath) return CXError_InvalidArguments; if (!path::is_absolute(virtualPath)) return CXError_InvalidArguments; if (!path::is_absolute(realPath)) return CXError_InvalidArguments; for (path::const_iterator PI = path::begin(virtualPath), PE = path::end(virtualPath); PI != PE; ++PI) { StringRef Comp = *PI; if (Comp == "." || Comp == "..") return CXError_InvalidArguments; } unwrap(VFO)->addFileMapping(virtualPath, realPath); return CXError_Success; } enum CXErrorCode clang_VirtualFileOverlay_setCaseSensitivity(CXVirtualFileOverlay VFO, int caseSensitive) { if (!VFO) return CXError_InvalidArguments; unwrap(VFO)->setCaseSensitivity(caseSensitive); return CXError_Success; } enum CXErrorCode clang_VirtualFileOverlay_writeToBuffer(CXVirtualFileOverlay VFO, unsigned, char **out_buffer_ptr, unsigned *out_buffer_size) { if (!VFO || !out_buffer_ptr || !out_buffer_size) return CXError_InvalidArguments; llvm::SmallString<256> Buf; llvm::raw_svector_ostream OS(Buf); unwrap(VFO)->write(OS); StringRef Data = OS.str(); *out_buffer_ptr = (char*)malloc(Data.size()); *out_buffer_size = Data.size(); memcpy(*out_buffer_ptr, Data.data(), Data.size()); return CXError_Success; } void clang_free(void *buffer) { free(buffer); } void clang_VirtualFileOverlay_dispose(CXVirtualFileOverlay VFO) { delete unwrap(VFO); } struct CXModuleMapDescriptorImpl { std::string ModuleName; std::string UmbrellaHeader; }; CXModuleMapDescriptor clang_ModuleMapDescriptor_create(unsigned) { return new CXModuleMapDescriptorImpl(); } enum CXErrorCode clang_ModuleMapDescriptor_setFrameworkModuleName(CXModuleMapDescriptor MMD, const char *name) { if (!MMD || !name) return CXError_InvalidArguments; MMD->ModuleName = name; return CXError_Success; } enum CXErrorCode clang_ModuleMapDescriptor_setUmbrellaHeader(CXModuleMapDescriptor MMD, const char *name) { if (!MMD || !name) return CXError_InvalidArguments; MMD->UmbrellaHeader = name; return CXError_Success; } enum CXErrorCode clang_ModuleMapDescriptor_writeToBuffer(CXModuleMapDescriptor MMD, unsigned, char **out_buffer_ptr, unsigned *out_buffer_size) { if (!MMD || !out_buffer_ptr || !out_buffer_size) return CXError_InvalidArguments; llvm::SmallString<256> Buf; llvm::raw_svector_ostream OS(Buf); OS << "framework module " << MMD->ModuleName << " {\n"; OS << " umbrella header \""; OS.write_escaped(MMD->UmbrellaHeader) << "\"\n"; OS << '\n'; OS << " export *\n"; OS << " module * { export * }\n"; OS << "}\n"; StringRef Data = OS.str(); *out_buffer_ptr = (char*)malloc(Data.size()); *out_buffer_size = Data.size(); memcpy(*out_buffer_ptr, Data.data(), Data.size()); return CXError_Success; } void clang_ModuleMapDescriptor_dispose(CXModuleMapDescriptor MMD) { delete MMD; } <commit_msg>Replace TimeValue with TimePoint in BuildSystem.cpp. NFC.<commit_after>//===- BuildSystem.cpp - Utilities for use by build systems ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements various utilities for use by build systems. // //===----------------------------------------------------------------------===// #include "clang-c/BuildSystem.h" #include "CXString.h" #include "clang/Basic/VirtualFileSystem.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/CBindingWrapping.h" #include "llvm/Support/Chrono.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" using namespace clang; using namespace llvm::sys; unsigned long long clang_getBuildSessionTimestamp(void) { return llvm::sys::toTimeT(std::chrono::system_clock::now()); } DEFINE_SIMPLE_CONVERSION_FUNCTIONS(clang::vfs::YAMLVFSWriter, CXVirtualFileOverlay) CXVirtualFileOverlay clang_VirtualFileOverlay_create(unsigned) { return wrap(new clang::vfs::YAMLVFSWriter()); } enum CXErrorCode clang_VirtualFileOverlay_addFileMapping(CXVirtualFileOverlay VFO, const char *virtualPath, const char *realPath) { if (!VFO || !virtualPath || !realPath) return CXError_InvalidArguments; if (!path::is_absolute(virtualPath)) return CXError_InvalidArguments; if (!path::is_absolute(realPath)) return CXError_InvalidArguments; for (path::const_iterator PI = path::begin(virtualPath), PE = path::end(virtualPath); PI != PE; ++PI) { StringRef Comp = *PI; if (Comp == "." || Comp == "..") return CXError_InvalidArguments; } unwrap(VFO)->addFileMapping(virtualPath, realPath); return CXError_Success; } enum CXErrorCode clang_VirtualFileOverlay_setCaseSensitivity(CXVirtualFileOverlay VFO, int caseSensitive) { if (!VFO) return CXError_InvalidArguments; unwrap(VFO)->setCaseSensitivity(caseSensitive); return CXError_Success; } enum CXErrorCode clang_VirtualFileOverlay_writeToBuffer(CXVirtualFileOverlay VFO, unsigned, char **out_buffer_ptr, unsigned *out_buffer_size) { if (!VFO || !out_buffer_ptr || !out_buffer_size) return CXError_InvalidArguments; llvm::SmallString<256> Buf; llvm::raw_svector_ostream OS(Buf); unwrap(VFO)->write(OS); StringRef Data = OS.str(); *out_buffer_ptr = (char*)malloc(Data.size()); *out_buffer_size = Data.size(); memcpy(*out_buffer_ptr, Data.data(), Data.size()); return CXError_Success; } void clang_free(void *buffer) { free(buffer); } void clang_VirtualFileOverlay_dispose(CXVirtualFileOverlay VFO) { delete unwrap(VFO); } struct CXModuleMapDescriptorImpl { std::string ModuleName; std::string UmbrellaHeader; }; CXModuleMapDescriptor clang_ModuleMapDescriptor_create(unsigned) { return new CXModuleMapDescriptorImpl(); } enum CXErrorCode clang_ModuleMapDescriptor_setFrameworkModuleName(CXModuleMapDescriptor MMD, const char *name) { if (!MMD || !name) return CXError_InvalidArguments; MMD->ModuleName = name; return CXError_Success; } enum CXErrorCode clang_ModuleMapDescriptor_setUmbrellaHeader(CXModuleMapDescriptor MMD, const char *name) { if (!MMD || !name) return CXError_InvalidArguments; MMD->UmbrellaHeader = name; return CXError_Success; } enum CXErrorCode clang_ModuleMapDescriptor_writeToBuffer(CXModuleMapDescriptor MMD, unsigned, char **out_buffer_ptr, unsigned *out_buffer_size) { if (!MMD || !out_buffer_ptr || !out_buffer_size) return CXError_InvalidArguments; llvm::SmallString<256> Buf; llvm::raw_svector_ostream OS(Buf); OS << "framework module " << MMD->ModuleName << " {\n"; OS << " umbrella header \""; OS.write_escaped(MMD->UmbrellaHeader) << "\"\n"; OS << '\n'; OS << " export *\n"; OS << " module * { export * }\n"; OS << "}\n"; StringRef Data = OS.str(); *out_buffer_ptr = (char*)malloc(Data.size()); *out_buffer_size = Data.size(); memcpy(*out_buffer_ptr, Data.data(), Data.size()); return CXError_Success; } void clang_ModuleMapDescriptor_dispose(CXModuleMapDescriptor MMD) { delete MMD; } <|endoftext|>
<commit_before>#include "Point.hpp" #include <math.h> namespace Slic3r { void Point::scale(double factor) { this->x *= factor; this->y *= factor; } void Point::translate(double x, double y) { this->x += x; this->y += y; } void Point::rotate(double angle, Point* center) { double cur_x = (double)this->x; double cur_y = (double)this->y; this->x = (long)( (double)center->x + cos(angle) * (cur_x - (double)center->x) - sin(angle) * (cur_y - (double)center->y) ); this->y = (long)( (double)center->y + cos(angle) * (cur_y - (double)center->y) + sin(angle) * (cur_x - (double)center->x) ); } bool Point::coincides_with(const Point* point) const { return this->x == point->x && this->y == point->y; } int Point::nearest_point_index(const Points points) const { int idx = -1; long distance = -1; for (Points::const_iterator it = points.begin(); it != points.end(); ++it) { /* If the X distance of the candidate is > than the total distance of the best previous candidate, we know we don't want it */ long d = pow(this->x - (*it).x, 2); if (distance != -1 && d > distance) continue; /* If the Y distance of the candidate is > than the total distance of the best previous candidate, we know we don't want it */ d += pow(this->y - (*it).y, 2); if (distance != -1 && d > distance) continue; idx = it - points.begin(); distance = d; if (distance < EPSILON) break; } return idx; } Point* Point::nearest_point(Points points) const { return &(points.at(this->nearest_point_index(points))); } double Point::distance_to(const Point* point) const { double dx = ((double)point->x - this->x); double dy = ((double)point->y - this->y); return sqrt(dx*dx + dy*dy); } SV* Point::to_SV_ref() { SV* sv = newSV(0); sv_setref_pv( sv, "Slic3r::Point::Ref", (void*)this ); return sv; } SV* Point::to_SV_clone_ref() const { SV* sv = newSV(0); sv_setref_pv( sv, "Slic3r::Point", new Point(*this) ); return sv; } SV* Point::to_SV_pureperl() const { AV* av = newAV(); av_fill(av, 1); av_store(av, 0, newSViv(this->x)); av_store(av, 1, newSViv(this->y)); return newRV_noinc((SV*)av); } void Point::from_SV(SV* point_sv) { AV* point_av = (AV*)SvRV(point_sv); this->x = (long)SvIV(*av_fetch(point_av, 0, 0)); this->y = (long)SvIV(*av_fetch(point_av, 1, 0)); } void Point::from_SV_check(SV* point_sv) { if (sv_isobject(point_sv) && (SvTYPE(SvRV(point_sv)) == SVt_PVMG)) { *this = *(Point*)SvIV((SV*)SvRV( point_sv )); } else { this->from_SV(point_sv); } } } <commit_msg>Round results when rotating to minimize errors & pass the tests<commit_after>#include "Point.hpp" #include <math.h> namespace Slic3r { void Point::scale(double factor) { this->x *= factor; this->y *= factor; } void Point::translate(double x, double y) { this->x += x; this->y += y; } void Point::rotate(double angle, Point* center) { double cur_x = (double)this->x; double cur_y = (double)this->y; this->x = (long)round( (double)center->x + cos(angle) * (cur_x - (double)center->x) - sin(angle) * (cur_y - (double)center->y) ); this->y = (long)round( (double)center->y + cos(angle) * (cur_y - (double)center->y) + sin(angle) * (cur_x - (double)center->x) ); } bool Point::coincides_with(const Point* point) const { return this->x == point->x && this->y == point->y; } int Point::nearest_point_index(const Points points) const { int idx = -1; long distance = -1; for (Points::const_iterator it = points.begin(); it != points.end(); ++it) { /* If the X distance of the candidate is > than the total distance of the best previous candidate, we know we don't want it */ long d = pow(this->x - (*it).x, 2); if (distance != -1 && d > distance) continue; /* If the Y distance of the candidate is > than the total distance of the best previous candidate, we know we don't want it */ d += pow(this->y - (*it).y, 2); if (distance != -1 && d > distance) continue; idx = it - points.begin(); distance = d; if (distance < EPSILON) break; } return idx; } Point* Point::nearest_point(Points points) const { return &(points.at(this->nearest_point_index(points))); } double Point::distance_to(const Point* point) const { double dx = ((double)point->x - this->x); double dy = ((double)point->y - this->y); return sqrt(dx*dx + dy*dy); } SV* Point::to_SV_ref() { SV* sv = newSV(0); sv_setref_pv( sv, "Slic3r::Point::Ref", (void*)this ); return sv; } SV* Point::to_SV_clone_ref() const { SV* sv = newSV(0); sv_setref_pv( sv, "Slic3r::Point", new Point(*this) ); return sv; } SV* Point::to_SV_pureperl() const { AV* av = newAV(); av_fill(av, 1); av_store(av, 0, newSViv(this->x)); av_store(av, 1, newSViv(this->y)); return newRV_noinc((SV*)av); } void Point::from_SV(SV* point_sv) { AV* point_av = (AV*)SvRV(point_sv); this->x = (long)SvIV(*av_fetch(point_av, 0, 0)); this->y = (long)SvIV(*av_fetch(point_av, 1, 0)); } void Point::from_SV_check(SV* point_sv) { if (sv_isobject(point_sv) && (SvTYPE(SvRV(point_sv)) == SVt_PVMG)) { *this = *(Point*)SvIV((SV*)SvRV( point_sv )); } else { this->from_SV(point_sv); } } } <|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: colrowst.hxx,v $ * $Revision: 1.23 $ * * 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 _COLROWST_HXX #define _COLROWST_HXX #ifndef EXC_XIROOT_HXX #include "xiroot.hxx" #endif class XclImpStream; // ============================================================================ class XclImpColRowSettings : protected XclImpRoot { public: explicit XclImpColRowSettings( const XclImpRoot& rRoot ); virtual ~XclImpColRowSettings(); void SetDefWidth( sal_uInt16 nDefWidth, bool bStdWidthRec = false ); void SetWidthRange( SCCOL nCol1, SCCOL nCol2, sal_uInt16 nWidth ); void HideCol( SCCOL nCol ); void HideColRange( SCCOL nCol1, SCCOL nCol2 ); void SetDefHeight( sal_uInt16 nDefHeight, sal_uInt16 nFlags ); void SetHeight( SCROW nRow, sal_uInt16 nHeight ); void HideRow( SCROW nRow ); void SetRowSettings( SCROW nRow, sal_uInt16 nHeight, sal_uInt16 nFlags ); void SetDefaultXF( SCCOL nScCol1, SCCOL nScCol2, sal_uInt16 nXFIndex ); /** Inserts all column and row settings of the specified sheet, except the hidden flags. */ void Convert( SCTAB nScTab ); /** Sets the HIDDEN flags at all hidden columns and rows in the specified sheet. */ void ConvertHiddenFlags( SCTAB nScTab ); private: ScfUInt16Vec maWidths; /// Column widths in twips. ScfUInt8Vec maColFlags; /// Flags for all columns. ScfUInt16Vec maHeights; /// Row heights in twips. ScfUInt8Vec maRowFlags; /// Flags for all rows. SCROW mnLastScRow; sal_uInt16 mnDefWidth; /// Default width from DEFCOLWIDTH or STANDARDWIDTH record. sal_uInt16 mnDefHeight; /// Default height from DEFAULTROWHEIGHT record. sal_uInt16 mnDefRowFlags; /// Default row flags from DEFAULTROWHEIGHT record. bool mbHasStdWidthRec; /// true = Width from STANDARDWIDTH (overrides DEFCOLWIDTH record). bool mbHasDefHeight; /// true = mnDefHeight and mnDefRowFlags are valid. bool mbDirty; }; #endif <commit_msg>INTEGRATION: CWS dr61 (1.23.16); FILE MERGED 2008/05/19 12:24:01 dr 1.23.16.1: #i10000# removed remaining include guards<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: colrowst.hxx,v $ * $Revision: 1.24 $ * * 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 SC_COLROWST_HXX #define SC_COLROWST_HXX #include "xiroot.hxx" class XclImpStream; // ============================================================================ class XclImpColRowSettings : protected XclImpRoot { public: explicit XclImpColRowSettings( const XclImpRoot& rRoot ); virtual ~XclImpColRowSettings(); void SetDefWidth( sal_uInt16 nDefWidth, bool bStdWidthRec = false ); void SetWidthRange( SCCOL nCol1, SCCOL nCol2, sal_uInt16 nWidth ); void HideCol( SCCOL nCol ); void HideColRange( SCCOL nCol1, SCCOL nCol2 ); void SetDefHeight( sal_uInt16 nDefHeight, sal_uInt16 nFlags ); void SetHeight( SCROW nRow, sal_uInt16 nHeight ); void HideRow( SCROW nRow ); void SetRowSettings( SCROW nRow, sal_uInt16 nHeight, sal_uInt16 nFlags ); void SetDefaultXF( SCCOL nScCol1, SCCOL nScCol2, sal_uInt16 nXFIndex ); /** Inserts all column and row settings of the specified sheet, except the hidden flags. */ void Convert( SCTAB nScTab ); /** Sets the HIDDEN flags at all hidden columns and rows in the specified sheet. */ void ConvertHiddenFlags( SCTAB nScTab ); private: ScfUInt16Vec maWidths; /// Column widths in twips. ScfUInt8Vec maColFlags; /// Flags for all columns. ScfUInt16Vec maHeights; /// Row heights in twips. ScfUInt8Vec maRowFlags; /// Flags for all rows. SCROW mnLastScRow; sal_uInt16 mnDefWidth; /// Default width from DEFCOLWIDTH or STANDARDWIDTH record. sal_uInt16 mnDefHeight; /// Default height from DEFAULTROWHEIGHT record. sal_uInt16 mnDefRowFlags; /// Default row flags from DEFAULTROWHEIGHT record. bool mbHasStdWidthRec; /// true = Width from STANDARDWIDTH (overrides DEFCOLWIDTH record). bool mbHasDefHeight; /// true = mnDefHeight and mnDefRowFlags are valid. bool mbDirty; }; #endif <|endoftext|>
<commit_before>/******************************************************************************* * Copyright (c) 2014, 2015 IBM Corporation and others * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *******************************************************************************/ #ifndef BLEBeacon_hpp #define BLEBeacon_hpp #include <stdio.h> #include <vector> #include <map> #include <iostream> #include <sstream> #include <boost/bimap/bimap.hpp> #include "Location.hpp" #include "Beacon.hpp" namespace loc{ class BLEBeacon; using BLEBeacons = std::vector<BLEBeacon>; // BLEBeacon class class BLEBeacon : public Location{ protected: std::string uuid_; int major_; int minor_; public: template<class Archive> void serialize(Archive& ar); BLEBeacon() = default; ~BLEBeacon() = default; BLEBeacon(std::string uuid, int major, int minor, double x, double y, double z, double floor){ this->x(x); this->y(y); this->z(z); this->floor(floor); this->uuid(uuid); this->major(major); this->minor(minor); } BLEBeacon* uuid(std::string uuid){ uuid_ = uuid; return this; } BLEBeacon* major(int major){ major_ = major; return this; } BLEBeacon* minor(int minor){ minor_ = minor; return this; } std::string uuid() const{ return uuid_; } int major() const{ return major_; } int minor() const{ return minor_; } std::string toString() const{ std::stringstream strstream; strstream << uuid_ << "," << major_ << "," << minor_ << "," << this->Location::toString(); return strstream.str(); } template<class Tbeacon> static std::map<long, int> constructBeaconIdToIndexMap(std::vector<Tbeacon> beacons); template<class Tbeacon> static boost::bimaps::bimap<long, int> constructBeaconIdToIndexBimap(std::vector<Tbeacon> beacons); friend std::ostream& operator<<(std::ostream& os, const BLEBeacon& bleBeacon); }; // Definition of template method template<class Tbeacon> std::map<long, int> BLEBeacon::constructBeaconIdToIndexMap(std::vector<Tbeacon> beacons){ std::map<long, int> beaconIdIndexMap; int i = 0; for(Tbeacon b: beacons){ int major = b.major(); int minor = b.minor(); long id = Beacon::convertMajorMinorToId(major, minor); beaconIdIndexMap[id] = i; i++; } return beaconIdIndexMap; } template<class Tbeacon> boost::bimaps::bimap<long, int> BLEBeacon::constructBeaconIdToIndexBimap(std::vector<Tbeacon> beacons){ typedef boost::bimaps::bimap<long, int> bimap_type; typedef bimap_type::value_type bimap_value_type; bimap_type beaconIdIndexMap; int i = 0; for(Tbeacon b: beacons){ int major = b.major(); int minor = b.minor(); long id = Beacon::convertMajorMinorToId(major, minor); beaconIdIndexMap.insert( bimap_value_type(id, i) ); i++; } return beaconIdIndexMap; } } #endif /* BLEBeacon_hpp */ <commit_msg>Add a function to check beacon duplication<commit_after>/******************************************************************************* * Copyright (c) 2014, 2015 IBM Corporation and others * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *******************************************************************************/ #ifndef BLEBeacon_hpp #define BLEBeacon_hpp #include <stdio.h> #include <vector> #include <map> #include <iostream> #include <sstream> #include <boost/bimap/bimap.hpp> #include "Location.hpp" #include "Beacon.hpp" namespace loc{ class BLEBeacon; using BLEBeacons = std::vector<BLEBeacon>; // BLEBeacon class class BLEBeacon : public Location{ protected: std::string uuid_; int major_; int minor_; public: template<class Archive> void serialize(Archive& ar); BLEBeacon() = default; ~BLEBeacon() = default; BLEBeacon(std::string uuid, int major, int minor, double x, double y, double z, double floor){ this->x(x); this->y(y); this->z(z); this->floor(floor); this->uuid(uuid); this->major(major); this->minor(minor); } BLEBeacon* uuid(std::string uuid){ uuid_ = uuid; return this; } BLEBeacon* major(int major){ major_ = major; return this; } BLEBeacon* minor(int minor){ minor_ = minor; return this; } std::string uuid() const{ return uuid_; } int major() const{ return major_; } int minor() const{ return minor_; } std::string toString() const{ std::stringstream strstream; strstream << uuid_ << "," << major_ << "," << minor_ << "," << this->Location::toString(); return strstream.str(); } template<class Tbeacon> static bool checkNoDuplication(const std::vector<Tbeacon>& beacons); template<class Tbeacon> static std::map<long, int> constructBeaconIdToIndexMap(std::vector<Tbeacon> beacons); template<class Tbeacon> static boost::bimaps::bimap<long, int> constructBeaconIdToIndexBimap(std::vector<Tbeacon> beacons); friend std::ostream& operator<<(std::ostream& os, const BLEBeacon& bleBeacon); }; // Definition of template method template<class Tbeacon> bool BLEBeacon::checkNoDuplication(const std::vector<Tbeacon>& beacons){ std::set<long> ids; bool flag = true; for(Tbeacon b: beacons){ long id = Beacon::convertMajorMinorToId(b.major(), b.minor()); if(ids.count(id)>0){ std::stringstream ss; ss << "BLEBeacon(major=" << b.major() <<", minor=" << b.minor() << ") is duplicated"; flag = false; throw std::runtime_error(ss.str()); } ids.insert(id); } return flag; } template<class Tbeacon> std::map<long, int> BLEBeacon::constructBeaconIdToIndexMap(std::vector<Tbeacon> beacons){ assert(checkNoDuplication(beacons)==true); std::map<long, int> beaconIdIndexMap; int i = 0; for(Tbeacon b: beacons){ int major = b.major(); int minor = b.minor(); long id = Beacon::convertMajorMinorToId(major, minor); beaconIdIndexMap[id] = i; i++; } return beaconIdIndexMap; } template<class Tbeacon> boost::bimaps::bimap<long, int> BLEBeacon::constructBeaconIdToIndexBimap(std::vector<Tbeacon> beacons){ typedef boost::bimaps::bimap<long, int> bimap_type; typedef bimap_type::value_type bimap_value_type; bimap_type beaconIdIndexMap; int i = 0; for(Tbeacon b: beacons){ int major = b.major(); int minor = b.minor(); long id = Beacon::convertMajorMinorToId(major, minor); beaconIdIndexMap.insert( bimap_value_type(id, i) ); i++; } return beaconIdIndexMap; } } #endif /* BLEBeacon_hpp */ <|endoftext|>
<commit_before>//===- llvm-prof.cpp - Read in and process llvmprof.out data files --------===// // // 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 tools is meant for use with the various LLVM profiling instrumentation // passes. It reads in the data file produced by executing an instrumented // program, and outputs a nice report. // //===----------------------------------------------------------------------===// #include "ProfileInfo.h" #include "llvm/Module.h" #include "llvm/Assembly/AsmAnnotationWriter.h" #include "llvm/Bytecode/Reader.h" #include "Support/CommandLine.h" #include <iostream> #include <cstdio> #include <map> #include <set> namespace { cl::opt<std::string> BytecodeFile(cl::Positional, cl::desc("<program bytecode file>"), cl::Required); cl::opt<std::string> ProfileDataFile(cl::Positional, cl::desc("<llvmprof.out file>"), cl::Optional, cl::init("llvmprof.out")); cl::opt<bool> PrintAnnotatedLLVM("annotated-llvm", cl::desc("Print LLVM code with frequency annotations")); cl::alias PrintAnnotated2("A", cl::desc("Alias for --annotated-llvm"), cl::aliasopt(PrintAnnotatedLLVM)); } // PairSecondSort - A sorting predicate to sort by the second element of a pair. template<class T> struct PairSecondSortReverse : public std::binary_function<std::pair<T, unsigned>, std::pair<T, unsigned>, bool> { bool operator()(const std::pair<T, unsigned> &LHS, const std::pair<T, unsigned> &RHS) const { return LHS.second > RHS.second; } }; namespace { class ProfileAnnotator : public AssemblyAnnotationWriter { std::map<const Function *, unsigned> &FuncFreqs; std::map<const BasicBlock*, unsigned> &BlockFreqs; public: ProfileAnnotator(std::map<const Function *, unsigned> &FF, std::map<const BasicBlock*, unsigned> &BF) : FuncFreqs(FF), BlockFreqs(BF) {} virtual void emitFunctionAnnot(const Function *F, std::ostream &OS) { OS << ";;; %" << F->getName() << " called " << FuncFreqs[F] << " times.\n;;;\n"; } virtual void emitBasicBlockAnnot(const BasicBlock *BB, std::ostream &OS) { if (BlockFreqs.empty()) return; if (unsigned Count = BlockFreqs[BB]) OS << ";;; Executed " << Count << " times.\n"; else OS << ";;; Never executed!\n"; } }; } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv, " llvm profile dump decoder\n"); // Read in the bytecode file... std::string ErrorMessage; Module *M = ParseBytecodeFile(BytecodeFile, &ErrorMessage); if (M == 0) { std::cerr << argv[0] << ": " << BytecodeFile << ": " << ErrorMessage << "\n"; return 1; } // Read the profiling information ProfileInfo PI(argv[0], ProfileDataFile, *M); std::map<const Function *, unsigned> FuncFreqs; std::map<const BasicBlock*, unsigned> BlockFreqs; // Output a report. Eventually, there will be multiple reports selectable on // the command line, for now, just keep things simple. // Emit the most frequent function table... std::vector<std::pair<Function*, unsigned> > FunctionCounts; PI.getFunctionCounts(FunctionCounts); FuncFreqs.insert(FunctionCounts.begin(), FunctionCounts.end()); // Sort by the frequency, backwards. std::sort(FunctionCounts.begin(), FunctionCounts.end(), PairSecondSortReverse<Function*>()); unsigned TotalExecutions = 0; for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) TotalExecutions += FunctionCounts[i].second; std::cout << "===" << std::string(73, '-') << "===\n" << "LLVM profiling output for execution"; if (PI.getNumExecutions() != 1) std::cout << "s"; std::cout << ":\n"; for (unsigned i = 0, e = PI.getNumExecutions(); i != e; ++i) { std::cout << " "; if (e != 1) std::cout << i+1 << ". "; std::cout << PI.getExecution(i) << "\n"; } std::cout << "\n===" << std::string(73, '-') << "===\n"; std::cout << "Function execution frequencies:\n\n"; // Print out the function frequencies... printf(" ## Frequency\n"); for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) { if (FunctionCounts[i].second == 0) { printf("\n NOTE: %d function%s never executed!\n", e-i, e-i-1 ? "s were" : " was"); break; } printf("%3d. %5d/%d %s\n", i+1, FunctionCounts[i].second, TotalExecutions, FunctionCounts[i].first->getName().c_str()); } std::set<Function*> FunctionsToPrint; // If we have block count information, print out the LLVM module with // frequency annotations. if (PI.hasAccurateBlockCounts()) { std::vector<std::pair<BasicBlock*, unsigned> > Counts; PI.getBlockCounts(Counts); TotalExecutions = 0; for (unsigned i = 0, e = Counts.size(); i != e; ++i) TotalExecutions += Counts[i].second; // Sort by the frequency, backwards. std::sort(Counts.begin(), Counts.end(), PairSecondSortReverse<BasicBlock*>()); std::cout << "\n===" << std::string(73, '-') << "===\n"; std::cout << "Top 20 most frequently executed basic blocks:\n\n"; // Print out the function frequencies... printf(" ## Frequency\n"); unsigned BlocksToPrint = Counts.size(); if (BlocksToPrint > 20) BlocksToPrint = 20; for (unsigned i = 0; i != BlocksToPrint; ++i) { Function *F = Counts[i].first->getParent(); printf("%3d. %5d/%d %s() - %s\n", i+1, Counts[i].second, TotalExecutions, F->getName().c_str(), Counts[i].first->getName().c_str()); FunctionsToPrint.insert(F); } BlockFreqs.insert(Counts.begin(), Counts.end()); } if (PrintAnnotatedLLVM) { std::cout << "\n===" << std::string(73, '-') << "===\n"; std::cout << "Annotated LLVM code for the module:\n\n"; if (FunctionsToPrint.empty()) for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) FunctionsToPrint.insert(I); ProfileAnnotator PA(FuncFreqs, BlockFreqs); for (std::set<Function*>::iterator I = FunctionsToPrint.begin(), E = FunctionsToPrint.end(); I != E; ++I) (*I)->print(std::cout, &PA); } return 0; } <commit_msg>Hrm, some of my counters are wrapping around 32 bits<commit_after>//===- llvm-prof.cpp - Read in and process llvmprof.out data files --------===// // // 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 tools is meant for use with the various LLVM profiling instrumentation // passes. It reads in the data file produced by executing an instrumented // program, and outputs a nice report. // //===----------------------------------------------------------------------===// #include "ProfileInfo.h" #include "llvm/Module.h" #include "llvm/Assembly/AsmAnnotationWriter.h" #include "llvm/Bytecode/Reader.h" #include "Support/CommandLine.h" #include <iostream> #include <cstdio> #include <map> #include <set> namespace { cl::opt<std::string> BytecodeFile(cl::Positional, cl::desc("<program bytecode file>"), cl::Required); cl::opt<std::string> ProfileDataFile(cl::Positional, cl::desc("<llvmprof.out file>"), cl::Optional, cl::init("llvmprof.out")); cl::opt<bool> PrintAnnotatedLLVM("annotated-llvm", cl::desc("Print LLVM code with frequency annotations")); cl::alias PrintAnnotated2("A", cl::desc("Alias for --annotated-llvm"), cl::aliasopt(PrintAnnotatedLLVM)); } // PairSecondSort - A sorting predicate to sort by the second element of a pair. template<class T> struct PairSecondSortReverse : public std::binary_function<std::pair<T, unsigned>, std::pair<T, unsigned>, bool> { bool operator()(const std::pair<T, unsigned> &LHS, const std::pair<T, unsigned> &RHS) const { return LHS.second > RHS.second; } }; namespace { class ProfileAnnotator : public AssemblyAnnotationWriter { std::map<const Function *, unsigned> &FuncFreqs; std::map<const BasicBlock*, unsigned> &BlockFreqs; public: ProfileAnnotator(std::map<const Function *, unsigned> &FF, std::map<const BasicBlock*, unsigned> &BF) : FuncFreqs(FF), BlockFreqs(BF) {} virtual void emitFunctionAnnot(const Function *F, std::ostream &OS) { OS << ";;; %" << F->getName() << " called " << FuncFreqs[F] << " times.\n;;;\n"; } virtual void emitBasicBlockAnnot(const BasicBlock *BB, std::ostream &OS) { if (BlockFreqs.empty()) return; if (unsigned Count = BlockFreqs[BB]) OS << ";;; Executed " << Count << " times.\n"; else OS << ";;; Never executed!\n"; } }; } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv, " llvm profile dump decoder\n"); // Read in the bytecode file... std::string ErrorMessage; Module *M = ParseBytecodeFile(BytecodeFile, &ErrorMessage); if (M == 0) { std::cerr << argv[0] << ": " << BytecodeFile << ": " << ErrorMessage << "\n"; return 1; } // Read the profiling information ProfileInfo PI(argv[0], ProfileDataFile, *M); std::map<const Function *, unsigned> FuncFreqs; std::map<const BasicBlock*, unsigned> BlockFreqs; // Output a report. Eventually, there will be multiple reports selectable on // the command line, for now, just keep things simple. // Emit the most frequent function table... std::vector<std::pair<Function*, unsigned> > FunctionCounts; PI.getFunctionCounts(FunctionCounts); FuncFreqs.insert(FunctionCounts.begin(), FunctionCounts.end()); // Sort by the frequency, backwards. std::sort(FunctionCounts.begin(), FunctionCounts.end(), PairSecondSortReverse<Function*>()); unsigned long long TotalExecutions = 0; for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) TotalExecutions += FunctionCounts[i].second; std::cout << "===" << std::string(73, '-') << "===\n" << "LLVM profiling output for execution"; if (PI.getNumExecutions() != 1) std::cout << "s"; std::cout << ":\n"; for (unsigned i = 0, e = PI.getNumExecutions(); i != e; ++i) { std::cout << " "; if (e != 1) std::cout << i+1 << ". "; std::cout << PI.getExecution(i) << "\n"; } std::cout << "\n===" << std::string(73, '-') << "===\n"; std::cout << "Function execution frequencies:\n\n"; // Print out the function frequencies... printf(" ## Frequency\n"); for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) { if (FunctionCounts[i].second == 0) { printf("\n NOTE: %d function%s never executed!\n", e-i, e-i-1 ? "s were" : " was"); break; } printf("%3d. %5u/%llu %s\n", i+1, FunctionCounts[i].second, TotalExecutions, FunctionCounts[i].first->getName().c_str()); } std::set<Function*> FunctionsToPrint; // If we have block count information, print out the LLVM module with // frequency annotations. if (PI.hasAccurateBlockCounts()) { std::vector<std::pair<BasicBlock*, unsigned> > Counts; PI.getBlockCounts(Counts); TotalExecutions = 0; for (unsigned i = 0, e = Counts.size(); i != e; ++i) TotalExecutions += Counts[i].second; // Sort by the frequency, backwards. std::sort(Counts.begin(), Counts.end(), PairSecondSortReverse<BasicBlock*>()); std::cout << "\n===" << std::string(73, '-') << "===\n"; std::cout << "Top 20 most frequently executed basic blocks:\n\n"; // Print out the function frequencies... printf(" ## \tFrequency\n"); unsigned BlocksToPrint = Counts.size(); if (BlocksToPrint > 20) BlocksToPrint = 20; for (unsigned i = 0; i != BlocksToPrint; ++i) { Function *F = Counts[i].first->getParent(); printf("%3d. %5u/%llu\t%s() - %s\n", i+1, Counts[i].second, TotalExecutions, F->getName().c_str(), Counts[i].first->getName().c_str()); FunctionsToPrint.insert(F); } BlockFreqs.insert(Counts.begin(), Counts.end()); } if (PrintAnnotatedLLVM) { std::cout << "\n===" << std::string(73, '-') << "===\n"; std::cout << "Annotated LLVM code for the module:\n\n"; if (FunctionsToPrint.empty()) for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) FunctionsToPrint.insert(I); ProfileAnnotator PA(FuncFreqs, BlockFreqs); for (std::set<Function*>::iterator I = FunctionsToPrint.begin(), E = FunctionsToPrint.end(); I != E; ++I) (*I)->print(std::cout, &PA); } 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 "media/base/android/media_player_bridge.h" #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/basictypes.h" #include "base/logging.h" #include "base/stringprintf.h" #include "base/message_loop_proxy.h" #include "jni/MediaPlayerBridge_jni.h" #include "jni/MediaPlayer_jni.h" #include "media/base/android/media_player_bridge_manager.h" #include "media/base/android/media_resource_getter.h" using base::android::ConvertUTF8ToJavaString; using base::android::ScopedJavaLocalRef; // Time update happens every 250ms. static const int kTimeUpdateInterval = 250; // Because we create the media player lazily on android, the duration of the // media is initially unknown to us. This makes the user unable to perform // seek. To solve this problem, we use a temporary duration of 100 seconds when // the duration is unknown. And we scale the seek position later when duration // is available. // TODO(qinmin): create a thread and use android MediaMetadataRetriever // class to extract the duration. static const int kTemporaryDuration = 100; namespace media { MediaPlayerBridge::MediaPlayerBridge( int player_id, const GURL& url, const GURL& first_party_for_cookies, MediaResourceGetter* resource_getter, bool hide_url_log, MediaPlayerBridgeManager* manager, const MediaErrorCB& media_error_cb, const VideoSizeChangedCB& video_size_changed_cb, const BufferingUpdateCB& buffering_update_cb, const MediaPreparedCB& media_prepared_cb, const PlaybackCompleteCB& playback_complete_cb, const SeekCompleteCB& seek_complete_cb, const TimeUpdateCB& time_update_cb, const MediaInterruptedCB& media_interrupted_cb) : media_error_cb_(media_error_cb), video_size_changed_cb_(video_size_changed_cb), buffering_update_cb_(buffering_update_cb), media_prepared_cb_(media_prepared_cb), playback_complete_cb_(playback_complete_cb), seek_complete_cb_(seek_complete_cb), media_interrupted_cb_(media_interrupted_cb), time_update_cb_(time_update_cb), player_id_(player_id), prepared_(false), pending_play_(false), url_(url), first_party_for_cookies_(first_party_for_cookies), hide_url_log_(hide_url_log), duration_(base::TimeDelta::FromSeconds(kTemporaryDuration)), width_(0), height_(0), can_pause_(true), can_seek_forward_(true), can_seek_backward_(true), manager_(manager), resource_getter_(resource_getter), ALLOW_THIS_IN_INITIALIZER_LIST(weak_this_(this)), listener_(base::MessageLoopProxy::current(), weak_this_.GetWeakPtr()) { has_cookies_ = url_.SchemeIsFileSystem() || url_.SchemeIsFile(); } MediaPlayerBridge::~MediaPlayerBridge() { Release(); } void MediaPlayerBridge::InitializePlayer() { JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); j_media_player_.Reset(JNI_MediaPlayer::Java_MediaPlayer_Constructor(env)); jobject j_context = base::android::GetApplicationContext(); DCHECK(j_context); listener_.CreateMediaPlayerListener(j_context, j_media_player_.obj()); } void MediaPlayerBridge::SetVideoSurface(jobject surface) { if (j_media_player_.is_null() && surface != NULL) Prepare(); JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); JNI_MediaPlayer::Java_MediaPlayer_setSurface( env, j_media_player_.obj(), surface); } void MediaPlayerBridge::Prepare() { if (j_media_player_.is_null()) InitializePlayer(); if (has_cookies_) { GetCookiesCallback(cookies_); } else { resource_getter_->GetCookies(url_, first_party_for_cookies_, base::Bind( &MediaPlayerBridge::GetCookiesCallback, weak_this_.GetWeakPtr())); } } void MediaPlayerBridge::GetCookiesCallback(const std::string& cookies) { cookies_ = cookies; has_cookies_ = true; if (j_media_player_.is_null()) return; if (url_.SchemeIsFileSystem()) { resource_getter_->GetPlatformPathFromFileSystemURL(url_, base::Bind( &MediaPlayerBridge::SetDataSource, weak_this_.GetWeakPtr())); } else { SetDataSource(url_.spec()); } } void MediaPlayerBridge::SetDataSource(const std::string& url) { if (j_media_player_.is_null()) return; JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); // Create a Java String for the URL. ScopedJavaLocalRef<jstring> j_url_string = ConvertUTF8ToJavaString(env, url); ScopedJavaLocalRef<jstring> j_cookies = ConvertUTF8ToJavaString( env, cookies_); jobject j_context = base::android::GetApplicationContext(); DCHECK(j_context); if (Java_MediaPlayerBridge_setDataSource( env, j_media_player_.obj(), j_context, j_url_string.obj(), j_cookies.obj(), hide_url_log_)) { if (manager_) manager_->RequestMediaResources(this); JNI_MediaPlayer::Java_MediaPlayer_prepareAsync( env, j_media_player_.obj()); } else { media_error_cb_.Run(player_id_, MEDIA_ERROR_FORMAT); } } void MediaPlayerBridge::Start() { if (j_media_player_.is_null()) { pending_play_ = true; Prepare(); } else { if (prepared_) StartInternal(); else pending_play_ = true; } } void MediaPlayerBridge::Pause() { if (j_media_player_.is_null()) { pending_play_ = false; } else { if (prepared_ && IsPlaying()) PauseInternal(); else pending_play_ = false; } } bool MediaPlayerBridge::IsPlaying() { if (!prepared_) return pending_play_; JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); jboolean result = JNI_MediaPlayer::Java_MediaPlayer_isPlaying( env, j_media_player_.obj()); return result; } int MediaPlayerBridge::GetVideoWidth() { if (!prepared_) return width_; JNIEnv* env = base::android::AttachCurrentThread(); return JNI_MediaPlayer::Java_MediaPlayer_getVideoWidth( env, j_media_player_.obj()); } int MediaPlayerBridge::GetVideoHeight() { if (!prepared_) return height_; JNIEnv* env = base::android::AttachCurrentThread(); return JNI_MediaPlayer::Java_MediaPlayer_getVideoHeight( env, j_media_player_.obj()); } void MediaPlayerBridge::SeekTo(base::TimeDelta time) { // Record the time to seek when OnMediaPrepared() is called. pending_seek_ = time; if (j_media_player_.is_null()) Prepare(); else if (prepared_) SeekInternal(time); } base::TimeDelta MediaPlayerBridge::GetCurrentTime() { if (!prepared_) return pending_seek_; JNIEnv* env = base::android::AttachCurrentThread(); return base::TimeDelta::FromMilliseconds( JNI_MediaPlayer::Java_MediaPlayer_getCurrentPosition( env, j_media_player_.obj())); } base::TimeDelta MediaPlayerBridge::GetDuration() { if (!prepared_) return duration_; JNIEnv* env = base::android::AttachCurrentThread(); return base::TimeDelta::FromMilliseconds( JNI_MediaPlayer::Java_MediaPlayer_getDuration( env, j_media_player_.obj())); } void MediaPlayerBridge::Release() { if (j_media_player_.is_null()) return; time_update_timer_.Stop(); if (prepared_) pending_seek_ = GetCurrentTime(); if (manager_) manager_->ReleaseMediaResources(this); prepared_ = false; pending_play_ = false; SetVideoSurface(NULL); JNIEnv* env = base::android::AttachCurrentThread(); JNI_MediaPlayer::Java_MediaPlayer_release(env, j_media_player_.obj()); j_media_player_.Reset(); listener_.ReleaseMediaPlayerListenerResources(); } void MediaPlayerBridge::SetVolume(float left_volume, float right_volume) { if (j_media_player_.is_null()) return; JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); JNI_MediaPlayer::Java_MediaPlayer_setVolume( env, j_media_player_.obj(), left_volume, right_volume); } void MediaPlayerBridge::DoTimeUpdate() { base::TimeDelta current = GetCurrentTime(); time_update_cb_.Run(player_id_, current); } void MediaPlayerBridge::OnMediaError(int error_type) { media_error_cb_.Run(player_id_, error_type); } void MediaPlayerBridge::OnVideoSizeChanged(int width, int height) { width_ = width; height_ = height; video_size_changed_cb_.Run(player_id_, width, height); } void MediaPlayerBridge::OnBufferingUpdate(int percent) { buffering_update_cb_.Run(player_id_, percent); } void MediaPlayerBridge::OnPlaybackComplete() { time_update_timer_.Stop(); playback_complete_cb_.Run(player_id_); } void MediaPlayerBridge::OnMediaInterrupted() { time_update_timer_.Stop(); media_interrupted_cb_.Run(player_id_); } void MediaPlayerBridge::OnSeekComplete() { seek_complete_cb_.Run(player_id_, GetCurrentTime()); } void MediaPlayerBridge::OnMediaPrepared() { if (j_media_player_.is_null()) return; prepared_ = true; base::TimeDelta dur = duration_; duration_ = GetDuration(); if (duration_ != dur && 0 != dur.InMilliseconds()) { // Scale the |pending_seek_| according to the new duration. pending_seek_ = base::TimeDelta::FromSeconds( pending_seek_.InSecondsF() * duration_.InSecondsF() / dur.InSecondsF()); } // If media player was recovered from a saved state, consume all the pending // events. SeekInternal(pending_seek_); if (pending_play_) { StartInternal(); pending_play_ = false; } GetMetadata(); media_prepared_cb_.Run(player_id_, duration_); } void MediaPlayerBridge::GetMetadata() { JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); ScopedJavaLocalRef<jobject> allowedOperations = Java_MediaPlayerBridge_getAllowedOperations(env, j_media_player_.obj()); can_pause_ = Java_AllowedOperations_canPause(env, allowedOperations.obj()); can_seek_forward_ = Java_AllowedOperations_canSeekForward( env, allowedOperations.obj()); can_seek_backward_ = Java_AllowedOperations_canSeekBackward( env, allowedOperations.obj()); } void MediaPlayerBridge::StartInternal() { JNIEnv* env = base::android::AttachCurrentThread(); JNI_MediaPlayer::Java_MediaPlayer_start(env, j_media_player_.obj()); if (!time_update_timer_.IsRunning()) { time_update_timer_.Start( FROM_HERE, base::TimeDelta::FromMilliseconds(kTimeUpdateInterval), this, &MediaPlayerBridge::DoTimeUpdate); } } void MediaPlayerBridge::PauseInternal() { JNIEnv* env = base::android::AttachCurrentThread(); JNI_MediaPlayer::Java_MediaPlayer_pause(env, j_media_player_.obj()); time_update_timer_.Stop(); } void MediaPlayerBridge::SeekInternal(base::TimeDelta time) { JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); int time_msec = static_cast<int>(time.InMilliseconds()); JNI_MediaPlayer::Java_MediaPlayer_seekTo( env, j_media_player_.obj(), time_msec); } bool MediaPlayerBridge::RegisterMediaPlayerBridge(JNIEnv* env) { bool ret = RegisterNativesImpl(env); DCHECK(g_MediaPlayerBridge_clazz); if (ret) ret = JNI_MediaPlayer::RegisterNativesImpl(env); return ret; } } // namespace media <commit_msg>Skip SetVideoSurface when |j_media_player_| and |surface| are null<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 "media/base/android/media_player_bridge.h" #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/basictypes.h" #include "base/logging.h" #include "base/stringprintf.h" #include "base/message_loop_proxy.h" #include "jni/MediaPlayerBridge_jni.h" #include "jni/MediaPlayer_jni.h" #include "media/base/android/media_player_bridge_manager.h" #include "media/base/android/media_resource_getter.h" using base::android::ConvertUTF8ToJavaString; using base::android::ScopedJavaLocalRef; // Time update happens every 250ms. static const int kTimeUpdateInterval = 250; // Because we create the media player lazily on android, the duration of the // media is initially unknown to us. This makes the user unable to perform // seek. To solve this problem, we use a temporary duration of 100 seconds when // the duration is unknown. And we scale the seek position later when duration // is available. // TODO(qinmin): create a thread and use android MediaMetadataRetriever // class to extract the duration. static const int kTemporaryDuration = 100; namespace media { MediaPlayerBridge::MediaPlayerBridge( int player_id, const GURL& url, const GURL& first_party_for_cookies, MediaResourceGetter* resource_getter, bool hide_url_log, MediaPlayerBridgeManager* manager, const MediaErrorCB& media_error_cb, const VideoSizeChangedCB& video_size_changed_cb, const BufferingUpdateCB& buffering_update_cb, const MediaPreparedCB& media_prepared_cb, const PlaybackCompleteCB& playback_complete_cb, const SeekCompleteCB& seek_complete_cb, const TimeUpdateCB& time_update_cb, const MediaInterruptedCB& media_interrupted_cb) : media_error_cb_(media_error_cb), video_size_changed_cb_(video_size_changed_cb), buffering_update_cb_(buffering_update_cb), media_prepared_cb_(media_prepared_cb), playback_complete_cb_(playback_complete_cb), seek_complete_cb_(seek_complete_cb), media_interrupted_cb_(media_interrupted_cb), time_update_cb_(time_update_cb), player_id_(player_id), prepared_(false), pending_play_(false), url_(url), first_party_for_cookies_(first_party_for_cookies), hide_url_log_(hide_url_log), duration_(base::TimeDelta::FromSeconds(kTemporaryDuration)), width_(0), height_(0), can_pause_(true), can_seek_forward_(true), can_seek_backward_(true), manager_(manager), resource_getter_(resource_getter), ALLOW_THIS_IN_INITIALIZER_LIST(weak_this_(this)), listener_(base::MessageLoopProxy::current(), weak_this_.GetWeakPtr()) { has_cookies_ = url_.SchemeIsFileSystem() || url_.SchemeIsFile(); } MediaPlayerBridge::~MediaPlayerBridge() { Release(); } void MediaPlayerBridge::InitializePlayer() { JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); j_media_player_.Reset(JNI_MediaPlayer::Java_MediaPlayer_Constructor(env)); jobject j_context = base::android::GetApplicationContext(); DCHECK(j_context); listener_.CreateMediaPlayerListener(j_context, j_media_player_.obj()); } void MediaPlayerBridge::SetVideoSurface(jobject surface) { if (j_media_player_.is_null()) { if (surface == NULL) return; Prepare(); } JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); JNI_MediaPlayer::Java_MediaPlayer_setSurface( env, j_media_player_.obj(), surface); } void MediaPlayerBridge::Prepare() { if (j_media_player_.is_null()) InitializePlayer(); if (has_cookies_) { GetCookiesCallback(cookies_); } else { resource_getter_->GetCookies(url_, first_party_for_cookies_, base::Bind( &MediaPlayerBridge::GetCookiesCallback, weak_this_.GetWeakPtr())); } } void MediaPlayerBridge::GetCookiesCallback(const std::string& cookies) { cookies_ = cookies; has_cookies_ = true; if (j_media_player_.is_null()) return; if (url_.SchemeIsFileSystem()) { resource_getter_->GetPlatformPathFromFileSystemURL(url_, base::Bind( &MediaPlayerBridge::SetDataSource, weak_this_.GetWeakPtr())); } else { SetDataSource(url_.spec()); } } void MediaPlayerBridge::SetDataSource(const std::string& url) { if (j_media_player_.is_null()) return; JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); // Create a Java String for the URL. ScopedJavaLocalRef<jstring> j_url_string = ConvertUTF8ToJavaString(env, url); ScopedJavaLocalRef<jstring> j_cookies = ConvertUTF8ToJavaString( env, cookies_); jobject j_context = base::android::GetApplicationContext(); DCHECK(j_context); if (Java_MediaPlayerBridge_setDataSource( env, j_media_player_.obj(), j_context, j_url_string.obj(), j_cookies.obj(), hide_url_log_)) { if (manager_) manager_->RequestMediaResources(this); JNI_MediaPlayer::Java_MediaPlayer_prepareAsync( env, j_media_player_.obj()); } else { media_error_cb_.Run(player_id_, MEDIA_ERROR_FORMAT); } } void MediaPlayerBridge::Start() { if (j_media_player_.is_null()) { pending_play_ = true; Prepare(); } else { if (prepared_) StartInternal(); else pending_play_ = true; } } void MediaPlayerBridge::Pause() { if (j_media_player_.is_null()) { pending_play_ = false; } else { if (prepared_ && IsPlaying()) PauseInternal(); else pending_play_ = false; } } bool MediaPlayerBridge::IsPlaying() { if (!prepared_) return pending_play_; JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); jboolean result = JNI_MediaPlayer::Java_MediaPlayer_isPlaying( env, j_media_player_.obj()); return result; } int MediaPlayerBridge::GetVideoWidth() { if (!prepared_) return width_; JNIEnv* env = base::android::AttachCurrentThread(); return JNI_MediaPlayer::Java_MediaPlayer_getVideoWidth( env, j_media_player_.obj()); } int MediaPlayerBridge::GetVideoHeight() { if (!prepared_) return height_; JNIEnv* env = base::android::AttachCurrentThread(); return JNI_MediaPlayer::Java_MediaPlayer_getVideoHeight( env, j_media_player_.obj()); } void MediaPlayerBridge::SeekTo(base::TimeDelta time) { // Record the time to seek when OnMediaPrepared() is called. pending_seek_ = time; if (j_media_player_.is_null()) Prepare(); else if (prepared_) SeekInternal(time); } base::TimeDelta MediaPlayerBridge::GetCurrentTime() { if (!prepared_) return pending_seek_; JNIEnv* env = base::android::AttachCurrentThread(); return base::TimeDelta::FromMilliseconds( JNI_MediaPlayer::Java_MediaPlayer_getCurrentPosition( env, j_media_player_.obj())); } base::TimeDelta MediaPlayerBridge::GetDuration() { if (!prepared_) return duration_; JNIEnv* env = base::android::AttachCurrentThread(); return base::TimeDelta::FromMilliseconds( JNI_MediaPlayer::Java_MediaPlayer_getDuration( env, j_media_player_.obj())); } void MediaPlayerBridge::Release() { if (j_media_player_.is_null()) return; time_update_timer_.Stop(); if (prepared_) pending_seek_ = GetCurrentTime(); if (manager_) manager_->ReleaseMediaResources(this); prepared_ = false; pending_play_ = false; SetVideoSurface(NULL); JNIEnv* env = base::android::AttachCurrentThread(); JNI_MediaPlayer::Java_MediaPlayer_release(env, j_media_player_.obj()); j_media_player_.Reset(); listener_.ReleaseMediaPlayerListenerResources(); } void MediaPlayerBridge::SetVolume(float left_volume, float right_volume) { if (j_media_player_.is_null()) return; JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); JNI_MediaPlayer::Java_MediaPlayer_setVolume( env, j_media_player_.obj(), left_volume, right_volume); } void MediaPlayerBridge::DoTimeUpdate() { base::TimeDelta current = GetCurrentTime(); time_update_cb_.Run(player_id_, current); } void MediaPlayerBridge::OnMediaError(int error_type) { media_error_cb_.Run(player_id_, error_type); } void MediaPlayerBridge::OnVideoSizeChanged(int width, int height) { width_ = width; height_ = height; video_size_changed_cb_.Run(player_id_, width, height); } void MediaPlayerBridge::OnBufferingUpdate(int percent) { buffering_update_cb_.Run(player_id_, percent); } void MediaPlayerBridge::OnPlaybackComplete() { time_update_timer_.Stop(); playback_complete_cb_.Run(player_id_); } void MediaPlayerBridge::OnMediaInterrupted() { time_update_timer_.Stop(); media_interrupted_cb_.Run(player_id_); } void MediaPlayerBridge::OnSeekComplete() { seek_complete_cb_.Run(player_id_, GetCurrentTime()); } void MediaPlayerBridge::OnMediaPrepared() { if (j_media_player_.is_null()) return; prepared_ = true; base::TimeDelta dur = duration_; duration_ = GetDuration(); if (duration_ != dur && 0 != dur.InMilliseconds()) { // Scale the |pending_seek_| according to the new duration. pending_seek_ = base::TimeDelta::FromSeconds( pending_seek_.InSecondsF() * duration_.InSecondsF() / dur.InSecondsF()); } // If media player was recovered from a saved state, consume all the pending // events. SeekInternal(pending_seek_); if (pending_play_) { StartInternal(); pending_play_ = false; } GetMetadata(); media_prepared_cb_.Run(player_id_, duration_); } void MediaPlayerBridge::GetMetadata() { JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); ScopedJavaLocalRef<jobject> allowedOperations = Java_MediaPlayerBridge_getAllowedOperations(env, j_media_player_.obj()); can_pause_ = Java_AllowedOperations_canPause(env, allowedOperations.obj()); can_seek_forward_ = Java_AllowedOperations_canSeekForward( env, allowedOperations.obj()); can_seek_backward_ = Java_AllowedOperations_canSeekBackward( env, allowedOperations.obj()); } void MediaPlayerBridge::StartInternal() { JNIEnv* env = base::android::AttachCurrentThread(); JNI_MediaPlayer::Java_MediaPlayer_start(env, j_media_player_.obj()); if (!time_update_timer_.IsRunning()) { time_update_timer_.Start( FROM_HERE, base::TimeDelta::FromMilliseconds(kTimeUpdateInterval), this, &MediaPlayerBridge::DoTimeUpdate); } } void MediaPlayerBridge::PauseInternal() { JNIEnv* env = base::android::AttachCurrentThread(); JNI_MediaPlayer::Java_MediaPlayer_pause(env, j_media_player_.obj()); time_update_timer_.Stop(); } void MediaPlayerBridge::SeekInternal(base::TimeDelta time) { JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); int time_msec = static_cast<int>(time.InMilliseconds()); JNI_MediaPlayer::Java_MediaPlayer_seekTo( env, j_media_player_.obj(), time_msec); } bool MediaPlayerBridge::RegisterMediaPlayerBridge(JNIEnv* env) { bool ret = RegisterNativesImpl(env); DCHECK(g_MediaPlayerBridge_clazz); if (ret) ret = JNI_MediaPlayer::RegisterNativesImpl(env); return ret; } } // namespace media <|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/>. */ #pragma once #include "bytes.hh" #include "timestamp.hh" #include "tombstone.hh" #include "gc_clock.hh" #include "utils/managed_bytes.hh" #include <seastar/net//byteorder.hh> #include <cstdint> #include <iosfwd> #include "data/cell.hh" #include "data/schema_info.hh" #include "imr/utils.hh" #include "utils/fragmented_temporary_buffer.hh" #include "serializer.hh" class abstract_type; class collection_type_impl; using atomic_cell_value_view = data::value_view; using atomic_cell_value_mutable_view = data::value_mutable_view; /// View of an atomic cell template<mutable_view is_mutable> class basic_atomic_cell_view { protected: data::cell::basic_atomic_cell_view<is_mutable> _view; friend class atomic_cell; public: using pointer_type = std::conditional_t<is_mutable == mutable_view::no, const uint8_t*, uint8_t*>; protected: explicit basic_atomic_cell_view(data::cell::basic_atomic_cell_view<is_mutable> v) : _view(std::move(v)) { } basic_atomic_cell_view(const data::type_info& ti, pointer_type ptr) : _view(data::cell::make_atomic_cell_view(ti, ptr)) { } friend class atomic_cell_or_collection; public: operator basic_atomic_cell_view<mutable_view::no>() const noexcept { return basic_atomic_cell_view<mutable_view::no>(_view); } void swap(basic_atomic_cell_view& other) noexcept { using std::swap; swap(_view, other._view); } bool is_counter_update() const { return _view.is_counter_update(); } bool is_live() const { return _view.is_live(); } bool is_live(tombstone t, bool is_counter) const { return is_live() && !is_covered_by(t, is_counter); } bool is_live(tombstone t, gc_clock::time_point now, bool is_counter) const { return is_live() && !is_covered_by(t, is_counter) && !has_expired(now); } bool is_live_and_has_ttl() const { return _view.is_expiring(); } bool is_dead(gc_clock::time_point now) const { return !is_live() || has_expired(now); } bool is_covered_by(tombstone t, bool is_counter) const { return timestamp() <= t.timestamp || (is_counter && t.timestamp != api::missing_timestamp); } // Can be called on live and dead cells api::timestamp_type timestamp() const { return _view.timestamp(); } void set_timestamp(api::timestamp_type ts) { _view.set_timestamp(ts); } // Can be called on live cells only data::basic_value_view<is_mutable> value() const { return _view.value(); } // Can be called on live cells only size_t value_size() const { return _view.value_size(); } bool is_value_fragmented() const { return _view.is_value_fragmented(); } // Can be called on live counter update cells only int64_t counter_update_value() const { return _view.counter_update_value(); } // Can be called only when is_dead(gc_clock::time_point) gc_clock::time_point deletion_time() const { return !is_live() ? _view.deletion_time() : expiry() - ttl(); } // Can be called only when is_live_and_has_ttl() gc_clock::time_point expiry() const { return _view.expiry(); } // Can be called only when is_live_and_has_ttl() gc_clock::duration ttl() const { return _view.ttl(); } // Can be called on live and dead cells bool has_expired(gc_clock::time_point now) const { return is_live_and_has_ttl() && expiry() <= now; } bytes_view serialize() const { return _view.serialize(); } }; class atomic_cell_view final : public basic_atomic_cell_view<mutable_view::no> { atomic_cell_view(const data::type_info& ti, const uint8_t* data) : basic_atomic_cell_view<mutable_view::no>(ti, data) {} template<mutable_view is_mutable> atomic_cell_view(data::cell::basic_atomic_cell_view<is_mutable> view) : basic_atomic_cell_view<mutable_view::no>(view) { } friend class atomic_cell; public: static atomic_cell_view from_bytes(const data::type_info& ti, const imr::utils::object<data::cell::structure>& data) { return atomic_cell_view(ti, data.get()); } static atomic_cell_view from_bytes(const data::type_info& ti, bytes_view bv) { return atomic_cell_view(ti, reinterpret_cast<const uint8_t*>(bv.begin())); } friend std::ostream& operator<<(std::ostream& os, const atomic_cell_view& acv); class printer { const abstract_type& _type; const atomic_cell_view& _cell; public: printer(const abstract_type& type, const atomic_cell_view& cell) : _type(type), _cell(cell) {} friend std::ostream& operator<<(std::ostream& os, const printer& acvp); }; }; class atomic_cell_mutable_view final : public basic_atomic_cell_view<mutable_view::yes> { atomic_cell_mutable_view(const data::type_info& ti, uint8_t* data) : basic_atomic_cell_view<mutable_view::yes>(ti, data) {} public: static atomic_cell_mutable_view from_bytes(const data::type_info& ti, imr::utils::object<data::cell::structure>& data) { return atomic_cell_mutable_view(ti, data.get()); } friend class atomic_cell; }; using atomic_cell_ref = atomic_cell_mutable_view; class atomic_cell final : public basic_atomic_cell_view<mutable_view::yes> { using imr_object_type = imr::utils::object<data::cell::structure>; imr_object_type _data; atomic_cell(const data::type_info& ti, imr::utils::object<data::cell::structure>&& data) : basic_atomic_cell_view<mutable_view::yes>(ti, data.get()), _data(std::move(data)) {} public: class collection_member_tag; using collection_member = bool_class<collection_member_tag>; atomic_cell(atomic_cell&&) = default; atomic_cell& operator=(const atomic_cell&) = delete; atomic_cell& operator=(atomic_cell&&) = default; void swap(atomic_cell& other) noexcept { basic_atomic_cell_view<mutable_view::yes>::swap(other); _data.swap(other._data); } operator atomic_cell_view() const { return atomic_cell_view(_view); } atomic_cell(const abstract_type& t, atomic_cell_view other); static atomic_cell make_dead(api::timestamp_type timestamp, gc_clock::time_point deletion_time); static atomic_cell make_live(const abstract_type& type, api::timestamp_type timestamp, bytes_view value, collection_member = collection_member::no); static atomic_cell make_live(const abstract_type& type, api::timestamp_type timestamp, ser::buffer_view<bytes_ostream::fragment_iterator> value, collection_member = collection_member::no); static atomic_cell make_live(const abstract_type& type, api::timestamp_type timestamp, const fragmented_temporary_buffer::view& value, collection_member = collection_member::no); static atomic_cell make_live(const abstract_type& type, api::timestamp_type timestamp, const bytes& value, collection_member cm = collection_member::no) { return make_live(type, timestamp, bytes_view(value), cm); } static atomic_cell make_live_counter_update(api::timestamp_type timestamp, int64_t value); static atomic_cell make_live(const abstract_type&, api::timestamp_type timestamp, bytes_view value, gc_clock::time_point expiry, gc_clock::duration ttl, collection_member = collection_member::no); static atomic_cell make_live(const abstract_type&, api::timestamp_type timestamp, ser::buffer_view<bytes_ostream::fragment_iterator> value, gc_clock::time_point expiry, gc_clock::duration ttl, collection_member = collection_member::no); static atomic_cell make_live(const abstract_type&, api::timestamp_type timestamp, const fragmented_temporary_buffer::view& value, gc_clock::time_point expiry, gc_clock::duration ttl, collection_member = collection_member::no); static atomic_cell make_live(const abstract_type& type, api::timestamp_type timestamp, const bytes& value, gc_clock::time_point expiry, gc_clock::duration ttl, collection_member cm = collection_member::no) { return make_live(type, timestamp, bytes_view(value), expiry, ttl, cm); } static atomic_cell make_live(const abstract_type& type, api::timestamp_type timestamp, bytes_view value, ttl_opt ttl, collection_member cm = collection_member::no) { if (!ttl) { return make_live(type, timestamp, value, cm); } else { return make_live(type, timestamp, value, gc_clock::now() + *ttl, *ttl, cm); } } static atomic_cell make_live_uninitialized(const abstract_type& type, api::timestamp_type timestamp, size_t size); friend class atomic_cell_or_collection; friend std::ostream& operator<<(std::ostream& os, const atomic_cell& ac); class printer : atomic_cell_view::printer { public: printer(const abstract_type& type, const atomic_cell_view& cell) : atomic_cell_view::printer(type, cell) {} friend std::ostream& operator<<(std::ostream& os, const printer& acvp); }; }; class column_definition; int compare_atomic_cell_for_merge(atomic_cell_view left, atomic_cell_view right); void merge_column(const abstract_type& def, atomic_cell_or_collection& old, const atomic_cell_or_collection& neww); <commit_msg>atomic_cell.hh: forward-declare atomic_cell_or_collection<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/>. */ #pragma once #include "bytes.hh" #include "timestamp.hh" #include "tombstone.hh" #include "gc_clock.hh" #include "utils/managed_bytes.hh" #include <seastar/net//byteorder.hh> #include <cstdint> #include <iosfwd> #include "data/cell.hh" #include "data/schema_info.hh" #include "imr/utils.hh" #include "utils/fragmented_temporary_buffer.hh" #include "serializer.hh" class abstract_type; class collection_type_impl; class atomic_cell_or_collection; using atomic_cell_value_view = data::value_view; using atomic_cell_value_mutable_view = data::value_mutable_view; /// View of an atomic cell template<mutable_view is_mutable> class basic_atomic_cell_view { protected: data::cell::basic_atomic_cell_view<is_mutable> _view; friend class atomic_cell; public: using pointer_type = std::conditional_t<is_mutable == mutable_view::no, const uint8_t*, uint8_t*>; protected: explicit basic_atomic_cell_view(data::cell::basic_atomic_cell_view<is_mutable> v) : _view(std::move(v)) { } basic_atomic_cell_view(const data::type_info& ti, pointer_type ptr) : _view(data::cell::make_atomic_cell_view(ti, ptr)) { } friend class atomic_cell_or_collection; public: operator basic_atomic_cell_view<mutable_view::no>() const noexcept { return basic_atomic_cell_view<mutable_view::no>(_view); } void swap(basic_atomic_cell_view& other) noexcept { using std::swap; swap(_view, other._view); } bool is_counter_update() const { return _view.is_counter_update(); } bool is_live() const { return _view.is_live(); } bool is_live(tombstone t, bool is_counter) const { return is_live() && !is_covered_by(t, is_counter); } bool is_live(tombstone t, gc_clock::time_point now, bool is_counter) const { return is_live() && !is_covered_by(t, is_counter) && !has_expired(now); } bool is_live_and_has_ttl() const { return _view.is_expiring(); } bool is_dead(gc_clock::time_point now) const { return !is_live() || has_expired(now); } bool is_covered_by(tombstone t, bool is_counter) const { return timestamp() <= t.timestamp || (is_counter && t.timestamp != api::missing_timestamp); } // Can be called on live and dead cells api::timestamp_type timestamp() const { return _view.timestamp(); } void set_timestamp(api::timestamp_type ts) { _view.set_timestamp(ts); } // Can be called on live cells only data::basic_value_view<is_mutable> value() const { return _view.value(); } // Can be called on live cells only size_t value_size() const { return _view.value_size(); } bool is_value_fragmented() const { return _view.is_value_fragmented(); } // Can be called on live counter update cells only int64_t counter_update_value() const { return _view.counter_update_value(); } // Can be called only when is_dead(gc_clock::time_point) gc_clock::time_point deletion_time() const { return !is_live() ? _view.deletion_time() : expiry() - ttl(); } // Can be called only when is_live_and_has_ttl() gc_clock::time_point expiry() const { return _view.expiry(); } // Can be called only when is_live_and_has_ttl() gc_clock::duration ttl() const { return _view.ttl(); } // Can be called on live and dead cells bool has_expired(gc_clock::time_point now) const { return is_live_and_has_ttl() && expiry() <= now; } bytes_view serialize() const { return _view.serialize(); } }; class atomic_cell_view final : public basic_atomic_cell_view<mutable_view::no> { atomic_cell_view(const data::type_info& ti, const uint8_t* data) : basic_atomic_cell_view<mutable_view::no>(ti, data) {} template<mutable_view is_mutable> atomic_cell_view(data::cell::basic_atomic_cell_view<is_mutable> view) : basic_atomic_cell_view<mutable_view::no>(view) { } friend class atomic_cell; public: static atomic_cell_view from_bytes(const data::type_info& ti, const imr::utils::object<data::cell::structure>& data) { return atomic_cell_view(ti, data.get()); } static atomic_cell_view from_bytes(const data::type_info& ti, bytes_view bv) { return atomic_cell_view(ti, reinterpret_cast<const uint8_t*>(bv.begin())); } friend std::ostream& operator<<(std::ostream& os, const atomic_cell_view& acv); class printer { const abstract_type& _type; const atomic_cell_view& _cell; public: printer(const abstract_type& type, const atomic_cell_view& cell) : _type(type), _cell(cell) {} friend std::ostream& operator<<(std::ostream& os, const printer& acvp); }; }; class atomic_cell_mutable_view final : public basic_atomic_cell_view<mutable_view::yes> { atomic_cell_mutable_view(const data::type_info& ti, uint8_t* data) : basic_atomic_cell_view<mutable_view::yes>(ti, data) {} public: static atomic_cell_mutable_view from_bytes(const data::type_info& ti, imr::utils::object<data::cell::structure>& data) { return atomic_cell_mutable_view(ti, data.get()); } friend class atomic_cell; }; using atomic_cell_ref = atomic_cell_mutable_view; class atomic_cell final : public basic_atomic_cell_view<mutable_view::yes> { using imr_object_type = imr::utils::object<data::cell::structure>; imr_object_type _data; atomic_cell(const data::type_info& ti, imr::utils::object<data::cell::structure>&& data) : basic_atomic_cell_view<mutable_view::yes>(ti, data.get()), _data(std::move(data)) {} public: class collection_member_tag; using collection_member = bool_class<collection_member_tag>; atomic_cell(atomic_cell&&) = default; atomic_cell& operator=(const atomic_cell&) = delete; atomic_cell& operator=(atomic_cell&&) = default; void swap(atomic_cell& other) noexcept { basic_atomic_cell_view<mutable_view::yes>::swap(other); _data.swap(other._data); } operator atomic_cell_view() const { return atomic_cell_view(_view); } atomic_cell(const abstract_type& t, atomic_cell_view other); static atomic_cell make_dead(api::timestamp_type timestamp, gc_clock::time_point deletion_time); static atomic_cell make_live(const abstract_type& type, api::timestamp_type timestamp, bytes_view value, collection_member = collection_member::no); static atomic_cell make_live(const abstract_type& type, api::timestamp_type timestamp, ser::buffer_view<bytes_ostream::fragment_iterator> value, collection_member = collection_member::no); static atomic_cell make_live(const abstract_type& type, api::timestamp_type timestamp, const fragmented_temporary_buffer::view& value, collection_member = collection_member::no); static atomic_cell make_live(const abstract_type& type, api::timestamp_type timestamp, const bytes& value, collection_member cm = collection_member::no) { return make_live(type, timestamp, bytes_view(value), cm); } static atomic_cell make_live_counter_update(api::timestamp_type timestamp, int64_t value); static atomic_cell make_live(const abstract_type&, api::timestamp_type timestamp, bytes_view value, gc_clock::time_point expiry, gc_clock::duration ttl, collection_member = collection_member::no); static atomic_cell make_live(const abstract_type&, api::timestamp_type timestamp, ser::buffer_view<bytes_ostream::fragment_iterator> value, gc_clock::time_point expiry, gc_clock::duration ttl, collection_member = collection_member::no); static atomic_cell make_live(const abstract_type&, api::timestamp_type timestamp, const fragmented_temporary_buffer::view& value, gc_clock::time_point expiry, gc_clock::duration ttl, collection_member = collection_member::no); static atomic_cell make_live(const abstract_type& type, api::timestamp_type timestamp, const bytes& value, gc_clock::time_point expiry, gc_clock::duration ttl, collection_member cm = collection_member::no) { return make_live(type, timestamp, bytes_view(value), expiry, ttl, cm); } static atomic_cell make_live(const abstract_type& type, api::timestamp_type timestamp, bytes_view value, ttl_opt ttl, collection_member cm = collection_member::no) { if (!ttl) { return make_live(type, timestamp, value, cm); } else { return make_live(type, timestamp, value, gc_clock::now() + *ttl, *ttl, cm); } } static atomic_cell make_live_uninitialized(const abstract_type& type, api::timestamp_type timestamp, size_t size); friend class atomic_cell_or_collection; friend std::ostream& operator<<(std::ostream& os, const atomic_cell& ac); class printer : atomic_cell_view::printer { public: printer(const abstract_type& type, const atomic_cell_view& cell) : atomic_cell_view::printer(type, cell) {} friend std::ostream& operator<<(std::ostream& os, const printer& acvp); }; }; class column_definition; int compare_atomic_cell_for_merge(atomic_cell_view left, atomic_cell_view right); void merge_column(const abstract_type& def, atomic_cell_or_collection& old, const atomic_cell_or_collection& neww); <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/planner/em/em_planner.h" #include <fstream> #include <limits> #include <utility> #include "modules/common/adapters/adapter_manager.h" #include "modules/common/log.h" #include "modules/common/math/math_utils.h" #include "modules/common/time/time.h" #include "modules/common/util/string_tokenizer.h" #include "modules/common/util/string_util.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/map/hdmap/hdmap.h" #include "modules/map/hdmap/hdmap_common.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/constraint_checker/constraint_checker.h" #include "modules/planning/math/curve1d/quartic_polynomial_curve1d.h" #include "modules/planning/tasks/dp_poly_path/dp_poly_path_optimizer.h" #include "modules/planning/tasks/dp_st_speed/dp_st_speed_optimizer.h" #include "modules/planning/tasks/path_decider/path_decider.h" #include "modules/planning/tasks/qp_spline_path/qp_spline_path_optimizer.h" #include "modules/planning/tasks/qp_spline_st_speed/qp_spline_st_speed_optimizer.h" #include "modules/planning/tasks/speed_decider/speed_decider.h" #include "modules/planning/tasks/traffic_decider/traffic_decider.h" namespace apollo { namespace planning { using common::Status; using common::adapter::AdapterManager; using common::time::Clock; using common::ErrorCode; using common::SpeedPoint; using common::SLPoint; using common::TrajectoryPoint; using common::math::Vec2d; void EMPlanner::RegisterTasks() { task_factory_.Register(TRAFFIC_DECIDER, []() -> Task* { return new TrafficDecider(); }); task_factory_.Register(DP_POLY_PATH_OPTIMIZER, []() -> Task* { return new DpPolyPathOptimizer(); }); task_factory_.Register(PATH_DECIDER, []() -> Task* { return new PathDecider(); }); task_factory_.Register(DP_ST_SPEED_OPTIMIZER, []() -> Task* { return new DpStSpeedOptimizer(); }); task_factory_.Register(SPEED_DECIDER, []() -> Task* { return new SpeedDecider(); }); task_factory_.Register(QP_SPLINE_PATH_OPTIMIZER, []() -> Task* { return new QpSplinePathOptimizer(); }); task_factory_.Register(QP_SPLINE_ST_SPEED_OPTIMIZER, []() -> Task* { return new QpSplineStSpeedOptimizer(); }); } Status EMPlanner::Init(const PlanningConfig& config) { AINFO << "In EMPlanner::Init()"; RegisterTasks(); for (const auto task : config.em_planner_config().task()) { tasks_.emplace_back( task_factory_.CreateObject(static_cast<TaskType>(task))); AINFO << "Created task:" << tasks_.back()->Name(); } for (auto& task : tasks_) { if (!task->Init(config)) { std::string msg( common::util::StrCat("Init task[", task->Name(), "] failed.")); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } } return Status::OK(); } void EMPlanner::RecordDebugInfo(const std::string& name, const double time_diff_ms, planning::LatencyStats* ptr_latency_stats) { if (!FLAGS_enable_record_debug) { ADEBUG << "Skip record debug info"; return; } auto ptr_stats = ptr_latency_stats->add_task_stats(); ptr_stats->set_name(name); ptr_stats->set_time_ms(time_diff_ms); } Status EMPlanner::Plan(const TrajectoryPoint& planning_start_point, Frame* frame, ReferenceLineInfo* reference_line_info) { const double kStraightForwardLineCost = 10.0; if (reference_line_info->Lanes().NextAction() != routing::FORWARD && reference_line_info->Lanes().IsOnSegment()) { reference_line_info->AddCost(kStraightForwardLineCost); } ADEBUG << "planning start point:" << planning_start_point.DebugString(); auto* heuristic_speed_data = reference_line_info->mutable_speed_data(); auto speed_profile = GenerateInitSpeedProfile(planning_start_point, reference_line_info); if (speed_profile.empty()) { speed_profile = GenerateSpeedHotStart(planning_start_point); ADEBUG << "Using dummy hot start for speed vector"; } heuristic_speed_data->set_speed_vector(speed_profile); auto ptr_debug = reference_line_info->mutable_debug(); auto ptr_latency_stats = reference_line_info->mutable_latency_stats(); auto ret = Status::OK(); for (auto& optimizer : tasks_) { const double start_timestamp = Clock::NowInSecond(); ret = optimizer->Execute(frame, reference_line_info); if (!ret.ok()) { reference_line_info->AddCost(std::numeric_limits<double>::infinity()); AERROR << "Failed to run tasks[" << optimizer->Name() << "], Error message: " << ret.error_message(); break; } const double end_timestamp = Clock::NowInSecond(); const double time_diff_ms = (end_timestamp - start_timestamp) * 1000; ADEBUG << "after optimizer " << optimizer->Name() << ":" << reference_line_info->PathSpeedDebugString() << std::endl; ADEBUG << optimizer->Name() << " time spend: " << time_diff_ms << " ms."; if (FLAGS_enable_record_debug && ptr_debug != nullptr && ptr_latency_stats != nullptr) { RecordDebugInfo(optimizer->Name(), time_diff_ms, ptr_latency_stats); } } DiscretizedTrajectory trajectory; if (!reference_line_info->CombinePathAndSpeedProfile( planning_start_point.relative_time(), planning_start_point.path_point().s(), &trajectory)) { std::string msg("Fail to aggregate planning trajectory."); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } double s = 0.0; if (!trajectory.trajectory_points().empty() && trajectory.trajectory_points().back().has_path_point()) { s = trajectory.trajectory_points().back().path_point().s(); } const double kRefrenceLineLengthTh = 10.0; const double kRefrenceLineLengthCost = 100.0; reference_line_info->AddCost( s > kRefrenceLineLengthTh ? 0.0 : kRefrenceLineLengthCost); if (FLAGS_enable_trajectory_check) { ConstraintChecker::ValidTrajectory(trajectory); } reference_line_info->SetTrajectory(trajectory); if (ret == Status::OK()) { // vehicle can drive on this reference line. reference_line_info->SetDriable(true); } return ret; } std::vector<SpeedPoint> EMPlanner::GenerateInitSpeedProfile( const TrajectoryPoint& planning_init_point, const ReferenceLineInfo* reference_line_info) { std::vector<SpeedPoint> speed_profile; const auto* last_frame = FrameHistory::instance()->Latest(); if (!last_frame) { AWARN << "last frame is empty"; return speed_profile; } const ReferenceLineInfo* last_reference_line_info = last_frame->DriveReferenceLineInfo(); if (!last_reference_line_info) { ADEBUG << "last reference line info is empty"; return speed_profile; } if (!reference_line_info->IsStartFrom(*last_reference_line_info)) { ADEBUG << "Current reference line is not started previous drived line"; return speed_profile; } const auto& last_speed_vector = last_reference_line_info->speed_data().speed_vector(); if (!last_speed_vector.empty()) { const auto& last_init_point = last_frame->PlanningStartPoint().path_point(); Vec2d last_xy_point(last_init_point.x(), last_init_point.y()); SLPoint last_sl_point; if (!last_reference_line_info->reference_line().XYToSL(last_xy_point, &last_sl_point)) { AERROR << "Fail to transfer xy to sl when init speed profile"; } Vec2d xy_point(planning_init_point.path_point().x(), planning_init_point.path_point().y()); SLPoint sl_point; if (!last_reference_line_info->reference_line().XYToSL(xy_point, &sl_point)) { AERROR << "Fail to transfer xy to sl when init speed profile"; } double s_diff = sl_point.s() - last_sl_point.s(); double start_time = 0.0; double start_s = 0.0; bool is_updated_start = false; for (const auto& speed_point : last_speed_vector) { if (speed_point.s() < s_diff) { continue; } if (!is_updated_start) { start_time = speed_point.t(); start_s = speed_point.s(); is_updated_start = true; } SpeedPoint refined_speed_point; refined_speed_point.set_s(speed_point.s() - start_s); refined_speed_point.set_t(speed_point.t() - start_time); refined_speed_point.set_v(speed_point.v()); refined_speed_point.set_a(speed_point.a()); refined_speed_point.set_da(speed_point.da()); speed_profile.push_back(std::move(refined_speed_point)); } } return speed_profile; } // This is a dummy simple hot start, need refine later std::vector<SpeedPoint> EMPlanner::GenerateSpeedHotStart( const TrajectoryPoint& planning_init_point) { std::vector<SpeedPoint> hot_start_speed_profile; double s = 0.0; double t = 0.0; double v = common::math::Clamp(planning_init_point.v(), 5.0, FLAGS_planning_upper_speed_limit); while (t < FLAGS_trajectory_time_length) { SpeedPoint speed_point; speed_point.set_s(s); speed_point.set_t(t); speed_point.set_v(v); hot_start_speed_profile.push_back(std::move(speed_point)); t += FLAGS_trajectory_time_min_interval; s += v * FLAGS_trajectory_time_min_interval; } return hot_start_speed_profile; } } // namespace planning } // namespace apollo <commit_msg>Planning: fixed scenario 0055. Added a large cost if the reference line has a static obstacle and the decision is stop. --- this part can be processed in earlier stages so that solving time is consumed.<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/planner/em/em_planner.h" #include <fstream> #include <limits> #include <utility> #include "modules/common/adapters/adapter_manager.h" #include "modules/common/log.h" #include "modules/common/math/math_utils.h" #include "modules/common/time/time.h" #include "modules/common/util/string_tokenizer.h" #include "modules/common/util/string_util.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/map/hdmap/hdmap.h" #include "modules/map/hdmap/hdmap_common.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/constraint_checker/constraint_checker.h" #include "modules/planning/math/curve1d/quartic_polynomial_curve1d.h" #include "modules/planning/tasks/dp_poly_path/dp_poly_path_optimizer.h" #include "modules/planning/tasks/dp_st_speed/dp_st_speed_optimizer.h" #include "modules/planning/tasks/path_decider/path_decider.h" #include "modules/planning/tasks/qp_spline_path/qp_spline_path_optimizer.h" #include "modules/planning/tasks/qp_spline_st_speed/qp_spline_st_speed_optimizer.h" #include "modules/planning/tasks/speed_decider/speed_decider.h" #include "modules/planning/tasks/traffic_decider/traffic_decider.h" namespace apollo { namespace planning { using common::Status; using common::adapter::AdapterManager; using common::time::Clock; using common::ErrorCode; using common::SpeedPoint; using common::SLPoint; using common::TrajectoryPoint; using common::math::Vec2d; void EMPlanner::RegisterTasks() { task_factory_.Register(TRAFFIC_DECIDER, []() -> Task* { return new TrafficDecider(); }); task_factory_.Register(DP_POLY_PATH_OPTIMIZER, []() -> Task* { return new DpPolyPathOptimizer(); }); task_factory_.Register(PATH_DECIDER, []() -> Task* { return new PathDecider(); }); task_factory_.Register(DP_ST_SPEED_OPTIMIZER, []() -> Task* { return new DpStSpeedOptimizer(); }); task_factory_.Register(SPEED_DECIDER, []() -> Task* { return new SpeedDecider(); }); task_factory_.Register(QP_SPLINE_PATH_OPTIMIZER, []() -> Task* { return new QpSplinePathOptimizer(); }); task_factory_.Register(QP_SPLINE_ST_SPEED_OPTIMIZER, []() -> Task* { return new QpSplineStSpeedOptimizer(); }); } Status EMPlanner::Init(const PlanningConfig& config) { AINFO << "In EMPlanner::Init()"; RegisterTasks(); for (const auto task : config.em_planner_config().task()) { tasks_.emplace_back( task_factory_.CreateObject(static_cast<TaskType>(task))); AINFO << "Created task:" << tasks_.back()->Name(); } for (auto& task : tasks_) { if (!task->Init(config)) { std::string msg( common::util::StrCat("Init task[", task->Name(), "] failed.")); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } } return Status::OK(); } void EMPlanner::RecordDebugInfo(const std::string& name, const double time_diff_ms, planning::LatencyStats* ptr_latency_stats) { if (!FLAGS_enable_record_debug) { ADEBUG << "Skip record debug info"; return; } auto ptr_stats = ptr_latency_stats->add_task_stats(); ptr_stats->set_name(name); ptr_stats->set_time_ms(time_diff_ms); } Status EMPlanner::Plan(const TrajectoryPoint& planning_start_point, Frame* frame, ReferenceLineInfo* reference_line_info) { const double kStraightForwardLineCost = 10.0; if (reference_line_info->Lanes().NextAction() != routing::FORWARD && reference_line_info->Lanes().IsOnSegment()) { reference_line_info->AddCost(kStraightForwardLineCost); } ADEBUG << "planning start point:" << planning_start_point.DebugString(); auto* heuristic_speed_data = reference_line_info->mutable_speed_data(); auto speed_profile = GenerateInitSpeedProfile(planning_start_point, reference_line_info); if (speed_profile.empty()) { speed_profile = GenerateSpeedHotStart(planning_start_point); ADEBUG << "Using dummy hot start for speed vector"; } heuristic_speed_data->set_speed_vector(speed_profile); auto ptr_debug = reference_line_info->mutable_debug(); auto ptr_latency_stats = reference_line_info->mutable_latency_stats(); auto ret = Status::OK(); for (auto& optimizer : tasks_) { const double start_timestamp = Clock::NowInSecond(); ret = optimizer->Execute(frame, reference_line_info); if (!ret.ok()) { reference_line_info->AddCost(std::numeric_limits<double>::infinity()); AERROR << "Failed to run tasks[" << optimizer->Name() << "], Error message: " << ret.error_message(); break; } const double end_timestamp = Clock::NowInSecond(); const double time_diff_ms = (end_timestamp - start_timestamp) * 1000; ADEBUG << "after optimizer " << optimizer->Name() << ":" << reference_line_info->PathSpeedDebugString() << std::endl; ADEBUG << optimizer->Name() << " time spend: " << time_diff_ms << " ms."; if (FLAGS_enable_record_debug && ptr_debug != nullptr && ptr_latency_stats != nullptr) { RecordDebugInfo(optimizer->Name(), time_diff_ms, ptr_latency_stats); } } DiscretizedTrajectory trajectory; if (!reference_line_info->CombinePathAndSpeedProfile( planning_start_point.relative_time(), planning_start_point.path_point().s(), &trajectory)) { std::string msg("Fail to aggregate planning trajectory."); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } for (const auto* path_obstacle : reference_line_info->path_decision()->path_obstacles().Items()) { if (!path_obstacle->obstacle()->IsStatic()) { continue; } if (path_obstacle->LongitudinalDecision().has_stop()) { constexpr double kRefrenceLineStaticObsCost = 1e3; reference_line_info->AddCost(kRefrenceLineStaticObsCost); } } if (FLAGS_enable_trajectory_check) { ConstraintChecker::ValidTrajectory(trajectory); } reference_line_info->SetTrajectory(trajectory); if (ret == Status::OK()) { // vehicle can drive on this reference line. reference_line_info->SetDriable(true); } return ret; } std::vector<SpeedPoint> EMPlanner::GenerateInitSpeedProfile( const TrajectoryPoint& planning_init_point, const ReferenceLineInfo* reference_line_info) { std::vector<SpeedPoint> speed_profile; const auto* last_frame = FrameHistory::instance()->Latest(); if (!last_frame) { AWARN << "last frame is empty"; return speed_profile; } const ReferenceLineInfo* last_reference_line_info = last_frame->DriveReferenceLineInfo(); if (!last_reference_line_info) { ADEBUG << "last reference line info is empty"; return speed_profile; } if (!reference_line_info->IsStartFrom(*last_reference_line_info)) { ADEBUG << "Current reference line is not started previous drived line"; return speed_profile; } const auto& last_speed_vector = last_reference_line_info->speed_data().speed_vector(); if (!last_speed_vector.empty()) { const auto& last_init_point = last_frame->PlanningStartPoint().path_point(); Vec2d last_xy_point(last_init_point.x(), last_init_point.y()); SLPoint last_sl_point; if (!last_reference_line_info->reference_line().XYToSL(last_xy_point, &last_sl_point)) { AERROR << "Fail to transfer xy to sl when init speed profile"; } Vec2d xy_point(planning_init_point.path_point().x(), planning_init_point.path_point().y()); SLPoint sl_point; if (!last_reference_line_info->reference_line().XYToSL(xy_point, &sl_point)) { AERROR << "Fail to transfer xy to sl when init speed profile"; } double s_diff = sl_point.s() - last_sl_point.s(); double start_time = 0.0; double start_s = 0.0; bool is_updated_start = false; for (const auto& speed_point : last_speed_vector) { if (speed_point.s() < s_diff) { continue; } if (!is_updated_start) { start_time = speed_point.t(); start_s = speed_point.s(); is_updated_start = true; } SpeedPoint refined_speed_point; refined_speed_point.set_s(speed_point.s() - start_s); refined_speed_point.set_t(speed_point.t() - start_time); refined_speed_point.set_v(speed_point.v()); refined_speed_point.set_a(speed_point.a()); refined_speed_point.set_da(speed_point.da()); speed_profile.push_back(std::move(refined_speed_point)); } } return speed_profile; } // This is a dummy simple hot start, need refine later std::vector<SpeedPoint> EMPlanner::GenerateSpeedHotStart( const TrajectoryPoint& planning_init_point) { std::vector<SpeedPoint> hot_start_speed_profile; double s = 0.0; double t = 0.0; double v = common::math::Clamp(planning_init_point.v(), 5.0, FLAGS_planning_upper_speed_limit); while (t < FLAGS_trajectory_time_length) { SpeedPoint speed_point; speed_point.set_s(s); speed_point.set_t(t); speed_point.set_v(v); hot_start_speed_profile.push_back(std::move(speed_point)); t += FLAGS_trajectory_time_min_interval; s += v * FLAGS_trajectory_time_min_interval; } return hot_start_speed_profile; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>/* * Copyright 2015 Intel(r) Corporation * * 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 "vmf/reader_compressed.hpp" #include "vmf/rwconst.hpp" namespace vmf { /* * parseXXX() methods: * Deserialize -> decompress -> Deserialize */ bool ReaderCompressed::parseAll(const std::string& text, IdType& nextId, std::string& filepath, std::string& checksum, std::vector<std::shared_ptr<MetadataStream::VideoSegment>>& segments, std::vector<std::shared_ptr<MetadataSchema>>& schemas, std::vector<std::shared_ptr<MetadataInternal>>& metadata) { std::string decompressed = decompress(text); return reader->parseAll(decompressed, nextId, filepath, checksum, segments, schemas, metadata); } bool ReaderCompressed::parseSchemas(const std::string& text, std::vector<std::shared_ptr<MetadataSchema>>& schemas) { std::string decompressed = decompress(text); return reader->parseSchemas(decompressed, schemas); } bool ReaderCompressed::parseMetadata(const std::string& text, const std::vector<std::shared_ptr<MetadataSchema>>& schemas, std::vector<std::shared_ptr<MetadataInternal>>& metadata) { std::string decompressed = decompress(text); return reader->parseMetadata(decompressed, schemas, metadata); } bool ReaderCompressed::parseVideoSegments(const std::string& text, std::vector<std::shared_ptr<MetadataStream::VideoSegment> >& segments) { std::string decompressed = decompress(text); return reader->parseVideoSegments(decompressed, segments); } std::string ReaderCompressed::decompress(const std::string& input) { //parse it as usual serialized VMF XML, search for specific schemas std::vector<std::shared_ptr<MetadataStream::VideoSegment>> segments; std::vector<std::shared_ptr<MetadataSchema>> schemas; std::vector<std::shared_ptr<MetadataInternal>> metadata; std::string filePath, checksum; IdType nextId; if(!reader->parseAll(input, nextId, filePath, checksum, segments, schemas, metadata)) { VMF_EXCEPTION(vmf::InternalErrorException, "Failed to parse input data"); } if(schemas.size() == 1 && schemas[0]->getName() == COMPRESSED_DATA_SCHEMA_NAME) { std::shared_ptr<Metadata> cMetadata = metadata[0]; vmf_string algo = cMetadata->getFieldValue(COMPRESSION_ALGO_PROP_NAME); vmf_string encoded = cMetadata->getFieldValue(COMPRESSED_DATA_PROP_NAME); if(algo.empty()) { VMF_EXCEPTION(vmf::InternalErrorException, "Algorithm name isn't specified"); } try { std::string decompressed; std::shared_ptr<Compressor> decompressor = Compressor::create(algo); // Compressed binary data should be represented in base64 // because of '\0' symbols vmf_rawbuffer compressed = Variant::base64decode(encoded); decompressor->decompress(compressed, decompressed); return decompressed; } catch(IncorrectParamException& ce) { if(ignoreUnknownCompressor) { return input; } else { VMF_EXCEPTION(IncorrectParamException, ce.what()); } } } else { return input; } } } <commit_msg>ReaderCompressed at decompress: parseSchemas() and parseMetadata() instead of parseAll()<commit_after>/* * Copyright 2015 Intel(r) Corporation * * 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 "vmf/reader_compressed.hpp" #include "vmf/rwconst.hpp" namespace vmf { /* * parseXXX() methods: * Deserialize -> decompress -> Deserialize */ bool ReaderCompressed::parseAll(const std::string& text, IdType& nextId, std::string& filepath, std::string& checksum, std::vector<std::shared_ptr<MetadataStream::VideoSegment>>& segments, std::vector<std::shared_ptr<MetadataSchema>>& schemas, std::vector<std::shared_ptr<MetadataInternal>>& metadata) { std::string decompressed = decompress(text); return reader->parseAll(decompressed, nextId, filepath, checksum, segments, schemas, metadata); } bool ReaderCompressed::parseSchemas(const std::string& text, std::vector<std::shared_ptr<MetadataSchema>>& schemas) { std::string decompressed = decompress(text); return reader->parseSchemas(decompressed, schemas); } bool ReaderCompressed::parseMetadata(const std::string& text, const std::vector<std::shared_ptr<MetadataSchema>>& schemas, std::vector<std::shared_ptr<MetadataInternal>>& metadata) { std::string decompressed = decompress(text); return reader->parseMetadata(decompressed, schemas, metadata); } bool ReaderCompressed::parseVideoSegments(const std::string& text, std::vector<std::shared_ptr<MetadataStream::VideoSegment> >& segments) { std::string decompressed = decompress(text); return reader->parseVideoSegments(decompressed, segments); } std::string ReaderCompressed::decompress(const std::string& input) { //parse it as usual serialized VMF XML, search for specific schemas std::vector<std::shared_ptr<MetadataSchema>> schemas; if(!reader->parseSchemas(input, schemas)) { VMF_EXCEPTION(vmf::InternalErrorException, "Failed to parse schemas in input data"); } if(schemas.size() == 1 && schemas[0]->getName() == COMPRESSED_DATA_SCHEMA_NAME) { std::vector<std::shared_ptr<MetadataInternal>> metadata; if(!reader->parseMetadata(input, schemas, metadata)) { VMF_EXCEPTION(vmf::InternalErrorException, "Failed to parse schemas in input data"); } std::shared_ptr<Metadata> cMetadata = metadata[0]; vmf_string algo = cMetadata->getFieldValue(COMPRESSION_ALGO_PROP_NAME); vmf_string encoded = cMetadata->getFieldValue(COMPRESSED_DATA_PROP_NAME); if(algo.empty()) { VMF_EXCEPTION(vmf::InternalErrorException, "Algorithm name isn't specified"); } try { std::string decompressed; std::shared_ptr<Compressor> decompressor = Compressor::create(algo); // Compressed binary data should be represented in base64 // because of '\0' symbols vmf_rawbuffer compressed = Variant::base64decode(encoded); decompressor->decompress(compressed, decompressed); return decompressed; } catch(IncorrectParamException& ce) { if(ignoreUnknownCompressor) { return input; } else { VMF_EXCEPTION(IncorrectParamException, ce.what()); } } } else { return input; } } } <|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 "ooxmldocpropimport.hxx" #include "services.hxx" #include <vector> #include <com/sun/star/embed/ElementModes.hpp> #include <com/sun/star/embed/XHierarchicalStorageAccess.hpp> #include <com/sun/star/embed/XRelationshipAccess.hpp> #include <com/sun/star/embed/XStorage.hpp> #include "oox/core/fastparser.hxx" #include "oox/core/relations.hxx" #include "oox/helper/containerhelper.hxx" #include "oox/helper/helper.hxx" #include "docprophandler.hxx" #include <cppuhelper/supportsservice.hxx> namespace oox { namespace docprop { using namespace ::com::sun::star::beans; using namespace ::com::sun::star::document; using namespace ::com::sun::star::embed; using namespace ::com::sun::star::io; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::xml::sax; OUString SAL_CALL DocumentPropertiesImport_getImplementationName() { return OUString( "com.sun.star.comp.oox.docprop.DocumentPropertiesImporter" ); } Sequence< OUString > SAL_CALL DocumentPropertiesImport_getSupportedServiceNames() { Sequence< OUString > aServices( 1 ); aServices[ 0 ] = "com.sun.star.document.OOXMLDocumentPropertiesImporter"; return aServices; } Reference< XInterface > SAL_CALL DocumentPropertiesImport_createInstance( const Reference< XComponentContext >& rxContext ) throw(Exception) { return static_cast< ::cppu::OWeakObject* >( new DocumentPropertiesImport( rxContext ) ); } namespace { Sequence< InputSource > lclGetRelatedStreams( const Reference< XStorage >& rxStorage, const OUString& rStreamType ) throw (RuntimeException) { Reference< XRelationshipAccess > xRelation( rxStorage, UNO_QUERY_THROW ); Reference< XHierarchicalStorageAccess > xHierarchy( rxStorage, UNO_QUERY_THROW ); Sequence< Sequence< StringPair > > aPropsInfo = xRelation->getRelationshipsByType( rStreamType ); ::std::vector< InputSource > aResult; for( sal_Int32 nIndex = 0, nLength = aPropsInfo.getLength(); nIndex < nLength; ++nIndex ) { const Sequence< StringPair >& rEntries = aPropsInfo[ nIndex ]; for( sal_Int32 nEntryIndex = 0, nEntryLength = rEntries.getLength(); nEntryIndex < nEntryLength; ++nEntryIndex ) { const StringPair& rEntry = rEntries[ nEntryIndex ]; if ( rEntry.First == "Target" ) { Reference< XExtendedStorageStream > xExtStream( xHierarchy->openStreamElementByHierarchicalName( rEntry.Second, ElementModes::READ ), UNO_QUERY_THROW ); Reference< XInputStream > xInStream = xExtStream->getInputStream(); if( xInStream.is() ) { aResult.resize( aResult.size() + 1 ); aResult.back().sSystemId = rEntry.Second; aResult.back().aInputStream = xExtStream->getInputStream(); } break; } } } return ContainerHelper::vectorToSequence( aResult ); } } // namespace DocumentPropertiesImport::DocumentPropertiesImport( const Reference< XComponentContext >& rxContext ) : mxContext( rxContext ) { } // XServiceInfo OUString SAL_CALL DocumentPropertiesImport::getImplementationName() throw (RuntimeException, std::exception) { return DocumentPropertiesImport_getImplementationName(); } sal_Bool SAL_CALL DocumentPropertiesImport::supportsService( const OUString& rServiceName ) throw (RuntimeException, std::exception) { return cppu::supportsService(this, rServiceName); } Sequence< OUString > SAL_CALL DocumentPropertiesImport::getSupportedServiceNames() throw (RuntimeException, std::exception) { return DocumentPropertiesImport_getSupportedServiceNames(); } // XOOXMLDocumentPropertiesImporter void SAL_CALL DocumentPropertiesImport::importProperties( const Reference< XStorage >& rxSource, const Reference< XDocumentProperties >& rxDocumentProperties ) throw (RuntimeException, IllegalArgumentException, SAXException, Exception, std::exception) { if( !mxContext.is() ) throw RuntimeException(); if( !rxSource.is() || !rxDocumentProperties.is() ) throw IllegalArgumentException(); Sequence< InputSource > aCoreStreams = lclGetRelatedStreams( rxSource, CREATE_OFFICEDOC_RELATION_TYPE( "metadata/core-properties" ) ); // OOXML strict if( !aCoreStreams.hasElements() ) aCoreStreams = lclGetRelatedStreams( rxSource, CREATE_OFFICEDOC_RELATION_TYPE_STRICT( "metadata/core-properties" ) ); // MS Office seems to have a bug, so we have to do similar handling if( !aCoreStreams.hasElements() ) aCoreStreams = lclGetRelatedStreams( rxSource, CREATE_PACKAGE_RELATION_TYPE( "metadata/core-properties" ) ); Sequence< InputSource > aExtStreams = lclGetRelatedStreams( rxSource, CREATE_OFFICEDOC_RELATION_TYPE( "extended-properties" ) ); // OOXML strict if( !aExtStreams.hasElements() ) aExtStreams = lclGetRelatedStreams( rxSource, CREATE_OFFICEDOC_RELATION_TYPE_STRICT( "extended-properties" ) ); Sequence< InputSource > aCustomStreams = lclGetRelatedStreams( rxSource, CREATE_OFFICEDOC_RELATION_TYPE( "custom-properties" ) ); // OOXML strict if( !aCustomStreams.hasElements() ) aCustomStreams = lclGetRelatedStreams( rxSource, CREATE_OFFICEDOC_RELATION_TYPE_STRICT( "custom-properties" ) ); if( aCoreStreams.hasElements() || aExtStreams.hasElements() || aCustomStreams.hasElements() ) { if( aCoreStreams.getLength() > 1 ) throw IOException( "Unexpected core properties stream!" ); ::oox::core::FastParser aParser( mxContext ); aParser.registerNamespace( NMSP_packageMetaCorePr ); aParser.registerNamespace( NMSP_dc ); aParser.registerNamespace( NMSP_dcTerms ); aParser.registerNamespace( NMSP_officeExtPr ); aParser.registerNamespace( NMSP_officeCustomPr ); aParser.registerNamespace( NMSP_officeDocPropsVT ); aParser.setDocumentHandler( new OOXMLDocPropHandler( mxContext, rxDocumentProperties ) ); if( aCoreStreams.hasElements() ) aParser.parseStream( aCoreStreams[ 0 ], true ); for( sal_Int32 nIndex = 0; nIndex < aExtStreams.getLength(); ++nIndex ) aParser.parseStream( aExtStreams[ nIndex ], true ); for( sal_Int32 nIndex = 0; nIndex < aCustomStreams.getLength(); ++nIndex ) aParser.parseStream( aCustomStreams[ nIndex ], true ); } } } // namespace docprop } // namespace oox /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Resolves: fdo#84261 unexpected exception -> clang builds terminate<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 "ooxmldocpropimport.hxx" #include "services.hxx" #include <vector> #include <com/sun/star/embed/ElementModes.hpp> #include <com/sun/star/embed/XHierarchicalStorageAccess.hpp> #include <com/sun/star/embed/XRelationshipAccess.hpp> #include <com/sun/star/embed/XStorage.hpp> #include "oox/core/fastparser.hxx" #include "oox/core/relations.hxx" #include "oox/helper/containerhelper.hxx" #include "oox/helper/helper.hxx" #include "docprophandler.hxx" #include <cppuhelper/supportsservice.hxx> namespace oox { namespace docprop { using namespace ::com::sun::star::beans; using namespace ::com::sun::star::document; using namespace ::com::sun::star::embed; using namespace ::com::sun::star::io; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::xml::sax; OUString SAL_CALL DocumentPropertiesImport_getImplementationName() { return OUString( "com.sun.star.comp.oox.docprop.DocumentPropertiesImporter" ); } Sequence< OUString > SAL_CALL DocumentPropertiesImport_getSupportedServiceNames() { Sequence< OUString > aServices( 1 ); aServices[ 0 ] = "com.sun.star.document.OOXMLDocumentPropertiesImporter"; return aServices; } Reference< XInterface > SAL_CALL DocumentPropertiesImport_createInstance( const Reference< XComponentContext >& rxContext ) throw(Exception) { return static_cast< ::cppu::OWeakObject* >( new DocumentPropertiesImport( rxContext ) ); } namespace { Sequence< InputSource > lclGetRelatedStreams( const Reference< XStorage >& rxStorage, const OUString& rStreamType ) throw (RuntimeException, css::io::IOException) { Reference< XRelationshipAccess > xRelation( rxStorage, UNO_QUERY_THROW ); Reference< XHierarchicalStorageAccess > xHierarchy( rxStorage, UNO_QUERY_THROW ); Sequence< Sequence< StringPair > > aPropsInfo = xRelation->getRelationshipsByType( rStreamType ); ::std::vector< InputSource > aResult; for( sal_Int32 nIndex = 0, nLength = aPropsInfo.getLength(); nIndex < nLength; ++nIndex ) { const Sequence< StringPair >& rEntries = aPropsInfo[ nIndex ]; for( sal_Int32 nEntryIndex = 0, nEntryLength = rEntries.getLength(); nEntryIndex < nEntryLength; ++nEntryIndex ) { const StringPair& rEntry = rEntries[ nEntryIndex ]; if ( rEntry.First == "Target" ) { Reference< XExtendedStorageStream > xExtStream( xHierarchy->openStreamElementByHierarchicalName( rEntry.Second, ElementModes::READ ), UNO_QUERY_THROW ); Reference< XInputStream > xInStream = xExtStream->getInputStream(); if( xInStream.is() ) { aResult.resize( aResult.size() + 1 ); aResult.back().sSystemId = rEntry.Second; aResult.back().aInputStream = xExtStream->getInputStream(); } break; } } } return ContainerHelper::vectorToSequence( aResult ); } } // namespace DocumentPropertiesImport::DocumentPropertiesImport( const Reference< XComponentContext >& rxContext ) : mxContext( rxContext ) { } // XServiceInfo OUString SAL_CALL DocumentPropertiesImport::getImplementationName() throw (RuntimeException, std::exception) { return DocumentPropertiesImport_getImplementationName(); } sal_Bool SAL_CALL DocumentPropertiesImport::supportsService( const OUString& rServiceName ) throw (RuntimeException, std::exception) { return cppu::supportsService(this, rServiceName); } Sequence< OUString > SAL_CALL DocumentPropertiesImport::getSupportedServiceNames() throw (RuntimeException, std::exception) { return DocumentPropertiesImport_getSupportedServiceNames(); } // XOOXMLDocumentPropertiesImporter void SAL_CALL DocumentPropertiesImport::importProperties( const Reference< XStorage >& rxSource, const Reference< XDocumentProperties >& rxDocumentProperties ) throw (RuntimeException, IllegalArgumentException, SAXException, Exception, std::exception) { if( !mxContext.is() ) throw RuntimeException(); if( !rxSource.is() || !rxDocumentProperties.is() ) throw IllegalArgumentException(); Sequence< InputSource > aCoreStreams = lclGetRelatedStreams( rxSource, CREATE_OFFICEDOC_RELATION_TYPE( "metadata/core-properties" ) ); // OOXML strict if( !aCoreStreams.hasElements() ) aCoreStreams = lclGetRelatedStreams( rxSource, CREATE_OFFICEDOC_RELATION_TYPE_STRICT( "metadata/core-properties" ) ); // MS Office seems to have a bug, so we have to do similar handling if( !aCoreStreams.hasElements() ) aCoreStreams = lclGetRelatedStreams( rxSource, CREATE_PACKAGE_RELATION_TYPE( "metadata/core-properties" ) ); Sequence< InputSource > aExtStreams = lclGetRelatedStreams( rxSource, CREATE_OFFICEDOC_RELATION_TYPE( "extended-properties" ) ); // OOXML strict if( !aExtStreams.hasElements() ) aExtStreams = lclGetRelatedStreams( rxSource, CREATE_OFFICEDOC_RELATION_TYPE_STRICT( "extended-properties" ) ); Sequence< InputSource > aCustomStreams = lclGetRelatedStreams( rxSource, CREATE_OFFICEDOC_RELATION_TYPE( "custom-properties" ) ); // OOXML strict if( !aCustomStreams.hasElements() ) aCustomStreams = lclGetRelatedStreams( rxSource, CREATE_OFFICEDOC_RELATION_TYPE_STRICT( "custom-properties" ) ); if( aCoreStreams.hasElements() || aExtStreams.hasElements() || aCustomStreams.hasElements() ) { if( aCoreStreams.getLength() > 1 ) throw IOException( "Unexpected core properties stream!" ); ::oox::core::FastParser aParser( mxContext ); aParser.registerNamespace( NMSP_packageMetaCorePr ); aParser.registerNamespace( NMSP_dc ); aParser.registerNamespace( NMSP_dcTerms ); aParser.registerNamespace( NMSP_officeExtPr ); aParser.registerNamespace( NMSP_officeCustomPr ); aParser.registerNamespace( NMSP_officeDocPropsVT ); aParser.setDocumentHandler( new OOXMLDocPropHandler( mxContext, rxDocumentProperties ) ); if( aCoreStreams.hasElements() ) aParser.parseStream( aCoreStreams[ 0 ], true ); for( sal_Int32 nIndex = 0; nIndex < aExtStreams.getLength(); ++nIndex ) aParser.parseStream( aExtStreams[ nIndex ], true ); for( sal_Int32 nIndex = 0; nIndex < aCustomStreams.getLength(); ++nIndex ) aParser.parseStream( aCustomStreams[ nIndex ], true ); } } } // namespace docprop } // namespace oox /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include "Absorbable.h" Absorbable::Absorbable(int newMass) { mass = newMass; posX = posY = 0; //Select a new color, using the HSL color wheel for bright colors. ColorHSL temp; temp.setH((rand() % 360) + 1); temp.setS(1); temp.setL(.5); color = temp.getRGB(); } void Absorbable::absorb(Absorbable* object) { mass += object->mass; //Do a neat averaging of colors thing, to make it look like something was really absorbed ColorHSL temp1 =color.getHSL(), temp2 = object->color.getHSL(); temp1.setH((temp1.getH() + temp2.getH()) / 2); color = temp1.getRGB(); } void Absorbable::draw(SDL_Renderer* renderer, float vPosX, float vPosY, float scale) { SDL_SetRenderDrawColor(renderer, color.getR(), color.getG(), color.getB(), 255); //Draw a circle... actually a square for now. Sorry! double radius = log2(mass) * scale * 10.f; //TODO: Ensure that this formula works as intended... SDL_Rect rect; rect.x = posX - (vPosX * scale), rect.y = posY - (vPosY * scale); rect.h = radius, rect.w = radius; SDL_RenderFillRect(renderer, &rect); } void Absorbable::setMass(float newMass) { mass = newMass; } void Absorbable::setX(float newX) { posX = newX; } void Absorbable::setY(float newY) { posY = newY; } float Absorbable::getX() { return posX; } float Absorbable::getY() { return posY; } float Absorbable::getMass() { return mass; } <commit_msg>"Fixed" Absorbable size formula<commit_after>#include "Absorbable.h" Absorbable::Absorbable(int newMass) { mass = newMass; posX = posY = 0; //Select a new color, using the HSL color wheel for bright colors. ColorHSL temp; temp.setH((rand() % 360) + 1); temp.setS(1); temp.setL(.5); color = temp.getRGB(); } void Absorbable::absorb(Absorbable* object) { mass += object->mass; //Do a neat averaging of colors thing, to make it look like something was really absorbed ColorHSL temp1 =color.getHSL(), temp2 = object->color.getHSL(); temp1.setH((temp1.getH() + temp2.getH()) / 2); color = temp1.getRGB(); } void Absorbable::draw(SDL_Renderer* renderer, float vPosX, float vPosY, float scale) { SDL_SetRenderDrawColor(renderer, color.getR(), color.getG(), color.getB(), 255); //Draw a circle... actually a square for now. Sorry! double radius = mass * scale; //TODO: Ensure that this formula works as intended... SDL_Rect rect; rect.x = posX - (vPosX * scale), rect.y = posY - (vPosY * scale); rect.h = radius, rect.w = radius; SDL_RenderFillRect(renderer, &rect); } void Absorbable::setMass(float newMass) { mass = newMass; } void Absorbable::setX(float newX) { posX = newX; } void Absorbable::setY(float newY) { posY = newY; } float Absorbable::getX() { return posX; } float Absorbable::getY() { return posY; } float Absorbable::getMass() { return mass; } <|endoftext|>
<commit_before>// Copyright 2014 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 "sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions.h" #include <errno.h> #include <sched.h> #include <sys/resource.h> #include <sys/syscall.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include "base/bind.h" #include "base/synchronization/waitable_event.h" #include "base/sys_info.h" #include "base/threading/thread.h" #include "base/time/time.h" #include "build/build_config.h" #include "sandbox/linux/bpf_dsl/bpf_dsl.h" #include "sandbox/linux/bpf_dsl/policy.h" #include "sandbox/linux/seccomp-bpf-helpers/sigsys_handlers.h" #include "sandbox/linux/seccomp-bpf/bpf_tests.h" #include "sandbox/linux/seccomp-bpf/sandbox_bpf.h" #include "sandbox/linux/seccomp-bpf/syscall.h" #include "sandbox/linux/services/linux_syscalls.h" #include "sandbox/linux/services/syscall_wrappers.h" #include "sandbox/linux/tests/unit_tests.h" #if !defined(OS_ANDROID) #include "third_party/lss/linux_syscall_support.h" // for MAKE_PROCESS_CPUCLOCK #endif namespace sandbox { namespace { // NOTE: most of the parameter restrictions are tested in // baseline_policy_unittest.cc as a more end-to-end test. using sandbox::bpf_dsl::Allow; using sandbox::bpf_dsl::ResultExpr; class RestrictClockIdPolicy : public bpf_dsl::Policy { public: RestrictClockIdPolicy() {} ~RestrictClockIdPolicy() override {} ResultExpr EvaluateSyscall(int sysno) const override { switch (sysno) { case __NR_clock_gettime: case __NR_clock_getres: return RestrictClockID(); default: return Allow(); } } }; void CheckClock(clockid_t clockid) { struct timespec ts; ts.tv_sec = ts.tv_nsec = -1; BPF_ASSERT_EQ(0, clock_gettime(clockid, &ts)); BPF_ASSERT_LE(0, ts.tv_sec); BPF_ASSERT_LE(0, ts.tv_nsec); } BPF_TEST_C(ParameterRestrictions, clock_gettime_allowed, RestrictClockIdPolicy) { CheckClock(CLOCK_MONOTONIC); CheckClock(CLOCK_PROCESS_CPUTIME_ID); CheckClock(CLOCK_REALTIME); CheckClock(CLOCK_THREAD_CPUTIME_ID); } BPF_DEATH_TEST_C(ParameterRestrictions, clock_gettime_crash_monotonic_raw, DEATH_SEGV_MESSAGE(sandbox::GetErrorMessageContentForTests()), RestrictClockIdPolicy) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC_RAW, &ts); } #if defined(OS_CHROMEOS) // A custom BPF tester delegate to run IsRunningOnChromeOS() before // the sandbox is enabled because we cannot run it with non-SFI BPF // sandbox enabled. class ClockSystemTesterDelegate : public sandbox::BPFTesterDelegate { public: ClockSystemTesterDelegate() : is_running_on_chromeos_(base::SysInfo::IsRunningOnChromeOS()) {} virtual ~ClockSystemTesterDelegate() {} virtual scoped_ptr<sandbox::bpf_dsl::Policy> GetSandboxBPFPolicy() override { return scoped_ptr<sandbox::bpf_dsl::Policy>(new RestrictClockIdPolicy()); } virtual void RunTestFunction() override { if (is_running_on_chromeos_) { CheckClock(base::TimeTicks::kClockSystemTrace); } else { struct timespec ts; // kClockSystemTrace is 11, which is CLOCK_THREAD_CPUTIME_ID of // the init process (pid=1). If kernel supports this feature, // this may succeed even if this is not running on Chrome OS. We // just check this clock_gettime call does not crash. clock_gettime(base::TimeTicks::kClockSystemTrace, &ts); } } private: const bool is_running_on_chromeos_; DISALLOW_COPY_AND_ASSIGN(ClockSystemTesterDelegate); }; BPF_TEST_D(BPFTest, BPFTestWithDelegateClass, ClockSystemTesterDelegate); #elif defined(OS_LINUX) BPF_DEATH_TEST_C(ParameterRestrictions, clock_gettime_crash_system_trace, DEATH_SEGV_MESSAGE(sandbox::GetErrorMessageContentForTests()), RestrictClockIdPolicy) { struct timespec ts; clock_gettime(base::TimeTicks::kClockSystemTrace, &ts); } #endif // defined(OS_CHROMEOS) #if !defined(OS_ANDROID) BPF_DEATH_TEST_C(ParameterRestrictions, clock_gettime_crash_cpu_clock, DEATH_SEGV_MESSAGE(sandbox::GetErrorMessageContentForTests()), RestrictClockIdPolicy) { // We can't use clock_getcpuclockid() because it's not implemented in newlib, // and it might not work inside the sandbox anyway. const pid_t kInitPID = 1; const clockid_t kInitCPUClockID = MAKE_PROCESS_CPUCLOCK(kInitPID, CPUCLOCK_SCHED); struct timespec ts; clock_gettime(kInitCPUClockID, &ts); } #endif // !defined(OS_ANDROID) class RestrictSchedPolicy : public bpf_dsl::Policy { public: RestrictSchedPolicy() {} ~RestrictSchedPolicy() override {} ResultExpr EvaluateSyscall(int sysno) const override { switch (sysno) { case __NR_sched_getparam: return RestrictSchedTarget(getpid(), sysno); default: return Allow(); } } }; void CheckSchedGetParam(pid_t pid, struct sched_param* param) { BPF_ASSERT_EQ(0, sched_getparam(pid, param)); } void SchedGetParamThread(base::WaitableEvent* thread_run) { const pid_t pid = getpid(); const pid_t tid = sys_gettid(); BPF_ASSERT_NE(pid, tid); struct sched_param current_pid_param; CheckSchedGetParam(pid, &current_pid_param); struct sched_param zero_param; CheckSchedGetParam(0, &zero_param); struct sched_param tid_param; CheckSchedGetParam(tid, &tid_param); BPF_ASSERT_EQ(zero_param.sched_priority, tid_param.sched_priority); // Verify that the SIGSYS handler sets errno properly. errno = 0; BPF_ASSERT_EQ(-1, sched_getparam(tid, NULL)); BPF_ASSERT_EQ(EINVAL, errno); thread_run->Signal(); } BPF_TEST_C(ParameterRestrictions, sched_getparam_allowed, RestrictSchedPolicy) { base::WaitableEvent thread_run(true, false); // Run the actual test in a new thread so that the current pid and tid are // different. base::Thread getparam_thread("sched_getparam_thread"); BPF_ASSERT(getparam_thread.Start()); getparam_thread.message_loop()->PostTask( FROM_HERE, base::Bind(&SchedGetParamThread, &thread_run)); BPF_ASSERT(thread_run.TimedWait(base::TimeDelta::FromMilliseconds(5000))); getparam_thread.Stop(); } BPF_DEATH_TEST_C(ParameterRestrictions, sched_getparam_crash_non_zero, DEATH_SEGV_MESSAGE(sandbox::GetErrorMessageContentForTests()), RestrictSchedPolicy) { const pid_t kInitPID = 1; struct sched_param param; sched_getparam(kInitPID, &param); } class RestrictPrlimit64Policy : public bpf_dsl::Policy { public: RestrictPrlimit64Policy() {} ~RestrictPrlimit64Policy() override {} ResultExpr EvaluateSyscall(int sysno) const override { switch (sysno) { case __NR_prlimit64: return RestrictPrlimit64(getpid()); default: return Allow(); } } }; BPF_TEST_C(ParameterRestrictions, prlimit64_allowed, RestrictPrlimit64Policy) { BPF_ASSERT_EQ(0, sys_prlimit64(0, RLIMIT_AS, NULL, NULL)); BPF_ASSERT_EQ(0, sys_prlimit64(getpid(), RLIMIT_AS, NULL, NULL)); } BPF_DEATH_TEST_C(ParameterRestrictions, prlimit64_crash_not_self, DEATH_SEGV_MESSAGE(sandbox::GetErrorMessageContentForTests()), RestrictPrlimit64Policy) { const pid_t kInitPID = 1; BPF_ASSERT_NE(kInitPID, getpid()); sys_prlimit64(kInitPID, RLIMIT_AS, NULL, NULL); } } // namespace } // namespace sandbox <commit_msg>Update {virtual,override,final} to follow C++11 style in sandbox, round 2.<commit_after>// Copyright 2014 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 "sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions.h" #include <errno.h> #include <sched.h> #include <sys/resource.h> #include <sys/syscall.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include "base/bind.h" #include "base/synchronization/waitable_event.h" #include "base/sys_info.h" #include "base/threading/thread.h" #include "base/time/time.h" #include "build/build_config.h" #include "sandbox/linux/bpf_dsl/bpf_dsl.h" #include "sandbox/linux/bpf_dsl/policy.h" #include "sandbox/linux/seccomp-bpf-helpers/sigsys_handlers.h" #include "sandbox/linux/seccomp-bpf/bpf_tests.h" #include "sandbox/linux/seccomp-bpf/sandbox_bpf.h" #include "sandbox/linux/seccomp-bpf/syscall.h" #include "sandbox/linux/services/linux_syscalls.h" #include "sandbox/linux/services/syscall_wrappers.h" #include "sandbox/linux/tests/unit_tests.h" #if !defined(OS_ANDROID) #include "third_party/lss/linux_syscall_support.h" // for MAKE_PROCESS_CPUCLOCK #endif namespace sandbox { namespace { // NOTE: most of the parameter restrictions are tested in // baseline_policy_unittest.cc as a more end-to-end test. using sandbox::bpf_dsl::Allow; using sandbox::bpf_dsl::ResultExpr; class RestrictClockIdPolicy : public bpf_dsl::Policy { public: RestrictClockIdPolicy() {} ~RestrictClockIdPolicy() override {} ResultExpr EvaluateSyscall(int sysno) const override { switch (sysno) { case __NR_clock_gettime: case __NR_clock_getres: return RestrictClockID(); default: return Allow(); } } }; void CheckClock(clockid_t clockid) { struct timespec ts; ts.tv_sec = ts.tv_nsec = -1; BPF_ASSERT_EQ(0, clock_gettime(clockid, &ts)); BPF_ASSERT_LE(0, ts.tv_sec); BPF_ASSERT_LE(0, ts.tv_nsec); } BPF_TEST_C(ParameterRestrictions, clock_gettime_allowed, RestrictClockIdPolicy) { CheckClock(CLOCK_MONOTONIC); CheckClock(CLOCK_PROCESS_CPUTIME_ID); CheckClock(CLOCK_REALTIME); CheckClock(CLOCK_THREAD_CPUTIME_ID); } BPF_DEATH_TEST_C(ParameterRestrictions, clock_gettime_crash_monotonic_raw, DEATH_SEGV_MESSAGE(sandbox::GetErrorMessageContentForTests()), RestrictClockIdPolicy) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC_RAW, &ts); } #if defined(OS_CHROMEOS) // A custom BPF tester delegate to run IsRunningOnChromeOS() before // the sandbox is enabled because we cannot run it with non-SFI BPF // sandbox enabled. class ClockSystemTesterDelegate : public sandbox::BPFTesterDelegate { public: ClockSystemTesterDelegate() : is_running_on_chromeos_(base::SysInfo::IsRunningOnChromeOS()) {} ~ClockSystemTesterDelegate() override {} scoped_ptr<sandbox::bpf_dsl::Policy> GetSandboxBPFPolicy() override { return scoped_ptr<sandbox::bpf_dsl::Policy>(new RestrictClockIdPolicy()); } void RunTestFunction() override { if (is_running_on_chromeos_) { CheckClock(base::TimeTicks::kClockSystemTrace); } else { struct timespec ts; // kClockSystemTrace is 11, which is CLOCK_THREAD_CPUTIME_ID of // the init process (pid=1). If kernel supports this feature, // this may succeed even if this is not running on Chrome OS. We // just check this clock_gettime call does not crash. clock_gettime(base::TimeTicks::kClockSystemTrace, &ts); } } private: const bool is_running_on_chromeos_; DISALLOW_COPY_AND_ASSIGN(ClockSystemTesterDelegate); }; BPF_TEST_D(BPFTest, BPFTestWithDelegateClass, ClockSystemTesterDelegate); #elif defined(OS_LINUX) BPF_DEATH_TEST_C(ParameterRestrictions, clock_gettime_crash_system_trace, DEATH_SEGV_MESSAGE(sandbox::GetErrorMessageContentForTests()), RestrictClockIdPolicy) { struct timespec ts; clock_gettime(base::TimeTicks::kClockSystemTrace, &ts); } #endif // defined(OS_CHROMEOS) #if !defined(OS_ANDROID) BPF_DEATH_TEST_C(ParameterRestrictions, clock_gettime_crash_cpu_clock, DEATH_SEGV_MESSAGE(sandbox::GetErrorMessageContentForTests()), RestrictClockIdPolicy) { // We can't use clock_getcpuclockid() because it's not implemented in newlib, // and it might not work inside the sandbox anyway. const pid_t kInitPID = 1; const clockid_t kInitCPUClockID = MAKE_PROCESS_CPUCLOCK(kInitPID, CPUCLOCK_SCHED); struct timespec ts; clock_gettime(kInitCPUClockID, &ts); } #endif // !defined(OS_ANDROID) class RestrictSchedPolicy : public bpf_dsl::Policy { public: RestrictSchedPolicy() {} ~RestrictSchedPolicy() override {} ResultExpr EvaluateSyscall(int sysno) const override { switch (sysno) { case __NR_sched_getparam: return RestrictSchedTarget(getpid(), sysno); default: return Allow(); } } }; void CheckSchedGetParam(pid_t pid, struct sched_param* param) { BPF_ASSERT_EQ(0, sched_getparam(pid, param)); } void SchedGetParamThread(base::WaitableEvent* thread_run) { const pid_t pid = getpid(); const pid_t tid = sys_gettid(); BPF_ASSERT_NE(pid, tid); struct sched_param current_pid_param; CheckSchedGetParam(pid, &current_pid_param); struct sched_param zero_param; CheckSchedGetParam(0, &zero_param); struct sched_param tid_param; CheckSchedGetParam(tid, &tid_param); BPF_ASSERT_EQ(zero_param.sched_priority, tid_param.sched_priority); // Verify that the SIGSYS handler sets errno properly. errno = 0; BPF_ASSERT_EQ(-1, sched_getparam(tid, NULL)); BPF_ASSERT_EQ(EINVAL, errno); thread_run->Signal(); } BPF_TEST_C(ParameterRestrictions, sched_getparam_allowed, RestrictSchedPolicy) { base::WaitableEvent thread_run(true, false); // Run the actual test in a new thread so that the current pid and tid are // different. base::Thread getparam_thread("sched_getparam_thread"); BPF_ASSERT(getparam_thread.Start()); getparam_thread.message_loop()->PostTask( FROM_HERE, base::Bind(&SchedGetParamThread, &thread_run)); BPF_ASSERT(thread_run.TimedWait(base::TimeDelta::FromMilliseconds(5000))); getparam_thread.Stop(); } BPF_DEATH_TEST_C(ParameterRestrictions, sched_getparam_crash_non_zero, DEATH_SEGV_MESSAGE(sandbox::GetErrorMessageContentForTests()), RestrictSchedPolicy) { const pid_t kInitPID = 1; struct sched_param param; sched_getparam(kInitPID, &param); } class RestrictPrlimit64Policy : public bpf_dsl::Policy { public: RestrictPrlimit64Policy() {} ~RestrictPrlimit64Policy() override {} ResultExpr EvaluateSyscall(int sysno) const override { switch (sysno) { case __NR_prlimit64: return RestrictPrlimit64(getpid()); default: return Allow(); } } }; BPF_TEST_C(ParameterRestrictions, prlimit64_allowed, RestrictPrlimit64Policy) { BPF_ASSERT_EQ(0, sys_prlimit64(0, RLIMIT_AS, NULL, NULL)); BPF_ASSERT_EQ(0, sys_prlimit64(getpid(), RLIMIT_AS, NULL, NULL)); } BPF_DEATH_TEST_C(ParameterRestrictions, prlimit64_crash_not_self, DEATH_SEGV_MESSAGE(sandbox::GetErrorMessageContentForTests()), RestrictPrlimit64Policy) { const pid_t kInitPID = 1; BPF_ASSERT_NE(kInitPID, getpid()); sys_prlimit64(kInitPID, RLIMIT_AS, NULL, NULL); } } // namespace } // namespace sandbox <|endoftext|>
<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/android/edge_effect.h" #include "cc/layers/layer.h" namespace content { namespace { enum State { STATE_IDLE = 0, STATE_PULL, STATE_ABSORB, STATE_RECEDE, STATE_PULL_DECAY }; // Time it will take the effect to fully recede in ms const int kRecedeTime = 1000; // Time it will take before a pulled glow begins receding in ms const int kPullTime = 167; // Time it will take in ms for a pulled glow to decay before release const int kPullDecayTime = 1000; const float kMaxAlpha = 1.f; const float kHeldEdgeScaleY = .5f; const float kMaxGlowHeight = 4.f; const float kPullGlowBegin = 1.f; const float kPullEdgeBegin = 0.6f; // Min/max velocity that will be absorbed const float kMinVelocity = 100.f; const float kMaxVelocity = 10000.f; const float kEpsilon = 0.001f; const float kGlowHeightToWidthRatio = 0.25f; // How much dragging should effect the height of the edge image. // Number determined by user testing. const int kPullDistanceEdgeFactor = 7; // How much dragging should effect the height of the glow image. // Number determined by user testing. const int kPullDistanceGlowFactor = 7; const float kPullDistanceAlphaGlowFactor = 1.1f; const int kVelocityEdgeFactor = 8; const int kVelocityGlowFactor = 12; template <typename T> T Lerp(T a, T b, T t) { return a + (b - a) * t; } template <typename T> T Clamp(T value, T low, T high) { return value < low ? low : (value > high ? high : value); } template <typename T> T Damp(T input, T factor) { T result; if (factor == 1) { result = 1 - (1 - input) * (1 - input); } else { result = 1 - std::pow(1 - input, 2 * factor); } return result; } gfx::Transform ComputeTransform(EdgeEffect::Edge edge, const gfx::SizeF& window_size, int offset, int height) { // Edge effects that require rotation are translated to the center about which // the layer should be rotated to align with the corresponding edge. switch (edge) { case EdgeEffect::EDGE_TOP: return gfx::Transform(1, 0, 0, 1, 0, offset); case EdgeEffect::EDGE_LEFT: return gfx::Transform(0, 1, -1, 0, (-window_size.height() + height) / 2.f + offset, (window_size.height() - height) / 2.f); case EdgeEffect::EDGE_BOTTOM: return gfx::Transform(-1, 0, 0, -1, 0, window_size.height() - height + offset); case EdgeEffect::EDGE_RIGHT: return gfx::Transform(0, -1, 1, 0, (-window_size.height() - height) / 2.f + window_size.width() + offset, (window_size.height() - height) / 2.f); default: NOTREACHED() << "Invalid edge: " << edge; return gfx::Transform(); }; } gfx::Size ComputeBounds(EdgeEffect::Edge edge, const gfx::SizeF& window_size, int height) { switch (edge) { case EdgeEffect::EDGE_TOP: case EdgeEffect::EDGE_BOTTOM: return gfx::Size(window_size.width(), height); case EdgeEffect::EDGE_LEFT: case EdgeEffect::EDGE_RIGHT: return gfx::Size(window_size.height(), height); default: NOTREACHED() << "Invalid edge: " << edge; return gfx::Size(); }; } void DisableLayer(cc::Layer* layer) { DCHECK(layer); layer->SetIsDrawable(false); layer->SetTransform(gfx::Transform()); layer->SetOpacity(1.f); } void UpdateLayer(cc::Layer* layer, EdgeEffect::Edge edge, const gfx::SizeF& window_size, int offset, int height, float opacity) { DCHECK(layer); layer->SetIsDrawable(true); layer->SetTransform(ComputeTransform(edge, window_size, offset, height)); layer->SetBounds(ComputeBounds(edge, window_size, height)); layer->SetOpacity(Clamp(opacity, 0.f, 1.f)); } } // namespace EdgeEffect::EdgeEffect(scoped_refptr<cc::Layer> edge, scoped_refptr<cc::Layer> glow) : edge_(edge) , glow_(glow) , edge_alpha_(0) , edge_scale_y_(0) , glow_alpha_(0) , glow_scale_y_(0) , edge_alpha_start_(0) , edge_alpha_finish_(0) , edge_scale_y_start_(0) , edge_scale_y_finish_(0) , glow_alpha_start_(0) , glow_alpha_finish_(0) , glow_scale_y_start_(0) , glow_scale_y_finish_(0) , state_(STATE_IDLE) , pull_distance_(0) { // Prevent the provided layers from drawing until the effect is activated. DisableLayer(edge_.get()); DisableLayer(glow_.get()); } EdgeEffect::~EdgeEffect() { } bool EdgeEffect::IsFinished() const { return state_ == STATE_IDLE; } void EdgeEffect::Finish() { DisableLayer(edge_.get()); DisableLayer(glow_.get()); pull_distance_ = 0; state_ = STATE_IDLE; } void EdgeEffect::Pull(base::TimeTicks current_time, float delta_distance) { if (state_ == STATE_PULL_DECAY && current_time - start_time_ < duration_) { return; } if (state_ != STATE_PULL) { glow_scale_y_ = kPullGlowBegin; } state_ = STATE_PULL; start_time_ = current_time; duration_ = base::TimeDelta::FromMilliseconds(kPullTime); float abs_delta_distance = std::abs(delta_distance); pull_distance_ += delta_distance; float distance = std::abs(pull_distance_); edge_alpha_ = edge_alpha_start_ = Clamp(distance, kPullEdgeBegin, kMaxAlpha); edge_scale_y_ = edge_scale_y_start_ = Clamp(distance * kPullDistanceEdgeFactor, kHeldEdgeScaleY, 1.f); glow_alpha_ = glow_alpha_start_ = std::min(kMaxAlpha, glow_alpha_ + abs_delta_distance * kPullDistanceAlphaGlowFactor); float glow_change = abs_delta_distance; if (delta_distance > 0 && pull_distance_ < 0) glow_change = -glow_change; if (pull_distance_ == 0) glow_scale_y_ = 0; // Do not allow glow to get larger than kMaxGlowHeight. glow_scale_y_ = glow_scale_y_start_ = Clamp(glow_scale_y_ + glow_change * kPullDistanceGlowFactor, 0.f, kMaxGlowHeight); edge_alpha_finish_ = edge_alpha_; edge_scale_y_finish_ = edge_scale_y_; glow_alpha_finish_ = glow_alpha_; glow_scale_y_finish_ = glow_scale_y_; } void EdgeEffect::Release(base::TimeTicks current_time) { pull_distance_ = 0; if (state_ != STATE_PULL && state_ != STATE_PULL_DECAY) return; state_ = STATE_RECEDE; edge_alpha_start_ = edge_alpha_; edge_scale_y_start_ = edge_scale_y_; glow_alpha_start_ = glow_alpha_; glow_scale_y_start_ = glow_scale_y_; edge_alpha_finish_ = 0.f; edge_scale_y_finish_ = 0.f; glow_alpha_finish_ = 0.f; glow_scale_y_finish_ = 0.f; start_time_ = current_time; duration_ = base::TimeDelta::FromMilliseconds(kRecedeTime); } void EdgeEffect::Absorb(base::TimeTicks current_time, float velocity) { state_ = STATE_ABSORB; velocity = Clamp(std::abs(velocity), kMinVelocity, kMaxVelocity); start_time_ = current_time; // This should never be less than 1 millisecond. duration_ = base::TimeDelta::FromMilliseconds(0.15f + (velocity * 0.02f)); // The edge should always be at least partially visible, regardless // of velocity. edge_alpha_start_ = 0.f; edge_scale_y_ = edge_scale_y_start_ = 0.f; // The glow depends more on the velocity, and therefore starts out // nearly invisible. glow_alpha_start_ = 0.3f; glow_scale_y_start_ = 0.f; // Factor the velocity by 8. Testing on device shows this works best to // reflect the strength of the user's scrolling. edge_alpha_finish_ = Clamp(velocity * kVelocityEdgeFactor, 0.f, 1.f); // Edge should never get larger than the size of its asset. edge_scale_y_finish_ = Clamp(velocity * kVelocityEdgeFactor, kHeldEdgeScaleY, 1.f); // Growth for the size of the glow should be quadratic to properly // respond // to a user's scrolling speed. The faster the scrolling speed, the more // intense the effect should be for both the size and the saturation. glow_scale_y_finish_ = std::min( 0.025f + (velocity * (velocity / 100) * 0.00015f), 1.75f); // Alpha should change for the glow as well as size. glow_alpha_finish_ = Clamp(glow_alpha_start_, velocity * kVelocityGlowFactor * .00001f, kMaxAlpha); } bool EdgeEffect::Update(base::TimeTicks current_time) { if (IsFinished()) return false; const double dt = (current_time - start_time_).InMilliseconds(); const double t = std::min(dt / duration_.InMilliseconds(), 1.); const float interp = static_cast<float>(Damp(t, 1.)); edge_alpha_ = Lerp(edge_alpha_start_, edge_alpha_finish_, interp); edge_scale_y_ = Lerp(edge_scale_y_start_, edge_scale_y_finish_, interp); glow_alpha_ = Lerp(glow_alpha_start_, glow_alpha_finish_, interp); glow_scale_y_ = Lerp(glow_scale_y_start_, glow_scale_y_finish_, interp); if (t >= 1.f - kEpsilon) { switch (state_) { case STATE_ABSORB: state_ = STATE_RECEDE; start_time_ = current_time; duration_ = base::TimeDelta::FromMilliseconds(kRecedeTime); edge_alpha_start_ = edge_alpha_; edge_scale_y_start_ = edge_scale_y_; glow_alpha_start_ = glow_alpha_; glow_scale_y_start_ = glow_scale_y_; // After absorb, the glow and edge should fade to nothing. edge_alpha_finish_ = 0.f; edge_scale_y_finish_ = 0.f; glow_alpha_finish_ = 0.f; glow_scale_y_finish_ = 0.f; break; case STATE_PULL: state_ = STATE_PULL_DECAY; start_time_ = current_time; duration_ = base::TimeDelta::FromMilliseconds(kPullDecayTime); edge_alpha_start_ = edge_alpha_; edge_scale_y_start_ = edge_scale_y_; glow_alpha_start_ = glow_alpha_; glow_scale_y_start_ = glow_scale_y_; // After pull, the glow and edge should fade to nothing. edge_alpha_finish_ = 0.f; edge_scale_y_finish_ = 0.f; glow_alpha_finish_ = 0.f; glow_scale_y_finish_ = 0.f; break; case STATE_PULL_DECAY: { // When receding, we want edge to decrease more slowly // than the glow. const float factor = glow_scale_y_finish_ != 0 ? 1 / (glow_scale_y_finish_ * glow_scale_y_finish_) : std::numeric_limits<float>::max(); edge_scale_y_ = edge_scale_y_start_ + (edge_scale_y_finish_ - edge_scale_y_start_) * interp * factor; state_ = STATE_RECEDE; } break; case STATE_RECEDE: Finish(); break; default: break; } } if (state_ == STATE_RECEDE && glow_scale_y_ <= 0 && edge_scale_y_ <= 0) Finish(); return !IsFinished(); } void EdgeEffect::ApplyToLayers(gfx::SizeF window_size, Edge edge, float edge_height, float glow_height, float offset) { if (IsFinished()) return; // An empty window size, while meaningless, is also relatively harmless, and // will simply prevent any drawing of the layers. if (window_size.IsEmpty()) { DisableLayer(edge_.get()); DisableLayer(glow_.get()); return; } // Glow const int scaled_glow_height = static_cast<int>( std::min(glow_height * glow_scale_y_ * kGlowHeightToWidthRatio * 0.6f, glow_height * kMaxGlowHeight) + 0.5f); UpdateLayer( glow_.get(), edge, window_size, offset, scaled_glow_height, glow_alpha_); // Edge const int scaled_edge_height = static_cast<int>(edge_height * edge_scale_y_); UpdateLayer( edge_.get(), edge, window_size, offset, scaled_edge_height, edge_alpha_); } } // namespace content <commit_msg>[Android] Use SetTransformOrigin for glow-effect layers<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/android/edge_effect.h" #include "cc/layers/layer.h" namespace content { namespace { enum State { STATE_IDLE = 0, STATE_PULL, STATE_ABSORB, STATE_RECEDE, STATE_PULL_DECAY }; // Time it will take the effect to fully recede in ms const int kRecedeTime = 1000; // Time it will take before a pulled glow begins receding in ms const int kPullTime = 167; // Time it will take in ms for a pulled glow to decay before release const int kPullDecayTime = 1000; const float kMaxAlpha = 1.f; const float kHeldEdgeScaleY = .5f; const float kMaxGlowHeight = 4.f; const float kPullGlowBegin = 1.f; const float kPullEdgeBegin = 0.6f; // Min/max velocity that will be absorbed const float kMinVelocity = 100.f; const float kMaxVelocity = 10000.f; const float kEpsilon = 0.001f; const float kGlowHeightToWidthRatio = 0.25f; // How much dragging should effect the height of the edge image. // Number determined by user testing. const int kPullDistanceEdgeFactor = 7; // How much dragging should effect the height of the glow image. // Number determined by user testing. const int kPullDistanceGlowFactor = 7; const float kPullDistanceAlphaGlowFactor = 1.1f; const int kVelocityEdgeFactor = 8; const int kVelocityGlowFactor = 12; template <typename T> T Lerp(T a, T b, T t) { return a + (b - a) * t; } template <typename T> T Clamp(T value, T low, T high) { return value < low ? low : (value > high ? high : value); } template <typename T> T Damp(T input, T factor) { T result; if (factor == 1) { result = 1 - (1 - input) * (1 - input); } else { result = 1 - std::pow(1 - input, 2 * factor); } return result; } gfx::Transform ComputeTransform(EdgeEffect::Edge edge, const gfx::SizeF& window_size, int offset, int height) { // Edge effects that require rotation are translated to the center about which // the layer should be rotated to align with the corresponding edge. switch (edge) { case EdgeEffect::EDGE_TOP: return gfx::Transform(1, 0, 0, 1, 0, offset); case EdgeEffect::EDGE_LEFT: return gfx::Transform(0, 1, -1, 0, (-window_size.height() + height) / 2.f + offset, (window_size.height() - height) / 2.f); case EdgeEffect::EDGE_BOTTOM: return gfx::Transform(-1, 0, 0, -1, 0, window_size.height() - height + offset); case EdgeEffect::EDGE_RIGHT: return gfx::Transform(0, -1, 1, 0, (-window_size.height() - height) / 2.f + window_size.width() + offset, (window_size.height() - height) / 2.f); default: NOTREACHED() << "Invalid edge: " << edge; return gfx::Transform(); }; } gfx::Size ComputeBounds(EdgeEffect::Edge edge, const gfx::SizeF& window_size, int height) { switch (edge) { case EdgeEffect::EDGE_TOP: case EdgeEffect::EDGE_BOTTOM: return gfx::Size(window_size.width(), height); case EdgeEffect::EDGE_LEFT: case EdgeEffect::EDGE_RIGHT: return gfx::Size(window_size.height(), height); default: NOTREACHED() << "Invalid edge: " << edge; return gfx::Size(); }; } void DisableLayer(cc::Layer* layer) { DCHECK(layer); layer->SetIsDrawable(false); layer->SetTransform(gfx::Transform()); layer->SetOpacity(1.f); } void UpdateLayer(cc::Layer* layer, EdgeEffect::Edge edge, const gfx::SizeF& window_size, int offset, int height, float opacity) { DCHECK(layer); layer->SetIsDrawable(true); gfx::Size bounds = ComputeBounds(edge, window_size, height); layer->SetTransformOrigin( gfx::Point3F(bounds.width() * 0.5f, bounds.height() * 0.5f, 0)); layer->SetTransform(ComputeTransform(edge, window_size, offset, height)); layer->SetBounds(bounds); layer->SetOpacity(Clamp(opacity, 0.f, 1.f)); } } // namespace EdgeEffect::EdgeEffect(scoped_refptr<cc::Layer> edge, scoped_refptr<cc::Layer> glow) : edge_(edge) , glow_(glow) , edge_alpha_(0) , edge_scale_y_(0) , glow_alpha_(0) , glow_scale_y_(0) , edge_alpha_start_(0) , edge_alpha_finish_(0) , edge_scale_y_start_(0) , edge_scale_y_finish_(0) , glow_alpha_start_(0) , glow_alpha_finish_(0) , glow_scale_y_start_(0) , glow_scale_y_finish_(0) , state_(STATE_IDLE) , pull_distance_(0) { // Prevent the provided layers from drawing until the effect is activated. DisableLayer(edge_.get()); DisableLayer(glow_.get()); } EdgeEffect::~EdgeEffect() { } bool EdgeEffect::IsFinished() const { return state_ == STATE_IDLE; } void EdgeEffect::Finish() { DisableLayer(edge_.get()); DisableLayer(glow_.get()); pull_distance_ = 0; state_ = STATE_IDLE; } void EdgeEffect::Pull(base::TimeTicks current_time, float delta_distance) { if (state_ == STATE_PULL_DECAY && current_time - start_time_ < duration_) { return; } if (state_ != STATE_PULL) { glow_scale_y_ = kPullGlowBegin; } state_ = STATE_PULL; start_time_ = current_time; duration_ = base::TimeDelta::FromMilliseconds(kPullTime); float abs_delta_distance = std::abs(delta_distance); pull_distance_ += delta_distance; float distance = std::abs(pull_distance_); edge_alpha_ = edge_alpha_start_ = Clamp(distance, kPullEdgeBegin, kMaxAlpha); edge_scale_y_ = edge_scale_y_start_ = Clamp(distance * kPullDistanceEdgeFactor, kHeldEdgeScaleY, 1.f); glow_alpha_ = glow_alpha_start_ = std::min(kMaxAlpha, glow_alpha_ + abs_delta_distance * kPullDistanceAlphaGlowFactor); float glow_change = abs_delta_distance; if (delta_distance > 0 && pull_distance_ < 0) glow_change = -glow_change; if (pull_distance_ == 0) glow_scale_y_ = 0; // Do not allow glow to get larger than kMaxGlowHeight. glow_scale_y_ = glow_scale_y_start_ = Clamp(glow_scale_y_ + glow_change * kPullDistanceGlowFactor, 0.f, kMaxGlowHeight); edge_alpha_finish_ = edge_alpha_; edge_scale_y_finish_ = edge_scale_y_; glow_alpha_finish_ = glow_alpha_; glow_scale_y_finish_ = glow_scale_y_; } void EdgeEffect::Release(base::TimeTicks current_time) { pull_distance_ = 0; if (state_ != STATE_PULL && state_ != STATE_PULL_DECAY) return; state_ = STATE_RECEDE; edge_alpha_start_ = edge_alpha_; edge_scale_y_start_ = edge_scale_y_; glow_alpha_start_ = glow_alpha_; glow_scale_y_start_ = glow_scale_y_; edge_alpha_finish_ = 0.f; edge_scale_y_finish_ = 0.f; glow_alpha_finish_ = 0.f; glow_scale_y_finish_ = 0.f; start_time_ = current_time; duration_ = base::TimeDelta::FromMilliseconds(kRecedeTime); } void EdgeEffect::Absorb(base::TimeTicks current_time, float velocity) { state_ = STATE_ABSORB; velocity = Clamp(std::abs(velocity), kMinVelocity, kMaxVelocity); start_time_ = current_time; // This should never be less than 1 millisecond. duration_ = base::TimeDelta::FromMilliseconds(0.15f + (velocity * 0.02f)); // The edge should always be at least partially visible, regardless // of velocity. edge_alpha_start_ = 0.f; edge_scale_y_ = edge_scale_y_start_ = 0.f; // The glow depends more on the velocity, and therefore starts out // nearly invisible. glow_alpha_start_ = 0.3f; glow_scale_y_start_ = 0.f; // Factor the velocity by 8. Testing on device shows this works best to // reflect the strength of the user's scrolling. edge_alpha_finish_ = Clamp(velocity * kVelocityEdgeFactor, 0.f, 1.f); // Edge should never get larger than the size of its asset. edge_scale_y_finish_ = Clamp(velocity * kVelocityEdgeFactor, kHeldEdgeScaleY, 1.f); // Growth for the size of the glow should be quadratic to properly // respond // to a user's scrolling speed. The faster the scrolling speed, the more // intense the effect should be for both the size and the saturation. glow_scale_y_finish_ = std::min( 0.025f + (velocity * (velocity / 100) * 0.00015f), 1.75f); // Alpha should change for the glow as well as size. glow_alpha_finish_ = Clamp(glow_alpha_start_, velocity * kVelocityGlowFactor * .00001f, kMaxAlpha); } bool EdgeEffect::Update(base::TimeTicks current_time) { if (IsFinished()) return false; const double dt = (current_time - start_time_).InMilliseconds(); const double t = std::min(dt / duration_.InMilliseconds(), 1.); const float interp = static_cast<float>(Damp(t, 1.)); edge_alpha_ = Lerp(edge_alpha_start_, edge_alpha_finish_, interp); edge_scale_y_ = Lerp(edge_scale_y_start_, edge_scale_y_finish_, interp); glow_alpha_ = Lerp(glow_alpha_start_, glow_alpha_finish_, interp); glow_scale_y_ = Lerp(glow_scale_y_start_, glow_scale_y_finish_, interp); if (t >= 1.f - kEpsilon) { switch (state_) { case STATE_ABSORB: state_ = STATE_RECEDE; start_time_ = current_time; duration_ = base::TimeDelta::FromMilliseconds(kRecedeTime); edge_alpha_start_ = edge_alpha_; edge_scale_y_start_ = edge_scale_y_; glow_alpha_start_ = glow_alpha_; glow_scale_y_start_ = glow_scale_y_; // After absorb, the glow and edge should fade to nothing. edge_alpha_finish_ = 0.f; edge_scale_y_finish_ = 0.f; glow_alpha_finish_ = 0.f; glow_scale_y_finish_ = 0.f; break; case STATE_PULL: state_ = STATE_PULL_DECAY; start_time_ = current_time; duration_ = base::TimeDelta::FromMilliseconds(kPullDecayTime); edge_alpha_start_ = edge_alpha_; edge_scale_y_start_ = edge_scale_y_; glow_alpha_start_ = glow_alpha_; glow_scale_y_start_ = glow_scale_y_; // After pull, the glow and edge should fade to nothing. edge_alpha_finish_ = 0.f; edge_scale_y_finish_ = 0.f; glow_alpha_finish_ = 0.f; glow_scale_y_finish_ = 0.f; break; case STATE_PULL_DECAY: { // When receding, we want edge to decrease more slowly // than the glow. const float factor = glow_scale_y_finish_ != 0 ? 1 / (glow_scale_y_finish_ * glow_scale_y_finish_) : std::numeric_limits<float>::max(); edge_scale_y_ = edge_scale_y_start_ + (edge_scale_y_finish_ - edge_scale_y_start_) * interp * factor; state_ = STATE_RECEDE; } break; case STATE_RECEDE: Finish(); break; default: break; } } if (state_ == STATE_RECEDE && glow_scale_y_ <= 0 && edge_scale_y_ <= 0) Finish(); return !IsFinished(); } void EdgeEffect::ApplyToLayers(gfx::SizeF window_size, Edge edge, float edge_height, float glow_height, float offset) { if (IsFinished()) return; // An empty window size, while meaningless, is also relatively harmless, and // will simply prevent any drawing of the layers. if (window_size.IsEmpty()) { DisableLayer(edge_.get()); DisableLayer(glow_.get()); return; } // Glow const int scaled_glow_height = static_cast<int>( std::min(glow_height * glow_scale_y_ * kGlowHeightToWidthRatio * 0.6f, glow_height * kMaxGlowHeight) + 0.5f); UpdateLayer( glow_.get(), edge, window_size, offset, scaled_glow_height, glow_alpha_); // Edge const int scaled_edge_height = static_cast<int>(edge_height * edge_scale_y_); UpdateLayer( edge_.get(), edge, window_size, offset, scaled_edge_height, edge_alpha_); } } // namespace content <|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/gpu/compositor_util.h" #include "base/command_line.h" #include "base/logging.h" #include "base/metrics/field_trial.h" #include "base/strings/string_number_conversions.h" #include "base/sys_info.h" #include "build/build_config.h" #include "cc/base/switches.h" #include "content/browser/gpu/gpu_data_manager_impl.h" #include "content/public/common/content_switches.h" #include "gpu/config/gpu_feature_type.h" namespace content { namespace { static bool IsGpuRasterizationBlacklisted() { GpuDataManagerImpl* manager = GpuDataManagerImpl::GetInstance(); return manager->IsFeatureBlacklisted( gpu::GPU_FEATURE_TYPE_GPU_RASTERIZATION); } const char* kGpuCompositingFeatureName = "gpu_compositing"; const char* kWebGLFeatureName = "webgl"; const char* kRasterizationFeatureName = "rasterization"; const char* kThreadedRasterizationFeatureName = "threaded_rasterization"; const char* kMultipleRasterThreadsFeatureName = "multiple_raster_threads"; const int kMinRasterThreads = 1; const int kMaxRasterThreads = 64; const int kMinMSAASampleCount = 0; struct GpuFeatureInfo { std::string name; bool blocked; bool disabled; std::string disabled_description; bool fallback_to_software; }; const GpuFeatureInfo GetGpuFeatureInfo(size_t index, bool* eof) { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); GpuDataManagerImpl* manager = GpuDataManagerImpl::GetInstance(); const GpuFeatureInfo kGpuFeatureInfo[] = { { "2d_canvas", manager->IsFeatureBlacklisted( gpu::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS), command_line.HasSwitch(switches::kDisableAccelerated2dCanvas) || !GpuDataManagerImpl::GetInstance()-> GetGPUInfo().SupportsAccelerated2dCanvas(), "Accelerated 2D canvas is unavailable: either disabled at the command" " line or not supported by the current system.", true }, { kGpuCompositingFeatureName, manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_GPU_COMPOSITING), command_line.HasSwitch(switches::kDisableGpuCompositing), "Gpu compositing has been disabled, either via about:flags or" " command line. The browser will fall back to software compositing" " and hardware acceleration will be unavailable.", true }, { kWebGLFeatureName, manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_WEBGL), command_line.HasSwitch(switches::kDisableExperimentalWebGL), "WebGL has been disabled, either via about:flags or command line.", false }, { "flash_3d", manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_FLASH3D), command_line.HasSwitch(switches::kDisableFlash3d), "Using 3d in flash has been disabled, either via about:flags or" " command line.", true }, { "flash_stage3d", manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_FLASH_STAGE3D), command_line.HasSwitch(switches::kDisableFlashStage3d), "Using Stage3d in Flash has been disabled, either via about:flags or" " command line.", true }, { "flash_stage3d_baseline", manager->IsFeatureBlacklisted( gpu::GPU_FEATURE_TYPE_FLASH_STAGE3D_BASELINE) || manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_FLASH_STAGE3D), command_line.HasSwitch(switches::kDisableFlashStage3d), "Using Stage3d Baseline profile in Flash has been disabled, either" " via about:flags or command line.", true }, { "video_decode", manager->IsFeatureBlacklisted( gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_DECODE), command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode), "Accelerated video decode has been disabled, either via about:flags" " or command line.", true }, #if defined(ENABLE_WEBRTC) { "video_encode", manager->IsFeatureBlacklisted( gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_ENCODE), command_line.HasSwitch(switches::kDisableWebRtcHWEncoding), "Accelerated video encode has been disabled, either via about:flags" " or command line.", true }, #endif #if defined(OS_CHROMEOS) { "panel_fitting", manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_PANEL_FITTING), command_line.HasSwitch(switches::kDisablePanelFitting), "Panel fitting has been disabled, either via about:flags or command" " line.", false }, #endif { kRasterizationFeatureName, IsGpuRasterizationBlacklisted() && !IsGpuRasterizationEnabled() && !IsForceGpuRasterizationEnabled(), !IsGpuRasterizationEnabled() && !IsForceGpuRasterizationEnabled() && !IsGpuRasterizationBlacklisted(), "Accelerated rasterization has been disabled, either via about:flags" " or command line.", true }, { kThreadedRasterizationFeatureName, false, !IsImplSidePaintingEnabled(), "Threaded rasterization has not been enabled or" " is not supported by the current system.", false }, { kMultipleRasterThreadsFeatureName, false, NumberOfRendererRasterThreads() == 1, "Raster is using a single thread.", false }, }; DCHECK(index < arraysize(kGpuFeatureInfo)); *eof = (index == arraysize(kGpuFeatureInfo) - 1); return kGpuFeatureInfo[index]; } } // namespace bool IsPinchVirtualViewportEnabled() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); // Command line switches take precedence over platform default. if (command_line.HasSwitch(cc::switches::kDisablePinchVirtualViewport)) return false; if (command_line.HasSwitch(cc::switches::kEnablePinchVirtualViewport)) return true; return true; } bool IsPropertyTreeVerificationEnabled() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); return command_line.HasSwitch(cc::switches::kEnablePropertyTreeVerification); } bool IsDelegatedRendererEnabled() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); bool enabled = false; #if defined(USE_AURA) || defined(OS_MACOSX) // Enable on Aura and Mac. enabled = true; #endif // Flags override. enabled |= command_line.HasSwitch(switches::kEnableDelegatedRenderer); enabled &= !command_line.HasSwitch(switches::kDisableDelegatedRenderer); return enabled; } bool IsImplSidePaintingEnabled() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kDisableImplSidePainting)) return false; return true; } int NumberOfRendererRasterThreads() { int num_raster_threads = 1; // Async uploads uses its own thread, so allow an extra thread when async // uploads is not in use. bool allow_extra_thread = IsZeroCopyUploadEnabled() || IsOneCopyUploadEnabled(); if (base::SysInfo::NumberOfProcessors() >= 4 && allow_extra_thread) num_raster_threads = 2; int force_num_raster_threads = ForceNumberOfRendererRasterThreads(); if (force_num_raster_threads) num_raster_threads = force_num_raster_threads; return num_raster_threads; } bool IsOneCopyUploadEnabled() { if (IsZeroCopyUploadEnabled()) return false; const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kEnableOneCopy)) return true; if (command_line.HasSwitch(switches::kDisableOneCopy)) return false; #if defined(OS_ANDROID) return false; #endif return true; } bool IsZeroCopyUploadEnabled() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); return command_line.HasSwitch(switches::kEnableZeroCopy); } int ForceNumberOfRendererRasterThreads() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); if (!command_line.HasSwitch(switches::kNumRasterThreads)) return 0; std::string string_value = command_line.GetSwitchValueASCII(switches::kNumRasterThreads); int force_num_raster_threads = 0; if (base::StringToInt(string_value, &force_num_raster_threads) && force_num_raster_threads >= kMinRasterThreads && force_num_raster_threads <= kMaxRasterThreads) { return force_num_raster_threads; } else { DLOG(WARNING) << "Failed to parse switch " << switches::kNumRasterThreads << ": " << string_value; return 0; } } bool IsGpuRasterizationEnabled() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); if (!IsImplSidePaintingEnabled()) return false; if (command_line.HasSwitch(switches::kDisableGpuRasterization)) return false; else if (command_line.HasSwitch(switches::kEnableGpuRasterization)) return true; if (IsGpuRasterizationBlacklisted()) { return false; } return true; } bool IsForceGpuRasterizationEnabled() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); if (!IsImplSidePaintingEnabled()) return false; return command_line.HasSwitch(switches::kForceGpuRasterization); } bool IsThreadedGpuRasterizationEnabled() { if (!IsImplSidePaintingEnabled()) return false; if (!IsGpuRasterizationEnabled() && !IsForceGpuRasterizationEnabled()) return false; const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kDisableThreadedGpuRasterization)) return false; return true; } bool UseSurfacesEnabled() { #if defined(OS_ANDROID) return true; #endif bool enabled = false; #if (defined(USE_AURA) && !defined(OS_CHROMEOS)) || defined(OS_MACOSX) enabled = true; #endif const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); // Flags override. enabled |= command_line.HasSwitch(switches::kUseSurfaces); enabled &= !command_line.HasSwitch(switches::kDisableSurfaces); return enabled; } int GpuRasterizationMSAASampleCount() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); if (!command_line.HasSwitch(switches::kGpuRasterizationMSAASampleCount)) return 0; std::string string_value = command_line.GetSwitchValueASCII( switches::kGpuRasterizationMSAASampleCount); int msaa_sample_count = 0; if (base::StringToInt(string_value, &msaa_sample_count) && msaa_sample_count >= kMinMSAASampleCount) { return msaa_sample_count; } else { DLOG(WARNING) << "Failed to parse switch " << switches::kGpuRasterizationMSAASampleCount << ": " << string_value; return 0; } } base::DictionaryValue* GetFeatureStatus() { GpuDataManagerImpl* manager = GpuDataManagerImpl::GetInstance(); std::string gpu_access_blocked_reason; bool gpu_access_blocked = !manager->GpuAccessAllowed(&gpu_access_blocked_reason); base::DictionaryValue* feature_status_dict = new base::DictionaryValue(); bool eof = false; for (size_t i = 0; !eof; ++i) { const GpuFeatureInfo gpu_feature_info = GetGpuFeatureInfo(i, &eof); std::string status; if (gpu_feature_info.disabled) { status = "disabled"; if (gpu_feature_info.fallback_to_software) status += "_software"; else status += "_off"; if (gpu_feature_info.name == kThreadedRasterizationFeatureName) status += "_ok"; } else if (gpu_feature_info.blocked || gpu_access_blocked) { status = "unavailable"; if (gpu_feature_info.fallback_to_software) status += "_software"; else status += "_off"; } else { status = "enabled"; if (gpu_feature_info.name == kWebGLFeatureName && manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_GPU_COMPOSITING)) status += "_readback"; if (gpu_feature_info.name == kRasterizationFeatureName) { if (IsForceGpuRasterizationEnabled()) status += "_force"; } if (gpu_feature_info.name == kMultipleRasterThreadsFeatureName) { if (ForceNumberOfRendererRasterThreads() > 0) status += "_force"; } if (gpu_feature_info.name == kThreadedRasterizationFeatureName || gpu_feature_info.name == kMultipleRasterThreadsFeatureName) status += "_on"; } if (gpu_feature_info.name == kWebGLFeatureName && (gpu_feature_info.blocked || gpu_access_blocked) && manager->ShouldUseSwiftShader()) { status = "unavailable_software"; } feature_status_dict->SetString( gpu_feature_info.name.c_str(), status.c_str()); } return feature_status_dict; } base::Value* GetProblems() { GpuDataManagerImpl* manager = GpuDataManagerImpl::GetInstance(); std::string gpu_access_blocked_reason; bool gpu_access_blocked = !manager->GpuAccessAllowed(&gpu_access_blocked_reason); base::ListValue* problem_list = new base::ListValue(); manager->GetBlacklistReasons(problem_list); if (gpu_access_blocked) { base::DictionaryValue* problem = new base::DictionaryValue(); problem->SetString("description", "GPU process was unable to boot: " + gpu_access_blocked_reason); problem->Set("crBugs", new base::ListValue()); problem->Set("webkitBugs", new base::ListValue()); base::ListValue* disabled_features = new base::ListValue(); disabled_features->AppendString("all"); problem->Set("affectedGpuSettings", disabled_features); problem->SetString("tag", "disabledFeatures"); problem_list->Insert(0, problem); } bool eof = false; for (size_t i = 0; !eof; ++i) { const GpuFeatureInfo gpu_feature_info = GetGpuFeatureInfo(i, &eof); if (gpu_feature_info.disabled) { base::DictionaryValue* problem = new base::DictionaryValue(); problem->SetString( "description", gpu_feature_info.disabled_description); problem->Set("crBugs", new base::ListValue()); problem->Set("webkitBugs", new base::ListValue()); base::ListValue* disabled_features = new base::ListValue(); disabled_features->AppendString(gpu_feature_info.name); problem->Set("affectedGpuSettings", disabled_features); problem->SetString("tag", "disabledFeatures"); problem_list->Append(problem); } } return problem_list; } std::vector<std::string> GetDriverBugWorkarounds() { return GpuDataManagerImpl::GetInstance()->GetDriverBugWorkarounds(); } } // namespace content <commit_msg>Revert of Enable Surfaces on Android (try #3) (patchset #1 id:1 of https://codereview.chromium.org/1001203002/)<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/gpu/compositor_util.h" #include "base/command_line.h" #include "base/logging.h" #include "base/metrics/field_trial.h" #include "base/strings/string_number_conversions.h" #include "base/sys_info.h" #include "build/build_config.h" #include "cc/base/switches.h" #include "content/browser/gpu/gpu_data_manager_impl.h" #include "content/public/common/content_switches.h" #include "gpu/config/gpu_feature_type.h" namespace content { namespace { static bool IsGpuRasterizationBlacklisted() { GpuDataManagerImpl* manager = GpuDataManagerImpl::GetInstance(); return manager->IsFeatureBlacklisted( gpu::GPU_FEATURE_TYPE_GPU_RASTERIZATION); } const char* kGpuCompositingFeatureName = "gpu_compositing"; const char* kWebGLFeatureName = "webgl"; const char* kRasterizationFeatureName = "rasterization"; const char* kThreadedRasterizationFeatureName = "threaded_rasterization"; const char* kMultipleRasterThreadsFeatureName = "multiple_raster_threads"; const int kMinRasterThreads = 1; const int kMaxRasterThreads = 64; const int kMinMSAASampleCount = 0; struct GpuFeatureInfo { std::string name; bool blocked; bool disabled; std::string disabled_description; bool fallback_to_software; }; const GpuFeatureInfo GetGpuFeatureInfo(size_t index, bool* eof) { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); GpuDataManagerImpl* manager = GpuDataManagerImpl::GetInstance(); const GpuFeatureInfo kGpuFeatureInfo[] = { { "2d_canvas", manager->IsFeatureBlacklisted( gpu::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS), command_line.HasSwitch(switches::kDisableAccelerated2dCanvas) || !GpuDataManagerImpl::GetInstance()-> GetGPUInfo().SupportsAccelerated2dCanvas(), "Accelerated 2D canvas is unavailable: either disabled at the command" " line or not supported by the current system.", true }, { kGpuCompositingFeatureName, manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_GPU_COMPOSITING), command_line.HasSwitch(switches::kDisableGpuCompositing), "Gpu compositing has been disabled, either via about:flags or" " command line. The browser will fall back to software compositing" " and hardware acceleration will be unavailable.", true }, { kWebGLFeatureName, manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_WEBGL), command_line.HasSwitch(switches::kDisableExperimentalWebGL), "WebGL has been disabled, either via about:flags or command line.", false }, { "flash_3d", manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_FLASH3D), command_line.HasSwitch(switches::kDisableFlash3d), "Using 3d in flash has been disabled, either via about:flags or" " command line.", true }, { "flash_stage3d", manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_FLASH_STAGE3D), command_line.HasSwitch(switches::kDisableFlashStage3d), "Using Stage3d in Flash has been disabled, either via about:flags or" " command line.", true }, { "flash_stage3d_baseline", manager->IsFeatureBlacklisted( gpu::GPU_FEATURE_TYPE_FLASH_STAGE3D_BASELINE) || manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_FLASH_STAGE3D), command_line.HasSwitch(switches::kDisableFlashStage3d), "Using Stage3d Baseline profile in Flash has been disabled, either" " via about:flags or command line.", true }, { "video_decode", manager->IsFeatureBlacklisted( gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_DECODE), command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode), "Accelerated video decode has been disabled, either via about:flags" " or command line.", true }, #if defined(ENABLE_WEBRTC) { "video_encode", manager->IsFeatureBlacklisted( gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_ENCODE), command_line.HasSwitch(switches::kDisableWebRtcHWEncoding), "Accelerated video encode has been disabled, either via about:flags" " or command line.", true }, #endif #if defined(OS_CHROMEOS) { "panel_fitting", manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_PANEL_FITTING), command_line.HasSwitch(switches::kDisablePanelFitting), "Panel fitting has been disabled, either via about:flags or command" " line.", false }, #endif { kRasterizationFeatureName, IsGpuRasterizationBlacklisted() && !IsGpuRasterizationEnabled() && !IsForceGpuRasterizationEnabled(), !IsGpuRasterizationEnabled() && !IsForceGpuRasterizationEnabled() && !IsGpuRasterizationBlacklisted(), "Accelerated rasterization has been disabled, either via about:flags" " or command line.", true }, { kThreadedRasterizationFeatureName, false, !IsImplSidePaintingEnabled(), "Threaded rasterization has not been enabled or" " is not supported by the current system.", false }, { kMultipleRasterThreadsFeatureName, false, NumberOfRendererRasterThreads() == 1, "Raster is using a single thread.", false }, }; DCHECK(index < arraysize(kGpuFeatureInfo)); *eof = (index == arraysize(kGpuFeatureInfo) - 1); return kGpuFeatureInfo[index]; } } // namespace bool IsPinchVirtualViewportEnabled() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); // Command line switches take precedence over platform default. if (command_line.HasSwitch(cc::switches::kDisablePinchVirtualViewport)) return false; if (command_line.HasSwitch(cc::switches::kEnablePinchVirtualViewport)) return true; return true; } bool IsPropertyTreeVerificationEnabled() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); return command_line.HasSwitch(cc::switches::kEnablePropertyTreeVerification); } bool IsDelegatedRendererEnabled() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); bool enabled = false; #if defined(USE_AURA) || defined(OS_MACOSX) // Enable on Aura and Mac. enabled = true; #endif // Flags override. enabled |= command_line.HasSwitch(switches::kEnableDelegatedRenderer); enabled &= !command_line.HasSwitch(switches::kDisableDelegatedRenderer); return enabled; } bool IsImplSidePaintingEnabled() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kDisableImplSidePainting)) return false; return true; } int NumberOfRendererRasterThreads() { int num_raster_threads = 1; // Async uploads uses its own thread, so allow an extra thread when async // uploads is not in use. bool allow_extra_thread = IsZeroCopyUploadEnabled() || IsOneCopyUploadEnabled(); if (base::SysInfo::NumberOfProcessors() >= 4 && allow_extra_thread) num_raster_threads = 2; int force_num_raster_threads = ForceNumberOfRendererRasterThreads(); if (force_num_raster_threads) num_raster_threads = force_num_raster_threads; return num_raster_threads; } bool IsOneCopyUploadEnabled() { if (IsZeroCopyUploadEnabled()) return false; const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kEnableOneCopy)) return true; if (command_line.HasSwitch(switches::kDisableOneCopy)) return false; #if defined(OS_ANDROID) return false; #endif return true; } bool IsZeroCopyUploadEnabled() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); return command_line.HasSwitch(switches::kEnableZeroCopy); } int ForceNumberOfRendererRasterThreads() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); if (!command_line.HasSwitch(switches::kNumRasterThreads)) return 0; std::string string_value = command_line.GetSwitchValueASCII(switches::kNumRasterThreads); int force_num_raster_threads = 0; if (base::StringToInt(string_value, &force_num_raster_threads) && force_num_raster_threads >= kMinRasterThreads && force_num_raster_threads <= kMaxRasterThreads) { return force_num_raster_threads; } else { DLOG(WARNING) << "Failed to parse switch " << switches::kNumRasterThreads << ": " << string_value; return 0; } } bool IsGpuRasterizationEnabled() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); if (!IsImplSidePaintingEnabled()) return false; if (command_line.HasSwitch(switches::kDisableGpuRasterization)) return false; else if (command_line.HasSwitch(switches::kEnableGpuRasterization)) return true; if (IsGpuRasterizationBlacklisted()) { return false; } return true; } bool IsForceGpuRasterizationEnabled() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); if (!IsImplSidePaintingEnabled()) return false; return command_line.HasSwitch(switches::kForceGpuRasterization); } bool IsThreadedGpuRasterizationEnabled() { if (!IsImplSidePaintingEnabled()) return false; if (!IsGpuRasterizationEnabled() && !IsForceGpuRasterizationEnabled()) return false; const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kDisableThreadedGpuRasterization)) return false; return true; } bool UseSurfacesEnabled() { #if defined(OS_ANDROID) return false; #endif bool enabled = false; #if (defined(USE_AURA) && !defined(OS_CHROMEOS)) || defined(OS_MACOSX) enabled = true; #endif const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); // Flags override. enabled |= command_line.HasSwitch(switches::kUseSurfaces); enabled &= !command_line.HasSwitch(switches::kDisableSurfaces); return enabled; } int GpuRasterizationMSAASampleCount() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); if (!command_line.HasSwitch(switches::kGpuRasterizationMSAASampleCount)) return 0; std::string string_value = command_line.GetSwitchValueASCII( switches::kGpuRasterizationMSAASampleCount); int msaa_sample_count = 0; if (base::StringToInt(string_value, &msaa_sample_count) && msaa_sample_count >= kMinMSAASampleCount) { return msaa_sample_count; } else { DLOG(WARNING) << "Failed to parse switch " << switches::kGpuRasterizationMSAASampleCount << ": " << string_value; return 0; } } base::DictionaryValue* GetFeatureStatus() { GpuDataManagerImpl* manager = GpuDataManagerImpl::GetInstance(); std::string gpu_access_blocked_reason; bool gpu_access_blocked = !manager->GpuAccessAllowed(&gpu_access_blocked_reason); base::DictionaryValue* feature_status_dict = new base::DictionaryValue(); bool eof = false; for (size_t i = 0; !eof; ++i) { const GpuFeatureInfo gpu_feature_info = GetGpuFeatureInfo(i, &eof); std::string status; if (gpu_feature_info.disabled) { status = "disabled"; if (gpu_feature_info.fallback_to_software) status += "_software"; else status += "_off"; if (gpu_feature_info.name == kThreadedRasterizationFeatureName) status += "_ok"; } else if (gpu_feature_info.blocked || gpu_access_blocked) { status = "unavailable"; if (gpu_feature_info.fallback_to_software) status += "_software"; else status += "_off"; } else { status = "enabled"; if (gpu_feature_info.name == kWebGLFeatureName && manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_GPU_COMPOSITING)) status += "_readback"; if (gpu_feature_info.name == kRasterizationFeatureName) { if (IsForceGpuRasterizationEnabled()) status += "_force"; } if (gpu_feature_info.name == kMultipleRasterThreadsFeatureName) { if (ForceNumberOfRendererRasterThreads() > 0) status += "_force"; } if (gpu_feature_info.name == kThreadedRasterizationFeatureName || gpu_feature_info.name == kMultipleRasterThreadsFeatureName) status += "_on"; } if (gpu_feature_info.name == kWebGLFeatureName && (gpu_feature_info.blocked || gpu_access_blocked) && manager->ShouldUseSwiftShader()) { status = "unavailable_software"; } feature_status_dict->SetString( gpu_feature_info.name.c_str(), status.c_str()); } return feature_status_dict; } base::Value* GetProblems() { GpuDataManagerImpl* manager = GpuDataManagerImpl::GetInstance(); std::string gpu_access_blocked_reason; bool gpu_access_blocked = !manager->GpuAccessAllowed(&gpu_access_blocked_reason); base::ListValue* problem_list = new base::ListValue(); manager->GetBlacklistReasons(problem_list); if (gpu_access_blocked) { base::DictionaryValue* problem = new base::DictionaryValue(); problem->SetString("description", "GPU process was unable to boot: " + gpu_access_blocked_reason); problem->Set("crBugs", new base::ListValue()); problem->Set("webkitBugs", new base::ListValue()); base::ListValue* disabled_features = new base::ListValue(); disabled_features->AppendString("all"); problem->Set("affectedGpuSettings", disabled_features); problem->SetString("tag", "disabledFeatures"); problem_list->Insert(0, problem); } bool eof = false; for (size_t i = 0; !eof; ++i) { const GpuFeatureInfo gpu_feature_info = GetGpuFeatureInfo(i, &eof); if (gpu_feature_info.disabled) { base::DictionaryValue* problem = new base::DictionaryValue(); problem->SetString( "description", gpu_feature_info.disabled_description); problem->Set("crBugs", new base::ListValue()); problem->Set("webkitBugs", new base::ListValue()); base::ListValue* disabled_features = new base::ListValue(); disabled_features->AppendString(gpu_feature_info.name); problem->Set("affectedGpuSettings", disabled_features); problem->SetString("tag", "disabledFeatures"); problem_list->Append(problem); } } return problem_list; } std::vector<std::string> GetDriverBugWorkarounds() { return GpuDataManagerImpl::GetInstance()->GetDriverBugWorkarounds(); } } // namespace content <|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/cc_messages.h" #include "base/test/launcher/unit_test_launcher.h" #include "base/test/test_suite.h" #include "cc/output/compositor_frame.h" #include "ipc/ipc_message.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/perf/perf_test.h" using cc::CompositorFrame; using cc::DelegatedFrameData; using cc::DrawQuad; using cc::PictureDrawQuad; using cc::RenderPass; using cc::SharedQuadState; namespace content { namespace { class CCMessagesPerfTest : public testing::Test {}; const int kNumWarmupRuns = 10; const int kNumRuns = 100; TEST_F(CCMessagesPerfTest, DelegatedFrame_ManyQuads_1_4000) { scoped_ptr<CompositorFrame> frame(new CompositorFrame); scoped_ptr<RenderPass> render_pass = RenderPass::Create(); render_pass->shared_quad_state_list.push_back(SharedQuadState::Create()); for (int i = 0; i < 4000; ++i) { render_pass->quad_list.push_back( PictureDrawQuad::Create().PassAs<DrawQuad>()); } frame->delegated_frame_data.reset(new DelegatedFrameData); frame->delegated_frame_data->render_pass_list.push_back(render_pass.Pass()); for (int i = 0; i < kNumWarmupRuns; ++i) { IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::ParamTraits<CompositorFrame>::Write(&msg, *frame); } base::TimeTicks start = base::TimeTicks::HighResNow(); for (int i = 0; i < kNumRuns; ++i) { IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::ParamTraits<CompositorFrame>::Write(&msg, *frame); } base::TimeTicks end = base::TimeTicks::HighResNow(); base::TimeDelta mean_time_delta = (end - start) / kNumRuns; perf_test::PrintResult("mean_frame_serialization_time", "", "DelegatedFrame_ManyQuads_1_4000", mean_time_delta.InMicroseconds(), "us", true); } TEST_F(CCMessagesPerfTest, DelegatedFrame_ManyQuads_1_10000) { scoped_ptr<CompositorFrame> frame(new CompositorFrame); scoped_ptr<RenderPass> render_pass = RenderPass::Create(); render_pass->shared_quad_state_list.push_back(SharedQuadState::Create()); for (int i = 0; i < 4000; ++i) { render_pass->quad_list.push_back( PictureDrawQuad::Create().PassAs<DrawQuad>()); } frame->delegated_frame_data.reset(new DelegatedFrameData); frame->delegated_frame_data->render_pass_list.push_back(render_pass.Pass()); for (int i = 0; i < kNumWarmupRuns; ++i) { IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::ParamTraits<CompositorFrame>::Write(&msg, *frame); } base::TimeTicks start = base::TimeTicks::HighResNow(); for (int i = 0; i < kNumRuns; ++i) { IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::ParamTraits<CompositorFrame>::Write(&msg, *frame); } base::TimeTicks end = base::TimeTicks::HighResNow(); base::TimeDelta mean_time_delta = (end - start) / kNumRuns; perf_test::PrintResult("mean_frame_serialization_time", "", "DelegatedFrame_ManyQuads_1_10000", mean_time_delta.InMicroseconds(), "us", true); } TEST_F(CCMessagesPerfTest, DelegatedFrame_ManyQuads_4000_4000) { scoped_ptr<CompositorFrame> frame(new CompositorFrame); scoped_ptr<RenderPass> render_pass = RenderPass::Create(); for (int i = 0; i < 4000; ++i) { render_pass->shared_quad_state_list.push_back(SharedQuadState::Create()); render_pass->quad_list.push_back( PictureDrawQuad::Create().PassAs<DrawQuad>()); } frame->delegated_frame_data.reset(new DelegatedFrameData); frame->delegated_frame_data->render_pass_list.push_back(render_pass.Pass()); for (int i = 0; i < kNumWarmupRuns; ++i) { IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::ParamTraits<CompositorFrame>::Write(&msg, *frame); } base::TimeTicks start = base::TimeTicks::HighResNow(); for (int i = 0; i < kNumRuns; ++i) { IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::ParamTraits<CompositorFrame>::Write(&msg, *frame); } base::TimeTicks end = base::TimeTicks::HighResNow(); base::TimeDelta mean_time_delta = (end - start) / kNumRuns; perf_test::PrintResult("mean_frame_serialization_time", "", "DelegatedFrame_ManyQuads_4000_4000", mean_time_delta.InMicroseconds(), "us", true); } TEST_F(CCMessagesPerfTest, DelegatedFrame_ManyQuads_10000_10000) { scoped_ptr<CompositorFrame> frame(new CompositorFrame); scoped_ptr<RenderPass> render_pass = RenderPass::Create(); for (int i = 0; i < 10000; ++i) { render_pass->shared_quad_state_list.push_back(SharedQuadState::Create()); render_pass->quad_list.push_back( PictureDrawQuad::Create().PassAs<DrawQuad>()); } frame->delegated_frame_data.reset(new DelegatedFrameData); frame->delegated_frame_data->render_pass_list.push_back(render_pass.Pass()); for (int i = 0; i < kNumWarmupRuns; ++i) { IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::ParamTraits<CompositorFrame>::Write(&msg, *frame); } base::TimeTicks start = base::TimeTicks::HighResNow(); for (int i = 0; i < kNumRuns; ++i) { IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::ParamTraits<CompositorFrame>::Write(&msg, *frame); } base::TimeTicks end = base::TimeTicks::HighResNow(); base::TimeDelta mean_time_delta = (end - start) / kNumRuns; perf_test::PrintResult("mean_frame_serialization_time", "", "DelegatedFrame_ManyQuads_10000_10000", mean_time_delta.InMicroseconds(), "us", true); } } // namespace } // namespace content <commit_msg>cc: Adjust content perf tests and add test for many render passes.<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/cc_messages.h" #include "base/test/launcher/unit_test_launcher.h" #include "base/test/test_suite.h" #include "cc/output/compositor_frame.h" #include "ipc/ipc_message.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/perf/perf_test.h" using cc::CompositorFrame; using cc::DelegatedFrameData; using cc::DrawQuad; using cc::PictureDrawQuad; using cc::RenderPass; using cc::SharedQuadState; namespace content { namespace { class CCMessagesPerfTest : public testing::Test {}; const int kNumWarmupRuns = 10; const int kNumRuns = 100; TEST_F(CCMessagesPerfTest, DelegatedFrame_ManyQuads_1_4000) { scoped_ptr<CompositorFrame> frame(new CompositorFrame); scoped_ptr<RenderPass> render_pass = RenderPass::Create(); render_pass->shared_quad_state_list.push_back(SharedQuadState::Create()); for (int i = 0; i < 4000; ++i) { render_pass->quad_list.push_back( PictureDrawQuad::Create().PassAs<DrawQuad>()); } frame->delegated_frame_data.reset(new DelegatedFrameData); frame->delegated_frame_data->render_pass_list.push_back(render_pass.Pass()); for (int i = 0; i < kNumWarmupRuns; ++i) { IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::ParamTraits<CompositorFrame>::Write(&msg, *frame); } base::TimeTicks start = base::TimeTicks::HighResNow(); for (int i = 0; i < kNumRuns; ++i) { IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::ParamTraits<CompositorFrame>::Write(&msg, *frame); } base::TimeTicks end = base::TimeTicks::HighResNow(); base::TimeDelta mean_time_delta = (end - start) / kNumRuns; perf_test::PrintResult("mean_frame_serialization_time", "", "DelegatedFrame_ManyQuads_1_4000", mean_time_delta.InMicroseconds(), "us", true); } TEST_F(CCMessagesPerfTest, DelegatedFrame_ManyQuads_1_100000) { scoped_ptr<CompositorFrame> frame(new CompositorFrame); scoped_ptr<RenderPass> render_pass = RenderPass::Create(); render_pass->shared_quad_state_list.push_back(SharedQuadState::Create()); for (int i = 0; i < 100000; ++i) { render_pass->quad_list.push_back( PictureDrawQuad::Create().PassAs<DrawQuad>()); } frame->delegated_frame_data.reset(new DelegatedFrameData); frame->delegated_frame_data->render_pass_list.push_back(render_pass.Pass()); for (int i = 0; i < kNumWarmupRuns; ++i) { IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::ParamTraits<CompositorFrame>::Write(&msg, *frame); } base::TimeTicks start = base::TimeTicks::HighResNow(); for (int i = 0; i < kNumRuns; ++i) { IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::ParamTraits<CompositorFrame>::Write(&msg, *frame); } base::TimeTicks end = base::TimeTicks::HighResNow(); base::TimeDelta mean_time_delta = (end - start) / kNumRuns; perf_test::PrintResult("mean_frame_serialization_time", "", "DelegatedFrame_ManyQuads_1_100000", mean_time_delta.InMicroseconds(), "us", true); } TEST_F(CCMessagesPerfTest, DelegatedFrame_ManyQuads_4000_4000) { scoped_ptr<CompositorFrame> frame(new CompositorFrame); scoped_ptr<RenderPass> render_pass = RenderPass::Create(); for (int i = 0; i < 4000; ++i) { render_pass->shared_quad_state_list.push_back(SharedQuadState::Create()); render_pass->quad_list.push_back( PictureDrawQuad::Create().PassAs<DrawQuad>()); } frame->delegated_frame_data.reset(new DelegatedFrameData); frame->delegated_frame_data->render_pass_list.push_back(render_pass.Pass()); for (int i = 0; i < kNumWarmupRuns; ++i) { IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::ParamTraits<CompositorFrame>::Write(&msg, *frame); } base::TimeTicks start = base::TimeTicks::HighResNow(); for (int i = 0; i < kNumRuns; ++i) { IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::ParamTraits<CompositorFrame>::Write(&msg, *frame); } base::TimeTicks end = base::TimeTicks::HighResNow(); base::TimeDelta mean_time_delta = (end - start) / kNumRuns; perf_test::PrintResult("mean_frame_serialization_time", "", "DelegatedFrame_ManyQuads_4000_4000", mean_time_delta.InMicroseconds(), "us", true); } TEST_F(CCMessagesPerfTest, DelegatedFrame_ManyQuads_100000_100000) { scoped_ptr<CompositorFrame> frame(new CompositorFrame); scoped_ptr<RenderPass> render_pass = RenderPass::Create(); for (int i = 0; i < 100000; ++i) { render_pass->shared_quad_state_list.push_back(SharedQuadState::Create()); render_pass->quad_list.push_back( PictureDrawQuad::Create().PassAs<DrawQuad>()); } frame->delegated_frame_data.reset(new DelegatedFrameData); frame->delegated_frame_data->render_pass_list.push_back(render_pass.Pass()); for (int i = 0; i < kNumWarmupRuns; ++i) { IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::ParamTraits<CompositorFrame>::Write(&msg, *frame); } base::TimeTicks start = base::TimeTicks::HighResNow(); for (int i = 0; i < kNumRuns; ++i) { IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::ParamTraits<CompositorFrame>::Write(&msg, *frame); } base::TimeTicks end = base::TimeTicks::HighResNow(); base::TimeDelta mean_time_delta = (end - start) / kNumRuns; perf_test::PrintResult("mean_frame_serialization_time", "", "DelegatedFrame_ManyQuads_100000_100000", mean_time_delta.InMicroseconds(), "us", true); } TEST_F(CCMessagesPerfTest, DelegatedFrame_ManyRenderPasses_10000_100) { scoped_ptr<CompositorFrame> frame(new CompositorFrame); frame->delegated_frame_data.reset(new DelegatedFrameData); for (int i = 0; i < 1000; ++i) { scoped_ptr<RenderPass> render_pass = RenderPass::Create(); for (int j = 0; j < 100; ++j) { render_pass->shared_quad_state_list.push_back(SharedQuadState::Create()); render_pass->quad_list.push_back( PictureDrawQuad::Create().PassAs<DrawQuad>()); } frame->delegated_frame_data->render_pass_list.push_back(render_pass.Pass()); } for (int i = 0; i < kNumWarmupRuns; ++i) { IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::ParamTraits<CompositorFrame>::Write(&msg, *frame); } base::TimeTicks start = base::TimeTicks::HighResNow(); for (int i = 0; i < kNumRuns; ++i) { IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::ParamTraits<CompositorFrame>::Write(&msg, *frame); } base::TimeTicks end = base::TimeTicks::HighResNow(); base::TimeDelta mean_time_delta = (end - start) / kNumRuns; perf_test::PrintResult("mean_frame_serialization_time", "", "DelegatedFrame_ManyRenderPasses_10000_100", mean_time_delta.InMicroseconds(), "us", true); } } // namespace } // namespace content <|endoftext|>
<commit_before>#ifndef MJOLNIR_UTIL_STATIC_STRING_HPP #define MJOLNIR_UTIL_STATIC_STRING_HPP #include <mjolnir/util/throw_exception.hpp> #include <string> #include <stdexcept> #include <istream> #include <ostream> #include <cstdint> namespace mjolnir { // static_string is a statically sized std::string, inspired by static_vector // provided by Boost.Container. // this is the minimal implementation for a specific perpose, so it doesn't have // all the functionalities that exists in `std::string`. For example, it assumes // that the character encoding is ascii. Basically, it can contain UTF-8 string // as byte-array. But in that case, `size()` might not fit to the actual number // of letters. template<std::size_t N> class static_string { // because it contains '\0' delimiter at the end of buffer, the actual // free buffer size is N-1. static_string is to manage the size of object, // the clarity of the size is considered more important than the usability. static constexpr std::size_t capacity_ = N - 1; // to make code shorter. void check_size() const { if(this->size_ > this->capacity_) { throw_exception<std::length_error>("constructing static_assert<", N, "> with literal string having ", this->size_, " length."); } return ; } public: using char_type = char; using traits_type = std::char_traits<char>; using container_type = std::array<char, N>; using value_type = typename container_type::value_type; using size_type = typename container_type::size_type; using difference_type = typename container_type::difference_type; using pointer = typename container_type::pointer; using const_pointer = typename container_type::const_pointer; using reference = typename container_type::reference; using const_reference = typename container_type::const_reference; using iterator = typename container_type::iterator; using const_iterator = typename container_type::const_iterator ; using reverse_iterator = typename container_type::reverse_iterator; using const_reverse_iterator = typename container_type::const_reverse_iterator; public: static_string() : size_(0), buffer_{0} {} ~static_string() = default; static_string(static_string const&) = default; static_string(static_string &&) = default; static_string& operator=(static_string const&) = default; static_string& operator=(static_string &&) = default; explicit static_string(const char* literal): size_(traits_type::length(literal)) { this->check_size(); traits_type::copy(this->data(), literal, this->size_+1); } explicit static_string(const std::string& str): size_(str.size()) { this->check_size(); traits_type::copy(this->data(), str.c_str(), this->size_+1); } template<std::size_t M> explicit static_string(const static_string<M>& str): size_(str.size()) { if(N < M) {this->check_size();} traits_type::copy(this->data(), str.c_str(), this->size_+1); } static_string& operator=(const char* literal) { this->size_ = traits_type::length(literal); this->check_size(); traits_type::copy(this->data(), literal, this->size_+1); return *this; } static_string& operator=(const std::string& str) { this->size_ = str.size(); this->check_size(); traits_type::copy(this->data(), str.c_str(), this->size_+1); return *this; } template<std::size_t M> static_string& operator=(static_string<M> const& rhs) { this->size_ = rhs.size(); if(N < M) {this->check_size();} traits_type::copy(this->data(), rhs.c_str(), this->size_+1); return *this; } static_string& operator+=(const char c) { this->size_++; this->check_size(); buffer_[this->size_-1] = c; return *this; } static_string& operator+=(const char* rhs) { const std::size_t last = this->size_; const std::size_t len = traits_type::length(rhs); this->size_ += len; this->check_size(); traits_type::copy(std::addressof(buffer_[last]), rhs, len+1); return *this; } template<std::size_t M> static_string& operator+=(const static_string<M>& rhs) { const std::size_t last = this->size_; this->size_ += rhs.size(); this->check_size(); traits_type::copy(std::addressof(buffer_[last]), rhs.c_str(), rhs.size()+1); return *this; } static_string& operator+=(const std::string& rhs) { const std::size_t last = this->size_; this->size_ += rhs.size(); this->check_size(); traits_type::copy(std::addressof(buffer_[last]), rhs.c_str(), rhs.size()+1); return *this; } bool empty() const noexcept {return this->size_ == 0;} void clear() {this->size_ = 0;} void resize(size_type i) {this->size_ = i; this->check_size();} value_type& operator[](size_type i) noexcept {return buffer_[i];} value_type operator[](size_type i) const noexcept {return buffer_[i];} value_type& at(size_type i) {return buffer_.at(i);} value_type at(size_type i) const {return buffer_.at(i);} value_type& front() noexcept {return buffer_.front();} value_type front() const noexcept {return buffer_.front();} value_type& back() noexcept {return buffer_[this->size_-1];} value_type back() const noexcept {return buffer_[this->size_-1];} std::size_t size() const noexcept {return this->size_;} std::size_t length() const noexcept {return this->size_;} std::size_t capacity() const noexcept {return capacity_;} std::size_t max_size() const noexcept {return capacity_;} pointer data() noexcept {return buffer_.data();} const_pointer data() const noexcept {return buffer_.data();} pointer c_str() noexcept {return buffer_.data();} const_pointer c_str() const noexcept {return buffer_.data();} iterator begin() noexcept {return buffer_.begin();} iterator end() noexcept {return buffer_.begin();} const_iterator begin() const noexcept {return buffer_.begin();} const_iterator end() const noexcept {return buffer_.begin();} const_iterator cbegin() const noexcept {return buffer_.cbegin();} const_iterator cend() const noexcept {return buffer_.cbegin();} reverse_iterator rbegin() noexcept {return buffer_.rbegin();} reverse_iterator rend() noexcept {return buffer_.rbegin();} const_reverse_iterator rbegin() const noexcept {return buffer_.rbegin();} const_reverse_iterator rend() const noexcept {return buffer_.rbegin();} const_reverse_iterator crbegin() const noexcept {return buffer_.crbegin();} const_reverse_iterator crend() const noexcept {return buffer_.crbegin();} private: std::size_t size_; container_type buffer_; }; template<std::size_t N, std::size_t M> static_string<N+M> operator+(const static_string<N>& lhs, const static_string<M>& rhs) { static_string<N+M> retval(lhs); retval += rhs; return retval; } template<std::size_t N> std::string operator+(const std::string& lhs, const static_string<N>& rhs) { std::string retval(lhs); retval.append(rhs.c_str()); return retval; } template<std::size_t N> std::string operator+(const static_string<N>& lhs, const std::string& rhs) { std::string retval(lhs.c_str()); retval.append(rhs); return retval; } template<std::size_t N> std::string operator+(const char* lhs, const static_string<N>& rhs) { std::string retval(lhs); retval.append(rhs.c_str()); return retval; } template<std::size_t N> std::string operator+(const static_string<N>& lhs, const char* rhs) { std::string retval(lhs.c_str()); retval.append(rhs); return retval; } // append static_string into std::string template<std::size_t N> std::string& operator+=(std::string& lhs, const static_string<N>& rhs) { lhs.append(rhs.c_str()); return lhs; } template<std::size_t N, std::size_t M> bool operator==(const static_string<N>& lhs, const static_string<M>& rhs) { return std::char_traits<char>::compare(lhs.data(), rhs.data(), std::min(lhs.size(), rhs.size())) == 0; } template<std::size_t N, std::size_t M> bool operator!=(const static_string<N>& lhs, const static_string<M>& rhs) { return !(lhs == rhs); } template<std::size_t N, std::size_t M> bool operator< (const static_string<N>& lhs, const static_string<M>& rhs) { return std::char_traits<char>::compare(lhs.data(), rhs.data(), std::min(lhs.size(), rhs.size())) < 0; } template<std::size_t N, std::size_t M> bool operator<=(const static_string<N>& lhs, const static_string<M>& rhs) { return std::char_traits<char>::compare(lhs.data(), rhs.data(), std::min(lhs.size(), rhs.size())) <= 0; } template<std::size_t N, std::size_t M> bool operator> (const static_string<N>& lhs, const static_string<M>& rhs) { return !(lhs <= rhs); } template<std::size_t N, std::size_t M> bool operator>=(const static_string<N>& lhs, const static_string<M>& rhs) { return !(lhs < rhs); } template<std::size_t N> std::ostream& operator<<(std::ostream& os, const static_string<N>& str) { os << str.c_str(); return os; } template<std::size_t N> std::istream& operator>>(std::istream& is, static_string<N>& str) { std::string tmp; is >> tmp; str = tmp; return is; } // compare with std::string. template<std::size_t N> bool operator==(const static_string<N>& lhs, const std::string& rhs) { return std::char_traits<char>::compare(lhs.data(), rhs.data(), std::min(lhs.size(), rhs.size())) == 0; } template<std::size_t N> bool operator==(const std::string& lhs, const static_string<N>& rhs) { return std::char_traits<char>::compare(lhs.data(), rhs.data(), std::min(lhs.size(), rhs.size())) == 0; } template<std::size_t N> bool operator!=(const static_string<N>& lhs, const std::string& rhs) { return !(lhs == rhs); } template<std::size_t N> bool operator!=(const std::string& lhs, const static_string<N>& rhs) { return !(lhs == rhs); } template<std::size_t N> bool operator< (const static_string<N>& lhs, const std::string& rhs) { return std::char_traits<char>::compare(lhs.data(), rhs.data(), std::min(lhs.size(), rhs.size())) < 0; } template<std::size_t N> bool operator< (const std::string& lhs, const static_string<N>& rhs) { return std::char_traits<char>::compare(lhs.data(), rhs.data(), std::min(lhs.size(), rhs.size())) < 0; } template<std::size_t N> bool operator<=(const static_string<N>& lhs, const std::string& rhs) { return std::char_traits<char>::compare(lhs.data(), rhs.data(), std::min(lhs.size(), rhs.size())) <= 0; } template<std::size_t N> bool operator<=(const std::string& lhs, const static_string<N>& rhs) { return std::char_traits<char>::compare(lhs.data(), rhs.data(), std::min(lhs.size(), rhs.size())) <= 0; } template<std::size_t N> bool operator> (const static_string<N>& lhs, const std::string& rhs) { return !(lhs <= rhs); } template<std::size_t N> bool operator> (const std::string& lhs, const static_string<N>& rhs) { return !(lhs <= rhs); } template<std::size_t N> bool operator>=(const std::string& lhs, const static_string<N>& rhs) { return !(lhs < rhs); } template<std::size_t N> bool operator>=(const static_string<N>& lhs, const std::string& rhs) { return !(lhs < rhs); } } // mjolnir #endif // MJOLNIR_UTIL_STATIC_STRING_HPP <commit_msg>nit: remove extraneous whitespaces<commit_after>#ifndef MJOLNIR_UTIL_STATIC_STRING_HPP #define MJOLNIR_UTIL_STATIC_STRING_HPP #include <mjolnir/util/throw_exception.hpp> #include <string> #include <stdexcept> #include <istream> #include <ostream> #include <cstdint> namespace mjolnir { // static_string is a statically sized std::string, inspired by static_vector // provided by Boost.Container. // this is the minimal implementation for a specific perpose, so it doesn't have // all the functionalities that exists in `std::string`. For example, it assumes // that the character encoding is ascii. Basically, it can contain UTF-8 string // as byte-array. But in that case, `size()` might not fit to the actual number // of letters. template<std::size_t N> class static_string { // because it contains '\0' delimiter at the end of buffer, the actual // free buffer size is N-1. static_string is to manage the size of object, // the clarity of the size is considered more important than the usability. static constexpr std::size_t capacity_ = N - 1; // to make code shorter. void check_size() const { if(this->size_ > this->capacity_) { throw_exception<std::length_error>("constructing static_assert<", N, "> with literal string having ", this->size_, " length."); } return ; } public: using char_type = char; using traits_type = std::char_traits<char>; using container_type = std::array<char, N>; using value_type = typename container_type::value_type; using size_type = typename container_type::size_type; using difference_type = typename container_type::difference_type; using pointer = typename container_type::pointer; using const_pointer = typename container_type::const_pointer; using reference = typename container_type::reference; using const_reference = typename container_type::const_reference; using iterator = typename container_type::iterator; using const_iterator = typename container_type::const_iterator ; using reverse_iterator = typename container_type::reverse_iterator; using const_reverse_iterator = typename container_type::const_reverse_iterator; public: static_string() : size_(0), buffer_{0} {} ~static_string() = default; static_string(static_string const&) = default; static_string(static_string &&) = default; static_string& operator=(static_string const&) = default; static_string& operator=(static_string &&) = default; explicit static_string(const char* literal): size_(traits_type::length(literal)) { this->check_size(); traits_type::copy(this->data(), literal, this->size_+1); } explicit static_string(const std::string& str): size_(str.size()) { this->check_size(); traits_type::copy(this->data(), str.c_str(), this->size_+1); } template<std::size_t M> explicit static_string(const static_string<M>& str): size_(str.size()) { if(N < M) {this->check_size();} traits_type::copy(this->data(), str.c_str(), this->size_+1); } static_string& operator=(const char* literal) { this->size_ = traits_type::length(literal); this->check_size(); traits_type::copy(this->data(), literal, this->size_+1); return *this; } static_string& operator=(const std::string& str) { this->size_ = str.size(); this->check_size(); traits_type::copy(this->data(), str.c_str(), this->size_+1); return *this; } template<std::size_t M> static_string& operator=(static_string<M> const& rhs) { this->size_ = rhs.size(); if(N < M) {this->check_size();} traits_type::copy(this->data(), rhs.c_str(), this->size_+1); return *this; } static_string& operator+=(const char c) { this->size_++; this->check_size(); buffer_[this->size_-1] = c; return *this; } static_string& operator+=(const char* rhs) { const std::size_t last = this->size_; const std::size_t len = traits_type::length(rhs); this->size_ += len; this->check_size(); traits_type::copy(std::addressof(buffer_[last]), rhs, len+1); return *this; } template<std::size_t M> static_string& operator+=(const static_string<M>& rhs) { const std::size_t last = this->size_; this->size_ += rhs.size(); this->check_size(); traits_type::copy(std::addressof(buffer_[last]), rhs.c_str(), rhs.size()+1); return *this; } static_string& operator+=(const std::string& rhs) { const std::size_t last = this->size_; this->size_ += rhs.size(); this->check_size(); traits_type::copy(std::addressof(buffer_[last]), rhs.c_str(), rhs.size()+1); return *this; } bool empty() const noexcept {return this->size_ == 0;} void clear() {this->size_ = 0;} void resize(size_type i) {this->size_ = i; this->check_size();} value_type& operator[](size_type i) noexcept {return buffer_[i];} value_type operator[](size_type i) const noexcept {return buffer_[i];} value_type& at(size_type i) {return buffer_.at(i);} value_type at(size_type i) const {return buffer_.at(i);} value_type& front() noexcept {return buffer_.front();} value_type front() const noexcept {return buffer_.front();} value_type& back() noexcept {return buffer_[this->size_-1];} value_type back() const noexcept {return buffer_[this->size_-1];} std::size_t size() const noexcept {return this->size_;} std::size_t length() const noexcept {return this->size_;} std::size_t capacity() const noexcept {return capacity_;} std::size_t max_size() const noexcept {return capacity_;} pointer data() noexcept {return buffer_.data();} const_pointer data() const noexcept {return buffer_.data();} pointer c_str() noexcept {return buffer_.data();} const_pointer c_str() const noexcept {return buffer_.data();} iterator begin() noexcept {return buffer_.begin();} iterator end() noexcept {return buffer_.begin();} const_iterator begin() const noexcept {return buffer_.begin();} const_iterator end() const noexcept {return buffer_.begin();} const_iterator cbegin() const noexcept {return buffer_.cbegin();} const_iterator cend() const noexcept {return buffer_.cbegin();} reverse_iterator rbegin() noexcept {return buffer_.rbegin();} reverse_iterator rend() noexcept {return buffer_.rbegin();} const_reverse_iterator rbegin() const noexcept {return buffer_.rbegin();} const_reverse_iterator rend() const noexcept {return buffer_.rbegin();} const_reverse_iterator crbegin() const noexcept {return buffer_.crbegin();} const_reverse_iterator crend() const noexcept {return buffer_.crbegin();} private: std::size_t size_; container_type buffer_; }; template<std::size_t N, std::size_t M> static_string<N+M> operator+(const static_string<N>& lhs, const static_string<M>& rhs) { static_string<N+M> retval(lhs); retval += rhs; return retval; } template<std::size_t N> std::string operator+(const std::string& lhs, const static_string<N>& rhs) { std::string retval(lhs); retval.append(rhs.c_str()); return retval; } template<std::size_t N> std::string operator+(const static_string<N>& lhs, const std::string& rhs) { std::string retval(lhs.c_str()); retval.append(rhs); return retval; } template<std::size_t N> std::string operator+(const char* lhs, const static_string<N>& rhs) { std::string retval(lhs); retval.append(rhs.c_str()); return retval; } template<std::size_t N> std::string operator+(const static_string<N>& lhs, const char* rhs) { std::string retval(lhs.c_str()); retval.append(rhs); return retval; } // append static_string into std::string template<std::size_t N> std::string& operator+=(std::string& lhs, const static_string<N>& rhs) { lhs.append(rhs.c_str()); return lhs; } template<std::size_t N, std::size_t M> bool operator==(const static_string<N>& lhs, const static_string<M>& rhs) { return std::char_traits<char>::compare(lhs.data(), rhs.data(), std::min(lhs.size(), rhs.size())) == 0; } template<std::size_t N, std::size_t M> bool operator!=(const static_string<N>& lhs, const static_string<M>& rhs) { return !(lhs == rhs); } template<std::size_t N, std::size_t M> bool operator< (const static_string<N>& lhs, const static_string<M>& rhs) { return std::char_traits<char>::compare(lhs.data(), rhs.data(), std::min(lhs.size(), rhs.size())) < 0; } template<std::size_t N, std::size_t M> bool operator<=(const static_string<N>& lhs, const static_string<M>& rhs) { return std::char_traits<char>::compare(lhs.data(), rhs.data(), std::min(lhs.size(), rhs.size())) <= 0; } template<std::size_t N, std::size_t M> bool operator> (const static_string<N>& lhs, const static_string<M>& rhs) { return !(lhs <= rhs); } template<std::size_t N, std::size_t M> bool operator>=(const static_string<N>& lhs, const static_string<M>& rhs) { return !(lhs < rhs); } template<std::size_t N> std::ostream& operator<<(std::ostream& os, const static_string<N>& str) { os << str.c_str(); return os; } template<std::size_t N> std::istream& operator>>(std::istream& is, static_string<N>& str) { std::string tmp; is >> tmp; str = tmp; return is; } // compare with std::string. template<std::size_t N> bool operator==(const static_string<N>& lhs, const std::string& rhs) { return std::char_traits<char>::compare(lhs.data(), rhs.data(), std::min(lhs.size(), rhs.size())) == 0; } template<std::size_t N> bool operator==(const std::string& lhs, const static_string<N>& rhs) { return std::char_traits<char>::compare(lhs.data(), rhs.data(), std::min(lhs.size(), rhs.size())) == 0; } template<std::size_t N> bool operator!=(const static_string<N>& lhs, const std::string& rhs) { return !(lhs == rhs); } template<std::size_t N> bool operator!=(const std::string& lhs, const static_string<N>& rhs) { return !(lhs == rhs); } template<std::size_t N> bool operator< (const static_string<N>& lhs, const std::string& rhs) { return std::char_traits<char>::compare(lhs.data(), rhs.data(), std::min(lhs.size(), rhs.size())) < 0; } template<std::size_t N> bool operator< (const std::string& lhs, const static_string<N>& rhs) { return std::char_traits<char>::compare(lhs.data(), rhs.data(), std::min(lhs.size(), rhs.size())) < 0; } template<std::size_t N> bool operator<=(const static_string<N>& lhs, const std::string& rhs) { return std::char_traits<char>::compare(lhs.data(), rhs.data(), std::min(lhs.size(), rhs.size())) <= 0; } template<std::size_t N> bool operator<=(const std::string& lhs, const static_string<N>& rhs) { return std::char_traits<char>::compare(lhs.data(), rhs.data(), std::min(lhs.size(), rhs.size())) <= 0; } template<std::size_t N> bool operator> (const static_string<N>& lhs, const std::string& rhs) { return !(lhs <= rhs); } template<std::size_t N> bool operator> (const std::string& lhs, const static_string<N>& rhs) { return !(lhs <= rhs); } template<std::size_t N> bool operator>=(const std::string& lhs, const static_string<N>& rhs) { return !(lhs < rhs); } template<std::size_t N> bool operator>=(const static_string<N>& lhs, const std::string& rhs) { return !(lhs < rhs); } } // mjolnir #endif // MJOLNIR_UTIL_STATIC_STRING_HPP <|endoftext|>
<commit_before>#include "SudokuGenerator.h" #include <vector> #include <string> #include <iostream> #include <fstream> #include <exception> #include <stdexcept> //#include <sstream> #include <stack> #include <stdlib.h> //#include <boost/numeric/ublas/matrix.hpp> //#include <boost/numeric/ublas/io.hpp> #include "Random/random.cpp" namespace Sudoku { void SudokuGenerator::generatePuzzles( std::string filename, long int max ) {//Create up to max number of puzzles and saves them to file filename. SudokuPuzzle puzzle; int numPuzzles = 0; std::cout << "Creating " << max << " puzzles." << std::endl << std::endl; while( numPuzzles < max ) { if( puzzleGenerator( puzzle, 1, 1, filename, max) ) {//If generated a puzzle. numPuzzles++; std::cout << "Created puzzle number " << numPuzzles << "." << std::endl; } } //puzzleGeneratorNR( filename, max ); } bool SudokuGenerator::puzzleGenerator( SudokuPuzzle puzzle, int x, int y, std::string &filename, long int max ) {//Recursively generates Sudoku puzzles. x and y are the coordinates for this call to modify. x and y should both be between 1 and 9 inclusive. filename is the file to hold the puzzles. max is the maximum number of valid values for an element to go through before stopping. /* std::string errorText; std::vector<int> possibleValues; if( (x < 1) || (x > 9) ) {//x is out of bounds, throw error. errorText = "In SudokuGenerator::puzzleGenerator( SudokuPuzzle &puzzle, int x, int y), x is out of bounds. x is "; errorText += x; errorText += " but should be between 1 and 9.\n"; std::cerr << errorText; throw std::out_of_range( errorText.c_str() ); } if( (y < 1) || (y > 9) ) {//y is out of bounds, throw error. errorText = "In SudokuGenerator::puzzleGenerator( SudokuPuzzle &puzzle, int x, int y), y is out of bounds. y is "; errorText += y; errorText += " but should be between 1 and 9.\n"; std::cerr << errorText; throw std::out_of_range( errorText.c_str() ); } possibleValues = puzzle.getPossibleValues( x, y ); if( possibleValues.size() == 0 ) { std::cout << "Currently no possible values at element (" << x << ", " << y << ")." << std::endl << puzzle; } for( unsigned int i = 0; i < possibleValues.size(); i++ ) {//Go through each of the possible values and place them in the puzzle. Then go on to the next element, if there is one, using a recursive call. //std::cout << "Setting value " << possibleValues.at(i) << " at element (" << x << ", " << y << ")." << std::endl; puzzle.setElementValue( x, y, possibleValues.at(i) ); if( (x == 9) && (y == 9) ) {//This is the last element, save the puzzle. puzzle.saveToFile( filename ); } else {//Not the last element, go to the next element. if( x == 9 ) {//Go to the next row since this is the last element of this row. puzzleGenerator( puzzle, 1, y+1, filename); } else {//Go to the element in this row. puzzleGenerator( puzzle, x+1, y, filename); } } puzzle.removeElementValue( x, y ); } */ std::string errorText; std::vector<int> possibleValues; int numValsTried = 0;//Number of valid values tried for this element. int numAttempts = 0;//Number of values attempted for this element. bool worked = false;//Whether a valid Sudoku puzzle has been found. std::vector<int> possibleValues; //std::cout << "(" << x << "," << y << ")" << std::endl; if( (x < 1) || (x > 9) ) {//x is out of bounds, throw error. errorText = "In SudokuGenerator::puzzleGenerator( SudokuPuzzle puzzle, int x, int y, std::string &filename, int max ), x is out of bounds. x is "; errorText += x; errorText += " but should be between 1 and 9.\n"; std::cerr << errorText; throw std::out_of_range( errorText.c_str() ); } if( (y < 1) || (y > 9) ) {//y is out of bounds, throw error. errorText = "In SudokuGenerator::puzzleGenerator( SudokuPuzzle puzzle, int x, int y, std::string &filename, int max ), y is out of bounds. y is "; errorText += y; errorText += " but should be between 1 and 9.\n"; std::cerr << errorText; throw std::out_of_range( errorText.c_str() ); } /* if( (max < 1) || (max > 9) ) {//max is out of bounds, throw error. errorText = "In SudokuGenerator::puzzleGenerator( SudokuPuzzle puzzle, int x, int y, std::string &filename, int max ), max is out of bounds. max is "; errorText += max; errorText += " but should be between 1 and 9.\n"; std::cerr << errorText; throw std::out_of_range( errorText.c_str() ); } */ possibleValues = puzzle.getPossibleValues( x, y ); //for( unsigned int i = 1; i <= 9; i++ ) //for( unsigned int i = 1; (i <= 9) && (numValsTried < max); i++ ) //while( (numValsTried < max) && (numAttempts < 3*puzzle.at(x,y).getNumPossibilities()) ) //while( (numValsTried < max) && (numAttempts < 3*9) ) //while( (numValsTried < 9) && (numAttempts < 3*9) && (worked == false) ) while( (possibleValues.size() > 0) && (worked == false) ) {//Go through each of the possible values and place them in the puzzle. Then go on to the next element, if there is one, using a recursive call. //int i = RNG::generateNumber<int>( 1, 9 );//Pick a random int between 1 and 9 inclusive. int j = RNG::generateNumber<int>( 0, possibleValues.size()-1); int i = possibleValues.at(j); possibleValues.erase( possibleValues.begin()+j-1 ); numAttempts++; //std::cout << "Generated random value " << i << " for element (" << x << ", " << y << ")." << std::endl; //std::cout << "Setting value " << i << " at element (" << x << ", " << y << ")." << std::endl; if( puzzle.isPossibleValue(x,y,i) ) { //std::cout << "Value works!" << std::endl << std::endl; numValsTried++; puzzle.setElementValue( x, y, i ); if( (x == 9) && (y == 9) ) {//This is the last element, save the puzzle. //std::cout << puzzle << std::endl; if( puzzle.isValid() ) {//It's a valid puzzle, save it. //std::cout << "Found valid puzzle!" << std::endl; puzzle.saveToFile( filename ); return true; } else { return false; } } else {//Not the last element, go to the next element. if( x == 9 ) {//Go to the next row since this is the last element of this row. //puzzleGenerator( puzzle, 1, y+1, filename, max); worked = puzzleGenerator( puzzle, 1, y+1, filename, max); } else {//Go to the element in this row. worked = puzzleGenerator( puzzle, x+1, y, filename, max); } } puzzle.removeElementValue( x, y ); } else { //std::cout << "Value doesn't work. :(" << std::endl << std::endl; } } return worked;//Return whether it worked or not. } void SudokuGenerator::puzzleGeneratorNR( std::string filename, int limit ) {//Non-recursively generates Sudoku puzzles. filename is the file to hold the puzzles. limit is the max amout of puzzles to create. /* std::stack< std::vector<int> > previousValues;//A stack to hold the last previously used values on each of the previous elements. std::vector<int> pValues; SudokuPuzzle puzzle;//The sudoku puzzle. int x = 1; int y = 1; int currentValue = 1; int numPuzzles = 0; while( !((x == 9) && (y == 9)) && (numPuzzles < limit) ) { if( pValues.size() > usedValues(x-1, y-1).size() ) {//If haven't used all the possible values, use the next one and move on. if( (x == 9) && (y == 9) ) {//This is the last element, save the puzzle. savePuzzleToFile( puzzle, filename ); } else {//Not the last element, go to the next element. if( x == 9 ) {//Go to the next row since this is the last element of this row. x = 1; y++; } else {//Go to the next element in this row. x++; } } } else {//Used up all the possible values for this element. Go back to the last element and start using the remaining possible values. if( (x == 1) && (y == 1) ) {//This is the first element, should mean all possible Sudoku puzzles have been explored. Exit the method. numPuzzles = limit;//Will cause an exit of the while loop. } else {//Not the first element, go to the previous element. if( x == 1 ) {//Go to the last row since this is the first element of this row. x = 9; y--; } else {//Go to the previous element in this row. x--; } } } } */ } } int main( int argc, char* argv[]) { if( (argc < 2) || (argc > 3) ) {//Didn't include the right arguments, error out. std::cerr << "Usage: " << argv[0] << " filename [maxPuzzles]\n"; std::cerr << "Where maxPuzzles is the maximum number of puzzles you want the program to generate.\n"; return 1; } else {//Start the sudokuGenerator. Sudoku::SudokuGenerator gen; long int max = 2; if( argc == 3 ) { max = atol(argv[2]); } gen.generatePuzzles( argv[1], max ); return 0; } } <commit_msg>Seemingly working randomized version that seems to be reasonably fast.<commit_after>#include "SudokuGenerator.h" #include <vector> #include <string> #include <iostream> #include <fstream> #include <exception> #include <stdexcept> //#include <sstream> #include <stack> #include <stdlib.h> //#include <boost/numeric/ublas/matrix.hpp> //#include <boost/numeric/ublas/io.hpp> #include "Random/random.cpp" namespace Sudoku { void SudokuGenerator::generatePuzzles( std::string filename, long int max ) {//Create up to max number of puzzles and saves them to file filename. SudokuPuzzle puzzle; int numPuzzles = 0; std::cout << "Creating " << max << " puzzles." << std::endl << std::endl; while( numPuzzles < max ) { if( puzzleGenerator( puzzle, 1, 1, filename, max) ) {//If generated a puzzle. numPuzzles++; std::cout << "Created puzzle number " << numPuzzles << "." << std::endl; } } //puzzleGeneratorNR( filename, max ); } bool SudokuGenerator::puzzleGenerator( SudokuPuzzle puzzle, int x, int y, std::string &filename, long int max ) {//Recursively generates Sudoku puzzles. x and y are the coordinates for this call to modify. x and y should both be between 1 and 9 inclusive. filename is the file to hold the puzzles. max is the maximum number of valid values for an element to go through before stopping. /* std::string errorText; std::vector<int> possibleValues; if( (x < 1) || (x > 9) ) {//x is out of bounds, throw error. errorText = "In SudokuGenerator::puzzleGenerator( SudokuPuzzle &puzzle, int x, int y), x is out of bounds. x is "; errorText += x; errorText += " but should be between 1 and 9.\n"; std::cerr << errorText; throw std::out_of_range( errorText.c_str() ); } if( (y < 1) || (y > 9) ) {//y is out of bounds, throw error. errorText = "In SudokuGenerator::puzzleGenerator( SudokuPuzzle &puzzle, int x, int y), y is out of bounds. y is "; errorText += y; errorText += " but should be between 1 and 9.\n"; std::cerr << errorText; throw std::out_of_range( errorText.c_str() ); } possibleValues = puzzle.getPossibleValues( x, y ); if( possibleValues.size() == 0 ) { std::cout << "Currently no possible values at element (" << x << ", " << y << ")." << std::endl << puzzle; } for( unsigned int i = 0; i < possibleValues.size(); i++ ) {//Go through each of the possible values and place them in the puzzle. Then go on to the next element, if there is one, using a recursive call. //std::cout << "Setting value " << possibleValues.at(i) << " at element (" << x << ", " << y << ")." << std::endl; puzzle.setElementValue( x, y, possibleValues.at(i) ); if( (x == 9) && (y == 9) ) {//This is the last element, save the puzzle. puzzle.saveToFile( filename ); } else {//Not the last element, go to the next element. if( x == 9 ) {//Go to the next row since this is the last element of this row. puzzleGenerator( puzzle, 1, y+1, filename); } else {//Go to the element in this row. puzzleGenerator( puzzle, x+1, y, filename); } } puzzle.removeElementValue( x, y ); } */ std::string errorText; std::vector<int> possibleValues; int numValsTried = 0;//Number of valid values tried for this element. int numAttempts = 0;//Number of values attempted for this element. bool worked = false;//Whether a valid Sudoku puzzle has been found. //std::vector<int> possibleValues; //std::cout << "(" << x << "," << y << ")" << std::endl; if( (x < 1) || (x > 9) ) {//x is out of bounds, throw error. errorText = "In SudokuGenerator::puzzleGenerator( SudokuPuzzle puzzle, int x, int y, std::string &filename, int max ), x is out of bounds. x is "; errorText += x; errorText += " but should be between 1 and 9.\n"; std::cerr << errorText; throw std::out_of_range( errorText.c_str() ); } if( (y < 1) || (y > 9) ) {//y is out of bounds, throw error. errorText = "In SudokuGenerator::puzzleGenerator( SudokuPuzzle puzzle, int x, int y, std::string &filename, int max ), y is out of bounds. y is "; errorText += y; errorText += " but should be between 1 and 9.\n"; std::cerr << errorText; throw std::out_of_range( errorText.c_str() ); } /* if( (max < 1) || (max > 9) ) {//max is out of bounds, throw error. errorText = "In SudokuGenerator::puzzleGenerator( SudokuPuzzle puzzle, int x, int y, std::string &filename, int max ), max is out of bounds. max is "; errorText += max; errorText += " but should be between 1 and 9.\n"; std::cerr << errorText; throw std::out_of_range( errorText.c_str() ); } */ //possibleValues = puzzle.getPossibleValues( x, y ); /* for( int i = 1; i <= 9; i++ ) { if( puzzle.isPossibleValue(x, y, i) ) { possibleValues.push_back(i); } } */ //for( unsigned int i = 1; i <= 9; i++ ) //for( unsigned int i = 1; (i <= 9) && (numValsTried < max); i++ ) //while( (numValsTried < max) && (numAttempts < 3*puzzle.at(x,y).getNumPossibilities()) ) //while( (numValsTried < max) && (numAttempts < 3*9) ) //while( (numValsTried < 9) && (numAttempts < 3*9) && (worked == false) ) //std::cout << "test 1: possibleValues.size() = " << possibleValues.size() << std::endl; //while( (possibleValues.size() > 0) && (worked == false) ) while( (worked == false) && (puzzle.getNumValues(x,y) > 0) && (numAttempts <= puzzle.getNumValues(x,y)) ) {//Randomly go through a possible value and place them in the puzzle. Then go on to the next element, if there is one, using a recursive call. //int i, j; int i; //int i = RNG::generateNumber<int>( 1, 9 );//Pick a random int between 1 and 9 inclusive. do { /* //std::cout << "test 2" << std::endl; j = RNG::generateNumber<int>( 0, possibleValues.size()-1); //std::cout << "test 3" << std::endl; i = possibleValues.at(j); //std::cout << "test 4" << std::endl; possibleValues.erase( possibleValues.begin()+j-1 ); //std::cout << "test 5" << std::endl; */ i = RNG::generateNumber<int>( 1, 9); } while( !(puzzle.isPossibleValue(x,y,i)) ); numAttempts++; //std::cout << "Generated random value " << i << " for element (" << x << ", " << y << ")." << std::endl; //std::cout << "Setting value " << i << " at element (" << x << ", " << y << ")." << std::endl; //if( puzzle.isPossibleValue(x,y,i) ) //{ //std::cout << "test 6" << std::endl; //std::cout << "Value works!" << std::endl << std::endl; numValsTried++; puzzle.setElementValue( x, y, i ); //std::cout << "test 7" << std::endl; if( (x == 9) && (y == 9) ) {//This is the last element, save the puzzle. //std::cout << puzzle << std::endl; //std::cout << "test 8a" << std::endl; if( puzzle.isValid() ) {//It's a valid puzzle, save it. //std::cout << "Found valid puzzle!" << std::endl; puzzle.saveToFile( filename ); //std::cout << "test 9a" << std::endl; return true; } else { //std::cout << "test 9b" << std::endl; return false; } } else {//Not the last element, go to the next element. //std::cout << "test 8b" << std::endl; if( x == 9 ) {//Go to the next row since this is the last element of this row. //puzzleGenerator( puzzle, 1, y+1, filename, max); //std::cout << "test 9c" << std::endl; worked = puzzleGenerator( puzzle, 1, y+1, filename, max); } else {//Go to the element in this row. //std::cout << "test 9d" << std::endl; worked = puzzleGenerator( puzzle, x+1, y, filename, max); } } //std::cout << "test 10" << std::endl; puzzle.removeElementValue( x, y ); /* } else { //std::cout << "Value doesn't work. :(" << std::endl << std::endl; } */ } //std::cout << "test 11" << std::endl; return worked;//Return whether it worked or not. } void SudokuGenerator::puzzleGeneratorNR( std::string filename, int limit ) {//Non-recursively generates Sudoku puzzles. filename is the file to hold the puzzles. limit is the max amout of puzzles to create. /* std::stack< std::vector<int> > previousValues;//A stack to hold the last previously used values on each of the previous elements. std::vector<int> pValues; SudokuPuzzle puzzle;//The sudoku puzzle. int x = 1; int y = 1; int currentValue = 1; int numPuzzles = 0; while( !((x == 9) && (y == 9)) && (numPuzzles < limit) ) { if( pValues.size() > usedValues(x-1, y-1).size() ) {//If haven't used all the possible values, use the next one and move on. if( (x == 9) && (y == 9) ) {//This is the last element, save the puzzle. savePuzzleToFile( puzzle, filename ); } else {//Not the last element, go to the next element. if( x == 9 ) {//Go to the next row since this is the last element of this row. x = 1; y++; } else {//Go to the next element in this row. x++; } } } else {//Used up all the possible values for this element. Go back to the last element and start using the remaining possible values. if( (x == 1) && (y == 1) ) {//This is the first element, should mean all possible Sudoku puzzles have been explored. Exit the method. numPuzzles = limit;//Will cause an exit of the while loop. } else {//Not the first element, go to the previous element. if( x == 1 ) {//Go to the last row since this is the first element of this row. x = 9; y--; } else {//Go to the previous element in this row. x--; } } } } */ } } int main( int argc, char* argv[]) { if( (argc < 2) || (argc > 3) ) {//Didn't include the right arguments, error out. std::cerr << "Usage: " << argv[0] << " filename [maxPuzzles]\n"; std::cerr << "Where maxPuzzles is the maximum number of puzzles you want the program to generate.\n"; return 1; } else {//Start the sudokuGenerator. Sudoku::SudokuGenerator gen; long int max = 2; if( argc == 3 ) { max = atol(argv[2]); } gen.generatePuzzles( argv[1], max ); return 0; } } <|endoftext|>
<commit_before>void ViewTOF() { //=====> Level 1 // Level 1 for TOF volumes gMC->Gsatt("B077","seen",0); //==========> Level 2 // Level 2 gMC->Gsatt("B076","seen",-1); // all B076 sub-levels skipped - gMC->Gsatt("B071","seen",0); gMC->Gsatt("B074","seen",0); gMC->Gsatt("B075","seen",0); gMC->Gsatt("B080","seen",0); // B080 does not has sub-level // Level 2 of B071 gMC->Gsatt("B063","seen",-1); // all B063 sub-levels skipped - gMC->Gsatt("B065","seen",-1); // all B065 sub-levels skipped - gMC->Gsatt("B067","seen",-1); // all B067 sub-levels skipped - gMC->Gsatt("B069","seen",-1); // all B069 sub-levels skipped - gMC->Gsatt("B056","seen",0); // B056 does not has sub-levels - gMC->Gsatt("B059","seen",-1); // all B059 sub-levels skipped - gMC->Gsatt("B072","seen",-1); // all B072 sub-levels skipped - gMC->Gsatt("BTR1","seen",0); // BTR1 do not have sub-levels - gMC->Gsatt("BTO1","seen",0); // Level 2 of B074 gMC->Gsatt("BTR2","seen",0); // BTR2 does not has sub-levels - gMC->Gsatt("BTO2","seen",0); // Level 2 of B075 gMC->Gsatt("BTR3","seen",0); // BTR3 do not have sub-levels - gMC->Gsatt("BTO3","seen",0); // ==================> Level 3 // Level 3 of B071 / Level 2 of BTO1 gMC->Gsatt("FTOC","seen",-2); gMC->Gsatt("FTOB","seen",-2); gMC->Gsatt("FTOA","seen",-2); // Level 3 of B074 / Level 2 of BTO2 // -> cfr previous settings // Level 3 of B075 / Level 2 of BTO3 // -> cfr previous settings } <commit_msg>Updated ViewTOFplates macro<commit_after>void ViewTOFplates() { //=====> Level 1 // Level 1 for TOF volumes gMC->Gsatt("B077","seen",0); //==========> Level 2 // Level 2 gMC->Gsatt("B076","seen",-1); // all B076 sub-levels skipped - gMC->Gsatt("B071","seen",0); gMC->Gsatt("B074","seen",0); gMC->Gsatt("B075","seen",0); gMC->Gsatt("B080","seen",0); // B080 does not has sub-level // Level 2 of B071 gMC->Gsatt("B063","seen",-1); // all B063 sub-levels skipped - gMC->Gsatt("B065","seen",-1); // all B065 sub-levels skipped - gMC->Gsatt("B067","seen",-1); // all B067 sub-levels skipped - gMC->Gsatt("B069","seen",-1); // all B069 sub-levels skipped - gMC->Gsatt("B056","seen",0); // B056 does not has sub-levels - gMC->Gsatt("B059","seen",-1); // all B059 sub-levels skipped - gMC->Gsatt("B072","seen",-1); // all B072 sub-levels skipped - gMC->Gsatt("BTR1","seen",0); // BTR1 do not have sub-levels - gMC->Gsatt("BTO1","seen",0); // Level 2 of B074 gMC->Gsatt("BTR2","seen",0); // BTR2 does not has sub-levels - gMC->Gsatt("BTO2","seen",0); // Level 2 of B075 gMC->Gsatt("BTR3","seen",0); // BTR3 do not have sub-levels - gMC->Gsatt("BTO3","seen",0); // ==================> Level 3 // Level 3 of B071 / Level 2 of BTO1 gMC->Gsatt("FTOC","seen",-2); gMC->Gsatt("FTOB","seen",-2); gMC->Gsatt("FTOA","seen",-2); // Level 3 of B074 / Level 2 of BTO2 // -> cfr previous settings // Level 3 of B075 / Level 2 of BTO3 // -> cfr previous settings } <|endoftext|>
<commit_before>#include <jni.h> #include <string> extern "C" jint Java_com_dev_bins_jniwithcmake_MainActivity_add(JNIEnv *env, jobject instance, jint x, jint y) { return x+y; } extern "C" jstring Java_com_dev_bins_jniwithcmake_MainActivity_stringFromJNI( JNIEnv *env, jobject /* this */) { std::string hello = "JniWithCMake"; return env->NewStringUTF(hello.c_str()); } <commit_msg>在cpp文件里需要把生成的方法包含在extern "C" {}里面<commit_after>#include <jni.h> #include <string> extern "C" { JNIEXPORT jint JNICALL Java_com_dev_bins_jniwithcmake_MainActivity_add(JNIEnv *env, jobject instance, jint x, jint y) { return x + y; } jstring Java_com_dev_bins_jniwithcmake_MainActivity_stringFromJNI( JNIEnv *env, jobject /* this */) { std::string hello = "JniWithCMake"; return env->NewStringUTF(hello.c_str()); } } <|endoftext|>
<commit_before>#include "stdafx.h" #include "CSVWriter.h" #include <filesystem> #include <fstream> #include "mmcore/param/FilePathParam.h" #include "mmstd_datatools/table/TableDataCall.h" megamol::stdplugin::datatools::CSVWriter::CSVWriter() : _data_in_slot("inData", ""), _filename_slot("filename", "") { _data_in_slot.SetCompatibleCall<table::TableDataCallDescription>(); MakeSlotAvailable(&_data_in_slot); _filename_slot << new core::param::FilePathParam("out.csv"); MakeSlotAvailable(&_filename_slot); } megamol::stdplugin::datatools::CSVWriter::~CSVWriter() { this->Release(); } bool megamol::stdplugin::datatools::CSVWriter::create() { return true; } void megamol::stdplugin::datatools::CSVWriter::release() {} bool megamol::stdplugin::datatools::CSVWriter::run() { auto filename = std::filesystem::path(std::string(_filename_slot.Param<core::param::FilePathParam>()->Value())); if (filename.empty()) { megamol::core::utility::log::Log::DefaultLog.WriteError("[CSVWriter]: No file name specified. Abort."); return false; } auto inCall = _data_in_slot.CallAs<table::TableDataCall>(); if (inCall == NULL) { megamol::core::utility::log::Log::DefaultLog.WriteError("[CSVWriter]: No data source connected. Abort."); return false; } if (std::filesystem::exists(filename)) { megamol::core::utility::log::Log::DefaultLog.WriteWarn( "[CSVWriter]: File %s already exists and will be overwritten.", filename.c_str()); } if (!(*inCall)(1) || !(*inCall)(0)) { megamol::core::utility::log::Log::DefaultLog.WriteError("[CSVWriter]: Could not load input data. Abort."); return false; } auto col_count = inCall->GetColumnsCount(); auto row_count = inCall->GetRowsCount(); auto infos = inCall->GetColumnsInfos(); auto data = inCall->GetData(); std::ofstream file = std::ofstream(filename); for (size_t col = 0; col < col_count; ++col) { if (col < col_count - 1) { file << infos[col].Name() << ","; } else { file << infos[col].Name() << "\n"; } } for (size_t row = 0; row < row_count; ++row) { for (size_t col = 0; col < col_count; ++col) { if (col < col_count - 1) { file << std::to_string(inCall->GetData(col, row)) << ","; } else { file << std::to_string(inCall->GetData(col, row)) << "\n"; } } } file.close(); return true; } bool megamol::stdplugin::datatools::CSVWriter::getCapabilities(core::DataWriterCtrlCall& call) { call.SetAbortable(false); return true; } <commit_msg>set locale<commit_after>#include "stdafx.h" #include "CSVWriter.h" #include <filesystem> #include <fstream> #include <locale> #include "mmcore/param/FilePathParam.h" #include "mmstd_datatools/table/TableDataCall.h" megamol::stdplugin::datatools::CSVWriter::CSVWriter() : _data_in_slot("inData", ""), _filename_slot("filename", "") { _data_in_slot.SetCompatibleCall<table::TableDataCallDescription>(); MakeSlotAvailable(&_data_in_slot); _filename_slot << new core::param::FilePathParam("out.csv"); MakeSlotAvailable(&_filename_slot); } megamol::stdplugin::datatools::CSVWriter::~CSVWriter() { this->Release(); } bool megamol::stdplugin::datatools::CSVWriter::create() { return true; } void megamol::stdplugin::datatools::CSVWriter::release() {} bool megamol::stdplugin::datatools::CSVWriter::run() { auto filename = std::filesystem::path(std::string(_filename_slot.Param<core::param::FilePathParam>()->Value())); if (filename.empty()) { megamol::core::utility::log::Log::DefaultLog.WriteError("[CSVWriter]: No file name specified. Abort."); return false; } auto inCall = _data_in_slot.CallAs<table::TableDataCall>(); if (inCall == NULL) { megamol::core::utility::log::Log::DefaultLog.WriteError("[CSVWriter]: No data source connected. Abort."); return false; } if (std::filesystem::exists(filename)) { megamol::core::utility::log::Log::DefaultLog.WriteWarn( "[CSVWriter]: File %s already exists and will be overwritten.", filename.c_str()); } if (!(*inCall)(1) || !(*inCall)(0)) { megamol::core::utility::log::Log::DefaultLog.WriteError("[CSVWriter]: Could not load input data. Abort."); return false; } auto col_count = inCall->GetColumnsCount(); auto row_count = inCall->GetRowsCount(); auto infos = inCall->GetColumnsInfos(); auto data = inCall->GetData(); std::ofstream file = std::ofstream(filename); file.imbue(std::locale::classic()); for (size_t col = 0; col < col_count; ++col) { if (col < col_count - 1) { file << infos[col].Name() << ","; } else { file << infos[col].Name() << "\n"; } } for (size_t row = 0; row < row_count; ++row) { for (size_t col = 0; col < col_count; ++col) { if (col < col_count - 1) { file << inCall->GetData(col, row) << ","; } else { file << inCall->GetData(col, row) << "\n"; } } } file.close(); return true; } bool megamol::stdplugin::datatools::CSVWriter::getCapabilities(core::DataWriterCtrlCall& call) { call.SetAbortable(false); return true; } <|endoftext|>
<commit_before>/* Siconos-Kernel, Copyright INRIA 2005-2011. * Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * Siconos is a 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. * Siconos 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 Siconos; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Contact: Vincent ACARY, [email protected] */ /*!\file * D1MinusLinear Time-Integrator for Dynamical Systems * T. Schindler, V. Acary */ #ifndef D1MINUSLINEAR_H #define D1MINUSLINEAR_H #define DEBUG_MESSAGES #include "OneStepIntegrator.hpp" #include "SimpleMatrix.hpp" class SiconosMatrix; /** D1MinusLinear Time-Integrator for Dynamical Systems * * \author SICONOS Development Team - copyright INRIA * \version 3.3.0. * \date (Creation) September 01, 2011 * * see Schindler/Acary : Timestepping Schemes for Nonsmooth Dynamics Based * on Discontinuous Galerkin Methods: Definition and Outlook * * A D1MinusLinear instance is defined by the list of concerned dynamical systems. * * Main functions: * * - computeFreeState(): computes xfree (or vfree), dynamical systems * state without taking non-smooth part into account \n * * - updateState(): computes x(q,v), the complete dynamical systems * states. */ class D1MinusLinear : public OneStepIntegrator { protected: /** nslaw effects */ struct _NSLEffectOnFreeOutput; friend class _NSLEffectOnFreeOutput; /** default constructor */ D1MinusLinear() {}; public: /** constructor from one dynamical system * \param DynamicalSystem to be integrated */ D1MinusLinear(SP::DynamicalSystem); /** constructor from a list of dynamical systems * \param list of DynamicalSystems to be integrated */ D1MinusLinear(DynamicalSystemsSet&); /** destructor */ virtual ~D1MinusLinear() {}; /** initialization of the D1MinusLinear integrator; for linear time * invariant systems, we compute time invariant operator */ virtual void initialize(); /** return the maximum of all norms for the residus of DS * \post{ds->residuFree will be calculated, ds->p() contains new position, ds->velocity contains predicted velocity} * \return double */ virtual double computeResidu(); /** integrates the Dynamical System linked to this integrator without taking non-smooth effects into account * \post{ds->velocity contains free velocity} */ virtual void computeFreeState(); /** integrates the UnitaryRelation linked to this integrator, without taking non-smooth effects into account * \param pointer to UnitaryRelation * \param pointer to OneStepNSProblem */ virtual void computeFreeOutput(SP::UnitaryRelation UR, OneStepNSProblem* osnsp); /** integrate the system, between tinit and tend (->iout=true), with possible stop at tout (->iout=false) * \param initial time * \param end time * \param real end time * \param useless flag (for D1MinusLinear, used in Lsodar) */ virtual void integrate(double&, double&, double&, int&) { RuntimeException::selfThrow("D1MinusLinear::integrate - not implemented!"); } /** updates the state of the Dynamical Systems * \param level of interest for the dynamics: not used at the time * \post{ds->velocity contains new velocity} */ virtual void updateState(unsigned int); /** displays the data of the D1MinusLinear's integrator */ virtual void display() { RuntimeException::selfThrow("D1MinusLinear::display - not implemented!"); } /** preparations for Newton iteration */ virtual void prepareNewtonIteration(double time) { RuntimeException::selfThrow("D1MinusLinear::prepareNewtonIteration - not implemented!"); } /** insert a dynamical system in this Integrator * \param pointer to DynamicalSystem */ virtual void insertDynamicalSystem(SP::DynamicalSystem ds); /** encapsulates an operation of dynamic casting * needed by Python interface * \param integrator which must be converted * \return pointer to the integrator if it is of the right type, NULL otherwise */ static D1MinusLinear* convert(OneStepIntegrator* osi); /** visitors hook */ ACCEPT_STD_VISITORS(); }; #endif // D1MINUSLINEAR_H <commit_msg>hidden debug line<commit_after>/* Siconos-Kernel, Copyright INRIA 2005-2011. * Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * Siconos is a 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. * Siconos 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 Siconos; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Contact: Vincent ACARY, [email protected] */ /*!\file * D1MinusLinear Time-Integrator for Dynamical Systems * T. Schindler, V. Acary */ #ifndef D1MINUSLINEAR_H #define D1MINUSLINEAR_H #ifdef DEBUG_D1MINUSLINEAR #define DEBUG_MESSAGES #endif #include "OneStepIntegrator.hpp" #include "SimpleMatrix.hpp" class SiconosMatrix; /** D1MinusLinear Time-Integrator for Dynamical Systems * * \author SICONOS Development Team - copyright INRIA * \version 3.3.0. * \date (Creation) September 01, 2011 * * see Schindler/Acary : Timestepping Schemes for Nonsmooth Dynamics Based * on Discontinuous Galerkin Methods: Definition and Outlook * * A D1MinusLinear instance is defined by the list of concerned dynamical systems. * * Main functions: * * - computeFreeState(): computes xfree (or vfree), dynamical systems * state without taking non-smooth part into account \n * * - updateState(): computes x(q,v), the complete dynamical systems * states. */ class D1MinusLinear : public OneStepIntegrator { protected: /** nslaw effects */ struct _NSLEffectOnFreeOutput; friend class _NSLEffectOnFreeOutput; /** default constructor */ D1MinusLinear() {}; public: /** constructor from one dynamical system * \param DynamicalSystem to be integrated */ D1MinusLinear(SP::DynamicalSystem); /** constructor from a list of dynamical systems * \param list of DynamicalSystems to be integrated */ D1MinusLinear(DynamicalSystemsSet&); /** destructor */ virtual ~D1MinusLinear() {}; /** initialization of the D1MinusLinear integrator; for linear time * invariant systems, we compute time invariant operator */ virtual void initialize(); /** return the maximum of all norms for the residus of DS * \post{ds->residuFree will be calculated, ds->p() contains new position, ds->velocity contains predicted velocity} * \return double */ virtual double computeResidu(); /** integrates the Dynamical System linked to this integrator without taking non-smooth effects into account * \post{ds->velocity contains free velocity} */ virtual void computeFreeState(); /** integrates the UnitaryRelation linked to this integrator, without taking non-smooth effects into account * \param pointer to UnitaryRelation * \param pointer to OneStepNSProblem */ virtual void computeFreeOutput(SP::UnitaryRelation UR, OneStepNSProblem* osnsp); /** integrate the system, between tinit and tend (->iout=true), with possible stop at tout (->iout=false) * \param initial time * \param end time * \param real end time * \param useless flag (for D1MinusLinear, used in Lsodar) */ virtual void integrate(double&, double&, double&, int&) { RuntimeException::selfThrow("D1MinusLinear::integrate - not implemented!"); } /** updates the state of the Dynamical Systems * \param level of interest for the dynamics: not used at the time * \post{ds->velocity contains new velocity} */ virtual void updateState(unsigned int); /** displays the data of the D1MinusLinear's integrator */ virtual void display() { RuntimeException::selfThrow("D1MinusLinear::display - not implemented!"); } /** preparations for Newton iteration */ virtual void prepareNewtonIteration(double time) { RuntimeException::selfThrow("D1MinusLinear::prepareNewtonIteration - not implemented!"); } /** insert a dynamical system in this Integrator * \param pointer to DynamicalSystem */ virtual void insertDynamicalSystem(SP::DynamicalSystem ds); /** encapsulates an operation of dynamic casting * needed by Python interface * \param integrator which must be converted * \return pointer to the integrator if it is of the right type, NULL otherwise */ static D1MinusLinear* convert(OneStepIntegrator* osi); /** visitors hook */ ACCEPT_STD_VISITORS(); }; #endif // D1MINUSLINEAR_H <|endoftext|>
<commit_before>#include "precomp.hpp" #include <iostream> #include <iomanip> using namespace std; using namespace cv; namespace { void helpParser() { printf("\nThe CommandLineParser class is designed for command line arguments parsing\n" "Keys map: \n" "Before you start to work with CommandLineParser you have to create a map for keys.\n" " It will look like this\n" " const char* keys =\n" " {\n" " { s| string| 123asd |string parameter}\n" " { d| digit | 100 |digit parameter }\n" " { c|noCamera|false |without camera }\n" " { 1| |some text|help }\n" " { 2| |333 |another help }\n" " };\n" "Usage syntax: \n" " \"{\" - start of parameter string.\n" " \"}\" - end of parameter string\n" " \"|\" - separator between short name, full name, default value and help\n" "Supported syntax: \n" " --key1=arg1 <If a key with '--' must has an argument\n" " you have to assign it through '=' sign.> \n" "<If the key with '--' doesn't have any argument, it means that it is a bool key>\n" " -key2=arg2 <If a key with '-' must has an argument \n" " you have to assign it through '=' sign.> \n" "If the key with '-' doesn't have any argument, it means that it is a bool key\n" " key3 <This key can't has any parameter> \n" "Usage: \n" " Imagine that the input parameters are next:\n" " -s=string_value --digit=250 --noCamera lena.jpg 10000\n" " CommandLineParser parser(argc, argv, keys) - create a parser object\n" " parser.get<string>(\"s\" or \"string\") will return you first parameter value\n" " parser.get<string>(\"s\", false or \"string\", false) will return you first parameter value\n" " without spaces in end and begin\n" " parser.get<int>(\"d\" or \"digit\") will return you second parameter value.\n" " It also works with 'unsigned int', 'double', and 'float' types>\n" " parser.get<bool>(\"c\" or \"noCamera\") will return you true .\n" " If you enter this key in commandline>\n" " It return you false otherwise.\n" " parser.get<string>(\"1\") will return you the first argument without parameter (lena.jpg) \n" " parser.get<int>(\"2\") will return you the second argument without parameter (10000)\n" " It also works with 'unsigned int', 'double', and 'float' types \n" ); } vector<string> split_string(const string& str, const string& delimiters) { vector<string> res; string split_str = str; size_t pos_delim = split_str.find(delimiters); while ( pos_delim != string::npos) { if (pos_delim == 0) { res.push_back(""); split_str.erase(0, 1); } else { res.push_back(split_str.substr(0, pos_delim)); split_str.erase(0, pos_delim + 1); } pos_delim = split_str.find(delimiters); } res.push_back(split_str); return res; } string del_space(string name) { while ((name.find_first_of(' ') == 0) && (name.length() > 0)) name.erase(0, 1); while ((name.find_last_of(' ') == (name.length() - 1)) && (name.length() > 0)) name.erase(name.end() - 1, name.end()); return name; } }//namespace CommandLineParser::CommandLineParser(int argc, const char* const argv[], const char* keys) { std::string keys_buffer; std::string values_buffer; std::string buffer; std::string curName; std::vector<string> keysVector; std::vector<string> paramVector; std::map<std::string, std::vector<std::string> >::iterator it; size_t flagPosition; int currentIndex = 1; //bool isFound = false; bool withNoKey = false; bool hasValueThroughEq = false; keys_buffer = keys; while (!keys_buffer.empty()) { flagPosition = keys_buffer.find_first_of('}'); flagPosition++; buffer = keys_buffer.substr(0, flagPosition); keys_buffer.erase(0, flagPosition); flagPosition = buffer.find('{'); if (flagPosition != buffer.npos) buffer.erase(flagPosition, (flagPosition + 1)); flagPosition = buffer.find('}'); if (flagPosition != buffer.npos) buffer.erase(flagPosition); paramVector = split_string(buffer, "|"); while (paramVector.size() < 4) paramVector.push_back(""); buffer = paramVector[0]; buffer += '|' + paramVector[1]; //if (buffer == "") CV_ERROR(CV_StsBadArg, "In CommandLineParser need set short and full name"); paramVector.erase(paramVector.begin(), paramVector.begin() + 2); data[buffer] = paramVector; } buffer.clear(); keys_buffer.clear(); paramVector.clear(); for (int i = 1; i < argc; i++) { if (!argv[i]) break; curName = argv[i]; if (curName.find('-') == 0 && ((curName[1] < '0') || (curName[1] > '9'))) { while (curName.find('-') == 0) curName.erase(curName.begin(), (curName.begin() + 1)); } else withNoKey = true; if (curName.find('=') != curName.npos) { hasValueThroughEq = true; buffer = curName; curName.erase(curName.find('=')); buffer.erase(0, (buffer.find('=') + 1)); } values_buffer = del_space(values_buffer); for(it = data.begin(); it != data.end(); it++) { keys_buffer = it->first; keysVector = split_string(keys_buffer, "|"); for (size_t j = 0; j < keysVector.size(); j++) keysVector[j] = del_space(keysVector[j]); values_buffer = it->second[0]; if (((curName == keysVector[0]) || (curName == keysVector[1])) && hasValueThroughEq) { it->second[0] = buffer; //isFound = true; break; } if (!hasValueThroughEq && ((curName == keysVector[0]) || (curName == keysVector[1])) && ( values_buffer.find("false") != values_buffer.npos || values_buffer == "" )) { it->second[0] = "true"; //isFound = true; break; } if (!hasValueThroughEq && (values_buffer.find("false") == values_buffer.npos) && ((curName == keysVector[0]) || (curName == keysVector[1]))) { it->second[0] = argv[++i]; //isFound = true; break; } if (withNoKey) { std::string noKeyStr = it->first; if(atoi(noKeyStr.c_str()) == currentIndex) { it->second[0] = curName; currentIndex++; //isFound = true; break; } } } withNoKey = false; hasValueThroughEq = false; //isFound = false; } } bool CommandLineParser::has(const std::string& keys) { std::map<std::string, std::vector<std::string> >::iterator it; std::vector<string> keysVector; for(it = data.begin(); it != data.end(); it++) { keysVector = split_string(it->first, "|"); for (size_t i = 0; i < keysVector.size(); i++) keysVector[i] = del_space(keysVector[i]); if (keysVector.size() == 1) keysVector.push_back(""); if ((del_space(keys).compare(keysVector[0]) == 0) || (del_space(keys).compare(keysVector[1]) == 0)) return true; } return false; } std::string CommandLineParser::getString(const std::string& keys) { std::map<std::string, std::vector<std::string> >::iterator it; std::vector<string> valueVector; for(it = data.begin(); it != data.end(); it++) { valueVector = split_string(it->first, "|"); for (size_t i = 0; i < valueVector.size(); i++) valueVector[i] = del_space(valueVector[i]); if (valueVector.size() == 1) valueVector.push_back(""); if ((del_space(keys).compare(valueVector[0]) == 0) || (del_space(keys).compare(valueVector[1]) == 0)) return it->second[0]; } return string(); } template<typename _Tp> _Tp CommandLineParser::fromStringNumber(const std::string& str)//the default conversion function for numbers { return getData<_Tp>(str); } void CommandLineParser::printParams() { int col_p = 30; int col_d = 50; std::map<std::string, std::vector<std::string> >::iterator it; std::vector<string> keysVector; std::string buf; for(it = data.begin(); it != data.end(); it++) { keysVector = split_string(it->first, "|"); for (size_t i = 0; i < keysVector.size(); i++) keysVector[i] = del_space(keysVector[i]); cout << " "; buf = ""; if (keysVector[0] != "") { buf = "-" + keysVector[0]; if (keysVector[1] != "") buf += ", --" + keysVector[1]; } else if (keysVector[1] != "") buf += "--" + keysVector[1]; if (del_space(it->second[0]) != "") buf += "=[" + del_space(it->second[0]) + "]"; cout << setw(col_p-2) << left << buf; if ((int)buf.length() > col_p-2) { cout << endl << " "; cout << setw(col_p-2) << left << " "; } buf = ""; if (del_space(it->second[1]) != "") buf += del_space(it->second[1]); for(;;) { bool tr = ((int)buf.length() > col_d-2) ? true: false; std::string::size_type pos = 0; if (tr) { pos = buf.find_first_of(' '); for(;;) { if (buf.find_first_of(' ', pos + 1 ) < (std::string::size_type)(col_d-2) && buf.find_first_of(' ', pos + 1 ) != std::string::npos) pos = buf.find_first_of(' ', pos + 1); else break; } pos++; cout << setw(col_d-2) << left << buf.substr(0, pos) << endl; } else { cout << setw(col_d-2) << left << buf<< endl; break; } buf.erase(0, pos); cout << " "; cout << setw(col_p-2) << left << " "; } } } template<> bool CommandLineParser::get<bool>(const std::string& name, bool space_delete) { std::string str_buf = getString(name); if (space_delete && str_buf != "") { str_buf = del_space(str_buf); } if (str_buf == "true") return true; return false; } template<> std::string CommandLineParser::analyzeValue<std::string>(const std::string& str, bool space_delete) { if (space_delete) { return del_space(str); } return str; } template<> int CommandLineParser::analyzeValue<int>(const std::string& str, bool /*space_delete*/) { return fromStringNumber<int>(str); } template<> unsigned int CommandLineParser::analyzeValue<unsigned int>(const std::string& str, bool /*space_delete*/) { return fromStringNumber<unsigned int>(str); } template<> uint64 CommandLineParser::analyzeValue<uint64>(const std::string& str, bool /*space_delete*/) { return fromStringNumber<uint64>(str); } template<> float CommandLineParser::analyzeValue<float>(const std::string& str, bool /*space_delete*/) { return fromStringNumber<float>(str); } template<> double CommandLineParser::analyzeValue<double>(const std::string& str, bool /*space_delete*/) { return fromStringNumber<double>(str); } <commit_msg>fixed cmd parser when arg is like -+<commit_after>#include "precomp.hpp" #include <iostream> #include <iomanip> using namespace std; using namespace cv; namespace { void helpParser() { printf("\nThe CommandLineParser class is designed for command line arguments parsing\n" "Keys map: \n" "Before you start to work with CommandLineParser you have to create a map for keys.\n" " It will look like this\n" " const char* keys =\n" " {\n" " { s| string| 123asd |string parameter}\n" " { d| digit | 100 |digit parameter }\n" " { c|noCamera|false |without camera }\n" " { 1| |some text|help }\n" " { 2| |333 |another help }\n" " };\n" "Usage syntax: \n" " \"{\" - start of parameter string.\n" " \"}\" - end of parameter string\n" " \"|\" - separator between short name, full name, default value and help\n" "Supported syntax: \n" " --key1=arg1 <If a key with '--' must has an argument\n" " you have to assign it through '=' sign.> \n" "<If the key with '--' doesn't have any argument, it means that it is a bool key>\n" " -key2=arg2 <If a key with '-' must has an argument \n" " you have to assign it through '=' sign.> \n" "If the key with '-' doesn't have any argument, it means that it is a bool key\n" " key3 <This key can't has any parameter> \n" "Usage: \n" " Imagine that the input parameters are next:\n" " -s=string_value --digit=250 --noCamera lena.jpg 10000\n" " CommandLineParser parser(argc, argv, keys) - create a parser object\n" " parser.get<string>(\"s\" or \"string\") will return you first parameter value\n" " parser.get<string>(\"s\", false or \"string\", false) will return you first parameter value\n" " without spaces in end and begin\n" " parser.get<int>(\"d\" or \"digit\") will return you second parameter value.\n" " It also works with 'unsigned int', 'double', and 'float' types>\n" " parser.get<bool>(\"c\" or \"noCamera\") will return you true .\n" " If you enter this key in commandline>\n" " It return you false otherwise.\n" " parser.get<string>(\"1\") will return you the first argument without parameter (lena.jpg) \n" " parser.get<int>(\"2\") will return you the second argument without parameter (10000)\n" " It also works with 'unsigned int', 'double', and 'float' types \n" ); } vector<string> split_string(const string& str, const string& delimiters) { vector<string> res; string split_str = str; size_t pos_delim = split_str.find(delimiters); while ( pos_delim != string::npos) { if (pos_delim == 0) { res.push_back(""); split_str.erase(0, 1); } else { res.push_back(split_str.substr(0, pos_delim)); split_str.erase(0, pos_delim + 1); } pos_delim = split_str.find(delimiters); } res.push_back(split_str); return res; } string del_space(string name) { while ((name.find_first_of(' ') == 0) && (name.length() > 0)) name.erase(0, 1); while ((name.find_last_of(' ') == (name.length() - 1)) && (name.length() > 0)) name.erase(name.end() - 1, name.end()); return name; } }//namespace static bool keyIsNumber(const std::string & option, size_t start) { bool isNumber = true; size_t end = option.find_first_of('=', start); end = option.npos == end ? option.length() : end; for ( ; start < end; ++start) if (!isdigit(option[start])) { isNumber = false; break; } return isNumber; } CommandLineParser::CommandLineParser(int argc, const char* const argv[], const char* keys) { std::string keys_buffer; std::string values_buffer; std::string buffer; std::string curName; std::vector<string> keysVector; std::vector<string> paramVector; std::map<std::string, std::vector<std::string> >::iterator it; size_t flagPosition; int currentIndex = 1; //bool isFound = false; bool withNoKey = false; bool hasValueThroughEq = false; keys_buffer = keys; while (!keys_buffer.empty()) { flagPosition = keys_buffer.find_first_of('}'); flagPosition++; buffer = keys_buffer.substr(0, flagPosition); keys_buffer.erase(0, flagPosition); flagPosition = buffer.find('{'); if (flagPosition != buffer.npos) buffer.erase(flagPosition, (flagPosition + 1)); flagPosition = buffer.find('}'); if (flagPosition != buffer.npos) buffer.erase(flagPosition); paramVector = split_string(buffer, "|"); while (paramVector.size() < 4) paramVector.push_back(""); buffer = paramVector[0]; buffer += '|' + paramVector[1]; //if (buffer == "") CV_ERROR(CV_StsBadArg, "In CommandLineParser need set short and full name"); paramVector.erase(paramVector.begin(), paramVector.begin() + 2); data[buffer] = paramVector; } buffer.clear(); keys_buffer.clear(); paramVector.clear(); for (int i = 1; i < argc; i++) { if (!argv[i]) break; curName = argv[i]; size_t nondash = curName.find_first_not_of("-"); if (nondash == 0 || nondash == curName.npos || keyIsNumber(curName, nondash)) withNoKey = true; else curName.erase(0, nondash); if (curName.find('=') != curName.npos) { hasValueThroughEq = true; buffer = curName; curName.erase(curName.find('=')); buffer.erase(0, (buffer.find('=') + 1)); } values_buffer = del_space(values_buffer); for(it = data.begin(); it != data.end(); it++) { keys_buffer = it->first; keysVector = split_string(keys_buffer, "|"); for (size_t j = 0; j < keysVector.size(); j++) keysVector[j] = del_space(keysVector[j]); values_buffer = it->second[0]; if (((curName == keysVector[0]) || (curName == keysVector[1])) && hasValueThroughEq) { it->second[0] = buffer; //isFound = true; break; } if (!hasValueThroughEq && ((curName == keysVector[0]) || (curName == keysVector[1])) && ( values_buffer.find("false") != values_buffer.npos || values_buffer == "" )) { it->second[0] = "true"; //isFound = true; break; } if (!hasValueThroughEq && (values_buffer.find("false") == values_buffer.npos) && ((curName == keysVector[0]) || (curName == keysVector[1]))) { it->second[0] = argv[++i]; //isFound = true; break; } if (withNoKey) { std::string noKeyStr = it->first; if(atoi(noKeyStr.c_str()) == currentIndex) { it->second[0] = curName; currentIndex++; //isFound = true; break; } } } withNoKey = false; hasValueThroughEq = false; //isFound = false; } } bool CommandLineParser::has(const std::string& keys) { std::map<std::string, std::vector<std::string> >::iterator it; std::vector<string> keysVector; for(it = data.begin(); it != data.end(); it++) { keysVector = split_string(it->first, "|"); for (size_t i = 0; i < keysVector.size(); i++) keysVector[i] = del_space(keysVector[i]); if (keysVector.size() == 1) keysVector.push_back(""); if ((del_space(keys).compare(keysVector[0]) == 0) || (del_space(keys).compare(keysVector[1]) == 0)) return true; } return false; } std::string CommandLineParser::getString(const std::string& keys) { std::map<std::string, std::vector<std::string> >::iterator it; std::vector<string> valueVector; for(it = data.begin(); it != data.end(); it++) { valueVector = split_string(it->first, "|"); for (size_t i = 0; i < valueVector.size(); i++) valueVector[i] = del_space(valueVector[i]); if (valueVector.size() == 1) valueVector.push_back(""); if ((del_space(keys).compare(valueVector[0]) == 0) || (del_space(keys).compare(valueVector[1]) == 0)) return it->second[0]; } return string(); } template<typename _Tp> _Tp CommandLineParser::fromStringNumber(const std::string& str)//the default conversion function for numbers { return getData<_Tp>(str); } void CommandLineParser::printParams() { int col_p = 30; int col_d = 50; std::map<std::string, std::vector<std::string> >::iterator it; std::vector<string> keysVector; std::string buf; for(it = data.begin(); it != data.end(); it++) { keysVector = split_string(it->first, "|"); for (size_t i = 0; i < keysVector.size(); i++) keysVector[i] = del_space(keysVector[i]); cout << " "; buf = ""; if (keysVector[0] != "") { buf = "-" + keysVector[0]; if (keysVector[1] != "") buf += ", --" + keysVector[1]; } else if (keysVector[1] != "") buf += "--" + keysVector[1]; if (del_space(it->second[0]) != "") buf += "=[" + del_space(it->second[0]) + "]"; cout << setw(col_p-2) << left << buf; if ((int)buf.length() > col_p-2) { cout << endl << " "; cout << setw(col_p-2) << left << " "; } buf = ""; if (del_space(it->second[1]) != "") buf += del_space(it->second[1]); for(;;) { bool tr = ((int)buf.length() > col_d-2) ? true: false; std::string::size_type pos = 0; if (tr) { pos = buf.find_first_of(' '); for(;;) { if (buf.find_first_of(' ', pos + 1 ) < (std::string::size_type)(col_d-2) && buf.find_first_of(' ', pos + 1 ) != std::string::npos) pos = buf.find_first_of(' ', pos + 1); else break; } pos++; cout << setw(col_d-2) << left << buf.substr(0, pos) << endl; } else { cout << setw(col_d-2) << left << buf<< endl; break; } buf.erase(0, pos); cout << " "; cout << setw(col_p-2) << left << " "; } } } template<> bool CommandLineParser::get<bool>(const std::string& name, bool space_delete) { std::string str_buf = getString(name); if (space_delete && str_buf != "") { str_buf = del_space(str_buf); } if (str_buf == "true") return true; return false; } template<> std::string CommandLineParser::analyzeValue<std::string>(const std::string& str, bool space_delete) { if (space_delete) { return del_space(str); } return str; } template<> int CommandLineParser::analyzeValue<int>(const std::string& str, bool /*space_delete*/) { return fromStringNumber<int>(str); } template<> unsigned int CommandLineParser::analyzeValue<unsigned int>(const std::string& str, bool /*space_delete*/) { return fromStringNumber<unsigned int>(str); } template<> uint64 CommandLineParser::analyzeValue<uint64>(const std::string& str, bool /*space_delete*/) { return fromStringNumber<uint64>(str); } template<> float CommandLineParser::analyzeValue<float>(const std::string& str, bool /*space_delete*/) { return fromStringNumber<float>(str); } template<> double CommandLineParser::analyzeValue<double>(const std::string& str, bool /*space_delete*/) { return fromStringNumber<double>(str); } <|endoftext|>
<commit_before>// $Id$ AliEmcalJetTask* AddTaskEmcalJet( const char *nTracks = "Tracks", const char *nClusters = "CaloClusters", const Int_t algo = 1, const Double_t radius = 0.4, const Int_t type = 0, const Double_t minTrPt = 0.15, const Double_t minClPt = 0.15 ) { // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskAliEmcalJet", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskAliEmcalJet", "This task requires an input event handler"); return NULL; } //------------------------------------------------------- // Init the task and do settings //------------------------------------------------------- char *algoString; if (algo == 0) algoString = "KT"; else if (algo == 1) algoString = "AKT"; char *typeString; if (type == 0) typeString = "Full"; else if (type == 1) typeString = "Charged"; else if (type == 2) typeString = "Neutral"; char radiusString[200]; sprintf(radiusString,"R0%2.0f",radius*100.0); char pTString[200]; if (minTrPt<1.0) sprintf(pTString,"pT0%3.0f",minTrPt*1000.0); else if (minTrPt>=1.0) sprintf(pTString,"pT%4.0f",minTrPt*1000.0); char ETString[200]; if (minClPt<1.0) sprintf(ETString,"ET0%3.0f",minClPt*1000.0); else if (minClPt>=1.0) sprintf(ETString,"ET%4.0f",minClPt*1000.0); TString name; if (type == 0) name = TString(Form("Jet_%s%sR%s_%s_%s_%s_%s",algoString,typeString,radiusString,nTracks,pTString,nClusters,ETString)); if (type == 1) name = TString(Form("Jet_%s%sR%s_%s_%s",algoString,typeString,radiusString,nTracks,pTString)); if (type == 2) name = TString(Form("Jet_%s%sR%s_%s_%s",algoString,typeString,radiusString,nClusters,ETString)); AliAnalysisTask* mgrTask = mgr->GetTask(name.Data()); if (mgrTask) return mgrTask; AliEmcalJetTask* jetTask = new AliEmcalJetTask(name); jetTask->SetTracksName(nTracks); jetTask->SetClusName(nClusters); jetTask->SetJetsName(name); jetTask->SetAlgo(algo); jetTask->SetMinJetTrackPt(minTrPt); jetTask->SetMinJetClusPt(minClPt); jetTask->SetRadius(radius); jetTask->SetType(type); //------------------------------------------------------- // Final settings, pass to manager and set the containers //------------------------------------------------------- mgr->AddTask(jetTask); // Create containers for input/output AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer() ; mgr->ConnectInput (jetTask, 0, cinput); return jetTask; } <commit_msg>small mods, minjetpt and AliEmcalJetTask return<commit_after>// $Id$ AliEmcalJetTask* AddTaskEmcalJet( const char *nTracks = "Tracks", const char *nClusters = "CaloClusters", const Int_t algo = 1, const Double_t radius = 0.4, const Int_t type = 0, const Double_t minTrPt = 0.15, const Double_t minClPt = 0.15 ) { // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskAliEmcalJet", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskAliEmcalJet", "This task requires an input event handler"); return NULL; } //------------------------------------------------------- // Init the task and do settings //------------------------------------------------------- Double_t minJetPt = 0; char *algoString; if (algo == 0) { algoString = "KT"; minJetPt = 0.1; } else if (algo == 1) { algoString = "AKT"; minJetPt = 1.0; } char *typeString; if (type == 0) typeString = "Full"; else if (type == 1) typeString = "Charged"; else if (type == 2) typeString = "Neutral"; char radiusString[200]; sprintf(radiusString,"R0%2.0f",radius*100.0); char pTString[200]; if (minTrPt<1.0) sprintf(pTString,"pT0%3.0f",minTrPt*1000.0); else if (minTrPt>=1.0) sprintf(pTString,"pT%4.0f",minTrPt*1000.0); char ETString[200]; if (minClPt<1.0) sprintf(ETString,"ET0%3.0f",minClPt*1000.0); else if (minClPt>=1.0) sprintf(ETString,"ET%4.0f",minClPt*1000.0); TString name; if (type == 0) name = TString(Form("Jet_%s%sR%s_%s_%s_%s_%s", algoString,typeString,radiusString,nTracks,pTString,nClusters,ETString)); else if (type == 1) name = TString(Form("Jet_%s%sR%s_%s_%s", algoString,typeString,radiusString,nTracks,pTString)); else if (type == 2) name = TString(Form("Jet_%s%sR%s_%s_%s", algoString,typeString,radiusString,nClusters,ETString)); AliEmcalJetTask* mgrTask = mgr->GetTask(name.Data()); if (mgrTask) return mgrTask; AliEmcalJetTask* jetTask = new AliEmcalJetTask(name); jetTask->SetTracksName(nTracks); jetTask->SetClusName(nClusters); jetTask->SetJetsName(name); jetTask->SetAlgo(algo); jetTask->SetMinJetTrackPt(minTrPt); jetTask->SetMinJetClusPt(minClPt); jetTask->SetMinJetPt(minJetPt); jetTask->SetRadius(radius); jetTask->SetType(type); //------------------------------------------------------- // Final settings, pass to manager and set the containers //------------------------------------------------------- mgr->AddTask(jetTask); // Create containers for input/output AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer() ; mgr->ConnectInput (jetTask, 0, cinput); return jetTask; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/mcbist_workarounds.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file mcbist_workarounds.C /// @brief Workarounds for the MCBISt engine /// Workarounds are very device specific, so there is no attempt to generalize /// this code in any way. /// // *HWP HWP Owner: Stephen Glancy <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <p9_mc_scom_addresses.H> #include <p9_mc_scom_addresses_fld.H> #include <lib/mss_attribute_accessors.H> #include <generic/memory/lib/utils/scom.H> #include <generic/memory/lib/utils/pos.H> #include <lib/dimm/kind.H> #include <lib/workarounds/mcbist_workarounds.H> #include <lib/mcbist/mcbist.H> #include <lib/fir/fir.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_DIMM; using fapi2::FAPI2_RC_SUCCESS; namespace mss { namespace workarounds { namespace mcbist { /// /// @brief Replace reads with displays in the passed in MCBIST program /// @param[in,out] the MCBIST program to check for read/display replacement /// @note Useful for testing /// void replace_read_helper(mss::mcbist::program<TARGET_TYPE_MCBIST>& io_program) { using TT = mss::mcbistTraits<TARGET_TYPE_MCBIST>; io_program.change_maint_broadcast_mode(mss::OFF); io_program.change_end_boundary(mss::mcbist::end_boundary::STOP_AFTER_ADDRESS); for (auto& st : io_program.iv_subtests) { uint64_t l_op = 0; st.iv_mcbmr.extractToRight<TT::OP_TYPE, TT::OP_TYPE_LEN>(l_op); if (l_op == mss::mcbist::op_type::READ) { l_op = mss::mcbist::op_type::DISPLAY; } st.iv_mcbmr.insertFromRight<TT::OP_TYPE, TT::OP_TYPE_LEN>(l_op); } } /// /// @brief End of rank work around /// For Nimbus DD1 the MCBIST engine doesn't detect the end of rank properly /// for a 1R DIMM during a super-fast read. To work around this, we check the /// MCBIST to see if any port has a 1R DIMM on it and if so we change our stop /// conditions to immediate. However, because that doesn't work (by design) with /// read, we also must change all reads to displays (slow read.) /// @param[in] i_target the fapi2 target of the mcbist /// @param[in,out] io_program the mcbist program to check /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// fapi2::ReturnCode end_of_rank( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target, mss::mcbist::program<TARGET_TYPE_MCBIST>& io_program ) { using TT = mss::mcbistTraits<TARGET_TYPE_MCBIST>; // If we don't need the mcbist work-around, we're done. if (! mss::chip_ec_feature_mcbist_end_of_rank(i_target) ) { return FAPI2_RC_SUCCESS; } // First things first - lets find out if we have an 1R DIMM on our side of the chip. const auto l_dimm_kinds = dimm::kind::vector( mss::find_targets<TARGET_TYPE_DIMM>(i_target) ); const auto l_kind = std::find_if(l_dimm_kinds.begin(), l_dimm_kinds.end(), [](const dimm::kind & k) -> bool { // If total ranks are 1, we have a 1R DIMM, SDP. This is the fellow of concern return k.iv_total_ranks == 1; }); // If we don't find the fellow of concern, we can get outta here if (l_kind == l_dimm_kinds.end()) { FAPI_INF("no 1R SDP DIMM on this MCBIST (%s), we're ok", mss::c_str(i_target)); return FAPI2_RC_SUCCESS; } // Keep in mind that pause-on-error-mode is two bits and it doesn't encode master/slave. The // end_boundary enums are constructed such that STOP_AFTER_MASTER_RANK is really stop on // either master or slave for the purposes of this field. So, checking stop-after-master-rank // will catch both master and slave pauses which is correct for this work-around. uint64_t l_pause_mode = 0; io_program.iv_config.extractToRight<TT::CFG_PAUSE_ON_ERROR_MODE, TT::CFG_PAUSE_ON_ERROR_MODE_LEN>(l_pause_mode); if( l_pause_mode != mss::mcbist::end_boundary::STOP_AFTER_MASTER_RANK ) { FAPI_INF("not checking rank boundaries on this MCBIST (%s), we're ok", mss::c_str(i_target)); return FAPI2_RC_SUCCESS; } // If we're here, we need to fix up our program. We need to set our stop to stop immediate, which implies // we don't do broadcasts and we can't do read, we have to do display. FAPI_INF("%s replacing reads and changing broadcast mode due to a chip bug", mss::c_str(i_target)); replace_read_helper(io_program); return fapi2::FAPI2_RC_SUCCESS; } /// /// @brief WAT debug attention /// For Nimbus DD1 the MCBIST engine uses the WAT debug bit as a workaround /// @param[in] i_target the fapi2 target of the mcbist /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// fapi2::ReturnCode wat_debug_attention( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target ) { // MCBIST attentions are already special attention if (mss::chip_ec_feature_mss_wat_debug_attn(i_target)) { fapi2::ReturnCode l_rc; fir::reg<MCBIST_MCBISTFIRQ> mcbist_fir_register(i_target, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCBIST_MCBISTFIRQ); FAPI_TRY(mcbist_fir_register.attention<MCBIST_MCBISTFIRQ_WAT_DEBUG_ATTN>().write()); } return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } } // close namespace mcbist } // close namespace workarounds } // close namespace mss <commit_msg>Added workaround for broadcast mode UE noise window<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/mcbist_workarounds.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file mcbist_workarounds.C /// @brief Workarounds for the MCBISt engine /// Workarounds are very device specific, so there is no attempt to generalize /// this code in any way. /// // *HWP HWP Owner: Stephen Glancy <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <p9_mc_scom_addresses.H> #include <p9_mc_scom_addresses_fld.H> #include <lib/mss_attribute_accessors.H> #include <generic/memory/lib/utils/scom.H> #include <generic/memory/lib/utils/pos.H> #include <lib/dimm/kind.H> #include <lib/workarounds/mcbist_workarounds.H> #include <lib/mcbist/mcbist.H> #include <lib/fir/fir.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_DIMM; using fapi2::FAPI2_RC_SUCCESS; namespace mss { namespace workarounds { namespace mcbist { /// /// @brief Replace reads with displays in the passed in MCBIST program /// @param[in,out] the MCBIST program to check for read/display replacement /// @note Useful for testing /// void replace_read_helper(mss::mcbist::program<TARGET_TYPE_MCBIST>& io_program) { using TT = mss::mcbistTraits<TARGET_TYPE_MCBIST>; io_program.change_maint_broadcast_mode(mss::OFF); io_program.change_end_boundary(mss::mcbist::end_boundary::STOP_AFTER_ADDRESS); for (auto& st : io_program.iv_subtests) { uint64_t l_op = 0; st.iv_mcbmr.extractToRight<TT::OP_TYPE, TT::OP_TYPE_LEN>(l_op); if (l_op == mss::mcbist::op_type::READ) { l_op = mss::mcbist::op_type::DISPLAY; } st.iv_mcbmr.insertFromRight<TT::OP_TYPE, TT::OP_TYPE_LEN>(l_op); } } /// /// @brief End of rank work around /// For Nimbus DD1 the MCBIST engine doesn't detect the end of rank properly /// for a 1R DIMM during a super-fast read. To work around this, we check the /// MCBIST to see if any port has a 1R DIMM on it and if so we change our stop /// conditions to immediate. However, because that doesn't work (by design) with /// read, we also must change all reads to displays (slow read.) /// @param[in] i_target the fapi2 target of the mcbist /// @param[in,out] io_program the mcbist program to check /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// fapi2::ReturnCode end_of_rank( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target, mss::mcbist::program<TARGET_TYPE_MCBIST>& io_program ) { using TT = mss::mcbistTraits<TARGET_TYPE_MCBIST>; // If we don't need the mcbist work-around, we're done. if (! mss::chip_ec_feature_mcbist_end_of_rank(i_target) ) { return FAPI2_RC_SUCCESS; } // First things first - lets find out if we have an 1R DIMM on our side of the chip. const auto l_dimm_kinds = dimm::kind::vector( mss::find_targets<TARGET_TYPE_DIMM>(i_target) ); const auto l_kind = std::find_if(l_dimm_kinds.begin(), l_dimm_kinds.end(), [](const dimm::kind & k) -> bool { // If total ranks are 1, we have a 1R DIMM, SDP. This is the fellow of concern return k.iv_total_ranks == 1; }); // If we don't find the fellow of concern, we can get outta here if (l_kind == l_dimm_kinds.end()) { FAPI_INF("no 1R SDP DIMM on this MCBIST (%s), we're ok", mss::c_str(i_target)); return FAPI2_RC_SUCCESS; } // Keep in mind that pause-on-error-mode is two bits and it doesn't encode master/slave. The // end_boundary enums are constructed such that STOP_AFTER_MASTER_RANK is really stop on // either master or slave for the purposes of this field. So, checking stop-after-master-rank // will catch both master and slave pauses which is correct for this work-around. uint64_t l_pause_mode = 0; io_program.iv_config.extractToRight<TT::CFG_PAUSE_ON_ERROR_MODE, TT::CFG_PAUSE_ON_ERROR_MODE_LEN>(l_pause_mode); if( l_pause_mode != mss::mcbist::end_boundary::STOP_AFTER_MASTER_RANK ) { FAPI_INF("not checking rank boundaries on this MCBIST (%s), we're ok", mss::c_str(i_target)); return FAPI2_RC_SUCCESS; } // If we're here, we need to fix up our program. We need to set our stop to stop immediate, which implies // we don't do broadcasts and we can't do read, we have to do display. FAPI_INF("%s replacing reads and changing broadcast mode due to a chip bug", mss::c_str(i_target)); replace_read_helper(io_program); return fapi2::FAPI2_RC_SUCCESS; } /// /// @brief WAT debug attention /// For Nimbus DD1 the MCBIST engine uses the WAT debug bit as a workaround /// @param[in] i_target the fapi2 target of the mcbist /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// fapi2::ReturnCode wat_debug_attention( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target ) { // MCBIST attentions are already special attention if (mss::chip_ec_feature_mss_wat_debug_attn(i_target)) { fapi2::ReturnCode l_rc; fir::reg<MCBIST_MCBISTFIRQ> mcbist_fir_register(i_target, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCBIST_MCBISTFIRQ); FAPI_TRY(mcbist_fir_register.attention<MCBIST_MCBISTFIRQ_WAT_DEBUG_ATTN>().write()); } return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } /// /// @brief BROADCAST OUT OF SYNC workaround /// A UE noise window is triggered by UE/AUEs causing an out of sync error /// @param[in] i_target the fapi2 target of the mcbist /// @param[in] i_value value to enable or disable workaround /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// fapi2::ReturnCode broadcast_out_of_sync( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target, const mss::states i_value ) { fapi2::ReturnCode l_rc; fapi2::buffer<uint64_t> recr_buffer; fir::reg<MCBIST_MCBISTFIRQ> l_mcbist_fir_reg(i_target, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCBIST_MCBISTFIRQ); // Check for enabled (post memdiag) or disbaled (pre memdiag) workaround if ( i_value ) { // Initialize Broadcast of out sync to checkstop post workaround l_mcbist_fir_reg.checkstop<MCBIST_MCBISTFIRQ_MCBIST_BRODCAST_OUT_OF_SYNC>(); } else { // Initialize Broadcast of out sync to recoverable pre workaround l_mcbist_fir_reg.recoverable_error<MCBIST_MCBISTFIRQ_MCBIST_BRODCAST_OUT_OF_SYNC>(); } FAPI_TRY(l_mcbist_fir_reg.write(), "unable to write fir::reg %d", MCBIST_MCBISTFIRQ); for (const auto& p : mss::find_targets<fapi2::TARGET_TYPE_MCA>(i_target)) { // Set UE noise window for workaround mss::read_recr_register(p, recr_buffer); mss::set_enable_ue_noise_window(recr_buffer, i_value); mss::write_recr_register(p, recr_buffer); } fapi_try_exit: return fapi2::current_err; } } // close namespace mcbist } // close namespace workarounds } // close namespace mss <|endoftext|>
<commit_before>#ifndef F_CPU #define F_CPU 8000000UL // Internal 8MHz clock #endif #include <avr/io.h> #include <util/delay.h> int main(void) { // Configure PORTB-pins DDRD = 0x04; // Loop forever while(1) { // LED On/Off every other loop PORTD ^= 0b00000100; _delay_ms(500); } } <commit_msg>Fixed erroneous comment<commit_after>#ifndef F_CPU #define F_CPU 8000000UL // Internal 8MHz clock #endif #include <avr/io.h> #include <util/delay.h> int main(void) { // Configure PD2 as output DDRD = 0x04; // Loop forever while(1) { // LED On/Off every other loop PORTD ^= 0b00000100; _delay_ms(500); } } <|endoftext|>
<commit_before>/*************************************************************************/ /* collision_polygon_2d.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "collision_polygon_2d.h" #include "collision_object_2d.h" #include "core/config/engine.h" #include "core/math/geometry_2d.h" #include "scene/resources/concave_polygon_shape_2d.h" #include "scene/resources/convex_polygon_shape_2d.h" #include "thirdparty/misc/polypartition.h" void CollisionPolygon2D::_build_polygon() { parent->shape_owner_clear_shapes(owner_id); if (polygon.size() == 0) { return; } bool solids = build_mode == BUILD_SOLIDS; if (solids) { //here comes the sun, lalalala //decompose concave into multiple convex polygons and add them Vector<Vector<Vector2>> decomp = _decompose_in_convex(); for (int i = 0; i < decomp.size(); i++) { Ref<ConvexPolygonShape2D> convex = memnew(ConvexPolygonShape2D); convex->set_points(decomp[i]); parent->shape_owner_add_shape(owner_id, convex); } } else { Ref<ConcavePolygonShape2D> concave = memnew(ConcavePolygonShape2D); Vector<Vector2> segments; segments.resize(polygon.size() * 2); Vector2 *w = segments.ptrw(); for (int i = 0; i < polygon.size(); i++) { w[(i << 1) + 0] = polygon[i]; w[(i << 1) + 1] = polygon[(i + 1) % polygon.size()]; } concave->set_segments(segments); parent->shape_owner_add_shape(owner_id, concave); } } Vector<Vector<Vector2>> CollisionPolygon2D::_decompose_in_convex() { Vector<Vector<Vector2>> decomp = Geometry2D::decompose_polygon_in_convex(polygon); return decomp; } void CollisionPolygon2D::_update_in_shape_owner(bool p_xform_only) { parent->shape_owner_set_transform(owner_id, get_transform()); if (p_xform_only) { return; } parent->shape_owner_set_disabled(owner_id, disabled); parent->shape_owner_set_one_way_collision(owner_id, one_way_collision); parent->shape_owner_set_one_way_collision_margin(owner_id, one_way_collision_margin); } void CollisionPolygon2D::_notification(int p_what) { switch (p_what) { case NOTIFICATION_PARENTED: { parent = Object::cast_to<CollisionObject2D>(get_parent()); if (parent) { owner_id = parent->create_shape_owner(this); _build_polygon(); _update_in_shape_owner(); } /*if (Engine::get_singleton()->is_editor_hint()) { //display above all else set_z_as_relative(false); set_z_index(RS::CANVAS_ITEM_Z_MAX - 1); }*/ } break; case NOTIFICATION_ENTER_TREE: { if (parent) { _update_in_shape_owner(); } } break; case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: { if (parent) { _update_in_shape_owner(true); } } break; case NOTIFICATION_UNPARENTED: { if (parent) { parent->remove_shape_owner(owner_id); } owner_id = 0; parent = nullptr; } break; case NOTIFICATION_DRAW: { if (!Engine::get_singleton()->is_editor_hint() && !get_tree()->is_debugging_collisions_hint()) { break; } for (int i = 0; i < polygon.size(); i++) { Vector2 p = polygon[i]; Vector2 n = polygon[(i + 1) % polygon.size()]; // draw line with width <= 1, so it does not scale with zoom and break pixel exact editing draw_line(p, n, Color(0.9, 0.2, 0.0, 0.8), 1); } #define DEBUG_DECOMPOSE #if defined(TOOLS_ENABLED) && defined(DEBUG_DECOMPOSE) Vector<Vector<Vector2>> decomp = _decompose_in_convex(); Color c(0.4, 0.9, 0.1); for (int i = 0; i < decomp.size(); i++) { c.set_hsv(Math::fmod(c.get_h() + 0.738, 1), c.get_s(), c.get_v(), 0.5); draw_colored_polygon(decomp[i], c); } #else draw_colored_polygon(polygon, get_tree()->get_debug_collisions_color()); #endif if (one_way_collision) { Color dcol = get_tree()->get_debug_collisions_color(); //0.9,0.2,0.2,0.4); dcol.a = 1.0; Vector2 line_to(0, 20); draw_line(Vector2(), line_to, dcol, 3); Vector<Vector2> pts; real_t tsize = 8; pts.push_back(line_to + (Vector2(0, tsize))); pts.push_back(line_to + (Vector2(Math_SQRT12 * tsize, 0))); pts.push_back(line_to + (Vector2(-Math_SQRT12 * tsize, 0))); Vector<Color> cols; for (int i = 0; i < 3; i++) { cols.push_back(dcol); } draw_primitive(pts, cols, Vector<Vector2>()); //small arrow } } break; } } void CollisionPolygon2D::set_polygon(const Vector<Point2> &p_polygon) { polygon = p_polygon; { for (int i = 0; i < polygon.size(); i++) { if (i == 0) { aabb = Rect2(polygon[i], Size2()); } else { aabb.expand_to(polygon[i]); } } if (aabb == Rect2()) { aabb = Rect2(-10, -10, 20, 20); } else { aabb.position -= aabb.size * 0.3; aabb.size += aabb.size * 0.6; } } if (parent) { _build_polygon(); _update_in_shape_owner(); } update(); update_configuration_warning(); } Vector<Point2> CollisionPolygon2D::get_polygon() const { return polygon; } void CollisionPolygon2D::set_build_mode(BuildMode p_mode) { ERR_FAIL_INDEX((int)p_mode, 2); build_mode = p_mode; if (parent) { _build_polygon(); _update_in_shape_owner(); } } CollisionPolygon2D::BuildMode CollisionPolygon2D::get_build_mode() const { return build_mode; } #ifdef TOOLS_ENABLED Rect2 CollisionPolygon2D::_edit_get_rect() const { return aabb; } bool CollisionPolygon2D::_edit_use_rect() const { return true; } bool CollisionPolygon2D::_edit_is_selected_on_click(const Point2 &p_point, double p_tolerance) const { return Geometry2D::is_point_in_polygon(p_point, Variant(polygon)); } #endif String CollisionPolygon2D::get_configuration_warning() const { String warning = Node2D::get_configuration_warning(); if (!Object::cast_to<CollisionObject2D>(get_parent())) { if (!warning.is_empty()) { warning += "\n\n"; } warning += TTR("CollisionPolygon2D only serves to provide a collision shape to a CollisionObject2D derived node. Please only use it as a child of Area2D, StaticBody2D, RigidBody2D, KinematicBody2D, etc. to give them a shape."); } if (polygon.is_empty()) { if (!warning.is_empty()) { warning += "\n\n"; } warning += TTR("An empty CollisionPolygon2D has no effect on collision."); } return warning; } void CollisionPolygon2D::set_disabled(bool p_disabled) { disabled = p_disabled; update(); if (parent) { parent->shape_owner_set_disabled(owner_id, p_disabled); } } bool CollisionPolygon2D::is_disabled() const { return disabled; } void CollisionPolygon2D::set_one_way_collision(bool p_enable) { one_way_collision = p_enable; update(); if (parent) { parent->shape_owner_set_one_way_collision(owner_id, p_enable); } } bool CollisionPolygon2D::is_one_way_collision_enabled() const { return one_way_collision; } void CollisionPolygon2D::set_one_way_collision_margin(real_t p_margin) { one_way_collision_margin = p_margin; if (parent) { parent->shape_owner_set_one_way_collision_margin(owner_id, one_way_collision_margin); } } real_t CollisionPolygon2D::get_one_way_collision_margin() const { return one_way_collision_margin; } void CollisionPolygon2D::_bind_methods() { ClassDB::bind_method(D_METHOD("set_polygon", "polygon"), &CollisionPolygon2D::set_polygon); ClassDB::bind_method(D_METHOD("get_polygon"), &CollisionPolygon2D::get_polygon); ClassDB::bind_method(D_METHOD("set_build_mode", "build_mode"), &CollisionPolygon2D::set_build_mode); ClassDB::bind_method(D_METHOD("get_build_mode"), &CollisionPolygon2D::get_build_mode); ClassDB::bind_method(D_METHOD("set_disabled", "disabled"), &CollisionPolygon2D::set_disabled); ClassDB::bind_method(D_METHOD("is_disabled"), &CollisionPolygon2D::is_disabled); ClassDB::bind_method(D_METHOD("set_one_way_collision", "enabled"), &CollisionPolygon2D::set_one_way_collision); ClassDB::bind_method(D_METHOD("is_one_way_collision_enabled"), &CollisionPolygon2D::is_one_way_collision_enabled); ClassDB::bind_method(D_METHOD("set_one_way_collision_margin", "margin"), &CollisionPolygon2D::set_one_way_collision_margin); ClassDB::bind_method(D_METHOD("get_one_way_collision_margin"), &CollisionPolygon2D::get_one_way_collision_margin); ADD_PROPERTY(PropertyInfo(Variant::INT, "build_mode", PROPERTY_HINT_ENUM, "Solids,Segments"), "set_build_mode", "get_build_mode"); ADD_PROPERTY(PropertyInfo(Variant::PACKED_VECTOR2_ARRAY, "polygon"), "set_polygon", "get_polygon"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "disabled"), "set_disabled", "is_disabled"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "one_way_collision"), "set_one_way_collision", "is_one_way_collision_enabled"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "one_way_collision_margin", PROPERTY_HINT_RANGE, "0,128,0.1"), "set_one_way_collision_margin", "get_one_way_collision_margin"); BIND_ENUM_CONSTANT(BUILD_SOLIDS); BIND_ENUM_CONSTANT(BUILD_SEGMENTS); } CollisionPolygon2D::CollisionPolygon2D() { set_notify_local_transform(true); } <commit_msg>Fix errors with invalid CollisionPolygon2D<commit_after>/*************************************************************************/ /* collision_polygon_2d.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "collision_polygon_2d.h" #include "collision_object_2d.h" #include "core/config/engine.h" #include "core/math/geometry_2d.h" #include "scene/resources/concave_polygon_shape_2d.h" #include "scene/resources/convex_polygon_shape_2d.h" #include "thirdparty/misc/polypartition.h" void CollisionPolygon2D::_build_polygon() { parent->shape_owner_clear_shapes(owner_id); bool solids = build_mode == BUILD_SOLIDS; if (solids) { if (polygon.size() < 3) { return; } //here comes the sun, lalalala //decompose concave into multiple convex polygons and add them Vector<Vector<Vector2>> decomp = _decompose_in_convex(); for (int i = 0; i < decomp.size(); i++) { Ref<ConvexPolygonShape2D> convex = memnew(ConvexPolygonShape2D); convex->set_points(decomp[i]); parent->shape_owner_add_shape(owner_id, convex); } } else { if (polygon.size() < 2) { return; } Ref<ConcavePolygonShape2D> concave = memnew(ConcavePolygonShape2D); Vector<Vector2> segments; segments.resize(polygon.size() * 2); Vector2 *w = segments.ptrw(); for (int i = 0; i < polygon.size(); i++) { w[(i << 1) + 0] = polygon[i]; w[(i << 1) + 1] = polygon[(i + 1) % polygon.size()]; } concave->set_segments(segments); parent->shape_owner_add_shape(owner_id, concave); } } Vector<Vector<Vector2>> CollisionPolygon2D::_decompose_in_convex() { Vector<Vector<Vector2>> decomp = Geometry2D::decompose_polygon_in_convex(polygon); return decomp; } void CollisionPolygon2D::_update_in_shape_owner(bool p_xform_only) { parent->shape_owner_set_transform(owner_id, get_transform()); if (p_xform_only) { return; } parent->shape_owner_set_disabled(owner_id, disabled); parent->shape_owner_set_one_way_collision(owner_id, one_way_collision); parent->shape_owner_set_one_way_collision_margin(owner_id, one_way_collision_margin); } void CollisionPolygon2D::_notification(int p_what) { switch (p_what) { case NOTIFICATION_PARENTED: { parent = Object::cast_to<CollisionObject2D>(get_parent()); if (parent) { owner_id = parent->create_shape_owner(this); _build_polygon(); _update_in_shape_owner(); } /*if (Engine::get_singleton()->is_editor_hint()) { //display above all else set_z_as_relative(false); set_z_index(RS::CANVAS_ITEM_Z_MAX - 1); }*/ } break; case NOTIFICATION_ENTER_TREE: { if (parent) { _update_in_shape_owner(); } } break; case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: { if (parent) { _update_in_shape_owner(true); } } break; case NOTIFICATION_UNPARENTED: { if (parent) { parent->remove_shape_owner(owner_id); } owner_id = 0; parent = nullptr; } break; case NOTIFICATION_DRAW: { if (!Engine::get_singleton()->is_editor_hint() && !get_tree()->is_debugging_collisions_hint()) { break; } int polygon_count = polygon.size(); for (int i = 0; i < polygon_count; i++) { Vector2 p = polygon[i]; Vector2 n = polygon[(i + 1) % polygon_count]; // draw line with width <= 1, so it does not scale with zoom and break pixel exact editing draw_line(p, n, Color(0.9, 0.2, 0.0, 0.8), 1); } if (polygon_count > 2) { #define DEBUG_DECOMPOSE #if defined(TOOLS_ENABLED) && defined(DEBUG_DECOMPOSE) Vector<Vector<Vector2>> decomp = _decompose_in_convex(); Color c(0.4, 0.9, 0.1); for (int i = 0; i < decomp.size(); i++) { c.set_hsv(Math::fmod(c.get_h() + 0.738, 1), c.get_s(), c.get_v(), 0.5); draw_colored_polygon(decomp[i], c); } #else draw_colored_polygon(polygon, get_tree()->get_debug_collisions_color()); #endif } if (one_way_collision) { Color dcol = get_tree()->get_debug_collisions_color(); //0.9,0.2,0.2,0.4); dcol.a = 1.0; Vector2 line_to(0, 20); draw_line(Vector2(), line_to, dcol, 3); Vector<Vector2> pts; real_t tsize = 8; pts.push_back(line_to + (Vector2(0, tsize))); pts.push_back(line_to + (Vector2(Math_SQRT12 * tsize, 0))); pts.push_back(line_to + (Vector2(-Math_SQRT12 * tsize, 0))); Vector<Color> cols; for (int i = 0; i < 3; i++) { cols.push_back(dcol); } draw_primitive(pts, cols, Vector<Vector2>()); //small arrow } } break; } } void CollisionPolygon2D::set_polygon(const Vector<Point2> &p_polygon) { polygon = p_polygon; { for (int i = 0; i < polygon.size(); i++) { if (i == 0) { aabb = Rect2(polygon[i], Size2()); } else { aabb.expand_to(polygon[i]); } } if (aabb == Rect2()) { aabb = Rect2(-10, -10, 20, 20); } else { aabb.position -= aabb.size * 0.3; aabb.size += aabb.size * 0.6; } } if (parent) { _build_polygon(); _update_in_shape_owner(); } update(); update_configuration_warning(); } Vector<Point2> CollisionPolygon2D::get_polygon() const { return polygon; } void CollisionPolygon2D::set_build_mode(BuildMode p_mode) { ERR_FAIL_INDEX((int)p_mode, 2); build_mode = p_mode; if (parent) { _build_polygon(); _update_in_shape_owner(); } update(); update_configuration_warning(); } CollisionPolygon2D::BuildMode CollisionPolygon2D::get_build_mode() const { return build_mode; } #ifdef TOOLS_ENABLED Rect2 CollisionPolygon2D::_edit_get_rect() const { return aabb; } bool CollisionPolygon2D::_edit_use_rect() const { return true; } bool CollisionPolygon2D::_edit_is_selected_on_click(const Point2 &p_point, double p_tolerance) const { return Geometry2D::is_point_in_polygon(p_point, Variant(polygon)); } #endif String CollisionPolygon2D::get_configuration_warning() const { String warning = Node2D::get_configuration_warning(); if (!Object::cast_to<CollisionObject2D>(get_parent())) { if (!warning.is_empty()) { warning += "\n\n"; } warning += TTR("CollisionPolygon2D only serves to provide a collision shape to a CollisionObject2D derived node. Please only use it as a child of Area2D, StaticBody2D, RigidBody2D, KinematicBody2D, etc. to give them a shape."); } int polygon_count = polygon.size(); if (polygon_count == 0) { if (!warning.is_empty()) { warning += "\n\n"; } warning += TTR("An empty CollisionPolygon2D has no effect on collision."); } else { bool solids = build_mode == BUILD_SOLIDS; if (solids) { if (polygon_count < 3) { if (!warning.is_empty()) { warning += "\n\n"; } warning += TTR("Invalid polygon. At least 3 points are needed in 'Solids' build mode."); } } else if (polygon_count < 2) { if (!warning.is_empty()) { warning += "\n\n"; } warning += TTR("Invalid polygon. At least 2 points are needed in 'Segments' build mode."); } } return warning; } void CollisionPolygon2D::set_disabled(bool p_disabled) { disabled = p_disabled; update(); if (parent) { parent->shape_owner_set_disabled(owner_id, p_disabled); } } bool CollisionPolygon2D::is_disabled() const { return disabled; } void CollisionPolygon2D::set_one_way_collision(bool p_enable) { one_way_collision = p_enable; update(); if (parent) { parent->shape_owner_set_one_way_collision(owner_id, p_enable); } } bool CollisionPolygon2D::is_one_way_collision_enabled() const { return one_way_collision; } void CollisionPolygon2D::set_one_way_collision_margin(real_t p_margin) { one_way_collision_margin = p_margin; if (parent) { parent->shape_owner_set_one_way_collision_margin(owner_id, one_way_collision_margin); } } real_t CollisionPolygon2D::get_one_way_collision_margin() const { return one_way_collision_margin; } void CollisionPolygon2D::_bind_methods() { ClassDB::bind_method(D_METHOD("set_polygon", "polygon"), &CollisionPolygon2D::set_polygon); ClassDB::bind_method(D_METHOD("get_polygon"), &CollisionPolygon2D::get_polygon); ClassDB::bind_method(D_METHOD("set_build_mode", "build_mode"), &CollisionPolygon2D::set_build_mode); ClassDB::bind_method(D_METHOD("get_build_mode"), &CollisionPolygon2D::get_build_mode); ClassDB::bind_method(D_METHOD("set_disabled", "disabled"), &CollisionPolygon2D::set_disabled); ClassDB::bind_method(D_METHOD("is_disabled"), &CollisionPolygon2D::is_disabled); ClassDB::bind_method(D_METHOD("set_one_way_collision", "enabled"), &CollisionPolygon2D::set_one_way_collision); ClassDB::bind_method(D_METHOD("is_one_way_collision_enabled"), &CollisionPolygon2D::is_one_way_collision_enabled); ClassDB::bind_method(D_METHOD("set_one_way_collision_margin", "margin"), &CollisionPolygon2D::set_one_way_collision_margin); ClassDB::bind_method(D_METHOD("get_one_way_collision_margin"), &CollisionPolygon2D::get_one_way_collision_margin); ADD_PROPERTY(PropertyInfo(Variant::INT, "build_mode", PROPERTY_HINT_ENUM, "Solids,Segments"), "set_build_mode", "get_build_mode"); ADD_PROPERTY(PropertyInfo(Variant::PACKED_VECTOR2_ARRAY, "polygon"), "set_polygon", "get_polygon"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "disabled"), "set_disabled", "is_disabled"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "one_way_collision"), "set_one_way_collision", "is_one_way_collision_enabled"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "one_way_collision_margin", PROPERTY_HINT_RANGE, "0,128,0.1"), "set_one_way_collision_margin", "get_one_way_collision_margin"); BIND_ENUM_CONSTANT(BUILD_SOLIDS); BIND_ENUM_CONSTANT(BUILD_SEGMENTS); } CollisionPolygon2D::CollisionPolygon2D() { set_notify_local_transform(true); } <|endoftext|>
<commit_before>/**************************************************************************** This file is part of the GLC-lib library. Copyright (C) 2005-2008 Laurent Ribon ([email protected]) Version 2.0.0, packaged on July 2010. http://glc-lib.sourceforge.net GLC-lib 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. GLC-lib 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 GLC-lib; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ //! \file glc_structinstance.cpp implementation of the GLC_StructInstance class. #include "glc_structinstance.h" #include "glc_structreference.h" #include "glc_structoccurence.h" // Default constructor GLC_StructInstance::GLC_StructInstance(GLC_StructReference* pStructReference) : m_pNumberOfInstance(NULL) , m_pStructReference(pStructReference) , m_ListOfOccurences() , m_RelativeMatrix() , m_Name() , m_pAttributes(NULL) { if (NULL == m_pStructReference) { m_pStructReference= new GLC_StructReference(); } m_Name= m_pStructReference->name(); if (m_pStructReference->hasStructInstance()) { m_pNumberOfInstance= m_pStructReference->firstInstanceHandle()->m_pNumberOfInstance; ++(*m_pNumberOfInstance); } else { m_pNumberOfInstance= new int(1); } // Inform reference that an instance has been created m_pStructReference->structInstanceCreated(this); //qDebug() << "GLC_StructInstance::GLC_StructInstance : " << (*m_pNumberOfInstance) << " " << m_pNumberOfInstance; } // Create instance with a rep GLC_StructInstance::GLC_StructInstance(GLC_Rep* pRep) : m_pNumberOfInstance(NULL) , m_pStructReference(new GLC_StructReference(pRep)) , m_ListOfOccurences() , m_RelativeMatrix() , m_Name(m_pStructReference->name()) , m_pAttributes(NULL) { if (m_pStructReference->hasStructInstance()) { m_pNumberOfInstance= m_pStructReference->firstInstanceHandle()->m_pNumberOfInstance; ++(*m_pNumberOfInstance); } else { m_pNumberOfInstance= new int(1); } // Inform reference that an instance has been created m_pStructReference->structInstanceCreated(this); //qDebug() << "GLC_StructInstance::GLC_StructInstance : " << (*m_pNumberOfInstance) << " " << m_pNumberOfInstance; } // Copy constructor GLC_StructInstance::GLC_StructInstance(const GLC_StructInstance& structInstance) : m_pNumberOfInstance(structInstance.m_pNumberOfInstance) , m_pStructReference(structInstance.m_pStructReference) , m_ListOfOccurences() , m_RelativeMatrix(structInstance.m_RelativeMatrix) , m_Name(structInstance.name()) , m_pAttributes(NULL) { //qDebug() << "Instance Copy constructor"; Q_ASSERT(NULL != m_pStructReference); // Copy attributes if necessary if (NULL != structInstance.m_pAttributes) { m_pAttributes= new GLC_Attributes(*(structInstance.m_pAttributes)); } ++(*m_pNumberOfInstance); // Inform reference that an instance has been created m_pStructReference->structInstanceCreated(this); } // Copy constructor GLC_StructInstance::GLC_StructInstance(GLC_StructInstance* pStructInstance) : m_pNumberOfInstance(pStructInstance->m_pNumberOfInstance) , m_pStructReference(pStructInstance->m_pStructReference) , m_ListOfOccurences() , m_RelativeMatrix(pStructInstance->m_RelativeMatrix) , m_Name(pStructInstance->name()) , m_pAttributes(NULL) { //qDebug() << "Instance Copy constructor"; Q_ASSERT(NULL != m_pStructReference); // Copy attributes if necessary if (NULL != pStructInstance->m_pAttributes) { m_pAttributes= new GLC_Attributes(*(pStructInstance->m_pAttributes)); } ++(*m_pNumberOfInstance); // Inform reference that an instance has been created m_pStructReference->structInstanceCreated(this); } // Create empty instance GLC_StructInstance::GLC_StructInstance(const QString& name) : m_pNumberOfInstance(NULL) , m_pStructReference(NULL) , m_ListOfOccurences() , m_RelativeMatrix() , m_Name(name) , m_pAttributes(NULL) { } // Set the reference of an empty instance void GLC_StructInstance::setReference(GLC_StructReference* pStructReference) { Q_ASSERT(NULL == m_pStructReference); m_pStructReference= pStructReference; if (m_pStructReference->hasStructInstance()) { m_pNumberOfInstance= m_pStructReference->firstInstanceHandle()->m_pNumberOfInstance; ++(*m_pNumberOfInstance); } else { m_pNumberOfInstance= new int(1); } // Inform reference that an instance has been created m_pStructReference->structInstanceCreated(this); if (m_Name.isEmpty()) { m_Name= pStructReference->name(); } //qDebug() << "GLC_StructInstance::GLC_StructInstance : " << (*m_pNumberOfInstance) << " " << m_pNumberOfInstance; } // Destructor GLC_StructInstance::~GLC_StructInstance() { if(m_pNumberOfInstance != NULL) { // Inform reference that an instance has been deleted m_pStructReference->structInstanceDeleted(this); // Update number of instance if ((--(*m_pNumberOfInstance)) == 0) { //qDebug() << "Delete structInstance"; Q_ASSERT(!m_pStructReference->hasStructInstance()); delete m_pStructReference; delete m_pNumberOfInstance; } delete m_pAttributes; } else qDebug() << "GLC_StructInstance::~GLC_StructInstance() of empty instance"; } <commit_msg>Minor change : Add an assertion<commit_after>/**************************************************************************** This file is part of the GLC-lib library. Copyright (C) 2005-2008 Laurent Ribon ([email protected]) Version 2.0.0, packaged on July 2010. http://glc-lib.sourceforge.net GLC-lib 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. GLC-lib 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 GLC-lib; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ //! \file glc_structinstance.cpp implementation of the GLC_StructInstance class. #include "glc_structinstance.h" #include "glc_structreference.h" #include "glc_structoccurence.h" // Default constructor GLC_StructInstance::GLC_StructInstance(GLC_StructReference* pStructReference) : m_pNumberOfInstance(NULL) , m_pStructReference(pStructReference) , m_ListOfOccurences() , m_RelativeMatrix() , m_Name() , m_pAttributes(NULL) { if (NULL == m_pStructReference) { m_pStructReference= new GLC_StructReference(); } m_Name= m_pStructReference->name(); if (m_pStructReference->hasStructInstance()) { m_pNumberOfInstance= m_pStructReference->firstInstanceHandle()->m_pNumberOfInstance; ++(*m_pNumberOfInstance); } else { m_pNumberOfInstance= new int(1); } // Inform reference that an instance has been created m_pStructReference->structInstanceCreated(this); //qDebug() << "GLC_StructInstance::GLC_StructInstance : " << (*m_pNumberOfInstance) << " " << m_pNumberOfInstance; } // Create instance with a rep GLC_StructInstance::GLC_StructInstance(GLC_Rep* pRep) : m_pNumberOfInstance(NULL) , m_pStructReference(new GLC_StructReference(pRep)) , m_ListOfOccurences() , m_RelativeMatrix() , m_Name(m_pStructReference->name()) , m_pAttributes(NULL) { if (m_pStructReference->hasStructInstance()) { m_pNumberOfInstance= m_pStructReference->firstInstanceHandle()->m_pNumberOfInstance; ++(*m_pNumberOfInstance); } else { m_pNumberOfInstance= new int(1); } // Inform reference that an instance has been created m_pStructReference->structInstanceCreated(this); //qDebug() << "GLC_StructInstance::GLC_StructInstance : " << (*m_pNumberOfInstance) << " " << m_pNumberOfInstance; } // Copy constructor GLC_StructInstance::GLC_StructInstance(const GLC_StructInstance& structInstance) : m_pNumberOfInstance(structInstance.m_pNumberOfInstance) , m_pStructReference(structInstance.m_pStructReference) , m_ListOfOccurences() , m_RelativeMatrix(structInstance.m_RelativeMatrix) , m_Name(structInstance.name()) , m_pAttributes(NULL) { //qDebug() << "Instance Copy constructor"; Q_ASSERT(NULL != m_pStructReference); // Copy attributes if necessary if (NULL != structInstance.m_pAttributes) { m_pAttributes= new GLC_Attributes(*(structInstance.m_pAttributes)); } ++(*m_pNumberOfInstance); // Inform reference that an instance has been created m_pStructReference->structInstanceCreated(this); } // Copy constructor GLC_StructInstance::GLC_StructInstance(GLC_StructInstance* pStructInstance) : m_pNumberOfInstance(pStructInstance->m_pNumberOfInstance) , m_pStructReference(pStructInstance->m_pStructReference) , m_ListOfOccurences() , m_RelativeMatrix(pStructInstance->m_RelativeMatrix) , m_Name(pStructInstance->name()) , m_pAttributes(NULL) { //qDebug() << "Instance Copy constructor"; Q_ASSERT(NULL != m_pStructReference); // Copy attributes if necessary if (NULL != pStructInstance->m_pAttributes) { m_pAttributes= new GLC_Attributes(*(pStructInstance->m_pAttributes)); } ++(*m_pNumberOfInstance); // Inform reference that an instance has been created m_pStructReference->structInstanceCreated(this); } // Create empty instance GLC_StructInstance::GLC_StructInstance(const QString& name) : m_pNumberOfInstance(NULL) , m_pStructReference(NULL) , m_ListOfOccurences() , m_RelativeMatrix() , m_Name(name) , m_pAttributes(NULL) { } // Set the reference of an empty instance void GLC_StructInstance::setReference(GLC_StructReference* pStructReference) { Q_ASSERT(NULL == m_pStructReference); Q_ASSERT(NULL == m_pNumberOfInstance); m_pStructReference= pStructReference; if (m_pStructReference->hasStructInstance()) { m_pNumberOfInstance= m_pStructReference->firstInstanceHandle()->m_pNumberOfInstance; ++(*m_pNumberOfInstance); } else { m_pNumberOfInstance= new int(1); } // Inform reference that an instance has been created m_pStructReference->structInstanceCreated(this); if (m_Name.isEmpty()) { m_Name= pStructReference->name(); } //qDebug() << "GLC_StructInstance::GLC_StructInstance : " << (*m_pNumberOfInstance) << " " << m_pNumberOfInstance; } // Destructor GLC_StructInstance::~GLC_StructInstance() { if(m_pNumberOfInstance != NULL) { // Inform reference that an instance has been deleted m_pStructReference->structInstanceDeleted(this); // Update number of instance if ((--(*m_pNumberOfInstance)) == 0) { //qDebug() << "Delete structInstance"; Q_ASSERT(!m_pStructReference->hasStructInstance()); delete m_pStructReference; delete m_pNumberOfInstance; } delete m_pAttributes; } else qDebug() << "GLC_StructInstance::~GLC_StructInstance() of empty instance"; } <|endoftext|>
<commit_before>#include "listaapo.h" #include "arvore.h" #include <iostream> using namespace std; extern int contArvore; extern int contLista; void main() { //lao esterno n = a 100 ate 2000 passo 100 for (int n = 100; n <= 2000; n+=100) { contArvore = 0, contLista = 0; //declara uma lista TipoLista Lista; //Declara uma rvore TipoArvore Arvore; //inicializa a lista Elemento X; // declara X e Item do tipo elemento FLVazia(Lista); // verifica se a lista est vazia //inicializa a arvore Elemento Ax; // declara Ax Inicializa(Arvore); // inicializa a rvore Arvore verificando se esta vazia //lao interno passo de 100 em 100 for (int i = 1; i <= n; i++) { Ax.Valor = rand();// o elemento da rvore recebe um nmero randmico X.Valor = Ax.Valor;// o elemento da lista recebe o mesmo nmero do elemento da rvore Insere(Ax, Arvore);// insere o elemento Ax na rvore Insere(X, Lista);// insere o elemento na X lista } //segundo lao interno para contar os valores da pesquisa for (int i = 1; i < (2 * n); i++) { Ax.Valor = rand();// o elemento da rvore recebe um nmero randmico X.Valor = Ax.Valor;// o elemento da lista recebe o mesmo nmero do elemento da rvore Pesquisa(Ax, Arvore); Localiza(Lista, X.Valor); } double mediaArvore = contArvore / (2.0 * n); double mediaLista = contLista / (2.0 * n); cout << n << "\t" << mediaArvore << "\t" << mediaLista << "\n"; //zera os contadores contArvore = contLista = 0; } system("Pause"); } <commit_msg>Versão Final Sem Grafico<commit_after>#include "listaapo.h" #include "arvore.h" #include <iostream> using namespace std; extern int contArvore; extern int contLista; void main() { //lao esterno n = a 100 ate 2000 passo 100 for (int n = 100; n <= 2000; n+=100) { contArvore = 0, contLista = 0; //declara uma lista TipoLista Lista; //Declara uma rvore TipoArvore Arvore; //inicializa a lista Elemento X; // declara X e Item do tipo elemento FLVazia(Lista); // verifica se a lista est vazia //inicializa a arvore Elemento Ax; // declara Ax Inicializa(Arvore); // inicializa a rvore Arvore verificando se esta vazia //lao interno passo de 100 em 100 for (int i = 1; i <= n; i++) { Ax.Valor = rand();// o elemento da rvore recebe um nmero randmico X.Valor = Ax.Valor;// o elemento da lista recebe o mesmo nmero do elemento da rvore Insere(Ax, Arvore);// insere o elemento Ax na rvore Insere(X, Lista);// insere o elemento na X lista } //segundo lao interno para contar os valores da pesquisa for (int i = 1; i < (2 * n); i++) { Ax.Valor = rand();// o elemento da rvore recebe um nmero randmico X.Valor = Ax.Valor;// o elemento da lista recebe o mesmo nmero do elemento da rvore Pesquisa(Ax, Arvore); Localiza(Lista, X.Valor); } double mediaArvore = contArvore / (2.0 * n); double mediaLista = contLista / (2.0 * n); cout << n << "\t" << mediaArvore << "\t" << mediaLista << "\n"; //zera os contadores contArvore = contLista = 0; } system("Pause"); } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTestingMacros.h" #include "mitkAbstractFileReader.h" #include "mitkIFileReader.h" #include "mitkFileReaderManager.h" #include "mitkGetModuleContext.h" #include "mitkModuleContext.h" #include <mitkBaseData.h> #include <itkProcessObject.h> #include <itkLightObject.h> #include <usServiceProperties.h> #include <MitkExports.h> #include <mitkCommon.h> #include <usGetModuleContext.h> #include <usModule.h> #include <usServiceProperties.h> class DummyReader : public mitk::AbstractFileReader, public itk::LightObject { public: mitkClassMacro(DummyReader, itk::LightObject); itkNewMacro(Self); virtual itk::SmartPointer<mitk::BaseData> Read(const std::string& path = 0) { return 0; } virtual itk::SmartPointer<mitk::BaseData> Read(const std::istream& stream ) { return 0; } virtual void SetOptions(std::list< std::string > options ) { m_Options = options; m_Registration.SetProperties(ConstructServiceProperties());} virtual void Init(std::string extension, int priority) { m_Extension = extension; m_Priority = priority; this->RegisterMicroservice(mitk::GetModuleContext()); } }; // End of internal dummy reader /** * TODO */ int mitkFileReaderManagerTest(int argc , char* argv[]) { // always start with this! MITK_TEST_BEGIN("FileReaderManager"); // mitk::FileReaderManager::Pointer frm = mitk::FileReaderManager::New(); // MITK_TEST_CONDITION_REQUIRED(argc == 2,"Testing FileReaderManager instantiation"); DummyReader* testDR = new DummyReader(); DummyReader* otherDR = new DummyReader(); DummyReader* mediocreTestDR = new DummyReader(); DummyReader* prettyFlyTestDR = new DummyReader(); DummyReader* awesomeTestDR = new DummyReader(); testDR->Init("test",1); otherDR->Init("other",1); MITK_TEST_CONDITION_REQUIRED(testDR->CanRead("/this/is/a/folder/file.test"),"Positive test of default CanRead() implementation"); MITK_TEST_CONDITION_REQUIRED(!testDR->CanRead("/this/is/a/folder/file.tes"),"Negative test of default CanRead() implementation"); mitk::IFileReader* returned = mitk::FileReaderManager::GetReader("test"); MITK_TEST_CONDITION_REQUIRED(testDR == returned,"Testing correct retrieval of FileReader 1/2"); returned = mitk::FileReaderManager::GetReader("other"); MITK_TEST_CONDITION_REQUIRED(otherDR == returned,"Testing correct retrieval of FileReader 2/2"); mediocreTestDR->Init("test",20); prettyFlyTestDR->Init("test",50); awesomeTestDR->Init("test",100); returned = mitk::FileReaderManager::GetReader("test"); MITK_TEST_CONDITION_REQUIRED(awesomeTestDR == returned, "Testing correct priorized retrieval of FileReader: Best reader"); // Now to give those readers some options, then we will try again std::list<std::string> options; options.push_front("isANiceGuy"); mediocreTestDR->SetOptions(options); options.clear(); options.push_front("canFly"); prettyFlyTestDR->SetOptions(options); options.push_front("isAwesome"); awesomeTestDR->SetOptions(options); //note: awesomeReader canFly and isAwesome // Reset Options, use to define what we want the reader to do options.clear(); options.push_front("canFly"); returned = mitk::FileReaderManager::GetReader("test", options); MITK_TEST_CONDITION_REQUIRED(awesomeTestDR == returned, "Testing correct retrieval of FileReader with Options: Best reader with options"); options.push_front("isAwesome"); returned = mitk::FileReaderManager::GetReader("test", options); MITK_TEST_CONDITION_REQUIRED(awesomeTestDR == returned, "Testing correct retrieval of FileReader with multiple Options: Best reader with options"); options.clear(); options.push_front("isANiceGuy"); returned = mitk::FileReaderManager::GetReader("test", options); MITK_TEST_CONDITION_REQUIRED(mediocreTestDR == returned, "Testing correct retrieval of specific FileReader with Options: Low priority reader with specific option"); options.push_front("canFly"); returned = mitk::FileReaderManager::GetReader("test", options); MITK_TEST_CONDITION_REQUIRED(returned == 0, "Testing correct return of 0 value when no matching reader was found"); // Onward to test the retrieval of multiple readers std::list< mitk::IFileReader* > returnedList; returnedList = mitk::FileReaderManager::GetReaders("test", options); MITK_TEST_CONDITION_REQUIRED(returnedList.size() == 0, "Testing correct return of zero readers when no matching reader was found, asking for all compatibles"); options.clear(); options.push_back("canFly"); returnedList = mitk::FileReaderManager::GetReaders("test", options); MITK_TEST_CONDITION_REQUIRED(returnedList.size() == 2, "Testing correct return of two readers when two matching reader was found, asking for all compatibles"); MITK_TEST_CONDITION_REQUIRED(returnedList.front() == awesomeTestDR, "Testing correct priorization of returned Readers with options 1/2"); MITK_TEST_CONDITION_REQUIRED(returnedList.back() == prettyFlyTestDR, "Testing correct priorization of returned Readers with options 2/2"); options.clear(); options.push_back("isAwesome"); returnedList = mitk::FileReaderManager::GetReaders("test", options); MITK_TEST_CONDITION_REQUIRED(returnedList.size() == 1, "Testing correct return of one readers when one matching reader was found, asking for all compatibles"); MITK_TEST_CONDITION_REQUIRED(returnedList.front() == awesomeTestDR, "Testing correctness of result from former query"); // always end with this! MITK_TEST_END(); } <commit_msg>Removed now superficial dummy implementation of read from FileReaderManagerTest<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTestingMacros.h" #include "mitkAbstractFileReader.h" #include "mitkIFileReader.h" #include "mitkFileReaderManager.h" #include "mitkGetModuleContext.h" #include "mitkModuleContext.h" #include <mitkBaseData.h> #include <itkProcessObject.h> #include <itkLightObject.h> #include <usServiceProperties.h> #include <MitkExports.h> #include <mitkCommon.h> #include <usGetModuleContext.h> #include <usModule.h> #include <usServiceProperties.h> class DummyReader : public mitk::AbstractFileReader, public itk::LightObject { public: mitkClassMacro(DummyReader, itk::LightObject); itkNewMacro(Self); virtual itk::SmartPointer<mitk::BaseData> Read(const std::istream& stream ) { return 0; } virtual void SetOptions(std::list< std::string > options ) { m_Options = options; m_Registration.SetProperties(ConstructServiceProperties());} virtual void Init(std::string extension, int priority) { m_Extension = extension; m_Priority = priority; this->RegisterMicroservice(mitk::GetModuleContext()); } }; // End of internal dummy reader /** * TODO */ int mitkFileReaderManagerTest(int argc , char* argv[]) { // always start with this! MITK_TEST_BEGIN("FileReaderManager"); // mitk::FileReaderManager::Pointer frm = mitk::FileReaderManager::New(); // MITK_TEST_CONDITION_REQUIRED(argc == 2,"Testing FileReaderManager instantiation"); DummyReader* testDR = new DummyReader(); DummyReader* otherDR = new DummyReader(); DummyReader* mediocreTestDR = new DummyReader(); DummyReader* prettyFlyTestDR = new DummyReader(); DummyReader* awesomeTestDR = new DummyReader(); testDR->Init("test",1); otherDR->Init("other",1); MITK_TEST_CONDITION_REQUIRED(testDR->CanRead("/this/is/a/folder/file.test"),"Positive test of default CanRead() implementation"); MITK_TEST_CONDITION_REQUIRED(!testDR->CanRead("/this/is/a/folder/file.tes"),"Negative test of default CanRead() implementation"); mitk::IFileReader* returned = mitk::FileReaderManager::GetReader("test"); MITK_TEST_CONDITION_REQUIRED(testDR == returned,"Testing correct retrieval of FileReader 1/2"); returned = mitk::FileReaderManager::GetReader("other"); MITK_TEST_CONDITION_REQUIRED(otherDR == returned,"Testing correct retrieval of FileReader 2/2"); mediocreTestDR->Init("test",20); prettyFlyTestDR->Init("test",50); awesomeTestDR->Init("test",100); returned = mitk::FileReaderManager::GetReader("test"); MITK_TEST_CONDITION_REQUIRED(awesomeTestDR == returned, "Testing correct priorized retrieval of FileReader: Best reader"); // Now to give those readers some options, then we will try again std::list<std::string> options; options.push_front("isANiceGuy"); mediocreTestDR->SetOptions(options); options.clear(); options.push_front("canFly"); prettyFlyTestDR->SetOptions(options); options.push_front("isAwesome"); awesomeTestDR->SetOptions(options); //note: awesomeReader canFly and isAwesome // Reset Options, use to define what we want the reader to do options.clear(); options.push_front("canFly"); returned = mitk::FileReaderManager::GetReader("test", options); MITK_TEST_CONDITION_REQUIRED(awesomeTestDR == returned, "Testing correct retrieval of FileReader with Options: Best reader with options"); options.push_front("isAwesome"); returned = mitk::FileReaderManager::GetReader("test", options); MITK_TEST_CONDITION_REQUIRED(awesomeTestDR == returned, "Testing correct retrieval of FileReader with multiple Options: Best reader with options"); options.clear(); options.push_front("isANiceGuy"); returned = mitk::FileReaderManager::GetReader("test", options); MITK_TEST_CONDITION_REQUIRED(mediocreTestDR == returned, "Testing correct retrieval of specific FileReader with Options: Low priority reader with specific option"); options.push_front("canFly"); returned = mitk::FileReaderManager::GetReader("test", options); MITK_TEST_CONDITION_REQUIRED(returned == 0, "Testing correct return of 0 value when no matching reader was found"); // Onward to test the retrieval of multiple readers std::list< mitk::IFileReader* > returnedList; returnedList = mitk::FileReaderManager::GetReaders("test", options); MITK_TEST_CONDITION_REQUIRED(returnedList.size() == 0, "Testing correct return of zero readers when no matching reader was found, asking for all compatibles"); options.clear(); options.push_back("canFly"); returnedList = mitk::FileReaderManager::GetReaders("test", options); MITK_TEST_CONDITION_REQUIRED(returnedList.size() == 2, "Testing correct return of two readers when two matching reader was found, asking for all compatibles"); MITK_TEST_CONDITION_REQUIRED(returnedList.front() == awesomeTestDR, "Testing correct priorization of returned Readers with options 1/2"); MITK_TEST_CONDITION_REQUIRED(returnedList.back() == prettyFlyTestDR, "Testing correct priorization of returned Readers with options 2/2"); options.clear(); options.push_back("isAwesome"); returnedList = mitk::FileReaderManager::GetReaders("test", options); MITK_TEST_CONDITION_REQUIRED(returnedList.size() == 1, "Testing correct return of one readers when one matching reader was found, asking for all compatibles"); MITK_TEST_CONDITION_REQUIRED(returnedList.front() == awesomeTestDR, "Testing correctness of result from former query"); // always end with this! MITK_TEST_END(); } <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions 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 <memory> #include <string> #include "SurgSim/Framework/Runtime.h" #include "SurgSim/Framework/Scene.h" #include <SurgSim/Blocks/BasicSceneElement.h> #include "SurgSim/Graphics/OsgView.h" #include "SurgSim/Graphics/OsgViewElement.h" #include "SurgSim/Graphics/OsgManager.h" #include "SurgSim/Graphics/OsgSceneryRepresentation.h" /// Create a SceneElement with stapler data load from obj file std::shared_ptr<SurgSim::Framework::SceneElement> loadStapler(const std::string& fileName) { std::shared_ptr<SurgSim::Framework::SceneElement> element = std::make_shared<SurgSim::Blocks::BasicSceneElement>("Stapler"); std::shared_ptr<SurgSim::Graphics::SceneryRepresentation> stapler = std::make_shared<SurgSim::Graphics::OsgSceneryRepresentation>("Stapler"); stapler->setFileName(fileName); element->addComponent(stapler); return element; } /// Create a SceneElement with arm data load from obj file std::shared_ptr<SurgSim::Framework::SceneElement> loadArm(const std::string& fileName) { std::shared_ptr<SurgSim::Framework::SceneElement> element = std::make_shared<SurgSim::Blocks::BasicSceneElement>("Arm"); std::shared_ptr<SurgSim::Graphics::SceneryRepresentation> arm = std::make_shared<SurgSim::Graphics::OsgSceneryRepresentation>("Arm"); arm->setFileName(fileName); element->addComponent(arm); return element; } std::shared_ptr<SurgSim::Graphics::ViewElement> createView() { auto view = std::make_shared<SurgSim::Graphics::OsgViewElement>("StaplingDemoView"); view->enableManipulator(true); view->setManipulatorParameters(SurgSim::Math::Vector3d(0.0, 0.5, 0.5), SurgSim::Math::Vector3d::Zero()); return view; } int main(int argc, char* argv[]) { // Create managers auto graphicsManager = std::make_shared<SurgSim::Graphics::OsgManager>(); auto runtime = std::make_shared<SurgSim::Framework::Runtime>("config.txt"); // Scene will contain all SceneElements in this stapler demo. std::shared_ptr<SurgSim::Framework::Scene> scene = runtime->getScene(); // Load scenery objects into Scene. scene->addSceneElement(loadStapler("stapler_collision.obj")); scene->addSceneElement(loadArm("forearm.osgb")); scene->addSceneElement(createView()); runtime->addManager(graphicsManager); runtime->execute(); return 0; } <commit_msg>CppLint warning fix<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions 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 <memory> #include <string> #include "SurgSim/Framework/Runtime.h" #include "SurgSim/Framework/Scene.h" #include "SurgSim/Blocks/BasicSceneElement.h" #include "SurgSim/Graphics/OsgManager.h" #include "SurgSim/Graphics/OsgSceneryRepresentation.h" #include "SurgSim/Graphics/OsgView.h" #include "SurgSim/Graphics/OsgViewElement.h" /// Create a SceneElement with stapler data load from obj file std::shared_ptr<SurgSim::Framework::SceneElement> loadStapler(const std::string& fileName) { std::shared_ptr<SurgSim::Framework::SceneElement> element = std::make_shared<SurgSim::Blocks::BasicSceneElement>("Stapler"); std::shared_ptr<SurgSim::Graphics::SceneryRepresentation> stapler = std::make_shared<SurgSim::Graphics::OsgSceneryRepresentation>("Stapler"); stapler->setFileName(fileName); element->addComponent(stapler); return element; } /// Create a SceneElement with arm data load from obj file std::shared_ptr<SurgSim::Framework::SceneElement> loadArm(const std::string& fileName) { std::shared_ptr<SurgSim::Framework::SceneElement> element = std::make_shared<SurgSim::Blocks::BasicSceneElement>("Arm"); std::shared_ptr<SurgSim::Graphics::SceneryRepresentation> arm = std::make_shared<SurgSim::Graphics::OsgSceneryRepresentation>("Arm"); arm->setFileName(fileName); element->addComponent(arm); return element; } std::shared_ptr<SurgSim::Graphics::ViewElement> createView() { auto view = std::make_shared<SurgSim::Graphics::OsgViewElement>("StaplingDemoView"); view->enableManipulator(true); view->setManipulatorParameters(SurgSim::Math::Vector3d(0.0, 0.5, 0.5), SurgSim::Math::Vector3d::Zero()); return view; } int main(int argc, char* argv[]) { // Create managers auto graphicsManager = std::make_shared<SurgSim::Graphics::OsgManager>(); auto runtime = std::make_shared<SurgSim::Framework::Runtime>("config.txt"); // Scene will contain all SceneElements in this stapler demo. std::shared_ptr<SurgSim::Framework::Scene> scene = runtime->getScene(); // Load scenery objects into Scene. scene->addSceneElement(loadStapler("stapler_collision.obj")); scene->addSceneElement(loadArm("forearm.osgb")); scene->addSceneElement(createView()); runtime->addManager(graphicsManager); runtime->execute(); return 0; } <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 ETH Zurich ** 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 ETH Zurich 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 "StandardMetaDefinitions.h" #include "ClangHelpers.h" #include "MacroDefinitions.h" #include "MacroExpansion.h" #include "MacroExpansions.h" #include "MacroArgumentInfo.h" #include "MacroArgumentLocation.h" #include "LexicalTransformations.h" #include "NodeToCloneMap.h" #include "NodeHelpers.h" #include "OOModel/src/allOOModelNodes.h" namespace CppImport { StandardMetaDefinitions::StandardMetaDefinitions(const ClangHelpers& clang, const MacroDefinitions& definitionManager, MacroExpansions& macroExpansions, const LexicalTransformations& lexicalHelper) : clang_(clang), definitionManager_(definitionManager), macroExpansions_(macroExpansions), lexicalTransformations_(lexicalHelper) {} OOModel::MetaDefinition* StandardMetaDefinitions::createMetaDef(const clang::MacroDirective* md) { if (metaDefinition(md)) return nullptr; auto metaDef = new OOModel::MetaDefinition(definitionManager_.definitionName(md)); standardMetaDefinitions_.insert(definitionManager_.signature(md), metaDef); // add formal arguments based on the expansion definition for (auto argName : clang_.argumentNames(md)) metaDef->arguments()->append(new OOModel::FormalMetaArgument(argName)); return metaDef; } OOModel::MetaDefinition* StandardMetaDefinitions::metaDefinition(const clang::MacroDirective* md) { QString h = definitionManager_.signature(md); auto it = standardMetaDefinitions_.find(h); return it != standardMetaDefinitions_.end() ? *it : nullptr; } void StandardMetaDefinitions::createMetaDefinitionBody(OOModel::MetaDefinition* metaDef, QVector<Model::Node*> nodes, MacroExpansion* expansion, NodeToCloneMap& mapping, QVector<MacroArgumentInfo>& arguments) { if (nodes.size() > 0) { // create a new context with type equal to the first node's context auto actualContext = NodeHelpers::actualContext(mapping.original(nodes.first())); metaDef->setContext(NodeHelpers::createContext(actualContext)); // clone and add nodes to the metaDef for (auto n : nodes) { NodeToCloneMap childMapping; auto cloned = NodeHelpers::cloneWithMapping(mapping.original(n), childMapping); applyLexicalTransformations(cloned, childMapping, clang_.argumentNames(expansion->definition())); insertChildMetaCalls(expansion, childMapping); if (removeUnownedNodes(cloned, expansion, childMapping)) continue; insertArgumentSplices(mapping, childMapping, arguments); NodeHelpers::addNodeToDeclaration(cloned, metaDef->context()); } } // add all child expansion meta calls that are not yet added anywhere else as declaration meta calls for (auto childExpansion : expansion->children()) if (!childExpansion->metaCall()->parent()) metaDef->context()->metaCalls()->append(childExpansion->metaCall()); } void StandardMetaDefinitions::insertChildMetaCalls(MacroExpansion* expansion, NodeToCloneMap& childMapping) { for (auto childExpansion : expansion->children()) { // do not handle xMacro children here if (childExpansion->xMacroParent()) continue; // retrieve the node that the child meta call should replace if (auto replacementNode = childExpansion->replacementNode()) // replacementNode is an original node therefore we need to get to the cloned domain first // clonedReplacementNode represents the cloned version of replacementNode if (auto clonedReplacementNode = childMapping.clone(replacementNode)) if (!DCast<OOModel::Declaration>(clonedReplacementNode)) { if (clonedReplacementNode->parent()) clonedReplacementNode->parent()->replaceChild(clonedReplacementNode, childExpansion->metaCall()); else qDebug() << "not inserted metacall" << clonedReplacementNode->typeName(); } } } void StandardMetaDefinitions::childrenUnownedByExpansion(Model::Node* node, MacroExpansion* expansion, NodeToCloneMap& mapping, QVector<Model::Node*>& result) { Q_ASSERT(expansion); // do not remove child meta calls if (DCast<OOModel::MetaCallExpression>(node)) return; if (auto original = mapping.original(node)) if (macroExpansions_.expansions(original).contains(expansion)) { for (auto child : node->children()) childrenUnownedByExpansion(child, expansion, mapping, result); return; } result.append(node); } bool StandardMetaDefinitions::removeUnownedNodes(Model::Node* cloned, MacroExpansion* expansion, NodeToCloneMap& mapping) { QVector<Model::Node*> unownedNodes; childrenUnownedByExpansion(cloned, expansion, mapping, unownedNodes); // if the unowned nodes contain the node itself then the node should not even be added to the meta definition if (unownedNodes.contains(cloned)) return true; NodeHelpers::removeNodesFromParent(NodeHelpers::topLevelNodes(unownedNodes)); return false; } void StandardMetaDefinitions::insertArgumentSplices(NodeToCloneMap& mapping, NodeToCloneMap& childMapping, QVector<MacroArgumentInfo>& arguments) { for (auto argument : arguments) { // map the argument node to the corresponding node in childMapping auto original = mapping.original(argument.node_); if (auto child = childMapping.clone(original)) { // the first entry of the spelling history is where the splice for this argument should be auto spliceLoc = argument.history_.first(); // the splice name is equal to the formal argument name where the argument is coming from auto argName = clang_.argumentNames(spliceLoc.expansion_->definition()).at(spliceLoc.argumentNumber_); auto newNode = new OOModel::ReferenceExpression(argName); // insert the splice into the tree if (child->parent()) child->parent()->replaceChild(child, newNode); childMapping.replaceClone(child, newNode); } } } void StandardMetaDefinitions::applyLexicalTransformations(Model::Node* node, NodeToCloneMap& mapping, QVector<QString> formalArgs) const { auto transformed = lexicalTransformations_.transformation(mapping.original(node)); if (!transformed.isEmpty()) { bool containsArg = false; for (auto arg : formalArgs) if (transformed.contains(arg)) { containsArg = true; break; } if (containsArg) { if (auto ref = DCast<OOModel::ReferenceExpression>(node)) ref->setName(transformed); else if (auto decl = DCast<OOModel::Class>(node)) decl->setName(transformed); else if (auto decl = DCast<OOModel::Method>(node)) decl->setName(transformed); else if (auto decl = DCast<OOModel::VariableDeclaration>(node)) decl->setName(transformed); else if (auto strLit = DCast<OOModel::StringLiteral>(node)) strLit->setValue(transformed); else if (auto formalResult = DCast<OOModel::FormalResult>(node)) formalResult->setTypeExpression(NodeHelpers::createNameExpressionFromString(transformed)); else if (auto boolLit = DCast<OOModel::BooleanLiteral>(node)) replaceWithReference(boolLit, transformed, mapping); else if (auto castExpr = DCast<OOModel::CastExpression>(node)) castExpr->setType(new OOModel::ReferenceExpression(transformed)); else if (auto castExpr = DCast<OOModel::PointerTypeExpression>(node)) replaceWithReference(castExpr, transformed, mapping); else if (auto methodCall = DCast<OOModel::MethodCallExpression>(node)) { if (auto ref = DCast<OOModel::ReferenceExpression>(methodCall->callee())) { if (transformed.startsWith("#")) replaceWithReference(methodCall, transformed, mapping); else replaceWithReference(ref, transformed, mapping); } else qDebug() << "Unhandled transformed node type" << node->typeName() << "transformed" << transformed; } else if (auto templateInst = DCast<OOModel::ExplicitTemplateInstantiation>(node)) { QRegularExpression regEx("((\\w+::)?\\w+<(\\w+::)?\\w+>)$"); auto m = regEx.match(transformed); if (m.hasMatch()) replaceWithReference(templateInst->instantiatedClass(), m.captured(1), mapping); else qDebug() << "could not correct explicit template instantiation: " << transformed; } else qDebug() << "Unhandled transformed node type" << node->typeName() << "transformed" << transformed; } } for (auto child : node->children()) applyLexicalTransformations(child, mapping, formalArgs); } void StandardMetaDefinitions::replaceWithReference(Model::Node* current, const QString& replacement, NodeToCloneMap& mapping) const { auto newValue = NodeHelpers::createNameExpressionFromString(replacement); current->parent()->replaceChild(current, newValue); mapping.replaceClone(current, newValue); } } <commit_msg>fix wrong placed meta call<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 ETH Zurich ** 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 ETH Zurich 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 "StandardMetaDefinitions.h" #include "ClangHelpers.h" #include "MacroDefinitions.h" #include "MacroExpansion.h" #include "MacroExpansions.h" #include "MacroArgumentInfo.h" #include "MacroArgumentLocation.h" #include "LexicalTransformations.h" #include "NodeToCloneMap.h" #include "NodeHelpers.h" #include "OOModel/src/allOOModelNodes.h" namespace CppImport { StandardMetaDefinitions::StandardMetaDefinitions(const ClangHelpers& clang, const MacroDefinitions& definitionManager, MacroExpansions& macroExpansions, const LexicalTransformations& lexicalHelper) : clang_(clang), definitionManager_(definitionManager), macroExpansions_(macroExpansions), lexicalTransformations_(lexicalHelper) {} OOModel::MetaDefinition* StandardMetaDefinitions::createMetaDef(const clang::MacroDirective* md) { if (metaDefinition(md)) return nullptr; auto metaDef = new OOModel::MetaDefinition(definitionManager_.definitionName(md)); standardMetaDefinitions_.insert(definitionManager_.signature(md), metaDef); // add formal arguments based on the expansion definition for (auto argName : clang_.argumentNames(md)) metaDef->arguments()->append(new OOModel::FormalMetaArgument(argName)); return metaDef; } OOModel::MetaDefinition* StandardMetaDefinitions::metaDefinition(const clang::MacroDirective* md) { QString h = definitionManager_.signature(md); auto it = standardMetaDefinitions_.find(h); return it != standardMetaDefinitions_.end() ? *it : nullptr; } void StandardMetaDefinitions::createMetaDefinitionBody(OOModel::MetaDefinition* metaDef, QVector<Model::Node*> nodes, MacroExpansion* expansion, NodeToCloneMap& mapping, QVector<MacroArgumentInfo>& arguments) { if (nodes.size() > 0) { // create a new context with type equal to the first node's context auto actualContext = NodeHelpers::actualContext(mapping.original(nodes.first())); metaDef->setContext(NodeHelpers::createContext(actualContext)); // clone and add nodes to the metaDef for (auto n : nodes) { NodeToCloneMap childMapping; auto cloned = NodeHelpers::cloneWithMapping(mapping.original(n), childMapping); applyLexicalTransformations(cloned, childMapping, clang_.argumentNames(expansion->definition())); insertChildMetaCalls(expansion, childMapping); if (removeUnownedNodes(cloned, expansion, childMapping)) continue; insertArgumentSplices(mapping, childMapping, arguments); NodeHelpers::addNodeToDeclaration(cloned, metaDef->context()); } } // add all child expansion meta calls that are not yet added anywhere else as declaration meta calls for (auto childExpansion : expansion->children()) if (!childExpansion->metaCall()->parent()) metaDef->context()->metaCalls()->append(childExpansion->metaCall()); } void StandardMetaDefinitions::insertChildMetaCalls(MacroExpansion* expansion, NodeToCloneMap& childMapping) { for (auto childExpansion : expansion->children()) { // do not handle xMacro children here if (childExpansion->xMacroParent()) continue; // retrieve the node that the child meta call should replace if (auto replacementNode = childExpansion->replacementNode()) // replacementNode is an original node therefore we need to get to the cloned domain first // clonedReplacementNode represents the cloned version of replacementNode if (auto clonedReplacementNode = childMapping.clone(replacementNode)) { if (DCast<OOModel::VariableDeclaration>(clonedReplacementNode)) { if (clonedReplacementNode->parent()->parent()) clonedReplacementNode->parent()->parent() ->replaceChild(clonedReplacementNode->parent(), childExpansion->metaCall()); else qDebug() << "not inserted metacall" << clonedReplacementNode->typeName(); } else if (!DCast<OOModel::Declaration>(clonedReplacementNode)) { if (clonedReplacementNode->parent()) clonedReplacementNode->parent()->replaceChild(clonedReplacementNode, childExpansion->metaCall()); else qDebug() << "not inserted metacall" << clonedReplacementNode->typeName(); } } } } void StandardMetaDefinitions::childrenUnownedByExpansion(Model::Node* node, MacroExpansion* expansion, NodeToCloneMap& mapping, QVector<Model::Node*>& result) { Q_ASSERT(expansion); // do not remove child meta calls if (DCast<OOModel::MetaCallExpression>(node)) return; if (auto original = mapping.original(node)) if (macroExpansions_.expansions(original).contains(expansion)) { for (auto child : node->children()) childrenUnownedByExpansion(child, expansion, mapping, result); return; } result.append(node); } bool StandardMetaDefinitions::removeUnownedNodes(Model::Node* cloned, MacroExpansion* expansion, NodeToCloneMap& mapping) { QVector<Model::Node*> unownedNodes; childrenUnownedByExpansion(cloned, expansion, mapping, unownedNodes); // if the unowned nodes contain the node itself then the node should not even be added to the meta definition if (unownedNodes.contains(cloned)) return true; NodeHelpers::removeNodesFromParent(NodeHelpers::topLevelNodes(unownedNodes)); return false; } void StandardMetaDefinitions::insertArgumentSplices(NodeToCloneMap& mapping, NodeToCloneMap& childMapping, QVector<MacroArgumentInfo>& arguments) { for (auto argument : arguments) { // map the argument node to the corresponding node in childMapping auto original = mapping.original(argument.node_); if (auto child = childMapping.clone(original)) { // the first entry of the spelling history is where the splice for this argument should be auto spliceLoc = argument.history_.first(); // the splice name is equal to the formal argument name where the argument is coming from auto argName = clang_.argumentNames(spliceLoc.expansion_->definition()).at(spliceLoc.argumentNumber_); auto newNode = new OOModel::ReferenceExpression(argName); // insert the splice into the tree if (child->parent()) child->parent()->replaceChild(child, newNode); childMapping.replaceClone(child, newNode); } } } void StandardMetaDefinitions::applyLexicalTransformations(Model::Node* node, NodeToCloneMap& mapping, QVector<QString> formalArgs) const { auto transformed = lexicalTransformations_.transformation(mapping.original(node)); if (!transformed.isEmpty()) { bool containsArg = false; for (auto arg : formalArgs) if (transformed.contains(arg)) { containsArg = true; break; } if (containsArg) { if (auto ref = DCast<OOModel::ReferenceExpression>(node)) ref->setName(transformed); else if (auto decl = DCast<OOModel::Class>(node)) decl->setName(transformed); else if (auto decl = DCast<OOModel::Method>(node)) decl->setName(transformed); else if (auto decl = DCast<OOModel::VariableDeclaration>(node)) decl->setName(transformed); else if (auto strLit = DCast<OOModel::StringLiteral>(node)) strLit->setValue(transformed); else if (auto formalResult = DCast<OOModel::FormalResult>(node)) formalResult->setTypeExpression(NodeHelpers::createNameExpressionFromString(transformed)); else if (auto boolLit = DCast<OOModel::BooleanLiteral>(node)) replaceWithReference(boolLit, transformed, mapping); else if (auto castExpr = DCast<OOModel::CastExpression>(node)) castExpr->setType(new OOModel::ReferenceExpression(transformed)); else if (auto castExpr = DCast<OOModel::PointerTypeExpression>(node)) replaceWithReference(castExpr, transformed, mapping); else if (auto methodCall = DCast<OOModel::MethodCallExpression>(node)) { if (auto ref = DCast<OOModel::ReferenceExpression>(methodCall->callee())) { if (transformed.startsWith("#")) replaceWithReference(methodCall, transformed, mapping); else replaceWithReference(ref, transformed, mapping); } else qDebug() << "Unhandled transformed node type" << node->typeName() << "transformed" << transformed; } else if (auto templateInst = DCast<OOModel::ExplicitTemplateInstantiation>(node)) { QRegularExpression regEx("((\\w+::)?\\w+<(\\w+::)?\\w+>)$"); auto m = regEx.match(transformed); if (m.hasMatch()) replaceWithReference(templateInst->instantiatedClass(), m.captured(1), mapping); else qDebug() << "could not correct explicit template instantiation: " << transformed; } else qDebug() << "Unhandled transformed node type" << node->typeName() << "transformed" << transformed; } } for (auto child : node->children()) applyLexicalTransformations(child, mapping, formalArgs); } void StandardMetaDefinitions::replaceWithReference(Model::Node* current, const QString& replacement, NodeToCloneMap& mapping) const { auto newValue = NodeHelpers::createNameExpressionFromString(replacement); current->parent()->replaceChild(current, newValue); mapping.replaceClone(current, newValue); } } <|endoftext|>
<commit_before>#include "Application.hh" #include <cstdlib> #include <ctime> #include <G4UImanager.hh> #include <G4UIterminal.hh> #include <G4UIsession.hh> #ifdef G4VIS_USE #include <G4VisExecutive.hh> #endif #ifdef G4UI_USE_QT #include <G4UIQt.hh> // #include <QtGui/QMainWindow> #else #include <G4UItcsh.hh> #endif #include "ComponentManager.hh" #include "ComponentRegistry.hh" #include "PluginLoader.hh" #include "ApplicationMessenger.hh" #include "RunManager.hh" using namespace std; using namespace g4::util; namespace g4 { Application::Application(int argc, char** argv) { Initialize(argc, argv); } Application::Application() { // TODO: Change to exception of a lower severity. G4cerr << "Warning: G4Application created without argc/argv!" << G4endl; Initialize(0, 0); } void Application::Initialize(int argc, char** argv) { _argc = argc; _argv = argv; _interactiveSession = 0; _componentManager = new ComponentManager(); _componentRegistry = &ComponentRegistry::Instance(); _messenger = new ApplicationMessenger(this); // Custom run manager _runManager = new RunManager(*_componentManager); // Plugin-loading system _pluginLoader = new PluginLoader(_componentManager); // Visualization #ifdef G4VIS_USE _visManager = new G4VisExecutive; _visManager->Initialize(); #endif } void Application::PrepareInteractiveMode() { #ifdef G4UI_USE_QT _interactiveSession = new G4UIQt(_argc, _argv); // There are no arguments but nevermind. #else #ifdef G4UI_USE_TCSH _interactiveSession = new G4UIterminal(new G4UItcsh); #else _interactiveSession = new G4UIterminal(); #endif #endif } Application::~Application() { // Visualization #ifdef G4VIS_USE delete _visManager; #endif // delete _componentManager; // delete _messenger; // delete _uiDirectory; delete _runManager; // delete _pluginLoader; } void Application::CreateInstance(int argc, char **argv) { if (instanceExists<Application>()) { G4Exception("G4Application", "DuplicateInstance", FatalException, "Cannot create second instance of G4Application." ); } new Application(argc, argv); } void Application::EnterInteractiveMode() { if (!_interactiveSession) { PrepareInteractiveMode(); } _interactiveSession->SessionStart(); } void Application::PauseExecution() { G4cout << "Press ENTER to continue..." << endl; G4cin.get(); } void Application::RunUI() { G4UImanager * UI = G4UImanager::GetUIpointer(); if (_argc != 1) // batch mode { // *** BATCH RUN (even more files) // Whatever commands - they are applied HERE G4String command = "/control/execute "; for (int macro = 1; macro < _argc; macro++) { G4String fileName = _argv[macro]; G4cout << "Executing macro file: " << fileName << endl; UI->ApplyCommand(command+fileName); } // G4RunManager::GetRunManager()->RunInitialization(); } else { G4cout << "No macro specified, entering interactive mode." << endl; EnterInteractiveMode(); } G4cout << "Closing application..." << endl; } void Application::GenerateRandomSeed() { /* initialize random seed: */ srand ( time(NULL) ); int seed = rand(); CLHEP::HepRandom::setTheSeed( seed ); G4cout << "New random seed has been set: " << seed << G4endl; } void Application::ApplyCommand(const string& command) { G4UImanager * UI = G4UImanager::GetUIpointer(); UI->ApplyCommand(command); } void Application::AddBuiltinComponent(const G4String& name) { Component* component = _componentRegistry->GetComponent(name); _componentManager->AddComponent(component); G4cout << "Loaded built-in component " << name << "." << G4endl; } } <commit_msg>Exception if component does not exist.<commit_after>#include "Application.hh" #include <cstdlib> #include <ctime> #include <G4UImanager.hh> #include <G4UIterminal.hh> #include <G4UIsession.hh> #ifdef G4VIS_USE #include <G4VisExecutive.hh> #endif #ifdef G4UI_USE_QT #include <G4UIQt.hh> // #include <QtGui/QMainWindow> #else #include <G4UItcsh.hh> #endif #include "ComponentManager.hh" #include "ComponentRegistry.hh" #include "PluginLoader.hh" #include "ApplicationMessenger.hh" #include "RunManager.hh" using namespace std; using namespace g4::util; namespace g4 { Application::Application(int argc, char** argv) { Initialize(argc, argv); } Application::Application() { // TODO: Change to exception of a lower severity. G4cerr << "Warning: G4Application created without argc/argv!" << G4endl; Initialize(0, 0); } void Application::Initialize(int argc, char** argv) { _argc = argc; _argv = argv; _interactiveSession = 0; _componentManager = new ComponentManager(); _componentRegistry = &ComponentRegistry::Instance(); _messenger = new ApplicationMessenger(this); // Custom run manager _runManager = new RunManager(*_componentManager); // Plugin-loading system _pluginLoader = new PluginLoader(_componentManager); // Visualization #ifdef G4VIS_USE _visManager = new G4VisExecutive; _visManager->Initialize(); #endif } void Application::PrepareInteractiveMode() { #ifdef G4UI_USE_QT _interactiveSession = new G4UIQt(_argc, _argv); // There are no arguments but nevermind. #else #ifdef G4UI_USE_TCSH _interactiveSession = new G4UIterminal(new G4UItcsh); #else _interactiveSession = new G4UIterminal(); #endif #endif } Application::~Application() { // Visualization #ifdef G4VIS_USE delete _visManager; #endif // delete _componentManager; // delete _messenger; // delete _uiDirectory; delete _runManager; // delete _pluginLoader; } void Application::CreateInstance(int argc, char **argv) { if (instanceExists<Application>()) { G4Exception("G4Application", "DuplicateInstance", FatalException, "Cannot create second instance of G4Application." ); } new Application(argc, argv); } void Application::EnterInteractiveMode() { if (!_interactiveSession) { PrepareInteractiveMode(); } _interactiveSession->SessionStart(); } void Application::PauseExecution() { G4cout << "Press ENTER to continue..." << endl; G4cin.get(); } void Application::RunUI() { G4UImanager * UI = G4UImanager::GetUIpointer(); if (_argc != 1) // batch mode { // *** BATCH RUN (even more files) // Whatever commands - they are applied HERE G4String command = "/control/execute "; for (int macro = 1; macro < _argc; macro++) { G4String fileName = _argv[macro]; G4cout << "Executing macro file: " << fileName << endl; UI->ApplyCommand(command+fileName); } // G4RunManager::GetRunManager()->RunInitialization(); } else { G4cout << "No macro specified, entering interactive mode." << endl; EnterInteractiveMode(); } G4cout << "Closing application..." << endl; } void Application::GenerateRandomSeed() { /* initialize random seed: */ srand ( time(NULL) ); int seed = rand(); CLHEP::HepRandom::setTheSeed( seed ); G4cout << "New random seed has been set: " << seed << G4endl; } void Application::ApplyCommand(const string& command) { G4UImanager * UI = G4UImanager::GetUIpointer(); UI->ApplyCommand(command); } void Application::AddBuiltinComponent(const G4String& name) { Component* component = _componentRegistry->GetComponent(name); if (!component) { G4ExceptionDescription message; message << "Component " << name << " does not exist."; G4Exception("Application", "UnknownComponent", FatalException, message); } _componentManager->AddComponent(component); G4cout << "Loaded built-in component " << name << "." << G4endl; } } <|endoftext|>
<commit_before>/* This file is part of cphVB and copyright (c) 2012 the cphVB team: http://cphvb.bitbucket.org cphVB 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. cphVB 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 Lesser General Public License along with cphVB. If not, see <http://www.gnu.org/licenses/>. */ #include <cphvb.h> #include <cphvb_compute.h> //This function protects against arrays that have superfluos dimensions, // which could negatively affect computation speed void cphvb_compact_dimensions(cphvb_tstate* state) { cphvb_index i, j; //As long as the inner dimension has length == 1, we can safely ignore it while(state->ndim > 1 && (state->shape[state->ndim - 1] == 1 || state->shape[state->ndim - 1] == 0)) state->ndim--; //We can also remove dimensions inside the seqence for(i = state->ndim-2; i >= 0; i--) { if (state->shape[i] == 1 || state->shape[i] == 0) { state->ndim--; memcpy(&state->shape[i], &state->shape[i+1], (state->ndim - i) * sizeof(cphvb_index)); for(j = 0; j < state->noperands; j++) memcpy(&state->stride[j][i], &state->stride[j][i+1], (state->ndim - i) * sizeof(cphvb_index)); } } } void cphvb_tstate_reset( cphvb_tstate *state, cphvb_instruction *instr ) { // As all arrays have the same dimensions, we keep a single shared shape cphvb_index i, blocksize; state->ndim = instr->operand[0]->ndim; state->noperands = cphvb_operands(instr->opcode); blocksize = state->ndim * sizeof(cphvb_index); memcpy(state->shape, instr->operand[0]->shape, blocksize); for(i = 0; i < state->noperands; i++) { if (!cphvb_is_constant(instr->operand[i])) { memcpy(state->stride[i], instr->operand[i]->stride, blocksize); state->start[i] = instr->operand[i]->start; } } cphvb_compact_dimensions(state); } /** * Execute an instruction using the optimization traversal. * * @param instr Instruction to execute. * @return Status of execution */ cphvb_error cphvb_compute_apply( cphvb_instruction *instr ) { cphvb_computeloop comp = cphvb_compute_get( instr ); cphvb_tstate state; cphvb_tstate_reset( &state, instr ); if (comp == NULL) { return CPHVB_TYPE_NOT_SUPPORTED; } else { return comp( instr, &state ); } } <commit_msg>fixed BUG where memcpy() was used for overlapping dst and src. Now using memmove()<commit_after>/* This file is part of cphVB and copyright (c) 2012 the cphVB team: http://cphvb.bitbucket.org cphVB 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. cphVB 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 Lesser General Public License along with cphVB. If not, see <http://www.gnu.org/licenses/>. */ #include <cphvb.h> #include <cphvb_compute.h> //This function protects against arrays that have superfluos dimensions, // which could negatively affect computation speed void cphvb_compact_dimensions(cphvb_tstate* state) { cphvb_index i, j; //As long as the inner dimension has length == 1, we can safely ignore it while(state->ndim > 1 && (state->shape[state->ndim - 1] == 1 || state->shape[state->ndim - 1] == 0)) state->ndim--; //We can also remove dimensions inside the seqence for(i = state->ndim-2; i >= 0; i--) { if (state->shape[i] == 1 || state->shape[i] == 0) { state->ndim--; memmove(&state->shape[i], &state->shape[i+1], (state->ndim - i) * sizeof(cphvb_index)); for(j = 0; j < state->noperands; j++) memmove(&state->stride[j][i], &state->stride[j][i+1], (state->ndim - i) * sizeof(cphvb_index)); } } } void cphvb_tstate_reset( cphvb_tstate *state, cphvb_instruction *instr ) { // As all arrays have the same dimensions, we keep a single shared shape cphvb_index i, blocksize; state->ndim = instr->operand[0]->ndim; state->noperands = cphvb_operands(instr->opcode); blocksize = state->ndim * sizeof(cphvb_index); memcpy(state->shape, instr->operand[0]->shape, blocksize); for(i = 0; i < state->noperands; i++) { if (!cphvb_is_constant(instr->operand[i])) { memcpy(state->stride[i], instr->operand[i]->stride, blocksize); state->start[i] = instr->operand[i]->start; } } cphvb_compact_dimensions(state); } /** * Execute an instruction using the optimization traversal. * * @param instr Instruction to execute. * @return Status of execution */ cphvb_error cphvb_compute_apply( cphvb_instruction *instr ) { cphvb_computeloop comp = cphvb_compute_get( instr ); cphvb_tstate state; cphvb_tstate_reset( &state, instr ); if (comp == NULL) { return CPHVB_TYPE_NOT_SUPPORTED; } else { return comp( instr, &state ); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: fusearch.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2003-03-27 10:57:51 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #define ITEMID_SEARCH SID_SEARCH_ITEM #include <svx/svxids.hrc> #include <svx/srchitem.hxx> #include <svx/srchdlg.hxx> #ifndef _SFX_BINDINGS_HXX //autogen #include <sfx2/bindings.hxx> #endif #include "fupoor.hxx" #include "fusearch.hxx" #include "fuspell.hxx" // wegen SidArraySpell[] #include "sdwindow.hxx" #include "drawdoc.hxx" #include "app.hrc" #include "app.hxx" #include "sdview.hxx" #include "sdoutl.hxx" #include "drviewsh.hxx" #include "outlnvsh.hxx" class SdViewShell; class SfxRequest; TYPEINIT1( FuSearch, FuPoor ); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuSearch::FuSearch( SdViewShell* pViewSh, SdWindow* pWin, SdView* pView, SdDrawDocument* pDoc, SfxRequest& rReq ) : FuPoor(pViewSh, pWin, pView, pDoc, rReq), pSdOutliner(NULL), bOwnOutliner(FALSE) { pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArraySpell ); if ( pViewShell->ISA(SdDrawViewShell) ) { bOwnOutliner = TRUE; pSdOutliner = new SdOutliner( pDoc, OUTLINERMODE_TEXTOBJECT ); } else if ( pViewShell->ISA(SdOutlineViewShell) ) { bOwnOutliner = FALSE; pSdOutliner = pDoc->GetOutliner(); } if (pSdOutliner) pSdOutliner->PrepareSpelling(); } /************************************************************************* |* |* Destruktor |* \************************************************************************/ FuSearch::~FuSearch() { if ( ! pDocSh->IsInDestruction()) pDocSh->GetViewShell()->GetViewFrame()->GetBindings().Invalidate( SidArraySpell ); if (pSdOutliner) pSdOutliner->EndSpelling(); if (bOwnOutliner) delete pSdOutliner; } /************************************************************************* |* |* Suchen&Ersetzen |* \************************************************************************/ void FuSearch::SearchAndReplace( const SvxSearchItem* pSearchItem ) { pViewShell = PTR_CAST( SdViewShell, SfxViewShell::Current() ); if( pViewShell ) { if ( pSdOutliner && pViewShell->ISA(SdDrawViewShell) && !bOwnOutliner ) { pSdOutliner->EndSpelling(); bOwnOutliner = TRUE; pSdOutliner = new SdOutliner( pDoc, OUTLINERMODE_TEXTOBJECT ); pSdOutliner->PrepareSpelling(); } else if ( pSdOutliner && pViewShell->ISA(SdOutlineViewShell) && bOwnOutliner ) { pSdOutliner->EndSpelling(); delete pSdOutliner; bOwnOutliner = FALSE; pSdOutliner = pDoc->GetOutliner(); pSdOutliner->PrepareSpelling(); } if (pSdOutliner) { BOOL bEndSpelling = pSdOutliner->StartSearchAndReplace(pSearchItem); if (bEndSpelling) { pSdOutliner->EndSpelling(); pSdOutliner->PrepareSpelling(); } } } } <commit_msg>INTEGRATION: CWS impress1 (1.4.128); FILE MERGED 2003/10/06 08:18:22 af 1.4.128.2: #111996# Adapted Outliner to new view shell architecture. 2003/09/17 09:02:28 af 1.4.128.1: #111996# Transition to stacked sub-shells. Introduction of namespace sd.<commit_after>/************************************************************************* * * $RCSfile: fusearch.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2004-01-20 11:12:08 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #include "fusearch.hxx" #define ITEMID_SEARCH SID_SEARCH_ITEM #include <svx/svxids.hrc> #include <svx/srchitem.hxx> #include <svx/srchdlg.hxx> #ifndef _SFX_BINDINGS_HXX //autogen #include <sfx2/bindings.hxx> #endif #ifndef SD_FU_POOR_HXX #include "fupoor.hxx" #endif #ifndef SD_FU_SPELL_HXX #include "fuspell.hxx" // wegen SidArraySpell[] #endif #ifndef SD_WINDOW_SHELL_HXX #include "Window.hxx" #endif #include "drawdoc.hxx" #include "app.hrc" #include "app.hxx" #ifndef SD_VIEW_HXX #include "View.hxx" #endif #ifndef SD_OUTLINER_HXX #include "Outliner.hxx" #endif #ifndef SD_DRAW_VIEW_SHELL_HXX #include "DrawViewShell.hxx" #endif #ifndef SD_OUTLINE_VIEW_SHELL_HXX #include "OutlineViewShell.hxx" #endif #ifndef SD_VIEW_SHELL_BASE_HXX #include "ViewShellBase.hxx" #endif class SfxRequest; namespace sd { TYPEINIT1( FuSearch, FuPoor ); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuSearch::FuSearch ( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq ) : FuPoor(pViewSh, pWin, pView, pDoc, rReq), pSdOutliner(NULL), bOwnOutliner(FALSE) { pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArraySpell ); if ( pViewShell->ISA(DrawViewShell) ) { bOwnOutliner = TRUE; pSdOutliner = new ::sd::Outliner( pDoc, OUTLINERMODE_TEXTOBJECT ); } else if ( pViewShell->ISA(OutlineViewShell) ) { bOwnOutliner = FALSE; pSdOutliner = pDoc->GetOutliner(); } if (pSdOutliner) pSdOutliner->PrepareSpelling(); } /************************************************************************* |* |* Destruktor |* \************************************************************************/ FuSearch::~FuSearch() { if ( ! pDocSh->IsInDestruction()) pDocSh->GetViewShell()->GetViewFrame()->GetBindings().Invalidate( SidArraySpell ); if (pSdOutliner) pSdOutliner->EndSpelling(); if (bOwnOutliner) delete pSdOutliner; } /************************************************************************* |* |* Suchen&Ersetzen |* \************************************************************************/ void FuSearch::SearchAndReplace( const SvxSearchItem* pSearchItem ) { ViewShellBase* pBase = PTR_CAST(ViewShellBase, SfxViewShell::Current()); ViewShell* pViewShell = NULL; if (pBase != NULL) pViewShell = pBase->GetSubShellManager().GetMainSubShell(); if (pViewShell != NULL) { if ( pSdOutliner && pViewShell->ISA(DrawViewShell) && !bOwnOutliner ) { pSdOutliner->EndSpelling(); bOwnOutliner = TRUE; pSdOutliner = new ::sd::Outliner( pDoc, OUTLINERMODE_TEXTOBJECT ); pSdOutliner->PrepareSpelling(); } else if ( pSdOutliner && pViewShell->ISA(OutlineViewShell) && bOwnOutliner ) { pSdOutliner->EndSpelling(); delete pSdOutliner; bOwnOutliner = FALSE; pSdOutliner = pDoc->GetOutliner(); pSdOutliner->PrepareSpelling(); } if (pSdOutliner) { BOOL bEndSpelling = pSdOutliner->StartSearchAndReplace(pSearchItem); if (bEndSpelling) { pSdOutliner->EndSpelling(); pSdOutliner->PrepareSpelling(); } } } } } // end of namespace sd <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2009 Werner Mayer <wmayer[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * 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 "PreCompiled.h" #ifndef _PreComp_ # include <sstream> # include <locale> # include <iostream> #endif # include <QTime> #include "PyExport.h" #include "Tools.h" namespace Base { struct string_comp : public std::binary_function<std::string, std::string, bool> { // s1 and s2 must be numbers represented as string bool operator()(const std::string& s1, const std::string& s2) { if (s1.size() < s2.size()) return true; else if (s1.size() > s2.size()) return false; else return s1 < s2; } static std::string increment(const std::string& s) { std::string n = s; int addcarry=1; for (std::string::reverse_iterator it = n.rbegin(); it != n.rend(); ++it) { if (addcarry == 0) break; int d = *it - 48; d = d + addcarry; *it = ((d%10) + 48); addcarry = d / 10; } if (addcarry > 0) { std::string b; b.resize(1); b[0] = addcarry + 48; n = b + n; } return n; } }; } std::string Base::Tools::getUniqueName(const std::string& name, const std::vector<std::string>& names, int d) { // find highest suffix std::string num_suffix; for (std::vector<std::string>::const_iterator it = names.begin(); it != names.end(); ++it) { if (it->substr(0, name.length()) == name) { // same prefix std::string suffix(it->substr(name.length())); if (suffix.size() > 0) { std::string::size_type pos = suffix.find_first_not_of("0123456789"); if (pos==std::string::npos) num_suffix = std::max<std::string>(num_suffix, suffix, Base::string_comp()); } } } std::stringstream str; str << name; if (d > 0) { str.fill('0'); str.width(d); } str << Base::string_comp::increment(num_suffix); return str.str(); } std::string Base::Tools::addNumber(const std::string& name, unsigned int num, int d) { std::stringstream str; str << name; if (d > 0) { str.fill('0'); str.width(d); } str << num; return str.str(); } std::string Base::Tools::getIdentifier(const std::string& name) { // check for first character whether it's a digit std::string CleanName = name; if (!CleanName.empty() && CleanName[0] >= 48 && CleanName[0] <= 57) CleanName[0] = '_'; // strip illegal chars for (std::string::iterator it = CleanName.begin(); it != CleanName.end(); ++it) { if (!((*it>=48 && *it<=57) || // number (*it>=65 && *it<=90) || // uppercase letter (*it>=97 && *it<=122))) // lowercase letter *it = '_'; // it's neither number nor letter } return CleanName; } std::wstring Base::Tools::widen(const std::string& str) { std::wostringstream wstm; const std::ctype<wchar_t>& ctfacet = std::use_facet< std::ctype<wchar_t> >(wstm.getloc()); for (size_t i=0; i<str.size(); ++i) wstm << ctfacet.widen(str[i]); return wstm.str(); } std::string Base::Tools::narrow(const std::wstring& str) { std::ostringstream stm; const std::ctype<char>& ctfacet = std::use_facet< std::ctype<char> >(stm.getloc()); for (size_t i=0; i<str.size(); ++i) stm << ctfacet.narrow(str[i], 0); return stm.str(); } std::string Base::Tools::escapedUnicodeFromUtf8(const char *s) { PyObject* unicode = PyUnicode_FromString(s); PyObject* escaped = PyUnicode_AsUnicodeEscapeString(unicode); Py_DECREF(unicode); std::string escapedstr = std::string(PyString_AsString(escaped)); Py_DECREF(escaped); return escapedstr; } std::string Base::Tools::escapedUnicodeToUtf8(const std::string& s) { std::string string; PyObject* unicode = PyUnicode_DecodeUnicodeEscape(s.c_str(), s.size(), "strict"); if (!unicode) return string; if (PyUnicode_Check(unicode)) { PyObject* value = PyUnicode_AsUTF8String(unicode); string = PyString_AsString(value); Py_DECREF(value); } else if (PyString_Check(unicode)) { string = PyString_AsString(unicode); } Py_DECREF(unicode); return string; } // ---------------------------------------------------------------------------- using namespace Base; struct StopWatch::Private { QTime t; }; StopWatch::StopWatch() : d(new Private) { } StopWatch::~StopWatch() { delete d; } void StopWatch::start() { d->t.start(); } int StopWatch::restart() { return d->t.restart(); } int StopWatch::elapsed() { return d->t.elapsed(); } std::string StopWatch::toString(int ms) const { int total = ms; int msec = total % 1000; total = total / 1000; int secs = total % 60; total = total / 60; int mins = total % 60; int hour = total / 60; std::stringstream str; str << "Needed time: "; if (hour > 0) str << hour << "h " << mins << "m " << secs << "s"; else if (mins > 0) str << mins << "m " << secs << "s"; else if (secs > 0) str << secs << "s"; else str << msec << "ms"; return str.str(); } <commit_msg>fix possible crashes in Tools::escapedUnicodeFromUtf8<commit_after>/*************************************************************************** * Copyright (c) 2009 Werner Mayer <wmayer[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * 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 "PreCompiled.h" #ifndef _PreComp_ # include <sstream> # include <locale> # include <iostream> #endif # include <QTime> #include "PyExport.h" #include "Interpreter.h" #include "Tools.h" namespace Base { struct string_comp : public std::binary_function<std::string, std::string, bool> { // s1 and s2 must be numbers represented as string bool operator()(const std::string& s1, const std::string& s2) { if (s1.size() < s2.size()) return true; else if (s1.size() > s2.size()) return false; else return s1 < s2; } static std::string increment(const std::string& s) { std::string n = s; int addcarry=1; for (std::string::reverse_iterator it = n.rbegin(); it != n.rend(); ++it) { if (addcarry == 0) break; int d = *it - 48; d = d + addcarry; *it = ((d%10) + 48); addcarry = d / 10; } if (addcarry > 0) { std::string b; b.resize(1); b[0] = addcarry + 48; n = b + n; } return n; } }; } std::string Base::Tools::getUniqueName(const std::string& name, const std::vector<std::string>& names, int d) { // find highest suffix std::string num_suffix; for (std::vector<std::string>::const_iterator it = names.begin(); it != names.end(); ++it) { if (it->substr(0, name.length()) == name) { // same prefix std::string suffix(it->substr(name.length())); if (suffix.size() > 0) { std::string::size_type pos = suffix.find_first_not_of("0123456789"); if (pos==std::string::npos) num_suffix = std::max<std::string>(num_suffix, suffix, Base::string_comp()); } } } std::stringstream str; str << name; if (d > 0) { str.fill('0'); str.width(d); } str << Base::string_comp::increment(num_suffix); return str.str(); } std::string Base::Tools::addNumber(const std::string& name, unsigned int num, int d) { std::stringstream str; str << name; if (d > 0) { str.fill('0'); str.width(d); } str << num; return str.str(); } std::string Base::Tools::getIdentifier(const std::string& name) { // check for first character whether it's a digit std::string CleanName = name; if (!CleanName.empty() && CleanName[0] >= 48 && CleanName[0] <= 57) CleanName[0] = '_'; // strip illegal chars for (std::string::iterator it = CleanName.begin(); it != CleanName.end(); ++it) { if (!((*it>=48 && *it<=57) || // number (*it>=65 && *it<=90) || // uppercase letter (*it>=97 && *it<=122))) // lowercase letter *it = '_'; // it's neither number nor letter } return CleanName; } std::wstring Base::Tools::widen(const std::string& str) { std::wostringstream wstm; const std::ctype<wchar_t>& ctfacet = std::use_facet< std::ctype<wchar_t> >(wstm.getloc()); for (size_t i=0; i<str.size(); ++i) wstm << ctfacet.widen(str[i]); return wstm.str(); } std::string Base::Tools::narrow(const std::wstring& str) { std::ostringstream stm; const std::ctype<char>& ctfacet = std::use_facet< std::ctype<char> >(stm.getloc()); for (size_t i=0; i<str.size(); ++i) stm << ctfacet.narrow(str[i], 0); return stm.str(); } std::string Base::Tools::escapedUnicodeFromUtf8(const char *s) { Base::PyGILStateLocker lock; std::string escapedstr; PyObject* unicode = PyUnicode_FromString(s); if (!unicode) return escapedstr; PyObject* escaped = PyUnicode_AsUnicodeEscapeString(unicode); if (escaped) { escapedstr = std::string(PyString_AsString(escaped)); Py_DECREF(escaped); } Py_DECREF(unicode); return escapedstr; } std::string Base::Tools::escapedUnicodeToUtf8(const std::string& s) { Base::PyGILStateLocker lock; std::string string; PyObject* unicode = PyUnicode_DecodeUnicodeEscape(s.c_str(), s.size(), "strict"); if (!unicode) return string; if (PyUnicode_Check(unicode)) { PyObject* value = PyUnicode_AsUTF8String(unicode); string = PyString_AsString(value); Py_DECREF(value); } else if (PyString_Check(unicode)) { string = PyString_AsString(unicode); } Py_DECREF(unicode); return string; } // ---------------------------------------------------------------------------- using namespace Base; struct StopWatch::Private { QTime t; }; StopWatch::StopWatch() : d(new Private) { } StopWatch::~StopWatch() { delete d; } void StopWatch::start() { d->t.start(); } int StopWatch::restart() { return d->t.restart(); } int StopWatch::elapsed() { return d->t.elapsed(); } std::string StopWatch::toString(int ms) const { int total = ms; int msec = total % 1000; total = total / 1000; int secs = total % 60; total = total / 60; int mins = total % 60; int hour = total / 60; std::stringstream str; str << "Needed time: "; if (hour > 0) str << hour << "h " << mins << "m " << secs << "s"; else if (mins > 0) str << mins << "m " << secs << "s"; else if (secs > 0) str << secs << "s"; else str << msec << "ms"; return str.str(); } <|endoftext|>
<commit_before>#include "THMMesh.h" #include "libmesh/node.h" #include "libmesh/edge_edge2.h" #include "libmesh/edge_edge3.h" #include "libmesh/face_quad4.h" #include "libmesh/face_quad9.h" registerMooseObject("THMApp", THMMesh); const BoundaryName THMMesh::INVALID_BOUNDARY_ID = "invalid_boundary_id"; InputParameters THMMesh::validParams() { InputParameters params = MooseMesh::validParams(); // we do not allow renumbering, becuase we generate our meshes params.set<bool>("allow_renumbering") = false; return params; } THMMesh::THMMesh(const InputParameters & parameters) : MooseMesh(parameters), _dim(getParam<MooseEnum>("dim")), _next_node_id(0), _next_element_id(0), _next_subdomain_id(0), _next_boundary_id(0) { } THMMesh::THMMesh(const THMMesh & other_mesh) : MooseMesh(other_mesh), _dim(other_mesh._dim), _next_node_id(other_mesh._next_node_id), _next_element_id(other_mesh._next_element_id), _next_subdomain_id(other_mesh._next_subdomain_id), _next_boundary_id(other_mesh._next_boundary_id) { } unsigned int THMMesh::dimension() const { return _dim; } unsigned int THMMesh::effectiveSpatialDimension() const { return _dim; } std::unique_ptr<MooseMesh> THMMesh::safeClone() const { return libmesh_make_unique<THMMesh>(*this); } void THMMesh::buildMesh() { getMesh().set_spatial_dimension(_dim); } void THMMesh::prep() { prepare(true); } dof_id_type THMMesh::getNextNodeId() { dof_id_type id = _next_node_id++; return id; } dof_id_type THMMesh::getNextElementId() { dof_id_type id = _next_element_id++; return id; } Node * THMMesh::addNode(const Point & pt) { dof_id_type id = getNextNodeId(); Node * node = _mesh->add_point(pt, id); return node; } Elem * THMMesh::addElement(libMesh::ElemType elem_type, const std::vector<dof_id_type> & node_ids) { const auto pid = _mesh->comm().rank(); dof_id_type elem_id = getNextElementId(); Elem * elem = libMesh::Elem::build(elem_type).release(); elem->set_id(elem_id); elem->processor_id() = pid; _mesh->add_elem(elem); for (std::size_t i = 0; i < node_ids.size(); i++) elem->set_node(i) = _mesh->node_ptr(node_ids[i]); return elem; } Elem * THMMesh::addElementEdge2(dof_id_type node0, dof_id_type node1) { const auto pid = _mesh->comm().rank(); dof_id_type elem_id = getNextElementId(); Elem * elem = new Edge2; elem->set_id(elem_id); elem->processor_id() = pid; _mesh->add_elem(elem); elem->set_node(0) = _mesh->node_ptr(node0); elem->set_node(1) = _mesh->node_ptr(node1); return elem; } Elem * THMMesh::addElementEdge3(dof_id_type node0, dof_id_type node1, dof_id_type node2) { const auto pid = _mesh->comm().rank(); dof_id_type elem_id = getNextElementId(); Elem * elem = new Edge3; elem->set_id(elem_id); elem->processor_id() = pid; _mesh->add_elem(elem); elem->set_node(0) = _mesh->node_ptr(node0); elem->set_node(1) = _mesh->node_ptr(node1); elem->set_node(2) = _mesh->node_ptr(node2); return elem; } Elem * THMMesh::addElementQuad4(dof_id_type node0, dof_id_type node1, dof_id_type node2, dof_id_type node3) { const auto pid = _mesh->comm().rank(); dof_id_type elem_id = getNextElementId(); Elem * elem = new Quad4; elem->set_id(elem_id); elem->processor_id() = pid; _mesh->add_elem(elem); elem->set_node(0) = _mesh->node_ptr(node0); elem->set_node(1) = _mesh->node_ptr(node1); elem->set_node(2) = _mesh->node_ptr(node2); elem->set_node(3) = _mesh->node_ptr(node3); return elem; } Elem * THMMesh::addElementQuad9(dof_id_type node0, dof_id_type node1, dof_id_type node2, dof_id_type node3, dof_id_type node4, dof_id_type node5, dof_id_type node6, dof_id_type node7, dof_id_type node8) { const auto pid = _mesh->comm().rank(); dof_id_type elem_id = getNextElementId(); Elem * elem = new Quad9; elem->set_id(elem_id); elem->processor_id() = pid; _mesh->add_elem(elem); // vertices elem->set_node(0) = _mesh->node_ptr(node0); elem->set_node(1) = _mesh->node_ptr(node1); elem->set_node(2) = _mesh->node_ptr(node2); elem->set_node(3) = _mesh->node_ptr(node3); // mid-edges elem->set_node(4) = _mesh->node_ptr(node4); elem->set_node(5) = _mesh->node_ptr(node5); elem->set_node(6) = _mesh->node_ptr(node6); elem->set_node(7) = _mesh->node_ptr(node7); // center elem->set_node(8) = _mesh->node_ptr(node8); return elem; } SubdomainID THMMesh::getNextSubdomainId() { SubdomainID id = _next_subdomain_id++; return id; } BoundaryID THMMesh::getNextBoundaryId() { BoundaryID id = _next_boundary_id++; return id; } <commit_msg>Do not set processor ID in elements<commit_after>#include "THMMesh.h" #include "libmesh/node.h" #include "libmesh/edge_edge2.h" #include "libmesh/edge_edge3.h" #include "libmesh/face_quad4.h" #include "libmesh/face_quad9.h" registerMooseObject("THMApp", THMMesh); const BoundaryName THMMesh::INVALID_BOUNDARY_ID = "invalid_boundary_id"; InputParameters THMMesh::validParams() { InputParameters params = MooseMesh::validParams(); // we do not allow renumbering, becuase we generate our meshes params.set<bool>("allow_renumbering") = false; return params; } THMMesh::THMMesh(const InputParameters & parameters) : MooseMesh(parameters), _dim(getParam<MooseEnum>("dim")), _next_node_id(0), _next_element_id(0), _next_subdomain_id(0), _next_boundary_id(0) { } THMMesh::THMMesh(const THMMesh & other_mesh) : MooseMesh(other_mesh), _dim(other_mesh._dim), _next_node_id(other_mesh._next_node_id), _next_element_id(other_mesh._next_element_id), _next_subdomain_id(other_mesh._next_subdomain_id), _next_boundary_id(other_mesh._next_boundary_id) { } unsigned int THMMesh::dimension() const { return _dim; } unsigned int THMMesh::effectiveSpatialDimension() const { return _dim; } std::unique_ptr<MooseMesh> THMMesh::safeClone() const { return libmesh_make_unique<THMMesh>(*this); } void THMMesh::buildMesh() { getMesh().set_spatial_dimension(_dim); } void THMMesh::prep() { prepare(true); } dof_id_type THMMesh::getNextNodeId() { dof_id_type id = _next_node_id++; return id; } dof_id_type THMMesh::getNextElementId() { dof_id_type id = _next_element_id++; return id; } Node * THMMesh::addNode(const Point & pt) { dof_id_type id = getNextNodeId(); Node * node = _mesh->add_point(pt, id); return node; } Elem * THMMesh::addElement(libMesh::ElemType elem_type, const std::vector<dof_id_type> & node_ids) { dof_id_type elem_id = getNextElementId(); Elem * elem = libMesh::Elem::build(elem_type).release(); elem->set_id(elem_id); _mesh->add_elem(elem); for (std::size_t i = 0; i < node_ids.size(); i++) elem->set_node(i) = _mesh->node_ptr(node_ids[i]); return elem; } Elem * THMMesh::addElementEdge2(dof_id_type node0, dof_id_type node1) { dof_id_type elem_id = getNextElementId(); Elem * elem = new Edge2; elem->set_id(elem_id); _mesh->add_elem(elem); elem->set_node(0) = _mesh->node_ptr(node0); elem->set_node(1) = _mesh->node_ptr(node1); return elem; } Elem * THMMesh::addElementEdge3(dof_id_type node0, dof_id_type node1, dof_id_type node2) { dof_id_type elem_id = getNextElementId(); Elem * elem = new Edge3; elem->set_id(elem_id); _mesh->add_elem(elem); elem->set_node(0) = _mesh->node_ptr(node0); elem->set_node(1) = _mesh->node_ptr(node1); elem->set_node(2) = _mesh->node_ptr(node2); return elem; } Elem * THMMesh::addElementQuad4(dof_id_type node0, dof_id_type node1, dof_id_type node2, dof_id_type node3) { dof_id_type elem_id = getNextElementId(); Elem * elem = new Quad4; elem->set_id(elem_id); _mesh->add_elem(elem); elem->set_node(0) = _mesh->node_ptr(node0); elem->set_node(1) = _mesh->node_ptr(node1); elem->set_node(2) = _mesh->node_ptr(node2); elem->set_node(3) = _mesh->node_ptr(node3); return elem; } Elem * THMMesh::addElementQuad9(dof_id_type node0, dof_id_type node1, dof_id_type node2, dof_id_type node3, dof_id_type node4, dof_id_type node5, dof_id_type node6, dof_id_type node7, dof_id_type node8) { dof_id_type elem_id = getNextElementId(); Elem * elem = new Quad9; elem->set_id(elem_id); _mesh->add_elem(elem); // vertices elem->set_node(0) = _mesh->node_ptr(node0); elem->set_node(1) = _mesh->node_ptr(node1); elem->set_node(2) = _mesh->node_ptr(node2); elem->set_node(3) = _mesh->node_ptr(node3); // mid-edges elem->set_node(4) = _mesh->node_ptr(node4); elem->set_node(5) = _mesh->node_ptr(node5); elem->set_node(6) = _mesh->node_ptr(node6); elem->set_node(7) = _mesh->node_ptr(node7); // center elem->set_node(8) = _mesh->node_ptr(node8); return elem; } SubdomainID THMMesh::getNextSubdomainId() { SubdomainID id = _next_subdomain_id++; return id; } BoundaryID THMMesh::getNextBoundaryId() { BoundaryID id = _next_boundary_id++; return id; } <|endoftext|>
<commit_before>#pragma once // Mostly copied from https://github.com/SaschaWillems/Vulkan #include <functional> namespace flex { namespace vk { template <typename T> class VDeleter { public: VDeleter(); VDeleter(std::function<void(T, VkAllocationCallbacks*)> deletef); VDeleter(const VDeleter<VkInstance>& instance, std::function<void(VkInstance, T, VkAllocationCallbacks*)> deletef); VDeleter(const VDeleter<VkDevice>& device, std::function<void(VkDevice, T, VkAllocationCallbacks*)> deletef); ~VDeleter(); T* operator &(); T* replace(); operator T() const; void operator=(T rhs); template<typename V> bool operator==(V rhs); private: T object{ VK_NULL_HANDLE }; std::function<void(T)> deleter; void cleanup(); }; template<typename T> VDeleter<T>::VDeleter() : VDeleter([](T, VkAllocationCallbacks*) {}) { } template<typename T> VDeleter<T>::VDeleter(std::function<void(T, VkAllocationCallbacks*)> deletef) { this->deleter = [=](T obj) { deletef(obj, nullptr); }; } template<typename T> VDeleter<T>::VDeleter(const VDeleter<VkInstance>& instance, std::function<void(VkInstance, T, VkAllocationCallbacks*)> deletef) { this->deleter = [&instance, deletef](T obj) { deletef(instance, obj, nullptr); }; } template<typename T> VDeleter<T>::VDeleter(const VDeleter<VkDevice>& device, std::function<void(VkDevice, T, VkAllocationCallbacks*)> deletef) { this->deleter = [&device, deletef](T obj) { deletef(device, obj, nullptr); }; } template<typename T> VDeleter<T>::~VDeleter() { cleanup(); } template<typename T> T* VDeleter<T>::operator &() { return &object; } template<typename T> T* VDeleter<T>::replace() { cleanup(); return &object; } template<typename T> VDeleter<T>::operator T() const { return object; } template<typename T> void VDeleter<T>::operator=(T rhs) { if (rhs != object) { cleanup(); object = rhs; } } template<typename T> template<typename V> inline bool VDeleter<T>::operator==(V rhs) { // TODO: Is this function needed? UNREFERENCED_PARAMETER(rhs); return false; } template<typename T> void VDeleter<T>::cleanup() { if (object != VK_NULL_HANDLE) { deleter(object); } object = VK_NULL_HANDLE; } } // namespace vk } // namespace flex<commit_msg>Remove unused function from VDeleter<commit_after>#pragma once // Mostly copied from https://github.com/SaschaWillems/Vulkan #include <functional> namespace flex { namespace vk { template <typename T> class VDeleter { public: VDeleter(); VDeleter(std::function<void(T, VkAllocationCallbacks*)> deletef); VDeleter(const VDeleter<VkInstance>& instance, std::function<void(VkInstance, T, VkAllocationCallbacks*)> deletef); VDeleter(const VDeleter<VkDevice>& device, std::function<void(VkDevice, T, VkAllocationCallbacks*)> deletef); ~VDeleter(); T* operator &(); T* replace(); operator T() const; void operator=(T rhs); private: T object{ VK_NULL_HANDLE }; std::function<void(T)> deleter; void cleanup(); }; template<typename T> VDeleter<T>::VDeleter() : VDeleter([](T, VkAllocationCallbacks*) {}) { } template<typename T> VDeleter<T>::VDeleter(std::function<void(T, VkAllocationCallbacks*)> deletef) { this->deleter = [=](T obj) { deletef(obj, nullptr); }; } template<typename T> VDeleter<T>::VDeleter(const VDeleter<VkInstance>& instance, std::function<void(VkInstance, T, VkAllocationCallbacks*)> deletef) { this->deleter = [&instance, deletef](T obj) { deletef(instance, obj, nullptr); }; } template<typename T> VDeleter<T>::VDeleter(const VDeleter<VkDevice>& device, std::function<void(VkDevice, T, VkAllocationCallbacks*)> deletef) { this->deleter = [&device, deletef](T obj) { deletef(device, obj, nullptr); }; } template<typename T> VDeleter<T>::~VDeleter() { cleanup(); } template<typename T> T* VDeleter<T>::operator &() { return &object; } template<typename T> T* VDeleter<T>::replace() { cleanup(); return &object; } template<typename T> VDeleter<T>::operator T() const { return object; } template<typename T> void VDeleter<T>::operator=(T rhs) { if (rhs != object) { cleanup(); object = rhs; } } template<typename T> void VDeleter<T>::cleanup() { if (object != VK_NULL_HANDLE) { deleter(object); } object = VK_NULL_HANDLE; } } // namespace vk } // namespace flex<|endoftext|>
<commit_before>/* * Copyright (c) 2012 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #pragma once #ifndef _LIBQI_QI_LOG_HXX_ #define _LIBQI_QI_LOG_HXX_ #include <boost/type_traits.hpp> #if defined(NO_QI_DEBUG) || defined(NDEBUG) # define _qiLogDebug(...) if (false) qi::log::detail::NullStream().self() #elif defined(NO_QI_LOG_DETAILED_CONTEXT) || defined(NDEBUG) # define _qiLogDebug(...) qi::log::LogStream(qi::log::debug, "", __FUNCTION__, 0, __VA_ARGS__).self() #else # define _qiLogDebug(...) qi::log::LogStream(qi::log::debug, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif #ifdef NO_QI_VERBOSE # define _qiLogVerbose(...) if (false) qi::log::detail::NullStream().self() #elif defined(NO_QI_LOG_DETAILED_CONTEXT) || defined(NDEBUG) # define _qiLogVerbose(...) qi::log::LogStream(qi::log::verbose, "", __FUNCTION__, 0, __VA_ARGS__).self() #else # define _qiLogVerbose(...) qi::log::LogStream(qi::log::verbose, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif #ifdef NO_QI_INFO # define _qiLogInfo(...) if (false) qi::log::detail::NullStream().self() #elif defined(NO_QI_LOG_DETAILED_CONTEXT) || defined(NDEBUG) # define _qiLogInfo(...) qi::log::LogStream(qi::log::info, "", __FUNCTION__, 0, __VA_ARGS__).self() #else # define _qiLogInfo(...) qi::log::LogStream(qi::log::info, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif #ifdef NO_QI_WARNING # define _qiLogWarning(...) if (false) qi::log::detail::NullStream().self() #elif defined(NO_QI_LOG_DETAILED_CONTEXT) || defined(NDEBUG) # define _qiLogWarning(...) qi::log::LogStream(qi::log::warning, "", __FUNCTION__, 0, __VA_ARGS__).self() #else # define _qiLogWarning(...) qi::log::LogStream(qi::log::warning, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif #ifdef NO_QI_ERROR # define _qiLogError(...) if (false) qi::log::detail::NullStream().self() #elif defined(NO_QI_LOG_DETAILED_CONTEXT) || defined(NDEBUG) # define _qiLogError(...) qi::log::LogStream(qi::log::error, "", __FUNCTION__, 0, __VA_ARGS__).self() #else # define _qiLogError(...) qi::log::LogStream(qi::log::error, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif #ifdef NO_QI_FATAL # define _qiLogFatal(...) if (false) qi::log::detail::NullStream().self() #elif defined(NO_QI_LOG_DETAILED_CONTEXT) || defined(NDEBUG) # define _qiLogFatal(...) qi::log::LogStream(qi::log::fatal, "", __FUNCTION__, 0, __VA_ARGS__).self() #else # define _qiLogFatal(...) qi::log::LogStream(qi::log::fatal, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif // enum level { // silent = 0, // fatal, // error, // warning, // info, // verbose, // debug // }; /* PREPROCESSING HELL * Empty vaargs is seen as one empty argument. There is no portable way * to detect it. So to avoid << format("foo") %() >> we use an other operator * that bounces to %, and wrap the argument through a nothing detector that * returns an instance of Nothing class. * Hopefuly that should have no impact on generated code. */ namespace qi { namespace log { namespace detail { template<typename T> struct logical_not : boost::integral_constant<bool, !T::value> {}; struct Nothing {}; inline Nothing isNothing() { return Nothing();} /* If we only provide the const T& version of isNothing, we force * acquiring a reference, which might cause troubles (for example with a * static const declared in a class with value, but not defined). * We cannot let the two overloads live together as they create an ambiguous * overload. */ template<typename T> inline typename boost::enable_if<logical_not<boost::is_fundamental<T> >, const T&>::type isNothing(const T& v) { return v;} template<typename T> inline typename boost::enable_if<boost::is_fundamental<T>, T>::type isNothing(T v) { return v;} } } } namespace boost { // We *must* take first argument as const ref. template<typename T> boost::format& operator /(const boost::format& a, const T& elem) { const_cast<boost::format&>(a) % elem; return const_cast<boost::format&>(a); } inline boost::format& operator / (const boost::format& a, ::qi::log::detail::Nothing) {return const_cast<boost::format&>(a);} }; # define _QI_FORMAT_ELEM(_, a, elem) / ::qi::log::detail::isNothing(elem) # define _QI_LOG_FORMAT(Msg, ...) \ boost::str(::qi::log::detail::getFormat(Msg) QI_VAARGS_APPLY(_QI_FORMAT_ELEM, _, __VA_ARGS__)) #define _QI_SECOND(a, ...) __VA_ARGS__ /* For fast category access, we use lookup to a fixed name symbol. * The user is required a QI_LOG_CATEGORY somewhere i<"n scope. */ # define _QI_LOG_CATEGORY_GET() _qi_log_category #if defined(NO_QI_LOG_DETAILED_CONTEXT) || defined(NDEBUG) # define _QI_LOG_MESSAGE(Type, Message) \ do \ { \ if (::qi::log::detail::isVisible(_QI_LOG_CATEGORY_GET(), ::qi::log::Type)) \ ::qi::log::log(::qi::log::Type, \ _QI_LOG_CATEGORY_GET(), \ Message, \ "", __FUNCTION__, 0); \ } \ while (false) #else # define _QI_LOG_MESSAGE(Type, Message) \ do \ { \ if (::qi::log::detail::isVisible(_QI_LOG_CATEGORY_GET(), ::qi::log::Type)) \ ::qi::log::log(::qi::log::Type, \ _QI_LOG_CATEGORY_GET(), \ Message, \ __FILE__, __FUNCTION__, __LINE__); \ } \ while (false) #endif /* Tricky, we do not want to hit category_get if a category is specified * Usual glitch of off-by-one list size: put argument 'TypeCased' in the vaargs */ # define _QI_LOG_MESSAGE_STREAM(Type, TypeCased, ...) \ QI_CAT(_QI_LOG_MESSAGE_STREAM_HASCAT_, _QI_LOG_ISEMPTY( __VA_ARGS__))(Type, TypeCased, __VA_ARGS__) // no extra argument #define _QI_LOG_MESSAGE_STREAM_HASCAT_1(Type, TypeCased, ...) \ ::qi::log::detail::isVisible(_QI_LOG_CATEGORY_GET(), ::qi::log::Type) \ && BOOST_PP_CAT(_qiLog, TypeCased)(_QI_LOG_CATEGORY_GET()) #ifdef _WIN32 // extra argument: at least a category, maybe a format and arguments #define _QI_LOG_MESSAGE_STREAM_HASCAT_0(...) QI_DELAY(_QI_LOG_MESSAGE_STREAM_HASCAT_0) ## _BOUNCE(__VA_ARGS__) #else #define _QI_LOG_MESSAGE_STREAM_HASCAT_0(...) _QI_LOG_MESSAGE_STREAM_HASCAT_0_BOUNCE(__VA_ARGS__) #endif #define _QI_LOG_MESSAGE_STREAM_HASCAT_0_BOUNCE(Type, TypeCased, cat, ...) \ QI_CAT(_QI_LOG_MESSAGE_STREAM_HASCAT_HASFORMAT_, _QI_LOG_ISEMPTY( __VA_ARGS__))(Type, TypeCased, cat, __VA_ARGS__) #define _QI_LOG_MESSAGE_STREAM_HASCAT_HASFORMAT_0(Type, TypeCased, cat, format, ...) \ BOOST_PP_CAT(_qiLog, TypeCased)(cat, _QI_LOG_FORMAT(format, __VA_ARGS__)) #define _QI_LOG_MESSAGE_STREAM_HASCAT_HASFORMAT_1(Type, TypeCased, cat, ...) \ BOOST_PP_CAT(_qiLog,TypeCased)(cat) /* Detecting empty arg is tricky. * Trick 1 below does not work with gcc, because x ## "foo" produces a preprocessor error. * Trick 2 rely on ##__VA_ARGS__ */ #ifdef _WIN32 #define _WQI_IS_EMPTY_HELPER___ a,b #define WQI_IS_EMPTY(a,...) QI_CAT_20(QI_LIST_VASIZE,((QI_CAT_22(_WQI_IS_EMPTY_HELPER, QI_CAT_24(QI_CAT_26(_, a), _))))) #define _QI_FIRST_ARG(a, ...) a #define _QI_LOG_ISEMPTY(...) WQI_IS_EMPTY(QI_CAT_18(_, _QI_FIRST_ARG(__VA_ARGS__, 12))) #else #define _QI_LOG_REVERSE 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0 #define _QI_LOG_REVERSEEMPTY 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1 #define _QI_LOG_ARGN(a, b, c, d, e, f, g, h, i, N, ...) N #define _QI_LOG_NARG_(dummy, ...) _QI_LOG_ARGN(__VA_ARGS__) #define _QI_LOG_NARG(...) _QI_LOG_NARG_(dummy, ##__VA_ARGS__, _QI_LOG_REVERSE) #define _QI_LOG_ISEMPTY(...) _QI_LOG_NARG_(dummy, ##__VA_ARGS__, _QI_LOG_REVERSEEMPTY) #endif namespace qi { namespace log{ namespace detail { class NullStream { public: NullStream(...) { } NullStream &self() { return *this; } template <typename T> NullStream& operator<<(const T &QI_UNUSED(val)) { return self(); } NullStream& operator<<(std::ostream& (*QI_UNUSED(f))(std::ostream&)) { return self(); } }; struct Category { std::string name; LogLevel mainLevel; std::vector<LogLevel> levels; }; QI_API boost::format getFormat(const std::string& s); /// @return a pointer to the global loglevel setting QI_API LogLevel* globalLogLevelPtr(); // We will end up with one instance per module, but we don't care inline LogLevel globalLogLevel() { static LogLevel* l = globalLogLevelPtr(); return *l; } inline bool isVisible(Category* category, LogLevel level) { return level <= globalLogLevel() && level <= category->mainLevel; } } typedef detail::Category* category_type; class LogStream: public std::stringstream { public: LogStream(const LogLevel level, const char *file, const char *function, const int line, const char *category) : _logLevel(level) , _category(category) , _categoryType(0) , _file(file) , _function(function) , _line(line) { } LogStream(const LogLevel level, const char *file, const char *function, const int line, category_type category) : _logLevel(level) , _category(0) , _categoryType(category) , _file(file) , _function(function) , _line(line) { } LogStream(const LogLevel level, const char *file, const char *function, const int line, const char *category, const std::string& message) : _logLevel(level) , _category(category) , _categoryType(0) , _file(file) , _function(function) , _line(line) { *this << message; } ~LogStream() { if (!this->str().empty()) { if (_category) qi::log::log(_logLevel, _category, this->str().c_str(), _file, _function, _line); else qi::log::log(_logLevel, _categoryType, this->str(), _file, _function, _line); } } LogStream& self() { return *this; } private: LogLevel _logLevel; const char *_category; category_type _categoryType; const char *_file; const char *_function; int _line; //avoid copy LogStream(const LogStream &rhs); LogStream &operator=(const LogStream &rhs); }; } } #endif <commit_msg>Add missing include.<commit_after>/* * Copyright (c) 2012 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #pragma once #ifndef _LIBQI_QI_LOG_HXX_ #define _LIBQI_QI_LOG_HXX_ #include <boost/type_traits.hpp> #include <boost/utility/enable_if.hpp> #if defined(NO_QI_DEBUG) || defined(NDEBUG) # define _qiLogDebug(...) if (false) qi::log::detail::NullStream().self() #elif defined(NO_QI_LOG_DETAILED_CONTEXT) || defined(NDEBUG) # define _qiLogDebug(...) qi::log::LogStream(qi::log::debug, "", __FUNCTION__, 0, __VA_ARGS__).self() #else # define _qiLogDebug(...) qi::log::LogStream(qi::log::debug, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif #ifdef NO_QI_VERBOSE # define _qiLogVerbose(...) if (false) qi::log::detail::NullStream().self() #elif defined(NO_QI_LOG_DETAILED_CONTEXT) || defined(NDEBUG) # define _qiLogVerbose(...) qi::log::LogStream(qi::log::verbose, "", __FUNCTION__, 0, __VA_ARGS__).self() #else # define _qiLogVerbose(...) qi::log::LogStream(qi::log::verbose, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif #ifdef NO_QI_INFO # define _qiLogInfo(...) if (false) qi::log::detail::NullStream().self() #elif defined(NO_QI_LOG_DETAILED_CONTEXT) || defined(NDEBUG) # define _qiLogInfo(...) qi::log::LogStream(qi::log::info, "", __FUNCTION__, 0, __VA_ARGS__).self() #else # define _qiLogInfo(...) qi::log::LogStream(qi::log::info, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif #ifdef NO_QI_WARNING # define _qiLogWarning(...) if (false) qi::log::detail::NullStream().self() #elif defined(NO_QI_LOG_DETAILED_CONTEXT) || defined(NDEBUG) # define _qiLogWarning(...) qi::log::LogStream(qi::log::warning, "", __FUNCTION__, 0, __VA_ARGS__).self() #else # define _qiLogWarning(...) qi::log::LogStream(qi::log::warning, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif #ifdef NO_QI_ERROR # define _qiLogError(...) if (false) qi::log::detail::NullStream().self() #elif defined(NO_QI_LOG_DETAILED_CONTEXT) || defined(NDEBUG) # define _qiLogError(...) qi::log::LogStream(qi::log::error, "", __FUNCTION__, 0, __VA_ARGS__).self() #else # define _qiLogError(...) qi::log::LogStream(qi::log::error, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif #ifdef NO_QI_FATAL # define _qiLogFatal(...) if (false) qi::log::detail::NullStream().self() #elif defined(NO_QI_LOG_DETAILED_CONTEXT) || defined(NDEBUG) # define _qiLogFatal(...) qi::log::LogStream(qi::log::fatal, "", __FUNCTION__, 0, __VA_ARGS__).self() #else # define _qiLogFatal(...) qi::log::LogStream(qi::log::fatal, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif // enum level { // silent = 0, // fatal, // error, // warning, // info, // verbose, // debug // }; /* PREPROCESSING HELL * Empty vaargs is seen as one empty argument. There is no portable way * to detect it. So to avoid << format("foo") %() >> we use an other operator * that bounces to %, and wrap the argument through a nothing detector that * returns an instance of Nothing class. * Hopefuly that should have no impact on generated code. */ namespace qi { namespace log { namespace detail { template<typename T> struct logical_not : boost::integral_constant<bool, !T::value> {}; struct Nothing {}; inline Nothing isNothing() { return Nothing();} /* If we only provide the const T& version of isNothing, we force * acquiring a reference, which might cause troubles (for example with a * static const declared in a class with value, but not defined). * We cannot let the two overloads live together as they create an ambiguous * overload. */ template<typename T> inline typename boost::enable_if<logical_not<boost::is_fundamental<T> >, const T&>::type isNothing(const T& v) { return v;} template<typename T> inline typename boost::enable_if<boost::is_fundamental<T>, T>::type isNothing(T v) { return v;} } } } namespace boost { // We *must* take first argument as const ref. template<typename T> boost::format& operator /(const boost::format& a, const T& elem) { const_cast<boost::format&>(a) % elem; return const_cast<boost::format&>(a); } inline boost::format& operator / (const boost::format& a, ::qi::log::detail::Nothing) {return const_cast<boost::format&>(a);} }; # define _QI_FORMAT_ELEM(_, a, elem) / ::qi::log::detail::isNothing(elem) # define _QI_LOG_FORMAT(Msg, ...) \ boost::str(::qi::log::detail::getFormat(Msg) QI_VAARGS_APPLY(_QI_FORMAT_ELEM, _, __VA_ARGS__)) #define _QI_SECOND(a, ...) __VA_ARGS__ /* For fast category access, we use lookup to a fixed name symbol. * The user is required a QI_LOG_CATEGORY somewhere i<"n scope. */ # define _QI_LOG_CATEGORY_GET() _qi_log_category #if defined(NO_QI_LOG_DETAILED_CONTEXT) || defined(NDEBUG) # define _QI_LOG_MESSAGE(Type, Message) \ do \ { \ if (::qi::log::detail::isVisible(_QI_LOG_CATEGORY_GET(), ::qi::log::Type)) \ ::qi::log::log(::qi::log::Type, \ _QI_LOG_CATEGORY_GET(), \ Message, \ "", __FUNCTION__, 0); \ } \ while (false) #else # define _QI_LOG_MESSAGE(Type, Message) \ do \ { \ if (::qi::log::detail::isVisible(_QI_LOG_CATEGORY_GET(), ::qi::log::Type)) \ ::qi::log::log(::qi::log::Type, \ _QI_LOG_CATEGORY_GET(), \ Message, \ __FILE__, __FUNCTION__, __LINE__); \ } \ while (false) #endif /* Tricky, we do not want to hit category_get if a category is specified * Usual glitch of off-by-one list size: put argument 'TypeCased' in the vaargs */ # define _QI_LOG_MESSAGE_STREAM(Type, TypeCased, ...) \ QI_CAT(_QI_LOG_MESSAGE_STREAM_HASCAT_, _QI_LOG_ISEMPTY( __VA_ARGS__))(Type, TypeCased, __VA_ARGS__) // no extra argument #define _QI_LOG_MESSAGE_STREAM_HASCAT_1(Type, TypeCased, ...) \ ::qi::log::detail::isVisible(_QI_LOG_CATEGORY_GET(), ::qi::log::Type) \ && BOOST_PP_CAT(_qiLog, TypeCased)(_QI_LOG_CATEGORY_GET()) #ifdef _WIN32 // extra argument: at least a category, maybe a format and arguments #define _QI_LOG_MESSAGE_STREAM_HASCAT_0(...) QI_DELAY(_QI_LOG_MESSAGE_STREAM_HASCAT_0) ## _BOUNCE(__VA_ARGS__) #else #define _QI_LOG_MESSAGE_STREAM_HASCAT_0(...) _QI_LOG_MESSAGE_STREAM_HASCAT_0_BOUNCE(__VA_ARGS__) #endif #define _QI_LOG_MESSAGE_STREAM_HASCAT_0_BOUNCE(Type, TypeCased, cat, ...) \ QI_CAT(_QI_LOG_MESSAGE_STREAM_HASCAT_HASFORMAT_, _QI_LOG_ISEMPTY( __VA_ARGS__))(Type, TypeCased, cat, __VA_ARGS__) #define _QI_LOG_MESSAGE_STREAM_HASCAT_HASFORMAT_0(Type, TypeCased, cat, format, ...) \ BOOST_PP_CAT(_qiLog, TypeCased)(cat, _QI_LOG_FORMAT(format, __VA_ARGS__)) #define _QI_LOG_MESSAGE_STREAM_HASCAT_HASFORMAT_1(Type, TypeCased, cat, ...) \ BOOST_PP_CAT(_qiLog,TypeCased)(cat) /* Detecting empty arg is tricky. * Trick 1 below does not work with gcc, because x ## "foo" produces a preprocessor error. * Trick 2 rely on ##__VA_ARGS__ */ #ifdef _WIN32 #define _WQI_IS_EMPTY_HELPER___ a,b #define WQI_IS_EMPTY(a,...) QI_CAT_20(QI_LIST_VASIZE,((QI_CAT_22(_WQI_IS_EMPTY_HELPER, QI_CAT_24(QI_CAT_26(_, a), _))))) #define _QI_FIRST_ARG(a, ...) a #define _QI_LOG_ISEMPTY(...) WQI_IS_EMPTY(QI_CAT_18(_, _QI_FIRST_ARG(__VA_ARGS__, 12))) #else #define _QI_LOG_REVERSE 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0 #define _QI_LOG_REVERSEEMPTY 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1 #define _QI_LOG_ARGN(a, b, c, d, e, f, g, h, i, N, ...) N #define _QI_LOG_NARG_(dummy, ...) _QI_LOG_ARGN(__VA_ARGS__) #define _QI_LOG_NARG(...) _QI_LOG_NARG_(dummy, ##__VA_ARGS__, _QI_LOG_REVERSE) #define _QI_LOG_ISEMPTY(...) _QI_LOG_NARG_(dummy, ##__VA_ARGS__, _QI_LOG_REVERSEEMPTY) #endif namespace qi { namespace log{ namespace detail { class NullStream { public: NullStream(...) { } NullStream &self() { return *this; } template <typename T> NullStream& operator<<(const T &QI_UNUSED(val)) { return self(); } NullStream& operator<<(std::ostream& (*QI_UNUSED(f))(std::ostream&)) { return self(); } }; struct Category { std::string name; LogLevel mainLevel; std::vector<LogLevel> levels; }; QI_API boost::format getFormat(const std::string& s); /// @return a pointer to the global loglevel setting QI_API LogLevel* globalLogLevelPtr(); // We will end up with one instance per module, but we don't care inline LogLevel globalLogLevel() { static LogLevel* l = globalLogLevelPtr(); return *l; } inline bool isVisible(Category* category, LogLevel level) { return level <= globalLogLevel() && level <= category->mainLevel; } } typedef detail::Category* category_type; class LogStream: public std::stringstream { public: LogStream(const LogLevel level, const char *file, const char *function, const int line, const char *category) : _logLevel(level) , _category(category) , _categoryType(0) , _file(file) , _function(function) , _line(line) { } LogStream(const LogLevel level, const char *file, const char *function, const int line, category_type category) : _logLevel(level) , _category(0) , _categoryType(category) , _file(file) , _function(function) , _line(line) { } LogStream(const LogLevel level, const char *file, const char *function, const int line, const char *category, const std::string& message) : _logLevel(level) , _category(category) , _categoryType(0) , _file(file) , _function(function) , _line(line) { *this << message; } ~LogStream() { if (!this->str().empty()) { if (_category) qi::log::log(_logLevel, _category, this->str().c_str(), _file, _function, _line); else qi::log::log(_logLevel, _categoryType, this->str(), _file, _function, _line); } } LogStream& self() { return *this; } private: LogLevel _logLevel; const char *_category; category_type _categoryType; const char *_file; const char *_function; int _line; //avoid copy LogStream(const LogStream &rhs); LogStream &operator=(const LogStream &rhs); }; } } #endif <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the qmake application of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "property.h" #include "option.h" #include <qdir.h> #include <qmap.h> #include <qsettings.h> #include <qstringlist.h> #include <stdio.h> QT_BEGIN_NAMESPACE QStringList qmake_mkspec_paths(); //project.cpp QMakeProperty::QMakeProperty() : settings(0) { } QMakeProperty::~QMakeProperty() { delete settings; settings = 0; } void QMakeProperty::initSettings() { if(!settings) { settings = new QSettings(QSettings::UserScope, "Trolltech", "QMake"); settings->setFallbacksEnabled(false); } } QString QMakeProperty::keyBase(bool version) const { if (version) return QString(qmake_version()) + "/"; return QString(); } QString QMakeProperty::value(QString v, bool just_check) { if(v == "QT_INSTALL_PREFIX") return QLibraryInfo::location(QLibraryInfo::PrefixPath); else if(v == "QT_INSTALL_DATA") return QLibraryInfo::location(QLibraryInfo::DataPath); else if(v == "QT_INSTALL_DOCS") return QLibraryInfo::location(QLibraryInfo::DocumentationPath); else if(v == "QT_INSTALL_HEADERS") return QLibraryInfo::location(QLibraryInfo::HeadersPath); else if(v == "QT_INSTALL_LIBS") return QLibraryInfo::location(QLibraryInfo::LibrariesPath); else if(v == "QT_INSTALL_BINS") return QLibraryInfo::location(QLibraryInfo::BinariesPath); else if(v == "QT_INSTALL_PLUGINS") return QLibraryInfo::location(QLibraryInfo::PluginsPath); else if(v == "QT_INSTALL_TRANSLATIONS") return QLibraryInfo::location(QLibraryInfo::TranslationsPath); else if(v == "QT_INSTALL_CONFIGURATION") return QLibraryInfo::location(QLibraryInfo::SettingsPath); else if(v == "QT_INSTALL_EXAMPLES") return QLibraryInfo::location(QLibraryInfo::ExamplesPath); else if(v == "QT_INSTALL_DEMOS") return QLibraryInfo::location(QLibraryInfo::DemosPath); else if(v == "QMAKE_MKSPECS") return qmake_mkspec_paths().join(Option::target_mode == Option::TARG_WIN_MODE ? ";" : ":"); else if(v == "QMAKE_VERSION") return qmake_version(); #ifdef QT_VERSION_STR else if(v == "QT_VERSION") return QT_VERSION_STR; #endif initSettings(); int slash = v.lastIndexOf('/'); QVariant var = settings->value(keyBase(slash == -1) + v); bool ok = var.isValid(); QString ret = var.toString(); if(!ok) { QString version = qmake_version(); if(slash != -1) { version = v.left(slash-1); v = v.mid(slash+1); } settings->beginGroup(keyBase(false)); QStringList subs = settings->childGroups(); settings->endGroup(); subs.sort(); for (int x = subs.count() - 1; x >= 0; x--) { QString s = subs[x]; if(s.isEmpty() || s > version) continue; var = settings->value(keyBase(false) + s + "/" + v); ok = var.isValid(); ret = var.toString(); if (ok) { if(!just_check) debug_msg(1, "Fell back from %s -> %s for '%s'.", version.toLatin1().constData(), s.toLatin1().constData(), v.toLatin1().constData()); return ret; } } } return ok ? ret : QString(); } bool QMakeProperty::hasValue(QString v) { return !value(v, true).isNull(); } void QMakeProperty::setValue(QString var, const QString &val) { initSettings(); settings->setValue(keyBase() + var, val); } bool QMakeProperty::exec() { bool ret = true; if(Option::qmake_mode == Option::QMAKE_QUERY_PROPERTY) { if(Option::prop::properties.isEmpty()) { initSettings(); settings->beginGroup(keyBase(false)); QStringList subs = settings->childGroups(); settings->endGroup(); subs.sort(); for(int x = subs.count() - 1; x >= 0; x--) { QString s = subs[x]; if(s.isEmpty()) continue; settings->beginGroup(keyBase(false) + s); QStringList keys = settings->childKeys(); settings->endGroup(); for(QStringList::ConstIterator it2 = keys.begin(); it2 != keys.end(); it2++) { QString ret = settings->value(keyBase(false) + s + "/" + (*it2)).toString(); if(s != qmake_version()) fprintf(stdout, "%s/", s.toLatin1().constData()); fprintf(stdout, "%s:%s\n", (*it2).toLatin1().constData(), ret.toLatin1().constData()); } } QStringList specialProps; specialProps.append("QT_INSTALL_PREFIX"); specialProps.append("QT_INSTALL_DATA"); specialProps.append("QT_INSTALL_DOCS"); specialProps.append("QT_INSTALL_HEADERS"); specialProps.append("QT_INSTALL_LIBS"); specialProps.append("QT_INSTALL_BINS"); specialProps.append("QT_INSTALL_PLUGINS"); specialProps.append("QT_INSTALL_TRANSLATIONS"); specialProps.append("QT_INSTALL_CONFIGURATION"); specialProps.append("QT_INSTALL_EXAMPLES"); specialProps.append("QT_INSTALL_DEMOS"); specialProps.append("QMAKE_MKSPECS"); specialProps.append("QMAKE_VERSION"); #ifdef QT_VERSION_STR specialProps.append("QT_VERSION"); #endif foreach (QString prop, specialProps) fprintf(stdout, "%s:%s\n", prop.toLatin1().constData(), value(prop).toLatin1().constData()); return true; } for(QStringList::ConstIterator it = Option::prop::properties.begin(); it != Option::prop::properties.end(); it++) { if(Option::prop::properties.count() > 1) fprintf(stdout, "%s:", (*it).toLatin1().constData()); if(!hasValue((*it))) { ret = false; fprintf(stdout, "**Unknown**\n"); } else { fprintf(stdout, "%s\n", value((*it)).toLatin1().constData()); } } } else if(Option::qmake_mode == Option::QMAKE_SET_PROPERTY) { for(QStringList::ConstIterator it = Option::prop::properties.begin(); it != Option::prop::properties.end(); it++) { QString var = (*it); it++; if(it == Option::prop::properties.end()) { ret = false; break; } if(!var.startsWith(".")) setValue(var, (*it)); } } return ret; } QT_END_NAMESPACE <commit_msg>simplify<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the qmake application of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "property.h" #include "option.h" #include <qdir.h> #include <qmap.h> #include <qsettings.h> #include <qstringlist.h> #include <stdio.h> QT_BEGIN_NAMESPACE QStringList qmake_mkspec_paths(); //project.cpp QMakeProperty::QMakeProperty() : settings(0) { } QMakeProperty::~QMakeProperty() { delete settings; settings = 0; } void QMakeProperty::initSettings() { if(!settings) { settings = new QSettings(QSettings::UserScope, "Trolltech", "QMake"); settings->setFallbacksEnabled(false); } } QString QMakeProperty::keyBase(bool version) const { if (version) return QString(qmake_version()) + "/"; return QString(); } QString QMakeProperty::value(QString v, bool just_check) { if(v == "QT_INSTALL_PREFIX") return QLibraryInfo::location(QLibraryInfo::PrefixPath); else if(v == "QT_INSTALL_DATA") return QLibraryInfo::location(QLibraryInfo::DataPath); else if(v == "QT_INSTALL_DOCS") return QLibraryInfo::location(QLibraryInfo::DocumentationPath); else if(v == "QT_INSTALL_HEADERS") return QLibraryInfo::location(QLibraryInfo::HeadersPath); else if(v == "QT_INSTALL_LIBS") return QLibraryInfo::location(QLibraryInfo::LibrariesPath); else if(v == "QT_INSTALL_BINS") return QLibraryInfo::location(QLibraryInfo::BinariesPath); else if(v == "QT_INSTALL_PLUGINS") return QLibraryInfo::location(QLibraryInfo::PluginsPath); else if(v == "QT_INSTALL_TRANSLATIONS") return QLibraryInfo::location(QLibraryInfo::TranslationsPath); else if(v == "QT_INSTALL_CONFIGURATION") return QLibraryInfo::location(QLibraryInfo::SettingsPath); else if(v == "QT_INSTALL_EXAMPLES") return QLibraryInfo::location(QLibraryInfo::ExamplesPath); else if(v == "QT_INSTALL_DEMOS") return QLibraryInfo::location(QLibraryInfo::DemosPath); else if(v == "QMAKE_MKSPECS") return qmake_mkspec_paths().join(Option::dirlist_sep); else if(v == "QMAKE_VERSION") return qmake_version(); #ifdef QT_VERSION_STR else if(v == "QT_VERSION") return QT_VERSION_STR; #endif initSettings(); int slash = v.lastIndexOf('/'); QVariant var = settings->value(keyBase(slash == -1) + v); bool ok = var.isValid(); QString ret = var.toString(); if(!ok) { QString version = qmake_version(); if(slash != -1) { version = v.left(slash-1); v = v.mid(slash+1); } settings->beginGroup(keyBase(false)); QStringList subs = settings->childGroups(); settings->endGroup(); subs.sort(); for (int x = subs.count() - 1; x >= 0; x--) { QString s = subs[x]; if(s.isEmpty() || s > version) continue; var = settings->value(keyBase(false) + s + "/" + v); ok = var.isValid(); ret = var.toString(); if (ok) { if(!just_check) debug_msg(1, "Fell back from %s -> %s for '%s'.", version.toLatin1().constData(), s.toLatin1().constData(), v.toLatin1().constData()); return ret; } } } return ok ? ret : QString(); } bool QMakeProperty::hasValue(QString v) { return !value(v, true).isNull(); } void QMakeProperty::setValue(QString var, const QString &val) { initSettings(); settings->setValue(keyBase() + var, val); } bool QMakeProperty::exec() { bool ret = true; if(Option::qmake_mode == Option::QMAKE_QUERY_PROPERTY) { if(Option::prop::properties.isEmpty()) { initSettings(); settings->beginGroup(keyBase(false)); QStringList subs = settings->childGroups(); settings->endGroup(); subs.sort(); for(int x = subs.count() - 1; x >= 0; x--) { QString s = subs[x]; if(s.isEmpty()) continue; settings->beginGroup(keyBase(false) + s); QStringList keys = settings->childKeys(); settings->endGroup(); for(QStringList::ConstIterator it2 = keys.begin(); it2 != keys.end(); it2++) { QString ret = settings->value(keyBase(false) + s + "/" + (*it2)).toString(); if(s != qmake_version()) fprintf(stdout, "%s/", s.toLatin1().constData()); fprintf(stdout, "%s:%s\n", (*it2).toLatin1().constData(), ret.toLatin1().constData()); } } QStringList specialProps; specialProps.append("QT_INSTALL_PREFIX"); specialProps.append("QT_INSTALL_DATA"); specialProps.append("QT_INSTALL_DOCS"); specialProps.append("QT_INSTALL_HEADERS"); specialProps.append("QT_INSTALL_LIBS"); specialProps.append("QT_INSTALL_BINS"); specialProps.append("QT_INSTALL_PLUGINS"); specialProps.append("QT_INSTALL_TRANSLATIONS"); specialProps.append("QT_INSTALL_CONFIGURATION"); specialProps.append("QT_INSTALL_EXAMPLES"); specialProps.append("QT_INSTALL_DEMOS"); specialProps.append("QMAKE_MKSPECS"); specialProps.append("QMAKE_VERSION"); #ifdef QT_VERSION_STR specialProps.append("QT_VERSION"); #endif foreach (QString prop, specialProps) fprintf(stdout, "%s:%s\n", prop.toLatin1().constData(), value(prop).toLatin1().constData()); return true; } for(QStringList::ConstIterator it = Option::prop::properties.begin(); it != Option::prop::properties.end(); it++) { if(Option::prop::properties.count() > 1) fprintf(stdout, "%s:", (*it).toLatin1().constData()); if(!hasValue((*it))) { ret = false; fprintf(stdout, "**Unknown**\n"); } else { fprintf(stdout, "%s\n", value((*it)).toLatin1().constData()); } } } else if(Option::qmake_mode == Option::QMAKE_SET_PROPERTY) { for(QStringList::ConstIterator it = Option::prop::properties.begin(); it != Option::prop::properties.end(); it++) { QString var = (*it); it++; if(it == Option::prop::properties.end()) { ret = false; break; } if(!var.startsWith(".")) setValue(var, (*it)); } } return ret; } QT_END_NAMESPACE <|endoftext|>
<commit_before>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html #include "formatter.hh" #include "main.hh" #include <cstring> namespace Rapicorn { namespace Lib { template<class... Args> static std::string system_string_printf (const char *format, Args... args) { char *cstr = NULL; int ret = asprintf (&cstr, format, args...); if (ret >= 0 && cstr) { std::string result = cstr; free (cstr); return result; } return format; } static bool parse_unsigned_integer (const char **stringp, uint64_t *up) { // '0' | [1-9] [0-9]* : <= 18446744073709551615 const char *p = *stringp; // zero if (*p == '0' && !(p[1] >= '0' && p[1] <= '9')) { *up = 0; *stringp = p + 1; return true; } // first digit if (!(*p >= '1' && *p <= '9')) return false; uint64_t u = *p - '0'; p++; // rest digits while (*p >= '0' && *p <= '9') { const uint64_t last = u; u = u * 10 + (*p - '0'); p++; if (u < last) // overflow return false; } *up = u; *stringp = p; return true; } static bool parse_positional (const char **stringp, uint64_t *ap) { // [0-9]+ '$' const char *p = *stringp; uint64_t ui64 = 0; if (parse_unsigned_integer (&p, &ui64) && *p == '$') { p++; *ap = ui64; *stringp = p; return true; } return false; } const char* StringFormatter::parse_directive (const char **stringp, size_t *indexp, Directive *dirp) { // '%' positional? [-+#0 '']* ([0-9]*|[*]positional?) ([.]([0-9]*|[*]positional?))? [hlLjztq]* [spmcdiouXxFfGgEeAa] const char *p = *stringp; size_t index = *indexp; Directive fdir; // '%' directive start if (*p != '%') return "missing '%' at start"; p++; // positional argument uint64_t ui64 = -1; if (parse_positional (&p, &ui64)) { if (ui64 > 0 && ui64 <= 2147483647) fdir.value_index = ui64; else return "invalid positional specification"; } // flags const char *flags = "-+#0 '"; while (strchr (flags, *p)) switch (*p) { case '-': fdir.adjust_left = true; goto default_case; case '+': fdir.add_sign = true; goto default_case; case '#': fdir.alternate_form = true; goto default_case; case '0': fdir.zero_padding = true; goto default_case; case ' ': fdir.add_space = true; goto default_case; case '\'': fdir.locale_grouping = true; goto default_case; default: default_case: p++; break; } // field width ui64 = 0; if (*p == '*') { p++; if (parse_positional (&p, &ui64)) { if (ui64 > 0 && ui64 <= 2147483647) fdir.width_index = ui64; else return "invalid positional specification"; } else fdir.width_index = index++; fdir.use_width = true; } else if (parse_unsigned_integer (&p, &ui64)) { if (ui64 <= 2147483647) fdir.field_width = ui64; else return "invalid field width specification"; fdir.use_width = true; } // precision if (*p == '.') { fdir.use_precision = true; p++; } if (*p == '*') { p++; if (parse_positional (&p, &ui64)) { if (ui64 > 0 && ui64 <= 2147483647) fdir.precision_index = ui64; else return "invalid positional specification"; } else fdir.precision_index = index++; } else if (parse_unsigned_integer (&p, &ui64)) { if (ui64 <= 2147483647) fdir.precision = ui64; else return "invalid precision specification"; } // modifiers const char *modifiers = "hlLjztq"; while (strchr (modifiers, *p)) p++; // conversion const char *conversion = "dioucspmXxEeFfGgAa%"; if (!strchr (conversion, *p)) return "missing conversion specifier"; if (fdir.value_index == 0 && !strchr ("m%", *p)) fdir.value_index = index++; fdir.conversion = *p++; // success *dirp = fdir; *indexp = index; *stringp = p; return NULL; // OK } // FIXME: support more sophisticated argument conversions uint32_t StringFormatter::arg_as_width (size_t nth) { int32_t w = arg_as_lluint (nth); w = ABS (w); return w < 0 ? ABS (w + 1) : w; // turn -2147483648 into +2147483647 } uint32_t StringFormatter::arg_as_precision (size_t nth) { const int32_t precision = arg_as_lluint (nth); return MAX (0, precision); } StringFormatter::LLUInt StringFormatter::arg_as_lluint (size_t nth) { return_unless (nth && nth <= nargs_, 0); return fargs_[nth-1].i; } StringFormatter::LDouble StringFormatter::arg_as_ldouble (size_t nth) { return_unless (nth && nth <= nargs_, 0); return fargs_[nth-1].d; } void* StringFormatter::arg_as_ptr (size_t nth) { return_unless (nth && nth <= nargs_, NULL); return fargs_[nth-1].p; } const char* StringFormatter::arg_as_chars (size_t nth) { return_unless (nth && nth <= nargs_, ""); return fargs_[nth-1].kind != 's' ? "" : fargs_[nth-1].s; } template<class Arg> std::string StringFormatter::render_arg (const Directive &dir, const char *modifier, Arg arg) { std::string result, format; const int field_width = !dir.use_width || !dir.width_index ? dir.field_width : arg_as_width (dir.width_index); const int field_precision = !dir.use_precision || !dir.precision_index ? MAX (0, dir.precision) : arg_as_precision (dir.precision_index); // format directive format += '%'; if (dir.adjust_left) format += '-'; if (dir.add_sign) format += '+'; if (dir.add_space) format += ' '; if (dir.zero_padding && !dir.adjust_left&& strchr ("diouXx" "FfGgEeAa", dir.conversion)) format += '0'; if (dir.alternate_form && strchr ("oXx" "FfGgEeAa", dir.conversion)) format += '#'; if (dir.locale_grouping && strchr ("idu" "FfGg", dir.conversion)) format += '\''; if (dir.use_width) format += '*'; if (dir.use_precision && strchr ("sm" "diouXx" "FfGgEeAa", dir.conversion)) // !cp format += ".*"; if (modifier) format += modifier; format += dir.conversion; // printf formatting if (dir.use_width && dir.use_precision) return system_string_printf (format.c_str(), field_width, field_precision, arg); else if (dir.use_precision) return system_string_printf (format.c_str(), field_precision, arg); else if (dir.use_width) return system_string_printf (format.c_str(), field_width, arg); else return system_string_printf (format.c_str(), arg); } std::string StringFormatter::render_directive (const Directive &dir) { switch (dir.conversion) { case 'm': return render_arg (dir, "", int (0)); // dummy arg to silence compiler case 'c': return render_arg (dir, "", int (arg_as_lluint (dir.value_index))); case 'p': return render_arg (dir, "", arg_as_ptr (dir.value_index)); case 's': // precision return render_arg (dir, "", arg_as_chars (dir.value_index)); case 'd': case 'i': case 'o': case 'u': case 'X': case 'x': return render_arg (dir, "ll", arg_as_lluint (dir.value_index)); case 'f': case 'F': case 'e': case 'E': case 'g': case 'G': case 'a': case 'A': return render_arg (dir, "L", arg_as_ldouble (dir.value_index)); case '%': return "%"; } return std::string ("%") + dir.conversion; } static inline size_t upper_directive_count (const char *format) { size_t n = 0; for (const char *p = format; *p; p++) if (p[0] == '%') // count %... { n++; if (p[1] == '%') // dont count %% twice p++; } return n; } std::string StringFormatter::render_format (const size_t last, const char *format) { assert (last == nargs_); // allocate enough space to hold all directives possibly contained in format const size_t max_dirs = 1 + upper_directive_count (format); Directive fdirs[max_dirs]; // parse format into Directive stack size_t nextarg = 1, ndirs = 0; const char *p = format; while (*p) { do { if (p[0] == '%') break; p++; } while (*p); if (*p == 0) break; const size_t start = p - format; const char *err = parse_directive (&p, &nextarg, &fdirs[ndirs]); if (err) return format_error (err, format, ndirs + 1); fdirs[ndirs].start = start; fdirs[ndirs].end = p - format; ndirs++; assert (ndirs < max_dirs); } const size_t argcounter = nextarg - 1; fdirs[ndirs].end = fdirs[ndirs].start = p - format; // check maximum argument reference and argument count size_t argmaxref = argcounter; for (size_t i = 0; i < ndirs; i++) { const Directive &fdir = fdirs[i]; argmaxref = MAX (argmaxref, fdir.value_index); argmaxref = MAX (argmaxref, fdir.width_index); argmaxref = MAX (argmaxref, fdir.precision_index); } if (argmaxref > last) return format_error ("too few arguments for format", format, 0); if (argmaxref < last) return format_error ("too many arguments for format", format, 0); // format pieces std::string result; p = format; for (size_t i = 0; i <= ndirs; i++) { const Directive &fdir = fdirs[i]; result += std::string (p, fdir.start - (p - format)); if (fdir.conversion) result += render_directive (fdir); p = format + fdir.end; } return result; } std::string StringFormatter::locale_format (const size_t last, const char *format) { if (locale_context_ == CURRENT_LOCALE) return render_format (last, format); else { ScopedPosixLocale posix_locale_scope; // pushes POSIX locale for this scope return render_format (last, format); } } std::string StringFormatter::format_error (const char *err, const char *format, size_t directive) { if (directive) fprintf (stderr, "error: %s in directive %zu: %s\n", err, directive, format); else fprintf (stderr, "error: %s: %s\n", err, format); return format; } } // Lib } // Rapicorn <commit_msg>RCORE: StringFormatter: handle "(null)" strings<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html #include "formatter.hh" #include "main.hh" #include <cstring> namespace Rapicorn { namespace Lib { template<class... Args> static std::string system_string_printf (const char *format, Args... args) { char *cstr = NULL; int ret = asprintf (&cstr, format, args...); if (ret >= 0 && cstr) { std::string result = cstr; free (cstr); return result; } return format; } static bool parse_unsigned_integer (const char **stringp, uint64_t *up) { // '0' | [1-9] [0-9]* : <= 18446744073709551615 const char *p = *stringp; // zero if (*p == '0' && !(p[1] >= '0' && p[1] <= '9')) { *up = 0; *stringp = p + 1; return true; } // first digit if (!(*p >= '1' && *p <= '9')) return false; uint64_t u = *p - '0'; p++; // rest digits while (*p >= '0' && *p <= '9') { const uint64_t last = u; u = u * 10 + (*p - '0'); p++; if (u < last) // overflow return false; } *up = u; *stringp = p; return true; } static bool parse_positional (const char **stringp, uint64_t *ap) { // [0-9]+ '$' const char *p = *stringp; uint64_t ui64 = 0; if (parse_unsigned_integer (&p, &ui64) && *p == '$') { p++; *ap = ui64; *stringp = p; return true; } return false; } const char* StringFormatter::parse_directive (const char **stringp, size_t *indexp, Directive *dirp) { // '%' positional? [-+#0 '']* ([0-9]*|[*]positional?) ([.]([0-9]*|[*]positional?))? [hlLjztq]* [spmcdiouXxFfGgEeAa] const char *p = *stringp; size_t index = *indexp; Directive fdir; // '%' directive start if (*p != '%') return "missing '%' at start"; p++; // positional argument uint64_t ui64 = -1; if (parse_positional (&p, &ui64)) { if (ui64 > 0 && ui64 <= 2147483647) fdir.value_index = ui64; else return "invalid positional specification"; } // flags const char *flags = "-+#0 '"; while (strchr (flags, *p)) switch (*p) { case '-': fdir.adjust_left = true; goto default_case; case '+': fdir.add_sign = true; goto default_case; case '#': fdir.alternate_form = true; goto default_case; case '0': fdir.zero_padding = true; goto default_case; case ' ': fdir.add_space = true; goto default_case; case '\'': fdir.locale_grouping = true; goto default_case; default: default_case: p++; break; } // field width ui64 = 0; if (*p == '*') { p++; if (parse_positional (&p, &ui64)) { if (ui64 > 0 && ui64 <= 2147483647) fdir.width_index = ui64; else return "invalid positional specification"; } else fdir.width_index = index++; fdir.use_width = true; } else if (parse_unsigned_integer (&p, &ui64)) { if (ui64 <= 2147483647) fdir.field_width = ui64; else return "invalid field width specification"; fdir.use_width = true; } // precision if (*p == '.') { fdir.use_precision = true; p++; } if (*p == '*') { p++; if (parse_positional (&p, &ui64)) { if (ui64 > 0 && ui64 <= 2147483647) fdir.precision_index = ui64; else return "invalid positional specification"; } else fdir.precision_index = index++; } else if (parse_unsigned_integer (&p, &ui64)) { if (ui64 <= 2147483647) fdir.precision = ui64; else return "invalid precision specification"; } // modifiers const char *modifiers = "hlLjztq"; while (strchr (modifiers, *p)) p++; // conversion const char *conversion = "dioucspmXxEeFfGgAa%"; if (!strchr (conversion, *p)) return "missing conversion specifier"; if (fdir.value_index == 0 && !strchr ("m%", *p)) fdir.value_index = index++; fdir.conversion = *p++; // success *dirp = fdir; *indexp = index; *stringp = p; return NULL; // OK } // FIXME: support more sophisticated argument conversions uint32_t StringFormatter::arg_as_width (size_t nth) { int32_t w = arg_as_lluint (nth); w = ABS (w); return w < 0 ? ABS (w + 1) : w; // turn -2147483648 into +2147483647 } uint32_t StringFormatter::arg_as_precision (size_t nth) { const int32_t precision = arg_as_lluint (nth); return MAX (0, precision); } StringFormatter::LLUInt StringFormatter::arg_as_lluint (size_t nth) { return_unless (nth && nth <= nargs_, 0); return fargs_[nth-1].i; } StringFormatter::LDouble StringFormatter::arg_as_ldouble (size_t nth) { return_unless (nth && nth <= nargs_, 0); return fargs_[nth-1].d; } void* StringFormatter::arg_as_ptr (size_t nth) { return_unless (nth && nth <= nargs_, NULL); return fargs_[nth-1].p; } const char* StringFormatter::arg_as_chars (size_t nth) { return_unless (nth && nth <= nargs_, ""); if ((fargs_[nth-1].kind == 's' || fargs_[nth-1].kind == 'p') && fargs_[nth-1].p == NULL) return "(null)"; return fargs_[nth-1].kind != 's' ? "" : fargs_[nth-1].s; } template<class Arg> std::string StringFormatter::render_arg (const Directive &dir, const char *modifier, Arg arg) { std::string result, format; const int field_width = !dir.use_width || !dir.width_index ? dir.field_width : arg_as_width (dir.width_index); const int field_precision = !dir.use_precision || !dir.precision_index ? MAX (0, dir.precision) : arg_as_precision (dir.precision_index); // format directive format += '%'; if (dir.adjust_left) format += '-'; if (dir.add_sign) format += '+'; if (dir.add_space) format += ' '; if (dir.zero_padding && !dir.adjust_left&& strchr ("diouXx" "FfGgEeAa", dir.conversion)) format += '0'; if (dir.alternate_form && strchr ("oXx" "FfGgEeAa", dir.conversion)) format += '#'; if (dir.locale_grouping && strchr ("idu" "FfGg", dir.conversion)) format += '\''; if (dir.use_width) format += '*'; if (dir.use_precision && strchr ("sm" "diouXx" "FfGgEeAa", dir.conversion)) // !cp format += ".*"; if (modifier) format += modifier; format += dir.conversion; // printf formatting if (dir.use_width && dir.use_precision) return system_string_printf (format.c_str(), field_width, field_precision, arg); else if (dir.use_precision) return system_string_printf (format.c_str(), field_precision, arg); else if (dir.use_width) return system_string_printf (format.c_str(), field_width, arg); else return system_string_printf (format.c_str(), arg); } std::string StringFormatter::render_directive (const Directive &dir) { switch (dir.conversion) { case 'm': return render_arg (dir, "", int (0)); // dummy arg to silence compiler case 'c': return render_arg (dir, "", int (arg_as_lluint (dir.value_index))); case 'p': return render_arg (dir, "", arg_as_ptr (dir.value_index)); case 's': // precision return render_arg (dir, "", arg_as_chars (dir.value_index)); case 'd': case 'i': case 'o': case 'u': case 'X': case 'x': return render_arg (dir, "ll", arg_as_lluint (dir.value_index)); case 'f': case 'F': case 'e': case 'E': case 'g': case 'G': case 'a': case 'A': return render_arg (dir, "L", arg_as_ldouble (dir.value_index)); case '%': return "%"; } return std::string ("%") + dir.conversion; } static inline size_t upper_directive_count (const char *format) { size_t n = 0; for (const char *p = format; *p; p++) if (p[0] == '%') // count %... { n++; if (p[1] == '%') // dont count %% twice p++; } return n; } std::string StringFormatter::render_format (const size_t last, const char *format) { assert (last == nargs_); // allocate enough space to hold all directives possibly contained in format const size_t max_dirs = 1 + upper_directive_count (format); Directive fdirs[max_dirs]; // parse format into Directive stack size_t nextarg = 1, ndirs = 0; const char *p = format; while (*p) { do { if (p[0] == '%') break; p++; } while (*p); if (*p == 0) break; const size_t start = p - format; const char *err = parse_directive (&p, &nextarg, &fdirs[ndirs]); if (err) return format_error (err, format, ndirs + 1); fdirs[ndirs].start = start; fdirs[ndirs].end = p - format; ndirs++; assert (ndirs < max_dirs); } const size_t argcounter = nextarg - 1; fdirs[ndirs].end = fdirs[ndirs].start = p - format; // check maximum argument reference and argument count size_t argmaxref = argcounter; for (size_t i = 0; i < ndirs; i++) { const Directive &fdir = fdirs[i]; argmaxref = MAX (argmaxref, fdir.value_index); argmaxref = MAX (argmaxref, fdir.width_index); argmaxref = MAX (argmaxref, fdir.precision_index); } if (argmaxref > last) return format_error ("too few arguments for format", format, 0); if (argmaxref < last) return format_error ("too many arguments for format", format, 0); // format pieces std::string result; p = format; for (size_t i = 0; i <= ndirs; i++) { const Directive &fdir = fdirs[i]; result += std::string (p, fdir.start - (p - format)); if (fdir.conversion) result += render_directive (fdir); p = format + fdir.end; } return result; } std::string StringFormatter::locale_format (const size_t last, const char *format) { if (locale_context_ == CURRENT_LOCALE) return render_format (last, format); else { ScopedPosixLocale posix_locale_scope; // pushes POSIX locale for this scope return render_format (last, format); } } std::string StringFormatter::format_error (const char *err, const char *format, size_t directive) { if (directive) fprintf (stderr, "error: %s in directive %zu: %s\n", err, directive, format); else fprintf (stderr, "error: %s: %s\n", err, format); return format; } } // Lib } // Rapicorn <|endoftext|>
<commit_before>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html #ifndef __RAPICORN_THREADLIB_HH__ #define __RAPICORN_THREADLIB_HH__ #include <condition_variable> namespace Rapicorn { namespace Lib { #define RAPICORN_MFENCE __sync_synchronize() ///< Memory Fence - prevent processor (and compiler) from reordering loads/stores (read/write barrier). #define RAPICORN_SFENCE RAPICORN_X86SFENCE ///< Store Fence - prevent processor (and compiler) from reordering stores (read barrier). #define RAPICORN_LFENCE RAPICORN_X86LFENCE ///< Load Fence - prevent processor (and compiler) from reordering loads (read barrier). #define RAPICORN_CFENCE __asm__ __volatile__ ("" ::: "memory") ///< Compiler Fence, prevent compiler from reordering non-volatiles loads/stores. #define RAPICORN_X86LFENCE __asm__ __volatile__ ("lfence" ::: "memory") ///< X86 lfence - prevent processor from reordering loads (read barrier). #define RAPICORN_X86SFENCE __asm__ __volatile__ ("sfence" ::: "memory") ///< X86 sfence - prevent processor from reordering stores (write barrier). template<typename T> T atomic_load (T volatile *p) { RAPICORN_CFENCE; T t = *p; RAPICORN_LFENCE; return t; } template<typename T> void atomic_store (T volatile *p, T i) { RAPICORN_SFENCE; *p = i; RAPICORN_CFENCE; } template<typename T> class Atomic { T volatile v; // FIXME /*ctor*/ Atomic () = delete; protected: constexpr Atomic () : v () {} constexpr Atomic (T i) : v (i) {} Atomic<T>& operator=(Atomic<T> &o) { store (o.load()); return *this; } Atomic<T> volatile& operator=(Atomic<T> &o) volatile { store (o.load()); return *this; } public: T load () const volatile { return atomic_load (&v); } void store (T i) volatile { atomic_store (&v, i); } bool cas (T o, T n) volatile { return __sync_bool_compare_and_swap (&v, o, n); } T operator+=(T i) volatile { return __sync_add_and_fetch (&v, i); } T operator-=(T i) volatile { return __sync_sub_and_fetch (&v, i); } T operator&=(T i) volatile { return __sync_and_and_fetch (&v, i); } T operator^=(T i) volatile { return __sync_xor_and_fetch (&v, i); } T operator|=(T i) volatile { return __sync_or_and_fetch (&v, i); } T operator++() volatile { return __sync_add_and_fetch (&v, 1); } T operator++(int) volatile { return __sync_fetch_and_add (&v, 1); } T operator--() volatile { return __sync_sub_and_fetch (&v, 1); } T operator--(int) volatile { return __sync_fetch_and_sub (&v, 1); } void operator= (T i) volatile { store (i); } operator T () const volatile { return load(); } }; #define RAPICORN_NEW_ONCE(pointer_variable) \ ({ typeof (pointer_variable) *___vp = &pointer_variable; \ while (once_enter (___vp)) { once_leave (___vp, new typeof (**___vp)); } *___vp; }) void once_list_enter (); bool once_list_bounce (volatile void *ptr); bool once_list_leave (volatile void *ptr); template<class Value> inline bool once_enter (volatile Value *value_location) { if (RAPICORN_LIKELY (atomic_load (value_location) != 0)) return false; else { once_list_enter(); const bool initialized = atomic_load (value_location) != 0; const bool needs_init = once_list_bounce (initialized ? NULL : value_location); return needs_init; } } template<class Value> inline void once_leave (volatile Value *value_location, Value initialization_value) { RAPICORN_RETURN_UNLESS (atomic_load (value_location) == 0); RAPICORN_RETURN_UNLESS (initialization_value != 0); atomic_store (value_location, initialization_value); const bool found_and_removed = once_list_leave (value_location); RAPICORN_RETURN_UNLESS (found_and_removed == true); } } // Lib } // Rapicorn #endif // __RAPICORN_THREADLIB_HH__ <commit_msg>RCORE: fixed useless ctor<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html #ifndef __RAPICORN_THREADLIB_HH__ #define __RAPICORN_THREADLIB_HH__ #include <condition_variable> namespace Rapicorn { namespace Lib { #define RAPICORN_MFENCE __sync_synchronize() ///< Memory Fence - prevent processor (and compiler) from reordering loads/stores (read/write barrier). #define RAPICORN_SFENCE RAPICORN_X86SFENCE ///< Store Fence - prevent processor (and compiler) from reordering stores (read barrier). #define RAPICORN_LFENCE RAPICORN_X86LFENCE ///< Load Fence - prevent processor (and compiler) from reordering loads (read barrier). #define RAPICORN_CFENCE __asm__ __volatile__ ("" ::: "memory") ///< Compiler Fence, prevent compiler from reordering non-volatiles loads/stores. #define RAPICORN_X86LFENCE __asm__ __volatile__ ("lfence" ::: "memory") ///< X86 lfence - prevent processor from reordering loads (read barrier). #define RAPICORN_X86SFENCE __asm__ __volatile__ ("sfence" ::: "memory") ///< X86 sfence - prevent processor from reordering stores (write barrier). template<typename T> T atomic_load (T volatile *p) { RAPICORN_CFENCE; T t = *p; RAPICORN_LFENCE; return t; } template<typename T> void atomic_store (T volatile *p, T i) { RAPICORN_SFENCE; *p = i; RAPICORN_CFENCE; } template<typename T> class Atomic { T volatile v; /*ctor*/ Atomic () = delete; protected: constexpr Atomic (T i) : v (i) {} Atomic<T>& operator=(Atomic<T> &o) { store (o.load()); return *this; } Atomic<T> volatile& operator=(Atomic<T> &o) volatile { store (o.load()); return *this; } public: T load () const volatile { return atomic_load (&v); } void store (T i) volatile { atomic_store (&v, i); } bool cas (T o, T n) volatile { return __sync_bool_compare_and_swap (&v, o, n); } T operator+=(T i) volatile { return __sync_add_and_fetch (&v, i); } T operator-=(T i) volatile { return __sync_sub_and_fetch (&v, i); } T operator&=(T i) volatile { return __sync_and_and_fetch (&v, i); } T operator^=(T i) volatile { return __sync_xor_and_fetch (&v, i); } T operator|=(T i) volatile { return __sync_or_and_fetch (&v, i); } T operator++() volatile { return __sync_add_and_fetch (&v, 1); } T operator++(int) volatile { return __sync_fetch_and_add (&v, 1); } T operator--() volatile { return __sync_sub_and_fetch (&v, 1); } T operator--(int) volatile { return __sync_fetch_and_sub (&v, 1); } void operator= (T i) volatile { store (i); } operator T () const volatile { return load(); } }; #define RAPICORN_NEW_ONCE(pointer_variable) \ ({ typeof (pointer_variable) *___vp = &pointer_variable; \ while (once_enter (___vp)) { once_leave (___vp, new typeof (**___vp)); } *___vp; }) void once_list_enter (); bool once_list_bounce (volatile void *ptr); bool once_list_leave (volatile void *ptr); template<class Value> inline bool once_enter (volatile Value *value_location) { if (RAPICORN_LIKELY (atomic_load (value_location) != 0)) return false; else { once_list_enter(); const bool initialized = atomic_load (value_location) != 0; const bool needs_init = once_list_bounce (initialized ? NULL : value_location); return needs_init; } } template<class Value> inline void once_leave (volatile Value *value_location, Value initialization_value) { RAPICORN_RETURN_UNLESS (atomic_load (value_location) == 0); RAPICORN_RETURN_UNLESS (initialization_value != 0); atomic_store (value_location, initialization_value); const bool found_and_removed = once_list_leave (value_location); RAPICORN_RETURN_UNLESS (found_and_removed == true); } } // Lib } // Rapicorn #endif // __RAPICORN_THREADLIB_HH__ <|endoftext|>
<commit_before>08e9ff38-2e4d-11e5-9284-b827eb9e62be<commit_msg>08ef0eb0-2e4d-11e5-9284-b827eb9e62be<commit_after>08ef0eb0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>5ce64adc-2e4e-11e5-9284-b827eb9e62be<commit_msg>5ceb4870-2e4e-11e5-9284-b827eb9e62be<commit_after>5ceb4870-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0ab57d4a-2e4f-11e5-9284-b827eb9e62be<commit_msg>0aba9532-2e4f-11e5-9284-b827eb9e62be<commit_after>0aba9532-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ff70847c-2e4c-11e5-9284-b827eb9e62be<commit_msg>ff7581e8-2e4c-11e5-9284-b827eb9e62be<commit_after>ff7581e8-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>5e0fce98-2e4d-11e5-9284-b827eb9e62be<commit_msg>5e14d7ee-2e4d-11e5-9284-b827eb9e62be<commit_after>5e14d7ee-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>176583f2-2e4d-11e5-9284-b827eb9e62be<commit_msg>176a9aae-2e4d-11e5-9284-b827eb9e62be<commit_after>176a9aae-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f070c46e-2e4c-11e5-9284-b827eb9e62be<commit_msg>f075fd62-2e4c-11e5-9284-b827eb9e62be<commit_after>f075fd62-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>286c0ec8-2e4d-11e5-9284-b827eb9e62be<commit_msg>287110da-2e4d-11e5-9284-b827eb9e62be<commit_after>287110da-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0bf1fc1a-2e4f-11e5-9284-b827eb9e62be<commit_msg>0bf6f33c-2e4f-11e5-9284-b827eb9e62be<commit_after>0bf6f33c-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>12b3914a-2e4e-11e5-9284-b827eb9e62be<commit_msg>12b8ca84-2e4e-11e5-9284-b827eb9e62be<commit_after>12b8ca84-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>db06f5d8-2e4e-11e5-9284-b827eb9e62be<commit_msg>db0bea7a-2e4e-11e5-9284-b827eb9e62be<commit_after>db0bea7a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>865c3116-2e4d-11e5-9284-b827eb9e62be<commit_msg>86612734-2e4d-11e5-9284-b827eb9e62be<commit_after>86612734-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>26d75742-2e4e-11e5-9284-b827eb9e62be<commit_msg>26dc621e-2e4e-11e5-9284-b827eb9e62be<commit_after>26dc621e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f5592e74-2e4e-11e5-9284-b827eb9e62be<commit_msg>f55e2802-2e4e-11e5-9284-b827eb9e62be<commit_after>f55e2802-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>578de6c2-2e4d-11e5-9284-b827eb9e62be<commit_msg>5792e9f6-2e4d-11e5-9284-b827eb9e62be<commit_after>5792e9f6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>edce134a-2e4e-11e5-9284-b827eb9e62be<commit_msg>edd3062a-2e4e-11e5-9284-b827eb9e62be<commit_after>edd3062a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>975e2924-2e4d-11e5-9284-b827eb9e62be<commit_msg>97631eb6-2e4d-11e5-9284-b827eb9e62be<commit_after>97631eb6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3b121afc-2e4f-11e5-9284-b827eb9e62be<commit_msg>3b17738a-2e4f-11e5-9284-b827eb9e62be<commit_after>3b17738a-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1c4a2f6c-2e4d-11e5-9284-b827eb9e62be<commit_msg>1c4f5866-2e4d-11e5-9284-b827eb9e62be<commit_after>1c4f5866-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e5d8d61c-2e4d-11e5-9284-b827eb9e62be<commit_msg>e5dde03a-2e4d-11e5-9284-b827eb9e62be<commit_after>e5dde03a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d2311436-2e4c-11e5-9284-b827eb9e62be<commit_msg>d2362516-2e4c-11e5-9284-b827eb9e62be<commit_after>d2362516-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>5c035fb6-2e4d-11e5-9284-b827eb9e62be<commit_msg>5c08602e-2e4d-11e5-9284-b827eb9e62be<commit_after>5c08602e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f3df0d84-2e4e-11e5-9284-b827eb9e62be<commit_msg>f3e40cee-2e4e-11e5-9284-b827eb9e62be<commit_after>f3e40cee-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>02288182-2e4e-11e5-9284-b827eb9e62be<commit_msg>022d7ade-2e4e-11e5-9284-b827eb9e62be<commit_after>022d7ade-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a5fe145c-2e4e-11e5-9284-b827eb9e62be<commit_msg>a6032870-2e4e-11e5-9284-b827eb9e62be<commit_after>a6032870-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b069767a-2e4e-11e5-9284-b827eb9e62be<commit_msg>b06e73c8-2e4e-11e5-9284-b827eb9e62be<commit_after>b06e73c8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>4b9d87dc-2e4d-11e5-9284-b827eb9e62be<commit_msg>4ba2b22a-2e4d-11e5-9284-b827eb9e62be<commit_after>4ba2b22a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a2e35184-2e4d-11e5-9284-b827eb9e62be<commit_msg>a2e84734-2e4d-11e5-9284-b827eb9e62be<commit_after>a2e84734-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>56e8280e-2e4d-11e5-9284-b827eb9e62be<commit_msg>56ed3416-2e4d-11e5-9284-b827eb9e62be<commit_after>56ed3416-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ec80d442-2e4d-11e5-9284-b827eb9e62be<commit_msg>ec85e414-2e4d-11e5-9284-b827eb9e62be<commit_after>ec85e414-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2badc72a-2e4d-11e5-9284-b827eb9e62be<commit_msg>2bb2bb40-2e4d-11e5-9284-b827eb9e62be<commit_after>2bb2bb40-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b0651186-2e4c-11e5-9284-b827eb9e62be<commit_msg>b06e6b50-2e4c-11e5-9284-b827eb9e62be<commit_after>b06e6b50-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f0d140fe-2e4d-11e5-9284-b827eb9e62be<commit_msg>f0d657c4-2e4d-11e5-9284-b827eb9e62be<commit_after>f0d657c4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2a2dd096-2e4f-11e5-9284-b827eb9e62be<commit_msg>2a41f24c-2e4f-11e5-9284-b827eb9e62be<commit_after>2a41f24c-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>cd96725e-2e4c-11e5-9284-b827eb9e62be<commit_msg>cd9b670a-2e4c-11e5-9284-b827eb9e62be<commit_after>cd9b670a-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>7f8cee92-2e4e-11e5-9284-b827eb9e62be<commit_msg>7f91f46e-2e4e-11e5-9284-b827eb9e62be<commit_after>7f91f46e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>