text
stringlengths
54
60.6k
<commit_before>/* * Author(s): * - Chris Kilner <[email protected]> * - Cedric Gestes <[email protected]> * * Copyright (C) 2010 Aldebaran Robotics */ #include "src/messaging/network/ip_address.hpp" #include <boost/algorithm/string.hpp> #ifdef _WIN32 # include <windows.h> # include <winsock2.h> # include <iphlpapi.h> # include <Ws2tcpip.h> #else # include <arpa/inet.h> # include <sys/socket.h> # include <netdb.h> # include <ifaddrs.h> # include <stdio.h> # include <stdlib.h> # include <unistd.h> #endif namespace qi { namespace detail { std::string getPrimaryPublicIPAddress() { std::vector<std::string> ips = getIPAddresses(); static const std::string ipLocalHost = "127.0.0.1"; // todo: some logic to choose between good addresses for (unsigned int i = 0; i< ips.size(); i++) { if (ipLocalHost.compare(ips[i]) != 0) return ips[i]; } return ""; } bool isValidAddress(const std::string& userHostString, Address& outAddress) { if (userHostString.empty()) return false; std::vector<std::string> parts; boost::split(parts, userHostString, boost::is_any_of(":/")); std::vector<std::string>::iterator i = parts.begin(); while (i != parts.end()) { if (i->empty()) parts.erase(i); else ++i; } if (parts.size() <= 2) parts.insert(parts.begin(), "tcp"); if (parts.size() < 2 || parts.size() > 3) return false; if (parts[1].empty()) return false; outAddress.transport = parts[0]; outAddress.address = parts[1]; if (parts.size() == 3) { outAddress.port = atoi(parts[2].c_str()); } else { outAddress.port = 0; parts.push_back("0"); // hmmm } return isValidHostAndPort(outAddress.address, parts[2]); } bool isValidHostAndPort(const std::string& hostName, std::string& port) { bool ret = true; #ifdef _WIN32 WSADATA WSAData; if(::WSAStartup(MAKEWORD(1, 0), &WSAData)) ret = false; #endif addrinfo req; memset(&req, 0, sizeof(req)); req.ai_family = AF_INET; req.ai_socktype = SOCK_STREAM; req.ai_flags = AI_NUMERICSERV; addrinfo *res; if(getaddrinfo(hostName.c_str(), port.c_str(), &req, &res)) ret = false; // lookup failed else { if (res == NULL) ret = false; else freeaddrinfo(res); } #ifdef _WIN32 WSACleanup(); #endif return ret; } std::vector<std::string> getIPAddresses() { std::vector<std::string> ret; #ifdef _WIN32 // win version char szHostName[128] = ""; WSADATA WSAData; if(::WSAStartup(MAKEWORD(1, 0), &WSAData)) return ret; if(::gethostname(szHostName, sizeof(szHostName))) return ret; struct sockaddr_in socketAddress; struct hostent* host = 0; host = ::gethostbyname(szHostName); if(!host) return ret; for(int i = 0; ((host->h_addr_list[i]) && (i < 10)); ++i) { memcpy(&socketAddress.sin_addr, host->h_addr_list[i], host->h_length); ret.push_back(inet_ntoa(socketAddress.sin_addr)); } WSACleanup(); #else // linux version struct ifaddrs *ifaddr, *ifa; int family, s; char host[NI_MAXHOST]; if (getifaddrs(&ifaddr) == -1) return ret; for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; family = ifa->ifa_addr->sa_family; // Don't include AF_INET6 for the moment if (family == AF_INET) { s = getnameinfo(ifa->ifa_addr, (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); if (s != 0) break; ret.push_back(host); } } freeifaddrs(ifaddr); #endif return ret; } } // namespace detail } // namespace qi <commit_msg>Split isValidAddress to have splitAddress<commit_after>/* * Author(s): * - Chris Kilner <[email protected]> * - Cedric Gestes <[email protected]> * * Copyright (C) 2010 Aldebaran Robotics */ #include "src/messaging/network/ip_address.hpp" #include <boost/algorithm/string.hpp> #ifdef _WIN32 # include <windows.h> # include <winsock2.h> # include <iphlpapi.h> # include <Ws2tcpip.h> #else # include <arpa/inet.h> # include <sys/socket.h> # include <netdb.h> # include <ifaddrs.h> # include <stdio.h> # include <stdlib.h> # include <unistd.h> #endif namespace qi { namespace detail { std::string getPrimaryPublicIPAddress() { std::vector<std::string> ips = getIPAddresses(); static const std::string ipLocalHost = "127.0.0.1"; // todo: some logic to choose between good addresses for (unsigned int i = 0; i< ips.size(); i++) { if (ipLocalHost.compare(ips[i]) != 0) return ips[i]; } return ""; } bool splitAddress(const std::string& userHostString, Address& outAddress, std::vector<std::string>& parts) { if (userHostString.empty()) return false; boost::split(parts, userHostString, boost::is_any_of(":/")); std::vector<std::string>::iterator i = parts.begin(); while (i != parts.end()) { if (i->empty()) parts.erase(i); else ++i; } if (parts.size() <= 2) parts.insert(parts.begin(), "tcp"); if (parts.size() < 2 || parts.size() > 3) return false; if (parts[1].empty()) return false; outAddress.transport = parts[0]; outAddress.address = parts[1]; if (parts.size() == 3) { outAddress.port = atoi(parts[2].c_str()); } else { outAddress.port = 0; parts.push_back("0"); // Hmm... shameless hack! } return true; } bool isValidAddress(const std::string& userHostString, Address& outAddress) { std::vector<std::string> parts; if (!splitAddress(userHostString, outAddress, parts)) return false; return isValidHostAndPort(outAddress.address, parts[2]); } bool isValidHostAndPort(const std::string& hostName, std::string& port) { bool ret = true; #ifdef _WIN32 WSADATA WSAData; if(::WSAStartup(MAKEWORD(1, 0), &WSAData)) ret = false; #endif addrinfo req; memset(&req, 0, sizeof(req)); req.ai_family = AF_INET; req.ai_socktype = SOCK_STREAM; req.ai_flags = AI_NUMERICSERV; addrinfo *res; if(getaddrinfo(hostName.c_str(), port.c_str(), &req, &res)) ret = false; // lookup failed else { if (res == NULL) ret = false; else freeaddrinfo(res); } #ifdef _WIN32 WSACleanup(); #endif return ret; } std::vector<std::string> getIPAddresses() { std::vector<std::string> ret; #ifdef _WIN32 // win version char szHostName[128] = ""; WSADATA WSAData; if(::WSAStartup(MAKEWORD(1, 0), &WSAData)) return ret; if(::gethostname(szHostName, sizeof(szHostName))) return ret; struct sockaddr_in socketAddress; struct hostent* host = 0; host = ::gethostbyname(szHostName); if(!host) return ret; for(int i = 0; ((host->h_addr_list[i]) && (i < 10)); ++i) { memcpy(&socketAddress.sin_addr, host->h_addr_list[i], host->h_length); ret.push_back(inet_ntoa(socketAddress.sin_addr)); } WSACleanup(); #else // linux version struct ifaddrs *ifaddr, *ifa; int family, s; char host[NI_MAXHOST]; if (getifaddrs(&ifaddr) == -1) return ret; for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; family = ifa->ifa_addr->sa_family; // Don't include AF_INET6 for the moment if (family == AF_INET) { s = getnameinfo(ifa->ifa_addr, (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); if (s != 0) break; ret.push_back(host); } } freeifaddrs(ifaddr); #endif return ret; } } // namespace detail } // namespace qi <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "base/message_loop.h" #include "chrome/browser/browser.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/renderer_host/web_cache_manager.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "testing/gtest/include/gtest/gtest.h" class WebCacheManagerBrowserTest : public InProcessBrowserTest { }; // Regression test for http://crbug.com/12362. If a renderer crashes and the // user navigates to another tab and back, the browser doesn't crash. // TODO(jam): http://crbug.com/15288 disabled because it fails on the build bot. IN_PROC_BROWSER_TEST_F(WebCacheManagerBrowserTest, DISABLED_CrashOnceOnly) { const FilePath kTestDir(FILE_PATH_LITERAL("google")); const FilePath kTestFile(FILE_PATH_LITERAL("google.html")); GURL url(ui_test_utils::GetTestUrl(kTestDir, kTestFile)); ui_test_utils::NavigateToURL(browser(), url); browser()->NewTab(); ui_test_utils::NavigateToURL(browser(), url); TabContents* tab = browser()->GetTabContentsAt(0); ASSERT_TRUE(tab != NULL); base::KillProcess(tab->GetRenderProcessHost()->GetHandle(), base::PROCESS_END_KILLED_BY_USER, true); browser()->SelectTabContentsAt(0, true); browser()->NewTab(); ui_test_utils::NavigateToURL(browser(), url); browser()->SelectTabContentsAt(0, true); browser()->NewTab(); ui_test_utils::NavigateToURL(browser(), url); // We would have crashed at the above line with the bug. browser()->SelectTabContentsAt(0, true); browser()->CloseTab(); browser()->SelectTabContentsAt(0, true); browser()->CloseTab(); browser()->SelectTabContentsAt(0, true); browser()->CloseTab(); ui_test_utils::NavigateToURL(browser(), url); EXPECT_EQ( WebCacheManager::GetInstance()->active_renderers_.size(), 1U); EXPECT_EQ( WebCacheManager::GetInstance()->inactive_renderers_.size(), 0U); EXPECT_EQ( WebCacheManager::GetInstance()->stats_.size(), 1U); } <commit_msg>TTF: Re-enable WebCacheManagerBrowserTest.CrashOnceOnly by marking it flaky.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "base/message_loop.h" #include "chrome/browser/browser.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/renderer_host/web_cache_manager.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "testing/gtest/include/gtest/gtest.h" class WebCacheManagerBrowserTest : public InProcessBrowserTest { }; // Regression test for http://crbug.com/12362. If a renderer crashes and the // user navigates to another tab and back, the browser doesn't crash. // Flaky, http://crbug.com/15288. IN_PROC_BROWSER_TEST_F(WebCacheManagerBrowserTest, FLAKY_CrashOnceOnly) { const FilePath kTestDir(FILE_PATH_LITERAL("google")); const FilePath kTestFile(FILE_PATH_LITERAL("google.html")); GURL url(ui_test_utils::GetTestUrl(kTestDir, kTestFile)); ui_test_utils::NavigateToURL(browser(), url); browser()->NewTab(); ui_test_utils::NavigateToURL(browser(), url); TabContents* tab = browser()->GetTabContentsAt(0); ASSERT_TRUE(tab != NULL); base::KillProcess(tab->GetRenderProcessHost()->GetHandle(), base::PROCESS_END_KILLED_BY_USER, true); browser()->SelectTabContentsAt(0, true); browser()->NewTab(); ui_test_utils::NavigateToURL(browser(), url); browser()->SelectTabContentsAt(0, true); browser()->NewTab(); ui_test_utils::NavigateToURL(browser(), url); // We would have crashed at the above line with the bug. browser()->SelectTabContentsAt(0, true); browser()->CloseTab(); browser()->SelectTabContentsAt(0, true); browser()->CloseTab(); browser()->SelectTabContentsAt(0, true); browser()->CloseTab(); ui_test_utils::NavigateToURL(browser(), url); EXPECT_EQ( WebCacheManager::GetInstance()->active_renderers_.size(), 1U); EXPECT_EQ( WebCacheManager::GetInstance()->inactive_renderers_.size(), 0U); EXPECT_EQ( WebCacheManager::GetInstance()->stats_.size(), 1U); } <|endoftext|>
<commit_before>/* * This file is part of meego-keyboard * * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * Contact: Nokia Corporation ([email protected]) * * If you have questions regarding the use of this file, please contact * Nokia at [email protected]. * * 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 * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "horizontalswitcher.h" #include <QGraphicsSceneResizeEvent> #include <QGraphicsScene> #include <QDebug> namespace { const int SwitchDuration = 500; const int SwitchFrames = 300; } HorizontalSwitcher::HorizontalSwitcher(QGraphicsItem *parent) : QGraphicsWidget(parent), currentIndex(-1), animTimeLine(SwitchDuration), loopingEnabled(false), playAnimations(true) { setFlag(QGraphicsItem::ItemHasNoContents); // doesn't paint itself anything setObjectName("HorizontalSwitcher"); animTimeLine.setFrameRange(0, SwitchFrames); enterAnim.setTimeLine(&animTimeLine); leaveAnim.setTimeLine(&animTimeLine); connect(&animTimeLine, SIGNAL(finished()), this, SLOT(finishAnimation())); } HorizontalSwitcher::~HorizontalSwitcher() { if (isRunning()) finishAnimation(); // Delete all widgets that were not removed with removeWidget(). qDeleteAll(slides); slides.clear(); } void HorizontalSwitcher::switchTo(SwitchDirection direction) { if (isRunning()) { finishAnimation(); } if (slides.count() < 2 || (!loopingEnabled && isAtBoundary(direction))) { return; } int newIndex = (direction == Left ? (currentIndex - 1) : (currentIndex + 1) % slides.count()); if (newIndex < 0) { newIndex += slides.count(); } QGraphicsWidget *currentWidget = slides.at(currentIndex); QGraphicsWidget *nextWidget = slides.at(newIndex); // Current item is about to leave leaveAnim.setItem(currentWidget); // New item is about to enter enterAnim.setItem(nextWidget); // Try to fit current size. nextWidget->resize(size()); currentIndex = newIndex; emit switchStarting(currentIndex, newIndex); emit switchStarting(currentWidget, nextWidget); if (!playAnimations) { nextWidget->setPos(0.0, 0.0); nextWidget->show(); finishAnimation(); } else { nextWidget->setPos((direction == Right ? size().width() : -(nextWidget->size().width())), 0.0); enterAnim.setPosAt(0.0, nextWidget->pos()); enterAnim.setPosAt(1.0, QPointF(0.0, 0.0)); leaveAnim.setPosAt(0.0, currentWidget->pos()); leaveAnim.setPosAt(1.0, QPointF((direction == Right ? -(currentWidget->size().width()) : size().width()), 0.0)); nextWidget->show(); animTimeLine.start(); } } bool HorizontalSwitcher::isAtBoundary(SwitchDirection direction) const { return (currentIndex == (direction == Left ? 0 : slides.count() - 1)); } void HorizontalSwitcher::setCurrent(QGraphicsWidget *widget) { if (!widget || !slides.contains(widget)) { qWarning() << "HorizontalSwitcher::setCurrent() - " << "Cannot set switcher to specified widget. Add widget to switcher first?"; return; } setCurrent(slides.indexOf(widget)); } void HorizontalSwitcher::setCurrent(int index) { if (isValidIndex(index) && index != currentIndex) { int oldIndex = -1; QGraphicsWidget *old = 0; if (isValidIndex(currentIndex)) { oldIndex = currentIndex; old = slides.at(currentIndex); } currentIndex = index; QGraphicsWidget *widget = slides.at(index); widget->setPos(0, 0); widget->resize(size()); widget->show(); // Ultimately might lead to a reaction map update in MKeyboardHost, // has no other purpose: emit switchDone(old, widget); updateGeometry(); if (old) { old->hide(); } } } int HorizontalSwitcher::current() const { return (slides.isEmpty() ? -1 : currentIndex); } QGraphicsWidget *HorizontalSwitcher::currentWidget() const { return (current() < 0 ? 0 : slides.at(currentIndex)); } QGraphicsWidget *HorizontalSwitcher::widget(int index) { return (isValidIndex(index) ? slides.at(index) : 0); } int HorizontalSwitcher::count() const { return slides.count(); } bool HorizontalSwitcher::isRunning() const { return (animTimeLine.state() == QTimeLine::Running); } void HorizontalSwitcher::setLooping(bool enable) { loopingEnabled = enable; } void HorizontalSwitcher::setDuration(int ms) { animTimeLine.setDuration(ms); animTimeLine.setFrameRange(0, ms * SwitchFrames / qMax(1, SwitchDuration)); } void HorizontalSwitcher::addWidget(QGraphicsWidget *widget) { if (!widget) { return; } widget->setParentItem(this); widget->setPreferredWidth(size().width()); slides.append(widget); widget->hide(); // HS was empty before, this was the first widget added: if (slides.size() == 1) { setCurrent(0); } } void HorizontalSwitcher::removeAll() { foreach(QGraphicsWidget * slide, slides) { slide->setParentItem(0); if (slide->scene()) { slide->scene()->removeItem(slide); } } slides.clear(); currentIndex = -1; updateGeometry(); } void HorizontalSwitcher::deleteAll() { qDeleteAll(slides); slides.clear(); currentIndex = -1; updateGeometry(); } void HorizontalSwitcher::resizeEvent(QGraphicsSceneResizeEvent *event) { QGraphicsWidget *widget = currentWidget(); if (widget) { widget->resize(event->newSize()); } } QSizeF HorizontalSwitcher::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const { // return the size hint of the currently visible widget QGraphicsWidget *widget = currentWidget(); QSizeF hint; if (widget) { hint = widget->effectiveSizeHint(which, constraint); } else { hint = QGraphicsWidget::sizeHint(which, constraint); } return hint; } void HorizontalSwitcher::finishAnimation() { int oldIndex = -1; // Hide old item QGraphicsWidget *old = static_cast<QGraphicsWidget *>(leaveAnim.item()); if (old) { oldIndex = slides.indexOf(old); old->hide(); } // Clear transformations leaveAnim.clear(); enterAnim.clear(); animTimeLine.stop(); // Discard cached sizehint info before telling that the switch is done. updateGeometry(); emit switchDone(oldIndex, currentIndex); emit switchDone(old, slides.at(currentIndex)); } bool HorizontalSwitcher::isValidIndex(int index) const { return (index >= 0 && index < slides.size()); } bool HorizontalSwitcher::isAnimationEnabled() const { return playAnimations; } void HorizontalSwitcher::setAnimationEnabled(bool enabled) { if (playAnimations != enabled) { if (isRunning()) finishAnimation(); playAnimations = enabled; } } <commit_msg>Changes: Disable KBA's while animating a language switch<commit_after>/* * This file is part of meego-keyboard * * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * Contact: Nokia Corporation ([email protected]) * * If you have questions regarding the use of this file, please contact * Nokia at [email protected]. * * 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 * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "horizontalswitcher.h" #include <QGraphicsSceneResizeEvent> #include <QGraphicsScene> #include <QDebug> namespace { const int SwitchDuration = 500; const int SwitchFrames = 300; } HorizontalSwitcher::HorizontalSwitcher(QGraphicsItem *parent) : QGraphicsWidget(parent), currentIndex(-1), animTimeLine(SwitchDuration), loopingEnabled(false), playAnimations(true) { setFlag(QGraphicsItem::ItemHasNoContents); // doesn't paint itself anything setObjectName("HorizontalSwitcher"); animTimeLine.setFrameRange(0, SwitchFrames); enterAnim.setTimeLine(&animTimeLine); leaveAnim.setTimeLine(&animTimeLine); connect(&animTimeLine, SIGNAL(finished()), this, SLOT(finishAnimation())); } HorizontalSwitcher::~HorizontalSwitcher() { if (isRunning()) finishAnimation(); // Delete all widgets that were not removed with removeWidget(). qDeleteAll(slides); slides.clear(); } void HorizontalSwitcher::switchTo(SwitchDirection direction) { if (isRunning()) { finishAnimation(); } if (slides.count() < 2 || (!loopingEnabled && isAtBoundary(direction))) { return; } int newIndex = (direction == Left ? (currentIndex - 1) : (currentIndex + 1) % slides.count()); if (newIndex < 0) { newIndex += slides.count(); } QGraphicsWidget *currentWidget = slides.at(currentIndex); QGraphicsWidget *nextWidget = slides.at(newIndex); // Current item is about to leave leaveAnim.setItem(currentWidget); currentWidget->setEnabled(false); // New item is about to enter enterAnim.setItem(nextWidget); nextWidget->setEnabled(false); // Try to fit current size. nextWidget->resize(size()); currentIndex = newIndex; emit switchStarting(currentIndex, newIndex); emit switchStarting(currentWidget, nextWidget); if (!playAnimations) { nextWidget->setPos(0.0, 0.0); nextWidget->show(); finishAnimation(); } else { nextWidget->setPos((direction == Right ? size().width() : -(nextWidget->size().width())), 0.0); enterAnim.setPosAt(0.0, nextWidget->pos()); enterAnim.setPosAt(1.0, QPointF(0.0, 0.0)); leaveAnim.setPosAt(0.0, currentWidget->pos()); leaveAnim.setPosAt(1.0, QPointF((direction == Right ? -(currentWidget->size().width()) : size().width()), 0.0)); nextWidget->show(); animTimeLine.start(); } } bool HorizontalSwitcher::isAtBoundary(SwitchDirection direction) const { return (currentIndex == (direction == Left ? 0 : slides.count() - 1)); } void HorizontalSwitcher::setCurrent(QGraphicsWidget *widget) { if (!widget || !slides.contains(widget)) { qWarning() << "HorizontalSwitcher::setCurrent() - " << "Cannot set switcher to specified widget. Add widget to switcher first?"; return; } setCurrent(slides.indexOf(widget)); } void HorizontalSwitcher::setCurrent(int index) { if (isValidIndex(index) && index != currentIndex) { int oldIndex = -1; QGraphicsWidget *old = 0; if (isValidIndex(currentIndex)) { oldIndex = currentIndex; old = slides.at(currentIndex); } currentIndex = index; QGraphicsWidget *widget = slides.at(index); widget->setPos(0, 0); widget->resize(size()); widget->show(); // Ultimately might lead to a reaction map update in MKeyboardHost, // has no other purpose: emit switchDone(old, widget); updateGeometry(); if (old) { old->hide(); } } } int HorizontalSwitcher::current() const { return (slides.isEmpty() ? -1 : currentIndex); } QGraphicsWidget *HorizontalSwitcher::currentWidget() const { return (current() < 0 ? 0 : slides.at(currentIndex)); } QGraphicsWidget *HorizontalSwitcher::widget(int index) { return (isValidIndex(index) ? slides.at(index) : 0); } int HorizontalSwitcher::count() const { return slides.count(); } bool HorizontalSwitcher::isRunning() const { return (animTimeLine.state() == QTimeLine::Running); } void HorizontalSwitcher::setLooping(bool enable) { loopingEnabled = enable; } void HorizontalSwitcher::setDuration(int ms) { animTimeLine.setDuration(ms); animTimeLine.setFrameRange(0, ms * SwitchFrames / qMax(1, SwitchDuration)); } void HorizontalSwitcher::addWidget(QGraphicsWidget *widget) { if (!widget) { return; } widget->setParentItem(this); widget->setPreferredWidth(size().width()); slides.append(widget); widget->hide(); // HS was empty before, this was the first widget added: if (slides.size() == 1) { setCurrent(0); } } void HorizontalSwitcher::removeAll() { foreach(QGraphicsWidget * slide, slides) { slide->setParentItem(0); if (slide->scene()) { slide->scene()->removeItem(slide); } } slides.clear(); currentIndex = -1; updateGeometry(); } void HorizontalSwitcher::deleteAll() { qDeleteAll(slides); slides.clear(); currentIndex = -1; updateGeometry(); } void HorizontalSwitcher::resizeEvent(QGraphicsSceneResizeEvent *event) { QGraphicsWidget *widget = currentWidget(); if (widget) { widget->resize(event->newSize()); } } QSizeF HorizontalSwitcher::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const { // return the size hint of the currently visible widget QGraphicsWidget *widget = currentWidget(); QSizeF hint; if (widget) { hint = widget->effectiveSizeHint(which, constraint); } else { hint = QGraphicsWidget::sizeHint(which, constraint); } return hint; } void HorizontalSwitcher::finishAnimation() { int oldIndex = -1; // Hide old item QGraphicsWidget *old = static_cast<QGraphicsWidget *>(leaveAnim.item()); if (old) { oldIndex = slides.indexOf(old); old->hide(); } // Clear transformations leaveAnim.clear(); enterAnim.clear(); animTimeLine.stop(); // Discard cached sizehint info before telling that the switch is done. updateGeometry(); if (currentWidget()) { currentWidget()->setEnabled(true); } emit switchDone(oldIndex, currentIndex); emit switchDone(old, slides.at(currentIndex)); } bool HorizontalSwitcher::isValidIndex(int index) const { return (index >= 0 && index < slides.size()); } bool HorizontalSwitcher::isAnimationEnabled() const { return playAnimations; } void HorizontalSwitcher::setAnimationEnabled(bool enabled) { if (playAnimations != enabled) { if (isRunning()) finishAnimation(); playAnimations = enabled; } } <|endoftext|>
<commit_before>/* * benchmarks/benchmark-dense-solve.C * * Copyright (C) 2019 The LinBox group * Author: J-G Dumas * ========LICENCE======== * This file is part of the library LinBox. * * LinBox is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ========LICENCE======== */ /**\file benchmarks/benchmark-dense-solve.C \brief Solving dense linear system over Q or Zp. \ingroup benchmarks */ #include "linbox/linbox-config.h" #include <iostream> #include <givaro/modular.h> #include "linbox/util/args-parser.h" #include "linbox/matrix/sparse-matrix.h" #include "linbox/solutions/solve.h" #include "linbox/util/matrix-stream.h" #include "linbox/solutions/methods.h" #ifdef _DEBUG #define _BENCHMARKS_DEBUG_ #endif using namespace LinBox; typedef Givaro::ZRing<Givaro::Integer> Ints; int main (int argc, char **argv) { Givaro::Integer q = -1 ; size_t n = 500 ; size_t bits = 10; // size_t p = 0; Argument as[] = { { 'q', "-q Q", "Set the field characteristic (-1 for rationals).", TYPE_INTEGER , &q }, { 'n', "-n N", "Set the matrix dimension.", TYPE_INT , &n }, { 'b', "-b B", "bit size", TYPE_INT , &bits }, // { 'p', "-p P", "0 for sequential, 1 for 2D iterative, 2 for 2D rec, 3 for 2D rec adaptive, 4 for 3D rec in-place, 5 for 3D rec, 6 for 3D rec adaptive.", TYPE_INT , &p }, END_OF_ARGUMENTS }; LinBox::parseArguments(argc,argv,as); bool ModComp = false; if (q > 0) ModComp = true; Timer chrono; if (ModComp) { typedef Givaro::Modular<double> Field; Field F(q); Field::RandIter G(F); #ifdef _BENCHMARKS_DEBUG_ std::clog << "Setting A ... " << std::endl; #endif chrono.start(); DenseMatrix<Field> A(F,n,n); PAR_BLOCK { FFLAS::pfrand(F,G, n,n,A.getPointer(),n); } chrono.stop(); #ifdef _BENCHMARKS_DEBUG_ std::clog << "... A is " << A.rowdim() << " by " << A.coldim() << ", " << chrono << std::endl; if (A.rowdim() <= 20 && A.coldim() <= 20) A.write(std::clog <<"A:=",Tag::FileFormat::Maple) << ';' << std::endl; #endif DenseVector<Field> X(F, A.coldim()),B(F, A.rowdim()); for(auto it=B.begin(); it != B.end(); ++it) if (drand48() <0.5) F.assign(*it,F.mOne); else F.assign(*it,F.one); #ifdef _BENCHMARKS_DEBUG_ std::clog << "B is ["; for(const auto& it: B) F.write(std::clog, it) << ' '; std::clog << ']' << std::endl; #endif // DenseElimination chrono.start(); solve (X, A, B, Method::DenseElimination()); chrono.stop(); #ifdef _BENCHMARKS_DEBUG_ std::clog << "(DenseElimination) Solution is ["; for(const auto& it: X) F.write(std::clog, it) << ' '; std::clog << ']' << std::endl; #endif std::cout << "Time: " << chrono.usertime() << " Bitsize: " << Givaro::logtwo(GIVMAX(X.front(), 1)); FFLAS::writeCommandString(std::cout, as) << std::endl; } else { typedef Ints Integers; Integers ZZ; Integers::RandIter G(ZZ,bits); #ifdef _BENCHMARKS_DEBUG_ std::clog << "Reading A ... " << std::endl; chrono.start(); #endif DenseMatrix<Integers> A(ZZ, n, n); PAR_BLOCK { FFLAS::pfrand(ZZ,G, n,n,A.getPointer(),n); } #ifdef _BENCHMARKS_DEBUG_ chrono.stop(); std::clog << "... A is " << A.rowdim() << " by " << A.coldim() << ", " << chrono << std::endl; if (A.rowdim() <= 20 && A.coldim() <= 20) A.write(std::clog <<"A:=",Tag::FileFormat::Maple) << ';' << std::endl; #endif Givaro::IntegerDom::Element d; DenseVector<Integers> X(ZZ, A.coldim()),B(ZZ, A.rowdim()); for(auto it=B.begin(); it != B.end(); ++it) if (drand48() <0.5) ZZ.assign(*it,ZZ.mOne); else ZZ.assign(*it,ZZ.one); #ifdef _BENCHMARKS_DEBUG_ std::clog << "B is ["; for(const auto& it: B) ZZ.write(std::clog, it) << ' '; std::clog << ']' << std::endl; #endif // DenseElimination chrono.start(); solve (X, d, A, B, RingCategories::IntegerTag(), Method::DenseElimination()); chrono.stop(); #ifdef _BENCHMARKS_DEBUG_ std::clog << "(DenseElimination) Solution is ["; for(const auto& it: X) ZZ.write(std::clog, it) << ' '; ZZ.write(std::clog << "] / ", d)<< std::endl; #endif std::cout << "Time: " << chrono.usertime() << " Bitsize: " << Givaro::logtwo(d); FFLAS::writeCommandString(std::cout, as) << std::endl; } return 0; } <commit_msg>median time<commit_after>/* * benchmarks/benchmark-dense-solve.C * * Copyright (C) 2019 The LinBox group * Author: J-G Dumas * ========LICENCE======== * This file is part of the library LinBox. * * LinBox is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ========LICENCE======== */ /**\file benchmarks/benchmark-dense-solve.C \brief Solving dense linear system over Q or Zp. \ingroup benchmarks */ #include "linbox/linbox-config.h" #include <iostream> #include <givaro/modular.h> #include "linbox/util/args-parser.h" #include "linbox/matrix/sparse-matrix.h" #include "linbox/solutions/solve.h" #include "linbox/util/matrix-stream.h" #include "linbox/solutions/methods.h" #ifdef _DEBUG #define _BENCHMARKS_DEBUG_ #endif using namespace LinBox; typedef Givaro::ZRing<Givaro::Integer> Ints; int main (int argc, char **argv) { Givaro::Integer q = -1 ; size_t nbiter = 3 ; size_t n = 500 ; size_t bits = 10; // size_t p = 0; Argument as[] = { { 'i', "-i R", "Set number of repetitions.", TYPE_INT , &nbiter }, { 'q', "-q Q", "Set the field characteristic (-1 for rationals).", TYPE_INTEGER , &q }, { 'n', "-n N", "Set the matrix dimension.", TYPE_INT , &n }, { 'b', "-b B", "bit size", TYPE_INT , &bits }, // { 'p', "-p P", "0 for sequential, 1 for 2D iterative, 2 for 2D rec, 3 for 2D rec adaptive, 4 for 3D rec in-place, 5 for 3D rec, 6 for 3D rec adaptive.", TYPE_INT , &p }, END_OF_ARGUMENTS }; LinBox::parseArguments(argc,argv,as); bool ModComp = false; if (q > 0) ModComp = true; Timer chrono; std::vector<std::pair<double,double>> timebits(nbiter); for(size_t iter=0; iter<nbiter; ++iter) { if (ModComp) { typedef Givaro::Modular<double> Field; Field F(q); Field::RandIter G(F); #ifdef _BENCHMARKS_DEBUG_ std::clog << "Setting A ... " << std::endl; #endif chrono.start(); DenseMatrix<Field> A(F,n,n); PAR_BLOCK { FFLAS::pfrand(F,G, n,n,A.getPointer(),n); } chrono.stop(); #ifdef _BENCHMARKS_DEBUG_ std::clog << "... A is " << A.rowdim() << " by " << A.coldim() << ", " << chrono << std::endl; if (A.rowdim() <= 20 && A.coldim() <= 20) A.write(std::clog <<"A:=",Tag::FileFormat::Maple) << ';' << std::endl; #endif DenseVector<Field> X(F, A.coldim()),B(F, A.rowdim()); for(auto it=B.begin(); it != B.end(); ++it) if (drand48() <0.5) F.assign(*it,F.mOne); else F.assign(*it,F.one); #ifdef _BENCHMARKS_DEBUG_ std::clog << "B is ["; for(const auto& it: B) F.write(std::clog, it) << ' '; std::clog << ']' << std::endl; #endif // DenseElimination chrono.start(); solve (X, A, B, Method::DenseElimination()); chrono.stop(); #ifdef _BENCHMARKS_DEBUG_ std::clog << "(DenseElimination) Solution is ["; for(const auto& it: X) F.write(std::clog, it) << ' '; std::clog << ']' << std::endl; #endif timebits[iter].second=Givaro::logtwo(GIVMAX(X.front(), 1)); } else { typedef Ints Integers; Integers ZZ; Integers::RandIter G(ZZ,bits); #ifdef _BENCHMARKS_DEBUG_ std::clog << "Reading A ... " << std::endl; chrono.start(); #endif DenseMatrix<Integers> A(ZZ, n, n); PAR_BLOCK { FFLAS::pfrand(ZZ,G, n,n,A.getPointer(),n); } #ifdef _BENCHMARKS_DEBUG_ chrono.stop(); std::clog << "... A is " << A.rowdim() << " by " << A.coldim() << ", " << chrono << std::endl; if (A.rowdim() <= 20 && A.coldim() <= 20) A.write(std::clog <<"A:=",Tag::FileFormat::Maple) << ';' << std::endl; #endif Givaro::IntegerDom::Element d; DenseVector<Integers> X(ZZ, A.coldim()),B(ZZ, A.rowdim()); for(auto it=B.begin(); it != B.end(); ++it) if (drand48() <0.5) ZZ.assign(*it,ZZ.mOne); else ZZ.assign(*it,ZZ.one); #ifdef _BENCHMARKS_DEBUG_ std::clog << "B is ["; for(const auto& it: B) ZZ.write(std::clog, it) << ' '; std::clog << ']' << std::endl; #endif // DenseElimination chrono.start(); solve (X, d, A, B, RingCategories::IntegerTag(), Method::DenseElimination()); chrono.stop(); #ifdef _BENCHMARKS_DEBUG_ std::clog << "(DenseElimination) Solution is ["; for(const auto& it: X) ZZ.write(std::clog, it) << ' '; ZZ.write(std::clog << "] / ", d)<< std::endl; #endif timebits[iter].second=Givaro::logtwo(d); } timebits[iter].first=chrono.usertime(); } #ifdef _BENCHMARKS_DEBUG_ for(const auto& it: timebits) std::clog << it.first << "s, " << it.second << " bits" << std::endl; #endif std::sort(timebits.begin(), timebits.end(), [](const std::pair<double,double> & a, const std::pair<double,double> & b) -> bool { return a.first > b.first; }); std::cout << "Time: " << timebits[nbiter/2].first << " Bitsize: " << timebits[nbiter/2].second; FFLAS::writeCommandString(std::cout, as) << std::endl; return 0; } <|endoftext|>
<commit_before>#include <windows.h> #include <tlhelp32.h> #include <vector> #include <algorithm> #include "NativeCore.hpp" void RC_CallConv EnumerateRemoteSectionsAndModules(RC_Pointer process, EnumerateRemoteSectionsCallback callbackSection, EnumerateRemoteModulesCallback callbackModule) { if (callbackSection == nullptr && callbackModule == nullptr) { return; } std::vector<EnumerateRemoteSectionData> sections; MEMORY_BASIC_INFORMATION memInfo = { }; memInfo.RegionSize = 0x1000; size_t address = 0; while (VirtualQueryEx(process, reinterpret_cast<LPCVOID>(address), &memInfo, sizeof(MEMORY_BASIC_INFORMATION)) != 0 && address + memInfo.RegionSize > address) { if (memInfo.State == MEM_COMMIT) { EnumerateRemoteSectionData section = {}; section.BaseAddress = memInfo.BaseAddress; section.Size = memInfo.RegionSize; section.Protection = SectionProtection::NoAccess; if ((memInfo.Protect & PAGE_EXECUTE) == PAGE_EXECUTE) section.Protection |= SectionProtection::Execute; if ((memInfo.Protect & PAGE_EXECUTE_READ) == PAGE_EXECUTE_READ) section.Protection |= SectionProtection::Execute | SectionProtection::Read; if ((memInfo.Protect & PAGE_EXECUTE_READWRITE) == PAGE_EXECUTE_READWRITE) section.Protection |= SectionProtection::Execute | SectionProtection::Read | SectionProtection::Write; if ((memInfo.Protect & PAGE_EXECUTE_WRITECOPY) == PAGE_EXECUTE_READWRITE) section.Protection |= SectionProtection::Execute | SectionProtection::Read | SectionProtection::CopyOnWrite; if ((memInfo.Protect & PAGE_READONLY) == PAGE_READONLY) section.Protection |= SectionProtection::Read; if ((memInfo.Protect & PAGE_READWRITE) == PAGE_READWRITE) section.Protection |= SectionProtection::Read | SectionProtection::Write; if ((memInfo.Protect & PAGE_WRITECOPY) == PAGE_WRITECOPY) section.Protection |= SectionProtection::Read | SectionProtection::CopyOnWrite; if ((memInfo.Protect & PAGE_GUARD) == PAGE_GUARD) section.Protection |= SectionProtection::Guard; switch (memInfo.Type) { case MEM_IMAGE: section.Type = SectionType::Image; break; case MEM_MAPPED: section.Type = SectionType::Mapped; break; case MEM_PRIVATE: section.Type = SectionType::Private; break; } section.Category = section.Type == SectionType::Private ? SectionCategory::HEAP : SectionCategory::Unknown; sections.push_back(std::move(section)); } address = reinterpret_cast<size_t>(memInfo.BaseAddress) + memInfo.RegionSize; } const auto handle = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetProcessId(process)); if (handle != INVALID_HANDLE_VALUE) { MODULEENTRY32W me32 = {}; me32.dwSize = sizeof(MODULEENTRY32W); if (Module32FirstW(handle, &me32)) { do { if (callbackModule != nullptr) { EnumerateRemoteModuleData data = {}; data.BaseAddress = me32.modBaseAddr; data.Size = me32.modBaseSize; std::memcpy(data.Path, me32.szExePath, std::min(MAX_PATH, PATH_MAXIMUM_LENGTH)); callbackModule(&data); } if (callbackSection != nullptr) { auto it = std::lower_bound(std::begin(sections), std::end(sections), static_cast<LPVOID>(me32.modBaseAddr), [&sections](const auto& lhs, const LPVOID& rhs) { return lhs.BaseAddress < rhs; }); IMAGE_DOS_HEADER DosHdr = {}; IMAGE_NT_HEADERS NtHdr = {}; ReadRemoteMemory(process, me32.modBaseAddr, &DosHdr, 0, sizeof(IMAGE_DOS_HEADER)); ReadRemoteMemory(process, me32.modBaseAddr + DosHdr.e_lfanew, &NtHdr, 0, sizeof(IMAGE_NT_HEADERS)); std::vector<IMAGE_SECTION_HEADER> sectionHeaders(NtHdr.FileHeader.NumberOfSections); ReadRemoteMemory(process, me32.modBaseAddr + DosHdr.e_lfanew + sizeof(IMAGE_NT_HEADERS), sectionHeaders.data(), 0, NtHdr.FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER)); for (auto i = 0; i < NtHdr.FileHeader.NumberOfSections; ++i) { auto&& sectionHeader = sectionHeaders[i]; const auto sectionAddress = reinterpret_cast<size_t>(me32.modBaseAddr) + sectionHeader.VirtualAddress; for (auto j = it; j != std::end(sections); ++j) { if (sectionAddress >= reinterpret_cast<size_t>(j->BaseAddress) && sectionAddress < reinterpret_cast<size_t>(j->BaseAddress) + static_cast<size_t>(j->Size)) { // Copy the name because it is not null padded. char buffer[IMAGE_SIZEOF_SHORT_NAME + 1] = { 0 }; std::memcpy(buffer, sectionHeader.Name, IMAGE_SIZEOF_SHORT_NAME); if (std::strcmp(buffer, ".text") == 0 || std::strcmp(buffer, "code") == 0) { j->Category = SectionCategory::CODE; } else if (std::strcmp(buffer, ".data") == 0 || std::strcmp(buffer, "data") == 0 || std::strcmp(buffer, ".rdata") == 0 || std::strcmp(buffer, ".idata") == 0) { j->Category = SectionCategory::DATA; } MultiByteToUnicode(buffer, j->Name, IMAGE_SIZEOF_SHORT_NAME); std::memcpy(j->ModulePath, me32.szExePath, std::min(MAX_PATH, PATH_MAXIMUM_LENGTH)); break; } } } } } while (Module32NextW(handle, &me32)); } CloseHandle(handle); if (callbackSection != nullptr) { for (auto&& section : sections) { callbackSection(&section); } } } } <commit_msg>Possible bug fix for memory region enumeration<commit_after>#include <windows.h> #include <tlhelp32.h> #include <vector> #include <algorithm> #include "NativeCore.hpp" void RC_CallConv EnumerateRemoteSectionsAndModules(RC_Pointer process, EnumerateRemoteSectionsCallback callbackSection, EnumerateRemoteModulesCallback callbackModule) { if (callbackSection == nullptr && callbackModule == nullptr) { return; } std::vector<EnumerateRemoteSectionData> sections; MEMORY_BASIC_INFORMATION memInfo = { }; memInfo.RegionSize = 0x1000; size_t address = 0; while (VirtualQueryEx(process, reinterpret_cast<LPCVOID>(address), &memInfo, sizeof(MEMORY_BASIC_INFORMATION)) != 0 && address + memInfo.RegionSize > address) { if (memInfo.State == MEM_COMMIT) { EnumerateRemoteSectionData section = {}; section.BaseAddress = memInfo.BaseAddress; section.Size = memInfo.RegionSize; section.Protection = SectionProtection::NoAccess; if ((memInfo.Protect & PAGE_EXECUTE) == PAGE_EXECUTE) section.Protection |= SectionProtection::Execute; if ((memInfo.Protect & PAGE_EXECUTE_READ) == PAGE_EXECUTE_READ) section.Protection |= SectionProtection::Execute | SectionProtection::Read; if ((memInfo.Protect & PAGE_EXECUTE_READWRITE) == PAGE_EXECUTE_READWRITE) section.Protection |= SectionProtection::Execute | SectionProtection::Read | SectionProtection::Write; if ((memInfo.Protect & PAGE_EXECUTE_WRITECOPY) == PAGE_EXECUTE_WRITECOPY) section.Protection |= SectionProtection::Execute | SectionProtection::Read | SectionProtection::CopyOnWrite; if ((memInfo.Protect & PAGE_READONLY) == PAGE_READONLY) section.Protection |= SectionProtection::Read; if ((memInfo.Protect & PAGE_READWRITE) == PAGE_READWRITE) section.Protection |= SectionProtection::Read | SectionProtection::Write; if ((memInfo.Protect & PAGE_WRITECOPY) == PAGE_WRITECOPY) section.Protection |= SectionProtection::Read | SectionProtection::CopyOnWrite; if ((memInfo.Protect & PAGE_GUARD) == PAGE_GUARD) section.Protection |= SectionProtection::Guard; switch (memInfo.Type) { case MEM_IMAGE: section.Type = SectionType::Image; break; case MEM_MAPPED: section.Type = SectionType::Mapped; break; case MEM_PRIVATE: section.Type = SectionType::Private; break; } section.Category = section.Type == SectionType::Private ? SectionCategory::HEAP : SectionCategory::Unknown; sections.push_back(std::move(section)); } address = reinterpret_cast<size_t>(memInfo.BaseAddress) + memInfo.RegionSize; } const auto handle = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetProcessId(process)); if (handle != INVALID_HANDLE_VALUE) { MODULEENTRY32W me32 = {}; me32.dwSize = sizeof(MODULEENTRY32W); if (Module32FirstW(handle, &me32)) { do { if (callbackModule != nullptr) { EnumerateRemoteModuleData data = {}; data.BaseAddress = me32.modBaseAddr; data.Size = me32.modBaseSize; std::memcpy(data.Path, me32.szExePath, std::min(MAX_PATH, PATH_MAXIMUM_LENGTH)); callbackModule(&data); } if (callbackSection != nullptr) { auto it = std::lower_bound(std::begin(sections), std::end(sections), static_cast<LPVOID>(me32.modBaseAddr), [&sections](const auto& lhs, const LPVOID& rhs) { return lhs.BaseAddress < rhs; }); IMAGE_DOS_HEADER DosHdr = {}; IMAGE_NT_HEADERS NtHdr = {}; ReadRemoteMemory(process, me32.modBaseAddr, &DosHdr, 0, sizeof(IMAGE_DOS_HEADER)); ReadRemoteMemory(process, me32.modBaseAddr + DosHdr.e_lfanew, &NtHdr, 0, sizeof(IMAGE_NT_HEADERS)); std::vector<IMAGE_SECTION_HEADER> sectionHeaders(NtHdr.FileHeader.NumberOfSections); ReadRemoteMemory(process, me32.modBaseAddr + DosHdr.e_lfanew + sizeof(IMAGE_NT_HEADERS), sectionHeaders.data(), 0, NtHdr.FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER)); for (auto i = 0; i < NtHdr.FileHeader.NumberOfSections; ++i) { auto&& sectionHeader = sectionHeaders[i]; const auto sectionAddress = reinterpret_cast<size_t>(me32.modBaseAddr) + sectionHeader.VirtualAddress; for (auto j = it; j != std::end(sections); ++j) { if (sectionAddress >= reinterpret_cast<size_t>(j->BaseAddress) && sectionAddress < reinterpret_cast<size_t>(j->BaseAddress) + static_cast<size_t>(j->Size)) { // Copy the name because it is not null padded. char buffer[IMAGE_SIZEOF_SHORT_NAME + 1] = { 0 }; std::memcpy(buffer, sectionHeader.Name, IMAGE_SIZEOF_SHORT_NAME); if (std::strcmp(buffer, ".text") == 0 || std::strcmp(buffer, "code") == 0) { j->Category = SectionCategory::CODE; } else if (std::strcmp(buffer, ".data") == 0 || std::strcmp(buffer, "data") == 0 || std::strcmp(buffer, ".rdata") == 0 || std::strcmp(buffer, ".idata") == 0) { j->Category = SectionCategory::DATA; } MultiByteToUnicode(buffer, j->Name, IMAGE_SIZEOF_SHORT_NAME); std::memcpy(j->ModulePath, me32.szExePath, std::min(MAX_PATH, PATH_MAXIMUM_LENGTH)); break; } } } } } while (Module32NextW(handle, &me32)); } CloseHandle(handle); if (callbackSection != nullptr) { for (auto&& section : sections) { callbackSection(&section); } } } } <|endoftext|>
<commit_before><commit_msg>No need for these to be statics.<commit_after><|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/test/layout_browsertest.h" class IndexedDBLayoutTest : public InProcessBrowserLayoutTest { public: IndexedDBLayoutTest() : InProcessBrowserLayoutTest( FilePath(), FilePath().AppendASCII("storage").AppendASCII("indexeddb")) { } void RunLayoutTests(const char* file_names[]) { for (size_t i = 0; file_names[i]; i++) RunLayoutTest(file_names[i]); } }; namespace { static const char* kBasicTests[] = { "basics.html", "basics-shared-workers.html", // Failing on Precise bot (crbug.com/145592). // "basics-workers.html", "database-basics.html", "factory-basics.html", "index-basics.html", "objectstore-basics.html", NULL }; static const char* kComplexTests[] = { "prefetch-bugfix-108071.html", // Flaky: http://crbug.com/123685 // "pending-version-change-stuck-works-with-terminate.html", NULL }; static const char* kIndexTests[] = { "deleteIndex.html", // Flaky: http://crbug.com/123685 // "index-basics-workers.html", "index-count.html", "index-cursor.html", // Locally takes ~6s compared to <1 for the others. "index-get-key-argument-required.html", "index-multientry.html", "index-population.html", "index-unique.html", NULL }; static const char* kKeyTests[] = { "key-generator.html", "keypath-basics.html", "keypath-edges.html", "keypath-fetch-key.html", "keyrange.html", "keyrange-required-arguments.html", "key-sort-order-across-types.html", "key-sort-order-date.html", "key-type-array.html", "key-type-infinity.html", "invalid-keys.html", NULL }; static const char* kTransactionTests[] = { "transaction-abort.html", "transaction-complete-with-js-recursion-cross-frame.html", "transaction-complete-with-js-recursion.html", "transaction-complete-workers.html", "transaction-after-close.html", "transaction-and-objectstore-calls.html", "transaction-basics.html", "transaction-crash-on-abort.html", "transaction-event-propagation.html", "transaction-read-only.html", "transaction-rollback.html", "transaction-storeNames-required.html", NULL }; static const char* kRegressionTests[] = { "dont-commit-on-blocked.html", NULL }; const char* kIntVersionTests[] = { "intversion-abort-in-initial-upgradeneeded.html", "intversion-and-setversion.html", "intversion-blocked.html", // "intversion-close-between-events.html", // crbug.com/150947 // "intversion-close-in-oncomplete.html", // crbug.com/150691 "intversion-close-in-upgradeneeded.html", "intversion-delete-in-upgradeneeded.html", // "intversion-gated-on-delete.html", // behaves slightly differently in DRT "intversion-long-queue.html", "intversion-omit-parameter.html", "intversion-open-with-version.html", NULL }; } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, BasicTests) { RunLayoutTests(kBasicTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, ComplexTests) { RunLayoutTests(kComplexTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, IndexTests) { RunLayoutTests(kIndexTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, KeyTests) { RunLayoutTests(kKeyTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, TransactionTests) { RunLayoutTests(kTransactionTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, IntVersionTests) { RunLayoutTests(kIntVersionTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, RegressionTests) { RunLayoutTests(kRegressionTests); } <commit_msg>Disable IndexedDBLayoutTest.IndexTests for being flaky and timing out.<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/test/layout_browsertest.h" class IndexedDBLayoutTest : public InProcessBrowserLayoutTest { public: IndexedDBLayoutTest() : InProcessBrowserLayoutTest( FilePath(), FilePath().AppendASCII("storage").AppendASCII("indexeddb")) { } void RunLayoutTests(const char* file_names[]) { for (size_t i = 0; file_names[i]; i++) RunLayoutTest(file_names[i]); } }; namespace { static const char* kBasicTests[] = { "basics.html", "basics-shared-workers.html", // Failing on Precise bot (crbug.com/145592). // "basics-workers.html", "database-basics.html", "factory-basics.html", "index-basics.html", "objectstore-basics.html", NULL }; static const char* kComplexTests[] = { "prefetch-bugfix-108071.html", // Flaky: http://crbug.com/123685 // "pending-version-change-stuck-works-with-terminate.html", NULL }; static const char* kIndexTests[] = { "deleteIndex.html", // Flaky: http://crbug.com/123685 // "index-basics-workers.html", "index-count.html", "index-cursor.html", // Locally takes ~6s compared to <1 for the others. "index-get-key-argument-required.html", "index-multientry.html", "index-population.html", "index-unique.html", NULL }; static const char* kKeyTests[] = { "key-generator.html", "keypath-basics.html", "keypath-edges.html", "keypath-fetch-key.html", "keyrange.html", "keyrange-required-arguments.html", "key-sort-order-across-types.html", "key-sort-order-date.html", "key-type-array.html", "key-type-infinity.html", "invalid-keys.html", NULL }; static const char* kTransactionTests[] = { "transaction-abort.html", "transaction-complete-with-js-recursion-cross-frame.html", "transaction-complete-with-js-recursion.html", "transaction-complete-workers.html", "transaction-after-close.html", "transaction-and-objectstore-calls.html", "transaction-basics.html", "transaction-crash-on-abort.html", "transaction-event-propagation.html", "transaction-read-only.html", "transaction-rollback.html", "transaction-storeNames-required.html", NULL }; static const char* kRegressionTests[] = { "dont-commit-on-blocked.html", NULL }; const char* kIntVersionTests[] = { "intversion-abort-in-initial-upgradeneeded.html", "intversion-and-setversion.html", "intversion-blocked.html", // "intversion-close-between-events.html", // crbug.com/150947 // "intversion-close-in-oncomplete.html", // crbug.com/150691 "intversion-close-in-upgradeneeded.html", "intversion-delete-in-upgradeneeded.html", // "intversion-gated-on-delete.html", // behaves slightly differently in DRT "intversion-long-queue.html", "intversion-omit-parameter.html", "intversion-open-with-version.html", NULL }; } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, BasicTests) { RunLayoutTests(kBasicTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, ComplexTests) { RunLayoutTests(kComplexTests); } // TODO(dgrogan): times out flakily. http://crbug.com/153064 IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, DISABLED_IndexTests) { RunLayoutTests(kIndexTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, KeyTests) { RunLayoutTests(kKeyTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, TransactionTests) { RunLayoutTests(kTransactionTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, IntVersionTests) { RunLayoutTests(kIntVersionTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, RegressionTests) { RunLayoutTests(kRegressionTests); } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief ルネサス RX 選択 @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2016, 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/byte_order.h" #include "common/vect.h" #include "common/delay.hpp" #if defined(SIG_RX621) #include "RX600/port.hpp" #include "RX600/cmt.hpp" #include "RX621/system.hpp" #include "RX621/sci.hpp" #include "RX621/icu.hpp" #elif defined(SIG_RX24T) #include "RX24T/peripheral.hpp" #include "RX600/port.hpp" #include "RX24T/system.hpp" #include "RX24T/system_io.hpp" #include "RX24T/dtc.hpp" #include "RX24T/icu.hpp" #include "RX24T/mtu3.hpp" #include "RX24T/poe3.hpp" #include "RX24T/gpt.hpp" #include "RX24T/tmr.hpp" #include "RX600/cmt.hpp" #include "RX24T/sci.hpp" #include "RX24T/riic.hpp" #include "RX24T/rspi.hpp" #include "RX24T/crc.hpp" #include "RX24T/s12ad.hpp" #include "RX24T/adc_io.hpp" #include "RX24T/da.hpp" #include "RX24T/cmpc.hpp" #include "RX24T/doc.hpp" #include "RX24T/port_map.hpp" #include "RX24T/power_cfg.hpp" #include "RX24T/icu_mgr.hpp" #include "RX24T/flash.hpp" #include "RX24T/flash_io.hpp" #elif defined(SIG_RX63T) #include "RX63T/peripheral.hpp" #include "RX600/port.hpp" #include "RX600/cmt.hpp" #include "RX63T/system.hpp" #include "RX63T/sci.hpp" #include "RX63T/icu.hpp" #include "RX63T/port_map.hpp" #include "RX63T/power_cfg.hpp" #include "RX63T/icu_mgr.hpp" #elif defined(SIG_RX64M) #include "RX600/peripheral.hpp" #include "RX600/system.hpp" #include "RX600/system_io.hpp" #include "RX600/dmac.hpp" #include "RX600/exdmac.hpp" #include "RX600/port.hpp" #include "RX600/bus.hpp" #include "RX600/mpc.hpp" #include "RX600/icu.hpp" #include "RX600/tpu.hpp" #include "RX600/cmt.hpp" #include "RX600/mtu3.hpp" #include "RX600/sci.hpp" #include "RX600/scif.hpp" #include "RX600/riic.hpp" #include "RX600/can.hpp" #include "RX600/rspi.hpp" #include "RX600/qspi.hpp" #include "RX600/port_map.hpp" #include "RX600/power_cfg.hpp" #include "RX600/icu_mgr.hpp" #include "RX600/s12adc.hpp" #include "RX600/adc_io.hpp" #include "RX600/r12da.hpp" #include "RX600/dac_out.hpp" #include "RX600/sdram.hpp" #include "RX600/etherc.hpp" #include "RX600/edmac.hpp" #include "RX600/usb.hpp" #include "RX600/rtc.hpp" #include "RX600/rtc_io.hpp" #include "RX600/wdta.hpp" #include "RX600/flash.hpp" #include "RX600/flash_io.hpp" #include "RX600/ether_io.hpp" #include "RX600/ssi.hpp" #include "RX600/src.hpp" #include "RX600/sdhi.hpp" #include "RX600/sdhi_io.hpp" #include "RX600/standby_ram.hpp" #include "RX600/ssi_io.hpp" #include "RX600/dmac_mgr.hpp" #elif defined(SIG_RX65N) #include "RX600/peripheral.hpp" #include "RX600/system.hpp" #include "RX600/system_io.hpp" #include "RX600/dmac.hpp" #include "RX600/exdmac.hpp" #include "RX600/port.hpp" #include "RX600/bus.hpp" #include "RX600/mpc.hpp" #include "RX600/icu.hpp" #include "RX600/tpu.hpp" #include "RX600/cmt.hpp" #include "RX600/mtu3.hpp" #include "RX600/sci.hpp" #include "RX600/scif.hpp" #include "RX600/riic.hpp" #include "RX600/can.hpp" #include "RX600/rspi.hpp" #include "RX600/qspi.hpp" #include "RX600/port_map.hpp" #include "RX600/power_cfg.hpp" #include "RX600/icu_mgr.hpp" #include "RX65x/s12adf.hpp" #include "RX600/adc_io.hpp" #include "RX600/r12da.hpp" #include "RX600/dac_out.hpp" #include "RX600/sdram.hpp" #include "RX600/etherc.hpp" #include "RX600/edmac.hpp" #include "RX600/usb.hpp" #include "RX600/rtc.hpp" #include "RX600/rtc_io.hpp" #include "RX600/wdta.hpp" #include "RX600/flash.hpp" #include "RX600/flash_io.hpp" #include "RX600/ether_io.hpp" #include "RX600/ssi.hpp" #include "RX600/src.hpp" #include "RX600/sdhi.hpp" #include "RX600/sdhi_io.hpp" #include "RX600/standby_ram.hpp" #include "RX600/ssi_io.hpp" #include "RX65x/glcdc.hpp" #include "RX65x/glcdc_io.hpp" #include "RX65x/drw2d.hpp" #include "RX65x/drw2d_mgr.hpp" #include "RX600/dmac_mgr.hpp" #elif defined(SIG_RX71M) #include "RX600/peripheral.hpp" #include "RX600/system.hpp" #include "RX600/system_io.hpp" #include "RX600/dmac.hpp" #include "RX600/exdmac.hpp" #include "RX600/port.hpp" #include "RX600/bus.hpp" #include "RX600/mpc.hpp" #include "RX600/icu.hpp" #include "RX600/tpu.hpp" #include "RX600/cmt.hpp" #include "RX600/mtu3.hpp" #include "RX600/sci.hpp" #include "RX600/scif.hpp" #include "RX600/riic.hpp" #include "RX600/can.hpp" #include "RX600/rspi.hpp" #include "RX600/qspi.hpp" #include "RX600/port_map.hpp" #include "RX600/power_cfg.hpp" #include "RX600/icu_mgr.hpp" #include "RX600/s12adc.hpp" #include "RX600/adc_io.hpp" #include "RX600/r12da.hpp" #include "RX600/dac_out.hpp" #include "RX600/sdram.hpp" #include "RX600/etherc.hpp" #include "RX600/edmac.hpp" #include "RX600/usb.hpp" #include "RX600/rtc.hpp" #include "RX600/rtc_io.hpp" #include "RX600/wdta.hpp" #include "RX600/flash.hpp" #include "RX600/flash_io.hpp" #include "RX600/ether_io.hpp" #include "RX600/ssi.hpp" #include "RX600/src.hpp" #include "RX600/sdhi.hpp" #include "RX600/sdhi_io.hpp" #include "RX600/standby_ram.hpp" #include "RX600/ssi_io.hpp" #include "RX600/dmac_mgr.hpp" #else # error "Requires SIG_XXX to be defined" #endif <commit_msg>update: include path<commit_after>#pragma once //=====================================================================// /*! @file @brief ルネサス RX 選択 @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2016, 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/byte_order.h" #include "common/vect.h" #include "common/delay.hpp" #if defined(SIG_RX621) #include "RX600/port.hpp" #include "RX600/cmt.hpp" #include "RX621/system.hpp" #include "RX621/sci.hpp" #include "RX621/icu.hpp" #elif defined(SIG_RX24T) #include "RX24T/peripheral.hpp" #include "RX600/port.hpp" #include "RX24T/system.hpp" #include "RX24T/system_io.hpp" #include "RX24T/dtc.hpp" #include "RX24T/icu.hpp" #include "RX24T/icu_mgr.hpp" #include "RX24T/mtu3.hpp" #include "RX24T/poe3.hpp" #include "RX24T/gpt.hpp" #include "RX24T/tmr.hpp" #include "RX600/cmt.hpp" #include "RX24T/sci.hpp" #include "RX24T/riic.hpp" #include "RX24T/rspi.hpp" #include "RX24T/crc.hpp" #include "RX24T/s12ad.hpp" #include "RX24T/adc_io.hpp" #include "RX24T/da.hpp" #include "RX24T/cmpc.hpp" #include "RX24T/doc.hpp" #include "RX24T/port_map.hpp" #include "RX24T/power_cfg.hpp" #include "RX24T/flash.hpp" #include "RX24T/flash_io.hpp" #elif defined(SIG_RX63T) #include "RX63T/peripheral.hpp" #include "RX600/port.hpp" #include "RX63T/icu.hpp" #include "RX63T/icu_mgr.hpp" #include "RX600/cmt.hpp" #include "RX63T/system.hpp" #include "RX63T/sci.hpp" #include "RX63T/port_map.hpp" #include "RX63T/power_cfg.hpp" #elif defined(SIG_RX64M) #include "RX600/peripheral.hpp" #include "RX600/system.hpp" #include "RX600/system_io.hpp" #include "RX600/dmac.hpp" #include "RX600/exdmac.hpp" #include "RX600/port.hpp" #include "RX600/bus.hpp" #include "RX600/mpc.hpp" #include "RX600/icu.hpp" #include "RX600/icu_mgr.hpp" #include "RX600/tpu.hpp" #include "RX600/cmt.hpp" #include "RX600/mtu3.hpp" #include "RX600/sci.hpp" #include "RX600/scif.hpp" #include "RX600/riic.hpp" #include "RX600/can.hpp" #include "RX600/rspi.hpp" #include "RX600/qspi.hpp" #include "RX600/port_map.hpp" #include "RX600/power_cfg.hpp" #include "RX600/s12adc.hpp" #include "RX600/adc_io.hpp" #include "RX600/r12da.hpp" #include "RX600/dac_out.hpp" #include "RX600/sdram.hpp" #include "RX600/etherc.hpp" #include "RX600/edmac.hpp" #include "RX600/usb.hpp" #include "RX600/rtc.hpp" #include "RX600/rtc_io.hpp" #include "RX600/wdta.hpp" #include "RX600/flash.hpp" #include "RX600/flash_io.hpp" #include "RX600/ether_io.hpp" #include "RX600/ssi.hpp" #include "RX600/src.hpp" #include "RX600/sdhi.hpp" #include "RX600/sdhi_io.hpp" #include "RX600/standby_ram.hpp" #include "RX600/ssi_io.hpp" #include "RX600/dmac_mgr.hpp" #elif defined(SIG_RX65N) #include "RX600/peripheral.hpp" #include "RX600/system.hpp" #include "RX600/system_io.hpp" #include "RX600/dmac.hpp" #include "RX600/exdmac.hpp" #include "RX600/port.hpp" #include "RX600/bus.hpp" #include "RX600/mpc.hpp" #include "RX600/icu.hpp" #include "RX600/icu_mgr.hpp" #include "RX600/tpu.hpp" #include "RX600/cmt.hpp" #include "RX600/mtu3.hpp" #include "RX600/sci.hpp" #include "RX600/scif.hpp" #include "RX600/riic.hpp" #include "RX600/can.hpp" #include "RX600/rspi.hpp" #include "RX600/qspi.hpp" #include "RX600/port_map.hpp" #include "RX600/power_cfg.hpp" #include "RX65x/s12adf.hpp" #include "RX600/adc_io.hpp" #include "RX600/r12da.hpp" #include "RX600/dac_out.hpp" #include "RX600/sdram.hpp" #include "RX600/etherc.hpp" #include "RX600/edmac.hpp" #include "RX600/usb.hpp" #include "RX600/rtc.hpp" #include "RX600/rtc_io.hpp" #include "RX600/wdta.hpp" #include "RX600/flash.hpp" #include "RX600/flash_io.hpp" #include "RX600/ether_io.hpp" #include "RX600/sdhi.hpp" #include "RX600/sdhi_io.hpp" #include "RX600/standby_ram.hpp" #include "RX65x/glcdc.hpp" #include "RX65x/glcdc_io.hpp" #include "RX65x/drw2d.hpp" #include "RX65x/drw2d_mgr.hpp" #include "RX600/dmac_mgr.hpp" #elif defined(SIG_RX71M) #include "RX600/peripheral.hpp" #include "RX600/system.hpp" #include "RX600/system_io.hpp" #include "RX600/dmac.hpp" #include "RX600/exdmac.hpp" #include "RX600/port.hpp" #include "RX600/bus.hpp" #include "RX600/mpc.hpp" #include "RX600/icu.hpp" #include "RX600/icu_mgr.hpp" #include "RX600/tpu.hpp" #include "RX600/cmt.hpp" #include "RX600/mtu3.hpp" #include "RX600/sci.hpp" #include "RX600/scif.hpp" #include "RX600/riic.hpp" #include "RX600/can.hpp" #include "RX600/rspi.hpp" #include "RX600/qspi.hpp" #include "RX600/port_map.hpp" #include "RX600/power_cfg.hpp" #include "RX600/s12adc.hpp" #include "RX600/adc_io.hpp" #include "RX600/r12da.hpp" #include "RX600/dac_out.hpp" #include "RX600/sdram.hpp" #include "RX600/etherc.hpp" #include "RX600/edmac.hpp" #include "RX600/usb.hpp" #include "RX600/rtc.hpp" #include "RX600/rtc_io.hpp" #include "RX600/wdta.hpp" #include "RX600/flash.hpp" #include "RX600/flash_io.hpp" #include "RX600/ether_io.hpp" #include "RX600/ssi.hpp" #include "RX600/src.hpp" #include "RX600/sdhi.hpp" #include "RX600/sdhi_io.hpp" #include "RX600/standby_ram.hpp" #include "RX600/ssi_io.hpp" #include "RX600/dmac_mgr.hpp" #else # error "Requires SIG_XXX to be defined" #endif <|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 "base/file_path.h" #include "content/test/layout_browsertest.h" class IndexedDBLayoutTest : public InProcessBrowserLayoutTest { public: IndexedDBLayoutTest() : InProcessBrowserLayoutTest( FilePath().AppendASCII("storage").AppendASCII("indexeddb")) { } virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { InProcessBrowserLayoutTest::SetUpInProcessBrowserTestFixture(); AddResourceForLayoutTest( FilePath().AppendASCII("fast").AppendASCII("js"), FilePath().AppendASCII("resources")); } }; namespace { static const char* kLayoutTestFileNames[] = { "basics.html", "basics-shared-workers.html", "basics-workers.html", "index-basics.html", "objectstore-basics.html", "prefetch-bugfix-108071.html", }; } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, FirstTest) { for (size_t i = 0; i < arraysize(kLayoutTestFileNames); ++i) RunLayoutTest(kLayoutTestFileNames[i]); } <commit_msg>Run indexeddb layout tests as browser tests.<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 "base/file_path.h" #include "content/test/layout_browsertest.h" class IndexedDBLayoutTest : public InProcessBrowserLayoutTest { public: IndexedDBLayoutTest() : InProcessBrowserLayoutTest( FilePath().AppendASCII("storage").AppendASCII("indexeddb")) { } virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { InProcessBrowserLayoutTest::SetUpInProcessBrowserTestFixture(); AddResourceForLayoutTest( FilePath().AppendASCII("fast").AppendASCII("js"), FilePath().AppendASCII("resources")); } void RunLayoutTests(const char* file_names[]) { for (size_t i = 0; file_names[i]; i++) RunLayoutTest(file_names[i]); } }; namespace { static const char* kBasicTests[] = { "basics.html", "basics-shared-workers.html", "basics-workers.html", "database-basics.html", "factory-basics.html", "index-basics.html", "objectstore-basics.html", NULL }; static const char* kComplexTests[] = { "prefetch-bugfix-108071.html", NULL }; static const char* kIndexTests[] = { "deleteIndex.html", "index-basics-workers.html", "index-count.html", "index-cursor.html", // Locally takes ~6s compared to <1 for the others. "index-get-key-argument-required.html", "index-multientry.html", "index-population.html", "index-unique.html", NULL }; static const char* kKeyTests[] = { "key-generator.html", "keypath-basics.html", "keypath-edges.html", "keypath-fetch-key.html", "keyrange.html", "keyrange-required-arguments.html", "key-sort-order-across-types.html", "key-sort-order-date.html", "key-type-array.html", "key-type-infinity.html", "invalid-keys.html", NULL }; static const char* kTransactionTests[] = { // "transaction-abort.html", // Flaky, http://crbug.com/83226 "transaction-abort-with-js-recursion-cross-frame.html", "transaction-abort-with-js-recursion.html", "transaction-abort-workers.html", "transaction-after-close.html", "transaction-and-objectstore-calls.html", "transaction-basics.html", "transaction-crash-on-abort.html", "transaction-event-propagation.html", "transaction-read-only.html", "transaction-rollback.html", "transaction-storeNames-required.html", NULL }; } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, BasicTests) { RunLayoutTests(kBasicTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, ComplexTests) { RunLayoutTests(kComplexTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, IndexTests) { RunLayoutTests(kIndexTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, KeyTests) { RunLayoutTests(kKeyTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, TransactionTests) { RunLayoutTests(kTransactionTests); } <|endoftext|>
<commit_before>/*************************************************************************** // Modified by Kishora Nayak - 14/06/2016 // Modified by Enrico Fragiacomo - 15/01/2014 // Modified by Kunal Garg - 04/02/2017 // Based on AddAnalysisTaskRsnMini // pPb specific settings from AddTaskKStarPPB.C // // Macro to configure the KStarPlusMinus analysis task // It calls all configs desired by the user, by means // of the boolean switches defined in the first lines. // --- // Inputs: // 1) flag to know if running on MC or data // 2) collision system, whether pp, pPb or PbPb // -- // Returns: // kTRUE --> initialization successful // kFALSE --> initialization failed (some config gave errors) // ****************************************************************************/ //enum ERsnCollType_t { kPP=0, kPPb, kPbPb}; enum pairYCutSet { kPairDefault, // USED ONLY FOR pA kNegative, // USED ONLY FOR pA kCentral // USED ONLY FOR pA }; /*enum eventCutSet { kOld = -1, kEvtDefault, //=0 kNoPileUpCut, //=1 kPileUpMV, //=2 kPileUpSPD3, //=3 kDefaultVtx8, //=4 kDefaultVtx5 //=5 };*/ enum eventCutSet { kEvtDefault=0, kNoPileUpCut, //=1 kDefaultVtx12,//=2 kDefaultVtx8, //=3 kDefaultVtx5, //=4 kMCEvtDefault //=5 }; enum eventMixConfig { kDisabled = -1, kMixDefault, //=0 //10 events, Dvz = 1cm, DC = 10 k5Evts, //=1 //5 events, Dvz = 1cm, DC = 10 k5Cent, //=2 //10 events, Dvz = 1cm, DC = 5 }; AliRsnMiniAnalysisTask *AddTaskKStarPlusMinusRun2 ( Bool_t isMC, Bool_t isPP, // Int_t collSyst, Float_t cutV = 10.0, Int_t evtCutSetID = 0, Int_t pairCutSetID = 0, Int_t mixingConfigID = 0, Int_t aodFilterBit = 5, Bool_t enableMonitor=kTRUE, TString monitorOpt="pp", Float_t piPIDCut = 3.0, AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutPiCandidate = AliRsnCutSetDaughterParticle::kTPCpidphipp2015, Float_t pi_k0s_PIDCut = 5.0, Float_t massTol = 0.03, Float_t massTolVeto = 0.004, Float_t pLife = 20, Float_t radiuslow = 0.5, Float_t radiushigh = 200, Bool_t Switch = kFALSE, Float_t k0sDCA = 0.3, Float_t k0sCosPoinAn = 0.97, Float_t k0sDaughDCA = 1.0, Int_t NTPCcluster = 70, Float_t maxDiffVzMix = 1.0, Float_t maxDiffMultMix = 10.0, Float_t maxDiffAngleMixDeg = 20.0, Int_t aodN = 68, TString outNameSuffix = "KStarPlusMinus_TestPID", Int_t centr = 0, Bool_t ptDep = kTRUE, Float_t DCAxy = 0.06, Bool_t enableSys = kFALSE, Int_t Sys= 0 ) { //------------------------------------------- // event cuts //------------------------------------------- UInt_t triggerMask=AliVEvent::kINT7; Bool_t rejectPileUp=kTRUE; Double_t vtxZcut=10.0;//cm, default cut on vtx z // cout<<"EVENTCUTID is "<<evtCutSetID<<endl; if(evtCutSetID==eventCutSet::kDefaultVtx12) vtxZcut=12.0; //cm if(evtCutSetID==eventCutSet::kDefaultVtx8) vtxZcut=8.0; //cm if(evtCutSetID==eventCutSet::kDefaultVtx5) vtxZcut=5.0; //cm if(evtCutSetID==eventCutSet::kNoPileUpCut) rejectPileUp=kFALSE; if(isMC) rejectPileUp=kFALSE; //------------------------------------------- //mixing settings //------------------------------------------- Int_t nmix = 10; if (mixingConfigID == eventMixConfig::kMixDefault) nmix = 10; if (mixingConfigID == eventMixConfig::k5Evts) nmix = 5; if (mixingConfigID == eventMixConfig::k5Cent) maxDiffMultMix = 5; // // -- INITIALIZATION ---------------------------------------------------------------------------- // retrieve analysis manager // AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskKStarPlusMinus", "No analysis manager to connect to."); return NULL; } // create the task and configure TString taskName = Form("KStarPlusMinus%s%s", (isPP? "pp" : "PbPb"), (isMC ? "MC" : "Data")); AliRsnMiniAnalysisTask* task = new AliRsnMiniAnalysisTask(taskName.Data(),isMC); //task->UseESDTriggerMask(AliVEvent::kINT7); //ESD ****** check this ***** task->SelectCollisionCandidates(triggerMask); //AOD //if(isPP) task->UseMultiplicity("QUALITY"); //else task->UseCentrality("V0M"); // set event mixing options task->UseContinuousMix(); //task->UseBinnedMix(); task->SetNMix(nmix); task->SetMaxDiffVz(maxDiffVzMix); task->SetMaxDiffMult(maxDiffMultMix); ::Info("AddAnalysisTaskTOFKStar", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %\5.3f", nmix, maxDiffVzMix, maxDiffMultMix)); mgr->AddTask(task); // // -- EVENT CUTS (same for all configs) --------------------------------------------------------- // // cut on primary vertex: // - 2nd argument --> |Vz| range // - 3rd argument --> minimum required number of contributors // - 4th argument --> tells if TPC stand-alone vertexes must be accepted AliRsnCutPrimaryVertex *cutVertex = new AliRsnCutPrimaryVertex("cutVertex", cutV, 0, kFALSE); cutVertex->SetCheckZResolutionSPD(); cutVertex->SetCheckDispersionSPD(); cutVertex->SetCheckZDifferenceSPDTrack(); AliRsnCutEventUtils* cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp); cutEventUtils->SetCheckIncompleteDAQ(); cutEventUtils->SetCheckSPDClusterVsTrackletBG(); if(!isMC){ //assume pp data cutVertex->SetCheckPileUp(rejectPileUp);// set the check for pileup ::Info("AddAnalysisTaskTOFKStar", Form(":::::::::::::::::: Pile-up rejection mode: %s", (rejectPileUp)?"ON":"OFF")); } // define and fill cut set for event cut AliRsnCutSet* eventCuts=new AliRsnCutSet("eventCuts",AliRsnTarget::kEvent); eventCuts->AddCut(cutEventUtils); eventCuts->AddCut(cutVertex); eventCuts->SetCutScheme(Form("%s&%s",cutEventUtils->GetName(),cutVertex->GetName())); task->SetEventCuts(eventCuts); // -- EVENT-ONLY COMPUTATIONS ------------------------------------------------------------------- //vertex Int_t vtxID=task->CreateValue(AliRsnMiniValue::kVz,kFALSE); AliRsnMiniOutput* outVtx=task->CreateOutput("eventVtx","HIST","EVENT"); outVtx->AddAxis(vtxID,240,-12.0,12.0); //multiplicity Int_t multID=task->CreateValue(AliRsnMiniValue::kMult,kFALSE); AliRsnMiniOutput* outMult=task->CreateOutput("eventMult","HIST","EVENT"); //if(isPP) outMult->AddAxis(multID,400,0.5,400.5); //else outMult->AddAxis(multID,100,0.,100.); TH2F* hvz=new TH2F("hVzVsCent","",100,0.,100., 240,-12.0,12.0); task->SetEventQAHist("vz",hvz);//plugs this histogram into the fHAEventVz data member TH2F* hmc=new TH2F("MultiVsCent","", 100,0.,100., 400,0.5,400.5); hmc->GetYaxis()->SetTitle("QUALITY"); task->SetEventQAHist("multicent",hmc);//plugs this histogram into the fHAEventMultiCent data member // // -- PAIR CUTS (common to all resonances) ------------------------------------------------------ Double_t minYlab = -0.5; Double_t maxYlab = 0.5; AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange); cutY->SetRangeD(minYlab, maxYlab); AliRsnCutMiniPair *cutV0 = new AliRsnCutMiniPair("cutV0", AliRsnCutMiniPair::kContainsV0Daughter); AliRsnCutSet *cutsPair = new AliRsnCutSet("pairCuts", AliRsnTarget::kMother); cutsPair->AddCut(cutY); cutsPair->AddCut(cutV0); cutsPair->SetCutScheme(TString::Format("%s&%s",cutY->GetName(),cutV0->GetName()).Data()); // // -- CONFIG ANALYSIS -------------------------------------------------------------------------- gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigKStarPlusMinusRun2.C"); //gROOT->LoadMacro("ConfigKStarPlusMinusRun2.C"); if (isMC) { Printf("========================== MC analysis - PID cuts not used"); } else Printf("========================== DATA analysis - PID cuts used"); if (!ConfigKStarPlusMinusRun2(task, isPP, isMC, piPIDCut, cutPiCandidate, pi_k0s_PIDCut, aodFilterBit, enableMonitor, monitorOpt.Data(), massTol, massTolVeto, pLife, radiuslow, radiushigh, Switch, k0sDCA, k0sCosPoinAn, k0sDaughDCA, NTPCcluster, "", cutsPair, ptDep, DCAxy, enableSys, Sys)) return 0x0; // // -- CONTAINERS -------------------------------------------------------------------------------- // TString outputFileName = AliAnalysisManager::GetCommonFileName(); // outputFileName += ":Rsn"; Printf("AddTaskKStarPlusMinus - Set OutputFileName : \n %s\n", outputFileName.Data() ); AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s_%.1f_%.1f_%.2f_%.3f_%.f_%.f_%.f_%.1f_%.2f_%.1f_%.3f_%.1f", outNameSuffix.Data(),piPIDCut,pi_k0s_PIDCut,massTol,massTolVeto,pLife,radiuslow,radiushigh,k0sDCA,k0sCosPoinAn,k0sDaughDCA, DCAxy, Sys), TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, output); return task; } <commit_msg>Rsn Fixed V0 cut in AddTaskKStarPlusMinusRun2.C<commit_after>/*************************************************************************** // Modified by Kishora Nayak - 14/06/2016 // Modified by Enrico Fragiacomo - 15/01/2014 // Modified by Kunal Garg - 04/02/2017 // Based on AddAnalysisTaskRsnMini // pPb specific settings from AddTaskKStarPPB.C // // Macro to configure the KStarPlusMinus analysis task // It calls all configs desired by the user, by means // of the boolean switches defined in the first lines. // --- // Inputs: // 1) flag to know if running on MC or data // 2) collision system, whether pp, pPb or PbPb // -- // Returns: // kTRUE --> initialization successful // kFALSE --> initialization failed (some config gave errors) // ****************************************************************************/ //enum ERsnCollType_t { kPP=0, kPPb, kPbPb}; enum pairYCutSet { kPairDefault, // USED ONLY FOR pA kNegative, // USED ONLY FOR pA kCentral // USED ONLY FOR pA }; /*enum eventCutSet { kOld = -1, kEvtDefault, //=0 kNoPileUpCut, //=1 kPileUpMV, //=2 kPileUpSPD3, //=3 kDefaultVtx8, //=4 kDefaultVtx5 //=5 };*/ enum eventCutSet { kEvtDefault=0, kNoPileUpCut, //=1 kDefaultVtx12,//=2 kDefaultVtx8, //=3 kDefaultVtx5, //=4 kMCEvtDefault //=5 }; enum eventMixConfig { kDisabled = -1, kMixDefault, //=0 //10 events, Dvz = 1cm, DC = 10 k5Evts, //=1 //5 events, Dvz = 1cm, DC = 10 k5Cent, //=2 //10 events, Dvz = 1cm, DC = 5 }; Ali:RsnMiniAnalysisTask *AddTaskKStarPlusMinusRun2 ( Bool_t isMC, Bool_t isPP, // Int_t collSyst, Float_t cutV = 10.0, Int_t evtCutSetID = 0, Int_t pairCutSetID = 0, Int_t mixingConfigID = 0, Int_t aodFilterBit = 5, Bool_t enableMonitor=kTRUE, TString monitorOpt="pp", Float_t piPIDCut = 3.0, AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutPiCandidate = AliRsnCutSetDaughterParticle::kTPCpidphipp2015, Float_t pi_k0s_PIDCut = 5.0, Float_t massTol = 0.03, Float_t massTolVeto = 0.004, Float_t pLife = 20, Float_t radiuslow = 0.5, Float_t radiushigh = 200, Bool_t Switch = kFALSE, Float_t k0sDCA = 0.3, Float_t k0sCosPoinAn = 0.97, Float_t k0sDaughDCA = 1.0, Int_t NTPCcluster = 70, Float_t maxDiffVzMix = 1.0, Float_t maxDiffMultMix = 10.0, Float_t maxDiffAngleMixDeg = 20.0, Int_t aodN = 68, TString outNameSuffix = "KStarPlusMinus_TestPID", Int_t centr = 0, Bool_t ptDep = kTRUE, Float_t DCAxy = 0.06, Bool_t enableSys = kFALSE, Int_t Sys= 0 ) { //------------------------------------------- // event cuts //------------------------------------------- UInt_t triggerMask=AliVEvent::kINT7; Bool_t rejectPileUp=kTRUE; Double_t vtxZcut=10.0;//cm, default cut on vtx z // cout<<"EVENTCUTID is "<<evtCutSetID<<endl; if(evtCutSetID==eventCutSet::kDefaultVtx12) vtxZcut=12.0; //cm if(evtCutSetID==eventCutSet::kDefaultVtx8) vtxZcut=8.0; //cm if(evtCutSetID==eventCutSet::kDefaultVtx5) vtxZcut=5.0; //cm if(evtCutSetID==eventCutSet::kNoPileUpCut) rejectPileUp=kFALSE; if(isMC) rejectPileUp=kFALSE; //------------------------------------------- //mixing settings //------------------------------------------- Int_t nmix = 10; if (mixingConfigID == eventMixConfig::kMixDefault) nmix = 10; if (mixingConfigID == eventMixConfig::k5Evts) nmix = 5; if (mixingConfigID == eventMixConfig::k5Cent) maxDiffMultMix = 5; // // -- INITIALIZATION ---------------------------------------------------------------------------- // retrieve analysis manager // AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskKStarPlusMinus", "No analysis manager to connect to."); return NULL; } // create the task and configure TString taskName = Form("KStarPlusMinus%s%s", (isPP? "pp" : "PbPb"), (isMC ? "MC" : "Data")); AliRsnMiniAnalysisTask* task = new AliRsnMiniAnalysisTask(taskName.Data(),isMC); //task->UseESDTriggerMask(AliVEvent::kINT7); //ESD ****** check this ***** task->SelectCollisionCandidates(triggerMask); //AOD //if(isPP) task->UseMultiplicity("QUALITY"); //else task->UseCentrality("V0M"); // set event mixing options task->UseContinuousMix(); //task->UseBinnedMix(); task->SetNMix(nmix); task->SetMaxDiffVz(maxDiffVzMix); task->SetMaxDiffMult(maxDiffMultMix); ::Info("AddAnalysisTaskTOFKStar", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %\5.3f", nmix, maxDiffVzMix, maxDiffMultMix)); mgr->AddTask(task); // // -- EVENT CUTS (same for all configs) --------------------------------------------------------- // // cut on primary vertex: // - 2nd argument --> |Vz| range // - 3rd argument --> minimum required number of contributors // - 4th argument --> tells if TPC stand-alone vertexes must be accepted AliRsnCutPrimaryVertex *cutVertex = new AliRsnCutPrimaryVertex("cutVertex", cutV, 0, kFALSE); cutVertex->SetCheckZResolutionSPD(); cutVertex->SetCheckDispersionSPD(); cutVertex->SetCheckZDifferenceSPDTrack(); AliRsnCutEventUtils* cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp); cutEventUtils->SetCheckIncompleteDAQ(); cutEventUtils->SetCheckSPDClusterVsTrackletBG(); if(!isMC){ //assume pp data cutVertex->SetCheckPileUp(rejectPileUp);// set the check for pileup ::Info("AddAnalysisTaskTOFKStar", Form(":::::::::::::::::: Pile-up rejection mode: %s", (rejectPileUp)?"ON":"OFF")); } // define and fill cut set for event cut AliRsnCutSet* eventCuts=new AliRsnCutSet("eventCuts",AliRsnTarget::kEvent); eventCuts->AddCut(cutEventUtils); eventCuts->AddCut(cutVertex); eventCuts->SetCutScheme(Form("%s&%s",cutEventUtils->GetName(),cutVertex->GetName())); task->SetEventCuts(eventCuts); // -- EVENT-ONLY COMPUTATIONS ------------------------------------------------------------------- //vertex Int_t vtxID=task->CreateValue(AliRsnMiniValue::kVz,kFALSE); AliRsnMiniOutput* outVtx=task->CreateOutput("eventVtx","HIST","EVENT"); outVtx->AddAxis(vtxID,240,-12.0,12.0); //multiplicity Int_t multID=task->CreateValue(AliRsnMiniValue::kMult,kFALSE); AliRsnMiniOutput* outMult=task->CreateOutput("eventMult","HIST","EVENT"); //if(isPP) outMult->AddAxis(multID,400,0.5,400.5); //else outMult->AddAxis(multID,100,0.,100.); TH2F* hvz=new TH2F("hVzVsCent","",100,0.,100., 240,-12.0,12.0); task->SetEventQAHist("vz",hvz);//plugs this histogram into the fHAEventVz data member TH2F* hmc=new TH2F("MultiVsCent","", 100,0.,100., 400,0.5,400.5); hmc->GetYaxis()->SetTitle("QUALITY"); task->SetEventQAHist("multicent",hmc);//plugs this histogram into the fHAEventMultiCent data member // // -- PAIR CUTS (common to all resonances) ------------------------------------------------------ Double_t minYlab = -0.5; Double_t maxYlab = 0.5; AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange); cutY->SetRangeD(minYlab, maxYlab); AliRsnCutSet *cutsPair = new AliRsnCutSet("pairCuts", AliRsnTarget::kMother); cutsPair->AddCut(cutY); if (ptDep) { cutsPair->SetCutScheme(cutY->GetName()); } else { AliRsnCutMiniPair *cutV0 = new AliRsnCutMiniPair("cutV0", AliRsnCutMiniPair::kContainsV0Daughter); cutsPair->AddCut(cutV0); cutsPair->SetCutScheme(TString::Format("%s&!%s",cutY->GetName(),cutV0->GetName()).Data()); } // // -- CONFIG ANALYSIS -------------------------------------------------------------------------- gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigKStarPlusMinusRun2.C"); //gROOT->LoadMacro("ConfigKStarPlusMinusRun2.C"); if (isMC) { Printf("========================== MC analysis - PID cuts not used"); } else Printf("========================== DATA analysis - PID cuts used"); if (!ConfigKStarPlusMinusRun2(task, isPP, isMC, piPIDCut, cutPiCandidate, pi_k0s_PIDCut, aodFilterBit, enableMonitor, monitorOpt.Data(), massTol, massTolVeto, pLife, radiuslow, radiushigh, Switch, k0sDCA, k0sCosPoinAn, k0sDaughDCA, NTPCcluster, "", cutsPair, ptDep, DCAxy, enableSys, Sys)) return 0x0; // // -- CONTAINERS -------------------------------------------------------------------------------- // TString outputFileName = AliAnalysisManager::GetCommonFileName(); // outputFileName += ":Rsn"; Printf("AddTaskKStarPlusMinus - Set OutputFileName : \n %s\n", outputFileName.Data() ); AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s_%.1f_%.1f_%.2f_%.3f_%.f_%.f_%.f_%.1f_%.2f_%.1f_%.3f_%.1f", outNameSuffix.Data(),piPIDCut,pi_k0s_PIDCut,massTol,massTolVeto,pLife,radiuslow,radiushigh,k0sDCA,k0sCosPoinAn,k0sDaughDCA, DCAxy, Sys), TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, output); return task; } <|endoftext|>
<commit_before>/******************************************************************************\ * File: vcs.cpp * Purpose: Implementation of wxExVCS class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/config.h> #include <wx/extension/vcs.h> #include <wx/extension/configdlg.h> #include <wx/extension/defs.h> #include <wx/extension/frame.h> #include <wx/extension/log.h> #include <wx/extension/stcdlg.h> #include <wx/extension/util.h> wxExVCS* wxExVCS::m_Self = NULL; #if wxUSE_GUI wxExSTCEntryDialog* wxExVCS::m_STCEntryDialog = NULL; #endif wxString wxExVCS::m_UsageKey; wxExVCS::wxExVCS() : m_Type(VCS_NONE) , m_FullPath(wxEmptyString) { Initialize(); } wxExVCS::wxExVCS(int command_id, const wxString& fullpath) : m_Type(GetType(command_id)) , m_FullPath(fullpath) { Initialize(); } wxExVCS::wxExVCS(wxExVCSType type, const wxString& fullpath) : m_Type(type) , m_FullPath(fullpath) { Initialize(); } #if wxUSE_GUI int wxExVCS::ConfigDialog( wxWindow* parent, const wxString& title) const { std::vector<wxExConfigItem> v; v.push_back(wxExConfigItem()); // a spacer v.push_back(wxExConfigItem(m_UsageKey, CONFIG_CHECKBOX)); v.push_back(wxExConfigItem(_("Comparator"), CONFIG_FILEPICKERCTRL)); return wxExConfigDialog(parent, v, title).ShowModal(); } #endif bool wxExVCS::DirExists(const wxFileName& filename) const { wxFileName path(filename); switch (m_System) { case VCS_SVN: path.AppendDir(".svn"); default: wxFAIL; } return path.DirExists(); } long wxExVCS::Execute() { wxASSERT(m_Type != VCS_NONE); const wxString cwd = wxGetCwd(); wxString file; if (m_FullPath.empty()) { if (!wxSetWorkingDirectory(wxExConfigFirstOf(_("Base folder")))) { m_Output = _("Cannot set working directory"); return -1; } if (m_Type == VCS_ADD) { file = " " + wxExConfigFirstOf(_("Path")); } } else { file = " \"" + m_FullPath + "\""; } wxString comment; if (m_Type == VCS_COMMIT) { comment = " -m \"" + wxExConfigFirstOf(_("Revision comment")) + "\""; } wxString subcommand; if (UseSubcommand()) { subcommand = wxConfigBase::Get()->Read(_("Subcommand")); if (!subcommand.empty()) { subcommand = " " + subcommand; } } wxString flags; if (UseFlags()) { flags = wxConfigBase::Get()->Read(_("Flags")); if (!flags.empty()) { flags = " " + flags; } } m_CommandWithFlags = m_Command + flags; const wxString commandline = "svn " + m_Command + subcommand + flags + comment + file; #if wxUSE_STATUSBAR wxExFrame::StatusText(commandline); #endif wxArrayString output; wxArrayString errors; long retValue; if ((retValue = wxExecute( commandline, output, errors)) == -1) { // See also process, same log is shown. wxLogError(_("Cannot execute") + ": " + commandline); } else { wxExLog::Get()->Log(commandline); } if (m_FullPath.empty()) { wxSetWorkingDirectory(cwd); } m_Output.clear(); // First output the errors. for ( size_t i = 0; i < errors.GetCount(); i++) { m_Output += errors[i] + "\n"; } // Then the normal output, will be empty if there are errors. for ( size_t j = 0; j < output.GetCount(); j++) { m_Output += output[j] + "\n"; } return retValue; } #if wxUSE_GUI wxStandardID wxExVCS::ExecuteDialog(wxWindow* parent) { if (ShowDialog(parent) == wxID_CANCEL) { return wxID_CANCEL; } if (UseFlags()) { wxConfigBase::Get()->Write(m_FlagsKey, wxConfigBase::Get()->Read(_("Flags"))); } Execute(); return wxID_OK; } #endif wxExVCS* wxExVCS::Get(bool createOnDemand) { if (m_Self == NULL && createOnDemand) { m_Self = new wxExVCS; if (!wxConfigBase::Get()->Exists(m_UsageKey)) { wxConfigBase::Get()->Write(m_UsageKey, true); } } return m_Self; } wxExVCS::wxExVCSType wxExVCS::GetType(int command_id) const { switch (command_id) { case ID_EDIT_VCS_ADD: case ID_VCS_ADD: return VCS_ADD; break; case ID_EDIT_VCS_BLAME: case ID_VCS_BLAME: return VCS_BLAME; break; case ID_EDIT_VCS_CAT: return VCS_CAT; break; case ID_EDIT_VCS_COMMIT: case ID_VCS_COMMIT: return VCS_COMMIT; break; case ID_EDIT_VCS_DIFF: case ID_VCS_DIFF: return VCS_DIFF; break; case ID_EDIT_VCS_HELP: case ID_VCS_HELP: return VCS_HELP; break; case ID_EDIT_VCS_INFO: case ID_VCS_INFO: return VCS_INFO; break; case ID_EDIT_VCS_LOG: case ID_VCS_LOG: return VCS_LOG; break; case ID_EDIT_VCS_LS: case ID_VCS_LS: return VCS_LS; break; case ID_EDIT_VCS_PROPLIST: case ID_VCS_PROPLIST: return VCS_PROPLIST; break; case ID_EDIT_VCS_PROPSET: case ID_VCS_PROPSET: return VCS_PROPSET; break; case ID_EDIT_VCS_REVERT: case ID_VCS_REVERT: return VCS_REVERT; break; case ID_EDIT_VCS_STAT: case ID_VCS_STAT: return VCS_STAT; break; case ID_EDIT_VCS_UPDATE: case ID_VCS_UPDATE: return VCS_UPDATE; break; default: wxFAIL; return VCS_NONE; break; } } void wxExVCS::Initialize() { if (m_Type != VCS_NONE) { switch (m_Type) { case VCS_ADD: m_Command = "add"; break; case VCS_BLAME: m_Command = "blame"; break; case VCS_CAT: m_Command = "cat"; break; case VCS_COMMIT: m_Command = "commit"; break; case VCS_DIFF: m_Command = "diff"; break; case VCS_HELP: m_Command = "help"; break; case VCS_INFO: m_Command = "info"; break; case VCS_LOG: m_Command = "log"; break; case VCS_LS: m_Command = "ls"; break; case VCS_PROPLIST: m_Command = "proplist"; break; case VCS_PROPSET: m_Command = "propset"; break; case VCS_REVERT: m_Command = "revert"; break; case VCS_STAT: m_Command = "stat"; break; case VCS_UPDATE: m_Command = "update"; break; default: wxFAIL; break; } m_Caption = "VCS " + m_Command; // Currently no flags, as no command was executed. m_CommandWithFlags = m_Command; } m_Output.clear(); // Use general key. m_FlagsKey = wxString::Format("cvsflags/name%d", m_Type); m_System = VCS_SVN; // Currently only svn is supported. switch (m_System) { case VCS_SVN: m_UsageKey = _("Use SVN"); default: wxFAIL; } } #if wxUSE_GUI wxStandardID wxExVCS::Request(wxWindow* parent) { wxStandardID retValue; if ((retValue = ExecuteDialog(parent)) == wxID_OK) { if (!m_Output.empty()) { ShowOutput(parent); } } return retValue; } #endif wxExVCS* wxExVCS::Set(wxExVCS* vcs) { wxExVCS* old = m_Self; m_Self = vcs; return old; } #if wxUSE_GUI int wxExVCS::ShowDialog(wxWindow* parent) { std::vector<wxExConfigItem> v; if (m_Type == VCS_COMMIT) { v.push_back(wxExConfigItem( _("Revision comment"), CONFIG_COMBOBOX, wxEmptyString, true)); // required } if (m_FullPath.empty() && m_Type != VCS_HELP) { v.push_back(wxExConfigItem( _("Base folder"), CONFIG_COMBOBOXDIR, wxEmptyString, true)); // required if (m_Type == VCS_ADD) { v.push_back(wxExConfigItem( _("Path"), CONFIG_COMBOBOX, wxEmptyString, true)); // required } } if (UseFlags()) { wxConfigBase::Get()->Write( _("Flags"), wxConfigBase::Get()->Read(m_FlagsKey)); v.push_back(wxExConfigItem(_("Flags"))); } if (UseSubcommand()) { v.push_back(wxExConfigItem(_("Subcommand"))); } return wxExConfigDialog(parent, v, m_Caption).ShowModal(); } #endif #if wxUSE_GUI void wxExVCS::ShowOutput(wxWindow* parent) const { wxString caption = m_Caption; if (m_Type != VCS_HELP) { caption += " " + (!m_FullPath.empty() ? wxFileName(m_FullPath).GetFullName(): wxExConfigFirstOf(_("Base folder"))); } // Create a dialog for contents. if (m_STCEntryDialog == NULL) { m_STCEntryDialog = new wxExSTCEntryDialog( parent, caption, m_Output, wxEmptyString, wxOK, wxID_ANY, wxDefaultPosition, wxSize(575, 250)); } else { m_STCEntryDialog->SetText(m_Output); m_STCEntryDialog->SetTitle(caption); } // Add a lexer if we specified a path, asked for cat or blame // and there is a lexer. if ( !m_FullPath.empty() && (m_Type == VCS_CAT || m_Type == VCS_BLAME)) { const wxExFileName fn(m_FullPath); if (!fn.GetLexer().GetScintillaLexer().empty()) { m_STCEntryDialog->SetLexer(fn.GetLexer().GetScintillaLexer()); } } m_STCEntryDialog->Show(); } #endif bool wxExVCS::Use() const { return wxConfigBase::Get()->ReadBool(m_UsageKey, true); } bool wxExVCS::UseFlags() const { return m_Type != VCS_UPDATE && m_Type != VCS_HELP; } bool wxExVCS::UseSubcommand() const { return m_Type == VCS_HELP; } <commit_msg>added missing breaks<commit_after>/******************************************************************************\ * File: vcs.cpp * Purpose: Implementation of wxExVCS class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/config.h> #include <wx/extension/vcs.h> #include <wx/extension/configdlg.h> #include <wx/extension/defs.h> #include <wx/extension/frame.h> #include <wx/extension/log.h> #include <wx/extension/stcdlg.h> #include <wx/extension/util.h> wxExVCS* wxExVCS::m_Self = NULL; #if wxUSE_GUI wxExSTCEntryDialog* wxExVCS::m_STCEntryDialog = NULL; #endif wxString wxExVCS::m_UsageKey; wxExVCS::wxExVCS() : m_Type(VCS_NONE) , m_FullPath(wxEmptyString) { Initialize(); } wxExVCS::wxExVCS(int command_id, const wxString& fullpath) : m_Type(GetType(command_id)) , m_FullPath(fullpath) { Initialize(); } wxExVCS::wxExVCS(wxExVCSType type, const wxString& fullpath) : m_Type(type) , m_FullPath(fullpath) { Initialize(); } #if wxUSE_GUI int wxExVCS::ConfigDialog( wxWindow* parent, const wxString& title) const { std::vector<wxExConfigItem> v; v.push_back(wxExConfigItem()); // a spacer v.push_back(wxExConfigItem(m_UsageKey, CONFIG_CHECKBOX)); v.push_back(wxExConfigItem(_("Comparator"), CONFIG_FILEPICKERCTRL)); return wxExConfigDialog(parent, v, title).ShowModal(); } #endif bool wxExVCS::DirExists(const wxFileName& filename) const { wxFileName path(filename); switch (m_System) { case VCS_SVN: path.AppendDir(".svn"); break; default: wxFAIL; } return path.DirExists(); } long wxExVCS::Execute() { wxASSERT(m_Type != VCS_NONE); const wxString cwd = wxGetCwd(); wxString file; if (m_FullPath.empty()) { if (!wxSetWorkingDirectory(wxExConfigFirstOf(_("Base folder")))) { m_Output = _("Cannot set working directory"); return -1; } if (m_Type == VCS_ADD) { file = " " + wxExConfigFirstOf(_("Path")); } } else { file = " \"" + m_FullPath + "\""; } wxString comment; if (m_Type == VCS_COMMIT) { comment = " -m \"" + wxExConfigFirstOf(_("Revision comment")) + "\""; } wxString subcommand; if (UseSubcommand()) { subcommand = wxConfigBase::Get()->Read(_("Subcommand")); if (!subcommand.empty()) { subcommand = " " + subcommand; } } wxString flags; if (UseFlags()) { flags = wxConfigBase::Get()->Read(_("Flags")); if (!flags.empty()) { flags = " " + flags; } } m_CommandWithFlags = m_Command + flags; const wxString commandline = "svn " + m_Command + subcommand + flags + comment + file; #if wxUSE_STATUSBAR wxExFrame::StatusText(commandline); #endif wxArrayString output; wxArrayString errors; long retValue; if ((retValue = wxExecute( commandline, output, errors)) == -1) { // See also process, same log is shown. wxLogError(_("Cannot execute") + ": " + commandline); } else { wxExLog::Get()->Log(commandline); } if (m_FullPath.empty()) { wxSetWorkingDirectory(cwd); } m_Output.clear(); // First output the errors. for ( size_t i = 0; i < errors.GetCount(); i++) { m_Output += errors[i] + "\n"; } // Then the normal output, will be empty if there are errors. for ( size_t j = 0; j < output.GetCount(); j++) { m_Output += output[j] + "\n"; } return retValue; } #if wxUSE_GUI wxStandardID wxExVCS::ExecuteDialog(wxWindow* parent) { if (ShowDialog(parent) == wxID_CANCEL) { return wxID_CANCEL; } if (UseFlags()) { wxConfigBase::Get()->Write(m_FlagsKey, wxConfigBase::Get()->Read(_("Flags"))); } Execute(); return wxID_OK; } #endif wxExVCS* wxExVCS::Get(bool createOnDemand) { if (m_Self == NULL && createOnDemand) { m_Self = new wxExVCS; if (!wxConfigBase::Get()->Exists(m_UsageKey)) { wxConfigBase::Get()->Write(m_UsageKey, true); } } return m_Self; } wxExVCS::wxExVCSType wxExVCS::GetType(int command_id) const { switch (command_id) { case ID_EDIT_VCS_ADD: case ID_VCS_ADD: return VCS_ADD; break; case ID_EDIT_VCS_BLAME: case ID_VCS_BLAME: return VCS_BLAME; break; case ID_EDIT_VCS_CAT: return VCS_CAT; break; case ID_EDIT_VCS_COMMIT: case ID_VCS_COMMIT: return VCS_COMMIT; break; case ID_EDIT_VCS_DIFF: case ID_VCS_DIFF: return VCS_DIFF; break; case ID_EDIT_VCS_HELP: case ID_VCS_HELP: return VCS_HELP; break; case ID_EDIT_VCS_INFO: case ID_VCS_INFO: return VCS_INFO; break; case ID_EDIT_VCS_LOG: case ID_VCS_LOG: return VCS_LOG; break; case ID_EDIT_VCS_LS: case ID_VCS_LS: return VCS_LS; break; case ID_EDIT_VCS_PROPLIST: case ID_VCS_PROPLIST: return VCS_PROPLIST; break; case ID_EDIT_VCS_PROPSET: case ID_VCS_PROPSET: return VCS_PROPSET; break; case ID_EDIT_VCS_REVERT: case ID_VCS_REVERT: return VCS_REVERT; break; case ID_EDIT_VCS_STAT: case ID_VCS_STAT: return VCS_STAT; break; case ID_EDIT_VCS_UPDATE: case ID_VCS_UPDATE: return VCS_UPDATE; break; default: wxFAIL; return VCS_NONE; break; } } void wxExVCS::Initialize() { if (m_Type != VCS_NONE) { switch (m_Type) { case VCS_ADD: m_Command = "add"; break; case VCS_BLAME: m_Command = "blame"; break; case VCS_CAT: m_Command = "cat"; break; case VCS_COMMIT: m_Command = "commit"; break; case VCS_DIFF: m_Command = "diff"; break; case VCS_HELP: m_Command = "help"; break; case VCS_INFO: m_Command = "info"; break; case VCS_LOG: m_Command = "log"; break; case VCS_LS: m_Command = "ls"; break; case VCS_PROPLIST: m_Command = "proplist"; break; case VCS_PROPSET: m_Command = "propset"; break; case VCS_REVERT: m_Command = "revert"; break; case VCS_STAT: m_Command = "stat"; break; case VCS_UPDATE: m_Command = "update"; break; default: wxFAIL; break; } m_Caption = "VCS " + m_Command; // Currently no flags, as no command was executed. m_CommandWithFlags = m_Command; } m_Output.clear(); // Use general key. m_FlagsKey = wxString::Format("cvsflags/name%d", m_Type); m_System = VCS_SVN; // Currently only svn is supported. switch (m_System) { case VCS_SVN: m_UsageKey = _("Use SVN"); break; default: wxFAIL; } } #if wxUSE_GUI wxStandardID wxExVCS::Request(wxWindow* parent) { wxStandardID retValue; if ((retValue = ExecuteDialog(parent)) == wxID_OK) { if (!m_Output.empty()) { ShowOutput(parent); } } return retValue; } #endif wxExVCS* wxExVCS::Set(wxExVCS* vcs) { wxExVCS* old = m_Self; m_Self = vcs; return old; } #if wxUSE_GUI int wxExVCS::ShowDialog(wxWindow* parent) { std::vector<wxExConfigItem> v; if (m_Type == VCS_COMMIT) { v.push_back(wxExConfigItem( _("Revision comment"), CONFIG_COMBOBOX, wxEmptyString, true)); // required } if (m_FullPath.empty() && m_Type != VCS_HELP) { v.push_back(wxExConfigItem( _("Base folder"), CONFIG_COMBOBOXDIR, wxEmptyString, true)); // required if (m_Type == VCS_ADD) { v.push_back(wxExConfigItem( _("Path"), CONFIG_COMBOBOX, wxEmptyString, true)); // required } } if (UseFlags()) { wxConfigBase::Get()->Write( _("Flags"), wxConfigBase::Get()->Read(m_FlagsKey)); v.push_back(wxExConfigItem(_("Flags"))); } if (UseSubcommand()) { v.push_back(wxExConfigItem(_("Subcommand"))); } return wxExConfigDialog(parent, v, m_Caption).ShowModal(); } #endif #if wxUSE_GUI void wxExVCS::ShowOutput(wxWindow* parent) const { wxString caption = m_Caption; if (m_Type != VCS_HELP) { caption += " " + (!m_FullPath.empty() ? wxFileName(m_FullPath).GetFullName(): wxExConfigFirstOf(_("Base folder"))); } // Create a dialog for contents. if (m_STCEntryDialog == NULL) { m_STCEntryDialog = new wxExSTCEntryDialog( parent, caption, m_Output, wxEmptyString, wxOK, wxID_ANY, wxDefaultPosition, wxSize(575, 250)); } else { m_STCEntryDialog->SetText(m_Output); m_STCEntryDialog->SetTitle(caption); } // Add a lexer if we specified a path, asked for cat or blame // and there is a lexer. if ( !m_FullPath.empty() && (m_Type == VCS_CAT || m_Type == VCS_BLAME)) { const wxExFileName fn(m_FullPath); if (!fn.GetLexer().GetScintillaLexer().empty()) { m_STCEntryDialog->SetLexer(fn.GetLexer().GetScintillaLexer()); } } m_STCEntryDialog->Show(); } #endif bool wxExVCS::Use() const { return wxConfigBase::Get()->ReadBool(m_UsageKey, true); } bool wxExVCS::UseFlags() const { return m_Type != VCS_UPDATE && m_Type != VCS_HELP; } bool wxExVCS::UseSubcommand() const { return m_Type == VCS_HELP; } <|endoftext|>
<commit_before>/******************************************************************************\ * File: vcs.cpp * Purpose: Implementation of wxExVCS class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/extension/vcs.h> #include <wx/extension/configdlg.h> #include <wx/extension/defs.h> #include <wx/extension/frame.h> #include <wx/extension/log.h> #include <wx/extension/stcdlg.h> #include <wx/extension/util.h> wxExVCS* wxExVCS::m_Self = NULL; #if wxUSE_GUI wxExSTCEntryDialog* wxExVCS::m_STCEntryDialog = NULL; #endif wxExVCS::wxExVCS() : m_Command(VCS_NO_COMMAND) , m_FileName(wxExFileName()) { Initialize(); } wxExVCS::wxExVCS(int command_id, const wxExFileName& filename) : m_Command(GetType(command_id)) , m_FileName(filename) { Initialize(); } wxExVCS::wxExVCS(wxExCommand type, const wxExFileName& filename) : m_Command(type) , m_FileName(filename) { Initialize(); } bool wxExVCS::CheckGIT(const wxFileName& fn) const { // The .git dir only exists in the root, so check all components. wxFileName root(fn.GetPath()); while (root.DirExists() && root.GetDirCount() > 0) { wxFileName path(root); path.AppendDir(".git"); if (path.DirExists()) { return true; } root.RemoveLastDir(); } return false; } bool wxExVCS::CheckSVN(const wxFileName& fn) const { // these cannot be combined, as AppendDir is a void (2.9.1). wxFileName path(fn); path.AppendDir(".svn"); return path.DirExists(); } #if wxUSE_GUI int wxExVCS::ConfigDialog( wxWindow* parent, const wxString& title) const { std::vector<wxExConfigItem> v; std::map<long, const wxString> choices; choices.insert(std::make_pair(VCS_NONE, _("None"))); choices.insert(std::make_pair(VCS_GIT, "GIT")); choices.insert(std::make_pair(VCS_SVN, "SVN")); choices.insert(std::make_pair(VCS_AUTO, "Auto")); v.push_back(wxExConfigItem("VCS", choices)); v.push_back(wxExConfigItem("GIT", CONFIG_FILEPICKERCTRL)); v.push_back(wxExConfigItem("SVN", CONFIG_FILEPICKERCTRL)); v.push_back(wxExConfigItem(_("Comparator"), CONFIG_FILEPICKERCTRL)); return wxExConfigDialog(parent, v, title).ShowModal(); } #endif bool wxExVCS::DirExists(const wxFileName& filename) const { switch (GetVCS()) { case VCS_AUTO: if (CheckSVN(filename)) { return true; } else { return CheckGIT(filename); } break; case VCS_GIT: return CheckGIT(filename); break; case VCS_NONE: break; // prevent wxFAIL case VCS_SVN: return CheckSVN(filename); break; default: wxFAIL; } return false; } long wxExVCS::Execute() { wxASSERT(m_Command != VCS_NO_COMMAND); wxString cwd; wxString file; if (!m_FileName.IsOk()) { cwd = wxGetCwd(); wxSetWorkingDirectory(wxExConfigFirstOf(_("Base folder"))); if (m_Command == VCS_ADD) { file = " " + wxExConfigFirstOf(_("Path")); } } else { if (GetVCS() == VCS_GIT) { cwd = wxGetCwd(); wxSetWorkingDirectory(m_FileName.GetPath()); file = " \"" + m_FileName.GetFullName() + "\""; } else { file = " \"" + m_FileName.GetFullPath() + "\""; } } wxString comment; if (m_Command == VCS_COMMIT) { comment = " -m \"" + wxExConfigFirstOf(_("Revision comment")) + "\""; } wxString subcommand; if (UseSubcommand()) { subcommand = wxConfigBase::Get()->Read(_("Subcommand")); if (!subcommand.empty()) { subcommand = " " + subcommand; } } wxString flags; if (UseFlags()) { flags = wxConfigBase::Get()->Read(_("Flags")); if (!flags.empty()) { flags = " " + flags; // If we specified help flags, we do not need a file argument. if (flags.Contains("help")) { file.clear(); } } } m_CommandWithFlags = m_CommandString + flags; wxString vcs_bin; switch (GetVCS()) { case VCS_GIT: vcs_bin = wxConfigBase::Get()->Read("GIT", "git"); break; case VCS_SVN: vcs_bin = wxConfigBase::Get()->Read("SVN", "svn"); break; default: wxFAIL; } if (vcs_bin.empty()) { wxLogError(GetVCSName() + " " + _("path is empty")); return -1; } const wxString commandline = vcs_bin + " " + m_CommandString + subcommand + flags + comment + file; #if wxUSE_STATUSBAR wxExFrame::StatusText(commandline); #endif wxArrayString output; wxArrayString errors; long retValue; // Call wxExcute to execute the cvs command and // collect the output and the errors. if ((retValue = wxExecute( commandline, output, errors)) == -1) { // See also process, same log is shown. wxLogError(_("Cannot execute") + ": " + commandline); } else { wxExLog::Get()->Log(commandline); } if (!cwd.empty()) { wxSetWorkingDirectory(cwd); } m_Output.clear(); // First output the errors. for ( size_t i = 0; i < errors.GetCount(); i++) { m_Output += errors[i] + "\n"; } // Then the normal output, will be empty if there are errors. for ( size_t j = 0; j < output.GetCount(); j++) { m_Output += output[j] + "\n"; } return retValue; } #if wxUSE_GUI wxStandardID wxExVCS::ExecuteDialog(wxWindow* parent) { if (ShowDialog(parent) == wxID_CANCEL) { return wxID_CANCEL; } if (UseFlags()) { wxConfigBase::Get()->Write(m_FlagsKey, wxConfigBase::Get()->Read(_("Flags"))); } const auto retValue = Execute(); return (retValue != -1 ? wxID_OK: wxID_CANCEL); } #endif wxExVCS* wxExVCS::Get(bool createOnDemand) { if (m_Self == NULL && createOnDemand) { m_Self = new wxExVCS; // Add default VCS. if (!wxConfigBase::Get()->Exists("VCS")) { // TODO: Add SVN only if svn bin exists on linux. wxConfigBase::Get()->Write("VCS", (long)VCS_SVN); } } return m_Self; } wxExVCS::wxExCommand wxExVCS::GetType(int command_id) const { if (command_id > ID_VCS_LOWEST && command_id < ID_VCS_HIGHEST) { return (wxExCommand)(command_id - ID_VCS_LOWEST); } else if (command_id > ID_EDIT_VCS_LOWEST && command_id < ID_EDIT_VCS_HIGHEST) { return (wxExCommand)(command_id - ID_EDIT_VCS_LOWEST); } else { wxFAIL; return VCS_NO_COMMAND; } } long wxExVCS::GetVCS() const { long vcs = wxConfigBase::Get()->ReadLong("VCS", VCS_SVN); if (vcs == VCS_AUTO) { if (CheckSVN(m_FileName)) { vcs = VCS_SVN; } else if (CheckGIT(m_FileName)) { vcs = VCS_GIT; } } return vcs; } const wxString wxExVCS::GetVCSName() const { wxString text; switch (GetVCS()) { case VCS_GIT: text = "GIT"; break; case VCS_SVN: text = "SVN"; break; default: wxFAIL; } return text; } void wxExVCS::Initialize() { if (Use() && m_Command != VCS_NO_COMMAND) { switch (GetVCS()) { case VCS_GIT: switch (m_Command) { case VCS_ADD: m_CommandString = "add"; break; case VCS_BLAME: m_CommandString = "blame"; break; case VCS_CAT: break; case VCS_COMMIT: m_CommandString = "commit"; break; case VCS_DIFF: m_CommandString = "diff"; break; case VCS_HELP: m_CommandString = "help"; break; case VCS_INFO: break; case VCS_LOG: m_CommandString = "log"; break; case VCS_LS: break; case VCS_PROPLIST: break; case VCS_PROPSET: break; case VCS_PUSH: m_CommandString = "push"; break; case VCS_REVERT: m_CommandString = "revert"; break; case VCS_SHOW: m_CommandString = "show"; break; case VCS_STAT: m_CommandString = "status"; break; case VCS_UPDATE: m_CommandString = "update"; break; default: wxFAIL; break; } break; case VCS_SVN: switch (m_Command) { case VCS_ADD: m_CommandString = "add"; break; case VCS_BLAME: m_CommandString = "blame"; break; case VCS_CAT: m_CommandString = "cat"; break; case VCS_COMMIT: m_CommandString = "commit"; break; case VCS_DIFF: m_CommandString = "diff"; break; case VCS_HELP: m_CommandString = "help"; break; case VCS_INFO: m_CommandString = "info"; break; case VCS_LOG: m_CommandString = "log"; break; case VCS_LS: m_CommandString = "ls"; break; case VCS_PROPLIST: m_CommandString = "proplist"; break; case VCS_PROPSET: m_CommandString = "propset"; break; case VCS_PUSH: break; case VCS_REVERT: m_CommandString = "revert"; break; case VCS_SHOW: break; case VCS_STAT: m_CommandString = "stat"; break; case VCS_UPDATE: m_CommandString = "update"; break; default: wxFAIL; break; } break; default: wxFAIL; } m_Caption = GetVCSName() + " " + m_CommandString; // Currently no flags, as no command was executed. m_CommandWithFlags = m_CommandString; // Use general key. m_FlagsKey = wxString::Format("cvsflags/name%d", m_Command); } m_Output.clear(); } bool wxExVCS::IsOpenCommand() const { return m_Command == wxExVCS::VCS_BLAME || m_Command == wxExVCS::VCS_CAT || m_Command == wxExVCS::VCS_DIFF; } #if wxUSE_GUI wxStandardID wxExVCS::Request(wxWindow* parent) { wxStandardID retValue; if ((retValue = ExecuteDialog(parent)) == wxID_OK) { ShowOutput(parent); } return retValue; } #endif wxExVCS* wxExVCS::Set(wxExVCS* vcs) { wxExVCS* old = m_Self; m_Self = vcs; return old; } #if wxUSE_GUI int wxExVCS::ShowDialog(wxWindow* parent) { std::vector<wxExConfigItem> v; if (m_Command == VCS_COMMIT) { v.push_back(wxExConfigItem( _("Revision comment"), CONFIG_COMBOBOX, wxEmptyString, true)); // required } if (!m_FileName.IsOk() && m_Command != VCS_HELP) { v.push_back(wxExConfigItem( _("Base folder"), CONFIG_COMBOBOXDIR, wxEmptyString, true, 1000)); if (m_Command == VCS_ADD) { v.push_back(wxExConfigItem( _("Path"), CONFIG_COMBOBOX, wxEmptyString, true)); // required } } if (UseFlags()) { wxConfigBase::Get()->Write( _("Flags"), wxConfigBase::Get()->Read(m_FlagsKey)); v.push_back(wxExConfigItem(_("Flags"))); } if (UseSubcommand()) { v.push_back(wxExConfigItem(_("Subcommand"))); } return wxExConfigDialog(parent, v, m_Caption).ShowModal(); } #endif #if wxUSE_GUI void wxExVCS::ShowOutput(wxWindow* parent) const { wxString caption = m_Caption; if (m_Command != VCS_HELP) { caption += " " + (m_FileName.IsOk() ? m_FileName.GetFullName(): wxExConfigFirstOf(_("Base folder"))); } // Create a dialog for contents. if (m_STCEntryDialog == NULL) { m_STCEntryDialog = new wxExSTCEntryDialog( parent, caption, m_Output, wxEmptyString, wxOK, wxID_ANY, wxDefaultPosition, wxSize(350, 50)); } else { m_STCEntryDialog->SetText(m_Output); m_STCEntryDialog->SetTitle(caption); } // Add a lexer when appropriate. if (m_Command == VCS_CAT || m_Command == VCS_BLAME) { if (m_FileName.GetLexer().IsOk()) { m_STCEntryDialog->SetLexer(m_FileName.GetLexer().GetScintillaLexer()); } } else if (m_Command == VCS_DIFF) { m_STCEntryDialog->SetLexer("diff"); } else { m_STCEntryDialog->SetLexer(wxEmptyString); } m_STCEntryDialog->Show(); } #endif bool wxExVCS::Use() const { return GetVCS() != VCS_NONE; } bool wxExVCS::UseFlags() const { return m_Command != VCS_UPDATE && m_Command != VCS_HELP; } bool wxExVCS::UseSubcommand() const { return m_Command == VCS_HELP; } <commit_msg>more vcs auto fixes<commit_after>/******************************************************************************\ * File: vcs.cpp * Purpose: Implementation of wxExVCS class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/extension/vcs.h> #include <wx/extension/configdlg.h> #include <wx/extension/defs.h> #include <wx/extension/frame.h> #include <wx/extension/log.h> #include <wx/extension/stcdlg.h> #include <wx/extension/util.h> wxExVCS* wxExVCS::m_Self = NULL; #if wxUSE_GUI wxExSTCEntryDialog* wxExVCS::m_STCEntryDialog = NULL; #endif wxExVCS::wxExVCS() : m_Command(VCS_NO_COMMAND) , m_FileName(wxExFileName()) { Initialize(); } wxExVCS::wxExVCS(int command_id, const wxExFileName& filename) : m_Command(GetType(command_id)) , m_FileName(filename) { Initialize(); } wxExVCS::wxExVCS(wxExCommand type, const wxExFileName& filename) : m_Command(type) , m_FileName(filename) { Initialize(); } bool wxExVCS::CheckGIT(const wxFileName& fn) const { // The .git dir only exists in the root, so check all components. wxFileName root(fn.GetPath()); while (root.DirExists() && root.GetDirCount() > 0) { wxFileName path(root); path.AppendDir(".git"); if (path.DirExists()) { return true; } root.RemoveLastDir(); } return false; } bool wxExVCS::CheckSVN(const wxFileName& fn) const { // these cannot be combined, as AppendDir is a void (2.9.1). wxFileName path(fn); path.AppendDir(".svn"); return path.DirExists(); } #if wxUSE_GUI int wxExVCS::ConfigDialog( wxWindow* parent, const wxString& title) const { std::vector<wxExConfigItem> v; std::map<long, const wxString> choices; choices.insert(std::make_pair(VCS_NONE, _("None"))); choices.insert(std::make_pair(VCS_GIT, "GIT")); choices.insert(std::make_pair(VCS_SVN, "SVN")); choices.insert(std::make_pair(VCS_AUTO, "Auto")); v.push_back(wxExConfigItem("VCS", choices)); v.push_back(wxExConfigItem("GIT", CONFIG_FILEPICKERCTRL)); v.push_back(wxExConfigItem("SVN", CONFIG_FILEPICKERCTRL)); v.push_back(wxExConfigItem(_("Comparator"), CONFIG_FILEPICKERCTRL)); return wxExConfigDialog(parent, v, title).ShowModal(); } #endif bool wxExVCS::DirExists(const wxFileName& filename) const { switch (GetVCS()) { case VCS_AUTO: if (CheckSVN(filename)) { return true; } else { return CheckGIT(filename); } break; case VCS_GIT: return CheckGIT(filename); break; case VCS_NONE: break; // prevent wxFAIL case VCS_SVN: return CheckSVN(filename); break; default: wxFAIL; } return false; } long wxExVCS::Execute() { wxASSERT(m_Command != VCS_NO_COMMAND); wxString cwd; wxString file; if (!m_FileName.IsOk()) { cwd = wxGetCwd(); wxSetWorkingDirectory(wxExConfigFirstOf(_("Base folder"))); if (m_Command == VCS_ADD) { file = " " + wxExConfigFirstOf(_("Path")); } } else { if (GetVCS() == VCS_GIT) { cwd = wxGetCwd(); wxSetWorkingDirectory(m_FileName.GetPath()); file = " \"" + m_FileName.GetFullName() + "\""; } else { file = " \"" + m_FileName.GetFullPath() + "\""; } } wxString comment; if (m_Command == VCS_COMMIT) { comment = " -m \"" + wxExConfigFirstOf(_("Revision comment")) + "\""; } wxString subcommand; if (UseSubcommand()) { subcommand = wxConfigBase::Get()->Read(_("Subcommand")); if (!subcommand.empty()) { subcommand = " " + subcommand; } } wxString flags; if (UseFlags()) { flags = wxConfigBase::Get()->Read(_("Flags")); if (!flags.empty()) { flags = " " + flags; // If we specified help flags, we do not need a file argument. if (flags.Contains("help")) { file.clear(); } } } m_CommandWithFlags = m_CommandString + flags; wxString vcs_bin; switch (GetVCS()) { case VCS_GIT: vcs_bin = wxConfigBase::Get()->Read("GIT", "git"); break; case VCS_SVN: vcs_bin = wxConfigBase::Get()->Read("SVN", "svn"); break; default: wxFAIL; } if (vcs_bin.empty()) { wxLogError(GetVCSName() + " " + _("path is empty")); return -1; } const wxString commandline = vcs_bin + " " + m_CommandString + subcommand + flags + comment + file; #if wxUSE_STATUSBAR wxExFrame::StatusText(commandline); #endif wxArrayString output; wxArrayString errors; long retValue; // Call wxExcute to execute the cvs command and // collect the output and the errors. if ((retValue = wxExecute( commandline, output, errors)) == -1) { // See also process, same log is shown. wxLogError(_("Cannot execute") + ": " + commandline); } else { wxExLog::Get()->Log(commandline); } if (!cwd.empty()) { wxSetWorkingDirectory(cwd); } m_Output.clear(); // First output the errors. for ( size_t i = 0; i < errors.GetCount(); i++) { m_Output += errors[i] + "\n"; } // Then the normal output, will be empty if there are errors. for ( size_t j = 0; j < output.GetCount(); j++) { m_Output += output[j] + "\n"; } return retValue; } #if wxUSE_GUI wxStandardID wxExVCS::ExecuteDialog(wxWindow* parent) { if (ShowDialog(parent) == wxID_CANCEL) { return wxID_CANCEL; } if (UseFlags()) { wxConfigBase::Get()->Write(m_FlagsKey, wxConfigBase::Get()->Read(_("Flags"))); } const auto retValue = Execute(); return (retValue != -1 ? wxID_OK: wxID_CANCEL); } #endif wxExVCS* wxExVCS::Get(bool createOnDemand) { if (m_Self == NULL && createOnDemand) { m_Self = new wxExVCS; // Add default VCS. if (!wxConfigBase::Get()->Exists("VCS")) { // TODO: Add SVN only if svn bin exists on linux. wxConfigBase::Get()->Write("VCS", (long)VCS_SVN); } } return m_Self; } wxExVCS::wxExCommand wxExVCS::GetType(int command_id) const { if (command_id > ID_VCS_LOWEST && command_id < ID_VCS_HIGHEST) { return (wxExCommand)(command_id - ID_VCS_LOWEST); } else if (command_id > ID_EDIT_VCS_LOWEST && command_id < ID_EDIT_VCS_HIGHEST) { return (wxExCommand)(command_id - ID_EDIT_VCS_LOWEST); } else { wxFAIL; return VCS_NO_COMMAND; } } long wxExVCS::GetVCS() const { long vcs = wxConfigBase::Get()->ReadLong("VCS", VCS_SVN); if (vcs == VCS_AUTO) { if (CheckSVN(m_FileName)) { vcs = VCS_SVN; } else if (CheckGIT(m_FileName)) { vcs = VCS_GIT; } else { vcs = VCS_NONE; } } return vcs; } const wxString wxExVCS::GetVCSName() const { wxString text; switch (GetVCS()) { case VCS_GIT: text = "GIT"; break; case VCS_SVN: text = "SVN"; break; case VCS_AUTO: break; // to prevent wxFAIL default: wxFAIL; } return text; } void wxExVCS::Initialize() { if (Use() && m_Command != VCS_NO_COMMAND) { switch (GetVCS()) { case VCS_GIT: switch (m_Command) { case VCS_ADD: m_CommandString = "add"; break; case VCS_BLAME: m_CommandString = "blame"; break; case VCS_CAT: break; case VCS_COMMIT: m_CommandString = "commit"; break; case VCS_DIFF: m_CommandString = "diff"; break; case VCS_HELP: m_CommandString = "help"; break; case VCS_INFO: break; case VCS_LOG: m_CommandString = "log"; break; case VCS_LS: break; case VCS_PROPLIST: break; case VCS_PROPSET: break; case VCS_PUSH: m_CommandString = "push"; break; case VCS_REVERT: m_CommandString = "revert"; break; case VCS_SHOW: m_CommandString = "show"; break; case VCS_STAT: m_CommandString = "status"; break; case VCS_UPDATE: m_CommandString = "update"; break; default: wxFAIL; break; } break; case VCS_SVN: switch (m_Command) { case VCS_ADD: m_CommandString = "add"; break; case VCS_BLAME: m_CommandString = "blame"; break; case VCS_CAT: m_CommandString = "cat"; break; case VCS_COMMIT: m_CommandString = "commit"; break; case VCS_DIFF: m_CommandString = "diff"; break; case VCS_HELP: m_CommandString = "help"; break; case VCS_INFO: m_CommandString = "info"; break; case VCS_LOG: m_CommandString = "log"; break; case VCS_LS: m_CommandString = "ls"; break; case VCS_PROPLIST: m_CommandString = "proplist"; break; case VCS_PROPSET: m_CommandString = "propset"; break; case VCS_PUSH: break; case VCS_REVERT: m_CommandString = "revert"; break; case VCS_SHOW: break; case VCS_STAT: m_CommandString = "stat"; break; case VCS_UPDATE: m_CommandString = "update"; break; default: wxFAIL; break; } break; case VCS_AUTO: break; default: wxFAIL; } m_Caption = GetVCSName() + " " + m_CommandString; // Currently no flags, as no command was executed. m_CommandWithFlags = m_CommandString; // Use general key. m_FlagsKey = wxString::Format("cvsflags/name%d", m_Command); } m_Output.clear(); } bool wxExVCS::IsOpenCommand() const { return m_Command == wxExVCS::VCS_BLAME || m_Command == wxExVCS::VCS_CAT || m_Command == wxExVCS::VCS_DIFF; } #if wxUSE_GUI wxStandardID wxExVCS::Request(wxWindow* parent) { wxStandardID retValue; if ((retValue = ExecuteDialog(parent)) == wxID_OK) { ShowOutput(parent); } return retValue; } #endif wxExVCS* wxExVCS::Set(wxExVCS* vcs) { wxExVCS* old = m_Self; m_Self = vcs; return old; } #if wxUSE_GUI int wxExVCS::ShowDialog(wxWindow* parent) { std::vector<wxExConfigItem> v; if (m_Command == VCS_COMMIT) { v.push_back(wxExConfigItem( _("Revision comment"), CONFIG_COMBOBOX, wxEmptyString, true)); // required } if (!m_FileName.IsOk() && m_Command != VCS_HELP) { v.push_back(wxExConfigItem( _("Base folder"), CONFIG_COMBOBOXDIR, wxEmptyString, true, 1000)); if (m_Command == VCS_ADD) { v.push_back(wxExConfigItem( _("Path"), CONFIG_COMBOBOX, wxEmptyString, true)); // required } } if (UseFlags()) { wxConfigBase::Get()->Write( _("Flags"), wxConfigBase::Get()->Read(m_FlagsKey)); v.push_back(wxExConfigItem(_("Flags"))); } if (UseSubcommand()) { v.push_back(wxExConfigItem(_("Subcommand"))); } return wxExConfigDialog(parent, v, m_Caption).ShowModal(); } #endif #if wxUSE_GUI void wxExVCS::ShowOutput(wxWindow* parent) const { wxString caption = m_Caption; if (m_Command != VCS_HELP) { caption += " " + (m_FileName.IsOk() ? m_FileName.GetFullName(): wxExConfigFirstOf(_("Base folder"))); } // Create a dialog for contents. if (m_STCEntryDialog == NULL) { m_STCEntryDialog = new wxExSTCEntryDialog( parent, caption, m_Output, wxEmptyString, wxOK, wxID_ANY, wxDefaultPosition, wxSize(350, 50)); } else { m_STCEntryDialog->SetText(m_Output); m_STCEntryDialog->SetTitle(caption); } // Add a lexer when appropriate. if (m_Command == VCS_CAT || m_Command == VCS_BLAME) { if (m_FileName.GetLexer().IsOk()) { m_STCEntryDialog->SetLexer(m_FileName.GetLexer().GetScintillaLexer()); } } else if (m_Command == VCS_DIFF) { m_STCEntryDialog->SetLexer("diff"); } else { m_STCEntryDialog->SetLexer(wxEmptyString); } m_STCEntryDialog->Show(); } #endif bool wxExVCS::Use() const { return GetVCS() != VCS_NONE; } bool wxExVCS::UseFlags() const { return m_Command != VCS_UPDATE && m_Command != VCS_HELP; } bool wxExVCS::UseSubcommand() const { return m_Command == VCS_HELP; } <|endoftext|>
<commit_before>// Header for AllocasToEntry, an LLVM pass to move allocas to the function // entry node. // // Copyright (c) 2013 Pekka Jääskeläinen / TUT // // 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 "config.h" #include <sstream> #include <iostream> #ifdef LLVM_3_2 # include <llvm/Instructions.h> #else # include <llvm/IR/Instructions.h> #endif #include "AllocasToEntry.h" namespace pocl { using namespace llvm; namespace { static RegisterPass<pocl::AllocasToEntry> X("allocastoentry", "Move allocas to the function entry node."); } char AllocasToEntry::ID = 0; AllocasToEntry::AllocasToEntry() : FunctionPass(ID) { } bool AllocasToEntry::runOnFunction(Function &F) { // This solves problem with dynamic stack objects that are // not supported by some targets (TCE). Function::iterator I = F.begin(); Instruction *firstInsertionPt = (I++)->getFirstInsertionPt(); bool changed = false; for (Function::iterator E = F.end(); I != E; ++I) { for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) { AllocaInst *allocaInst = dyn_cast<AllocaInst>(BI++); if (allocaInst && isa<ConstantInt>(allocaInst->getArraySize())) { allocaInst->moveBefore(firstInsertionPt); changed = true; } } } return changed; } } <commit_msg>Follow change in LLVM 3.4<commit_after>// Header for AllocasToEntry, an LLVM pass to move allocas to the function // entry node. // // Copyright (c) 2013 Pekka Jääskeläinen / TUT // // 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 "config.h" #include <sstream> #include <iostream> #ifdef LLVM_3_4 # include <llvm/IR/Constants.h> #endif #ifdef LLVM_3_2 # include <llvm/Instructions.h> #else # include <llvm/IR/Instructions.h> #endif #include "AllocasToEntry.h" namespace pocl { using namespace llvm; namespace { static RegisterPass<pocl::AllocasToEntry> X("allocastoentry", "Move allocas to the function entry node."); } char AllocasToEntry::ID = 0; AllocasToEntry::AllocasToEntry() : FunctionPass(ID) { } bool AllocasToEntry::runOnFunction(Function &F) { // This solves problem with dynamic stack objects that are // not supported by some targets (TCE). Function::iterator I = F.begin(); Instruction *firstInsertionPt = (I++)->getFirstInsertionPt(); bool changed = false; for (Function::iterator E = F.end(); I != E; ++I) { for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) { AllocaInst *allocaInst = dyn_cast<AllocaInst>(BI++); if (allocaInst && isa<ConstantInt>(allocaInst->getArraySize())) { allocaInst->moveBefore(firstInsertionPt); changed = true; } } } return changed; } } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_cme_firinit.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 p9_pm_cme_firinit.C /// @brief Configures the CME FIRs, Mask & Actions /// // *HWP HW Owner: Amit Kumar <[email protected]> // *HWP Backup HWP Owner: Greg Still <[email protected]> // *HWP FW Owner: Sangeetha T S <[email protected]> // *HWP Team: PM // *HWP Level: 2 // *HWP Consumed by: FSP:HS /// High-level procedure flow: /// \verbatim /// if reset: /// loop over all functional chiplets { /// Mask all bits of FIR /// } /// else if init: /// loop over all functional chiplets { /// Establish the mask/action bits for the following settings: /// 1) Checkstop /// 2) Malf Alert /// 3) Recoverable Attention /// 4) Recoverable Interrupt /// } /// /// Procedure Prereq: /// o System clocks are running /// \endverbatim // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_pm_cme_firinit.H> #include <p9_query_cache_access_state.H> // ---------------------------------------------------------------------- // Constant Definitions // ---------------------------------------------------------------------- enum CME_FIRS { PPE_INT_ERR, // 0 PPE_EXT_ERR, // 1 PPE_PROG_ERR, // 2 PPE_BRKPT_ERR, // 3 PPE_WATCHDOG, // 4 PPE_HALT, // 5 PPE_DBGTRG, // 6 CME_SRAM_UE, // 7 CME_SRAM_CE, // 8 SRAM_SCRUB_ERR, // 9 BCE_ERR, // 10 CME_SPARE_11, // 11 CME_SPARE_12, // 12 C0_iVRM_DPOUT, // 13 C1_iVRM_DPOUT, // 14 CACHE_iVRM_DPOUT, // 15 EXTRM_DROOP_ERR, // 16 LARGE_DROOP_ERR, // 17 SMALL_DROOP_ERR, // 18 UNEXP_DROOP_ENCODE, // 19 CME_FIR_PAR_ERR_DUP, // 20 CME_FIR_PAR_ERR // 21 }; // ---------------------------------------------------------------------- // Function prototype // ---------------------------------------------------------------------- /// @brief Initialize the actions for CME FIR, MASK and Action registers /// /// @param[in] i_target Chip target /// /// @return FAPI2_RC_SUCCESS if success, else error code. /// fapi2::ReturnCode pm_cme_fir_init( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); /// @brief Reset the actions for CME FIR, MASK and Action registers /// /// @param[in] i_target Chip target /// /// @return FAPI2_RC_SUCCESS if success, else error code. /// fapi2::ReturnCode pm_cme_fir_reset( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); // ---------------------------------------------------------------------- // Function definitions // ---------------------------------------------------------------------- fapi2::ReturnCode p9_pm_cme_firinit( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const p9pm::PM_FLOW_MODE i_mode) { FAPI_IMP("p9_pm_cme_firinit start"); if(i_mode == p9pm::PM_RESET) { FAPI_TRY(pm_cme_fir_reset(i_target), "ERROR: Failed to reset the CME FIRs"); } else if(i_mode == p9pm::PM_INIT) { FAPI_TRY(pm_cme_fir_init(i_target), "ERROR: Failed to initialize the CME FIRs"); } else { FAPI_ASSERT(false, fapi2::PM_CME_FIRINIT_BAD_MODE().set_BADMODE(i_mode), "ERROR; Unknown mode passed to p9_pm_cme_firinit. Mode %x", i_mode); } fapi_try_exit: FAPI_INF("p9_pm_cme_firinit end"); return fapi2::current_err; } fapi2::ReturnCode pm_cme_fir_init( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { FAPI_IMP("pm_cme_fir_init start"); uint8_t l_firinit_done_flag; auto l_exChiplets = i_target.getChildren<fapi2::TARGET_TYPE_EX> (fapi2::TARGET_STATE_FUNCTIONAL); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PM_FIRINIT_DONE_ONCE_FLAG, i_target, l_firinit_done_flag), "ERROR: Failed to fetch the entry status of FIRINIT"); for (auto l_ex_chplt : l_exChiplets) { p9pmFIR::PMFir <p9pmFIR::FIRTYPE_CME_LFIR> l_cmeFir(l_ex_chplt); FAPI_TRY(l_cmeFir.get(p9pmFIR::REG_ALL), "ERROR: Failed to get the CME FIR values"); /* Clear the FIR and action buffers */ FAPI_TRY(l_cmeFir.clearAllRegBits(p9pmFIR::REG_FIR), "ERROR: Failed to clear CME FIR"); FAPI_TRY(l_cmeFir.clearAllRegBits(p9pmFIR::REG_ACTION0), "ERROR: Failed to clear CME FIR"); FAPI_TRY(l_cmeFir.clearAllRegBits(p9pmFIR::REG_ACTION1), "ERROR: Failed to clear CME FIR"); /* Set the action and mask for the CME LFIR bits */ FAPI_TRY(l_cmeFir.mask(PPE_INT_ERR), "ERROR: Failed to mask"); FAPI_TRY(l_cmeFir.mask(PPE_EXT_ERR), "ERROR: Failed to mask"); FAPI_TRY(l_cmeFir.mask(PPE_PROG_ERR), "ERROR: Failed to mask"); FAPI_TRY(l_cmeFir.mask(PPE_BRKPT_ERR), "ERROR: Failed to mask"); FAPI_TRY(l_cmeFir.mask(PPE_WATCHDOG), "ERROR: Failed to mask"); FAPI_TRY(l_cmeFir.mask(PPE_HALT), "ERROR: Failed to mask"); FAPI_TRY(l_cmeFir.mask(PPE_DBGTRG), "ERROR: Failed to mask"); FAPI_TRY(l_cmeFir.setRecvAttn(CME_SRAM_UE), "ERROR: Failed to set recovery on interrupt"); FAPI_TRY(l_cmeFir.setRecvAttn(CME_SRAM_CE), "ERROR: Failed to set recoverable error"); FAPI_TRY(l_cmeFir.setRecvAttn(SRAM_SCRUB_ERR), "ERROR: Failed to set recoverable error"); FAPI_TRY(l_cmeFir.mask(BCE_ERR), "ERROR: Failed to mask"); FAPI_TRY(l_cmeFir.mask(CME_SPARE_11), "ERROR: Failed to mask"); FAPI_TRY(l_cmeFir.mask(CME_SPARE_12), "ERROR: Failed to mask"); FAPI_TRY(l_cmeFir.setRecvAttn(C0_iVRM_DPOUT), "ERROR: Failed to set recoverable error"); FAPI_TRY(l_cmeFir.setRecvAttn(C1_iVRM_DPOUT), "ERROR: Failed to set recoverable error"); FAPI_TRY(l_cmeFir.setRecvAttn(CACHE_iVRM_DPOUT), "ERROR: Failed to set recoverable error"); FAPI_TRY(l_cmeFir.setRecvAttn(EXTRM_DROOP_ERR), "ERROR: Failed to set recoverable error"); FAPI_TRY(l_cmeFir.setRecvAttn(LARGE_DROOP_ERR), "ERROR: Failed to set recoverable error"); FAPI_TRY(l_cmeFir.setRecvAttn(SMALL_DROOP_ERR), "ERROR: Failed to set recoverable error"); FAPI_TRY(l_cmeFir.setRecvAttn(UNEXP_DROOP_ENCODE), "ERROR: Failed to set recoverable error"); FAPI_TRY(l_cmeFir.mask(CME_FIR_PAR_ERR_DUP), "ERROR: Failed to mask"); FAPI_TRY(l_cmeFir.mask(CME_FIR_PAR_ERR), "ERROR: Failed to mask"); //todo: Yet to confirm on the action for the following bits if (l_firinit_done_flag) { FAPI_TRY(l_cmeFir.restoreSavedMask(), "ERROR: Failed to restore the CME mask saved"); } FAPI_TRY(l_cmeFir.put(), "ERROR:Failed to write to the CME FIR MASK"); } fapi_try_exit: return fapi2::current_err; } fapi2::ReturnCode pm_cme_fir_reset( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { FAPI_IMP("pm_cme_fir_reset start"); uint8_t l_firinit_done_flag; auto l_eqChiplets = i_target.getChildren<fapi2::TARGET_TYPE_EQ> (fapi2::TARGET_STATE_FUNCTIONAL); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PM_FIRINIT_DONE_ONCE_FLAG, i_target, l_firinit_done_flag), "ERROR: Failed to fetch the entry status of FIRINIT"); for (auto l_eq_chplt : l_eqChiplets) { //We cannot rely on the HWAS state because during an MPIPL //the cores get stopped and the SP doesnt know until an //attr sync occurs with the platform. We must use the //query_cache_state to safely determine if we can scom //the ex targets fapi2::ReturnCode l_rc; bool l_l2_is_scanable = false; bool l_l3_is_scanable = false; bool l_l2_is_scomable = false; bool l_l3_is_scomable = false; uint8_t l_chip_unit_pos; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_eq_chplt, l_chip_unit_pos), "ERROR: Failed to get the chip unit pos attribute from the eq"); FAPI_EXEC_HWP(l_rc, p9_query_cache_access_state, l_eq_chplt, l_l2_is_scomable, l_l2_is_scanable, l_l3_is_scomable, l_l3_is_scanable); FAPI_TRY(l_rc, "ERROR: failed to query cache access state for EQ %d", l_chip_unit_pos); //If this cache isnt scommable continue to the next EQ if(!l_l3_is_scomable) { continue; } auto l_exChiplets = l_eq_chplt.getChildren<fapi2::TARGET_TYPE_EX> (fapi2::TARGET_STATE_FUNCTIONAL); for(auto l_ex_chplt : l_exChiplets) { p9pmFIR::PMFir <p9pmFIR::FIRTYPE_CME_LFIR> l_cmeFir(l_ex_chplt); if (l_firinit_done_flag == 1) { FAPI_TRY(l_cmeFir.get(p9pmFIR::REG_FIRMASK), "ERROR: Failed to get the CME FIR MASK value"); /* Fetch the CME FIR MASK; Save it to HWP attribute; clear it */ FAPI_TRY(l_cmeFir.saveMask(), "ERROR: Failed to save CME FIR Mask to the attribute"); } FAPI_TRY(l_cmeFir.setAllRegBits(p9pmFIR::REG_FIRMASK), "ERROR: Faled to set the CME FIR MASK"); FAPI_TRY(l_cmeFir.put(), "ERROR:Failed to write to the CME FIR MASK"); } } fapi_try_exit: return fapi2::current_err; } <commit_msg>Bug fixes in Fir mask updates<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_cme_firinit.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 p9_pm_cme_firinit.C /// @brief Configures the CME FIRs, Mask & Actions /// // *HWP HW Owner: Amit Kumar <[email protected]> // *HWP Backup HWP Owner: Greg Still <[email protected]> // *HWP FW Owner: Sangeetha T S <[email protected]> // *HWP Team: PM // *HWP Level: 2 // *HWP Consumed by: FSP:HS /// High-level procedure flow: /// \verbatim /// if reset: /// loop over all functional chiplets { /// Mask all bits of FIR /// } /// else if init: /// loop over all functional chiplets { /// Establish the mask/action bits for the following settings: /// 1) Checkstop /// 2) Malf Alert /// 3) Recoverable Attention /// 4) Recoverable Interrupt /// } /// /// Procedure Prereq: /// o System clocks are running /// \endverbatim // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_pm_cme_firinit.H> #include <p9_query_cache_access_state.H> // ---------------------------------------------------------------------- // Constant Definitions // ---------------------------------------------------------------------- enum CME_FIRS { PPE_INT_ERR, // 0 PPE_EXT_ERR, // 1 PPE_PROG_ERR, // 2 PPE_BRKPT_ERR, // 3 PPE_WATCHDOG, // 4 PPE_HALT, // 5 PPE_DBGTRG, // 6 CME_SRAM_UE, // 7 CME_SRAM_CE, // 8 SRAM_SCRUB_ERR, // 9 BCE_ERR, // 10 CME_SPARE_11, // 11 CME_SPARE_12, // 12 C0_iVRM_DPOUT, // 13 C1_iVRM_DPOUT, // 14 CACHE_iVRM_DPOUT, // 15 EXTRM_DROOP_ERR, // 16 LARGE_DROOP_ERR, // 17 SMALL_DROOP_ERR, // 18 UNEXP_DROOP_ENCODE, // 19 CME_FIR_PAR_ERR_DUP, // 20 CME_FIR_PAR_ERR // 21 }; // ---------------------------------------------------------------------- // Function prototype // ---------------------------------------------------------------------- /// @brief Initialize the actions for CME FIR, MASK and Action registers /// /// @param[in] i_target Chip target /// /// @return FAPI2_RC_SUCCESS if success, else error code. /// fapi2::ReturnCode pm_cme_fir_init( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); /// @brief Reset the actions for CME FIR, MASK and Action registers /// /// @param[in] i_target Chip target /// /// @return FAPI2_RC_SUCCESS if success, else error code. /// fapi2::ReturnCode pm_cme_fir_reset( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); // ---------------------------------------------------------------------- // Function definitions // ---------------------------------------------------------------------- fapi2::ReturnCode p9_pm_cme_firinit( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const p9pm::PM_FLOW_MODE i_mode) { FAPI_IMP("p9_pm_cme_firinit start"); if(i_mode == p9pm::PM_RESET) { FAPI_TRY(pm_cme_fir_reset(i_target), "ERROR: Failed to reset the CME FIRs"); } else if(i_mode == p9pm::PM_INIT) { FAPI_TRY(pm_cme_fir_init(i_target), "ERROR: Failed to initialize the CME FIRs"); } else { FAPI_ASSERT(false, fapi2::PM_CME_FIRINIT_BAD_MODE().set_BADMODE(i_mode), "ERROR; Unknown mode passed to p9_pm_cme_firinit. Mode %x", i_mode); } fapi_try_exit: FAPI_INF("p9_pm_cme_firinit end"); return fapi2::current_err; } fapi2::ReturnCode pm_cme_fir_init( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { FAPI_IMP("pm_cme_fir_init start"); uint8_t l_firinit_done_flag; auto l_exChiplets = i_target.getChildren<fapi2::TARGET_TYPE_EX> (fapi2::TARGET_STATE_FUNCTIONAL); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PM_FIRINIT_DONE_ONCE_FLAG, i_target, l_firinit_done_flag), "ERROR: Failed to fetch the entry status of FIRINIT"); for (auto l_ex_chplt : l_exChiplets) { p9pmFIR::PMFir <p9pmFIR::FIRTYPE_CME_LFIR> l_cmeFir(l_ex_chplt); FAPI_TRY(l_cmeFir.get(p9pmFIR::REG_ALL), "ERROR: Failed to get the CME FIR values"); /* Clear the FIR and action buffers */ FAPI_TRY(l_cmeFir.clearAllRegBits(p9pmFIR::REG_FIR), "ERROR: Failed to clear CME FIR"); FAPI_TRY(l_cmeFir.clearAllRegBits(p9pmFIR::REG_ACTION0), "ERROR: Failed to clear CME FIR"); FAPI_TRY(l_cmeFir.clearAllRegBits(p9pmFIR::REG_ACTION1), "ERROR: Failed to clear CME FIR"); /* Set the action and mask for the CME LFIR bits */ FAPI_TRY(l_cmeFir.mask(PPE_INT_ERR), FIR_MASK_ERROR); FAPI_TRY(l_cmeFir.mask(PPE_EXT_ERR), FIR_MASK_ERROR); FAPI_TRY(l_cmeFir.mask(PPE_PROG_ERR), FIR_MASK_ERROR); FAPI_TRY(l_cmeFir.mask(PPE_BRKPT_ERR), FIR_MASK_ERROR); FAPI_TRY(l_cmeFir.mask(PPE_WATCHDOG), FIR_MASK_ERROR); FAPI_TRY(l_cmeFir.mask(PPE_HALT), FIR_MASK_ERROR); FAPI_TRY(l_cmeFir.mask(PPE_DBGTRG), FIR_MASK_ERROR); FAPI_TRY(l_cmeFir.setRecvAttn(CME_SRAM_UE), FIR_REC_ATTN_ERROR); FAPI_TRY(l_cmeFir.setRecvAttn(CME_SRAM_CE), FIR_REC_ATTN_ERROR); FAPI_TRY(l_cmeFir.setRecvAttn(SRAM_SCRUB_ERR), FIR_REC_ATTN_ERROR); FAPI_TRY(l_cmeFir.mask(BCE_ERR), FIR_MASK_ERROR); FAPI_TRY(l_cmeFir.mask(CME_SPARE_11), FIR_MASK_ERROR); FAPI_TRY(l_cmeFir.mask(CME_SPARE_12), FIR_MASK_ERROR); FAPI_TRY(l_cmeFir.setRecvAttn(C0_iVRM_DPOUT), FIR_REC_ATTN_ERROR); FAPI_TRY(l_cmeFir.setRecvAttn(C1_iVRM_DPOUT), FIR_REC_ATTN_ERROR); FAPI_TRY(l_cmeFir.setRecvAttn(CACHE_iVRM_DPOUT), FIR_REC_ATTN_ERROR); FAPI_TRY(l_cmeFir.setRecvAttn(EXTRM_DROOP_ERR), FIR_REC_ATTN_ERROR); FAPI_TRY(l_cmeFir.setRecvAttn(LARGE_DROOP_ERR), FIR_REC_ATTN_ERROR); FAPI_TRY(l_cmeFir.setRecvAttn(SMALL_DROOP_ERR), FIR_REC_ATTN_ERROR); FAPI_TRY(l_cmeFir.setRecvAttn(UNEXP_DROOP_ENCODE), FIR_REC_ATTN_ERROR); FAPI_TRY(l_cmeFir.mask(CME_FIR_PAR_ERR_DUP), FIR_MASK_ERROR); FAPI_TRY(l_cmeFir.mask(CME_FIR_PAR_ERR), FIR_MASK_ERROR); //todo: Yet to confirm on the action for the following bits if (l_firinit_done_flag) { FAPI_TRY(l_cmeFir.restoreSavedMask(), "ERROR: Failed to restore the CME mask saved"); } FAPI_TRY(l_cmeFir.put(), "ERROR:Failed to write to the CME FIR MASK"); } fapi_try_exit: return fapi2::current_err; } fapi2::ReturnCode pm_cme_fir_reset( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { FAPI_IMP("pm_cme_fir_reset start"); uint8_t l_firinit_done_flag; auto l_eqChiplets = i_target.getChildren<fapi2::TARGET_TYPE_EQ> (fapi2::TARGET_STATE_FUNCTIONAL); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PM_FIRINIT_DONE_ONCE_FLAG, i_target, l_firinit_done_flag), "ERROR: Failed to fetch the entry status of FIRINIT"); for (auto l_eq_chplt : l_eqChiplets) { //We cannot rely on the HWAS state because during an MPIPL //the cores get stopped and the SP doesnt know until an //attr sync occurs with the platform. We must use the //query_cache_state to safely determine if we can scom //the ex targets fapi2::ReturnCode l_rc; bool l_l2_is_scanable = false; bool l_l3_is_scanable = false; bool l_l2_is_scomable = false; bool l_l3_is_scomable = false; uint8_t l_chip_unit_pos; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_eq_chplt, l_chip_unit_pos), "ERROR: Failed to get the chip unit pos attribute from the eq"); FAPI_EXEC_HWP(l_rc, p9_query_cache_access_state, l_eq_chplt, l_l2_is_scomable, l_l2_is_scanable, l_l3_is_scomable, l_l3_is_scanable); FAPI_TRY(l_rc, "ERROR: failed to query cache access state for EQ %d", l_chip_unit_pos); //If this cache isnt scommable continue to the next EQ if(!l_l3_is_scomable) { continue; } auto l_exChiplets = l_eq_chplt.getChildren<fapi2::TARGET_TYPE_EX> (fapi2::TARGET_STATE_FUNCTIONAL); for(auto l_ex_chplt : l_exChiplets) { p9pmFIR::PMFir <p9pmFIR::FIRTYPE_CME_LFIR> l_cmeFir(l_ex_chplt); if (l_firinit_done_flag == 1) { FAPI_TRY(l_cmeFir.get(p9pmFIR::REG_FIRMASK), "ERROR: Failed to get the CME FIR MASK value"); /* Fetch the CME FIR MASK; Save it to HWP attribute; clear it */ FAPI_TRY(l_cmeFir.saveMask(), "ERROR: Failed to save CME FIR Mask to the attribute"); } FAPI_TRY(l_cmeFir.setAllRegBits(p9pmFIR::REG_FIRMASK), "ERROR: Faled to set the CME FIR MASK"); FAPI_TRY(l_cmeFir.put(), "ERROR:Failed to write to the CME FIR MASK"); } } fapi_try_exit: return fapi2::current_err; } <|endoftext|>
<commit_before>// This file is part of the AliceVision 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 https://mozilla.org/MPL/2.0/. #include <aliceVision/delaunaycut/mv_delaunay_GC.hpp> #include <aliceVision/delaunaycut/mv_delaunay_meshSmooth.hpp> #include <aliceVision/largeScale/reconstructionPlan.hpp> #include <aliceVision/planeSweeping/ps_refine_rc.hpp> #include <aliceVision/CUDAInterfaces/refine.hpp> #include <aliceVision/common/fileIO.hpp> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> namespace bfs = boost::filesystem; namespace po = boost::program_options; #define ALICEVISION_COUT(x) std::cout << x << std::endl #define ALICEVISION_CERR(x) std::cerr << x << std::endl #define EXIT_FAILURE -1; int main(int argc, char* argv[]) { long startTime = clock(); std::string iniFilepath; std::string depthMapFolder; std::string outputFolder; int rangeStart = -1; int rangeSize = -1; int minNumOfConsistensCams = 3; int minNumOfConsistensCamsWithLowSimilarity = 4; int pixSizeBall = 0; int pixSizeBallWithLowSimilarity = 0; int nNearestCams = 10; po::options_description allParams("AliceVision depthMapFiltering\n" "Filter depth map to remove values that are not consistent with other depth maps"); po::options_description requiredParams("Required parameters"); requiredParams.add_options() ("ini", po::value<std::string>(&iniFilepath)->required(), "Configuration file (mvs.ini).") ("depthMapFolder", po::value<std::string>(&depthMapFolder)->required(), "Input depth map folder.") ("output,o", po::value<std::string>(&outputFolder)->required(), "Output folder for filtered depth maps."); po::options_description optionalParams("Optional parameters"); optionalParams.add_options() ("rangeStart", po::value<int>(&rangeStart)->default_value(rangeStart), "Compute only a sub-range of images from index rangeStart to rangeStart+rangeSize.") ("rangeSize", po::value<int>(&rangeSize)->default_value(rangeSize), "Compute only a sub-range of N images (N=rangeSize).") ("minNumOfConsistensCams", po::value<int>(&minNumOfConsistensCams)->default_value(minNumOfConsistensCams), "Minimal number of consistent cameras to consider the pixel.") ("minNumOfConsistensCamsWithLowSimilarity", po::value<int>(&minNumOfConsistensCamsWithLowSimilarity)->default_value(minNumOfConsistensCamsWithLowSimilarity), "Minimal number of consistent cameras to consider the pixel when the similarity is weak or ambiguous.") ("pixSizeBall", po::value<int>(&pixSizeBall)->default_value(pixSizeBall), "Filter ball size (in px).") ("pixSizeBallWithLowSimilarity", po::value<int>(&pixSizeBallWithLowSimilarity)->default_value(pixSizeBallWithLowSimilarity), "Filter ball size (in px) when the similarity is weak or ambiguous.") ("nNearestCams", po::value<int>(&nNearestCams)->default_value(nNearestCams), "Number of nearest cameras."); allParams.add(requiredParams).add(optionalParams); po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, allParams), vm); if(vm.count("help") || (argc == 1)) { ALICEVISION_COUT(allParams); return EXIT_SUCCESS; } po::notify(vm); } catch(boost::program_options::required_option& e) { ALICEVISION_CERR("ERROR: " << e.what() << std::endl); ALICEVISION_COUT("Usage:\n\n" << allParams); return EXIT_FAILURE; } catch(boost::program_options::error& e) { ALICEVISION_CERR("ERROR: " << e.what() << std::endl); ALICEVISION_COUT("Usage:\n\n" << allParams); return EXIT_FAILURE; } ALICEVISION_COUT("ini file: " << iniFilepath); // .ini parsing multiviewInputParams mip(iniFilepath, depthMapFolder, outputFolder); const double simThr = mip._ini.get<double>("global.simThr", 0.0); multiviewParams mp(mip.getNbCameras(), &mip, (float) simThr); mv_prematch_cams pc(&mp); staticVector<int> cams(mp.ncams); if(rangeSize == -1) { for(int rc = 0; rc < mp.ncams; rc++) // process all cameras cams.push_back(rc); } else { if(rangeStart < 0) { ALICEVISION_CERR("invalid subrange of cameras to process."); return EXIT_FAILURE; } for(int rc = rangeStart; rc < std::min(rangeStart + rangeSize, mp.ncams); ++rc) cams.push_back(rc); if(cams.empty()) { ALICEVISION_COUT("No camera to process"); return EXIT_SUCCESS; } } ALICEVISION_COUT("--- filter depthmap"); { mv_fuse fs(&mp, &pc); fs.filterGroups(cams, pixSizeBall, pixSizeBallWithLowSimilarity, nNearestCams); fs.filterDepthMaps(cams, minNumOfConsistensCams, minNumOfConsistensCamsWithLowSimilarity); } printfElapsedTime(startTime, "#"); return EXIT_SUCCESS; } <commit_msg>[software] EXIT_FAILURE redefined<commit_after>// This file is part of the AliceVision 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 https://mozilla.org/MPL/2.0/. #include <aliceVision/delaunaycut/mv_delaunay_GC.hpp> #include <aliceVision/delaunaycut/mv_delaunay_meshSmooth.hpp> #include <aliceVision/largeScale/reconstructionPlan.hpp> #include <aliceVision/planeSweeping/ps_refine_rc.hpp> #include <aliceVision/CUDAInterfaces/refine.hpp> #include <aliceVision/common/fileIO.hpp> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> namespace bfs = boost::filesystem; namespace po = boost::program_options; #define ALICEVISION_COUT(x) std::cout << x << std::endl #define ALICEVISION_CERR(x) std::cerr << x << std::endl int main(int argc, char* argv[]) { long startTime = clock(); std::string iniFilepath; std::string depthMapFolder; std::string outputFolder; int rangeStart = -1; int rangeSize = -1; int minNumOfConsistensCams = 3; int minNumOfConsistensCamsWithLowSimilarity = 4; int pixSizeBall = 0; int pixSizeBallWithLowSimilarity = 0; int nNearestCams = 10; po::options_description allParams("AliceVision depthMapFiltering\n" "Filter depth map to remove values that are not consistent with other depth maps"); po::options_description requiredParams("Required parameters"); requiredParams.add_options() ("ini", po::value<std::string>(&iniFilepath)->required(), "Configuration file (mvs.ini).") ("depthMapFolder", po::value<std::string>(&depthMapFolder)->required(), "Input depth map folder.") ("output,o", po::value<std::string>(&outputFolder)->required(), "Output folder for filtered depth maps."); po::options_description optionalParams("Optional parameters"); optionalParams.add_options() ("rangeStart", po::value<int>(&rangeStart)->default_value(rangeStart), "Compute only a sub-range of images from index rangeStart to rangeStart+rangeSize.") ("rangeSize", po::value<int>(&rangeSize)->default_value(rangeSize), "Compute only a sub-range of N images (N=rangeSize).") ("minNumOfConsistensCams", po::value<int>(&minNumOfConsistensCams)->default_value(minNumOfConsistensCams), "Minimal number of consistent cameras to consider the pixel.") ("minNumOfConsistensCamsWithLowSimilarity", po::value<int>(&minNumOfConsistensCamsWithLowSimilarity)->default_value(minNumOfConsistensCamsWithLowSimilarity), "Minimal number of consistent cameras to consider the pixel when the similarity is weak or ambiguous.") ("pixSizeBall", po::value<int>(&pixSizeBall)->default_value(pixSizeBall), "Filter ball size (in px).") ("pixSizeBallWithLowSimilarity", po::value<int>(&pixSizeBallWithLowSimilarity)->default_value(pixSizeBallWithLowSimilarity), "Filter ball size (in px) when the similarity is weak or ambiguous.") ("nNearestCams", po::value<int>(&nNearestCams)->default_value(nNearestCams), "Number of nearest cameras."); allParams.add(requiredParams).add(optionalParams); po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, allParams), vm); if(vm.count("help") || (argc == 1)) { ALICEVISION_COUT(allParams); return EXIT_SUCCESS; } po::notify(vm); } catch(boost::program_options::required_option& e) { ALICEVISION_CERR("ERROR: " << e.what() << std::endl); ALICEVISION_COUT("Usage:\n\n" << allParams); return EXIT_FAILURE; } catch(boost::program_options::error& e) { ALICEVISION_CERR("ERROR: " << e.what() << std::endl); ALICEVISION_COUT("Usage:\n\n" << allParams); return EXIT_FAILURE; } ALICEVISION_COUT("ini file: " << iniFilepath); // .ini parsing multiviewInputParams mip(iniFilepath, depthMapFolder, outputFolder); const double simThr = mip._ini.get<double>("global.simThr", 0.0); multiviewParams mp(mip.getNbCameras(), &mip, (float) simThr); mv_prematch_cams pc(&mp); staticVector<int> cams(mp.ncams); if(rangeSize == -1) { for(int rc = 0; rc < mp.ncams; rc++) // process all cameras cams.push_back(rc); } else { if(rangeStart < 0) { ALICEVISION_CERR("invalid subrange of cameras to process."); return EXIT_FAILURE; } for(int rc = rangeStart; rc < std::min(rangeStart + rangeSize, mp.ncams); ++rc) cams.push_back(rc); if(cams.empty()) { ALICEVISION_COUT("No camera to process"); return EXIT_SUCCESS; } } ALICEVISION_COUT("--- filter depthmap"); { mv_fuse fs(&mp, &pc); fs.filterGroups(cams, pixSizeBall, pixSizeBallWithLowSimilarity, nNearestCams); fs.filterDepthMaps(cams, minNumOfConsistensCams, minNumOfConsistensCamsWithLowSimilarity); } printfElapsedTime(startTime, "#"); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* Copyright 2016 Mitchell Young 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. */ #pragma once #include <cmath> #include "util/force_inline.hpp" #include "util/global_config.hpp" #include "core/constants.hpp" #include "core/geometry/angle.hpp" #include "ray.hpp" namespace mocc { namespace moc { /** * This can be used as a template parameter to the \ref * MoCSweeper::sweep1g() method. Using this class in such a way avoids * the extra work needed to compute currents, and with any optimization * enabled, should yield code identical to a hand-written MoC sweep * without the current work. */ class NoCurrent { public: /** * \brief Subscriptable abstraction for only storing a scalar value * * This class allows the MoC sweeper kernel to be agnostic to the type of * storage needed to represent the flux along a ray. In cases where current * or some other value is needed from the sweeper, it is necessary to keep * the angular flux along the entire length of the ray. In other situations * where this is unnecessary, it is a waste to keep track of this ray flux, * and sufficient to just maintain the angular flux at the furthest-swept * position on the ray. To allow the sweeper kernel to be written in a * manner allowing both options, this class implements a subscript operator, * which points to the same scalar every time, which should be elided by an * optimizing compiler. * * \sa moc::Current::FluxStore */ class FluxStore { public: FluxStore(int size) { return; } real_t &operator[](int i) { return psi_; } real_t operator[](int i) const { return psi_; } private: real_t psi_; }; NoCurrent() { } NoCurrent(CoarseData *data, const Mesh *mesh) { } /** * Defines work to be done following the sweep of a single ray. This * is useful for when you need to do something with the angular * flux. */ MOCC_FORCE_INLINE void post_ray(FluxStore psi1, FluxStore psi2, const ArrayB1 &e_tau, const Ray &ray, int first_reg) { return; } /** * Defines work to be done before sweeping rays in a given angle. */ MOCC_FORCE_INLINE void set_angle(Angle ang, real_t spacing) { return; } /** * Defines work to be done after sweeping all rays in a given angle. */ MOCC_FORCE_INLINE void post_angle(int iang) { return; } MOCC_FORCE_INLINE void set_plane(int iplane) { return; } MOCC_FORCE_INLINE void post_sweep() { return; } MOCC_FORCE_INLINE void post_plane() { return; } MOCC_FORCE_INLINE void set_group(int group) { return; } }; /** * This class can be used as a template parameter to the \ref * MoCSweeper::sweep1g() method to control whether or not extra work is * done during the sweep to compute currents. Specifically, when this * class is used as the template parameter, currents are calculated. * * See documentation for \ref moc::NoCurrent for canonical documentation * for each of the methods. */ class Current { public: /** * \brief Typedef for a STL vector of real_t for storing angular flux along * a ray. * * This type is used to store the flux along the entire length of the ray * when such information is needed from the MoC sweeper kernel. * * \sa moc::NoCurrent::FluxStore */ typedef std::vector<real_t> FluxStore; Current() : coarse_data_(nullptr), mesh_(nullptr) { } Current(CoarseData *data, const Mesh *mesh) : coarse_data_(data), mesh_(mesh) { return; } MOCC_FORCE_INLINE void post_angle(int iang) { return; }; MOCC_FORCE_INLINE void post_plane() { return; } MOCC_FORCE_INLINE void set_group(int group) { group_ = group; } MOCC_FORCE_INLINE void set_plane(int plane) { plane_ = plane; cell_offset_ = mesh_->coarse_cell_offset(plane); surf_offset_ = mesh_->coarse_surf_offset(plane); } MOCC_FORCE_INLINE void set_angle(Angle ang, real_t spacing) { #pragma omp single { // Scale the angle weight to sum to 4*PI real_t w = ang.weight * PI; // Multiply by dz so that we conform to the actual coarse // mesh area. real_t dz = mesh_->dz(plane_); current_weights_[0] = w * ang.ox * spacing / std::abs(std::cos(ang.alpha)) * dz; current_weights_[1] = w * ang.oy * spacing / std::abs(std::sin(ang.alpha)) * dz; flux_weights_[0] = w * spacing / std::abs(std::cos(ang.alpha)) * dz; flux_weights_[1] = w * spacing / std::abs(std::sin(ang.alpha)) * dz; } #pragma omp barrier } MOCC_FORCE_INLINE void post_ray(const FluxStore &psi1, const FluxStore &psi2, const ArrayB1 &e_tau, const Ray &ray, int first_reg) { #pragma omp critical { /** * \todo this is going to perform poorly as implemented. this is a * really large critical section, which we might be able to do as * atomic updates, as is done in the Sn current worker. The Blitz * array slicing is not thread safe, though, so we would need to be * careful. It'd be nice to fiddle with this and profile once things * settle down some. */ auto all = blitz::Range::all(); auto current = coarse_data_->current(all, group_); auto surface_flux = coarse_data_->surface_flux(all, group_); size_t cell_fw = ray.cm_cell_fw() + cell_offset_; size_t cell_bw = ray.cm_cell_bw() + cell_offset_; int surf_fw = ray.cm_surf_fw() + surf_offset_; int surf_bw = ray.cm_surf_bw() + surf_offset_; int iseg_fw = 0; int iseg_bw = ray.nseg(); int norm_fw = (int)mesh_->surface_normal(surf_fw); int norm_bw = (int)mesh_->surface_normal(surf_bw); current(surf_fw) += psi1[iseg_fw] * current_weights_[norm_fw]; current(surf_bw) -= psi2[iseg_bw] * current_weights_[norm_bw]; surface_flux(surf_fw) += psi1[iseg_fw] * flux_weights_[norm_fw]; surface_flux(surf_bw) += psi2[iseg_bw] * flux_weights_[norm_bw]; auto begin = ray.cm_data().cbegin(); auto end = ray.cm_data().cend(); for (auto crd = begin; crd != end; ++crd) { // Hopefully branch prediction saves me here. if (crd->fw != Surface::INVALID) { iseg_fw += crd->nseg_fw; norm_fw = (int)surface_to_normal(crd->fw); surf_fw = mesh_->coarse_surf(cell_fw, crd->fw); current(surf_fw) += psi1[iseg_fw] * current_weights_[norm_fw]; surface_flux(surf_fw) += psi1[iseg_fw] * flux_weights_[norm_fw]; } if (crd->bw != Surface::INVALID) { iseg_bw -= crd->nseg_bw; norm_bw = (int)surface_to_normal(crd->bw); surf_bw = mesh_->coarse_surf(cell_bw, crd->bw); current(surf_bw) -= psi2[iseg_bw] * current_weights_[norm_bw]; surface_flux(surf_bw) += psi2[iseg_bw] * flux_weights_[norm_bw]; } cell_fw = mesh_->coarse_neighbor(cell_fw, (crd)->fw); cell_bw = mesh_->coarse_neighbor(cell_bw, (crd)->bw); } } // OMP critical return; } /** * \brief Clean up anything that needs to be done after sweeping all angles * * In the context of the \ref CurrentWorker and most of its children, this * only includes expanding the currents to the full PIN grid from the * potentially smaller MoC axial grid. */ MOCC_FORCE_INLINE void post_sweep() { #pragma omp single { // Check to see if we need to expand the currents across the mesh. if ((int)mesh_->nz() - 1 != (mesh_->macroplane_index().back())) { // In the presence of subplaning, the currents coming from the // sweeper are stored by macroplane, packed towards the bottom // of the mesh. To safely perform an in-place expansion, we // will expand the currents in reverse, filling from the top // down. This prevents over-writing of the source currents from // the MoC sweep before having a chance to expand them, as would // happen if the expansion went from the bottom up. int iz = mesh_->nz() - 1; for (auto mplane_it = mesh_->macroplane_index().crbegin(); mplane_it != mesh_->macroplane_index().crend(); ++mplane_it) { int stt_out = mesh_->plane_surf_xy_begin(iz); int stp_out = mesh_->plane_surf_end(iz); int ip = *mplane_it; int stt_in = mesh_->plane_surf_xy_begin(ip); int stp_in = mesh_->plane_surf_end(ip); coarse_data_->current(blitz::Range(stt_out, stp_out), group_) = coarse_data_->current(blitz::Range(stt_in, stp_in), group_); iz--; } } auto all = blitz::Range::all(); auto current = coarse_data_->current(all, group_); auto surface_flux = coarse_data_->surface_flux(all, group_); // Normalize the surface currents for (size_t plane = 0; plane < mesh_->nz(); plane++) { for (int surf = mesh_->plane_surf_xy_begin(plane); surf != (int)mesh_->plane_surf_end(plane); ++surf) { real_t area = mesh_->coarse_area(surf); current(surf) /= area; surface_flux(surf) /= area; } } } return; } protected: CoarseData *coarse_data_; const Mesh *mesh_; std::array<real_t, 2> current_weights_; std::array<real_t, 2> flux_weights_; int plane_; int group_; int cell_offset_; int surf_offset_; }; } } <commit_msg>Use int instead of size_t in sn kernel<commit_after>/* Copyright 2016 Mitchell Young 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. */ #pragma once #include <cmath> #include "util/force_inline.hpp" #include "util/global_config.hpp" #include "core/constants.hpp" #include "core/geometry/angle.hpp" #include "ray.hpp" namespace mocc { namespace moc { /** * This can be used as a template parameter to the \ref * MoCSweeper::sweep1g() method. Using this class in such a way avoids * the extra work needed to compute currents, and with any optimization * enabled, should yield code identical to a hand-written MoC sweep * without the current work. */ class NoCurrent { public: /** * \brief Subscriptable abstraction for only storing a scalar value * * This class allows the MoC sweeper kernel to be agnostic to the type of * storage needed to represent the flux along a ray. In cases where current * or some other value is needed from the sweeper, it is necessary to keep * the angular flux along the entire length of the ray. In other situations * where this is unnecessary, it is a waste to keep track of this ray flux, * and sufficient to just maintain the angular flux at the furthest-swept * position on the ray. To allow the sweeper kernel to be written in a * manner allowing both options, this class implements a subscript operator, * which points to the same scalar every time, which should be elided by an * optimizing compiler. * * \sa moc::Current::FluxStore */ class FluxStore { public: FluxStore(int size) { return; } real_t &operator[](int i) { return psi_; } real_t operator[](int i) const { return psi_; } private: real_t psi_; }; NoCurrent() { } NoCurrent(CoarseData *data, const Mesh *mesh) { } /** * Defines work to be done following the sweep of a single ray. This * is useful for when you need to do something with the angular * flux. */ MOCC_FORCE_INLINE void post_ray(FluxStore psi1, FluxStore psi2, const ArrayB1 &e_tau, const Ray &ray, int first_reg) { return; } /** * Defines work to be done before sweeping rays in a given angle. */ MOCC_FORCE_INLINE void set_angle(Angle ang, real_t spacing) { return; } /** * Defines work to be done after sweeping all rays in a given angle. */ MOCC_FORCE_INLINE void post_angle(int iang) { return; } MOCC_FORCE_INLINE void set_plane(int iplane) { return; } MOCC_FORCE_INLINE void post_sweep() { return; } MOCC_FORCE_INLINE void post_plane() { return; } MOCC_FORCE_INLINE void set_group(int group) { return; } }; /** * This class can be used as a template parameter to the \ref * MoCSweeper::sweep1g() method to control whether or not extra work is * done during the sweep to compute currents. Specifically, when this * class is used as the template parameter, currents are calculated. * * See documentation for \ref moc::NoCurrent for canonical documentation * for each of the methods. */ class Current { public: /** * \brief Typedef for a STL vector of real_t for storing angular flux along * a ray. * * This type is used to store the flux along the entire length of the ray * when such information is needed from the MoC sweeper kernel. * * \sa moc::NoCurrent::FluxStore */ typedef std::vector<real_t> FluxStore; Current() : coarse_data_(nullptr), mesh_(nullptr) { } Current(CoarseData *data, const Mesh *mesh) : coarse_data_(data), mesh_(mesh) { return; } MOCC_FORCE_INLINE void post_angle(int iang) { return; }; MOCC_FORCE_INLINE void post_plane() { return; } MOCC_FORCE_INLINE void set_group(int group) { group_ = group; } MOCC_FORCE_INLINE void set_plane(int plane) { plane_ = plane; cell_offset_ = mesh_->coarse_cell_offset(plane); surf_offset_ = mesh_->coarse_surf_offset(plane); } MOCC_FORCE_INLINE void set_angle(Angle ang, real_t spacing) { #pragma omp single { // Scale the angle weight to sum to 4*PI real_t w = ang.weight * PI; // Multiply by dz so that we conform to the actual coarse // mesh area. real_t dz = mesh_->dz(plane_); current_weights_[0] = w * ang.ox * spacing / std::abs(std::cos(ang.alpha)) * dz; current_weights_[1] = w * ang.oy * spacing / std::abs(std::sin(ang.alpha)) * dz; flux_weights_[0] = w * spacing / std::abs(std::cos(ang.alpha)) * dz; flux_weights_[1] = w * spacing / std::abs(std::sin(ang.alpha)) * dz; } #pragma omp barrier } MOCC_FORCE_INLINE void post_ray(const FluxStore &psi1, const FluxStore &psi2, const ArrayB1 &e_tau, const Ray &ray, int first_reg) { #pragma omp critical { /** * \todo this is going to perform poorly as implemented. this is a * really large critical section, which we might be able to do as * atomic updates, as is done in the Sn current worker. The Blitz * array slicing is not thread safe, though, so we would need to be * careful. It'd be nice to fiddle with this and profile once things * settle down some. */ auto all = blitz::Range::all(); auto current = coarse_data_->current(all, group_); auto surface_flux = coarse_data_->surface_flux(all, group_); int cell_fw = ray.cm_cell_fw() + cell_offset_; int cell_bw = ray.cm_cell_bw() + cell_offset_; int surf_fw = ray.cm_surf_fw() + surf_offset_; int surf_bw = ray.cm_surf_bw() + surf_offset_; int iseg_fw = 0; int iseg_bw = ray.nseg(); int norm_fw = (int)mesh_->surface_normal(surf_fw); int norm_bw = (int)mesh_->surface_normal(surf_bw); current(surf_fw) += psi1[iseg_fw] * current_weights_[norm_fw]; current(surf_bw) -= psi2[iseg_bw] * current_weights_[norm_bw]; surface_flux(surf_fw) += psi1[iseg_fw] * flux_weights_[norm_fw]; surface_flux(surf_bw) += psi2[iseg_bw] * flux_weights_[norm_bw]; auto begin = ray.cm_data().cbegin(); auto end = ray.cm_data().cend(); for (auto crd = begin; crd != end; ++crd) { // Hopefully branch prediction saves me here. if (crd->fw != Surface::INVALID) { iseg_fw += crd->nseg_fw; norm_fw = (int)surface_to_normal(crd->fw); surf_fw = mesh_->coarse_surf(cell_fw, crd->fw); current(surf_fw) += psi1[iseg_fw] * current_weights_[norm_fw]; surface_flux(surf_fw) += psi1[iseg_fw] * flux_weights_[norm_fw]; } if (crd->bw != Surface::INVALID) { iseg_bw -= crd->nseg_bw; norm_bw = (int)surface_to_normal(crd->bw); surf_bw = mesh_->coarse_surf(cell_bw, crd->bw); current(surf_bw) -= psi2[iseg_bw] * current_weights_[norm_bw]; surface_flux(surf_bw) += psi2[iseg_bw] * flux_weights_[norm_bw]; } cell_fw = mesh_->coarse_neighbor(cell_fw, (crd)->fw); cell_bw = mesh_->coarse_neighbor(cell_bw, (crd)->bw); } } // OMP critical return; } /** * \brief Clean up anything that needs to be done after sweeping all angles * * In the context of the \ref CurrentWorker and most of its children, this * only includes expanding the currents to the full PIN grid from the * potentially smaller MoC axial grid. */ MOCC_FORCE_INLINE void post_sweep() { #pragma omp single { // Check to see if we need to expand the currents across the mesh. if ((int)mesh_->nz() - 1 != (mesh_->macroplane_index().back())) { // In the presence of subplaning, the currents coming from the // sweeper are stored by macroplane, packed towards the bottom // of the mesh. To safely perform an in-place expansion, we // will expand the currents in reverse, filling from the top // down. This prevents over-writing of the source currents from // the MoC sweep before having a chance to expand them, as would // happen if the expansion went from the bottom up. int iz = mesh_->nz() - 1; for (auto mplane_it = mesh_->macroplane_index().crbegin(); mplane_it != mesh_->macroplane_index().crend(); ++mplane_it) { int stt_out = mesh_->plane_surf_xy_begin(iz); int stp_out = mesh_->plane_surf_end(iz); int ip = *mplane_it; int stt_in = mesh_->plane_surf_xy_begin(ip); int stp_in = mesh_->plane_surf_end(ip); coarse_data_->current(blitz::Range(stt_out, stp_out), group_) = coarse_data_->current(blitz::Range(stt_in, stp_in), group_); iz--; } } auto all = blitz::Range::all(); auto current = coarse_data_->current(all, group_); auto surface_flux = coarse_data_->surface_flux(all, group_); // Normalize the surface currents for (size_t plane = 0; plane < mesh_->nz(); plane++) { for (int surf = mesh_->plane_surf_xy_begin(plane); surf != (int)mesh_->plane_surf_end(plane); ++surf) { real_t area = mesh_->coarse_area(surf); current(surf) /= area; surface_flux(surf) /= area; } } } return; } protected: CoarseData *coarse_data_; const Mesh *mesh_; std::array<real_t, 2> current_weights_; std::array<real_t, 2> flux_weights_; int plane_; int group_; int cell_offset_; int surf_offset_; }; } } <|endoftext|>
<commit_before>/*++ Copyright (c) 2016 Microsoft Corporation Module Name: ackermannize_tactic.cpp Abstract: Author: Mikolas Janota Revision History: --*/ #include"tactical.h" #include"lackr.h" #include"ackr_params.hpp" #include"ackr_model_converter.h" #include"model_smt2_pp.h" class ackermannize_tactic : public tactic { public: ackermannize_tactic(ast_manager& m, params_ref const& p) : m_m(m) , m_p(p) {} virtual ~ackermannize_tactic() { } virtual void operator()(goal_ref const & g, goal_ref_buffer & result, model_converter_ref & mc, proof_converter_ref & pc, expr_dependency_ref & core) { mc = 0; ast_manager& m(g->m()); expr_ref_vector flas(m); const unsigned sz = g->size(); for (unsigned i = 0; i < sz; i++) flas.push_back(g->form(i)); scoped_ptr<lackr> imp = alloc(lackr, m, m_p, m_st, flas); flas.reset(); // mk result goal_ref resg(alloc(goal, *g, true)); imp->mk_ackermann(resg); result.push_back(resg.get()); // report model if (g->models_enabled()) { model_ref abstr_model = imp->get_model(); mc = mk_ackr_model_converter(m, imp->get_info(), abstr_model); } } virtual void collect_statistics(statistics & st) const { st.update("ackr-constraints", m_st.m_ackrs_sz); } virtual void reset_statistics() { m_st.reset(); } virtual void cleanup() { } virtual tactic* translate(ast_manager& m) { return alloc(ackermannize_tactic, m, m_p); } private: ast_manager& m_m; params_ref m_p; lackr_stats m_st; }; tactic * mk_ackermannize_tactic(ast_manager & m, params_ref const & p) { return alloc(ackermannize_tactic, m, p); } <commit_msg>small fix<commit_after>/*++ Copyright (c) 2016 Microsoft Corporation Module Name: ackermannize_tactic.cpp Abstract: Author: Mikolas Janota Revision History: --*/ #include"tactical.h" #include"lackr.h" #include"ackr_params.hpp" #include"ackr_model_converter.h" #include"model_smt2_pp.h" class ackermannize_tactic : public tactic { public: ackermannize_tactic(ast_manager& m, params_ref const& p) : m_m(m) , m_p(p) {} virtual ~ackermannize_tactic() { } virtual void operator()(goal_ref const & g, goal_ref_buffer & result, model_converter_ref & mc, proof_converter_ref & pc, expr_dependency_ref & core) { mc = 0; ast_manager& m(g->m()); expr_ref_vector flas(m); const unsigned sz = g->size(); for (unsigned i = 0; i < sz; i++) flas.push_back(g->form(i)); scoped_ptr<lackr> imp = alloc(lackr, m, m_p, m_st, flas); flas.reset(); // mk result goal_ref resg(alloc(goal, *g, true)); imp->mk_ackermann(resg); result.push_back(resg.get()); // report model if (g->models_enabled()) { mc = mk_ackr_model_converter(m, imp->get_info()); } } virtual void collect_statistics(statistics & st) const { st.update("ackr-constraints", m_st.m_ackrs_sz); } virtual void reset_statistics() { m_st.reset(); } virtual void cleanup() { } virtual tactic* translate(ast_manager& m) { return alloc(ackermannize_tactic, m, m_p); } private: ast_manager& m_m; params_ref m_p; lackr_stats m_st; }; tactic * mk_ackermannize_tactic(ast_manager & m, params_ref const & p) { return alloc(ackermannize_tactic, m, p); } <|endoftext|>
<commit_before>/// \file /// \ingroup tutorial_graphics /// \notebook /// Example illustrating how to modify individual labels of a TGaxis. The method /// `SetLabelAttributes` allows to do that. /// /// The first parameter of this method is the label number to be modified. If /// this number is negative then labels are numbered from the last one. The other /// parameter of this method are in order: the new angle value, the new size /// (0 erase the label), the new text alignment, the new label color and the new /// label text. /// /// \macro_image /// \macro_code /// /// \author Olivier Couet void gaxis3() { c1 = new TCanvas("c1","Examples of Gaxis",10,10,800,400); c1->Range(-6,-0.1,6,0.1); TGaxis *axis = new TGaxis(-5.5,0.,5.5,0.,0.0,100,510,""); axis->SetName("axis"); axis->SetTitle("Axis Title"); axis->SetTitleSize(0.05); axis->SetTitleColor(kBlue); axis->SetTitleFont(42); // Change the 1st label color to red. axis->SetLabelAttributes(1,-1,-1,-1,2); // Erase the 3rd label axis->SetLabelAttributes(3,-1,0.); // 5th label is drawn with an angle of 30 degrees axis->SetLabelAttributes(5,30.,-1,0); // Change the text of the 6th label. axis->SetLabelAttributes(6,-1,-1,-1,3,-1,"6th label"); // Change the text of the 2nd label to the end. axis->SetLabelAttributes(-2,-1,-1,-1,3,-1,"2nd to last label"); axis->Draw(); } <commit_msg>- formating.<commit_after>/// \file /// \ingroup tutorial_graphics /// \notebook /// Example illustrating how to modify individual labels of a TGaxis. The method /// `SetLabelAttributes` allows to do that. /// /// The first parameter of this method is the label number to be modified. If /// this number is negative labels are numbered from the last one. The other /// parameters are (in order): /// - the new angle value, /// - the new size (0 erase the label), /// - the new text alignment, /// - the new label color, /// = the new label text. /// /// \macro_image /// \macro_code /// /// \author Olivier Couet void gaxis3() { c1 = new TCanvas("c1","Examples of Gaxis",10,10,800,400); c1->Range(-6,-0.1,6,0.1); TGaxis *axis = new TGaxis(-5.5,0.,5.5,0.,0.0,100,510,""); axis->SetName("axis"); axis->SetTitle("Axis Title"); axis->SetTitleSize(0.05); axis->SetTitleColor(kBlue); axis->SetTitleFont(42); // Change the 1st label color to red. axis->SetLabelAttributes(1,-1,-1,-1,2); // Erase the 3rd label axis->SetLabelAttributes(3,-1,0.); // 5th label is drawn with an angle of 30 degrees axis->SetLabelAttributes(5,30.,-1,0); // Change the text of the 6th label. axis->SetLabelAttributes(6,-1,-1,-1,3,-1,"6th label"); // Change the text of the 2nd label to the end. axis->SetLabelAttributes(-2,-1,-1,-1,3,-1,"2nd to last label"); axis->Draw(); } <|endoftext|>
<commit_before>// An example how to display PS, EPS, PDF files in canvas // To load a PS file in a TCanvas, the ghostscript program needs to be install. // On most unix systems it is usually installed. On Windows it has to be // installed from http://pages.cs.wisc.edu/~ghost/ //Author: Valeriy Onoutchin #include "TROOT.h" #include "TCanvas.h" #include "TImage.h" void psview() { // set to batch mode -> do not display graphics gROOT->SetBatch(1); // create a PostScript file gROOT->Macro("feynman.C"); gPad->Print("feynman.ps"); // back to graphics mode gROOT->SetBatch(0); // create an image from PS file TImage *ps = TImage::Open("feynman.ps"); if (!ps) { printf("GhostScript (gs) program must be installed\n"); return; } new TCanvas("psexam", "Example how to display PS file in canvas", 500, 650); ps->Draw("xxx"); } <commit_msg>- Complete help.<commit_after>// An example how to display PS, EPS, PDF files in canvas // To load a PS file in a TCanvas, the ghostscript program needs to be install. // - On most unix systems it is installed by default. // - On Windows it has to be installed from http://pages.cs.wisc.edu/~ghost/ // also the place where gswin32c.exe sits should be added in the PATH. One // way to do it is: // 1. Start the Control Panel // 2. Double click on System // 3, Open the "Advanced" tab // 4. Click on the "Environment Variables" button // 5. Find "Path" in "System varibale list", click on it. // 6. Click on the "Edit" button. // 7. In the "Variable value" field add the path of gswin32c // (after a ";") it should be something like: // "C:\Program Files\gs\gs8.13\bin" // 8. click "OK" as much as needed. // //Author: Valeriy Onoutchin #include "TROOT.h" #include "TCanvas.h" #include "TImage.h" void psview() { // set to batch mode -> do not display graphics gROOT->SetBatch(1); // create a PostScript file gROOT->Macro("feynman.C"); gPad->Print("feynman.ps"); // back to graphics mode gROOT->SetBatch(0); // create an image from PS file TImage *ps = TImage::Open("feynman.ps"); if (!ps) { printf("GhostScript (gs) program must be installed\n"); return; } new TCanvas("psexam", "Example how to display PS file in canvas", 500, 650); ps->Draw("xxx"); } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkLaplacianImageFilterTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkImage.h" #include <iostream> #include "itkLaplacianImageFilter.h" #include "itkNullImageToImageFilterDriver.txx" #include "itkVector.h" #include "itkFilterWatcher.h" inline std::ostream& operator<<(std::ostream &o, const itk::Vector<float, 3> &v) { o << "["<< v[0] << " " << v[1] << " " << v[2] << "]"; return o; } int itkLaplacianImageFilterTest(int , char * [] ) { try { typedef itk::Image<float, 2> ImageType; // Set up filter itk::LaplacianImageFilter<ImageType, ImageType>::Pointer filter = itk::LaplacianImageFilter<ImageType, ImageType>::New(); FilterWatcher watch(filter); // Run Test itk::Size<2> sz; sz[0] = 100 ; //atoi(argv[1]); sz[1] = 100 ; // atoi(argv[2]); // sz[2] = 10;//atoi(argv[3]); // sz[3] = 5;//atoi(argv[4]); itk::NullImageToImageFilterDriver< ImageType, ImageType > test1; test1.SetImageSize(sz); test1.SetFilter(filter.GetPointer()); test1.Execute(); // verify the fix for Bug: 788 // The following code should not crash. filter->SetInput(NULL); filter->Update(); } catch(itk::ExceptionObject &err) { (&err)->Print(std::cerr); return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>BUG: 788. The new test should catch an expected exception.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkLaplacianImageFilterTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkImage.h" #include <iostream> #include "itkLaplacianImageFilter.h" #include "itkNullImageToImageFilterDriver.txx" #include "itkVector.h" #include "itkFilterWatcher.h" inline std::ostream& operator<<(std::ostream &o, const itk::Vector<float, 3> &v) { o << "["<< v[0] << " " << v[1] << " " << v[2] << "]"; return o; } int itkLaplacianImageFilterTest(int , char * [] ) { try { typedef itk::Image<float, 2> ImageType; // Set up filter itk::LaplacianImageFilter<ImageType, ImageType>::Pointer filter = itk::LaplacianImageFilter<ImageType, ImageType>::New(); FilterWatcher watch(filter); // Run Test itk::Size<2> sz; sz[0] = 100 ; //atoi(argv[1]); sz[1] = 100 ; // atoi(argv[2]); // sz[2] = 10;//atoi(argv[3]); // sz[3] = 5;//atoi(argv[4]); itk::NullImageToImageFilterDriver< ImageType, ImageType > test1; test1.SetImageSize(sz); test1.SetFilter(filter.GetPointer()); test1.Execute(); // verify the fix for Bug: 788 // The following code should throw an excption and not crash. filter->SetInput(NULL); bool exceptionSeen = false; try { filter->Update(); } catch(itk::ExceptionObject &err) { exceptionSeen = true; std::cout << "Expected exception was received OK" << std::endl; } if( !exceptionSeen ) { std::cerr << "Expected exception was not thrown" << std::endl; return EXIT_FAILURE; } } catch(itk::ExceptionObject &err) { (&err)->Print(std::cerr); return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * tests.cpp * * Created on: Apr 16, 2009 * Author: jdw */ #include <iostream> #include <math.h> // Tests won't run without 'DEBUG' #define DEBUG 1 #include "lib/jdw_vector2d.h" #include "lib/jdw_vector3d.h" #include "lib/jdw_misc.h" #include "lib/jdw_test.h" #include "lib/jdw_vertex.h" #include "lib/jdw_polygon.h" #include "lib/jdw_camera.h" #include "lib/jdw_cube.h" #include "lib/jdw_improvedperlinnoise.h" #include "lib/jdw_list.h" using namespace std; void test_v2() { dV2 tmp = dV2(); // Testing default values TEST_TRUE(tmp.x == 0); TEST_TRUE(tmp.y == 0); // Testing operators // = tmp = tmp; TEST_VAL(tmp, dV2()); tmp.x = tmp.y = 0; TEST_VAL(tmp, dV2()); TEST_VAL((tmp = dV2(2, 2)), dV2(2, 2)); tmp.x = 0; tmp.y = 0; // == TEST_TRUE(tmp == dV2()); TEST_FALSE(tmp == dV2(1, 0)); TEST_FALSE(tmp == dV2(0, 1)); // != TEST_TRUE(tmp != dV2(1, 0)); TEST_TRUE(tmp != dV2(0, 1)); // + TEST_VAL((tmp + dV2(23, 2)), dV2(23, 2)); // += tmp += dV2(23, 2); TEST_VAL(tmp, dV2(23, 2)); tmp.x = 0; tmp.y = 0; // - TEST_VAL((tmp - dV2(23, 2)), dV2(-23, -2)); // + - TEST_VAL((tmp + dV2(23, 2) - dV2(23, 2)), tmp); // - + TEST_VAL((tmp - dV2(23, 2) + dV2(23, 2)), tmp); // -= tmp -= dV2(27, 45); TEST_VAL(tmp, dV2(-27, -45)); tmp.x = 0; tmp.y = 0; // * TEST_VAL((dV2(4, 2) * 5), dV2(20, 10)); // *= tmp.x = 3; tmp.y = 7; tmp *= 5; TEST_VAL(tmp, dV2(15, 35)); tmp.x = 2; tmp.y = 4; // Testing functions TEST_VAL(tmp.GetDP(dV2(4, 3)), 20); TEST_VAL(dV2(2.0, 4.0).GetUnit(), dV2(2.0 / sqrt(20.0), 4.0 / sqrt(20.0))); //TEST_VAL(tmp.GetXP(V2i(3, 7)), V2i(6, 28)); TEST_VAL(tmp.GetLength(), sqrt(20)); TEST_VAL(tmp.GetDist(dV2()), tmp.GetLength()); TEST_VAL(tmp.GetDist(tmp), 0); // Testing against self TEST_VAL(tmp.GetDist(dV2(tmp.x, tmp.y)), 0); // Testing with same values TEST_VAL(tmp.GetUnit().GetLength(), 1); } void test_v3() { dV3 tmp = dV3(); // Testing default values TEST_TRUE(tmp.x == 0); TEST_TRUE(tmp.y == 0); TEST_TRUE(tmp.z == 0); // Testing operators // = tmp = tmp; TEST_VAL(tmp, dV3()); tmp.x = tmp.y = tmp.z = 0; TEST_VAL(tmp, dV3()); TEST_VAL((tmp = dV3(2, 2, 2)), dV3(2, 2, 2)); tmp.x = tmp.y = tmp.z = 0; // == TEST_TRUE(tmp == dV3()); TEST_FALSE(tmp == dV3(1, 0, 0)); TEST_FALSE(tmp == dV3(0, 1, 0)); TEST_FALSE(tmp == dV3(0, 0, 1)); // != TEST_TRUE(tmp != dV3(1, 0, 0)); TEST_TRUE(tmp != dV3(0, 1, 0)); TEST_TRUE(tmp != dV3(0, 0, 1)); // + TEST_VAL((tmp + dV3(3, 5, 7)), dV3(3, 5, 7)); // += tmp += dV3(3, 5, 7); TEST_VAL(tmp, dV3(3, 5, 7)); tmp.x = tmp.y = tmp.z = 0; // - TEST_VAL((tmp - dV3(1337, 4711, 4242)), dV3(-1337, -4711, -4242)); // + - TEST_VAL((tmp + dV3(23, 2, 7) - dV3(23, 2, 7)), tmp); // - + TEST_VAL((tmp - dV3(23, 2, 9) + dV3(23, 2, 9)), tmp); // -= tmp -= dV3(27, 45, 19); TEST_VAL(tmp, dV3(-27, -45, -19)); tmp.x = tmp.y = tmp.z = 0; // * TEST_VAL((iV3(4, 2, 7) * 5), iV3(20, 10, 35)); // *= tmp.x = 3; tmp.y = 5; tmp.z = 7; tmp *= 5; TEST_VAL(tmp, dV3(15, 25, 35)); tmp.x = 3; tmp.y = 5; tmp.z = 7; // Testing functions TEST_VAL(tmp.GetDP(dV3(4, 3, 2)), 41); TEST_VAL(tmp.GetXP(dV3(12, 11, 10)), dV3(-27, 54, -27)); TEST_VAL(tmp.GetLength(), sqrt(83)); TEST_VAL(dV3(3.0, 5.0, 7.0).GetUnit(), dV3(3.0 / sqrt(83.0), 5.0 / sqrt(83.0), 7.0 / sqrt(83.0))); TEST_VAL(tmp.GetDist(dV3()), tmp.GetLength()); TEST_VAL(tmp.GetDist(tmp), 0); // Testing against self TEST_VAL(tmp.GetDist(dV3(tmp.x, tmp.y, tmp.z)), 0); // Testing with same values TEST_VAL(tmp.GetUnit().GetLength(), tmp.GetUnit().GetLength()); TEST_VAL(tmp.GetUnit().GetLength(), 1.0); } void test_list() { int val = 1; iList* tmp = new iList(new int(val)); int sum = val; val++; TEST_PTR(tmp); TEST_PTR(tmp->pObj); for (; val < 6; val++) { sum += val; tmp->Add(new int(val)); } TEST_VAL(tmp->Size(), 5); iList* it = tmp; int it_sum = 0; while (it != NULL) { if (it->pObj != NULL) it_sum += *it->pObj; it = it->pNext; } tmp->DelAllObj(); delete tmp; TEST_VAL(it_sum, sum); } int main() { // All tests should go trough OK, and if so, no output be given. test_v2(); test_v3(); test_list(); exit(0); } <commit_msg>Adding tests for pixel, image, IO, sizes and types.<commit_after>/* * tests.cpp * * Created on: Apr 16, 2009 * Author: jdw */ #include <iostream> #include <fstream> #include <math.h> // Tests won't run without 'DEBUG' #define DEBUG 1 #include "lib/jdw_types.h" #include "lib/jdw_vector2d.h" #include "lib/jdw_vector3d.h" #include "lib/jdw_misc.h" #include "lib/jdw_test.h" #include "lib/jdw_vertex.h" #include "lib/jdw_polygon.h" #include "lib/jdw_camera.h" #include "lib/jdw_cube.h" #include "lib/jdw_improvedperlinnoise.h" #include "lib/jdw_list.h" #include "lib/jdw_pixel.h" #include "lib/jdw_image.h"; using namespace std; void TestVector2d() { dV2 tmp = dV2(); // Testing default values TEST_TRUE(tmp.x == 0); TEST_TRUE(tmp.y == 0); // Testing operators // = tmp = tmp; TEST_VAL(tmp, dV2()); tmp.x = tmp.y = 0; TEST_VAL(tmp, dV2()); TEST_VAL((tmp = dV2(2, 2)), dV2(2, 2)); tmp.x = 0; tmp.y = 0; // == TEST_TRUE(tmp == dV2()); TEST_FALSE(tmp == dV2(1, 0)); TEST_FALSE(tmp == dV2(0, 1)); // != TEST_TRUE(tmp != dV2(1, 0)); TEST_TRUE(tmp != dV2(0, 1)); // + TEST_VAL((tmp + dV2(23, 2)), dV2(23, 2)); // += tmp += dV2(23, 2); TEST_VAL(tmp, dV2(23, 2)); tmp.x = 0; tmp.y = 0; // - TEST_VAL((tmp - dV2(23, 2)), dV2(-23, -2)); // + - TEST_VAL((tmp + dV2(23, 2) - dV2(23, 2)), tmp); // - + TEST_VAL((tmp - dV2(23, 2) + dV2(23, 2)), tmp); // -= tmp -= dV2(27, 45); TEST_VAL(tmp, dV2(-27, -45)); tmp.x = 0; tmp.y = 0; // * TEST_VAL((dV2(4, 2) * 5), dV2(20, 10)); // *= tmp.x = 3; tmp.y = 7; tmp *= 5; TEST_VAL(tmp, dV2(15, 35)); tmp.x = 2; tmp.y = 4; // Testing functions TEST_VAL(tmp.GetDP(dV2(4, 3)), 20); TEST_VAL(dV2(2.0, 4.0).GetUnit(), dV2(2.0 / sqrt(20.0), 4.0 / sqrt(20.0))); //TEST_VAL(tmp.GetXP(V2i(3, 7)), V2i(6, 28)); TEST_VAL(tmp.GetLength(), sqrt(20)); TEST_VAL(tmp.GetDist(dV2()), tmp.GetLength()); TEST_VAL(tmp.GetDist(tmp), 0); // Testing against self TEST_VAL(tmp.GetDist(dV2(tmp.x, tmp.y)), 0); // Testing with same values TEST_VAL(tmp.GetUnit().GetLength(), 1); } void TestVector3d() { dV3 tmp = dV3(); // Testing default values TEST_TRUE(tmp.x == 0); TEST_TRUE(tmp.y == 0); TEST_TRUE(tmp.z == 0); // Testing operators // = tmp = tmp; TEST_VAL(tmp, dV3()); tmp.x = tmp.y = tmp.z = 0; TEST_VAL(tmp, dV3()); TEST_VAL((tmp = dV3(2, 2, 2)), dV3(2, 2, 2)); tmp.x = tmp.y = tmp.z = 0; // == TEST_TRUE(tmp == dV3()); TEST_FALSE(tmp == dV3(1, 0, 0)); TEST_FALSE(tmp == dV3(0, 1, 0)); TEST_FALSE(tmp == dV3(0, 0, 1)); // != TEST_TRUE(tmp != dV3(1, 0, 0)); TEST_TRUE(tmp != dV3(0, 1, 0)); TEST_TRUE(tmp != dV3(0, 0, 1)); // + TEST_VAL((tmp + dV3(3, 5, 7)), dV3(3, 5, 7)); // += tmp += dV3(3, 5, 7); TEST_VAL(tmp, dV3(3, 5, 7)); tmp.x = tmp.y = tmp.z = 0; // - TEST_VAL((tmp - dV3(1337, 4711, 4242)), dV3(-1337, -4711, -4242)); // + - TEST_VAL((tmp + dV3(23, 2, 7) - dV3(23, 2, 7)), tmp); // - + TEST_VAL((tmp - dV3(23, 2, 9) + dV3(23, 2, 9)), tmp); // -= tmp -= dV3(27, 45, 19); TEST_VAL(tmp, dV3(-27, -45, -19)); tmp.x = tmp.y = tmp.z = 0; // * TEST_VAL((iV3(4, 2, 7) * 5), iV3(20, 10, 35)); // *= tmp.x = 3; tmp.y = 5; tmp.z = 7; tmp *= 5; TEST_VAL(tmp, dV3(15, 25, 35)); tmp.x = 3; tmp.y = 5; tmp.z = 7; // Testing functions TEST_VAL(tmp.GetDP(dV3(4, 3, 2)), 41); TEST_VAL(tmp.GetXP(dV3(12, 11, 10)), dV3(-27, 54, -27)); TEST_VAL(tmp.GetLength(), sqrt(83)); TEST_VAL(dV3(3.0, 5.0, 7.0).GetUnit(), dV3(3.0 / sqrt(83.0), 5.0 / sqrt(83.0), 7.0 / sqrt(83.0))); TEST_VAL(tmp.GetDist(dV3()), tmp.GetLength()); TEST_VAL(tmp.GetDist(tmp), 0); // Testing against self TEST_VAL(tmp.GetDist(dV3(tmp.x, tmp.y, tmp.z)), 0); // Testing with same values TEST_VAL(tmp.GetUnit().GetLength(), tmp.GetUnit().GetLength()); TEST_VAL(tmp.GetUnit().GetLength(), 1.0); } void TestList() { int val = 1; iList* tmp = new iList(new int(val)); int sum = val; val++; TEST_PTR(tmp); TEST_PTR(tmp->pObj); for (; val < 6; val++) { sum += val; tmp->Add(new int(val)); } TEST_VAL(tmp->Size(), 5); iList* it = tmp; int it_sum = 0; while (it != NULL) { if (it->pObj != NULL) it_sum += *it->pObj; it = it->pNext; } tmp->DelAllObj(); delete tmp; TEST_VAL(it_sum, sum); } void TestPixel() { JDW_Pixel tmp; tmp.integer = 0; TEST_VAL(tmp.a, 0); TEST_VAL(tmp.r, 0); TEST_VAL(tmp.g, 0); TEST_VAL(tmp.b, 0); TEST_VAL(tmp.integer, 0); tmp.a = 16; tmp.r = 32; tmp.g = 64; tmp.b = 128; TEST_VAL(tmp.a, 16); TEST_VAL(tmp.r, 32); TEST_VAL(tmp.g, 64); TEST_VAL(tmp.b, 128); TEST_TRUE(tmp.integer != 0); } void TestIO() { JDW_Image<JDW_Pixel, JDW_Pixel>* tmp_pImg1 = new JDW_Image<JDW_Pixel, JDW_Pixel>(iV2(2, 3)); tmp_pImg1->PutPixel(iV2(0,0), JDW_Pixel(0, 0, 0)); tmp_pImg1->PutPixel(iV2(1,0), JDW_Pixel(255, 0, 0)); tmp_pImg1->PutPixel(iV2(0,1), JDW_Pixel(0, 255, 0)); tmp_pImg1->PutPixel(iV2(1,1), JDW_Pixel(0, 0, 255)); tmp_pImg1->PutPixel(iV2(0,2), JDW_Pixel(255, 0, 255)); tmp_pImg1->PutPixel(iV2(1,2), JDW_Pixel(255, 255, 255)); tmp_pImg1->SetTrans(JDW_Pixel(255, 255, 255)); ofstream fout("test.data", ios::binary); fout.write((char *)(&tmp_pImg1->GetSize()), sizeof(tmp_pImg1->GetSize())); fout.write((char *)(tmp_pImg1), sizeof(*tmp_pImg1)); fout.close(); ifstream fin("test.data", ios::binary); iV2 tmp_size = iV2(); fin.read((char *)(&tmp_size), sizeof(tmp_size)); TEST_VAL(tmp_size, tmp_pImg1->GetSize()); JDW_Image<JDW_Pixel, JDW_Pixel>* tmp_pImg2 = new JDW_Image<JDW_Pixel, JDW_Pixel>(tmp_size); fin.read((char *)(tmp_pImg2), sizeof(*tmp_pImg2)); fin.close(); TEST_TRUE(tmp_pImg1->GetPixel(iV2(0, 0)) == tmp_pImg2->GetPixel(iV2(0, 0))); TEST_TRUE(tmp_pImg1->GetPixel(iV2(1, 0)) == tmp_pImg2->GetPixel(iV2(1, 0))); TEST_TRUE(tmp_pImg1->GetPixel(iV2(0, 1)) == tmp_pImg2->GetPixel(iV2(0, 1))); TEST_TRUE(tmp_pImg1->GetPixel(iV2(1, 1)) == tmp_pImg2->GetPixel(iV2(1, 1))); TEST_TRUE(tmp_pImg1->GetPixel(iV2(0, 2)) == tmp_pImg2->GetPixel(iV2(0, 2))); TEST_TRUE(tmp_pImg1->GetPixel(iV2(1, 2)) == tmp_pImg2->GetPixel(iV2(1, 2))); TEST_TRUE(tmp_pImg1->GetTrans() == tmp_pImg2->GetTrans()); TEST_TRUE(tmp_pImg1->GetSize() == tmp_pImg2->GetSize()); } void TestSizes() { TEST_VAL(sizeof(unsigned char), 1); TEST_VAL(sizeof(char), 1); TEST_VAL(sizeof(unsigned short), 2); TEST_VAL(sizeof(short), 2); TEST_VAL(sizeof(unsigned int), 4); TEST_VAL(sizeof(int), 4); TEST_VAL(sizeof(double), 8); TEST_VAL(sizeof(long), 4); } void TestTypes() { ui8 tmp_ui8 = 255; i8 tmp_i8 = -128; i16 tmp_i16 = -32768; //ui32 tmp_ui32 = 4294967296; i32 tmp_i32 = 2147483647; d64 tmp_d64 = -1.1; TEST_VAL(tmp_ui8, 255); TEST_VAL(tmp_i8, -128); // TEST_VAL(tmp_ui16, 65536); TEST_VAL(tmp_i16, -32768); // TEST_VAL(tmp_ui32, 4294967296); TEST_VAL(tmp_i32, 2147483647); tmp_i32 = -2147483647; TEST_VAL(tmp_i32, -2147483647); TEST_VAL(tmp_d64, -1.1); } void TestImage() { JDW_Image<JDW_Pixel, JDW_Pixel>* tmp_pImg = new JDW_Image<JDW_Pixel, JDW_Pixel>(iV2(5, 5)); TEST_TRUE(tmp_pImg->IsInside(iV2(0, 0))); TEST_TRUE(tmp_pImg->IsInside(iV2(0, 4))); TEST_TRUE(tmp_pImg->IsInside(iV2(4, 0))); TEST_TRUE(tmp_pImg->IsInside(iV2(4, 4))); TEST_FALSE(tmp_pImg->IsInside(iV2(-1, -1))); TEST_FALSE(tmp_pImg->IsInside(iV2(0, 5))); TEST_FALSE(tmp_pImg->IsInside(iV2(5, 0))); TEST_FALSE(tmp_pImg->IsInside(iV2(5, 5))); TEST_TRUE(tmp_pImg->IsInside(iV2(-1, 3))); } int main() { // All tests should go trough OK, and if so, no output be given. TestVector2d(); TestVector3d(); TestList(); TestPixel(); TestImage(); TestIO(); TestSizes(); TestTypes(); exit(0); } <|endoftext|>
<commit_before>#include "ShaderProgram.h" #include "LightShaderUniforms.h" #include "RubikCubeControl.h" #include <memory> #include <thread> #include <iostream> #include <glm/gtc/type_ptr.hpp> namespace { const int WINDOW_WIDTH = 800; const int WINDOW_HEIGHT = 600; const int DELTA_TIME = 1000.f / 30; const float MAX_ROTATION_DIST = 30.f; int glutWindow; std::unique_ptr<ShaderProgram> shader; std::shared_ptr<RubikCube> rubikCube; std::unique_ptr<RubikCubeControl> rubikCubeControl; Camera camera(1.f * WINDOW_WIDTH, 1.f * WINDOW_HEIGHT); GLint positionAttribute; GLint normalAttribute; MatrixShaderUniforms matrixUniforms; MaterialShaderUniforms materialUniforms; LightShaderUniforms lightUniforms; GLint eyePositionUniform; bool cameraRotationEnabled = false; int prevMouseX = -1; int prevMouseY = -1; void InitializeUniforms() { // in attributes positionAttribute = glGetAttribLocation(shader->GetProgram(), "position"); normalAttribute = glGetAttribLocation(shader->GetProgram(), "normal"); // matrices matrixUniforms.pvmMatrixUniform = glGetUniformLocation(shader->GetProgram(), "pvm_matrix"); matrixUniforms.normalMatrixUniform = glGetUniformLocation(shader->GetProgram(), "normal_matrix"); matrixUniforms.modelMatrixUniform = glGetUniformLocation(shader->GetProgram(), "model_matrix"); // materials materialUniforms.ambientColorUniform = glGetUniformLocation(shader->GetProgram(), "material_ambient_color"); materialUniforms.diffuseColorUniform = glGetUniformLocation(shader->GetProgram(), "material_diffuse_color"); materialUniforms.specularColorUniform = glGetUniformLocation(shader->GetProgram(), "material_specular_color"); materialUniforms.shininessUniform = glGetUniformLocation(shader->GetProgram(), "material_shininess"); // light lightUniforms.ambientColorUniform = glGetUniformLocation(shader->GetProgram(), "light_ambient_color"); lightUniforms.diffuseColorUniform = glGetUniformLocation(shader->GetProgram(), "light_diffuse_color"); lightUniforms.specularColorUniform = glGetUniformLocation(shader->GetProgram(), "light_specular_color"); lightUniforms.positionUniform = glGetUniformLocation(shader->GetProgram(), "light_position"); eyePositionUniform = glGetUniformLocation(shader->GetProgram(), "eye_position"); } void Initialize() { glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); glClearColor(0.01f, 0.01f, 0.01f, 1.0f); glClearDepth(1.0f); glEnable(GL_DEPTH_TEST); shader = std::make_unique<ShaderProgram>("VertexShader.glsl", "FragmentShader.glsl"); InitializeUniforms(); rubikCube = std::make_shared<RubikCube>(positionAttribute, normalAttribute, 3); rubikCubeControl = std::make_unique<RubikCubeControl>(rubikCube); } void Destroy() { // Must be called before OpenGL destroys it's own content rubikCubeControl.reset(); rubikCube.reset(); shader.reset(); glutDestroyWindow(glutWindow); } void SetupLight() { glm::vec4 lightPosition(camera.GetEyePosition(), 1.f); glUniform4fv(lightUniforms.positionUniform, 1, glm::value_ptr(lightPosition)); glUniform3f(lightUniforms.ambientColorUniform, .05f, .05f, .05f); glUniform3f(lightUniforms.diffuseColorUniform, 1.f, 1.f, 1.f); glUniform3f(lightUniforms.specularColorUniform, 1.f, 1.f, 1.f); } void SetupEyePosition() { glUniform3fv(eyePositionUniform, 1, glm::value_ptr(camera.GetEyePosition())); } void Update() { if (!rubikCubeControl->IsRunning()) { Destroy(); exit(0); } // FYI delta time is overkill for this simple animation rubikCube->Update(1.f / DELTA_TIME); } void Display() { // Update part Update(); // Draw part glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shader->SetActive(); SetupLight(); rubikCube->Draw(camera, matrixUniforms, materialUniforms); shader->SetInactive(); glutSwapBuffers(); } void MouseButton(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON || button == GLUT_RIGHT_BUTTON) { cameraRotationEnabled = (state == GLUT_DOWN); } } void MouseMotion(int x, int y) { // Initialization if (prevMouseX < 0 && prevMouseY < 0) { // @goto masterrace prevMouseX = x; prevMouseY = y; return; } auto deltaX = static_cast<float>(x - prevMouseX); auto deltaY = static_cast<float>(y - prevMouseY); if (cameraRotationEnabled) { if (fabsf(deltaX) < MAX_ROTATION_DIST && fabsf(deltaY) < MAX_ROTATION_DIST) { camera.Rotate(deltaX, deltaY); } } prevMouseX = x; prevMouseY = y; } void WheelMotion(int wheel, int direction, int mx, int my) { if (direction < 0) { camera.ZoomIn(); } else { camera.ZoomOut(); } } void KeyboardDown(unsigned char key, int mx, int my) { switch (key) { case 27: Destroy(); exit(0); break; /*case '\t': cubeRotationPositive = !cubeRotationPositive; break; case 'q': rubikCube->Rotate(RubikCube::X_AXIS, 0, cubeRotationPositive); break; case 'w': rubikCube->Rotate(RubikCube::X_AXIS, 1, cubeRotationPositive); break; case 'e': rubikCube->Rotate(RubikCube::X_AXIS, 2, cubeRotationPositive); break; case 'a': rubikCube->Rotate(RubikCube::Y_AXIS, 0, cubeRotationPositive); break; case 's': rubikCube->Rotate(RubikCube::Y_AXIS, 1, cubeRotationPositive); break; case 'd': rubikCube->Rotate(RubikCube::Y_AXIS, 2, cubeRotationPositive); break; case 'z': rubikCube->Rotate(RubikCube::Z_AXIS, 0, cubeRotationPositive); break; case 'x': rubikCube->Rotate(RubikCube::Z_AXIS, 1, cubeRotationPositive); break; case 'c': rubikCube->Rotate(RubikCube::Z_AXIS, 2, cubeRotationPositive); break; */ } } void KeyboardUp(unsigned char key, int mx, int my) { } void Timer(int value) { glutTimerFunc(DELTA_TIME, Timer, 0); glutPostRedisplay(); } void OpenGLCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const char* message, const void* userParam) { std::cout << message << std::endl; } void SetupOpenGLCallback() { auto debugExtAddr = wglGetProcAddress("glDebugMessageCallbackARB"); auto debugExtCallback = reinterpret_cast<PFNGLDEBUGMESSAGECALLBACKARBPROC>(debugExtAddr); if (debugExtCallback) // callback function exists { glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); debugExtCallback(reinterpret_cast<GLDEBUGPROCARB>(OpenGLCallback), nullptr); } } } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); glutInitContextVersion(3, 3); glutInitContextProfile(GLUT_COMPATIBILITY_PROFILE); glutInitContextFlags(GLUT_DEBUG); glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT); glutWindow = glutCreateWindow("Rubik's Cube Visualizer"); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { return -1; } Initialize(); SetupOpenGLCallback(); glutDisplayFunc(Display); glutKeyboardFunc(KeyboardDown); glutKeyboardUpFunc(KeyboardUp); glutMouseFunc(MouseButton); glutMotionFunc(MouseMotion); glutMouseWheelFunc(::WheelMotion); glutTimerFunc(DELTA_TIME, Timer, 0); glutMainLoop(); Destroy(); return 0; } <commit_msg>Update Main.cpp<commit_after>#include "ShaderProgram.h" #include "LightShaderUniforms.h" #include "RubikCubeControl.h" #include <memory> #include <thread> #include <iostream> #include <glm/gtc/type_ptr.hpp> namespace { const int WINDOW_WIDTH = 800; const int WINDOW_HEIGHT = 600; const float DELTA_TIME = 1000.f / 30; const float MAX_ROTATION_DIST = 30.f; int glutWindow; std::unique_ptr<ShaderProgram> shader; std::shared_ptr<RubikCube> rubikCube; std::unique_ptr<RubikCubeControl> rubikCubeControl; Camera camera(1.f * WINDOW_WIDTH, 1.f * WINDOW_HEIGHT); GLint positionAttribute; GLint normalAttribute; MatrixShaderUniforms matrixUniforms; MaterialShaderUniforms materialUniforms; LightShaderUniforms lightUniforms; GLint eyePositionUniform; bool cameraRotationEnabled = false; int prevMouseX = -1; int prevMouseY = -1; void InitializeUniforms() { // in attributes positionAttribute = glGetAttribLocation(shader->GetProgram(), "position"); normalAttribute = glGetAttribLocation(shader->GetProgram(), "normal"); // matrices matrixUniforms.pvmMatrixUniform = glGetUniformLocation(shader->GetProgram(), "pvm_matrix"); matrixUniforms.normalMatrixUniform = glGetUniformLocation(shader->GetProgram(), "normal_matrix"); matrixUniforms.modelMatrixUniform = glGetUniformLocation(shader->GetProgram(), "model_matrix"); // materials materialUniforms.ambientColorUniform = glGetUniformLocation(shader->GetProgram(), "material_ambient_color"); materialUniforms.diffuseColorUniform = glGetUniformLocation(shader->GetProgram(), "material_diffuse_color"); materialUniforms.specularColorUniform = glGetUniformLocation(shader->GetProgram(), "material_specular_color"); materialUniforms.shininessUniform = glGetUniformLocation(shader->GetProgram(), "material_shininess"); // light lightUniforms.ambientColorUniform = glGetUniformLocation(shader->GetProgram(), "light_ambient_color"); lightUniforms.diffuseColorUniform = glGetUniformLocation(shader->GetProgram(), "light_diffuse_color"); lightUniforms.specularColorUniform = glGetUniformLocation(shader->GetProgram(), "light_specular_color"); lightUniforms.positionUniform = glGetUniformLocation(shader->GetProgram(), "light_position"); eyePositionUniform = glGetUniformLocation(shader->GetProgram(), "eye_position"); } void Initialize() { glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); glClearColor(0.01f, 0.01f, 0.01f, 1.0f); glClearDepth(1.0f); glEnable(GL_DEPTH_TEST); shader = std::make_unique<ShaderProgram>("VertexShader.glsl", "FragmentShader.glsl"); InitializeUniforms(); rubikCube = std::make_shared<RubikCube>(positionAttribute, normalAttribute, 3); rubikCubeControl = std::make_unique<RubikCubeControl>(rubikCube); } void Destroy() { // Must be called before OpenGL destroys it's own content rubikCubeControl.reset(); rubikCube.reset(); shader.reset(); glutDestroyWindow(glutWindow); } void SetupLight() { glm::vec4 lightPosition(camera.GetEyePosition(), 1.f); glUniform4fv(lightUniforms.positionUniform, 1, glm::value_ptr(lightPosition)); glUniform3f(lightUniforms.ambientColorUniform, .05f, .05f, .05f); glUniform3f(lightUniforms.diffuseColorUniform, 1.f, 1.f, 1.f); glUniform3f(lightUniforms.specularColorUniform, 1.f, 1.f, 1.f); } void SetupEyePosition() { glUniform3fv(eyePositionUniform, 1, glm::value_ptr(camera.GetEyePosition())); } void Update() { if (!rubikCubeControl->IsRunning()) { Destroy(); exit(0); } // FYI delta time is overkill for this simple animation rubikCube->Update(1.f / DELTA_TIME); } void Display() { // Update part Update(); // Draw part glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shader->SetActive(); SetupLight(); rubikCube->Draw(camera, matrixUniforms, materialUniforms); shader->SetInactive(); glutSwapBuffers(); } void MouseButton(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON || button == GLUT_RIGHT_BUTTON) { cameraRotationEnabled = (state == GLUT_DOWN); } } void MouseMotion(int x, int y) { // Initialization if (prevMouseX < 0 && prevMouseY < 0) { // @goto masterrace prevMouseX = x; prevMouseY = y; return; } auto deltaX = static_cast<float>(x - prevMouseX); auto deltaY = static_cast<float>(y - prevMouseY); if (cameraRotationEnabled) { if (fabsf(deltaX) < MAX_ROTATION_DIST && fabsf(deltaY) < MAX_ROTATION_DIST) { camera.Rotate(deltaX, deltaY); } } prevMouseX = x; prevMouseY = y; } void WheelMotion(int wheel, int direction, int mx, int my) { if (direction < 0) { camera.ZoomIn(); } else { camera.ZoomOut(); } } void KeyboardDown(unsigned char key, int mx, int my) { switch (key) { case 27: Destroy(); exit(0); break; /*case '\t': cubeRotationPositive = !cubeRotationPositive; break; case 'q': rubikCube->Rotate(RubikCube::X_AXIS, 0, cubeRotationPositive); break; case 'w': rubikCube->Rotate(RubikCube::X_AXIS, 1, cubeRotationPositive); break; case 'e': rubikCube->Rotate(RubikCube::X_AXIS, 2, cubeRotationPositive); break; case 'a': rubikCube->Rotate(RubikCube::Y_AXIS, 0, cubeRotationPositive); break; case 's': rubikCube->Rotate(RubikCube::Y_AXIS, 1, cubeRotationPositive); break; case 'd': rubikCube->Rotate(RubikCube::Y_AXIS, 2, cubeRotationPositive); break; case 'z': rubikCube->Rotate(RubikCube::Z_AXIS, 0, cubeRotationPositive); break; case 'x': rubikCube->Rotate(RubikCube::Z_AXIS, 1, cubeRotationPositive); break; case 'c': rubikCube->Rotate(RubikCube::Z_AXIS, 2, cubeRotationPositive); break; */ } } void KeyboardUp(unsigned char key, int mx, int my) { } void Timer(int value) { glutTimerFunc(DELTA_TIME, Timer, 0); glutPostRedisplay(); } void OpenGLCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const char* message, const void* userParam) { std::cout << message << std::endl; } void SetupOpenGLCallback() { auto debugExtAddr = wglGetProcAddress("glDebugMessageCallbackARB"); auto debugExtCallback = reinterpret_cast<PFNGLDEBUGMESSAGECALLBACKARBPROC>(debugExtAddr); if (debugExtCallback) // callback function exists { glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); debugExtCallback(reinterpret_cast<GLDEBUGPROCARB>(OpenGLCallback), nullptr); } } } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); glutInitContextVersion(3, 3); glutInitContextProfile(GLUT_COMPATIBILITY_PROFILE); glutInitContextFlags(GLUT_DEBUG); glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT); glutWindow = glutCreateWindow("Rubik's Cube Visualizer"); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { return -1; } Initialize(); SetupOpenGLCallback(); glutDisplayFunc(Display); glutKeyboardFunc(KeyboardDown); glutKeyboardUpFunc(KeyboardUp); glutMouseFunc(MouseButton); glutMotionFunc(MouseMotion); glutMouseWheelFunc(::WheelMotion); glutTimerFunc(DELTA_TIME, Timer, 0); glutMainLoop(); Destroy(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2016-2020 The ZCash developers // Copyright (c) 2020 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet/test/wallet_test_fixture.h" #include "sapling/sapling_util.h" #include "sapling/address.h" #include "wallet/wallet.h" #include "wallet/walletdb.h" #include "util.h" #include <boost/test/unit_test.hpp> /** * This test covers methods on CWallet * GenerateNewZKey() * AddZKey() * LoadZKey() * LoadZKeyMetadata() */ BOOST_FIXTURE_TEST_SUITE(wallet_zkeys_tests, WalletTestingSetup) /** * This test covers Sapling methods on CWallet * GenerateNewSaplingZKey() * AddSaplingZKey() * LoadSaplingZKey() * LoadSaplingZKeyMetadata() */ BOOST_AUTO_TEST_CASE(StoreAndLoadSaplingZkeys) { SelectParams(CBaseChainParams::MAIN); CWallet wallet; LOCK(wallet.cs_wallet); // wallet should be empty std::set<libzcash::SaplingPaymentAddress> addrs; wallet.GetSaplingPaymentAddresses(addrs); BOOST_CHECK_EQUAL(0, addrs.size()); // No HD seed in the wallet BOOST_CHECK_THROW(wallet.GenerateNewSaplingZKey(), std::runtime_error); // Random seed CKey seed; seed.MakeNewKey(true); wallet.AddKeyPubKey(seed, seed.GetPubKey()); wallet.GetSaplingScriptPubKeyMan()->SetHDSeed(seed.GetPubKey(), false, true); // wallet should have one key auto address = wallet.GenerateNewSaplingZKey(); wallet.GetSaplingPaymentAddresses(addrs); BOOST_CHECK_EQUAL(1, addrs.size()); // verify wallet has incoming viewing key for the address BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(address)); // manually add new spending key to wallet HDSeed seed1(seed.GetPrivKey()); auto m = libzcash::SaplingExtendedSpendingKey::Master(seed1); auto sk = m.Derive(0); BOOST_CHECK(wallet.AddSaplingZKey(sk)); // verify wallet did add it auto extfvk = sk.ToXFVK(); BOOST_CHECK(wallet.HaveSaplingSpendingKey(extfvk)); // verify spending key stored correctly libzcash::SaplingExtendedSpendingKey keyOut; wallet.GetSaplingSpendingKey(extfvk, keyOut); BOOST_CHECK(sk == keyOut); // verify there are two keys wallet.GetSaplingPaymentAddresses(addrs); BOOST_CHECK_EQUAL(2, addrs.size()); BOOST_CHECK_EQUAL(1, addrs.count(address)); BOOST_CHECK_EQUAL(1, addrs.count(sk.DefaultAddress())); // Generate a diversified address different to the default // If we can't get an early diversified address, we are very unlucky blob88 diversifier; diversifier.begin()[0] = 10; auto dpa = sk.ToXFVK().Address(diversifier).get().second; // verify wallet only has the default address BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(sk.DefaultAddress())); BOOST_CHECK(!wallet.HaveSaplingIncomingViewingKey(dpa)); // manually add a diversified address auto ivk = extfvk.fvk.in_viewing_key(); BOOST_CHECK(wallet.AddSaplingIncomingViewingKeyW(ivk, dpa)); // verify wallet did add it BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(sk.DefaultAddress())); BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(dpa)); // Load a third key into the wallet auto sk2 = m.Derive(1); BOOST_CHECK(wallet.LoadSaplingZKey(sk2)); // attach metadata to this third key auto ivk2 = sk2.expsk.full_viewing_key().in_viewing_key(); int64_t now = GetTime(); CKeyMetadata meta(now); BOOST_CHECK(wallet.LoadSaplingZKeyMetadata(ivk2, meta)); // check metadata is the same BOOST_CHECK_EQUAL(wallet.GetSaplingScriptPubKeyMan()->mapSaplingZKeyMetadata[ivk2].nCreateTime, now); // Load a diversified address for the third key into the wallet auto dpa2 = sk2.ToXFVK().Address(diversifier).get().second; BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(sk2.DefaultAddress())); BOOST_CHECK(!wallet.HaveSaplingIncomingViewingKey(dpa2)); BOOST_CHECK(wallet.LoadSaplingPaymentAddress(dpa2, ivk2)); BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(dpa2)); } /** * This test covers methods on CWalletDB to load/save crypted sapling z keys. */ BOOST_AUTO_TEST_CASE(WriteCryptedSaplingZkeyDirectToDb) { SelectParams(CBaseChainParams::TESTNET); BOOST_CHECK(!pwalletMain->HasSaplingSPKM()); assert(pwalletMain->SetupSPKM(true)); // wallet should be empty std::set<libzcash::SaplingPaymentAddress> addrs; pwalletMain->GetSaplingPaymentAddresses(addrs); BOOST_CHECK_EQUAL(0, addrs.size()); // Add random key to the wallet auto address = pwalletMain->GenerateNewSaplingZKey(); // wallet should have one key pwalletMain->GetSaplingPaymentAddresses(addrs); BOOST_CHECK_EQUAL(1, addrs.size()); // encrypt wallet SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = "hello"; BOOST_CHECK(pwalletMain->EncryptWallet(strWalletPass)); // adding a new key will fail as the wallet is locked BOOST_CHECK_THROW(pwalletMain->GenerateNewSaplingZKey(), std::runtime_error); // unlock wallet and then add pwalletMain->Unlock(strWalletPass); libzcash::SaplingPaymentAddress address2 = pwalletMain->GenerateNewSaplingZKey(); // Create a new wallet from the existing wallet path bool fFirstRun; CWallet wallet2(pwalletMain->strWalletFile); BOOST_CHECK_EQUAL(DB_LOAD_OK, wallet2.LoadWallet(fFirstRun)); // Confirm it's not the same as the other wallet BOOST_CHECK(pwalletMain != &wallet2); BOOST_CHECK(wallet2.HasSaplingSPKM()); // wallet should have two keys wallet2.GetSaplingPaymentAddresses(addrs); BOOST_CHECK_EQUAL(2, addrs.size()); //check we have entries for our payment addresses BOOST_CHECK(addrs.count(address)); BOOST_CHECK(addrs.count(address2)); // spending key is crypted, so we can't extract valid payment address libzcash::SaplingExtendedSpendingKey keyOut; BOOST_CHECK(!wallet2.GetSaplingExtendedSpendingKey(address, keyOut)); // unlock wallet to get spending keys and verify payment addresses wallet2.Unlock(strWalletPass); BOOST_CHECK(wallet2.GetSaplingExtendedSpendingKey(address, keyOut)); BOOST_CHECK(address == keyOut.DefaultAddress()); BOOST_CHECK(wallet2.GetSaplingExtendedSpendingKey(address2, keyOut)); BOOST_CHECK(address2 == keyOut.DefaultAddress()); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Test: print error if shield diversified address is equal to the default address.<commit_after>// Copyright (c) 2016-2020 The ZCash developers // Copyright (c) 2020 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet/test/wallet_test_fixture.h" #include "sapling/sapling_util.h" #include "sapling/address.h" #include "wallet/wallet.h" #include "wallet/walletdb.h" #include "util.h" #include <boost/test/unit_test.hpp> /** * This test covers methods on CWallet * GenerateNewZKey() * AddZKey() * LoadZKey() * LoadZKeyMetadata() */ BOOST_FIXTURE_TEST_SUITE(wallet_zkeys_tests, WalletTestingSetup) /** * This test covers Sapling methods on CWallet * GenerateNewSaplingZKey() * AddSaplingZKey() * LoadSaplingZKey() * LoadSaplingZKeyMetadata() */ BOOST_AUTO_TEST_CASE(StoreAndLoadSaplingZkeys) { SelectParams(CBaseChainParams::MAIN); CWallet wallet; LOCK(wallet.cs_wallet); // wallet should be empty std::set<libzcash::SaplingPaymentAddress> addrs; wallet.GetSaplingPaymentAddresses(addrs); BOOST_CHECK_EQUAL(0, addrs.size()); // No HD seed in the wallet BOOST_CHECK_THROW(wallet.GenerateNewSaplingZKey(), std::runtime_error); // Random seed CKey seed; seed.MakeNewKey(true); wallet.AddKeyPubKey(seed, seed.GetPubKey()); wallet.GetSaplingScriptPubKeyMan()->SetHDSeed(seed.GetPubKey(), false, true); // wallet should have one key auto address = wallet.GenerateNewSaplingZKey(); wallet.GetSaplingPaymentAddresses(addrs); BOOST_CHECK_EQUAL(1, addrs.size()); // verify wallet has incoming viewing key for the address BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(address)); // manually add new spending key to wallet HDSeed seed1(seed.GetPrivKey()); auto m = libzcash::SaplingExtendedSpendingKey::Master(seed1); auto sk = m.Derive(0); BOOST_CHECK(wallet.AddSaplingZKey(sk)); // verify wallet did add it auto extfvk = sk.ToXFVK(); BOOST_CHECK(wallet.HaveSaplingSpendingKey(extfvk)); // verify spending key stored correctly libzcash::SaplingExtendedSpendingKey keyOut; wallet.GetSaplingSpendingKey(extfvk, keyOut); BOOST_CHECK(sk == keyOut); // verify there are two keys wallet.GetSaplingPaymentAddresses(addrs); BOOST_CHECK_EQUAL(2, addrs.size()); BOOST_CHECK_EQUAL(1, addrs.count(address)); BOOST_CHECK_EQUAL(1, addrs.count(sk.DefaultAddress())); // Generate a diversified address different to the default // If we can't get an early diversified address, we are very unlucky blob88 diversifier; diversifier.begin()[0] = 10; auto dpa = sk.ToXFVK().Address(diversifier).get().second; // verify wallet only has the default address libzcash::SaplingPaymentAddress defaultAddr = sk.DefaultAddress(); BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(defaultAddr)); BOOST_CHECK_MESSAGE(!(dpa == defaultAddr), "ERROR: default address is equal to diversified address"); BOOST_CHECK(!wallet.HaveSaplingIncomingViewingKey(dpa)); // manually add a diversified address auto ivk = extfvk.fvk.in_viewing_key(); BOOST_CHECK(wallet.AddSaplingIncomingViewingKeyW(ivk, dpa)); // verify wallet did add it BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(sk.DefaultAddress())); BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(dpa)); // Load a third key into the wallet auto sk2 = m.Derive(1); BOOST_CHECK(wallet.LoadSaplingZKey(sk2)); // attach metadata to this third key auto ivk2 = sk2.expsk.full_viewing_key().in_viewing_key(); int64_t now = GetTime(); CKeyMetadata meta(now); BOOST_CHECK(wallet.LoadSaplingZKeyMetadata(ivk2, meta)); // check metadata is the same BOOST_CHECK_EQUAL(wallet.GetSaplingScriptPubKeyMan()->mapSaplingZKeyMetadata[ivk2].nCreateTime, now); // Load a diversified address for the third key into the wallet auto dpa2 = sk2.ToXFVK().Address(diversifier).get().second; BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(sk2.DefaultAddress())); BOOST_CHECK(!wallet.HaveSaplingIncomingViewingKey(dpa2)); BOOST_CHECK(wallet.LoadSaplingPaymentAddress(dpa2, ivk2)); BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(dpa2)); } /** * This test covers methods on CWalletDB to load/save crypted sapling z keys. */ BOOST_AUTO_TEST_CASE(WriteCryptedSaplingZkeyDirectToDb) { SelectParams(CBaseChainParams::TESTNET); BOOST_CHECK(!pwalletMain->HasSaplingSPKM()); assert(pwalletMain->SetupSPKM(true)); // wallet should be empty std::set<libzcash::SaplingPaymentAddress> addrs; pwalletMain->GetSaplingPaymentAddresses(addrs); BOOST_CHECK_EQUAL(0, addrs.size()); // Add random key to the wallet auto address = pwalletMain->GenerateNewSaplingZKey(); // wallet should have one key pwalletMain->GetSaplingPaymentAddresses(addrs); BOOST_CHECK_EQUAL(1, addrs.size()); // encrypt wallet SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = "hello"; BOOST_CHECK(pwalletMain->EncryptWallet(strWalletPass)); // adding a new key will fail as the wallet is locked BOOST_CHECK_THROW(pwalletMain->GenerateNewSaplingZKey(), std::runtime_error); // unlock wallet and then add pwalletMain->Unlock(strWalletPass); libzcash::SaplingPaymentAddress address2 = pwalletMain->GenerateNewSaplingZKey(); // Create a new wallet from the existing wallet path bool fFirstRun; CWallet wallet2(pwalletMain->strWalletFile); BOOST_CHECK_EQUAL(DB_LOAD_OK, wallet2.LoadWallet(fFirstRun)); // Confirm it's not the same as the other wallet BOOST_CHECK(pwalletMain != &wallet2); BOOST_CHECK(wallet2.HasSaplingSPKM()); // wallet should have two keys wallet2.GetSaplingPaymentAddresses(addrs); BOOST_CHECK_EQUAL(2, addrs.size()); //check we have entries for our payment addresses BOOST_CHECK(addrs.count(address)); BOOST_CHECK(addrs.count(address2)); // spending key is crypted, so we can't extract valid payment address libzcash::SaplingExtendedSpendingKey keyOut; BOOST_CHECK(!wallet2.GetSaplingExtendedSpendingKey(address, keyOut)); // unlock wallet to get spending keys and verify payment addresses wallet2.Unlock(strWalletPass); BOOST_CHECK(wallet2.GetSaplingExtendedSpendingKey(address, keyOut)); BOOST_CHECK(address == keyOut.DefaultAddress()); BOOST_CHECK(wallet2.GetSaplingExtendedSpendingKey(address2, keyOut)); BOOST_CHECK(address2 == keyOut.DefaultAddress()); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ucbserv.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: sb $ $Date: 2000-12-04 17:36:40 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _UCB_HXX #include "ucb.hxx" #endif #ifndef _UCBCFG_HXX #include "ucbcfg.hxx" #endif #ifndef _UCBSTORE_HXX #include "ucbstore.hxx" #endif #ifndef _UCBPROPS_HXX #include "ucbprops.hxx" #endif #ifndef _PROVPROX_HXX #include "provprox.hxx" #endif using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::registry; //========================================================================= static sal_Bool writeInfo( void * pRegistryKey, const OUString & rImplementationName, Sequence< OUString > const & rServiceNames ) { OUString aKeyName( OUString::createFromAscii( "/" ) ); aKeyName += rImplementationName; aKeyName += OUString::createFromAscii( "/UNO/SERVICES" ); Reference< XRegistryKey > xKey; try { xKey = static_cast< XRegistryKey * >( pRegistryKey )->createKey( aKeyName ); } catch ( InvalidRegistryException const & ) { } if ( !xKey.is() ) return sal_False; sal_Bool bSuccess = sal_True; for ( sal_Int32 n = 0; n < rServiceNames.getLength(); ++n ) { try { xKey->createKey( rServiceNames[ n ] ); } catch ( InvalidRegistryException const & ) { bSuccess = sal_False; break; } } return bSuccess; } //========================================================================= extern "C" void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } //========================================================================= extern "C" sal_Bool SAL_CALL component_writeInfo( void * pServiceManager, void * pRegistryKey ) { return pRegistryKey && ////////////////////////////////////////////////////////////////////// // Universal Content Broker. ////////////////////////////////////////////////////////////////////// writeInfo( pRegistryKey, UniversalContentBroker::getImplementationName_Static(), UniversalContentBroker::getSupportedServiceNames_Static() ) && ////////////////////////////////////////////////////////////////////// // UCB Configuration. ////////////////////////////////////////////////////////////////////// writeInfo( pRegistryKey, UcbConfigurationManager::getImplementationName_Static(), UcbConfigurationManager::getSupportedServiceNames_Static() ) && ////////////////////////////////////////////////////////////////////// // UCB Store. ////////////////////////////////////////////////////////////////////// writeInfo( pRegistryKey, UcbStore::getImplementationName_Static(), UcbStore::getSupportedServiceNames_Static() ) && ////////////////////////////////////////////////////////////////////// // UCB PropertiesManager. ////////////////////////////////////////////////////////////////////// writeInfo( pRegistryKey, UcbPropertiesManager::getImplementationName_Static(), UcbPropertiesManager::getSupportedServiceNames_Static() ) && ////////////////////////////////////////////////////////////////////// // UCP Proxy Factory. ////////////////////////////////////////////////////////////////////// writeInfo( pRegistryKey, UcbContentProviderProxyFactory::getImplementationName_Static(), UcbContentProviderProxyFactory::getSupportedServiceNames_Static() ); } //========================================================================= extern "C" void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey ) { void * pRet = 0; Reference< XMultiServiceFactory > xSMgr( reinterpret_cast< XMultiServiceFactory * >( pServiceManager ) ); Reference< XSingleServiceFactory > xFactory; ////////////////////////////////////////////////////////////////////// // Universal Content Broker. ////////////////////////////////////////////////////////////////////// if ( UniversalContentBroker::getImplementationName_Static(). compareToAscii( pImplName ) == 0 ) { xFactory = UniversalContentBroker::createServiceFactory( xSMgr ); } ////////////////////////////////////////////////////////////////////// // UCB Configuration. ////////////////////////////////////////////////////////////////////// else if ( UcbConfigurationManager::getImplementationName_Static(). compareToAscii( pImplName ) == 0 ) { xFactory = UcbConfigurationManager::createServiceFactory( xSMgr ); } ////////////////////////////////////////////////////////////////////// // UCB Store. ////////////////////////////////////////////////////////////////////// else if ( UcbStore::getImplementationName_Static(). compareToAscii( pImplName ) == 0 ) { xFactory = UcbStore::createServiceFactory( xSMgr ); } ////////////////////////////////////////////////////////////////////// // UCB PropertiesManager. ////////////////////////////////////////////////////////////////////// else if ( UcbPropertiesManager::getImplementationName_Static(). compareToAscii( pImplName ) == 0 ) { xFactory = UcbPropertiesManager::createServiceFactory( xSMgr ); } ////////////////////////////////////////////////////////////////////// // UCP Proxy Factory. ////////////////////////////////////////////////////////////////////// else if ( UcbContentProviderProxyFactory::getImplementationName_Static(). compareToAscii( pImplName ) == 0 ) { xFactory = UcbContentProviderProxyFactory::createServiceFactory( xSMgr ); } ////////////////////////////////////////////////////////////////////// if ( xFactory.is() ) { xFactory->acquire(); pRet = xFactory.get(); } return pRet; } <commit_msg>#83541# - Removed UCB configuration service.<commit_after>/************************************************************************* * * $RCSfile: ucbserv.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kso $ $Date: 2001-02-06 10:55:37 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _UCB_HXX #include "ucb.hxx" #endif #ifndef _UCBSTORE_HXX #include "ucbstore.hxx" #endif #ifndef _UCBPROPS_HXX #include "ucbprops.hxx" #endif #ifndef _PROVPROX_HXX #include "provprox.hxx" #endif using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::registry; //========================================================================= static sal_Bool writeInfo( void * pRegistryKey, const OUString & rImplementationName, Sequence< OUString > const & rServiceNames ) { OUString aKeyName( OUString::createFromAscii( "/" ) ); aKeyName += rImplementationName; aKeyName += OUString::createFromAscii( "/UNO/SERVICES" ); Reference< XRegistryKey > xKey; try { xKey = static_cast< XRegistryKey * >( pRegistryKey )->createKey( aKeyName ); } catch ( InvalidRegistryException const & ) { } if ( !xKey.is() ) return sal_False; sal_Bool bSuccess = sal_True; for ( sal_Int32 n = 0; n < rServiceNames.getLength(); ++n ) { try { xKey->createKey( rServiceNames[ n ] ); } catch ( InvalidRegistryException const & ) { bSuccess = sal_False; break; } } return bSuccess; } //========================================================================= extern "C" void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } //========================================================================= extern "C" sal_Bool SAL_CALL component_writeInfo( void * pServiceManager, void * pRegistryKey ) { return pRegistryKey && ////////////////////////////////////////////////////////////////////// // Universal Content Broker. ////////////////////////////////////////////////////////////////////// writeInfo( pRegistryKey, UniversalContentBroker::getImplementationName_Static(), UniversalContentBroker::getSupportedServiceNames_Static() ) && ////////////////////////////////////////////////////////////////////// // UCB Store. ////////////////////////////////////////////////////////////////////// writeInfo( pRegistryKey, UcbStore::getImplementationName_Static(), UcbStore::getSupportedServiceNames_Static() ) && ////////////////////////////////////////////////////////////////////// // UCB PropertiesManager. ////////////////////////////////////////////////////////////////////// writeInfo( pRegistryKey, UcbPropertiesManager::getImplementationName_Static(), UcbPropertiesManager::getSupportedServiceNames_Static() ) && ////////////////////////////////////////////////////////////////////// // UCP Proxy Factory. ////////////////////////////////////////////////////////////////////// writeInfo( pRegistryKey, UcbContentProviderProxyFactory::getImplementationName_Static(), UcbContentProviderProxyFactory::getSupportedServiceNames_Static() ); } //========================================================================= extern "C" void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey ) { void * pRet = 0; Reference< XMultiServiceFactory > xSMgr( reinterpret_cast< XMultiServiceFactory * >( pServiceManager ) ); Reference< XSingleServiceFactory > xFactory; ////////////////////////////////////////////////////////////////////// // Universal Content Broker. ////////////////////////////////////////////////////////////////////// if ( UniversalContentBroker::getImplementationName_Static(). compareToAscii( pImplName ) == 0 ) { xFactory = UniversalContentBroker::createServiceFactory( xSMgr ); } ////////////////////////////////////////////////////////////////////// // UCB Store. ////////////////////////////////////////////////////////////////////// else if ( UcbStore::getImplementationName_Static(). compareToAscii( pImplName ) == 0 ) { xFactory = UcbStore::createServiceFactory( xSMgr ); } ////////////////////////////////////////////////////////////////////// // UCB PropertiesManager. ////////////////////////////////////////////////////////////////////// else if ( UcbPropertiesManager::getImplementationName_Static(). compareToAscii( pImplName ) == 0 ) { xFactory = UcbPropertiesManager::createServiceFactory( xSMgr ); } ////////////////////////////////////////////////////////////////////// // UCP Proxy Factory. ////////////////////////////////////////////////////////////////////// else if ( UcbContentProviderProxyFactory::getImplementationName_Static(). compareToAscii( pImplName ) == 0 ) { xFactory = UcbContentProviderProxyFactory::createServiceFactory( xSMgr ); } ////////////////////////////////////////////////////////////////////// if ( xFactory.is() ) { xFactory->acquire(); pRet = xFactory.get(); } return pRet; } <|endoftext|>
<commit_before>/*! * \author David * \date 29-Apr-16. */ #include <algorithm> #include <cmath> #include <easylogging++.h> #include "texture_manager.h" #include "../../vulkan/render_context.h" #include "../../../mc_interface/mc_objects.h" namespace nova { texture_manager::texture_manager(std::shared_ptr<render_context> context) : context(context) { LOG(INFO) << "Creating the Texture Manager"; reset(); LOG(INFO) << "Texture manager created"; } texture_manager::~texture_manager() { // gotta free up all the Vulkan textures reset(); } void texture_manager::reset() { if(!atlases.empty()) { // Nothing to deallocate, let's just return return; } for(auto& tex : atlases) { tex.second.destroy(); } atlases.clear(); locations.clear(); atlases["lightmap"] = texture2D(vk::Extent2D{16, 16}, vk::Format::eR8G8B8A8Unorm, context); atlases["lightmap"].set_name("lightmap"); LOG(INFO) << "Created lightmap"; clear_dynamic_textures(); } void texture_manager::add_texture(mc_atlas_texture &new_texture) { LOG(INFO) << "Adding texture " << new_texture.name << " (" << new_texture.width << "x" << new_texture.height << ")"; std::string texture_name = new_texture.name; LOG(TRACE) << "Saved texture name"; auto dimensions = vk::Extent2D{new_texture.width, new_texture.height}; texture2D texture{dimensions, vk::Format::eR8G8B8A8Unorm, context}; LOG(TRACE) << "Created texture object"; texture.set_name(texture_name); std::vector<uint8_t> pixel_data((std::size_t) (new_texture.width * new_texture.height * new_texture.num_components)); for(uint32_t i = 0; i < new_texture.width * new_texture.height * new_texture.num_components; i++) { pixel_data[i] = (uint8_t) new_texture.texture_data[i]; } LOG(TRACE) << "Added pixel data to buffer"; texture.set_data(pixel_data.data(), dimensions); LOG(TRACE) << "Sent texture data to GPU"; atlases[texture_name] = texture; LOG(DEBUG) << "Texture atlas " << texture_name << " is Vulkan texture " << texture.get_vk_image(); } void texture_manager::add_texture_location(mc_texture_atlas_location &location) { texture_location tex_loc = { { location.min_u, location.min_v }, { location.max_u, location.max_v } }; locations[location.name] = tex_loc; } const texture_manager::texture_location texture_manager::get_texture_location(const std::string &texture_name) { // If we haven't explicitly added a texture location for this texture, let's just assume that the texture isn't // in an atlas and thus covers the whole (0 - 1) UV space if(locations.find(texture_name) != locations.end()) { return locations[texture_name]; } else { return {{0, 0}, {1, 1}}; } } texture2D &texture_manager::get_texture(std::string texture_name) { if(atlases.find(texture_name) != atlases.end()) { return atlases.at(texture_name); } LOG(INFO) << "Checking if texture " << texture_name << " is in the dynamic textures. There's " << dynamic_tex_name_to_idx.size() << " dynamic textures, it should be one of them"; if(dynamic_tex_name_to_idx.find(texture_name) != dynamic_tex_name_to_idx.end()) { auto idx = dynamic_tex_name_to_idx.at(texture_name); if(dynamic_textures.size() > idx) { return dynamic_textures.at(idx); } } LOG(ERROR) << "Could not find texture " << texture_name; throw std::domain_error("Could not find texture " + texture_name); } int texture_manager::get_max_texture_size() { if(max_texture_size < 0) { max_texture_size = context->gpu.props.limits.maxImageDimension2D; LOG(DEBUG) << "max texturesize reported by gpu: " << max_texture_size; } return max_texture_size; } // Implementation based on RenderGraph::build_aliases from the Granite engine void texture_manager::create_dynamic_textures(const std::unordered_map<std::string, texture_resource> &textures, const std::vector<render_pass> &passes, std::shared_ptr<swapchain_manager> swapchain) { // For each texture in the passes, try to assign it to an existing resource // We'll basically create a list of which texture resources can be assigned to each physical resource // We want to alias textures. We can alias texture A and B if all reads from A finish before all writes to B AND // if A and B have the same format and dimension // Maybe we should make a list of things with the same format and dimension? clear_dynamic_textures(); struct range { uint32_t first_write_pass = ~0u; uint32_t last_write_pass = 0; uint32_t first_read_pass = ~0u; uint32_t last_read_pass = 0; bool has_writer() const { return first_write_pass <= last_write_pass; } bool has_reader() const { return first_read_pass <= last_read_pass; } bool is_used() const { return has_writer() || has_reader(); } bool can_alias() const { // If we read before we have completely written to a resource we need to preserve it, so no alias is possible. return !(has_reader() && has_writer() && first_read_pass <= first_write_pass); } unsigned last_used_pass() const { unsigned last_pass = 0; if (has_writer()) last_pass = std::max(last_pass, last_write_pass); if (has_reader()) last_pass = std::max(last_pass, last_read_pass); return last_pass; } unsigned first_used_pass() const { unsigned first_pass = ~0u; if (has_writer()) first_pass = std::min(first_pass, first_write_pass); if (has_reader()) first_pass = std::min(first_pass, first_read_pass); return first_pass; } bool is_disjoint_with(const range& other) const { if (!is_used() || !other.is_used()) return false; if (!can_alias() || !other.can_alias()) return false; bool left = last_used_pass() < other.first_used_pass(); bool right = other.last_used_pass() < first_used_pass(); return left || right; } }; // Look at what range of render passes each resource is used in std::unordered_map<std::string, range> resource_used_range; std::vector<std::string> resources_in_order; uint32_t pass_idx = 0; for(const auto& pass : passes) { if(pass.texture_inputs) { for(const auto &input : pass.texture_inputs.value()) { auto& tex_range = resource_used_range[input]; if(pass_idx < tex_range.first_write_pass) { tex_range.first_write_pass = pass_idx; } else if(pass_idx > tex_range.last_write_pass) { tex_range.last_write_pass = pass_idx; } if(std::find(resources_in_order.begin(), resources_in_order.end(), input) == resources_in_order.end()) { resources_in_order.push_back(input); } } } if(pass.texture_outputs) { for(const auto &output : pass.texture_outputs.value()) { auto& tex_range = resource_used_range[output]; if(pass_idx < tex_range.first_write_pass) { tex_range.first_write_pass = pass_idx; } else if(pass_idx > tex_range.last_write_pass) { tex_range.last_write_pass = pass_idx; } if(std::find(resources_in_order.begin(), resources_in_order.end(), output) == resources_in_order.end()) { resources_in_order.push_back(output); } } } pass_idx++; } LOG(INFO) << "Ordered resources"; // Figure out which resources can be aliased std::unordered_map<std::string, std::string> aliases; for(size_t i = 0; i < resources_in_order.size(); i++) { const auto& to_alias_name = resources_in_order[i]; LOG(INFO) << "Determining if we can alias `" << to_alias_name << "`. Does it exist? " << (textures.find(to_alias_name) != textures.end()); const auto& to_alias_format = textures.at(to_alias_name).format; // Only try to alias with lower-indexed resources for(size_t j = 0; j < i; j++) { LOG(INFO) << "Trying to alias it with rexource at index " << j << " out of " << resources_in_order.size(); const auto& try_alias_name = resources_in_order[j]; if(resource_used_range[to_alias_name].is_disjoint_with(resource_used_range[try_alias_name])) { // They can be aliased if they have the same format const auto& try_alias_format = textures.at(try_alias_name).format; if(to_alias_format == try_alias_format) { aliases[to_alias_name] = try_alias_name; } } } } LOG(INFO) << "Figured out which resources can be aliased"; auto swapchain_dimensions = swapchain->get_swapchain_extent(); // For each texture: // - If it isn't in the aliases map, create a new texture with its format and add it to the textures map // - If it is in the aliases map, follow its chain of aliases for(const auto& named_texture : textures) { std::string texture_name = named_texture.first; while(aliases.find(texture_name) != aliases.end()) { LOG(INFO) << "Resource " << texture_name << " is aliased with " << aliases[texture_name]; texture_name = aliases[texture_name]; } // We've found the first texture in this alias chain - let's create an actual texture for it if needed if(dynamic_tex_name_to_idx.find(texture_name) == dynamic_tex_name_to_idx.end()) { LOG(INFO) << "Need to create it"; // The texture we're all aliasing doesn't have a real texture yet. Let's fix that const texture_format& format = textures.at(texture_name).format; vk::Extent2D dimensions; if(format.dimension_type == texture_dimension_type_enum::Absolute) { dimensions = vk::Extent2D{static_cast<uint32_t>(format.width), static_cast<uint32_t>(format.height)}; } else { dimensions = swapchain_dimensions; dimensions.width *= format.width; dimensions.height *= format.height; } auto pixel_format = get_vk_format_from_pixel_format(format.pixel_format); auto tex = texture2D{dimensions, pixel_format, context}; auto new_tex_index = dynamic_textures.size(); dynamic_textures.push_back(tex); dynamic_tex_name_to_idx[texture_name] = new_tex_index; //dynamic_tex_name_to_idx[named_texture.first] = new_tex_index; LOG(INFO) << "Added texture " << tex.get_name() << " to the dynamic textures"; LOG(INFO) << "set dynamic_texture_to_idx[" << texture_name << "] = " << new_tex_index; //LOG(INFO) << "dynamic_texture_to_idx[" << named_texture.first << "] = " << new_tex_index; } else { LOG(INFO) << "The physical resource already exists, so we're just gonna use that"; // The texture we're aliasing already has a real texture behind it - so let's use that dynamic_tex_name_to_idx[named_texture.first] = dynamic_tex_name_to_idx[texture_name]; } } } void texture_manager::clear_dynamic_textures() { LOG(INFO) << "Cleared dynamic textures"; dynamic_textures.resize(0); dynamic_tex_name_to_idx.erase(dynamic_tex_name_to_idx.begin(), dynamic_tex_name_to_idx.end()); } bool texture_manager::is_texture_known(const std::string &texture_name) const { if(atlases.find(texture_name) != atlases.end()) { return true; } return dynamic_tex_name_to_idx.find(texture_name) != dynamic_tex_name_to_idx.end(); } vk::Format get_vk_format_from_pixel_format(pixel_format_enum format) { switch(format) { case pixel_format_enum::RGB8: return vk::Format::eR8G8B8Unorm; case pixel_format_enum::RGBA8: return vk::Format::eR8G8B8A8Unorm; case pixel_format_enum::RGB16F: return vk::Format::eR16G16B16Sfloat; case pixel_format_enum::RGBA16F: return vk::Format::eR16G16B16A16Sfloat; case pixel_format_enum::RGB32F: return vk::Format::eR32G32B32Sfloat; case pixel_format_enum::RGBA32F: return vk::Format::eR32G32B32A32Sfloat; case pixel_format_enum::Depth: return vk::Format::eD32Sfloat; case pixel_format_enum::DepthStencil: return vk::Format::eD24UnormS8Uint; default: LOG(WARNING) << "Could not determine Vulkan format for pixel format " << pixel_format_enum::to_string(format); return vk::Format::eR8G8B8Unorm; } } } <commit_msg>No more flickering or bad spelling<commit_after>/*! * \author David * \date 29-Apr-16. */ #include <algorithm> #include <cmath> #include <easylogging++.h> #include "texture_manager.h" #include "../../vulkan/render_context.h" #include "../../../mc_interface/mc_objects.h" namespace nova { texture_manager::texture_manager(std::shared_ptr<render_context> context) : context(context) { LOG(INFO) << "Creating the Texture Manager"; reset(); LOG(INFO) << "Texture manager created"; } texture_manager::~texture_manager() { // gotta free up all the Vulkan textures reset(); } void texture_manager::reset() { if(!atlases.empty()) { // Nothing to deallocate, let's just return return; } for(auto& tex : atlases) { tex.second.destroy(); } atlases.clear(); locations.clear(); atlases["lightmap"] = texture2D(vk::Extent2D{16, 16}, vk::Format::eR8G8B8A8Unorm, context); atlases["lightmap"].set_name("lightmap"); LOG(INFO) << "Created lightmap"; clear_dynamic_textures(); } void texture_manager::add_texture(mc_atlas_texture &new_texture) { LOG(INFO) << "Adding texture " << new_texture.name << " (" << new_texture.width << "x" << new_texture.height << ")"; std::string texture_name = new_texture.name; LOG(TRACE) << "Saved texture name"; auto dimensions = vk::Extent2D{new_texture.width, new_texture.height}; texture2D texture{dimensions, vk::Format::eR8G8B8A8Unorm, context}; LOG(TRACE) << "Created texture object"; texture.set_name(texture_name); std::vector<uint8_t> pixel_data((std::size_t) (new_texture.width * new_texture.height * new_texture.num_components)); for(uint32_t i = 0; i < new_texture.width * new_texture.height * new_texture.num_components; i++) { pixel_data[i] = (uint8_t) new_texture.texture_data[i]; } LOG(TRACE) << "Added pixel data to buffer"; texture.set_data(pixel_data.data(), dimensions); LOG(TRACE) << "Sent texture data to GPU"; atlases[texture_name] = texture; LOG(DEBUG) << "Texture atlas " << texture_name << " is Vulkan texture " << texture.get_vk_image(); } void texture_manager::add_texture_location(mc_texture_atlas_location &location) { texture_location tex_loc = { { location.min_u, location.min_v }, { location.max_u, location.max_v } }; locations[location.name] = tex_loc; } const texture_manager::texture_location texture_manager::get_texture_location(const std::string &texture_name) { // If we haven't explicitly added a texture location for this texture, let's just assume that the texture isn't // in an atlas and thus covers the whole (0 - 1) UV space if(locations.find(texture_name) != locations.end()) { return locations[texture_name]; } else { return {{0, 0}, {1, 1}}; } } texture2D &texture_manager::get_texture(std::string texture_name) { if(atlases.find(texture_name) != atlases.end()) { return atlases.at(texture_name); } LOG(INFO) << "Checking if texture " << texture_name << " is in the dynamic textures. There's " << dynamic_tex_name_to_idx.size() << " dynamic textures, it should be one of them"; if(dynamic_tex_name_to_idx.find(texture_name) != dynamic_tex_name_to_idx.end()) { auto idx = dynamic_tex_name_to_idx.at(texture_name); if(dynamic_textures.size() > idx) { return dynamic_textures.at(idx); } } LOG(ERROR) << "Could not find texture " << texture_name; throw std::domain_error("Could not find texture " + texture_name); } int texture_manager::get_max_texture_size() { if(max_texture_size < 0) { max_texture_size = context->gpu.props.limits.maxImageDimension2D; LOG(DEBUG) << "max texturesize reported by gpu: " << max_texture_size; } return max_texture_size; } // Implementation based on RenderGraph::build_aliases from the Granite engine void texture_manager::create_dynamic_textures(const std::unordered_map<std::string, texture_resource> &textures, const std::vector<render_pass> &passes, std::shared_ptr<swapchain_manager> swapchain) { // For each texture in the passes, try to assign it to an existing resource // We'll basically create a list of which texture resources can be assigned to each physical resource // We want to alias textures. We can alias texture A and B if all reads from A finish before all writes to B AND // if A and B have the same format and dimension // Maybe we should make a list of things with the same format and dimension? clear_dynamic_textures(); struct range { uint32_t first_write_pass = ~0u; uint32_t last_write_pass = 0; uint32_t first_read_pass = ~0u; uint32_t last_read_pass = 0; bool has_writer() const { return first_write_pass <= last_write_pass; } bool has_reader() const { return first_read_pass <= last_read_pass; } bool is_used() const { return has_writer() || has_reader(); } bool can_alias() const { // If we read before we have completely written to a resource we need to preserve it, so no alias is possible. return !(has_reader() && has_writer() && first_read_pass <= first_write_pass); } unsigned last_used_pass() const { unsigned last_pass = 0; if (has_writer()) last_pass = std::max(last_pass, last_write_pass); if (has_reader()) last_pass = std::max(last_pass, last_read_pass); return last_pass; } unsigned first_used_pass() const { unsigned first_pass = ~0u; if (has_writer()) first_pass = std::min(first_pass, first_write_pass); if (has_reader()) first_pass = std::min(first_pass, first_read_pass); return first_pass; } bool is_disjoint_with(const range& other) const { if (!is_used() || !other.is_used()) return false; if (!can_alias() || !other.can_alias()) return false; bool left = last_used_pass() < other.first_used_pass(); bool right = other.last_used_pass() < first_used_pass(); return left || right; } }; // Look at what range of render passes each resource is used in std::unordered_map<std::string, range> resource_used_range; std::vector<std::string> resources_in_order; uint32_t pass_idx = 0; for(const auto& pass : passes) { if(pass.texture_inputs) { for(const auto &input : pass.texture_inputs.value()) { auto& tex_range = resource_used_range[input]; if(pass_idx < tex_range.first_write_pass) { tex_range.first_write_pass = pass_idx; } else if(pass_idx > tex_range.last_write_pass) { tex_range.last_write_pass = pass_idx; } if(std::find(resources_in_order.begin(), resources_in_order.end(), input) == resources_in_order.end()) { resources_in_order.push_back(input); } } } if(pass.texture_outputs) { for(const auto &output : pass.texture_outputs.value()) { auto& tex_range = resource_used_range[output]; if(pass_idx < tex_range.first_write_pass) { tex_range.first_write_pass = pass_idx; } else if(pass_idx > tex_range.last_write_pass) { tex_range.last_write_pass = pass_idx; } if(std::find(resources_in_order.begin(), resources_in_order.end(), output) == resources_in_order.end()) { resources_in_order.push_back(output); } } } pass_idx++; } LOG(INFO) << "Ordered resources"; // Figure out which resources can be aliased std::unordered_map<std::string, std::string> aliases; for(size_t i = 0; i < resources_in_order.size(); i++) { const auto& to_alias_name = resources_in_order[i]; LOG(INFO) << "Determining if we can alias `" << to_alias_name << "`. Does it exist? " << (textures.find(to_alias_name) != textures.end()); const auto& to_alias_format = textures.at(to_alias_name).format; // Only try to alias with lower-indexed resources for(size_t j = 0; j < i; j++) { LOG(INFO) << "Trying to alias it with rexource at index " << j << " out of " << resources_in_order.size(); const auto& try_alias_name = resources_in_order[j]; if(resource_used_range[to_alias_name].is_disjoint_with(resource_used_range[try_alias_name])) { // They can be aliased if they have the same format const auto& try_alias_format = textures.at(try_alias_name).format; if(to_alias_format == try_alias_format) { aliases[to_alias_name] = try_alias_name; } } } } LOG(INFO) << "Figured out which resources can be aliased"; auto swapchain_dimensions = swapchain->get_swapchain_extent(); // For each texture: // - If it isn't in the aliases map, create a new texture with its format and add it to the textures map // - If it is in the aliases map, follow its chain of aliases for(const auto& named_texture : textures) { std::string texture_name = named_texture.first; while(aliases.find(texture_name) != aliases.end()) { LOG(INFO) << "Resource " << texture_name << " is aliased with " << aliases[texture_name]; texture_name = aliases[texture_name]; } // We've found the first texture in this alias chain - let's create an actual texture for it if needed if(dynamic_tex_name_to_idx.find(texture_name) == dynamic_tex_name_to_idx.end()) { LOG(INFO) << "Need to create it"; // The texture we're all aliasing doesn't have a real texture yet. Let's fix that const texture_format& format = textures.at(texture_name).format; vk::Extent2D dimensions; if(format.dimension_type == texture_dimension_type_enum::Absolute) { dimensions = vk::Extent2D{static_cast<uint32_t>(format.width), static_cast<uint32_t>(format.height)}; } else { dimensions = swapchain_dimensions; dimensions.width *= format.width; dimensions.height *= format.height; } auto pixel_format = get_vk_format_from_pixel_format(format.pixel_format); auto tex = texture2D{dimensions, pixel_format, context}; auto new_tex_index = dynamic_textures.size(); dynamic_textures.push_back(tex); dynamic_tex_name_to_idx[texture_name] = new_tex_index; //dynamic_tex_name_to_idx[named_texture.first] = new_tex_index; LOG(INFO) << "Added texture " << tex.get_name() << " to the dynamic textures"; LOG(INFO) << "set dynamic_texture_to_idx[" << texture_name << "] = " << new_tex_index; //LOG(INFO) << "dynamic_texture_to_idx[" << named_texture.first << "] = " << new_tex_index; } else { LOG(INFO) << "The physical resource already exists, so we're just gonna use that"; // The texture we're aliasing already has a real texture behind it - so let's use that dynamic_tex_name_to_idx[named_texture.first] = dynamic_tex_name_to_idx[texture_name]; } } } void texture_manager::clear_dynamic_textures() { LOG(INFO) << "Cleared dynamic textures"; dynamic_textures.resize(0); dynamic_tex_name_to_idx.erase(dynamic_tex_name_to_idx.begin(), dynamic_tex_name_to_idx.end()); } bool texture_manager::is_texture_known(const std::string &texture_name) const { if(atlases.find(texture_name) != atlases.end()) { return true; } return dynamic_tex_name_to_idx.find(texture_name) != dynamic_tex_name_to_idx.end(); } vk::Format get_vk_format_from_pixel_format(pixel_format_enum format) { switch(format) { case pixel_format_enum::RGB8: return vk::Format::eR8G8B8Unorm; case pixel_format_enum::RGBA8: return vk::Format::eR8G8B8A8Unorm; case pixel_format_enum::RGB16F: return vk::Format::eR16G16B16Sfloat; case pixel_format_enum::RGBA16F: return vk::Format::eR16G16B16A16Sfloat; case pixel_format_enum::RGB32F: return vk::Format::eR32G32B32Sfloat; case pixel_format_enum::RGBA32F: return vk::Format::eR32G32B32A32Sfloat; case pixel_format_enum::Depth: return vk::Format::eD32Sfloat; case pixel_format_enum::DepthStencil: return vk::Format::eD24UnormS8Uint; default: LOG(WARNING) << "Could not determine Vulkan format for pixel format " << pixel_format_enum::to_string(format); return vk::Format::eR8G8B8Unorm; } } } <|endoftext|>
<commit_before>#include "include/udata.h" #include "include/amici_model.h" #include <cstdio> #include <cstring> UserData::UserData() { init(); } int UserData::unscaleParameters(const Model *model, double *bufferUnscaled) const { switch(pscale) { case AMICI_SCALING_LOG10: for(int ip = 0; ip < model->np; ++ip) { bufferUnscaled[ip] = pow(10, p[ip]); } break; case AMICI_SCALING_LN: for(int ip = 0; ip < model->np; ++ip) bufferUnscaled[ip] = exp(p[ip]); break; case AMICI_SCALING_NONE: break; } return AMICI_SUCCESS; } UserData::~UserData() { if(qpositivex) delete[] qpositivex; if(p) delete[] p; if(k) delete[] k; if(ts) delete[] ts; if(pbar) delete[] pbar; if(xbar) delete[] xbar; if(x0data) delete[] x0data; if(sx0data) delete[] sx0data; if(plist) delete[] plist; } void UserData::init() { qpositivex = NULL; plist = NULL; nplist = 0; nt = 0; p = NULL; k = NULL; ts = NULL; tstart = 0; pbar = NULL; xbar = NULL; sensi = AMICI_SENSI_ORDER_NONE; atol = 1e-16; rtol = 1e-8; maxsteps = 0; newton_maxsteps = 0; newton_maxlinsteps = 0; ism = 1; nmaxevent = 10; sensi_meth = AMICI_SENSI_FSA; linsol = 9; interpType = 1; lmm = 2; iter = 2; stldet = true; x0data = NULL; sx0data = NULL; ordering = 0; } void UserData::print() { printf("qpositivex: %p\n", qpositivex); printf("plist: %p\n", plist); printf("nplist: %d\n", nplist); printf("nt: %d\n", nt); printf("nmaxevent: %d\n", nmaxevent); printf("p: %p\n", p); printf("k: %p\n", k); printf("tstart: %e\n", tstart); printf("ts: %p\n", ts); printf("pbar: %p\n", pbar); printf("xbar: %p\n", xbar); printf("sensi: %d\n", sensi); printf("atol: %e\n", atol); printf("rtol: %e\n", rtol); printf("maxsteps: %d\n", maxsteps); printf("newton_maxsteps: %d\n", newton_maxsteps); printf("newton_maxlinsteps: %d\n", newton_maxlinsteps); printf("ism: %d\n", ism); printf("sensi_meth: %d\n", sensi_meth); printf("linsol: %d\n", linsol); printf("interpType: %d\n", interpType); printf("lmm: %d\n", lmm); printf("iter: %d\n", iter); printf("stldet: %d\n", stldet); printf("x0data: %p\n", x0data); printf("sx0data: %p\n", sx0data); printf("ordering: %d\n", ordering); } <commit_msg>Fix: parameters were not copied to TempData with AMICI_SCALING_NONE<commit_after>#include "include/udata.h" #include "include/amici_model.h" #include <cstdio> #include <cstring> UserData::UserData() { init(); } int UserData::unscaleParameters(const Model *model, double *bufferUnscaled) const { switch(pscale) { case AMICI_SCALING_LOG10: for(int ip = 0; ip < model->np; ++ip) { bufferUnscaled[ip] = pow(10, p[ip]); } break; case AMICI_SCALING_LN: for(int ip = 0; ip < model->np; ++ip) bufferUnscaled[ip] = exp(p[ip]); break; case AMICI_SCALING_NONE: for(int ip = 0; ip < model->np; ++ip) bufferUnscaled[ip] = p[ip]; break; } return AMICI_SUCCESS; } UserData::~UserData() { if(qpositivex) delete[] qpositivex; if(p) delete[] p; if(k) delete[] k; if(ts) delete[] ts; if(pbar) delete[] pbar; if(xbar) delete[] xbar; if(x0data) delete[] x0data; if(sx0data) delete[] sx0data; if(plist) delete[] plist; } void UserData::init() { qpositivex = NULL; plist = NULL; nplist = 0; nt = 0; p = NULL; k = NULL; ts = NULL; tstart = 0; pbar = NULL; xbar = NULL; sensi = AMICI_SENSI_ORDER_NONE; atol = 1e-16; rtol = 1e-8; maxsteps = 0; newton_maxsteps = 0; newton_maxlinsteps = 0; ism = 1; nmaxevent = 10; sensi_meth = AMICI_SENSI_FSA; linsol = 9; interpType = 1; lmm = 2; iter = 2; stldet = true; x0data = NULL; sx0data = NULL; ordering = 0; } void UserData::print() { printf("qpositivex: %p\n", qpositivex); printf("plist: %p\n", plist); printf("nplist: %d\n", nplist); printf("nt: %d\n", nt); printf("nmaxevent: %d\n", nmaxevent); printf("p: %p\n", p); printf("k: %p\n", k); printf("tstart: %e\n", tstart); printf("ts: %p\n", ts); printf("pbar: %p\n", pbar); printf("xbar: %p\n", xbar); printf("sensi: %d\n", sensi); printf("atol: %e\n", atol); printf("rtol: %e\n", rtol); printf("maxsteps: %d\n", maxsteps); printf("newton_maxsteps: %d\n", newton_maxsteps); printf("newton_maxlinsteps: %d\n", newton_maxlinsteps); printf("ism: %d\n", ism); printf("sensi_meth: %d\n", sensi_meth); printf("linsol: %d\n", linsol); printf("interpType: %d\n", interpType); printf("lmm: %d\n", lmm); printf("iter: %d\n", iter); printf("stldet: %d\n", stldet); printf("x0data: %p\n", x0data); printf("sx0data: %p\n", sx0data); printf("ordering: %d\n", ordering); } <|endoftext|>
<commit_before>/* * StochasticReleaseTestProbe.cpp * * Created on: Aug 28, 2013 * Author: pschultz */ #include "StochasticReleaseTestProbe.hpp" namespace PV { StochasticReleaseTestProbe::StochasticReleaseTestProbe(const char * name, HyPerCol * hc) { initialize_base(); initStochasticReleaseTestProbe(name, hc); } StochasticReleaseTestProbe::StochasticReleaseTestProbe() { initialize_base(); } int StochasticReleaseTestProbe::initialize_base() { conn = NULL; for (int k=0; k<8; k++) { bins[k] = 0; } sumbins = 0; binprobs[0] = 0.00023262907903552502; // erfc(3.5/sqrt(2))/2 binprobs[1] = 0.005977036246740614; // (erfc(2.5/sqrt(2))-erfc(3.5/sqrt(2)))/2 binprobs[2] = 0.06059753594308195; // (erfc(1.5/sqrt(2))-erfc(2.5/sqrt(2)))/2 binprobs[3] = 0.24173033745712885; // (erfc(0.5/sqrt(2))-erfc(1.5/sqrt(2)))/2 binprobs[4] = 0.3829249225480262; // erf(0.5/sqrt(2) binprobs[5] = 0.24173033745712885; // (erfc(0.5/sqrt(2))-erfc(1.5/sqrt(2)))/2 binprobs[6] = 0.06059753594308195; // (erfc(1.5/sqrt(2))-erfc(2.5/sqrt(2)))/2 binprobs[7] = 0.005977036246740614; // (erfc(2.5/sqrt(2))-erfc(3.5/sqrt(2)))/2 binprobs[8] = 0.00023262907903552502; // erfc(3.5/sqrt(2))/2 return PV_SUCCESS; } int StochasticReleaseTestProbe::initStochasticReleaseTestProbe(const char * name, HyPerCol * hc) { const char * classkeyword = hc->parameters()->groupKeywordFromName(name); HyPerLayer * targetlayer = NULL; char * message = NULL; const char * filename; getLayerFunctionProbeParameters(name, classkeyword, hc, &targetlayer, &message, &filename); int status = initStatsProbe(filename, targetlayer, BufActivity, message); const int numconns = hc->numberOfConnections(); for (int c=0; c<numconns; c++) { if (!strcmp(hc->getConnection(c)->getPostLayerName(),getTargetLayer()->getName())) { assert(conn==NULL); conn = hc->getConnection(c); } } assert(conn!=NULL); return PV_SUCCESS; } int StochasticReleaseTestProbe::outputState(double timed) { int status = StatsProbe::outputState(timed); assert(status==PV_SUCCESS); assert(conn->numberOfAxonalArborLists()==1); assert(conn->getNumDataPatches()==1); assert(conn->xPatchSize()==1); assert(conn->yPatchSize()==1); assert(conn->fPatchSize()==1); pvdata_t wgt = *conn->get_wDataStart(0); HyPerLayer * pre = conn->preSynapticLayer(); const pvdata_t * preactPtr = pre->getLayerData(); const PVLayerLoc * preLoc = pre->getLayerLoc(); const int numPreNeurons = pre->getNumNeurons(); bool found=false; pvdata_t preact = 0.0f; for (int n=0; n<numPreNeurons; n++) { int nExt = kIndexExtended(n, preLoc->nx, preLoc->ny, preLoc->nf, preLoc->nb); pvdata_t a = preactPtr[nExt]; if (a!=0.0f) { if (found) { assert(preact==a); } else { found = true; preact = a; } } } if (preact < 0.0f) preact = 0.0f; if (preact > 1.0f) preact = 1.0f; const int numNeurons = getTargetLayer()->getNumNeurons(); const PVLayerLoc * loc = getTargetLayer()->getLayerLoc(); const pvdata_t * activity = getTargetLayer()->getLayerData(); for (int n=0; n<numNeurons; n++) { int nExt = kIndexExtended(n, loc->nx, loc->ny, loc->nf, loc->nb); assert(activity[nExt]==0 || activity[nExt]==wgt); } double mean = preact * numNeurons; double stddev = sqrt(numNeurons*preact*(1-preact)); double numStdDevs = stddev==0.0 && mean==nnz ? 0.0 : (nnz-mean)/stddev; HyPerCol * hc = getTargetLayer()->getParent(); if (timed>0.0 && hc->columnId()==0) { fprintf(outputstream->fp, " t=%f, number of standard deviations = %f\n", timed, numStdDevs); int bin = numStdDevs < -3.5 ? 0 : numStdDevs < -2.5 ? 1 : numStdDevs < -1.5 ? 2 : numStdDevs < -0.5 ? 3 : numStdDevs <= 0.5 ? 4 : numStdDevs <= 1.5 ? 5 : numStdDevs <= 2.5 ? 6 : numStdDevs <= 3.5 ? 7 : 8; bins[bin]++; sumbins++; if (hc->simulationTime()+hc->getDeltaTime()>=hc->getStopTime()) { fprintf(outputstream->fp, " Histogram: "); for (int k=0; k<9; k++) { fprintf(outputstream->fp, " %7d", bins[k]); } fprintf(outputstream->fp, "\n"); int minallowed[9]; int maxallowed[9]; if (stddev==0) { for (int k=0; k<9; k++) { minallowed[k] = (k==4 ? sumbins : 0); maxallowed[k] = (k==4 ? sumbins : 0); assert(bins[k]==(k==4 ? sumbins : 0)); } } else { assert(preact<1.0f && preact>0.0f); for (int k=0; k<9; k++) { // find first m for which prob(bins[k]<m) >= 0.005 double p = binprobs[k]; double outcomeprob = pow(1-p,sumbins); double cumulativeprob = outcomeprob; double m=0; printf("m=%10.4f, outcomeprob=%.20f, cumulativeprob=%.20f\n", m, outcomeprob, cumulativeprob); while(cumulativeprob < 0.005 && m <= sumbins) { m++; outcomeprob *= (sumbins+1-m)/m*p/(1-p); cumulativeprob += outcomeprob; printf("m=%10.4f, outcomeprob=%.20f, cumulativeprob=%.20f\n", m, outcomeprob, cumulativeprob); } minallowed[k] = m; if (bins[k]<minallowed[k]) status = PV_FAILURE; // find first m for which prob(bins[k]<m) < 0.995 while(cumulativeprob <= 0.995 && sumbins) { m++; outcomeprob *= (sumbins+1-m)/m*p/(1-p); cumulativeprob += outcomeprob; printf("m=%10.4f, outcomeprob=%.20f, cumulativeprob=%.20f\n", m, outcomeprob, cumulativeprob); } maxallowed[k] = m; if (bins[k]>maxallowed[k]) status = PV_FAILURE; } fprintf(outputstream->fp, " Min allowed:"); for (int k=0; k<9; k++) { fprintf(outputstream->fp, " %7d", minallowed[k]); } fprintf(outputstream->fp, "\n"); fprintf(outputstream->fp, " Max allowed:"); for (int k=0; k<9; k++) { fprintf(outputstream->fp, " %7d", maxallowed[k]); } fprintf(outputstream->fp, "\n"); assert(status==PV_SUCCESS); } } } return status; } StochasticReleaseTestProbe::~StochasticReleaseTestProbe() { } } /* namespace PV */ <commit_msg>Fix a bug in StochasticReleaseTestProbe that confused getNumNeurons with getNumGlobalNeurons<commit_after>/* * StochasticReleaseTestProbe.cpp * * Created on: Aug 28, 2013 * Author: pschultz */ #include "StochasticReleaseTestProbe.hpp" namespace PV { StochasticReleaseTestProbe::StochasticReleaseTestProbe(const char * name, HyPerCol * hc) { initialize_base(); initStochasticReleaseTestProbe(name, hc); } StochasticReleaseTestProbe::StochasticReleaseTestProbe() { initialize_base(); } int StochasticReleaseTestProbe::initialize_base() { conn = NULL; for (int k=0; k<8; k++) { bins[k] = 0; } sumbins = 0; binprobs[0] = 0.00023262907903552502; // erfc(3.5/sqrt(2))/2 binprobs[1] = 0.005977036246740614; // (erfc(2.5/sqrt(2))-erfc(3.5/sqrt(2)))/2 binprobs[2] = 0.06059753594308195; // (erfc(1.5/sqrt(2))-erfc(2.5/sqrt(2)))/2 binprobs[3] = 0.24173033745712885; // (erfc(0.5/sqrt(2))-erfc(1.5/sqrt(2)))/2 binprobs[4] = 0.3829249225480262; // erf(0.5/sqrt(2) binprobs[5] = 0.24173033745712885; // (erfc(0.5/sqrt(2))-erfc(1.5/sqrt(2)))/2 binprobs[6] = 0.06059753594308195; // (erfc(1.5/sqrt(2))-erfc(2.5/sqrt(2)))/2 binprobs[7] = 0.005977036246740614; // (erfc(2.5/sqrt(2))-erfc(3.5/sqrt(2)))/2 binprobs[8] = 0.00023262907903552502; // erfc(3.5/sqrt(2))/2 return PV_SUCCESS; } int StochasticReleaseTestProbe::initStochasticReleaseTestProbe(const char * name, HyPerCol * hc) { const char * classkeyword = hc->parameters()->groupKeywordFromName(name); HyPerLayer * targetlayer = NULL; char * message = NULL; const char * filename; getLayerFunctionProbeParameters(name, classkeyword, hc, &targetlayer, &message, &filename); int status = initStatsProbe(filename, targetlayer, BufActivity, message); const int numconns = hc->numberOfConnections(); for (int c=0; c<numconns; c++) { if (!strcmp(hc->getConnection(c)->getPostLayerName(),getTargetLayer()->getName())) { assert(conn==NULL); conn = hc->getConnection(c); } } assert(conn!=NULL); return PV_SUCCESS; } int StochasticReleaseTestProbe::outputState(double timed) { int status = StatsProbe::outputState(timed); assert(status==PV_SUCCESS); assert(conn->numberOfAxonalArborLists()==1); assert(conn->getNumDataPatches()==1); assert(conn->xPatchSize()==1); assert(conn->yPatchSize()==1); assert(conn->fPatchSize()==1); pvdata_t wgt = *conn->get_wDataStart(0); HyPerLayer * pre = conn->preSynapticLayer(); const pvdata_t * preactPtr = pre->getLayerData(); const PVLayerLoc * preLoc = pre->getLayerLoc(); const int numPreNeurons = pre->getNumNeurons(); bool found=false; pvdata_t preact = 0.0f; for (int n=0; n<numPreNeurons; n++) { int nExt = kIndexExtended(n, preLoc->nx, preLoc->ny, preLoc->nf, preLoc->nb); pvdata_t a = preactPtr[nExt]; if (a!=0.0f) { if (found) { assert(preact==a); } else { found = true; preact = a; } } } if (preact < 0.0f) preact = 0.0f; if (preact > 1.0f) preact = 1.0f; const int numNeurons = getTargetLayer()->getNumNeurons(); const PVLayerLoc * loc = getTargetLayer()->getLayerLoc(); const pvdata_t * activity = getTargetLayer()->getLayerData(); for (int n=0; n<numNeurons; n++) { int nExt = kIndexExtended(n, loc->nx, loc->ny, loc->nf, loc->nb); assert(activity[nExt]==0 || activity[nExt]==wgt); } const int numGlobalNeurons = getTargetLayer()->getNumGlobalNeurons(); double mean = preact * numGlobalNeurons; double stddev = sqrt(numGlobalNeurons*preact*(1-preact)); double numStdDevs = stddev==0.0 && mean==nnz ? 0.0 : (nnz-mean)/stddev; HyPerCol * hc = getTargetLayer()->getParent(); if (timed>0.0 && hc->columnId()==0) { fprintf(outputstream->fp, " t=%f, number of standard deviations = %f\n", timed, numStdDevs); int bin = numStdDevs < -3.5 ? 0 : numStdDevs < -2.5 ? 1 : numStdDevs < -1.5 ? 2 : numStdDevs < -0.5 ? 3 : numStdDevs <= 0.5 ? 4 : numStdDevs <= 1.5 ? 5 : numStdDevs <= 2.5 ? 6 : numStdDevs <= 3.5 ? 7 : 8; bins[bin]++; sumbins++; if (hc->simulationTime()+hc->getDeltaTime()>=hc->getStopTime()) { fprintf(outputstream->fp, " Histogram: "); for (int k=0; k<9; k++) { fprintf(outputstream->fp, " %7d", bins[k]); } fprintf(outputstream->fp, "\n"); int minallowed[9]; int maxallowed[9]; if (stddev==0) { for (int k=0; k<9; k++) { minallowed[k] = (k==4 ? sumbins : 0); maxallowed[k] = (k==4 ? sumbins : 0); assert(bins[k]==(k==4 ? sumbins : 0)); } } else { assert(preact<1.0f && preact>0.0f); for (int k=0; k<9; k++) { // find first m for which prob(bins[k]<m) >= 0.005 double p = binprobs[k]; double outcomeprob = pow(1-p,sumbins); double cumulativeprob = outcomeprob; double m=0; printf("m=%10.4f, outcomeprob=%.20f, cumulativeprob=%.20f\n", m, outcomeprob, cumulativeprob); while(cumulativeprob < 0.005 && m <= sumbins) { m++; outcomeprob *= (sumbins+1-m)/m*p/(1-p); cumulativeprob += outcomeprob; printf("m=%10.4f, outcomeprob=%.20f, cumulativeprob=%.20f\n", m, outcomeprob, cumulativeprob); } minallowed[k] = m; if (bins[k]<minallowed[k]) status = PV_FAILURE; // find first m for which prob(bins[k]<m) < 0.995 while(cumulativeprob <= 0.995 && sumbins) { m++; outcomeprob *= (sumbins+1-m)/m*p/(1-p); cumulativeprob += outcomeprob; printf("m=%10.4f, outcomeprob=%.20f, cumulativeprob=%.20f\n", m, outcomeprob, cumulativeprob); } maxallowed[k] = m; if (bins[k]>maxallowed[k]) status = PV_FAILURE; } fprintf(outputstream->fp, " Min allowed:"); for (int k=0; k<9; k++) { fprintf(outputstream->fp, " %7d", minallowed[k]); } fprintf(outputstream->fp, "\n"); fprintf(outputstream->fp, " Max allowed:"); for (int k=0; k<9; k++) { fprintf(outputstream->fp, " %7d", maxallowed[k]); } fprintf(outputstream->fp, "\n"); assert(status==PV_SUCCESS); } } } return status; } StochasticReleaseTestProbe::~StochasticReleaseTestProbe() { } } /* namespace PV */ <|endoftext|>
<commit_before>#include "platform_macro.h" #if defined(TARGET_ARCH_X64) #include "InstructionRelocation/x64/X64InstructionRelocation.h" #include <string.h> #include "dobby_internal.h" #include "InstructionRelocation/x86/x86_insn_decode/x86_insn_decode.h" #include "core/arch/x64/registers-x64.h" #include "core/modules/assembler/assembler-x64.h" #include "core/modules/codegen/codegen-x64.h" using namespace zz::x64; static int GenRelocateCodeFixed(void *buffer, AssemblyCodeChunk *origin, AssemblyCodeChunk *relocated) { TurboAssembler turbo_assembler_(0); // Set fixed executable code chunk address turbo_assembler_.SetRealizedAddress((void *)relocated->raw_instruction_start()); #define _ turbo_assembler_. #define __ turbo_assembler_.GetCodeBuffer()-> addr64_t curr_orig_ip = origin->raw_instruction_start(); addr64_t curr_relo_ip = relocated->raw_instruction_start(); addr_t buffer_cursor = (addr_t)buffer; x86_options_t conf = {.mode = 64}; int predefined_relocate_size = origin->raw_instruction_size(); while ((buffer_cursor < ((addr_t)buffer + predefined_relocate_size))) { int last_relo_offset = turbo_assembler_.GetCodeBuffer()->getSize(); x86_insn_decode_t insn = {0}; memset(&insn, 0, sizeof(insn)); // decode x86 insn x86_insn_decode(&insn, (uint8_t *)buffer_cursor, &conf); if (insn.primary_opcode >= 0x70 && insn.primary_opcode <= 0x7F) { // jc rel8 DLOG(1, "[x86 relo] jc rel8, %p", buffer_cursor); int8_t orig_offset = insn.immediate; int new_offset = (int)(curr_orig_ip + orig_offset - curr_relo_ip); uint8_t opcode = 0x80 | (insn.primary_opcode & 0x0f); __ Emit8(0x0F); __ Emit8(opcode); __ Emit32(new_offset); } else if (insn.primary_opcode == 0xEB) { // jmp rel8 DLOG(1, "[x86 relo] jmp rel8, %p", buffer_cursor); int8_t orig_offset = insn.immediate; int8_t new_offset = (int8_t)(curr_orig_ip + orig_offset - curr_relo_ip); __ Emit8(0xE9); __ Emit32(new_offset); } else if ((insn.flags & X86_INSN_DECODE_FLAG_IP_RELATIVE) && (insn.operands[1].mem.base == RIP)) { // RIP DLOG(1, "[x86 relo] rip, %p", buffer_cursor); // dword orig_disp = *(dword *)(buffer_cursor + insn.operands[1].mem.disp); dword orig_disp = insn.operands[1].mem.disp; dword disp = (dword)(curr_orig_ip + orig_disp - curr_relo_ip); __ EmitBuffer((void *)buffer_cursor, insn.displacement_offset); __ Emit32(disp); } else if (insn.primary_opcode == 0xE8 || insn.primary_opcode == 0xE9) { // call or jmp rel32 DLOG(1, "[x86 relo] jmp or call rel32, %p", buffer_cursor); dword orig_offset = insn.immediate; dword offset = (dword)(curr_orig_ip + orig_offset - curr_relo_ip); __ EmitBuffer((void *)buffer_cursor, insn.immediate_offset); __ Emit32(offset); } else if (insn.primary_opcode >= 0xE0 && insn.primary_opcode <= 0xE2) { // LOOPNZ/LOOPZ/LOOP/JECXZ // LOOP/LOOPcc UNIMPLEMENTED(); } else if (insn.primary_opcode == 0xE3) { // JCXZ JCEXZ JCRXZ UNIMPLEMENTED(); } else { // Emit the origin instrution __ EmitBuffer((void *)buffer_cursor, insn.length); } // go next curr_orig_ip += insn.length; buffer_cursor += insn.length; #if 0 { // 1 orignal instrution => ? relocated instruction int relo_offset = turbo_assembler_.GetCodeBuffer()->getSize(); int relo_len = relo_offset - last_relo_offset; curr_relo_ip += relo_len; } #endif curr_relo_ip = relocated->raw_instruction_start() + turbo_assembler_.ip_offset(); } // jmp to the origin rest instructions CodeGen codegen(&turbo_assembler_); // TODO: 6 == jmp [RIP + disp32] instruction size addr64_t stub_addr = curr_relo_ip + 6; codegen.JmpNearIndirect(stub_addr); turbo_assembler_.GetCodeBuffer()->Emit64(curr_orig_ip); // update origin int new_origin_len = curr_orig_ip - origin->raw_instruction_start(); origin->re_init_region_range(origin->raw_instruction_start(), new_origin_len); int relo_len = turbo_assembler_.GetCodeBuffer()->getSize(); if (relo_len > relocated->raw_instruction_size()) { DLOG(0, "pre-alloc code chunk not enough"); return RT_FAILED; } // Generate executable code { AssemblyCodeChunk *code = NULL; code = AssemblyCodeBuilder::FinalizeFromTurboAssembler(&turbo_assembler_); delete code; } return RT_SUCCESS; } void GenRelocateCodeAndBranch(void *buffer, AssemblyCodeChunk *origin, AssemblyCodeChunk *relocated) { // pre-alloc code chunk AssemblyCodeChunk *cchunk = NULL; int relo_code_chunk_size = 32; const int chunk_size_step = 16; x64_try_again: if (relocated->raw_instruction_start() == 0) { cchunk = MemoryArena::AllocateCodeChunk(relo_code_chunk_size); if (cchunk == nullptr) { return; } relocated->re_init_region_range((addr_t)cchunk->address, (int)cchunk->length); } int ret = GenRelocateCodeFixed(buffer, origin, relocated); if (ret != RT_SUCCESS) { // free the cchunk MemoryArena::Destroy(cchunk); relo_code_chunk_size += chunk_size_step; relocated->re_init_region_range(0, 0); goto x64_try_again; } } #endif <commit_msg>[bug-fix] fix x64 relo ip addressing mode less immediate<commit_after>#include "platform_macro.h" #if defined(TARGET_ARCH_X64) #include "InstructionRelocation/x64/X64InstructionRelocation.h" #include <string.h> #include "dobby_internal.h" #include "InstructionRelocation/x86/x86_insn_decode/x86_insn_decode.h" #include "core/arch/x64/registers-x64.h" #include "core/modules/assembler/assembler-x64.h" #include "core/modules/codegen/codegen-x64.h" using namespace zz::x64; static int GenRelocateCodeFixed(void *buffer, AssemblyCodeChunk *origin, AssemblyCodeChunk *relocated) { TurboAssembler turbo_assembler_(0); // Set fixed executable code chunk address turbo_assembler_.SetRealizedAddress((void *)relocated->raw_instruction_start()); #define _ turbo_assembler_. #define __ turbo_assembler_.GetCodeBuffer()-> addr64_t curr_orig_ip = origin->raw_instruction_start(); addr64_t curr_relo_ip = relocated->raw_instruction_start(); addr_t buffer_cursor = (addr_t)buffer; x86_options_t conf = {.mode = 64}; int predefined_relocate_size = origin->raw_instruction_size(); while ((buffer_cursor < ((addr_t)buffer + predefined_relocate_size))) { int last_relo_offset = turbo_assembler_.GetCodeBuffer()->getSize(); x86_insn_decode_t insn = {0}; memset(&insn, 0, sizeof(insn)); // decode x86 insn x86_insn_decode(&insn, (uint8_t *)buffer_cursor, &conf); if (insn.primary_opcode >= 0x70 && insn.primary_opcode <= 0x7F) { // jc rel8 DLOG(1, "[x86 relo] jc rel8, %p", buffer_cursor); int8_t orig_offset = insn.immediate; int new_offset = (int)(curr_orig_ip + orig_offset - curr_relo_ip); uint8_t opcode = 0x80 | (insn.primary_opcode & 0x0f); __ Emit8(0x0F); __ Emit8(opcode); __ Emit32(new_offset); } else if (insn.primary_opcode == 0xEB) { // jmp rel8 DLOG(1, "[x86 relo] jmp rel8, %p", buffer_cursor); int8_t orig_offset = insn.immediate; int8_t new_offset = (int8_t)(curr_orig_ip + orig_offset - curr_relo_ip); __ Emit8(0xE9); __ Emit32(new_offset); } else if ((insn.flags & X86_INSN_DECODE_FLAG_IP_RELATIVE) && (insn.operands[1].mem.base == RIP)) { // RIP DLOG(1, "[x86 relo] rip, %p", buffer_cursor); // dword orig_disp = *(dword *)(buffer_cursor + insn.operands[1].mem.disp); dword orig_disp = insn.operands[1].mem.disp; dword new_disp = (dword)(curr_orig_ip + orig_disp - curr_relo_ip); __ EmitBuffer((void *)buffer_cursor, insn.displacement_offset); __ Emit32(new_disp); if(insn.immediate_offset) { __ EmitBuffer((void *)(buffer_cursor + insn.immediate_offset), insn.length - insn.immediate_offset); } } else if (insn.primary_opcode == 0xE8 || insn.primary_opcode == 0xE9) { // call or jmp rel32 DLOG(1, "[x86 relo] jmp or call rel32, %p", buffer_cursor); dword orig_offset = insn.immediate; dword offset = (dword)(curr_orig_ip + orig_offset - curr_relo_ip); __ EmitBuffer((void *)buffer_cursor, insn.immediate_offset); __ Emit32(offset); } else if (insn.primary_opcode >= 0xE0 && insn.primary_opcode <= 0xE2) { // LOOPNZ/LOOPZ/LOOP/JECXZ // LOOP/LOOPcc UNIMPLEMENTED(); } else if (insn.primary_opcode == 0xE3) { // JCXZ JCEXZ JCRXZ UNIMPLEMENTED(); } else { // Emit the origin instrution __ EmitBuffer((void *)buffer_cursor, insn.length); } // go next curr_orig_ip += insn.length; buffer_cursor += insn.length; #if 0 { // 1 orignal instrution => ? relocated instruction int relo_offset = turbo_assembler_.GetCodeBuffer()->getSize(); int relo_len = relo_offset - last_relo_offset; curr_relo_ip += relo_len; } #endif curr_relo_ip = relocated->raw_instruction_start() + turbo_assembler_.ip_offset(); } // jmp to the origin rest instructions CodeGen codegen(&turbo_assembler_); // TODO: 6 == jmp [RIP + disp32] instruction size addr64_t stub_addr = curr_relo_ip + 6; codegen.JmpNearIndirect(stub_addr); turbo_assembler_.GetCodeBuffer()->Emit64(curr_orig_ip); // update origin int new_origin_len = curr_orig_ip - origin->raw_instruction_start(); origin->re_init_region_range(origin->raw_instruction_start(), new_origin_len); int relo_len = turbo_assembler_.GetCodeBuffer()->getSize(); if (relo_len > relocated->raw_instruction_size()) { DLOG(0, "pre-alloc code chunk not enough"); return RT_FAILED; } // Generate executable code { AssemblyCodeChunk *code = NULL; code = AssemblyCodeBuilder::FinalizeFromTurboAssembler(&turbo_assembler_); delete code; } return RT_SUCCESS; } void GenRelocateCodeAndBranch(void *buffer, AssemblyCodeChunk *origin, AssemblyCodeChunk *relocated) { // pre-alloc code chunk AssemblyCodeChunk *cchunk = NULL; int relo_code_chunk_size = 32; const int chunk_size_step = 16; x64_try_again: if (relocated->raw_instruction_start() == 0) { cchunk = MemoryArena::AllocateCodeChunk(relo_code_chunk_size); if (cchunk == nullptr) { return; } relocated->re_init_region_range((addr_t)cchunk->address, (int)cchunk->length); } int ret = GenRelocateCodeFixed(buffer, origin, relocated); if (ret != RT_SUCCESS) { // free the cchunk MemoryArena::Destroy(cchunk); relo_code_chunk_size += chunk_size_step; relocated->re_init_region_range(0, 0); goto x64_try_again; } } #endif <|endoftext|>
<commit_before>/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2018-2020 Couchbase, 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 "internal.h" #include <iostream> #include <vector> #define LOGARGS(tracer, lvl) tracer->m_settings, "tracer", LCB_LOG_##lvl, __FILE__, __LINE__ using namespace lcb::trace; LIBCOUCHBASE_API lcbtrace_TRACER *lcbtrace_new(lcb_INSTANCE *instance, uint64_t flags) { if (instance == NULL || (flags & LCBTRACE_F_THRESHOLD) == 0) { return NULL; } return (new ThresholdLoggingTracer(instance))->wrap(); } extern "C" { static void tlt_destructor(lcbtrace_TRACER *wrapper) { if (wrapper == NULL) { return; } if (wrapper->cookie) { ThresholdLoggingTracer *tracer = reinterpret_cast< ThresholdLoggingTracer * >(wrapper->cookie); tracer->do_flush_orphans(); tracer->do_flush_threshold(); delete tracer; wrapper->cookie = NULL; } delete wrapper; } static void tlt_report(lcbtrace_TRACER *wrapper, lcbtrace_SPAN *span) { if (wrapper == NULL || wrapper->cookie == NULL) { return; } ThresholdLoggingTracer *tracer = reinterpret_cast< ThresholdLoggingTracer * >(wrapper->cookie); char *value = NULL; size_t nvalue; if (lcbtrace_span_get_tag_str(span, LCBTRACE_TAG_SERVICE, &value, &nvalue) == LCB_SUCCESS) { if (strncmp(value, LCBTRACE_TAG_SERVICE_KV, nvalue) == 0) { if (lcbtrace_span_is_orphaned(span)) { tracer->add_orphan(span); } else { tracer->check_threshold(span); } } } } } lcbtrace_TRACER *ThresholdLoggingTracer::wrap() { if (m_wrapper) { return m_wrapper; } m_wrapper = new lcbtrace_TRACER(); m_wrapper->version = 0; m_wrapper->flags = 0; m_wrapper->cookie = this; m_wrapper->destructor = tlt_destructor; m_wrapper->v.v0.report = tlt_report; return m_wrapper; } QueueEntry ThresholdLoggingTracer::convert(lcbtrace_SPAN *span) { QueueEntry orphan; orphan.duration = span->duration(); Json::Value entry; char *value; size_t nvalue; if (lcbtrace_span_get_tag_str(span, LCBTRACE_TAG_OPERATION_ID, &value, &nvalue) == LCB_SUCCESS) { entry["last_operation_id"] = std::string(span->m_opname) + ":" + std::string(value, value + nvalue); } if (lcbtrace_span_get_tag_str(span, LCBTRACE_TAG_LOCAL_ID, &value, &nvalue) == LCB_SUCCESS) { entry["last_local_id"] = std::string(value, value + nvalue); } if (lcbtrace_span_get_tag_str(span, LCBTRACE_TAG_LOCAL_ADDRESS, &value, &nvalue) == LCB_SUCCESS) { entry["last_local_address"] = std::string(value, value + nvalue); } if (lcbtrace_span_get_tag_str(span, LCBTRACE_TAG_PEER_ADDRESS, &value, &nvalue) == LCB_SUCCESS) { entry["last_remote_address"] = std::string(value, value + nvalue); } uint64_t num; if (lcbtrace_span_get_tag_uint64(span, LCBTRACE_TAG_PEER_LATENCY, &num) == LCB_SUCCESS) { entry["server_us"] = (Json::UInt64)num; } entry["total_us"] = (Json::UInt64)orphan.duration; orphan.payload = Json::FastWriter().write(entry); return orphan; } void ThresholdLoggingTracer::add_orphan(lcbtrace_SPAN *span) { m_orphans.push(convert(span)); } void ThresholdLoggingTracer::check_threshold(lcbtrace_SPAN *span) { if (span->duration() > m_settings->tracer_threshold[LCBTRACE_THRESHOLD_KV]) { m_threshold.push(convert(span)); } } void ThresholdLoggingTracer::flush_queue(FixedSpanQueue &queue, const char *message, bool warn = false) { Json::Value entries; entries["service"] = "kv"; entries["count"] = (Json::UInt)queue.size(); Json::Value top; while (!queue.empty()) { Json::Value entry; if (Json::Reader().parse(queue.top().payload, entry)) { top.append(entry); } queue.pop(); } entries["top"] = top; std::string doc = Json::FastWriter().write(entries); if (doc.size() > 0 && doc[doc.size() - 1] == '\n') { doc[doc.size() - 1] = '\0'; } if (warn) { lcb_log(LOGARGS(this, WARN), "%s: %s", message, doc.c_str()); } else { lcb_log(LOGARGS(this, INFO), "%s: %s", message, doc.c_str()); } } void ThresholdLoggingTracer::do_flush_orphans() { if (m_orphans.empty()) { return; } flush_queue(m_orphans, "Orphan responses observed", true); } void ThresholdLoggingTracer::do_flush_threshold() { if (m_threshold.empty()) { return; } flush_queue(m_threshold, "Operations over threshold"); } void ThresholdLoggingTracer::flush_orphans() { lcb_U32 tv = m_settings->tracer_orphaned_queue_flush_interval; if (tv == 0) { m_oflush.cancel(); } else { m_oflush.rearm(tv); } do_flush_orphans(); } void ThresholdLoggingTracer::flush_threshold() { lcb_U32 tv = m_settings->tracer_threshold_queue_flush_interval; if (tv == 0) { m_tflush.cancel(); } else { m_tflush.rearm(tv); } do_flush_threshold(); } ThresholdLoggingTracer::ThresholdLoggingTracer(lcb_INSTANCE *instance) : m_wrapper(NULL), m_settings(instance->settings), m_orphans(LCBT_SETTING(instance, tracer_orphaned_queue_size)), m_threshold(LCBT_SETTING(instance, tracer_threshold_queue_size)), m_oflush(instance->iotable, this), m_tflush(instance->iotable, this) { lcb_U32 tv = m_settings->tracer_orphaned_queue_flush_interval; if (tv > 0) { m_oflush.rearm(tv); } tv = m_settings->tracer_threshold_queue_flush_interval; if (tv > 0) { m_tflush.rearm(tv); } } <commit_msg>CCBC-1233: Updated RTO to independently specify operation_name.<commit_after>/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2018-2020 Couchbase, 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 "internal.h" #include <iostream> #include <vector> #define LOGARGS(tracer, lvl) tracer->m_settings, "tracer", LCB_LOG_##lvl, __FILE__, __LINE__ using namespace lcb::trace; LIBCOUCHBASE_API lcbtrace_TRACER *lcbtrace_new(lcb_INSTANCE *instance, uint64_t flags) { if (instance == NULL || (flags & LCBTRACE_F_THRESHOLD) == 0) { return NULL; } return (new ThresholdLoggingTracer(instance))->wrap(); } extern "C" { static void tlt_destructor(lcbtrace_TRACER *wrapper) { if (wrapper == NULL) { return; } if (wrapper->cookie) { ThresholdLoggingTracer *tracer = reinterpret_cast< ThresholdLoggingTracer * >(wrapper->cookie); tracer->do_flush_orphans(); tracer->do_flush_threshold(); delete tracer; wrapper->cookie = NULL; } delete wrapper; } static void tlt_report(lcbtrace_TRACER *wrapper, lcbtrace_SPAN *span) { if (wrapper == NULL || wrapper->cookie == NULL) { return; } ThresholdLoggingTracer *tracer = reinterpret_cast< ThresholdLoggingTracer * >(wrapper->cookie); char *value = NULL; size_t nvalue; if (lcbtrace_span_get_tag_str(span, LCBTRACE_TAG_SERVICE, &value, &nvalue) == LCB_SUCCESS) { if (strncmp(value, LCBTRACE_TAG_SERVICE_KV, nvalue) == 0) { if (lcbtrace_span_is_orphaned(span)) { tracer->add_orphan(span); } else { tracer->check_threshold(span); } } } } } lcbtrace_TRACER *ThresholdLoggingTracer::wrap() { if (m_wrapper) { return m_wrapper; } m_wrapper = new lcbtrace_TRACER(); m_wrapper->version = 0; m_wrapper->flags = 0; m_wrapper->cookie = this; m_wrapper->destructor = tlt_destructor; m_wrapper->v.v0.report = tlt_report; return m_wrapper; } QueueEntry ThresholdLoggingTracer::convert(lcbtrace_SPAN *span) { QueueEntry orphan; orphan.duration = span->duration(); Json::Value entry; char *value; size_t nvalue; entry["operation_name"] = std::string(span->m_opname); if (lcbtrace_span_get_tag_str(span, LCBTRACE_TAG_OPERATION_ID, &value, &nvalue) == LCB_SUCCESS) { entry["last_operation_id"] = std::string(value, value + nvalue); } if (lcbtrace_span_get_tag_str(span, LCBTRACE_TAG_LOCAL_ID, &value, &nvalue) == LCB_SUCCESS) { entry["last_local_id"] = std::string(value, value + nvalue); } if (lcbtrace_span_get_tag_str(span, LCBTRACE_TAG_LOCAL_ADDRESS, &value, &nvalue) == LCB_SUCCESS) { entry["last_local_address"] = std::string(value, value + nvalue); } if (lcbtrace_span_get_tag_str(span, LCBTRACE_TAG_PEER_ADDRESS, &value, &nvalue) == LCB_SUCCESS) { entry["last_remote_address"] = std::string(value, value + nvalue); } uint64_t num; if (lcbtrace_span_get_tag_uint64(span, LCBTRACE_TAG_PEER_LATENCY, &num) == LCB_SUCCESS) { entry["server_us"] = (Json::UInt64)num; } entry["total_us"] = (Json::UInt64)orphan.duration; orphan.payload = Json::FastWriter().write(entry); return orphan; } void ThresholdLoggingTracer::add_orphan(lcbtrace_SPAN *span) { m_orphans.push(convert(span)); } void ThresholdLoggingTracer::check_threshold(lcbtrace_SPAN *span) { if (span->duration() > m_settings->tracer_threshold[LCBTRACE_THRESHOLD_KV]) { m_threshold.push(convert(span)); } } void ThresholdLoggingTracer::flush_queue(FixedSpanQueue &queue, const char *message, bool warn = false) { Json::Value entries; entries["service"] = "kv"; entries["count"] = (Json::UInt)queue.size(); Json::Value top; while (!queue.empty()) { Json::Value entry; if (Json::Reader().parse(queue.top().payload, entry)) { top.append(entry); } queue.pop(); } entries["top"] = top; std::string doc = Json::FastWriter().write(entries); if (doc.size() > 0 && doc[doc.size() - 1] == '\n') { doc[doc.size() - 1] = '\0'; } if (warn) { lcb_log(LOGARGS(this, WARN), "%s: %s", message, doc.c_str()); } else { lcb_log(LOGARGS(this, INFO), "%s: %s", message, doc.c_str()); } } void ThresholdLoggingTracer::do_flush_orphans() { if (m_orphans.empty()) { return; } flush_queue(m_orphans, "Orphan responses observed", true); } void ThresholdLoggingTracer::do_flush_threshold() { if (m_threshold.empty()) { return; } flush_queue(m_threshold, "Operations over threshold"); } void ThresholdLoggingTracer::flush_orphans() { lcb_U32 tv = m_settings->tracer_orphaned_queue_flush_interval; if (tv == 0) { m_oflush.cancel(); } else { m_oflush.rearm(tv); } do_flush_orphans(); } void ThresholdLoggingTracer::flush_threshold() { lcb_U32 tv = m_settings->tracer_threshold_queue_flush_interval; if (tv == 0) { m_tflush.cancel(); } else { m_tflush.rearm(tv); } do_flush_threshold(); } ThresholdLoggingTracer::ThresholdLoggingTracer(lcb_INSTANCE *instance) : m_wrapper(NULL), m_settings(instance->settings), m_orphans(LCBT_SETTING(instance, tracer_orphaned_queue_size)), m_threshold(LCBT_SETTING(instance, tracer_threshold_queue_size)), m_oflush(instance->iotable, this), m_tflush(instance->iotable, this) { lcb_U32 tv = m_settings->tracer_orphaned_queue_flush_interval; if (tv > 0) { m_oflush.rearm(tv); } tv = m_settings->tracer_threshold_queue_flush_interval; if (tv > 0) { m_tflush.rearm(tv); } } <|endoftext|>
<commit_before>// clang-format off // REQUIRES: lld // Test that we can display function signatures with class types. // RUN: %build --compiler=clang-cl --nodefaultlib -o %t.exe -- %s // RUN: env LLDB_USE_NATIVE_PDB_READER=1 %lldb -f %t.exe -s \ // RUN: %p/Inputs/function-types-classes.lldbinit | FileCheck %s // This is just some unimportant helpers needed so that we can get reference and // rvalue-reference types into return values. template<typename T> struct MakeResult { static T result() { return T{}; } }; template<typename T> struct MakeResult<T&> { static T& result() { static T t; return t; } }; template<typename T> struct MakeResult<T&&> { static T&& result() { static T t; return static_cast<T&&>(t); } }; template<typename R> R nullary() { return MakeResult<R>::result(); } template<typename R, typename A, typename B> R three(A a, B b) { return MakeResult<R>::result(); } template<typename R, typename A, typename B, typename C> R four(A a, B b, C c) { return MakeResult<R>::result(); } struct S {}; class C {}; union U {}; enum E {}; namespace A { namespace B { // NS::NS struct S { }; } struct C { // NS::Struct struct S {}; }; } struct B { struct A { // Struct::Struct struct S {}; }; }; // clang (incorrectly) doesn't emit debug information for outer classes // unless they are instantiated. They should also be emitted if there // is an inner class which is instantiated. A::C ForceInstantiateAC; B ForceInstantiateB; B::A ForceInstantiateBA; template<typename T> struct TC {}; // const and volatile modifiers auto a = &four<S, C*, U&, E&&>; // CHECK: (S (*)(C *, U &, E &&)) a = {{.*}} auto b = &four<E, const S*, const C&, const U&&>; // CHECK: (E (*)(const S *, const C &, const U &&)) b = {{.*}} auto c = &four<U, volatile E*, volatile S&, volatile C&&>; // CHECK: (U (*)(volatile E *, volatile S &, volatile C &&)) c = {{.*}} auto d = &four<C, const volatile U*, const volatile E&, const volatile S&&>; // CHECK: (C (*)(const volatile U *, const volatile E &, const volatile S &&)) d = {{.*}} // classes nested in namespaces and inner classes auto e = &three<A::B::S*, B::A::S*, A::C::S&>; // CHECK: (A::B::S *(*)(B::A::S *, A::C::S &)) e = {{.*}} auto f = &three<A::C::S&, A::B::S*, B::A::S*>; // CHECK: (A::C::S &(*)(A::B::S *, B::A::S *)) f = {{.*}} auto g = &three<B::A::S*, A::C::S&, A::B::S*>; // CHECK: (B::A::S *(*)(A::C::S &, A::B::S *)) g = {{.*}} // parameter types that are themselves template instantiations. auto h = &four<TC<void>, TC<int>, TC<TC<int>>, TC<A::B::S>>; // CHECK: (TC<void> (*)(TC<int>, TC<struct TC<int>>, TC<struct A::B::S>)) h = {{.*}} auto i = &nullary<A::B::S>; // CHECK: (A::B::S (*)()) i = {{.*}} // Make sure we can handle types that don't have complete debug info. struct Incomplete; auto incomplete = &three<Incomplete*, Incomplete**, const Incomplete*>; // CHECK: (Incomplete *(*)(Incomplete **, const Incomplete *)) incomplete = {{.*}} // CHECK: TranslationUnitDecl {{.*}} // CHECK: |-CXXRecordDecl {{.*}} class C // CHECK: |-CXXRecordDecl {{.*}} union U // CHECK: |-EnumDecl {{.*}} E // CHECK: |-CXXRecordDecl {{.*}} struct S // CHECK: |-CXXRecordDecl {{.*}} struct B // CHECK: | |-CXXRecordDecl {{.*}} struct A // CHECK: | | |-CXXRecordDecl {{.*}} struct S // CHECK: |-NamespaceDecl {{.*}} A // CHECK: | |-CXXRecordDecl {{.*}} struct C // CHECK: | | |-CXXRecordDecl {{.*}} struct S // CHECK: | `-NamespaceDecl {{.*}} B // CHECK: | `-CXXRecordDecl {{.*}} struct S // CHECK: |-CXXRecordDecl {{.*}} struct TC<int> // CHECK: |-CXXRecordDecl {{.*}} struct TC<struct TC<int>> // CHECK: |-CXXRecordDecl {{.*}} struct TC<struct A::B::S> // CHECK: |-CXXRecordDecl {{.*}} struct TC<void> // CHECK: |-CXXRecordDecl {{.*}} struct Incomplete int main(int argc, char **argv) { return 0; } <commit_msg>[NativePDB] Update function-types-classes test to check VarDecls.<commit_after>// clang-format off // REQUIRES: lld // Test that we can display function signatures with class types. // RUN: %build --compiler=clang-cl --nodefaultlib -o %t.exe -- %s // RUN: env LLDB_USE_NATIVE_PDB_READER=1 %lldb -f %t.exe -s \ // RUN: %p/Inputs/function-types-classes.lldbinit | FileCheck %s // This is just some unimportant helpers needed so that we can get reference and // rvalue-reference types into return values. template<typename T> struct MakeResult { static T result() { return T{}; } }; template<typename T> struct MakeResult<T&> { static T& result() { static T t; return t; } }; template<typename T> struct MakeResult<T&&> { static T&& result() { static T t; return static_cast<T&&>(t); } }; template<typename R> R nullary() { return MakeResult<R>::result(); } template<typename R, typename A, typename B> R three(A a, B b) { return MakeResult<R>::result(); } template<typename R, typename A, typename B, typename C> R four(A a, B b, C c) { return MakeResult<R>::result(); } struct S {}; class C {}; union U {}; enum E {}; namespace A { namespace B { // NS::NS struct S { }; } struct C { // NS::Struct struct S {}; }; } struct B { struct A { // Struct::Struct struct S {}; }; }; // clang (incorrectly) doesn't emit debug information for outer classes // unless they are instantiated. They should also be emitted if there // is an inner class which is instantiated. A::C ForceInstantiateAC; B ForceInstantiateB; B::A ForceInstantiateBA; template<typename T> struct TC {}; // const and volatile modifiers auto a = &four<S, C*, U&, E&&>; // CHECK: (S (*)(C *, U &, E &&)) a = {{.*}} auto b = &four<E, const S*, const C&, const U&&>; // CHECK: (E (*)(const S *, const C &, const U &&)) b = {{.*}} auto c = &four<U, volatile E*, volatile S&, volatile C&&>; // CHECK: (U (*)(volatile E *, volatile S &, volatile C &&)) c = {{.*}} auto d = &four<C, const volatile U*, const volatile E&, const volatile S&&>; // CHECK: (C (*)(const volatile U *, const volatile E &, const volatile S &&)) d = {{.*}} // classes nested in namespaces and inner classes auto e = &three<A::B::S*, B::A::S*, A::C::S&>; // CHECK: (A::B::S *(*)(B::A::S *, A::C::S &)) e = {{.*}} auto f = &three<A::C::S&, A::B::S*, B::A::S*>; // CHECK: (A::C::S &(*)(A::B::S *, B::A::S *)) f = {{.*}} auto g = &three<B::A::S*, A::C::S&, A::B::S*>; // CHECK: (B::A::S *(*)(A::C::S &, A::B::S *)) g = {{.*}} // parameter types that are themselves template instantiations. auto h = &four<TC<void>, TC<int>, TC<TC<int>>, TC<A::B::S>>; // CHECK: (TC<void> (*)(TC<int>, TC<TC<int>>, TC<A::B::S>)) h = {{.*}} auto i = &nullary<A::B::S>; // CHECK: (A::B::S (*)()) i = {{.*}} // Make sure we can handle types that don't have complete debug info. struct Incomplete; auto incomplete = &three<Incomplete*, Incomplete**, const Incomplete*>; // CHECK: (Incomplete *(*)(Incomplete **, const Incomplete *)) incomplete = {{.*}} // CHECK: TranslationUnitDecl {{.*}} // CHECK: |-CXXRecordDecl {{.*}} class C // CHECK: |-CXXRecordDecl {{.*}} union U // CHECK: |-EnumDecl {{.*}} E // CHECK: |-CXXRecordDecl {{.*}} struct S // CHECK: |-VarDecl {{.*}} a 'S (*)(C *, U &, E &&)' // CHECK: |-VarDecl {{.*}} b 'E (*)(const S *, const C &, const U &&)' // CHECK: |-VarDecl {{.*}} c 'U (*)(volatile E *, volatile S &, volatile C &&)' // CHECK: |-VarDecl {{.*}} d 'C (*)(const volatile U *, const volatile E &, const volatile S &&)' // CHECK: |-CXXRecordDecl {{.*}} struct B // CHECK: | |-CXXRecordDecl {{.*}} struct A // CHECK: | | |-CXXRecordDecl {{.*}} struct S // CHECK: |-NamespaceDecl {{.*}} A // CHECK: | |-CXXRecordDecl {{.*}} struct C // CHECK: | | |-CXXRecordDecl {{.*}} struct S // CHECK: | `-NamespaceDecl {{.*}} B // CHECK: | `-CXXRecordDecl {{.*}} struct S // CHECK: |-VarDecl {{.*}} e 'A::B::S *(*)(B::A::S *, A::C::S &)' // CHECK: |-VarDecl {{.*}} f 'A::C::S &(*)(A::B::S *, B::A::S *)' // CHECK: |-VarDecl {{.*}} g 'B::A::S *(*)(A::C::S &, A::B::S *)' // CHECK: |-CXXRecordDecl {{.*}} struct TC<int> // CHECK: |-CXXRecordDecl {{.*}} struct TC<TC<int>> // CHECK: |-CXXRecordDecl {{.*}} struct TC<A::B::S> // CHECK: |-CXXRecordDecl {{.*}} struct TC<void> // CHECK: |-VarDecl {{.*}} h 'TC<void> (*)(TC<int>, TC<TC<int>>, TC<A::B::S>)' // CHECK: |-VarDecl {{.*}} i 'A::B::S (*)()' // CHECK: |-CXXRecordDecl {{.*}} struct Incomplete // CHECK: |-VarDecl {{.*}} incomplete 'Incomplete *(*)(Incomplete **, const Incomplete *)' int main(int argc, char **argv) { return 0; } <|endoftext|>
<commit_before>/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2016 INRIA. * * 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. */ /*! \file SiconosCollisionManager.hpp \brief A mechanics world is a Siconos InteractionManager that supports static contactors and dynamic contactors attached to special Dynamical Systems (BodyDS, derived from NewtonEulerDS) found in the NonSmoothDynamicalSystem. */ #ifndef SiconosCollisionManager_h #define SiconosCollisionManager_h #include <InteractionManager.hpp> #include <SiconosContactor.hpp> #include <SiconosCollisionQueryResult.hpp> class SiconosCollisionManager : public InteractionManager { protected: /** serialization hooks */ ACCEPT_SERIALIZATION(SiconosCollisionManager); public: SiconosCollisionManager() : InteractionManager() {} virtual ~SiconosCollisionManager() {} /** An opaque handle can be used to refer to a specific static * contactor set previously added to the collision manager. */ typedef void* StaticContactorSetID; /** Remove a body from the collision detector. This must be done * after removing a body from the NonSmoothDynamicalSystem * otherwise contact will occur with a non-graph body which results * in failure. */ virtual void removeBody(const SP::BodyDS& body) {} /** Perform an intersection test on all shapes in the contactors and * return a vector of all results, ordered by distance from start. \param start The starting point of the line segment in inertial frame (world) coordinates. \param end The ending point of the line segment in inertial frame (world) coordinates. \param closestOnly If true, indicates only interested in first result closest to half-space boundary, max size of returned vector = 1. \param sorted If true, results are sorted by distance. \return A vector of SiconosCollisionQueryResult that contain information about the query results. */ virtual std::vector<SP::SiconosCollisionQueryResult> lineIntersectionQuery(const SiconosVector& start, const SiconosVector& end, bool closestOnly=false, bool sorted=true) { return std::vector<SP::SiconosCollisionQueryResult>(); } /** Find all shapes that are within a sphere defined by a point and * a radius and return them in an ordered list based on distance to * the center. \param center The center of the sphere in inertial frame (world) coordinates. \param radius The radius of the sphere. \param closestOnly If true, indicates only interested in first result closest to half-space boundary, max size of returned vector = 1. \param sorted If true, results are sorted by distance. \return A vector of SiconosCollisionQueryResult that contain information about the query results. */ virtual std::vector<SP::SiconosCollisionQueryResult> inSphereQuery(const SiconosVector& center, double radius, bool closestOnly=false, bool sorted=true) { return std::vector<SP::SiconosCollisionQueryResult>(); } /** Find all shapes that are within a box defined by a center point * and a dimensions (3-vector), and return them in an ordered list * based on distance to the center. \param center The center of the box in inertial frame (world) coordinates. \param dimensions The dimensions of the box (3-vector). \param closestOnly If true, indicates only interested in first result closest to half-space boundary, max size of returned vector = 1. \param sorted If true, results are sorted by distance. \return A vector of SiconosCollisionQueryResult that contain information about the query results. */ virtual std::vector<SP::SiconosCollisionQueryResult> inBoxQuery(const SiconosVector& center, const SiconosVector& dimensions, bool closestOnly=false, bool sorted=true) { return std::vector<SP::SiconosCollisionQueryResult>(); } /** Find all shapes that are inside a half-space, defined by a point * and a normal direction. \param point The point defining the boundary of the half-space. \param normal The normal pointing away from the surface of the half-space. \param closestOnly If true, indicates only interested in first result closest to half-space boundary, max size of returned vector = 1. \param sorted If true, results are sorted by distance. \return A vector of SiconosCollisionQueryResult that contain information about the query results. */ virtual std::vector<SP::SiconosCollisionQueryResult> inHalfSpaceQuery(const SiconosVector& point, const SiconosVector& normal, bool closestOnly=false, bool sorted=true) { return std::vector<SP::SiconosCollisionQueryResult>(); } public: virtual StaticContactorSetID insertStaticContactorSet( SP::SiconosContactorSet cs, SP::SiconosVector position = SP::SiconosVector()) = 0; virtual bool removeStaticContactorSet(StaticContactorSetID id) = 0; }; #endif /* SiconosCollisionManager.hpp */ <commit_msg>[mechanics] make insert/removeStaticContactorSet not pure abstract<commit_after>/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2016 INRIA. * * 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. */ /*! \file SiconosCollisionManager.hpp \brief A mechanics world is a Siconos InteractionManager that supports static contactors and dynamic contactors attached to special Dynamical Systems (BodyDS, derived from NewtonEulerDS) found in the NonSmoothDynamicalSystem. */ #ifndef SiconosCollisionManager_h #define SiconosCollisionManager_h #include <InteractionManager.hpp> #include <SiconosContactor.hpp> #include <SiconosCollisionQueryResult.hpp> class SiconosCollisionManager : public InteractionManager { protected: /** serialization hooks */ ACCEPT_SERIALIZATION(SiconosCollisionManager); public: SiconosCollisionManager() : InteractionManager() {} virtual ~SiconosCollisionManager() {} /** An opaque handle can be used to refer to a specific static * contactor set previously added to the collision manager. */ typedef void* StaticContactorSetID; /** Remove a body from the collision detector. This must be done * after removing a body from the NonSmoothDynamicalSystem * otherwise contact will occur with a non-graph body which results * in failure. */ virtual void removeBody(const SP::BodyDS& body) {} /** Perform an intersection test on all shapes in the contactors and * return a vector of all results, ordered by distance from start. \param start The starting point of the line segment in inertial frame (world) coordinates. \param end The ending point of the line segment in inertial frame (world) coordinates. \param closestOnly If true, indicates only interested in first result closest to half-space boundary, max size of returned vector = 1. \param sorted If true, results are sorted by distance. \return A vector of SiconosCollisionQueryResult that contain information about the query results. */ virtual std::vector<SP::SiconosCollisionQueryResult> lineIntersectionQuery(const SiconosVector& start, const SiconosVector& end, bool closestOnly=false, bool sorted=true) { return std::vector<SP::SiconosCollisionQueryResult>(); } /** Find all shapes that are within a sphere defined by a point and * a radius and return them in an ordered list based on distance to * the center. \param center The center of the sphere in inertial frame (world) coordinates. \param radius The radius of the sphere. \param closestOnly If true, indicates only interested in first result closest to half-space boundary, max size of returned vector = 1. \param sorted If true, results are sorted by distance. \return A vector of SiconosCollisionQueryResult that contain information about the query results. */ virtual std::vector<SP::SiconosCollisionQueryResult> inSphereQuery(const SiconosVector& center, double radius, bool closestOnly=false, bool sorted=true) { return std::vector<SP::SiconosCollisionQueryResult>(); } /** Find all shapes that are within a box defined by a center point * and a dimensions (3-vector), and return them in an ordered list * based on distance to the center. \param center The center of the box in inertial frame (world) coordinates. \param dimensions The dimensions of the box (3-vector). \param closestOnly If true, indicates only interested in first result closest to half-space boundary, max size of returned vector = 1. \param sorted If true, results are sorted by distance. \return A vector of SiconosCollisionQueryResult that contain information about the query results. */ virtual std::vector<SP::SiconosCollisionQueryResult> inBoxQuery(const SiconosVector& center, const SiconosVector& dimensions, bool closestOnly=false, bool sorted=true) { return std::vector<SP::SiconosCollisionQueryResult>(); } /** Find all shapes that are inside a half-space, defined by a point * and a normal direction. \param point The point defining the boundary of the half-space. \param normal The normal pointing away from the surface of the half-space. \param closestOnly If true, indicates only interested in first result closest to half-space boundary, max size of returned vector = 1. \param sorted If true, results are sorted by distance. \return A vector of SiconosCollisionQueryResult that contain information about the query results. */ virtual std::vector<SP::SiconosCollisionQueryResult> inHalfSpaceQuery(const SiconosVector& point, const SiconosVector& normal, bool closestOnly=false, bool sorted=true) { return std::vector<SP::SiconosCollisionQueryResult>(); } public: /** Insert a static contactor set */ virtual StaticContactorSetID insertStaticContactorSet( SP::SiconosContactorSet cs, SP::SiconosVector position = SP::SiconosVector()) { return (StaticContactorSetID)0; } /** Remove a static contactor set. * \param id An identifier returned by insertStaticContactorSet. */ virtual bool removeStaticContactorSet(StaticContactorSetID id) { return !id; }; }; #endif /* SiconosCollisionManager.hpp */ <|endoftext|>
<commit_before>#if defined(TI_WITH_CUDA) #if defined(min) #undef min #endif #if defined(max) #undef max #endif #include <memory> #include <cuda_runtime_api.h> #include <cuda.h> #include "llvm/ADT/StringRef.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/LLVMContext.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetMachine.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/Transforms/InstCombine/InstCombine.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Scalar/GVN.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include <llvm/Analysis/TargetTransformInfo.h> #include <llvm/Support/TargetRegistry.h> #include <llvm/Target/TargetMachine.h> #include <llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h> #include <taichi/platform/cuda/cuda_utils.h> #include <taichi/platform/cuda/cuda_context.h> #include <taichi/program.h> #include <taichi/context.h> #include <taichi/system/timer.h> #include "../tlang_util.h" #include "jit_session.h" TLANG_NAMESPACE_BEGIN class JITModuleCUDA : public JITModule { private: CUmodule module; public: JITModuleCUDA(CUmodule module) : module(module) { } virtual void *lookup_function(const std::string &name) { // auto _ = cuda_context->get_guard(); cuda_context->make_current(); CUfunction func; auto t = Time::get_time(); check_cuda_error(cuModuleGetFunction(&func, module, name.c_str())); t = Time::get_time() - t; TI_TRACE("Kernel {} compilation time: {}ms", name, t * 1000); return (void *)func; } }; class JITSessionCUDA : public JITSession { public: llvm::DataLayout DL; JITSessionCUDA(llvm::DataLayout data_layout) : DL(data_layout) { } virtual JITModule *add_module(std::unique_ptr<llvm::Module> M) override { auto ptx = compile_module_to_ptx(M); // auto _ = cuda_context->get_guard(); cuda_context->make_current(); // Create module for object CUmodule cudaModule; TI_TRACE("PTX size: {:.2f}KB", ptx.size() / 1024.0); auto t = Time::get_time(); TI_TRACE("Loading module..."); auto _ = std::lock_guard<std::mutex>(cuda_context->lock); check_cuda_error( cuModuleLoadDataEx(&cudaModule, ptx.c_str(), 0, nullptr, nullptr)); TI_TRACE("CUDA module load time : {}ms", (Time::get_time() - t) * 1000); // cudaModules.push_back(cudaModule); modules.push_back(std::make_unique<JITModuleCUDA>(cudaModule)); return modules.back().get(); } virtual llvm::DataLayout get_data_layout() override { return DL; } static std::string compile_module_to_ptx( std::unique_ptr<llvm::Module> &module); }; std::string cuda_mattrs() { return "+ptx50"; } std::string JITSessionCUDA::compile_module_to_ptx( std::unique_ptr<llvm::Module> &module) { // Part of this function is borrowed from Halide::CodeGen_PTX_Dev.cpp using namespace llvm; llvm::Triple triple(module->getTargetTriple()); // Allocate target machine std::string err_str; const llvm::Target *target = TargetRegistry::lookupTarget(triple.str(), err_str); TI_ERROR_UNLESS(target, err_str); bool fast_math = get_current_program().config.fast_math; TargetOptions options; options.PrintMachineCode = 0; if (fast_math) { options.AllowFPOpFusion = FPOpFusion::Fast; // See NVPTXISelLowering.cpp // Setting UnsafeFPMath true will result in approximations such as // sqrt.approx in PTX for both f32 and f64 options.UnsafeFPMath = 1; options.NoInfsFPMath = 1; options.NoNaNsFPMath = 1; } else { options.AllowFPOpFusion = FPOpFusion::Strict; options.UnsafeFPMath = 0; options.NoInfsFPMath = 0; options.NoNaNsFPMath = 0; } options.HonorSignDependentRoundingFPMathOption = 0; options.NoZerosInBSS = 0; options.GuaranteedTailCallOpt = 0; options.StackAlignmentOverride = 0; std::unique_ptr<TargetMachine> target_machine(target->createTargetMachine( triple.str(), cuda_context->get_mcpu(), cuda_mattrs(), options, llvm::Reloc::PIC_, llvm::CodeModel::Small, CodeGenOpt::Aggressive)); TI_ERROR_UNLESS(target_machine.get(), "Could not allocate target machine!"); module->setDataLayout(target_machine->createDataLayout()); // Set up passes llvm::SmallString<8> outstr; raw_svector_ostream ostream(outstr); ostream.SetUnbuffered(); legacy::FunctionPassManager function_pass_manager(module.get()); legacy::PassManager module_pass_manager; module_pass_manager.add(createTargetTransformInfoWrapperPass( target_machine->getTargetIRAnalysis())); function_pass_manager.add(createTargetTransformInfoWrapperPass( target_machine->getTargetIRAnalysis())); // NVidia's libdevice library uses a __nvvm_reflect to choose // how to handle denormalized numbers. (The pass replaces calls // to __nvvm_reflect with a constant via a map lookup. The inliner // pass then resolves these situations to fast code, often a single // instruction per decision point.) // // The default is (more) IEEE like handling. FTZ mode flushes them // to zero. (This may only apply to single-precision.) // // The libdevice documentation covers other options for math accuracy // such as replacing division with multiply by the reciprocal and // use of fused-multiply-add, but they do not seem to be controlled // by this __nvvvm_reflect mechanism and may be flags to earlier compiler // passes. const auto kFTZDenorms = 1; // Insert a module flag for the FTZ handling. module->addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", kFTZDenorms); if (kFTZDenorms) { for (llvm::Function &fn : *module) { fn.addFnAttr("nvptx-f32ftz", "true"); } } PassManagerBuilder b; b.OptLevel = 3; b.Inliner = createFunctionInliningPass(b.OptLevel, 0, false); b.LoopVectorize = false; b.SLPVectorize = false; target_machine->adjustPassManager(b); b.populateFunctionPassManager(function_pass_manager); b.populateModulePassManager(module_pass_manager); // Override default to generate verbose assembly. target_machine->Options.MCOptions.AsmVerbose = true; // Output string stream // Ask the target to add backend passes as necessary. bool fail = target_machine->addPassesToEmitFile( module_pass_manager, ostream, nullptr, TargetMachine::CGFT_AssemblyFile, true); TI_ERROR_IF(fail, "Failed to set up passes to emit PTX source\n"); // Run optimization passes function_pass_manager.doInitialization(); for (llvm::Module::iterator i = module->begin(); i != module->end(); i++) { function_pass_manager.run(*i); } function_pass_manager.doFinalization(); module_pass_manager.run(*module); std::string buffer(outstr.begin(), outstr.end()); // Null-terminate the ptx source buffer.push_back(0); return buffer; } std::unique_ptr<JITSession> create_llvm_jit_session_cuda(Arch arch) { TI_ASSERT(arch == Arch::cuda); // TODO: assuming CUDA has the same data layout as the host arch std::unique_ptr<llvm::orc::JITTargetMachineBuilder> jtmb; auto JTMB = llvm::orc::JITTargetMachineBuilder::detectHost(); if (!JTMB) TI_ERROR("LLVM TargetMachineBuilder has failed."); jtmb = std::make_unique<llvm::orc::JITTargetMachineBuilder>(std::move(*JTMB)); auto DL = jtmb->getDefaultDataLayoutForTarget(); if (!DL) { TI_ERROR("LLVM TargetMachineBuilder has failed when getting data layout."); } return std::make_unique<JITSessionCUDA>(DL.get()); } TLANG_NAMESPACE_END #endif <commit_msg>fix non-cuda build<commit_after>#if defined(min) #undef min #endif #if defined(max) #undef max #endif #include <memory> #include <cuda_runtime_api.h> #include <cuda.h> #include "llvm/ADT/StringRef.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/LLVMContext.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetMachine.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/Transforms/InstCombine/InstCombine.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Scalar/GVN.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include <llvm/Analysis/TargetTransformInfo.h> #include <llvm/Support/TargetRegistry.h> #include <llvm/Target/TargetMachine.h> #include <llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h> #include <taichi/platform/cuda/cuda_utils.h> #include <taichi/platform/cuda/cuda_context.h> #include <taichi/program.h> #include <taichi/context.h> #include <taichi/system/timer.h> #include "../tlang_util.h" #include "jit_session.h" TLANG_NAMESPACE_BEGIN #if defined(TI_WITH_CUDA) class JITModuleCUDA : public JITModule { private: CUmodule module; public: JITModuleCUDA(CUmodule module) : module(module) { } virtual void *lookup_function(const std::string &name) { // auto _ = cuda_context->get_guard(); cuda_context->make_current(); CUfunction func; auto t = Time::get_time(); check_cuda_error(cuModuleGetFunction(&func, module, name.c_str())); t = Time::get_time() - t; TI_TRACE("Kernel {} compilation time: {}ms", name, t * 1000); return (void *)func; } }; class JITSessionCUDA : public JITSession { public: llvm::DataLayout DL; JITSessionCUDA(llvm::DataLayout data_layout) : DL(data_layout) { } virtual JITModule *add_module(std::unique_ptr<llvm::Module> M) override { auto ptx = compile_module_to_ptx(M); // auto _ = cuda_context->get_guard(); cuda_context->make_current(); // Create module for object CUmodule cudaModule; TI_TRACE("PTX size: {:.2f}KB", ptx.size() / 1024.0); auto t = Time::get_time(); TI_TRACE("Loading module..."); auto _ = std::lock_guard<std::mutex>(cuda_context->lock); check_cuda_error( cuModuleLoadDataEx(&cudaModule, ptx.c_str(), 0, nullptr, nullptr)); TI_TRACE("CUDA module load time : {}ms", (Time::get_time() - t) * 1000); // cudaModules.push_back(cudaModule); modules.push_back(std::make_unique<JITModuleCUDA>(cudaModule)); return modules.back().get(); } virtual llvm::DataLayout get_data_layout() override { return DL; } static std::string compile_module_to_ptx( std::unique_ptr<llvm::Module> &module); }; std::string cuda_mattrs() { return "+ptx50"; } std::string JITSessionCUDA::compile_module_to_ptx( std::unique_ptr<llvm::Module> &module) { // Part of this function is borrowed from Halide::CodeGen_PTX_Dev.cpp using namespace llvm; llvm::Triple triple(module->getTargetTriple()); // Allocate target machine std::string err_str; const llvm::Target *target = TargetRegistry::lookupTarget(triple.str(), err_str); TI_ERROR_UNLESS(target, err_str); bool fast_math = get_current_program().config.fast_math; TargetOptions options; options.PrintMachineCode = 0; if (fast_math) { options.AllowFPOpFusion = FPOpFusion::Fast; // See NVPTXISelLowering.cpp // Setting UnsafeFPMath true will result in approximations such as // sqrt.approx in PTX for both f32 and f64 options.UnsafeFPMath = 1; options.NoInfsFPMath = 1; options.NoNaNsFPMath = 1; } else { options.AllowFPOpFusion = FPOpFusion::Strict; options.UnsafeFPMath = 0; options.NoInfsFPMath = 0; options.NoNaNsFPMath = 0; } options.HonorSignDependentRoundingFPMathOption = 0; options.NoZerosInBSS = 0; options.GuaranteedTailCallOpt = 0; options.StackAlignmentOverride = 0; std::unique_ptr<TargetMachine> target_machine(target->createTargetMachine( triple.str(), cuda_context->get_mcpu(), cuda_mattrs(), options, llvm::Reloc::PIC_, llvm::CodeModel::Small, CodeGenOpt::Aggressive)); TI_ERROR_UNLESS(target_machine.get(), "Could not allocate target machine!"); module->setDataLayout(target_machine->createDataLayout()); // Set up passes llvm::SmallString<8> outstr; raw_svector_ostream ostream(outstr); ostream.SetUnbuffered(); legacy::FunctionPassManager function_pass_manager(module.get()); legacy::PassManager module_pass_manager; module_pass_manager.add(createTargetTransformInfoWrapperPass( target_machine->getTargetIRAnalysis())); function_pass_manager.add(createTargetTransformInfoWrapperPass( target_machine->getTargetIRAnalysis())); // NVidia's libdevice library uses a __nvvm_reflect to choose // how to handle denormalized numbers. (The pass replaces calls // to __nvvm_reflect with a constant via a map lookup. The inliner // pass then resolves these situations to fast code, often a single // instruction per decision point.) // // The default is (more) IEEE like handling. FTZ mode flushes them // to zero. (This may only apply to single-precision.) // // The libdevice documentation covers other options for math accuracy // such as replacing division with multiply by the reciprocal and // use of fused-multiply-add, but they do not seem to be controlled // by this __nvvvm_reflect mechanism and may be flags to earlier compiler // passes. const auto kFTZDenorms = 1; // Insert a module flag for the FTZ handling. module->addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", kFTZDenorms); if (kFTZDenorms) { for (llvm::Function &fn : *module) { fn.addFnAttr("nvptx-f32ftz", "true"); } } PassManagerBuilder b; b.OptLevel = 3; b.Inliner = createFunctionInliningPass(b.OptLevel, 0, false); b.LoopVectorize = false; b.SLPVectorize = false; target_machine->adjustPassManager(b); b.populateFunctionPassManager(function_pass_manager); b.populateModulePassManager(module_pass_manager); // Override default to generate verbose assembly. target_machine->Options.MCOptions.AsmVerbose = true; // Output string stream // Ask the target to add backend passes as necessary. bool fail = target_machine->addPassesToEmitFile( module_pass_manager, ostream, nullptr, TargetMachine::CGFT_AssemblyFile, true); TI_ERROR_IF(fail, "Failed to set up passes to emit PTX source\n"); // Run optimization passes function_pass_manager.doInitialization(); for (llvm::Module::iterator i = module->begin(); i != module->end(); i++) { function_pass_manager.run(*i); } function_pass_manager.doFinalization(); module_pass_manager.run(*module); std::string buffer(outstr.begin(), outstr.end()); // Null-terminate the ptx source buffer.push_back(0); return buffer; } std::unique_ptr<JITSession> create_llvm_jit_session_cuda(Arch arch) { TI_ASSERT(arch == Arch::cuda); // TODO: assuming CUDA has the same data layout as the host arch std::unique_ptr<llvm::orc::JITTargetMachineBuilder> jtmb; auto JTMB = llvm::orc::JITTargetMachineBuilder::detectHost(); if (!JTMB) TI_ERROR("LLVM TargetMachineBuilder has failed."); jtmb = std::make_unique<llvm::orc::JITTargetMachineBuilder>(std::move(*JTMB)); auto DL = jtmb->getDefaultDataLayoutForTarget(); if (!DL) { TI_ERROR("LLVM TargetMachineBuilder has failed when getting data layout."); } return std::make_unique<JITSessionCUDA>(DL.get()); } #else std::unique_ptr<JITSession> create_llvm_jit_session_cuda(Arch arch) { TI_NOT_IMPLEMENTED } #endif TLANG_NAMESPACE_END <|endoftext|>
<commit_before>/* Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "ml_metadata/tools/mlmd_bench/fill_types_workload.h" #include <random> #include "absl/memory/memory.h" #include "absl/strings/substitute.h" #include "ml_metadata/metadata_store/metadata_store.h" #include "ml_metadata/metadata_store/types.h" #include "ml_metadata/proto/metadata_store.pb.h" #include "ml_metadata/proto/metadata_store_service.pb.h" #include "ml_metadata/tools/mlmd_bench/proto/mlmd_bench.pb.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/status.h" namespace ml_metadata { namespace { // A template function where the Type can be ArtifactType / ExecutionType / // ContextType. It takes a `type_name` to generate a type and generates number // of properties w.r.t. to the uniform distribution. template <typename Type> void GenerateRandomType(const std::string& type_name, std::uniform_int_distribution<int64>& uniform_dist, std::minstd_rand0& gen, Type* type, int64* curr_bytes) { // The random type name will be a random number. type->set_name(type_name); // The curr_bytes records the total transferred bytes for executing each work // item. *curr_bytes += type->name().size(); // Generates the number of properties for each type // w.r.t. the uniform distribution const int64 num_properties = uniform_dist(gen); for (int64 i = 0; i < num_properties; i++) { (*type->mutable_properties())[absl::StrCat("p-", i)] = STRING; *curr_bytes += absl::StrCat("p-", i).size(); } } // Gets the number of current types(num_curr_type) and total // types(num_total_type) for later insert or update. Also updates the // get_response for later update. Returns detailed error if query executions // failed. tensorflow::Status GetNumberOfTypes(const FillTypesConfig& fill_types_config, MetadataStore*& store, int64& num_curr_type, int64& num_total_type, GetTypeResponseType& get_response) { int64 num_artifact_type = 0, num_execution_type = 0, num_context_type = 0; switch (fill_types_config.specification()) { case FillTypesConfig::ARTIFACT_TYPE: { get_response.emplace<GetArtifactTypesResponse>(); TF_RETURN_IF_ERROR(store->GetArtifactTypes( /*request=*/{}, &absl::get<GetArtifactTypesResponse>(get_response))); num_artifact_type = absl::get<GetArtifactTypesResponse>(get_response) .artifact_types_size(); num_curr_type = num_artifact_type; break; } case FillTypesConfig::EXECUTION_TYPE: { get_response.emplace<GetExecutionTypesResponse>(); TF_RETURN_IF_ERROR(store->GetExecutionTypes( /*request=*/{}, &absl::get<GetExecutionTypesResponse>(get_response))); num_execution_type = absl::get<GetExecutionTypesResponse>(get_response) .execution_types_size(); num_curr_type = num_execution_type; break; } case FillTypesConfig::CONTEXT_TYPE: { get_response.emplace<GetContextTypesResponse>(); TF_RETURN_IF_ERROR(store->GetContextTypes( /*request=*/{}, &absl::get<GetContextTypesResponse>(get_response))); num_context_type = absl::get<GetContextTypesResponse>(get_response).context_types_size(); num_curr_type = num_context_type; break; } default: LOG(FATAL) << "Wrong specification for FillTypes!"; } num_total_type = num_artifact_type + num_execution_type + num_context_type; return tensorflow::Status::OK(); } // Inserts new types into the db if the current types inside db is not enough // for update. Returns detailed error if query executions failed. tensorflow::Status MakeUpTypesForUpdate( const FillTypesConfig& fill_types_config, MetadataStore*& store, int64 num_type_to_make_up) { FillTypesConfig make_up_config = fill_types_config; make_up_config.set_update(false); std::unique_ptr<FillTypes> make_up_fill_types; make_up_fill_types = absl::make_unique<FillTypes>( FillTypes(make_up_config, num_type_to_make_up)); TF_RETURN_IF_ERROR(make_up_fill_types->SetUp(store)); for (int64 i = 0; i < num_type_to_make_up; ++i) { OpStats op_stats; TF_RETURN_IF_ERROR(make_up_fill_types->RunOp(i, store, op_stats)); } return tensorflow::Status::OK(); } // A template function where the Type can be ArtifactType / ExecutionType / // ContextType. // Takes an existed type and generates a new type for later update accordingly. // The updated type will have some new fields added and the number of new added // fields will be generated w.r.t. the uniform distribution. template <typename Type> void UpdateType(std::uniform_int_distribution<int64>& uniform_dist, std::minstd_rand0& gen, const Type& existed_type, Type* updated_type, int64* curr_bytes) { // Except the new added fields, update_type will the same as existed_type. *updated_type = existed_type; *curr_bytes += existed_type.name().size(); for (auto& pair : existed_type.properties()) { // pair.first is the property of existed_type. *curr_bytes += pair.first.size(); } const int64 num_properties = uniform_dist(gen); for (int64 i = 0; i < num_properties; i++) { (*updated_type->mutable_properties())[absl::StrCat("add_p-", i)] = STRING; *curr_bytes += absl::StrCat("add_p-", i).size(); } } } // namespace FillTypes::FillTypes(const FillTypesConfig& fill_types_config, int64 num_operations) : fill_types_config_(fill_types_config), num_operations_(num_operations) { switch (fill_types_config_.specification()) { case FillTypesConfig::ARTIFACT_TYPE: { name_ = "fill_artifact_type"; break; } case FillTypesConfig::EXECUTION_TYPE: { name_ = "fill_execution_type"; break; } case FillTypesConfig::CONTEXT_TYPE: { name_ = "fill_context_type"; break; } default: LOG(FATAL) << "Wrong specification for FillTypes!"; } } tensorflow::Status FillTypes::SetUpImpl(MetadataStore* store) { LOG(INFO) << "Setting up ..."; int64 curr_bytes = 0; // Uniform distribution that describes the number of properties for each // generated types. UniformDistribution num_properties = fill_types_config_.num_properties(); int64 min = num_properties.minimum(); int64 max = num_properties.maximum(); std::uniform_int_distribution<int64> uniform_dist{min, max}; // The seed for the random generator is the time when the FillTypes is // created. std::minstd_rand0 gen(absl::ToUnixMillis(absl::Now())); // Gets the number of current types(num_curr_type) and total // types(num_total_type) for later insert or update. int64 num_curr_type = 0, num_total_type = 0; GetTypeResponseType get_response; TF_RETURN_IF_ERROR(GetNumberOfTypes(fill_types_config_, store, num_curr_type, num_total_type, get_response)); // If the number of current types is less than the update number of // operations, calls MakeUpTypesForUpdate() for inserting new types into the // db for later update. if (fill_types_config_.update() && num_curr_type < num_operations_) { int64 num_type_to_make_up = num_operations_ - num_curr_type; TF_RETURN_IF_ERROR( MakeUpTypesForUpdate(fill_types_config_, store, num_type_to_make_up)); // Updates the get_response to contain the up-to-date types inside db for // later update. TF_RETURN_IF_ERROR(GetNumberOfTypes(fill_types_config_, store, num_curr_type, num_total_type, get_response)); } for (int64 i = num_total_type; i < num_total_type + num_operations_; i++) { curr_bytes = 0; int64 update_type_index = i - num_total_type; FillTypeWorkItemType put_request; const std::string type_name = absl::StrCat("type_", i); switch (fill_types_config_.specification()) { case FillTypesConfig::ARTIFACT_TYPE: { put_request.emplace<PutArtifactTypeRequest>(); if (fill_types_config_.update()) { // For update purpose, the can_add_fields field should be set to true. absl::get<PutArtifactTypeRequest>(put_request) .set_can_add_fields(true); UpdateType<ArtifactType>( uniform_dist, gen, absl::get<GetArtifactTypesResponse>(get_response) .artifact_types()[update_type_index], absl::get<PutArtifactTypeRequest>(put_request) .mutable_artifact_type(), &curr_bytes); } else { GenerateRandomType<ArtifactType>( type_name, uniform_dist, gen, absl::get<PutArtifactTypeRequest>(put_request) .mutable_artifact_type(), &curr_bytes); } break; } case FillTypesConfig::EXECUTION_TYPE: { put_request.emplace<PutExecutionTypeRequest>(); if (fill_types_config_.update()) { // For update purpose, the can_add_fields field should be set to true. absl::get<PutExecutionTypeRequest>(put_request) .set_can_add_fields(true); UpdateType<ExecutionType>( uniform_dist, gen, absl::get<GetExecutionTypesResponse>(get_response) .execution_types()[update_type_index], absl::get<PutExecutionTypeRequest>(put_request) .mutable_execution_type(), &curr_bytes); } else { GenerateRandomType<ExecutionType>( type_name, uniform_dist, gen, absl::get<PutExecutionTypeRequest>(put_request) .mutable_execution_type(), &curr_bytes); } break; } case FillTypesConfig::CONTEXT_TYPE: { put_request.emplace<PutContextTypeRequest>(); if (fill_types_config_.update()) { // For update purpose, the can_add_fields field should be set to true. absl::get<PutContextTypeRequest>(put_request) .set_can_add_fields(true); UpdateType<ContextType>( uniform_dist, gen, absl::get<GetContextTypesResponse>(get_response) .context_types()[update_type_index], absl::get<PutContextTypeRequest>(put_request) .mutable_context_type(), &curr_bytes); } else { GenerateRandomType<ContextType>( type_name, uniform_dist, gen, absl::get<PutContextTypeRequest>(put_request) .mutable_context_type(), &curr_bytes); } break; } default: return tensorflow::errors::InvalidArgument("Wrong specification!"); } // Updates work_items_. work_items_.emplace_back(put_request, curr_bytes); } return tensorflow::Status::OK(); } // Executions of work items. tensorflow::Status FillTypes::RunOpImpl(int64 i, MetadataStore* store) { switch (fill_types_config_.specification()) { case FillTypesConfig::ARTIFACT_TYPE: { PutArtifactTypeRequest put_request = absl::get<PutArtifactTypeRequest>(work_items_[i].first); PutArtifactTypeResponse put_response; return store->PutArtifactType(put_request, &put_response); } case FillTypesConfig::EXECUTION_TYPE: { PutExecutionTypeRequest put_request = absl::get<PutExecutionTypeRequest>(work_items_[i].first); PutExecutionTypeResponse put_response; return store->PutExecutionType(put_request, &put_response); } case FillTypesConfig::CONTEXT_TYPE: { PutContextTypeRequest put_request = absl::get<PutContextTypeRequest>(work_items_[i].first); PutContextTypeResponse put_response; return store->PutContextType(put_request, &put_response); } default: return tensorflow::errors::InvalidArgument("Wrong specification!"); } return tensorflow::errors::InvalidArgument( "Cannot execute the query due to wrong specification!"); } tensorflow::Status FillTypes::TearDownImpl() { work_items_.clear(); return tensorflow::Status::OK(); } std::string FillTypes::GetName() { return name_; } } // namespace ml_metadata <commit_msg>Fixs GetNumberOfTypes() for update mode of FillTypes.<commit_after>/* Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "ml_metadata/tools/mlmd_bench/fill_types_workload.h" #include <random> #include "absl/memory/memory.h" #include "absl/strings/substitute.h" #include "ml_metadata/metadata_store/metadata_store.h" #include "ml_metadata/metadata_store/types.h" #include "ml_metadata/proto/metadata_store.pb.h" #include "ml_metadata/proto/metadata_store_service.pb.h" #include "ml_metadata/tools/mlmd_bench/proto/mlmd_bench.pb.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/status.h" namespace ml_metadata { namespace { // A template function where the Type can be ArtifactType / ExecutionType / // ContextType. It takes a `type_name` to generate a type and generates number // of properties w.r.t. to the uniform distribution. template <typename Type> void GenerateRandomType(const std::string& type_name, std::uniform_int_distribution<int64>& uniform_dist, std::minstd_rand0& gen, Type* type, int64* curr_bytes) { // The random type name will be a random number. type->set_name(type_name); // The curr_bytes records the total transferred bytes for executing each work // item. *curr_bytes += type->name().size(); // Generates the number of properties for each type // w.r.t. the uniform distribution const int64 num_properties = uniform_dist(gen); for (int64 i = 0; i < num_properties; i++) { (*type->mutable_properties())[absl::StrCat("p-", i)] = STRING; *curr_bytes += absl::StrCat("p-", i).size(); } } // Gets the number of current types(num_curr_type) and total // types(num_total_type) for later insert or update. Also updates the // get_response for later update. Returns detailed error if query executions // failed. tensorflow::Status GetNumberOfTypes(const FillTypesConfig& fill_types_config, MetadataStore* store, int64& num_curr_type, int64& num_total_type, GetTypeResponseType& get_response) { GetArtifactTypesResponse get_artifact_type_response; TF_RETURN_IF_ERROR(store->GetArtifactTypes( /*request=*/{}, &get_artifact_type_response)); int64 num_artifact_type = get_artifact_type_response.artifact_types_size(); GetExecutionTypesResponse get_execution_type_response; TF_RETURN_IF_ERROR(store->GetExecutionTypes( /*request=*/{}, &get_execution_type_response)); int64 num_execution_type = get_execution_type_response.execution_types_size(); GetContextTypesResponse get_context_type_response; TF_RETURN_IF_ERROR(store->GetContextTypes( /*request=*/{}, &get_context_type_response)); int64 num_context_type = get_context_type_response.context_types_size(); switch (fill_types_config.specification()) { case FillTypesConfig::ARTIFACT_TYPE: { num_curr_type = num_artifact_type; get_response.emplace<GetArtifactTypesResponse>( get_artifact_type_response); break; } case FillTypesConfig::EXECUTION_TYPE: { num_curr_type = num_execution_type; get_response.emplace<GetExecutionTypesResponse>( get_execution_type_response); break; } case FillTypesConfig::CONTEXT_TYPE: { num_curr_type = num_context_type; get_response.emplace<GetContextTypesResponse>(get_context_type_response); break; } default: LOG(FATAL) << "Wrong specification for FillTypes!"; } num_total_type = num_artifact_type + num_execution_type + num_context_type; return tensorflow::Status::OK(); } // Inserts new types into the db if the current types inside db is not enough // for update. Returns detailed error if query executions failed. tensorflow::Status MakeUpTypesForUpdate( const FillTypesConfig& fill_types_config, MetadataStore* store, int64 num_type_to_make_up) { FillTypesConfig make_up_config = fill_types_config; make_up_config.set_update(false); std::unique_ptr<FillTypes> make_up_fill_types; make_up_fill_types = absl::make_unique<FillTypes>( FillTypes(make_up_config, num_type_to_make_up)); TF_RETURN_IF_ERROR(make_up_fill_types->SetUp(store)); for (int64 i = 0; i < num_type_to_make_up; ++i) { OpStats op_stats; TF_RETURN_IF_ERROR(make_up_fill_types->RunOp(i, store, op_stats)); } return tensorflow::Status::OK(); } // A template function where the Type can be ArtifactType / ExecutionType / // ContextType. // Takes an existed type and generates a new type for later update accordingly. // The updated type will have some new fields added and the number of new added // fields will be generated w.r.t. the uniform distribution. template <typename Type> void UpdateType(std::uniform_int_distribution<int64>& uniform_dist, std::minstd_rand0& gen, const Type& existed_type, Type* updated_type, int64* curr_bytes) { // Except the new added fields, update_type will the same as existed_type. *updated_type = existed_type; *curr_bytes += existed_type.name().size(); for (auto& pair : existed_type.properties()) { // pair.first is the property of existed_type. *curr_bytes += pair.first.size(); } const int64 num_properties = uniform_dist(gen); for (int64 i = 0; i < num_properties; i++) { (*updated_type->mutable_properties())[absl::StrCat("add_p-", i)] = STRING; *curr_bytes += absl::StrCat("add_p-", i).size(); } } } // namespace FillTypes::FillTypes(const FillTypesConfig& fill_types_config, int64 num_operations) : fill_types_config_(fill_types_config), num_operations_(num_operations) { switch (fill_types_config_.specification()) { case FillTypesConfig::ARTIFACT_TYPE: { name_ = "fill_artifact_type"; break; } case FillTypesConfig::EXECUTION_TYPE: { name_ = "fill_execution_type"; break; } case FillTypesConfig::CONTEXT_TYPE: { name_ = "fill_context_type"; break; } default: LOG(FATAL) << "Wrong specification for FillTypes!"; } if (fill_types_config_.update()) { name_ += "(update)"; } } tensorflow::Status FillTypes::SetUpImpl(MetadataStore* store) { LOG(INFO) << "Setting up ..."; int64 curr_bytes = 0; // Uniform distribution that describes the number of properties for each // generated types. UniformDistribution num_properties = fill_types_config_.num_properties(); int64 min = num_properties.minimum(); int64 max = num_properties.maximum(); std::uniform_int_distribution<int64> uniform_dist{min, max}; // The seed for the random generator is the time when the FillTypes is // created. std::minstd_rand0 gen(absl::ToUnixMillis(absl::Now())); // Gets the number of current types(num_curr_type) and total // types(num_total_type) for later insert or update. int64 num_curr_type = 0, num_total_type = 0; GetTypeResponseType get_response; TF_RETURN_IF_ERROR(GetNumberOfTypes(fill_types_config_, store, num_curr_type, num_total_type, get_response)); // If the number of current types is less than the update number of // operations, calls MakeUpTypesForUpdate() for inserting new types into the // db for later update. if (fill_types_config_.update() && num_curr_type < num_operations_) { int64 num_type_to_make_up = num_operations_ - num_curr_type; TF_RETURN_IF_ERROR( MakeUpTypesForUpdate(fill_types_config_, store, num_type_to_make_up)); // Updates the get_response to contain the up-to-date types inside db for // later update. TF_RETURN_IF_ERROR(GetNumberOfTypes(fill_types_config_, store, num_curr_type, num_total_type, get_response)); } for (int64 i = num_total_type; i < num_total_type + num_operations_; i++) { curr_bytes = 0; int64 update_type_index = i - num_total_type; FillTypeWorkItemType put_request; const std::string type_name = absl::StrCat("type_", i); switch (fill_types_config_.specification()) { case FillTypesConfig::ARTIFACT_TYPE: { put_request.emplace<PutArtifactTypeRequest>(); if (fill_types_config_.update()) { // For update purpose, the can_add_fields field should be set to true. absl::get<PutArtifactTypeRequest>(put_request) .set_can_add_fields(true); UpdateType<ArtifactType>( uniform_dist, gen, absl::get<GetArtifactTypesResponse>(get_response) .artifact_types()[update_type_index], absl::get<PutArtifactTypeRequest>(put_request) .mutable_artifact_type(), &curr_bytes); } else { GenerateRandomType<ArtifactType>( type_name, uniform_dist, gen, absl::get<PutArtifactTypeRequest>(put_request) .mutable_artifact_type(), &curr_bytes); } break; } case FillTypesConfig::EXECUTION_TYPE: { put_request.emplace<PutExecutionTypeRequest>(); if (fill_types_config_.update()) { // For update purpose, the can_add_fields field should be set to true. absl::get<PutExecutionTypeRequest>(put_request) .set_can_add_fields(true); UpdateType<ExecutionType>( uniform_dist, gen, absl::get<GetExecutionTypesResponse>(get_response) .execution_types()[update_type_index], absl::get<PutExecutionTypeRequest>(put_request) .mutable_execution_type(), &curr_bytes); } else { GenerateRandomType<ExecutionType>( type_name, uniform_dist, gen, absl::get<PutExecutionTypeRequest>(put_request) .mutable_execution_type(), &curr_bytes); } break; } case FillTypesConfig::CONTEXT_TYPE: { put_request.emplace<PutContextTypeRequest>(); if (fill_types_config_.update()) { // For update purpose, the can_add_fields field should be set to true. absl::get<PutContextTypeRequest>(put_request) .set_can_add_fields(true); UpdateType<ContextType>( uniform_dist, gen, absl::get<GetContextTypesResponse>(get_response) .context_types()[update_type_index], absl::get<PutContextTypeRequest>(put_request) .mutable_context_type(), &curr_bytes); } else { GenerateRandomType<ContextType>( type_name, uniform_dist, gen, absl::get<PutContextTypeRequest>(put_request) .mutable_context_type(), &curr_bytes); } break; } default: return tensorflow::errors::InvalidArgument("Wrong specification!"); } // Updates work_items_. work_items_.emplace_back(put_request, curr_bytes); } return tensorflow::Status::OK(); } // Executions of work items. tensorflow::Status FillTypes::RunOpImpl(int64 i, MetadataStore* store) { switch (fill_types_config_.specification()) { case FillTypesConfig::ARTIFACT_TYPE: { PutArtifactTypeRequest put_request = absl::get<PutArtifactTypeRequest>(work_items_[i].first); PutArtifactTypeResponse put_response; return store->PutArtifactType(put_request, &put_response); } case FillTypesConfig::EXECUTION_TYPE: { PutExecutionTypeRequest put_request = absl::get<PutExecutionTypeRequest>(work_items_[i].first); PutExecutionTypeResponse put_response; return store->PutExecutionType(put_request, &put_response); } case FillTypesConfig::CONTEXT_TYPE: { PutContextTypeRequest put_request = absl::get<PutContextTypeRequest>(work_items_[i].first); PutContextTypeResponse put_response; return store->PutContextType(put_request, &put_response); } default: return tensorflow::errors::InvalidArgument("Wrong specification!"); } return tensorflow::errors::InvalidArgument( "Cannot execute the query due to wrong specification!"); } tensorflow::Status FillTypes::TearDownImpl() { work_items_.clear(); return tensorflow::Status::OK(); } std::string FillTypes::GetName() { return name_; } } // namespace ml_metadata <|endoftext|>
<commit_before>//===-- tsan_interface_ann.cc -----------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of ThreadSanitizer (TSan), a race detector. // //===----------------------------------------------------------------------===// #include "tsan_interface_ann.h" #include "tsan_mutex.h" #include "tsan_placement_new.h" #include "tsan_report.h" #include "tsan_rtl.h" #include "tsan_mman.h" #include "tsan_flags.h" #define CALLERPC ((uptr)__builtin_return_address(0)) using namespace __tsan; // NOLINT namespace __tsan { class ScopedAnnotation { public: ScopedAnnotation(ThreadState *thr, const char *aname, const char *f, int l, uptr pc) : thr_(thr) , in_rtl_(thr->in_rtl) { CHECK_EQ(thr_->in_rtl, 0); FuncEntry(thr_, pc); thr_->in_rtl++; DPrintf("#%d: annotation %s() %s:%d\n", thr_->tid, aname, f, l); } ~ScopedAnnotation() { thr_->in_rtl--; CHECK_EQ(in_rtl_, thr_->in_rtl); FuncExit(thr_); } private: ThreadState *const thr_; const int in_rtl_; }; #define SCOPED_ANNOTATION(typ) \ if (!flags()->enable_annotations) \ return; \ ThreadState *thr = cur_thread(); \ StatInc(thr, StatAnnotation); \ StatInc(thr, Stat##typ); \ ScopedAnnotation sa(thr, __FUNCTION__, f, l, \ (uptr)__builtin_return_address(0)); \ const uptr pc = (uptr)&__FUNCTION__; \ (void)pc; \ /**/ static const int kMaxDescLen = 128; struct ExpectRace { ExpectRace *next; ExpectRace *prev; int hitcount; uptr addr; uptr size; char *file; int line; char desc[kMaxDescLen]; }; struct DynamicAnnContext { Mutex mtx; ExpectRace expect; ExpectRace benign; DynamicAnnContext() : mtx(MutexTypeAnnotations, StatMtxAnnotations) { } }; static DynamicAnnContext *dyn_ann_ctx; static char dyn_ann_ctx_placeholder[sizeof(DynamicAnnContext)] ALIGN(64); static void AddExpectRace(ExpectRace *list, char *f, int l, uptr addr, uptr size, char *desc) { ExpectRace *race = list->next; for (; race != list; race = race->next) { if (race->addr == addr && race->size == size) return; } race = (ExpectRace*)internal_alloc(MBlockExpectRace, sizeof(ExpectRace)); race->hitcount = 0; race->addr = addr; race->size = size; race->file = f; race->line = l; race->desc[0] = 0; if (desc) { int i = 0; for (; i < kMaxDescLen - 1 && desc[i]; i++) race->desc[i] = desc[i]; race->desc[i] = 0; } race->prev = list; race->next = list->next; race->next->prev = race; list->next = race; } static ExpectRace *FindRace(ExpectRace *list, uptr addr, uptr size) { for (ExpectRace *race = list->next; race != list; race = race->next) { uptr maxbegin = max(race->addr, addr); uptr minend = min(race->addr + race->size, addr + size); if (maxbegin < minend) return race; } return 0; } static bool CheckContains(ExpectRace *list, uptr addr, uptr size) { ExpectRace *race = FindRace(list, addr, size); if (race == 0) return false; DPrintf("Hit expected/benign race: %s addr=%lx:%d %s:%d\n", race->desc, race->addr, (int)race->size, race->file, race->line); race->hitcount++; return true; } static void InitList(ExpectRace *list) { list->next = list; list->prev = list; } void InitializeDynamicAnnotations() { dyn_ann_ctx = new(dyn_ann_ctx_placeholder) DynamicAnnContext; InitList(&dyn_ann_ctx->expect); InitList(&dyn_ann_ctx->benign); } bool IsExpectedReport(uptr addr, uptr size) { Lock lock(&dyn_ann_ctx->mtx); if (CheckContains(&dyn_ann_ctx->expect, addr, size)) return true; if (CheckContains(&dyn_ann_ctx->benign, addr, size)) return true; return false; } } // namespace __tsan using namespace __tsan; // NOLINT extern "C" { void AnnotateHappensBefore(char *f, int l, uptr addr) { SCOPED_ANNOTATION(AnnotateHappensBefore); Release(cur_thread(), CALLERPC, addr); } void AnnotateHappensAfter(char *f, int l, uptr addr) { SCOPED_ANNOTATION(AnnotateHappensAfter); Acquire(cur_thread(), CALLERPC, addr); } void AnnotateCondVarSignal(char *f, int l, uptr cv) { SCOPED_ANNOTATION(AnnotateCondVarSignal); } void AnnotateCondVarSignalAll(char *f, int l, uptr cv) { SCOPED_ANNOTATION(AnnotateCondVarSignalAll); } void AnnotateMutexIsNotPHB(char *f, int l, uptr mu) { SCOPED_ANNOTATION(AnnotateMutexIsNotPHB); } void AnnotateCondVarWait(char *f, int l, uptr cv, uptr lock) { SCOPED_ANNOTATION(AnnotateCondVarWait); } void AnnotateRWLockCreate(char *f, int l, uptr lock) { SCOPED_ANNOTATION(AnnotateRWLockCreate); } void AnnotateRWLockDestroy(char *f, int l, uptr lock) { SCOPED_ANNOTATION(AnnotateRWLockDestroy); } void AnnotateRWLockAcquired(char *f, int l, uptr lock, uptr is_w) { SCOPED_ANNOTATION(AnnotateRWLockAcquired); } void AnnotateRWLockReleased(char *f, int l, uptr lock, uptr is_w) { SCOPED_ANNOTATION(AnnotateRWLockReleased); } void AnnotateTraceMemory(char *f, int l, uptr mem) { SCOPED_ANNOTATION(AnnotateTraceMemory); } void AnnotateFlushState(char *f, int l) { SCOPED_ANNOTATION(AnnotateFlushState); } void AnnotateNewMemory(char *f, int l, uptr mem, uptr size) { SCOPED_ANNOTATION(AnnotateNewMemory); } void AnnotateNoOp(char *f, int l, uptr mem) { SCOPED_ANNOTATION(AnnotateNoOp); } static void ReportMissedExpectedRace(ExpectRace *race) { Printf("==================\n"); Printf("WARNING: ThreadSanitizer: missed expected data race\n"); Printf(" %s addr=%lx %s:%d\n", race->desc, race->addr, race->file, race->line); Printf("==================\n"); } void AnnotateFlushExpectedRaces(char *f, int l) { SCOPED_ANNOTATION(AnnotateFlushExpectedRaces); Lock lock(&dyn_ann_ctx->mtx); while (dyn_ann_ctx->expect.next != &dyn_ann_ctx->expect) { ExpectRace *race = dyn_ann_ctx->expect.next; if (race->hitcount == 0) { CTX()->nmissed_expected++; ReportMissedExpectedRace(race); } race->prev->next = race->next; race->next->prev = race->prev; internal_free(race); } } void AnnotateEnableRaceDetection(char *f, int l, int enable) { SCOPED_ANNOTATION(AnnotateEnableRaceDetection); // FIXME: Reconsider this functionality later. It may be irrelevant. } void AnnotateMutexIsUsedAsCondVar(char *f, int l, uptr mu) { SCOPED_ANNOTATION(AnnotateMutexIsUsedAsCondVar); } void AnnotatePCQGet(char *f, int l, uptr pcq) { SCOPED_ANNOTATION(AnnotatePCQGet); } void AnnotatePCQPut(char *f, int l, uptr pcq) { SCOPED_ANNOTATION(AnnotatePCQPut); } void AnnotatePCQDestroy(char *f, int l, uptr pcq) { SCOPED_ANNOTATION(AnnotatePCQDestroy); } void AnnotatePCQCreate(char *f, int l, uptr pcq) { SCOPED_ANNOTATION(AnnotatePCQCreate); } void AnnotateExpectRace(char *f, int l, uptr mem, char *desc) { SCOPED_ANNOTATION(AnnotateExpectRace); Lock lock(&dyn_ann_ctx->mtx); AddExpectRace(&dyn_ann_ctx->expect, f, l, mem, 1, desc); DPrintf("Add expected race: %s addr=%lx %s:%d\n", desc, mem, f, l); } static void BenignRaceImpl(char *f, int l, uptr mem, uptr size, char *desc) { Lock lock(&dyn_ann_ctx->mtx); AddExpectRace(&dyn_ann_ctx->benign, f, l, mem, size, desc); DPrintf("Add benign race: %s addr=%lx %s:%d\n", desc, mem, f, l); } // FIXME: Turn it off later. WTF is benign race?1?? Go talk to Hans Boehm. void AnnotateBenignRaceSized(char *f, int l, uptr mem, uptr size, char *desc) { SCOPED_ANNOTATION(AnnotateBenignRaceSized); BenignRaceImpl(f, l, mem, size, desc); } void AnnotateBenignRace(char *f, int l, uptr mem, char *desc) { SCOPED_ANNOTATION(AnnotateBenignRace); BenignRaceImpl(f, l, mem, 1, desc); } void AnnotateIgnoreReadsBegin(char *f, int l) { SCOPED_ANNOTATION(AnnotateIgnoreReadsBegin); IgnoreCtl(cur_thread(), false, true); } void AnnotateIgnoreReadsEnd(char *f, int l) { SCOPED_ANNOTATION(AnnotateIgnoreReadsEnd); IgnoreCtl(cur_thread(), false, false); } void AnnotateIgnoreWritesBegin(char *f, int l) { SCOPED_ANNOTATION(AnnotateIgnoreWritesBegin); IgnoreCtl(cur_thread(), true, true); } void AnnotateIgnoreWritesEnd(char *f, int l) { SCOPED_ANNOTATION(AnnotateIgnoreWritesEnd); IgnoreCtl(cur_thread(), true, false); } void AnnotatePublishMemoryRange(char *f, int l, uptr addr, uptr size) { SCOPED_ANNOTATION(AnnotatePublishMemoryRange); } void AnnotateUnpublishMemoryRange(char *f, int l, uptr addr, uptr size) { SCOPED_ANNOTATION(AnnotateUnpublishMemoryRange); } void AnnotateThreadName(char *f, int l, char *name) { SCOPED_ANNOTATION(AnnotateThreadName); } void WTFAnnotateHappensBefore(char *f, int l, uptr addr) { SCOPED_ANNOTATION(AnnotateHappensBefore); } void WTFAnnotateHappensAfter(char *f, int l, uptr addr) { SCOPED_ANNOTATION(AnnotateHappensAfter); } void WTFAnnotateBenignRaceSized(char *f, int l, uptr mem, uptr sz, char *desc) { SCOPED_ANNOTATION(AnnotateBenignRaceSized); } int RunningOnValgrind() { return 0; } double ValgrindSlowdown(void) { return 10.0; } const char *ThreadSanitizerQuery(const char *query) { if (internal_strcmp(query, "pure_happens_before") == 0) return "1"; else return "0"; } } // extern "C" <commit_msg>tsan: ValgrindSlowdown() should be weak for some time<commit_after>//===-- tsan_interface_ann.cc -----------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of ThreadSanitizer (TSan), a race detector. // //===----------------------------------------------------------------------===// #include "tsan_interface_ann.h" #include "tsan_mutex.h" #include "tsan_placement_new.h" #include "tsan_report.h" #include "tsan_rtl.h" #include "tsan_mman.h" #include "tsan_flags.h" #define CALLERPC ((uptr)__builtin_return_address(0)) using namespace __tsan; // NOLINT namespace __tsan { class ScopedAnnotation { public: ScopedAnnotation(ThreadState *thr, const char *aname, const char *f, int l, uptr pc) : thr_(thr) , in_rtl_(thr->in_rtl) { CHECK_EQ(thr_->in_rtl, 0); FuncEntry(thr_, pc); thr_->in_rtl++; DPrintf("#%d: annotation %s() %s:%d\n", thr_->tid, aname, f, l); } ~ScopedAnnotation() { thr_->in_rtl--; CHECK_EQ(in_rtl_, thr_->in_rtl); FuncExit(thr_); } private: ThreadState *const thr_; const int in_rtl_; }; #define SCOPED_ANNOTATION(typ) \ if (!flags()->enable_annotations) \ return; \ ThreadState *thr = cur_thread(); \ StatInc(thr, StatAnnotation); \ StatInc(thr, Stat##typ); \ ScopedAnnotation sa(thr, __FUNCTION__, f, l, \ (uptr)__builtin_return_address(0)); \ const uptr pc = (uptr)&__FUNCTION__; \ (void)pc; \ /**/ static const int kMaxDescLen = 128; struct ExpectRace { ExpectRace *next; ExpectRace *prev; int hitcount; uptr addr; uptr size; char *file; int line; char desc[kMaxDescLen]; }; struct DynamicAnnContext { Mutex mtx; ExpectRace expect; ExpectRace benign; DynamicAnnContext() : mtx(MutexTypeAnnotations, StatMtxAnnotations) { } }; static DynamicAnnContext *dyn_ann_ctx; static char dyn_ann_ctx_placeholder[sizeof(DynamicAnnContext)] ALIGN(64); static void AddExpectRace(ExpectRace *list, char *f, int l, uptr addr, uptr size, char *desc) { ExpectRace *race = list->next; for (; race != list; race = race->next) { if (race->addr == addr && race->size == size) return; } race = (ExpectRace*)internal_alloc(MBlockExpectRace, sizeof(ExpectRace)); race->hitcount = 0; race->addr = addr; race->size = size; race->file = f; race->line = l; race->desc[0] = 0; if (desc) { int i = 0; for (; i < kMaxDescLen - 1 && desc[i]; i++) race->desc[i] = desc[i]; race->desc[i] = 0; } race->prev = list; race->next = list->next; race->next->prev = race; list->next = race; } static ExpectRace *FindRace(ExpectRace *list, uptr addr, uptr size) { for (ExpectRace *race = list->next; race != list; race = race->next) { uptr maxbegin = max(race->addr, addr); uptr minend = min(race->addr + race->size, addr + size); if (maxbegin < minend) return race; } return 0; } static bool CheckContains(ExpectRace *list, uptr addr, uptr size) { ExpectRace *race = FindRace(list, addr, size); if (race == 0) return false; DPrintf("Hit expected/benign race: %s addr=%lx:%d %s:%d\n", race->desc, race->addr, (int)race->size, race->file, race->line); race->hitcount++; return true; } static void InitList(ExpectRace *list) { list->next = list; list->prev = list; } void InitializeDynamicAnnotations() { dyn_ann_ctx = new(dyn_ann_ctx_placeholder) DynamicAnnContext; InitList(&dyn_ann_ctx->expect); InitList(&dyn_ann_ctx->benign); } bool IsExpectedReport(uptr addr, uptr size) { Lock lock(&dyn_ann_ctx->mtx); if (CheckContains(&dyn_ann_ctx->expect, addr, size)) return true; if (CheckContains(&dyn_ann_ctx->benign, addr, size)) return true; return false; } } // namespace __tsan using namespace __tsan; // NOLINT extern "C" { void AnnotateHappensBefore(char *f, int l, uptr addr) { SCOPED_ANNOTATION(AnnotateHappensBefore); Release(cur_thread(), CALLERPC, addr); } void AnnotateHappensAfter(char *f, int l, uptr addr) { SCOPED_ANNOTATION(AnnotateHappensAfter); Acquire(cur_thread(), CALLERPC, addr); } void AnnotateCondVarSignal(char *f, int l, uptr cv) { SCOPED_ANNOTATION(AnnotateCondVarSignal); } void AnnotateCondVarSignalAll(char *f, int l, uptr cv) { SCOPED_ANNOTATION(AnnotateCondVarSignalAll); } void AnnotateMutexIsNotPHB(char *f, int l, uptr mu) { SCOPED_ANNOTATION(AnnotateMutexIsNotPHB); } void AnnotateCondVarWait(char *f, int l, uptr cv, uptr lock) { SCOPED_ANNOTATION(AnnotateCondVarWait); } void AnnotateRWLockCreate(char *f, int l, uptr lock) { SCOPED_ANNOTATION(AnnotateRWLockCreate); } void AnnotateRWLockDestroy(char *f, int l, uptr lock) { SCOPED_ANNOTATION(AnnotateRWLockDestroy); } void AnnotateRWLockAcquired(char *f, int l, uptr lock, uptr is_w) { SCOPED_ANNOTATION(AnnotateRWLockAcquired); } void AnnotateRWLockReleased(char *f, int l, uptr lock, uptr is_w) { SCOPED_ANNOTATION(AnnotateRWLockReleased); } void AnnotateTraceMemory(char *f, int l, uptr mem) { SCOPED_ANNOTATION(AnnotateTraceMemory); } void AnnotateFlushState(char *f, int l) { SCOPED_ANNOTATION(AnnotateFlushState); } void AnnotateNewMemory(char *f, int l, uptr mem, uptr size) { SCOPED_ANNOTATION(AnnotateNewMemory); } void AnnotateNoOp(char *f, int l, uptr mem) { SCOPED_ANNOTATION(AnnotateNoOp); } static void ReportMissedExpectedRace(ExpectRace *race) { Printf("==================\n"); Printf("WARNING: ThreadSanitizer: missed expected data race\n"); Printf(" %s addr=%lx %s:%d\n", race->desc, race->addr, race->file, race->line); Printf("==================\n"); } void AnnotateFlushExpectedRaces(char *f, int l) { SCOPED_ANNOTATION(AnnotateFlushExpectedRaces); Lock lock(&dyn_ann_ctx->mtx); while (dyn_ann_ctx->expect.next != &dyn_ann_ctx->expect) { ExpectRace *race = dyn_ann_ctx->expect.next; if (race->hitcount == 0) { CTX()->nmissed_expected++; ReportMissedExpectedRace(race); } race->prev->next = race->next; race->next->prev = race->prev; internal_free(race); } } void AnnotateEnableRaceDetection(char *f, int l, int enable) { SCOPED_ANNOTATION(AnnotateEnableRaceDetection); // FIXME: Reconsider this functionality later. It may be irrelevant. } void AnnotateMutexIsUsedAsCondVar(char *f, int l, uptr mu) { SCOPED_ANNOTATION(AnnotateMutexIsUsedAsCondVar); } void AnnotatePCQGet(char *f, int l, uptr pcq) { SCOPED_ANNOTATION(AnnotatePCQGet); } void AnnotatePCQPut(char *f, int l, uptr pcq) { SCOPED_ANNOTATION(AnnotatePCQPut); } void AnnotatePCQDestroy(char *f, int l, uptr pcq) { SCOPED_ANNOTATION(AnnotatePCQDestroy); } void AnnotatePCQCreate(char *f, int l, uptr pcq) { SCOPED_ANNOTATION(AnnotatePCQCreate); } void AnnotateExpectRace(char *f, int l, uptr mem, char *desc) { SCOPED_ANNOTATION(AnnotateExpectRace); Lock lock(&dyn_ann_ctx->mtx); AddExpectRace(&dyn_ann_ctx->expect, f, l, mem, 1, desc); DPrintf("Add expected race: %s addr=%lx %s:%d\n", desc, mem, f, l); } static void BenignRaceImpl(char *f, int l, uptr mem, uptr size, char *desc) { Lock lock(&dyn_ann_ctx->mtx); AddExpectRace(&dyn_ann_ctx->benign, f, l, mem, size, desc); DPrintf("Add benign race: %s addr=%lx %s:%d\n", desc, mem, f, l); } // FIXME: Turn it off later. WTF is benign race?1?? Go talk to Hans Boehm. void AnnotateBenignRaceSized(char *f, int l, uptr mem, uptr size, char *desc) { SCOPED_ANNOTATION(AnnotateBenignRaceSized); BenignRaceImpl(f, l, mem, size, desc); } void AnnotateBenignRace(char *f, int l, uptr mem, char *desc) { SCOPED_ANNOTATION(AnnotateBenignRace); BenignRaceImpl(f, l, mem, 1, desc); } void AnnotateIgnoreReadsBegin(char *f, int l) { SCOPED_ANNOTATION(AnnotateIgnoreReadsBegin); IgnoreCtl(cur_thread(), false, true); } void AnnotateIgnoreReadsEnd(char *f, int l) { SCOPED_ANNOTATION(AnnotateIgnoreReadsEnd); IgnoreCtl(cur_thread(), false, false); } void AnnotateIgnoreWritesBegin(char *f, int l) { SCOPED_ANNOTATION(AnnotateIgnoreWritesBegin); IgnoreCtl(cur_thread(), true, true); } void AnnotateIgnoreWritesEnd(char *f, int l) { SCOPED_ANNOTATION(AnnotateIgnoreWritesEnd); IgnoreCtl(cur_thread(), true, false); } void AnnotatePublishMemoryRange(char *f, int l, uptr addr, uptr size) { SCOPED_ANNOTATION(AnnotatePublishMemoryRange); } void AnnotateUnpublishMemoryRange(char *f, int l, uptr addr, uptr size) { SCOPED_ANNOTATION(AnnotateUnpublishMemoryRange); } void AnnotateThreadName(char *f, int l, char *name) { SCOPED_ANNOTATION(AnnotateThreadName); } void WTFAnnotateHappensBefore(char *f, int l, uptr addr) { SCOPED_ANNOTATION(AnnotateHappensBefore); } void WTFAnnotateHappensAfter(char *f, int l, uptr addr) { SCOPED_ANNOTATION(AnnotateHappensAfter); } void WTFAnnotateBenignRaceSized(char *f, int l, uptr mem, uptr sz, char *desc) { SCOPED_ANNOTATION(AnnotateBenignRaceSized); } int RunningOnValgrind() { return 0; } double __attribute__((weak)) ValgrindSlowdown(void) { return 10.0; } const char *ThreadSanitizerQuery(const char *query) { if (internal_strcmp(query, "pure_happens_before") == 0) return "1"; else return "0"; } } // extern "C" <|endoftext|>
<commit_before>// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/ #include "test.hh" namespace pegtl { namespace { std::string u32s( const char32_t u ) { return std::string( reinterpret_cast< const char * >( & u ), sizeof( u ) ); } } // void unit_test() { verify_rule< utf32::any >( __LINE__, __FILE__, "", result_type::LOCAL_FAILURE, 0 ); verify_rule< utf32::any >( __LINE__, __FILE__, "\xff", result_type::LOCAL_FAILURE, 1 ); verify_rule< utf32::any >( __LINE__, __FILE__, "\xff\xff", result_type::LOCAL_FAILURE, 2 ); verify_rule< utf32::any >( __LINE__, __FILE__, "\xff\xff\xff", result_type::LOCAL_FAILURE, 3 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0 ), result_type::SUCCESS, 0 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 1 ), result_type::SUCCESS, 0 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0x00ff ) + " ", result_type::SUCCESS, 1 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0x0100 ) + " ", result_type::SUCCESS, 2 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0x0fff ) + " ", result_type::SUCCESS, 3 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0x1000 ) + " ", result_type::SUCCESS, 4 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0xfffe ), result_type::SUCCESS, 0 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0xffff ), result_type::SUCCESS, 0 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0x100000 ), result_type::SUCCESS, 0 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0x10fffe ), result_type::SUCCESS, 0 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0x10ffff ), result_type::SUCCESS, 0 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0x110000 ), result_type::LOCAL_FAILURE, 4 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0x110000 ) + u32s( 0 ), result_type::LOCAL_FAILURE, 8 ); verify_rule< utf32::one< 0x20 > >( __LINE__, __FILE__, u32s( 0x20 ), result_type::SUCCESS, 0 ); verify_rule< utf32::one< 0x10fedc > >( __LINE__, __FILE__, u32s( 0x10fedc ), result_type::SUCCESS, 0 ); } } // pegtl #include "main.hh" <commit_msg>More tests<commit_after>// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/ #include "test.hh" namespace pegtl { namespace { std::string u32s( const char32_t u ) { return std::string( reinterpret_cast< const char * >( & u ), sizeof( u ) ); } } // void unit_test() { verify_rule< utf32::any >( __LINE__, __FILE__, "", result_type::LOCAL_FAILURE, 0 ); verify_rule< utf32::any >( __LINE__, __FILE__, "\xff", result_type::LOCAL_FAILURE, 1 ); verify_rule< utf32::any >( __LINE__, __FILE__, "\xff\xff", result_type::LOCAL_FAILURE, 2 ); verify_rule< utf32::any >( __LINE__, __FILE__, "\xff\xff\xff", result_type::LOCAL_FAILURE, 3 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0 ), result_type::SUCCESS, 0 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 1 ), result_type::SUCCESS, 0 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0x00ff ) + " ", result_type::SUCCESS, 1 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0x0100 ) + " ", result_type::SUCCESS, 2 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0x0fff ) + " ", result_type::SUCCESS, 3 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0x1000 ) + " ", result_type::SUCCESS, 4 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0xfffe ), result_type::SUCCESS, 0 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0xffff ), result_type::SUCCESS, 0 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0x100000 ), result_type::SUCCESS, 0 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0x10fffe ), result_type::SUCCESS, 0 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0x10ffff ), result_type::SUCCESS, 0 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0x110000 ), result_type::LOCAL_FAILURE, 4 ); verify_rule< utf32::any >( __LINE__, __FILE__, u32s( 0x110000 ) + u32s( 0 ), result_type::LOCAL_FAILURE, 8 ); verify_rule< utf32::one< 0x20 > >( __LINE__, __FILE__, u32s( 0x20 ), result_type::SUCCESS, 0 ); verify_rule< utf32::one< 0x20ac > >( __LINE__, __FILE__, u32s( 0x20ac ), result_type::SUCCESS, 0 ); verify_rule< utf32::one< 0x10fedc > >( __LINE__, __FILE__, u32s( 0x10fedc ), result_type::SUCCESS, 0 ); } } // pegtl #include "main.hh" <|endoftext|>
<commit_before>//===- unittests/Basic/LexerTest.cpp ------ Lexer tests -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Basic/SourceManager.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/TargetOptions.h" #include "clang/Basic/TargetInfo.h" #include "clang/Lex/ModuleLoader.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/Preprocessor.h" #include "llvm/Config/config.h" #include "gtest/gtest.h" using namespace llvm; using namespace clang; namespace { // The test fixture. class LexerTest : public ::testing::Test { protected: LexerTest() : FileMgr(FileMgrOpts), DiagID(new DiagnosticIDs()), Diags(DiagID, new IgnoringDiagConsumer()), SourceMgr(Diags, FileMgr) { TargetOpts.Triple = "x86_64-apple-darwin11.1.0"; Target = TargetInfo::CreateTargetInfo(Diags, TargetOpts); } FileSystemOptions FileMgrOpts; FileManager FileMgr; llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID; DiagnosticsEngine Diags; SourceManager SourceMgr; LangOptions LangOpts; TargetOptions TargetOpts; llvm::IntrusiveRefCntPtr<TargetInfo> Target; }; class VoidModuleLoader : public ModuleLoader { virtual Module *loadModule(SourceLocation ImportLoc, ModuleIdPath Path, Module::NameVisibilityKind Visibility, bool IsInclusionDirective) { return 0; } }; TEST_F(LexerTest, LexAPI) { const char *source = "#define M(x) [x]\n" "M(foo)"; MemoryBuffer *buf = MemoryBuffer::getMemBuffer(source); FileID mainFileID = SourceMgr.createMainFileIDForMemBuffer(buf); VoidModuleLoader ModLoader; HeaderSearch HeaderInfo(FileMgr, Diags, LangOpts); Preprocessor PP(Diags, LangOpts, Target.getPtr(), SourceMgr, HeaderInfo, ModLoader, /*IILookup =*/ 0, /*OwnsHeaderSearch =*/false, /*DelayInitialization =*/ false); PP.EnterMainSourceFile(); std::vector<Token> toks; while (1) { Token tok; PP.Lex(tok); if (tok.is(tok::eof)) break; toks.push_back(tok); } // Make sure we got the tokens that we expected. ASSERT_EQ(3U, toks.size()); ASSERT_EQ(tok::l_square, toks[0].getKind()); ASSERT_EQ(tok::identifier, toks[1].getKind()); ASSERT_EQ(tok::r_square, toks[2].getKind()); SourceLocation lsqrLoc = toks[0].getLocation(); SourceLocation idLoc = toks[1].getLocation(); SourceLocation rsqrLoc = toks[2].getLocation(); std::pair<SourceLocation,SourceLocation> macroPair = SourceMgr.getExpansionRange(lsqrLoc); SourceRange macroRange = SourceRange(macroPair.first, macroPair.second); SourceLocation Loc; EXPECT_TRUE(Lexer::isAtStartOfMacroExpansion(lsqrLoc, SourceMgr, LangOpts, &Loc)); EXPECT_EQ(Loc, macroRange.getBegin()); EXPECT_FALSE(Lexer::isAtStartOfMacroExpansion(idLoc, SourceMgr, LangOpts)); EXPECT_FALSE(Lexer::isAtEndOfMacroExpansion(idLoc, SourceMgr, LangOpts)); EXPECT_TRUE(Lexer::isAtEndOfMacroExpansion(rsqrLoc, SourceMgr, LangOpts, &Loc)); EXPECT_EQ(Loc, macroRange.getEnd()); CharSourceRange range = Lexer::makeFileCharRange(SourceRange(lsqrLoc, idLoc), SourceMgr, LangOpts); EXPECT_TRUE(range.isInvalid()); range = Lexer::makeFileCharRange(SourceRange(idLoc, rsqrLoc), SourceMgr, LangOpts); EXPECT_TRUE(range.isInvalid()); range = Lexer::makeFileCharRange(SourceRange(lsqrLoc, rsqrLoc), SourceMgr, LangOpts); EXPECT_TRUE(!range.isTokenRange()); EXPECT_EQ(range.getAsRange(), SourceRange(macroRange.getBegin(), macroRange.getEnd().getLocWithOffset(1))); StringRef text = Lexer::getSourceText( CharSourceRange::getTokenRange(SourceRange(lsqrLoc, rsqrLoc)), SourceMgr, LangOpts); EXPECT_EQ(text, "M(foo)"); } } // anonymous namespace <commit_msg>Silence set-but-unused warning.<commit_after>//===- unittests/Basic/LexerTest.cpp ------ Lexer tests -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Basic/SourceManager.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/TargetOptions.h" #include "clang/Basic/TargetInfo.h" #include "clang/Lex/ModuleLoader.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/Preprocessor.h" #include "llvm/Config/config.h" #include "gtest/gtest.h" using namespace llvm; using namespace clang; namespace { // The test fixture. class LexerTest : public ::testing::Test { protected: LexerTest() : FileMgr(FileMgrOpts), DiagID(new DiagnosticIDs()), Diags(DiagID, new IgnoringDiagConsumer()), SourceMgr(Diags, FileMgr) { TargetOpts.Triple = "x86_64-apple-darwin11.1.0"; Target = TargetInfo::CreateTargetInfo(Diags, TargetOpts); } FileSystemOptions FileMgrOpts; FileManager FileMgr; llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID; DiagnosticsEngine Diags; SourceManager SourceMgr; LangOptions LangOpts; TargetOptions TargetOpts; llvm::IntrusiveRefCntPtr<TargetInfo> Target; }; class VoidModuleLoader : public ModuleLoader { virtual Module *loadModule(SourceLocation ImportLoc, ModuleIdPath Path, Module::NameVisibilityKind Visibility, bool IsInclusionDirective) { return 0; } }; TEST_F(LexerTest, LexAPI) { const char *source = "#define M(x) [x]\n" "M(foo)"; MemoryBuffer *buf = MemoryBuffer::getMemBuffer(source); SourceMgr.createMainFileIDForMemBuffer(buf); VoidModuleLoader ModLoader; HeaderSearch HeaderInfo(FileMgr, Diags, LangOpts); Preprocessor PP(Diags, LangOpts, Target.getPtr(), SourceMgr, HeaderInfo, ModLoader, /*IILookup =*/ 0, /*OwnsHeaderSearch =*/false, /*DelayInitialization =*/ false); PP.EnterMainSourceFile(); std::vector<Token> toks; while (1) { Token tok; PP.Lex(tok); if (tok.is(tok::eof)) break; toks.push_back(tok); } // Make sure we got the tokens that we expected. ASSERT_EQ(3U, toks.size()); ASSERT_EQ(tok::l_square, toks[0].getKind()); ASSERT_EQ(tok::identifier, toks[1].getKind()); ASSERT_EQ(tok::r_square, toks[2].getKind()); SourceLocation lsqrLoc = toks[0].getLocation(); SourceLocation idLoc = toks[1].getLocation(); SourceLocation rsqrLoc = toks[2].getLocation(); std::pair<SourceLocation,SourceLocation> macroPair = SourceMgr.getExpansionRange(lsqrLoc); SourceRange macroRange = SourceRange(macroPair.first, macroPair.second); SourceLocation Loc; EXPECT_TRUE(Lexer::isAtStartOfMacroExpansion(lsqrLoc, SourceMgr, LangOpts, &Loc)); EXPECT_EQ(Loc, macroRange.getBegin()); EXPECT_FALSE(Lexer::isAtStartOfMacroExpansion(idLoc, SourceMgr, LangOpts)); EXPECT_FALSE(Lexer::isAtEndOfMacroExpansion(idLoc, SourceMgr, LangOpts)); EXPECT_TRUE(Lexer::isAtEndOfMacroExpansion(rsqrLoc, SourceMgr, LangOpts, &Loc)); EXPECT_EQ(Loc, macroRange.getEnd()); CharSourceRange range = Lexer::makeFileCharRange(SourceRange(lsqrLoc, idLoc), SourceMgr, LangOpts); EXPECT_TRUE(range.isInvalid()); range = Lexer::makeFileCharRange(SourceRange(idLoc, rsqrLoc), SourceMgr, LangOpts); EXPECT_TRUE(range.isInvalid()); range = Lexer::makeFileCharRange(SourceRange(lsqrLoc, rsqrLoc), SourceMgr, LangOpts); EXPECT_TRUE(!range.isTokenRange()); EXPECT_EQ(range.getAsRange(), SourceRange(macroRange.getBegin(), macroRange.getEnd().getLocWithOffset(1))); StringRef text = Lexer::getSourceText( CharSourceRange::getTokenRange(SourceRange(lsqrLoc, rsqrLoc)), SourceMgr, LangOpts); EXPECT_EQ(text, "M(foo)"); } } // anonymous namespace <|endoftext|>
<commit_before>// THIS FILE IS AUTO GENERATED, EDIT AT YOUR OWN RISK #include <tuple> #include "ComponentImplementationInclude.h" #define myoffsetof(st, m) static_cast<int>((size_t)(&((st *)0)->m)) // Implementation of the base entity class // Constructor of entity Entity::Entity(const MessageHandler *messageHandlers, const int* componentOffsets {% for attrib in general.common_entity_attributes %} ,{{attrib.get_declaration()}} {% endfor %} ): messageHandlers(messageHandlers), componentOffsets(componentOffsets) {% for attrib in general.common_entity_attributes %} ,{{attrib.get_initializer()}} {% endfor %} { } Entity::~Entity() { } void Entity::SendMessage(int msg, const void* data) { MessageHandler handler = messageHandlers[msg]; if (handler) { handler(this, data); } } // Entity helper functions to send message e.g. // void Entity::Damage(int value); {% for message in messages %} void Entity::{{message.name}}({{message.get_function_args()}}) { {% if message.get_num_args() == 0 %} SendMessage({{message.get_enum_name()}}, nullptr); {% else %} {{message.get_tuple_type()}} data({{message.get_args_names()}}); SendMessage({{message.get_enum_name()}}, &data); {% endif %} } {% endfor %} // Entity helper functions to get the components e.g. // HealthComponent* GetHealthComponent(); {% for component in components %} {{component.get_type_name()}}* Entity::Get{{component.get_type_name()}}() { int index = {{component.get_priority()}}; int offset = componentOffsets[index]; if (offset) { return ({{component.get_type_name()}}*) (((char*) this) + offset); } else { return nullptr; } } {% endfor %} // Implementation of the components // Component helper functions to change the attributes values e.g. // void SetHealth(int value); {% for component in components %} {% for attrib in component.get_own_attribs() %} void {{component.get_base_type_name()}}::{{attrib.get_setter_name()}}({{attrib.typ}} value) { entity->SendMessage({{attrib.get_message().get_enum_name()}}, new {{attrib.typ}}(value)); } {% endfor %} {% endfor %} // Implementation of the entities {% for entity in entities %} // The vtable of offset of components in an entity // TODO: doesn't handle component inheritance? const int {{entity.get_type_name()}}::componentOffsets[] = { {% for component in components %} {% if component in entity.get_components() %} myoffsetof({{entity.get_type_name()}}, {{component.get_variable_name()}}), {% else %} 0, {% endif %} {% endfor %} }; // The static message handlers put in the vtable {% for message in entity.get_messages_to_handle() %} void {{entity.get_message_handler_name(message)}}(Entity* _entity, const void* {% if message.get_num_args() > 0 %} _data {% endif %} ) { // Cast the entity to the correct type (receive an Entity*) {{entity.get_type_name()}}* entity = ({{entity.get_type_name()}}*) _entity; {% if message.get_num_args() == 0 %} // No argument for the message, just call the handlers of all the components {% for component in entity.get_components() %} {% if message in component.get_messages_to_handle() %} entity->{{component.get_variable_name()}}->{{message.get_handler_name()}}(); {% endif %} {% endfor %} {% else %} // Cast the message content to the right type (receive a const void*) const {{message.get_tuple_type()}}* data = (const {{message.get_tuple_type()}}*) _data; {% for component in entity.get_components() %} {% if message in component.get_messages_to_handle() %} entity->{{component.get_variable_name()}}->{{message.get_handler_name()}}({{message.get_unpacked_tuple_args('*data')}}); {% endif %} {% endfor %} {% endif %} // The message is for an attribute change, update the value accordingly {% if message.is_attrib() %} entity->{{message.get_attrib().get_variable_name()}} = std::get<0>(*data); {% endif %} } {% endfor%} // The vtable of message handlers for an entity const MessageHandler {{entity.get_type_name()}}::messageHandlers[] = { {% for message in messages %} {% if message in entity.get_messages_to_handle() %} {{entity.get_message_handler_name(message)}}, {% else %} nullptr, {% endif %} {% endfor%} }; // Fat constructor for the entity that initializes the components. {{entity.get_type_name()}}::{{entity.get_type_name()}}( {% for (i, attrib) in enumerate(general.common_entity_attributes) %} {% if i != 0 %}, {% endif %} {{attrib.get_declaration()}} {% endfor %} ): Entity(messageHandlers, componentOffsets {% for attrib in general.common_entity_attributes %} ,{{attrib.get_name()}} {% endfor %} ) {% for component in entity.get_components() %} // Each component takes the entity it is in, its parameters, the shared attributes and the components it requires , {{component.get_variable_name()}}(new {{component.get_type_name()}}( this {% for param in component.get_param_names() %} , {{entity.get_params()[component.name][param]}} {% endfor %} {% for attrib in component.get_attribs() %} , {{attrib.get_variable_name()}} {% endfor %} {% for required in component.get_required_components() %} , {{required.get_variable_name()}} {% endfor %} )) {% endfor %} {} // The destructor of the entity destroys all the components in reverse order {{entity.get_type_name()}}::~{{entity.get_type_name()}}() { {% for component in entity.get_components()[::-1] %} delete {{component.get_variable_name()}}; {% endfor %} } {% endfor %} #undef myoffsetof <commit_msg>Fix the Get*Component returning a bad pointer<commit_after>// THIS FILE IS AUTO GENERATED, EDIT AT YOUR OWN RISK #include <tuple> #include "ComponentImplementationInclude.h" #define myoffsetof(st, m) static_cast<int>((size_t)(&((st *)0)->m)) // Implementation of the base entity class // Constructor of entity Entity::Entity(const MessageHandler *messageHandlers, const int* componentOffsets {% for attrib in general.common_entity_attributes %} ,{{attrib.get_declaration()}} {% endfor %} ): messageHandlers(messageHandlers), componentOffsets(componentOffsets) {% for attrib in general.common_entity_attributes %} ,{{attrib.get_initializer()}} {% endfor %} { } Entity::~Entity() { } void Entity::SendMessage(int msg, const void* data) { MessageHandler handler = messageHandlers[msg]; if (handler) { handler(this, data); } } // Entity helper functions to send message e.g. // void Entity::Damage(int value); {% for message in messages %} void Entity::{{message.name}}({{message.get_function_args()}}) { {% if message.get_num_args() == 0 %} SendMessage({{message.get_enum_name()}}, nullptr); {% else %} {{message.get_tuple_type()}} data({{message.get_args_names()}}); SendMessage({{message.get_enum_name()}}, &data); {% endif %} } {% endfor %} // Entity helper functions to get the components e.g. // HealthComponent* GetHealthComponent(); {% for component in components %} {{component.get_type_name()}}* Entity::Get{{component.get_type_name()}}() { int index = {{component.get_priority()}}; int offset = componentOffsets[index]; if (offset) { return *({{component.get_type_name()}}**) (((char*) this) + offset); } else { return nullptr; } } {% endfor %} // Implementation of the components // Component helper functions to change the attributes values e.g. // void SetHealth(int value); {% for component in components %} {% for attrib in component.get_own_attribs() %} void {{component.get_base_type_name()}}::{{attrib.get_setter_name()}}({{attrib.typ}} value) { entity->SendMessage({{attrib.get_message().get_enum_name()}}, new {{attrib.typ}}(value)); } {% endfor %} {% endfor %} // Implementation of the entities {% for entity in entities %} // The vtable of offset of components in an entity // TODO: doesn't handle component inheritance? const int {{entity.get_type_name()}}::componentOffsets[] = { {% for component in components %} {% if component in entity.get_components() %} myoffsetof({{entity.get_type_name()}}, {{component.get_variable_name()}}), {% else %} 0, {% endif %} {% endfor %} }; // The static message handlers put in the vtable {% for message in entity.get_messages_to_handle() %} void {{entity.get_message_handler_name(message)}}(Entity* _entity, const void* {% if message.get_num_args() > 0 %} _data {% endif %} ) { // Cast the entity to the correct type (receive an Entity*) {{entity.get_type_name()}}* entity = ({{entity.get_type_name()}}*) _entity; {% if message.get_num_args() == 0 %} // No argument for the message, just call the handlers of all the components {% for component in entity.get_components() %} {% if message in component.get_messages_to_handle() %} entity->{{component.get_variable_name()}}->{{message.get_handler_name()}}(); {% endif %} {% endfor %} {% else %} // Cast the message content to the right type (receive a const void*) const {{message.get_tuple_type()}}* data = (const {{message.get_tuple_type()}}*) _data; {% for component in entity.get_components() %} {% if message in component.get_messages_to_handle() %} entity->{{component.get_variable_name()}}->{{message.get_handler_name()}}({{message.get_unpacked_tuple_args('*data')}}); {% endif %} {% endfor %} {% endif %} // The message is for an attribute change, update the value accordingly {% if message.is_attrib() %} entity->{{message.get_attrib().get_variable_name()}} = std::get<0>(*data); {% endif %} } {% endfor%} // The vtable of message handlers for an entity const MessageHandler {{entity.get_type_name()}}::messageHandlers[] = { {% for message in messages %} {% if message in entity.get_messages_to_handle() %} {{entity.get_message_handler_name(message)}}, {% else %} nullptr, {% endif %} {% endfor%} }; // Fat constructor for the entity that initializes the components. {{entity.get_type_name()}}::{{entity.get_type_name()}}( {% for (i, attrib) in enumerate(general.common_entity_attributes) %} {% if i != 0 %}, {% endif %} {{attrib.get_declaration()}} {% endfor %} ): Entity(messageHandlers, componentOffsets {% for attrib in general.common_entity_attributes %} ,{{attrib.get_name()}} {% endfor %} ) {% for component in entity.get_components() %} // Each component takes the entity it is in, its parameters, the shared attributes and the components it requires , {{component.get_variable_name()}}(new {{component.get_type_name()}}( this {% for param in component.get_param_names() %} , {{entity.get_params()[component.name][param]}} {% endfor %} {% for attrib in component.get_attribs() %} , {{attrib.get_variable_name()}} {% endfor %} {% for required in component.get_required_components() %} , {{required.get_variable_name()}} {% endfor %} )) {% endfor %} {} // The destructor of the entity destroys all the components in reverse order {{entity.get_type_name()}}::~{{entity.get_type_name()}}() { {% for component in entity.get_components()[::-1] %} delete {{component.get_variable_name()}}; {% endfor %} } {% endfor %} #undef myoffsetof <|endoftext|>
<commit_before>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2017 * * * * 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 <modules/onscreengui/include/guiorigincomponent.h> #include <openspace/engine/openspaceengine.h> #include <openspace/interaction/interactionhandler.h> #include <openspace/rendering/renderengine.h> #include <openspace/scene/scenegraphnode.h> #include <ghoul/misc/assert.h> #include "imgui.h" namespace openspace { namespace gui { GuiOriginComponent::GuiOriginComponent() : GuiComponent("Origin") {} void GuiOriginComponent::render() { SceneGraphNode* currentFocus = OsEng.interactionHandler().focusNode(); std::vector<SceneGraphNode*> nodes = OsEng.renderEngine().scene()->allSceneGraphNodes(); std::sort( nodes.begin(), nodes.end(), [](SceneGraphNode* lhs, SceneGraphNode* rhs) { return lhs->name() < rhs->name(); } ); std::string nodeNames = ""; for (SceneGraphNode* n : nodes) { nodeNames += n->name() + '\0'; } auto iCurrentFocus = std::find(nodes.begin(), nodes.end(), currentFocus); ghoul_assert(iCurrentFocus != nodes.end(), "Focus node not found"); int currentPosition = static_cast<int>(std::distance(iCurrentFocus, nodes.begin())); bool hasChanged = ImGui::Combo("Origin", &currentPosition, nodeNames.c_str()); if (hasChanged) { OsEng.scriptEngine().queueScript( "openspace.setPropertyValue('Interaction.origin', '" + nodes[currentPosition]->name() + "');", scripting::ScriptEngine::RemoteScripting::Yes ); } } } // gui } // openspace <commit_msg>Don't assert if the focus node is not found if there are no nodes at all<commit_after>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2017 * * * * 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 <modules/onscreengui/include/guiorigincomponent.h> #include <openspace/engine/openspaceengine.h> #include <openspace/interaction/interactionhandler.h> #include <openspace/rendering/renderengine.h> #include <openspace/scene/scenegraphnode.h> #include <ghoul/misc/assert.h> #include "imgui.h" namespace openspace { namespace gui { GuiOriginComponent::GuiOriginComponent() : GuiComponent("Origin") {} void GuiOriginComponent::render() { SceneGraphNode* currentFocus = OsEng.interactionHandler().focusNode(); std::vector<SceneGraphNode*> nodes = OsEng.renderEngine().scene()->allSceneGraphNodes(); std::sort( nodes.begin(), nodes.end(), [](SceneGraphNode* lhs, SceneGraphNode* rhs) { return lhs->name() < rhs->name(); } ); std::string nodeNames = ""; for (SceneGraphNode* n : nodes) { nodeNames += n->name() + '\0'; } auto iCurrentFocus = std::find(nodes.begin(), nodes.end(), currentFocus); if (!nodes.empty()) { // Only check if we found the current focus node if we have any nodes at all // only then it would be a real error ghoul_assert(iCurrentFocus != nodes.end(), "Focus node not found"); } int currentPosition = static_cast<int>(std::distance(iCurrentFocus, nodes.begin())); bool hasChanged = ImGui::Combo("Origin", &currentPosition, nodeNames.c_str()); if (hasChanged) { OsEng.scriptEngine().queueScript( "openspace.setPropertyValue('Interaction.origin', '" + nodes[currentPosition]->name() + "');", scripting::ScriptEngine::RemoteScripting::Yes ); } } } // gui } // openspace <|endoftext|>
<commit_before>/* * Copyright (C) 2019 Nagisa Sekiguchi * * 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 <sys/utsname.h> #include <regex> #include <fstream> #include <misc/util.hpp> #include <constant.h> #include "platform.h" namespace ydsh { namespace platform { static bool reSearch(const char *reStr, const std::string &value) { std::regex re(reStr, std::regex_constants::ECMAScript | std::regex_constants::icase); std::smatch match; return std::regex_search(value, match, re); } const char *toString(PlatformType c) { const char *table[] = { #define GEN_STR(E) #E, EACH_PLATFORM_TYPE(GEN_STR) #undef GEN_STR }; return table[static_cast<unsigned int>(c)]; } static bool detectContainer() { std::ifstream stream("/proc/1/cgroup"); if(!stream) { return false; } for(std::string line; std::getline(stream, line); ) { if(reSearch("docker|lxc", line)) { return true; } } return false; } static PlatformType detectImpl() { struct utsname name{}; if(uname(&name) == -1) { return PlatformType::UNKNOWN; } std::string sysName = name.sysname; if(reSearch("linux", sysName)) { if(reSearch("microsoft", name.release)) { return PlatformType::WSL; } if(detectContainer()) { return PlatformType::CONTAINER; } return PlatformType::LINUX; } if(reSearch("darwin", sysName)) { return PlatformType::DARWIN; } if(reSearch("cygwin", sysName)) { return PlatformType::CYGWIN; } return PlatformType::UNKNOWN; } PlatformType platform() { static auto p = detectImpl(); return p; } bool containPlatform(const std::string &text, PlatformType type) { return reSearch(toString(type), text); } const char *toString(ArchType c) { const char *table[] = { #define GEN_STR(E, S) #E, EACH_ARCH_TYPE(GEN_STR) #undef GEN_STR }; return table[static_cast<unsigned int>(c)]; } static ArchType archImpl() { ArchType types[] = { #define GEN_ENUM(E, S) ArchType::E, EACH_ARCH_TYPE(GEN_ENUM) #undef GEN_ENUM }; for(auto &type : types) { if(containArch(BUILD_ARCH, type)) { return type; } } return ArchType::UNKNOWN; } ArchType arch() { static auto a = archImpl(); return a; } bool containArch(const std::string &text, ArchType type) { const char *table[] = { #define GEN_STR(E, S) #E "|" S, EACH_ARCH_TYPE(GEN_STR) #undef GEN_STR }; return reSearch(table[static_cast<unsigned int>(type)], text); } } // namespace platform } // namespace ydsh<commit_msg>support containerd in platform detection<commit_after>/* * Copyright (C) 2019 Nagisa Sekiguchi * * 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 <sys/utsname.h> #include <regex> #include <fstream> #include <misc/util.hpp> #include <constant.h> #include "platform.h" namespace ydsh { namespace platform { static bool reSearch(const char *reStr, const std::string &value) { std::regex re(reStr, std::regex_constants::ECMAScript | std::regex_constants::icase); std::smatch match; return std::regex_search(value, match, re); } const char *toString(PlatformType c) { const char *table[] = { #define GEN_STR(E) #E, EACH_PLATFORM_TYPE(GEN_STR) #undef GEN_STR }; return table[static_cast<unsigned int>(c)]; } static bool detectContainer() { std::ifstream stream("/proc/1/cgroup"); if(!stream) { return false; } for(std::string line; std::getline(stream, line); ) { if(reSearch("docker|lxc|containerd", line)) { return true; } } return false; } static PlatformType detectImpl() { struct utsname name{}; if(uname(&name) == -1) { return PlatformType::UNKNOWN; } std::string sysName = name.sysname; if(reSearch("linux", sysName)) { if(reSearch("microsoft", name.release)) { return PlatformType::WSL; } if(detectContainer()) { return PlatformType::CONTAINER; } return PlatformType::LINUX; } if(reSearch("darwin", sysName)) { return PlatformType::DARWIN; } if(reSearch("cygwin", sysName)) { return PlatformType::CYGWIN; } return PlatformType::UNKNOWN; } PlatformType platform() { static auto p = detectImpl(); return p; } bool containPlatform(const std::string &text, PlatformType type) { return reSearch(toString(type), text); } const char *toString(ArchType c) { const char *table[] = { #define GEN_STR(E, S) #E, EACH_ARCH_TYPE(GEN_STR) #undef GEN_STR }; return table[static_cast<unsigned int>(c)]; } static ArchType archImpl() { ArchType types[] = { #define GEN_ENUM(E, S) ArchType::E, EACH_ARCH_TYPE(GEN_ENUM) #undef GEN_ENUM }; for(auto &type : types) { if(containArch(BUILD_ARCH, type)) { return type; } } return ArchType::UNKNOWN; } ArchType arch() { static auto a = archImpl(); return a; } bool containArch(const std::string &text, ArchType type) { const char *table[] = { #define GEN_STR(E, S) #E "|" S, EACH_ARCH_TYPE(GEN_STR) #undef GEN_STR }; return reSearch(table[static_cast<unsigned int>(type)], text); } } // namespace platform } // namespace ydsh<|endoftext|>
<commit_before>#include "ssaorenderpass.hpp" #include "../../engine.hpp" #include <random> #include <world/component/transformcomponent.hpp> SSAORenderSystem::SSAORenderSystem(int width, int height) { shaderProgram .attach("assets/shaders/ssao.vert", ShaderType::vertex) .attach("assets/shaders/ssao.frag", ShaderType::fragment) .finalize(); shaderProgram .addUniform("positionMap") .addUniform("normalMap") .addUniform("noiseMap") .addUniform("noiseScale") .addUniform("nrOfSamples") .addUniform("sampleRadius") .addUniform("sampleBias") .addUniform("samplePoints") .addUniform("viewMatrix") .addUniform("projectionMatrix"); gBuffer.attachTexture(0, width, height, GL_RED, GL_FLOAT, 1); shaderProgram.bind(); generateUniformData(width, height); } float SSAORenderSystem::lerp(float a, float b, float f) { return a + f * (b - a); } void SSAORenderSystem::generateUniformData(int width, int height) { std::uniform_real_distribution<GLfloat> randomFlaots(0.0, 1.0); std::default_random_engine generator; std::vector<glm::vec3> samplePoints; for (size_t i = 0; i < 64; i++) { glm::vec3 samplePoint = { randomFlaots(generator) * 2.0 - 1.0, randomFlaots(generator) * 2.0 - 1.0, randomFlaots(generator) }; samplePoint = glm::normalize(samplePoint); samplePoint *= randomFlaots(generator); float scale = float(i) / 64.0; scale = lerp(0.1, 1.0, scale * scale); samplePoint *= scale; samplePoints.push_back(samplePoint); } shaderProgram.setUniformArray("samplePoints", samplePoints); std::vector<glm::vec3> noiseData; for (size_t i = 0; i < 16; i++) { glm::vec3 noise = { randomFlaots(generator) * 2.0 - 1.0, randomFlaots(generator) * 2.0 - 1.0, 0.0 }; noiseData.push_back(noise); } noiseMap = std::make_shared<Texture>(width, height, GL_RGB32F, GL_RGB, GL_FLOAT, &noiseData[0]); noiseMap->bind() .setParameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST) .setParameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST) .setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT) .setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT); attachInputTexture(3, noiseMap); shaderProgram.setUniform("noiseMap", 3); glm::vec2 noiseScale = { width / 4.0, height / 4.0 }; shaderProgram.setUniform("noiseScale", noiseScale); } void SSAORenderSystem::render(World & world) { CameraEntity & camera = *Engine::getInstance().getCamera(); shaderProgram.bind(); shaderProgram.setUniform("viewMatrix", camera.getComponent<TransformComponent>()->rotation); shaderProgram.setUniform("projectionMatrix", camera.getComponent<TransformComponent>()->rotation); } <commit_msg>formating<commit_after>#include "ssaorenderpass.hpp" #include "../../engine.hpp" #include <random> #include <world/component/transformcomponent.hpp> SSAORenderSystem::SSAORenderSystem(int width, int height) { shaderProgram .attach("assets/shaders/ssao.vert", ShaderType::vertex) .attach("assets/shaders/ssao.frag", ShaderType::fragment) .finalize(); shaderProgram .addUniform("positionMap") .addUniform("normalMap") .addUniform("noiseMap") .addUniform("noiseScale") .addUniform("nrOfSamples") .addUniform("sampleRadius") .addUniform("sampleBias") .addUniform("samplePoints") .addUniform("viewMatrix") .addUniform("projectionMatrix"); gBuffer.attachTexture(0, width, height, GL_RED, GL_FLOAT, 1); shaderProgram.bind(); generateUniformData(width, height); } float SSAORenderSystem::lerp(float a, float b, float f) { return a + f * (b - a); } void SSAORenderSystem::generateUniformData(int width, int height) { shaderProgram.setUniform("positionMap", 0); shaderProgram.setUniform("normalMap", 1); shaderProgram.setUniform("normalMap", 2); std::uniform_real_distribution<GLfloat> randomFlaots(0.0, 1.0); std::default_random_engine generator; std::vector<glm::vec3> samplePoints; for (size_t i = 0; i < 64; i++) { glm::vec3 samplePoint = { randomFlaots(generator) * 2.0 - 1.0, randomFlaots(generator) * 2.0 - 1.0, randomFlaots(generator) }; samplePoint = glm::normalize(samplePoint); samplePoint *= randomFlaots(generator); float scale = float(i) / 64.0; scale = lerp(0.1, 1.0, scale * scale); samplePoint *= scale; samplePoints.push_back(samplePoint); } shaderProgram.setUniformArray("samplePoints", samplePoints); std::vector<glm::vec3> noiseData; for (size_t i = 0; i < 16; i++) { glm::vec3 noise = { randomFlaots(generator) * 2.0 - 1.0, randomFlaots(generator) * 2.0 - 1.0, 0.0 }; noiseData.push_back(noise); } noiseMap = std::make_shared<Texture>(width, height, GL_RGB32F, GL_RGB, GL_FLOAT, &noiseData[0]); noiseMap->bind() .setParameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST) .setParameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST) .setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT) .setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT); attachInputTexture(2, noiseMap); glm::vec2 noiseScale = { width / 4.0, height / 4.0 }; shaderProgram.setUniform("noiseScale", noiseScale); } void SSAORenderSystem::render(World & world) { CameraEntity & camera = *Engine::getInstance().getCamera(); shaderProgram.bind(); shaderProgram.setUniform("viewMatrix", camera.getComponent<TransformComponent>()->rotation); shaderProgram.setUniform("projectionMatrix", camera.getComponent<TransformComponent>()->rotation); } <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2014-2016 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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 "ordinalpropertyanimator.h" #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/util/exception.h> namespace inviwo { const ProcessorInfo OrdinalPropertyAnimator::processorInfo_{ "org.inviwo.OrdinalPropertyAnimator", // Class identifier "Property Animator", // Display name "Various", // Category CodeState::Experimental, // Code state Tags::CPU, // Tags }; const ProcessorInfo OrdinalPropertyAnimator::getProcessorInfo() const { return processorInfo_; } OrdinalPropertyAnimator::OrdinalPropertyAnimator() : Processor() , type_("property", "Property") , delay_("delay", "Delay (ms)", 50, 1, 10000, 1) , pbc_("pbc", "Periodic", true) , active_("active", "Active", false) , timer_(delay_, [this]() { timerEvent(); }) { delay_.onChange(this, &OrdinalPropertyAnimator::updateTimerInterval); properties_.push_back( std::make_unique<PrimProp<float>>("org.inviwo.FloatProperty", "org.inviwo.FloatProperty")); properties_.push_back(std::make_unique<VecProp<vec2>>("org.inviwo.FloatVec2Property", "org.inviwo.FloatVec2Property")); properties_.push_back(std::make_unique<VecProp<vec3>>("org.inviwo.FloatVec3Property", "org.inviwo.FloatVec3Property")); properties_.push_back(std::make_unique<VecProp<vec4>>("org.inviwo.FloatVec4Property", "org.inviwo.FloatVec4Property")); properties_.push_back(std::make_unique<PrimProp<double>>("org.inviwo.DoubleProperty", "org.inviwo.DoubleProperty")); properties_.push_back(std::make_unique<VecProp<dvec2>>("org.inviwo.DoubleVec2Property", "org.inviwo.DoubleVec2Property")); properties_.push_back(std::make_unique<VecProp<dvec3>>("org.inviwo.DoubleVec3Property", "org.inviwo.DoubleVec3Property")); properties_.push_back(std::make_unique<VecProp<dvec4>>("org.inviwo.DoubleVec4Property", "org.inviwo.DoubleVec4Property")); properties_.push_back( std::make_unique<PrimProp<int>>("org.inviwo.IntProperty", "org.inviwo.IntProperty")); properties_.push_back(std::make_unique<VecProp<ivec2>>("org.inviwo.IntVec2Property", "org.inviwo.IntVec2Property")); properties_.push_back(std::make_unique<VecProp<ivec3>>("org.inviwo.IntVec3Property", "org.inviwo.IntVec3Property")); properties_.push_back(std::make_unique<VecProp<ivec4>>("org.inviwo.IntVec4Property", "org.inviwo.IntVec4Property")); addProperty(type_); addProperty(active_); addProperty(delay_); addProperty(pbc_); int count = 0; for (auto& p : properties_) { type_.addOption(p->classname_, p->displayName_, count); Property* prop = p->getProp(); Property* delta = p->getDelta(); addProperty(prop, false); addProperty(delta, false); prop->setVisible(false); delta->setVisible(false); count++; } type_.setSelectedIndex(0); type_.setCurrentStateAsDefault(); type_.onChange(this, &OrdinalPropertyAnimator::changeProperty); active_.onChange(this, &OrdinalPropertyAnimator::changeActive); changeProperty(); setAllPropertiesCurrentStateAsDefault(); } void OrdinalPropertyAnimator::initializeResources() { changeProperty(); updateTimerInterval(); } void OrdinalPropertyAnimator::updateTimerInterval() { timer_.stop(); if (active_.get()) timer_.start(delay_); } void OrdinalPropertyAnimator::timerEvent() { int ind = type_.get(); properties_[ind]->update(pbc_.get()); } void OrdinalPropertyAnimator::changeProperty() { int ind = type_.get(); for (auto& p : properties_) { Property* prop = p->getProp(); Property* delta = p->getDelta(); prop->setVisible(false); delta->setVisible(false); } properties_[ind]->getProp()->setVisible(true); properties_[ind]->getDelta()->setVisible(true); } void OrdinalPropertyAnimator::changeActive() { updateTimerInterval(); } } // namespace <commit_msg>Base: bugfix<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2014-2016 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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 "ordinalpropertyanimator.h" #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/util/exception.h> namespace inviwo { const ProcessorInfo OrdinalPropertyAnimator::processorInfo_{ "org.inviwo.OrdinalPropertyAnimator", // Class identifier "Property Animator", // Display name "Various", // Category CodeState::Experimental, // Code state Tags::CPU, // Tags }; const ProcessorInfo OrdinalPropertyAnimator::getProcessorInfo() const { return processorInfo_; } OrdinalPropertyAnimator::OrdinalPropertyAnimator() : Processor() , type_("property", "Property") , delay_("delay", "Delay (ms)", 50, 1, 10000, 1) , pbc_("pbc", "Periodic", true) , active_("active", "Active", false) , timer_(delay_, [this]() { timerEvent(); }) { delay_.onChange(this, &OrdinalPropertyAnimator::updateTimerInterval); properties_.push_back( util::make_unique<PrimProp<float>>("org.inviwo.FloatProperty", "org.inviwo.FloatProperty")); properties_.push_back(util::make_unique<VecProp<vec2>>("org.inviwo.FloatVec2Property", "org.inviwo.FloatVec2Property")); properties_.push_back(util::make_unique<VecProp<vec3>>("org.inviwo.FloatVec3Property", "org.inviwo.FloatVec3Property")); properties_.push_back(util::make_unique<VecProp<vec4>>("org.inviwo.FloatVec4Property", "org.inviwo.FloatVec4Property")); properties_.push_back(util::make_unique<PrimProp<double>>("org.inviwo.DoubleProperty", "org.inviwo.DoubleProperty")); properties_.push_back(util::make_unique<VecProp<dvec2>>("org.inviwo.DoubleVec2Property", "org.inviwo.DoubleVec2Property")); properties_.push_back(util::make_unique<VecProp<dvec3>>("org.inviwo.DoubleVec3Property", "org.inviwo.DoubleVec3Property")); properties_.push_back(util::make_unique<VecProp<dvec4>>("org.inviwo.DoubleVec4Property", "org.inviwo.DoubleVec4Property")); properties_.push_back( util::make_unique<PrimProp<int>>("org.inviwo.IntProperty", "org.inviwo.IntProperty")); properties_.push_back(util::make_unique<VecProp<ivec2>>("org.inviwo.IntVec2Property", "org.inviwo.IntVec2Property")); properties_.push_back(util::make_unique<VecProp<ivec3>>("org.inviwo.IntVec3Property", "org.inviwo.IntVec3Property")); properties_.push_back(util::make_unique<VecProp<ivec4>>("org.inviwo.IntVec4Property", "org.inviwo.IntVec4Property")); addProperty(type_); addProperty(active_); addProperty(delay_); addProperty(pbc_); int count = 0; for (auto& p : properties_) { type_.addOption(p->classname_, p->displayName_, count); Property* prop = p->getProp(); Property* delta = p->getDelta(); addProperty(prop, false); addProperty(delta, false); prop->setVisible(false); delta->setVisible(false); count++; } type_.setSelectedIndex(0); type_.setCurrentStateAsDefault(); type_.onChange(this, &OrdinalPropertyAnimator::changeProperty); active_.onChange(this, &OrdinalPropertyAnimator::changeActive); changeProperty(); setAllPropertiesCurrentStateAsDefault(); } void OrdinalPropertyAnimator::initializeResources() { changeProperty(); updateTimerInterval(); } void OrdinalPropertyAnimator::updateTimerInterval() { timer_.stop(); if (active_.get()) timer_.start(delay_); } void OrdinalPropertyAnimator::timerEvent() { int ind = type_.get(); properties_[ind]->update(pbc_.get()); } void OrdinalPropertyAnimator::changeProperty() { int ind = type_.get(); for (auto& p : properties_) { Property* prop = p->getProp(); Property* delta = p->getDelta(); prop->setVisible(false); delta->setVisible(false); } properties_[ind]->getProp()->setVisible(true); properties_[ind]->getDelta()->setVisible(true); } void OrdinalPropertyAnimator::changeActive() { updateTimerInterval(); } } // namespace <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2020 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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 <modules/base/algorithm/volume/volumevoronoi.h> namespace inviwo { namespace util { std::shared_ptr<Volume> voronoiSegmentation( const size3_t volumeDimensions, const mat4& indexToModelMatrix, const std::vector<std::pair<uint32_t, vec3>>& seedPointsWithIndices, const std::optional<std::vector<float>>& weights, bool weightedVoronoi) { if (seedPointsWithIndices.size() == 0) { throw Exception("No seed points, cannot create volume voronoi segmentation", IVW_CONTEXT_CUSTOM("VoronoiSegmentation")); } if (weightedVoronoi && weights.has_value() && weights.value().size() != seedPointsWithIndices.size()) { throw Exception( "Cannot use weighted voronoi when dimensions do not match (weights and seed positions)", IVW_CONTEXT_CUSTOM("VoronoiSegmentation")); } auto newVolumeRep = std::make_shared<VolumeRAMPrecision<unsigned short>>(volumeDimensions); auto newVolume = std::make_shared<Volume>(newVolumeRep); newVolume->dataMap_.dataRange = dvec2(0.0, static_cast<double>(seedPointsWithIndices.size())); newVolume->dataMap_.valueRange = newVolume->dataMap_.dataRange; auto volumeIndices = newVolumeRep->getDataTyped(); util::IndexMapper3D index(volumeDimensions); util::forEachVoxelParallel(volumeDimensions, [&](const size3_t& voxelPos) { const auto transformedVoxelPos = mat3(indexToModelMatrix) * voxelPos; if (weightedVoronoi && weights.has_value()) { auto zipped = util::zip(seedPointsWithIndices, weights.value()); auto&& [posWithIndex, weight] = *std::min_element( zipped.begin(), zipped.end(), [transformedVoxelPos](auto&& i1, auto&& i2) { auto&& [p1, w1] = i1; auto&& [p2, w2] = i2; return glm::distance2(p1.second, transformedVoxelPos) - w1 * w1 < glm::distance2(p2.second, transformedVoxelPos) - w2 * w2; }); volumeIndices[index(voxelPos)] = posWithIndex.first; } else { auto it = std::min_element(seedPointsWithIndices.cbegin(), seedPointsWithIndices.cend(), [transformedVoxelPos](const auto& p1, const auto& p2) { return glm::distance2(p1.second, transformedVoxelPos) < glm::distance2(p2.second, transformedVoxelPos); }); volumeIndices[index(voxelPos)] = it->first; } }); return newVolume; }; } // namespace util } // namespace inviwo <commit_msg>Check if weighted outside foreach<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2020 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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 <modules/base/algorithm/volume/volumevoronoi.h> namespace inviwo { namespace util { std::shared_ptr<Volume> voronoiSegmentation( const size3_t volumeDimensions, const mat4& indexToModelMatrix, const std::vector<std::pair<uint32_t, vec3>>& seedPointsWithIndices, const std::optional<std::vector<float>>& weights, bool weightedVoronoi) { if (seedPointsWithIndices.size() == 0) { throw Exception("No seed points, cannot create volume voronoi segmentation", IVW_CONTEXT_CUSTOM("VoronoiSegmentation")); } if (weightedVoronoi && weights.has_value() && weights.value().size() != seedPointsWithIndices.size()) { throw Exception( "Cannot use weighted voronoi when dimensions do not match (weights and seed positions)", IVW_CONTEXT_CUSTOM("VoronoiSegmentation")); } auto newVolumeRep = std::make_shared<VolumeRAMPrecision<unsigned short>>(volumeDimensions); auto newVolume = std::make_shared<Volume>(newVolumeRep); newVolume->dataMap_.dataRange = dvec2(0.0, static_cast<double>(seedPointsWithIndices.size())); newVolume->dataMap_.valueRange = newVolume->dataMap_.dataRange; auto volumeIndices = newVolumeRep->getDataTyped(); util::IndexMapper3D index(volumeDimensions); if (weightedVoronoi && weights.has_value()) { util::forEachVoxelParallel(volumeDimensions, [&](const size3_t& voxelPos) { const auto transformedVoxelPos = mat3(indexToModelMatrix) * voxelPos; auto zipped = util::zip(seedPointsWithIndices, weights.value()); auto&& [posWithIndex, weight] = *std::min_element( zipped.begin(), zipped.end(), [transformedVoxelPos](auto&& i1, auto&& i2) { auto&& [p1, w1] = i1; auto&& [p2, w2] = i2; return glm::distance2(p1.second, transformedVoxelPos) - w1 * w1 < glm::distance2(p2.second, transformedVoxelPos) - w2 * w2; }); volumeIndices[index(voxelPos)] = posWithIndex.first; }); } else { util::forEachVoxelParallel(volumeDimensions, [&](const size3_t& voxelPos) { const auto transformedVoxelPos = mat3(indexToModelMatrix) * voxelPos; auto it = std::min_element(seedPointsWithIndices.cbegin(), seedPointsWithIndices.cend(), [transformedVoxelPos](const auto& p1, const auto& p2) { return glm::distance2(p1.second, transformedVoxelPos) < glm::distance2(p2.second, transformedVoxelPos); }); volumeIndices[index(voxelPos)] = it->first; }); } return newVolume; }; } // namespace util } // namespace inviwo <|endoftext|>
<commit_before><commit_msg>planning: fixed a bug in navi planner dispatcher<commit_after><|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2011 \file context.cpp \author ([email protected]) \date 06.06.2010 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH #include "simulator/compiler/parser/pch.h" // ----------------------------------------------------------------------- INCLUDES // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/compiler/parser/rdoparser.h" #include "simulator/compiler/parser/context/context.h" #include "simulator/compiler/parser/context/context_switch_i.h" // -------------------------------------------------------------------------------- OPEN_RDO_PARSER_NAMESPACE Context::Context() {} Context::~Context() {} void Context::init() {} void Context::deinit() { m_findResult = IContextFind::Result(); } void Context::setContextStack(CREF(LPContextStack) pContextStack) { ASSERT(pContextStack ); ASSERT(!m_pContextStack); m_pContextStack = pContextStack; } LPContext Context::find(CREF(LPRDOValue) pValue) const { ASSERT(pValue); LPContext pThis(const_cast<PTR(Context)>(this)); LPIContextFind pThisContextFind = pThis.interface_dynamic_cast<IContextFind>(); if (pThisContextFind) { const_cast<PTR(Context)>(this)->m_findResult = pThisContextFind->onFindContext(pValue); if (m_findResult.m_pContext) { return m_findResult.m_pContext; } } LPContext pPrev = m_pContextStack->prev(pThis); return pPrev ? pPrev->find(pValue) : LPContext(); } LPContext Context::swch(CREF(LPRDOValue) pValue) const { ASSERT(pValue); LPIContextSwitch pContextSwitch = m_findResult.m_pValueContext.interface_dynamic_cast<IContextSwitch>(); ASSERT(pContextSwitch); IContextFind::Result result = pContextSwitch->onSwitchContext(m_findResult.m_pExpression, pValue); ASSERT(result.m_pContext); result.m_pContext->m_findResult = result; ASSERT(result.m_pContext); return result.m_pContext; } LPExpression Context::create(CREF(LPRDOValue) pValue) { ASSERT(pValue); ASSERT(m_findResult.m_pFindByValue == pValue); ASSERT(m_findResult.m_pExpression); return m_findResult.m_pExpression; } CLOSE_RDO_PARSER_NAMESPACE <commit_msg> - очистка контекста<commit_after>/*! \copyright (c) RDO-Team, 2011 \file context.cpp \author ([email protected]) \date 06.06.2010 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH #include "simulator/compiler/parser/pch.h" // ----------------------------------------------------------------------- INCLUDES // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/compiler/parser/rdoparser.h" #include "simulator/compiler/parser/context/context.h" #include "simulator/compiler/parser/context/context_switch_i.h" // -------------------------------------------------------------------------------- OPEN_RDO_PARSER_NAMESPACE Context::Context() {} Context::~Context() {} void Context::init() {} void Context::deinit() { m_findResult = IContextFind::Result(); } void Context::setContextStack(CREF(LPContextStack) pContextStack) { ASSERT(pContextStack ); ASSERT(!m_pContextStack); m_pContextStack = pContextStack; } LPContext Context::find(CREF(LPRDOValue) pValue) const { ASSERT(pValue); LPContext pThis(const_cast<PTR(Context)>(this)); LPIContextFind pThisContextFind = pThis.interface_dynamic_cast<IContextFind>(); if (pThisContextFind) { const_cast<PTR(Context)>(this)->m_findResult = pThisContextFind->onFindContext(pValue); if (m_findResult.m_pContext) { return m_findResult.m_pContext; } } LPContext pPrev = m_pContextStack->prev(pThis); return pPrev ? pPrev->find(pValue) : LPContext(); } LPContext Context::swch(CREF(LPRDOValue) pValue) const { ASSERT(pValue); LPIContextSwitch pContextSwitch = m_findResult.m_pValueContext.interface_dynamic_cast<IContextSwitch>(); ASSERT(pContextSwitch); IContextFind::Result result = pContextSwitch->onSwitchContext(m_findResult.m_pExpression, pValue); ASSERT(result.m_pContext); result.m_pContext->m_findResult = result; ASSERT(result.m_pContext); const_cast<PTR(Context)>(this)->deinit(); return result.m_pContext; } LPExpression Context::create(CREF(LPRDOValue) pValue) { ASSERT(pValue); ASSERT(m_findResult.m_pFindByValue == pValue); ASSERT(m_findResult.m_pExpression); LPExpression pExpression = m_findResult.m_pExpression; deinit(); return pExpression; } CLOSE_RDO_PARSER_NAMESPACE <|endoftext|>
<commit_before>// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. #include "CppUnitTest.h" #include "pipe_extensions.h" #include <memory> #include <sstream> #include "UIStrings.h" namespace Microsoft { namespace VisualStudio { namespace CppUnitTestFramework { template<> static wstring ToString<RequestLanguage>(const RequestLanguage& lang) { return lang == RequestLanguage::CSHARPCOMPILE ? L"CSHARPCOMPILE" : L"VBCOMPILE"; } template<> static wstring ToString <vector<Request::Argument>>(const vector<Request::Argument>& vec) { return L""; } template<> static wstring ToString <vector<BYTE>>(const vector<BYTE>& vec) { return L""; } } } } using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace NativeClientTests { // To run these test from command line // vstest.console.exe Roslyn.Compilers.NativeClient.UnitTests.dll TEST_CLASS(MessageTests) { public: TEST_METHOD(SimpleRequestWithoutUtf8) { auto language = RequestLanguage::CSHARPCOMPILE; list<wstring> args = { L"test.cs" }; wstring keepAlive; int errorId; auto success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsTrue(success); Assert::IsTrue(keepAlive.empty()); auto request = Request(language, L""); request.AddCommandLineArguments(args); Assert::AreEqual(PROTOCOL_VERSION, request.ProtocolVersion); Assert::AreEqual(language, request.Language); vector<Request::Argument> expectedArgs = { Request::Argument(ArgumentId::CURRENTDIRECTORY, 0, L""), Request::Argument(ArgumentId::COMMANDLINEARGUMENT, 0, L"test.cs"), }; Assert::AreEqual(expectedArgs, request.Arguments()); vector<byte> expectedBytes = { 0x32, 0x0, 0x0, 0x0, // Size of request 0x2, 0x0, 0x0, 0x0, // Protocol version 0x21, 0x25, 0x53, 0x44, // C# compile token 0x2, 0x0, 0x0, 0x0, // Number of arguments 0x21, 0x72, 0x14, 0x51, // Current directory token 0x0, 0x0, 0x0, 0x0, // Index 0x0, 0x0, 0x0, 0x0, // Length of value string 0x22, 0x72, 0x14, 0x51, // Command line arg token 0x0, 0x0, 0x0, 0x0, // Index 0x7, 0x0, 0x0, 0x0, // Length of value string in characters 0x74, 0x0, 0x65, 0x0, 0x73, // 't', 'e', 's' 0x0, 0x74, 0x0, 0x2e, 0x0, // 't', '.' 0x63, 0x0, 0x73, 0x0 // 'c', 's' }; WriteOnlyMemoryPipe pipe; Assert::IsTrue(request.WriteToPipe(pipe)); Assert::AreEqual(expectedBytes, pipe.Bytes()); } TEST_METHOD(SimpleRequestWithUtf8) { auto language = RequestLanguage::CSHARPCOMPILE; list<wstring> args = { L"/utf8output", L"test.cs" }; wstring keepAlive; int errorId; auto success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsTrue(success); Assert::IsTrue(keepAlive.empty()); auto request = Request(language, L""); request.AddCommandLineArguments(args); Assert::AreEqual(PROTOCOL_VERSION, request.ProtocolVersion); Assert::AreEqual(language, request.Language); vector<Request::Argument> expectedArgs = { Request::Argument(ArgumentId::CURRENTDIRECTORY, 0, L""), Request::Argument(ArgumentId::COMMANDLINEARGUMENT, 0, L"/utf8output"), Request::Argument(ArgumentId::COMMANDLINEARGUMENT, 1, L"test.cs"), }; Assert::AreEqual(expectedArgs, request.Arguments()); vector<byte> expectedBytes = { 0x54, 0x0, 0x0, 0x0, // Size of request 0x2, 0x0, 0x0, 0x0, // Protocol version 0x21, 0x25, 0x53, 0x44, // C# compile token 0x3, 0x0, 0x0, 0x0, // Number of arguments 0x21, 0x72, 0x14, 0x51, // Current directory token 0x0, 0x0, 0x0, 0x0, // Index 0x0, 0x0, 0x0, 0x0, // Length of value string 0x22, 0x72, 0x14, 0x51, // Command line arg token 0x0, 0x0, 0x0, 0x0, // Index 0xb, 0x0, 0x0, 0x0, // Length of value string in characters 0x2f, 0x0, 0x75, 0x0, // '/', 'u' 0x74, 0x0, 0x66, 0x0, // 't', 'f' 0x38, 0x0, 0x6f, 0x0, // '8, 'o' 0x75, 0x0, 0x74, 0x0, // 'u', 't' 0x70, 0x0, 0x75, 0x0, // 'p', 'u' 0x74, 0x0, // 't' 0x22, 0x72, 0x14, 0x51, // Command line arg token 0x1, 0x0, 0x0, 0x0, // Index 0x7, 0x0, 0x0, 0x0, // Length of value string in characters 0x74, 0x0, 0x65, 0x0, 0x73, // 't', 'e', 's' 0x0, 0x74, 0x0, 0x2e, 0x0, // 't', '.' 0x63, 0x0, 0x73, 0x0 // 'c', 's' }; WriteOnlyMemoryPipe pipe; request.WriteToPipe(pipe); Assert::AreEqual(expectedBytes, pipe.Bytes()); } TEST_METHOD(RequestsWithKeepAlive) { list<wstring> args = { L"/keepalive:10" }; wstring keepAlive; int errorId; auto success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsTrue(success); Assert::IsTrue(args.empty()); Assert::AreEqual(L"10", keepAlive.c_str()); auto language = RequestLanguage::CSHARPCOMPILE; auto request = Request(language, L""); request.AddKeepAlive(wstring(keepAlive)); vector<Request::Argument> expected = { Request::Argument(ArgumentId::CURRENTDIRECTORY, 0, L""), Request::Argument(ArgumentId::KEEPALIVE, 0, L"10"), }; Assert::AreEqual(expected, request.Arguments()); args = { L"/keepalive=10" }; success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsTrue(success); Assert::IsTrue(args.empty()); Assert::AreEqual(L"10", keepAlive.c_str()); request = Request(language, L""); request.AddKeepAlive(wstring(keepAlive)); Assert::AreEqual(expected, request.Arguments()); } TEST_METHOD(NegativeValidKeepAlive) { list<wstring> args = { L"/keepalive:-1" }; wstring keepAlive; int errorId; auto success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsTrue(success); Assert::IsTrue(args.empty()); Assert::AreEqual(L"-1", keepAlive.c_str()); } TEST_METHOD(ParseKeepAliveNoValue) { list<wstring> args = { L"/keepalive", }; wstring keepAlive; int errorId; auto success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsFalse(success); Assert::AreEqual( IDS_MissingKeepAlive, errorId); } TEST_METHOD(ParseKeepAliveNoValue2) { list<wstring> args = { L"/keepalive:", }; wstring keepAlive; int errorId; auto success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsFalse(success); Assert::AreEqual( IDS_MissingKeepAlive, errorId); } TEST_METHOD(ParseKeepAliveBadInteger) { list<wstring> args = { L"/keepalive", }; wstring keepAlive; int errorId; auto success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsFalse(success); Assert::AreEqual( IDS_MissingKeepAlive, errorId); } TEST_METHOD(ParseKeepAliveIntegerTooSmall) { list<wstring> args = { L"/keepalive:-2", }; wstring keepAlive; int errorId; auto success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsFalse(success); Assert::AreEqual( IDS_KeepAliveIsTooSmall, errorId); } TEST_METHOD(ParseKeepAliveOutOfRange) { list<wstring> args = { L"/keepalive:9999999999", }; wstring keepAlive; int errorId; auto success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsFalse(success); Assert::AreEqual( IDS_KeepAliveIsOutOfRange, errorId); } TEST_METHOD(ParseKeepAliveNotAnInt) { list<wstring> args = { L"/keepalive:string", }; wstring keepAlive; int errorId; auto success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsFalse(success); Assert::AreEqual( IDS_KeepAliveIsNotAnInteger, errorId); } }; } <commit_msg>Fix warnings in NativeClientTests and hide warnings in VsCppUnitTest (changeset 1410899)<commit_after>// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Disable warning about static explicit specialization until bug 1118730 is fixed #pragma warning( push ) #pragma warning( disable: 4499 ) #include "CppUnitTest.h" #pragma warning (pop) #include "pipe_extensions.h" #include <memory> #include <sstream> #include "UIStrings.h" namespace Microsoft { namespace VisualStudio { namespace CppUnitTestFramework { template<> wstring ToString<RequestLanguage>(const RequestLanguage& lang) { return lang == RequestLanguage::CSHARPCOMPILE ? L"CSHARPCOMPILE" : L"VBCOMPILE"; } template<> wstring ToString <vector<Request::Argument>>(const vector<Request::Argument>& vec) { return L""; } template<> wstring ToString <vector<BYTE>>(const vector<BYTE>& vec) { return L""; } } } } using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace NativeClientTests { // To run these test from command line // vstest.console.exe Roslyn.Compilers.NativeClient.UnitTests.dll TEST_CLASS(MessageTests) { public: TEST_METHOD(SimpleRequestWithoutUtf8) { auto language = RequestLanguage::CSHARPCOMPILE; list<wstring> args = { L"test.cs" }; wstring keepAlive; int errorId; auto success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsTrue(success); Assert::IsTrue(keepAlive.empty()); auto request = Request(language, L""); request.AddCommandLineArguments(args); Assert::AreEqual(PROTOCOL_VERSION, request.ProtocolVersion); Assert::AreEqual(language, request.Language); vector<Request::Argument> expectedArgs = { Request::Argument(ArgumentId::CURRENTDIRECTORY, 0, L""), Request::Argument(ArgumentId::COMMANDLINEARGUMENT, 0, L"test.cs"), }; Assert::AreEqual(expectedArgs, request.Arguments()); vector<byte> expectedBytes = { 0x32, 0x0, 0x0, 0x0, // Size of request 0x2, 0x0, 0x0, 0x0, // Protocol version 0x21, 0x25, 0x53, 0x44, // C# compile token 0x2, 0x0, 0x0, 0x0, // Number of arguments 0x21, 0x72, 0x14, 0x51, // Current directory token 0x0, 0x0, 0x0, 0x0, // Index 0x0, 0x0, 0x0, 0x0, // Length of value string 0x22, 0x72, 0x14, 0x51, // Command line arg token 0x0, 0x0, 0x0, 0x0, // Index 0x7, 0x0, 0x0, 0x0, // Length of value string in characters 0x74, 0x0, 0x65, 0x0, 0x73, // 't', 'e', 's' 0x0, 0x74, 0x0, 0x2e, 0x0, // 't', '.' 0x63, 0x0, 0x73, 0x0 // 'c', 's' }; WriteOnlyMemoryPipe pipe; Assert::IsTrue(request.WriteToPipe(pipe)); Assert::AreEqual(expectedBytes, pipe.Bytes()); } TEST_METHOD(SimpleRequestWithUtf8) { auto language = RequestLanguage::CSHARPCOMPILE; list<wstring> args = { L"/utf8output", L"test.cs" }; wstring keepAlive; int errorId; auto success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsTrue(success); Assert::IsTrue(keepAlive.empty()); auto request = Request(language, L""); request.AddCommandLineArguments(args); Assert::AreEqual(PROTOCOL_VERSION, request.ProtocolVersion); Assert::AreEqual(language, request.Language); vector<Request::Argument> expectedArgs = { Request::Argument(ArgumentId::CURRENTDIRECTORY, 0, L""), Request::Argument(ArgumentId::COMMANDLINEARGUMENT, 0, L"/utf8output"), Request::Argument(ArgumentId::COMMANDLINEARGUMENT, 1, L"test.cs"), }; Assert::AreEqual(expectedArgs, request.Arguments()); vector<byte> expectedBytes = { 0x54, 0x0, 0x0, 0x0, // Size of request 0x2, 0x0, 0x0, 0x0, // Protocol version 0x21, 0x25, 0x53, 0x44, // C# compile token 0x3, 0x0, 0x0, 0x0, // Number of arguments 0x21, 0x72, 0x14, 0x51, // Current directory token 0x0, 0x0, 0x0, 0x0, // Index 0x0, 0x0, 0x0, 0x0, // Length of value string 0x22, 0x72, 0x14, 0x51, // Command line arg token 0x0, 0x0, 0x0, 0x0, // Index 0xb, 0x0, 0x0, 0x0, // Length of value string in characters 0x2f, 0x0, 0x75, 0x0, // '/', 'u' 0x74, 0x0, 0x66, 0x0, // 't', 'f' 0x38, 0x0, 0x6f, 0x0, // '8, 'o' 0x75, 0x0, 0x74, 0x0, // 'u', 't' 0x70, 0x0, 0x75, 0x0, // 'p', 'u' 0x74, 0x0, // 't' 0x22, 0x72, 0x14, 0x51, // Command line arg token 0x1, 0x0, 0x0, 0x0, // Index 0x7, 0x0, 0x0, 0x0, // Length of value string in characters 0x74, 0x0, 0x65, 0x0, 0x73, // 't', 'e', 's' 0x0, 0x74, 0x0, 0x2e, 0x0, // 't', '.' 0x63, 0x0, 0x73, 0x0 // 'c', 's' }; WriteOnlyMemoryPipe pipe; request.WriteToPipe(pipe); Assert::AreEqual(expectedBytes, pipe.Bytes()); } TEST_METHOD(RequestsWithKeepAlive) { list<wstring> args = { L"/keepalive:10" }; wstring keepAlive; int errorId; auto success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsTrue(success); Assert::IsTrue(args.empty()); Assert::AreEqual(L"10", keepAlive.c_str()); auto language = RequestLanguage::CSHARPCOMPILE; auto request = Request(language, L""); request.AddKeepAlive(wstring(keepAlive)); vector<Request::Argument> expected = { Request::Argument(ArgumentId::CURRENTDIRECTORY, 0, L""), Request::Argument(ArgumentId::KEEPALIVE, 0, L"10"), }; Assert::AreEqual(expected, request.Arguments()); args = { L"/keepalive=10" }; success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsTrue(success); Assert::IsTrue(args.empty()); Assert::AreEqual(L"10", keepAlive.c_str()); request = Request(language, L""); request.AddKeepAlive(wstring(keepAlive)); Assert::AreEqual(expected, request.Arguments()); } TEST_METHOD(NegativeValidKeepAlive) { list<wstring> args = { L"/keepalive:-1" }; wstring keepAlive; int errorId; auto success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsTrue(success); Assert::IsTrue(args.empty()); Assert::AreEqual(L"-1", keepAlive.c_str()); } TEST_METHOD(ParseKeepAliveNoValue) { list<wstring> args = { L"/keepalive", }; wstring keepAlive; int errorId; auto success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsFalse(success); Assert::AreEqual( IDS_MissingKeepAlive, errorId); } TEST_METHOD(ParseKeepAliveNoValue2) { list<wstring> args = { L"/keepalive:", }; wstring keepAlive; int errorId; auto success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsFalse(success); Assert::AreEqual( IDS_MissingKeepAlive, errorId); } TEST_METHOD(ParseKeepAliveBadInteger) { list<wstring> args = { L"/keepalive", }; wstring keepAlive; int errorId; auto success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsFalse(success); Assert::AreEqual( IDS_MissingKeepAlive, errorId); } TEST_METHOD(ParseKeepAliveIntegerTooSmall) { list<wstring> args = { L"/keepalive:-2", }; wstring keepAlive; int errorId; auto success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsFalse(success); Assert::AreEqual( IDS_KeepAliveIsTooSmall, errorId); } TEST_METHOD(ParseKeepAliveOutOfRange) { list<wstring> args = { L"/keepalive:9999999999", }; wstring keepAlive; int errorId; auto success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsFalse(success); Assert::AreEqual( IDS_KeepAliveIsOutOfRange, errorId); } TEST_METHOD(ParseKeepAliveNotAnInt) { list<wstring> args = { L"/keepalive:string", }; wstring keepAlive; int errorId; auto success = ParseAndValidateClientArguments(args, keepAlive, errorId); Assert::IsFalse(success); Assert::AreEqual( IDS_KeepAliveIsNotAnInteger, errorId); } }; } <|endoftext|>
<commit_before>#include "stdafx.h" #include "CppUnitTest.h" #include "../dummy_values.h" #include "internal/internal_datastore.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace You { namespace DataStore { namespace UnitTests { using DataStore = You::DataStore::Internal::DataStore; /// Unit Test Class for DataStore class TEST_CLASS(DataStoreTest) { public: TEST_METHOD(beginTransaction) { DataStore& sut = DataStore::get(); sut.post(0, task1); SerializedTask task = sut.getTask(0); Assert::AreEqual(task1.at(TASK_ID), task[TASK_ID]); Assert::AreEqual(task1.at(DESCRIPTION), task[DESCRIPTION]); Assert::AreEqual(task1.at(DEADLINE), task[DEADLINE]); Assert::AreEqual(task1.at(PRIORITY), task[PRIORITY]); Assert::AreEqual(task1.at(DEPENDENCIES), task[DEPENDENCIES]); sut.document.reset(); sut.saveData(); } TEST_METHOD(postWithoutTransaction) { DataStore& sut = DataStore::get(); // Checks if the document is initially empty Assert::IsTrue(sut.document.first_child().empty()); // Equivalent to postWithNewId Assert::IsTrue(sut.post(0, task1)); // Checks if the document is now not empty Assert::IsFalse(sut.document.first_child().empty()); // Equivalent to postWithUsedId Assert::IsFalse(sut.post(0, task1)); sut.document.reset(); sut.saveData(); } /// Basic test for editing a task TEST_METHOD(putWithoutTransaction) { DataStore& sut = DataStore::get(); // Checks if the document is initially empty Assert::IsTrue(sut.document.first_child().empty()); pugi::xml_node node = sut.document.append_child(L"task"); node.append_attribute(L"id").set_value(L"0"); // Equivalent to putWithExistingId Assert::IsTrue(sut.put(0, task1)); // Equivalent to putNonExistentId Assert::IsFalse(sut.put(1, task1)); sut.document.reset(); sut.saveData(); } /// Basic test for erasing a task with the specified task id TEST_METHOD(eraseWithoutTransaction) { DataStore& sut = DataStore::get(); pugi::xml_node node = sut.document.append_child(L"task"); node.append_attribute(L"id").set_value(L"0"); // Equivalent to eraseExistingId Assert::IsTrue(sut.erase(0)); // Equivalent to eraseNonExistentId Assert::IsFalse(sut.erase(1)); sut.document.reset(); sut.saveData(); } TEST_METHOD(getAllTasks) { DataStore& sut = DataStore::get(); sut.document.append_child(L"task"). append_child(pugi::xml_node_type::node_pcdata).set_value(L"what"); std::vector<SerializedTask> result = sut.getAllTask(); Assert::AreEqual(1, boost::lexical_cast<int>(result.size())); sut.document.reset(); sut.saveData(); } TEST_METHOD(saveThenLoad) { DataStore& sut = DataStore::get(); sut.document.append_child(L"task"). append_child(pugi::xml_node_type::node_pcdata).set_value(L"what"); bool result = sut.saveData(); Assert::IsTrue(result); sut.loadData(); std::wstring value = sut.document.child(L"task").child_value(); Assert::AreEqual(std::wstring(L"what"), value); sut.document.reset(); sut.saveData(); } }; } // namespace UnitTests } // namespace DataStore } // namespace You <commit_msg>Add test for pushing operations to transaction<commit_after>#include "stdafx.h" #include "CppUnitTest.h" #include "../dummy_values.h" #include "internal/operations/erase_operation.h" #include "internal/operations/post_operation.h" #include "internal/operations/put_operation.h" #include "internal/internal_datastore.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace You { namespace DataStore { namespace UnitTests { using DataStore = You::DataStore::Internal::DataStore; /// Unit Test Class for DataStore class TEST_CLASS(DataStoreTest) { public: TEST_METHOD(beginTransaction) { DataStore& sut = DataStore::get(); sut.post(0, task1); SerializedTask task = sut.getTask(0); Assert::AreEqual(task1.at(TASK_ID), task[TASK_ID]); Assert::AreEqual(task1.at(DESCRIPTION), task[DESCRIPTION]); Assert::AreEqual(task1.at(DEADLINE), task[DEADLINE]); Assert::AreEqual(task1.at(PRIORITY), task[PRIORITY]); Assert::AreEqual(task1.at(DEPENDENCIES), task[DEPENDENCIES]); sut.document.reset(); sut.saveData(); } TEST_METHOD(postWithoutTransaction) { DataStore& sut = DataStore::get(); // Checks if the document is initially empty Assert::IsTrue(sut.document.first_child().empty()); // Equivalent to postWithNewId Assert::IsTrue(sut.post(0, task1)); // Checks if the document is now not empty Assert::IsFalse(sut.document.first_child().empty()); // Equivalent to postWithUsedId Assert::IsFalse(sut.post(0, task1)); sut.document.reset(); sut.saveData(); } /// Basic test for editing a task TEST_METHOD(putWithoutTransaction) { DataStore& sut = DataStore::get(); // Checks if the document is initially empty Assert::IsTrue(sut.document.first_child().empty()); pugi::xml_node node = sut.document.append_child(L"task"); node.append_attribute(L"id").set_value(L"0"); // Equivalent to putWithExistingId Assert::IsTrue(sut.put(0, task1)); // Equivalent to putNonExistentId Assert::IsFalse(sut.put(1, task1)); sut.document.reset(); sut.saveData(); } /// Basic test for erasing a task with the specified task id TEST_METHOD(eraseWithoutTransaction) { DataStore& sut = DataStore::get(); pugi::xml_node node = sut.document.append_child(L"task"); node.append_attribute(L"id").set_value(L"0"); // Equivalent to eraseExistingId Assert::IsTrue(sut.erase(0)); // Equivalent to eraseNonExistentId Assert::IsFalse(sut.erase(1)); sut.document.reset(); sut.saveData(); } TEST_METHOD(getAllTasks) { DataStore& sut = DataStore::get(); sut.document.append_child(L"task"). append_child(pugi::xml_node_type::node_pcdata).set_value(L"what"); std::vector<SerializedTask> result = sut.getAllTask(); Assert::AreEqual(1, boost::lexical_cast<int>(result.size())); sut.document.reset(); sut.saveData(); } TEST_METHOD(saveThenLoad) { DataStore& sut = DataStore::get(); sut.document.append_child(L"task"). append_child(pugi::xml_node_type::node_pcdata).set_value(L"what"); bool result = sut.saveData(); Assert::IsTrue(result); sut.loadData(); std::wstring value = sut.document.child(L"task").child_value(); Assert::AreEqual(std::wstring(L"what"), value); sut.document.reset(); sut.saveData(); } TEST_METHOD(pushOperationToTransaction) { Internal::Transaction sut; std::unique_ptr<Internal::IOperation> post = std::make_unique<Internal::PostOperation>(0, task1); sut.push(std::move(post)); Assert::AreEqual(1U, sut.operationsQueue.size()); std::unique_ptr<Internal::IOperation> put = std::make_unique<Internal::PutOperation>(0, task1); sut.push(std::move(put)); Assert::AreEqual(2U, sut.operationsQueue.size()); std::unique_ptr<Internal::IOperation> erase = std::make_unique<Internal::EraseOperation>(0); sut.push(std::move(erase)); Assert::AreEqual(3U, sut.operationsQueue.size()); sut.operationsQueue.clear(); } }; } // namespace UnitTests } // namespace DataStore } // namespace You <|endoftext|>
<commit_before>#include "SyntaxTree.h" #include <list> #include <vector> #include <sstream> #include <iostream> #include <stdexcept> #include <assert.h> #include <boost/format.hpp> #include "parser.tab.hh" #include "template.common.h" #include "template.cs.h" using namespace std; using namespace boost; using namespace Krystal; // class Node // { // public: Krystal::Node::Node(Context* _context) { context = _context; } Krystal::Node::~Node() { } int Krystal::Node::getType() { return 0; } //TODO: remove getType() if unnecessary size_t Krystal::Node::getHash(vector<Node*>* referencingStack) { return 0; } string* Krystal::Node::getParsed(int as) { return 0; } // }; // class NodeKst : public Node // { // list<Node*>* commands; // string* fileName; // public: Krystal::NodeKst::NodeKst(Context* _context, list<Node*>* _commands, string* _fileName) : Node(_context) { commands = _commands; fileName = _fileName; } int Krystal::NodeKst::getType() { return CsNodeType::kst; } size_t Krystal::NodeKst::getHash(vector<Node*>* referencingStack) { return 0; } string* Krystal::NodeKst::getParsed(int as) { stringstream parsed; parsed << format(TCS_HEADER) % *fileName; parsed << TCS_USINGS; string namespaceByFileName = fileName->substr(0, fileName->find(".")); parsed << format(TCS_NAMESPACE_BEGIN) % namespaceByFileName; list<Node*>::iterator i = commands->begin(); list<Node*>::iterator end = commands->end(); string* temp; for (; i != end; i++) { temp = (*i)->getParsed(CsParseAs::Default); temp = indent(temp); parsed << *temp; parsed << "\n"; } parsed << TCS_NAMESPACE_END; parsed << "\n\n"; return new string(parsed.str()); } // }; // class NodeInclude : public Node // { // string* value; // public: Krystal::NodeInclude::NodeInclude(Context* _context, string* _value) : Node(_context) { value = _value; } int Krystal::NodeInclude::getType() { return CsNodeType::include; } size_t Krystal::NodeInclude::getHash(vector<Node*>* referencingStack) { return 0; } string* Krystal::NodeInclude::getParsed(int as) { stringstream parsed; parsed << "#include \""; parsed << *(value); parsed << "\""; return new string(parsed.str()); } // }; // class NodePacket : public Node // { // string* packetName; // list<Node*>* packetMembers; // public: Krystal::NodePacket::NodePacket(Context* _context, string* _packetName, list<Node*>* _packetMembers) : Node(_context) { packetName = _packetName; packetMembers = _packetMembers; } int Krystal::NodePacket::getType() { return CsNodeType::packet; } size_t Krystal::NodePacket::getHash(vector<Node*>* referencingStack) { if (referencingStack == NULL) { referencingStack = new vector<Node*>(); } else // check circular reference { vector<Node*>::iterator end = referencingStack->end(); for (vector<Node*>::iterator i = referencingStack->begin(); i != end; i++) { if (*i == this) { throw(runtime_error("Circular reference between packets")); } } } referencingStack->push_back(this); size_t packetHash = getHashCode(packetName); list<Node*>::iterator i = packetMembers->begin(); list<Node*>::iterator end = packetMembers->end(); for (; i != end; i++) { combineHashCode(packetHash, (*i)->getHash(referencingStack)); } referencingStack->pop_back(); return packetHash; } string* Krystal::NodePacket::getParsed(int as) { stringstream parsed; switch (as) { case CsParseAs::Default: { parsed << format(TCS_PACKET_BEGIN) % *packetName; { stringstream body; body << format(TCS_PACKET_ID_FIELD) % ((TCS_PACKET_ID_TYPE)getHash(NULL)); body << TCS_PACKET_COOKIE_FIELD; // Member Variables list<Node*>::iterator i = packetMembers->begin(); list<Node*>::iterator end = packetMembers->end(); for (; i != end; i++) { body << *((*i)->getParsed(CsParseAs::Default)); } body << format(TCS_PACKET_CONSTRUCTOR) % *packetName; body << TCS_PACKET_GET_ID; body << TCS_PACKET_SET_COOKIE; body << TCS_PACKET_GET_COOKIE; body << TCS_PACKET_GET_LENGTH_BEGIN; { stringstream bodyGetLengthBlock; for (i = packetMembers->begin(); i != end; i++) { bodyGetLengthBlock << *((*i)->getParsed(CsParseAs::GetLength)); } body << *(indent(new string(bodyGetLengthBlock.str()))); } body << TCS_PACKET_GET_LENGTH_END; parsed << *(indent(new string(body.str()))); } parsed << TCS_PACKET_END; } break; } return new string(parsed.str()); } // }; // class NodePacketMember : public Node // { // Node* memberType; // Node* memberName; // public: Krystal::NodePacketMember::NodePacketMember(Context* _context, Node* _memberType, Node* _memberName) : Node(_context) { memberType = _memberType; memberName = _memberName; } int Krystal::NodePacketMember::getType() { return CsNodeType::packetMember; } size_t Krystal::NodePacketMember::getHash(vector<Node*>* referencingStack) { assert(referencingStack != NULL); size_t packetMemberHash = memberType->getHash(referencingStack); combineHashCode(packetMemberHash, memberName->getHash(referencingStack)); return packetMemberHash; } string* Krystal::NodePacketMember::getParsed(int as) { stringstream parsed; switch (as) { case CsParseAs::Default: { parsed << format(TCS_PACKET_MEMBER_AS_DEFAULT) % *(memberType->getParsed(CsParseAs::Default)) % *(memberName->getParsed(CsParseAs::Default)) % *(memberType->getParsed(CsParseAs::Initialization)); } break; case CsParseAs::GetLength: { int typeType = memberType->getType(); switch (typeType) { case CsNodeType::packetMemberTypePrimitive: { string* serializerName = lookupSerializerName(memberType->getParsed(CsParseAs::Default)); parsed << format(TCS_PACKET_MEMBER_AS_GET_LENGTH_PRIMITIVE) % *serializerName % *(memberName->getParsed(CsParseAs::Default)); } break; case CsNodeType::packetMemberTypeReference: { parsed << format(TCS_PACKET_MEMBER_AS_GET_LENGTH_REFERENCE) % *(memberName->getParsed(CsParseAs::Default)); } break; case CsNodeType::packetMemberTypeMap: { parsed << format(TCS_PACKET_MEMBER_AS_GET_LENGTH_MAP) % *(memberType->getParsed(CsParseAs::GenericType1)) % *(memberType->getParsed(CsParseAs::GenericType2)) % *(memberName->getParsed(CsParseAs::Default)) % *(memberType->getParsed(CsParseAs::GenericTypeSerializer1)) % *(memberType->getParsed(CsParseAs::GenericTypeSerializer2)); } break; case CsNodeType::packetMemberTypeList: { parsed << "<temp> length += 4;\nforeach(...list...)\n{\n}\n"; } break; } } break; } return new string(parsed.str()); } // }; // class NodePacketMemberType : public Node // { // int typeType; // one of PRIMITIVE_DATA_TYPE, REFERENCE_DATA_TYPE, MAP, LIST // string* value; // "int", "bool", ..., "MyPacket", "Skill" or NULL when type is MAP or LIST // Node* generic1; // LIST<generic1> // Node* generic2; // MAP <generic1, generic2> // Node* generic3; // reserved // public: Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, string* _value) : Node(_context) { typeType = _type; value = _value; generic1 = NULL; generic2 = NULL; generic3 = NULL; } Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, Node* _generic1) : Node(_context) { typeType = _type; value = NULL; generic1 = _generic1; generic2 = NULL; generic3 = NULL; } Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, Node* _generic1, Node* _generic2) : Node(_context) { typeType = _type; value = NULL; generic1 = _generic1; generic2 = _generic2; generic3 = NULL; } Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, Node* _generic1, Node* _generic2, Node* _generic3) : Node(_context) { typeType = _type; value = NULL; generic1 = _generic1; generic2 = _generic2; generic3 = _generic3; } int Krystal::NodePacketMemberType::getType() { switch (typeType) { case Parser::token::PRIMITIVE_DATA_TYPE: { return CsNodeType::packetMemberTypePrimitive; } break; case Parser::token::REFERENCE_DATA_TYPE: { return CsNodeType::packetMemberTypeReference; } break; case Parser::token::MAP: { return CsNodeType::packetMemberTypeMap; } break; case Parser::token::LIST: { return CsNodeType::packetMemberTypeList; } break; } return CsNodeType::packetMemberType; } size_t Krystal::NodePacketMemberType::getHash(vector<Node*>* referencingStack) { assert(referencingStack != NULL); size_t packetMemberTypeHash = 0; switch(typeType) { case Parser::token::PRIMITIVE_DATA_TYPE: { packetMemberTypeHash = getHashCode(value); } break; case Parser::token::REFERENCE_DATA_TYPE: { // lookup Context::declarations table Node* typePacketNode = context->getDeclarationNode(value); if (typePacketNode == NULL) { throw(runtime_error("No such packet type.")); } packetMemberTypeHash = typePacketNode->getHash(referencingStack); } break; case Parser::token::MAP: { // must be specified this is map type // in case of other generic<t1, t2> added. packetMemberTypeHash = getHashCode((int)Parser::token::MAP); combineHashCode(packetMemberTypeHash, generic1->getHash(referencingStack)); combineHashCode(packetMemberTypeHash, generic2->getHash(referencingStack)); } break; case Parser::token::LIST: { // must be specified this is list type // in case of other generic<t> added. packetMemberTypeHash = getHashCode((int)Parser::token::LIST); combineHashCode(packetMemberTypeHash, generic1->getHash(referencingStack)); } break; } return packetMemberTypeHash; } string* Krystal::NodePacketMemberType::getParsed(int as) { stringstream parsed; switch (as) { case CsParseAs::Default: { switch (typeType) { case Parser::token::PRIMITIVE_DATA_TYPE: case Parser::token::REFERENCE_DATA_TYPE: { parsed << *value; } break; case Parser::token::MAP: { parsed << format(TCS_PACKET_MEMBER_TYPE_MAP_AS_DEFAULT) % *(generic1->getParsed(CsParseAs::Default)) % *(generic2->getParsed(CsParseAs::Default)); } break; case Parser::token::LIST: { parsed << format(TCS_PACKET_MEMBER_TYPE_LIST_AS_DEFAULT) % *(generic1->getParsed(CsParseAs::Default)); } break; default: { throw(runtime_error("Unknown NodePacketMemberType type.")); } break; } } break; case CsParseAs::GenericType1: { parsed << *(generic1->getParsed(CsParseAs::Default)); } break; case CsParseAs::GenericType2: { parsed << *(generic2->getParsed(CsParseAs::Default)); } break; case CsParseAs::GenericType3: { parsed << *(generic3->getParsed(CsParseAs::Default)); } break; case CsParseAs::GenericTypeSerializer1: { parsed << *(generic1->getParsed(CsParseAs::SerializerName)); } break; case CsParseAs::GenericTypeSerializer2: { parsed << *(generic2->getParsed(CsParseAs::SerializerName)); } break; case CsParseAs::GenericTypeSerializer3: { parsed << *(generic3->getParsed(CsParseAs::SerializerName)); } break; case CsParseAs::SerializerName: { switch (typeType) { case Parser::token::PRIMITIVE_DATA_TYPE: { string* serializerName = lookupSerializerName(value); parsed << *serializerName; } break; case Parser::token::REFERENCE_DATA_TYPE: { parsed << TCS_PACKET_CUSTOM_SERIALIZER_NAME; } break; default: { throw(runtime_error("Serializer not supported for nested generic type")); } break; } } break; case CsParseAs::Initialization: { switch (typeType) { case Parser::token::PRIMITIVE_DATA_TYPE: { parsed << ""; } break; case Parser::token::REFERENCE_DATA_TYPE: case Parser::token::MAP: case Parser::token::LIST: { parsed << format(TCS_PACKET_MEMBER_TYPE_NEW_AS_INITIALIZATION) % *(getParsed(CsParseAs::Default)); } break; default: { throw(runtime_error("Unknown NodePacketMemberType type.")); } break; } } break; } return new string(parsed.str()); } // }; // class NodePacketMemberName : public Node // { // string* value; // public: Krystal::NodePacketMemberName::NodePacketMemberName(Context* _context, string* _value) : Node(_context) { value = _value; } int Krystal::NodePacketMemberName::getType() { return CsNodeType::packetMemberName; } size_t Krystal::NodePacketMemberName::getHash(vector<Node*>* referencingStack) { size_t packetMemberNameHash = getHashCode(value); return packetMemberNameHash; } string* Krystal::NodePacketMemberName::getParsed(int as) { return value; } // }; <commit_msg>print LIST type packet member's GetLength code<commit_after>#include "SyntaxTree.h" #include <list> #include <vector> #include <sstream> #include <iostream> #include <stdexcept> #include <assert.h> #include <boost/format.hpp> #include "parser.tab.hh" #include "template.common.h" #include "template.cs.h" using namespace std; using namespace boost; using namespace Krystal; // class Node // { // public: Krystal::Node::Node(Context* _context) { context = _context; } Krystal::Node::~Node() { } int Krystal::Node::getType() { return 0; } //TODO: remove getType() if unnecessary size_t Krystal::Node::getHash(vector<Node*>* referencingStack) { return 0; } string* Krystal::Node::getParsed(int as) { return 0; } // }; // class NodeKst : public Node // { // list<Node*>* commands; // string* fileName; // public: Krystal::NodeKst::NodeKst(Context* _context, list<Node*>* _commands, string* _fileName) : Node(_context) { commands = _commands; fileName = _fileName; } int Krystal::NodeKst::getType() { return CsNodeType::kst; } size_t Krystal::NodeKst::getHash(vector<Node*>* referencingStack) { return 0; } string* Krystal::NodeKst::getParsed(int as) { stringstream parsed; parsed << format(TCS_HEADER) % *fileName; parsed << TCS_USINGS; string namespaceByFileName = fileName->substr(0, fileName->find(".")); parsed << format(TCS_NAMESPACE_BEGIN) % namespaceByFileName; list<Node*>::iterator i = commands->begin(); list<Node*>::iterator end = commands->end(); string* temp; for (; i != end; i++) { temp = (*i)->getParsed(CsParseAs::Default); temp = indent(temp); parsed << *temp; parsed << "\n"; } parsed << TCS_NAMESPACE_END; parsed << "\n\n"; return new string(parsed.str()); } // }; // class NodeInclude : public Node // { // string* value; // public: Krystal::NodeInclude::NodeInclude(Context* _context, string* _value) : Node(_context) { value = _value; } int Krystal::NodeInclude::getType() { return CsNodeType::include; } size_t Krystal::NodeInclude::getHash(vector<Node*>* referencingStack) { return 0; } string* Krystal::NodeInclude::getParsed(int as) { stringstream parsed; parsed << "#include \""; parsed << *(value); parsed << "\""; return new string(parsed.str()); } // }; // class NodePacket : public Node // { // string* packetName; // list<Node*>* packetMembers; // public: Krystal::NodePacket::NodePacket(Context* _context, string* _packetName, list<Node*>* _packetMembers) : Node(_context) { packetName = _packetName; packetMembers = _packetMembers; } int Krystal::NodePacket::getType() { return CsNodeType::packet; } size_t Krystal::NodePacket::getHash(vector<Node*>* referencingStack) { if (referencingStack == NULL) { referencingStack = new vector<Node*>(); } else // check circular reference { vector<Node*>::iterator end = referencingStack->end(); for (vector<Node*>::iterator i = referencingStack->begin(); i != end; i++) { if (*i == this) { throw(runtime_error("Circular reference between packets")); } } } referencingStack->push_back(this); size_t packetHash = getHashCode(packetName); list<Node*>::iterator i = packetMembers->begin(); list<Node*>::iterator end = packetMembers->end(); for (; i != end; i++) { combineHashCode(packetHash, (*i)->getHash(referencingStack)); } referencingStack->pop_back(); return packetHash; } string* Krystal::NodePacket::getParsed(int as) { stringstream parsed; switch (as) { case CsParseAs::Default: { parsed << format(TCS_PACKET_BEGIN) % *packetName; { stringstream body; body << format(TCS_PACKET_ID_FIELD) % ((TCS_PACKET_ID_TYPE)getHash(NULL)); body << TCS_PACKET_COOKIE_FIELD; // Member Variables list<Node*>::iterator i = packetMembers->begin(); list<Node*>::iterator end = packetMembers->end(); for (; i != end; i++) { body << *((*i)->getParsed(CsParseAs::Default)); } body << format(TCS_PACKET_CONSTRUCTOR) % *packetName; body << TCS_PACKET_GET_ID; body << TCS_PACKET_SET_COOKIE; body << TCS_PACKET_GET_COOKIE; body << TCS_PACKET_GET_LENGTH_BEGIN; { stringstream bodyGetLengthBlock; for (i = packetMembers->begin(); i != end; i++) { bodyGetLengthBlock << *((*i)->getParsed(CsParseAs::GetLength)); } body << *(indent(new string(bodyGetLengthBlock.str()))); } body << TCS_PACKET_GET_LENGTH_END; parsed << *(indent(new string(body.str()))); } parsed << TCS_PACKET_END; } break; } return new string(parsed.str()); } // }; // class NodePacketMember : public Node // { // Node* memberType; // Node* memberName; // public: Krystal::NodePacketMember::NodePacketMember(Context* _context, Node* _memberType, Node* _memberName) : Node(_context) { memberType = _memberType; memberName = _memberName; } int Krystal::NodePacketMember::getType() { return CsNodeType::packetMember; } size_t Krystal::NodePacketMember::getHash(vector<Node*>* referencingStack) { assert(referencingStack != NULL); size_t packetMemberHash = memberType->getHash(referencingStack); combineHashCode(packetMemberHash, memberName->getHash(referencingStack)); return packetMemberHash; } string* Krystal::NodePacketMember::getParsed(int as) { stringstream parsed; switch (as) { case CsParseAs::Default: { parsed << format(TCS_PACKET_MEMBER_AS_DEFAULT) % *(memberType->getParsed(CsParseAs::Default)) % *(memberName->getParsed(CsParseAs::Default)) % *(memberType->getParsed(CsParseAs::Initialization)); } break; case CsParseAs::GetLength: { int typeType = memberType->getType(); switch (typeType) { case CsNodeType::packetMemberTypePrimitive: { string* serializerName = lookupSerializerName(memberType->getParsed(CsParseAs::Default)); parsed << format(TCS_PACKET_MEMBER_AS_GET_LENGTH_PRIMITIVE) % *serializerName % *(memberName->getParsed(CsParseAs::Default)); } break; case CsNodeType::packetMemberTypeReference: { parsed << format(TCS_PACKET_MEMBER_AS_GET_LENGTH_REFERENCE) % *(memberName->getParsed(CsParseAs::Default)); } break; case CsNodeType::packetMemberTypeMap: { parsed << format(TCS_PACKET_MEMBER_AS_GET_LENGTH_MAP) % *(memberType->getParsed(CsParseAs::GenericType1)) % *(memberType->getParsed(CsParseAs::GenericType2)) % *(memberName->getParsed(CsParseAs::Default)) % *(memberType->getParsed(CsParseAs::GenericTypeSerializer1)) % *(memberType->getParsed(CsParseAs::GenericTypeSerializer2)); } break; case CsNodeType::packetMemberTypeList: { parsed << format(TCS_PACKET_MEMBER_AS_GET_LENGTH_LIST) % *(memberType->getParsed(CsParseAs::GenericType1)) % *(memberName->getParsed(CsParseAs::Default)) % *(memberType->getParsed(CsParseAs::GenericTypeSerializer1)); } break; } } break; } return new string(parsed.str()); } // }; // class NodePacketMemberType : public Node // { // int typeType; // one of PRIMITIVE_DATA_TYPE, REFERENCE_DATA_TYPE, MAP, LIST // string* value; // "int", "bool", ..., "MyPacket", "Skill" or NULL when type is MAP or LIST // Node* generic1; // LIST<generic1> // Node* generic2; // MAP <generic1, generic2> // Node* generic3; // reserved // public: Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, string* _value) : Node(_context) { typeType = _type; value = _value; generic1 = NULL; generic2 = NULL; generic3 = NULL; } Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, Node* _generic1) : Node(_context) { typeType = _type; value = NULL; generic1 = _generic1; generic2 = NULL; generic3 = NULL; } Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, Node* _generic1, Node* _generic2) : Node(_context) { typeType = _type; value = NULL; generic1 = _generic1; generic2 = _generic2; generic3 = NULL; } Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, Node* _generic1, Node* _generic2, Node* _generic3) : Node(_context) { typeType = _type; value = NULL; generic1 = _generic1; generic2 = _generic2; generic3 = _generic3; } int Krystal::NodePacketMemberType::getType() { switch (typeType) { case Parser::token::PRIMITIVE_DATA_TYPE: { return CsNodeType::packetMemberTypePrimitive; } break; case Parser::token::REFERENCE_DATA_TYPE: { return CsNodeType::packetMemberTypeReference; } break; case Parser::token::MAP: { return CsNodeType::packetMemberTypeMap; } break; case Parser::token::LIST: { return CsNodeType::packetMemberTypeList; } break; } return CsNodeType::packetMemberType; } size_t Krystal::NodePacketMemberType::getHash(vector<Node*>* referencingStack) { assert(referencingStack != NULL); size_t packetMemberTypeHash = 0; switch(typeType) { case Parser::token::PRIMITIVE_DATA_TYPE: { packetMemberTypeHash = getHashCode(value); } break; case Parser::token::REFERENCE_DATA_TYPE: { // lookup Context::declarations table Node* typePacketNode = context->getDeclarationNode(value); if (typePacketNode == NULL) { throw(runtime_error("No such packet type.")); } packetMemberTypeHash = typePacketNode->getHash(referencingStack); } break; case Parser::token::MAP: { // must be specified this is map type // in case of other generic<t1, t2> added. packetMemberTypeHash = getHashCode((int)Parser::token::MAP); combineHashCode(packetMemberTypeHash, generic1->getHash(referencingStack)); combineHashCode(packetMemberTypeHash, generic2->getHash(referencingStack)); } break; case Parser::token::LIST: { // must be specified this is list type // in case of other generic<t> added. packetMemberTypeHash = getHashCode((int)Parser::token::LIST); combineHashCode(packetMemberTypeHash, generic1->getHash(referencingStack)); } break; } return packetMemberTypeHash; } string* Krystal::NodePacketMemberType::getParsed(int as) { stringstream parsed; switch (as) { case CsParseAs::Default: { switch (typeType) { case Parser::token::PRIMITIVE_DATA_TYPE: case Parser::token::REFERENCE_DATA_TYPE: { parsed << *value; } break; case Parser::token::MAP: { parsed << format(TCS_PACKET_MEMBER_TYPE_MAP_AS_DEFAULT) % *(generic1->getParsed(CsParseAs::Default)) % *(generic2->getParsed(CsParseAs::Default)); } break; case Parser::token::LIST: { parsed << format(TCS_PACKET_MEMBER_TYPE_LIST_AS_DEFAULT) % *(generic1->getParsed(CsParseAs::Default)); } break; default: { throw(runtime_error("Unknown NodePacketMemberType type.")); } break; } } break; case CsParseAs::GenericType1: { parsed << *(generic1->getParsed(CsParseAs::Default)); } break; case CsParseAs::GenericType2: { parsed << *(generic2->getParsed(CsParseAs::Default)); } break; case CsParseAs::GenericType3: { parsed << *(generic3->getParsed(CsParseAs::Default)); } break; case CsParseAs::GenericTypeSerializer1: { parsed << *(generic1->getParsed(CsParseAs::SerializerName)); } break; case CsParseAs::GenericTypeSerializer2: { parsed << *(generic2->getParsed(CsParseAs::SerializerName)); } break; case CsParseAs::GenericTypeSerializer3: { parsed << *(generic3->getParsed(CsParseAs::SerializerName)); } break; case CsParseAs::SerializerName: { switch (typeType) { case Parser::token::PRIMITIVE_DATA_TYPE: { string* serializerName = lookupSerializerName(value); parsed << *serializerName; } break; case Parser::token::REFERENCE_DATA_TYPE: { parsed << TCS_PACKET_CUSTOM_SERIALIZER_NAME; } break; default: { throw(runtime_error("Serializer not supported for nested generic type")); } break; } } break; case CsParseAs::Initialization: { switch (typeType) { case Parser::token::PRIMITIVE_DATA_TYPE: { parsed << ""; } break; case Parser::token::REFERENCE_DATA_TYPE: case Parser::token::MAP: case Parser::token::LIST: { parsed << format(TCS_PACKET_MEMBER_TYPE_NEW_AS_INITIALIZATION) % *(getParsed(CsParseAs::Default)); } break; default: { throw(runtime_error("Unknown NodePacketMemberType type.")); } break; } } break; } return new string(parsed.str()); } // }; // class NodePacketMemberName : public Node // { // string* value; // public: Krystal::NodePacketMemberName::NodePacketMemberName(Context* _context, string* _value) : Node(_context) { value = _value; } int Krystal::NodePacketMemberName::getType() { return CsNodeType::packetMemberName; } size_t Krystal::NodePacketMemberName::getHash(vector<Node*>* referencingStack) { size_t packetMemberNameHash = getHashCode(value); return packetMemberNameHash; } string* Krystal::NodePacketMemberName::getParsed(int as) { return value; } // }; <|endoftext|>
<commit_before>#include <cassert> #include <cstring> #include <sstream> #include <sys/time.h> #include <unordered_set> #include <derecho/conf/conf.hpp> #include <derecho/core/detail/p2p_connection_manager.hpp> #include <derecho/sst/detail/poll_utils.hpp> #include <derecho/utils/logger.hpp> namespace sst { P2PConnectionManager::P2PConnectionManager(const P2PParams params) : my_node_id(params.my_node_id), failure_upcall(params.failure_upcall) { // HARD-CODED. Adding another request type will break this request_params.window_sizes[P2P_REPLY] = params.p2p_window_size; request_params.window_sizes[P2P_REQUEST] = params.p2p_window_size; request_params.window_sizes[RPC_REPLY] = params.rpc_window_size; request_params.max_msg_sizes[P2P_REPLY] = params.max_p2p_reply_size; request_params.max_msg_sizes[P2P_REQUEST] = params.max_p2p_request_size; request_params.max_msg_sizes[RPC_REPLY] = params.max_rpc_reply_size; p2p_buf_size = 0; for(uint8_t i = 0; i < num_request_types; ++i) { request_params.offsets[i] = p2p_buf_size; p2p_buf_size += request_params.window_sizes[i] * request_params.max_msg_sizes[i]; } p2p_buf_size += sizeof(bool); p2p_connections[my_node_id] = std::make_unique<P2PConnection>(my_node_id, my_node_id, p2p_buf_size, request_params); // external client doesn't need failure checking if (!params.is_external) { timeout_thread = std::thread(&P2PConnectionManager::check_failures_loop, this); } } P2PConnectionManager::~P2PConnectionManager() { shutdown_failures_thread(); } void P2PConnectionManager::add_connections(const std::vector<node_id_t>& node_ids) { std::lock_guard<std::mutex> lock(connections_mutex); for (const node_id_t remote_id : node_ids) { if (p2p_connections.find(remote_id) == p2p_connections.end()) { p2p_connections.emplace(remote_id, std::make_unique<P2PConnection>(my_node_id, remote_id, p2p_buf_size, request_params)); } } } void P2PConnectionManager::remove_connections(const std::vector<node_id_t>& node_ids) { std::lock_guard<std::mutex> lock(connections_mutex); for(const node_id_t remote_id : node_ids) { p2p_connections.erase(remote_id); } } bool P2PConnectionManager::contains_node(const node_id_t node_id) { std::lock_guard<std::mutex> lock(connections_mutex); return (p2p_connections.find(node_id) != p2p_connections.end()); } void P2PConnectionManager::shutdown_failures_thread() { thread_shutdown = true; if(timeout_thread.joinable()) { timeout_thread.join(); } } uint64_t P2PConnectionManager::get_max_p2p_reply_size() { return request_params.max_msg_sizes[P2P_REPLY] - sizeof(uint64_t); } void P2PConnectionManager::update_incoming_seq_num() { p2p_connections[last_node_id]->update_incoming_seq_num(); } // check if there's a new request from any node std::optional<std::pair<node_id_t, char*>> P2PConnectionManager::probe_all() { for(const auto& [node_id, p2p_conn] : p2p_connections) { auto buf = p2p_conn->probe(); if(buf && buf[0]) { last_node_id = node_id; return std::pair<node_id_t, char*>(node_id, buf); } else if(buf) { // this means that we have a null reply // we don't need to process it, but we still want to increment the seq num p2p_conn->update_incoming_seq_num(); return std::pair<node_id_t, char*>(INVALID_NODE_ID, nullptr); } } return {}; } char* P2PConnectionManager::get_sendbuffer_ptr(node_id_t node_id, REQUEST_TYPE type) { return p2p_connections.at(node_id)->get_sendbuffer_ptr(type); } void P2PConnectionManager::send(node_id_t node_id) { p2p_connections.at(node_id)->send(); if(node_id != my_node_id) { p2p_connections.at(node_id)->num_rdma_writes++; } } void P2PConnectionManager::check_failures_loop() { pthread_setname_np(pthread_self(), "p2p_timeout"); // using CONF_DERECHO_HEARTBEAT_MS from derecho.cfg uint32_t heartbeat_ms = derecho::getConfUInt32(CONF_DERECHO_HEARTBEAT_MS); const auto tid = std::this_thread::get_id(); // get id first uint32_t ce_idx = util::polling_data.get_index(tid); uint16_t tick_count = 0; const uint16_t one_second_count = 1000/heartbeat_ms; while(!thread_shutdown) { std::this_thread::sleep_for(std::chrono::milliseconds(heartbeat_ms)); tick_count++; std::unordered_set<node_id_t> posted_write_to; util::polling_data.set_waiting(tid); #ifdef USE_VERBS_API std::map<uint32_t, verbs_sender_ctxt> sctxt; #else std::map<uint32_t, lf_sender_ctxt> sctxt; #endif for(const auto& [node_id, p2p_conn] : p2p_connections) { // checks every second regardless of num_rdma_writes if (node_id == my_node_id || (p2p_conn->num_rdma_writes < 1000 && tick_count < one_second_count)) { continue; } p2p_conn->num_rdma_writes = 0; sctxt[node_id].set_remote_id(node_id); sctxt[node_id].set_ce_idx(ce_idx); p2p_conn->get_res()->post_remote_write_with_completion(&sctxt[node_id], p2p_buf_size - sizeof(bool), sizeof(bool)); posted_write_to.insert(node_id); } if (tick_count >= one_second_count) { tick_count = 0; } // track which nodes respond successfully std::unordered_set<node_id_t> polled_successfully_from; std::vector<node_id_t> failed_node_indexes; /** Completion Queue poll timeout in millisec */ const unsigned int MAX_POLL_CQ_TIMEOUT = derecho::getConfUInt32(CONF_DERECHO_SST_POLL_CQ_TIMEOUT_MS); unsigned long start_time_msec; unsigned long cur_time_msec; struct timeval cur_time; // wait for completion for a while before giving up of doing it .. gettimeofday(&cur_time, NULL); start_time_msec = (cur_time.tv_sec * 1000) + (cur_time.tv_usec / 1000); for(unsigned int i = 0; i < posted_write_to.size(); i++) { std::optional<std::pair<int32_t, int32_t>> ce; while(true) { // check if polling result is available ce = util::polling_data.get_completion_entry(tid); if(ce) { break; } gettimeofday(&cur_time, NULL); cur_time_msec = (cur_time.tv_sec * 1000) + (cur_time.tv_usec / 1000); if((cur_time_msec - start_time_msec) >= MAX_POLL_CQ_TIMEOUT) { tick_count += MAX_POLL_CQ_TIMEOUT; break; } } // if waiting for a completion entry timed out if(!ce) { // mark all nodes that have not yet responded as failed for(const auto& pair : p2p_connections) { const auto& node_id = pair.first; if(posted_write_to.find(node_id) == posted_write_to.end() || polled_successfully_from.find(node_id) != polled_successfully_from.end()) { continue; } failed_node_indexes.push_back(node_id); } break; } auto ce_v = ce.value(); int remote_id = ce_v.first; int result = ce_v.second; if(result == 1) { polled_successfully_from.insert(remote_id); } else if(result == -1) { failed_node_indexes.push_back(remote_id); } } util::polling_data.reset_waiting(tid); for(auto nid : failed_node_indexes) { dbg_default_debug("p2p_connection_manager detected failure/timeout on node {}", nid); p2p_connections.at(nid)->get_res()->report_failure(); if(failure_upcall) { failure_upcall(nid); } } } } void P2PConnectionManager::filter_to(const std::vector<node_id_t>& live_nodes_list) { std::vector<node_id_t> prev_nodes_list; for (const auto& e : p2p_connections ) { prev_nodes_list.push_back(e.first); } std::vector<node_id_t> departed; std::set_difference(prev_nodes_list.begin(), prev_nodes_list.end(), live_nodes_list.begin(), live_nodes_list.end(), std::back_inserter(departed)); remove_connections(departed); } void P2PConnectionManager::debug_print() { // std::cout << "Members: " << std::endl; // for(const auto& [node_id, p2p_conn] : p2p_connections) { // std::cout << node_id << " "; // } // std::cout << std::endl; // for(const auto& type : p2p_request_types) { // std::cout << "P2PConnections: Request type " << type << std::endl; // for(uint32_t node = 0; node < num_members; ++node) { // std::cout << "Node " << node << std::endl; // std::cout << "incoming seq_nums:"; // for(uint32_t i = 0; i < request_params.window_sizes[type]; ++i) { // uint64_t offset = request_params.max_msg_sizes[type] * (type * request_params.window_sizes[type] + i + 1) - sizeof(uint64_t); // std::cout << " " << (uint64_t&)p2p_connections[node]->incoming_p2p_buffer[offset]; // } // std::cout << std::endl // << "outgoing seq_nums:"; // for(uint32_t i = 0; i < request_params.window_sizes[type]; ++i) { // uint64_t offset = request_params.max_msg_sizes[type] * (type * request_params.window_sizes[type] + i + 1) - sizeof(uint64_t); // std::cout << " " << (uint64_t&)p2p_connections[node]->outgoing_p2p_buffer[offset]; // } // std::cout << std::endl; // } // } } } // namespace sst <commit_msg>bugfix: testing null reply condition using the first byte in the buffer is not reliable. #187<commit_after>#include <cassert> #include <cstring> #include <sstream> #include <sys/time.h> #include <unordered_set> #include <derecho/conf/conf.hpp> #include <derecho/core/detail/p2p_connection_manager.hpp> #include <derecho/sst/detail/poll_utils.hpp> #include <derecho/utils/logger.hpp> namespace sst { P2PConnectionManager::P2PConnectionManager(const P2PParams params) : my_node_id(params.my_node_id), failure_upcall(params.failure_upcall) { // HARD-CODED. Adding another request type will break this request_params.window_sizes[P2P_REPLY] = params.p2p_window_size; request_params.window_sizes[P2P_REQUEST] = params.p2p_window_size; request_params.window_sizes[RPC_REPLY] = params.rpc_window_size; request_params.max_msg_sizes[P2P_REPLY] = params.max_p2p_reply_size; request_params.max_msg_sizes[P2P_REQUEST] = params.max_p2p_request_size; request_params.max_msg_sizes[RPC_REPLY] = params.max_rpc_reply_size; p2p_buf_size = 0; for(uint8_t i = 0; i < num_request_types; ++i) { request_params.offsets[i] = p2p_buf_size; p2p_buf_size += request_params.window_sizes[i] * request_params.max_msg_sizes[i]; } p2p_buf_size += sizeof(bool); p2p_connections[my_node_id] = std::make_unique<P2PConnection>(my_node_id, my_node_id, p2p_buf_size, request_params); // external client doesn't need failure checking if (!params.is_external) { timeout_thread = std::thread(&P2PConnectionManager::check_failures_loop, this); } } P2PConnectionManager::~P2PConnectionManager() { shutdown_failures_thread(); } void P2PConnectionManager::add_connections(const std::vector<node_id_t>& node_ids) { std::lock_guard<std::mutex> lock(connections_mutex); for (const node_id_t remote_id : node_ids) { if (p2p_connections.find(remote_id) == p2p_connections.end()) { p2p_connections.emplace(remote_id, std::make_unique<P2PConnection>(my_node_id, remote_id, p2p_buf_size, request_params)); } } } void P2PConnectionManager::remove_connections(const std::vector<node_id_t>& node_ids) { std::lock_guard<std::mutex> lock(connections_mutex); for(const node_id_t remote_id : node_ids) { p2p_connections.erase(remote_id); } } bool P2PConnectionManager::contains_node(const node_id_t node_id) { std::lock_guard<std::mutex> lock(connections_mutex); return (p2p_connections.find(node_id) != p2p_connections.end()); } void P2PConnectionManager::shutdown_failures_thread() { thread_shutdown = true; if(timeout_thread.joinable()) { timeout_thread.join(); } } uint64_t P2PConnectionManager::get_max_p2p_reply_size() { return request_params.max_msg_sizes[P2P_REPLY] - sizeof(uint64_t); } void P2PConnectionManager::update_incoming_seq_num() { p2p_connections[last_node_id]->update_incoming_seq_num(); } // check if there's a new request from any node std::optional<std::pair<node_id_t, char*>> P2PConnectionManager::probe_all() { for(const auto& [node_id, p2p_conn] : p2p_connections) { auto buf = p2p_conn->probe(); // In include/derecho/core/detail/rpc_utils.hpp: // Please note that populate_header() put payload_size(size_t) at the beginning of buffer. // If we only test buf[0], it will fall in the wrong path if the least significant byte of the payload size is // zero. if(buf && reinterpret_cast<size_t*>(buf)[0]) { last_node_id = node_id; return std::pair<node_id_t, char*>(node_id, buf); } else if(buf) { // this means that we have a null reply // we don't need to process it, but we still want to increment the seq num p2p_conn->update_incoming_seq_num(); return std::pair<node_id_t, char*>(INVALID_NODE_ID, nullptr); } } return {}; } char* P2PConnectionManager::get_sendbuffer_ptr(node_id_t node_id, REQUEST_TYPE type) { return p2p_connections.at(node_id)->get_sendbuffer_ptr(type); } void P2PConnectionManager::send(node_id_t node_id) { p2p_connections.at(node_id)->send(); if(node_id != my_node_id) { p2p_connections.at(node_id)->num_rdma_writes++; } } void P2PConnectionManager::check_failures_loop() { pthread_setname_np(pthread_self(), "p2p_timeout"); // using CONF_DERECHO_HEARTBEAT_MS from derecho.cfg uint32_t heartbeat_ms = derecho::getConfUInt32(CONF_DERECHO_HEARTBEAT_MS); const auto tid = std::this_thread::get_id(); // get id first uint32_t ce_idx = util::polling_data.get_index(tid); uint16_t tick_count = 0; const uint16_t one_second_count = 1000/heartbeat_ms; while(!thread_shutdown) { std::this_thread::sleep_for(std::chrono::milliseconds(heartbeat_ms)); tick_count++; std::unordered_set<node_id_t> posted_write_to; util::polling_data.set_waiting(tid); #ifdef USE_VERBS_API std::map<uint32_t, verbs_sender_ctxt> sctxt; #else std::map<uint32_t, lf_sender_ctxt> sctxt; #endif for(const auto& [node_id, p2p_conn] : p2p_connections) { // checks every second regardless of num_rdma_writes if (node_id == my_node_id || (p2p_conn->num_rdma_writes < 1000 && tick_count < one_second_count)) { continue; } p2p_conn->num_rdma_writes = 0; sctxt[node_id].set_remote_id(node_id); sctxt[node_id].set_ce_idx(ce_idx); p2p_conn->get_res()->post_remote_write_with_completion(&sctxt[node_id], p2p_buf_size - sizeof(bool), sizeof(bool)); posted_write_to.insert(node_id); } if (tick_count >= one_second_count) { tick_count = 0; } // track which nodes respond successfully std::unordered_set<node_id_t> polled_successfully_from; std::vector<node_id_t> failed_node_indexes; /** Completion Queue poll timeout in millisec */ const unsigned int MAX_POLL_CQ_TIMEOUT = derecho::getConfUInt32(CONF_DERECHO_SST_POLL_CQ_TIMEOUT_MS); unsigned long start_time_msec; unsigned long cur_time_msec; struct timeval cur_time; // wait for completion for a while before giving up of doing it .. gettimeofday(&cur_time, NULL); start_time_msec = (cur_time.tv_sec * 1000) + (cur_time.tv_usec / 1000); for(unsigned int i = 0; i < posted_write_to.size(); i++) { std::optional<std::pair<int32_t, int32_t>> ce; while(true) { // check if polling result is available ce = util::polling_data.get_completion_entry(tid); if(ce) { break; } gettimeofday(&cur_time, NULL); cur_time_msec = (cur_time.tv_sec * 1000) + (cur_time.tv_usec / 1000); if((cur_time_msec - start_time_msec) >= MAX_POLL_CQ_TIMEOUT) { tick_count += MAX_POLL_CQ_TIMEOUT; break; } } // if waiting for a completion entry timed out if(!ce) { // mark all nodes that have not yet responded as failed for(const auto& pair : p2p_connections) { const auto& node_id = pair.first; if(posted_write_to.find(node_id) == posted_write_to.end() || polled_successfully_from.find(node_id) != polled_successfully_from.end()) { continue; } failed_node_indexes.push_back(node_id); } break; } auto ce_v = ce.value(); int remote_id = ce_v.first; int result = ce_v.second; if(result == 1) { polled_successfully_from.insert(remote_id); } else if(result == -1) { failed_node_indexes.push_back(remote_id); } } util::polling_data.reset_waiting(tid); for(auto nid : failed_node_indexes) { dbg_default_debug("p2p_connection_manager detected failure/timeout on node {}", nid); p2p_connections.at(nid)->get_res()->report_failure(); if(failure_upcall) { failure_upcall(nid); } } } } void P2PConnectionManager::filter_to(const std::vector<node_id_t>& live_nodes_list) { std::vector<node_id_t> prev_nodes_list; for (const auto& e : p2p_connections ) { prev_nodes_list.push_back(e.first); } std::vector<node_id_t> departed; std::set_difference(prev_nodes_list.begin(), prev_nodes_list.end(), live_nodes_list.begin(), live_nodes_list.end(), std::back_inserter(departed)); remove_connections(departed); } void P2PConnectionManager::debug_print() { // std::cout << "Members: " << std::endl; // for(const auto& [node_id, p2p_conn] : p2p_connections) { // std::cout << node_id << " "; // } // std::cout << std::endl; // for(const auto& type : p2p_request_types) { // std::cout << "P2PConnections: Request type " << type << std::endl; // for(uint32_t node = 0; node < num_members; ++node) { // std::cout << "Node " << node << std::endl; // std::cout << "incoming seq_nums:"; // for(uint32_t i = 0; i < request_params.window_sizes[type]; ++i) { // uint64_t offset = request_params.max_msg_sizes[type] * (type * request_params.window_sizes[type] + i + 1) - sizeof(uint64_t); // std::cout << " " << (uint64_t&)p2p_connections[node]->incoming_p2p_buffer[offset]; // } // std::cout << std::endl // << "outgoing seq_nums:"; // for(uint32_t i = 0; i < request_params.window_sizes[type]; ++i) { // uint64_t offset = request_params.max_msg_sizes[type] * (type * request_params.window_sizes[type] + i + 1) - sizeof(uint64_t); // std::cout << " " << (uint64_t&)p2p_connections[node]->outgoing_p2p_buffer[offset]; // } // std::cout << std::endl; // } // } } } // namespace sst <|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/common/adapters/adapter_manager.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/util/util.h" namespace apollo { namespace common { namespace adapter { AdapterManager::AdapterManager() {} void AdapterManager::Observe() { for (const auto observe : instance()->observers_) { observe(); } } bool AdapterManager::Initialized() { return instance()->initialized_; } void AdapterManager::Reset() { instance()->initialized_ = false; } void AdapterManager::Init(const std::string &adapter_config_filename) { // Parse config file AdapterManagerConfig configs; CHECK(util::GetProtoFromFile(adapter_config_filename, &configs)) << "Unable to parse adapter config file " << adapter_config_filename; AINFO << "Init AdapterManger config:" << configs.DebugString(); Init(configs); } void AdapterManager::Init(const AdapterManagerConfig &configs) { if (Initialized()) { return; } instance()->initialized_ = true; if (configs.is_ros()) { instance()->node_handle_.reset(new ros::NodeHandle()); } for (const auto &config : configs.config()) { switch (config.type()) { case AdapterConfig::POINT_CLOUD: EnablePointCloud(FLAGS_pointcloud_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::GPS: EnableGps(FLAGS_gps_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::IMU: EnableImu(FLAGS_imu_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::CHASSIS: EnableChassis(FLAGS_chassis_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::LOCALIZATION: EnableLocalization(FLAGS_localization_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::PERCEPTION_OBSTACLES: EnablePerceptionObstacles(FLAGS_perception_obstacle_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::TRAFFIC_LIGHT_DETECTION: EnableTrafficLightDetection(FLAGS_traffic_light_detection_topic, config.mode(), config.message_history_limit()); case AdapterConfig::PAD: EnablePad(FLAGS_pad_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::CONTROL_COMMAND: EnableControlCommand(FLAGS_control_command_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::ROUTING_REQUEST: EnableRoutingRequest(FLAGS_routing_request_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::ROUTING_RESPONSE: EnableRoutingResponse(FLAGS_routing_response_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::PLANNING_TRAJECTORY: EnablePlanning(FLAGS_planning_trajectory_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::PREDICTION: EnablePrediction(FLAGS_prediction_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::MONITOR: EnableMonitor(FLAGS_monitor_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::CHASSIS_DETAIL: EnableChassisDetail(FLAGS_chassis_detail_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::RELATIVE_ODOMETRY: EnableRelativeOdometry(FLAGS_relative_odometry_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::INS_STAT: EnableInsStat(FLAGS_ins_stat_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::HMI_COMMAND: EnableHMICommand(FLAGS_hmi_command_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::MOBILEYE: EnableMobileye(FLAGS_mobileye_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::DELPHIESR: EnableDelphiESR(FLAGS_delphi_esr_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::COMPRESSED_IMAGE: EnableCompressedImage(FLAGS_compressed_image_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::HMI_STATUS: EnableHMIStatus(FLAGS_hmi_status_topic, config.mode(), config.message_history_limit()); break; default: AERROR << "Unknown adapter config type!"; break; } } } } // namespace adapter } // namespace common } // namespace apollo <commit_msg>Common: Fix reset (#920)<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/common/adapters/adapter_manager.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/util/util.h" namespace apollo { namespace common { namespace adapter { AdapterManager::AdapterManager() {} void AdapterManager::Observe() { for (const auto observe : instance()->observers_) { observe(); } } bool AdapterManager::Initialized() { return instance()->initialized_; } void AdapterManager::Reset() { instance()->initialized_ = false; instance()->observers_.clear(); } void AdapterManager::Init(const std::string &adapter_config_filename) { // Parse config file AdapterManagerConfig configs; CHECK(util::GetProtoFromFile(adapter_config_filename, &configs)) << "Unable to parse adapter config file " << adapter_config_filename; AINFO << "Init AdapterManger config:" << configs.DebugString(); Init(configs); } void AdapterManager::Init(const AdapterManagerConfig &configs) { if (Initialized()) { return; } instance()->initialized_ = true; if (configs.is_ros()) { instance()->node_handle_.reset(new ros::NodeHandle()); } for (const auto &config : configs.config()) { switch (config.type()) { case AdapterConfig::POINT_CLOUD: EnablePointCloud(FLAGS_pointcloud_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::GPS: EnableGps(FLAGS_gps_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::IMU: EnableImu(FLAGS_imu_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::CHASSIS: EnableChassis(FLAGS_chassis_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::LOCALIZATION: EnableLocalization(FLAGS_localization_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::PERCEPTION_OBSTACLES: EnablePerceptionObstacles(FLAGS_perception_obstacle_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::TRAFFIC_LIGHT_DETECTION: EnableTrafficLightDetection(FLAGS_traffic_light_detection_topic, config.mode(), config.message_history_limit()); case AdapterConfig::PAD: EnablePad(FLAGS_pad_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::CONTROL_COMMAND: EnableControlCommand(FLAGS_control_command_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::ROUTING_REQUEST: EnableRoutingRequest(FLAGS_routing_request_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::ROUTING_RESPONSE: EnableRoutingResponse(FLAGS_routing_response_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::PLANNING_TRAJECTORY: EnablePlanning(FLAGS_planning_trajectory_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::PREDICTION: EnablePrediction(FLAGS_prediction_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::MONITOR: EnableMonitor(FLAGS_monitor_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::CHASSIS_DETAIL: EnableChassisDetail(FLAGS_chassis_detail_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::RELATIVE_ODOMETRY: EnableRelativeOdometry(FLAGS_relative_odometry_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::INS_STAT: EnableInsStat(FLAGS_ins_stat_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::HMI_COMMAND: EnableHMICommand(FLAGS_hmi_command_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::MOBILEYE: EnableMobileye(FLAGS_mobileye_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::DELPHIESR: EnableDelphiESR(FLAGS_delphi_esr_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::COMPRESSED_IMAGE: EnableCompressedImage(FLAGS_compressed_image_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::HMI_STATUS: EnableHMIStatus(FLAGS_hmi_status_topic, config.mode(), config.message_history_limit()); break; default: AERROR << "Unknown adapter config type!"; break; } } } } // namespace adapter } // namespace common } // namespace apollo <|endoftext|>
<commit_before>/* <x0/mod_accesslog.cpp> * * This file is part of the x0 web server, released under GPLv3. * (c) 2009 Chrisitan Parpart <[email protected]> */ #include <x0/server.hpp> #include <x0/request.hpp> #include <x0/response.hpp> #include <x0/header.hpp> #include <x0/strutils.hpp> #include <x0/types.hpp> #include <boost/lexical_cast.hpp> #include <boost/bind.hpp> #include <iostream> #include <cstring> #include <cerrno> /** * \ingroup modules * \brief implements an accesslog log facility - in spirit of "combined" mode of apache's accesslog logs. */ class accesslog_plugin : public x0::plugin { private: boost::signals::connection c; std::string filename; int fd; public: accesslog_plugin(x0::server& srv, const std::string& name) : x0::plugin(srv, name), filename(), fd(-1) { c = srv.request_done.connect(boost::bind(&accesslog_plugin::request_done, this, _1, _2)); } ~accesslog_plugin() { server_.request_done.disconnect(c); if (fd != -1) { ::close(fd); } } virtual void configure() { // TODO retrieve file to store accesslog log to. filename = server_.get_config().get("service", "accesslog-filename"); if (!filename.empty()) { fd = ::open(filename.c_str(), O_APPEND | O_WRONLY | O_CREAT | O_LARGEFILE, 0644); if (fd == -1) { LOG(server_, x0::severity::error, "Could not open access log file."); } } } private: void request_done(x0::request& in, x0::response& out) { if (fd != -1) { std::stringstream sstr; sstr << hostname(in); sstr << " - "; // identity as of identd sstr << username(in) << ' '; sstr << now() << " \""; sstr << request_line(in) << "\" "; sstr << out.status << ' '; sstr << out.content.length() << ' '; sstr << '"' << get_header(in, "Referer") << "\" "; sstr << '"' << get_header(in, "User-Agent") << '"'; sstr << std::endl; std::string line(sstr.str()); ::write(fd, line.c_str(), line.size()); } } inline std::string hostname(x0::request& in) { std::string name = in.connection->socket().remote_endpoint().address().to_string(); return !name.empty() ? name : "-"; } inline std::string username(x0::request& in) { return !in.username.empty() ? in.username : "-"; } inline std::string request_line(x0::request& in) { std::stringstream str; str << in.method << ' ' << in.uri << " HTTP/" << in.http_version_major << '.' << in.http_version_minor; return str.str(); } inline std::string now() { char buf[26]; std::time_t ts = time(0); if (struct tm *tm = localtime(&ts)) { if (strftime(buf, sizeof(buf), "[%m/%d/%y:%T %z]", tm) != 0) { return buf; } } return "-"; } inline std::string get_header(const x0::request& in, const std::string& name) { std::string value(in.get_header(name)); return !value.empty() ? value : "-"; } }; extern "C" x0::plugin *accesslog_init(x0::server& srv, const std::string& name) { return new accesslog_plugin(srv, name); } <commit_msg>typo fix in timestamp format<commit_after>/* <x0/mod_accesslog.cpp> * * This file is part of the x0 web server, released under GPLv3. * (c) 2009 Chrisitan Parpart <[email protected]> */ #include <x0/server.hpp> #include <x0/request.hpp> #include <x0/response.hpp> #include <x0/header.hpp> #include <x0/strutils.hpp> #include <x0/types.hpp> #include <boost/lexical_cast.hpp> #include <boost/bind.hpp> #include <iostream> #include <cstring> #include <cerrno> /** * \ingroup modules * \brief implements an accesslog log facility - in spirit of "combined" mode of apache's accesslog logs. */ class accesslog_plugin : public x0::plugin { private: boost::signals::connection c; std::string filename; int fd; public: accesslog_plugin(x0::server& srv, const std::string& name) : x0::plugin(srv, name), filename(), fd(-1) { c = srv.request_done.connect(boost::bind(&accesslog_plugin::request_done, this, _1, _2)); } ~accesslog_plugin() { server_.request_done.disconnect(c); if (fd != -1) { ::close(fd); } } virtual void configure() { // TODO retrieve file to store accesslog log to. filename = server_.get_config().get("service", "accesslog-filename"); if (!filename.empty()) { fd = ::open(filename.c_str(), O_APPEND | O_WRONLY | O_CREAT | O_LARGEFILE, 0644); if (fd == -1) { LOG(server_, x0::severity::error, "Could not open access log file."); } } } private: void request_done(x0::request& in, x0::response& out) { if (fd != -1) { std::stringstream sstr; sstr << hostname(in); sstr << " - "; // identity as of identd sstr << username(in) << ' '; sstr << now() << " \""; sstr << request_line(in) << "\" "; sstr << out.status << ' '; sstr << out.content.length() << ' '; sstr << '"' << get_header(in, "Referer") << "\" "; sstr << '"' << get_header(in, "User-Agent") << '"'; sstr << std::endl; std::string line(sstr.str()); ::write(fd, line.c_str(), line.size()); } } inline std::string hostname(x0::request& in) { std::string name = in.connection->socket().remote_endpoint().address().to_string(); return !name.empty() ? name : "-"; } inline std::string username(x0::request& in) { return !in.username.empty() ? in.username : "-"; } inline std::string request_line(x0::request& in) { std::stringstream str; str << in.method << ' ' << in.uri << " HTTP/" << in.http_version_major << '.' << in.http_version_minor; return str.str(); } inline std::string now() { char buf[26]; std::time_t ts = time(0); if (struct tm *tm = localtime(&ts)) { if (strftime(buf, sizeof(buf), "[%m/%d/%Y:%T %z]", tm) != 0) { return buf; } } return "-"; } inline std::string get_header(const x0::request& in, const std::string& name) { std::string value(in.get_header(name)); return !value.empty() ? value : "-"; } }; extern "C" x0::plugin *accesslog_init(x0::server& srv, const std::string& name) { return new accesslog_plugin(srv, name); } <|endoftext|>
<commit_before>#include <limits> #include <string> #include <utility> // Algorithm to be tested template <class Type> constexpr Type to_base(char c, unsigned base) { return base <= 10 ? c - '0' : (c > '9' ? static_cast<Type>(c-'a'+10) : static_cast<Type>(c-'0')); } template <class OutType> constexpr OutType _atox(const char* expression, unsigned base, OutType prev = OutType()) { return *expression == '\0' ? prev : (*expression == '-' ? -_atox(expression +1, base, prev) : _atox(expression +1, base, prev * base + to_base<OutType>(*expression, base))); } constexpr auto string_to_int(const char* expression, unsigned base=10) { return _atox<int>(expression, base); } auto string_to_int(std::string const& expression, unsigned base=10) { return string_to_int(expression.c_str(), base); } constexpr auto string_to_long(const char* expression, unsigned base=10) { return _atox<long>(expression, base); } auto string_to_long(std::string const& expression, unsigned base=10) { return string_to_long(expression.c_str(), base); } constexpr auto string_to_longlong(const char* expression, unsigned base=10) { return _atox<long long>(expression, base); } auto string_to_longlong(std::string const& expression, unsigned base=10) { return string_to_longlong(expression.c_str(), base); } <commit_msg>[visual studio][string-to-int] Bad template instanciation<commit_after>#include <limits> #include <string> #include <utility> // Algorithm to be tested template <class Type> constexpr Type to_base(char c, unsigned base) { return base <= 10 ? c - '0' : (c > '9' ? static_cast<Type>(c-'a'+10) : static_cast<Type>(c-'0')); } template <class OutType> constexpr OutType _atox(const char* expression, unsigned base, OutType prev = OutType()) { return *expression == '\0' ? prev : (*expression == '-' ? -_atox(expression +1, base, prev) : _atox(expression +1, base, static_cast<OutType>(prev * base + to_base<OutType>(*expression, base)))); } constexpr auto string_to_int(const char* expression, unsigned base=10) { return _atox<int>(expression, base); } auto string_to_int(std::string const& expression, unsigned base=10) { return string_to_int(expression.c_str(), base); } constexpr auto string_to_long(const char* expression, unsigned base=10) { return _atox<long>(expression, base); } auto string_to_long(std::string const& expression, unsigned base=10) { return string_to_long(expression.c_str(), base); } constexpr auto string_to_longlong(const char* expression, unsigned base=10) { return _atox<long long>(expression, base); } auto string_to_longlong(std::string const& expression, unsigned base=10) { return string_to_longlong(expression.c_str(), base); } <|endoftext|>
<commit_before>#ifndef VOLE_VALUE #define VOLE_VALUE #include "slice.hpp" namespace Vole { struct Value; using String = Slice<char>; using Vector = Slice<Value>; struct Value { enum Type { BOOLEAN, NUMBER, // SYMBOL, STRING, // REGEXP, VECTOR, // MAPPING } type; // for garbage collection enum Color { BLACK, GRAY, WHITE } color; union Content { bool boolean; double number; // wrapper around a String, every symbol with a name is unique // Symbol symbol; String string; // Regexp regexp; Vector vector; // Mapping mapping; Content(bool b) : boolean(b) { } Content(double d) : number(d) { } // Content(Symbol s) { new (&symbol) Symbol(s); } Content(String s) { new (&string) String(s); } Content(Vector v) { new (&vector) Vector(v); } // Content(Mapping m) { new (&mapping) Mapping(m); } } content; template <typename T> Value(T thing, Color c = BLACK) : type(BOOLEAN), color(c), content(true) { } operator std::string() { std::stringstream ss; switch (type) { case BOOLEAN: { ss << content.boolean; } break; case NUMBER: { ss << content.number; } break; case STRING: { ss << content.string; } break; case VECTOR: { ss << content.vector; } break; } return ss.str(); } }; template <> Value::Value(bool b, Color c) : type(BOOLEAN), color(c), content(b) { } template <> Value::Value(double d, Color c) : type(NUMBER), color(c), content(d) { } template <> Value::Value(String s, Color c) : type(STRING), color(c), content(s) { } template <> Value::Value(Vector v, Color c) : type(VECTOR), color(c), content(v) { } template <typename IOS> IOS& operator<<(IOS& ios, Value val) { switch (val.type) { case Value::BOOLEAN: { ios << val.content.boolean; } break; case Value::NUMBER: { ios << val.content.number; } break; case Value::STRING: { ios << val.content.string; } break; case Value::VECTOR: { ios << val.content.vector; } break; } return ios; } } #endif<commit_msg>making bools look more traditional<commit_after>#ifndef VOLE_VALUE #define VOLE_VALUE #include "slice.hpp" namespace Vole { struct Value; using String = Slice<char>; using Vector = Slice<Value>; struct Value { enum Type { BOOLEAN, NUMBER, // SYMBOL, STRING, // REGEXP, VECTOR, // MAPPING } type; // for garbage collection enum Color { BLACK, GRAY, WHITE } color; union Content { bool boolean; double number; // wrapper around a String, every symbol with a name is unique // Symbol symbol; String string; // Regexp regexp; Vector vector; // Mapping mapping; Content(bool b) : boolean(b) { } Content(double d) : number(d) { } // Content(Symbol s) { new (&symbol) Symbol(s); } Content(String s) { new (&string) String(s); } Content(Vector v) { new (&vector) Vector(v); } // Content(Mapping m) { new (&mapping) Mapping(m); } } content; template <typename T> Value(T thing, Color c = BLACK) : type(BOOLEAN), color(c), content(true) { } operator std::string() { std::stringstream ss; switch (type) { case BOOLEAN: { ss << (content.boolean ? "#t" : "#f"); } break; case NUMBER: { ss << content.number; } break; case STRING: { ss << content.string; } break; case VECTOR: { ss << content.vector; } break; } return ss.str(); } }; template <> Value::Value(bool b, Color c) : type(BOOLEAN), color(c), content(b) { } template <> Value::Value(double d, Color c) : type(NUMBER), color(c), content(d) { } template <> Value::Value(String s, Color c) : type(STRING), color(c), content(s) { } template <> Value::Value(Vector v, Color c) : type(VECTOR), color(c), content(v) { } template <typename IOS> IOS& operator<<(IOS& ios, Value val) { switch (val.type) { case Value::BOOLEAN: { ios << (val.content.boolean ? "#t" : "#f"); } break; case Value::NUMBER: { ios << val.content.number; } break; case Value::STRING: { ios << val.content.string; } break; case Value::VECTOR: { ios << val.content.vector; } break; } return ios; } } #endif<|endoftext|>
<commit_before>/* * adcalendar.cpp - configuration file access * Program: KAlarm's alarm daemon (kalarmd) * Copyright (c) 2001, 2004, 2005 by David Jarvie <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kalarmd.h" #include <qregexp.h> #include <qstringlist.h> #include <kconfig.h> #include <kstandarddirs.h> #include <kdebug.h> #include "adcalendar.h" #include "adconfigdata.h" // Config file key strings const QString CLIENT_GROUP(QLatin1String("Client ")); const QRegExp CLIENT_GROUP_SEARCH("^Client "); // Client data file key strings const QString CALENDAR_KEY(QLatin1String("Calendar")); const QString TITLE_KEY(QLatin1String("Title")); const QString DCOP_OBJECT_KEY(QLatin1String("DCOP object")); const QString START_CLIENT_KEY(QLatin1String("Start")); /****************************************************************************** * Read the configuration file. * Create the client list and open all calendar files. */ void ADConfigData::readConfig() { kdDebug(5900) << "ADConfigData::readConfig()" << endl; ClientInfo::clear(); KConfig* config = KGlobal::config(); QStringList clients = config->groupList().filter(CLIENT_GROUP_SEARCH); for (QStringList::Iterator cl = clients.begin(); cl != clients.end(); ++cl) { // Read this client's configuration config->setGroup(*cl); QString client = *cl; client.remove(CLIENT_GROUP_SEARCH); QString title = config->readEntry(TITLE_KEY, client); // read app title (default = app name) QByteArray dcopObject = config->readEntry(DCOP_OBJECT_KEY, QString()).toLocal8Bit(); bool startClient = config->readEntry(START_CLIENT_KEY, QVariant(false)).toBool(); QString calendar = config->readPathEntry(CALENDAR_KEY); // Verify the configuration bool ok = false; if (client.isEmpty() || KStandardDirs::findExe(client).isNull()) kdError(5900) << "ADConfigData::readConfig(): group '" << *cl << "' deleted (client app not found)\n"; else if (calendar.isEmpty()) kdError(5900) << "ADConfigData::readConfig(): no calendar specified for '" << client << "'\n"; else if (dcopObject.isEmpty()) kdError(5900) << "ADConfigData::readConfig(): no DCOP object specified for '" << client << "'\n"; else { ADCalendar* cal = ADCalendar::calendar(calendar); if (cal) kdError(5900) << "ADConfigData::readConfig(): calendar registered by multiple clients: " << calendar << endl; else ok = true; } if (!ok) { config->deleteGroup(*cl, KConfig::NLS); continue; } // Create the client and calendar objects new ClientInfo(client.toLocal8Bit(), title, dcopObject, calendar, startClient); kdDebug(5900) << "ADConfigData::readConfig(): client " << client << " : calendar " << calendar << endl; } // Remove obsolete CheckInterval entry (if it exists) config->setGroup("General"); config->deleteEntry("CheckInterval"); // Save any updates config->sync(); } /****************************************************************************** * Write a client application's details to the config file. */ void ADConfigData::writeClient(const QByteArray& appName, const ClientInfo* cinfo) { KConfig* config = KGlobal::config(); config->setGroup(CLIENT_GROUP + QString::fromLocal8Bit(appName)); config->writeEntry(TITLE_KEY, cinfo->title()); config->writeEntry(DCOP_OBJECT_KEY, QString::fromLocal8Bit(cinfo->dcopObject())); config->writeEntry(START_CLIENT_KEY, cinfo->startClient()); config->writePathEntry(CALENDAR_KEY, cinfo->calendar()->urlString()); config->sync(); } /****************************************************************************** * Remove a client application's details from the config file. */ void ADConfigData::removeClient(const QByteArray& appName) { KConfig* config = KGlobal::config(); config->deleteGroup(CLIENT_GROUP + QString::fromLocal8Bit(appName)); config->sync(); } /****************************************************************************** * Set the calendar file URL for a specified application. */ void ADConfigData::setCalendar(const QByteArray& appName, ADCalendar* cal) { KConfig* config = KGlobal::config(); config->setGroup(CLIENT_GROUP + QString::fromLocal8Bit(appName)); config->writePathEntry(CALENDAR_KEY, cal->urlString()); config->sync(); } /****************************************************************************** * DCOP call to set autostart at login on or off. */ void ADConfigData::enableAutoStart(bool on) { kdDebug(5900) << "ADConfigData::enableAutoStart(" << on << ")\n"; KConfig* config = KGlobal::config(); config->reparseConfiguration(); config->setGroup(QLatin1String(DAEMON_AUTOSTART_SECTION)); config->writeEntry(QLatin1String(DAEMON_AUTOSTART_KEY), on); config->sync(); } <commit_msg>Fix compilation errors<commit_after>/* * adcalendar.cpp - configuration file access * Program: KAlarm's alarm daemon (kalarmd) * Copyright (c) 2001, 2004, 2005 by David Jarvie <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kalarmd.h" #include <qregexp.h> #include <qstringlist.h> #include <kconfig.h> #include <kstandarddirs.h> #include <kdebug.h> #include "adcalendar.h" #include "adconfigdata.h" // Config file key strings const QString CLIENT_GROUP(QLatin1String("Client ")); const QRegExp CLIENT_GROUP_SEARCH("^Client "); // Client data file key strings const char* CALENDAR_KEY = "Calendar"; const char* TITLE_KEY = "Title"; const char* DCOP_OBJECT_KEY = "DCOP object"; const char* START_CLIENT_KEY = "Start"; /****************************************************************************** * Read the configuration file. * Create the client list and open all calendar files. */ void ADConfigData::readConfig() { kdDebug(5900) << "ADConfigData::readConfig()" << endl; ClientInfo::clear(); KConfig* config = KGlobal::config(); QStringList clients = config->groupList().filter(CLIENT_GROUP_SEARCH); for (QStringList::Iterator cl = clients.begin(); cl != clients.end(); ++cl) { // Read this client's configuration config->setGroup(*cl); QString client = *cl; client.remove(CLIENT_GROUP_SEARCH); QString title = config->readEntry(TITLE_KEY, client); // read app title (default = app name) QByteArray dcopObject = config->readEntry(DCOP_OBJECT_KEY, QString()).toLocal8Bit(); bool startClient = config->readEntry(START_CLIENT_KEY, QVariant(false)).toBool(); QString calendar = config->readPathEntry(CALENDAR_KEY); // Verify the configuration bool ok = false; if (client.isEmpty() || KStandardDirs::findExe(client).isNull()) kdError(5900) << "ADConfigData::readConfig(): group '" << *cl << "' deleted (client app not found)\n"; else if (calendar.isEmpty()) kdError(5900) << "ADConfigData::readConfig(): no calendar specified for '" << client << "'\n"; else if (dcopObject.isEmpty()) kdError(5900) << "ADConfigData::readConfig(): no DCOP object specified for '" << client << "'\n"; else { ADCalendar* cal = ADCalendar::calendar(calendar); if (cal) kdError(5900) << "ADConfigData::readConfig(): calendar registered by multiple clients: " << calendar << endl; else ok = true; } if (!ok) { config->deleteGroup(*cl, KConfig::NLS); continue; } // Create the client and calendar objects new ClientInfo(client.toLocal8Bit(), title, dcopObject, calendar, startClient); kdDebug(5900) << "ADConfigData::readConfig(): client " << client << " : calendar " << calendar << endl; } // Remove obsolete CheckInterval entry (if it exists) config->setGroup("General"); config->deleteEntry("CheckInterval"); // Save any updates config->sync(); } /****************************************************************************** * Write a client application's details to the config file. */ void ADConfigData::writeClient(const QByteArray& appName, const ClientInfo* cinfo) { KConfig* config = KGlobal::config(); config->setGroup(CLIENT_GROUP + QString::fromLocal8Bit(appName)); config->writeEntry(TITLE_KEY, cinfo->title()); config->writeEntry(DCOP_OBJECT_KEY, QString::fromLocal8Bit(cinfo->dcopObject())); config->writeEntry(START_CLIENT_KEY, cinfo->startClient()); config->writePathEntry(CALENDAR_KEY, cinfo->calendar()->urlString()); config->sync(); } /****************************************************************************** * Remove a client application's details from the config file. */ void ADConfigData::removeClient(const QByteArray& appName) { KConfig* config = KGlobal::config(); config->deleteGroup(CLIENT_GROUP + QString::fromLocal8Bit(appName)); config->sync(); } /****************************************************************************** * Set the calendar file URL for a specified application. */ void ADConfigData::setCalendar(const QByteArray& appName, ADCalendar* cal) { KConfig* config = KGlobal::config(); config->setGroup(CLIENT_GROUP + QString::fromLocal8Bit(appName)); config->writePathEntry(CALENDAR_KEY, cal->urlString()); config->sync(); } /****************************************************************************** * DCOP call to set autostart at login on or off. */ void ADConfigData::enableAutoStart(bool on) { kdDebug(5900) << "ADConfigData::enableAutoStart(" << on << ")\n"; KConfig* config = KGlobal::config(); config->reparseConfiguration(); config->setGroup(QLatin1String(DAEMON_AUTOSTART_SECTION)); config->writeEntry(QLatin1String(DAEMON_AUTOSTART_KEY), on); config->sync(); } <|endoftext|>
<commit_before><commit_msg>Correction in Prefix Function<commit_after><|endoftext|>
<commit_before>/*************************************************************************** filter_thunderbird.cxx - Thunderbird mail import ------------------- begin : Januar 26 2005 copyright : (C) 2005 by Danny Kukawka email : [email protected] ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "filter_thunderbird.hxx" #include <config.h> #include <klocale.h> #include <kfiledialog.h> #include <ktempfile.h> /** Default constructor. */ FilterThunderbird::FilterThunderbird(void) : Filter(i18n("Import Thunderbird Local Mails and Folder Structure"), "Danny Kukawka", i18n("<p><b>Thunderbird import filter</b></p>" "<p>Select your base Thunderbird mailfolder" " (usually ~/.thunderbird/*.default/Mail/Local Folders/).</p>" "<p><b>Note:</b> Never choose a Folder, which <u>does not</u> contain mbox-files (for example" " a maildir). If you do it anyway, you will get many new folders.</p>" "<p>As it is currently impossible to recreate the folder structure, it will be " "\"contained\" in the generated folder's names.</p>")) {} /** Destructor. */ FilterThunderbird::~FilterThunderbird(void) { endImport(); } /** Recursive import of Evolution's mboxes. */ void FilterThunderbird::import(FilterInfo *info) { /** * We ask the user to choose Evolution's root directory. * This should be usually ~/.thunderbird/xxxx.default/Mail/Local Folders/ */ QString mailDir = KFileDialog::getExistingDirectory(QDir::homeDirPath(), info->parent()); info->setOverall(0); /** Recursive import of the MailArchives */ QDir dir(mailDir); QStringList rootSubDirs = dir.entryList("[^\\.]*", QDir::Dirs, QDir::Name); // Removal of . and .. int currentDir = 1, numSubDirs = rootSubDirs.size(); for(QStringList::Iterator filename = rootSubDirs.begin() ; filename != rootSubDirs.end() ; ++filename, ++currentDir) { importDirContents(info, dir.filePath(*filename), *filename, QString::null); info->setOverall((int) ((float) currentDir / numSubDirs * 100)); } /** import last but not least all archives from the root-dir */ QDir importDir (mailDir); QStringList files = importDir.entryList("[^\\.]*", QDir::Files, QDir::Name); for ( QStringList::Iterator mailFile = files.begin(); mailFile != files.end(); ++mailFile) { QString temp_mailfile = *mailFile; if (temp_mailfile.endsWith(".msf")) {} else { info->addLog( i18n("Start import file %1...").arg( temp_mailfile ) ); importMBox(info, mailDir + "/" + temp_mailfile , temp_mailfile, QString::null); } } info->addLog( i18n("Finished importing emails from %1").arg( mailDir )); info->setCurrent(100); if(count_duplicates > 0) { info->addLog( i18n("1 duplicate message not imported", "%n duplicate messages not imported", count_duplicates)); } } /** * Import of a directory contents. * @param info Information storage for the operation. * @param dirName The name of the directory to import. * @param KMailRootDir The directory's root directory in KMail's folder structure. * @param KMailSubDir The directory's direct ancestor in KMail's folder structure. */ void FilterThunderbird::importDirContents(FilterInfo *info, const QString& dirName, const QString& KMailRootDir, const QString& KMailSubDir) { /** Here Import all archives in the current dir */ QDir dir(dirName); QDir importDir (dirName); QStringList files = importDir.entryList("[^\\.]*", QDir::Files, QDir::Name); for ( QStringList::Iterator mailFile = files.begin(); mailFile != files.end(); ++mailFile) { QString temp_mailfile = *mailFile; if (temp_mailfile.endsWith(".msf")) {} else { info->addLog( i18n("Start import file %1...").arg( temp_mailfile ) ); importMBox(info, (dirName + "/" + temp_mailfile) , KMailRootDir, KMailSubDir); } } /** If there are subfolders, we import them one by one */ QDir subfolders(dirName); QStringList subDirs = subfolders.entryList("[^\\.]*", QDir::Dirs, QDir::Name); for(QStringList::Iterator filename = subDirs.begin() ; filename != subDirs.end() ; ++filename) { QString kSubDir; if(!KMailSubDir.isNull()) { kSubDir = KMailSubDir + "-" + *filename; } else { kSubDir = *filename; } importDirContents(info, subfolders.filePath(*filename), KMailRootDir, kSubDir); } } /** * Import of a MBox file. * @param info Information storage for the operation. * @param dirName The MBox's name. * @param KMailRootDir The directory's root directory in KMail's folder structure. * @param KMailSubDir The directory's equivalent in KMail's folder structure. * */ void FilterThunderbird::importMBox(FilterInfo *info, const QString& mboxName, const QString& rootDir, const QString& targetDir) { QFile mbox(mboxName); if (!mbox.open(IO_ReadOnly)) { info->alert(i18n("Unable to open %1, skipping").arg(mboxName)); } else { QFileInfo filenameInfo(mboxName); info->setCurrent(0); info->setFrom(mboxName); info->setTo(targetDir); while (!mbox.atEnd()) { KTempFile tmp; /** @todo check if the file is really a mbox, maybe search for 'from' string at start */ /* comment by Danny: * Don't use QTextStream to read from mbox, etter use QDataStream. QTextStream only * support Unicode/Latin1/Locale. So you lost information from emails with * charset!=Unicode/Latin1/Locale (e.g. KOI8-R) and Content-Transfer-Encoding != base64 * (e.g. 8Bit). It also not help to convert the QTextStream to Unicode. By this you * get Unicode/UTF-email but KMail can't detect the correct charset. */ QByteArray input(MAX_LINE); QCString seperate; mbox.readLine(input.data(),MAX_LINE); long l = mbox.readLine( input.data(),MAX_LINE); // read the first line, prevent "From " tmp.file()->writeBlock( input, l ); while ( ! mbox.atEnd() && (l = mbox.readLine(input.data(),MAX_LINE)) && ((seperate = input.data()).left(5) != "From ")) { tmp.file()->writeBlock( input, l ); } tmp.close(); QString destFolder = rootDir; QString _targetDir = targetDir; if(destFolder.contains(".sbd")) destFolder.remove(".sbd"); if(!targetDir.isNull()){ if(_targetDir.contains(".sbd")) _targetDir.remove(".sbd"); destFolder += ("-" + _targetDir); destFolder += "-" + filenameInfo.baseName(TRUE);// mboxName; } if(info->removeDupMsg) addMessage( info, destFolder, tmp.name() ); else addMessage_fastImport( info, destFolder, tmp.name() ); tmp.unlink(); int currentPercentage = (int) (((float) mbox.at() / filenameInfo.size()) * 100); info->setCurrent(currentPercentage); if (info->shouldTerminate()) return; } mbox.close(); } } <commit_msg>- workaround for bug in kdelibs. Now a own filedialog is used to ask the user for the loaction of the mail archive. [see Bug: #101034] - added check for wrong dirs e.g. homedir (no import need, prevent to import wrong files) - set the overall processbars to 100% at end of import<commit_after>/*************************************************************************** filter_thunderbird.cxx - Thunderbird mail import ------------------- begin : Januar 26 2005 copyright : (C) 2005 by Danny Kukawka email : [email protected] ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "filter_thunderbird.hxx" #include <config.h> #include <klocale.h> #include <kfiledialog.h> #include <ktempfile.h> /** Default constructor. */ FilterThunderbird::FilterThunderbird(void) : Filter(i18n("Import Thunderbird Local Mails and Folder Structure"), "Danny Kukawka", i18n("<p><b>Thunderbird import filter</b></p>" "<p>Select your base Thunderbird mailfolder" " (usually ~/.thunderbird/*.default/Mail/Local Folders/).</p>" "<p><b>Note:</b> Never choose a Folder, which <u>does not</u> contain mbox-files (for example" " a maildir). If you do it anyway, you will get many new folders.</p>" "<p>As it is currently impossible to recreate the folder structure, it will be " "\"contained\" in the generated folder's names.</p>")) {} /** Destructor. */ FilterThunderbird::~FilterThunderbird(void) { endImport(); } /** Recursive import of Evolution's mboxes. */ void FilterThunderbird::import(FilterInfo *info) { /** * We ask the user to choose Evolution's root directory. * This should be usually ~/.thunderbird/xxxx.default/Mail/Local Folders/ */ QString thunderDir = QDir::homeDirPath() + "/.thunderbird/"; QDir d( thunderDir ); if ( !d.exists() ) { thunderDir = QDir::homeDirPath(); } KFileDialog *kfd; kfd = new KFileDialog( thunderDir, "", 0, "kfiledialog", true ); kfd->setMode(KFile::Directory | KFile::LocalOnly); kfd->exec(); QString mailDir = kfd->selectedFile(); if (mailDir.isEmpty()) { info->alert(i18n("No directory selected.")); } /** * If the user only select homedir no import needed because * there should be no files and we shurely import wrong files. */ else if ( mailDir == QDir::homeDirPath() || mailDir == (QDir::homeDirPath() + "/")) { info->addLog(i18n("No files found for import.")); } else { info->setOverall(0); /** Recursive import of the MailArchives */ QDir dir(mailDir); QStringList rootSubDirs = dir.entryList("[^\\.]*", QDir::Dirs, QDir::Name); // Removal of . and .. int currentDir = 1, numSubDirs = rootSubDirs.size(); for(QStringList::Iterator filename = rootSubDirs.begin() ; filename != rootSubDirs.end() ; ++filename, ++currentDir) { importDirContents(info, dir.filePath(*filename), *filename, QString::null); info->setOverall((int) ((float) currentDir / numSubDirs * 100)); } /** import last but not least all archives from the root-dir */ QDir importDir (mailDir); QStringList files = importDir.entryList("[^\\.]*", QDir::Files, QDir::Name); for ( QStringList::Iterator mailFile = files.begin(); mailFile != files.end(); ++mailFile) { QString temp_mailfile = *mailFile; if (temp_mailfile.endsWith(".msf")) {} else { info->addLog( i18n("Start import file %1...").arg( temp_mailfile ) ); importMBox(info, mailDir + "/" + temp_mailfile , temp_mailfile, QString::null); } } info->addLog( i18n("Finished importing emails from %1").arg( mailDir )); if(count_duplicates > 0) { info->addLog( i18n("1 duplicate message not imported", "%n duplicate messages not imported", count_duplicates)); } } info->setCurrent(100); info->setOverall(100); } /** * Import of a directory contents. * @param info Information storage for the operation. * @param dirName The name of the directory to import. * @param KMailRootDir The directory's root directory in KMail's folder structure. * @param KMailSubDir The directory's direct ancestor in KMail's folder structure. */ void FilterThunderbird::importDirContents(FilterInfo *info, const QString& dirName, const QString& KMailRootDir, const QString& KMailSubDir) { /** Here Import all archives in the current dir */ QDir dir(dirName); QDir importDir (dirName); QStringList files = importDir.entryList("[^\\.]*", QDir::Files, QDir::Name); for ( QStringList::Iterator mailFile = files.begin(); mailFile != files.end(); ++mailFile) { QString temp_mailfile = *mailFile; if (temp_mailfile.endsWith(".msf")) {} else { info->addLog( i18n("Start import file %1...").arg( temp_mailfile ) ); importMBox(info, (dirName + "/" + temp_mailfile) , KMailRootDir, KMailSubDir); } } /** If there are subfolders, we import them one by one */ QDir subfolders(dirName); QStringList subDirs = subfolders.entryList("[^\\.]*", QDir::Dirs, QDir::Name); for(QStringList::Iterator filename = subDirs.begin() ; filename != subDirs.end() ; ++filename) { QString kSubDir; if(!KMailSubDir.isNull()) { kSubDir = KMailSubDir + "-" + *filename; } else { kSubDir = *filename; } importDirContents(info, subfolders.filePath(*filename), KMailRootDir, kSubDir); } } /** * Import of a MBox file. * @param info Information storage for the operation. * @param dirName The MBox's name. * @param KMailRootDir The directory's root directory in KMail's folder structure. * @param KMailSubDir The directory's equivalent in KMail's folder structure. * */ void FilterThunderbird::importMBox(FilterInfo *info, const QString& mboxName, const QString& rootDir, const QString& targetDir) { QFile mbox(mboxName); if (!mbox.open(IO_ReadOnly)) { info->alert(i18n("Unable to open %1, skipping").arg(mboxName)); } else { QFileInfo filenameInfo(mboxName); info->setCurrent(0); info->setFrom(mboxName); info->setTo(targetDir); while (!mbox.atEnd()) { KTempFile tmp; /** @todo check if the file is really a mbox, maybe search for 'from' string at start */ /* comment by Danny: * Don't use QTextStream to read from mbox, etter use QDataStream. QTextStream only * support Unicode/Latin1/Locale. So you lost information from emails with * charset!=Unicode/Latin1/Locale (e.g. KOI8-R) and Content-Transfer-Encoding != base64 * (e.g. 8Bit). It also not help to convert the QTextStream to Unicode. By this you * get Unicode/UTF-email but KMail can't detect the correct charset. */ QByteArray input(MAX_LINE); QCString seperate; mbox.readLine(input.data(),MAX_LINE); long l = mbox.readLine( input.data(),MAX_LINE); // read the first line, prevent "From " tmp.file()->writeBlock( input, l ); while ( ! mbox.atEnd() && (l = mbox.readLine(input.data(),MAX_LINE)) && ((seperate = input.data()).left(5) != "From ")) { tmp.file()->writeBlock( input, l ); } tmp.close(); QString destFolder = rootDir; QString _targetDir = targetDir; if(destFolder.contains(".sbd")) destFolder.remove(".sbd"); if(!targetDir.isNull()){ if(_targetDir.contains(".sbd")) _targetDir.remove(".sbd"); destFolder += ("-" + _targetDir); destFolder += "-" + filenameInfo.baseName(TRUE);// mboxName; } if(info->removeDupMsg) addMessage( info, destFolder, tmp.name() ); else addMessage_fastImport( info, destFolder, tmp.name() ); tmp.unlink(); int currentPercentage = (int) (((float) mbox.at() / filenameInfo.size()) * 100); info->setCurrent(currentPercentage); if (info->shouldTerminate()) return; } mbox.close(); } } <|endoftext|>
<commit_before>/* This file is part of KOrganizer. Copyright (c) 2001 Cornelius Schumacher <[email protected]> Copyright (C) 2004 Reinhold Kainhofer <[email protected]> Copyright (C) 2005 Thomas Zander <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qpushbutton.h> #include <qcheckbox.h> #include <qbuttongroup.h> #include <qlineedit.h> #include <qradiobutton.h> #include <qlistbox.h> #include <qwhatsthis.h> #include <kdebug.h> #include <klocale.h> #include <kmessagebox.h> #include <knuminput.h> #include <libkcal/calfilter.h> #include <libkdepim/categoryselectdialog.h> #include "koprefs.h" #include "filteredit_base.h" #include "filtereditdialog.h" #include "filtereditdialog.moc" FilterEditDialog::FilterEditDialog( QPtrList<CalFilter> *filters, QWidget *parent, const char *name) : KDialogBase( parent, name, false, i18n("Edit Calendar Filters"), Ok | Apply | Cancel ) { setMainWidget( mFilterEdit = new FilterEdit(filters, this)); connect(mFilterEdit, SIGNAL(dataConsistent(bool)), SLOT(setDialogConsistent(bool))); updateFilterList(); connect( mFilterEdit, SIGNAL( editCategories() ), SIGNAL( editCategories() ) ); connect( mFilterEdit, SIGNAL( filterChanged() ), SIGNAL( filterChanged() ) ); } FilterEditDialog::~FilterEditDialog() { delete mFilterEdit; mFilterEdit = 0L; } void FilterEditDialog::updateFilterList() { mFilterEdit->updateFilterList(); } void FilterEditDialog::updateCategoryConfig() { mFilterEdit->updateCategoryConfig(); } void FilterEditDialog::slotApply() { mFilterEdit->saveChanges(); } void FilterEditDialog::slotOk() { slotApply(); accept(); } void FilterEditDialog::setDialogConsistent(bool consistent) { enableButtonOK( consistent ); enableButtonApply( consistent ); } FilterEdit::FilterEdit(QPtrList<CalFilter> *filters, QWidget *parent) : FilterEdit_base( parent), current(0), mCategorySelectDialog( 0 ) { mFilters = filters; QWhatsThis::add( mNewButton, i18n( "Press this button to define a new filter." ) ); QWhatsThis::add( mDeleteButton, i18n( "Press this button to remove the currently active filter." ) ); connect(mRulesList, SIGNAL(selectionChanged()), this, SLOT(filterSelected())); connect( mNewButton, SIGNAL( clicked() ), SLOT( bNewPressed() ) ); connect( mDeleteButton, SIGNAL( clicked() ), SLOT( bDeletePressed() ) ); connect( mNameLineEdit, SIGNAL( textChanged(const QString &) ), SLOT( updateSelectedName(const QString &) ) ); connect( mCatEditButton, SIGNAL( clicked() ), SLOT( editCategorySelection() ) ); } FilterEdit::~FilterEdit() { } void FilterEdit::updateFilterList() { mRulesList->clear(); CalFilter *filter = mFilters->first(); if ( !filter ) emit(dataConsistent(false)); else { while( filter ) { mRulesList->insertItem( filter->name() ); filter = mFilters->next(); } CalFilter *f = mFilters->at( mRulesList->currentItem() ); if ( f ) filterSelected( f ); emit(dataConsistent(true)); } if(current == 0L && mFilters->count() > 0) filterSelected(mFilters->at(0)); mDeleteButton->setEnabled( mFilters->count() > 1 ); } void FilterEdit::saveChanges() { if(current != 0L) filterSelected(current); } void FilterEdit::filterSelected() { filterSelected(mFilters->at(mRulesList->currentItem())); } void FilterEdit::filterSelected(CalFilter *filter) { if(filter == current) return; kdDebug(5850) << "Selected filter " << (filter!=0?filter->name():"") << endl; if(current != 0L) { // save the old values first. current->setName(mNameLineEdit->text()); int criteria = 0; if ( mCompletedCheck->isChecked() ) criteria |= CalFilter::HideCompleted; if ( mRecurringCheck->isChecked() ) criteria |= CalFilter::HideRecurring; if ( mCatShowCheck->isChecked() ) criteria |= CalFilter::ShowCategories; if ( mHideInactiveTodosCheck->isChecked() ) criteria |= CalFilter::HideInactiveTodos; current->setCriteria( criteria ); current->setCompletedTimeSpan( mCompletedTimeSpan->value() ); QStringList categoryList; for( uint i = 0; i < mCatList->count(); ++i ) categoryList.append( mCatList->text( i ) ); current->setCategoryList( categoryList ); emit filterChanged(); } current = filter; mNameLineEdit->blockSignals(true); mNameLineEdit->setText(current->name()); mNameLineEdit->blockSignals(false); mDetailsFrame->setEnabled(current != 0L); mCompletedCheck->setChecked( current->criteria() & CalFilter::HideCompleted ); mCompletedTimeSpan->setValue( current->completedTimeSpan() ); mRecurringCheck->setChecked( current->criteria() & CalFilter::HideRecurring ); mHideInactiveTodosCheck->setChecked( current->criteria() & CalFilter::HideInactiveTodos ); mCategoriesButtonGroup->setButton( (current->criteria() & CalFilter::ShowCategories)?0:1 ); mCatList->clear(); mCatList->insertStringList( current->categoryList() ); } void FilterEdit::bNewPressed() { CalFilter *newFilter = new CalFilter( i18n("New Filter %1").arg(mFilters->count()) ); mFilters->append( newFilter ); updateFilterList(); mRulesList->setSelected(mRulesList->count()-1, true); emit filterChanged(); } void FilterEdit::bDeletePressed() { if ( mRulesList->currentItem() < 0 ) return; // nothing selected if ( mFilters->count() <= 1 ) return; // We need at least a default filter object. int result = KMessageBox::warningContinueCancel( this, i18n("This item will be permanently deleted."), i18n("Delete Confirmation"), KGuiItem(i18n("Delete"),"editdelete") ); if ( result != KMessageBox::Continue ) return; unsigned int selected = mRulesList->currentItem(); mFilters->remove( selected ); current = 0L; updateFilterList(); mRulesList->setSelected(QMIN(mRulesList->count()-1, selected), true); emit filterChanged(); } void FilterEdit::updateSelectedName(const QString &newText) { mRulesList->changeItem(newText, mRulesList->currentItem()); bool allOk = true; CalFilter *filter = mFilters->first(); while( allOk && filter ) { if(filter->name().isEmpty()) allOk = false; filter = mFilters->next(); } emit dataConsistent(allOk); } void FilterEdit::editCategorySelection() { if( !current ) return; if ( !mCategorySelectDialog ) { mCategorySelectDialog = new KPIM::CategorySelectDialog( KOPrefs::instance(), this, "filterCatSelect" ); connect( mCategorySelectDialog, SIGNAL( categoriesSelected( const QStringList & ) ), SLOT( updateCategorySelection( const QStringList & ) ) ); connect( mCategorySelectDialog, SIGNAL( editCategories() ), SIGNAL( editCategories() ) ); } mCategorySelectDialog->setSelected( current->categoryList() ); mCategorySelectDialog->show(); } void FilterEdit::updateCategorySelection( const QStringList &categories ) { mCatList->clear(); mCatList->insertStringList(categories); current->setCategoryList(categories); } void FilterEdit::updateCategoryConfig() { if ( mCategorySelectDialog ) mCategorySelectDialog->updateCategoryConfig(); } <commit_msg>Make 'ok' also save the changes in the dialog<commit_after>/* This file is part of KOrganizer. Copyright (c) 2001 Cornelius Schumacher <[email protected]> Copyright (C) 2004 Reinhold Kainhofer <[email protected]> Copyright (C) 2005 Thomas Zander <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qpushbutton.h> #include <qcheckbox.h> #include <qbuttongroup.h> #include <qlineedit.h> #include <qradiobutton.h> #include <qlistbox.h> #include <qwhatsthis.h> #include <kdebug.h> #include <klocale.h> #include <kmessagebox.h> #include <knuminput.h> #include <libkcal/calfilter.h> #include <libkdepim/categoryselectdialog.h> #include "koprefs.h" #include "filteredit_base.h" #include "filtereditdialog.h" #include "filtereditdialog.moc" FilterEditDialog::FilterEditDialog( QPtrList<CalFilter> *filters, QWidget *parent, const char *name) : KDialogBase( parent, name, false, i18n("Edit Calendar Filters"), Ok | Apply | Cancel ) { setMainWidget( mFilterEdit = new FilterEdit(filters, this)); connect(mFilterEdit, SIGNAL(dataConsistent(bool)), SLOT(setDialogConsistent(bool))); updateFilterList(); connect( mFilterEdit, SIGNAL( editCategories() ), SIGNAL( editCategories() ) ); connect( mFilterEdit, SIGNAL( filterChanged() ), SIGNAL( filterChanged() ) ); } FilterEditDialog::~FilterEditDialog() { delete mFilterEdit; mFilterEdit = 0L; } void FilterEditDialog::updateFilterList() { mFilterEdit->updateFilterList(); } void FilterEditDialog::updateCategoryConfig() { mFilterEdit->updateCategoryConfig(); } void FilterEditDialog::slotApply() { mFilterEdit->saveChanges(); } void FilterEditDialog::slotOk() { slotApply(); accept(); } void FilterEditDialog::setDialogConsistent(bool consistent) { enableButtonOK( consistent ); enableButtonApply( consistent ); } FilterEdit::FilterEdit(QPtrList<CalFilter> *filters, QWidget *parent) : FilterEdit_base( parent), current(0), mCategorySelectDialog( 0 ) { mFilters = filters; QWhatsThis::add( mNewButton, i18n( "Press this button to define a new filter." ) ); QWhatsThis::add( mDeleteButton, i18n( "Press this button to remove the currently active filter." ) ); connect( mRulesList, SIGNAL(selectionChanged()), this, SLOT(filterSelected()) ); connect( mNewButton, SIGNAL( clicked() ), SLOT( bNewPressed() ) ); connect( mDeleteButton, SIGNAL( clicked() ), SLOT( bDeletePressed() ) ); connect( mNameLineEdit, SIGNAL( textChanged(const QString &) ), SLOT( updateSelectedName(const QString &) ) ); connect( mCatEditButton, SIGNAL( clicked() ), SLOT( editCategorySelection() ) ); } FilterEdit::~FilterEdit() { } void FilterEdit::updateFilterList() { mRulesList->clear(); CalFilter *filter = mFilters->first(); if ( !filter ) emit(dataConsistent(false)); else { while( filter ) { mRulesList->insertItem( filter->name() ); filter = mFilters->next(); } CalFilter *f = mFilters->at( mRulesList->currentItem() ); if ( f ) filterSelected( f ); emit(dataConsistent(true)); } if(current == 0L && mFilters->count() > 0) filterSelected(mFilters->at(0)); mDeleteButton->setEnabled( mFilters->count() > 1 ); } void FilterEdit::saveChanges() { if(current == 0L) return; current->setName(mNameLineEdit->text()); int criteria = 0; if ( mCompletedCheck->isChecked() ) criteria |= CalFilter::HideCompleted; if ( mRecurringCheck->isChecked() ) criteria |= CalFilter::HideRecurring; if ( mCatShowCheck->isChecked() ) criteria |= CalFilter::ShowCategories; if ( mHideInactiveTodosCheck->isChecked() ) criteria |= CalFilter::HideInactiveTodos; current->setCriteria( criteria ); current->setCompletedTimeSpan( mCompletedTimeSpan->value() ); QStringList categoryList; for( uint i = 0; i < mCatList->count(); ++i ) categoryList.append( mCatList->text( i ) ); current->setCategoryList( categoryList ); emit filterChanged(); } void FilterEdit::filterSelected() { filterSelected(mFilters->at(mRulesList->currentItem())); } void FilterEdit::filterSelected(CalFilter *filter) { if(filter == current) return; kdDebug(5850) << "Selected filter " << (filter!=0?filter->name():"") << endl; saveChanges(); current = filter; mNameLineEdit->blockSignals(true); mNameLineEdit->setText(current->name()); mNameLineEdit->blockSignals(false); mDetailsFrame->setEnabled(current != 0L); mCompletedCheck->setChecked( current->criteria() & CalFilter::HideCompleted ); mCompletedTimeSpan->setValue( current->completedTimeSpan() ); mRecurringCheck->setChecked( current->criteria() & CalFilter::HideRecurring ); mHideInactiveTodosCheck->setChecked( current->criteria() & CalFilter::HideInactiveTodos ); mCategoriesButtonGroup->setButton( (current->criteria() & CalFilter::ShowCategories)?0:1 ); mCatList->clear(); mCatList->insertStringList( current->categoryList() ); } void FilterEdit::bNewPressed() { CalFilter *newFilter = new CalFilter( i18n("New Filter %1").arg(mFilters->count()) ); mFilters->append( newFilter ); updateFilterList(); mRulesList->setSelected(mRulesList->count()-1, true); emit filterChanged(); } void FilterEdit::bDeletePressed() { if ( mRulesList->currentItem() < 0 ) return; // nothing selected if ( mFilters->count() <= 1 ) return; // We need at least a default filter object. int result = KMessageBox::warningContinueCancel( this, i18n("This item will be permanently deleted."), i18n("Delete Confirmation"), KGuiItem(i18n("Delete"),"editdelete") ); if ( result != KMessageBox::Continue ) return; unsigned int selected = mRulesList->currentItem(); mFilters->remove( selected ); current = 0L; updateFilterList(); mRulesList->setSelected(QMIN(mRulesList->count()-1, selected), true); emit filterChanged(); } void FilterEdit::updateSelectedName(const QString &newText) { mRulesList->blockSignals( true ); mRulesList->changeItem(newText, mRulesList->currentItem()); mRulesList->blockSignals( false ); bool allOk = true; CalFilter *filter = mFilters->first(); while( allOk && filter ) { if(filter->name().isEmpty()) allOk = false; filter = mFilters->next(); } emit dataConsistent(allOk); } void FilterEdit::editCategorySelection() { if( !current ) return; if ( !mCategorySelectDialog ) { mCategorySelectDialog = new KPIM::CategorySelectDialog( KOPrefs::instance(), this, "filterCatSelect" ); connect( mCategorySelectDialog, SIGNAL( categoriesSelected( const QStringList & ) ), SLOT( updateCategorySelection( const QStringList & ) ) ); connect( mCategorySelectDialog, SIGNAL( editCategories() ), SIGNAL( editCategories() ) ); } mCategorySelectDialog->setSelected( current->categoryList() ); mCategorySelectDialog->show(); } void FilterEdit::updateCategorySelection( const QStringList &categories ) { mCatList->clear(); mCatList->insertStringList(categories); current->setCategoryList(categories); } void FilterEdit::updateCategoryConfig() { if ( mCategorySelectDialog ) mCategorySelectDialog->updateCategoryConfig(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2001 Peter Kelly ([email protected]) * Copyright (C) 2001 Tobias Anton ([email protected]) * Copyright (C) 2006 Samuel Weinig ([email protected]) * Copyright (C) 2003, 2005, 2006, 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "core/events/Event.h" #include "core/dom/StaticNodeList.h" #include "core/events/EventTarget.h" #include "core/frame/UseCounter.h" #include "core/svg/SVGElement.h" #include "wtf/CurrentTime.h" namespace blink { EventInit::EventInit() : bubbles(false) , cancelable(false) { } Event::Event() : m_canBubble(false) , m_cancelable(false) , m_propagationStopped(false) , m_immediatePropagationStopped(false) , m_defaultPrevented(false) , m_defaultHandled(false) , m_cancelBubble(false) , m_eventPhase(0) , m_currentTarget(nullptr) , m_createTime(convertSecondsToDOMTimeStamp(currentTime())) { ScriptWrappable::init(this); } Event::Event(const AtomicString& eventType, bool canBubbleArg, bool cancelableArg) : m_type(eventType) , m_canBubble(canBubbleArg) , m_cancelable(cancelableArg) , m_propagationStopped(false) , m_immediatePropagationStopped(false) , m_defaultPrevented(false) , m_defaultHandled(false) , m_cancelBubble(false) , m_eventPhase(0) , m_currentTarget(nullptr) , m_createTime(convertSecondsToDOMTimeStamp(currentTime())) { ScriptWrappable::init(this); } Event::Event(const AtomicString& eventType, const EventInit& initializer) : m_type(eventType) , m_canBubble(initializer.bubbles) , m_cancelable(initializer.cancelable) , m_propagationStopped(false) , m_immediatePropagationStopped(false) , m_defaultPrevented(false) , m_defaultHandled(false) , m_cancelBubble(false) , m_eventPhase(0) , m_currentTarget(nullptr) , m_createTime(convertSecondsToDOMTimeStamp(currentTime())) { ScriptWrappable::init(this); } Event::~Event() { } void Event::initEvent(const AtomicString& eventTypeArg, bool canBubbleArg, bool cancelableArg) { if (dispatched()) return; m_propagationStopped = false; m_immediatePropagationStopped = false; m_defaultPrevented = false; m_type = eventTypeArg; m_canBubble = canBubbleArg; m_cancelable = cancelableArg; } bool Event::legacyReturnValue(ExecutionContext* executionContext) const { bool returnValue = !defaultPrevented(); if (returnValue) UseCounter::count(executionContext, UseCounter::EventGetReturnValueTrue); else UseCounter::count(executionContext, UseCounter::EventGetReturnValueFalse); return returnValue; } void Event::setLegacyReturnValue(ExecutionContext* executionContext, bool returnValue) { if (returnValue) UseCounter::count(executionContext, UseCounter::EventSetReturnValueTrue); else UseCounter::count(executionContext, UseCounter::EventSetReturnValueFalse); setDefaultPrevented(!returnValue); } const AtomicString& Event::interfaceName() const { return EventNames::Event; } bool Event::hasInterface(const AtomicString& name) const { return interfaceName() == name; } bool Event::isUIEvent() const { return false; } bool Event::isMouseEvent() const { return false; } bool Event::isFocusEvent() const { return false; } bool Event::isKeyboardEvent() const { return false; } bool Event::isTouchEvent() const { return false; } bool Event::isGestureEvent() const { return false; } bool Event::isWheelEvent() const { return false; } bool Event::isRelatedEvent() const { return false; } bool Event::isDragEvent() const { return false; } bool Event::isClipboardEvent() const { return false; } bool Event::isBeforeTextInsertedEvent() const { return false; } bool Event::isBeforeUnloadEvent() const { return false; } void Event::setTarget(PassRefPtrWillBeRawPtr<EventTarget> target) { if (m_target == target) return; m_target = target; if (m_target) receivedTarget(); } void Event::receivedTarget() { } void Event::setUnderlyingEvent(PassRefPtrWillBeRawPtr<Event> ue) { // Prohibit creation of a cycle -- just do nothing in that case. for (Event* e = ue.get(); e; e = e->underlyingEvent()) if (e == this) return; m_underlyingEvent = ue; } EventPath& Event::ensureEventPath() { if (!m_eventPath) m_eventPath = adoptPtrWillBeNoop(new EventPath(this)); return *m_eventPath; } PassRefPtrWillBeRawPtr<StaticNodeList> Event::path() const { if (!m_currentTarget) { ASSERT(m_eventPhase == PhaseType::NONE); if (!m_eventPath) { // Before dispatching the event return StaticNodeList::createEmpty(); } ASSERT(!m_eventPath->isEmpty()); // After dispatching the event return m_eventPath->last().treeScopeEventContext().ensureEventPath(*m_eventPath); } if (!m_currentTarget->toNode()) return StaticNodeList::createEmpty(); Node* node = m_currentTarget->toNode(); size_t eventPathSize = m_eventPath->size(); for (size_t i = 0; i < eventPathSize; ++i) { if (node == (*m_eventPath)[i].node()) { return (*m_eventPath)[i].treeScopeEventContext().ensureEventPath(*m_eventPath); } } return StaticNodeList::createEmpty(); } EventTarget* Event::currentTarget() const { if (!m_currentTarget) return 0; Node* node = m_currentTarget->toNode(); if (node && node->isSVGElement()) { if (SVGElement* svgElement = toSVGElement(node)->correspondingElement()) return svgElement; } return m_currentTarget.get(); } void Event::trace(Visitor* visitor) { visitor->trace(m_currentTarget); visitor->trace(m_target); visitor->trace(m_underlyingEvent); visitor->trace(m_eventPath); } } // namespace blink <commit_msg>use c++03 style enum scope<commit_after>/* * Copyright (C) 2001 Peter Kelly ([email protected]) * Copyright (C) 2001 Tobias Anton ([email protected]) * Copyright (C) 2006 Samuel Weinig ([email protected]) * Copyright (C) 2003, 2005, 2006, 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "core/events/Event.h" #include "core/dom/StaticNodeList.h" #include "core/events/EventTarget.h" #include "core/frame/UseCounter.h" #include "core/svg/SVGElement.h" #include "wtf/CurrentTime.h" namespace blink { EventInit::EventInit() : bubbles(false) , cancelable(false) { } Event::Event() : m_canBubble(false) , m_cancelable(false) , m_propagationStopped(false) , m_immediatePropagationStopped(false) , m_defaultPrevented(false) , m_defaultHandled(false) , m_cancelBubble(false) , m_eventPhase(0) , m_currentTarget(nullptr) , m_createTime(convertSecondsToDOMTimeStamp(currentTime())) { ScriptWrappable::init(this); } Event::Event(const AtomicString& eventType, bool canBubbleArg, bool cancelableArg) : m_type(eventType) , m_canBubble(canBubbleArg) , m_cancelable(cancelableArg) , m_propagationStopped(false) , m_immediatePropagationStopped(false) , m_defaultPrevented(false) , m_defaultHandled(false) , m_cancelBubble(false) , m_eventPhase(0) , m_currentTarget(nullptr) , m_createTime(convertSecondsToDOMTimeStamp(currentTime())) { ScriptWrappable::init(this); } Event::Event(const AtomicString& eventType, const EventInit& initializer) : m_type(eventType) , m_canBubble(initializer.bubbles) , m_cancelable(initializer.cancelable) , m_propagationStopped(false) , m_immediatePropagationStopped(false) , m_defaultPrevented(false) , m_defaultHandled(false) , m_cancelBubble(false) , m_eventPhase(0) , m_currentTarget(nullptr) , m_createTime(convertSecondsToDOMTimeStamp(currentTime())) { ScriptWrappable::init(this); } Event::~Event() { } void Event::initEvent(const AtomicString& eventTypeArg, bool canBubbleArg, bool cancelableArg) { if (dispatched()) return; m_propagationStopped = false; m_immediatePropagationStopped = false; m_defaultPrevented = false; m_type = eventTypeArg; m_canBubble = canBubbleArg; m_cancelable = cancelableArg; } bool Event::legacyReturnValue(ExecutionContext* executionContext) const { bool returnValue = !defaultPrevented(); if (returnValue) UseCounter::count(executionContext, UseCounter::EventGetReturnValueTrue); else UseCounter::count(executionContext, UseCounter::EventGetReturnValueFalse); return returnValue; } void Event::setLegacyReturnValue(ExecutionContext* executionContext, bool returnValue) { if (returnValue) UseCounter::count(executionContext, UseCounter::EventSetReturnValueTrue); else UseCounter::count(executionContext, UseCounter::EventSetReturnValueFalse); setDefaultPrevented(!returnValue); } const AtomicString& Event::interfaceName() const { return EventNames::Event; } bool Event::hasInterface(const AtomicString& name) const { return interfaceName() == name; } bool Event::isUIEvent() const { return false; } bool Event::isMouseEvent() const { return false; } bool Event::isFocusEvent() const { return false; } bool Event::isKeyboardEvent() const { return false; } bool Event::isTouchEvent() const { return false; } bool Event::isGestureEvent() const { return false; } bool Event::isWheelEvent() const { return false; } bool Event::isRelatedEvent() const { return false; } bool Event::isDragEvent() const { return false; } bool Event::isClipboardEvent() const { return false; } bool Event::isBeforeTextInsertedEvent() const { return false; } bool Event::isBeforeUnloadEvent() const { return false; } void Event::setTarget(PassRefPtrWillBeRawPtr<EventTarget> target) { if (m_target == target) return; m_target = target; if (m_target) receivedTarget(); } void Event::receivedTarget() { } void Event::setUnderlyingEvent(PassRefPtrWillBeRawPtr<Event> ue) { // Prohibit creation of a cycle -- just do nothing in that case. for (Event* e = ue.get(); e; e = e->underlyingEvent()) if (e == this) return; m_underlyingEvent = ue; } EventPath& Event::ensureEventPath() { if (!m_eventPath) m_eventPath = adoptPtrWillBeNoop(new EventPath(this)); return *m_eventPath; } PassRefPtrWillBeRawPtr<StaticNodeList> Event::path() const { if (!m_currentTarget) { ASSERT(m_eventPhase == Event::NONE); if (!m_eventPath) { // Before dispatching the event return StaticNodeList::createEmpty(); } ASSERT(!m_eventPath->isEmpty()); // After dispatching the event return m_eventPath->last().treeScopeEventContext().ensureEventPath(*m_eventPath); } if (!m_currentTarget->toNode()) return StaticNodeList::createEmpty(); Node* node = m_currentTarget->toNode(); size_t eventPathSize = m_eventPath->size(); for (size_t i = 0; i < eventPathSize; ++i) { if (node == (*m_eventPath)[i].node()) { return (*m_eventPath)[i].treeScopeEventContext().ensureEventPath(*m_eventPath); } } return StaticNodeList::createEmpty(); } EventTarget* Event::currentTarget() const { if (!m_currentTarget) return 0; Node* node = m_currentTarget->toNode(); if (node && node->isSVGElement()) { if (SVGElement* svgElement = toSVGElement(node)->correspondingElement()) return svgElement; } return m_currentTarget.get(); } void Event::trace(Visitor* visitor) { visitor->trace(m_currentTarget); visitor->trace(m_target); visitor->trace(m_underlyingEvent); visitor->trace(m_eventPath); } } // namespace blink <|endoftext|>
<commit_before>/* * Copyright (C) 2013 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 "config.h" #include "wtf/PageAllocator.h" #include "wtf/CryptographicallyRandomNumber.h" #include "wtf/SpinLock.h" #if OS(POSIX) #include <sys/mman.h> #ifndef MADV_FREE #define MADV_FREE MADV_DONTNEED #endif #ifndef MAP_ANONYMOUS #define MAP_ANONYMOUS MAP_ANON #endif #elif OS(WIN) #include <windows.h> #else #error Unknown OS #endif // OS(POSIX) namespace WTF { void* allocSuperPages(void* addr, size_t len) { ASSERT(!(len & kSuperPageOffsetMask)); ASSERT(!(reinterpret_cast<uintptr_t>(addr) & kSuperPageOffsetMask)); #if OS(POSIX) char* ptr = reinterpret_cast<char*>(mmap(addr, len, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0)); RELEASE_ASSERT(ptr != MAP_FAILED); // If our requested address collided with another mapping, there's a // chance we'll get back an unaligned address. We fix this by attempting // the allocation again, but with enough slack pages that we can find // correct alignment within the allocation. if (UNLIKELY(reinterpret_cast<uintptr_t>(ptr) & kSuperPageOffsetMask)) { int ret = munmap(ptr, len); ASSERT(!ret); ptr = reinterpret_cast<char*>(mmap(0, len + kSuperPageSize - kSystemPageSize, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0)); RELEASE_ASSERT(ptr != MAP_FAILED); int numSystemPagesToUnmap = kNumSystemPagesPerSuperPage - 1; int numSystemPagesBefore = (kNumSystemPagesPerSuperPage - ((reinterpret_cast<uintptr_t>(ptr) & kSuperPageOffsetMask) / kSystemPageSize)) % kNumSystemPagesPerSuperPage; ASSERT(numSystemPagesBefore <= numSystemPagesToUnmap); int numSystemPagesAfter = numSystemPagesToUnmap - numSystemPagesBefore; if (numSystemPagesBefore) { size_t beforeSize = kSystemPageSize * numSystemPagesBefore; ret = munmap(ptr, beforeSize); ASSERT(!ret); ptr += beforeSize; } if (numSystemPagesAfter) { ret = munmap(ptr + len, kSystemPageSize * numSystemPagesAfter); ASSERT(!ret); } } void* ret = ptr; #else // Windows is a lot simpler because we've designed around its // coarser-grained alignement. void* ret = VirtualAlloc(addr, len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (!ret) ret = VirtualAlloc(0, len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); RELEASE_ASSERT(ret); #endif // OS(POSIX) SuperPageBitmap::registerSuperPage(ret); return ret; } void freeSuperPages(void* addr, size_t len) { ASSERT(!(reinterpret_cast<uintptr_t>(addr) & kSuperPageOffsetMask)); ASSERT(!(len & kSuperPageOffsetMask)); #if OS(POSIX) int ret = munmap(addr, len); ASSERT(!ret); #else BOOL ret = VirtualFree(addr, 0, MEM_RELEASE); ASSERT(ret); #endif SuperPageBitmap::unregisterSuperPage(addr); } void setSystemPagesInaccessible(void* addr, size_t len) { ASSERT(!(len & kSystemPageOffsetMask)); #if OS(POSIX) int ret = mprotect(addr, len, PROT_NONE); ASSERT(!ret); #else BOOL ret = VirtualFree(addr, len, MEM_DECOMMIT); ASSERT(ret); #endif } void decommitSystemPages(void* addr, size_t len) { ASSERT(!(len & kSystemPageOffsetMask)); #if OS(POSIX) int ret = madvise(addr, len, MADV_FREE); ASSERT(!ret); #else void* ret = VirtualAlloc(addr, len, MEM_RESET, PAGE_READWRITE); ASSERT(ret); #endif } char* getRandomSuperPageBase() { uintptr_t random; random = static_cast<uintptr_t>(cryptographicallyRandomNumber()); #if CPU(X86_64) random <<= 32UL; random |= static_cast<uintptr_t>(cryptographicallyRandomNumber()); // This address mask gives a low liklihood of address space collisions. // We handle the situation gracefully if there is a collision. #if OS(WIN) // 64-bit Windows has a bizarrely small 8TB user address space. // Allocates in the 1-5TB region. random &= (0x3ffffffffffUL & kSuperPageBaseMask); random += 0x10000000000UL; #else random &= (0x3fffffffffffUL & kSuperPageBaseMask); #endif #else // !CPU(X86_64) // This is a good range on Windows, Linux and Mac. // Allocates in the 0.5-1.5GB region. random &= (0x3fffffff & kSuperPageBaseMask); random += 0x20000000; #endif // CPU(X86_64) return reinterpret_cast<char*>(random); } #if CPU(32BIT) unsigned char SuperPageBitmap::s_bitmap[1 << (32 - kSuperPageShift - 3)]; static int bitmapLock = 0; void SuperPageBitmap::registerSuperPage(void* ptr) { ASSERT(!isPointerInSuperPage(ptr)); uintptr_t raw = reinterpret_cast<uintptr_t>(ptr); raw >>= kSuperPageShift; size_t byteIndex = raw >> 3; size_t bit = raw & 7; ASSERT(byteIndex < sizeof(s_bitmap)); // The read/modify/write is not guaranteed atomic, so take a lock. spinLockLock(&bitmapLock); s_bitmap[byteIndex] |= (1 << bit); spinLockUnlock(&bitmapLock); } void SuperPageBitmap::unregisterSuperPage(void* ptr) { ASSERT(isPointerInSuperPage(ptr)); uintptr_t raw = reinterpret_cast<uintptr_t>(ptr); raw >>= kSuperPageShift; size_t byteIndex = raw >> 3; size_t bit = raw & 7; ASSERT(byteIndex < sizeof(s_bitmap)); // The read/modify/write is not guaranteed atomic, so take a lock. spinLockLock(&bitmapLock); s_bitmap[byteIndex] &= ~(1 << bit); spinLockUnlock(&bitmapLock); } #endif } // namespace WTF <commit_msg>Remove dependency between PageAllocator and platform.<commit_after>/* * Copyright (C) 2013 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 "config.h" #include "wtf/PageAllocator.h" #include "wtf/ProcessID.h" #include "wtf/SpinLock.h" #if OS(POSIX) #include <sys/mman.h> #ifndef MADV_FREE #define MADV_FREE MADV_DONTNEED #endif #ifndef MAP_ANONYMOUS #define MAP_ANONYMOUS MAP_ANON #endif #elif OS(WIN) #include <windows.h> #else #error Unknown OS #endif // OS(POSIX) namespace WTF { void* allocSuperPages(void* addr, size_t len) { ASSERT(!(len & kSuperPageOffsetMask)); ASSERT(!(reinterpret_cast<uintptr_t>(addr) & kSuperPageOffsetMask)); #if OS(POSIX) char* ptr = reinterpret_cast<char*>(mmap(addr, len, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0)); RELEASE_ASSERT(ptr != MAP_FAILED); // If our requested address collided with another mapping, there's a // chance we'll get back an unaligned address. We fix this by attempting // the allocation again, but with enough slack pages that we can find // correct alignment within the allocation. if (UNLIKELY(reinterpret_cast<uintptr_t>(ptr) & kSuperPageOffsetMask)) { int ret = munmap(ptr, len); ASSERT(!ret); ptr = reinterpret_cast<char*>(mmap(0, len + kSuperPageSize - kSystemPageSize, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0)); RELEASE_ASSERT(ptr != MAP_FAILED); int numSystemPagesToUnmap = kNumSystemPagesPerSuperPage - 1; int numSystemPagesBefore = (kNumSystemPagesPerSuperPage - ((reinterpret_cast<uintptr_t>(ptr) & kSuperPageOffsetMask) / kSystemPageSize)) % kNumSystemPagesPerSuperPage; ASSERT(numSystemPagesBefore <= numSystemPagesToUnmap); int numSystemPagesAfter = numSystemPagesToUnmap - numSystemPagesBefore; if (numSystemPagesBefore) { size_t beforeSize = kSystemPageSize * numSystemPagesBefore; ret = munmap(ptr, beforeSize); ASSERT(!ret); ptr += beforeSize; } if (numSystemPagesAfter) { ret = munmap(ptr + len, kSystemPageSize * numSystemPagesAfter); ASSERT(!ret); } } void* ret = ptr; #else // Windows is a lot simpler because we've designed around its // coarser-grained alignement. void* ret = VirtualAlloc(addr, len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (!ret) ret = VirtualAlloc(0, len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); RELEASE_ASSERT(ret); #endif // OS(POSIX) SuperPageBitmap::registerSuperPage(ret); return ret; } void freeSuperPages(void* addr, size_t len) { ASSERT(!(reinterpret_cast<uintptr_t>(addr) & kSuperPageOffsetMask)); ASSERT(!(len & kSuperPageOffsetMask)); #if OS(POSIX) int ret = munmap(addr, len); ASSERT(!ret); #else BOOL ret = VirtualFree(addr, 0, MEM_RELEASE); ASSERT(ret); #endif SuperPageBitmap::unregisterSuperPage(addr); } void setSystemPagesInaccessible(void* addr, size_t len) { ASSERT(!(len & kSystemPageOffsetMask)); #if OS(POSIX) int ret = mprotect(addr, len, PROT_NONE); ASSERT(!ret); #else BOOL ret = VirtualFree(addr, len, MEM_DECOMMIT); ASSERT(ret); #endif } void decommitSystemPages(void* addr, size_t len) { ASSERT(!(len & kSystemPageOffsetMask)); #if OS(POSIX) int ret = madvise(addr, len, MADV_FREE); ASSERT(!ret); #else void* ret = VirtualAlloc(addr, len, MEM_RESET, PAGE_READWRITE); ASSERT(ret); #endif } // This is the same PRNG as used by tcmalloc for mapping address randomness; // see http://burtleburtle.net/bob/rand/smallprng.html struct ranctx { int lock; bool initialized; uint32_t a; uint32_t b; uint32_t c; uint32_t d; }; #define rot(x, k) (((x) << (k)) | ((x) >> (32 - (k)))) uint32_t ranvalInternal(ranctx* x) { uint32_t e = x->a - rot(x->b, 27); x->a = x->b ^ rot(x->c, 17); x->b = x->c + x->d; x->c = x->d + e; x->d = e + x->a; return x->d; } #undef rot uint32_t ranval(ranctx* x) { spinLockLock(&x->lock); if (UNLIKELY(!x->initialized)) { x->initialized = true; char c; uint32_t seed = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(&c)); seed ^= static_cast<uint32_t>(getCurrentProcessID()); x->a = 0xf1ea5eed; x->b = x->c = x->d = seed; for (int i = 0; i < 20; ++i) { (void) ranvalInternal(x); } } uint32_t ret = ranvalInternal(x); spinLockUnlock(&x->lock); return ret; } char* getRandomSuperPageBase() { static struct ranctx ranctx; uintptr_t random; random = static_cast<uintptr_t>(ranval(&ranctx)); #if CPU(X86_64) random <<= 32UL; random |= static_cast<uintptr_t>(ranval(&ranctx)); // This address mask gives a low liklihood of address space collisions. // We handle the situation gracefully if there is a collision. #if OS(WIN) // 64-bit Windows has a bizarrely small 8TB user address space. // Allocates in the 1-5TB region. random &= (0x3ffffffffffUL & kSuperPageBaseMask); random += 0x10000000000UL; #else random &= (0x3fffffffffffUL & kSuperPageBaseMask); #endif #else // !CPU(X86_64) // This is a good range on Windows, Linux and Mac. // Allocates in the 0.5-1.5GB region. random &= (0x3fffffff & kSuperPageBaseMask); random += 0x20000000; #endif // CPU(X86_64) return reinterpret_cast<char*>(random); } #if CPU(32BIT) unsigned char SuperPageBitmap::s_bitmap[1 << (32 - kSuperPageShift - 3)]; static int bitmapLock = 0; void SuperPageBitmap::registerSuperPage(void* ptr) { ASSERT(!isPointerInSuperPage(ptr)); uintptr_t raw = reinterpret_cast<uintptr_t>(ptr); raw >>= kSuperPageShift; size_t byteIndex = raw >> 3; size_t bit = raw & 7; ASSERT(byteIndex < sizeof(s_bitmap)); // The read/modify/write is not guaranteed atomic, so take a lock. spinLockLock(&bitmapLock); s_bitmap[byteIndex] |= (1 << bit); spinLockUnlock(&bitmapLock); } void SuperPageBitmap::unregisterSuperPage(void* ptr) { ASSERT(isPointerInSuperPage(ptr)); uintptr_t raw = reinterpret_cast<uintptr_t>(ptr); raw >>= kSuperPageShift; size_t byteIndex = raw >> 3; size_t bit = raw & 7; ASSERT(byteIndex < sizeof(s_bitmap)); // The read/modify/write is not guaranteed atomic, so take a lock. spinLockLock(&bitmapLock); s_bitmap[byteIndex] &= ~(1 << bit); spinLockUnlock(&bitmapLock); } #endif } // namespace WTF <|endoftext|>
<commit_before>/* * Copyright (C) 2013 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 "config.h" #include "wtf/PageAllocator.h" #include "wtf/Assertions.h" #include "wtf/ProcessID.h" #include "wtf/SpinLock.h" #include <limits.h> #if OS(POSIX) #include <sys/mman.h> #ifndef MADV_FREE #define MADV_FREE MADV_DONTNEED #endif #ifndef MAP_ANONYMOUS #define MAP_ANONYMOUS MAP_ANON #endif #elif OS(WIN) #include <windows.h> #else #error Unknown OS #endif // OS(POSIX) namespace WTF { // This simple internal function wraps the OS-specific page allocation call so // that it behaves consistently: the address is a hint and if it cannot be used, // the allocation will be placed elsewhere. static void* systemAllocPages(void* addr, size_t len) { ASSERT(!(len & kPageAllocationGranularityOffsetMask)); ASSERT(!(reinterpret_cast<uintptr_t>(addr) & kPageAllocationGranularityOffsetMask)); void* ret; #if OS(WIN) ret = VirtualAlloc(addr, len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (!ret) ret = VirtualAlloc(0, len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); #else ret = mmap(addr, len, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); if (ret == MAP_FAILED) ret = 0; #endif return ret; } static bool trimMapping(void* baseAddr, size_t baseLen, void* trimAddr, size_t trimLen) { #if OS(WIN) return false; #else char* basePtr = static_cast<char*>(baseAddr); char* trimPtr = static_cast<char*>(trimAddr); ASSERT(trimPtr >= basePtr); ASSERT(trimPtr + trimLen <= basePtr + baseLen); size_t preLen = trimPtr - basePtr; if (preLen) { int ret = munmap(basePtr, preLen); RELEASE_ASSERT(!ret); } size_t postLen = (basePtr + baseLen) - (trimPtr + trimLen); if (postLen) { int ret = munmap(trimPtr + trimLen, postLen); RELEASE_ASSERT(!ret); } return true; #endif } // This is the same PRNG as used by tcmalloc for mapping address randomness; // see http://burtleburtle.net/bob/rand/smallprng.html struct ranctx { int lock; bool initialized; uint32_t a; uint32_t b; uint32_t c; uint32_t d; }; #define rot(x, k) (((x) << (k)) | ((x) >> (32 - (k)))) uint32_t ranvalInternal(ranctx* x) { uint32_t e = x->a - rot(x->b, 27); x->a = x->b ^ rot(x->c, 17); x->b = x->c + x->d; x->c = x->d + e; x->d = e + x->a; return x->d; } #undef rot uint32_t ranval(ranctx* x) { spinLockLock(&x->lock); if (UNLIKELY(!x->initialized)) { x->initialized = true; char c; uint32_t seed = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(&c)); seed ^= static_cast<uint32_t>(getCurrentProcessID()); x->a = 0xf1ea5eed; x->b = x->c = x->d = seed; for (int i = 0; i < 20; ++i) { (void) ranvalInternal(x); } } uint32_t ret = ranvalInternal(x); spinLockUnlock(&x->lock); return ret; } static struct ranctx s_ranctx; // This internal function calculates a random preferred mapping address. // It is used when the client of allocPages() passes null as the address. // In calculating an address, we balance good ASLR against not fragmenting the // address space too badly. static void* getRandomPageBase() { uintptr_t random; random = static_cast<uintptr_t>(ranval(&s_ranctx)); #if CPU(X86_64) random <<= 32UL; random |= static_cast<uintptr_t>(ranval(&s_ranctx)); // This address mask gives a low liklihood of address space collisions. // We handle the situation gracefully if there is a collision. #if OS(WIN) // 64-bit Windows has a bizarrely small 8TB user address space. // Allocates in the 1-5TB region. random &= 0x3ffffffffffUL; random += 0x10000000000UL; #else // Linux and OS X support the full 47-bit user space of x64 processors. random &= 0x3fffffffffffUL; #endif #else // !CPU(X86_64) // This is a good range on Windows, Linux and Mac. // Allocates in the 0.5-1.5GB region. random &= 0x3fffffff; random += 0x20000000; #endif // CPU(X86_64) random &= kPageAllocationGranularityBaseMask; return reinterpret_cast<void*>(random); } void* allocPages(void* addr, size_t len, size_t align) { ASSERT(len >= kPageAllocationGranularity); ASSERT(!(len & kPageAllocationGranularityOffsetMask)); ASSERT(align >= kPageAllocationGranularity); ASSERT(!(align & kPageAllocationGranularityOffsetMask)); ASSERT(!(reinterpret_cast<uintptr_t>(addr) & kPageAllocationGranularityOffsetMask)); size_t alignOffsetMask = align - 1; size_t alignBaseMask = ~alignOffsetMask; ASSERT(!(reinterpret_cast<uintptr_t>(addr) & alignOffsetMask)); // If the client passed null as the address, choose a good one. if (!addr) { addr = getRandomPageBase(); addr = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(addr) & alignBaseMask); } // The common case, which is also the least work we can do, is that the // address and length are suitable. Just try it. void* ret = systemAllocPages(addr, len); // If the alignment is to our liking, we're done. if (!ret || !(reinterpret_cast<uintptr_t>(ret) & alignOffsetMask)) return ret; // Annoying. Unmap and map a larger range to be sure to succeed on the // second, slower attempt. freePages(ret, len); size_t tryLen = len + (align - kPageAllocationGranularity); RELEASE_ASSERT(tryLen > len); // We loop to cater for the unlikely case where another thread maps on top // of the aligned location we choose. int count = 0; while (count++ < 100) { ret = systemAllocPages(addr, tryLen); if (!ret) return 0; // We can now try and trim out a subset of the mapping. addr = reinterpret_cast<void*>((reinterpret_cast<uintptr_t>(ret) + alignOffsetMask) & alignBaseMask); // On POSIX systems, we can trim the oversized mapping to fit exactly. // This will always work on POSIX systems. if (trimMapping(ret, tryLen, addr, len)) return addr; // On Windows, you can't trim an existing mapping so we unmap and remap // a subset. We used to do for all platforms, but OSX 10.8 has a // broken mmap() that ignores address hints for valid, unused addresses. freePages(ret, tryLen); ret = systemAllocPages(addr, len); if (ret == addr || !ret) return ret; // Unlikely race / collision. Do the simple thing and just start again. freePages(ret, len); addr = getRandomPageBase(); addr = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(addr) & alignBaseMask); } IMMEDIATE_CRASH(); return 0; } void freePages(void* addr, size_t len) { ASSERT(!(reinterpret_cast<uintptr_t>(addr) & kPageAllocationGranularityOffsetMask)); ASSERT(!(len & kPageAllocationGranularityOffsetMask)); #if OS(POSIX) int ret = munmap(addr, len); RELEASE_ASSERT(!ret); #else BOOL ret = VirtualFree(addr, 0, MEM_RELEASE); RELEASE_ASSERT(ret); #endif } void setSystemPagesInaccessible(void* addr, size_t len) { ASSERT(!(len & kSystemPageOffsetMask)); #if OS(POSIX) int ret = mprotect(addr, len, PROT_NONE); RELEASE_ASSERT(!ret); #else BOOL ret = VirtualFree(addr, len, MEM_DECOMMIT); RELEASE_ASSERT(ret); #endif } void setSystemPagesAccessible(void* addr, size_t len) { ASSERT(!(len & kSystemPageOffsetMask)); #if OS(POSIX) int ret = mprotect(addr, len, PROT_READ | PROT_WRITE); RELEASE_ASSERT(!ret); #else void* ret = VirtualAlloc(addr, len, MEM_COMMIT, PAGE_READWRITE); RELEASE_ASSERT(ret); #endif } void decommitSystemPages(void* addr, size_t len) { ASSERT(!(len & kSystemPageOffsetMask)); #if OS(POSIX) int ret = madvise(addr, len, MADV_FREE); RELEASE_ASSERT(!ret); #else void* ret = VirtualAlloc(addr, len, MEM_RESET, PAGE_READWRITE); RELEASE_ASSERT(ret); #endif } void recommitSystemPages(void* addr, size_t len) { // FIXME: experiment with a Windows implementation that uses MEM_COMMIT // instead of just faulting a MEM_RESET page. (void) addr; ASSERT(!(len & kSystemPageOffsetMask)); } } // namespace WTF <commit_msg>ARM64 has 39-bits of address space.<commit_after>/* * Copyright (C) 2013 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 "config.h" #include "wtf/PageAllocator.h" #include "wtf/Assertions.h" #include "wtf/ProcessID.h" #include "wtf/SpinLock.h" #include <limits.h> #if OS(POSIX) #include <sys/mman.h> #ifndef MADV_FREE #define MADV_FREE MADV_DONTNEED #endif #ifndef MAP_ANONYMOUS #define MAP_ANONYMOUS MAP_ANON #endif #elif OS(WIN) #include <windows.h> #else #error Unknown OS #endif // OS(POSIX) namespace WTF { // This simple internal function wraps the OS-specific page allocation call so // that it behaves consistently: the address is a hint and if it cannot be used, // the allocation will be placed elsewhere. static void* systemAllocPages(void* addr, size_t len) { ASSERT(!(len & kPageAllocationGranularityOffsetMask)); ASSERT(!(reinterpret_cast<uintptr_t>(addr) & kPageAllocationGranularityOffsetMask)); void* ret; #if OS(WIN) ret = VirtualAlloc(addr, len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (!ret) ret = VirtualAlloc(0, len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); #else ret = mmap(addr, len, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); if (ret == MAP_FAILED) ret = 0; #endif return ret; } static bool trimMapping(void* baseAddr, size_t baseLen, void* trimAddr, size_t trimLen) { #if OS(WIN) return false; #else char* basePtr = static_cast<char*>(baseAddr); char* trimPtr = static_cast<char*>(trimAddr); ASSERT(trimPtr >= basePtr); ASSERT(trimPtr + trimLen <= basePtr + baseLen); size_t preLen = trimPtr - basePtr; if (preLen) { int ret = munmap(basePtr, preLen); RELEASE_ASSERT(!ret); } size_t postLen = (basePtr + baseLen) - (trimPtr + trimLen); if (postLen) { int ret = munmap(trimPtr + trimLen, postLen); RELEASE_ASSERT(!ret); } return true; #endif } // This is the same PRNG as used by tcmalloc for mapping address randomness; // see http://burtleburtle.net/bob/rand/smallprng.html struct ranctx { int lock; bool initialized; uint32_t a; uint32_t b; uint32_t c; uint32_t d; }; #define rot(x, k) (((x) << (k)) | ((x) >> (32 - (k)))) uint32_t ranvalInternal(ranctx* x) { uint32_t e = x->a - rot(x->b, 27); x->a = x->b ^ rot(x->c, 17); x->b = x->c + x->d; x->c = x->d + e; x->d = e + x->a; return x->d; } #undef rot uint32_t ranval(ranctx* x) { spinLockLock(&x->lock); if (UNLIKELY(!x->initialized)) { x->initialized = true; char c; uint32_t seed = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(&c)); seed ^= static_cast<uint32_t>(getCurrentProcessID()); x->a = 0xf1ea5eed; x->b = x->c = x->d = seed; for (int i = 0; i < 20; ++i) { (void) ranvalInternal(x); } } uint32_t ret = ranvalInternal(x); spinLockUnlock(&x->lock); return ret; } static struct ranctx s_ranctx; // This internal function calculates a random preferred mapping address. // It is used when the client of allocPages() passes null as the address. // In calculating an address, we balance good ASLR against not fragmenting the // address space too badly. static void* getRandomPageBase() { uintptr_t random; random = static_cast<uintptr_t>(ranval(&s_ranctx)); #if CPU(X86_64) random <<= 32UL; random |= static_cast<uintptr_t>(ranval(&s_ranctx)); // This address mask gives a low liklihood of address space collisions. // We handle the situation gracefully if there is a collision. #if OS(WIN) // 64-bit Windows has a bizarrely small 8TB user address space. // Allocates in the 1-5TB region. random &= 0x3ffffffffffUL; random += 0x10000000000UL; #else // Linux and OS X support the full 47-bit user space of x64 processors. random &= 0x3fffffffffffUL; #endif #elif CPU(ARM64) // ARM64 on Linux has 39-bit user space. random &= 0x3fffffffffUL; random += 0x1000000000UL; #else // !CPU(X86_64) && !CPU(ARM64) // This is a good range on Windows, Linux and Mac. // Allocates in the 0.5-1.5GB region. random &= 0x3fffffff; random += 0x20000000; #endif // CPU(X86_64) random &= kPageAllocationGranularityBaseMask; return reinterpret_cast<void*>(random); } void* allocPages(void* addr, size_t len, size_t align) { ASSERT(len >= kPageAllocationGranularity); ASSERT(!(len & kPageAllocationGranularityOffsetMask)); ASSERT(align >= kPageAllocationGranularity); ASSERT(!(align & kPageAllocationGranularityOffsetMask)); ASSERT(!(reinterpret_cast<uintptr_t>(addr) & kPageAllocationGranularityOffsetMask)); size_t alignOffsetMask = align - 1; size_t alignBaseMask = ~alignOffsetMask; ASSERT(!(reinterpret_cast<uintptr_t>(addr) & alignOffsetMask)); // If the client passed null as the address, choose a good one. if (!addr) { addr = getRandomPageBase(); addr = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(addr) & alignBaseMask); } // The common case, which is also the least work we can do, is that the // address and length are suitable. Just try it. void* ret = systemAllocPages(addr, len); // If the alignment is to our liking, we're done. if (!ret || !(reinterpret_cast<uintptr_t>(ret) & alignOffsetMask)) return ret; // Annoying. Unmap and map a larger range to be sure to succeed on the // second, slower attempt. freePages(ret, len); size_t tryLen = len + (align - kPageAllocationGranularity); RELEASE_ASSERT(tryLen > len); // We loop to cater for the unlikely case where another thread maps on top // of the aligned location we choose. int count = 0; while (count++ < 100) { ret = systemAllocPages(addr, tryLen); if (!ret) return 0; // We can now try and trim out a subset of the mapping. addr = reinterpret_cast<void*>((reinterpret_cast<uintptr_t>(ret) + alignOffsetMask) & alignBaseMask); // On POSIX systems, we can trim the oversized mapping to fit exactly. // This will always work on POSIX systems. if (trimMapping(ret, tryLen, addr, len)) return addr; // On Windows, you can't trim an existing mapping so we unmap and remap // a subset. We used to do for all platforms, but OSX 10.8 has a // broken mmap() that ignores address hints for valid, unused addresses. freePages(ret, tryLen); ret = systemAllocPages(addr, len); if (ret == addr || !ret) return ret; // Unlikely race / collision. Do the simple thing and just start again. freePages(ret, len); addr = getRandomPageBase(); addr = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(addr) & alignBaseMask); } IMMEDIATE_CRASH(); return 0; } void freePages(void* addr, size_t len) { ASSERT(!(reinterpret_cast<uintptr_t>(addr) & kPageAllocationGranularityOffsetMask)); ASSERT(!(len & kPageAllocationGranularityOffsetMask)); #if OS(POSIX) int ret = munmap(addr, len); RELEASE_ASSERT(!ret); #else BOOL ret = VirtualFree(addr, 0, MEM_RELEASE); RELEASE_ASSERT(ret); #endif } void setSystemPagesInaccessible(void* addr, size_t len) { ASSERT(!(len & kSystemPageOffsetMask)); #if OS(POSIX) int ret = mprotect(addr, len, PROT_NONE); RELEASE_ASSERT(!ret); #else BOOL ret = VirtualFree(addr, len, MEM_DECOMMIT); RELEASE_ASSERT(ret); #endif } void setSystemPagesAccessible(void* addr, size_t len) { ASSERT(!(len & kSystemPageOffsetMask)); #if OS(POSIX) int ret = mprotect(addr, len, PROT_READ | PROT_WRITE); RELEASE_ASSERT(!ret); #else void* ret = VirtualAlloc(addr, len, MEM_COMMIT, PAGE_READWRITE); RELEASE_ASSERT(ret); #endif } void decommitSystemPages(void* addr, size_t len) { ASSERT(!(len & kSystemPageOffsetMask)); #if OS(POSIX) int ret = madvise(addr, len, MADV_FREE); RELEASE_ASSERT(!ret); #else void* ret = VirtualAlloc(addr, len, MEM_RESET, PAGE_READWRITE); RELEASE_ASSERT(ret); #endif } void recommitSystemPages(void* addr, size_t len) { // FIXME: experiment with a Windows implementation that uses MEM_COMMIT // instead of just faulting a MEM_RESET page. (void) addr; ASSERT(!(len & kSystemPageOffsetMask)); } } // namespace WTF <|endoftext|>
<commit_before>/*************************************************************************/ /* audio_stream_ogg_vorbis.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2017 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 "audio_stream_ogg_vorbis.h" #include "os/file_access.h" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" #include "thirdparty/misc/stb_vorbis.c" #pragma GCC diagnostic pop void AudioStreamPlaybackOGGVorbis::_mix_internal(AudioFrame *p_buffer, int p_frames) { ERR_FAIL_COND(!active); int todo = p_frames; while (todo && active) { int mixed = stb_vorbis_get_samples_float_interleaved(ogg_stream, 2, (float *)p_buffer, todo * 2); if (vorbis_stream->channels == 1 && mixed > 0) { //mix mono to stereo for (int i = 0; i < mixed; i++) { p_buffer[i].r = p_buffer[i].l; } } todo -= mixed; frames_mixed += mixed; if (todo) { //end of file! if (vorbis_stream->loop) { //loop seek(vorbis_stream->loop_offset); loops++; } else { for (int i = mixed; i < p_frames; i++) { p_buffer[i] = AudioFrame(0, 0); } active = false; } } } } float AudioStreamPlaybackOGGVorbis::get_stream_sampling_rate() { return vorbis_stream->sample_rate; } void AudioStreamPlaybackOGGVorbis::start(float p_from_pos) { active = true; seek(p_from_pos); loops = 0; _begin_resample(); } void AudioStreamPlaybackOGGVorbis::stop() { active = false; } bool AudioStreamPlaybackOGGVorbis::is_playing() const { return active; } int AudioStreamPlaybackOGGVorbis::get_loop_count() const { return loops; } float AudioStreamPlaybackOGGVorbis::get_playback_position() const { return float(frames_mixed) / vorbis_stream->sample_rate; } void AudioStreamPlaybackOGGVorbis::seek(float p_time) { if (!active) return; if (p_time >= get_length()) { p_time = 0; } frames_mixed = uint32_t(vorbis_stream->sample_rate * p_time); stb_vorbis_seek(ogg_stream, frames_mixed); } float AudioStreamPlaybackOGGVorbis::get_length() const { return vorbis_stream->length; } AudioStreamPlaybackOGGVorbis::~AudioStreamPlaybackOGGVorbis() { if (ogg_alloc.alloc_buffer) { stb_vorbis_close(ogg_stream); AudioServer::get_singleton()->audio_data_free(ogg_alloc.alloc_buffer); } } Ref<AudioStreamPlayback> AudioStreamOGGVorbis::instance_playback() { Ref<AudioStreamPlaybackOGGVorbis> ovs; ERR_FAIL_COND_V(data == NULL, ovs); ovs.instance(); ovs->vorbis_stream = Ref<AudioStreamOGGVorbis>(this); ovs->ogg_alloc.alloc_buffer = (char *)AudioServer::get_singleton()->audio_data_alloc(decode_mem_size); ovs->ogg_alloc.alloc_buffer_length_in_bytes = decode_mem_size; ovs->frames_mixed = 0; ovs->active = false; ovs->loops = 0; int error; ovs->ogg_stream = stb_vorbis_open_memory((const unsigned char *)data, data_len, &error, &ovs->ogg_alloc); if (!ovs->ogg_stream) { AudioServer::get_singleton()->audio_data_free(ovs->ogg_alloc.alloc_buffer); ovs->ogg_alloc.alloc_buffer = NULL; ERR_FAIL_COND_V(!ovs->ogg_stream, Ref<AudioStreamPlaybackOGGVorbis>()); } return ovs; } String AudioStreamOGGVorbis::get_stream_name() const { return ""; //return stream_name; } void AudioStreamOGGVorbis::set_data(const PoolVector<uint8_t> &p_data) { int src_data_len = p_data.size(); #define MAX_TEST_MEM (1 << 20) uint32_t alloc_try = 1024; PoolVector<char> alloc_mem; PoolVector<char>::Write w; stb_vorbis *ogg_stream = NULL; stb_vorbis_alloc ogg_alloc; while (alloc_try < MAX_TEST_MEM) { alloc_mem.resize(alloc_try); w = alloc_mem.write(); ogg_alloc.alloc_buffer = w.ptr(); ogg_alloc.alloc_buffer_length_in_bytes = alloc_try; PoolVector<uint8_t>::Read src_datar = p_data.read(); int error; ogg_stream = stb_vorbis_open_memory((const unsigned char *)src_datar.ptr(), src_data_len, &error, &ogg_alloc); if (!ogg_stream && error == VORBIS_outofmem) { w = PoolVector<char>::Write(); alloc_try *= 2; } else { ERR_FAIL_COND(alloc_try == MAX_TEST_MEM); ERR_FAIL_COND(ogg_stream == NULL); stb_vorbis_info info = stb_vorbis_get_info(ogg_stream); channels = info.channels; sample_rate = info.sample_rate; decode_mem_size = alloc_try; //does this work? (it's less mem..) //decode_mem_size = ogg_alloc.alloc_buffer_length_in_bytes + info.setup_memory_required + info.temp_memory_required + info.max_frame_size; //print_line("succeeded "+itos(ogg_alloc.alloc_buffer_length_in_bytes)+" setup "+itos(info.setup_memory_required)+" setup temp "+itos(info.setup_temp_memory_required)+" temp "+itos(info.temp_memory_required)+" maxframe"+itos(info.max_frame_size)); length = stb_vorbis_stream_length_in_seconds(ogg_stream); stb_vorbis_close(ogg_stream); data = AudioServer::get_singleton()->audio_data_alloc(src_data_len, src_datar.ptr()); data_len = src_data_len; break; } } } PoolVector<uint8_t> AudioStreamOGGVorbis::get_data() const { PoolVector<uint8_t> vdata; if (data_len && data) { vdata.resize(data_len); { PoolVector<uint8_t>::Write w = vdata.write(); copymem(w.ptr(), data, data_len); } } return vdata; } void AudioStreamOGGVorbis::set_loop(bool p_enable) { loop = p_enable; } bool AudioStreamOGGVorbis::has_loop() const { return loop; } void AudioStreamOGGVorbis::set_loop_offset(float p_seconds) { loop_offset = p_seconds; } float AudioStreamOGGVorbis::get_loop_offset() const { return loop_offset; } void AudioStreamOGGVorbis::_bind_methods() { ClassDB::bind_method(D_METHOD("set_data", "data"), &AudioStreamOGGVorbis::set_data); ClassDB::bind_method(D_METHOD("get_data"), &AudioStreamOGGVorbis::get_data); ClassDB::bind_method(D_METHOD("set_loop", "enable"), &AudioStreamOGGVorbis::set_loop); ClassDB::bind_method(D_METHOD("has_loop"), &AudioStreamOGGVorbis::has_loop); ClassDB::bind_method(D_METHOD("set_loop_offset", "seconds"), &AudioStreamOGGVorbis::set_loop_offset); ClassDB::bind_method(D_METHOD("get_loop_offset"), &AudioStreamOGGVorbis::get_loop_offset); ADD_PROPERTY(PropertyInfo(Variant::POOL_BYTE_ARRAY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_data", "get_data"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "loop", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_loop", "has_loop"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "loop_offset", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_loop_offset", "get_loop_offset"); } AudioStreamOGGVorbis::AudioStreamOGGVorbis() { data = NULL; length = 0; sample_rate = 1; channels = 1; loop_offset = 0; decode_mem_size = 0; loop = false; } <commit_msg>Fix ogg looping pop noise. Closes #11468<commit_after>/*************************************************************************/ /* audio_stream_ogg_vorbis.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2017 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 "audio_stream_ogg_vorbis.h" #include "os/file_access.h" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" #include "thirdparty/misc/stb_vorbis.c" #pragma GCC diagnostic pop void AudioStreamPlaybackOGGVorbis::_mix_internal(AudioFrame *p_buffer, int p_frames) { ERR_FAIL_COND(!active); int todo = p_frames; int start_buffer = 0; while (todo && active) { float *buffer = (float *)p_buffer; if (start_buffer > 0) { buffer = (buffer + start_buffer * 2); } int mixed = stb_vorbis_get_samples_float_interleaved(ogg_stream, 2, buffer, todo * 2); if (vorbis_stream->channels == 1 && mixed > 0) { //mix mono to stereo for (int i = start_buffer; i < mixed; i++) { p_buffer[i].r = p_buffer[i].l; } } todo -= mixed; frames_mixed += mixed; if (todo) { //end of file! if (vorbis_stream->loop) { //loop seek(vorbis_stream->loop_offset); loops++; // we still have buffer to fill, start from this element in the next iteration. start_buffer = p_frames - todo; } else { for (int i = p_frames - todo; i < p_frames; i++) { p_buffer[i] = AudioFrame(0, 0); } active = false; todo = 0; } } } } float AudioStreamPlaybackOGGVorbis::get_stream_sampling_rate() { return vorbis_stream->sample_rate; } void AudioStreamPlaybackOGGVorbis::start(float p_from_pos) { active = true; seek(p_from_pos); loops = 0; _begin_resample(); } void AudioStreamPlaybackOGGVorbis::stop() { active = false; } bool AudioStreamPlaybackOGGVorbis::is_playing() const { return active; } int AudioStreamPlaybackOGGVorbis::get_loop_count() const { return loops; } float AudioStreamPlaybackOGGVorbis::get_playback_position() const { return float(frames_mixed) / vorbis_stream->sample_rate; } void AudioStreamPlaybackOGGVorbis::seek(float p_time) { if (!active) return; if (p_time >= get_length()) { p_time = 0; } frames_mixed = uint32_t(vorbis_stream->sample_rate * p_time); stb_vorbis_seek(ogg_stream, frames_mixed); } float AudioStreamPlaybackOGGVorbis::get_length() const { return vorbis_stream->length; } AudioStreamPlaybackOGGVorbis::~AudioStreamPlaybackOGGVorbis() { if (ogg_alloc.alloc_buffer) { stb_vorbis_close(ogg_stream); AudioServer::get_singleton()->audio_data_free(ogg_alloc.alloc_buffer); } } Ref<AudioStreamPlayback> AudioStreamOGGVorbis::instance_playback() { Ref<AudioStreamPlaybackOGGVorbis> ovs; ERR_FAIL_COND_V(data == NULL, ovs); ovs.instance(); ovs->vorbis_stream = Ref<AudioStreamOGGVorbis>(this); ovs->ogg_alloc.alloc_buffer = (char *)AudioServer::get_singleton()->audio_data_alloc(decode_mem_size); ovs->ogg_alloc.alloc_buffer_length_in_bytes = decode_mem_size; ovs->frames_mixed = 0; ovs->active = false; ovs->loops = 0; int error; ovs->ogg_stream = stb_vorbis_open_memory((const unsigned char *)data, data_len, &error, &ovs->ogg_alloc); if (!ovs->ogg_stream) { AudioServer::get_singleton()->audio_data_free(ovs->ogg_alloc.alloc_buffer); ovs->ogg_alloc.alloc_buffer = NULL; ERR_FAIL_COND_V(!ovs->ogg_stream, Ref<AudioStreamPlaybackOGGVorbis>()); } return ovs; } String AudioStreamOGGVorbis::get_stream_name() const { return ""; //return stream_name; } void AudioStreamOGGVorbis::set_data(const PoolVector<uint8_t> &p_data) { int src_data_len = p_data.size(); #define MAX_TEST_MEM (1 << 20) uint32_t alloc_try = 1024; PoolVector<char> alloc_mem; PoolVector<char>::Write w; stb_vorbis *ogg_stream = NULL; stb_vorbis_alloc ogg_alloc; while (alloc_try < MAX_TEST_MEM) { alloc_mem.resize(alloc_try); w = alloc_mem.write(); ogg_alloc.alloc_buffer = w.ptr(); ogg_alloc.alloc_buffer_length_in_bytes = alloc_try; PoolVector<uint8_t>::Read src_datar = p_data.read(); int error; ogg_stream = stb_vorbis_open_memory((const unsigned char *)src_datar.ptr(), src_data_len, &error, &ogg_alloc); if (!ogg_stream && error == VORBIS_outofmem) { w = PoolVector<char>::Write(); alloc_try *= 2; } else { ERR_FAIL_COND(alloc_try == MAX_TEST_MEM); ERR_FAIL_COND(ogg_stream == NULL); stb_vorbis_info info = stb_vorbis_get_info(ogg_stream); channels = info.channels; sample_rate = info.sample_rate; decode_mem_size = alloc_try; //does this work? (it's less mem..) //decode_mem_size = ogg_alloc.alloc_buffer_length_in_bytes + info.setup_memory_required + info.temp_memory_required + info.max_frame_size; //print_line("succeeded "+itos(ogg_alloc.alloc_buffer_length_in_bytes)+" setup "+itos(info.setup_memory_required)+" setup temp "+itos(info.setup_temp_memory_required)+" temp "+itos(info.temp_memory_required)+" maxframe"+itos(info.max_frame_size)); length = stb_vorbis_stream_length_in_seconds(ogg_stream); stb_vorbis_close(ogg_stream); data = AudioServer::get_singleton()->audio_data_alloc(src_data_len, src_datar.ptr()); data_len = src_data_len; break; } } } PoolVector<uint8_t> AudioStreamOGGVorbis::get_data() const { PoolVector<uint8_t> vdata; if (data_len && data) { vdata.resize(data_len); { PoolVector<uint8_t>::Write w = vdata.write(); copymem(w.ptr(), data, data_len); } } return vdata; } void AudioStreamOGGVorbis::set_loop(bool p_enable) { loop = p_enable; } bool AudioStreamOGGVorbis::has_loop() const { return loop; } void AudioStreamOGGVorbis::set_loop_offset(float p_seconds) { loop_offset = p_seconds; } float AudioStreamOGGVorbis::get_loop_offset() const { return loop_offset; } void AudioStreamOGGVorbis::_bind_methods() { ClassDB::bind_method(D_METHOD("set_data", "data"), &AudioStreamOGGVorbis::set_data); ClassDB::bind_method(D_METHOD("get_data"), &AudioStreamOGGVorbis::get_data); ClassDB::bind_method(D_METHOD("set_loop", "enable"), &AudioStreamOGGVorbis::set_loop); ClassDB::bind_method(D_METHOD("has_loop"), &AudioStreamOGGVorbis::has_loop); ClassDB::bind_method(D_METHOD("set_loop_offset", "seconds"), &AudioStreamOGGVorbis::set_loop_offset); ClassDB::bind_method(D_METHOD("get_loop_offset"), &AudioStreamOGGVorbis::get_loop_offset); ADD_PROPERTY(PropertyInfo(Variant::POOL_BYTE_ARRAY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_data", "get_data"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "loop", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_loop", "has_loop"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "loop_offset", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_loop_offset", "get_loop_offset"); } AudioStreamOGGVorbis::AudioStreamOGGVorbis() { data = NULL; length = 0; sample_rate = 1; channels = 1; loop_offset = 0; decode_mem_size = 0; loop = false; } <|endoftext|>
<commit_before>#include "catch.hpp" /* TEST_CASE("matrix_io/read_matrix | matrix_io/write_matrix") { REQUIRE(false); } TEST_CASE("matrix_io/read_dense_float64_bin | matrix_io/write_dense_float64_bin") { REQUIRE(false); } TEST_CASE("matrix_io/read_dense_float64_csv | matrix_io/write_dense_float64_csv") { REQUIRE(false); } TEST_CASE("matrix_io/read_sparse_float64_bin | matrix_io/write_sparse_float64_bin") { REQUIRE(false); } TEST_CASE("matrix_io/read_sparse_float64_mtx | matrix_io/write_sparse_float64_mtx") { REQUIRE(false); } TEST_CASE("matrix_io/read_sparse_binary_bin | matrix_io/write_sparse_binary_bin") { REQUIRE(false); } TEST_CASE("matrix_io/eigen::read_dense_float64_bin | matrix_io/eigen::write_dense_float64_bin") { REQUIRE(false); } TEST_CASE("matrix_io/eigen::read_dense_float64_csv | matrix_io/eigen::write_dense_float64_csv") { REQUIRE(false); } TEST_CASE("matrix_io/eigen::read_sparse_float64_bin | matrix_io/eigen::write_sparse_float64_bin") { REQUIRE(false); } TEST_CASE("matrix_io/eigen::read_sparse_float64_mtx | matrix_io/eigen::write_sparse_float64_mtx") { REQUIRE(false); } TEST_CASE("matrix_io/eigen::read_sparse_binary_bin | matrix_io/eigen::write_sparse_binary_bin") { REQUIRE(false); } */<commit_msg>Add tests to TestsMatrixIO.cpp<commit_after>#include "catch.hpp" #include "matrix_io.h" #include "MatrixUtils.h" #include <sstream> #include <Eigen/Core> #include <Eigen/SparseCore> using namespace smurff; TEST_CASE("matrix_io/read_matrix | matrix_io/write_matrix | .ddm") { REQUIRE(false); } TEST_CASE("matrix_io/read_matrix | matrix_io/write_matrix | .csv") { REQUIRE(false); } TEST_CASE("matrix_io/read_matrix | matrix_io/write_matrix | .sdm") { REQUIRE(false); } TEST_CASE("matrix_io/read_matrix | matrix_io/write_matrix | .mtx") { REQUIRE(false); } TEST_CASE("matrix_io/read_matrix | matrix_io/write_matrix | .sbm") { REQUIRE(false); } // === TEST_CASE("matrix_io/read_dense_float64_bin | matrix_io/write_dense_float64_bin") { std::uint64_t matrixConfigNRow = 3; std::uint64_t matrixConfigNCol = 3; std::vector<double> matrixConfigValues = { 1, 4, 7, 2, 5, 8, 3, 6, 9 }; MatrixConfig matrixConfig( matrixConfigNRow , matrixConfigNCol , std::move(matrixConfigValues) , NoiseConfig() ); std::stringstream matrixStream; matrix_io::write_dense_float64_bin(matrixStream, matrixConfig); MatrixConfig actualMatrixConfig = matrix_io::read_dense_float64_bin(matrixStream); Eigen::MatrixXd actualMatrix = dense_to_eigen(actualMatrixConfig); Eigen::MatrixXd expectedMatrix(3, 3); expectedMatrix << 1, 2, 3, 4, 5, 6, 7, 8, 9; REQUIRE(actualMatrix.isApprox(expectedMatrix)); } TEST_CASE("matrix_io/read_dense_float64_csv | matrix_io/write_dense_float64_csv") { std::uint64_t matrixConfigNRow = 3; std::uint64_t matrixConfigNCol = 3; std::vector<double> matrixConfigValues = { 1, 4, 7, 2, 5, 8, 3, 6, 9 }; MatrixConfig matrixConfig( matrixConfigNRow , matrixConfigNCol , std::move(matrixConfigValues) , NoiseConfig() ); std::stringstream matrixConfigStream; matrix_io::write_dense_float64_csv(matrixConfigStream, matrixConfig); MatrixConfig actualMatrixConfig = matrix_io::read_dense_float64_csv(matrixConfigStream); Eigen::MatrixXd actualMatrix = dense_to_eigen(actualMatrixConfig); Eigen::MatrixXd expectedMatrix(3, 3); expectedMatrix << 1, 2, 3, 4, 5, 6, 7, 8, 9; REQUIRE(actualMatrix.isApprox(expectedMatrix)); } TEST_CASE("matrix_io/read_sparse_float64_bin | matrix_io/write_sparse_float64_bin") { std::uint64_t matrixConfigNRow = 3; std::uint64_t matrixConfigNCol = 3; std::vector<std::uint32_t> matrixConfigRows = { 0, 0, 0, 2, 2, 2 }; std::vector<std::uint32_t> matrixConfigCols = { 0, 1, 2, 0, 1, 2 }; std::vector<double> matrixConfigValues = { 1, 2, 3, 7, 8, 9 }; MatrixConfig matrixConfig( matrixConfigNRow , matrixConfigNCol , std::move(matrixConfigRows) , std::move(matrixConfigCols) , std::move(matrixConfigValues) , NoiseConfig() ); std::stringstream matrixConfigStream; matrix_io::write_sparse_float64_bin(matrixConfigStream, matrixConfig); MatrixConfig actualMatrixConfig = matrix_io::read_sparse_float64_bin(matrixConfigStream); Eigen::SparseMatrix<double> actualMatrix = sparse_to_eigen(actualMatrixConfig); Eigen::SparseMatrix<double> expectedMatrix(3, 3); std::vector<Eigen::Triplet<double> > expectedMatrixTriplets; expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 0, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 1, 2)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 2, 3)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 0, 7)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 1, 8)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 2, 9)); expectedMatrix.setFromTriplets(expectedMatrixTriplets.begin(), expectedMatrixTriplets.end()); REQUIRE(actualMatrix.isApprox(expectedMatrix)); } TEST_CASE("matrix_io/read_sparse_float64_mtx | matrix_io/write_sparse_float64_mtx") { std::uint64_t matrixConfigNRow = 3; std::uint64_t matrixConfigNCol = 3; std::vector<std::uint32_t> matrixConfigRows = { 0, 0, 0, 2, 2, 2 }; std::vector<std::uint32_t> matrixConfigCols = { 0, 1, 2, 0, 1, 2 }; std::vector<double> matrixConfigValues = { 1, 2, 3, 7, 8, 9 }; MatrixConfig matrixConfig( matrixConfigNRow , matrixConfigNCol , std::move(matrixConfigRows) , std::move(matrixConfigCols) , std::move(matrixConfigValues) , NoiseConfig() ); std::stringstream matrixConfigStream; matrix_io::write_sparse_float64_mtx(matrixConfigStream, matrixConfig); MatrixConfig actualMatrixConfig = matrix_io::read_sparse_float64_mtx(matrixConfigStream); Eigen::SparseMatrix<double> actualMatrix = sparse_to_eigen(actualMatrixConfig); Eigen::SparseMatrix<double> expectedMatrix(3, 3); std::vector<Eigen::Triplet<double> > expectedMatrixTriplets; expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 0, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 1, 2)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 2, 3)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 0, 7)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 1, 8)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 2, 9)); expectedMatrix.setFromTriplets(expectedMatrixTriplets.begin(), expectedMatrixTriplets.end()); REQUIRE(actualMatrix.isApprox(expectedMatrix)); } TEST_CASE("matrix_io/read_sparse_binary_bin | matrix_io/write_sparse_binary_bin") { std::uint64_t matrixConfigNRow = 3; std::uint64_t matrixConfigNCol = 3; std::vector<std::uint32_t> matrixConfigRows = { 0, 0, 0, 2, 2, 2 }; std::vector<std::uint32_t> matrixConfigCols = { 0, 1, 2, 0, 1, 2 }; MatrixConfig matrixConfig( matrixConfigNRow , matrixConfigNCol , std::move(matrixConfigRows) , std::move(matrixConfigCols) , NoiseConfig() ); std::stringstream matrixConfigStream; matrix_io::write_sparse_binary_bin(matrixConfigStream, matrixConfig); MatrixConfig actualMatrixConfig = matrix_io::read_sparse_binary_bin(matrixConfigStream); Eigen::SparseMatrix<double> actualMatrix = sparse_to_eigen(actualMatrixConfig); Eigen::SparseMatrix<double> expectedMatrix(3, 3); std::vector<Eigen::Triplet<double> > expectedMatrixTriplets; expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 0, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 1, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 2, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 0, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 1, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 2, 1)); expectedMatrix.setFromTriplets(expectedMatrixTriplets.begin(), expectedMatrixTriplets.end()); REQUIRE(actualMatrix.isApprox(expectedMatrix)); } // === TEST_CASE("matrix_io/eigen::read_matrix(const std::string& filename, Eigen::VectorXd& V) | matrix_io/eigen::write_matrix(const std::string& filename, const Eigen::MatrixXd& X) | .ddm") { REQUIRE(false); } TEST_CASE("matrix_io/eigen::read_matrix(const std::string& filename, Eigen::VectorXd& V) | matrix_io/eigen::write_matrix(const std::string& filename, const Eigen::MatrixXd& X) | .csv") { REQUIRE(false); } TEST_CASE("matrix_io/eigen::read_matrix(const std::string& filename, Eigen::VectorXd& V) | matrix_io/eigen::write_matrix(const std::string& filename, const Eigen::MatrixXd& X) | .sdm") { REQUIRE(false); } TEST_CASE("matrix_io/eigen::read_matrix(const std::string& filename, Eigen::VectorXd& V) | matrix_io/eigen::write_matrix(const std::string& filename, const Eigen::MatrixXd& X) | .mtx") { REQUIRE(false); } TEST_CASE("matrix_io/eigen::read_matrix(const std::string& filename, Eigen::VectorXd& V) | matrix_io/eigen::write_matrix(const std::string& filename, const Eigen::MatrixXd& X) | .sbm") { REQUIRE(false); } // === TEST_CASE("matrix_io/eigen::read_matrix(const std::string& filename, Eigen::MatrixXd& X) | matrix_io/eigen::write_matrix(const std::string& filename, const Eigen::MatrixXd& X) | .ddm") { REQUIRE(false); } TEST_CASE("matrix_io/eigen::read_matrix(const std::string& filename, Eigen::MatrixXd& X) | matrix_io/eigen::write_matrix(const std::string& filename, const Eigen::MatrixXd& X) | .csv") { REQUIRE(false); } TEST_CASE("matrix_io/eigen::read_matrix(const std::string& filename, Eigen::MatrixXd& X) | matrix_io/eigen::write_matrix(const std::string& filename, const Eigen::MatrixXd& X) | .sdm") { REQUIRE(false); } TEST_CASE("matrix_io/eigen::read_matrix(const std::string& filename, Eigen::MatrixXd& X) | matrix_io/eigen::write_matrix(const std::string& filename, const Eigen::MatrixXd& X) | .mtx") { REQUIRE(false); } TEST_CASE("matrix_io/eigen::read_matrix(const std::string& filename, Eigen::MatrixXd& X) | matrix_io/eigen::write_matrix(const std::string& filename, const Eigen::MatrixXd& X) | .sbm") { REQUIRE(false); } // === TEST_CASE("matrix_io/eigen::read_matrix(const std::string& filename, Eigen::SparseMatrix<double>& X) | matrix_io/eigen::write_matrix(const std::string& filename, const Eigen::SparseMatrix<double>& X) | .ddm") { REQUIRE(false); } TEST_CASE("matrix_io/eigen::read_matrix(const std::string& filename, Eigen::SparseMatrix<double>& X) | matrix_io/eigen::write_matrix(const std::string& filename, const Eigen::SparseMatrix<double>& X) | .csv") { REQUIRE(false); } TEST_CASE("matrix_io/eigen::read_matrix(const std::string& filename, Eigen::SparseMatrix<double>& X) | matrix_io/eigen::write_matrix(const std::string& filename, const Eigen::SparseMatrix<double>& X) | .sdm") { REQUIRE(false); } TEST_CASE("matrix_io/eigen::read_matrix(const std::string& filename, Eigen::SparseMatrix<double>& X) | matrix_io/eigen::write_matrix(const std::string& filename, const Eigen::SparseMatrix<double>& X) | .mtx") { REQUIRE(false); } TEST_CASE("matrix_io/eigen::read_matrix(const std::string& filename, Eigen::SparseMatrix<double>& X) | matrix_io/eigen::write_matrix(const std::string& filename, const Eigen::SparseMatrix<double>& X) | .sbm") { REQUIRE(false); } // === TEST_CASE("matrix_io/eigen::read_dense_float64_bin | matrix_io/eigen::write_dense_float64_bin") { Eigen::MatrixXd expectedMatrix(3, 3); expectedMatrix << 1, 2, 3, 4, 5, 6, 7, 8, 9; std::stringstream matrixStream; matrix_io::eigen::write_dense_float64_bin(matrixStream, expectedMatrix); Eigen::MatrixXd actualMatrix(3, 3); matrix_io::eigen::read_dense_float64_bin(matrixStream, actualMatrix); REQUIRE(actualMatrix.isApprox(expectedMatrix)); } TEST_CASE("matrix_io/eigen::read_dense_float64_csv | matrix_io/eigen::write_dense_float64_csv") { Eigen::MatrixXd expectedMatrix(3, 3); expectedMatrix << 1, 2, 3, 4, 5, 6, 7, 8, 9; std::stringstream matrixStream; matrix_io::eigen::write_dense_float64_csv(matrixStream, expectedMatrix); Eigen::MatrixXd actualMatrix(3, 3); matrix_io::eigen::read_dense_float64_csv(matrixStream, actualMatrix); REQUIRE(actualMatrix.isApprox(expectedMatrix)); } TEST_CASE("matrix_io/eigen::read_sparse_float64_bin | matrix_io/eigen::write_sparse_float64_bin") { Eigen::SparseMatrix<double> expectedMatrix(3, 3); std::vector<Eigen::Triplet<double> > expectedMatrixTriplets; expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 0, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 1, 2)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 2, 3)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 0, 7)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 1, 8)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 2, 9)); expectedMatrix.setFromTriplets(expectedMatrixTriplets.begin(), expectedMatrixTriplets.end()); std::stringstream matrixStream; matrix_io::eigen::write_sparse_float64_bin(matrixStream, expectedMatrix); Eigen::SparseMatrix<double> actualMatrix(3, 3); matrix_io::eigen::read_sparse_float64_bin(matrixStream, actualMatrix); REQUIRE(actualMatrix.isApprox(expectedMatrix)); } TEST_CASE("matrix_io/eigen::read_sparse_float64_mtx | matrix_io/eigen::write_sparse_float64_mtx") { Eigen::SparseMatrix<double> expectedMatrix(3, 3); std::vector<Eigen::Triplet<double> > expectedMatrixTriplets; expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 0, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 1, 2)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 2, 3)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 0, 7)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 1, 8)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 2, 9)); expectedMatrix.setFromTriplets(expectedMatrixTriplets.begin(), expectedMatrixTriplets.end()); std::stringstream matrixStream; matrix_io::eigen::write_sparse_float64_mtx(matrixStream, expectedMatrix); Eigen::SparseMatrix<double> actualMatrix(3, 3); matrix_io::eigen::read_sparse_float64_mtx(matrixStream, actualMatrix); REQUIRE(actualMatrix.isApprox(expectedMatrix)); } TEST_CASE("matrix_io/eigen::read_sparse_binary_bin | matrix_io/eigen::write_sparse_binary_bin") { Eigen::SparseMatrix<double> expectedMatrix(3, 3); std::vector<Eigen::Triplet<double> > expectedMatrixTriplets; expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 0, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 1, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(0, 2, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 0, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 1, 1)); expectedMatrixTriplets.push_back(Eigen::Triplet<double>(2, 2, 1)); expectedMatrix.setFromTriplets(expectedMatrixTriplets.begin(), expectedMatrixTriplets.end()); std::stringstream matrixStream; matrix_io::eigen::write_sparse_binary_bin(matrixStream, expectedMatrix); Eigen::SparseMatrix<double> actualMatrix(3, 3); matrix_io::eigen::read_sparse_binary_bin(matrixStream, actualMatrix); REQUIRE(actualMatrix.isApprox(expectedMatrix)); }<|endoftext|>
<commit_before>// // TZX.cpp // Clock Signal // // Created by Thomas Harte on 16/07/2017. // Copyright © 2017 Thomas Harte. All rights reserved. // #include "TZX.hpp" using namespace Storage::Tape; namespace { const unsigned int StandardTZXClock = 3500000; } TZX::TZX(const char *file_name) : Storage::FileHolder(file_name), is_high_(false) { // Check for signature followed by a 0x1a char identifier[7]; char signature[] = "ZXTape!"; fread(identifier, 1, strlen(signature), file_); if(memcmp(identifier, signature, strlen(signature))) throw ErrorNotTZX; if(fgetc(file_) != 0x1a) throw ErrorNotTZX; // Get version number uint8_t major_version = (uint8_t)fgetc(file_); uint8_t minor_version = (uint8_t)fgetc(file_); // Reject if an incompatible version if(major_version != 1 || minor_version > 20) throw ErrorNotTZX; } void TZX::virtual_reset() { clear(); fseek(file_, 0x0a, SEEK_SET); } void TZX::get_next_pulses() { while(empty()) { uint8_t chunk_id = (uint8_t)fgetc(file_); if(feof(file_)) { set_is_at_end(true); return; } switch(chunk_id) { case 0x19: get_generalised_data_block(); break; case 0x30: { // Text description. Ripe for ignoring. int length = fgetc(file_); fseek(file_, length, SEEK_CUR); } break; default: // In TZX each chunk has a different way of stating or implying its length, // so there is no route past an unimplemented chunk. printf("!!Unknown %02x!!", chunk_id); set_is_at_end(true); return; } } } void TZX::get_generalised_data_block() { uint32_t block_length = fgetc32le(); uint16_t pause_after_block = fgetc16le(); uint32_t total_pilot_symbols = fgetc32le(); uint8_t maximum_pulses_per_pilot_symbol = (uint8_t)fgetc(file_); uint8_t symbols_in_pilot_table = (uint8_t)fgetc(file_); uint32_t total_data_symbols = fgetc32le(); uint8_t maximum_pulses_per_data_symbol = (uint8_t)fgetc(file_); uint8_t symbols_in_data_table = (uint8_t)fgetc(file_); get_generalised_segment(total_pilot_symbols, maximum_pulses_per_pilot_symbol, symbols_in_pilot_table, false); get_generalised_segment(total_data_symbols, maximum_pulses_per_data_symbol, symbols_in_data_table, true); emplace_back(Tape::Pulse::Zero, Storage::Time((unsigned int)pause_after_block, 1000u)); } void TZX::get_generalised_segment(uint32_t output_symbols, uint8_t max_pulses_per_symbol, uint8_t number_of_symbols, bool is_data) { if(!output_symbols) return; // Construct the symbol table. struct Symbol { uint8_t flags; std::vector<uint16_t> pulse_lengths; }; std::vector<Symbol> symbol_table; for(int c = 0; c < number_of_symbols; c++) { Symbol symbol; symbol.flags = (uint8_t)fgetc(file_); for(int ic = 0; ic < max_pulses_per_symbol; ic++) { symbol.pulse_lengths.push_back(fgetc16le()); } symbol_table.push_back(symbol); } // Hence produce the output. BitStream stream(file_, false); int base = 2; int bits = 1; while(base < number_of_symbols) { base <<= 1; bits++; } for(int c = 0; c < output_symbols; c++) { uint8_t symbol_value; int count; if(is_data) { symbol_value = stream.get_bits(bits); count = 1; } else { symbol_value = (uint8_t)fgetc(file_); count = fgetc16le(); } if(symbol_value > number_of_symbols) { continue; } Symbol &symbol = symbol_table[symbol_value]; while(count--) { // Mutate initial output level. switch(symbol.flags & 3) { case 0: break; case 1: is_high_ ^= true; break; case 2: is_high_ = true; break; case 3: is_high_ = false; break; } // Output waves. for(auto length : symbol.pulse_lengths) { if(!length) break; is_high_ ^= true; emplace_back(is_high_ ? Tape::Pulse::High : Tape::Pulse::Low, Storage::Time((unsigned int)length, StandardTZXClock)); } } } } <commit_msg>Added a safety seek.<commit_after>// // TZX.cpp // Clock Signal // // Created by Thomas Harte on 16/07/2017. // Copyright © 2017 Thomas Harte. All rights reserved. // #include "TZX.hpp" using namespace Storage::Tape; namespace { const unsigned int StandardTZXClock = 3500000; } TZX::TZX(const char *file_name) : Storage::FileHolder(file_name), is_high_(false) { // Check for signature followed by a 0x1a char identifier[7]; char signature[] = "ZXTape!"; fread(identifier, 1, strlen(signature), file_); if(memcmp(identifier, signature, strlen(signature))) throw ErrorNotTZX; if(fgetc(file_) != 0x1a) throw ErrorNotTZX; // Get version number uint8_t major_version = (uint8_t)fgetc(file_); uint8_t minor_version = (uint8_t)fgetc(file_); // Reject if an incompatible version if(major_version != 1 || minor_version > 20) throw ErrorNotTZX; } void TZX::virtual_reset() { clear(); fseek(file_, 0x0a, SEEK_SET); } void TZX::get_next_pulses() { while(empty()) { uint8_t chunk_id = (uint8_t)fgetc(file_); if(feof(file_)) { set_is_at_end(true); return; } switch(chunk_id) { case 0x19: get_generalised_data_block(); break; case 0x30: { // Text description. Ripe for ignoring. int length = fgetc(file_); fseek(file_, length, SEEK_CUR); } break; default: // In TZX each chunk has a different way of stating or implying its length, // so there is no route past an unimplemented chunk. printf("!!Unknown %02x!!", chunk_id); set_is_at_end(true); return; } } } void TZX::get_generalised_data_block() { uint32_t block_length = fgetc32le(); long endpoint = ftell(file_) + (long)block_length; uint16_t pause_after_block = fgetc16le(); uint32_t total_pilot_symbols = fgetc32le(); uint8_t maximum_pulses_per_pilot_symbol = (uint8_t)fgetc(file_); uint8_t symbols_in_pilot_table = (uint8_t)fgetc(file_); uint32_t total_data_symbols = fgetc32le(); uint8_t maximum_pulses_per_data_symbol = (uint8_t)fgetc(file_); uint8_t symbols_in_data_table = (uint8_t)fgetc(file_); get_generalised_segment(total_pilot_symbols, maximum_pulses_per_pilot_symbol, symbols_in_pilot_table, false); get_generalised_segment(total_data_symbols, maximum_pulses_per_data_symbol, symbols_in_data_table, true); emplace_back(Tape::Pulse::Zero, Storage::Time((unsigned int)pause_after_block, 1000u)); // This should be unnecessary, but intends to preserve sanity. fseek(file_, endpoint, SEEK_SET); } void TZX::get_generalised_segment(uint32_t output_symbols, uint8_t max_pulses_per_symbol, uint8_t number_of_symbols, bool is_data) { if(!output_symbols) return; // Construct the symbol table. struct Symbol { uint8_t flags; std::vector<uint16_t> pulse_lengths; }; std::vector<Symbol> symbol_table; for(int c = 0; c < number_of_symbols; c++) { Symbol symbol; symbol.flags = (uint8_t)fgetc(file_); for(int ic = 0; ic < max_pulses_per_symbol; ic++) { symbol.pulse_lengths.push_back(fgetc16le()); } symbol_table.push_back(symbol); } // Hence produce the output. BitStream stream(file_, false); int base = 2; int bits = 1; while(base < number_of_symbols) { base <<= 1; bits++; } for(int c = 0; c < output_symbols; c++) { uint8_t symbol_value; int count; if(is_data) { symbol_value = stream.get_bits(bits); count = 1; } else { symbol_value = (uint8_t)fgetc(file_); count = fgetc16le(); } if(symbol_value > number_of_symbols) { continue; } Symbol &symbol = symbol_table[symbol_value]; while(count--) { // Mutate initial output level. switch(symbol.flags & 3) { case 0: break; case 1: is_high_ ^= true; break; case 2: is_high_ = true; break; case 3: is_high_ = false; break; } // Output waves. for(auto length : symbol.pulse_lengths) { if(!length) break; is_high_ ^= true; emplace_back(is_high_ ? Tape::Pulse::High : Tape::Pulse::Low, Storage::Time((unsigned int)length, StandardTZXClock)); } } } } <|endoftext|>
<commit_before>/* Simple access class for I2C EEPROM chips like Microchip 24LC * Copyright (c) 2015 Robin Hourahane * * 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 "I2CEEBlockDevice.h" #include "rtos/ThisThread.h" using namespace mbed; #define I2CEE_TIMEOUT 10000 I2CEEBlockDevice::I2CEEBlockDevice( PinName sda, PinName scl, uint8_t addr, bd_size_t size, bd_size_t block, int freq) : _i2c_addr(addr), _size(size), _block(block) { _i2c = new (_i2c_buffer) I2C(sda, scl); _i2c->frequency(freq); } I2CEEBlockDevice::I2CEEBlockDevice( I2C *i2c_obj, uint8_t addr, bd_size_t size, bd_size_t block) : _i2c_addr(addr), _size(size), _block(block) { _i2c = i2c_obj; } I2CEEBlockDevice::~I2CEEBlockDevice() { if (_i2c == (I2C *)_i2c_buffer) { _i2c->~I2C(); } } int I2CEEBlockDevice::init() { return _sync(); } int I2CEEBlockDevice::deinit() { return 0; } int I2CEEBlockDevice::read(void *buffer, bd_addr_t addr, bd_size_t size) { // Check the address and size fit onto the chip. MBED_ASSERT(is_valid_read(addr, size)); _i2c->start(); if (!_i2c->write(_i2c_addr | 0) || !_i2c->write((char)(addr >> 8)) || !_i2c->write((char)(addr & 0xff))) { return BD_ERROR_DEVICE_ERROR; } _i2c->stop(); _sync(); if (0 != _i2c->read(_i2c_addr, static_cast<char *>(buffer), size)) { return BD_ERROR_DEVICE_ERROR; } return 0; } int I2CEEBlockDevice::program(const void *buffer, bd_addr_t addr, bd_size_t size) { // Check the addr and size fit onto the chip. MBED_ASSERT(is_valid_program(addr, size)); // While we have some more data to write. while (size > 0) { uint32_t off = addr % _block; uint32_t chunk = (off + size < _block) ? size : (_block - off); _i2c->start(); if (!_i2c->write(_i2c_addr | 0) || !_i2c->write((char)(addr >> 8)) || !_i2c->write((char)(addr & 0xff))) { return BD_ERROR_DEVICE_ERROR; } for (unsigned i = 0; i < chunk; i++) { _i2c->write(static_cast<const char *>(buffer)[i]); } _i2c->stop(); int err = _sync(); if (err) { return err; } addr += chunk; size -= chunk; buffer = static_cast<const char *>(buffer) + chunk; } return 0; } int I2CEEBlockDevice::erase(bd_addr_t addr, bd_size_t size) { // No erase needed return 0; } int I2CEEBlockDevice::_sync() { // The chip doesn't ACK while writing to the actual EEPROM // so loop trying to do a zero byte write until it is ACKed // by the chip. for (int i = 0; i < I2CEE_TIMEOUT; i++) { if (_i2c->write(_i2c_addr | 0, 0, 0) < 1) { return 0; } rtos::ThisThread::sleep_for(1); } return BD_ERROR_DEVICE_ERROR; } bd_size_t I2CEEBlockDevice::get_read_size() const { return 1; } bd_size_t I2CEEBlockDevice::get_program_size() const { return 1; } bd_size_t I2CEEBlockDevice::get_erase_size() const { return 1; } bd_size_t I2CEEBlockDevice::size() const { return _size; } const char *I2CEEBlockDevice::get_type() const { return "I2CEE"; } <commit_msg>Add error check for _sync() in I2CEEBlockDevice::read<commit_after>/* Simple access class for I2C EEPROM chips like Microchip 24LC * Copyright (c) 2015 Robin Hourahane * * 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 "I2CEEBlockDevice.h" #include "rtos/ThisThread.h" using namespace mbed; #define I2CEE_TIMEOUT 10000 I2CEEBlockDevice::I2CEEBlockDevice( PinName sda, PinName scl, uint8_t addr, bd_size_t size, bd_size_t block, int freq) : _i2c_addr(addr), _size(size), _block(block) { _i2c = new (_i2c_buffer) I2C(sda, scl); _i2c->frequency(freq); } I2CEEBlockDevice::I2CEEBlockDevice( I2C *i2c_obj, uint8_t addr, bd_size_t size, bd_size_t block) : _i2c_addr(addr), _size(size), _block(block) { _i2c = i2c_obj; } I2CEEBlockDevice::~I2CEEBlockDevice() { if (_i2c == (I2C *)_i2c_buffer) { _i2c->~I2C(); } } int I2CEEBlockDevice::init() { return _sync(); } int I2CEEBlockDevice::deinit() { return 0; } int I2CEEBlockDevice::read(void *buffer, bd_addr_t addr, bd_size_t size) { // Check the address and size fit onto the chip. MBED_ASSERT(is_valid_read(addr, size)); _i2c->start(); if (!_i2c->write(_i2c_addr | 0) || !_i2c->write((char)(addr >> 8)) || !_i2c->write((char)(addr & 0xff))) { return BD_ERROR_DEVICE_ERROR; } _i2c->stop(); auto err = _sync(); if (err) { return err; } if (0 != _i2c->read(_i2c_addr, static_cast<char *>(buffer), size)) { return BD_ERROR_DEVICE_ERROR; } return 0; } int I2CEEBlockDevice::program(const void *buffer, bd_addr_t addr, bd_size_t size) { // Check the addr and size fit onto the chip. MBED_ASSERT(is_valid_program(addr, size)); // While we have some more data to write. while (size > 0) { uint32_t off = addr % _block; uint32_t chunk = (off + size < _block) ? size : (_block - off); _i2c->start(); if (!_i2c->write(_i2c_addr | 0) || !_i2c->write((char)(addr >> 8)) || !_i2c->write((char)(addr & 0xff))) { return BD_ERROR_DEVICE_ERROR; } for (unsigned i = 0; i < chunk; i++) { _i2c->write(static_cast<const char *>(buffer)[i]); } _i2c->stop(); int err = _sync(); if (err) { return err; } addr += chunk; size -= chunk; buffer = static_cast<const char *>(buffer) + chunk; } return 0; } int I2CEEBlockDevice::erase(bd_addr_t addr, bd_size_t size) { // No erase needed return 0; } int I2CEEBlockDevice::_sync() { // The chip doesn't ACK while writing to the actual EEPROM // so loop trying to do a zero byte write until it is ACKed // by the chip. for (int i = 0; i < I2CEE_TIMEOUT; i++) { if (_i2c->write(_i2c_addr | 0, 0, 0) < 1) { return 0; } rtos::ThisThread::sleep_for(1); } return BD_ERROR_DEVICE_ERROR; } bd_size_t I2CEEBlockDevice::get_read_size() const { return 1; } bd_size_t I2CEEBlockDevice::get_program_size() const { return 1; } bd_size_t I2CEEBlockDevice::get_erase_size() const { return 1; } bd_size_t I2CEEBlockDevice::size() const { return _size; } const char *I2CEEBlockDevice::get_type() const { return "I2CEE"; } <|endoftext|>
<commit_before>/* mbed Microcontroller Library * Copyright (c) 2017 ARM Limited * * 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 "mbed_events.h" #include "mbed.h" #include "rtos.h" #include "greentea-client/test_env.h" #include "unity.h" #include "utest.h" #include <cstdlib> #include <cmath> using namespace utest::v1; // Test delay #ifndef TEST_EVENTS_TIMING_TIME #define TEST_EVENTS_TIMING_TIME 20000 #endif #ifndef TEST_EVENTS_TIMING_MEAN #define TEST_EVENTS_TIMING_MEAN 25 #endif #ifndef M_PI #define M_PI 3.14159265358979323846264338327950288 #endif // Random number generation to skew timing values float gauss(float mu, float sigma) { float x = (float)rand() / ((float)RAND_MAX+1); float y = (float)rand() / ((float)RAND_MAX+1); float x2pi = x*2.0*M_PI; float g2rad = sqrt(-2.0 * log(1.0-y)); float z = cos(x2pi) * g2rad; return mu + z*sigma; } float chisq(float sigma) { return pow(gauss(0, sqrt(sigma)), 2); } Timer timer; DigitalOut led(LED1); equeue_sema_t sema; // Timer timing test void timer_timing_test() { timer.reset(); timer.start(); int prev = timer.read_us(); while (prev < TEST_EVENTS_TIMING_TIME*1000) { int next = timer.read_us(); if (next < prev) { printf("backwards drift %d -> %d (%08x -> %08x)\r\n", prev, next, prev, next); } TEST_ASSERT(next >= prev); prev = next; } } // equeue tick timing test void tick_timing_test() { unsigned start = equeue_tick(); int prev = 0; while (prev < TEST_EVENTS_TIMING_TIME) { int next = equeue_tick() - start; if (next < prev) { printf("backwards drift %d -> %d (%08x -> %08x)\r\n", prev, next, prev, next); } TEST_ASSERT(next >= prev); prev = next; } } // equeue semaphore timing test void semaphore_timing_test() { srand(0); timer.reset(); timer.start(); int err = equeue_sema_create(&sema); TEST_ASSERT_EQUAL(0, err); while (timer.read_ms() < TEST_EVENTS_TIMING_TIME) { int delay = chisq(TEST_EVENTS_TIMING_MEAN); int start = timer.read_us(); equeue_sema_wait(&sema, delay); int taken = timer.read_us() - start; printf("delay %dms => error %dus\r\n", delay, abs(1000*delay - taken)); TEST_ASSERT_INT_WITHIN(5000, taken, delay * 1000); led = !led; } equeue_sema_destroy(&sema); } // Test setup utest::v1::status_t test_setup(const size_t number_of_cases) { GREENTEA_SETUP((number_of_cases+1)*TEST_EVENTS_TIMING_TIME/1000, "default_auto"); return verbose_test_setup_handler(number_of_cases); } const Case cases[] = { Case("Testing accuracy of timer", timer_timing_test), Case("Testing accuracy of equeue tick", tick_timing_test), Case("Testing accuracy of equeue semaphore", semaphore_timing_test), }; Specification specification(test_setup, cases); int main() { return !Harness::run(specification); } <commit_msg>tests-events-timing - print debug info only in case of failure.<commit_after>/* mbed Microcontroller Library * Copyright (c) 2017 ARM Limited * * 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 "mbed_events.h" #include "mbed.h" #include "rtos.h" #include "greentea-client/test_env.h" #include "unity.h" #include "utest.h" #include <cstdlib> #include <cmath> using namespace utest::v1; // Test delay #ifndef TEST_EVENTS_TIMING_TIME #define TEST_EVENTS_TIMING_TIME 20000 #endif #ifndef TEST_EVENTS_TIMING_MEAN #define TEST_EVENTS_TIMING_MEAN 25 #endif #ifndef M_PI #define M_PI 3.14159265358979323846264338327950288 #endif // Random number generation to skew timing values float gauss(float mu, float sigma) { float x = (float)rand() / ((float)RAND_MAX+1); float y = (float)rand() / ((float)RAND_MAX+1); float x2pi = x*2.0*M_PI; float g2rad = sqrt(-2.0 * log(1.0-y)); float z = cos(x2pi) * g2rad; return mu + z*sigma; } float chisq(float sigma) { return pow(gauss(0, sqrt(sigma)), 2); } Timer timer; DigitalOut led(LED1); equeue_sema_t sema; // Timer timing test void timer_timing_test() { timer.reset(); timer.start(); int prev = timer.read_us(); while (prev < TEST_EVENTS_TIMING_TIME*1000) { int next = timer.read_us(); if (next < prev) { printf("backwards drift %d -> %d (%08x -> %08x)\r\n", prev, next, prev, next); } TEST_ASSERT(next >= prev); prev = next; } } // equeue tick timing test void tick_timing_test() { unsigned start = equeue_tick(); int prev = 0; while (prev < TEST_EVENTS_TIMING_TIME) { int next = equeue_tick() - start; if (next < prev) { printf("backwards drift %d -> %d (%08x -> %08x)\r\n", prev, next, prev, next); } TEST_ASSERT(next >= prev); prev = next; } } // equeue semaphore timing test void semaphore_timing_test() { srand(0); timer.reset(); timer.start(); int err = equeue_sema_create(&sema); TEST_ASSERT_EQUAL(0, err); while (timer.read_ms() < TEST_EVENTS_TIMING_TIME) { int delay = chisq(TEST_EVENTS_TIMING_MEAN); int start = timer.read_us(); equeue_sema_wait(&sema, delay); int taken = timer.read_us() - start; if (taken < (delay * 1000 - 5000) || taken > (delay * 1000 + 5000)) { printf("delay %dms => error %dus\r\n", delay, abs(1000 * delay - taken)); } TEST_ASSERT_INT_WITHIN(5000, taken, delay * 1000); led = !led; } equeue_sema_destroy(&sema); } // Test setup utest::v1::status_t test_setup(const size_t number_of_cases) { GREENTEA_SETUP((number_of_cases+1)*TEST_EVENTS_TIMING_TIME/1000, "default_auto"); return verbose_test_setup_handler(number_of_cases); } const Case cases[] = { Case("Testing accuracy of timer", timer_timing_test), Case("Testing accuracy of equeue tick", tick_timing_test), Case("Testing accuracy of equeue semaphore", semaphore_timing_test), }; Specification specification(test_setup, cases); int main() { return !Harness::run(specification); } <|endoftext|>
<commit_before>/* * Copyright (c) 2018, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * 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. */ #if !defined(MBED_CONF_RTOS_PRESENT) #error [NOT_SUPPORTED] Test not supported. #else #define WIFI 2 #if !defined(MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE) || \ (MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE == WIFI && !defined(MBED_CONF_NSAPI_DEFAULT_WIFI_SSID)) #error [NOT_SUPPORTED] No network configuration found for this target. #else #include "mbed.h" #include "greentea-client/test_env.h" #include "unity.h" #include "utest.h" #include "nsapi_dns.h" #include "events/EventQueue.h" #include "dns_tests.h" using namespace utest::v1; namespace { NetworkInterface *net; } const char dns_test_hosts[MBED_CONF_APP_DNS_TEST_HOSTS_NUM][DNS_TEST_HOST_LEN] = MBED_CONF_APP_DNS_TEST_HOSTS; const char dns_test_hosts_second[MBED_CONF_APP_DNS_TEST_HOSTS_NUM][DNS_TEST_HOST_LEN] = MBED_CONF_APP_DNS_TEST_HOSTS_SECOND; // Callback used for asynchronous DNS result void hostbyname_cb(void *data, nsapi_error_t result, SocketAddress *address) { dns_application_data *app_data = static_cast<dns_application_data *>(data); app_data->result = result; if (address) { app_data->addr = *address; } app_data->semaphore->release(); app_data->value_set = true; } // General function to do asynchronous DNS host name resolution void do_asynchronous_gethostbyname(const char hosts[][DNS_TEST_HOST_LEN], unsigned int op_count, int *exp_ok, int *exp_no_mem, int *exp_dns_failure, int *exp_timeout) { // Verify that there is enough hosts in the host list TEST_ASSERT(op_count <= MBED_CONF_APP_DNS_TEST_HOSTS_NUM) // Reset counters (*exp_ok) = 0; (*exp_no_mem) = 0; (*exp_dns_failure) = 0; (*exp_timeout) = 0; // Create callback semaphore and data rtos::Semaphore semaphore; dns_application_data *data = new dns_application_data[op_count]; unsigned int count = 0; for (unsigned int i = 0; i < op_count; i++) { data[i].semaphore = &semaphore; nsapi_error_t err = net->gethostbyname_async(hosts[i], mbed::Callback<void(nsapi_error_t, SocketAddress *)>(hostbyname_cb, (void *) &data[i])); TEST_ASSERT(err >= 0 || err == NSAPI_ERROR_NO_MEMORY || err == NSAPI_ERROR_BUSY); if (err >= 0) { // Callback will be called count++; } else { // No memory to initiate DNS query, callback will not be called data[i].result = err; } } // Wait for callback(s) to complete for (unsigned int i = 0; i < count; i++) { semaphore.acquire(); } // Print result for (unsigned int i = 0; i < op_count; i++) { TEST_ASSERT(data[i].result == NSAPI_ERROR_OK || data[i].result == NSAPI_ERROR_NO_MEMORY || data[i].result == NSAPI_ERROR_BUSY || data[i].result == NSAPI_ERROR_DNS_FAILURE || data[i].result == NSAPI_ERROR_TIMEOUT); if (data[i].result == NSAPI_ERROR_OK) { (*exp_ok)++; printf("DNS: query \"%s\" => \"%s\"\n", hosts[i], data[i].addr.get_ip_address()); } else if (data[i].result == NSAPI_ERROR_DNS_FAILURE) { (*exp_dns_failure)++; printf("DNS: query \"%s\" => DNS failure\n", hosts[i]); } else if (data[i].result == NSAPI_ERROR_TIMEOUT) { (*exp_timeout)++; printf("DNS: query \"%s\" => timeout\n", hosts[i]); } else if (data[i].result == NSAPI_ERROR_NO_MEMORY) { (*exp_no_mem)++; printf("DNS: query \"%s\" => no memory\n", hosts[i]); } else if (data[i].result == NSAPI_ERROR_BUSY) { (*exp_no_mem)++; printf("DNS: query \"%s\" => busy\n", hosts[i]); } } delete[] data; } void do_gethostbyname(const char hosts[][DNS_TEST_HOST_LEN], unsigned int op_count, int *exp_ok, int *exp_no_mem, int *exp_dns_failure, int *exp_timeout) { // Verify that there is enough hosts in the host list TEST_ASSERT(op_count <= MBED_CONF_APP_DNS_TEST_HOSTS_NUM) // Reset counters (*exp_ok) = 0; (*exp_no_mem) = 0; (*exp_dns_failure) = 0; (*exp_timeout) = 0; for (unsigned int i = 0; i < op_count; i++) { SocketAddress address; nsapi_error_t err = net->gethostbyname(hosts[i], &address); if (err == NSAPI_ERROR_OK) { (*exp_ok)++; printf("DNS: query \"%s\" => \"%s\"\n", hosts[i], address.get_ip_address()); } else if (err == NSAPI_ERROR_DNS_FAILURE) { (*exp_dns_failure)++; printf("DNS: query \"%s\" => DNS failure\n", hosts[i]); } else if (err == NSAPI_ERROR_TIMEOUT) { (*exp_timeout)++; printf("DNS: query \"%s\" => timeout\n", hosts[i]); } else if (err == NSAPI_ERROR_NO_MEMORY) { (*exp_no_mem)++; printf("DNS: query \"%s\" => no memory\n", hosts[i]); } else if (err == NSAPI_ERROR_BUSY) { (*exp_no_mem)++; printf("DNS: query \"%s\" => busy\n", hosts[i]); } else { printf("DNS: query \"%s\" => %d, unexpected answer\n", hosts[i], err); TEST_ASSERT(err == NSAPI_ERROR_OK || err == NSAPI_ERROR_NO_MEMORY || err == NSAPI_ERROR_BUSY || err == NSAPI_ERROR_DNS_FAILURE || err == NSAPI_ERROR_TIMEOUT); } } } NetworkInterface *get_interface() { return net; } static void net_bringup() { nsapi_dns_reset(); MBED_ASSERT(MBED_CONF_APP_DNS_TEST_HOSTS_NUM >= MBED_CONF_NSAPI_DNS_CACHE_SIZE && MBED_CONF_APP_DNS_TEST_HOSTS_NUM >= MBED_CONF_APP_DNS_SIMULT_QUERIES + 1); net = NetworkInterface::get_default_instance(); nsapi_error_t err = net->connect(); TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, err); printf("MBED: IP address is '%s'\n", net->get_ip_address() ? net->get_ip_address() : "null"); } static void net_bringdown() { NetworkInterface::get_default_instance()->disconnect(); printf("MBED: ifdown\n"); } // Test setup utest::v1::status_t test_setup(const size_t number_of_cases) { GREENTEA_SETUP(dns_global::TESTS_TIMEOUT, "default_auto"); net_bringup(); return verbose_test_setup_handler(number_of_cases); } void greentea_teardown(const size_t passed, const size_t failed, const failure_t failure) { net_bringdown(); return greentea_test_teardown_handler(passed, failed, failure); } Case cases[] = { Case("ASYNCHRONOUS_DNS", ASYNCHRONOUS_DNS), Case("ASYNCHRONOUS_DNS_SIMULTANEOUS", ASYNCHRONOUS_DNS_SIMULTANEOUS), Case("ASYNCHRONOUS_DNS_SIMULTANEOUS_CACHE", ASYNCHRONOUS_DNS_SIMULTANEOUS_CACHE), Case("SYNCHRONOUS_DNS_CACHE", SYNCHRONOUS_DNS_CACHE), #ifndef MBED_CONF_CELLULAR_OFFLOAD_DNS_QUERIES Case("ASYNCHRONOUS_DNS_CACHE", ASYNCHRONOUS_DNS_CACHE), #endif #if !defined MBED_CONF_CELLULAR_OFFLOAD_DNS_QUERIES || MBED_CONF_CELLULAR_OFFLOAD_DNS_QUERIES > MBED_CONF_APP_DNS_TEST_HOSTS_NUM Case("ASYNCHRONOUS_DNS_NON_ASYNC_AND_ASYNC", ASYNCHRONOUS_DNS_NON_ASYNC_AND_ASYNC), #endif Case("ASYNCHRONOUS_DNS_CANCEL", ASYNCHRONOUS_DNS_CANCEL), #ifndef MBED_CONF_CELLULAR_OFFLOAD_DNS_QUERIES Case("ASYNCHRONOUS_DNS_EXTERNAL_EVENT_QUEUE", ASYNCHRONOUS_DNS_EXTERNAL_EVENT_QUEUE), Case("ASYNCHRONOUS_DNS_INVALID_HOST", ASYNCHRONOUS_DNS_INVALID_HOST), Case("ASYNCHRONOUS_DNS_TIMEOUTS", ASYNCHRONOUS_DNS_TIMEOUTS), #endif Case("ASYNCHRONOUS_DNS_SIMULTANEOUS_REPEAT", ASYNCHRONOUS_DNS_SIMULTANEOUS_REPEAT), Case("SYNCHRONOUS_DNS", SYNCHRONOUS_DNS), Case("SYNCHRONOUS_DNS_MULTIPLE", SYNCHRONOUS_DNS_MULTIPLE), Case("SYNCHRONOUS_DNS_INVALID", SYNCHRONOUS_DNS_INVALID), }; Specification specification(test_setup, cases, greentea_teardown, greentea_continue_handlers); int main() { return !Harness::run(specification); } #endif // !defined(MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE) || (MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE == WIFI && !defined(MBED_CONF_NSAPI_DEFAULT_WIFI_SSID)) #endif // !defined(MBED_CONF_RTOS_PRESENT) <commit_msg>Incorporated the review comments<commit_after>/* * Copyright (c) 2018, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * 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. */ #if !defined(MBED_CONF_RTOS_PRESENT) #error [NOT_SUPPORTED] dns test cases requires RTOS to run. #else #define WIFI 2 #if !defined(MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE) || \ (MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE == WIFI && !defined(MBED_CONF_NSAPI_DEFAULT_WIFI_SSID)) #error [NOT_SUPPORTED] No network configuration found for this target. #else #include "mbed.h" #include "greentea-client/test_env.h" #include "unity.h" #include "utest.h" #include "nsapi_dns.h" #include "events/EventQueue.h" #include "dns_tests.h" using namespace utest::v1; namespace { NetworkInterface *net; } const char dns_test_hosts[MBED_CONF_APP_DNS_TEST_HOSTS_NUM][DNS_TEST_HOST_LEN] = MBED_CONF_APP_DNS_TEST_HOSTS; const char dns_test_hosts_second[MBED_CONF_APP_DNS_TEST_HOSTS_NUM][DNS_TEST_HOST_LEN] = MBED_CONF_APP_DNS_TEST_HOSTS_SECOND; // Callback used for asynchronous DNS result void hostbyname_cb(void *data, nsapi_error_t result, SocketAddress *address) { dns_application_data *app_data = static_cast<dns_application_data *>(data); app_data->result = result; if (address) { app_data->addr = *address; } app_data->semaphore->release(); app_data->value_set = true; } // General function to do asynchronous DNS host name resolution void do_asynchronous_gethostbyname(const char hosts[][DNS_TEST_HOST_LEN], unsigned int op_count, int *exp_ok, int *exp_no_mem, int *exp_dns_failure, int *exp_timeout) { // Verify that there is enough hosts in the host list TEST_ASSERT(op_count <= MBED_CONF_APP_DNS_TEST_HOSTS_NUM) // Reset counters (*exp_ok) = 0; (*exp_no_mem) = 0; (*exp_dns_failure) = 0; (*exp_timeout) = 0; // Create callback semaphore and data rtos::Semaphore semaphore; dns_application_data *data = new dns_application_data[op_count]; unsigned int count = 0; for (unsigned int i = 0; i < op_count; i++) { data[i].semaphore = &semaphore; nsapi_error_t err = net->gethostbyname_async(hosts[i], mbed::Callback<void(nsapi_error_t, SocketAddress *)>(hostbyname_cb, (void *) &data[i])); TEST_ASSERT(err >= 0 || err == NSAPI_ERROR_NO_MEMORY || err == NSAPI_ERROR_BUSY); if (err >= 0) { // Callback will be called count++; } else { // No memory to initiate DNS query, callback will not be called data[i].result = err; } } // Wait for callback(s) to complete for (unsigned int i = 0; i < count; i++) { semaphore.acquire(); } // Print result for (unsigned int i = 0; i < op_count; i++) { TEST_ASSERT(data[i].result == NSAPI_ERROR_OK || data[i].result == NSAPI_ERROR_NO_MEMORY || data[i].result == NSAPI_ERROR_BUSY || data[i].result == NSAPI_ERROR_DNS_FAILURE || data[i].result == NSAPI_ERROR_TIMEOUT); if (data[i].result == NSAPI_ERROR_OK) { (*exp_ok)++; printf("DNS: query \"%s\" => \"%s\"\n", hosts[i], data[i].addr.get_ip_address()); } else if (data[i].result == NSAPI_ERROR_DNS_FAILURE) { (*exp_dns_failure)++; printf("DNS: query \"%s\" => DNS failure\n", hosts[i]); } else if (data[i].result == NSAPI_ERROR_TIMEOUT) { (*exp_timeout)++; printf("DNS: query \"%s\" => timeout\n", hosts[i]); } else if (data[i].result == NSAPI_ERROR_NO_MEMORY) { (*exp_no_mem)++; printf("DNS: query \"%s\" => no memory\n", hosts[i]); } else if (data[i].result == NSAPI_ERROR_BUSY) { (*exp_no_mem)++; printf("DNS: query \"%s\" => busy\n", hosts[i]); } } delete[] data; } void do_gethostbyname(const char hosts[][DNS_TEST_HOST_LEN], unsigned int op_count, int *exp_ok, int *exp_no_mem, int *exp_dns_failure, int *exp_timeout) { // Verify that there is enough hosts in the host list TEST_ASSERT(op_count <= MBED_CONF_APP_DNS_TEST_HOSTS_NUM) // Reset counters (*exp_ok) = 0; (*exp_no_mem) = 0; (*exp_dns_failure) = 0; (*exp_timeout) = 0; for (unsigned int i = 0; i < op_count; i++) { SocketAddress address; nsapi_error_t err = net->gethostbyname(hosts[i], &address); if (err == NSAPI_ERROR_OK) { (*exp_ok)++; printf("DNS: query \"%s\" => \"%s\"\n", hosts[i], address.get_ip_address()); } else if (err == NSAPI_ERROR_DNS_FAILURE) { (*exp_dns_failure)++; printf("DNS: query \"%s\" => DNS failure\n", hosts[i]); } else if (err == NSAPI_ERROR_TIMEOUT) { (*exp_timeout)++; printf("DNS: query \"%s\" => timeout\n", hosts[i]); } else if (err == NSAPI_ERROR_NO_MEMORY) { (*exp_no_mem)++; printf("DNS: query \"%s\" => no memory\n", hosts[i]); } else if (err == NSAPI_ERROR_BUSY) { (*exp_no_mem)++; printf("DNS: query \"%s\" => busy\n", hosts[i]); } else { printf("DNS: query \"%s\" => %d, unexpected answer\n", hosts[i], err); TEST_ASSERT(err == NSAPI_ERROR_OK || err == NSAPI_ERROR_NO_MEMORY || err == NSAPI_ERROR_BUSY || err == NSAPI_ERROR_DNS_FAILURE || err == NSAPI_ERROR_TIMEOUT); } } } NetworkInterface *get_interface() { return net; } static void net_bringup() { nsapi_dns_reset(); MBED_ASSERT(MBED_CONF_APP_DNS_TEST_HOSTS_NUM >= MBED_CONF_NSAPI_DNS_CACHE_SIZE && MBED_CONF_APP_DNS_TEST_HOSTS_NUM >= MBED_CONF_APP_DNS_SIMULT_QUERIES + 1); net = NetworkInterface::get_default_instance(); nsapi_error_t err = net->connect(); TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, err); printf("MBED: IP address is '%s'\n", net->get_ip_address() ? net->get_ip_address() : "null"); } static void net_bringdown() { NetworkInterface::get_default_instance()->disconnect(); printf("MBED: ifdown\n"); } // Test setup utest::v1::status_t test_setup(const size_t number_of_cases) { GREENTEA_SETUP(dns_global::TESTS_TIMEOUT, "default_auto"); net_bringup(); return verbose_test_setup_handler(number_of_cases); } void greentea_teardown(const size_t passed, const size_t failed, const failure_t failure) { net_bringdown(); return greentea_test_teardown_handler(passed, failed, failure); } Case cases[] = { Case("ASYNCHRONOUS_DNS", ASYNCHRONOUS_DNS), Case("ASYNCHRONOUS_DNS_SIMULTANEOUS", ASYNCHRONOUS_DNS_SIMULTANEOUS), Case("ASYNCHRONOUS_DNS_SIMULTANEOUS_CACHE", ASYNCHRONOUS_DNS_SIMULTANEOUS_CACHE), Case("SYNCHRONOUS_DNS_CACHE", SYNCHRONOUS_DNS_CACHE), #ifndef MBED_CONF_CELLULAR_OFFLOAD_DNS_QUERIES Case("ASYNCHRONOUS_DNS_CACHE", ASYNCHRONOUS_DNS_CACHE), #endif #if !defined MBED_CONF_CELLULAR_OFFLOAD_DNS_QUERIES || MBED_CONF_CELLULAR_OFFLOAD_DNS_QUERIES > MBED_CONF_APP_DNS_TEST_HOSTS_NUM Case("ASYNCHRONOUS_DNS_NON_ASYNC_AND_ASYNC", ASYNCHRONOUS_DNS_NON_ASYNC_AND_ASYNC), #endif Case("ASYNCHRONOUS_DNS_CANCEL", ASYNCHRONOUS_DNS_CANCEL), #ifndef MBED_CONF_CELLULAR_OFFLOAD_DNS_QUERIES Case("ASYNCHRONOUS_DNS_EXTERNAL_EVENT_QUEUE", ASYNCHRONOUS_DNS_EXTERNAL_EVENT_QUEUE), Case("ASYNCHRONOUS_DNS_INVALID_HOST", ASYNCHRONOUS_DNS_INVALID_HOST), Case("ASYNCHRONOUS_DNS_TIMEOUTS", ASYNCHRONOUS_DNS_TIMEOUTS), #endif Case("ASYNCHRONOUS_DNS_SIMULTANEOUS_REPEAT", ASYNCHRONOUS_DNS_SIMULTANEOUS_REPEAT), Case("SYNCHRONOUS_DNS", SYNCHRONOUS_DNS), Case("SYNCHRONOUS_DNS_MULTIPLE", SYNCHRONOUS_DNS_MULTIPLE), Case("SYNCHRONOUS_DNS_INVALID", SYNCHRONOUS_DNS_INVALID), }; Specification specification(test_setup, cases, greentea_teardown, greentea_continue_handlers); int main() { return !Harness::run(specification); } #endif // !defined(MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE) || (MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE == WIFI && !defined(MBED_CONF_NSAPI_DEFAULT_WIFI_SSID)) #endif // !defined(MBED_CONF_RTOS_PRESENT) <|endoftext|>
<commit_before>#include "ClientBackend.hpp" #include "ClientConnection.hpp" #include "CClientTcpTransport.hpp" #include "ClientSettings.hpp" #include "AccountStorage.hpp" #include "ClientConnection.hpp" #include "Client.hpp" #include "ClientRpcLayer.hpp" #include "DataStorage.hpp" #include "Operations/ClientAuthOperation.hpp" #include <QLoggingCategory> #include <QTimer> // Generated low-level layer includes #include "ClientRpcAccountLayer.hpp" #include "ClientRpcAuthLayer.hpp" #include "ClientRpcBotsLayer.hpp" #include "ClientRpcChannelsLayer.hpp" #include "ClientRpcContactsLayer.hpp" #include "ClientRpcHelpLayer.hpp" #include "ClientRpcLangpackLayer.hpp" #include "ClientRpcMessagesLayer.hpp" #include "ClientRpcPaymentsLayer.hpp" #include "ClientRpcPhoneLayer.hpp" #include "ClientRpcPhotosLayer.hpp" #include "ClientRpcStickersLayer.hpp" #include "ClientRpcUpdatesLayer.hpp" #include "ClientRpcUploadLayer.hpp" #include "ClientRpcUsersLayer.hpp" // End of generated low-level layer includes namespace Telegram { namespace Client { Backend::Backend(Client *parent) : QObject(parent), m_client(parent) { Backend *b = this; BaseRpcLayerExtension::SendMethod sendMethod = [b](const QByteArray &payload) mutable { return sendRpcRequest(b, payload); }; // Generated low-level layer initialization m_accountLayer = new AccountRpcLayer(this); m_accountLayer->setSendMethod(sendMethod); m_authLayer = new AuthRpcLayer(this); m_authLayer->setSendMethod(sendMethod); m_botsLayer = new BotsRpcLayer(this); m_botsLayer->setSendMethod(sendMethod); m_channelsLayer = new ChannelsRpcLayer(this); m_channelsLayer->setSendMethod(sendMethod); m_contactsLayer = new ContactsRpcLayer(this); m_contactsLayer->setSendMethod(sendMethod); m_helpLayer = new HelpRpcLayer(this); m_helpLayer->setSendMethod(sendMethod); m_langpackLayer = new LangpackRpcLayer(this); m_langpackLayer->setSendMethod(sendMethod); m_messagesLayer = new MessagesRpcLayer(this); m_messagesLayer->setSendMethod(sendMethod); m_paymentsLayer = new PaymentsRpcLayer(this); m_paymentsLayer->setSendMethod(sendMethod); m_phoneLayer = new PhoneRpcLayer(this); m_phoneLayer->setSendMethod(sendMethod); m_photosLayer = new PhotosRpcLayer(this); m_photosLayer->setSendMethod(sendMethod); m_stickersLayer = new StickersRpcLayer(this); m_stickersLayer->setSendMethod(sendMethod); m_updatesLayer = new UpdatesRpcLayer(this); m_updatesLayer->setSendMethod(sendMethod); m_uploadLayer = new UploadRpcLayer(this); m_uploadLayer->setSendMethod(sendMethod); m_usersLayer = new UsersRpcLayer(this); m_usersLayer->setSendMethod(sendMethod); // End of generated low-level layer initialization } PendingOperation *Backend::connectToServer() { if (m_mainConnection && m_mainConnection->status() != Connection::Status::Disconnected) { return PendingOperation::failOperation<PendingOperation>({ { QStringLiteral("text"), QStringLiteral("Connection is already in progress") } }); } if (m_mainConnection) { // TODO! } Connection *connection = nullptr; if (m_accountStorage->hasMinimalDataSet()) { connection = createConnection(m_accountStorage->dcInfo()); connection->setAuthKey(m_accountStorage->authKey()); } else { connection = createConnection(m_settings->serverConfiguration().first()); } connection->setServerRsaKey(m_settings->serverRsaKey()); setMainConnection(connection); return connection->connectToDc(); } AuthOperation *Backend::signIn() { if (!m_authOperation) { m_authOperation = new AuthOperation(this); } if (m_signedIn) { m_authOperation->setDelayedFinishedWithError({ { QStringLiteral("text"), QStringLiteral("Already signed in") } }); return m_authOperation; } if (!m_settings || !m_settings->isValid()) { qWarning() << "Invalid settings"; m_authOperation->setDelayedFinishedWithError({ { QStringLiteral("text"), QStringLiteral("Invalid settings") } }); return m_authOperation; } // Transport? /* 1 ) Establish TCP connection 2a) if there is no key in AccountStorage, use DH layer to get it 2b) use the key from AccountStorage -3) try to get self phone (postponed) -4) if error, report an error (postponed) 5a) if there is no phone number in AccountStorage, emit phoneRequired() 6b) use phone from AccountStorage 7) API Call authSendCode() 8) If error 401 SESSION_PASSWORD_NEEDED: 9) API Call accountGetPassword() -> TLAccountPassword(salt) 10) API Call authCheckPassword( Utils::sha256(salt + password + salt) ) 11) API Call authSignIn() Request phone number Request auth code Request password Done! */ // if (!m_private->m_appInfo || !m_private->m_appInfo->isValid()) { // qWarning() << "CTelegramCore::connectToServer(): App information is null or is not valid."; // return false; // } // m_private->m_dispatcher->setAppInformation(m_private->m_appInfo); // return m_private->m_dispatcher->connectToServer(); // connectToServer(), // checkPhoneNumber() m_authOperation->setBackend(this); if (!m_accountStorage->phoneNumber().isEmpty()) { m_authOperation->setPhoneNumber(m_accountStorage->phoneNumber()); } if (!mainConnection()) { m_authOperation->runAfter(connectToServer()); return m_authOperation; } m_authOperation->setRunMethod(&AuthOperation::requestAuthCode); m_authOperation->startLater(); connect(m_authOperation, &PendingOperation::succeeded, [this]() { m_signedIn = true; emit m_client->signedInChanged(m_signedIn); }); return m_authOperation; } Connection *Backend::createConnection(const DcOption &dcOption) { Connection *connection = new Connection(this); connection->setDcOption(dcOption); connection->rpcLayer()->setAppInformation(m_appInformation); TcpTransport *transport = new TcpTransport(connection); switch (m_settings->preferedSessionType()) { case Settings::SessionType::Default: break; case Settings::SessionType::Abridged: transport->setPreferedSessionType(TcpTransport::Abridged); break; case Settings::SessionType::Obfuscated: transport->setPreferedSessionType(TcpTransport::Obfuscated); break; } connection->setTransport(transport); return connection; } Connection *Backend::mainConnection() { return m_mainConnection; } void Backend::setMainConnection(Connection *connection) { m_mainConnection = connection; connect(m_mainConnection, &BaseConnection::statusChanged, [this](Connection::Status status) { switch (status) { case Connection::Status::Authenticated: case Connection::Status::Signed: m_accountStorage->setAuthKey(m_mainConnection->authKey()); m_accountStorage->setAuthId(m_mainConnection->authId()); break; default: break; } }); } PendingRpcOperation *Backend::sendRpcRequest(Backend *backend, const QByteArray &payload) { return backend->mainConnection()->rpcLayer()->sendEncryptedPackage(payload); } } // Client namespace } // Telegram namespace <commit_msg>ClientBackend: Check the conn status on setMainConnection()<commit_after>#include "ClientBackend.hpp" #include "ClientConnection.hpp" #include "CClientTcpTransport.hpp" #include "ClientSettings.hpp" #include "AccountStorage.hpp" #include "ClientConnection.hpp" #include "Client.hpp" #include "ClientRpcLayer.hpp" #include "DataStorage.hpp" #include "Operations/ClientAuthOperation.hpp" #include <QLoggingCategory> #include <QTimer> // Generated low-level layer includes #include "ClientRpcAccountLayer.hpp" #include "ClientRpcAuthLayer.hpp" #include "ClientRpcBotsLayer.hpp" #include "ClientRpcChannelsLayer.hpp" #include "ClientRpcContactsLayer.hpp" #include "ClientRpcHelpLayer.hpp" #include "ClientRpcLangpackLayer.hpp" #include "ClientRpcMessagesLayer.hpp" #include "ClientRpcPaymentsLayer.hpp" #include "ClientRpcPhoneLayer.hpp" #include "ClientRpcPhotosLayer.hpp" #include "ClientRpcStickersLayer.hpp" #include "ClientRpcUpdatesLayer.hpp" #include "ClientRpcUploadLayer.hpp" #include "ClientRpcUsersLayer.hpp" // End of generated low-level layer includes namespace Telegram { namespace Client { Backend::Backend(Client *parent) : QObject(parent), m_client(parent) { Backend *b = this; BaseRpcLayerExtension::SendMethod sendMethod = [b](const QByteArray &payload) mutable { return sendRpcRequest(b, payload); }; // Generated low-level layer initialization m_accountLayer = new AccountRpcLayer(this); m_accountLayer->setSendMethod(sendMethod); m_authLayer = new AuthRpcLayer(this); m_authLayer->setSendMethod(sendMethod); m_botsLayer = new BotsRpcLayer(this); m_botsLayer->setSendMethod(sendMethod); m_channelsLayer = new ChannelsRpcLayer(this); m_channelsLayer->setSendMethod(sendMethod); m_contactsLayer = new ContactsRpcLayer(this); m_contactsLayer->setSendMethod(sendMethod); m_helpLayer = new HelpRpcLayer(this); m_helpLayer->setSendMethod(sendMethod); m_langpackLayer = new LangpackRpcLayer(this); m_langpackLayer->setSendMethod(sendMethod); m_messagesLayer = new MessagesRpcLayer(this); m_messagesLayer->setSendMethod(sendMethod); m_paymentsLayer = new PaymentsRpcLayer(this); m_paymentsLayer->setSendMethod(sendMethod); m_phoneLayer = new PhoneRpcLayer(this); m_phoneLayer->setSendMethod(sendMethod); m_photosLayer = new PhotosRpcLayer(this); m_photosLayer->setSendMethod(sendMethod); m_stickersLayer = new StickersRpcLayer(this); m_stickersLayer->setSendMethod(sendMethod); m_updatesLayer = new UpdatesRpcLayer(this); m_updatesLayer->setSendMethod(sendMethod); m_uploadLayer = new UploadRpcLayer(this); m_uploadLayer->setSendMethod(sendMethod); m_usersLayer = new UsersRpcLayer(this); m_usersLayer->setSendMethod(sendMethod); // End of generated low-level layer initialization } PendingOperation *Backend::connectToServer() { if (m_mainConnection && m_mainConnection->status() != Connection::Status::Disconnected) { return PendingOperation::failOperation<PendingOperation>({ { QStringLiteral("text"), QStringLiteral("Connection is already in progress") } }); } if (m_mainConnection) { // TODO! } Connection *connection = nullptr; if (m_accountStorage->hasMinimalDataSet()) { connection = createConnection(m_accountStorage->dcInfo()); connection->setAuthKey(m_accountStorage->authKey()); } else { connection = createConnection(m_settings->serverConfiguration().first()); } connection->setServerRsaKey(m_settings->serverRsaKey()); setMainConnection(connection); return connection->connectToDc(); } AuthOperation *Backend::signIn() { if (!m_authOperation) { m_authOperation = new AuthOperation(this); } if (m_signedIn) { m_authOperation->setDelayedFinishedWithError({ { QStringLiteral("text"), QStringLiteral("Already signed in") } }); return m_authOperation; } if (!m_settings || !m_settings->isValid()) { qWarning() << "Invalid settings"; m_authOperation->setDelayedFinishedWithError({ { QStringLiteral("text"), QStringLiteral("Invalid settings") } }); return m_authOperation; } // Transport? /* 1 ) Establish TCP connection 2a) if there is no key in AccountStorage, use DH layer to get it 2b) use the key from AccountStorage -3) try to get self phone (postponed) -4) if error, report an error (postponed) 5a) if there is no phone number in AccountStorage, emit phoneRequired() 6b) use phone from AccountStorage 7) API Call authSendCode() 8) If error 401 SESSION_PASSWORD_NEEDED: 9) API Call accountGetPassword() -> TLAccountPassword(salt) 10) API Call authCheckPassword( Utils::sha256(salt + password + salt) ) 11) API Call authSignIn() Request phone number Request auth code Request password Done! */ // if (!m_private->m_appInfo || !m_private->m_appInfo->isValid()) { // qWarning() << "CTelegramCore::connectToServer(): App information is null or is not valid."; // return false; // } // m_private->m_dispatcher->setAppInformation(m_private->m_appInfo); // return m_private->m_dispatcher->connectToServer(); // connectToServer(), // checkPhoneNumber() m_authOperation->setBackend(this); if (!m_accountStorage->phoneNumber().isEmpty()) { m_authOperation->setPhoneNumber(m_accountStorage->phoneNumber()); } if (!mainConnection()) { m_authOperation->runAfter(connectToServer()); return m_authOperation; } m_authOperation->setRunMethod(&AuthOperation::requestAuthCode); m_authOperation->startLater(); connect(m_authOperation, &PendingOperation::succeeded, [this]() { m_signedIn = true; emit m_client->signedInChanged(m_signedIn); }); return m_authOperation; } Connection *Backend::createConnection(const DcOption &dcOption) { Connection *connection = new Connection(this); connection->setDcOption(dcOption); connection->rpcLayer()->setAppInformation(m_appInformation); TcpTransport *transport = new TcpTransport(connection); switch (m_settings->preferedSessionType()) { case Settings::SessionType::Default: break; case Settings::SessionType::Abridged: transport->setPreferedSessionType(TcpTransport::Abridged); break; case Settings::SessionType::Obfuscated: transport->setPreferedSessionType(TcpTransport::Obfuscated); break; } connection->setTransport(transport); return connection; } Connection *Backend::mainConnection() { return m_mainConnection; } void Backend::setMainConnection(Connection *connection) { m_mainConnection = connection; auto updateStatusLambda = [this](Connection::Status status) { switch (status) { case Connection::Status::Authenticated: case Connection::Status::Signed: m_accountStorage->setAuthKey(m_mainConnection->authKey()); m_accountStorage->setAuthId(m_mainConnection->authId()); break; default: break; } }; connect(m_mainConnection, &BaseConnection::statusChanged, updateStatusLambda); updateStatusLambda(m_mainConnection->status()); } PendingRpcOperation *Backend::sendRpcRequest(Backend *backend, const QByteArray &payload) { return backend->mainConnection()->rpcLayer()->sendEncryptedPackage(payload); } } // Client namespace } // Telegram namespace <|endoftext|>
<commit_before>#include <string.h> #include <fstream> #include <iostream> #include <string> #include <complex> #include <math.h> #include <set> #include <vector> #include <map> #include <queue> #include <stdio.h> #include <stack> #include <algorithm> #include <list> #include <ctime> #include <memory.h> #include <ctime> #include <assert.h> #define pi 3.14159 #define mod 1000000007 using namespace std; long long int a[500000]; int main() { int t; cin>>t; if(t%2==1) { cout<<"NO"; } else { if(t == 2) { cout<<"NO"; } else { cout<<"YES"; } } return 0; } <commit_msg>Delete Watermelon.cpp<commit_after><|endoftext|>
<commit_before>//-------------------------------------------------------------------------------------------------- /** * @file moduleBuildScript.cpp * * Implementation of the build script generator for pre-built kernel modules. * * <hr> * * Copyright (C) Sierra Wireless Inc. */ //-------------------------------------------------------------------------------------------------- #include "mkTools.h" #include "buildScriptCommon.h" #include "moduleBuildScript.h" namespace ninja { //-------------------------------------------------------------------------------------------------- /** * Generate comment header for a build script. */ //-------------------------------------------------------------------------------------------------- void ModuleBuildScriptGenerator_t::GenerateCommentHeader ( model::Module_t* modulePtr ) //-------------------------------------------------------------------------------------------------- { script << "# Build script for module '" << modulePtr->name << "'\n" "\n" "# == Auto-generated file. Do not edit. ==\n" "\n"; } //-------------------------------------------------------------------------------------------------- /** * Print to a given build script the build statements related to a given module. * If it's a pre-built module, just copy it. Otherwise generate a module Makefile and build it. **/ //-------------------------------------------------------------------------------------------------- void ModuleBuildScriptGenerator_t::GenerateBuildStatements ( model::Module_t* modulePtr ) //-------------------------------------------------------------------------------------------------- { if (modulePtr->moduleBuildType == model::Module_t::Sources) { // In case of Sources, koFiles map will consist of only one element. // Hence, use the first element in koFiles for generating build statement. auto const it = modulePtr->koFiles.begin(); if (it != modulePtr->koFiles.end()) { script << "build " << "$builddir/" << it->second->path << ": "; // No pre-built module: generate and invoke a Makefile GenerateMakefile(modulePtr); script << "MakeKernelModule " << "$builddir/" << path::GetContainingDir(it->second->path) << "\n"; } else { throw mk::Exception_t( mk::format(LE_I18N("error: %s container of kernel object file is empty."), modulePtr->defFilePtr->path)); } } else if (modulePtr->moduleBuildType == model::Module_t::Prebuilt) { for (auto const& it: modulePtr->koFiles) { script << "build " << "$builddir/" << it.second->path << ": "; // Pre-built module: add build statement for bundling the .ko file script << "BundleFile " << it.first << "\n" << " modeFlags = u+rw-x,g+r-wx,o+r-wx\n"; } } else { throw mk::Exception_t( mk::format(LE_I18N("error: %s must have either 'sources' or 'preBuilt' section."), modulePtr->defFilePtr->path)); } script << "\n"; // Generate build statament GenerateModuleBundleBuildStatement(modulePtr, buildParams.outputDir); script << "\n"; if ((!modulePtr->installScript.empty()) && (!(modulePtr->removeScript.empty()))) { std::string stageInstallPath; stageInstallPath +="staging/modules/files/"; stageInstallPath += modulePtr->name; stageInstallPath += "/scripts/"; stageInstallPath += path::GetLastNode(modulePtr->installScript); script << "build " << "$builddir/" << stageInstallPath << ": "; // Build statement for bundling the module install script script << "BundleFile " << modulePtr->installScript << "\n" << " modeFlags = u+rwx,g+rx-w,o+rx-w\n"; std::string stageRemovePath; stageRemovePath +="staging/modules/files/"; stageRemovePath += modulePtr->name; stageRemovePath += "/scripts/"; stageRemovePath += path::GetLastNode(modulePtr->removeScript); script << "build " << "$builddir/" << stageRemovePath << ": "; // Build statement for bundling the module remove file script << "BundleFile " << modulePtr->removeScript << "\n" << " modeFlags = u+rwx,g+rx-w,o+rx-w\n"; } } //-------------------------------------------------------------------------------------------------- /** * Write to a given build script the build statements for the build script itself. **/ //-------------------------------------------------------------------------------------------------- void ModuleBuildScriptGenerator_t::GenerateNinjaScriptBuildStatement ( model::Module_t* modulePtr ) //-------------------------------------------------------------------------------------------------- { // The build.ninja depends on module .mdef and .ko files // Create a set of dependencies. std::set<std::string> dependencies; for (auto const& it : modulePtr->koFiles) { dependencies.insert(it.first); } dependencies.insert(modulePtr->defFilePtr->path); // It also depends on changes to the mk tools. dependencies.insert(path::Combine(envVars::Get("LEGATO_ROOT"), "build/tools/mk")); baseGeneratorPtr->GenerateNinjaScriptBuildStatement(dependencies); } //-------------------------------------------------------------------------------------------------- /** * Generate a Makefile for a kernel module. **/ //-------------------------------------------------------------------------------------------------- void ModuleBuildScriptGenerator_t::GenerateMakefile ( model::Module_t* modulePtr ) //-------------------------------------------------------------------------------------------------- { std::string buildPath = path::MakeAbsolute(buildParams.workingDir + "/modules/" + modulePtr->name); const std::string& compilerPath = buildParams.cCompilerPath; std::ofstream makefile; OpenFile(makefile, buildPath + "/Makefile", buildParams.beVerbose); // Specify kernel module name and list all object files to link makefile << "obj-m += " << modulePtr->name << ".o\n"; // Don't list object files in case of a single source file with module name if (modulePtr->cObjectFiles.size() > 1 || modulePtr->cObjectFiles.front()->path != modulePtr->name + ".o") { for (auto obj : modulePtr->cObjectFiles) { makefile << modulePtr->name << "-objs += " << obj->path << "\n"; } } makefile << "\n"; // Specify directory where the sources are located makefile << "src = " << modulePtr->dir << "\n\n"; // Add compiler and linker options for (auto const &obj : modulePtr->cFlags) { makefile << "ccflags-y += " << obj << "\n"; } for (auto const &obj : modulePtr->ldFlags) { makefile << "ldflags-y += " << obj << "\n"; } makefile << "\n"; makefile << "KBUILD := " << modulePtr->kernelDir << "\n"; if (buildParams.target != "localhost") { // Specify the CROSS_COMPILE and ARCH environment variables // Note: compiler path may contain dashes in directory names std::string compiler = path::GetLastNode(compilerPath); std::string cross = path::GetContainingDir(compilerPath) + "/" + compiler.substr(0, compiler.rfind('-') + 1); std::string arch = compiler.substr(0, compiler.find('-')); if ((arch == "i586") || (arch == "i686")) { arch = "x86"; } makefile << "export CROSS_COMPILE := " << cross << "\n"; makefile << "export ARCH := " << arch << "\n"; } makefile << "\n"; // Specify build rules makefile << "all:\n"; makefile << "\tmake -C $(KBUILD) M=" + buildPath + " modules\n"; makefile << "\n"; makefile << "clean:\n"; makefile << "\t make -C $(KBUILD) M=" + buildPath + " clean\n"; CloseFile(makefile); } //-------------------------------------------------------------------------------------------------- /** * Write to a given build script the build statement for bundling a single file into * the staging area. **/ //-------------------------------------------------------------------------------------------------- void ModuleBuildScriptGenerator_t::GenerateFileBundleBuildStatement ( model::FileSystemObjectSet_t& bundledFiles, ///< Set to fill with bundled file paths. model::Module_t* modulePtr, ///< Module to bundle the file into. const model::FileSystemObject_t* fileSystemObjPtr ///< File bundling info. ) //-------------------------------------------------------------------------------------------------- { // The file will be added to the module's staging area. path::Path_t destPath = "$builddir/staging/modules/files/"; destPath += modulePtr->name; destPath += fileSystemObjPtr->destPath; baseGeneratorPtr->GenerateFileBundleBuildStatement(model::FileSystemObject_t( fileSystemObjPtr->srcPath, destPath.str, fileSystemObjPtr->permissions, fileSystemObjPtr), bundledFiles); } //-------------------------------------------------------------------------------------------------- /** * Write to a given build script the build statements for bundling files from a directory into * the staging area. **/ //-------------------------------------------------------------------------------------------------- void ModuleBuildScriptGenerator_t::GenerateDirBundleBuildStatements ( model::FileSystemObjectSet_t& bundledFiles, ///< Set to fill with bundled file paths. model::Module_t* modulePtr, ///< Module to bundle the directory into. const model::FileSystemObject_t* fileSystemObjPtr ///< Directory bundling info. ) //-------------------------------------------------------------------------------------------------- { // The files will be added to the modules's staging area. path::Path_t destPath = "$builddir/staging/modules/files/"; destPath += modulePtr->name; destPath += fileSystemObjPtr->destPath; baseGeneratorPtr->GenerateDirBundleBuildStatements(model::FileSystemObject_t( fileSystemObjPtr->srcPath, destPath.str, fileSystemObjPtr->permissions, fileSystemObjPtr), bundledFiles); } //-------------------------------------------------------------------------------------------------- /** * Write to a given build script the build statements for bundling a given module's files into the * module's staging area. * **/ //-------------------------------------------------------------------------------------------------- void ModuleBuildScriptGenerator_t::GenerateStagingBundleBuildStatements ( model::Module_t* modulePtr ) //-------------------------------------------------------------------------------------------------- { auto& allBundledFiles = modulePtr->getTargetInfo<target::FileSystemInfo_t>()->allBundledFiles; for (auto fileSystemObjPtr : modulePtr->bundledFiles) { GenerateFileBundleBuildStatement(allBundledFiles, modulePtr, fileSystemObjPtr.get()); } for (auto fileSystemObjPtr : modulePtr->bundledDirs) { GenerateDirBundleBuildStatements(allBundledFiles, modulePtr, fileSystemObjPtr.get()); } } //-------------------------------------------------------------------------------------------------- /** * Write to a given script the build statements for packing up everything into a module bundle. * **/ //-------------------------------------------------------------------------------------------------- void ModuleBuildScriptGenerator_t::GenerateModuleBundleBuildStatement ( model::Module_t* modulePtr, const std::string& outputDir ///< Path to the directory into which built module will be added. ) //-------------------------------------------------------------------------------------------------- { // Give this a FS target info modulePtr->setTargetInfo(new target::FileSystemInfo_t()); // Generate build statements for bundling files into the staging area. GenerateStagingBundleBuildStatements(modulePtr); } //-------------------------------------------------------------------------------------------------- /** * Generate a build script for a kernel module. */ //-------------------------------------------------------------------------------------------------- void ModuleBuildScriptGenerator_t::Generate ( model::Module_t* modulePtr ) { // Start the script with a comment, the file-level variable definitions, and // a set of generic rules. GenerateCommentHeader(modulePtr); script << "builddir = " << path::MakeAbsolute(buildParams.workingDir) << "\n\n"; script << "target = " << buildParams.target << "\n\n"; baseGeneratorPtr->GenerateIfgenFlagsDef(); baseGeneratorPtr->GenerateBuildRules(); if (!buildParams.codeGenOnly) { // Add build statements for the module. GenerateBuildStatements(modulePtr); } // Add a build statement for the build.ninja file itself. GenerateNinjaScriptBuildStatement(modulePtr); } //-------------------------------------------------------------------------------------------------- /** * Generate a build script for a pre-built kernel module. **/ //-------------------------------------------------------------------------------------------------- void Generate ( model::Module_t* modulePtr, const mk::BuildParams_t& buildParams ) //-------------------------------------------------------------------------------------------------- { std::string filePath = path::Minimize(buildParams.workingDir + "/build.ninja"); ModuleBuildScriptGenerator_t scriptGenerator(filePath, buildParams); scriptGenerator.Generate(modulePtr); } } // namespace ninja <commit_msg>Consider external kernel module build dependencies<commit_after>//-------------------------------------------------------------------------------------------------- /** * @file moduleBuildScript.cpp * * Implementation of the build script generator for pre-built kernel modules. * * <hr> * * Copyright (C) Sierra Wireless Inc. */ //-------------------------------------------------------------------------------------------------- #include "mkTools.h" #include "buildScriptCommon.h" #include "moduleBuildScript.h" namespace ninja { //-------------------------------------------------------------------------------------------------- /** * Generate comment header for a build script. */ //-------------------------------------------------------------------------------------------------- void ModuleBuildScriptGenerator_t::GenerateCommentHeader ( model::Module_t* modulePtr ) //-------------------------------------------------------------------------------------------------- { script << "# Build script for module '" << modulePtr->name << "'\n" "\n" "# == Auto-generated file. Do not edit. ==\n" "\n"; } //-------------------------------------------------------------------------------------------------- /** * Print to a given build script the build statements related to a given module. * If it's a pre-built module, just copy it. Otherwise generate a module Makefile and build it. **/ //-------------------------------------------------------------------------------------------------- void ModuleBuildScriptGenerator_t::GenerateBuildStatements ( model::Module_t* modulePtr ) //-------------------------------------------------------------------------------------------------- { if (modulePtr->moduleBuildType == model::Module_t::Sources) { // In case of Sources, koFiles map will consist of only one element. // Hence, use the first element in koFiles for generating build statement. auto const it = modulePtr->koFiles.begin(); if (it != modulePtr->koFiles.end()) { script << "build " << "$builddir/" << it->second->path << ": "; // No pre-built module: generate and invoke a Makefile GenerateMakefile(modulePtr); script << "MakeKernelModule " << "$builddir/" << path::GetContainingDir(it->second->path); if (!modulePtr->requiredModules.empty()) { // Include order-only build dependencies to make sure the dependency module is // built first than the module that depends on it. Expressed with sytax // "|| dep1 dep2" on the end of a build line. script << " || "; for (auto const& reqMod : modulePtr->requiredModules) { model::Module_t* reqModPtr = model::Module_t::GetModule(reqMod.first); if (reqModPtr == NULL) { throw mk::Exception_t( mk::format( LE_I18N("Internal Error: Module object not found for '%s'."), reqMod.first)); } for (auto const& reqMod : reqModPtr->koFiles) { script << "$builddir/" << reqMod.second->path << " "; } } } script << "\n"; } else { throw mk::Exception_t( mk::format(LE_I18N("error: %s container of kernel object file is empty."), modulePtr->defFilePtr->path)); } } else if (modulePtr->moduleBuildType == model::Module_t::Prebuilt) { for (auto const& it: modulePtr->koFiles) { script << "build " << "$builddir/" << it.second->path << ": "; // Pre-built module: add build statement for bundling the .ko file script << "BundleFile " << it.first << "\n" << " modeFlags = u+rw-x,g+r-wx,o+r-wx\n"; } } else { throw mk::Exception_t( mk::format(LE_I18N("error: %s must have either 'sources' or 'preBuilt' section."), modulePtr->defFilePtr->path)); } script << "\n"; // Generate build statament GenerateModuleBundleBuildStatement(modulePtr, buildParams.outputDir); script << "\n"; if ((!modulePtr->installScript.empty()) && (!(modulePtr->removeScript.empty()))) { std::string stageInstallPath; stageInstallPath +="staging/modules/files/"; stageInstallPath += modulePtr->name; stageInstallPath += "/scripts/"; stageInstallPath += path::GetLastNode(modulePtr->installScript); script << "build " << "$builddir/" << stageInstallPath << ": "; // Build statement for bundling the module install script script << "BundleFile " << modulePtr->installScript << "\n" << " modeFlags = u+rwx,g+rx-w,o+rx-w\n"; std::string stageRemovePath; stageRemovePath +="staging/modules/files/"; stageRemovePath += modulePtr->name; stageRemovePath += "/scripts/"; stageRemovePath += path::GetLastNode(modulePtr->removeScript); script << "build " << "$builddir/" << stageRemovePath << ": "; // Build statement for bundling the module remove file script << "BundleFile " << modulePtr->removeScript << "\n" << " modeFlags = u+rwx,g+rx-w,o+rx-w\n"; } } //-------------------------------------------------------------------------------------------------- /** * Write to a given build script the build statements for the build script itself. **/ //-------------------------------------------------------------------------------------------------- void ModuleBuildScriptGenerator_t::GenerateNinjaScriptBuildStatement ( model::Module_t* modulePtr ) //-------------------------------------------------------------------------------------------------- { // The build.ninja depends on module .mdef and .ko files // Create a set of dependencies. std::set<std::string> dependencies; for (auto const& it : modulePtr->koFiles) { dependencies.insert(it.first); } dependencies.insert(modulePtr->defFilePtr->path); // It also depends on changes to the mk tools. dependencies.insert(path::Combine(envVars::Get("LEGATO_ROOT"), "build/tools/mk")); baseGeneratorPtr->GenerateNinjaScriptBuildStatement(dependencies); } //-------------------------------------------------------------------------------------------------- /** * Generate a Makefile for a kernel module. **/ //-------------------------------------------------------------------------------------------------- void ModuleBuildScriptGenerator_t::GenerateMakefile ( model::Module_t* modulePtr ) //-------------------------------------------------------------------------------------------------- { std::string buildPath = path::MakeAbsolute(buildParams.workingDir + "/modules/" + modulePtr->name); const std::string& compilerPath = buildParams.cCompilerPath; std::ofstream makefile; OpenFile(makefile, buildPath + "/Makefile", buildParams.beVerbose); // Specify kernel module name and list all object files to link makefile << "obj-m += " << modulePtr->name << ".o\n"; // Don't list object files in case of a single source file with module name if (modulePtr->cObjectFiles.size() > 1 || modulePtr->cObjectFiles.front()->path != modulePtr->name + ".o") { for (auto obj : modulePtr->cObjectFiles) { makefile << modulePtr->name << "-objs += " << obj->path << "\n"; } } makefile << "\n"; // Specify directory where the sources are located makefile << "src = " << modulePtr->dir << "\n\n"; // Add compiler and linker options for (auto const &obj : modulePtr->cFlags) { makefile << "ccflags-y += " << obj << "\n"; } for (auto const &obj : modulePtr->ldFlags) { makefile << "ldflags-y += " << obj << "\n"; } makefile << "\n"; makefile << "KBUILD := " << modulePtr->kernelDir << "\n"; // Iterate through all the required modules and concatenate the modules's Module.symvers file // path for later passing it to KBUILD_EXTRA_SYMBOLS variable during make. std::string buildPathModuleSymvers; for (auto const &reqMod : modulePtr->requiredModules) { model::Module_t* reqModPtr = model::Module_t::GetModule(reqMod.first); if (reqModPtr == NULL) { throw mk::Exception_t( mk::format(LE_I18N("Internal Error: Module object not found for '%s'."), reqMod.first)); } if (reqModPtr->moduleBuildType == model::Module_t::Sources) { std::string reqModuleSymvers = path::MakeAbsolute(buildParams.workingDir + "/modules/" + reqMod.first + "/Module.symvers"); buildPathModuleSymvers = buildPathModuleSymvers + reqModuleSymvers + " "; } } if (buildParams.target != "localhost") { // Specify the CROSS_COMPILE and ARCH environment variables // Note: compiler path may contain dashes in directory names std::string compiler = path::GetLastNode(compilerPath); std::string cross = path::GetContainingDir(compilerPath) + "/" + compiler.substr(0, compiler.rfind('-') + 1); std::string arch = compiler.substr(0, compiler.find('-')); if ((arch == "i586") || (arch == "i686")) { arch = "x86"; } makefile << "export CROSS_COMPILE := " << cross << "\n"; makefile << "export ARCH := " << arch << "\n"; } makefile << "\n"; // Specify build rules makefile << "all:\n"; makefile << "\tmake -C $(KBUILD) M=" + buildPath; // Pass KBUILD_EXTRA_SYMBOLS to resolve module build dependencies. if (!buildPathModuleSymvers.empty()) { makefile << " 'KBUILD_EXTRA_SYMBOLS=" + buildPathModuleSymvers + "'"; } makefile << " modules\n"; makefile << "\n"; makefile << "clean:\n"; makefile << "\t make -C $(KBUILD) M=" + buildPath + " clean\n"; CloseFile(makefile); } //-------------------------------------------------------------------------------------------------- /** * Write to a given build script the build statement for bundling a single file into * the staging area. **/ //-------------------------------------------------------------------------------------------------- void ModuleBuildScriptGenerator_t::GenerateFileBundleBuildStatement ( model::FileSystemObjectSet_t& bundledFiles, ///< Set to fill with bundled file paths. model::Module_t* modulePtr, ///< Module to bundle the file into. const model::FileSystemObject_t* fileSystemObjPtr ///< File bundling info. ) //-------------------------------------------------------------------------------------------------- { // The file will be added to the module's staging area. path::Path_t destPath = "$builddir/staging/modules/files/"; destPath += modulePtr->name; destPath += fileSystemObjPtr->destPath; baseGeneratorPtr->GenerateFileBundleBuildStatement(model::FileSystemObject_t( fileSystemObjPtr->srcPath, destPath.str, fileSystemObjPtr->permissions, fileSystemObjPtr), bundledFiles); } //-------------------------------------------------------------------------------------------------- /** * Write to a given build script the build statements for bundling files from a directory into * the staging area. **/ //-------------------------------------------------------------------------------------------------- void ModuleBuildScriptGenerator_t::GenerateDirBundleBuildStatements ( model::FileSystemObjectSet_t& bundledFiles, ///< Set to fill with bundled file paths. model::Module_t* modulePtr, ///< Module to bundle the directory into. const model::FileSystemObject_t* fileSystemObjPtr ///< Directory bundling info. ) //-------------------------------------------------------------------------------------------------- { // The files will be added to the modules's staging area. path::Path_t destPath = "$builddir/staging/modules/files/"; destPath += modulePtr->name; destPath += fileSystemObjPtr->destPath; baseGeneratorPtr->GenerateDirBundleBuildStatements(model::FileSystemObject_t( fileSystemObjPtr->srcPath, destPath.str, fileSystemObjPtr->permissions, fileSystemObjPtr), bundledFiles); } //-------------------------------------------------------------------------------------------------- /** * Write to a given build script the build statements for bundling a given module's files into the * module's staging area. * **/ //-------------------------------------------------------------------------------------------------- void ModuleBuildScriptGenerator_t::GenerateStagingBundleBuildStatements ( model::Module_t* modulePtr ) //-------------------------------------------------------------------------------------------------- { auto& allBundledFiles = modulePtr->getTargetInfo<target::FileSystemInfo_t>()->allBundledFiles; for (auto fileSystemObjPtr : modulePtr->bundledFiles) { GenerateFileBundleBuildStatement(allBundledFiles, modulePtr, fileSystemObjPtr.get()); } for (auto fileSystemObjPtr : modulePtr->bundledDirs) { GenerateDirBundleBuildStatements(allBundledFiles, modulePtr, fileSystemObjPtr.get()); } } //-------------------------------------------------------------------------------------------------- /** * Write to a given script the build statements for packing up everything into a module bundle. * **/ //-------------------------------------------------------------------------------------------------- void ModuleBuildScriptGenerator_t::GenerateModuleBundleBuildStatement ( model::Module_t* modulePtr, const std::string& outputDir ///< Path to the directory into which built module will be added. ) //-------------------------------------------------------------------------------------------------- { // Give this a FS target info modulePtr->setTargetInfo(new target::FileSystemInfo_t()); // Generate build statements for bundling files into the staging area. GenerateStagingBundleBuildStatements(modulePtr); } //-------------------------------------------------------------------------------------------------- /** * Generate a build script for a kernel module. */ //-------------------------------------------------------------------------------------------------- void ModuleBuildScriptGenerator_t::Generate ( model::Module_t* modulePtr ) { // Start the script with a comment, the file-level variable definitions, and // a set of generic rules. GenerateCommentHeader(modulePtr); script << "builddir = " << path::MakeAbsolute(buildParams.workingDir) << "\n\n"; script << "target = " << buildParams.target << "\n\n"; baseGeneratorPtr->GenerateIfgenFlagsDef(); baseGeneratorPtr->GenerateBuildRules(); if (!buildParams.codeGenOnly) { // Add build statements for the module. GenerateBuildStatements(modulePtr); } // Add a build statement for the build.ninja file itself. GenerateNinjaScriptBuildStatement(modulePtr); } //-------------------------------------------------------------------------------------------------- /** * Generate a build script for a pre-built kernel module. **/ //-------------------------------------------------------------------------------------------------- void Generate ( model::Module_t* modulePtr, const mk::BuildParams_t& buildParams ) //-------------------------------------------------------------------------------------------------- { std::string filePath = path::Minimize(buildParams.workingDir + "/build.ninja"); ModuleBuildScriptGenerator_t scriptGenerator(filePath, buildParams); scriptGenerator.Generate(modulePtr); } } // namespace ninja <|endoftext|>
<commit_before>#pragma once #include <algorithm> #include <cmath> #include <ctime> #include <vector> #include "quantities/quantities.hpp" // Mixed assemblies are not supported by Unity/Mono. #include "glog/logging.h" namespace principia { using quantities::Quotient; namespace integrators { template<typename Position, typename Momentum> inline SPRKIntegrator<Position, Momentum>::SPRKIntegrator() : stages_(0) {} template<typename Position, typename Momentum> inline typename SPRKIntegrator<Position, Momentum>::Coefficients const& SPRKIntegrator<Position, Momentum>::Leapfrog() const { static Coefficients const leapfrog = {{ 0.5, 0.5}, { 0.0, 1.0}}; return leapfrog; } template<typename Position, typename Momentum> inline typename SPRKIntegrator<Position, Momentum>::Coefficients const& SPRKIntegrator<Position, Momentum>::Order4FirstSameAsLast() const { static Coefficients const order_4_first_same_as_last = { { 0.6756035959798288170, -0.1756035959798288170, -0.1756035959798288170, 0.6756035959798288170}, { 0.0, 1.351207191959657634, -1.702414383919315268, 1.351207191959657634}}; return order_4_first_same_as_last; } template<typename Position, typename Momentum> inline typename SPRKIntegrator<Position, Momentum>::Coefficients const& SPRKIntegrator<Position, Momentum>::Order5Optimal() const { static Coefficients const order_5_optimal = { { 0.339839625839110000, -0.088601336903027329, 0.5858564768259621188, -0.603039356536491888, 0.3235807965546976394, 0.4423637942197494587}, { 0.1193900292875672758, 0.6989273703824752308, -0.1713123582716007754, 0.4012695022513534480, 0.0107050818482359840, -0.0589796254980311632}}; return order_5_optimal; } template<typename Position, typename Momentum> inline void SPRKIntegrator<Position, Momentum>::Initialize( Coefficients const& coefficients) { CHECK_EQ(2, coefficients.size()); if (coefficients[1].front() == 0.0) { vanishing_coefficients_ = FirstBVanishes; first_same_as_last_ = std::make_unique<FirstSameAsLast>(); first_same_as_last_->first = coefficients[0].front(); first_same_as_last_->last = coefficients[0].back(); a_ = std::vector<double>(coefficients[0].begin() + 1, coefficients[0].end()); b_ = std::vector<double>(coefficients[0].begin() + 1, coefficients[0].end()); a_.back() += first_same_as_last_->first; stages_ = b_.size(); CHECK_EQ(stages_, a_.size()); } else if (coefficients[0].back() == 0.0) { vanishing_coefficients_ = LastAVanishes; first_same_as_last_ = std::make_unique<FirstSameAsLast>(); first_same_as_last_->first = coefficients[1].front(); first_same_as_last_->last = coefficients[1].back(); a_ = std::vector<double>(coefficients[0].begin(), coefficients[0].end() - 1); b_ = std::vector<double>(coefficients[0].begin(), coefficients[0].end() - 1); b_.front() += first_same_as_last_->last; stages_ = b_.size(); CHECK_EQ(stages_, a_.size()); } else { vanishing_coefficients_ = None; a_ = coefficients[0]; b_ = coefficients[1]; stages_ = b_.size(); CHECK_EQ(stages_, a_.size()); } // Runge-Kutta time weights. c_.resize(stages_); if (vanishing_coefficients_ == FirstBVanishes) { c_[0] = first_same_as_last_->first; } else { c_[0] = 0.0; } for (int j = 1; j < stages_; ++j) { c_[j] = c_[j - 1] + a_[j - 1]; } } template<typename Position, typename Momentum> template<typename AutonomousRightHandSideComputation, typename RightHandSideComputation> void SPRKIntegrator<Position, Momentum>::Solve( RightHandSideComputation compute_force, AutonomousRightHandSideComputation compute_velocity, Parameters const& parameters, not_null<std::vector<SystemState>*> const solution) const { switch (vanishing_coefficients_) { case None: SolveOptimized<None>( compute_force, compute_velocity, parameters, solution); break; case FirstBVanishes: SolveOptimized<FirstBVanishes>( compute_force, compute_velocity, parameters, solution); break; case LastAVanishes: SolveOptimized<LastAVanishes>( compute_force, compute_velocity, parameters, solution); break; default: LOG(FATAL) << "Invalid vanishing coefficients"; } } template<typename Position, typename Momentum> template<VanishingCoefficients vanishing_coefficients, typename AutonomousRightHandSideComputation, typename RightHandSideComputation> void SPRKIntegrator<Position, Momentum>::SolveOptimized( RightHandSideComputation compute_force, AutonomousRightHandSideComputation compute_velocity, Parameters const& parameters, not_null<std::vector<SystemState>*> const solution) const { int const dimension = parameters.initial.positions.size(); std::vector<Position> Δqstage0(dimension); std::vector<Position> Δqstage1(dimension); std::vector<Momentum> Δpstage0(dimension); std::vector<Momentum> Δpstage1(dimension); std::vector<Position>* Δqstage_current = &Δqstage1; std::vector<Position>* Δqstage_previous = &Δqstage0; std::vector<Momentum>* Δpstage_current = &Δpstage1; std::vector<Momentum>* Δpstage_previous = &Δpstage0; // Dimension the result. int const capacity = parameters.sampling_period == 0 ? 1 : static_cast<int>( ceil((((parameters.tmax - parameters.initial.time.value) / parameters.Δt) + 1) / parameters.sampling_period)) + 1; solution->clear(); solution->reserve(capacity); std::vector<DoublePrecision<Position>> q_last(parameters.initial.positions); std::vector<DoublePrecision<Momentum>> p_last(parameters.initial.momenta); int sampling_phase = 0; std::vector<Position> q_stage(dimension); std::vector<Momentum> p_stage(dimension); std::vector<Quotient<Momentum, Time>> f(dimension); // Current forces. std::vector<Quotient<Position, Time>> v(dimension); // Current velocities. // The following quantity is generally equal to |Δt|, but during the last // iteration, if |tmax_is_exact|, it may differ significantly from |Δt|. Time h = parameters.Δt; // Constant for now. // During one iteration of the outer loop below we process the time interval // [|tn|, |tn| + |h|[. |tn| is computed using compensated summation to make // sure that we don't have drifts. DoublePrecision<Time> tn = parameters.initial.time; // Whether position and momentum are synchronized between steps, relevant for // first-same-as-last (FSAL) integrators. Time is always synchronous with // position. bool q_and_p_are_synchronized = true; bool should_synchronize = false; auto const advance_Δqstage = [&Δqstage_previous, &Δqstage_current, &dimension, &compute_velocity, &p_stage, &v, &q_stage, &q_last](Time step) { compute_velocity(p_stage, &v); for (int k = 0; k < dimension; ++k) { Position const Δq = (*Δqstage_previous)[k] + step * v[k]; q_stage[k] = q_last[k].value + Δq; (*Δqstage_current)[k] = Δq; } }; auto const advance_Δpstage = [&compute_force, &q_stage, &f, &dimension, &Δpstage_previous, &Δpstage_current, &p_stage, &p_last](Time step, Time q_clock) { compute_force(q_clock, q_stage, &f); for (int k = 0; k < dimension; ++k) { Momentum const Δp = (*Δpstage_previous)[k] + step * f[k]; p_stage[k] = p_last[k].value + Δp; (*Δpstage_current)[k] = Δp; } }; // Integration. For details see Wolfram Reference, // http://reference.wolfram.com/mathematica/tutorial/NDSolveSPRK.html#74387056 bool at_end = !parameters.tmax_is_exact && parameters.tmax < tn.value + h; while (!at_end) { // Check if this is the last interval and if so process it appropriately. if (parameters.tmax_is_exact) { // If |tn| is getting close to |tmax|, use |tmax| as the upper bound of // the interval and update |h| accordingly. The bound chosen here for // |tmax| ensures that we don't end up with a ridiculously small last // interval: we'd rather make the last interval a bit bigger. More // precisely, the last interval generally has a length between 0.5 Δt and // 1.5 Δt, unless it is also the first interval. // NOTE(phl): This may lead to convergence as bad as (1.5 Δt)^5 rather // than Δt^5. if (parameters.tmax <= tn.value + 3 * h / 2) { at_end = true; h = (parameters.tmax - tn.value) - tn.error; } } else if (parameters.tmax < tn.value + 2 * h) { // If the next interval would overshoot, make this the last interval but // stick to the same step. at_end = true; } // Here |h| is the length of the current time interval and |tn| is its // start. // Increment SPRK step from "'SymplecticPartitionedRungeKutta' Method // for NDSolve", algorithm 3. for (int k = 0; k < dimension; ++k) { (*Δqstage_current)[k] = Position(); (*Δpstage_current)[k] = Momentum(); q_stage[k] = q_last[k].value; } if (vanishing_coefficients_ != None) { should_synchronize = at_end || (parameters.sampling_period != 0 && sampling_phase % parameters.sampling_period == 0); } if (vanishing_coefficients_ == FirstBVanishes && q_and_p_are_synchronized) { // Desynchronize. for (int k = 0; k < dimension; ++k) { p_stage[k] = p_last[k].value; } advance_Δqstage(first_same_as_last_->first * h); q_and_p_are_synchronized = false; } for (int i = 0; i < stages_; ++i) { std::swap(Δqstage_current, Δqstage_previous); std::swap(Δpstage_current, Δpstage_previous); // Beware, the p/q order matters here, the two computations depend on one // another. // By using |tn.error| below we get a time value which is possibly a wee // bit more precise. if (vanishing_coefficients_ == LastAVanishes && q_and_p_are_synchronized && i == 0) { advance_Δpstage(first_same_as_last_->first * h, tn.value + (tn.error + c_[i] * h)); q_and_p_are_synchronized = false; } else { advance_Δpstage(b_[i] * h, tn.value + (tn.error + c_[i] * h)); } if (vanishing_coefficients_ == FirstBVanishes && should_synchronize && i == stages_ - 1) { advance_Δqstage(first_same_as_last_->last * h); q_and_p_are_synchronized = true; } else { advance_Δqstage(a_[i] * h); } } if (vanishing_coefficients_ == LastAVanishes && should_synchronize) { // TODO(egg): the second parameter below is really just tn.value + h. advance_Δpstage(first_same_as_last_->last * h, tn.value + (tn.error + c_.back() * h)); q_and_p_are_synchronized = true; } // Compensated summation from "'SymplecticPartitionedRungeKutta' Method // for NDSolve", algorithm 2. for (int k = 0; k < dimension; ++k) { q_last[k].Increment((*Δqstage_current)[k]); p_last[k].Increment((*Δpstage_current)[k]); q_stage[k] = q_last[k].value; p_stage[k] = p_last[k].value; } tn.Increment(h); if (parameters.sampling_period != 0) { if (sampling_phase % parameters.sampling_period == 0) { solution->emplace_back(); SystemState* state = &solution->back(); state->time = tn; state->positions.reserve(dimension); state->momenta.reserve(dimension); for (int k = 0; k < dimension; ++k) { state->positions.emplace_back(q_last[k]); state->momenta.emplace_back(p_last[k]); } } ++sampling_phase; } } if (parameters.sampling_period == 0) { solution->emplace_back(); SystemState* state = &solution->back(); state->time = tn; state->positions.reserve(dimension); state->momenta.reserve(dimension); for (int k = 0; k < dimension; ++k) { state->positions.emplace_back(q_last[k]); state->momenta.emplace_back(p_last[k]); } } } } // namespace integrators } // namespace principia <commit_msg>fast (but uglyyyy)<commit_after>#pragma once #include <algorithm> #include <cmath> #include <ctime> #include <vector> #include "quantities/quantities.hpp" // Mixed assemblies are not supported by Unity/Mono. #include "glog/logging.h" namespace principia { using quantities::Quotient; namespace integrators { template<typename Position, typename Momentum> inline SPRKIntegrator<Position, Momentum>::SPRKIntegrator() : stages_(0) {} template<typename Position, typename Momentum> inline typename SPRKIntegrator<Position, Momentum>::Coefficients const& SPRKIntegrator<Position, Momentum>::Leapfrog() const { static Coefficients const leapfrog = {{ 0.5, 0.5}, { 0.0, 1.0}}; return leapfrog; } template<typename Position, typename Momentum> inline typename SPRKIntegrator<Position, Momentum>::Coefficients const& SPRKIntegrator<Position, Momentum>::Order4FirstSameAsLast() const { static Coefficients const order_4_first_same_as_last = { { 0.6756035959798288170, -0.1756035959798288170, -0.1756035959798288170, 0.6756035959798288170}, { 0.0, 1.351207191959657634, -1.702414383919315268, 1.351207191959657634}}; return order_4_first_same_as_last; } template<typename Position, typename Momentum> inline typename SPRKIntegrator<Position, Momentum>::Coefficients const& SPRKIntegrator<Position, Momentum>::Order5Optimal() const { static Coefficients const order_5_optimal = { { 0.339839625839110000, -0.088601336903027329, 0.5858564768259621188, -0.603039356536491888, 0.3235807965546976394, 0.4423637942197494587}, { 0.1193900292875672758, 0.6989273703824752308, -0.1713123582716007754, 0.4012695022513534480, 0.0107050818482359840, -0.0589796254980311632}}; return order_5_optimal; } template<typename Position, typename Momentum> inline void SPRKIntegrator<Position, Momentum>::Initialize( Coefficients const& coefficients) { CHECK_EQ(2, coefficients.size()); if (coefficients[1].front() == 0.0) { vanishing_coefficients_ = FirstBVanishes; first_same_as_last_ = std::make_unique<FirstSameAsLast>(); first_same_as_last_->first = coefficients[0].front(); first_same_as_last_->last = coefficients[0].back(); a_ = std::vector<double>(coefficients[0].begin() + 1, coefficients[0].end()); b_ = std::vector<double>(coefficients[0].begin() + 1, coefficients[0].end()); a_.back() += first_same_as_last_->first; stages_ = b_.size(); CHECK_EQ(stages_, a_.size()); } else if (coefficients[0].back() == 0.0) { vanishing_coefficients_ = LastAVanishes; first_same_as_last_ = std::make_unique<FirstSameAsLast>(); first_same_as_last_->first = coefficients[1].front(); first_same_as_last_->last = coefficients[1].back(); a_ = std::vector<double>(coefficients[0].begin(), coefficients[0].end() - 1); b_ = std::vector<double>(coefficients[0].begin(), coefficients[0].end() - 1); b_.front() += first_same_as_last_->last; stages_ = b_.size(); CHECK_EQ(stages_, a_.size()); } else { vanishing_coefficients_ = None; a_ = coefficients[0]; b_ = coefficients[1]; stages_ = b_.size(); CHECK_EQ(stages_, a_.size()); } // Runge-Kutta time weights. c_.resize(stages_); if (vanishing_coefficients_ == FirstBVanishes) { c_[0] = first_same_as_last_->first; } else { c_[0] = 0.0; } for (int j = 1; j < stages_; ++j) { c_[j] = c_[j - 1] + a_[j - 1]; } } template<typename Position, typename Momentum> template<typename AutonomousRightHandSideComputation, typename RightHandSideComputation> void SPRKIntegrator<Position, Momentum>::Solve( RightHandSideComputation compute_force, AutonomousRightHandSideComputation compute_velocity, Parameters const& parameters, not_null<std::vector<SystemState>*> const solution) const { switch (vanishing_coefficients_) { case None: SolveOptimized<None>( compute_force, compute_velocity, parameters, solution); break; case FirstBVanishes: SolveOptimized<FirstBVanishes>( compute_force, compute_velocity, parameters, solution); break; case LastAVanishes: SolveOptimized<LastAVanishes>( compute_force, compute_velocity, parameters, solution); break; default: LOG(FATAL) << "Invalid vanishing coefficients"; } } template<typename Position, typename Momentum> template<VanishingCoefficients vanishing_coefficients, typename AutonomousRightHandSideComputation, typename RightHandSideComputation> void SPRKIntegrator<Position, Momentum>::SolveOptimized( RightHandSideComputation compute_force, AutonomousRightHandSideComputation compute_velocity, Parameters const& parameters, not_null<std::vector<SystemState>*> const solution) const { int const dimension = parameters.initial.positions.size(); std::vector<Position> Δqstage0(dimension); std::vector<Position> Δqstage1(dimension); std::vector<Momentum> Δpstage0(dimension); std::vector<Momentum> Δpstage1(dimension); std::vector<Position>* Δqstage_current = &Δqstage1; std::vector<Position>* Δqstage_previous = &Δqstage0; std::vector<Momentum>* Δpstage_current = &Δpstage1; std::vector<Momentum>* Δpstage_previous = &Δpstage0; // Dimension the result. int const capacity = parameters.sampling_period == 0 ? 1 : static_cast<int>( ceil((((parameters.tmax - parameters.initial.time.value) / parameters.Δt) + 1) / parameters.sampling_period)) + 1; solution->clear(); solution->reserve(capacity); std::vector<DoublePrecision<Position>> q_last(parameters.initial.positions); std::vector<DoublePrecision<Momentum>> p_last(parameters.initial.momenta); int sampling_phase = 0; std::vector<Position> q_stage(dimension); std::vector<Momentum> p_stage(dimension); std::vector<Quotient<Momentum, Time>> f(dimension); // Current forces. std::vector<Quotient<Position, Time>> v(dimension); // Current velocities. // The following quantity is generally equal to |Δt|, but during the last // iteration, if |tmax_is_exact|, it may differ significantly from |Δt|. Time h = parameters.Δt; // Constant for now. // During one iteration of the outer loop below we process the time interval // [|tn|, |tn| + |h|[. |tn| is computed using compensated summation to make // sure that we don't have drifts. DoublePrecision<Time> tn = parameters.initial.time; // Whether position and momentum are synchronized between steps, relevant for // first-same-as-last (FSAL) integrators. Time is always synchronous with // position. bool q_and_p_are_synchronized = true; bool should_synchronize = false; #define ADVANCE_ΔQSTAGE(step) \ do { \ compute_velocity(p_stage, &v); \ for (int k = 0; k < dimension; ++k) { \ Position const Δq = (*Δqstage_previous)[k] + step * v[k]; \ q_stage[k] = q_last[k].value + Δq; \ (*Δqstage_current)[k] = Δq; \ } \ } while (false); #define ADVANCE_ΔPSTAGE(step, q_clock) \ do { \ compute_force(q_clock, q_stage, &f); \ for (int k = 0; k < dimension; ++k) { \ Momentum const Δp = (*Δpstage_previous)[k] + step * f[k];\ p_stage[k] = p_last[k].value + Δp;\ (*Δpstage_current)[k] = Δp;\ } \ } while (false); // Integration. For details see Wolfram Reference, // http://reference.wolfram.com/mathematica/tutorial/NDSolveSPRK.html#74387056 bool at_end = !parameters.tmax_is_exact && parameters.tmax < tn.value + h; while (!at_end) { // Check if this is the last interval and if so process it appropriately. if (parameters.tmax_is_exact) { // If |tn| is getting close to |tmax|, use |tmax| as the upper bound of // the interval and update |h| accordingly. The bound chosen here for // |tmax| ensures that we don't end up with a ridiculously small last // interval: we'd rather make the last interval a bit bigger. More // precisely, the last interval generally has a length between 0.5 Δt and // 1.5 Δt, unless it is also the first interval. // NOTE(phl): This may lead to convergence as bad as (1.5 Δt)^5 rather // than Δt^5. if (parameters.tmax <= tn.value + 3 * h / 2) { at_end = true; h = (parameters.tmax - tn.value) - tn.error; } } else if (parameters.tmax < tn.value + 2 * h) { // If the next interval would overshoot, make this the last interval but // stick to the same step. at_end = true; } // Here |h| is the length of the current time interval and |tn| is its // start. // Increment SPRK step from "'SymplecticPartitionedRungeKutta' Method // for NDSolve", algorithm 3. for (int k = 0; k < dimension; ++k) { (*Δqstage_current)[k] = Position(); (*Δpstage_current)[k] = Momentum(); q_stage[k] = q_last[k].value; } if (vanishing_coefficients_ != None) { should_synchronize = at_end || (parameters.sampling_period != 0 && sampling_phase % parameters.sampling_period == 0); } if (vanishing_coefficients_ == FirstBVanishes && q_and_p_are_synchronized) { // Desynchronize. for (int k = 0; k < dimension; ++k) { p_stage[k] = p_last[k].value; } ADVANCE_ΔQSTAGE(first_same_as_last_->first * h); q_and_p_are_synchronized = false; } for (int i = 0; i < stages_; ++i) { std::swap(Δqstage_current, Δqstage_previous); std::swap(Δpstage_current, Δpstage_previous); // Beware, the p/q order matters here, the two computations depend on one // another. // By using |tn.error| below we get a time value which is possibly a wee // bit more precise. if (vanishing_coefficients_ == LastAVanishes && q_and_p_are_synchronized && i == 0) { ADVANCE_ΔPSTAGE(first_same_as_last_->first * h, tn.value + (tn.error + c_[i] * h)); q_and_p_are_synchronized = false; } else { ADVANCE_ΔPSTAGE(b_[i] * h, tn.value + (tn.error + c_[i] * h)); } if (vanishing_coefficients_ == FirstBVanishes && should_synchronize && i == stages_ - 1) { ADVANCE_ΔQSTAGE(first_same_as_last_->last * h); q_and_p_are_synchronized = true; } else { ADVANCE_ΔQSTAGE(a_[i] * h); } } if (vanishing_coefficients_ == LastAVanishes && should_synchronize) { // TODO(egg): the second parameter below is really just tn.value + h. ADVANCE_ΔPSTAGE(first_same_as_last_->last * h, tn.value + (tn.error + c_.back() * h)); q_and_p_are_synchronized = true; } // Compensated summation from "'SymplecticPartitionedRungeKutta' Method // for NDSolve", algorithm 2. for (int k = 0; k < dimension; ++k) { q_last[k].Increment((*Δqstage_current)[k]); p_last[k].Increment((*Δpstage_current)[k]); q_stage[k] = q_last[k].value; p_stage[k] = p_last[k].value; } tn.Increment(h); if (parameters.sampling_period != 0) { if (sampling_phase % parameters.sampling_period == 0) { solution->emplace_back(); SystemState* state = &solution->back(); state->time = tn; state->positions.reserve(dimension); state->momenta.reserve(dimension); for (int k = 0; k < dimension; ++k) { state->positions.emplace_back(q_last[k]); state->momenta.emplace_back(p_last[k]); } } ++sampling_phase; } } if (parameters.sampling_period == 0) { solution->emplace_back(); SystemState* state = &solution->back(); state->time = tn; state->positions.reserve(dimension); state->momenta.reserve(dimension); for (int k = 0; k < dimension; ++k) { state->positions.emplace_back(q_last[k]); state->momenta.emplace_back(p_last[k]); } } } } // namespace integrators } // namespace principia <|endoftext|>
<commit_before>/*Copyright 2014-2015 George Karagoulis 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 <grypto_passworddatabase.h> #include <grypto_xmlconverter.h> #include <grypto_entry.h> #include <gutil/databaseutils.h> #include <QString> #include <QtTest> using namespace std; USING_NAMESPACE_GUTIL; USING_NAMESPACE_GRYPTO; #define TEST_FILEPATH "testdb.sqlite" #define TEST_PASSWORD "password...shhh" Grypt::Credentials creds; class DatabaseTest : public QObject { Q_OBJECT PasswordDatabase *db; public: DatabaseTest(); private Q_SLOTS: void initTestCase(); void test_create(); void test_entry(); void test_entry_insert(); void test_entry_delete(); void test_entry_update(); void cleanupTestCase(); }; DatabaseTest::DatabaseTest() :db(0) { creds.Password = TEST_PASSWORD; } void DatabaseTest::initTestCase() { if(QFile::exists(TEST_FILEPATH)) QVERIFY(QFile::remove(TEST_FILEPATH)); bool no_exception = true; try { db = new PasswordDatabase(TEST_FILEPATH, creds); } catch(...) { no_exception = false; } QVERIFY(no_exception); } void DatabaseTest::test_create() { // Try opening the database with the wrong key bool exception_hit = false; Credentials bad_creds; bad_creds.Password = "wrong password"; try { PasswordDatabase newdb(TEST_FILEPATH, bad_creds); } catch(const AuthenticationException<> &ex) { exception_hit = true; } QVERIFY(exception_hit); // Try opening the database with the right key (No exception) PasswordDatabase newdb(TEST_FILEPATH, creds); } bool __compare_entries(const Entry &lhs, const Entry &rhs) { bool ret = lhs.GetName() == rhs.GetName() && lhs.GetDescription() == rhs.GetDescription() && lhs.GetFavoriteIndex() == rhs.GetFavoriteIndex() && lhs.GetModifyDate().toTime_t() == rhs.GetModifyDate().toTime_t() && lhs.GetId() == rhs.GetId() && lhs.GetParentId() == rhs.GetParentId() && lhs.GetRow() == rhs.GetRow() && lhs.Values().count() == rhs.Values().count(); for(int i = 0; ret && i < lhs.Values().count(); ++i) { ret = lhs.Values()[i].GetName() == rhs.Values()[i].GetName() && lhs.Values()[i].GetValue() == rhs.Values()[i].GetValue() && lhs.Values()[i].GetNotes() == rhs.Values()[i].GetNotes() && lhs.Values()[i].GetIsHidden() == rhs.Values()[i].GetIsHidden(); } return ret; } void DatabaseTest::test_entry() { Entry e, e2; SecretValue v; e.SetName("first entry"); e.SetDescription("first description"); e.SetModifyDate(QDateTime::currentDateTime()); v.SetName("one"); v.SetValue("Hello World!"); v.SetNotes("note to self"); e.Values().append(v); QByteArray entry_xml = XmlConverter::ToXmlString(e); e2 = XmlConverter::FromXmlString<Entry>(entry_xml); QVERIFY(__compare_entries(e, e2)); db->AddEntry(e); // After insertion, the id should be updated to the new value QVERIFY(e.GetId() != e2.GetId()); // Try reading it back in, it should be the same as the original Entry e3 = db->FindEntry(e.GetId()); QVERIFY(__compare_entries(e, e3)); } void DatabaseTest::test_entry_insert() { Entry e; e.SetName("new entry"); e.SetDescription("testing insertion"); e.SetModifyDate(QDateTime::currentDateTime()); e.SetRow(1); db->AddEntry(e); e.SetRow(0); db->AddEntry(e); vector<Entry> el = db->FindEntriesByParentId(EntryId::Null()); QVERIFY(el.size() == 3); QVERIFY(el[0].GetName() == "new entry"); QVERIFY(el[1].GetName() == "first entry"); QVERIFY(el[2].GetName() == "new entry"); QVERIFY(el[0].GetRow() == 0); QVERIFY(el[1].GetRow() == 1); QVERIFY(el[2].GetRow() == 2); QVERIFY(__compare_entries(el[0], e)); } void DatabaseTest::test_entry_delete() { Entry e; e.SetRow(0); db->AddEntry(e); db->DeleteEntry(e.GetId()); vector<Entry> el = db->FindEntriesByParentId(EntryId::Null()); QVERIFY(el.size() == 3); QVERIFY(el[0].GetName() == "new entry"); QVERIFY(el[1].GetName() == "first entry"); QVERIFY(el[2].GetName() == "new entry"); QVERIFY(el[0].GetRow() == 0); QVERIFY(el[1].GetRow() == 1); QVERIFY(el[2].GetRow() == 2); } void DatabaseTest::test_entry_update() { Entry e; db->AddEntry(e); e.SetName("updated entry"); e.SetDescription("totally new description"); e.SetFavoriteIndex(0); db->UpdateEntry(e); Entry e2 = db->FindEntry(e.GetId()); QVERIFY(__compare_entries(e, e2)); } void DatabaseTest::cleanupTestCase() { delete db; // Make sure we can remove the file after destroying the class QVERIFY(QFile::remove(TEST_FILEPATH)); } QTEST_APPLESS_MAIN(DatabaseTest) #include "tst_databasetest.moc" <commit_msg>Fixed the test before I add new tests<commit_after>/*Copyright 2014-2015 George Karagoulis 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 <grypto_passworddatabase.h> #include <grypto_xmlconverter.h> #include <grypto_entry.h> #include <gutil/cryptopp_rng.h> #include <gutil/databaseutils.h> #include <QString> #include <QtTest> using namespace std; USING_NAMESPACE_GUTIL; USING_NAMESPACE_GRYPTO; #define TEST_FILEPATH "testdb.sqlite" #define TEST_PASSWORD "password...shhh" static GUtil::CryptoPP::RNG __cryptopp_rng; static GUtil::RNG_Initializer __rng_init(&__cryptopp_rng); Grypt::Credentials creds; class DatabaseTest : public QObject { Q_OBJECT PasswordDatabase *db; public: DatabaseTest(); private Q_SLOTS: void initTestCase(); void test_create(); void test_entry(); void test_entry_insert(); void test_entry_delete(); void test_entry_update(); void cleanupTestCase(); }; DatabaseTest::DatabaseTest() :db(0) { creds.Password = TEST_PASSWORD; } void DatabaseTest::initTestCase() { if(QFile::exists(TEST_FILEPATH)) QVERIFY(QFile::remove(TEST_FILEPATH)); bool no_exception = true; try { db = new PasswordDatabase(TEST_FILEPATH, creds); } catch(...) { no_exception = false; } QVERIFY(no_exception); } void DatabaseTest::test_create() { // Try opening the database with the wrong key bool exception_hit = false; Credentials bad_creds; bad_creds.Password = "wrong password"; try { PasswordDatabase newdb(TEST_FILEPATH, bad_creds); } catch(const AuthenticationException<> &ex) { exception_hit = true; } QVERIFY(exception_hit); // Try opening the database with the right key (No exception) PasswordDatabase newdb(TEST_FILEPATH, creds); } bool __compare_entries(const Entry &lhs, const Entry &rhs) { bool ret = lhs.GetName() == rhs.GetName() && lhs.GetDescription() == rhs.GetDescription() && lhs.GetFavoriteIndex() == rhs.GetFavoriteIndex() && lhs.GetModifyDate().toTime_t() == rhs.GetModifyDate().toTime_t() && lhs.GetId() == rhs.GetId() && lhs.GetParentId() == rhs.GetParentId() && lhs.GetRow() == rhs.GetRow() && lhs.Values().count() == rhs.Values().count(); for(int i = 0; ret && i < lhs.Values().count(); ++i) { ret = lhs.Values()[i].GetName() == rhs.Values()[i].GetName() && lhs.Values()[i].GetValue() == rhs.Values()[i].GetValue() && lhs.Values()[i].GetNotes() == rhs.Values()[i].GetNotes() && lhs.Values()[i].GetIsHidden() == rhs.Values()[i].GetIsHidden(); } return ret; } void DatabaseTest::test_entry() { Entry e, e2; SecretValue v; e.SetName("first entry"); e.SetDescription("first description"); e.SetModifyDate(QDateTime::currentDateTime()); v.SetName("one"); v.SetValue("Hello World!"); v.SetNotes("note to self"); e.Values().append(v); QByteArray entry_xml = XmlConverter::ToXmlString(e); e2 = XmlConverter::FromXmlString<Entry>(entry_xml); QVERIFY(__compare_entries(e, e2)); db->AddEntry(e); // After insertion, the id should be updated to the new value QVERIFY(e.GetId() != e2.GetId()); // Try reading it back in, it should be the same as the original Entry e3 = db->FindEntry(e.GetId()); QVERIFY(__compare_entries(e, e3)); } void DatabaseTest::test_entry_insert() { Entry e; e.SetName("new entry"); e.SetDescription("testing insertion"); e.SetModifyDate(QDateTime::currentDateTime()); e.SetRow(1); db->AddEntry(e); e.SetRow(0); db->AddEntry(e); vector<Entry> el = db->FindEntriesByParentId(EntryId::Null()); QVERIFY(el.size() == 3); QVERIFY(el[0].GetName() == "new entry"); QVERIFY(el[1].GetName() == "first entry"); QVERIFY(el[2].GetName() == "new entry"); QVERIFY(el[0].GetRow() == 0); QVERIFY(el[1].GetRow() == 1); QVERIFY(el[2].GetRow() == 2); QVERIFY(__compare_entries(el[0], e)); } void DatabaseTest::test_entry_delete() { Entry e; e.SetRow(0); db->AddEntry(e); db->DeleteEntry(e.GetId()); vector<Entry> el = db->FindEntriesByParentId(EntryId::Null()); QVERIFY(el.size() == 3); QVERIFY(el[0].GetName() == "new entry"); QVERIFY(el[1].GetName() == "first entry"); QVERIFY(el[2].GetName() == "new entry"); QVERIFY(el[0].GetRow() == 0); QVERIFY(el[1].GetRow() == 1); QVERIFY(el[2].GetRow() == 2); } void DatabaseTest::test_entry_update() { Entry e; db->AddEntry(e); e.SetName("updated entry"); e.SetDescription("totally new description"); e.SetFavoriteIndex(0); db->UpdateEntry(e); Entry e2 = db->FindEntry(e.GetId()); QVERIFY(__compare_entries(e, e2)); } void DatabaseTest::cleanupTestCase() { delete db; // Make sure we can remove the file after destroying the class QVERIFY(QFile::remove(TEST_FILEPATH)); } QTEST_APPLESS_MAIN(DatabaseTest) #include "tst_databasetest.moc" <|endoftext|>
<commit_before>// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #define CAF_SUITE json_writer #include "caf/json_writer.hpp" #include "core-test.hpp" using namespace caf; using namespace std::literals::string_literals; namespace { struct fixture { template <class T> expected<std::string> to_json_string(T&& x, size_t indentation_factor) { json_writer writer; writer.indentation(indentation_factor); if (writer.apply(std::forward<T>(x))) { auto buf = writer.str(); return {std::string{buf.begin(), buf.end()}}; } else { MESSAGE("partial JSON output: " << writer.str()); return {writer.get_error()}; } } }; } // namespace CAF_TEST_FIXTURE_SCOPE(json_writer_tests, fixture) SCENARIO("the JSON writer converts builtin types to strings") { GIVEN("an integer") { auto x = 42; WHEN("converting it to JSON with any indentation factor") { THEN("the JSON output is the number") { CHECK_EQ(to_json_string(x, 0), "42"s); CHECK_EQ(to_json_string(x, 2), "42"s); } } } GIVEN("a string") { auto x = R"_(hello "world"!)_"s; WHEN("converting it to JSON with any indentation factor") { THEN("the JSON output is the escaped string") { CHECK_EQ(to_json_string(x, 0), R"_("hello \"world\"!")_"s); CHECK_EQ(to_json_string(x, 2), R"_("hello \"world\"!")_"s); } } } GIVEN("a list") { auto x = std::vector<int>{1, 2, 3}; WHEN("converting it to JSON with indentation factor 0") { THEN("the JSON output is a single line") { CHECK_EQ(to_json_string(x, 0), "[1, 2, 3]"s); } } WHEN("converting it to JSON with indentation factor 2") { THEN("the JSON output uses multiple lines") { auto out = R"_([ 1, 2, 3 ])_"s; CHECK_EQ(to_json_string(x, 2), out); } } } GIVEN("a dictionary") { std::map<std::string, std::string> x; x.emplace("a", "A"); x.emplace("b", "B"); x.emplace("c", "C"); WHEN("converting it to JSON with indentation factor 0") { THEN("the JSON output is a single line") { CHECK_EQ(to_json_string(x, 0), R"_({"a": "A", "b": "B", "c": "C"})_"s); } } WHEN("converting it to JSON with indentation factor 2") { THEN("the JSON output uses multiple lines") { auto out = R"_({ "a": "A", "b": "B", "c": "C" })_"s; CHECK_EQ(to_json_string(x, 2), out); } } } GIVEN("a message") { auto x = make_message(put_atom_v, "foo", 42); WHEN("converting it to JSON with indentation factor 0") { THEN("the JSON output is a single line") { CHECK_EQ(to_json_string(x, 0), R"_([{"@type": "caf::put_atom"}, "foo", 42])_"s); } } WHEN("converting it to JSON with indentation factor 2") { THEN("the JSON output uses multiple lines") { auto out = R"_([ { "@type": "caf::put_atom" }, "foo", 42 ])_"s; CHECK_EQ(to_json_string(x, 2), out); } } } } SCENARIO("the JSON writer converts simple structs to strings") { GIVEN("a dummy_struct object") { dummy_struct x{10, "foo"}; WHEN("converting it to JSON with indentation factor 0") { THEN("the JSON output is a single line") { auto out = R"_({"@type": "dummy_struct", "a": 10, "b": "foo"})_"s; CHECK_EQ(to_json_string(x, 0), out); } } WHEN("converting it to JSON with indentation factor 2") { THEN("the JSON output uses multiple lines") { auto out = R"_({ "@type": "dummy_struct", "a": 10, "b": "foo" })_"s; CHECK_EQ(to_json_string(x, 2), out); } } } } CAF_TEST_FIXTURE_SCOPE_END() <commit_msg>Fix build on MSVC<commit_after>// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #define CAF_SUITE json_writer #include "caf/json_writer.hpp" #include "core-test.hpp" using namespace caf; using namespace std::literals::string_literals; namespace { struct fixture { template <class T> expected<std::string> to_json_string(T&& x, size_t indentation_factor) { json_writer writer; writer.indentation(indentation_factor); if (writer.apply(std::forward<T>(x))) { auto buf = writer.str(); return {std::string{buf.begin(), buf.end()}}; } else { MESSAGE("partial JSON output: " << writer.str()); return {writer.get_error()}; } } }; } // namespace CAF_TEST_FIXTURE_SCOPE(json_writer_tests, fixture) SCENARIO("the JSON writer converts builtin types to strings") { GIVEN("an integer") { auto x = 42; WHEN("converting it to JSON with any indentation factor") { THEN("the JSON output is the number") { CHECK_EQ(to_json_string(x, 0), "42"s); CHECK_EQ(to_json_string(x, 2), "42"s); } } } GIVEN("a string") { std::string x = R"_(hello "world"!)_"; WHEN("converting it to JSON with any indentation factor") { THEN("the JSON output is the escaped string") { std::string out = R"_("hello \"world\"!")_"; CHECK_EQ(to_json_string(x, 0), out); CHECK_EQ(to_json_string(x, 2), out); } } } GIVEN("a list") { auto x = std::vector<int>{1, 2, 3}; WHEN("converting it to JSON with indentation factor 0") { THEN("the JSON output is a single line") { std::string out = "[1, 2, 3]"; CHECK_EQ(to_json_string(x, 0), out); } } WHEN("converting it to JSON with indentation factor 2") { THEN("the JSON output uses multiple lines") { std::string out = R"_([ 1, 2, 3 ])_"; CHECK_EQ(to_json_string(x, 2), out); } } } GIVEN("a dictionary") { std::map<std::string, std::string> x; x.emplace("a", "A"); x.emplace("b", "B"); x.emplace("c", "C"); WHEN("converting it to JSON with indentation factor 0") { THEN("the JSON output is a single line") { CHECK_EQ(to_json_string(x, 0), R"_({"a": "A", "b": "B", "c": "C"})_"s); } } WHEN("converting it to JSON with indentation factor 2") { THEN("the JSON output uses multiple lines") { std::string out = R"_({ "a": "A", "b": "B", "c": "C" })_"; CHECK_EQ(to_json_string(x, 2), out); } } } GIVEN("a message") { auto x = make_message(put_atom_v, "foo", 42); WHEN("converting it to JSON with indentation factor 0") { THEN("the JSON output is a single line") { std::string out = R"_([{"@type": "caf::put_atom"}, "foo", 42])_"; CHECK_EQ(to_json_string(x, 0), out); } } WHEN("converting it to JSON with indentation factor 2") { THEN("the JSON output uses multiple lines") { std::string out = R"_([ { "@type": "caf::put_atom" }, "foo", 42 ])_"; CHECK_EQ(to_json_string(x, 2), out); } } } } SCENARIO("the JSON writer converts simple structs to strings") { GIVEN("a dummy_struct object") { dummy_struct x{10, "foo"}; WHEN("converting it to JSON with indentation factor 0") { THEN("the JSON output is a single line") { std::string out = R"_({"@type": "dummy_struct", "a": 10, "b": "foo"})_"; CHECK_EQ(to_json_string(x, 0), out); } } WHEN("converting it to JSON with indentation factor 2") { THEN("the JSON output uses multiple lines") { std::string out = R"_({ "@type": "dummy_struct", "a": 10, "b": "foo" })_"; CHECK_EQ(to_json_string(x, 2), out); } } } } CAF_TEST_FIXTURE_SCOPE_END() <|endoftext|>
<commit_before>//===- FuzzerTraceState.cpp - Trace-based fuzzer mutator ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Data tracing. //===----------------------------------------------------------------------===// #include "FuzzerDictionary.h" #include "FuzzerInternal.h" #include "FuzzerIO.h" #include "FuzzerMutate.h" #include "FuzzerRandom.h" #include "FuzzerTracePC.h" #include <algorithm> #include <cstring> #include <map> #include <set> #include <thread> namespace fuzzer { // For now, very simple: put Size bytes of Data at position Pos. struct TraceBasedMutation { uint32_t Pos; Word W; }; // Declared as static globals for faster checks inside the hooks. static bool RecordingMemcmp = false; static bool RecordingMemmem = false; static bool DoingMyOwnMemmem = false; ScopedDoingMyOwnMemmem::ScopedDoingMyOwnMemmem() { DoingMyOwnMemmem = true; } ScopedDoingMyOwnMemmem::~ScopedDoingMyOwnMemmem() { DoingMyOwnMemmem = false; } class TraceState { public: TraceState(MutationDispatcher &MD, const FuzzingOptions &Options, const Fuzzer *F) : MD(MD), Options(Options), F(F) {} void TraceMemcmpCallback(size_t CmpSize, const uint8_t *Data1, const uint8_t *Data2); void TraceSwitchCallback(uintptr_t PC, size_t ValSizeInBits, uint64_t Val, size_t NumCases, uint64_t *Cases); int TryToAddDesiredData(uint64_t PresentData, uint64_t DesiredData, size_t DataSize); int TryToAddDesiredData(const uint8_t *PresentData, const uint8_t *DesiredData, size_t DataSize); void StartTraceRecording() { if (!Options.UseMemcmp) return; RecordingMemcmp = Options.UseMemcmp; RecordingMemmem = Options.UseMemmem; NumMutations = 0; InterestingWords.clear(); MD.ClearAutoDictionary(); } void StopTraceRecording() { if (!RecordingMemcmp) return; RecordingMemcmp = false; for (size_t i = 0; i < NumMutations; i++) { auto &M = Mutations[i]; if (Options.Verbosity >= 2) { AutoDictUnitCounts[M.W]++; AutoDictAdds++; if ((AutoDictAdds & (AutoDictAdds - 1)) == 0) { typedef std::pair<size_t, Word> CU; std::vector<CU> CountedUnits; for (auto &I : AutoDictUnitCounts) CountedUnits.push_back(std::make_pair(I.second, I.first)); std::sort(CountedUnits.begin(), CountedUnits.end(), [](const CU &a, const CU &b) { return a.first > b.first; }); Printf("AutoDict:\n"); for (auto &I : CountedUnits) { Printf(" %zd ", I.first); PrintASCII(I.second.data(), I.second.size()); Printf("\n"); } } } MD.AddWordToAutoDictionary({M.W, M.Pos}); } for (auto &W : InterestingWords) MD.AddWordToAutoDictionary({W}); } void AddMutation(uint32_t Pos, uint32_t Size, const uint8_t *Data) { if (NumMutations >= kMaxMutations) return; auto &M = Mutations[NumMutations++]; M.Pos = Pos; M.W.Set(Data, Size); } void AddMutation(uint32_t Pos, uint32_t Size, uint64_t Data) { assert(Size <= sizeof(Data)); AddMutation(Pos, Size, reinterpret_cast<uint8_t*>(&Data)); } void AddInterestingWord(const uint8_t *Data, size_t Size) { if (!RecordingMemmem || !F->InFuzzingThread()) return; if (Size <= 1) return; Size = std::min(Size, Word::GetMaxSize()); Word W(Data, Size); InterestingWords.insert(W); } private: bool IsTwoByteData(uint64_t Data) { int64_t Signed = static_cast<int64_t>(Data); Signed >>= 16; return Signed == 0 || Signed == -1L; } // We don't want to create too many trace-based mutations as it is both // expensive and useless. So after some number of mutations is collected, // start rejecting some of them. The more there are mutations the more we // reject. bool WantToHandleOneMoreMutation() { const size_t FirstN = 64; // Gladly handle first N mutations. if (NumMutations <= FirstN) return true; size_t Diff = NumMutations - FirstN; size_t DiffLog = sizeof(long) * 8 - __builtin_clzl((long)Diff); assert(DiffLog > 0 && DiffLog < 64); bool WantThisOne = MD.GetRand()(1 << DiffLog) == 0; // 1 out of DiffLog. return WantThisOne; } static const size_t kMaxMutations = 1 << 16; size_t NumMutations; TraceBasedMutation Mutations[kMaxMutations]; // TODO: std::set is too inefficient, need to have a custom DS here. std::set<Word> InterestingWords; MutationDispatcher &MD; const FuzzingOptions Options; const Fuzzer *F; std::map<Word, size_t> AutoDictUnitCounts; size_t AutoDictAdds = 0; }; int TraceState::TryToAddDesiredData(uint64_t PresentData, uint64_t DesiredData, size_t DataSize) { if (NumMutations >= kMaxMutations || !WantToHandleOneMoreMutation()) return 0; ScopedDoingMyOwnMemmem scoped_doing_my_own_memmem; const uint8_t *UnitData; auto UnitSize = F->GetCurrentUnitInFuzzingThead(&UnitData); int Res = 0; const uint8_t *Beg = UnitData; const uint8_t *End = Beg + UnitSize; for (const uint8_t *Cur = Beg; Cur < End; Cur++) { Cur = (uint8_t *)SearchMemory(Cur, End - Cur, &PresentData, DataSize); if (!Cur) break; size_t Pos = Cur - Beg; assert(Pos < UnitSize); AddMutation(Pos, DataSize, DesiredData); AddMutation(Pos, DataSize, DesiredData + 1); AddMutation(Pos, DataSize, DesiredData - 1); Res++; } return Res; } int TraceState::TryToAddDesiredData(const uint8_t *PresentData, const uint8_t *DesiredData, size_t DataSize) { if (NumMutations >= kMaxMutations || !WantToHandleOneMoreMutation()) return 0; ScopedDoingMyOwnMemmem scoped_doing_my_own_memmem; const uint8_t *UnitData; auto UnitSize = F->GetCurrentUnitInFuzzingThead(&UnitData); int Res = 0; const uint8_t *Beg = UnitData; const uint8_t *End = Beg + UnitSize; for (const uint8_t *Cur = Beg; Cur < End; Cur++) { Cur = (uint8_t *)SearchMemory(Cur, End - Cur, PresentData, DataSize); if (!Cur) break; size_t Pos = Cur - Beg; assert(Pos < UnitSize); AddMutation(Pos, DataSize, DesiredData); Res++; } return Res; } void TraceState::TraceMemcmpCallback(size_t CmpSize, const uint8_t *Data1, const uint8_t *Data2) { if (!RecordingMemcmp || !F->InFuzzingThread()) return; CmpSize = std::min(CmpSize, Word::GetMaxSize()); int Added2 = TryToAddDesiredData(Data1, Data2, CmpSize); int Added1 = TryToAddDesiredData(Data2, Data1, CmpSize); if ((Added1 || Added2) && Options.Verbosity >= 3) { Printf("MemCmp Added %d%d: ", Added1, Added2); if (Added1) PrintASCII(Data1, CmpSize); if (Added2) PrintASCII(Data2, CmpSize); Printf("\n"); } } void TraceState::TraceSwitchCallback(uintptr_t PC, size_t ValSizeInBits, uint64_t Val, size_t NumCases, uint64_t *Cases) { if (F->InFuzzingThread()) return; size_t ValSize = ValSizeInBits / 8; bool TryShort = IsTwoByteData(Val); for (size_t i = 0; i < NumCases; i++) TryShort &= IsTwoByteData(Cases[i]); if (Options.Verbosity >= 3) Printf("TraceSwitch: %p %zd # %zd; TryShort %d\n", PC, Val, NumCases, TryShort); for (size_t i = 0; i < NumCases; i++) { TryToAddDesiredData(Val, Cases[i], ValSize); if (TryShort) TryToAddDesiredData(Val, Cases[i], 2); } } static TraceState *TS; void Fuzzer::StartTraceRecording() { if (!TS) return; TS->StartTraceRecording(); } void Fuzzer::StopTraceRecording() { if (!TS) return; TS->StopTraceRecording(); } void Fuzzer::InitializeTraceState() { if (!Options.UseMemcmp) return; TS = new TraceState(MD, Options, this); } static size_t InternalStrnlen(const char *S, size_t MaxLen) { size_t Len = 0; for (; Len < MaxLen && S[Len]; Len++) {} return Len; } } // namespace fuzzer using fuzzer::TS; using fuzzer::RecordingMemcmp; extern "C" { // We may need to avoid defining weak hooks to stay compatible with older clang. #ifndef LLVM_FUZZER_DEFINES_SANITIZER_WEAK_HOOOKS # define LLVM_FUZZER_DEFINES_SANITIZER_WEAK_HOOOKS 1 #endif #if LLVM_FUZZER_DEFINES_SANITIZER_WEAK_HOOOKS void __sanitizer_weak_hook_memcmp(void *caller_pc, const void *s1, const void *s2, size_t n, int result) { fuzzer::TPC.AddValueForMemcmp(caller_pc, s1, s2, n); if (!RecordingMemcmp) return; if (result == 0) return; // No reason to mutate. if (n <= 1) return; // Not interesting. TS->TraceMemcmpCallback(n, reinterpret_cast<const uint8_t *>(s1), reinterpret_cast<const uint8_t *>(s2)); } void __sanitizer_weak_hook_strncmp(void *caller_pc, const char *s1, const char *s2, size_t n, int result) { fuzzer::TPC.AddValueForStrcmp(caller_pc, s1, s2, n); if (!RecordingMemcmp) return; if (result == 0) return; // No reason to mutate. size_t Len1 = fuzzer::InternalStrnlen(s1, n); size_t Len2 = fuzzer::InternalStrnlen(s2, n); n = std::min(n, Len1); n = std::min(n, Len2); if (n <= 1) return; // Not interesting. TS->TraceMemcmpCallback(n, reinterpret_cast<const uint8_t *>(s1), reinterpret_cast<const uint8_t *>(s2)); } void __sanitizer_weak_hook_strcmp(void *caller_pc, const char *s1, const char *s2, int result) { fuzzer::TPC.AddValueForStrcmp(caller_pc, s1, s2, 64); if (!RecordingMemcmp) return; if (result == 0) return; // No reason to mutate. size_t Len1 = strlen(s1); size_t Len2 = strlen(s2); size_t N = std::min(Len1, Len2); if (N <= 1) return; // Not interesting. TS->TraceMemcmpCallback(N, reinterpret_cast<const uint8_t *>(s1), reinterpret_cast<const uint8_t *>(s2)); } void __sanitizer_weak_hook_strncasecmp(void *called_pc, const char *s1, const char *s2, size_t n, int result) { return __sanitizer_weak_hook_strncmp(called_pc, s1, s2, n, result); } void __sanitizer_weak_hook_strcasecmp(void *called_pc, const char *s1, const char *s2, int result) { return __sanitizer_weak_hook_strcmp(called_pc, s1, s2, result); } void __sanitizer_weak_hook_strstr(void *called_pc, const char *s1, const char *s2, char *result) { TS->AddInterestingWord(reinterpret_cast<const uint8_t *>(s2), strlen(s2)); } void __sanitizer_weak_hook_strcasestr(void *called_pc, const char *s1, const char *s2, char *result) { TS->AddInterestingWord(reinterpret_cast<const uint8_t *>(s2), strlen(s2)); } void __sanitizer_weak_hook_memmem(void *called_pc, const void *s1, size_t len1, const void *s2, size_t len2, void *result) { if (fuzzer::DoingMyOwnMemmem) return; TS->AddInterestingWord(reinterpret_cast<const uint8_t *>(s2), len2); } #endif // LLVM_FUZZER_DEFINES_SANITIZER_WEAK_HOOOKS } // extern "C" <commit_msg>[libFuzzer] remove dead code, NFC<commit_after>//===- FuzzerTraceState.cpp - Trace-based fuzzer mutator ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Data tracing. //===----------------------------------------------------------------------===// #include "FuzzerDictionary.h" #include "FuzzerInternal.h" #include "FuzzerIO.h" #include "FuzzerMutate.h" #include "FuzzerRandom.h" #include "FuzzerTracePC.h" #include <algorithm> #include <cstring> #include <map> #include <set> #include <thread> namespace fuzzer { // For now, very simple: put Size bytes of Data at position Pos. struct TraceBasedMutation { uint32_t Pos; Word W; }; // Declared as static globals for faster checks inside the hooks. static bool RecordingMemcmp = false; static bool RecordingMemmem = false; static bool DoingMyOwnMemmem = false; ScopedDoingMyOwnMemmem::ScopedDoingMyOwnMemmem() { DoingMyOwnMemmem = true; } ScopedDoingMyOwnMemmem::~ScopedDoingMyOwnMemmem() { DoingMyOwnMemmem = false; } class TraceState { public: TraceState(MutationDispatcher &MD, const FuzzingOptions &Options, const Fuzzer *F) : MD(MD), Options(Options), F(F) {} void TraceMemcmpCallback(size_t CmpSize, const uint8_t *Data1, const uint8_t *Data2); int TryToAddDesiredData(const uint8_t *PresentData, const uint8_t *DesiredData, size_t DataSize); void StartTraceRecording() { if (!Options.UseMemcmp) return; RecordingMemcmp = Options.UseMemcmp; RecordingMemmem = Options.UseMemmem; NumMutations = 0; InterestingWords.clear(); MD.ClearAutoDictionary(); } void StopTraceRecording() { if (!RecordingMemcmp) return; RecordingMemcmp = false; for (size_t i = 0; i < NumMutations; i++) { auto &M = Mutations[i]; if (Options.Verbosity >= 2) { AutoDictUnitCounts[M.W]++; AutoDictAdds++; if ((AutoDictAdds & (AutoDictAdds - 1)) == 0) { typedef std::pair<size_t, Word> CU; std::vector<CU> CountedUnits; for (auto &I : AutoDictUnitCounts) CountedUnits.push_back(std::make_pair(I.second, I.first)); std::sort(CountedUnits.begin(), CountedUnits.end(), [](const CU &a, const CU &b) { return a.first > b.first; }); Printf("AutoDict:\n"); for (auto &I : CountedUnits) { Printf(" %zd ", I.first); PrintASCII(I.second.data(), I.second.size()); Printf("\n"); } } } MD.AddWordToAutoDictionary({M.W, M.Pos}); } for (auto &W : InterestingWords) MD.AddWordToAutoDictionary({W}); } void AddMutation(uint32_t Pos, uint32_t Size, const uint8_t *Data) { if (NumMutations >= kMaxMutations) return; auto &M = Mutations[NumMutations++]; M.Pos = Pos; M.W.Set(Data, Size); } void AddMutation(uint32_t Pos, uint32_t Size, uint64_t Data) { assert(Size <= sizeof(Data)); AddMutation(Pos, Size, reinterpret_cast<uint8_t*>(&Data)); } void AddInterestingWord(const uint8_t *Data, size_t Size) { if (!RecordingMemmem || !F->InFuzzingThread()) return; if (Size <= 1) return; Size = std::min(Size, Word::GetMaxSize()); Word W(Data, Size); InterestingWords.insert(W); } private: bool IsTwoByteData(uint64_t Data) { int64_t Signed = static_cast<int64_t>(Data); Signed >>= 16; return Signed == 0 || Signed == -1L; } // We don't want to create too many trace-based mutations as it is both // expensive and useless. So after some number of mutations is collected, // start rejecting some of them. The more there are mutations the more we // reject. bool WantToHandleOneMoreMutation() { const size_t FirstN = 64; // Gladly handle first N mutations. if (NumMutations <= FirstN) return true; size_t Diff = NumMutations - FirstN; size_t DiffLog = sizeof(long) * 8 - __builtin_clzl((long)Diff); assert(DiffLog > 0 && DiffLog < 64); bool WantThisOne = MD.GetRand()(1 << DiffLog) == 0; // 1 out of DiffLog. return WantThisOne; } static const size_t kMaxMutations = 1 << 16; size_t NumMutations; TraceBasedMutation Mutations[kMaxMutations]; // TODO: std::set is too inefficient, need to have a custom DS here. std::set<Word> InterestingWords; MutationDispatcher &MD; const FuzzingOptions Options; const Fuzzer *F; std::map<Word, size_t> AutoDictUnitCounts; size_t AutoDictAdds = 0; }; int TraceState::TryToAddDesiredData(const uint8_t *PresentData, const uint8_t *DesiredData, size_t DataSize) { if (NumMutations >= kMaxMutations || !WantToHandleOneMoreMutation()) return 0; ScopedDoingMyOwnMemmem scoped_doing_my_own_memmem; const uint8_t *UnitData; auto UnitSize = F->GetCurrentUnitInFuzzingThead(&UnitData); int Res = 0; const uint8_t *Beg = UnitData; const uint8_t *End = Beg + UnitSize; for (const uint8_t *Cur = Beg; Cur < End; Cur++) { Cur = (uint8_t *)SearchMemory(Cur, End - Cur, PresentData, DataSize); if (!Cur) break; size_t Pos = Cur - Beg; assert(Pos < UnitSize); AddMutation(Pos, DataSize, DesiredData); Res++; } return Res; } void TraceState::TraceMemcmpCallback(size_t CmpSize, const uint8_t *Data1, const uint8_t *Data2) { if (!RecordingMemcmp || !F->InFuzzingThread()) return; CmpSize = std::min(CmpSize, Word::GetMaxSize()); int Added2 = TryToAddDesiredData(Data1, Data2, CmpSize); int Added1 = TryToAddDesiredData(Data2, Data1, CmpSize); if ((Added1 || Added2) && Options.Verbosity >= 3) { Printf("MemCmp Added %d%d: ", Added1, Added2); if (Added1) PrintASCII(Data1, CmpSize); if (Added2) PrintASCII(Data2, CmpSize); Printf("\n"); } } static TraceState *TS; void Fuzzer::StartTraceRecording() { if (!TS) return; TS->StartTraceRecording(); } void Fuzzer::StopTraceRecording() { if (!TS) return; TS->StopTraceRecording(); } void Fuzzer::InitializeTraceState() { if (!Options.UseMemcmp) return; TS = new TraceState(MD, Options, this); } static size_t InternalStrnlen(const char *S, size_t MaxLen) { size_t Len = 0; for (; Len < MaxLen && S[Len]; Len++) {} return Len; } } // namespace fuzzer using fuzzer::TS; using fuzzer::RecordingMemcmp; extern "C" { // We may need to avoid defining weak hooks to stay compatible with older clang. #ifndef LLVM_FUZZER_DEFINES_SANITIZER_WEAK_HOOOKS # define LLVM_FUZZER_DEFINES_SANITIZER_WEAK_HOOOKS 1 #endif #if LLVM_FUZZER_DEFINES_SANITIZER_WEAK_HOOOKS void __sanitizer_weak_hook_memcmp(void *caller_pc, const void *s1, const void *s2, size_t n, int result) { fuzzer::TPC.AddValueForMemcmp(caller_pc, s1, s2, n); if (!RecordingMemcmp) return; if (result == 0) return; // No reason to mutate. if (n <= 1) return; // Not interesting. TS->TraceMemcmpCallback(n, reinterpret_cast<const uint8_t *>(s1), reinterpret_cast<const uint8_t *>(s2)); } void __sanitizer_weak_hook_strncmp(void *caller_pc, const char *s1, const char *s2, size_t n, int result) { fuzzer::TPC.AddValueForStrcmp(caller_pc, s1, s2, n); if (!RecordingMemcmp) return; if (result == 0) return; // No reason to mutate. size_t Len1 = fuzzer::InternalStrnlen(s1, n); size_t Len2 = fuzzer::InternalStrnlen(s2, n); n = std::min(n, Len1); n = std::min(n, Len2); if (n <= 1) return; // Not interesting. TS->TraceMemcmpCallback(n, reinterpret_cast<const uint8_t *>(s1), reinterpret_cast<const uint8_t *>(s2)); } void __sanitizer_weak_hook_strcmp(void *caller_pc, const char *s1, const char *s2, int result) { fuzzer::TPC.AddValueForStrcmp(caller_pc, s1, s2, 64); if (!RecordingMemcmp) return; if (result == 0) return; // No reason to mutate. size_t Len1 = strlen(s1); size_t Len2 = strlen(s2); size_t N = std::min(Len1, Len2); if (N <= 1) return; // Not interesting. TS->TraceMemcmpCallback(N, reinterpret_cast<const uint8_t *>(s1), reinterpret_cast<const uint8_t *>(s2)); } void __sanitizer_weak_hook_strncasecmp(void *called_pc, const char *s1, const char *s2, size_t n, int result) { return __sanitizer_weak_hook_strncmp(called_pc, s1, s2, n, result); } void __sanitizer_weak_hook_strcasecmp(void *called_pc, const char *s1, const char *s2, int result) { return __sanitizer_weak_hook_strcmp(called_pc, s1, s2, result); } void __sanitizer_weak_hook_strstr(void *called_pc, const char *s1, const char *s2, char *result) { TS->AddInterestingWord(reinterpret_cast<const uint8_t *>(s2), strlen(s2)); } void __sanitizer_weak_hook_strcasestr(void *called_pc, const char *s1, const char *s2, char *result) { TS->AddInterestingWord(reinterpret_cast<const uint8_t *>(s2), strlen(s2)); } void __sanitizer_weak_hook_memmem(void *called_pc, const void *s1, size_t len1, const void *s2, size_t len2, void *result) { if (fuzzer::DoingMyOwnMemmem) return; TS->AddInterestingWord(reinterpret_cast<const uint8_t *>(s2), len2); } #endif // LLVM_FUZZER_DEFINES_SANITIZER_WEAK_HOOOKS } // extern "C" <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// @brief task for http communication /// /// @file /// /// DISCLAIMER /// /// Copyright 2010-2011 triagens GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Dr. Frank Celler /// @author Achim Brandt /// @author Copyright 2009-2011, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "HttpCommTask.h" #include <Basics/StringUtils.h> #include <Rest/HttpRequest.h> #include <Rest/HttpResponse.h> #include "Scheduler/Scheduler.h" #include "GeneralServer/GeneralFigures.h" #include "HttpServer/HttpHandlerFactory.h" #include "HttpServer/HttpHandler.h" #include "HttpServer/HttpServerImpl.h" using namespace triagens::basics; using namespace triagens::rest::GeneralFigures; namespace triagens { namespace rest { // ----------------------------------------------------------------------------- // constructors and destructors // ----------------------------------------------------------------------------- HttpCommTask::HttpCommTask (HttpServerImpl* server, socket_t fd, ConnectionInfo const& info) : Task("HttpCommTask"), GeneralCommTask<HttpServerImpl, HttpHandlerFactory>(server, fd, info), _handler(0) { incCounter<GeneralServerStatistics::httpAccessor>(); } HttpCommTask::~HttpCommTask () { decCounter<GeneralServerStatistics::httpAccessor>(); destroyHandler(); } // ----------------------------------------------------------------------------- // GeneralCommTask methods // ----------------------------------------------------------------------------- bool HttpCommTask::processRead () { if (requestPending || readBuffer->c_str() == 0) { return true; } bool handleRequest = false; if (! readRequestBody) { const char * ptr = readBuffer->c_str() + readPosition; // TODO FIXME: HTTP request might be shorter than 4 bytes if malformed const char * end = readBuffer->end() - 3; // TODO FIXME: HTTP request might not contain \r\n\r\n at all if malformed for (; ptr < end; ptr++) { if (ptr[0] == '\r' && ptr[1] == '\n' && ptr[2] == '\r' && ptr[3] == '\n') { break; } } size_t headerLength = ptr - readBuffer->c_str(); if (headerLength > maximalHeaderSize) { LOGGER_WARNING << "maximal header size is " << maximalHeaderSize << ", request header size is " << headerLength; return false; } if (ptr < end) { readPosition = ptr - readBuffer->c_str() + 4; LOGGER_TRACE << "HTTP READ FOR " << static_cast<Task*>(this) << ":\n" << string(readBuffer->c_str(), readPosition); // check that we know, how to serve this request request = server->createRequest(readBuffer->c_str(), readPosition); if (request == 0) { LOGGER_ERROR << "cannot generate request"; return false; } // update the connection information, i. e. client and server addresses and ports request->setConnectionInfo(connectionInfo); LOGGER_TRACE << "server port = " << connectionInfo.serverPort << ", client port = " << connectionInfo.clientPort; // set body start to current position bodyPosition = readPosition; // and different methods switch (request->requestType()) { case HttpRequest::HTTP_REQUEST_GET: case HttpRequest::HTTP_REQUEST_DELETE: case HttpRequest::HTTP_REQUEST_HEAD: bodyLength = request->contentLength(); if (bodyLength > 0) { LOGGER_WARNING << "received http GET/DELETE/HEAD request with body length, this should not happen"; readRequestBody = true; } else { handleRequest = true; } break; case HttpRequest::HTTP_REQUEST_POST: case HttpRequest::HTTP_REQUEST_PUT: bodyLength = request->contentLength(); if (bodyLength > 0) { readRequestBody = true; } else { handleRequest = true; } break; default: LOGGER_WARNING << "got corrupted HTTP request '" << string(readBuffer->c_str(), (readPosition < 6 ? readPosition : 6)) << "'"; return false; } // check for a 100-continue if (readRequestBody) { bool found; string const& expect = request->header("expect", found); if (found && StringUtils::trim(expect) == "100-continue") { LOGGER_TRACE << "received a 100-continue request"; StringBuffer* buffer = new StringBuffer(TRI_UNKNOWN_MEM_ZONE); buffer->appendText("HTTP/1.1 100 (Continue)\r\n\r\n"); writeBuffers.push_back(buffer); fillWriteBuffer(); } } } else { if (readBuffer->c_str() < end) { readPosition = end - readBuffer->c_str(); } } } // readRequestBody might have changed, so cannot use else if (readRequestBody) { if (bodyLength > maximalBodySize) { LOGGER_WARNING << "maximal body size is " << maximalBodySize << ", request body size is " << bodyLength; return false; } if (readBuffer->length() - bodyPosition < bodyLength) { return true; } // read "bodyLength" from read buffer and add this body to "httpRequest" request->setBody(readBuffer->c_str() + bodyPosition, bodyLength); LOGGER_TRACE << string(readBuffer->c_str() + bodyPosition, bodyLength); // remove body from read buffer and reset read position readRequestBody = false; handleRequest = true; } // we have to delete request in here or pass it to a handler, which will delete it if (handleRequest) { readBuffer->erase_front(bodyPosition + bodyLength); requestPending = true; string connectionType = StringUtils::tolower(StringUtils::trim(request->header("connection"))); if (connectionType == "close") { LOGGER_DEBUG << "connection close requested by client"; closeRequested = true; } else if (server->getCloseWithoutKeepAlive() && connectionType != "keep-alive") { LOGGER_DEBUG << "no keep-alive, connection close requested by client"; closeRequested = true; } readPosition = 0; bodyPosition = 0; bodyLength = 0; _handler = server->createHandler(request); bool ok = false; if (_handler == 0) { LOGGER_TRACE << "no handler is known, giving up"; delete request; request = 0; HttpResponse response(HttpResponse::NOT_FOUND); handleResponse(&response); } else { // let the handler know the comm task _handler->setTask(this); request = 0; ok = server->handleRequest(this, _handler); if (! ok) { HttpResponse response(HttpResponse::SERVER_ERROR); handleResponse(&response); } } return processRead(); } return true; } void HttpCommTask::addResponse (HttpResponse* response) { StringBuffer * buffer; // save header buffer = new StringBuffer(TRI_UNKNOWN_MEM_ZONE); response->writeHeader(buffer); buffer->appendText(response->body()); writeBuffers.push_back(buffer); LOGGER_TRACE << "HTTP WRITE FOR " << static_cast<Task*>(this) << ":\n" << buffer->c_str(); // clear body response->body().clear(); // start output fillWriteBuffer(); } //////////////////////////////////////////////////////////////////////////////// /// @brief destroy the handler if any present //////////////////////////////////////////////////////////////////////////////// void HttpCommTask::destroyHandler () { if (_handler) { _handler->setTask(0); server->destroyHandler(_handler); _handler = 0; } } } } <commit_msg>removed bogus FIXME comments<commit_after>//////////////////////////////////////////////////////////////////////////////// /// @brief task for http communication /// /// @file /// /// DISCLAIMER /// /// Copyright 2010-2011 triagens GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Dr. Frank Celler /// @author Achim Brandt /// @author Copyright 2009-2011, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "HttpCommTask.h" #include <Basics/StringUtils.h> #include <Rest/HttpRequest.h> #include <Rest/HttpResponse.h> #include "Scheduler/Scheduler.h" #include "GeneralServer/GeneralFigures.h" #include "HttpServer/HttpHandlerFactory.h" #include "HttpServer/HttpHandler.h" #include "HttpServer/HttpServerImpl.h" using namespace triagens::basics; using namespace triagens::rest::GeneralFigures; namespace triagens { namespace rest { // ----------------------------------------------------------------------------- // constructors and destructors // ----------------------------------------------------------------------------- HttpCommTask::HttpCommTask (HttpServerImpl* server, socket_t fd, ConnectionInfo const& info) : Task("HttpCommTask"), GeneralCommTask<HttpServerImpl, HttpHandlerFactory>(server, fd, info), _handler(0) { incCounter<GeneralServerStatistics::httpAccessor>(); } HttpCommTask::~HttpCommTask () { decCounter<GeneralServerStatistics::httpAccessor>(); destroyHandler(); } // ----------------------------------------------------------------------------- // GeneralCommTask methods // ----------------------------------------------------------------------------- bool HttpCommTask::processRead () { if (requestPending || readBuffer->c_str() == 0) { return true; } bool handleRequest = false; if (! readRequestBody) { const char * ptr = readBuffer->c_str() + readPosition; const char * end = readBuffer->end() - 3; for (; ptr < end; ptr++) { if (ptr[0] == '\r' && ptr[1] == '\n' && ptr[2] == '\r' && ptr[3] == '\n') { break; } } size_t headerLength = ptr - readBuffer->c_str(); if (headerLength > maximalHeaderSize) { LOGGER_WARNING << "maximal header size is " << maximalHeaderSize << ", request header size is " << headerLength; return false; } if (ptr < end) { readPosition = ptr - readBuffer->c_str() + 4; LOGGER_TRACE << "HTTP READ FOR " << static_cast<Task*>(this) << ":\n" << string(readBuffer->c_str(), readPosition); // check that we know, how to serve this request request = server->createRequest(readBuffer->c_str(), readPosition); if (request == 0) { LOGGER_ERROR << "cannot generate request"; return false; } // update the connection information, i. e. client and server addresses and ports request->setConnectionInfo(connectionInfo); LOGGER_TRACE << "server port = " << connectionInfo.serverPort << ", client port = " << connectionInfo.clientPort; // set body start to current position bodyPosition = readPosition; // and different methods switch (request->requestType()) { case HttpRequest::HTTP_REQUEST_GET: case HttpRequest::HTTP_REQUEST_DELETE: case HttpRequest::HTTP_REQUEST_HEAD: bodyLength = request->contentLength(); if (bodyLength > 0) { LOGGER_WARNING << "received http GET/DELETE/HEAD request with body length, this should not happen"; readRequestBody = true; } else { handleRequest = true; } break; case HttpRequest::HTTP_REQUEST_POST: case HttpRequest::HTTP_REQUEST_PUT: bodyLength = request->contentLength(); if (bodyLength > 0) { readRequestBody = true; } else { handleRequest = true; } break; default: LOGGER_WARNING << "got corrupted HTTP request '" << string(readBuffer->c_str(), (readPosition < 6 ? readPosition : 6)) << "'"; return false; } // check for a 100-continue if (readRequestBody) { bool found; string const& expect = request->header("expect", found); if (found && StringUtils::trim(expect) == "100-continue") { LOGGER_TRACE << "received a 100-continue request"; StringBuffer* buffer = new StringBuffer(TRI_UNKNOWN_MEM_ZONE); buffer->appendText("HTTP/1.1 100 (Continue)\r\n\r\n"); writeBuffers.push_back(buffer); fillWriteBuffer(); } } } else { if (readBuffer->c_str() < end) { readPosition = end - readBuffer->c_str(); } } } // readRequestBody might have changed, so cannot use else if (readRequestBody) { if (bodyLength > maximalBodySize) { LOGGER_WARNING << "maximal body size is " << maximalBodySize << ", request body size is " << bodyLength; return false; } if (readBuffer->length() - bodyPosition < bodyLength) { return true; } // read "bodyLength" from read buffer and add this body to "httpRequest" request->setBody(readBuffer->c_str() + bodyPosition, bodyLength); LOGGER_TRACE << string(readBuffer->c_str() + bodyPosition, bodyLength); // remove body from read buffer and reset read position readRequestBody = false; handleRequest = true; } // we have to delete request in here or pass it to a handler, which will delete it if (handleRequest) { readBuffer->erase_front(bodyPosition + bodyLength); requestPending = true; string connectionType = StringUtils::tolower(StringUtils::trim(request->header("connection"))); if (connectionType == "close") { LOGGER_DEBUG << "connection close requested by client"; closeRequested = true; } else if (server->getCloseWithoutKeepAlive() && connectionType != "keep-alive") { LOGGER_DEBUG << "no keep-alive, connection close requested by client"; closeRequested = true; } readPosition = 0; bodyPosition = 0; bodyLength = 0; _handler = server->createHandler(request); bool ok = false; if (_handler == 0) { LOGGER_TRACE << "no handler is known, giving up"; delete request; request = 0; HttpResponse response(HttpResponse::NOT_FOUND); handleResponse(&response); } else { // let the handler know the comm task _handler->setTask(this); request = 0; ok = server->handleRequest(this, _handler); if (! ok) { HttpResponse response(HttpResponse::SERVER_ERROR); handleResponse(&response); } } return processRead(); } return true; } void HttpCommTask::addResponse (HttpResponse* response) { StringBuffer * buffer; // save header buffer = new StringBuffer(TRI_UNKNOWN_MEM_ZONE); response->writeHeader(buffer); buffer->appendText(response->body()); writeBuffers.push_back(buffer); LOGGER_TRACE << "HTTP WRITE FOR " << static_cast<Task*>(this) << ":\n" << buffer->c_str(); // clear body response->body().clear(); // start output fillWriteBuffer(); } //////////////////////////////////////////////////////////////////////////////// /// @brief destroy the handler if any present //////////////////////////////////////////////////////////////////////////////// void HttpCommTask::destroyHandler () { if (_handler) { _handler->setTask(0); server->destroyHandler(_handler); _handler = 0; } } } } <|endoftext|>
<commit_before>/* Sirikata * Breakpad.cpp * * Copyright (c) 2011, Ewen Cheslack-Postava * 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 Sirikata 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 <sirikata/core/util/Standard.hh> #include <sirikata/core/service/Breakpad.hpp> #include <sirikata/core/util/Platform.hpp> #include <sirikata/core/options/CommonOptions.hpp> #ifdef HAVE_BREAKPAD #if SIRIKATA_PLATFORM == PLATFORM_WINDOWS #include <client/windows/handler/exception_handler.h> #elif SIRIKATA_PLATFORM == PLATFORM_LINUX #include <client/linux/handler/exception_handler.h> #endif #endif // HAVE_BREAKPAD namespace Sirikata { namespace Breakpad { #ifdef HAVE_BREAKPAD // Each implementation of ExceptionHandler and the setup are different enough // that these are worth just completely separating. Each just needs to setup the // exception handler. Currently, all should set it up to save minidumps to the // current directory. #if SIRIKATA_PLATFORM == PLATFORM_WINDOWS namespace { static google_breakpad::ExceptionHandler* breakpad_handler = NULL; static std::string breakpad_url; std::string wchar_to_string(const wchar_t* orig) { size_t origsize = wcslen(orig) + 1; const size_t newsize = origsize; size_t convertedChars = 0; char* nstring = new char[newsize]; wcstombs_s(&convertedChars, nstring, origsize, orig, _TRUNCATE); std::string res(nstring); delete nstring; return res; } bool finishedDump(const wchar_t* dump_path, const wchar_t* minidump_id, void* context, EXCEPTION_POINTERS* exinfo, MDRawAssertionInfo* assertion, bool succeeded) { printf("Finished breakpad dump at %s/%s.dmp: success %d\n", dump_path, minidump_id, succeeded ? 1 : -1); if (breakpad_url.empty()) return succeeded; const char* reporter_name = #if SIRIKATA_DEBUG "crashreporter_d.exe" #else "crashreporter.exe" #endif ; STARTUPINFO info={sizeof(info)}; PROCESS_INFORMATION processInfo; std::string cmd = reporter_name + std::string(" ") + breakpad_url + std::string(" ") + wchar_to_string(dump_path) + std::string(" ") + wchar_to_string(minidump_id); CreateProcess(reporter_name, (LPSTR)cmd.c_str(), NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo); return succeeded; } } void init() { if (breakpad_handler != NULL) return; // This is needed for CRT to not show dialog for invalid param // failures and instead let the code handle it. _CrtSetReportMode(_CRT_ASSERT, 0); breakpad_url = GetOptionValue<String>(OPT_CRASHREPORT_URL); using namespace google_breakpad; breakpad_handler = new ExceptionHandler(L".\\", NULL, finishedDump, NULL, ExceptionHandler::HANDLER_ALL, MiniDumpNormal, NULL, NULL); } #elif SIRIKATA_PLATFORM == PLATFORM_LINUX namespace { static google_breakpad::ExceptionHandler* breakpad_handler = NULL; static std::string breakpad_url; bool finishedDump(const char* dump_path, const char* minidump_id, void* context, bool succeeded) { printf("Finished breakpad dump at %s/%s.dmp: success %d\n", dump_path, minidump_id, succeeded ? 1 : -1); // If no URL, just finish crashing after the dump. if (breakpad_url.empty()) return succeeded; // Fork and exec the crashreporter pid_t pID = fork(); if (pID == 0) { const char* reporter_name = #if SIRIKATA_DEBUG "crashreporter_d" #else "crashreporter" #endif ; execlp(reporter_name, reporter_name, breakpad_url.c_str(), dump_path, minidump_id, (char*)NULL); // If crashreporter not in path, try current directory execl(reporter_name, reporter_name, breakpad_url.c_str(), dump_path, minidump_id, (char*)NULL); } else if (pID < 0) { printf("Failed to fork crashreporter\n"); } return succeeded; } } void init() { if (breakpad_handler != NULL) return; breakpad_url = GetOptionValue<String>(OPT_CRASHREPORT_URL); using namespace google_breakpad; breakpad_handler = new ExceptionHandler("./", NULL, finishedDump, NULL, true); } #elif SIRIKATA_PLATFORM == PLATFORM_MAC // No mac support currently void init() { } #endif #else //def HAVE_BREAKPAD // Dummy implementation void init() { } #endif } // namespace Breakpad } // namespace Sirikata <commit_msg>Only invoke the crash reporter in release builds so that you aren't always thrown into a browser during normal development.<commit_after>/* Sirikata * Breakpad.cpp * * Copyright (c) 2011, Ewen Cheslack-Postava * 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 Sirikata 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 <sirikata/core/util/Standard.hh> #include <sirikata/core/service/Breakpad.hpp> #include <sirikata/core/util/Platform.hpp> #include <sirikata/core/options/CommonOptions.hpp> #ifdef HAVE_BREAKPAD #if SIRIKATA_PLATFORM == PLATFORM_WINDOWS #include <client/windows/handler/exception_handler.h> #elif SIRIKATA_PLATFORM == PLATFORM_LINUX #include <client/linux/handler/exception_handler.h> #endif #endif // HAVE_BREAKPAD namespace Sirikata { namespace Breakpad { #ifdef HAVE_BREAKPAD // Each implementation of ExceptionHandler and the setup are different enough // that these are worth just completely separating. Each just needs to setup the // exception handler. Currently, all should set it up to save minidumps to the // current directory. #if SIRIKATA_PLATFORM == PLATFORM_WINDOWS namespace { static google_breakpad::ExceptionHandler* breakpad_handler = NULL; static std::string breakpad_url; std::string wchar_to_string(const wchar_t* orig) { size_t origsize = wcslen(orig) + 1; const size_t newsize = origsize; size_t convertedChars = 0; char* nstring = new char[newsize]; wcstombs_s(&convertedChars, nstring, origsize, orig, _TRUNCATE); std::string res(nstring); delete nstring; return res; } bool finishedDump(const wchar_t* dump_path, const wchar_t* minidump_id, void* context, EXCEPTION_POINTERS* exinfo, MDRawAssertionInfo* assertion, bool succeeded) { printf("Finished breakpad dump at %s/%s.dmp: success %d\n", dump_path, minidump_id, succeeded ? 1 : -1); // Only run the reporter in release mode. This is a decent heuristic -- // generally you'll only run the debug mode when you have a dev environment. #if SIRIKATA_DEBUG return succeeded; #else if (breakpad_url.empty()) return succeeded; const char* reporter_name = #if SIRIKATA_DEBUG "crashreporter_d.exe" #else "crashreporter.exe" #endif ; STARTUPINFO info={sizeof(info)}; PROCESS_INFORMATION processInfo; std::string cmd = reporter_name + std::string(" ") + breakpad_url + std::string(" ") + wchar_to_string(dump_path) + std::string(" ") + wchar_to_string(minidump_id); CreateProcess(reporter_name, (LPSTR)cmd.c_str(), NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo); return succeeded; #endif // SIRIKATA_DEBUG } } void init() { if (breakpad_handler != NULL) return; // This is needed for CRT to not show dialog for invalid param // failures and instead let the code handle it. _CrtSetReportMode(_CRT_ASSERT, 0); breakpad_url = GetOptionValue<String>(OPT_CRASHREPORT_URL); using namespace google_breakpad; breakpad_handler = new ExceptionHandler(L".\\", NULL, finishedDump, NULL, ExceptionHandler::HANDLER_ALL, MiniDumpNormal, NULL, NULL); } #elif SIRIKATA_PLATFORM == PLATFORM_LINUX namespace { static google_breakpad::ExceptionHandler* breakpad_handler = NULL; static std::string breakpad_url; bool finishedDump(const char* dump_path, const char* minidump_id, void* context, bool succeeded) { printf("Finished breakpad dump at %s/%s.dmp: success %d\n", dump_path, minidump_id, succeeded ? 1 : -1); // Only run the reporter in release mode. This is a decent heuristic -- // generally you'll only run the debug mode when you have a dev environment. #if SIRIKATA_DEBUG return succeeded; #else // If no URL, just finish crashing after the dump. if (breakpad_url.empty()) return succeeded; // Fork and exec the crashreporter pid_t pID = fork(); if (pID == 0) { const char* reporter_name = #if SIRIKATA_DEBUG "crashreporter_d" #else "crashreporter" #endif ; execlp(reporter_name, reporter_name, breakpad_url.c_str(), dump_path, minidump_id, (char*)NULL); // If crashreporter not in path, try current directory execl(reporter_name, reporter_name, breakpad_url.c_str(), dump_path, minidump_id, (char*)NULL); } else if (pID < 0) { printf("Failed to fork crashreporter\n"); } return succeeded; #endif //SIRIKATA_DEBUG } } void init() { if (breakpad_handler != NULL) return; breakpad_url = GetOptionValue<String>(OPT_CRASHREPORT_URL); using namespace google_breakpad; breakpad_handler = new ExceptionHandler("./", NULL, finishedDump, NULL, true); } #elif SIRIKATA_PLATFORM == PLATFORM_MAC // No mac support currently void init() { } #endif #else //def HAVE_BREAKPAD // Dummy implementation void init() { } #endif } // namespace Breakpad } // namespace Sirikata <|endoftext|>
<commit_before>#include "worker.h" #include "utils.h" #include <pynumbuf/serialize.h> extern "C" { static PyObject *RayError; } Status WorkerServiceImpl::ExecuteTask(ServerContext* context, const ExecuteTaskRequest* request, ExecuteTaskReply* reply) { task_ = request->task(); // Copy task RAY_LOG(RAY_INFO, "invoked task " << request->task().name()); Task* taskptr = &task_; send_queue_.send(&taskptr); return Status::OK; } Worker::Worker(const std::string& worker_address, std::shared_ptr<Channel> scheduler_channel, std::shared_ptr<Channel> objstore_channel) : worker_address_(worker_address), scheduler_stub_(Scheduler::NewStub(scheduler_channel)), objstore_stub_(ObjStore::NewStub(objstore_channel)) { receive_queue_.connect(worker_address_, true); connected_ = true; } SubmitTaskReply Worker::submit_task(SubmitTaskRequest* request) { RAY_CHECK(connected_, "Attempted to perform submit_task but failed."); SubmitTaskReply reply; ClientContext context; Status status = scheduler_stub_->SubmitTask(&context, *request, &reply); return reply; } void Worker::register_worker(const std::string& worker_address, const std::string& objstore_address) { RegisterWorkerRequest request; request.set_worker_address(worker_address); request.set_objstore_address(objstore_address); RegisterWorkerReply reply; ClientContext context; Status status = scheduler_stub_->RegisterWorker(&context, request, &reply); workerid_ = reply.workerid(); objstoreid_ = reply.objstoreid(); segmentpool_ = std::make_shared<MemorySegmentPool>(objstoreid_, false); request_obj_queue_.connect(std::string("queue:") + objstore_address + std::string(":obj"), false); std::string queue_name = std::string("queue:") + objstore_address + std::string(":worker:") + std::to_string(workerid_) + std::string(":obj"); receive_obj_queue_.connect(queue_name, true); return; } void Worker::request_object(ObjRef objref) { RAY_CHECK(connected_, "Attempted to perform request_object but failed."); RequestObjRequest request; request.set_workerid(workerid_); request.set_objref(objref); AckReply reply; ClientContext context; Status status = scheduler_stub_->RequestObj(&context, request, &reply); return; } ObjRef Worker::get_objref() { // first get objref for the new object RAY_CHECK(connected_, "Attempted to perform get_objref but failed."); PushObjRequest push_request; PushObjReply push_reply; ClientContext push_context; Status push_status = scheduler_stub_->PushObj(&push_context, push_request, &push_reply); return push_reply.objref(); } slice Worker::get_object(ObjRef objref) { // get_object assumes that objref is a canonical objref RAY_CHECK(connected_, "Attempted to perform get_object but failed."); ObjRequest request; request.workerid = workerid_; request.type = ObjRequestType::GET; request.objref = objref; request_obj_queue_.send(&request); ObjHandle result; receive_obj_queue_.receive(&result); slice slice; slice.data = segmentpool_->get_address(result); slice.len = result.size(); return slice; } // TODO(pcm): More error handling // contained_objrefs is a vector of all the objrefs contained in obj void Worker::put_object(ObjRef objref, const Obj* obj, std::vector<ObjRef> &contained_objrefs) { RAY_CHECK(connected_, "Attempted to perform put_object but failed."); std::string data; obj->SerializeToString(&data); // TODO(pcm): get rid of this serialization ObjRequest request; request.workerid = workerid_; request.type = ObjRequestType::ALLOC; request.objref = objref; request.size = data.size(); request_obj_queue_.send(&request); if (contained_objrefs.size() > 0) { RAY_LOG(RAY_REFCOUNT, "In put_object, calling increment_reference_count for contained objrefs"); increment_reference_count(contained_objrefs); // Notify the scheduler that some object references are serialized in the objstore. } ObjHandle result; receive_obj_queue_.receive(&result); uint8_t* target = segmentpool_->get_address(result); std::memcpy(target, &data[0], data.size()); request.type = ObjRequestType::WORKER_DONE; request.metadata_offset = 0; request_obj_queue_.send(&request); // Notify the scheduler about the objrefs that we are serializing in the objstore. AddContainedObjRefsRequest contained_objrefs_request; contained_objrefs_request.set_objref(objref); for (int i = 0; i < contained_objrefs.size(); ++i) { contained_objrefs_request.add_contained_objref(contained_objrefs[i]); // TODO(rkn): The naming here is bad } AckReply reply; ClientContext context; scheduler_stub_->AddContainedObjRefs(&context, contained_objrefs_request, &reply); } #define CHECK_ARROW_STATUS(s, msg) \ do { \ arrow::Status _s = (s); \ if (!_s.ok()) { \ std::string _errmsg = std::string(msg) + _s.ToString(); \ PyErr_SetString(RayError, _errmsg.c_str()); \ return NULL; \ } \ } while (0); PyObject* Worker::put_arrow(ObjRef objref, PyObject* value) { RAY_CHECK(connected_, "Attempted to perform put_arrow but failed."); ObjRequest request; pynumbuf::PythonObjectWriter writer; int64_t size; CHECK_ARROW_STATUS(writer.AssemblePayload(value), "error during AssemblePayload: "); CHECK_ARROW_STATUS(writer.GetTotalSize(&size), "error during GetTotalSize: "); request.workerid = workerid_; request.type = ObjRequestType::ALLOC; request.objref = objref; request.size = size; request_obj_queue_.send(&request); ObjHandle result; receive_obj_queue_.receive(&result); int64_t metadata_offset; uint8_t* address = segmentpool_->get_address(result); auto source = std::make_shared<BufferMemorySource>(address, size); CHECK_ARROW_STATUS(writer.Write(source.get(), &metadata_offset), "error during Write: "); request.type = ObjRequestType::WORKER_DONE; request.metadata_offset = metadata_offset; request_obj_queue_.send(&request); Py_RETURN_NONE; } PyObject* Worker::get_arrow(ObjRef objref) { RAY_CHECK(connected_, "Attempted to perform get_arrow but failed."); ObjRequest request; request.workerid = workerid_; request.type = ObjRequestType::GET; request.objref = objref; request_obj_queue_.send(&request); ObjHandle result; receive_obj_queue_.receive(&result); uint8_t* address = segmentpool_->get_address(result); auto source = std::make_shared<BufferMemorySource>(address, result.size()); PyObject* value; CHECK_ARROW_STATUS(pynumbuf::ReadPythonObjectFrom(source.get(), result.metadata_offset(), &value), "error during ReadPythonObjectFrom: "); return value; } bool Worker::is_arrow(ObjRef objref) { RAY_CHECK(connected_, "Attempted to perform is_arrow but failed."); ObjRequest request; request.workerid = workerid_; request.type = ObjRequestType::GET; request.objref = objref; request_obj_queue_.send(&request); ObjHandle result; receive_obj_queue_.receive(&result); return result.metadata_offset() != 0; } void Worker::alias_objrefs(ObjRef alias_objref, ObjRef target_objref) { RAY_CHECK(connected_, "Attempted to perform alias_objrefs but failed."); ClientContext context; AliasObjRefsRequest request; request.set_alias_objref(alias_objref); request.set_target_objref(target_objref); AckReply reply; scheduler_stub_->AliasObjRefs(&context, request, &reply); } void Worker::increment_reference_count(std::vector<ObjRef> &objrefs) { if (!connected_) { RAY_LOG(RAY_INFO, "Attempting to increment_reference_count for objrefs, but connected_ = " << connected_ << " so returning instead."); return; } if (objrefs.size() > 0) { ClientContext context; IncrementRefCountRequest request; for (int i = 0; i < objrefs.size(); ++i) { RAY_LOG(RAY_REFCOUNT, "Incrementing reference count for objref " << objrefs[i]); request.add_objref(objrefs[i]); } AckReply reply; scheduler_stub_->IncrementRefCount(&context, request, &reply); } } void Worker::decrement_reference_count(std::vector<ObjRef> &objrefs) { if (!connected_) { RAY_LOG(RAY_INFO, "Attempting to decrement_reference_count, but connected_ = " << connected_ << " so returning instead."); return; } if (objrefs.size() > 0) { ClientContext context; DecrementRefCountRequest request; for (int i = 0; i < objrefs.size(); ++i) { RAY_LOG(RAY_REFCOUNT, "Decrementing reference count for objref " << objrefs[i]); request.add_objref(objrefs[i]); } AckReply reply; scheduler_stub_->DecrementRefCount(&context, request, &reply); } } void Worker::register_function(const std::string& name, size_t num_return_vals) { RAY_CHECK(connected_, "Attempted to perform register_function but failed."); ClientContext context; RegisterFunctionRequest request; request.set_fnname(name); request.set_num_return_vals(num_return_vals); request.set_workerid(workerid_); AckReply reply; scheduler_stub_->RegisterFunction(&context, request, &reply); } Task* Worker::receive_next_task() { Task* task; receive_queue_.receive(&task); return task; } void Worker::notify_task_completed(bool task_succeeded, std::string error_message) { RAY_CHECK(connected_, "Attempted to perform notify_task_completed but failed."); ClientContext context; NotifyTaskCompletedRequest request; request.set_workerid(workerid_); request.set_task_succeeded(task_succeeded); request.set_error_message(error_message); AckReply reply; scheduler_stub_->NotifyTaskCompleted(&context, request, &reply); } void Worker::disconnect() { connected_ = false; } bool Worker::connected() { return connected_; } // TODO(rkn): Should we be using pointers or references? And should they be const? void Worker::scheduler_info(ClientContext &context, SchedulerInfoRequest &request, SchedulerInfoReply &reply) { RAY_CHECK(connected_, "Attempted to get scheduler info but failed."); scheduler_stub_->SchedulerInfo(&context, request, &reply); } // Communication between the WorkerServer and the Worker happens via a message // queue. This is because the Python interpreter needs to be single threaded // (in our case running in the main thread), whereas the WorkerService will // run in a separate thread and potentially utilize multiple threads. void Worker::start_worker_service() { const char* service_addr = worker_address_.c_str(); worker_server_thread_ = std::thread([service_addr]() { std::string service_address(service_addr); std::string::iterator split_point = split_ip_address(service_address); std::string port; port.assign(split_point, service_address.end()); WorkerServiceImpl service(service_address); ServerBuilder builder; builder.AddListeningPort(std::string("0.0.0.0:") + port, grpc::InsecureServerCredentials()); builder.RegisterService(&service); std::unique_ptr<Server> server(builder.BuildAndStart()); RAY_LOG(RAY_INFO, "worker server listening on " << service_address); server->Wait(); }); } <commit_msg>Downgrading reference count logging to DEBUG<commit_after>#include "worker.h" #include "utils.h" #include <pynumbuf/serialize.h> extern "C" { static PyObject *RayError; } Status WorkerServiceImpl::ExecuteTask(ServerContext* context, const ExecuteTaskRequest* request, ExecuteTaskReply* reply) { task_ = request->task(); // Copy task RAY_LOG(RAY_INFO, "invoked task " << request->task().name()); Task* taskptr = &task_; send_queue_.send(&taskptr); return Status::OK; } Worker::Worker(const std::string& worker_address, std::shared_ptr<Channel> scheduler_channel, std::shared_ptr<Channel> objstore_channel) : worker_address_(worker_address), scheduler_stub_(Scheduler::NewStub(scheduler_channel)), objstore_stub_(ObjStore::NewStub(objstore_channel)) { receive_queue_.connect(worker_address_, true); connected_ = true; } SubmitTaskReply Worker::submit_task(SubmitTaskRequest* request) { RAY_CHECK(connected_, "Attempted to perform submit_task but failed."); SubmitTaskReply reply; ClientContext context; Status status = scheduler_stub_->SubmitTask(&context, *request, &reply); return reply; } void Worker::register_worker(const std::string& worker_address, const std::string& objstore_address) { RegisterWorkerRequest request; request.set_worker_address(worker_address); request.set_objstore_address(objstore_address); RegisterWorkerReply reply; ClientContext context; Status status = scheduler_stub_->RegisterWorker(&context, request, &reply); workerid_ = reply.workerid(); objstoreid_ = reply.objstoreid(); segmentpool_ = std::make_shared<MemorySegmentPool>(objstoreid_, false); request_obj_queue_.connect(std::string("queue:") + objstore_address + std::string(":obj"), false); std::string queue_name = std::string("queue:") + objstore_address + std::string(":worker:") + std::to_string(workerid_) + std::string(":obj"); receive_obj_queue_.connect(queue_name, true); return; } void Worker::request_object(ObjRef objref) { RAY_CHECK(connected_, "Attempted to perform request_object but failed."); RequestObjRequest request; request.set_workerid(workerid_); request.set_objref(objref); AckReply reply; ClientContext context; Status status = scheduler_stub_->RequestObj(&context, request, &reply); return; } ObjRef Worker::get_objref() { // first get objref for the new object RAY_CHECK(connected_, "Attempted to perform get_objref but failed."); PushObjRequest push_request; PushObjReply push_reply; ClientContext push_context; Status push_status = scheduler_stub_->PushObj(&push_context, push_request, &push_reply); return push_reply.objref(); } slice Worker::get_object(ObjRef objref) { // get_object assumes that objref is a canonical objref RAY_CHECK(connected_, "Attempted to perform get_object but failed."); ObjRequest request; request.workerid = workerid_; request.type = ObjRequestType::GET; request.objref = objref; request_obj_queue_.send(&request); ObjHandle result; receive_obj_queue_.receive(&result); slice slice; slice.data = segmentpool_->get_address(result); slice.len = result.size(); return slice; } // TODO(pcm): More error handling // contained_objrefs is a vector of all the objrefs contained in obj void Worker::put_object(ObjRef objref, const Obj* obj, std::vector<ObjRef> &contained_objrefs) { RAY_CHECK(connected_, "Attempted to perform put_object but failed."); std::string data; obj->SerializeToString(&data); // TODO(pcm): get rid of this serialization ObjRequest request; request.workerid = workerid_; request.type = ObjRequestType::ALLOC; request.objref = objref; request.size = data.size(); request_obj_queue_.send(&request); if (contained_objrefs.size() > 0) { RAY_LOG(RAY_REFCOUNT, "In put_object, calling increment_reference_count for contained objrefs"); increment_reference_count(contained_objrefs); // Notify the scheduler that some object references are serialized in the objstore. } ObjHandle result; receive_obj_queue_.receive(&result); uint8_t* target = segmentpool_->get_address(result); std::memcpy(target, &data[0], data.size()); request.type = ObjRequestType::WORKER_DONE; request.metadata_offset = 0; request_obj_queue_.send(&request); // Notify the scheduler about the objrefs that we are serializing in the objstore. AddContainedObjRefsRequest contained_objrefs_request; contained_objrefs_request.set_objref(objref); for (int i = 0; i < contained_objrefs.size(); ++i) { contained_objrefs_request.add_contained_objref(contained_objrefs[i]); // TODO(rkn): The naming here is bad } AckReply reply; ClientContext context; scheduler_stub_->AddContainedObjRefs(&context, contained_objrefs_request, &reply); } #define CHECK_ARROW_STATUS(s, msg) \ do { \ arrow::Status _s = (s); \ if (!_s.ok()) { \ std::string _errmsg = std::string(msg) + _s.ToString(); \ PyErr_SetString(RayError, _errmsg.c_str()); \ return NULL; \ } \ } while (0); PyObject* Worker::put_arrow(ObjRef objref, PyObject* value) { RAY_CHECK(connected_, "Attempted to perform put_arrow but failed."); ObjRequest request; pynumbuf::PythonObjectWriter writer; int64_t size; CHECK_ARROW_STATUS(writer.AssemblePayload(value), "error during AssemblePayload: "); CHECK_ARROW_STATUS(writer.GetTotalSize(&size), "error during GetTotalSize: "); request.workerid = workerid_; request.type = ObjRequestType::ALLOC; request.objref = objref; request.size = size; request_obj_queue_.send(&request); ObjHandle result; receive_obj_queue_.receive(&result); int64_t metadata_offset; uint8_t* address = segmentpool_->get_address(result); auto source = std::make_shared<BufferMemorySource>(address, size); CHECK_ARROW_STATUS(writer.Write(source.get(), &metadata_offset), "error during Write: "); request.type = ObjRequestType::WORKER_DONE; request.metadata_offset = metadata_offset; request_obj_queue_.send(&request); Py_RETURN_NONE; } PyObject* Worker::get_arrow(ObjRef objref) { RAY_CHECK(connected_, "Attempted to perform get_arrow but failed."); ObjRequest request; request.workerid = workerid_; request.type = ObjRequestType::GET; request.objref = objref; request_obj_queue_.send(&request); ObjHandle result; receive_obj_queue_.receive(&result); uint8_t* address = segmentpool_->get_address(result); auto source = std::make_shared<BufferMemorySource>(address, result.size()); PyObject* value; CHECK_ARROW_STATUS(pynumbuf::ReadPythonObjectFrom(source.get(), result.metadata_offset(), &value), "error during ReadPythonObjectFrom: "); return value; } bool Worker::is_arrow(ObjRef objref) { RAY_CHECK(connected_, "Attempted to perform is_arrow but failed."); ObjRequest request; request.workerid = workerid_; request.type = ObjRequestType::GET; request.objref = objref; request_obj_queue_.send(&request); ObjHandle result; receive_obj_queue_.receive(&result); return result.metadata_offset() != 0; } void Worker::alias_objrefs(ObjRef alias_objref, ObjRef target_objref) { RAY_CHECK(connected_, "Attempted to perform alias_objrefs but failed."); ClientContext context; AliasObjRefsRequest request; request.set_alias_objref(alias_objref); request.set_target_objref(target_objref); AckReply reply; scheduler_stub_->AliasObjRefs(&context, request, &reply); } void Worker::increment_reference_count(std::vector<ObjRef> &objrefs) { if (!connected_) { RAY_LOG(RAY_DEBUG, "Attempting to increment_reference_count for objrefs, but connected_ = " << connected_ << " so returning instead."); return; } if (objrefs.size() > 0) { ClientContext context; IncrementRefCountRequest request; for (int i = 0; i < objrefs.size(); ++i) { RAY_LOG(RAY_REFCOUNT, "Incrementing reference count for objref " << objrefs[i]); request.add_objref(objrefs[i]); } AckReply reply; scheduler_stub_->IncrementRefCount(&context, request, &reply); } } void Worker::decrement_reference_count(std::vector<ObjRef> &objrefs) { if (!connected_) { RAY_LOG(RAY_DEBUG, "Attempting to decrement_reference_count, but connected_ = " << connected_ << " so returning instead."); return; } if (objrefs.size() > 0) { ClientContext context; DecrementRefCountRequest request; for (int i = 0; i < objrefs.size(); ++i) { RAY_LOG(RAY_REFCOUNT, "Decrementing reference count for objref " << objrefs[i]); request.add_objref(objrefs[i]); } AckReply reply; scheduler_stub_->DecrementRefCount(&context, request, &reply); } } void Worker::register_function(const std::string& name, size_t num_return_vals) { RAY_CHECK(connected_, "Attempted to perform register_function but failed."); ClientContext context; RegisterFunctionRequest request; request.set_fnname(name); request.set_num_return_vals(num_return_vals); request.set_workerid(workerid_); AckReply reply; scheduler_stub_->RegisterFunction(&context, request, &reply); } Task* Worker::receive_next_task() { Task* task; receive_queue_.receive(&task); return task; } void Worker::notify_task_completed(bool task_succeeded, std::string error_message) { RAY_CHECK(connected_, "Attempted to perform notify_task_completed but failed."); ClientContext context; NotifyTaskCompletedRequest request; request.set_workerid(workerid_); request.set_task_succeeded(task_succeeded); request.set_error_message(error_message); AckReply reply; scheduler_stub_->NotifyTaskCompleted(&context, request, &reply); } void Worker::disconnect() { connected_ = false; } bool Worker::connected() { return connected_; } // TODO(rkn): Should we be using pointers or references? And should they be const? void Worker::scheduler_info(ClientContext &context, SchedulerInfoRequest &request, SchedulerInfoReply &reply) { RAY_CHECK(connected_, "Attempted to get scheduler info but failed."); scheduler_stub_->SchedulerInfo(&context, request, &reply); } // Communication between the WorkerServer and the Worker happens via a message // queue. This is because the Python interpreter needs to be single threaded // (in our case running in the main thread), whereas the WorkerService will // run in a separate thread and potentially utilize multiple threads. void Worker::start_worker_service() { const char* service_addr = worker_address_.c_str(); worker_server_thread_ = std::thread([service_addr]() { std::string service_address(service_addr); std::string::iterator split_point = split_ip_address(service_address); std::string port; port.assign(split_point, service_address.end()); WorkerServiceImpl service(service_address); ServerBuilder builder; builder.AddListeningPort(std::string("0.0.0.0:") + port, grpc::InsecureServerCredentials()); builder.RegisterService(&service); std::unique_ptr<Server> server(builder.BuildAndStart()); RAY_LOG(RAY_INFO, "worker server listening on " << service_address); server->Wait(); }); } <|endoftext|>
<commit_before>/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * 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 <dali/integration-api/debug.h> #include <dali/internal/text/text-abstraction/plugin/font-client-utils.h> #include <dali/internal/text/text-abstraction/plugin/font-face-cache-item.h> #if defined(DEBUG_ENABLED) extern Dali::Integration::Log::Filter* gFontClientLogFilter; #endif namespace Dali::TextAbstraction::Internal { const float FROM_266 = 1.0f / 64.0f; const float POINTS_PER_INCH = 72.f; FontFaceCacheItem::FontFaceCacheItem(FT_Library& freeTypeLibrary, FT_Face ftFace, const FontPath& path, PointSize26Dot6 requestedPointSize, FaceIndex face, const FontMetrics& metrics) : mFreeTypeLibrary(freeTypeLibrary), mFreeTypeFace(ftFace), mPath(path), mRequestedPointSize(requestedPointSize), mFaceIndex(face), mMetrics(metrics), mCharacterSet(nullptr), mFixedSizeIndex(0), mFixedWidthPixels(0.f), mFixedHeightPixels(0.f), mVectorFontId(0u), mFontId(0u), mIsFixedSizeBitmap(false), mHasColorTables(false) { } FontFaceCacheItem::FontFaceCacheItem(FT_Library& freeTypeLibrary, FT_Face ftFace, const FontPath& path, PointSize26Dot6 requestedPointSize, FaceIndex face, const FontMetrics& metrics, int fixedSizeIndex, float fixedWidth, float fixedHeight, bool hasColorTables) : mFreeTypeLibrary(freeTypeLibrary), mFreeTypeFace(ftFace), mPath(path), mRequestedPointSize(requestedPointSize), mFaceIndex(face), mMetrics(metrics), mCharacterSet(nullptr), mFixedSizeIndex(fixedSizeIndex), mFixedWidthPixels(fixedWidth), mFixedHeightPixels(fixedHeight), mVectorFontId(0u), mFontId(0u), mIsFixedSizeBitmap(true), mHasColorTables(hasColorTables) { } void FontFaceCacheItem::GetFontMetrics(FontMetrics& metrics, unsigned int dpiVertical) const { metrics = mMetrics; // Adjust the metrics if the fixed-size font should be down-scaled if(mIsFixedSizeBitmap) { const float desiredFixedSize = static_cast<float>(mRequestedPointSize) * FROM_266 / POINTS_PER_INCH * dpiVertical; if(desiredFixedSize > 0.f) { const float scaleFactor = desiredFixedSize / mFixedHeightPixels; metrics.ascender = metrics.ascender * scaleFactor; metrics.descender = metrics.descender * scaleFactor; metrics.height = metrics.height * scaleFactor; metrics.underlinePosition = metrics.underlinePosition * scaleFactor; metrics.underlineThickness = metrics.underlineThickness * scaleFactor; } } } bool FontFaceCacheItem::GetGlyphMetrics(GlyphInfo& glyph, unsigned int dpiVertical, bool horizontal) const { bool success(true); FT_Face ftFace = mFreeTypeFace; #ifdef FREETYPE_BITMAP_SUPPORT // Check to see if we should be loading a Fixed Size bitmap? if(mIsFixedSizeBitmap) { FT_Select_Size(ftFace, mFixedSizeIndex); ///< @todo: needs to be investigated why it's needed to select the size again. int error = FT_Load_Glyph(ftFace, glyph.index, FT_LOAD_COLOR); if(FT_Err_Ok == error) { glyph.width = mFixedWidthPixels; glyph.height = mFixedHeightPixels; glyph.advance = mFixedWidthPixels; glyph.xBearing = 0.0f; glyph.yBearing = mFixedHeightPixels; // Adjust the metrics if the fixed-size font should be down-scaled const float desiredFixedSize = static_cast<float>(mRequestedPointSize) * FROM_266 / POINTS_PER_INCH * dpiVertical; if(desiredFixedSize > 0.f) { const float scaleFactor = desiredFixedSize / mFixedHeightPixels; glyph.width = glyph.width * scaleFactor; glyph.height = glyph.height * scaleFactor; glyph.advance = glyph.advance * scaleFactor; glyph.xBearing = glyph.xBearing * scaleFactor; glyph.yBearing = glyph.yBearing * scaleFactor; glyph.scaleFactor = scaleFactor; } } else { DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "FontClient::Plugin::GetBitmapMetrics. FreeType Bitmap Load_Glyph error %d\n", error); success = false; } } else #endif { // FT_LOAD_DEFAULT causes some issues in the alignment of the glyph inside the bitmap. // i.e. with the SNum-3R font. // @todo: add an option to use the FT_LOAD_DEFAULT if required? int error = FT_Load_Glyph(ftFace, glyph.index, FT_LOAD_NO_AUTOHINT); // Keep the width of the glyph before doing the software emboldening. // It will be used to calculate a scale factor to be applied to the // advance as Harfbuzz doesn't apply any SW emboldening to calculate // the advance of the glyph. const float width = static_cast<float>(ftFace->glyph->metrics.width) * FROM_266; if(FT_Err_Ok == error) { const bool isEmboldeningRequired = glyph.isBoldRequired && !(ftFace->style_flags & FT_STYLE_FLAG_BOLD); if(isEmboldeningRequired) { // Does the software bold. FT_GlyphSlot_Embolden(ftFace->glyph); } glyph.width = static_cast<float>(ftFace->glyph->metrics.width) * FROM_266; glyph.height = static_cast<float>(ftFace->glyph->metrics.height) * FROM_266; if(horizontal) { glyph.xBearing += static_cast<float>(ftFace->glyph->metrics.horiBearingX) * FROM_266; glyph.yBearing += static_cast<float>(ftFace->glyph->metrics.horiBearingY) * FROM_266; } else { glyph.xBearing += static_cast<float>(ftFace->glyph->metrics.vertBearingX) * FROM_266; glyph.yBearing += static_cast<float>(ftFace->glyph->metrics.vertBearingY) * FROM_266; } if(isEmboldeningRequired && !Dali::EqualsZero(width)) { // If the glyph is emboldened by software, the advance is multiplied by a // scale factor to make it slightly bigger. glyph.advance *= (glyph.width / width); } // Use the bounding box of the bitmap to correct the metrics. // For some fonts i.e the SNum-3R the metrics need to be corrected, // otherwise the glyphs 'dance' up and down depending on the // font's point size. FT_Glyph ftGlyph; error = FT_Get_Glyph(ftFace->glyph, &ftGlyph); FT_BBox bbox; FT_Glyph_Get_CBox(ftGlyph, FT_GLYPH_BBOX_GRIDFIT, &bbox); const float descender = glyph.height - glyph.yBearing; glyph.height = (bbox.yMax - bbox.yMin) * FROM_266; glyph.yBearing = glyph.height - round(descender); // Created FT_Glyph object must be released with FT_Done_Glyph FT_Done_Glyph(ftGlyph); } else { success = false; } } return success; } /** * @brief Create a bitmap representation of a glyph from a face font * * @param[in] glyphIndex The index of a glyph within the specified font. * @param[in] isItalicRequired Whether the glyph requires italic style. * @param[in] isBoldRequired Whether the glyph requires bold style. * @param[out] data The bitmap data. * @param[in] outlineWidth The width of the glyph outline in pixels. */ void FontFaceCacheItem::CreateBitmap( GlyphIndex glyphIndex, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth, bool isItalicRequired, bool isBoldRequired) const { FT_Face ftFace = mFreeTypeFace; FT_Error error; // For the software italics. bool isShearRequired = false; #ifdef FREETYPE_BITMAP_SUPPORT // Check to see if this is fixed size bitmap if(mIsFixedSizeBitmap) { error = FT_Load_Glyph(ftFace, glyphIndex, FT_LOAD_COLOR); } else #endif { // FT_LOAD_DEFAULT causes some issues in the alignment of the glyph inside the bitmap. // i.e. with the SNum-3R font. // @todo: add an option to use the FT_LOAD_DEFAULT if required? error = FT_Load_Glyph(ftFace, glyphIndex, FT_LOAD_NO_AUTOHINT); } if(FT_Err_Ok == error) { if(isBoldRequired && !(ftFace->style_flags & FT_STYLE_FLAG_BOLD)) { // Does the software bold. FT_GlyphSlot_Embolden(ftFace->glyph); } if(isItalicRequired && !(ftFace->style_flags & FT_STYLE_FLAG_ITALIC)) { // Will do the software italic. isShearRequired = true; } FT_Glyph glyph; error = FT_Get_Glyph(ftFace->glyph, &glyph); // Convert to bitmap if necessary if(FT_Err_Ok == error) { if(glyph->format != FT_GLYPH_FORMAT_BITMAP) { int offsetX = 0, offsetY = 0; bool isOutlineGlyph = (glyph->format == FT_GLYPH_FORMAT_OUTLINE && outlineWidth > 0); // Create a bitmap for the outline if(isOutlineGlyph) { // Retrieve the horizontal and vertical distance from the current pen position to the // left and top border of the glyph bitmap for a normal glyph before applying the outline. if(FT_Err_Ok == error) { FT_Glyph normalGlyph; error = FT_Get_Glyph(ftFace->glyph, &normalGlyph); error = FT_Glyph_To_Bitmap(&normalGlyph, FT_RENDER_MODE_NORMAL, 0, 1); if(FT_Err_Ok == error) { FT_BitmapGlyph bitmapGlyph = reinterpret_cast<FT_BitmapGlyph>(normalGlyph); offsetX = bitmapGlyph->left; offsetY = bitmapGlyph->top; } // Created FT_Glyph object must be released with FT_Done_Glyph FT_Done_Glyph(normalGlyph); } // Now apply the outline // Set up a stroker FT_Stroker stroker; error = FT_Stroker_New(mFreeTypeLibrary, &stroker); if(FT_Err_Ok == error) { FT_Stroker_Set(stroker, outlineWidth * 64, FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0); error = FT_Glyph_StrokeBorder(&glyph, stroker, 0, 1); if(FT_Err_Ok == error) { FT_Stroker_Done(stroker); } else { DALI_LOG_ERROR("FT_Glyph_StrokeBorder Failed with error: %d\n", error); } } else { DALI_LOG_ERROR("FT_Stroker_New Failed with error: %d\n", error); } } error = FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1); if(FT_Err_Ok == error) { FT_BitmapGlyph bitmapGlyph = reinterpret_cast<FT_BitmapGlyph>(glyph); if(isOutlineGlyph) { // Calculate the additional horizontal and vertical offsets needed for the position of the outline glyph data.outlineOffsetX = offsetX - bitmapGlyph->left - outlineWidth; data.outlineOffsetY = bitmapGlyph->top - offsetY - outlineWidth; } ConvertBitmap(data, bitmapGlyph->bitmap, isShearRequired); } else { DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "FontClient::Plugin::CreateBitmap. FT_Get_Glyph Failed with error: %d\n", error); } } else { ConvertBitmap(data, ftFace->glyph->bitmap, isShearRequired); } data.isColorEmoji = mIsFixedSizeBitmap; // Created FT_Glyph object must be released with FT_Done_Glyph FT_Done_Glyph(glyph); } } else { DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "FontClient::Plugin::CreateBitmap. FT_Load_Glyph Failed with error: %d\n", error); } } bool FontFaceCacheItem::IsColorGlyph(GlyphIndex glyphIndex) const { FT_Error error = -1; #ifdef FREETYPE_BITMAP_SUPPORT // Check to see if this is fixed size bitmap if(mHasColorTables) { error = FT_Load_Glyph(mFreeTypeFace, glyphIndex, FT_LOAD_COLOR); } #endif return FT_Err_Ok == error; } /** * Check if the character is supported by this font * @param[in] character The character to test */ bool FontFaceCacheItem::IsCharacterSupported(Character character) { if(nullptr == mCharacterSet) { // Create again the character set. // It can be null if the ResetSystemDefaults() method has been called. FontDescription description; description.path = mPath; description.family = std::move(FontFamily(mFreeTypeFace->family_name)); description.weight = FontWeight::NONE; description.width = FontWidth::NONE; description.slant = FontSlant::NONE; // Note FreeType doesn't give too much info to build a proper font style. if(mFreeTypeFace->style_flags & FT_STYLE_FLAG_ITALIC) { description.slant = FontSlant::ITALIC; } if(mFreeTypeFace->style_flags & FT_STYLE_FLAG_BOLD) { description.weight = FontWeight::BOLD; } mCharacterSet = FcCharSetCopy(CreateCharacterSetFromDescription(description)); } return FcCharSetHasChar(mCharacterSet, character); } GlyphIndex FontFaceCacheItem::GetGlyphIndex(Character character) const { return FT_Get_Char_Index(mFreeTypeFace, character); } } // namespace Dali::TextAbstraction::Internal <commit_msg>Adjust the yBearing value of the emoji.<commit_after>/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * 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 <dali/integration-api/debug.h> #include <dali/internal/text/text-abstraction/plugin/font-client-utils.h> #include <dali/internal/text/text-abstraction/plugin/font-face-cache-item.h> #if defined(DEBUG_ENABLED) extern Dali::Integration::Log::Filter* gFontClientLogFilter; #endif namespace Dali::TextAbstraction::Internal { const float FROM_266 = 1.0f / 64.0f; const float POINTS_PER_INCH = 72.f; FontFaceCacheItem::FontFaceCacheItem(FT_Library& freeTypeLibrary, FT_Face ftFace, const FontPath& path, PointSize26Dot6 requestedPointSize, FaceIndex face, const FontMetrics& metrics) : mFreeTypeLibrary(freeTypeLibrary), mFreeTypeFace(ftFace), mPath(path), mRequestedPointSize(requestedPointSize), mFaceIndex(face), mMetrics(metrics), mCharacterSet(nullptr), mFixedSizeIndex(0), mFixedWidthPixels(0.f), mFixedHeightPixels(0.f), mVectorFontId(0u), mFontId(0u), mIsFixedSizeBitmap(false), mHasColorTables(false) { } FontFaceCacheItem::FontFaceCacheItem(FT_Library& freeTypeLibrary, FT_Face ftFace, const FontPath& path, PointSize26Dot6 requestedPointSize, FaceIndex face, const FontMetrics& metrics, int fixedSizeIndex, float fixedWidth, float fixedHeight, bool hasColorTables) : mFreeTypeLibrary(freeTypeLibrary), mFreeTypeFace(ftFace), mPath(path), mRequestedPointSize(requestedPointSize), mFaceIndex(face), mMetrics(metrics), mCharacterSet(nullptr), mFixedSizeIndex(fixedSizeIndex), mFixedWidthPixels(fixedWidth), mFixedHeightPixels(fixedHeight), mVectorFontId(0u), mFontId(0u), mIsFixedSizeBitmap(true), mHasColorTables(hasColorTables) { } void FontFaceCacheItem::GetFontMetrics(FontMetrics& metrics, unsigned int dpiVertical) const { metrics = mMetrics; // Adjust the metrics if the fixed-size font should be down-scaled if(mIsFixedSizeBitmap) { const float desiredFixedSize = static_cast<float>(mRequestedPointSize) * FROM_266 / POINTS_PER_INCH * dpiVertical; if(desiredFixedSize > 0.f) { const float scaleFactor = desiredFixedSize / mFixedHeightPixels; metrics.ascender = metrics.ascender * scaleFactor; metrics.descender = metrics.descender * scaleFactor; metrics.height = metrics.height * scaleFactor; metrics.underlinePosition = metrics.underlinePosition * scaleFactor; metrics.underlineThickness = metrics.underlineThickness * scaleFactor; } } } bool FontFaceCacheItem::GetGlyphMetrics(GlyphInfo& glyph, unsigned int dpiVertical, bool horizontal) const { bool success(true); FT_Face ftFace = mFreeTypeFace; #ifdef FREETYPE_BITMAP_SUPPORT // Check to see if we should be loading a Fixed Size bitmap? if(mIsFixedSizeBitmap) { FT_Select_Size(ftFace, mFixedSizeIndex); ///< @todo: needs to be investigated why it's needed to select the size again. int error = FT_Load_Glyph(ftFace, glyph.index, FT_LOAD_COLOR); if(FT_Err_Ok == error) { glyph.width = mFixedWidthPixels; glyph.height = mFixedHeightPixels; glyph.advance = mFixedWidthPixels; glyph.xBearing = 0.0f; if(horizontal) { glyph.yBearing += static_cast<float>(ftFace->glyph->metrics.horiBearingY) * FROM_266; } else { glyph.yBearing += static_cast<float>(ftFace->glyph->metrics.vertBearingY) * FROM_266; } // Adjust the metrics if the fixed-size font should be down-scaled const float desiredFixedSize = static_cast<float>(mRequestedPointSize) * FROM_266 / POINTS_PER_INCH * dpiVertical; if(desiredFixedSize > 0.f) { const float scaleFactor = desiredFixedSize / mFixedHeightPixels; glyph.width = glyph.width * scaleFactor; glyph.height = glyph.height * scaleFactor; glyph.advance = glyph.advance * scaleFactor; glyph.xBearing = glyph.xBearing * scaleFactor; glyph.yBearing = glyph.yBearing * scaleFactor; glyph.scaleFactor = scaleFactor; } } else { DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "FontClient::Plugin::GetBitmapMetrics. FreeType Bitmap Load_Glyph error %d\n", error); success = false; } } else #endif { // FT_LOAD_DEFAULT causes some issues in the alignment of the glyph inside the bitmap. // i.e. with the SNum-3R font. // @todo: add an option to use the FT_LOAD_DEFAULT if required? int error = FT_Load_Glyph(ftFace, glyph.index, FT_LOAD_NO_AUTOHINT); // Keep the width of the glyph before doing the software emboldening. // It will be used to calculate a scale factor to be applied to the // advance as Harfbuzz doesn't apply any SW emboldening to calculate // the advance of the glyph. const float width = static_cast<float>(ftFace->glyph->metrics.width) * FROM_266; if(FT_Err_Ok == error) { const bool isEmboldeningRequired = glyph.isBoldRequired && !(ftFace->style_flags & FT_STYLE_FLAG_BOLD); if(isEmboldeningRequired) { // Does the software bold. FT_GlyphSlot_Embolden(ftFace->glyph); } glyph.width = static_cast<float>(ftFace->glyph->metrics.width) * FROM_266; glyph.height = static_cast<float>(ftFace->glyph->metrics.height) * FROM_266; if(horizontal) { glyph.xBearing += static_cast<float>(ftFace->glyph->metrics.horiBearingX) * FROM_266; glyph.yBearing += static_cast<float>(ftFace->glyph->metrics.horiBearingY) * FROM_266; } else { glyph.xBearing += static_cast<float>(ftFace->glyph->metrics.vertBearingX) * FROM_266; glyph.yBearing += static_cast<float>(ftFace->glyph->metrics.vertBearingY) * FROM_266; } if(isEmboldeningRequired && !Dali::EqualsZero(width)) { // If the glyph is emboldened by software, the advance is multiplied by a // scale factor to make it slightly bigger. glyph.advance *= (glyph.width / width); } // Use the bounding box of the bitmap to correct the metrics. // For some fonts i.e the SNum-3R the metrics need to be corrected, // otherwise the glyphs 'dance' up and down depending on the // font's point size. FT_Glyph ftGlyph; error = FT_Get_Glyph(ftFace->glyph, &ftGlyph); FT_BBox bbox; FT_Glyph_Get_CBox(ftGlyph, FT_GLYPH_BBOX_GRIDFIT, &bbox); const float descender = glyph.height - glyph.yBearing; glyph.height = (bbox.yMax - bbox.yMin) * FROM_266; glyph.yBearing = glyph.height - round(descender); // Created FT_Glyph object must be released with FT_Done_Glyph FT_Done_Glyph(ftGlyph); } else { success = false; } } return success; } /** * @brief Create a bitmap representation of a glyph from a face font * * @param[in] glyphIndex The index of a glyph within the specified font. * @param[in] isItalicRequired Whether the glyph requires italic style. * @param[in] isBoldRequired Whether the glyph requires bold style. * @param[out] data The bitmap data. * @param[in] outlineWidth The width of the glyph outline in pixels. */ void FontFaceCacheItem::CreateBitmap( GlyphIndex glyphIndex, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth, bool isItalicRequired, bool isBoldRequired) const { FT_Face ftFace = mFreeTypeFace; FT_Error error; // For the software italics. bool isShearRequired = false; #ifdef FREETYPE_BITMAP_SUPPORT // Check to see if this is fixed size bitmap if(mIsFixedSizeBitmap) { error = FT_Load_Glyph(ftFace, glyphIndex, FT_LOAD_COLOR); } else #endif { // FT_LOAD_DEFAULT causes some issues in the alignment of the glyph inside the bitmap. // i.e. with the SNum-3R font. // @todo: add an option to use the FT_LOAD_DEFAULT if required? error = FT_Load_Glyph(ftFace, glyphIndex, FT_LOAD_NO_AUTOHINT); } if(FT_Err_Ok == error) { if(isBoldRequired && !(ftFace->style_flags & FT_STYLE_FLAG_BOLD)) { // Does the software bold. FT_GlyphSlot_Embolden(ftFace->glyph); } if(isItalicRequired && !(ftFace->style_flags & FT_STYLE_FLAG_ITALIC)) { // Will do the software italic. isShearRequired = true; } FT_Glyph glyph; error = FT_Get_Glyph(ftFace->glyph, &glyph); // Convert to bitmap if necessary if(FT_Err_Ok == error) { if(glyph->format != FT_GLYPH_FORMAT_BITMAP) { int offsetX = 0, offsetY = 0; bool isOutlineGlyph = (glyph->format == FT_GLYPH_FORMAT_OUTLINE && outlineWidth > 0); // Create a bitmap for the outline if(isOutlineGlyph) { // Retrieve the horizontal and vertical distance from the current pen position to the // left and top border of the glyph bitmap for a normal glyph before applying the outline. if(FT_Err_Ok == error) { FT_Glyph normalGlyph; error = FT_Get_Glyph(ftFace->glyph, &normalGlyph); error = FT_Glyph_To_Bitmap(&normalGlyph, FT_RENDER_MODE_NORMAL, 0, 1); if(FT_Err_Ok == error) { FT_BitmapGlyph bitmapGlyph = reinterpret_cast<FT_BitmapGlyph>(normalGlyph); offsetX = bitmapGlyph->left; offsetY = bitmapGlyph->top; } // Created FT_Glyph object must be released with FT_Done_Glyph FT_Done_Glyph(normalGlyph); } // Now apply the outline // Set up a stroker FT_Stroker stroker; error = FT_Stroker_New(mFreeTypeLibrary, &stroker); if(FT_Err_Ok == error) { FT_Stroker_Set(stroker, outlineWidth * 64, FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0); error = FT_Glyph_StrokeBorder(&glyph, stroker, 0, 1); if(FT_Err_Ok == error) { FT_Stroker_Done(stroker); } else { DALI_LOG_ERROR("FT_Glyph_StrokeBorder Failed with error: %d\n", error); } } else { DALI_LOG_ERROR("FT_Stroker_New Failed with error: %d\n", error); } } error = FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1); if(FT_Err_Ok == error) { FT_BitmapGlyph bitmapGlyph = reinterpret_cast<FT_BitmapGlyph>(glyph); if(isOutlineGlyph) { // Calculate the additional horizontal and vertical offsets needed for the position of the outline glyph data.outlineOffsetX = offsetX - bitmapGlyph->left - outlineWidth; data.outlineOffsetY = bitmapGlyph->top - offsetY - outlineWidth; } ConvertBitmap(data, bitmapGlyph->bitmap, isShearRequired); } else { DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "FontClient::Plugin::CreateBitmap. FT_Get_Glyph Failed with error: %d\n", error); } } else { ConvertBitmap(data, ftFace->glyph->bitmap, isShearRequired); } data.isColorEmoji = mIsFixedSizeBitmap; // Created FT_Glyph object must be released with FT_Done_Glyph FT_Done_Glyph(glyph); } } else { DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "FontClient::Plugin::CreateBitmap. FT_Load_Glyph Failed with error: %d\n", error); } } bool FontFaceCacheItem::IsColorGlyph(GlyphIndex glyphIndex) const { FT_Error error = -1; #ifdef FREETYPE_BITMAP_SUPPORT // Check to see if this is fixed size bitmap if(mHasColorTables) { error = FT_Load_Glyph(mFreeTypeFace, glyphIndex, FT_LOAD_COLOR); } #endif return FT_Err_Ok == error; } /** * Check if the character is supported by this font * @param[in] character The character to test */ bool FontFaceCacheItem::IsCharacterSupported(Character character) { if(nullptr == mCharacterSet) { // Create again the character set. // It can be null if the ResetSystemDefaults() method has been called. FontDescription description; description.path = mPath; description.family = std::move(FontFamily(mFreeTypeFace->family_name)); description.weight = FontWeight::NONE; description.width = FontWidth::NONE; description.slant = FontSlant::NONE; // Note FreeType doesn't give too much info to build a proper font style. if(mFreeTypeFace->style_flags & FT_STYLE_FLAG_ITALIC) { description.slant = FontSlant::ITALIC; } if(mFreeTypeFace->style_flags & FT_STYLE_FLAG_BOLD) { description.weight = FontWeight::BOLD; } mCharacterSet = FcCharSetCopy(CreateCharacterSetFromDescription(description)); } return FcCharSetHasChar(mCharacterSet, character); } GlyphIndex FontFaceCacheItem::GetGlyphIndex(Character character) const { return FT_Get_Char_Index(mFreeTypeFace, character); } } // namespace Dali::TextAbstraction::Internal <|endoftext|>
<commit_before>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "bump_user.h" #include <fclaw2d_clawpatch.h> #include <fc2d_clawpack46.h> #include <fc2d_clawpack5.h> #include <fc2d_cudaclaw.h> #include "../rp/shallow_user_fort.h" void bump_link_solvers(fclaw2d_global_t *glob) { fclaw2d_vtable_t *vt = fclaw2d_vt(); vt->problem_setup = &bump_problem_setup; /* Version-independent */ const user_options_t* user = bump_get_options(glob); if(user->cuda) { fc2d_cudaclaw_vtable_t *cuclaw_vt = fc2d_cudaclaw_vt(); cuclaw_vt->fort_qinit = &CLAWPACK46_QINIT; // cuclaw_vt->fort_rpn2 = &CLAWPACK46_RPN2; // cuclaw_vt->fort_rpt2 = &CLAWPACK46_RPT2; bump_assign_rpn2(&cuclaw_vt->cuda_rpn2); FCLAW_ASSERT(cuclaw_vt->cuda_rpn2 != NULL); bump_assign_rpt2(&cuclaw_vt->cuda_rpt2); FCLAW_ASSERT(cuclaw_vt->cuda_rpt2 != NULL); } else { if (user->claw_version == 4) { fclaw2d_clawpatch_vtable_t *clawpatch_vt = fclaw2d_clawpatch_vt(); fc2d_clawpack46_vtable_t *claw46_vt = fc2d_clawpack46_vt(); claw46_vt->fort_qinit = &CLAWPACK46_QINIT; claw46_vt->fort_rpn2 = &CLAWPACK46_RPN2; claw46_vt->fort_rpt2 = &CLAWPACK46_RPT2; /* Avoid tagging block corners in 5 patch example*/ clawpatch_vt->fort_tag4refinement = &TAG4REFINEMENT; clawpatch_vt->fort_tag4coarsening = &TAG4COARSENING; } } else if (user->claw_version == 5) { fc2d_clawpack5_vtable_t *claw5_vt = fc2d_clawpack5_vt(); claw5_vt->fort_qinit = &CLAWPACK5_QINIT; if (user->example == 0) { claw5_vt->fort_rpn2 = &CLAWPACK5_RPN2; claw5_vt->fort_rpt2 = &CLAWPACK5_RPT2; } else if (user->example == 1) { fclaw2d_clawpatch_vtable_t *clawpatch_vt = fclaw2d_clawpatch_vt(); fclaw2d_patch_vtable_t *patch_vt = fclaw2d_patch_vt(); patch_vt->setup = &bump_patch_setup; claw5_vt->fort_rpn2 = &CLAWPACK5_RPN2_MANIFOLD; claw5_vt->fort_rpt2 = &CLAWPACK5_RPT2_MANIFOLD; /* Avoid tagging block corners in 5 patch example*/ clawpatch_vt->fort_tag4refinement = &CLAWPACK5_TAG4REFINEMENT; clawpatch_vt->fort_tag4coarsening = &CLAWPACK5_TAG4COARSENING; } } } void bump_problem_setup(fclaw2d_global_t* glob) { const user_options_t* user = bump_get_options(glob); if (glob->mpirank == 0) { FILE *f = fopen("setprob.data","w"); fprintf(f, "%-24d %s",user->example,"\% example\n"); fprintf(f, "%-24.16f %s",user->gravity,"\% gravity\n"); fclose(f); } fclaw2d_domain_barrier (glob->domain); BUMP_SETPROB(); if (user->cuda == 1) { bump_setprob_cuda(user->gravity); } } void bump_patch_setup(fclaw2d_global_t *glob, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx) { int mx,my,mbc,maux; double xlower,ylower,dx,dy; double *aux,*xd,*yd,*zd,*area; double *xp,*yp,*zp; double *xnormals,*ynormals,*xtangents,*ytangents; double *surfnormals,*edgelengths,*curvature; if (fclaw2d_patch_is_ghost(this_patch)) { /* Mapped info is needed only for an update */ return; } fclaw2d_clawpatch_grid_data(glob,this_patch,&mx,&my,&mbc, &xlower,&ylower,&dx,&dy); fclaw2d_clawpatch_metric_data(glob,this_patch,&xp,&yp,&zp, &xd,&yd,&zd,&area); fclaw2d_clawpatch_metric_data2(glob,this_patch, &xnormals,&ynormals, &xtangents,&ytangents, &surfnormals,&edgelengths, &curvature); fclaw2d_clawpatch_aux_data(glob,this_patch,&aux,&maux); USER5_SETAUX_MANIFOLD(&mbc,&mx,&my,&xlower,&ylower, &dx,&dy,&maux,aux, xnormals,xtangents, ynormals,ytangents, surfnormals,area); } <commit_msg>(clawpack/shallow/bump_cuda) Fix syntax error<commit_after>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "bump_user.h" #include <fclaw2d_clawpatch.h> #include <fc2d_clawpack46.h> #include <fc2d_clawpack5.h> #include <fc2d_cudaclaw.h> #include "../rp/shallow_user_fort.h" void bump_link_solvers(fclaw2d_global_t *glob) { fclaw2d_vtable_t *vt = fclaw2d_vt(); vt->problem_setup = &bump_problem_setup; /* Version-independent */ const user_options_t* user = bump_get_options(glob); if(user->cuda) { fc2d_cudaclaw_vtable_t *cuclaw_vt = fc2d_cudaclaw_vt(); cuclaw_vt->fort_qinit = &CLAWPACK46_QINIT; // cuclaw_vt->fort_rpn2 = &CLAWPACK46_RPN2; // cuclaw_vt->fort_rpt2 = &CLAWPACK46_RPT2; bump_assign_rpn2(&cuclaw_vt->cuda_rpn2); FCLAW_ASSERT(cuclaw_vt->cuda_rpn2 != NULL); bump_assign_rpt2(&cuclaw_vt->cuda_rpt2); FCLAW_ASSERT(cuclaw_vt->cuda_rpt2 != NULL); } else { if (user->claw_version == 4) { fclaw2d_clawpatch_vtable_t *clawpatch_vt = fclaw2d_clawpatch_vt(); fc2d_clawpack46_vtable_t *claw46_vt = fc2d_clawpack46_vt(); claw46_vt->fort_qinit = &CLAWPACK46_QINIT; claw46_vt->fort_rpn2 = &CLAWPACK46_RPN2; claw46_vt->fort_rpt2 = &CLAWPACK46_RPT2; /* Avoid tagging block corners in 5 patch example*/ clawpatch_vt->fort_tag4refinement = &TAG4REFINEMENT; clawpatch_vt->fort_tag4coarsening = &TAG4COARSENING; } else if (user->claw_version == 5) { fc2d_clawpack5_vtable_t *claw5_vt = fc2d_clawpack5_vt(); claw5_vt->fort_qinit = &CLAWPACK5_QINIT; if (user->example == 0) { claw5_vt->fort_rpn2 = &CLAWPACK5_RPN2; claw5_vt->fort_rpt2 = &CLAWPACK5_RPT2; } else if (user->example == 1) { fclaw2d_clawpatch_vtable_t *clawpatch_vt = fclaw2d_clawpatch_vt(); fclaw2d_patch_vtable_t *patch_vt = fclaw2d_patch_vt(); patch_vt->setup = &bump_patch_setup; claw5_vt->fort_rpn2 = &CLAWPACK5_RPN2_MANIFOLD; claw5_vt->fort_rpt2 = &CLAWPACK5_RPT2_MANIFOLD; /* Avoid tagging block corners in 5 patch example*/ clawpatch_vt->fort_tag4refinement = &CLAWPACK5_TAG4REFINEMENT; clawpatch_vt->fort_tag4coarsening = &CLAWPACK5_TAG4COARSENING; } } } } void bump_problem_setup(fclaw2d_global_t* glob) { const user_options_t* user = bump_get_options(glob); if (glob->mpirank == 0) { FILE *f = fopen("setprob.data","w"); fprintf(f, "%-24d %s",user->example,"\% example\n"); fprintf(f, "%-24.16f %s",user->gravity,"\% gravity\n"); fclose(f); } fclaw2d_domain_barrier (glob->domain); BUMP_SETPROB(); if (user->cuda == 1) { bump_setprob_cuda(user->gravity); } } void bump_patch_setup(fclaw2d_global_t *glob, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx) { int mx,my,mbc,maux; double xlower,ylower,dx,dy; double *aux,*xd,*yd,*zd,*area; double *xp,*yp,*zp; double *xnormals,*ynormals,*xtangents,*ytangents; double *surfnormals,*edgelengths,*curvature; if (fclaw2d_patch_is_ghost(this_patch)) { /* Mapped info is needed only for an update */ return; } fclaw2d_clawpatch_grid_data(glob,this_patch,&mx,&my,&mbc, &xlower,&ylower,&dx,&dy); fclaw2d_clawpatch_metric_data(glob,this_patch,&xp,&yp,&zp, &xd,&yd,&zd,&area); fclaw2d_clawpatch_metric_data2(glob,this_patch, &xnormals,&ynormals, &xtangents,&ytangents, &surfnormals,&edgelengths, &curvature); fclaw2d_clawpatch_aux_data(glob,this_patch,&aux,&maux); USER5_SETAUX_MANIFOLD(&mbc,&mx,&my,&xlower,&ylower, &dx,&dy,&maux,aux, xnormals,xtangents, ynormals,ytangents, surfnormals,area); } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "itkImageToImageFilter.h" #include "otbMaximumAutocorrelationFactorImageFilter.h" #include "otbPCAImageFilter.h" #include "otbNAPCAImageFilter.h" #include "otbLocalActivityVectorImageFilter.h" #include "otbMaximumAutocorrelationFactorImageFilter.h" #include "otbFastICAImageFilter.h" #include "otbFastICAInternalOptimizerVectorImageFilter.h" //#include "otbVirtualDimensionality.h" #include "otbStreamingMinMaxVectorImageFilter.h" #include "otbVectorRescaleIntensityImageFilter.h" namespace otb { namespace Wrapper { class DimensionalityReduction: public Application { public: /** Standard class typedefs. */ typedef DimensionalityReduction Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; // Dimensionality reduction typedef typedef otb::MaximumAutocorrelationFactorImageFilter<FloatVectorImageType, FloatVectorImageType> MAFFilterType; typedef itk::ImageToImageFilter<FloatVectorImageType, FloatVectorImageType> DimensionalityReductionFilter; // Reduction dimensio filters typedef otb::PCAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::FORWARD> PCAForwardFilterType; typedef otb::PCAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::INVERSE> PCAInverseFilterType; //typedef otb::PCAImageFilter< FloatVectorImageType, FloatVectorImageType, otb::Transform::FORWARD > typedef otb::LocalActivityVectorImageFilter<FloatVectorImageType, FloatVectorImageType> NoiseFilterType; typedef otb::NAPCAImageFilter<FloatVectorImageType, FloatVectorImageType, NoiseFilterType, otb::Transform::FORWARD> NAPCAForwardFilterType; typedef otb::NAPCAImageFilter<FloatVectorImageType, FloatVectorImageType, NoiseFilterType, otb::Transform::INVERSE> NAPCAInverseFilterType; typedef otb::MaximumAutocorrelationFactorImageFilter<FloatVectorImageType, FloatVectorImageType> MAFForwardFilterType; typedef otb::FastICAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::FORWARD> ICAForwardFilterType; typedef otb::FastICAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::INVERSE> ICAInverseFilterType; typedef otb::StreamingStatisticsVectorImageFilter<FloatVectorImageType> StreamingStatisticsVectorImageFilterType; typedef StreamingStatisticsVectorImageFilterType::MatrixObjectType::ComponentType MatrixType; //typedef otb::VirtualDimensionality<double> VDFilterType; // output rescale typedef otb::StreamingMinMaxVectorImageFilter<FloatVectorImageType> MinMaxFilterType; typedef otb::VectorRescaleIntensityImageFilter<FloatVectorImageType> RescaleImageFilterType; /** Standard macro */ itkNewMacro(Self) ; itkTypeMacro(DimensionalityReduction, otb::Wrapper::Application) ; private: void DoInit() { SetName("DimensionalityReduction"); SetDescription("Perform Dimension reduction of the input image."); SetDocName("Dimensionality reduction"); SetDocLongDescription("Performs dimensionality reduction on input image. PCA,NA-PCA,MAF,ICA methods are available. It is also possible to compute the inverse transform to reconstruct the image. It is also possible to optionnaly export the transformation matrix to a text file."); SetDocLimitations("This application does not provide the inverse transform and the transformation matrix export for the MAF."); SetDocAuthors("OTB-Team"); SetDocSeeAlso( "\"Kernel maximum autocorrelation factor and minimum noise fraction transformations,\" IEEE Transactions on Image Processing, vol. 20, no. 3, pp. 612-624, (2011)"); AddDocTag(Tags::DimensionReduction); AddDocTag(Tags::Filter); AddParameter(ParameterType_InputImage, "in", "Input Image"); SetParameterDescription("in", "The input image to apply dimensionality reduction."); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription("out", "output image. Components are ordered by decreasing eigenvalues."); AddParameter(ParameterType_Group, "rescale", "Rescale Output."); MandatoryOff("rescale"); // AddChoice("rescale.no","No rescale"); // AddChoice("rescale.minmax","rescale to min max value"); AddParameter(ParameterType_Float, "rescale.outmin", "Output min value"); AddParameter(ParameterType_Float, "rescale.outmax", "Output max value"); SetDefaultParameterFloat("rescale.outmin", 0.0); SetParameterDescription("rescale.outmin", "Minimum value of the output image."); SetDefaultParameterFloat("rescale.outmax", 255.0); SetParameterDescription("rescale.outmax", "Maximum value of the output image."); AddParameter(ParameterType_OutputImage, "outinv", " Inverse Output Image"); SetParameterDescription("outinv", "reconstruct output image."); MandatoryOff("outinv"); AddParameter(ParameterType_Choice, "method", "Algorithm"); SetParameterDescription("method", "Selection of the reduction dimension method."); AddChoice("method.pca", "PCA"); SetParameterDescription("method.pca", "Principal Component Analysis."); AddChoice("method.napca", "NA-PCA"); SetParameterDescription("method.napca", "Noise Adjusted Principal Component Analysis."); AddParameter(ParameterType_Int, "method.napca.radiusx", "Set the x radius of the sliding window."); SetMinimumParameterIntValue("method.napca.radiusx", 1); SetDefaultParameterInt("method.napca.radiusx", 1); AddParameter(ParameterType_Int, "method.napca.radiusy", "Set the y radius of the sliding window."); SetMinimumParameterIntValue("method.napca.radiusy", 1); SetDefaultParameterInt("method.napca.radiusy", 1); AddChoice("method.maf", "MAF"); SetParameterDescription("method.maf", "Maximum Autocorrelation Factor."); AddChoice("method.ica", "ICA"); SetParameterDescription("method.ica", "Independant Component Analysis."); AddParameter(ParameterType_Int, "method.ica.iter", "number of iterations "); SetMinimumParameterIntValue("method.ica.iter", 1); SetDefaultParameterInt("method.ica.iter", 20); MandatoryOff("method.ica.iter"); AddParameter(ParameterType_Float, "method.ica.mu", "Give the increment weight of W in [0, 1]"); SetMinimumParameterFloatValue("method.ica.mu", 0.); SetMaximumParameterFloatValue("method.ica.mu", 1.); SetDefaultParameterFloat("method.ica.mu", 1.); MandatoryOff("method.ica.mu"); //AddChoice("method.vd","virual Dimension"); //SetParameterDescription("method.vd","Virtual Dimension."); //MandatoryOff("method"); AddParameter(ParameterType_Int, "nbcomp", "Number of Components."); SetParameterDescription("nbcomp", "Number of relevant components kept. By default all components are kept."); SetDefaultParameterInt("nbcomp", 0); MandatoryOff("nbcomp"); SetMinimumParameterIntValue("nbcomp", 0); AddParameter(ParameterType_Empty, "normalize", "Normalize."); SetParameterDescription("normalize", "center AND reduce data before Dimensionality reduction."); MandatoryOff("normalize"); AddParameter(ParameterType_OutputFilename, "outmatrix", "Transformation matrix output"); SetParameterDescription("outmatrix", "Filename to store the transformation matrix (csv format)"); MandatoryOff("outmatrix"); // Doc example parameter settings SetDocExampleParameterValue("in", "cupriteSubHsi.tif"); SetDocExampleParameterValue("out", "FilterOutput.tif"); SetDocExampleParameterValue("method", "pca"); } void DoUpdateParameters() { } void DoExecute() { // Get Parameters int nbComp = GetParameterInt("nbcomp"); bool normalize = HasValue("normalize"); bool rescale = IsParameterEnabled("rescale"); bool invTransform = HasValue("outinv"); switch (GetParameterInt("method")) { // PCA Algorithm case 0: { otbAppLogDEBUG( << "PCA Algorithm "); PCAForwardFilterType::Pointer filter = PCAForwardFilterType::New(); m_ForwardFilter = filter; PCAInverseFilterType::Pointer invFilter = PCAInverseFilterType::New(); m_InverseFilter = invFilter; filter->SetInput(GetParameterFloatVectorImage("in")); filter->SetNumberOfPrincipalComponentsRequired(nbComp); filter->SetUseNormalization(normalize); m_ForwardFilter->Update(); if (invTransform) { invFilter->SetInput(m_ForwardFilter->GetOutput()); if (normalize) { otbAppLogINFO( << "Normalization MeanValue :"<<filter->GetMeanValues()<< "StdValue :" <<filter->GetStdDevValues() ); invFilter->SetMeanValues(filter->GetMeanValues()); invFilter->SetStdDevValues(filter->GetStdDevValues()); } invFilter->SetTransformationMatrix(filter->GetTransformationMatrix()); m_TransformationMatrix = invFilter->GetTransformationMatrix(); } m_TransformationMatrix = filter->GetTransformationMatrix(); break; } case 1: { otbAppLogDEBUG( << "NA-PCA Algorithm "); // NA-PCA unsigned int radiusX = static_cast<unsigned int> (GetParameterInt("method.napca.radiusx")); unsigned int radiusY = static_cast<unsigned int> (GetParameterInt("method.napca.radiusy")); // Noise filtering NoiseFilterType::RadiusType radius = { { radiusX, radiusY } }; NAPCAForwardFilterType::Pointer filter = NAPCAForwardFilterType::New(); m_ForwardFilter = filter; NAPCAInverseFilterType::Pointer invFilter = NAPCAInverseFilterType::New(); m_InverseFilter = invFilter; filter->SetInput(GetParameterFloatVectorImage("in")); filter->SetNumberOfPrincipalComponentsRequired(nbComp); filter->SetUseNormalization(normalize); filter->GetNoiseImageFilter()->SetRadius(radius); m_ForwardFilter->Update(); if (invTransform) { otbAppLogDEBUG( << "Compute Inverse Transform"); invFilter->SetInput(m_ForwardFilter->GetOutput()); invFilter->SetMeanValues(filter->GetMeanValues()); if (normalize) { invFilter->SetStdDevValues(filter->GetStdDevValues()); } invFilter->SetTransformationMatrix(filter->GetTransformationMatrix()); m_TransformationMatrix = invFilter->GetTransformationMatrix(); } m_TransformationMatrix = filter->GetTransformationMatrix(); break; } case 2: { otbAppLogDEBUG( << "MAF Algorithm "); MAFForwardFilterType::Pointer filter = MAFForwardFilterType::New(); m_ForwardFilter = filter; filter->SetInput(GetParameterFloatVectorImage("in")); m_ForwardFilter->Update(); otbAppLogINFO( << "V :"<<std::endl<<filter->GetV()<<"Auto-Correlation :"<<std::endl <<filter->GetAutoCorrelation() ); break; } case 3: { otbAppLogDEBUG( << "Fast ICA Algorithm "); unsigned int nbIterations = static_cast<unsigned int> (GetParameterInt("method.ica.iter")); double mu = static_cast<double> (GetParameterFloat("method.ica.mu")); ICAForwardFilterType::Pointer filter = ICAForwardFilterType::New(); m_ForwardFilter = filter; ICAInverseFilterType::Pointer invFilter = ICAInverseFilterType::New(); m_InverseFilter = invFilter; filter->SetInput(GetParameterFloatVectorImage("in")); filter->SetNumberOfPrincipalComponentsRequired(nbComp); filter->SetNumberOfIterations(nbIterations); filter->SetMu(mu); m_ForwardFilter->Update(); if (invTransform) { otbAppLogDEBUG( << "Compute Inverse Transform"); invFilter->SetInput(m_ForwardFilter->GetOutput()); if (normalize) { invFilter->SetMeanValues(filter->GetMeanValues()); invFilter->SetStdDevValues(filter->GetStdDevValues()); } invFilter->SetPCATransformationMatrix(filter->GetPCATransformationMatrix()); invFilter->SetTransformationMatrix(filter->GetTransformationMatrix()); } m_TransformationMatrix = filter->GetTransformationMatrix(); break; } /* case 4: { otbAppLogDEBUG( << "VD Algorithm"); break; }*/ default: { otbAppLogFATAL(<<"non defined method "<<GetParameterInt("method")<<std::endl); break; } return; } if (invTransform) { if (GetParameterInt("method") == 2) //MAF or VD { otbAppLogWARNING(<<"This application only provides the forward transform ."); } else SetParameterOutputImage("outinv", m_InverseFilter->GetOutput()); } //Write transformation matrix if (this->GetParameterString("outmatrix").size() != 0) { if (GetParameterInt("method") == 2) //MAF or VD { otbAppLogWARNING(<<"No transformation matrix available for MAF."); } else { //Write transformation matrix std::ofstream outFile; outFile.open(this->GetParameterString("outmatrix").c_str()); outFile << std::fixed; outFile.precision(10); outFile << m_TransformationMatrix; outFile.close(); } } if (!rescale) { SetParameterOutputImage("out", m_ForwardFilter->GetOutput()); } else { otbAppLogDEBUG( << "Rescaling " ) otbAppLogDEBUG( << "Starting Min/Max computation" ) m_MinMaxFilter = MinMaxFilterType::New(); m_MinMaxFilter->SetInput(m_ForwardFilter->GetOutput()); m_MinMaxFilter->GetStreamer()->SetNumberOfLinesStrippedStreaming(50); AddProcess(m_MinMaxFilter->GetStreamer(), "Min/Max computing"); m_MinMaxFilter->Update(); otbAppLogDEBUG( << "Min/Max computation done : min=" << m_MinMaxFilter->GetMinimum() << " max=" << m_MinMaxFilter->GetMaximum() ) FloatVectorImageType::PixelType inMin, inMax; m_RescaleFilter = RescaleImageFilterType::New(); m_RescaleFilter->SetInput(m_ForwardFilter->GetOutput()); m_RescaleFilter->SetInputMinimum(m_MinMaxFilter->GetMinimum()); m_RescaleFilter->SetInputMaximum(m_MinMaxFilter->GetMaximum()); FloatVectorImageType::PixelType outMin, outMax; outMin.SetSize(m_ForwardFilter->GetOutput()->GetNumberOfComponentsPerPixel()); outMax.SetSize(m_ForwardFilter->GetOutput()->GetNumberOfComponentsPerPixel()); outMin.Fill(GetParameterFloat("rescale.outmin")); outMax.Fill(GetParameterFloat("rescale.outmax")); m_RescaleFilter->SetOutputMinimum(outMin); m_RescaleFilter->SetOutputMaximum(outMax); m_RescaleFilter->UpdateOutputInformation(); SetParameterOutputImage("out", m_RescaleFilter->GetOutput()); } } MinMaxFilterType::Pointer m_MinMaxFilter; RescaleImageFilterType::Pointer m_RescaleFilter; DimensionalityReductionFilter::Pointer m_ForwardFilter; DimensionalityReductionFilter::Pointer m_InverseFilter; MatrixType m_TransformationMatrix; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::DimensionalityReduction) <commit_msg>BUG: disable outinv parameter in case we compute the MAF transformation<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "itkImageToImageFilter.h" #include "otbMaximumAutocorrelationFactorImageFilter.h" #include "otbPCAImageFilter.h" #include "otbNAPCAImageFilter.h" #include "otbLocalActivityVectorImageFilter.h" #include "otbMaximumAutocorrelationFactorImageFilter.h" #include "otbFastICAImageFilter.h" #include "otbFastICAInternalOptimizerVectorImageFilter.h" //#include "otbVirtualDimensionality.h" #include "otbStreamingMinMaxVectorImageFilter.h" #include "otbVectorRescaleIntensityImageFilter.h" namespace otb { namespace Wrapper { class DimensionalityReduction: public Application { public: /** Standard class typedefs. */ typedef DimensionalityReduction Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; // Dimensionality reduction typedef typedef otb::MaximumAutocorrelationFactorImageFilter<FloatVectorImageType, FloatVectorImageType> MAFFilterType; typedef itk::ImageToImageFilter<FloatVectorImageType, FloatVectorImageType> DimensionalityReductionFilter; // Reduction dimensio filters typedef otb::PCAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::FORWARD> PCAForwardFilterType; typedef otb::PCAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::INVERSE> PCAInverseFilterType; //typedef otb::PCAImageFilter< FloatVectorImageType, FloatVectorImageType, otb::Transform::FORWARD > typedef otb::LocalActivityVectorImageFilter<FloatVectorImageType, FloatVectorImageType> NoiseFilterType; typedef otb::NAPCAImageFilter<FloatVectorImageType, FloatVectorImageType, NoiseFilterType, otb::Transform::FORWARD> NAPCAForwardFilterType; typedef otb::NAPCAImageFilter<FloatVectorImageType, FloatVectorImageType, NoiseFilterType, otb::Transform::INVERSE> NAPCAInverseFilterType; typedef otb::MaximumAutocorrelationFactorImageFilter<FloatVectorImageType, FloatVectorImageType> MAFForwardFilterType; typedef otb::FastICAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::FORWARD> ICAForwardFilterType; typedef otb::FastICAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::INVERSE> ICAInverseFilterType; typedef otb::StreamingStatisticsVectorImageFilter<FloatVectorImageType> StreamingStatisticsVectorImageFilterType; typedef StreamingStatisticsVectorImageFilterType::MatrixObjectType::ComponentType MatrixType; //typedef otb::VirtualDimensionality<double> VDFilterType; // output rescale typedef otb::StreamingMinMaxVectorImageFilter<FloatVectorImageType> MinMaxFilterType; typedef otb::VectorRescaleIntensityImageFilter<FloatVectorImageType> RescaleImageFilterType; /** Standard macro */ itkNewMacro(Self) ; itkTypeMacro(DimensionalityReduction, otb::Wrapper::Application) ; private: void DoInit() { SetName("DimensionalityReduction"); SetDescription("Perform Dimension reduction of the input image."); SetDocName("Dimensionality reduction"); SetDocLongDescription("Performs dimensionality reduction on input image. PCA,NA-PCA,MAF,ICA methods are available. It is also possible to compute the inverse transform to reconstruct the image. It is also possible to optionnaly export the transformation matrix to a text file."); SetDocLimitations("This application does not provide the inverse transform and the transformation matrix export for the MAF."); SetDocAuthors("OTB-Team"); SetDocSeeAlso( "\"Kernel maximum autocorrelation factor and minimum noise fraction transformations,\" IEEE Transactions on Image Processing, vol. 20, no. 3, pp. 612-624, (2011)"); AddDocTag(Tags::DimensionReduction); AddDocTag(Tags::Filter); AddParameter(ParameterType_InputImage, "in", "Input Image"); SetParameterDescription("in", "The input image to apply dimensionality reduction."); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription("out", "output image. Components are ordered by decreasing eigenvalues."); AddParameter(ParameterType_Group, "rescale", "Rescale Output."); MandatoryOff("rescale"); // AddChoice("rescale.no","No rescale"); // AddChoice("rescale.minmax","rescale to min max value"); AddParameter(ParameterType_Float, "rescale.outmin", "Output min value"); AddParameter(ParameterType_Float, "rescale.outmax", "Output max value"); SetDefaultParameterFloat("rescale.outmin", 0.0); SetParameterDescription("rescale.outmin", "Minimum value of the output image."); SetDefaultParameterFloat("rescale.outmax", 255.0); SetParameterDescription("rescale.outmax", "Maximum value of the output image."); AddParameter(ParameterType_OutputImage, "outinv", " Inverse Output Image"); SetParameterDescription("outinv", "reconstruct output image."); MandatoryOff("outinv"); AddParameter(ParameterType_Choice, "method", "Algorithm"); SetParameterDescription("method", "Selection of the reduction dimension method."); AddChoice("method.pca", "PCA"); SetParameterDescription("method.pca", "Principal Component Analysis."); AddChoice("method.napca", "NA-PCA"); SetParameterDescription("method.napca", "Noise Adjusted Principal Component Analysis."); AddParameter(ParameterType_Int, "method.napca.radiusx", "Set the x radius of the sliding window."); SetMinimumParameterIntValue("method.napca.radiusx", 1); SetDefaultParameterInt("method.napca.radiusx", 1); AddParameter(ParameterType_Int, "method.napca.radiusy", "Set the y radius of the sliding window."); SetMinimumParameterIntValue("method.napca.radiusy", 1); SetDefaultParameterInt("method.napca.radiusy", 1); AddChoice("method.maf", "MAF"); SetParameterDescription("method.maf", "Maximum Autocorrelation Factor."); AddChoice("method.ica", "ICA"); SetParameterDescription("method.ica", "Independant Component Analysis."); AddParameter(ParameterType_Int, "method.ica.iter", "number of iterations "); SetMinimumParameterIntValue("method.ica.iter", 1); SetDefaultParameterInt("method.ica.iter", 20); MandatoryOff("method.ica.iter"); AddParameter(ParameterType_Float, "method.ica.mu", "Give the increment weight of W in [0, 1]"); SetMinimumParameterFloatValue("method.ica.mu", 0.); SetMaximumParameterFloatValue("method.ica.mu", 1.); SetDefaultParameterFloat("method.ica.mu", 1.); MandatoryOff("method.ica.mu"); //AddChoice("method.vd","virual Dimension"); //SetParameterDescription("method.vd","Virtual Dimension."); //MandatoryOff("method"); AddParameter(ParameterType_Int, "nbcomp", "Number of Components."); SetParameterDescription("nbcomp", "Number of relevant components kept. By default all components are kept."); SetDefaultParameterInt("nbcomp", 0); MandatoryOff("nbcomp"); SetMinimumParameterIntValue("nbcomp", 0); AddParameter(ParameterType_Empty, "normalize", "Normalize."); SetParameterDescription("normalize", "center AND reduce data before Dimensionality reduction."); MandatoryOff("normalize"); AddParameter(ParameterType_OutputFilename, "outmatrix", "Transformation matrix output"); SetParameterDescription("outmatrix", "Filename to store the transformation matrix (csv format)"); MandatoryOff("outmatrix"); // Doc example parameter settings SetDocExampleParameterValue("in", "cupriteSubHsi.tif"); SetDocExampleParameterValue("out", "FilterOutput.tif"); SetDocExampleParameterValue("method", "pca"); } void DoUpdateParameters() { } void DoExecute() { // Get Parameters int nbComp = GetParameterInt("nbcomp"); bool normalize = HasValue("normalize"); bool rescale = IsParameterEnabled("rescale"); bool invTransform = HasValue("outinv"); switch (GetParameterInt("method")) { // PCA Algorithm case 0: { otbAppLogDEBUG( << "PCA Algorithm "); PCAForwardFilterType::Pointer filter = PCAForwardFilterType::New(); m_ForwardFilter = filter; PCAInverseFilterType::Pointer invFilter = PCAInverseFilterType::New(); m_InverseFilter = invFilter; filter->SetInput(GetParameterFloatVectorImage("in")); filter->SetNumberOfPrincipalComponentsRequired(nbComp); filter->SetUseNormalization(normalize); m_ForwardFilter->Update(); if (invTransform) { invFilter->SetInput(m_ForwardFilter->GetOutput()); if (normalize) { otbAppLogINFO( << "Normalization MeanValue :"<<filter->GetMeanValues()<< "StdValue :" <<filter->GetStdDevValues() ); invFilter->SetMeanValues(filter->GetMeanValues()); invFilter->SetStdDevValues(filter->GetStdDevValues()); } invFilter->SetTransformationMatrix(filter->GetTransformationMatrix()); m_TransformationMatrix = invFilter->GetTransformationMatrix(); } m_TransformationMatrix = filter->GetTransformationMatrix(); break; } case 1: { otbAppLogDEBUG( << "NA-PCA Algorithm "); // NA-PCA unsigned int radiusX = static_cast<unsigned int> (GetParameterInt("method.napca.radiusx")); unsigned int radiusY = static_cast<unsigned int> (GetParameterInt("method.napca.radiusy")); // Noise filtering NoiseFilterType::RadiusType radius = { { radiusX, radiusY } }; NAPCAForwardFilterType::Pointer filter = NAPCAForwardFilterType::New(); m_ForwardFilter = filter; NAPCAInverseFilterType::Pointer invFilter = NAPCAInverseFilterType::New(); m_InverseFilter = invFilter; filter->SetInput(GetParameterFloatVectorImage("in")); filter->SetNumberOfPrincipalComponentsRequired(nbComp); filter->SetUseNormalization(normalize); filter->GetNoiseImageFilter()->SetRadius(radius); m_ForwardFilter->Update(); if (invTransform) { otbAppLogDEBUG( << "Compute Inverse Transform"); invFilter->SetInput(m_ForwardFilter->GetOutput()); invFilter->SetMeanValues(filter->GetMeanValues()); if (normalize) { invFilter->SetStdDevValues(filter->GetStdDevValues()); } invFilter->SetTransformationMatrix(filter->GetTransformationMatrix()); m_TransformationMatrix = invFilter->GetTransformationMatrix(); } m_TransformationMatrix = filter->GetTransformationMatrix(); break; } case 2: { otbAppLogDEBUG( << "MAF Algorithm "); MAFForwardFilterType::Pointer filter = MAFForwardFilterType::New(); m_ForwardFilter = filter; filter->SetInput(GetParameterFloatVectorImage("in")); m_ForwardFilter->Update(); otbAppLogINFO( << "V :"<<std::endl<<filter->GetV()<<"Auto-Correlation :"<<std::endl <<filter->GetAutoCorrelation() ); break; } case 3: { otbAppLogDEBUG( << "Fast ICA Algorithm "); unsigned int nbIterations = static_cast<unsigned int> (GetParameterInt("method.ica.iter")); double mu = static_cast<double> (GetParameterFloat("method.ica.mu")); ICAForwardFilterType::Pointer filter = ICAForwardFilterType::New(); m_ForwardFilter = filter; ICAInverseFilterType::Pointer invFilter = ICAInverseFilterType::New(); m_InverseFilter = invFilter; filter->SetInput(GetParameterFloatVectorImage("in")); filter->SetNumberOfPrincipalComponentsRequired(nbComp); filter->SetNumberOfIterations(nbIterations); filter->SetMu(mu); m_ForwardFilter->Update(); if (invTransform) { otbAppLogDEBUG( << "Compute Inverse Transform"); invFilter->SetInput(m_ForwardFilter->GetOutput()); if (normalize) { invFilter->SetMeanValues(filter->GetMeanValues()); invFilter->SetStdDevValues(filter->GetStdDevValues()); } invFilter->SetPCATransformationMatrix(filter->GetPCATransformationMatrix()); invFilter->SetTransformationMatrix(filter->GetTransformationMatrix()); } m_TransformationMatrix = filter->GetTransformationMatrix(); break; } /* case 4: { otbAppLogDEBUG( << "VD Algorithm"); break; }*/ default: { otbAppLogFATAL(<<"non defined method "<<GetParameterInt("method")<<std::endl); break; } return; } if (invTransform) { if (GetParameterInt("method") == 2) //MAF or VD { this->DisableParameter("outinv"); otbAppLogWARNING(<<"This application only provides the forward transform for the MAF method."); } else SetParameterOutputImage("outinv", m_InverseFilter->GetOutput()); } //Write transformation matrix if (this->GetParameterString("outmatrix").size() != 0) { if (GetParameterInt("method") == 2) //MAF or VD { otbAppLogWARNING(<<"No transformation matrix available for MAF."); } else { //Write transformation matrix std::ofstream outFile; outFile.open(this->GetParameterString("outmatrix").c_str()); outFile << std::fixed; outFile.precision(10); outFile << m_TransformationMatrix; outFile.close(); } } if (!rescale) { SetParameterOutputImage("out", m_ForwardFilter->GetOutput()); } else { otbAppLogDEBUG( << "Rescaling " ) otbAppLogDEBUG( << "Starting Min/Max computation" ) m_MinMaxFilter = MinMaxFilterType::New(); m_MinMaxFilter->SetInput(m_ForwardFilter->GetOutput()); m_MinMaxFilter->GetStreamer()->SetNumberOfLinesStrippedStreaming(50); AddProcess(m_MinMaxFilter->GetStreamer(), "Min/Max computing"); m_MinMaxFilter->Update(); otbAppLogDEBUG( << "Min/Max computation done : min=" << m_MinMaxFilter->GetMinimum() << " max=" << m_MinMaxFilter->GetMaximum() ) FloatVectorImageType::PixelType inMin, inMax; m_RescaleFilter = RescaleImageFilterType::New(); m_RescaleFilter->SetInput(m_ForwardFilter->GetOutput()); m_RescaleFilter->SetInputMinimum(m_MinMaxFilter->GetMinimum()); m_RescaleFilter->SetInputMaximum(m_MinMaxFilter->GetMaximum()); FloatVectorImageType::PixelType outMin, outMax; outMin.SetSize(m_ForwardFilter->GetOutput()->GetNumberOfComponentsPerPixel()); outMax.SetSize(m_ForwardFilter->GetOutput()->GetNumberOfComponentsPerPixel()); outMin.Fill(GetParameterFloat("rescale.outmin")); outMax.Fill(GetParameterFloat("rescale.outmax")); m_RescaleFilter->SetOutputMinimum(outMin); m_RescaleFilter->SetOutputMaximum(outMax); m_RescaleFilter->UpdateOutputInformation(); SetParameterOutputImage("out", m_RescaleFilter->GetOutput()); } } MinMaxFilterType::Pointer m_MinMaxFilter; RescaleImageFilterType::Pointer m_RescaleFilter; DimensionalityReductionFilter::Pointer m_ForwardFilter; DimensionalityReductionFilter::Pointer m_InverseFilter; MatrixType m_TransformationMatrix; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::DimensionalityReduction) <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: i18nhelp.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2003-12-01 13:05:40 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <i18nhelp.hxx> /* #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif */ // #include <cppuhelper/servicefactory.hxx> #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_I18N_TRANSLITERATIONMODULES_HPP_ #include <com/sun/star/i18n/TransliterationModules.hpp> #endif #ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX #include <unotools/localedatawrapper.hxx> #endif #ifndef _UNOTOOLS_TRANSLITERATIONWRAPPER_HXX #include <unotools/transliterationwrapper.hxx> #endif #ifndef _ISOLANG_HXX #include <tools/isolang.hxx> #endif using namespace ::com::sun::star; vcl::I18nHelper::I18nHelper( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& rxMSF, const ::com::sun::star::lang::Locale& rLocale ) { mxMSF = rxMSF; maLocale = rLocale; mpLocaleDataWrapper = NULL; mpTransliterationWrapper= NULL; mbTransliterateIgnoreCase = sal_False; } vcl::I18nHelper::~I18nHelper() { ImplDestroyWrappers(); } void vcl::I18nHelper::ImplDestroyWrappers() { delete mpLocaleDataWrapper; mpLocaleDataWrapper = NULL; delete mpTransliterationWrapper; mpTransliterationWrapper= NULL; } utl::TransliterationWrapper& vcl::I18nHelper::ImplGetTransliterationWrapper() const { if ( !mpTransliterationWrapper ) { sal_Int32 nModules = i18n::TransliterationModules_IGNORE_WIDTH; if ( mbTransliterateIgnoreCase ) nModules |= i18n::TransliterationModules_IGNORE_CASE; ((vcl::I18nHelper*)this)->mpTransliterationWrapper = new utl::TransliterationWrapper( mxMSF, (i18n::TransliterationModules)nModules ); ((vcl::I18nHelper*)this)->mpTransliterationWrapper->loadModuleIfNeeded( ConvertIsoNamesToLanguage( maLocale.Language, maLocale.Country ) ); } return *mpTransliterationWrapper; } LocaleDataWrapper& vcl::I18nHelper::ImplGetLocaleDataWrapper() const { if ( !mpLocaleDataWrapper ) { ((vcl::I18nHelper*)this)->mpLocaleDataWrapper = new LocaleDataWrapper( mxMSF, maLocale ); } return *mpLocaleDataWrapper; } const ::com::sun::star::lang::Locale& vcl::I18nHelper::getLocale() const { return maLocale; } sal_Int32 vcl::I18nHelper::CompareString( const String& rStr1, const String& rStr2 ) const { ::osl::Guard< ::osl::Mutex > aGuard( ((vcl::I18nHelper*)this)->maMutex ); if ( mbTransliterateIgnoreCase ) { // Change mbTransliterateIgnoreCase and destroy the warpper, next call to // ImplGetTransliterationWrapper() will create a wrapper with the correct bIgnoreCase ((vcl::I18nHelper*)this)->mbTransliterateIgnoreCase = FALSE; delete ((vcl::I18nHelper*)this)->mpTransliterationWrapper; ((vcl::I18nHelper*)this)->mpTransliterationWrapper = NULL; } return ImplGetTransliterationWrapper().compareString( rStr1, rStr2 ); } sal_Bool vcl::I18nHelper::MatchString( const String& rStr1, const String& rStr2 ) const { ::osl::Guard< ::osl::Mutex > aGuard( ((vcl::I18nHelper*)this)->maMutex ); if ( !mbTransliterateIgnoreCase ) { // Change mbTransliterateIgnoreCase and destroy the warpper, next call to // ImplGetTransliterationWrapper() will create a wrapper with the correct bIgnoreCase ((vcl::I18nHelper*)this)->mbTransliterateIgnoreCase = TRUE; delete ((vcl::I18nHelper*)this)->mpTransliterationWrapper; ((vcl::I18nHelper*)this)->mpTransliterationWrapper = NULL; } return ImplGetTransliterationWrapper().isMatch( rStr1, rStr2 ); } sal_Bool vcl::I18nHelper::MatchMnemonic( const String& rString, sal_Unicode cMnemonicChar ) const { ::osl::Guard< ::osl::Mutex > aGuard( ((vcl::I18nHelper*)this)->maMutex ); BOOL bEqual = FALSE; USHORT n = rString.Search( '~' ); if ( n != STRING_NOTFOUND ) { String aMatchStr( rString, n+1, STRING_LEN ); // not only one char, because of transliteration... bEqual = MatchString( cMnemonicChar, aMatchStr ); } return bEqual; } String vcl::I18nHelper::GetDate( const Date& rDate ) const { ::osl::Guard< ::osl::Mutex > aGuard( ((vcl::I18nHelper*)this)->maMutex ); return ImplGetLocaleDataWrapper().getDate( rDate ); } String vcl::I18nHelper::GetNum( long nNumber, USHORT nDecimals, BOOL bUseThousandSep, BOOL bTrailingZeros ) const { return ImplGetLocaleDataWrapper().getNum( nNumber, nDecimals, bUseThousandSep, bTrailingZeros ); } <commit_msg>INTEGRATION: CWS ooo19126 (1.4.556); FILE MERGED 2005/09/05 14:44:36 rt 1.4.556.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: i18nhelp.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 11:40:26 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <i18nhelp.hxx> /* #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif */ // #include <cppuhelper/servicefactory.hxx> #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_I18N_TRANSLITERATIONMODULES_HPP_ #include <com/sun/star/i18n/TransliterationModules.hpp> #endif #ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX #include <unotools/localedatawrapper.hxx> #endif #ifndef _UNOTOOLS_TRANSLITERATIONWRAPPER_HXX #include <unotools/transliterationwrapper.hxx> #endif #ifndef _ISOLANG_HXX #include <tools/isolang.hxx> #endif using namespace ::com::sun::star; vcl::I18nHelper::I18nHelper( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& rxMSF, const ::com::sun::star::lang::Locale& rLocale ) { mxMSF = rxMSF; maLocale = rLocale; mpLocaleDataWrapper = NULL; mpTransliterationWrapper= NULL; mbTransliterateIgnoreCase = sal_False; } vcl::I18nHelper::~I18nHelper() { ImplDestroyWrappers(); } void vcl::I18nHelper::ImplDestroyWrappers() { delete mpLocaleDataWrapper; mpLocaleDataWrapper = NULL; delete mpTransliterationWrapper; mpTransliterationWrapper= NULL; } utl::TransliterationWrapper& vcl::I18nHelper::ImplGetTransliterationWrapper() const { if ( !mpTransliterationWrapper ) { sal_Int32 nModules = i18n::TransliterationModules_IGNORE_WIDTH; if ( mbTransliterateIgnoreCase ) nModules |= i18n::TransliterationModules_IGNORE_CASE; ((vcl::I18nHelper*)this)->mpTransliterationWrapper = new utl::TransliterationWrapper( mxMSF, (i18n::TransliterationModules)nModules ); ((vcl::I18nHelper*)this)->mpTransliterationWrapper->loadModuleIfNeeded( ConvertIsoNamesToLanguage( maLocale.Language, maLocale.Country ) ); } return *mpTransliterationWrapper; } LocaleDataWrapper& vcl::I18nHelper::ImplGetLocaleDataWrapper() const { if ( !mpLocaleDataWrapper ) { ((vcl::I18nHelper*)this)->mpLocaleDataWrapper = new LocaleDataWrapper( mxMSF, maLocale ); } return *mpLocaleDataWrapper; } const ::com::sun::star::lang::Locale& vcl::I18nHelper::getLocale() const { return maLocale; } sal_Int32 vcl::I18nHelper::CompareString( const String& rStr1, const String& rStr2 ) const { ::osl::Guard< ::osl::Mutex > aGuard( ((vcl::I18nHelper*)this)->maMutex ); if ( mbTransliterateIgnoreCase ) { // Change mbTransliterateIgnoreCase and destroy the warpper, next call to // ImplGetTransliterationWrapper() will create a wrapper with the correct bIgnoreCase ((vcl::I18nHelper*)this)->mbTransliterateIgnoreCase = FALSE; delete ((vcl::I18nHelper*)this)->mpTransliterationWrapper; ((vcl::I18nHelper*)this)->mpTransliterationWrapper = NULL; } return ImplGetTransliterationWrapper().compareString( rStr1, rStr2 ); } sal_Bool vcl::I18nHelper::MatchString( const String& rStr1, const String& rStr2 ) const { ::osl::Guard< ::osl::Mutex > aGuard( ((vcl::I18nHelper*)this)->maMutex ); if ( !mbTransliterateIgnoreCase ) { // Change mbTransliterateIgnoreCase and destroy the warpper, next call to // ImplGetTransliterationWrapper() will create a wrapper with the correct bIgnoreCase ((vcl::I18nHelper*)this)->mbTransliterateIgnoreCase = TRUE; delete ((vcl::I18nHelper*)this)->mpTransliterationWrapper; ((vcl::I18nHelper*)this)->mpTransliterationWrapper = NULL; } return ImplGetTransliterationWrapper().isMatch( rStr1, rStr2 ); } sal_Bool vcl::I18nHelper::MatchMnemonic( const String& rString, sal_Unicode cMnemonicChar ) const { ::osl::Guard< ::osl::Mutex > aGuard( ((vcl::I18nHelper*)this)->maMutex ); BOOL bEqual = FALSE; USHORT n = rString.Search( '~' ); if ( n != STRING_NOTFOUND ) { String aMatchStr( rString, n+1, STRING_LEN ); // not only one char, because of transliteration... bEqual = MatchString( cMnemonicChar, aMatchStr ); } return bEqual; } String vcl::I18nHelper::GetDate( const Date& rDate ) const { ::osl::Guard< ::osl::Mutex > aGuard( ((vcl::I18nHelper*)this)->maMutex ); return ImplGetLocaleDataWrapper().getDate( rDate ); } String vcl::I18nHelper::GetNum( long nNumber, USHORT nDecimals, BOOL bUseThousandSep, BOOL bTrailingZeros ) const { return ImplGetLocaleDataWrapper().getNum( nNumber, nDecimals, bUseThousandSep, bTrailingZeros ); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: svpbmp.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2007-11-01 14:48:17 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "svpbmp.hxx" #include <basegfx/vector/b2ivector.hxx> #include <basegfx/range/b2irange.hxx> #include <basebmp/scanlineformats.hxx> #include <basebmp/color.hxx> #include <vcl/salbtype.hxx> #include <vcl/bitmap.hxx> using namespace basebmp; using namespace basegfx; SvpSalBitmap::~SvpSalBitmap() { } bool SvpSalBitmap::Create( const Size& rSize, USHORT nBitCount, const BitmapPalette& rPalette ) { sal_uInt32 nFormat = SVP_DEFAULT_BITMAP_FORMAT; switch( nBitCount ) { case 1: nFormat = Format::ONE_BIT_MSB_PAL; break; case 4: nFormat = Format::FOUR_BIT_MSB_PAL; break; case 8: nFormat = Format::EIGHT_BIT_PAL; break; #ifdef OSL_BIGENDIAN case 16: nFormat = Format::SIXTEEN_BIT_MSB_TC_MASK; break; #else case 16: nFormat = Format::SIXTEEN_BIT_LSB_TC_MASK; break; #endif case 24: nFormat = Format::TWENTYFOUR_BIT_TC_MASK; break; case 32: nFormat = Format::THIRTYTWO_BIT_TC_MASK; break; } B2IVector aSize( rSize.Width(), rSize.Height() ); if( aSize.getX() == 0 ) aSize.setX( 1 ); if( aSize.getY() == 0 ) aSize.setY( 1 ); if( nBitCount > 8 ) m_aBitmap = createBitmapDevice( aSize, false, nFormat ); else { // prepare palette unsigned int nEntries = 1U << nBitCount; std::vector<basebmp::Color>* pPalette = new std::vector<basebmp::Color>( nEntries, basebmp::Color(COL_WHITE) ); unsigned int nColors = rPalette.GetEntryCount(); for( unsigned int i = 0; i < nColors; i++ ) { const BitmapColor& rCol = rPalette[i]; (*pPalette)[i] = basebmp::Color( rCol.GetRed(), rCol.GetGreen(), rCol.GetBlue() ); } m_aBitmap = createBitmapDevice( aSize, false, nFormat, basebmp::RawMemorySharedArray(), basebmp::PaletteMemorySharedVector( pPalette ) ); } return true; } bool SvpSalBitmap::Create( const SalBitmap& rSalBmp ) { const SvpSalBitmap& rSrc = static_cast<const SvpSalBitmap&>(rSalBmp); const BitmapDeviceSharedPtr& rSrcBmp = rSrc.getBitmap(); if( rSrcBmp.get() ) { B2IVector aSize = rSrcBmp->getSize(); m_aBitmap = cloneBitmapDevice( aSize, rSrcBmp ); B2IRange aRect( 0, 0, aSize.getX(), aSize.getY() ); m_aBitmap->drawBitmap( rSrcBmp, aRect, aRect, DrawMode_PAINT ); } else m_aBitmap.reset(); return true; } bool SvpSalBitmap::Create( const SalBitmap& /*rSalBmp*/, SalGraphics* /*pGraphics*/ ) { return false; } bool SvpSalBitmap::Create( const SalBitmap& /*rSalBmp*/, USHORT /*nNewBitCount*/ ) { return false; } void SvpSalBitmap::Destroy() { m_aBitmap.reset(); } Size SvpSalBitmap::GetSize() const { Size aSize; if( m_aBitmap.get() ) { B2IVector aVec( m_aBitmap->getSize() ); aSize = Size( aVec.getX(), aVec.getY() ); } return aSize; } USHORT SvpSalBitmap::GetBitCount() const { USHORT nDepth = 0; if( m_aBitmap.get() ) nDepth = getBitCountFromScanlineFormat( m_aBitmap->getScanlineFormat() ); return nDepth; } BitmapBuffer* SvpSalBitmap::AcquireBuffer( bool ) { BitmapBuffer* pBuf = NULL; if( m_aBitmap.get() ) { pBuf = new BitmapBuffer(); USHORT nBitCount = 1; switch( m_aBitmap->getScanlineFormat() ) { case Format::ONE_BIT_MSB_GREY: case Format::ONE_BIT_MSB_PAL: nBitCount = 1; pBuf->mnFormat = BMP_FORMAT_1BIT_MSB_PAL; break; case Format::ONE_BIT_LSB_GREY: case Format::ONE_BIT_LSB_PAL: nBitCount = 1; pBuf->mnFormat = BMP_FORMAT_1BIT_LSB_PAL; break; case Format::FOUR_BIT_MSB_GREY: case Format::FOUR_BIT_MSB_PAL: nBitCount = 4; pBuf->mnFormat = BMP_FORMAT_4BIT_MSN_PAL; break; case Format::FOUR_BIT_LSB_GREY: case Format::FOUR_BIT_LSB_PAL: nBitCount = 4; pBuf->mnFormat = BMP_FORMAT_4BIT_LSN_PAL; break; case Format::EIGHT_BIT_PAL: nBitCount = 8; pBuf->mnFormat = BMP_FORMAT_8BIT_PAL; break; case Format::EIGHT_BIT_GREY: nBitCount = 8; pBuf->mnFormat = BMP_FORMAT_8BIT_PAL; break; case Format::SIXTEEN_BIT_LSB_TC_MASK: nBitCount = 16; pBuf->mnFormat = BMP_FORMAT_16BIT_TC_LSB_MASK; pBuf->maColorMask = ColorMask( 0xf800, 0x07e0, 0x001f ); break; case Format::SIXTEEN_BIT_MSB_TC_MASK: nBitCount = 16; pBuf->mnFormat = BMP_FORMAT_16BIT_TC_MSB_MASK; pBuf->maColorMask = ColorMask( 0xf800, 0x07e0, 0x001f ); break; case Format::TWENTYFOUR_BIT_TC_MASK: nBitCount = 24; pBuf->mnFormat = BMP_FORMAT_24BIT_TC_BGR; break; case Format::THIRTYTWO_BIT_TC_MASK: nBitCount = 32; pBuf->mnFormat = BMP_FORMAT_32BIT_TC_MASK; #ifdef OSL_BIGENDIAN pBuf->maColorMask = ColorMask( 0x0000ff, 0x00ff00, 0xff0000 ); #else pBuf->maColorMask = ColorMask( 0xff0000, 0x00ff00, 0x0000ff ); #endif break; default: // this is an error case !!!!! nBitCount = 1; pBuf->mnFormat = BMP_FORMAT_1BIT_MSB_PAL; break; } if( m_aBitmap->isTopDown() ) pBuf->mnFormat |= BMP_FORMAT_TOP_DOWN; B2IVector aSize = m_aBitmap->getSize(); pBuf->mnWidth = aSize.getX(); pBuf->mnHeight = aSize.getY(); pBuf->mnScanlineSize = m_aBitmap->getScanlineStride(); pBuf->mnBitCount = nBitCount; pBuf->mpBits = (BYTE*)m_aBitmap->getBuffer().get(); if( nBitCount <= 8 ) { if( m_aBitmap->getScanlineFormat() == Format::EIGHT_BIT_GREY || m_aBitmap->getScanlineFormat() == Format::FOUR_BIT_LSB_GREY || m_aBitmap->getScanlineFormat() == Format::FOUR_BIT_MSB_GREY || m_aBitmap->getScanlineFormat() == Format::ONE_BIT_LSB_GREY || m_aBitmap->getScanlineFormat() == Format::ONE_BIT_MSB_GREY ) pBuf->maPalette = Bitmap::GetGreyPalette( 1U << nBitCount ); else { basebmp::PaletteMemorySharedVector aPalette = m_aBitmap->getPalette(); if( aPalette.get() ) { unsigned int nColors = aPalette->size(); if( nColors > 0 ) { pBuf->maPalette.SetEntryCount( nColors ); for( unsigned int i = 0; i < nColors; i++ ) { const basebmp::Color& rCol = (*aPalette)[i]; pBuf->maPalette[i] = BitmapColor( rCol.getRed(), rCol.getGreen(), rCol.getBlue() ); } } } } } } return pBuf; } void SvpSalBitmap::ReleaseBuffer( BitmapBuffer* pBuffer, bool bReadOnly ) { if( !bReadOnly && pBuffer->maPalette.GetEntryCount() ) { // palette might have changed, clone device (but recycle // memory) USHORT nBitCount = 0; switch( m_aBitmap->getScanlineFormat() ) { case Format::ONE_BIT_MSB_GREY: // FALLTHROUGH intended case Format::ONE_BIT_MSB_PAL: // FALLTHROUGH intended case Format::ONE_BIT_LSB_GREY: // FALLTHROUGH intended case Format::ONE_BIT_LSB_PAL: nBitCount = 1; break; case Format::FOUR_BIT_MSB_GREY: // FALLTHROUGH intended case Format::FOUR_BIT_MSB_PAL: // FALLTHROUGH intended case Format::FOUR_BIT_LSB_GREY: // FALLTHROUGH intended case Format::FOUR_BIT_LSB_PAL: nBitCount = 4; break; case Format::EIGHT_BIT_PAL: // FALLTHROUGH intended case Format::EIGHT_BIT_GREY: nBitCount = 8; break; default: break; } if( nBitCount ) { sal_uInt32 nEntries = 1U << nBitCount; boost::shared_ptr< std::vector<basebmp::Color> > pPal( new std::vector<basebmp::Color>( nEntries, basebmp::Color(COL_WHITE))); const sal_uInt32 nColors = std::min( (sal_uInt32)pBuffer->maPalette.GetEntryCount(), nEntries); for( sal_uInt32 i = 0; i < nColors; i++ ) { const BitmapColor& rCol = pBuffer->maPalette[i]; (*pPal)[i] = basebmp::Color( rCol.GetRed(), rCol.GetGreen(), rCol.GetBlue() ); } m_aBitmap = basebmp::createBitmapDevice( m_aBitmap->getSize(), m_aBitmap->isTopDown(), m_aBitmap->getScanlineFormat(), m_aBitmap->getBuffer(), pPal ); } } delete pBuffer; } bool SvpSalBitmap::GetSystemData( BitmapSystemData& ) { return false; } <commit_msg>INTEGRATION: CWS changefileheader (1.3.148); FILE MERGED 2008/03/28 15:45:12 rt 1.3.148.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: svpbmp.cxx,v $ * $Revision: 1.4 $ * * 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. * ************************************************************************/ #include "svpbmp.hxx" #include <basegfx/vector/b2ivector.hxx> #include <basegfx/range/b2irange.hxx> #include <basebmp/scanlineformats.hxx> #include <basebmp/color.hxx> #include <vcl/salbtype.hxx> #include <vcl/bitmap.hxx> using namespace basebmp; using namespace basegfx; SvpSalBitmap::~SvpSalBitmap() { } bool SvpSalBitmap::Create( const Size& rSize, USHORT nBitCount, const BitmapPalette& rPalette ) { sal_uInt32 nFormat = SVP_DEFAULT_BITMAP_FORMAT; switch( nBitCount ) { case 1: nFormat = Format::ONE_BIT_MSB_PAL; break; case 4: nFormat = Format::FOUR_BIT_MSB_PAL; break; case 8: nFormat = Format::EIGHT_BIT_PAL; break; #ifdef OSL_BIGENDIAN case 16: nFormat = Format::SIXTEEN_BIT_MSB_TC_MASK; break; #else case 16: nFormat = Format::SIXTEEN_BIT_LSB_TC_MASK; break; #endif case 24: nFormat = Format::TWENTYFOUR_BIT_TC_MASK; break; case 32: nFormat = Format::THIRTYTWO_BIT_TC_MASK; break; } B2IVector aSize( rSize.Width(), rSize.Height() ); if( aSize.getX() == 0 ) aSize.setX( 1 ); if( aSize.getY() == 0 ) aSize.setY( 1 ); if( nBitCount > 8 ) m_aBitmap = createBitmapDevice( aSize, false, nFormat ); else { // prepare palette unsigned int nEntries = 1U << nBitCount; std::vector<basebmp::Color>* pPalette = new std::vector<basebmp::Color>( nEntries, basebmp::Color(COL_WHITE) ); unsigned int nColors = rPalette.GetEntryCount(); for( unsigned int i = 0; i < nColors; i++ ) { const BitmapColor& rCol = rPalette[i]; (*pPalette)[i] = basebmp::Color( rCol.GetRed(), rCol.GetGreen(), rCol.GetBlue() ); } m_aBitmap = createBitmapDevice( aSize, false, nFormat, basebmp::RawMemorySharedArray(), basebmp::PaletteMemorySharedVector( pPalette ) ); } return true; } bool SvpSalBitmap::Create( const SalBitmap& rSalBmp ) { const SvpSalBitmap& rSrc = static_cast<const SvpSalBitmap&>(rSalBmp); const BitmapDeviceSharedPtr& rSrcBmp = rSrc.getBitmap(); if( rSrcBmp.get() ) { B2IVector aSize = rSrcBmp->getSize(); m_aBitmap = cloneBitmapDevice( aSize, rSrcBmp ); B2IRange aRect( 0, 0, aSize.getX(), aSize.getY() ); m_aBitmap->drawBitmap( rSrcBmp, aRect, aRect, DrawMode_PAINT ); } else m_aBitmap.reset(); return true; } bool SvpSalBitmap::Create( const SalBitmap& /*rSalBmp*/, SalGraphics* /*pGraphics*/ ) { return false; } bool SvpSalBitmap::Create( const SalBitmap& /*rSalBmp*/, USHORT /*nNewBitCount*/ ) { return false; } void SvpSalBitmap::Destroy() { m_aBitmap.reset(); } Size SvpSalBitmap::GetSize() const { Size aSize; if( m_aBitmap.get() ) { B2IVector aVec( m_aBitmap->getSize() ); aSize = Size( aVec.getX(), aVec.getY() ); } return aSize; } USHORT SvpSalBitmap::GetBitCount() const { USHORT nDepth = 0; if( m_aBitmap.get() ) nDepth = getBitCountFromScanlineFormat( m_aBitmap->getScanlineFormat() ); return nDepth; } BitmapBuffer* SvpSalBitmap::AcquireBuffer( bool ) { BitmapBuffer* pBuf = NULL; if( m_aBitmap.get() ) { pBuf = new BitmapBuffer(); USHORT nBitCount = 1; switch( m_aBitmap->getScanlineFormat() ) { case Format::ONE_BIT_MSB_GREY: case Format::ONE_BIT_MSB_PAL: nBitCount = 1; pBuf->mnFormat = BMP_FORMAT_1BIT_MSB_PAL; break; case Format::ONE_BIT_LSB_GREY: case Format::ONE_BIT_LSB_PAL: nBitCount = 1; pBuf->mnFormat = BMP_FORMAT_1BIT_LSB_PAL; break; case Format::FOUR_BIT_MSB_GREY: case Format::FOUR_BIT_MSB_PAL: nBitCount = 4; pBuf->mnFormat = BMP_FORMAT_4BIT_MSN_PAL; break; case Format::FOUR_BIT_LSB_GREY: case Format::FOUR_BIT_LSB_PAL: nBitCount = 4; pBuf->mnFormat = BMP_FORMAT_4BIT_LSN_PAL; break; case Format::EIGHT_BIT_PAL: nBitCount = 8; pBuf->mnFormat = BMP_FORMAT_8BIT_PAL; break; case Format::EIGHT_BIT_GREY: nBitCount = 8; pBuf->mnFormat = BMP_FORMAT_8BIT_PAL; break; case Format::SIXTEEN_BIT_LSB_TC_MASK: nBitCount = 16; pBuf->mnFormat = BMP_FORMAT_16BIT_TC_LSB_MASK; pBuf->maColorMask = ColorMask( 0xf800, 0x07e0, 0x001f ); break; case Format::SIXTEEN_BIT_MSB_TC_MASK: nBitCount = 16; pBuf->mnFormat = BMP_FORMAT_16BIT_TC_MSB_MASK; pBuf->maColorMask = ColorMask( 0xf800, 0x07e0, 0x001f ); break; case Format::TWENTYFOUR_BIT_TC_MASK: nBitCount = 24; pBuf->mnFormat = BMP_FORMAT_24BIT_TC_BGR; break; case Format::THIRTYTWO_BIT_TC_MASK: nBitCount = 32; pBuf->mnFormat = BMP_FORMAT_32BIT_TC_MASK; #ifdef OSL_BIGENDIAN pBuf->maColorMask = ColorMask( 0x0000ff, 0x00ff00, 0xff0000 ); #else pBuf->maColorMask = ColorMask( 0xff0000, 0x00ff00, 0x0000ff ); #endif break; default: // this is an error case !!!!! nBitCount = 1; pBuf->mnFormat = BMP_FORMAT_1BIT_MSB_PAL; break; } if( m_aBitmap->isTopDown() ) pBuf->mnFormat |= BMP_FORMAT_TOP_DOWN; B2IVector aSize = m_aBitmap->getSize(); pBuf->mnWidth = aSize.getX(); pBuf->mnHeight = aSize.getY(); pBuf->mnScanlineSize = m_aBitmap->getScanlineStride(); pBuf->mnBitCount = nBitCount; pBuf->mpBits = (BYTE*)m_aBitmap->getBuffer().get(); if( nBitCount <= 8 ) { if( m_aBitmap->getScanlineFormat() == Format::EIGHT_BIT_GREY || m_aBitmap->getScanlineFormat() == Format::FOUR_BIT_LSB_GREY || m_aBitmap->getScanlineFormat() == Format::FOUR_BIT_MSB_GREY || m_aBitmap->getScanlineFormat() == Format::ONE_BIT_LSB_GREY || m_aBitmap->getScanlineFormat() == Format::ONE_BIT_MSB_GREY ) pBuf->maPalette = Bitmap::GetGreyPalette( 1U << nBitCount ); else { basebmp::PaletteMemorySharedVector aPalette = m_aBitmap->getPalette(); if( aPalette.get() ) { unsigned int nColors = aPalette->size(); if( nColors > 0 ) { pBuf->maPalette.SetEntryCount( nColors ); for( unsigned int i = 0; i < nColors; i++ ) { const basebmp::Color& rCol = (*aPalette)[i]; pBuf->maPalette[i] = BitmapColor( rCol.getRed(), rCol.getGreen(), rCol.getBlue() ); } } } } } } return pBuf; } void SvpSalBitmap::ReleaseBuffer( BitmapBuffer* pBuffer, bool bReadOnly ) { if( !bReadOnly && pBuffer->maPalette.GetEntryCount() ) { // palette might have changed, clone device (but recycle // memory) USHORT nBitCount = 0; switch( m_aBitmap->getScanlineFormat() ) { case Format::ONE_BIT_MSB_GREY: // FALLTHROUGH intended case Format::ONE_BIT_MSB_PAL: // FALLTHROUGH intended case Format::ONE_BIT_LSB_GREY: // FALLTHROUGH intended case Format::ONE_BIT_LSB_PAL: nBitCount = 1; break; case Format::FOUR_BIT_MSB_GREY: // FALLTHROUGH intended case Format::FOUR_BIT_MSB_PAL: // FALLTHROUGH intended case Format::FOUR_BIT_LSB_GREY: // FALLTHROUGH intended case Format::FOUR_BIT_LSB_PAL: nBitCount = 4; break; case Format::EIGHT_BIT_PAL: // FALLTHROUGH intended case Format::EIGHT_BIT_GREY: nBitCount = 8; break; default: break; } if( nBitCount ) { sal_uInt32 nEntries = 1U << nBitCount; boost::shared_ptr< std::vector<basebmp::Color> > pPal( new std::vector<basebmp::Color>( nEntries, basebmp::Color(COL_WHITE))); const sal_uInt32 nColors = std::min( (sal_uInt32)pBuffer->maPalette.GetEntryCount(), nEntries); for( sal_uInt32 i = 0; i < nColors; i++ ) { const BitmapColor& rCol = pBuffer->maPalette[i]; (*pPal)[i] = basebmp::Color( rCol.GetRed(), rCol.GetGreen(), rCol.GetBlue() ); } m_aBitmap = basebmp::createBitmapDevice( m_aBitmap->getSize(), m_aBitmap->isTopDown(), m_aBitmap->getScanlineFormat(), m_aBitmap->getBuffer(), pPal ); } } delete pBuffer; } bool SvpSalBitmap::GetSystemData( BitmapSystemData& ) { return false; } <|endoftext|>
<commit_before>#include "chrono_parallel/ChSystemParallel.h" #include <omp.h> using namespace chrono; ChSystemParallelDVI::ChSystemParallelDVI(unsigned int max_objects) : ChSystemParallel(max_objects) { LCP_descriptor = new ChLcpSystemDescriptorParallelDVI(); LCP_solver_speed = new ChLcpSolverParallelDVI(); ((ChLcpSystemDescriptorParallelDVI*) LCP_descriptor)->data_container = data_manager; ((ChLcpSolverParallel*) LCP_solver_speed)->data_container = data_manager; data_manager->system_timer.AddTimer("ChConstraintRigidRigid_shurA_normal"); data_manager->system_timer.AddTimer("ChConstraintRigidRigid_shurA_sliding"); data_manager->system_timer.AddTimer("ChConstraintRigidRigid_shurA_spinning"); data_manager->system_timer.AddTimer("ChConstraintRigidRigid_shurA_reduce"); data_manager->system_timer.AddTimer("ChConstraintRigidRigid_shurB_normal"); data_manager->system_timer.AddTimer("ChConstraintRigidRigid_shurB_sliding"); data_manager->system_timer.AddTimer("ChConstraintRigidRigid_shurB_spinning"); data_manager->system_timer.AddTimer("ChSolverParallel_solverA"); data_manager->system_timer.AddTimer("ChSolverParallel_solverB"); data_manager->system_timer.AddTimer("ChSolverParallel_solverC"); data_manager->system_timer.AddTimer("ChSolverParallel_solverD"); data_manager->system_timer.AddTimer("ChSolverParallel_solverE"); data_manager->system_timer.AddTimer("ChSolverParallel_solverF"); data_manager->system_timer.AddTimer("ChSolverParallel_solverG"); data_manager->system_timer.AddTimer("ChSolverParallel_Project"); data_manager->system_timer.AddTimer("ChSolverParallel_Solve"); } void ChSystemParallelDVI::LoadMaterialSurfaceData(ChSharedPtr<ChBody> newbody) { assert(typeid(*newbody.get_ptr()) == typeid(ChBody)); ChSharedPtr<ChMaterialSurface>& mat = newbody->GetMaterialSurface(); data_manager->host_data.fric_data.push_back( R3(mat->GetKfriction(), mat->GetRollingFriction(), mat->GetSpinningFriction())); data_manager->host_data.cohesion_data.push_back(mat->GetCohesion()); data_manager->host_data.compliance_data.push_back( R4(mat->GetCompliance(), mat->GetComplianceT(), mat->GetComplianceRolling(), mat->GetComplianceSpinning())); } void ChSystemParallelDVI::UpdateBodies() { real3 *vel_pointer = data_manager->host_data.vel_data.data(); real3 *omg_pointer = data_manager->host_data.omg_data.data(); real3 *pos_pointer = data_manager->host_data.pos_data.data(); real4 *rot_pointer = data_manager->host_data.rot_data.data(); real3 *inr_pointer = data_manager->host_data.inr_data.data(); real3 *frc_pointer = data_manager->host_data.frc_data.data(); real3 *trq_pointer = data_manager->host_data.trq_data.data(); bool *active_pointer = data_manager->host_data.active_data.data(); bool *collide_pointer = data_manager->host_data.collide_data.data(); real *mass_pointer = data_manager->host_data.mass_data.data(); real3 *fric_pointer = data_manager->host_data.fric_data.data(); real *cohesion_pointer = data_manager->host_data.cohesion_data.data(); real4 *compliance_pointer = data_manager->host_data.compliance_data.data(); real3 *lim_pointer = data_manager->host_data.lim_data.data(); #pragma omp parallel for for (int i = 0; i < bodylist.size(); i++) { bodylist[i]->UpdateTime(ChTime); //bodylist[i]->TrySleeping(); // See if the body can fall asleep; if so, put it to sleeping bodylist[i]->ClampSpeed(); // Apply limits (if in speed clamping mode) to speeds. bodylist[i]->ComputeGyro(); // Set the gyroscopic momentum. bodylist[i]->UpdateForces(ChTime); bodylist[i]->VariablesFbReset(); bodylist[i]->VariablesFbLoadForces(GetStep()); bodylist[i]->VariablesQbLoadSpeed(); bodylist[i]->UpdateMarkers(ChTime); //because the loop is running in parallel, this cannot be run (not really needed anyways) //bodylist[i]->InjectVariables(*this->LCP_descriptor); ChMatrix33<> inertia = bodylist[i]->VariablesBody().GetBodyInvInertia(); vel_pointer[i] = (R3(bodylist[i]->Variables().Get_qb().ElementN(0), bodylist[i]->Variables().Get_qb().ElementN(1), bodylist[i]->Variables().Get_qb().ElementN(2))); omg_pointer[i] = (R3(bodylist[i]->Variables().Get_qb().ElementN(3), bodylist[i]->Variables().Get_qb().ElementN(4), bodylist[i]->Variables().Get_qb().ElementN(5))); pos_pointer[i] = (R3(bodylist[i]->GetPos().x, bodylist[i]->GetPos().y, bodylist[i]->GetPos().z)); rot_pointer[i] = (R4(bodylist[i]->GetRot().e0, bodylist[i]->GetRot().e1, bodylist[i]->GetRot().e2, bodylist[i]->GetRot().e3)); inr_pointer[i] = (R3(inertia.GetElement(0, 0), inertia.GetElement(1, 1), inertia.GetElement(2, 2))); frc_pointer[i] = (R3(bodylist[i]->Variables().Get_fb().ElementN(0), bodylist[i]->Variables().Get_fb().ElementN(1), bodylist[i]->Variables().Get_fb().ElementN(2))); //forces trq_pointer[i] = (R3(bodylist[i]->Variables().Get_fb().ElementN(3), bodylist[i]->Variables().Get_fb().ElementN(4), bodylist[i]->Variables().Get_fb().ElementN(5))); //torques active_pointer[i] = bodylist[i]->IsActive(); collide_pointer[i] = bodylist[i]->GetCollide(); mass_pointer[i] = 1.0f / bodylist[i]->VariablesBody().GetBodyMass(); fric_pointer[i] = R3(bodylist[i]->GetKfriction(), ((bodylist[i]))->GetMaterialSurface()->GetRollingFriction(), ((bodylist[i]))->GetMaterialSurface()->GetSpinningFriction()); cohesion_pointer[i] = bodylist[i]->GetMaterialSurface()->GetCohesion(); compliance_pointer[i] = R4(bodylist[i]->GetMaterialSurface()->GetCompliance(), bodylist[i]->GetMaterialSurface()->GetComplianceT(), bodylist[i]->GetMaterialSurface()->GetComplianceRolling(), bodylist[i]->GetMaterialSurface()->GetComplianceSpinning()); lim_pointer[i] = (R3(bodylist[i]->GetLimitSpeed(), .05 / GetStep(), .05 / GetStep())); bodylist[i]->GetCollisionModel()->SyncPosition(); } } static inline chrono::ChVector<real> ToChVector(const real3 &a) { return chrono::ChVector<real>(a.x, a.y, a.z); } void ChSystemParallelDVI::SolveSystem() { data_manager->system_timer.Reset(); data_manager->system_timer.start("step"); data_manager->system_timer.start("update"); Setup(); Update(); data_manager->system_timer.stop("update"); data_manager->system_timer.start("collision"); collision_system->Run(); collision_system->ReportContacts(this->contact_container); data_manager->system_timer.stop("collision"); data_manager->system_timer.start("lcp"); ((ChLcpSolverParallel *) (LCP_solver_speed))->RunTimeStep(GetStep()); data_manager->system_timer.stop("lcp"); data_manager->system_timer.stop("step"); } void ChSystemParallelDVI::AssembleSystem() { collision_system->Run(); collision_system->ReportContacts(this->contact_container); this->contact_container->BeginAddContact(); chrono::collision::ChCollisionInfo icontact; for (int i = 0; i < data_manager->num_contacts; i++) { int2 cd_pair = data_manager->host_data.bids_rigid_rigid[i]; icontact.modelA = bodylist[cd_pair.x]->GetCollisionModel(); icontact.modelB = bodylist[cd_pair.y]->GetCollisionModel(); icontact.vN = ToChVector(data_manager->host_data.norm_rigid_rigid[i]); icontact.vpA = ToChVector(data_manager->host_data.cpta_rigid_rigid[i] + data_manager->host_data.pos_data[cd_pair.x]); icontact.vpB = ToChVector(data_manager->host_data.cptb_rigid_rigid[i] + data_manager->host_data.pos_data[cd_pair.y]); icontact.distance = data_manager->host_data.dpth_rigid_rigid[i]; this->contact_container->AddContact(icontact); } this->contact_container->EndAddContact(); { std::list<ChLink*>::iterator iterlink = linklist.begin(); while (iterlink != linklist.end()) { (*iterlink)->ConstraintsBiReset(); iterlink++; } std::vector<ChBody*>::iterator ibody = bodylist.begin(); while (ibody != bodylist.end()) { (*ibody)->VariablesFbReset(); ibody++; } this->contact_container->ConstraintsBiReset(); } LCPprepare_load(true, // Cq, true, // adds [M]*v_old to the known vector step, // f*dt step * step, // dt^2*K (nb only non-Schur based solvers support K matrix blocks) step, // dt*R (nb only non-Schur based solvers support R matrix blocks) 1.0, // M (for FEM with non-lumped masses, add their mass-matrixes) 1.0, // Ct (needed, for rheonomic motors) 1.0 / step, // C/dt max_penetration_recovery_speed, // vlim, max penetrations recovery speed (positive for exiting) true // do above max. clamping on -C/dt ); this->LCP_descriptor->BeginInsertion(); for (int i = 0; i < bodylist.size(); i++) { bodylist[i]->InjectVariables(*this->LCP_descriptor); } std::list<ChLink *>::iterator it; for (it = linklist.begin(); it != linklist.end(); it++) { (*it)->InjectConstraints(*this->LCP_descriptor); } this->contact_container->InjectConstraints(*this->LCP_descriptor); this->LCP_descriptor->EndInsertion(); } <commit_msg>Update function needs to be run before assembling everything otherwise the results will be different than what chrono and chrono-parallel report<commit_after>#include "chrono_parallel/ChSystemParallel.h" #include <omp.h> using namespace chrono; ChSystemParallelDVI::ChSystemParallelDVI(unsigned int max_objects) : ChSystemParallel(max_objects) { LCP_descriptor = new ChLcpSystemDescriptorParallelDVI(); LCP_solver_speed = new ChLcpSolverParallelDVI(); ((ChLcpSystemDescriptorParallelDVI*) LCP_descriptor)->data_container = data_manager; ((ChLcpSolverParallel*) LCP_solver_speed)->data_container = data_manager; data_manager->system_timer.AddTimer("ChConstraintRigidRigid_shurA_normal"); data_manager->system_timer.AddTimer("ChConstraintRigidRigid_shurA_sliding"); data_manager->system_timer.AddTimer("ChConstraintRigidRigid_shurA_spinning"); data_manager->system_timer.AddTimer("ChConstraintRigidRigid_shurA_reduce"); data_manager->system_timer.AddTimer("ChConstraintRigidRigid_shurB_normal"); data_manager->system_timer.AddTimer("ChConstraintRigidRigid_shurB_sliding"); data_manager->system_timer.AddTimer("ChConstraintRigidRigid_shurB_spinning"); data_manager->system_timer.AddTimer("ChSolverParallel_solverA"); data_manager->system_timer.AddTimer("ChSolverParallel_solverB"); data_manager->system_timer.AddTimer("ChSolverParallel_solverC"); data_manager->system_timer.AddTimer("ChSolverParallel_solverD"); data_manager->system_timer.AddTimer("ChSolverParallel_solverE"); data_manager->system_timer.AddTimer("ChSolverParallel_solverF"); data_manager->system_timer.AddTimer("ChSolverParallel_solverG"); data_manager->system_timer.AddTimer("ChSolverParallel_Project"); data_manager->system_timer.AddTimer("ChSolverParallel_Solve"); } void ChSystemParallelDVI::LoadMaterialSurfaceData(ChSharedPtr<ChBody> newbody) { assert(typeid(*newbody.get_ptr()) == typeid(ChBody)); ChSharedPtr<ChMaterialSurface>& mat = newbody->GetMaterialSurface(); data_manager->host_data.fric_data.push_back( R3(mat->GetKfriction(), mat->GetRollingFriction(), mat->GetSpinningFriction())); data_manager->host_data.cohesion_data.push_back(mat->GetCohesion()); data_manager->host_data.compliance_data.push_back( R4(mat->GetCompliance(), mat->GetComplianceT(), mat->GetComplianceRolling(), mat->GetComplianceSpinning())); } void ChSystemParallelDVI::UpdateBodies() { real3 *vel_pointer = data_manager->host_data.vel_data.data(); real3 *omg_pointer = data_manager->host_data.omg_data.data(); real3 *pos_pointer = data_manager->host_data.pos_data.data(); real4 *rot_pointer = data_manager->host_data.rot_data.data(); real3 *inr_pointer = data_manager->host_data.inr_data.data(); real3 *frc_pointer = data_manager->host_data.frc_data.data(); real3 *trq_pointer = data_manager->host_data.trq_data.data(); bool *active_pointer = data_manager->host_data.active_data.data(); bool *collide_pointer = data_manager->host_data.collide_data.data(); real *mass_pointer = data_manager->host_data.mass_data.data(); real3 *fric_pointer = data_manager->host_data.fric_data.data(); real *cohesion_pointer = data_manager->host_data.cohesion_data.data(); real4 *compliance_pointer = data_manager->host_data.compliance_data.data(); real3 *lim_pointer = data_manager->host_data.lim_data.data(); #pragma omp parallel for for (int i = 0; i < bodylist.size(); i++) { bodylist[i]->UpdateTime(ChTime); //bodylist[i]->TrySleeping(); // See if the body can fall asleep; if so, put it to sleeping bodylist[i]->ClampSpeed(); // Apply limits (if in speed clamping mode) to speeds. bodylist[i]->ComputeGyro(); // Set the gyroscopic momentum. bodylist[i]->UpdateForces(ChTime); bodylist[i]->VariablesFbReset(); bodylist[i]->VariablesFbLoadForces(GetStep()); bodylist[i]->VariablesQbLoadSpeed(); bodylist[i]->UpdateMarkers(ChTime); //because the loop is running in parallel, this cannot be run (not really needed anyways) //bodylist[i]->InjectVariables(*this->LCP_descriptor); ChMatrix33<> inertia = bodylist[i]->VariablesBody().GetBodyInvInertia(); vel_pointer[i] = (R3(bodylist[i]->Variables().Get_qb().ElementN(0), bodylist[i]->Variables().Get_qb().ElementN(1), bodylist[i]->Variables().Get_qb().ElementN(2))); omg_pointer[i] = (R3(bodylist[i]->Variables().Get_qb().ElementN(3), bodylist[i]->Variables().Get_qb().ElementN(4), bodylist[i]->Variables().Get_qb().ElementN(5))); pos_pointer[i] = (R3(bodylist[i]->GetPos().x, bodylist[i]->GetPos().y, bodylist[i]->GetPos().z)); rot_pointer[i] = (R4(bodylist[i]->GetRot().e0, bodylist[i]->GetRot().e1, bodylist[i]->GetRot().e2, bodylist[i]->GetRot().e3)); inr_pointer[i] = (R3(inertia.GetElement(0, 0), inertia.GetElement(1, 1), inertia.GetElement(2, 2))); frc_pointer[i] = (R3(bodylist[i]->Variables().Get_fb().ElementN(0), bodylist[i]->Variables().Get_fb().ElementN(1), bodylist[i]->Variables().Get_fb().ElementN(2))); //forces trq_pointer[i] = (R3(bodylist[i]->Variables().Get_fb().ElementN(3), bodylist[i]->Variables().Get_fb().ElementN(4), bodylist[i]->Variables().Get_fb().ElementN(5))); //torques active_pointer[i] = bodylist[i]->IsActive(); collide_pointer[i] = bodylist[i]->GetCollide(); mass_pointer[i] = 1.0f / bodylist[i]->VariablesBody().GetBodyMass(); fric_pointer[i] = R3(bodylist[i]->GetKfriction(), ((bodylist[i]))->GetMaterialSurface()->GetRollingFriction(), ((bodylist[i]))->GetMaterialSurface()->GetSpinningFriction()); cohesion_pointer[i] = bodylist[i]->GetMaterialSurface()->GetCohesion(); compliance_pointer[i] = R4(bodylist[i]->GetMaterialSurface()->GetCompliance(), bodylist[i]->GetMaterialSurface()->GetComplianceT(), bodylist[i]->GetMaterialSurface()->GetComplianceRolling(), bodylist[i]->GetMaterialSurface()->GetComplianceSpinning()); lim_pointer[i] = (R3(bodylist[i]->GetLimitSpeed(), .05 / GetStep(), .05 / GetStep())); bodylist[i]->GetCollisionModel()->SyncPosition(); } } static inline chrono::ChVector<real> ToChVector(const real3 &a) { return chrono::ChVector<real>(a.x, a.y, a.z); } void ChSystemParallelDVI::SolveSystem() { data_manager->system_timer.Reset(); data_manager->system_timer.start("step"); data_manager->system_timer.start("update"); Setup(); Update(); data_manager->system_timer.stop("update"); data_manager->system_timer.start("collision"); collision_system->Run(); collision_system->ReportContacts(this->contact_container); data_manager->system_timer.stop("collision"); data_manager->system_timer.start("lcp"); ((ChLcpSolverParallel *) (LCP_solver_speed))->RunTimeStep(GetStep()); data_manager->system_timer.stop("lcp"); data_manager->system_timer.stop("step"); } void ChSystemParallelDVI::AssembleSystem() { Setup(); collision_system->Run(); collision_system->ReportContacts(this->contact_container); ChSystem::Update(); this->contact_container->BeginAddContact(); chrono::collision::ChCollisionInfo icontact; for (int i = 0; i < data_manager->num_contacts; i++) { int2 cd_pair = data_manager->host_data.bids_rigid_rigid[i]; icontact.modelA = bodylist[cd_pair.x]->GetCollisionModel(); icontact.modelB = bodylist[cd_pair.y]->GetCollisionModel(); icontact.vN = ToChVector(data_manager->host_data.norm_rigid_rigid[i]); icontact.vpA = ToChVector(data_manager->host_data.cpta_rigid_rigid[i] + data_manager->host_data.pos_data[cd_pair.x]); icontact.vpB = ToChVector(data_manager->host_data.cptb_rigid_rigid[i] + data_manager->host_data.pos_data[cd_pair.y]); icontact.distance = data_manager->host_data.dpth_rigid_rigid[i]; this->contact_container->AddContact(icontact); } this->contact_container->EndAddContact(); { std::list<ChLink*>::iterator iterlink = linklist.begin(); while (iterlink != linklist.end()) { (*iterlink)->ConstraintsBiReset(); iterlink++; } std::vector<ChBody*>::iterator ibody = bodylist.begin(); while (ibody != bodylist.end()) { (*ibody)->VariablesFbReset(); ibody++; } this->contact_container->ConstraintsBiReset(); } LCPprepare_load(true, // Cq, true, // adds [M]*v_old to the known vector step, // f*dt step * step, // dt^2*K (nb only non-Schur based solvers support K matrix blocks) step, // dt*R (nb only non-Schur based solvers support R matrix blocks) 1.0, // M (for FEM with non-lumped masses, add their mass-matrixes) 1.0, // Ct (needed, for rheonomic motors) 1.0 / step, // C/dt max_penetration_recovery_speed, // vlim, max penetrations recovery speed (positive for exiting) true // do above max. clamping on -C/dt ); this->LCP_descriptor->BeginInsertion(); for (int i = 0; i < bodylist.size(); i++) { bodylist[i]->InjectVariables(*this->LCP_descriptor); } std::list<ChLink *>::iterator it; for (it = linklist.begin(); it != linklist.end(); it++) { (*it)->InjectConstraints(*this->LCP_descriptor); } this->contact_container->InjectConstraints(*this->LCP_descriptor); this->LCP_descriptor->EndInsertion(); } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_obus_linktrain.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,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 p9_io_obus_linktrain.C /// @brief I/O Link Training on the Abus(Obus PHY) Links. ///----------------------------------------------------------------------------- /// *HWP HWP Owner : Chris Steffen <[email protected]> /// *HWP HWP Backup Owner : Gary Peterson <[email protected]> /// *HWP FW Owner : Jamie Knight <[email protected]> /// *HWP Team : IO /// *HWP Level : 3 /// *HWP Consumed by : FSP:HB ///----------------------------------------------------------------------------- /// /// @verbatim /// High-level procedure flow: /// /// Train the link. /// /// Procedure Prereq: /// - System clocks are running. /// - Scominit Procedure is completed. /// - Dccal Procedure is completed. /// /// @endverbatim ///---------------------------------------------------------------------------- //------------------------------------------------------------------------------ // Defines //------------------------------------------------------------------------------ //----------------------------------------------------------------------------- // Includes //----------------------------------------------------------------------------- #include <p9_io_obus_linktrain.H> #include <p9_io_scom.H> #include <p9_io_regs.H> #include <p9_io_common.H> #include <p9_obus_scom_addresses.H> #include <p9_obus_scom_addresses_fld.H> //----------------------------------------------------------------------------- // Definitions //----------------------------------------------------------------------------- /** * @brief A HWP to perform FIFO init for ABUS(OPT) * @param[in] i_mode Linktraining Mode * @param[in] i_tgt Reference to the Target * @retval ReturnCode */ fapi2::ReturnCode p9_io_obus_linktrain(const OBUS_TGT& i_tgt) { FAPI_IMP("p9_io_obus_linktrain: P9 I/O OPT Abus Entering"); const uint32_t MAX_LANES = 24; const uint8_t GRP0 = 0; char l_tgt_str[fapi2::MAX_ECMD_STRING_LEN]; fapi2::toString(i_tgt, l_tgt_str, fapi2::MAX_ECMD_STRING_LEN); fapi2::buffer<uint64_t> l_data = 0; fapi2::buffer<uint64_t> l_dl_control_data; fapi2::buffer<uint64_t> l_dl_control_mask; fapi2::ATTR_PROC_FABRIC_LINK_ACTIVE_Type l_fbc_active; fapi2::ATTR_LINK_TRAIN_Type l_link_train; fapi2::ATTR_CHIP_EC_FEATURE_HW419022_Type l_hw419022 = 0; fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> i_chip_target = i_tgt.getParent<fapi2::TARGET_TYPE_PROC_CHIP>(); bool l_even = true; bool l_odd = true; FAPI_DBG("I/O Abus FIFO init: Target(%s)", l_tgt_str); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_LINK_ACTIVE, i_tgt, l_fbc_active), "Error from FAPI_ATTR_GET (ATTR_PROC_FABRIC_LINK_ACTIVE)"); if (!l_fbc_active) { FAPI_DBG("Skipping link, not active for FBC protocol"); goto fapi_try_exit; } // PHY initialization sequence: // - clear TX_UNLOAD_CLK_DISABLE // - set TX_FIFO_INIT // - set TX_UNLOAD_CLK_DISABLE // - set RX_AC_COUPLED // Clear TX_UNLOAD_CLK_DISABLE for (uint32_t lane = 0; lane < MAX_LANES; ++lane) { FAPI_TRY(io::read(OPT_TX_MODE2_PL, i_tgt, GRP0, lane, l_data)); io::set(OPT_TX_UNLOAD_CLK_DISABLE, 0, l_data); FAPI_TRY(io::write(OPT_TX_MODE2_PL, i_tgt, GRP0, lane, l_data)); } // Set TX_FIFO_INIT l_data.flush<0>(); io::set(OPT_TX_FIFO_INIT, 1, l_data); for (uint32_t lane = 0; lane < MAX_LANES; ++lane) { FAPI_TRY(io::write(OPT_TX_CNTL1G_PL, i_tgt, GRP0, lane, l_data)); } // Set TX_UNLOAD_CLK_DISABLE for (uint32_t lane = 0; lane < MAX_LANES; ++lane) { FAPI_TRY(io::read(OPT_TX_MODE2_PL, i_tgt, GRP0, lane, l_data)); io::set(OPT_TX_UNLOAD_CLK_DISABLE, 1, l_data ); FAPI_TRY(io::write(OPT_TX_MODE2_PL, i_tgt, GRP0, lane, l_data)); } FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_HW419022, i_chip_target, l_hw419022), "Error from FAPI_ATTR_GET (fapi2::ATTR_CHIP_EC_FEATURE_HW419022)"); // Cable CDR lock // determine link train capabilities (half/full) FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_LINK_TRAIN, i_tgt, l_link_train), "Error from FAPI_ATTR_GET (ATTR_LINK_TRAIN)"); l_even = (l_link_train == fapi2::ENUM_ATTR_LINK_TRAIN_BOTH) || (l_link_train == fapi2::ENUM_ATTR_LINK_TRAIN_EVEN_ONLY); l_odd = (l_link_train == fapi2::ENUM_ATTR_LINK_TRAIN_BOTH) || (l_link_train == fapi2::ENUM_ATTR_LINK_TRAIN_ODD_ONLY); // set TX lane control to force send of TS1 pattern if (l_even) { FAPI_TRY(fapi2::putScom(i_tgt, OBUS_LL0_IOOL_LINK0_TX_LANE_CONTROL, 0x1111111111100000ULL), "Error from putScom (OBUS_LL0_IOOL_LINK0_TX_LANE_CONTROL)"); } if (l_odd) { FAPI_TRY(fapi2::putScom(i_tgt, OBUS_LL0_IOOL_LINK1_TX_LANE_CONTROL, 0x1111111111100000ULL), "Error from putScom (OBUS_LL0_IOOL_LINK1_TX_LANE_CONTROL)"); } // Delay to compensate for active links FAPI_TRY(fapi2::delay(100000000, 1000000), "Error from A-link retimer delay"); // DD1.1+ HW Start training sequence if(!l_hw419022) { // clear TX lane control overrides if (l_even) { l_dl_control_data.setBit<OBUS_LL0_IOOL_CONTROL_LINK0_PHY_TRAINING>(); l_dl_control_mask.setBit<OBUS_LL0_IOOL_CONTROL_LINK0_PHY_TRAINING>(); FAPI_TRY(fapi2::putScom(i_tgt, OBUS_LL0_IOOL_LINK0_TX_LANE_CONTROL, 0x0000000000000000ULL), "Error from putScom (OBUS_LL0_IOOL_LINK0_TX_LANE_CONTROL)"); } if (l_odd) { l_dl_control_data.setBit<OBUS_LL0_IOOL_CONTROL_LINK1_PHY_TRAINING>(); l_dl_control_mask.setBit<OBUS_LL0_IOOL_CONTROL_LINK1_PHY_TRAINING>(); FAPI_TRY(fapi2::putScom(i_tgt, OBUS_LL0_IOOL_LINK1_TX_LANE_CONTROL, 0x0000000000000000ULL), "Error from putScom (OBUS_LL0_IOOL_LINK1_TX_LANE_CONTROL)"); } // Start phy training FAPI_TRY(fapi2::putScomUnderMask(i_tgt, OBUS_LL0_IOOL_CONTROL, l_dl_control_data, l_dl_control_mask), "Error writing DLL control register (0x%08X)!", OBUS_LL0_IOOL_CONTROL); } fapi_try_exit: FAPI_IMP("p9_io_obus_linktrain: P9 I/O OPT Abus Exiting"); return fapi2::current_err; } <commit_msg>SMP Abus PPE Workaround<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_obus_linktrain.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,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 p9_io_obus_linktrain.C /// @brief I/O Link Training on the Abus(Obus PHY) Links. ///----------------------------------------------------------------------------- /// *HWP HWP Owner : Chris Steffen <[email protected]> /// *HWP HWP Backup Owner : Gary Peterson <[email protected]> /// *HWP FW Owner : Jamie Knight <[email protected]> /// *HWP Team : IO /// *HWP Level : 3 /// *HWP Consumed by : FSP:HB ///----------------------------------------------------------------------------- /// /// @verbatim /// High-level procedure flow: /// /// Train the link. /// /// Procedure Prereq: /// - System clocks are running. /// - Scominit Procedure is completed. /// - Dccal Procedure is completed. /// /// @endverbatim ///---------------------------------------------------------------------------- //------------------------------------------------------------------------------ // Defines //------------------------------------------------------------------------------ //----------------------------------------------------------------------------- // Includes //----------------------------------------------------------------------------- #include <p9_io_obus_linktrain.H> #include <p9_io_obus_pdwn_lanes.H> #include <p9_io_scom.H> #include <p9_io_regs.H> #include <p9_io_common.H> #include <p9_obus_scom_addresses.H> #include <p9_obus_scom_addresses_fld.H> //----------------------------------------------------------------------------- // Definitions //----------------------------------------------------------------------------- /** * @brief A HWP to perform FIFO init for ABUS(OPT) * @param[in] i_mode Linktraining Mode * @param[in] i_tgt Reference to the Target * @retval ReturnCode */ fapi2::ReturnCode p9_io_obus_linktrain(const OBUS_TGT& i_tgt) { FAPI_IMP("p9_io_obus_linktrain: P9 I/O OPT Abus Entering"); const uint32_t MAX_LANES = 24; const uint8_t GRP0 = 0; char l_tgt_str[fapi2::MAX_ECMD_STRING_LEN]; fapi2::toString(i_tgt, l_tgt_str, fapi2::MAX_ECMD_STRING_LEN); fapi2::buffer<uint64_t> l_data = 0; fapi2::buffer<uint64_t> l_dl_control_data; fapi2::buffer<uint64_t> l_dl_control_mask; fapi2::ATTR_PROC_FABRIC_LINK_ACTIVE_Type l_fbc_active; fapi2::ATTR_LINK_TRAIN_Type l_link_train; fapi2::ATTR_CHIP_EC_FEATURE_HW419022_Type l_hw419022 = 0; fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> i_chip_target = i_tgt.getParent<fapi2::TARGET_TYPE_PROC_CHIP>(); bool l_even = true; bool l_odd = true; FAPI_DBG("I/O Abus FIFO init: Target(%s)", l_tgt_str); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_LINK_ACTIVE, i_tgt, l_fbc_active), "Error from FAPI_ATTR_GET (ATTR_PROC_FABRIC_LINK_ACTIVE)"); if (!l_fbc_active) { FAPI_DBG("Skipping link, not active for FBC protocol"); goto fapi_try_exit; } // PHY initialization sequence: // - clear TX_UNLOAD_CLK_DISABLE // - set TX_FIFO_INIT // - set TX_UNLOAD_CLK_DISABLE // - set RX_AC_COUPLED // Clear TX_UNLOAD_CLK_DISABLE for (uint32_t lane = 0; lane < MAX_LANES; ++lane) { FAPI_TRY(io::read(OPT_TX_MODE2_PL, i_tgt, GRP0, lane, l_data)); io::set(OPT_TX_UNLOAD_CLK_DISABLE, 0, l_data); FAPI_TRY(io::write(OPT_TX_MODE2_PL, i_tgt, GRP0, lane, l_data)); } // Set TX_FIFO_INIT l_data.flush<0>(); io::set(OPT_TX_FIFO_INIT, 1, l_data); for (uint32_t lane = 0; lane < MAX_LANES; ++lane) { FAPI_TRY(io::write(OPT_TX_CNTL1G_PL, i_tgt, GRP0, lane, l_data)); } // Set TX_UNLOAD_CLK_DISABLE for (uint32_t lane = 0; lane < MAX_LANES; ++lane) { FAPI_TRY(io::read(OPT_TX_MODE2_PL, i_tgt, GRP0, lane, l_data)); io::set(OPT_TX_UNLOAD_CLK_DISABLE, 1, l_data ); FAPI_TRY(io::write(OPT_TX_MODE2_PL, i_tgt, GRP0, lane, l_data)); } FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_HW419022, i_chip_target, l_hw419022), "Error from FAPI_ATTR_GET (fapi2::ATTR_CHIP_EC_FEATURE_HW419022)"); // Cable CDR lock // determine link train capabilities (half/full) FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_LINK_TRAIN, i_tgt, l_link_train), "Error from FAPI_ATTR_GET (ATTR_LINK_TRAIN)"); l_even = (l_link_train == fapi2::ENUM_ATTR_LINK_TRAIN_BOTH) || (l_link_train == fapi2::ENUM_ATTR_LINK_TRAIN_EVEN_ONLY); l_odd = (l_link_train == fapi2::ENUM_ATTR_LINK_TRAIN_BOTH) || (l_link_train == fapi2::ENUM_ATTR_LINK_TRAIN_ODD_ONLY); // set TX lane control to force send of TS1 pattern if (l_even) { FAPI_TRY(fapi2::putScom(i_tgt, OBUS_LL0_IOOL_LINK0_TX_LANE_CONTROL, 0x1111111111100000ULL), "Error from putScom (OBUS_LL0_IOOL_LINK0_TX_LANE_CONTROL)"); } else { const uint32_t EVEN_LANES = 0x000007FF; FAPI_TRY(p9_io_obus_pdwn_lanes(i_tgt, EVEN_LANES), "Error from p9_io_obus_pdwn_lanes"); } if (l_odd) { FAPI_TRY(fapi2::putScom(i_tgt, OBUS_LL0_IOOL_LINK1_TX_LANE_CONTROL, 0x1111111111100000ULL), "Error from putScom (OBUS_LL0_IOOL_LINK1_TX_LANE_CONTROL)"); } else { const uint32_t ODD_LANES = 0x00FFE000; FAPI_TRY(p9_io_obus_pdwn_lanes(i_tgt, ODD_LANES), "Error from p9_io_obus_pdwn_lanes"); } // Delay to compensate for active links FAPI_TRY(fapi2::delay(100000000, 1000000), "Error from A-link retimer delay"); // DD1.1+ HW Start training sequence if(!l_hw419022) { // clear TX lane control overrides if (l_even) { l_dl_control_data.setBit<OBUS_LL0_IOOL_CONTROL_LINK0_PHY_TRAINING>(); l_dl_control_mask.setBit<OBUS_LL0_IOOL_CONTROL_LINK0_PHY_TRAINING>(); FAPI_TRY(fapi2::putScom(i_tgt, OBUS_LL0_IOOL_LINK0_TX_LANE_CONTROL, 0x0000000000000000ULL), "Error from putScom (OBUS_LL0_IOOL_LINK0_TX_LANE_CONTROL)"); } if (l_odd) { l_dl_control_data.setBit<OBUS_LL0_IOOL_CONTROL_LINK1_PHY_TRAINING>(); l_dl_control_mask.setBit<OBUS_LL0_IOOL_CONTROL_LINK1_PHY_TRAINING>(); FAPI_TRY(fapi2::putScom(i_tgt, OBUS_LL0_IOOL_LINK1_TX_LANE_CONTROL, 0x0000000000000000ULL), "Error from putScom (OBUS_LL0_IOOL_LINK1_TX_LANE_CONTROL)"); } // Start phy training FAPI_TRY(fapi2::putScomUnderMask(i_tgt, OBUS_LL0_IOOL_CONTROL, l_dl_control_data, l_dl_control_mask), "Error writing DLL control register (0x%08X)!", OBUS_LL0_IOOL_CONTROL); } fapi_try_exit: FAPI_IMP("p9_io_obus_linktrain: P9 I/O OPT Abus Exiting"); return fapi2::current_err; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_block_wakeup_intr.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,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 p9_block_wakeup_intr.C /// @brief Set/reset the BLOCK_REG_WKUP_SOURCES bit in the PCBS-PM associated /// with an EX chiplet /// // *HWP HWP Owner: Amit Kumar <[email protected]> // *HWP FW Owner: Bilicon Patil <[email protected]> // *HWP Team: PM // *HWP Level: 2 // *HWP Consumed by: FSP:HS /// /// @verbatim /// High-level procedure flow: /// /// With set/reset enum parameter, either set or clear PMGP0(53) /// /// Procedure Prereq: /// - System clocks are running /// @endverbatim /// //------------------------------------------------------------------------------ // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_block_wakeup_intr.H> // This must stay in sync with enum OP_TYPE enum in header file const char* OP_TYPE_STRING[] = { "SET", "CLEAR" }; // ---------------------------------------------------------------------- // Procedure Function // ---------------------------------------------------------------------- /// @brief @brief Set/reset the BLOCK_INTR_INPUTS bit in the Core PPM /// associated with an EX chiplet fapi2::ReturnCode p9_block_wakeup_intr( const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_core_target, const p9pmblockwkup::OP_TYPE i_operation) { FAPI_INF("> p9_block_wakeup_intr..."); fapi2::buffer<uint64_t> l_data64 = 0; // Get the core number uint8_t l_attr_chip_unit_pos = 0; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_core_target, l_attr_chip_unit_pos), "fapiGetAttribute of ATTR_CHIP_UNIT_POS failed"); // Read for trace { fapi2::buffer<uint64_t> l_cpmmr = 0; fapi2::buffer<uint64_t> l_gpmmr = 0; // Read the CPMMR and GPMMR as a trace FAPI_TRY(fapi2::getScom(i_core_target, C_CPPM_CPMMR, l_cpmmr), "getScom of CPMMR failed"); FAPI_TRY(fapi2::getScom(i_core_target, C_PPM_GPMMR, l_gpmmr), "getScom of GPMMR failed"); FAPI_DBG("Debug: before setting PPM_WRITE_OVERRIDE on Core %d - CPPMR: 0x%016llX GPMMR: 0x%016llX", l_attr_chip_unit_pos, l_cpmmr, l_gpmmr); } // Ensure access to the GPMMR is in place using CPMMR Write Access // Override. This will not affect the CME functionality as only the // Block Wake-up bit is being manipulated -- a bit that the CME does // not control but does react upon. FAPI_INF("Set the CPPM PPM Write Override"); l_data64.flush<0>().setBit<C_CPPM_CPMMR_PPM_WRITE_OVERRIDE>(); FAPI_TRY(fapi2::putScom(i_core_target, C_CPPM_CPMMR_OR, l_data64), "putScom of CPMMR to set PMM Write Override failed"); l_data64.flush<0>().setBit<BLOCK_REG_WKUP_EVENTS>(); switch (i_operation) { case p9pmblockwkup::SET: // @todo RTC 144905 Add Special Wakeup setting here when available FAPI_INF("Setting GPMMR[Block Interrupt Sources] on Core %d", l_attr_chip_unit_pos); FAPI_TRY(fapi2::putScom(i_core_target, C_PPM_GPMMR_OR, l_data64), "Setting GPMMR failed"); // @todo RTC 144905 Add Special Wakeup clearing here when available break; case p9pmblockwkup::SET_NOSPWUP: FAPI_INF("Setting GPMMR[Block Interrupt Sources] without Special Wake-up on Core %d", l_attr_chip_unit_pos); FAPI_TRY(fapi2::putScom(i_core_target, C_PPM_GPMMR_OR, l_data64), "Setting GPMMR failed"); break; case p9pmblockwkup::CLEAR: FAPI_INF("Clearing GPMMR[Block Interrupt Sources] on Core %d", l_attr_chip_unit_pos); FAPI_TRY(fapi2::putScom(i_core_target, C_PPM_GPMMR_CLEAR, l_data64), "Clearing GPMMR failed"); break; default: ; } FAPI_INF("Clear the CPPM PPM Write Override"); l_data64.flush<0>().setBit<C_CPPM_CPMMR_PPM_WRITE_OVERRIDE>(); FAPI_TRY(fapi2::putScom(i_core_target, C_CPPM_CPMMR_CLEAR, l_data64), "putScom of CPMMR to clear PMM Write Override failed"); fapi_try_exit: FAPI_INF("< p9_block_wakeup_intr..."); return fapi2::current_err; } <commit_msg>p9_block_wakeup_intr Level 2 - fix PPE compilation issue<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_block_wakeup_intr.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,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 p9_block_wakeup_intr.C /// @brief Set/reset the BLOCK_REG_WKUP_SOURCES bit in the PCBS-PM associated /// with an EX chiplet /// // *HWP HWP Owner: Amit Kumar <[email protected]> // *HWP FW Owner: Prem Jha <[email protected]> // *HWP Team: PM // *HWP Level: 2 // *HWP Consumed by: FSP:HS /// /// @verbatim /// High-level procedure flow: /// /// With set/reset enum parameter, either set or clear PMGP0(53) /// /// Procedure Prereq: /// - System clocks are running /// @endverbatim /// //------------------------------------------------------------------------------ // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_block_wakeup_intr.H> #include <p9_hcd_common.H> // This must stay in sync with enum OP_TYPE enum in header file const char* OP_TYPE_STRING[] = { "SET", "CLEAR" }; // ---------------------------------------------------------------------- // Procedure Function // ---------------------------------------------------------------------- /// @brief @brief Set/reset the BLOCK_INTR_INPUTS bit in the Core PPM /// associated with an EX chiplet fapi2::ReturnCode p9_block_wakeup_intr( const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_core_target, const p9pmblockwkup::OP_TYPE i_operation) { FAPI_INF("> p9_block_wakeup_intr..."); fapi2::buffer<uint64_t> l_data64 = 0; // Get the core number uint8_t l_attr_chip_unit_pos = 0; fapi2::Target<fapi2::TARGET_TYPE_PERV> l_perv = i_core_target.getParent<fapi2::TARGET_TYPE_PERV>(); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_perv, l_attr_chip_unit_pos), "fapiGetAttribute of ATTR_CHIP_UNIT_POS failed"); l_attr_chip_unit_pos = l_attr_chip_unit_pos - p9hcd::PERV_TO_CORE_POS_OFFSET; // Read for trace { fapi2::buffer<uint64_t> l_cpmmr = 0; fapi2::buffer<uint64_t> l_gpmmr = 0; // Read the CPMMR and GPMMR as a trace FAPI_TRY(fapi2::getScom(i_core_target, C_CPPM_CPMMR, l_cpmmr), "getScom of CPMMR failed"); FAPI_TRY(fapi2::getScom(i_core_target, C_PPM_GPMMR, l_gpmmr), "getScom of GPMMR failed"); FAPI_DBG("Debug: before setting PPM_WRITE_OVERRIDE on Core %d - CPPMR: 0x%016llX GPMMR: 0x%016llX", l_attr_chip_unit_pos, l_cpmmr, l_gpmmr); } // Ensure access to the GPMMR is in place using CPMMR Write Access // Override. This will not affect the CME functionality as only the // Block Wake-up bit is being manipulated -- a bit that the CME does // not control but does react upon. FAPI_INF("Set the CPPM PPM Write Override"); l_data64.flush<0>().setBit<C_CPPM_CPMMR_PPM_WRITE_OVERRIDE>(); FAPI_TRY(fapi2::putScom(i_core_target, C_CPPM_CPMMR_OR, l_data64), "putScom of CPMMR to set PMM Write Override failed"); l_data64.flush<0>().setBit<BLOCK_REG_WKUP_EVENTS>(); switch (i_operation) { case p9pmblockwkup::SET: // @todo RTC 144905 Add Special Wakeup setting here when available FAPI_INF("Setting GPMMR[Block Interrupt Sources] on Core %d", l_attr_chip_unit_pos); FAPI_TRY(fapi2::putScom(i_core_target, C_PPM_GPMMR_OR, l_data64), "Setting GPMMR failed"); // @todo RTC 144905 Add Special Wakeup clearing here when available break; case p9pmblockwkup::SET_NOSPWUP: FAPI_INF("Setting GPMMR[Block Interrupt Sources] without Special Wake-up on Core %d", l_attr_chip_unit_pos); FAPI_TRY(fapi2::putScom(i_core_target, C_PPM_GPMMR_OR, l_data64), "Setting GPMMR failed"); break; case p9pmblockwkup::CLEAR: FAPI_INF("Clearing GPMMR[Block Interrupt Sources] on Core %d", l_attr_chip_unit_pos); FAPI_TRY(fapi2::putScom(i_core_target, C_PPM_GPMMR_CLEAR, l_data64), "Clearing GPMMR failed"); break; default: ; } FAPI_INF("Clear the CPPM PPM Write Override"); l_data64.flush<0>().setBit<C_CPPM_CPMMR_PPM_WRITE_OVERRIDE>(); FAPI_TRY(fapi2::putScom(i_core_target, C_CPPM_CPMMR_CLEAR, l_data64), "putScom of CPMMR to clear PMM Write Override failed"); fapi_try_exit: FAPI_INF("< p9_block_wakeup_intr..."); return fapi2::current_err; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: helpagentwindow.cxx,v $ * * $Revision: 1.1 $ * * last change: $Author: fs $ $Date: 2001-05-07 15:18:58 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVTOOLS_HELPAGENTWIDNOW_HXX_ #include "helpagentwindow.hxx" #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _SV_BUTTON_HXX #include <vcl/button.hxx> #endif #ifndef _SV_BITMAP_HXX #include <vcl/bitmap.hxx> #endif #ifndef _SVTOOLS_HRC #include "svtools.hrc" #endif #ifndef _SVTOOLS_SVTDATA_HXX #include <svtools/svtdata.hxx> #endif #define WB_AGENT_STYLE 0 //........................................................................ namespace svt { //........................................................................ using namespace ::com::sun::star::uno; using namespace ::com::sun::star::awt; using namespace ::com::sun::star::lang; //==================================================================== //= HelpAgentWindow //==================================================================== //-------------------------------------------------------------------- HelpAgentWindow::HelpAgentWindow( Window* _pParent ) :FloatingWindow( _pParent, WB_AGENT_STYLE) ,m_pCloser(NULL) ,m_pCallback(NULL) { // ----------------- // the closer button Bitmap aCloserBitmap(SvtResId(BMP_HELP_AGENT_CLOSER)); Image aCloserImage( aCloserBitmap ); m_pCloser = new ImageButton( this, WB_NOTABSTOP | WB_NOPOINTERFOCUS ); static_cast<ImageButton*>(m_pCloser)->SetImage( aCloserImage ); static_cast<ImageButton*>(m_pCloser)->SetClickHdl( LINK(this, HelpAgentWindow, OnButtonClicked) ); m_pCloser->SetSizePixel( implOptimalButtonSize(aCloserImage) ); m_pCloser->Show(); m_pCloser->SetZOrder( NULL, WINDOW_ZORDER_LAST ); // ---------------------------- // calculate our preferred size Bitmap aHelpAgentBitmap(SvtResId(BMP_HELP_AGENT_IMAGE)); m_aPicture = Image( aHelpAgentBitmap ); m_aPreferredSize = m_aPicture.GetSizePixel(); m_aPreferredSize.Width() += 2; m_aPreferredSize.Height() += 2; Size aSize = GetSizePixel(); Size aOutputSize = GetOutputSizePixel(); m_aPreferredSize.Width() += aSize.Width() - aOutputSize.Width(); m_aPreferredSize.Height() += aSize.Height() - aOutputSize.Height(); SetPointer(Pointer(POINTER_REFHAND)); } //-------------------------------------------------------------------- HelpAgentWindow::~HelpAgentWindow() { if (m_pCloser && m_pCloser->IsTracking()) m_pCloser->EndTracking(); if (m_pCloser && m_pCloser->IsMouseCaptured()) m_pCloser->ReleaseMouse(); delete m_pCloser; } //-------------------------------------------------------------------- void HelpAgentWindow::Paint( const Rectangle& rRect ) { FloatingWindow::Paint(rRect); Size aOutputSize( GetOutputSizePixel() ); Rectangle aOutputRect( Point(), aOutputSize ); Rectangle aInnerRect( aOutputRect ); // paint the background SetLineColor( GetSettings().GetStyleSettings().GetFaceColor() ); SetFillColor( GetSettings().GetStyleSettings().GetFaceColor() ); DrawRect( aOutputRect ); // paint the image Size aPictureSize( m_aPicture.GetSizePixel() ); Point aPicturePos( aOutputRect.Left() + (aInnerRect.GetWidth() - aPictureSize.Width()) / 2, aOutputRect.Top() + (aInnerRect.GetHeight() - aPictureSize.Height()) / 2 ); DrawImage( aPicturePos, m_aPicture, 0 ); } //-------------------------------------------------------------------- void HelpAgentWindow::MouseButtonUp( const MouseEvent& rMEvt ) { FloatingWindow::MouseButtonUp(rMEvt); if (m_pCallback) m_pCallback->helpRequested(); } //-------------------------------------------------------------------- Size HelpAgentWindow::implOptimalButtonSize( const Image& _rButtonImage ) { Size aPreferredSize = _rButtonImage.GetSizePixel(); // add a small frame, needed by the button aPreferredSize.Width() += 5; aPreferredSize.Height() += 5; return aPreferredSize; } //-------------------------------------------------------------------- void HelpAgentWindow::Resize() { FloatingWindow::Resize(); Size aOutputSize = GetOutputSizePixel(); Size aCloserSize = m_pCloser->GetSizePixel(); if (m_pCloser) m_pCloser->SetPosPixel( Point(aOutputSize.Width() - aCloserSize.Width() - 3, 4) ); } //-------------------------------------------------------------------- IMPL_LINK( HelpAgentWindow, OnButtonClicked, Window*, _pWhichOne ) { if (m_pCloser == _pWhichOne) if (m_pCallback) m_pCallback->closeAgent(); return 0L; } //........................................................................ } // namespace svt //........................................................................ /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.1 2001/05/07 13:42:30 fs * initial checkin - help agent window * * * Revision 1.0 03.05.01 11:51:40 fs ************************************************************************/ <commit_msg>#65293# fix for gcc (needs temporary variable for Point() )<commit_after>/************************************************************************* * * $RCSfile: helpagentwindow.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2001-05-11 09:07:24 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVTOOLS_HELPAGENTWIDNOW_HXX_ #include "helpagentwindow.hxx" #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _SV_BUTTON_HXX #include <vcl/button.hxx> #endif #ifndef _SV_BITMAP_HXX #include <vcl/bitmap.hxx> #endif #ifndef _SVTOOLS_HRC #include "svtools.hrc" #endif #ifndef _SVTOOLS_SVTDATA_HXX #include <svtools/svtdata.hxx> #endif #define WB_AGENT_STYLE 0 //........................................................................ namespace svt { //........................................................................ using namespace ::com::sun::star::uno; using namespace ::com::sun::star::awt; using namespace ::com::sun::star::lang; //==================================================================== //= HelpAgentWindow //==================================================================== //-------------------------------------------------------------------- HelpAgentWindow::HelpAgentWindow( Window* _pParent ) :FloatingWindow( _pParent, WB_AGENT_STYLE) ,m_pCloser(NULL) ,m_pCallback(NULL) { // ----------------- // the closer button Bitmap aCloserBitmap(SvtResId(BMP_HELP_AGENT_CLOSER)); Image aCloserImage( aCloserBitmap ); m_pCloser = new ImageButton( this, WB_NOTABSTOP | WB_NOPOINTERFOCUS ); static_cast<ImageButton*>(m_pCloser)->SetImage( aCloserImage ); static_cast<ImageButton*>(m_pCloser)->SetClickHdl( LINK(this, HelpAgentWindow, OnButtonClicked) ); m_pCloser->SetSizePixel( implOptimalButtonSize(aCloserImage) ); m_pCloser->Show(); m_pCloser->SetZOrder( NULL, WINDOW_ZORDER_LAST ); // ---------------------------- // calculate our preferred size Bitmap aHelpAgentBitmap(SvtResId(BMP_HELP_AGENT_IMAGE)); m_aPicture = Image( aHelpAgentBitmap ); m_aPreferredSize = m_aPicture.GetSizePixel(); m_aPreferredSize.Width() += 2; m_aPreferredSize.Height() += 2; Size aSize = GetSizePixel(); Size aOutputSize = GetOutputSizePixel(); m_aPreferredSize.Width() += aSize.Width() - aOutputSize.Width(); m_aPreferredSize.Height() += aSize.Height() - aOutputSize.Height(); SetPointer(Pointer(POINTER_REFHAND)); } //-------------------------------------------------------------------- HelpAgentWindow::~HelpAgentWindow() { if (m_pCloser && m_pCloser->IsTracking()) m_pCloser->EndTracking(); if (m_pCloser && m_pCloser->IsMouseCaptured()) m_pCloser->ReleaseMouse(); delete m_pCloser; } //-------------------------------------------------------------------- void HelpAgentWindow::Paint( const Rectangle& rRect ) { FloatingWindow::Paint(rRect); Size aOutputSize( GetOutputSizePixel() ); Point aPoint=Point(); Rectangle aOutputRect( aPoint, aOutputSize ); Rectangle aInnerRect( aOutputRect ); // paint the background SetLineColor( GetSettings().GetStyleSettings().GetFaceColor() ); SetFillColor( GetSettings().GetStyleSettings().GetFaceColor() ); DrawRect( aOutputRect ); // paint the image Size aPictureSize( m_aPicture.GetSizePixel() ); Point aPicturePos( aOutputRect.Left() + (aInnerRect.GetWidth() - aPictureSize.Width()) / 2, aOutputRect.Top() + (aInnerRect.GetHeight() - aPictureSize.Height()) / 2 ); DrawImage( aPicturePos, m_aPicture, 0 ); } //-------------------------------------------------------------------- void HelpAgentWindow::MouseButtonUp( const MouseEvent& rMEvt ) { FloatingWindow::MouseButtonUp(rMEvt); if (m_pCallback) m_pCallback->helpRequested(); } //-------------------------------------------------------------------- Size HelpAgentWindow::implOptimalButtonSize( const Image& _rButtonImage ) { Size aPreferredSize = _rButtonImage.GetSizePixel(); // add a small frame, needed by the button aPreferredSize.Width() += 5; aPreferredSize.Height() += 5; return aPreferredSize; } //-------------------------------------------------------------------- void HelpAgentWindow::Resize() { FloatingWindow::Resize(); Size aOutputSize = GetOutputSizePixel(); Size aCloserSize = m_pCloser->GetSizePixel(); if (m_pCloser) m_pCloser->SetPosPixel( Point(aOutputSize.Width() - aCloserSize.Width() - 3, 4) ); } //-------------------------------------------------------------------- IMPL_LINK( HelpAgentWindow, OnButtonClicked, Window*, _pWhichOne ) { if (m_pCloser == _pWhichOne) if (m_pCallback) m_pCallback->closeAgent(); return 0L; } //........................................................................ } // namespace svt //........................................................................ /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.1 2001/05/07 15:18:58 fs * initial checkin - window for the new help agent * * Revision 1.1 2001/05/07 13:42:30 fs * initial checkin - help agent window * * * Revision 1.0 03.05.01 11:51:40 fs ************************************************************************/ <|endoftext|>
<commit_before>// Author: Enric Tejedor CERN 04/2019 // Original PyROOT code by Wim Lavrijsen, LBL /************************************************************************* * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ // Bindings #include "Python.h" #include "CPyCppyy.h" #include "RPyROOTApplication.h" // ROOT #include "TInterpreter.h" #include "TSystem.h" #include "TBenchmark.h" #include "TStyle.h" #include "TError.h" #include "Getline.h" #include "TVirtualMutex.h" //////////////////////////////////////////////////////////////////////////// /// \brief Create an RPyROOTApplication. /// \param[in] ignoreCmdLineOpts True if Python command line options should /// be ignored. /// \return false if gApplication is not null, true otherwise. /// /// If ignoreCmdLineOpts is false, this method processes the command line /// arguments from sys.argv. A distinction between arguments for /// TApplication and user arguments can be made by using "-" or "--" as a /// separator on the command line. /// /// For example, to enable batch mode from the command line: /// > python script_name.py -b -- user_arg1 ... user_argn /// or, if the user script receives no arguments: /// > python script_name.py -b bool PyROOT::RPyROOTApplication::CreateApplication(int ignoreCmdLineOpts) { if (!gApplication) { int argc = 1; char **argv = nullptr; if (ignoreCmdLineOpts) { argv = new char *[argc]; } else { // Retrieve sys.argv list from Python PyObject *argl = PySys_GetObject(const_cast<char *>("argv")); if (argl && 0 < PyList_Size(argl)) argc = (int)PyList_GET_SIZE(argl); argv = new char *[argc]; for (int i = 1; i < argc; ++i) { char *argi = const_cast<char *>(CPyCppyy_PyText_AsString(PyList_GET_ITEM(argl, i))); if (strcmp(argi, "-") == 0 || strcmp(argi, "--") == 0) { // Stop collecting options, the remaining are for the Python script argc = i; // includes program name break; } argv[i] = argi; } } #if PY_VERSION_HEX < 0x03000000 if (Py_GetProgramName() && strlen(Py_GetProgramName()) != 0) argv[0] = Py_GetProgramName(); else argv[0] = (char *)"python"; #else argv[0] = (char *)"python"; #endif gApplication = new RPyROOTApplication("PyROOT", &argc, argv); delete[] argv; // TApplication ctor has copied argv, so done with it return true; } return false; } //////////////////////////////////////////////////////////////////////////// /// \brief Setup the basic ROOT globals gBenchmark, gStyle and gProgname, /// if not already set. void PyROOT::RPyROOTApplication::InitROOTGlobals() { if (!gBenchmark) gBenchmark = new TBenchmark(); if (!gStyle) gStyle = new TStyle(); if (!gProgName) // should have been set by TApplication #if PY_VERSION_HEX < 0x03000000 gSystem->SetProgname(Py_GetProgramName()); #else gSystem->SetProgname("python"); #endif } //////////////////////////////////////////////////////////////////////////// /// \brief Translate ROOT error/warning to Python. static void ErrMsgHandler(int level, Bool_t abort, const char *location, const char *msg) { // Initialization from gEnv (the default handler will return w/o msg b/c level too low) if (gErrorIgnoreLevel == kUnset) ::DefaultErrorHandler(kUnset - 1, kFALSE, "", ""); if (level < gErrorIgnoreLevel) return; // Turn warnings into Python warnings if (level >= kError) { ::DefaultErrorHandler(level, abort, location, msg); } else if (level >= kWarning) { static const char *emptyString = ""; if (!location) location = emptyString; // This warning might be triggered while holding the ROOT lock, while // some other thread is holding the GIL and waiting for the ROOT lock. // That will trigger a deadlock. // So if ROOT is in MT mode, use ROOT's error handler that doesn't take // the GIL. if (!gGlobalMutex) { // Either printout or raise exception, depending on user settings PyErr_WarnExplicit(NULL, (char *)msg, (char *)location, 0, (char *)"ROOT", NULL); } else { ::DefaultErrorHandler(level, abort, location, msg); } } else { ::DefaultErrorHandler(level, abort, location, msg); } } //////////////////////////////////////////////////////////////////////////// /// \brief Install the ROOT message handler which will turn ROOT error /// messages into Python exceptions. void PyROOT::RPyROOTApplication::InitROOTMessageCallback() { SetErrorHandler((ErrorHandlerFunc_t)&ErrMsgHandler); } //////////////////////////////////////////////////////////////////////////// /// \brief Initialize an RPyROOTApplication. /// \param[in] self Always null, since this is a module function. /// \param[in] args Command line options PyObject *PyROOT::RPyROOTApplication::InitApplication(PyObject * /*self*/, PyObject *args) { int argc = PyTuple_GET_SIZE(args); if (argc == 1) { PyObject *ignoreCmdLineOpts = PyTuple_GetItem(args, 0); if (!PyBool_Check(ignoreCmdLineOpts)) { PyErr_SetString(PyExc_TypeError, "Expected boolean type as argument."); return nullptr; } if (CreateApplication(PyObject_IsTrue(ignoreCmdLineOpts))) { InitROOTGlobals(); InitROOTMessageCallback(); } } else { PyErr_Format(PyExc_TypeError, "Expected 1 argument, %d passed.", argc); return nullptr; } Py_RETURN_NONE; } //////////////////////////////////////////////////////////////////////////// /// \brief Construct a TApplication for PyROOT. /// \param[in] acn Application class name. /// \param[in] argc Number of arguments. /// \param[in] argv Arguments. PyROOT::RPyROOTApplication::RPyROOTApplication(const char *acn, int *argc, char **argv) : TApplication(acn, argc, argv) { // Save current interpreter context gInterpreter->SaveContext(); gInterpreter->SaveGlobalsContext(); // Prevent crashes on accessing history Gl_histinit((char *)"-"); // Prevent ROOT from exiting python SetReturnFromRun(true); } namespace { static int (*sOldInputHook)() = nullptr; static PyThreadState *sInputHookEventThreadState = nullptr; static int EventInputHook() { // This method is supposed to be called from CPython's command line and // drives the GUI PyEval_RestoreThread(sInputHookEventThreadState); gSystem->ProcessEvents(); PyEval_SaveThread(); if (sOldInputHook) return sOldInputHook(); return 0; } } // unnamed namespace //////////////////////////////////////////////////////////////////////////// /// \brief Install a method hook for sending events to the GUI. /// \param[in] self Always null, since this is a module function. /// \param[in] args Pointer to an empty Python tuple. PyObject *PyROOT::RPyROOTApplication::InstallGUIEventInputHook(PyObject * /* self */, PyObject * /* args */) { if (PyOS_InputHook && PyOS_InputHook != &EventInputHook) sOldInputHook = PyOS_InputHook; sInputHookEventThreadState = PyThreadState_Get(); PyOS_InputHook = (int (*)()) & EventInputHook; Py_RETURN_NONE; } <commit_msg>clarify CLI args<commit_after>// Author: Enric Tejedor CERN 04/2019 // Original PyROOT code by Wim Lavrijsen, LBL /************************************************************************* * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ // Bindings #include "Python.h" #include "CPyCppyy.h" #include "RPyROOTApplication.h" // ROOT #include "TInterpreter.h" #include "TSystem.h" #include "TBenchmark.h" #include "TStyle.h" #include "TError.h" #include "Getline.h" #include "TVirtualMutex.h" //////////////////////////////////////////////////////////////////////////// /// \brief Create an RPyROOTApplication. /// \param[in] ignoreCmdLineOpts True if Python command line options should /// be ignored. /// \return false if gApplication is not null, true otherwise. /// /// If ignoreCmdLineOpts is false, this method processes the command line /// arguments from sys.argv. A distinction between arguments for /// TApplication and user arguments can be made by using "-" or "--" as a /// separator on the command line. /// /// For example, to enable batch mode from the command line: /// > python script_name.py -b -- user_arg1 ... user_argn /// or, if the user script receives no arguments: /// > python script_name.py -b bool PyROOT::RPyROOTApplication::CreateApplication(int ignoreCmdLineOpts) { if (!gApplication) { int argc = 1; char **argv = nullptr; if (ignoreCmdLineOpts) { argv = new char *[argc]; } else { // Retrieve sys.argv list from Python PyObject *argl = PySys_GetObject(const_cast<char *>("argv")); if (argl && 0 < PyList_Size(argl)) argc = (int)PyList_GET_SIZE(argl); argv = new char *[argc]; for (int i = 1; i < argc; ++i) { char *argi = const_cast<char *>(CPyCppyy_PyText_AsString(PyList_GET_ITEM(argl, i))); if (strcmp(argi, "-") == 0 || strcmp(argi, "--") == 0) { // Stop collecting options, the remaining are for the Python script argc = i; // includes program name break; } argv[i] = argi; } } #if PY_VERSION_HEX < 0x03000000 if (Py_GetProgramName() && strlen(Py_GetProgramName()) != 0) argv[0] = Py_GetProgramName(); else argv[0] = (char *)"python"; #else argv[0] = (char *)"python"; #endif gApplication = new RPyROOTApplication("PyROOT", &argc, argv); delete[] argv; // TApplication ctor has copied argv, so done with it return true; } return false; } //////////////////////////////////////////////////////////////////////////// /// \brief Setup the basic ROOT globals gBenchmark, gStyle and gProgname, /// if not already set. void PyROOT::RPyROOTApplication::InitROOTGlobals() { if (!gBenchmark) gBenchmark = new TBenchmark(); if (!gStyle) gStyle = new TStyle(); if (!gProgName) // should have been set by TApplication #if PY_VERSION_HEX < 0x03000000 gSystem->SetProgname(Py_GetProgramName()); #else gSystem->SetProgname("python"); #endif } //////////////////////////////////////////////////////////////////////////// /// \brief Translate ROOT error/warning to Python. static void ErrMsgHandler(int level, Bool_t abort, const char *location, const char *msg) { // Initialization from gEnv (the default handler will return w/o msg b/c level too low) if (gErrorIgnoreLevel == kUnset) ::DefaultErrorHandler(kUnset - 1, kFALSE, "", ""); if (level < gErrorIgnoreLevel) return; // Turn warnings into Python warnings if (level >= kError) { ::DefaultErrorHandler(level, abort, location, msg); } else if (level >= kWarning) { static const char *emptyString = ""; if (!location) location = emptyString; // This warning might be triggered while holding the ROOT lock, while // some other thread is holding the GIL and waiting for the ROOT lock. // That will trigger a deadlock. // So if ROOT is in MT mode, use ROOT's error handler that doesn't take // the GIL. if (!gGlobalMutex) { // Either printout or raise exception, depending on user settings PyErr_WarnExplicit(NULL, (char *)msg, (char *)location, 0, (char *)"ROOT", NULL); } else { ::DefaultErrorHandler(level, abort, location, msg); } } else { ::DefaultErrorHandler(level, abort, location, msg); } } //////////////////////////////////////////////////////////////////////////// /// \brief Install the ROOT message handler which will turn ROOT error /// messages into Python exceptions. void PyROOT::RPyROOTApplication::InitROOTMessageCallback() { SetErrorHandler((ErrorHandlerFunc_t)&ErrMsgHandler); } //////////////////////////////////////////////////////////////////////////// /// \brief Initialize an RPyROOTApplication. /// \param[in] self Always null, since this is a module function. /// \param[in] args [0] Boolean that tells whether to ignore the command line options. PyObject *PyROOT::RPyROOTApplication::InitApplication(PyObject * /*self*/, PyObject *args) { int argc = PyTuple_GET_SIZE(args); if (argc == 1) { PyObject *ignoreCmdLineOpts = PyTuple_GetItem(args, 0); if (!PyBool_Check(ignoreCmdLineOpts)) { PyErr_SetString(PyExc_TypeError, "Expected boolean type as argument."); return nullptr; } if (CreateApplication(PyObject_IsTrue(ignoreCmdLineOpts))) { InitROOTGlobals(); InitROOTMessageCallback(); } } else { PyErr_Format(PyExc_TypeError, "Expected 1 argument, %d passed.", argc); return nullptr; } Py_RETURN_NONE; } //////////////////////////////////////////////////////////////////////////// /// \brief Construct a TApplication for PyROOT. /// \param[in] acn Application class name. /// \param[in] argc Number of arguments. /// \param[in] argv Arguments. PyROOT::RPyROOTApplication::RPyROOTApplication(const char *acn, int *argc, char **argv) : TApplication(acn, argc, argv) { // Save current interpreter context gInterpreter->SaveContext(); gInterpreter->SaveGlobalsContext(); // Prevent crashes on accessing history Gl_histinit((char *)"-"); // Prevent ROOT from exiting python SetReturnFromRun(true); } namespace { static int (*sOldInputHook)() = nullptr; static PyThreadState *sInputHookEventThreadState = nullptr; static int EventInputHook() { // This method is supposed to be called from CPython's command line and // drives the GUI PyEval_RestoreThread(sInputHookEventThreadState); gSystem->ProcessEvents(); PyEval_SaveThread(); if (sOldInputHook) return sOldInputHook(); return 0; } } // unnamed namespace //////////////////////////////////////////////////////////////////////////// /// \brief Install a method hook for sending events to the GUI. /// \param[in] self Always null, since this is a module function. /// \param[in] args Pointer to an empty Python tuple. PyObject *PyROOT::RPyROOTApplication::InstallGUIEventInputHook(PyObject * /* self */, PyObject * /* args */) { if (PyOS_InputHook && PyOS_InputHook != &EventInputHook) sOldInputHook = PyOS_InputHook; sInputHookEventThreadState = PyThreadState_Get(); PyOS_InputHook = (int (*)()) & EventInputHook; Py_RETURN_NONE; } <|endoftext|>
<commit_before>/**************************************************************************** * Copyright (c) 2012-2019 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #include <DTK_DetailsTreeVisualization.hpp> #include <DTK_LinearBVH.hpp> #include <Kokkos_Core.hpp> #include <Kokkos_DefaultNode.hpp> #include <algorithm> #include <fstream> #include <random> #include <point_clouds.hpp> template <typename TreeType> void viz() { using DeviceType = typename TreeType::device_type; using ExecutionSpace = typename DeviceType::execution_space; Kokkos::View<DataTransferKit::Point *, DeviceType> points( "points" ); loadPointCloud( "/scratch/source/trilinos/release/DataTransferKit/packages/" "Search/examples/point_clouds/leaf_cloud.txt", points ); TreeType bvh( points ); std::fstream fout; // Print the entire tree std::string const prefix = "trash_"; fout.open( prefix + "tree_all_nodes_and_edges.dot.m4", std::fstream::out ); using TreeVisualization = typename DataTransferKit::Details::TreeVisualization<DeviceType>; using GraphvizVisitor = typename TreeVisualization::GraphvizVisitor; TreeVisualization::visitAllIterative( bvh, GraphvizVisitor{fout} ); fout.close(); int const n_neighbors = 10; int const n_queries = bvh.size(); Kokkos::View<DataTransferKit::Nearest<DataTransferKit::Point> *, DeviceType> queries( "queries", n_queries ); Kokkos::parallel_for( Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ), KOKKOS_LAMBDA( int i ) { queries( i ) = DataTransferKit::nearest( points( i ), n_neighbors ); } ); Kokkos::fence(); for ( int i = 0; i < n_queries; ++i ) { fout.open( prefix + "untouched_" + std::to_string( i ) + "_nearest_traversal.dot.m4", std::fstream::out ); TreeVisualization::visit( bvh, queries( i ), GraphvizVisitor{fout} ); fout.close(); } // Shuffle the queries std::random_device rd; std::mt19937 g( rd() ); std::shuffle( queries.data(), queries.data() + queries.size(), g ); for ( int i = 0; i < n_queries; ++i ) { fout.open( prefix + "shuffled_" + std::to_string( i ) + "_nearest_traversal.dot.m4", std::fstream::out ); TreeVisualization::visit( bvh, queries( i ), GraphvizVisitor{fout} ); fout.close(); } // Sort them auto permute = DataTransferKit::Details::BatchedQueries< DeviceType>::sortQueriesAlongZOrderCurve( bvh.bounds(), queries ); queries = DataTransferKit::Details::BatchedQueries<DeviceType>::applyPermutation( permute, queries ); for ( int i = 0; i < n_queries; ++i ) { fout.open( prefix + "sorted_" + std::to_string( i ) + "_nearest_traversal.dot.m4", std::fstream::out ); TreeVisualization::visit( bvh, queries( i ), GraphvizVisitor{fout} ); fout.close(); } } int main( int argc, char *argv[] ) { Kokkos::initialize( argc, argv ); using Serial = Kokkos::Compat::KokkosSerialWrapperNode::device_type; using Tree = DataTransferKit::BVH<Serial>; viz<Tree>(); Kokkos::finalize(); return 0; } <commit_msg>Print the point cloud in TikZ format<commit_after>/**************************************************************************** * Copyright (c) 2012-2019 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #include <DTK_DetailsTreeVisualization.hpp> #include <DTK_LinearBVH.hpp> #include <Kokkos_Core.hpp> #include <Kokkos_DefaultNode.hpp> #include <algorithm> #include <fstream> #include <random> #include <point_clouds.hpp> template <typename View> void printPointCloud( View points, std::ostream &os ) { auto const n = points.extent_int( 0 ); for ( int i = 0; i < n; ++i ) os << "\\node[leaf] at (" << points( i )[0] << "," << points( i )[1] << ") {\\textbullet};\n"; } template <typename TreeType> void viz() { using DeviceType = typename TreeType::device_type; using ExecutionSpace = typename DeviceType::execution_space; Kokkos::View<DataTransferKit::Point *, DeviceType> points( "points" ); loadPointCloud( "/scratch/source/trilinos/release/DataTransferKit/packages/" "Search/examples/point_clouds/leaf_cloud.txt", points ); TreeType bvh( points ); std::fstream fout; std::string const prefix = "trash_"; // Print the point cloud fout.open( prefix + "points.tex", std::fstream::out ); printPointCloud( points, fout ); fout.close(); // Print the entire tree fout.open( prefix + "tree_all_nodes_and_edges.dot.m4", std::fstream::out ); using TreeVisualization = typename DataTransferKit::Details::TreeVisualization<DeviceType>; using GraphvizVisitor = typename TreeVisualization::GraphvizVisitor; TreeVisualization::visitAllIterative( bvh, GraphvizVisitor{fout} ); fout.close(); int const n_neighbors = 10; int const n_queries = bvh.size(); Kokkos::View<DataTransferKit::Nearest<DataTransferKit::Point> *, DeviceType> queries( "queries", n_queries ); Kokkos::parallel_for( Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ), KOKKOS_LAMBDA( int i ) { queries( i ) = DataTransferKit::nearest( points( i ), n_neighbors ); } ); Kokkos::fence(); for ( int i = 0; i < n_queries; ++i ) { fout.open( prefix + "untouched_" + std::to_string( i ) + "_nearest_traversal.dot.m4", std::fstream::out ); TreeVisualization::visit( bvh, queries( i ), GraphvizVisitor{fout} ); fout.close(); } // Shuffle the queries std::random_device rd; std::mt19937 g( rd() ); std::shuffle( queries.data(), queries.data() + queries.size(), g ); for ( int i = 0; i < n_queries; ++i ) { fout.open( prefix + "shuffled_" + std::to_string( i ) + "_nearest_traversal.dot.m4", std::fstream::out ); TreeVisualization::visit( bvh, queries( i ), GraphvizVisitor{fout} ); fout.close(); } // Sort them auto permute = DataTransferKit::Details::BatchedQueries< DeviceType>::sortQueriesAlongZOrderCurve( bvh.bounds(), queries ); queries = DataTransferKit::Details::BatchedQueries<DeviceType>::applyPermutation( permute, queries ); for ( int i = 0; i < n_queries; ++i ) { fout.open( prefix + "sorted_" + std::to_string( i ) + "_nearest_traversal.dot.m4", std::fstream::out ); TreeVisualization::visit( bvh, queries( i ), GraphvizVisitor{fout} ); fout.close(); } } int main( int argc, char *argv[] ) { Kokkos::initialize( argc, argv ); using Serial = Kokkos::Compat::KokkosSerialWrapperNode::device_type; using Tree = DataTransferKit::BVH<Serial>; viz<Tree>(); Kokkos::finalize(); return 0; } <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 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 "expression_editor/ExpressionTreeUtils.h" #include "expression_editor/Value.h" #include "expression_editor/Empty.h" #include "expression_editor/Operator.h" #include "expression_editor/UnfinishedOperator.h" #include "expression_editor/OperatorDescriptor.h" namespace Interaction { void ExpressionTreeUtils::fixTop(Expression*& top) { fixPrecedence(top); fixWrongIds(top); } Expression* ExpressionTreeUtils::replace(Expression*& top, Expression* oldExpr, Expression* newExpr) { if (oldExpr == top) { top = newExpr; newExpr->setParent(nullptr); return oldExpr; } else return oldExpr->parent()->replaceOperand(oldExpr, newExpr); } void ExpressionTreeUtils::rotateRight(Expression*& top, Operator* child, Operator* parent) { parent->first(true); replace(top, parent, child); Expression* branch = child->last(true); child->append(parent); parent->prepend(branch); } void ExpressionTreeUtils::rotateLeft(Expression*& top, Operator* child, Operator* parent) { parent->last(true); replace(top, parent, child); Expression* branch = child->first(true); child->prepend(parent); parent->append(branch); } void ExpressionTreeUtils::fixPrecedence(Expression*& top) { bool more_iterations_needed = true; while (more_iterations_needed ) more_iterations_needed = fixExprPrecedence(top, top); } bool ExpressionTreeUtils::fixExprPrecedence(Expression*& top, Expression* e) { if ( dynamic_cast<Value*> (e)) return false; if ( dynamic_cast<Empty*> (e)) return false; Operator* op = dynamic_cast<Operator*> (e); bool more_iterations_needed = true; while (more_iterations_needed) { more_iterations_needed = false; // Fix all children for (int operand = 0; operand < op->size(); ++operand) more_iterations_needed = fixExprPrecedence(top, op->at(operand)) || more_iterations_needed; } //Look left if (op->descriptor()->prefix().isEmpty()) { Operator* left = dynamic_cast<Operator*> (op->first()); if (left && left->descriptor()->postfix().isEmpty()) { if (op->descriptor()->precedence() < left->descriptor()->precedence() // Must rotate because of precedence // Must rotate because of associativity. This assumes that the associativity of different operators at // the same precedence level is the same. || ( (op->descriptor()->precedence() == left->descriptor()->precedence()) && op->descriptor()->associativity() == OperatorDescriptor::RightAssociative) ) { rotateRight(top, left, op); return true; } } } //Look right if (op->descriptor()->postfix().isEmpty()) { Operator* right = dynamic_cast<Operator*> (op->last()); if (right && right->descriptor()->prefix().isEmpty()) { if (op->descriptor()->precedence() < right->descriptor()->precedence() // Must rotate because of precedence // Must rotate because of associativity. This assumes that the associativity of different operators at // the same precedence level is the same. || ( (op->descriptor()->precedence() == right->descriptor()->precedence()) && op->descriptor()->associativity() == OperatorDescriptor::LeftAssociative) ) { rotateLeft(top, right, op); return true; } } } return false; } void ExpressionTreeUtils::grow(Expression*& top, Operator* op, bool leftside) { bool rightside = !leftside; // Can't grow if there is no parent if ( !op->parent() ) return; // Can't grow from a side where there is no delimiter if ( (leftside && op->descriptor()->prefix().isEmpty() ) || (rightside && op->descriptor()->postfix().isEmpty()) ) return; Operator* parent = op->parent(); // Get context int delim_begin; int delim_end; op->globalDelimiterBoundaries(leftside ? 0 : op->descriptor()->numOperands(), delim_begin, delim_end); ExpressionContext c = top->findContext(leftside ? delim_begin: delim_end); // If this is an expression in the middle of two delimiters that belong to the same operator // this typically means that it can not be grown any more from only a single side... bool wrap_parent = false; if ( ( leftside && (c.leftType() == ExpressionContext::None || c.leftType() == ExpressionContext::OpBoundary) ) || ( rightside && (c.rightType() == ExpressionContext::None || c.rightType() == ExpressionContext::OpBoundary) ) ) { // .. EXCEPT: when both delimiters are the same as the delimiter we're trying to grow and the // direction opposite of the growth direction is an end delimiter. In that case we simply // engulf the entire parent. op->globalDelimiterBoundaries(leftside ? op->descriptor()->numOperands() : 0, delim_begin, delim_end); ExpressionContext c_other = top->findContext(leftside ? delim_end : delim_begin ); if ( ( leftside && c_other.rightType() == ExpressionContext::OpBoundary && c_other.rightText() == op->descriptor()->postfix() && c_other.rightDelim() == c_other.rightOp()->size()) || ( rightside && c_other.leftType() == ExpressionContext::OpBoundary && c_other.leftText() == op->descriptor()->prefix() && c_other.leftDelim() == 0) ) wrap_parent = true; else return; } // Special case when the parent ends with a pre/postfix in the direction we're growing. // In that case we must wrap the whole operator as we can not break the delimiters. wrap_parent = wrap_parent || ( !(leftside && parent->descriptor()->prefix().isEmpty()) && !(rightside && parent->descriptor()->postfix().isEmpty())); if (wrap_parent) { Expression* placeholder = new Empty(); replace(top, parent, placeholder); replace(top, op, leftside ? op->first(true) : op->last(true)); if (leftside) op->prepend(parent); else op->append(parent); delete replace(top, placeholder, op); return; } // Find the expression that must be wrapped Operator* top_op = parent; Operator* child = op; while ( (leftside ? top_op->last() : top_op->first()) != child) { child = top_op; top_op = top_op->parent(); if (!top_op) return; } Expression* to_wrap = leftside ? top_op->first()->smallestRightmostSubExpr() : top_op->last()->smallestLeftmostSubExpr(); // Do the exchange -------------------------------------- // Disconnect top_op from the the entire tree and from it's first and last // Note that if we've reached this point then first and last must be two different nodes Expression* top_op_placeholder = new Empty(); replace(top, top_op, top_op_placeholder); Expression* top_op_last = top_op->last(true); // Special case when rightside: top_op_last == to_wrap Expression* top_op_first = top_op->first(true); // Special case when leftside: top_op_first == to_wrap // Disconnect the to_wrap expression if not yet disconnected Expression* to_wrap_placeholder = nullptr; if ( (leftside && to_wrap != top_op_first) || (rightside && to_wrap != top_op_last) ) { to_wrap_placeholder = new Empty(); replace(top, to_wrap, to_wrap_placeholder); } // Disconnect the old_wrapped expression Expression* old_wrap = leftside ? op->first(true) : op->last(true); // This is the content that was previously wrapped // Disconnect the left and right children of top_op. // Make the necessary connections if (leftside) { op->prepend(top_op); top_op->prepend(to_wrap); top_op->append(old_wrap); //Consider the special case if (top_op_first == to_wrap) { delete replace(top, top_op_placeholder, top_op_last ); } else { delete replace(top, top_op_placeholder, top_op_first ); delete replace(top, to_wrap_placeholder, top_op_last); } } else { op->append(top_op); top_op->prepend(old_wrap); top_op->append(to_wrap); //Consider the special case if (top_op_last == to_wrap) { delete replace(top, top_op_placeholder, top_op_first ); } else { delete replace(top, top_op_placeholder, top_op_last ); delete replace(top, to_wrap_placeholder, top_op_first); } } fixTop(top); } void ExpressionTreeUtils::shrink(Expression*& top, Operator* op, bool leftside) { // Can't shrink if only an atomic value left if ( ( leftside ? op->first()->type() : op->last()->type() ) != Operator::type() ) return; // Can't shrink from a side where there is no delimiter if ( (leftside && op->descriptor()->prefix().isEmpty() ) || (!leftside && op->descriptor()->postfix().isEmpty())) return; Expression* new_border_expr = (leftside ? op->first() : op->last()) ->findCutExpression(leftside, leftside ? op->descriptor()->postfix() : op->descriptor()->prefix()); if (new_border_expr == nullptr) return; Operator* cut_op = new_border_expr->parent(); Operator* cut_op_parent = cut_op->parent(); // Rewire the tree Expression* op_placeholder = new Empty; replace(top, op, op_placeholder); if (leftside) { cut_op->last(true); cut_op_parent->first(true); cut_op_parent->prepend(new_border_expr); cut_op->append(op); } else { cut_op->first(true); cut_op_parent->last(true); cut_op_parent->append(new_border_expr); cut_op->prepend(op); } delete replace(top, op_placeholder, cut_op); fixTop(top); } void ExpressionTreeUtils::fixWrongIds(Expression*& top) { QList<Expression*> toFix; toFix << top; while (!toFix.isEmpty()) { auto e = toFix.first(); toFix.removeFirst(); if (auto op = dynamic_cast<Operator*>(e)) { bool unfinished = dynamic_cast<UnfinishedOperator*>(op); if (!unfinished) { bool badId = false; int operandIndex = 0; for (auto s : op->descriptor()->signature()) { if (s == "id") { auto v = dynamic_cast<Value*> (op->operands().at(operandIndex)); badId = badId || !v || v->text().isEmpty() || !(v->text()[0].isLetter() || v->text()[0] == '_'); if (badId) break; } if (!OperatorDescriptor::isDelimiter(s)) ++operandIndex; } if (badId) op = UnfinishedOperator::replaceFinishedWithUnfinished(top, op); } for (auto operand : op->operands()) toFix.append(operand); } } } } /* namespace InteractionBase */ <commit_msg>Fix a crash when an error expression contained the string "id"<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 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 "expression_editor/ExpressionTreeUtils.h" #include "expression_editor/Value.h" #include "expression_editor/Empty.h" #include "expression_editor/Operator.h" #include "expression_editor/UnfinishedOperator.h" #include "expression_editor/ErrorDescriptor.h" #include "expression_editor/OperatorDescriptor.h" namespace Interaction { void ExpressionTreeUtils::fixTop(Expression*& top) { fixPrecedence(top); fixWrongIds(top); } Expression* ExpressionTreeUtils::replace(Expression*& top, Expression* oldExpr, Expression* newExpr) { if (oldExpr == top) { top = newExpr; newExpr->setParent(nullptr); return oldExpr; } else return oldExpr->parent()->replaceOperand(oldExpr, newExpr); } void ExpressionTreeUtils::rotateRight(Expression*& top, Operator* child, Operator* parent) { parent->first(true); replace(top, parent, child); Expression* branch = child->last(true); child->append(parent); parent->prepend(branch); } void ExpressionTreeUtils::rotateLeft(Expression*& top, Operator* child, Operator* parent) { parent->last(true); replace(top, parent, child); Expression* branch = child->first(true); child->prepend(parent); parent->append(branch); } void ExpressionTreeUtils::fixPrecedence(Expression*& top) { bool more_iterations_needed = true; while (more_iterations_needed ) more_iterations_needed = fixExprPrecedence(top, top); } bool ExpressionTreeUtils::fixExprPrecedence(Expression*& top, Expression* e) { if ( dynamic_cast<Value*> (e)) return false; if ( dynamic_cast<Empty*> (e)) return false; Operator* op = dynamic_cast<Operator*> (e); bool more_iterations_needed = true; while (more_iterations_needed) { more_iterations_needed = false; // Fix all children for (int operand = 0; operand < op->size(); ++operand) more_iterations_needed = fixExprPrecedence(top, op->at(operand)) || more_iterations_needed; } //Look left if (op->descriptor()->prefix().isEmpty()) { Operator* left = dynamic_cast<Operator*> (op->first()); if (left && left->descriptor()->postfix().isEmpty()) { if (op->descriptor()->precedence() < left->descriptor()->precedence() // Must rotate because of precedence // Must rotate because of associativity. This assumes that the associativity of different operators at // the same precedence level is the same. || ( (op->descriptor()->precedence() == left->descriptor()->precedence()) && op->descriptor()->associativity() == OperatorDescriptor::RightAssociative) ) { rotateRight(top, left, op); return true; } } } //Look right if (op->descriptor()->postfix().isEmpty()) { Operator* right = dynamic_cast<Operator*> (op->last()); if (right && right->descriptor()->prefix().isEmpty()) { if (op->descriptor()->precedence() < right->descriptor()->precedence() // Must rotate because of precedence // Must rotate because of associativity. This assumes that the associativity of different operators at // the same precedence level is the same. || ( (op->descriptor()->precedence() == right->descriptor()->precedence()) && op->descriptor()->associativity() == OperatorDescriptor::LeftAssociative) ) { rotateLeft(top, right, op); return true; } } } return false; } void ExpressionTreeUtils::grow(Expression*& top, Operator* op, bool leftside) { bool rightside = !leftside; // Can't grow if there is no parent if ( !op->parent() ) return; // Can't grow from a side where there is no delimiter if ( (leftside && op->descriptor()->prefix().isEmpty() ) || (rightside && op->descriptor()->postfix().isEmpty()) ) return; Operator* parent = op->parent(); // Get context int delim_begin; int delim_end; op->globalDelimiterBoundaries(leftside ? 0 : op->descriptor()->numOperands(), delim_begin, delim_end); ExpressionContext c = top->findContext(leftside ? delim_begin: delim_end); // If this is an expression in the middle of two delimiters that belong to the same operator // this typically means that it can not be grown any more from only a single side... bool wrap_parent = false; if ( ( leftside && (c.leftType() == ExpressionContext::None || c.leftType() == ExpressionContext::OpBoundary) ) || ( rightside && (c.rightType() == ExpressionContext::None || c.rightType() == ExpressionContext::OpBoundary) ) ) { // .. EXCEPT: when both delimiters are the same as the delimiter we're trying to grow and the // direction opposite of the growth direction is an end delimiter. In that case we simply // engulf the entire parent. op->globalDelimiterBoundaries(leftside ? op->descriptor()->numOperands() : 0, delim_begin, delim_end); ExpressionContext c_other = top->findContext(leftside ? delim_end : delim_begin ); if ( ( leftside && c_other.rightType() == ExpressionContext::OpBoundary && c_other.rightText() == op->descriptor()->postfix() && c_other.rightDelim() == c_other.rightOp()->size()) || ( rightside && c_other.leftType() == ExpressionContext::OpBoundary && c_other.leftText() == op->descriptor()->prefix() && c_other.leftDelim() == 0) ) wrap_parent = true; else return; } // Special case when the parent ends with a pre/postfix in the direction we're growing. // In that case we must wrap the whole operator as we can not break the delimiters. wrap_parent = wrap_parent || ( !(leftside && parent->descriptor()->prefix().isEmpty()) && !(rightside && parent->descriptor()->postfix().isEmpty())); if (wrap_parent) { Expression* placeholder = new Empty(); replace(top, parent, placeholder); replace(top, op, leftside ? op->first(true) : op->last(true)); if (leftside) op->prepend(parent); else op->append(parent); delete replace(top, placeholder, op); return; } // Find the expression that must be wrapped Operator* top_op = parent; Operator* child = op; while ( (leftside ? top_op->last() : top_op->first()) != child) { child = top_op; top_op = top_op->parent(); if (!top_op) return; } Expression* to_wrap = leftside ? top_op->first()->smallestRightmostSubExpr() : top_op->last()->smallestLeftmostSubExpr(); // Do the exchange -------------------------------------- // Disconnect top_op from the the entire tree and from it's first and last // Note that if we've reached this point then first and last must be two different nodes Expression* top_op_placeholder = new Empty(); replace(top, top_op, top_op_placeholder); Expression* top_op_last = top_op->last(true); // Special case when rightside: top_op_last == to_wrap Expression* top_op_first = top_op->first(true); // Special case when leftside: top_op_first == to_wrap // Disconnect the to_wrap expression if not yet disconnected Expression* to_wrap_placeholder = nullptr; if ( (leftside && to_wrap != top_op_first) || (rightside && to_wrap != top_op_last) ) { to_wrap_placeholder = new Empty(); replace(top, to_wrap, to_wrap_placeholder); } // Disconnect the old_wrapped expression Expression* old_wrap = leftside ? op->first(true) : op->last(true); // This is the content that was previously wrapped // Disconnect the left and right children of top_op. // Make the necessary connections if (leftside) { op->prepend(top_op); top_op->prepend(to_wrap); top_op->append(old_wrap); //Consider the special case if (top_op_first == to_wrap) { delete replace(top, top_op_placeholder, top_op_last ); } else { delete replace(top, top_op_placeholder, top_op_first ); delete replace(top, to_wrap_placeholder, top_op_last); } } else { op->append(top_op); top_op->prepend(old_wrap); top_op->append(to_wrap); //Consider the special case if (top_op_last == to_wrap) { delete replace(top, top_op_placeholder, top_op_first ); } else { delete replace(top, top_op_placeholder, top_op_last ); delete replace(top, to_wrap_placeholder, top_op_first); } } fixTop(top); } void ExpressionTreeUtils::shrink(Expression*& top, Operator* op, bool leftside) { // Can't shrink if only an atomic value left if ( ( leftside ? op->first()->type() : op->last()->type() ) != Operator::type() ) return; // Can't shrink from a side where there is no delimiter if ( (leftside && op->descriptor()->prefix().isEmpty() ) || (!leftside && op->descriptor()->postfix().isEmpty())) return; Expression* new_border_expr = (leftside ? op->first() : op->last()) ->findCutExpression(leftside, leftside ? op->descriptor()->postfix() : op->descriptor()->prefix()); if (new_border_expr == nullptr) return; Operator* cut_op = new_border_expr->parent(); Operator* cut_op_parent = cut_op->parent(); // Rewire the tree Expression* op_placeholder = new Empty; replace(top, op, op_placeholder); if (leftside) { cut_op->last(true); cut_op_parent->first(true); cut_op_parent->prepend(new_border_expr); cut_op->append(op); } else { cut_op->first(true); cut_op_parent->last(true); cut_op_parent->append(new_border_expr); cut_op->prepend(op); } delete replace(top, op_placeholder, cut_op); fixTop(top); } void ExpressionTreeUtils::fixWrongIds(Expression*& top) { QList<Expression*> toFix; toFix << top; while (!toFix.isEmpty()) { auto e = toFix.first(); toFix.removeFirst(); if (auto op = dynamic_cast<Operator*>(e)) { bool isUnfinished = dynamic_cast<UnfinishedOperator*>(op); if (!isUnfinished) { bool isError = dynamic_cast<ErrorDescriptor*>(op->descriptor()); if (!isError) { bool badId = false; int operandIndex = 0; for (auto s : op->descriptor()->signature()) { if (s == "id") { auto v = dynamic_cast<Value*> (op->operands().at(operandIndex)); badId = badId || !v || v->text().isEmpty() || !(v->text()[0].isLetter() || v->text()[0] == '_'); if (badId) break; } if (!OperatorDescriptor::isDelimiter(s)) ++operandIndex; } if (badId) op = UnfinishedOperator::replaceFinishedWithUnfinished(top, op); } } for (auto operand : op->operands()) toFix.append(operand); } } } } /* namespace InteractionBase */ <|endoftext|>
<commit_before>#ifndef ALEPH_PERSISTENCE_DIAGRAMS_PERSISTENCE_INDICATOR_FUNCTION_HH__ #define ALEPH_PERSISTENCE_DIAGRAMS_PERSISTENCE_INDICATOR_FUNCTION_HH__ #include "math/StepFunction.hh" #include "persistenceDiagrams/PersistenceDiagram.hh" #include <algorithm> #include <limits> #include <utility> #include <vector> #include <cmath> namespace aleph { namespace detail { template <class T> struct EventPoint { T value; bool destroyer; bool operator<( const EventPoint& other ) const noexcept { // Sort event point by their corresponding values. In case of ties, // consider creators to come after destroyers. This makes sense, as // a creator may increase the number of active intervals again. return value < other.value || ( value == other.value && destroyer && !other.destroyer ); } }; template <class T> T next( T x ) { if( std::numeric_limits<T>::is_integer ) return x+1; else return std::nextafter( x, std::numeric_limits<T>::max() ); } } // namespace detail /** Calculates the persistence indicator function of a persistence diagram. This function counts the number of 'active' intervals for every parameter value. It is a stable summary of a diagram and may be used to discern more information about the topology and its variation over time. */ template <class DataType> aleph::math::StepFunction<DataType> persistenceIndicatorFunction( const PersistenceDiagram<DataType>& D ) { using namespace detail; using namespace math; using EP = EventPoint<DataType>; std::vector<EP> eventPoints; eventPoints.reserve( 2 * D.size() ); for( auto&& p : D ) { eventPoints.push_back( { p.x(), false } ); eventPoints.push_back( { p.y(), true } ); } std::sort( eventPoints.begin(), eventPoints.end() ); unsigned numActiveFeatures = 0; bool isDegenerate = false; // Sanity check: A destroyer and a creator should never have the same // function value. Else, the number of 'active' intervals will behave // somewhat strangely. if( eventPoints.size() >= 2 ) { for( std::size_t i = 0; i < eventPoints.size(); i += 2 ) { if( eventPoints[i].value == eventPoints[i+1].value ) { if( eventPoints[i].destroyer != eventPoints[i+1].destroyer ) { isDegenerate = true; break; } } } } // Lambda expression for counting duplicate event points that appear after a // certain index in the vector of event points. Duplicate event points occur // if the persistence diagram contains points with equal values. auto numDuplicateValues = [&eventPoints] ( std::size_t i ) { auto eventPoint = eventPoints.at(i); unsigned numOccurrences = 0; unsigned numDestroyers = 0; do { numDestroyers += eventPoints.at(i).destroyer; ++numOccurrences; ++i; } while( i < eventPoints.size() && eventPoints.at(i).value == eventPoint.value ); return std::make_pair( numOccurrences, numDestroyers ); }; StepFunction<DataType> f; // Previous interval end point. This is required in order to create proper // indicator functions later on. DataType previous = DataType(); for( std::size_t i = 0; i < eventPoints.size(); ) { auto pair = numDuplicateValues(i); auto occurrences = pair.first; auto destroyers = pair.second; auto creators = occurrences - destroyers; bool useNextPoint = false; // Case 1: No duplicates or duplicates of the same type. In this case, the // number of active intervals changes and we add an interval. It comprises // the number of active intervals up to this point. if( occurrences == 1 || creators == occurrences || creators == 0 ) { if( i != 0 ) f.add( previous, eventPoints.at(i).value, static_cast<DataType>( numActiveFeatures ) ); } // Case 2: There are duplicate creation & destruction values. This // necessitates the creation of two intervals: one interval at the // current even point, with the proper number of active intervals, // the other one *directly* afterwards to indicate the destruction // implied by the values. else { f.add( previous, eventPoints.at(i).value, static_cast<DataType>( numActiveFeatures + creators ) ); useNextPoint = true; } numActiveFeatures += creators; numActiveFeatures -= destroyers; previous = useNextPoint ? next( eventPoints.at(i).value ) : eventPoints.at(i).value; i += occurrences; } return f; } } // namespace aleph #endif <commit_msg>Removed obsolete sanity check for persistence indicator function<commit_after>#ifndef ALEPH_PERSISTENCE_DIAGRAMS_PERSISTENCE_INDICATOR_FUNCTION_HH__ #define ALEPH_PERSISTENCE_DIAGRAMS_PERSISTENCE_INDICATOR_FUNCTION_HH__ #include "math/StepFunction.hh" #include "persistenceDiagrams/PersistenceDiagram.hh" #include <algorithm> #include <limits> #include <utility> #include <vector> #include <cmath> namespace aleph { namespace detail { template <class T> struct EventPoint { T value; bool destroyer; bool operator<( const EventPoint& other ) const noexcept { // Sort event point by their corresponding values. In case of ties, // consider creators to come after destroyers. This makes sense, as // a creator may increase the number of active intervals again. return value < other.value || ( value == other.value && destroyer && !other.destroyer ); } }; template <class T> T next( T x ) { if( std::numeric_limits<T>::is_integer ) return x+1; else return std::nextafter( x, std::numeric_limits<T>::max() ); } } // namespace detail /** Calculates the persistence indicator function of a persistence diagram. This function counts the number of 'active' intervals for every parameter value. It is a stable summary of a diagram and may be used to discern more information about the topology and its variation over time. */ template <class DataType> aleph::math::StepFunction<DataType> persistenceIndicatorFunction( const PersistenceDiagram<DataType>& D ) { using namespace detail; using namespace math; using EP = EventPoint<DataType>; std::vector<EP> eventPoints; eventPoints.reserve( 2 * D.size() ); for( auto&& p : D ) { eventPoints.push_back( { p.x(), false } ); eventPoints.push_back( { p.y(), true } ); } std::sort( eventPoints.begin(), eventPoints.end() ); unsigned numActiveFeatures = 0; // Lambda expression for counting duplicate event points that appear after a // certain index in the vector of event points. Duplicate event points occur // if the persistence diagram contains points with equal values. auto numDuplicateValues = [&eventPoints] ( std::size_t i ) { auto eventPoint = eventPoints.at(i); unsigned numOccurrences = 0; unsigned numDestroyers = 0; do { numDestroyers += eventPoints.at(i).destroyer; ++numOccurrences; ++i; } while( i < eventPoints.size() && eventPoints.at(i).value == eventPoint.value ); return std::make_pair( numOccurrences, numDestroyers ); }; StepFunction<DataType> f; // Previous interval end point. This is required in order to create proper // indicator functions later on. DataType previous = DataType(); for( std::size_t i = 0; i < eventPoints.size(); ) { auto pair = numDuplicateValues(i); auto occurrences = pair.first; auto destroyers = pair.second; auto creators = occurrences - destroyers; bool useNextPoint = false; // Case 1: No duplicates or duplicates of the same type. In this case, the // number of active intervals changes and we add an interval. It comprises // the number of active intervals up to this point. if( occurrences == 1 || creators == occurrences || creators == 0 ) { if( i != 0 ) f.add( previous, eventPoints.at(i).value, static_cast<DataType>( numActiveFeatures ) ); } // Case 2: There are duplicate creation & destruction values. This // necessitates the creation of two intervals: one interval at the // current even point, with the proper number of active intervals, // the other one *directly* afterwards to indicate the destruction // implied by the values. else { f.add( previous, eventPoints.at(i).value, static_cast<DataType>( numActiveFeatures + creators ) ); useNextPoint = true; } numActiveFeatures += creators; numActiveFeatures -= destroyers; previous = useNextPoint ? next( eventPoints.at(i).value ) : eventPoints.at(i).value; i += occurrences; } return f; } } // namespace aleph #endif <|endoftext|>
<commit_before>#include "eigenvalue/k_effective/updater_via_rayleigh_quotient.hpp" #include "system/system.h" #include "system/moments/tests/spherical_harmonic_mock.h" #include "test_helpers/gmock_wrapper.h" namespace { using namespace bart; using ::testing::DoDefault, ::testing::NiceMock, ::testing::ReturnRef; class K_EffectiveUpdaterViaRayleighQuotientTest : public ::testing::Test { public: using SphericalHarmonicMock = NiceMock<system::moments::SphericalHarmonicMock>; using Vector = dealii::Vector<double>; static constexpr int total_groups_{ 2 }; static constexpr int vector_size_{ 3 }; const double initial_k_effective_{ 1.0235 }; const double expected_k_effective_{ 0.4094 }; std::array<Vector, total_groups_> current_moments_, previous_moments_; system::System test_system_ { .k_effective = initial_k_effective_, .total_groups = total_groups_ }; SphericalHarmonicMock* current_moments_obs_ptr_; SphericalHarmonicMock* previous_moments_obs_ptr_; auto SetUp() -> void override; }; auto K_EffectiveUpdaterViaRayleighQuotientTest::SetUp() -> void { for (int group = 0; group < total_groups_; ++group) { Vector current_group_moment(vector_size_), previous_group_moment(vector_size_); for (int i = 0; i < vector_size_; ++i) { if (group == 0) { current_group_moment[i] = (i + 1); previous_group_moment[i] = (i + 1 + vector_size_); } else { current_group_moment[i] = vector_size_ - i; previous_group_moment[i] = 2 * vector_size_ - i; } } current_moments_.at(group) = current_group_moment; previous_moments_.at(group) = previous_group_moment; } test_system_.current_moments = std::make_unique<SphericalHarmonicMock>(); test_system_.previous_moments = std::make_unique<SphericalHarmonicMock>(); current_moments_obs_ptr_ = dynamic_cast<SphericalHarmonicMock*>(test_system_.current_moments.get()); previous_moments_obs_ptr_ = dynamic_cast<SphericalHarmonicMock*>(test_system_.previous_moments.get()); for (int group = 0; group < total_groups_; ++group) { std::array<int, 3> index{ group, 0, 0 }; ON_CALL(*current_moments_obs_ptr_, GetMoment(index)).WillByDefault(ReturnRef(current_moments_.at(group))); ON_CALL(*previous_moments_obs_ptr_, GetMoment(index)).WillByDefault(ReturnRef(previous_moments_.at(group))); } } TEST_F(K_EffectiveUpdaterViaRayleighQuotientTest, Calculate) { eigenvalue::k_effective::UpdaterViaRayleighQuotient test_updater; EXPECT_FALSE(test_updater.k_effective().has_value()); for (int group = 0; group < total_groups_; ++group) { std::array<int, 3> index{ group, 0, 0 }; EXPECT_CALL(*current_moments_obs_ptr_, GetMoment(index)).WillOnce(DoDefault()); EXPECT_CALL(*previous_moments_obs_ptr_, GetMoment(index)).WillOnce(DoDefault()); } auto calculated_k_effective = test_updater.CalculateK_Effective(test_system_); EXPECT_NEAR(calculated_k_effective, expected_k_effective_, 1e-8); ASSERT_TRUE(test_updater.k_effective().has_value()); EXPECT_EQ(calculated_k_effective, test_updater.k_effective().value()); } TEST_F(K_EffectiveUpdaterViaRayleighQuotientTest, ZeroCurrentFlux) { eigenvalue::k_effective::UpdaterViaRayleighQuotient test_updater; EXPECT_FALSE(test_updater.k_effective().has_value()); Vector zero_flux(vector_size_); for (int group = 0; group < total_groups_; ++group) { std::array<int, 3> index{ group, 0, 0 }; EXPECT_CALL(*current_moments_obs_ptr_, GetMoment(index)).WillOnce(ReturnRef(zero_flux)); EXPECT_CALL(*previous_moments_obs_ptr_, GetMoment(index)).WillOnce(DoDefault()); } auto calculated_k_effective = test_updater.CalculateK_Effective(test_system_); EXPECT_NEAR(calculated_k_effective, 0, 1e-8); ASSERT_TRUE(test_updater.k_effective().has_value()); EXPECT_EQ(calculated_k_effective, test_updater.k_effective().value()); } TEST_F(K_EffectiveUpdaterViaRayleighQuotientTest, ZeroPreviousFlux) { eigenvalue::k_effective::UpdaterViaRayleighQuotient test_updater; EXPECT_FALSE(test_updater.k_effective().has_value()); Vector zero_flux(vector_size_); for (int group = 0; group < total_groups_; ++group) { std::array<int, 3> index{ group, 0, 0 }; EXPECT_CALL(*current_moments_obs_ptr_, GetMoment(index)).WillOnce(DoDefault()); EXPECT_CALL(*previous_moments_obs_ptr_, GetMoment(index)).WillOnce(ReturnRef(zero_flux)); } auto calculated_k_effective = test_updater.CalculateK_Effective(test_system_); EXPECT_NEAR(calculated_k_effective, initial_k_effective_, 1e-8); ASSERT_TRUE(test_updater.k_effective().has_value()); EXPECT_EQ(calculated_k_effective, test_updater.k_effective().value()); } } // namespace <commit_msg>fixed system.hpp name in updater_via_rayleigh_quotient_test.cpp<commit_after>#include "eigenvalue/k_effective/updater_via_rayleigh_quotient.hpp" #include "system/system.hpp" #include "system/moments/tests/spherical_harmonic_mock.h" #include "test_helpers/gmock_wrapper.h" namespace { using namespace bart; using ::testing::DoDefault, ::testing::NiceMock, ::testing::ReturnRef; class K_EffectiveUpdaterViaRayleighQuotientTest : public ::testing::Test { public: using SphericalHarmonicMock = NiceMock<system::moments::SphericalHarmonicMock>; using Vector = dealii::Vector<double>; static constexpr int total_groups_{ 2 }; static constexpr int vector_size_{ 3 }; const double initial_k_effective_{ 1.0235 }; const double expected_k_effective_{ 0.4094 }; std::array<Vector, total_groups_> current_moments_, previous_moments_; system::System test_system_ { .k_effective = initial_k_effective_, .total_groups = total_groups_ }; SphericalHarmonicMock* current_moments_obs_ptr_; SphericalHarmonicMock* previous_moments_obs_ptr_; auto SetUp() -> void override; }; auto K_EffectiveUpdaterViaRayleighQuotientTest::SetUp() -> void { for (int group = 0; group < total_groups_; ++group) { Vector current_group_moment(vector_size_), previous_group_moment(vector_size_); for (int i = 0; i < vector_size_; ++i) { if (group == 0) { current_group_moment[i] = (i + 1); previous_group_moment[i] = (i + 1 + vector_size_); } else { current_group_moment[i] = vector_size_ - i; previous_group_moment[i] = 2 * vector_size_ - i; } } current_moments_.at(group) = current_group_moment; previous_moments_.at(group) = previous_group_moment; } test_system_.current_moments = std::make_unique<SphericalHarmonicMock>(); test_system_.previous_moments = std::make_unique<SphericalHarmonicMock>(); current_moments_obs_ptr_ = dynamic_cast<SphericalHarmonicMock*>(test_system_.current_moments.get()); previous_moments_obs_ptr_ = dynamic_cast<SphericalHarmonicMock*>(test_system_.previous_moments.get()); for (int group = 0; group < total_groups_; ++group) { std::array<int, 3> index{ group, 0, 0 }; ON_CALL(*current_moments_obs_ptr_, GetMoment(index)).WillByDefault(ReturnRef(current_moments_.at(group))); ON_CALL(*previous_moments_obs_ptr_, GetMoment(index)).WillByDefault(ReturnRef(previous_moments_.at(group))); } } TEST_F(K_EffectiveUpdaterViaRayleighQuotientTest, Calculate) { eigenvalue::k_effective::UpdaterViaRayleighQuotient test_updater; EXPECT_FALSE(test_updater.k_effective().has_value()); for (int group = 0; group < total_groups_; ++group) { std::array<int, 3> index{ group, 0, 0 }; EXPECT_CALL(*current_moments_obs_ptr_, GetMoment(index)).WillOnce(DoDefault()); EXPECT_CALL(*previous_moments_obs_ptr_, GetMoment(index)).WillOnce(DoDefault()); } auto calculated_k_effective = test_updater.CalculateK_Effective(test_system_); EXPECT_NEAR(calculated_k_effective, expected_k_effective_, 1e-8); ASSERT_TRUE(test_updater.k_effective().has_value()); EXPECT_EQ(calculated_k_effective, test_updater.k_effective().value()); } TEST_F(K_EffectiveUpdaterViaRayleighQuotientTest, ZeroCurrentFlux) { eigenvalue::k_effective::UpdaterViaRayleighQuotient test_updater; EXPECT_FALSE(test_updater.k_effective().has_value()); Vector zero_flux(vector_size_); for (int group = 0; group < total_groups_; ++group) { std::array<int, 3> index{ group, 0, 0 }; EXPECT_CALL(*current_moments_obs_ptr_, GetMoment(index)).WillOnce(ReturnRef(zero_flux)); EXPECT_CALL(*previous_moments_obs_ptr_, GetMoment(index)).WillOnce(DoDefault()); } auto calculated_k_effective = test_updater.CalculateK_Effective(test_system_); EXPECT_NEAR(calculated_k_effective, 0, 1e-8); ASSERT_TRUE(test_updater.k_effective().has_value()); EXPECT_EQ(calculated_k_effective, test_updater.k_effective().value()); } TEST_F(K_EffectiveUpdaterViaRayleighQuotientTest, ZeroPreviousFlux) { eigenvalue::k_effective::UpdaterViaRayleighQuotient test_updater; EXPECT_FALSE(test_updater.k_effective().has_value()); Vector zero_flux(vector_size_); for (int group = 0; group < total_groups_; ++group) { std::array<int, 3> index{ group, 0, 0 }; EXPECT_CALL(*current_moments_obs_ptr_, GetMoment(index)).WillOnce(DoDefault()); EXPECT_CALL(*previous_moments_obs_ptr_, GetMoment(index)).WillOnce(ReturnRef(zero_flux)); } auto calculated_k_effective = test_updater.CalculateK_Effective(test_system_); EXPECT_NEAR(calculated_k_effective, initial_k_effective_, 1e-8); ASSERT_TRUE(test_updater.k_effective().has_value()); EXPECT_EQ(calculated_k_effective, test_updater.k_effective().value()); } } // namespace <|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 Qt Mobility Components. ** ** $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 "qcontactactionservicemanager_p.h" #include "qcontactaction.h" #include "qcontactactiondescriptor.h" #include "qcontactactionfactory.h" #include "qservicemanager.h" #include <QMutexLocker> QTM_BEGIN_NAMESPACE Q_GLOBAL_STATIC(QContactActionServiceManager, contactActionServiceManagerInstance) Q_EXPORT_PLUGIN2(qtcontacts_serviceactionmanager, QContactActionServiceManager); /*! \internal \class QContactActionServiceManager This class uses the service framework to discover contact actions which are provided by third parties. It is an implementation detail of QContactAction. */ QContactActionServiceManager* QContactActionServiceManager::instance() { return contactActionServiceManagerInstance(); } QContactActionServiceManager::QContactActionServiceManager() : QObject(), initLock(false) { } QContactActionServiceManager::~QContactActionServiceManager() { // we don't use qDeleteAll() because some factories produce more than one action descriptor. QList<QContactActionDescriptor> keys = m_actionFactoryHash.keys(); QSet<QContactActionFactory*> deletedFactories; foreach (const QContactActionDescriptor& key, keys) { QContactActionFactory *curr = m_actionFactoryHash.value(key); if (!deletedFactories.contains(curr)) { deletedFactories.insert(curr); delete curr; } } } void QContactActionServiceManager::init() { // XXX NOTE: should already be locked PRIOR to entering this function. if (!initLock) { initLock = true; // fill up our hashes QList<QServiceInterfaceDescriptor> sids = m_serviceManager.findInterfaces(); // all services, all interfaces. foreach (const QServiceInterfaceDescriptor& sid, sids) { if (sid.interfaceName() == QContactActionFactory::InterfaceName) { QContactActionFactory* actionFactory = qobject_cast<QContactActionFactory*>(m_serviceManager.loadInterface(sid)); if (actionFactory) { // if we cannot get the action factory from the service manager, then we don't add it to our hash. QList<QContactActionDescriptor> descriptors = actionFactory->actionDescriptors(); foreach (const QContactActionDescriptor& ad, descriptors) { m_descriptorHash.insert(ad.actionName(), ad); // multihash insert. m_actionFactoryHash.insert(ad, actionFactory); } } } } // and listen for signals. connect(&m_serviceManager, SIGNAL(serviceAdded(QString, QService::Scope)), this, SLOT(serviceAdded(QString))); connect(&m_serviceManager, SIGNAL(serviceRemoved(QString, QService::Scope)), this, SLOT(serviceRemoved(QString))); } } QHash<QContactActionDescriptor, QContactActionFactory*> QContactActionServiceManager::actionFactoryHash() { QMutexLocker locker(&m_instanceMutex); init(); return m_actionFactoryHash; } QMultiHash<QString, QContactActionDescriptor> QContactActionServiceManager::descriptorHash() { QMutexLocker locker(&m_instanceMutex); init(); return m_descriptorHash; } void QContactActionServiceManager::serviceAdded(const QString& serviceName) { QMutexLocker locker(&m_instanceMutex); QList<QServiceInterfaceDescriptor> sids = m_serviceManager.findInterfaces(serviceName); foreach (const QServiceInterfaceDescriptor& sid, sids) { if (sid.interfaceName().startsWith(QString(QLatin1String("com.nokia.qt.mobility.contacts")))) { QContactActionFactory* actionFactory = qobject_cast<QContactActionFactory*>(m_serviceManager.loadInterface(sid)); if (actionFactory) { // if we cannot get the action factory from the service manager, then we don't add it to our hash. QList<QContactActionDescriptor> descriptors = actionFactory->actionDescriptors(); foreach (const QContactActionDescriptor& ad, descriptors) { m_descriptorHash.insert(ad.actionName(), ad); // multihash insert. m_actionFactoryHash.insert(ad, actionFactory); } } } } } void QContactActionServiceManager::serviceRemoved(const QString& serviceName) { QMutexLocker locker(&m_instanceMutex); QList<QServiceInterfaceDescriptor> sids = m_serviceManager.findInterfaces(serviceName); foreach (const QServiceInterfaceDescriptor& sid, sids) { if (sid.interfaceName().startsWith(QString(QLatin1String("com.nokia.qt.mobility.contacts")))) { QList<QContactActionDescriptor> cads = m_actionFactoryHash.keys(); foreach (const QContactActionDescriptor& cad, cads) { if (cad.serviceName() != serviceName) continue; delete m_actionFactoryHash.value(cad); m_actionFactoryHash.remove(cad); m_descriptorHash.remove(cad.actionName(), cad); } } } } #include "moc_qcontactactionservicemanager_p.cpp" QTM_END_NAMESPACE <commit_msg>Ensure that contact action factory services are provided in-process<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 Qt Mobility Components. ** ** $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 "qcontactactionservicemanager_p.h" #include "qcontactaction.h" #include "qcontactactiondescriptor.h" #include "qcontactactionfactory.h" #include "qservicemanager.h" #include <QMutexLocker> QTM_BEGIN_NAMESPACE Q_GLOBAL_STATIC(QContactActionServiceManager, contactActionServiceManagerInstance) Q_EXPORT_PLUGIN2(qtcontacts_serviceactionmanager, QContactActionServiceManager); /*! \internal \class QContactActionServiceManager This class uses the service framework to discover contact actions which are provided by third parties. It is an implementation detail of QContactAction. */ QContactActionServiceManager* QContactActionServiceManager::instance() { return contactActionServiceManagerInstance(); } QContactActionServiceManager::QContactActionServiceManager() : QObject(), initLock(false) { } QContactActionServiceManager::~QContactActionServiceManager() { // we don't use qDeleteAll() because some factories produce more than one action descriptor. QList<QContactActionDescriptor> keys = m_actionFactoryHash.keys(); QSet<QContactActionFactory*> deletedFactories; foreach (const QContactActionDescriptor& key, keys) { QContactActionFactory *curr = m_actionFactoryHash.value(key); if (!deletedFactories.contains(curr)) { deletedFactories.insert(curr); delete curr; } } } void QContactActionServiceManager::init() { // XXX NOTE: should already be locked PRIOR to entering this function. if (!initLock) { initLock = true; // fill up our hashes QList<QServiceInterfaceDescriptor> sids = m_serviceManager.findInterfaces(); // all services, all interfaces. foreach (const QServiceInterfaceDescriptor& sid, sids) { if (sid.interfaceName() == QContactActionFactory::InterfaceName) { if (static_cast<QService::Type>(sid.attribute(QServiceInterfaceDescriptor::ServiceType).toInt()) != QService::Plugin) { continue; // we don't allow IPC contact action factories. } QContactActionFactory* actionFactory = qobject_cast<QContactActionFactory*>(m_serviceManager.loadInterface(sid)); if (actionFactory) { // if we cannot get the action factory from the service manager, then we don't add it to our hash. QList<QContactActionDescriptor> descriptors = actionFactory->actionDescriptors(); foreach (const QContactActionDescriptor& ad, descriptors) { m_descriptorHash.insert(ad.actionName(), ad); // multihash insert. m_actionFactoryHash.insert(ad, actionFactory); } } } } // and listen for signals. connect(&m_serviceManager, SIGNAL(serviceAdded(QString, QService::Scope)), this, SLOT(serviceAdded(QString))); connect(&m_serviceManager, SIGNAL(serviceRemoved(QString, QService::Scope)), this, SLOT(serviceRemoved(QString))); } } QHash<QContactActionDescriptor, QContactActionFactory*> QContactActionServiceManager::actionFactoryHash() { QMutexLocker locker(&m_instanceMutex); init(); return m_actionFactoryHash; } QMultiHash<QString, QContactActionDescriptor> QContactActionServiceManager::descriptorHash() { QMutexLocker locker(&m_instanceMutex); init(); return m_descriptorHash; } void QContactActionServiceManager::serviceAdded(const QString& serviceName) { QMutexLocker locker(&m_instanceMutex); QList<QServiceInterfaceDescriptor> sids = m_serviceManager.findInterfaces(serviceName); foreach (const QServiceInterfaceDescriptor& sid, sids) { if (sid.interfaceName() == QContactActionFactory::InterfaceName) { if (static_cast<QService::Type>(sid.attribute(QServiceInterfaceDescriptor::ServiceType).toInt()) != QService::Plugin) { continue; // we don't allow IPC contact action factories. } QContactActionFactory* actionFactory = qobject_cast<QContactActionFactory*>(m_serviceManager.loadInterface(sid)); if (actionFactory) { // if we cannot get the action factory from the service manager, then we don't add it to our hash. QList<QContactActionDescriptor> descriptors = actionFactory->actionDescriptors(); foreach (const QContactActionDescriptor& ad, descriptors) { m_descriptorHash.insert(ad.actionName(), ad); // multihash insert. m_actionFactoryHash.insert(ad, actionFactory); } } } } } void QContactActionServiceManager::serviceRemoved(const QString& serviceName) { QMutexLocker locker(&m_instanceMutex); QList<QServiceInterfaceDescriptor> sids = m_serviceManager.findInterfaces(serviceName); foreach (const QServiceInterfaceDescriptor& sid, sids) { if (sid.interfaceName() == QContactActionFactory::InterfaceName) { if (static_cast<QService::Type>(sid.attribute(QServiceInterfaceDescriptor::ServiceType).toInt()) != QService::Plugin) { continue; // we don't allow IPC contact action factories. } QList<QContactActionDescriptor> cads = m_actionFactoryHash.keys(); foreach (const QContactActionDescriptor& cad, cads) { if (cad.serviceName() != serviceName) continue; delete m_actionFactoryHash.value(cad); m_actionFactoryHash.remove(cad); m_descriptorHash.remove(cad.actionName(), cad); } } } } #include "moc_qcontactactionservicemanager_p.cpp" QTM_END_NAMESPACE <|endoftext|>
<commit_before>#include <libdvid/DVIDNode.h> #include <iostream> #include <string> #include <fstream> #include <vector> #include <tr1/unordered_map> #include <tr1/unordered_set> using std::cout; using std::endl; using std::ifstream; using std::string; using std::tr1::unordered_map; using std::tr1::unordered_set; using std::vector; using std::pair; using std::make_pair; using std::cin; const char * USAGE = "<prog> <dvid-server> <uuid> <label name> <sparse file> <body ID>"; const char * HELP = "Program takes a sparse volume and loads it into DVID"; int read_int(ifstream& fin) { char buffer[4]; // reading signed ints fin.read(buffer, 4); return *((int*) buffer); } int main(int argc, char** argv) { if (argc != 6) { cout << USAGE << endl; cout << HELP << endl; exit(1); } // create DVID node accessor libdvid::DVIDServer server(argv[1]); libdvid::DVIDNode dvid_node(server, argv[2]); string label_name = string(argv[3]); ifstream fin(argv[4]); unsigned long long new_body_id = (unsigned long long)(atoi(argv[5])); // read sparse volume one at a time int num_stripes = read_int(fin); typedef vector<pair<int, int> > segments_t; typedef unordered_map<int, segments_t> segmentsets_t; typedef unordered_map<int, segmentsets_t > sparse_t; sparse_t plane2segments; for (int i = 0; i < num_stripes; ++i) { int z = read_int(fin); int y = read_int(fin); // will same z,y appear multiple times segments_t segment_list; int num_segments = read_int(fin); for (int j = 0; j < num_segments; ++j) { int x1 = read_int(fin); int x2 = read_int(fin); segment_list.push_back(make_pair(x1, x2)); } plane2segments[z][y] = segment_list; } fin.close(); libdvid::tuple channels; channels.push_back(0); channels.push_back(1); channels.push_back(2); // iterate each z, load appropriate slice of a given size, relabel sparsely for (sparse_t::iterator iter = plane2segments.begin(); iter != plane2segments.end(); ++iter) { // get bounds int maxy = 0; int miny = INT_MAX; int maxx = 0; int minx = INT_MAX; for (segmentsets_t::iterator iter2 = iter->second.begin(); iter2 != iter->second.end(); ++iter2) { if (iter2->first < miny) { miny = iter2->first; } if (iter2->first > maxy) { maxy = iter2->first; } segments_t& segment_list = iter2->second; for (int i = 0; i < segment_list.size(); ++i) { if (segment_list[i].first < minx) { minx = segment_list[i].first; } if (segment_list[i].second > maxx) { maxx = segment_list[i].second; } } } // create dvid size and start points (X, Y, Z) libdvid::tuple sizes; sizes.push_back(maxx-minx+1); sizes.push_back(maxy-miny+1); sizes.push_back(1); libdvid::tuple start; start.push_back(minx); start.push_back(miny); sizes.push_back(iter->first); // retrieve dvid slice libdvid::DVIDLabelPtr label_data; dvid_node.get_volume_roi(label_name, start, sizes, channels, label_data); unsigned long long* ldata_raw = label_data->get_raw(); int width = maxx-minx+1; // rewrite body id in label data for (segmentsets_t::iterator iter2 = iter->second.begin(); iter2 != iter->second.end(); ++iter2) { segments_t& segment_list = iter2->second; int offset = (iter2->first - miny)*width; for (int i = 0; i < segment_list.size(); ++i) { for (int j = segment_list[i].first; j <= segment_list[i].second; ++j) { ldata_raw[offset + (j-minx)] = new_body_id; } } } // write new volume back libdvid::BinaryDataPtr labelbin = libdvid::BinaryData::create_binary_data((char*)(ldata_raw), sizeof(unsigned long long)*(width)*(maxy-miny+1)); dvid_node.write_volume_roi(label_name, start, sizes, channels, labelbin); } return 0; } <commit_msg>small bug fix and disabling throttling in load sparse<commit_after>#include <libdvid/DVIDNode.h> #include <iostream> #include <string> #include <fstream> #include <vector> #include <tr1/unordered_map> #include <tr1/unordered_set> using std::cout; using std::endl; using std::ifstream; using std::string; using std::tr1::unordered_map; using std::tr1::unordered_set; using std::vector; using std::pair; using std::make_pair; using std::cin; const char * USAGE = "<prog> <dvid-server> <uuid> <label name> <sparse file> <body ID>"; const char * HELP = "Program takes a sparse volume and loads it into DVID"; int read_int(ifstream& fin) { char buffer[4]; // reading signed ints fin.read(buffer, 4); return *((int*) buffer); } int main(int argc, char** argv) { if (argc != 6) { cout << USAGE << endl; cout << HELP << endl; exit(1); } // create DVID node accessor libdvid::DVIDServer server(argv[1]); libdvid::DVIDNode dvid_node(server, argv[2]); string label_name = string(argv[3]); ifstream fin(argv[4]); unsigned long long new_body_id = (unsigned long long)(atoi(argv[5])); // read sparse volume one at a time int num_stripes = read_int(fin); //cout << num_stripes << endl; typedef vector<pair<int, int> > segments_t; typedef unordered_map<int, segments_t> segmentsets_t; typedef unordered_map<int, segmentsets_t > sparse_t; sparse_t plane2segments; for (int i = 0; i < num_stripes; ++i) { int z = read_int(fin); int y = read_int(fin); //cout << z << " " << y << endl; // will same z,y appear multiple times segments_t segment_list; int num_segments = read_int(fin); for (int j = 0; j < num_segments; ++j) { int x1 = read_int(fin); int x2 = read_int(fin); segment_list.push_back(make_pair(x1, x2)); } plane2segments[z][y] = segment_list; } fin.close(); //return 0; libdvid::tuple channels; channels.push_back(0); channels.push_back(1); channels.push_back(2); // iterate each z, load appropriate slice of a given size, relabel sparsely for (sparse_t::iterator iter = plane2segments.begin(); iter != plane2segments.end(); ++iter) { // get bounds int maxy = 0; int miny = INT_MAX; int maxx = 0; int minx = INT_MAX; for (segmentsets_t::iterator iter2 = iter->second.begin(); iter2 != iter->second.end(); ++iter2) { if (iter2->first < miny) { miny = iter2->first; } if (iter2->first > maxy) { maxy = iter2->first; } segments_t& segment_list = iter2->second; for (int i = 0; i < segment_list.size(); ++i) { if (segment_list[i].first < minx) { minx = segment_list[i].first; } if (segment_list[i].second > maxx) { maxx = segment_list[i].second; } } } //cout << "z: " << iter->first << " y: " << miny << " x: " << minx << endl; //cout << maxx-minx+1 << "x" << maxy-miny+1 << "x1" << endl; // create dvid size and start points (X, Y, Z) libdvid::tuple sizes; sizes.push_back(maxx-minx+1); sizes.push_back(maxy-miny+1); sizes.push_back(1); libdvid::tuple start; start.push_back(minx); start.push_back(miny); start.push_back(iter->first); // retrieve dvid slice libdvid::DVIDLabelPtr label_data; dvid_node.get_volume_roi(label_name, start, sizes, channels, label_data, false); unsigned long long* ldata_raw = label_data->get_raw(); int width = maxx-minx+1; // rewrite body id in label data for (segmentsets_t::iterator iter2 = iter->second.begin(); iter2 != iter->second.end(); ++iter2) { segments_t& segment_list = iter2->second; int offset = (iter2->first - miny)*width; for (int i = 0; i < segment_list.size(); ++i) { for (int j = segment_list[i].first; j <= segment_list[i].second; ++j) { ldata_raw[offset + (j-minx)] = new_body_id; } } } // write new volume back libdvid::BinaryDataPtr labelbin = libdvid::BinaryData::create_binary_data((char*)(ldata_raw), sizeof(unsigned long long)*(width)*(maxy-miny+1)); dvid_node.write_volume_roi(label_name, start, sizes, channels, labelbin, false); } return 0; } <|endoftext|>
<commit_before>// REQUIRES: x86-registered-target // RUN: %clang_cc1 -triple x86_64-apple-darwin10 -g -fstandalone-debug -S -mllvm -generate-dwarf-pub-sections=Enable %s -o - | FileCheck %s // FIXME: This testcase shouldn't rely on assembly emission. //CHECK: Lpubtypes_begin[[SECNUM:[0-9]:]] //CHECK: .asciz "G" //CHECK-NEXT: .long 0 //CHECK-NEXT: Lpubtypes_end[[SECNUM]] class G { public: void foo(); }; void G::foo() { } <commit_msg>DebugInfo: Fix test for LLVM change r203619<commit_after>// REQUIRES: x86-registered-target // RUN: %clang_cc1 -triple x86_64-apple-darwin10 -g -fstandalone-debug -S -mllvm -generate-dwarf-pub-sections=Enable %s -o - | FileCheck %s // FIXME: This testcase shouldn't rely on assembly emission. //CHECK: LpubTypes_begin[[SECNUM:[0-9]:]] //CHECK: .asciz "G" //CHECK-NEXT: .long 0 //CHECK-NEXT: LpubTypes_end[[SECNUM]] class G { public: void foo(); }; void G::foo() { } <|endoftext|>
<commit_before>// RUN: %clang_cc1 -std=c++17 -fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name default-method.cpp -w %s | FileCheck %s -implicit-check-not="->" namespace PR39822 { struct unique_ptr { unique_ptr &operator=(unique_ptr &); }; class foo { foo &operator=(foo &); unique_ptr convertable_values_[2]; }; // CHECK: _ZN7PR398223fooaSERS0_: // CHECK-NEXT: File 0, [[@LINE+1]]:28 -> [[@LINE+1]]:29 = #0 foo &foo::operator=(foo &) = default; } // namespace PR39822 <commit_msg>[Coverage] Specify the Itanium ABI triple for a C++ test<commit_after>// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++17 -fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name default-method.cpp -w %s | FileCheck %s -implicit-check-not="->" namespace PR39822 { struct unique_ptr { unique_ptr &operator=(unique_ptr &); }; class foo { foo &operator=(foo &); unique_ptr convertable_values_[2]; }; // CHECK: _ZN7PR398223fooaSERS0_: // CHECK-NEXT: File 0, [[@LINE+1]]:28 -> [[@LINE+1]]:29 = #0 foo &foo::operator=(foo &) = default; } // namespace PR39822 <|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 "base/logging.h" #include "views/window/client_view.h" #if defined(OS_LINUX) #include "views/window/hit_test.h" #endif #include "views/window/window.h" #include "views/window/window_delegate.h" namespace views { /////////////////////////////////////////////////////////////////////////////// // ClientView, public: ClientView::ClientView(Window* window, View* contents_view) : window_(window), contents_view_(contents_view) { } int ClientView::NonClientHitTest(const gfx::Point& point) { return bounds().Contains(point) ? HTCLIENT : HTNOWHERE; } void ClientView::WindowClosing() { window_->GetDelegate()->WindowClosing(); } /////////////////////////////////////////////////////////////////////////////// // ClientView, View overrides: gfx::Size ClientView::GetPreferredSize() { // |contents_view_| is allowed to be NULL up until the point where this view // is attached to a Container. if (contents_view_) return contents_view_->GetPreferredSize(); return gfx::Size(); } void ClientView::Layout() { // |contents_view_| is allowed to be NULL up until the point where this view // is attached to a Container. if (contents_view_) contents_view_->SetBounds(0, 0, width(), height()); } void ClientView::ViewHierarchyChanged(bool is_add, View* parent, View* child) { if (is_add && child == this) { DCHECK(GetWidget()); DCHECK(contents_view_); // |contents_view_| must be valid now! AddChildView(contents_view_); } } void ClientView::DidChangeBounds(const gfx::Rect& previous, const gfx::Rect& current) { // Overridden to do nothing. The NonClientView manually calls Layout on the // ClientView when it is itself laid out, see comment in // NonClientView::Layout. } bool ClientView::GetAccessibleRole(AccessibilityTypes::Role* role) { *role = AccessibilityTypes::ROLE_CLIENT; return true; } } // namespace views <commit_msg>Fix focus traversal order in dialogs. In a dialog, the contents view is added after the buttons have been added. That would mess up the focus traversal order. The problem was particularly visible in the basic auth dialog. This CL ensures the contents is added as the first view so the focus chain is right.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/logging.h" #include "views/window/client_view.h" #if defined(OS_LINUX) #include "views/window/hit_test.h" #endif #include "views/window/window.h" #include "views/window/window_delegate.h" namespace views { /////////////////////////////////////////////////////////////////////////////// // ClientView, public: ClientView::ClientView(Window* window, View* contents_view) : window_(window), contents_view_(contents_view) { } int ClientView::NonClientHitTest(const gfx::Point& point) { return bounds().Contains(point) ? HTCLIENT : HTNOWHERE; } void ClientView::WindowClosing() { window_->GetDelegate()->WindowClosing(); } /////////////////////////////////////////////////////////////////////////////// // ClientView, View overrides: gfx::Size ClientView::GetPreferredSize() { // |contents_view_| is allowed to be NULL up until the point where this view // is attached to a Container. if (contents_view_) return contents_view_->GetPreferredSize(); return gfx::Size(); } void ClientView::Layout() { // |contents_view_| is allowed to be NULL up until the point where this view // is attached to a Container. if (contents_view_) contents_view_->SetBounds(0, 0, width(), height()); } void ClientView::ViewHierarchyChanged(bool is_add, View* parent, View* child) { if (is_add && child == this) { DCHECK(GetWidget()); DCHECK(contents_view_); // |contents_view_| must be valid now! // Insert |contents_view_| at index 0 so it is first in the focus chain. // (the OK/Cancel buttons are inserted before contents_view_) AddChildView(0, contents_view_); } } void ClientView::DidChangeBounds(const gfx::Rect& previous, const gfx::Rect& current) { // Overridden to do nothing. The NonClientView manually calls Layout on the // ClientView when it is itself laid out, see comment in // NonClientView::Layout. } bool ClientView::GetAccessibleRole(AccessibilityTypes::Role* role) { *role = AccessibilityTypes::ROLE_CLIENT; return true; } } // namespace views <|endoftext|>
<commit_before>/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under both the Apache 2.0 license (found in the * LICENSE file in the root directory of this source tree) and the GPLv2 (found * in the COPYING file in the root directory of this source tree). * You may select, at your option, one of the above-listed licenses. */ #include <asm/unistd_64.h> #include <osquery/logger.h> #include <osquery/registry_factory.h> #include <osquery/sql.h> #include "osquery/tables/events/linux/process_events.h" namespace osquery { FLAG(bool, audit_allow_process_events, true, "Allow the audit publisher to install process event monitoring rules"); // Depend on the external getUptime table method. namespace tables { extern long getUptime(); } REGISTER(AuditProcessEventSubscriber, "event_subscriber", "process_events"); Status AuditProcessEventSubscriber::init() { if (!FLAGS_audit_allow_process_events) { return Status(1, "Subscriber disabled via configuration"); } auto sc = createSubscriptionContext(); subscribe(&AuditProcessEventSubscriber::Callback, sc); return Status(0, "OK"); } Status AuditProcessEventSubscriber::Callback(const ECRef& ec, const SCRef& sc) { std::vector<Row> emitted_row_list; auto status = ProcessEvents(emitted_row_list, ec->audit_events); if (!status.ok()) { return status; } addBatch(emitted_row_list); return Status(0, "Ok"); } Status AuditProcessEventSubscriber::ProcessEvents( std::vector<Row>& emitted_row_list, const std::vector<AuditEvent>& event_list) noexcept { // clang-format off /* 1300 audit(1502125323.756:6): arch=c000003e syscall=59 success=yes exit=0 a0=23eb8e0 a1=23ebbc0 a2=23c9860 a3=7ffe18d32ed0 items=2 ppid=6882 pid=7841 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts1 ses=2 comm="sh" exe="/usr/bin/bash" subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 key=(null) 1309 audit(1502125323.756:6): argc=1 a0="sh" 1307 audit(1502125323.756:6): cwd="/home/alessandro" 1302 audit(1502125323.756:6): item=0 name="/usr/bin/sh" inode=18867 dev=fd:00 mode=0100755 ouid=0 ogid=0 rdev=00:00 obj=system_u:object_r:shell_exec_t:s0 objtype=NORMAL 1302 audit(1502125323.756:6): item=1 name="/lib64/ld-linux-x86-64.so.2" inode=33604032 dev=fd:00 mode=0100755 ouid=0 ogid=0 rdev=00:00 obj=system_u:object_r:ld_so_t:s0 objtype=NORMAL 1320 audit(1502125323.756:6): */ // clang-format on emitted_row_list.clear(); emitted_row_list.reserve(event_list.size()); for (const auto& event : event_list) { if (event.type != AuditEvent::Type::Syscall) { continue; } const auto& event_data = boost::get<SyscallAuditEventData>(event.data); if (event_data.syscall_number != __NR_execve) { continue; } const AuditEventRecord* syscall_event_record = GetEventRecord(event, AUDIT_SYSCALL); if (syscall_event_record == nullptr) { VLOG(1) << "Malformed AUDIT_SYSCALL event"; continue; } const AuditEventRecord* execve_event_record = GetEventRecord(event, AUDIT_EXECVE); if (execve_event_record == nullptr) { VLOG(1) << "Malformed AUDIT_EXECVE event"; continue; } const AuditEventRecord* first_path_event_record = GetEventRecord(event, AUDIT_PATH); if (first_path_event_record == nullptr) { VLOG(1) << "Malformed AUDIT_PATH event"; continue; } Row row = {}; CopyFieldFromMap(row, syscall_event_record->fields, "auid", "0"); CopyFieldFromMap(row, syscall_event_record->fields, "pid", "0"); CopyFieldFromMap(row, syscall_event_record->fields, "ppid", "0"); CopyFieldFromMap(row, syscall_event_record->fields, "uid", "0"); CopyFieldFromMap(row, syscall_event_record->fields, "euid", "0"); CopyFieldFromMap(row, syscall_event_record->fields, "gid", "0"); CopyFieldFromMap(row, syscall_event_record->fields, "egid", "0"); std::string field_value; GetStringFieldFromMap(field_value, syscall_event_record->fields, "exe", ""); row["path"] = DecodeAuditPathValues(field_value); auto qd = SQL::selectAllFrom("file", "path", EQUALS, row.at("path")); if (qd.size() == 1) { row["ctime"] = qd.front().at("ctime"); row["atime"] = qd.front().at("atime"); row["mtime"] = qd.front().at("mtime"); row["btime"] = "0"; } row["overflows"] = ""; row["env_size"] = "0"; row["env_count"] = "0"; row["env"] = ""; row["uptime"] = std::to_string(tables::getUptime()); // build the command line from the AUDIT_EXECVE record row["cmdline"] = ""; for (const auto& arg : execve_event_record->fields) { if (arg.first == "argc") { continue; } // Amalgamate all the "arg*" fields. if (row.at("cmdline").size() > 0) { row["cmdline"] += " "; } row["cmdline"] += DecodeAuditPathValues(arg.second); } // There may be a better way to calculate actual size from audit. // Then an overflow could be calculated/determined based on // actual/expected. row["cmdline_size"] = std::to_string(row.at("cmdline").size()); // Get the remaining data from the first AUDIT_PATH record CopyFieldFromMap(row, first_path_event_record->fields, "mode", ""); GetStringFieldFromMap( row["owner_uid"], first_path_event_record->fields, "ouid", "0"); GetStringFieldFromMap( row["owner_gid"], first_path_event_record->fields, "ogid", "0"); // Parent is currently not supported on Linux. row["parent"] = "-1"; emitted_row_list.push_back(row); } return Status(0, "Ok"); } const std::set<int>& AuditProcessEventSubscriber::GetSyscallSet() noexcept { static const std::set<int> syscall_set = {__NR_execve}; return syscall_set; } } // namespace osquery <commit_msg>Add ppid and cwd field for each new created process (#4784)<commit_after>/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under both the Apache 2.0 license (found in the * LICENSE file in the root directory of this source tree) and the GPLv2 (found * in the COPYING file in the root directory of this source tree). * You may select, at your option, one of the above-listed licenses. */ #include <asm/unistd_64.h> #include <osquery/logger.h> #include <osquery/registry_factory.h> #include <osquery/sql.h> #include "osquery/tables/events/linux/process_events.h" namespace osquery { FLAG(bool, audit_allow_process_events, true, "Allow the audit publisher to install process event monitoring rules"); // Depend on the external getUptime table method. namespace tables { extern long getUptime(); } REGISTER(AuditProcessEventSubscriber, "event_subscriber", "process_events"); Status AuditProcessEventSubscriber::init() { if (!FLAGS_audit_allow_process_events) { return Status(1, "Subscriber disabled via configuration"); } auto sc = createSubscriptionContext(); subscribe(&AuditProcessEventSubscriber::Callback, sc); return Status(0, "OK"); } Status AuditProcessEventSubscriber::Callback(const ECRef& ec, const SCRef& sc) { std::vector<Row> emitted_row_list; auto status = ProcessEvents(emitted_row_list, ec->audit_events); if (!status.ok()) { return status; } addBatch(emitted_row_list); return Status(0, "Ok"); } Status AuditProcessEventSubscriber::ProcessEvents( std::vector<Row>& emitted_row_list, const std::vector<AuditEvent>& event_list) noexcept { // clang-format off /* 1300 audit(1502125323.756:6): arch=c000003e syscall=59 success=yes exit=0 a0=23eb8e0 a1=23ebbc0 a2=23c9860 a3=7ffe18d32ed0 items=2 ppid=6882 pid=7841 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts1 ses=2 comm="sh" exe="/usr/bin/bash" subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 key=(null) 1309 audit(1502125323.756:6): argc=1 a0="sh" 1307 audit(1502125323.756:6): cwd="/home/alessandro" 1302 audit(1502125323.756:6): item=0 name="/usr/bin/sh" inode=18867 dev=fd:00 mode=0100755 ouid=0 ogid=0 rdev=00:00 obj=system_u:object_r:shell_exec_t:s0 objtype=NORMAL 1302 audit(1502125323.756:6): item=1 name="/lib64/ld-linux-x86-64.so.2" inode=33604032 dev=fd:00 mode=0100755 ouid=0 ogid=0 rdev=00:00 obj=system_u:object_r:ld_so_t:s0 objtype=NORMAL 1320 audit(1502125323.756:6): */ // clang-format on emitted_row_list.clear(); emitted_row_list.reserve(event_list.size()); for (const auto& event : event_list) { if (event.type != AuditEvent::Type::Syscall) { continue; } const auto& event_data = boost::get<SyscallAuditEventData>(event.data); if (event_data.syscall_number != __NR_execve) { continue; } const AuditEventRecord* syscall_event_record = GetEventRecord(event, AUDIT_SYSCALL); if (syscall_event_record == nullptr) { VLOG(1) << "Malformed AUDIT_SYSCALL event"; continue; } const AuditEventRecord* execve_event_record = GetEventRecord(event, AUDIT_EXECVE); if (execve_event_record == nullptr) { VLOG(1) << "Malformed AUDIT_EXECVE event"; continue; } const AuditEventRecord* first_path_event_record = GetEventRecord(event, AUDIT_PATH); if (first_path_event_record == nullptr) { VLOG(1) << "Malformed AUDIT_PATH event"; continue; } const AuditEventRecord* cwd_event_record = GetEventRecord(event, AUDIT_CWD); if (cwd_event_record == nullptr) { VLOG(1) << "Malformed AUDIT_CWD event"; continue; } Row row = {}; CopyFieldFromMap(row, syscall_event_record->fields, "auid", "0"); CopyFieldFromMap(row, syscall_event_record->fields, "pid", "0"); CopyFieldFromMap(row, syscall_event_record->fields, "uid", "0"); CopyFieldFromMap(row, syscall_event_record->fields, "euid", "0"); CopyFieldFromMap(row, syscall_event_record->fields, "gid", "0"); CopyFieldFromMap(row, syscall_event_record->fields, "egid", "0"); CopyFieldFromMap(row, cwd_event_record->fields, "cwd", "0"); std::uint64_t parent_process_id; GetIntegerFieldFromMap( parent_process_id, syscall_event_record->fields, "ppid"); row["parent"] = std::to_string(parent_process_id); std::string field_value; GetStringFieldFromMap(field_value, syscall_event_record->fields, "exe", ""); row["path"] = DecodeAuditPathValues(field_value); auto qd = SQL::selectAllFrom("file", "path", EQUALS, row.at("path")); if (qd.size() == 1) { row["ctime"] = qd.front().at("ctime"); row["atime"] = qd.front().at("atime"); row["mtime"] = qd.front().at("mtime"); row["btime"] = "0"; } row["overflows"] = ""; row["env_size"] = "0"; row["env_count"] = "0"; row["env"] = ""; row["uptime"] = std::to_string(tables::getUptime()); // build the command line from the AUDIT_EXECVE record row["cmdline"] = ""; for (const auto& arg : execve_event_record->fields) { if (arg.first == "argc") { continue; } // Amalgamate all the "arg*" fields. if (row.at("cmdline").size() > 0) { row["cmdline"] += " "; } row["cmdline"] += DecodeAuditPathValues(arg.second); } // There may be a better way to calculate actual size from audit. // Then an overflow could be calculated/determined based on // actual/expected. row["cmdline_size"] = std::to_string(row.at("cmdline").size()); // Get the remaining data from the first AUDIT_PATH record CopyFieldFromMap(row, first_path_event_record->fields, "mode", ""); GetStringFieldFromMap( row["owner_uid"], first_path_event_record->fields, "ouid", "0"); GetStringFieldFromMap( row["owner_gid"], first_path_event_record->fields, "ogid", "0"); emitted_row_list.push_back(row); } return Status(0, "Ok"); } const std::set<int>& AuditProcessEventSubscriber::GetSyscallSet() noexcept { static const std::set<int> syscall_set = {__NR_execve}; return syscall_set; } } // namespace osquery <|endoftext|>
<commit_before>#include "objectives/noisy/genetic-noise/NonNoisyGeneticSource.hpp" NonNoisyGeneticSource::NonNoisyGeneticSource() : GeneticNoiseSource() {}; Genome NonNoisyGeneticSource::addNoise(Genome * target) { return Genome(target); } <commit_msg>[NonNoisyGeneticSource]: Dropped unnecessary semicolon<commit_after>#include "objectives/noisy/genetic-noise/NonNoisyGeneticSource.hpp" NonNoisyGeneticSource::NonNoisyGeneticSource() : GeneticNoiseSource() {} Genome NonNoisyGeneticSource::addNoise(Genome * target) { return Genome(target); } <|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 QtSparql module (not yet part of the Qt Toolkit). ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qsparql_tracker_direct.h" #include "qsparql_tracker_direct_p.h" #include <qsparqlerror.h> #include <qsparqlbinding.h> #include <qsparqlquery.h> #include <qsparqlresultrow.h> #include <qcoreapplication.h> #include <qvariant.h> #include <qstringlist.h> #include <qvector.h> #include <qdebug.h> QT_BEGIN_NAMESPACE static void async_cursor_next_callback( GObject *source_object, GAsyncResult *result, gpointer user_data) { Q_UNUSED(source_object); QTrackerDirectResultPrivate *data = static_cast<QTrackerDirectResultPrivate*>(user_data); GError *error = NULL; gboolean active = tracker_sparql_cursor_next_finish(data->cursor, result, &error); if (error != NULL) { QSparqlError e(QString::fromLatin1(error ? error->message : "unknown error")); e.setType(QSparqlError::BackendError); data->setLastError(e); data->terminate(); return; } if (!active) { if (data->q->isBool()) { data->setBoolValue(data->results.count() == 1 && data->results[0].count() == 1 && data->results[0].value(0).toString() == QLatin1String("1")); } data->terminate(); return; } QSparqlResultRow resultRow; gint n_columns = tracker_sparql_cursor_get_n_columns(data->cursor); for (int i = 0; i < n_columns; i++) { // As Tracker doesn't return the variable names in the query yet, call // the variables $1, $2, $3.. as that is better than no names QString name = QString::fromLatin1("$%1").arg(i + 1); QString value = QString::fromUtf8(tracker_sparql_cursor_get_string(data->cursor, i, NULL)); if (value.startsWith(QLatin1String("_:"))) { QSparqlBinding binding(name); binding.setBlankNodeLabel(value.mid(2)); resultRow.append(binding); } else if (value.startsWith(QLatin1String("http:")) || value.startsWith(QLatin1String("urn:"))) { resultRow.append(QSparqlBinding(name, QUrl(value))); } else { resultRow.append(QSparqlBinding(name, value)); } } data->results.append(resultRow); data->dataReady(data->results.count()); tracker_sparql_cursor_next_async(data->cursor, NULL, async_cursor_next_callback, data); } static void async_query_callback( GObject *source_object, GAsyncResult *result, gpointer user_data) { Q_UNUSED(source_object); QTrackerDirectResultPrivate *data = static_cast<QTrackerDirectResultPrivate*>(user_data); GError *error = NULL; data->cursor = tracker_sparql_connection_query_finish(data->driverPrivate->connection, result, &error); if (error != NULL || data->cursor == NULL) { QSparqlError e(QString::fromLatin1(error ? error->message : "unknown error")); e.setType(QSparqlError::StatementError); data->setLastError(e); data->terminate(); return; } tracker_sparql_cursor_next_async(data->cursor, NULL, async_cursor_next_callback, data); } static void async_update_callback( GObject *source_object, GAsyncResult *result, gpointer user_data) { Q_UNUSED(source_object); QTrackerDirectResultPrivate *data = static_cast<QTrackerDirectResultPrivate*>(user_data); GError *error = NULL; tracker_sparql_connection_update_finish(data->driverPrivate->connection, result, &error); if (error != NULL) { QSparqlError e(QString::fromLatin1(error ? error->message : "unknown error")); e.setType(QSparqlError::StatementError); data->setLastError(e); data->terminate(); return; } data->terminate(); } QTrackerDirectResultPrivate::QTrackerDirectResultPrivate(QTrackerDirectResult* result, QTrackerDirectDriverPrivate *dpp) : isFinished(false), loop(0), q(result), driverPrivate(dpp) { } QTrackerDirectResultPrivate::~QTrackerDirectResultPrivate() { } void QTrackerDirectResultPrivate::terminate() { isFinished = true; q->emit finished(); if (loop != 0) loop->exit(); } void QTrackerDirectResultPrivate::setLastError(const QSparqlError& e) { q->setLastError(e); } void QTrackerDirectResultPrivate::setBoolValue(bool v) { q->setBoolValue(v); } void QTrackerDirectResultPrivate::dataReady(int totalCount) { emit q->dataReady(totalCount); } QTrackerDirectResult::QTrackerDirectResult(QTrackerDirectDriverPrivate* p) { d = new QTrackerDirectResultPrivate(this, p); } QTrackerDirectResult::~QTrackerDirectResult() { delete d; } QTrackerDirectResult* QTrackerDirectDriver::exec(const QString& query, QSparqlQuery::StatementType type) { QTrackerDirectResult* res = new QTrackerDirectResult(d); res->setStatementType(type); switch (type) { case QSparqlQuery::AskStatement: case QSparqlQuery::SelectStatement: { tracker_sparql_connection_query_async( d->connection, query.toLatin1().constData(), NULL, async_query_callback, res->d); break; } case QSparqlQuery::InsertStatement: case QSparqlQuery::DeleteStatement: tracker_sparql_connection_update_async( d->connection, query.toLatin1().constData(), 0, NULL, async_update_callback, res->d); { break; } default: qWarning() << "Tracker backend: unsupported statement type"; res->setLastError(QSparqlError( QLatin1String("Unsupported statement type"), QSparqlError::BackendError)); break; } return res; } void QTrackerDirectResult::cleanup() { setPos(QSparql::BeforeFirstRow); } bool QTrackerDirectResult::fetch(int i) { if (i < 0) { setPos(QSparql::BeforeFirstRow); return false; } if (i >= d->results.size()) { setPos(QSparql::AfterLastRow); return false; } setPos(i); return true; } bool QTrackerDirectResult::fetchLast() { if (d->results.count() == 0) return false; setPos(d->results.count() - 1); return true; } bool QTrackerDirectResult::fetchFirst() { if (pos() == 0) return true; return fetch(0); } QVariant QTrackerDirectResult::data(int field) const { if (field >= d->results[pos()].count() || field < 0) { qWarning() << "QTrackerDirectResult::data[" << pos() << "]: column" << field << "out of range"; return QVariant(); } return d->results[pos()].binding(field).value(); } void QTrackerDirectResult::waitForFinished() { if (d->isFinished) return; QEventLoop loop; d->loop = &loop; loop.exec(); d->loop = 0; } bool QTrackerDirectResult::isFinished() const { // if (d->watcher) // return d->watcher->isFinished(); return true; } bool QTrackerDirectResult::isNull(int field) const { Q_UNUSED(field); return false; } int QTrackerDirectResult::size() const { return d->results.count(); } QSparqlResultRow QTrackerDirectResult::resultRow() const { QSparqlResultRow info; if (pos() < 0 || pos() >= d->results.count()) return info; return d->results[pos()]; } QTrackerDirectDriverPrivate::QTrackerDirectDriverPrivate() { } QTrackerDirectDriverPrivate::~QTrackerDirectDriverPrivate() { } QTrackerDirectDriver::QTrackerDirectDriver(QObject* parent) : QSparqlDriver(parent) { d = new QTrackerDirectDriverPrivate(); /* Initialize GLib type system */ g_type_init(); } QTrackerDirectDriver::~QTrackerDirectDriver() { delete d; } bool QTrackerDirectDriver::hasFeature(QSparqlConnection::Feature f) const { switch (f) { case QSparqlConnection::QuerySize: return true; case QSparqlConnection::AskQueries: return true; case QSparqlConnection::ConstructQueries: return false; case QSparqlConnection::UpdateQueries: return true; case QSparqlConnection::DefaultGraph: return true; } return false; } QAtomicInt connectionCounter = 0; bool QTrackerDirectDriver::open(const QSparqlConnectionOptions& options) { Q_UNUSED(options); if (isOpen()) close(); GError *error = NULL; d->connection = tracker_sparql_connection_get(&error); if (!d->connection) { qWarning("Couldn't obtain a direct connection to the Tracker store: %s", error ? error->message : "unknown error"); return false; } setOpen(true); setOpenError(false); return true; } void QTrackerDirectDriver::close() { if (isOpen()) { setOpen(false); setOpenError(false); } } QT_END_NAMESPACE <commit_msg>* Call g_object_unref() on the tracker connection in the driver close() method<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 QtSparql module (not yet part of the Qt Toolkit). ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qsparql_tracker_direct.h" #include "qsparql_tracker_direct_p.h" #include <qsparqlerror.h> #include <qsparqlbinding.h> #include <qsparqlquery.h> #include <qsparqlresultrow.h> #include <qcoreapplication.h> #include <qvariant.h> #include <qstringlist.h> #include <qvector.h> #include <qdebug.h> QT_BEGIN_NAMESPACE static void async_cursor_next_callback( GObject *source_object, GAsyncResult *result, gpointer user_data) { Q_UNUSED(source_object); QTrackerDirectResultPrivate *data = static_cast<QTrackerDirectResultPrivate*>(user_data); GError *error = NULL; gboolean active = tracker_sparql_cursor_next_finish(data->cursor, result, &error); if (error != NULL) { QSparqlError e(QString::fromLatin1(error ? error->message : "unknown error")); e.setType(QSparqlError::BackendError); data->setLastError(e); data->terminate(); return; } if (!active) { if (data->q->isBool()) { data->setBoolValue(data->results.count() == 1 && data->results[0].count() == 1 && data->results[0].value(0).toString() == QLatin1String("1")); } data->terminate(); return; } QSparqlResultRow resultRow; gint n_columns = tracker_sparql_cursor_get_n_columns(data->cursor); for (int i = 0; i < n_columns; i++) { // As Tracker doesn't return the variable names in the query yet, call // the variables $1, $2, $3.. as that is better than no names QString name = QString::fromLatin1("$%1").arg(i + 1); QString value = QString::fromUtf8(tracker_sparql_cursor_get_string(data->cursor, i, NULL)); if (value.startsWith(QLatin1String("_:"))) { QSparqlBinding binding(name); binding.setBlankNodeLabel(value.mid(2)); resultRow.append(binding); } else if (value.startsWith(QLatin1String("http:")) || value.startsWith(QLatin1String("urn:"))) { resultRow.append(QSparqlBinding(name, QUrl(value))); } else { resultRow.append(QSparqlBinding(name, value)); } } data->results.append(resultRow); data->dataReady(data->results.count()); tracker_sparql_cursor_next_async(data->cursor, NULL, async_cursor_next_callback, data); } static void async_query_callback( GObject *source_object, GAsyncResult *result, gpointer user_data) { Q_UNUSED(source_object); QTrackerDirectResultPrivate *data = static_cast<QTrackerDirectResultPrivate*>(user_data); GError *error = NULL; data->cursor = tracker_sparql_connection_query_finish(data->driverPrivate->connection, result, &error); if (error != NULL || data->cursor == NULL) { QSparqlError e(QString::fromLatin1(error ? error->message : "unknown error")); e.setType(QSparqlError::StatementError); data->setLastError(e); data->terminate(); return; } tracker_sparql_cursor_next_async(data->cursor, NULL, async_cursor_next_callback, data); } static void async_update_callback( GObject *source_object, GAsyncResult *result, gpointer user_data) { Q_UNUSED(source_object); QTrackerDirectResultPrivate *data = static_cast<QTrackerDirectResultPrivate*>(user_data); GError *error = NULL; tracker_sparql_connection_update_finish(data->driverPrivate->connection, result, &error); if (error != NULL) { QSparqlError e(QString::fromLatin1(error ? error->message : "unknown error")); e.setType(QSparqlError::StatementError); data->setLastError(e); data->terminate(); return; } data->terminate(); } QTrackerDirectResultPrivate::QTrackerDirectResultPrivate(QTrackerDirectResult* result, QTrackerDirectDriverPrivate *dpp) : isFinished(false), loop(0), q(result), driverPrivate(dpp) { } QTrackerDirectResultPrivate::~QTrackerDirectResultPrivate() { } void QTrackerDirectResultPrivate::terminate() { isFinished = true; q->emit finished(); if (loop != 0) loop->exit(); } void QTrackerDirectResultPrivate::setLastError(const QSparqlError& e) { q->setLastError(e); } void QTrackerDirectResultPrivate::setBoolValue(bool v) { q->setBoolValue(v); } void QTrackerDirectResultPrivate::dataReady(int totalCount) { emit q->dataReady(totalCount); } QTrackerDirectResult::QTrackerDirectResult(QTrackerDirectDriverPrivate* p) { d = new QTrackerDirectResultPrivate(this, p); } QTrackerDirectResult::~QTrackerDirectResult() { delete d; } QTrackerDirectResult* QTrackerDirectDriver::exec(const QString& query, QSparqlQuery::StatementType type) { QTrackerDirectResult* res = new QTrackerDirectResult(d); res->setStatementType(type); switch (type) { case QSparqlQuery::AskStatement: case QSparqlQuery::SelectStatement: { tracker_sparql_connection_query_async( d->connection, query.toLatin1().constData(), NULL, async_query_callback, res->d); break; } case QSparqlQuery::InsertStatement: case QSparqlQuery::DeleteStatement: tracker_sparql_connection_update_async( d->connection, query.toLatin1().constData(), 0, NULL, async_update_callback, res->d); { break; } default: qWarning() << "Tracker backend: unsupported statement type"; res->setLastError(QSparqlError( QLatin1String("Unsupported statement type"), QSparqlError::BackendError)); break; } return res; } void QTrackerDirectResult::cleanup() { setPos(QSparql::BeforeFirstRow); } bool QTrackerDirectResult::fetch(int i) { if (i < 0) { setPos(QSparql::BeforeFirstRow); return false; } if (i >= d->results.size()) { setPos(QSparql::AfterLastRow); return false; } setPos(i); return true; } bool QTrackerDirectResult::fetchLast() { if (d->results.count() == 0) return false; setPos(d->results.count() - 1); return true; } bool QTrackerDirectResult::fetchFirst() { if (pos() == 0) return true; return fetch(0); } QVariant QTrackerDirectResult::data(int field) const { if (field >= d->results[pos()].count() || field < 0) { qWarning() << "QTrackerDirectResult::data[" << pos() << "]: column" << field << "out of range"; return QVariant(); } return d->results[pos()].binding(field).value(); } void QTrackerDirectResult::waitForFinished() { if (d->isFinished) return; QEventLoop loop; d->loop = &loop; loop.exec(); d->loop = 0; } bool QTrackerDirectResult::isFinished() const { // if (d->watcher) // return d->watcher->isFinished(); return true; } bool QTrackerDirectResult::isNull(int field) const { Q_UNUSED(field); return false; } int QTrackerDirectResult::size() const { return d->results.count(); } QSparqlResultRow QTrackerDirectResult::resultRow() const { QSparqlResultRow info; if (pos() < 0 || pos() >= d->results.count()) return info; return d->results[pos()]; } QTrackerDirectDriverPrivate::QTrackerDirectDriverPrivate() { } QTrackerDirectDriverPrivate::~QTrackerDirectDriverPrivate() { } QTrackerDirectDriver::QTrackerDirectDriver(QObject* parent) : QSparqlDriver(parent) { d = new QTrackerDirectDriverPrivate(); /* Initialize GLib type system */ g_type_init(); } QTrackerDirectDriver::~QTrackerDirectDriver() { delete d; } bool QTrackerDirectDriver::hasFeature(QSparqlConnection::Feature f) const { switch (f) { case QSparqlConnection::QuerySize: return true; case QSparqlConnection::AskQueries: return true; case QSparqlConnection::ConstructQueries: return false; case QSparqlConnection::UpdateQueries: return true; case QSparqlConnection::DefaultGraph: return true; } return false; } QAtomicInt connectionCounter = 0; bool QTrackerDirectDriver::open(const QSparqlConnectionOptions& options) { Q_UNUSED(options); if (isOpen()) close(); GError *error = NULL; d->connection = tracker_sparql_connection_get(&error); if (!d->connection) { qWarning("Couldn't obtain a direct connection to the Tracker store: %s", error ? error->message : "unknown error"); return false; } setOpen(true); setOpenError(false); return true; } void QTrackerDirectDriver::close() { g_object_unref(d->connection); if (isOpen()) { setOpen(false); setOpenError(false); } } QT_END_NAMESPACE <|endoftext|>
<commit_before>/**************************************************************************** * Copyright (c) 2012-2019 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #include "DTK_BoostRangeAdapters.hpp" #include "DTK_EnableViewComparison.hpp" #include <DTK_Box.hpp> #include <DTK_DetailsAlgorithms.hpp> #include <DTK_Point.hpp> #include <Kokkos_Core.hpp> #include <Teuchos_UnitTestHarness.hpp> #include <boost/range/algorithm.hpp> // reverse_copy, replace_if, count, generate, count_if #include <boost/range/algorithm_ext.hpp> // iota #include <boost/range/numeric.hpp> // accumulate #include <boost/test/unit_test.hpp> #include <random> #include <sstream> #define BOOST_TEST_MODULE BoostRangeAdapters namespace tt = boost::test_tools; BOOST_AUTO_TEST_CASE( range_algorithms ) { Kokkos::View<int[4], Kokkos::HostSpace> w( "w" ); boost::iota( w, 0 ); std::stringstream ss; boost::reverse_copy( w, std::ostream_iterator<int>( ss, " " ) ); BOOST_TEST( ss.str() == "3 2 1 0 " ); boost::replace_if( w, []( int i ) { return ( i > 1 ); }, -1 ); BOOST_TEST( w == std::vector<int>( {0, 1, -1, -1} ), tt::per_element() ); BOOST_TEST( boost::count( w, -1 ), 2 ); BOOST_TEST( boost::accumulate( w, 5 ), 4 ); } BOOST_AUTO_TEST_CASE( point_cloud ) { using DataTransferKit::Point; using DataTransferKit::Details::distance; double const seed = 3.14; std::default_random_engine generator( seed ); std::uniform_real_distribution<double> distribution( -1., 1. ); int const n = 10000; Kokkos::View<Point *, Kokkos::HostSpace> cloud( "cloud", n ); boost::generate( cloud, [&distribution, &generator]() { Point p; p[0] = distribution( generator ); p[1] = distribution( generator ); p[2] = distribution( generator ); return p; } ); Point const origin = {0., 0., 0.}; double const radius = 1.; // 4/3 pi 1^3 / 2^3 double const pi = 6. * static_cast<double>( boost::count_if( cloud, [origin, radius]( Point point ) { return ( distance( point, origin ) <= radius ); } ) ) / static_cast<double>( n ); double const relative_tolerance = .05; BOOST_TEST( pi == 3.14, tt::tolerance( relative_tolerance ) ); } <commit_msg>Get rid of last Teuchos header that slipped through the cracks<commit_after>/**************************************************************************** * Copyright (c) 2012-2019 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #include "DTK_BoostRangeAdapters.hpp" #include "DTK_EnableViewComparison.hpp" #include <DTK_Box.hpp> #include <DTK_DetailsAlgorithms.hpp> #include <DTK_Point.hpp> #include <Kokkos_Core.hpp> #include <boost/range/algorithm.hpp> // reverse_copy, replace_if, count, generate, count_if #include <boost/range/algorithm_ext.hpp> // iota #include <boost/range/numeric.hpp> // accumulate #include <boost/test/unit_test.hpp> #include <random> #include <sstream> #define BOOST_TEST_MODULE BoostRangeAdapters namespace tt = boost::test_tools; BOOST_AUTO_TEST_CASE( range_algorithms ) { Kokkos::View<int[4], Kokkos::HostSpace> w( "w" ); boost::iota( w, 0 ); std::stringstream ss; boost::reverse_copy( w, std::ostream_iterator<int>( ss, " " ) ); BOOST_TEST( ss.str() == "3 2 1 0 " ); boost::replace_if( w, []( int i ) { return ( i > 1 ); }, -1 ); BOOST_TEST( w == std::vector<int>( {0, 1, -1, -1} ), tt::per_element() ); BOOST_TEST( boost::count( w, -1 ), 2 ); BOOST_TEST( boost::accumulate( w, 5 ), 4 ); } BOOST_AUTO_TEST_CASE( point_cloud ) { using DataTransferKit::Point; using DataTransferKit::Details::distance; double const seed = 3.14; std::default_random_engine generator( seed ); std::uniform_real_distribution<double> distribution( -1., 1. ); int const n = 10000; Kokkos::View<Point *, Kokkos::HostSpace> cloud( "cloud", n ); boost::generate( cloud, [&distribution, &generator]() { Point p; p[0] = distribution( generator ); p[1] = distribution( generator ); p[2] = distribution( generator ); return p; } ); Point const origin = {0., 0., 0.}; double const radius = 1.; // 4/3 pi 1^3 / 2^3 double const pi = 6. * static_cast<double>( boost::count_if( cloud, [origin, radius]( Point point ) { return ( distance( point, origin ) <= radius ); } ) ) / static_cast<double>( n ); double const relative_tolerance = .05; BOOST_TEST( pi == 3.14, tt::tolerance( relative_tolerance ) ); } <|endoftext|>
<commit_before>#include "setup/scheduler.hpp" #include "setup/interop.hpp" #include <SFML/OpenGL.hpp> #if defined _WIN32 || defined _WIN64 #include <Wingdi.h> #endif static GLuint texture; void interop::initialize(const cl::Device &device, sf::WindowHandle handle) { #if defined _WIN32 || defined _WIN64 cl_context_properties props[] = { CL_GL_CONTEXT_KHR, (cl_context_properties)wglGetCurrentContext(), CL_WGL_HDC_KHR, (cl_context_properties)GetDC(handle), 0 }; scheduler::setup(device, props); #elif defined __linux__ #error "Linux interop support not implemented yet!" #else #error "Platform not supported!" #endif } cl::ImageGL interop::get_image(std::size_t width, std::size_t height) { glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glViewport(0, 0, (GLint)width, (GLint)height); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); return scheduler::alloc_gl_image(CL_MEM_WRITE_ONLY, texture); } void interop::free_image(const cl::ImageGL &/*image*/) { glDeleteTextures(1, &texture); } void interop::draw_image(const cl::ImageGL &/*image*/) { glEnable(GL_TEXTURE_2D); glBegin(GL_QUADS); glTexCoord2d(0, 0); glVertex2d(-1, -1); glTexCoord2d(1, 0); glVertex2d(+1, -1); glTexCoord2d(1, 1); glVertex2d(+1, +1); glTexCoord2d(0, 1); glVertex2d(-1, +1); glEnd(); glDisable(GL_TEXTURE_2D); } <commit_msg>Added tentative interop support for Linux<commit_after>#include "setup/scheduler.hpp" #include "setup/interop.hpp" #include <SFML/OpenGL.hpp> #if defined _WIN32 || defined _WIN64 #include <Wingdi.h> #elif defined __linux__ #include <GL/glx.h> #endif static GLuint texture; void interop::initialize(const cl::Device &device, sf::WindowHandle handle) { #if defined _WIN32 || defined _WIN64 cl_context_properties props[] = { CL_GL_CONTEXT_KHR, (cl_context_properties)wglGetCurrentContext(), CL_WGL_HDC_KHR, (cl_context_properties)GetDC(handle), 0 }; scheduler::setup(device, props); #elif defined __linux__ cl_context_properties props[] = { CL_GL_CONTEXT_KHR,(cl_context_properties)glXGetCurrentContext(), CL_GLX_DISPLAY_KHR, (cl_context_properties)glXGetCurrentDisplay(), 0 }; scheduler::setup(device, props); #else #error "Interop not supported for your platform!" #endif } cl::ImageGL interop::get_image(std::size_t width, std::size_t height) { glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glViewport(0, 0, (GLint)width, (GLint)height); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); return scheduler::alloc_gl_image(CL_MEM_WRITE_ONLY, texture); } void interop::free_image(const cl::ImageGL &/*image*/) { glDeleteTextures(1, &texture); } void interop::draw_image(const cl::ImageGL &/*image*/) { glEnable(GL_TEXTURE_2D); glBegin(GL_QUADS); glTexCoord2d(0, 0); glVertex2d(-1, -1); glTexCoord2d(1, 0); glVertex2d(+1, -1); glTexCoord2d(1, 1); glVertex2d(+1, +1); glTexCoord2d(0, 1); glVertex2d(-1, +1); glEnd(); glDisable(GL_TEXTURE_2D); } <|endoftext|>
<commit_before><commit_msg>Delete test2.cpp<commit_after><|endoftext|>