text
stringlengths
54
60.6k
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: drviewsh.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: kz $ $Date: 2008-04-03 15:18:57 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "DrawViewShell.hxx" #ifndef _AEITEM_HXX //autogen #include <svtools/aeitem.hxx> #endif #ifndef _SFXITEMSET_HXX //autogen #include <svtools/itemset.hxx> #endif #ifndef _SFXREQUEST_HXX //autogen #include <sfx2/request.hxx> #endif #ifndef _SVXIDS_HRC #include <svx/svxids.hrc> #endif #ifndef _SVX_FMSHELL_HXX // XXX nur temp (dg) #include <svx/fmshell.hxx> #endif #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #include "app.hrc" #include "strings.hrc" #include "sdpage.hxx" #ifndef SD_FRAME_VIEW #include "FrameView.hxx" #endif #include "sdresid.hxx" #include "drawdoc.hxx" #include "DrawDocShell.hxx" #ifndef SD_WINDOW_HXX #include "Window.hxx" #endif #ifndef SD_GRAPHIC_VIEW_SHELL_HXX #include "GraphicViewShell.hxx" #endif #ifndef SD_DRAW_VIEW_HXX #include "drawview.hxx" #endif #include "slideshow.hxx" namespace sd { #define TABCONTROL_INITIAL_SIZE 500 /************************************************************************* |* |* Sprung zu Bookmark |* \************************************************************************/ BOOL DrawViewShell::GotoBookmark(const String& rBookmark) { BOOL bRet = FALSE; ::sd::DrawDocShell* pDocSh = GetDocSh(); if( pDocSh ) { if( !pDocSh->GetViewShell() ) //#i26016# this case occurs if the jump-target-document was opened already with file open dialog before triggering the jump via hyperlink pDocSh->Connect(this); bRet = (pDocSh->GotoBookmark(rBookmark)); } return bRet; } /************************************************************************* |* |* Bereich sichtbar machen (Bildausschnitt scrollen) |* \************************************************************************/ void DrawViewShell::MakeVisible(const Rectangle& rRect, ::Window& rWin) { // #98568# In older versions, if in X or Y the size of the object was // smaller than the visible area, the user-defined zoom was // changed. This was decided to be a bug for 6.x, thus I developed a // version which instead handles X/Y bigger/smaller and visibility // questions seperately. The new behaviour is triggered with the // bZoomAllowed parameter which for old behaviour should be set to // sal_True. I looked at all uses of MakeVisible() in the application // and found no valid reason for really changing the zoom factor, thus I // decided to NOT expand (incompatible) this virtual method to get one // more parameter. If this is wanted in later versions, feel free to add // that bool to the parameter list. sal_Bool bZoomAllowed(sal_False); Size aLogicSize(rRect.GetSize()); // Sichtbarer Bereich Size aVisSizePixel(rWin.GetOutputSizePixel()); Rectangle aVisArea(rWin.PixelToLogic(Rectangle(Point(0,0), aVisSizePixel))); Size aVisAreaSize(aVisArea.GetSize()); if(!aVisArea.IsInside(rRect) && !SlideShow::IsRunning( GetViewShellBase() ) ) { // Objekt liegt nicht komplett im sichtbaren Bereich sal_Int32 nFreeSpaceX(aVisAreaSize.Width() - aLogicSize.Width()); sal_Int32 nFreeSpaceY(aVisAreaSize.Height() - aLogicSize.Height()); if(bZoomAllowed && (nFreeSpaceX < 0 || nFreeSpaceY < 0)) { // Objekt passt nicht in sichtbaren Bereich -> auf Objektgroesse zoomen SetZoomRect(rRect); } else { // #98568# allow a mode for move-only visibility without zooming. const sal_Int32 nPercentBorder(30); const Rectangle aInnerRectangle( aVisArea.Left() + ((aVisAreaSize.Width() * nPercentBorder) / 200), aVisArea.Top() + ((aVisAreaSize.Height() * nPercentBorder) / 200), aVisArea.Right() - ((aVisAreaSize.Width() * nPercentBorder) / 200), aVisArea.Bottom() - ((aVisAreaSize.Height() * nPercentBorder) / 200) ); Point aNewPos(aVisArea.TopLeft()); if(nFreeSpaceX < 0) { if(aInnerRectangle.Left() > rRect.Right()) { // object moves out to the left aNewPos.X() -= aVisAreaSize.Width() / 2; } if(aInnerRectangle.Right() < rRect.Left()) { // object moves out to the right aNewPos.X() += aVisAreaSize.Width() / 2; } } else { if(nFreeSpaceX > rRect.GetWidth()) nFreeSpaceX = rRect.GetWidth(); while(rRect.Right() > aNewPos.X() + aVisAreaSize.Width()) aNewPos.X() += nFreeSpaceX; while(rRect.Left() < aNewPos.X()) aNewPos.X() -= nFreeSpaceX; } if(nFreeSpaceY < 0) { if(aInnerRectangle.Top() > rRect.Bottom()) { // object moves out to the top aNewPos.Y() -= aVisAreaSize.Height() / 2; } if(aInnerRectangle.Bottom() < rRect.Top()) { // object moves out to the right aNewPos.Y() += aVisAreaSize.Height() / 2; } } else { if(nFreeSpaceY > rRect.GetHeight()) nFreeSpaceY = rRect.GetHeight(); while(rRect.Bottom() > aNewPos.Y() + aVisAreaSize.Height()) aNewPos.Y() += nFreeSpaceY; while(rRect.Top() < aNewPos.Y()) aNewPos.Y() -= nFreeSpaceY; } // did position change? Does it need to be set? if(aNewPos != aVisArea.TopLeft()) { aVisArea.SetPos(aNewPos); SetZoomRect(aVisArea); } } } } } <commit_msg>INTEGRATION: CWS changefileheader (1.10.358); FILE MERGED 2008/04/01 15:36:33 thb 1.10.358.3: #i85898# Stripping all external header guards 2008/04/01 12:39:40 thb 1.10.358.2: #i85898# Stripping all external header guards 2008/03/31 13:59:13 rt 1.10.358.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: drviewsh.cxx,v $ * $Revision: 1.12 $ * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "DrawViewShell.hxx" #include <svtools/aeitem.hxx> #include <svtools/itemset.hxx> #include <sfx2/request.hxx> #ifndef _SVXIDS_HRC #include <svx/svxids.hrc> #endif #include <svx/fmshell.hxx> #include <sfx2/dispatch.hxx> #include "app.hrc" #include "strings.hrc" #include "sdpage.hxx" #ifndef SD_FRAME_VIEW #include "FrameView.hxx" #endif #include "sdresid.hxx" #include "drawdoc.hxx" #include "DrawDocShell.hxx" #include "Window.hxx" #include "GraphicViewShell.hxx" #include "drawview.hxx" #include "slideshow.hxx" namespace sd { #define TABCONTROL_INITIAL_SIZE 500 /************************************************************************* |* |* Sprung zu Bookmark |* \************************************************************************/ BOOL DrawViewShell::GotoBookmark(const String& rBookmark) { BOOL bRet = FALSE; ::sd::DrawDocShell* pDocSh = GetDocSh(); if( pDocSh ) { if( !pDocSh->GetViewShell() ) //#i26016# this case occurs if the jump-target-document was opened already with file open dialog before triggering the jump via hyperlink pDocSh->Connect(this); bRet = (pDocSh->GotoBookmark(rBookmark)); } return bRet; } /************************************************************************* |* |* Bereich sichtbar machen (Bildausschnitt scrollen) |* \************************************************************************/ void DrawViewShell::MakeVisible(const Rectangle& rRect, ::Window& rWin) { // #98568# In older versions, if in X or Y the size of the object was // smaller than the visible area, the user-defined zoom was // changed. This was decided to be a bug for 6.x, thus I developed a // version which instead handles X/Y bigger/smaller and visibility // questions seperately. The new behaviour is triggered with the // bZoomAllowed parameter which for old behaviour should be set to // sal_True. I looked at all uses of MakeVisible() in the application // and found no valid reason for really changing the zoom factor, thus I // decided to NOT expand (incompatible) this virtual method to get one // more parameter. If this is wanted in later versions, feel free to add // that bool to the parameter list. sal_Bool bZoomAllowed(sal_False); Size aLogicSize(rRect.GetSize()); // Sichtbarer Bereich Size aVisSizePixel(rWin.GetOutputSizePixel()); Rectangle aVisArea(rWin.PixelToLogic(Rectangle(Point(0,0), aVisSizePixel))); Size aVisAreaSize(aVisArea.GetSize()); if(!aVisArea.IsInside(rRect) && !SlideShow::IsRunning( GetViewShellBase() ) ) { // Objekt liegt nicht komplett im sichtbaren Bereich sal_Int32 nFreeSpaceX(aVisAreaSize.Width() - aLogicSize.Width()); sal_Int32 nFreeSpaceY(aVisAreaSize.Height() - aLogicSize.Height()); if(bZoomAllowed && (nFreeSpaceX < 0 || nFreeSpaceY < 0)) { // Objekt passt nicht in sichtbaren Bereich -> auf Objektgroesse zoomen SetZoomRect(rRect); } else { // #98568# allow a mode for move-only visibility without zooming. const sal_Int32 nPercentBorder(30); const Rectangle aInnerRectangle( aVisArea.Left() + ((aVisAreaSize.Width() * nPercentBorder) / 200), aVisArea.Top() + ((aVisAreaSize.Height() * nPercentBorder) / 200), aVisArea.Right() - ((aVisAreaSize.Width() * nPercentBorder) / 200), aVisArea.Bottom() - ((aVisAreaSize.Height() * nPercentBorder) / 200) ); Point aNewPos(aVisArea.TopLeft()); if(nFreeSpaceX < 0) { if(aInnerRectangle.Left() > rRect.Right()) { // object moves out to the left aNewPos.X() -= aVisAreaSize.Width() / 2; } if(aInnerRectangle.Right() < rRect.Left()) { // object moves out to the right aNewPos.X() += aVisAreaSize.Width() / 2; } } else { if(nFreeSpaceX > rRect.GetWidth()) nFreeSpaceX = rRect.GetWidth(); while(rRect.Right() > aNewPos.X() + aVisAreaSize.Width()) aNewPos.X() += nFreeSpaceX; while(rRect.Left() < aNewPos.X()) aNewPos.X() -= nFreeSpaceX; } if(nFreeSpaceY < 0) { if(aInnerRectangle.Top() > rRect.Bottom()) { // object moves out to the top aNewPos.Y() -= aVisAreaSize.Height() / 2; } if(aInnerRectangle.Bottom() < rRect.Top()) { // object moves out to the right aNewPos.Y() += aVisAreaSize.Height() / 2; } } else { if(nFreeSpaceY > rRect.GetHeight()) nFreeSpaceY = rRect.GetHeight(); while(rRect.Bottom() > aNewPos.Y() + aVisAreaSize.Height()) aNewPos.Y() += nFreeSpaceY; while(rRect.Top() < aNewPos.Y()) aNewPos.Y() -= nFreeSpaceY; } // did position change? Does it need to be set? if(aNewPos != aVisArea.TopLeft()) { aVisArea.SetPos(aNewPos); SetZoomRect(aVisArea); } } } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: showview.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2004-05-10 14:37:34 $ * * 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 "showview.hxx" #ifndef _SVDMODEL_HXX //autogen #include <svx/svdmodel.hxx> #endif #ifndef _SVX_FMVIEW_HXX #include <svx/fmview.hxx> #endif #pragma hdrstop #include "drawdoc.hxx" #include "sdpage.hxx" #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #ifndef SD_FRAME_VIEW_HXX #include "FrameView.hxx" #endif namespace sd { #ifndef SO2_DECL_SVINPLACEOBJECT_DEFINED #define SO2_DECL_SVINPLACEOBJECT_DEFINED SO2_DECL_REF(SvInPlaceObject) #endif #ifndef SO2_DECL_SVINPLACECLIENT_DEFINED #define SO2_DECL_SVINPLACECLIENT_DEFINED SO2_DECL_REF(SvInPlaceClient) #endif /************************************************************************* |* |* der Konstruktor setzt den MapMode und arrangiert die einzelnen Seiten |* \************************************************************************/ ShowView::ShowView ( SdDrawDocument* pDoc, OutputDevice* pOut, ViewShell* pViewShell, ::Window* pWin) : FmFormView(pDoc, pOut), pDrDoc(pDoc), pViewSh(pViewShell), pWindowForPlugIns(pWin), nAllowInvalidateSmph(0), bAllowMasterPageCaching(TRUE) { // #114898# SetBufferedOutputAllowed(sal_True); EnableExtendedKeyInputDispatcher(FALSE); EnableExtendedMouseEventDispatcher(FALSE); EnableExtendedCommandEventDispatcher(FALSE); } /************************************************************************* |* |* Destruktor |* \************************************************************************/ ShowView::~ShowView() { } /************************************************************************* |* |* Zaehler fuer Invalidierungserlaubnis hoch- oder runter zaehlen |* \************************************************************************/ void ShowView::SetAllowInvalidate(BOOL bFlag) { if (!bFlag) { nAllowInvalidateSmph++; } else if (nAllowInvalidateSmph > 0) { nAllowInvalidateSmph--; } } /************************************************************************* |* |* ermittelt, ob invalidiert werden darf |* \************************************************************************/ BOOL ShowView::IsInvalidateAllowed() const { return (nAllowInvalidateSmph == 0); } /************************************************************************* |* |* Invalidate abfangen |* \************************************************************************/ void ShowView::InvalidateOneWin (::Window& rWin) { if (IsInvalidateAllowed()) { FmFormView::InvalidateOneWin(rWin); } } /************************************************************************* |* |* Invalidate abfangen |* \************************************************************************/ void ShowView::InvalidateOneWin (::Window& rWin, const Rectangle& rRect) { if (IsInvalidateAllowed()) { FmFormView::InvalidateOneWin(rWin, rRect); } } /************************************************************************* |* |* Paint-Methode: das Ereignis wird an die View weitergeleitet |* \************************************************************************/ void ShowView::InitRedraw(OutputDevice* pOutDev, const Region& rReg, const Link* pPaintProc /*=NULL*/) { // #110094#-7 // BOOL bMPCache = FALSE; // if (bAllowMasterPageCaching && pViewSh && // pViewSh == (ViewShell*) SfxViewShell::Current() && // pViewSh->GetFrameView()->IsMasterPagePaintCaching() && // pOutDev->GetOutDevType() != OUTDEV_PRINTER) // { // // Aktive ViewShell: Caching einschalten // bMPCache = TRUE; // } // if (bMPCache) // { // if (!IsMasterPagePaintCaching()) // { // SetMasterPagePaintCaching(TRUE); // } // } // else // { // if (IsMasterPagePaintCaching()) // { // ReleaseMasterPagePaintCache(); // SetMasterPagePaintCaching(FALSE); // } // } FmFormView::InitRedraw(pOutDev, rReg, SDRPAINTMODE_ANILIKEPRN, pPaintProc); } /************************************************************************* |* |* DoConnect |* \************************************************************************/ void ShowView::DoConnect(SdrOle2Obj* pOleObj) { // connected wird jetzt in FuSlideShow::ShowPlugIns() } } // end of namespace sd <commit_msg>INTEGRATION: CWS aw013 (1.6.34); FILE MERGED 2004/06/15 16:25:30 aw 1.6.34.2: #117095# 2004/06/11 16:14:48 aw 1.6.34.1: #114389#, #114394#<commit_after>/************************************************************************* * * $RCSfile: showview.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2004-07-12 15:23:30 $ * * 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 "showview.hxx" #ifndef _SVDMODEL_HXX //autogen #include <svx/svdmodel.hxx> #endif #ifndef _SVX_FMVIEW_HXX #include <svx/fmview.hxx> #endif #pragma hdrstop #include "drawdoc.hxx" #include "sdpage.hxx" #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #ifndef SD_FRAME_VIEW_HXX #include "FrameView.hxx" #endif namespace sd { #ifndef SO2_DECL_SVINPLACEOBJECT_DEFINED #define SO2_DECL_SVINPLACEOBJECT_DEFINED SO2_DECL_REF(SvInPlaceObject) #endif #ifndef SO2_DECL_SVINPLACECLIENT_DEFINED #define SO2_DECL_SVINPLACECLIENT_DEFINED SO2_DECL_REF(SvInPlaceClient) #endif /************************************************************************* |* |* der Konstruktor setzt den MapMode und arrangiert die einzelnen Seiten |* \************************************************************************/ ShowView::ShowView ( SdDrawDocument* pDoc, OutputDevice* pOut, ViewShell* pViewShell, ::Window* pWin) : FmFormView(pDoc, pOut), pDrDoc(pDoc), pViewSh(pViewShell), pWindowForPlugIns(pWin), nAllowInvalidateSmph(0), bAllowMasterPageCaching(TRUE) { // #114898# SetBufferedOutputAllowed(sal_True); EnableExtendedKeyInputDispatcher(FALSE); EnableExtendedMouseEventDispatcher(FALSE); EnableExtendedCommandEventDispatcher(FALSE); } /************************************************************************* |* |* Destruktor |* \************************************************************************/ ShowView::~ShowView() { } /************************************************************************* |* |* Zaehler fuer Invalidierungserlaubnis hoch- oder runter zaehlen |* \************************************************************************/ void ShowView::SetAllowInvalidate(BOOL bFlag) { if (!bFlag) { nAllowInvalidateSmph++; } else if (nAllowInvalidateSmph > 0) { nAllowInvalidateSmph--; } } /************************************************************************* |* |* ermittelt, ob invalidiert werden darf |* \************************************************************************/ BOOL ShowView::IsInvalidateAllowed() const { return (nAllowInvalidateSmph == 0); } /************************************************************************* |* |* Invalidate abfangen |* \************************************************************************/ void ShowView::InvalidateOneWin (::Window& rWin) { if (IsInvalidateAllowed()) { FmFormView::InvalidateOneWin(rWin); } } /************************************************************************* |* |* Invalidate abfangen |* \************************************************************************/ void ShowView::InvalidateOneWin (::Window& rWin, const Rectangle& rRect) { if (IsInvalidateAllowed()) { FmFormView::InvalidateOneWin(rWin, rRect); } } /************************************************************************* |* |* Paint-Methode: das Ereignis wird an die View weitergeleitet |* \************************************************************************/ void ShowView::CompleteRedraw(OutputDevice* pOutDev, const Region& rReg, ::sdr::contact::ViewObjectContactRedirector* pRedirector /*=0L*/) { // #110094#-7 // BOOL bMPCache = FALSE; // if (bAllowMasterPageCaching && pViewSh && // pViewSh == (ViewShell*) SfxViewShell::Current() && // pViewSh->GetFrameView()->IsMasterPagePaintCaching() && // pOutDev->GetOutDevType() != OUTDEV_PRINTER) // { // // Aktive ViewShell: Caching einschalten // bMPCache = TRUE; // } // if (bMPCache) // { // if (!IsMasterPagePaintCaching()) // { // SetMasterPagePaintCaching(TRUE); // } // } // else // { // if (IsMasterPagePaintCaching()) // { // ReleaseMasterPagePaintCache(); // SetMasterPagePaintCaching(FALSE); // } // } FmFormView::CompleteRedraw(pOutDev, rReg, SDRPAINTMODE_ANILIKEPRN, pRedirector); } /************************************************************************* |* |* DoConnect |* \************************************************************************/ void ShowView::DoConnect(SdrOle2Obj* pOleObj) { // connected wird jetzt in FuSlideShow::ShowPlugIns() } } // end of namespace sd <|endoftext|>
<commit_before>#include "cinder/app/AppNative.h" #include "cinder/gl/gl.h" using namespace ci; using namespace ci::app; using namespace std; class RetinaSampleApp : public AppNative { public: void prepareSettings( Settings *settings ) override; void setup(); void mouseDrag( MouseEvent event ); void keyDown( KeyEvent event ); void displayChange(); void draw(); // This will maintain a list of points which we will draw line segments between list<Vec2f> mPoints; }; void RetinaSampleApp::prepareSettings( Settings *settings ) { settings->enableHighDensityDisplay(); console() << "settings->getHighDensityDisplayEnabled()= " << settings->isHighDensityDisplayEnabled() << endl; } void RetinaSampleApp::setup() { getWindow()->getSignalDisplayChange().connect( std::bind( &RetinaSampleApp::displayChange, this ) ); } void RetinaSampleApp::mouseDrag( MouseEvent event ) { mPoints.push_back( event.getPos() ); } void RetinaSampleApp::keyDown( KeyEvent event ) { if( event.getChar() == 'f' ) setFullScreen( ! isFullScreen() ); } void RetinaSampleApp::displayChange() { console() << "Window display changed: " << getWindow()->getDisplay()->getBounds() << std::endl; console() << "ContentScale = " << getWindowContentScale() << endl; console() << "getWindowCenter() = " << getWindowCenter() << endl; console() << "getWindow()->toPixels( 1.0f ) = " << toPixels( 1.0f ) << endl; } void RetinaSampleApp::draw() { gl::clear( Color( 0.1f, 0.1f, 0.15f ) ); gl::color( 1.0f, 0.5f, 0.25f ); gl::pushMatrices(); glLineWidth( getWindow()->toPixels( 1.0f ) ); gl::begin( GL_LINE_STRIP ); for( auto pointIter = mPoints.begin(); pointIter != mPoints.end(); ++pointIter ) { gl::vertex( *pointIter ); } gl::end(); gl::popMatrices(); gl::pushMatrices(); glColor3f( 1.0f, 0.2f, 0.15f ); gl::translate( getWindowCenter() ); gl::rotate( getElapsedSeconds() * 5 ); gl::drawSolidRect( Rectf( Area( -100, -100, 100, 100 ) ) ); gl::popMatrices(); } CINDER_APP_NATIVE( RetinaSampleApp, RendererGl ) <commit_msg>samples/RetinaSample improvements<commit_after>#include "cinder/app/AppNative.h" #include "cinder/gl/gl.h" #include "cinder/gl/Texture.h" using namespace ci; using namespace ci::app; using namespace std; class RetinaSampleApp : public AppNative { public: void prepareSettings( Settings *settings ) override; void setup(); void mouseDrag( MouseEvent event ); void keyDown( KeyEvent event ); void displayChange(); void draw(); // This will maintain a list of points which we will draw line segments between list<Vec2f> mPoints; gl::Texture mLogo; }; void RetinaSampleApp::prepareSettings( Settings *settings ) { settings->enableHighDensityDisplay(); } void RetinaSampleApp::setup() { // this should have mipmapping enabled in a real app but leaving it disabled // helps us see the change in going from Retina to non-Retina mLogo = loadImage( loadResource( "CinderApp.icns" ) ); getWindow()->getSignalDisplayChange().connect( std::bind( &RetinaSampleApp::displayChange, this ) ); } void RetinaSampleApp::mouseDrag( MouseEvent event ) { mPoints.push_back( event.getPos() ); } void RetinaSampleApp::keyDown( KeyEvent event ) { if( event.getChar() == 'f' ) setFullScreen( ! isFullScreen() ); } void RetinaSampleApp::displayChange() { console() << "Window display changed: " << getWindow()->getDisplay()->getBounds() << std::endl; console() << "ContentScale = " << getWindowContentScale() << endl; console() << "getWindowCenter() = " << getWindowCenter() << endl; console() << "toPixels( 1.0f ) = " << toPixels( 1.0f ) << endl; } void RetinaSampleApp::draw() { gl::clear( Color( 0.1f, 0.1f, 0.15f ) ); gl::enableAlphaBlending(); gl::pushMatrices(); gl::color( 1.0f, 0.5f, 0.25f ); glLineWidth( getWindow()->toPixels( 1.0f ) ); gl::begin( GL_LINE_STRIP ); for( auto pointIter = mPoints.begin(); pointIter != mPoints.end(); ++pointIter ) { gl::vertex( *pointIter ); } gl::end(); gl::popMatrices(); gl::pushMatrices(); gl::color( 1.0f, 0.2f, 0.15f ); gl::translate( getWindowCenter() ); gl::rotate( getElapsedSeconds() * 5 ); gl::drawSolidRect( Rectf( Area( -100, -100, 100, 100 ) ) ); gl::popMatrices(); // draw the logo in the lower-left corner gl::color( Color::white() ); gl::draw( mLogo, Rectf( 0, getWindowHeight() - 64, 64, getWindowHeight() ) ); } CINDER_APP_NATIVE( RetinaSampleApp, RendererGl ) <|endoftext|>
<commit_before>/* * Copyright (c) 2016, Nils Asmussen * All rights reserved. * * Redistribution and use in source and binary forms, with or without * * 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. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of the FreeBSD Project. */ #include "cpu/dtu-accel/syscallsm.hh" std::string SyscallSM::stateName() const { const char *names[] = { "SEND", "WAIT", "FETCH", "READ_ADDR", "ACK" }; return names[static_cast<size_t>(state)]; } PacketPtr SyscallSM::tick() { PacketPtr pkt = nullptr; switch(state) { case State::SYSC_SEND: { pkt = accel->createDtuCmdPkt(Dtu::Command::SEND, DtuAccel::EP_SYSS, accel->sendMsgAddr(), syscallSize, DtuAccel::EP_SYSR); break; } case State::SYSC_WAIT: { Addr regAddr = accel->getRegAddr(CmdReg::COMMAND); pkt = accel->createDtuRegPkt(regAddr, 0, MemCmd::ReadReq); break; } case State::SYSC_FETCH: { Addr regAddr = accel->getRegAddr(CmdReg::COMMAND); uint64_t value = Dtu::Command::FETCH_MSG | (DtuAccel::EP_SYSR << 4); pkt = accel->createDtuRegPkt(regAddr, value, MemCmd::WriteReq); break; } case State::SYSC_READ_ADDR: { Addr regAddr = accel->getRegAddr(CmdReg::OFFSET); pkt = accel->createDtuRegPkt(regAddr, 0, MemCmd::ReadReq); break; } case State::SYSC_ACK: { pkt = accel->createDtuCmdPkt(Dtu::Command::ACK_MSG, DtuAccel::EP_SYSR, 0, 0, replyAddr); break; } } return pkt; } bool SyscallSM::handleMemResp(PacketPtr pkt) { auto lastState = state; switch(state) { case State::SYSC_SEND: { state = State::SYSC_WAIT; break; } case State::SYSC_WAIT: { RegFile::reg_t reg = *pkt->getConstPtr<RegFile::reg_t>(); if ((reg & 0xF) == 0) { if (!waitForReply) return true; state = State::SYSC_FETCH; } break; } case State::SYSC_FETCH: { state = State::SYSC_READ_ADDR; break; } case State::SYSC_READ_ADDR: { const RegFile::reg_t *regs = pkt->getConstPtr<RegFile::reg_t>(); if(regs[0]) { replyAddr = regs[0]; state = State::SYSC_ACK; } else state = State::SYSC_FETCH; break; } case State::SYSC_ACK: { return true; } } stateChanged = state != lastState; return false; } <commit_msg>DtuAccel: don't wait for sysc replies on errors.<commit_after>/* * Copyright (c) 2016, Nils Asmussen * All rights reserved. * * Redistribution and use in source and binary forms, with or without * * 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. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of the FreeBSD Project. */ #include "cpu/dtu-accel/syscallsm.hh" std::string SyscallSM::stateName() const { const char *names[] = { "SEND", "WAIT", "FETCH", "READ_ADDR", "ACK" }; return names[static_cast<size_t>(state)]; } PacketPtr SyscallSM::tick() { PacketPtr pkt = nullptr; switch(state) { case State::SYSC_SEND: { pkt = accel->createDtuCmdPkt(Dtu::Command::SEND, DtuAccel::EP_SYSS, accel->sendMsgAddr(), syscallSize, DtuAccel::EP_SYSR); break; } case State::SYSC_WAIT: { Addr regAddr = accel->getRegAddr(CmdReg::COMMAND); pkt = accel->createDtuRegPkt(regAddr, 0, MemCmd::ReadReq); break; } case State::SYSC_FETCH: { Addr regAddr = accel->getRegAddr(CmdReg::COMMAND); uint64_t value = Dtu::Command::FETCH_MSG | (DtuAccel::EP_SYSR << 4); pkt = accel->createDtuRegPkt(regAddr, value, MemCmd::WriteReq); break; } case State::SYSC_READ_ADDR: { Addr regAddr = accel->getRegAddr(CmdReg::OFFSET); pkt = accel->createDtuRegPkt(regAddr, 0, MemCmd::ReadReq); break; } case State::SYSC_ACK: { pkt = accel->createDtuCmdPkt(Dtu::Command::ACK_MSG, DtuAccel::EP_SYSR, 0, 0, replyAddr); break; } } return pkt; } bool SyscallSM::handleMemResp(PacketPtr pkt) { auto lastState = state; switch(state) { case State::SYSC_SEND: { state = State::SYSC_WAIT; break; } case State::SYSC_WAIT: { auto data = pkt->getConstPtr<RegFile::reg_t>(); Dtu::Command::Bits cmd = *reinterpret_cast<const RegFile::reg_t*>(data); if (cmd.opcode == 0) { auto err = static_cast<Dtu::Error>((long)cmd.error); if (!waitForReply || err != Dtu::Error::NONE) return true; state = State::SYSC_FETCH; } break; } case State::SYSC_FETCH: { state = State::SYSC_READ_ADDR; break; } case State::SYSC_READ_ADDR: { const RegFile::reg_t *regs = pkt->getConstPtr<RegFile::reg_t>(); if(regs[0]) { replyAddr = regs[0]; state = State::SYSC_ACK; } else state = State::SYSC_FETCH; break; } case State::SYSC_ACK: { return true; } } stateChanged = state != lastState; return false; } <|endoftext|>
<commit_before>#include <chrono> #include <random> #include <array> #include <opencv2/core/core.hpp> #include <opencv2/ocl/ocl.hpp> #include "opencl.hpp" #include "utility.hpp" #include "hog.pencil.h" #include "HogDescriptor.h" #include "hog.clh" void time_hog( const std::vector<carp::record_t>& pool, const std::vector<float>& sizes, int num_positions, int repeat ) { carp::Timing timing("HOG"); for (;repeat>0; --repeat) { for ( auto & size : sizes ) { for ( auto & item : pool ) { std::mt19937 rng(0); //uses same seed, reseed for all iteration cv::Mat cpu_gray; cv::cvtColor( item.cpuimg(), cpu_gray, CV_RGB2GRAY ); static_assert(sizeof(float[2]) == sizeof(std::array<float,2>), "This code needs std::array to behave exactly like C arrays."); std::vector<std::array<float,2>> locations; std::uniform_real_distribution<float> genx(size/2+1, cpu_gray.rows-1-size/2-1); std::uniform_real_distribution<float> geny(size/2+1, cpu_gray.cols-1-size/2-1); std::generate_n(std::back_inserter(locations), num_positions, [&](){ return std::array<float,2>{{ genx(rng), geny(rng) }}; }); std::vector<float> cpu_result(num_positions * HISTOGRAM_BINS), gpu_result(num_positions * HISTOGRAM_BINS), pen_result(num_positions * HISTOGRAM_BINS); std::chrono::duration<double> elapsed_time_cpu, elapsed_time_gpu_p_copy, elapsed_time_gpu_nocopy, elapsed_time_pencil; { //CPU implement const auto cpu_start = std::chrono::high_resolution_clock::now(); auto result = nel::HOGDescriptor< NUMBER_OF_CELLS , NUMBER_OF_BINS , GAUSSIAN_WEIGHTS , SPARTIAL_WEIGHTS , SIGNED_HOG >::compute(cpu_gray, locations, size); const auto cpu_end = std::chrono::high_resolution_clock::now(); std::copy(result.begin(), result.end(), cpu_result.begin()); elapsed_time_cpu = cpu_end - cpu_start; //Free up resources } { carp::opencl::device device; size_t max_work_group_size; cl_int err; err = clGetDeviceInfo( device.get_device_id() , CL_DEVICE_MAX_WORK_GROUP_SIZE , sizeof(size_t) , &max_work_group_size , nullptr ); const int work_size_locations = 64; const int work_size_x = pow(2, std::ceil(std::log2(max_work_group_size / work_size_locations)/2)); //The square root of the max size/locations, rounded up to power-of-two const int work_size_y = max_work_group_size / work_size_locations / work_size_x; if (err != CL_SUCCESS) throw std::runtime_error("Cannot query max work group size."); const auto gpu_compile_start = std::chrono::high_resolution_clock::now(); device.source_compile( hog_opencl_cl, hog_opencl_cl_len, {"calc_histogram", "fill_zeros"} ); const auto gpu_copy_start = std::chrono::high_resolution_clock::now(); cl_mem gpu_gray = clCreateBuffer( device.get_context() , CL_MEM_READ_ONLY|CL_MEM_COPY_HOST_PTR , cpu_gray.elemSize()*cpu_gray.rows*cpu_gray.step1() , cpu_gray.data , &err ); if (err != CL_SUCCESS) throw std::runtime_error("Cannot copy source image to GPU."); cl_mem gpu_locations = clCreateBuffer( device.get_context() , CL_MEM_READ_ONLY|CL_MEM_COPY_HOST_PTR , sizeof(float[2])*num_positions , locations.data() , &err ); if (err != CL_SUCCESS) throw std::runtime_error("Cannot copy locations array to GPU."); cl_mem gpu_hist = clCreateBuffer(device.get_context(), CL_MEM_WRITE_ONLY, sizeof(cl_float)*HISTOGRAM_BINS*num_positions, nullptr, &err); if (err != CL_SUCCESS) throw std::runtime_error("Cannot allocate histogram array."); device["fill_zeros"](gpu_hist, HISTOGRAM_BINS*num_positions).groupsize({std::min<size_t>(max_work_group_size, HISTOGRAM_BINS*num_positions)}, {HISTOGRAM_BINS*num_positions}); const auto gpu_start = std::chrono::high_resolution_clock::now(); device["calc_histogram"]( cpu_gray.rows , cpu_gray.cols , (int)cpu_gray.step1() , gpu_gray , num_positions , gpu_locations , size , gpu_hist , carp::opencl::buffer(sizeof(cl_float)*HISTOGRAM_BINS*num_positions) ).groupsize({work_size_locations,work_size_x,work_size_y}, {num_positions, (int)ceil(size), (int)ceil(size)}); const auto gpu_end = std::chrono::high_resolution_clock::now(); err = clEnqueueReadBuffer(device.get_queue(), gpu_hist, CL_TRUE, 0, sizeof(cl_float)*HISTOGRAM_BINS*num_positions, gpu_result.data(), 0, nullptr, nullptr); if (err != CL_SUCCESS) throw std::runtime_error("Cannot copy histogram array to host."); err = clReleaseMemObject(gpu_hist); if (err != CL_SUCCESS) throw std::runtime_error("Cannot free histogram array."); err = clReleaseMemObject(gpu_locations); if (err != CL_SUCCESS) throw std::runtime_error("Cannot free gpu_locations array."); err = clReleaseMemObject(gpu_gray); if (err != CL_SUCCESS) throw std::runtime_error("Cannot free gpu_image array."); const auto gpu_copy_end = std::chrono::high_resolution_clock::now(); const auto gpu_compile_end = std::chrono::high_resolution_clock::now(); elapsed_time_gpu_p_copy = gpu_copy_end - gpu_copy_start; elapsed_time_gpu_nocopy = gpu_end - gpu_start; auto elapsed_time_gpu_compile = gpu_compile_end - gpu_compile_start; //Free up resources } { pen_result.resize(num_positions * HISTOGRAM_BINS, 0.0f); const auto pencil_start = std::chrono::high_resolution_clock::now(); pencil_hog( cpu_gray.rows, cpu_gray.cols, cpu_gray.step1(), cpu_gray.ptr<uint8_t>() , num_positions, reinterpret_cast<const float (*)[2]>(locations.data()) , size , pen_result.data() ); const auto pencil_end = std::chrono::high_resolution_clock::now(); elapsed_time_pencil = pencil_end - pencil_start; //Free up resources } // Verifying the results if ( cv::norm( cpu_result, gpu_result, cv::NORM_INF) > cv::norm( gpu_result, cv::NORM_INF)*1e-5 || cv::norm( cpu_result, pen_result, cv::NORM_INF) > cv::norm( cpu_result, cv::NORM_INF)*1e-5 ) { std::vector<float> diff; std::transform(cpu_result.begin(), cpu_result.end(), gpu_result.begin(), std::back_inserter(diff), std::minus<float>()); std::cerr << "ERROR: Results don't match." << std::endl; std::cerr << "CPU norm:" << cv::norm(cpu_result, cv::NORM_INF) << std::endl; std::cerr << "GPU norm:" << cv::norm(gpu_result, cv::NORM_INF) << std::endl; std::cerr << "PEN norm:" << cv::norm(pen_result, cv::NORM_INF) << std::endl; std::cerr << "GPU-CPU norm:" << cv::norm(gpu_result, cpu_result, cv::NORM_INF) << std::endl; std::cerr << "PEN-CPU norm:" << cv::norm(pen_result, cpu_result, cv::NORM_INF) << std::endl; throw std::runtime_error("The OpenCL or PENCIL results are not equivalent with the C++ results."); } timing.print( elapsed_time_cpu, elapsed_time_gpu_p_copy, elapsed_time_gpu_nocopy, elapsed_time_pencil ); } } } } int main(int argc, char* argv[]) { try { std::cout << "This executable is iterating over all the files which are present in the directory `./pool'. " << std::endl; auto pool = carp::get_pool("pool"); #ifdef RUN_ONLY_ONE_EXPERIMENT time_hog( pool, {64}, 50, 1 ); #else time_hog( pool, {16, 32, 64, 128, 192}, 50, 10 ); #endif return EXIT_SUCCESS; }catch(const std::exception& e) { std::cout << e.what() << std::endl; return EXIT_FAILURE; } } // main <commit_msg>Tune work group sizes more.<commit_after>#include <chrono> #include <random> #include <array> #include <opencv2/core/core.hpp> #include <opencv2/ocl/ocl.hpp> #include "opencl.hpp" #include "utility.hpp" #include "hog.pencil.h" #include "HogDescriptor.h" #include "hog.clh" void time_hog( const std::vector<carp::record_t>& pool, const std::vector<float>& sizes, int num_positions, int repeat ) { carp::Timing timing("HOG"); for (;repeat>0; --repeat) { for ( auto & size : sizes ) { for ( auto & item : pool ) { std::mt19937 rng(0); //uses same seed, reseed for all iteration cv::Mat cpu_gray; cv::cvtColor( item.cpuimg(), cpu_gray, CV_RGB2GRAY ); static_assert(sizeof(float[2]) == sizeof(std::array<float,2>), "This code needs std::array to behave exactly like C arrays."); std::vector<std::array<float,2>> locations; std::uniform_real_distribution<float> genx(size/2+1, cpu_gray.rows-1-size/2-1); std::uniform_real_distribution<float> geny(size/2+1, cpu_gray.cols-1-size/2-1); std::generate_n(std::back_inserter(locations), num_positions, [&](){ return std::array<float,2>{{ genx(rng), geny(rng) }}; }); std::vector<float> cpu_result(num_positions * HISTOGRAM_BINS), gpu_result(num_positions * HISTOGRAM_BINS), pen_result(num_positions * HISTOGRAM_BINS); std::chrono::duration<double> elapsed_time_cpu, elapsed_time_gpu_p_copy, elapsed_time_gpu_nocopy, elapsed_time_pencil; { //CPU implement const auto cpu_start = std::chrono::high_resolution_clock::now(); auto result = nel::HOGDescriptor< NUMBER_OF_CELLS , NUMBER_OF_BINS , GAUSSIAN_WEIGHTS , SPARTIAL_WEIGHTS , SIGNED_HOG >::compute(cpu_gray, locations, size); const auto cpu_end = std::chrono::high_resolution_clock::now(); std::copy(result.begin(), result.end(), cpu_result.begin()); elapsed_time_cpu = cpu_end - cpu_start; //Free up resources } { carp::opencl::device device; size_t max_work_group_size; cl_int err; err = clGetDeviceInfo( device.get_device_id() , CL_DEVICE_MAX_WORK_GROUP_SIZE , sizeof(size_t) , &max_work_group_size , nullptr ); const int work_size_locations = num_positions; const int work_size_x = pow(2, std::ceil(std::log2(max_work_group_size / work_size_locations)/2)); //The square root of the max size/locations, rounded up to power-of-two const int work_size_y = max_work_group_size / work_size_locations / work_size_x; if (err != CL_SUCCESS) throw std::runtime_error("Cannot query max work group size."); const auto gpu_compile_start = std::chrono::high_resolution_clock::now(); device.source_compile( hog_opencl_cl, hog_opencl_cl_len, {"calc_histogram", "fill_zeros"} ); const auto gpu_copy_start = std::chrono::high_resolution_clock::now(); cl_mem gpu_gray = clCreateBuffer( device.get_context() , CL_MEM_READ_ONLY|CL_MEM_COPY_HOST_PTR , cpu_gray.elemSize()*cpu_gray.rows*cpu_gray.step1() , cpu_gray.data , &err ); if (err != CL_SUCCESS) throw std::runtime_error("Cannot copy source image to GPU."); cl_mem gpu_locations = clCreateBuffer( device.get_context() , CL_MEM_READ_ONLY|CL_MEM_COPY_HOST_PTR , sizeof(float[2])*num_positions , locations.data() , &err ); if (err != CL_SUCCESS) throw std::runtime_error("Cannot copy locations array to GPU."); cl_mem gpu_hist = clCreateBuffer(device.get_context(), CL_MEM_WRITE_ONLY, sizeof(cl_float)*HISTOGRAM_BINS*num_positions, nullptr, &err); if (err != CL_SUCCESS) throw std::runtime_error("Cannot allocate histogram array."); device["fill_zeros"](gpu_hist, HISTOGRAM_BINS*num_positions).groupsize({std::min<size_t>(max_work_group_size, HISTOGRAM_BINS*num_positions)}, {HISTOGRAM_BINS*num_positions}); const auto gpu_start = std::chrono::high_resolution_clock::now(); device["calc_histogram"]( cpu_gray.rows , cpu_gray.cols , (int)cpu_gray.step1() , gpu_gray , num_positions , gpu_locations , size , gpu_hist , carp::opencl::buffer(sizeof(cl_float)*HISTOGRAM_BINS*num_positions) ).groupsize({work_size_locations,work_size_x,work_size_y}, {num_positions, (int)ceil(size), (int)ceil(size)}); const auto gpu_end = std::chrono::high_resolution_clock::now(); err = clEnqueueReadBuffer(device.get_queue(), gpu_hist, CL_TRUE, 0, sizeof(cl_float)*HISTOGRAM_BINS*num_positions, gpu_result.data(), 0, nullptr, nullptr); if (err != CL_SUCCESS) throw std::runtime_error("Cannot copy histogram array to host."); err = clReleaseMemObject(gpu_hist); if (err != CL_SUCCESS) throw std::runtime_error("Cannot free histogram array."); err = clReleaseMemObject(gpu_locations); if (err != CL_SUCCESS) throw std::runtime_error("Cannot free gpu_locations array."); err = clReleaseMemObject(gpu_gray); if (err != CL_SUCCESS) throw std::runtime_error("Cannot free gpu_image array."); const auto gpu_copy_end = std::chrono::high_resolution_clock::now(); const auto gpu_compile_end = std::chrono::high_resolution_clock::now(); elapsed_time_gpu_p_copy = gpu_copy_end - gpu_copy_start; elapsed_time_gpu_nocopy = gpu_end - gpu_start; auto elapsed_time_gpu_compile = gpu_compile_end - gpu_compile_start; //Free up resources } { pen_result.resize(num_positions * HISTOGRAM_BINS, 0.0f); const auto pencil_start = std::chrono::high_resolution_clock::now(); pencil_hog( cpu_gray.rows, cpu_gray.cols, cpu_gray.step1(), cpu_gray.ptr<uint8_t>() , num_positions, reinterpret_cast<const float (*)[2]>(locations.data()) , size , pen_result.data() ); const auto pencil_end = std::chrono::high_resolution_clock::now(); elapsed_time_pencil = pencil_end - pencil_start; //Free up resources } // Verifying the results if ( cv::norm( cpu_result, gpu_result, cv::NORM_INF) > cv::norm( gpu_result, cv::NORM_INF)*1e-5 || cv::norm( cpu_result, pen_result, cv::NORM_INF) > cv::norm( cpu_result, cv::NORM_INF)*1e-5 ) { std::vector<float> diff; std::transform(cpu_result.begin(), cpu_result.end(), gpu_result.begin(), std::back_inserter(diff), std::minus<float>()); std::cerr << "ERROR: Results don't match." << std::endl; std::cerr << "CPU norm:" << cv::norm(cpu_result, cv::NORM_INF) << std::endl; std::cerr << "GPU norm:" << cv::norm(gpu_result, cv::NORM_INF) << std::endl; std::cerr << "PEN norm:" << cv::norm(pen_result, cv::NORM_INF) << std::endl; std::cerr << "GPU-CPU norm:" << cv::norm(gpu_result, cpu_result, cv::NORM_INF) << std::endl; std::cerr << "PEN-CPU norm:" << cv::norm(pen_result, cpu_result, cv::NORM_INF) << std::endl; throw std::runtime_error("The OpenCL or PENCIL results are not equivalent with the C++ results."); } timing.print( elapsed_time_cpu, elapsed_time_gpu_p_copy, elapsed_time_gpu_nocopy, elapsed_time_pencil ); } } } } int main(int argc, char* argv[]) { try { std::cout << "This executable is iterating over all the files which are present in the directory `./pool'. " << std::endl; auto pool = carp::get_pool("pool"); #ifdef RUN_ONLY_ONE_EXPERIMENT time_hog( pool, {64}, 50, 1 ); #else time_hog( pool, {16, 32, 64, 128, 192}, 50, 10 ); #endif return EXIT_SUCCESS; }catch(const std::exception& e) { std::cout << e.what() << std::endl; return EXIT_FAILURE; } } // main <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2019 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "condition.h" #if defined(__WIN32__) && !defined(PTHREADS_WIN32) #define WIN32_LEAN_AND_MEAN #include <windows.h> namespace embree { #if (_WIN32_WINNT >= 0x0600) struct ConditionImplementation { __forceinline ConditionImplementation () { InitializeConditionVariable(&cond); } __forceinline ~ConditionImplementation () { } __forceinline void wait(MutexSys& mutex_in) { SleepConditionVariableCS(&cond, (LPCRITICAL_SECTION)mutex_in.mutex, INFINITE); } __forceinline void notify_all() { WakeAllConditionVariable(&cond); } public: CONDITION_VARIABLE cond; }; #else #pragma message ("WARNING: This condition variable implementation has known performance issues!") struct ConditionImplementation { __forceinline ConditionImplementation () : count(0) { event = CreateEvent(nullptr,TRUE,FALSE,nullptr); } __forceinline ~ConditionImplementation () { CloseHandle(event); } __forceinline void wait(MutexSys& mutex_in) { /* atomically increment thread count */ ssize_t cnt0 = atomic_add(&count,+1); mutex_in.unlock(); /* all threads except the last one are wait in the barrier */ if (WaitForSingleObject(event, INFINITE) != WAIT_OBJECT_0) THROW_RUNTIME_ERROR("WaitForSingleObject failed"); /* atomically decrement thread count */ mutex_in.lock(); ssize_t cnt1 = atomic_add(&count,-1); /* the last thread that left the barrier resets the event again */ if (cnt1 == 1) { if (ResetEvent(event) == 0) THROW_RUNTIME_ERROR("ResetEvent failed"); } } __forceinline void notify_all() { /* we support only one broadcast at a given time */ bool hasWaiters = count > 0; /* if threads are waiting, let them continue */ if (hasWaiters) if (SetEvent(event) == 0) THROW_RUNTIME_ERROR("SetEvent failed"); } public: HANDLE event; volatile atomic_t count; }; #endif } #endif #if defined(__UNIX__) || defined(PTHREADS_WIN32) #include <pthread.h> namespace embree { struct ConditionImplementation { __forceinline ConditionImplementation () { pthread_cond_init(&cond,nullptr); } __forceinline ~ConditionImplementation() { pthread_cond_destroy(&cond); } __forceinline void wait(MutexSys& mutex) { pthread_cond_wait(&cond, (pthread_mutex_t*)mutex.mutex); } __forceinline void notify_all() { pthread_cond_broadcast(&cond); } public: pthread_cond_t cond; }; } #endif namespace embree { ConditionSys::ConditionSys () { cond = new ConditionImplementation; } ConditionSys::~ConditionSys() { delete (ConditionImplementation*) cond; } void ConditionSys::wait(MutexSys& mutex) { ((ConditionImplementation*) cond)->wait(mutex); } void ConditionSys::notify_all() { ((ConditionImplementation*) cond)->notify_all(); } } <commit_msg>removed old Windows condition variable implementation<commit_after>// ======================================================================== // // Copyright 2009-2019 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "condition.h" #if defined(__WIN32__) && !defined(PTHREADS_WIN32) #define WIN32_LEAN_AND_MEAN #include <windows.h> namespace embree { struct ConditionImplementation { __forceinline ConditionImplementation () { InitializeConditionVariable(&cond); } __forceinline ~ConditionImplementation () { } __forceinline void wait(MutexSys& mutex_in) { SleepConditionVariableCS(&cond, (LPCRITICAL_SECTION)mutex_in.mutex, INFINITE); } __forceinline void notify_all() { WakeAllConditionVariable(&cond); } public: CONDITION_VARIABLE cond; }; } #endif #if defined(__UNIX__) || defined(PTHREADS_WIN32) #include <pthread.h> namespace embree { struct ConditionImplementation { __forceinline ConditionImplementation () { pthread_cond_init(&cond,nullptr); } __forceinline ~ConditionImplementation() { pthread_cond_destroy(&cond); } __forceinline void wait(MutexSys& mutex) { pthread_cond_wait(&cond, (pthread_mutex_t*)mutex.mutex); } __forceinline void notify_all() { pthread_cond_broadcast(&cond); } public: pthread_cond_t cond; }; } #endif namespace embree { ConditionSys::ConditionSys () { cond = new ConditionImplementation; } ConditionSys::~ConditionSys() { delete (ConditionImplementation*) cond; } void ConditionSys::wait(MutexSys& mutex) { ((ConditionImplementation*) cond)->wait(mutex); } void ConditionSys::notify_all() { ((ConditionImplementation*) cond)->notify_all(); } } <|endoftext|>
<commit_before>#include "server_engine.h" #include <SFML/Graphics.hpp> #include <cotsb/logging.h> #include "map.h" #include "map_tcp_serialiser.h" #include "player_tcp_serialiser.h" #include "game_object_tcp_serialiser.h" #include "game_object.h" #include "tile.h" #include "profile.h" #include "map_lua_deserialiser.h" #include <utils/lua_serialiser.h> #include <signal.h> #include <string.h> namespace cotsb { void kill_sig_handler(int, siginfo_t*, void*) { ServerEngine::shutdown(); } bool ServerEngine::s_running = false; Server ServerEngine::s_server; bool ServerEngine::init() { if (s_running) { return true; } struct sigaction act; memset(&act, 0, sizeof(struct sigaction)); sigemptyset(&act.sa_mask); act.sa_sigaction = kill_sig_handler; act.sa_flags = SA_SIGINFO; if (-1 == sigaction(SIGINT, &act, NULL)) { logger % "Error" << "sigaction()" << endl; return false; } s_running = true; s_server.port(8888); try { s_server.start_server(); } catch (...) { return false; } TileManager::init(); MapManager::init(); auto map1 = MapLuaDeserialiser::deserialise("data/maps/map1.lua"); if (map1 == nullptr) { logger % "Error" << "Failed to load map1!" << endl; } else { MapManager::map(map1); } logger % "Info" << "Started server" <<endl; s_server.on_connect(on_connect); s_server.on_disconnect(on_disconnect); return true; } void ServerEngine::deinit() { ProfileManager::deinit(); } void ServerEngine::shutdown() { s_running = false; } bool ServerEngine::is_running() { return s_running; } void ServerEngine::server_loop() { sf::Time sleep_time = sf::milliseconds(16); while (s_running) { s_server.check_network(); for (const auto &iter : s_server.new_data()) { auto &packet = *iter.second; CommandType command_temp; packet >> command_temp; process_command(iter.first, static_cast<Commands::Type>(command_temp), packet); } s_server.clear_new_data(); update(sleep_time.asSeconds()); sf::sleep(sleep_time); } } sf::Packet &ServerEngine::send(Commands::Type command, sf::TcpSocket *socket) { return s_server.send(command, socket); } sf::Packet &ServerEngine::send_callback(Commands::Type command, Packet::PacketSendCallback callback) { return s_server.send_callback(command, callback); } sf::Packet &ServerEngine::broadcast(Commands::Type command, sf::TcpSocket *skip_socket) { return s_server.broadcast(command, skip_socket); } void ServerEngine::process_command(sf::TcpSocket *socket, Commands::Type command, sf::Packet &packet) { if (command == Commands::LoadMap) { std::string map_name; packet >> map_name; auto player = PlayerManager::player(socket); logger % "Info" << "Request for map: " << map_name << endl; auto &response = s_server.send(Commands::NewMap, socket); response << map_name; auto found_map = MapManager::map(map_name); if (found_map == nullptr) { response << false << "Failed to find map."; } else { response << true; MapTcpSerialiser::serialise(*found_map, response); if (player->current_map() == found_map) { player->state(Player::LoadingMap); } for (auto &obj : found_map->game_objects()) { send_game_obj(obj, player); } } } else if (command == Commands::Message) { std::string message; packet >> message; auto &response = s_server.broadcast(command, socket); response << message; } else if (command == Commands::JoinGame) { std::string profile_name; packet >> profile_name; auto profile = ProfileManager::find_load_profile(profile_name); if (profile == nullptr) { profile = ProfileManager::create_profile(profile_name); setup_profile(profile); ProfileManager::save_profile(profile); } auto player = PlayerManager::create_player(socket); profile->player(player); player->profile(profile); profile->colour(profile->colour()); auto player_game_object = GameObjectManager::create_game_object<GameObject>(); player->game_object(player_game_object); player_game_object->setPosition(profile->location()); // Starter map auto map = MapManager::map(profile->map_name()); player_game_object->current_map(map); // The player knows what map it's on, but it's added to that map until // the client says that it's ready. player->current_map(map); map->add_game_object(player_game_object); logger % "Network" << "Player joined " << profile->display_name() << endl; // Tell everyone except the original player about the new player auto &broadcast_player = s_server.broadcast(Commands::NewPlayer, socket); PlayerTcpSerialiser::serialise(*player, broadcast_player); // Tell everyone about the new game object for the player broadcast_game_obj(player_game_object); // Respond directly to the player about the player info. auto &response = s_server.send(Commands::JoinedGame, socket); PlayerTcpSerialiser::serialise(*player, response); } else if (command == Commands::LoadedPlayerMap) { auto player = PlayerManager::player(socket); if (player->current_map() == nullptr) { logger % "Error" << "Cannot add player to null map!" << endl; return; } player->state(Player::Ready); player->current_map()->add_player(player); } else if (command == Commands::MoveInDirection) { auto player = PlayerManager::player(socket); int8_t x, y; packet >> x >> y; player->move(x, y); logger % "Info" << "Move in direction: " << static_cast<int32_t>(x) << ", " << static_cast<int32_t>(y) << endl; } else if (command == Commands::CreateProfile) { std::string profile_name; std::string display_name; packet >> profile_name >> display_name; } } void ServerEngine::broadcast_game_obj(GameObject *obj) { for (auto &player : PlayerManager::players()) { send_game_obj(obj, player.second.get()); } } void ServerEngine::send_game_obj(GameObject *obj, Player *player) { auto id = obj->id(); if (!player->has_seen_game_obj(id)) { player->add_seen_game_obj(id); auto &send_game_obj = s_server.send(Commands::NewGameObject, player->socket()); GameObjectTcpSerialiser::serialise(obj, send_game_obj); } } void ServerEngine::on_connect(sf::TcpSocket *socket) { auto &welcome = s_server.send(Commands::Message, socket); welcome << "Welcome friend"; } void ServerEngine::on_disconnect(sf::TcpSocket *socket) { auto player = PlayerManager::player(socket); if (player == nullptr) { // Player was disconnected before a player structure was created. return; } ProfileManager::save_profile(player->profile()); PlayerManager::remove_player(socket); } void ServerEngine::update(float dt) { MapManager::update(dt); PlayerManager::update(dt); GameObjectManager::check_for_updates(); } void ServerEngine::setup_profile(Profile *profile) { profile->map_name("map1"); profile->location(sf::Vector2f(1, 1)); profile->colour(sf::Color::Cyan); } } <commit_msg>- Fixed colour not being applied from profile to player game object.<commit_after>#include "server_engine.h" #include <SFML/Graphics.hpp> #include <cotsb/logging.h> #include "map.h" #include "map_tcp_serialiser.h" #include "player_tcp_serialiser.h" #include "game_object_tcp_serialiser.h" #include "game_object.h" #include "tile.h" #include "profile.h" #include "map_lua_deserialiser.h" #include <utils/lua_serialiser.h> #include <signal.h> #include <string.h> namespace cotsb { void kill_sig_handler(int, siginfo_t*, void*) { ServerEngine::shutdown(); } bool ServerEngine::s_running = false; Server ServerEngine::s_server; bool ServerEngine::init() { if (s_running) { return true; } struct sigaction act; memset(&act, 0, sizeof(struct sigaction)); sigemptyset(&act.sa_mask); act.sa_sigaction = kill_sig_handler; act.sa_flags = SA_SIGINFO; if (-1 == sigaction(SIGINT, &act, NULL)) { logger % "Error" << "sigaction()" << endl; return false; } s_running = true; s_server.port(8888); try { s_server.start_server(); } catch (...) { return false; } TileManager::init(); MapManager::init(); auto map1 = MapLuaDeserialiser::deserialise("data/maps/map1.lua"); if (map1 == nullptr) { logger % "Error" << "Failed to load map1!" << endl; } else { MapManager::map(map1); } logger % "Info" << "Started server" <<endl; s_server.on_connect(on_connect); s_server.on_disconnect(on_disconnect); return true; } void ServerEngine::deinit() { ProfileManager::deinit(); } void ServerEngine::shutdown() { s_running = false; } bool ServerEngine::is_running() { return s_running; } void ServerEngine::server_loop() { sf::Time sleep_time = sf::milliseconds(16); while (s_running) { s_server.check_network(); for (const auto &iter : s_server.new_data()) { auto &packet = *iter.second; CommandType command_temp; packet >> command_temp; process_command(iter.first, static_cast<Commands::Type>(command_temp), packet); } s_server.clear_new_data(); update(sleep_time.asSeconds()); sf::sleep(sleep_time); } } sf::Packet &ServerEngine::send(Commands::Type command, sf::TcpSocket *socket) { return s_server.send(command, socket); } sf::Packet &ServerEngine::send_callback(Commands::Type command, Packet::PacketSendCallback callback) { return s_server.send_callback(command, callback); } sf::Packet &ServerEngine::broadcast(Commands::Type command, sf::TcpSocket *skip_socket) { return s_server.broadcast(command, skip_socket); } void ServerEngine::process_command(sf::TcpSocket *socket, Commands::Type command, sf::Packet &packet) { if (command == Commands::LoadMap) { std::string map_name; packet >> map_name; auto player = PlayerManager::player(socket); logger % "Info" << "Request for map: " << map_name << endl; auto &response = s_server.send(Commands::NewMap, socket); response << map_name; auto found_map = MapManager::map(map_name); if (found_map == nullptr) { response << false << "Failed to find map."; } else { response << true; MapTcpSerialiser::serialise(*found_map, response); if (player->current_map() == found_map) { player->state(Player::LoadingMap); } for (auto &obj : found_map->game_objects()) { send_game_obj(obj, player); } } } else if (command == Commands::Message) { std::string message; packet >> message; auto &response = s_server.broadcast(command, socket); response << message; } else if (command == Commands::JoinGame) { std::string profile_name; packet >> profile_name; auto profile = ProfileManager::find_load_profile(profile_name); if (profile == nullptr) { profile = ProfileManager::create_profile(profile_name); setup_profile(profile); ProfileManager::save_profile(profile); } auto player = PlayerManager::create_player(socket); profile->player(player); player->profile(profile); auto player_game_object = GameObjectManager::create_game_object<GameObject>(); player->game_object(player_game_object); player_game_object->setPosition(profile->location()); player_game_object->colour(profile->colour()); // Starter map auto map = MapManager::map(profile->map_name()); player_game_object->current_map(map); // The player knows what map it's on, but it's added to that map until // the client says that it's ready. player->current_map(map); map->add_game_object(player_game_object); logger % "Network" << "Player joined " << profile->display_name() << endl; // Tell everyone except the original player about the new player auto &broadcast_player = s_server.broadcast(Commands::NewPlayer, socket); PlayerTcpSerialiser::serialise(*player, broadcast_player); // Tell everyone about the new game object for the player broadcast_game_obj(player_game_object); // Respond directly to the player about the player info. auto &response = s_server.send(Commands::JoinedGame, socket); PlayerTcpSerialiser::serialise(*player, response); } else if (command == Commands::LoadedPlayerMap) { auto player = PlayerManager::player(socket); if (player->current_map() == nullptr) { logger % "Error" << "Cannot add player to null map!" << endl; return; } player->state(Player::Ready); player->current_map()->add_player(player); } else if (command == Commands::MoveInDirection) { auto player = PlayerManager::player(socket); int8_t x, y; packet >> x >> y; player->move(x, y); logger % "Info" << "Move in direction: " << static_cast<int32_t>(x) << ", " << static_cast<int32_t>(y) << endl; } else if (command == Commands::CreateProfile) { std::string profile_name; std::string display_name; packet >> profile_name >> display_name; } } void ServerEngine::broadcast_game_obj(GameObject *obj) { for (auto &player : PlayerManager::players()) { send_game_obj(obj, player.second.get()); } } void ServerEngine::send_game_obj(GameObject *obj, Player *player) { auto id = obj->id(); if (!player->has_seen_game_obj(id)) { player->add_seen_game_obj(id); auto &send_game_obj = s_server.send(Commands::NewGameObject, player->socket()); GameObjectTcpSerialiser::serialise(obj, send_game_obj); } } void ServerEngine::on_connect(sf::TcpSocket *socket) { auto &welcome = s_server.send(Commands::Message, socket); welcome << "Welcome friend"; } void ServerEngine::on_disconnect(sf::TcpSocket *socket) { auto player = PlayerManager::player(socket); if (player == nullptr) { // Player was disconnected before a player structure was created. return; } ProfileManager::save_profile(player->profile()); PlayerManager::remove_player(socket); } void ServerEngine::update(float dt) { MapManager::update(dt); PlayerManager::update(dt); GameObjectManager::check_for_updates(); } void ServerEngine::setup_profile(Profile *profile) { profile->map_name("map1"); profile->location(sf::Vector2f(1, 1)); profile->colour(sf::Color::Cyan); } } <|endoftext|>
<commit_before>#include <SFML/Graphics.hpp> #include <Astra/Astra.h> #include <AstraUL/AstraUL.h> #include "../../common/LitDepthVisualizer.h" #include <chrono> #include <iostream> #include <iomanip> #include <key_handler.h> #include <sstream> class DepthFrameListener : public astra::FrameReadyListener { public: DepthFrameListener() { m_lastTimepoint = clock_type::now(); m_font.loadFromFile("Inconsolata.otf"); } void init_texture(int width, int height) { if (m_displayBuffer == nullptr || width != m_displayWidth || height != m_displayHeight) { m_displayWidth = width; m_displayHeight = height; // texture is RGBA int byteLength = m_displayWidth * m_displayHeight * 4; m_displayBuffer = BufferPtr(new uint8_t[byteLength]); memset(m_displayBuffer.get(), 0, byteLength); m_texture.create(m_displayWidth, m_displayHeight); m_sprite.setTexture(m_texture); m_sprite.setPosition(0, 0); } } void check_fps() { const double frameWeight = 0.2; auto newTimepoint = clock_type::now(); auto frameDuration = std::chrono::duration_cast<duration_type>(newTimepoint - m_lastTimepoint); m_frameDuration = frameDuration * frameWeight + m_frameDuration * (1 - frameWeight); m_lastTimepoint = newTimepoint; double fps = 1.0 / m_frameDuration.count(); auto precision = std::cout.precision(); std::cout << std::fixed << std::setprecision(1) << fps << " fps (" << std::setprecision(2) << frameDuration.count() * 1000 << " ms)" << std::setprecision(precision) << std::endl; } virtual void on_frame_ready(astra::StreamReader& reader, astra::Frame& frame) override { astra::PointFrame pointFrame = frame.get<astra::PointFrame>(); int width = pointFrame.resolutionX(); int height = pointFrame.resolutionY(); init_texture(width, height); update_mouse_overlay_from_depth(frame); check_fps(); if (m_isPaused) { return; } copy_depth_data(frame); m_visualizer.update(pointFrame); astra_rgb_pixel_t* vizBuffer = m_visualizer.get_output(); for (int i = 0; i < width * height; i++) { int rgbaOffset = i * 4; m_displayBuffer[rgbaOffset] = vizBuffer[i].r; m_displayBuffer[rgbaOffset + 1] = vizBuffer[i].b; m_displayBuffer[rgbaOffset + 2] = vizBuffer[i].g; m_displayBuffer[rgbaOffset + 3] = 255; } m_texture.update(m_displayBuffer.get()); } void copy_depth_data(astra::Frame& frame) { astra::DepthFrame depthFrame = frame.get<astra::DepthFrame>(); if (depthFrame.is_valid()) { int width = depthFrame.resolutionX(); int height = depthFrame.resolutionY(); if (m_depthData == nullptr || width != m_depthWidth || height != m_depthHeight) { m_depthWidth = width; m_depthHeight = height; // texture is RGBA int byteLength = m_depthWidth * m_depthHeight * sizeof(uint16_t); m_depthData = DepthPtr(new int16_t[byteLength]); } depthFrame.copy_to(m_depthData.get()); } } void update_mouse_overlay_from_depth(astra::Frame& frame) { if (m_depthData != nullptr) { m_mouse_X = m_depthWidth * m_mouseNormX; m_mouse_Y = m_depthHeight * m_mouseNormY; size_t index = (m_depthWidth * m_mouse_Y + m_mouse_X); m_mouse_Z = m_depthData[index]; } } void update_mouse_position(sf::RenderWindow& window) { sf::Vector2i position = sf::Mouse::getPosition(window); auto windowSize = window.getSize(); m_mouseNormX = position.x / static_cast<float>(windowSize.x); m_mouseNormY = position.y / static_cast<float>(windowSize.y); } void drawText(sf::RenderWindow& window, sf::Text& text, sf::Color color, int x, int y) { text.setColor(sf::Color::Black); text.setPosition(x + 5, y + 5); window.draw(text); text.setColor(color); text.setPosition(x, y); window.draw(text); } void drawMouseOverlay(sf::RenderWindow& window, float depthWScale, float depthHScale) { if (!m_isMouseOverlayEnabled) { return; } std::stringstream str; str << std::fixed << std::setprecision(0); str << "X:" << m_mouse_X << " " << "Y:" << m_mouse_Y << " " << "Z:" << m_mouse_Z; sf::Text text(str.str(), m_font); int characterSize = 40; text.setCharacterSize(characterSize); text.setStyle(sf::Text::Bold); float display_x = 10; float display_y = window.getView().getSize().y - 10 - characterSize; drawText(window, text, sf::Color::White, display_x, display_y); } void drawTo(sf::RenderWindow& window) { if (m_displayBuffer != nullptr) { float depthWScale = window.getView().getSize().x / m_displayWidth; float depthHScale = window.getView().getSize().y / m_displayHeight; m_sprite.setScale(depthWScale, depthHScale); window.draw(m_sprite); drawMouseOverlay(window, depthWScale, depthHScale); } } void toggle_isPaused() { m_isPaused = !m_isPaused; } bool get_isPaused() const { return m_isPaused; } void toggle_isMouseOverlayEnabled() { m_isMouseOverlayEnabled = !m_isMouseOverlayEnabled; } bool get_isMouseOverlayEnabled() const { return m_isMouseOverlayEnabled; } private: samples::common::LitDepthVisualizer m_visualizer; using duration_type = std::chrono::duration<double>; duration_type m_frameDuration{0.0}; using clock_type = std::chrono::system_clock; std::chrono::time_point<clock_type> m_lastTimepoint; sf::Texture m_texture; sf::Sprite m_sprite; sf::Font m_font; using BufferPtr = std::unique_ptr< uint8_t[] >; BufferPtr m_displayBuffer{ nullptr }; int m_displayWidth{ 0 }; int m_displayHeight{ 0 }; int m_depthWidth{ 0 }; int m_depthHeight{ 0 }; using DepthPtr = std::unique_ptr < int16_t[] > ; DepthPtr m_depthData{ nullptr }; int m_mouse_X{ 0 }; int m_mouse_Y{ 0 }; int m_mouse_Z{ 0 }; float m_mouseNormX{ 0 }; float m_mouseNormY{ 0 }; bool m_isPaused{ false }; bool m_isMouseOverlayEnabled{ false }; }; int main(int argc, char** argv) { astra::Astra::initialize(); set_key_handler(); sf::RenderWindow window(sf::VideoMode(1280, 960), "Depth Viewer"); #ifdef _WIN32 auto fullscreenStyle = sf::Style::None; #else auto fullscreenStyle = sf::Style::Fullscreen; #endif sf::VideoMode fullscreen_mode = sf::VideoMode::getFullscreenModes()[0]; sf::VideoMode windowed_mode(1280, 960); bool is_fullscreen = false; astra::StreamSet streamset; astra::StreamReader reader = streamset.create_reader(); reader.stream<astra::PointStream>().start(); auto depthStream = reader.stream<astra::DepthStream>(); depthStream.start(); DepthFrameListener listener; reader.addListener(listener); while (window.isOpen()) { astra_temp_update(); sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::KeyPressed: { if (event.key.code == sf::Keyboard::C && event.key.control) { window.close(); } switch (event.key.code) { case sf::Keyboard::Escape: window.close(); break; case sf::Keyboard::F: if (is_fullscreen) { is_fullscreen = false; window.create(windowed_mode, "Depth Viewer", sf::Style::Default); } else { is_fullscreen = true; window.create(fullscreen_mode, "Depth Viewer", fullscreenStyle); } break; case sf::Keyboard::R: depthStream.enable_registration(!depthStream.registration_enabled()); break; case sf::Keyboard::M: depthStream.enable_mirroring(!depthStream.mirroring_enabled()); break; case sf::Keyboard::P: listener.toggle_isPaused(); break; case sf::Keyboard::Space: listener.toggle_isMouseOverlayEnabled(); break; default: break; } break; } case sf::Event::MouseMoved: { listener.update_mouse_position(window); break; } default: break; } } // clear the window with black color window.clear(sf::Color::Black); listener.drawTo(window); window.display(); if (!shouldContinue) { window.close(); } } astra::Astra::terminate(); return 0; } <commit_msg>Update mouse overlay to show depth x&y and real world x&y. Simply some methods. Add guards for out-of-bounds mouse position.<commit_after>#include <SFML/Graphics.hpp> #include <Astra/Astra.h> #include <AstraUL/AstraUL.h> #include "../../common/LitDepthVisualizer.h" #include <chrono> #include <iostream> #include <iomanip> #include <key_handler.h> #include <sstream> class DepthFrameListener : public astra::FrameReadyListener { public: DepthFrameListener(const astra::CoordinateMapper& coordinate_mapper) : m_coordinate_mapper(coordinate_mapper) { m_lastTimepoint = clock_type::now(); m_font.loadFromFile("Inconsolata.otf"); } void init_texture(int width, int height) { if (m_displayBuffer == nullptr || width != m_displayWidth || height != m_displayHeight) { m_displayWidth = width; m_displayHeight = height; // texture is RGBA int byteLength = m_displayWidth * m_displayHeight * 4; m_displayBuffer = BufferPtr(new uint8_t[byteLength]); memset(m_displayBuffer.get(), 0, byteLength); m_texture.create(m_displayWidth, m_displayHeight); m_sprite.setTexture(m_texture); m_sprite.setPosition(0, 0); } } void check_fps() { const double frameWeight = 0.2; auto newTimepoint = clock_type::now(); auto frameDuration = std::chrono::duration_cast<duration_type>(newTimepoint - m_lastTimepoint); m_frameDuration = frameDuration * frameWeight + m_frameDuration * (1 - frameWeight); m_lastTimepoint = newTimepoint; double fps = 1.0 / m_frameDuration.count(); auto precision = std::cout.precision(); std::cout << std::fixed << std::setprecision(1) << fps << " fps (" << std::setprecision(2) << frameDuration.count() * 1000 << " ms)" << std::setprecision(precision) << std::endl; } virtual void on_frame_ready(astra::StreamReader& reader, astra::Frame& frame) override { astra::PointFrame pointFrame = frame.get<astra::PointFrame>(); int width = pointFrame.resolutionX(); int height = pointFrame.resolutionY(); init_texture(width, height); check_fps(); if (m_isPaused) { return; } copy_depth_data(frame); m_visualizer.update(pointFrame); astra_rgb_pixel_t* vizBuffer = m_visualizer.get_output(); for (int i = 0; i < width * height; i++) { int rgbaOffset = i * 4; m_displayBuffer[rgbaOffset] = vizBuffer[i].r; m_displayBuffer[rgbaOffset + 1] = vizBuffer[i].b; m_displayBuffer[rgbaOffset + 2] = vizBuffer[i].g; m_displayBuffer[rgbaOffset + 3] = 255; } m_texture.update(m_displayBuffer.get()); } void copy_depth_data(astra::Frame& frame) { astra::DepthFrame depthFrame = frame.get<astra::DepthFrame>(); if (depthFrame.is_valid()) { int width = depthFrame.resolutionX(); int height = depthFrame.resolutionY(); if (m_depthData == nullptr || width != m_depthWidth || height != m_depthHeight) { m_depthWidth = width; m_depthHeight = height; // texture is RGBA int byteLength = m_depthWidth * m_depthHeight * sizeof(uint16_t); m_depthData = DepthPtr(new int16_t[byteLength]); } depthFrame.copy_to(m_depthData.get()); } } void update_mouse_position(sf::RenderWindow& window) { sf::Vector2i position = sf::Mouse::getPosition(window); auto windowSize = window.getSize(); m_mouseNormX = position.x / static_cast<float>(windowSize.x); m_mouseNormY = position.y / static_cast<float>(windowSize.y); } void drawText(sf::RenderWindow& window, sf::Text& text, sf::Color color, int x, int y) { text.setColor(sf::Color::Black); text.setPosition(x + 5, y + 5); window.draw(text); text.setColor(color); text.setPosition(x, y); window.draw(text); } void drawMouseOverlay(sf::RenderWindow& window, float depthWScale, float depthHScale) { if (!m_isMouseOverlayEnabled || m_depthData == nullptr) { return; } int mouseX = m_depthWidth * m_mouseNormX; int mouseY = m_depthHeight * m_mouseNormY; if (mouseX >= m_depthWidth || mouseY >= m_depthHeight || mouseX < 0 || mouseY < 0) { return; } size_t index = (m_depthWidth * mouseY + mouseX); int z = m_depthData[index]; float worldX, worldY, worldZ; m_coordinate_mapper.convert_depth_to_world(static_cast<float>(mouseX), static_cast<float>(mouseY), static_cast<float>(z), &worldX, &worldY, &worldZ); std::stringstream str; str << std::fixed << std::setprecision(0); str << "(" << mouseX << ", " << mouseY << ") X:" << worldX << " Y:" << worldY << " Z:" << worldZ; sf::Text text(str.str(), m_font); int characterSize = 40; text.setCharacterSize(characterSize); text.setStyle(sf::Text::Bold); float display_x = 10; float display_y = window.getView().getSize().y - 10 - characterSize; drawText(window, text, sf::Color::White, display_x, display_y); } void drawTo(sf::RenderWindow& window) { if (m_displayBuffer != nullptr) { float depthWScale = window.getView().getSize().x / m_displayWidth; float depthHScale = window.getView().getSize().y / m_displayHeight; m_sprite.setScale(depthWScale, depthHScale); window.draw(m_sprite); drawMouseOverlay(window, depthWScale, depthHScale); } } void toggle_isPaused() { m_isPaused = !m_isPaused; } bool get_isPaused() const { return m_isPaused; } void toggle_isMouseOverlayEnabled() { m_isMouseOverlayEnabled = !m_isMouseOverlayEnabled; } bool get_isMouseOverlayEnabled() const { return m_isMouseOverlayEnabled; } private: samples::common::LitDepthVisualizer m_visualizer; using duration_type = std::chrono::duration<double>; duration_type m_frameDuration{0.0}; using clock_type = std::chrono::system_clock; std::chrono::time_point<clock_type> m_lastTimepoint; sf::Texture m_texture; sf::Sprite m_sprite; sf::Font m_font; const astra::CoordinateMapper& m_coordinate_mapper; using BufferPtr = std::unique_ptr< uint8_t[] >; BufferPtr m_displayBuffer{ nullptr }; int m_displayWidth{ 0 }; int m_displayHeight{ 0 }; int m_depthWidth{ 0 }; int m_depthHeight{ 0 }; using DepthPtr = std::unique_ptr < int16_t[] > ; DepthPtr m_depthData{ nullptr }; float m_mouseNormX{ 0 }; float m_mouseNormY{ 0 }; bool m_isPaused{ false }; bool m_isMouseOverlayEnabled{ true }; }; int main(int argc, char** argv) { astra::Astra::initialize(); set_key_handler(); sf::RenderWindow window(sf::VideoMode(1280, 960), "Depth Viewer"); #ifdef _WIN32 auto fullscreenStyle = sf::Style::None; #else auto fullscreenStyle = sf::Style::Fullscreen; #endif sf::VideoMode fullscreen_mode = sf::VideoMode::getFullscreenModes()[0]; sf::VideoMode windowed_mode(1280, 960); bool is_fullscreen = false; astra::StreamSet streamset; astra::StreamReader reader = streamset.create_reader(); reader.stream<astra::PointStream>().start(); auto depthStream = reader.stream<astra::DepthStream>(); depthStream.start(); auto coordinate_mapper = depthStream.coordinateMapper(); DepthFrameListener listener(coordinate_mapper); reader.addListener(listener); while (window.isOpen()) { astra_temp_update(); sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::KeyPressed: { if (event.key.code == sf::Keyboard::C && event.key.control) { window.close(); } switch (event.key.code) { case sf::Keyboard::Escape: window.close(); break; case sf::Keyboard::F: if (is_fullscreen) { is_fullscreen = false; window.create(windowed_mode, "Depth Viewer", sf::Style::Default); } else { is_fullscreen = true; window.create(fullscreen_mode, "Depth Viewer", fullscreenStyle); } break; case sf::Keyboard::R: depthStream.enable_registration(!depthStream.registration_enabled()); break; case sf::Keyboard::M: depthStream.enable_mirroring(!depthStream.mirroring_enabled()); break; case sf::Keyboard::P: listener.toggle_isPaused(); break; case sf::Keyboard::Space: listener.toggle_isMouseOverlayEnabled(); break; default: break; } break; } case sf::Event::MouseMoved: { listener.update_mouse_position(window); break; } default: break; } } // clear the window with black color window.clear(sf::Color::Black); listener.drawTo(window); window.display(); if (!shouldContinue) { window.close(); } } astra::Astra::terminate(); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkCollection.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include <stdlib.h> #include <math.h> #include "vtkCollection.h" // Description: // Construct with empty list. vtkCollection::vtkCollection() { this->NumberOfItems = 0; this->Top = NULL; this->Bottom = NULL; this->Current = NULL; } vtkCollection::~vtkCollection() { this->RemoveAllItems(); } // Description: // protected function to delete an element. Internal use only. void vtkCollection::DeleteElement(vtkCollectionElement *e) { delete e; } // Description: // Add an object to the list. Does not prevent duplicate entries. void vtkCollection::AddItem(vtkObject *a) { vtkCollectionElement *elem; elem = new vtkCollectionElement; if (!this->Top) { this->Top = elem; } else { this->Bottom->Next = elem; } this->Bottom = elem; elem->Item = a; elem->Next = NULL; this->NumberOfItems++; } // Description: // Remove an object from the list. Removes the first object found, not // all occurrences. If no object found, list is unaffected. See warning // in description of RemoveItem(int). void vtkCollection::RemoveItem(vtkObject *a) { int i; vtkCollectionElement *elem,*prev; if (!this->Top) return; elem = this->Top; prev = NULL; for (i = 0; i < this->NumberOfItems; i++) { if (elem->Item == a) { this->RemoveItem(i); return; } else { prev = elem; elem = elem->Next; } } } // Description: // Remove all objects from the list. void vtkCollection::RemoveAllItems() { int i; vtkCollectionElement *p, *next; for (i = this->NumberOfItems - 1; i >= 0; i--) { this->RemoveItem(i); } } // Description: // Search for an object and return location in list. If location == 0, // object was not found. int vtkCollection::IsItemPresent(vtkObject *a) { int i; vtkCollectionElement *elem; if (!this->Top) return 0; elem = this->Top; for (i = 0; i < this->NumberOfItems; i++) { if (elem->Item == a) { return i + 1; } else { elem = elem->Next; } } return 0; } // Description: // Return the number of objects in the list. int vtkCollection::GetNumberOfItems() { return this->NumberOfItems; } void vtkCollection::PrintSelf(ostream& os, vtkIndent indent) { vtkObject::PrintSelf(os,indent); os << indent << "Number Of Items: " << this->NumberOfItems << "\n"; } // Description: // Get the i'th item in the collection. NULL is returned if i is out // of range vtkObject *vtkCollection::GetItemAsObject(int i) { vtkCollectionElement *elem=this->Top; if (i < 0) { return NULL; } while (elem != NULL && i > 0) { elem = elem->Next; i--; } if ( elem != NULL ) { return elem->Item; } else { return NULL; } } // Description: // Replace the i'th item in the collection with a void vtkCollection::ReplaceItem(int i, vtkObject *a) { vtkCollectionElement *elem; if( i < 0 || i >= this->NumberOfItems ) return; elem = this->Top; for (int j = 0; j < i; j++, elem = elem->Next ) {} // j == i elem->Item = a; } // Description: // Remove the i'th item in the list. // Be careful if using this function during traversal of the list using // GetNextItemAsObject (or GetNextItem in derived class). The list WILL // be shortened if a valid index is given! If this->Current is equal to the // element being removed, have it point to then next element in the list. void vtkCollection::RemoveItem(int i) { vtkCollectionElement *elem,*prev; if( i < 0 || i >= this->NumberOfItems ) return; elem = this->Top; prev = NULL; for (int j = 0; j < i; j++) { prev = elem; elem = elem->Next; } // j == i if (prev) prev->Next = elem->Next; else this->Top = elem->Next; if (!elem->Next) this->Bottom = prev; if ( this->Current == elem ) this->Current = elem->Next; this->DeleteElement(elem); this->NumberOfItems--; } <commit_msg>ENH: cleaned up some unused variables<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkCollection.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include <stdlib.h> #include <math.h> #include "vtkCollection.h" // Description: // Construct with empty list. vtkCollection::vtkCollection() { this->NumberOfItems = 0; this->Top = NULL; this->Bottom = NULL; this->Current = NULL; } vtkCollection::~vtkCollection() { this->RemoveAllItems(); } // Description: // protected function to delete an element. Internal use only. void vtkCollection::DeleteElement(vtkCollectionElement *e) { delete e; } // Description: // Add an object to the list. Does not prevent duplicate entries. void vtkCollection::AddItem(vtkObject *a) { vtkCollectionElement *elem; elem = new vtkCollectionElement; if (!this->Top) { this->Top = elem; } else { this->Bottom->Next = elem; } this->Bottom = elem; elem->Item = a; elem->Next = NULL; this->NumberOfItems++; } // Description: // Remove an object from the list. Removes the first object found, not // all occurrences. If no object found, list is unaffected. See warning // in description of RemoveItem(int). void vtkCollection::RemoveItem(vtkObject *a) { int i; vtkCollectionElement *elem,*prev; if (!this->Top) return; elem = this->Top; prev = NULL; for (i = 0; i < this->NumberOfItems; i++) { if (elem->Item == a) { this->RemoveItem(i); return; } else { prev = elem; elem = elem->Next; } } } // Description: // Remove all objects from the list. void vtkCollection::RemoveAllItems() { int i; for (i = this->NumberOfItems - 1; i >= 0; i--) { this->RemoveItem(i); } } // Description: // Search for an object and return location in list. If location == 0, // object was not found. int vtkCollection::IsItemPresent(vtkObject *a) { int i; vtkCollectionElement *elem; if (!this->Top) return 0; elem = this->Top; for (i = 0; i < this->NumberOfItems; i++) { if (elem->Item == a) { return i + 1; } else { elem = elem->Next; } } return 0; } // Description: // Return the number of objects in the list. int vtkCollection::GetNumberOfItems() { return this->NumberOfItems; } void vtkCollection::PrintSelf(ostream& os, vtkIndent indent) { vtkObject::PrintSelf(os,indent); os << indent << "Number Of Items: " << this->NumberOfItems << "\n"; } // Description: // Get the i'th item in the collection. NULL is returned if i is out // of range vtkObject *vtkCollection::GetItemAsObject(int i) { vtkCollectionElement *elem=this->Top; if (i < 0) { return NULL; } while (elem != NULL && i > 0) { elem = elem->Next; i--; } if ( elem != NULL ) { return elem->Item; } else { return NULL; } } // Description: // Replace the i'th item in the collection with a void vtkCollection::ReplaceItem(int i, vtkObject *a) { vtkCollectionElement *elem; if( i < 0 || i >= this->NumberOfItems ) return; elem = this->Top; for (int j = 0; j < i; j++, elem = elem->Next ) {} // j == i elem->Item = a; } // Description: // Remove the i'th item in the list. // Be careful if using this function during traversal of the list using // GetNextItemAsObject (or GetNextItem in derived class). The list WILL // be shortened if a valid index is given! If this->Current is equal to the // element being removed, have it point to then next element in the list. void vtkCollection::RemoveItem(int i) { vtkCollectionElement *elem,*prev; if( i < 0 || i >= this->NumberOfItems ) return; elem = this->Top; prev = NULL; for (int j = 0; j < i; j++) { prev = elem; elem = elem->Next; } // j == i if (prev) prev->Next = elem->Next; else this->Top = elem->Next; if (!elem->Next) this->Bottom = prev; if ( this->Current == elem ) this->Current = elem->Next; this->DeleteElement(elem); this->NumberOfItems--; } <|endoftext|>
<commit_before>// Copyright (c) 2020 ASMlover. 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 ofconditions 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 materialsprovided 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. #if defined(CORO_WIN) # include <WS2tcpip.h> # include <WinSock2.h> # define NEAGAIN WSAEWOULDBLOCK # define NEWOULDBLOCK WSAEWOULDBLOCK #else # include <arpa/inet.h> # include <netdb.h> # include <fcntl.h> # include <unistd.h> # define NEAGAIN EAGAIN # define NEWOULDBLOCK EWOULDBLOCK #endif #include <cerrno> #include "socket.hh" namespace coro::net { int get_errno() { #if defined(CORO_WIN) return ::WSAGetLastError(); #else return errno; #endif } void init_addr(sockaddr_in& addr, strv_t host, u16_t port) { addr.sin_family = AF_INET; addr.sin_port = ::htons(port); #if defined(CORO_WIN) ::InetPtonA(AF_INET, host.data(), &addr.sin_addr); #else ::inet_pton(AF_INET, host.data(), &addr.sin_addr); #endif } bool Socket::open() { if (is_valid()) return false; fd_ = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); return is_valid(); } void Socket::close() { if (is_valid()) { #if defined(CORO_WIN) ::shutdown(fd_, SD_BOTH); ::closesocket(fd_); #else ::shutdown(fd_, SHUT_RDWR); ::close(fd_); #endif fd_ = kInvalidSocket; } } void Socket::set_nonblocking(bool mode) { if (!is_valid()) return; #if defined(CORO_WIN) u_long flag = mode ? 1 : 0; ::ioctlsocket(fd_, FIONBIO, &flag); #else int flag = ::fcntl(fd_, F_GETFL, 0); flag = (mode ? (flag | O_NONBLOCK) : (flag & ~O_NONBLOCK)); ::fcntl(fd_, F_SETFL, flag); #endif } bool Socket::listen(strv_t host, u16_t port, int backlog) { if (!is_valid()) return false; sockaddr_in addr; init_addr(addr, host, port); if (::bind(fd_, (const sockaddr*)&addr, static_cast<int>(sizeof(addr))) == kSocketError) return false; return ::listen(fd_, backlog) != kSocketError; } bool Socket::connect(strv_t host, u16_t port) { if (!is_valid()) return false; sockaddr_in addr; init_addr(addr, host, port); return ::connect(fd_, (const sockaddr*)&addr, static_cast<int>(sizeof(addr))) != kSocketError; } std::optional<bool> Socket::async_connect(strv_t host, u16_t port) { if (!is_valid()) return {}; sockaddr_in addr; init_addr(addr, host, port); if (auto r = ::connect(fd_, (const sockaddr*)&addr, static_cast<int>(sizeof(addr))); r == kSocketError) { if (auto ec = get_errno(); ec == NEAGAIN || ec == NEWOULDBLOCK) return {false}; return {}; } return {true}; } std::optional<Socket> Socket::accept() { if (!is_valid()) return {}; sockaddr_in addr; socklen_t addr_len = sizeof(addr); if (auto fd = ::accept( fd_, (sockaddr*)&addr, &addr_len); fd != kInvalidSocket) return {fd}; return {}; } std::optional<Socket> Socket::async_accept() { if (!is_valid()) return {}; sockaddr_in addr; socklen_t addr_len = sizeof(addr); if (auto fd = ::accept( fd_, (sockaddr*)&addr, &addr_len); fd != kInvalidSocket) return {fd}; if (auto ec = get_errno(); ec == NEAGAIN || ec == NEWOULDBLOCK) return {kInvalidSocket}; return {}; } sz_t Socket::read(char* buf, sz_t len) { if (!is_valid()) return 0; return static_cast<sz_t>(::recv(fd_, buf, static_cast<int>(len), 0)); } std::optional<sz_t> Socket::async_read(char* buf, sz_t len) { if (!is_valid()) return 0; auto n = ::recv(fd_, buf, static_cast<int>(len), 0); if (n == kSocketError) { if (auto ec = get_errno(); ec == NEAGAIN || ec == NEWOULDBLOCK) return {0}; } else if (n > 0) { return {n}; } return {}; } sz_t Socket::write(const char* buf, sz_t len) { if (!is_valid()) return 0; return static_cast<sz_t>(::send(fd_, buf, static_cast<int>(len), 0)); } std::optional<sz_t> Socket::async_write(const char* buf, sz_t len) { if (!is_valid()) return 0; auto n = ::send(fd_, buf, static_cast<int>(len), 0); if (n == kSocketError) { if (auto ec = get_errno(); ec == NEAGAIN || ec == NEWOULDBLOCK) return {0}; } else if (n > 0) { return {n}; } return {}; } } <commit_msg>:bug: fix(error-code): fixed error code<commit_after>// Copyright (c) 2020 ASMlover. 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 ofconditions 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 materialsprovided 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. #if defined(CORO_WIN) # include <WS2tcpip.h> # include <WinSock2.h> # define NEAGAIN ERROR_RETRY # define NEWOULDBLOCK WSAEWOULDBLOCK #else # include <arpa/inet.h> # include <netdb.h> # include <fcntl.h> # include <unistd.h> # define NEAGAIN EAGAIN # define NEWOULDBLOCK EWOULDBLOCK #endif #include <cerrno> #include "socket.hh" namespace coro::net { int get_errno() { #if defined(CORO_WIN) return ::WSAGetLastError(); #else return errno; #endif } void init_addr(sockaddr_in& addr, strv_t host, u16_t port) { addr.sin_family = AF_INET; addr.sin_port = ::htons(port); #if defined(CORO_WIN) ::InetPtonA(AF_INET, host.data(), &addr.sin_addr); #else ::inet_pton(AF_INET, host.data(), &addr.sin_addr); #endif } bool Socket::open() { if (is_valid()) return false; fd_ = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); return is_valid(); } void Socket::close() { if (is_valid()) { #if defined(CORO_WIN) ::shutdown(fd_, SD_BOTH); ::closesocket(fd_); #else ::shutdown(fd_, SHUT_RDWR); ::close(fd_); #endif fd_ = kInvalidSocket; } } void Socket::set_nonblocking(bool mode) { if (!is_valid()) return; #if defined(CORO_WIN) u_long flag = mode ? 1 : 0; ::ioctlsocket(fd_, FIONBIO, &flag); #else int flag = ::fcntl(fd_, F_GETFL, 0); flag = (mode ? (flag | O_NONBLOCK) : (flag & ~O_NONBLOCK)); ::fcntl(fd_, F_SETFL, flag); #endif } bool Socket::listen(strv_t host, u16_t port, int backlog) { if (!is_valid()) return false; sockaddr_in addr; init_addr(addr, host, port); if (::bind(fd_, (const sockaddr*)&addr, static_cast<int>(sizeof(addr))) == kSocketError) return false; return ::listen(fd_, backlog) != kSocketError; } bool Socket::connect(strv_t host, u16_t port) { if (!is_valid()) return false; sockaddr_in addr; init_addr(addr, host, port); return ::connect(fd_, (const sockaddr*)&addr, static_cast<int>(sizeof(addr))) != kSocketError; } std::optional<bool> Socket::async_connect(strv_t host, u16_t port) { if (!is_valid()) return {}; sockaddr_in addr; init_addr(addr, host, port); if (auto r = ::connect(fd_, (const sockaddr*)&addr, static_cast<int>(sizeof(addr))); r == kSocketError) { if (auto ec = get_errno(); ec == NEAGAIN || ec == NEWOULDBLOCK) return {false}; return {}; } return {true}; } std::optional<Socket> Socket::accept() { if (!is_valid()) return {}; sockaddr_in addr; socklen_t addr_len = sizeof(addr); if (auto fd = ::accept( fd_, (sockaddr*)&addr, &addr_len); fd != kInvalidSocket) return {fd}; return {}; } std::optional<Socket> Socket::async_accept() { if (!is_valid()) return {}; sockaddr_in addr; socklen_t addr_len = sizeof(addr); if (auto fd = ::accept( fd_, (sockaddr*)&addr, &addr_len); fd != kInvalidSocket) return {fd}; if (auto ec = get_errno(); ec == NEAGAIN || ec == NEWOULDBLOCK) return {kInvalidSocket}; return {}; } sz_t Socket::read(char* buf, sz_t len) { if (!is_valid()) return 0; return static_cast<sz_t>(::recv(fd_, buf, static_cast<int>(len), 0)); } std::optional<sz_t> Socket::async_read(char* buf, sz_t len) { if (!is_valid()) return 0; auto n = ::recv(fd_, buf, static_cast<int>(len), 0); if (n == kSocketError) { if (auto ec = get_errno(); ec == NEAGAIN || ec == NEWOULDBLOCK) return {0}; } else if (n > 0) { return {n}; } return {}; } sz_t Socket::write(const char* buf, sz_t len) { if (!is_valid()) return 0; return static_cast<sz_t>(::send(fd_, buf, static_cast<int>(len), 0)); } std::optional<sz_t> Socket::async_write(const char* buf, sz_t len) { if (!is_valid()) return 0; auto n = ::send(fd_, buf, static_cast<int>(len), 0); if (n == kSocketError) { if (auto ec = get_errno(); ec == NEAGAIN || ec == NEWOULDBLOCK) return {0}; } else if (n > 0) { return {n}; } return {}; } } <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2016 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "AsyncRenderEngine.h" #include "sg/common/FrameBuffer.h" #include "sg/Renderer.h" namespace ospray { AsyncRenderEngine::AsyncRenderEngine(std::shared_ptr<sg::Node> sgRenderer, std::shared_ptr<sg::Node> sgRendererDW) : scenegraph(sgRenderer), scenegraphDW(sgRendererDW) { backgroundThread = make_unique<AsyncLoop>([&](){ if (commitDeviceOnAsyncLoopThread) { auto *device = ospGetCurrentDevice(); if (!device) throw std::runtime_error("could not get the current device!"); ospDeviceCommit(device); // workaround #239 commitDeviceOnAsyncLoopThread = false; } static sg::TimeStamp lastFTime; auto &sgFB = scenegraph->child("frameBuffer"); static bool once = false; //TODO: initial commit as timestamp cannot // be set to 0 static int counter = 0; if (sgFB.childrenLastModified() > lastFTime || !once) { auto &size = sgFB["size"]; nPixels = size.valueAs<vec2i>().x * size.valueAs<vec2i>().y; pixelBuffers.front().resize(nPixels); pixelBuffers.back().resize(nPixels); lastFTime = sg::TimeStamp(); } if (scenegraph->childrenLastModified() > lastRTime || !once) { double time = ospcommon::getSysTime(); scenegraph->traverse("verify"); double verifyTime = ospcommon::getSysTime() - time; time = ospcommon::getSysTime(); scenegraph->traverse("commit"); double commitTime = ospcommon::getSysTime() - time; if (scenegraphDW) { scenegraphDW->traverse("verify"); scenegraphDW->traverse("commit"); } lastRTime = sg::TimeStamp(); } if (scenegraph->hasChild("animationcontroller")) scenegraph->child("animationcontroller").traverse("animate"); if (pickPos.update()) { pickResult = scenegraph->nodeAs<sg::Renderer>()->pick(pickPos.ref()); } fps.start(); scenegraph->traverse("render"); if (scenegraphDW) scenegraphDW->traverse("render"); once = true; fps.stop(); auto sgFBptr = sgFB.nodeAs<sg::FrameBuffer>(); auto *srcPB = (uint32_t*)sgFBptr->map(); auto *dstPB = (uint32_t*)pixelBuffers.back().data(); memcpy(dstPB, srcPB, nPixels*sizeof(uint32_t)); sgFBptr->unmap(srcPB); if (fbMutex.try_lock()) { pixelBuffers.swap(); newPixels = true; fbMutex.unlock(); } }); } AsyncRenderEngine::~AsyncRenderEngine() { stop(); } void AsyncRenderEngine::setFbSize(const ospcommon::vec2i &size) { fbSize = size; } void AsyncRenderEngine::start(int numThreads) { if (state == ExecState::RUNNING) return; numOsprayThreads = numThreads; validate(); if (state == ExecState::INVALID) throw std::runtime_error("Can't start the engine in an invalid state!"); auto device = ospGetCurrentDevice(); if(device == nullptr) throw std::runtime_error("Can't get current device!"); if (numOsprayThreads > 0) ospDeviceSet1i(device, "numThreads", numOsprayThreads); state = ExecState::RUNNING; commitDeviceOnAsyncLoopThread = true; backgroundThread->start(); } void AsyncRenderEngine::stop() { if (state != ExecState::RUNNING) return; state = ExecState::STOPPED; backgroundThread->stop(); } ExecState AsyncRenderEngine::runningState() const { return state; } bool AsyncRenderEngine::hasNewFrame() const { return newPixels; } double AsyncRenderEngine::lastFrameFps() const { return fps.perSecondSmoothed(); } float AsyncRenderEngine::getLastVariance() const { return scenegraph->nodeAs<sg::Renderer>()->getLastVariance(); } void AsyncRenderEngine::pick(const vec2f &screenPos) { pickPos = screenPos; } bool AsyncRenderEngine::hasNewPickResult() { return pickResult.update(); } OSPPickResult AsyncRenderEngine::getPickResult() { return pickResult.get(); } const std::vector<uint32_t> &AsyncRenderEngine::mapFramebuffer() { fbMutex.lock(); newPixels = false; return pixelBuffers.front(); } void AsyncRenderEngine::unmapFramebuffer() { fbMutex.unlock(); } void AsyncRenderEngine::validate() { if (state == ExecState::INVALID) state = ExecState::STOPPED; } }// namespace ospray <commit_msg>cleanup<commit_after>// ======================================================================== // // Copyright 2009-2016 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "AsyncRenderEngine.h" #include "sg/common/FrameBuffer.h" #include "sg/Renderer.h" namespace ospray { AsyncRenderEngine::AsyncRenderEngine(std::shared_ptr<sg::Node> sgRenderer, std::shared_ptr<sg::Node> sgRendererDW) : scenegraph(sgRenderer), scenegraphDW(sgRendererDW) { backgroundThread = make_unique<AsyncLoop>([&](){ if (commitDeviceOnAsyncLoopThread) { auto *device = ospGetCurrentDevice(); if (!device) throw std::runtime_error("could not get the current device!"); ospDeviceCommit(device); // workaround #239 commitDeviceOnAsyncLoopThread = false; } static sg::TimeStamp lastFTime; auto &sgFB = scenegraph->child("frameBuffer"); static bool once = false; //TODO: initial commit as timestamp cannot // be set to 0 static int counter = 0; if (sgFB.childrenLastModified() > lastFTime || !once) { auto &size = sgFB["size"]; nPixels = size.valueAs<vec2i>().x * size.valueAs<vec2i>().y; pixelBuffers.front().resize(nPixels); pixelBuffers.back().resize(nPixels); lastFTime = sg::TimeStamp(); } if (scenegraph->childrenLastModified() > lastRTime || !once) { double time = ospcommon::getSysTime(); scenegraph->traverse("verify"); double verifyTime = ospcommon::getSysTime() - time; time = ospcommon::getSysTime(); scenegraph->traverse("commit"); double commitTime = ospcommon::getSysTime() - time; if (scenegraphDW) { scenegraphDW->traverse("verify"); scenegraphDW->traverse("commit"); } lastRTime = sg::TimeStamp(); } if (scenegraph->hasChild("animationcontroller")) scenegraph->child("animationcontroller").traverse("animate"); if (pickPos.update()) { pickResult = scenegraph->nodeAs<sg::Renderer>()->pick(pickPos.ref()); } fps.start(); scenegraph->traverse("render"); if (scenegraphDW) scenegraphDW->traverse("render"); once = true; fps.stop(); auto sgFBptr = sgFB.nodeAs<sg::FrameBuffer>(); auto *srcPB = (uint32_t*)sgFBptr->map(); auto *dstPB = (uint32_t*)pixelBuffers.back().data(); memcpy(dstPB, srcPB, nPixels*sizeof(uint32_t)); sgFBptr->unmap(srcPB); if (fbMutex.try_lock()) { pixelBuffers.swap(); newPixels = true; fbMutex.unlock(); } }); } AsyncRenderEngine::~AsyncRenderEngine() { stop(); } void AsyncRenderEngine::setFbSize(const ospcommon::vec2i &size) { fbSize = size; } void AsyncRenderEngine::start(int numOsprayThreads) { if (state == ExecState::RUNNING) return; validate(); if (state == ExecState::INVALID) throw std::runtime_error("Can't start the engine in an invalid state!"); if (numOsprayThreads > 0) { auto device = ospGetCurrentDevice(); if(device == nullptr) throw std::runtime_error("Can't get current device!"); ospDeviceSet1i(device, "numThreads", numOsprayThreads); } state = ExecState::RUNNING; commitDeviceOnAsyncLoopThread = true; backgroundThread->start(); } void AsyncRenderEngine::stop() { if (state != ExecState::RUNNING) return; state = ExecState::STOPPED; backgroundThread->stop(); } ExecState AsyncRenderEngine::runningState() const { return state; } bool AsyncRenderEngine::hasNewFrame() const { return newPixels; } double AsyncRenderEngine::lastFrameFps() const { return fps.perSecondSmoothed(); } float AsyncRenderEngine::getLastVariance() const { return scenegraph->nodeAs<sg::Renderer>()->getLastVariance(); } void AsyncRenderEngine::pick(const vec2f &screenPos) { pickPos = screenPos; } bool AsyncRenderEngine::hasNewPickResult() { return pickResult.update(); } OSPPickResult AsyncRenderEngine::getPickResult() { return pickResult.get(); } const std::vector<uint32_t> &AsyncRenderEngine::mapFramebuffer() { fbMutex.lock(); newPixels = false; return pixelBuffers.front(); } void AsyncRenderEngine::unmapFramebuffer() { fbMutex.unlock(); } void AsyncRenderEngine::validate() { if (state == ExecState::INVALID) state = ExecState::STOPPED; } }// namespace ospray <|endoftext|>
<commit_before>// Copyright Amazon.com, Inc. or its affiliates.All Rights Reserved. // SPDX - License - Identifier: Apache - 2.0 // snippet - start: [general.cpp.starter.main] #include <aws/core/Aws.h> #include <aws/core/utils/logging/LogLevel.h> #include <aws/s3/S3Client.h> #include <iostream> using namespace Aws; int main() { //The Aws::SDKOptions struct contains SDK configuration options. //An instance of Aws::SDKOptions is passed to the Aws::InitAPI and //Aws::ShutdownAPI methods. The same instance should be sent to both methods. SDKOptions options; options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug; //The AWS SDK for C++ must be initialized by calling Aws::InitAPI. InitAPI(options); { S3::S3Client client; auto outcome = client.ListBuckets(); if (outcome.IsSuccess()) { std::cout << "Found " << outcome.GetResult().GetBuckets().size() << " buckets\n"; for (auto&& b : outcome.GetResult().GetBuckets()) { std::cout << b.GetName() << std::endl; } } else { std::cout << "Failed with error: " << outcome.GetError() << std::endl; } } //Before the application terminates, the SDK must be shut down. ShutdownAPI(options); return 0; } // snippet - end: [general.cpp.starter.main]<commit_msg>Updating syntax for snippet<commit_after>// Copyright Amazon.com, Inc. or its affiliates.All Rights Reserved. // SPDX - License - Identifier: Apache - 2.0 // snippet-start:[general.cpp.starter.main] #include <aws/core/Aws.h> #include <aws/core/utils/logging/LogLevel.h> #include <aws/s3/S3Client.h> #include <iostream> using namespace Aws; int main() { //The Aws::SDKOptions struct contains SDK configuration options. //An instance of Aws::SDKOptions is passed to the Aws::InitAPI and //Aws::ShutdownAPI methods. The same instance should be sent to both methods. SDKOptions options; options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug; //The AWS SDK for C++ must be initialized by calling Aws::InitAPI. InitAPI(options); { S3::S3Client client; auto outcome = client.ListBuckets(); if (outcome.IsSuccess()) { std::cout << "Found " << outcome.GetResult().GetBuckets().size() << " buckets\n"; for (auto&& b : outcome.GetResult().GetBuckets()) { std::cout << b.GetName() << std::endl; } } else { std::cout << "Failed with error: " << outcome.GetError() << std::endl; } } //Before the application terminates, the SDK must be shut down. ShutdownAPI(options); return 0; } // snippet-end:[general.cpp.starter.main] <|endoftext|>
<commit_before>/* * Copyright (c) 2009-2010 by Bjoern Kolbeck, Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ #include "rpc/client_connection.h" #include <errno.h> #include <boost/bind.hpp> #include <iostream> #include <string> #include <vector> #include "rpc/grid_ssl_socket_channel.h" #include "rpc/ssl_socket_channel.h" #include "rpc/tcp_socket_channel.h" #include "util/logging.h" namespace xtreemfs { namespace rpc { using namespace xtreemfs::pbrpc; using namespace xtreemfs::util; using namespace std; using namespace boost; using namespace google::protobuf; using namespace boost::asio::ip; ClientConnection::ClientConnection( const string& server_name, const string& port, asio::io_service& service, request_map *request_table, int32_t connect_timeout_s, int32_t max_reconnect_interval_s, bool use_gridssl, boost::asio::ssl::context* ssl_context) : receive_marker_(NULL), receive_hdr_(NULL), receive_msg_(NULL), receive_data_(NULL), connection_state_(IDLE), requests_(), current_request_(NULL), server_name_(server_name), server_port_(port), service_(service), resolver_(service), socket_(NULL), endpoint_(NULL), request_table_(request_table), timer_(service), connect_timeout_s_(connect_timeout_s), max_reconnect_interval_s_(max_reconnect_interval_s), next_reconnect_at_(boost::posix_time::not_a_date_time), reconnect_interval_s_(1), use_gridssl_(use_gridssl), ssl_context_(ssl_context) { receive_marker_buffer_ = new char[RecordMarker::get_size()]; CreateChannel(); } void ClientConnection::AddRequest(ClientRequest* request) { requests_.push(request); (*request_table_)[request->call_id()] = request; } void ClientConnection::SendError(POSIXErrno posix_errno, const string &error_message) { if (!requests_.empty()) { Logging::log->getLog(LEVEL_ERROR) << "operation failed: errno=" << posix_errno << " message=" << error_message << endl; RPCHeader::ErrorResponse *err = new RPCHeader::ErrorResponse(); err->set_error_type(IO_ERROR); err->set_posix_errno(posix_errno); err->set_error_message(error_message); while (!requests_.empty()) { ClientRequest *request = requests_.front(); request_table_->erase(request->call_id()); requests_.pop(); request->set_error(new RPCHeader::ErrorResponse(*err)); request->ExecuteCallback(); } delete err; } } void ClientConnection::DoProcess() { last_used_ = posix_time::second_clock::local_time(); if (connection_state_ == IDLE) { if (endpoint_ == NULL) { Connect(); } else { // Do write. SendRequest(); } } else if (connection_state_ == WAIT_FOR_RECONNECT) { posix_time::ptime now = posix_time::second_clock::local_time(); if (next_reconnect_at_ <= now) { next_reconnect_at_ = posix_time::not_a_date_time; if (Logging::log->loggingActive(LEVEL_DEBUG)) { Logging::log->getLog(LEVEL_DEBUG) << "trying reconnect..." << endl; } Connect(); } else { SendError(POSIX_ERROR_EIO, "cannot connect to server '" + server_name_ + ":" + server_port_ + "', reconnect blocked"); } } } void ClientConnection::CreateChannel() { if (socket_ != NULL) { socket_->close(); delete socket_; } if (ssl_context_ == NULL) { socket_ = new TCPSocketChannel(service_); } else if (use_gridssl_) { socket_ = new GridSSLSocketChannel(service_, *ssl_context_); } else { socket_ = new SSLSocketChannel(service_, *ssl_context_); } } void ClientConnection::Connect() { connection_state_ = CONNECTING; asio::ip::tcp::resolver::query query(server_name_, server_port_); resolver_.async_resolve(query, bind(&ClientConnection::PostResolve, this, asio::placeholders::error, asio::placeholders::iterator)); if (Logging::log->loggingActive(LEVEL_DEBUG)) { Logging::log->getLog(LEVEL_DEBUG) << "connect timeout is " << connect_timeout_s_ << " seconds\n"; } } void ClientConnection::OnConnectTimeout(const boost::system::error_code& err) { if (err != asio::error::operation_aborted) { Reset(); SendError(POSIX_ERROR_EIO, "connection to '" + server_name_ + ":" + server_port_ + "' timed out"); } } void ClientConnection::PostResolve( const boost::system::error_code& err, tcp::resolver::iterator endpoint_iterator) { if (err) { Reset(); SendError(POSIX_ERROR_EIO, "could not connect to '" + server_name_ + ":" + server_port_ + "': " + err.message()); } if (endpoint_iterator != tcp::resolver::iterator()) { if (Logging::log->loggingActive(LEVEL_DEBUG)) { Logging::log->getLog(LEVEL_DEBUG) << "resolved: " << (*endpoint_iterator).host_name() << endl; } endpoint_ = new tcp::endpoint(*endpoint_iterator); timer_.expires_from_now(posix_time::seconds(connect_timeout_s_)); timer_.async_wait(bind(&ClientConnection::OnConnectTimeout, this, asio::placeholders::error)); socket_->async_connect(*endpoint_, bind(&ClientConnection::PostConnect, this, asio::placeholders::error, endpoint_iterator)); } else { SendError(POSIX_ERROR_EINVAL, string("cannot resolve hostname: '") + this->server_name_ + ":" + server_port_ + string("'")); } } void ClientConnection::PostConnect( const boost::system::error_code& err, tcp::resolver::iterator endpoint_iterator) { timer_.cancel(); if (err) { if (err == asio::error::operation_aborted) { return; } delete endpoint_; endpoint_ = NULL; if (++endpoint_iterator != tcp::resolver::iterator()) { // Try next endpoint. CreateChannel(); if (Logging::log->loggingActive(LEVEL_DEBUG)) { Logging::log->getLog(LEVEL_DEBUG) << "failed: next endpoint" << err.message() << "\n"; } PostResolve(err, endpoint_iterator); } else { Reset(); string ssl_error_info; if (err.category() == asio::error::ssl_category) { ssl_error_info = ERR_error_string(ERR_get_error(), NULL); } SendError(POSIX_ERROR_EIO, "could not connect to host '" + server_name_ + ":" + server_port_ + "': " + err.message()+" "+ssl_error_info); } } else { // Do something useful. reconnect_interval_s_ = 1; next_reconnect_at_ = posix_time::not_a_date_time; if (Logging::log->loggingActive(LEVEL_DEBUG)) { Logging::log->getLog(LEVEL_DEBUG) << "connected to " << (*endpoint_iterator).host_name() << ":" << (*endpoint_iterator).service_name() << endl; } connection_state_ = IDLE; if (!requests_.empty()) { SendRequest(); ReceiveRequest(); } } } void ClientConnection::SendRequest() { if (!requests_.empty()) { connection_state_ = ACTIVE; ClientRequest* rq = requests_.front(); assert(rq != NULL); if (rq->cancelled()) { delete rq; // The element must be poped from the queue. requests_.pop(); SendRequest(); } const RecordMarker* rrm = rq->request_marker(); vector<boost::asio::const_buffer> bufs; bufs.push_back(boost::asio::buffer( reinterpret_cast<const void*>(rq->rq_hdr_msg()), RecordMarker::get_size() + rrm->header_len() + rrm->message_len())); if (rrm->data_len() > 0) { bufs.push_back(boost::asio::buffer( reinterpret_cast<const void*> (rq->rq_data()), rrm->data_len())); } socket_->async_write(bufs, bind(&ClientConnection::PostWrite, this, asio::placeholders::error, asio::placeholders::bytes_transferred)); } else { connection_state_ = IDLE; } } void ClientConnection::ReceiveRequest() { if (endpoint_) { socket_->async_read(asio::buffer(receive_marker_buffer_, RecordMarker::get_size()), bind(&ClientConnection::PostReadRecordMarker, this, asio::placeholders::error)); } } void ClientConnection::Reset() { CreateChannel(); delete endpoint_; endpoint_ = NULL; connection_state_ = WAIT_FOR_RECONNECT; if (Logging::log->loggingActive(LEVEL_DEBUG)) { Logging::log->getLog(LEVEL_DEBUG) << "connection reset, next reconnect in " << reconnect_interval_s_ << "s " << endl; } next_reconnect_at_ = posix_time::second_clock::local_time() + posix_time::seconds(reconnect_interval_s_); reconnect_interval_s_ = reconnect_interval_s_ * 2; if (reconnect_interval_s_ > max_reconnect_interval_s_) { reconnect_interval_s_ = max_reconnect_interval_s_; } } void ClientConnection::Close() { socket_->close(); delete socket_; socket_ = NULL; connection_state_ = CLOSED; SendError(POSIX_ERROR_EIO, "connection to '" + server_name_ + ":" + server_port_ + "' closed" " locally"); } void ClientConnection::PostWrite(const boost::system::error_code& err, size_t bytes_written) { if (err) { Reset(); SendError(POSIX_ERROR_EIO, "could not send request to '" + server_name_ + ":" +server_port_ + "': " + err.message()); } else { // Send next? requests_.pop(); connection_state_ = IDLE; SendRequest(); } } void ClientConnection::PostReadRecordMarker( const boost::system::error_code& err) { if (err) { Reset(); SendError(POSIX_ERROR_EIO, "could not read record marker in response from '" + server_name_ + ":" + server_port_ + "': " + err.message()); } else { // Do read. receive_marker_ = new RecordMarker(receive_marker_buffer_); vector<boost::asio::mutable_buffer> bufs; receive_hdr_ = new char[receive_marker_->header_len()]; bufs.push_back(asio::buffer(reinterpret_cast<void*> (receive_hdr_), receive_marker_->header_len())); if (receive_marker_->message_len() > 0) { receive_msg_ = new char[receive_marker_->message_len()]; bufs.push_back(asio::buffer(reinterpret_cast<void*> (receive_msg_), receive_marker_->message_len())); } else { receive_msg_ = NULL; } if (receive_marker_->data_len() > 0) { receive_data_ = new char[receive_marker_->data_len()]; bufs.push_back(asio::buffer(reinterpret_cast<void*> (receive_data_), receive_marker_->data_len())); } else { receive_data_ = NULL; } socket_->async_read(bufs, bind(&ClientConnection::PostReadMessage, this, asio::placeholders::error)); } } void ClientConnection::PostReadMessage(const boost::system::error_code& err) { if (err) { DeleteInternalBuffers(); Reset(); SendError(POSIX_ERROR_EIO, "could not read response from '" + server_name_ + ":" + server_port_ + "': " + err.message()); } else { // Parse header. RPCHeader *respHdr = new RPCHeader(); if (respHdr->ParseFromArray(receive_hdr_, receive_marker_->header_len())) { delete[] receive_hdr_; receive_hdr_ = NULL; } else { // Error parsing the header. DeleteInternalBuffers(); delete respHdr; Reset(); SendError(POSIX_ERROR_EINVAL, "received garbage header from '" + server_name_ + ":" + server_port_ + "', closing connection"); return; } // Get request from table. request_map::iterator iter = request_table_->find(respHdr->call_id()); ClientRequest *rq; if (iter != request_table_->end()) { rq = iter->second; } else { if (Logging::log->loggingActive(LEVEL_WARN)) { Logging::log->getLog(LEVEL_WARN) << "Received response for unknown request id: " << respHdr->call_id() << " from " << server_name_ << std::endl; } DeleteInternalBuffers(); delete respHdr; return; } uint32 call_id = respHdr->call_id(); if (respHdr->has_error_response()) { // Error response. rq->set_error(new RPCHeader::ErrorResponse(respHdr->error_response())); // Manually cleanup response header. delete respHdr; } else { // Parse message, if exists. if (receive_marker_->message_len() > 0) { if (!rq->resp_message()) { // Not prepared to receive a message. // Print error and discard data. Logging::log->getLog(LEVEL_WARN) << "Received an unexpected response message (expected size 0, got " << receive_marker_->message_len() << " bytes) from " << server_name_ << std::endl; } else { assert(receive_msg_ != NULL); if (!rq->resp_message()->ParseFromArray( receive_msg_, receive_marker_->message_len())) { // Parsing message failed. Generate error. RPCHeader::ErrorResponse *err = new RPCHeader::ErrorResponse(); err->set_error_type(GARBAGE_ARGS); err->set_posix_errno(POSIX_ERROR_NONE); err->set_error_message(string("cannot parse message data: ") + rq->resp_message()->InitializationErrorString()); rq->set_error(err); // manually cleanup response header delete respHdr; } else { // Message successfully parsed, set data. // Hand over responsibility for receive_data_ to request object. rq->set_resp_data(receive_data_); rq->set_resp_data_len(receive_marker_->data_len()); receive_data_ = NULL; } } } // Always set response header. rq->set_resp_header(respHdr); } // Remove from table and clean up buffers. request_table_->erase(call_id); DeleteInternalBuffers(); rq->ExecuteCallback(); // Receive next request. ReceiveRequest(); } } void ClientConnection::DeleteInternalBuffers() { delete[] receive_hdr_; receive_hdr_ = NULL; delete[] receive_msg_; receive_msg_ = NULL; delete[] receive_data_; receive_data_ = NULL; delete receive_marker_; receive_marker_ = NULL; } ClientConnection::~ClientConnection() { delete endpoint_; delete socket_; delete[] receive_marker_buffer_; DeleteInternalBuffers(); } } // namespace rpc } // namespace xtreemfs <commit_msg>client: added fix for crash on connection close in the RPC client.<commit_after>/* * Copyright (c) 2009-2010 by Bjoern Kolbeck, Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ #include "rpc/client_connection.h" #include <errno.h> #include <boost/bind.hpp> #include <iostream> #include <string> #include <vector> #include "rpc/grid_ssl_socket_channel.h" #include "rpc/ssl_socket_channel.h" #include "rpc/tcp_socket_channel.h" #include "util/logging.h" namespace xtreemfs { namespace rpc { using namespace xtreemfs::pbrpc; using namespace xtreemfs::util; using namespace std; using namespace boost; using namespace google::protobuf; using namespace boost::asio::ip; ClientConnection::ClientConnection( const string& server_name, const string& port, asio::io_service& service, request_map *request_table, int32_t connect_timeout_s, int32_t max_reconnect_interval_s, bool use_gridssl, boost::asio::ssl::context* ssl_context) : receive_marker_(NULL), receive_hdr_(NULL), receive_msg_(NULL), receive_data_(NULL), connection_state_(IDLE), requests_(), current_request_(NULL), server_name_(server_name), server_port_(port), service_(service), resolver_(service), socket_(NULL), endpoint_(NULL), request_table_(request_table), timer_(service), connect_timeout_s_(connect_timeout_s), max_reconnect_interval_s_(max_reconnect_interval_s), next_reconnect_at_(boost::posix_time::not_a_date_time), reconnect_interval_s_(1), use_gridssl_(use_gridssl), ssl_context_(ssl_context) { receive_marker_buffer_ = new char[RecordMarker::get_size()]; CreateChannel(); } void ClientConnection::AddRequest(ClientRequest* request) { requests_.push(request); (*request_table_)[request->call_id()] = request; } void ClientConnection::SendError(POSIXErrno posix_errno, const string &error_message) { if (!requests_.empty()) { Logging::log->getLog(LEVEL_ERROR) << "operation failed: errno=" << posix_errno << " message=" << error_message << endl; RPCHeader::ErrorResponse *err = new RPCHeader::ErrorResponse(); err->set_error_type(IO_ERROR); err->set_posix_errno(posix_errno); err->set_error_message(error_message); while (!requests_.empty()) { ClientRequest *request = requests_.front(); request_table_->erase(request->call_id()); requests_.pop(); request->set_error(new RPCHeader::ErrorResponse(*err)); request->ExecuteCallback(); } delete err; } } void ClientConnection::DoProcess() { last_used_ = posix_time::second_clock::local_time(); if (connection_state_ == IDLE) { if (endpoint_ == NULL) { Connect(); } else { // Do write. SendRequest(); } } else if (connection_state_ == WAIT_FOR_RECONNECT) { posix_time::ptime now = posix_time::second_clock::local_time(); if (next_reconnect_at_ <= now) { next_reconnect_at_ = posix_time::not_a_date_time; if (Logging::log->loggingActive(LEVEL_DEBUG)) { Logging::log->getLog(LEVEL_DEBUG) << "trying reconnect..." << endl; } Connect(); } else { SendError(POSIX_ERROR_EIO, "cannot connect to server '" + server_name_ + ":" + server_port_ + "', reconnect blocked"); } } } void ClientConnection::CreateChannel() { if (socket_ != NULL) { socket_->close(); delete socket_; } if (ssl_context_ == NULL) { socket_ = new TCPSocketChannel(service_); } else if (use_gridssl_) { socket_ = new GridSSLSocketChannel(service_, *ssl_context_); } else { socket_ = new SSLSocketChannel(service_, *ssl_context_); } } void ClientConnection::Connect() { connection_state_ = CONNECTING; asio::ip::tcp::resolver::query query(server_name_, server_port_); resolver_.async_resolve(query, bind(&ClientConnection::PostResolve, this, asio::placeholders::error, asio::placeholders::iterator)); if (Logging::log->loggingActive(LEVEL_DEBUG)) { Logging::log->getLog(LEVEL_DEBUG) << "connect timeout is " << connect_timeout_s_ << " seconds\n"; } } void ClientConnection::OnConnectTimeout(const boost::system::error_code& err) { if (err != asio::error::operation_aborted) { Reset(); SendError(POSIX_ERROR_EIO, "connection to '" + server_name_ + ":" + server_port_ + "' timed out"); } } void ClientConnection::PostResolve( const boost::system::error_code& err, tcp::resolver::iterator endpoint_iterator) { if (err) { Reset(); SendError(POSIX_ERROR_EIO, "could not connect to '" + server_name_ + ":" + server_port_ + "': " + err.message()); } if (endpoint_iterator != tcp::resolver::iterator()) { if (Logging::log->loggingActive(LEVEL_DEBUG)) { Logging::log->getLog(LEVEL_DEBUG) << "resolved: " << (*endpoint_iterator).host_name() << endl; } endpoint_ = new tcp::endpoint(*endpoint_iterator); timer_.expires_from_now(posix_time::seconds(connect_timeout_s_)); timer_.async_wait(bind(&ClientConnection::OnConnectTimeout, this, asio::placeholders::error)); socket_->async_connect(*endpoint_, bind(&ClientConnection::PostConnect, this, asio::placeholders::error, endpoint_iterator)); } else { SendError(POSIX_ERROR_EINVAL, string("cannot resolve hostname: '") + this->server_name_ + ":" + server_port_ + string("'")); } } void ClientConnection::PostConnect( const boost::system::error_code& err, tcp::resolver::iterator endpoint_iterator) { timer_.cancel(); if (err) { if (err == asio::error::operation_aborted) { return; } delete endpoint_; endpoint_ = NULL; if (++endpoint_iterator != tcp::resolver::iterator()) { // Try next endpoint. CreateChannel(); if (Logging::log->loggingActive(LEVEL_DEBUG)) { Logging::log->getLog(LEVEL_DEBUG) << "failed: next endpoint" << err.message() << "\n"; } PostResolve(err, endpoint_iterator); } else { Reset(); string ssl_error_info; if (err.category() == asio::error::ssl_category) { ssl_error_info = ERR_error_string(ERR_get_error(), NULL); } SendError(POSIX_ERROR_EIO, "could not connect to host '" + server_name_ + ":" + server_port_ + "': " + err.message()+" "+ssl_error_info); } } else { // Do something useful. reconnect_interval_s_ = 1; next_reconnect_at_ = posix_time::not_a_date_time; if (Logging::log->loggingActive(LEVEL_DEBUG)) { Logging::log->getLog(LEVEL_DEBUG) << "connected to " << (*endpoint_iterator).host_name() << ":" << (*endpoint_iterator).service_name() << endl; } connection_state_ = IDLE; if (!requests_.empty()) { SendRequest(); ReceiveRequest(); } } } void ClientConnection::SendRequest() { if (!requests_.empty()) { connection_state_ = ACTIVE; ClientRequest* rq = requests_.front(); assert(rq != NULL); if (rq->cancelled()) { delete rq; // The element must be poped from the queue. requests_.pop(); SendRequest(); } const RecordMarker* rrm = rq->request_marker(); vector<boost::asio::const_buffer> bufs; bufs.push_back(boost::asio::buffer( reinterpret_cast<const void*>(rq->rq_hdr_msg()), RecordMarker::get_size() + rrm->header_len() + rrm->message_len())); if (rrm->data_len() > 0) { bufs.push_back(boost::asio::buffer( reinterpret_cast<const void*> (rq->rq_data()), rrm->data_len())); } socket_->async_write(bufs, bind(&ClientConnection::PostWrite, this, asio::placeholders::error, asio::placeholders::bytes_transferred)); } else { connection_state_ = IDLE; } } void ClientConnection::ReceiveRequest() { if (endpoint_) { socket_->async_read(asio::buffer(receive_marker_buffer_, RecordMarker::get_size()), bind(&ClientConnection::PostReadRecordMarker, this, asio::placeholders::error)); } } void ClientConnection::Reset() { CreateChannel(); delete endpoint_; endpoint_ = NULL; connection_state_ = WAIT_FOR_RECONNECT; if (Logging::log->loggingActive(LEVEL_DEBUG)) { Logging::log->getLog(LEVEL_DEBUG) << "connection reset, next reconnect in " << reconnect_interval_s_ << "s " << endl; } next_reconnect_at_ = posix_time::second_clock::local_time() + posix_time::seconds(reconnect_interval_s_); reconnect_interval_s_ = reconnect_interval_s_ * 2; if (reconnect_interval_s_ > max_reconnect_interval_s_) { reconnect_interval_s_ = max_reconnect_interval_s_; } } void ClientConnection::Close() { socket_->close(); delete socket_; socket_ = NULL; connection_state_ = CLOSED; SendError(POSIX_ERROR_EIO, "connection to '" + server_name_ + ":" + server_port_ + "' closed" " locally"); } void ClientConnection::PostWrite(const boost::system::error_code& err, size_t bytes_written) { if (err) { Reset(); SendError(POSIX_ERROR_EIO, "could not send request to '" + server_name_ + ":" +server_port_ + "': " + err.message()); } else { // Send next? requests_.pop(); connection_state_ = IDLE; SendRequest(); } } void ClientConnection::PostReadRecordMarker( const boost::system::error_code& err) { if (err) { if (err == boost::asio::error::operation_aborted) { // Connection was closed. Ignore error. return; } Reset(); SendError(POSIX_ERROR_EIO, "could not read record marker in response from '" + server_name_ + ":" + server_port_ + "': " + err.message()); } else { // Do read. receive_marker_ = new RecordMarker(receive_marker_buffer_); vector<boost::asio::mutable_buffer> bufs; receive_hdr_ = new char[receive_marker_->header_len()]; bufs.push_back(asio::buffer(reinterpret_cast<void*> (receive_hdr_), receive_marker_->header_len())); if (receive_marker_->message_len() > 0) { receive_msg_ = new char[receive_marker_->message_len()]; bufs.push_back(asio::buffer(reinterpret_cast<void*> (receive_msg_), receive_marker_->message_len())); } else { receive_msg_ = NULL; } if (receive_marker_->data_len() > 0) { receive_data_ = new char[receive_marker_->data_len()]; bufs.push_back(asio::buffer(reinterpret_cast<void*> (receive_data_), receive_marker_->data_len())); } else { receive_data_ = NULL; } socket_->async_read(bufs, bind(&ClientConnection::PostReadMessage, this, asio::placeholders::error)); } } void ClientConnection::PostReadMessage(const boost::system::error_code& err) { if (err) { DeleteInternalBuffers(); Reset(); SendError(POSIX_ERROR_EIO, "could not read response from '" + server_name_ + ":" + server_port_ + "': " + err.message()); } else { // Parse header. RPCHeader *respHdr = new RPCHeader(); if (respHdr->ParseFromArray(receive_hdr_, receive_marker_->header_len())) { delete[] receive_hdr_; receive_hdr_ = NULL; } else { // Error parsing the header. DeleteInternalBuffers(); delete respHdr; Reset(); SendError(POSIX_ERROR_EINVAL, "received garbage header from '" + server_name_ + ":" + server_port_ + "', closing connection"); return; } // Get request from table. request_map::iterator iter = request_table_->find(respHdr->call_id()); ClientRequest *rq; if (iter != request_table_->end()) { rq = iter->second; } else { if (Logging::log->loggingActive(LEVEL_WARN)) { Logging::log->getLog(LEVEL_WARN) << "Received response for unknown request id: " << respHdr->call_id() << " from " << server_name_ << std::endl; } DeleteInternalBuffers(); delete respHdr; return; } uint32 call_id = respHdr->call_id(); if (respHdr->has_error_response()) { // Error response. rq->set_error(new RPCHeader::ErrorResponse(respHdr->error_response())); // Manually cleanup response header. delete respHdr; } else { // Parse message, if exists. if (receive_marker_->message_len() > 0) { if (!rq->resp_message()) { // Not prepared to receive a message. // Print error and discard data. Logging::log->getLog(LEVEL_WARN) << "Received an unexpected response message (expected size 0, got " << receive_marker_->message_len() << " bytes) from " << server_name_ << std::endl; } else { assert(receive_msg_ != NULL); if (!rq->resp_message()->ParseFromArray( receive_msg_, receive_marker_->message_len())) { // Parsing message failed. Generate error. RPCHeader::ErrorResponse *err = new RPCHeader::ErrorResponse(); err->set_error_type(GARBAGE_ARGS); err->set_posix_errno(POSIX_ERROR_NONE); err->set_error_message(string("cannot parse message data: ") + rq->resp_message()->InitializationErrorString()); rq->set_error(err); // manually cleanup response header delete respHdr; } else { // Message successfully parsed, set data. // Hand over responsibility for receive_data_ to request object. rq->set_resp_data(receive_data_); rq->set_resp_data_len(receive_marker_->data_len()); receive_data_ = NULL; } } } // Always set response header. rq->set_resp_header(respHdr); } // Remove from table and clean up buffers. request_table_->erase(call_id); DeleteInternalBuffers(); rq->ExecuteCallback(); // Receive next request. ReceiveRequest(); } } void ClientConnection::DeleteInternalBuffers() { delete[] receive_hdr_; receive_hdr_ = NULL; delete[] receive_msg_; receive_msg_ = NULL; delete[] receive_data_; receive_data_ = NULL; delete receive_marker_; receive_marker_ = NULL; } ClientConnection::~ClientConnection() { delete endpoint_; delete socket_; delete[] receive_marker_buffer_; DeleteInternalBuffers(); } } // namespace rpc } // namespace xtreemfs <|endoftext|>
<commit_before>/** \brief Utility for validating and fixing up records harvested by zts_harvester * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2018-2020 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <map> #include <unordered_set> #include <cstdio> #include <cstdlib> #include "Compiler.h" #include "DbConnection.h" #include "DbResultSet.h" #include "DnsUtil.h" #include "EmailSender.h" #include "IniFile.h" #include "MARC.h" #include "UBTools.h" #include "util.h" namespace { [[noreturn]] void Usage() { ::Usage("(marc_input marc_output missed_expectations_file email_address)|(update_db journal_name field_name field_presence)\n" "\tThis tool has two operating modes 1) checking MARC data for missed expectations and 2) altering these expectations.\n" "\tin the \"update_db\" mode, \"field_name\" must be a 3-character MARC tag and \"field_presence\" must be one of\n" "\tALWAYS, SOMETIMES, IGNORE. Please note that only existing entries can be changed!"); } enum FieldPresence { ALWAYS, SOMETIMES, IGNORE }; bool StringToFieldPresence(const std::string &field_presence_str, FieldPresence * const field_presence) { if (field_presence_str == "ALWAYS") { *field_presence = ALWAYS; return true; } if (field_presence_str == "SOMETIMES") { *field_presence = SOMETIMES; return true; } if (field_presence_str == "IGNORE") { *field_presence = IGNORE; return true; } return false; } struct FieldInfo { std::string name_; FieldPresence presence_; public: FieldInfo(const std::string &name, const FieldPresence presence): name_(name), presence_(presence) { } }; class JournalInfo { bool not_in_database_yet_; std::vector<FieldInfo> field_infos_; public: using const_iterator = std::vector<FieldInfo>::const_iterator; using iterator = std::vector<FieldInfo>::iterator; public: explicit JournalInfo(const bool not_in_database_yet): not_in_database_yet_(not_in_database_yet) { } JournalInfo() = default; JournalInfo(const JournalInfo &rhs) = default; size_t size() const { return field_infos_.size(); } bool isInDatabase() const { return not not_in_database_yet_; } void addField(const std::string &field_name, const FieldPresence field_presence) { field_infos_.emplace_back(field_name, field_presence); } const_iterator begin() const { return field_infos_.cbegin(); } const_iterator end() const { return field_infos_.cend(); } iterator begin() { return field_infos_.begin(); } iterator end() { return field_infos_.end(); } iterator find(const std::string &field_name) { return std::find_if(field_infos_.begin(), field_infos_.end(), [&field_name](const FieldInfo &field_info){ return field_name == field_info.name_; }); } }; FieldPresence StringToFieldPresence(const std::string &s) { if (s == "always") return ALWAYS; if (s == "sometimes") return SOMETIMES; if (s == "ignore") return IGNORE; LOG_ERROR("unknown enumerated value \"" + s + "\"!"); } std::string FieldPresenceToString(const FieldPresence field_presence) { switch (field_presence) { case ALWAYS: return "always"; case SOMETIMES: return "sometimes"; case IGNORE: return "ignore"; default: LOG_ERROR("we should *never get here!"); } } void LoadFromDatabaseOrCreateFromScratch(DbConnection * const db_connection, const std::string &journal_name, JournalInfo * const journal_info) { db_connection->queryOrDie("SELECT metadata_field_name,field_presence FROM metadata_presence_tracer WHERE journal_name='" + db_connection->escapeString(journal_name) + "'"); DbResultSet result_set(db_connection->getLastResultSet()); if (result_set.empty()) { LOG_INFO("\"" + journal_name + "\" was not yet in the database."); *journal_info = JournalInfo(/* not_in_database_yet = */true); return; } *journal_info = JournalInfo(/* not_in_database_yet = */false); while (auto row = result_set.getNextRow()) journal_info->addField(row["metadata_field_name"], StringToFieldPresence(row["field_presence"])); } // Two-way mapping required as the map is uni-directional const std::map<std::string, std::string> EQUIVALENT_TAGS_MAP{ { "700", "100" }, { "100", "700" } }; void AnalyseNewJournalRecord(const MARC::Record &record, const bool first_record, JournalInfo * const journal_info) { std::unordered_set<std::string> seen_tags; MARC::Tag last_tag; for (const auto &field : record) { auto current_tag(field.getTag()); if (current_tag == last_tag) continue; seen_tags.emplace(current_tag.toString()); if (first_record) journal_info->addField(current_tag.toString(), ALWAYS); else if (journal_info->find(current_tag.toString()) == journal_info->end()) journal_info->addField(current_tag.toString(), SOMETIMES); last_tag = current_tag; } for (auto &field_info : *journal_info) { if (seen_tags.find(field_info.name_) == seen_tags.end()) field_info.presence_ = SOMETIMES; } } bool RecordMeetsExpectations(const MARC::Record &record, const std::string &journal_name, const JournalInfo &journal_info) { std::unordered_set<std::string> seen_tags; MARC::Tag last_tag; for (const auto &field : record) { const auto current_tag(field.getTag()); if (current_tag == last_tag) continue; seen_tags.emplace(current_tag.toString()); last_tag = current_tag; } bool missed_at_least_one_expectation(false); for (const auto &field_info : journal_info) { if (field_info.presence_ != ALWAYS) continue; // we only care about required fields that are missing const auto equivalent_tag(EQUIVALENT_TAGS_MAP.find(field_info.name_)); if (seen_tags.find(field_info.name_) != seen_tags.end()) ;// required tag found else if (equivalent_tag != EQUIVALENT_TAGS_MAP.end() and seen_tags.find(equivalent_tag->second) != seen_tags.end()) ;// equivalent tag found else { LOG_WARNING("Record w/ control number " + record.getControlNumber() + " in \"" + journal_name + "\" is missing the always expected " + field_info.name_ + " field."); missed_at_least_one_expectation = true; } } return not missed_at_least_one_expectation; } void WriteToDatabase(DbConnection * const db_connection, const std::string &journal_name, const JournalInfo &journal_info) { for (const auto &field_info : journal_info) db_connection->queryOrDie("INSERT INTO metadata_presence_tracer SET journal_name='" + journal_name + "', metadata_field_name='" + db_connection->escapeString(field_info.name_) + "', field_presence='" + FieldPresenceToString(field_info.presence_) + "'"); } void SendEmail(const std::string &email_address, const std::string &message_subject, const std::string &message_body) { const auto reply_code(EmailSender::SendEmail("zts_harvester_delivery_pipeline@uni-tuebingen.de", email_address, message_subject, message_body, EmailSender::MEDIUM, EmailSender::PLAIN_TEXT, /* reply_to = */ "", /* use_ssl = */ true, /* use_authentication = */ true)); if (reply_code >= 300) LOG_WARNING("failed to send email, the response code was: " + std::to_string(reply_code)); } void UpdateDB(DbConnection * const db_connection, const std::string &journal_name, const std::string &field_name, const std::string &field_presence_str) { FieldPresence field_presence; if (not StringToFieldPresence(field_presence_str, &field_presence)) LOG_ERROR("\"" + field_presence_str + "\" is not a valid field_presence!"); if (field_name.length() != MARC::Record::TAG_LENGTH) LOG_ERROR("\"" + field_name + "\" is not a valid field name!"); DbTransaction transcation(db_connection); db_connection->queryOrDie("SELECT field_presence FROM metadata_presence_tracer WHERE journal_name=" + db_connection->escapeAndQuoteString(journal_name) + " AND field_name='" + field_name + "'"); const DbResultSet result_set(db_connection->getLastResultSet()); if (result_set.empty()) LOG_ERROR("can't update non-existent database entry!"); db_connection->queryOrDie("UPDATE metadata_presence_tracer SET field_presence='" + field_presence_str + "' WHERE journal_name=" + db_connection->escapeAndQuoteString(journal_name) + " AND field_name='" + field_name + "'"); } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc != 5) Usage(); DbConnection db_connection; if (std::strcmp(argv[1], "update_db") == 0) { UpdateDB(&db_connection, argv[2], argv[3], argv[4]); return EXIT_SUCCESS; } auto reader(MARC::Reader::Factory(argv[1])); auto valid_records_writer(MARC::Writer::Factory(argv[2])); auto delinquent_records_writer(MARC::Writer::Factory(argv[3])); std::map<std::string, JournalInfo> journal_name_to_info_map; const std::string email_address(argv[4]); unsigned total_record_count(0), new_record_count(0), missed_expectation_count(0); while (const auto record = reader->read()) { ++total_record_count; bool validation_failed(false); // Intentionally true to allow early breaking while (true) { const auto journal_name(record.getSuperiorTitle()); if (journal_name.empty()) { LOG_WARNING("Record w/ control number \"" + record.getControlNumber() + "\" is missing a superior title!"); validation_failed = true; break; } auto journal_name_and_info(journal_name_to_info_map.find(journal_name)); bool first_record(false); // True if the current record is the first encounter of a journal if (journal_name_and_info == journal_name_to_info_map.end()) { first_record = true; JournalInfo new_journal_info; LoadFromDatabaseOrCreateFromScratch(&db_connection, journal_name, &new_journal_info); journal_name_to_info_map[journal_name] = new_journal_info; journal_name_and_info = journal_name_to_info_map.find(journal_name); } if (journal_name_and_info->second.isInDatabase()) { if (not RecordMeetsExpectations(record, journal_name_and_info->first, journal_name_and_info->second)) { validation_failed = true; ++missed_expectation_count; break; } } else { AnalyseNewJournalRecord(record, first_record, &journal_name_and_info->second); ++new_record_count; } // Break unconditionally break; } if (validation_failed) delinquent_records_writer->write(record); else valid_records_writer->write(record); } for (const auto &journal_name_and_info : journal_name_to_info_map) { if (not journal_name_and_info.second.isInDatabase()) WriteToDatabase(&db_connection, journal_name_and_info.first, journal_name_and_info.second); } if (missed_expectation_count > 0) { // send notification to the email address SendEmail(email_address, "validate_harvested_records encountered warnings (from: " + DnsUtil::GetHostname() + ")", "Some records missed expectations with respect to MARC fields. " "Check the log at '/usr/local/var/log/tuefind/zts_harvester_delivery_pipeline.log' for details."); } LOG_INFO("Processed " + std::to_string(total_record_count) + " record(s) of which " + std::to_string(new_record_count) + " was/were (a) record(s) of new journals and " + std::to_string(missed_expectation_count) + " record(s) missed expectations."); return EXIT_SUCCESS; } <commit_msg>validate_harvested_records.cc: Use function instead of infinite while loop with early breaks<commit_after>/** \brief Utility for validating and fixing up records harvested by zts_harvester * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2018-2020 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <map> #include <unordered_set> #include <cstdio> #include <cstdlib> #include "Compiler.h" #include "DbConnection.h" #include "DbResultSet.h" #include "DnsUtil.h" #include "EmailSender.h" #include "IniFile.h" #include "MARC.h" #include "UBTools.h" #include "util.h" namespace { [[noreturn]] void Usage() { ::Usage("(marc_input marc_output missed_expectations_file email_address)|(update_db journal_name field_name field_presence)\n" "\tThis tool has two operating modes 1) checking MARC data for missed expectations and 2) altering these expectations.\n" "\tin the \"update_db\" mode, \"field_name\" must be a 3-character MARC tag and \"field_presence\" must be one of\n" "\tALWAYS, SOMETIMES, IGNORE. Please note that only existing entries can be changed!"); } enum FieldPresence { ALWAYS, SOMETIMES, IGNORE }; bool StringToFieldPresence(const std::string &field_presence_str, FieldPresence * const field_presence) { if (field_presence_str == "ALWAYS") { *field_presence = ALWAYS; return true; } if (field_presence_str == "SOMETIMES") { *field_presence = SOMETIMES; return true; } if (field_presence_str == "IGNORE") { *field_presence = IGNORE; return true; } return false; } struct FieldInfo { std::string name_; FieldPresence presence_; public: FieldInfo(const std::string &name, const FieldPresence presence): name_(name), presence_(presence) { } }; class JournalInfo { bool not_in_database_yet_; std::vector<FieldInfo> field_infos_; public: using const_iterator = std::vector<FieldInfo>::const_iterator; using iterator = std::vector<FieldInfo>::iterator; public: explicit JournalInfo(const bool not_in_database_yet): not_in_database_yet_(not_in_database_yet) { } JournalInfo() = default; JournalInfo(const JournalInfo &rhs) = default; size_t size() const { return field_infos_.size(); } bool isInDatabase() const { return not not_in_database_yet_; } void addField(const std::string &field_name, const FieldPresence field_presence) { field_infos_.emplace_back(field_name, field_presence); } const_iterator begin() const { return field_infos_.cbegin(); } const_iterator end() const { return field_infos_.cend(); } iterator begin() { return field_infos_.begin(); } iterator end() { return field_infos_.end(); } iterator find(const std::string &field_name) { return std::find_if(field_infos_.begin(), field_infos_.end(), [&field_name](const FieldInfo &field_info){ return field_name == field_info.name_; }); } }; FieldPresence StringToFieldPresence(const std::string &s) { if (s == "always") return ALWAYS; if (s == "sometimes") return SOMETIMES; if (s == "ignore") return IGNORE; LOG_ERROR("unknown enumerated value \"" + s + "\"!"); } std::string FieldPresenceToString(const FieldPresence field_presence) { switch (field_presence) { case ALWAYS: return "always"; case SOMETIMES: return "sometimes"; case IGNORE: return "ignore"; default: LOG_ERROR("we should *never get here!"); } } void LoadFromDatabaseOrCreateFromScratch(DbConnection * const db_connection, const std::string &journal_name, JournalInfo * const journal_info) { db_connection->queryOrDie("SELECT metadata_field_name,field_presence FROM metadata_presence_tracer WHERE journal_name='" + db_connection->escapeString(journal_name) + "'"); DbResultSet result_set(db_connection->getLastResultSet()); if (result_set.empty()) { LOG_INFO("\"" + journal_name + "\" was not yet in the database."); *journal_info = JournalInfo(/* not_in_database_yet = */true); return; } *journal_info = JournalInfo(/* not_in_database_yet = */false); while (auto row = result_set.getNextRow()) journal_info->addField(row["metadata_field_name"], StringToFieldPresence(row["field_presence"])); } // Two-way mapping required as the map is uni-directional const std::map<std::string, std::string> EQUIVALENT_TAGS_MAP{ { "700", "100" }, { "100", "700" } }; void AnalyseNewJournalRecord(const MARC::Record &record, const bool first_record, JournalInfo * const journal_info) { std::unordered_set<std::string> seen_tags; MARC::Tag last_tag; for (const auto &field : record) { auto current_tag(field.getTag()); if (current_tag == last_tag) continue; seen_tags.emplace(current_tag.toString()); if (first_record) journal_info->addField(current_tag.toString(), ALWAYS); else if (journal_info->find(current_tag.toString()) == journal_info->end()) journal_info->addField(current_tag.toString(), SOMETIMES); last_tag = current_tag; } for (auto &field_info : *journal_info) { if (seen_tags.find(field_info.name_) == seen_tags.end()) field_info.presence_ = SOMETIMES; } } bool RecordMeetsExpectations(const MARC::Record &record, const std::string &journal_name, const JournalInfo &journal_info) { std::unordered_set<std::string> seen_tags; MARC::Tag last_tag; for (const auto &field : record) { const auto current_tag(field.getTag()); if (current_tag == last_tag) continue; seen_tags.emplace(current_tag.toString()); last_tag = current_tag; } bool missed_at_least_one_expectation(false); for (const auto &field_info : journal_info) { if (field_info.presence_ != ALWAYS) continue; // we only care about required fields that are missing const auto equivalent_tag(EQUIVALENT_TAGS_MAP.find(field_info.name_)); if (seen_tags.find(field_info.name_) != seen_tags.end()) ;// required tag found else if (equivalent_tag != EQUIVALENT_TAGS_MAP.end() and seen_tags.find(equivalent_tag->second) != seen_tags.end()) ;// equivalent tag found else { LOG_WARNING("Record w/ control number " + record.getControlNumber() + " in \"" + journal_name + "\" is missing the always expected " + field_info.name_ + " field."); missed_at_least_one_expectation = true; } } return not missed_at_least_one_expectation; } void WriteToDatabase(DbConnection * const db_connection, const std::string &journal_name, const JournalInfo &journal_info) { for (const auto &field_info : journal_info) db_connection->queryOrDie("INSERT INTO metadata_presence_tracer SET journal_name='" + journal_name + "', metadata_field_name='" + db_connection->escapeString(field_info.name_) + "', field_presence='" + FieldPresenceToString(field_info.presence_) + "'"); } void SendEmail(const std::string &email_address, const std::string &message_subject, const std::string &message_body) { const auto reply_code(EmailSender::SendEmail("zts_harvester_delivery_pipeline@uni-tuebingen.de", email_address, message_subject, message_body, EmailSender::MEDIUM, EmailSender::PLAIN_TEXT, /* reply_to = */ "", /* use_ssl = */ true, /* use_authentication = */ true)); if (reply_code >= 300) LOG_WARNING("failed to send email, the response code was: " + std::to_string(reply_code)); } void UpdateDB(DbConnection * const db_connection, const std::string &journal_name, const std::string &field_name, const std::string &field_presence_str) { FieldPresence field_presence; if (not StringToFieldPresence(field_presence_str, &field_presence)) LOG_ERROR("\"" + field_presence_str + "\" is not a valid field_presence!"); if (field_name.length() != MARC::Record::TAG_LENGTH) LOG_ERROR("\"" + field_name + "\" is not a valid field name!"); DbTransaction transcation(db_connection); db_connection->queryOrDie("SELECT field_presence FROM metadata_presence_tracer WHERE journal_name=" + db_connection->escapeAndQuoteString(journal_name) + " AND field_name='" + field_name + "'"); const DbResultSet result_set(db_connection->getLastResultSet()); if (result_set.empty()) LOG_ERROR("can't update non-existent database entry!"); db_connection->queryOrDie("UPDATE metadata_presence_tracer SET field_presence='" + field_presence_str + "' WHERE journal_name=" + db_connection->escapeAndQuoteString(journal_name) + " AND field_name='" + field_name + "'"); } bool IsRecordValid(DbConnection * const db_connection, const MARC::Record &record, std::map<std::string, JournalInfo> * const journal_name_to_info_map, unsigned * const new_record_count, unsigned * const missed_expectation_count) { const auto journal_name(record.getSuperiorTitle()); if (journal_name.empty()) { LOG_WARNING("Record w/ control number \"" + record.getControlNumber() + "\" is missing a superior title!"); ++(*missed_expectation_count); return false; } auto journal_name_and_info(journal_name_to_info_map->find(journal_name)); bool first_record(false); // True if the current record is the first encounter of a journal if (journal_name_and_info == journal_name_to_info_map->end()) { first_record = true; JournalInfo new_journal_info; LoadFromDatabaseOrCreateFromScratch(db_connection, journal_name, &new_journal_info); (*journal_name_to_info_map)[journal_name] = new_journal_info; journal_name_and_info = journal_name_to_info_map->find(journal_name); } if (journal_name_and_info->second.isInDatabase()) { if (not RecordMeetsExpectations(record, journal_name_and_info->first, journal_name_and_info->second)) { ++(*missed_expectation_count); return false; } } else { AnalyseNewJournalRecord(record, first_record, &journal_name_and_info->second); ++(*new_record_count); } return true; } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc != 5) Usage(); DbConnection db_connection; if (std::strcmp(argv[1], "update_db") == 0) { UpdateDB(&db_connection, argv[2], argv[3], argv[4]); return EXIT_SUCCESS; } auto reader(MARC::Reader::Factory(argv[1])); auto valid_records_writer(MARC::Writer::Factory(argv[2])); auto delinquent_records_writer(MARC::Writer::Factory(argv[3])); std::map<std::string, JournalInfo> journal_name_to_info_map; const std::string email_address(argv[4]); unsigned total_record_count(0), new_record_count(0), missed_expectation_count(0); while (const auto record = reader->read()) { ++total_record_count; if (IsRecordValid(&db_connection, record, &journal_name_to_info_map, &new_record_count, &missed_expectation_count)) valid_records_writer->write(record); else delinquent_records_writer->write(record); } for (const auto &journal_name_and_info : journal_name_to_info_map) { if (not journal_name_and_info.second.isInDatabase()) WriteToDatabase(&db_connection, journal_name_and_info.first, journal_name_and_info.second); } if (missed_expectation_count > 0) { // send notification to the email address SendEmail(email_address, "validate_harvested_records encountered warnings (from: " + DnsUtil::GetHostname() + ")", "Some records missed expectations with respect to MARC fields. " "Check the log at '/usr/local/var/log/tuefind/zts_harvester_delivery_pipeline.log' for details."); } LOG_INFO("Processed " + std::to_string(total_record_count) + " record(s) of which " + std::to_string(new_record_count) + " was/were (a) record(s) of new journals and " + std::to_string(missed_expectation_count) + " record(s) missed expectations."); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// @brief V8 line editor /// /// @file /// /// DISCLAIMER /// /// Copyright 2004-2012 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 Copyright 2011-2012, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "V8LineEditor.h" #include <readline/readline.h> #include <readline/history.h> #include "BasicsC/strings.h" #include "V8/v8-utils.h" #if RL_READLINE_VERSION >= 0x0500 #define completion_matches rl_completion_matches #endif using namespace std; // ----------------------------------------------------------------------------- // --SECTION-- class V8LineEditor // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // --SECTION-- private variables // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup V8Shell /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief word break characters //////////////////////////////////////////////////////////////////////////////// static char WordBreakCharacters[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '<', '>', '=', ';', '|', '&', '{', '}', '(', ')', '\0' }; //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- private functions // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup V8LineEditor /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief completion generator //////////////////////////////////////////////////////////////////////////////// static char* CompletionGenerator (char const* text, int state) { static size_t currentIndex; static vector<string> result; char* prefix; // compute the possible completion if (state == 0) { if (! v8::Context::InContext()) { return 0; } // locate global object or sub-object v8::Handle<v8::Object> current = v8::Context::GetCurrent()->Global(); string path; if (*text != '\0') { TRI_vector_string_t splitted = TRI_SplitString(text, '.'); if (1 < splitted._length) { for (size_t i = 0; i < splitted._length - 1; ++i) { v8::Handle<v8::String> name = v8::String::New(splitted._buffer[i]); if (! current->Has(name)) { TRI_DestroyVectorString(&splitted); return 0; } v8::Handle<v8::Value> val = current->Get(name); if (! val->IsObject()) { TRI_DestroyVectorString(&splitted); return 0; } current = val->ToObject(); path = path + splitted._buffer[i] + "."; } prefix = TRI_DuplicateString(splitted._buffer[splitted._length - 1]); } else { prefix = TRI_DuplicateString(text); } TRI_DestroyVectorString(&splitted); } else { prefix = TRI_DuplicateString(text); } // compute all possible completions v8::Handle<v8::Array> properties; v8::Handle<v8::String> cpl = v8::String::New("_COMPLETIONS"); if (current->HasOwnProperty(cpl)) { v8::Handle<v8::Value> funcVal = current->Get(cpl); if (funcVal->IsFunction()) { v8::Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(funcVal); v8::Handle<v8::Value> args; v8::Handle<v8::Value> cpls = func->Call(current, 0, &args); if (cpls->IsArray()) { properties = v8::Handle<v8::Array>::Cast(cpls); } } } else { properties = current->GetPropertyNames(); } // locate if (! properties.IsEmpty()) { size_t n = properties->Length(); for (size_t i = 0; i < n; ++i) { v8::Handle<v8::Value> v = properties->Get(i); TRI_Utf8ValueNFC str(TRI_UNKNOWN_MEM_ZONE, v); char const* s = *str; if (s != 0 && *s) { string suffix = (current->Get(v)->IsFunction()) ? "()" : ""; string name = path + s + suffix; if (*prefix == '\0' || TRI_IsPrefixString(s, prefix)) { result.push_back(name); } } } } currentIndex = 0; TRI_FreeString(TRI_CORE_MEM_ZONE, prefix); } if (currentIndex < result.size()) { return TRI_SystemDuplicateString(result[currentIndex++].c_str()); } else { result.clear(); return 0; } } //////////////////////////////////////////////////////////////////////////////// /// @brief attempted completion //////////////////////////////////////////////////////////////////////////////// static char** AttemptedCompletion (char const* text, int start, int end) { char** result; result = completion_matches(text, CompletionGenerator); rl_attempted_completion_over = true; if (result != 0 && result[0] != 0 && result[1] == 0) { size_t n = strlen(result[0]); if (result[0][n-1] == ')') { result[0][n-1] = '\0'; #if RL_READLINE_VERSION >= 0x0500 rl_completion_suppress_append = 1; #endif } } return result; } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup V8LineEditor /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief constructs a new editor //////////////////////////////////////////////////////////////////////////////// V8LineEditor::V8LineEditor (v8::Handle<v8::Context> context, std::string const& history) : LineEditor(history), _context(context) { } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- public methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup V8LineEditor /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief line editor open //////////////////////////////////////////////////////////////////////////////// bool V8LineEditor::open (const bool autoComplete) { if (autoComplete) { rl_attempted_completion_function = AttemptedCompletion; rl_completer_word_break_characters = WordBreakCharacters; rl_bind_key('\t', rl_complete); } return LineEditor::open(autoComplete); } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- protected methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup LineEditor /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief check if line is complete //////////////////////////////////////////////////////////////////////////////// bool V8LineEditor::isComplete (string const& source, size_t, size_t) { char const* ptr; char const* end; int openParen; int openBrackets; int openBraces; enum { NORMAL, // start NORMAL_1, // from NORMAL: seen a single / DOUBLE_QUOTE, // from NORMAL: seen a single " DOUBLE_QUOTE_ESC, // from DOUBLE_QUOTE: seen a backslash SINGLE_QUOTE, // from NORMAL: seen a single ' SINGLE_QUOTE_ESC, // from SINGLE_QUOTE: seen a backslash MULTI_COMMENT, // from NORMAL_1: seen a * MULTI_COMMENT_1, // from MULTI_COMMENT, seen a * SINGLE_COMMENT // from NORMAL_1; seen a / } state; openParen = 0; openBrackets = 0; openBraces = 0; ptr = source.c_str(); end = ptr + source.length(); state = NORMAL; while (ptr < end) { if (state == DOUBLE_QUOTE) { if (*ptr == '\\') { state = DOUBLE_QUOTE_ESC; } else if (*ptr == '"') { state = NORMAL; } ++ptr; } else if (state == DOUBLE_QUOTE_ESC) { state = DOUBLE_QUOTE; ptr++; } else if (state == SINGLE_QUOTE) { if (*ptr == '\\') { state = SINGLE_QUOTE_ESC; } else if (*ptr == '\'') { state = NORMAL; } ++ptr; } else if (state == SINGLE_QUOTE_ESC) { state = SINGLE_QUOTE; ptr++; } else if (state == MULTI_COMMENT) { if (*ptr == '*') { state = MULTI_COMMENT_1; } ++ptr; } else if (state == MULTI_COMMENT_1) { if (*ptr == '/') { state = NORMAL; } ++ptr; } else if (state == SINGLE_COMMENT) { ++ptr; if (ptr == end) { state = NORMAL; } } else if (state == NORMAL_1) { switch (*ptr) { case '/': state = SINGLE_COMMENT; ++ptr; break; case '*': state = MULTI_COMMENT; ++ptr; break; default: state = NORMAL; // try again, do not change ptr break; } } else { switch (*ptr) { case '"': state = DOUBLE_QUOTE; break; case '\'': state = SINGLE_QUOTE; break; case '/': state = NORMAL_1; break; case '(': ++openParen; break; case ')': --openParen; break; case '[': ++openBrackets; break; case ']': --openBrackets; break; case '{': ++openBraces; break; case '}': --openBraces; break; } ++ptr; } } return openParen <= 0 && openBrackets <= 0 && openBraces <= 0; } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // Local Variables: // mode: outline-minor // outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}\\)" // End: <commit_msg>issue #289<commit_after>//////////////////////////////////////////////////////////////////////////////// /// @brief V8 line editor /// /// @file /// /// DISCLAIMER /// /// Copyright 2004-2012 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 Copyright 2011-2012, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "V8LineEditor.h" #include <readline/readline.h> #include <readline/history.h> #include "BasicsC/strings.h" #include "V8/v8-utils.h" #if RL_READLINE_VERSION >= 0x0500 #define completion_matches rl_completion_matches #endif using namespace std; // ----------------------------------------------------------------------------- // --SECTION-- class V8LineEditor // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // --SECTION-- private variables // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup V8Shell /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief word break characters //////////////////////////////////////////////////////////////////////////////// static char WordBreakCharacters[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '<', '>', '=', ';', '|', '&', '{', '}', '(', ')', '\0' }; //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- private functions // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup V8LineEditor /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief completion generator //////////////////////////////////////////////////////////////////////////////// static char* CompletionGenerator (char const* text, int state) { static size_t currentIndex; static vector<string> result; char* prefix; // compute the possible completion if (state == 0) { if (! v8::Context::InContext()) { return 0; } // locate global object or sub-object v8::Handle<v8::Object> current = v8::Context::GetCurrent()->Global(); string path; if (*text != '\0') { TRI_vector_string_t splitted = TRI_SplitString(text, '.'); if (1 < splitted._length) { for (size_t i = 0; i < splitted._length - 1; ++i) { v8::Handle<v8::String> name = v8::String::New(splitted._buffer[i]); if (! current->Has(name)) { TRI_DestroyVectorString(&splitted); return 0; } v8::Handle<v8::Value> val = current->Get(name); if (! val->IsObject()) { TRI_DestroyVectorString(&splitted); return 0; } current = val->ToObject(); path = path + splitted._buffer[i] + "."; } prefix = TRI_DuplicateString(splitted._buffer[splitted._length - 1]); } else { prefix = TRI_DuplicateString(text); } TRI_DestroyVectorString(&splitted); } else { prefix = TRI_DuplicateString(text); } // compute all possible completions v8::Handle<v8::Array> properties; v8::Handle<v8::String> cpl = v8::String::New("_COMPLETIONS"); if (current->HasOwnProperty(cpl)) { v8::Handle<v8::Value> funcVal = current->Get(cpl); if (funcVal->IsFunction()) { v8::Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(funcVal); v8::Handle<v8::Value> args; v8::Handle<v8::Value> cpls = func->Call(current, 0, &args); if (cpls->IsArray()) { properties = v8::Handle<v8::Array>::Cast(cpls); } } } else { properties = current->GetPropertyNames(); } // locate if (! properties.IsEmpty()) { size_t n = properties->Length(); for (size_t i = 0; i < n; ++i) { v8::Handle<v8::Value> v = properties->Get(i); TRI_Utf8ValueNFC str(TRI_UNKNOWN_MEM_ZONE, v); char const* s = *str; if (s != 0 && *s) { string suffix = (current->Get(v)->IsFunction()) ? "()" : ""; string name = path + s + suffix; if (*prefix == '\0' || TRI_IsPrefixString(s, prefix)) { result.push_back(name); } } } } currentIndex = 0; TRI_FreeString(TRI_CORE_MEM_ZONE, prefix); } if (currentIndex < result.size()) { return TRI_SystemDuplicateString(result[currentIndex++].c_str()); } else { result.clear(); return 0; } } //////////////////////////////////////////////////////////////////////////////// /// @brief attempted completion //////////////////////////////////////////////////////////////////////////////// static char** AttemptedCompletion (char const* text, int start, int end) { char** result; result = completion_matches(text, CompletionGenerator); rl_attempted_completion_over = true; if (result != 0 && result[0] != 0 && result[1] == 0) { size_t n = strlen(result[0]); if (result[0][n - 1] == ')') { result[0][n - 1] = '\0'; #if RL_READLINE_VERSION >= 0x0500 rl_completion_suppress_append = 1; #endif } } return result; } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup V8LineEditor /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief constructs a new editor //////////////////////////////////////////////////////////////////////////////// V8LineEditor::V8LineEditor (v8::Handle<v8::Context> context, std::string const& history) : LineEditor(history), _context(context) { } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- public methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup V8LineEditor /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief line editor open //////////////////////////////////////////////////////////////////////////////// bool V8LineEditor::open (const bool autoComplete) { if (autoComplete) { // issue #289: do not append a space after completion rl_completion_append_character = '\0'; rl_attempted_completion_function = AttemptedCompletion; rl_completer_word_break_characters = WordBreakCharacters; rl_bind_key('\t', rl_complete); } return LineEditor::open(autoComplete); } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- protected methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup LineEditor /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief check if line is complete //////////////////////////////////////////////////////////////////////////////// bool V8LineEditor::isComplete (string const& source, size_t, size_t) { char const* ptr; char const* end; int openParen; int openBrackets; int openBraces; enum { NORMAL, // start NORMAL_1, // from NORMAL: seen a single / DOUBLE_QUOTE, // from NORMAL: seen a single " DOUBLE_QUOTE_ESC, // from DOUBLE_QUOTE: seen a backslash SINGLE_QUOTE, // from NORMAL: seen a single ' SINGLE_QUOTE_ESC, // from SINGLE_QUOTE: seen a backslash MULTI_COMMENT, // from NORMAL_1: seen a * MULTI_COMMENT_1, // from MULTI_COMMENT, seen a * SINGLE_COMMENT // from NORMAL_1; seen a / } state; openParen = 0; openBrackets = 0; openBraces = 0; ptr = source.c_str(); end = ptr + source.length(); state = NORMAL; while (ptr < end) { if (state == DOUBLE_QUOTE) { if (*ptr == '\\') { state = DOUBLE_QUOTE_ESC; } else if (*ptr == '"') { state = NORMAL; } ++ptr; } else if (state == DOUBLE_QUOTE_ESC) { state = DOUBLE_QUOTE; ptr++; } else if (state == SINGLE_QUOTE) { if (*ptr == '\\') { state = SINGLE_QUOTE_ESC; } else if (*ptr == '\'') { state = NORMAL; } ++ptr; } else if (state == SINGLE_QUOTE_ESC) { state = SINGLE_QUOTE; ptr++; } else if (state == MULTI_COMMENT) { if (*ptr == '*') { state = MULTI_COMMENT_1; } ++ptr; } else if (state == MULTI_COMMENT_1) { if (*ptr == '/') { state = NORMAL; } ++ptr; } else if (state == SINGLE_COMMENT) { ++ptr; if (ptr == end) { state = NORMAL; } } else if (state == NORMAL_1) { switch (*ptr) { case '/': state = SINGLE_COMMENT; ++ptr; break; case '*': state = MULTI_COMMENT; ++ptr; break; default: state = NORMAL; // try again, do not change ptr break; } } else { switch (*ptr) { case '"': state = DOUBLE_QUOTE; break; case '\'': state = SINGLE_QUOTE; break; case '/': state = NORMAL_1; break; case '(': ++openParen; break; case ')': --openParen; break; case '[': ++openBrackets; break; case ']': --openBrackets; break; case '{': ++openBraces; break; case '}': --openBraces; break; } ++ptr; } } return openParen <= 0 && openBrackets <= 0 && openBraces <= 0; } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // Local Variables: // mode: outline-minor // outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}\\)" // End: <|endoftext|>
<commit_before>/* test_cryptoconfig.cpp This file is part of libkleopatra's test suite. Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. Libkleopatra 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 In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include <backends/qgpgme/qgpgmecryptoconfig.h> #include <kapplication.h> #include <kaboutdata.h> #include <kcmdlineargs.h> #include <iostream> using namespace std; #include <stdlib.h> #include <assert.h> int main( int argc, char** argv ) { KAboutData aboutData( "test_cryptoconfig", "CryptoConfig Test", "0.1" ); KCmdLineArgs::init( argc, argv, &aboutData ); KApplication app( false, false ); Kleo::CryptoConfig * config = new QGpgMECryptoConfig(); // Dynamic querying of the options cout << "Components:" << endl; QStringList components = config->componentList(); for( QStringList::Iterator compit = components.begin(); compit != components.end(); ++compit ) { cout << "Component " << (*compit).local8Bit() << ":" << endl; const Kleo::CryptoConfigComponent* comp = config->component( *compit ); assert( comp ); QStringList groups = comp->groupList(); for( QStringList::Iterator groupit = groups.begin(); groupit != groups.end(); ++groupit ) { const Kleo::CryptoConfigGroup* group = comp->group( *groupit ); assert( group ); cout << " Group " << (*groupit).local8Bit() << ": descr=\"" << group->description().local8Bit() << "\"" << " level=" << group->level() << endl; QStringList entries = group->entryList(); for( QStringList::Iterator entryit = entries.begin(); entryit != entries.end(); ++entryit ) { const Kleo::CryptoConfigEntry* entry = group->entry( *entryit ); assert( entry ); cout << " Entry " << (*entryit).local8Bit() << ":" << " descr=\"" << entry->description().local8Bit() << "\"" << " " << ( entry->isSet() ? "is set" : "is not set" ); if ( !entry->isList() ) switch( entry->argType() ) { case Kleo::CryptoConfigEntry::ArgType_None: break; case Kleo::CryptoConfigEntry::ArgType_Int: cout << " int value=" << entry->intValue(); break; case Kleo::CryptoConfigEntry::ArgType_UInt: cout << " uint value=" << entry->uintValue(); break; case Kleo::CryptoConfigEntry::ArgType_URL: cout << " URL value=" << entry->urlValue().prettyURL().local8Bit(); // fallthrough case Kleo::CryptoConfigEntry::ArgType_Path: // fallthrough case Kleo::CryptoConfigEntry::ArgType_String: cout << " string value=" << entry->stringValue().local8Bit(); break; } else // lists switch( entry->argType() ) { case Kleo::CryptoConfigEntry::ArgType_None: { cout << " set " << entry->numberOfTimesSet() << " times"; break; } case Kleo::CryptoConfigEntry::ArgType_Int: { QValueList<int> lst = entry->intValueList(); QString str; for( QValueList<int>::Iterator it = lst.begin(); it != lst.end(); ++it ) { str += QString::number( *it ); } cout << " int values=" << str.local8Bit(); break; } case Kleo::CryptoConfigEntry::ArgType_UInt: { QValueList<uint> lst = entry->uintValueList(); QString str; for( QValueList<uint>::Iterator it = lst.begin(); it != lst.end(); ++it ) { str += QString::number( *it ); } cout << " uint values=" << str.local8Bit(); break; } case Kleo::CryptoConfigEntry::ArgType_URL: { KURL::List urls = entry->urlValueList(); cout << " url values=" << urls.toStringList().join(" ").local8Bit() << "\n "; } // fallthrough case Kleo::CryptoConfigEntry::ArgType_Path: // fallthrough case Kleo::CryptoConfigEntry::ArgType_String: { QStringList lst = entry->stringValueList(); cout << " string values=" << lst.join(" ").local8Bit(); break; } } cout << endl; } // ... } } { // Static querying of a single boolean option Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", "LDAP", "ldaptimeout" ); if ( entry ) { assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_UInt ); uint val = entry->uintValue(); cout << "LDAP timeout: " << val << " seconds." << endl; // Test setting the option directly, then querying again //system( "echo 'ldaptimeout:0:101' | gpgconf --change-options dirmngr" ); // Now let's do it with the C++ API instead entry->setUIntValue( 101 ); assert( entry->isDirty() ); config->sync( true ); // Clear cached values! config->clear(); // Check new value Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", "LDAP", "ldaptimeout" ); assert( entry ); assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_UInt ); cout << "LDAP timeout: " << entry->uintValue() << " seconds." << endl; assert( entry->uintValue() == 101 ); // Set to default entry->resetToDefault(); assert( entry->isDirty() ); assert( !entry->isSet() ); config->sync( true ); config->clear(); // Check value entry = config->entry( "dirmngr", "LDAP", "ldaptimeout" ); assert( !entry->isDirty() ); assert( !entry->isSet() ); cout << "LDAP timeout reset to default, " << val << " seconds." << endl; // Reset old value entry->setUIntValue( val ); assert( entry->isDirty() ); config->sync( true ); cout << "LDAP timeout reset to initial " << val << " seconds." << endl; } else cout << "Entry dirmngr/LDAP/ldaptimeout not found" << endl; } { // Static querying of a single string option Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", "Debug", "log-file" ); if ( entry ) { assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_Path ); QString val = entry->stringValue(); cout << "Log-file: " << val.local8Bit() << endl; // Test setting the option directly, then querying again //system( "echo 'log-file:\"/tmp/test%3a%e5' | gpgconf --change-options dirmngr" ); // Now let's do it with the C++ API instead entry->setStringValue( "/tmp/test:%e5" ); assert( entry->isDirty() ); config->sync( true ); // Let's see how it prints it system( "gpgconf --list-options dirmngr | grep log-file" ); // Clear cached values! config->clear(); // Check new value Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", "Debug", "log-file" ); assert( entry ); assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_Path ); cout << "Log-file: " << entry->stringValue().local8Bit() << endl; // This is what it should be, but gpgconf escapes wrongly the arguments (aegypten issue90) //assert( entry->stringValue() == "/tmp/test:%e5" ); // (or even with %e5 decoded) // Reset old value #if 0 QString arg( val ); if ( !arg.isEmpty() ) arg.prepend( '"' ); QCString sys; sys.sprintf( "echo 'log-file:%s' | gpgconf --change-options dirmngr", arg.local8Bit().data() ); system( sys.data() ); #endif entry->setStringValue( val ); assert( entry->isDirty() ); config->sync( true ); cout << "Log-file reset to " << val.local8Bit() << endl; } else cout << "Entry dirmngr/Debug/log-file not found" << endl; } // TODO setting options cout << "Done." << endl; } <commit_msg>This also works now that gpgconf was fixed.<commit_after>/* test_cryptoconfig.cpp This file is part of libkleopatra's test suite. Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. Libkleopatra 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 In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include <backends/qgpgme/qgpgmecryptoconfig.h> #include <kapplication.h> #include <kaboutdata.h> #include <kcmdlineargs.h> #include <iostream> using namespace std; #include <stdlib.h> #include <assert.h> int main( int argc, char** argv ) { KAboutData aboutData( "test_cryptoconfig", "CryptoConfig Test", "0.1" ); KCmdLineArgs::init( argc, argv, &aboutData ); KApplication app( false, false ); Kleo::CryptoConfig * config = new QGpgMECryptoConfig(); // Dynamic querying of the options cout << "Components:" << endl; QStringList components = config->componentList(); for( QStringList::Iterator compit = components.begin(); compit != components.end(); ++compit ) { cout << "Component " << (*compit).local8Bit() << ":" << endl; const Kleo::CryptoConfigComponent* comp = config->component( *compit ); assert( comp ); QStringList groups = comp->groupList(); for( QStringList::Iterator groupit = groups.begin(); groupit != groups.end(); ++groupit ) { const Kleo::CryptoConfigGroup* group = comp->group( *groupit ); assert( group ); cout << " Group " << (*groupit).local8Bit() << ": descr=\"" << group->description().local8Bit() << "\"" << " level=" << group->level() << endl; QStringList entries = group->entryList(); for( QStringList::Iterator entryit = entries.begin(); entryit != entries.end(); ++entryit ) { const Kleo::CryptoConfigEntry* entry = group->entry( *entryit ); assert( entry ); cout << " Entry " << (*entryit).local8Bit() << ":" << " descr=\"" << entry->description().local8Bit() << "\"" << " " << ( entry->isSet() ? "is set" : "is not set" ); if ( !entry->isList() ) switch( entry->argType() ) { case Kleo::CryptoConfigEntry::ArgType_None: break; case Kleo::CryptoConfigEntry::ArgType_Int: cout << " int value=" << entry->intValue(); break; case Kleo::CryptoConfigEntry::ArgType_UInt: cout << " uint value=" << entry->uintValue(); break; case Kleo::CryptoConfigEntry::ArgType_URL: cout << " URL value=" << entry->urlValue().prettyURL().local8Bit(); // fallthrough case Kleo::CryptoConfigEntry::ArgType_Path: // fallthrough case Kleo::CryptoConfigEntry::ArgType_String: cout << " string value=" << entry->stringValue().local8Bit(); break; } else // lists switch( entry->argType() ) { case Kleo::CryptoConfigEntry::ArgType_None: { cout << " set " << entry->numberOfTimesSet() << " times"; break; } case Kleo::CryptoConfigEntry::ArgType_Int: { QValueList<int> lst = entry->intValueList(); QString str; for( QValueList<int>::Iterator it = lst.begin(); it != lst.end(); ++it ) { str += QString::number( *it ); } cout << " int values=" << str.local8Bit(); break; } case Kleo::CryptoConfigEntry::ArgType_UInt: { QValueList<uint> lst = entry->uintValueList(); QString str; for( QValueList<uint>::Iterator it = lst.begin(); it != lst.end(); ++it ) { str += QString::number( *it ); } cout << " uint values=" << str.local8Bit(); break; } case Kleo::CryptoConfigEntry::ArgType_URL: { KURL::List urls = entry->urlValueList(); cout << " url values=" << urls.toStringList().join(" ").local8Bit() << "\n "; } // fallthrough case Kleo::CryptoConfigEntry::ArgType_Path: // fallthrough case Kleo::CryptoConfigEntry::ArgType_String: { QStringList lst = entry->stringValueList(); cout << " string values=" << lst.join(" ").local8Bit(); break; } } cout << endl; } // ... } } { // Static querying of a single boolean option Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", "LDAP", "ldaptimeout" ); if ( entry ) { assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_UInt ); uint val = entry->uintValue(); cout << "LDAP timeout: " << val << " seconds." << endl; // Test setting the option directly, then querying again //system( "echo 'ldaptimeout:0:101' | gpgconf --change-options dirmngr" ); // Now let's do it with the C++ API instead entry->setUIntValue( 101 ); assert( entry->isDirty() ); config->sync( true ); // Clear cached values! config->clear(); // Check new value Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", "LDAP", "ldaptimeout" ); assert( entry ); assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_UInt ); cout << "LDAP timeout: " << entry->uintValue() << " seconds." << endl; assert( entry->uintValue() == 101 ); // Set to default entry->resetToDefault(); assert( entry->isDirty() ); assert( !entry->isSet() ); config->sync( true ); config->clear(); // Check value entry = config->entry( "dirmngr", "LDAP", "ldaptimeout" ); assert( !entry->isDirty() ); assert( !entry->isSet() ); cout << "LDAP timeout reset to default, " << val << " seconds." << endl; // Reset old value entry->setUIntValue( val ); assert( entry->isDirty() ); config->sync( true ); cout << "LDAP timeout reset to initial " << val << " seconds." << endl; } else cout << "Entry dirmngr/LDAP/ldaptimeout not found" << endl; } { // Static querying of a single string option Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", "Debug", "log-file" ); if ( entry ) { assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_Path ); QString val = entry->stringValue(); cout << "Log-file: " << val.local8Bit() << endl; // Test setting the option, sync'ing, then querying again entry->setStringValue( "/tmp/test:%e5" ); assert( entry->isDirty() ); config->sync( true ); // Let's see how it prints it system( "gpgconf --list-options dirmngr | grep log-file" ); // Clear cached values! config->clear(); // Check new value Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", "Debug", "log-file" ); assert( entry ); assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_Path ); cout << "Log-file: " << entry->stringValue().local8Bit() << endl; assert( entry->stringValue() == "/tmp/test:%e5" ); // (or even with %e5 decoded) // Reset old value #if 0 QString arg( val ); if ( !arg.isEmpty() ) arg.prepend( '"' ); QCString sys; sys.sprintf( "echo 'log-file:%s' | gpgconf --change-options dirmngr", arg.local8Bit().data() ); system( sys.data() ); #endif entry->setStringValue( val ); assert( entry->isDirty() ); config->sync( true ); cout << "Log-file reset to " << val.local8Bit() << endl; } else cout << "Entry dirmngr/Debug/log-file not found" << endl; } cout << "Done." << endl; } <|endoftext|>
<commit_before>/* This file is part of the KDE project. Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 or 3 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QT_NO_DEBUG #include <QTextStream> #include <QWidget> #include <coecntrl.h> #include "objectdump_symbian.h" #include <QtGui/private/qwidget_p.h> // to access QWExtra QT_BEGIN_NAMESPACE namespace ObjectDump { namespace Symbian { QList<QByteArray> QAnnotatorWidget::annotation(const QObject& object) { QList<QByteArray> result; const QWidget* widget = qobject_cast<const QWidget*>(&object); if (widget) { const QWExtra* extra = qt_widget_private(const_cast<QWidget *>(widget))->extraData(); if (extra) { QByteArray array; QTextStream stream(&array); stream << "widget (Symbian): "; stream << "activated " << extra->activated << ' '; stream << "disableBlit " << extra->disableBlit << ' '; stream.flush(); result.append(array); } } return result; } QList<QByteArray> QAnnotatorControl::annotation(const QObject& object) { QList<QByteArray> result; const QWidget* widget = qobject_cast<const QWidget*>(&object); if (widget) { const CCoeControl* control = widget->effectiveWinId(); if (control) { QByteArray array; QTextStream stream(&array); stream << "control: " << control << ' '; stream << "parent " << control->Parent() << ' '; if (control->IsVisible()) stream << "visible "; else stream << "invisible "; stream << control->Position().iX << ',' << control->Position().iY << ' '; stream << control->Size().iWidth << 'x' << control->Size().iHeight; if (control->OwnsWindow()) stream << " ownsWindow "; stream.flush(); result.append(array); } } return result; } QList<QByteArray> QAnnotatorWindow::annotation(const QObject& object) { QList<QByteArray> result; const QWidget* widget = qobject_cast<const QWidget*>(&object); if (widget) { const CCoeControl* control = widget->effectiveWinId(); RDrawableWindow *window = 0; if (control && (window = control->DrawableWindow())) { QByteArray array; QTextStream stream(&array); stream << "window: "; // ClientHandle() is available first in 5.0. #if !defined(__SERIES60_31__) && !defined(__S60_32__) if (QSysInfo::s60Version() > QSysInfo::SV_S60_3_2) // Client-side window handle // Cast to a void pointer so that log output is in hexadecimal format. stream << "cli " << reinterpret_cast<const void*>(window->ClientHandle()) << ' '; #endif // Server-side address of CWsWindow object // This is useful for correlation with the window tree dumped by the window // server (see RWsSession::LogCommand). // Cast to a void pointer so that log output is in hexadecimal format. stream << "srv " << reinterpret_cast<const void*>(window->WsHandle()) << ' '; stream << "group " << window->WindowGroupId() << ' '; // Client-side handle to the parent window. // Cast to a void pointer so that log output is in hexadecimal format. stream << "parent " << reinterpret_cast<const void*>(window->Parent()) << ' '; stream << window->Position().iX << ',' << window->Position().iY << ' '; stream << '(' << window->AbsPosition().iX << ',' << window->AbsPosition().iY << ") "; stream << window->Size().iWidth << 'x' << window->Size().iHeight << ' '; const TDisplayMode displayMode = window->DisplayMode(); stream << "mode " << displayMode << ' '; stream << "ord " << window->OrdinalPosition(); stream.flush(); result.append(array); } } return result; } } // namespace Symbian void addDefaultAnnotators_sys(QDumper& dumper) { dumper.addAnnotator(new Symbian::QAnnotatorWidget); dumper.addAnnotator(new Symbian::QAnnotatorControl); dumper.addAnnotator(new Symbian::QAnnotatorWindow); } void addDefaultAnnotators_sys(QVisitor& visitor) { visitor.addAnnotator(new Symbian::QAnnotatorWidget); visitor.addAnnotator(new Symbian::QAnnotatorControl); visitor.addAnnotator(new Symbian::QAnnotatorWindow); } } // namespace ObjectDump QT_END_NAMESPACE #endif <commit_msg>Removed logging from Phonon MMF backend<commit_after>/* This file is part of the KDE project. Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 or 3 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QT_NO_DEBUG #include <QTextStream> #include <QWidget> #include <coecntrl.h> #include "objectdump_symbian.h" #include <QtGui/private/qwidget_p.h> // to access QWExtra QT_BEGIN_NAMESPACE namespace ObjectDump { namespace Symbian { QList<QByteArray> QAnnotatorWidget::annotation(const QObject& object) { QList<QByteArray> result; const QWidget* widget = qobject_cast<const QWidget*>(&object); if (widget) { const QWExtra* extra = qt_widget_private(const_cast<QWidget *>(widget))->extraData(); if (extra) { QByteArray array; QTextStream stream(&array); stream << "widget (Symbian): "; stream << "activated " << extra->activated << ' '; stream << "disableBlit " << extra->disableBlit << ' '; stream.flush(); result.append(array); } } return result; } QList<QByteArray> QAnnotatorControl::annotation(const QObject& object) { QList<QByteArray> result; const QWidget* widget = qobject_cast<const QWidget*>(&object); if (widget) { const CCoeControl* control = widget->effectiveWinId(); if (control) { QByteArray array; QTextStream stream(&array); stream << "control: " << control << ' '; stream << "parent " << control->Parent() << ' '; if (control->IsVisible()) stream << "visible "; else stream << "invisible "; stream << control->Position().iX << ',' << control->Position().iY << ' '; stream << control->Size().iWidth << 'x' << control->Size().iHeight; if (control->OwnsWindow()) stream << " ownsWindow "; stream.flush(); result.append(array); } } return result; } QList<QByteArray> QAnnotatorWindow::annotation(const QObject& object) { QList<QByteArray> result; const QWidget* widget = qobject_cast<const QWidget*>(&object); if (widget) { const CCoeControl* control = widget->effectiveWinId(); RDrawableWindow *window = 0; if (control && (window = control->DrawableWindow())) { QByteArray array; QTextStream stream(&array); stream << "window: "; // Server-side address of CWsWindow object // This is useful for correlation with the window tree dumped by the window // server (see RWsSession::LogCommand). // Cast to a void pointer so that log output is in hexadecimal format. stream << "srv " << reinterpret_cast<const void*>(window->WsHandle()) << ' '; stream << "group " << window->WindowGroupId() << ' '; // Client-side handle to the parent window. // Cast to a void pointer so that log output is in hexadecimal format. stream << "parent " << reinterpret_cast<const void*>(window->Parent()) << ' '; stream << window->Position().iX << ',' << window->Position().iY << ' '; stream << '(' << window->AbsPosition().iX << ',' << window->AbsPosition().iY << ") "; stream << window->Size().iWidth << 'x' << window->Size().iHeight << ' '; const TDisplayMode displayMode = window->DisplayMode(); stream << "mode " << displayMode << ' '; stream << "ord " << window->OrdinalPosition(); stream.flush(); result.append(array); } } return result; } } // namespace Symbian void addDefaultAnnotators_sys(QDumper& dumper) { dumper.addAnnotator(new Symbian::QAnnotatorWidget); dumper.addAnnotator(new Symbian::QAnnotatorControl); dumper.addAnnotator(new Symbian::QAnnotatorWindow); } void addDefaultAnnotators_sys(QVisitor& visitor) { visitor.addAnnotator(new Symbian::QAnnotatorWidget); visitor.addAnnotator(new Symbian::QAnnotatorControl); visitor.addAnnotator(new Symbian::QAnnotatorWindow); } } // namespace ObjectDump QT_END_NAMESPACE #endif <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/browser/automation/url_request_mock_http_job.h" #include "chrome/browser/download/save_package.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/url_request/url_request_unittest.h" const std::wstring kTestDir = L"save_page"; class SavePageTest : public UITest { protected: SavePageTest() : UITest() {} void CheckFile(const std::wstring& client_file, const std::wstring& server_file, bool check_equal) { bool exist = false; for (int i = 0; i < 20; ++i) { if (file_util::PathExists(client_file)) { exist = true; break; } Sleep(sleep_timeout_ms()); } EXPECT_TRUE(exist); if (check_equal) { std::wstring server_file_name; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &server_file_name)); server_file_name += L"\\" + kTestDir + L"\\" + server_file; ASSERT_TRUE(file_util::PathExists(server_file_name)); int64 client_file_size = 0; int64 server_file_size = 0; EXPECT_TRUE(file_util::GetFileSize(client_file, &client_file_size)); EXPECT_TRUE(file_util::GetFileSize(server_file_name, &server_file_size)); EXPECT_EQ(client_file_size, server_file_size); EXPECT_TRUE(file_util::ContentsEqual(client_file, server_file_name)); } EXPECT_TRUE(DieFileDie(client_file, false)); } SavePageTest virtual void SetUp() { UITest::SetUp(); EXPECT_TRUE(file_util::CreateNewTempDirectory(L"", &save_dir_)); save_dir_ += FilePath::kSeparators[0]; download_dir_ = GetDownloadDirectory(); download_dir_ += FilePath::kSeparators[0]; } virtual void TearDown() { UITest::TearDown(); DieFileDie(save_dir_, true); } std::wstring save_dir_; std::wstring download_dir_; }; TEST_F(SavePageTest, SaveHTMLOnly) { std::wstring file_name = L"a.htm"; std::wstring full_file_name = save_dir_ + file_name; std::wstring dir = save_dir_ + L"a_files"; GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name); scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilTabCount(1); EXPECT_TRUE(tab->SavePage(full_file_name, dir, SavePackage::SAVE_AS_ONLY_HTML)); EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get())); CheckFile(full_file_name, file_name, true); EXPECT_FALSE(file_util::PathExists(dir)); } TEST_F(SavePageTest, SaveCompleteHTML) { std::wstring file_name = L"b.htm"; std::wstring full_file_name = save_dir_ + file_name; std::wstring dir = save_dir_ + L"b_files"; GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name); scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilTabCount(1); EXPECT_TRUE(tab->SavePage(full_file_name, dir, SavePackage::SAVE_AS_COMPLETE_HTML)); EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get())); CheckFile(dir + L"\\1.png", L"1.png", true); CheckFile(dir + L"\\1.css", L"1.css", true); CheckFile(full_file_name, file_name, false); EXPECT_TRUE(DieFileDie(dir, true)); } TEST_F(SavePageTest, NoSave) { std::wstring file_name = L"c.htm"; std::wstring full_file_name = save_dir_ + file_name; std::wstring dir = save_dir_ + L"c_files"; scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(GURL(L"about:blank"))); WaitUntilTabCount(1); EXPECT_FALSE(tab->SavePage(full_file_name, dir, SavePackage::SAVE_AS_ONLY_HTML)); EXPECT_FALSE(WaitForDownloadShelfVisible(tab.get())); } TEST_F(SavePageTest, FilenameFromPageTitle) { std::wstring file_name = L"b.htm"; std::wstring full_file_name = download_dir_ + L"Test page for saving page feature.htm"; std::wstring dir = download_dir_ + L"Test page for saving page feature_files"; GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name); scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilTabCount(1); scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); automation()->SavePackageShouldPromptUser(false); EXPECT_TRUE(browser->RunCommand(IDC_SAVE_PAGE)); EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get())); automation()->SavePackageShouldPromptUser(true); CheckFile(dir + L"\\1.png", L"1.png", true); CheckFile(dir + L"\\1.css", L"1.css", true); CheckFile(full_file_name, file_name, false); EXPECT_TRUE(DieFileDie(full_file_name, false)); EXPECT_TRUE(DieFileDie(dir, true)); } // BUG 6514 TEST_F(SavePageTest, DISABLED_CleanFilenameFromPageTitle) { std::wstring file_name = L"c.htm"; std::wstring full_file_name = download_dir_ + L"test.htm"; std::wstring dir = download_dir_ + L"test_files"; GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name); scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilTabCount(1); scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); automation()->SavePackageShouldPromptUser(false); EXPECT_TRUE(browser->RunCommand(IDC_SAVE_PAGE)); EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get())); automation()->SavePackageShouldPromptUser(true); CheckFile(full_file_name, file_name, false); EXPECT_TRUE(DieFileDie(full_file_name, false)); EXPECT_TRUE(DieFileDie(dir, true)); } <commit_msg>Removed a stray string. Review URL: http://codereview.chromium.org/18317<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/browser/automation/url_request_mock_http_job.h" #include "chrome/browser/download/save_package.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/url_request/url_request_unittest.h" const std::wstring kTestDir = L"save_page"; class SavePageTest : public UITest { protected: SavePageTest() : UITest() {} void CheckFile(const std::wstring& client_file, const std::wstring& server_file, bool check_equal) { bool exist = false; for (int i = 0; i < 20; ++i) { if (file_util::PathExists(client_file)) { exist = true; break; } Sleep(sleep_timeout_ms()); } EXPECT_TRUE(exist); if (check_equal) { std::wstring server_file_name; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &server_file_name)); server_file_name += L"\\" + kTestDir + L"\\" + server_file; ASSERT_TRUE(file_util::PathExists(server_file_name)); int64 client_file_size = 0; int64 server_file_size = 0; EXPECT_TRUE(file_util::GetFileSize(client_file, &client_file_size)); EXPECT_TRUE(file_util::GetFileSize(server_file_name, &server_file_size)); EXPECT_EQ(client_file_size, server_file_size); EXPECT_TRUE(file_util::ContentsEqual(client_file, server_file_name)); } EXPECT_TRUE(DieFileDie(client_file, false)); } virtual void SetUp() { UITest::SetUp(); EXPECT_TRUE(file_util::CreateNewTempDirectory(L"", &save_dir_)); save_dir_ += FilePath::kSeparators[0]; download_dir_ = GetDownloadDirectory(); download_dir_ += FilePath::kSeparators[0]; } virtual void TearDown() { UITest::TearDown(); DieFileDie(save_dir_, true); } std::wstring save_dir_; std::wstring download_dir_; }; TEST_F(SavePageTest, SaveHTMLOnly) { std::wstring file_name = L"a.htm"; std::wstring full_file_name = save_dir_ + file_name; std::wstring dir = save_dir_ + L"a_files"; GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name); scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilTabCount(1); EXPECT_TRUE(tab->SavePage(full_file_name, dir, SavePackage::SAVE_AS_ONLY_HTML)); EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get())); CheckFile(full_file_name, file_name, true); EXPECT_FALSE(file_util::PathExists(dir)); } TEST_F(SavePageTest, SaveCompleteHTML) { std::wstring file_name = L"b.htm"; std::wstring full_file_name = save_dir_ + file_name; std::wstring dir = save_dir_ + L"b_files"; GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name); scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilTabCount(1); EXPECT_TRUE(tab->SavePage(full_file_name, dir, SavePackage::SAVE_AS_COMPLETE_HTML)); EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get())); CheckFile(dir + L"\\1.png", L"1.png", true); CheckFile(dir + L"\\1.css", L"1.css", true); CheckFile(full_file_name, file_name, false); EXPECT_TRUE(DieFileDie(dir, true)); } TEST_F(SavePageTest, NoSave) { std::wstring file_name = L"c.htm"; std::wstring full_file_name = save_dir_ + file_name; std::wstring dir = save_dir_ + L"c_files"; scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(GURL(L"about:blank"))); WaitUntilTabCount(1); EXPECT_FALSE(tab->SavePage(full_file_name, dir, SavePackage::SAVE_AS_ONLY_HTML)); EXPECT_FALSE(WaitForDownloadShelfVisible(tab.get())); } TEST_F(SavePageTest, FilenameFromPageTitle) { std::wstring file_name = L"b.htm"; std::wstring full_file_name = download_dir_ + L"Test page for saving page feature.htm"; std::wstring dir = download_dir_ + L"Test page for saving page feature_files"; GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name); scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilTabCount(1); scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); automation()->SavePackageShouldPromptUser(false); EXPECT_TRUE(browser->RunCommand(IDC_SAVE_PAGE)); EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get())); automation()->SavePackageShouldPromptUser(true); CheckFile(dir + L"\\1.png", L"1.png", true); CheckFile(dir + L"\\1.css", L"1.css", true); CheckFile(full_file_name, file_name, false); EXPECT_TRUE(DieFileDie(full_file_name, false)); EXPECT_TRUE(DieFileDie(dir, true)); } // BUG 6514 TEST_F(SavePageTest, DISABLED_CleanFilenameFromPageTitle) { std::wstring file_name = L"c.htm"; std::wstring full_file_name = download_dir_ + L"test.htm"; std::wstring dir = download_dir_ + L"test_files"; GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name); scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilTabCount(1); scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); automation()->SavePackageShouldPromptUser(false); EXPECT_TRUE(browser->RunCommand(IDC_SAVE_PAGE)); EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get())); automation()->SavePackageShouldPromptUser(true); CheckFile(full_file_name, file_name, false); EXPECT_TRUE(DieFileDie(full_file_name, false)); EXPECT_TRUE(DieFileDie(dir, true)); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/printing/print_dialog_gtk.h" #include <fcntl.h> #include <gtk/gtkpagesetupunixdialog.h> #include <gtk/gtkprintjob.h> #include <sys/stat.h> #include <sys/types.h> #include "base/file_util.h" #include "base/file_util_proxy.h" #include "base/logging.h" #include "base/synchronization/waitable_event.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_window.h" #include "content/browser/browser_thread.h" #include "printing/print_settings_initializer_gtk.h" // static void* PrintDialogGtk::CreatePrintDialog( PrintingContextCairo::PrintSettingsCallback* callback, PrintingContextCairo* context) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); PrintDialogGtk* dialog = new PrintDialogGtk(callback, context); return dialog; } // static void PrintDialogGtk::PrintDocument(void* print_dialog, const NativeMetafile* metafile, const string16& document_name) { PrintDialogGtk* dialog = static_cast<PrintDialogGtk*>(print_dialog); scoped_ptr<base::WaitableEvent> event(new base::WaitableEvent(false, false)); dialog->set_save_document_event(event.get()); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, NewRunnableMethod(dialog, &PrintDialogGtk::SaveDocumentToDisk, metafile, document_name)); // Wait for SaveDocumentToDisk() to finish. event->Wait(); } PrintDialogGtk::PrintDialogGtk( PrintingContextCairo::PrintSettingsCallback* callback, PrintingContextCairo* context) : callback_(callback), context_(context), dialog_(NULL), page_setup_(NULL), printer_(NULL), gtk_settings_(NULL), save_document_event_(NULL) { // Manual AddRef since PrintDialogGtk manages its own lifetime. AddRef(); GtkWindow* parent = BrowserList::GetLastActive()->window()->GetNativeHandle(); // TODO(estade): We need a window title here. dialog_ = gtk_print_unix_dialog_new(NULL, parent); // Set modal so user cannot focus the same tab and press print again. gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE); // Since we only generate PDF, only show printers that support PDF. // TODO(thestig) Add more capabilities to support? GtkPrintCapabilities cap = static_cast<GtkPrintCapabilities>( GTK_PRINT_CAPABILITY_GENERATE_PDF | GTK_PRINT_CAPABILITY_PAGE_SET | GTK_PRINT_CAPABILITY_COPIES | GTK_PRINT_CAPABILITY_COLLATE | GTK_PRINT_CAPABILITY_REVERSE); gtk_print_unix_dialog_set_manual_capabilities(GTK_PRINT_UNIX_DIALOG(dialog_), cap); #if GTK_CHECK_VERSION(2, 18, 0) gtk_print_unix_dialog_set_embed_page_setup(GTK_PRINT_UNIX_DIALOG(dialog_), TRUE); #endif g_signal_connect(dialog_, "response", G_CALLBACK(OnResponseThunk), this); gtk_widget_show(dialog_); } PrintDialogGtk::~PrintDialogGtk() { gtk_widget_destroy(dialog_); dialog_ = NULL; page_setup_ = NULL; printer_ = NULL; if (gtk_settings_) { g_object_unref(gtk_settings_); gtk_settings_ = NULL; } } void PrintDialogGtk::OnResponse(GtkWidget* dialog, gint response_id) { gtk_widget_hide(dialog_); switch (response_id) { case GTK_RESPONSE_OK: { // |gtk_settings_| is a new object. gtk_settings_ = gtk_print_unix_dialog_get_settings( GTK_PRINT_UNIX_DIALOG(dialog_)); // |printer_| and |page_setup_| are owned by |dialog_|. page_setup_ = gtk_print_unix_dialog_get_page_setup( GTK_PRINT_UNIX_DIALOG(dialog_)); printer_ = gtk_print_unix_dialog_get_selected_printer( GTK_PRINT_UNIX_DIALOG(dialog_)); printing::PageRanges ranges_vector; gint num_ranges; GtkPageRange* gtk_range = gtk_print_settings_get_page_ranges(gtk_settings_, &num_ranges); if (gtk_range) { for (int i = 0; i < num_ranges; ++i) { printing::PageRange* range = new printing::PageRange; range->from = gtk_range[i].start; range->to = gtk_range[i].end; ranges_vector.push_back(*range); } g_free(gtk_range); } printing::PrintSettings settings; printing::PrintSettingsInitializerGtk::InitPrintSettings( gtk_settings_, page_setup_, ranges_vector, false, &settings); context_->InitWithSettings(settings); callback_->Run(PrintingContextCairo::OK); return; } case GTK_RESPONSE_DELETE_EVENT: // Fall through. case GTK_RESPONSE_CANCEL: { callback_->Run(PrintingContextCairo::CANCEL); Release(); return; } case GTK_RESPONSE_APPLY: default: { NOTREACHED(); } } } void PrintDialogGtk::SaveDocumentToDisk(const NativeMetafile* metafile, const string16& document_name) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); bool error = false; if (!file_util::CreateTemporaryFile(&path_to_pdf_)) { LOG(ERROR) << "Creating temporary file failed"; error = true; } if (!error) { base::FileDescriptor temp_file_fd; temp_file_fd.fd = open(path_to_pdf_.value().c_str(), O_WRONLY); temp_file_fd.auto_close = true; if (!metafile->SaveTo(temp_file_fd)) { LOG(ERROR) << "Saving metafile failed"; file_util::Delete(path_to_pdf_, false); error = true; } } // Done saving, let PrintDialogGtk::PrintDocument() continue. save_document_event_->Signal(); if (error) { Release(); } else { // No errors, continue printing. BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &PrintDialogGtk::SendDocumentToPrinter, document_name)); } } void PrintDialogGtk::SendDocumentToPrinter(const string16& document_name) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); GtkPrintJob* print_job = gtk_print_job_new( UTF16ToUTF8(document_name).c_str(), printer_, gtk_settings_, page_setup_); gtk_print_job_set_source_file(print_job, path_to_pdf_.value().c_str(), NULL); gtk_print_job_send(print_job, OnJobCompletedThunk, this, NULL); } // static void PrintDialogGtk::OnJobCompletedThunk(GtkPrintJob* print_job, gpointer user_data, GError* error) { static_cast<PrintDialogGtk*>(user_data)->OnJobCompleted(print_job, error); } void PrintDialogGtk::OnJobCompleted(GtkPrintJob* print_job, GError* error) { if (error) LOG(ERROR) << "Printing failed: " << error->message; if (print_job) g_object_unref(print_job); base::FileUtilProxy::Delete( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE), path_to_pdf_, false, NULL); // Printing finished. Release(); } void PrintDialogGtk::set_save_document_event(base::WaitableEvent* event) { DCHECK(event); DCHECK(!save_document_event_); save_document_event_ = event; } <commit_msg>Linux: Fix leak in print dialog.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/printing/print_dialog_gtk.h" #include <fcntl.h> #include <gtk/gtkpagesetupunixdialog.h> #include <gtk/gtkprintjob.h> #include <sys/stat.h> #include <sys/types.h> #include "base/file_util.h" #include "base/file_util_proxy.h" #include "base/logging.h" #include "base/synchronization/waitable_event.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_window.h" #include "content/browser/browser_thread.h" #include "printing/print_settings_initializer_gtk.h" // static void* PrintDialogGtk::CreatePrintDialog( PrintingContextCairo::PrintSettingsCallback* callback, PrintingContextCairo* context) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); PrintDialogGtk* dialog = new PrintDialogGtk(callback, context); return dialog; } // static void PrintDialogGtk::PrintDocument(void* print_dialog, const NativeMetafile* metafile, const string16& document_name) { PrintDialogGtk* dialog = static_cast<PrintDialogGtk*>(print_dialog); scoped_ptr<base::WaitableEvent> event(new base::WaitableEvent(false, false)); dialog->set_save_document_event(event.get()); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, NewRunnableMethod(dialog, &PrintDialogGtk::SaveDocumentToDisk, metafile, document_name)); // Wait for SaveDocumentToDisk() to finish. event->Wait(); } PrintDialogGtk::PrintDialogGtk( PrintingContextCairo::PrintSettingsCallback* callback, PrintingContextCairo* context) : callback_(callback), context_(context), dialog_(NULL), page_setup_(NULL), printer_(NULL), gtk_settings_(NULL), save_document_event_(NULL) { // Manual AddRef since PrintDialogGtk manages its own lifetime. AddRef(); GtkWindow* parent = BrowserList::GetLastActive()->window()->GetNativeHandle(); // TODO(estade): We need a window title here. dialog_ = gtk_print_unix_dialog_new(NULL, parent); // Set modal so user cannot focus the same tab and press print again. gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE); // Since we only generate PDF, only show printers that support PDF. // TODO(thestig) Add more capabilities to support? GtkPrintCapabilities cap = static_cast<GtkPrintCapabilities>( GTK_PRINT_CAPABILITY_GENERATE_PDF | GTK_PRINT_CAPABILITY_PAGE_SET | GTK_PRINT_CAPABILITY_COPIES | GTK_PRINT_CAPABILITY_COLLATE | GTK_PRINT_CAPABILITY_REVERSE); gtk_print_unix_dialog_set_manual_capabilities(GTK_PRINT_UNIX_DIALOG(dialog_), cap); #if GTK_CHECK_VERSION(2, 18, 0) gtk_print_unix_dialog_set_embed_page_setup(GTK_PRINT_UNIX_DIALOG(dialog_), TRUE); #endif g_signal_connect(dialog_, "response", G_CALLBACK(OnResponseThunk), this); gtk_widget_show(dialog_); } PrintDialogGtk::~PrintDialogGtk() { gtk_widget_destroy(dialog_); dialog_ = NULL; page_setup_ = NULL; printer_ = NULL; if (gtk_settings_) { g_object_unref(gtk_settings_); gtk_settings_ = NULL; } } void PrintDialogGtk::OnResponse(GtkWidget* dialog, gint response_id) { gtk_widget_hide(dialog_); switch (response_id) { case GTK_RESPONSE_OK: { // |gtk_settings_| is a new object. gtk_settings_ = gtk_print_unix_dialog_get_settings( GTK_PRINT_UNIX_DIALOG(dialog_)); // |printer_| and |page_setup_| are owned by |dialog_|. page_setup_ = gtk_print_unix_dialog_get_page_setup( GTK_PRINT_UNIX_DIALOG(dialog_)); printer_ = gtk_print_unix_dialog_get_selected_printer( GTK_PRINT_UNIX_DIALOG(dialog_)); printing::PageRanges ranges_vector; gint num_ranges; GtkPageRange* gtk_range = gtk_print_settings_get_page_ranges(gtk_settings_, &num_ranges); if (gtk_range) { for (int i = 0; i < num_ranges; ++i) { printing::PageRange range; range.from = gtk_range[i].start; range.to = gtk_range[i].end; ranges_vector.push_back(range); } g_free(gtk_range); } printing::PrintSettings settings; printing::PrintSettingsInitializerGtk::InitPrintSettings( gtk_settings_, page_setup_, ranges_vector, false, &settings); context_->InitWithSettings(settings); callback_->Run(PrintingContextCairo::OK); return; } case GTK_RESPONSE_DELETE_EVENT: // Fall through. case GTK_RESPONSE_CANCEL: { callback_->Run(PrintingContextCairo::CANCEL); Release(); return; } case GTK_RESPONSE_APPLY: default: { NOTREACHED(); } } } void PrintDialogGtk::SaveDocumentToDisk(const NativeMetafile* metafile, const string16& document_name) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); bool error = false; if (!file_util::CreateTemporaryFile(&path_to_pdf_)) { LOG(ERROR) << "Creating temporary file failed"; error = true; } if (!error) { base::FileDescriptor temp_file_fd; temp_file_fd.fd = open(path_to_pdf_.value().c_str(), O_WRONLY); temp_file_fd.auto_close = true; if (!metafile->SaveTo(temp_file_fd)) { LOG(ERROR) << "Saving metafile failed"; file_util::Delete(path_to_pdf_, false); error = true; } } // Done saving, let PrintDialogGtk::PrintDocument() continue. save_document_event_->Signal(); if (error) { Release(); } else { // No errors, continue printing. BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &PrintDialogGtk::SendDocumentToPrinter, document_name)); } } void PrintDialogGtk::SendDocumentToPrinter(const string16& document_name) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); GtkPrintJob* print_job = gtk_print_job_new( UTF16ToUTF8(document_name).c_str(), printer_, gtk_settings_, page_setup_); gtk_print_job_set_source_file(print_job, path_to_pdf_.value().c_str(), NULL); gtk_print_job_send(print_job, OnJobCompletedThunk, this, NULL); } // static void PrintDialogGtk::OnJobCompletedThunk(GtkPrintJob* print_job, gpointer user_data, GError* error) { static_cast<PrintDialogGtk*>(user_data)->OnJobCompleted(print_job, error); } void PrintDialogGtk::OnJobCompleted(GtkPrintJob* print_job, GError* error) { if (error) LOG(ERROR) << "Printing failed: " << error->message; if (print_job) g_object_unref(print_job); base::FileUtilProxy::Delete( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE), path_to_pdf_, false, NULL); // Printing finished. Release(); } void PrintDialogGtk::set_save_document_event(base::WaitableEvent* event) { DCHECK(event); DCHECK(!save_document_event_); save_document_event_ = event; } <|endoftext|>
<commit_before>// @(#)root/base:$Id$ // Author: Philippe Canal 13/05/2003 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun, Fons Rademakers and al. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TBranchProxy // // // Base class for all the proxy object. It includes the imeplemtation // of the autoloading of branches as well as all the generic setup // routine. // // ////////////////////////////////////////////////////////////////////////// #include "TBranchProxy.h" #include "TLeaf.h" #include "TBranchElement.h" #include "TStreamerElement.h" #include "TStreamerInfo.h" ClassImp(ROOT::TBranchProxy); ROOT::TBranchProxy::TBranchProxy() : fDirector(0), fInitialized(false), fBranchName(""), fParent(0), fDataMember(""), fIsMember(false), fIsClone(false), fIsaPointer(0), fClassName(""), fClass(0), fElement(0), fMemberOffset(0), fOffset(0), fBranch(0), fBranchCount(0), fLastTree(0), fRead(-1), fWhere(0),fCollection(0) { // Constructor. }; ROOT::TBranchProxy::TBranchProxy(TBranchProxyDirector* boss, const char* top, const char* name) : fDirector(boss), fInitialized(false), fBranchName(top), fParent(0), fDataMember(""), fIsMember(false), fIsClone(false), fIsaPointer(false), fClassName(""), fClass(0), fElement(0), fMemberOffset(0), fOffset(0), fBranch(0), fBranchCount(0), fLastTree(0), fRead(-1), fWhere(0),fCollection(0) { // Constructor. if (fBranchName.Length() && fBranchName[fBranchName.Length()-1]!='.' && name) { ((TString&)fBranchName).Append("."); } if (name) ((TString&)fBranchName).Append(name); boss->Attach(this); } ROOT::TBranchProxy::TBranchProxy(TBranchProxyDirector* boss, const char *top, const char *name, const char *membername) : fDirector(boss), fInitialized(false), fBranchName(top), fParent(0), fDataMember(membername), fIsMember(true), fIsClone(false), fIsaPointer(false), fClassName(""), fClass(0), fElement(0), fMemberOffset(0), fOffset(0), fBranch(0), fBranchCount(0), fLastTree(0), fRead(-1), fWhere(0),fCollection(0) { // Constructor. if (name && strlen(name)) { if (fBranchName.Length() && fBranchName[fBranchName.Length()-1]!='.') { ((TString&)fBranchName).Append("."); } ((TString&)fBranchName).Append(name); } boss->Attach(this); } ROOT::TBranchProxy::TBranchProxy(TBranchProxyDirector* boss, TBranchProxy *parent, const char* membername, const char* top, const char* name) : fDirector(boss), fInitialized(false), fBranchName(top), fParent(parent), fDataMember(membername), fIsMember(true), fIsClone(false), fIsaPointer(false), fClassName(""), fClass(0), fElement(0), fMemberOffset(0), fOffset(0), fBranch(0), fBranchCount(0), fLastTree(0), fRead(-1), fWhere(0),fCollection(0) { // Constructor. if (name && strlen(name)) { if (fBranchName.Length() && fBranchName[fBranchName.Length()-1]!='.') { ((TString&)fBranchName).Append("."); } ((TString&)fBranchName).Append(name); } boss->Attach(this); } ROOT::TBranchProxy::~TBranchProxy() { // Typical Destructor } void ROOT::TBranchProxy::Reset() { // Completely reset the object. fWhere = 0; fBranch = 0; fBranchCount = 0; fRead = -1; fClass = 0; fElement = 0; fMemberOffset = 0; fIsClone = false; fInitialized = false; fLastTree = 0; delete fCollection; } void ROOT::TBranchProxy::Print() { // Display the content of the object cout << "fBranchName " << fBranchName << endl; //cout << "fTree " << fDirector->fTree << endl; cout << "fBranch " << fBranch << endl; if (fBranchCount) cout << "fBranchCount " << fBranchCount << endl; } Bool_t ROOT::TBranchProxy::Setup() { // Initialize/cache the necessary information. // Should we check the type? if (!fDirector->GetTree()) { return false; } if (fParent) { TClass *pcl = fParent->GetClass(); R__ASSERT(pcl); if (pcl==TClonesArray::Class()) { // We always skip the clones array Int_t i = fDirector->GetReadEntry(); if (i<0) fDirector->SetReadEntry(0); fParent->Read(); if (i<0) fDirector->SetReadEntry(i); TClonesArray *clones; clones = (TClonesArray*)fParent->GetStart(); pcl = clones->GetClass(); } else if (pcl->GetCollectionProxy()) { // We always skip the collections. if (fCollection) delete fCollection; fCollection = pcl->GetCollectionProxy()->Generate(); pcl = fCollection->GetValueClass(); } fElement = (TStreamerElement*)pcl->GetStreamerInfo()->GetElements()->FindObject(fDataMember); fIsaPointer = fElement->IsaPointer(); fClass = fElement->GetClassPointer(); R__ASSERT(fElement); fIsClone = (fClass==TClonesArray::Class()); fOffset = fMemberOffset = fElement->GetOffset(); fWhere = fParent->fWhere; // not really used ... it is reset by GetStart and GetClStart if (fParent->IsaPointer()) { // fprintf(stderr,"non-split pointer de-referencing non implemented yet \n"); // nothing to do! } else { // Accumulate offsets. // or not!? fOffset = fMemberOffset = fMemberOffset + fParent->fOffset; } // This is not sufficient for following pointers } else if (!fBranch) { // This does not allow (yet) to precede the branch name with // its mother's name fBranch = fDirector->GetTree()->GetBranch(fBranchName.Data()); if (!fBranch) return false; { // Calculate fBranchCount for a leaf. TLeaf *leaf = (TLeaf*) fBranch->GetListOfLeaves()->At(0); // fBranch->GetLeaf(fLeafname); if (leaf) leaf = leaf->GetLeafCount(); if (leaf) { fBranchCount = leaf->GetBranch(); // fprintf(stderr,"for leaf %s setting up leafcount %s branchcount %s\n", // fBranch->GetName(),leaf->GetName(),fBranchCount->GetName()); //fBranchCount->Print(); } } fWhere = (double*)fBranch->GetAddress(); if (!fWhere && fBranch->IsA()==TBranchElement::Class() && ((TBranchElement*)fBranch)->GetMother()) { TBranchElement* be = ((TBranchElement*)fBranch); be->GetMother()->SetAddress(0); fWhere = (double*)fBranch->GetAddress(); } if (fBranch->IsA()==TBranch::Class()) { TLeaf *leaf2; if (fDataMember.Length()) { leaf2 = fBranch->GetLeaf(fDataMember); fWhere = leaf2->GetValuePointer(); } else if (!fWhere) { leaf2 = (TLeaf*)fBranch->GetListOfLeaves()->At(0); // fBranch->GetLeaf(fLeafname); fWhere = leaf2->GetValuePointer(); } } if (!fWhere) { fBranch->SetAddress(0); fWhere = (double*)fBranch->GetAddress(); } if (fWhere && fBranch->IsA()==TBranchElement::Class()) { TBranchElement* be = ((TBranchElement*)fBranch); TStreamerInfo * info = be->GetInfo(); Int_t id = be->GetID(); if (id>=0) { fOffset = info->GetOffsets()[id]; fElement = (TStreamerElement*)info->GetElements()->At(id); fIsaPointer = fElement->IsaPointer(); fClass = fElement->GetClassPointer(); if ((fIsMember || (be->GetType()!=3 && be->GetType() !=4)) && (be->GetType()!=31 && be->GetType()!=41)) { if (fClass==TClonesArray::Class()) { Int_t i = be->GetTree()->GetReadEntry(); if (i<0) i = 0; be->GetEntry(i); TClonesArray *clones; if ( fIsMember && be->GetType()==3 ) { clones = (TClonesArray*)be->GetObject(); } else if (fIsaPointer) { clones = (TClonesArray*)*(void**)((char*)fWhere+fOffset); } else { clones = (TClonesArray*)((char*)fWhere+fOffset); } if (!fIsMember) fIsClone = true; fClass = clones->GetClass(); } else if (fClass && fClass->GetCollectionProxy()) { delete fCollection; fCollection = fClass->GetCollectionProxy()->Generate(); fClass = fCollection->GetValueClass(); } } if (fClass) fClassName = fClass->GetName(); } else { fClassName = be->GetClassName(); fClass = TClass::GetClass(fClassName); } if (be->GetType()==3) { // top level TClonesArray if (!fIsMember) fIsClone = true; fIsaPointer = false; fWhere = be->GetObject(); } else if (be->GetType()==4) { // top level TClonesArray fCollection = be->GetCollectionProxy()->Generate(); fIsaPointer = false; fWhere = be->GetObject(); } else if (id<0) { // top level object fIsaPointer = false; fWhere = be->GetObject(); } else if (be->GetType()==41) { fCollection = be->GetCollectionProxy()->Generate(); fWhere = be->GetObject(); fOffset += be->GetOffset(); } else if (be->GetType()==31) { fWhere = be->GetObject(); fOffset += be->GetOffset(); } else if (be->GetType()==2) { // this might also be the right path for GetType()==1 fWhere = be->GetObject(); } else { // fWhere = ((unsigned char*)fWhere) + fOffset; fWhere = ((unsigned char*)be->GetObject()) + fOffset; } } else { fClassName = fBranch->GetClassName(); fClass = TClass::GetClass(fClassName); } /* fClassName = fBranch->GetClassName(); // What about TClonesArray? if ( fBranch->IsA()==TBranchElement::Class() && ((TBranchElement*)fBranch)->GetType()==31 ||((TBranchElement*)fBranch)->GetType()==3 ) { Int_t id = ((TBranchElement*)fBranch)->GetID(); if (id>=0) { fElement = ((TStreamerElement*)(((TBranchElement*)fBranch)->GetInfo())->GetElements()->At(id)); fClass = fElement->GetClassPointer(); if (fClass) fClassName = fClass->GetName(); } } if (fClass==0 && fClassName.Length()) fClass = TClass::GetClass(fClassName); */ //fprintf(stderr,"For %s fClass is %p which is %s\n", // fBranchName.Data(),fClass,fClass==0?"not set":fClass->GetName()); if ( fBranch->IsA()==TBranchElement::Class() && (((TBranchElement*)fBranch)->GetType()==3 || fClass==TClonesArray::Class()) && !fIsMember ) { fIsClone = true; } if (fIsMember) { if ( fBranch->IsA()==TBranchElement::Class() && fClass==TClonesArray::Class() && (((TBranchElement*)fBranch)->GetType()==31 || ((TBranchElement*)fBranch)->GetType()==3) ) { TBranchElement *bcount = ((TBranchElement*)fBranch)->GetBranchCount(); TString member; if (bcount) { TString bname = fBranch->GetName(); TString bcname = bcount->GetName(); member = bname.Remove(0,bcname.Length()+1); } else { member = fDataMember; } fMemberOffset = fClass->GetDataMemberOffset(member); if (fMemberOffset<0) { Error("Setup",Form("Negative offset %d for %s in %s", fMemberOffset,fBranch->GetName(), bcount?bcount->GetName():"unknown")); } } else if (fClass) { fElement = (TStreamerElement*) fClass->GetStreamerInfo()->GetElements()->FindObject(fDataMember); if (fElement) fMemberOffset = fElement->GetOffset(); else { // Need to compose the proper sub name TString member; Bool_t forgotWhenThisHappens = false; R__ASSERT(forgotWhenThisHappens); member += fDataMember; fMemberOffset = fClass->GetDataMemberOffset(member); } } else if (fBranch->IsA() != TBranch::Class()) { Error("Setup",Form("Missing TClass object for %s\n",fClassName.Data())); } if ( fBranch->IsA()==TBranchElement::Class() && (((TBranchElement*)fBranch)->GetType()==31 || ((TBranchElement*)fBranch)->GetType()==3) ) { fOffset = fMemberOffset; } else { fWhere = ((unsigned char*)fWhere) + fMemberOffset; } } } if (fClass==TClonesArray::Class()) fIsClone = true; if (fWhere!=0) { if (fCollection) { if (IsaPointer()) { fCollection->PushProxy( *(void**)fWhere ); } else { fCollection->PushProxy( fWhere ); } } fLastTree = fDirector->GetTree(); fInitialized = true; return true; } else { return false; } } <commit_msg>Add missing re-initialization<commit_after>// @(#)root/base:$Id$ // Author: Philippe Canal 13/05/2003 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun, Fons Rademakers and al. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TBranchProxy // // // Base class for all the proxy object. It includes the imeplemtation // of the autoloading of branches as well as all the generic setup // routine. // // ////////////////////////////////////////////////////////////////////////// #include "TBranchProxy.h" #include "TLeaf.h" #include "TBranchElement.h" #include "TStreamerElement.h" #include "TStreamerInfo.h" ClassImp(ROOT::TBranchProxy); ROOT::TBranchProxy::TBranchProxy() : fDirector(0), fInitialized(false), fBranchName(""), fParent(0), fDataMember(""), fIsMember(false), fIsClone(false), fIsaPointer(0), fClassName(""), fClass(0), fElement(0), fMemberOffset(0), fOffset(0), fBranch(0), fBranchCount(0), fLastTree(0), fRead(-1), fWhere(0),fCollection(0) { // Constructor. }; ROOT::TBranchProxy::TBranchProxy(TBranchProxyDirector* boss, const char* top, const char* name) : fDirector(boss), fInitialized(false), fBranchName(top), fParent(0), fDataMember(""), fIsMember(false), fIsClone(false), fIsaPointer(false), fClassName(""), fClass(0), fElement(0), fMemberOffset(0), fOffset(0), fBranch(0), fBranchCount(0), fLastTree(0), fRead(-1), fWhere(0),fCollection(0) { // Constructor. if (fBranchName.Length() && fBranchName[fBranchName.Length()-1]!='.' && name) { ((TString&)fBranchName).Append("."); } if (name) ((TString&)fBranchName).Append(name); boss->Attach(this); } ROOT::TBranchProxy::TBranchProxy(TBranchProxyDirector* boss, const char *top, const char *name, const char *membername) : fDirector(boss), fInitialized(false), fBranchName(top), fParent(0), fDataMember(membername), fIsMember(true), fIsClone(false), fIsaPointer(false), fClassName(""), fClass(0), fElement(0), fMemberOffset(0), fOffset(0), fBranch(0), fBranchCount(0), fLastTree(0), fRead(-1), fWhere(0),fCollection(0) { // Constructor. if (name && strlen(name)) { if (fBranchName.Length() && fBranchName[fBranchName.Length()-1]!='.') { ((TString&)fBranchName).Append("."); } ((TString&)fBranchName).Append(name); } boss->Attach(this); } ROOT::TBranchProxy::TBranchProxy(TBranchProxyDirector* boss, TBranchProxy *parent, const char* membername, const char* top, const char* name) : fDirector(boss), fInitialized(false), fBranchName(top), fParent(parent), fDataMember(membername), fIsMember(true), fIsClone(false), fIsaPointer(false), fClassName(""), fClass(0), fElement(0), fMemberOffset(0), fOffset(0), fBranch(0), fBranchCount(0), fLastTree(0), fRead(-1), fWhere(0),fCollection(0) { // Constructor. if (name && strlen(name)) { if (fBranchName.Length() && fBranchName[fBranchName.Length()-1]!='.') { ((TString&)fBranchName).Append("."); } ((TString&)fBranchName).Append(name); } boss->Attach(this); } ROOT::TBranchProxy::~TBranchProxy() { // Typical Destructor } void ROOT::TBranchProxy::Reset() { // Completely reset the object. fWhere = 0; fBranch = 0; fBranchCount = 0; fRead = -1; fClass = 0; fElement = 0; fMemberOffset = 0; fIsClone = false; fInitialized = false; fLastTree = 0; delete fCollection; fCollection = 0; } void ROOT::TBranchProxy::Print() { // Display the content of the object cout << "fBranchName " << fBranchName << endl; //cout << "fTree " << fDirector->fTree << endl; cout << "fBranch " << fBranch << endl; if (fBranchCount) cout << "fBranchCount " << fBranchCount << endl; } Bool_t ROOT::TBranchProxy::Setup() { // Initialize/cache the necessary information. // Should we check the type? if (!fDirector->GetTree()) { return false; } if (fParent) { TClass *pcl = fParent->GetClass(); R__ASSERT(pcl); if (pcl==TClonesArray::Class()) { // We always skip the clones array Int_t i = fDirector->GetReadEntry(); if (i<0) fDirector->SetReadEntry(0); fParent->Read(); if (i<0) fDirector->SetReadEntry(i); TClonesArray *clones; clones = (TClonesArray*)fParent->GetStart(); pcl = clones->GetClass(); } else if (pcl->GetCollectionProxy()) { // We always skip the collections. if (fCollection) delete fCollection; fCollection = pcl->GetCollectionProxy()->Generate(); pcl = fCollection->GetValueClass(); } fElement = (TStreamerElement*)pcl->GetStreamerInfo()->GetElements()->FindObject(fDataMember); fIsaPointer = fElement->IsaPointer(); fClass = fElement->GetClassPointer(); R__ASSERT(fElement); fIsClone = (fClass==TClonesArray::Class()); fOffset = fMemberOffset = fElement->GetOffset(); fWhere = fParent->fWhere; // not really used ... it is reset by GetStart and GetClStart if (fParent->IsaPointer()) { // fprintf(stderr,"non-split pointer de-referencing non implemented yet \n"); // nothing to do! } else { // Accumulate offsets. // or not!? fOffset = fMemberOffset = fMemberOffset + fParent->fOffset; } // This is not sufficient for following pointers } else if (!fBranch) { // This does not allow (yet) to precede the branch name with // its mother's name fBranch = fDirector->GetTree()->GetBranch(fBranchName.Data()); if (!fBranch) return false; { // Calculate fBranchCount for a leaf. TLeaf *leaf = (TLeaf*) fBranch->GetListOfLeaves()->At(0); // fBranch->GetLeaf(fLeafname); if (leaf) leaf = leaf->GetLeafCount(); if (leaf) { fBranchCount = leaf->GetBranch(); // fprintf(stderr,"for leaf %s setting up leafcount %s branchcount %s\n", // fBranch->GetName(),leaf->GetName(),fBranchCount->GetName()); //fBranchCount->Print(); } } fWhere = (double*)fBranch->GetAddress(); if (!fWhere && fBranch->IsA()==TBranchElement::Class() && ((TBranchElement*)fBranch)->GetMother()) { TBranchElement* be = ((TBranchElement*)fBranch); be->GetMother()->SetAddress(0); fWhere = (double*)fBranch->GetAddress(); } if (fBranch->IsA()==TBranch::Class()) { TLeaf *leaf2; if (fDataMember.Length()) { leaf2 = fBranch->GetLeaf(fDataMember); fWhere = leaf2->GetValuePointer(); } else if (!fWhere) { leaf2 = (TLeaf*)fBranch->GetListOfLeaves()->At(0); // fBranch->GetLeaf(fLeafname); fWhere = leaf2->GetValuePointer(); } } if (!fWhere) { fBranch->SetAddress(0); fWhere = (double*)fBranch->GetAddress(); } if (fWhere && fBranch->IsA()==TBranchElement::Class()) { TBranchElement* be = ((TBranchElement*)fBranch); TStreamerInfo * info = be->GetInfo(); Int_t id = be->GetID(); if (id>=0) { fOffset = info->GetOffsets()[id]; fElement = (TStreamerElement*)info->GetElements()->At(id); fIsaPointer = fElement->IsaPointer(); fClass = fElement->GetClassPointer(); if ((fIsMember || (be->GetType()!=3 && be->GetType() !=4)) && (be->GetType()!=31 && be->GetType()!=41)) { if (fClass==TClonesArray::Class()) { Int_t i = be->GetTree()->GetReadEntry(); if (i<0) i = 0; be->GetEntry(i); TClonesArray *clones; if ( fIsMember && be->GetType()==3 ) { clones = (TClonesArray*)be->GetObject(); } else if (fIsaPointer) { clones = (TClonesArray*)*(void**)((char*)fWhere+fOffset); } else { clones = (TClonesArray*)((char*)fWhere+fOffset); } if (!fIsMember) fIsClone = true; fClass = clones->GetClass(); } else if (fClass && fClass->GetCollectionProxy()) { delete fCollection; fCollection = fClass->GetCollectionProxy()->Generate(); fClass = fCollection->GetValueClass(); } } if (fClass) fClassName = fClass->GetName(); } else { fClassName = be->GetClassName(); fClass = TClass::GetClass(fClassName); } if (be->GetType()==3) { // top level TClonesArray if (!fIsMember) fIsClone = true; fIsaPointer = false; fWhere = be->GetObject(); } else if (be->GetType()==4) { // top level TClonesArray fCollection = be->GetCollectionProxy()->Generate(); fIsaPointer = false; fWhere = be->GetObject(); } else if (id<0) { // top level object fIsaPointer = false; fWhere = be->GetObject(); } else if (be->GetType()==41) { fCollection = be->GetCollectionProxy()->Generate(); fWhere = be->GetObject(); fOffset += be->GetOffset(); } else if (be->GetType()==31) { fWhere = be->GetObject(); fOffset += be->GetOffset(); } else if (be->GetType()==2) { // this might also be the right path for GetType()==1 fWhere = be->GetObject(); } else { // fWhere = ((unsigned char*)fWhere) + fOffset; fWhere = ((unsigned char*)be->GetObject()) + fOffset; } } else { fClassName = fBranch->GetClassName(); fClass = TClass::GetClass(fClassName); } /* fClassName = fBranch->GetClassName(); // What about TClonesArray? if ( fBranch->IsA()==TBranchElement::Class() && ((TBranchElement*)fBranch)->GetType()==31 ||((TBranchElement*)fBranch)->GetType()==3 ) { Int_t id = ((TBranchElement*)fBranch)->GetID(); if (id>=0) { fElement = ((TStreamerElement*)(((TBranchElement*)fBranch)->GetInfo())->GetElements()->At(id)); fClass = fElement->GetClassPointer(); if (fClass) fClassName = fClass->GetName(); } } if (fClass==0 && fClassName.Length()) fClass = TClass::GetClass(fClassName); */ //fprintf(stderr,"For %s fClass is %p which is %s\n", // fBranchName.Data(),fClass,fClass==0?"not set":fClass->GetName()); if ( fBranch->IsA()==TBranchElement::Class() && (((TBranchElement*)fBranch)->GetType()==3 || fClass==TClonesArray::Class()) && !fIsMember ) { fIsClone = true; } if (fIsMember) { if ( fBranch->IsA()==TBranchElement::Class() && fClass==TClonesArray::Class() && (((TBranchElement*)fBranch)->GetType()==31 || ((TBranchElement*)fBranch)->GetType()==3) ) { TBranchElement *bcount = ((TBranchElement*)fBranch)->GetBranchCount(); TString member; if (bcount) { TString bname = fBranch->GetName(); TString bcname = bcount->GetName(); member = bname.Remove(0,bcname.Length()+1); } else { member = fDataMember; } fMemberOffset = fClass->GetDataMemberOffset(member); if (fMemberOffset<0) { Error("Setup",Form("Negative offset %d for %s in %s", fMemberOffset,fBranch->GetName(), bcount?bcount->GetName():"unknown")); } } else if (fClass) { fElement = (TStreamerElement*) fClass->GetStreamerInfo()->GetElements()->FindObject(fDataMember); if (fElement) fMemberOffset = fElement->GetOffset(); else { // Need to compose the proper sub name TString member; Bool_t forgotWhenThisHappens = false; R__ASSERT(forgotWhenThisHappens); member += fDataMember; fMemberOffset = fClass->GetDataMemberOffset(member); } } else if (fBranch->IsA() != TBranch::Class()) { Error("Setup",Form("Missing TClass object for %s\n",fClassName.Data())); } if ( fBranch->IsA()==TBranchElement::Class() && (((TBranchElement*)fBranch)->GetType()==31 || ((TBranchElement*)fBranch)->GetType()==3) ) { fOffset = fMemberOffset; } else { fWhere = ((unsigned char*)fWhere) + fMemberOffset; } } } if (fClass==TClonesArray::Class()) fIsClone = true; if (fWhere!=0) { if (fCollection) { if (IsaPointer()) { fCollection->PushProxy( *(void**)fWhere ); } else { fCollection->PushProxy( fWhere ); } } fLastTree = fDirector->GetTree(); fInitialized = true; return true; } else { return false; } } <|endoftext|>
<commit_before>#include "ImageThresholder.h" #include <chrono> #include <thread> #define EDSIZE 24 #define ERODESIZE 10 //#define IMAGETHRESHOLDER_PARALLEL_FOR //#define IMAGETHRESHOLDER_PARALLEL_THREADS #define IMAGETHRESHOLDER_PARALLEL_INRANGE #ifdef IMAGETHRESHOLDER_PARALLEL_FOR #include <ppl.h> #endif ImageThresholder::ImageThresholder(ThresholdedImages &images, HSVColorRangeMap &objectMap) : ThreadedClass("ImageThresholder"), thresholdedImages(images), objectMap(objectMap) { stop_thread = false; running = false; m_iWorkersInProgress = 0; #if defined(IMAGETHRESHOLDER_PARALLEL_THREADS) for (auto objectRange : objectMap) { auto object = objectRange.first; //threads.create_thread(boost::bind(&ImageThresholder::Run2, this, objectRange.first)); threads.add_thread(new boost::thread(&ImageThresholder::Run2, this, objectRange.first)); } #endif elemDilate = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(EDSIZE, EDSIZE)); //millega hiljem erode ja dilatet teha elemErode = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(EDSIZE + 6, EDSIZE + 6)); elemErode2 = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(ERODESIZE, ERODESIZE)); }; ImageThresholder::~ImageThresholder(){ WaitForStop(); }; void ImageThresholder::Start(cv::Mat &frameHSV, std::vector<OBJECT> objectList) { #if defined(IMAGETHRESHOLDER_PARALLEL_FOR) concurrency::parallel_for_each(begin(objectList), end(objectList), [&frameHSV, this](OBJECT object) { auto r = objectMap[object]; inRange(frameHSV, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]); }); #elif defined(IMAGETHRESHOLDER_PARALLEL_THREADS) if (m_iWorkersInProgress > 0) { std::cout << "Still working" << std::endl; } frame = frameHSV; int mask = 0; for (auto &object : objectList) { //std::cout << "mask " << (1 << object) << " " <<( mask | (1 << object)) << std::endl; mask = mask | (1 << object); } m_iWorkersInProgress = mask; while (m_iWorkersInProgress > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); // limit fps to about 50fps } /* for (auto &object : objectList) { threads.create_thread([&frameHSV, object, this]{ auto r = objectMap[object]; do { inRange(frameHSV, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]); } while (thresholdedImages[object].size().height == 0); }); } */ #elif defined(IMAGETHRESHOLDER_PARALLEL_INRANGE) for (auto &object : objectList) { thresholdedImages[object] = cv::Mat(frameHSV.rows, frameHSV.cols, CV_8U, cv::Scalar::all(0)); } std::map<OBJECT, uchar*> pMap; for (int row = 0; row < frameHSV.rows; ++row) { uchar * p_src = frameHSV.ptr(row); for (auto &object : objectList) { pMap[object] = thresholdedImages[object].ptr(row); } for (int col = 0; col < frameHSV.cols; ++col) { int srcH = *p_src++; int srcS = *p_src++; int srcV = *p_src++; for (auto &object : objectList) { auto r = objectMap[object]; int lhue = r.hue.low; int hhue = r.hue.high; int lsat = r.sat.low; int hsat = r.sat.high; int lval = r.val.low; int hval = r.val.high; if (srcH >= lhue && srcH <= hhue && srcS >= lsat && srcS <= hsat && srcV >= lval && srcV <= hval) { *(pMap[object]) = 255; } (*pMap[object])++; } } /* for (int i = 0; i < frameHSV.rows; i++) { for (int j = 0; j < frameHSV.cols; j++) { cv::Vec3b p = frameHSV.at<cv::Vec3b>(i, j); if (p[0] >= lhue && p[0] <= hhue && p[1] >= lsat && p[1] <= hsat && p[2] >= lval && p[2] <= hval) { thresholdedImages[object].at<unsigned char>(i, j) = 255; } } } */ } #else for (auto &object : objectList) { auto r = objectMap[object]; inRange(frameHSV, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]); } #endif /* if (object == BLUE_GATE || object == YELLOW_GATE) { cv::erode(thresholdedImages[object],thresholdedImages[object],elemErode2); } cv::dilate(thresholdedImages[object],thresholdedImages[object],elemErode2); */ } void ImageThresholder::Run2(OBJECT object){ while (!stop_thread) { if (m_iWorkersInProgress & (1 << object)) { auto r = objectMap[object]; inRange(frame, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]); m_iWorkersInProgress &= ~(1 << object); } else { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } }; <commit_msg>simd principle used<commit_after>#include "ImageThresholder.h" #include <chrono> #include <thread> #include <algorithm> #define EDSIZE 24 #define ERODESIZE 10 //#define IMAGETHRESHOLDER_PARALLEL_FOR //#define IMAGETHRESHOLDER_PARALLEL_THREADS #define IMAGETHRESHOLDER_PARALLEL_INRANGE #ifdef IMAGETHRESHOLDER_PARALLEL_FOR #include <ppl.h> #endif ImageThresholder::ImageThresholder(ThresholdedImages &images, HSVColorRangeMap &objectMap) : ThreadedClass("ImageThresholder"), thresholdedImages(images), objectMap(objectMap) { stop_thread = false; running = false; m_iWorkersInProgress = 0; #if defined(IMAGETHRESHOLDER_PARALLEL_THREADS) for (auto objectRange : objectMap) { auto object = objectRange.first; //threads.create_thread(boost::bind(&ImageThresholder::Run2, this, objectRange.first)); threads.add_thread(new boost::thread(&ImageThresholder::Run2, this, objectRange.first)); } #endif elemDilate = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(EDSIZE, EDSIZE)); //millega hiljem erode ja dilatet teha elemErode = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(EDSIZE + 6, EDSIZE + 6)); elemErode2 = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(ERODESIZE, ERODESIZE)); }; ImageThresholder::~ImageThresholder(){ WaitForStop(); }; void ImageThresholder::Start(cv::Mat &frameHSV, std::vector<OBJECT> objectList) { #if defined(IMAGETHRESHOLDER_PARALLEL_FOR) concurrency::parallel_for_each(begin(objectList), end(objectList), [&frameHSV, this](OBJECT object) { auto r = objectMap[object]; inRange(frameHSV, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]); }); #elif defined(IMAGETHRESHOLDER_PARALLEL_THREADS) if (m_iWorkersInProgress > 0) { std::cout << "Still working" << std::endl; } frame = frameHSV; int mask = 0; for (auto &object : objectList) { //std::cout << "mask " << (1 << object) << " " <<( mask | (1 << object)) << std::endl; mask = mask | (1 << object); } m_iWorkersInProgress = mask; while (m_iWorkersInProgress > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); // limit fps to about 50fps } /* for (auto &object : objectList) { threads.create_thread([&frameHSV, object, this]{ auto r = objectMap[object]; do { inRange(frameHSV, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]); } while (thresholdedImages[object].size().height == 0); }); } */ #elif defined(IMAGETHRESHOLDER_PARALLEL_INRANGE) auto &rb = objectMap[BALL]; auto &rbg = objectMap[BLUE_GATE]; auto &ryg = objectMap[YELLOW_GATE]; for (int i = 0; i < frameHSV.cols*frameHSV.rows * 3; i += 3) { int h = frameHSV.data[i]; int s = frameHSV.data[i + 1]; int v = frameHSV.data[i + 2]; bool ball = (rb.hue.low < h) && (rb.hue.high > h) && (rb.sat.low < s) && (rb.sat.high > s) && (rb.val.low < v) && (rb.val.high > v); bool blue = (rbg.hue.low < h) && (rbg.hue.high > h) && (rbg.sat.low < s) && (rbg.sat.high > s) && (rbg.val.low < v) && (rbg.val.high > v); bool yellow = (ryg.hue.low < h) && (ryg.hue.high > h) && (ryg.sat.low < s) && (ryg.sat.high > s) && (ryg.val.low < v) && (ryg.val.high > v); frameHSV.data[i] = ball ? 255 : 0; frameHSV.data[i + 1] = blue ? 255 : 0; frameHSV.data[i + 2] = yellow ? 255 : 0; } cv::extractChannel(frameHSV, thresholdedImages[BALL], 0); cv::extractChannel(frameHSV, thresholdedImages[BLUE_GATE], 1); cv::extractChannel(frameHSV, thresholdedImages[YELLOW_GATE], 2); #else for (auto &object : objectList) { auto r = objectMap[object]; inRange(frameHSV, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]); } #endif /* if (object == BLUE_GATE || object == YELLOW_GATE) { cv::erode(thresholdedImages[object],thresholdedImages[object],elemErode2); } cv::dilate(thresholdedImages[object],thresholdedImages[object],elemErode2); */ } void ImageThresholder::Run2(OBJECT object){ while (!stop_thread) { if (m_iWorkersInProgress & (1 << object)) { auto r = objectMap[object]; inRange(frame, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]); m_iWorkersInProgress &= ~(1 << object); } else { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } }; <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/printing/printed_document.h" #include <set> #include "base/gfx/platform_device_win.h" #include "base/message_loop.h" #include "base/time.h" #include "chrome/browser/printing/page_number.h" #include "chrome/browser/printing/page_overlays.h" #include "chrome/browser/printing/printed_pages_source.h" #include "chrome/browser/printing/printed_page.h" #include "chrome/browser/printing/units.h" #include "chrome/common/gfx/chrome_font.h" #include "chrome/common/gfx/emf.h" #include "chrome/common/gfx/url_elider.h" #include "chrome/common/time_format.h" #include "chrome/common/notification_service.h" #include "chrome/common/win_util.h" using base::Time; namespace printing { PrintedDocument::PrintedDocument(const PrintSettings& settings, PrintedPagesSource* source, int cookie) : mutable_(source), immutable_(settings, source, cookie) { // Records the expected page count if a range is setup. if (!settings.ranges.empty()) { // If there is a range, set the number of page for (unsigned i = 0; i < settings.ranges.size(); ++i) { const PageRange& range = settings.ranges[i]; mutable_.expected_page_count_ += range.to - range.from + 1; } } } PrintedDocument::~PrintedDocument() { } void PrintedDocument::SetPage(int page_number, gfx::Emf* emf, double shrink) { // Notice the page_number + 1, the reason is that this is the value that will // be shown. Users dislike 0-based counting. scoped_refptr<PrintedPage> page( new PrintedPage(page_number + 1, emf, immutable_.settings_.page_setup_pixels().physical_size())); { AutoLock lock(lock_); mutable_.pages_[page_number] = page; if (mutable_.shrink_factor == 0) { mutable_.shrink_factor = shrink; } else { DCHECK_EQ(mutable_.shrink_factor, shrink); } } NotificationService::current()->Notify( NOTIFY_PRINTED_DOCUMENT_UPDATED, Source<PrintedDocument>(this), Details<PrintedPage>(page)); } bool PrintedDocument::GetPage(int page_number, scoped_refptr<PrintedPage>* page) { bool request = false; { AutoLock lock(lock_); PrintedPages::const_iterator itr = mutable_.pages_.find(page_number); if (itr != mutable_.pages_.end()) { if (itr->second.get()) { *page = itr->second; return true; } request = false; } else { request = true; // Force the creation to not repeatedly request the same page. mutable_.pages_[page_number]; } } if (request) { PrintPage_ThreadJump(page_number); } return false; } void PrintedDocument::RenderPrintedPage(const PrintedPage& page, HDC context) const { #ifndef NDEBUG { // Make sure the page is from our list. AutoLock lock(lock_); DCHECK(&page == mutable_.pages_.find(page.page_number() - 1)->second.get()); } #endif // Save the state to make sure the context this function call does not modify // the device context. int saved_state = SaveDC(context); DCHECK_NE(saved_state, 0); gfx::PlatformDeviceWin::InitializeDC(context); { // Save the state (again) to apply the necessary world transformation. int saved_state = SaveDC(context); DCHECK_NE(saved_state, 0); // Setup the matrix to translate and scale to the right place. Take in // account the actual shrinking factor. XFORM xform = { 0 }; xform.eDx = static_cast<float>( immutable_.settings_.page_setup_pixels().content_area().x()); xform.eDy = static_cast<float>( immutable_.settings_.page_setup_pixels().content_area().y()); xform.eM11 = static_cast<float>(1. / mutable_.shrink_factor); xform.eM22 = static_cast<float>(1. / mutable_.shrink_factor); BOOL res = ModifyWorldTransform(context, &xform, MWT_LEFTMULTIPLY); DCHECK_NE(res, 0); if (!page.emf()->SafePlayback(context)) { NOTREACHED(); } res = RestoreDC(context, saved_state); DCHECK_NE(res, 0); } // Print the header and footer. int base_font_size = ChromeFont().height(); int new_font_size = ConvertUnit(10, immutable_.settings_.desired_dpi, immutable_.settings_.dpi()); DCHECK_GT(new_font_size, base_font_size); ChromeFont font(ChromeFont().DeriveFont(new_font_size - base_font_size)); HGDIOBJ old_font = SelectObject(context, font.hfont()); DCHECK(old_font != NULL); // We don't want a white square around the text ever if overflowing. SetBkMode(context, TRANSPARENT); PrintHeaderFooter(context, page, PageOverlays::LEFT, PageOverlays::TOP, font); PrintHeaderFooter(context, page, PageOverlays::CENTER, PageOverlays::TOP, font); PrintHeaderFooter(context, page, PageOverlays::RIGHT, PageOverlays::TOP, font); PrintHeaderFooter(context, page, PageOverlays::LEFT, PageOverlays::BOTTOM, font); PrintHeaderFooter(context, page, PageOverlays::CENTER, PageOverlays::BOTTOM, font); PrintHeaderFooter(context, page, PageOverlays::RIGHT, PageOverlays::BOTTOM, font); int res = RestoreDC(context, saved_state); DCHECK_NE(res, 0); } bool PrintedDocument::RenderPrintedPageNumber(int page_number, HDC context) { scoped_refptr<PrintedPage> page; if (!GetPage(page_number, &page)) return false; RenderPrintedPage(*page.get(), context); return true; } bool PrintedDocument::IsComplete() const { AutoLock lock(lock_); if (!mutable_.page_count_) return false; PageNumber page(immutable_.settings_, mutable_.page_count_); if (page == PageNumber::npos()) return false; for (; page != PageNumber::npos(); ++page) { PrintedPages::const_iterator itr = mutable_.pages_.find(page.ToInt()); if (itr == mutable_.pages_.end() || !itr->second.get() || !itr->second->emf()) return false; } return true; } bool PrintedDocument::RequestMissingPages() { typedef std::set<int> PageNumbers; PageNumbers missing_pages; { AutoLock lock(lock_); PageNumber page(immutable_.settings_, mutable_.page_count_); if (page == PageNumber::npos()) return false; for (; page != PageNumber::npos(); ++page) { PrintedPage* printed_page = mutable_.pages_[page.ToInt()].get(); if (!printed_page || !printed_page->emf()) missing_pages.insert(page.ToInt()); } } if (!missing_pages.size()) return true; PageNumbers::const_iterator end = missing_pages.end(); for (PageNumbers::const_iterator itr = missing_pages.begin(); itr != end; ++itr) { int page_number = *itr; PrintPage_ThreadJump(page_number); } return true; } void PrintedDocument::DisconnectSource() { AutoLock lock(lock_); mutable_.source_ = NULL; } size_t PrintedDocument::MemoryUsage() const { std::vector<scoped_refptr<PrintedPage>> pages_copy; { AutoLock lock(lock_); pages_copy.reserve(mutable_.pages_.size()); PrintedPages::const_iterator end = mutable_.pages_.end(); for (PrintedPages::const_iterator itr = mutable_.pages_.begin(); itr != end; ++itr) { if (itr->second.get()) { pages_copy.push_back(itr->second); } } } size_t total = 0; for (size_t i = 0; i < pages_copy.size(); ++i) { total += pages_copy[i]->emf()->GetDataSize(); } return total; } void PrintedDocument::set_page_count(int max_page) { { AutoLock lock(lock_); DCHECK_EQ(0, mutable_.page_count_); mutable_.page_count_ = max_page; if (immutable_.settings_.ranges.empty()) { mutable_.expected_page_count_ = max_page; } else { // If there is a range, don't bother since expected_page_count_ is already // initialized. DCHECK_NE(mutable_.expected_page_count_, 0); } } NotificationService::current()->Notify( NOTIFY_PRINTED_DOCUMENT_UPDATED, Source<PrintedDocument>(this), NotificationService::NoDetails()); } int PrintedDocument::page_count() const { AutoLock lock(lock_); return mutable_.page_count_; } int PrintedDocument::expected_page_count() const { AutoLock lock(lock_); return mutable_.expected_page_count_; } void PrintedDocument::PrintHeaderFooter(HDC context, const PrintedPage& page, PageOverlays::HorizontalPosition x, PageOverlays::VerticalPosition y, const ChromeFont& font) const { const PrintSettings& settings = immutable_.settings_; const std::wstring& line = settings.overlays.GetOverlay(x, y); if (line.empty()) { return; } std::wstring output(PageOverlays::ReplaceVariables(line, *this, page)); if (output.empty()) { // May happens if document name or url is empty. return; } const gfx::Size string_size(font.GetStringWidth(output), font.height()); gfx::Rect bounding; bounding.set_height(string_size.height()); const gfx::Rect& overlay_area(settings.page_setup_pixels().overlay_area()); // Hard code .25 cm interstice between overlays. Make sure that some space is // kept between each headers. const int interstice = ConvertUnit(250, kHundrethsMMPerInch, settings.dpi()); const int max_width = overlay_area.width() / 3 - interstice; const int actual_width = std::min(string_size.width(), max_width); switch (x) { case PageOverlays::LEFT: bounding.set_x(overlay_area.x()); bounding.set_width(max_width); break; case PageOverlays::CENTER: bounding.set_x(overlay_area.x() + (overlay_area.width() - actual_width) / 2); bounding.set_width(actual_width); break; case PageOverlays::RIGHT: bounding.set_x(overlay_area.right() - actual_width); bounding.set_width(actual_width); break; } DCHECK_LE(bounding.right(), overlay_area.right()); switch (y) { case PageOverlays::BOTTOM: bounding.set_y(overlay_area.bottom() - string_size.height()); break; case PageOverlays::TOP: bounding.set_y(overlay_area.y()); break; } if (string_size.width() > bounding.width()) output = gfx::ElideText(output, font, bounding.width()); // Save the state (again) for the clipping region. int saved_state = SaveDC(context); DCHECK_NE(saved_state, 0); int result = IntersectClipRect(context, bounding.x(), bounding.y(), bounding.right() + 1, bounding.bottom() + 1); DCHECK(result == SIMPLEREGION || result == COMPLEXREGION); TextOut(context, bounding.x(), bounding.y(), output.c_str(), static_cast<int>(output.size())); int res = RestoreDC(context, saved_state); DCHECK_NE(res, 0); } void PrintedDocument::PrintPage_ThreadJump(int page_number) { if (MessageLoop::current() != immutable_.source_message_loop_) { immutable_.source_message_loop_->PostTask(FROM_HERE, NewRunnableMethod( this, &PrintedDocument::PrintPage_ThreadJump, page_number)); } else { PrintedPagesSource* source = NULL; { AutoLock lock(lock_); source = mutable_.source_; } if (source) { // Don't render with the lock held. source->RenderOnePrintedPage(this, page_number); } else { // Printing has probably been canceled already. } } } PrintedDocument::Mutable::Mutable(PrintedPagesSource* source) : source_(source), expected_page_count_(0), page_count_(0), shrink_factor(0) { } PrintedDocument::Immutable::Immutable(const PrintSettings& settings, PrintedPagesSource* source, int cookie) : settings_(settings), source_message_loop_(MessageLoop::current()), name_(source->RenderSourceName()), url_(source->RenderSourceUrl()), cookie_(cookie) { // Setup the document's date. #ifdef WIN32 // On Windows, use the native time formatting for printing. SYSTEMTIME systemtime; GetLocalTime(&systemtime); date_ = win_util::FormatSystemDate(systemtime, std::wstring()); time_ = win_util::FormatSystemTime(systemtime, std::wstring()); #else Time now = Time::Now(); date_ = TimeFormat::ShortDateNumeric(now); time_ = TimeFormat::TimeOfDay(now); #endif // WIN32 } } // namespace printing <commit_msg>Use ElideUrl for urls. It is much nicer. Review URL: http://codereview.chromium.org/9265<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/printing/printed_document.h" #include <set> #include "base/gfx/platform_device_win.h" #include "base/message_loop.h" #include "base/time.h" #include "chrome/browser/printing/page_number.h" #include "chrome/browser/printing/page_overlays.h" #include "chrome/browser/printing/printed_pages_source.h" #include "chrome/browser/printing/printed_page.h" #include "chrome/browser/printing/units.h" #include "chrome/common/gfx/chrome_font.h" #include "chrome/common/gfx/emf.h" #include "chrome/common/gfx/url_elider.h" #include "chrome/common/time_format.h" #include "chrome/common/notification_service.h" #include "chrome/common/win_util.h" using base::Time; namespace printing { PrintedDocument::PrintedDocument(const PrintSettings& settings, PrintedPagesSource* source, int cookie) : mutable_(source), immutable_(settings, source, cookie) { // Records the expected page count if a range is setup. if (!settings.ranges.empty()) { // If there is a range, set the number of page for (unsigned i = 0; i < settings.ranges.size(); ++i) { const PageRange& range = settings.ranges[i]; mutable_.expected_page_count_ += range.to - range.from + 1; } } } PrintedDocument::~PrintedDocument() { } void PrintedDocument::SetPage(int page_number, gfx::Emf* emf, double shrink) { // Notice the page_number + 1, the reason is that this is the value that will // be shown. Users dislike 0-based counting. scoped_refptr<PrintedPage> page( new PrintedPage(page_number + 1, emf, immutable_.settings_.page_setup_pixels().physical_size())); { AutoLock lock(lock_); mutable_.pages_[page_number] = page; if (mutable_.shrink_factor == 0) { mutable_.shrink_factor = shrink; } else { DCHECK_EQ(mutable_.shrink_factor, shrink); } } NotificationService::current()->Notify( NOTIFY_PRINTED_DOCUMENT_UPDATED, Source<PrintedDocument>(this), Details<PrintedPage>(page)); } bool PrintedDocument::GetPage(int page_number, scoped_refptr<PrintedPage>* page) { bool request = false; { AutoLock lock(lock_); PrintedPages::const_iterator itr = mutable_.pages_.find(page_number); if (itr != mutable_.pages_.end()) { if (itr->second.get()) { *page = itr->second; return true; } request = false; } else { request = true; // Force the creation to not repeatedly request the same page. mutable_.pages_[page_number]; } } if (request) { PrintPage_ThreadJump(page_number); } return false; } void PrintedDocument::RenderPrintedPage(const PrintedPage& page, HDC context) const { #ifndef NDEBUG { // Make sure the page is from our list. AutoLock lock(lock_); DCHECK(&page == mutable_.pages_.find(page.page_number() - 1)->second.get()); } #endif // Save the state to make sure the context this function call does not modify // the device context. int saved_state = SaveDC(context); DCHECK_NE(saved_state, 0); gfx::PlatformDeviceWin::InitializeDC(context); { // Save the state (again) to apply the necessary world transformation. int saved_state = SaveDC(context); DCHECK_NE(saved_state, 0); // Setup the matrix to translate and scale to the right place. Take in // account the actual shrinking factor. XFORM xform = { 0 }; xform.eDx = static_cast<float>( immutable_.settings_.page_setup_pixels().content_area().x()); xform.eDy = static_cast<float>( immutable_.settings_.page_setup_pixels().content_area().y()); xform.eM11 = static_cast<float>(1. / mutable_.shrink_factor); xform.eM22 = static_cast<float>(1. / mutable_.shrink_factor); BOOL res = ModifyWorldTransform(context, &xform, MWT_LEFTMULTIPLY); DCHECK_NE(res, 0); if (!page.emf()->SafePlayback(context)) { NOTREACHED(); } res = RestoreDC(context, saved_state); DCHECK_NE(res, 0); } // Print the header and footer. int base_font_size = ChromeFont().height(); int new_font_size = ConvertUnit(10, immutable_.settings_.desired_dpi, immutable_.settings_.dpi()); DCHECK_GT(new_font_size, base_font_size); ChromeFont font(ChromeFont().DeriveFont(new_font_size - base_font_size)); HGDIOBJ old_font = SelectObject(context, font.hfont()); DCHECK(old_font != NULL); // We don't want a white square around the text ever if overflowing. SetBkMode(context, TRANSPARENT); PrintHeaderFooter(context, page, PageOverlays::LEFT, PageOverlays::TOP, font); PrintHeaderFooter(context, page, PageOverlays::CENTER, PageOverlays::TOP, font); PrintHeaderFooter(context, page, PageOverlays::RIGHT, PageOverlays::TOP, font); PrintHeaderFooter(context, page, PageOverlays::LEFT, PageOverlays::BOTTOM, font); PrintHeaderFooter(context, page, PageOverlays::CENTER, PageOverlays::BOTTOM, font); PrintHeaderFooter(context, page, PageOverlays::RIGHT, PageOverlays::BOTTOM, font); int res = RestoreDC(context, saved_state); DCHECK_NE(res, 0); } bool PrintedDocument::RenderPrintedPageNumber(int page_number, HDC context) { scoped_refptr<PrintedPage> page; if (!GetPage(page_number, &page)) return false; RenderPrintedPage(*page.get(), context); return true; } bool PrintedDocument::IsComplete() const { AutoLock lock(lock_); if (!mutable_.page_count_) return false; PageNumber page(immutable_.settings_, mutable_.page_count_); if (page == PageNumber::npos()) return false; for (; page != PageNumber::npos(); ++page) { PrintedPages::const_iterator itr = mutable_.pages_.find(page.ToInt()); if (itr == mutable_.pages_.end() || !itr->second.get() || !itr->second->emf()) return false; } return true; } bool PrintedDocument::RequestMissingPages() { typedef std::set<int> PageNumbers; PageNumbers missing_pages; { AutoLock lock(lock_); PageNumber page(immutable_.settings_, mutable_.page_count_); if (page == PageNumber::npos()) return false; for (; page != PageNumber::npos(); ++page) { PrintedPage* printed_page = mutable_.pages_[page.ToInt()].get(); if (!printed_page || !printed_page->emf()) missing_pages.insert(page.ToInt()); } } if (!missing_pages.size()) return true; PageNumbers::const_iterator end = missing_pages.end(); for (PageNumbers::const_iterator itr = missing_pages.begin(); itr != end; ++itr) { int page_number = *itr; PrintPage_ThreadJump(page_number); } return true; } void PrintedDocument::DisconnectSource() { AutoLock lock(lock_); mutable_.source_ = NULL; } size_t PrintedDocument::MemoryUsage() const { std::vector<scoped_refptr<PrintedPage>> pages_copy; { AutoLock lock(lock_); pages_copy.reserve(mutable_.pages_.size()); PrintedPages::const_iterator end = mutable_.pages_.end(); for (PrintedPages::const_iterator itr = mutable_.pages_.begin(); itr != end; ++itr) { if (itr->second.get()) { pages_copy.push_back(itr->second); } } } size_t total = 0; for (size_t i = 0; i < pages_copy.size(); ++i) { total += pages_copy[i]->emf()->GetDataSize(); } return total; } void PrintedDocument::set_page_count(int max_page) { { AutoLock lock(lock_); DCHECK_EQ(0, mutable_.page_count_); mutable_.page_count_ = max_page; if (immutable_.settings_.ranges.empty()) { mutable_.expected_page_count_ = max_page; } else { // If there is a range, don't bother since expected_page_count_ is already // initialized. DCHECK_NE(mutable_.expected_page_count_, 0); } } NotificationService::current()->Notify( NOTIFY_PRINTED_DOCUMENT_UPDATED, Source<PrintedDocument>(this), NotificationService::NoDetails()); } int PrintedDocument::page_count() const { AutoLock lock(lock_); return mutable_.page_count_; } int PrintedDocument::expected_page_count() const { AutoLock lock(lock_); return mutable_.expected_page_count_; } void PrintedDocument::PrintHeaderFooter(HDC context, const PrintedPage& page, PageOverlays::HorizontalPosition x, PageOverlays::VerticalPosition y, const ChromeFont& font) const { const PrintSettings& settings = immutable_.settings_; const std::wstring& line = settings.overlays.GetOverlay(x, y); if (line.empty()) { return; } std::wstring output(PageOverlays::ReplaceVariables(line, *this, page)); if (output.empty()) { // May happens if document name or url is empty. return; } const gfx::Size string_size(font.GetStringWidth(output), font.height()); gfx::Rect bounding; bounding.set_height(string_size.height()); const gfx::Rect& overlay_area(settings.page_setup_pixels().overlay_area()); // Hard code .25 cm interstice between overlays. Make sure that some space is // kept between each headers. const int interstice = ConvertUnit(250, kHundrethsMMPerInch, settings.dpi()); const int max_width = overlay_area.width() / 3 - interstice; const int actual_width = std::min(string_size.width(), max_width); switch (x) { case PageOverlays::LEFT: bounding.set_x(overlay_area.x()); bounding.set_width(max_width); break; case PageOverlays::CENTER: bounding.set_x(overlay_area.x() + (overlay_area.width() - actual_width) / 2); bounding.set_width(actual_width); break; case PageOverlays::RIGHT: bounding.set_x(overlay_area.right() - actual_width); bounding.set_width(actual_width); break; } DCHECK_LE(bounding.right(), overlay_area.right()); switch (y) { case PageOverlays::BOTTOM: bounding.set_y(overlay_area.bottom() - string_size.height()); break; case PageOverlays::TOP: bounding.set_y(overlay_area.y()); break; } if (string_size.width() > bounding.width()) { if (line == PageOverlays::kUrl) { output = gfx::ElideUrl(url(), font, bounding.width(), std::wstring()); } else { output = gfx::ElideText(output, font, bounding.width()); } } // Save the state (again) for the clipping region. int saved_state = SaveDC(context); DCHECK_NE(saved_state, 0); int result = IntersectClipRect(context, bounding.x(), bounding.y(), bounding.right() + 1, bounding.bottom() + 1); DCHECK(result == SIMPLEREGION || result == COMPLEXREGION); TextOut(context, bounding.x(), bounding.y(), output.c_str(), static_cast<int>(output.size())); int res = RestoreDC(context, saved_state); DCHECK_NE(res, 0); } void PrintedDocument::PrintPage_ThreadJump(int page_number) { if (MessageLoop::current() != immutable_.source_message_loop_) { immutable_.source_message_loop_->PostTask(FROM_HERE, NewRunnableMethod( this, &PrintedDocument::PrintPage_ThreadJump, page_number)); } else { PrintedPagesSource* source = NULL; { AutoLock lock(lock_); source = mutable_.source_; } if (source) { // Don't render with the lock held. source->RenderOnePrintedPage(this, page_number); } else { // Printing has probably been canceled already. } } } PrintedDocument::Mutable::Mutable(PrintedPagesSource* source) : source_(source), expected_page_count_(0), page_count_(0), shrink_factor(0) { } PrintedDocument::Immutable::Immutable(const PrintSettings& settings, PrintedPagesSource* source, int cookie) : settings_(settings), source_message_loop_(MessageLoop::current()), name_(source->RenderSourceName()), url_(source->RenderSourceUrl()), cookie_(cookie) { // Setup the document's date. #ifdef WIN32 // On Windows, use the native time formatting for printing. SYSTEMTIME systemtime; GetLocalTime(&systemtime); date_ = win_util::FormatSystemDate(systemtime, std::wstring()); time_ = win_util::FormatSystemTime(systemtime, std::wstring()); #else Time now = Time::Now(); date_ = TimeFormat::ShortDateNumeric(now); time_ = TimeFormat::TimeOfDay(now); #endif // WIN32 } } // namespace printing <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // Name: managedframe.cpp // Purpose: Implementation of wxExManagedFrame class. // Author: Anton van Wezenbeek // Created: 2010-04-11 // RCS-ID: $Id$ // Copyright: (c) 2010 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/wxcrt.h> #include <wx/extension/managedframe.h> #include <wx/extension/defs.h> #include <wx/extension/frd.h> #include <wx/extension/stc.h> #include <wx/extension/toolbar.h> #include <wx/extension/util.h> #include <wx/extension/vi.h> #if wxUSE_GUI // Support class. // Offers a text ctrl related to a vi object. class wxExViFindCtrl: public wxTextCtrl { public: /// Constructor. Fills the combobox box with values /// from FindReplace from config. wxExViFindCtrl( wxWindow* parent, wxExManagedFrame* frame, wxStaticText* text, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize); /// Sets callback. void SetVi(wxExVi* vi) {m_vi = vi;}; protected: void OnCommand(wxCommandEvent& event); void OnEnter(wxCommandEvent& event); void OnKey(wxKeyEvent& event); private: wxExManagedFrame* m_Frame; wxExVi* m_vi; wxStaticText* m_StaticText; bool m_UserInput; DECLARE_EVENT_TABLE() }; BEGIN_EVENT_TABLE(wxExManagedFrame, wxExFrame) EVT_MENU(wxID_PREFERENCES, wxExManagedFrame::OnCommand) EVT_MENU_RANGE(ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnCommand) EVT_UPDATE_UI_RANGE( ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnUpdateUI) END_EVENT_TABLE() wxExManagedFrame::wxExManagedFrame(wxWindow* parent, wxWindowID id, const wxString& title, long style) : wxExFrame(parent, id, title, style) { m_Manager.SetManagedWindow(this); wxExToolBar* toolBar = new wxExToolBar(this); toolBar->AddControls(); DoAddControl(toolBar); AddToolBarPane(toolBar, "TOOLBAR", _("Toolbar")); AddToolBarPane(new wxExFindToolBar(this), "FINDBAR"); CreateViPanel(m_viFindPrefix, m_viFind, "VIFINDBAR"); CreateViPanel(m_viCommandPrefix, m_viCommand, "VICOMMANDBAR"); m_Manager.Update(); } wxExManagedFrame::~wxExManagedFrame() { m_Manager.UnInit(); } bool wxExManagedFrame::AddToolBarPane( wxWindow* window, const wxString& name, const wxString& caption) { wxAuiPaneInfo pane; pane .LeftDockable(false) .RightDockable(false) .Name(name); // The real toolbar is at the top, others at bottom and initially hidden. if (!caption.empty()) { pane .Top() .ToolbarPane() .Caption(caption); } else { pane .Bottom() .CloseButton(false) .Hide() .DockFixed(true) .Movable(false) .CaptionVisible(false); } return m_Manager.AddPane(window, pane); } void wxExManagedFrame::CreateViPanel( wxStaticText*& statictext, wxExViFindCtrl*& victrl, const wxString& name) { // A vi panel starts with small static text for : or /, then // comes the vi ctrl for getting user input. wxPanel* panel = new wxPanel(this); statictext = new wxStaticText(panel, wxID_ANY, wxEmptyString); victrl = new wxExViFindCtrl(panel, this, statictext, wxID_ANY); wxFlexGridSizer* sizer = new wxFlexGridSizer(2); sizer->AddGrowableCol(1); sizer->Add(statictext, wxSizerFlags().Expand()); sizer->Add(victrl, wxSizerFlags().Expand()); panel->SetSizerAndFit(sizer); AddToolBarPane(panel, name); } void wxExManagedFrame::GetViCommand(wxExVi* vi, const wxString& command) { if (command == ":") { GetViPaneCommand( m_viCommandPrefix, m_viCommand, "VICOMMANDBAR", vi, command); } else { // sync with frd data. m_viFind->SetValue(wxExFindReplaceData::Get()->GetFindString()); GetViPaneCommand( m_viFindPrefix, m_viFind, "VIFINDBAR", vi, command); } } void wxExManagedFrame::GetViPaneCommand( wxStaticText* statictext, wxExViFindCtrl* victrl, const wxString& pane, wxExVi* vi, const wxString& command) { statictext->SetLabel(command); victrl->Show(); victrl->SelectAll(); victrl->SetFocus(); victrl->SetVi(vi); m_Manager.GetPane(pane).Show(); m_Manager.Update(); } void wxExManagedFrame::HideViBar() { if (m_Manager.GetPane("VIFINDBAR").IsShown()) { m_Manager.GetPane("VIFINDBAR").Hide(); m_Manager.Update(); } if (m_Manager.GetPane("VICOMMANDBAR").IsShown()) { m_Manager.GetPane("VICOMMANDBAR").Hide(); m_Manager.Update(); } wxExSTC* stc = GetSTC(); if (stc != NULL) { stc->SetFocus(); } } void wxExManagedFrame::OnCommand(wxCommandEvent& event) { switch (event.GetId()) { case wxID_PREFERENCES: wxExSTC::ConfigDialog(this, _("Editor Options"), wxExSTC::STC_CONFIG_MODELESS | wxExSTC::STC_CONFIG_SIMPLE | wxExSTC::STC_CONFIG_WITH_APPLY, event.GetId()); break; case ID_VIEW_FINDBAR: TogglePane("FINDBAR"); break; case ID_VIEW_TOOLBAR: TogglePane("TOOLBAR"); break; default: wxFAIL; } } void wxExManagedFrame::OnUpdateUI(wxUpdateUIEvent& event) { switch (event.GetId()) { case ID_VIEW_FINDBAR: event.Check(m_Manager.GetPane("FINDBAR").IsShown()); break; case ID_VIEW_TOOLBAR: event.Check(m_Manager.GetPane("TOOLBAR").IsShown()); break; default: wxFAIL; } } void wxExManagedFrame::ShowViMessage(const wxString& text) { if (GetStatusBar()->IsShown()) { GetStatusBar()->SetStatusText(text); m_Manager.GetPane("VICOMMANDBAR").Hide(); } else { m_viCommandPrefix->SetLabel(text); m_viCommand->Hide(); m_Manager.GetPane("VICOMMANDBAR").Show(); } m_Manager.GetPane("VIFINDBAR").Hide(); m_Manager.Update(); } void wxExManagedFrame::TogglePane(const wxString& pane) { wxAuiPaneInfo& info = m_Manager.GetPane(pane); wxASSERT(info.IsOk()); info.IsShown() ? info.Hide(): info.Show(); m_Manager.Update(); } // Implementation of support class. BEGIN_EVENT_TABLE(wxExViFindCtrl, wxTextCtrl) EVT_CHAR(wxExViFindCtrl::OnKey) EVT_TEXT(wxID_ANY, wxExViFindCtrl::OnCommand) EVT_TEXT_ENTER(wxID_ANY, wxExViFindCtrl::OnEnter) END_EVENT_TABLE() wxExViFindCtrl::wxExViFindCtrl( wxWindow* parent, wxExManagedFrame* frame, wxStaticText* text, wxWindowID id, const wxPoint& pos, const wxSize& size) : wxTextCtrl(parent, id, wxEmptyString, pos, size, wxTE_PROCESS_ENTER) , m_Frame(frame) , m_vi(NULL) , m_StaticText(text) , m_UserInput(false) { } void wxExViFindCtrl::OnCommand(wxCommandEvent& event) { event.Skip(); if (m_UserInput && m_vi != NULL && m_StaticText->GetLabel() != ":") { m_vi->PositionRestore(); m_vi->GetSTC()->FindNext( GetValue(), m_vi->GetSearchFlags(), m_StaticText->GetLabel() == '/'); } } void wxExViFindCtrl::OnEnter(wxCommandEvent& event) { if (m_StaticText->GetLabel() == ":") { if (m_vi != NULL) { if (m_vi->ExecCommand(GetValue())) { m_Frame->HideViBar(); } } } else { if (!GetValue().empty()) { wxExFindReplaceData::Get()->SetFindString(GetValue()); } m_Frame->HideViBar(); } } void wxExViFindCtrl::OnKey(wxKeyEvent& event) { const auto key = event.GetKeyCode(); if (key == WXK_ESCAPE) { if (m_vi != NULL) { m_vi->PositionRestore(); } m_Frame->HideViBar(); m_UserInput = false; } else { if (!m_UserInput) { m_vi->PositionSave(); m_UserInput = true; } event.Skip(); } } #endif // wxUSE_GUI <commit_msg>fixed user input problem<commit_after>//////////////////////////////////////////////////////////////////////////////// // Name: managedframe.cpp // Purpose: Implementation of wxExManagedFrame class. // Author: Anton van Wezenbeek // Created: 2010-04-11 // RCS-ID: $Id$ // Copyright: (c) 2010 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/wxcrt.h> #include <wx/extension/managedframe.h> #include <wx/extension/defs.h> #include <wx/extension/frd.h> #include <wx/extension/stc.h> #include <wx/extension/toolbar.h> #include <wx/extension/util.h> #include <wx/extension/vi.h> #if wxUSE_GUI // Support class. // Offers a text ctrl related to a vi object. class wxExViFindCtrl: public wxTextCtrl { public: /// Constructor. Fills the combobox box with values /// from FindReplace from config. wxExViFindCtrl( wxWindow* parent, wxExManagedFrame* frame, wxStaticText* text, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize); /// Sets callback. void SetVi(wxExVi* vi); protected: void OnCommand(wxCommandEvent& event); void OnEnter(wxCommandEvent& event); void OnKey(wxKeyEvent& event); private: wxExManagedFrame* m_Frame; wxExVi* m_vi; wxStaticText* m_StaticText; bool m_UserInput; DECLARE_EVENT_TABLE() }; BEGIN_EVENT_TABLE(wxExManagedFrame, wxExFrame) EVT_MENU(wxID_PREFERENCES, wxExManagedFrame::OnCommand) EVT_MENU_RANGE(ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnCommand) EVT_UPDATE_UI_RANGE( ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnUpdateUI) END_EVENT_TABLE() wxExManagedFrame::wxExManagedFrame(wxWindow* parent, wxWindowID id, const wxString& title, long style) : wxExFrame(parent, id, title, style) { m_Manager.SetManagedWindow(this); wxExToolBar* toolBar = new wxExToolBar(this); toolBar->AddControls(); DoAddControl(toolBar); AddToolBarPane(toolBar, "TOOLBAR", _("Toolbar")); AddToolBarPane(new wxExFindToolBar(this), "FINDBAR"); CreateViPanel(m_viFindPrefix, m_viFind, "VIFINDBAR"); CreateViPanel(m_viCommandPrefix, m_viCommand, "VICOMMANDBAR"); m_Manager.Update(); } wxExManagedFrame::~wxExManagedFrame() { m_Manager.UnInit(); } bool wxExManagedFrame::AddToolBarPane( wxWindow* window, const wxString& name, const wxString& caption) { wxAuiPaneInfo pane; pane .LeftDockable(false) .RightDockable(false) .Name(name); // The real toolbar is at the top, others at bottom and initially hidden. if (!caption.empty()) { pane .Top() .ToolbarPane() .Caption(caption); } else { pane .Bottom() .CloseButton(false) .Hide() .DockFixed(true) .Movable(false) .CaptionVisible(false); } return m_Manager.AddPane(window, pane); } void wxExManagedFrame::CreateViPanel( wxStaticText*& statictext, wxExViFindCtrl*& victrl, const wxString& name) { // A vi panel starts with small static text for : or /, then // comes the vi ctrl for getting user input. wxPanel* panel = new wxPanel(this); statictext = new wxStaticText(panel, wxID_ANY, wxEmptyString); victrl = new wxExViFindCtrl(panel, this, statictext, wxID_ANY); wxFlexGridSizer* sizer = new wxFlexGridSizer(2); sizer->AddGrowableCol(1); sizer->Add(statictext, wxSizerFlags().Expand()); sizer->Add(victrl, wxSizerFlags().Expand()); panel->SetSizerAndFit(sizer); AddToolBarPane(panel, name); } void wxExManagedFrame::GetViCommand(wxExVi* vi, const wxString& command) { if (command == ":") { GetViPaneCommand( m_viCommandPrefix, m_viCommand, "VICOMMANDBAR", vi, command); } else { // sync with frd data. m_viFind->SetValue(wxExFindReplaceData::Get()->GetFindString()); GetViPaneCommand( m_viFindPrefix, m_viFind, "VIFINDBAR", vi, command); } } void wxExManagedFrame::GetViPaneCommand( wxStaticText* statictext, wxExViFindCtrl* victrl, const wxString& pane, wxExVi* vi, const wxString& command) { statictext->SetLabel(command); victrl->SetVi(vi); m_Manager.GetPane(pane).Show(); m_Manager.Update(); } void wxExManagedFrame::HideViBar() { if (m_Manager.GetPane("VIFINDBAR").IsShown()) { m_Manager.GetPane("VIFINDBAR").Hide(); m_Manager.Update(); } if (m_Manager.GetPane("VICOMMANDBAR").IsShown()) { m_Manager.GetPane("VICOMMANDBAR").Hide(); m_Manager.Update(); } wxExSTC* stc = GetSTC(); if (stc != NULL) { stc->SetFocus(); } } void wxExManagedFrame::OnCommand(wxCommandEvent& event) { switch (event.GetId()) { case wxID_PREFERENCES: wxExSTC::ConfigDialog(this, _("Editor Options"), wxExSTC::STC_CONFIG_MODELESS | wxExSTC::STC_CONFIG_SIMPLE | wxExSTC::STC_CONFIG_WITH_APPLY, event.GetId()); break; case ID_VIEW_FINDBAR: TogglePane("FINDBAR"); break; case ID_VIEW_TOOLBAR: TogglePane("TOOLBAR"); break; default: wxFAIL; } } void wxExManagedFrame::OnUpdateUI(wxUpdateUIEvent& event) { switch (event.GetId()) { case ID_VIEW_FINDBAR: event.Check(m_Manager.GetPane("FINDBAR").IsShown()); break; case ID_VIEW_TOOLBAR: event.Check(m_Manager.GetPane("TOOLBAR").IsShown()); break; default: wxFAIL; } } void wxExManagedFrame::ShowViMessage(const wxString& text) { if (GetStatusBar()->IsShown()) { GetStatusBar()->SetStatusText(text); m_Manager.GetPane("VICOMMANDBAR").Hide(); } else { m_viCommandPrefix->SetLabel(text); m_viCommand->Hide(); m_Manager.GetPane("VICOMMANDBAR").Show(); } m_Manager.GetPane("VIFINDBAR").Hide(); m_Manager.Update(); } void wxExManagedFrame::TogglePane(const wxString& pane) { wxAuiPaneInfo& info = m_Manager.GetPane(pane); wxASSERT(info.IsOk()); info.IsShown() ? info.Hide(): info.Show(); m_Manager.Update(); } // Implementation of support class. BEGIN_EVENT_TABLE(wxExViFindCtrl, wxTextCtrl) EVT_CHAR(wxExViFindCtrl::OnKey) EVT_TEXT(wxID_ANY, wxExViFindCtrl::OnCommand) EVT_TEXT_ENTER(wxID_ANY, wxExViFindCtrl::OnEnter) END_EVENT_TABLE() wxExViFindCtrl::wxExViFindCtrl( wxWindow* parent, wxExManagedFrame* frame, wxStaticText* text, wxWindowID id, const wxPoint& pos, const wxSize& size) : wxTextCtrl(parent, id, wxEmptyString, pos, size, wxTE_PROCESS_ENTER) , m_Frame(frame) , m_vi(NULL) , m_StaticText(text) , m_UserInput(false) { } void wxExViFindCtrl::OnCommand(wxCommandEvent& event) { event.Skip(); if (m_UserInput && m_vi != NULL && m_StaticText->GetLabel() != ":") { m_vi->PositionRestore(); m_vi->GetSTC()->FindNext( GetValue(), m_vi->GetSearchFlags(), m_StaticText->GetLabel() == '/'); } } void wxExViFindCtrl::OnEnter(wxCommandEvent& event) { if (m_StaticText->GetLabel() == ":") { if (m_vi != NULL) { if (m_vi->ExecCommand(GetValue())) { m_Frame->HideViBar(); } } } else { if (!GetValue().empty()) { wxExFindReplaceData::Get()->SetFindString(GetValue()); } m_Frame->HideViBar(); } } void wxExViFindCtrl::OnKey(wxKeyEvent& event) { const auto key = event.GetKeyCode(); if (key == WXK_ESCAPE) { if (m_vi != NULL) { m_vi->PositionRestore(); } m_Frame->HideViBar(); m_UserInput = false; } else { if (!m_UserInput) { m_vi->PositionSave(); m_UserInput = true; } event.Skip(); } } void wxExViFindCtrl::SetVi(wxExVi* vi) { m_vi = vi; m_UserInput = false; Show(); SelectAll(); SetFocus(); }; #endif // wxUSE_GUI <|endoftext|>
<commit_before>// Copyright (c) 2013 The Chromium OS 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 "chromiumos-wide-profiling/address_mapper.h" #include "base/logging.h" #include "chromiumos-wide-profiling/limits.h" #include <vector> namespace quipper { AddressMapper::AddressMapper(const AddressMapper& source) { mappings_ = source.mappings_; real_address_map_ = source.real_address_map_; } bool AddressMapper::Map(const uint64_t real_addr, const uint64_t size, const bool remove_existing_mappings) { return MapWithID(real_addr, size, kUint64Max, 0, remove_existing_mappings); } bool AddressMapper::MapWithID(const uint64_t real_addr, const uint64_t size, const uint64_t id, const uint64_t offset_base, bool remove_existing_mappings) { MappedRange range; range.real_addr = real_addr; range.size = size; range.id = id; range.offset_base = offset_base; if (size == 0) { LOG(ERROR) << "Must allocate a nonzero-length address range."; return false; } // Check that this mapping does not overflow the address space. if (real_addr + size - 1 != kUint64Max && !(real_addr + size > real_addr)) { DumpToLog(); LOG(ERROR) << "Address mapping at " << std::hex << real_addr << " with size " << std::hex << size << " overflows."; return false; } // Check for collision with an existing mapping. This must be an overlap that // does not result in one range being completely covered by another MappingList::iterator iter; if (!mappings_.empty()) { std::vector<MappedRange> mappings_to_delete; bool old_range_found = false; MappedRange old_range; iter = find(real_addr); if (iter != mappings_.begin() && iter->second.real_addr > real_addr) --iter; for (; iter != mappings_.end() && iter->second.real_addr < (real_addr + size); ++iter) { if (!iter->second.Intersects(range)) continue; // Quit if existing ranges that collide aren't supposed to be removed. if (!remove_existing_mappings) return false; if (!old_range_found && iter->second.Covers(range) && iter->second.size > range.size) { old_range_found = true; old_range = iter->second; continue; } mappings_to_delete.push_back(iter->second); } for (const MappedRange &R : mappings_to_delete) CHECK(Unmap(R)); // Otherwise check for this range being covered by another range. If that // happens, split or reduce the existing range to make room. if (old_range_found) { CHECK(Unmap(old_range)); uint64_t gap_before = range.real_addr - old_range.real_addr; uint64_t gap_after = (old_range.real_addr + old_range.size) - (range.real_addr + range.size); if (gap_before) { CHECK(MapWithID(old_range.real_addr, gap_before, old_range.id, old_range.offset_base, false)); } CHECK(MapWithID(range.real_addr, range.size, id, offset_base, false)); if (gap_after) { CHECK(MapWithID(range.real_addr + range.size, gap_after, old_range.id, old_range.offset_base + gap_before + range.size, false)); } return true; } } // Now search for a location for the new range. It should be in the first // free block in quipper space. // If there is no existing mapping, add it to the beginning of quipper space. if (mappings_.empty()) { range.mapped_addr = 0; range.unmapped_space_after = kUint64Max - range.size; insert(range); return true; } CHECK(!real_address_map_.empty()); // If there is space before the first mapped range in quipper space, use it. uint64_t first_mapped = real_address_map_.begin()->first; if (first_mapped >= range.size) { range.mapped_addr = 0; range.unmapped_space_after = first_mapped - range.size; insert(range); return true; } // Otherwise, search through the existing mappings for a free block after one // of them. MappingList::iterator first = mappings_.end(); uint64_t last_mapped_start = real_address_map_.rbegin()->first; for (iter = mappings_.begin(); iter != mappings_.end(); ++iter) { if (iter->second.unmapped_space_after < size) continue; first = iter; if (iter->second.mapped_addr != last_mapped_start) break; } if (first != mappings_.end()) { range.mapped_addr = first->second.mapped_addr + first->second.size; range.unmapped_space_after = first->second.unmapped_space_after - range.size; first->second.unmapped_space_after = 0; insert(range); return true; } // If it still hasn't succeeded in mapping, it means there is no free space in // quipper space large enough for a mapping of this size. DumpToLog(); LOG(ERROR) << "Could not find space to map addr=" << std::hex << real_addr << " with size " << std::hex << size; return false; } void AddressMapper::DumpToLog() const { MappingList::const_iterator it; for (it = mappings_.begin(); it != mappings_.end(); ++it) { LOG(INFO) << " real_addr: " << std::hex << it->second.real_addr << " mapped: " << std::hex << it->second.mapped_addr << " id: " << std::hex << it->second.id << " size: " << std::hex << it->second.size; } } bool AddressMapper::GetMappedAddress(const uint64_t real_addr, uint64_t* mapped_addr) const { CHECK(mapped_addr); MappingList::const_iterator iter = find(real_addr); if (!iter->second.ContainsAddress(real_addr)) return false; *mapped_addr = iter->second.mapped_addr + real_addr - iter->second.real_addr; return true; } bool AddressMapper::GetMappedIDAndOffset(const uint64_t real_addr, uint64_t* id, uint64_t* offset) const { CHECK(id); CHECK(offset); MappingList::const_iterator iter = find(real_addr); if (!iter->second.ContainsAddress(real_addr)) return false; *id = iter->second.id; *offset = real_addr - iter->second.real_addr + iter->second.offset_base; return true; } uint64_t AddressMapper::GetMaxMappedLength() const { if (IsEmpty()) return 0; // The first mapped address uint64_t min = real_address_map_.begin()->first; // The real address start of the last mapped range uint64_t last_real_start = real_address_map_.rbegin()->second; auto iter = find(last_real_start); uint64_t last_addr = iter->second.mapped_addr; // The end of the last mapped range uint64_t max = last_addr + iter->second.size; return max - min; } bool AddressMapper::Unmap(const MappedRange &range) { // Find the range to be removed auto range_iter = mappings_.find(range.real_addr); if (!range_iter->second.Matches(range)) return false; // Find the range that preceeds this in mapped space. auto iter = real_address_map_.find(range_iter->second.mapped_addr); if (iter != real_address_map_.begin()) { auto prev = iter; --prev; // update the corresponding range entry auto prev_range_iter = mappings_.find(prev->second); prev_range_iter->second.unmapped_space_after += range.size + range.unmapped_space_after; } real_address_map_.erase(iter); mappings_.erase(range_iter); return true; } void AddressMapper::insert(const MappedRange &range) { mappings_.emplace(range.real_addr, range); real_address_map_.emplace(range.mapped_addr, range.real_addr); } AddressMapper::MappingList::iterator AddressMapper::find(uint64_t addr) { auto iter = mappings_.upper_bound(addr); if (iter != mappings_.begin()) --iter; return iter; } AddressMapper::MappingList::const_iterator AddressMapper::find(uint64_t addr) const { auto iter = mappings_.upper_bound(addr); if (iter != mappings_.begin()) --iter; return iter; } } // namespace quipper <commit_msg>Fix bug in checking of a mapping exists<commit_after>// Copyright (c) 2013 The Chromium OS 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 "chromiumos-wide-profiling/address_mapper.h" #include "base/logging.h" #include "chromiumos-wide-profiling/limits.h" #include <vector> namespace quipper { AddressMapper::AddressMapper(const AddressMapper& source) { mappings_ = source.mappings_; real_address_map_ = source.real_address_map_; } bool AddressMapper::Map(const uint64_t real_addr, const uint64_t size, const bool remove_existing_mappings) { return MapWithID(real_addr, size, kUint64Max, 0, remove_existing_mappings); } bool AddressMapper::MapWithID(const uint64_t real_addr, const uint64_t size, const uint64_t id, const uint64_t offset_base, bool remove_existing_mappings) { MappedRange range; range.real_addr = real_addr; range.size = size; range.id = id; range.offset_base = offset_base; if (size == 0) { LOG(ERROR) << "Must allocate a nonzero-length address range."; return false; } // Check that this mapping does not overflow the address space. if (real_addr + size - 1 != kUint64Max && !(real_addr + size > real_addr)) { DumpToLog(); LOG(ERROR) << "Address mapping at " << std::hex << real_addr << " with size " << std::hex << size << " overflows."; return false; } // Check for collision with an existing mapping. This must be an overlap that // does not result in one range being completely covered by another MappingList::iterator iter; if (!mappings_.empty()) { std::vector<MappedRange> mappings_to_delete; bool old_range_found = false; MappedRange old_range; iter = find(real_addr); if (iter != mappings_.begin() && iter->second.real_addr > real_addr) --iter; for (; iter != mappings_.end() && iter->second.real_addr < (real_addr + size); ++iter) { if (!iter->second.Intersects(range)) continue; // Quit if existing ranges that collide aren't supposed to be removed. if (!remove_existing_mappings) return false; if (!old_range_found && iter->second.Covers(range) && iter->second.size > range.size) { old_range_found = true; old_range = iter->second; continue; } mappings_to_delete.push_back(iter->second); } for (const MappedRange &R : mappings_to_delete) CHECK(Unmap(R)); // Otherwise check for this range being covered by another range. If that // happens, split or reduce the existing range to make room. if (old_range_found) { CHECK(Unmap(old_range)); uint64_t gap_before = range.real_addr - old_range.real_addr; uint64_t gap_after = (old_range.real_addr + old_range.size) - (range.real_addr + range.size); if (gap_before) { CHECK(MapWithID(old_range.real_addr, gap_before, old_range.id, old_range.offset_base, false)); } CHECK(MapWithID(range.real_addr, range.size, id, offset_base, false)); if (gap_after) { CHECK(MapWithID(range.real_addr + range.size, gap_after, old_range.id, old_range.offset_base + gap_before + range.size, false)); } return true; } } // Now search for a location for the new range. It should be in the first // free block in quipper space. // If there is no existing mapping, add it to the beginning of quipper space. if (mappings_.empty()) { range.mapped_addr = 0; range.unmapped_space_after = kUint64Max - range.size; insert(range); return true; } CHECK(!real_address_map_.empty()); // If there is space before the first mapped range in quipper space, use it. uint64_t first_mapped = real_address_map_.begin()->first; if (first_mapped >= range.size) { range.mapped_addr = 0; range.unmapped_space_after = first_mapped - range.size; insert(range); return true; } // Otherwise, search through the existing mappings for a free block after one // of them. MappingList::iterator first = mappings_.end(); uint64_t last_mapped_start = real_address_map_.rbegin()->first; for (iter = mappings_.begin(); iter != mappings_.end(); ++iter) { if (iter->second.unmapped_space_after < size) continue; first = iter; if (iter->second.mapped_addr != last_mapped_start) break; } if (first != mappings_.end()) { range.mapped_addr = first->second.mapped_addr + first->second.size; range.unmapped_space_after = first->second.unmapped_space_after - range.size; first->second.unmapped_space_after = 0; insert(range); return true; } // If it still hasn't succeeded in mapping, it means there is no free space in // quipper space large enough for a mapping of this size. DumpToLog(); LOG(ERROR) << "Could not find space to map addr=" << std::hex << real_addr << " with size " << std::hex << size; return false; } void AddressMapper::DumpToLog() const { MappingList::const_iterator it; for (it = mappings_.begin(); it != mappings_.end(); ++it) { LOG(INFO) << " real_addr: " << std::hex << it->second.real_addr << " mapped: " << std::hex << it->second.mapped_addr << " id: " << std::hex << it->second.id << " size: " << std::hex << it->second.size; } } bool AddressMapper::GetMappedAddress(const uint64_t real_addr, uint64_t* mapped_addr) const { CHECK(mapped_addr); MappingList::const_iterator iter = find(real_addr); if (iter == mappings_.end() || !iter->second.ContainsAddress(real_addr)) return false; *mapped_addr = iter->second.mapped_addr + real_addr - iter->second.real_addr; return true; } bool AddressMapper::GetMappedIDAndOffset(const uint64_t real_addr, uint64_t* id, uint64_t* offset) const { CHECK(id); CHECK(offset); MappingList::const_iterator iter = find(real_addr); if (iter == mappings_.end() || !iter->second.ContainsAddress(real_addr)) return false; *id = iter->second.id; *offset = real_addr - iter->second.real_addr + iter->second.offset_base; return true; } uint64_t AddressMapper::GetMaxMappedLength() const { if (IsEmpty()) return 0; // The first mapped address uint64_t min = real_address_map_.begin()->first; // The real address start of the last mapped range uint64_t last_real_start = real_address_map_.rbegin()->second; auto iter = find(last_real_start); uint64_t last_addr = iter->second.mapped_addr; // The end of the last mapped range uint64_t max = last_addr + iter->second.size; return max - min; } bool AddressMapper::Unmap(const MappedRange &range) { // Find the range to be removed auto range_iter = mappings_.find(range.real_addr); if (!range_iter->second.Matches(range)) return false; // Find the range that preceeds this in mapped space. auto iter = real_address_map_.find(range_iter->second.mapped_addr); if (iter != real_address_map_.begin()) { auto prev = iter; --prev; // update the corresponding range entry auto prev_range_iter = mappings_.find(prev->second); prev_range_iter->second.unmapped_space_after += range.size + range.unmapped_space_after; } real_address_map_.erase(iter); mappings_.erase(range_iter); return true; } void AddressMapper::insert(const MappedRange &range) { mappings_.emplace(range.real_addr, range); real_address_map_.emplace(range.mapped_addr, range.real_addr); } AddressMapper::MappingList::iterator AddressMapper::find(uint64_t addr) { auto iter = mappings_.upper_bound(addr); if (iter != mappings_.begin()) --iter; return iter; } AddressMapper::MappingList::const_iterator AddressMapper::find(uint64_t addr) const { auto iter = mappings_.upper_bound(addr); if (iter != mappings_.begin()) --iter; return iter; } } // namespace quipper <|endoftext|>
<commit_before>// Halide tutorial lesson 12. // This lesson demonstrates how to use Halide to run code on a GPU. // This lesson can be built by invoking the command: // make tutorial_lesson_12_using_the_gpu // in a shell with the current directory at the top of the halide source tree. // Otherwise, see the platform-specific compiler invocations below. // On linux, you can compile and run it like so: // g++ lesson_12*.cpp -g -I ../include -L ../bin -lHalide `libpng-config --cflags --ldflags` -lpthread -ldl -o lesson_12 // LD_LIBRARY_PATH=../bin ./lesson_12 // On os x: // g++ lesson_12*.cpp -g -I ../include -L ../bin -lHalide `libpng-config --cflags --ldflags` -o lesson_12 // DYLD_LIBRARY_PATH=../bin ./lesson_12 #include <Halide.h> #include <stdio.h> using namespace Halide; // Include some support code for loading pngs. #include "image_io.h" // Include a clock to do performance testing. #include "clock.h" // Define some Vars to use. Var x, y, c, i; // We're going to want to schedule a pipeline in several ways, so we // define the pipeline in a class so that we can recreate it several // times with different schedules. class Pipeline { public: Func lut, padded, padded16, sharpen, curved; Image<uint8_t> input; Pipeline(Image<uint8_t> in) : input(in) { // For this lesson, we'll use a two-stage pipeline that sharpens // and then applies a look-up-table (LUT). // First we'll define the LUT. It will be a gamma curve. lut(i) = cast<uint8_t>(clamp(pow(i / 255.0f, 1.2f) * 255.0f, 0, 255)); // Augment the input with a boundary condition. padded(x, y, c) = input(clamp(x, 0, input.width()-1), clamp(y, 0, input.height()-1), c); // Cast it to 16-bit to do the math. padded16(x, y, c) = cast<uint16_t>(padded(x, y, c)); // Next we sharpen it with a five-tap filter. sharpen(x, y, c) = (padded16(x, y, c) * 2- (padded16(x - 1, y, c) + padded16(x, y - 1, c) + padded16(x + 1, y, c) + padded16(x, y + 1, c)) / 4); // Then apply the LUT. curved(x, y, c) = lut(sharpen(x, y, c)); } // Now we define methods that give our pipeline several different // schedules. void schedule_for_cpu() { // Compute the look-up-table ahead of time. lut.compute_root(); // Compute color channels innermost. Promise that there will // be three of them and unroll across them. curved.reorder(c, x, y) .bound(c, 0, 3) .unroll(c); // Look-up-tables don't vectorize well, so just parallelize // curved in slices of 16 scanlines. Var yo, yi; curved.split(y, yo, yi, 16) .parallel(yo); // Compute sharpen as needed per scanline of curved, reusing // previous values computed within the same strip of 16 // scanlines. sharpen.store_at(curved, yo) .compute_at(curved, yi); // Vectorize the sharpen. It's 16-bit so we'll vectorize it 8-wide. sharpen.vectorize(x, 8); // Compute the padded input at the same granularity as the // sharpen. We'll leave the cast to 16-bit inlined into // sharpen. padded.store_at(curved, yo) .compute_at(curved, yi); // Also vectorize the padding. It's 8-bit, so we'll vectorize // 16-wide. padded.vectorize(x, 16); // JIT-compile the pipeline for the CPU. curved.compile_jit(); } // Now a schedule that uses CUDA or OpenCL. void schedule_for_gpu() { // We make the decision about whether to use the GPU for each // Func independently. If you have one Func computed on the // CPU, and the next computed on the GPU, Halide will do the // copy-to-gpu under the hood. For this pipeline, there's no // reason to use the CPU for any of the stages. Halide will // copy the input image to the GPU the first time we run the // pipeline, and leave it there to reuse on subsequent runs. // As before, we'll compute the LUT once at the start of the // pipeline. lut.compute_root(); // Let's compute the look-up-table using the GPU in 16-wide // one-dimensional thread blocks. First we split the index // into blocks of size 16: Var block, thread; lut.split(i, block, thread, 16); // Then we tell cuda that our Vars 'block' and 'thread' // correspond to CUDA's notions of blocks and threads, or // OpenCL's notions of thread groups and threads. lut.gpu_blocks(block) .gpu_threads(thread); // This is a very common scheduling pattern on the GPU, so // there's a shorthand for it: // lut.gpu_tile(i, 16); // Func::gpu_tile method is similar to Func::tile, except that // it also specifies that the tile coordinates correspond to // GPU blocks, and the coordinates within each tile correspond // to GPU threads. // Compute color channels innermost. Promise that there will // be three of them and unroll across them. curved.reorder(c, x, y) .bound(c, 0, 3) .unroll(c); // Compute curved in 2D 8x8 tiles using the GPU. curved.gpu_tile(x, y, 8, 8); // This is equivalent to: // curved.tile(x, y, xo, yo, xi, yi, 8, 8) // .gpu_blocks(xo, yo) // .gpu_threads(xi, yi); // We'll leave sharpen as inlined into curved. // Compute the padded input as needed per GPU block, storing the // intermediate result in shared memory. Var::gpu_blocks, and // Var::gpu_threads exist to help you schedule producers within // GPU threads and blocks. padded.compute_at(curved, Var::gpu_blocks()); // Use the GPU threads for the x and y coordinates of the // padded input. padded.gpu_threads(x, y); // JIT-compile the pipeline for the GPU. CUDA or OpenCL are // not enabled by default. We have to construct a Target // object, enable one of them, and then pass that target // object to compile_jit. Otherwise your CPU will very slowly // pretend it's a GPU, and use one thread per output pixel. // Start with a target suitable for the machine you're running // this on. Target target = get_host_target(); // Then enable OpenCL or CUDA. // We'll enable OpenCL here, because it tends to give better // performance than CUDA, even with NVidia's drivers, because // NVidia's open source LLVM backend doesn't seem to do all // the same optimizations their proprietary compiler does. target.set_feature(Target::OpenCL); // Uncomment the next line and comment out the line above to // try CUDA instead. // target.set_feature(Target::CUDA); // If you want to see all of the OpenCL or CUDA API calls done // by the pipeline, you can also enable the Debug // flag. This is helpful for figuring out which stages are // slow, or when CPU -> GPU copies happen. It hurts // performance though, so we'll leave it commented out. // target.set_feature(Target::Debug); curved.compile_jit(target); } void test_performance() { // Test the performance of the scheduled Pipeline. // If we realize curved into a Halide::Image, that will // unfairly penalize GPU performance by including a GPU->CPU // copy in every run. Halide::Image objects always exist on // the CPU. // Halide::Buffer, however, represents a buffer that may // exist on either CPU or GPU or both. Buffer output(UInt(8), input.width(), input.height(), input.channels()); // Run the filter once to initialize any GPU runtime state. curved.realize(output); // Now take the best of 3 runs for timing. double best_time; for (int i = 0; i < 3; i++) { double t1 = current_time(); // Run the filter 100 times. for (int j = 0; j < 100; j++) { curved.realize(output); } // Force any GPU code to finish by copying the buffer back to the CPU. output.copy_to_host(); double t2 = current_time(); double elapsed = (t2 - t1)/100; if (i == 0 || elapsed < best_time) { best_time = elapsed; } } printf("%1.4f milliseconds\n", best_time); } void test_correctness(Image<uint8_t> reference_output) { Image<uint8_t> output = curved.realize(input.width(), input.height(), input.channels()); // Check against the reference output. for (int c = 0; c < input.channels(); c++) { for (int y = 0; y < input.height(); y++) { for (int x = 0; x < input.width(); x++) { if (output(x, y, c) != reference_output(x, y, c)) { printf("Mismatch between output (%d) and " "reference output (%d) at %d, %d, %d\n", output(x, y, c), reference_output(x, y, c), x, y, c); exit(0); } } } } } }; bool have_opencl(); int main(int argc, char **argv) { // Load an input image. Image<uint8_t> input = load<uint8_t>("images/rgb.png"); // Allocated an image that will store the correct output Image<uint8_t> reference_output(input.width(), input.height(), input.channels()); printf("Testing performance on CPU:\n"); Pipeline p1(input); p1.schedule_for_cpu(); p1.test_performance(); p1.curved.realize(reference_output); if (have_opencl()) { printf("Testing performance on GPU:\n"); Pipeline p2(input); p2.schedule_for_gpu(); p2.test_performance(); p2.test_correctness(reference_output); } else { printf("Not testing performance on GPU, because I can't find the opencl library\n"); } return 0; } // A helper function to check if OpenCL seems to exist on this machine. #ifdef _WIN32 #include <windows.h> #else #include <dlfcn.h> #endif bool have_opencl() { #ifdef _WIN32 return LoadLibrary("opengl.dll") != NULL; #elif __APPLE__ return dlopen("/System/Library/Frameworks/OpenCL.framework/Versions/Current/OpenCL", RTLD_LAZY) != NULL; #else return dlopen("libOpenCL.so", RTLD_LAZY) != NULL; #endif } <commit_msg>Fixed typo: opengl -> opencl<commit_after>// Halide tutorial lesson 12. // This lesson demonstrates how to use Halide to run code on a GPU. // This lesson can be built by invoking the command: // make tutorial_lesson_12_using_the_gpu // in a shell with the current directory at the top of the halide source tree. // Otherwise, see the platform-specific compiler invocations below. // On linux, you can compile and run it like so: // g++ lesson_12*.cpp -g -I ../include -L ../bin -lHalide `libpng-config --cflags --ldflags` -lpthread -ldl -o lesson_12 // LD_LIBRARY_PATH=../bin ./lesson_12 // On os x: // g++ lesson_12*.cpp -g -I ../include -L ../bin -lHalide `libpng-config --cflags --ldflags` -o lesson_12 // DYLD_LIBRARY_PATH=../bin ./lesson_12 #include <Halide.h> #include <stdio.h> using namespace Halide; // Include some support code for loading pngs. #include "image_io.h" // Include a clock to do performance testing. #include "clock.h" // Define some Vars to use. Var x, y, c, i; // We're going to want to schedule a pipeline in several ways, so we // define the pipeline in a class so that we can recreate it several // times with different schedules. class Pipeline { public: Func lut, padded, padded16, sharpen, curved; Image<uint8_t> input; Pipeline(Image<uint8_t> in) : input(in) { // For this lesson, we'll use a two-stage pipeline that sharpens // and then applies a look-up-table (LUT). // First we'll define the LUT. It will be a gamma curve. lut(i) = cast<uint8_t>(clamp(pow(i / 255.0f, 1.2f) * 255.0f, 0, 255)); // Augment the input with a boundary condition. padded(x, y, c) = input(clamp(x, 0, input.width()-1), clamp(y, 0, input.height()-1), c); // Cast it to 16-bit to do the math. padded16(x, y, c) = cast<uint16_t>(padded(x, y, c)); // Next we sharpen it with a five-tap filter. sharpen(x, y, c) = (padded16(x, y, c) * 2- (padded16(x - 1, y, c) + padded16(x, y - 1, c) + padded16(x + 1, y, c) + padded16(x, y + 1, c)) / 4); // Then apply the LUT. curved(x, y, c) = lut(sharpen(x, y, c)); } // Now we define methods that give our pipeline several different // schedules. void schedule_for_cpu() { // Compute the look-up-table ahead of time. lut.compute_root(); // Compute color channels innermost. Promise that there will // be three of them and unroll across them. curved.reorder(c, x, y) .bound(c, 0, 3) .unroll(c); // Look-up-tables don't vectorize well, so just parallelize // curved in slices of 16 scanlines. Var yo, yi; curved.split(y, yo, yi, 16) .parallel(yo); // Compute sharpen as needed per scanline of curved, reusing // previous values computed within the same strip of 16 // scanlines. sharpen.store_at(curved, yo) .compute_at(curved, yi); // Vectorize the sharpen. It's 16-bit so we'll vectorize it 8-wide. sharpen.vectorize(x, 8); // Compute the padded input at the same granularity as the // sharpen. We'll leave the cast to 16-bit inlined into // sharpen. padded.store_at(curved, yo) .compute_at(curved, yi); // Also vectorize the padding. It's 8-bit, so we'll vectorize // 16-wide. padded.vectorize(x, 16); // JIT-compile the pipeline for the CPU. curved.compile_jit(); } // Now a schedule that uses CUDA or OpenCL. void schedule_for_gpu() { // We make the decision about whether to use the GPU for each // Func independently. If you have one Func computed on the // CPU, and the next computed on the GPU, Halide will do the // copy-to-gpu under the hood. For this pipeline, there's no // reason to use the CPU for any of the stages. Halide will // copy the input image to the GPU the first time we run the // pipeline, and leave it there to reuse on subsequent runs. // As before, we'll compute the LUT once at the start of the // pipeline. lut.compute_root(); // Let's compute the look-up-table using the GPU in 16-wide // one-dimensional thread blocks. First we split the index // into blocks of size 16: Var block, thread; lut.split(i, block, thread, 16); // Then we tell cuda that our Vars 'block' and 'thread' // correspond to CUDA's notions of blocks and threads, or // OpenCL's notions of thread groups and threads. lut.gpu_blocks(block) .gpu_threads(thread); // This is a very common scheduling pattern on the GPU, so // there's a shorthand for it: // lut.gpu_tile(i, 16); // Func::gpu_tile method is similar to Func::tile, except that // it also specifies that the tile coordinates correspond to // GPU blocks, and the coordinates within each tile correspond // to GPU threads. // Compute color channels innermost. Promise that there will // be three of them and unroll across them. curved.reorder(c, x, y) .bound(c, 0, 3) .unroll(c); // Compute curved in 2D 8x8 tiles using the GPU. curved.gpu_tile(x, y, 8, 8); // This is equivalent to: // curved.tile(x, y, xo, yo, xi, yi, 8, 8) // .gpu_blocks(xo, yo) // .gpu_threads(xi, yi); // We'll leave sharpen as inlined into curved. // Compute the padded input as needed per GPU block, storing the // intermediate result in shared memory. Var::gpu_blocks, and // Var::gpu_threads exist to help you schedule producers within // GPU threads and blocks. padded.compute_at(curved, Var::gpu_blocks()); // Use the GPU threads for the x and y coordinates of the // padded input. padded.gpu_threads(x, y); // JIT-compile the pipeline for the GPU. CUDA or OpenCL are // not enabled by default. We have to construct a Target // object, enable one of them, and then pass that target // object to compile_jit. Otherwise your CPU will very slowly // pretend it's a GPU, and use one thread per output pixel. // Start with a target suitable for the machine you're running // this on. Target target = get_host_target(); // Then enable OpenCL or CUDA. // We'll enable OpenCL here, because it tends to give better // performance than CUDA, even with NVidia's drivers, because // NVidia's open source LLVM backend doesn't seem to do all // the same optimizations their proprietary compiler does. target.set_feature(Target::OpenCL); // Uncomment the next line and comment out the line above to // try CUDA instead. // target.set_feature(Target::CUDA); // If you want to see all of the OpenCL or CUDA API calls done // by the pipeline, you can also enable the Debug // flag. This is helpful for figuring out which stages are // slow, or when CPU -> GPU copies happen. It hurts // performance though, so we'll leave it commented out. // target.set_feature(Target::Debug); curved.compile_jit(target); } void test_performance() { // Test the performance of the scheduled Pipeline. // If we realize curved into a Halide::Image, that will // unfairly penalize GPU performance by including a GPU->CPU // copy in every run. Halide::Image objects always exist on // the CPU. // Halide::Buffer, however, represents a buffer that may // exist on either CPU or GPU or both. Buffer output(UInt(8), input.width(), input.height(), input.channels()); // Run the filter once to initialize any GPU runtime state. curved.realize(output); // Now take the best of 3 runs for timing. double best_time; for (int i = 0; i < 3; i++) { double t1 = current_time(); // Run the filter 100 times. for (int j = 0; j < 100; j++) { curved.realize(output); } // Force any GPU code to finish by copying the buffer back to the CPU. output.copy_to_host(); double t2 = current_time(); double elapsed = (t2 - t1)/100; if (i == 0 || elapsed < best_time) { best_time = elapsed; } } printf("%1.4f milliseconds\n", best_time); } void test_correctness(Image<uint8_t> reference_output) { Image<uint8_t> output = curved.realize(input.width(), input.height(), input.channels()); // Check against the reference output. for (int c = 0; c < input.channels(); c++) { for (int y = 0; y < input.height(); y++) { for (int x = 0; x < input.width(); x++) { if (output(x, y, c) != reference_output(x, y, c)) { printf("Mismatch between output (%d) and " "reference output (%d) at %d, %d, %d\n", output(x, y, c), reference_output(x, y, c), x, y, c); exit(0); } } } } } }; bool have_opencl(); int main(int argc, char **argv) { // Load an input image. Image<uint8_t> input = load<uint8_t>("images/rgb.png"); // Allocated an image that will store the correct output Image<uint8_t> reference_output(input.width(), input.height(), input.channels()); printf("Testing performance on CPU:\n"); Pipeline p1(input); p1.schedule_for_cpu(); p1.test_performance(); p1.curved.realize(reference_output); if (have_opencl()) { printf("Testing performance on GPU:\n"); Pipeline p2(input); p2.schedule_for_gpu(); p2.test_performance(); p2.test_correctness(reference_output); } else { printf("Not testing performance on GPU, because I can't find the opencl library\n"); } return 0; } // A helper function to check if OpenCL seems to exist on this machine. #ifdef _WIN32 #include <windows.h> #else #include <dlfcn.h> #endif bool have_opencl() { #ifdef _WIN32 return LoadLibrary("OpenCL.dll") != NULL; #elif __APPLE__ return dlopen("/System/Library/Frameworks/OpenCL.framework/Versions/Current/OpenCL", RTLD_LAZY) != NULL; #else return dlopen("libOpenCL.so", RTLD_LAZY) != NULL; #endif } <|endoftext|>
<commit_before>//===--- ExplicitMakePairCheck.cpp - clang-tidy -----------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ExplicitMakePairCheck.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/AST/ASTContext.h" using namespace clang::ast_matchers; namespace clang { namespace ast_matchers { AST_MATCHER(DeclRefExpr, hasExplicitTemplateArgs) { return Node.hasExplicitTemplateArgs(); } // FIXME: This should just be callee(ignoringImpCasts()) but it's not overloaded // for Expr. AST_MATCHER_P(CallExpr, calleeIgnoringParenImpCasts, internal::Matcher<Stmt>, InnerMatcher) { const Expr *ExprNode = Node.getCallee(); return (ExprNode != nullptr && InnerMatcher.matches(*ExprNode->IgnoreParenImpCasts(), Finder, Builder)); } } // namespace ast_matchers namespace tidy { namespace build { void ExplicitMakePairCheck::registerMatchers(ast_matchers::MatchFinder *Finder) { // Look for std::make_pair with explicit template args. Ignore calls in // templates. Finder->addMatcher( callExpr(unless(hasAncestor(decl(anyOf( recordDecl(ast_matchers::isTemplateInstantiation()), functionDecl(ast_matchers::isTemplateInstantiation()))))), calleeIgnoringParenImpCasts( declRefExpr(hasExplicitTemplateArgs(), to(functionDecl(hasName("::std::make_pair")))) .bind("declref"))).bind("call"), this); } void ExplicitMakePairCheck::check(const MatchFinder::MatchResult &Result) { const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call"); const auto *DeclRef = Result.Nodes.getNodeAs<DeclRefExpr>("declref"); // Sanity check: The use might have overriden ::std::make_pair. if (Call->getNumArgs() != 2) return; const Expr *Arg0 = Call->getArg(0)->IgnoreParenImpCasts(); const Expr *Arg1 = Call->getArg(1)->IgnoreParenImpCasts(); // If types don't match, we suggest replacing with std::pair and explicit // template arguments. Otherwise just remove the template arguments from // make_pair. if (Arg0->getType() != Call->getArg(0)->getType() || Arg1->getType() != Call->getArg(1)->getType()) { diag(Call->getLocStart(), "for C++11-compatibility, use pair directly") << FixItHint::CreateReplacement( SourceRange(DeclRef->getLocStart(), DeclRef->getLAngleLoc()), "std::pair<"); } else { diag(Call->getLocStart(), "for C++11-compatibility, omit template arguments from make_pair") << FixItHint::CreateRemoval( SourceRange(DeclRef->getLAngleLoc(), DeclRef->getRAngleLoc())); } } } // namespace build } // namespace tidy } // namespace clang <commit_msg>[clang-tidy] Simplify ast matcher.<commit_after>//===--- ExplicitMakePairCheck.cpp - clang-tidy -----------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ExplicitMakePairCheck.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/AST/ASTContext.h" using namespace clang::ast_matchers; namespace clang { namespace ast_matchers { AST_MATCHER(DeclRefExpr, hasExplicitTemplateArgs) { return Node.hasExplicitTemplateArgs(); } } // namespace ast_matchers namespace tidy { namespace build { void ExplicitMakePairCheck::registerMatchers(ast_matchers::MatchFinder *Finder) { // Look for std::make_pair with explicit template args. Ignore calls in // templates. Finder->addMatcher( callExpr(unless(hasAncestor(decl(anyOf( recordDecl(ast_matchers::isTemplateInstantiation()), functionDecl(ast_matchers::isTemplateInstantiation()))))), callee(expr(ignoringParenImpCasts( declRefExpr(hasExplicitTemplateArgs(), to(functionDecl(hasName("::std::make_pair")))) .bind("declref"))))).bind("call"), this); } void ExplicitMakePairCheck::check(const MatchFinder::MatchResult &Result) { const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call"); const auto *DeclRef = Result.Nodes.getNodeAs<DeclRefExpr>("declref"); // Sanity check: The use might have overriden ::std::make_pair. if (Call->getNumArgs() != 2) return; const Expr *Arg0 = Call->getArg(0)->IgnoreParenImpCasts(); const Expr *Arg1 = Call->getArg(1)->IgnoreParenImpCasts(); // If types don't match, we suggest replacing with std::pair and explicit // template arguments. Otherwise just remove the template arguments from // make_pair. if (Arg0->getType() != Call->getArg(0)->getType() || Arg1->getType() != Call->getArg(1)->getType()) { diag(Call->getLocStart(), "for C++11-compatibility, use pair directly") << FixItHint::CreateReplacement( SourceRange(DeclRef->getLocStart(), DeclRef->getLAngleLoc()), "std::pair<"); } else { diag(Call->getLocStart(), "for C++11-compatibility, omit template arguments from make_pair") << FixItHint::CreateRemoval( SourceRange(DeclRef->getLAngleLoc(), DeclRef->getRAngleLoc())); } } } // namespace build } // namespace tidy } // namespace clang <|endoftext|>
<commit_before>#include "memoryleak.h" #include "abstractmanager.h" #include <QSortFilterProxyModel> #include <QDebug> #include "feedmodel.h" #include "servicemodel.h" #include "feedmanager.h" #include "feedcache.h" #include "aggregatedmodel.h" #include "feedadapter.h" #include "memoryleak-defines.h" McaAbstractManager::McaAbstractManager(QObject *parent) : QObject(parent) { m_feedmgr = McaFeedManager::takeManager(); m_cache = new McaFeedCache(this); connect(m_cache, SIGNAL(frozenChanged(bool)), this, SIGNAL(frozenChanged(bool))); m_aggregator = new McaAggregatedModel(m_cache); m_cache->setSourceModel(m_aggregator); m_feedProxy = new QSortFilterProxyModel(this); m_feedProxy->setSourceModel(m_cache); m_feedProxy->setSortRole(McaFeedModel::RequiredTimestampRole); m_feedProxy->sort(0, Qt::DescendingOrder); m_feedProxy->setDynamicSortFilter(true); connect(m_feedmgr, SIGNAL(feedCreated(QObject*,McaFeedAdapter*,int)), this, SLOT(createFeedDone(QObject*,McaFeedAdapter*,int)), Qt::DirectConnection); connect(m_feedmgr, SIGNAL(createFeedError(QString,int)), this, SLOT(createFeedError(QString,int))); } McaAbstractManager::~McaAbstractManager() { m_requestIds.clear(); if(0 != m_cache) { delete m_cache; m_cache = 0; } McaFeedManager::releaseManager(); } bool McaAbstractManager::frozen() { return m_cache->frozen(); } QSortFilterProxyModel *McaAbstractManager::feedModel() { return m_feedProxy; } void McaAbstractManager::setFrozen(bool frozen) { m_cache->setFrozen(frozen); } void McaAbstractManager::rowsAboutToBeRemoved(const QModelIndex &index, int start, int end) { Q_UNUSED(index) for (int i=start; i<=end; i++) { QModelIndex qmi = serviceModelIndex(i); removeFeed(qmi); } } void McaAbstractManager::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) { for (int i=topLeft.row(); i<=bottomRight.row(); i++) { QModelIndex qmi = serviceModelIndex(i);//m_serviceProxy->index(i, 0); QAbstractListModel *model = qobject_cast<QAbstractListModel*>(serviceModelData(qmi, McaAggregatedModel::SourceModelRole).value<QObject*>()); QString name = serviceModelData(qmi, McaServiceModel::RequiredNameRole).toString(); QString id = m_feedmgr->serviceId(model, name); if (m_upidToFeedInfo.contains(id)) { // if the feed now has a configuration error, remove it if (serviceModelData(qmi, McaServiceModel::CommonConfigErrorRole).toBool() || !dataChangedCondition(qmi)) { removeFeed(qmi); } } else { // if the feed is now configured correctly, add it if (!serviceModelData(qmi, McaServiceModel::CommonConfigErrorRole).toBool() && dataChangedCondition(qmi)) { addFeed(qmi); } } } } void McaAbstractManager::addFeed(const QModelIndex &index) { QAbstractListModel *model = qobject_cast<QAbstractListModel*>(serviceModelData(index, McaAggregatedModel::SourceModelRole).value<QObject*>()); QString name = serviceModelData(index, McaServiceModel::RequiredNameRole).toString(); QString upid = m_feedmgr->serviceId(model, name); if (m_upidToFeedInfo.contains(upid)) { qWarning() << "warning: search manager: unexpected duplicate add feed request"; return; } m_requestIds[createFeed(model, name)] = index.row(); } void McaAbstractManager::removeFeed(const QModelIndex &index) { QAbstractListModel *model = qobject_cast<QAbstractListModel*>(serviceModelData(index, McaAggregatedModel::SourceModelRole).value<QObject*>()); QString name = serviceModelData(index, McaServiceModel::RequiredNameRole).toString(); QString upid = m_feedmgr->serviceId(model, name); FeedInfo *info = m_upidToFeedInfo.value(upid, NULL); if (info) { m_aggregator->removeSourceModel(info->feed); removeFeedCleanup(upid); m_upidToFeedInfo.remove(upid); info->feed->deleteLater(); delete info; } } void McaAbstractManager::removeAllFeeds() { QHashIterator<QString, FeedInfo *> iter(m_upidToFeedInfo); while( iter.hasNext() ) { iter.next(); FeedInfo *info = iter.value(); QString upid = iter.key(); if(info) { m_aggregator->removeSourceModel(info->feed); removeFeedCleanup(upid); info->feed->deleteLater(); delete info; } } m_upidToFeedInfo.clear(); } void McaAbstractManager::rowsInserted(const QModelIndex &index, int start, int end) { Q_UNUSED(index) for (int i=start; i<=end; i++) { QModelIndex qmi = serviceModelIndex(i); if (serviceModelData(qmi, McaServiceModel::CommonConfigErrorRole).toBool() || !dataChangedCondition(qmi)) { continue; } addFeed(qmi); } } void McaAbstractManager::createFeedDone(QObject *containerObj, McaFeedAdapter *feedAdapter, int uniqueRequestId) { if (m_requestIds.keys().contains(uniqueRequestId) && 0 != containerObj) { QModelIndex index = serviceModelIndex(m_requestIds[uniqueRequestId]); QString name = serviceModelData(index, McaServiceModel::RequiredNameRole).toString(); QAbstractListModel *model = qobject_cast<QAbstractListModel*>(serviceModelData(index, McaAggregatedModel::SourceModelRole).value<QObject*>()); QString upid = m_feedmgr->serviceId(model, name); m_requestIds.remove(uniqueRequestId); FeedInfo *info = new FeedInfo; info->upid = upid; info->feed = feedAdapter; m_upidToFeedInfo.insert(upid, info); createFeedFinalize(containerObj, feedAdapter, info); m_aggregator->addSourceModel(feedAdapter); } } void McaAbstractManager::createFeedError(QString serviceName, int uniqueRequestId) { if(m_requestIds.contains(uniqueRequestId)) { qDebug() << "CREATE Feed Error " << serviceName << " with request id " << uniqueRequestId; m_requestIds.remove(uniqueRequestId); //TODO: any aditional cleanup on feed creation error } } <commit_msg>Fix BMC #15984 meego-ux-content causes segfault when network cycled off/on<commit_after>#include "memoryleak.h" #include "abstractmanager.h" #include <QSortFilterProxyModel> #include <QDebug> #include "feedmodel.h" #include "servicemodel.h" #include "feedmanager.h" #include "feedcache.h" #include "aggregatedmodel.h" #include "feedadapter.h" #include "memoryleak-defines.h" McaAbstractManager::McaAbstractManager(QObject *parent) : QObject(parent) { m_feedmgr = McaFeedManager::takeManager(); m_cache = new McaFeedCache(this); connect(m_cache, SIGNAL(frozenChanged(bool)), this, SIGNAL(frozenChanged(bool))); m_aggregator = new McaAggregatedModel(m_cache); m_cache->setSourceModel(m_aggregator); m_feedProxy = new QSortFilterProxyModel(this); m_feedProxy->setSourceModel(m_cache); m_feedProxy->setSortRole(McaFeedModel::RequiredTimestampRole); m_feedProxy->sort(0, Qt::DescendingOrder); m_feedProxy->setDynamicSortFilter(true); connect(m_feedmgr, SIGNAL(feedCreated(QObject*,McaFeedAdapter*,int)), this, SLOT(createFeedDone(QObject*,McaFeedAdapter*,int)), Qt::DirectConnection); connect(m_feedmgr, SIGNAL(createFeedError(QString,int)), this, SLOT(createFeedError(QString,int))); } McaAbstractManager::~McaAbstractManager() { m_requestIds.clear(); if(0 != m_cache) { delete m_cache; m_cache = 0; } McaFeedManager::releaseManager(); } bool McaAbstractManager::frozen() { return m_cache->frozen(); } QSortFilterProxyModel *McaAbstractManager::feedModel() { return m_feedProxy; } void McaAbstractManager::setFrozen(bool frozen) { m_cache->setFrozen(frozen); } void McaAbstractManager::rowsAboutToBeRemoved(const QModelIndex &index, int start, int end) { Q_UNUSED(index) for (int i=start; i<=end; i++) { QModelIndex qmi = serviceModelIndex(i); removeFeed(qmi); } } void McaAbstractManager::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) { for (int i=topLeft.row(); i<=bottomRight.row(); i++) { QModelIndex qmi = serviceModelIndex(i);//m_serviceProxy->index(i, 0); QAbstractListModel *model = qobject_cast<QAbstractListModel*>(serviceModelData(qmi, McaAggregatedModel::SourceModelRole).value<QObject*>()); QString name = serviceModelData(qmi, McaServiceModel::RequiredNameRole).toString(); QString id = m_feedmgr->serviceId(model, name); if (m_upidToFeedInfo.contains(id)) { // if the feed now has a configuration error, remove it if (serviceModelData(qmi, McaServiceModel::CommonConfigErrorRole).toBool() || !dataChangedCondition(qmi)) { removeFeed(qmi); } } else { // if the feed is now configured correctly, add it if (!serviceModelData(qmi, McaServiceModel::CommonConfigErrorRole).toBool() && dataChangedCondition(qmi)) { addFeed(qmi); } } } } void McaAbstractManager::addFeed(const QModelIndex &index) { QAbstractListModel *model = qobject_cast<QAbstractListModel*>(serviceModelData(index, McaAggregatedModel::SourceModelRole).value<QObject*>()); QString name = serviceModelData(index, McaServiceModel::RequiredNameRole).toString(); QString upid = m_feedmgr->serviceId(model, name); if (m_upidToFeedInfo.contains(upid)) { qWarning() << "warning: search manager: unexpected duplicate add feed request"; return; } m_upidToFeedInfo.insert(upid, NULL); m_requestIds[createFeed(model, name)] = index.row(); } void McaAbstractManager::removeFeed(const QModelIndex &index) { QAbstractListModel *model = qobject_cast<QAbstractListModel*>(serviceModelData(index, McaAggregatedModel::SourceModelRole).value<QObject*>()); QString name = serviceModelData(index, McaServiceModel::RequiredNameRole).toString(); QString upid = m_feedmgr->serviceId(model, name); FeedInfo *info = m_upidToFeedInfo.value(upid, NULL); if (info) { m_aggregator->removeSourceModel(info->feed); removeFeedCleanup(upid); m_upidToFeedInfo.remove(upid); info->feed->deleteLater(); delete info; } } void McaAbstractManager::removeAllFeeds() { QHashIterator<QString, FeedInfo *> iter(m_upidToFeedInfo); while( iter.hasNext() ) { iter.next(); FeedInfo *info = iter.value(); QString upid = iter.key(); if(info) { m_aggregator->removeSourceModel(info->feed); removeFeedCleanup(upid); info->feed->deleteLater(); delete info; } } m_upidToFeedInfo.clear(); } void McaAbstractManager::rowsInserted(const QModelIndex &index, int start, int end) { Q_UNUSED(index) for (int i=start; i<=end; i++) { QModelIndex qmi = serviceModelIndex(i); if (serviceModelData(qmi, McaServiceModel::CommonConfigErrorRole).toBool() || !dataChangedCondition(qmi)) { continue; } addFeed(qmi); } } void McaAbstractManager::createFeedDone(QObject *containerObj, McaFeedAdapter *feedAdapter, int uniqueRequestId) { if (m_requestIds.keys().contains(uniqueRequestId) && 0 != containerObj) { QModelIndex index = serviceModelIndex(m_requestIds[uniqueRequestId]); QString name = serviceModelData(index, McaServiceModel::RequiredNameRole).toString(); QAbstractListModel *model = qobject_cast<QAbstractListModel*>(serviceModelData(index, McaAggregatedModel::SourceModelRole).value<QObject*>()); QString upid = m_feedmgr->serviceId(model, name); m_requestIds.remove(uniqueRequestId); FeedInfo *info = new FeedInfo; info->upid = upid; info->feed = feedAdapter; m_upidToFeedInfo.insert(upid, info); createFeedFinalize(containerObj, feedAdapter, info); m_aggregator->addSourceModel(feedAdapter); } } void McaAbstractManager::createFeedError(QString serviceName, int uniqueRequestId) { if(m_requestIds.contains(uniqueRequestId)) { qDebug() << "CREATE Feed Error " << serviceName << " with request id " << uniqueRequestId; m_requestIds.remove(uniqueRequestId); //TODO: any aditional cleanup on feed creation error } } <|endoftext|>
<commit_before> #include "Math/Chebyshev.h" #include "Math/IFunction.h" #include "Math/Functor.h" #include "Math/SpecFunc.h" //#include "MathCore/GSLIntegrator.h" #include <iostream> #include <cmath> typedef double ( * FP ) ( double, void * ); // function is a step function double myfunc ( double x, void * /* params */) { //double * p = reinterpret_cast<double *>( params); if (x < 0.5) return 0.25; else return 0.75; } double gamma_func( double x, void *) { return ROOT::Math::tgamma(x); } // gamma function class GammaFunction : public ROOT::Math::IGenFunction { public: ROOT::Math::IGenFunction * Clone() const { return new GammaFunction(); } private: double DoEval ( double x) const { return ROOT::Math::tgamma(x); } }; int printCheb( const ROOT::Math::Chebyshev & c, double x0, double x1, FP func = 0 ) { double dx = (x1-x0)/10; for ( double x = x0; x < x1; x+= dx ) { double y = c(x); double ey = c.EvalErr(x).second; double y10 = c(x,10); double ey10 = c.EvalErr(x,10).second; double fVal = 0; if (func) fVal = func(x,0); std::cout << " x = " << x << " true Val = " << fVal << " y = " << y << " +/- " << ey << " y@10 = " << y10 << " +/- " << ey10 << std::endl; } return 0; } int main() { // test with cos(x) + 1.0 std::cout << "Test Cheb approx to step function :" << std::endl; ROOT::Math::Chebyshev c(myfunc, 0, 0., 1.0, 40); printCheb(c, 0, 1, myfunc); std::cout << "Test integral of step function :" << std::endl; ROOT::Math::Chebyshev * cInteg = c.Integral(); printCheb(*cInteg, 0., 1); delete cInteg; std::cout << "Test Cheb approx to Gamma function :" << std::endl; GammaFunction gf; ROOT::Math::Chebyshev c2(gf, 1.0, 2.0, 40); printCheb(c2, 1.0, 2.0, gamma_func); std::cout << "Test derivative of gammma :" << std::endl; ROOT::Math::Chebyshev * cDeriv = c2.Deriv(); printCheb(*cDeriv, 1.0, 2.0); delete cDeriv; return 0; } <commit_msg>update test for new class name<commit_after> #include "Math/ChebyshevApprox.h" #include "Math/IFunction.h" #include "Math/Functor.h" #include "Math/SpecFunc.h" //#include "MathCore/GSLIntegrator.h" #include <iostream> #include <cmath> typedef double ( * FP ) ( double, void * ); // function is a step function double myfunc ( double x, void * /* params */) { //double * p = reinterpret_cast<double *>( params); if (x < 0.5) return 0.25; else return 0.75; } double gamma_func( double x, void *) { return ROOT::Math::tgamma(x); } // gamma function class GammaFunction : public ROOT::Math::IGenFunction { public: ROOT::Math::IGenFunction * Clone() const { return new GammaFunction(); } private: double DoEval ( double x) const { return ROOT::Math::tgamma(x); } }; int printCheb( const ROOT::Math::ChebyshevApprox & c, double x0, double x1, FP func = 0 ) { double dx = (x1-x0)/10; for ( double x = x0; x < x1; x+= dx ) { double y = c(x); double ey = c.EvalErr(x).second; double y10 = c(x,10); double ey10 = c.EvalErr(x,10).second; double fVal = 0; if (func) fVal = func(x,0); std::cout << " x = " << x << " true Val = " << fVal << " y = " << y << " +/- " << ey << " y@10 = " << y10 << " +/- " << ey10 << std::endl; } return 0; } int main() { // test with cos(x) + 1.0 std::cout << "Test Cheb approx to step function :" << std::endl; ROOT::Math::ChebyshevApprox c(myfunc, 0, 0., 1.0, 40); printCheb(c, 0, 1, myfunc); std::cout << "Test integral of step function :" << std::endl; ROOT::Math::ChebyshevApprox * cInteg = c.Integral(); printCheb(*cInteg, 0., 1); delete cInteg; std::cout << "Test Cheb approx to Gamma function :" << std::endl; GammaFunction gf; ROOT::Math::ChebyshevApprox c2(gf, 1.0, 2.0, 40); printCheb(c2, 1.0, 2.0, gamma_func); std::cout << "Test derivative of gammma :" << std::endl; ROOT::Math::ChebyshevApprox * cDeriv = c2.Deriv(); printCheb(*cDeriv, 1.0, 2.0); delete cDeriv; return 0; } <|endoftext|>
<commit_before>#include <map> #include "mem_vector.h" #include "bulk_operate.h" #include "data_frame.h" #include "local_vec_store.h" using namespace fm; using namespace detail; template<class T> class count_impl: public gr_apply_operate<local_vec_store> { public: virtual void run(const void *key, const local_vec_store &vec, local_vec_store &output) const { size_t num_eles = vec.get_length(); assert(num_eles > 0); const T *arr = (const T *) vec.get_raw_arr(); T val = *arr; if (num_eles > 1) for (size_t i = 1; i < num_eles; i++) assert(val == arr[i]); assert(output.get_type() == get_scalar_type<size_t>()); output.set<size_t>(0, num_eles); } virtual const scalar_type &get_key_type() const { return get_scalar_type<T>(); } virtual const scalar_type &get_output_type() const { return get_scalar_type<size_t>(); } virtual size_t get_num_out_eles() const { return 1; } }; void test_groupby() { printf("test groupby\n"); smp_vec_store::ptr store = smp_vec_store::create(1000000, get_scalar_type<int>()); for (size_t i = 0; i < store->get_length(); i++) store->set<int>(i, random() % 1000); mem_vector::ptr vec = mem_vector::create(store); count_impl<int> count; data_frame::ptr res = vec->groupby(count, true); printf("size: %ld\n", res->get_num_entries()); std::map<int, size_t> ele_counts; for (size_t i = 0; i < vec->get_length(); i++) { int val = vec->get<int>(i); auto it = ele_counts.find(val); if (it == ele_counts.end()) ele_counts.insert(std::pair<int, size_t>(val, 1)); else it->second++; } smp_vec_store::ptr vals = smp_vec_store::cast(res->get_vec("val")); smp_vec_store::ptr aggs = smp_vec_store::cast(res->get_vec("agg")); for (size_t i = 0; i < vals->get_length(); i++) { int val = vals->get<int>(i); size_t count = aggs->get<size_t>(i); auto it = ele_counts.find(val); assert(it != ele_counts.end()); assert(it->second == count); } } void test_append() { printf("test append\n"); smp_vec_store::ptr res = smp_vec_store::create(16, get_scalar_type<int>()); size_t tot_len = res->get_length(); std::vector<vec_store::const_ptr> vecs(16); for (size_t i = 0; i < vecs.size(); i++) { vecs[i] = smp_vec_store::create(32, get_scalar_type<int>()); tot_len += vecs[i]->get_length(); } res->append(vecs.begin(), vecs.end()); assert(tot_len == res->get_length()); } void test_sort() { printf("test sort\n"); smp_vec_store::ptr vec = smp_vec_store::create(1000000, get_scalar_type<int>()); for (size_t i = 0; i < vec->get_length(); i++) vec->set<int>(i, random() % 1000); smp_vec_store::ptr clone = smp_vec_store::cast(vec->deep_copy()); mem_vector::ptr vec1 = mem_vector::create(clone); mem_vector::ptr vec2 = mem_vector::create(vec); assert(vec1->equals(*vec2)); smp_vec_store::ptr idxs = smp_vec_store::cast(vec->sort_with_index()); smp_vec_store::ptr sorted = clone->smp_vec_store::get(*idxs); vec1 = mem_vector::create(sorted); vec2 = mem_vector::create(vec); assert(vec1->equals(*vec2)); } void test_max() { printf("test max\n"); smp_vec_store::ptr vec = smp_vec_store::create(1000000, get_scalar_type<int>()); int max = 0; for (size_t i = 0; i < vec->get_length(); i++) { int v = random() % 1000; vec->set<int>(i, v); max = std::max(max, v); } mem_vector::ptr vec1 = mem_vector::create(vec); assert(vec1->max<int>() == max); } void test_resize() { printf("test resize\n"); mem_vector::ptr vec = mem_vector::cast(create_vector<int>(1, 10000, 2)); smp_vec_store::ptr copy = smp_vec_store::cast(vec->get_data().deep_copy()); copy->resize(100); size_t min_len = std::min(copy->get_length(), vec->get_length()); for (size_t i = 0; i < min_len; i++) assert(vec->get<int>(i) == copy->get<int>(i)); copy->resize(200); // The semantics don't guarantee that this works, but it works with // the current implementation min_len = std::min(copy->get_length(), vec->get_length()); for (size_t i = 0; i < min_len; i++) assert(vec->get<int>(i) == copy->get<int>(i)); copy->resize(20000); for (size_t i = 0; i < min_len; i++) assert(vec->get<int>(i) == copy->get<int>(i)); } void test_get_sub() { printf("test get sub\n"); mem_vector::ptr vec = mem_vector::cast(create_vector<int>(1, 10000, 2)); smp_vec_store::ptr idxs = smp_vec_store::create(1000, get_scalar_type<off_t>()); for (size_t i = 0; i < idxs->get_length(); i++) idxs->set<off_t>(i, random() % idxs->get_length()); smp_vec_store::ptr res = smp_vec_store::cast(vec->get_raw_store())->get(*idxs); for (size_t i = 0; i < res->get_length(); i++) assert(res->get<int>(i) == vec->get<int>(idxs->get<off_t>(i))); } int main() { test_sort(); test_append(); test_groupby(); test_max(); test_resize(); test_get_sub(); } <commit_msg>[Matrix]: test "copy_from"<commit_after>#include <map> #include "mem_vector.h" #include "bulk_operate.h" #include "data_frame.h" #include "local_vec_store.h" #include "dense_matrix.h" using namespace fm; using namespace detail; template<class T> class count_impl: public gr_apply_operate<local_vec_store> { public: virtual void run(const void *key, const local_vec_store &vec, local_vec_store &output) const { size_t num_eles = vec.get_length(); assert(num_eles > 0); const T *arr = (const T *) vec.get_raw_arr(); T val = *arr; if (num_eles > 1) for (size_t i = 1; i < num_eles; i++) assert(val == arr[i]); assert(output.get_type() == get_scalar_type<size_t>()); output.set<size_t>(0, num_eles); } virtual const scalar_type &get_key_type() const { return get_scalar_type<T>(); } virtual const scalar_type &get_output_type() const { return get_scalar_type<size_t>(); } virtual size_t get_num_out_eles() const { return 1; } }; void test_groupby() { printf("test groupby\n"); smp_vec_store::ptr store = smp_vec_store::create(1000000, get_scalar_type<int>()); for (size_t i = 0; i < store->get_length(); i++) store->set<int>(i, random() % 1000); mem_vector::ptr vec = mem_vector::create(store); count_impl<int> count; data_frame::ptr res = vec->groupby(count, true); printf("size: %ld\n", res->get_num_entries()); std::map<int, size_t> ele_counts; for (size_t i = 0; i < vec->get_length(); i++) { int val = vec->get<int>(i); auto it = ele_counts.find(val); if (it == ele_counts.end()) ele_counts.insert(std::pair<int, size_t>(val, 1)); else it->second++; } smp_vec_store::ptr vals = smp_vec_store::cast(res->get_vec("val")); smp_vec_store::ptr aggs = smp_vec_store::cast(res->get_vec("agg")); for (size_t i = 0; i < vals->get_length(); i++) { int val = vals->get<int>(i); size_t count = aggs->get<size_t>(i); auto it = ele_counts.find(val); assert(it != ele_counts.end()); assert(it->second == count); } } void test_append() { printf("test append\n"); smp_vec_store::ptr res = smp_vec_store::create(16, get_scalar_type<int>()); size_t tot_len = res->get_length(); std::vector<vec_store::const_ptr> vecs(16); for (size_t i = 0; i < vecs.size(); i++) { vecs[i] = smp_vec_store::create(32, get_scalar_type<int>()); tot_len += vecs[i]->get_length(); } res->append(vecs.begin(), vecs.end()); assert(tot_len == res->get_length()); } void test_sort() { printf("test sort\n"); smp_vec_store::ptr vec = smp_vec_store::create(1000000, get_scalar_type<int>()); for (size_t i = 0; i < vec->get_length(); i++) vec->set<int>(i, random() % 1000); smp_vec_store::ptr clone = smp_vec_store::cast(vec->deep_copy()); mem_vector::ptr vec1 = mem_vector::create(clone); mem_vector::ptr vec2 = mem_vector::create(vec); assert(vec1->equals(*vec2)); smp_vec_store::ptr idxs = smp_vec_store::cast(vec->sort_with_index()); smp_vec_store::ptr sorted = clone->smp_vec_store::get(*idxs); vec1 = mem_vector::create(sorted); vec2 = mem_vector::create(vec); assert(vec1->equals(*vec2)); } void test_max() { printf("test max\n"); smp_vec_store::ptr vec = smp_vec_store::create(1000000, get_scalar_type<int>()); int max = 0; for (size_t i = 0; i < vec->get_length(); i++) { int v = random() % 1000; vec->set<int>(i, v); max = std::max(max, v); } mem_vector::ptr vec1 = mem_vector::create(vec); assert(vec1->max<int>() == max); } void test_resize() { printf("test resize\n"); mem_vector::ptr vec = mem_vector::cast(create_vector<int>(1, 10000, 2)); smp_vec_store::ptr copy = smp_vec_store::cast(vec->get_data().deep_copy()); copy->resize(100); size_t min_len = std::min(copy->get_length(), vec->get_length()); for (size_t i = 0; i < min_len; i++) assert(vec->get<int>(i) == copy->get<int>(i)); copy->resize(200); // The semantics don't guarantee that this works, but it works with // the current implementation min_len = std::min(copy->get_length(), vec->get_length()); for (size_t i = 0; i < min_len; i++) assert(vec->get<int>(i) == copy->get<int>(i)); copy->resize(20000); for (size_t i = 0; i < min_len; i++) assert(vec->get<int>(i) == copy->get<int>(i)); } void test_get_sub() { printf("test get sub\n"); mem_vector::ptr vec = mem_vector::cast(create_vector<int>(1, 10000, 2)); smp_vec_store::ptr idxs = smp_vec_store::create(1000, get_scalar_type<off_t>()); for (size_t i = 0; i < idxs->get_length(); i++) idxs->set<off_t>(i, random() % idxs->get_length()); smp_vec_store::ptr res = smp_vec_store::cast(vec->get_raw_store())->get(*idxs); for (size_t i = 0; i < res->get_length(); i++) assert(res->get<int>(i) == vec->get<int>(idxs->get<off_t>(i))); } void test_copy_from() { printf("test copy vector\n"); smp_vec_store::ptr vec = smp_vec_store::create(1000000, get_scalar_type<int>()); std::vector<int> stl_vec(vec->get_length()); for (size_t i = 0; i < stl_vec.size(); i++) stl_vec[i] = i; vec->copy_from((const char *) stl_vec.data(), vec->get_length() * vec->get_entry_size()); for (size_t i = 0; i < stl_vec.size(); i++) assert(stl_vec[i] == vec->get<int>(i)); } int main() { test_sort(); test_append(); test_groupby(); test_max(); test_resize(); test_get_sub(); test_copy_from(); } <|endoftext|>
<commit_before>/* Q Light Controller Plus positiontool.cpp Copyright (c) Jano Svitok 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.txt 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 <QDebug> #include <QPoint> #include "positiontool.h" #include "vcxypadarea.h" #include "qlcmacros.h" /***************************************************************************** * Initialization *****************************************************************************/ PositionTool::PositionTool(const QPointF & initial, QRectF degreesRange, QWidget* parent) : QDialog(parent) { setupUi(this); m_area = new VCXYPadArea(this); setPosition(initial); m_area->setMode(Doc::Operate); // to activate the area m_area->setWindowTitle(""); m_area->setDegreesRange(degreesRange); m_gridLayout->addWidget(m_area, 0, 0); connect(m_area, SIGNAL(positionChanged(const QPointF &)), this, SLOT(slotPositionChanged(const QPointF &))); } PositionTool::~PositionTool() { } /***************************************************************************** * Current XY position *****************************************************************************/ QPointF PositionTool::position() const { if (m_area == NULL) return QPointF(127, 127); return m_area->position(); } void PositionTool::setPosition(const QPointF & position) { m_area->setPosition(position); } void PositionTool::slotPositionChanged(const QPointF & position) { emit currentPositionChanged(position); } <commit_msg>Position tool: set focus to the area, so that keyboard control works without clicking<commit_after>/* Q Light Controller Plus positiontool.cpp Copyright (c) Jano Svitok 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.txt 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 <QDebug> #include <QPoint> #include "positiontool.h" #include "vcxypadarea.h" #include "qlcmacros.h" /***************************************************************************** * Initialization *****************************************************************************/ PositionTool::PositionTool(const QPointF & initial, QRectF degreesRange, QWidget* parent) : QDialog(parent) { setupUi(this); m_area = new VCXYPadArea(this); setPosition(initial); m_area->setMode(Doc::Operate); // to activate the area m_area->setWindowTitle(""); m_area->setDegreesRange(degreesRange); m_area->setFocus(); m_gridLayout->addWidget(m_area, 0, 0); connect(m_area, SIGNAL(positionChanged(const QPointF &)), this, SLOT(slotPositionChanged(const QPointF &))); } PositionTool::~PositionTool() { } /***************************************************************************** * Current XY position *****************************************************************************/ QPointF PositionTool::position() const { if (m_area == NULL) return QPointF(127, 127); return m_area->position(); } void PositionTool::setPosition(const QPointF & position) { m_area->setPosition(position); } void PositionTool::slotPositionChanged(const QPointF & position) { emit currentPositionChanged(position); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: AccessibleSlideSorterView.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 05:00:29 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_ACCESSIBILITY_ACCESSIBLE_SLIDE_SORTER_VIEW_HXX #define SD_ACCESSIBILITY_ACCESSIBLE_SLIDE_SORTER_VIEW_HXX #include "MutexOwner.hxx" #ifndef _CPPUHELPER_COMPBASE6_HXX_ #include <cppuhelper/compbase6.hxx> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_ #include <com/sun/star/accessibility/XAccessible.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECONTEXT_HPP_ #include <com/sun/star/accessibility/XAccessibleContext.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECOMPONENT_HPP_ #include <com/sun/star/accessibility/XAccessibleComponent.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESELECTION_HPP_ #include <com/sun/star/accessibility/XAccessibleSelection.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEVENTBROADCASTER_HPP_ #include <com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XFOCUSLISTENER_HPP_ #include <com/sun/star/awt/XFocusListener.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEVENTLISTENER_HPP_ #include <com/sun/star/document/XEventListener.hpp> #endif #include <memory> class Window; namespace sd { namespace slidesorter { namespace controller { class SlideSorterController; } } } namespace accessibility { class AccessibleSlideSorterObject; typedef ::cppu::WeakComponentImplHelper6< ::com::sun::star::accessibility::XAccessible, ::com::sun::star::accessibility::XAccessibleEventBroadcaster, ::com::sun::star::accessibility::XAccessibleContext, ::com::sun::star::accessibility::XAccessibleComponent, ::com::sun::star::accessibility::XAccessibleSelection, ::com::sun::star::lang::XServiceInfo > AccessibleSlideSorterViewBase; /** This class makes the SlideSorterViewShell accessible. It uses objects of the AccessibleSlideSorterObject class to the make the page objects accessible. */ class AccessibleSlideSorterView : public ::sd::MutexOwner, public AccessibleSlideSorterViewBase { public: AccessibleSlideSorterView( ::sd::slidesorter::controller::SlideSorterController& rController, const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> & rxParent, ::Window* pParentWindow); virtual ~AccessibleSlideSorterView (void); /** This method acts like a dispose call. It sends a disposing to all of its listeners. It may be called twice. */ void Destroyed (void); void FireAccessibleEvent ( short nEventId, const ::com::sun::star::uno::Any& rOldValue, const ::com::sun::star::uno::Any& rNewValue); virtual void SAL_CALL disposing (void); //===== XAccessible ======================================================= virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext (void) throw (::com::sun::star::uno::RuntimeException); //===== XAccessibleEventBroadcaster ======================================= virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleEventListener >& rxListener) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleEventListener >& rxListener ) throw (::com::sun::star::uno::RuntimeException); //===== XAccessibleContext ============================================== /// Return the number of currently visible children. virtual sal_Int32 SAL_CALL getAccessibleChildCount (void) throw (::com::sun::star::uno::RuntimeException); /// Return the specified child or throw exception. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL getAccessibleChild (sal_Int32 nIndex) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); /// Return a reference to the parent. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL getAccessibleParent (void) throw (::com::sun::star::uno::RuntimeException); /// Return this objects index among the parents children. virtual sal_Int32 SAL_CALL getAccessibleIndexInParent (void) throw (::com::sun::star::uno::RuntimeException); /// Return this object's role. virtual sal_Int16 SAL_CALL getAccessibleRole (void) throw (::com::sun::star::uno::RuntimeException); /// Return this object's description. virtual ::rtl::OUString SAL_CALL getAccessibleDescription (void) throw (::com::sun::star::uno::RuntimeException); /// Return the object's current name. virtual ::rtl::OUString SAL_CALL getAccessibleName (void) throw (::com::sun::star::uno::RuntimeException); /// Return NULL to indicate that an empty relation set. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleRelationSet> SAL_CALL getAccessibleRelationSet (void) throw (::com::sun::star::uno::RuntimeException); /// Return the set of current states. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL getAccessibleStateSet (void) throw (::com::sun::star::uno::RuntimeException); /** Return the parents locale or throw exception if this object has no parent yet/anymore. */ virtual ::com::sun::star::lang::Locale SAL_CALL getLocale (void) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::accessibility::IllegalAccessibleComponentStateException); //===== XAccessibleComponent ================================================ /** The default implementation uses the result of <member>getBounds</member> to determine whether the given point lies inside this object. */ virtual sal_Bool SAL_CALL containsPoint ( const ::com::sun::star::awt::Point& aPoint) throw (::com::sun::star::uno::RuntimeException); /** The default implementation returns an empty reference. */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint ( const ::com::sun::star::awt::Point& aPoint) throw (::com::sun::star::uno::RuntimeException); /** The default implementation returns an empty rectangle. */ virtual ::com::sun::star::awt::Rectangle SAL_CALL getBounds (void) throw (::com::sun::star::uno::RuntimeException); /** The default implementation uses the result of <member>getBounds</member> to determine the location. */ virtual ::com::sun::star::awt::Point SAL_CALL getLocation (void) throw (::com::sun::star::uno::RuntimeException); /** The default implementation returns an empty position, i.e. the * result of the default constructor of <type>com::sun::star::awt::Point</type>. */ virtual ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen (void) throw (::com::sun::star::uno::RuntimeException); /** The default implementation uses the result of <member>getBounds</member> to determine the size. */ virtual ::com::sun::star::awt::Size SAL_CALL getSize (void) throw (::com::sun::star::uno::RuntimeException); /** The default implementation does nothing. */ virtual void SAL_CALL grabFocus (void) throw (::com::sun::star::uno::RuntimeException); /** Returns black as the default foreground color. */ virtual sal_Int32 SAL_CALL getForeground (void) throw (::com::sun::star::uno::RuntimeException); /** Returns white as the default background color. */ virtual sal_Int32 SAL_CALL getBackground (void) throw (::com::sun::star::uno::RuntimeException); //===== XAccessibleSelection ============================================== virtual void SAL_CALL selectAccessibleChild (sal_Int32 nChildIndex) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isAccessibleChildSelected( sal_Int32 nChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL clearAccessibleSelection( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL selectAllAccessibleChildren( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getSelectedAccessibleChildCount( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL deselectAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); //===== XServiceInfo ==================================================== /** Returns an identifier for the implementation of this object. */ virtual ::rtl::OUString SAL_CALL getImplementationName (void) throw (::com::sun::star::uno::RuntimeException); /** Return whether the specified service is supported by this class. */ virtual sal_Bool SAL_CALL supportsService (const ::rtl::OUString& sServiceName) throw (::com::sun::star::uno::RuntimeException); /** Returns a list of all supported services. */ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames (void) throw (::com::sun::star::uno::RuntimeException); private: class Implementation; ::std::auto_ptr<Implementation> mpImpl; ::sd::slidesorter::controller::SlideSorterController& mrSlideSorterController; ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> mxParent; sal_uInt32 mnClientId; ::Window* mpContentWindow; /** Check whether or not the object has been disposed (or is in the state of beeing disposed). If that is the case then DisposedException is thrown to inform the (indirect) caller of the foul deed. */ void ThrowIfDisposed (void) throw (::com::sun::star::lang::DisposedException); /** Check whether or not the object has been disposed (or is in the state of beeing disposed). @return sal_True, if the object is disposed or in the course of being disposed. Otherwise, sal_False is returned. */ sal_Bool IsDisposed (void); }; } // end of namespace ::accessibility #endif <commit_msg>INTEGRATION: CWS impress78 (1.3.84); FILE MERGED 2006/01/11 10:21:53 af 1.3.84.1: #i57918# New GetAccessibleChildImplementation() method.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: AccessibleSlideSorterView.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-01-19 12:51:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_ACCESSIBILITY_ACCESSIBLE_SLIDE_SORTER_VIEW_HXX #define SD_ACCESSIBILITY_ACCESSIBLE_SLIDE_SORTER_VIEW_HXX #include "MutexOwner.hxx" #ifndef _CPPUHELPER_COMPBASE6_HXX_ #include <cppuhelper/compbase6.hxx> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_ #include <com/sun/star/accessibility/XAccessible.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECONTEXT_HPP_ #include <com/sun/star/accessibility/XAccessibleContext.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECOMPONENT_HPP_ #include <com/sun/star/accessibility/XAccessibleComponent.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESELECTION_HPP_ #include <com/sun/star/accessibility/XAccessibleSelection.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEVENTBROADCASTER_HPP_ #include <com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XFOCUSLISTENER_HPP_ #include <com/sun/star/awt/XFocusListener.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEVENTLISTENER_HPP_ #include <com/sun/star/document/XEventListener.hpp> #endif #include <memory> class Window; namespace sd { namespace slidesorter { namespace controller { class SlideSorterController; } } } namespace accessibility { class AccessibleSlideSorterObject; typedef ::cppu::WeakComponentImplHelper6< ::com::sun::star::accessibility::XAccessible, ::com::sun::star::accessibility::XAccessibleEventBroadcaster, ::com::sun::star::accessibility::XAccessibleContext, ::com::sun::star::accessibility::XAccessibleComponent, ::com::sun::star::accessibility::XAccessibleSelection, ::com::sun::star::lang::XServiceInfo > AccessibleSlideSorterViewBase; /** This class makes the SlideSorterViewShell accessible. It uses objects of the AccessibleSlideSorterObject class to the make the page objects accessible. */ class AccessibleSlideSorterView : public ::sd::MutexOwner, public AccessibleSlideSorterViewBase { public: AccessibleSlideSorterView( ::sd::slidesorter::controller::SlideSorterController& rController, const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> & rxParent, ::Window* pParentWindow); virtual ~AccessibleSlideSorterView (void); /** This method acts like a dispose call. It sends a disposing to all of its listeners. It may be called twice. */ void Destroyed (void); void FireAccessibleEvent ( short nEventId, const ::com::sun::star::uno::Any& rOldValue, const ::com::sun::star::uno::Any& rNewValue); virtual void SAL_CALL disposing (void); /** Return the implementation object of the specified child. @param nIndex Index of the child for which to return the implementation object. */ AccessibleSlideSorterObject* GetAccessibleChildImplementation (sal_Int32 nIndex); //===== XAccessible ======================================================= virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext (void) throw (::com::sun::star::uno::RuntimeException); //===== XAccessibleEventBroadcaster ======================================= virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleEventListener >& rxListener) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleEventListener >& rxListener ) throw (::com::sun::star::uno::RuntimeException); //===== XAccessibleContext ============================================== /// Return the number of currently visible children. virtual sal_Int32 SAL_CALL getAccessibleChildCount (void) throw (::com::sun::star::uno::RuntimeException); /// Return the specified child or throw exception. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL getAccessibleChild (sal_Int32 nIndex) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); /// Return a reference to the parent. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL getAccessibleParent (void) throw (::com::sun::star::uno::RuntimeException); /// Return this objects index among the parents children. virtual sal_Int32 SAL_CALL getAccessibleIndexInParent (void) throw (::com::sun::star::uno::RuntimeException); /// Return this object's role. virtual sal_Int16 SAL_CALL getAccessibleRole (void) throw (::com::sun::star::uno::RuntimeException); /// Return this object's description. virtual ::rtl::OUString SAL_CALL getAccessibleDescription (void) throw (::com::sun::star::uno::RuntimeException); /// Return the object's current name. virtual ::rtl::OUString SAL_CALL getAccessibleName (void) throw (::com::sun::star::uno::RuntimeException); /// Return NULL to indicate that an empty relation set. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleRelationSet> SAL_CALL getAccessibleRelationSet (void) throw (::com::sun::star::uno::RuntimeException); /// Return the set of current states. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL getAccessibleStateSet (void) throw (::com::sun::star::uno::RuntimeException); /** Return the parents locale or throw exception if this object has no parent yet/anymore. */ virtual ::com::sun::star::lang::Locale SAL_CALL getLocale (void) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::accessibility::IllegalAccessibleComponentStateException); //===== XAccessibleComponent ================================================ /** The default implementation uses the result of <member>getBounds</member> to determine whether the given point lies inside this object. */ virtual sal_Bool SAL_CALL containsPoint ( const ::com::sun::star::awt::Point& aPoint) throw (::com::sun::star::uno::RuntimeException); /** The default implementation returns an empty reference. */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint ( const ::com::sun::star::awt::Point& aPoint) throw (::com::sun::star::uno::RuntimeException); /** The default implementation returns an empty rectangle. */ virtual ::com::sun::star::awt::Rectangle SAL_CALL getBounds (void) throw (::com::sun::star::uno::RuntimeException); /** The default implementation uses the result of <member>getBounds</member> to determine the location. */ virtual ::com::sun::star::awt::Point SAL_CALL getLocation (void) throw (::com::sun::star::uno::RuntimeException); /** The default implementation returns an empty position, i.e. the * result of the default constructor of <type>com::sun::star::awt::Point</type>. */ virtual ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen (void) throw (::com::sun::star::uno::RuntimeException); /** The default implementation uses the result of <member>getBounds</member> to determine the size. */ virtual ::com::sun::star::awt::Size SAL_CALL getSize (void) throw (::com::sun::star::uno::RuntimeException); /** The default implementation does nothing. */ virtual void SAL_CALL grabFocus (void) throw (::com::sun::star::uno::RuntimeException); /** Returns black as the default foreground color. */ virtual sal_Int32 SAL_CALL getForeground (void) throw (::com::sun::star::uno::RuntimeException); /** Returns white as the default background color. */ virtual sal_Int32 SAL_CALL getBackground (void) throw (::com::sun::star::uno::RuntimeException); //===== XAccessibleSelection ============================================== virtual void SAL_CALL selectAccessibleChild (sal_Int32 nChildIndex) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isAccessibleChildSelected( sal_Int32 nChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL clearAccessibleSelection( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL selectAllAccessibleChildren( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getSelectedAccessibleChildCount( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL deselectAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); //===== XServiceInfo ==================================================== /** Returns an identifier for the implementation of this object. */ virtual ::rtl::OUString SAL_CALL getImplementationName (void) throw (::com::sun::star::uno::RuntimeException); /** Return whether the specified service is supported by this class. */ virtual sal_Bool SAL_CALL supportsService (const ::rtl::OUString& sServiceName) throw (::com::sun::star::uno::RuntimeException); /** Returns a list of all supported services. */ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames (void) throw (::com::sun::star::uno::RuntimeException); private: class Implementation; ::std::auto_ptr<Implementation> mpImpl; ::sd::slidesorter::controller::SlideSorterController& mrSlideSorterController; ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> mxParent; sal_uInt32 mnClientId; ::Window* mpContentWindow; /** Check whether or not the object has been disposed (or is in the state of beeing disposed). If that is the case then DisposedException is thrown to inform the (indirect) caller of the foul deed. */ void ThrowIfDisposed (void) throw (::com::sun::star::lang::DisposedException); /** Check whether or not the object has been disposed (or is in the state of beeing disposed). @return sal_True, if the object is disposed or in the course of being disposed. Otherwise, sal_False is returned. */ sal_Bool IsDisposed (void); }; } // end of namespace ::accessibility #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PresentationViewShellBase.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 05:12:37 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_PRESENTATION_VIEW_SHELL_BASE_HXX #define SD_PRESENTATION_VIEW_SHELL_BASE_HXX #include "ViewShellBase.hxx" namespace sd { /** This class exists to be able to register another factory that creates the view shell for the presentation. */ class PresentationViewShellBase : public ViewShellBase { public: TYPEINFO(); SFX_DECL_VIEWFACTORY(PresentationViewShellBase); /** This constructor is used by the view factory of the SFX macros. */ PresentationViewShellBase (SfxViewFrame *pFrame, SfxViewShell* pOldShell); virtual ~PresentationViewShellBase (void); /** We delete the ViewTabBar that is not needed for the presentation. */ virtual void LateInit (void); }; } // end of namespace sd #endif <commit_msg>INTEGRATION: CWS viewswitch (1.4.72); FILE MERGED 2006/02/02 09:52:22 af 1.4.72.1: #i61191# Removed LateInit(). Added CreateViewTabBar().<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PresentationViewShellBase.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-03-21 17:24:43 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_PRESENTATION_VIEW_SHELL_BASE_HXX #define SD_PRESENTATION_VIEW_SHELL_BASE_HXX #include "ViewShellBase.hxx" namespace sd { /** This class exists to be able to register another factory that creates the view shell for the presentation. */ class PresentationViewShellBase : public ViewShellBase { public: TYPEINFO(); SFX_DECL_VIEWFACTORY(PresentationViewShellBase); /** This constructor is used by the view factory of the SFX macros. */ PresentationViewShellBase (SfxViewFrame *pFrame, SfxViewShell* pOldShell); virtual ~PresentationViewShellBase (void); protected: /** The ViewTabBar is not supported so this factory method always returns <NULL/>. */ virtual ViewTabBar* CreateViewTabBar (void); }; } // end of namespace sd #endif <|endoftext|>
<commit_before>void Config() { // // Set Random Number seed TDatime dt; UInt_t curtime=dt.Get(); UInt_t procid=gSystem->GetPid(); UInt_t seed=curtime-procid; gRandom->SetSeed(seed); cerr<<"Seed for random number generation= "<<seed<<endl; new AliGeant3("C++ Interface to Geant3"); //======================================================================= // Create the output file TFile *rootfile = new TFile("galice.root","recreate"); rootfile->SetCompressionLevel(2); TGeant3 *geant3 = (TGeant3*)gMC; // // Set External decayer AliDecayer* decayer = new AliDecayerPythia(); decayer->SetForceDecay(kAll); decayer->Init(); gMC->SetExternalDecayer(decayer); // // //======================================================================= // ******* GEANT STEERING parameters FOR ALICE SIMULATION ******* geant3->SetTRIG(1); //Number of events to be processed geant3->SetSWIT(4,10); geant3->SetDEBU(0,0,1); //geant3->SetSWIT(2,2); geant3->SetDCAY(1); geant3->SetPAIR(1); geant3->SetCOMP(1); geant3->SetPHOT(1); geant3->SetPFIS(0); geant3->SetDRAY(0); geant3->SetANNI(1); geant3->SetBREM(1); geant3->SetMUNU(1); geant3->SetCKOV(1); geant3->SetHADR(1); //Select pure GEANH (HADR 1) or GEANH/NUCRIN (HADR 3) geant3->SetLOSS(2); geant3->SetMULS(1); geant3->SetRAYL(1); geant3->SetAUTO(1); //Select automatic STMIN etc... calc. (AUTO 1) or manual (AUTO 0) geant3->SetABAN(0); //Restore 3.16 behaviour for abandoned tracks geant3->SetOPTI(2); //Select optimisation level for GEANT geometry searches (0,1,2) geant3->SetERAN(5.e-7); Float_t cut = 1.e-3; // 1MeV cut by default Float_t tofmax = 1.e10; // GAM ELEC NHAD CHAD MUON EBREM MUHAB EDEL MUDEL MUPA TOFMAX geant3->SetCUTS(cut,cut, cut, cut, cut, cut, cut, cut, cut, cut, tofmax); // //======================================================================= // ************* STEERING parameters FOR ALICE SIMULATION ************** // --- Specify event type to be tracked through the ALICE setup // --- All positions are in cm, angles in degrees, and P and E in GeV // AliGenPythia *gener = new AliGenPythia(ntracks); AliGenPythia *gener = new AliGenPythia(-1); gener->SetMomentumRange(0,999); gener->SetPhiRange(-180.,180.); gener->SetThetaRange(0,180); gener->SetYRange(-999,999); //gener->SetPtRange(0,100); gener->SetOrigin(0,0,0); // vertex position //gener->SetVertexSmear(kPerEvent); gener->SetSigma(0,0,5.3); // Sigma in (X,Y,Z) (cm) on IP position gener->SetTrackingFlag(0); // gener->SetForceDecay(kHadronicD); // // The following settings select the Pythia parameters tuned to agree // with charm NLO calculation for Pb-Pb @ 5.5 TeV with MNR code. // gener->SetProcess(kPyCharmPbMNR); gener->SetStrucFunc(kCTEQ_4L); gener->SetPtHard(2.1,-1.0); gener->SetEnergyCMS(5500.); gener->SetNuclei(208,208); // Pb-Pb collisions gener->Init(); // // Activate this line if you want the vertex smearing to happen // track by track // //gener->SetVertexSmear(perTrack); // Field (L3 0.4 T) AliMagFCM* field = new AliMagFCM( "Map2","$(ALICE_ROOT)/data/field01.dat", 2, 1., 10.); field->SetSolenoidField(4.); gAlice->SetField(field); Int_t iABSO=0; Int_t iCASTOR=0; Int_t iDIPO=0; Int_t iFMD=0; Int_t iFRAME=0; Int_t iHALL=0; Int_t iITS=0; Int_t iMAG=0; Int_t iMUON=0; Int_t iPHOS=0; Int_t iPIPE=0; Int_t iPMD=0; Int_t iRICH=0; Int_t iSHIL=0; Int_t iSTART=0; Int_t iTOF=0; Int_t iTPC=0; Int_t iTRD=0; Int_t iZDC=0; //=================== Alice BODY parameters ============================= AliBODY *BODY = new AliBODY("BODY","Alice envelop"); if(iMAG) { //=================== MAG parameters ============================ // --- Start with Magnet since detector layouts may be depending --- // --- on the selected Magnet dimensions --- AliMAG *MAG = new AliMAG("MAG","Magnet"); } if(iABSO) { //=================== ABSO parameters ============================ AliABSO *ABSO = new AliABSOv0("ABSO","Muon Absorber"); } if(iDIPO) { //=================== DIPO parameters ============================ AliDIPO *DIPO = new AliDIPOv2("DIPO","Dipole version 2"); } if(iHALL) { //=================== HALL parameters ============================ AliHALL *HALL = new AliHALL("HALL","Alice Hall"); } if(iFRAME) { //=================== FRAME parameters ============================ AliFRAME *FRAME = new AliFRAMEv2("FRAME","Space Frame"); } if(iSHIL) { //=================== SHIL parameters ============================ AliSHIL *SHIL = new AliSHILv0("SHIL","Shielding"); } if(iPIPE) { //=================== PIPE parameters ============================ AliPIPE *PIPE = new AliPIPEv0("PIPE","Beam Pipe"); } if(iITS) { //=================== ITS parameters ============================ // // As the innermost detector in ALICE, the Inner Tracking System "impacts" on // almost all other detectors. This involves the fact that the ITS geometry // still has several options to be followed in parallel in order to determine // the best set-up which minimizes the induced background. All the geometries // available to date are described in the following. Read carefully the comments // and use the default version (the only one uncommented) unless you are making // comparisons and you know what you are doing. In this case just uncomment the // ITS geometry you want to use and run Aliroot. // // Detailed geometries: // // //AliITS *ITS = new AliITSv5symm("ITS","Updated ITS TDR detailed version with symmetric services"); // //AliITS *ITS = new AliITSv5asymm("ITS","Updates ITS TDR detailed version with asymmetric services"); // AliITSvPPRasymm *ITS = new AliITSvPPRasymm("ITS","New ITS PPR detailed version with asymmetric services"); ITS->SetMinorVersion(2); // don't touch this parameter if you're not an ITS developer ITS->SetReadDet(kFALSE); // don't touch this parameter if you're not an ITS developer ITS->SetWriteDet("$ALICE_ROOT/ITS/ITSgeometry_vPPRasymm2.det"); // don't touch this parameter if you're not an ITS developer ITS->SetThicknessDet1(200.); // detector thickness on layer 1 must be in the range [150,300] ITS->SetThicknessDet2(200.); // detector thickness on layer 2 must be in the range [150,300] ITS->SetThicknessChip1(200.); // chip thickness on layer 1 must be in the range [100,300] ITS->SetThicknessChip2(200.); // chip thickness on layer 2 must be in the range [100,300] ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out ITS->SetCoolingFluid(1); // 1 --> water ; 0 --> freon // //AliITSvPPRsymm *ITS = new AliITSvPPRsymm("ITS","New ITS PPR detailed version with symmetric services"); //ITS->SetMinorVersion(2); // don't touch this parameter if you're not an ITS developer //ITS->SetReadDet(kFALSE); // don't touch this parameter if you're not an ITS developer //ITS->SetWriteDet("$ALICE_ROOT/ITS/ITSgeometry_vPPRsymm2.det"); // don't touch this parameter if you're not an ITS developer //ITS->SetThicknessDet1(300.); // detector thickness on layer 1 must be in the range [150,300] //ITS->SetThicknessDet2(300.); // detector thickness on layer 2 must be in the range [150,300] //ITS->SetThicknessChip1(300.); // chip thickness on layer 1 must be in the range [100,300] //ITS->SetThicknessChip2(300.); // chip thickness on layer 2 must be in the range [100,300] //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetCoolingFluid(1); // 1 --> water ; 0 --> freon // // // Coarse geometries (warning: no hits are produced with these coarse geometries and they unuseful // for reconstruction !): // // //AliITSvPPRcoarseasymm *ITS = new AliITSvPPRcoarseasymm("ITS","New ITS PPR coarse version with asymmetric services"); //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetSupportMaterial(0); // 0 --> Copper ; 1 --> Aluminum ; 2 --> Carbon // //AliITS *ITS = new AliITSvPPRcoarsesymm("ITS","New ITS PPR coarse version with symmetric services"); //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetSupportMaterial(0); // 0 --> Copper ; 1 --> Aluminum ; 2 --> Carbon // // // // Geant3 <-> EUCLID conversion // ============================ // // SetEUCLID is a flag to output (=1) or not to output (=0) both geometry and // media to two ASCII files (called by default ITSgeometry.euc and // ITSgeometry.tme) in a format understandable to the CAD system EUCLID. // The default (=0) means that you dont want to use this facility. // ITS->SetEUCLID(0); } if(iTPC) { //============================ TPC parameters ================================ // --- This allows the user to specify sectors for the SLOW (TPC geometry 2) // --- Simulator. SecAL (SecAU) <0 means that ALL lower (upper) // --- sectors are specified, any value other than that requires at least one // --- sector (lower or upper)to be specified! // --- Reminder: sectors 1-24 are lower sectors (1-12 -> z>0, 13-24 -> z<0) // --- sectors 25-72 are the upper ones (25-48 -> z>0, 49-72 -> z<0) // --- SecLows - number of lower sectors specified (up to 6) // --- SecUps - number of upper sectors specified (up to 12) // --- Sens - sensitive strips for the Slow Simulator !!! // --- This does NOT work if all S or L-sectors are specified, i.e. // --- if SecAL or SecAU < 0 // // //----------------------------------------------------------------------------- // gROOT->LoadMacro("SetTPCParam.C"); // AliTPCParam *param = SetTPCParam(); AliTPC *TPC = new AliTPCv2("TPC","Default"); // All sectors included TPC->SetSecAL(-1); TPC->SetSecAU(-1); } if(iTOF) { //=================== TOF parameters ============================ AliTOF *TOF = new AliTOFv2("TOF","normal TOF"); } if(iRICH) { //=================== RICH parameters =========================== AliRICH *RICH = new AliRICHv1("RICH","normal RICH"); } if(iZDC) { //=================== ZDC parameters ============================ AliZDC *ZDC = new AliZDCv1("ZDC","normal ZDC"); } if(iCASTOR) { //=================== CASTOR parameters ============================ AliCASTOR *CASTOR = new AliCASTORv1("CASTOR","normal CASTOR"); } if(iTRD) { //=================== TRD parameters ============================ AliTRD *TRD = new AliTRDv1("TRD","TRD slow simulator"); // Select the gas mixture (0: 97% Xe + 3% isobutane, 1: 90% Xe + 10% CO2) TRD->SetGasMix(1); // With hole in front of PHOS TRD->SetPHOShole(); // With hole in front of RICH TRD->SetRICHhole(); // Switch on TR AliTRDsim *TRDsim = TRD->CreateTR(); } if(iFMD) { //=================== FMD parameters ============================ AliFMD *FMD = new AliFMDv0("FMD","normal FMD"); } if(iMUON) { //=================== MUON parameters =========================== AliMUON *MUON = new AliMUONv1("MUON","default"); } //=================== PHOS parameters =========================== if(iPHOS) { AliPHOS *PHOS = new AliPHOSv1("PHOS","GPS2"); } if(iPMD) { //=================== PMD parameters ============================ AliPMD *PMD = new AliPMDv1("PMD","normal PMD"); PMD->SetPAR(1., 1., 0.8, 0.02); PMD->SetIN(6., 18., -580., 27., 27.); PMD->SetGEO(0.0, 0.2, 4.); PMD->SetPadSize(0.8, 1.0, 1.0, 1.5); } if(iSTART) { //=================== START parameters ============================ AliSTART *START = new AliSTARTv1("START","START Detector"); } } <commit_msg>Underscore removed. (Nicola Carrer)<commit_after>void Config() { // // Set Random Number seed TDatime dt; UInt_t curtime=dt.Get(); UInt_t procid=gSystem->GetPid(); UInt_t seed=curtime-procid; gRandom->SetSeed(seed); cerr<<"Seed for random number generation= "<<seed<<endl; new AliGeant3("C++ Interface to Geant3"); //======================================================================= // Create the output file TFile *rootfile = new TFile("galice.root","recreate"); rootfile->SetCompressionLevel(2); TGeant3 *geant3 = (TGeant3*)gMC; // // Set External decayer AliDecayer* decayer = new AliDecayerPythia(); decayer->SetForceDecay(kAll); decayer->Init(); gMC->SetExternalDecayer(decayer); // // //======================================================================= // ******* GEANT STEERING parameters FOR ALICE SIMULATION ******* geant3->SetTRIG(1); //Number of events to be processed geant3->SetSWIT(4,10); geant3->SetDEBU(0,0,1); //geant3->SetSWIT(2,2); geant3->SetDCAY(1); geant3->SetPAIR(1); geant3->SetCOMP(1); geant3->SetPHOT(1); geant3->SetPFIS(0); geant3->SetDRAY(0); geant3->SetANNI(1); geant3->SetBREM(1); geant3->SetMUNU(1); geant3->SetCKOV(1); geant3->SetHADR(1); //Select pure GEANH (HADR 1) or GEANH/NUCRIN (HADR 3) geant3->SetLOSS(2); geant3->SetMULS(1); geant3->SetRAYL(1); geant3->SetAUTO(1); //Select automatic STMIN etc... calc. (AUTO 1) or manual (AUTO 0) geant3->SetABAN(0); //Restore 3.16 behaviour for abandoned tracks geant3->SetOPTI(2); //Select optimisation level for GEANT geometry searches (0,1,2) geant3->SetERAN(5.e-7); Float_t cut = 1.e-3; // 1MeV cut by default Float_t tofmax = 1.e10; // GAM ELEC NHAD CHAD MUON EBREM MUHAB EDEL MUDEL MUPA TOFMAX geant3->SetCUTS(cut,cut, cut, cut, cut, cut, cut, cut, cut, cut, tofmax); // //======================================================================= // ************* STEERING parameters FOR ALICE SIMULATION ************** // --- Specify event type to be tracked through the ALICE setup // --- All positions are in cm, angles in degrees, and P and E in GeV // AliGenPythia *gener = new AliGenPythia(ntracks); AliGenPythia *gener = new AliGenPythia(-1); gener->SetMomentumRange(0,999); gener->SetPhiRange(-180.,180.); gener->SetThetaRange(0,180); gener->SetYRange(-999,999); //gener->SetPtRange(0,100); gener->SetOrigin(0,0,0); // vertex position //gener->SetVertexSmear(kPerEvent); gener->SetSigma(0,0,5.3); // Sigma in (X,Y,Z) (cm) on IP position gener->SetTrackingFlag(0); // gener->SetForceDecay(kHadronicD); // // The following settings select the Pythia parameters tuned to agree // with charm NLO calculation for Pb-Pb @ 5.5 TeV with MNR code. // gener->SetProcess(kPyCharmPbMNR); gener->SetStrucFunc(kCTEQ4L); gener->SetPtHard(2.1,-1.0); gener->SetEnergyCMS(5500.); gener->SetNuclei(208,208); // Pb-Pb collisions gener->Init(); // // Activate this line if you want the vertex smearing to happen // track by track // //gener->SetVertexSmear(perTrack); // Field (L3 0.4 T) AliMagFCM* field = new AliMagFCM( "Map2","$(ALICE_ROOT)/data/field01.dat", 2, 1., 10.); field->SetSolenoidField(4.); gAlice->SetField(field); Int_t iABSO=0; Int_t iCASTOR=0; Int_t iDIPO=0; Int_t iFMD=0; Int_t iFRAME=0; Int_t iHALL=0; Int_t iITS=0; Int_t iMAG=0; Int_t iMUON=0; Int_t iPHOS=0; Int_t iPIPE=0; Int_t iPMD=0; Int_t iRICH=0; Int_t iSHIL=0; Int_t iSTART=0; Int_t iTOF=0; Int_t iTPC=0; Int_t iTRD=0; Int_t iZDC=0; //=================== Alice BODY parameters ============================= AliBODY *BODY = new AliBODY("BODY","Alice envelop"); if(iMAG) { //=================== MAG parameters ============================ // --- Start with Magnet since detector layouts may be depending --- // --- on the selected Magnet dimensions --- AliMAG *MAG = new AliMAG("MAG","Magnet"); } if(iABSO) { //=================== ABSO parameters ============================ AliABSO *ABSO = new AliABSOv0("ABSO","Muon Absorber"); } if(iDIPO) { //=================== DIPO parameters ============================ AliDIPO *DIPO = new AliDIPOv2("DIPO","Dipole version 2"); } if(iHALL) { //=================== HALL parameters ============================ AliHALL *HALL = new AliHALL("HALL","Alice Hall"); } if(iFRAME) { //=================== FRAME parameters ============================ AliFRAME *FRAME = new AliFRAMEv2("FRAME","Space Frame"); } if(iSHIL) { //=================== SHIL parameters ============================ AliSHIL *SHIL = new AliSHILv0("SHIL","Shielding"); } if(iPIPE) { //=================== PIPE parameters ============================ AliPIPE *PIPE = new AliPIPEv0("PIPE","Beam Pipe"); } if(iITS) { //=================== ITS parameters ============================ // // As the innermost detector in ALICE, the Inner Tracking System "impacts" on // almost all other detectors. This involves the fact that the ITS geometry // still has several options to be followed in parallel in order to determine // the best set-up which minimizes the induced background. All the geometries // available to date are described in the following. Read carefully the comments // and use the default version (the only one uncommented) unless you are making // comparisons and you know what you are doing. In this case just uncomment the // ITS geometry you want to use and run Aliroot. // // Detailed geometries: // // //AliITS *ITS = new AliITSv5symm("ITS","Updated ITS TDR detailed version with symmetric services"); // //AliITS *ITS = new AliITSv5asymm("ITS","Updates ITS TDR detailed version with asymmetric services"); // AliITSvPPRasymm *ITS = new AliITSvPPRasymm("ITS","New ITS PPR detailed version with asymmetric services"); ITS->SetMinorVersion(2); // don't touch this parameter if you're not an ITS developer ITS->SetReadDet(kFALSE); // don't touch this parameter if you're not an ITS developer ITS->SetWriteDet("$ALICE_ROOT/ITS/ITSgeometry_vPPRasymm2.det"); // don't touch this parameter if you're not an ITS developer ITS->SetThicknessDet1(200.); // detector thickness on layer 1 must be in the range [150,300] ITS->SetThicknessDet2(200.); // detector thickness on layer 2 must be in the range [150,300] ITS->SetThicknessChip1(200.); // chip thickness on layer 1 must be in the range [100,300] ITS->SetThicknessChip2(200.); // chip thickness on layer 2 must be in the range [100,300] ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out ITS->SetCoolingFluid(1); // 1 --> water ; 0 --> freon // //AliITSvPPRsymm *ITS = new AliITSvPPRsymm("ITS","New ITS PPR detailed version with symmetric services"); //ITS->SetMinorVersion(2); // don't touch this parameter if you're not an ITS developer //ITS->SetReadDet(kFALSE); // don't touch this parameter if you're not an ITS developer //ITS->SetWriteDet("$ALICE_ROOT/ITS/ITSgeometry_vPPRsymm2.det"); // don't touch this parameter if you're not an ITS developer //ITS->SetThicknessDet1(300.); // detector thickness on layer 1 must be in the range [150,300] //ITS->SetThicknessDet2(300.); // detector thickness on layer 2 must be in the range [150,300] //ITS->SetThicknessChip1(300.); // chip thickness on layer 1 must be in the range [100,300] //ITS->SetThicknessChip2(300.); // chip thickness on layer 2 must be in the range [100,300] //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetCoolingFluid(1); // 1 --> water ; 0 --> freon // // // Coarse geometries (warning: no hits are produced with these coarse geometries and they unuseful // for reconstruction !): // // //AliITSvPPRcoarseasymm *ITS = new AliITSvPPRcoarseasymm("ITS","New ITS PPR coarse version with asymmetric services"); //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetSupportMaterial(0); // 0 --> Copper ; 1 --> Aluminum ; 2 --> Carbon // //AliITS *ITS = new AliITSvPPRcoarsesymm("ITS","New ITS PPR coarse version with symmetric services"); //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetSupportMaterial(0); // 0 --> Copper ; 1 --> Aluminum ; 2 --> Carbon // // // // Geant3 <-> EUCLID conversion // ============================ // // SetEUCLID is a flag to output (=1) or not to output (=0) both geometry and // media to two ASCII files (called by default ITSgeometry.euc and // ITSgeometry.tme) in a format understandable to the CAD system EUCLID. // The default (=0) means that you dont want to use this facility. // ITS->SetEUCLID(0); } if(iTPC) { //============================ TPC parameters ================================ // --- This allows the user to specify sectors for the SLOW (TPC geometry 2) // --- Simulator. SecAL (SecAU) <0 means that ALL lower (upper) // --- sectors are specified, any value other than that requires at least one // --- sector (lower or upper)to be specified! // --- Reminder: sectors 1-24 are lower sectors (1-12 -> z>0, 13-24 -> z<0) // --- sectors 25-72 are the upper ones (25-48 -> z>0, 49-72 -> z<0) // --- SecLows - number of lower sectors specified (up to 6) // --- SecUps - number of upper sectors specified (up to 12) // --- Sens - sensitive strips for the Slow Simulator !!! // --- This does NOT work if all S or L-sectors are specified, i.e. // --- if SecAL or SecAU < 0 // // //----------------------------------------------------------------------------- // gROOT->LoadMacro("SetTPCParam.C"); // AliTPCParam *param = SetTPCParam(); AliTPC *TPC = new AliTPCv2("TPC","Default"); // All sectors included TPC->SetSecAL(-1); TPC->SetSecAU(-1); } if(iTOF) { //=================== TOF parameters ============================ AliTOF *TOF = new AliTOFv2("TOF","normal TOF"); } if(iRICH) { //=================== RICH parameters =========================== AliRICH *RICH = new AliRICHv1("RICH","normal RICH"); } if(iZDC) { //=================== ZDC parameters ============================ AliZDC *ZDC = new AliZDCv1("ZDC","normal ZDC"); } if(iCASTOR) { //=================== CASTOR parameters ============================ AliCASTOR *CASTOR = new AliCASTORv1("CASTOR","normal CASTOR"); } if(iTRD) { //=================== TRD parameters ============================ AliTRD *TRD = new AliTRDv1("TRD","TRD slow simulator"); // Select the gas mixture (0: 97% Xe + 3% isobutane, 1: 90% Xe + 10% CO2) TRD->SetGasMix(1); // With hole in front of PHOS TRD->SetPHOShole(); // With hole in front of RICH TRD->SetRICHhole(); // Switch on TR AliTRDsim *TRDsim = TRD->CreateTR(); } if(iFMD) { //=================== FMD parameters ============================ AliFMD *FMD = new AliFMDv0("FMD","normal FMD"); } if(iMUON) { //=================== MUON parameters =========================== AliMUON *MUON = new AliMUONv1("MUON","default"); } //=================== PHOS parameters =========================== if(iPHOS) { AliPHOS *PHOS = new AliPHOSv1("PHOS","GPS2"); } if(iPMD) { //=================== PMD parameters ============================ AliPMD *PMD = new AliPMDv1("PMD","normal PMD"); PMD->SetPAR(1., 1., 0.8, 0.02); PMD->SetIN(6., 18., -580., 27., 27.); PMD->SetGEO(0.0, 0.2, 4.); PMD->SetPadSize(0.8, 1.0, 1.0, 1.5); } if(iSTART) { //=================== START parameters ============================ AliSTART *START = new AliSTARTv1("START","START Detector"); } } <|endoftext|>
<commit_before>#include "ocos.h" #ifdef ENABLE_GPT2_TOKENIZER #include "gpt2_tokenizer.hpp" #endif #ifdef ENABLE_SPM_TOKENIZER #include "sentencepiece_tokenizer.hpp" #endif #ifdef ENABLE_BERT_TOKENIZER #include "wordpiece_tokenizer.hpp" #endif #ifdef ENABLE_BLINGFIRE #include "blingfire_sentencebreaker.hpp" #endif FxLoadCustomOpFactory LoadCustomOpClasses_Tokenizer = &LoadCustomOpClasses< #ifdef ENABLE_GPT2_TOKENIZER CustomOpBpeTokenizer #endif #ifdef ENABLE_SPM_TOKENIZER , CustomOpSentencepieceTokenizer #endif #ifdef ENABLE_BERT_TOKENIZER , CustomOpWordpieceTokenizer #endif #ifdef ENABLE_BLINGFIRE , CustomOpBlingFireSentenceBreaker #endif >; <commit_msg>Fix comma error. (#138)<commit_after>#include "ocos.h" #ifdef ENABLE_GPT2_TOKENIZER #include "gpt2_tokenizer.hpp" #endif #ifdef ENABLE_SPM_TOKENIZER #include "sentencepiece_tokenizer.hpp" #endif #ifdef ENABLE_BERT_TOKENIZER #include "wordpiece_tokenizer.hpp" #endif #ifdef ENABLE_BLINGFIRE #include "blingfire_sentencebreaker.hpp" #endif FxLoadCustomOpFactory LoadCustomOpClasses_Tokenizer = &LoadCustomOpClasses< #ifdef ENABLE_GPT2_TOKENIZER CustomOpBpeTokenizer #endif #ifdef ENABLE_SPM_TOKENIZER #if defined ENABLE_GPT2_TOKENIZER // comma required only when previous tokenizer is defined, // otherwise it will throw build error: expected expression. , #endif CustomOpSentencepieceTokenizer #endif #ifdef ENABLE_BERT_TOKENIZER #if defined ENABLE_GPT2_TOKENIZER || defined ENABLE_SPM_TOKENIZER // comma required only when previous tokenizer is defined , #endif CustomOpWordpieceTokenizer #endif #ifdef ENABLE_BLINGFIRE #if defined ENABLE_GPT2_TOKENIZER || defined ENABLE_SPM_TOKENIZER || defined ENABLE_BERT_TOKENIZER // comma required only when previous tokenizer is defined , #endif CustomOpBlingFireSentenceBreaker #endif >; <|endoftext|>
<commit_before>/*-------------------------------------------------------------------------- * Copyright 2011 Taro L. Saito * * 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 <string> #include <cstring> #include <snappy.h> #include "SnappyNative.h" void throw_exception(JNIEnv *env, jobject self, int errorCode) { jclass c = env->FindClass("org/xerial/snappy/SnappyNative"); if(c==0) return; jmethodID mth_throwex = env->GetMethodID(c, "throw_error", "(I)V"); if(mth_throwex == 0) return; env->CallVoidMethod(self, mth_throwex, (jint) errorCode); } JNIEXPORT jstring JNICALL Java_org_xerial_snappy_SnappyNative_nativeLibraryVersion (JNIEnv * env, jobject self) { return env->NewStringUTF("1.1.0"); } JNIEXPORT jlong JNICALL Java_org_xerial_snappy_SnappyNative_rawCompress__JJJ (JNIEnv* env, jobject self, jlong srcAddr, jlong length, jlong destAddr) { size_t compressedLength; snappy::RawCompress((char*) srcAddr, (size_t) length, (char*) destAddr, &compressedLength); return (jlong) compressedLength; } JNIEXPORT jlong JNICALL Java_org_xerial_snappy_SnappyNative_rawUncompress__JJJ (JNIEnv* env, jobject self, jlong srcAddr, jlong length, jlong destAddr) { size_t uncompressedLength; snappy::GetUncompressedLength((char*) srcAddr, (size_t) length, &uncompressedLength); bool ret = snappy::RawUncompress((char*) srcAddr, (size_t) length, (char*) destAddr); if(!ret) { throw_exception(env, self, 5); return 0; } return (jlong) uncompressedLength; } /* * Class: org_xerial_snappy_Snappy * Method: compress * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)J */ JNIEXPORT jint JNICALL Java_org_xerial_snappy_SnappyNative_rawCompress__Ljava_nio_ByteBuffer_2IILjava_nio_ByteBuffer_2I (JNIEnv* env, jobject self, jobject uncompressed, jint upos, jint ulen, jobject compressed, jint cpos) { char* uncompressedBuffer = (char*) env->GetDirectBufferAddress(uncompressed); char* compressedBuffer = (char*) env->GetDirectBufferAddress(compressed); if(uncompressedBuffer == 0 || compressedBuffer == 0) { throw_exception(env, self, 3); return (jint) 0; } size_t compressedLength; snappy::RawCompress(uncompressedBuffer + upos, (size_t) ulen, compressedBuffer + cpos, &compressedLength); return (jint) compressedLength; } JNIEXPORT jint JNICALL Java_org_xerial_snappy_SnappyNative_rawCompress__Ljava_lang_Object_2IILjava_lang_Object_2I (JNIEnv * env, jobject self, jobject input, jint inputOffset, jint inputLen, jobject output, jint outputOffset) { char* in = (char*) env->GetPrimitiveArrayCritical((jarray) input, 0); char* out = (char*) env->GetPrimitiveArrayCritical((jarray) output, 0); if(in == 0 || out == 0) { // out of memory throw_exception(env, self, 4); return 0; } size_t compressedLength; snappy::RawCompress(in + inputOffset, (size_t) inputLen, out + outputOffset, &compressedLength); env->ReleasePrimitiveArrayCritical((jarray) input, in, 0); env->ReleasePrimitiveArrayCritical((jarray) output, out, 0); return (jint) compressedLength; } JNIEXPORT jint JNICALL Java_org_xerial_snappy_SnappyNative_rawUncompress__Ljava_lang_Object_2IILjava_lang_Object_2I (JNIEnv * env, jobject self, jobject input, jint inputOffset, jint inputLength, jobject output, jint outputOffset) { char* in = (char*) env->GetPrimitiveArrayCritical((jarray) input, 0); char* out = (char*) env->GetPrimitiveArrayCritical((jarray) output, 0); if(in == 0 || out == 0) { // out of memory throw_exception(env, self, 4); return 0; } size_t uncompressedLength; snappy::GetUncompressedLength(in + inputOffset, (size_t) inputLength, &uncompressedLength); bool ret = snappy::RawUncompress(in + inputOffset, (size_t) inputLength, out + outputOffset); env->ReleasePrimitiveArrayCritical((jarray) input, in, 0); env->ReleasePrimitiveArrayCritical((jarray) output, out, 0); if(!ret) { throw_exception(env, self, 5); return 0; } return (jint) uncompressedLength; } /* * Class: org_xerial_snappy_Snappy * Method: uncompress * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)Z */ JNIEXPORT jint JNICALL Java_org_xerial_snappy_SnappyNative_rawUncompress__Ljava_nio_ByteBuffer_2IILjava_nio_ByteBuffer_2I (JNIEnv * env, jobject self, jobject compressed, jint cpos, jint clen, jobject decompressed, jint dpos) { char* compressedBuffer = (char*) env->GetDirectBufferAddress(compressed); char* decompressedBuffer = (char*) env->GetDirectBufferAddress(decompressed); if(compressedBuffer == 0 || decompressedBuffer == 0) { throw_exception(env, self, 3); return (jint) 0; } size_t decompressedLength; snappy::GetUncompressedLength(compressedBuffer + cpos, (size_t) clen, &decompressedLength); bool ret = snappy::RawUncompress(compressedBuffer + cpos, (size_t) clen, decompressedBuffer + dpos); if(!ret) { throw_exception(env, self, 5); return 0; } return (jint) decompressedLength; } /* * Class: org_xerial_snappy_Snappy * Method: maxCompressedLength * Signature: (J)J */ JNIEXPORT jint JNICALL Java_org_xerial_snappy_SnappyNative_maxCompressedLength (JNIEnv *, jobject, jint size) { size_t l = snappy::MaxCompressedLength((size_t) size); return (jint) l; } /* * Class: org_xerial_snappy_Snappy * Method: getUncompressedLength * Signature: (Ljava/nio/ByteBuffer;)J */ JNIEXPORT jint JNICALL Java_org_xerial_snappy_SnappyNative_uncompressedLength__Ljava_nio_ByteBuffer_2II (JNIEnv * env, jobject self, jobject compressed, jint cpos, jint clen) { char* compressedBuffer = (char*) env->GetDirectBufferAddress(compressed); if(compressedBuffer == 0) { throw_exception(env, self, 3); return (jint) 0; } size_t result; bool ret = snappy::GetUncompressedLength(compressedBuffer + cpos, (size_t) clen, &result); if(!ret) { throw_exception(env, self, 2); return 0; } return (jint) result; } JNIEXPORT jint JNICALL Java_org_xerial_snappy_SnappyNative_uncompressedLength__Ljava_lang_Object_2II (JNIEnv * env, jobject self, jobject input, jint offset, jint length) { char* in = (char*) env->GetPrimitiveArrayCritical((jarray) input, 0); if(in == 0) { // out of memory throw_exception(env, self, 4); return 0; } size_t result; bool ret = snappy::GetUncompressedLength(in + offset, (size_t) length, &result); env->ReleasePrimitiveArrayCritical((jarray) input, in, 0); if(!ret) { throw_exception(env, self, 2); return 0; } return (jint) result; } JNIEXPORT jlong JNICALL Java_org_xerial_snappy_SnappyNative_uncompressedLength__JJ (JNIEnv *env, jobject self, jlong inputAddr, jlong len) { size_t result; bool ret = snappy::GetUncompressedLength((char*) inputAddr, (size_t) len, &result); if(!ret) { throw_exception(env, self, 2); return 0; } return (jint) result; } JNIEXPORT jboolean JNICALL Java_org_xerial_snappy_SnappyNative_isValidCompressedBuffer__Ljava_nio_ByteBuffer_2II (JNIEnv * env, jobject self, jobject compressed, jint cpos, jint clen) { char* compressedBuffer = (char*) env->GetDirectBufferAddress(compressed); if(compressedBuffer == 0) { throw_exception(env, self, 3); return (jint) 0; } bool ret = snappy::IsValidCompressedBuffer(compressedBuffer + cpos, (size_t) clen); return ret; } JNIEXPORT jboolean JNICALL Java_org_xerial_snappy_SnappyNative_isValidCompressedBuffer__Ljava_lang_Object_2II (JNIEnv * env, jobject self, jobject input, jint offset, jint length) { char* in = (char*) env->GetPrimitiveArrayCritical((jarray) input, 0); if(in == 0) { // out of memory throw_exception(env, self, 4); return 0; } bool ret = snappy::IsValidCompressedBuffer(in + offset, (size_t) length); env->ReleasePrimitiveArrayCritical((jarray) input, in, 0); return ret; } JNIEXPORT void JNICALL Java_org_xerial_snappy_SnappyNative_arrayCopy (JNIEnv * env, jobject self, jobject input, jint offset, jint length, jobject output, jint output_offset) { char* src = (char*) env->GetPrimitiveArrayCritical((jarray) input, 0); char* dest = (char*) env->GetPrimitiveArrayCritical((jarray) output, 0); if(src == 0 || dest == 0) { // out of memory throw_exception(env, self, 4); return; } memcpy(dest+output_offset, src+offset, (size_t) length); env->ReleasePrimitiveArrayCritical((jarray) input, src, 0); env->ReleasePrimitiveArrayCritical((jarray) output, dest, 0); } <commit_msg>Avoid leaks with GetPrimitiveArrayCritical.<commit_after>/*-------------------------------------------------------------------------- * Copyright 2011 Taro L. Saito * * 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 <string> #include <cstring> #include <snappy.h> #include "SnappyNative.h" void throw_exception(JNIEnv *env, jobject self, int errorCode) { jclass c = env->FindClass("org/xerial/snappy/SnappyNative"); if(c==0) return; jmethodID mth_throwex = env->GetMethodID(c, "throw_error", "(I)V"); if(mth_throwex == 0) return; env->CallVoidMethod(self, mth_throwex, (jint) errorCode); } JNIEXPORT jstring JNICALL Java_org_xerial_snappy_SnappyNative_nativeLibraryVersion (JNIEnv * env, jobject self) { return env->NewStringUTF("1.1.0"); } JNIEXPORT jlong JNICALL Java_org_xerial_snappy_SnappyNative_rawCompress__JJJ (JNIEnv* env, jobject self, jlong srcAddr, jlong length, jlong destAddr) { size_t compressedLength; snappy::RawCompress((char*) srcAddr, (size_t) length, (char*) destAddr, &compressedLength); return (jlong) compressedLength; } JNIEXPORT jlong JNICALL Java_org_xerial_snappy_SnappyNative_rawUncompress__JJJ (JNIEnv* env, jobject self, jlong srcAddr, jlong length, jlong destAddr) { size_t uncompressedLength; snappy::GetUncompressedLength((char*) srcAddr, (size_t) length, &uncompressedLength); bool ret = snappy::RawUncompress((char*) srcAddr, (size_t) length, (char*) destAddr); if(!ret) { throw_exception(env, self, 5); return 0; } return (jlong) uncompressedLength; } /* * Class: org_xerial_snappy_Snappy * Method: compress * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)J */ JNIEXPORT jint JNICALL Java_org_xerial_snappy_SnappyNative_rawCompress__Ljava_nio_ByteBuffer_2IILjava_nio_ByteBuffer_2I (JNIEnv* env, jobject self, jobject uncompressed, jint upos, jint ulen, jobject compressed, jint cpos) { char* uncompressedBuffer = (char*) env->GetDirectBufferAddress(uncompressed); char* compressedBuffer = (char*) env->GetDirectBufferAddress(compressed); if(uncompressedBuffer == 0 || compressedBuffer == 0) { throw_exception(env, self, 3); return (jint) 0; } size_t compressedLength; snappy::RawCompress(uncompressedBuffer + upos, (size_t) ulen, compressedBuffer + cpos, &compressedLength); return (jint) compressedLength; } JNIEXPORT jint JNICALL Java_org_xerial_snappy_SnappyNative_rawCompress__Ljava_lang_Object_2IILjava_lang_Object_2I (JNIEnv * env, jobject self, jobject input, jint inputOffset, jint inputLen, jobject output, jint outputOffset) { char* in = (char*) env->GetPrimitiveArrayCritical((jarray) input, 0); char* out = (char*) env->GetPrimitiveArrayCritical((jarray) output, 0); if(in == 0 || out == 0) { // out of memory if(in != 0) { env->ReleasePrimitiveArrayCritical((jarray) input, in, 0); } if(out != 0) { env->ReleasePrimitiveArrayCritical((jarray) output, out, 0); } throw_exception(env, self, 4); return 0; } size_t compressedLength; snappy::RawCompress(in + inputOffset, (size_t) inputLen, out + outputOffset, &compressedLength); env->ReleasePrimitiveArrayCritical((jarray) input, in, 0); env->ReleasePrimitiveArrayCritical((jarray) output, out, 0); return (jint) compressedLength; } JNIEXPORT jint JNICALL Java_org_xerial_snappy_SnappyNative_rawUncompress__Ljava_lang_Object_2IILjava_lang_Object_2I (JNIEnv * env, jobject self, jobject input, jint inputOffset, jint inputLength, jobject output, jint outputOffset) { char* in = (char*) env->GetPrimitiveArrayCritical((jarray) input, 0); char* out = (char*) env->GetPrimitiveArrayCritical((jarray) output, 0); if(in == 0 || out == 0) { // out of memory if(in != 0) { env->ReleasePrimitiveArrayCritical((jarray) input, in, 0); } if(out != 0) { env->ReleasePrimitiveArrayCritical((jarray) output, out, 0); } throw_exception(env, self, 4); return 0; } size_t uncompressedLength; snappy::GetUncompressedLength(in + inputOffset, (size_t) inputLength, &uncompressedLength); bool ret = snappy::RawUncompress(in + inputOffset, (size_t) inputLength, out + outputOffset); env->ReleasePrimitiveArrayCritical((jarray) input, in, 0); env->ReleasePrimitiveArrayCritical((jarray) output, out, 0); if(!ret) { throw_exception(env, self, 5); return 0; } return (jint) uncompressedLength; } /* * Class: org_xerial_snappy_Snappy * Method: uncompress * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)Z */ JNIEXPORT jint JNICALL Java_org_xerial_snappy_SnappyNative_rawUncompress__Ljava_nio_ByteBuffer_2IILjava_nio_ByteBuffer_2I (JNIEnv * env, jobject self, jobject compressed, jint cpos, jint clen, jobject decompressed, jint dpos) { char* compressedBuffer = (char*) env->GetDirectBufferAddress(compressed); char* decompressedBuffer = (char*) env->GetDirectBufferAddress(decompressed); if(compressedBuffer == 0 || decompressedBuffer == 0) { throw_exception(env, self, 3); return (jint) 0; } size_t decompressedLength; snappy::GetUncompressedLength(compressedBuffer + cpos, (size_t) clen, &decompressedLength); bool ret = snappy::RawUncompress(compressedBuffer + cpos, (size_t) clen, decompressedBuffer + dpos); if(!ret) { throw_exception(env, self, 5); return 0; } return (jint) decompressedLength; } /* * Class: org_xerial_snappy_Snappy * Method: maxCompressedLength * Signature: (J)J */ JNIEXPORT jint JNICALL Java_org_xerial_snappy_SnappyNative_maxCompressedLength (JNIEnv *, jobject, jint size) { size_t l = snappy::MaxCompressedLength((size_t) size); return (jint) l; } /* * Class: org_xerial_snappy_Snappy * Method: getUncompressedLength * Signature: (Ljava/nio/ByteBuffer;)J */ JNIEXPORT jint JNICALL Java_org_xerial_snappy_SnappyNative_uncompressedLength__Ljava_nio_ByteBuffer_2II (JNIEnv * env, jobject self, jobject compressed, jint cpos, jint clen) { char* compressedBuffer = (char*) env->GetDirectBufferAddress(compressed); if(compressedBuffer == 0) { throw_exception(env, self, 3); return (jint) 0; } size_t result; bool ret = snappy::GetUncompressedLength(compressedBuffer + cpos, (size_t) clen, &result); if(!ret) { throw_exception(env, self, 2); return 0; } return (jint) result; } JNIEXPORT jint JNICALL Java_org_xerial_snappy_SnappyNative_uncompressedLength__Ljava_lang_Object_2II (JNIEnv * env, jobject self, jobject input, jint offset, jint length) { char* in = (char*) env->GetPrimitiveArrayCritical((jarray) input, 0); if(in == 0) { // out of memory throw_exception(env, self, 4); return 0; } size_t result; bool ret = snappy::GetUncompressedLength(in + offset, (size_t) length, &result); env->ReleasePrimitiveArrayCritical((jarray) input, in, 0); if(!ret) { throw_exception(env, self, 2); return 0; } return (jint) result; } JNIEXPORT jlong JNICALL Java_org_xerial_snappy_SnappyNative_uncompressedLength__JJ (JNIEnv *env, jobject self, jlong inputAddr, jlong len) { size_t result; bool ret = snappy::GetUncompressedLength((char*) inputAddr, (size_t) len, &result); if(!ret) { throw_exception(env, self, 2); return 0; } return (jint) result; } JNIEXPORT jboolean JNICALL Java_org_xerial_snappy_SnappyNative_isValidCompressedBuffer__Ljava_nio_ByteBuffer_2II (JNIEnv * env, jobject self, jobject compressed, jint cpos, jint clen) { char* compressedBuffer = (char*) env->GetDirectBufferAddress(compressed); if(compressedBuffer == 0) { throw_exception(env, self, 3); return (jint) 0; } bool ret = snappy::IsValidCompressedBuffer(compressedBuffer + cpos, (size_t) clen); return ret; } JNIEXPORT jboolean JNICALL Java_org_xerial_snappy_SnappyNative_isValidCompressedBuffer__Ljava_lang_Object_2II (JNIEnv * env, jobject self, jobject input, jint offset, jint length) { char* in = (char*) env->GetPrimitiveArrayCritical((jarray) input, 0); if(in == 0) { // out of memory throw_exception(env, self, 4); return 0; } bool ret = snappy::IsValidCompressedBuffer(in + offset, (size_t) length); env->ReleasePrimitiveArrayCritical((jarray) input, in, 0); return ret; } JNIEXPORT void JNICALL Java_org_xerial_snappy_SnappyNative_arrayCopy (JNIEnv * env, jobject self, jobject input, jint offset, jint length, jobject output, jint output_offset) { char* src = (char*) env->GetPrimitiveArrayCritical((jarray) input, 0); char* dest = (char*) env->GetPrimitiveArrayCritical((jarray) output, 0); if(src == 0 || dest == 0) { // out of memory if(src != 0) { env->ReleasePrimitiveArrayCritical((jarray) input, src, 0); } if(dest != 0) { env->ReleasePrimitiveArrayCritical((jarray) output, dest, 0); } throw_exception(env, self, 4); return; } memcpy(dest+output_offset, src+offset, (size_t) length); env->ReleasePrimitiveArrayCritical((jarray) input, src, 0); env->ReleasePrimitiveArrayCritical((jarray) output, dest, 0); } <|endoftext|>
<commit_before>// Copyright (c) 2010 Nickolas Pohilets // // This file is a part of the CppEvents library. // // 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 <pthread.h> namespace Cpp { //------------------------------------------------------------------------------ class RecursiveMutex { public: RecursiveMutex() { pthread_mutexattr_init(&attr_); pthread_mutexattr_settype(&attr_, PTHREAD_MUTEX_RECURSIVE_NP); pthread_mutex_init(&mutex_, &attr_); } ~RecursiveMutex() { pthread_mutex_destroy(&mutex_); pthread_mutexattr_destroy(&attr_); } void lock() { pthread_mutex_lock(&mutex_); } void unlock() { pthread_mutex_unlock(&mutex_); } private: pthread_mutexattr_t attr_; pthread_mutex_t mutex_; }; //------------------------------------------------------------------------------ } //namespace Cpp <commit_msg>-: Fixed: Compilation problem on Mac OS X<commit_after>// Copyright (c) 2010 Nickolas Pohilets // // This file is a part of the CppEvents library. // // 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 <pthread.h> namespace Cpp { //------------------------------------------------------------------------------ class RecursiveMutex { public: RecursiveMutex() { pthread_mutexattr_init(&attr_); pthread_mutexattr_settype(&attr_, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mutex_, &attr_); } ~RecursiveMutex() { pthread_mutex_destroy(&mutex_); pthread_mutexattr_destroy(&attr_); } void lock() { pthread_mutex_lock(&mutex_); } void unlock() { pthread_mutex_unlock(&mutex_); } private: pthread_mutexattr_t attr_; pthread_mutex_t mutex_; }; //------------------------------------------------------------------------------ } //namespace Cpp <|endoftext|>
<commit_before>#include "AudioMaterialEditor.hpp" #include <Engine/Audio/AudioMaterial.hpp> #include "../FileSelector.hpp" #include <functional> #include <imgui.h> #include "ImGui/GuiHelpers.hpp" using namespace GUI; AudioMaterialEditor::AudioMaterialEditor() { name[0] = '\0'; } void AudioMaterialEditor::Show() { if (ImGui::Begin(("Sound: " + audioMaterial->name + "###" + std::to_string(reinterpret_cast<uintptr_t>(audioMaterial))).c_str(), &visible, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders)) { ImGui::InputText("Name", name, 128); audioMaterial->name = name; glm::vec3 freqAbsorption(audioMaterial->lowFreqAbsorption, audioMaterial->midFreqAbsorption, audioMaterial->highFreqAbsorption); ImGui::Text("Frequency absorption"); ImGui::ShowHelpMarker("Fraction of sound energy absorbed at [low, mid, high] frequencies", 150.f); ImGui::Indent(); ImGui::DragFloat3("[low, mid, high] absorption", &freqAbsorption[0], 0.f, 0.f, 1.f); ImGui::Unindent(); audioMaterial->lowFreqAbsorption = freqAbsorption[0]; audioMaterial->midFreqAbsorption = freqAbsorption[1]; audioMaterial->highFreqAbsorption = freqAbsorption[2]; glm::vec3 freqTransmission(audioMaterial->lowFreqTransmission, audioMaterial->midFreqTransmission, audioMaterial->highFreqTransmission); ImGui::Text("Frequency transmission"); ImGui::ShowHelpMarker("Fraction of sound energy transmitted through at [low, mid, high] frequencies", 165.f); ImGui::Indent(); ImGui::DragFloat3("[low, mid, high] transmitted", &freqTransmission[0], 0.f, 0.f, 1.f); ImGui::Unindent(); audioMaterial->lowFreqTransmission = freqTransmission[0]; audioMaterial->midFreqTransmission = freqTransmission[1]; audioMaterial->highFreqTransmission = freqTransmission[2]; ImGui::Text("Scattering"); ImGui::ShowHelpMarker("Fraction of sound energy that is scattered in a random direction when it reaches the surface", 80.f); ImGui::ShowHelpMarker("A value of 0.0 describes a smooth surface with mirror - like reflection properties; a value of 1.0 describes rough surface with diffuse reflection properties.", 100.f); ImGui::Indent(); ImGui::DraggableFloat("", audioMaterial->scattering, 0.f, 1.f); ImGui::Unindent(); } ImGui::End(); if (fileSelector.IsVisible()) fileSelector.Show(); } const Audio::AudioMaterial* AudioMaterialEditor::GetAudioMaterial() const { return audioMaterial; } void AudioMaterialEditor::SetAudioMaterial(Audio::AudioMaterial* audioMaterial) { this->audioMaterial = audioMaterial; strcpy(name, audioMaterial->name.c_str()); } bool AudioMaterialEditor::IsVisible() const { return visible; } void AudioMaterialEditor::SetVisible(bool visible) { this->visible = visible; } <commit_msg>Move audio material file when renaming<commit_after>#include "AudioMaterialEditor.hpp" #include <Engine/Audio/AudioMaterial.hpp> #include "../FileSelector.hpp" #include <functional> #include <imgui.h> #include "ImGui/GuiHelpers.hpp" #include <Engine/Hymn.hpp> using namespace GUI; AudioMaterialEditor::AudioMaterialEditor() { name[0] = '\0'; } void AudioMaterialEditor::Show() { if (ImGui::Begin(("Sound: " + audioMaterial->name + "###" + std::to_string(reinterpret_cast<uintptr_t>(audioMaterial))).c_str(), &visible, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders)) { if (ImGui::InputText("Name", name, 128)) { // Rename audio material file. std::string path = Hymn().GetPath() + "/" + audioMaterial->path; rename((path + audioMaterial->name + ".json").c_str(), (path + name + ".json").c_str()); audioMaterial->name = name; } glm::vec3 freqAbsorption(audioMaterial->lowFreqAbsorption, audioMaterial->midFreqAbsorption, audioMaterial->highFreqAbsorption); ImGui::Text("Frequency absorption"); ImGui::ShowHelpMarker("Fraction of sound energy absorbed at [low, mid, high] frequencies", 150.f); ImGui::Indent(); ImGui::DragFloat3("[low, mid, high] absorption", &freqAbsorption[0], 0.f, 0.f, 1.f); ImGui::Unindent(); audioMaterial->lowFreqAbsorption = freqAbsorption[0]; audioMaterial->midFreqAbsorption = freqAbsorption[1]; audioMaterial->highFreqAbsorption = freqAbsorption[2]; glm::vec3 freqTransmission(audioMaterial->lowFreqTransmission, audioMaterial->midFreqTransmission, audioMaterial->highFreqTransmission); ImGui::Text("Frequency transmission"); ImGui::ShowHelpMarker("Fraction of sound energy transmitted through at [low, mid, high] frequencies", 165.f); ImGui::Indent(); ImGui::DragFloat3("[low, mid, high] transmitted", &freqTransmission[0], 0.f, 0.f, 1.f); ImGui::Unindent(); audioMaterial->lowFreqTransmission = freqTransmission[0]; audioMaterial->midFreqTransmission = freqTransmission[1]; audioMaterial->highFreqTransmission = freqTransmission[2]; ImGui::Text("Scattering"); ImGui::ShowHelpMarker("Fraction of sound energy that is scattered in a random direction when it reaches the surface", 80.f); ImGui::ShowHelpMarker("A value of 0.0 describes a smooth surface with mirror - like reflection properties; a value of 1.0 describes rough surface with diffuse reflection properties.", 100.f); ImGui::Indent(); ImGui::DraggableFloat("", audioMaterial->scattering, 0.f, 1.f); ImGui::Unindent(); } ImGui::End(); if (fileSelector.IsVisible()) fileSelector.Show(); } const Audio::AudioMaterial* AudioMaterialEditor::GetAudioMaterial() const { return audioMaterial; } void AudioMaterialEditor::SetAudioMaterial(Audio::AudioMaterial* audioMaterial) { this->audioMaterial = audioMaterial; strcpy(name, audioMaterial->name.c_str()); } bool AudioMaterialEditor::IsVisible() const { return visible; } void AudioMaterialEditor::SetVisible(bool visible) { this->visible = visible; } <|endoftext|>
<commit_before>#include <string> #include <iostream> #if defined(_MSC_VER) #include <SDL.h> #include <SDL_image.h> #elif defined(__clang__) #include <SDL2/SDL.h> #include <SDL2_image/SDL_image.h> #else #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #endif /* * Lesson 5: Clipping Sprite Sheets */ //Screen attributes const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; /** * Log an SDL error with some error message to the output stream of our choice * @param os The output stream to write the message too * @param msg The error message to write, format will be msg error: SDL_GetError() */ void logSDLError(std::ostream &os, const std::string &msg){ os << msg << " error: " << SDL_GetError() << std::endl; } /** * Loads an image into a texture on the rendering device * @param file The image file to load * @param ren The renderer to load the texture onto * @return the loaded texture, or nullptr if something went wrong. */ SDL_Texture* loadTexture(const std::string &file, SDL_Renderer *ren){ SDL_Texture *texture = IMG_LoadTexture(ren, file.c_str()); if (texture == nullptr) logSDLError(std::cout, "LoadTexture"); return texture; } /** * Draw an SDL_Texture to an SDL_Renderer at some destination rect * taking a clip of the texture if desired * @param tex The source texture we want to draw * @param rend The renderer we want to draw too * @param dst The destination rectangle to render the texture too * @param clip The sub-section of the texture to draw (clipping rect) * default of nullptr draws the entire texture */ void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, SDL_Rect dst, SDL_Rect *clip = nullptr){ SDL_RenderCopy(ren, tex, clip, &dst); } /** * Draw an SDL_Texture to an SDL_Renderer at position x, y, preserving * the texture's width and height and taking a clip of the texture if desired * If a clip is passed, the clip's width and height will be used instead of the texture's * @param tex The source texture we want to draw * @param rend The renderer we want to draw too * @param x The x coordinate to draw too * @param y The y coordinate to draw too * @param clip The sub-section of the texture to draw (clipping rect) * default of nullptr draws the entire texture */ void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y, SDL_Rect *clip = nullptr){ SDL_Rect dst; dst.x = x; dst.y = y; if (clip != nullptr){ dst.w = clip->w; dst.h = clip->h; } else SDL_QueryTexture(tex, NULL, NULL, &dst.w, &dst.h); renderTexture(tex, ren, dst, clip); } int main(int argc, char** argv){ //Start up SDL and make sure it went ok if (SDL_Init(SDL_INIT_EVERYTHING) != 0){ logSDLError(std::cout, "SDL_Init"); return 1; } //Setup our window and renderer SDL_Window *window = SDL_CreateWindow("Lesson 5", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (window == nullptr){ logSDLError(std::cout, "CreateWindow"); return 2; } SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (renderer == nullptr){ logSDLError(std::cout, "CreateRenderer"); return 3; } SDL_Texture *image = loadTexture("../res/Lesson5/image.png", renderer); if (image == nullptr) return 4; //iW and iH are the clip width and height //We'll be drawing only clips so get a center position for the w/h of a clip int iW = 100, iH = 100; int x = SCREEN_WIDTH / 2 - iW / 2; int y = SCREEN_HEIGHT / 2 - iH / 2; //Setup the clips for our image SDL_Rect clips[4]; //Since our clips our uniform in size we can generate a list of their //positions using some math (the specifics of this are covered in the lesson) for (int i = 0; i < 4; ++i){ clips[i].x = i / 2 * iW; clips[i].y = i % 2 * iH; clips[i].w = iW; clips[i].h = iH; } //Specify a default clip to start with int useClip = 0; SDL_Event e; bool quit = false; while (!quit){ //Event Polling while (SDL_PollEvent(&e)){ //If user closes he window if (e.type == SDL_QUIT) quit = true; //Use number input to select which clip should be drawn if (e.type == SDL_KEYDOWN){ switch (e.key.keysym.sym){ case SDLK_1: useClip = 0; break; case SDLK_2: useClip = 1; break; case SDLK_3: useClip = 2; break; case SDLK_4: useClip = 3; break; case SDLK_ESCAPE: quit = true; break; default: break; } } } //Rendering SDL_RenderClear(renderer); //Draw the image renderTexture(image, renderer, x, y, &clips[useClip]); //Update the screen SDL_RenderPresent(renderer); } //Clean up SDL_DestroyTexture(image); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); return 0; } <commit_msg>whoops a typo<commit_after>#include <string> #include <iostream> #if defined(_MSC_VER) #include <SDL.h> #include <SDL_image.h> #elif defined(__clang__) #include <SDL2/SDL.h> #include <SDL2_image/SDL_image.h> #else #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #endif /* * Lesson 5: Clipping Sprite Sheets */ //Screen attributes const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; /** * Log an SDL error with some error message to the output stream of our choice * @param os The output stream to write the message too * @param msg The error message to write, format will be msg error: SDL_GetError() */ void logSDLError(std::ostream &os, const std::string &msg){ os << msg << " error: " << SDL_GetError() << std::endl; } /** * Loads an image into a texture on the rendering device * @param file The image file to load * @param ren The renderer to load the texture onto * @return the loaded texture, or nullptr if something went wrong. */ SDL_Texture* loadTexture(const std::string &file, SDL_Renderer *ren){ SDL_Texture *texture = IMG_LoadTexture(ren, file.c_str()); if (texture == nullptr) logSDLError(std::cout, "LoadTexture"); return texture; } /** * Draw an SDL_Texture to an SDL_Renderer at some destination rect * taking a clip of the texture if desired * @param tex The source texture we want to draw * @param rend The renderer we want to draw too * @param dst The destination rectangle to render the texture too * @param clip The sub-section of the texture to draw (clipping rect) * default of nullptr draws the entire texture */ void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, SDL_Rect dst, SDL_Rect *clip = nullptr){ SDL_RenderCopy(ren, tex, clip, &dst); } /** * Draw an SDL_Texture to an SDL_Renderer at position x, y, preserving * the texture's width and height and taking a clip of the texture if desired * If a clip is passed, the clip's width and height will be used instead of the texture's * @param tex The source texture we want to draw * @param rend The renderer we want to draw too * @param x The x coordinate to draw too * @param y The y coordinate to draw too * @param clip The sub-section of the texture to draw (clipping rect) * default of nullptr draws the entire texture */ void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y, SDL_Rect *clip = nullptr){ SDL_Rect dst; dst.x = x; dst.y = y; if (clip != nullptr){ dst.w = clip->w; dst.h = clip->h; } else SDL_QueryTexture(tex, NULL, NULL, &dst.w, &dst.h); renderTexture(tex, ren, dst, clip); } int main(int argc, char** argv){ //Start up SDL and make sure it went ok if (SDL_Init(SDL_INIT_EVERYTHING) != 0){ logSDLError(std::cout, "SDL_Init"); return 1; } //Setup our window and renderer SDL_Window *window = SDL_CreateWindow("Lesson 5", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (window == nullptr){ logSDLError(std::cout, "CreateWindow"); return 2; } SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (renderer == nullptr){ logSDLError(std::cout, "CreateRenderer"); return 3; } SDL_Texture *image = loadTexture("../res/Lesson5/image.png", renderer); if (image == nullptr) return 4; //iW and iH are the clip width and height //We'll be drawing only clips so get a center position for the w/h of a clip int iW = 100, iH = 100; int x = SCREEN_WIDTH / 2 - iW / 2; int y = SCREEN_HEIGHT / 2 - iH / 2; //Setup the clips for our image SDL_Rect clips[4]; //Since our clips our uniform in size we can generate a list of their //positions using some math (the specifics of this are covered in the lesson) for (int i = 0; i < 4; ++i){ clips[i].x = i / 2 * iW; clips[i].y = i % 2 * iH; clips[i].w = iW; clips[i].h = iH; } //Specify a default clip to start with int useClip = 0; SDL_Event e; bool quit = false; while (!quit){ //Event Polling while (SDL_PollEvent(&e)){ if (e.type == SDL_QUIT) quit = true; //Use number input to select which clip should be drawn if (e.type == SDL_KEYDOWN){ switch (e.key.keysym.sym){ case SDLK_1: useClip = 0; break; case SDLK_2: useClip = 1; break; case SDLK_3: useClip = 2; break; case SDLK_4: useClip = 3; break; case SDLK_ESCAPE: quit = true; break; default: break; } } } //Rendering SDL_RenderClear(renderer); //Draw the image renderTexture(image, renderer, x, y, &clips[useClip]); //Update the screen SDL_RenderPresent(renderer); } //Clean up SDL_DestroyTexture(image); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); return 0; } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ // --- // Macro for MUON alignment using physics tracks. The macro uses AliMUONAlignment // class to calculate the alignment parameters. // An array for the alignment parameters is created and can be filled with // initial values that will be used as starting values by the alignment // algorithm. // Ny default the macro run over galice.root in the working directory. If a file list // of galice.root is provided as third argument the macro will run over all files. // The macro loop over the files, events and tracks. For each track // AliMUONAlignment::ProcessTrack(AliMUONTrack * track) and then // AliMUONAlignment::LocalFit(Int_t iTrack, Double_t *lTrackParam, Int_t // lSingleFit) are called. After all tracks have been procesed and fitted // AliMUONAlignment::GlobalFit(Double_t *parameters,Double_t *errors,Double_t *pulls) // is called. The array parameters contains the obatained misalignement parameters. // A realigned geometry is generated in a local CDB. // // Authors: B. Becker and J. Castillo // --- void MUONAlignment(Int_t nEvents = 100000, char* geoFilename = "geometry.root", TString fileName = "galice.root", TString fileList = "") { // Import TGeo geometry (needed by AliMUONTrackExtrap::ExtrapToVertex) if (!gGeoManager) { TGeoManager::Import(geoFilename); if (!gGeoManager) { Error("MUONmass_ESD", "getting geometry from file %s failed", geoFilename); return; } } // set mag field // waiting for mag field in CDB printf("Loading field map...\n"); AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 1, 1., 10., AliMagFMaps::k5kG); AliTracker::SetFieldMap(field, kFALSE); // set the magnetic field for track extrapolations AliMUONTrackExtrap::SetField(AliTracker::GetFieldMap()); Double_t parameters[3*156]; Double_t errors[3*156]; Double_t pulls[3*156]; for(Int_t k=0;k<3*156;k++) { parameters[k]=0.; errors[k]=0.; pulls[k]=0.; } Double_t trackParams[8] = {0.,0.,0.,0.,0.,0.,0.,0.}; Int_t iPar = 0; // Set initial values here, good guess may help convergence // St 1 // parameters[iPar++] = 0.010300 ; parameters[iPar++] = 0.010600 ; parameters[iPar++] = 0.000396 ; bool bLoop = kFALSE; ifstream sFileList; if (fileList.Contains(".list")) { cout << "Reading file list: " << fileList.Data() << endl; bLoop = kTRUE; TString fullListName("."); fullListName +="/"; fullListName +=fileList; sFileList.open(fileList.Data()); } TH1F *fInvBenMom = new TH1F("fInvBenMom","fInvBenMom",200,-0.1,0.1); TH1F *fBenMom = new TH1F("fBenMom","fBenMom",200,-40,40); AliMUONAlignment* alig = new AliMUONAlignment(); alig->InitGlobalParameters(parameters); AliMUONGeometryTransformer *transform = new AliMUONGeometryTransformer(true); transform->ReadGeometryData("volpath.dat", gGeoManager); alig->SetGeometryTransformer(transform); // Set tracking station to use Bool_t bStOnOff[5] = {kTRUE,kTRUE,kTRUE,kTRUE,kTRUE}; // Fix parameters or add constraints here for (Int_t iSt=0; iSt<5; iSt++) if (!bStOnOff[iSt]) alig->FixStation(iSt+1); // Left and right sides of the detector are independent, one can choose to align // only one side Bool_t bSpecLROnOff[2] = {kTRUE,kTRUE}; alig->FixHalfSpectrometer(bStOnOff,bSpecLROnOff); // Set predifined global constrains: X, Y, P, XvsZ, YvsZ, PvsZ, XvsY, YvsY, PvsY Bool_t bVarXYT[9] = {kTRUE,kTRUE,kTRUE,kTRUE,kTRUE,kTRUE,kTRUE,kTRUE,kTRUE}; Bool_t bDetTLBR[4] = {kFALSE,kTRUE,kFALSE,kTRUE}; alig->AddConstraints(bStOnOff,bVarXYT,bDetTLBR,bSpecLROnOff); char cFileName[100]; AliMUONDataInterface amdi; Int_t lMaxFile = 1000; Int_t iFile = 0; Int_t iEvent = 0; bool bKeepLoop = kTRUE; Int_t iTrackTot=0; Int_t iTrackOk=0; while(bKeepLoop && iFile<lMaxFile){ iFile++; if (bLoop) { sFileList.getline(cFileName,100); if (sFileList.eof()) bKeepLoop = kFALSE; } else { sprintf(cFileName,fileName.Data()); bKeepLoop = kFALSE; } if (!strstr(cFileName,"galice.root")) continue; cout << "Using file: " << cFileName << endl; amdi.SetFile(cFileName); Int_t nevents = amdi.NumberOfEvents(); cout << "... with " << nevents << endl; for(Int_t event = 0; event < nevents; event++) { amdi.GetEvent(event); if (iEvent >= nEvents){ bKeepLoop = kFALSE; break; } iEvent++; Int_t ntracks = amdi.NumberOfRecTracks(); if (!event%100) cout << " there are " << ntracks << " tracks in event " << event << endl; Int_t iTrack=0; AliMUONTrack* track = amdi.RecTrack(iTrack); while(track) { AliMUONTrackParam trackParam(*((AliMUONTrackParam*)(track->GetTrackParamAtHit()->First()))); AliMUONTrackExtrap::ExtrapToVertex(&trackParam,0.,0.,0.); Double_t invBenMom = trackParam.GetInverseBendingMomentum(); fInvBenMom->Fill(invBenMom); fBenMom->Fill(1./invBenMom); if (TMath::Abs(invBenMom)<=1.04) { alig->ProcessTrack(track); alig->LocalFit(iTrackOk++,trackParams,0); } iTrack++; iTrackTot++; track = amdi.RecTrack(iTrack); } } cout << "Processed " << iTrackTot << " Tracks so far." << endl; } alig->GlobalFit(parameters,errors,pulls); cout << "Done with GlobalFit " << endl; // Store results Double_t DEid[156] = {0}; Double_t MSDEx[156] = {0}; Double_t MSDEy[156] = {0}; Double_t MSDExt[156] = {0}; Double_t MSDEyt[156] = {0}; Double_t DEidErr[156] = {0}; Double_t MSDExErr[156] = {0}; Double_t MSDEyErr[156] = {0}; Double_t MSDExtErr[156] = {0}; Double_t MSDEytErr[156] = {0}; Int_t lNDetElem = 4*2+4*2+18*2+26*2+26*2; Int_t lNDetElemCh[10] = {4,4,4,4,18,18,26,26,26,26}; Int_t lSNDetElemCh[10] = {4,8,12,16,34,52,78,104,130,156}; Int_t idOffset = 0; // 400 Int_t lSDetElemCh = 0; for(Int_t iDE=0; iDE<lNDetElem; iDE++){ DEidErr[iDE] = 0.; DEid[iDE] = idOffset+100; DEid[iDE] += iDE; lSDetElemCh = 0; for(Int_t iCh=0; iCh<9; iCh++){ lSDetElemCh += lNDetElemCh[iCh]; if (iDE>=lSDetElemCh) { DEid[iDE] += 100; DEid[iDE] -= lNDetElemCh[iCh]; } } MSDEx[iDE]=parameters[3*iDE+0]; MSDEy[iDE]=parameters[3*iDE+1]; MSDExt[iDE]=parameters[3*iDE+2]; MSDEyt[iDE]=parameters[3*iDE+2]; MSDExErr[iDE]=(Double_t)alig->GetParError(3*iDE+0); MSDEyErr[iDE]=(Double_t)alig->GetParError(3*iDE+1); MSDExtErr[iDE]=(Double_t)alig->GetParError(3*iDE+2); MSDEytErr[iDE]=(Double_t)alig->GetParError(3*iDE+2); } cout << "Let's create graphs ... " << endl; TGraphErrors *gMSDEx = new TGraphErrors(lNDetElem,DEid,MSDEx,DEidErr,MSDExErr); TGraphErrors *gMSDEy = new TGraphErrors(lNDetElem,DEid,MSDEy,DEidErr,MSDEyErr); TGraphErrors *gMSDExt = new TGraphErrors(lNDetElem,DEid,MSDExt,DEidErr,MSDExtErr); TGraphErrors *gMSDEyt = new TGraphErrors(lNDetElem,DEid,MSDEyt,DEidErr,MSDEytErr); cout << "... graphs created, open file ... " << endl; TFile *hFile = new TFile("measShifts.root","RECREATE"); cout << "... file opened ... " << endl; gMSDEx->Write("gMSDEx"); gMSDEy->Write("gMSDEy"); gMSDExt->Write("gMSDExt"); gMSDEyt->Write("gMSDEyt"); fInvBenMom->Write(); fBenMom->Write(); hFile->Close(); cout << "... and closed!" << endl; // Re Align AliMUONGeometryTransformer *newTransform = alig->ReAlign(transform,parameters,true); newTransform->WriteTransformations("transform2ReAlign.dat"); // Generate realigned data in local cdb TClonesArray* array = newTransform->GetMisAlignmentData(); // CDB manager AliCDBManager* cdbManager = AliCDBManager::Instance(); cdbManager->SetDefaultStorage("local://ReAlignCDB"); AliCDBMetaData* cdbData = new AliCDBMetaData(); cdbData->SetResponsible("Dimuon Offline project"); cdbData->SetComment("MUON alignment objects with residual misalignment"); AliCDBId id("MUON/Align/Data", 0, 0); cdbManager->Put(array, id, cdbData); } <commit_msg>Added includes to make macro compilable and corrected compiler errors & warnings<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ // --- // Macro for MUON alignment using physics tracks. The macro uses AliMUONAlignment // class to calculate the alignment parameters. // An array for the alignment parameters is created and can be filled with // initial values that will be used as starting values by the alignment // algorithm. // Ny default the macro run over galice.root in the working directory. If a file list // of galice.root is provided as third argument the macro will run over all files. // The macro loop over the files, events and tracks. For each track // AliMUONAlignment::ProcessTrack(AliMUONTrack * track) and then // AliMUONAlignment::LocalFit(Int_t iTrack, Double_t *lTrackParam, Int_t // lSingleFit) are called. After all tracks have been procesed and fitted // AliMUONAlignment::GlobalFit(Double_t *parameters,Double_t *errors,Double_t *pulls) // is called. The array parameters contains the obatained misalignement parameters. // A realigned geometry is generated in a local CDB. // // Authors: B. Becker and J. Castillo // --- #if !defined(__CINT__) || defined(__MAKECINT__) #include "AliMUONAlignment.h" #include "AliMUONTrack.h" #include "AliMUONTrackExtrap.h" #include "AliMUONTrackParam.h" #include "AliMUONGeometryTransformer.h" #include "AliMUONDataInterface.h" #include "AliMagFMaps.h" #include "AliTracker.h" #include "AliCDBManager.h" #include "AliCDBMetaData.h" #include "AliCDBId.h" #include <TString.h> #include <TGeoManager.h> #include <TError.h> #include <TH1.h> #include <TGraphErrors.h> #include <TFile.h> #include <TClonesArray.h> #include <Riostream.h> #include <fstream> #endif void MUONAlignment(Int_t nEvents = 100000, char* geoFilename = "geometry.root", TString fileName = "galice.root", TString fileList = "") { // Import TGeo geometry (needed by AliMUONTrackExtrap::ExtrapToVertex) if (!gGeoManager) { TGeoManager::Import(geoFilename); if (!gGeoManager) { Error("MUONmass_ESD", "getting geometry from file %s failed", geoFilename); return; } } // set mag field // waiting for mag field in CDB printf("Loading field map...\n"); AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 1, 1., 10., AliMagFMaps::k5kG); AliTracker::SetFieldMap(field, kFALSE); // set the magnetic field for track extrapolations AliMUONTrackExtrap::SetField(AliTracker::GetFieldMap()); Double_t parameters[3*156]; Double_t errors[3*156]; Double_t pulls[3*156]; for(Int_t k=0;k<3*156;k++) { parameters[k]=0.; errors[k]=0.; pulls[k]=0.; } Double_t trackParams[8] = {0.,0.,0.,0.,0.,0.,0.,0.}; // Set initial values here, good guess may help convergence // St 1 // Int_t iPar = 0; // parameters[iPar++] = 0.010300 ; parameters[iPar++] = 0.010600 ; parameters[iPar++] = 0.000396 ; bool bLoop = kFALSE; ifstream sFileList; if (fileList.Contains(".list")) { cout << "Reading file list: " << fileList.Data() << endl; bLoop = kTRUE; TString fullListName("."); fullListName +="/"; fullListName +=fileList; sFileList.open(fileList.Data()); } TH1F *fInvBenMom = new TH1F("fInvBenMom","fInvBenMom",200,-0.1,0.1); TH1F *fBenMom = new TH1F("fBenMom","fBenMom",200,-40,40); AliMUONAlignment* alig = new AliMUONAlignment(); alig->InitGlobalParameters(parameters); AliMUONGeometryTransformer *transform = new AliMUONGeometryTransformer(true); transform->ReadGeometryData("volpath.dat", gGeoManager); alig->SetGeometryTransformer(transform); // Set tracking station to use Bool_t bStOnOff[5] = {kTRUE,kTRUE,kTRUE,kTRUE,kTRUE}; // Fix parameters or add constraints here for (Int_t iSt=0; iSt<5; iSt++) if (!bStOnOff[iSt]) alig->FixStation(iSt+1); // Left and right sides of the detector are independent, one can choose to align // only one side Bool_t bSpecLROnOff[2] = {kTRUE,kTRUE}; alig->FixHalfSpectrometer(bStOnOff,bSpecLROnOff); // Set predifined global constrains: X, Y, P, XvsZ, YvsZ, PvsZ, XvsY, YvsY, PvsY Bool_t bVarXYT[9] = {kTRUE,kTRUE,kTRUE,kTRUE,kTRUE,kTRUE,kTRUE,kTRUE,kTRUE}; Bool_t bDetTLBR[4] = {kFALSE,kTRUE,kFALSE,kTRUE}; alig->AddConstraints(bStOnOff,bVarXYT,bDetTLBR,bSpecLROnOff); char cFileName[100]; AliMUONDataInterface amdi; Int_t lMaxFile = 1000; Int_t iFile = 0; Int_t iEvent = 0; bool bKeepLoop = kTRUE; Int_t iTrackTot=0; Int_t iTrackOk=0; while(bKeepLoop && iFile<lMaxFile){ iFile++; if (bLoop) { sFileList.getline(cFileName,100); if (sFileList.eof()) bKeepLoop = kFALSE; } else { sprintf(cFileName,fileName.Data()); bKeepLoop = kFALSE; } if (!strstr(cFileName,"galice.root")) continue; cout << "Using file: " << cFileName << endl; amdi.SetFile(cFileName); Int_t nevents = amdi.NumberOfEvents(); cout << "... with " << nevents << endl; for(Int_t event = 0; event < nevents; event++) { amdi.GetEvent(event); if (iEvent >= nEvents){ bKeepLoop = kFALSE; break; } iEvent++; Int_t ntracks = amdi.NumberOfRecTracks(); if (!event%100) cout << " there are " << ntracks << " tracks in event " << event << endl; Int_t iTrack=0; AliMUONTrack* track = amdi.RecTrack(iTrack); while(track) { AliMUONTrackParam trackParam(*((AliMUONTrackParam*)(track->GetTrackParamAtHit()->First()))); AliMUONTrackExtrap::ExtrapToVertex(&trackParam,0.,0.,0.); Double_t invBenMom = trackParam.GetInverseBendingMomentum(); fInvBenMom->Fill(invBenMom); fBenMom->Fill(1./invBenMom); if (TMath::Abs(invBenMom)<=1.04) { alig->ProcessTrack(track); alig->LocalFit(iTrackOk++,trackParams,0); } iTrack++; iTrackTot++; track = amdi.RecTrack(iTrack); } } cout << "Processed " << iTrackTot << " Tracks so far." << endl; } alig->GlobalFit(parameters,errors,pulls); cout << "Done with GlobalFit " << endl; // Store results Double_t DEid[156] = {0}; Double_t MSDEx[156] = {0}; Double_t MSDEy[156] = {0}; Double_t MSDExt[156] = {0}; Double_t MSDEyt[156] = {0}; Double_t DEidErr[156] = {0}; Double_t MSDExErr[156] = {0}; Double_t MSDEyErr[156] = {0}; Double_t MSDExtErr[156] = {0}; Double_t MSDEytErr[156] = {0}; Int_t lNDetElem = 4*2+4*2+18*2+26*2+26*2; Int_t lNDetElemCh[10] = {4,4,4,4,18,18,26,26,26,26}; // Int_t lSNDetElemCh[10] = {4,8,12,16,34,52,78,104,130,156}; Int_t idOffset = 0; // 400 Int_t lSDetElemCh = 0; for(Int_t iDE=0; iDE<lNDetElem; iDE++){ DEidErr[iDE] = 0.; DEid[iDE] = idOffset+100; DEid[iDE] += iDE; lSDetElemCh = 0; for(Int_t iCh=0; iCh<9; iCh++){ lSDetElemCh += lNDetElemCh[iCh]; if (iDE>=lSDetElemCh) { DEid[iDE] += 100; DEid[iDE] -= lNDetElemCh[iCh]; } } MSDEx[iDE]=parameters[3*iDE+0]; MSDEy[iDE]=parameters[3*iDE+1]; MSDExt[iDE]=parameters[3*iDE+2]; MSDEyt[iDE]=parameters[3*iDE+2]; MSDExErr[iDE]=(Double_t)alig->GetParError(3*iDE+0); MSDEyErr[iDE]=(Double_t)alig->GetParError(3*iDE+1); MSDExtErr[iDE]=(Double_t)alig->GetParError(3*iDE+2); MSDEytErr[iDE]=(Double_t)alig->GetParError(3*iDE+2); } cout << "Let's create graphs ... " << endl; TGraphErrors *gMSDEx = new TGraphErrors(lNDetElem,DEid,MSDEx,DEidErr,MSDExErr); TGraphErrors *gMSDEy = new TGraphErrors(lNDetElem,DEid,MSDEy,DEidErr,MSDEyErr); TGraphErrors *gMSDExt = new TGraphErrors(lNDetElem,DEid,MSDExt,DEidErr,MSDExtErr); TGraphErrors *gMSDEyt = new TGraphErrors(lNDetElem,DEid,MSDEyt,DEidErr,MSDEytErr); cout << "... graphs created, open file ... " << endl; TFile *hFile = new TFile("measShifts.root","RECREATE"); cout << "... file opened ... " << endl; gMSDEx->Write("gMSDEx"); gMSDEy->Write("gMSDEy"); gMSDExt->Write("gMSDExt"); gMSDEyt->Write("gMSDEyt"); fInvBenMom->Write(); fBenMom->Write(); hFile->Close(); cout << "... and closed!" << endl; // Re Align AliMUONGeometryTransformer *newTransform = alig->ReAlign(transform,parameters,true); newTransform->WriteTransformations("transform2ReAlign.dat"); // Generate realigned data in local cdb const TClonesArray* array = newTransform->GetMisAlignmentData(); // CDB manager AliCDBManager* cdbManager = AliCDBManager::Instance(); cdbManager->SetDefaultStorage("local://ReAlignCDB"); AliCDBMetaData* cdbData = new AliCDBMetaData(); cdbData->SetResponsible("Dimuon Offline project"); cdbData->SetComment("MUON alignment objects with residual misalignment"); AliCDBId id("MUON/Align/Data", 0, 0); cdbManager->Put(const_cast<TClonesArray*>(array), id, cdbData); } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ /// \ingroup macros /// \file MUONStatusMap.C /// \brief Macro to check/test pad status and pad status map makers /// /// \author Laurent Aphecetche #if !defined(__CINT__) || defined(__MAKECINT__) #include "AliCDBManager.h" #include "AliMUONCalibrationData.h" #include "AliMUONLogger.h" #include "AliMUONPadStatusMaker.h" #include "AliMUONPadStatusMapMaker.h" #include "AliMUONRecoParam.h" #include "AliMUONVCalibParam.h" #include "AliMUONVStore.h" #include "AliMUONCDB.h" #include "AliMpConstants.h" #include "AliMpDDLStore.h" #include "AliMpDetElement.h" #include "AliMpManuIterator.h" #include "Riostream.h" #endif //AliMUONVStore* MUONStatusMap(const TString& cdbStorage = "alien://folder=/alice/data/2009/OCDB", AliMUONVStore* MUONStatusMap(const TString& cdbStorage = "alien://folder=/alice/data/2011/OCDB", Int_t runNumber=145000, Bool_t statusOnly=kTRUE) { AliCDBManager::Instance()->SetDefaultStorage(cdbStorage); AliCDBManager::Instance()->SetRun(runNumber); AliMUONCDB::LoadMapping(); AliMUONRecoParam* recoParam = AliMUONCDB::LoadRecoParam(); AliCDBManager* man = AliCDBManager::Instance(); man->SetDefaultStorage(cdbStorage.Data()); // man->SetSpecificStorage("MUON/Calib/OccupancyMap","local://$ALICE_ROOT/OCDB"); // man->SetSpecificStorage("MUON/Calib/OccupancyMap","alien://folder=/alice/cern.ch/user/l/laphecet/OCDB"); // man->SetSpecificStorage("MUON/Calib/RejectList","alien://folder=/alice/cern.ch/user/l/laphecet/OCDB"); // man->SetSpecificStorage("MUON/Align/Data","alien://folder=/alice/cern.ch/user/l/laphecet/OCDB"); AliMUONCalibrationData cd(runNumber); AliMUONPadStatusMaker statusMaker(cd); statusMaker.SetLimits(*recoParam); UInt_t mask = recoParam->PadGoodnessMask(); // delete recoParam; statusMaker.Report(mask); if ( statusOnly ) return statusMaker.StatusStore(); const Bool_t deferredInitialization = kFALSE; AliMUONPadStatusMapMaker statusMapMaker(cd,mask,deferredInitialization); return statusMapMaker.StatusMap(); } <commit_msg>Upgrade to draw evolution of the number of live channels<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ /// \ingroup macros /// \file MUONStatusMap.C /// \brief Macro to check/test pad status and pad status map makers /// /// \author Laurent Aphecetche #if !defined(__CINT__) || defined(__MAKECINT__) #include "AliCDBManager.h" #include "AliCDBEntry.h" #include "AliLog.h" #include "AliMpCDB.h" #include "AliMUONCDB.h" #include "AliMUONCalibrationData.h" #include "AliMUONPadStatusMaker.h" #include "AliMUONPadStatusMapMaker.h" #include "AliMUONRecoParam.h" #include "AliMUONVCalibParam.h" #include "AliMUONVStore.h" #include "AliMpConstants.h" #include "AliMpDDLStore.h" #include "AliMpDetElement.h" #include "AliMpManuIterator.h" #include "Riostream.h" #include "TAxis.h" #include "TCanvas.h" #include "TLegend.h" #include "TFile.h" #include "TGraph.h" #include "TBox.h" #include "TH2F.h" #include "TStyle.h" #include "TText.h" #include <vector> #endif namespace { Int_t NTOTALNUMBEROFPADS(1064008); } //______________________________________________________________________________ void ReadIntegers(const char* filename, std::vector<int>& integers) { /// Read integers from filename, where integers are either /// separated by "," or by return carriage ifstream in(gSystem->ExpandPathName(filename)); int i; char line[10000]; in.getline(line,10000,'\n'); TString sline(line); if (sline.Contains(",")) { TObjArray* a = sline.Tokenize(","); TIter next(a); TObjString* s; while ( ( s = static_cast<TObjString*>(next()) ) ) { integers.push_back(s->String().Atoi()); } } else { integers.push_back(sline.Atoi()); while ( in >> i ) { integers.push_back(i); } } std::sort(integers.begin(),integers.end()); } //______________________________________________________________________________ void MUONStatusMap(AliMUONVStore*& vstatus, AliMUONVStore*& vstatusMap, const char* cdbStorage = "alien://folder=/alice/data/2011/OCDB", Int_t runNumber=145292) { AliCDBManager::Instance()->SetDefaultStorage(cdbStorage); AliCDBManager::Instance()->SetRun(runNumber); // AliCDBManager::Instance()->SetSpecificStorage("MUON/Calib/RecoParam","alien://folder=/alice/cern.ch/user/c/cgeuna/OCDB"); AliMUONCDB::LoadMapping(); AliMUONRecoParam* recoParam = AliMUONCDB::LoadRecoParam(); // man->SetSpecificStorage("MUON/Calib/OccupancyMap","local://$ALICE_ROOT/OCDB"); // man->SetSpecificStorage("MUON/Calib/OccupancyMap","alien://folder=/alice/cern.ch/user/l/laphecet/OCDB"); // man->SetSpecificStorage("MUON/Calib/RejectList","alien://folder=/alice/cern.ch/user/l/laphecet/OCDB"); // man->SetSpecificStorage("MUON/Align/Data","alien://folder=/alice/cern.ch/user/l/laphecet/OCDB"); AliMUONCalibrationData cd(runNumber); AliMUONPadStatusMaker statusMaker(cd); statusMaker.SetLimits(*recoParam); UInt_t mask = recoParam->PadGoodnessMask(); // delete recoParam; statusMaker.Report(mask); vstatus = static_cast<AliMUONVStore*>(statusMaker.StatusStore()->Clone()); const Bool_t deferredInitialization = kFALSE; AliMUONPadStatusMapMaker statusMapMaker(cd,mask,deferredInitialization); vstatusMap = static_cast<AliMUONVStore*>(statusMapMaker.StatusMap()->Clone()); } //______________________________________________________________________________ Int_t GetBadChannels(Int_t runNumber, Int_t& nbadped, Int_t& nbadhv, Int_t& nbadgain, Int_t& nbadocc, Int_t& nmissing, Int_t& nreco) { if (!AliCDBManager::Instance()->IsDefaultStorageSet()) { AliCDBManager::Instance()->SetDefaultStorage("raw://"); } AliCDBManager::Instance()->SetRun(runNumber); AliMpCDB::LoadDDLStore(); AliMUONCalibrationData cd(runNumber,true); AliMUONPadStatusMaker statusMaker(cd); AliMUONRecoParam* recoParam = AliMUONCDB::LoadRecoParam(); statusMaker.SetLimits(*recoParam); AliMpManuIterator it; Int_t detElemId, manuId; Int_t pedCheck = ( AliMUONPadStatusMaker::kPedMeanZero | AliMUONPadStatusMaker::kPedMeanTooLow | AliMUONPadStatusMaker::kPedMeanTooHigh | AliMUONPadStatusMaker::kPedSigmaTooLow | AliMUONPadStatusMaker::kPedSigmaTooHigh ); Int_t hvCheck = ( AliMUONPadStatusMaker::kHVError | AliMUONPadStatusMaker::kHVTooLow | AliMUONPadStatusMaker::kHVTooHigh | AliMUONPadStatusMaker::kHVChannelOFF | AliMUONPadStatusMaker::kHVSwitchOFF ); Int_t occCheck = ( AliMUONPadStatusMaker::kManuOccupancyTooHigh ); Int_t ntotal(0); Int_t nbad(0); nbadped=0; nbadocc=0; nbadgain=0; nbadhv=0; nmissing=0; nreco=0; while ( it.Next(detElemId,manuId) ) { AliMpDetElement* de = AliMpDDLStore::Instance()->GetDetElement(detElemId); for ( Int_t manuChannel = 0; manuChannel < AliMpConstants::ManuNofChannels(); ++manuChannel ) { if ( de->IsConnectedChannel(manuId,manuChannel) ) { ++ntotal; UInt_t status = statusMaker.PadStatus(detElemId, manuId, manuChannel); if (!status) continue; bool bad(false); if ( status & AliMUONPadStatusMaker::BuildStatus(pedCheck,0,0,0) ) { ++nbadped; bad=true; } if ( status & AliMUONPadStatusMaker::BuildStatus(0,hvCheck,0,0) ) { ++nbadhv; bad=true; } if ( status & AliMUONPadStatusMaker::BuildStatus(0,0,0,occCheck) ) { ++nbadocc; bad=true; } if ( status & recoParam->PadGoodnessMask() ) { ++nreco; } if ( status & AliMUONPadStatusMaker::BuildStatus(AliMUONPadStatusMaker::kMissing,0,0,AliMUONPadStatusMaker::kMissing) ) { bad=true; ++nmissing; } if (bad) ++nbad; } } } if (ntotal!=NTOTALNUMBEROFPADS) { cerr << Form("ERROR ! NOT THE EXPECTED NUMBER OF CHANNELS (%d vs 1064008) FOR RUN %09d", ntotal,runNumber) << endl; } AliCDBManager::Instance()->ClearCache(); return nbad; } //______________________________________________________________________________ void Draw(TFile* f, const char* gname, TLegend* l, Bool_t normalized) { if (!f) return; TGraph* g = static_cast<TGraph*>(f->Get(gname)); if (!g) return; if ( normalized ) { g = static_cast<TGraph*>(g->Clone()); for ( Int_t i = 0; i < g->GetN(); ++i ) { Double_t y = g->GetY()[i]; g->SetPoint(i,g->GetX()[i],y/NTOTALNUMBEROFPADS); } } g->Draw("lp"); g->GetXaxis()->SetNdivisions(505); g->GetXaxis()->SetNoExponent(); if (l) l->AddEntry(g,gname,"LP"); } //______________________________________________________________________________ void DrawPeriod(double run1, double run2, double ymin, double ymax, const char* label) { TBox* b = new TBox(run1,ymin,run2,ymax); b->SetFillColor(5); b->Draw(); TText* text = new TText((run1+run2)/2.0,ymax*0.6,label); text->SetTextSize(0.05); text->Draw(); } //______________________________________________________________________________ void DrawEvolution(const char* file, bool normalized=true) { TFile* f = TFile::Open(file); if (!f) return; TCanvas* c = new TCanvas("mch-status-evolution","mch-status-evolution"); c->SetGridy(); c->SetTicky(); c->Draw(); TLegend* l = new TLegend(0.1,0.7,0.3,0.95,"ch evolution"); TGraph* g = static_cast<TGraph*>(f->Get("nbad")); if (!g) return; int runmin = TMath::Nint(g->GetX()[0]); int runmax = TMath::Nint(g->GetX()[g->GetN()-1]); double ymax(0.4); TH2* h = new TH2F("hframe","hframe;Run number;Fraction of dead channels",100,runmin-200,runmax+200,100,0,ymax); gStyle->SetOptStat(kFALSE); h->Draw(); h->GetXaxis()->SetNoExponent(); h->GetXaxis()->SetNdivisions(505); gStyle->SetOptTitle(kFALSE); DrawPeriod(115881,117222,0,ymax,"10b"); DrawPeriod(119159,120824,0,ymax,"10c"); DrawPeriod(122374,126424,0,ymax,"10d"); DrawPeriod(127724,130850,0,ymax,"10e"); DrawPeriod(133005,134929,0,ymax,"10f"); DrawPeriod(135658,136376,0,ymax,"10g"); DrawPeriod(137133,139513,0,ymax,"10h"); DrawPeriod(143856,146860,0,ymax,"11a"); DrawPeriod(148370,150702,0,ymax,"11b"); DrawPeriod(155384,155384,0,ymax,"11c"); DrawPeriod(156477,159606,0,ymax,"11d"); Draw(f,"nbad",l,normalized); Draw(f,"nbadped",l,normalized); Draw(f,"nbadocc",l,normalized); Draw(f,"nbadhv",l,normalized); Draw(f,"nmissing",l,normalized); Draw(f,"nreco",l,normalized); h->Draw("same"); c->RedrawAxis("g"); l->Draw(); } //______________________________________________________________________________ void MUONStatusMapEvolution(const char* runlist, const char* outfile) { // Compute the number of bad pads (because of bad ped, bad hv, bad occupancy // or missing in configuration) // // output a root file with the different graphs. // // output can be then plotted using the DrawEvolution function // std::vector<int> runs; ReadIntegers(runlist,runs); if ( runs.empty() ) { cout << "No runs to process..." << endl; return; } int year(2011); if ( runs[0] <= 139699 ) year=2010; AliCDBManager::Instance()->SetDefaultStorage(Form("alien://folder=/alice/data/%d/OCDB?cacheFold=/local/cdb",year)); // AliCDBManager::Instance()->SetDefaultStorage("local:///local/cdb/alice/data/2010/OCDB"); TList glist; glist.SetOwner(kTRUE); TGraph* gnbad = new TGraph(runs.size()); gnbad->SetName("nbad"); glist.Add(gnbad); TGraph* gnbadped = new TGraph(runs.size()); gnbadped->SetName("nbadped"); glist.Add(gnbadped); TGraph* gnbadocc = new TGraph(runs.size()); gnbadocc->SetName("nbadocc"); glist.Add(gnbadocc); TGraph* gnbadhv = new TGraph(runs.size()); gnbadhv->SetName("nbadhv"); glist.Add(gnbadhv); TGraph* gnmissing = new TGraph(runs.size()); gnmissing->SetName("nmissing"); glist.Add(gnmissing); TGraph* gnreco = new TGraph(runs.size()); gnreco->SetName("nreco"); glist.Add(gnreco); for ( std::vector<int>::size_type i = 0; i < runs.size(); ++i ) { Int_t runNumber = runs[i]; Int_t nbadped; Int_t nbadhv; Int_t nbadgain; Int_t nbadocc; Int_t nmissing; Int_t nreco; Int_t nbad = GetBadChannels(runNumber,nbadped,nbadhv,nbadgain,nbadocc,nmissing,nreco); gnbad->SetPoint(i,runNumber,nbad); gnbadped->SetPoint(i,runNumber,nbadped); gnbadhv->SetPoint(i,runNumber,nbadhv); gnbadocc->SetPoint(i,runNumber,nbadocc); gnmissing->SetPoint(i,runNumber,nmissing); gnreco->SetPoint(i,runNumber,nreco); } TIter next(&glist); TGraph* g; Int_t index(0); TFile f(outfile,"recreate"); Int_t color[] = { 1 , 2 , 3 , 4, 6, 8 }; Int_t marker[] = { 28 , 24 , 23 , 26, 30, 5 }; while ( ( g = static_cast<TGraph*>(next() ) ) ) { g->GetXaxis()->SetNdivisions(505); g->GetXaxis()->SetNoExponent(); g->SetMinimum(0); g->GetYaxis()->SetNoExponent(); g->SetLineColor(color[index]); g->SetMarkerStyle(marker[index]); g->SetMarkerColor(color[index]); g->SetMarkerSize(1.0); ++index; g->Write(); } f.Close(); } <|endoftext|>
<commit_before>#include <unordered_map> #include <string> #include <numeric> #include <algorithm> #include <Rcpp.h> using namespace Rcpp; using namespace std; // [[Rcpp::export]] SEXP cpp_stack(SEXP arlist) { auto array_list = as<List>(arlist); auto dimnames = vector<vector<string>>(); // dim: names along auto axmap = vector<unordered_map<string, int>>(); // dim: element name->index auto a2r = vector<vector<vector<int>>>(array_list.size()); // array > dim > element // create lookup tables for all present dimension names for (int a=0; a<Rf_xlength(array_list); a++) { // array in arlist auto va = as<NumericVector>(array_list[a]); auto dn = as<List>(va.attr("dimnames")); auto da = as<vector<int>>(va.attr("dim")); a2r[a] = vector<vector<int>>(da.size()); if (dimnames.size() < da.size()) { dimnames.resize(da.size()); axmap.resize(da.size()); } for (int d=0; d<da.size(); d++) { // dimension in array auto dni = as<vector<string>>(dn[d]); for (int e=0; e<da[d]; e++) { // element in dimension if (axmap[d].count(dni[e]) == 0) { cout << "array " << a << " dim " << d << ": " << dni[e] << " -> " << axmap[d].size() << "\n"; axmap[d].emplace(dni[e], axmap[d].size()); dimnames[d].push_back(dni[e]); } a2r[a][d].push_back(axmap[d][dni[e]]); } } } for (auto ai=0; ai<a2r.size(); ai++) for (auto di=0; di<a2r[ai].size(); di++) { cout << "*** array " << ai << " dim " << di << ": "; copy(a2r[ai][di].begin(), a2r[ai][di].end(), ostream_iterator<int>(cout, " ")); cout << "\n"; } // create result array with attributes auto rdim = IntegerVector(dimnames.size()); auto rdnames = List(dimnames.size()); for (int i=0; i<dimnames.size(); i++) { rdim[i] = dimnames[i].size(); rdnames[i] = CharacterVector(dimnames[i].begin(), dimnames[i].end()); } auto n = accumulate(rdim.begin(), rdim.end(), 1, multiplies<int>()); auto result = NumericVector(n); result.attr("dim") = rdim; result.attr("dimnames") = rdnames; // fill the result array int maxdim = rdim.size() - 1; for (int ai=0; ai<Rf_xlength(array_list); ai++) { auto a = as<NumericVector>(array_list[ai]); int aidx = 0; // consecutive elements in original array auto it = vector<vector<int>::iterator>(a2r[ai].size()); // one for each result dim for (int d=0; d<it.size(); d++) it[d] = a2r[ai][d].begin(); int dim_offset = 0; for (int d=0; d<maxdim; d++) dim_offset += rdim[d] * *it[d+1]; do { int cur_offset = *it[0]; int dim_offset_new = 0; it[0]++; for (int d=0; d<maxdim; d++) { if (it[d] != a2r[ai][d].end()) // no dimension jump break; dim_offset_new += rdim[d]; // add only dimensions we jump it[d] = a2r[ai][d].begin(); it[d+1]++; } cout << "result[" << cur_offset + dim_offset << "] = a[" << ai << "][" << aidx << "]\n"; result[cur_offset + dim_offset] = a[aidx++]; dim_offset += dim_offset_new; } while(it[maxdim] != a2r[ai][maxdim].end()); } return result; } <commit_msg>more consistent var names<commit_after>#include <unordered_map> #include <string> #include <numeric> #include <algorithm> #include <Rcpp.h> using namespace Rcpp; using namespace std; // [[Rcpp::export]] SEXP cpp_stack(SEXP arlist) { auto array_list = as<List>(arlist); auto dimnames = vector<vector<string>>(); // dim: names along auto axmap = vector<unordered_map<string, int>>(); // dim: element name->index auto a2r = vector<vector<vector<int>>>(array_list.size()); // array > dim > element // create lookup tables for all present dimension names for (int ai=0; ai<Rf_xlength(array_list); ai++) { // array in arlist auto a = as<NumericVector>(array_list[ai]); auto dn = as<List>(a.attr("dimnames")); auto da = as<vector<int>>(a.attr("dim")); a2r[ai] = vector<vector<int>>(da.size()); if (dimnames.size() < da.size()) { dimnames.resize(da.size()); axmap.resize(da.size()); } for (int d=0; d<da.size(); d++) { // dimension in array auto dni = as<vector<string>>(dn[d]); for (int e=0; e<da[d]; e++) { // element in dimension if (axmap[d].count(dni[e]) == 0) { cout << "array " << ai << " dim " << d << ": " << dni[e] << " -> " << axmap[d].size() << "\n"; axmap[d].emplace(dni[e], axmap[d].size()); dimnames[d].push_back(dni[e]); } a2r[ai][d].push_back(axmap[d][dni[e]]); } } } for (auto ai=0; ai<a2r.size(); ai++) for (auto di=0; di<a2r[ai].size(); di++) { cout << "*** array " << ai << " dim " << di << ": "; copy(a2r[ai][di].begin(), a2r[ai][di].end(), ostream_iterator<int>(cout, " ")); cout << "\n"; } // create result array with attributes auto rdim = IntegerVector(dimnames.size()); auto rdnames = List(dimnames.size()); for (int i=0; i<dimnames.size(); i++) { rdim[i] = dimnames[i].size(); rdnames[i] = CharacterVector(dimnames[i].begin(), dimnames[i].end()); } auto n = accumulate(rdim.begin(), rdim.end(), 1, multiplies<int>()); auto result = NumericVector(n); result.attr("dim") = rdim; result.attr("dimnames") = rdnames; // fill the result array int maxdim = rdim.size() - 1; for (int ai=0; ai<Rf_xlength(array_list); ai++) { auto a = as<NumericVector>(array_list[ai]); int aidx = 0; // consecutive elements in original array auto it = vector<vector<int>::iterator>(a2r[ai].size()); // one for each result dim for (int d=0; d<it.size(); d++) it[d] = a2r[ai][d].begin(); int dim_offset = 0; for (int d=0; d<maxdim; d++) dim_offset += rdim[d] * *it[d+1]; do { int cur_offset = *it[0]; int dim_offset_new = 0; it[0]++; for (int d=0; d<maxdim; d++) { if (it[d] != a2r[ai][d].end()) // no dimension jump break; dim_offset_new += rdim[d]; // add only dimensions we jump it[d] = a2r[ai][d].begin(); it[d+1]++; } cout << "result[" << cur_offset + dim_offset << "] = a[" << ai << "][" << aidx << "]\n"; result[cur_offset + dim_offset] = a[aidx++]; dim_offset += dim_offset_new; } while(it[maxdim] != a2r[ai][maxdim].end()); } return result; } <|endoftext|>
<commit_before>#include "stack.h" #include<string> #include<iostream> using namespace std; //Not using STL at the moment ... //stack.cpp is just temporary work-around till a more suitable solution is found node::node() { cmd = " "; next = NULL; } stack::stack() { top = NULL; temp = NULL; } void stack::pop() { temp = top; if (temp == NULL) return; top = top->next; delete temp; } int stack::isEmpty() { return (top == NULL) ? 1 : 0; } void stack::clear() { temp = top; while (temp != NULL) { top = top->next; delete temp; temp = top; } } string stack::read(int index) { if (index >= 0 && index <= MAX_SIZE - 1) { int begin = 0; temp = top; while (temp != NULL) { if (begin == index) { return temp->cmd; break; } begin++; temp = temp->next; } } else { cout << "\nINDEX OUT OF STACK RANGE\n"; return NULL; } } void stack::push(const string& _CMD) { temp = new node; if (temp == NULL) { cout << "\nERROR : stack > push > temp receives NULL value\n"; return; } temp->cmd = _CMD; temp->next = top; top = temp; }<commit_msg>Update stack.cpp<commit_after>#include "stack.h" #include<string> #include<iostream> using namespace std; //Not using STL at the moment, because uhm NIH syndrome node::node() { cmd = " "; next = NULL; } stack::stack() { top = NULL; temp = NULL; } void stack::pop() { temp = top; if (temp == NULL) return; top = top->next; delete temp; } int stack::isEmpty() { return (top == NULL) ? 1 : 0; } void stack::clear() { temp = top; while (temp != NULL) { top = top->next; delete temp; temp = top; } } string stack::read(int index) { if (index >= 0 && index <= MAX_SIZE - 1) { int begin = 0; temp = top; while (temp != NULL) { if (begin == index) { return temp->cmd; break; } begin++; temp = temp->next; } } else { cout << "\nINDEX OUT OF STACK RANGE\n"; return NULL; } } void stack::push(const string& _CMD) { temp = new node; if (temp == NULL) { cout << "\nERROR : stack > push > temp receives NULL value\n"; return; } temp->cmd = _CMD; temp->next = top; top = temp; } <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/platform_window/x11/x11_window.h" #include <X11/extensions/XInput2.h> #include <X11/Xatom.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include "ui/events/event.h" #include "ui/events/event_utils.h" #include "ui/events/platform/platform_event_dispatcher.h" #include "ui/events/platform/platform_event_source.h" #include "ui/events/platform/x11/x11_event_source.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/x11_types.h" #include "ui/platform_window/platform_window_delegate.h" namespace ui { namespace { const char* kAtomsToCache[] = { "WM_DELETE_WINDOW", "_NET_WM_PING", "_NET_WM_PID", NULL }; XID FindXEventTarget(XEvent* xevent) { XID target = xevent->xany.window; if (xevent->type == GenericEvent) target = static_cast<XIDeviceEvent*>(xevent->xcookie.data)->event; return target; } } // namespace X11Window::X11Window(PlatformWindowDelegate* delegate) : delegate_(delegate), xdisplay_(gfx::GetXDisplay()), xwindow_(None), xroot_window_(DefaultRootWindow(xdisplay_)), atom_cache_(xdisplay_, kAtomsToCache), window_mapped_(false) { CHECK(delegate_); } X11Window::~X11Window() { Destroy(); } void X11Window::Destroy() { if (xwindow_ == None) return; // Stop processing events. PlatformEventSource::GetInstance()->RemovePlatformEventDispatcher(this); XDestroyWindow(xdisplay_, xwindow_); xwindow_ = None; } void X11Window::Show() { if (window_mapped_) return; CHECK(PlatformEventSource::GetInstance()); PlatformEventSource::GetInstance()->AddPlatformEventDispatcher(this); XSetWindowAttributes swa; memset(&swa, 0, sizeof(swa)); swa.background_pixmap = None; swa.override_redirect = False; xwindow_ = XCreateWindow(xdisplay_, xroot_window_, requested_bounds_.x(), requested_bounds_.y(), requested_bounds_.width(), requested_bounds_.height(), 0, // border width CopyFromParent, // depth InputOutput, CopyFromParent, // visual CWBackPixmap | CWOverrideRedirect, &swa); long event_mask = ButtonPressMask | ButtonReleaseMask | FocusChangeMask | KeyPressMask | KeyReleaseMask | EnterWindowMask | LeaveWindowMask | ExposureMask | VisibilityChangeMask | StructureNotifyMask | PropertyChangeMask | PointerMotionMask; XSelectInput(xdisplay_, xwindow_, event_mask); unsigned char mask[XIMaskLen(XI_LASTEVENT)]; memset(mask, 0, sizeof(mask)); XISetMask(mask, XI_TouchBegin); XISetMask(mask, XI_TouchUpdate); XISetMask(mask, XI_TouchEnd); XISetMask(mask, XI_ButtonPress); XISetMask(mask, XI_ButtonRelease); XISetMask(mask, XI_Motion); XIEventMask evmask; evmask.deviceid = XIAllDevices; evmask.mask_len = sizeof(mask); evmask.mask = mask; XISelectEvents(xdisplay_, xwindow_, &evmask, 1); XFlush(xdisplay_); ::Atom protocols[2]; protocols[0] = atom_cache_.GetAtom("WM_DELETE_WINDOW"); protocols[1] = atom_cache_.GetAtom("_NET_WM_PING"); XSetWMProtocols(xdisplay_, xwindow_, protocols, 2); // We need a WM_CLIENT_MACHINE and WM_LOCALE_NAME value so we integrate with // the desktop environment. XSetWMProperties( xdisplay_, xwindow_, NULL, NULL, NULL, 0, NULL, NULL, NULL); // Likewise, the X server needs to know this window's pid so it knows which // program to kill if the window hangs. // XChangeProperty() expects "pid" to be long. COMPILE_ASSERT(sizeof(long) >= sizeof(pid_t), pid_t_bigger_than_long); long pid = getpid(); XChangeProperty(xdisplay_, xwindow_, atom_cache_.GetAtom("_NET_WM_PID"), XA_CARDINAL, 32, PropModeReplace, reinterpret_cast<unsigned char*>(&pid), 1); // Before we map the window, set size hints. Otherwise, some window managers // will ignore toplevel XMoveWindow commands. XSizeHints size_hints; size_hints.flags = PPosition | PWinGravity; size_hints.x = requested_bounds_.x(); size_hints.y = requested_bounds_.y(); // Set StaticGravity so that the window position is not affected by the // frame width when running with window manager. size_hints.win_gravity = StaticGravity; XSetWMNormalHints(xdisplay_, xwindow_, &size_hints); delegate_->OnAcceleratedWidgetAvailable(xwindow_); XMapWindow(xdisplay_, xwindow_); // We now block until our window is mapped. Some X11 APIs will crash and // burn if passed |xwindow_| before the window is mapped, and XMapWindow is // asynchronous. if (X11EventSource::GetInstance()) X11EventSource::GetInstance()->BlockUntilWindowMapped(xwindow_); window_mapped_ = true; } void X11Window::Hide() { if (!window_mapped_) return; XWithdrawWindow(xdisplay_, xwindow_, 0); window_mapped_ = false; } void X11Window::Close() { Destroy(); } void X11Window::SetBounds(const gfx::Rect& bounds) { requested_bounds_ = bounds; if (!window_mapped_) return; XWindowChanges changes = {0}; unsigned value_mask = CWX | CWY | CWWidth | CWHeight; changes.x = bounds.x(); changes.y = bounds.y(); changes.width = bounds.width(); changes.height = bounds.height(); XConfigureWindow(xdisplay_, xwindow_, value_mask, &changes); } gfx::Rect X11Window::GetBounds() { return confirmed_bounds_; } void X11Window::SetCapture() {} void X11Window::ReleaseCapture() {} void X11Window::ToggleFullscreen() {} void X11Window::Maximize() {} void X11Window::Minimize() {} void X11Window::Restore() {} bool X11Window::CanDispatchEvent(const PlatformEvent& event) { return FindXEventTarget(event) == xwindow_; } uint32_t X11Window::DispatchEvent(const PlatformEvent& event) { XEvent* xev = event; switch (xev->type) { case EnterNotify: { // EnterNotify creates ET_MOUSE_MOVED. Mark as synthesized as this is // not real mouse move event. MouseEvent mouse_event(xev); CHECK_EQ(ET_MOUSE_MOVED, mouse_event.type()); mouse_event.set_flags(mouse_event.flags() | EF_IS_SYNTHESIZED); delegate_->DispatchEvent(&mouse_event); break; } case LeaveNotify: { MouseEvent mouse_event(xev); delegate_->DispatchEvent(&mouse_event); break; } case Expose: { gfx::Rect damage_rect(xev->xexpose.x, xev->xexpose.y, xev->xexpose.width, xev->xexpose.height); delegate_->OnDamageRect(damage_rect); break; } case KeyPress: case KeyRelease: { KeyEvent key_event(xev, false); delegate_->DispatchEvent(&key_event); break; } case ButtonPress: case ButtonRelease: { switch (EventTypeFromNative(xev)) { case ET_MOUSEWHEEL: { MouseWheelEvent mouseev(xev); delegate_->DispatchEvent(&mouseev); break; } case ET_MOUSE_PRESSED: case ET_MOUSE_RELEASED: { MouseEvent mouseev(xev); delegate_->DispatchEvent(&mouseev); break; } case ET_UNKNOWN: // No event is created for X11-release events for mouse-wheel // buttons. break; default: NOTREACHED(); } break; } case FocusOut: if (xev->xfocus.mode != NotifyGrab) delegate_->OnLostCapture(); break; case ConfigureNotify: { DCHECK_EQ(xwindow_, xev->xconfigure.event); DCHECK_EQ(xwindow_, xev->xconfigure.window); gfx::Rect bounds(xev->xconfigure.x, xev->xconfigure.y, xev->xconfigure.width, xev->xconfigure.height); if (confirmed_bounds_ != bounds) { confirmed_bounds_ = bounds; delegate_->OnBoundsChanged(confirmed_bounds_); } break; } case ClientMessage: { Atom message = static_cast<Atom>(xev->xclient.data.l[0]); if (message == atom_cache_.GetAtom("WM_DELETE_WINDOW")) { delegate_->OnCloseRequest(); } else if (message == atom_cache_.GetAtom("_NET_WM_PING")) { XEvent reply_event = *xev; reply_event.xclient.window = xroot_window_; XSendEvent(xdisplay_, reply_event.xclient.window, False, SubstructureRedirectMask | SubstructureNotifyMask, &reply_event); XFlush(xdisplay_); } break; } } return POST_DISPATCH_STOP_PROPAGATION; } } // namespace ui <commit_msg>x11: Do not listen for XI2 mouse events for X11Window.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/platform_window/x11/x11_window.h" #include <X11/extensions/XInput2.h> #include <X11/Xatom.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include "ui/events/event.h" #include "ui/events/event_utils.h" #include "ui/events/platform/platform_event_dispatcher.h" #include "ui/events/platform/platform_event_source.h" #include "ui/events/platform/x11/x11_event_source.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/x11_types.h" #include "ui/platform_window/platform_window_delegate.h" namespace ui { namespace { const char* kAtomsToCache[] = { "WM_DELETE_WINDOW", "_NET_WM_PING", "_NET_WM_PID", NULL }; XID FindXEventTarget(XEvent* xevent) { XID target = xevent->xany.window; if (xevent->type == GenericEvent) target = static_cast<XIDeviceEvent*>(xevent->xcookie.data)->event; return target; } } // namespace X11Window::X11Window(PlatformWindowDelegate* delegate) : delegate_(delegate), xdisplay_(gfx::GetXDisplay()), xwindow_(None), xroot_window_(DefaultRootWindow(xdisplay_)), atom_cache_(xdisplay_, kAtomsToCache), window_mapped_(false) { CHECK(delegate_); } X11Window::~X11Window() { Destroy(); } void X11Window::Destroy() { if (xwindow_ == None) return; // Stop processing events. PlatformEventSource::GetInstance()->RemovePlatformEventDispatcher(this); XDestroyWindow(xdisplay_, xwindow_); xwindow_ = None; } void X11Window::Show() { if (window_mapped_) return; CHECK(PlatformEventSource::GetInstance()); PlatformEventSource::GetInstance()->AddPlatformEventDispatcher(this); XSetWindowAttributes swa; memset(&swa, 0, sizeof(swa)); swa.background_pixmap = None; swa.override_redirect = False; xwindow_ = XCreateWindow(xdisplay_, xroot_window_, requested_bounds_.x(), requested_bounds_.y(), requested_bounds_.width(), requested_bounds_.height(), 0, // border width CopyFromParent, // depth InputOutput, CopyFromParent, // visual CWBackPixmap | CWOverrideRedirect, &swa); long event_mask = ButtonPressMask | ButtonReleaseMask | FocusChangeMask | KeyPressMask | KeyReleaseMask | EnterWindowMask | LeaveWindowMask | ExposureMask | VisibilityChangeMask | StructureNotifyMask | PropertyChangeMask | PointerMotionMask; XSelectInput(xdisplay_, xwindow_, event_mask); unsigned char mask[XIMaskLen(XI_LASTEVENT)]; memset(mask, 0, sizeof(mask)); XISetMask(mask, XI_TouchBegin); XISetMask(mask, XI_TouchUpdate); XISetMask(mask, XI_TouchEnd); XIEventMask evmask; evmask.deviceid = XIAllDevices; evmask.mask_len = sizeof(mask); evmask.mask = mask; XISelectEvents(xdisplay_, xwindow_, &evmask, 1); XFlush(xdisplay_); ::Atom protocols[2]; protocols[0] = atom_cache_.GetAtom("WM_DELETE_WINDOW"); protocols[1] = atom_cache_.GetAtom("_NET_WM_PING"); XSetWMProtocols(xdisplay_, xwindow_, protocols, 2); // We need a WM_CLIENT_MACHINE and WM_LOCALE_NAME value so we integrate with // the desktop environment. XSetWMProperties( xdisplay_, xwindow_, NULL, NULL, NULL, 0, NULL, NULL, NULL); // Likewise, the X server needs to know this window's pid so it knows which // program to kill if the window hangs. // XChangeProperty() expects "pid" to be long. COMPILE_ASSERT(sizeof(long) >= sizeof(pid_t), pid_t_bigger_than_long); long pid = getpid(); XChangeProperty(xdisplay_, xwindow_, atom_cache_.GetAtom("_NET_WM_PID"), XA_CARDINAL, 32, PropModeReplace, reinterpret_cast<unsigned char*>(&pid), 1); // Before we map the window, set size hints. Otherwise, some window managers // will ignore toplevel XMoveWindow commands. XSizeHints size_hints; size_hints.flags = PPosition | PWinGravity; size_hints.x = requested_bounds_.x(); size_hints.y = requested_bounds_.y(); // Set StaticGravity so that the window position is not affected by the // frame width when running with window manager. size_hints.win_gravity = StaticGravity; XSetWMNormalHints(xdisplay_, xwindow_, &size_hints); delegate_->OnAcceleratedWidgetAvailable(xwindow_); XMapWindow(xdisplay_, xwindow_); // We now block until our window is mapped. Some X11 APIs will crash and // burn if passed |xwindow_| before the window is mapped, and XMapWindow is // asynchronous. if (X11EventSource::GetInstance()) X11EventSource::GetInstance()->BlockUntilWindowMapped(xwindow_); window_mapped_ = true; } void X11Window::Hide() { if (!window_mapped_) return; XWithdrawWindow(xdisplay_, xwindow_, 0); window_mapped_ = false; } void X11Window::Close() { Destroy(); } void X11Window::SetBounds(const gfx::Rect& bounds) { requested_bounds_ = bounds; if (!window_mapped_) return; XWindowChanges changes = {0}; unsigned value_mask = CWX | CWY | CWWidth | CWHeight; changes.x = bounds.x(); changes.y = bounds.y(); changes.width = bounds.width(); changes.height = bounds.height(); XConfigureWindow(xdisplay_, xwindow_, value_mask, &changes); } gfx::Rect X11Window::GetBounds() { return confirmed_bounds_; } void X11Window::SetCapture() {} void X11Window::ReleaseCapture() {} void X11Window::ToggleFullscreen() {} void X11Window::Maximize() {} void X11Window::Minimize() {} void X11Window::Restore() {} bool X11Window::CanDispatchEvent(const PlatformEvent& event) { return FindXEventTarget(event) == xwindow_; } uint32_t X11Window::DispatchEvent(const PlatformEvent& event) { XEvent* xev = event; switch (xev->type) { case EnterNotify: { // EnterNotify creates ET_MOUSE_MOVED. Mark as synthesized as this is // not real mouse move event. MouseEvent mouse_event(xev); CHECK_EQ(ET_MOUSE_MOVED, mouse_event.type()); mouse_event.set_flags(mouse_event.flags() | EF_IS_SYNTHESIZED); delegate_->DispatchEvent(&mouse_event); break; } case LeaveNotify: { MouseEvent mouse_event(xev); delegate_->DispatchEvent(&mouse_event); break; } case Expose: { gfx::Rect damage_rect(xev->xexpose.x, xev->xexpose.y, xev->xexpose.width, xev->xexpose.height); delegate_->OnDamageRect(damage_rect); break; } case KeyPress: case KeyRelease: { KeyEvent key_event(xev, false); delegate_->DispatchEvent(&key_event); break; } case ButtonPress: case ButtonRelease: { switch (EventTypeFromNative(xev)) { case ET_MOUSEWHEEL: { MouseWheelEvent mouseev(xev); delegate_->DispatchEvent(&mouseev); break; } case ET_MOUSE_PRESSED: case ET_MOUSE_RELEASED: { MouseEvent mouseev(xev); delegate_->DispatchEvent(&mouseev); break; } case ET_UNKNOWN: // No event is created for X11-release events for mouse-wheel // buttons. break; default: NOTREACHED(); } break; } case FocusOut: if (xev->xfocus.mode != NotifyGrab) delegate_->OnLostCapture(); break; case ConfigureNotify: { DCHECK_EQ(xwindow_, xev->xconfigure.event); DCHECK_EQ(xwindow_, xev->xconfigure.window); gfx::Rect bounds(xev->xconfigure.x, xev->xconfigure.y, xev->xconfigure.width, xev->xconfigure.height); if (confirmed_bounds_ != bounds) { confirmed_bounds_ = bounds; delegate_->OnBoundsChanged(confirmed_bounds_); } break; } case ClientMessage: { Atom message = static_cast<Atom>(xev->xclient.data.l[0]); if (message == atom_cache_.GetAtom("WM_DELETE_WINDOW")) { delegate_->OnCloseRequest(); } else if (message == atom_cache_.GetAtom("_NET_WM_PING")) { XEvent reply_event = *xev; reply_event.xclient.window = xroot_window_; XSendEvent(xdisplay_, reply_event.xclient.window, False, SubstructureRedirectMask | SubstructureNotifyMask, &reply_event); XFlush(xdisplay_); } break; } } return POST_DISPATCH_STOP_PROPAGATION; } } // namespace ui <|endoftext|>
<commit_before>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Clifford Wolf <clifford@clifford.at> * Copyright (C) 2018 David Shah <dave@ds0.me> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "bitstream.h" #include <vector> inline TileType tile_at(const Chip &chip, int x, int y) { return chip.chip_info.tile_grid[y * chip.chip_info.width + x]; } const ConfigEntryPOD &find_config(const TileInfoPOD &tile, const std::string &name) { for (int i = 0; i < tile.num_config_entries; i++) { if (std::string(tile.entries[i].name) == name) { return tile.entries[i]; } } assert(false); } std::tuple<int8_t, int8_t, int8_t> get_ieren(const BitstreamInfoPOD &bi, int8_t x, int8_t y, int8_t z) { for (int i = 0; i < bi.num_ierens; i++) { auto ie = bi.ierens[i]; if (ie.iox == x && ie.ioy == y && ie.ioz == z) { return std::make_tuple(ie.ierx, ie.iery, ie.ierz); } } // No pin at this location return std::make_tuple(-1, -1, -1); }; void set_config(const TileInfoPOD &ti, vector<vector<int8_t>> &tile_cfg, const std::string &name, bool value, int index = -1) { const ConfigEntryPOD &cfg = find_config(ti, name); if (index == -1) { for (int i = 0; i < cfg.num_bits; i++) { int8_t &cbit = tile_cfg.at(cfg.bits[i].row).at(cfg.bits[i].col); cbit = value; } } else { int8_t &cbit = tile_cfg.at(cfg.bits[index].row).at(cfg.bits[index].col); cbit = value; } } void write_asc(const Design &design, std::ostream &out) { const Chip &chip = design.chip; // [y][x][row][col] const ChipInfoPOD &ci = chip.chip_info; const BitstreamInfoPOD &bi = *ci.bits_info; std::vector<std::vector<std::vector<std::vector<int8_t>>>> config; config.resize(ci.height); for (int y = 0; y < ci.height; y++) { config.at(y).resize(ci.width); for (int x = 0; x < ci.width; x++) { TileType tile = tile_at(chip, x, y); int rows = bi.tiles_nonrouting[tile].rows; int cols = bi.tiles_nonrouting[tile].cols; config.at(y).at(x).resize(rows, vector<int8_t>(cols)); } } out << ".comment from next-pnr" << std::endl; switch (chip.args.type) { case ChipArgs::LP384: out << ".device 384" << std::endl; break; case ChipArgs::HX1K: case ChipArgs::LP1K: out << ".device 1k" << std::endl; break; case ChipArgs::HX8K: case ChipArgs::LP8K: out << ".device 8k" << std::endl; break; case ChipArgs::UP5K: out << ".device 5k" << std::endl; break; default: assert(false); } // Set pips for (auto pip : chip.getPips()) { if (chip.pip_to_net[pip.index] != IdString()) { const PipInfoPOD &pi = ci.pip_data[pip.index]; const SwitchInfoPOD &swi = bi.switches[pi.switch_index]; for (int i = 0; i < swi.num_bits; i++) { bool val = (pi.switch_mask & (1 << ((swi.num_bits - 1) - i))) != 0; int8_t &cbit = config.at(swi.y) .at(swi.x) .at(swi.cbits[i].row) .at(swi.cbits[i].col); if (bool(cbit) != 0) assert(false); cbit = val; } } } // Set logic cell config for (auto cell : design.cells) { BelId bel = cell.second->bel; if (bel == BelId()) { std::cout << "Found unplaced cell " << cell.first << " while generating bitstream!" << std::endl; continue; } const BelInfoPOD &beli = ci.bel_data[bel.index]; int x = beli.x, y = beli.y, z = beli.z; if (cell.second->type == "ICESTORM_LC") { TileInfoPOD &ti = bi.tiles_nonrouting[TILE_LOGIC]; unsigned lut_init = std::stoi(cell.second->params["LUT_INIT"]); bool neg_clk = std::stoi(cell.second->params["NEG_CLK"]); bool dff_enable = std::stoi(cell.second->params["DFF_ENABLE"]); bool async_sr = std::stoi(cell.second->params["ASYNC_SR"]); bool set_noreset = std::stoi(cell.second->params["SET_NORESET"]); bool carry_enable = std::stoi(cell.second->params["CARRY_ENABLE"]); vector<bool> lc(20, false); // From arachne-pnr static std::vector<int> lut_perm = { 4, 14, 15, 5, 6, 16, 17, 7, 3, 13, 12, 2, 1, 11, 10, 0, }; for (int i = 0; i < 16; i++) { if ((lut_init >> i) & 0x1) lc.at(lut_perm.at(i)) = true; } lc.at(8) = carry_enable; lc.at(9) = dff_enable; lc.at(18) = set_noreset; lc.at(19) = async_sr; for (int i = 0; i < 20; i++) set_config(ti, config.at(y).at(x), "LC_" + std::to_string(z), lc.at(i), i); set_config(ti, config.at(y).at(x), "NegClk", neg_clk); } else if (cell.second->type == "SB_IO") { TileInfoPOD &ti = bi.tiles_nonrouting[TILE_IO]; unsigned pin_type = std::stoi(cell.second->params["PIN_TYPE"]); bool neg_trigger = std::stoi(cell.second->params["NEG_TRIGGER"]); bool pullup = std::stoi(cell.second->params["PULLUP"]); for (int i = 0; i < 6; i++) { bool val = (pin_type >> i) & 0x01; set_config(ti, config.at(y).at(x), "IOB_" + std::to_string(z) + ".PINTYPE_" + std::to_string(i), val); } auto ieren = get_ieren(bi, x, y, z); int iex, iey, iez; std::tie(iex, iey, iez) = ieren; assert(iez != -1); bool input_en = false; if ((chip.wire_to_net[chip.getWireBelPin(bel, PIN_D_IN_0).index] != IdString()) || (chip.wire_to_net[chip.getWireBelPin(bel, PIN_D_IN_1).index] != IdString())) { input_en = true; } set_config(ti, config.at(iey).at(iex), "IoCtrl.IE_" + std::to_string(iez), !input_en); set_config(ti, config.at(iey).at(iex), "IoCtrl.REN_" + std::to_string(iez), !pullup); } else { assert(false); } } // Set other config bits - currently just disable RAM to stop icebox_vlog // crashing // TODO: ColBufCtrl , unused IO for (int y = 0; y < ci.height; y++) { for (int x = 0; x < ci.width; x++) { TileType tile = tile_at(chip, x, y); TileInfoPOD &ti = bi.tiles_nonrouting[tile]; if (tile == TILE_RAMB) { set_config(ti, config.at(y).at(x), "RamConfig.PowerUp", true); } } } // Write config out for (int y = 0; y < ci.height; y++) { for (int x = 0; x < ci.width; x++) { TileType tile = tile_at(chip, x, y); if (tile == TILE_NONE) continue; switch (tile) { case TILE_LOGIC: out << ".logic_tile"; break; case TILE_IO: out << ".io_tile"; break; case TILE_RAMB: out << ".ramb_tile"; break; case TILE_RAMT: out << ".ramt_tile"; break; default: assert(false); } out << " " << x << " " << y << std::endl; for (auto row : config.at(y).at(x)) { for (auto col : row) { if (col == 1) out << "1"; else out << "0"; } out << std::endl; } out << std::endl; } } } <commit_msg>ice40: Set config bits for unused IO<commit_after>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Clifford Wolf <clifford@clifford.at> * Copyright (C) 2018 David Shah <dave@ds0.me> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "bitstream.h" #include <vector> inline TileType tile_at(const Chip &chip, int x, int y) { return chip.chip_info.tile_grid[y * chip.chip_info.width + x]; } const ConfigEntryPOD &find_config(const TileInfoPOD &tile, const std::string &name) { for (int i = 0; i < tile.num_config_entries; i++) { if (std::string(tile.entries[i].name) == name) { return tile.entries[i]; } } assert(false); } std::tuple<int8_t, int8_t, int8_t> get_ieren(const BitstreamInfoPOD &bi, int8_t x, int8_t y, int8_t z) { for (int i = 0; i < bi.num_ierens; i++) { auto ie = bi.ierens[i]; if (ie.iox == x && ie.ioy == y && ie.ioz == z) { return std::make_tuple(ie.ierx, ie.iery, ie.ierz); } } // No pin at this location return std::make_tuple(-1, -1, -1); }; void set_config(const TileInfoPOD &ti, vector<vector<int8_t>> &tile_cfg, const std::string &name, bool value, int index = -1) { const ConfigEntryPOD &cfg = find_config(ti, name); if (index == -1) { for (int i = 0; i < cfg.num_bits; i++) { int8_t &cbit = tile_cfg.at(cfg.bits[i].row).at(cfg.bits[i].col); cbit = value; } } else { int8_t &cbit = tile_cfg.at(cfg.bits[index].row).at(cfg.bits[index].col); cbit = value; } } void write_asc(const Design &design, std::ostream &out) { const Chip &chip = design.chip; // [y][x][row][col] const ChipInfoPOD &ci = chip.chip_info; const BitstreamInfoPOD &bi = *ci.bits_info; std::vector<std::vector<std::vector<std::vector<int8_t>>>> config; config.resize(ci.height); for (int y = 0; y < ci.height; y++) { config.at(y).resize(ci.width); for (int x = 0; x < ci.width; x++) { TileType tile = tile_at(chip, x, y); int rows = bi.tiles_nonrouting[tile].rows; int cols = bi.tiles_nonrouting[tile].cols; config.at(y).at(x).resize(rows, vector<int8_t>(cols)); } } out << ".comment from next-pnr" << std::endl; switch (chip.args.type) { case ChipArgs::LP384: out << ".device 384" << std::endl; break; case ChipArgs::HX1K: case ChipArgs::LP1K: out << ".device 1k" << std::endl; break; case ChipArgs::HX8K: case ChipArgs::LP8K: out << ".device 8k" << std::endl; break; case ChipArgs::UP5K: out << ".device 5k" << std::endl; break; default: assert(false); } // Set pips for (auto pip : chip.getPips()) { if (chip.pip_to_net[pip.index] != IdString()) { const PipInfoPOD &pi = ci.pip_data[pip.index]; const SwitchInfoPOD &swi = bi.switches[pi.switch_index]; for (int i = 0; i < swi.num_bits; i++) { bool val = (pi.switch_mask & (1 << ((swi.num_bits - 1) - i))) != 0; int8_t &cbit = config.at(swi.y) .at(swi.x) .at(swi.cbits[i].row) .at(swi.cbits[i].col); if (bool(cbit) != 0) assert(false); cbit = val; } } } // Set logic cell config for (auto cell : design.cells) { BelId bel = cell.second->bel; if (bel == BelId()) { std::cout << "Found unplaced cell " << cell.first << " while generating bitstream!" << std::endl; continue; } const BelInfoPOD &beli = ci.bel_data[bel.index]; int x = beli.x, y = beli.y, z = beli.z; if (cell.second->type == "ICESTORM_LC") { TileInfoPOD &ti = bi.tiles_nonrouting[TILE_LOGIC]; unsigned lut_init = std::stoi(cell.second->params["LUT_INIT"]); bool neg_clk = std::stoi(cell.second->params["NEG_CLK"]); bool dff_enable = std::stoi(cell.second->params["DFF_ENABLE"]); bool async_sr = std::stoi(cell.second->params["ASYNC_SR"]); bool set_noreset = std::stoi(cell.second->params["SET_NORESET"]); bool carry_enable = std::stoi(cell.second->params["CARRY_ENABLE"]); vector<bool> lc(20, false); // From arachne-pnr static std::vector<int> lut_perm = { 4, 14, 15, 5, 6, 16, 17, 7, 3, 13, 12, 2, 1, 11, 10, 0, }; for (int i = 0; i < 16; i++) { if ((lut_init >> i) & 0x1) lc.at(lut_perm.at(i)) = true; } lc.at(8) = carry_enable; lc.at(9) = dff_enable; lc.at(18) = set_noreset; lc.at(19) = async_sr; for (int i = 0; i < 20; i++) set_config(ti, config.at(y).at(x), "LC_" + std::to_string(z), lc.at(i), i); set_config(ti, config.at(y).at(x), "NegClk", neg_clk); } else if (cell.second->type == "SB_IO") { TileInfoPOD &ti = bi.tiles_nonrouting[TILE_IO]; unsigned pin_type = std::stoi(cell.second->params["PIN_TYPE"]); bool neg_trigger = std::stoi(cell.second->params["NEG_TRIGGER"]); bool pullup = std::stoi(cell.second->params["PULLUP"]); for (int i = 0; i < 6; i++) { bool val = (pin_type >> i) & 0x01; set_config(ti, config.at(y).at(x), "IOB_" + std::to_string(z) + ".PINTYPE_" + std::to_string(i), val); } auto ieren = get_ieren(bi, x, y, z); int iex, iey, iez; std::tie(iex, iey, iez) = ieren; assert(iez != -1); bool input_en = false; if ((chip.wire_to_net[chip.getWireBelPin(bel, PIN_D_IN_0).index] != IdString()) || (chip.wire_to_net[chip.getWireBelPin(bel, PIN_D_IN_1).index] != IdString())) { input_en = true; } set_config(ti, config.at(iey).at(iex), "IoCtrl.IE_" + std::to_string(iez), !input_en); set_config(ti, config.at(iey).at(iex), "IoCtrl.REN_" + std::to_string(iez), !pullup); } else { assert(false); } } // Set config bits in unused IO for (auto bel : chip.getBels()) { if (chip.bel_to_cell[bel.index] == IdString() && chip.getBelType(bel) == TYPE_SB_IO) { TileInfoPOD &ti = bi.tiles_nonrouting[TILE_IO]; const BelInfoPOD &beli = ci.bel_data[bel.index]; int x = beli.x, y = beli.y, z = beli.z; auto ieren = get_ieren(bi, x, y, z); int iex, iey, iez; std::tie(iex, iey, iez) = ieren; if (iez != -1) { set_config(ti, config.at(iey).at(iex), "IoCtrl.IE_" + std::to_string(iez), true); set_config(ti, config.at(iey).at(iex), "IoCtrl.REN_" + std::to_string(iez), false); } } } // Set other config bits - currently just disable RAM to stop icebox_vlog // crashing // TODO: ColBufCtrl for (int y = 0; y < ci.height; y++) { for (int x = 0; x < ci.width; x++) { TileType tile = tile_at(chip, x, y); TileInfoPOD &ti = bi.tiles_nonrouting[tile]; if (tile == TILE_RAMB) { set_config(ti, config.at(y).at(x), "RamConfig.PowerUp", true); } } } // Write config out for (int y = 0; y < ci.height; y++) { for (int x = 0; x < ci.width; x++) { TileType tile = tile_at(chip, x, y); if (tile == TILE_NONE) continue; switch (tile) { case TILE_LOGIC: out << ".logic_tile"; break; case TILE_IO: out << ".io_tile"; break; case TILE_RAMB: out << ".ramb_tile"; break; case TILE_RAMT: out << ".ramt_tile"; break; default: assert(false); } out << " " << x << " " << y << std::endl; for (auto row : config.at(y).at(x)) { for (auto col : row) { if (col == 1) out << "1"; else out << "0"; } out << std::endl; } out << std::endl; } } } <|endoftext|>
<commit_before>// Copyright 2010 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 "utils/datetime.hpp" extern "C" { #include <time.h> } #include <atf-c++.hpp> namespace datetime = utils::datetime; ATF_TEST_CASE_WITHOUT_HEAD(delta__defaults); ATF_TEST_CASE_BODY(delta__defaults) { const datetime::delta delta; ATF_REQUIRE_EQ(0, delta.seconds); ATF_REQUIRE_EQ(0, delta.useconds); } ATF_TEST_CASE_WITHOUT_HEAD(delta__overrides); ATF_TEST_CASE_BODY(delta__overrides) { const datetime::delta delta(1, 2); ATF_REQUIRE_EQ(1, delta.seconds); ATF_REQUIRE_EQ(2, delta.useconds); } ATF_TEST_CASE_WITHOUT_HEAD(delta__from_useconds); ATF_TEST_CASE_BODY(delta__from_useconds) { { const datetime::delta delta = datetime::delta::from_useconds(0); ATF_REQUIRE_EQ(0, delta.seconds); ATF_REQUIRE_EQ(0, delta.useconds); } { const datetime::delta delta = datetime::delta::from_useconds(999999); ATF_REQUIRE_EQ(0, delta.seconds); ATF_REQUIRE_EQ(999999, delta.useconds); } { const datetime::delta delta = datetime::delta::from_useconds(1000000); ATF_REQUIRE_EQ(1, delta.seconds); ATF_REQUIRE_EQ(0, delta.useconds); } { const datetime::delta delta = datetime::delta::from_useconds(10576293); ATF_REQUIRE_EQ(10, delta.seconds); ATF_REQUIRE_EQ(576293, delta.useconds); } } ATF_TEST_CASE_WITHOUT_HEAD(delta__to_useconds); ATF_TEST_CASE_BODY(delta__to_useconds) { ATF_REQUIRE_EQ(0, datetime::delta(0, 0).to_useconds()); ATF_REQUIRE_EQ(999999, datetime::delta(0, 999999).to_useconds()); ATF_REQUIRE_EQ(1000000, datetime::delta(1, 0).to_useconds()); ATF_REQUIRE_EQ(10576293, datetime::delta(10, 576293).to_useconds()); ATF_REQUIRE_EQ(11576293, datetime::delta(10, 1576293).to_useconds()); } ATF_TEST_CASE_WITHOUT_HEAD(delta__equals); ATF_TEST_CASE_BODY(delta__equals) { ATF_REQUIRE(datetime::delta() == datetime::delta()); ATF_REQUIRE(datetime::delta() == datetime::delta(0, 0)); ATF_REQUIRE(datetime::delta(1, 2) == datetime::delta(1, 2)); ATF_REQUIRE(!(datetime::delta() == datetime::delta(0, 1))); ATF_REQUIRE(!(datetime::delta() == datetime::delta(1, 0))); ATF_REQUIRE(!(datetime::delta(1, 2) == datetime::delta(2, 1))); } ATF_TEST_CASE_WITHOUT_HEAD(delta__differs); ATF_TEST_CASE_BODY(delta__differs) { ATF_REQUIRE(!(datetime::delta() != datetime::delta())); ATF_REQUIRE(!(datetime::delta() != datetime::delta(0, 0))); ATF_REQUIRE(!(datetime::delta(1, 2) != datetime::delta(1, 2))); ATF_REQUIRE(datetime::delta() != datetime::delta(0, 1)); ATF_REQUIRE(datetime::delta() != datetime::delta(1, 0)); ATF_REQUIRE(datetime::delta(1, 2) != datetime::delta(2, 1)); } ATF_TEST_CASE_WITHOUT_HEAD(delta__addition); ATF_TEST_CASE_BODY(delta__addition) { using datetime::delta; ATF_REQUIRE(delta() == delta() + delta()); ATF_REQUIRE(delta(0, 10) == delta() + delta(0, 10)); ATF_REQUIRE(delta(10, 0) == delta(10, 0) + delta()); ATF_REQUIRE(delta(1, 234567) == delta(0, 1234567) + delta()); ATF_REQUIRE(delta(12, 34) == delta(10, 20) + delta(2, 14)); } ATF_TEST_CASE_WITHOUT_HEAD(delta__addition_and_set); ATF_TEST_CASE_BODY(delta__addition_and_set) { using datetime::delta; { delta d; d += delta(3, 5); ATF_REQUIRE(delta(3, 5) == d); } { delta d(1, 2); d += delta(3, 5); ATF_REQUIRE(delta(4, 7) == d); } { delta d(1, 2); ATF_REQUIRE(delta(4, 7) == (d += delta(3, 5))); } } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__copy); ATF_TEST_CASE_BODY(timestamp__copy) { const datetime::timestamp ts1 = datetime::timestamp::from_values( 2011, 2, 16, 19, 15, 30, 0); { const datetime::timestamp ts2 = ts1; const datetime::timestamp ts3 = datetime::timestamp::from_values( 2012, 2, 16, 19, 15, 30, 0); ATF_REQUIRE_EQ("2011", ts1.strftime("%Y")); ATF_REQUIRE_EQ("2011", ts2.strftime("%Y")); ATF_REQUIRE_EQ("2012", ts3.strftime("%Y")); } ATF_REQUIRE_EQ("2011", ts1.strftime("%Y")); } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__from_microseconds); ATF_TEST_CASE_BODY(timestamp__from_microseconds) { const datetime::timestamp ts = datetime::timestamp::from_microseconds( 1328829351987654); ATF_REQUIRE_EQ("2012-02-09 23:15:51", ts.strftime("%Y-%m-%d %H:%M:%S")); ATF_REQUIRE_EQ(1328829351987654, ts.to_microseconds()); ATF_REQUIRE_EQ(1328829351, ts.to_seconds()); } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__now__mock); ATF_TEST_CASE_BODY(timestamp__now__mock) { datetime::set_mock_now(2011, 2, 21, 18, 5, 10, 0); ATF_REQUIRE_EQ("2011-02-21 18:05:10", datetime::timestamp::now().strftime("%Y-%m-%d %H:%M:%S")); datetime::set_mock_now(2012, 3, 22, 19, 6, 11, 54321); ATF_REQUIRE_EQ("2012-03-22 19:06:11", datetime::timestamp::now().strftime("%Y-%m-%d %H:%M:%S")); ATF_REQUIRE_EQ("2012-03-22 19:06:11", datetime::timestamp::now().strftime("%Y-%m-%d %H:%M:%S")); } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__now__real); ATF_TEST_CASE_BODY(timestamp__now__real) { // This test is might fail if we happen to run at the crossing of one // day to the other and the two measures we pick of the current time // differ. This is so unlikely that I haven't bothered to do this in any // other way. const time_t just_before = ::time(NULL); const datetime::timestamp now = datetime::timestamp::now(); ::tm data; char buf[1024]; ATF_REQUIRE(::gmtime_r(&just_before, &data) != 0); ATF_REQUIRE(::strftime(buf, sizeof(buf), "%Y-%m-%d", &data) != 0); ATF_REQUIRE_EQ(buf, now.strftime("%Y-%m-%d")); ATF_REQUIRE(now.strftime("%Z") == "GMT" || now.strftime("%Z") == "UTC"); } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__now__granularity); ATF_TEST_CASE_BODY(timestamp__now__granularity) { const datetime::timestamp first = datetime::timestamp::now(); ::usleep(1); const datetime::timestamp second = datetime::timestamp::now(); ATF_REQUIRE(first.to_microseconds() != second.to_microseconds()); } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__strftime); ATF_TEST_CASE_BODY(timestamp__strftime) { const datetime::timestamp ts1 = datetime::timestamp::from_values( 2010, 12, 10, 8, 45, 50, 0); ATF_REQUIRE_EQ("2010-12-10", ts1.strftime("%Y-%m-%d")); ATF_REQUIRE_EQ("08:45:50", ts1.strftime("%H:%M:%S")); const datetime::timestamp ts2 = datetime::timestamp::from_values( 2011, 2, 16, 19, 15, 30, 0); ATF_REQUIRE_EQ("2011-02-16T19:15:30", ts2.strftime("%Y-%m-%dT%H:%M:%S")); } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__to_microseconds); ATF_TEST_CASE_BODY(timestamp__to_microseconds) { const datetime::timestamp ts1 = datetime::timestamp::from_values( 2010, 12, 10, 8, 45, 50, 123456); ATF_REQUIRE_EQ(1291970750123456, ts1.to_microseconds()); } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__to_seconds); ATF_TEST_CASE_BODY(timestamp__to_seconds) { const datetime::timestamp ts1 = datetime::timestamp::from_values( 2010, 12, 10, 8, 45, 50, 123456); ATF_REQUIRE_EQ(1291970750, ts1.to_seconds()); } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__equals); ATF_TEST_CASE_BODY(timestamp__equals) { ATF_REQUIRE(datetime::timestamp::from_microseconds(1291970750123456) == datetime::timestamp::from_microseconds(1291970750123456)); } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__differs); ATF_TEST_CASE_BODY(timestamp__differs) { ATF_REQUIRE(datetime::timestamp::from_microseconds(1291970750123456) != datetime::timestamp::from_microseconds(1291970750123455)); } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__subtraction); ATF_TEST_CASE_BODY(timestamp__subtraction) { const datetime::timestamp ts1 = datetime::timestamp::from_microseconds( 1291970750123456); const datetime::timestamp ts2 = datetime::timestamp::from_microseconds( 1291970750123468); const datetime::timestamp ts3 = datetime::timestamp::from_microseconds( 1291970850123456); ATF_REQUIRE(datetime::delta(0, 0) == ts1 - ts1); ATF_REQUIRE(datetime::delta(0, 12) == ts2 - ts1); ATF_REQUIRE(datetime::delta(100, 0) == ts3 - ts1); ATF_REQUIRE(datetime::delta(99, 999988) == ts3 - ts2); } ATF_INIT_TEST_CASES(tcs) { ATF_ADD_TEST_CASE(tcs, delta__defaults); ATF_ADD_TEST_CASE(tcs, delta__overrides); ATF_ADD_TEST_CASE(tcs, delta__from_useconds); ATF_ADD_TEST_CASE(tcs, delta__to_useconds); ATF_ADD_TEST_CASE(tcs, delta__equals); ATF_ADD_TEST_CASE(tcs, delta__differs); ATF_ADD_TEST_CASE(tcs, delta__addition); ATF_ADD_TEST_CASE(tcs, delta__addition_and_set); ATF_ADD_TEST_CASE(tcs, timestamp__copy); ATF_ADD_TEST_CASE(tcs, timestamp__from_microseconds); ATF_ADD_TEST_CASE(tcs, timestamp__now__mock); ATF_ADD_TEST_CASE(tcs, timestamp__now__real); ATF_ADD_TEST_CASE(tcs, timestamp__now__granularity); ATF_ADD_TEST_CASE(tcs, timestamp__strftime); ATF_ADD_TEST_CASE(tcs, timestamp__to_microseconds); ATF_ADD_TEST_CASE(tcs, timestamp__to_seconds); ATF_ADD_TEST_CASE(tcs, timestamp__equals); ATF_ADD_TEST_CASE(tcs, timestamp__differs); ATF_ADD_TEST_CASE(tcs, timestamp__subtraction); } <commit_msg>Add missing include of unistd.h<commit_after>// Copyright 2010 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 "utils/datetime.hpp" extern "C" { #include <time.h> #include <unistd.h> } #include <atf-c++.hpp> namespace datetime = utils::datetime; ATF_TEST_CASE_WITHOUT_HEAD(delta__defaults); ATF_TEST_CASE_BODY(delta__defaults) { const datetime::delta delta; ATF_REQUIRE_EQ(0, delta.seconds); ATF_REQUIRE_EQ(0, delta.useconds); } ATF_TEST_CASE_WITHOUT_HEAD(delta__overrides); ATF_TEST_CASE_BODY(delta__overrides) { const datetime::delta delta(1, 2); ATF_REQUIRE_EQ(1, delta.seconds); ATF_REQUIRE_EQ(2, delta.useconds); } ATF_TEST_CASE_WITHOUT_HEAD(delta__from_useconds); ATF_TEST_CASE_BODY(delta__from_useconds) { { const datetime::delta delta = datetime::delta::from_useconds(0); ATF_REQUIRE_EQ(0, delta.seconds); ATF_REQUIRE_EQ(0, delta.useconds); } { const datetime::delta delta = datetime::delta::from_useconds(999999); ATF_REQUIRE_EQ(0, delta.seconds); ATF_REQUIRE_EQ(999999, delta.useconds); } { const datetime::delta delta = datetime::delta::from_useconds(1000000); ATF_REQUIRE_EQ(1, delta.seconds); ATF_REQUIRE_EQ(0, delta.useconds); } { const datetime::delta delta = datetime::delta::from_useconds(10576293); ATF_REQUIRE_EQ(10, delta.seconds); ATF_REQUIRE_EQ(576293, delta.useconds); } } ATF_TEST_CASE_WITHOUT_HEAD(delta__to_useconds); ATF_TEST_CASE_BODY(delta__to_useconds) { ATF_REQUIRE_EQ(0, datetime::delta(0, 0).to_useconds()); ATF_REQUIRE_EQ(999999, datetime::delta(0, 999999).to_useconds()); ATF_REQUIRE_EQ(1000000, datetime::delta(1, 0).to_useconds()); ATF_REQUIRE_EQ(10576293, datetime::delta(10, 576293).to_useconds()); ATF_REQUIRE_EQ(11576293, datetime::delta(10, 1576293).to_useconds()); } ATF_TEST_CASE_WITHOUT_HEAD(delta__equals); ATF_TEST_CASE_BODY(delta__equals) { ATF_REQUIRE(datetime::delta() == datetime::delta()); ATF_REQUIRE(datetime::delta() == datetime::delta(0, 0)); ATF_REQUIRE(datetime::delta(1, 2) == datetime::delta(1, 2)); ATF_REQUIRE(!(datetime::delta() == datetime::delta(0, 1))); ATF_REQUIRE(!(datetime::delta() == datetime::delta(1, 0))); ATF_REQUIRE(!(datetime::delta(1, 2) == datetime::delta(2, 1))); } ATF_TEST_CASE_WITHOUT_HEAD(delta__differs); ATF_TEST_CASE_BODY(delta__differs) { ATF_REQUIRE(!(datetime::delta() != datetime::delta())); ATF_REQUIRE(!(datetime::delta() != datetime::delta(0, 0))); ATF_REQUIRE(!(datetime::delta(1, 2) != datetime::delta(1, 2))); ATF_REQUIRE(datetime::delta() != datetime::delta(0, 1)); ATF_REQUIRE(datetime::delta() != datetime::delta(1, 0)); ATF_REQUIRE(datetime::delta(1, 2) != datetime::delta(2, 1)); } ATF_TEST_CASE_WITHOUT_HEAD(delta__addition); ATF_TEST_CASE_BODY(delta__addition) { using datetime::delta; ATF_REQUIRE(delta() == delta() + delta()); ATF_REQUIRE(delta(0, 10) == delta() + delta(0, 10)); ATF_REQUIRE(delta(10, 0) == delta(10, 0) + delta()); ATF_REQUIRE(delta(1, 234567) == delta(0, 1234567) + delta()); ATF_REQUIRE(delta(12, 34) == delta(10, 20) + delta(2, 14)); } ATF_TEST_CASE_WITHOUT_HEAD(delta__addition_and_set); ATF_TEST_CASE_BODY(delta__addition_and_set) { using datetime::delta; { delta d; d += delta(3, 5); ATF_REQUIRE(delta(3, 5) == d); } { delta d(1, 2); d += delta(3, 5); ATF_REQUIRE(delta(4, 7) == d); } { delta d(1, 2); ATF_REQUIRE(delta(4, 7) == (d += delta(3, 5))); } } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__copy); ATF_TEST_CASE_BODY(timestamp__copy) { const datetime::timestamp ts1 = datetime::timestamp::from_values( 2011, 2, 16, 19, 15, 30, 0); { const datetime::timestamp ts2 = ts1; const datetime::timestamp ts3 = datetime::timestamp::from_values( 2012, 2, 16, 19, 15, 30, 0); ATF_REQUIRE_EQ("2011", ts1.strftime("%Y")); ATF_REQUIRE_EQ("2011", ts2.strftime("%Y")); ATF_REQUIRE_EQ("2012", ts3.strftime("%Y")); } ATF_REQUIRE_EQ("2011", ts1.strftime("%Y")); } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__from_microseconds); ATF_TEST_CASE_BODY(timestamp__from_microseconds) { const datetime::timestamp ts = datetime::timestamp::from_microseconds( 1328829351987654); ATF_REQUIRE_EQ("2012-02-09 23:15:51", ts.strftime("%Y-%m-%d %H:%M:%S")); ATF_REQUIRE_EQ(1328829351987654, ts.to_microseconds()); ATF_REQUIRE_EQ(1328829351, ts.to_seconds()); } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__now__mock); ATF_TEST_CASE_BODY(timestamp__now__mock) { datetime::set_mock_now(2011, 2, 21, 18, 5, 10, 0); ATF_REQUIRE_EQ("2011-02-21 18:05:10", datetime::timestamp::now().strftime("%Y-%m-%d %H:%M:%S")); datetime::set_mock_now(2012, 3, 22, 19, 6, 11, 54321); ATF_REQUIRE_EQ("2012-03-22 19:06:11", datetime::timestamp::now().strftime("%Y-%m-%d %H:%M:%S")); ATF_REQUIRE_EQ("2012-03-22 19:06:11", datetime::timestamp::now().strftime("%Y-%m-%d %H:%M:%S")); } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__now__real); ATF_TEST_CASE_BODY(timestamp__now__real) { // This test is might fail if we happen to run at the crossing of one // day to the other and the two measures we pick of the current time // differ. This is so unlikely that I haven't bothered to do this in any // other way. const time_t just_before = ::time(NULL); const datetime::timestamp now = datetime::timestamp::now(); ::tm data; char buf[1024]; ATF_REQUIRE(::gmtime_r(&just_before, &data) != 0); ATF_REQUIRE(::strftime(buf, sizeof(buf), "%Y-%m-%d", &data) != 0); ATF_REQUIRE_EQ(buf, now.strftime("%Y-%m-%d")); ATF_REQUIRE(now.strftime("%Z") == "GMT" || now.strftime("%Z") == "UTC"); } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__now__granularity); ATF_TEST_CASE_BODY(timestamp__now__granularity) { const datetime::timestamp first = datetime::timestamp::now(); ::usleep(1); const datetime::timestamp second = datetime::timestamp::now(); ATF_REQUIRE(first.to_microseconds() != second.to_microseconds()); } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__strftime); ATF_TEST_CASE_BODY(timestamp__strftime) { const datetime::timestamp ts1 = datetime::timestamp::from_values( 2010, 12, 10, 8, 45, 50, 0); ATF_REQUIRE_EQ("2010-12-10", ts1.strftime("%Y-%m-%d")); ATF_REQUIRE_EQ("08:45:50", ts1.strftime("%H:%M:%S")); const datetime::timestamp ts2 = datetime::timestamp::from_values( 2011, 2, 16, 19, 15, 30, 0); ATF_REQUIRE_EQ("2011-02-16T19:15:30", ts2.strftime("%Y-%m-%dT%H:%M:%S")); } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__to_microseconds); ATF_TEST_CASE_BODY(timestamp__to_microseconds) { const datetime::timestamp ts1 = datetime::timestamp::from_values( 2010, 12, 10, 8, 45, 50, 123456); ATF_REQUIRE_EQ(1291970750123456, ts1.to_microseconds()); } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__to_seconds); ATF_TEST_CASE_BODY(timestamp__to_seconds) { const datetime::timestamp ts1 = datetime::timestamp::from_values( 2010, 12, 10, 8, 45, 50, 123456); ATF_REQUIRE_EQ(1291970750, ts1.to_seconds()); } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__equals); ATF_TEST_CASE_BODY(timestamp__equals) { ATF_REQUIRE(datetime::timestamp::from_microseconds(1291970750123456) == datetime::timestamp::from_microseconds(1291970750123456)); } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__differs); ATF_TEST_CASE_BODY(timestamp__differs) { ATF_REQUIRE(datetime::timestamp::from_microseconds(1291970750123456) != datetime::timestamp::from_microseconds(1291970750123455)); } ATF_TEST_CASE_WITHOUT_HEAD(timestamp__subtraction); ATF_TEST_CASE_BODY(timestamp__subtraction) { const datetime::timestamp ts1 = datetime::timestamp::from_microseconds( 1291970750123456); const datetime::timestamp ts2 = datetime::timestamp::from_microseconds( 1291970750123468); const datetime::timestamp ts3 = datetime::timestamp::from_microseconds( 1291970850123456); ATF_REQUIRE(datetime::delta(0, 0) == ts1 - ts1); ATF_REQUIRE(datetime::delta(0, 12) == ts2 - ts1); ATF_REQUIRE(datetime::delta(100, 0) == ts3 - ts1); ATF_REQUIRE(datetime::delta(99, 999988) == ts3 - ts2); } ATF_INIT_TEST_CASES(tcs) { ATF_ADD_TEST_CASE(tcs, delta__defaults); ATF_ADD_TEST_CASE(tcs, delta__overrides); ATF_ADD_TEST_CASE(tcs, delta__from_useconds); ATF_ADD_TEST_CASE(tcs, delta__to_useconds); ATF_ADD_TEST_CASE(tcs, delta__equals); ATF_ADD_TEST_CASE(tcs, delta__differs); ATF_ADD_TEST_CASE(tcs, delta__addition); ATF_ADD_TEST_CASE(tcs, delta__addition_and_set); ATF_ADD_TEST_CASE(tcs, timestamp__copy); ATF_ADD_TEST_CASE(tcs, timestamp__from_microseconds); ATF_ADD_TEST_CASE(tcs, timestamp__now__mock); ATF_ADD_TEST_CASE(tcs, timestamp__now__real); ATF_ADD_TEST_CASE(tcs, timestamp__now__granularity); ATF_ADD_TEST_CASE(tcs, timestamp__strftime); ATF_ADD_TEST_CASE(tcs, timestamp__to_microseconds); ATF_ADD_TEST_CASE(tcs, timestamp__to_seconds); ATF_ADD_TEST_CASE(tcs, timestamp__equals); ATF_ADD_TEST_CASE(tcs, timestamp__differs); ATF_ADD_TEST_CASE(tcs, timestamp__subtraction); } <|endoftext|>
<commit_before>/* * Author: Pierre Chifflier <chifflier@edenwall.com> */ #include <cstdio> #include <cstring> #include <iostream> #include <stdlib.h> #include <apt-pkg/init.h> #include <apt-pkg/error.h> #include <apt-pkg/mmap.h> #include <apt-pkg/pkgcache.h> #include <apt-pkg/pkgrecords.h> #include "dpkginfo-helper.h" using namespace std; static int _init_done = 0; static pkgCache *cgCache = NULL; static MMap *dpkg_mmap = NULL; static int opencache (void) { if (pkgInitConfig (*_config) == false) return 0; if (pkgInitSystem (*_config, _system) == false) return 0; FileFd *fd = new FileFd (_config->FindFile ("Dir::Cache::pkgcache"), FileFd::ReadOnly); dpkg_mmap = new MMap (*fd, MMap::Public|MMap::ReadOnly); if (_error->PendingError () == true) { _error->DumpErrors (); return 0; } cgCache = new pkgCache (dpkg_mmap); if (0 == cgCache) return 0; if (_error->PendingError () == true) { _error->DumpErrors (); return 0; } return 1; } struct dpkginfo_reply_t * dpkginfo_get_by_name(const char *name, int *err) { pkgCache &cache = *cgCache; pkgRecords Recs (cache); struct dpkginfo_reply_t *reply = NULL; // Locate the package pkgCache::PkgIterator Pkg = cache.FindPkg(name); if (Pkg.end() == true) { /* not found, clear error flag */ if (err) *err = 0; return NULL; } pkgCache::VerIterator V1 = Pkg.CurrentVer(); if (V1.end() == true) { /* not installed, clear error flag */ /* FIXME this should be different that not found */ if (err) *err = 0; return NULL; } pkgRecords::Parser &P = Recs.Lookup(V1.FileList()); /* split epoch, version and release */ string evr = V1.VerStr(); string epoch, version, release; string::size_type version_start = 0, version_stop; string::size_type pos; string evr_str; pos = evr.find_first_of(":"); if (pos != string::npos) { epoch = evr.substr(0, pos); version_start = pos+1; } else { epoch = "0"; } pos = evr.find_first_of("-"); if (pos != string::npos) { version = evr.substr(version_start, pos-version_start); version_stop = pos+1; release = evr.substr(version_stop, evr.length()-version_stop); evr_str = epoch + ":" + version + "-" + release; } else { /* no release number, probably a native package */ version = evr.substr(version_start, evr.length()-version_start); release = ""; evr_str = epoch + ":" + version; } reply = new(struct dpkginfo_reply_t); memset(reply, 0, sizeof(struct dpkginfo_reply_t)); reply->name = strdup(Pkg.Name()); reply->arch = strdup(V1.Arch()); reply->epoch = strdup(epoch.c_str()); reply->release = strdup(release.c_str()); reply->version = strdup(version.c_str()); reply->evr = strdup(evr_str.c_str()); return reply; } void * dpkginfo_free_reply(struct dpkginfo_reply_t *reply) { if (reply) { free(reply->name); delete reply; } } int dpkginfo_init() { if (_init_done == 0) if (opencache() != 1) { return -1; } return 0; } int dpkginfo_fini() { delete cgCache; cgCache = NULL; delete dpkg_mmap; dpkg_mmap = NULL; return 0; } <commit_msg>Include additional headers in dkpginfo-helper for apt 1.9<commit_after>/* * Author: Pierre Chifflier <chifflier@edenwall.com> */ #include <cstdio> #include <cstring> #include <iostream> #include <stdlib.h> #include <apt-pkg/init.h> #include <apt-pkg/error.h> #include <apt-pkg/configuration.h> #include <apt-pkg/fileutl.h> #include <apt-pkg/mmap.h> #include <apt-pkg/pkgcache.h> #include <apt-pkg/pkgrecords.h> #include <apt-pkg/pkgsystem.h> #include "dpkginfo-helper.h" using namespace std; static int _init_done = 0; static pkgCache *cgCache = NULL; static MMap *dpkg_mmap = NULL; static int opencache (void) { if (pkgInitConfig (*_config) == false) return 0; if (pkgInitSystem (*_config, _system) == false) return 0; FileFd *fd = new FileFd (_config->FindFile ("Dir::Cache::pkgcache"), FileFd::ReadOnly); dpkg_mmap = new MMap (*fd, MMap::Public|MMap::ReadOnly); if (_error->PendingError () == true) { _error->DumpErrors (); return 0; } cgCache = new pkgCache (dpkg_mmap); if (0 == cgCache) return 0; if (_error->PendingError () == true) { _error->DumpErrors (); return 0; } return 1; } struct dpkginfo_reply_t * dpkginfo_get_by_name(const char *name, int *err) { pkgCache &cache = *cgCache; pkgRecords Recs (cache); struct dpkginfo_reply_t *reply = NULL; // Locate the package pkgCache::PkgIterator Pkg = cache.FindPkg(name); if (Pkg.end() == true) { /* not found, clear error flag */ if (err) *err = 0; return NULL; } pkgCache::VerIterator V1 = Pkg.CurrentVer(); if (V1.end() == true) { /* not installed, clear error flag */ /* FIXME this should be different that not found */ if (err) *err = 0; return NULL; } pkgRecords::Parser &P = Recs.Lookup(V1.FileList()); /* split epoch, version and release */ string evr = V1.VerStr(); string epoch, version, release; string::size_type version_start = 0, version_stop; string::size_type pos; string evr_str; pos = evr.find_first_of(":"); if (pos != string::npos) { epoch = evr.substr(0, pos); version_start = pos+1; } else { epoch = "0"; } pos = evr.find_first_of("-"); if (pos != string::npos) { version = evr.substr(version_start, pos-version_start); version_stop = pos+1; release = evr.substr(version_stop, evr.length()-version_stop); evr_str = epoch + ":" + version + "-" + release; } else { /* no release number, probably a native package */ version = evr.substr(version_start, evr.length()-version_start); release = ""; evr_str = epoch + ":" + version; } reply = new(struct dpkginfo_reply_t); memset(reply, 0, sizeof(struct dpkginfo_reply_t)); reply->name = strdup(Pkg.Name()); reply->arch = strdup(V1.Arch()); reply->epoch = strdup(epoch.c_str()); reply->release = strdup(release.c_str()); reply->version = strdup(version.c_str()); reply->evr = strdup(evr_str.c_str()); return reply; } void * dpkginfo_free_reply(struct dpkginfo_reply_t *reply) { if (reply) { free(reply->name); delete reply; } } int dpkginfo_init() { if (_init_done == 0) if (opencache() != 1) { return -1; } return 0; } int dpkginfo_fini() { delete cgCache; cgCache = NULL; delete dpkg_mmap; dpkg_mmap = NULL; return 0; } <|endoftext|>
<commit_before>#include <algorithm> #include <ctime> #include <functional> #include <map> #include <memory> #include "BrickCache.h" #include "Controller/StackTimer.h" namespace tuvok { // This is used to basically get rid of a type. You can do: // std::vector<TypeErase> data; // std::vector<uint8_t> foo; // std::vector<uint16_t> bar; // data.push_back(TypeErase<std::vector<uint8_t>>(foo)); // data.push_back(TypeErase<std::vector<uint16_t>>(bar)); // with 'MyTypeOne' and 'MyTypeTwo' being completely unrelated (they do not // need to have a common base class) struct TypeErase { struct GenericType { virtual ~GenericType() {} virtual size_t elems() const { return 0; } }; template<typename T> struct TypeEraser : GenericType { TypeEraser(const T& t) : thing(t) {} virtual ~TypeEraser() {} T& get() { return thing; } size_t elems() const { return thing.size(); } private: T thing; }; std::shared_ptr<GenericType> gt; size_t width; // this isn't a very good type eraser, because we require that the type has // an internal typedef 'value_type' which we can use to obtain the size of // it. not to mention the '.size()' member function that TypeEraser<> // requires, above. // But that's fine for our usage here; we're really just using this to store // vectors and erase the value_type in there anyway. template<typename T> TypeErase(const T& t): gt(new TypeEraser<T>(t)), width(sizeof(typename T::value_type)) {} }; struct BrickInfo { BrickKey key; uint64_t access_time; BrickInfo(const BrickKey& k, time_t t) : key(k), access_time(uint64_t(t)) {} }; struct CacheLRU { typedef std::pair<BrickInfo, TypeErase> CacheElem; bool operator()(const CacheElem& a, const CacheElem& b) const { return a.first.access_time > b.first.access_time; } }; struct BrickCache::bcinfo { bcinfo(): bytes(0) {} // this is wordy but they all just forward to a real implementation below. const void* lookup(const BrickKey& k) { return this->typed_lookup<uint8_t>(k); } // the erasure means we can just do the insert with the thing we already // have: it'll make a shared_ptr out of it and insert it into the // container. ///@{ const void* add(const BrickKey& k, std::vector<uint8_t>& data) { return this->typed_add<uint8_t>(k, data); } const void* add(const BrickKey& k, std::vector<uint16_t>& data) { return this->typed_add<uint16_t>(k, data); } const void* add(const BrickKey& k, std::vector<uint32_t>& data) { return this->typed_add<uint32_t>(k, data); } const void* add(const BrickKey& k, std::vector<uint64_t>& data) { return this->typed_add<uint64_t>(k, data); } const void* add(const BrickKey& k, std::vector<int8_t>& data) { return this->typed_add<int8_t>(k, data); } const void* add(const BrickKey& k, std::vector<int16_t>& data) { return this->typed_add<int16_t>(k, data); } const void* add(const BrickKey& k, std::vector<int32_t>& data) { return this->typed_add<int32_t>(k, data); } const void* add(const BrickKey& k, std::vector<int64_t>& data) { return this->typed_add<int64_t>(k, data); } const void* add(const BrickKey& k, std::vector<float>& data) { return this->typed_add<float>(k, data); } ///@} void remove() { if(!cache.empty()) { // libstdc++ complains it's not a heap otherwise.. somehow. bug? std::make_heap(this->cache.begin(), this->cache.end(), CacheLRU()); const auto entry = this->cache.front(); TypeErase::GenericType& gt = *(entry.second.gt); assert((entry.second.width * gt.elems()) <= this->bytes); this->bytes -= entry.second.width * gt.elems(); std::pop_heap(this->cache.begin(), this->cache.end(), CacheLRU()); this->cache.pop_back(); } assert(this->size() == this->bytes); } size_t size() const { return this->bytes; } private: template<typename T> const void* typed_lookup(const BrickKey& k); template<typename T> const void* typed_add(const BrickKey&, std::vector<T>&); private: typedef std::pair<BrickInfo, TypeErase> CacheElem; std::vector<CacheElem> cache; size_t bytes; ///< how much memory we're currently using for data. }; struct KeyMatches { bool operator()(const BrickKey& key, const std::pair<BrickInfo,TypeErase>& a) const { return key == a.first.key; } }; // if the key doesn't exist, you get an empty vector. template<typename T> const void* BrickCache::bcinfo::typed_lookup(const BrickKey& k) { using namespace std::placeholders; KeyMatches km; auto func = std::bind(&KeyMatches::operator(), km, k, _1); // gcc can't seem to deduce this with 'auto'. typedef std::vector<CacheElem> maptype; maptype::iterator i = std::find_if(this->cache.begin(), this->cache.end(), func); if(i == this->cache.end()) { return NULL; } i->first.access_time = time(NULL); TypeErase::GenericType& gt = *(i->second.gt); assert(this->size() == this->bytes); return dynamic_cast<TypeErase::TypeEraser<std::vector<T>>&>(gt).get().data(); } template<typename T> const void* BrickCache::bcinfo::typed_add(const BrickKey& k, std::vector<T>& data) { // maybe the case of a general case allows duplicate insert, but for our uses // there should never be a duplicate entry. #ifndef NDEBUG KeyMatches km; using namespace std::placeholders; auto func = std::bind(&KeyMatches::operator(), km, k, _1); assert(std::find_if(this->cache.begin(), this->cache.end(), func) == this->cache.end()); #endif this->cache.push_back(std::make_pair(BrickInfo(k, time(NULL)), std::move(data))); StackTimer st(PERF_SOMETHING); this->bytes += sizeof(T) * data.size(); assert(this->size() == this->bytes); return this->typed_lookup<T>(k); } BrickCache::BrickCache() : ci(new BrickCache::bcinfo) {} BrickCache::~BrickCache() {} const void* BrickCache::lookup(const BrickKey& k) { return this->ci->lookup(k); } #if 0 void BrickCache::lookup(const BrickKey& k, std::vector<uint16_t>& data) { return this->ci->lookup(k, data); } void BrickCache::lookup(const BrickKey& k, std::vector<uint32_t>& data) { return this->ci->lookup(k, data); } void BrickCache::lookup(const BrickKey& k, std::vector<uint64_t>& data) { return this->ci->lookup(k, data); } void BrickCache::lookup(const BrickKey& k, std::vector<int8_t>& data) { return this->ci->lookup(k, data); } void BrickCache::lookup(const BrickKey& k, std::vector<int16_t>& data) { return this->ci->lookup(k, data); } void BrickCache::lookup(const BrickKey& k, std::vector<int32_t>& data) { return this->ci->lookup(k, data); } void BrickCache::lookup(const BrickKey& k, std::vector<int64_t>& data) { return this->ci->lookup(k, data); } void BrickCache::lookup(const BrickKey& k, std::vector<float>& data) { return this->ci->lookup(k, data); } #endif const void* BrickCache::add(const BrickKey& k, std::vector<uint8_t>& data) { return this->ci->add(k, data); } const void* BrickCache::add(const BrickKey& k, std::vector<uint16_t>& data) { return this->ci->add(k, data); } const void* BrickCache::add(const BrickKey& k, std::vector<uint32_t>& data) { return this->ci->add(k, data); } const void* BrickCache::add(const BrickKey& k, std::vector<uint64_t>& data) { return this->ci->add(k, data); } const void* BrickCache::add(const BrickKey& k, std::vector<int8_t>& data) { return this->ci->add(k, data); } const void* BrickCache::add(const BrickKey& k, std::vector<int16_t>& data) { return this->ci->add(k, data); } const void* BrickCache::add(const BrickKey& k, std::vector<int32_t>& data) { return this->ci->add(k, data); } const void* BrickCache::add(const BrickKey& k, std::vector<int64_t>& data) { return this->ci->add(k, data); } const void* BrickCache::add(const BrickKey& k, std::vector<float>& data) { return this->ci->add(k, data); } void BrickCache::remove() { this->ci->remove(); } size_t BrickCache::size() const { return this->ci->size(); } } /* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2013 Scientific Computing and Imaging Institute, University of Utah. 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. */ <commit_msg>cache: Fix byte counts: count before moving the data.<commit_after>#include <algorithm> #include <ctime> #include <functional> #include <map> #include <memory> #include "BrickCache.h" #include "Controller/StackTimer.h" namespace tuvok { // This is used to basically get rid of a type. You can do: // std::vector<TypeErase> data; // std::vector<uint8_t> foo; // std::vector<uint16_t> bar; // data.push_back(TypeErase<std::vector<uint8_t>>(foo)); // data.push_back(TypeErase<std::vector<uint16_t>>(bar)); // with 'MyTypeOne' and 'MyTypeTwo' being completely unrelated (they do not // need to have a common base class) struct TypeErase { struct GenericType { virtual ~GenericType() {} virtual size_t elems() const { return 0; } }; template<typename T> struct TypeEraser : GenericType { TypeEraser(const T& t) : thing(t) {} virtual ~TypeEraser() {} T& get() { return thing; } size_t elems() const { return thing.size(); } private: T thing; }; std::shared_ptr<GenericType> gt; size_t width; // this isn't a very good type eraser, because we require that the type has // an internal typedef 'value_type' which we can use to obtain the size of // it. not to mention the '.size()' member function that TypeEraser<> // requires, above. // But that's fine for our usage here; we're really just using this to store // vectors and erase the value_type in there anyway. template<typename T> TypeErase(const T& t): gt(new TypeEraser<T>(t)), width(sizeof(typename T::value_type)) {} }; struct BrickInfo { BrickKey key; uint64_t access_time; BrickInfo(const BrickKey& k, time_t t) : key(k), access_time(uint64_t(t)) {} }; struct CacheLRU { typedef std::pair<BrickInfo, TypeErase> CacheElem; bool operator()(const CacheElem& a, const CacheElem& b) const { return a.first.access_time > b.first.access_time; } }; struct BrickCache::bcinfo { bcinfo(): bytes(0) {} // this is wordy but they all just forward to a real implementation below. const void* lookup(const BrickKey& k) { return this->typed_lookup<uint8_t>(k); } // the erasure means we can just do the insert with the thing we already // have: it'll make a shared_ptr out of it and insert it into the // container. ///@{ const void* add(const BrickKey& k, std::vector<uint8_t>& data) { return this->typed_add<uint8_t>(k, data); } const void* add(const BrickKey& k, std::vector<uint16_t>& data) { return this->typed_add<uint16_t>(k, data); } const void* add(const BrickKey& k, std::vector<uint32_t>& data) { return this->typed_add<uint32_t>(k, data); } const void* add(const BrickKey& k, std::vector<uint64_t>& data) { return this->typed_add<uint64_t>(k, data); } const void* add(const BrickKey& k, std::vector<int8_t>& data) { return this->typed_add<int8_t>(k, data); } const void* add(const BrickKey& k, std::vector<int16_t>& data) { return this->typed_add<int16_t>(k, data); } const void* add(const BrickKey& k, std::vector<int32_t>& data) { return this->typed_add<int32_t>(k, data); } const void* add(const BrickKey& k, std::vector<int64_t>& data) { return this->typed_add<int64_t>(k, data); } const void* add(const BrickKey& k, std::vector<float>& data) { return this->typed_add<float>(k, data); } ///@} void remove() { if(!cache.empty()) { // libstdc++ complains it's not a heap otherwise.. somehow. bug? std::make_heap(this->cache.begin(), this->cache.end(), CacheLRU()); const auto entry = this->cache.front(); TypeErase::GenericType& gt = *(entry.second.gt); assert((entry.second.width * gt.elems()) <= this->bytes); this->bytes -= entry.second.width * gt.elems(); std::pop_heap(this->cache.begin(), this->cache.end(), CacheLRU()); this->cache.pop_back(); } assert(this->size() == this->bytes); } size_t size() const { return this->bytes; } private: template<typename T> const void* typed_lookup(const BrickKey& k); template<typename T> const void* typed_add(const BrickKey&, std::vector<T>&); private: typedef std::pair<BrickInfo, TypeErase> CacheElem; std::vector<CacheElem> cache; size_t bytes; ///< how much memory we're currently using for data. }; struct KeyMatches { bool operator()(const BrickKey& key, const std::pair<BrickInfo,TypeErase>& a) const { return key == a.first.key; } }; // if the key doesn't exist, you get an empty vector. template<typename T> const void* BrickCache::bcinfo::typed_lookup(const BrickKey& k) { using namespace std::placeholders; KeyMatches km; auto func = std::bind(&KeyMatches::operator(), km, k, _1); // gcc can't seem to deduce this with 'auto'. typedef std::vector<CacheElem> maptype; maptype::iterator i = std::find_if(this->cache.begin(), this->cache.end(), func); if(i == this->cache.end()) { return NULL; } i->first.access_time = time(NULL); TypeErase::GenericType& gt = *(i->second.gt); assert(this->size() == this->bytes); return dynamic_cast<TypeErase::TypeEraser<std::vector<T>>&>(gt).get().data(); } template<typename T> const void* BrickCache::bcinfo::typed_add(const BrickKey& k, std::vector<T>& data) { // maybe the case of a general cache allows duplicate insert, but for our uses // there should never be a duplicate entry. #ifndef NDEBUG KeyMatches km; using namespace std::placeholders; auto func = std::bind(&KeyMatches::operator(), km, k, _1); assert(std::find_if(this->cache.begin(), this->cache.end(), func) == this->cache.end()); #endif this->bytes += sizeof(T) * data.size(); this->cache.push_back(std::make_pair(BrickInfo(k, time(NULL)), std::move(data))); StackTimer st(PERF_SOMETHING); assert(this->size() == this->bytes); return this->typed_lookup<T>(k); } BrickCache::BrickCache() : ci(new BrickCache::bcinfo) {} BrickCache::~BrickCache() {} const void* BrickCache::lookup(const BrickKey& k) { return this->ci->lookup(k); } #if 0 void BrickCache::lookup(const BrickKey& k, std::vector<uint16_t>& data) { return this->ci->lookup(k, data); } void BrickCache::lookup(const BrickKey& k, std::vector<uint32_t>& data) { return this->ci->lookup(k, data); } void BrickCache::lookup(const BrickKey& k, std::vector<uint64_t>& data) { return this->ci->lookup(k, data); } void BrickCache::lookup(const BrickKey& k, std::vector<int8_t>& data) { return this->ci->lookup(k, data); } void BrickCache::lookup(const BrickKey& k, std::vector<int16_t>& data) { return this->ci->lookup(k, data); } void BrickCache::lookup(const BrickKey& k, std::vector<int32_t>& data) { return this->ci->lookup(k, data); } void BrickCache::lookup(const BrickKey& k, std::vector<int64_t>& data) { return this->ci->lookup(k, data); } void BrickCache::lookup(const BrickKey& k, std::vector<float>& data) { return this->ci->lookup(k, data); } #endif const void* BrickCache::add(const BrickKey& k, std::vector<uint8_t>& data) { return this->ci->add(k, data); } const void* BrickCache::add(const BrickKey& k, std::vector<uint16_t>& data) { return this->ci->add(k, data); } const void* BrickCache::add(const BrickKey& k, std::vector<uint32_t>& data) { return this->ci->add(k, data); } const void* BrickCache::add(const BrickKey& k, std::vector<uint64_t>& data) { return this->ci->add(k, data); } const void* BrickCache::add(const BrickKey& k, std::vector<int8_t>& data) { return this->ci->add(k, data); } const void* BrickCache::add(const BrickKey& k, std::vector<int16_t>& data) { return this->ci->add(k, data); } const void* BrickCache::add(const BrickKey& k, std::vector<int32_t>& data) { return this->ci->add(k, data); } const void* BrickCache::add(const BrickKey& k, std::vector<int64_t>& data) { return this->ci->add(k, data); } const void* BrickCache::add(const BrickKey& k, std::vector<float>& data) { return this->ci->add(k, data); } void BrickCache::remove() { this->ci->remove(); } size_t BrickCache::size() const { return this->ci->size(); } } /* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2013 Scientific Computing and Imaging Institute, University of Utah. 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. */ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: i18n_im.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: kz $ $Date: 2005-03-18 17:53:44 $ * * 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 _SAL_I18N_INPUTMETHOD_HXX #define _SAL_I18N_INPUTMETHOD_HXX #ifndef _VCL_DLLAPI_H #include "dllapi.h" #endif extern "C" char* GetMethodName( XIMStyle nStyle, char *pBuf, int nBufSize); #define bUseInputMethodDefault True class VCL_DLLPUBLIC SalI18N_InputMethod { Bool mbUseable; // system supports locale as well as status // and preedit style ? Bool mbMultiLingual; // system supports iiimp XIM maMethod; XIMCallback maDestroyCallback; XIMStyles *mpStyles; public: Bool IsMultiLingual() { return mbMultiLingual; } Bool PosixLocale(); Bool UseMethod() { return mbUseable; } XIM GetMethod() { return maMethod; } void HandleDestroyIM(); Bool CreateMethod( Display *pDisplay ); XIMStyles *GetSupportedStyles() { return mpStyles; } Bool SetLocale( const char* pLocale = "" ); Bool FilterEvent( XEvent *pEvent, XLIB_Window window ); Bool AddConnectionWatch (Display *pDisplay, void *pConnectionHandler); #ifdef _USE_PRINT_EXTENSION_ void Invalidate() { mbUseable = False; } #endif SalI18N_InputMethod(); ~SalI18N_InputMethod(); }; #endif // _SAL_I18N_INPUTMETHOD_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.12.186); FILE MERGED 2005/09/05 14:45:26 rt 1.12.186.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: i18n_im.hxx,v $ * * $Revision: 1.13 $ * * last change: $Author: rt $ $Date: 2005-09-09 12:40:19 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SAL_I18N_INPUTMETHOD_HXX #define _SAL_I18N_INPUTMETHOD_HXX #ifndef _VCL_DLLAPI_H #include "dllapi.h" #endif extern "C" char* GetMethodName( XIMStyle nStyle, char *pBuf, int nBufSize); #define bUseInputMethodDefault True class VCL_DLLPUBLIC SalI18N_InputMethod { Bool mbUseable; // system supports locale as well as status // and preedit style ? Bool mbMultiLingual; // system supports iiimp XIM maMethod; XIMCallback maDestroyCallback; XIMStyles *mpStyles; public: Bool IsMultiLingual() { return mbMultiLingual; } Bool PosixLocale(); Bool UseMethod() { return mbUseable; } XIM GetMethod() { return maMethod; } void HandleDestroyIM(); Bool CreateMethod( Display *pDisplay ); XIMStyles *GetSupportedStyles() { return mpStyles; } Bool SetLocale( const char* pLocale = "" ); Bool FilterEvent( XEvent *pEvent, XLIB_Window window ); Bool AddConnectionWatch (Display *pDisplay, void *pConnectionHandler); #ifdef _USE_PRINT_EXTENSION_ void Invalidate() { mbUseable = False; } #endif SalI18N_InputMethod(); ~SalI18N_InputMethod(); }; #endif // _SAL_I18N_INPUTMETHOD_HXX <|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 "ui/views/controls/webview/webview.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "ipc/ipc_message.h" #include "ui/base/accessibility/accessible_view_state.h" #include "ui/base/accessibility/accessibility_types.h" #include "ui/views/controls/native/native_view_host.h" #include "ui/views/focus/focus_manager.h" namespace views { // static const char WebView::kViewClassName[] = "ui/views/WebView"; //////////////////////////////////////////////////////////////////////////////// // WebView, public: WebView::WebView(content::BrowserContext* browser_context) : wcv_holder_(new NativeViewHost), web_contents_(NULL), browser_context_(browser_context) { AddChildView(wcv_holder_); } WebView::~WebView() { } content::WebContents* WebView::GetWebContents() { CreateWebContentsWithSiteInstance(NULL); return web_contents_; } void WebView::CreateWebContentsWithSiteInstance( content::SiteInstance* site_instance) { if (!web_contents_) { wc_owner_.reset(content::WebContents::Create(browser_context_, site_instance, MSG_ROUTING_NONE, NULL, NULL)); web_contents_ = wc_owner_.get(); web_contents_->SetDelegate(this); AttachWebContents(); } } void WebView::SetWebContents(content::WebContents* web_contents) { if (web_contents == web_contents_) return; DetachWebContents(); wc_owner_.reset(); web_contents_ = web_contents; AttachWebContents(); } void WebView::LoadInitialURL(const GURL& url) { GetWebContents()->GetController().LoadURL( url, content::Referrer(), content::PAGE_TRANSITION_START_PAGE, std::string()); } void WebView::SetFastResize(bool fast_resize) { wcv_holder_->set_fast_resize(fast_resize); } void WebView::OnWebContentsFocused(content::WebContents* web_contents) { FocusManager* focus_manager = GetFocusManager(); if (focus_manager) focus_manager->SetFocusedView(this); } //////////////////////////////////////////////////////////////////////////////// // WebView, View overrides: std::string WebView::GetClassName() const { return kViewClassName; } void WebView::OnBoundsChanged(const gfx::Rect& previous_bounds) { wcv_holder_->SetSize(bounds().size()); } void WebView::ViewHierarchyChanged(bool is_add, View* parent, View* child) { if (is_add) AttachWebContents(); } bool WebView::SkipDefaultKeyEventProcessing(const views::KeyEvent& event) { // Don't look-up accelerators or tab-traversal if we are showing a non-crashed // TabContents. // We'll first give the page a chance to process the key events. If it does // not process them, they'll be returned to us and we'll treat them as // accelerators then. return web_contents_ && !web_contents_->IsCrashed(); } bool WebView::IsFocusable() const { // We need to be focusable when our contents is not a view hierarchy, as // clicking on the contents needs to focus us. return !!web_contents_; } void WebView::OnFocus() { if (web_contents_) web_contents_->Focus(); } void WebView::AboutToRequestFocusFromTabTraversal(bool reverse) { if (web_contents_) web_contents_->FocusThroughTabTraversal(reverse); } void WebView::GetAccessibleState(ui::AccessibleViewState* state) { state->role = ui::AccessibilityTypes::ROLE_GROUPING; } gfx::NativeViewAccessible WebView::GetNativeViewAccessible() { if (web_contents_) { content::RenderWidgetHostView* host_view = web_contents_->GetRenderWidgetHostView(); if (host_view) return host_view->GetNativeViewAccessible(); } return View::GetNativeViewAccessible(); } //////////////////////////////////////////////////////////////////////////////// // WebView, content::NotificationObserver implementation: void WebView::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { if (type == content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED) { std::pair<content::RenderViewHost*, content::RenderViewHost*>* switched_details = content::Details<std::pair<content::RenderViewHost*, content::RenderViewHost*> >( details).ptr(); RenderViewHostChanged(switched_details->first, switched_details->second); } else if (type == content::NOTIFICATION_WEB_CONTENTS_DESTROYED) { WebContentsDestroyed(content::Source<content::WebContents>(source).ptr()); } else { NOTREACHED(); } } //////////////////////////////////////////////////////////////////////////////// // WebView, content::WebContentsDelegate implementation: void WebView::WebContentsFocused(content::WebContents* web_contents) { DCHECK(wc_owner_.get()); // The WebView is only the delegate of WebContentses it creates itself. OnWebContentsFocused(web_contents_); } //////////////////////////////////////////////////////////////////////////////// // WebView, private: void WebView::AttachWebContents() { // Prevents attachment if the WebView isn't already in a Widget, or it's // already attached. if (!GetWidget() || !web_contents_ || wcv_holder_->native_view() == web_contents_->GetNativeView()) { return; } if (web_contents_) { wcv_holder_->Attach(web_contents_->GetNativeView()); registrar_.Add( this, content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED, content::Source<content::NavigationController>( &web_contents_->GetController())); registrar_.Add( this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED, content::Source<content::WebContents>(web_contents_)); } } void WebView::DetachWebContents() { if (web_contents_) { wcv_holder_->Detach(); #if defined(OS_WIN) && !defined(USE_AURA) // TODO(beng): This should either not be necessary, or be done implicitly by // NativeViewHostWin on Detach(). As it stands, this is needed // so that the view of the detached contents knows to tell the // renderer its been hidden. ShowWindow(web_contents_->GetNativeView(), SW_HIDE); #endif } registrar_.RemoveAll(); } void WebView::RenderViewHostChanged(content::RenderViewHost* old_host, content::RenderViewHost* new_host) { if (GetFocusManager()->GetFocusedView() == this) web_contents_->Focus(); } void WebView::WebContentsDestroyed(content::WebContents* web_contents) { DCHECK(web_contents == web_contents_); SetWebContents(NULL); } } // namespace views <commit_msg>Make sure the WebContents has focus after being attached to a WebView, if that WebView was focused.<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 "ui/views/controls/webview/webview.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "ipc/ipc_message.h" #include "ui/base/accessibility/accessible_view_state.h" #include "ui/base/accessibility/accessibility_types.h" #include "ui/views/controls/native/native_view_host.h" #include "ui/views/focus/focus_manager.h" namespace views { // static const char WebView::kViewClassName[] = "ui/views/WebView"; //////////////////////////////////////////////////////////////////////////////// // WebView, public: WebView::WebView(content::BrowserContext* browser_context) : wcv_holder_(new NativeViewHost), web_contents_(NULL), browser_context_(browser_context) { AddChildView(wcv_holder_); } WebView::~WebView() { } content::WebContents* WebView::GetWebContents() { CreateWebContentsWithSiteInstance(NULL); return web_contents_; } void WebView::CreateWebContentsWithSiteInstance( content::SiteInstance* site_instance) { if (!web_contents_) { wc_owner_.reset(content::WebContents::Create(browser_context_, site_instance, MSG_ROUTING_NONE, NULL, NULL)); web_contents_ = wc_owner_.get(); web_contents_->SetDelegate(this); AttachWebContents(); } } void WebView::SetWebContents(content::WebContents* web_contents) { if (web_contents == web_contents_) return; DetachWebContents(); wc_owner_.reset(); web_contents_ = web_contents; AttachWebContents(); } void WebView::LoadInitialURL(const GURL& url) { GetWebContents()->GetController().LoadURL( url, content::Referrer(), content::PAGE_TRANSITION_START_PAGE, std::string()); } void WebView::SetFastResize(bool fast_resize) { wcv_holder_->set_fast_resize(fast_resize); } void WebView::OnWebContentsFocused(content::WebContents* web_contents) { FocusManager* focus_manager = GetFocusManager(); if (focus_manager) focus_manager->SetFocusedView(this); } //////////////////////////////////////////////////////////////////////////////// // WebView, View overrides: std::string WebView::GetClassName() const { return kViewClassName; } void WebView::OnBoundsChanged(const gfx::Rect& previous_bounds) { wcv_holder_->SetSize(bounds().size()); } void WebView::ViewHierarchyChanged(bool is_add, View* parent, View* child) { if (is_add) AttachWebContents(); } bool WebView::SkipDefaultKeyEventProcessing(const views::KeyEvent& event) { // Don't look-up accelerators or tab-traversal if we are showing a non-crashed // TabContents. // We'll first give the page a chance to process the key events. If it does // not process them, they'll be returned to us and we'll treat them as // accelerators then. return web_contents_ && !web_contents_->IsCrashed(); } bool WebView::IsFocusable() const { // We need to be focusable when our contents is not a view hierarchy, as // clicking on the contents needs to focus us. return !!web_contents_; } void WebView::OnFocus() { if (web_contents_) web_contents_->Focus(); } void WebView::AboutToRequestFocusFromTabTraversal(bool reverse) { if (web_contents_) web_contents_->FocusThroughTabTraversal(reverse); } void WebView::GetAccessibleState(ui::AccessibleViewState* state) { state->role = ui::AccessibilityTypes::ROLE_GROUPING; } gfx::NativeViewAccessible WebView::GetNativeViewAccessible() { if (web_contents_) { content::RenderWidgetHostView* host_view = web_contents_->GetRenderWidgetHostView(); if (host_view) return host_view->GetNativeViewAccessible(); } return View::GetNativeViewAccessible(); } //////////////////////////////////////////////////////////////////////////////// // WebView, content::NotificationObserver implementation: void WebView::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { if (type == content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED) { std::pair<content::RenderViewHost*, content::RenderViewHost*>* switched_details = content::Details<std::pair<content::RenderViewHost*, content::RenderViewHost*> >( details).ptr(); RenderViewHostChanged(switched_details->first, switched_details->second); } else if (type == content::NOTIFICATION_WEB_CONTENTS_DESTROYED) { WebContentsDestroyed(content::Source<content::WebContents>(source).ptr()); } else { NOTREACHED(); } } //////////////////////////////////////////////////////////////////////////////// // WebView, content::WebContentsDelegate implementation: void WebView::WebContentsFocused(content::WebContents* web_contents) { DCHECK(wc_owner_.get()); // The WebView is only the delegate of WebContentses it creates itself. OnWebContentsFocused(web_contents_); } //////////////////////////////////////////////////////////////////////////////// // WebView, private: void WebView::AttachWebContents() { // Prevents attachment if the WebView isn't already in a Widget, or it's // already attached. if (!GetWidget() || !web_contents_ || wcv_holder_->native_view() == web_contents_->GetNativeView()) { return; } if (web_contents_) { wcv_holder_->Attach(web_contents_->GetNativeView()); // The WebContentsView will not be focused automatically when it is // attached, so we need to pass on focus to it if the FocusManager thinks // the WebView is focused. Note that not every Widget has a focus manager. FocusManager* focus_manager = GetFocusManager(); if (focus_manager && focus_manager->GetFocusedView() == this) web_contents_->Focus(); registrar_.Add( this, content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED, content::Source<content::NavigationController>( &web_contents_->GetController())); registrar_.Add( this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED, content::Source<content::WebContents>(web_contents_)); } } void WebView::DetachWebContents() { if (web_contents_) { wcv_holder_->Detach(); #if defined(OS_WIN) && !defined(USE_AURA) // TODO(beng): This should either not be necessary, or be done implicitly by // NativeViewHostWin on Detach(). As it stands, this is needed // so that the view of the detached contents knows to tell the // renderer its been hidden. ShowWindow(web_contents_->GetNativeView(), SW_HIDE); #endif } registrar_.RemoveAll(); } void WebView::RenderViewHostChanged(content::RenderViewHost* old_host, content::RenderViewHost* new_host) { if (GetFocusManager()->GetFocusedView() == this) web_contents_->Focus(); } void WebView::WebContentsDestroyed(content::WebContents* web_contents) { DCHECK(web_contents == web_contents_); SetWebContents(NULL); } } // namespace views <|endoftext|>
<commit_before>// MIT License // Copyright (c) 2017 Simon Pettersson // 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. namespace cmap { constexpr auto map(auto key, auto value) { return [key,value](auto _key) { return std::pair(_key == key, value); }; } // There is really no need for operator overloading here, it's just that I have // no idea of how to do the fold expression in `make_map()` with a "regular" function constexpr auto operator<<(auto left, auto right) { return [left,right](auto key) { const auto [lresult, lvalue] = left(key); if(lresult) { return std::pair(true, lvalue); } const auto [rresult, rvalue] = right(key); return std::pair(rresult, rvalue); }; } template<typename T> struct root { constexpr root(T _chain) : chain(_chain) {} constexpr auto operator[](auto key) const { const auto [success, value] = chain(key); return success ? value : throw std::out_of_range("No such key!"); } const T chain; }; template<typename...Ts> constexpr auto make_map(Ts...ts) { const auto chain = (... << ts); return root(chain); } constexpr auto join(root<auto> left, root<auto> right) { return root(left.chain << right.chain); } } // namespace cmap <commit_msg>Made code a bit clearer<commit_after>// MIT License // Copyright (c) 2017 Simon Pettersson // 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. namespace cmap { constexpr auto map(auto key, auto value) { return [key,value](auto _key) { return std::pair(_key == key, value); }; } // There is really no need for operator overloading here, it's just that I have // no idea of how to do the fold expression in `make_map()` with a "regular" function constexpr auto operator<<(auto left, auto right) { return [left,right](auto key) { if(const auto [lresult, lvalue] = left(key); lresult) { return std::pair(true, lvalue); } if(const auto [rresult, rvalue] = right(key); rresult) { return std::pair(true, rvalue); } using T = decltype(left(key).second); return std::pair(false, T{}); }; } template<typename T> struct root { constexpr root(T _chain) : chain(_chain) {} constexpr auto operator[](auto key) const { const auto [success, value] = chain(key); return success ? value : throw std::out_of_range("No such key!"); } const T chain; }; template<typename...Ts> constexpr auto make_map(Ts...ts) { const auto chain = (... << ts); return root(chain); } constexpr auto join(root<auto> left, root<auto> right) { return root(left.chain << right.chain); } } // namespace cmap <|endoftext|>
<commit_before>/* * MIT License * Copyright (c) 2016 Thomas Prescher * 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. */ #pragma once #include "heap_config.hpp" class memory { public: virtual ~memory() {} virtual size_t base() const = 0; virtual size_t size() const = 0; virtual size_t end() const = 0; }; class fixed_memory : public memory { private: size_t base_; size_t size_; public: fixed_memory(size_t base, size_t size) : base_(base) , size_(size) { } virtual size_t base() const { return base_; } virtual size_t size() const { return size_; }; virtual size_t end() const { return base_ + size_; } }; template<size_t ALIGNMENT> class first_fit_heap { private: static constexpr size_t min_alignment() { return 16; } struct empty {}; template <size_t, bool, class T> struct align_helper : public T {}; template <size_t SIZE, class T> struct HEAP_PACKED align_helper<SIZE, true, T> : public T { char align_chars[SIZE - min_alignment()]; }; template <size_t MIN, size_t SIZE> using prepend_alignment_if_greater = align_helper<SIZE, (SIZE > MIN), empty>; class header_free; class header_used; class footer { public: size_t size() const { return s; } void size(size_t size) { s = size; } header_free* header() { return reinterpret_cast<header_free*>(reinterpret_cast<char *>(this) + sizeof(footer) - size() - sizeof(header_used)); } private: size_t s; }; class HEAP_PACKED header_used : private prepend_alignment_if_greater<16, ALIGNMENT> { private: enum { PREV_FREE_MASK = ~(1ul << (sizeof(size_t) * 8 - 1)), THIS_FREE_MASK = ~(1ul << (sizeof(size_t) * 8 - 2)), SIZE_MASK = (~PREV_FREE_MASK) | (~THIS_FREE_MASK), CANARY_VALUE = 0x1337133713371337ul, }; size_t raw {0}; volatile size_t canary {CANARY_VALUE}; public: header_used(const size_t size_) { size(size_); } size_t size() const { return raw & ~SIZE_MASK; } void size(size_t s) { ASSERT_HEAP((s & ~SIZE_MASK) == s); raw &= SIZE_MASK; raw |= s & ~SIZE_MASK; } bool prev_free() const { return raw & ~PREV_FREE_MASK; } void prev_free(bool val) { raw &= PREV_FREE_MASK; raw |= (~PREV_FREE_MASK) * val; } bool is_free() const { return raw & ~THIS_FREE_MASK; } void is_free(bool val) { raw &= THIS_FREE_MASK; raw |= (~THIS_FREE_MASK) * val; } bool canary_alive() { return canary == CANARY_VALUE; } header_used *following_block(const memory &mem) { auto *following = reinterpret_cast<header_used *>(reinterpret_cast<char *>(this) + sizeof(header_used) + size()); if (reinterpret_cast<size_t>(following) >= mem.end()) { return nullptr; } return following; } header_used *preceding_block(const memory& mem) { if (not prev_free()) { return nullptr; } footer *prev_footer = reinterpret_cast<footer *>(reinterpret_cast<char *>(this) - sizeof(footer)); ASSERT_HEAP(reinterpret_cast<size_t>(prev_footer) > mem.base()); return prev_footer->header(); } void *data_ptr() { return this+1; } }; class HEAP_PACKED header_free : public header_used { public: header_free(const size_t size) : header_used(size) { update_footer(); this->is_free(true); } header_free *next() const { return next_; } void next(header_free *val) { next_ = val; } footer *get_footer() { return reinterpret_cast<footer *>(reinterpret_cast<char *>(this) + sizeof(header_used) + this->size() - sizeof(footer)); } void update_footer() { get_footer()->size(this->size()); } header_free *next_ {nullptr}; }; class free_list_container { public: free_list_container(memory &mem_, header_free *root) : mem(mem_), list(root) { ASSERT_HEAP(ALIGNMENT != 0); ASSERT_HEAP(ALIGNMENT >= min_alignment()); ASSERT_HEAP((ALIGNMENT & (ALIGNMENT - 1)) == 0); ASSERT_HEAP(sizeof(header_used) == ALIGNMENT); ASSERT_HEAP(mem.size() != 0); ASSERT_HEAP((mem.base() & (ALIGNMENT - 1)) == 0); ASSERT_HEAP((mem.base() + mem.size()) > mem.base()); } class iterator { public: iterator(header_free *block_ = nullptr) : block(block_) {} iterator &operator++() { block = block->next(); ASSERT_HEAP(block ? block->canary_alive() : true); return *this; } header_free *operator*() const { return block; } bool operator!=(const iterator &other) const { return block != other.block; } bool operator==(const iterator &other) const { return not operator!=(other); } private: header_free *block; }; iterator begin() const { return iterator(list); } iterator end() const { return iterator(); } private: iterator position_for(header_free *val) { for (auto elem : *this) { if (not elem->next() or (elem->next() > val)) { return elem < val ? iterator(elem) : iterator(); } } return end(); } iterator insert_after(header_free *val, iterator other) { if (not val) { return {}; } ASSERT_HEAP(val > *other); if (other == end()) { // insert at list head val->next(list); val->is_free(true); val->update_footer(); list = val; } else { // insert block into chain auto *tmp = (*other)->next(); val->next(tmp); val->is_free(true); val->update_footer(); ASSERT_HEAP(val != *other); (*other)->next(val); } // update meta data of surrounding blocks auto *following = val->following_block(mem); const auto *preceding = val->preceding_block(mem); if (following) { following->prev_free(true); } if (preceding and preceding->is_free()) { val->prev_free(true); } return {val}; } iterator try_merge_back(iterator it) { auto *following = (*it)->following_block(mem); if (following and following->is_free()) { auto *following_free = static_cast<header_free*>(following); (*it)->next(following_free->next()); (*it)->size((*it)->size() + following_free->size() + sizeof(header_used)); (*it)->update_footer(); } return it; } iterator try_merge_front(iterator it) { if (not (*it)->prev_free()) { return it; } auto *preceding = static_cast<header_free *>((*it)->preceding_block(mem)); if (not preceding) { return it; } ASSERT_HEAP(preceding->is_free()); return try_merge_back({preceding}); } static constexpr size_t min_block_size() { return sizeof(header_free) - sizeof(header_used) + sizeof(footer); } size_t align(size_t size) const { size_t real_size {(size + ALIGNMENT - 1) & ~(ALIGNMENT - 1)}; return HEAP_MAX(min_block_size(), real_size); } bool fits(header_free &block, size_t size) const { ASSERT_HEAP(size >= min_block_size()); return block.size() >= size; } iterator first_free(size_t size, iterator &before) const { iterator before_ = end(); for (auto elem : *this) { if (fits(*elem, size)) { before = before_; return {elem}; } before_ = iterator(elem); } return {}; } public: iterator insert(header_free *val) { auto pos = position_for(val); auto elem = insert_after(val, pos); return try_merge_front(try_merge_back(elem)); } header_used *alloc(size_t size) { size = HEAP_MAX(size, ALIGNMENT); size = align(size); iterator prev; auto it = first_free(size, prev); if (it == end()) { return nullptr; } auto &block = **it; size_t size_remaining = block.size() - size; if (size_remaining < (sizeof(header_free) + sizeof(footer))) { // remaining size cannot hold another block, use entire space size += size_remaining; } else { // split block into two block.size(size); block.update_footer(); auto *new_block = new (block.following_block(mem)) header_free(size_remaining - sizeof(header_used)); new_block->next(block.next()); new_block->prev_free(true); block.next(new_block); } if (*prev) { (*prev)->next(block.next()); } else { list = block.next(); } auto *following = block.following_block(mem); if (following) { following->prev_free(false); } block.is_free(false); return &block; } bool ptr_in_range(void *p) { return reinterpret_cast<size_t>(p) >= mem.base() and reinterpret_cast<size_t>(p) < mem.end(); } private: memory &mem; header_free *list; }; private: free_list_container free_list; public: first_fit_heap(memory &mem_) : free_list(mem_, new(reinterpret_cast<void *>(mem_.base())) header_free(mem_.size() - sizeof(header_used))) { } void *alloc(size_t size) { auto *block = free_list.alloc(size); return block ? block->data_ptr() : nullptr; } void free(void *p) { header_free *header {reinterpret_cast<header_free *>(reinterpret_cast<char *>(p) - sizeof(header_used))}; if (not p or not free_list.ptr_in_range(header)) { return; } ASSERT_HEAP(header->canary_alive()); ASSERT_HEAP(not header->is_free()); free_list.insert(header); } size_t num_blocks() const { size_t cnt {0}; for (auto HEAP_UNUSED elem : free_list) { cnt++; } return cnt; } size_t free_mem() const { size_t size {0}; for (auto elem : free_list) { size += elem->size(); } return size; } constexpr size_t alignment() const { return ALIGNMENT; } }; <commit_msg>support a default alignment<commit_after>/* * MIT License * Copyright (c) 2016 Thomas Prescher * 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. */ #pragma once #include "heap_config.hpp" class memory { public: virtual ~memory() {} virtual size_t base() const = 0; virtual size_t size() const = 0; virtual size_t end() const = 0; }; class fixed_memory : public memory { private: size_t base_; size_t size_; public: fixed_memory(size_t base, size_t size) : base_(base) , size_(size) { } virtual size_t base() const { return base_; } virtual size_t size() const { return size_; }; virtual size_t end() const { return base_ + size_; } }; static constexpr size_t HEAP_MIN_ALIGNMENT = 16; template<size_t ALIGNMENT = HEAP_MIN_ALIGNMENT> class first_fit_heap { private: static constexpr size_t min_alignment() { return HEAP_MIN_ALIGNMENT; } struct empty {}; template <size_t, bool, class T> struct align_helper : public T {}; template <size_t SIZE, class T> struct HEAP_PACKED align_helper<SIZE, true, T> : public T { char align_chars[SIZE - min_alignment()]; }; template <size_t MIN, size_t SIZE> using prepend_alignment_if_greater = align_helper<SIZE, (SIZE > MIN), empty>; class header_free; class header_used; class footer { public: size_t size() const { return s; } void size(size_t size) { s = size; } header_free* header() { return reinterpret_cast<header_free*>(reinterpret_cast<char *>(this) + sizeof(footer) - size() - sizeof(header_used)); } private: size_t s; }; class HEAP_PACKED header_used : private prepend_alignment_if_greater<16, ALIGNMENT> { private: enum { PREV_FREE_MASK = ~(1ul << (sizeof(size_t) * 8 - 1)), THIS_FREE_MASK = ~(1ul << (sizeof(size_t) * 8 - 2)), SIZE_MASK = (~PREV_FREE_MASK) | (~THIS_FREE_MASK), CANARY_VALUE = 0x1337133713371337ul, }; size_t raw {0}; volatile size_t canary {CANARY_VALUE}; public: header_used(const size_t size_) { size(size_); } size_t size() const { return raw & ~SIZE_MASK; } void size(size_t s) { ASSERT_HEAP((s & ~SIZE_MASK) == s); raw &= SIZE_MASK; raw |= s & ~SIZE_MASK; } bool prev_free() const { return raw & ~PREV_FREE_MASK; } void prev_free(bool val) { raw &= PREV_FREE_MASK; raw |= (~PREV_FREE_MASK) * val; } bool is_free() const { return raw & ~THIS_FREE_MASK; } void is_free(bool val) { raw &= THIS_FREE_MASK; raw |= (~THIS_FREE_MASK) * val; } bool canary_alive() { return canary == CANARY_VALUE; } header_used *following_block(const memory &mem) { auto *following = reinterpret_cast<header_used *>(reinterpret_cast<char *>(this) + sizeof(header_used) + size()); if (reinterpret_cast<size_t>(following) >= mem.end()) { return nullptr; } return following; } header_used *preceding_block(const memory& mem) { if (not prev_free()) { return nullptr; } footer *prev_footer = reinterpret_cast<footer *>(reinterpret_cast<char *>(this) - sizeof(footer)); ASSERT_HEAP(reinterpret_cast<size_t>(prev_footer) > mem.base()); return prev_footer->header(); } void *data_ptr() { return this+1; } }; class HEAP_PACKED header_free : public header_used { public: header_free(const size_t size) : header_used(size) { update_footer(); this->is_free(true); } header_free *next() const { return next_; } void next(header_free *val) { next_ = val; } footer *get_footer() { return reinterpret_cast<footer *>(reinterpret_cast<char *>(this) + sizeof(header_used) + this->size() - sizeof(footer)); } void update_footer() { get_footer()->size(this->size()); } header_free *next_ {nullptr}; }; class free_list_container { public: free_list_container(memory &mem_, header_free *root) : mem(mem_), list(root) { ASSERT_HEAP(ALIGNMENT != 0); ASSERT_HEAP(ALIGNMENT >= min_alignment()); ASSERT_HEAP((ALIGNMENT & (ALIGNMENT - 1)) == 0); ASSERT_HEAP(sizeof(header_used) == ALIGNMENT); ASSERT_HEAP(mem.size() != 0); ASSERT_HEAP((mem.base() & (ALIGNMENT - 1)) == 0); ASSERT_HEAP((mem.base() + mem.size()) > mem.base()); } class iterator { public: iterator(header_free *block_ = nullptr) : block(block_) {} iterator &operator++() { block = block->next(); ASSERT_HEAP(block ? block->canary_alive() : true); return *this; } header_free *operator*() const { return block; } bool operator!=(const iterator &other) const { return block != other.block; } bool operator==(const iterator &other) const { return not operator!=(other); } private: header_free *block; }; iterator begin() const { return iterator(list); } iterator end() const { return iterator(); } private: iterator position_for(header_free *val) { for (auto elem : *this) { if (not elem->next() or (elem->next() > val)) { return elem < val ? iterator(elem) : iterator(); } } return end(); } iterator insert_after(header_free *val, iterator other) { if (not val) { return {}; } ASSERT_HEAP(val > *other); if (other == end()) { // insert at list head val->next(list); val->is_free(true); val->update_footer(); list = val; } else { // insert block into chain auto *tmp = (*other)->next(); val->next(tmp); val->is_free(true); val->update_footer(); ASSERT_HEAP(val != *other); (*other)->next(val); } // update meta data of surrounding blocks auto *following = val->following_block(mem); const auto *preceding = val->preceding_block(mem); if (following) { following->prev_free(true); } if (preceding and preceding->is_free()) { val->prev_free(true); } return {val}; } iterator try_merge_back(iterator it) { auto *following = (*it)->following_block(mem); if (following and following->is_free()) { auto *following_free = static_cast<header_free*>(following); (*it)->next(following_free->next()); (*it)->size((*it)->size() + following_free->size() + sizeof(header_used)); (*it)->update_footer(); } return it; } iterator try_merge_front(iterator it) { if (not (*it)->prev_free()) { return it; } auto *preceding = static_cast<header_free *>((*it)->preceding_block(mem)); if (not preceding) { return it; } ASSERT_HEAP(preceding->is_free()); return try_merge_back({preceding}); } static constexpr size_t min_block_size() { return sizeof(header_free) - sizeof(header_used) + sizeof(footer); } size_t align(size_t size) const { size_t real_size {(size + ALIGNMENT - 1) & ~(ALIGNMENT - 1)}; return HEAP_MAX(min_block_size(), real_size); } bool fits(header_free &block, size_t size) const { ASSERT_HEAP(size >= min_block_size()); return block.size() >= size; } iterator first_free(size_t size, iterator &before) const { iterator before_ = end(); for (auto elem : *this) { if (fits(*elem, size)) { before = before_; return {elem}; } before_ = iterator(elem); } return {}; } public: iterator insert(header_free *val) { auto pos = position_for(val); auto elem = insert_after(val, pos); return try_merge_front(try_merge_back(elem)); } header_used *alloc(size_t size) { size = HEAP_MAX(size, ALIGNMENT); size = align(size); iterator prev; auto it = first_free(size, prev); if (it == end()) { return nullptr; } auto &block = **it; size_t size_remaining = block.size() - size; if (size_remaining < (sizeof(header_free) + sizeof(footer))) { // remaining size cannot hold another block, use entire space size += size_remaining; } else { // split block into two block.size(size); block.update_footer(); auto *new_block = new (block.following_block(mem)) header_free(size_remaining - sizeof(header_used)); new_block->next(block.next()); new_block->prev_free(true); block.next(new_block); } if (*prev) { (*prev)->next(block.next()); } else { list = block.next(); } auto *following = block.following_block(mem); if (following) { following->prev_free(false); } block.is_free(false); return &block; } bool ptr_in_range(void *p) { return reinterpret_cast<size_t>(p) >= mem.base() and reinterpret_cast<size_t>(p) < mem.end(); } private: memory &mem; header_free *list; }; private: free_list_container free_list; public: first_fit_heap(memory &mem_) : free_list(mem_, new(reinterpret_cast<void *>(mem_.base())) header_free(mem_.size() - sizeof(header_used))) { } void *alloc(size_t size) { auto *block = free_list.alloc(size); return block ? block->data_ptr() : nullptr; } void free(void *p) { header_free *header {reinterpret_cast<header_free *>(reinterpret_cast<char *>(p) - sizeof(header_used))}; if (not p or not free_list.ptr_in_range(header)) { return; } ASSERT_HEAP(header->canary_alive()); ASSERT_HEAP(not header->is_free()); free_list.insert(header); } size_t num_blocks() const { size_t cnt {0}; for (auto HEAP_UNUSED elem : free_list) { cnt++; } return cnt; } size_t free_mem() const { size_t size {0}; for (auto elem : free_list) { size += elem->size(); } return size; } constexpr size_t alignment() const { return ALIGNMENT; } }; <|endoftext|>
<commit_before>/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2011-2016 Martin Raiber * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ #include "ServerIdentityMgr.h" #include "../Interface/Server.h" #include "../stringtools.h" #include <algorithm> #include "file_permissions.h" #include "../urbackupcommon/os_functions.h" const unsigned int ident_online_timeout=1*60*60*1000; //1h std::vector<SIdentity> ServerIdentityMgr::identities; IMutex *ServerIdentityMgr::mutex=NULL; IFileServ *ServerIdentityMgr::filesrv=NULL; std::vector<std::string> ServerIdentityMgr::new_identities; std::vector<SSessionIdentity> ServerIdentityMgr::session_identities; #ifdef _WIN32 const std::string server_ident_file="server_idents.txt"; const std::string server_session_ident_file="session_idents.txt"; const std::string server_new_ident_file="new_server_idents.txt"; #else const std::string server_ident_file="urbackup/server_idents.txt"; const std::string server_session_ident_file="urbackup/session_idents.txt"; const std::string server_new_ident_file="urbackup/new_server_idents.txt"; #endif void ServerIdentityMgr::init_mutex(void) { mutex=Server->createMutex(); } void ServerIdentityMgr::destroy_mutex(void) { Server->destroy(mutex); } void ServerIdentityMgr::addServerIdentity(const std::string &pIdentity, const SPublicKeys& pPublicKey) { IScopedLock lock(mutex); loadServerIdentities(); identities.push_back(SIdentity(pIdentity, pPublicKey)); if(pPublicKey.empty()) { filesrv->addIdentity("#I"+pIdentity+"#"); } writeServerIdentities(); } bool ServerIdentityMgr::checkServerSessionIdentity(const std::string &pIdentity, const std::string& endpoint) { IScopedLock lock(mutex); for(size_t i=0;i<session_identities.size();++i) { int64 time = session_identities[i].onlinetime; if(time<0) time*=-1; if(session_identities[i].ident==pIdentity && session_identities[i].endpoint==endpoint && Server->getTimeMS()-time<ident_online_timeout) { session_identities[i].onlinetime=Server->getTimeMS(); return true; } } return false; } bool ServerIdentityMgr::checkServerIdentity(const std::string &pIdentity) { IScopedLock lock(mutex); return std::find(identities.begin(), identities.end(), SIdentity(pIdentity))!=identities.end(); } void ServerIdentityMgr::loadServerIdentities(void) { IScopedLock lock(mutex); std::vector<SIdentity> old_identities=identities; identities.clear(); std::string data=getFile(server_ident_file); int numl=linecount(data); for(int i=0;i<=numl;++i) { std::string l=trim(getline(i, data)); if(!l.empty() && l[0]=='#') { continue; } if(l.size()>5) { size_t hashpos = l.find("#"); SPublicKeys pubkeys; if(hashpos!=std::string::npos) { str_map params; ParseParamStrHttp(l.substr(hashpos+1), &params); pubkeys = SPublicKeys(base64_decode_dash(params["pubkey"]), base64_decode_dash(params["pubkey_ecdsa409k1"])); l = l.substr(0, hashpos); } else { filesrv->addIdentity("#I"+l+"#"); } identities.push_back(SIdentity(l, pubkeys)); std::vector<SIdentity>::iterator it=std::find(old_identities.begin(), old_identities.end(), SIdentity(l)); if(it!=old_identities.end()) { identities[identities.size()-1].onlinetime = it->onlinetime; } } } new_identities.clear(); data=getFile(server_new_ident_file); numl=linecount(data); for(int i=0;i<=numl;++i) { std::string l=trim(getline(i, data)); if(l.size()>5) { new_identities.push_back(l); } } std::vector<SSessionIdentity> old_session_identities=session_identities; session_identities.clear(); data=getFile(server_session_ident_file); numl=linecount(data); for(int i=0;i<=numl;++i) { std::string l=trim(getline(i, data)); if(l.size()>5) { size_t hashpos = l.find("#"); if(hashpos==std::string::npos) continue; str_map params; ParseParamStrHttp(l.substr(hashpos+1), &params); l = l.substr(0, hashpos); SSessionIdentity session_ident(l, params["endpoint"], -1*Server->getTimeMS()); session_identities.push_back(session_ident); filesrv->addIdentity("#I"+l+"#"); std::vector<SSessionIdentity>::iterator it=std::find(old_session_identities.begin(), old_session_identities.end(), SSessionIdentity(session_ident)); if(it!=old_session_identities.end()) { session_identities[session_identities.size()-1].onlinetime = it->onlinetime; } } } } void ServerIdentityMgr::setFileServ(IFileServ *pFilesrv) { filesrv=pFilesrv; } size_t ServerIdentityMgr::numServerIdentities(void) { IScopedLock lock(mutex); return identities.size(); } bool ServerIdentityMgr::isNewIdentity(const std::string &pIdentity) { IScopedLock lock(mutex); if( std::find(new_identities.begin(), new_identities.end(), pIdentity)!=new_identities.end()) { return false; } else { new_identities.push_back(pIdentity); writeServerIdentities(); return true; } } void ServerIdentityMgr::writeServerIdentities(void) { IScopedLock lock(mutex); std::string idents; for(size_t i=0;i<identities.size();++i) { if(!idents.empty()) idents+="\r\n"; idents+=identities[i].ident; bool has_pubkey=false; if(!identities[i].publickeys.dsa_key.empty()) { idents+="#pubkey="+base64_encode_dash(identities[i].publickeys.dsa_key); has_pubkey=true; } if(!identities[i].publickeys.ecdsa409k1_key.empty()) { if(has_pubkey) { idents+="&"; } else { idents+="#"; } idents+="pubkey_ecdsa409k1="+base64_encode_dash(identities[i].publickeys.ecdsa409k1_key); } } write_file_admin_atomic(idents, server_ident_file); std::string new_idents; for(size_t i=0;i<new_identities.size();++i) { if(!new_idents.empty()) new_idents+="\r\n"; new_idents+=new_identities[i]; } write_file_admin_atomic(new_idents, server_new_ident_file); } bool ServerIdentityMgr::hasOnlineServer(void) { IScopedLock lock(mutex); int64 ctime=Server->getTimeMS(); for(size_t i=0;i<identities.size();++i) { if(identities[i].onlinetime!=0 && ctime-identities[i].onlinetime<ident_online_timeout) { return true; } } for(size_t i=0;i<session_identities.size();++i) { if(session_identities[i].onlinetime!=0 && ctime-session_identities[i].onlinetime<ident_online_timeout) { return true; } } return false; } SPublicKeys ServerIdentityMgr::getPublicKeys( const std::string &pIdentity ) { IScopedLock lock(mutex); std::vector<SIdentity>::iterator it = std::find(identities.begin(), identities.end(), SIdentity(pIdentity)); if(it!=identities.end()) { return it->publickeys; } return SPublicKeys(std::string(), std::string()); } bool ServerIdentityMgr::setPublicKeys( const std::string &pIdentity, const SPublicKeys &pPublicKeys ) { IScopedLock lock(mutex); std::vector<SIdentity>::iterator it = std::find(identities.begin(), identities.end(), SIdentity(pIdentity)); if(it!=identities.end()) { it->publickeys = pPublicKeys; if(!pPublicKeys.empty()) { filesrv->removeIdentity(pIdentity); } writeServerIdentities(); return true; } return false; } bool ServerIdentityMgr::hasPublicKey( const std::string &pIdentity ) { IScopedLock lock(mutex); std::vector<SIdentity>::iterator it = std::find(identities.begin(), identities.end(), SIdentity(pIdentity)); if(it!=identities.end()) { return !it->publickeys.empty(); } return false; } void ServerIdentityMgr::addSessionIdentity( const std::string &pIdentity, const std::string& endpoint ) { IScopedLock lock(mutex); SSessionIdentity session_ident(pIdentity, endpoint, Server->getTimeMS()); session_identities.push_back(session_ident); filesrv->addIdentity("#I"+pIdentity+"#"); writeSessionIdentities(); } void ServerIdentityMgr::writeSessionIdentities() { IScopedLock lock(mutex); const size_t max_session_identities=1000; size_t start=0; if(session_identities.size()>max_session_identities) { start=session_identities.size()-max_session_identities; } size_t written = 0; std::string idents; for(size_t i=session_identities.size(); i-- >0;) { int64 time = session_identities[i].onlinetime; if(time<0) time*=-1; if(Server->getTimeMS()-time<ident_online_timeout) { if(!idents.empty()) idents+="\r\n"; idents+=session_identities[i].ident; idents+="#endpoint="+session_identities[i].endpoint; ++written; if(written>=max_session_identities) { break; } } } write_file_admin_atomic(idents, server_session_ident_file); } bool ServerIdentityMgr::write_file_admin_atomic(const std::string & data, const std::string & fn) { if (!write_file_only_admin(data, fn + ".new")) { return false; } { std::auto_ptr<IFile> f(Server->openFile(fn + ".new", MODE_RW)); if (f.get() != NULL) f->Sync(); } return os_rename_file(fn + ".new", fn); } <commit_msg>Add missing include<commit_after>/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2011-2016 Martin Raiber * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ #include "ServerIdentityMgr.h" #include "../Interface/Server.h" #include "../stringtools.h" #include <algorithm> #include <memory> #include "file_permissions.h" #include "../urbackupcommon/os_functions.h" const unsigned int ident_online_timeout=1*60*60*1000; //1h std::vector<SIdentity> ServerIdentityMgr::identities; IMutex *ServerIdentityMgr::mutex=NULL; IFileServ *ServerIdentityMgr::filesrv=NULL; std::vector<std::string> ServerIdentityMgr::new_identities; std::vector<SSessionIdentity> ServerIdentityMgr::session_identities; #ifdef _WIN32 const std::string server_ident_file="server_idents.txt"; const std::string server_session_ident_file="session_idents.txt"; const std::string server_new_ident_file="new_server_idents.txt"; #else const std::string server_ident_file="urbackup/server_idents.txt"; const std::string server_session_ident_file="urbackup/session_idents.txt"; const std::string server_new_ident_file="urbackup/new_server_idents.txt"; #endif void ServerIdentityMgr::init_mutex(void) { mutex=Server->createMutex(); } void ServerIdentityMgr::destroy_mutex(void) { Server->destroy(mutex); } void ServerIdentityMgr::addServerIdentity(const std::string &pIdentity, const SPublicKeys& pPublicKey) { IScopedLock lock(mutex); loadServerIdentities(); identities.push_back(SIdentity(pIdentity, pPublicKey)); if(pPublicKey.empty()) { filesrv->addIdentity("#I"+pIdentity+"#"); } writeServerIdentities(); } bool ServerIdentityMgr::checkServerSessionIdentity(const std::string &pIdentity, const std::string& endpoint) { IScopedLock lock(mutex); for(size_t i=0;i<session_identities.size();++i) { int64 time = session_identities[i].onlinetime; if(time<0) time*=-1; if(session_identities[i].ident==pIdentity && session_identities[i].endpoint==endpoint && Server->getTimeMS()-time<ident_online_timeout) { session_identities[i].onlinetime=Server->getTimeMS(); return true; } } return false; } bool ServerIdentityMgr::checkServerIdentity(const std::string &pIdentity) { IScopedLock lock(mutex); return std::find(identities.begin(), identities.end(), SIdentity(pIdentity))!=identities.end(); } void ServerIdentityMgr::loadServerIdentities(void) { IScopedLock lock(mutex); std::vector<SIdentity> old_identities=identities; identities.clear(); std::string data=getFile(server_ident_file); int numl=linecount(data); for(int i=0;i<=numl;++i) { std::string l=trim(getline(i, data)); if(!l.empty() && l[0]=='#') { continue; } if(l.size()>5) { size_t hashpos = l.find("#"); SPublicKeys pubkeys; if(hashpos!=std::string::npos) { str_map params; ParseParamStrHttp(l.substr(hashpos+1), &params); pubkeys = SPublicKeys(base64_decode_dash(params["pubkey"]), base64_decode_dash(params["pubkey_ecdsa409k1"])); l = l.substr(0, hashpos); } else { filesrv->addIdentity("#I"+l+"#"); } identities.push_back(SIdentity(l, pubkeys)); std::vector<SIdentity>::iterator it=std::find(old_identities.begin(), old_identities.end(), SIdentity(l)); if(it!=old_identities.end()) { identities[identities.size()-1].onlinetime = it->onlinetime; } } } new_identities.clear(); data=getFile(server_new_ident_file); numl=linecount(data); for(int i=0;i<=numl;++i) { std::string l=trim(getline(i, data)); if(l.size()>5) { new_identities.push_back(l); } } std::vector<SSessionIdentity> old_session_identities=session_identities; session_identities.clear(); data=getFile(server_session_ident_file); numl=linecount(data); for(int i=0;i<=numl;++i) { std::string l=trim(getline(i, data)); if(l.size()>5) { size_t hashpos = l.find("#"); if(hashpos==std::string::npos) continue; str_map params; ParseParamStrHttp(l.substr(hashpos+1), &params); l = l.substr(0, hashpos); SSessionIdentity session_ident(l, params["endpoint"], -1*Server->getTimeMS()); session_identities.push_back(session_ident); filesrv->addIdentity("#I"+l+"#"); std::vector<SSessionIdentity>::iterator it=std::find(old_session_identities.begin(), old_session_identities.end(), SSessionIdentity(session_ident)); if(it!=old_session_identities.end()) { session_identities[session_identities.size()-1].onlinetime = it->onlinetime; } } } } void ServerIdentityMgr::setFileServ(IFileServ *pFilesrv) { filesrv=pFilesrv; } size_t ServerIdentityMgr::numServerIdentities(void) { IScopedLock lock(mutex); return identities.size(); } bool ServerIdentityMgr::isNewIdentity(const std::string &pIdentity) { IScopedLock lock(mutex); if( std::find(new_identities.begin(), new_identities.end(), pIdentity)!=new_identities.end()) { return false; } else { new_identities.push_back(pIdentity); writeServerIdentities(); return true; } } void ServerIdentityMgr::writeServerIdentities(void) { IScopedLock lock(mutex); std::string idents; for(size_t i=0;i<identities.size();++i) { if(!idents.empty()) idents+="\r\n"; idents+=identities[i].ident; bool has_pubkey=false; if(!identities[i].publickeys.dsa_key.empty()) { idents+="#pubkey="+base64_encode_dash(identities[i].publickeys.dsa_key); has_pubkey=true; } if(!identities[i].publickeys.ecdsa409k1_key.empty()) { if(has_pubkey) { idents+="&"; } else { idents+="#"; } idents+="pubkey_ecdsa409k1="+base64_encode_dash(identities[i].publickeys.ecdsa409k1_key); } } write_file_admin_atomic(idents, server_ident_file); std::string new_idents; for(size_t i=0;i<new_identities.size();++i) { if(!new_idents.empty()) new_idents+="\r\n"; new_idents+=new_identities[i]; } write_file_admin_atomic(new_idents, server_new_ident_file); } bool ServerIdentityMgr::hasOnlineServer(void) { IScopedLock lock(mutex); int64 ctime=Server->getTimeMS(); for(size_t i=0;i<identities.size();++i) { if(identities[i].onlinetime!=0 && ctime-identities[i].onlinetime<ident_online_timeout) { return true; } } for(size_t i=0;i<session_identities.size();++i) { if(session_identities[i].onlinetime!=0 && ctime-session_identities[i].onlinetime<ident_online_timeout) { return true; } } return false; } SPublicKeys ServerIdentityMgr::getPublicKeys( const std::string &pIdentity ) { IScopedLock lock(mutex); std::vector<SIdentity>::iterator it = std::find(identities.begin(), identities.end(), SIdentity(pIdentity)); if(it!=identities.end()) { return it->publickeys; } return SPublicKeys(std::string(), std::string()); } bool ServerIdentityMgr::setPublicKeys( const std::string &pIdentity, const SPublicKeys &pPublicKeys ) { IScopedLock lock(mutex); std::vector<SIdentity>::iterator it = std::find(identities.begin(), identities.end(), SIdentity(pIdentity)); if(it!=identities.end()) { it->publickeys = pPublicKeys; if(!pPublicKeys.empty()) { filesrv->removeIdentity(pIdentity); } writeServerIdentities(); return true; } return false; } bool ServerIdentityMgr::hasPublicKey( const std::string &pIdentity ) { IScopedLock lock(mutex); std::vector<SIdentity>::iterator it = std::find(identities.begin(), identities.end(), SIdentity(pIdentity)); if(it!=identities.end()) { return !it->publickeys.empty(); } return false; } void ServerIdentityMgr::addSessionIdentity( const std::string &pIdentity, const std::string& endpoint ) { IScopedLock lock(mutex); SSessionIdentity session_ident(pIdentity, endpoint, Server->getTimeMS()); session_identities.push_back(session_ident); filesrv->addIdentity("#I"+pIdentity+"#"); writeSessionIdentities(); } void ServerIdentityMgr::writeSessionIdentities() { IScopedLock lock(mutex); const size_t max_session_identities=1000; size_t start=0; if(session_identities.size()>max_session_identities) { start=session_identities.size()-max_session_identities; } size_t written = 0; std::string idents; for(size_t i=session_identities.size(); i-- >0;) { int64 time = session_identities[i].onlinetime; if(time<0) time*=-1; if(Server->getTimeMS()-time<ident_online_timeout) { if(!idents.empty()) idents+="\r\n"; idents+=session_identities[i].ident; idents+="#endpoint="+session_identities[i].endpoint; ++written; if(written>=max_session_identities) { break; } } } write_file_admin_atomic(idents, server_session_ident_file); } bool ServerIdentityMgr::write_file_admin_atomic(const std::string & data, const std::string & fn) { if (!write_file_only_admin(data, fn + ".new")) { return false; } { std::auto_ptr<IFile> f(Server->openFile(fn + ".new", MODE_RW)); if (f.get() != NULL) f->Sync(); } return os_rename_file(fn + ".new", fn); } <|endoftext|>
<commit_before>#ifndef string_hh_INCLUDED #define string_hh_INCLUDED #include "units.hh" #include "utf8.hh" #include "hash.hh" #include "vector.hh" #include <string> #include <climits> namespace Kakoune { class StringView; template<typename Type, typename CharType> class StringOps { public: using value_type = CharType; [[gnu::always_inline]] friend bool operator==(const Type& lhs, const Type& rhs) { return lhs.length() == rhs.length() and std::equal(lhs.begin(), lhs.end(), rhs.begin()); } [[gnu::always_inline]] friend bool operator!=(const Type& lhs, const Type& rhs) { return not (lhs == rhs); } friend bool operator<(const Type& lhs, const Type& rhs) { return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); } friend inline size_t hash_value(const Type& str) { return hash_data(str.data(), (int)str.length()); } using iterator = CharType*; using const_iterator = const CharType*; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; [[gnu::always_inline]] iterator begin() { return type().data(); } [[gnu::always_inline]] const_iterator begin() const { return type().data(); } [[gnu::always_inline]] iterator end() { return type().data() + (int)type().length(); } [[gnu::always_inline]] const_iterator end() const { return type().data() + (int)type().length(); } reverse_iterator rbegin() { return reverse_iterator{end()}; } const_reverse_iterator rbegin() const { return const_reverse_iterator{end()}; } reverse_iterator rend() { return reverse_iterator{begin()}; } const_reverse_iterator rend() const { return const_reverse_iterator{begin()}; } CharType& front() { return *type().data(); } const CharType& front() const { return *type().data(); } CharType& back() { return type().data()[(int)type().length() - 1]; } const CharType& back() const { return type().data()[(int)type().length() - 1]; } [[gnu::always_inline]] CharType& operator[](ByteCount pos) { return type().data()[(int)pos]; } [[gnu::always_inline]] const CharType& operator[](ByteCount pos) const { return type().data()[(int)pos]; } Codepoint operator[](CharCount pos) const { return utf8::codepoint(utf8::advance(begin(), end(), pos), end()); } CharCount char_length() const { return utf8::distance(begin(), end()); } [[gnu::always_inline]] bool empty() const { return type().length() == 0_byte; } ByteCount byte_count_to(CharCount count) const { return utf8::advance(begin(), end(), (int)count) - begin(); } CharCount char_count_to(ByteCount count) const { return utf8::distance(begin(), begin() + (int)count); } StringView substr(ByteCount from, ByteCount length = INT_MAX) const; StringView substr(CharCount from, CharCount length = INT_MAX) const; private: [[gnu::always_inline]] Type& type() { return *static_cast<Type*>(this); } [[gnu::always_inline]] const Type& type() const { return *static_cast<const Type*>(this); } }; class String : public StringOps<String, char> { public: using Content = std::basic_string<char, std::char_traits<char>, Allocator<char, MemoryDomain::String>>; String() {} String(const char* content) : m_data(content) {} explicit String(char content, CharCount count = 1) : m_data((size_t)(int)count, content) {} explicit String(Codepoint cp, CharCount count = 1) { while (count-- > 0) utf8::dump(std::back_inserter(*this), cp); } template<typename Iterator> String(Iterator begin, Iterator end) : m_data(begin, end) {} [[gnu::always_inline]] char* data() { return &m_data[0]; } [[gnu::always_inline]] const char* data() const { return m_data.data(); } [[gnu::always_inline]] ByteCount length() const { return (int)m_data.length(); } [[gnu::always_inline]] const char* c_str() const { return m_data.c_str(); } [[gnu::always_inline]] void append(const char* data, ByteCount count) { m_data.append(data, (size_t)(int)count); } void push_back(char c) { m_data.push_back(c); } void resize(ByteCount size) { m_data.resize((size_t)(int)size); } void reserve(ByteCount size) { m_data.reserve((size_t)(int)size); } private: Content m_data; }; class StringView : public StringOps<StringView, const char> { public: constexpr StringView() = default; constexpr StringView(const char* data, ByteCount length) : m_data{data}, m_length{length} {} constexpr StringView(const char* data) : m_data{data}, m_length{strlen(data)} {} constexpr StringView(const char* begin, const char* end) : m_data{begin}, m_length{(int)(end - begin)} {} StringView(const String& str) : m_data{str.data()}, m_length{(int)str.length()} {} StringView(const char& c) : m_data(&c), m_length(1) {} StringView(int c) = delete; [[gnu::always_inline]] constexpr const char* data() const { return m_data; } [[gnu::always_inline]] constexpr ByteCount length() const { return m_length; } String str() const { return {begin(), end()}; } struct ZeroTerminatedString { ZeroTerminatedString(const char* begin, const char* end) { if (*end == '\0') unowned = begin; else owned = String::Content(begin, end); } operator const char*() const { return unowned ? unowned : owned.c_str(); } private: String::Content owned; const char* unowned = nullptr; }; ZeroTerminatedString zstr() const { return {begin(), end()}; } private: static constexpr ByteCount strlen(const char* s) { return *s == 0 ? 0 : strlen(s+1) + 1; } const char* m_data = nullptr; ByteCount m_length = 0; }; template<typename Type, typename CharType> inline StringView StringOps<Type, CharType>::substr(ByteCount from, ByteCount length) const { if (length < 0) length = INT_MAX; return StringView{ type().data() + (int)from, std::min(type().length() - from, length) }; } template<typename Type, typename CharType> inline StringView StringOps<Type, CharType>::substr(CharCount from, CharCount length) const { if (length < 0) length = INT_MAX; auto beg = utf8::advance(begin(), end(), (int)from); return StringView{ beg, utf8::advance(beg, end(), length) }; } inline String& operator+=(String& lhs, StringView rhs) { lhs.append(rhs.data(), rhs.length()); return lhs; } inline String operator+(StringView lhs, StringView rhs) { String res; res.reserve((int)(lhs.length() + rhs.length())); res.append(lhs.data(), lhs.length()); res.append(rhs.data(), rhs.length()); return res; } Vector<String> split(StringView str, char separator, char escape); Vector<StringView> split(StringView str, char separator); String escape(StringView str, StringView characters, char escape); String unescape(StringView str, StringView characters, char escape); String indent(StringView str, StringView indent = " "); template<typename Container> String join(const Container& container, char joiner, bool esc_joiner = true) { String res; for (const auto& str : container) { if (not res.empty()) res += joiner; res += esc_joiner ? escape(str, joiner, '\\') : str; } return res; } inline String operator"" _str(const char* str, size_t) { return String(str); } inline String codepoint_to_str(Codepoint cp) { String str; utf8::dump(std::back_inserter(str), cp); return str; } int str_to_int(StringView str); String to_string(int val); String to_string(size_t val); String to_string(float val); template<typename RealType, typename ValueType> String to_string(const StronglyTypedNumber<RealType, ValueType>& val) { return to_string((ValueType)val); } inline bool prefix_match(StringView str, StringView prefix) { return str.substr(0_byte, prefix.length()) == prefix; } bool subsequence_match(StringView str, StringView subseq); String expand_tabs(StringView line, CharCount tabstop, CharCount col = 0); Vector<StringView> wrap_lines(StringView text, CharCount max_width); } #endif // string_hh_INCLUDED <commit_msg>Always go through StringView to compare strings<commit_after>#ifndef string_hh_INCLUDED #define string_hh_INCLUDED #include "units.hh" #include "utf8.hh" #include "hash.hh" #include "vector.hh" #include <string> #include <climits> namespace Kakoune { class StringView; template<typename Type, typename CharType> class StringOps { public: using value_type = CharType; friend inline size_t hash_value(const Type& str) { return hash_data(str.data(), (int)str.length()); } using iterator = CharType*; using const_iterator = const CharType*; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; [[gnu::always_inline]] iterator begin() { return type().data(); } [[gnu::always_inline]] const_iterator begin() const { return type().data(); } [[gnu::always_inline]] iterator end() { return type().data() + (int)type().length(); } [[gnu::always_inline]] const_iterator end() const { return type().data() + (int)type().length(); } reverse_iterator rbegin() { return reverse_iterator{end()}; } const_reverse_iterator rbegin() const { return const_reverse_iterator{end()}; } reverse_iterator rend() { return reverse_iterator{begin()}; } const_reverse_iterator rend() const { return const_reverse_iterator{begin()}; } CharType& front() { return *type().data(); } const CharType& front() const { return *type().data(); } CharType& back() { return type().data()[(int)type().length() - 1]; } const CharType& back() const { return type().data()[(int)type().length() - 1]; } [[gnu::always_inline]] CharType& operator[](ByteCount pos) { return type().data()[(int)pos]; } [[gnu::always_inline]] const CharType& operator[](ByteCount pos) const { return type().data()[(int)pos]; } Codepoint operator[](CharCount pos) const { return utf8::codepoint(utf8::advance(begin(), end(), pos), end()); } CharCount char_length() const { return utf8::distance(begin(), end()); } [[gnu::always_inline]] bool empty() const { return type().length() == 0_byte; } ByteCount byte_count_to(CharCount count) const { return utf8::advance(begin(), end(), (int)count) - begin(); } CharCount char_count_to(ByteCount count) const { return utf8::distance(begin(), begin() + (int)count); } StringView substr(ByteCount from, ByteCount length = INT_MAX) const; StringView substr(CharCount from, CharCount length = INT_MAX) const; private: [[gnu::always_inline]] Type& type() { return *static_cast<Type*>(this); } [[gnu::always_inline]] const Type& type() const { return *static_cast<const Type*>(this); } }; class String : public StringOps<String, char> { public: using Content = std::basic_string<char, std::char_traits<char>, Allocator<char, MemoryDomain::String>>; String() {} String(const char* content) : m_data(content) {} explicit String(char content, CharCount count = 1) : m_data((size_t)(int)count, content) {} explicit String(Codepoint cp, CharCount count = 1) { while (count-- > 0) utf8::dump(std::back_inserter(*this), cp); } template<typename Iterator> String(Iterator begin, Iterator end) : m_data(begin, end) {} [[gnu::always_inline]] char* data() { return &m_data[0]; } [[gnu::always_inline]] const char* data() const { return m_data.data(); } [[gnu::always_inline]] ByteCount length() const { return (int)m_data.length(); } [[gnu::always_inline]] const char* c_str() const { return m_data.c_str(); } [[gnu::always_inline]] void append(const char* data, ByteCount count) { m_data.append(data, (size_t)(int)count); } void push_back(char c) { m_data.push_back(c); } void resize(ByteCount size) { m_data.resize((size_t)(int)size); } void reserve(ByteCount size) { m_data.reserve((size_t)(int)size); } private: Content m_data; }; class StringView : public StringOps<StringView, const char> { public: constexpr StringView() = default; constexpr StringView(const char* data, ByteCount length) : m_data{data}, m_length{length} {} constexpr StringView(const char* data) : m_data{data}, m_length{strlen(data)} {} constexpr StringView(const char* begin, const char* end) : m_data{begin}, m_length{(int)(end - begin)} {} StringView(const String& str) : m_data{str.data()}, m_length{(int)str.length()} {} StringView(const char& c) : m_data(&c), m_length(1) {} StringView(int c) = delete; [[gnu::always_inline]] constexpr const char* data() const { return m_data; } [[gnu::always_inline]] constexpr ByteCount length() const { return m_length; } String str() const { return {begin(), end()}; } struct ZeroTerminatedString { ZeroTerminatedString(const char* begin, const char* end) { if (*end == '\0') unowned = begin; else owned = String::Content(begin, end); } operator const char*() const { return unowned ? unowned : owned.c_str(); } private: String::Content owned; const char* unowned = nullptr; }; ZeroTerminatedString zstr() const { return {begin(), end()}; } private: static constexpr ByteCount strlen(const char* s) { return *s == 0 ? 0 : strlen(s+1) + 1; } const char* m_data = nullptr; ByteCount m_length = 0; }; template<typename Type, typename CharType> inline StringView StringOps<Type, CharType>::substr(ByteCount from, ByteCount length) const { if (length < 0) length = INT_MAX; return StringView{ type().data() + (int)from, std::min(type().length() - from, length) }; } template<typename Type, typename CharType> inline StringView StringOps<Type, CharType>::substr(CharCount from, CharCount length) const { if (length < 0) length = INT_MAX; auto beg = utf8::advance(begin(), end(), (int)from); return StringView{ beg, utf8::advance(beg, end(), length) }; } inline String& operator+=(String& lhs, StringView rhs) { lhs.append(rhs.data(), rhs.length()); return lhs; } inline String operator+(StringView lhs, StringView rhs) { String res; res.reserve((int)(lhs.length() + rhs.length())); res.append(lhs.data(), lhs.length()); res.append(rhs.data(), rhs.length()); return res; } [[gnu::always_inline]] inline bool operator==(const StringView& lhs, const StringView& rhs) { return lhs.length() == rhs.length() and std::equal(lhs.begin(), lhs.end(), rhs.begin()); } [[gnu::always_inline]] inline bool operator!=(const StringView& lhs, const StringView& rhs) { return not (lhs == rhs); } inline bool operator<(const StringView& lhs, const StringView& rhs) { return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); } Vector<String> split(StringView str, char separator, char escape); Vector<StringView> split(StringView str, char separator); String escape(StringView str, StringView characters, char escape); String unescape(StringView str, StringView characters, char escape); String indent(StringView str, StringView indent = " "); template<typename Container> String join(const Container& container, char joiner, bool esc_joiner = true) { String res; for (const auto& str : container) { if (not res.empty()) res += joiner; res += esc_joiner ? escape(str, joiner, '\\') : str; } return res; } inline String operator"" _str(const char* str, size_t) { return String(str); } inline String codepoint_to_str(Codepoint cp) { String str; utf8::dump(std::back_inserter(str), cp); return str; } int str_to_int(StringView str); String to_string(int val); String to_string(size_t val); String to_string(float val); template<typename RealType, typename ValueType> String to_string(const StronglyTypedNumber<RealType, ValueType>& val) { return to_string((ValueType)val); } inline bool prefix_match(StringView str, StringView prefix) { return str.substr(0_byte, prefix.length()) == prefix; } bool subsequence_match(StringView str, StringView subseq); String expand_tabs(StringView line, CharCount tabstop, CharCount col = 0); Vector<StringView> wrap_lines(StringView text, CharCount max_width); } #endif // string_hh_INCLUDED <|endoftext|>
<commit_before>//****************************************************************** // // Copyright 2016 Intel Corporation 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 <boost/algorithm/string/join.hpp> #include <boost/tokenizer.hpp> #include <iostream> #include <poll.h> #include "ocstack.h" #include "ocpayload.h" #include "payload_logging.h" #include "cbor.h" #include "cborjson.h" #include "cJSON.h" extern "C" OCStackResult OCParsePayload(OCPayload **outPayload, OCPayloadType payloadType, const uint8_t *payload, size_t payloadSize); extern "C" OCStackResult OCConvertPayload(OCPayload *payload, uint8_t **outPayload, size_t *size); static CborError ConvertJSONToCBOR(CborEncoder *encoder, cJSON *json) { CborEncoder containerEncoder; CborError err = CborNoError; if (json->string) { err = cbor_encode_text_stringz(encoder, json->string); } switch (json->type) { case cJSON_False: err = cbor_encode_boolean(encoder, false); break; case cJSON_True: err = cbor_encode_boolean(encoder, true); break; case cJSON_NULL: err = cbor_encode_null(encoder); break; case cJSON_Number: err = cbor_encode_double(encoder, json->valuedouble); break; case cJSON_String: err = cbor_encode_text_stringz(encoder, json->valuestring); break; case cJSON_Array: err = cbor_encoder_create_array(encoder, &containerEncoder, cJSON_GetArraySize(json)); for (cJSON *child = json->child; err == CborNoError && child; child = child->next) { err = ConvertJSONToCBOR(&containerEncoder, child); } if (err == CborNoError) { err = cbor_encoder_close_container(encoder, &containerEncoder); } break; case cJSON_Object: err = cbor_encoder_create_map(encoder, &containerEncoder, cJSON_GetArraySize(json)); for (cJSON *child = json->child; err == CborNoError && child; child = child->next) { err = ConvertJSONToCBOR(&containerEncoder, child); } if (err == CborNoError) { err = cbor_encoder_close_container(encoder, &containerEncoder); } break; } return err; } static size_t ConvertJSONToCBOR(const char *jsonStr, uint8_t *buffer, size_t size) { CborEncoder encoder; CborError err = CborNoError; cbor_encoder_init(&encoder, buffer, size, 0); cJSON *json = cJSON_Parse(jsonStr); for (; err == CborNoError && json; json = json->next) { err = ConvertJSONToCBOR(&encoder, json); } if (json) { cJSON_Delete(json); } if (err == CborNoError) { return cbor_encoder_get_buffer_size(&encoder, buffer); } else { return 0; } } static void LogResponse(OCMethod method, OCClientResponse *response) { if (!response) { return; } switch (method) { case OC_REST_DISCOVER: case OC_REST_GET: case OC_REST_OBSERVE: std::cout << "get"; break; case OC_REST_POST: std::cout << "post"; break; default: std::cout << method; } std::cout << " - " << response->result << std::endl; std::cout << "Uri-Host: " << response->devAddr.addr << std::endl << "Uri-Port: " << response->devAddr.port << std::endl << "Uri-Path: " << (response->resourceUri ? response->resourceUri : "") << std::endl; if (method & OC_REST_OBSERVE) { std::cout << "Observe: " << response->sequenceNumber << std::endl; } uint8_t *buffer = NULL; size_t size; OCStackResult result = OCConvertPayload(response->payload, &buffer, &size); if (result != OC_STACK_OK) { return; } CborParser parser; CborValue it; CborError err = cbor_parser_init(buffer, size, CborConvertDefaultFlags, &parser, &it); char value[8192]; FILE *fp = fmemopen(value, 8192, "w"); while (err == CborNoError) { err = cbor_value_to_json_advance(fp, &it, CborConvertDefaultFlags); } fclose(fp); cJSON *json = cJSON_Parse(value); char *valueStr = cJSON_Print(json); std::cout << valueStr << std::endl; free(valueStr); cJSON_Delete(json); OICFree(buffer); } #define DEFAULT_CONTEXT_VALUE 0x99 struct Resource { OCDevAddr host; std::string uri; }; static std::vector<Resource> g_resources; static OCStackApplicationResult onDiscover(void *, OCDoHandle, OCClientResponse *response) { LogResponse(OC_REST_DISCOVER, response); if (response) { OCDiscoveryPayload *payload = (OCDiscoveryPayload *) response->payload; while (payload) { Resource r; r.host = response->devAddr; r.uri = payload->uri ? payload->uri : "/oic/res"; g_resources.push_back(r); OCResourcePayload *resource = (OCResourcePayload *) payload->resources; while (resource) { Resource r; r.host = response->devAddr; r.uri = resource->uri; g_resources.push_back(r); resource = resource->next; } payload = payload->next; } } return OC_STACK_KEEP_TRANSACTION; } static OCStackApplicationResult onGet(void *, OCDoHandle, OCClientResponse *response) { LogResponse(OC_REST_GET, response); return OC_STACK_DELETE_TRANSACTION; } static OCStackApplicationResult onPost(void *, OCDoHandle, OCClientResponse *response) { LogResponse(OC_REST_POST, response); return OC_STACK_DELETE_TRANSACTION; } static OCStackApplicationResult onObserve(void *, OCDoHandle, OCClientResponse *response) { LogResponse(OC_REST_OBSERVE, response); if (response->payload) { return OC_STACK_KEEP_TRANSACTION; } else { return OC_STACK_DELETE_TRANSACTION; } } static void usage() { std::cout << "Usage:" << std::endl << std::endl << "Find smart home bridge devices:" << std::endl << " find /oic/res?rt=oic.d.bridge" << std::endl << "Find light devices:" << std::endl << " find /oic/res?rt=oic.d.light" << std::endl << "Find all devices:" << std::endl << " find /oic/res" << std::endl << std::endl << "List all found devices:" << std::endl << " list" << std::endl << std::endl << "Get attributes of a resource:" << std::endl << " get INDEX [QUERY PARAM]..." << std::endl << std::endl << "Post attributes of a resource:" << std::endl << " post INDEX [QUERY PARAM]... [JSON]" << std::endl << std::endl << "Observe attributes of a resource:" << std::endl << " observe INDEX [QUERY PARAM]" << std::endl; } int main(int, char **) { std::cout.setf(std::ios::boolalpha); if (OCInit1(OC_CLIENT, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS) != OC_STACK_OK) { std::cerr << "OCStack init error" << std::endl; return EXIT_FAILURE; } for (;;) { struct pollfd pfd = { STDIN_FILENO, POLLIN, 0 }; int ret = poll(&pfd, 1, 1000); if (ret != 1) { if (OCProcess() != OC_STACK_OK) { std::cerr << "OCStack process error" << std::endl; return 0; } continue; } std::string line; std::getline(std::cin, line); boost::char_separator<char> sep(" "); boost::tokenizer<boost::char_separator<char>> tokens(line, sep); auto token = tokens.begin(); if (token == tokens.end()) { usage(); continue; } std::string cmd = *token++; if (cmd == "list") { for (size_t i = 0; i < g_resources.size(); ++i) { std::cout << "[" << i << "]" << std::endl; std::cout << "\tcoap://" << g_resources[i].host.addr << ":" << g_resources[i].host.port << g_resources[i].uri << std::endl; } } else if (cmd == "find") { std::string requestURI = *token++; OCCallbackData cbData; cbData.cb = onDiscover; cbData.context = (void *)DEFAULT_CONTEXT_VALUE; cbData.cd = NULL; OCStackResult result = OCDoResource(NULL, OC_REST_DISCOVER, requestURI.c_str(), NULL, 0, CT_DEFAULT, OC_HIGH_QOS, &cbData, NULL, 0); std::cout << "find " << requestURI << " - " << result << std::endl; } else if (cmd == "get") { size_t i = std::stoi(*token++); std::string query; while (token != tokens.end()) { std::string str = *token++; if (str.find('=') != std::string::npos) { if (!query.empty()) { query += ";"; } query += str; } } std::string uri = g_resources[i].uri; if (!query.empty()) { uri += "?" + query; } OCCallbackData cbData; cbData.cb = onGet; cbData.context = (void *)DEFAULT_CONTEXT_VALUE; cbData.cd = NULL; OCStackResult result = OCDoResource(NULL, OC_REST_GET, uri.c_str(), &g_resources[i].host, NULL, CT_DEFAULT, OC_HIGH_QOS, &cbData, NULL, 0); std::cout << "get " << g_resources[i].host.addr << ":" << g_resources[i].host.port << g_resources[i].uri << " - " << result << std::endl; } else if (cmd == "put") { // TODO } else if (cmd == "post") { size_t i = std::stoi(*token++); std::string query, body; while (token != tokens.end()) { std::string str = *token++; if (str.find('=') != std::string::npos) { if (!query.empty()) { query += ";"; } query += str; } else { body += str; } } std::string uri = g_resources[i].uri; if (!query.empty()) { uri += "?" + query; } OCRepPayload *payload = NULL; size_t size = 8192; uint8_t buffer[8192]; size = ConvertJSONToCBOR(body.c_str(), buffer, size); if (size) { payload = OCRepPayloadCreate(); OCParsePayload((OCPayload **) &payload, PAYLOAD_TYPE_REPRESENTATION, buffer, size); } OCCallbackData cbData; cbData.cb = onPost; cbData.context = (void *)DEFAULT_CONTEXT_VALUE; cbData.cd = NULL; OCStackResult result = OCDoResource(NULL, OC_REST_POST, uri.c_str(), &g_resources[i].host, (OCPayload *) payload, CT_DEFAULT, OC_HIGH_QOS, &cbData, NULL, 0); std::cout << "post " << g_resources[i].host.addr << ":" << g_resources[i].host.port << g_resources[i].uri << " - " << result << std::endl; } else if (cmd == "observe") { size_t i = std::stoi(*token++); std::string query; while (token != tokens.end()) { std::string str = *token++; if (str.find('=') != std::string::npos) { if (!query.empty()) { query += ";"; } query += str; } } std::string uri = g_resources[i].uri; if (!query.empty()) { uri += "?" + query; } OCDoHandle handle; OCCallbackData cbData; cbData.cb = onObserve; cbData.context = (void *)DEFAULT_CONTEXT_VALUE; cbData.cd = NULL; OCStackResult result = OCDoResource(&handle, OC_REST_OBSERVE, uri.c_str(), &g_resources[i].host, NULL, CT_DEFAULT, OC_HIGH_QOS, &cbData, NULL, 0); std::cout << "observe " << g_resources[i].host.addr << ":" << g_resources[i].host.port << g_resources[i].uri << " (" << handle << ") - " << result << std::endl; } else if (cmd == "cancel") { OCDoHandle handle = (OCDoHandle) (intptr_t) std::stoi(*token++, 0, 0); OCStackResult result = OCCancel(handle, OC_HIGH_QOS, NULL, 0); std::cout << "cancel (" << handle << ") - " << result << std::endl; } else if (cmd == "delete") { // TODO } else if (cmd == "quit") { break; } } if (OCStop() != OC_STACK_OK) { std::cerr << "OCStack stop error" << std::endl; } return EXIT_SUCCESS; } <commit_msg>Allow query keys with no values in occlient test app.<commit_after>//****************************************************************** // // Copyright 2016 Intel Corporation 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 <boost/algorithm/string/join.hpp> #include <boost/tokenizer.hpp> #include <iostream> #include <poll.h> #include "ocstack.h" #include "ocpayload.h" #include "payload_logging.h" #include "cbor.h" #include "cborjson.h" #include "cJSON.h" extern "C" OCStackResult OCParsePayload(OCPayload **outPayload, OCPayloadType payloadType, const uint8_t *payload, size_t payloadSize); extern "C" OCStackResult OCConvertPayload(OCPayload *payload, uint8_t **outPayload, size_t *size); static CborError ConvertJSONToCBOR(CborEncoder *encoder, cJSON *json) { CborEncoder containerEncoder; CborError err = CborNoError; if (json->string) { err = cbor_encode_text_stringz(encoder, json->string); } switch (json->type) { case cJSON_False: err = cbor_encode_boolean(encoder, false); break; case cJSON_True: err = cbor_encode_boolean(encoder, true); break; case cJSON_NULL: err = cbor_encode_null(encoder); break; case cJSON_Number: err = cbor_encode_double(encoder, json->valuedouble); break; case cJSON_String: err = cbor_encode_text_stringz(encoder, json->valuestring); break; case cJSON_Array: err = cbor_encoder_create_array(encoder, &containerEncoder, cJSON_GetArraySize(json)); for (cJSON *child = json->child; err == CborNoError && child; child = child->next) { err = ConvertJSONToCBOR(&containerEncoder, child); } if (err == CborNoError) { err = cbor_encoder_close_container(encoder, &containerEncoder); } break; case cJSON_Object: err = cbor_encoder_create_map(encoder, &containerEncoder, cJSON_GetArraySize(json)); for (cJSON *child = json->child; err == CborNoError && child; child = child->next) { err = ConvertJSONToCBOR(&containerEncoder, child); } if (err == CborNoError) { err = cbor_encoder_close_container(encoder, &containerEncoder); } break; } return err; } static size_t ConvertJSONToCBOR(const char *jsonStr, uint8_t *buffer, size_t size) { CborEncoder encoder; CborError err = CborNoError; cbor_encoder_init(&encoder, buffer, size, 0); cJSON *json = cJSON_Parse(jsonStr); for (; err == CborNoError && json; json = json->next) { err = ConvertJSONToCBOR(&encoder, json); } if (json) { cJSON_Delete(json); } if (err == CborNoError) { return cbor_encoder_get_buffer_size(&encoder, buffer); } else { return 0; } } static void LogResponse(OCMethod method, OCClientResponse *response) { if (!response) { return; } switch (method) { case OC_REST_DISCOVER: case OC_REST_GET: case OC_REST_OBSERVE: std::cout << "GET"; break; case OC_REST_POST: std::cout << "POST"; break; default: std::cout << method; break; } std::cout << " - " << response->result << std::endl; std::cout << "Uri-Host: " << response->devAddr.addr << std::endl << "Uri-Port: " << response->devAddr.port << std::endl << "Uri-Path: " << (response->resourceUri ? response->resourceUri : "") << std::endl; if (method & OC_REST_OBSERVE) { std::cout << "Observe: " << response->sequenceNumber << std::endl; } uint8_t *buffer = NULL; size_t size; OCStackResult result = OCConvertPayload(response->payload, &buffer, &size); if (result != OC_STACK_OK) { return; } CborParser parser; CborValue it; CborError err = cbor_parser_init(buffer, size, CborConvertDefaultFlags, &parser, &it); char value[8192]; FILE *fp = fmemopen(value, 8192, "w"); while (err == CborNoError) { err = cbor_value_to_json_advance(fp, &it, CborConvertDefaultFlags); } fclose(fp); cJSON *json = cJSON_Parse(value); char *valueStr = cJSON_Print(json); std::cout << valueStr << std::endl; free(valueStr); cJSON_Delete(json); OICFree(buffer); } #define DEFAULT_CONTEXT_VALUE 0x99 struct Resource { OCDevAddr host; std::string uri; }; static std::vector<Resource> g_resources; static OCStackApplicationResult onDiscover(void *, OCDoHandle, OCClientResponse *response) { LogResponse(OC_REST_DISCOVER, response); if (response) { OCDiscoveryPayload *payload = (OCDiscoveryPayload *) response->payload; while (payload) { Resource r; r.host = response->devAddr; r.uri = payload->uri ? payload->uri : "/oic/res"; g_resources.push_back(r); OCResourcePayload *resource = (OCResourcePayload *) payload->resources; while (resource) { Resource r; r.host = response->devAddr; r.uri = resource->uri; g_resources.push_back(r); resource = resource->next; } payload = payload->next; } } return OC_STACK_KEEP_TRANSACTION; } static OCStackApplicationResult onGet(void *, OCDoHandle, OCClientResponse *response) { LogResponse(OC_REST_GET, response); return OC_STACK_DELETE_TRANSACTION; } static OCStackApplicationResult onPost(void *, OCDoHandle, OCClientResponse *response) { LogResponse(OC_REST_POST, response); return OC_STACK_DELETE_TRANSACTION; } static OCStackApplicationResult onObserve(void *, OCDoHandle, OCClientResponse *response) { LogResponse(OC_REST_OBSERVE, response); if (response->payload) { return OC_STACK_KEEP_TRANSACTION; } else { return OC_STACK_DELETE_TRANSACTION; } } static void usage() { std::cout << "Usage:" << std::endl << std::endl << "Find smart home bridge devices:" << std::endl << " find /oic/res?rt=oic.d.bridge" << std::endl << "Find light devices:" << std::endl << " find /oic/res?rt=oic.d.light" << std::endl << "Find all devices:" << std::endl << " find /oic/res" << std::endl << std::endl << "List all found devices:" << std::endl << " list" << std::endl << std::endl << "Get attributes of a resource:" << std::endl << " get INDEX [QUERY PARAM]..." << std::endl << std::endl << "Post attributes of a resource:" << std::endl << " post INDEX [QUERY PARAM]... [JSON]" << std::endl << std::endl << "Observe attributes of a resource:" << std::endl << " observe INDEX [QUERY PARAM]" << std::endl; } int main(int, char **) { std::cout.setf(std::ios::boolalpha); if (OCInit1(OC_CLIENT, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS) != OC_STACK_OK) { std::cerr << "OCStack init error" << std::endl; return EXIT_FAILURE; } for (;;) { struct pollfd pfd = { STDIN_FILENO, POLLIN, 0 }; int ret = poll(&pfd, 1, 1000); if (ret != 1) { if (OCProcess() != OC_STACK_OK) { std::cerr << "OCStack process error" << std::endl; return 0; } continue; } std::string line; std::getline(std::cin, line); boost::char_separator<char> sep(" "); boost::tokenizer<boost::char_separator<char>> tokens(line, sep); auto token = tokens.begin(); if (token == tokens.end()) { usage(); continue; } std::string cmd = *token++; if (cmd == "list") { for (size_t i = 0; i < g_resources.size(); ++i) { std::cout << "[" << i << "]" << std::endl; std::cout << "\tcoap://" << g_resources[i].host.addr << ":" << g_resources[i].host.port << g_resources[i].uri << std::endl; } } else if (cmd == "find") { std::string requestURI = *token++; OCCallbackData cbData; cbData.cb = onDiscover; cbData.context = (void *)DEFAULT_CONTEXT_VALUE; cbData.cd = NULL; OCStackResult result = OCDoResource(NULL, OC_REST_DISCOVER, requestURI.c_str(), NULL, 0, CT_DEFAULT, OC_HIGH_QOS, &cbData, NULL, 0); std::cout << "find " << requestURI << " - " << result << std::endl; } else if (cmd == "get") { size_t i = std::stoi(*token++); std::string query; while (token != tokens.end()) { std::string str = *token++; if (str != "{") { if (!query.empty()) { query += ";"; } query += str; } } std::string uri = g_resources[i].uri; if (!query.empty()) { uri += "?" + query; } OCCallbackData cbData; cbData.cb = onGet; cbData.context = (void *)DEFAULT_CONTEXT_VALUE; cbData.cd = NULL; OCStackResult result = OCDoResource(NULL, OC_REST_GET, uri.c_str(), &g_resources[i].host, NULL, CT_DEFAULT, OC_HIGH_QOS, &cbData, NULL, 0); std::cout << "get " << g_resources[i].host.addr << ":" << g_resources[i].host.port << g_resources[i].uri << " - " << result << std::endl; } else if (cmd == "put") { // TODO } else if (cmd == "post") { size_t i = std::stoi(*token++); std::string query, body; while (token != tokens.end()) { std::string str = *token++; if (str.find('=') != std::string::npos) { if (!query.empty()) { query += ";"; } query += str; } else { body += str; } } std::string uri = g_resources[i].uri; if (!query.empty()) { uri += "?" + query; } OCRepPayload *payload = NULL; size_t size = 8192; uint8_t buffer[8192]; size = ConvertJSONToCBOR(body.c_str(), buffer, size); if (size) { payload = OCRepPayloadCreate(); OCParsePayload((OCPayload **) &payload, PAYLOAD_TYPE_REPRESENTATION, buffer, size); } OCCallbackData cbData; cbData.cb = onPost; cbData.context = (void *)DEFAULT_CONTEXT_VALUE; cbData.cd = NULL; OCStackResult result = OCDoResource(NULL, OC_REST_POST, uri.c_str(), &g_resources[i].host, (OCPayload *) payload, CT_DEFAULT, OC_HIGH_QOS, &cbData, NULL, 0); std::cout << "post " << g_resources[i].host.addr << ":" << g_resources[i].host.port << g_resources[i].uri << " - " << result << std::endl; } else if (cmd == "observe") { size_t i = std::stoi(*token++); std::string query; while (token != tokens.end()) { std::string str = *token++; if (str.find('=') != std::string::npos) { if (!query.empty()) { query += ";"; } query += str; } } std::string uri = g_resources[i].uri; if (!query.empty()) { uri += "?" + query; } OCDoHandle handle; OCCallbackData cbData; cbData.cb = onObserve; cbData.context = (void *)DEFAULT_CONTEXT_VALUE; cbData.cd = NULL; OCStackResult result = OCDoResource(&handle, OC_REST_OBSERVE, uri.c_str(), &g_resources[i].host, NULL, CT_DEFAULT, OC_HIGH_QOS, &cbData, NULL, 0); std::cout << "observe " << g_resources[i].host.addr << ":" << g_resources[i].host.port << g_resources[i].uri << " (" << handle << ") - " << result << std::endl; } else if (cmd == "cancel") { OCDoHandle handle = (OCDoHandle) (intptr_t) std::stoi(*token++, 0, 0); OCStackResult result = OCCancel(handle, OC_HIGH_QOS, NULL, 0); std::cout << "cancel (" << handle << ") - " << result << std::endl; } else if (cmd == "delete") { // TODO } else if (cmd == "quit") { break; } } if (OCStop() != OC_STACK_OK) { std::cerr << "OCStack stop error" << std::endl; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <sys/types.h> #include <dirent.h> #include "pushnotificationservice.hh" #include "pushnotificationclient.hh" #include "common.hh" #include <boost/bind.hpp> #include <sstream> #include <openssl/x509.h> #include <openssl/x509_vfy.h> #include <openssl/err.h> static const char *APN_DEV_ADDRESS = "gateway.sandbox.push.apple.com"; static const char *APN_PROD_ADDRESS = "gateway.push.apple.com"; static const char *APN_PORT = "2195"; static const char *GPN_ADDRESS = "android.googleapis.com"; static const char *GPN_PORT = "443"; static const char *WPPN_PORT = "80"; using namespace ::std; namespace ssl = boost::asio::ssl; int PushNotificationService::sendRequest(const std::shared_ptr<PushNotificationRequest> &pn) { std::shared_ptr<PushNotificationClient> client = mClients[pn->getAppIdentifier()]; if (client == 0) { if (pn->getType().compare(string("wp")) == 0) { string wpClient = pn->getAppIdentifier(); std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client)); boost::system::error_code err; ctx->set_options(ssl::context::default_workarounds, err); ctx->set_verify_mode(ssl::context::verify_none); mClients[wpClient] = std::make_shared<PushNotificationClient>(wpClient, this, ctx, pn->getAppIdentifier(), WPPN_PORT, mMaxQueueSize, false); LOGD("Creating PN client for %s", pn->getAppIdentifier().c_str()); client = mClients[wpClient]; } else { LOGE("No push notification certificate for client %s", pn->getAppIdentifier().c_str()); return -1; } } // this method is called from flexisip main thread, while service is running in its own thread. // To avoid using dedicated mutex, use the server post() method to delegate the processing of the push notification // to the service thread. mIOService.post(std::bind(&PushNotificationClient::sendRequest, client, pn)); return 0; } void PushNotificationService::start() { if (mThread && !mThread->joinable()) { delete mThread; mThread = NULL; } if (mThread == NULL) { LOGD("Start PushNotificationService"); mHaveToStop = false; mThread = new thread(&PushNotificationService::run, this); } } void PushNotificationService::stop() { if (mThread != NULL) { LOGD("Stopping PushNotificationService"); mHaveToStop = true; mIOService.stop(); if (mThread->joinable()) { mThread->join(); } delete mThread; mThread = NULL; } } void PushNotificationService::waitEnd() { if (mThread != NULL) { LOGD("Waiting for PushNotificationService to end"); bool finished = false; while (!finished) { finished = true; map<string, std::shared_ptr<PushNotificationClient>>::const_iterator it; for (it = mClients.begin(); it != mClients.end(); ++it) { if (!it->second->isIdle()) { finished = false; break; } } } usleep(100000); // avoid eating all cpu for nothing } } void PushNotificationService::setupErrorClient() { // Error client std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client)); boost::system::error_code err; ctx->set_options(ssl::context::default_workarounds, err); ctx->set_verify_mode(ssl::context::verify_none); mClients["error"] = std::make_shared<PushNotificationClient>("error", this, ctx, "127.0.0.1", "1", mMaxQueueSize, false); } void PushNotificationService::setupGenericClient(const url_t *url) { std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client)); boost::system::error_code err; ctx->set_options(ssl::context::default_workarounds, err); ctx->set_verify_mode(ssl::context::verify_none); mClients["generic"] = std::make_shared<PushNotificationClient>("generic", this, ctx, url->url_host, url_port(url), mMaxQueueSize, false); } /* Utility function to convert ASN1_TIME to a printable string in a buffer */ static int ASN1_TIME_toString( const ASN1_TIME* time, char* buffer, uint32_t buff_length){ int write = 0; BIO* bio = BIO_new(BIO_s_mem()); if (bio) { if (ASN1_TIME_print(bio, time)) write = BIO_read(bio, buffer, buff_length-1); BIO_free(bio); } buffer[write]='\0'; return write; } bool PushNotificationService::isCertExpired( const std::string &certPath ){ bool expired = true; BIO* certbio = BIO_new(BIO_s_file()); int err = BIO_read_filename(certbio, certPath.c_str()); if( err == 0 ){ LOGE("BIO_read_filename failed for %s", certPath.c_str()); return expired; } X509* cert = PEM_read_bio_X509(certbio, NULL, 0, 0); if( !cert ){ char buf[128] = {}; unsigned long error = ERR_get_error(); ERR_error_string(error, buf); LOGE("Couldn't parse certificate at %s : %s", certPath.c_str(), buf); return expired; } else { ASN1_TIME *notBefore = X509_get_notBefore(cert); ASN1_TIME *notAfter = X509_get_notAfter(cert); if( X509_cmp_current_time(notBefore) > 0 && X509_cmp_current_time(notAfter) < 0 ) { LOGD("Certificate %s has a valid expiration.", certPath.c_str()); expired = false; } else { // the certificate has an expire or not before value that makes it not valid regarding the server's date. char beforeStr[128] = {}; char afterStr[128] = {}; if( ASN1_TIME_toString(notBefore, beforeStr, 128) && ASN1_TIME_toString(notAfter, afterStr, 128)){ LOGD("Certificate %s is expired or not yet valid! Not Before: %s, Not After: %s", certPath.c_str(), beforeStr, afterStr); } else { LOGD("Certificate %s is expired or not yet valid!", certPath.c_str()); } } } X509_free(cert); BIO_free_all(certbio); return expired; } void PushNotificationService::setupiOSClient(const std::string &certdir, const std::string &cafile) { struct dirent *dirent; DIR *dirp; dirp = opendir(certdir.c_str()); if (dirp == NULL) { LOGE("Could not open push notification certificates directory (%s): %s", certdir.c_str(), strerror(errno)); return; } SLOGD << "Searching push notification client on dir [" << certdir << "]"; while (true) { errno = 0; if ((dirent = readdir(dirp)) == NULL) { if (errno) SLOGE << "Cannot read dir [" << certdir << "] because [" << strerror(errno) << "]"; break; } string cert = string(dirent->d_name); // only consider files which end with .pem string suffix = ".pem"; if (cert.compare(".") == 0 || cert.compare("..") == 0 || (cert.compare(cert.length() - suffix.length(), suffix.length(), suffix) != 0)) { continue; } string certpath = string(certdir) + "/" + cert; std::shared_ptr<ssl::context> context(new ssl::context(mIOService, ssl::context::sslv23_client)); boost::system::error_code error; context->set_options(ssl::context::default_workarounds, error); context->set_password_callback(bind(&PushNotificationService::handle_password_callback, this, _1, _2)); if (!cafile.empty()) { context->set_verify_mode(ssl::context::verify_peer); #if BOOST_VERSION >= 104800 context->set_verify_callback(bind(&PushNotificationService::handle_verify_callback, this, _1, _2)); #endif context->load_verify_file(cafile, error); if (error) { LOGE("load_verify_file: %s", error.message().c_str()); continue; } } else { context->set_verify_mode(ssl::context::verify_none); } context->add_verify_path("/etc/ssl/certs"); if (!cert.empty()) { context->use_certificate_file(certpath, ssl::context::file_format::pem, error); if (error) { LOGE("use_certificate_file %s: %s", certpath.c_str(), error.message().c_str()); continue; } else if ( isCertExpired(certpath) ){ LOGF("Certificate %s is expired! You won't be able to use it for push notifications. Please update your certificate or remove it entirely.", certpath.c_str()); // will exit flexisip } } string key = certpath; if (!key.empty()) { context->use_private_key_file(key, ssl::context::file_format::pem, error); if (error) { LOGE("use_private_key_file %s: %s", certpath.c_str(), error.message().c_str()); continue; } } string certName = cert.substr(0, cert.size() - 4); // Remove .pem at the end of cert const char *apn_server; if (certName.find(".dev") != string::npos) apn_server = APN_DEV_ADDRESS; else apn_server = APN_PROD_ADDRESS; mClients[certName] = std::make_shared<PushNotificationClient>(cert, this, context, apn_server, APN_PORT, mMaxQueueSize, true); SLOGD << "Adding ios push notification client [" << certName << "]"; } closedir(dirp); } void PushNotificationService::setupAndroidClient(const std::map<std::string, std::string> googleKeys) { map<string, string>::const_iterator it; for (it = googleKeys.begin(); it != googleKeys.end(); ++it) { string android_app_id = it->first; std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client)); boost::system::error_code err; ctx->set_options(ssl::context::default_workarounds, err); ctx->set_verify_mode(ssl::context::verify_none); mClients[android_app_id] = std::make_shared<PushNotificationClient>("google", this, ctx, GPN_ADDRESS, GPN_PORT, mMaxQueueSize, true); SLOGD << "Adding android push notification client [" << android_app_id << "]"; } } PushNotificationService::PushNotificationService(int maxQueueSize) : mIOService(), mThread(NULL), mMaxQueueSize(maxQueueSize), mClients(), mCountFailed(NULL), mCountSent(NULL) { setupErrorClient(); } PushNotificationService::~PushNotificationService() { stop(); } int PushNotificationService::run() { LOGD("PushNotificationService Start"); boost::asio::io_service::work work(mIOService); mIOService.run(); LOGD("PushNotificationService End"); return 0; } void PushNotificationService::clientEnded() { } boost::asio::io_service &PushNotificationService::getService() { return mIOService; } string PushNotificationService::handle_password_callback(size_t max_length, ssl::context_base::password_purpose purpose) const { return mPassword; } bool PushNotificationService::handle_verify_callback(bool preverified, ssl::verify_context &ctx) const { char subject_name[256]; X509 *cert = X509_STORE_CTX_get_current_cert(ctx.native_handle()); X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256); SLOGD << "Verifying " << subject_name; int error = X509_STORE_CTX_get_error(ctx.native_handle()); if( error != 0 ){ switch (error) { case X509_V_ERR_CERT_NOT_YET_VALID: case X509_V_ERR_CRL_NOT_YET_VALID: LOGE("Certificate for %s is not yet valid. Push won't work.", subject_name); break; case X509_V_ERR_CERT_HAS_EXPIRED: case X509_V_ERR_CRL_HAS_EXPIRED: LOGE("Certificate for %s is expired. Push won't work.", subject_name); break; default:{ const char* errString = X509_verify_cert_error_string(error); LOGE("Certificate for %s is invalid (reason: %d - %s). Push won't work.", subject_name, error, errString ? errString:"unknown" ); break; } } } return preverified; } <commit_msg>Don’t exit flexisip when the certificate is expired for push. Only log an error.<commit_after>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <sys/types.h> #include <dirent.h> #include "pushnotificationservice.hh" #include "pushnotificationclient.hh" #include "common.hh" #include <boost/bind.hpp> #include <sstream> #include <openssl/x509.h> #include <openssl/x509_vfy.h> #include <openssl/err.h> static const char *APN_DEV_ADDRESS = "gateway.sandbox.push.apple.com"; static const char *APN_PROD_ADDRESS = "gateway.push.apple.com"; static const char *APN_PORT = "2195"; static const char *GPN_ADDRESS = "android.googleapis.com"; static const char *GPN_PORT = "443"; static const char *WPPN_PORT = "80"; using namespace ::std; namespace ssl = boost::asio::ssl; int PushNotificationService::sendRequest(const std::shared_ptr<PushNotificationRequest> &pn) { std::shared_ptr<PushNotificationClient> client = mClients[pn->getAppIdentifier()]; if (client == 0) { if (pn->getType().compare(string("wp")) == 0) { string wpClient = pn->getAppIdentifier(); std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client)); boost::system::error_code err; ctx->set_options(ssl::context::default_workarounds, err); ctx->set_verify_mode(ssl::context::verify_none); mClients[wpClient] = std::make_shared<PushNotificationClient>(wpClient, this, ctx, pn->getAppIdentifier(), WPPN_PORT, mMaxQueueSize, false); LOGD("Creating PN client for %s", pn->getAppIdentifier().c_str()); client = mClients[wpClient]; } else { LOGE("No push notification certificate for client %s", pn->getAppIdentifier().c_str()); return -1; } } // this method is called from flexisip main thread, while service is running in its own thread. // To avoid using dedicated mutex, use the server post() method to delegate the processing of the push notification // to the service thread. mIOService.post(std::bind(&PushNotificationClient::sendRequest, client, pn)); return 0; } void PushNotificationService::start() { if (mThread && !mThread->joinable()) { delete mThread; mThread = NULL; } if (mThread == NULL) { LOGD("Start PushNotificationService"); mHaveToStop = false; mThread = new thread(&PushNotificationService::run, this); } } void PushNotificationService::stop() { if (mThread != NULL) { LOGD("Stopping PushNotificationService"); mHaveToStop = true; mIOService.stop(); if (mThread->joinable()) { mThread->join(); } delete mThread; mThread = NULL; } } void PushNotificationService::waitEnd() { if (mThread != NULL) { LOGD("Waiting for PushNotificationService to end"); bool finished = false; while (!finished) { finished = true; map<string, std::shared_ptr<PushNotificationClient>>::const_iterator it; for (it = mClients.begin(); it != mClients.end(); ++it) { if (!it->second->isIdle()) { finished = false; break; } } } usleep(100000); // avoid eating all cpu for nothing } } void PushNotificationService::setupErrorClient() { // Error client std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client)); boost::system::error_code err; ctx->set_options(ssl::context::default_workarounds, err); ctx->set_verify_mode(ssl::context::verify_none); mClients["error"] = std::make_shared<PushNotificationClient>("error", this, ctx, "127.0.0.1", "1", mMaxQueueSize, false); } void PushNotificationService::setupGenericClient(const url_t *url) { std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client)); boost::system::error_code err; ctx->set_options(ssl::context::default_workarounds, err); ctx->set_verify_mode(ssl::context::verify_none); mClients["generic"] = std::make_shared<PushNotificationClient>("generic", this, ctx, url->url_host, url_port(url), mMaxQueueSize, false); } /* Utility function to convert ASN1_TIME to a printable string in a buffer */ static int ASN1_TIME_toString( const ASN1_TIME* time, char* buffer, uint32_t buff_length){ int write = 0; BIO* bio = BIO_new(BIO_s_mem()); if (bio) { if (ASN1_TIME_print(bio, time)) write = BIO_read(bio, buffer, buff_length-1); BIO_free(bio); } buffer[write]='\0'; return write; } bool PushNotificationService::isCertExpired( const std::string &certPath ){ bool expired = true; BIO* certbio = BIO_new(BIO_s_file()); int err = BIO_read_filename(certbio, certPath.c_str()); if( err == 0 ){ LOGE("BIO_read_filename failed for %s", certPath.c_str()); return expired; } X509* cert = PEM_read_bio_X509(certbio, NULL, 0, 0); if( !cert ){ char buf[128] = {}; unsigned long error = ERR_get_error(); ERR_error_string(error, buf); LOGE("Couldn't parse certificate at %s : %s", certPath.c_str(), buf); return expired; } else { ASN1_TIME *notBefore = X509_get_notBefore(cert); ASN1_TIME *notAfter = X509_get_notAfter(cert); if( X509_cmp_current_time(notBefore) > 0 && X509_cmp_current_time(notAfter) < 0 ) { LOGD("Certificate %s has a valid expiration.", certPath.c_str()); expired = false; } else { // the certificate has an expire or not before value that makes it not valid regarding the server's date. char beforeStr[128] = {}; char afterStr[128] = {}; if( ASN1_TIME_toString(notBefore, beforeStr, 128) && ASN1_TIME_toString(notAfter, afterStr, 128)){ LOGD("Certificate %s is expired or not yet valid! Not Before: %s, Not After: %s", certPath.c_str(), beforeStr, afterStr); } else { LOGD("Certificate %s is expired or not yet valid!", certPath.c_str()); } } } X509_free(cert); BIO_free_all(certbio); return expired; } void PushNotificationService::setupiOSClient(const std::string &certdir, const std::string &cafile) { struct dirent *dirent; DIR *dirp; dirp = opendir(certdir.c_str()); if (dirp == NULL) { LOGE("Could not open push notification certificates directory (%s): %s", certdir.c_str(), strerror(errno)); return; } SLOGD << "Searching push notification client on dir [" << certdir << "]"; while (true) { errno = 0; if ((dirent = readdir(dirp)) == NULL) { if (errno) SLOGE << "Cannot read dir [" << certdir << "] because [" << strerror(errno) << "]"; break; } string cert = string(dirent->d_name); // only consider files which end with .pem string suffix = ".pem"; if (cert.compare(".") == 0 || cert.compare("..") == 0 || (cert.compare(cert.length() - suffix.length(), suffix.length(), suffix) != 0)) { continue; } string certpath = string(certdir) + "/" + cert; std::shared_ptr<ssl::context> context(new ssl::context(mIOService, ssl::context::sslv23_client)); boost::system::error_code error; context->set_options(ssl::context::default_workarounds, error); context->set_password_callback(bind(&PushNotificationService::handle_password_callback, this, _1, _2)); if (!cafile.empty()) { context->set_verify_mode(ssl::context::verify_peer); #if BOOST_VERSION >= 104800 context->set_verify_callback(bind(&PushNotificationService::handle_verify_callback, this, _1, _2)); #endif context->load_verify_file(cafile, error); if (error) { LOGE("load_verify_file: %s", error.message().c_str()); continue; } } else { context->set_verify_mode(ssl::context::verify_none); } context->add_verify_path("/etc/ssl/certs"); if (!cert.empty()) { context->use_certificate_file(certpath, ssl::context::file_format::pem, error); if (error) { LOGE("use_certificate_file %s: %s", certpath.c_str(), error.message().c_str()); continue; } else if ( isCertExpired(certpath) ){ LOGEN("Certificate %s is expired! You won't be able to use it for push notifications. Please update your certificate or remove it entirely.", certpath.c_str()); } } string key = certpath; if (!key.empty()) { context->use_private_key_file(key, ssl::context::file_format::pem, error); if (error) { LOGE("use_private_key_file %s: %s", certpath.c_str(), error.message().c_str()); continue; } } string certName = cert.substr(0, cert.size() - 4); // Remove .pem at the end of cert const char *apn_server; if (certName.find(".dev") != string::npos) apn_server = APN_DEV_ADDRESS; else apn_server = APN_PROD_ADDRESS; mClients[certName] = std::make_shared<PushNotificationClient>(cert, this, context, apn_server, APN_PORT, mMaxQueueSize, true); SLOGD << "Adding ios push notification client [" << certName << "]"; } closedir(dirp); } void PushNotificationService::setupAndroidClient(const std::map<std::string, std::string> googleKeys) { map<string, string>::const_iterator it; for (it = googleKeys.begin(); it != googleKeys.end(); ++it) { string android_app_id = it->first; std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client)); boost::system::error_code err; ctx->set_options(ssl::context::default_workarounds, err); ctx->set_verify_mode(ssl::context::verify_none); mClients[android_app_id] = std::make_shared<PushNotificationClient>("google", this, ctx, GPN_ADDRESS, GPN_PORT, mMaxQueueSize, true); SLOGD << "Adding android push notification client [" << android_app_id << "]"; } } PushNotificationService::PushNotificationService(int maxQueueSize) : mIOService(), mThread(NULL), mMaxQueueSize(maxQueueSize), mClients(), mCountFailed(NULL), mCountSent(NULL) { setupErrorClient(); } PushNotificationService::~PushNotificationService() { stop(); } int PushNotificationService::run() { LOGD("PushNotificationService Start"); boost::asio::io_service::work work(mIOService); mIOService.run(); LOGD("PushNotificationService End"); return 0; } void PushNotificationService::clientEnded() { } boost::asio::io_service &PushNotificationService::getService() { return mIOService; } string PushNotificationService::handle_password_callback(size_t max_length, ssl::context_base::password_purpose purpose) const { return mPassword; } bool PushNotificationService::handle_verify_callback(bool preverified, ssl::verify_context &ctx) const { char subject_name[256]; X509 *cert = X509_STORE_CTX_get_current_cert(ctx.native_handle()); X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256); SLOGD << "Verifying " << subject_name; int error = X509_STORE_CTX_get_error(ctx.native_handle()); if( error != 0 ){ switch (error) { case X509_V_ERR_CERT_NOT_YET_VALID: case X509_V_ERR_CRL_NOT_YET_VALID: LOGEN("Certificate for %s is not yet valid. Push won't work.", subject_name); break; case X509_V_ERR_CERT_HAS_EXPIRED: case X509_V_ERR_CRL_HAS_EXPIRED: LOGEN("Certificate for %s is expired. Push won't work.", subject_name); break; default:{ const char* errString = X509_verify_cert_error_string(error); LOGEN("Certificate for %s is invalid (reason: %d - %s). Push won't work.", subject_name, error, errString ? errString:"unknown" ); break; } } } return preverified; } <|endoftext|>
<commit_before>#include <stdio.h> #include <fcntl.h> #include <io.h> #include <vector> #include "dbg_unicode.h" #include "stdinput.h" #include "launch.h" #include "attach.h" #include "dbg_capabilities.h" #include "dbg_unicode.cpp" #include <base/filesystem.h> #include <base/hook/fp_call.h> class module { public: module(const wchar_t* path) : handle_(LoadLibraryW(path)) { } ~module() { } HMODULE handle() const { return handle_; } intptr_t api(const char* name) { return (intptr_t)GetProcAddress(handle_, name); } private: HMODULE handle_; }; bool create_process_with_debugger(vscode::rprotocol& req) { module dll(L"debugger-inject.dll"); if (!dll.handle()) { return false; } intptr_t create_process = dll.api("create_process_with_debugger"); intptr_t set_luadll = dll.api("set_luadll"); if (!create_process || !set_luadll) { return false; } auto& args = req["arguments"]; if (args.HasMember("luadll") && args["luadll"].IsString()) { std::wstring wluadll = vscode::u2w(args["luadll"].Get<std::string>()); if (!base::c_call<bool>(set_luadll, wluadll.data(), wluadll.size())) { return false; } } if (!args.HasMember("runtimeExecutable") || !args["runtimeExecutable"].IsString()) { return false; } std::wstring wapplication = vscode::u2w(args["runtimeExecutable"].Get<std::string>()); std::wstring wcommand = wapplication; if (args.HasMember("runtimeArgs") && args["runtimeArgs"].IsString()) { wcommand = L"\"" + wapplication + L"\" " + vscode::u2w(args["runtimeArgs"].Get<std::string>()); } std::wstring wcwd; if (args.HasMember("cwd") && args["cwd"].IsString()) { wcwd = vscode::u2w(args["cwd"].Get<std::string>()); } else { wcwd = fs::path(wapplication).remove_filename(); } if (!base::c_call<bool>(create_process, 4278, wapplication.c_str(), wcommand.c_str(), wcwd.c_str())) { return false; } return true; } int64_t seq = 1; void response_initialized(stdinput& io, vscode::rprotocol& req) { vscode::wprotocol res; vscode::capabilities(res, req["seq"].GetInt64()); io.output(res); } void response_error(stdinput& io, vscode::rprotocol& req, const char *msg) { vscode::wprotocol res; for (auto _ : res.Object()) { res("type").String("response"); res("seq").Int64(seq++); res("command").String(req["command"]); res("request_seq").Int64(req["seq"].GetInt64()); res("success").Bool(false); res("message").String(msg); } io.output(res); } int main() { _setmode(_fileno(stdout), _O_BINARY); setbuf(stdout, NULL); stdinput io; vscode::rprotocol initproto; std::unique_ptr<attach> attach_; std::unique_ptr<launch> launch_; for (;; std::this_thread::sleep_for(std::chrono::milliseconds(10))) { if (launch_) { launch_->update(); continue; } if (attach_) { attach_->update(); continue; } while (!io.input_empty()) { vscode::rprotocol rp = io.input(); if (rp["type"] == "request") { if (rp["command"] == "initialize") { response_initialized(io, rp); initproto = std::move(rp); initproto.AddMember("__norepl", true, initproto.GetAllocator()); seq = 1; continue; } else if (rp["command"] == "launch") { auto& args = rp["arguments"]; if (args.HasMember("runtimeExecutable")) { if (!create_process_with_debugger(rp)) { response_error(io, rp, "Launch failed"); exit(0); continue; } attach_.reset(new attach(io)); attach_->connect(net::endpoint("127.0.0.1", 4278)); if (seq > 1) initproto.AddMember("__initseq", seq, initproto.GetAllocator()); attach_->send(initproto); attach_->send(rp); } else { launch_.reset(new launch(io)); if (seq > 1) initproto.AddMember("__initseq", seq, initproto.GetAllocator()); launch_->send(std::move(initproto)); launch_->send(std::move(rp)); break; } } else if (rp["command"] == "attach") { attach_.reset(new attach(io)); std::string ip = "127.0.0.1"; uint16_t port = 4278; auto& args = rp["arguments"]; if (args.HasMember("ip")) { ip = args["ip"].Get<std::string>(); } if (args.HasMember("port")) { port = args["port"].GetUint(); } attach_->connect(net::endpoint(ip, port)); if (seq > 1) initproto.AddMember("__initseq", seq, initproto.GetAllocator()); attach_->send(initproto); attach_->send(rp); } } } } io.join(); } <commit_msg>修正一个错误<commit_after>#include <stdio.h> #include <fcntl.h> #include <io.h> #include <vector> #include "dbg_unicode.h" #include "stdinput.h" #include "launch.h" #include "attach.h" #include "dbg_capabilities.h" #include "dbg_unicode.cpp" #include <base/filesystem.h> #include <base/hook/fp_call.h> class module { public: module(const wchar_t* path) : handle_(LoadLibraryW(path)) { } ~module() { } HMODULE handle() const { return handle_; } intptr_t api(const char* name) { return (intptr_t)GetProcAddress(handle_, name); } private: HMODULE handle_; }; bool create_process_with_debugger(vscode::rprotocol& req) { module dll(L"debugger-inject.dll"); if (!dll.handle()) { return false; } intptr_t create_process = dll.api("create_process_with_debugger"); intptr_t set_luadll = dll.api("set_luadll"); if (!create_process || !set_luadll) { return false; } auto& args = req["arguments"]; if (args.HasMember("luadll") && args["luadll"].IsString()) { std::wstring wluadll = vscode::u2w(args["luadll"].Get<std::string>()); if (!base::c_call<bool>(set_luadll, wluadll.data(), wluadll.size())) { return false; } } if (!args.HasMember("runtimeExecutable") || !args["runtimeExecutable"].IsString()) { return false; } std::wstring wapplication = vscode::u2w(args["runtimeExecutable"].Get<std::string>()); std::wstring wcommand = L"\"" + wapplication + L"\""; if (args.HasMember("runtimeArgs") && args["runtimeArgs"].IsString()) { wcommand = wcommand + L" " + vscode::u2w(args["runtimeArgs"].Get<std::string>()); } std::wstring wcwd; if (args.HasMember("cwd") && args["cwd"].IsString()) { wcwd = vscode::u2w(args["cwd"].Get<std::string>()); } else { wcwd = fs::path(wapplication).remove_filename(); } if (!base::c_call<bool>(create_process, 4278, wapplication.c_str(), wcommand.c_str(), wcwd.c_str())) { return false; } return true; } int64_t seq = 1; void response_initialized(stdinput& io, vscode::rprotocol& req) { vscode::wprotocol res; vscode::capabilities(res, req["seq"].GetInt64()); io.output(res); } void response_error(stdinput& io, vscode::rprotocol& req, const char *msg) { vscode::wprotocol res; for (auto _ : res.Object()) { res("type").String("response"); res("seq").Int64(seq++); res("command").String(req["command"]); res("request_seq").Int64(req["seq"].GetInt64()); res("success").Bool(false); res("message").String(msg); } io.output(res); } int main() { _setmode(_fileno(stdout), _O_BINARY); setbuf(stdout, NULL); stdinput io; vscode::rprotocol initproto; std::unique_ptr<attach> attach_; std::unique_ptr<launch> launch_; for (;; std::this_thread::sleep_for(std::chrono::milliseconds(10))) { if (launch_) { launch_->update(); continue; } if (attach_) { attach_->update(); continue; } while (!io.input_empty()) { vscode::rprotocol rp = io.input(); if (rp["type"] == "request") { if (rp["command"] == "initialize") { response_initialized(io, rp); initproto = std::move(rp); initproto.AddMember("__norepl", true, initproto.GetAllocator()); seq = 1; continue; } else if (rp["command"] == "launch") { auto& args = rp["arguments"]; if (args.HasMember("runtimeExecutable")) { if (!create_process_with_debugger(rp)) { response_error(io, rp, "Launch failed"); exit(0); continue; } attach_.reset(new attach(io)); attach_->connect(net::endpoint("127.0.0.1", 4278)); if (seq > 1) initproto.AddMember("__initseq", seq, initproto.GetAllocator()); attach_->send(initproto); attach_->send(rp); } else { launch_.reset(new launch(io)); if (seq > 1) initproto.AddMember("__initseq", seq, initproto.GetAllocator()); launch_->send(std::move(initproto)); launch_->send(std::move(rp)); break; } } else if (rp["command"] == "attach") { attach_.reset(new attach(io)); std::string ip = "127.0.0.1"; uint16_t port = 4278; auto& args = rp["arguments"]; if (args.HasMember("ip")) { ip = args["ip"].Get<std::string>(); } if (args.HasMember("port")) { port = args["port"].GetUint(); } attach_->connect(net::endpoint(ip, port)); if (seq > 1) initproto.AddMember("__initseq", seq, initproto.GetAllocator()); attach_->send(initproto); attach_->send(rp); } } } } io.join(); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Mozilla 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: // // * 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 Mozilla Foundation 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 <getopt.h> #include <limits.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <set> #include <vector> #include <curl/curl.h> #include "google_breakpad/processor/basic_source_line_resolver.h" #include "google_breakpad/processor/minidump.h" #include "google_breakpad/processor/minidump_processor.h" #include "google_breakpad/processor/process_state.h" #include "google_breakpad/processor/stack_frame.h" #include "google_breakpad/processor/stack_frame_symbolizer.h" #include "processor/pathname_stripper.h" #include "processor/simple_symbol_supplier.h" using namespace google_breakpad; using std::vector; CURL* curl; std::set<string> error_symbols; void error(const char* fmt, ...) { va_list args; va_start(args, fmt); vfprintf(stderr, fmt, args); fprintf(stderr, "\n"); va_end(args); exit(1); } void usage() { fprintf(stderr, "Usage: get-minidump-instructions [options] <minidump> [<symbol paths]\n"); fprintf(stderr, "Options:\n"); fprintf(stderr, "\t--disassemble\tAttempt to disassemble the instructions using objdump\n"); fprintf(stderr, "\t--address=ADDRESS\tShow instructions at ADDRESS\n"); fprintf(stderr, "\t--help\tDisplay this help text.\n"); } enum UnmangleType { Annotate, RawFile, LocalFile }; string unmangle_source_file(const string& source_file, int line, UnmangleType type) { string source_and_line = source_file + ":" + std::to_string(line); if (source_file.compare(0, 3, "hg:") != 0) { if (type != Annotate) { return ""; } return source_and_line; } string ret = type != Annotate ? "" : source_and_line; string s = source_file; char* junk = strtok(&s[0], ":"); char* repo = strtok(nullptr, ":"); char* path = strtok(nullptr, ":"); char* rev = strtok(nullptr, ":"); if (repo && path && rev) { if (type == RawFile) { char url[1024]; snprintf(url, sizeof(url), "http://%s/raw-file/%s/%s", repo, rev, path); ret = url; } else if (type == LocalFile) { char filename[1024]; snprintf(filename, sizeof(filename), "/tmp/%s_%s_%s", repo, rev, path); char* c; while ((c = strchr(filename+5, '/')) != nullptr) { *c = '_'; } ret = filename; } else { char url[1024]; snprintf(url, sizeof(url), "http://%s/annotate/%s/%s#l%d", repo, rev, path, line); ret = url; } } return ret; } static bool file_exists(const string &file_name) { struct stat sb; return stat(file_name.c_str(), &sb) == 0; } bool get_line_from_file(const string& file, int line, string& out) { FILE* f = fopen(file.c_str(), "r"); if (!f) { return false; } char source[1024]; for (int current = 1; current <= line; current++) { if (!fgets(source, sizeof(source), f)) { break; } if (current == line) { out = source; fclose(f); return true; } } fclose(f); return false; } bool fetch_url_to_file(const string& url, const string& file) { string tempfile = file + ".tmp"; FILE* f = fopen(tempfile.c_str(), "w"); if (!f) { return false; } curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_ENCODING, ""); curl_easy_setopt(curl, CURLOPT_STDERR, stderr); curl_easy_setopt(curl, CURLOPT_WRITEDATA, f); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); bool result; long retcode = -1; if (curl_easy_perform(curl) != 0 || curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &retcode) != 0 || retcode != 200) { result = false; } else { result = true; } if (!result) { return false; } fclose(f); if (rename(tempfile.c_str(), file.c_str()) == 0) { return true; } unlink(tempfile.c_str()); return false; } bool get_line_from_url(const string& url, const string& file, int line, string& out) { // Check for URLs that failed. if (error_symbols.find(url) != error_symbols.end()) { return false; } if (!file_exists(file)) { // Fetch URL. if (!fetch_url_to_file(url, file)) { error_symbols.insert(url); return false; } } return get_line_from_file(file, line, out); } void print_source_line(const string& file, int line) { string url = unmangle_source_file(file, line, RawFile); if (url.empty()) { return; } string local_file = unmangle_source_file(file, line, LocalFile); string out; if (get_line_from_url(url, local_file, line, out)) { printf("% 5d %s", line, out.c_str()); } } void print_frame(const StackFrame& frame, const StackFrame& last_frame) { if (!frame.source_file_name.empty()) { bool new_file = false; if (frame.source_file_name != last_frame.source_file_name) { printf("%s\n", unmangle_source_file(frame.source_file_name, frame.source_line, Annotate).c_str()); new_file = true; } if (new_file || frame.source_line != last_frame.source_line) { print_source_line(frame.source_file_name, frame.source_line); } } else if (frame.module && (!last_frame.module || frame.module->code_file() != last_frame.module->code_file())) { printf("%s+0x%lx\n", PathnameStripper::File(frame.module->code_file()).c_str(), frame.instruction - frame.module->base_address()); } } int main(int argc, char** argv) { static struct option long_options[] = { {"address", required_argument, nullptr, 'a'}, {"disassemble", no_argument, nullptr, 'd'}, {"help", no_argument, nullptr, 'h'}, {nullptr, 0, nullptr, 0} }; bool disassemble = false; char* address_arg = nullptr; int arg; int option_index = 0; while((arg = getopt_long(argc, argv, "", long_options, &option_index)) != -1) { switch(arg) { case 0: if (long_options[option_index].flag != 0) break; break; case 'd': disassemble = true; break; case 'a': address_arg = optarg; break; case 'h': usage(); return 0; case '?': break; default: fprintf(stderr, "Unknown option: -%c\n", (char)arg); usage(); return 1; } } if (optind >= argc) { usage(); return 1; } const char* minidump_file = argv[optind]; Minidump minidump(minidump_file); if (!minidump.Read()) { error("Couldn't read minidump %s", minidump_file); } vector<string> symbol_paths; // allow symbol paths to be passed on the commandline. for (int i = optind + 1; i < argc; i++) { symbol_paths.push_back(argv[i]); } MinidumpMemoryList* memory_list = minidump.GetMemoryList(); if (!memory_list) { error("Minidump %s doesn't contain a memory list", minidump_file); } MinidumpModuleList* module_list = minidump.GetModuleList(); if (!module_list) { error("Minidump %s doesn't contain a module list", minidump_file); } u_int64_t instruction_pointer; if (address_arg) { instruction_pointer = strtoull(address_arg, NULL, 16); arg++; } else { MinidumpException* exception = minidump.GetException(); if (!exception) { error("Minidump doesn't contain exception information"); } MinidumpContext* context = exception->GetContext(); if (!context->GetInstructionPointer(&instruction_pointer)) { error("Couldn't get instruction pointer. Unknown CPU?"); } } MinidumpMemoryRegion* region = memory_list->GetMemoryRegionForAddress(instruction_pointer); if (!region) { error("Minidump doesn't contain a memory region that contains " "the instruction pointer from the exception record"); } printf("Faulting instruction pointer: 0x%08lx\n", instruction_pointer); const u_int8_t* bytes = region->GetMemory(); if (disassemble) { curl = curl_easy_init(); char tempfile[1024] = "/tmp/minidump-instructions-XXXXXX"; int fd = mkstemp(tempfile); write(fd, bytes, region->GetSize()); close(fd); const char* arch; const char* archopts = ""; const char* objdump = "objdump"; uint32_t cpu; minidump.GetContextCPUFlagsFromSystemInfo(&cpu); switch (cpu) { case MD_CONTEXT_X86: arch = "i386"; archopts = "att-mnemonic,i386,addr32,data32"; break; case MD_CONTEXT_AMD64: arch = "i386:x86-64"; archopts = "att-mnemonic,x86-64"; break; case MD_CONTEXT_ARM: //XXX: might not work everywhere //"arm-linux-gnueabi-objdump" objdump = "arm-linux-androideabi-objdump"; arch = "arm"; //XXX: not sure how to tell whether force-thumb is needed archopts = "reg-names-std,force-thumb"; break; default: error("Unknown CPU architecture"); } char cmdline[1024]; sprintf(cmdline, "%s -b binary -m %s -M %s --adjust-vma=0x%lx -D \"%s\"", objdump, arch, archopts, region->GetBase(), tempfile); FILE* fp = popen(cmdline, "r"); if (!fp) { error("Couldn't launch objdump"); } SimpleSymbolSupplier supplier(symbol_paths); BasicSourceLineResolver resolver; StackFrameSymbolizer symbolizer(&supplier, &resolver); SystemInfo system_info; MinidumpProcessor::GetCPUInfo(&minidump, &system_info); MinidumpProcessor::GetOSInfo(&minidump, &system_info); StackFrame last_frame = {}; char line[LINE_MAX]; bool printed_highlight = false; while (fgets(line, LINE_MAX, fp) != nullptr) { const char* p = strchr(line, ':'); StackFrame frame = {}; if (p && (p - line == 8 || p - line == 16) && !strstr(line, "<.data>:")) { frame.instruction = strtoull(line, nullptr, 16); symbolizer.FillSourceLineInfo(module_list, &system_info, &frame); print_frame(frame, last_frame); last_frame = frame; } printf("%s", line); if (frame.instruction >= instruction_pointer && !printed_highlight) { int l = strlen(line); for (int i = 0; i < l; i++) { if (line[i] == '\t') { putc('\t', stdout); } else { putc('^', stdout); } } printf("\n"); printed_highlight = true; } } unlink(tempfile); if (pclose(fp) == -1) { error("Error running objdump"); } curl_easy_cleanup(curl); } else { printf("Memory:"); const int kBytesPerLine = 16; for (unsigned int i = 0; i < region->GetSize(); i++) { if ((i % kBytesPerLine) == 0) { printf("\n%08lx ", region->GetBase() + i); } printf("%02x ", bytes[i]); } printf("\n"); } return 0; } <commit_msg>bug 1119525 - fix get-minidump-instructions build in vagrant<commit_after>// Copyright (c) 2010 The Mozilla 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: // // * 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 Mozilla Foundation 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 <getopt.h> #include <limits.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <set> #include <vector> #include <curl/curl.h> #include "google_breakpad/processor/basic_source_line_resolver.h" #include "google_breakpad/processor/minidump.h" #include "google_breakpad/processor/minidump_processor.h" #include "google_breakpad/processor/process_state.h" #include "google_breakpad/processor/stack_frame.h" #include "google_breakpad/processor/stack_frame_symbolizer.h" #include "processor/pathname_stripper.h" #include "processor/simple_symbol_supplier.h" using namespace google_breakpad; using std::vector; #if (__GNUC__ == 4) && (__GNUC_MINOR__ < 6) #define nullptr __null #endif CURL* curl; std::set<string> error_symbols; void error(const char* fmt, ...) { va_list args; va_start(args, fmt); vfprintf(stderr, fmt, args); fprintf(stderr, "\n"); va_end(args); exit(1); } void usage() { fprintf(stderr, "Usage: get-minidump-instructions [options] <minidump> [<symbol paths]\n"); fprintf(stderr, "Options:\n"); fprintf(stderr, "\t--disassemble\tAttempt to disassemble the instructions using objdump\n"); fprintf(stderr, "\t--address=ADDRESS\tShow instructions at ADDRESS\n"); fprintf(stderr, "\t--help\tDisplay this help text.\n"); } enum UnmangleType { Annotate, RawFile, LocalFile }; string unmangle_source_file(const string& source_file, int line, UnmangleType type) { string source_and_line = source_file + ":" + std::to_string((long long)line); if (source_file.compare(0, 3, "hg:") != 0) { if (type != Annotate) { return ""; } return source_and_line; } string ret = type != Annotate ? "" : source_and_line; string s = source_file; char* junk = strtok(&s[0], ":"); char* repo = strtok(nullptr, ":"); char* path = strtok(nullptr, ":"); char* rev = strtok(nullptr, ":"); if (repo && path && rev) { if (type == RawFile) { char url[1024]; snprintf(url, sizeof(url), "http://%s/raw-file/%s/%s", repo, rev, path); ret = url; } else if (type == LocalFile) { char filename[1024]; snprintf(filename, sizeof(filename), "/tmp/%s_%s_%s", repo, rev, path); char* c; while ((c = strchr(filename+5, '/')) != nullptr) { *c = '_'; } ret = filename; } else { char url[1024]; snprintf(url, sizeof(url), "http://%s/annotate/%s/%s#l%d", repo, rev, path, line); ret = url; } } return ret; } static bool file_exists(const string &file_name) { struct stat sb; return stat(file_name.c_str(), &sb) == 0; } bool get_line_from_file(const string& file, int line, string& out) { FILE* f = fopen(file.c_str(), "r"); if (!f) { return false; } char source[1024]; for (int current = 1; current <= line; current++) { if (!fgets(source, sizeof(source), f)) { break; } if (current == line) { out = source; fclose(f); return true; } } fclose(f); return false; } bool fetch_url_to_file(const string& url, const string& file) { string tempfile = file + ".tmp"; FILE* f = fopen(tempfile.c_str(), "w"); if (!f) { return false; } curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_ENCODING, ""); curl_easy_setopt(curl, CURLOPT_STDERR, stderr); curl_easy_setopt(curl, CURLOPT_WRITEDATA, f); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); bool result; long retcode = -1; if (curl_easy_perform(curl) != 0 || curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &retcode) != 0 || retcode != 200) { result = false; } else { result = true; } if (!result) { return false; } fclose(f); if (rename(tempfile.c_str(), file.c_str()) == 0) { return true; } unlink(tempfile.c_str()); return false; } bool get_line_from_url(const string& url, const string& file, int line, string& out) { // Check for URLs that failed. if (error_symbols.find(url) != error_symbols.end()) { return false; } if (!file_exists(file)) { // Fetch URL. if (!fetch_url_to_file(url, file)) { error_symbols.insert(url); return false; } } return get_line_from_file(file, line, out); } void print_source_line(const string& file, int line) { string url = unmangle_source_file(file, line, RawFile); if (url.empty()) { return; } string local_file = unmangle_source_file(file, line, LocalFile); string out; if (get_line_from_url(url, local_file, line, out)) { printf("% 5d %s", line, out.c_str()); } } void print_frame(const StackFrame& frame, const StackFrame& last_frame) { if (!frame.source_file_name.empty()) { bool new_file = false; if (frame.source_file_name != last_frame.source_file_name) { printf("%s\n", unmangle_source_file(frame.source_file_name, frame.source_line, Annotate).c_str()); new_file = true; } if (new_file || frame.source_line != last_frame.source_line) { print_source_line(frame.source_file_name, frame.source_line); } } else if (frame.module && (!last_frame.module || frame.module->code_file() != last_frame.module->code_file())) { printf("%s+0x%lx\n", PathnameStripper::File(frame.module->code_file()).c_str(), frame.instruction - frame.module->base_address()); } } int main(int argc, char** argv) { static struct option long_options[] = { {"address", required_argument, nullptr, 'a'}, {"disassemble", no_argument, nullptr, 'd'}, {"help", no_argument, nullptr, 'h'}, {nullptr, 0, nullptr, 0} }; bool disassemble = false; char* address_arg = nullptr; int arg; int option_index = 0; while((arg = getopt_long(argc, argv, "", long_options, &option_index)) != -1) { switch(arg) { case 0: if (long_options[option_index].flag != 0) break; break; case 'd': disassemble = true; break; case 'a': address_arg = optarg; break; case 'h': usage(); return 0; case '?': break; default: fprintf(stderr, "Unknown option: -%c\n", (char)arg); usage(); return 1; } } if (optind >= argc) { usage(); return 1; } const char* minidump_file = argv[optind]; Minidump minidump(minidump_file); if (!minidump.Read()) { error("Couldn't read minidump %s", minidump_file); } vector<string> symbol_paths; // allow symbol paths to be passed on the commandline. for (int i = optind + 1; i < argc; i++) { symbol_paths.push_back(argv[i]); } MinidumpMemoryList* memory_list = minidump.GetMemoryList(); if (!memory_list) { error("Minidump %s doesn't contain a memory list", minidump_file); } MinidumpModuleList* module_list = minidump.GetModuleList(); if (!module_list) { error("Minidump %s doesn't contain a module list", minidump_file); } u_int64_t instruction_pointer; if (address_arg) { instruction_pointer = strtoull(address_arg, NULL, 16); arg++; } else { MinidumpException* exception = minidump.GetException(); if (!exception) { error("Minidump doesn't contain exception information"); } MinidumpContext* context = exception->GetContext(); if (!context->GetInstructionPointer(&instruction_pointer)) { error("Couldn't get instruction pointer. Unknown CPU?"); } } MinidumpMemoryRegion* region = memory_list->GetMemoryRegionForAddress(instruction_pointer); if (!region) { error("Minidump doesn't contain a memory region that contains " "the instruction pointer from the exception record"); } printf("Faulting instruction pointer: 0x%08lx\n", instruction_pointer); const u_int8_t* bytes = region->GetMemory(); if (disassemble) { curl = curl_easy_init(); char tempfile[1024] = "/tmp/minidump-instructions-XXXXXX"; int fd = mkstemp(tempfile); write(fd, bytes, region->GetSize()); close(fd); const char* arch; const char* archopts = ""; const char* objdump = "objdump"; uint32_t cpu; minidump.GetContextCPUFlagsFromSystemInfo(&cpu); switch (cpu) { case MD_CONTEXT_X86: arch = "i386"; archopts = "att-mnemonic,i386,addr32,data32"; break; case MD_CONTEXT_AMD64: arch = "i386:x86-64"; archopts = "att-mnemonic,x86-64"; break; case MD_CONTEXT_ARM: //XXX: might not work everywhere //"arm-linux-gnueabi-objdump" objdump = "arm-linux-androideabi-objdump"; arch = "arm"; //XXX: not sure how to tell whether force-thumb is needed archopts = "reg-names-std,force-thumb"; break; default: error("Unknown CPU architecture"); } char cmdline[1024]; sprintf(cmdline, "%s -b binary -m %s -M %s --adjust-vma=0x%lx -D \"%s\"", objdump, arch, archopts, region->GetBase(), tempfile); FILE* fp = popen(cmdline, "r"); if (!fp) { error("Couldn't launch objdump"); } SimpleSymbolSupplier supplier(symbol_paths); BasicSourceLineResolver resolver; StackFrameSymbolizer symbolizer(&supplier, &resolver); SystemInfo system_info; MinidumpProcessor::GetCPUInfo(&minidump, &system_info); MinidumpProcessor::GetOSInfo(&minidump, &system_info); StackFrame last_frame = {}; char line[LINE_MAX]; bool printed_highlight = false; while (fgets(line, LINE_MAX, fp) != nullptr) { const char* p = strchr(line, ':'); StackFrame frame = {}; if (p && (p - line == 8 || p - line == 16) && !strstr(line, "<.data>:")) { frame.instruction = strtoull(line, nullptr, 16); symbolizer.FillSourceLineInfo(module_list, &system_info, &frame); print_frame(frame, last_frame); last_frame = frame; } printf("%s", line); if (frame.instruction >= instruction_pointer && !printed_highlight) { int l = strlen(line); for (int i = 0; i < l; i++) { if (line[i] == '\t') { putc('\t', stdout); } else { putc('^', stdout); } } printf("\n"); printed_highlight = true; } } unlink(tempfile); if (pclose(fp) == -1) { error("Error running objdump"); } curl_easy_cleanup(curl); } else { printf("Memory:"); const int kBytesPerLine = 16; for (unsigned int i = 0; i < region->GetSize(); i++) { if ((i % kBytesPerLine) == 0) { printf("\n%08lx ", region->GetBase() + i); } printf("%02x ", bytes[i]); } printf("\n"); } return 0; } <|endoftext|>
<commit_before>#ifdef MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL #define MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL #include <vector> #include <algorithm> #include <cmath> namespace mjolnir { /* Implicit membrane potential & derivative * * potential field dependent on z coordinate. * * tanh is used to represent membrane potential. * * V(z) = ma * tanh(be * (|z| - th)) * * dV/dr = ma * z / (|z| * tanh(be * (|z| - th))) */ template<typename traitT> class ImplicitMembranePotential { public: typedef traitT traits_type; typedef typename traits_type::real_type real_type; typedef typename traits_type::coordinate_type coordinate_type; public: ImplicitMembranePotential(const real_type th, const real_type ma, const real_type be) : thickness_(th),interantion_magnitude_(ma),bend_(be); {} ~ImplicitMembranePotential() = default; real_type potential(const real_type z) const { return this->interantion_magnitude_ * tanh(bend_ * (abs(z) - thickness_)); } real_type derivative(const real_type z) const { return this->interantion_magnitude_ * z / (abs(z) * tanh(bend_ * (abs(z) - thickness_))); } void reset_parameter(const std::string&, const real_type){return;} private: const real_type thickness_; const real_type interantion_magnitude_; const real_type bend_; }; } #endif /* MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL */ <commit_msg>add namespace specifier<commit_after>#ifdef MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL #define MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL #include <cmath> namespace mjolnir { /* Implicit membrane potential & derivative * * potential field dependent on z coordinate. * * tanh is used to represent membrane potential. * * V(z) = ma * tanh(be * (|z| - th)) * * dV/dr = ma * z / (|z| * tanh(be * (|z| - th))) */ template<typename traitT> class ImplicitMembranePotential { public: typedef traitT traits_type; typedef typename traits_type::real_type real_type; typedef typename traits_type::coordinate_type coordinate_type; public: ImplicitMembranePotential(const real_type th, const real_type ma, const real_type be) : thickness_(th),interantion_magnitude_(ma),bend_(be); {} ~ImplicitMembranePotential() = default; real_type potential(const real_type z) const { return this->interantion_magnitude_ * std::tanh(bend_ * (std::abs(z) - thickness_)); } real_type derivative(const real_type z) const { return this->interantion_magnitude_ * z / (std::abs(z) * std::tanh(bend_ * (std::abs(z) - thickness_))); } void reset_parameter(const std::string&, const real_type){return;} private: const real_type thickness_; const real_type interantion_magnitude_; const real_type bend_; }; } #endif /* MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL */ <|endoftext|>
<commit_before>/* Copyright (C) 2013 Slawomir Cygan <slawomir.cygan@gmail.com> * * 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 <stdexcept> #include "dglblitterbase.h" #include <DGLNet/protocol/pixeltransfer.h> DGLBlitterBase::DGLBlitterBase() { for (size_t i = 0; i < DGL_ARRAY_LENGTH(m_ChannelScaleBiases); i++) { m_ChannelScaleBiases[i] = std::pair<float, float>(1.0f, 0.0f); } } void DGLBlitterBase::blit(unsigned int width, unsigned int height, unsigned int rowBytes, gl_t format, gl_t type, const void* data) { m_SrcStride = rowBytes; m_Width = width; m_Height = height; m_DataFormat = GLFormats::getDataFormat(format); m_DataType = GLFormats::getDataType(type); if (!m_DataFormat || !m_DataType) { throw std::runtime_error( "Got image of unknown type and format. It may be debugger bug"); } m_SrcData = data; doBlit(); } void DGLBlitterBase::setChannelScale(Channel channel, float scale, float bias) { m_ChannelScaleBiases[channel] = std::pair<float, float>(scale, bias); if (m_DataFormat && m_DataType) { doBlit(); } } void DGLBlitterBase::doBlit() { OutputFormat outputFormat = _GL_RGBX32; std::pair<float, float> channelSBs[4] = { std::pair<float, float>(1.0f, 0.0f), std::pair<float, float>(1.0f, 0.0f), std::pair<float, float>(1.0f, 0.0f), std::pair<float, float>(1.0f, 0.0f)}; switch (m_DataFormat->format) { case GL_RED: case GL_RG: case GL_RGB: case GL_RED_INTEGER: case GL_RG_INTEGER: case GL_RGB_INTEGER: outputFormat = _GL_RGBX32; channelSBs[0] = m_ChannelScaleBiases[CHANNEL_R]; channelSBs[1] = m_ChannelScaleBiases[CHANNEL_G]; channelSBs[2] = m_ChannelScaleBiases[CHANNEL_B]; break; case GL_RGBA: case GL_RGBA_INTEGER: outputFormat = _GL_BGRA32; channelSBs[0] = m_ChannelScaleBiases[CHANNEL_B]; channelSBs[1] = m_ChannelScaleBiases[CHANNEL_G]; channelSBs[2] = m_ChannelScaleBiases[CHANNEL_R]; channelSBs[3] = m_ChannelScaleBiases[CHANNEL_A]; break; case GL_DEPTH_COMPONENT: outputFormat = _GL_MONO8; channelSBs[0] = m_ChannelScaleBiases[CHANNEL_D]; break; case GL_STENCIL_INDEX: channelSBs[0] = m_ChannelScaleBiases[CHANNEL_S]; outputFormat = _GL_MONO8; break; case GL_ALPHA: channelSBs[0] = m_ChannelScaleBiases[CHANNEL_A]; outputFormat = _GL_MONO8; break; case GL_LUMINANCE: outputFormat = _GL_MONO8; break; case GL_DEPTH_STENCIL: outputFormat = _GL_RGBX32; channelSBs[0] = m_ChannelScaleBiases[CHANNEL_D]; channelSBs[1] = m_ChannelScaleBiases[CHANNEL_S]; break; case GL_LUMINANCE_ALPHA: outputFormat = _GL_RGBX32; break; default: DGL_ASSERT(0); } int srcPixelSize = 0; if (m_DataType->packed) { srcPixelSize = m_DataType->byteSize; } else { srcPixelSize = m_DataFormat->components * m_DataType->byteSize; } size_t dstPixelSize = 0; for (int i = 0; i < 4; i++) { if (outputOffsets[outputFormat][i] >= 0) dstPixelSize++; } size_t targetRowBytes = (m_Width * dstPixelSize + 4 - 1) & (-4); if (outputData.size() < size_t(targetRowBytes * m_Height)) outputData = std::vector<char>(targetRowBytes * m_Height); m_DataType->blitFunc(outputOffsets[outputFormat], m_Width, m_Height, m_SrcData, &outputData[0], m_SrcStride, targetRowBytes, srcPixelSize, dstPixelSize, m_DataFormat->components, channelSBs); sink(m_Width, m_Height, outputFormat, &outputData[0]); } std::vector<AnyValue> DGLBlitterBase::describePixel(unsigned int x, unsigned int y) { if (!m_SrcStride || !m_DataType || !m_DataFormat || x > m_Width || y > m_Height) { return std::vector<AnyValue>(); } int srcPixelSize = 0; if (m_DataType->packed) { srcPixelSize = m_DataType->byteSize; } else { srcPixelSize = m_DataFormat->components * m_DataType->byteSize; } const void* pixPtr = &reinterpret_cast<const unsigned char*>( m_SrcData)[y * m_SrcStride + x * srcPixelSize]; return m_DataType->extractor(pixPtr, m_DataFormat->components); } const int DGLBlitterBase::outputOffsets[3][4] = {{2, 1, 0, 3}, {0, 1, 2, -1}, {0, -1, -1, -1}}; <commit_msg>Fixup random crashes in DGLBlitterBase due to uninitialized pointers.<commit_after>/* Copyright (C) 2013 Slawomir Cygan <slawomir.cygan@gmail.com> * * 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 <stdexcept> #include "dglblitterbase.h" #include <DGLNet/protocol/pixeltransfer.h> DGLBlitterBase::DGLBlitterBase() : m_SrcData(nullptr), m_DataFormat(nullptr), m_DataType(nullptr), m_Width(0), m_Height(0) { for (size_t i = 0; i < DGL_ARRAY_LENGTH(m_ChannelScaleBiases); i++) { m_ChannelScaleBiases[i] = std::pair<float, float>(1.0f, 0.0f); } } void DGLBlitterBase::blit(unsigned int width, unsigned int height, unsigned int rowBytes, gl_t format, gl_t type, const void* data) { m_SrcStride = rowBytes; m_Width = width; m_Height = height; m_DataFormat = GLFormats::getDataFormat(format); m_DataType = GLFormats::getDataType(type); if (!m_DataFormat || !m_DataType) { throw std::runtime_error( "Got image of unknown type and format. It may be debugger bug"); } m_SrcData = data; doBlit(); } void DGLBlitterBase::setChannelScale(Channel channel, float scale, float bias) { m_ChannelScaleBiases[channel] = std::pair<float, float>(scale, bias); if (m_DataFormat && m_DataType) { doBlit(); } } void DGLBlitterBase::doBlit() { OutputFormat outputFormat = _GL_RGBX32; std::pair<float, float> channelSBs[4] = { std::pair<float, float>(1.0f, 0.0f), std::pair<float, float>(1.0f, 0.0f), std::pair<float, float>(1.0f, 0.0f), std::pair<float, float>(1.0f, 0.0f)}; switch (m_DataFormat->format) { case GL_RED: case GL_RG: case GL_RGB: case GL_RED_INTEGER: case GL_RG_INTEGER: case GL_RGB_INTEGER: outputFormat = _GL_RGBX32; channelSBs[0] = m_ChannelScaleBiases[CHANNEL_R]; channelSBs[1] = m_ChannelScaleBiases[CHANNEL_G]; channelSBs[2] = m_ChannelScaleBiases[CHANNEL_B]; break; case GL_RGBA: case GL_RGBA_INTEGER: outputFormat = _GL_BGRA32; channelSBs[0] = m_ChannelScaleBiases[CHANNEL_B]; channelSBs[1] = m_ChannelScaleBiases[CHANNEL_G]; channelSBs[2] = m_ChannelScaleBiases[CHANNEL_R]; channelSBs[3] = m_ChannelScaleBiases[CHANNEL_A]; break; case GL_DEPTH_COMPONENT: outputFormat = _GL_MONO8; channelSBs[0] = m_ChannelScaleBiases[CHANNEL_D]; break; case GL_STENCIL_INDEX: channelSBs[0] = m_ChannelScaleBiases[CHANNEL_S]; outputFormat = _GL_MONO8; break; case GL_ALPHA: channelSBs[0] = m_ChannelScaleBiases[CHANNEL_A]; outputFormat = _GL_MONO8; break; case GL_LUMINANCE: outputFormat = _GL_MONO8; break; case GL_DEPTH_STENCIL: outputFormat = _GL_RGBX32; channelSBs[0] = m_ChannelScaleBiases[CHANNEL_D]; channelSBs[1] = m_ChannelScaleBiases[CHANNEL_S]; break; case GL_LUMINANCE_ALPHA: outputFormat = _GL_RGBX32; break; default: DGL_ASSERT(0); } int srcPixelSize = 0; if (m_DataType->packed) { srcPixelSize = m_DataType->byteSize; } else { srcPixelSize = m_DataFormat->components * m_DataType->byteSize; } size_t dstPixelSize = 0; for (int i = 0; i < 4; i++) { if (outputOffsets[outputFormat][i] >= 0) dstPixelSize++; } size_t targetRowBytes = (m_Width * dstPixelSize + 4 - 1) & (-4); if (outputData.size() < size_t(targetRowBytes * m_Height)) outputData = std::vector<char>(targetRowBytes * m_Height); m_DataType->blitFunc(outputOffsets[outputFormat], m_Width, m_Height, m_SrcData, &outputData[0], m_SrcStride, targetRowBytes, srcPixelSize, dstPixelSize, m_DataFormat->components, channelSBs); sink(m_Width, m_Height, outputFormat, &outputData[0]); } std::vector<AnyValue> DGLBlitterBase::describePixel(unsigned int x, unsigned int y) { if (!m_SrcStride || !m_DataType || !m_DataFormat || x > m_Width || y > m_Height) { return std::vector<AnyValue>(); } int srcPixelSize = 0; if (m_DataType->packed) { srcPixelSize = m_DataType->byteSize; } else { srcPixelSize = m_DataFormat->components * m_DataType->byteSize; } const void* pixPtr = &reinterpret_cast<const unsigned char*>( m_SrcData)[y * m_SrcStride + x * srcPixelSize]; return m_DataType->extractor(pixPtr, m_DataFormat->components); } const int DGLBlitterBase::outputOffsets[3][4] = {{2, 1, 0, 3}, {0, 1, 2, -1}, {0, -1, -1, -1}}; <|endoftext|>
<commit_before>#pragma once /* * A page-table-like structure for mapping fixed-length keys to void* ptrs. */ #include "gc.hh" #include <iterator> enum { bits_per_level = 9 }; enum { key_bits = 36 }; enum { radix_levels = (key_bits + bits_per_level - 1) / bits_per_level }; class radix_elem; class radix_node; /* * Each pointer to a radix_elem or radix_node can be in one of four * states: * * - pointer to radix_node * - unlocked leaf * - locked leaf * - dead leaf * * A leaf is either a pointer to a radix_elem or null. * * Before making semantic modifications to a range, the range must be * locked. This is done by locking the leaf pointers (be they to * radix_entry or null) corresponding to that range. If necessary, a * leaf may be "pushed down" and replaced with a pointer to radix_node * full of the old value to get the endpoints accurate. Locking NEVER * happens higher level than the current set of leaves. * * We assuming that a thread attempting to push down a leaf is doing * so to lock it. * * When replacing a range, we'd like to possibly retire old * radix_nodes when their contents are all set to be the same. Before * doing this, all leaves under that radix_node must be locked. We * transition them to 'dead leaf' state. This informs all others * attempting to lock the pointer to retry. The radix_node itself is * RCU-freed. To avoid restarting writers, set the leaves to the right * value too. Replaced elements are written in locked state, to be * unlocked when the radix_range goes away. * * Once a pointer is dead, it stays dead until the containing * radix_node is deallocated. Dead pointers do not own references. * * For now we do not implement the dead state. It is only necessary * when collapsing an already-expanded node. It's unclear this * optimization is very useful as it requires RCU-freeing radix_nodes, * which makes them just over a power of 2 and inefficient to * allocate. * * Races: * * - If a leaf to be locked (or pushed down) gets pushed down, lock * the new radix_node at a more granular level. * * - If a leaf to be locked (or pushed down) goes dead, restart * everything from the root. Many values may have gone invalid. * * - If a leaf to be locked (or pushed down) gets locked, spin. * * [*] XXX: Try not to bounce on the radix_elem refcount too much. */ enum entry_state { entry_unlocked = 0, entry_locked = 1, // entry_dead = 2, entry_node = 2, entry_mask = 3 }; class radix_entry { public: radix_entry() : value_(0 | entry_unlocked) { } explicit radix_entry(uptr value) : value_(value) { } explicit radix_entry(radix_node *ptr) : value_(reinterpret_cast<uptr>(ptr) | entry_node) { // XXX: This is kinda wonky. Maybe switch the status to // entry_unlocked is ptr is null, make null pass both is_elem() // and is_node(). assert(ptr != nullptr); } explicit radix_entry(radix_elem *ptr, entry_state state = entry_unlocked) : value_(reinterpret_cast<uptr>(ptr) | state) { assert(state != entry_node); } explicit radix_entry(decltype(nullptr) nullp, entry_state state = entry_unlocked) : value_(0 | state) { assert(state != entry_node); } uptr value() const { return value_; } uptr& value() { return value_; } entry_state state() const { return static_cast<entry_state>(value_ & entry_mask); } uptr ptr() const { return value_ & ~entry_mask; } bool is_node() const { return state() == entry_node; } bool is_elem() const { return !is_node(); } bool is_null() const { return ptr() == 0; } // Convenience function radix_entry with_state(entry_state state) { return radix_entry(elem(), state); } radix_elem *elem() const { assert(is_elem()); return reinterpret_cast<radix_elem*>(ptr()); } radix_node *node() const { assert(is_node()); return reinterpret_cast<radix_node*>(ptr()); } void release(); private: uptr value_; }; // Our version of std::atomic doesn't work for structs, even if they // are integer sized. class radix_ptr { public: radix_ptr() : ptr_(radix_entry().value()) { } radix_ptr(radix_entry e) : ptr_(e.value()) { } radix_entry load() const { return radix_entry(ptr_.load()); } void store(radix_entry e) { ptr_.store(e.value()); } bool compare_exchange_weak(radix_entry &old, radix_entry val) { return ptr_.compare_exchange_weak(old.value(), val.value()); } private: static_assert(sizeof(uptr) == sizeof(radix_entry), "radix_entry is a uptr"); std::atomic<uptr> ptr_; }; class radix_elem : public rcu_freed { private: bool deleted_; std::atomic<u64> ref_; public: radix_elem() : rcu_freed("radix_elem"), deleted_(false), ref_(0) {} bool deleted() { return deleted_; } void decref(u64 delta = 1) { if ((ref_ -= delta) == 0) { deleted_ = true; gc_delayed(this); } } void incref(u64 delta = 1) { ref_ += delta; } }; struct radix_node { radix_ptr child[1 << bits_per_level]; // We need to customize not only allocation but initialization, so // radix_node has no constructors. Instead, use create. radix_node() = delete; radix_node(const radix_node &o) = delete; static radix_node *create(); ~radix_node(); // Since we use custom allocation for radix_node's, we must also // custom delete them. Note that callers may alternatively use // zfree when freeing a radix_node that's known to be empty (for // example, after failed optimistic concurrency). static void operator delete(void *p); }; // Assert we have enough spare bits for all flags. static_assert(alignof(radix_node) > entry_mask, "radix_node sufficiently aligned"); static_assert(alignof(radix_elem) > entry_mask, "radix_elem sufficiently aligned"); struct radix; struct radix_iterator; struct radix_range { radix* r_; u64 start_; u64 size_; radix_range(radix* r, u64 start, u64 size); radix_range(radix_range&&); ~radix_range(); void replace(u64 start, u64 size, radix_elem* val); radix_iterator begin() const; radix_iterator end() const; radix_range(const radix_range&) = delete; void operator=(const radix_range&) = delete; }; struct radix { typedef radix_iterator iterator; radix_ptr root_; u32 shift_; radix(u32 shift) : root_(radix_entry(radix_node::create())), shift_(shift) { } ~radix(); radix_elem* search(u64 key); radix_range search_lock(u64 start, u64 size); radix_iterator begin() const; radix_iterator end() const; NEW_DELETE_OPS(radix) }; struct radix_iterator { const radix* r_; u64 k_; // The key value just past the end of the range being iterator over. u64 key_limit_; // path_[i] points into the child array of the node at level i. const radix_ptr *path_[radix_levels]; // The level of the current element. u32 level_; radix_iterator(const radix* r, u64 k, u64 limit) : r_(r), k_(k), key_limit_(limit) { if (k_ != key_limit_) prime_path(); } radix_iterator &operator++() { assert(k_ < key_limit_); advance(); return *this; } radix_elem* operator*() { return path_[level_]->load().elem(); } // Compare equality on just the key. bool operator==(const radix_iterator &other) { return r_ == other.r_ && k_ == other.k_; } bool operator!=(const radix_iterator &other) { return r_ != other.r_ || k_ != other.k_; } private: // Prepare the initial path_ and level_ based on k_. void prime_path(); // Advance to the next non-null leaf. This assumes that // k_ < key_limit_. void advance(); }; inline radix_iterator radix_range::begin() const { return radix_iterator(r_, start_, start_ + size_); } inline radix_iterator radix_range::end() const { return radix_iterator(r_, start_ + size_, start_ + size_); } inline radix_iterator radix::begin() const { return radix_iterator(this, 0, (u64)1 << key_bits); } inline radix_iterator radix::end() const { return radix_iterator(this, (u64)1 << key_bits, (u64)1 << key_bits); } <commit_msg>radix: Make radix_iterator fields private<commit_after>#pragma once /* * A page-table-like structure for mapping fixed-length keys to void* ptrs. */ #include "gc.hh" #include <iterator> enum { bits_per_level = 9 }; enum { key_bits = 36 }; enum { radix_levels = (key_bits + bits_per_level - 1) / bits_per_level }; class radix_elem; class radix_node; /* * Each pointer to a radix_elem or radix_node can be in one of four * states: * * - pointer to radix_node * - unlocked leaf * - locked leaf * - dead leaf * * A leaf is either a pointer to a radix_elem or null. * * Before making semantic modifications to a range, the range must be * locked. This is done by locking the leaf pointers (be they to * radix_entry or null) corresponding to that range. If necessary, a * leaf may be "pushed down" and replaced with a pointer to radix_node * full of the old value to get the endpoints accurate. Locking NEVER * happens higher level than the current set of leaves. * * We assuming that a thread attempting to push down a leaf is doing * so to lock it. * * When replacing a range, we'd like to possibly retire old * radix_nodes when their contents are all set to be the same. Before * doing this, all leaves under that radix_node must be locked. We * transition them to 'dead leaf' state. This informs all others * attempting to lock the pointer to retry. The radix_node itself is * RCU-freed. To avoid restarting writers, set the leaves to the right * value too. Replaced elements are written in locked state, to be * unlocked when the radix_range goes away. * * Once a pointer is dead, it stays dead until the containing * radix_node is deallocated. Dead pointers do not own references. * * For now we do not implement the dead state. It is only necessary * when collapsing an already-expanded node. It's unclear this * optimization is very useful as it requires RCU-freeing radix_nodes, * which makes them just over a power of 2 and inefficient to * allocate. * * Races: * * - If a leaf to be locked (or pushed down) gets pushed down, lock * the new radix_node at a more granular level. * * - If a leaf to be locked (or pushed down) goes dead, restart * everything from the root. Many values may have gone invalid. * * - If a leaf to be locked (or pushed down) gets locked, spin. * * [*] XXX: Try not to bounce on the radix_elem refcount too much. */ enum entry_state { entry_unlocked = 0, entry_locked = 1, // entry_dead = 2, entry_node = 2, entry_mask = 3 }; class radix_entry { public: radix_entry() : value_(0 | entry_unlocked) { } explicit radix_entry(uptr value) : value_(value) { } explicit radix_entry(radix_node *ptr) : value_(reinterpret_cast<uptr>(ptr) | entry_node) { // XXX: This is kinda wonky. Maybe switch the status to // entry_unlocked is ptr is null, make null pass both is_elem() // and is_node(). assert(ptr != nullptr); } explicit radix_entry(radix_elem *ptr, entry_state state = entry_unlocked) : value_(reinterpret_cast<uptr>(ptr) | state) { assert(state != entry_node); } explicit radix_entry(decltype(nullptr) nullp, entry_state state = entry_unlocked) : value_(0 | state) { assert(state != entry_node); } uptr value() const { return value_; } uptr& value() { return value_; } entry_state state() const { return static_cast<entry_state>(value_ & entry_mask); } uptr ptr() const { return value_ & ~entry_mask; } bool is_node() const { return state() == entry_node; } bool is_elem() const { return !is_node(); } bool is_null() const { return ptr() == 0; } // Convenience function radix_entry with_state(entry_state state) { return radix_entry(elem(), state); } radix_elem *elem() const { assert(is_elem()); return reinterpret_cast<radix_elem*>(ptr()); } radix_node *node() const { assert(is_node()); return reinterpret_cast<radix_node*>(ptr()); } void release(); private: uptr value_; }; // Our version of std::atomic doesn't work for structs, even if they // are integer sized. class radix_ptr { public: radix_ptr() : ptr_(radix_entry().value()) { } radix_ptr(radix_entry e) : ptr_(e.value()) { } radix_entry load() const { return radix_entry(ptr_.load()); } void store(radix_entry e) { ptr_.store(e.value()); } bool compare_exchange_weak(radix_entry &old, radix_entry val) { return ptr_.compare_exchange_weak(old.value(), val.value()); } private: static_assert(sizeof(uptr) == sizeof(radix_entry), "radix_entry is a uptr"); std::atomic<uptr> ptr_; }; class radix_elem : public rcu_freed { private: bool deleted_; std::atomic<u64> ref_; public: radix_elem() : rcu_freed("radix_elem"), deleted_(false), ref_(0) {} bool deleted() { return deleted_; } void decref(u64 delta = 1) { if ((ref_ -= delta) == 0) { deleted_ = true; gc_delayed(this); } } void incref(u64 delta = 1) { ref_ += delta; } }; struct radix_node { radix_ptr child[1 << bits_per_level]; // We need to customize not only allocation but initialization, so // radix_node has no constructors. Instead, use create. radix_node() = delete; radix_node(const radix_node &o) = delete; static radix_node *create(); ~radix_node(); // Since we use custom allocation for radix_node's, we must also // custom delete them. Note that callers may alternatively use // zfree when freeing a radix_node that's known to be empty (for // example, after failed optimistic concurrency). static void operator delete(void *p); }; // Assert we have enough spare bits for all flags. static_assert(alignof(radix_node) > entry_mask, "radix_node sufficiently aligned"); static_assert(alignof(radix_elem) > entry_mask, "radix_elem sufficiently aligned"); struct radix; struct radix_iterator; struct radix_range { radix* r_; u64 start_; u64 size_; radix_range(radix* r, u64 start, u64 size); radix_range(radix_range&&); ~radix_range(); void replace(u64 start, u64 size, radix_elem* val); radix_iterator begin() const; radix_iterator end() const; radix_range(const radix_range&) = delete; void operator=(const radix_range&) = delete; }; struct radix { typedef radix_iterator iterator; radix_ptr root_; u32 shift_; radix(u32 shift) : root_(radix_entry(radix_node::create())), shift_(shift) { } ~radix(); radix_elem* search(u64 key); radix_range search_lock(u64 start, u64 size); radix_iterator begin() const; radix_iterator end() const; NEW_DELETE_OPS(radix) }; struct radix_iterator { radix_iterator(const radix* r, u64 k, u64 limit) : r_(r), k_(k), key_limit_(limit) { if (k_ != key_limit_) prime_path(); } radix_iterator &operator++() { assert(k_ < key_limit_); advance(); return *this; } radix_elem* operator*() { return path_[level_]->load().elem(); } // Compare equality on just the key. bool operator==(const radix_iterator &other) { return r_ == other.r_ && k_ == other.k_; } bool operator!=(const radix_iterator &other) { return r_ != other.r_ || k_ != other.k_; } private: const radix* r_; u64 k_; // The key value just past the end of the range being iterator over. u64 key_limit_; // path_[i] points into the child array of the node at level i. const radix_ptr *path_[radix_levels]; // The level of the current element. u32 level_; // Prepare the initial path_ and level_ based on k_. void prime_path(); // Advance to the next non-null leaf. This assumes that // k_ < key_limit_. void advance(); }; inline radix_iterator radix_range::begin() const { return radix_iterator(r_, start_, start_ + size_); } inline radix_iterator radix_range::end() const { return radix_iterator(r_, start_ + size_, start_ + size_); } inline radix_iterator radix::begin() const { return radix_iterator(this, 0, (u64)1 << key_bits); } inline radix_iterator radix::end() const { return radix_iterator(this, (u64)1 << key_bits, (u64)1 << key_bits); } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PresenterHelpView.hxx,v $ * * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SDEXT_PRESENTER_HELP_VIEW_HXX #define SDEXT_PRESENTER_HELP_VIEW_HXX #include "PresenterController.hxx" #include <cppuhelper/basemutex.hxx> #include <cppuhelper/compbase3.hxx> #include <com/sun/star/awt/XPaintListener.hpp> #include <com/sun/star/awt/XWindowListener.hpp> #include <com/sun/star/drawing/framework/XView.hpp> #include <com/sun/star/drawing/framework/XResourceId.hpp> #include <com/sun/star/frame/XController.hpp> #include <com/sun/star/rendering/XSpriteCanvas.hpp> namespace css = ::com::sun::star; namespace { typedef cppu::WeakComponentImplHelper3< css::drawing::framework::XView, css::awt::XWindowListener, css::awt::XPaintListener > PresenterHelpViewInterfaceBase; } namespace sdext { namespace presenter { /** Experimental. Do not use (yet). */ class PresenterHelpView : private ::cppu::BaseMutex, public PresenterHelpViewInterfaceBase { public: explicit PresenterHelpView ( const css::uno::Reference<css::uno::XComponentContext>& rxContext, const css::uno::Reference<css::drawing::framework::XResourceId>& rxViewId, const css::uno::Reference<css::frame::XController>& rxController, const ::rtl::Reference<PresenterController>& rpPresenterController); virtual ~PresenterHelpView (void); virtual void SAL_CALL disposing (void); // lang::XEventListener virtual void SAL_CALL disposing (const css::lang::EventObject& rEventObject) throw (css::uno::RuntimeException); // XWindowListener virtual void SAL_CALL windowResized (const css::awt::WindowEvent& rEvent) throw (css::uno::RuntimeException); virtual void SAL_CALL windowMoved (const css::awt::WindowEvent& rEvent) throw (css::uno::RuntimeException); virtual void SAL_CALL windowShown (const css::lang::EventObject& rEvent) throw (css::uno::RuntimeException); virtual void SAL_CALL windowHidden (const css::lang::EventObject& rEvent) throw (css::uno::RuntimeException); // XPaintListener virtual void SAL_CALL windowPaint (const css::awt::PaintEvent& rEvent) throw (css::uno::RuntimeException); // XResourceId virtual css::uno::Reference<css::drawing::framework::XResourceId> SAL_CALL getResourceId (void) throw (css::uno::RuntimeException); virtual sal_Bool SAL_CALL isAnchorOnly (void) throw (com::sun::star::uno::RuntimeException); private: css::uno::Reference<css::uno::XComponentContext> mxComponentContext; css::uno::Reference<css::drawing::framework::XResourceId> mxViewId; css::uno::Reference<css::drawing::framework::XPane> mxPane; css::uno::Reference<css::awt::XWindow> mxWindow; ::rtl::Reference<PresenterController> mpPresenterController; css::uno::Reference<css::rendering::XSpriteCanvas> mxCanvas; css::uno::Reference<css::rendering::XCanvasFont> mxFont; void ProvideCanvas (void); void Resize (void); void Paint (const css::awt::Rectangle& rRedrawArea); /** This method throws a DisposedException when the object has already been disposed. */ void ThrowIfDisposed (void) throw (css::lang::DisposedException); }; } } // end of namespace ::sdext::presenter #endif <commit_msg>INTEGRATION: CWS presenterscreen (1.2.4); FILE MERGED 2008/04/30 08:17:43 af 1.2.4.3: #i88850# Make sure that all help text can be displayed. 2008/04/22 08:24:47 af 1.2.4.2: RESYNC: (1.2-1.3); FILE MERGED 2008/04/16 15:35:32 af 1.2.4.1: #i18486# Help view now displays supported keyboard keys.<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: PresenterHelpView.hxx,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. * ************************************************************************/ #ifndef SDEXT_PRESENTER_HELP_VIEW_HXX #define SDEXT_PRESENTER_HELP_VIEW_HXX #include "PresenterController.hxx" #include <cppuhelper/basemutex.hxx> #include <cppuhelper/compbase3.hxx> #include <com/sun/star/awt/XPaintListener.hpp> #include <com/sun/star/awt/XWindowListener.hpp> #include <com/sun/star/drawing/framework/XView.hpp> #include <com/sun/star/drawing/framework/XResourceId.hpp> #include <com/sun/star/frame/XController.hpp> #include <com/sun/star/rendering/XSpriteCanvas.hpp> namespace css = ::com::sun::star; namespace { typedef cppu::WeakComponentImplHelper3< css::drawing::framework::XView, css::awt::XWindowListener, css::awt::XPaintListener > PresenterHelpViewInterfaceBase; } namespace sdext { namespace presenter { class PresenterButton; /** Show help text that describes the defined keys. */ class PresenterHelpView : private ::cppu::BaseMutex, public PresenterHelpViewInterfaceBase { public: explicit PresenterHelpView ( const css::uno::Reference<css::uno::XComponentContext>& rxContext, const css::uno::Reference<css::drawing::framework::XResourceId>& rxViewId, const css::uno::Reference<css::frame::XController>& rxController, const ::rtl::Reference<PresenterController>& rpPresenterController); virtual ~PresenterHelpView (void); virtual void SAL_CALL disposing (void); // lang::XEventListener virtual void SAL_CALL disposing (const css::lang::EventObject& rEventObject) throw (css::uno::RuntimeException); // XWindowListener virtual void SAL_CALL windowResized (const css::awt::WindowEvent& rEvent) throw (css::uno::RuntimeException); virtual void SAL_CALL windowMoved (const css::awt::WindowEvent& rEvent) throw (css::uno::RuntimeException); virtual void SAL_CALL windowShown (const css::lang::EventObject& rEvent) throw (css::uno::RuntimeException); virtual void SAL_CALL windowHidden (const css::lang::EventObject& rEvent) throw (css::uno::RuntimeException); // XPaintListener virtual void SAL_CALL windowPaint (const css::awt::PaintEvent& rEvent) throw (css::uno::RuntimeException); // XResourceId virtual css::uno::Reference<css::drawing::framework::XResourceId> SAL_CALL getResourceId (void) throw (css::uno::RuntimeException); virtual sal_Bool SAL_CALL isAnchorOnly (void) throw (com::sun::star::uno::RuntimeException); private: class TextContainer; css::uno::Reference<css::uno::XComponentContext> mxComponentContext; css::uno::Reference<css::drawing::framework::XResourceId> mxViewId; css::uno::Reference<css::drawing::framework::XPane> mxPane; css::uno::Reference<css::awt::XWindow> mxWindow; css::uno::Reference<css::rendering::XCanvas> mxCanvas; ::rtl::Reference<PresenterController> mpPresenterController; PresenterTheme::SharedFontDescriptor mpFont; ::boost::scoped_ptr<TextContainer> mpTextContainer; ::rtl::Reference<PresenterButton> mpCloseButton; sal_Int32 mnSeparatorY; sal_Int32 mnMaximalWidth; void ProvideCanvas (void); void Resize (void); void Paint (const css::awt::Rectangle& rRedrawArea); void ReadHelpStrings (void); void ProcessString ( const css::uno::Reference<css::beans::XPropertySet>& rsProperties); /** Find a font size, so that all text can be displayed at the same time. */ void CheckFontSize (void); /** This method throws a DisposedException when the object has already been disposed. */ void ThrowIfDisposed (void) throw (css::lang::DisposedException); }; } } // end of namespace ::sdext::presenter #endif <|endoftext|>
<commit_before>/**************************************************************************** ** ** This file is part of QtCompositor** ** ** Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** ** Contact: Nokia Corporation qt-info@nokia.com ** ** You may use this file under the terms of the BSD license as follows: ** ** 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 Nokia Corporation and its Subsidiary(-ies) 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 "wlsurface.h" #include "waylandsurface.h" #include "wlcompositor.h" #include "wlshmbuffer.h" #include <QtCore/QDebug> #include <wayland-server.h> #include <linux/input.h> #ifdef QT_COMPOSITOR_WAYLAND_GL #include "hardware_integration/graphicshardwareintegration.h" #include <QtGui/QPlatformGLContext> #endif namespace Wayland { class SurfacePrivate { public: SurfacePrivate(struct wl_client *client, Compositor *compositor) : client(client) , compositor(compositor) , needsMap(false) , textureCreatedForBuffer(false) , directRenderBuffer(0) , surfaceBuffer(0) , surfaceType(WaylandSurface::Invalid) { #ifdef QT_COMPOSITOR_WAYLAND_GL texture_id = 0; #endif } WaylandSurface::Type type() const { if (surfaceType == WaylandSurface::Invalid) { SurfacePrivate *that = const_cast<SurfacePrivate *>(this); if (qtSurface->handle() == compositor->directRenderSurface()) { that->surfaceType = WaylandSurface::Direct; } else if (surfaceBuffer && wl_buffer_is_shm(surfaceBuffer)) { that->surfaceType = WaylandSurface::Shm; } else if (surfaceBuffer){ that->surfaceType = WaylandSurface::Texture; } } return surfaceType; } void attach(struct wl_buffer *buffer) { this->surfaceBuffer = buffer; surfaceType = WaylandSurface::Invalid; textureCreatedForBuffer = false; } inline struct wl_buffer *buffer() const { return surfaceBuffer; } struct wl_client *client; Compositor *compositor; WaylandSurface *qtSurface; #ifdef QT_COMPOSITOR_WAYLAND_GL GLuint texture_id; #endif bool needsMap; bool textureCreatedForBuffer; wl_buffer *directRenderBuffer; private: struct wl_buffer *surfaceBuffer; WaylandSurface::Type surfaceType; }; void surface_destroy(struct wl_client *client, struct wl_surface *surface) { wl_resource_destroy(&surface->resource, client, Compositor::currentTimeMsecs()); } void surface_attach(struct wl_client *client, struct wl_surface *surface, struct wl_buffer *buffer, int x, int y) { Q_UNUSED(client); Q_UNUSED(x); Q_UNUSED(y); wayland_cast<Surface *>(surface)->attach(buffer); } void surface_map_toplevel(struct wl_client *client, struct wl_surface *surface) { Q_UNUSED(client); printf("surface_map_toplevel: %p, %p\n", client, surface); wayland_cast<Surface *>(surface)->mapTopLevel(); } void surface_map_transient(struct wl_client *client, struct wl_surface *surface, struct wl_surface *parent, int x, int y, uint32_t flags) { Q_UNUSED(client); Q_UNUSED(surface); Q_UNUSED(parent); Q_UNUSED(x); Q_UNUSED(y); Q_UNUSED(flags); printf("surface_map_transient: %p, %p\n", client, surface); } void surface_map_fullscreen(struct wl_client *client, struct wl_surface *surface) { Q_UNUSED(client); Q_UNUSED(surface); printf("surface_map_fullscreen: %p, %p\n", client, surface); } void surface_damage(struct wl_client *client, struct wl_surface *surface, int32_t x, int32_t y, int32_t width, int32_t height) { Q_UNUSED(client); wayland_cast<Surface *>(surface)->damage(QRect(x, y, width, height)); } Surface::Surface(struct wl_client *client, Compositor *compositor) : d_ptr(new SurfacePrivate(client,compositor)) { base()->client = client; d_ptr->qtSurface = new WaylandSurface(this); } Surface::~Surface() { Q_D(Surface); d->compositor->surfaceDestroyed(this); #ifdef QT_COMPOSITOR_WAYLAND_GL glDeleteTextures(1,&d->texture_id); #endif delete d->qtSurface; } WaylandSurface::Type Surface::type() const { Q_D(const Surface); return d->type(); } bool Surface::isYInverted() const { Q_D(const Surface); if (d->type() == WaylandSurface::Texture) { if (textureId()) { return d->compositor->graphicsHWIntegration()->isYInverted(d->buffer()); } } else if (d->type() == WaylandSurface::Direct) { return d->compositor->graphicsHWIntegration()->isYInverted(d->buffer()); } //shm surfaces are not flipped (in our "world") return false; } void Surface::damage(const QRect &rect) { Q_D(Surface); #ifdef QT_COMPOSITOR_WAYLAND_GL if (d->type() == WaylandSurface::Direct) { //should the texture be deleted here, or should we explicitly delete it //when going into direct mode... if (d->textureCreatedForBuffer) { glDeleteTextures(1,&d->texture_id); d->textureCreatedForBuffer = false; } if (d->compositor->graphicsHWIntegration()->postBuffer(d->directRenderBuffer)) return; } #endif if (d->needsMap) { QRect rect(0,0,d->buffer()->width,d->buffer()->height); emit d->qtSurface->mapped(rect); d->needsMap = false; } d->compositor->markSurfaceAsDirty(this); if (d->type() == WaylandSurface::Shm) { static_cast<ShmBuffer *>(d->buffer()->user_data)->damage(); } emit d->qtSurface->damaged(rect); } QImage Surface::image() const { Q_D(const Surface); if (d->type() == WaylandSurface::Shm) { ShmBuffer *shmBuffer = static_cast<ShmBuffer *>(d->buffer()->user_data); return shmBuffer->image(); } return QImage(); } #ifdef QT_COMPOSITOR_WAYLAND_GL GLuint Surface::textureId() const { Q_D(const Surface); if (!d->texture_id && d->type() == WaylandSurface::Texture && !d->textureCreatedForBuffer) { glDeleteTextures(1,&d->texture_id); Surface *that = const_cast<Surface *>(this); GraphicsHardwareIntegration *hwIntegration = d->compositor->graphicsHWIntegration(); that->d_func()->texture_id = hwIntegration->createTextureFromBuffer(d->buffer()); that->d_func()->textureCreatedForBuffer = true; } return d->texture_id; } #endif // QT_COMPOSITOR_WAYLAND_GL void Surface::attach(struct wl_buffer *buffer) { Q_D(Surface); d->attach(buffer); } void Surface::mapTopLevel() { Q_D(Surface); if (!d->buffer()) d->needsMap = true; else emit d->qtSurface->mapped(QRect(0,0,d->buffer()->width, d->buffer()->height)); } WaylandSurface * Surface::handle() const { Q_D(const Surface); return d->qtSurface; } uint32_t toWaylandButton(Qt::MouseButton button) { switch (button) { case Qt::LeftButton: return BTN_LEFT; case Qt::RightButton: return BTN_RIGHT; default: return BTN_MIDDLE; } } void Surface::sendMousePressEvent(int x, int y, Qt::MouseButton button) { Q_D(Surface); sendMouseMoveEvent(x, y); if (d->client) { uint32_t time = d->compositor->currentTimeMsecs(); wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object, WL_INPUT_DEVICE_BUTTON, time, toWaylandButton(button), 1); } } void Surface::sendMouseReleaseEvent(int x, int y, Qt::MouseButton button) { Q_D(Surface); sendMouseMoveEvent(x, y); if (d->client) { uint32_t time = d->compositor->currentTimeMsecs(); wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object, WL_INPUT_DEVICE_BUTTON, time, toWaylandButton(button), 0); } } void Surface::sendMouseMoveEvent(int x, int y) { Q_D(Surface); if (d->client) { uint32_t time = d->compositor->currentTimeMsecs(); d->compositor->setPointerFocus(this, QPoint(x, y)); wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object, WL_INPUT_DEVICE_MOTION, time, x, y, x, y); } } void Surface::sendKeyPressEvent(uint code) { Q_D(Surface); if (d->compositor->defaultInputDevice()->keyboard_focus != NULL) { uint32_t time = d->compositor->currentTimeMsecs(); wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object, WL_INPUT_DEVICE_KEY, time, code - 8, 1); } } void Surface::sendKeyReleaseEvent(uint code) { Q_D(Surface); if (d->compositor->defaultInputDevice()->keyboard_focus != NULL) { uint32_t time = d->compositor->currentTimeMsecs(); wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object, WL_INPUT_DEVICE_KEY, time, code - 8, 0); } } void Surface::setInputFocus() { Q_D(Surface); d->compositor->setInputFocus(this); } } <commit_msg>Bug, we didn't support multiple attaches<commit_after>/**************************************************************************** ** ** This file is part of QtCompositor** ** ** Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** ** Contact: Nokia Corporation qt-info@nokia.com ** ** You may use this file under the terms of the BSD license as follows: ** ** 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 Nokia Corporation and its Subsidiary(-ies) 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 "wlsurface.h" #include "waylandsurface.h" #include "wlcompositor.h" #include "wlshmbuffer.h" #include <QtCore/QDebug> #include <wayland-server.h> #include <linux/input.h> #ifdef QT_COMPOSITOR_WAYLAND_GL #include "hardware_integration/graphicshardwareintegration.h" #include <QtGui/QPlatformGLContext> #endif namespace Wayland { class SurfacePrivate { public: SurfacePrivate(struct wl_client *client, Compositor *compositor) : client(client) , compositor(compositor) , needsMap(false) , textureCreatedForBuffer(false) , directRenderBuffer(0) , surfaceBuffer(0) , surfaceType(WaylandSurface::Invalid) { #ifdef QT_COMPOSITOR_WAYLAND_GL texture_id = 0; #endif } WaylandSurface::Type type() const { if (surfaceType == WaylandSurface::Invalid) { SurfacePrivate *that = const_cast<SurfacePrivate *>(this); if (qtSurface->handle() == compositor->directRenderSurface()) { that->surfaceType = WaylandSurface::Direct; } else if (surfaceBuffer && wl_buffer_is_shm(surfaceBuffer)) { that->surfaceType = WaylandSurface::Shm; } else if (surfaceBuffer){ that->surfaceType = WaylandSurface::Texture; } } return surfaceType; } void attach(struct wl_buffer *buffer) { this->surfaceBuffer = buffer; surfaceType = WaylandSurface::Invalid; textureCreatedForBuffer = false; } inline struct wl_buffer *buffer() const { return surfaceBuffer; } struct wl_client *client; Compositor *compositor; WaylandSurface *qtSurface; #ifdef QT_COMPOSITOR_WAYLAND_GL GLuint texture_id; #endif bool needsMap; bool textureCreatedForBuffer; wl_buffer *directRenderBuffer; private: struct wl_buffer *surfaceBuffer; WaylandSurface::Type surfaceType; }; void surface_destroy(struct wl_client *client, struct wl_surface *surface) { wl_resource_destroy(&surface->resource, client, Compositor::currentTimeMsecs()); } void surface_attach(struct wl_client *client, struct wl_surface *surface, struct wl_buffer *buffer, int x, int y) { Q_UNUSED(client); Q_UNUSED(x); Q_UNUSED(y); wayland_cast<Surface *>(surface)->attach(buffer); } void surface_map_toplevel(struct wl_client *client, struct wl_surface *surface) { Q_UNUSED(client); printf("surface_map_toplevel: %p, %p\n", client, surface); wayland_cast<Surface *>(surface)->mapTopLevel(); } void surface_map_transient(struct wl_client *client, struct wl_surface *surface, struct wl_surface *parent, int x, int y, uint32_t flags) { Q_UNUSED(client); Q_UNUSED(surface); Q_UNUSED(parent); Q_UNUSED(x); Q_UNUSED(y); Q_UNUSED(flags); printf("surface_map_transient: %p, %p\n", client, surface); } void surface_map_fullscreen(struct wl_client *client, struct wl_surface *surface) { Q_UNUSED(client); Q_UNUSED(surface); printf("surface_map_fullscreen: %p, %p\n", client, surface); } void surface_damage(struct wl_client *client, struct wl_surface *surface, int32_t x, int32_t y, int32_t width, int32_t height) { Q_UNUSED(client); wayland_cast<Surface *>(surface)->damage(QRect(x, y, width, height)); } Surface::Surface(struct wl_client *client, Compositor *compositor) : d_ptr(new SurfacePrivate(client,compositor)) { base()->client = client; d_ptr->qtSurface = new WaylandSurface(this); } Surface::~Surface() { Q_D(Surface); d->compositor->surfaceDestroyed(this); #ifdef QT_COMPOSITOR_WAYLAND_GL glDeleteTextures(1,&d->texture_id); #endif delete d->qtSurface; } WaylandSurface::Type Surface::type() const { Q_D(const Surface); return d->type(); } bool Surface::isYInverted() const { Q_D(const Surface); if (d->type() == WaylandSurface::Texture) { if (textureId()) { return d->compositor->graphicsHWIntegration()->isYInverted(d->buffer()); } } else if (d->type() == WaylandSurface::Direct) { return d->compositor->graphicsHWIntegration()->isYInverted(d->buffer()); } //shm surfaces are not flipped (in our "world") return false; } void Surface::damage(const QRect &rect) { Q_D(Surface); #ifdef QT_COMPOSITOR_WAYLAND_GL if (d->type() == WaylandSurface::Direct) { //should the texture be deleted here, or should we explicitly delete it //when going into direct mode... if (d->textureCreatedForBuffer) { glDeleteTextures(1,&d->texture_id); d->textureCreatedForBuffer = false; } if (d->compositor->graphicsHWIntegration()->postBuffer(d->directRenderBuffer)) return; } #endif if (d->needsMap) { QRect rect(0,0,d->buffer()->width,d->buffer()->height); emit d->qtSurface->mapped(rect); d->needsMap = false; } d->compositor->markSurfaceAsDirty(this); if (d->type() == WaylandSurface::Shm) { static_cast<ShmBuffer *>(d->buffer()->user_data)->damage(); } emit d->qtSurface->damaged(rect); } QImage Surface::image() const { Q_D(const Surface); if (d->type() == WaylandSurface::Shm) { ShmBuffer *shmBuffer = static_cast<ShmBuffer *>(d->buffer()->user_data); return shmBuffer->image(); } return QImage(); } #ifdef QT_COMPOSITOR_WAYLAND_GL GLuint Surface::textureId() const { Q_D(const Surface); if ( d->type() == WaylandSurface::Texture && !d->textureCreatedForBuffer) { glDeleteTextures(1,&d->texture_id); Surface *that = const_cast<Surface *>(this); GraphicsHardwareIntegration *hwIntegration = d->compositor->graphicsHWIntegration(); that->d_func()->texture_id = hwIntegration->createTextureFromBuffer(d->buffer()); that->d_func()->textureCreatedForBuffer = true; } return d->texture_id; } #endif // QT_COMPOSITOR_WAYLAND_GL void Surface::attach(struct wl_buffer *buffer) { Q_D(Surface); d->attach(buffer); } void Surface::mapTopLevel() { Q_D(Surface); if (!d->buffer()) d->needsMap = true; else emit d->qtSurface->mapped(QRect(0,0,d->buffer()->width, d->buffer()->height)); } WaylandSurface * Surface::handle() const { Q_D(const Surface); return d->qtSurface; } uint32_t toWaylandButton(Qt::MouseButton button) { switch (button) { case Qt::LeftButton: return BTN_LEFT; case Qt::RightButton: return BTN_RIGHT; default: return BTN_MIDDLE; } } void Surface::sendMousePressEvent(int x, int y, Qt::MouseButton button) { Q_D(Surface); sendMouseMoveEvent(x, y); if (d->client) { uint32_t time = d->compositor->currentTimeMsecs(); wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object, WL_INPUT_DEVICE_BUTTON, time, toWaylandButton(button), 1); } } void Surface::sendMouseReleaseEvent(int x, int y, Qt::MouseButton button) { Q_D(Surface); sendMouseMoveEvent(x, y); if (d->client) { uint32_t time = d->compositor->currentTimeMsecs(); wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object, WL_INPUT_DEVICE_BUTTON, time, toWaylandButton(button), 0); } } void Surface::sendMouseMoveEvent(int x, int y) { Q_D(Surface); if (d->client) { uint32_t time = d->compositor->currentTimeMsecs(); d->compositor->setPointerFocus(this, QPoint(x, y)); wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object, WL_INPUT_DEVICE_MOTION, time, x, y, x, y); } } void Surface::sendKeyPressEvent(uint code) { Q_D(Surface); if (d->compositor->defaultInputDevice()->keyboard_focus != NULL) { uint32_t time = d->compositor->currentTimeMsecs(); wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object, WL_INPUT_DEVICE_KEY, time, code - 8, 1); } } void Surface::sendKeyReleaseEvent(uint code) { Q_D(Surface); if (d->compositor->defaultInputDevice()->keyboard_focus != NULL) { uint32_t time = d->compositor->currentTimeMsecs(); wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object, WL_INPUT_DEVICE_KEY, time, code - 8, 0); } } void Surface::setInputFocus() { Q_D(Surface); d->compositor->setInputFocus(this); } } <|endoftext|>
<commit_before>/* * DebuggerView.cpp * * This file is part of the XShaderCompiler project (Copyright (c) 2014-2016 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "DebuggerView.h" #include <sstream> #include <memory> #include <vector> #include <fstream> namespace Xsc { static long DebuggerViewStyle() { return (wxSYSTEM_MENU | wxCAPTION | wxCLIP_CHILDREN | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxRESIZE_BORDER | wxCLOSE_BOX); } DebuggerView::DebuggerView(const wxPoint& pos, const wxSize& size) : wxFrame{ nullptr, wxID_ANY, "Xsc Debugger", pos, size, DebuggerViewStyle() } { #ifdef _WIN32 SetIcon(wxICON(APP_ICON)); #endif CreateLayout(); Centre(); Bind(wxEVT_CLOSE_WINDOW, &DebuggerView::OnClose, this); } static const std::string settingsFilename("XscDebuggerSettings"); static const std::string codeFilename("XscDebuggerCode"); void DebuggerView::SaveSettings() { std::ofstream settingsFile(settingsFilename); if (settingsFile.good()) settingsFile << propGrid_->SaveEditableState().ToStdString() << std::endl; std::ofstream codeFile(codeFilename); if (codeFile.good()) codeFile << inputSourceView_->GetText(); } void DebuggerView::LoadSettings() { std::ifstream settingsFile(settingsFilename); if (settingsFile.good()) { std::string state; std::getline(settingsFile, state); propGrid_->RestoreEditableState(state); } std::ifstream codeFile(codeFilename); if (codeFile.good()) { inputSourceView_->SetText( std::string( ( std::istreambuf_iterator<char>(codeFile) ), ( std::istreambuf_iterator<char>() ) ) ); } } /* * ======= Private: ======= */ void DebuggerView::CreateLayout() { mainSplitter_ = new wxSplitterWindow(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_LIVE_UPDATE); CreateLayoutPropertyGrid(); CreateLayoutSubSplitter(); mainSplitter_->SplitVertically(propGrid_, subSplitter_, 300); } void DebuggerView::CreateLayoutPropertyGrid() { propGrid_ = new wxPropertyGrid(mainSplitter_, wxID_ANY, wxDefaultPosition, wxSize(200, 600), wxPG_SPLITTER_AUTO_CENTER); CreateLayoutPropertyGridShaderInput(*propGrid_); CreateLayoutPropertyGridShaderOutput(*propGrid_); CreateLayoutPropertyGridOptions(*propGrid_); CreateLayoutPropertyGridFormatting(*propGrid_); propGrid_->Bind(wxEVT_PG_CHANGED, &DebuggerView::OnPropertyGridChange, this); } void DebuggerView::CreateLayoutPropertyGridShaderInput(wxPropertyGrid& pg) { pg.Append(new wxPropertyCategory("Shader Input")); wxPGChoices choices0; { choices0.Add("HLSL3"); choices0.Add("HLSL4"); choices0.Add("HLSL5"); } pg.Append(new wxEnumProperty("Shader Version", "inputVersion", choices0, 2))->Enable(false); wxPGChoices choices1; { choices1.Add("Vertex Shader"); choices1.Add("Tessellation-Control Shader"); choices1.Add("Tessellation-Evaluation Shader"); choices1.Add("Geometry Shader"); choices1.Add("Fragment Shader"); choices1.Add("Compute Shader"); } pg.Append(new wxEnumProperty("Shader Target", "target", choices1)); pg.Append(new wxStringProperty("Entry Point", "entry", "")); pg.Append(new wxStringProperty("Secondary Entry Point", "secondaryEntry", "")); } void DebuggerView::CreateLayoutPropertyGridShaderOutput(wxPropertyGrid& pg) { pg.Append(new wxPropertyCategory("Shader Output")); wxPGChoices choices0; { choices0.Add("GLSL (Auto-Detect)"); choices0.Add("GLSL110"); choices0.Add("GLSL120"); choices0.Add("GLSL130"); choices0.Add("GLSL140"); choices0.Add("GLSL150"); choices0.Add("GLSL330"); choices0.Add("GLSL400"); choices0.Add("GLSL410"); choices0.Add("GLSL420"); choices0.Add("GLSL430"); choices0.Add("GLSL440"); choices0.Add("GLSL450"); choices0.Add("ESSL (Auto-Detect)"); choices0.Add("ESSL100"); choices0.Add("ESSL300"); choices0.Add("ESSL310"); choices0.Add("ESSL320"); choices0.Add("VKSL (Auto-Detect)"); choices0.Add("VKSL450"); } pg.Append(new wxEnumProperty("Shader Version", "outputVersion", choices0))->Enable(false); pg.Append(new wxStringProperty("Name Mangling Prefix", "prefix", "xsc_")); } void DebuggerView::CreateLayoutPropertyGridOptions(wxPropertyGrid& pg) { pg.Append(new wxPropertyCategory("Options")); pg.Append(new wxBoolProperty("Allow Extensions", "extensions")); pg.Append(new wxBoolProperty("Explicit Binding", "binding")); pg.Append(new wxBoolProperty("Optimize", "optimize")); pg.Append(new wxBoolProperty("Prefer Wrappers", "wrappers")); pg.Append(new wxBoolProperty("Preprocess Only", "preprocess")); pg.Append(new wxBoolProperty("Preserve Comments", "comments")); } void DebuggerView::CreateLayoutPropertyGridFormatting(wxPropertyGrid& pg) { pg.Append(new wxPropertyCategory("Formatting")); pg.Append(new wxStringProperty("Indentation", "indent", " ")); pg.Append(new wxBoolProperty("Blanks", "blanks", true)); pg.Append(new wxBoolProperty("Line Marks", "lineMarks")); pg.Append(new wxBoolProperty("Compact Wrappers", "compactWrappers", true)); pg.Append(new wxBoolProperty("Always Braced Scopes", "alwaysBracedScopes")); pg.Append(new wxBoolProperty("New-Line Open Scope", "newLineOpenScope", true)); pg.Append(new wxBoolProperty("Line Separation", "lineSeparation", true)); } void DebuggerView::CreateLayoutSubSplitter() { subSplitter_ = new wxSplitterWindow(mainSplitter_, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_LIVE_UPDATE); CreateLayoutReportView(); CreateLayoutSourceSplitter(); subSplitter_->SplitHorizontally(sourceSplitter_, reportView_, 600); } void DebuggerView::CreateLayoutReportView() { reportView_ = new ReportView(subSplitter_, wxDefaultPosition, wxSize(400, 50)); } void DebuggerView::CreateLayoutSourceSplitter() { sourceSplitter_ = new wxSplitterWindow(subSplitter_, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_LIVE_UPDATE); CreateLayoutInputSourceView(); CreateLayoutOutputSourceView(); sourceSplitter_->SplitVertically(inputSourceView_, outputSourceView_); } void DebuggerView::CreateLayoutInputSourceView() { inputSourceView_ = new SourceView(sourceSplitter_, wxDefaultPosition, wxSize(200, 600)); inputSourceView_->SetLanguage(SourceViewLanguage::HLSL); inputSourceView_->SetCharEnterCallback(std::bind(&DebuggerView::OnInputSourceCharEnter, this, std::placeholders::_1)); } void DebuggerView::CreateLayoutOutputSourceView() { outputSourceView_ = new SourceView(sourceSplitter_, wxDefaultPosition, wxSize(200, 600)); outputSourceView_->SetLanguage(SourceViewLanguage::GLSL); //outputSourceView_->SetReadOnly(true); } void DebuggerView::OnPropertyGridChange(wxPropertyGridEvent& event) { auto p = event.GetProperty(); auto name = p->GetName(); auto ValueStr = [p]() { return p->GetValueAsString().ToStdString(); }; auto ValueInt = [p]() { return p->GetValue().GetInteger(); }; auto ValueBool = [p]() { return p->GetValue().GetBool(); }; if (name == "entry") shaderInput_.entryPoint = ValueStr(); else if (name == "secondaryEntry") shaderInput_.secondaryEntryPoint = ValueStr(); else if (name == "target") shaderInput_.shaderTarget = static_cast<ShaderTarget>(static_cast<long>(ShaderTarget::VertexShader) + ValueInt()); else if (name == "prefix") shaderOutput_.nameManglingPrefix = ValueStr(); else if (name == "indent") shaderOutput_.formatting.indent = ValueStr(); else if (name == "extensions") shaderOutput_.options.allowExtensions = ValueBool(); else if (name == "binding") shaderOutput_.options.explicitBinding = ValueBool(); else if (name == "optimize") shaderOutput_.options.optimize = ValueBool(); else if (name == "wrappers") shaderOutput_.options.preferWrappers = ValueBool(); else if (name == "preprocess") shaderOutput_.options.preprocessOnly = ValueBool(); else if (name == "comments") shaderOutput_.options.preserveComments = ValueBool(); else if (name == "blanks") shaderOutput_.formatting.blanks = ValueBool(); else if (name == "lineMarks") shaderOutput_.formatting.lineMarks = ValueBool(); else if (name == "compactWrappers") shaderOutput_.formatting.compactWrappers = ValueBool(); else if (name == "alwaysBracedScopes") shaderOutput_.formatting.alwaysBracedScopes = ValueBool(); else if (name == "newLineOpenScope") shaderOutput_.formatting.newLineOpenScope = ValueBool(); else if (name == "lineSeparation") shaderOutput_.formatting.lineSeparation = ValueBool(); TranslateInputToOutput(); } void DebuggerView::OnInputSourceCharEnter(char chr) { TranslateInputToOutput(); } void DebuggerView::OnClose(wxCloseEvent& event) { SaveSettings(); event.Skip(); } class DebuggerLog : public Log { public: DebuggerLog(ReportView* reportView) : reportView_{ reportView } { } void SumitReport(const Report& report) override { reportView_->AddReport(report); } private: ReportView* reportView_ = nullptr; }; void DebuggerView::TranslateInputToOutput() { /* Initialize input source */ auto inputSource = std::make_shared<std::stringstream>(); *inputSource << inputSourceView_->GetText().ToStdString(); shaderInput_.sourceCode = inputSource; /* Initialize output source */ std::stringstream outputSource; shaderOutput_.sourceCode = (&outputSource); /* Compile shader */ reportView_->Clear(); DebuggerLog log(reportView_); if (Xsc::CompileShader(shaderInput_, shaderOutput_, &log)) { /* Show output */ outputSourceView_->SetTextAndRefresh(outputSource.str()); } } } // /namespace Xsc // ================================================================================ <commit_msg>Added "Unroll Array Initializers" property to DebuggerView.<commit_after>/* * DebuggerView.cpp * * This file is part of the XShaderCompiler project (Copyright (c) 2014-2016 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "DebuggerView.h" #include <sstream> #include <memory> #include <vector> #include <fstream> namespace Xsc { static long DebuggerViewStyle() { return (wxSYSTEM_MENU | wxCAPTION | wxCLIP_CHILDREN | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxRESIZE_BORDER | wxCLOSE_BOX); } DebuggerView::DebuggerView(const wxPoint& pos, const wxSize& size) : wxFrame{ nullptr, wxID_ANY, "Xsc Debugger", pos, size, DebuggerViewStyle() } { #ifdef _WIN32 SetIcon(wxICON(APP_ICON)); #endif CreateLayout(); Centre(); Bind(wxEVT_CLOSE_WINDOW, &DebuggerView::OnClose, this); } static const std::string settingsFilename("XscDebuggerSettings"); static const std::string codeFilename("XscDebuggerCode"); void DebuggerView::SaveSettings() { std::ofstream settingsFile(settingsFilename); if (settingsFile.good()) settingsFile << propGrid_->SaveEditableState().ToStdString() << std::endl; std::ofstream codeFile(codeFilename); if (codeFile.good()) codeFile << inputSourceView_->GetText(); } void DebuggerView::LoadSettings() { std::ifstream settingsFile(settingsFilename); if (settingsFile.good()) { std::string state; std::getline(settingsFile, state); propGrid_->RestoreEditableState(state); } std::ifstream codeFile(codeFilename); if (codeFile.good()) { inputSourceView_->SetText( std::string( ( std::istreambuf_iterator<char>(codeFile) ), ( std::istreambuf_iterator<char>() ) ) ); } } /* * ======= Private: ======= */ void DebuggerView::CreateLayout() { mainSplitter_ = new wxSplitterWindow(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_LIVE_UPDATE); CreateLayoutPropertyGrid(); CreateLayoutSubSplitter(); mainSplitter_->SplitVertically(propGrid_, subSplitter_, 300); } void DebuggerView::CreateLayoutPropertyGrid() { propGrid_ = new wxPropertyGrid(mainSplitter_, wxID_ANY, wxDefaultPosition, wxSize(200, 600), wxPG_SPLITTER_AUTO_CENTER); CreateLayoutPropertyGridShaderInput(*propGrid_); CreateLayoutPropertyGridShaderOutput(*propGrid_); CreateLayoutPropertyGridOptions(*propGrid_); CreateLayoutPropertyGridFormatting(*propGrid_); propGrid_->Bind(wxEVT_PG_CHANGED, &DebuggerView::OnPropertyGridChange, this); } void DebuggerView::CreateLayoutPropertyGridShaderInput(wxPropertyGrid& pg) { pg.Append(new wxPropertyCategory("Shader Input")); wxPGChoices choices0; { choices0.Add("HLSL3"); choices0.Add("HLSL4"); choices0.Add("HLSL5"); } pg.Append(new wxEnumProperty("Shader Version", "inputVersion", choices0, 2))->Enable(false); wxPGChoices choices1; { choices1.Add("Vertex Shader"); choices1.Add("Tessellation-Control Shader"); choices1.Add("Tessellation-Evaluation Shader"); choices1.Add("Geometry Shader"); choices1.Add("Fragment Shader"); choices1.Add("Compute Shader"); } pg.Append(new wxEnumProperty("Shader Target", "target", choices1)); pg.Append(new wxStringProperty("Entry Point", "entry", "")); pg.Append(new wxStringProperty("Secondary Entry Point", "secondaryEntry", "")); } void DebuggerView::CreateLayoutPropertyGridShaderOutput(wxPropertyGrid& pg) { pg.Append(new wxPropertyCategory("Shader Output")); wxPGChoices choices0; { choices0.Add("GLSL (Auto-Detect)"); choices0.Add("GLSL110"); choices0.Add("GLSL120"); choices0.Add("GLSL130"); choices0.Add("GLSL140"); choices0.Add("GLSL150"); choices0.Add("GLSL330"); choices0.Add("GLSL400"); choices0.Add("GLSL410"); choices0.Add("GLSL420"); choices0.Add("GLSL430"); choices0.Add("GLSL440"); choices0.Add("GLSL450"); choices0.Add("ESSL (Auto-Detect)"); choices0.Add("ESSL100"); choices0.Add("ESSL300"); choices0.Add("ESSL310"); choices0.Add("ESSL320"); choices0.Add("VKSL (Auto-Detect)"); choices0.Add("VKSL450"); } pg.Append(new wxEnumProperty("Shader Version", "outputVersion", choices0))->Enable(false); pg.Append(new wxStringProperty("Name Mangling Prefix", "prefix", "xsc_")); } void DebuggerView::CreateLayoutPropertyGridOptions(wxPropertyGrid& pg) { pg.Append(new wxPropertyCategory("Options")); pg.Append(new wxBoolProperty("Allow Extensions", "extensions")); pg.Append(new wxBoolProperty("Explicit Binding", "binding")); pg.Append(new wxBoolProperty("Optimize", "optimize")); pg.Append(new wxBoolProperty("Prefer Wrappers", "wrappers")); pg.Append(new wxBoolProperty("Preprocess Only", "preprocess")); pg.Append(new wxBoolProperty("Preserve Comments", "comments")); pg.Append(new wxBoolProperty("Unroll Array Initializers", "unrollInitializers")); } void DebuggerView::CreateLayoutPropertyGridFormatting(wxPropertyGrid& pg) { pg.Append(new wxPropertyCategory("Formatting")); pg.Append(new wxStringProperty("Indentation", "indent", " ")); pg.Append(new wxBoolProperty("Blanks", "blanks", true)); pg.Append(new wxBoolProperty("Line Marks", "lineMarks")); pg.Append(new wxBoolProperty("Compact Wrappers", "compactWrappers", true)); pg.Append(new wxBoolProperty("Always Braced Scopes", "alwaysBracedScopes")); pg.Append(new wxBoolProperty("New-Line Open Scope", "newLineOpenScope", true)); pg.Append(new wxBoolProperty("Line Separation", "lineSeparation", true)); } void DebuggerView::CreateLayoutSubSplitter() { subSplitter_ = new wxSplitterWindow(mainSplitter_, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_LIVE_UPDATE); CreateLayoutReportView(); CreateLayoutSourceSplitter(); subSplitter_->SplitHorizontally(sourceSplitter_, reportView_, 600); } void DebuggerView::CreateLayoutReportView() { reportView_ = new ReportView(subSplitter_, wxDefaultPosition, wxSize(400, 50)); } void DebuggerView::CreateLayoutSourceSplitter() { sourceSplitter_ = new wxSplitterWindow(subSplitter_, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_LIVE_UPDATE); CreateLayoutInputSourceView(); CreateLayoutOutputSourceView(); sourceSplitter_->SplitVertically(inputSourceView_, outputSourceView_); } void DebuggerView::CreateLayoutInputSourceView() { inputSourceView_ = new SourceView(sourceSplitter_, wxDefaultPosition, wxSize(200, 600)); inputSourceView_->SetLanguage(SourceViewLanguage::HLSL); inputSourceView_->SetCharEnterCallback(std::bind(&DebuggerView::OnInputSourceCharEnter, this, std::placeholders::_1)); } void DebuggerView::CreateLayoutOutputSourceView() { outputSourceView_ = new SourceView(sourceSplitter_, wxDefaultPosition, wxSize(200, 600)); outputSourceView_->SetLanguage(SourceViewLanguage::GLSL); //outputSourceView_->SetReadOnly(true); } void DebuggerView::OnPropertyGridChange(wxPropertyGridEvent& event) { auto p = event.GetProperty(); auto name = p->GetName(); auto ValueStr = [p]() { return p->GetValueAsString().ToStdString(); }; auto ValueInt = [p]() { return p->GetValue().GetInteger(); }; auto ValueBool = [p]() { return p->GetValue().GetBool(); }; if (name == "entry") shaderInput_.entryPoint = ValueStr(); else if (name == "secondaryEntry") shaderInput_.secondaryEntryPoint = ValueStr(); else if (name == "target") shaderInput_.shaderTarget = static_cast<ShaderTarget>(static_cast<long>(ShaderTarget::VertexShader) + ValueInt()); else if (name == "prefix") shaderOutput_.nameManglingPrefix = ValueStr(); else if (name == "indent") shaderOutput_.formatting.indent = ValueStr(); else if (name == "extensions") shaderOutput_.options.allowExtensions = ValueBool(); else if (name == "binding") shaderOutput_.options.explicitBinding = ValueBool(); else if (name == "optimize") shaderOutput_.options.optimize = ValueBool(); else if (name == "wrappers") shaderOutput_.options.preferWrappers = ValueBool(); else if (name == "preprocess") shaderOutput_.options.preprocessOnly = ValueBool(); else if (name == "comments") shaderOutput_.options.preserveComments = ValueBool(); else if (name == "unrollInitializers") shaderOutput_.options.unrollArrayInitializers = ValueBool(); else if (name == "blanks") shaderOutput_.formatting.blanks = ValueBool(); else if (name == "lineMarks") shaderOutput_.formatting.lineMarks = ValueBool(); else if (name == "compactWrappers") shaderOutput_.formatting.compactWrappers = ValueBool(); else if (name == "alwaysBracedScopes") shaderOutput_.formatting.alwaysBracedScopes = ValueBool(); else if (name == "newLineOpenScope") shaderOutput_.formatting.newLineOpenScope = ValueBool(); else if (name == "lineSeparation") shaderOutput_.formatting.lineSeparation = ValueBool(); TranslateInputToOutput(); } void DebuggerView::OnInputSourceCharEnter(char chr) { TranslateInputToOutput(); } void DebuggerView::OnClose(wxCloseEvent& event) { SaveSettings(); event.Skip(); } class DebuggerLog : public Log { public: DebuggerLog(ReportView* reportView) : reportView_{ reportView } { } void SumitReport(const Report& report) override { reportView_->AddReport(report); } private: ReportView* reportView_ = nullptr; }; void DebuggerView::TranslateInputToOutput() { /* Initialize input source */ auto inputSource = std::make_shared<std::stringstream>(); *inputSource << inputSourceView_->GetText().ToStdString(); shaderInput_.sourceCode = inputSource; /* Initialize output source */ std::stringstream outputSource; shaderOutput_.sourceCode = (&outputSource); /* Compile shader */ reportView_->Clear(); DebuggerLog log(reportView_); if (Xsc::CompileShader(shaderInput_, shaderOutput_, &log)) { /* Show output */ outputSourceView_->SetTextAndRefresh(outputSource.str()); } } } // /namespace Xsc // ================================================================================ <|endoftext|>
<commit_before>/* Copyright 2017 Istio 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 "src/envoy/http/mixer/filter.h" #include "common/common/base64.h" #include "common/protobuf/utility.h" #include "include/istio/utils/status.h" #include "src/envoy/http/mixer/check_data.h" #include "src/envoy/http/mixer/report_data.h" #include "src/envoy/utils/authn.h" #include "src/envoy/utils/header_update.h" using ::google::protobuf::util::Status; using ::istio::mixer::v1::config::client::ServiceConfig; using ::istio::mixerclient::CheckResponseInfo; namespace Envoy { namespace Http { namespace Mixer { namespace { // Per route opaque data for "destination.service". const std::string kPerRouteDestinationService("destination.service"); // Per route opaque data name "mixer" is base64(JSON(ServiceConfig)) const std::string kPerRouteMixer("mixer"); // Per route opaque data name "mixer_sha" is SHA(JSON(ServiceConfig)) const std::string kPerRouteMixerSha("mixer_sha"); // Read a string value from a string map. bool ReadStringMap(const std::multimap<std::string, std::string>& string_map, const std::string& name, std::string* value) { auto it = string_map.find(name); if (it != string_map.end()) { *value = it->second; return true; } return false; } } // namespace Filter::Filter(Control& control) : control_(control), state_(NotStarted), initiating_call_(false), headers_(nullptr) { ENVOY_LOG(debug, "Called Mixer::Filter : {}", __func__); } void Filter::ReadPerRouteConfig( const Router::RouteEntry* entry, ::istio::control::http::Controller::PerRouteConfig* config) { if (entry == nullptr) { return; } // Check v2 per-route config. auto route_cfg = entry->perFilterConfigTyped<PerRouteServiceConfig>("mixer"); if (route_cfg) { if (!control_.controller()->LookupServiceConfig(route_cfg->hash)) { control_.controller()->AddServiceConfig(route_cfg->hash, route_cfg->config); } config->service_config_id = route_cfg->hash; return; } const auto& string_map = entry->opaqueConfig(); ReadStringMap(string_map, kPerRouteDestinationService, &config->destination_service); if (!ReadStringMap(string_map, kPerRouteMixerSha, &config->service_config_id) || config->service_config_id.empty()) { return; } if (control_.controller()->LookupServiceConfig(config->service_config_id)) { return; } std::string config_base64; if (!ReadStringMap(string_map, kPerRouteMixer, &config_base64)) { ENVOY_LOG(warn, "Service {} missing [mixer] per-route attribute", config->destination_service); return; } std::string config_json = Base64::decode(config_base64); if (config_json.empty()) { ENVOY_LOG(warn, "Service {} invalid base64 config data", config->destination_service); return; } ServiceConfig config_pb; auto status = Utils::ParseJsonMessage(config_json, &config_pb); if (!status.ok()) { ENVOY_LOG(warn, "Service {} failed to convert JSON config to protobuf, error: {}", config->destination_service, status.ToString()); return; } control_.controller()->AddServiceConfig(config->service_config_id, config_pb); ENVOY_LOG(info, "Service {}, config_id {}, config: {}", config->destination_service, config->service_config_id, MessageUtil::getJsonStringFromMessage(config_pb, true)); } FilterHeadersStatus Filter::decodeHeaders(HeaderMap& headers, bool) { ENVOY_LOG(debug, "Called Mixer::Filter : {}", __func__); request_total_size_ += headers.byteSize(); ::istio::control::http::Controller::PerRouteConfig config; auto route = decoder_callbacks_->route(); if (route) { ReadPerRouteConfig(route->routeEntry(), &config); } handler_ = control_.controller()->CreateRequestHandler(config); state_ = Calling; initiating_call_ = true; CheckData check_data(headers, decoder_callbacks_->requestInfo().dynamicMetadata(), decoder_callbacks_->connection()); Utils::HeaderUpdate header_update(&headers); headers_ = &headers; cancel_check_ = handler_->Check( &check_data, &header_update, control_.GetCheckTransport(decoder_callbacks_->activeSpan()), [this](const CheckResponseInfo& info) { completeCheck(info); }); initiating_call_ = false; if (state_ == Complete) { return FilterHeadersStatus::Continue; } ENVOY_LOG(debug, "Called Mixer::Filter : {} Stop", __func__); return FilterHeadersStatus::StopIteration; } FilterDataStatus Filter::decodeData(Buffer::Instance& data, bool end_stream) { ENVOY_LOG(debug, "Called Mixer::Filter : {} ({}, {})", __func__, data.length(), end_stream); request_total_size_ += data.length(); if (state_ == Calling) { return FilterDataStatus::StopIterationAndWatermark; } return FilterDataStatus::Continue; } FilterTrailersStatus Filter::decodeTrailers(HeaderMap& trailers) { ENVOY_LOG(debug, "Called Mixer::Filter : {}", __func__); request_total_size_ += trailers.byteSize(); if (state_ == Calling) { return FilterTrailersStatus::StopIteration; } return FilterTrailersStatus::Continue; } void Filter::UpdateHeaders( HeaderMap& headers, const ::google::protobuf::RepeatedPtrField< ::istio::mixer::v1::HeaderOperation>& operations) { for (auto const iter : operations) { switch (iter.operation()) { case ::istio::mixer::v1::HeaderOperation_Operation_REPLACE: headers.remove(LowerCaseString(iter.name())); headers.addCopy(LowerCaseString(iter.name()), iter.value()); break; case ::istio::mixer::v1::HeaderOperation_Operation_REMOVE: headers.remove(LowerCaseString(iter.name())); break; case ::istio::mixer::v1::HeaderOperation_Operation_APPEND: headers.addCopy(LowerCaseString(iter.name()), iter.value()); break; default: PANIC("unreachable header operation"); } } } FilterHeadersStatus Filter::encodeHeaders(HeaderMap& headers, bool) { ENVOY_LOG(debug, "Called Mixer::Filter : {} {}", __func__, state_); // Init state is possible if a filter prior to mixerfilter interrupts the // filter chain ASSERT(state_ == NotStarted || state_ == Complete || state_ == Responded); if (state_ == Complete) { // handle response header operations UpdateHeaders(headers, route_directive_.response_header_operations()); } return FilterHeadersStatus::Continue; } void Filter::setDecoderFilterCallbacks( StreamDecoderFilterCallbacks& callbacks) { ENVOY_LOG(debug, "Called Mixer::Filter : {}", __func__); decoder_callbacks_ = &callbacks; } void Filter::completeCheck(const CheckResponseInfo& info) { auto status = info.response_status; ENVOY_LOG(debug, "Called Mixer::Filter : check complete {}", status.ToString()); // This stream has been reset, abort the callback. if (state_ == Responded) { return; } if (!status.ok()) { state_ = Responded; int status_code = ::istio::utils::StatusHttpCode(status.error_code()); decoder_callbacks_->sendLocalReply(Code(status_code), status.ToString(), nullptr); return; } state_ = Complete; route_directive_ = info.route_directive; // handle direct response from the route directive if (status.ok() && route_directive_.direct_response_code() != 0) { ENVOY_LOG(debug, "Mixer::Filter direct response"); state_ = Responded; decoder_callbacks_->sendLocalReply( Code(route_directive_.direct_response_code()), route_directive_.direct_response_body(), [this](HeaderMap& headers) { UpdateHeaders(headers, route_directive_.response_header_operations()); }); return; } // handle request header operations if (nullptr != headers_) { UpdateHeaders(*headers_, route_directive_.request_header_operations()); headers_ = nullptr; } if (!initiating_call_) { decoder_callbacks_->continueDecoding(); } } void Filter::onDestroy() { ENVOY_LOG(debug, "Called Mixer::Filter : {} state: {}", __func__, state_); if (state_ != Calling) { cancel_check_ = nullptr; } state_ = Responded; if (cancel_check_) { ENVOY_LOG(debug, "Cancelling check call"); cancel_check_(); cancel_check_ = nullptr; } } void Filter::log(const HeaderMap* request_headers, const HeaderMap* response_headers, const HeaderMap* response_trailers, const RequestInfo::RequestInfo& request_info) { ENVOY_LOG(debug, "Called Mixer::Filter : {}", __func__); if (!handler_) { if (request_headers == nullptr) { return; } // Here Request is rejected by other filters, Mixer filter is not called. ::istio::control::http::Controller::PerRouteConfig config; ReadPerRouteConfig(request_info.routeEntry(), &config); handler_ = control_.controller()->CreateRequestHandler(config); CheckData check_data(*request_headers, request_info.dynamicMetadata(), nullptr); handler_->ExtractRequestAttributes(&check_data); } // response trailer header is not counted to response total size. ReportData report_data(response_headers, response_trailers, request_info, request_total_size_); handler_->Report(&report_data); } } // namespace Mixer } // namespace Http } // namespace Envoy <commit_msg>format it (#1923)<commit_after>/* Copyright 2017 Istio 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 "src/envoy/http/mixer/filter.h" #include "common/common/base64.h" #include "common/protobuf/utility.h" #include "include/istio/utils/status.h" #include "src/envoy/http/mixer/check_data.h" #include "src/envoy/http/mixer/report_data.h" #include "src/envoy/utils/authn.h" #include "src/envoy/utils/header_update.h" using ::google::protobuf::util::Status; using ::istio::mixer::v1::config::client::ServiceConfig; using ::istio::mixerclient::CheckResponseInfo; namespace Envoy { namespace Http { namespace Mixer { namespace { // Per route opaque data for "destination.service". const std::string kPerRouteDestinationService("destination.service"); // Per route opaque data name "mixer" is base64(JSON(ServiceConfig)) const std::string kPerRouteMixer("mixer"); // Per route opaque data name "mixer_sha" is SHA(JSON(ServiceConfig)) const std::string kPerRouteMixerSha("mixer_sha"); // Read a string value from a string map. bool ReadStringMap(const std::multimap<std::string, std::string>& string_map, const std::string& name, std::string* value) { auto it = string_map.find(name); if (it != string_map.end()) { *value = it->second; return true; } return false; } } // namespace Filter::Filter(Control& control) : control_(control), state_(NotStarted), initiating_call_(false), headers_(nullptr) { ENVOY_LOG(debug, "Called Mixer::Filter : {}", __func__); } void Filter::ReadPerRouteConfig( const Router::RouteEntry* entry, ::istio::control::http::Controller::PerRouteConfig* config) { if (entry == nullptr) { return; } // Check v2 per-route config. auto route_cfg = entry->perFilterConfigTyped<PerRouteServiceConfig>("mixer"); if (route_cfg) { if (!control_.controller()->LookupServiceConfig(route_cfg->hash)) { control_.controller()->AddServiceConfig(route_cfg->hash, route_cfg->config); } config->service_config_id = route_cfg->hash; return; } const auto& string_map = entry->opaqueConfig(); ReadStringMap(string_map, kPerRouteDestinationService, &config->destination_service); if (!ReadStringMap(string_map, kPerRouteMixerSha, &config->service_config_id) || config->service_config_id.empty()) { return; } if (control_.controller()->LookupServiceConfig(config->service_config_id)) { return; } std::string config_base64; if (!ReadStringMap(string_map, kPerRouteMixer, &config_base64)) { ENVOY_LOG(warn, "Service {} missing [mixer] per-route attribute", config->destination_service); return; } std::string config_json = Base64::decode(config_base64); if (config_json.empty()) { ENVOY_LOG(warn, "Service {} invalid base64 config data", config->destination_service); return; } ServiceConfig config_pb; auto status = Utils::ParseJsonMessage(config_json, &config_pb); if (!status.ok()) { ENVOY_LOG(warn, "Service {} failed to convert JSON config to protobuf, error: {}", config->destination_service, status.ToString()); return; } control_.controller()->AddServiceConfig(config->service_config_id, config_pb); ENVOY_LOG(info, "Service {}, config_id {}, config: {}", config->destination_service, config->service_config_id, MessageUtil::getJsonStringFromMessage(config_pb, true)); } FilterHeadersStatus Filter::decodeHeaders(HeaderMap& headers, bool) { ENVOY_LOG(debug, "Called Mixer::Filter : {}", __func__); request_total_size_ += headers.byteSize(); ::istio::control::http::Controller::PerRouteConfig config; auto route = decoder_callbacks_->route(); if (route) { ReadPerRouteConfig(route->routeEntry(), &config); } handler_ = control_.controller()->CreateRequestHandler(config); state_ = Calling; initiating_call_ = true; CheckData check_data(headers, decoder_callbacks_->requestInfo().dynamicMetadata(), decoder_callbacks_->connection()); Utils::HeaderUpdate header_update(&headers); headers_ = &headers; cancel_check_ = handler_->Check( &check_data, &header_update, control_.GetCheckTransport(decoder_callbacks_->activeSpan()), [this](const CheckResponseInfo& info) { completeCheck(info); }); initiating_call_ = false; if (state_ == Complete) { return FilterHeadersStatus::Continue; } ENVOY_LOG(debug, "Called Mixer::Filter : {} Stop", __func__); return FilterHeadersStatus::StopIteration; } FilterDataStatus Filter::decodeData(Buffer::Instance& data, bool end_stream) { ENVOY_LOG(debug, "Called Mixer::Filter : {} ({}, {})", __func__, data.length(), end_stream); request_total_size_ += data.length(); if (state_ == Calling) { return FilterDataStatus::StopIterationAndWatermark; } return FilterDataStatus::Continue; } FilterTrailersStatus Filter::decodeTrailers(HeaderMap& trailers) { ENVOY_LOG(debug, "Called Mixer::Filter : {}", __func__); request_total_size_ += trailers.byteSize(); if (state_ == Calling) { return FilterTrailersStatus::StopIteration; } return FilterTrailersStatus::Continue; } void Filter::UpdateHeaders( HeaderMap& headers, const ::google::protobuf::RepeatedPtrField< ::istio::mixer::v1::HeaderOperation>& operations) { for (auto const iter : operations) { switch (iter.operation()) { case ::istio::mixer::v1::HeaderOperation_Operation_REPLACE: headers.remove(LowerCaseString(iter.name())); headers.addCopy(LowerCaseString(iter.name()), iter.value()); break; case ::istio::mixer::v1::HeaderOperation_Operation_REMOVE: headers.remove(LowerCaseString(iter.name())); break; case ::istio::mixer::v1::HeaderOperation_Operation_APPEND: headers.addCopy(LowerCaseString(iter.name()), iter.value()); break; default: PANIC("unreachable header operation"); } } } FilterHeadersStatus Filter::encodeHeaders(HeaderMap& headers, bool) { ENVOY_LOG(debug, "Called Mixer::Filter : {} {}", __func__, state_); // Init state is possible if a filter prior to mixerfilter interrupts the // filter chain ASSERT(state_ == NotStarted || state_ == Complete || state_ == Responded); if (state_ == Complete) { // handle response header operations UpdateHeaders(headers, route_directive_.response_header_operations()); } return FilterHeadersStatus::Continue; } void Filter::setDecoderFilterCallbacks( StreamDecoderFilterCallbacks& callbacks) { ENVOY_LOG(debug, "Called Mixer::Filter : {}", __func__); decoder_callbacks_ = &callbacks; } void Filter::completeCheck(const CheckResponseInfo& info) { auto status = info.response_status; ENVOY_LOG(debug, "Called Mixer::Filter : check complete {}", status.ToString()); // This stream has been reset, abort the callback. if (state_ == Responded) { return; } if (!status.ok()) { state_ = Responded; int status_code = ::istio::utils::StatusHttpCode(status.error_code()); decoder_callbacks_->sendLocalReply(Code(status_code), status.ToString(), nullptr); decoder_callbacks_->requestInfo().setResponseFlag( RequestInfo::ResponseFlag::UnauthorizedExternalService); return; } state_ = Complete; route_directive_ = info.route_directive; // handle direct response from the route directive if (status.ok() && route_directive_.direct_response_code() != 0) { ENVOY_LOG(debug, "Mixer::Filter direct response"); state_ = Responded; decoder_callbacks_->sendLocalReply( Code(route_directive_.direct_response_code()), route_directive_.direct_response_body(), [this](HeaderMap& headers) { UpdateHeaders(headers, route_directive_.response_header_operations()); }); return; } // handle request header operations if (nullptr != headers_) { UpdateHeaders(*headers_, route_directive_.request_header_operations()); headers_ = nullptr; } if (!initiating_call_) { decoder_callbacks_->continueDecoding(); } } void Filter::onDestroy() { ENVOY_LOG(debug, "Called Mixer::Filter : {} state: {}", __func__, state_); if (state_ != Calling) { cancel_check_ = nullptr; } state_ = Responded; if (cancel_check_) { ENVOY_LOG(debug, "Cancelling check call"); cancel_check_(); cancel_check_ = nullptr; } } void Filter::log(const HeaderMap* request_headers, const HeaderMap* response_headers, const HeaderMap* response_trailers, const RequestInfo::RequestInfo& request_info) { ENVOY_LOG(debug, "Called Mixer::Filter : {}", __func__); if (!handler_) { if (request_headers == nullptr) { return; } // Here Request is rejected by other filters, Mixer filter is not called. ::istio::control::http::Controller::PerRouteConfig config; ReadPerRouteConfig(request_info.routeEntry(), &config); handler_ = control_.controller()->CreateRequestHandler(config); CheckData check_data(*request_headers, request_info.dynamicMetadata(), nullptr); handler_->ExtractRequestAttributes(&check_data); } // response trailer header is not counted to response total size. ReportData report_data(response_headers, response_trailers, request_info, request_total_size_); handler_->Report(&report_data); } } // namespace Mixer } // namespace Http } // namespace Envoy <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2015 Jett * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef HCKT_TREE_H #define HCKT_TREE_H #include <cassert> #include <vector> #include <bitset> #include "lmemvector.hpp" namespace hckt { template <typename ValueType> class tree { protected: std::bitset<64> bitset; hckt::lmemvector<ValueType> values; hckt::lmemvector<tree<ValueType>*> children; public: tree() : bitset { 0 }, values { }, children { } { } ~tree() { collapse(); } //counts number of set bits static inline int popcount(std::uint64_t x) { #ifdef __SSE4_2__ return _popcnt64(x); #else constexpr std::uint64_t m1 { 0x5555555555555555 }; constexpr std::uint64_t m2 { 0x3333333333333333 }; constexpr std::uint64_t m4 { 0x0f0f0f0f0f0f0f0f }; constexpr std::uint64_t h01 { 0x0101010101010101 }; x -= (x >> 1) & m1; x = (x & m2) + ((x >> 2) & m2); x = (x + (x >> 4)) & m4; return (x * h01) >> 56; #endif } std::size_t get_children_position(const std::size_t position) const { assert(position >= 0 && position < 64); //we know it will be 0 //plus - we cant shift by 64 without ub if(position == 0) { return 0; } return popcount(bitset.to_ullong() << (64 - position)); } std::size_t calculate_memory_size() const { std::size_t size { sizeof(bitset) + sizeof(values) + (values.capacity() * sizeof(ValueType)) + sizeof(children) + (children.capacity() * sizeof(tree<ValueType>*)) }; for(auto child : children) { size += child->calculate_memory_size(); } return size; } std::size_t calculate_children_amount() const { std::size_t amount { popcount(bitset.to_ullong()) }; for(auto child : children) { amount += child->calculate_children_amount(); } return amount; } /* * 2d get position * convert three part positions to memory location * as input: (left = 0 | right = 1) + (top = 0 | bottom = 2) * * result will be: * y1:x1:y2:x2:y3:x3 * */ static std::size_t get_position_2d(const std::size_t d1, const std::size_t d2, const std::size_t d3) { assert(d1 >= 0 && d1 < 4); assert(d2 >= 0 && d2 < 4); assert(d3 >= 0 && d3 < 4); return ((1 << 0) * ((d1 & 2) >> 1)) + ((1 << 1) * (d1 & 1)) + ((1 << 2) * ((d2 & 2) >> 1)) + ((1 << 3) * (d2 & 1)) + ((1 << 4) * ((d3 & 2) >> 1)) + ((1 << 5) * (d3 & 1)); } static std::size_t get_x_2d(const std::size_t d1, const std::size_t d2, const std::size_t d3) { assert(d1 >= 0 && d1 < 4); assert(d2 >= 0 && d2 < 4); assert(d3 >= 0 && d3 < 4); return ((d1 & 1) << 0) + ((d2 & 1) << 1) + ((d3 & 1) << 2); } static std::size_t get_y_2d(const std::size_t d1, const std::size_t d2, const std::size_t d3) { assert(d1 >= 0 && d1 < 4); assert(d2 >= 0 && d2 < 4); assert(d3 >= 0 && d3 < 4); return ((d1 & 2) >> 1 << 0) + ((d2 & 2) >> 1 << 1) + ((d3 & 2) >> 1 << 2); } /* * 3d get position * convert two part positions to memory location * as input: (left = 0 | right = 1) + (top = 0 | bottom = 2) + (in = 0 | out = 4) * * result will be: * z1:y1:x1:z2:y2:x2 * */ static std::size_t get_position_3d(const std::size_t d1, const std::size_t d2) { assert(d1 >= 0 && d1 < 8); assert(d2 >= 0 && d2 < 8); return ((1 << 0) * ((d1 & 4) >> 2)) + ((1 << 1) * ((d1 & 2) >> 1)) + ((1 << 2) * (d1 & 1)) + ((1 << 3) * ((d2 & 4) >> 2)) + ((1 << 4) * ((d2 & 2) >> 1)) + ((1 << 5) * (d2 & 1)); } static std::size_t get_x_3d(const std::size_t d1, const std::size_t d2) { assert(d1 >= 0 && d1 < 8); assert(d2 >= 0 && d2 < 8); return ((d1 & 1) << 0) + ((d2 & 1) << 1); } static std::size_t get_y_3d(const std::size_t d1, const std::size_t d2) { assert(d1 >= 0 && d1 < 8); assert(d2 >= 0 && d2 < 8); return ((d1 & 2) >> 1 << 0) + ((d2 & 2) >> 1 << 1); } static std::size_t get_z_3d(const std::size_t d1, const std::size_t d2) { assert(d1 >= 0 && d1 < 8); assert(d2 >= 0 && d2 < 8); return ((d1 & 4) >> 2 << 0) + ((d2 & 4) >> 2 << 1); } /* * check if we have any children */ bool empty() const { return bitset.none(); } bool isset(const std::size_t position) const { assert(position >= 0 && position < 64); return bitset[position]; } /* * destroy children */ void collapse() { for(auto child : children) { child->collapse(); } children.clear(); values.clear(); bitset.reset(); } /* * insert an item into position of tree * position should be result of get_position */ void insert(const std::size_t position, const ValueType value) { assert(position >= 0 && position < 64); const std::size_t cpos { get_children_position(position) }; children.insert(cpos, new tree<ValueType>()); values.insert(cpos, value); bitset.set(position); } void insert_direct(const std::size_t position, const std::size_t cpos, const ValueType value) { assert(position >= 0 && position < 64); assert(cpos >= 0 && cpos < 64); children.insert(cpos, new tree<ValueType>()); values.insert(cpos, value); bitset.set(position); } /* * removes an item from tree * position should be result of get_position */ void remove(const std::size_t position) { assert(position >= 0 && position < 64); const std::size_t cpos { get_children_position(position) }; children[cpos]->collapse(); children.erase(cpos); values.erase(cpos); bitset.reset(position); } void remove_direct(const std::size_t position, const std::size_t cpos) { assert(position >= 0 && position < 64); assert(cpos >= 0 && cpos < 64); children[cpos]->collapse(); children.erase(cpos); values.erase(cpos); bitset.reset(position); } /* * get child node * position should be result of get_position */ tree<ValueType> * child(const std::size_t position) const { assert(position >= 0 && position < 64); return child_direct(get_children_position(position)); } tree<ValueType> * child_direct(const std::size_t cpos) const { assert(cpos >= 0 && cpos < 64); return children[cpos]; } /* * sets node to specific value * note: this does not check whether a value has been inserted here yet * position should be result of get_position */ void set_value(const std::size_t position, const ValueType value) { assert(position >= 0 && position < 64); set_value_direct(get_children_position(position)); } void set_value_direct(const std::size_t cpos, const ValueType value) { assert(cpos >= 0 && cpos < 64); values[cpos] = value; } /* * gets value from specific position * note: this does not check whether a value has been inserted here yet * position should be result of get_position */ ValueType get_value(const std::size_t position) const { assert(position >= 0 && position < 64); return get_value_direct(get_children_position(position)); } ValueType get_value_direct(const std::size_t cpos) const { assert(cpos >= 0 && cpos < 64); return values[cpos]; } }; }; #endif <commit_msg>use faster data types<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2015 Jett * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef HCKT_TREE_H #define HCKT_TREE_H #include <cassert> #include <vector> #include <bitset> #include "lmemvector.hpp" namespace hckt { template <typename ValueType> class tree { protected: std::bitset<64> bitset; hckt::lmemvector<ValueType> values; hckt::lmemvector<tree<ValueType>*> children; public: tree() : bitset { 0 }, values { }, children { } { } ~tree() { collapse(); } //counts number of set bits static inline unsigned popcount(std::uint64_t x) { #ifdef __SSE4_2__ return _popcnt64(x); #else constexpr std::uint64_t m1 { 0x5555555555555555 }; constexpr std::uint64_t m2 { 0x3333333333333333 }; constexpr std::uint64_t m4 { 0x0f0f0f0f0f0f0f0f }; constexpr std::uint64_t h01 { 0x0101010101010101 }; x -= (x >> 1) & m1; x = (x & m2) + ((x >> 2) & m2); x = (x + (x >> 4)) & m4; return (x * h01) >> 56; #endif } unsigned get_children_position(const unsigned position) const { assert(position < 64); //we know it will be 0 //plus - we cant shift by 64 without ub if(position == 0) { return 0; } return popcount(bitset.to_ullong() << (64 - position)); } std::size_t calculate_memory_size() const { std::size_t size { sizeof(bitset) + sizeof(values) + (values.capacity() * sizeof(ValueType)) + sizeof(children) + (children.capacity() * sizeof(tree<ValueType>*)) }; for(auto child : children) { size += child->calculate_memory_size(); } return size; } std::size_t calculate_children_amount() const { std::size_t amount { popcount(bitset.to_ullong()) }; for(auto child : children) { amount += child->calculate_children_amount(); } return amount; } /* * 2d get position * convert three part positions to memory location * as input: (left = 0 | right = 1) + (top = 0 | bottom = 2) * * result will be: * y1:x1:y2:x2:y3:x3 * */ static unsigned get_position_2d(const unsigned d1, const unsigned d2, const unsigned d3) { assert(d1 < 4); assert(d2 < 4); assert(d3 < 4); return ((1 << 0) * ((d1 & 2) >> 1)) + ((1 << 1) * (d1 & 1)) + ((1 << 2) * ((d2 & 2) >> 1)) + ((1 << 3) * (d2 & 1)) + ((1 << 4) * ((d3 & 2) >> 1)) + ((1 << 5) * (d3 & 1)); } static unsigned get_x_2d(const unsigned d1, const unsigned d2, const unsigned d3) { assert(d1 < 4); assert(d2 < 4); assert(d3 < 4); return ((d1 & 1) << 0) + ((d2 & 1) << 1) + ((d3 & 1) << 2); } static unsigned get_y_2d(const unsigned d1, const unsigned d2, const unsigned d3) { assert(d1 < 4); assert(d2 < 4); assert(d3 < 4); return ((d1 & 2) >> 1 << 0) + ((d2 & 2) >> 1 << 1) + ((d3 & 2) >> 1 << 2); } /* * 3d get position * convert two part positions to memory location * as input: (left = 0 | right = 1) + (top = 0 | bottom = 2) + (in = 0 | out = 4) * * result will be: * z1:y1:x1:z2:y2:x2 * */ static unsigned get_position_3d(const unsigned d1, const unsigned d2) { assert(d1 < 8); assert(d2 < 8); return ((1 << 0) * ((d1 & 4) >> 2)) + ((1 << 1) * ((d1 & 2) >> 1)) + ((1 << 2) * (d1 & 1)) + ((1 << 3) * ((d2 & 4) >> 2)) + ((1 << 4) * ((d2 & 2) >> 1)) + ((1 << 5) * (d2 & 1)); } static unsigned get_x_3d(const unsigned d1, const unsigned d2) { assert(d1 < 8); assert(d2 < 8); return ((d1 & 1) << 0) + ((d2 & 1) << 1); } static unsigned get_y_3d(const unsigned d1, const unsigned d2) { assert(d1 < 8); assert(d2 < 8); return ((d1 & 2) >> 1 << 0) + ((d2 & 2) >> 1 << 1); } static unsigned get_z_3d(const unsigned d1, const unsigned d2) { assert(d1 < 8); assert(d2 < 8); return ((d1 & 4) >> 2 << 0) + ((d2 & 4) >> 2 << 1); } /* * check if we have any children */ bool empty() const { return bitset.none(); } bool isset(const unsigned position) const { assert(position >= 0 && position < 64); return bitset[position]; } /* * destroy children */ void collapse() { for(auto child : children) { child->collapse(); } children.clear(); values.clear(); bitset.reset(); } /* * insert an item unsignedo position of tree * position should be result of get_position */ void insert(const unsigned position, const ValueType value) { assert(position < 64); const unsigned cpos { get_children_position(position) }; children.insert(cpos, new tree<ValueType>()); values.insert(cpos, value); bitset.set(position); } void insert_direct(const unsigned position, const unsigned cpos, const ValueType value) { assert(position < 64); assert(cpos < 64); children.insert(cpos, new tree<ValueType>()); values.insert(cpos, value); bitset.set(position); } /* * removes an item from tree * position should be result of get_position */ void remove(const unsigned position) { assert(position < 64); const unsigned cpos { get_children_position(position) }; children[cpos]->collapse(); children.erase(cpos); values.erase(cpos); bitset.reset(position); } void remove_direct(const unsigned position, const unsigned cpos) { assert(position < 64); assert(cpos < 64); children[cpos]->collapse(); children.erase(cpos); values.erase(cpos); bitset.reset(position); } /* * get child node * position should be result of get_position */ tree<ValueType> * child(const unsigned position) const { assert(position < 64); return child_direct(get_children_position(position)); } tree<ValueType> * child_direct(const unsigned cpos) const { assert(cpos < 64); return children[cpos]; } /* * sets node to specific value * note: this does not check whether a value has been inserted here yet * position should be result of get_position */ void set_value(const unsigned position, const ValueType value) { assert(position < 64); set_value_direct(get_children_position(position)); } void set_value_direct(const unsigned cpos, const ValueType value) { assert(cpos < 64); values[cpos] = value; } /* * gets value from specific position * note: this does not check whether a value has been inserted here yet * position should be result of get_position */ ValueType get_value(const unsigned position) const { assert(position < 64); return get_value_direct(get_children_position(position)); } ValueType get_value_direct(const unsigned cpos) const { assert(cpos < 64); return values[cpos]; } }; }; #endif <|endoftext|>
<commit_before>/** * binary search tree class * created by lisovskey */ #ifndef TREE_H #define TREE_H #define ANYWAY #define THEN #include <memory> #include <experimental/optional> // waiting for cpp17 using std::experimental::optional; using std::experimental::make_optional; template <typename T> class Tree { // prototype struct node; // aliases using pointer = std::shared_ptr<node>; using pair = std::pair<int, T>; // unit of tree struct node { pair data; pointer left; pointer right; node(pair data) : data(data), left(NULL), right(NULL) {} }; // start point pointer root; // CONDITION ACTION pointer _insert(pointer leaf, pair data) { if (!leaf) return leaf = pointer(new node(data)); else if (data.first < leaf->data.first) leaf->left = _insert(leaf->left, data); else if (data.first > leaf->data.first) leaf->right = _insert(leaf->right, data); else leaf->data.first = data.first; ANYWAY return leaf; } pointer _find(pointer leaf, int key) { if (!leaf || leaf->data.first == key) return leaf; else if (key < leaf->data.first) return _find(leaf->left, key); else return _find(leaf->right, key); } pointer _min(pointer leaf) { if (leaf->left) return _min(leaf->left); else return leaf; } pointer _remove(pointer leaf, int key) { if (!leaf) return leaf; else if (key < leaf->data.first) leaf->left = _remove(leaf->left, key); else if (key > leaf->data.first) leaf->right = _remove(leaf->right, key); else if (leaf->left && leaf->right) { THEN leaf->data.first = (_min(leaf->right))->data.first; THEN leaf->right = _remove(leaf->right, leaf->data.first); } else if (leaf->left) leaf = leaf->left; else if (leaf->right) leaf = leaf->right; else leaf = NULL; ANYWAY return leaf; } int _size(pointer leaf) { if (!leaf) return 0; else return _size(leaf->left) + 1 + _size(leaf->right); } public: // constructors Tree() : root(NULL) {} Tree(int key, T value) : root(new node(pair(key, value))) {} // usable methods void insert(int key, T value) { ANYWAY root = _insert(root, pair(key, value)); } optional<T> find(int key) { ANYWAY pointer leaf = _find(root, key); if (leaf) return make_optional(leaf->data.second); else return {}; } void remove(int key) { ANYWAY root = _remove(root, key); } int size() { ANYWAY return _size(root); } }; #endif <commit_msg>namespace, operators, const, doc<commit_after>/** * binary search tree class * created by lisovskey */ #ifndef TREE_H #define TREE_H #define RZD_BEGIN namespace rzd { #define RZD_END } #define ANYWAY #define THEN #include <list> #include <memory> #include <ostream> #include <optional> RZD_BEGIN using std::list; using std::ostream; using std::optional; using std::make_optional; // binary search tree template <typename T> class Tree { // prototype struct Node; // aliases using pointer = std::shared_ptr<Node>; using pair = std::pair<int, T>; // unit of tree struct Node { pair data; pointer left; pointer right; Node(pair data) : data{ data }, left{ nullptr }, right{ nullptr } {} }; // start point pointer root; // IF CONDITION ACTION pointer _insert(pointer leaf, const pair data) { if (!leaf) return leaf = pointer(new Node(data)); else if (data.first < leaf->data.first) leaf->left = _insert(leaf->left, data); else if (data.first > leaf->data.first) leaf->right = _insert(leaf->right, data); else leaf->data.first = data.first; ANYWAY return leaf; } pointer _find(const pointer leaf, const int key) const { if (!leaf || leaf->data.first == key) return leaf; else if (key < leaf->data.first) return _find(leaf->left, key); else return _find(leaf->right, key); } pointer _min(const pointer leaf) const { if (leaf->left) return _min(leaf->left); else return leaf; } pointer _remove(pointer leaf, const int key) { if (!leaf) return leaf; else if (key < leaf->data.first) leaf->left = _remove(leaf->left, key); else if (key > leaf->data.first) leaf->right = _remove(leaf->right, key); else if (leaf->left && leaf->right) { THEN leaf->data.first = (_min(leaf->right))->data.first; THEN leaf->right = _remove(leaf->right, leaf->data.first); } else if (leaf->left) leaf = leaf->left; else if (leaf->right) leaf = leaf->right; else leaf = nullptr; ANYWAY return leaf; } int _size(const pointer leaf) const { if (leaf) return _size(leaf->left) + 1 + _size(leaf->right); else return 0; } ostream& _view(const pointer leaf, ostream& os) const { if (leaf) { THEN _view(leaf->left, os); THEN os << leaf->data.second << "\n"; THEN _view(leaf->right, os); } ANYWAY return os; } list<pair>& _get_list(const pointer leaf, list<pair>& list) const { if (leaf) { THEN _get_list(leaf->left, list); THEN list.push_back(leaf->data); THEN _get_list(leaf->right, list); } ANYWAY return list; } public: // operators optional<T> operator[](const int key) { ANYWAY return find(key); } friend ostream& operator<<(ostream& os, const Tree& tree) { ANYWAY return tree._view(tree.root, os); } // constructors Tree() : root{ nullptr } {} Tree(const int key, const T value) : root{ new Node(pair(key, value)) } {} // usable methods // inserts new node with key and value void insert(const int key, const T value) { ANYWAY root = _insert(root, pair(key, value)); } // returns optional value by key optional<T> find(const int key) const { ANYWAY pointer leaf = _find(root, key); if (leaf) return make_optional(leaf->data.second); else return {}; } // removes node by key void remove(const int key) { ANYWAY root = _remove(root, key); } // returns number of nodes int size() const { ANYWAY return _size(root); } // returns sorted list list<pair> get_list() const { ANYWAY list<pair> list; ANYWAY return _get_list(root, list); } }; RZD_END #endif<|endoftext|>
<commit_before>#pragma once extern "C" { #include <TH/TH.h> } #include <opencv2/core.hpp> #ifdef WITH_CUDA #include <THC/THC.h> #include <opencv2/core/cuda.hpp> #endif #include <iostream> #include <array> extern "C" int getIntMax() { return INT_MAX; } extern "C" float getFloatMax() { return FLT_MAX; } /***************** Tensor <=> Mat conversion *****************/ #define TO_MAT_OR_NOARRAY(mat) (mat.isNull() ? cv::noArray() : mat.toMat()) #define TO_MAT_LIST_OR_NOARRAY(mat) (mat.isNull() ? cv::noArray() : mat.toMatList()) struct TensorWrapper { void *tensorPtr; char typeCode; TensorWrapper(); TensorWrapper(cv::Mat & mat); TensorWrapper(cv::Mat && mat); TensorWrapper(cv::cuda::GpuMat & mat, THCState *state); TensorWrapper(cv::cuda::GpuMat && mat, THCState *state); operator cv::Mat(); // synonym for operator cv::Mat() inline cv::Mat toMat() { return *this; } #ifdef WITH_CUDA cv::cuda::GpuMat toGpuMat(); #endif inline bool isNull() { return tensorPtr == nullptr; } }; struct TensorArray { struct TensorWrapper *tensors; int size; TensorArray(); TensorArray(std::vector<cv::Mat> & matList); explicit TensorArray(short size); #ifdef WITH_CUDA TensorArray(std::vector<cv::cuda::GpuMat> & matList, THCState *state); #endif operator std::vector<cv::Mat>(); // synonym for operator std::vector<cv::Mat>() inline std::vector<cv::Mat> toMatList() { return *this; } inline bool isNull() { return tensors == nullptr; } }; inline std::string typeStr(cv::Mat & mat) { switch (mat.depth()) { case CV_8U: return "Byte"; case CV_8S: return "Char"; case CV_16S: return "Short"; case CV_32S: return "Int"; case CV_32F: return "Float"; case CV_64F: return "Double"; default: return "Unknown"; } } /***************** Wrappers for small OpenCV classes *****************/ struct SizeWrapper { int width, height; inline operator cv::Size() { return cv::Size(width, height); } SizeWrapper(const cv::Size & other); inline SizeWrapper() {} }; struct Size2fWrapper { float width, height; inline operator cv::Size2f() { return cv::Size2f(width, height); } inline Size2fWrapper() {} Size2fWrapper(const cv::Size2f & other); }; struct TermCriteriaWrapper { int type, maxCount; double epsilon; inline operator cv::TermCriteria() { return cv::TermCriteria(type, maxCount, epsilon); } inline cv::TermCriteria orDefault(cv::TermCriteria defaultVal) { return (this->type == 0 ? defaultVal : *this); } TermCriteriaWrapper(cv::TermCriteria && other); }; struct ScalarWrapper { double v0, v1, v2, v3; inline operator cv::Scalar() { return cv::Scalar(v0, v1, v2, v3); } inline cv::Scalar orDefault(cv::Scalar defaultVal) { return (isnan(this->v0) ? defaultVal : *this); } }; struct Vec2dWrapper { double v0, v1; inline operator cv::Vec2d() { return cv::Vec2d(v0, v1); } inline Vec2dWrapper(const cv::Vec2d & other) { this->v0 = other.val[0]; this->v1 = other.val[1]; } }; struct Vec3dWrapper { double v0, v1, v2; }; struct Vec3fWrapper { float v0, v1, v2; }; struct Vec3iWrapper { int v0, v1, v2; }; struct RectWrapper { int x, y, width, height; inline operator cv::Rect() { return cv::Rect(x, y, width, height); } RectWrapper & operator=(cv::Rect & other); RectWrapper(const cv::Rect & other); inline RectWrapper() {} }; struct PointWrapper { int x, y; inline operator cv::Point() { return cv::Point(x, y); } PointWrapper(const cv::Point & other); }; struct Point2fWrapper { float x, y; inline operator cv::Point2f() { return cv::Point2f(x, y); } Point2fWrapper(const cv::Point2f & other); inline Point2fWrapper() {} }; struct RotatedRectWrapper { struct Point2fWrapper center; struct Size2fWrapper size; float angle; RotatedRectWrapper() {} RotatedRectWrapper(const cv::RotatedRect & other); inline operator cv::RotatedRect() { return cv::RotatedRect(center, size, angle); } }; struct MomentsWrapper { double m00, m10, m01, m20, m11, m02, m30, m21, m12, m03; double mu20, mu11, mu02, mu30, mu21, mu12, mu03; double nu20, nu11, nu02, nu30, nu21, nu12, nu03; MomentsWrapper(const cv::Moments & other); inline operator cv::Moments() { return cv::Moments(m00, m10, m01, m20, m11, m02, m30, m21, m12, m03); } }; struct RotatedRectPlusRect { struct RotatedRectWrapper rotrect; struct RectWrapper rect; }; struct DMatchWrapper { int queryIdx; int trainIdx; int imgIdx; float distance; }; struct DMatchArray { int size; struct DMatchWrapper *data; DMatchArray() {} DMatchArray(std::vector<cv::DMatch> & other); operator std::vector<cv::DMatch>(); }; struct DMatchArrayOfArrays { int size; struct DMatchArray *data; DMatchArrayOfArrays() {} DMatchArrayOfArrays(std::vector<std::vector<cv::DMatch>> & other); operator std::vector<std::vector<cv::DMatch>>(); }; /***************** Helper wrappers for [OpenCV class + some primitive] *****************/ struct TensorPlusDouble { struct TensorWrapper tensor; double val; }; struct TensorPlusFloat { struct TensorWrapper tensor; float val; }; struct TensorPlusInt { struct TensorWrapper tensor; int val; }; struct TensorPlusBool { struct TensorWrapper tensor; bool val; }; struct TensorArrayPlusFloat { struct TensorArray tensors; float val; }; struct TensorArrayPlusDouble { struct TensorArray tensors; double val; }; struct TensorArrayPlusInt { struct TensorArray tensors; int val; }; struct TensorArrayPlusBool { struct TensorArray tensors; bool val; }; struct RectPlusInt { struct RectWrapper rect; int val; }; struct ScalarPlusBool { struct ScalarWrapper scalar; bool val; }; struct SizePlusInt { struct SizeWrapper size; int val; }; struct Point2fPlusInt { struct Point2fWrapper point; int val; }; /***************** Other helper structs *****************/ // Arrays struct IntArray { int *data; int size; }; struct FloatArray { float *data; int size; inline std::vector<float>& toFloatList(std::vector<float>& res) { for (int i = 0; i < size; ++i) res.push_back(data[i]); return res; } }; struct DoubleArray { double *data; int size; }; struct PointArray { struct PointWrapper *data; int size; }; struct RectArray { struct RectWrapper *data; int size; RectArray() {} RectArray(std::vector<cv::Rect> & vec); }; struct TensorPlusRectArray { struct TensorWrapper tensor; struct RectArray rects; TensorPlusRectArray() {} }; // Arrays of arrays struct FloatArrayOfArrays { float **pointers; float *realData; int dims; }; struct PointArrayOfArrays { struct PointWrapper **pointers; struct PointWrapper *realData; int dims; int *sizes; };<commit_msg>add WITH_CUDA ifdef for GpuMat<commit_after>#pragma once extern "C" { #include <TH/TH.h> } #include <opencv2/core.hpp> #ifdef WITH_CUDA #include <THC/THC.h> #include <opencv2/core/cuda.hpp> #endif #include <iostream> #include <array> extern "C" int getIntMax() { return INT_MAX; } extern "C" float getFloatMax() { return FLT_MAX; } /***************** Tensor <=> Mat conversion *****************/ #define TO_MAT_OR_NOARRAY(mat) (mat.isNull() ? cv::noArray() : mat.toMat()) #define TO_MAT_LIST_OR_NOARRAY(mat) (mat.isNull() ? cv::noArray() : mat.toMatList()) struct TensorWrapper { void *tensorPtr; char typeCode; TensorWrapper(); TensorWrapper(cv::Mat & mat); TensorWrapper(cv::Mat && mat); #ifdef WITH_CUDA TensorWrapper(cv::cuda::GpuMat & mat, THCState *state); TensorWrapper(cv::cuda::GpuMat && mat, THCState *state); #endif operator cv::Mat(); // synonym for operator cv::Mat() inline cv::Mat toMat() { return *this; } #ifdef WITH_CUDA cv::cuda::GpuMat toGpuMat(); #endif inline bool isNull() { return tensorPtr == nullptr; } }; struct TensorArray { struct TensorWrapper *tensors; int size; TensorArray(); TensorArray(std::vector<cv::Mat> & matList); explicit TensorArray(short size); #ifdef WITH_CUDA TensorArray(std::vector<cv::cuda::GpuMat> & matList, THCState *state); #endif operator std::vector<cv::Mat>(); // synonym for operator std::vector<cv::Mat>() inline std::vector<cv::Mat> toMatList() { return *this; } inline bool isNull() { return tensors == nullptr; } }; inline std::string typeStr(cv::Mat & mat) { switch (mat.depth()) { case CV_8U: return "Byte"; case CV_8S: return "Char"; case CV_16S: return "Short"; case CV_32S: return "Int"; case CV_32F: return "Float"; case CV_64F: return "Double"; default: return "Unknown"; } } /***************** Wrappers for small OpenCV classes *****************/ struct SizeWrapper { int width, height; inline operator cv::Size() { return cv::Size(width, height); } SizeWrapper(const cv::Size & other); inline SizeWrapper() {} }; struct Size2fWrapper { float width, height; inline operator cv::Size2f() { return cv::Size2f(width, height); } inline Size2fWrapper() {} Size2fWrapper(const cv::Size2f & other); }; struct TermCriteriaWrapper { int type, maxCount; double epsilon; inline operator cv::TermCriteria() { return cv::TermCriteria(type, maxCount, epsilon); } inline cv::TermCriteria orDefault(cv::TermCriteria defaultVal) { return (this->type == 0 ? defaultVal : *this); } TermCriteriaWrapper(cv::TermCriteria && other); }; struct ScalarWrapper { double v0, v1, v2, v3; inline operator cv::Scalar() { return cv::Scalar(v0, v1, v2, v3); } inline cv::Scalar orDefault(cv::Scalar defaultVal) { return (isnan(this->v0) ? defaultVal : *this); } }; struct Vec2dWrapper { double v0, v1; inline operator cv::Vec2d() { return cv::Vec2d(v0, v1); } inline Vec2dWrapper(const cv::Vec2d & other) { this->v0 = other.val[0]; this->v1 = other.val[1]; } }; struct Vec3dWrapper { double v0, v1, v2; }; struct Vec3fWrapper { float v0, v1, v2; }; struct Vec3iWrapper { int v0, v1, v2; }; struct RectWrapper { int x, y, width, height; inline operator cv::Rect() { return cv::Rect(x, y, width, height); } RectWrapper & operator=(cv::Rect & other); RectWrapper(const cv::Rect & other); inline RectWrapper() {} }; struct PointWrapper { int x, y; inline operator cv::Point() { return cv::Point(x, y); } PointWrapper(const cv::Point & other); }; struct Point2fWrapper { float x, y; inline operator cv::Point2f() { return cv::Point2f(x, y); } Point2fWrapper(const cv::Point2f & other); inline Point2fWrapper() {} }; struct RotatedRectWrapper { struct Point2fWrapper center; struct Size2fWrapper size; float angle; RotatedRectWrapper() {} RotatedRectWrapper(const cv::RotatedRect & other); inline operator cv::RotatedRect() { return cv::RotatedRect(center, size, angle); } }; struct MomentsWrapper { double m00, m10, m01, m20, m11, m02, m30, m21, m12, m03; double mu20, mu11, mu02, mu30, mu21, mu12, mu03; double nu20, nu11, nu02, nu30, nu21, nu12, nu03; MomentsWrapper(const cv::Moments & other); inline operator cv::Moments() { return cv::Moments(m00, m10, m01, m20, m11, m02, m30, m21, m12, m03); } }; struct RotatedRectPlusRect { struct RotatedRectWrapper rotrect; struct RectWrapper rect; }; struct DMatchWrapper { int queryIdx; int trainIdx; int imgIdx; float distance; }; struct DMatchArray { int size; struct DMatchWrapper *data; DMatchArray() {} DMatchArray(std::vector<cv::DMatch> & other); operator std::vector<cv::DMatch>(); }; struct DMatchArrayOfArrays { int size; struct DMatchArray *data; DMatchArrayOfArrays() {} DMatchArrayOfArrays(std::vector<std::vector<cv::DMatch>> & other); operator std::vector<std::vector<cv::DMatch>>(); }; /***************** Helper wrappers for [OpenCV class + some primitive] *****************/ struct TensorPlusDouble { struct TensorWrapper tensor; double val; }; struct TensorPlusFloat { struct TensorWrapper tensor; float val; }; struct TensorPlusInt { struct TensorWrapper tensor; int val; }; struct TensorPlusBool { struct TensorWrapper tensor; bool val; }; struct TensorArrayPlusFloat { struct TensorArray tensors; float val; }; struct TensorArrayPlusDouble { struct TensorArray tensors; double val; }; struct TensorArrayPlusInt { struct TensorArray tensors; int val; }; struct TensorArrayPlusBool { struct TensorArray tensors; bool val; }; struct RectPlusInt { struct RectWrapper rect; int val; }; struct ScalarPlusBool { struct ScalarWrapper scalar; bool val; }; struct SizePlusInt { struct SizeWrapper size; int val; }; struct Point2fPlusInt { struct Point2fWrapper point; int val; }; /***************** Other helper structs *****************/ // Arrays struct IntArray { int *data; int size; }; struct FloatArray { float *data; int size; inline std::vector<float>& toFloatList(std::vector<float>& res) { for (int i = 0; i < size; ++i) res.push_back(data[i]); return res; } }; struct DoubleArray { double *data; int size; }; struct PointArray { struct PointWrapper *data; int size; }; struct RectArray { struct RectWrapper *data; int size; RectArray() {} RectArray(std::vector<cv::Rect> & vec); }; struct TensorPlusRectArray { struct TensorWrapper tensor; struct RectArray rects; TensorPlusRectArray() {} }; // Arrays of arrays struct FloatArrayOfArrays { float **pointers; float *realData; int dims; }; struct PointArrayOfArrays { struct PointWrapper **pointers; struct PointWrapper *realData; int dims; int *sizes; }; <|endoftext|>
<commit_before><commit_msg>coverity#708898 Unused pointer value<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" #include "osl/module.h" #include "osl/process.h" #include "rtl/ustrbuf.hxx" #include "vcl/salinst.hxx" #include "saldata.hxx" #include <cstdio> #include <unistd.h> using namespace rtl; extern "C" { typedef SalInstance*(*salFactoryProc)( oslModule pModule); } static oslModule pCloseModule = NULL; enum { DESKTOP_NONE = 0, DESKTOP_UNKNOWN, DESKTOP_GNOME, DESKTOP_KDE, DESKTOP_KDE4, DESKTOP_CDE }; static const char * desktop_strings[] = { "none", "unknown", "GNOME", "KDE", "KDE4", "CDE" }; static SalInstance* tryInstance( const OUString& rModuleBase ) { SalInstance* pInst = NULL; OUStringBuffer aModName( 128 ); aModName.appendAscii( SAL_DLLPREFIX"vclplug_" ); aModName.append( rModuleBase ); aModName.appendAscii( SAL_DLLPOSTFIX ); aModName.appendAscii( SAL_DLLEXTENSION ); OUString aModule = aModName.makeStringAndClear(); oslModule aMod = osl_loadModuleRelative( reinterpret_cast< oslGenericFunction >( &tryInstance ), aModule.pData, SAL_LOADMODULE_DEFAULT ); if( aMod ) { salFactoryProc aProc = (salFactoryProc)osl_getAsciiFunctionSymbol( aMod, "create_SalInstance" ); if( aProc ) { pInst = aProc( aMod ); #if OSL_DEBUG_LEVEL > 1 std::fprintf( stderr, "sal plugin %s produced instance %p\n", OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr(), pInst ); #endif if( pInst ) { pCloseModule = aMod; /* * Recent GTK+ versions load their modules with RTLD_LOCAL, so we can * not access the 'gnome_accessibility_module_shutdown' anymore. * So make sure libgtk+ & co are still mapped into memory when * atk-bridge's atexit handler gets called. */ if( rModuleBase.equalsAscii("gtk") ) { pCloseModule = NULL; } GetSalData()->m_pPlugin = aMod; } else osl_unloadModule( aMod ); } else { #if OSL_DEBUG_LEVEL > 1 std::fprintf( stderr, "could not load symbol %s from shared object %s\n", "create_SalInstance", OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr() ); #endif osl_unloadModule( aMod ); } } #if OSL_DEBUG_LEVEL > 1 else std::fprintf( stderr, "could not load shared object %s\n", OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr() ); #endif return pInst; } static const rtl::OUString& get_desktop_environment() { static rtl::OUString aRet; if( ! aRet.getLength() ) { OUStringBuffer aModName( 128 ); aModName.appendAscii( SAL_DLLPREFIX"desktop_detector" ); aModName.appendAscii( SAL_DLLPOSTFIX ); aModName.appendAscii( SAL_DLLEXTENSION ); OUString aModule = aModName.makeStringAndClear(); oslModule aMod = osl_loadModuleRelative( reinterpret_cast< oslGenericFunction >( &tryInstance ), aModule.pData, SAL_LOADMODULE_DEFAULT ); if( aMod ) { rtl::OUString (*pSym)() = (rtl::OUString(*)()) osl_getAsciiFunctionSymbol( aMod, "get_desktop_environment" ); if( pSym ) aRet = pSym(); } osl_unloadModule( aMod ); } return aRet; } static SalInstance* autodetect_plugin() { static const char* pKDEFallbackList[] = { "kde4", "kde", "gtk", "gen", 0 }; static const char* pStandardFallbackList[] = { "gtk", "gen", 0 }; static const char* pHeadlessFallbackList[] = { "svp", 0 }; const rtl::OUString& desktop( get_desktop_environment() ); const char ** pList = pStandardFallbackList; int nListEntry = 0; // no server at all: dummy plugin if ( desktop.equalsAscii( desktop_strings[DESKTOP_NONE] ) ) pList = pHeadlessFallbackList; else if ( desktop.equalsAscii( desktop_strings[DESKTOP_GNOME] ) ) pList = pStandardFallbackList; else if( desktop.equalsAscii( desktop_strings[DESKTOP_KDE] ) ) { pList = pKDEFallbackList; nListEntry = 1; } else if( desktop.equalsAscii( desktop_strings[DESKTOP_KDE4] ) ) pList = pKDEFallbackList; SalInstance* pInst = NULL; while( pList[nListEntry] && pInst == NULL ) { rtl::OUString aTry( rtl::OUString::createFromAscii( pList[nListEntry] ) ); pInst = tryInstance( aTry ); #if OSL_DEBUG_LEVEL > 1 if( pInst ) std::fprintf( stderr, "plugin autodetection: %s\n", pList[nListEntry] ); #endif nListEntry++; } return pInst; } static SalInstance* check_headless_plugin() { int nParams = osl_getCommandArgCount(); OUString aParam; for( int i = 0; i < nParams; i++ ) { osl_getCommandArg( i, &aParam.pData ); if( aParam.equalsAscii( "-headless" ) ) return tryInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "svp" ) ) ); } return NULL; } SalInstance *CreateSalInstance() { SalInstance* pInst = NULL; static const char* pUsePlugin = getenv( "SAL_USE_VCLPLUGIN" ); if( !(pUsePlugin && *pUsePlugin) ) pInst = check_headless_plugin(); if( ! pInst && !(pUsePlugin && *pUsePlugin) ) pInst = autodetect_plugin(); // fallback to gen if( ! pInst ) pInst = tryInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "gen" ) ) ); if( ! pInst ) { std::fprintf( stderr, "no suitable windowing system found, exiting.\n" ); _exit( 1 ); } // acquire SolarMutex pInst->AcquireYieldMutex( 1 ); return pInst; } void DestroySalInstance( SalInstance *pInst ) { // release SolarMutex pInst->ReleaseYieldMutex(); delete pInst; if( pCloseModule ) osl_unloadModule( pCloseModule ); } void InitSalData() { } void DeInitSalData() { } void InitSalMain() { } void DeInitSalMain() { } void SalAbort( const XubString& rErrorText ) { if( !rErrorText.Len() ) std::fprintf( stderr, "Application Error" ); else std::fprintf( stderr, ByteString( rErrorText, gsl_getSystemTextEncoding() ).GetBuffer() ); abort(); } const OUString& SalGetDesktopEnvironment() { return get_desktop_environment(); } SalData::SalData() : m_pInstance(NULL), m_pPlugin(NULL) { } SalData::~SalData() { } <commit_msg>vcl108: #i107878# reenable accidentally lost environment variable SAL_USE_VCLPLUGIN<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 * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" #include "osl/module.h" #include "osl/process.h" #include "rtl/ustrbuf.hxx" #include "vcl/salinst.hxx" #include "saldata.hxx" #include <cstdio> #include <unistd.h> using namespace rtl; extern "C" { typedef SalInstance*(*salFactoryProc)( oslModule pModule); } static oslModule pCloseModule = NULL; enum { DESKTOP_NONE = 0, DESKTOP_UNKNOWN, DESKTOP_GNOME, DESKTOP_KDE, DESKTOP_KDE4, DESKTOP_CDE }; static const char * desktop_strings[] = { "none", "unknown", "GNOME", "KDE", "KDE4", "CDE" }; static SalInstance* tryInstance( const OUString& rModuleBase ) { SalInstance* pInst = NULL; OUStringBuffer aModName( 128 ); aModName.appendAscii( SAL_DLLPREFIX"vclplug_" ); aModName.append( rModuleBase ); aModName.appendAscii( SAL_DLLPOSTFIX ); aModName.appendAscii( SAL_DLLEXTENSION ); OUString aModule = aModName.makeStringAndClear(); oslModule aMod = osl_loadModuleRelative( reinterpret_cast< oslGenericFunction >( &tryInstance ), aModule.pData, SAL_LOADMODULE_DEFAULT ); if( aMod ) { salFactoryProc aProc = (salFactoryProc)osl_getAsciiFunctionSymbol( aMod, "create_SalInstance" ); if( aProc ) { pInst = aProc( aMod ); #if OSL_DEBUG_LEVEL > 1 std::fprintf( stderr, "sal plugin %s produced instance %p\n", OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr(), pInst ); #endif if( pInst ) { pCloseModule = aMod; /* * Recent GTK+ versions load their modules with RTLD_LOCAL, so we can * not access the 'gnome_accessibility_module_shutdown' anymore. * So make sure libgtk+ & co are still mapped into memory when * atk-bridge's atexit handler gets called. */ if( rModuleBase.equalsAscii("gtk") ) { pCloseModule = NULL; } GetSalData()->m_pPlugin = aMod; } else osl_unloadModule( aMod ); } else { #if OSL_DEBUG_LEVEL > 1 std::fprintf( stderr, "could not load symbol %s from shared object %s\n", "create_SalInstance", OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr() ); #endif osl_unloadModule( aMod ); } } #if OSL_DEBUG_LEVEL > 1 else std::fprintf( stderr, "could not load shared object %s\n", OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr() ); #endif return pInst; } static const rtl::OUString& get_desktop_environment() { static rtl::OUString aRet; if( ! aRet.getLength() ) { OUStringBuffer aModName( 128 ); aModName.appendAscii( SAL_DLLPREFIX"desktop_detector" ); aModName.appendAscii( SAL_DLLPOSTFIX ); aModName.appendAscii( SAL_DLLEXTENSION ); OUString aModule = aModName.makeStringAndClear(); oslModule aMod = osl_loadModuleRelative( reinterpret_cast< oslGenericFunction >( &tryInstance ), aModule.pData, SAL_LOADMODULE_DEFAULT ); if( aMod ) { rtl::OUString (*pSym)() = (rtl::OUString(*)()) osl_getAsciiFunctionSymbol( aMod, "get_desktop_environment" ); if( pSym ) aRet = pSym(); } osl_unloadModule( aMod ); } return aRet; } static SalInstance* autodetect_plugin() { static const char* pKDEFallbackList[] = { "kde4", "kde", "gtk", "gen", 0 }; static const char* pStandardFallbackList[] = { "gtk", "gen", 0 }; static const char* pHeadlessFallbackList[] = { "svp", 0 }; const rtl::OUString& desktop( get_desktop_environment() ); const char ** pList = pStandardFallbackList; int nListEntry = 0; // no server at all: dummy plugin if ( desktop.equalsAscii( desktop_strings[DESKTOP_NONE] ) ) pList = pHeadlessFallbackList; else if ( desktop.equalsAscii( desktop_strings[DESKTOP_GNOME] ) ) pList = pStandardFallbackList; else if( desktop.equalsAscii( desktop_strings[DESKTOP_KDE] ) ) { pList = pKDEFallbackList; nListEntry = 1; } else if( desktop.equalsAscii( desktop_strings[DESKTOP_KDE4] ) ) pList = pKDEFallbackList; SalInstance* pInst = NULL; while( pList[nListEntry] && pInst == NULL ) { rtl::OUString aTry( rtl::OUString::createFromAscii( pList[nListEntry] ) ); pInst = tryInstance( aTry ); #if OSL_DEBUG_LEVEL > 1 if( pInst ) std::fprintf( stderr, "plugin autodetection: %s\n", pList[nListEntry] ); #endif nListEntry++; } return pInst; } static SalInstance* check_headless_plugin() { int nParams = osl_getCommandArgCount(); OUString aParam; for( int i = 0; i < nParams; i++ ) { osl_getCommandArg( i, &aParam.pData ); if( aParam.equalsAscii( "-headless" ) ) return tryInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "svp" ) ) ); } return NULL; } SalInstance *CreateSalInstance() { SalInstance* pInst = NULL; static const char* pUsePlugin = getenv( "SAL_USE_VCLPLUGIN" ); if( !(pUsePlugin && *pUsePlugin) ) pInst = check_headless_plugin(); else pInst = tryInstance( OUString::createFromAscii( pUsePlugin ) ); if( ! pInst ) pInst = autodetect_plugin(); // fallback to gen if( ! pInst ) pInst = tryInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "gen" ) ) ); if( ! pInst ) { std::fprintf( stderr, "no suitable windowing system found, exiting.\n" ); _exit( 1 ); } // acquire SolarMutex pInst->AcquireYieldMutex( 1 ); return pInst; } void DestroySalInstance( SalInstance *pInst ) { // release SolarMutex pInst->ReleaseYieldMutex(); delete pInst; if( pCloseModule ) osl_unloadModule( pCloseModule ); } void InitSalData() { } void DeInitSalData() { } void InitSalMain() { } void DeInitSalMain() { } void SalAbort( const XubString& rErrorText ) { if( !rErrorText.Len() ) std::fprintf( stderr, "Application Error" ); else std::fprintf( stderr, ByteString( rErrorText, gsl_getSystemTextEncoding() ).GetBuffer() ); abort(); } const OUString& SalGetDesktopEnvironment() { return get_desktop_environment(); } SalData::SalData() : m_pInstance(NULL), m_pPlugin(NULL) { } SalData::~SalData() { } <|endoftext|>
<commit_before>//#include "timestamp.h" #include "txn.h" #include "row.h" #include "row_ts.h" #include "mem_alloc.h" #include "manager.h" #include "stdint.h" void Row_ts::init(row_t * row) { _row = row; uint64_t part_id = row->get_part_id(); wts = 0; rts = 0; min_wts = UINT64_MAX; min_rts = UINT64_MAX; min_pts = UINT64_MAX; readreq = NULL; writereq = NULL; prereq = NULL; preq_len = 0; latch = (pthread_mutex_t *) mem_allocator.alloc(sizeof(pthread_mutex_t), part_id); pthread_mutex_init( latch, NULL ); blatch = false; } TsReqEntry * Row_ts::get_req_entry() { uint64_t part_id = get_part_id(_row); return (TsReqEntry *) mem_allocator.alloc(sizeof(TsReqEntry), part_id); } void Row_ts::return_req_entry(TsReqEntry * entry) { if (entry->row != NULL) { entry->row->free_row(); mem_allocator.free(entry->row, sizeof(row_t)); } mem_allocator.free(entry, sizeof(TsReqEntry)); } void Row_ts::return_req_list(TsReqEntry * list) { TsReqEntry * req = list; TsReqEntry * prev = NULL; while (req != NULL) { prev = req; req = req->next; return_req_entry(prev); } } void Row_ts::buffer_req(TsType type, txn_man * txn, row_t * row) { TsReqEntry * req_entry = get_req_entry(); assert(req_entry != NULL); req_entry->txn = txn; req_entry->row = row; req_entry->ts = txn->get_ts(); if (type == R_REQ) { req_entry->next = readreq; readreq = req_entry; if (req_entry->ts < min_rts) min_rts = req_entry->ts; } else if (type == W_REQ) { assert(row != NULL); req_entry->next = writereq; writereq = req_entry; if (req_entry->ts < min_wts) min_wts = req_entry->ts; } else if (type == P_REQ) { preq_len ++; req_entry->next = prereq; prereq = req_entry; if (req_entry->ts < min_pts) min_pts = req_entry->ts; } } TsReqEntry * Row_ts::debuffer_req(TsType type, txn_man * txn) { return debuffer_req(type, txn, UINT64_MAX); } TsReqEntry * Row_ts::debuffer_req(TsType type, ts_t ts) { return debuffer_req(type, NULL, ts); } TsReqEntry * Row_ts::debuffer_req( TsType type, txn_man * txn, ts_t ts ) { TsReqEntry ** queue; TsReqEntry * return_queue = NULL; switch (type) { case R_REQ : queue = &readreq; break; case P_REQ : queue = &prereq; break; case W_REQ : queue = &writereq; break; default: assert(false); } TsReqEntry * req = *queue; TsReqEntry * prev_req = NULL; if (txn != NULL) { while (req != NULL && req->txn != txn) { prev_req = req; req = req->next; } assert(req != NULL); if (prev_req != NULL) prev_req->next = req->next; else { assert( req == *queue ); *queue = req->next; } preq_len --; req->next = return_queue; return_queue = req; } else { while (req != NULL) { if (req->ts <= ts) { if (prev_req == NULL) { assert(req == *queue); *queue = (*queue)->next; } else { prev_req->next = req->next; } req->next = return_queue; return_queue = req; req = (prev_req == NULL)? *queue : prev_req->next; } else { prev_req = req; req = req->next; } } } return return_queue; } ts_t Row_ts::cal_min(TsType type) { // update the min_pts TsReqEntry * queue; switch (type) { case R_REQ : queue = readreq; break; case P_REQ : queue = prereq; break; case W_REQ : queue = writereq; break; default: assert(false); } ts_t new_min_pts = UINT64_MAX; TsReqEntry * req = queue; while (req != NULL) { if (req->ts < new_min_pts) new_min_pts = req->ts; req = req->next; } return new_min_pts; } RC Row_ts::access(txn_man * txn, TsType type, row_t * row) { RC rc; ts_t ts = txn->get_ts(); if (g_central_man) glob_manager.lock_row(_row); else pthread_mutex_lock( latch ); if (type == R_REQ) { if (ts < wts) { rc = Abort; } else if (ts > min_pts) { // insert the req into the read request queue buffer_req(R_REQ, txn, NULL); txn->ts_ready = false; rc = WAIT; txn->rc = rc; } else { // return the value. txn->cur_row->copy(_row); if (rts < ts) rts = ts; rc = RCOK; } } else if (type == P_REQ) { if (ts < rts) { rc = Abort; } else { #if TS_TWR buffer_req(P_REQ, txn, NULL); rc = RCOK; #else if (ts < wts) { rc = Abort; } else { buffer_req(P_REQ, txn, NULL); rc = RCOK; } #endif } } else if (type == W_REQ) { // write requests are always accepted. rc = RCOK; #if TS_TWR // according to TWR, this write is already stale, ignore. if (ts < wts) { TsReqEntry * req = debuffer_req(P_REQ, txn); assert(req != NULL); update_buffer(); return_req_entry(req); row->free_row(); mem_allocator.free(row, sizeof(row_t)); goto final; } #else if (ts > min_pts) { buffer_req(W_REQ, txn, row); goto final; } #endif if (ts > min_rts) { buffer_req(W_REQ, txn, row); goto final; } else { // the write is output. _row->copy(row); if (wts < ts) wts = ts; // debuffer the P_REQ TsReqEntry * req = debuffer_req(P_REQ, txn); assert(req != NULL); update_buffer(); return_req_entry(req); // the "row" is freed after hard copy to "_row" row->free_row(); mem_allocator.free(row, sizeof(row_t)); } } else if (type == XP_REQ) { TsReqEntry * req = debuffer_req(P_REQ, txn); assert (req != NULL); update_buffer(); return_req_entry(req); } else assert(false); final: if (g_central_man) glob_manager.release_row(_row); else pthread_mutex_unlock( latch ); return rc; } void Row_ts::update_buffer() { while (true) { ts_t new_min_pts = cal_min(P_REQ); assert(new_min_pts >= min_pts); if (new_min_pts > min_pts) min_pts = new_min_pts; else break; // min_pts is not updated. // debuffer readreq. ready_read can be a list TsReqEntry * ready_read = debuffer_req(R_REQ, min_pts); if (ready_read == NULL) break; // for each debuffered readreq, perform read. TsReqEntry * req = ready_read; while (req != NULL) { req->txn->cur_row->copy(_row); if (rts < req->ts) rts = req->ts; // TODO: Add req->txn to work queue req->txn->ts_ready = true; txn_pool.restart_txn(req->txn->get_txn_id()); req = req->next; } // return all the req_entry back to freelist return_req_list(ready_read); // re-calculate min_rts ts_t new_min_rts = cal_min(R_REQ); if (new_min_rts > min_rts) min_rts = new_min_rts; else break; // debuffer writereq TsReqEntry * ready_write = debuffer_req(W_REQ, min_rts); if (ready_write == NULL) break; ts_t young_ts = UINT64_MAX; TsReqEntry * young_req = NULL; req = ready_write; while (req != NULL) { TsReqEntry * tmp_req = debuffer_req(P_REQ, req->txn); assert(tmp_req != NULL); return_req_entry(tmp_req); if (req->ts < young_ts) { young_ts = req->ts; young_req = req; } //else loser = req; req = req->next; } // perform write. _row->copy(young_req->row); if (wts < young_req->ts) wts = young_req->ts; return_req_list(ready_write); } } <commit_msg>Added support for TIMESTAMP<commit_after>//#include "timestamp.h" #include "txn.h" #include "row.h" #include "row_ts.h" #include "mem_alloc.h" #include "manager.h" #include "stdint.h" void Row_ts::init(row_t * row) { _row = row; uint64_t part_id = row->get_part_id(); wts = 0; rts = 0; min_wts = UINT64_MAX; min_rts = UINT64_MAX; min_pts = UINT64_MAX; readreq = NULL; writereq = NULL; prereq = NULL; preq_len = 0; latch = (pthread_mutex_t *) mem_allocator.alloc(sizeof(pthread_mutex_t), part_id); pthread_mutex_init( latch, NULL ); blatch = false; } TsReqEntry * Row_ts::get_req_entry() { uint64_t part_id = get_part_id(_row); return (TsReqEntry *) mem_allocator.alloc(sizeof(TsReqEntry), part_id); } void Row_ts::return_req_entry(TsReqEntry * entry) { if (entry->row != NULL) { entry->row->free_row(); mem_allocator.free(entry->row, sizeof(row_t)); } mem_allocator.free(entry, sizeof(TsReqEntry)); } void Row_ts::return_req_list(TsReqEntry * list) { TsReqEntry * req = list; TsReqEntry * prev = NULL; while (req != NULL) { prev = req; req = req->next; return_req_entry(prev); } } void Row_ts::buffer_req(TsType type, txn_man * txn, row_t * row) { TsReqEntry * req_entry = get_req_entry(); assert(req_entry != NULL); req_entry->txn = txn; req_entry->row = row; req_entry->ts = txn->get_ts(); if (type == R_REQ) { req_entry->next = readreq; readreq = req_entry; if (req_entry->ts < min_rts) min_rts = req_entry->ts; } else if (type == W_REQ) { assert(row != NULL); req_entry->next = writereq; writereq = req_entry; if (req_entry->ts < min_wts) min_wts = req_entry->ts; } else if (type == P_REQ) { preq_len ++; req_entry->next = prereq; prereq = req_entry; if (req_entry->ts < min_pts) min_pts = req_entry->ts; } } TsReqEntry * Row_ts::debuffer_req(TsType type, txn_man * txn) { return debuffer_req(type, txn, UINT64_MAX); } TsReqEntry * Row_ts::debuffer_req(TsType type, ts_t ts) { return debuffer_req(type, NULL, ts); } TsReqEntry * Row_ts::debuffer_req( TsType type, txn_man * txn, ts_t ts ) { TsReqEntry ** queue; TsReqEntry * return_queue = NULL; switch (type) { case R_REQ : queue = &readreq; break; case P_REQ : queue = &prereq; break; case W_REQ : queue = &writereq; break; default: assert(false); } TsReqEntry * req = *queue; TsReqEntry * prev_req = NULL; if (txn != NULL) { while (req != NULL && req->txn != txn) { prev_req = req; req = req->next; } assert(req != NULL); if (prev_req != NULL) prev_req->next = req->next; else { assert( req == *queue ); *queue = req->next; } preq_len --; req->next = return_queue; return_queue = req; } else { while (req != NULL) { if (req->ts <= ts) { if (prev_req == NULL) { assert(req == *queue); *queue = (*queue)->next; } else { prev_req->next = req->next; } req->next = return_queue; return_queue = req; req = (prev_req == NULL)? *queue : prev_req->next; } else { prev_req = req; req = req->next; } } } return return_queue; } ts_t Row_ts::cal_min(TsType type) { // update the min_pts TsReqEntry * queue; switch (type) { case R_REQ : queue = readreq; break; case P_REQ : queue = prereq; break; case W_REQ : queue = writereq; break; default: assert(false); } ts_t new_min_pts = UINT64_MAX; TsReqEntry * req = queue; while (req != NULL) { if (req->ts < new_min_pts) new_min_pts = req->ts; req = req->next; } return new_min_pts; } RC Row_ts::access(txn_man * txn, TsType type, row_t * row) { RC rc; ts_t ts = txn->get_ts(); if (g_central_man) glob_manager.lock_row(_row); else pthread_mutex_lock( latch ); if (type == R_REQ) { if (ts < wts) { rc = Abort; } else if (ts > min_pts) { // insert the req into the read request queue buffer_req(R_REQ, txn, NULL); txn->ts_ready = false; rc = WAIT; txn->rc = rc; } else { // return the value. txn->cur_row->copy(_row); if (rts < ts) rts = ts; rc = RCOK; } } else if (type == P_REQ) { if (ts < rts) { rc = Abort; } else { #if TS_TWR buffer_req(P_REQ, txn, NULL); rc = RCOK; #else if (ts < wts) { rc = Abort; } else { buffer_req(P_REQ, txn, NULL); rc = RCOK; } #endif } } else if (type == W_REQ) { // write requests are always accepted. rc = RCOK; #if TS_TWR // according to TWR, this write is already stale, ignore. if (ts < wts) { TsReqEntry * req = debuffer_req(P_REQ, txn); assert(req != NULL); update_buffer(); return_req_entry(req); row->free_row(); mem_allocator.free(row, sizeof(row_t)); goto final; } #else if (ts > min_pts) { buffer_req(W_REQ, txn, row); goto final; } #endif if (ts > min_rts) { row = txn->cur_row; buffer_req(W_REQ, txn, row); goto final; } else { // the write is output. _row->copy(row); if (wts < ts) wts = ts; // debuffer the P_REQ TsReqEntry * req = debuffer_req(P_REQ, txn); assert(req != NULL); update_buffer(); return_req_entry(req); // the "row" is freed after hard copy to "_row" row->free_row(); mem_allocator.free(row, sizeof(row_t)); } } else if (type == XP_REQ) { TsReqEntry * req = debuffer_req(P_REQ, txn); assert (req != NULL); update_buffer(); return_req_entry(req); } else assert(false); final: if (g_central_man) glob_manager.release_row(_row); else pthread_mutex_unlock( latch ); return rc; } void Row_ts::update_buffer() { while (true) { ts_t new_min_pts = cal_min(P_REQ); assert(new_min_pts >= min_pts); if (new_min_pts > min_pts) min_pts = new_min_pts; else break; // min_pts is not updated. // debuffer readreq. ready_read can be a list TsReqEntry * ready_read = debuffer_req(R_REQ, min_pts); if (ready_read == NULL) break; // for each debuffered readreq, perform read. TsReqEntry * req = ready_read; while (req != NULL) { req->txn->cur_row->copy(_row); if (rts < req->ts) rts = req->ts; // TODO: Add req->txn to work queue req->txn->ts_ready = true; txn_pool.restart_txn(req->txn->get_txn_id()); req = req->next; } // return all the req_entry back to freelist return_req_list(ready_read); // re-calculate min_rts ts_t new_min_rts = cal_min(R_REQ); if (new_min_rts > min_rts) min_rts = new_min_rts; else break; // debuffer writereq TsReqEntry * ready_write = debuffer_req(W_REQ, min_rts); if (ready_write == NULL) break; ts_t young_ts = UINT64_MAX; TsReqEntry * young_req = NULL; req = ready_write; while (req != NULL) { TsReqEntry * tmp_req = debuffer_req(P_REQ, req->txn); assert(tmp_req != NULL); return_req_entry(tmp_req); if (req->ts < young_ts) { young_ts = req->ts; young_req = req; } //else loser = req; req = req->next; } // perform write. _row->copy(young_req->row); if (wts < young_req->ts) wts = young_req->ts; return_req_list(ready_write); } } <|endoftext|>
<commit_before>#include <osgParticle/ParticleEffect> #include <osg/io_utils> #include <osgDB/Registry> #include <osgDB/Input> #include <osgDB/Output> #include <osg/Notify> bool ParticleEffect_readLocalData(osg::Object &obj, osgDB::Input &fr); bool ParticleEffect_writeLocalData(const osg::Object &obj, osgDB::Output &fw); osgDB::RegisterDotOsgWrapperProxy ParticleEffect_Proxy ( 0, "ParticleEffect", "Object Node ParticleEffect", ParticleEffect_readLocalData, ParticleEffect_writeLocalData ); bool ParticleEffect_readLocalData(osg::Object& object, osgDB::Input& fr) { osgParticle::ParticleEffect& effect = static_cast<osgParticle::ParticleEffect&>(object); bool itrAdvanced = false; if (fr.matchSequence("position %s")) { effect.setTextureFileName(fr[1].getStr()); fr += 2; itrAdvanced = true; } if (fr.matchSequence("position %f %f %f")) { osg::Vec3 position; fr[1].getFloat(position[0]); fr[2].getFloat(position[1]); fr[3].getFloat(position[2]); effect.setPosition(position); fr += 4; itrAdvanced = true; } if (fr.matchSequence("scale %f")) { float scale; fr[1].getFloat(scale); effect.setScale(scale); fr += 2; itrAdvanced = true; } if (fr.matchSequence("intensity %f")) { float intensity; fr[1].getFloat(intensity); effect.setIntensity(intensity); fr += 2; itrAdvanced = true; } if (fr.matchSequence("startTime %f")) { float startTime; fr[1].getFloat(startTime); effect.setStartTime(startTime); fr += 2; itrAdvanced = true; } if (fr.matchSequence("emitterDuration %f")) { float emitterDuration; fr[1].getFloat(emitterDuration); effect.setEmitterDuration(emitterDuration); fr += 2; itrAdvanced = true; } osgParticle::Particle particle = effect.getDefaultParticleTemplate(); bool particleSet = false; if (fr.matchSequence("particleDuration %f")) { float particleDuration; fr[1].getFloat(particleDuration); particle.setLifeTime(particleDuration); particleSet = true; fr += 2; itrAdvanced = true; } if (fr[0].matchWord("particleSizeRange")) { osgParticle::rangef r; if (fr[1].getFloat(r.minimum) && fr[2].getFloat(r.maximum)) { particle.setSizeRange(r); particleSet = true; fr += 3; itrAdvanced = true; } } if (fr[0].matchWord("particleAlphaRange")) { osgParticle::rangef r; if (fr[1].getFloat(r.minimum) && fr[2].getFloat(r.maximum)) { particle.setAlphaRange(r); particleSet = true; fr += 3; itrAdvanced = true; } } if (fr[0].matchWord("particleColorRange")) { osgParticle::rangev4 r; if (fr[1].getFloat(r.minimum.x()) && fr[2].getFloat(r.minimum.y()) && fr[3].getFloat(r.minimum.z()) && fr[4].getFloat(r.minimum.w()) && fr[5].getFloat(r.maximum.x()) && fr[6].getFloat(r.maximum.y()) && fr[7].getFloat(r.maximum.z()) && fr[8].getFloat(r.maximum.w())) { particle.setColorRange(r); particleSet = true; fr += 9; itrAdvanced = true; } } if (particleSet) { effect.setDefaultParticleTemplate(particle); } if (fr.matchSequence("wind %f %f %f")) { osg::Vec3 wind; fr[1].getFloat(wind[0]); fr[2].getFloat(wind[1]); fr[3].getFloat(wind[2]); effect.setWind(wind); fr += 4; itrAdvanced = true; } if (fr[0].matchWord("useLocalParticleSystem")) { if (fr[1].matchWord("FALSE")) { effect.setUseLocalParticleSystem(false); fr+=2; itrAdvanced = true; // now read the particle system that is shared with an node external to this particle effect osg::ref_ptr<osg::Object> readObject = fr.readObjectOfType(osgDB::type_wrapper<osgParticle::ParticleSystem>()); if (readObject.valid()) { osgParticle::ParticleSystem* ps = static_cast<osgParticle::ParticleSystem*>(readObject.get()); effect.setParticleSystem(ps); itrAdvanced = true; } } else if (fr[1].matchWord("TRUE")) { effect.setUseLocalParticleSystem(true); fr+=2; itrAdvanced = true; } } if (!effect.getAutomaticSetup()) { // since by default the clone of the ParticleEffect is done with automatic setup off to prevent premature loading of // imagery, we still want to make sure the ParticleEffect is properly built so we'll now mannually enable the automatic setup // run the buildEffect(). effect.setAutomaticSetup(true); effect.buildEffect(); } return itrAdvanced; } bool ParticleEffect_writeLocalData(const osg::Object& object, osgDB::Output& fw) { const osgParticle::ParticleEffect& effect = static_cast<const osgParticle::ParticleEffect&>(object); fw.indent()<<"textFileName "<<effect.getTextureFileName()<<std::endl; fw.indent()<<"position "<<effect.getPosition()<<std::endl; fw.indent()<<"scale "<<effect.getScale()<<std::endl; fw.indent()<<"intensity "<<effect.getIntensity()<<std::endl; fw.indent()<<"startTime "<<effect.getStartTime()<<std::endl; fw.indent()<<"emitterDuration "<<effect.getEmitterDuration()<<std::endl; fw.indent()<<"particleDuration "<<effect.getParticleDuration()<<std::endl; osgParticle::rangef rf = effect.getDefaultParticleTemplate().getSizeRange(); fw.indent() << "particleSizeRange " << rf.minimum << " " << rf.maximum << std::endl; rf = effect.getDefaultParticleTemplate().getAlphaRange(); fw.indent() << "particleAlphaRange " << rf.minimum << " " << rf.maximum << std::endl; osgParticle::rangev4 rv4 = effect.getDefaultParticleTemplate().getColorRange(); fw.indent() << "particleColorRange "; fw << rv4.minimum.x() << " " << rv4.minimum.y() << " " << rv4.minimum.z() << " " << rv4.minimum.w() << " "; fw << rv4.maximum.x() << " " << rv4.maximum.y() << " " << rv4.maximum.z() << " " << rv4.maximum.w() << std::endl; fw.indent()<<"wind "<<effect.getWind()<<std::endl; fw.indent()<<"useLocalParticleSystem "; if (effect.getUseLocalParticleSystem()) fw<<"TRUE"<<std::endl; else { fw<<"FALSE"<<std::endl; fw.writeObject(*effect.getParticleSystem()); } return true; } <commit_msg>From Lionel Lagarde, "this correct how the ParticleEffect are serialized : - the texture file name is taken from the TextFileName field - the texture file name is written using writeString "<commit_after>#include <osgParticle/ParticleEffect> #include <osg/io_utils> #include <osgDB/Registry> #include <osgDB/Input> #include <osgDB/Output> #include <osg/Notify> bool ParticleEffect_readLocalData(osg::Object &obj, osgDB::Input &fr); bool ParticleEffect_writeLocalData(const osg::Object &obj, osgDB::Output &fw); osgDB::RegisterDotOsgWrapperProxy ParticleEffect_Proxy ( 0, "ParticleEffect", "Object Node ParticleEffect", ParticleEffect_readLocalData, ParticleEffect_writeLocalData ); bool ParticleEffect_readLocalData(osg::Object& object, osgDB::Input& fr) { osgParticle::ParticleEffect& effect = static_cast<osgParticle::ParticleEffect&>(object); bool itrAdvanced = false; if (fr.matchSequence("textFileName %s")) { effect.setTextureFileName(fr[1].getStr()); fr += 2; itrAdvanced = true; } if (fr.matchSequence("position %f %f %f")) { osg::Vec3 position; fr[1].getFloat(position[0]); fr[2].getFloat(position[1]); fr[3].getFloat(position[2]); effect.setPosition(position); fr += 4; itrAdvanced = true; } if (fr.matchSequence("scale %f")) { float scale; fr[1].getFloat(scale); effect.setScale(scale); fr += 2; itrAdvanced = true; } if (fr.matchSequence("intensity %f")) { float intensity; fr[1].getFloat(intensity); effect.setIntensity(intensity); fr += 2; itrAdvanced = true; } if (fr.matchSequence("startTime %f")) { float startTime; fr[1].getFloat(startTime); effect.setStartTime(startTime); fr += 2; itrAdvanced = true; } if (fr.matchSequence("emitterDuration %f")) { float emitterDuration; fr[1].getFloat(emitterDuration); effect.setEmitterDuration(emitterDuration); fr += 2; itrAdvanced = true; } osgParticle::Particle particle = effect.getDefaultParticleTemplate(); bool particleSet = false; if (fr.matchSequence("particleDuration %f")) { float particleDuration; fr[1].getFloat(particleDuration); particle.setLifeTime(particleDuration); particleSet = true; fr += 2; itrAdvanced = true; } if (fr[0].matchWord("particleSizeRange")) { osgParticle::rangef r; if (fr[1].getFloat(r.minimum) && fr[2].getFloat(r.maximum)) { particle.setSizeRange(r); particleSet = true; fr += 3; itrAdvanced = true; } } if (fr[0].matchWord("particleAlphaRange")) { osgParticle::rangef r; if (fr[1].getFloat(r.minimum) && fr[2].getFloat(r.maximum)) { particle.setAlphaRange(r); particleSet = true; fr += 3; itrAdvanced = true; } } if (fr[0].matchWord("particleColorRange")) { osgParticle::rangev4 r; if (fr[1].getFloat(r.minimum.x()) && fr[2].getFloat(r.minimum.y()) && fr[3].getFloat(r.minimum.z()) && fr[4].getFloat(r.minimum.w()) && fr[5].getFloat(r.maximum.x()) && fr[6].getFloat(r.maximum.y()) && fr[7].getFloat(r.maximum.z()) && fr[8].getFloat(r.maximum.w())) { particle.setColorRange(r); particleSet = true; fr += 9; itrAdvanced = true; } } if (particleSet) { effect.setDefaultParticleTemplate(particle); } if (fr.matchSequence("wind %f %f %f")) { osg::Vec3 wind; fr[1].getFloat(wind[0]); fr[2].getFloat(wind[1]); fr[3].getFloat(wind[2]); effect.setWind(wind); fr += 4; itrAdvanced = true; } if (fr[0].matchWord("useLocalParticleSystem")) { if (fr[1].matchWord("FALSE")) { effect.setUseLocalParticleSystem(false); fr+=2; itrAdvanced = true; // now read the particle system that is shared with an node external to this particle effect osg::ref_ptr<osg::Object> readObject = fr.readObjectOfType(osgDB::type_wrapper<osgParticle::ParticleSystem>()); if (readObject.valid()) { osgParticle::ParticleSystem* ps = static_cast<osgParticle::ParticleSystem*>(readObject.get()); effect.setParticleSystem(ps); itrAdvanced = true; } } else if (fr[1].matchWord("TRUE")) { effect.setUseLocalParticleSystem(true); fr+=2; itrAdvanced = true; } } if (!effect.getAutomaticSetup()) { // since by default the clone of the ParticleEffect is done with automatic setup off to prevent premature loading of // imagery, we still want to make sure the ParticleEffect is properly built so we'll now mannually enable the automatic setup // run the buildEffect(). effect.setAutomaticSetup(true); effect.buildEffect(); } return itrAdvanced; } bool ParticleEffect_writeLocalData(const osg::Object& object, osgDB::Output& fw) { const osgParticle::ParticleEffect& effect = static_cast<const osgParticle::ParticleEffect&>(object); fw.indent()<<"textFileName "<<fw.wrapString(effect.getTextureFileName())<<std::endl; fw.indent()<<"position "<<effect.getPosition()<<std::endl; fw.indent()<<"scale "<<effect.getScale()<<std::endl; fw.indent()<<"intensity "<<effect.getIntensity()<<std::endl; fw.indent()<<"startTime "<<effect.getStartTime()<<std::endl; fw.indent()<<"emitterDuration "<<effect.getEmitterDuration()<<std::endl; fw.indent()<<"particleDuration "<<effect.getParticleDuration()<<std::endl; osgParticle::rangef rf = effect.getDefaultParticleTemplate().getSizeRange(); fw.indent() << "particleSizeRange " << rf.minimum << " " << rf.maximum << std::endl; rf = effect.getDefaultParticleTemplate().getAlphaRange(); fw.indent() << "particleAlphaRange " << rf.minimum << " " << rf.maximum << std::endl; osgParticle::rangev4 rv4 = effect.getDefaultParticleTemplate().getColorRange(); fw.indent() << "particleColorRange "; fw << rv4.minimum.x() << " " << rv4.minimum.y() << " " << rv4.minimum.z() << " " << rv4.minimum.w() << " "; fw << rv4.maximum.x() << " " << rv4.maximum.y() << " " << rv4.maximum.z() << " " << rv4.maximum.w() << std::endl; fw.indent()<<"wind "<<effect.getWind()<<std::endl; fw.indent()<<"useLocalParticleSystem "; if (effect.getUseLocalParticleSystem()) fw<<"TRUE"<<std::endl; else { fw<<"FALSE"<<std::endl; fw.writeObject(*effect.getParticleSystem()); } return true; } <|endoftext|>
<commit_before>/* [xad] HYBRID player, by Riven the Mage <riven@ok.ru> */ /* - discovery - file(s) : HYBRID.EXE type : Hybrid cracktro for Apache Longbow CD-RIP tune : from 'Mig-29 Fulcrum' game by Domark player : from 'Mig-29 Fulcrum' game by Domark */ #include "hybrid.h" #include "debug.h" unsigned char hyb_adlib_registers[99] = { 0xE0, 0x60, 0x80, 0x20, 0x40, 0xE3, 0x63, 0x83, 0x23, 0x43, 0xC0, 0xE1, 0x61, 0x81, 0x21, 0x41, 0xE4, 0x64, 0x84, 0x24, 0x44, 0xC1, 0xE2, 0x62, 0x82, 0x22, 0x42, 0xE5, 0x65, 0x85, 0x25, 0x45, 0xC2, 0xE8, 0x68, 0x88, 0x28, 0x48, 0xEB, 0x6B, 0x8B, 0x2B, 0x4B, 0xC3, 0xE9, 0x69, 0x89, 0x29, 0x49, 0xEC, 0x6C, 0x8C, 0x2C, 0x4C, 0xC4, 0xEA, 0x6A, 0x8A, 0x2A, 0x4A, 0xED, 0x6D, 0x8D, 0x2D, 0x4D, 0xC5, 0xF0, 0x70, 0x90, 0x30, 0x50, 0xF3, 0x73, 0x93, 0x33, 0x53, 0xC6, 0xF1, 0x71, 0x91, 0x31, 0x51, 0xF4, 0x74, 0x94, 0x34, 0x54, 0xC7, 0xF2, 0x72, 0x92, 0x32, 0x52, 0xF5, 0x75, 0x95, 0x35, 0x55, 0xC8 }; unsigned short hyb_notes[98] = { 0x0000, 0x0000, 0x016B, 0x0181, 0x0198, 0x01B0, 0x01CA, 0x01E5, 0x0202, 0x0220, 0x0241, 0x0263, 0x0287, 0x02AE, 0x056B, 0x0581, 0x0598, 0x05B0, 0x05CA, 0x05E5, 0x0602, 0x0620, 0x0641, 0x0663, 0x0687, 0x06AE, 0x096B, 0x0981, 0x0998, 0x09B0, 0x09CA, 0x09E5, 0x0A02, 0x0A20, 0x0A41, 0x0A63, 0x0A87, 0x0AAE, 0x0D6B, 0x0D81, 0x0D98, 0x0DB0, 0x0DCA, 0x0DE5, 0x0E02, 0x0E20, 0x0E41, 0x0E63, 0x0E87, 0x0EAE, 0x116B, 0x1181, 0x1198, 0x11B0, 0x11CA, 0x11E5, 0x1202, 0x1220, 0x1241, 0x1263, 0x1287, 0x12AE, 0x156B, 0x1581, 0x1598, 0x15B0, 0x15CA, 0x15E5, 0x1602, 0x1620, 0x1641, 0x1663, 0x1687, 0x16AE, 0x196B, 0x1981, 0x1998, 0x19B0, 0x19CA, 0x19E5, 0x1A02, 0x1A20, 0x1A41, 0x1A63, 0x1A87, 0x1AAE, 0x1D6B, 0x1D81, 0x1D98, 0x1DB0, 0x1DCA, 0x1DE5, 0x1E02, 0x1E20, 0x1E41, 0x1E63, 0x1E87, 0x1EAE }; unsigned char hyb_default_instrument[11] = { 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00 }; CPlayer *CxadhybridPlayer::factory(Copl *newopl) { CxadhybridPlayer *p = new CxadhybridPlayer(newopl); return p; } bool CxadhybridPlayer::xadplayer_load(istream &f) { if(xad.fmt != HYBRID) return false; // load instruments hyb.inst = (hyb_instrument *)&tune[0]; // load order hyb.order = &tune[0x1D4]; return true; } void CxadhybridPlayer::xadplayer_rewind(unsigned int subsong) { int i; hyb.order_pos = 0; hyb.pattern_pos = 0; hyb.speed = 6; hyb.speed_counter = 1; plr.speed = 1; // init channel data for(i=0;i<9;i++) { hyb.channel[i].freq = 0x2000; hyb.channel[i].freq_slide = 0x0000; } // basic OPL init opl_write(0x01, 0x20); opl_write(0xBD, 0x40); opl_write(0x08, 0x00); // init OPL channels for(i=0;i<9;i++) { for(int j=0;j<11;j++) opl_write(hyb_adlib_registers[i*11+j], 0x00 /* hyb_default_instrument[j] */ ); opl_write(0xA0+i, 0x00); opl_write(0xB0+i, 0x20); } } void CxadhybridPlayer::xadplayer_update() { int i,j; unsigned char patpos,ordpos; if (--hyb.speed_counter) goto update_slides; hyb.speed_counter = hyb.speed; patpos = hyb.pattern_pos; ordpos = hyb.order_pos; // process channels for(i=0;i<9;i++) { // read event unsigned short event = *(unsigned short *)&tune[0xADE + (hyb.order[hyb.order_pos*9 + i] * 64 * 2) + (patpos * 2)]; #ifdef DEBUG AdPlug_LogWrite("track %02X, channel %02X, event %04X:\n", hyb.order[hyb.order_pos*9 + i], i, event ); #endif // calculate variables unsigned char note = event >> 9; unsigned char ins = ((event & 0x01F0) >> 4); unsigned char slide = event & 0x000F; // play event switch(note) { case 0x7D: // 0x7D: Set Speed hyb.speed = event & 0xFF; break; case 0x7E: // 0x7E: Jump Position hyb.order_pos = event & 0xFF; hyb.pattern_pos = 0x3F; // jumpback ? if (hyb.order_pos <= ordpos) plr.looping = 1; break; case 0x7F: // 0x7F: Pattern Break hyb.pattern_pos = 0x3F; break; default: // is instrument ? if (ins) for(j=0;j<11;j++) opl_write(hyb_adlib_registers[i*11+j], *((unsigned char *)&hyb.inst[ins-1] + 7 + j)); // +7 = skip name... // is note ? if (note) { hyb.channel[i].freq = hyb_notes[note]; hyb.channel[i].freq_slide = 0; } // is slide ? if (slide) { hyb.channel[i].freq_slide = (((slide >> 3) * -1) * (slide & 7)) << 1; if (slide & 0x80) slide = -(slide & 7); } // set frequency if (!(hyb.channel[i].freq & 0x2000)) { opl_write(0xA0+i, hyb.channel[i].freq & 0xFF); opl_write(0xB0+i, hyb.channel[i].freq >> 8); hyb.channel[i].freq |= 0x2000; opl_write(0xA0+i, hyb.channel[i].freq & 0xFF); opl_write(0xB0+i, hyb.channel[i].freq >> 8); } break; } } hyb.pattern_pos++; // end of pattern ? if (hyb.pattern_pos >= 0x40) { hyb.pattern_pos = 0; hyb.order_pos++; } update_slides: #ifdef DEBUG AdPlug_LogWrite("slides:\n"); #endif // update fine frequency slides for(i=0;i<9;i++) if (hyb.channel[i].freq_slide) { hyb.channel[i].freq = (((hyb.channel[i].freq & 0x1FFF) + hyb.channel[i].freq_slide) & 0x1FFF) | 0x2000; opl_write(0xA0+i, hyb.channel[i].freq & 0xFF); opl_write(0xB0+i, hyb.channel[i].freq >> 8); } } float CxadhybridPlayer::xadplayer_getrefresh() { return 50.0f; } std::string CxadhybridPlayer::xadplayer_gettype() { return (std::string("xad: hybrid player")); } std::string CxadhybridPlayer::xadplayer_getinstrument(unsigned int i) { return (std::string(hyb.inst[i].name,7)); } unsigned int CxadhybridPlayer::xadplayer_getinstruments() { return 26; } <commit_msg>nothing important :)<commit_after>/* [xad] HYBRID player, by Riven the Mage <riven@ok.ru> */ /* - discovery - file(s) : HYBRID.EXE type : Hybrid cracktro for Apache Longbow CD-RIP tune : from 'Mig-29 Super Fulcrum' game by Domark player : from 'Mig-29 Super Fulcrum' game by Domark */ #include "hybrid.h" #include "debug.h" unsigned char hyb_adlib_registers[99] = { 0xE0, 0x60, 0x80, 0x20, 0x40, 0xE3, 0x63, 0x83, 0x23, 0x43, 0xC0, 0xE1, 0x61, 0x81, 0x21, 0x41, 0xE4, 0x64, 0x84, 0x24, 0x44, 0xC1, 0xE2, 0x62, 0x82, 0x22, 0x42, 0xE5, 0x65, 0x85, 0x25, 0x45, 0xC2, 0xE8, 0x68, 0x88, 0x28, 0x48, 0xEB, 0x6B, 0x8B, 0x2B, 0x4B, 0xC3, 0xE9, 0x69, 0x89, 0x29, 0x49, 0xEC, 0x6C, 0x8C, 0x2C, 0x4C, 0xC4, 0xEA, 0x6A, 0x8A, 0x2A, 0x4A, 0xED, 0x6D, 0x8D, 0x2D, 0x4D, 0xC5, 0xF0, 0x70, 0x90, 0x30, 0x50, 0xF3, 0x73, 0x93, 0x33, 0x53, 0xC6, 0xF1, 0x71, 0x91, 0x31, 0x51, 0xF4, 0x74, 0x94, 0x34, 0x54, 0xC7, 0xF2, 0x72, 0x92, 0x32, 0x52, 0xF5, 0x75, 0x95, 0x35, 0x55, 0xC8 }; unsigned short hyb_notes[98] = { 0x0000, 0x0000, 0x016B, 0x0181, 0x0198, 0x01B0, 0x01CA, 0x01E5, 0x0202, 0x0220, 0x0241, 0x0263, 0x0287, 0x02AE, 0x056B, 0x0581, 0x0598, 0x05B0, 0x05CA, 0x05E5, 0x0602, 0x0620, 0x0641, 0x0663, 0x0687, 0x06AE, 0x096B, 0x0981, 0x0998, 0x09B0, 0x09CA, 0x09E5, 0x0A02, 0x0A20, 0x0A41, 0x0A63, 0x0A87, 0x0AAE, 0x0D6B, 0x0D81, 0x0D98, 0x0DB0, 0x0DCA, 0x0DE5, 0x0E02, 0x0E20, 0x0E41, 0x0E63, 0x0E87, 0x0EAE, 0x116B, 0x1181, 0x1198, 0x11B0, 0x11CA, 0x11E5, 0x1202, 0x1220, 0x1241, 0x1263, 0x1287, 0x12AE, 0x156B, 0x1581, 0x1598, 0x15B0, 0x15CA, 0x15E5, 0x1602, 0x1620, 0x1641, 0x1663, 0x1687, 0x16AE, 0x196B, 0x1981, 0x1998, 0x19B0, 0x19CA, 0x19E5, 0x1A02, 0x1A20, 0x1A41, 0x1A63, 0x1A87, 0x1AAE, 0x1D6B, 0x1D81, 0x1D98, 0x1DB0, 0x1DCA, 0x1DE5, 0x1E02, 0x1E20, 0x1E41, 0x1E63, 0x1E87, 0x1EAE }; unsigned char hyb_default_instrument[11] = { 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00 }; CPlayer *CxadhybridPlayer::factory(Copl *newopl) { CxadhybridPlayer *p = new CxadhybridPlayer(newopl); return p; } bool CxadhybridPlayer::xadplayer_load(istream &f) { if(xad.fmt != HYBRID) return false; // load instruments hyb.inst = (hyb_instrument *)&tune[0]; // load order hyb.order = &tune[0x1D4]; return true; } void CxadhybridPlayer::xadplayer_rewind(unsigned int subsong) { int i; hyb.order_pos = 0; hyb.pattern_pos = 0; hyb.speed = 6; hyb.speed_counter = 1; plr.speed = 1; // init channel data for(i=0;i<9;i++) { hyb.channel[i].freq = 0x2000; hyb.channel[i].freq_slide = 0x0000; } // basic OPL init opl_write(0x01, 0x20); opl_write(0xBD, 0x40); opl_write(0x08, 0x00); // init OPL channels for(i=0;i<9;i++) { for(int j=0;j<11;j++) opl_write(hyb_adlib_registers[i*11+j], 0x00 /* hyb_default_instrument[j] */ ); opl_write(0xA0+i, 0x00); opl_write(0xB0+i, 0x20); } } void CxadhybridPlayer::xadplayer_update() { int i,j; unsigned char patpos,ordpos; if (--hyb.speed_counter) goto update_slides; hyb.speed_counter = hyb.speed; patpos = hyb.pattern_pos; ordpos = hyb.order_pos; // process channels for(i=0;i<9;i++) { // read event unsigned short event = *(unsigned short *)&tune[0xADE + (hyb.order[hyb.order_pos*9 + i] * 64 * 2) + (patpos * 2)]; #ifdef DEBUG AdPlug_LogWrite("track %02X, channel %02X, event %04X:\n", hyb.order[hyb.order_pos*9 + i], i, event ); #endif // calculate variables unsigned char note = event >> 9; unsigned char ins = ((event & 0x01F0) >> 4); unsigned char slide = event & 0x000F; // play event switch(note) { case 0x7D: // 0x7D: Set Speed hyb.speed = event & 0xFF; break; case 0x7E: // 0x7E: Jump Position hyb.order_pos = event & 0xFF; hyb.pattern_pos = 0x3F; // jumpback ? if (hyb.order_pos <= ordpos) plr.looping = 1; break; case 0x7F: // 0x7F: Pattern Break hyb.pattern_pos = 0x3F; break; default: // is instrument ? if (ins) for(j=0;j<11;j++) opl_write(hyb_adlib_registers[i*11+j], *((unsigned char *)&hyb.inst[ins-1] + 7 + j)); // +7 = skip name... // is note ? if (note) { hyb.channel[i].freq = hyb_notes[note]; hyb.channel[i].freq_slide = 0; } // is slide ? if (slide) { hyb.channel[i].freq_slide = (((slide >> 3) * -1) * (slide & 7)) << 1; if (slide & 0x80) slide = -(slide & 7); } // set frequency if (!(hyb.channel[i].freq & 0x2000)) { opl_write(0xA0+i, hyb.channel[i].freq & 0xFF); opl_write(0xB0+i, hyb.channel[i].freq >> 8); hyb.channel[i].freq |= 0x2000; opl_write(0xA0+i, hyb.channel[i].freq & 0xFF); opl_write(0xB0+i, hyb.channel[i].freq >> 8); } break; } } hyb.pattern_pos++; // end of pattern ? if (hyb.pattern_pos >= 0x40) { hyb.pattern_pos = 0; hyb.order_pos++; } update_slides: #ifdef DEBUG AdPlug_LogWrite("slides:\n"); #endif // update fine frequency slides for(i=0;i<9;i++) if (hyb.channel[i].freq_slide) { hyb.channel[i].freq = (((hyb.channel[i].freq & 0x1FFF) + hyb.channel[i].freq_slide) & 0x1FFF) | 0x2000; opl_write(0xA0+i, hyb.channel[i].freq & 0xFF); opl_write(0xB0+i, hyb.channel[i].freq >> 8); } } float CxadhybridPlayer::xadplayer_getrefresh() { return 50.0f; } std::string CxadhybridPlayer::xadplayer_gettype() { return (std::string("xad: hybrid player")); } std::string CxadhybridPlayer::xadplayer_getinstrument(unsigned int i) { return (std::string(hyb.inst[i].name,7)); } unsigned int CxadhybridPlayer::xadplayer_getinstruments() { return 26; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Library Module: SbrText.hh Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ // .NAME vlKSbrTexture - starbase texture map object // .SECTION Description // vlSbrTexture is a concrete implementation of the abstract class vlTexture. // currently we don't support texture mapping on starbase. #ifndef __vlSbrTexture_hh #define __vlSbrTexture_hh #include "Texture.hh" class vlSbrRenderer; class vlSbrTexture : public vlTexture { public: vlSbrTexture(); char *GetClassName() {return "vlSbrTexture";}; void Load(vlRenderer *ren); void Load(vlSbrRenderer *ren); protected: vlTimeStamp LoadTime; long Index; static long GlobalIndex; }; #endif <commit_msg>new arch device stuff<commit_after>/*========================================================================= Program: Visualization Library Module: SbrText.hh Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ // .NAME vlKSbrTexture - starbase texture map object // .SECTION Description // vlSbrTexture is a concrete implementation of the abstract class vlTexture. // currently we don't support texture mapping on starbase. #ifndef __vlSbrTexture_hh #define __vlSbrTexture_hh #include "Texture.hh" class vlSbrRenderer; class vlSbrTexture : public vlTexture { public: vlSbrTexture(); char *GetClassName() {return "vlSbrTexture";}; void Load(vlTexture *txt, vlRenderer *ren); void Load(vlTexture *txt, vlSbrRenderer *ren); protected: vlTimeStamp LoadTime; long Index; static long GlobalIndex; }; #endif <|endoftext|>
<commit_before>// Copyright (C) 2007-2013 CEA/DEN, EDF R&D, OPEN CASCADE // // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License. // // 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 // // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com // #ifdef WNT #pragma warning( disable:4786 ) #endif #include <Standard_Stream.hxx> #include "GEOM_Gen_i.hh" #include <TCollection_AsciiString.hxx> #include <TCollection_ExtendedString.hxx> #include <TColStd_HSequenceOfAsciiString.hxx> #include <Resource_DataMapOfAsciiStringAsciiString.hxx> #include <vector> #include <string> //======================================================================= //function : RemoveTabulation //purpose : //======================================================================= void RemoveTabulation( TCollection_AsciiString& theScript ) { std::string aString( theScript.ToCString() ); std::string::size_type aPos = 0; while( aPos < aString.length() ) { aPos = aString.find( "\n\t", aPos ); if( aPos == std::string::npos ) break; aString.replace( aPos, 2, "\n" ); aPos++; } theScript = aString.c_str(); } //======================================================================= //function : DumpPython //purpose : //======================================================================= Engines::TMPFile* GEOM_Gen_i::DumpPython(CORBA::Object_ptr theStudy, CORBA::Boolean isPublished, CORBA::Boolean isMultiFile, CORBA::Boolean& isValidScript) { SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy); if(CORBA::is_nil(aStudy)) return new Engines::TMPFile(0); SALOMEDS::SObject_var aSO = aStudy->FindComponent(ComponentDataType()); if(CORBA::is_nil(aSO)) return new Engines::TMPFile(0); TObjectData objData; std::vector<TObjectData> objectDataVec; TVariablesList aVariableMap; SALOMEDS::ChildIterator_var Itr = aStudy->NewChildIterator(aSO); for(Itr->InitEx(true); Itr->More(); Itr->Next()) { SALOMEDS::SObject_var aValue = Itr->Value(); CORBA::String_var IOR = aValue->GetIOR(); if(strlen(IOR.in()) > 0) { CORBA::Object_var obj = _orb->string_to_object(IOR); GEOM::GEOM_Object_var GO = GEOM::GEOM_Object::_narrow(obj); if(!CORBA::is_nil(GO)) { CORBA::String_var aName = aValue->GetName(); CORBA::String_var anEntry = GO->GetEntry(); CORBA::String_var aStudyEntry = aValue->GetID(); objData._name = aName.in(); objData._entry = anEntry.in(); objData._studyEntry = aStudyEntry.in(); //Find Drawable Attribute SALOMEDS::GenericAttribute_var aGenAttr; if(aValue->FindAttribute(aGenAttr, "AttributeDrawable") ) { SALOMEDS::AttributeDrawable_var aDrw = SALOMEDS::AttributeDrawable::_narrow(aGenAttr); objData._unpublished = !aDrw->IsDrawable(); } else { objData._unpublished = false; } objectDataVec.push_back( objData ); //Find attribute with list of used notebook variables SALOMEDS::GenericAttribute_var anAttr; SALOMEDS::AttributeString_var anAttrStr; if(aValue->FindAttribute(anAttr,"AttributeString")){ anAttrStr = SALOMEDS::AttributeString::_narrow(anAttr); SALOMEDS::ListOfListOfStrings_var aSections = aStudy->ParseVariables(anAttrStr->Value()); ObjectStates* aStates = new ObjectStates(); for(int i = 0; i < aSections->length(); i++) { TState aState; SALOMEDS::ListOfStrings aListOfVars = aSections[i]; for(int j = 0; j < aListOfVars.length(); j++) { bool isVar = aStudy->IsVariable(aListOfVars[j].in()); TVariable aVar = TVariable( (char*)aListOfVars[j].in(), isVar ); aState.push_back(aVar); } aStates->AddState(aState); } aVariableMap.insert(std::make_pair(TCollection_AsciiString(anEntry),aStates)); } } } } TCollection_AsciiString aScript; aScript += _impl->DumpPython(aStudy->StudyId(), objectDataVec, aVariableMap, isPublished, isMultiFile, isValidScript); if (isPublished) { SALOMEDS::AttributeParameter_var ap = aStudy->GetModuleParameters("Interface Applicative", ComponentDataType(), -1); if(!CORBA::is_nil(ap)) { //Add the id parameter of the object std::vector<TObjectData>::iterator it = objectDataVec.begin(); for( ;it != objectDataVec.end(); it++ ) { //1. Encode entry if ( (*it)._studyEntry.Length() < 7 ) continue; std::string tail( (*it)._studyEntry.ToCString(), 6, (*it)._studyEntry.Length()-1 ); std::string newEntry(ComponentDataType()); newEntry+=("_"+tail); CORBA::String_var anEntry = CORBA::string_dup(newEntry.c_str()); if( ap->IsSet(anEntry, 6) ) { //6 Means string array, see SALOMEDS_Attributes.idl AttributeParameter interface std::string idCommand = std::string("geompy.getObjectID(") + GetDumpName((*it)._studyEntry.ToCString()) + std::string(")"); SALOMEDS::StringSeq_var aSeq= ap->GetStrArray(anEntry); int oldLenght = aSeq->length(); aSeq->length(oldLenght+2); aSeq[oldLenght] = CORBA::string_dup("_PT_OBJECT_ID_"); aSeq[oldLenght + 1] = CORBA::string_dup(idCommand.c_str()); ap->SetStrArray( anEntry, aSeq ); } } } //Output the script that sets up the visual parameters. char* script = aStudy->GetDefaultScript(ComponentDataType(), "\t"); if (script && strlen(script) > 0) { aScript += "\n\t### Store presentation parameters of displayed objects\n"; aScript += script; CORBA::string_free(script); } } if( isMultiFile ) aScript += "\n\tpass"; aScript += "\n"; if( !isMultiFile ) // remove unnecessary tabulation RemoveTabulation( aScript ); int aLen = aScript.Length(); unsigned char* aBuffer = new unsigned char[aLen+1]; strcpy((char*)aBuffer, aScript.ToCString()); CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer; Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1); return aStreamFile._retn(); } //======================================================================= //function : GetDumpName //purpose : //======================================================================= char* GEOM_Gen_i::GetDumpName (const char* theStudyEntry) { const char* name = _impl->GetDumpName( theStudyEntry ); if ( name && strlen( name ) > 0 ) return strdup( name ); return NULL; } //======================================================================= //function : GetAllDumpNames //purpose : //======================================================================= GEOM::string_array* GEOM_Gen_i::GetAllDumpNames() { Handle(TColStd_HSequenceOfAsciiString) aHSeq = _impl->GetAllDumpNames(); int i = 0, aLen = aHSeq->Length(); GEOM::string_array_var seq = new GEOM::string_array(); seq->length(aLen); for (; i < aLen; i++) { seq[i] = CORBA::string_dup(aHSeq->Value(i + 1).ToCString()); } return seq._retn(); } <commit_msg>PR: dump correction when sudies from older versions are loaded<commit_after>// Copyright (C) 2007-2013 CEA/DEN, EDF R&D, OPEN CASCADE // // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License. // // 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 // // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com // #ifdef WNT #pragma warning( disable:4786 ) #endif #include <Standard_Stream.hxx> #include "GEOM_Gen_i.hh" #include <TCollection_AsciiString.hxx> #include <TCollection_ExtendedString.hxx> #include <TColStd_HSequenceOfAsciiString.hxx> #include <Resource_DataMapOfAsciiStringAsciiString.hxx> #include <vector> #include <string> //======================================================================= //function : RemoveTabulation //purpose : //======================================================================= void RemoveTabulation( TCollection_AsciiString& theScript ) { std::string aString( theScript.ToCString() ); std::string::size_type aPos = 0; while( aPos < aString.length() ) { aPos = aString.find( "\n\t", aPos ); if( aPos == std::string::npos ) break; aString.replace( aPos, 2, "\n" ); aPos++; } theScript = aString.c_str(); } //======================================================================= //function : ConvertV6toV7 //purpose : dump elements are stored when study is saved, // and kept when study is reloaded. // When a study from an older version is loaded, // the dump must be post processed in case of syntax modification. // In V7.2, geompy.GEOM --> GEOM //======================================================================= void ConvertV6toV7( TCollection_AsciiString& theScript ) { std::string aString( theScript.ToCString() ); std::string::size_type aPos = 0; while( aPos < aString.length() ) { aPos = aString.find( "geompy.GEOM", aPos ); if( aPos == std::string::npos ) break; aString.replace( aPos, 11, "GEOM" ); aPos++; } theScript = aString.c_str(); } //======================================================================= //function : DumpPython //purpose : //======================================================================= Engines::TMPFile* GEOM_Gen_i::DumpPython(CORBA::Object_ptr theStudy, CORBA::Boolean isPublished, CORBA::Boolean isMultiFile, CORBA::Boolean& isValidScript) { SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy); if(CORBA::is_nil(aStudy)) return new Engines::TMPFile(0); SALOMEDS::SObject_var aSO = aStudy->FindComponent(ComponentDataType()); if(CORBA::is_nil(aSO)) return new Engines::TMPFile(0); TObjectData objData; std::vector<TObjectData> objectDataVec; TVariablesList aVariableMap; SALOMEDS::ChildIterator_var Itr = aStudy->NewChildIterator(aSO); for(Itr->InitEx(true); Itr->More(); Itr->Next()) { SALOMEDS::SObject_var aValue = Itr->Value(); CORBA::String_var IOR = aValue->GetIOR(); if(strlen(IOR.in()) > 0) { CORBA::Object_var obj = _orb->string_to_object(IOR); GEOM::GEOM_Object_var GO = GEOM::GEOM_Object::_narrow(obj); if(!CORBA::is_nil(GO)) { CORBA::String_var aName = aValue->GetName(); CORBA::String_var anEntry = GO->GetEntry(); CORBA::String_var aStudyEntry = aValue->GetID(); objData._name = aName.in(); objData._entry = anEntry.in(); objData._studyEntry = aStudyEntry.in(); //Find Drawable Attribute SALOMEDS::GenericAttribute_var aGenAttr; if(aValue->FindAttribute(aGenAttr, "AttributeDrawable") ) { SALOMEDS::AttributeDrawable_var aDrw = SALOMEDS::AttributeDrawable::_narrow(aGenAttr); objData._unpublished = !aDrw->IsDrawable(); } else { objData._unpublished = false; } objectDataVec.push_back( objData ); //Find attribute with list of used notebook variables SALOMEDS::GenericAttribute_var anAttr; SALOMEDS::AttributeString_var anAttrStr; if(aValue->FindAttribute(anAttr,"AttributeString")){ anAttrStr = SALOMEDS::AttributeString::_narrow(anAttr); SALOMEDS::ListOfListOfStrings_var aSections = aStudy->ParseVariables(anAttrStr->Value()); ObjectStates* aStates = new ObjectStates(); for(int i = 0; i < aSections->length(); i++) { TState aState; SALOMEDS::ListOfStrings aListOfVars = aSections[i]; for(int j = 0; j < aListOfVars.length(); j++) { bool isVar = aStudy->IsVariable(aListOfVars[j].in()); TVariable aVar = TVariable( (char*)aListOfVars[j].in(), isVar ); aState.push_back(aVar); } aStates->AddState(aState); } aVariableMap.insert(std::make_pair(TCollection_AsciiString(anEntry),aStates)); } } } } TCollection_AsciiString aScript; aScript += _impl->DumpPython(aStudy->StudyId(), objectDataVec, aVariableMap, isPublished, isMultiFile, isValidScript); if (isPublished) { SALOMEDS::AttributeParameter_var ap = aStudy->GetModuleParameters("Interface Applicative", ComponentDataType(), -1); if(!CORBA::is_nil(ap)) { //Add the id parameter of the object std::vector<TObjectData>::iterator it = objectDataVec.begin(); for( ;it != objectDataVec.end(); it++ ) { //1. Encode entry if ( (*it)._studyEntry.Length() < 7 ) continue; std::string tail( (*it)._studyEntry.ToCString(), 6, (*it)._studyEntry.Length()-1 ); std::string newEntry(ComponentDataType()); newEntry+=("_"+tail); CORBA::String_var anEntry = CORBA::string_dup(newEntry.c_str()); if( ap->IsSet(anEntry, 6) ) { //6 Means string array, see SALOMEDS_Attributes.idl AttributeParameter interface std::string idCommand = std::string("geompy.getObjectID(") + GetDumpName((*it)._studyEntry.ToCString()) + std::string(")"); SALOMEDS::StringSeq_var aSeq= ap->GetStrArray(anEntry); int oldLenght = aSeq->length(); aSeq->length(oldLenght+2); aSeq[oldLenght] = CORBA::string_dup("_PT_OBJECT_ID_"); aSeq[oldLenght + 1] = CORBA::string_dup(idCommand.c_str()); ap->SetStrArray( anEntry, aSeq ); } } } //Output the script that sets up the visual parameters. char* script = aStudy->GetDefaultScript(ComponentDataType(), "\t"); if (script && strlen(script) > 0) { aScript += "\n\t### Store presentation parameters of displayed objects\n"; aScript += script; CORBA::string_free(script); } } if( isMultiFile ) aScript += "\n\tpass"; aScript += "\n"; if( !isMultiFile ) // remove unnecessary tabulation RemoveTabulation( aScript ); ConvertV6toV7( aScript ); //convert scripts related to studies saved in SALOME V6 and older int aLen = aScript.Length(); unsigned char* aBuffer = new unsigned char[aLen+1]; strcpy((char*)aBuffer, aScript.ToCString()); CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer; Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1); return aStreamFile._retn(); } //======================================================================= //function : GetDumpName //purpose : //======================================================================= char* GEOM_Gen_i::GetDumpName (const char* theStudyEntry) { const char* name = _impl->GetDumpName( theStudyEntry ); if ( name && strlen( name ) > 0 ) return strdup( name ); return NULL; } //======================================================================= //function : GetAllDumpNames //purpose : //======================================================================= GEOM::string_array* GEOM_Gen_i::GetAllDumpNames() { Handle(TColStd_HSequenceOfAsciiString) aHSeq = _impl->GetAllDumpNames(); int i = 0, aLen = aHSeq->Length(); GEOM::string_array_var seq = new GEOM::string_array(); seq->length(aLen); for (; i < aLen; i++) { seq[i] = CORBA::string_dup(aHSeq->Value(i + 1).ToCString()); } return seq._retn(); } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2011-2012, John Haddon. All rights reserved. // Copyright (c) 2012-2015, Image Engine Design 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 John Haddon nor the names of // any other contributors to this software 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 <pwd.h> #include <grp.h> #include <sys/stat.h> #include "boost/filesystem.hpp" #include "boost/filesystem/operations.hpp" #include "boost/algorithm/string.hpp" #include "boost/date_time/posix_time/conversion.hpp" #include "IECore/SimpleTypedData.h" #include "IECore/DateTimeData.h" #include "IECore/FileSequenceFunctions.h" #include "Gaffer/PathFilter.h" #include "Gaffer/FileSystemPath.h" #include "Gaffer/FileSequencePathFilter.h" #include "Gaffer/CompoundPathFilter.h" #include "Gaffer/MatchPatternPathFilter.h" using namespace std; using namespace boost::filesystem; using namespace boost::algorithm; using namespace boost::posix_time; using namespace IECore; using namespace Gaffer; IE_CORE_DEFINERUNTIMETYPED( FileSystemPath ); static InternedString g_ownerPropertyName( "fileSystem:owner" ); static InternedString g_groupPropertyName( "fileSystem:group" ); static InternedString g_modificationTimePropertyName( "fileSystem:modificationTime" ); static InternedString g_sizePropertyName( "fileSystem:size" ); static InternedString g_frameRangePropertyName( "fileSystem:frameRange" ); FileSystemPath::FileSystemPath( PathFilterPtr filter, bool includeSequences ) : Path( filter ), m_includeSequences( includeSequences ) { } FileSystemPath::FileSystemPath( const std::string &path, PathFilterPtr filter, bool includeSequences ) : Path( path, filter ), m_includeSequences( includeSequences ) { } FileSystemPath::FileSystemPath( const Names &names, const IECore::InternedString &root, PathFilterPtr filter, bool includeSequences ) : Path( names, root, filter ), m_includeSequences( includeSequences ) { } FileSystemPath::~FileSystemPath() { } bool FileSystemPath::isValid() const { if( !Path::isValid() ) { return false; } if( m_includeSequences && isFileSequence() ) { return true; } const file_type t = symlink_status( path( this->string() ) ).type(); return t != status_error && t != file_not_found; } bool FileSystemPath::isLeaf() const { return isValid() && !is_directory( path( this->string() ) ); } bool FileSystemPath::getIncludeSequences() const { return m_includeSequences; } void FileSystemPath::setIncludeSequences( bool includeSequences ) { m_includeSequences = includeSequences; } bool FileSystemPath::isFileSequence() const { if( !m_includeSequences || is_directory( path( this->string() ) ) ) { return false; } try { return new FileSequence( this->string() ); } catch( ... ) { } return false; } FileSequencePtr FileSystemPath::fileSequence() const { if( !m_includeSequences || is_directory( path( this->string() ) ) ) { return NULL; } FileSequencePtr sequence = NULL; IECore::ls( this->string(), sequence, /* minSequenceSize = */ 1 ); return sequence; } void FileSystemPath::propertyNames( std::vector<IECore::InternedString> &names ) const { Path::propertyNames( names ); names.push_back( g_ownerPropertyName ); names.push_back( g_groupPropertyName ); names.push_back( g_modificationTimePropertyName ); names.push_back( g_sizePropertyName ); if( m_includeSequences ) { names.push_back( g_frameRangePropertyName ); } } IECore::ConstRunTimeTypedPtr FileSystemPath::property( const IECore::InternedString &name ) const { if( name == g_ownerPropertyName ) { if( m_includeSequences ) { FileSequencePtr sequence = fileSequence(); if( sequence ) { std::vector<std::string> files; sequence->fileNames( files ); size_t maxCount = 0; std::string mostCommon = ""; std::map<std::string,size_t> ownerCounter; for( std::vector<std::string>::iterator it = files.begin(); it != files.end(); ++it ) { struct stat s; stat( it->c_str(), &s ); struct passwd *pw = getpwuid( s.st_uid ); std::string value = pw ? pw->pw_name : ""; std::pair<std::map<std::string,size_t>::iterator,bool> oIt = ownerCounter.insert( std::pair<std::string,size_t>( value, 0 ) ); oIt.first->second++; if( oIt.first->second > maxCount ) { mostCommon = value; } } return new StringData( mostCommon ); } } std::string n = this->string(); struct stat s; stat( n.c_str(), &s ); struct passwd *pw = getpwuid( s.st_uid ); return new StringData( pw ? pw->pw_name : "" ); } else if( name == g_groupPropertyName ) { if( m_includeSequences ) { FileSequencePtr sequence = fileSequence(); if( sequence ) { std::vector<std::string> files; sequence->fileNames( files ); size_t maxCount = 0; std::string mostCommon = ""; std::map<std::string,size_t> ownerCounter; for( std::vector<std::string>::iterator it = files.begin(); it != files.end(); ++it ) { struct stat s; stat( it->c_str(), &s ); struct group *gr = getgrgid( s.st_gid ); std::string value = gr ? gr->gr_name : ""; std::pair<std::map<std::string,size_t>::iterator,bool> oIt = ownerCounter.insert( std::pair<std::string,size_t>( value, 0 ) ); oIt.first->second++; if( oIt.first->second > maxCount ) { mostCommon = value; } } return new StringData( mostCommon ); } } std::string n = this->string(); struct stat s; stat( n.c_str(), &s ); struct group *gr = getgrgid( s.st_gid ); return new StringData( gr ? gr->gr_name : "" ); } else if( name == g_modificationTimePropertyName ) { boost::system::error_code e; if( m_includeSequences ) { FileSequencePtr sequence = fileSequence(); if( sequence ) { std::vector<std::string> files; sequence->fileNames( files ); std::time_t newest = 0; for( std::vector<std::string>::iterator it = files.begin(); it != files.end(); ++it ) { std::time_t t = last_write_time( path( *it ), e ); if( t > newest ) { newest = t; } } return new DateTimeData( from_time_t( newest ) ); } } std::time_t t = last_write_time( path( this->string() ), e ); return new DateTimeData( from_time_t( t ) ); } else if( name == g_sizePropertyName ) { boost::system::error_code e; if( m_includeSequences ) { FileSequencePtr sequence = fileSequence(); if( sequence ) { std::vector<std::string> files; sequence->fileNames( files ); uintmax_t total = 0; for( std::vector<std::string>::iterator it = files.begin(); it != files.end(); ++it ) { uintmax_t s = file_size( path( *it ), e ); if( !e ) { total += s; } } return new UInt64Data( total ); } } uintmax_t s = file_size( path( this->string() ), e ); return new UInt64Data( !e ? s : 0 ); } else if( name == g_frameRangePropertyName ) { FileSequencePtr sequence = fileSequence(); if( sequence ) { return new StringData( sequence->getFrameList()->asString() ); } return new StringData; } return Path::property( name ); } PathPtr FileSystemPath::copy() const { return new FileSystemPath( names(), root(), const_cast<PathFilter *>( getFilter() ), m_includeSequences ); } void FileSystemPath::doChildren( std::vector<PathPtr> &children ) const { path p( this->string() ); if( !is_directory( p ) ) { return; } for( directory_iterator it( p ), eIt; it != eIt; ++it ) { children.push_back( new FileSystemPath( it->path().string(), const_cast<PathFilter *>( getFilter() ), m_includeSequences ) ); } if( m_includeSequences ) { std::vector<FileSequencePtr> sequences; IECore::ls( p.string(), sequences, /* minSequenceSize */ 1 ); for( std::vector<FileSequencePtr>::iterator it = sequences.begin(); it != sequences.end(); ++it ) { std::vector<FrameList::Frame> frames; (*it)->getFrameList()->asList( frames ); if ( !is_directory( path( (*it)->fileNameForFrame( frames[0] ) ) ) ) { children.push_back( new FileSystemPath( path( p / (*it)->getFileName() ).string(), const_cast<PathFilter *>( getFilter() ), m_includeSequences ) ); } } } } PathFilterPtr FileSystemPath::createStandardFilter( const std::vector<std::string> &extensions, const std::string &extensionsLabel, bool includeSequenceFilter ) { CompoundPathFilterPtr result = new CompoundPathFilter(); // Filter for the extensions if( extensions.size() ) { std::string defaultLabel = "Show only "; vector<MatchPattern> patterns; for( std::vector<std::string>::const_iterator it = extensions.begin(), eIt = extensions.end(); it != eIt; ++it ) { patterns.push_back( "*." + to_lower_copy( *it ) ); patterns.push_back( "*." + to_upper_copy( *it ) ); // the form below is for file sequences, where the frame // range will come after the extension. patterns.push_back( "*." + to_lower_copy( *it ) + " *" ); patterns.push_back( "*." + to_upper_copy( *it ) + " *" ); if( it != extensions.begin() ) { defaultLabel += ", "; } defaultLabel += "." + to_lower_copy( *it ); } defaultLabel += " files"; MatchPatternPathFilterPtr fileNameFilter = new MatchPatternPathFilter( patterns, "name" ); CompoundDataPtr uiUserData = new CompoundData; uiUserData->writable()["label"] = new StringData( extensionsLabel.size() ? extensionsLabel : defaultLabel ); fileNameFilter->userData()->writable()["UI"] = uiUserData; result->addFilter( fileNameFilter ); } // Filter for sequences if( includeSequenceFilter ) { result->addFilter( new FileSequencePathFilter( /* mode = */ FileSequencePathFilter::Concise ) ); } // Filter for hidden files std::vector<std::string> hiddenFilePatterns; hiddenFilePatterns.push_back( ".*" ); MatchPatternPathFilterPtr hiddenFilesFilter = new MatchPatternPathFilter( hiddenFilePatterns, "name", /* leafOnly = */ false ); hiddenFilesFilter->setInverted( true ); CompoundDataPtr hiddenFilesUIUserData = new CompoundData; hiddenFilesUIUserData->writable()["label"] = new StringData( "Show hidden files" ); hiddenFilesUIUserData->writable()["invertEnabled"] = new BoolData( true ); hiddenFilesFilter->userData()->writable()["UI"] = hiddenFilesUIUserData; result->addFilter( hiddenFilesFilter ); // User defined search filter std::vector<std::string> searchPatterns; searchPatterns.push_back( "" ); MatchPatternPathFilterPtr searchFilter = new MatchPatternPathFilter( searchPatterns ); searchFilter->setEnabled( false ); CompoundDataPtr searchUIUserData = new CompoundData; searchUIUserData->writable()["editable"] = new BoolData( true ); searchFilter->userData()->writable()["UI"] = searchUIUserData; result->addFilter( searchFilter ); return result; } <commit_msg>Using FileSequence::fileNameValidator() to find valid paths.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2011-2012, John Haddon. All rights reserved. // Copyright (c) 2012-2015, Image Engine Design 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 John Haddon nor the names of // any other contributors to this software 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 <pwd.h> #include <grp.h> #include <sys/stat.h> #include "boost/filesystem.hpp" #include "boost/filesystem/operations.hpp" #include "boost/algorithm/string.hpp" #include "boost/date_time/posix_time/conversion.hpp" #include "IECore/SimpleTypedData.h" #include "IECore/DateTimeData.h" #include "IECore/FileSequenceFunctions.h" #include "Gaffer/PathFilter.h" #include "Gaffer/FileSystemPath.h" #include "Gaffer/FileSequencePathFilter.h" #include "Gaffer/CompoundPathFilter.h" #include "Gaffer/MatchPatternPathFilter.h" using namespace std; using namespace boost::filesystem; using namespace boost::algorithm; using namespace boost::posix_time; using namespace IECore; using namespace Gaffer; IE_CORE_DEFINERUNTIMETYPED( FileSystemPath ); static InternedString g_ownerPropertyName( "fileSystem:owner" ); static InternedString g_groupPropertyName( "fileSystem:group" ); static InternedString g_modificationTimePropertyName( "fileSystem:modificationTime" ); static InternedString g_sizePropertyName( "fileSystem:size" ); static InternedString g_frameRangePropertyName( "fileSystem:frameRange" ); FileSystemPath::FileSystemPath( PathFilterPtr filter, bool includeSequences ) : Path( filter ), m_includeSequences( includeSequences ) { } FileSystemPath::FileSystemPath( const std::string &path, PathFilterPtr filter, bool includeSequences ) : Path( path, filter ), m_includeSequences( includeSequences ) { } FileSystemPath::FileSystemPath( const Names &names, const IECore::InternedString &root, PathFilterPtr filter, bool includeSequences ) : Path( names, root, filter ), m_includeSequences( includeSequences ) { } FileSystemPath::~FileSystemPath() { } bool FileSystemPath::isValid() const { if( !Path::isValid() ) { return false; } if( m_includeSequences && isFileSequence() ) { return true; } const file_type t = symlink_status( path( this->string() ) ).type(); return t != status_error && t != file_not_found; } bool FileSystemPath::isLeaf() const { return isValid() && !is_directory( path( this->string() ) ); } bool FileSystemPath::getIncludeSequences() const { return m_includeSequences; } void FileSystemPath::setIncludeSequences( bool includeSequences ) { m_includeSequences = includeSequences; } bool FileSystemPath::isFileSequence() const { if( !m_includeSequences || is_directory( path( this->string() ) ) ) { return false; } try { return boost::regex_match( this->string(), FileSequence::fileNameValidator() ); } catch( ... ) { } return false; } FileSequencePtr FileSystemPath::fileSequence() const { if( !m_includeSequences || is_directory( path( this->string() ) ) ) { return NULL; } FileSequencePtr sequence = NULL; IECore::ls( this->string(), sequence, /* minSequenceSize = */ 1 ); return sequence; } void FileSystemPath::propertyNames( std::vector<IECore::InternedString> &names ) const { Path::propertyNames( names ); names.push_back( g_ownerPropertyName ); names.push_back( g_groupPropertyName ); names.push_back( g_modificationTimePropertyName ); names.push_back( g_sizePropertyName ); if( m_includeSequences ) { names.push_back( g_frameRangePropertyName ); } } IECore::ConstRunTimeTypedPtr FileSystemPath::property( const IECore::InternedString &name ) const { if( name == g_ownerPropertyName ) { if( m_includeSequences ) { FileSequencePtr sequence = fileSequence(); if( sequence ) { std::vector<std::string> files; sequence->fileNames( files ); size_t maxCount = 0; std::string mostCommon = ""; std::map<std::string,size_t> ownerCounter; for( std::vector<std::string>::iterator it = files.begin(); it != files.end(); ++it ) { struct stat s; stat( it->c_str(), &s ); struct passwd *pw = getpwuid( s.st_uid ); std::string value = pw ? pw->pw_name : ""; std::pair<std::map<std::string,size_t>::iterator,bool> oIt = ownerCounter.insert( std::pair<std::string,size_t>( value, 0 ) ); oIt.first->second++; if( oIt.first->second > maxCount ) { mostCommon = value; } } return new StringData( mostCommon ); } } std::string n = this->string(); struct stat s; stat( n.c_str(), &s ); struct passwd *pw = getpwuid( s.st_uid ); return new StringData( pw ? pw->pw_name : "" ); } else if( name == g_groupPropertyName ) { if( m_includeSequences ) { FileSequencePtr sequence = fileSequence(); if( sequence ) { std::vector<std::string> files; sequence->fileNames( files ); size_t maxCount = 0; std::string mostCommon = ""; std::map<std::string,size_t> ownerCounter; for( std::vector<std::string>::iterator it = files.begin(); it != files.end(); ++it ) { struct stat s; stat( it->c_str(), &s ); struct group *gr = getgrgid( s.st_gid ); std::string value = gr ? gr->gr_name : ""; std::pair<std::map<std::string,size_t>::iterator,bool> oIt = ownerCounter.insert( std::pair<std::string,size_t>( value, 0 ) ); oIt.first->second++; if( oIt.first->second > maxCount ) { mostCommon = value; } } return new StringData( mostCommon ); } } std::string n = this->string(); struct stat s; stat( n.c_str(), &s ); struct group *gr = getgrgid( s.st_gid ); return new StringData( gr ? gr->gr_name : "" ); } else if( name == g_modificationTimePropertyName ) { boost::system::error_code e; if( m_includeSequences ) { FileSequencePtr sequence = fileSequence(); if( sequence ) { std::vector<std::string> files; sequence->fileNames( files ); std::time_t newest = 0; for( std::vector<std::string>::iterator it = files.begin(); it != files.end(); ++it ) { std::time_t t = last_write_time( path( *it ), e ); if( t > newest ) { newest = t; } } return new DateTimeData( from_time_t( newest ) ); } } std::time_t t = last_write_time( path( this->string() ), e ); return new DateTimeData( from_time_t( t ) ); } else if( name == g_sizePropertyName ) { boost::system::error_code e; if( m_includeSequences ) { FileSequencePtr sequence = fileSequence(); if( sequence ) { std::vector<std::string> files; sequence->fileNames( files ); uintmax_t total = 0; for( std::vector<std::string>::iterator it = files.begin(); it != files.end(); ++it ) { uintmax_t s = file_size( path( *it ), e ); if( !e ) { total += s; } } return new UInt64Data( total ); } } uintmax_t s = file_size( path( this->string() ), e ); return new UInt64Data( !e ? s : 0 ); } else if( name == g_frameRangePropertyName ) { FileSequencePtr sequence = fileSequence(); if( sequence ) { return new StringData( sequence->getFrameList()->asString() ); } return new StringData; } return Path::property( name ); } PathPtr FileSystemPath::copy() const { return new FileSystemPath( names(), root(), const_cast<PathFilter *>( getFilter() ), m_includeSequences ); } void FileSystemPath::doChildren( std::vector<PathPtr> &children ) const { path p( this->string() ); if( !is_directory( p ) ) { return; } for( directory_iterator it( p ), eIt; it != eIt; ++it ) { children.push_back( new FileSystemPath( it->path().string(), const_cast<PathFilter *>( getFilter() ), m_includeSequences ) ); } if( m_includeSequences ) { std::vector<FileSequencePtr> sequences; IECore::ls( p.string(), sequences, /* minSequenceSize */ 1 ); for( std::vector<FileSequencePtr>::iterator it = sequences.begin(); it != sequences.end(); ++it ) { std::vector<FrameList::Frame> frames; (*it)->getFrameList()->asList( frames ); if ( !is_directory( path( (*it)->fileNameForFrame( frames[0] ) ) ) ) { children.push_back( new FileSystemPath( path( p / (*it)->getFileName() ).string(), const_cast<PathFilter *>( getFilter() ), m_includeSequences ) ); } } } } PathFilterPtr FileSystemPath::createStandardFilter( const std::vector<std::string> &extensions, const std::string &extensionsLabel, bool includeSequenceFilter ) { CompoundPathFilterPtr result = new CompoundPathFilter(); // Filter for the extensions if( extensions.size() ) { std::string defaultLabel = "Show only "; vector<MatchPattern> patterns; for( std::vector<std::string>::const_iterator it = extensions.begin(), eIt = extensions.end(); it != eIt; ++it ) { patterns.push_back( "*." + to_lower_copy( *it ) ); patterns.push_back( "*." + to_upper_copy( *it ) ); // the form below is for file sequences, where the frame // range will come after the extension. patterns.push_back( "*." + to_lower_copy( *it ) + " *" ); patterns.push_back( "*." + to_upper_copy( *it ) + " *" ); if( it != extensions.begin() ) { defaultLabel += ", "; } defaultLabel += "." + to_lower_copy( *it ); } defaultLabel += " files"; MatchPatternPathFilterPtr fileNameFilter = new MatchPatternPathFilter( patterns, "name" ); CompoundDataPtr uiUserData = new CompoundData; uiUserData->writable()["label"] = new StringData( extensionsLabel.size() ? extensionsLabel : defaultLabel ); fileNameFilter->userData()->writable()["UI"] = uiUserData; result->addFilter( fileNameFilter ); } // Filter for sequences if( includeSequenceFilter ) { result->addFilter( new FileSequencePathFilter( /* mode = */ FileSequencePathFilter::Concise ) ); } // Filter for hidden files std::vector<std::string> hiddenFilePatterns; hiddenFilePatterns.push_back( ".*" ); MatchPatternPathFilterPtr hiddenFilesFilter = new MatchPatternPathFilter( hiddenFilePatterns, "name", /* leafOnly = */ false ); hiddenFilesFilter->setInverted( true ); CompoundDataPtr hiddenFilesUIUserData = new CompoundData; hiddenFilesUIUserData->writable()["label"] = new StringData( "Show hidden files" ); hiddenFilesUIUserData->writable()["invertEnabled"] = new BoolData( true ); hiddenFilesFilter->userData()->writable()["UI"] = hiddenFilesUIUserData; result->addFilter( hiddenFilesFilter ); // User defined search filter std::vector<std::string> searchPatterns; searchPatterns.push_back( "" ); MatchPatternPathFilterPtr searchFilter = new MatchPatternPathFilter( searchPatterns ); searchFilter->setEnabled( false ); CompoundDataPtr searchUIUserData = new CompoundData; searchUIUserData->writable()["editable"] = new BoolData( true ); searchFilter->userData()->writable()["UI"] = searchUIUserData; result->addFilter( searchFilter ); return result; } <|endoftext|>
<commit_before>/** * @file broker.hpp * @brief Component Broker * @author Byunghun Hwang<bhhwang@nsynapse.com> * @date 2015. 6. 21 * @details */ #ifndef _COSSB_BROKER_HPP_ #define _COSSB_BROKER_HPP_ #include <map> #include <string> #include "interface/icomponent.hpp" #include "arch/singleton.hpp" #include "manager.hpp" #include "logger.hpp" using namespace std; namespace cossb { namespace broker { //(topic, component name) pair typedef multimap<string, string> topic_map; class component_broker : public arch::singleton<component_broker> { public: component_broker() { }; virtual ~component_broker() { }; /** *@brief regist component with topic */ bool regist(interface::icomponent* component, string topic_name) { _topic_map.insert(topic_map::value_type(topic_name, component->get_name())); return true; } /** * @brief publish data pack to specific service component */ template<typename... Args> bool publish(interface::icomponent* component, const char* to_topic, const char* api, const Args&... args) { auto range = _topic_map.equal_range(to_topic); for(topic_map::iterator itr = range.first; itr!=range.second; ++itr) { if(itr->second.compare(component->get_name())==0) { driver::component_driver* _drv = cossb_component_manager->get_driver(itr->second.c_str()); if(_drv) { cossb_log->log(log::loglevel::INFO, "publish"); _drv->request(api, args...); } else cossb_log->log(log::loglevel::INFO, "cannot publish"); } } return true; } private: topic_map _topic_map; }; #define cossb_broker cossb::broker::component_broker::instance() } /* namespace broker */ } /* namespace cossb */ #endif <commit_msg>remove comment<commit_after>/** * @file broker.hpp * @brief Component Broker * @author Byunghun Hwang<bhhwang@nsynapse.com> * @date 2015. 6. 21 * @details */ #ifndef _COSSB_BROKER_HPP_ #define _COSSB_BROKER_HPP_ #include <map> #include <string> #include "interface/icomponent.hpp" #include "arch/singleton.hpp" #include "manager.hpp" #include "logger.hpp" using namespace std; namespace cossb { namespace broker { //(topic, component name) pair typedef multimap<string, string> topic_map; class component_broker : public arch::singleton<component_broker> { public: component_broker() { }; virtual ~component_broker() { }; /** *@brief regist component with topic */ bool regist(interface::icomponent* component, string topic_name) { _topic_map.insert(topic_map::value_type(topic_name, component->get_name())); return true; } /** * @brief publish data pack to specific service component */ template<typename... Args> bool publish(interface::icomponent* component, const char* to_topic, const char* api, const Args&... args) { auto range = _topic_map.equal_range(to_topic); for(topic_map::iterator itr = range.first; itr!=range.second; ++itr) { if(itr->second.compare(component->get_name())==0) { driver::component_driver* _drv = cossb_component_manager->get_driver(itr->second.c_str()); if(_drv) _drv->request(api, args...); } } return true; } private: topic_map _topic_map; }; #define cossb_broker cossb::broker::component_broker::instance() } /* namespace broker */ } /* namespace cossb */ #endif <|endoftext|>
<commit_before>#include <QObject> #include <QDebug> #include <QCanBusFrame> #include <QSettings> #include <QStringBuilder> #include <QtNetwork> #include "mqtt_bus.h" MQTT_BUS::MQTT_BUS(QString topicName) : CANConnection(topicName, "mqtt_client", CANCon::MQTT, 1, 4000, true), mTimer(this) /*NB: set this as parent of timer to manage it from working thread */ { sendDebug("MQTT_BUS()"); crypto = new SimpleCrypt(Q_UINT64_C(0xdeadbeefface6285)); isAutoRestart = false; this->topicName = topicName; timeBasis = 0; lastSystemTimeBasis = 0; readSettings(); } MQTT_BUS::~MQTT_BUS() { delete crypto; stop(); sendDebug("~MQTT_BUS"); } void MQTT_BUS::sendDebug(const QString debugText) { qDebug() << debugText; debugOutput(debugText); } void MQTT_BUS::piStarted() { QSettings settings; QString userName = settings.value("Remote/User", "Anonymous").toString(); QString host = settings.value("Remote/Host", "api.savvycan.com").toString(); int port = settings.value("Remote/Port", 8333).toInt(); QByteArray encPass = settings.value("Remote/Pass", "").toByteArray(); QByteArray password = crypto->decryptToByteArray(encPass); QSslConfiguration sslConfig = QSslConfiguration::defaultConfiguration(); mqttClient = new QMQTT::Client(host, port, sslConfig); connect(mqttClient, &QMQTT::Client::connected, this, &MQTT_BUS::clientConnected); connect(mqttClient, &QMQTT::Client::error, this, &MQTT_BUS::clientErrored); //qDebug() << "User: " << userName << " Pass: " << password; mqttClient->setClientId(genRandomClientID()); mqttClient->setUsername(userName); mqttClient->setPassword(password); mqttClient->connectToHost(); } //MQTT required a client ID and they cannot be the same for any two clients. But, they really aren't super exciting //or important to be named explicitly. Perhaps it might be nice to be able to see it for debugging though. QString MQTT_BUS::genRandomClientID() { QString output; output.reserve(12); QRandomGenerator gen; for (int i = 0; i < 12; i++) { int val = gen.bounded(0, 62); if (val < 26) output.append(QChar('A'+val)); else if (val < 52) output.append(QChar('a'+val-26)); else output.append(QChar('0'+val-52)); } qDebug() << "Client ID: " << output; return output; } void MQTT_BUS::clientErrored(const QMQTT::ClientError error) { qDebug() << QString::number(error); } void MQTT_BUS::piSuspend(bool pSuspend) { /* update capSuspended */ setCapSuspended(pSuspend); /* flush queue if we are suspended */ if(isCapSuspended()) getQueue().flush(); } void MQTT_BUS::piStop() { mTimer.stop(); disconnectDevice(); } bool MQTT_BUS::piGetBusSettings(int pBusIdx, CANBus& pBus) { return getBusConfig(pBusIdx, pBus); } void MQTT_BUS::piSetBusSettings(int pBusIdx, CANBus bus) { /* sanity checks */ if( (pBusIdx < 0) || pBusIdx >= getNumBuses()) return; /* copy bus config */ setBusConfig(pBusIdx, bus); //we don't really update anything. We're just here to listen and perhaps send frames. } bool MQTT_BUS::piSendFrame(const CANFrame& frame) { QByteArray buffer; int c; quint32 ID; //qDebug() << "Sending out GVRET frame with id " << frame.ID << " on bus " << frame.bus; framesRapid++; // Doesn't make sense to send an error frame // to an adapter if (frame.frameId() & 0x20000000) { return true; } ID = frame.frameId(); if (frame.hasExtendedFrameFormat()) ID |= 1u << 31; buffer[0] = (char)0xF1; //start of a command over serial buffer[1] = 0; //command ID for sending a CANBUS frame buffer[2] = (char)(ID & 0xFF); //four bytes of ID LSB first buffer[3] = (char)(ID >> 8); buffer[4] = (char)(ID >> 16); buffer[5] = (char)(ID >> 24); buffer[6] = (char)((frame.bus) & 3); buffer[7] = (char)frame.payload().length(); for (c = 0; c < frame.payload().length(); c++) { buffer[8 + c] = frame.payload()[c]; } buffer[8 + frame.payload().length()] = 0; return true; } /****************************************************************/ void MQTT_BUS::readSettings() { QSettings settings; } void MQTT_BUS::clientMessageReceived(const QMQTT::Message& message) { uint64_t timeBasis = CANConManager::getInstance()->getTimeBasis(); /* drop frame if capture is suspended */ if(isCapSuspended()) return; CANFrame* frame_p = getQueue().get(); if(frame_p) { uint32_t frameID = message.topic().split("/")[1].toInt(); uint64_t timeStamp = message.payload()[0] + (message.payload()[1] << 8) + (message.payload()[2] << 16) + (message.payload()[3] << 24) + ((uint64_t)message.payload()[4] << 32ull) + ((uint64_t)message.payload()[5] << 40ull) + ((uint64_t)message.payload()[6] << 48ull) + ((uint64_t)message.payload()[7] << 56ull); int flags = message.payload()[8]; frame_p->setPayload(message.payload().right(message.payload().count() - 9)); frame_p->bus = 0; frame_p->setExtendedFrameFormat(flags & 1); frame_p->setFrameId(frameID); frame_p->setFrameType(QCanBusFrame::DataFrame); frame_p->isReceived = true; if (useSystemTime) { frame_p->setTimeStamp(QCanBusFrame::TimeStamp(0, QDateTime::currentMSecsSinceEpoch() * 1000ul)); } else frame_p->setTimeStamp(QCanBusFrame::TimeStamp(0, timeStamp)); checkTargettedFrame(*frame_p); /* enqueue frame */ getQueue().queue(); } } void MQTT_BUS::clientConnected() { sendDebug("Connecting to MQTT Broker!"); mqttClient->subscribe(topicName + "/+", 0); //subscribe to all sub topics to grab the frames. connect(mqttClient, &QMQTT::Client::received, this, &MQTT_BUS::clientMessageReceived); setStatus(CANCon::CONNECTED); CANConStatus stats; stats.conStatus = getStatus(); stats.numHardwareBuses = 1;//mNumBuses; emit status(stats); } void MQTT_BUS::disconnectDevice() { setStatus(CANCon::NOT_CONNECTED); CANConStatus stats; stats.conStatus = getStatus(); stats.numHardwareBuses = mNumBuses; emit status(stats); } void MQTT_BUS::rebuildLocalTimeBasis() { //qDebug() << "Rebuilding GVRET time base. GVRET local base = " << buildTimeBasis; /* our time basis is the value we have to modulate the main system basis by in order to sync the GVRET timestamps to the rest of the system. The rest of the system uses CANConManager::getInstance()->getTimeBasis as the basis. GVRET returns to us the current time since boot up in microseconds. timeAtGVRETSync stores the "system" timestamp when the GVRET timestamp was retrieved. */ /* lastSystemTimeBasis = CANConManager::getInstance()->getTimeBasis(); int64_t systemDelta = timeAtGVRETSync - lastSystemTimeBasis; int32_t localDelta = buildTimeBasis - systemDelta; timeBasis = -localDelta; */ } <commit_msg>Changes to MQTT interface to make it work properly with current python script<commit_after>#include <QObject> #include <QDebug> #include <QCanBusFrame> #include <QSettings> #include <QStringBuilder> #include <QtNetwork> #include "utility.h" #include "mqtt_bus.h" MQTT_BUS::MQTT_BUS(QString topicName) : CANConnection(topicName, "mqtt_client", CANCon::MQTT, 1, 4000, true), mTimer(this) /*NB: set this as parent of timer to manage it from working thread */ { sendDebug("MQTT_BUS()"); crypto = new SimpleCrypt(Q_UINT64_C(0xdeadbeefface6285)); isAutoRestart = false; this->topicName = topicName; timeBasis = 0; lastSystemTimeBasis = 0; readSettings(); } MQTT_BUS::~MQTT_BUS() { delete crypto; stop(); sendDebug("~MQTT_BUS"); } void MQTT_BUS::sendDebug(const QString debugText) { qDebug() << debugText; debugOutput(debugText); } void MQTT_BUS::piStarted() { QSettings settings; QString userName = settings.value("Remote/User", "Anonymous").toString(); QString host = settings.value("Remote/Host", "api.savvycan.com").toString(); int port = settings.value("Remote/Port", 8333).toInt(); QByteArray encPass = settings.value("Remote/Pass", "").toByteArray(); QByteArray password = crypto->decryptToByteArray(encPass); QSslConfiguration sslConfig = QSslConfiguration::defaultConfiguration(); mqttClient = new QMQTT::Client(host, port, sslConfig); connect(mqttClient, &QMQTT::Client::connected, this, &MQTT_BUS::clientConnected); connect(mqttClient, &QMQTT::Client::error, this, &MQTT_BUS::clientErrored); //qDebug() << "User: " << userName << " Pass: " << password; mqttClient->setClientId(genRandomClientID()); mqttClient->setUsername(userName); mqttClient->setPassword(password); mqttClient->connectToHost(); } //MQTT required a client ID and they cannot be the same for any two clients. But, they really aren't super exciting //or important to be named explicitly. Perhaps it might be nice to be able to see it for debugging though. QString MQTT_BUS::genRandomClientID() { QString output; output.reserve(12); QRandomGenerator gen; for (int i = 0; i < 12; i++) { int val = gen.bounded(0, 62); if (val < 26) output.append(QChar('A'+val)); else if (val < 52) output.append(QChar('a'+val-26)); else output.append(QChar('0'+val-52)); } qDebug() << "Client ID: " << output; return output; } void MQTT_BUS::clientErrored(const QMQTT::ClientError error) { qDebug() << QString::number(error); } void MQTT_BUS::piSuspend(bool pSuspend) { /* update capSuspended */ setCapSuspended(pSuspend); /* flush queue if we are suspended */ if(isCapSuspended()) getQueue().flush(); } void MQTT_BUS::piStop() { mTimer.stop(); disconnectDevice(); } bool MQTT_BUS::piGetBusSettings(int pBusIdx, CANBus& pBus) { return getBusConfig(pBusIdx, pBus); } void MQTT_BUS::piSetBusSettings(int pBusIdx, CANBus bus) { /* sanity checks */ if( (pBusIdx < 0) || pBusIdx >= getNumBuses()) return; /* copy bus config */ setBusConfig(pBusIdx, bus); //we don't really update anything. We're just here to listen and perhaps send frames. } bool MQTT_BUS::piSendFrame(const CANFrame& frame) { QByteArray buffer; int c; quint32 ID; //qDebug() << "Sending out GVRET frame with id " << frame.ID << " on bus " << frame.bus; framesRapid++; // Doesn't make sense to send an error frame // to an adapter if (frame.frameId() & 0x20000000) { return true; } QMQTT::Message msg; QByteArray bytes; msg.setTopic(topicName + "/s/" + QString::number(frame.frameId())); uint8_t flags = 0; if (frame.hasExtendedFrameFormat()) flags += 1; if (frame.frameType() == QCanBusFrame::RemoteRequestFrame) flags += 2; if (frame.hasFlexibleDataRateFormat()) flags += 4; if (frame.frameType() == QCanBusFrame::ErrorFrame) flags += 8; uint64_t micros = QDateTime::currentMSecsSinceEpoch() * 1000ull; for (int x = 0; x < 8; x++) { bytes.append(micros & 0xFF); micros = micros / 256; } bytes.append(flags); bytes.append(frame.payload()); msg.setPayload(bytes); mqttClient->publish(msg); return true; } /****************************************************************/ void MQTT_BUS::readSettings() { QSettings settings; } void MQTT_BUS::clientMessageReceived(const QMQTT::Message& message) { uint64_t timeBasis = CANConManager::getInstance()->getTimeBasis(); /* drop frame if capture is suspended */ if(isCapSuspended()) return; CANFrame* frame_p = getQueue().get(); if(frame_p) { uint32_t frameID = message.topic().split("/")[1].toInt(); uint64_t timeStamp = message.payload()[0] + (message.payload()[1] << 8) + (message.payload()[2] << 16) + (message.payload()[3] << 24) + ((uint64_t)message.payload()[4] << 32ull) + ((uint64_t)message.payload()[5] << 40ull) + ((uint64_t)message.payload()[6] << 48ull) + ((uint64_t)message.payload()[7] << 56ull); int flags = message.payload()[8]; frame_p->setPayload(message.payload().right(message.payload().count() - 9)); frame_p->bus = 0; frame_p->setExtendedFrameFormat(flags & 1); frame_p->setFrameId(frameID); frame_p->setFrameType(QCanBusFrame::DataFrame); frame_p->isReceived = true; if (useSystemTime) { frame_p->setTimeStamp(QCanBusFrame::TimeStamp(0, QDateTime::currentMSecsSinceEpoch() * 1000ul)); } else frame_p->setTimeStamp(QCanBusFrame::TimeStamp(0, timeStamp)); checkTargettedFrame(*frame_p); /* enqueue frame */ getQueue().queue(); } } void MQTT_BUS::clientConnected() { sendDebug("Connecting to MQTT Broker!"); mqttClient->subscribe(topicName + "/+", 0); //subscribe to all sub topics to grab the frames. connect(mqttClient, &QMQTT::Client::received, this, &MQTT_BUS::clientMessageReceived); setStatus(CANCon::CONNECTED); CANConStatus stats; stats.conStatus = getStatus(); stats.numHardwareBuses = 1;//mNumBuses; emit status(stats); } void MQTT_BUS::disconnectDevice() { setStatus(CANCon::NOT_CONNECTED); CANConStatus stats; stats.conStatus = getStatus(); stats.numHardwareBuses = mNumBuses; emit status(stats); } void MQTT_BUS::rebuildLocalTimeBasis() { //qDebug() << "Rebuilding GVRET time base. GVRET local base = " << buildTimeBasis; /* our time basis is the value we have to modulate the main system basis by in order to sync the GVRET timestamps to the rest of the system. The rest of the system uses CANConManager::getInstance()->getTimeBasis as the basis. GVRET returns to us the current time since boot up in microseconds. timeAtGVRETSync stores the "system" timestamp when the GVRET timestamp was retrieved. */ /* lastSystemTimeBasis = CANConManager::getInstance()->getTimeBasis(); int64_t systemDelta = timeAtGVRETSync - lastSystemTimeBasis; int32_t localDelta = buildTimeBasis - systemDelta; timeBasis = -localDelta; */ } <|endoftext|>
<commit_before>/* * CampKitMenuComponent * * Created on: 12/1/2012 * Author: kyle */ #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/managers/structure/StructureManager.h" #include "server/zone/managers/planet/PlanetManager.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/Zone.h" #include "CampKitMenuComponent.h" #include "server/zone/objects/scene/components/ObjectMenuComponent.h" #include "server/zone/packets/object/ObjectMenuResponse.h" #include "server/zone/packets/player/PlayMusicMessage.h" #include "server/zone/packets/object/PlayClientEffectObjectMessage.h" #include "server/zone/packets/scene/PlayClientEffectLocMessage.h" #include "server/zone/objects/structure/StructureObject.h" #include "server/zone/templates/tangible/CampKitTemplate.h" #include "server/zone/templates/tangible/CampStructureTemplate.h" #include "server/zone/objects/area/CampSiteActiveArea.h" #include "server/zone/objects/tangible/terminal/Terminal.h" void CampKitMenuComponent::fillObjectMenuResponse(SceneObject* sceneObject, ObjectMenuResponse* menuResponse, CreatureObject* player) { if (!sceneObject->isCampKit()) return; TangibleObjectMenuComponent::fillObjectMenuResponse(sceneObject, menuResponse, player); } int CampKitMenuComponent::handleObjectMenuSelect(SceneObject* sceneObject, CreatureObject* player, byte selectedID) { if (!sceneObject->isTangibleObject()) return 0; if (!player->isPlayerCreature()) return 0; if (selectedID == 20) { /// Get Camp Kit Template SharedObjectTemplate* templateData = TemplateManager::instance()->getTemplate( sceneObject->getServerObjectCRC()); if (templateData == NULL) { error("No template for: " + sceneObject->getServerObjectCRC()); return 0; } CampKitTemplate* campKitData = cast<CampKitTemplate*> (templateData); if (campKitData == NULL) { error("No CampKitTemplate for: " + sceneObject->getServerObjectCRC()); return 0; } /// Get Camp Template templateData = TemplateManager::instance()->getTemplate(campKitData->getSpawnObjectTemplate().hashCode()); CampStructureTemplate* campStructureData = cast<CampStructureTemplate*> (templateData); if (campStructureData == NULL) { error("No CampStructureTemplate for: " + campKitData->getSpawnObjectTemplate()); return 0; } ManagedReference<ZoneServer*> zoneServer = player->getZoneServer(); if (zoneServer == NULL) { error("ZoneServer is null when trying to create camp"); return 0; } ManagedReference<Zone*> zone = player->getZone(); if (zone == NULL) { error("Zone is null when trying to create camp"); return 0; } ManagedReference<PlanetManager*> planetManager = zone->getPlanetManager(); if (planetManager == NULL) { error("Unable to get PlanetManager when placing camp"); return 0; } ManagedReference<StructureManager*> structureManager = zone->getStructureManager(); if (structureManager == NULL) { error("Unable to get StructureManager when placing camp"); return 0; } /// Get Ghost PlayerObject* ghost = cast<PlayerObject*> (player->getSlottedObject("ghost")); if (ghost == NULL) { error("PlayerCreature has no ghost: " + player->getObjectID()); return 0; } // int playerSkill = player->getSkillMod("camp"); // if(playerSkill < campStructureData->getSkillRequired()) { // player->sendSystemMessage("camp", "sys_nsf_skill"); // return 0; // } if(player->isInCombat()) { player->sendSystemMessage("camp", "sys_not_in_combat"); return 0; } if(player->getParent() != NULL && player->getParent()->isCellObject()) { player->sendSystemMessage("camp", "error_inside"); return 0; } if(!sceneObject->isASubChildOf(player)) { player->sendSystemMessage("camp", "sys_not_in_inventory"); return 0; } if(!player->isStanding()) { player->sendSystemMessage("camp", "error_cmd_fail"); return 0; } if(planetManager->getRegion(player->getPositionX(), player->getPositionY()) != NULL) { player->sendSystemMessage("camp", "error_muni_true"); return 0; } /// Check for water if(player->isSwimming() || player->isInWater()) { player->sendSystemMessage("camp", "error_in_water"); return 0; } /// Make sure player doesn't already have a camp setup somewhere else for (int i = 0; i < ghost->getTotalOwnedStructureCount(); ++i) { if (ghost->getOwnedStructure(i)->isCampStructure()) { player->sendSystemMessage("camp", "sys_already_camping"); return 0; } } /// Check if player is in another camp if(player->getCurrentCamp() != NULL) { player->sendSystemMessage("camp", "error_camp_exists"); return 0; } /// Check camps/lairs nearby SortedVector<ManagedReference<QuadTreeEntry* > > nearbyObjects; zone->getInRangeObjects(player->getPositionX(), player->getPositionY(), 512, &nearbyObjects); for(int i = 0; i < nearbyObjects.size(); ++i) { SceneObject* scno = cast<SceneObject*>(nearbyObjects.get(i).get()); if (scno != NULL && scno->isCampStructure() && scno->getDistanceTo( player) <= scno->getObjectTemplate()->getNoBuildRadius()) { player->sendSystemMessage("camp", "error_camp_too_close"); return 0; } if (scno != NULL && scno->isBuildingObject() && scno->getDistanceTo( player) <= scno->getObjectTemplate()->getNoBuildRadius()) { player->sendSystemMessage("camp", "error_building_too_close"); return 0; } if(scno != NULL && scno->getObserverCount(ObserverEventType::OBJECTDESTRUCTION) > 0 && scno->getDistanceTo(player) <= scno->getObjectTemplate()->getNoBuildRadius()) { SortedVector<ManagedReference<Observer* > >* observers = scno->getObservers(ObserverEventType::OBJECTDESTRUCTION); for(int j = 0; j < observers->size(); ++j) { if(observers->get(j)->isObserverType(ObserverType::LAIR)) { player->sendSystemMessage("camp", "error_lair_too_close"); return 0; } } } } /// No Builds //if (!planetManager->isBuildingPermittedAt(player->getPositionX(), player->getPositionY(), player)) { // player->sendSystemMessage("camp", "error_nobuild"); // return 0; //} player->sendSystemMessage("camp", "starting_camp"); /// Create Structure StructureObject* structureObject = structureManager->placeStructure( player, campKitData->getSpawnObjectTemplate(), player->getPositionX(), player->getPositionY(), (int) player->getDirectionAngle()); if (structureObject == NULL) { error("Unable to create camp: " + campKitData->getSpawnObjectTemplate()); return 0; } /// Identify terminal for Active area Terminal* campTerminal = NULL; SortedVector < ManagedReference<SceneObject*> > *childObjects = structureObject->getChildObjects(); for (int i = 0; i < childObjects->size(); ++i) { if (childObjects->get(i)->isTerminal()) { campTerminal = cast<Terminal*> (childObjects->get(i).get()); break; } } if (campTerminal == NULL) { error("Camp does not have terminal: " + campStructureData->getTemplateFileName()); return 0; } String campName = player->getFirstName(); if(!player->getLastName().isEmpty()) campName += " " + player->getLastName(); campName += "'s Camp"; campTerminal->setCustomObjectName(campName, true); /// Create active area String areaPath = "object/camp_area.iff"; ManagedReference<CampSiteActiveArea*> campArea = cast< CampSiteActiveArea*> (zoneServer->createObject( areaPath.hashCode(), 1)); campArea->init(campStructureData); campArea->setTerminal(campTerminal); campArea->setCamp(structureObject); campArea->setOwner(player); campArea->setNoBuildArea(true); campArea->initializePosition(player->getPositionX(), 0, player->getPositionY()); zone->transferObject(campArea, -1, false); structureObject->addActiveArea(campArea); ghost->addOwnedStructure(structureObject); player->sendSystemMessage("camp", "camp_complete"); /// Remove Camp TangibleObject* tano = cast<TangibleObject*>(sceneObject); if(tano != NULL) tano->decreaseUseCount(player); return 0; } else return TangibleObjectMenuComponent::handleObjectMenuSelect(sceneObject, player, selectedID); return 0; } <commit_msg>[fixed] stability issues<commit_after>/* * CampKitMenuComponent * * Created on: 12/1/2012 * Author: kyle */ #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/managers/structure/StructureManager.h" #include "server/zone/managers/planet/PlanetManager.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/Zone.h" #include "CampKitMenuComponent.h" #include "server/zone/objects/scene/components/ObjectMenuComponent.h" #include "server/zone/packets/object/ObjectMenuResponse.h" #include "server/zone/packets/player/PlayMusicMessage.h" #include "server/zone/packets/object/PlayClientEffectObjectMessage.h" #include "server/zone/packets/scene/PlayClientEffectLocMessage.h" #include "server/zone/objects/structure/StructureObject.h" #include "server/zone/templates/tangible/CampKitTemplate.h" #include "server/zone/templates/tangible/CampStructureTemplate.h" #include "server/zone/objects/area/CampSiteActiveArea.h" #include "server/zone/objects/tangible/terminal/Terminal.h" void CampKitMenuComponent::fillObjectMenuResponse(SceneObject* sceneObject, ObjectMenuResponse* menuResponse, CreatureObject* player) { if (!sceneObject->isCampKit()) return; TangibleObjectMenuComponent::fillObjectMenuResponse(sceneObject, menuResponse, player); } int CampKitMenuComponent::handleObjectMenuSelect(SceneObject* sceneObject, CreatureObject* player, byte selectedID) { if (!sceneObject->isTangibleObject()) return 0; if (!player->isPlayerCreature()) return 0; if (player->getZone() == NULL) return 0; if (selectedID == 20) { /// Get Camp Kit Template SharedObjectTemplate* templateData = TemplateManager::instance()->getTemplate( sceneObject->getServerObjectCRC()); if (templateData == NULL) { error("No template for: " + sceneObject->getServerObjectCRC()); return 0; } CampKitTemplate* campKitData = cast<CampKitTemplate*> (templateData); if (campKitData == NULL) { error("No CampKitTemplate for: " + sceneObject->getServerObjectCRC()); return 0; } /// Get Camp Template templateData = TemplateManager::instance()->getTemplate(campKitData->getSpawnObjectTemplate().hashCode()); CampStructureTemplate* campStructureData = cast<CampStructureTemplate*> (templateData); if (campStructureData == NULL) { error("No CampStructureTemplate for: " + campKitData->getSpawnObjectTemplate()); return 0; } ManagedReference<ZoneServer*> zoneServer = player->getZoneServer(); if (zoneServer == NULL) { error("ZoneServer is null when trying to create camp"); return 0; } ManagedReference<Zone*> zone = player->getZone(); if (zone == NULL) { error("Zone is null when trying to create camp"); return 0; } ManagedReference<PlanetManager*> planetManager = zone->getPlanetManager(); if (planetManager == NULL) { error("Unable to get PlanetManager when placing camp"); return 0; } ManagedReference<StructureManager*> structureManager = zone->getStructureManager(); if (structureManager == NULL) { error("Unable to get StructureManager when placing camp"); return 0; } /// Get Ghost PlayerObject* ghost = cast<PlayerObject*> (player->getSlottedObject("ghost")); if (ghost == NULL) { error("PlayerCreature has no ghost: " + player->getObjectID()); return 0; } // int playerSkill = player->getSkillMod("camp"); // if(playerSkill < campStructureData->getSkillRequired()) { // player->sendSystemMessage("camp", "sys_nsf_skill"); // return 0; // } if(player->isInCombat()) { player->sendSystemMessage("camp", "sys_not_in_combat"); return 0; } if(player->getParent() != NULL && player->getParent()->isCellObject()) { player->sendSystemMessage("camp", "error_inside"); return 0; } if(!sceneObject->isASubChildOf(player)) { player->sendSystemMessage("camp", "sys_not_in_inventory"); return 0; } if(!player->isStanding()) { player->sendSystemMessage("camp", "error_cmd_fail"); return 0; } if(planetManager->getRegion(player->getPositionX(), player->getPositionY()) != NULL) { player->sendSystemMessage("camp", "error_muni_true"); return 0; } /// Check for water if(player->isSwimming() || player->isInWater()) { player->sendSystemMessage("camp", "error_in_water"); return 0; } /// Make sure player doesn't already have a camp setup somewhere else for (int i = 0; i < ghost->getTotalOwnedStructureCount(); ++i) { if (ghost->getOwnedStructure(i)->isCampStructure()) { player->sendSystemMessage("camp", "sys_already_camping"); return 0; } } /// Check if player is in another camp if(player->getCurrentCamp() != NULL) { player->sendSystemMessage("camp", "error_camp_exists"); return 0; } /// Check camps/lairs nearby SortedVector<ManagedReference<QuadTreeEntry* > > nearbyObjects; zone->getInRangeObjects(player->getPositionX(), player->getPositionY(), 512, &nearbyObjects); for(int i = 0; i < nearbyObjects.size(); ++i) { SceneObject* scno = cast<SceneObject*>(nearbyObjects.get(i).get()); if (scno != NULL && scno->isCampStructure() && scno->getDistanceTo( player) <= scno->getObjectTemplate()->getNoBuildRadius()) { player->sendSystemMessage("camp", "error_camp_too_close"); return 0; } if (scno != NULL && scno->isBuildingObject() && scno->getDistanceTo( player) <= scno->getObjectTemplate()->getNoBuildRadius()) { player->sendSystemMessage("camp", "error_building_too_close"); return 0; } if(scno != NULL && scno->getObserverCount(ObserverEventType::OBJECTDESTRUCTION) > 0 && scno->getDistanceTo(player) <= scno->getObjectTemplate()->getNoBuildRadius()) { SortedVector<ManagedReference<Observer* > >* observers = scno->getObservers(ObserverEventType::OBJECTDESTRUCTION); for(int j = 0; j < observers->size(); ++j) { if(observers->get(j)->isObserverType(ObserverType::LAIR)) { player->sendSystemMessage("camp", "error_lair_too_close"); return 0; } } } } /// No Builds //if (!planetManager->isBuildingPermittedAt(player->getPositionX(), player->getPositionY(), player)) { // player->sendSystemMessage("camp", "error_nobuild"); // return 0; //} player->sendSystemMessage("camp", "starting_camp"); /// Create Structure StructureObject* structureObject = structureManager->placeStructure( player, campKitData->getSpawnObjectTemplate(), player->getPositionX(), player->getPositionY(), (int) player->getDirectionAngle()); if (structureObject == NULL) { error("Unable to create camp: " + campKitData->getSpawnObjectTemplate()); return 0; } /// Identify terminal for Active area Terminal* campTerminal = NULL; SortedVector < ManagedReference<SceneObject*> > *childObjects = structureObject->getChildObjects(); for (int i = 0; i < childObjects->size(); ++i) { if (childObjects->get(i)->isTerminal()) { campTerminal = cast<Terminal*> (childObjects->get(i).get()); break; } } if (campTerminal == NULL) { error("Camp does not have terminal: " + campStructureData->getTemplateFileName()); return 0; } String campName = player->getFirstName(); if(!player->getLastName().isEmpty()) campName += " " + player->getLastName(); campName += "'s Camp"; campTerminal->setCustomObjectName(campName, true); /// Create active area String areaPath = "object/camp_area.iff"; ManagedReference<CampSiteActiveArea*> campArea = cast< CampSiteActiveArea*> (zoneServer->createObject( areaPath.hashCode(), 1)); campArea->init(campStructureData); campArea->setTerminal(campTerminal); campArea->setCamp(structureObject); campArea->setOwner(player); campArea->setNoBuildArea(true); campArea->initializePosition(player->getPositionX(), 0, player->getPositionY()); zone->transferObject(campArea, -1, false); structureObject->addActiveArea(campArea); ghost->addOwnedStructure(structureObject); player->sendSystemMessage("camp", "camp_complete"); /// Remove Camp TangibleObject* tano = cast<TangibleObject*>(sceneObject); if(tano != NULL) tano->decreaseUseCount(player); return 0; } else return TangibleObjectMenuComponent::handleObjectMenuSelect(sceneObject, player, selectedID); return 0; } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkXnatConnectionPreferencePage.h" #include "QmitkXnatTreeBrowserView.h" #include "org_mitk_gui_qt_xnatinterface_Activator.h" #include "berryIPreferencesService.h" #include "berryPlatform.h" #include <QFileDialog> #include <QLabel> #include <QPushButton> #include <QLineEdit> #include <QGridLayout> #include <QMessageBox> #include <QApplication> #include <QMap> #include "ctkXnatSession.h" #include "ctkXnatLoginProfile.h" #include "ctkXnatException.h" #include <mitkIOUtil.h> using namespace berry; QmitkXnatConnectionPreferencePage::QmitkXnatConnectionPreferencePage() : m_Control(0) { } void QmitkXnatConnectionPreferencePage::Init(berry::IWorkbench::Pointer) { } void QmitkXnatConnectionPreferencePage::CreateQtControl(QWidget* parent) { IPreferencesService* prefService = Platform::GetPreferencesService(); berry::IPreferences::Pointer _XnatConnectionPreferencesNode = prefService->GetSystemPreferences()->Node(QmitkXnatTreeBrowserView::VIEW_ID); m_XnatConnectionPreferencesNode = _XnatConnectionPreferencesNode; m_Controls.setupUi(parent); m_Control = new QWidget(parent); m_Control->setLayout(m_Controls.gridLayout); ctkXnatSession* session; try { session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference<ctkXnatSession>()); } catch (std::invalid_argument) { session = nullptr; } if (session != nullptr && session->isOpen()) { m_Controls.xnatTestConnectionLabel->setStyleSheet("QLabel { color: green; }"); m_Controls.xnatTestConnectionLabel->setText("Already connected."); m_Controls.xnatTestConnectionButton->setEnabled(false); } const QIntValidator *portV = new QIntValidator(0, 65535, parent); m_Controls.inXnatPort->setValidator(portV); const QRegExp hostRx("^(https?)://[^ /](\\S)+$"); const QRegExpValidator *hostV = new QRegExpValidator(hostRx, parent); m_Controls.inXnatHostAddress->setValidator(hostV); connect(m_Controls.xnatTestConnectionButton, SIGNAL(clicked()), this, SLOT(TestConnection())); connect(m_Controls.inXnatHostAddress, SIGNAL(editingFinished()), this, SLOT(UrlChanged())); connect(m_Controls.inXnatDownloadPath, SIGNAL(editingFinished()), this, SLOT(DownloadPathChanged())); connect(m_Controls.cbUseNetworkProxy, SIGNAL(toggled(bool)), this, SLOT(onUseNetworkProxy(bool))); connect(m_Controls.btnDownloadPath, SIGNAL(clicked()), this, SLOT(OnDownloadPathButtonClicked())); m_Controls.groupBoxProxySettings->setVisible(m_Controls.cbUseNetworkProxy->isChecked()); this->Update(); } QWidget* QmitkXnatConnectionPreferencePage::GetQtControl() const { return m_Control; } bool QmitkXnatConnectionPreferencePage::PerformOk() { if (!UserInformationEmpty()) { IPreferences::Pointer _XnatConnectionPreferencesNode = m_XnatConnectionPreferencesNode.Lock(); if (_XnatConnectionPreferencesNode.IsNotNull()) { _XnatConnectionPreferencesNode->Put(m_Controls.xnatHostAddressLabel->text(), m_Controls.inXnatHostAddress->text()); _XnatConnectionPreferencesNode->Put(m_Controls.xnatPortLabel->text(), m_Controls.inXnatPort->text()); _XnatConnectionPreferencesNode->Put(m_Controls.xnatUsernameLabel->text(), m_Controls.inXnatUsername->text()); _XnatConnectionPreferencesNode->Put(m_Controls.xnatPasswortLabel->text(), m_Controls.inXnatPassword->text()); _XnatConnectionPreferencesNode->Put(m_Controls.xnatDownloadPathLabel->text(), m_Controls.inXnatDownloadPath->text()); // Network proxy settings _XnatConnectionPreferencesNode->PutBool(m_Controls.cbUseNetworkProxy->text(), m_Controls.cbUseNetworkProxy->isChecked()); _XnatConnectionPreferencesNode->Put(m_Controls.proxyAddressLabel->text(), m_Controls.inProxyAddress->text()); _XnatConnectionPreferencesNode->Put(m_Controls.proxyPortLabel->text(), m_Controls.inProxyPort->text()); _XnatConnectionPreferencesNode->Put(m_Controls.proxyUsernameLabel->text(), m_Controls.inProxyUsername->text()); _XnatConnectionPreferencesNode->Put(m_Controls.proxyPasswordLabel->text(), m_Controls.inProxyPassword->text()); // Silent Mode _XnatConnectionPreferencesNode->PutBool(m_Controls.cbUseSilentMode->text(), m_Controls.cbUseSilentMode->isChecked()); //Write _XnatConnectionPreferencesNode->Flush(); return true; } } else { QMessageBox::critical(QApplication::activeWindow(), "Saving Preferences failed", "The connection parameters in XNAT Preferences were empty.\nPlease use the 'Connect' button to validate the connection parameters."); } return false; } void QmitkXnatConnectionPreferencePage::PerformCancel() { } bool QmitkXnatConnectionPreferencePage::UserInformationEmpty() { // To check empty QLineEdits in the following QString errString; if (m_Controls.inXnatHostAddress->text().isEmpty()) { errString += "Server Address is empty.\n"; } if (m_Controls.inXnatUsername->text().isEmpty()) { errString += "Username is empty.\n"; } if (m_Controls.inXnatPassword->text().isEmpty()) { errString += "Password is empty.\n"; } // if something is empty if (!errString.isEmpty()) { m_Controls.xnatTestConnectionLabel->setStyleSheet("QLabel { color: red; }"); m_Controls.xnatTestConnectionLabel->setText("Connecting failed.\n" + errString); return true; } else { return false; } } void QmitkXnatConnectionPreferencePage::Update() { IPreferences::Pointer _XnatConnectionPreferencesNode = m_XnatConnectionPreferencesNode.Lock(); if (_XnatConnectionPreferencesNode.IsNotNull()) { m_Controls.inXnatHostAddress->setText(_XnatConnectionPreferencesNode->Get( m_Controls.xnatHostAddressLabel->text(), m_Controls.inXnatHostAddress->text())); m_Controls.inXnatPort->setText(_XnatConnectionPreferencesNode->Get( m_Controls.xnatPortLabel->text(), m_Controls.inXnatPort->text())); m_Controls.inXnatUsername->setText(_XnatConnectionPreferencesNode->Get( m_Controls.xnatUsernameLabel->text(), m_Controls.inXnatUsername->text())); m_Controls.inXnatPassword->setText(_XnatConnectionPreferencesNode->Get( m_Controls.xnatPasswortLabel->text(), m_Controls.inXnatPassword->text())); m_Controls.inXnatDownloadPath->setText(_XnatConnectionPreferencesNode->Get( m_Controls.xnatDownloadPathLabel->text(), m_Controls.inXnatDownloadPath->text())); // Network proxy settings m_Controls.cbUseNetworkProxy->setChecked(_XnatConnectionPreferencesNode->GetBool( m_Controls.cbUseNetworkProxy->text(), false)); m_Controls.inProxyAddress->setText(_XnatConnectionPreferencesNode->Get( m_Controls.proxyAddressLabel->text(), m_Controls.inProxyAddress->text())); m_Controls.inProxyPort->setText(_XnatConnectionPreferencesNode->Get( m_Controls.proxyPortLabel->text(), m_Controls.inProxyPort->text())); m_Controls.inProxyUsername->setText(_XnatConnectionPreferencesNode->Get( m_Controls.proxyUsernameLabel->text(), m_Controls.inProxyUsername->text())); m_Controls.inProxyPassword->setText(_XnatConnectionPreferencesNode->Get( m_Controls.proxyPasswordLabel->text(), m_Controls.inProxyPassword->text())); // Silent Mode m_Controls.cbUseSilentMode->setChecked(_XnatConnectionPreferencesNode->GetBool( m_Controls.cbUseSilentMode->text(), false)); } } void QmitkXnatConnectionPreferencePage::UrlChanged() { m_Controls.inXnatHostAddress->setStyleSheet("QLineEdit { background-color: white; }"); QString str = m_Controls.inXnatHostAddress->text(); while (str.endsWith("/")) { str = str.left(str.length() - 1); } m_Controls.inXnatHostAddress->setText(str); QUrl url(m_Controls.inXnatHostAddress->text()); if (!url.isValid()) { m_Controls.inXnatHostAddress->setStyleSheet("QLineEdit { background-color: red; }"); } } void QmitkXnatConnectionPreferencePage::DownloadPathChanged() { m_Controls.inXnatDownloadPath->setStyleSheet("QLineEdit { background-color: white; }"); QString downloadPath = m_Controls.inXnatDownloadPath->text(); if (!downloadPath.isEmpty()) { if (downloadPath.lastIndexOf("/") != downloadPath.size() - 1) { downloadPath.append("/"); m_Controls.inXnatDownloadPath->setText(downloadPath); } QFileInfo path(m_Controls.inXnatDownloadPath->text()); if (!path.isDir()) { m_Controls.inXnatDownloadPath->setStyleSheet("QLineEdit { background-color: red; }"); } } } void QmitkXnatConnectionPreferencePage::onUseNetworkProxy(bool status) { m_Controls.groupBoxProxySettings->setVisible(status); } void QmitkXnatConnectionPreferencePage::OnDownloadPathButtonClicked() { QString dir = QFileDialog::getExistingDirectory(); if (!dir.endsWith("/") || !dir.endsWith("\\")) dir.append("/"); m_Controls.inXnatDownloadPath->setText(dir); } void QmitkXnatConnectionPreferencePage::TestConnection() { ctkXnatSession* session = 0; try { session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference<ctkXnatSession>()); } catch (std::invalid_argument) { if (!UserInformationEmpty()) { PerformOk(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CreateXnatSession(); session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference<ctkXnatSession>()); } } try { mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->OpenXnatSession(); m_Controls.xnatTestConnectionLabel->setStyleSheet("QLabel { color: green; }"); m_Controls.xnatTestConnectionLabel->setText("Connecting successful."); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); } catch (const ctkXnatAuthenticationException& auth) { m_Controls.xnatTestConnectionLabel->setStyleSheet("QLabel { color: red; }"); m_Controls.xnatTestConnectionLabel->setText("Connecting failed:\nAuthentication error."); MITK_INFO << auth.message().toStdString(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); } catch (const ctkException& e) { m_Controls.xnatTestConnectionLabel->setStyleSheet("QLabel { color: red; }"); m_Controls.xnatTestConnectionLabel->setText("Connecting failed:\nInvalid Server Adress"); MITK_INFO << e.message().toStdString(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); } } <commit_msg>Add hint about missing OpenSSL<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkXnatConnectionPreferencePage.h" #include "QmitkXnatTreeBrowserView.h" #include "org_mitk_gui_qt_xnatinterface_Activator.h" #include "berryIPreferencesService.h" #include "berryPlatform.h" #include <QFileDialog> #include <QLabel> #include <QPushButton> #include <QLineEdit> #include <QGridLayout> #include <QMessageBox> #include <QApplication> #include <QMap> #include "ctkXnatSession.h" #include "ctkXnatLoginProfile.h" #include "ctkXnatException.h" #include <mitkIOUtil.h> using namespace berry; QmitkXnatConnectionPreferencePage::QmitkXnatConnectionPreferencePage() : m_Control(0) { } void QmitkXnatConnectionPreferencePage::Init(berry::IWorkbench::Pointer) { } void QmitkXnatConnectionPreferencePage::CreateQtControl(QWidget* parent) { IPreferencesService* prefService = Platform::GetPreferencesService(); berry::IPreferences::Pointer _XnatConnectionPreferencesNode = prefService->GetSystemPreferences()->Node(QmitkXnatTreeBrowserView::VIEW_ID); m_XnatConnectionPreferencesNode = _XnatConnectionPreferencesNode; m_Controls.setupUi(parent); m_Control = new QWidget(parent); m_Control->setLayout(m_Controls.gridLayout); ctkXnatSession* session; try { session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference<ctkXnatSession>()); } catch (std::invalid_argument) { session = nullptr; } if (session != nullptr && session->isOpen()) { m_Controls.xnatTestConnectionLabel->setStyleSheet("QLabel { color: green; }"); m_Controls.xnatTestConnectionLabel->setText("Already connected."); m_Controls.xnatTestConnectionButton->setEnabled(false); } const QIntValidator *portV = new QIntValidator(0, 65535, parent); m_Controls.inXnatPort->setValidator(portV); const QRegExp hostRx("^(https?)://[^ /](\\S)+$"); const QRegExpValidator *hostV = new QRegExpValidator(hostRx, parent); m_Controls.inXnatHostAddress->setValidator(hostV); connect(m_Controls.xnatTestConnectionButton, SIGNAL(clicked()), this, SLOT(TestConnection())); connect(m_Controls.inXnatHostAddress, SIGNAL(editingFinished()), this, SLOT(UrlChanged())); connect(m_Controls.inXnatDownloadPath, SIGNAL(editingFinished()), this, SLOT(DownloadPathChanged())); connect(m_Controls.cbUseNetworkProxy, SIGNAL(toggled(bool)), this, SLOT(onUseNetworkProxy(bool))); connect(m_Controls.btnDownloadPath, SIGNAL(clicked()), this, SLOT(OnDownloadPathButtonClicked())); m_Controls.groupBoxProxySettings->setVisible(m_Controls.cbUseNetworkProxy->isChecked()); this->Update(); } QWidget* QmitkXnatConnectionPreferencePage::GetQtControl() const { return m_Control; } bool QmitkXnatConnectionPreferencePage::PerformOk() { if (!UserInformationEmpty()) { IPreferences::Pointer _XnatConnectionPreferencesNode = m_XnatConnectionPreferencesNode.Lock(); if (_XnatConnectionPreferencesNode.IsNotNull()) { _XnatConnectionPreferencesNode->Put(m_Controls.xnatHostAddressLabel->text(), m_Controls.inXnatHostAddress->text()); _XnatConnectionPreferencesNode->Put(m_Controls.xnatPortLabel->text(), m_Controls.inXnatPort->text()); _XnatConnectionPreferencesNode->Put(m_Controls.xnatUsernameLabel->text(), m_Controls.inXnatUsername->text()); _XnatConnectionPreferencesNode->Put(m_Controls.xnatPasswortLabel->text(), m_Controls.inXnatPassword->text()); _XnatConnectionPreferencesNode->Put(m_Controls.xnatDownloadPathLabel->text(), m_Controls.inXnatDownloadPath->text()); // Network proxy settings _XnatConnectionPreferencesNode->PutBool(m_Controls.cbUseNetworkProxy->text(), m_Controls.cbUseNetworkProxy->isChecked()); _XnatConnectionPreferencesNode->Put(m_Controls.proxyAddressLabel->text(), m_Controls.inProxyAddress->text()); _XnatConnectionPreferencesNode->Put(m_Controls.proxyPortLabel->text(), m_Controls.inProxyPort->text()); _XnatConnectionPreferencesNode->Put(m_Controls.proxyUsernameLabel->text(), m_Controls.inProxyUsername->text()); _XnatConnectionPreferencesNode->Put(m_Controls.proxyPasswordLabel->text(), m_Controls.inProxyPassword->text()); // Silent Mode _XnatConnectionPreferencesNode->PutBool(m_Controls.cbUseSilentMode->text(), m_Controls.cbUseSilentMode->isChecked()); //Write _XnatConnectionPreferencesNode->Flush(); return true; } } else { QMessageBox::critical(QApplication::activeWindow(), "Saving Preferences failed", "The connection parameters in XNAT Preferences were empty.\nPlease use the 'Connect' button to validate the connection parameters."); } return false; } void QmitkXnatConnectionPreferencePage::PerformCancel() { } bool QmitkXnatConnectionPreferencePage::UserInformationEmpty() { // To check empty QLineEdits in the following QString errString; if (m_Controls.inXnatHostAddress->text().isEmpty()) { errString += "Server Address is empty.\n"; } if (m_Controls.inXnatUsername->text().isEmpty()) { errString += "Username is empty.\n"; } if (m_Controls.inXnatPassword->text().isEmpty()) { errString += "Password is empty.\n"; } // if something is empty if (!errString.isEmpty()) { m_Controls.xnatTestConnectionLabel->setStyleSheet("QLabel { color: red; }"); m_Controls.xnatTestConnectionLabel->setText("Connecting failed.\n" + errString); return true; } else { return false; } } void QmitkXnatConnectionPreferencePage::Update() { IPreferences::Pointer _XnatConnectionPreferencesNode = m_XnatConnectionPreferencesNode.Lock(); if (_XnatConnectionPreferencesNode.IsNotNull()) { m_Controls.inXnatHostAddress->setText(_XnatConnectionPreferencesNode->Get( m_Controls.xnatHostAddressLabel->text(), m_Controls.inXnatHostAddress->text())); m_Controls.inXnatPort->setText(_XnatConnectionPreferencesNode->Get( m_Controls.xnatPortLabel->text(), m_Controls.inXnatPort->text())); m_Controls.inXnatUsername->setText(_XnatConnectionPreferencesNode->Get( m_Controls.xnatUsernameLabel->text(), m_Controls.inXnatUsername->text())); m_Controls.inXnatPassword->setText(_XnatConnectionPreferencesNode->Get( m_Controls.xnatPasswortLabel->text(), m_Controls.inXnatPassword->text())); m_Controls.inXnatDownloadPath->setText(_XnatConnectionPreferencesNode->Get( m_Controls.xnatDownloadPathLabel->text(), m_Controls.inXnatDownloadPath->text())); // Network proxy settings m_Controls.cbUseNetworkProxy->setChecked(_XnatConnectionPreferencesNode->GetBool( m_Controls.cbUseNetworkProxy->text(), false)); m_Controls.inProxyAddress->setText(_XnatConnectionPreferencesNode->Get( m_Controls.proxyAddressLabel->text(), m_Controls.inProxyAddress->text())); m_Controls.inProxyPort->setText(_XnatConnectionPreferencesNode->Get( m_Controls.proxyPortLabel->text(), m_Controls.inProxyPort->text())); m_Controls.inProxyUsername->setText(_XnatConnectionPreferencesNode->Get( m_Controls.proxyUsernameLabel->text(), m_Controls.inProxyUsername->text())); m_Controls.inProxyPassword->setText(_XnatConnectionPreferencesNode->Get( m_Controls.proxyPasswordLabel->text(), m_Controls.inProxyPassword->text())); // Silent Mode m_Controls.cbUseSilentMode->setChecked(_XnatConnectionPreferencesNode->GetBool( m_Controls.cbUseSilentMode->text(), false)); } } void QmitkXnatConnectionPreferencePage::UrlChanged() { m_Controls.inXnatHostAddress->setStyleSheet("QLineEdit { background-color: white; }"); QString str = m_Controls.inXnatHostAddress->text(); while (str.endsWith("/")) { str = str.left(str.length() - 1); } m_Controls.inXnatHostAddress->setText(str); QUrl url(m_Controls.inXnatHostAddress->text()); if (!url.isValid()) { m_Controls.inXnatHostAddress->setStyleSheet("QLineEdit { background-color: red; }"); } } void QmitkXnatConnectionPreferencePage::DownloadPathChanged() { m_Controls.inXnatDownloadPath->setStyleSheet("QLineEdit { background-color: white; }"); QString downloadPath = m_Controls.inXnatDownloadPath->text(); if (!downloadPath.isEmpty()) { if (downloadPath.lastIndexOf("/") != downloadPath.size() - 1) { downloadPath.append("/"); m_Controls.inXnatDownloadPath->setText(downloadPath); } QFileInfo path(m_Controls.inXnatDownloadPath->text()); if (!path.isDir()) { m_Controls.inXnatDownloadPath->setStyleSheet("QLineEdit { background-color: red; }"); } } } void QmitkXnatConnectionPreferencePage::onUseNetworkProxy(bool status) { m_Controls.groupBoxProxySettings->setVisible(status); } void QmitkXnatConnectionPreferencePage::OnDownloadPathButtonClicked() { QString dir = QFileDialog::getExistingDirectory(); if (!dir.endsWith("/") || !dir.endsWith("\\")) dir.append("/"); m_Controls.inXnatDownloadPath->setText(dir); } void QmitkXnatConnectionPreferencePage::TestConnection() { ctkXnatSession* session = 0; try { session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference<ctkXnatSession>()); } catch (std::invalid_argument) { if (!UserInformationEmpty()) { PerformOk(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CreateXnatSession(); session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference<ctkXnatSession>()); } } try { mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->OpenXnatSession(); m_Controls.xnatTestConnectionLabel->setStyleSheet("QLabel { color: green; }"); m_Controls.xnatTestConnectionLabel->setText("Connecting successful."); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); } catch (const ctkXnatAuthenticationException& auth) { m_Controls.xnatTestConnectionLabel->setStyleSheet("QLabel { color: red; }"); m_Controls.xnatTestConnectionLabel->setText("Connecting failed:\nAuthentication error."); MITK_INFO << auth.message().toStdString(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); } catch (const ctkException& e) { m_Controls.xnatTestConnectionLabel->setStyleSheet("QLabel { color: red; }"); m_Controls.xnatTestConnectionLabel->setText("Connecting failed:\nInvalid Server Adress\nPossibly due to missing OpenSSL for HTTPS connections"); MITK_INFO << e.message().toStdString(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); } } <|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/. #pragma once #include <aliceVision/eig33/eig33.hpp> #include <algorithm> #include <assert.h> #include <cstdlib> #include <sstream> #include <vector> #include <zlib.h> #include <iostream> #include <stdexcept> template <class T> class staticVector { std::vector<T> _data; typedef typename std::vector<T>::iterator Iterator; typedef typename std::vector<T>::const_iterator ConstIterator; public: staticVector() { } staticVector(int _allocated) { _data.reserve(_allocated); } const T& operator[](int index) const { return _data[index]; } T& operator[](int index) { return _data[index]; } void clear() { _data.clear(); } Iterator begin() { return _data.begin(); } Iterator end() { return _data.end(); } ConstIterator begin() const { return _data.begin(); } ConstIterator end() const { return _data.end(); } const std::vector<T>& getData() const { return _data; } std::vector<T>& getDataWritable() { return _data; } int size() const { return _data.size(); } bool empty() const { return _data.empty(); } size_t capacity() const { return _data.capacity(); } void reserve(int n) { _data.reserve(n); } void resize(int n) { _data.resize(n); } void resize_with(int n, const T& val) { _data.resize(n, val); } void swap( staticVector& other ) { _data.swap(other._data); } void shrink_to_fit() { _data.shrink_to_fit(); } void resizeAddIfNeeded(int nplanned, int ntoallocated) { if(size() + nplanned > capacity()) { resizeAdd(nplanned + ntoallocated); } } void resizeAdd(int ntoallocated) { _data.reserve(capacity() + ntoallocated); } void push_sorted_asc(const T& val) { _data.insert(std::lower_bound(_data.begin(), _data.end(), val), val); } void push_back(const T& val) { _data.push_back(val); } void push_front(const T& val) { _data.insert(_data.begin(), val); } void push_back_arr(staticVector<T>* arr) { _data.insert(_data.end(), arr->getData().begin(), arr->getData().end()); } void remove(int i) { _data.erase(_data.begin() + i); } int push_back_distinct(const T& val) { int id = indexOf(val); if(id == -1) _data.push_back(val); return id; } T pop() { T val = _data.back(); _data.pop_back(); return val; } int indexOf(const T& value) const { const auto it = std::find(_data.begin(), _data.end(), value); return it != _data.end() ? std::distance(_data.begin(), it) : -1; } int indexOfSorted(const T& value) const { return indexOf(value); } int indexOfNearestSorted(const T& value) const { // Retrieve the first element >= value in _data auto it = std::lower_bound(_data.begin(), _data.end(), value); if(it == _data.end()) return -1; // If we're between two values... if(it != _data.begin()) { // ...select the index of the closest value between it (>= value) and prevIt (< value) auto prevIt = std::prev(it); it = (value - *prevIt) < (*it - value) ? prevIt : it; } return std::distance(_data.begin(), it); } T minVal() const { if (_data.empty()) return 0; return *std::min_element(_data.begin(), _data.end()); } T maxVal() const { if(_data.empty()) return 0; return *std::max_element(_data.begin(), _data.end()); } int minValId() const { if(_data.empty()) return -1; return std::distance(_data.begin(), std::min_element(_data.begin(), _data.end())); } int maxValId() const { if (_data.empty()) return -1; return std::distance(_data.begin(), std::max_element(_data.begin(), _data.end())); } }; // TODO: to remove // Avoid the problematic case of std::vector<bool>::operator[] using staticVectorBool = staticVector<char>; template <class T> int sizeOfStaticVector(staticVector<T>* a) { if(a == nullptr) return 0; return a->size(); }; template <class T> int indexOf(T* arr, int n, const T& what) { int isthereindex = -1; int i = 0; while((i < n) && (isthereindex == -1)) { if(arr[i] == what) { isthereindex = i; }; i++; }; return isthereindex; }; template <class T> void saveArrayOfArraysToFile(std::string fileName, staticVector<staticVector<T>*>* aa) { std::cout << "[IO] saveArrayOfArraysToFile: " << fileName << std::endl; FILE* f = fopen(fileName.c_str(), "wb"); int n = aa->size(); fwrite(&n, sizeof(int), 1, f); for(int i = 0; i < n; i++) { int m = 0; staticVector<T>* a = (*aa)[i]; if(a == NULL) { fwrite(&m, sizeof(int), 1, f); } else { m = a->size(); fwrite(&m, sizeof(int), 1, f); if(m > 0) { fwrite(&(*a)[0], sizeof(T), m, f); }; }; }; fclose(f); } template <class T> staticVector<staticVector<T>*>* loadArrayOfArraysFromFile(std::string fileName) { std::cout << "[IO] loadArrayOfArraysFromFile: " << fileName << std::endl; FILE* f = fopen(fileName.c_str(), "rb"); if(f == nullptr) throw std::runtime_error("loadArrayOfArraysFromFile : can't open file " + fileName); int n = 0; fread(&n, sizeof(int), 1, f); staticVector<staticVector<T>*>* aa = new staticVector<staticVector<T>*>(n); aa->resize_with(n, NULL); for(int i = 0; i < n; i++) { int m = 0; fread(&m, sizeof(int), 1, f); if(m > 0) { staticVector<T>* a = new staticVector<T>(m); a->resize(m); fread(&(*a)[0], sizeof(T), m, f); (*aa)[i] = a; }; }; fclose(f); return aa; } template <class T> void saveArrayToFile(std::string fileName, staticVector<T>* a, bool docompress = true) { std::cout << "[IO] saveArrayToFile: " << fileName << std::endl; if((docompress == false) || (a->size() < 1000)) { FILE* f = fopen(fileName.c_str(), "wb"); int n = a->size(); fwrite(&n, sizeof(int), 1, f); fwrite(&(*a)[0], sizeof(T), n, f); fclose(f); } else { /* =========================================================================== //from zlib - compress.c Compresses the source buffer into the destination buffer. The level parameter has the same meaning as in deflateInit. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least 0.1% larger than sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, Z_STREAM_ERROR if the level parameter is invalid. */ // uLong comprLen = sizeof(T)*a->size(); uLong comprLen = uLong((double)(sizeof(T) * a->size()) * 1.02) + 12; Byte* compr = (Byte*)calloc((uInt)comprLen, 1); int err = compress(compr, &comprLen, (const Bytef*)(&(*a)[0]), sizeof(T) * a->size()); if(err != Z_OK) { printf("compress error %i : %lu -> %lu, n %i \n", err, sizeof(T) * a->size(), comprLen, a->size()); FILE* f = fopen(fileName.c_str(), "wb"); int n = a->size(); fwrite(&n, sizeof(int), 1, f); fwrite(&(*a)[0], sizeof(T), n, f); fclose(f); } else { FILE* f = fopen(fileName.c_str(), "wb"); int n = -1; fwrite(&n, sizeof(int), 1, f); n = a->size(); fwrite(&n, sizeof(int), 1, f); fwrite(&comprLen, sizeof(uLong), 1, f); fwrite(compr, sizeof(Byte), comprLen, f); fclose(f); }; free(compr); }; } template <class T> staticVector<T>* loadArrayFromFile(std::string fileName, bool printfWarning = false) { std::cout << "[IO] loadArrayFromFile: " << fileName << std::endl; FILE* f = fopen(fileName.c_str(), "rb"); if(f == NULL) { throw std::runtime_error("loadArrayOfArraysFromFile : can't open file " + fileName); } else { int n = 0; fread(&n, sizeof(int), 1, f); staticVector<T>* a = NULL; if(n == -1) { fread(&n, sizeof(int), 1, f); a = new staticVector<T>(n); a->resize(n); uLong comprLen; fread(&comprLen, sizeof(uLong), 1, f); Byte* compr = (Byte*)calloc((uInt)comprLen, 1); fread(compr, sizeof(Byte), comprLen, f); uLong uncomprLen = sizeof(T) * n; int err = uncompress((Bytef*)(&(*a)[0]), &uncomprLen, compr, comprLen); if(err != Z_OK) { printf("uncompress error %i : %lu -> %lu, n %i \n", err, sizeof(T) * n, uncomprLen, n); } if(uncomprLen != sizeof(T) * n) { throw std::runtime_error("loadArrayFromFile: uncompression failed uncomprLen!=sizeof(T)*n"); } free(compr); } else { a = new staticVector<T>(n); a->resize(n); fread(&(*a)[0], sizeof(T), n, f); } fclose(f); return a; } } template <class T> void loadArrayFromFileIntoArray(staticVector<T>* a, std::string fileName, bool printfWarning = false) { std::cout << "[IO] loadArrayFromFileIntoArray: " << fileName << std::endl; FILE* f = fopen(fileName.c_str(), "rb"); if(f == NULL) { throw std::runtime_error("loadArrayFromFileIntoArray: can not open file: " + fileName); } int n = 0; fread(&n, sizeof(int), 1, f); if(n == -1) { fread(&n, sizeof(int), 1, f); if(a->size() != n) { std::stringstream s; s << "loadArrayFromFileIntoArray: expected length " << a->size() << " loaded length " << n; throw std::runtime_error(s.str()); } uLong comprLen; fread(&comprLen, sizeof(uLong), 1, f); Byte* compr = (Byte*)calloc((uInt)comprLen, 1); fread(compr, sizeof(Byte), comprLen, f); uLong uncomprLen = sizeof(T) * n; int err = uncompress((Bytef*)(&(*a)[0]), &uncomprLen, compr, comprLen); if(err != Z_OK) { printf("uncompress error %i : %lu -> %lu, n %i \n", err, sizeof(T) * n, uncomprLen, n); } if(uncomprLen != sizeof(T) * n) { throw std::runtime_error("loadArrayFromFileIntoArray: uncompression failed uncomprLen!=sizeof(T)*n"); } free(compr); } else { if(a->size() != n) { std::stringstream s; s << "loadArrayFromFileIntoArray: expected length " << a->size() << " loaded length " << n; throw std::runtime_error(s.str()); } fread(&(*a)[0], sizeof(T), n, f); } fclose(f); } int getArrayLengthFromFile(std::string fileName); template <class T> void deleteArrayOfArrays(staticVector<staticVector<T>*>** aa) { for(int i = 0; i < (*aa)->size(); i++) { if((*(*aa))[i] != NULL) { delete(*(*aa))[i]; (*(*aa))[i] = NULL; }; }; delete(*aa); } template <class T> staticVector<staticVector<T>*>* cloneArrayOfArrays(staticVector<staticVector<T>*>* inAOA) { staticVector<staticVector<T>*>* outAOA = new staticVector<staticVector<T>*>(inAOA->size()); // copy for(int i = 0; i < inAOA->size(); i++) { if((*inAOA)[i] == NULL) { outAOA->push_back(NULL); } else { staticVector<T>* outA = new staticVector<T>((*inAOA)[i]->size()); outA->push_back_arr((*inAOA)[i]); outAOA->push_back(outA); }; }; return outAOA; } <commit_msg>[structure] staticVector: add utility methods "front" and "resize" with initialization value<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/. #pragma once #include <aliceVision/eig33/eig33.hpp> #include <algorithm> #include <assert.h> #include <cstdlib> #include <sstream> #include <vector> #include <zlib.h> #include <iostream> #include <stdexcept> template <class T> class staticVector { std::vector<T> _data; typedef typename std::vector<T>::iterator Iterator; typedef typename std::vector<T>::const_iterator ConstIterator; typedef typename std::vector<T>::reference Reference; typedef typename std::vector<T>::const_reference ConstReference; public: staticVector() { } staticVector(int _allocated) { _data.reserve(_allocated); } const T& operator[](int index) const { return _data[index]; } T& operator[](int index) { return _data[index]; } void clear() { _data.clear(); } Iterator begin() { return _data.begin(); } Iterator end() { return _data.end(); } ConstIterator begin() const { return _data.begin(); } ConstIterator end() const { return _data.end(); } Reference front() { return _data.front(); } ConstReference front() const { return _data.front(); } const std::vector<T>& getData() const { return _data; } std::vector<T>& getDataWritable() { return _data; } int size() const { return _data.size(); } bool empty() const { return _data.empty(); } size_t capacity() const { return _data.capacity(); } void reserve(int n) { _data.reserve(n); } void resize(int n) { _data.resize(n); } void resize(int n, T value) { _data.resize(n, value); } void resize_with(int n, const T& val) { _data.resize(n, val); } void swap( staticVector& other ) { _data.swap(other._data); } void shrink_to_fit() { _data.shrink_to_fit(); } void resizeAddIfNeeded(int nplanned, int ntoallocated) { if(size() + nplanned > capacity()) { resizeAdd(nplanned + ntoallocated); } } void resizeAdd(int ntoallocated) { _data.reserve(capacity() + ntoallocated); } void push_sorted_asc(const T& val) { _data.insert(std::lower_bound(_data.begin(), _data.end(), val), val); } void push_back(const T& val) { _data.push_back(val); } void push_front(const T& val) { _data.insert(_data.begin(), val); } void push_back_arr(staticVector<T>* arr) { _data.insert(_data.end(), arr->getData().begin(), arr->getData().end()); } void remove(int i) { _data.erase(_data.begin() + i); } int push_back_distinct(const T& val) { int id = indexOf(val); if(id == -1) _data.push_back(val); return id; } T pop() { T val = _data.back(); _data.pop_back(); return val; } int indexOf(const T& value) const { const auto it = std::find(_data.begin(), _data.end(), value); return it != _data.end() ? std::distance(_data.begin(), it) : -1; } int indexOfSorted(const T& value) const { return indexOf(value); } int indexOfNearestSorted(const T& value) const { // Retrieve the first element >= value in _data auto it = std::lower_bound(_data.begin(), _data.end(), value); if(it == _data.end()) return -1; // If we're between two values... if(it != _data.begin()) { // ...select the index of the closest value between it (>= value) and prevIt (< value) auto prevIt = std::prev(it); it = (value - *prevIt) < (*it - value) ? prevIt : it; } return std::distance(_data.begin(), it); } T minVal() const { if (_data.empty()) return 0; return *std::min_element(_data.begin(), _data.end()); } T maxVal() const { if(_data.empty()) return 0; return *std::max_element(_data.begin(), _data.end()); } int minValId() const { if(_data.empty()) return -1; return std::distance(_data.begin(), std::min_element(_data.begin(), _data.end())); } int maxValId() const { if (_data.empty()) return -1; return std::distance(_data.begin(), std::max_element(_data.begin(), _data.end())); } }; // TODO: to remove // Avoid the problematic case of std::vector<bool>::operator[] using staticVectorBool = staticVector<char>; template <class T> int sizeOfStaticVector(staticVector<T>* a) { if(a == nullptr) return 0; return a->size(); }; template <class T> int indexOf(T* arr, int n, const T& what) { int isthereindex = -1; int i = 0; while((i < n) && (isthereindex == -1)) { if(arr[i] == what) { isthereindex = i; }; i++; }; return isthereindex; }; template <class T> void saveArrayOfArraysToFile(std::string fileName, staticVector<staticVector<T>*>* aa) { std::cout << "[IO] saveArrayOfArraysToFile: " << fileName << std::endl; FILE* f = fopen(fileName.c_str(), "wb"); int n = aa->size(); fwrite(&n, sizeof(int), 1, f); for(int i = 0; i < n; i++) { int m = 0; staticVector<T>* a = (*aa)[i]; if(a == NULL) { fwrite(&m, sizeof(int), 1, f); } else { m = a->size(); fwrite(&m, sizeof(int), 1, f); if(m > 0) { fwrite(&(*a)[0], sizeof(T), m, f); }; }; }; fclose(f); } template <class T> staticVector<staticVector<T>*>* loadArrayOfArraysFromFile(std::string fileName) { std::cout << "[IO] loadArrayOfArraysFromFile: " << fileName << std::endl; FILE* f = fopen(fileName.c_str(), "rb"); if(f == nullptr) throw std::runtime_error("loadArrayOfArraysFromFile : can't open file " + fileName); int n = 0; fread(&n, sizeof(int), 1, f); staticVector<staticVector<T>*>* aa = new staticVector<staticVector<T>*>(n); aa->resize_with(n, NULL); for(int i = 0; i < n; i++) { int m = 0; fread(&m, sizeof(int), 1, f); if(m > 0) { staticVector<T>* a = new staticVector<T>(m); a->resize(m); fread(&(*a)[0], sizeof(T), m, f); (*aa)[i] = a; }; }; fclose(f); return aa; } template <class T> void saveArrayToFile(std::string fileName, staticVector<T>* a, bool docompress = true) { std::cout << "[IO] saveArrayToFile: " << fileName << std::endl; if((docompress == false) || (a->size() < 1000)) { FILE* f = fopen(fileName.c_str(), "wb"); int n = a->size(); fwrite(&n, sizeof(int), 1, f); fwrite(&(*a)[0], sizeof(T), n, f); fclose(f); } else { /* =========================================================================== //from zlib - compress.c Compresses the source buffer into the destination buffer. The level parameter has the same meaning as in deflateInit. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least 0.1% larger than sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, Z_STREAM_ERROR if the level parameter is invalid. */ // uLong comprLen = sizeof(T)*a->size(); uLong comprLen = uLong((double)(sizeof(T) * a->size()) * 1.02) + 12; Byte* compr = (Byte*)calloc((uInt)comprLen, 1); int err = compress(compr, &comprLen, (const Bytef*)(&(*a)[0]), sizeof(T) * a->size()); if(err != Z_OK) { printf("compress error %i : %lu -> %lu, n %i \n", err, sizeof(T) * a->size(), comprLen, a->size()); FILE* f = fopen(fileName.c_str(), "wb"); int n = a->size(); fwrite(&n, sizeof(int), 1, f); fwrite(&(*a)[0], sizeof(T), n, f); fclose(f); } else { FILE* f = fopen(fileName.c_str(), "wb"); int n = -1; fwrite(&n, sizeof(int), 1, f); n = a->size(); fwrite(&n, sizeof(int), 1, f); fwrite(&comprLen, sizeof(uLong), 1, f); fwrite(compr, sizeof(Byte), comprLen, f); fclose(f); }; free(compr); }; } template <class T> staticVector<T>* loadArrayFromFile(std::string fileName, bool printfWarning = false) { std::cout << "[IO] loadArrayFromFile: " << fileName << std::endl; FILE* f = fopen(fileName.c_str(), "rb"); if(f == NULL) { throw std::runtime_error("loadArrayOfArraysFromFile : can't open file " + fileName); } else { int n = 0; fread(&n, sizeof(int), 1, f); staticVector<T>* a = NULL; if(n == -1) { fread(&n, sizeof(int), 1, f); a = new staticVector<T>(n); a->resize(n); uLong comprLen; fread(&comprLen, sizeof(uLong), 1, f); Byte* compr = (Byte*)calloc((uInt)comprLen, 1); fread(compr, sizeof(Byte), comprLen, f); uLong uncomprLen = sizeof(T) * n; int err = uncompress((Bytef*)(&(*a)[0]), &uncomprLen, compr, comprLen); if(err != Z_OK) { printf("uncompress error %i : %lu -> %lu, n %i \n", err, sizeof(T) * n, uncomprLen, n); } if(uncomprLen != sizeof(T) * n) { throw std::runtime_error("loadArrayFromFile: uncompression failed uncomprLen!=sizeof(T)*n"); } free(compr); } else { a = new staticVector<T>(n); a->resize(n); fread(&(*a)[0], sizeof(T), n, f); } fclose(f); return a; } } template <class T> void loadArrayFromFileIntoArray(staticVector<T>* a, std::string fileName, bool printfWarning = false) { std::cout << "[IO] loadArrayFromFileIntoArray: " << fileName << std::endl; FILE* f = fopen(fileName.c_str(), "rb"); if(f == NULL) { throw std::runtime_error("loadArrayFromFileIntoArray: can not open file: " + fileName); } int n = 0; fread(&n, sizeof(int), 1, f); if(n == -1) { fread(&n, sizeof(int), 1, f); if(a->size() != n) { std::stringstream s; s << "loadArrayFromFileIntoArray: expected length " << a->size() << " loaded length " << n; throw std::runtime_error(s.str()); } uLong comprLen; fread(&comprLen, sizeof(uLong), 1, f); Byte* compr = (Byte*)calloc((uInt)comprLen, 1); fread(compr, sizeof(Byte), comprLen, f); uLong uncomprLen = sizeof(T) * n; int err = uncompress((Bytef*)(&(*a)[0]), &uncomprLen, compr, comprLen); if(err != Z_OK) { printf("uncompress error %i : %lu -> %lu, n %i \n", err, sizeof(T) * n, uncomprLen, n); } if(uncomprLen != sizeof(T) * n) { throw std::runtime_error("loadArrayFromFileIntoArray: uncompression failed uncomprLen!=sizeof(T)*n"); } free(compr); } else { if(a->size() != n) { std::stringstream s; s << "loadArrayFromFileIntoArray: expected length " << a->size() << " loaded length " << n; throw std::runtime_error(s.str()); } fread(&(*a)[0], sizeof(T), n, f); } fclose(f); } int getArrayLengthFromFile(std::string fileName); template <class T> void deleteArrayOfArrays(staticVector<staticVector<T>*>** aa) { for(int i = 0; i < (*aa)->size(); i++) { if((*(*aa))[i] != NULL) { delete(*(*aa))[i]; (*(*aa))[i] = NULL; }; }; delete(*aa); } template <class T> staticVector<staticVector<T>*>* cloneArrayOfArrays(staticVector<staticVector<T>*>* inAOA) { staticVector<staticVector<T>*>* outAOA = new staticVector<staticVector<T>*>(inAOA->size()); // copy for(int i = 0; i < inAOA->size(); i++) { if((*inAOA)[i] == NULL) { outAOA->push_back(NULL); } else { staticVector<T>* outA = new staticVector<T>((*inAOA)[i]->size()); outA->push_back_arr((*inAOA)[i]); outAOA->push_back(outA); }; }; return outAOA; } <|endoftext|>
<commit_before>#ifndef LIBTEN_URI_HH #define LIBTEN_URI_HH #include <string> #include <utility> #include <vector> #include <stdexcept> #include <algorithm> #include <sstream> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> namespace ten { class uri_error : std::exception { public: uri_error(const std::string &uri_str, const char *where) { std::stringstream ss; ss << "uri parse(" << uri_str << ") error at " << where; _msg = ss.str(); } uri_error(const std::string &uri_str) { std::stringstream ss; ss << "uri parser error on (" << uri_str << ")"; _msg = ss.str(); } const char *what() const throw() { return _msg.c_str(); } private: std::string _msg; }; /* TODO: * comparison * http://tools.ietf.org/html/rfc3986#section-6 */ //! uniform resource locator // //! parser based on ebnf in rfc3986, relaxed for the real-world class uri { private: int parse(const char *buf, size_t len, const char **error_at = NULL); public: std::string scheme; std::string userinfo; std::string host; std::string path; std::string query; std::string fragment; uint16_t port; uri() : port(0) {} uri(const std::string &uri_str) { assign(uri_str); } void assign(const std::string &uri_str) { const char *error_at = NULL; if (!parse(uri_str.c_str(), uri_str.size(), &error_at)) { if (error_at) { throw uri_error(uri_str, error_at); } else { throw uri_error(uri_str); } } } void clear() { scheme.clear(); userinfo.clear(); host.clear(); path.clear(); query.clear(); fragment.clear(); port = 0; } void normalize(); std::string compose_path() { return compose(true); } std::string compose(bool path_only=false); void transform(uri &base, uri &relative); static std::string encode(const std::string& src); static std::string decode(const std::string& src); private: friend class query_params; template <typename T> struct query_match { query_match(const T &k_) : k(k_) {} const T &k; bool operator()(const std::pair<T, T> &i) { return i.first == k; } }; public: //! map-like interface to uri query parameters class query_params { public: typedef std::vector<std::pair<std::string, std::string>> params_type; typedef params_type::iterator iterator; typedef params_type::const_iterator const_iterator; private: params_type _params; public: query_params(const std::string &query); template <typename ValueT, typename ...Args> query_params(std::string key, ValueT value, Args ...args) { _params.reserve(sizeof...(args)); init(key, value, args...); } // init can go away with delegating constructor support void init() {} template <typename ValueT, typename ...Args> void init(std::string key, ValueT value, Args ...args) { append<ValueT>(key, value); init(args...); } void append(const std::string &key, const std::string &value) { _params.push_back(std::make_pair(key, value)); } template <typename ValueT> void append(const std::string &field, const ValueT &value) { append(field, boost::lexical_cast<std::string>(value)); } params_type::const_iterator find(const std::string &k) const { return std::find_if(_params.cbegin(), _params.cend(), query_match<std::string>(k)); } params_type::iterator find(const std::string &k) { return std::find_if(_params.begin(), _params.end(), query_match<std::string>(k)); } iterator begin() { return _params.begin(); } const_iterator cbegin() { return _params.cbegin(); } iterator end() { return _params.end(); } const_iterator cend() { return _params.cend(); } template <typename ParamT> bool get(const std::string &k, ParamT &v) const { auto i = find(k); if (i != _params.cend()) { try { v = boost::lexical_cast<ParamT>(i->second); return true; } catch (boost::bad_lexical_cast &e) {} } return false; } void erase(const std::string &k) { iterator nend = std::remove_if(_params.begin(), _params.end(), query_match<std::string>(k)); _params.erase(nend, _params.end()); } std::string str() const { if (_params.empty()) return ""; std::stringstream ss; ss << "?"; params_type::const_iterator it = _params.cbegin(); while (it!=_params.end()) { ss << encode(it->first) << "=" << encode(it->second); ++it; if (it != _params.end()) { ss << "&"; } } return ss.str(); } size_t size() const { return _params.size(); } }; public: query_params query_part() { return query_params(query); } struct match_char { char c; match_char(char c_) : c(c_) {} bool operator()(char x) const { return x == c; } }; typedef std::vector<std::string> split_vector; split_vector path_splits() { split_vector splits; boost::split(splits, path, match_char('/')); return splits; } }; } // end namespace ten #endif // LIBTEN_URI_HH <commit_msg>fix gcc 4.4 error<commit_after>#ifndef LIBTEN_URI_HH #define LIBTEN_URI_HH #include <string> #include <utility> #include <vector> #include <stdexcept> #include <algorithm> #include <sstream> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> namespace ten { class uri_error : std::exception { public: uri_error(const std::string &uri_str, const char *where) { std::stringstream ss; ss << "uri parse(" << uri_str << ") error at " << where; _msg = ss.str(); } uri_error(const std::string &uri_str) { std::stringstream ss; ss << "uri parser error on (" << uri_str << ")"; _msg = ss.str(); } virtual ~uri_error() throw () {} const char *what() const throw() { return _msg.c_str(); } private: std::string _msg; }; /* TODO: * comparison * http://tools.ietf.org/html/rfc3986#section-6 */ //! uniform resource locator // //! parser based on ebnf in rfc3986, relaxed for the real-world class uri { private: int parse(const char *buf, size_t len, const char **error_at = NULL); public: std::string scheme; std::string userinfo; std::string host; std::string path; std::string query; std::string fragment; uint16_t port; uri() : port(0) {} uri(const std::string &uri_str) { assign(uri_str); } void assign(const std::string &uri_str) { const char *error_at = NULL; if (!parse(uri_str.c_str(), uri_str.size(), &error_at)) { if (error_at) { throw uri_error(uri_str, error_at); } else { throw uri_error(uri_str); } } } void clear() { scheme.clear(); userinfo.clear(); host.clear(); path.clear(); query.clear(); fragment.clear(); port = 0; } void normalize(); std::string compose_path() { return compose(true); } std::string compose(bool path_only=false); void transform(uri &base, uri &relative); static std::string encode(const std::string& src); static std::string decode(const std::string& src); private: friend class query_params; template <typename T> struct query_match { query_match(const T &k_) : k(k_) {} const T &k; bool operator()(const std::pair<T, T> &i) { return i.first == k; } }; public: //! map-like interface to uri query parameters class query_params { public: typedef std::vector<std::pair<std::string, std::string>> params_type; typedef params_type::iterator iterator; typedef params_type::const_iterator const_iterator; private: params_type _params; public: query_params(const std::string &query); template <typename ValueT, typename ...Args> query_params(std::string key, ValueT value, Args ...args) { _params.reserve(sizeof...(args)); init(key, value, args...); } // init can go away with delegating constructor support void init() {} template <typename ValueT, typename ...Args> void init(std::string key, ValueT value, Args ...args) { append<ValueT>(key, value); init(args...); } void append(const std::string &key, const std::string &value) { _params.push_back(std::make_pair(key, value)); } template <typename ValueT> void append(const std::string &field, const ValueT &value) { append(field, boost::lexical_cast<std::string>(value)); } params_type::const_iterator find(const std::string &k) const { return std::find_if(_params.cbegin(), _params.cend(), query_match<std::string>(k)); } params_type::iterator find(const std::string &k) { return std::find_if(_params.begin(), _params.end(), query_match<std::string>(k)); } iterator begin() { return _params.begin(); } const_iterator cbegin() { return _params.cbegin(); } iterator end() { return _params.end(); } const_iterator cend() { return _params.cend(); } template <typename ParamT> bool get(const std::string &k, ParamT &v) const { auto i = find(k); if (i != _params.cend()) { try { v = boost::lexical_cast<ParamT>(i->second); return true; } catch (boost::bad_lexical_cast &e) {} } return false; } void erase(const std::string &k) { iterator nend = std::remove_if(_params.begin(), _params.end(), query_match<std::string>(k)); _params.erase(nend, _params.end()); } std::string str() const { if (_params.empty()) return ""; std::stringstream ss; ss << "?"; params_type::const_iterator it = _params.cbegin(); while (it!=_params.end()) { ss << encode(it->first) << "=" << encode(it->second); ++it; if (it != _params.end()) { ss << "&"; } } return ss.str(); } size_t size() const { return _params.size(); } }; public: query_params query_part() { return query_params(query); } struct match_char { char c; match_char(char c_) : c(c_) {} bool operator()(char x) const { return x == c; } }; typedef std::vector<std::string> split_vector; split_vector path_splits() { split_vector splits; boost::split(splits, path, match_char('/')); return splits; } }; } // end namespace ten #endif // LIBTEN_URI_HH <|endoftext|>
<commit_before>/** @file @brief Save data from database to RAM (or hard drive in future version). @author Yi Zhao */ #include "main.h" /** @brief Save data from MYSQL_RES to RAM. @see localrow @remark Data saved in linked list.\n Usage:\n MYSQL_RES *result=mysql_store_result(mysql_conn);\n localrow *localresult;\n int res=make_mysqlres_local(&localresult,result); */ int make_mysqlres_local(localrow **localresult,MYSQL_RES *result_t){ int count=0; mysql_data_seek(result_t,0); localrow **p=localresult; MYSQL_ROW sql_row; while((sql_row=mysql_fetch_row(result_t))){ *p=(localrow*)malloc(sizeof(localrow)); for(int i=0;i<8;i++){ strcpy((*p)->row[i],sql_row[i]); } p=&((*p)->next); count++; } *p=NULL; return count; } /** @brief Free data on RAM. @see localrow */ void free_mysqlres_local(localrow *localresult){ while(localresult){ localrow *p=localresult; if(p->next==NULL) printf(">>%d\n",p); localresult=p->next; free(p); } } /** @brief Get number of saved sgRNA-Info on RAM. @see localrow */ int localres_count(localrow *lr){ int i=0; while(lr){ i++; lr=lr->next; if(i>1000000) return -1; } return i; } <commit_msg>show less and less<commit_after>/** @file @brief Save data from database to RAM (or hard drive in future version). @author Yi Zhao */ #include "main.h" /** @brief Save data from MYSQL_RES to RAM. @see localrow @remark Data saved in linked list.\n Usage:\n MYSQL_RES *result=mysql_store_result(mysql_conn);\n localrow *localresult;\n int res=make_mysqlres_local(&localresult,result); */ int make_mysqlres_local(localrow **localresult,MYSQL_RES *result_t){ int count=0; mysql_data_seek(result_t,0); localrow **p=localresult; MYSQL_ROW sql_row; while((sql_row=mysql_fetch_row(result_t))){ *p=(localrow*)malloc(sizeof(localrow)); for(int i=0;i<8;i++){ strcpy((*p)->row[i],sql_row[i]); } p=&((*p)->next); count++; } *p=NULL; return count; } /** @brief Free data on RAM. @see localrow */ void free_mysqlres_local(localrow *localresult){ while(localresult){ localrow *p=localresult; if(p->next) printf(">>%d\n",p); localresult=p->next; free(p); } } /** @brief Get number of saved sgRNA-Info on RAM. @see localrow */ int localres_count(localrow *lr){ int i=0; while(lr){ i++; lr=lr->next; if(i>1000000) return -1; } return i; } <|endoftext|>
<commit_before>#include <node.h> #include <node_object_wrap.h> #include <iostream> #include <cmath> using namespace std; using namespace v8; class WrappedPoly : public node::ObjectWrap { public: static void Init(v8::Local<v8::Object> exports) { Isolate* isolate = exports->GetIsolate(); // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New); tpl->SetClassName(String::NewFromUtf8(isolate, "Polynomial")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Prototype NODE_SET_PROTOTYPE_METHOD(tpl, "at", At); NODE_SET_PROTOTYPE_METHOD(tpl, "roots", Roots); tpl->InstanceTemplate()->SetAccessor(String::NewFromUtf8(isolate, "a"), GetCoeff, SetCoeff); tpl->InstanceTemplate()->SetAccessor(String::NewFromUtf8(isolate, "b"), GetCoeff, SetCoeff); tpl->InstanceTemplate()->SetAccessor(String::NewFromUtf8(isolate, "c"), GetCoeff, SetCoeff); constructor.Reset(isolate, tpl->GetFunction()); exports->Set(String::NewFromUtf8(isolate, "Polynomial"), tpl->GetFunction()); } private: explicit WrappedPoly(double a = 0, double b = 0, double c = 0) : a_(a), b_(b), c_(c) {} ~WrappedPoly() {} static void New(const v8::FunctionCallbackInfo<v8::Value>& args) { Isolate* isolate = args.GetIsolate(); if (args.IsConstructCall()) { // Invoked as constructor: `new Polynomial(...)` double a = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(); double b = args[1]->IsUndefined() ? 0 : args[1]->NumberValue(); double c = args[2]->IsUndefined() ? 0 : args[2]->NumberValue(); WrappedPoly* obj = new WrappedPoly(a, b, c); obj->Wrap(args.This()); args.GetReturnValue().Set(args.This()); } else { // Invoked as plain function `Polynomial(...)`, turn into construct call. const int argc = 3; Local<Value> argv[argc] = { args[0] , args[1], args[2]}; Local<Function> cons = Local<Function>::New(isolate, constructor); args.GetReturnValue().Set(cons->NewInstance(argc, argv)); } } static void At(const v8::FunctionCallbackInfo<v8::Value>& args); static void Roots(const v8::FunctionCallbackInfo<v8::Value>& args); static void GetCoeff(Local<String> property, const PropertyCallbackInfo<Value>& info); static void SetCoeff(Local<String> property, Local<Value> value, const PropertyCallbackInfo<void>& info); static v8::Persistent<v8::Function> constructor; double a_; double b_; double c_; }; Persistent<Function> WrappedPoly::constructor; void WrappedPoly::At(const v8::FunctionCallbackInfo<v8::Value>& args) { Isolate* isolate = args.GetIsolate(); double x = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(); WrappedPoly* poly = ObjectWrap::Unwrap<WrappedPoly>(args.Holder()); double results = x * x * poly->a_ + x * poly->b_ + poly->c_; args.GetReturnValue().Set(Number::New(isolate, results)); } void WrappedPoly::Roots(const v8::FunctionCallbackInfo<v8::Value>& args) { Isolate* isolate = args.GetIsolate(); WrappedPoly* poly = ObjectWrap::Unwrap<WrappedPoly>(args.Holder()); Local<Array> roots = Array::New(isolate); double desc = poly->b_ * poly->b_ - (4 * poly->a_ * poly->c_); if (desc >= 0 ) { double r = (-poly->b_ + sqrt(desc))/(2 * poly->a_); roots->Set(0,Number::New(isolate, r)); if ( desc > 0) { r = (-poly->b_ - sqrt(desc))/(2 * poly->a_); roots->Set(1,Number::New(isolate, r)); } } args.GetReturnValue().Set(roots); } void WrappedPoly::GetCoeff(Local<String> property, const PropertyCallbackInfo<Value>& info) { Isolate* isolate = info.GetIsolate(); WrappedPoly* obj = ObjectWrap::Unwrap<WrappedPoly>(info.This()); v8::String::Utf8Value s(property); std::string str(*s); if ( str == "a") { info.GetReturnValue().Set(Number::New(isolate, obj->a_)); } else if (str == "b") { info.GetReturnValue().Set(Number::New(isolate, obj->b_)); } else if (str == "c") { info.GetReturnValue().Set(Number::New(isolate, obj->c_)); } } void WrappedPoly::SetCoeff(Local<String> property, Local<Value> value, const PropertyCallbackInfo<void>& info) { WrappedPoly* obj = ObjectWrap::Unwrap<WrappedPoly>(info.This()); v8::String::Utf8Value s(property); std::string str(*s); if ( str == "a") { obj->a_ = value->NumberValue(); } else if (str == "b") { obj->b_ = value->NumberValue(); } else if (str == "c") { obj->c_ = value->NumberValue(); } } void InitPoly(Local<Object> exports) { WrappedPoly::Init(exports); } NODE_MODULE(polynomial, InitPoly)<commit_msg>Delete polynomial.cpp<commit_after><|endoftext|>
<commit_before>/*- * Copyright (c) 2016 Frederic Culot <culot@FreeBSD.org> * 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 * in this position and unchanged. * 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 AUTHOR(S) ``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 AUTHOR(S) 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 <thread> #include <chrono> #include <curses.h> #include "popupwindow.h" namespace portal { namespace gfx { PopupWindow::PopupWindow(const std::string& msg, Type type, const Point& center) : Window() { Size size; size.setHeight(1); size.setWidth(msg.length() + 2); setSize(size); Point pos; pos.setX(center.x() - msg.length() / 2); pos.setY(center.y()); setPosition(pos); Style style; switch (type) { case Type::brief: style.color = Style::Color::magenta; break; case Type::info: style.color = Style::Color::blue; break; case Type::warning: style.color = Style::Color::yellow; break; case Type::error: style.color = Style::Color::red; break; } setStyle(style); print(msg); int duration; switch (type) { case Type::brief: duration = 500; break; default: duration = 1400; break; } std::this_thread::sleep_for(std::chrono::milliseconds(duration)); clear(); } } } <commit_msg>Update screen upon popup deletion, otherwise it stays since previous commit<commit_after>/*- * Copyright (c) 2016 Frederic Culot <culot@FreeBSD.org> * 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 * in this position and unchanged. * 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 AUTHOR(S) ``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 AUTHOR(S) 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 <thread> #include <chrono> #include <curses.h> #include "popupwindow.h" namespace portal { namespace gfx { PopupWindow::PopupWindow(const std::string& msg, Type type, const Point& center) : Window() { Size size; size.setHeight(1); size.setWidth(msg.length() + 2); setSize(size); Point pos; pos.setX(center.x() - msg.length() / 2); pos.setY(center.y()); setPosition(pos); Style style; switch (type) { case Type::brief: style.color = Style::Color::magenta; break; case Type::info: style.color = Style::Color::blue; break; case Type::warning: style.color = Style::Color::yellow; break; case Type::error: style.color = Style::Color::red; break; } setStyle(style); print(msg); int duration; switch (type) { case Type::brief: duration = 500; break; default: duration = 1400; break; } std::this_thread::sleep_for(std::chrono::milliseconds(duration)); clear(); Gfx::instance().update(); } } } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/controls/button/menu_button.h" #include "app/drag_drop_types.h" #include "app/gfx/canvas.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "grit/app_strings.h" #include "grit/app_resources.h" #include "views/controls/button/button.h" #include "views/controls/menu/view_menu_delegate.h" #include "views/event.h" #include "views/screen.h" #include "views/widget/root_view.h" #include "views/widget/widget.h" #include "views/window/window.h" using base::Time; using base::TimeDelta; namespace views { // The amount of time, in milliseconds, we wait before allowing another mouse // pressed event to show the menu. static const int64 kMinimumTimeBetweenButtonClicks = 100; // The down arrow used to differentiate the menu button from normal // text buttons. static const SkBitmap* kMenuMarker = NULL; // How much padding to put on the left and right of the menu marker. static const int kMenuMarkerPaddingLeft = 3; static const int kMenuMarkerPaddingRight = -1; //////////////////////////////////////////////////////////////////////////////// // // MenuButton - constructors, destructors, initialization // //////////////////////////////////////////////////////////////////////////////// MenuButton::MenuButton(ButtonListener* listener, const std::wstring& text, ViewMenuDelegate* menu_delegate, bool show_menu_marker) : TextButton(listener, text), menu_visible_(false), menu_delegate_(menu_delegate), show_menu_marker_(show_menu_marker) { if (kMenuMarker == NULL) { kMenuMarker = ResourceBundle::GetSharedInstance() .GetBitmapNamed(IDR_MENU_DROPARROW); } set_alignment(TextButton::ALIGN_LEFT); } MenuButton::~MenuButton() { } //////////////////////////////////////////////////////////////////////////////// // // MenuButton - Public APIs // //////////////////////////////////////////////////////////////////////////////// gfx::Size MenuButton::GetPreferredSize() { gfx::Size prefsize = TextButton::GetPreferredSize(); if (show_menu_marker_) { prefsize.Enlarge(kMenuMarker->width() + kMenuMarkerPaddingLeft + kMenuMarkerPaddingRight, 0); } return prefsize; } void MenuButton::Paint(gfx::Canvas* canvas, bool for_drag) { TextButton::Paint(canvas, for_drag); if (show_menu_marker_) { gfx::Insets insets = GetInsets(); // We can not use the views' mirroring infrastructure for mirroring a // MenuButton control (see TextButton::Paint() for a detailed explanation // regarding why we can not flip the canvas). Therefore, we need to // manually mirror the position of the down arrow. gfx::Rect arrow_bounds(width() - insets.right() - kMenuMarker->width() - kMenuMarkerPaddingRight, height() / 2 - kMenuMarker->height() / 2, kMenuMarker->width(), kMenuMarker->height()); arrow_bounds.set_x(MirroredLeftPointForRect(arrow_bounds)); canvas->DrawBitmapInt(*kMenuMarker, arrow_bounds.x(), arrow_bounds.y()); } } //////////////////////////////////////////////////////////////////////////////// // // MenuButton - Events // //////////////////////////////////////////////////////////////////////////////// int MenuButton::GetMaximumScreenXCoordinate() { if (!GetWidget()) { NOTREACHED(); return 0; } gfx::Rect monitor_bounds = Screen::GetMonitorWorkAreaNearestWindow(GetWidget()->GetNativeView()); return monitor_bounds.right() - 1; } bool MenuButton::Activate() { SetState(BS_PUSHED); // We need to synchronously paint here because subsequently we enter a // menu modal loop which will stop this window from updating and // receiving the paint message that should be spawned by SetState until // after the menu closes. PaintNow(); if (menu_delegate_) { gfx::Rect lb = GetLocalBounds(true); // The position of the menu depends on whether or not the locale is // right-to-left. gfx::Point menu_position(lb.right(), lb.bottom()); if (UILayoutIsRightToLeft()) menu_position.set_x(lb.x()); View::ConvertPointToScreen(this, &menu_position); if (UILayoutIsRightToLeft()) menu_position.Offset(2, -4); else menu_position.Offset(-2, -4); int max_x_coordinate = GetMaximumScreenXCoordinate(); if (max_x_coordinate && max_x_coordinate <= menu_position.x()) menu_position.set_x(max_x_coordinate - 1); // We're about to show the menu from a mouse press. By showing from the // mouse press event we block RootView in mouse dispatching. This also // appears to cause RootView to get a mouse pressed BEFORE the mouse // release is seen, which means RootView sends us another mouse press no // matter where the user pressed. To force RootView to recalculate the // mouse target during the mouse press we explicitly set the mouse handler // to NULL. GetRootView()->SetMouseHandler(NULL); menu_visible_ = true; menu_delegate_->RunMenu(this, menu_position); menu_visible_ = false; menu_closed_time_ = Time::Now(); // Now that the menu has closed, we need to manually reset state to // "normal" since the menu modal loop will have prevented normal // mouse move messages from getting to this View. We set "normal" // and not "hot" because the likelihood is that the mouse is now // somewhere else (user clicked elsewhere on screen to close the menu // or selected an item) and we will inevitably refresh the hot state // in the event the mouse _is_ over the view. SetState(BS_NORMAL); // We must return false here so that the RootView does not get stuck // sending all mouse pressed events to us instead of the appropriate // target. return false; } return true; } bool MenuButton::OnMousePressed(const MouseEvent& e) { RequestFocus(); if (state() != BS_DISABLED) { // If we're draggable (GetDragOperations returns a non-zero value), then // don't pop on press, instead wait for release. if (e.IsOnlyLeftMouseButton() && HitTest(e.location()) && GetDragOperations(e.x(), e.y()) == DragDropTypes::DRAG_NONE) { TimeDelta delta = Time::Now() - menu_closed_time_; int64 delta_in_milliseconds = delta.InMilliseconds(); if (delta_in_milliseconds > kMinimumTimeBetweenButtonClicks) { return Activate(); } } } return true; } void MenuButton::OnMouseReleased(const MouseEvent& e, bool canceled) { if (GetDragOperations(e.x(), e.y()) != DragDropTypes::DRAG_NONE && state() != BS_DISABLED && !canceled && !InDrag() && !IsTriggerableEvent(e) && HitTest(e.location())) { Activate(); } else { TextButton::OnMouseReleased(e, canceled); } } // When the space bar or the enter key is pressed we need to show the menu. bool MenuButton::OnKeyReleased(const KeyEvent& e) { #if defined(OS_WIN) if ((e.GetKeyCode() == base::VKEY_SPACE) || (e.GetKeyCode() == base::VKEY_RETURN)) { return Activate(); } #else NOTIMPLEMENTED(); #endif return true; } // The reason we override View::OnMouseExited is because we get this event when // we display the menu. If we don't override this method then // BaseButton::OnMouseExited will get the event and will set the button's state // to BS_NORMAL instead of keeping the state BM_PUSHED. This, in turn, will // cause the button to appear depressed while the menu is displayed. void MenuButton::OnMouseExited(const MouseEvent& event) { if ((state_ != BS_DISABLED) && (!menu_visible_) && (!InDrag())) { SetState(BS_NORMAL); } } //////////////////////////////////////////////////////////////////////////////// // // MenuButton - accessibility // //////////////////////////////////////////////////////////////////////////////// bool MenuButton::GetAccessibleDefaultAction(std::wstring* action) { DCHECK(action); action->assign(l10n_util::GetString(IDS_APP_ACCACTION_PRESS)); return true; } bool MenuButton::GetAccessibleRole(AccessibilityTypes::Role* role) { DCHECK(role); *role = AccessibilityTypes::ROLE_BUTTONMENU; return true; } bool MenuButton::GetAccessibleState(AccessibilityTypes::State* state) { DCHECK(state); *state = AccessibilityTypes::STATE_HASPOPUP; return true; } } // namespace views <commit_msg>Fixes regression introduced in fixing 19597. This change effectively reverts menu_button to what it was before the fix. This way 19597 is still fixed, and we don't have this crash. I'm working on a regression test for coverage of this, but I don't want to hold up anything with the fix. <commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/controls/button/menu_button.h" #include "app/drag_drop_types.h" #include "app/gfx/canvas.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "grit/app_strings.h" #include "grit/app_resources.h" #include "views/controls/button/button.h" #include "views/controls/menu/view_menu_delegate.h" #include "views/event.h" #include "views/screen.h" #include "views/widget/root_view.h" #include "views/widget/widget.h" #include "views/window/window.h" using base::Time; using base::TimeDelta; namespace views { // The amount of time, in milliseconds, we wait before allowing another mouse // pressed event to show the menu. static const int64 kMinimumTimeBetweenButtonClicks = 100; // The down arrow used to differentiate the menu button from normal // text buttons. static const SkBitmap* kMenuMarker = NULL; // How much padding to put on the left and right of the menu marker. static const int kMenuMarkerPaddingLeft = 3; static const int kMenuMarkerPaddingRight = -1; //////////////////////////////////////////////////////////////////////////////// // // MenuButton - constructors, destructors, initialization // //////////////////////////////////////////////////////////////////////////////// MenuButton::MenuButton(ButtonListener* listener, const std::wstring& text, ViewMenuDelegate* menu_delegate, bool show_menu_marker) : TextButton(listener, text), menu_visible_(false), menu_delegate_(menu_delegate), show_menu_marker_(show_menu_marker) { if (kMenuMarker == NULL) { kMenuMarker = ResourceBundle::GetSharedInstance() .GetBitmapNamed(IDR_MENU_DROPARROW); } set_alignment(TextButton::ALIGN_LEFT); } MenuButton::~MenuButton() { } //////////////////////////////////////////////////////////////////////////////// // // MenuButton - Public APIs // //////////////////////////////////////////////////////////////////////////////// gfx::Size MenuButton::GetPreferredSize() { gfx::Size prefsize = TextButton::GetPreferredSize(); if (show_menu_marker_) { prefsize.Enlarge(kMenuMarker->width() + kMenuMarkerPaddingLeft + kMenuMarkerPaddingRight, 0); } return prefsize; } void MenuButton::Paint(gfx::Canvas* canvas, bool for_drag) { TextButton::Paint(canvas, for_drag); if (show_menu_marker_) { gfx::Insets insets = GetInsets(); // We can not use the views' mirroring infrastructure for mirroring a // MenuButton control (see TextButton::Paint() for a detailed explanation // regarding why we can not flip the canvas). Therefore, we need to // manually mirror the position of the down arrow. gfx::Rect arrow_bounds(width() - insets.right() - kMenuMarker->width() - kMenuMarkerPaddingRight, height() / 2 - kMenuMarker->height() / 2, kMenuMarker->width(), kMenuMarker->height()); arrow_bounds.set_x(MirroredLeftPointForRect(arrow_bounds)); canvas->DrawBitmapInt(*kMenuMarker, arrow_bounds.x(), arrow_bounds.y()); } } //////////////////////////////////////////////////////////////////////////////// // // MenuButton - Events // //////////////////////////////////////////////////////////////////////////////// int MenuButton::GetMaximumScreenXCoordinate() { if (!GetWidget()) { NOTREACHED(); return 0; } gfx::Rect monitor_bounds = Screen::GetMonitorWorkAreaNearestWindow(GetWidget()->GetNativeView()); return monitor_bounds.right() - 1; } bool MenuButton::Activate() { SetState(BS_PUSHED); // We need to synchronously paint here because subsequently we enter a // menu modal loop which will stop this window from updating and // receiving the paint message that should be spawned by SetState until // after the menu closes. PaintNow(); if (menu_delegate_) { gfx::Rect lb = GetLocalBounds(true); // The position of the menu depends on whether or not the locale is // right-to-left. gfx::Point menu_position(lb.right(), lb.bottom()); if (UILayoutIsRightToLeft()) menu_position.set_x(lb.x()); View::ConvertPointToScreen(this, &menu_position); if (UILayoutIsRightToLeft()) menu_position.Offset(2, -4); else menu_position.Offset(-2, -4); int max_x_coordinate = GetMaximumScreenXCoordinate(); if (max_x_coordinate && max_x_coordinate <= menu_position.x()) menu_position.set_x(max_x_coordinate - 1); // We're about to show the menu from a mouse press. By showing from the // mouse press event we block RootView in mouse dispatching. This also // appears to cause RootView to get a mouse pressed BEFORE the mouse // release is seen, which means RootView sends us another mouse press no // matter where the user pressed. To force RootView to recalculate the // mouse target during the mouse press we explicitly set the mouse handler // to NULL. GetRootView()->SetMouseHandler(NULL); menu_visible_ = true; menu_delegate_->RunMenu(this, menu_position); menu_visible_ = false; menu_closed_time_ = Time::Now(); // Now that the menu has closed, we need to manually reset state to // "normal" since the menu modal loop will have prevented normal // mouse move messages from getting to this View. We set "normal" // and not "hot" because the likelihood is that the mouse is now // somewhere else (user clicked elsewhere on screen to close the menu // or selected an item) and we will inevitably refresh the hot state // in the event the mouse _is_ over the view. SetState(BS_NORMAL); // We must return false here so that the RootView does not get stuck // sending all mouse pressed events to us instead of the appropriate // target. return false; } return true; } bool MenuButton::OnMousePressed(const MouseEvent& e) { RequestFocus(); if (state() != BS_DISABLED) { // If we're draggable (GetDragOperations returns a non-zero value), then // don't pop on press, instead wait for release. if (e.IsOnlyLeftMouseButton() && HitTest(e.location()) && GetDragOperations(e.x(), e.y()) == DragDropTypes::DRAG_NONE) { TimeDelta delta = Time::Now() - menu_closed_time_; int64 delta_in_milliseconds = delta.InMilliseconds(); if (delta_in_milliseconds > kMinimumTimeBetweenButtonClicks) { return Activate(); } } } return true; } void MenuButton::OnMouseReleased(const MouseEvent& e, bool canceled) { // Explicitly test for left mouse button to show the menu. If we tested for // !IsTriggerableEvent it could lead to a situation where we end up showing // the menu and context menu (this would happen if the right button is not // triggerable and there's a context menu). if (GetDragOperations(e.x(), e.y()) != DragDropTypes::DRAG_NONE && state() != BS_DISABLED && !canceled && !InDrag() && e.IsOnlyLeftMouseButton() && HitTest(e.location())) { Activate(); } else { TextButton::OnMouseReleased(e, canceled); } } // When the space bar or the enter key is pressed we need to show the menu. bool MenuButton::OnKeyReleased(const KeyEvent& e) { #if defined(OS_WIN) if ((e.GetKeyCode() == base::VKEY_SPACE) || (e.GetKeyCode() == base::VKEY_RETURN)) { return Activate(); } #else NOTIMPLEMENTED(); #endif return true; } // The reason we override View::OnMouseExited is because we get this event when // we display the menu. If we don't override this method then // BaseButton::OnMouseExited will get the event and will set the button's state // to BS_NORMAL instead of keeping the state BM_PUSHED. This, in turn, will // cause the button to appear depressed while the menu is displayed. void MenuButton::OnMouseExited(const MouseEvent& event) { if ((state_ != BS_DISABLED) && (!menu_visible_) && (!InDrag())) { SetState(BS_NORMAL); } } //////////////////////////////////////////////////////////////////////////////// // // MenuButton - accessibility // //////////////////////////////////////////////////////////////////////////////// bool MenuButton::GetAccessibleDefaultAction(std::wstring* action) { DCHECK(action); action->assign(l10n_util::GetString(IDS_APP_ACCACTION_PRESS)); return true; } bool MenuButton::GetAccessibleRole(AccessibilityTypes::Role* role) { DCHECK(role); *role = AccessibilityTypes::ROLE_BUTTONMENU; return true; } bool MenuButton::GetAccessibleState(AccessibilityTypes::State* state) { DCHECK(state); *state = AccessibilityTypes::STATE_HASPOPUP; return true; } } // namespace views <|endoftext|>
<commit_before>// Copyright 2015 Las Venturas Playground. All rights reserved. // Use of this source code is governed by the MIT license, a copy of which can // be found in the LICENSE file. #include "plugin/native_function_manager.h" #include <string.h> #include "base/logging.h" #include "plugin/fake_amx.h" #include "plugin/sdk/amx.h" #include "plugin/sdk/plugincommon.h" #include "third_party/subhook/subhook.h" namespace plugin { namespace { // The Incognito streamer unfortunately derives from the [array][array_size] parameters being right // next to each other-paradigm, so we need to special case those. size_t GetArraySizeOffsetForFunctionName(const std::string& function_name) { if (function_name.rfind("CreateDynamic") == 0) return 5; return 1; } // Type definition of the original amx_Register_t function that is being intercepted. typedef int AMXAPI(*amx_Register_t)(AMX* amx, const AMX_NATIVE_INFO* nativelist, int number); // Global instance of the NativeFunctionManager instance, only to be used by amx_Register_hook(). NativeFunctionManager* g_native_function_manager = nullptr; int amx_Register_hook(AMX* amx, const AMX_NATIVE_INFO* nativelist, int number) { return g_native_function_manager->OnRegister(amx, nativelist, number); } } // namespace NativeFunctionManager::NativeFunctionManager() : fake_amx_(new FakeAMX) { g_native_function_manager = this; } NativeFunctionManager::~NativeFunctionManager() { g_native_function_manager = nullptr; } bool NativeFunctionManager::Install() { if (!pAMXFunctions) return true; // testing void* current_address = static_cast<void**>(pAMXFunctions)[PLUGIN_AMX_EXPORT_Register]; if (current_address == nullptr) { LOG(ERROR) << "Invalid address found for the amx_Register() function."; return false; } hook_.reset(new SubHook(current_address, (void*) amx_Register_hook)); if (!hook_->Install()) { LOG(ERROR) << "Unable to install a SubHook for the amx_Register() function."; return false; } return true; } int NativeFunctionManager::OnRegister(AMX* amx, const AMX_NATIVE_INFO* nativelist, int number) { if (nativelist != nullptr) { for (size_t index = 0; ; ++index) { if (number > 0 && static_cast<int>(index) >= number) break; if (nativelist[index].func == nullptr || nativelist[index].name == nullptr) break; const std::string native_name(nativelist[index].name); // The Pawn interpreter iterates over unresolved functions in the gamemode, and finds them in // the functions that are being registered in the amx_Register() call. This means that the first // function registered for a given name will be used, rather than having later registrations // override previous ones. Simply drop out if a double-registration is observed. if (!FunctionExists(native_name)) native_functions_[native_name] = static_cast<NativeFn*>(nativelist[index].func); } } // Trampoline back to the original amx_Register function that we intercepted. return ((amx_Register_t) hook_->GetTrampoline())(amx, nativelist, number); } bool NativeFunctionManager::FunctionExists(const std::string& function_name) const { return native_functions_.find(function_name) != native_functions_.end(); } int NativeFunctionManager::CallFunction(const std::string& function_name, const char* format, void** arguments) { auto function_iter = native_functions_.find(function_name); if (function_iter == native_functions_.end()) { LOG(WARNING) << "Attempting to invoke unknown Pawn native " << function_name << ". Ignoring."; return -1; } AMX* amx = fake_amx_->amx(); size_t param_count = format ? strlen(format) : 0; params_.resize(param_count + 1); params_[0] = param_count * sizeof(cell); // Early-return if there are no arguments required for this native invication. if (!param_count) return function_iter->second(amx, params_.data()); size_t arraySizeParamOffset = GetArraySizeOffsetForFunctionName(function_name); auto amx_stack = fake_amx_->GetScopedStackModifier(); DCHECK(arguments); // Process the existing parameters, either store them in |params_| or push them on the stack. for (size_t i = 0; i < param_count; ++i) { switch (format[i]) { case 'i': params_[i + 1] = *reinterpret_cast<cell*>(arguments[i]); break; case 'f': params_[i + 1] = amx_ftoc(*reinterpret_cast<float*>(arguments[i])); break; case 'r': params_[i + 1] = amx_stack.PushCell(*reinterpret_cast<cell*>(arguments[i])); break; case 's': params_[i + 1] = amx_stack.PushString(reinterpret_cast<char*>(arguments[i])); break; case 'a': if (format[i + arraySizeParamOffset] != 'i') { LOG(WARNING) << "Cannot invoke " << function_name << ": 'a' parameter must be followed by a 'i'."; return -1; } { int32_t size = *reinterpret_cast<int32_t*>(arguments[i + arraySizeParamOffset]); params_[i + 1] = amx_stack.PushArray(reinterpret_cast<cell*>(arguments[i]), size); if (arraySizeParamOffset == 1) params_[i + 1 + arraySizeParamOffset] = size; } if (arraySizeParamOffset == 1) ++i; break; } } const int return_value = function_iter->second(amx, params_.data()); // Read back the values which may have been modified by the SA-MP server. for (size_t i = 0; i < param_count; ++i) { switch (format[i]) { case 'r': amx_stack.ReadCell(params_[i + 1], reinterpret_cast<cell*>(arguments[i])); break; case 'a': { char* data = reinterpret_cast<char*>(arguments[i]); int32_t size = *reinterpret_cast<int32_t*>(arguments[i + arraySizeParamOffset]); amx_stack.ReadArray(params_[i + 1], data, size); } break; } } return return_value; } } // namespace plugin <commit_msg>Enable the area functions to be used in JavaScript too<commit_after>// Copyright 2015 Las Venturas Playground. All rights reserved. // Use of this source code is governed by the MIT license, a copy of which can // be found in the LICENSE file. #include "plugin/native_function_manager.h" #include <set> #include <string.h> #include "base/logging.h" #include "plugin/fake_amx.h" #include "plugin/sdk/amx.h" #include "plugin/sdk/plugincommon.h" #include "third_party/subhook/subhook.h" namespace plugin { namespace { const std::set<std::string> kDynamicEntityFunctions{ "CreateDynamic3DTextLabelEx", "CreateDynamicActorEx", "CreateDynamicCPEx", "CreateDynamicMapIconEx", "CreateDynamicObjectEx", "CreateDynamicPickupEx", "CreateDynamicRaceCPEx" }; const std::set<std::string> kDynamicAreaFunctions{ "CreateDynamicCircleEx", "CreateDynamicCubeEx", "CreateDynamicCuboidEx", "CreateDynamicCylinderEx", "CreateDynamicPolygonEx", "CreateDynamicRectangleEx", "CreateDynamicSphereEx" }; // The Incognito streamer unfortunately derives from the [array][array_size] parameters being right // next to each other-paradigm, so we need to special case those. size_t GetArraySizeOffsetForFunctionName(const std::string& function_name) { if (function_name.rfind("CreateDynamic") != 0) return 1; if (kDynamicEntityFunctions.find(function_name) != kDynamicEntityFunctions.end()) return 5; if (kDynamicAreaFunctions.find(function_name) != kDynamicAreaFunctions.end()) return 4; return 1; } // Type definition of the original amx_Register_t function that is being intercepted. typedef int AMXAPI(*amx_Register_t)(AMX* amx, const AMX_NATIVE_INFO* nativelist, int number); // Global instance of the NativeFunctionManager instance, only to be used by amx_Register_hook(). NativeFunctionManager* g_native_function_manager = nullptr; int amx_Register_hook(AMX* amx, const AMX_NATIVE_INFO* nativelist, int number) { return g_native_function_manager->OnRegister(amx, nativelist, number); } } // namespace NativeFunctionManager::NativeFunctionManager() : fake_amx_(new FakeAMX) { g_native_function_manager = this; } NativeFunctionManager::~NativeFunctionManager() { g_native_function_manager = nullptr; } bool NativeFunctionManager::Install() { if (!pAMXFunctions) return true; // testing void* current_address = static_cast<void**>(pAMXFunctions)[PLUGIN_AMX_EXPORT_Register]; if (current_address == nullptr) { LOG(ERROR) << "Invalid address found for the amx_Register() function."; return false; } hook_.reset(new SubHook(current_address, (void*) amx_Register_hook)); if (!hook_->Install()) { LOG(ERROR) << "Unable to install a SubHook for the amx_Register() function."; return false; } return true; } int NativeFunctionManager::OnRegister(AMX* amx, const AMX_NATIVE_INFO* nativelist, int number) { if (nativelist != nullptr) { for (size_t index = 0; ; ++index) { if (number > 0 && static_cast<int>(index) >= number) break; if (nativelist[index].func == nullptr || nativelist[index].name == nullptr) break; const std::string native_name(nativelist[index].name); // The Pawn interpreter iterates over unresolved functions in the gamemode, and finds them in // the functions that are being registered in the amx_Register() call. This means that the first // function registered for a given name will be used, rather than having later registrations // override previous ones. Simply drop out if a double-registration is observed. if (!FunctionExists(native_name)) native_functions_[native_name] = static_cast<NativeFn*>(nativelist[index].func); } } // Trampoline back to the original amx_Register function that we intercepted. return ((amx_Register_t) hook_->GetTrampoline())(amx, nativelist, number); } bool NativeFunctionManager::FunctionExists(const std::string& function_name) const { return native_functions_.find(function_name) != native_functions_.end(); } int NativeFunctionManager::CallFunction(const std::string& function_name, const char* format, void** arguments) { auto function_iter = native_functions_.find(function_name); if (function_iter == native_functions_.end()) { LOG(WARNING) << "Attempting to invoke unknown Pawn native " << function_name << ". Ignoring."; return -1; } AMX* amx = fake_amx_->amx(); size_t param_count = format ? strlen(format) : 0; params_.resize(param_count + 1); params_[0] = param_count * sizeof(cell); // Early-return if there are no arguments required for this native invication. if (!param_count) return function_iter->second(amx, params_.data()); size_t arraySizeParamOffset = GetArraySizeOffsetForFunctionName(function_name); auto amx_stack = fake_amx_->GetScopedStackModifier(); DCHECK(arguments); // Process the existing parameters, either store them in |params_| or push them on the stack. for (size_t i = 0; i < param_count; ++i) { switch (format[i]) { case 'i': params_[i + 1] = *reinterpret_cast<cell*>(arguments[i]); break; case 'f': params_[i + 1] = amx_ftoc(*reinterpret_cast<float*>(arguments[i])); break; case 'r': params_[i + 1] = amx_stack.PushCell(*reinterpret_cast<cell*>(arguments[i])); break; case 's': params_[i + 1] = amx_stack.PushString(reinterpret_cast<char*>(arguments[i])); break; case 'a': if (format[i + arraySizeParamOffset] != 'i') { LOG(WARNING) << "Cannot invoke " << function_name << ": 'a' parameter must be followed by a 'i'."; return -1; } { int32_t size = *reinterpret_cast<int32_t*>(arguments[i + arraySizeParamOffset]); params_[i + 1] = amx_stack.PushArray(reinterpret_cast<cell*>(arguments[i]), size); if (arraySizeParamOffset == 1) params_[i + 1 + arraySizeParamOffset] = size; } if (arraySizeParamOffset == 1) ++i; break; } } const int return_value = function_iter->second(amx, params_.data()); // Read back the values which may have been modified by the SA-MP server. for (size_t i = 0; i < param_count; ++i) { switch (format[i]) { case 'r': amx_stack.ReadCell(params_[i + 1], reinterpret_cast<cell*>(arguments[i])); break; case 'a': { char* data = reinterpret_cast<char*>(arguments[i]); int32_t size = *reinterpret_cast<int32_t*>(arguments[i + arraySizeParamOffset]); amx_stack.ReadArray(params_[i + 1], data, size); } break; } } return return_value; } } // namespace plugin <|endoftext|>
<commit_before>#include <OGLPlugin/VertexArray.h> IMPGEARS_BEGIN std::uint32_t VertexArray::_s_count = 0; std::uint32_t VertexArray::_s_vboCount = 0; //-------------------------------------------------------------- VertexArray::VertexArray() { _vao = 0; _buffers.resize(Buffer_Count, 0); _primitive = Geometry::Primitive_Triangles; _useElements = false; _instanced = false; _count = 0; _instanceCount = 0; glGenVertexArrays(1, &_vao); GL_CHECKERROR("gen vao"); _s_count++; glGenBuffers(_buffers.size(), _buffers.data()); GL_CHECKERROR("gen vbo"); _s_vboCount += _buffers.size(); } //-------------------------------------------------------------- VertexArray::~VertexArray() { use(); glDeleteBuffers(_buffers.size(), _buffers.data()); GL_CHECKERROR("delete vbo"); _s_vboCount -= _buffers.size(); glDeleteBuffers(1, &_vao); GL_CHECKERROR("delete vao"); _s_count--; } //-------------------------------------------------------------- void VertexArray::load(const Geometry& geometry) { _useElements = geometry._hasIndices; _primitive = geometry.getPrimitive(); std::vector<float> buf; geometry.fillBuffer( buf ); loadBuffer<float>(Buffer_Vertices, buf); _count = geometry.size(); if(geometry._hasColors) { std::vector<float> buf; fillBuffer<float,3,Vec3>(buf, geometry._colors); loadBuffer<float>(Buffer_Colors, buf); } if(geometry._hasNormals) { std::vector<float> buf; fillBuffer<float,3,Vec3>(buf, geometry._normals); loadBuffer<float>(Buffer_Normals, buf); } if(geometry._hasTexCoords) { std::vector<float> buf; fillBuffer<float,2,Geometry::TexCoord>(buf, geometry._texCoords); loadBuffer<float>(Buffer_TexCoords, buf); } if(geometry._hasIndices) { loadBuffer<std::uint32_t>(Buffer_Indices, geometry._indices, true); _count = geometry._indices.size(); } const InstancedGeometry* instancedGeo = dynamic_cast<const InstancedGeometry*>( &geometry ); if(instancedGeo && instancedGeo->getTransforms().size()>0)// && instancedGeo->hasChanged()) { std::cout << "instanced geometry detected" << std::endl; const std::vector<Matrix4>& bufMat = instancedGeo->getTransforms(); _instanced = bufMat.size()>0; _instanceCount = bufMat.size(); std::vector<float> buf(_instanceCount * 16); for(int i=0;i<_instanceCount;++i) { const float* data = bufMat[i].data(); for(int k=0;k<16;++k) buf[i*16+k] = data[k]; } loadBuffer<float>(Buffer_InstTransforms, buf); } GLuint glVertex = 0, glColor = 1, glNormal = 2, glTexCoord = 3; GLuint glInstTransform1 = 4, glInstTransform2 = 5, glInstTransform3 = 6, glInstTransform4 = 7; enableAttrib(Buffer_Vertices, glVertex, 3, sizeof(float)*3, 0); if(geometry._hasColors) enableAttrib(Buffer_Colors, glColor, 3, sizeof(float)*3, 0); if(geometry._hasNormals) enableAttrib(Buffer_Normals, glNormal, 3, sizeof(float)*3, 0); if(geometry._hasTexCoords) enableAttrib(Buffer_TexCoords, glTexCoord, 2, sizeof(float)*2, 0); if(_instanced) { GLsizei vec4size = sizeof(float)*4; enableAttrib(Buffer_InstTransforms, glInstTransform1, 4, 4*vec4size, 0*4); enableAttrib(Buffer_InstTransforms, glInstTransform2, 4, 4*vec4size, 1*4); enableAttrib(Buffer_InstTransforms, glInstTransform3, 4, 4*vec4size, 2*4); enableAttrib(Buffer_InstTransforms, glInstTransform4, 4, 4*vec4size, 3*4); glVertexAttribDivisor(glInstTransform1, 1); glVertexAttribDivisor(glInstTransform2, 1); glVertexAttribDivisor(glInstTransform3, 1); glVertexAttribDivisor(glInstTransform4, 1); } } //-------------------------------------------------------------- void VertexArray::enableAttrib(BufferName bufName, GLuint location, int size, int stride, int offset) { if(bufName == Buffer_Indices) return; GLenum glType = GL_FLOAT; void* addrOffset = (void*) (sizeof(float) * offset); use(); glBindBuffer(GL_ARRAY_BUFFER, _buffers[bufName]); GL_CHECKERROR("VertexArray::enableAttrib bind"); glEnableVertexAttribArray(location); GL_CHECKERROR("VertexArray::enableAttrib enable"); glVertexAttribPointer(location, size, glType, GL_FALSE, stride, addrOffset); GL_CHECKERROR("VertexArray::enableAttrib pointer"); } //-------------------------------------------------------------- void VertexArray::use() { glBindVertexArray(_vao); GL_CHECKERROR("VertexArray use"); } //-------------------------------------------------------------- void VertexArray::draw() { use(); GLenum glPrimitive = GL_TRIANGLES; if(_primitive == Geometry::Primitive_Points) glPrimitive = GL_POINTS; else if(_primitive == Geometry::Primitive_Lines) glPrimitive = GL_LINES; else if(_primitive == Geometry::Primitive_Triangles) glPrimitive = GL_TRIANGLES; if(_useElements && _instanced) glDrawElementsInstanced(glPrimitive,_count,GL_UNSIGNED_INT,(void*)0,_instanceCount); else if(_useElements) glDrawElements(glPrimitive, _count, GL_UNSIGNED_INT, (void*)0); else if(_instanced) glDrawArraysInstanced(glPrimitive,0,_count,_instanceCount); else glDrawArrays(glPrimitive, 0, _count); GL_CHECKERROR("VertexArray draw"); } IMPGEARS_END <commit_msg>bad gl call for deleting vao<commit_after>#include <OGLPlugin/VertexArray.h> IMPGEARS_BEGIN std::uint32_t VertexArray::_s_count = 0; std::uint32_t VertexArray::_s_vboCount = 0; //-------------------------------------------------------------- VertexArray::VertexArray() { _vao = 0; _buffers.resize(Buffer_Count, 0); _primitive = Geometry::Primitive_Triangles; _useElements = false; _instanced = false; _count = 0; _instanceCount = 0; glGenVertexArrays(1, &_vao); GL_CHECKERROR("gen vao"); _s_count++; glGenBuffers(_buffers.size(), _buffers.data()); GL_CHECKERROR("gen vbo"); _s_vboCount += _buffers.size(); } //-------------------------------------------------------------- VertexArray::~VertexArray() { use(); glDeleteBuffers(_buffers.size(), _buffers.data()); GL_CHECKERROR("delete vbo"); _s_vboCount -= _buffers.size(); glDeleteVertexArrays(1, &_vao); GL_CHECKERROR("delete vao"); _s_count--; } //-------------------------------------------------------------- void VertexArray::load(const Geometry& geometry) { _useElements = geometry._hasIndices; _primitive = geometry.getPrimitive(); std::vector<float> buf; geometry.fillBuffer( buf ); loadBuffer<float>(Buffer_Vertices, buf); _count = geometry.size(); if(geometry._hasColors) { std::vector<float> buf; fillBuffer<float,3,Vec3>(buf, geometry._colors); loadBuffer<float>(Buffer_Colors, buf); } if(geometry._hasNormals) { std::vector<float> buf; fillBuffer<float,3,Vec3>(buf, geometry._normals); loadBuffer<float>(Buffer_Normals, buf); } if(geometry._hasTexCoords) { std::vector<float> buf; fillBuffer<float,2,Geometry::TexCoord>(buf, geometry._texCoords); loadBuffer<float>(Buffer_TexCoords, buf); } if(geometry._hasIndices) { loadBuffer<std::uint32_t>(Buffer_Indices, geometry._indices, true); _count = geometry._indices.size(); } const InstancedGeometry* instancedGeo = dynamic_cast<const InstancedGeometry*>( &geometry ); if(instancedGeo && instancedGeo->getTransforms().size()>0)// && instancedGeo->hasChanged()) { std::cout << "instanced geometry detected" << std::endl; const std::vector<Matrix4>& bufMat = instancedGeo->getTransforms(); _instanced = bufMat.size()>0; _instanceCount = bufMat.size(); std::vector<float> buf(_instanceCount * 16); for(int i=0;i<_instanceCount;++i) { const float* data = bufMat[i].data(); for(int k=0;k<16;++k) buf[i*16+k] = data[k]; } loadBuffer<float>(Buffer_InstTransforms, buf); } GLuint glVertex = 0, glColor = 1, glNormal = 2, glTexCoord = 3; GLuint glInstTransform1 = 4, glInstTransform2 = 5, glInstTransform3 = 6, glInstTransform4 = 7; enableAttrib(Buffer_Vertices, glVertex, 3, sizeof(float)*3, 0); if(geometry._hasColors) enableAttrib(Buffer_Colors, glColor, 3, sizeof(float)*3, 0); if(geometry._hasNormals) enableAttrib(Buffer_Normals, glNormal, 3, sizeof(float)*3, 0); if(geometry._hasTexCoords) enableAttrib(Buffer_TexCoords, glTexCoord, 2, sizeof(float)*2, 0); if(_instanced) { GLsizei vec4size = sizeof(float)*4; enableAttrib(Buffer_InstTransforms, glInstTransform1, 4, 4*vec4size, 0*4); enableAttrib(Buffer_InstTransforms, glInstTransform2, 4, 4*vec4size, 1*4); enableAttrib(Buffer_InstTransforms, glInstTransform3, 4, 4*vec4size, 2*4); enableAttrib(Buffer_InstTransforms, glInstTransform4, 4, 4*vec4size, 3*4); glVertexAttribDivisor(glInstTransform1, 1); glVertexAttribDivisor(glInstTransform2, 1); glVertexAttribDivisor(glInstTransform3, 1); glVertexAttribDivisor(glInstTransform4, 1); } } //-------------------------------------------------------------- void VertexArray::enableAttrib(BufferName bufName, GLuint location, int size, int stride, int offset) { if(bufName == Buffer_Indices) return; GLenum glType = GL_FLOAT; void* addrOffset = (void*) (sizeof(float) * offset); use(); glBindBuffer(GL_ARRAY_BUFFER, _buffers[bufName]); GL_CHECKERROR("VertexArray::enableAttrib bind"); glEnableVertexAttribArray(location); GL_CHECKERROR("VertexArray::enableAttrib enable"); glVertexAttribPointer(location, size, glType, GL_FALSE, stride, addrOffset); GL_CHECKERROR("VertexArray::enableAttrib pointer"); } //-------------------------------------------------------------- void VertexArray::use() { glBindVertexArray(_vao); GL_CHECKERROR("VertexArray use"); } //-------------------------------------------------------------- void VertexArray::draw() { use(); GLenum glPrimitive = GL_TRIANGLES; if(_primitive == Geometry::Primitive_Points) glPrimitive = GL_POINTS; else if(_primitive == Geometry::Primitive_Lines) glPrimitive = GL_LINES; else if(_primitive == Geometry::Primitive_Triangles) glPrimitive = GL_TRIANGLES; if(_useElements && _instanced) glDrawElementsInstanced(glPrimitive,_count,GL_UNSIGNED_INT,(void*)0,_instanceCount); else if(_useElements) glDrawElements(glPrimitive, _count, GL_UNSIGNED_INT, (void*)0); else if(_instanced) glDrawArraysInstanced(glPrimitive,0,_count,_instanceCount); else glDrawArrays(glPrimitive, 0, _count); GL_CHECKERROR("VertexArray draw"); } IMPGEARS_END <|endoftext|>
<commit_before>#include "chainerx/native/native_device.h" #include <cmath> #include <cstdint> #include <type_traits> #include "chainerx/array.h" #include "chainerx/backend.h" #include "chainerx/device.h" #include "chainerx/dtype.h" #include "chainerx/indexable_array.h" #include "chainerx/kernels/creation.h" #include "chainerx/kernels/linalg.h" #include "chainerx/macro.h" #include "chainerx/native/data_type.h" #include "chainerx/native/elementwise.h" #include "chainerx/native/kernel_regist.h" #include "chainerx/routines/creation.h" #include "chainerx/routines/indexing.h" #include "chainerx/shape.h" #if CHAINERX_ENABLE_LAPACK extern "C" { // gesv void dgesv_(int* n, int* nrhs, double* a, int* lda, int* ipiv, double* b, int* ldb, int* info); void sgesv_(int* n, int* nrhs, float* a, int* lda, int* ipiv, float* b, int* ldb, int* info); // getrf void dgetrf_(int* m, int* n, double* a, int* lda, int* ipiv, int* info); void sgetrf_(int* m, int* n, float* a, int* lda, int* ipiv, int* info); // getri void dgetri_(int* n, double* a, int* lda, int* ipiv, double* work, int* lwork, int* info); void sgetri_(int* n, float* a, int* lda, int* ipiv, float* work, int* lwork, int* info); // gesdd void dgesdd_( char* jobz, int* m, int* n, double* a, int* lda, double* s, double* u, int* ldu, double* vt, int* ldvt, double* work, int* lwork, int* iwork, int* info); void sgesdd_( char* jobz, int* m, int* n, float* a, int* lda, float* s, float* u, int* ldu, float* vt, int* ldvt, float* work, int* lwork, int* iwork, int* info); } #endif // CHAINERX_ENABLE_LAPACK namespace chainerx { namespace native { namespace { template <typename T> void Gesv(int /*n*/, int /*nrhs*/, T* /*a*/, int /*lda*/, int* /*ipiv*/, T* /*b*/, int /*ldb*/, int* /*info*/) { throw DtypeError{"Only Arrays of float or double type are supported by gesv (Solve)"}; } template <typename T> void Getrf(int /*m*/, int /*n*/, T* /*a*/, int /*lda*/, int* /*ipiv*/, int* /*info*/) { throw DtypeError{"Only Arrays of float or double type are supported by getri (LU)"}; } template <typename T> void Getri(int /*n*/, T* /*a*/, int /*lda*/, int* /*ipiv*/, T* /*work*/, int /*lwork*/, int* /*info*/) { throw DtypeError{"Only Arrays of float or double type are supported by getri (Inverse LU)"}; } template <typename T> void Gesdd( char /*jobz*/, int /*m*/, int /*n*/, T* /*a*/, int /*lda*/, T* /*s*/, T* /*u*/, int /*ldu*/, T* /*vt*/, int /*ldvt*/, T* /*work*/, int /*lwork*/, int* /*iwork*/, int* /*info*/) { throw DtypeError{"Only Arrays of float or double type are supported by gesdd (SVD)"}; } #if CHAINERX_ENABLE_LAPACK template <> void Gesv<double>(int n, int nrhs, double* a, int lda, int* ipiv, double* b, int ldb, int* info) { dgesv_(&n, &nrhs, a, &lda, ipiv, b, &ldb, info); } template <> void Gesv<float>(int n, int nrhs, float* a, int lda, int* ipiv, float* b, int ldb, int* info) { sgesv_(&n, &nrhs, a, &lda, ipiv, b, &ldb, info); } template <> void Getrf<double>(int m, int n, double* a, int lda, int* ipiv, int* info) { dgetrf_(&m, &n, a, &lda, ipiv, info); } template <> void Getrf<float>(int m, int n, float* a, int lda, int* ipiv, int* info) { sgetrf_(&m, &n, a, &lda, ipiv, info); } template <> void Getri<double>(int n, double* a, int lda, int* ipiv, double* work, int lwork, int* info) { dgetri_(&n, a, &lda, ipiv, work, &lwork, info); } template <> void Getri<float>(int n, float* a, int lda, int* ipiv, float* work, int lwork, int* info) { sgetri_(&n, a, &lda, ipiv, work, &lwork, info); } template <> void Gesdd<double>( char jobz, int m, int n, double* a, int lda, double* s, double* u, int ldu, double* vt, int ldvt, double* work, int lwork, int* iwork, int* info) { dgesdd_(&jobz, &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, work, &lwork, iwork, info); } template <> void Gesdd<float>( char jobz, int m, int n, float* a, int lda, float* s, float* u, int ldu, float* vt, int ldvt, float* work, int lwork, int* iwork, int* info) { sgesdd_(&jobz, &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, work, &lwork, iwork, info); } #endif // CHAINERX_ENABLE_LAPACK template <typename T> void SolveImpl(const Array& a, const Array& b, const Array& out) { Device& device = a.device(); Dtype dtype = a.dtype(); Array lu_matrix = Empty(a.shape(), dtype, device); device.backend().CallKernel<CopyKernel>(a.Transpose(), lu_matrix); auto lu_ptr = static_cast<T*>(internal::GetRawOffsetData(lu_matrix)); int64_t n = a.shape()[0]; int64_t nrhs = 1; if (b.ndim() == 2) { nrhs = b.shape()[1]; } Array ipiv = Empty(Shape{n}, Dtype::kInt32, device); auto ipiv_ptr = static_cast<int*>(internal::GetRawOffsetData(ipiv)); Array out_transposed = b.Transpose().Copy(); auto out_ptr = static_cast<T*>(internal::GetRawOffsetData(out_transposed)); int info; Gesv(n, nrhs, lu_ptr, n, ipiv_ptr, out_ptr, n, &info); if (info != 0) { throw ChainerxError{"Unsuccessful gesv (Solve) execution. Info = ", info}; } device.backend().CallKernel<CopyKernel>(out_transposed.Transpose(), out); } template <typename T> void InverseImpl(const Array& a, const Array& out) { Device& device = a.device(); Dtype dtype = a.dtype(); device.backend().CallKernel<CopyKernel>(a, out); auto out_ptr = static_cast<T*>(internal::GetRawOffsetData(out)); int64_t n = a.shape()[0]; Array ipiv = Empty(Shape{n}, Dtype::kInt32, device); auto ipiv_ptr = static_cast<int*>(internal::GetRawOffsetData(ipiv)); int info; Getrf(n, n, out_ptr, n, ipiv_ptr, &info); if (info != 0) { throw ChainerxError{"Unsuccessful getrf (LU) execution. Info = ", info}; } int buffersize = -1; T work_size; Getri(n, out_ptr, n, ipiv_ptr, &work_size, buffersize, &info); buffersize = static_cast<int>(work_size); Array work = Empty(Shape{buffersize}, dtype, device); auto work_ptr = static_cast<T*>(internal::GetRawOffsetData(work)); Getri(n, out_ptr, n, ipiv_ptr, work_ptr, buffersize, &info); if (info != 0) { throw ChainerxError{"Unsuccessful getri (Inverse LU) execution. Info = ", info}; } } } // namespace class NativeSolveKernel : public SolveKernel { public: void Call(const Array& a, const Array& b, const Array& out) override { #if CHAINERX_ENABLE_LAPACK CHAINERX_ASSERT(a.ndim() == 2); CHAINERX_ASSERT(a.shape()[0] == a.shape()[1]); VisitFloatingPointDtype(a.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; SolveImpl<T>(a, b, out); }); #else // CHAINERX_ENABLE_LAPACK (void)a; // unused (void)b; // unused (void)out; // unused throw ChainerxError{"LAPACK is not linked to ChainerX."}; #endif // CHAINERX_ENABLE_LAPACK } }; CHAINERX_NATIVE_REGISTER_KERNEL(SolveKernel, NativeSolveKernel); class NativeInverseKernel : public InverseKernel { public: void Call(const Array& a, const Array& out) override { #if CHAINERX_ENABLE_LAPACK CHAINERX_ASSERT(a.ndim() == 2); CHAINERX_ASSERT(a.shape()[0] == a.shape()[1]); VisitFloatingPointDtype(a.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; InverseImpl<T>(a, out); }); #else // CHAINERX_ENABLE_LAPACK (void)a; // unused (void)out; // unused throw ChainerxError{"LAPACK is not linked to ChainerX."}; #endif // CHAINERX_ENABLE_LAPACK } }; CHAINERX_NATIVE_REGISTER_KERNEL(InverseKernel, NativeInverseKernel); class NativeSVDKernel : public SVDKernel { public: std::tuple<Array, Array, Array> Call(const Array& a, bool full_matrices, bool compute_uv) override { #if CHAINERX_ENABLE_LAPACK Device& device = a.device(); Dtype dtype = a.dtype(); CHAINERX_ASSERT(a.ndim() == 2); int n = a.shape()[0]; int m = a.shape()[1]; Array x{}; bool trans_flag; if (m >= n) { x = Empty(Shape{n, m}, dtype, device); device.backend().CallKernel<CopyKernel>(a, x); trans_flag = false; } else { m = a.shape()[0]; n = a.shape()[1]; x = Empty(Shape{n, m}, dtype, device); device.backend().CallKernel<CopyKernel>(a.Transpose(), x); trans_flag = true; } int mn = std::min(m, n); Array u{}; Array vt{}; if (compute_uv) { if (full_matrices) { u = Empty(Shape{m, m}, dtype, device); vt = Empty(Shape{n, n}, dtype, device); } else { u = Empty(Shape{mn, m}, dtype, device); vt = Empty(Shape{mn, n}, dtype, device); } } else { u = Empty(Shape{0}, dtype, device); vt = Empty(Shape{0}, dtype, device); } Array s = Empty(Shape{mn}, dtype, device); auto svd_impl = [&](auto pt) -> std::tuple<Array, Array, Array> { using T = typename decltype(pt)::type; T* x_ptr = static_cast<T*>(internal::GetRawOffsetData(x)); T* s_ptr = static_cast<T*>(internal::GetRawOffsetData(s)); T* u_ptr = static_cast<T*>(internal::GetRawOffsetData(u)); T* vt_ptr = static_cast<T*>(internal::GetRawOffsetData(vt)); char job; if (compute_uv) { job = full_matrices ? 'A' : 'S'; } else { job = 'N'; } Array iwork = Empty(Shape{8 * mn}, Dtype::kInt64, device); auto iwork_ptr = static_cast<int*>(internal::GetRawOffsetData(iwork)); int info; int buffersize = -1; T work_size; Gesdd(job, m, n, x_ptr, m, s_ptr, u_ptr, m, vt_ptr, n, &work_size, buffersize, iwork_ptr, &info); buffersize = static_cast<int>(work_size); Array work = Empty(Shape{buffersize}, dtype, device); T* work_ptr = static_cast<T*>(internal::GetRawOffsetData(work)); Gesdd(job, m, n, x_ptr, m, s_ptr, u_ptr, m, vt_ptr, n, work_ptr, buffersize, iwork_ptr, &info); if (info != 0) { throw ChainerxError{"Unsuccessful gesdd (SVD) execution. Info = ", info}; } if (trans_flag) { return std::make_tuple(std::move(u.Transpose()), std::move(s), std::move(vt.Transpose())); } else { return std::make_tuple(std::move(vt), std::move(s), std::move(u)); } }; return VisitFloatingPointDtype(dtype, svd_impl); #else // CHAINERX_LAPACK_AVAILABLE (void)a; // unused (void)full_matrices; // unused (void)compute_uv; // unused throw ChainerxError{"LAPACK is not linked to ChainerX."}; #endif // CHAINERX_LAPACK_AVAILABLE } }; CHAINERX_NATIVE_REGISTER_KERNEL(SVDKernel, NativeSVDKernel); class NativePseudoInverseKernel : public PseudoInverseKernel { public: void Call(const Array& a, const Array& out, float rcond = 1e-15) override { Device& device = a.device(); device.CheckDevicesCompatible(a, out); CHAINERX_ASSERT(a.ndim() == 2); Array u{}; Array s{}; Array vt{}; std::tie(u, s, vt) = device.backend().CallKernel<SVDKernel>(a, false, true); Array cutoff = rcond * s.Max(); Array cutoff_indices = s <= cutoff; Array sinv = 1.0 / s; sinv = Where(cutoff_indices, 0, sinv); std::vector<ArrayIndex> indices{Slice{}, NewAxis{}}; device.backend().CallKernel<DotKernel>(vt.Transpose(), sinv.At(indices) * u.Transpose(), out); } }; CHAINERX_NATIVE_REGISTER_KERNEL(PseudoInverseKernel, NativePseudoInverseKernel); } // namespace native } // namespace chainerx <commit_msg>Change type of shape dims to int64_t<commit_after>#include "chainerx/native/native_device.h" #include <cmath> #include <cstdint> #include <type_traits> #include "chainerx/array.h" #include "chainerx/backend.h" #include "chainerx/device.h" #include "chainerx/dtype.h" #include "chainerx/indexable_array.h" #include "chainerx/kernels/creation.h" #include "chainerx/kernels/linalg.h" #include "chainerx/macro.h" #include "chainerx/native/data_type.h" #include "chainerx/native/elementwise.h" #include "chainerx/native/kernel_regist.h" #include "chainerx/routines/creation.h" #include "chainerx/routines/indexing.h" #include "chainerx/shape.h" #if CHAINERX_ENABLE_LAPACK extern "C" { // gesv void dgesv_(int* n, int* nrhs, double* a, int* lda, int* ipiv, double* b, int* ldb, int* info); void sgesv_(int* n, int* nrhs, float* a, int* lda, int* ipiv, float* b, int* ldb, int* info); // getrf void dgetrf_(int* m, int* n, double* a, int* lda, int* ipiv, int* info); void sgetrf_(int* m, int* n, float* a, int* lda, int* ipiv, int* info); // getri void dgetri_(int* n, double* a, int* lda, int* ipiv, double* work, int* lwork, int* info); void sgetri_(int* n, float* a, int* lda, int* ipiv, float* work, int* lwork, int* info); // gesdd void dgesdd_( char* jobz, int* m, int* n, double* a, int* lda, double* s, double* u, int* ldu, double* vt, int* ldvt, double* work, int* lwork, int* iwork, int* info); void sgesdd_( char* jobz, int* m, int* n, float* a, int* lda, float* s, float* u, int* ldu, float* vt, int* ldvt, float* work, int* lwork, int* iwork, int* info); } #endif // CHAINERX_ENABLE_LAPACK namespace chainerx { namespace native { namespace { template <typename T> void Gesv(int /*n*/, int /*nrhs*/, T* /*a*/, int /*lda*/, int* /*ipiv*/, T* /*b*/, int /*ldb*/, int* /*info*/) { throw DtypeError{"Only Arrays of float or double type are supported by gesv (Solve)"}; } template <typename T> void Getrf(int /*m*/, int /*n*/, T* /*a*/, int /*lda*/, int* /*ipiv*/, int* /*info*/) { throw DtypeError{"Only Arrays of float or double type are supported by getri (LU)"}; } template <typename T> void Getri(int /*n*/, T* /*a*/, int /*lda*/, int* /*ipiv*/, T* /*work*/, int /*lwork*/, int* /*info*/) { throw DtypeError{"Only Arrays of float or double type are supported by getri (Inverse LU)"}; } template <typename T> void Gesdd( char /*jobz*/, int /*m*/, int /*n*/, T* /*a*/, int /*lda*/, T* /*s*/, T* /*u*/, int /*ldu*/, T* /*vt*/, int /*ldvt*/, T* /*work*/, int /*lwork*/, int* /*iwork*/, int* /*info*/) { throw DtypeError{"Only Arrays of float or double type are supported by gesdd (SVD)"}; } #if CHAINERX_ENABLE_LAPACK template <> void Gesv<double>(int n, int nrhs, double* a, int lda, int* ipiv, double* b, int ldb, int* info) { dgesv_(&n, &nrhs, a, &lda, ipiv, b, &ldb, info); } template <> void Gesv<float>(int n, int nrhs, float* a, int lda, int* ipiv, float* b, int ldb, int* info) { sgesv_(&n, &nrhs, a, &lda, ipiv, b, &ldb, info); } template <> void Getrf<double>(int m, int n, double* a, int lda, int* ipiv, int* info) { dgetrf_(&m, &n, a, &lda, ipiv, info); } template <> void Getrf<float>(int m, int n, float* a, int lda, int* ipiv, int* info) { sgetrf_(&m, &n, a, &lda, ipiv, info); } template <> void Getri<double>(int n, double* a, int lda, int* ipiv, double* work, int lwork, int* info) { dgetri_(&n, a, &lda, ipiv, work, &lwork, info); } template <> void Getri<float>(int n, float* a, int lda, int* ipiv, float* work, int lwork, int* info) { sgetri_(&n, a, &lda, ipiv, work, &lwork, info); } template <> void Gesdd<double>( char jobz, int m, int n, double* a, int lda, double* s, double* u, int ldu, double* vt, int ldvt, double* work, int lwork, int* iwork, int* info) { dgesdd_(&jobz, &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, work, &lwork, iwork, info); } template <> void Gesdd<float>( char jobz, int m, int n, float* a, int lda, float* s, float* u, int ldu, float* vt, int ldvt, float* work, int lwork, int* iwork, int* info) { sgesdd_(&jobz, &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, work, &lwork, iwork, info); } #endif // CHAINERX_ENABLE_LAPACK template <typename T> void SolveImpl(const Array& a, const Array& b, const Array& out) { Device& device = a.device(); Dtype dtype = a.dtype(); Array lu_matrix = Empty(a.shape(), dtype, device); device.backend().CallKernel<CopyKernel>(a.Transpose(), lu_matrix); auto lu_ptr = static_cast<T*>(internal::GetRawOffsetData(lu_matrix)); int64_t n = a.shape()[0]; int64_t nrhs = 1; if (b.ndim() == 2) { nrhs = b.shape()[1]; } Array ipiv = Empty(Shape{n}, Dtype::kInt32, device); auto ipiv_ptr = static_cast<int*>(internal::GetRawOffsetData(ipiv)); Array out_transposed = b.Transpose().Copy(); auto out_ptr = static_cast<T*>(internal::GetRawOffsetData(out_transposed)); int info; Gesv(n, nrhs, lu_ptr, n, ipiv_ptr, out_ptr, n, &info); if (info != 0) { throw ChainerxError{"Unsuccessful gesv (Solve) execution. Info = ", info}; } device.backend().CallKernel<CopyKernel>(out_transposed.Transpose(), out); } template <typename T> void InverseImpl(const Array& a, const Array& out) { Device& device = a.device(); Dtype dtype = a.dtype(); device.backend().CallKernel<CopyKernel>(a, out); auto out_ptr = static_cast<T*>(internal::GetRawOffsetData(out)); int64_t n = a.shape()[0]; Array ipiv = Empty(Shape{n}, Dtype::kInt32, device); auto ipiv_ptr = static_cast<int*>(internal::GetRawOffsetData(ipiv)); int info; Getrf(n, n, out_ptr, n, ipiv_ptr, &info); if (info != 0) { throw ChainerxError{"Unsuccessful getrf (LU) execution. Info = ", info}; } int buffersize = -1; T work_size; Getri(n, out_ptr, n, ipiv_ptr, &work_size, buffersize, &info); buffersize = static_cast<int>(work_size); Array work = Empty(Shape{buffersize}, dtype, device); auto work_ptr = static_cast<T*>(internal::GetRawOffsetData(work)); Getri(n, out_ptr, n, ipiv_ptr, work_ptr, buffersize, &info); if (info != 0) { throw ChainerxError{"Unsuccessful getri (Inverse LU) execution. Info = ", info}; } } } // namespace class NativeSolveKernel : public SolveKernel { public: void Call(const Array& a, const Array& b, const Array& out) override { #if CHAINERX_ENABLE_LAPACK CHAINERX_ASSERT(a.ndim() == 2); CHAINERX_ASSERT(a.shape()[0] == a.shape()[1]); VisitFloatingPointDtype(a.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; SolveImpl<T>(a, b, out); }); #else // CHAINERX_ENABLE_LAPACK (void)a; // unused (void)b; // unused (void)out; // unused throw ChainerxError{"LAPACK is not linked to ChainerX."}; #endif // CHAINERX_ENABLE_LAPACK } }; CHAINERX_NATIVE_REGISTER_KERNEL(SolveKernel, NativeSolveKernel); class NativeInverseKernel : public InverseKernel { public: void Call(const Array& a, const Array& out) override { #if CHAINERX_ENABLE_LAPACK CHAINERX_ASSERT(a.ndim() == 2); CHAINERX_ASSERT(a.shape()[0] == a.shape()[1]); VisitFloatingPointDtype(a.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; InverseImpl<T>(a, out); }); #else // CHAINERX_ENABLE_LAPACK (void)a; // unused (void)out; // unused throw ChainerxError{"LAPACK is not linked to ChainerX."}; #endif // CHAINERX_ENABLE_LAPACK } }; CHAINERX_NATIVE_REGISTER_KERNEL(InverseKernel, NativeInverseKernel); class NativeSVDKernel : public SVDKernel { public: std::tuple<Array, Array, Array> Call(const Array& a, bool full_matrices, bool compute_uv) override { #if CHAINERX_ENABLE_LAPACK Device& device = a.device(); Dtype dtype = a.dtype(); CHAINERX_ASSERT(a.ndim() == 2); int64_t n = a.shape()[0]; int64_t m = a.shape()[1]; Array x{}; bool trans_flag; if (m >= n) { x = Empty(Shape{n, m}, dtype, device); device.backend().CallKernel<CopyKernel>(a, x); trans_flag = false; } else { m = a.shape()[0]; n = a.shape()[1]; x = Empty(Shape{n, m}, dtype, device); device.backend().CallKernel<CopyKernel>(a.Transpose(), x); trans_flag = true; } int64_t mn = std::min(m, n); Array u{}; Array vt{}; if (compute_uv) { if (full_matrices) { u = Empty(Shape{m, m}, dtype, device); vt = Empty(Shape{n, n}, dtype, device); } else { u = Empty(Shape{mn, m}, dtype, device); vt = Empty(Shape{mn, n}, dtype, device); } } else { u = Empty(Shape{0}, dtype, device); vt = Empty(Shape{0}, dtype, device); } Array s = Empty(Shape{mn}, dtype, device); auto svd_impl = [&](auto pt) -> std::tuple<Array, Array, Array> { using T = typename decltype(pt)::type; T* x_ptr = static_cast<T*>(internal::GetRawOffsetData(x)); T* s_ptr = static_cast<T*>(internal::GetRawOffsetData(s)); T* u_ptr = static_cast<T*>(internal::GetRawOffsetData(u)); T* vt_ptr = static_cast<T*>(internal::GetRawOffsetData(vt)); char job; if (compute_uv) { job = full_matrices ? 'A' : 'S'; } else { job = 'N'; } Array iwork = Empty(Shape{8 * mn}, Dtype::kInt64, device); auto iwork_ptr = static_cast<int*>(internal::GetRawOffsetData(iwork)); int info; int buffersize = -1; T work_size; Gesdd(job, m, n, x_ptr, m, s_ptr, u_ptr, m, vt_ptr, n, &work_size, buffersize, iwork_ptr, &info); buffersize = static_cast<int>(work_size); Array work = Empty(Shape{buffersize}, dtype, device); T* work_ptr = static_cast<T*>(internal::GetRawOffsetData(work)); Gesdd(job, m, n, x_ptr, m, s_ptr, u_ptr, m, vt_ptr, n, work_ptr, buffersize, iwork_ptr, &info); if (info != 0) { throw ChainerxError{"Unsuccessful gesdd (SVD) execution. Info = ", info}; } if (trans_flag) { return std::make_tuple(std::move(u.Transpose()), std::move(s), std::move(vt.Transpose())); } else { return std::make_tuple(std::move(vt), std::move(s), std::move(u)); } }; return VisitFloatingPointDtype(dtype, svd_impl); #else // CHAINERX_LAPACK_AVAILABLE (void)a; // unused (void)full_matrices; // unused (void)compute_uv; // unused throw ChainerxError{"LAPACK is not linked to ChainerX."}; #endif // CHAINERX_LAPACK_AVAILABLE } }; CHAINERX_NATIVE_REGISTER_KERNEL(SVDKernel, NativeSVDKernel); class NativePseudoInverseKernel : public PseudoInverseKernel { public: void Call(const Array& a, const Array& out, float rcond = 1e-15) override { Device& device = a.device(); device.CheckDevicesCompatible(a, out); CHAINERX_ASSERT(a.ndim() == 2); Array u{}; Array s{}; Array vt{}; std::tie(u, s, vt) = device.backend().CallKernel<SVDKernel>(a, false, true); Array cutoff = rcond * s.Max(); Array cutoff_indices = s <= cutoff; Array sinv = 1.0 / s; sinv = Where(cutoff_indices, 0, sinv); std::vector<ArrayIndex> indices{Slice{}, NewAxis{}}; device.backend().CallKernel<DotKernel>(vt.Transpose(), sinv.At(indices) * u.Transpose(), out); } }; CHAINERX_NATIVE_REGISTER_KERNEL(PseudoInverseKernel, NativePseudoInverseKernel); } // namespace native } // namespace chainerx <|endoftext|>
<commit_before>#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QI_STRAND_HPP_ #define _QI_STRAND_HPP_ #include <deque> #include <atomic> #include <qi/assert.hpp> #include <qi/detail/executioncontext.hpp> #include <qi/detail/futureunwrap.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/shared_ptr.hpp> #include <boost/function.hpp> #include <boost/noncopyable.hpp> #include <boost/type_traits/function_traits.hpp> # ifdef _MSC_VER # pragma warning( push ) # pragma warning( disable: 4996 ) // TODO: Reactivate this warning once msvc stop triggerring a warning on overloading a deprecated function # endif namespace qi { // C++14 these can be lambdas, but we need perfect forwarding in the capture in scheduleFor below namespace detail { template <typename F> struct Stranded; template <typename F> struct StrandedUnwrapped; } // we use ExecutionContext's helpers in schedulerFor, we don't need to implement all the methods class StrandPrivate : public ExecutionContext, public boost::enable_shared_from_this<StrandPrivate> { public: enum class State; struct Callback; using Queue = std::deque<boost::shared_ptr<Callback>>; qi::ExecutionContext& _eventLoop; std::atomic<unsigned int> _curId; std::atomic<unsigned int> _aliveCount; bool _processing; // protected by mutex, no need for atomic std::atomic<int> _processingThread; boost::recursive_mutex _mutex; boost::condition_variable_any _processFinished; bool _dying; Queue _queue; StrandPrivate(qi::ExecutionContext& eventLoop); Future<void> asyncAtImpl(boost::function<void()> cb, qi::SteadyClockTimePoint tp) override; Future<void> asyncDelayImpl(boost::function<void()> cb, qi::Duration delay) override; boost::shared_ptr<Callback> createCallback(boost::function<void()> cb); void enqueue(boost::shared_ptr<Callback> cbStruct); void process(); void cancel(boost::shared_ptr<Callback> cbStruct); bool isInThisContext() const override; void postImpl(boost::function<void()> callback) override { QI_ASSERT(false); throw 0; } qi::Future<void> async(const boost::function<void()>& callback, qi::SteadyClockTimePoint tp) override { QI_ASSERT(false); throw 0; } qi::Future<void> async(const boost::function<void()>& callback, qi::Duration delay) override { QI_ASSERT(false); throw 0; } using ExecutionContext::async; private: void stopProcess(boost::recursive_mutex::scoped_lock& lock, bool finished); }; inline StrandPrivate::StrandPrivate(qi::ExecutionContext& eventLoop) : _eventLoop(eventLoop) , _curId(0) , _aliveCount(0) , _processing(false) , _processingThread(0) , _dying(false) { } /** Class that schedules tasks sequentially * * A strand allows one to schedule work on an eventloop with the guaranty * that two callback will never be called concurrently. * * Methods are thread-safe except for destructor which must never be called * concurrently. * * \includename{qi/strand.hpp} */ class QI_API Strand : public ExecutionContext, private boost::noncopyable { public: /// Construct a strand that will schedule work on the default event loop Strand(); /// Construct a strand that will schedule work on executionContext Strand(qi::ExecutionContext& executionContext); /// Call detroy() ~Strand(); /** Joins the strand * * This will wait for currently running tasks to finish and will drop all tasks scheduled from the moment of the call * on. A strand can't be reused after it has been join()ed. * * It is safe to call this method concurrently with other methods. All the returned futures will be set to error. */ void join(); // DEPRECATED QI_API_DEPRECATED_MSG(Use 'asyncAt' instead) qi::Future<void> async(const boost::function<void()>& cb, qi::SteadyClockTimePoint tp) override; QI_API_DEPRECATED_MSG(Use 'asyncDelay' instead) qi::Future<void> async(const boost::function<void()>& cb, qi::Duration delay) override; using ExecutionContext::async; #define genCall(n, ATYPEDECL, ATYPES, ADECL, AUSE, comma) \ template <typename T, typename F, typename ARG0 comma ATYPEDECL> \ QI_API_DEPRECATED_MSG(Use generic 'schedulerFor' overload instead) boost::function<T> schedulerFor( \ const F& func, const ARG0& arg0 comma ADECL, \ const boost::function<void()>& fallbackCb = boost::function<void()>()) \ { \ boost::function<T> funcbind = qi::bind<T>(func, arg0 comma AUSE); \ return qi::trackWithFallback( \ fallbackCb, \ SchedulerHelper<boost::function_traits<T>::arity, T>::_scheduler( \ funcbind, this), \ arg0); \ } QI_GEN(genCall) #undef genCall // END DEPRECATED /** * \return true if current code is running in this strand, false otherwise. If the strand is dying (destroy() has been * called, returns false) */ bool isInThisContext() const override; template <typename F> auto schedulerFor(F&& func, boost::function<void()> onFail = {}) -> detail::Stranded<typename std::decay<F>::type> { return detail::Stranded<typename std::decay<F>::type>(std::forward<F>(func), _p, std::move(onFail)); } template <typename F> auto unwrappedSchedulerFor(F&& func, boost::function<void()> onFail = {}) -> detail::StrandedUnwrapped<typename std::decay<F>::type> { return detail::StrandedUnwrapped<typename std::decay<F>::type>(std::forward<F>(func), _p, std::move(onFail)); } private: boost::shared_ptr<StrandPrivate> _p; void postImpl(boost::function<void()> callback) override; qi::Future<void> asyncAtImpl(boost::function<void()> cb, qi::SteadyClockTimePoint tp) override; qi::Future<void> asyncDelayImpl(boost::function<void()> cb, qi::Duration delay) override; // DEPRECATED template <int N, typename T> struct SchedulerHelper; #define typedefi(z, n, _) \ typedef typename boost::function_traits<T>::BOOST_PP_CAT( \ BOOST_PP_CAT(arg, BOOST_PP_INC(n)), _type) BOOST_PP_CAT(P, n); #define placeholders(z, n, __) , BOOST_PP_CAT(_, BOOST_PP_INC(n)) #define genCall(n, ATYPEDECL, ATYPES, ADECL, AUSE, comma) \ template <typename T> \ struct SchedulerHelper<n, T> \ { \ BOOST_PP_REPEAT(n, typedefi, _); \ typedef typename boost::function_traits<T>::result_type R; \ static boost::function<T> _scheduler(const boost::function<T>& f, \ Strand* strand) \ { \ return qi::bind<T>(&_asyncCall, strand, \ f BOOST_PP_REPEAT(n, placeholders, _)); \ } \ static qi::Future<R> _asyncCall(Strand* strand, \ const boost::function<T>& func comma \ ADECL) \ { \ /* use qi::bind again since first arg may be a Trackable */ \ return ((qi::ExecutionContext*)strand) \ ->async(qi::bind<R()>(func comma AUSE)); \ } \ }; QI_GEN(genCall) #undef genCall #undef placeholders #undef typedefi // END DEPRECATED }; namespace detail { template <typename F, typename... Args> static auto callInStrand( F& func, const boost::function<void()>& onFail, boost::weak_ptr<StrandPrivate> weakStrand, Args&&... args) -> decltype(weakStrand.lock()->async(std::bind(func, std::forward<Args>(args)...))) // TODO: remove in C++14 { if (auto strand = weakStrand.lock()) { return strand->async(std::bind(func, std::forward<Args>(args)...)); } else { if (onFail) onFail(); return qi::makeFutureError< typename std::decay<decltype(func(std::forward<Args>(args)...))>::type>("strand is dead"); } } // C++14 these can be lambdas, but we need perfect forwarding in the capture in scheduleFor // A callable object that, when called defers the call of the given function to the strand. template <typename F> struct Stranded { static const bool is_async = true; F _func; boost::weak_ptr<StrandPrivate> _strand; boost::function<void()> _onFail; Stranded(F f, boost::weak_ptr<StrandPrivate> strand, boost::function<void()> onFail) : _func(std::move(f)) , _strand(std::move(strand)) , _onFail(std::move(onFail)) { } template <typename... Args> auto operator()(Args&&... args) const -> decltype(callInStrand(_func, _onFail, _strand, std::forward<Args>(args)...)) { return callInStrand(_func, _onFail, _strand, std::forward<Args>(args)...); } template <typename... Args> auto operator()(Args&&... args) -> decltype(callInStrand(_func, _onFail, _strand, std::forward<Args>(args)...)) { return callInStrand(_func, _onFail, _strand, std::forward<Args>(args)...); } }; // Like Stranded, but unwraps the result. template <typename F> struct StrandedUnwrapped { QI_API_DEPRECATED_MSG("is_async used") static const bool is_async = true; private: Stranded<F> _stranded; public: StrandedUnwrapped(F&& f, const boost::weak_ptr<StrandPrivate>& strand, const boost::function<void()>& onFail) : _stranded(std::forward<F>(f), strand, onFail) {} template <typename... Args> auto operator()(Args&&... args) const -> decltype(tryUnwrap(_stranded(std::forward<Args>(args)...))) { return tryUnwrap(_stranded(std::forward<Args>(args)...)); } template <typename... Args> auto operator()(Args&&... args) -> decltype(tryUnwrap(_stranded(std::forward<Args>(args)...))) { return tryUnwrap(_stranded(std::forward<Args>(args)...)); } }; } // detail } // qi # ifdef _MSC_VER # pragma warning( pop ) # endif # include <qi/async.hpp> #endif // _QI_STRAND_HPP_ <commit_msg>add a feature flag for the stranded() API change transition #40589<commit_after>#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QI_STRAND_HPP_ #define _QI_STRAND_HPP_ #include <deque> #include <atomic> #include <qi/assert.hpp> #include <qi/detail/executioncontext.hpp> #include <qi/detail/futureunwrap.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/shared_ptr.hpp> #include <boost/function.hpp> #include <boost/noncopyable.hpp> #include <boost/type_traits/function_traits.hpp> # ifdef _MSC_VER # pragma warning( push ) # pragma warning( disable: 4996 ) // TODO: Reactivate this warning once msvc stop triggerring a warning on overloading a deprecated function # endif #define QI_DETAIL_FEATURE_STRANDED_UNWRAPPED namespace qi { // C++14 these can be lambdas, but we need perfect forwarding in the capture in scheduleFor below namespace detail { template <typename F> struct Stranded; template <typename F> struct StrandedUnwrapped; } // we use ExecutionContext's helpers in schedulerFor, we don't need to implement all the methods class StrandPrivate : public ExecutionContext, public boost::enable_shared_from_this<StrandPrivate> { public: enum class State; struct Callback; using Queue = std::deque<boost::shared_ptr<Callback>>; qi::ExecutionContext& _eventLoop; std::atomic<unsigned int> _curId; std::atomic<unsigned int> _aliveCount; bool _processing; // protected by mutex, no need for atomic std::atomic<int> _processingThread; boost::recursive_mutex _mutex; boost::condition_variable_any _processFinished; bool _dying; Queue _queue; StrandPrivate(qi::ExecutionContext& eventLoop); Future<void> asyncAtImpl(boost::function<void()> cb, qi::SteadyClockTimePoint tp) override; Future<void> asyncDelayImpl(boost::function<void()> cb, qi::Duration delay) override; boost::shared_ptr<Callback> createCallback(boost::function<void()> cb); void enqueue(boost::shared_ptr<Callback> cbStruct); void process(); void cancel(boost::shared_ptr<Callback> cbStruct); bool isInThisContext() const override; void postImpl(boost::function<void()> callback) override { QI_ASSERT(false); throw 0; } qi::Future<void> async(const boost::function<void()>& callback, qi::SteadyClockTimePoint tp) override { QI_ASSERT(false); throw 0; } qi::Future<void> async(const boost::function<void()>& callback, qi::Duration delay) override { QI_ASSERT(false); throw 0; } using ExecutionContext::async; private: void stopProcess(boost::recursive_mutex::scoped_lock& lock, bool finished); }; inline StrandPrivate::StrandPrivate(qi::ExecutionContext& eventLoop) : _eventLoop(eventLoop) , _curId(0) , _aliveCount(0) , _processing(false) , _processingThread(0) , _dying(false) { } /** Class that schedules tasks sequentially * * A strand allows one to schedule work on an eventloop with the guaranty * that two callback will never be called concurrently. * * Methods are thread-safe except for destructor which must never be called * concurrently. * * \includename{qi/strand.hpp} */ class QI_API Strand : public ExecutionContext, private boost::noncopyable { public: /// Construct a strand that will schedule work on the default event loop Strand(); /// Construct a strand that will schedule work on executionContext Strand(qi::ExecutionContext& executionContext); /// Call detroy() ~Strand(); /** Joins the strand * * This will wait for currently running tasks to finish and will drop all tasks scheduled from the moment of the call * on. A strand can't be reused after it has been join()ed. * * It is safe to call this method concurrently with other methods. All the returned futures will be set to error. */ void join(); // DEPRECATED QI_API_DEPRECATED_MSG(Use 'asyncAt' instead) qi::Future<void> async(const boost::function<void()>& cb, qi::SteadyClockTimePoint tp) override; QI_API_DEPRECATED_MSG(Use 'asyncDelay' instead) qi::Future<void> async(const boost::function<void()>& cb, qi::Duration delay) override; using ExecutionContext::async; #define genCall(n, ATYPEDECL, ATYPES, ADECL, AUSE, comma) \ template <typename T, typename F, typename ARG0 comma ATYPEDECL> \ QI_API_DEPRECATED_MSG(Use generic 'schedulerFor' overload instead) boost::function<T> schedulerFor( \ const F& func, const ARG0& arg0 comma ADECL, \ const boost::function<void()>& fallbackCb = boost::function<void()>()) \ { \ boost::function<T> funcbind = qi::bind<T>(func, arg0 comma AUSE); \ return qi::trackWithFallback( \ fallbackCb, \ SchedulerHelper<boost::function_traits<T>::arity, T>::_scheduler( \ funcbind, this), \ arg0); \ } QI_GEN(genCall) #undef genCall // END DEPRECATED /** * \return true if current code is running in this strand, false otherwise. If the strand is dying (destroy() has been * called, returns false) */ bool isInThisContext() const override; template <typename F> auto schedulerFor(F&& func, boost::function<void()> onFail = {}) -> detail::Stranded<typename std::decay<F>::type> { return detail::Stranded<typename std::decay<F>::type>(std::forward<F>(func), _p, std::move(onFail)); } template <typename F> auto unwrappedSchedulerFor(F&& func, boost::function<void()> onFail = {}) -> detail::StrandedUnwrapped<typename std::decay<F>::type> { return detail::StrandedUnwrapped<typename std::decay<F>::type>(std::forward<F>(func), _p, std::move(onFail)); } private: boost::shared_ptr<StrandPrivate> _p; void postImpl(boost::function<void()> callback) override; qi::Future<void> asyncAtImpl(boost::function<void()> cb, qi::SteadyClockTimePoint tp) override; qi::Future<void> asyncDelayImpl(boost::function<void()> cb, qi::Duration delay) override; // DEPRECATED template <int N, typename T> struct SchedulerHelper; #define typedefi(z, n, _) \ typedef typename boost::function_traits<T>::BOOST_PP_CAT( \ BOOST_PP_CAT(arg, BOOST_PP_INC(n)), _type) BOOST_PP_CAT(P, n); #define placeholders(z, n, __) , BOOST_PP_CAT(_, BOOST_PP_INC(n)) #define genCall(n, ATYPEDECL, ATYPES, ADECL, AUSE, comma) \ template <typename T> \ struct SchedulerHelper<n, T> \ { \ BOOST_PP_REPEAT(n, typedefi, _); \ typedef typename boost::function_traits<T>::result_type R; \ static boost::function<T> _scheduler(const boost::function<T>& f, \ Strand* strand) \ { \ return qi::bind<T>(&_asyncCall, strand, \ f BOOST_PP_REPEAT(n, placeholders, _)); \ } \ static qi::Future<R> _asyncCall(Strand* strand, \ const boost::function<T>& func comma \ ADECL) \ { \ /* use qi::bind again since first arg may be a Trackable */ \ return ((qi::ExecutionContext*)strand) \ ->async(qi::bind<R()>(func comma AUSE)); \ } \ }; QI_GEN(genCall) #undef genCall #undef placeholders #undef typedefi // END DEPRECATED }; namespace detail { template <typename F, typename... Args> static auto callInStrand( F& func, const boost::function<void()>& onFail, boost::weak_ptr<StrandPrivate> weakStrand, Args&&... args) -> decltype(weakStrand.lock()->async(std::bind(func, std::forward<Args>(args)...))) // TODO: remove in C++14 { if (auto strand = weakStrand.lock()) { return strand->async(std::bind(func, std::forward<Args>(args)...)); } else { if (onFail) onFail(); return qi::makeFutureError< typename std::decay<decltype(func(std::forward<Args>(args)...))>::type>("strand is dead"); } } // C++14 these can be lambdas, but we need perfect forwarding in the capture in scheduleFor // A callable object that, when called defers the call of the given function to the strand. template <typename F> struct Stranded { static const bool is_async = true; F _func; boost::weak_ptr<StrandPrivate> _strand; boost::function<void()> _onFail; Stranded(F f, boost::weak_ptr<StrandPrivate> strand, boost::function<void()> onFail) : _func(std::move(f)) , _strand(std::move(strand)) , _onFail(std::move(onFail)) { } template <typename... Args> auto operator()(Args&&... args) const -> decltype(callInStrand(_func, _onFail, _strand, std::forward<Args>(args)...)) { return callInStrand(_func, _onFail, _strand, std::forward<Args>(args)...); } template <typename... Args> auto operator()(Args&&... args) -> decltype(callInStrand(_func, _onFail, _strand, std::forward<Args>(args)...)) { return callInStrand(_func, _onFail, _strand, std::forward<Args>(args)...); } }; // Like Stranded, but unwraps the result. template <typename F> struct StrandedUnwrapped { QI_API_DEPRECATED_MSG("is_async used") static const bool is_async = true; private: Stranded<F> _stranded; public: StrandedUnwrapped(F&& f, const boost::weak_ptr<StrandPrivate>& strand, const boost::function<void()>& onFail) : _stranded(std::forward<F>(f), strand, onFail) {} template <typename... Args> auto operator()(Args&&... args) const -> decltype(tryUnwrap(_stranded(std::forward<Args>(args)...))) { return tryUnwrap(_stranded(std::forward<Args>(args)...)); } template <typename... Args> auto operator()(Args&&... args) -> decltype(tryUnwrap(_stranded(std::forward<Args>(args)...))) { return tryUnwrap(_stranded(std::forward<Args>(args)...)); } }; } // detail } // qi # ifdef _MSC_VER # pragma warning( pop ) # endif # include <qi/async.hpp> #endif // _QI_STRAND_HPP_ <|endoftext|>
<commit_before>#include "CbcConfig.h" // CBC_VERSION_MAJOR defined for Cbc > 2.5 #ifndef CBC_VERSION_MAJOR #include "OsiCbcSolverInterface_2_5.cpp" #elif CBC_VERSION_MAJOR == 2 && CBC_VERSION_MINOR <= 8 #include "OsiCbcSolverInterface_2_8.cpp" #elif CBC_VERSION_MAJOR == 2 && CBC_VERSION_MINOR == 9 #include "OsiCbcSolverInterface_2_9.cpp" #else #error "Cyclus cannot yet handle your version of CoinCBC. Please open an issue with your CoinCBC version." #endif // for some reason these symbol doesn't exist in the mac binaries void OsiSolverInterface::addCol(CoinPackedVectorBase const& vec, double collb, double colub, double obj, std::string name) { // just ignore the name addCol(vec, collb, colub, obj); } void OsiSolverInterface::addCol(int numberElements, const int* rows, const double* elements, double collb, double colub, double obj, std::string name) { // just ignore the name addCol(numberElements, rows, elements, collb, colub, obj); } void OsiSolverInterface::addRow(CoinPackedVectorBase const& vec, char rowsen, double rowrhs, double rowrng, std::string name) { // just ignore the name addRow(vec, rowsen, rowrhs, rowrng, name); } void OsiSolverInterface::addRow(CoinPackedVectorBase const& vec, double rowlb, double rowub, std::string name) { // just ignore the name addRow(vec, rowlb, rowub); } #ifdef __APPLE__ #endif<commit_msg>replace apple<commit_after>#include "CbcConfig.h" // CBC_VERSION_MAJOR defined for Cbc > 2.5 #ifndef CBC_VERSION_MAJOR #include "OsiCbcSolverInterface_2_5.cpp" #elif CBC_VERSION_MAJOR == 2 && CBC_VERSION_MINOR <= 8 #include "OsiCbcSolverInterface_2_8.cpp" #elif CBC_VERSION_MAJOR == 2 && CBC_VERSION_MINOR == 9 #include "OsiCbcSolverInterface_2_9.cpp" #else #error "Cyclus cannot yet handle your version of CoinCBC. Please open an issue with your CoinCBC version." #endif #ifdef __APPLE__ // for some reason these symbol doesn't exist in the mac binaries void OsiSolverInterface::addCol(CoinPackedVectorBase const& vec, double collb, double colub, double obj, std::string name) { // just ignore the name addCol(vec, collb, colub, obj); } void OsiSolverInterface::addCol(int numberElements, const int* rows, const double* elements, double collb, double colub, double obj, std::string name) { // just ignore the name addCol(numberElements, rows, elements, collb, colub, obj); } void OsiSolverInterface::addRow(CoinPackedVectorBase const& vec, char rowsen, double rowrhs, double rowrng, std::string name) { // just ignore the name addRow(vec, rowsen, rowrhs, rowrng, name); } void OsiSolverInterface::addRow(CoinPackedVectorBase const& vec, double rowlb, double rowub, std::string name) { // just ignore the name addRow(vec, rowlb, rowub); } #endif<|endoftext|>
<commit_before>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2010 Loic Dachary <loic@dacary.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **/ #define _PCREPOSIX_H // avoid pcreposix.h conflict with regex.h used by gtest #include <gtest/gtest.h> #include "json_renderer.h" #include "json_renderer_private.h" using namespace seeks_plugins; using namespace json_renderer_private; TEST(JsonRendererTest, render_engines) { EXPECT_EQ("\"google\",\"bing\",\"yauba\",\"yahoo\",\"exalead\",\"twitter\"", json_renderer::render_engines(SE_GOOGLE|SE_BING|SE_YAUBA|SE_YAHOO|SE_EXALEAD|SE_TWITTER)); } TEST(JsonRendererTest, render_snippets) { websearch::_wconfig = new websearch_configuration("not a real filename"); std::string json_str; int current_page = 1; std::vector<search_snippet*> snippets; const std::string query_clean; hash_map<const char*, const char*, hash<const char*>, eqstr> parameters; // zero snippet EXPECT_EQ(SP_ERR_OK, json_renderer::render_snippets(query_clean, current_page, snippets, json_str, &parameters)); EXPECT_EQ("\"snippets\":[]", json_str); // 1 snippet, page 1 json_str = ""; snippets.resize(1); search_snippet s1; s1.set_url("URL1"); snippets[0] = &s1; EXPECT_EQ(SP_ERR_OK, json_renderer::render_snippets(query_clean, current_page, snippets, json_str, &parameters)); EXPECT_TRUE(json_str.find(s1._url) != std::string::npos); EXPECT_EQ(std::string::npos, json_str.find("thumb")); // 1 snippet, page 1, thumbs on json_str = ""; parameters.insert(std::pair<const char*,const char*>("thumbs", "on")); EXPECT_EQ(SP_ERR_OK, json_renderer::render_snippets(query_clean, current_page, snippets, json_str, &parameters)); EXPECT_TRUE(json_str.find(s1._url) != std::string::npos); EXPECT_NE(std::string::npos, json_str.find("thumb")); // 3 snippets, page 2, 2 result per page, thumbs on snippets.resize(3); search_snippet s2; s2.set_url("URL2"); snippets[1] = &s2; search_snippet s3; s3.set_url("URL3"); snippets[2] = &s3; parameters.insert(std::pair<const char*,const char*>("rpp", "2")); current_page = 2; json_str = ""; EXPECT_EQ(SP_ERR_OK, json_renderer::render_snippets(query_clean, current_page, snippets, json_str, &parameters)); EXPECT_EQ(std::string::npos, json_str.find(s1._url)); EXPECT_EQ(std::string::npos, json_str.find(s2._url)); EXPECT_NE(std::string::npos, json_str.find(s3._url)); // 3 snippets, page 1, 2 result per page, thumbs on current_page = 1; json_str = ""; EXPECT_EQ(SP_ERR_OK, json_renderer::render_snippets(query_clean, current_page, snippets, json_str, &parameters)); EXPECT_NE(std::string::npos, json_str.find(s1._url)); EXPECT_NE(std::string::npos, json_str.find(s2._url)); EXPECT_EQ(std::string::npos, json_str.find(s3._url)); // 3 snippets, page 1, 2 result per page, second snippet rejected, thumbs on current_page = 1; s1._doc_type = REJECTED; json_str = ""; EXPECT_EQ(SP_ERR_OK, json_renderer::render_snippets(query_clean, current_page, snippets, json_str, &parameters)); EXPECT_EQ(std::string::npos, json_str.find(s1._url)); EXPECT_NE(std::string::npos, json_str.find(s2._url)); EXPECT_NE(std::string::npos, json_str.find(s3._url)); s1._doc_type = WEBPAGE; // 3 snippets, page 1, 2 result per page, similarity on, thumbs on current_page = 1; s1._seeks_ir = 1.0; s2._seeks_ir = 0.0; s3._seeks_ir = 1.0; json_str = ""; EXPECT_EQ(SP_ERR_OK, json_renderer::render_snippets(query_clean, current_page, snippets, json_str, &parameters)); EXPECT_NE(std::string::npos, json_str.find(s1._url)); EXPECT_EQ(std::string::npos, json_str.find(s2._url)); EXPECT_NE(std::string::npos, json_str.find(s3._url)); } TEST(JsonRendererTest, render_clustered_snippets) { websearch::_wconfig = new websearch_configuration("not a real filename"); query_context context; cluster clusters[3]; std::string json_str; std::vector<search_snippet*> snippets; const std::string query_clean; hash_map<const char*, const char*, hash<const char*>, eqstr> parameters; search_snippet s1; s1.set_url("URL1"); context.add_to_unordered_cache(&s1); clusters[0].add_point(s1._id, NULL); clusters[0]._label = "CLUSTER1"; search_snippet s2; s2.set_url("URL2"); context.add_to_unordered_cache(&s2); clusters[1].add_point(s2._id, NULL); search_snippet s3; s3.set_url("URL3"); context.add_to_unordered_cache(&s3); clusters[1].add_point(s3._id, NULL); clusters[1]._label = "CLUSTER2"; clusters[2]._label = "CLUSTER3"; parameters.insert(std::pair<const char*,const char*>("rpp", "1")); EXPECT_EQ(SP_ERR_OK, json_renderer::render_clustered_snippets(query_clean, clusters, 3, &context, json_str, &parameters)); EXPECT_NE(std::string::npos, json_str.find(clusters[0]._label)); EXPECT_NE(std::string::npos, json_str.find(s1._url)); EXPECT_NE(std::string::npos, json_str.find(clusters[1]._label)); EXPECT_NE(std::string::npos, json_str.find(s2._url)); EXPECT_NE(std::string::npos, json_str.find(s3._url)); EXPECT_EQ(std::string::npos, json_str.find(clusters[2]._label)); } TEST(JsonRendererTest, render_json_results) { websearch::_wconfig = new websearch_configuration("not a real filename"); http_response* rsp; query_context context; double qtime = 1234; std::vector<search_snippet*> snippets; hash_map<const char*, const char*, hash<const char*>, eqstr> parameters; snippets.resize(2); search_snippet s1; s1.set_url("URL1"); snippets[0] = &s1; search_snippet s2; s2.set_url("URL2"); snippets[1] = &s2; parameters.insert(std::pair<const char*,const char*>("rpp", "1")); parameters.insert(std::pair<const char*,const char*>("q", "<QUERY>")); parameters.insert(std::pair<const char*,const char*>("callback", "JSONP")); // select page 1 rsp = new http_response(); EXPECT_EQ(SP_ERR_OK, json_renderer::render_json_results(snippets, NULL, rsp, &parameters, &context, qtime)); EXPECT_NE(std::string::npos, std::string(rsp->_body).find("JSONP({")); EXPECT_NE(std::string::npos, std::string(rsp->_body).find("\"qtime\":1234")); EXPECT_NE(std::string::npos, std::string(rsp->_body).find("\"&lt;QUERY&gt;\"")); EXPECT_NE(std::string::npos, std::string(rsp->_body).find(s1._url)); EXPECT_EQ(std::string::npos, std::string(rsp->_body).find(s2._url)); delete rsp; // select page 2 parameters.insert(std::pair<const char*,const char*>("page", "2")); rsp = new http_response(); EXPECT_EQ(SP_ERR_OK, json_renderer::render_json_results(snippets, NULL, rsp, &parameters, &context, qtime)); EXPECT_EQ(std::string::npos, std::string(rsp->_body).find(s1._url)); EXPECT_NE(std::string::npos, std::string(rsp->_body).find(s2._url)); delete rsp; } TEST(JsonRendererTest, render_clustered_json_results) { websearch::_wconfig = new websearch_configuration("not a real filename"); cluster clusters[1]; http_response* rsp; query_context context; double qtime = 1234; std::vector<search_snippet*> snippets; const std::string query_clean; hash_map<const char*, const char*, hash<const char*>, eqstr> parameters; search_snippet s1; s1.set_url("URL1"); context.add_to_unordered_cache(&s1); clusters[0].add_point(s1._id, NULL); clusters[0]._label = "CLUSTER1"; parameters.insert(std::pair<const char*,const char*>("q", "<QUERY>")); parameters.insert(std::pair<const char*,const char*>("callback", "JSONP")); rsp = new http_response(); EXPECT_EQ(SP_ERR_OK, json_renderer::render_clustered_json_results(clusters, 1, NULL, rsp, &parameters, &context, qtime)); EXPECT_NE(std::string::npos, std::string(rsp->_body).find("JSONP({")); EXPECT_NE(std::string::npos, std::string(rsp->_body).find("\"qtime\":1234")); EXPECT_NE(std::string::npos, std::string(rsp->_body).find("\"&lt;QUERY&gt;\"")); EXPECT_NE(std::string::npos, std::string(rsp->_body).find(s1._url)); EXPECT_NE(std::string::npos, std::string(rsp->_body).find(clusters[0]._label)); std::cout << rsp->_body << std::endl; delete rsp; } TEST(JsonRendererTest, response) { http_response rsp; response(&rsp, "JSON"); EXPECT_EQ(rsp._content_length, strlen(rsp._body)); EXPECT_STREQ("JSON", rsp._body); } TEST(JsonRendererTest, query_clean) { std::string q(":CMD<QUERY>"); EXPECT_EQ("&lt;QUERY&gt;", query_clean(q)); } TEST(JsonRendererTest, jsonp) { std::string input("WHAT"); const char* callback = "CALLBACK"; EXPECT_EQ("CALLBACK(WHAT)", jsonp(input, callback)); EXPECT_EQ("WHAT", jsonp(input, NULL)); } TEST(JsonRendererTest, collect_json_results) { websearch::_wconfig = new websearch_configuration("not a real filename"); std::string result; std::list<std::string> results; query_context context; double qtime = 1234; hash_map<const char*, const char*, hash<const char*>, eqstr> parameters; parameters.insert(std::pair<const char*,const char*>("q", ":CMD<QUERY>")); context._auto_lang = "LANG"; // select page 1 EXPECT_EQ(SP_ERR_OK, collect_json_results(results, &parameters, &context, qtime)); result = miscutil::join_string_list(",", results); EXPECT_NE(std::string::npos, std::string(result).find("\"LANG\"")); EXPECT_NE(std::string::npos, std::string(result).find("\"date\"")); EXPECT_NE(std::string::npos, std::string(result).find("\"qtime\":1234")); EXPECT_NE(std::string::npos, std::string(result).find("\"pers\":\"on\"")); EXPECT_NE(std::string::npos, std::string(result).find("\"&lt;QUERY&gt;\"")); EXPECT_EQ(std::string::npos, std::string(result).find("CMD")); EXPECT_EQ(std::string::npos, std::string(result).find("suggestion")); EXPECT_EQ(std::string::npos, std::string(result).find("engines")); EXPECT_EQ(std::string::npos, std::string(result).find("\"yahoo\"")); // prs precedence logic websearch::_wconfig->_personalization = false; results.clear(); EXPECT_EQ(SP_ERR_OK, collect_json_results(results, &parameters, &context, qtime)); result = miscutil::join_string_list(",", results); EXPECT_NE(std::string::npos, std::string(result).find("\"pers\":\"off\"")); parameters.insert(std::pair<const char*,const char*>("prs", "on")); results.clear(); EXPECT_EQ(SP_ERR_OK, collect_json_results(results, &parameters, &context, qtime)); result = miscutil::join_string_list(",", results); EXPECT_NE(std::string::npos, std::string(result).find("\"pers\":\"on\"")); // suggestion context._suggestions.push_back("SUGGESTION1"); context._suggestions.push_back("SUGGESTION2"); results.clear(); EXPECT_EQ(SP_ERR_OK, collect_json_results(results, &parameters, &context, qtime)); result = miscutil::join_string_list(",", results); EXPECT_NE(std::string::npos, std::string(result).find("suggestion")); EXPECT_NE(std::string::npos, std::string(result).find("SUGGESTION1")); EXPECT_EQ(std::string::npos, std::string(result).find("SUGGESTION2")); // engines context._engines = std::bitset<NSEs>(SE_YAHOO); results.clear(); EXPECT_EQ(SP_ERR_OK, collect_json_results(results, &parameters, &context, qtime)); result = miscutil::join_string_list(",", results); EXPECT_NE(std::string::npos, std::string(result).find("\"yahoo\"")); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>type in author name<commit_after>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2010 Loic Dachary <loic@dachary.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **/ #define _PCREPOSIX_H // avoid pcreposix.h conflict with regex.h used by gtest #include <gtest/gtest.h> #include "json_renderer.h" #include "json_renderer_private.h" using namespace seeks_plugins; using namespace json_renderer_private; TEST(JsonRendererTest, render_engines) { EXPECT_EQ("\"google\",\"bing\",\"yauba\",\"yahoo\",\"exalead\",\"twitter\"", json_renderer::render_engines(SE_GOOGLE|SE_BING|SE_YAUBA|SE_YAHOO|SE_EXALEAD|SE_TWITTER)); } TEST(JsonRendererTest, render_snippets) { websearch::_wconfig = new websearch_configuration("not a real filename"); std::string json_str; int current_page = 1; std::vector<search_snippet*> snippets; const std::string query_clean; hash_map<const char*, const char*, hash<const char*>, eqstr> parameters; // zero snippet EXPECT_EQ(SP_ERR_OK, json_renderer::render_snippets(query_clean, current_page, snippets, json_str, &parameters)); EXPECT_EQ("\"snippets\":[]", json_str); // 1 snippet, page 1 json_str = ""; snippets.resize(1); search_snippet s1; s1.set_url("URL1"); snippets[0] = &s1; EXPECT_EQ(SP_ERR_OK, json_renderer::render_snippets(query_clean, current_page, snippets, json_str, &parameters)); EXPECT_TRUE(json_str.find(s1._url) != std::string::npos); EXPECT_EQ(std::string::npos, json_str.find("thumb")); // 1 snippet, page 1, thumbs on json_str = ""; parameters.insert(std::pair<const char*,const char*>("thumbs", "on")); EXPECT_EQ(SP_ERR_OK, json_renderer::render_snippets(query_clean, current_page, snippets, json_str, &parameters)); EXPECT_TRUE(json_str.find(s1._url) != std::string::npos); EXPECT_NE(std::string::npos, json_str.find("thumb")); // 3 snippets, page 2, 2 result per page, thumbs on snippets.resize(3); search_snippet s2; s2.set_url("URL2"); snippets[1] = &s2; search_snippet s3; s3.set_url("URL3"); snippets[2] = &s3; parameters.insert(std::pair<const char*,const char*>("rpp", "2")); current_page = 2; json_str = ""; EXPECT_EQ(SP_ERR_OK, json_renderer::render_snippets(query_clean, current_page, snippets, json_str, &parameters)); EXPECT_EQ(std::string::npos, json_str.find(s1._url)); EXPECT_EQ(std::string::npos, json_str.find(s2._url)); EXPECT_NE(std::string::npos, json_str.find(s3._url)); // 3 snippets, page 1, 2 result per page, thumbs on current_page = 1; json_str = ""; EXPECT_EQ(SP_ERR_OK, json_renderer::render_snippets(query_clean, current_page, snippets, json_str, &parameters)); EXPECT_NE(std::string::npos, json_str.find(s1._url)); EXPECT_NE(std::string::npos, json_str.find(s2._url)); EXPECT_EQ(std::string::npos, json_str.find(s3._url)); // 3 snippets, page 1, 2 result per page, second snippet rejected, thumbs on current_page = 1; s1._doc_type = REJECTED; json_str = ""; EXPECT_EQ(SP_ERR_OK, json_renderer::render_snippets(query_clean, current_page, snippets, json_str, &parameters)); EXPECT_EQ(std::string::npos, json_str.find(s1._url)); EXPECT_NE(std::string::npos, json_str.find(s2._url)); EXPECT_NE(std::string::npos, json_str.find(s3._url)); s1._doc_type = WEBPAGE; // 3 snippets, page 1, 2 result per page, similarity on, thumbs on current_page = 1; s1._seeks_ir = 1.0; s2._seeks_ir = 0.0; s3._seeks_ir = 1.0; json_str = ""; EXPECT_EQ(SP_ERR_OK, json_renderer::render_snippets(query_clean, current_page, snippets, json_str, &parameters)); EXPECT_NE(std::string::npos, json_str.find(s1._url)); EXPECT_EQ(std::string::npos, json_str.find(s2._url)); EXPECT_NE(std::string::npos, json_str.find(s3._url)); } TEST(JsonRendererTest, render_clustered_snippets) { websearch::_wconfig = new websearch_configuration("not a real filename"); query_context context; cluster clusters[3]; std::string json_str; std::vector<search_snippet*> snippets; const std::string query_clean; hash_map<const char*, const char*, hash<const char*>, eqstr> parameters; search_snippet s1; s1.set_url("URL1"); context.add_to_unordered_cache(&s1); clusters[0].add_point(s1._id, NULL); clusters[0]._label = "CLUSTER1"; search_snippet s2; s2.set_url("URL2"); context.add_to_unordered_cache(&s2); clusters[1].add_point(s2._id, NULL); search_snippet s3; s3.set_url("URL3"); context.add_to_unordered_cache(&s3); clusters[1].add_point(s3._id, NULL); clusters[1]._label = "CLUSTER2"; clusters[2]._label = "CLUSTER3"; parameters.insert(std::pair<const char*,const char*>("rpp", "1")); EXPECT_EQ(SP_ERR_OK, json_renderer::render_clustered_snippets(query_clean, clusters, 3, &context, json_str, &parameters)); EXPECT_NE(std::string::npos, json_str.find(clusters[0]._label)); EXPECT_NE(std::string::npos, json_str.find(s1._url)); EXPECT_NE(std::string::npos, json_str.find(clusters[1]._label)); EXPECT_NE(std::string::npos, json_str.find(s2._url)); EXPECT_NE(std::string::npos, json_str.find(s3._url)); EXPECT_EQ(std::string::npos, json_str.find(clusters[2]._label)); } TEST(JsonRendererTest, render_json_results) { websearch::_wconfig = new websearch_configuration("not a real filename"); http_response* rsp; query_context context; double qtime = 1234; std::vector<search_snippet*> snippets; hash_map<const char*, const char*, hash<const char*>, eqstr> parameters; snippets.resize(2); search_snippet s1; s1.set_url("URL1"); snippets[0] = &s1; search_snippet s2; s2.set_url("URL2"); snippets[1] = &s2; parameters.insert(std::pair<const char*,const char*>("rpp", "1")); parameters.insert(std::pair<const char*,const char*>("q", "<QUERY>")); parameters.insert(std::pair<const char*,const char*>("callback", "JSONP")); // select page 1 rsp = new http_response(); EXPECT_EQ(SP_ERR_OK, json_renderer::render_json_results(snippets, NULL, rsp, &parameters, &context, qtime)); EXPECT_NE(std::string::npos, std::string(rsp->_body).find("JSONP({")); EXPECT_NE(std::string::npos, std::string(rsp->_body).find("\"qtime\":1234")); EXPECT_NE(std::string::npos, std::string(rsp->_body).find("\"&lt;QUERY&gt;\"")); EXPECT_NE(std::string::npos, std::string(rsp->_body).find(s1._url)); EXPECT_EQ(std::string::npos, std::string(rsp->_body).find(s2._url)); delete rsp; // select page 2 parameters.insert(std::pair<const char*,const char*>("page", "2")); rsp = new http_response(); EXPECT_EQ(SP_ERR_OK, json_renderer::render_json_results(snippets, NULL, rsp, &parameters, &context, qtime)); EXPECT_EQ(std::string::npos, std::string(rsp->_body).find(s1._url)); EXPECT_NE(std::string::npos, std::string(rsp->_body).find(s2._url)); delete rsp; } TEST(JsonRendererTest, render_clustered_json_results) { websearch::_wconfig = new websearch_configuration("not a real filename"); cluster clusters[1]; http_response* rsp; query_context context; double qtime = 1234; std::vector<search_snippet*> snippets; const std::string query_clean; hash_map<const char*, const char*, hash<const char*>, eqstr> parameters; search_snippet s1; s1.set_url("URL1"); context.add_to_unordered_cache(&s1); clusters[0].add_point(s1._id, NULL); clusters[0]._label = "CLUSTER1"; parameters.insert(std::pair<const char*,const char*>("q", "<QUERY>")); parameters.insert(std::pair<const char*,const char*>("callback", "JSONP")); rsp = new http_response(); EXPECT_EQ(SP_ERR_OK, json_renderer::render_clustered_json_results(clusters, 1, NULL, rsp, &parameters, &context, qtime)); EXPECT_NE(std::string::npos, std::string(rsp->_body).find("JSONP({")); EXPECT_NE(std::string::npos, std::string(rsp->_body).find("\"qtime\":1234")); EXPECT_NE(std::string::npos, std::string(rsp->_body).find("\"&lt;QUERY&gt;\"")); EXPECT_NE(std::string::npos, std::string(rsp->_body).find(s1._url)); EXPECT_NE(std::string::npos, std::string(rsp->_body).find(clusters[0]._label)); std::cout << rsp->_body << std::endl; delete rsp; } TEST(JsonRendererTest, response) { http_response rsp; response(&rsp, "JSON"); EXPECT_EQ(rsp._content_length, strlen(rsp._body)); EXPECT_STREQ("JSON", rsp._body); } TEST(JsonRendererTest, query_clean) { std::string q(":CMD<QUERY>"); EXPECT_EQ("&lt;QUERY&gt;", query_clean(q)); } TEST(JsonRendererTest, jsonp) { std::string input("WHAT"); const char* callback = "CALLBACK"; EXPECT_EQ("CALLBACK(WHAT)", jsonp(input, callback)); EXPECT_EQ("WHAT", jsonp(input, NULL)); } TEST(JsonRendererTest, collect_json_results) { websearch::_wconfig = new websearch_configuration("not a real filename"); std::string result; std::list<std::string> results; query_context context; double qtime = 1234; hash_map<const char*, const char*, hash<const char*>, eqstr> parameters; parameters.insert(std::pair<const char*,const char*>("q", ":CMD<QUERY>")); context._auto_lang = "LANG"; // select page 1 EXPECT_EQ(SP_ERR_OK, collect_json_results(results, &parameters, &context, qtime)); result = miscutil::join_string_list(",", results); EXPECT_NE(std::string::npos, std::string(result).find("\"LANG\"")); EXPECT_NE(std::string::npos, std::string(result).find("\"date\"")); EXPECT_NE(std::string::npos, std::string(result).find("\"qtime\":1234")); EXPECT_NE(std::string::npos, std::string(result).find("\"pers\":\"on\"")); EXPECT_NE(std::string::npos, std::string(result).find("\"&lt;QUERY&gt;\"")); EXPECT_EQ(std::string::npos, std::string(result).find("CMD")); EXPECT_EQ(std::string::npos, std::string(result).find("suggestion")); EXPECT_EQ(std::string::npos, std::string(result).find("engines")); EXPECT_EQ(std::string::npos, std::string(result).find("\"yahoo\"")); // prs precedence logic websearch::_wconfig->_personalization = false; results.clear(); EXPECT_EQ(SP_ERR_OK, collect_json_results(results, &parameters, &context, qtime)); result = miscutil::join_string_list(",", results); EXPECT_NE(std::string::npos, std::string(result).find("\"pers\":\"off\"")); parameters.insert(std::pair<const char*,const char*>("prs", "on")); results.clear(); EXPECT_EQ(SP_ERR_OK, collect_json_results(results, &parameters, &context, qtime)); result = miscutil::join_string_list(",", results); EXPECT_NE(std::string::npos, std::string(result).find("\"pers\":\"on\"")); // suggestion context._suggestions.push_back("SUGGESTION1"); context._suggestions.push_back("SUGGESTION2"); results.clear(); EXPECT_EQ(SP_ERR_OK, collect_json_results(results, &parameters, &context, qtime)); result = miscutil::join_string_list(",", results); EXPECT_NE(std::string::npos, std::string(result).find("suggestion")); EXPECT_NE(std::string::npos, std::string(result).find("SUGGESTION1")); EXPECT_EQ(std::string::npos, std::string(result).find("SUGGESTION2")); // engines context._engines = std::bitset<NSEs>(SE_YAHOO); results.clear(); EXPECT_EQ(SP_ERR_OK, collect_json_results(results, &parameters, &context, qtime)); result = miscutil::join_string_list(",", results); EXPECT_NE(std::string::npos, std::string(result).find("\"yahoo\"")); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>// Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Nazara Engine - Vulkan Renderer" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/VulkanRenderer/Wrapper/Device.hpp> #include <Nazara/Core/CallOnExit.hpp> #include <Nazara/Core/Error.hpp> #include <Nazara/Core/ErrorFlags.hpp> #include <Nazara/VulkanRenderer/Wrapper/CommandBuffer.hpp> #include <Nazara/VulkanRenderer/Wrapper/CommandPool.hpp> #include <Nazara/VulkanRenderer/Wrapper/QueueHandle.hpp> #define VMA_IMPLEMENTATION #define VMA_STATIC_VULKAN_FUNCTIONS 0 #include <vma/vk_mem_alloc.h> #include <Nazara/VulkanRenderer/Debug.hpp> namespace Nz { namespace Vk { struct Device::InternalData { std::array<Vk::CommandPool, QueueCount> commandPools; }; Device::Device(Instance& instance) : m_instance(instance), m_physicalDevice(nullptr), m_device(VK_NULL_HANDLE), m_lastErrorCode(VK_SUCCESS), m_memAllocator(VK_NULL_HANDLE) { } Device::~Device() { if (m_device != VK_NULL_HANDLE) WaitAndDestroyDevice(); } AutoCommandBuffer Device::AllocateCommandBuffer(QueueType queueType) { return m_internalData->commandPools[UnderlyingCast(queueType)].AllocateCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY); } bool Device::Create(const Vk::PhysicalDevice& deviceInfo, const VkDeviceCreateInfo& createInfo, const VkAllocationCallbacks* allocator) { m_lastErrorCode = m_instance.vkCreateDevice(deviceInfo.physDevice, &createInfo, allocator, &m_device); if (m_lastErrorCode != VkResult::VK_SUCCESS) { NazaraError("Failed to create Vulkan device: " + TranslateVulkanError(m_lastErrorCode)); return false; } CallOnExit destroyOnFailure([this] { Destroy(); }); m_physicalDevice = &deviceInfo; // Store the allocator to access them when needed if (allocator) m_allocator = *allocator; else m_allocator.pfnAllocation = nullptr; // Parse extensions and layers for (UInt32 i = 0; i < createInfo.enabledExtensionCount; ++i) m_loadedExtensions.emplace(createInfo.ppEnabledExtensionNames[i]); for (UInt32 i = 0; i < createInfo.enabledLayerCount; ++i) m_loadedLayers.emplace(createInfo.ppEnabledLayerNames[i]); // Load all device-related functions try { ErrorFlags flags(ErrorFlag_ThrowException, true); UInt32 deviceVersion = deviceInfo.properties.apiVersion; #define NAZARA_VULKANRENDERER_DEVICE_EXT_BEGIN(ext) if (IsExtensionLoaded(#ext)) { #define NAZARA_VULKANRENDERER_DEVICE_EXT_END() } #define NAZARA_VULKANRENDERER_DEVICE_FUNCTION(func) func = reinterpret_cast<PFN_##func>(GetProcAddr(#func)); #define NAZARA_VULKANRENDERER_INSTANCE_EXT_BEGIN(ext) if (m_instance.IsExtensionLoaded(#ext)) { #define NAZARA_VULKANRENDERER_INSTANCE_EXT_END() } #define NAZARA_VULKANRENDERER_DEVICE_CORE_EXT_FUNCTION(func, coreVersion, suffix, extName) \ if (deviceVersion >= coreVersion) \ func = reinterpret_cast<PFN_##func>(GetProcAddr(#func)); \ else if (IsExtensionLoaded("VK_" #suffix "_" #extName)) \ func = reinterpret_cast<PFN_##func##suffix>(GetProcAddr(#func #suffix)); #include <Nazara/VulkanRenderer/Wrapper/DeviceFunctions.hpp> } catch (const std::exception& e) { NazaraError(std::string("Failed to query device function: ") + e.what()); return false; } // And retains informations about queues UInt32 maxFamilyIndex = 0; m_enabledQueuesInfos.resize(createInfo.queueCreateInfoCount); for (UInt32 i = 0; i < createInfo.queueCreateInfoCount; ++i) { const VkDeviceQueueCreateInfo& queueCreateInfo = createInfo.pQueueCreateInfos[i]; QueueFamilyInfo& info = m_enabledQueuesInfos[i]; info.familyIndex = queueCreateInfo.queueFamilyIndex; if (info.familyIndex > maxFamilyIndex) maxFamilyIndex = info.familyIndex; const VkQueueFamilyProperties& queueProperties = deviceInfo.queueFamilies[info.familyIndex]; info.flags = queueProperties.queueFlags; info.minImageTransferGranularity = queueProperties.minImageTransferGranularity; info.timestampValidBits = queueProperties.timestampValidBits; info.queues.resize(queueCreateInfo.queueCount); for (UInt32 queueIndex = 0; queueIndex < queueCreateInfo.queueCount; ++queueIndex) { QueueInfo& queueInfo = info.queues[queueIndex]; queueInfo.familyInfo = &info; queueInfo.priority = queueCreateInfo.pQueuePriorities[queueIndex]; vkGetDeviceQueue(m_device, info.familyIndex, queueIndex, &queueInfo.queue); } } m_queuesByFamily.resize(maxFamilyIndex + 1); for (const QueueFamilyInfo& familyInfo : m_enabledQueuesInfos) m_queuesByFamily[familyInfo.familyIndex] = &familyInfo.queues; m_internalData = std::make_unique<InternalData>(); m_defaultQueues.fill(InvalidQueue); for (QueueType queueType : { QueueType::Graphics, QueueType::Compute, QueueType::Transfer }) { auto QueueTypeToFlags = [](QueueType type) -> VkQueueFlags { switch (type) { case QueueType::Compute: return VK_QUEUE_COMPUTE_BIT; case QueueType::Graphics: return VK_QUEUE_GRAPHICS_BIT; case QueueType::Transfer: return VK_QUEUE_COMPUTE_BIT | VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_TRANSFER_BIT; //< Compute/graphics imply transfer } return 0U; }; std::size_t queueIndex = static_cast<std::size_t>(queueType); for (const QueueFamilyInfo& familyInfo : m_enabledQueuesInfos) { if (familyInfo.flags & QueueTypeToFlags(queueType) == 0) continue; m_defaultQueues[queueIndex] = familyInfo.familyIndex; // Break only if queue has not been selected before auto queueBegin = m_defaultQueues.begin(); auto queueEnd = queueBegin + queueIndex; if (std::find(queueBegin, queueEnd, familyInfo.familyIndex) == queueEnd) break; } Vk::CommandPool& commandPool = m_internalData->commandPools[queueIndex]; if (!commandPool.Create(*this, m_defaultQueues[queueIndex], VK_COMMAND_POOL_CREATE_TRANSIENT_BIT)) { NazaraError("Failed to create command pool: " + TranslateVulkanError(commandPool.GetLastErrorCode())); return false; } } assert(GetDefaultFamilyIndex(QueueType::Transfer) != InvalidQueue); // Initialize VMA VmaVulkanFunctions vulkanFunctions = { m_instance.vkGetPhysicalDeviceProperties, m_instance.vkGetPhysicalDeviceMemoryProperties, vkAllocateMemory, vkFreeMemory, vkMapMemory, vkUnmapMemory, vkFlushMappedMemoryRanges, vkInvalidateMappedMemoryRanges, vkBindBufferMemory, vkBindImageMemory, vkGetBufferMemoryRequirements, vkGetImageMemoryRequirements, vkCreateBuffer, vkDestroyBuffer, vkCreateImage, vkDestroyImage, vkCmdCopyBuffer, #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 vkGetBufferMemoryRequirements2, vkGetImageMemoryRequirements2, #endif #if VMA_BIND_MEMORY2 || VMA_VULKAN_VERSION >= 1001000 vkBindBufferMemory2, vkBindImageMemory2, #endif #if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000 m_instance.vkGetPhysicalDeviceMemoryProperties2, #endif }; VmaAllocatorCreateInfo allocatorInfo = {}; allocatorInfo.physicalDevice = deviceInfo.physDevice; allocatorInfo.device = m_device; allocatorInfo.instance = m_instance; allocatorInfo.vulkanApiVersion = std::min<UInt32>(VK_API_VERSION_1_1, m_instance.GetApiVersion()); allocatorInfo.pVulkanFunctions = &vulkanFunctions; if (vkGetBufferMemoryRequirements2 && vkGetImageMemoryRequirements2) allocatorInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT; if (vkBindBufferMemory2 && vkBindImageMemory2) allocatorInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT; if (IsExtensionLoaded(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME)) allocatorInfo.flags |= VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT; m_lastErrorCode = vmaCreateAllocator(&allocatorInfo, &m_memAllocator); if (m_lastErrorCode != VK_SUCCESS) { NazaraError("Failed to initialize Vulkan Memory Allocator (VMA): " + TranslateVulkanError(m_lastErrorCode)); return false; } destroyOnFailure.Reset(); return true; } void Device::Destroy() { if (m_device != VK_NULL_HANDLE) { WaitAndDestroyDevice(); ResetPointers(); } } QueueHandle Device::GetQueue(UInt32 queueFamilyIndex, UInt32 queueIndex) { const auto& queues = GetEnabledQueues(queueFamilyIndex); NazaraAssert(queueIndex < queues.size(), "Invalid queue index"); return QueueHandle(*this, queues[queueIndex].queue, queueFamilyIndex); } void Device::ResetPointers() { m_device = VK_NULL_HANDLE; m_physicalDevice = nullptr; // Reset functions pointers #define NAZARA_VULKANRENDERER_DEVICE_FUNCTION(func) func = nullptr; #define NAZARA_VULKANRENDERER_DEVICE_CORE_EXT_FUNCTION(func, ...) NAZARA_VULKANRENDERER_DEVICE_FUNCTION(func) #include <Nazara/VulkanRenderer/Wrapper/DeviceFunctions.hpp> } void Device::WaitAndDestroyDevice() { assert(m_device != VK_NULL_HANDLE); if (vkDeviceWaitIdle) vkDeviceWaitIdle(m_device); if (m_memAllocator != VK_NULL_HANDLE) vmaDestroyAllocator(m_memAllocator); m_internalData.reset(); if (vkDestroyDevice) vkDestroyDevice(m_device, (m_allocator.pfnAllocation) ? &m_allocator : nullptr); } } } <commit_msg>Fix some warnings<commit_after>// Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Nazara Engine - Vulkan Renderer" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/VulkanRenderer/Wrapper/Device.hpp> #include <Nazara/Core/CallOnExit.hpp> #include <Nazara/Core/Error.hpp> #include <Nazara/Core/ErrorFlags.hpp> #include <Nazara/VulkanRenderer/Wrapper/CommandBuffer.hpp> #include <Nazara/VulkanRenderer/Wrapper/CommandPool.hpp> #include <Nazara/VulkanRenderer/Wrapper/QueueHandle.hpp> #define VMA_IMPLEMENTATION #define VMA_USE_STL_CONTAINERS 1 #define VMA_STATIC_VULKAN_FUNCTIONS 0 #include <vma/vk_mem_alloc.h> #include <Nazara/VulkanRenderer/Debug.hpp> namespace Nz { namespace Vk { struct Device::InternalData { std::array<Vk::CommandPool, QueueCount> commandPools; }; Device::Device(Instance& instance) : m_instance(instance), m_physicalDevice(nullptr), m_device(VK_NULL_HANDLE), m_lastErrorCode(VK_SUCCESS), m_memAllocator(VK_NULL_HANDLE) { } Device::~Device() { if (m_device != VK_NULL_HANDLE) WaitAndDestroyDevice(); } AutoCommandBuffer Device::AllocateCommandBuffer(QueueType queueType) { return m_internalData->commandPools[UnderlyingCast(queueType)].AllocateCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY); } bool Device::Create(const Vk::PhysicalDevice& deviceInfo, const VkDeviceCreateInfo& createInfo, const VkAllocationCallbacks* allocator) { m_lastErrorCode = m_instance.vkCreateDevice(deviceInfo.physDevice, &createInfo, allocator, &m_device); if (m_lastErrorCode != VkResult::VK_SUCCESS) { NazaraError("Failed to create Vulkan device: " + TranslateVulkanError(m_lastErrorCode)); return false; } CallOnExit destroyOnFailure([this] { Destroy(); }); m_physicalDevice = &deviceInfo; // Store the allocator to access them when needed if (allocator) m_allocator = *allocator; else m_allocator.pfnAllocation = nullptr; // Parse extensions and layers for (UInt32 i = 0; i < createInfo.enabledExtensionCount; ++i) m_loadedExtensions.emplace(createInfo.ppEnabledExtensionNames[i]); for (UInt32 i = 0; i < createInfo.enabledLayerCount; ++i) m_loadedLayers.emplace(createInfo.ppEnabledLayerNames[i]); // Load all device-related functions try { ErrorFlags flags(ErrorFlag_ThrowException, true); UInt32 deviceVersion = deviceInfo.properties.apiVersion; #define NAZARA_VULKANRENDERER_DEVICE_EXT_BEGIN(ext) if (IsExtensionLoaded(#ext)) { #define NAZARA_VULKANRENDERER_DEVICE_EXT_END() } #define NAZARA_VULKANRENDERER_DEVICE_FUNCTION(func) func = reinterpret_cast<PFN_##func>(GetProcAddr(#func)); #define NAZARA_VULKANRENDERER_INSTANCE_EXT_BEGIN(ext) if (m_instance.IsExtensionLoaded(#ext)) { #define NAZARA_VULKANRENDERER_INSTANCE_EXT_END() } #define NAZARA_VULKANRENDERER_DEVICE_CORE_EXT_FUNCTION(func, coreVersion, suffix, extName) \ if (deviceVersion >= coreVersion) \ func = reinterpret_cast<PFN_##func>(GetProcAddr(#func)); \ else if (IsExtensionLoaded("VK_" #suffix "_" #extName)) \ func = reinterpret_cast<PFN_##func##suffix>(GetProcAddr(#func #suffix)); #include <Nazara/VulkanRenderer/Wrapper/DeviceFunctions.hpp> } catch (const std::exception& e) { NazaraError(std::string("Failed to query device function: ") + e.what()); return false; } // And retains informations about queues UInt32 maxFamilyIndex = 0; m_enabledQueuesInfos.resize(createInfo.queueCreateInfoCount); for (UInt32 i = 0; i < createInfo.queueCreateInfoCount; ++i) { const VkDeviceQueueCreateInfo& queueCreateInfo = createInfo.pQueueCreateInfos[i]; QueueFamilyInfo& info = m_enabledQueuesInfos[i]; info.familyIndex = queueCreateInfo.queueFamilyIndex; if (info.familyIndex > maxFamilyIndex) maxFamilyIndex = info.familyIndex; const VkQueueFamilyProperties& queueProperties = deviceInfo.queueFamilies[info.familyIndex]; info.flags = queueProperties.queueFlags; info.minImageTransferGranularity = queueProperties.minImageTransferGranularity; info.timestampValidBits = queueProperties.timestampValidBits; info.queues.resize(queueCreateInfo.queueCount); for (UInt32 queueIndex = 0; queueIndex < queueCreateInfo.queueCount; ++queueIndex) { QueueInfo& queueInfo = info.queues[queueIndex]; queueInfo.familyInfo = &info; queueInfo.priority = queueCreateInfo.pQueuePriorities[queueIndex]; vkGetDeviceQueue(m_device, info.familyIndex, queueIndex, &queueInfo.queue); } } m_queuesByFamily.resize(maxFamilyIndex + 1); for (const QueueFamilyInfo& familyInfo : m_enabledQueuesInfos) m_queuesByFamily[familyInfo.familyIndex] = &familyInfo.queues; m_internalData = std::make_unique<InternalData>(); m_defaultQueues.fill(InvalidQueue); for (QueueType queueType : { QueueType::Graphics, QueueType::Compute, QueueType::Transfer }) { auto QueueTypeToFlags = [](QueueType type) -> VkQueueFlags { switch (type) { case QueueType::Compute: return VK_QUEUE_COMPUTE_BIT; case QueueType::Graphics: return VK_QUEUE_GRAPHICS_BIT; case QueueType::Transfer: return VK_QUEUE_COMPUTE_BIT | VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_TRANSFER_BIT; //< Compute/graphics imply transfer } return 0U; }; std::size_t queueIndex = static_cast<std::size_t>(queueType); for (const QueueFamilyInfo& familyInfo : m_enabledQueuesInfos) { if ((familyInfo.flags & QueueTypeToFlags(queueType)) == 0) continue; m_defaultQueues[queueIndex] = familyInfo.familyIndex; // Break only if queue has not been selected before auto queueBegin = m_defaultQueues.begin(); auto queueEnd = queueBegin + queueIndex; if (std::find(queueBegin, queueEnd, familyInfo.familyIndex) == queueEnd) break; } Vk::CommandPool& commandPool = m_internalData->commandPools[queueIndex]; if (!commandPool.Create(*this, m_defaultQueues[queueIndex], VK_COMMAND_POOL_CREATE_TRANSIENT_BIT)) { NazaraError("Failed to create command pool: " + TranslateVulkanError(commandPool.GetLastErrorCode())); return false; } } assert(GetDefaultFamilyIndex(QueueType::Transfer) != InvalidQueue); // Initialize VMA VmaVulkanFunctions vulkanFunctions = { m_instance.vkGetPhysicalDeviceProperties, m_instance.vkGetPhysicalDeviceMemoryProperties, vkAllocateMemory, vkFreeMemory, vkMapMemory, vkUnmapMemory, vkFlushMappedMemoryRanges, vkInvalidateMappedMemoryRanges, vkBindBufferMemory, vkBindImageMemory, vkGetBufferMemoryRequirements, vkGetImageMemoryRequirements, vkCreateBuffer, vkDestroyBuffer, vkCreateImage, vkDestroyImage, vkCmdCopyBuffer, #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 vkGetBufferMemoryRequirements2, vkGetImageMemoryRequirements2, #endif #if VMA_BIND_MEMORY2 || VMA_VULKAN_VERSION >= 1001000 vkBindBufferMemory2, vkBindImageMemory2, #endif #if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000 m_instance.vkGetPhysicalDeviceMemoryProperties2, #endif }; VmaAllocatorCreateInfo allocatorInfo = {}; allocatorInfo.physicalDevice = deviceInfo.physDevice; allocatorInfo.device = m_device; allocatorInfo.instance = m_instance; allocatorInfo.vulkanApiVersion = std::min<UInt32>(VK_API_VERSION_1_1, m_instance.GetApiVersion()); allocatorInfo.pVulkanFunctions = &vulkanFunctions; if (vkGetBufferMemoryRequirements2 && vkGetImageMemoryRequirements2) allocatorInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT; if (vkBindBufferMemory2 && vkBindImageMemory2) allocatorInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT; if (IsExtensionLoaded(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME)) allocatorInfo.flags |= VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT; m_lastErrorCode = vmaCreateAllocator(&allocatorInfo, &m_memAllocator); if (m_lastErrorCode != VK_SUCCESS) { NazaraError("Failed to initialize Vulkan Memory Allocator (VMA): " + TranslateVulkanError(m_lastErrorCode)); return false; } destroyOnFailure.Reset(); return true; } void Device::Destroy() { if (m_device != VK_NULL_HANDLE) { WaitAndDestroyDevice(); ResetPointers(); } } QueueHandle Device::GetQueue(UInt32 queueFamilyIndex, UInt32 queueIndex) { const auto& queues = GetEnabledQueues(queueFamilyIndex); NazaraAssert(queueIndex < queues.size(), "Invalid queue index"); return QueueHandle(*this, queues[queueIndex].queue, queueFamilyIndex); } void Device::ResetPointers() { m_device = VK_NULL_HANDLE; m_physicalDevice = nullptr; // Reset functions pointers #define NAZARA_VULKANRENDERER_DEVICE_FUNCTION(func) func = nullptr; #define NAZARA_VULKANRENDERER_DEVICE_CORE_EXT_FUNCTION(func, ...) NAZARA_VULKANRENDERER_DEVICE_FUNCTION(func) #include <Nazara/VulkanRenderer/Wrapper/DeviceFunctions.hpp> } void Device::WaitAndDestroyDevice() { assert(m_device != VK_NULL_HANDLE); if (vkDeviceWaitIdle) vkDeviceWaitIdle(m_device); if (m_memAllocator != VK_NULL_HANDLE) vmaDestroyAllocator(m_memAllocator); m_internalData.reset(); if (vkDestroyDevice) vkDestroyDevice(m_device, (m_allocator.pfnAllocation) ? &m_allocator : nullptr); } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2009, Yuuki Takano (ytakanoster@gmail.com). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the writers 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 "timer.hpp" #include <iostream> namespace libcage { void timer_callback(int fd, short event, void *arg) { timer::callback &func = *(timer::callback*)arg; timer *t = func.get_timer(); t->m_events.erase(&func); func(); } timer::~timer() { boost::unordered_map<callback*, boost::shared_ptr<event> >::iterator it; for (it = m_events.begin(); it != m_events.end(); ++it) { evtimer_del(it->second.get()); } } void timer::set_timer(callback *func, timeval *t) { typedef boost::shared_ptr<event> ev_ptr; ev_ptr ev = ev_ptr(new event); // delete old event unset_timer(func); func->m_timer = this; // add new event m_events[func] = ev; evtimer_set(ev.get(), timer_callback, func); evtimer_add(ev.get(), t); } void timer::unset_timer(callback *func) { if (m_events[func] != NULL) { evtimer_del(m_events[func].get()); } } #ifdef DEBUG class timer_func : public timer::callback { public: virtual void operator() () { printf("test timer: ok\n"); } }; void timer::test_timer() { timeval tval1; tval1.tv_sec = 2; tval1.tv_usec = 0; timer *t; timer_func *func; t = new timer(); func = new timer_func(); t->set_timer(func, &tval1); } #endif // DEBUG } <commit_msg>fixed a bug<commit_after>/* * Copyright (c) 2009, Yuuki Takano (ytakanoster@gmail.com). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the writers 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 "timer.hpp" #include <iostream> namespace libcage { void timer_callback(int fd, short event, void *arg) { timer::callback &func = *(timer::callback*)arg; timer *t = func.get_timer(); t->m_events.erase(&func); func(); } timer::~timer() { boost::unordered_map<callback*, boost::shared_ptr<event> >::iterator it; for (it = m_events.begin(); it != m_events.end(); ++it) { evtimer_del(it->second.get()); } } void timer::set_timer(callback *func, timeval *t) { typedef boost::shared_ptr<event> ev_ptr; ev_ptr ev = ev_ptr(new event); // delete old event unset_timer(func); func->m_timer = this; // add new event m_events[func] = ev; evtimer_set(ev.get(), timer_callback, func); evtimer_add(ev.get(), t); } void timer::unset_timer(callback *func) { if (m_events.find(func) != m_events.end()) { evtimer_del(m_events[func].get()); m_events.erase(func); } } #ifdef DEBUG class timer_func : public timer::callback { public: virtual void operator() () { printf("test timer: ok\n"); } }; void timer::test_timer() { timeval tval1; tval1.tv_sec = 2; tval1.tv_usec = 0; timer *t; timer_func *func; t = new timer(); func = new timer_func(); t->set_timer(func, &tval1); } #endif // DEBUG } <|endoftext|>
<commit_before>#include "tmath.hpp" /* ================================ SINE ======================================== */ TMath::DOUBLE TMath::sin(DOUBLE x) { x = mod(x + PI, 2 * PI) - PI; DOUBLE r = 0; for (LONG n = 0; n <= 8L; n++) { r += pow(DOUBLE(-1), n) * pow(x, 2 * n + 1) / fac(2 * n + 1); } return r; } TMath::DOUBLE TMath::asin(DOUBLE x) { DOUBLE r = 0; DOUBLE delta = 1; for (LONG n = 1; delta > 1e-6; n++) { LONG odd = 2 * n - 1; DOUBLE oddf = oddfacd(odd - 2); DOUBLE f = facd(odd); DOUBLE p = pow(x, odd); DOUBLE d = p / f * oddf * oddf; delta = abs(d); r += p / f * oddf * oddf; } return r; } TMath::DOUBLE TMath::sinh(DOUBLE x) { return 0.5 * (exp(x) - exp(-x)); } /* ================================ COSINE ======================================== */ TMath::DOUBLE TMath::cos(DOUBLE x) { x = mod(x + PI, 2 * PI) - PI; DOUBLE r = 0; for (LONG n = 0; n <= 8L; n++) { r += pow(DOUBLE(-1.0), n) * pow(x, 2 * n) / fac(2 * n); } return r; } TMath::DOUBLE TMath::acos(DOUBLE x) { return PI / 2 - asin(x); } TMath::DOUBLE TMath::cosh(DOUBLE x) { return 0.5 * (exp(x) + exp(-x)); } /* ================================ TANGENT ======================================== */ TMath::DOUBLE TMath::tan(DOUBLE x) { return sin(x) / cos(x); } TMath::DOUBLE TMath::atan(DOUBLE x) { DOUBLE r = 0; DOUBLE delta = 1; for (LONG n = 0; delta > 1e-4; n++) { LONG odd = 2 * n + 1; DOUBLE d = DOUBLE(pow(-1LL, n)) * pow(x, odd) / DOUBLE(odd); delta = abs(d); r += d; } return r; } TMath::DOUBLE TMath::tanh(DOUBLE x) { return sinh(x) / cosh(x); } /* ================================ COTANGENT ======================================== */ TMath::DOUBLE TMath::cot(DOUBLE x) { return cos(x) / sin(x); } TMath::DOUBLE TMath::acot(DOUBLE x) { return PI / 2 - atan(x); } TMath::DOUBLE TMath::coth(DOUBLE x) { return cosh(x) / sinh(x); } /* ================================ SECANT ======================================== */ TMath::DOUBLE TMath::sec(DOUBLE x) { return 1 / cos(x); } TMath::DOUBLE TMath::asec(DOUBLE x) { return acos(1 / x); } TMath::DOUBLE TMath::sech(DOUBLE x) { return 1 / cosh(x); } /* ================================ COSECANT ======================================== */ TMath::DOUBLE TMath::csc(DOUBLE x) { return 1 / sin(x); } TMath::DOUBLE TMath::acsc(DOUBLE x) { return asin(1 / x); } TMath::DOUBLE TMath::csch(DOUBLE x) { return 1 / sinh(x); } /* ================================= FLOOR, CEIL AND MODULO ======================================== */ TMath::LONG TMath::floor(DOUBLE x) { LONG truncated = LONG(x); if (x < 0) { if (truncated > x) { return truncated - 1; } else { return truncated; } } else { return truncated; } } TMath::LONG TMath::ceil(DOUBLE x) { LONG truncated = LONG(x); if (x < 0) { return truncated; } else { return truncated + 1; } } TMath::DOUBLE TMath::mod(DOUBLE x, DOUBLE y) { return y * ((x / y) - floor(x / y)); } /* =============================== EXPONENTIAL FUNCTION, SQRT, LOGARITHM ======================= */ TMath::DOUBLE TMath::exp(DOUBLE x) { DOUBLE r = 0; for (LONG n = 0; n <= 15L; n++) { r += pow(x, n) / fac(n); } return r; } TMath::DOUBLE TMath::sqrt(DOUBLE x) { return root(x, 2); } TMath::DOUBLE TMath::root(DOUBLE x, DOUBLE n) { return pow(x, 1 / n); } TMath::DOUBLE TMath::ln(DOUBLE x) { x = (x - 1) / (x + 1); DOUBLE r = 0; for (LONG n = 0; n <= 100L; n++) { r += 2 * pow(x, 2 * n + 1) / (2 * n + 1); } return r; } TMath::DOUBLE TMath::lg(DOUBLE x) { return ln(x) / ln(10); } TMath::DOUBLE TMath::lb(DOUBLE x) { return ln(x) / ln(2); } TMath::DOUBLE TMath::log(DOUBLE x, DOUBLE n) { return ln(x) / ln(n); } /* =================================== POWER FUNCTIONS =====================================================*/ TMath::DOUBLE TMath::pow(DOUBLE x, LONG n) { if (n < 0) { return 1 / pow(x, -n); } DOUBLE r = 1; for (LONG i = 1; i <= n; i++) { r *= x; } return r; } TMath::LONG TMath::pow(LONG x, LONG n) { if (n < 0) { return 1 / pow(x, -n); } LONG r = 1; for (LONG i = 1; i <= n; i++) { r *= x; } return r; } TMath::DOUBLE TMath::pow(DOUBLE x, DOUBLE n) { return exp(n * ln(x)); } /* ========================================== FACULTY ============================================*/ TMath::LONG TMath::fac(LONG n) { LONG r = 1; for (LONG i = 2; i <= n; i++) { r *= i; } return r; } TMath::DOUBLE TMath::facd(LONG n) { DOUBLE r = 1; for (LONG i = 2; i <= n; i++) { r *= DOUBLE(i); } return r; } TMath::LONG TMath::oddfac(LONG n) { LONG r = 1; for (LONG i = 3; i <= n; i += 2) { r *= i; } return r; } TMath::DOUBLE TMath::oddfacd(LONG n) { DOUBLE r = 1; for (LONG i = 3; i <= n; i += 2) { r *= DOUBLE(i); } return r; } TMath::DOUBLE TMath::abs(DOUBLE x) { if (x < 0) return -x; else return x; } /* ========================================== DEGREE / RADIANT CONVERSION ================================*/ TMath::DOUBLE TMath::rad(DOUBLE deg) { return PI / 180 * deg; } TMath::DOUBLE TMath::deg(DOUBLE rad) { return 180 / PI * rad; } <commit_msg>fix: increased accuracy of exp<commit_after>#include "tmath.hpp" /* ================================ SINE ======================================== */ TMath::DOUBLE TMath::sin(DOUBLE x) { x = mod(x + PI, 2 * PI) - PI; DOUBLE r = 0; for (LONG n = 0; n <= 8L; n++) { r += pow(DOUBLE(-1), n) * pow(x, 2 * n + 1) / fac(2 * n + 1); } return r; } TMath::DOUBLE TMath::asin(DOUBLE x) { DOUBLE r = 0; DOUBLE delta = 1; for (LONG n = 1; delta > 1e-6; n++) { LONG odd = 2 * n - 1; DOUBLE oddf = oddfacd(odd - 2); DOUBLE f = facd(odd); DOUBLE p = pow(x, odd); DOUBLE d = p / f * oddf * oddf; delta = abs(d); r += p / f * oddf * oddf; } return r; } TMath::DOUBLE TMath::sinh(DOUBLE x) { return 0.5 * (exp(x) - exp(-x)); } /* ================================ COSINE ======================================== */ TMath::DOUBLE TMath::cos(DOUBLE x) { x = mod(x + PI, 2 * PI) - PI; DOUBLE r = 0; for (LONG n = 0; n <= 8L; n++) { r += pow(DOUBLE(-1.0), n) * pow(x, 2 * n) / fac(2 * n); } return r; } TMath::DOUBLE TMath::acos(DOUBLE x) { return PI / 2 - asin(x); } TMath::DOUBLE TMath::cosh(DOUBLE x) { return 0.5 * (exp(x) + exp(-x)); } /* ================================ TANGENT ======================================== */ TMath::DOUBLE TMath::tan(DOUBLE x) { return sin(x) / cos(x); } TMath::DOUBLE TMath::atan(DOUBLE x) { DOUBLE r = 0; DOUBLE delta = 1; for (LONG n = 0; delta > 1e-4; n++) { LONG odd = 2 * n + 1; DOUBLE d = DOUBLE(pow(-1LL, n)) * pow(x, odd) / DOUBLE(odd); delta = abs(d); r += d; } return r; } TMath::DOUBLE TMath::tanh(DOUBLE x) { return sinh(x) / cosh(x); } /* ================================ COTANGENT ======================================== */ TMath::DOUBLE TMath::cot(DOUBLE x) { return cos(x) / sin(x); } TMath::DOUBLE TMath::acot(DOUBLE x) { return PI / 2 - atan(x); } TMath::DOUBLE TMath::coth(DOUBLE x) { return cosh(x) / sinh(x); } /* ================================ SECANT ======================================== */ TMath::DOUBLE TMath::sec(DOUBLE x) { return 1 / cos(x); } TMath::DOUBLE TMath::asec(DOUBLE x) { return acos(1 / x); } TMath::DOUBLE TMath::sech(DOUBLE x) { return 1 / cosh(x); } /* ================================ COSECANT ======================================== */ TMath::DOUBLE TMath::csc(DOUBLE x) { return 1 / sin(x); } TMath::DOUBLE TMath::acsc(DOUBLE x) { return asin(1 / x); } TMath::DOUBLE TMath::csch(DOUBLE x) { return 1 / sinh(x); } /* ================================= FLOOR, CEIL AND MODULO ======================================== */ TMath::LONG TMath::floor(DOUBLE x) { LONG truncated = LONG(x); if (x < 0) { if (truncated > x) { return truncated - 1; } else { return truncated; } } else { return truncated; } } TMath::LONG TMath::ceil(DOUBLE x) { LONG truncated = LONG(x); if (x < 0) { return truncated; } else { return truncated + 1; } } TMath::DOUBLE TMath::mod(DOUBLE x, DOUBLE y) { return y * ((x / y) - floor(x / y)); } /* =============================== EXPONENTIAL FUNCTION, SQRT, LOGARITHM ======================= */ TMath::DOUBLE TMath::exp(DOUBLE x) { DOUBLE r = 0; for (LONG n = 0; n <= 15L; n++) { r += pow(x, n) / facd(n); } return r; } TMath::DOUBLE TMath::sqrt(DOUBLE x) { return root(x, 2); } TMath::DOUBLE TMath::root(DOUBLE x, DOUBLE n) { return pow(x, 1 / n); } TMath::DOUBLE TMath::ln(DOUBLE x) { x = (x - 1) / (x + 1); DOUBLE r = 0; for (LONG n = 0; n <= 100L; n++) { r += 2 * pow(x, 2 * n + 1) / (2 * n + 1); } return r; } TMath::DOUBLE TMath::lg(DOUBLE x) { return ln(x) / ln(10); } TMath::DOUBLE TMath::lb(DOUBLE x) { return ln(x) / ln(2); } TMath::DOUBLE TMath::log(DOUBLE x, DOUBLE n) { return ln(x) / ln(n); } /* =================================== POWER FUNCTIONS =====================================================*/ TMath::DOUBLE TMath::pow(DOUBLE x, LONG n) { if (n < 0) { return 1 / pow(x, -n); } DOUBLE r = 1; for (LONG i = 1; i <= n; i++) { r *= x; } return r; } TMath::LONG TMath::pow(LONG x, LONG n) { if (n < 0) { return 1 / pow(x, -n); } LONG r = 1; for (LONG i = 1; i <= n; i++) { r *= x; } return r; } TMath::DOUBLE TMath::pow(DOUBLE x, DOUBLE n) { return exp(n * ln(x)); } /* ========================================== FACULTY ============================================*/ TMath::LONG TMath::fac(LONG n) { LONG r = 1; for (LONG i = 2; i <= n; i++) { r *= i; } return r; } TMath::DOUBLE TMath::facd(LONG n) { DOUBLE r = 1; for (LONG i = 2; i <= n; i++) { r *= DOUBLE(i); } return r; } TMath::LONG TMath::oddfac(LONG n) { LONG r = 1; for (LONG i = 3; i <= n; i += 2) { r *= i; } return r; } TMath::DOUBLE TMath::oddfacd(LONG n) { DOUBLE r = 1; for (LONG i = 3; i <= n; i += 2) { r *= DOUBLE(i); } return r; } TMath::DOUBLE TMath::abs(DOUBLE x) { if (x < 0) return -x; else return x; } /* ========================================== DEGREE / RADIANT CONVERSION ================================*/ TMath::DOUBLE TMath::rad(DOUBLE deg) { return PI / 180 * deg; } TMath::DOUBLE TMath::deg(DOUBLE rad) { return 180 / PI * rad; } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <geometry_msgs/Twist.h> #include <sensor_msgs/PointCloud.h> #include <math.h> static const float tol = 0.000000000000001f; double magnitude(double vec[3]){ return sqrt(vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]); } void normalize(double vec[3]){ float m = magnitude(vec); if(tol <= m) m = 1; vec[0] /= m; vec[1] /= m; vec[2] /= m; if(fabs(vec[0]) < tol) vec[0] = 0.0f; if(fabs(vec[1]) < tol) vec[1] = 0.0f; if(fabs(vec[2]) < tol) vec[2] = 0.0f; } class ArtificialPotentialField{ public: ArtificialPotentialField(ros::NodeHandle &node) : cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)), obs_sub_(node.subscribe("slam_cloud", 10, &ArtificialPotentialField::obstacleCallback, this)) { for(int i=0; i < 3; i++) obs_[i] = 0; } void spin(){ ros::Rate r(10); ros::Duration(1).sleep(); geometry_msgs::Twist cmd; cmd.linear.z = 0.15; cmd_pub_.publish(cmd); ros::Duration(3).sleep(); cmd.linear.z = 0; cmd_pub_.publish(cmd); ros::Duration(3).sleep(); const double A = 0; const double B = 3; const double n = 1; const double m = 1.5; const double force = 0.025; while(ros::ok()){ double Fs[3]; Fs[0] = Fs[1] = Fs[2] = 0; double u[3]; u[0] = obs_[0]; u[1] = obs_[1]; u[2] = obs_[2]; normalize(u); const double d = magnitude(obs_); double U = -A/pow(d, n) + B/pow(d, m); Fs[0] += U * u[0]; Fs[1] += U * u[1]; Fs[2] += U * u[2]; cmd.linear.x = Fs[0] * force; cmd.linear.y = Fs[1] * force; ROS_INFO_STREAM("cmd = " << cmd); cmd_pub_.publish(cmd); r.sleep(); } } private: void obstacleCallback(const sensor_msgs::PointCloud &obs_msg){ double min_obs[3]; min_obs[0] = obs_msg.points[0].x; min_obs[1] = obs_msg.points[0].y; min_obs[2] = obs_msg.points[0].z; float min_dist = magnitude(min_obs); for(int i=1; i < obs_msg.channels.size(); i++){ double obs[3]; obs[0] = obs_msg.points[i].x; obs[1] = obs_msg.points[i].y; obs[2] = obs_msg.points[i].z; double dist = magnitude(obs); if(dist < min_dist){ min_obs[0] = obs[0]; min_obs[1] = obs[1]; min_obs[2] = obs[2]; min_dist = dist; } } obs_[0] = min_obs[0]; obs_[1] = min_obs[1]; obs_[2] = min_obs[2]; } double obs_[3]; ros::Publisher cmd_pub_; ros::Subscriber obs_sub_; }; int main(int argc, char *argv[]){ ros::init(argc, argv, "obstacle_avoidance"); ros::NodeHandle node; ArtificialPotentialField apf = ArtificialPotentialField(node); apf.spin(); return 0; } <commit_msg>improve debug message<commit_after>#include <ros/ros.h> #include <geometry_msgs/Twist.h> #include <sensor_msgs/PointCloud.h> #include <math.h> static const float tol = 0.000000000000001f; double magnitude(double vec[3]){ return sqrt(vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]); } void normalize(double vec[3]){ float m = magnitude(vec); if(tol <= m) m = 1; vec[0] /= m; vec[1] /= m; vec[2] /= m; if(fabs(vec[0]) < tol) vec[0] = 0.0f; if(fabs(vec[1]) < tol) vec[1] = 0.0f; if(fabs(vec[2]) < tol) vec[2] = 0.0f; } class ArtificialPotentialField{ public: ArtificialPotentialField(ros::NodeHandle &node) : cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)), obs_sub_(node.subscribe("slam_cloud", 10, &ArtificialPotentialField::obstacleCallback, this)) { for(int i=0; i < 3; i++) obs_[i] = 0; } void spin(){ ros::Rate r(10); ros::Duration(1).sleep(); geometry_msgs::Twist cmd; cmd.linear.z = 0.15; cmd_pub_.publish(cmd); ros::Duration(3).sleep(); cmd.linear.z = 0; cmd_pub_.publish(cmd); ros::Duration(3).sleep(); const double A = 0; const double B = 3; const double n = 1; const double m = 1.5; const double force = 0.025; while(ros::ok()){ double Fs[3]; Fs[0] = Fs[1] = Fs[2] = 0; double u[3]; u[0] = obs_[0]; u[1] = obs_[1]; u[2] = obs_[2]; normalize(u); const double d = magnitude(obs_); double U = -A/pow(d, n) + B/pow(d, m); Fs[0] += U * u[0]; Fs[1] += U * u[1]; Fs[2] += U * u[2]; cmd.linear.x = Fs[0] * force; cmd.linear.y = Fs[1] * force; //ROS_INFO_STREAM("cmd = " << cmd); cmd_pub_.publish(cmd); r.sleep(); } } private: void obstacleCallback(const sensor_msgs::PointCloud &obs_msg){ double min_obs[3]; min_obs[0] = obs_msg.points[0].x; min_obs[1] = obs_msg.points[0].y; min_obs[2] = obs_msg.points[0].z; float min_dist = magnitude(min_obs); ROS_INFO_STREAM("size = " << obs_msg.channels.size()); for(int i=1; i < obs_msg.channels.size(); i++){ double obs[3]; obs[0] = obs_msg.points[i].x; obs[1] = obs_msg.points[i].y; obs[2] = obs_msg.points[i].z; double dist = magnitude(obs); if(dist < min_dist){ min_obs[0] = obs[0]; min_obs[1] = obs[1]; min_obs[2] = obs[2]; min_dist = dist; } } obs_[0] = min_obs[0]; obs_[1] = min_obs[1]; obs_[2] = min_obs[2]; } double obs_[3]; ros::Publisher cmd_pub_; ros::Subscriber obs_sub_; }; int main(int argc, char *argv[]){ ros::init(argc, argv, "obstacle_avoidance"); ros::NodeHandle node; ArtificialPotentialField apf = ArtificialPotentialField(node); apf.spin(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "net/test/test_server.h" namespace { // Used to block until a dev tools client window's browser is closed. class BrowserClosedObserver : public NotificationObserver { public: explicit BrowserClosedObserver(Browser* browser) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(browser)); ui_test_utils::RunMessageLoop(); } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { MessageLoopForUI::current()->Quit(); } private: NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver); }; // The delay waited in some cases where we don't have a notifications for an // action we take. const int kActionDelayMs = 500; const char kConsoleTestPage[] = "files/devtools/console_test_page.html"; const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html"; const char kJsPage[] = "files/devtools/js_page.html"; const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html"; const char kPauseOnExceptionTestPage[] = "files/devtools/pause_on_exception.html"; const char kPauseWhenLoadingDevTools[] = "files/devtools/pause_when_loading_devtools.html"; const char kPauseWhenScriptIsRunning[] = "files/devtools/pause_when_script_is_running.html"; const char kResourceContentLengthTestPage[] = "files/devtools/image.html"; const char kResourceTestPage[] = "files/devtools/resource_test_page.html"; const char kSimplePage[] = "files/devtools/simple_page.html"; const char kSyntaxErrorTestPage[] = "files/devtools/script_syntax_error.html"; const char kDebuggerClosurePage[] = "files/devtools/debugger_closure.html"; const char kCompletionOnPause[] = "files/devtools/completion_on_pause.html"; const char kPageWithContentScript[] = "files/devtools/page_with_content_script.html"; class DevToolsSanityTest : public InProcessBrowserTest { public: DevToolsSanityTest() { set_show_window(true); EnableDOMAutomation(); } protected: void RunTest(const std::string& test_name, const std::string& test_page) { OpenDevToolsWindow(test_page); std::string result; // At first check that JavaScript part of the front-end is loaded by // checking that global variable uiTests exists(it's created after all js // files have been loaded) and has runTest method. ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", L"window.domAutomationController.send(" L"'' + (window.uiTests && (typeof uiTests.runTest)));", &result)); if (result == "function") { ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", UTF8ToWide(StringPrintf("uiTests.runTest('%s')", test_name.c_str())), &result)); EXPECT_EQ("[OK]", result); } else { FAIL() << "DevTools front-end is broken."; } CloseDevToolsWindow(); } void OpenDevToolsWindow(const std::string& test_page) { ASSERT_TRUE(test_server()->Start()); GURL url = test_server()->GetURL(test_page); ui_test_utils::NavigateToURL(browser(), url); inspected_rvh_ = GetInspectedTab()->render_view_host(); DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->OpenDevToolsWindow(inspected_rvh_); DevToolsClientHost* client_host = devtools_manager->GetDevToolsClientHostFor(inspected_rvh_); window_ = client_host->AsDevToolsWindow(); RenderViewHost* client_rvh = window_->GetRenderViewHost(); client_contents_ = client_rvh->delegate()->GetAsTabContents(); ui_test_utils::WaitForNavigation(&client_contents_->controller()); } TabContents* GetInspectedTab() { return browser()->GetTabContentsAt(0); } void CloseDevToolsWindow() { DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); // UnregisterDevToolsClientHostFor may destroy window_ so store the browser // first. Browser* browser = window_->browser(); devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_); // Wait only when DevToolsWindow has a browser. For docked DevTools, this // is NULL and we skip the wait. if (browser) BrowserClosedObserver close_observer(browser); } TabContents* client_contents_; DevToolsWindow* window_; RenderViewHost* inspected_rvh_; }; class CancelableQuitTask : public Task { public: explicit CancelableQuitTask(const std::string& timeout_message) : timeout_message_(timeout_message), cancelled_(false) { } void cancel() { cancelled_ = true; } virtual void Run() { if (cancelled_) { return; } FAIL() << timeout_message_; MessageLoop::current()->Quit(); } private: std::string timeout_message_; bool cancelled_; }; // Base class for DevTools tests that test devtools functionality for // extensions and content scripts. class DevToolsExtensionDebugTest : public DevToolsSanityTest, public NotificationObserver { public: DevToolsExtensionDebugTest() : DevToolsSanityTest() { PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_); test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools"); test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions"); } protected: // Load an extention from test\data\devtools\extensions\<extension_name> void LoadExtension(const char* extension_name) { FilePath path = test_extensions_dir_.AppendASCII(extension_name); ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension."; } private: bool LoadExtensionFromPath(const FilePath& path) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); size_t num_before = service->extensions()->size(); { NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_LOADED, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); service->LoadExtension(path); ui_test_utils::RunMessageLoop(); delayed_quit->cancel(); } size_t num_after = service->extensions()->size(); if (num_after != (num_before + 1)) return false; return WaitForExtensionHostsToLoad(); } bool WaitForExtensionHostsToLoad() { // Wait for all the extension hosts that exist to finish loading. // NOTE: This assumes that the extension host list is not changing while // this method is running. NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension host load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); ExtensionProcessManager* manager = browser()->profile()->GetExtensionProcessManager(); for (ExtensionProcessManager::const_iterator iter = manager->begin(); iter != manager->end();) { if ((*iter)->did_stop_loading()) ++iter; else ui_test_utils::RunMessageLoop(); } delayed_quit->cancel(); return true; } void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::EXTENSION_LOADED: case NotificationType::EXTENSION_HOST_DID_STOP_LOADING: MessageLoopForUI::current()->Quit(); break; default: NOTREACHED(); break; } } FilePath test_extensions_dir_; }; // WebInspector opens. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) { RunTest("testHostIsPresent", kSimplePage); } // Tests elements panel basics. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) { RunTest("testElementsTreeRoot", kSimplePage); } // Tests main resource load. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) { RunTest("testMainResource", kSimplePage); } // Tests resources panel enabling. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) { RunTest("testEnableResourcesTab", kSimplePage); } // Fails after WebKit roll 59365:59477, http://crbug.com/44202. #if defined(OS_LINUX) #define MAYBE_TestResourceContentLength FLAKY_TestResourceContentLength #else #define MAYBE_TestResourceContentLength TestResourceContentLength #endif // defined(OS_LINUX) // Tests resources have correct sizes. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestResourceContentLength) { RunTest("testResourceContentLength", kResourceContentLengthTestPage); } // Tests resource headers. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) { RunTest("testResourceHeaders", kResourceTestPage); } // Tests cached resource mime type. // @see http://crbug.com/27364 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCachedResourceMimeType) { RunTest("testCachedResourceMimeType", kResourceTestPage); } // Tests profiler panel. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) { RunTest("testProfilerTab", kJsPage); } // Tests heap profiler. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) { RunTest("testHeapProfiler", kHeapProfilerPage); } // Tests scripts panel showing. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) { RunTest("testShowScriptsTab", kDebuggerTestPage); } // Tests that scripts tab is populated with inspected scripts even if it // hadn't been shown by the moment inspected paged refreshed. // @see http://crbug.com/26312 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestScriptsTabIsPopulatedOnInspectedPageRefresh) { // Clear inspector settings to ensure that Elements will be // current panel when DevTools window is open. GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings(); RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh", kDebuggerTestPage); } // Tests that a content script is in the scripts list. // This test is disabled, see bug 28961. IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest, TestContentScriptIsPresent) { LoadExtension("simple_content_script"); RunTest("testContentScriptIsPresent", kPageWithContentScript); } // Tests that scripts are not duplicated after Scripts Panel switch. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNoScriptDuplicatesOnPanelSwitch) { RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage); } // Tests set breakpoint. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) { RunTest("testSetBreakpoint", kDebuggerTestPage); } // Tests pause on exception. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseOnException) { RunTest("testPauseOnException", kPauseOnExceptionTestPage); } // Tests that debugger works correctly if pause event occurs when DevTools // frontend is being loaded. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) { RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools); } // Tests that pressing 'Pause' will pause script execution if the script // is already running. // The test fails on linux and should be related to Webkit patch // http://trac.webkit.org/changeset/64124/trunk. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) { RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning); } // Tests eval on call frame. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalOnCallFrame) { RunTest("testEvalOnCallFrame", kDebuggerTestPage); } // Tests that scope can be expanded and contains expected variables. // TODO(japhet): Disabled during webkit landing per bug http://crbug.com/52085 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestExpandScope) { RunTest("testExpandScope", kDebuggerClosurePage); } // Tests that execution continues automatically when there is a syntax error in // script and DevTools are open. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestAutoContinueOnSyntaxError) { RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage); } IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCompletionOnPause) { RunTest("testCompletionOnPause", kCompletionOnPause); } // Tests that 'Pause' button works for eval. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) { RunTest("testPauseInEval", kDebuggerTestPage); } // Test that Storage panel can be shown. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowStoragePanel) { RunTest("testShowStoragePanel", kDebuggerTestPage); } IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMessageLoopReentrant) { RunTest("testMessageLoopReentrant", kDebuggerTestPage); } } // namespace <commit_msg>DevTools: remove tests that have been converted into layout tests<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "net/test/test_server.h" namespace { // Used to block until a dev tools client window's browser is closed. class BrowserClosedObserver : public NotificationObserver { public: explicit BrowserClosedObserver(Browser* browser) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(browser)); ui_test_utils::RunMessageLoop(); } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { MessageLoopForUI::current()->Quit(); } private: NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver); }; // The delay waited in some cases where we don't have a notifications for an // action we take. const int kActionDelayMs = 500; const char kConsoleTestPage[] = "files/devtools/console_test_page.html"; const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html"; const char kJsPage[] = "files/devtools/js_page.html"; const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html"; const char kPauseOnExceptionTestPage[] = "files/devtools/pause_on_exception.html"; const char kPauseWhenLoadingDevTools[] = "files/devtools/pause_when_loading_devtools.html"; const char kPauseWhenScriptIsRunning[] = "files/devtools/pause_when_script_is_running.html"; const char kResourceContentLengthTestPage[] = "files/devtools/image.html"; const char kResourceTestPage[] = "files/devtools/resource_test_page.html"; const char kSimplePage[] = "files/devtools/simple_page.html"; const char kSyntaxErrorTestPage[] = "files/devtools/script_syntax_error.html"; const char kDebuggerClosurePage[] = "files/devtools/debugger_closure.html"; const char kCompletionOnPause[] = "files/devtools/completion_on_pause.html"; const char kPageWithContentScript[] = "files/devtools/page_with_content_script.html"; class DevToolsSanityTest : public InProcessBrowserTest { public: DevToolsSanityTest() { set_show_window(true); EnableDOMAutomation(); } protected: void RunTest(const std::string& test_name, const std::string& test_page) { OpenDevToolsWindow(test_page); std::string result; // At first check that JavaScript part of the front-end is loaded by // checking that global variable uiTests exists(it's created after all js // files have been loaded) and has runTest method. ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", L"window.domAutomationController.send(" L"'' + (window.uiTests && (typeof uiTests.runTest)));", &result)); if (result == "function") { ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", UTF8ToWide(StringPrintf("uiTests.runTest('%s')", test_name.c_str())), &result)); EXPECT_EQ("[OK]", result); } else { FAIL() << "DevTools front-end is broken."; } CloseDevToolsWindow(); } void OpenDevToolsWindow(const std::string& test_page) { ASSERT_TRUE(test_server()->Start()); GURL url = test_server()->GetURL(test_page); ui_test_utils::NavigateToURL(browser(), url); inspected_rvh_ = GetInspectedTab()->render_view_host(); DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->OpenDevToolsWindow(inspected_rvh_); DevToolsClientHost* client_host = devtools_manager->GetDevToolsClientHostFor(inspected_rvh_); window_ = client_host->AsDevToolsWindow(); RenderViewHost* client_rvh = window_->GetRenderViewHost(); client_contents_ = client_rvh->delegate()->GetAsTabContents(); ui_test_utils::WaitForNavigation(&client_contents_->controller()); } TabContents* GetInspectedTab() { return browser()->GetTabContentsAt(0); } void CloseDevToolsWindow() { DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); // UnregisterDevToolsClientHostFor may destroy window_ so store the browser // first. Browser* browser = window_->browser(); devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_); // Wait only when DevToolsWindow has a browser. For docked DevTools, this // is NULL and we skip the wait. if (browser) BrowserClosedObserver close_observer(browser); } TabContents* client_contents_; DevToolsWindow* window_; RenderViewHost* inspected_rvh_; }; class CancelableQuitTask : public Task { public: explicit CancelableQuitTask(const std::string& timeout_message) : timeout_message_(timeout_message), cancelled_(false) { } void cancel() { cancelled_ = true; } virtual void Run() { if (cancelled_) { return; } FAIL() << timeout_message_; MessageLoop::current()->Quit(); } private: std::string timeout_message_; bool cancelled_; }; // Base class for DevTools tests that test devtools functionality for // extensions and content scripts. class DevToolsExtensionDebugTest : public DevToolsSanityTest, public NotificationObserver { public: DevToolsExtensionDebugTest() : DevToolsSanityTest() { PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_); test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools"); test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions"); } protected: // Load an extention from test\data\devtools\extensions\<extension_name> void LoadExtension(const char* extension_name) { FilePath path = test_extensions_dir_.AppendASCII(extension_name); ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension."; } private: bool LoadExtensionFromPath(const FilePath& path) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); size_t num_before = service->extensions()->size(); { NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_LOADED, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); service->LoadExtension(path); ui_test_utils::RunMessageLoop(); delayed_quit->cancel(); } size_t num_after = service->extensions()->size(); if (num_after != (num_before + 1)) return false; return WaitForExtensionHostsToLoad(); } bool WaitForExtensionHostsToLoad() { // Wait for all the extension hosts that exist to finish loading. // NOTE: This assumes that the extension host list is not changing while // this method is running. NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension host load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); ExtensionProcessManager* manager = browser()->profile()->GetExtensionProcessManager(); for (ExtensionProcessManager::const_iterator iter = manager->begin(); iter != manager->end();) { if ((*iter)->did_stop_loading()) ++iter; else ui_test_utils::RunMessageLoop(); } delayed_quit->cancel(); return true; } void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::EXTENSION_LOADED: case NotificationType::EXTENSION_HOST_DID_STOP_LOADING: MessageLoopForUI::current()->Quit(); break; default: NOTREACHED(); break; } } FilePath test_extensions_dir_; }; // WebInspector opens. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) { RunTest("testHostIsPresent", kSimplePage); } // Tests resources panel enabling. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) { RunTest("testEnableResourcesTab", kSimplePage); } // Fails after WebKit roll 59365:59477, http://crbug.com/44202. #if defined(OS_LINUX) #define MAYBE_TestResourceContentLength FLAKY_TestResourceContentLength #else #define MAYBE_TestResourceContentLength TestResourceContentLength #endif // defined(OS_LINUX) // Tests resources have correct sizes. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestResourceContentLength) { RunTest("testResourceContentLength", kResourceContentLengthTestPage); } // Tests resource headers. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) { RunTest("testResourceHeaders", kResourceTestPage); } // Tests cached resource mime type. // @see http://crbug.com/27364 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCachedResourceMimeType) { RunTest("testCachedResourceMimeType", kResourceTestPage); } // Tests profiler panel. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) { RunTest("testProfilerTab", kJsPage); } // Tests heap profiler. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) { RunTest("testHeapProfiler", kHeapProfilerPage); } // Tests scripts panel showing. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) { RunTest("testShowScriptsTab", kDebuggerTestPage); } // Tests that scripts tab is populated with inspected scripts even if it // hadn't been shown by the moment inspected paged refreshed. // @see http://crbug.com/26312 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestScriptsTabIsPopulatedOnInspectedPageRefresh) { // Clear inspector settings to ensure that Elements will be // current panel when DevTools window is open. GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings(); RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh", kDebuggerTestPage); } // Tests that a content script is in the scripts list. // This test is disabled, see bug 28961. IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest, TestContentScriptIsPresent) { LoadExtension("simple_content_script"); RunTest("testContentScriptIsPresent", kPageWithContentScript); } // Tests that scripts are not duplicated after Scripts Panel switch. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNoScriptDuplicatesOnPanelSwitch) { RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage); } // Tests set breakpoint. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) { RunTest("testSetBreakpoint", kDebuggerTestPage); } // Tests pause on exception. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseOnException) { RunTest("testPauseOnException", kPauseOnExceptionTestPage); } // Tests that debugger works correctly if pause event occurs when DevTools // frontend is being loaded. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) { RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools); } // Tests that pressing 'Pause' will pause script execution if the script // is already running. // The test fails on linux and should be related to Webkit patch // http://trac.webkit.org/changeset/64124/trunk. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) { RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning); } // Tests eval on call frame. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalOnCallFrame) { RunTest("testEvalOnCallFrame", kDebuggerTestPage); } // Tests that scope can be expanded and contains expected variables. // TODO(japhet): Disabled during webkit landing per bug http://crbug.com/52085 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestExpandScope) { RunTest("testExpandScope", kDebuggerClosurePage); } // Tests that execution continues automatically when there is a syntax error in // script and DevTools are open. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestAutoContinueOnSyntaxError) { RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage); } IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCompletionOnPause) { RunTest("testCompletionOnPause", kCompletionOnPause); } // Tests that 'Pause' button works for eval. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) { RunTest("testPauseInEval", kDebuggerTestPage); } // Test that Storage panel can be shown. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowStoragePanel) { RunTest("testShowStoragePanel", kDebuggerTestPage); } IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMessageLoopReentrant) { RunTest("testMessageLoopReentrant", kDebuggerTestPage); } } // namespace <|endoftext|>
<commit_before>#include "builtin/block_environment.hpp" #include "builtin/class.hpp" #include "builtin/compiledmethod.hpp" #include "builtin/fixnum.hpp" #include "builtin/lookuptable.hpp" #include "builtin/tuple.hpp" #include "gc_object_mark.hpp" #include "objectmemory.hpp" #include "vm/object_utils.hpp" #include "builtin/contexts.hpp" #include "builtin/nativemethodcontext.hpp" #include <iostream> namespace rubinius { void MethodContext::init(STATE) { GO(methctx).set(state->new_class("MethodContext", G(object))); G(methctx)->set_object_type(state, MethodContextType); GO(blokctx).set(state->new_class("BlockContext", G(methctx))); G(blokctx)->set_object_type(state, BlockContextType); } /* Initialize +ctx+'s fields */ static inline void init_context(STATE, MethodContext* ctx, size_t stack) { ctx->StoresBytes = 1; ctx->ip = 0; ctx->native_ip = 0; ctx->current_unwind = 0; ctx->ivars(state, Qnil); // Do this here because it's possible for us to pass a context // around and it could leak out before the real sender is set. ctx->sender(state, (MethodContext*)Qnil); // Don't initialize any fields you KNOW are always set later // on before the ctx is used. We just waste precious time if we do. ctx->stack_size = stack; for(size_t i = 0; i < stack; i++) { ctx->stk[i] = Qnil; } ctx->js.stack = ctx->stk - 1; ctx->js.stack_top = (ctx->stk + stack - 1); } /* Find a context to use. Either use a cache or create one in the heap. */ template <class T> static inline T* allocate(STATE, Class* cls, size_t stack_size) { T* ctx; ctx = reinterpret_cast<T*>(state->om->allocate_context(stack_size)); if(ctx) { assert((uintptr_t)ctx + ctx->full_size < (uintptr_t)state->om->contexts.last); ctx->klass(state, (Class*)Qnil); ctx->obj_type = T::type; } else { // We're going to end up referencing a stack context from a heap // context, so we need to be sure all stack contexts stick around! state->om->clamp_contexts(); ctx = state->new_struct<T>(cls, stack_size * sizeof(Object*)); } init_context(state, ctx, stack_size); return ctx; } int MethodContext::line(STATE) { if(cm_->nil_p()) return -2; // trampoline context if(cm_->lines()->nil_p()) return -3; for(size_t i = 0; i < cm_->lines()->num_fields(); i++) { Tuple* entry = as<Tuple>(cm_->lines()->at(state, i)); Fixnum* start_ip = as<Fixnum>(entry->at(state, 0)); Fixnum* end_ip = as<Fixnum>(entry->at(state, 1)); Fixnum* line = as<Fixnum>(entry->at(state, 2)); if(start_ip->to_native() <= ip && end_ip->to_native() >= ip) return line->to_native(); } return -1; } void MethodContext::post_copy(MethodContext* old) { this->js.stack_top = this->stk + (this->stack_size - 1); this->position_stack(old->calculate_sp()); if(this->obj_type == MethodContextType) { assert(this->home() == old->home()); } } /* Attempt to recycle +this+ context into the context cache, based * on it's size. Returns true if the context was recycled, otherwise * false. */ bool MethodContext::recycle(STATE) { if(zone != YoungObjectZone) return false; return state->om->deallocate_context(this); } /* Create a ContextCache object and install it in +state+ */ void MethodContext::initialize_cache(STATE) { } /* Zero out the caches. */ void MethodContext::reset_cache(STATE) { state->om->clamp_contexts(); } /* Return a new +MethodContext+ object, which needs +stack_size fields * worth of stack. */ MethodContext* MethodContext::create(STATE, size_t stack_size) { return allocate<MethodContext>(state, G(methctx), stack_size); } /* Generate a MethodContext for the provided receiver and CompiledMethod * The returned MethodContext is in an 'initial' state. The caller is * expected to SET any fields it needs to, e.g. +module+ */ MethodContext* MethodContext::create(STATE, Object* recv, CompiledMethod* meth) { size_t stack_size = meth->backend_method_->stack_size; MethodContext* ctx = state->om->allocate_context(stack_size); if(likely(ctx)) { ctx->klass_ = (Class*)Qnil; ctx->obj_type = MethodContextType; ctx->self_ = recv; ctx->cm_ = meth; ctx->home_ = ctx; } else { // We're going to end up referencing a stack context from a heap // context, so we need to be sure all stack contexts stick around! state->om->clamp_contexts(); ctx = state->new_struct<MethodContext>(G(methctx), stack_size * sizeof(Object*)); ctx->self(state, recv); ctx->cm(state, meth); ctx->home(state, ctx); } init_context(state, ctx, stack_size); ctx->vmm = meth->backend_method_; // nil out just where the locals are native_int locals = ctx->vmm->number_of_locals; ctx->position_stack(locals - 1); return ctx; } /* Called as the context_dup primitive */ MethodContext* MethodContext::dup(STATE) { MethodContext* ctx = create(state, this->stack_size); /* This ctx is escaping into Ruby-land */ ctx->reference(state); ctx->sender(state, this->sender()); ctx->self(state, this->self()); ctx->cm(state, this->cm()); ctx->module(state, this->module()); ctx->block(state, this->block()); ctx->name(state, this->name()); ctx->home(state, this->home()); this->home()->reference(state); // so that the closure won't be deallocated. /* Set the obj_type because we get called * for both BlockContext and MethodContext */ ctx->obj_type = this->obj_type; ctx->vmm = this->vmm; ctx->js = this->js; ctx->ip = this->ip; ctx->args = this->args; ctx->stack_size = this->stack_size; ctx->full_size = this->full_size; ctx->current_unwind = this->current_unwind; for(int i = 0; i < this->current_unwind; i++) { ctx->unwinds[i] = this->unwinds[i]; } for(size_t i = 0; i < this->stack_size; i++) { ctx->stk[i] = this->stk[i]; } ctx->js.stack_top = ctx->stk + (ctx->stack_size - 1); ctx->position_stack(this->calculate_sp()); /* Stack Management procedures. Make sure that we don't * miss object stored into the stack of a context */ if(ctx->zone == MatureObjectZone) { state->om->remember_object(ctx); } return ctx; } MethodContext* MethodContext::dup_chain(STATE) { LookupTable* map = LookupTable::create(state); MethodContext* ret = this->dup(state); for(MethodContext* ctx = ret; !ctx->sender()->nil_p(); ctx = ctx->sender()) { MethodContext* old_sender = ctx->sender(); ctx->sender(state, old_sender->dup(state)); if(old_sender->obj_type == MethodContextType) { map->store(state, old_sender, ctx->sender()); } } for(MethodContext* ctx = ret; !ctx->sender()->nil_p(); ctx = ctx->sender()) { if(ctx->obj_type == BlockContextType) { BlockEnvironment* old_env = as<BlockContext>(ctx)->env(); Object* new_env_home = map->aref(state, (old_env->home())); if(new_env_home->nil_p()) continue; BlockEnvironment* new_env = old_env->dup(state); new_env->home(state, as<MethodContext>(new_env_home)); ctx->block(state, new_env); } } for(MethodContext* ctx = this; !ctx->sender()->nil_p(); ctx = ctx->sender()) { if(ctx->obj_type == MethodContextType) { map->remove(state, ctx); } } return ret; } /* Retrieve the BlockEnvironment from +this+ BlockContext. We reuse the * block field from MethodContext and use a type-safe cast. */ BlockEnvironment* BlockContext::env() { return as<BlockEnvironment>(block()); } /* Called as the block_context_env primitive */ BlockEnvironment* BlockContext::env(STATE) { return this->env(); } /* Lazy initialize fields that might have been left uninitialized * when +this+ was only used in the context cache. */ void MethodContext::initialize_as_reference(STATE) { switch(obj_type) { case MethodContext::type: this->klass(state, G(methctx)); break; case BlockContext::type: this->klass(state, G(blokctx)); break; case NativeMethodContext::type: break; default: abort(); } } /* Called when a context is referenced. Typically, this is via the push_context * opcode or MethodContext#sender. */ void MethodContext::reference(STATE) { state->om->reference_context(this); initialize_as_reference(state); } /* Retrieve a field within the context, referenced by name. This * is used as a primitive. */ Object* MethodContext::get_internal_data(STATE, Fixnum* type) { switch(type->to_native()) { case 1: return Fixnum::from(ip); case 2: return Fixnum::from(calculate_sp()); case 3: if(native_ip == 0) { return Qnil; } else { return Integer::from(state, reinterpret_cast<uintptr_t>(native_ip)); } } sassert(0 && "invalid index"); return Qnil; } Array* MethodContext::locals(STATE) { int n = this->vmm->number_of_locals; Array* ary = Array::create(state, n); for(int i = 0; i < n; i++) { ary->set(state, i, this->get_local(i)); } return ary; } /* Return a new +BlockContext+ object, which needs +stack_size+ fields * worth of stack. */ BlockContext* BlockContext::create(STATE, size_t stack_size) { BlockContext* ctx = allocate<BlockContext>(state, G(blokctx), stack_size); ctx->block(state, Qnil); ctx->cm(state, reinterpret_cast<CompiledMethod*>(Qnil)); ctx->home(state, reinterpret_cast<MethodContext*>(Qnil)); ctx->module(state, reinterpret_cast<Module*>(Qnil)); ctx->name(state, Qnil); ctx->self(state, Qnil); ctx->sender(state, reinterpret_cast<MethodContext*>(Qnil)); return ctx; } void MethodContext::Info::mark(Object* obj, ObjectMark& mark) { MethodContext* ctx = as<MethodContext>(obj); // Detect a context on the special context stack and fix it up. if(ctx->klass_->nil_p()) { ctx->initialize_as_reference(state()); } // FIXME this is to help detect an ellusive bug if(!ctx->sender()->nil_p() && (ctx->sender()->zone == UnspecifiedZone || !ctx->sender()->StoresBytes)) { MethodContext* s = ctx->sender(); std::cout << "Corrupt context detected!\n"; std::cout << "origin = " << obj << "\n"; std::cout << "object = " << s << "\n"; std::cout << "full_size = " << s->full_size << "\n"; std::cout << "klass = " << s->klass_ << "\n"; ObjectPosition pos = mark.gc->object_memory->validate_object(ctx->sender()); if(pos == cContextStack) { Assertion::raise("A sender on the context stack has an UnspecifiedZone"); } else if(pos == cUnknown){ Assertion::raise("A sender in unknown memory has an UnspecifiedZone"); } else { Assertion::raise("A sender in normal heap has an UnspecifiedZone"); } } // MethodContext's need to be inspected on every GC collection, young // and old. This is because we perform stores into the MethodContext's // stack without running the write barrier. So if the context is // in mature, we remember it. if(!ctx->young_object_p()) { mark.gc->object_memory->remember_object(ctx); } auto_mark(obj, mark); /* Now also mark the stack */ for(size_t i = 0; i < ctx->stack_size; i++) { Object* stack_obj = ctx->stack_at(i); if(!stack_obj) continue; Object* marked = mark.call(stack_obj); if(marked) { ctx->stack_put(i, marked); mark.just_set(ctx, marked); } } } void MethodContext::Info::show(STATE, Object* self, int level) { MethodContext* ctx = as<MethodContext>(self); class_header(state, self); indent_attribute(++level, "name"); ctx->name()->show(state, level); indent_attribute(level, "sp"); std::cout << ctx->calculate_sp() << "\n"; indent_attribute(level, "ip"); std::cout << ctx->ip << "\n"; indent_attribute(level, "sender"); if(ctx->sender()->nil_p()) { ctx->sender()->show(state, level); } else { if(ctx->sender()->klass()->nil_p()) { std::cout << "<stack context:" << (void*)ctx->sender() << ">\n"; } else { class_info(state, ctx->sender(), true); } } indent_attribute(level, "home"); if(ctx->home()->nil_p()) { ctx->home()->show(state, level); } else { class_info(state, ctx->home(), true); } indent_attribute(level, "self"); ctx->self()->show(state, level); indent_attribute(level, "cm"); ctx->cm()->show(state, level); indent_attribute(level, "module"); ctx->module()->show(state, level); indent_attribute(level, "block"); ctx->block()->show(state, level); close_body(level); } } <commit_msg>Sets elements after sp in the stack to nil to prevent memory leak.<commit_after>#include "builtin/block_environment.hpp" #include "builtin/class.hpp" #include "builtin/compiledmethod.hpp" #include "builtin/fixnum.hpp" #include "builtin/lookuptable.hpp" #include "builtin/tuple.hpp" #include "gc_object_mark.hpp" #include "objectmemory.hpp" #include "vm/object_utils.hpp" #include "builtin/contexts.hpp" #include "builtin/nativemethodcontext.hpp" #include <iostream> namespace rubinius { void MethodContext::init(STATE) { GO(methctx).set(state->new_class("MethodContext", G(object))); G(methctx)->set_object_type(state, MethodContextType); GO(blokctx).set(state->new_class("BlockContext", G(methctx))); G(blokctx)->set_object_type(state, BlockContextType); } /* Initialize +ctx+'s fields */ static inline void init_context(STATE, MethodContext* ctx, size_t stack) { ctx->StoresBytes = 1; ctx->ip = 0; ctx->native_ip = 0; ctx->current_unwind = 0; ctx->ivars(state, Qnil); // Do this here because it's possible for us to pass a context // around and it could leak out before the real sender is set. ctx->sender(state, (MethodContext*)Qnil); // Don't initialize any fields you KNOW are always set later // on before the ctx is used. We just waste precious time if we do. ctx->stack_size = stack; for(size_t i = 0; i < stack; i++) { ctx->stk[i] = Qnil; } ctx->js.stack = ctx->stk - 1; ctx->js.stack_top = (ctx->stk + stack - 1); } /* Find a context to use. Either use a cache or create one in the heap. */ template <class T> static inline T* allocate(STATE, Class* cls, size_t stack_size) { T* ctx; ctx = reinterpret_cast<T*>(state->om->allocate_context(stack_size)); if(ctx) { assert((uintptr_t)ctx + ctx->full_size < (uintptr_t)state->om->contexts.last); ctx->klass(state, (Class*)Qnil); ctx->obj_type = T::type; } else { // We're going to end up referencing a stack context from a heap // context, so we need to be sure all stack contexts stick around! state->om->clamp_contexts(); ctx = state->new_struct<T>(cls, stack_size * sizeof(Object*)); } init_context(state, ctx, stack_size); return ctx; } int MethodContext::line(STATE) { if(cm_->nil_p()) return -2; // trampoline context if(cm_->lines()->nil_p()) return -3; for(size_t i = 0; i < cm_->lines()->num_fields(); i++) { Tuple* entry = as<Tuple>(cm_->lines()->at(state, i)); Fixnum* start_ip = as<Fixnum>(entry->at(state, 0)); Fixnum* end_ip = as<Fixnum>(entry->at(state, 1)); Fixnum* line = as<Fixnum>(entry->at(state, 2)); if(start_ip->to_native() <= ip && end_ip->to_native() >= ip) return line->to_native(); } return -1; } void MethodContext::post_copy(MethodContext* old) { this->js.stack_top = this->stk + (this->stack_size - 1); this->position_stack(old->calculate_sp()); if(this->obj_type == MethodContextType) { assert(this->home() == old->home()); } } /* Attempt to recycle +this+ context into the context cache, based * on it's size. Returns true if the context was recycled, otherwise * false. */ bool MethodContext::recycle(STATE) { if(zone != YoungObjectZone) return false; return state->om->deallocate_context(this); } /* Create a ContextCache object and install it in +state+ */ void MethodContext::initialize_cache(STATE) { } /* Zero out the caches. */ void MethodContext::reset_cache(STATE) { state->om->clamp_contexts(); } /* Return a new +MethodContext+ object, which needs +stack_size fields * worth of stack. */ MethodContext* MethodContext::create(STATE, size_t stack_size) { return allocate<MethodContext>(state, G(methctx), stack_size); } /* Generate a MethodContext for the provided receiver and CompiledMethod * The returned MethodContext is in an 'initial' state. The caller is * expected to SET any fields it needs to, e.g. +module+ */ MethodContext* MethodContext::create(STATE, Object* recv, CompiledMethod* meth) { size_t stack_size = meth->backend_method_->stack_size; MethodContext* ctx = state->om->allocate_context(stack_size); if(likely(ctx)) { ctx->klass_ = (Class*)Qnil; ctx->obj_type = MethodContextType; ctx->self_ = recv; ctx->cm_ = meth; ctx->home_ = ctx; } else { // We're going to end up referencing a stack context from a heap // context, so we need to be sure all stack contexts stick around! state->om->clamp_contexts(); ctx = state->new_struct<MethodContext>(G(methctx), stack_size * sizeof(Object*)); ctx->self(state, recv); ctx->cm(state, meth); ctx->home(state, ctx); } init_context(state, ctx, stack_size); ctx->vmm = meth->backend_method_; // nil out just where the locals are native_int locals = ctx->vmm->number_of_locals; ctx->position_stack(locals - 1); return ctx; } /* Called as the context_dup primitive */ MethodContext* MethodContext::dup(STATE) { MethodContext* ctx = create(state, this->stack_size); /* This ctx is escaping into Ruby-land */ ctx->reference(state); ctx->sender(state, this->sender()); ctx->self(state, this->self()); ctx->cm(state, this->cm()); ctx->module(state, this->module()); ctx->block(state, this->block()); ctx->name(state, this->name()); ctx->home(state, this->home()); this->home()->reference(state); // so that the closure won't be deallocated. /* Set the obj_type because we get called * for both BlockContext and MethodContext */ ctx->obj_type = this->obj_type; ctx->vmm = this->vmm; ctx->js = this->js; ctx->ip = this->ip; ctx->args = this->args; ctx->stack_size = this->stack_size; ctx->full_size = this->full_size; ctx->current_unwind = this->current_unwind; for(int i = 0; i < this->current_unwind; i++) { ctx->unwinds[i] = this->unwinds[i]; } for(size_t i = 0; i < this->stack_size; i++) { ctx->stk[i] = this->stk[i]; } ctx->js.stack_top = ctx->stk + (ctx->stack_size - 1); ctx->position_stack(this->calculate_sp()); /* Stack Management procedures. Make sure that we don't * miss object stored into the stack of a context */ if(ctx->zone == MatureObjectZone) { state->om->remember_object(ctx); } return ctx; } MethodContext* MethodContext::dup_chain(STATE) { LookupTable* map = LookupTable::create(state); MethodContext* ret = this->dup(state); for(MethodContext* ctx = ret; !ctx->sender()->nil_p(); ctx = ctx->sender()) { MethodContext* old_sender = ctx->sender(); ctx->sender(state, old_sender->dup(state)); if(old_sender->obj_type == MethodContextType) { map->store(state, old_sender, ctx->sender()); } } for(MethodContext* ctx = ret; !ctx->sender()->nil_p(); ctx = ctx->sender()) { if(ctx->obj_type == BlockContextType) { BlockEnvironment* old_env = as<BlockContext>(ctx)->env(); Object* new_env_home = map->aref(state, (old_env->home())); if(new_env_home->nil_p()) continue; BlockEnvironment* new_env = old_env->dup(state); new_env->home(state, as<MethodContext>(new_env_home)); ctx->block(state, new_env); } } for(MethodContext* ctx = this; !ctx->sender()->nil_p(); ctx = ctx->sender()) { if(ctx->obj_type == MethodContextType) { map->remove(state, ctx); } } return ret; } /* Retrieve the BlockEnvironment from +this+ BlockContext. We reuse the * block field from MethodContext and use a type-safe cast. */ BlockEnvironment* BlockContext::env() { return as<BlockEnvironment>(block()); } /* Called as the block_context_env primitive */ BlockEnvironment* BlockContext::env(STATE) { return this->env(); } /* Lazy initialize fields that might have been left uninitialized * when +this+ was only used in the context cache. */ void MethodContext::initialize_as_reference(STATE) { switch(obj_type) { case MethodContext::type: this->klass(state, G(methctx)); break; case BlockContext::type: this->klass(state, G(blokctx)); break; case NativeMethodContext::type: break; default: abort(); } } /* Called when a context is referenced. Typically, this is via the push_context * opcode or MethodContext#sender. */ void MethodContext::reference(STATE) { state->om->reference_context(this); initialize_as_reference(state); } /* Retrieve a field within the context, referenced by name. This * is used as a primitive. */ Object* MethodContext::get_internal_data(STATE, Fixnum* type) { switch(type->to_native()) { case 1: return Fixnum::from(ip); case 2: return Fixnum::from(calculate_sp()); case 3: if(native_ip == 0) { return Qnil; } else { return Integer::from(state, reinterpret_cast<uintptr_t>(native_ip)); } } sassert(0 && "invalid index"); return Qnil; } Array* MethodContext::locals(STATE) { int n = this->vmm->number_of_locals; Array* ary = Array::create(state, n); for(int i = 0; i < n; i++) { ary->set(state, i, this->get_local(i)); } return ary; } /* Return a new +BlockContext+ object, which needs +stack_size+ fields * worth of stack. */ BlockContext* BlockContext::create(STATE, size_t stack_size) { BlockContext* ctx = allocate<BlockContext>(state, G(blokctx), stack_size); ctx->block(state, Qnil); ctx->cm(state, reinterpret_cast<CompiledMethod*>(Qnil)); ctx->home(state, reinterpret_cast<MethodContext*>(Qnil)); ctx->module(state, reinterpret_cast<Module*>(Qnil)); ctx->name(state, Qnil); ctx->self(state, Qnil); ctx->sender(state, reinterpret_cast<MethodContext*>(Qnil)); return ctx; } void MethodContext::Info::mark(Object* obj, ObjectMark& mark) { MethodContext* ctx = as<MethodContext>(obj); // Detect a context on the special context stack and fix it up. if(ctx->klass_->nil_p()) { ctx->initialize_as_reference(state()); } // FIXME this is to help detect an ellusive bug if(!ctx->sender()->nil_p() && (ctx->sender()->zone == UnspecifiedZone || !ctx->sender()->StoresBytes)) { MethodContext* s = ctx->sender(); std::cout << "Corrupt context detected!\n"; std::cout << "origin = " << obj << "\n"; std::cout << "object = " << s << "\n"; std::cout << "full_size = " << s->full_size << "\n"; std::cout << "klass = " << s->klass_ << "\n"; ObjectPosition pos = mark.gc->object_memory->validate_object(ctx->sender()); if(pos == cContextStack) { Assertion::raise("A sender on the context stack has an UnspecifiedZone"); } else if(pos == cUnknown){ Assertion::raise("A sender in unknown memory has an UnspecifiedZone"); } else { Assertion::raise("A sender in normal heap has an UnspecifiedZone"); } } // MethodContext's need to be inspected on every GC collection, young // and old. This is because we perform stores into the MethodContext's // stack without running the write barrier. So if the context is // in mature, we remember it. if(!ctx->young_object_p()) { mark.gc->object_memory->remember_object(ctx); } auto_mark(obj, mark); /* Now also mark the stack. Set elements after sp to nil to prevent * memory leak */ int sp = ctx->calculate_sp(); if(sp < 0) { for(size_t i = 0; i < ctx->stack_size; i++) { ctx->stack_put(i, Qnil); } } else { size_t usp = sp; for(size_t i = 0; i <= usp; i++) { Object* stack_obj = ctx->stack_at(i); if(!stack_obj) continue; Object* marked = mark.call(stack_obj); if(marked) { ctx->stack_put(i, marked); mark.just_set(ctx, marked); } } for(size_t i = usp+1; i < ctx->stack_size; i++) { ctx->stack_put(i, Qnil); } } } void MethodContext::Info::show(STATE, Object* self, int level) { MethodContext* ctx = as<MethodContext>(self); class_header(state, self); indent_attribute(++level, "name"); ctx->name()->show(state, level); indent_attribute(level, "sp"); std::cout << ctx->calculate_sp() << "\n"; indent_attribute(level, "ip"); std::cout << ctx->ip << "\n"; indent_attribute(level, "sender"); if(ctx->sender()->nil_p()) { ctx->sender()->show(state, level); } else { if(ctx->sender()->klass()->nil_p()) { std::cout << "<stack context:" << (void*)ctx->sender() << ">\n"; } else { class_info(state, ctx->sender(), true); } } indent_attribute(level, "home"); if(ctx->home()->nil_p()) { ctx->home()->show(state, level); } else { class_info(state, ctx->home(), true); } indent_attribute(level, "self"); ctx->self()->show(state, level); indent_attribute(level, "cm"); ctx->cm()->show(state, level); indent_attribute(level, "module"); ctx->module()->show(state, level); indent_attribute(level, "block"); ctx->block()->show(state, level); close_body(level); } } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <geometry_msgs/Twist.h> #include <sensor_msgs/PointCloud.h> #include <math.h> static const float tol = 0.000000000000001f; double magnitude(double vec[3]){ return sqrt(vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]); } void normalize(double vec[3]){ float m = magnitude(vec); if(tol <= m) m = 1; vec[0] /= m; vec[1] /= m; vec[2] /= m; if(fabs(vec[0]) < tol) vec[0] = 0.0f; if(fabs(vec[1]) < tol) vec[1] = 0.0f; if(fabs(vec[2]) < tol) vec[2] = 0.0f; } class ArtificialPotentialField{ public: ArtificialPotentialField(const ros::NodeHandle &node) : cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)) { for(int i=0; i < 3; i++) obs_[i] = 0; } void spin(){ ros::Duration(1).sleep(); geometry_msgs::Twist cmd; cmd.linear.z = 0.15; cmd_pub_.publish(cmd); ros::Duration(3).sleep(); cmd.linear.z = 0; cmd_pub_.publish(cmd); ros::Duration(3).sleep(); double Fs[3]; double u[3]; double obs[3]; const double A = 0; const double B = 3; const double n = 1; const double m = 1.5; const double force = 0.025; Fs[0] = Fs[1] = Fs[2] = 0; obs[0] = 0.5; obs[1] = 0; obs[2] = 0; u[0] = obs[0]; u[1] = obs[1]; u[2] = obs[2]; normalize(u); const double d = magnitude(obs); double U = -A/pow(d, n) + B/pow(d, m); Fs[0] += U * u[0]; Fs[1] += U * u[1]; Fs[2] += U * u[2]; cmd.linear.x = Fs[0] * force; cmd.linear.y = Fs[1] * force; ROS_INFO_STREAM("cmd = " << cmd); cmd_pub_.publish(cmd); ros::Duration(10).sleep(); } private: void obstacleCallback(const sensor_msgs::PointCloud::ConstPtr &obs_msg){ double min_obs[3]; double min_obs[0] = obs_msg->points[0].x; double min_obs[1] = obs_msg->points[0].y; double min_obs[2] = obs_msg->points[0].z; float min_dist = magnitude(obs1); for(int i=1; i < obs_msg->get_points_size(); i++){ double obs[3]; obs[0] = obs_msg->points[i].x; obs[1] = obs_msg->points[i].y; obs[2] = obs_msg->points[i].z; double dist = magnitude(obs2); if(dist < min_dist){ min_obs[0] = obs[0]; min_obs[1] = obs[1]; min_obs[2] = obs[2]; min_dist = dist; } } obs_[0] = min_obs[0]; obs_[1] = min_obs[1]; obs_[2] = min_obs[2]; } double obs_[3]; ros::Publisher cmd_pub_; }; int main(int argc, char *argv[]){ ros::init(argc, argv, "obstacle_avoidance"); ros::NodeHandle node; apf = ArtificialPotentialField(node); apf.spin(); return 0; } <commit_msg>fix conflicting declaration<commit_after>#include <ros/ros.h> #include <geometry_msgs/Twist.h> #include <sensor_msgs/PointCloud.h> #include <math.h> static const float tol = 0.000000000000001f; double magnitude(double vec[3]){ return sqrt(vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]); } void normalize(double vec[3]){ float m = magnitude(vec); if(tol <= m) m = 1; vec[0] /= m; vec[1] /= m; vec[2] /= m; if(fabs(vec[0]) < tol) vec[0] = 0.0f; if(fabs(vec[1]) < tol) vec[1] = 0.0f; if(fabs(vec[2]) < tol) vec[2] = 0.0f; } class ArtificialPotentialField{ public: ArtificialPotentialField(const ros::NodeHandle &node) : cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)) { for(int i=0; i < 3; i++) obs_[i] = 0; } void spin(){ ros::Duration(1).sleep(); geometry_msgs::Twist cmd; cmd.linear.z = 0.15; cmd_pub_.publish(cmd); ros::Duration(3).sleep(); cmd.linear.z = 0; cmd_pub_.publish(cmd); ros::Duration(3).sleep(); double Fs[3]; double u[3]; double obs[3]; const double A = 0; const double B = 3; const double n = 1; const double m = 1.5; const double force = 0.025; Fs[0] = Fs[1] = Fs[2] = 0; obs[0] = 0.5; obs[1] = 0; obs[2] = 0; u[0] = obs[0]; u[1] = obs[1]; u[2] = obs[2]; normalize(u); const double d = magnitude(obs); double U = -A/pow(d, n) + B/pow(d, m); Fs[0] += U * u[0]; Fs[1] += U * u[1]; Fs[2] += U * u[2]; cmd.linear.x = Fs[0] * force; cmd.linear.y = Fs[1] * force; ROS_INFO_STREAM("cmd = " << cmd); cmd_pub_.publish(cmd); ros::Duration(10).sleep(); } private: void obstacleCallback(const sensor_msgs::PointCloud::ConstPtr &obs_msg){ double min_obs[3]; min_obs[0] = obs_msg->points[0].x; min_obs[1] = obs_msg->points[0].y; min_obs[2] = obs_msg->points[0].z; float min_dist = magnitude(obs1); for(int i=1; i < obs_msg->get_points_size(); i++){ double obs[3]; obs[0] = obs_msg->points[i].x; obs[1] = obs_msg->points[i].y; obs[2] = obs_msg->points[i].z; double dist = magnitude(obs2); if(dist < min_dist){ min_obs[0] = obs[0]; min_obs[1] = obs[1]; min_obs[2] = obs[2]; min_dist = dist; } } obs_[0] = min_obs[0]; obs_[1] = min_obs[1]; obs_[2] = min_obs[2]; } double obs_[3]; ros::Publisher cmd_pub_; }; int main(int argc, char *argv[]){ ros::init(argc, argv, "obstacle_avoidance"); ros::NodeHandle node; apf = ArtificialPotentialField(node); apf.spin(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/download/download_request_manager.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/download/download_request_infobar_delegate.h" #include "chrome/browser/tab_contents/navigation_controller.h" #include "chrome/browser/tab_contents/navigation_entry.h" #include "chrome/browser/tab_contents/tab_contents_delegate.h" #include "chrome/browser/tab_contents/tab_util.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/notification_service.h" // TabDownloadState ------------------------------------------------------------ DownloadRequestManager::TabDownloadState::TabDownloadState( DownloadRequestManager* host, NavigationController* controller, NavigationController* originating_controller) : host_(host), controller_(controller), status_(DownloadRequestManager::ALLOW_ONE_DOWNLOAD), infobar_(NULL) { Source<NavigationController> notification_source(controller); registrar_.Add(this, NotificationType::NAV_ENTRY_PENDING, notification_source); registrar_.Add(this, NotificationType::TAB_CLOSED, notification_source); NavigationEntry* active_entry = originating_controller ? originating_controller->GetActiveEntry() : controller->GetActiveEntry(); if (active_entry) initial_page_host_ = active_entry->url().host(); } DownloadRequestManager::TabDownloadState::~TabDownloadState() { // We should only be destroyed after the callbacks have been notified. DCHECK(callbacks_.empty()); // And we should have closed the infobar. DCHECK(!infobar_); } void DownloadRequestManager::TabDownloadState::OnUserGesture() { if (is_showing_prompt()) { // Don't change the state if the user clicks on the page some where. return; } if (status_ != DownloadRequestManager::ALLOW_ALL_DOWNLOADS && status_ != DownloadRequestManager::DOWNLOADS_NOT_ALLOWED) { // Revert to default status. host_->Remove(this); // WARNING: We've been deleted. return; } } void DownloadRequestManager::TabDownloadState::PromptUserForDownload( TabContents* tab, DownloadRequestManager::Callback* callback) { callbacks_.push_back(callback); if (is_showing_prompt()) return; // Already showing prompt. if (DownloadRequestManager::delegate_) { NotifyCallbacks(DownloadRequestManager::delegate_->ShouldAllowDownload()); } else { infobar_ = new DownloadRequestInfoBarDelegate(tab, this); } } void DownloadRequestManager::TabDownloadState::Cancel() { NotifyCallbacks(false); } void DownloadRequestManager::TabDownloadState::Accept() { NotifyCallbacks(true); } void DownloadRequestManager::TabDownloadState::Observe( NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if ((type != NotificationType::NAV_ENTRY_PENDING && type != NotificationType::TAB_CLOSED) || Source<NavigationController>(source).ptr() != controller_) { NOTREACHED(); return; } switch (type.value) { case NotificationType::NAV_ENTRY_PENDING: { // NOTE: resetting state on a pending navigate isn't ideal. In particular // it is possible that queued up downloads for the page before the // pending navigate will be delivered to us after we process this // request. If this happens we may let a download through that we // shouldn't have. But this is rather rare, and it is difficult to get // 100% right, so we don't deal with it. NavigationEntry* entry = controller_->pending_entry(); if (!entry) return; if (PageTransition::IsRedirect(entry->transition_type())) { // Redirects don't count. return; } if (status_ == DownloadRequestManager::ALLOW_ALL_DOWNLOADS || status_ == DownloadRequestManager::DOWNLOADS_NOT_ALLOWED) { // User has either allowed all downloads or canceled all downloads. Only // reset the download state if the user is navigating to a different // host (or host is empty). if (!initial_page_host_.empty() && !entry->url().host().empty() && entry->url().host() == initial_page_host_) { return; } } break; } case NotificationType::TAB_CLOSED: // Tab closed, no need to handle closing the dialog as it's owned by the // TabContents, break so that we get deleted after switch. break; default: NOTREACHED(); } NotifyCallbacks(false); host_->Remove(this); } void DownloadRequestManager::TabDownloadState::NotifyCallbacks(bool allow) { status_ = allow ? DownloadRequestManager::ALLOW_ALL_DOWNLOADS : DownloadRequestManager::DOWNLOADS_NOT_ALLOWED; std::vector<DownloadRequestManager::Callback*> callbacks; bool change_status = false; // Selectively send first few notifications only if number of downloads exceed // kMaxDownloadsAtOnce. In that case, we also retain the infobar instance and // don't close it. If allow is false, we send all the notifications to cancel // all remaining downloads and close the infobar. if (!allow || (callbacks_.size() < kMaxDownloadsAtOnce)) { if (infobar_) { // Reset the delegate so we don't get notified again. infobar_->set_host(NULL); infobar_ = NULL; } callbacks.swap(callbacks_); } else { std::vector<DownloadRequestManager::Callback*>::iterator start, end; start = callbacks_.begin(); end = callbacks_.begin() + kMaxDownloadsAtOnce; callbacks.assign(start, end); callbacks_.erase(start, end); change_status = true; } for (size_t i = 0; i < callbacks.size(); ++i) { host_->ScheduleNotification(callbacks[i], allow); } if (change_status) status_ = DownloadRequestManager::PROMPT_BEFORE_DOWNLOAD; } // DownloadRequestManager ------------------------------------------------------ DownloadRequestManager::DownloadRequestManager() { } DownloadRequestManager::~DownloadRequestManager() { // All the tabs should have closed before us, which sends notification and // removes from state_map_. As such, there should be no pending callbacks. DCHECK(state_map_.empty()); } DownloadRequestManager::DownloadStatus DownloadRequestManager::GetDownloadStatus(TabContents* tab) { TabDownloadState* state = GetDownloadState(&tab->controller(), NULL, false); return state ? state->download_status() : ALLOW_ONE_DOWNLOAD; } void DownloadRequestManager::CanDownloadOnIOThread(int render_process_host_id, int render_view_id, Callback* callback) { // This is invoked on the IO thread. Schedule the task to run on the UI // thread so that we can query UI state. DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)); ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableMethod(this, &DownloadRequestManager::CanDownload, render_process_host_id, render_view_id, callback)); } void DownloadRequestManager::OnUserGesture(TabContents* tab) { TabDownloadState* state = GetDownloadState(&tab->controller(), NULL, false); if (!state) return; state->OnUserGesture(); } // static void DownloadRequestManager::SetTestingDelegate(TestingDelegate* delegate) { delegate_ = delegate; } DownloadRequestManager::TabDownloadState* DownloadRequestManager:: GetDownloadState(NavigationController* controller, NavigationController* originating_controller, bool create) { DCHECK(controller); StateMap::iterator i = state_map_.find(controller); if (i != state_map_.end()) return i->second; if (!create) return NULL; TabDownloadState* state = new TabDownloadState(this, controller, originating_controller); state_map_[controller] = state; return state; } void DownloadRequestManager::CanDownload(int render_process_host_id, int render_view_id, Callback* callback) { DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI)); TabContents* originating_tab = tab_util::GetTabContentsByID(render_process_host_id, render_view_id); if (!originating_tab) { // The tab was closed, don't allow the download. ScheduleNotification(callback, false); return; } CanDownloadImpl(originating_tab, callback); } void DownloadRequestManager::CanDownloadImpl( TabContents* originating_tab, Callback* callback) { // FYI: Chrome Frame overrides CanDownload in ExternalTabContainer in order // to cancel the download operation in chrome and let the host browser // take care of it. if (!originating_tab->CanDownload(callback->GetRequestId())) { ScheduleNotification(callback, false); return; } // If the tab requesting the download is a constrained popup that is not // shown, treat the request as if it came from the parent. TabContents* effective_tab = originating_tab; if (effective_tab->delegate()) { effective_tab = effective_tab->delegate()->GetConstrainingContents(effective_tab); } TabDownloadState* state = GetDownloadState( &effective_tab->controller(), &originating_tab->controller(), true); switch (state->download_status()) { case ALLOW_ALL_DOWNLOADS: if (state->download_count() && !(state->download_count() % DownloadRequestManager::kMaxDownloadsAtOnce)) state->set_download_status(PROMPT_BEFORE_DOWNLOAD); ScheduleNotification(callback, true); state->increment_download_count(); break; case ALLOW_ONE_DOWNLOAD: state->set_download_status(PROMPT_BEFORE_DOWNLOAD); ScheduleNotification(callback, true); break; case DOWNLOADS_NOT_ALLOWED: ScheduleNotification(callback, false); break; case PROMPT_BEFORE_DOWNLOAD: state->PromptUserForDownload(effective_tab, callback); state->increment_download_count(); break; default: NOTREACHED(); } } void DownloadRequestManager::ScheduleNotification(Callback* callback, bool allow) { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod( this, &DownloadRequestManager::NotifyCallback, callback, allow)); } void DownloadRequestManager::NotifyCallback(Callback* callback, bool allow) { // We better be on the IO thread now. DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)); if (allow) callback->ContinueDownload(); else callback->CancelDownload(); } void DownloadRequestManager::Remove(TabDownloadState* state) { DCHECK(state_map_.find(state->controller()) != state_map_.end()); state_map_.erase(state->controller()); delete state; } // static DownloadRequestManager::TestingDelegate* DownloadRequestManager::delegate_ = NULL; <commit_msg>Fix a UMR reported on the valgrind linux build bots while running the DownloadRequestManagerTest.Allow test<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/download/download_request_manager.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/download/download_request_infobar_delegate.h" #include "chrome/browser/tab_contents/navigation_controller.h" #include "chrome/browser/tab_contents/navigation_entry.h" #include "chrome/browser/tab_contents/tab_contents_delegate.h" #include "chrome/browser/tab_contents/tab_util.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/notification_service.h" // TabDownloadState ------------------------------------------------------------ DownloadRequestManager::TabDownloadState::TabDownloadState( DownloadRequestManager* host, NavigationController* controller, NavigationController* originating_controller) : host_(host), controller_(controller), status_(DownloadRequestManager::ALLOW_ONE_DOWNLOAD), infobar_(NULL), download_count_(0) { Source<NavigationController> notification_source(controller); registrar_.Add(this, NotificationType::NAV_ENTRY_PENDING, notification_source); registrar_.Add(this, NotificationType::TAB_CLOSED, notification_source); NavigationEntry* active_entry = originating_controller ? originating_controller->GetActiveEntry() : controller->GetActiveEntry(); if (active_entry) initial_page_host_ = active_entry->url().host(); } DownloadRequestManager::TabDownloadState::~TabDownloadState() { // We should only be destroyed after the callbacks have been notified. DCHECK(callbacks_.empty()); // And we should have closed the infobar. DCHECK(!infobar_); } void DownloadRequestManager::TabDownloadState::OnUserGesture() { if (is_showing_prompt()) { // Don't change the state if the user clicks on the page some where. return; } if (status_ != DownloadRequestManager::ALLOW_ALL_DOWNLOADS && status_ != DownloadRequestManager::DOWNLOADS_NOT_ALLOWED) { // Revert to default status. host_->Remove(this); // WARNING: We've been deleted. return; } } void DownloadRequestManager::TabDownloadState::PromptUserForDownload( TabContents* tab, DownloadRequestManager::Callback* callback) { callbacks_.push_back(callback); if (is_showing_prompt()) return; // Already showing prompt. if (DownloadRequestManager::delegate_) { NotifyCallbacks(DownloadRequestManager::delegate_->ShouldAllowDownload()); } else { infobar_ = new DownloadRequestInfoBarDelegate(tab, this); } } void DownloadRequestManager::TabDownloadState::Cancel() { NotifyCallbacks(false); } void DownloadRequestManager::TabDownloadState::Accept() { NotifyCallbacks(true); } void DownloadRequestManager::TabDownloadState::Observe( NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if ((type != NotificationType::NAV_ENTRY_PENDING && type != NotificationType::TAB_CLOSED) || Source<NavigationController>(source).ptr() != controller_) { NOTREACHED(); return; } switch (type.value) { case NotificationType::NAV_ENTRY_PENDING: { // NOTE: resetting state on a pending navigate isn't ideal. In particular // it is possible that queued up downloads for the page before the // pending navigate will be delivered to us after we process this // request. If this happens we may let a download through that we // shouldn't have. But this is rather rare, and it is difficult to get // 100% right, so we don't deal with it. NavigationEntry* entry = controller_->pending_entry(); if (!entry) return; if (PageTransition::IsRedirect(entry->transition_type())) { // Redirects don't count. return; } if (status_ == DownloadRequestManager::ALLOW_ALL_DOWNLOADS || status_ == DownloadRequestManager::DOWNLOADS_NOT_ALLOWED) { // User has either allowed all downloads or canceled all downloads. Only // reset the download state if the user is navigating to a different // host (or host is empty). if (!initial_page_host_.empty() && !entry->url().host().empty() && entry->url().host() == initial_page_host_) { return; } } break; } case NotificationType::TAB_CLOSED: // Tab closed, no need to handle closing the dialog as it's owned by the // TabContents, break so that we get deleted after switch. break; default: NOTREACHED(); } NotifyCallbacks(false); host_->Remove(this); } void DownloadRequestManager::TabDownloadState::NotifyCallbacks(bool allow) { status_ = allow ? DownloadRequestManager::ALLOW_ALL_DOWNLOADS : DownloadRequestManager::DOWNLOADS_NOT_ALLOWED; std::vector<DownloadRequestManager::Callback*> callbacks; bool change_status = false; // Selectively send first few notifications only if number of downloads exceed // kMaxDownloadsAtOnce. In that case, we also retain the infobar instance and // don't close it. If allow is false, we send all the notifications to cancel // all remaining downloads and close the infobar. if (!allow || (callbacks_.size() < kMaxDownloadsAtOnce)) { if (infobar_) { // Reset the delegate so we don't get notified again. infobar_->set_host(NULL); infobar_ = NULL; } callbacks.swap(callbacks_); } else { std::vector<DownloadRequestManager::Callback*>::iterator start, end; start = callbacks_.begin(); end = callbacks_.begin() + kMaxDownloadsAtOnce; callbacks.assign(start, end); callbacks_.erase(start, end); change_status = true; } for (size_t i = 0; i < callbacks.size(); ++i) { host_->ScheduleNotification(callbacks[i], allow); } if (change_status) status_ = DownloadRequestManager::PROMPT_BEFORE_DOWNLOAD; } // DownloadRequestManager ------------------------------------------------------ DownloadRequestManager::DownloadRequestManager() { } DownloadRequestManager::~DownloadRequestManager() { // All the tabs should have closed before us, which sends notification and // removes from state_map_. As such, there should be no pending callbacks. DCHECK(state_map_.empty()); } DownloadRequestManager::DownloadStatus DownloadRequestManager::GetDownloadStatus(TabContents* tab) { TabDownloadState* state = GetDownloadState(&tab->controller(), NULL, false); return state ? state->download_status() : ALLOW_ONE_DOWNLOAD; } void DownloadRequestManager::CanDownloadOnIOThread(int render_process_host_id, int render_view_id, Callback* callback) { // This is invoked on the IO thread. Schedule the task to run on the UI // thread so that we can query UI state. DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)); ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableMethod(this, &DownloadRequestManager::CanDownload, render_process_host_id, render_view_id, callback)); } void DownloadRequestManager::OnUserGesture(TabContents* tab) { TabDownloadState* state = GetDownloadState(&tab->controller(), NULL, false); if (!state) return; state->OnUserGesture(); } // static void DownloadRequestManager::SetTestingDelegate(TestingDelegate* delegate) { delegate_ = delegate; } DownloadRequestManager::TabDownloadState* DownloadRequestManager:: GetDownloadState(NavigationController* controller, NavigationController* originating_controller, bool create) { DCHECK(controller); StateMap::iterator i = state_map_.find(controller); if (i != state_map_.end()) return i->second; if (!create) return NULL; TabDownloadState* state = new TabDownloadState(this, controller, originating_controller); state_map_[controller] = state; return state; } void DownloadRequestManager::CanDownload(int render_process_host_id, int render_view_id, Callback* callback) { DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI)); TabContents* originating_tab = tab_util::GetTabContentsByID(render_process_host_id, render_view_id); if (!originating_tab) { // The tab was closed, don't allow the download. ScheduleNotification(callback, false); return; } CanDownloadImpl(originating_tab, callback); } void DownloadRequestManager::CanDownloadImpl( TabContents* originating_tab, Callback* callback) { // FYI: Chrome Frame overrides CanDownload in ExternalTabContainer in order // to cancel the download operation in chrome and let the host browser // take care of it. if (!originating_tab->CanDownload(callback->GetRequestId())) { ScheduleNotification(callback, false); return; } // If the tab requesting the download is a constrained popup that is not // shown, treat the request as if it came from the parent. TabContents* effective_tab = originating_tab; if (effective_tab->delegate()) { effective_tab = effective_tab->delegate()->GetConstrainingContents(effective_tab); } TabDownloadState* state = GetDownloadState( &effective_tab->controller(), &originating_tab->controller(), true); switch (state->download_status()) { case ALLOW_ALL_DOWNLOADS: if (state->download_count() && !(state->download_count() % DownloadRequestManager::kMaxDownloadsAtOnce)) state->set_download_status(PROMPT_BEFORE_DOWNLOAD); ScheduleNotification(callback, true); state->increment_download_count(); break; case ALLOW_ONE_DOWNLOAD: state->set_download_status(PROMPT_BEFORE_DOWNLOAD); ScheduleNotification(callback, true); break; case DOWNLOADS_NOT_ALLOWED: ScheduleNotification(callback, false); break; case PROMPT_BEFORE_DOWNLOAD: state->PromptUserForDownload(effective_tab, callback); state->increment_download_count(); break; default: NOTREACHED(); } } void DownloadRequestManager::ScheduleNotification(Callback* callback, bool allow) { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod( this, &DownloadRequestManager::NotifyCallback, callback, allow)); } void DownloadRequestManager::NotifyCallback(Callback* callback, bool allow) { // We better be on the IO thread now. DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)); if (allow) callback->ContinueDownload(); else callback->CancelDownload(); } void DownloadRequestManager::Remove(TabDownloadState* state) { DCHECK(state_map_.find(state->controller()) != state_map_.end()); state_map_.erase(state->controller()); delete state; } // static DownloadRequestManager::TestingDelegate* DownloadRequestManager::delegate_ = NULL; <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "base/prefs/pref_service.h" #include "chrome/browser/prefs/incognito_mode_prefs.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "net/dns/mock_host_resolver.h" #if defined(OS_WIN) #include "ui/aura/window.h" #include "ui/aura/window_tree_host.h" #endif // Window resizes are not completed by the time the callback happens, // so these tests fail on linux/gtk. http://crbug.com/72369 #if defined(OS_LINUX) && !defined(USE_AURA) #define MAYBE_UpdateWindowResize DISABLED_UpdateWindowResize #define MAYBE_UpdateWindowShowState DISABLED_UpdateWindowShowState #else #if defined(USE_AURA) || defined(OS_MACOSX) // Maximizing/fullscreen popup window doesn't work on aura's managed mode. // See bug crbug.com/116305. // Mac: http://crbug.com/103912 #define MAYBE_UpdateWindowShowState DISABLED_UpdateWindowShowState #else #define MAYBE_UpdateWindowShowState UpdateWindowShowState #endif // defined(USE_AURA) || defined(OS_MACOSX) #define MAYBE_UpdateWindowResize UpdateWindowResize #endif // defined(OS_LINUX) && !defined(USE_AURA) // http://crbug.com/145639 #if defined(OS_LINUX) || defined(OS_WIN) #define MAYBE_TabEvents DISABLED_TabEvents #else #define MAYBE_TabEvents TabEvents #endif class ExtensionApiNewTabTest : public ExtensionApiTest { public: ExtensionApiNewTabTest() {} virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { ExtensionApiTest::SetUpCommandLine(command_line); // Override the default which InProcessBrowserTest adds if it doesn't see a // homepage. command_line->AppendSwitchASCII( switches::kHomePage, chrome::kChromeUINewTabURL); } }; IN_PROC_BROWSER_TEST_F(ExtensionApiNewTabTest, Tabs) { // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud.html")) << message_; } // Flaky on windows: http://crbug.com/238667 #if defined(OS_WIN) #define MAYBE_Tabs2 DISABLED_Tabs2 #else #define MAYBE_Tabs2 Tabs2 #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs2) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud2.html")) << message_; } // crbug.com/149924 IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabDuplicate) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "duplicate.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabSize) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "tab_size.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabUpdate) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "update.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabPinned) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "pinned.html")) << message_; } // Flaky on windows: http://crbug.com/238667 #if defined(OS_WIN) #define MAYBE_TabMove DISABLED_TabMove #else #define MAYBE_TabMove TabMove #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabMove) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "move.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabEvents) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "events.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabRelativeURLs) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "relative_urls.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabQuery) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "query.html")) << message_; } // Flaky on windows: http://crbug.com/239022 #if defined(OS_WIN) #define MAYBE_TabHighlight DISABLED_TabHighlight #else #define MAYBE_TabHighlight TabHighlight #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabHighlight) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "highlight.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabCrashBrowser) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crash.html")) << message_; } // Flaky on windows: http://crbug.com/238667 #if defined(OS_WIN) #define MAYBE_TabOpener DISABLED_TabOpener #else #define MAYBE_TabOpener TabOpener #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOpener) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "opener.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabGetCurrent) { ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } // Flaky on the trybots. See http://crbug.com/96725. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabConnect) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } // Possible race in ChromeURLDataManager. http://crbug.com/59198 IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabOnRemoved) { ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabReload) { ASSERT_TRUE(RunExtensionTest("tabs/reload")) << message_; } class ExtensionApiCaptureTest : public ExtensionApiTest { public: ExtensionApiCaptureTest() {} virtual void SetUp() OVERRIDE { EnablePixelOutput(); ExtensionApiTest::SetUp(); } virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { ExtensionApiTest::SetUpCommandLine(command_line); } }; IN_PROC_BROWSER_TEST_F(ExtensionApiCaptureTest, DISABLED_CaptureVisibleTabJpeg) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiCaptureTest, DISABLED_CaptureVisibleTabPng) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } // Times out on non-Windows. // See http://crbug.com/80212 IN_PROC_BROWSER_TEST_F(ExtensionApiCaptureTest, DISABLED_CaptureVisibleTabRace) { ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_race.html")) << message_; } // Disabled for being flaky, see http://crbug/367695. IN_PROC_BROWSER_TEST_F(ExtensionApiCaptureTest, DISABLED_CaptureVisibleFile) { ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_file.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiCaptureTest, CaptureVisibleDisabled) { browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableScreenshots, true); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_disabled.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsNoPermissions) { ASSERT_TRUE(RunExtensionTest("tabs/no_permissions")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_UpdateWindowResize) { ASSERT_TRUE(RunExtensionTest("window_update/resize")) << message_; } #if defined(OS_WIN) IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FocusWindowDoesNotUnmaximize) { HWND window = browser()->window()->GetNativeWindow()->GetHost()->GetAcceleratedWidget(); ::SendMessage(window, WM_SYSCOMMAND, SC_MAXIMIZE, 0); ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_; ASSERT_TRUE(::IsZoomed(window)); } #endif // OS_WIN IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_UpdateWindowShowState) { ASSERT_TRUE(RunExtensionTest("window_update/show_state")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabledByPref) { IncognitoModePrefs::SetAvailability(browser()->profile()->GetPrefs(), IncognitoModePrefs::DISABLED); // This makes sure that creating an incognito window fails due to pref // (policy) being set. ASSERT_TRUE(RunExtensionTest("tabs/incognito_disabled")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_GetViewsOfCreatedPopup) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_popup.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_GetViewsOfCreatedWindow) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_window.html")) << message_; } // Adding a new test? Awesome. But API tests are the old hotness. The // new hotness is extension_test_utils. See tabs_test.cc for an example. // We are trying to phase out many uses of API tests as they tend to be flaky. <commit_msg>Cleanup: Remove some dead GTK code in ExtensionApiTest.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "base/prefs/pref_service.h" #include "chrome/browser/prefs/incognito_mode_prefs.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "net/dns/mock_host_resolver.h" #if defined(OS_WIN) #include "ui/aura/window.h" #include "ui/aura/window_tree_host.h" #endif #if defined(USE_AURA) || defined(OS_MACOSX) // Maximizing/fullscreen popup window doesn't work on aura's managed mode. // See bug crbug.com/116305. // Mac: http://crbug.com/103912 #define MAYBE_UpdateWindowShowState DISABLED_UpdateWindowShowState #else #define MAYBE_UpdateWindowShowState UpdateWindowShowState #endif // defined(USE_AURA) || defined(OS_MACOSX) // http://crbug.com/145639 #if defined(OS_LINUX) || defined(OS_WIN) #define MAYBE_TabEvents DISABLED_TabEvents #else #define MAYBE_TabEvents TabEvents #endif class ExtensionApiNewTabTest : public ExtensionApiTest { public: ExtensionApiNewTabTest() {} virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { ExtensionApiTest::SetUpCommandLine(command_line); // Override the default which InProcessBrowserTest adds if it doesn't see a // homepage. command_line->AppendSwitchASCII( switches::kHomePage, chrome::kChromeUINewTabURL); } }; IN_PROC_BROWSER_TEST_F(ExtensionApiNewTabTest, Tabs) { // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud.html")) << message_; } // Flaky on windows: http://crbug.com/238667 #if defined(OS_WIN) #define MAYBE_Tabs2 DISABLED_Tabs2 #else #define MAYBE_Tabs2 Tabs2 #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs2) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud2.html")) << message_; } // crbug.com/149924 IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabDuplicate) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "duplicate.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabSize) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "tab_size.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabUpdate) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "update.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabPinned) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "pinned.html")) << message_; } // Flaky on windows: http://crbug.com/238667 #if defined(OS_WIN) #define MAYBE_TabMove DISABLED_TabMove #else #define MAYBE_TabMove TabMove #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabMove) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "move.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabEvents) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "events.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabRelativeURLs) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "relative_urls.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabQuery) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "query.html")) << message_; } // Flaky on windows: http://crbug.com/239022 #if defined(OS_WIN) #define MAYBE_TabHighlight DISABLED_TabHighlight #else #define MAYBE_TabHighlight TabHighlight #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabHighlight) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "highlight.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabCrashBrowser) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crash.html")) << message_; } // Flaky on windows: http://crbug.com/238667 #if defined(OS_WIN) #define MAYBE_TabOpener DISABLED_TabOpener #else #define MAYBE_TabOpener TabOpener #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOpener) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "opener.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabGetCurrent) { ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } // Flaky on the trybots. See http://crbug.com/96725. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabConnect) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } // Possible race in ChromeURLDataManager. http://crbug.com/59198 IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabOnRemoved) { ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_TabReload) { ASSERT_TRUE(RunExtensionTest("tabs/reload")) << message_; } class ExtensionApiCaptureTest : public ExtensionApiTest { public: ExtensionApiCaptureTest() {} virtual void SetUp() OVERRIDE { EnablePixelOutput(); ExtensionApiTest::SetUp(); } virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { ExtensionApiTest::SetUpCommandLine(command_line); } }; IN_PROC_BROWSER_TEST_F(ExtensionApiCaptureTest, DISABLED_CaptureVisibleTabJpeg) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiCaptureTest, DISABLED_CaptureVisibleTabPng) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } // Times out on non-Windows. // See http://crbug.com/80212 IN_PROC_BROWSER_TEST_F(ExtensionApiCaptureTest, DISABLED_CaptureVisibleTabRace) { ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_race.html")) << message_; } // Disabled for being flaky, see http://crbug/367695. IN_PROC_BROWSER_TEST_F(ExtensionApiCaptureTest, DISABLED_CaptureVisibleFile) { ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_file.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiCaptureTest, CaptureVisibleDisabled) { browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableScreenshots, true); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_disabled.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsNoPermissions) { ASSERT_TRUE(RunExtensionTest("tabs/no_permissions")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, UpdateWindowResize) { ASSERT_TRUE(RunExtensionTest("window_update/resize")) << message_; } #if defined(OS_WIN) IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FocusWindowDoesNotUnmaximize) { HWND window = browser()->window()->GetNativeWindow()->GetHost()->GetAcceleratedWidget(); ::SendMessage(window, WM_SYSCOMMAND, SC_MAXIMIZE, 0); ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_; ASSERT_TRUE(::IsZoomed(window)); } #endif // OS_WIN IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_UpdateWindowShowState) { ASSERT_TRUE(RunExtensionTest("window_update/show_state")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabledByPref) { IncognitoModePrefs::SetAvailability(browser()->profile()->GetPrefs(), IncognitoModePrefs::DISABLED); // This makes sure that creating an incognito window fails due to pref // (policy) being set. ASSERT_TRUE(RunExtensionTest("tabs/incognito_disabled")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_GetViewsOfCreatedPopup) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_popup.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_GetViewsOfCreatedWindow) { ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_window.html")) << message_; } // Adding a new test? Awesome. But API tests are the old hotness. The // new hotness is extension_test_utils. See tabs_test.cc for an example. // We are trying to phase out many uses of API tests as they tend to be flaky. <|endoftext|>