<commit_before>#include "rendering/object3d.h"

void Object3D::setSimpleDirection(vec3 dir){

//    rotation[0] = vec4(glm::normalize(glm::cross(dir,vec3(0,1,0))),0);
//    rotation[1] = vec4(0,1,0,0);
//    rotation[2] = vec4(-dir,0);
    calculateModel();
}

void Object3D::turn(float angleX, float angleY){
    rotateGlobal(vec3(0,1,0),angleX);
    mat4 modeltmp = model;
    rotateLocal(vec3(1,0,0),angleY);
    if (model[1][1] < 0){
        model = modeltmp;
    }
    calculateModel();

//    std::cout<<this->getDirection()<<" "<<(rot*vec4(0,0,1,0))<<std::endl;
//    std::cout<<this->getRightVector()<<" "<<(rot*vec4(1,0,0,0))<<std::endl;
//    std::cout<<this->getUpVector()<<" "<<(rot*vec4(0,1,0,0))<<std::endl;
}

void Object3D::rotateLocal2(vec3 axis, float angle){
//    mat4 rot = glm::rotate(mat4(),degreesToRadians(angle),axis);
//    rotation =  rot*rotation ;
    calculateModel();
}

void Object3D::rotateLocal(vec3 axis, float angle){
//    mat4 rot = glm::rotate(mat4(),degreesToRadians(angle),axis);
//    rotation =  rotation * rot ;

    this->rot = glm::rotate(this->rot,degreesToRadians(angle),axis);
//    rotation = glm::mat4_cast(this->rot);
    calculateModel();
}

void Object3D::rotateGlobal(vec3 axis, float angle){
    axis = vec3((glm::inverse(rot)) * vec4(axis,0));
    axis = glm::normalize(axis);
//    mat4 rot = glm::rotate(mat4(),degreesToRadians(angle),axis);
//    rotation =  rotation * rot ;

    this->rot = glm::rotate(this->rot,degreesToRadians(angle),axis);
//    rotation = glm::mat4_cast(this->rot);
    calculateModel();
//    model = glm::rotate(model,degreesToRadians(angle),axis);
}

void Object3D::translateLocal(vec4 d){
    translateLocal(vec3(d));
}

void Object3D::translateGlobal(vec4 d){
    translateGlobal(vec3(d));
}

void Object3D::translateLocal(vec3 d){
//    base = glm::translate(base,d);

    vec4 d2 = rot*vec4(d,1);
    translateGlobal(d2);
//    calculateModel();
}

void Object3D::translateGlobal(vec3 d){
    base[3] += vec4(d,0);
    calculateModel();
}

void Object3D::normalize(){
//    model[0] = glm::normalize(model[0]);
//    model[1] = glm::normalize(model[1]);
//    model[2] = glm::normalize(model[2]);
}

void Object3D::scale(vec3 s){
    mat4 scale = glm::scale(mat4(), s);
    size = size *scale ;
    calculateModel();
}

vec3 Object3D::getScale(){
    return vec3(size[0][0],size[1][1],size[2][2]);
}

void Object3D::setScale(vec3 s){
    size[0][0] = s.x;
    size[1][1] = s.y;
    size[2][2] = s.z;
    calculateModel();
}

void Object3D::getViewMatrix(mat4& view){
    view = glm::inverse(base*glm::mat4_cast(rot));
}

<commit_msg>setsimpledirection<commit_after>#include "rendering/object3d.h"

void Object3D::setSimpleDirection(vec3 dir){
    glm::mat4 rotmat;
    rotmat[0] = vec4(glm::normalize(glm::cross(dir,vec3(0,1,0))),0);
    rotmat[1] = vec4(0,1,0,0);
    rotmat[2] = vec4(-dir,0);

    this->rot = glm::quat(rotmat);
    calculateModel();
}

void Object3D::turn(float angleX, float angleY){
    rotateGlobal(vec3(0,1,0),angleX);
    mat4 modeltmp = model;
    rotateLocal(vec3(1,0,0),angleY);
    if (model[1][1] < 0){
        model = modeltmp;
    }
    calculateModel();

//    std::cout<<this->getDirection()<<" "<<(rot*vec4(0,0,1,0))<<std::endl;
//    std::cout<<this->getRightVector()<<" "<<(rot*vec4(1,0,0,0))<<std::endl;
//    std::cout<<this->getUpVector()<<" "<<(rot*vec4(0,1,0,0))<<std::endl;
}

void Object3D::rotateLocal2(vec3 axis, float angle){
//    mat4 rot = glm::rotate(mat4(),degreesToRadians(angle),axis);
//    rotation =  rot*rotation ;
    calculateModel();
}

void Object3D::rotateLocal(vec3 axis, float angle){
//    mat4 rot = glm::rotate(mat4(),degreesToRadians(angle),axis);
//    rotation =  rotation * rot ;

    this->rot = glm::rotate(this->rot,degreesToRadians(angle),axis);
//    rotation = glm::mat4_cast(this->rot);
    calculateModel();
}

void Object3D::rotateGlobal(vec3 axis, float angle){
    axis = vec3((glm::inverse(rot)) * vec4(axis,0));
    axis = glm::normalize(axis);
//    mat4 rot = glm::rotate(mat4(),degreesToRadians(angle),axis);
//    rotation =  rotation * rot ;

    this->rot = glm::rotate(this->rot,degreesToRadians(angle),axis);
//    rotation = glm::mat4_cast(this->rot);
    calculateModel();
//    model = glm::rotate(model,degreesToRadians(angle),axis);
}

void Object3D::translateLocal(vec4 d){
    translateLocal(vec3(d));
}

void Object3D::translateGlobal(vec4 d){
    translateGlobal(vec3(d));
}

void Object3D::translateLocal(vec3 d){
//    base = glm::translate(base,d);

    vec4 d2 = rot*vec4(d,1);
    translateGlobal(d2);
//    calculateModel();
}

void Object3D::translateGlobal(vec3 d){
    base[3] += vec4(d,0);
    calculateModel();
}

void Object3D::normalize(){
//    model[0] = glm::normalize(model[0]);
//    model[1] = glm::normalize(model[1]);
//    model[2] = glm::normalize(model[2]);
}

void Object3D::scale(vec3 s){
    mat4 scale = glm::scale(mat4(), s);
    size = size *scale ;
    calculateModel();
}

vec3 Object3D::getScale(){
    return vec3(size[0][0],size[1][1],size[2][2]);
}

void Object3D::setScale(vec3 s){
    size[0][0] = s.x;
    size[1][1] = s.y;
    size[2][2] = s.z;
    calculateModel();
}

void Object3D::getViewMatrix(mat4& view){
    view = glm::inverse(base*glm::mat4_cast(rot));
}

<|endoftext|>


<commit_before>// DuiVisionDemo.cpp : ӦóΪ
//

#include "stdafx.h"
#include "DuiVisionDemo.h"
#include "DuiHandlerMain.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// CDuiVisionDemoApp

BEGIN_MESSAGE_MAP(CDuiVisionDemoApp, CWinApp)
	ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()

// CDuiVisionDemoApp

CDuiVisionDemoApp::CDuiVisionDemoApp()
{
	// TODO: ڴ˴ӹ룬
	// Ҫĳʼ InitInstance
}

// Ψһһ CDuiVisionDemoApp

CDuiVisionDemoApp theApp;

// CDuiVisionDemoApp ʼ

BOOL CDuiVisionDemoApp::InitInstance()
{
	CWinApp::InitInstance();

	AfxEnableControlContainer();

	// TODO: Ӧʵ޸ĸַ
	// ޸Ϊ˾֯
	SetRegistryKey(_T("Blueant"));

	// ʼDuiVision,ָ,dwLangIDΪ0ʾԶжϵǰ
	// 1116ӦóID,ÿDUIӦóӦʹòͬID,IDҪڽ̼ͨŴʱӦ
	DWORD dwLangID = 0;
	new DuiSystem(m_hInstance, dwLangID, _T("DuiVisionDemo.ui"), 1116, IDD_DUIVISIONDEMO_DIALOG, _T(""));

	// ǷѾн
	CString strAppMutex = DuiSystem::Instance()->GetConfig(_T("appMutex"));	// ļлȡ
	if(!strAppMutex.IsEmpty())
	{
		::CreateMutex(NULL,TRUE, _T("Global\\") + strAppMutex);
		if(ERROR_ALREADY_EXISTS == GetLastError() || ERROR_ACCESS_DENIED == GetLastError())
		{
			// ȡв,Ҫпֱ˳
			CString strCmd = _T("");
			if(__argc > 1)
			{
				strCmd = __targv[1];
				DuiSystem::LogEvent(LOG_LEVEL_DEBUG, _T("Command line:%s"), strCmd);
			}

			// ͽ̼Ϣ(lParamΪ1ʾʾ,appMutexΪӦ,Ϣв)
			CString strAppName = DuiSystem::Instance()->GetConfig(_T("appMutex"));
			DuiSystem::Instance()->SendInterprocessMessage(0, DuiSystem::Instance()->GetAppID(), 1, strAppName, strCmd);
			// ͷDuiVisionԴ
			DuiSystem::Release();

			return FALSE; // Here we quit this application
		}
	}

	//
	CDlgBase* pMainDlg = DuiSystem::CreateDuiDialog(_T("dlg_main"), NULL, _T(""), TRUE);
	// ע¼
	CDuiHandlerMain* pHandler = new CDuiHandlerMain();
	pHandler->SetDialog(pMainDlg);
	DuiSystem::RegisterHandler(pMainDlg, pHandler);

	// ʼʾϢ
	DuiSystem::Instance()->CreateNotifyMsgBox(_T("dlg_notifymsg"));

	// շģʽԻ򴴽,Ĭ
	pMainDlg->Create(pMainDlg->GetIDTemplate(), NULL);
	//pMainDlg->ShowWindow(SW_HIDE);
	INT_PTR nResponse = pMainDlg->RunModalLoop();

	// ǰģʽԻ,ֻҪΪ´Ϳ
	//INT_PTR nResponse = pMainDlg->DoModal();

	// ͷDuiVisionԴ
	DuiSystem::Release();

	// ڶԻѹرգԽ FALSE Ա˳Ӧó
	//  ӦóϢá
	return FALSE;
}
<commit_msg>Demo程序增加WebKit控件的注册代码。<commit_after>// DuiVisionDemo.cpp : ӦóΪ
//

#include "stdafx.h"
#include "DuiVisionDemo.h"
#include "DuiHandlerMain.h"
#include "DuiWkeView.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// CDuiVisionDemoApp

BEGIN_MESSAGE_MAP(CDuiVisionDemoApp, CWinApp)
	ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()

// CDuiVisionDemoApp

CDuiVisionDemoApp::CDuiVisionDemoApp()
{
	// TODO: ڴ˴ӹ룬
	// Ҫĳʼ InitInstance
}

// Ψһһ CDuiVisionDemoApp

CDuiVisionDemoApp theApp;

// CDuiVisionDemoApp ʼ

BOOL CDuiVisionDemoApp::InitInstance()
{
	CWinApp::InitInstance();

	AfxEnableControlContainer();

	// TODO: Ӧʵ޸ĸַ
	// ޸Ϊ˾֯
	SetRegistryKey(_T("Blueant"));

	// ʼDuiVision,ָ,dwLangIDΪ0ʾԶжϵǰ
	// 1116ӦóID,ÿDUIӦóӦʹòͬID,IDҪڽ̼ͨŴʱӦ
	DWORD dwLangID = 0;
	new DuiSystem(m_hInstance, dwLangID, _T("DuiVisionDemo.ui"), 1116, IDD_DUIVISIONDEMO_DIALOG, _T(""));

	// ǷѾн
	CString strAppMutex = DuiSystem::Instance()->GetConfig(_T("appMutex"));	// ļлȡ
	if(!strAppMutex.IsEmpty())
	{
		::CreateMutex(NULL,TRUE, _T("Global\\") + strAppMutex);
		if(ERROR_ALREADY_EXISTS == GetLastError() || ERROR_ACCESS_DENIED == GetLastError())
		{
			// ȡв,Ҫпֱ˳
			CString strCmd = _T("");
			if(__argc > 1)
			{
				strCmd = __targv[1];
				DuiSystem::LogEvent(LOG_LEVEL_DEBUG, _T("Command line:%s"), strCmd);
			}

			// ͽ̼Ϣ(lParamΪ1ʾʾ,appMutexΪӦ,Ϣв)
			CString strAppName = DuiSystem::Instance()->GetConfig(_T("appMutex"));
			DuiSystem::Instance()->SendInterprocessMessage(0, DuiSystem::Instance()->GetAppID(), 1, strAppName, strCmd);
			// ͷDuiVisionԴ
			DuiSystem::Release();

			return FALSE; // Here we quit this application
		}
	}

	// עWKEؼ
	REGISTER_DUICONTROL(CDuiWkeView, CDuiWkeView::WkeShutdown);

	//
	CDlgBase* pMainDlg = DuiSystem::CreateDuiDialog(_T("dlg_main"), NULL, _T(""), TRUE);
	// ע¼
	CDuiHandlerMain* pHandler = new CDuiHandlerMain();
	pHandler->SetDialog(pMainDlg);
	DuiSystem::RegisterHandler(pMainDlg, pHandler);

	// ʼʾϢ
	DuiSystem::Instance()->CreateNotifyMsgBox(_T("dlg_notifymsg"));

	// շģʽԻ򴴽,Ĭ
	pMainDlg->Create(pMainDlg->GetIDTemplate(), NULL);
	//pMainDlg->ShowWindow(SW_HIDE);
	INT_PTR nResponse = pMainDlg->RunModalLoop();

	// ǰģʽԻ,ֻҪΪ´Ϳ
	//INT_PTR nResponse = pMainDlg->DoModal();

	// ͷDuiVisionԴ
	DuiSystem::Release();

	// ڶԻѹرգԽ FALSE Ա˳Ӧó
	//  ӦóϢá
	return FALSE;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: NeonInputStream.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kso $ $Date: 2001-09-12 10:03:35 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _NEONINPUTSTREAM_HXX_
#define _NEONINPUTSTREAM_HXX_

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_
#include <com/sun/star/io/XSeekable.hpp>
#endif

namespace webdav_ucp
{

// -------------------------------------------------------------------
// NeonInputStream
// A simple XInputStream implementation provided specifically for use
// by the DAVSession::GET method.
// -------------------------------------------------------------------
class NeonInputStream : public ::com::sun::star::io::XInputStream,
                        public ::com::sun::star::io::XSeekable,
                        public ::cppu::OWeakObject
{
    private:
        com::sun::star::uno::Sequence< sal_Int8 > mInputBuffer;
        sal_Int64 mLen;
        sal_Int64 mPos;

    public:
                 NeonInputStream( void );
        virtual ~NeonInputStream();

        // Add some data to the end of the stream
        void AddToStream( const char * inBuf, sal_Int32 inLen );

    // XInterface
    virtual com::sun::star::uno::Any SAL_CALL queryInterface(
                                        const ::com::sun::star::uno::Type & type )
                            throw( ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL acquire( void )
                            throw ( ::com::sun::star::uno::RuntimeException )
                                { OWeakObject::acquire(); }

    virtual void SAL_CALL release( void )
                            throw( ::com::sun::star::uno::RuntimeException )
                                { OWeakObject::release(); }

    // XInputStream
    virtual sal_Int32 SAL_CALL readBytes(
              ::com::sun::star::uno::Sequence< sal_Int8 > & aData,
            sal_Int32 nBytesToRead )
                throw( ::com::sun::star::io::NotConnectedException,
                          ::com::sun::star::io::BufferSizeExceededException,
                          ::com::sun::star::io::IOException,
                          ::com::sun::star::uno::RuntimeException );

    virtual sal_Int32 SAL_CALL readSomeBytes(
            ::com::sun::star::uno::Sequence< sal_Int8 > & aData,
            sal_Int32 nMaxBytesToRead )
                throw( ::com::sun::star::io::NotConnectedException,
                          ::com::sun::star::io::BufferSizeExceededException,
                          ::com::sun::star::io::IOException,
                          ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip )
                throw( ::com::sun::star::io::NotConnectedException,
                          ::com::sun::star::io::BufferSizeExceededException,
                          ::com::sun::star::io::IOException,
                          ::com::sun::star::uno::RuntimeException );

    virtual sal_Int32 SAL_CALL available( void )
                throw( ::com::sun::star::io::NotConnectedException,
                          ::com::sun::star::io::IOException,
                          ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL closeInput( void )
                throw( ::com::sun::star::io::NotConnectedException,
                          ::com::sun::star::io::IOException,
                          ::com::sun::star::uno::RuntimeException );

    // XSeekable
    virtual void SAL_CALL seek( sal_Int64 location )
        throw( ::com::sun::star::lang::IllegalArgumentException,
               ::com::sun::star::io::IOException,
               ::com::sun::star::uno::RuntimeException );

    virtual sal_Int64 SAL_CALL getPosition()
        throw( ::com::sun::star::io::IOException,
               ::com::sun::star::uno::RuntimeException );

    virtual sal_Int64 SAL_CALL getLength()
        throw( ::com::sun::star::io::IOException,
               ::com::sun::star::uno::RuntimeException );
};

}; // namespace webdav_ucp
#endif // _NEONINPUTSTREAM_HXX_
<commit_msg>#92924#: exception specifications<commit_after>/*************************************************************************
 *
 *  $RCSfile: NeonInputStream.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2001-11-08 13:13:31 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _NEONINPUTSTREAM_HXX_
#define _NEONINPUTSTREAM_HXX_

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_
#include <com/sun/star/io/XSeekable.hpp>
#endif

namespace webdav_ucp
{

// -------------------------------------------------------------------
// NeonInputStream
// A simple XInputStream implementation provided specifically for use
// by the DAVSession::GET method.
// -------------------------------------------------------------------
class NeonInputStream : public ::com::sun::star::io::XInputStream,
                        public ::com::sun::star::io::XSeekable,
                        public ::cppu::OWeakObject
{
    private:
        com::sun::star::uno::Sequence< sal_Int8 > mInputBuffer;
        sal_Int64 mLen;
        sal_Int64 mPos;

    public:
                 NeonInputStream( void );
        virtual ~NeonInputStream();

        // Add some data to the end of the stream
        void AddToStream( const char * inBuf, sal_Int32 inLen );

    // XInterface
    virtual com::sun::star::uno::Any SAL_CALL queryInterface(
                                        const ::com::sun::star::uno::Type & type )
                            throw( ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL acquire( void )
                            throw ()
                                { OWeakObject::acquire(); }

    virtual void SAL_CALL release( void )
                            throw()
                                { OWeakObject::release(); }

    // XInputStream
    virtual sal_Int32 SAL_CALL readBytes(
              ::com::sun::star::uno::Sequence< sal_Int8 > & aData,
            sal_Int32 nBytesToRead )
                throw( ::com::sun::star::io::NotConnectedException,
                          ::com::sun::star::io::BufferSizeExceededException,
                          ::com::sun::star::io::IOException,
                          ::com::sun::star::uno::RuntimeException );

    virtual sal_Int32 SAL_CALL readSomeBytes(
            ::com::sun::star::uno::Sequence< sal_Int8 > & aData,
            sal_Int32 nMaxBytesToRead )
                throw( ::com::sun::star::io::NotConnectedException,
                          ::com::sun::star::io::BufferSizeExceededException,
                          ::com::sun::star::io::IOException,
                          ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip )
                throw( ::com::sun::star::io::NotConnectedException,
                          ::com::sun::star::io::BufferSizeExceededException,
                          ::com::sun::star::io::IOException,
                          ::com::sun::star::uno::RuntimeException );

    virtual sal_Int32 SAL_CALL available( void )
                throw( ::com::sun::star::io::NotConnectedException,
                          ::com::sun::star::io::IOException,
                          ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL closeInput( void )
                throw( ::com::sun::star::io::NotConnectedException,
                          ::com::sun::star::io::IOException,
                          ::com::sun::star::uno::RuntimeException );

    // XSeekable
    virtual void SAL_CALL seek( sal_Int64 location )
        throw( ::com::sun::star::lang::IllegalArgumentException,
               ::com::sun::star::io::IOException,
               ::com::sun::star::uno::RuntimeException );

    virtual sal_Int64 SAL_CALL getPosition()
        throw( ::com::sun::star::io::IOException,
               ::com::sun::star::uno::RuntimeException );

    virtual sal_Int64 SAL_CALL getLength()
        throw( ::com::sun::star::io::IOException,
               ::com::sun::star::uno::RuntimeException );
};

}; // namespace webdav_ucp
#endif // _NEONINPUTSTREAM_HXX_
<|endoftext|>


<commit_before>// $Id$
// Author: Matevz Tadel 2009

/**************************************************************************
 * Copyright(c) 1998-2009, ALICE Experiment at CERN, all rights reserved. *
 * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for          *
 * full copyright notice.                                                 *
 **************************************************************************/

#include "AliEveMultiView.h"

//______________________________________________________________________________
// Full description of AliEveMultiView
//

ClassImp(AliEveMultiView)

AliEveMultiView* AliEveMultiView::fgInstance = 0;

AliEveMultiView* AliEveMultiView::Instance()
{
  // Return static instance.

  return fgInstance;
}

AliEveMultiView::AliEveMultiView() :
  fGeomGentle(0), fGeomGentleRPhi(0), fGeomGentleRhoZ(0),
  fGeomGentleTrd(0), fGeomGentleMuon(0)
{
  // Constructor --- creates required scenes, projection managers
  // and GL viewers.

  if (fgInstance)
    throw TEveException("AliEveMultiView::AliEveMultiView already instantiated.");
  fgInstance = this;

  // Scenes
  //========

  fRPhiGeomScene  = gEve->SpawnNewScene("RPhi Geometry",
                                        "Scene holding projected geometry for the RPhi view.");
  fRhoZGeomScene  = gEve->SpawnNewScene("RhoZ Geometry",
                                        "Scene holding projected geometry for the RhoZ view.");
  fRPhiEventScene = gEve->SpawnNewScene("RPhi Event Data",
                                        "Scene holding projected event-data for the RPhi view.");
  fRhoZEventScene = gEve->SpawnNewScene("RhoZ Event Data",
                                        "Scene holding projected event-data for the RhoZ view.");

  // Projection managers
  //=====================

  fRPhiMgr = new TEveProjectionManager();
  fRPhiMgr->SetProjection(TEveProjection::kPT_RPhi);
  gEve->AddToListTree(fRPhiMgr, kFALSE);
  {
    TEveProjectionAxes* a = new TEveProjectionAxes(fRPhiMgr);
    a->SetMainColor(kWhite);
    a->SetTitle("R-Phi");
    a->SetTitleSize(0.05);
    a->SetTitleFont(102);
    a->SetLabelSize(0.025);
    a->SetLabelFont(102);
    fRPhiGeomScene->AddElement(a);
  }

  fRhoZMgr = new TEveProjectionManager();
  fRhoZMgr->SetProjection(TEveProjection::kPT_RhoZ);
  gEve->AddToListTree(fRhoZMgr, kFALSE);
  {
    TEveProjectionAxes* a = new TEveProjectionAxes(fRhoZMgr);
    a->SetMainColor(kWhite);
    a->SetTitle("Rho-Z");
    a->SetTitleSize(0.05);
    a->SetTitleFont(102);
    a->SetLabelSize(0.025);
    a->SetLabelFont(102);
    fRhoZGeomScene->AddElement(a);
  }

  // Viewers
  //=========

  TEveWindowSlot *slot = 0;
  TEveWindowPack *pack = 0;

  slot = TEveWindow::CreateWindowInTab(gEve->GetBrowser()->GetTabRight());
  pack = slot->MakePack();
  pack->SetElementName("Multi View");
  pack->SetHorizontal();
  pack->SetShowTitleBar(kFALSE);
  pack->NewSlot()->MakeCurrent();
  f3DView = gEve->SpawnNewViewer("3D View", "");
  f3DView->AddScene(gEve->GetGlobalScene());
  f3DView->AddScene(gEve->GetEventScene());

  pack = pack->NewSlot()->MakePack();
  pack->SetShowTitleBar(kFALSE);
  pack->NewSlot()->MakeCurrent();
  fRPhiView = gEve->SpawnNewViewer("RPhi View", "");
  fRPhiView->GetGLViewer()->SetCurrentCamera(TGLViewer::kCameraOrthoXOY);
  fRPhiView->AddScene(fRPhiGeomScene);
  fRPhiView->AddScene(fRPhiEventScene);

  pack->NewSlot()->MakeCurrent();
  fRhoZView = gEve->SpawnNewViewer("RhoZ View", "");
  fRhoZView->GetGLViewer()->SetCurrentCamera(TGLViewer::kCameraOrthoXOY);
  fRhoZView->AddScene(fRhoZGeomScene);
  fRhoZView->AddScene(fRhoZEventScene);
}

//-------------------------------------------------------------------------

void AliEveMultiView::InitGeomGentle(TEveGeoShape* g3d, TEveGeoShape* grphi, TEveGeoShape* grhoz)
{
  // Initialize gentle geometry.

  fGeomGentle     = g3d;
  fGeomGentleRPhi = grphi; fGeomGentleRPhi->IncDenyDestroy();
  fGeomGentleRhoZ = grhoz; fGeomGentleRhoZ->IncDenyDestroy();

  ImportGeomRPhi(fGeomGentleRPhi);
  ImportGeomRhoZ(fGeomGentleRhoZ);
}

void AliEveMultiView::InitGeomGentleTrd(TEveGeoShape* gtrd)
{
  // Initialize gentle geometry TRD.

  fGeomGentleTrd = gtrd;
  ImportGeomRPhi(fGeomGentleTrd);
  ImportGeomRhoZ(fGeomGentleTrd);
}

void AliEveMultiView::InitGeomGentleMuon(TEveGeoShape* gmuon, Bool_t showRPhi, Bool_t showRhoZ)
{
  // Initialize gentle geometry for MUON.

  fGeomGentleMuon = gmuon;
  if (showRPhi) ImportGeomRPhi(fGeomGentleMuon);
  if (showRhoZ) ImportGeomRhoZ(fGeomGentleMuon);
}

//-------------------------------------------------------------------------

void AliEveMultiView::SetDepth(Float_t d)
{
  // Set current depth on all projection managers.

  fRPhiMgr->SetCurrentDepth(d);
  fRhoZMgr->SetCurrentDepth(d);
}

//-------------------------------------------------------------------------

void AliEveMultiView::ImportGeomRPhi(TEveElement* el)
{
  // Import el into r-phi geometry scene.

  fRPhiMgr->ImportElements(el, fRPhiGeomScene);
}

void AliEveMultiView::ImportGeomRhoZ(TEveElement* el)
{
  // Import el into rho-z geometry scene.

  fRhoZMgr->ImportElements(el, fRhoZGeomScene);
}

void AliEveMultiView::ImportEventRPhi(TEveElement* el)
{
  // Import el into r-phi event scene.

  fRPhiMgr->ImportElements(el, fRPhiEventScene);
}

void AliEveMultiView::ImportEventRhoZ(TEveElement* el)
{
  // Import el into rho-z event scene.

  fRhoZMgr->ImportElements(el, fRhoZEventScene);
}

void AliEveMultiView::DestroyEventRPhi()
{
  // Destroy all elements in r-phi event scene.

  fRPhiEventScene->DestroyElements();
}

void AliEveMultiView::DestroyEventRhoZ()
{
  // Destroy all elements in rho-z event scene.

  fRhoZEventScene->DestroyElements();
}

//-------------------------------------------------------------------------

void AliEveMultiView::SetCenterRPhi(Double_t x, Double_t y, Double_t z)
{
  // Set center of r-phi manager.

  fRPhiMgr->SetCenter(x, y, z);
}

void AliEveMultiView::SetCenterRhoZ(Double_t x, Double_t y, Double_t z)
{
  // Set center of rho-z manager.

  fRhoZMgr->SetCenter(x, y, z);
}

<commit_msg>Initialize all pointers in ctor.<commit_after>// $Id$
// Author: Matevz Tadel 2009

/**************************************************************************
 * Copyright(c) 1998-2009, ALICE Experiment at CERN, all rights reserved. *
 * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for          *
 * full copyright notice.                                                 *
 **************************************************************************/

#include "AliEveMultiView.h"

//______________________________________________________________________________
// Full description of AliEveMultiView
//

ClassImp(AliEveMultiView)

AliEveMultiView* AliEveMultiView::fgInstance = 0;

AliEveMultiView* AliEveMultiView::Instance()
{
  // Return static instance.

  return fgInstance;
}

AliEveMultiView::AliEveMultiView() :
  fRPhiMgr(0), fRhoZMgr(0),
  f3DView(0), fRPhiView(0), fRhoZView(0),
  fRPhiGeomScene(0), fRhoZGeomScene(0), fRPhiEventScene(0), fRhoZEventScene(0),
  fGeomGentle(0), fGeomGentleRPhi(0), fGeomGentleRhoZ(0),
  fGeomGentleTrd(0), fGeomGentleMuon(0)
{
  // Constructor --- creates required scenes, projection managers
  // and GL viewers.

  if (fgInstance)
    throw TEveException("AliEveMultiView::AliEveMultiView already instantiated.");
  fgInstance = this;

  // Scenes
  //========

  fRPhiGeomScene  = gEve->SpawnNewScene("RPhi Geometry",
                                        "Scene holding projected geometry for the RPhi view.");
  fRhoZGeomScene  = gEve->SpawnNewScene("RhoZ Geometry",
                                        "Scene holding projected geometry for the RhoZ view.");
  fRPhiEventScene = gEve->SpawnNewScene("RPhi Event Data",
                                        "Scene holding projected event-data for the RPhi view.");
  fRhoZEventScene = gEve->SpawnNewScene("RhoZ Event Data",
                                        "Scene holding projected event-data for the RhoZ view.");

  // Projection managers
  //=====================

  fRPhiMgr = new TEveProjectionManager();
  fRPhiMgr->SetProjection(TEveProjection::kPT_RPhi);
  gEve->AddToListTree(fRPhiMgr, kFALSE);
  {
    TEveProjectionAxes* a = new TEveProjectionAxes(fRPhiMgr);
    a->SetMainColor(kWhite);
    a->SetTitle("R-Phi");
    a->SetTitleSize(0.05);
    a->SetTitleFont(102);
    a->SetLabelSize(0.025);
    a->SetLabelFont(102);
    fRPhiGeomScene->AddElement(a);
  }

  fRhoZMgr = new TEveProjectionManager();
  fRhoZMgr->SetProjection(TEveProjection::kPT_RhoZ);
  gEve->AddToListTree(fRhoZMgr, kFALSE);
  {
    TEveProjectionAxes* a = new TEveProjectionAxes(fRhoZMgr);
    a->SetMainColor(kWhite);
    a->SetTitle("Rho-Z");
    a->SetTitleSize(0.05);
    a->SetTitleFont(102);
    a->SetLabelSize(0.025);
    a->SetLabelFont(102);
    fRhoZGeomScene->AddElement(a);
  }

  // Viewers
  //=========

  TEveWindowSlot *slot = 0;
  TEveWindowPack *pack = 0;

  slot = TEveWindow::CreateWindowInTab(gEve->GetBrowser()->GetTabRight());
  pack = slot->MakePack();
  pack->SetElementName("Multi View");
  pack->SetHorizontal();
  pack->SetShowTitleBar(kFALSE);
  pack->NewSlot()->MakeCurrent();
  f3DView = gEve->SpawnNewViewer("3D View", "");
  f3DView->AddScene(gEve->GetGlobalScene());
  f3DView->AddScene(gEve->GetEventScene());

  pack = pack->NewSlot()->MakePack();
  pack->SetShowTitleBar(kFALSE);
  pack->NewSlot()->MakeCurrent();
  fRPhiView = gEve->SpawnNewViewer("RPhi View", "");
  fRPhiView->GetGLViewer()->SetCurrentCamera(TGLViewer::kCameraOrthoXOY);
  fRPhiView->AddScene(fRPhiGeomScene);
  fRPhiView->AddScene(fRPhiEventScene);

  pack->NewSlot()->MakeCurrent();
  fRhoZView = gEve->SpawnNewViewer("RhoZ View", "");
  fRhoZView->GetGLViewer()->SetCurrentCamera(TGLViewer::kCameraOrthoXOY);
  fRhoZView->AddScene(fRhoZGeomScene);
  fRhoZView->AddScene(fRhoZEventScene);
}

//-------------------------------------------------------------------------

void AliEveMultiView::InitGeomGentle(TEveGeoShape* g3d, TEveGeoShape* grphi, TEveGeoShape* grhoz)
{
  // Initialize gentle geometry.

  fGeomGentle     = g3d;
  fGeomGentleRPhi = grphi; fGeomGentleRPhi->IncDenyDestroy();
  fGeomGentleRhoZ = grhoz; fGeomGentleRhoZ->IncDenyDestroy();

  ImportGeomRPhi(fGeomGentleRPhi);
  ImportGeomRhoZ(fGeomGentleRhoZ);
}

void AliEveMultiView::InitGeomGentleTrd(TEveGeoShape* gtrd)
{
  // Initialize gentle geometry TRD.

  fGeomGentleTrd = gtrd;
  ImportGeomRPhi(fGeomGentleTrd);
  ImportGeomRhoZ(fGeomGentleTrd);
}

void AliEveMultiView::InitGeomGentleMuon(TEveGeoShape* gmuon, Bool_t showRPhi, Bool_t showRhoZ)
{
  // Initialize gentle geometry for MUON.

  fGeomGentleMuon = gmuon;
  if (showRPhi) ImportGeomRPhi(fGeomGentleMuon);
  if (showRhoZ) ImportGeomRhoZ(fGeomGentleMuon);
}

//-------------------------------------------------------------------------

void AliEveMultiView::SetDepth(Float_t d)
{
  // Set current depth on all projection managers.

  fRPhiMgr->SetCurrentDepth(d);
  fRhoZMgr->SetCurrentDepth(d);
}

//-------------------------------------------------------------------------

void AliEveMultiView::ImportGeomRPhi(TEveElement* el)
{
  // Import el into r-phi geometry scene.

  fRPhiMgr->ImportElements(el, fRPhiGeomScene);
}

void AliEveMultiView::ImportGeomRhoZ(TEveElement* el)
{
  // Import el into rho-z geometry scene.

  fRhoZMgr->ImportElements(el, fRhoZGeomScene);
}

void AliEveMultiView::ImportEventRPhi(TEveElement* el)
{
  // Import el into r-phi event scene.

  fRPhiMgr->ImportElements(el, fRPhiEventScene);
}

void AliEveMultiView::ImportEventRhoZ(TEveElement* el)
{
  // Import el into rho-z event scene.

  fRhoZMgr->ImportElements(el, fRhoZEventScene);
}

void AliEveMultiView::DestroyEventRPhi()
{
  // Destroy all elements in r-phi event scene.

  fRPhiEventScene->DestroyElements();
}

void AliEveMultiView::DestroyEventRhoZ()
{
  // Destroy all elements in rho-z event scene.

  fRhoZEventScene->DestroyElements();
}

//-------------------------------------------------------------------------

void AliEveMultiView::SetCenterRPhi(Double_t x, Double_t y, Double_t z)
{
  // Set center of r-phi manager.

  fRPhiMgr->SetCenter(x, y, z);
}

void AliEveMultiView::SetCenterRhoZ(Double_t x, Double_t y, Double_t z)
{
  // Set center of rho-z manager.

  fRhoZMgr->SetCenter(x, y, z);
}

<|endoftext|>


<commit_before>/**
 * This file is part of the CernVM File System.
 */

#include "swissknife_reflog.h"

#include <cassert>

#include <string>
#include <vector>

#include "manifest.h"
#include "object_fetcher.h"
#include "upload_facility.h"

namespace swissknife {

typedef HttpObjectFetcher<> ObjectFetcher;

class RootChainWalker {
 public:
  typedef ObjectFetcher::CatalogTN CatalogTN;
  typedef ObjectFetcher::HistoryTN HistoryTN;

 public:
  RootChainWalker(const manifest::Manifest *manifest,
                  ObjectFetcher            *object_fetcher,
                  manifest::Reflog         *reflog)
    : object_fetcher_(object_fetcher)
    , reflog_(reflog)
    , manifest_(manifest) {}

  void FindObjectsAndPopulateReflog();

 protected:
  typedef std::vector<shash::Any> CatalogList;

 protected:
  CatalogTN* FetchCatalog(const shash::Any catalog_hash);
  HistoryTN* FetchHistory(const shash::Any history_hash);

  void WalkRootCatalogs(const shash::Any &root_catalog_hash);
  void WalkHistories(const shash::Any &history_hash);

  void WalkCatalogsInHistory(const HistoryTN *history);
  void WalkListedCatalogs(const CatalogList &catalog_list);

  template <class DatabaseT>
  DatabaseT* ReturnOrAbort(const ObjectFetcherFailures::Failures  failure,
                           const shash::Any                      &content_hash,
                           DatabaseT                             *database);

 private:
  ObjectFetcher            *object_fetcher_;
  manifest::Reflog         *reflog_;
  const manifest::Manifest *manifest_;
};

ParameterList CommandReconstructReflog::GetParams() const {
  ParameterList r;
  r.push_back(Parameter::Mandatory('r', "repository url"));
  r.push_back(Parameter::Mandatory('u', "spooler definition string"));
  r.push_back(Parameter::Mandatory('n', "fully qualified repository name"));
  r.push_back(Parameter::Mandatory('t', "temporary directory"));
  r.push_back(Parameter::Mandatory('k', "repository keychain"));
  r.push_back(Parameter::Mandatory('R', "path to reflog.chksum file"));
  return r;
}

int CommandReconstructReflog::Main(const ArgumentList &args) {
  const std::string &repo_url           = *args.find('r')->second;
  const std::string &spooler            = *args.find('u')->second;
  const std::string &repo_name          = *args.find('n')->second;
  const std::string &tmp_dir            = *args.find('t')->second;
  const std::string &repo_keys          = *args.find('k')->second;
  const std::string &reflog_chksum_path = *args.find('R')->second;

  const bool follow_redirects = false;
  if (!this->InitDownloadManager(follow_redirects) ||
      !this->InitVerifyingSignatureManager(repo_keys)) {
    LogCvmfs(kLogCvmfs, kLogStderr, "failed to init repo connection");
    return 1;
  }

  ObjectFetcher object_fetcher(repo_name,
                               repo_url,
                               tmp_dir,
                               download_manager(),
                               signature_manager());

  UniquePtr<manifest::Manifest> manifest;
  ObjectFetcher::Failures retval = object_fetcher.FetchManifest(&manifest);
  if (retval != ObjectFetcher::kFailOk) {
    LogCvmfs(kLogCvmfs, kLogStderr, "failed to load repository manifest "
                                    "(%d - %s)",
                                    retval, Code2Ascii(retval));
    return 1;
  }

  const upload::SpoolerDefinition spooler_definition(spooler, shash::kAny);
  UniquePtr<upload::AbstractUploader> uploader(
                       upload::AbstractUploader::Construct(spooler_definition));

  if (!uploader.IsValid()) {
    LogCvmfs(kLogCvmfs, kLogStderr, "failed to initialize spooler for '%s'",
             spooler.c_str());
    return 1;
  }

  UniquePtr<manifest::Reflog> reflog(CreateEmptyReflog(tmp_dir, repo_name));
  reflog->TakeDatabaseFileOwnership();

  reflog->BeginTransaction();
  AddStaticManifestObjects(reflog.weak_ref(), manifest.weak_ref());
  RootChainWalker walker(manifest.weak_ref(),
                         &object_fetcher,
                         reflog.weak_ref());
  walker.FindObjectsAndPopulateReflog();
  reflog->CommitTransaction();

  LogCvmfs(kLogCvmfs, kLogStdout, "found %d entries", reflog->CountEntries());

  reflog->DropDatabaseFileOwnership();
  const std::string reflog_db = reflog->database_file();
  reflog.Destroy();
  uploader->Upload(reflog_db, ".cvmfsreflog");
  shash::Any reflog_hash(manifest->GetHashAlgorithm());
  manifest::Reflog::HashDatabase(reflog_db, &reflog_hash);
  uploader->WaitForUpload();
  unlink(reflog_db.c_str());

  const int errors = uploader->GetNumberOfErrors();
  if (errors > 0) {
    LogCvmfs(kLogCvmfs, kLogStderr, "failed to upload generated Reflog");
  }

  uploader->TearDown();

  manifest::Reflog::WriteChecksum(reflog_chksum_path, reflog_hash);

  return (errors == 0) ? 0 : 1;
}

void CommandReconstructReflog::AddStaticManifestObjects(
                                          manifest::Reflog    *reflog,
                                          manifest::Manifest  *manifest) const {
  const shash::Any certificate = manifest->certificate();
  const shash::Any meta_info   = manifest->meta_info();
  assert(!certificate.IsNull());

  bool success = reflog->AddCertificate(certificate);
  assert(success);
  LogCvmfs(kLogCvmfs, kLogStdout, "Certificate: %s",
           certificate.ToString().c_str());

  if (!meta_info.IsNull()) {
    success = reflog->AddMetainfo(meta_info);
    assert(success);
    LogCvmfs(kLogCvmfs, kLogStdout, "Metainfo: %s",
             meta_info.ToString().c_str());
  }
}

void RootChainWalker::FindObjectsAndPopulateReflog() {
  const shash::Any root_catalog = manifest_->catalog_hash();
  const shash::Any history      = manifest_->history();

  assert(!root_catalog.IsNull());
  WalkRootCatalogs(root_catalog);

  if (!history.IsNull()) {
    WalkHistories(history);
  }
}

void RootChainWalker::WalkRootCatalogs(const shash::Any &root_catalog_hash) {
  shash::Any           current_hash = root_catalog_hash;
  UniquePtr<CatalogTN> current_catalog;

  while (!current_hash.IsNull()                  &&
         !reflog_->ContainsCatalog(current_hash) &&
         (current_catalog = FetchCatalog(current_hash)).IsValid()) {
    LogCvmfs(kLogCvmfs, kLogStdout, "Catalog: %s Revision: %d",
             current_hash.ToString().c_str(), current_catalog->GetRevision());

    const bool success = reflog_->AddCatalog(current_hash);
    assert(success);

    current_hash = current_catalog->GetPreviousRevision();
  }
}

void RootChainWalker::WalkHistories(const shash::Any &history_hash) {
  shash::Any           current_hash = history_hash;
  UniquePtr<HistoryTN> current_history;

  while (!current_hash.IsNull()                  &&
         !reflog_->ContainsHistory(current_hash) &&
         (current_history = FetchHistory(current_hash)).IsValid()) {
    LogCvmfs(kLogCvmfs, kLogStdout, "History: %s",
             current_hash.ToString().c_str());

    WalkCatalogsInHistory(current_history);
    const bool success = reflog_->AddHistory(current_hash);
    assert(success);

    current_hash = current_history->previous_revision();
  }
}

void RootChainWalker::WalkCatalogsInHistory(const HistoryTN *history) {
  CatalogList tag_hashes;
  const bool list_success = history->GetHashes(&tag_hashes);
  assert(list_success);

  CatalogList bin_hashes;
  const bool bin_success = history->ListRecycleBin(&bin_hashes);
  assert(bin_success);

  WalkListedCatalogs(tag_hashes);
  WalkListedCatalogs(bin_hashes);
}

void RootChainWalker::WalkListedCatalogs(
                             const RootChainWalker::CatalogList &catalog_list) {
  CatalogList::const_iterator i    = catalog_list.begin();
  CatalogList::const_iterator iend = catalog_list.end();
  for (; i != iend; ++i) {
    WalkRootCatalogs(*i);
  }
}

RootChainWalker::CatalogTN* RootChainWalker::FetchCatalog(
                                                const shash::Any catalog_hash) {
  CatalogTN *catalog = NULL;
  const char *root_path = "";
  ObjectFetcherFailures::Failures failure =
    object_fetcher_->FetchCatalog(catalog_hash, root_path, &catalog);

  return ReturnOrAbort(failure, catalog_hash, catalog);
}

RootChainWalker::HistoryTN* RootChainWalker::FetchHistory(
                                                const shash::Any history_hash) {
  HistoryTN *history = NULL;
  ObjectFetcherFailures::Failures failure =
    object_fetcher_->FetchHistory(&history, history_hash);

  return ReturnOrAbort(failure, history_hash, history);
}

template <class DatabaseT>
DatabaseT* RootChainWalker::ReturnOrAbort(
                            const ObjectFetcherFailures::Failures  failure,
                            const shash::Any                      &content_hash,
                            DatabaseT                             *database) {
  switch (failure) {
    case ObjectFetcherFailures::kFailOk:
      return database;
    case ObjectFetcherFailures::kFailNotFound:
      return NULL;
    default:
      LogCvmfs(kLogCvmfs, kLogStderr, "Failed to load object '%s' (%d - %s)",
                                      content_hash.ToStringWithSuffix().c_str(),
                                      failure, Code2Ascii(failure));
      abort();
  }
}

}  // namespace swissknife
<commit_msg>less agressive database checks on reflog reconstruction (for cernvm-prod.cern.ch)<commit_after>/**
 * This file is part of the CernVM File System.
 */

#include "swissknife_reflog.h"

#include <cassert>

#include <string>
#include <vector>

#include "manifest.h"
#include "object_fetcher.h"
#include "upload_facility.h"

namespace swissknife {

typedef HttpObjectFetcher<> ObjectFetcher;

class RootChainWalker {
 public:
  typedef ObjectFetcher::CatalogTN CatalogTN;
  typedef ObjectFetcher::HistoryTN HistoryTN;

 public:
  RootChainWalker(const manifest::Manifest *manifest,
                  ObjectFetcher            *object_fetcher,
                  manifest::Reflog         *reflog)
    : object_fetcher_(object_fetcher)
    , reflog_(reflog)
    , manifest_(manifest) {}

  void FindObjectsAndPopulateReflog();

 protected:
  typedef std::vector<shash::Any> CatalogList;

 protected:
  CatalogTN* FetchCatalog(const shash::Any catalog_hash);
  HistoryTN* FetchHistory(const shash::Any history_hash);

  void WalkRootCatalogs(const shash::Any &root_catalog_hash);
  void WalkHistories(const shash::Any &history_hash);

  void WalkCatalogsInHistory(const HistoryTN *history);
  void WalkListedCatalogs(const CatalogList &catalog_list);

  template <class DatabaseT>
  DatabaseT* ReturnOrAbort(const ObjectFetcherFailures::Failures  failure,
                           const shash::Any                      &content_hash,
                           DatabaseT                             *database);

 private:
  ObjectFetcher            *object_fetcher_;
  manifest::Reflog         *reflog_;
  const manifest::Manifest *manifest_;
};

ParameterList CommandReconstructReflog::GetParams() const {
  ParameterList r;
  r.push_back(Parameter::Mandatory('r', "repository url"));
  r.push_back(Parameter::Mandatory('u', "spooler definition string"));
  r.push_back(Parameter::Mandatory('n', "fully qualified repository name"));
  r.push_back(Parameter::Mandatory('t', "temporary directory"));
  r.push_back(Parameter::Mandatory('k', "repository keychain"));
  r.push_back(Parameter::Mandatory('R', "path to reflog.chksum file"));
  return r;
}

int CommandReconstructReflog::Main(const ArgumentList &args) {
  const std::string &repo_url           = *args.find('r')->second;
  const std::string &spooler            = *args.find('u')->second;
  const std::string &repo_name          = *args.find('n')->second;
  const std::string &tmp_dir            = *args.find('t')->second;
  const std::string &repo_keys          = *args.find('k')->second;
  const std::string &reflog_chksum_path = *args.find('R')->second;

  const bool follow_redirects = false;
  if (!this->InitDownloadManager(follow_redirects) ||
      !this->InitVerifyingSignatureManager(repo_keys)) {
    LogCvmfs(kLogCvmfs, kLogStderr, "failed to init repo connection");
    return 1;
  }

  ObjectFetcher object_fetcher(repo_name,
                               repo_url,
                               tmp_dir,
                               download_manager(),
                               signature_manager());

  UniquePtr<manifest::Manifest> manifest;
  ObjectFetcher::Failures retval = object_fetcher.FetchManifest(&manifest);
  if (retval != ObjectFetcher::kFailOk) {
    LogCvmfs(kLogCvmfs, kLogStderr, "failed to load repository manifest "
                                    "(%d - %s)",
                                    retval, Code2Ascii(retval));
    return 1;
  }

  const upload::SpoolerDefinition spooler_definition(spooler, shash::kAny);
  UniquePtr<upload::AbstractUploader> uploader(
                       upload::AbstractUploader::Construct(spooler_definition));

  if (!uploader.IsValid()) {
    LogCvmfs(kLogCvmfs, kLogStderr, "failed to initialize spooler for '%s'",
             spooler.c_str());
    return 1;
  }

  UniquePtr<manifest::Reflog> reflog(CreateEmptyReflog(tmp_dir, repo_name));
  reflog->TakeDatabaseFileOwnership();

  reflog->BeginTransaction();
  AddStaticManifestObjects(reflog.weak_ref(), manifest.weak_ref());
  RootChainWalker walker(manifest.weak_ref(),
                         &object_fetcher,
                         reflog.weak_ref());
  walker.FindObjectsAndPopulateReflog();
  reflog->CommitTransaction();

  LogCvmfs(kLogCvmfs, kLogStdout, "found %d entries", reflog->CountEntries());

  reflog->DropDatabaseFileOwnership();
  const std::string reflog_db = reflog->database_file();
  reflog.Destroy();
  uploader->Upload(reflog_db, ".cvmfsreflog");
  shash::Any reflog_hash(manifest->GetHashAlgorithm());
  manifest::Reflog::HashDatabase(reflog_db, &reflog_hash);
  uploader->WaitForUpload();
  unlink(reflog_db.c_str());

  const int errors = uploader->GetNumberOfErrors();
  if (errors > 0) {
    LogCvmfs(kLogCvmfs, kLogStderr, "failed to upload generated Reflog");
  }

  uploader->TearDown();

  manifest::Reflog::WriteChecksum(reflog_chksum_path, reflog_hash);

  return (errors == 0) ? 0 : 1;
}

void CommandReconstructReflog::AddStaticManifestObjects(
                                          manifest::Reflog    *reflog,
                                          manifest::Manifest  *manifest) const {
  const shash::Any certificate = manifest->certificate();
  const shash::Any meta_info   = manifest->meta_info();
  assert(!certificate.IsNull());

  bool success = reflog->AddCertificate(certificate);
  assert(success);
  LogCvmfs(kLogCvmfs, kLogStdout, "Certificate: %s",
           certificate.ToString().c_str());

  if (!meta_info.IsNull()) {
    success = reflog->AddMetainfo(meta_info);
    assert(success);
    LogCvmfs(kLogCvmfs, kLogStdout, "Metainfo: %s",
             meta_info.ToString().c_str());
  }
}

void RootChainWalker::FindObjectsAndPopulateReflog() {
  const shash::Any root_catalog = manifest_->catalog_hash();
  const shash::Any history      = manifest_->history();

  assert(!root_catalog.IsNull());
  WalkRootCatalogs(root_catalog);

  if (!history.IsNull()) {
    WalkHistories(history);
  }
}

void RootChainWalker::WalkRootCatalogs(const shash::Any &root_catalog_hash) {
  shash::Any           current_hash = root_catalog_hash;
  UniquePtr<CatalogTN> current_catalog;

  while (!current_hash.IsNull()                  &&
         !reflog_->ContainsCatalog(current_hash) &&
         (current_catalog = FetchCatalog(current_hash)).IsValid()) {
    LogCvmfs(kLogCvmfs, kLogStdout, "Catalog: %s Revision: %d",
             current_hash.ToString().c_str(), current_catalog->GetRevision());

    const bool success = reflog_->AddCatalog(current_hash);
    assert(success);

    current_hash = current_catalog->GetPreviousRevision();
  }
}

void RootChainWalker::WalkHistories(const shash::Any &history_hash) {
  shash::Any           current_hash = history_hash;
  UniquePtr<HistoryTN> current_history;

  while (!current_hash.IsNull()                  &&
         !reflog_->ContainsHistory(current_hash) &&
         (current_history = FetchHistory(current_hash)).IsValid()) {
    LogCvmfs(kLogCvmfs, kLogStdout, "History: %s",
             current_hash.ToString().c_str());

    WalkCatalogsInHistory(current_history);
    const bool success = reflog_->AddHistory(current_hash);
    assert(success);

    current_hash = current_history->previous_revision();
  }
}

void RootChainWalker::WalkCatalogsInHistory(const HistoryTN *history) {
  CatalogList tag_hashes;
  const bool list_success = history->GetHashes(&tag_hashes);
  assert(list_success);

  CatalogList bin_hashes;
  const bool bin_success = history->ListRecycleBin(&bin_hashes);
  if (!bin_success) {
    LogCvmfs(kLogCvmfs, kLogStderr, "  Warning: 'recycle bin' table missing");
  }

  WalkListedCatalogs(tag_hashes);
  WalkListedCatalogs(bin_hashes);
}

void RootChainWalker::WalkListedCatalogs(
                             const RootChainWalker::CatalogList &catalog_list) {
  CatalogList::const_iterator i    = catalog_list.begin();
  CatalogList::const_iterator iend = catalog_list.end();
  for (; i != iend; ++i) {
    WalkRootCatalogs(*i);
  }
}

RootChainWalker::CatalogTN* RootChainWalker::FetchCatalog(
                                                const shash::Any catalog_hash) {
  CatalogTN *catalog = NULL;
  const char *root_path = "";
  ObjectFetcherFailures::Failures failure =
    object_fetcher_->FetchCatalog(catalog_hash, root_path, &catalog);

  return ReturnOrAbort(failure, catalog_hash, catalog);
}

RootChainWalker::HistoryTN* RootChainWalker::FetchHistory(
                                                const shash::Any history_hash) {
  HistoryTN *history = NULL;
  ObjectFetcherFailures::Failures failure =
    object_fetcher_->FetchHistory(&history, history_hash);

  return ReturnOrAbort(failure, history_hash, history);
}

template <class DatabaseT>
DatabaseT* RootChainWalker::ReturnOrAbort(
                            const ObjectFetcherFailures::Failures  failure,
                            const shash::Any                      &content_hash,
                            DatabaseT                             *database) {
  switch (failure) {
    case ObjectFetcherFailures::kFailOk:
      return database;
    case ObjectFetcherFailures::kFailNotFound:
      return NULL;
    default:
      LogCvmfs(kLogCvmfs, kLogStderr, "Failed to load object '%s' (%d - %s)",
                                      content_hash.ToStringWithSuffix().c_str(),
                                      failure, Code2Ascii(failure));
      abort();
  }
}

}  // namespace swissknife
<|endoftext|>


<commit_before>// -*- c++ -*- ///////////////////////////////////////////////////////////////
//
// This file is part of Miro (The Middleware for Robots)
// Copyright (C) 1999-2013
// Department of Neural Information Processing, University of Ulm
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//

#include "FileListDialog.h"

#include <QGroupBox>
#include <QWidget>
#include <qlayout.h>
#include <qpushbutton.h>
#include <qmessagebox.h>
#include <QListWidget>
#include <qstringlist.h>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <cassert>

FileListDialog::FileListDialog(QWidget* parent,
			       QString const& _dialogTitle,
			       QString const& _listTitle,
			       char const * _filters[]) :
  QDialog(parent, "FileListDialog", TRUE),       // TRUE = modal dialog
  list_(NULL),
  delButton_(NULL),
  fileDialog_(NULL),
  modified_(false)
{
  resize(300, 200);
  setCaption(_dialogTitle);

  // Create and configure the layout for the FileListDialog
  QVBoxLayout * const pFileListDialogLayout = createLayout();
  assert(pFileListDialogLayout != NULL);

  // Create the upper pane, contining the ListBox of file pathnames and the
  // "Add" and "Remove" buttons
  const QString fileBoxTitle("");
  QGroupBox * const pFileBox = new QGroupBox(fileBoxTitle);
  assert(pFileBox != NULL);

  // The ListBox is above the pane that contains the buttons
  QVBoxLayout * const pFileBoxLayout = new QVBoxLayout;
  assert(pFileBoxLayout != NULL);
  pFileBox->setLayout(pFileBoxLayout);

  // Create the QListWidget that contains the file pathnames
  list_ = new QListWidget;
  // Add the List Widget to the Group Box's Layout
  pFileBoxLayout->addWidget(list_);

  createFileButtonsBox(pFileBoxLayout);

  // Create the dialog for soliciting the pathname
  createDialogBox(_dialogTitle, _filters);

  pFileListDialogLayout->addSpacing(10);
  // The ListBox goes on top
  pFileListDialogLayout->addWidget(pFileBox);
  // The title for the ListBox
  pFileBox->setTitle(_listTitle);

  pFileListDialogLayout->addSpacing(10);
  createDialogButtonsBox(pFileListDialogLayout);

  selectListItem();
}

FileListDialog::~FileListDialog()
{
}

void
FileListDialog::init(const QStringList& _list)
{
  // fill list with current parameters
  modified_ = false;
  // Remove any existing items
  list_->clear();
  // Insert at the beginning
  const int row = 0;
  // Create a ListBoxItem for each Parameter Description File pathname in _list
  list_->insertItems(row, _list);
  // Select the first item, if any
  selectListItem();
}

void
FileListDialog::selectListItem()
{
  // Precondition
  assert(list_ != NULL);
  if (list_->count() != 0)
  {
    // Select the current item, or item 0 if there is no current item
    QListWidgetItem * const pCurrentItem = list_->currentItem();
    if (pCurrentItem)
    {
      // There is a current item; select it
      pCurrentItem->setSelected(true);
    }
    else
    {
      // There is no current item; make item 0 current and select it
      list_->setCurrentRow(0);
      assert(list_->currentItem() != NULL);
      list_->currentItem()->setSelected(true);
    }
  }
  // If the list is not empty, enable the Delete button
  delButton_->setEnabled(list_->count() > 0);
}

/**
 * Return a QStringList of the Parameter Description File pathnames in list_.
 */
QStringList
FileListDialog::result()
{
  // Precondition
  assert(list_ != NULL);

  // The return value
  QStringList list;
  for (int i = 0; i < list_->count(); ++i)
  {
    // Append the QListWidgetItem's label to list
    const QListWidgetItem * const pItem = list_->item(i);
    assert(pItem != NULL);
    const QString& s = pItem->text();
    list.append(s);
  }

  return list;
}

void
FileListDialog::add()
{
  // Precondition
  assert(fileDialog_ != NULL);
  assert(list_ != NULL);

  if (fileDialog_->exec() == QDialog::Accepted ) {
    const QStringList selectedFileNames = fileDialog_->selectedFiles();
    const int count = selectedFileNames.size();
    assert(count > 0); // If accepted, there must be one

    QStringList duplicates;
    for (int i = 0; i < count; i++)
    {
      const QString& selectedFileName = selectedFileNames.at(i);

      // Search for the file name among the QListWidget items
      // This is case insensitive. Use Qt::MatchCaseSensitive or Qt::MatchExactly?
      Qt::MatchFlags flags = Qt::MatchFixedString;
      const QList<QListWidgetItem*> found =
	list_->findItems(selectedFileName, flags);
      if (found.empty())
      {
	// The selected file name was not already in the QListWidget; insert it
	// at the end
	const int endRow = list_->count();
	list_->insertItem(endRow, selectedFileName);
	// Record that the QListWidget has been modified
	modified_ = true;
      } else {
	duplicates.append(selectedFileName);
      }
    }
    if (!duplicates.isEmpty())
    {
      const QString title("Duplicated file(s)");
      QString text("The following selected files are already part of the file list:");
      for (int i = 0; i < duplicates.size(); ++i)
      {
	text.append("\n");
	text.append(duplicates.at(i));
      }
      QMessageBox::warning(this, title, text);
    }
  }

  selectListItem();
}

void
FileListDialog::del() {
  // Precondition
  assert(list_ != 0);

  QListWidgetItem * const pCurrentItem = list_->currentItem();
  if (pCurrentItem != NULL)
  {
    const int row = list_->row(pCurrentItem);
    const QListWidgetItem * const pItem = list_->takeItem(row);
    // Items removed from a list widget will not be managed by Qt, and will
    // need to be deleted manually.
    delete pItem;
    modified_ = true;
  }

  selectListItem();
}

void
FileListDialog::createDialogBox(const QString& title, const char * filters[])
{
  QWidget * const fdParent = this;
  const QString caption(title);
  const QString directory;
  QString filter;
  if (filters)
  {
    // A non-NULL filters argument was passed to the constructor
    for (int i = 0; filters[i] != NULL; ++i)
    {
      if (i != 0)
      {
	filter.append(";;");
      }
      filter.append(filters[i]);
    }
  }
  else
  {
    // A NULL filters aregument was passed to the constructor
    filter = "all files (*)";
  }
  fileDialog_ = new QFileDialog(fdParent, caption, directory, filter);
  assert(fileDialog_ != NULL);
  // The names of zero or more existing files
  fileDialog_->setFileMode(QFileDialog::ExistingFiles);
}

void
FileListDialog::createFileButtonsBox(QVBoxLayout * const pFileBoxLayout)
{
  // Create the widget to hold the Add and Remove buttons, arrayed horizontally
  QWidget * const pFileButtonsBox = new QWidget;
  assert(pFileButtonsBox != NULL);

  // Create and set its Layout
  QHBoxLayout * const pFileButtonsBoxLayout = new QHBoxLayout;
  assert(pFileButtonsBoxLayout != NULL);
  pFileButtonsBox->setLayout(pFileButtonsBoxLayout);

  // Create the Add button and add it to the layout
  const QString addButtonText("Add...");
  QPushButton * const addButton = new QPushButton(addButtonText);
  assert(addButton != NULL);
  pFileButtonsBoxLayout->addWidget(addButton);

  // Create the Remove button and add it to the layout
  const QString delButtonText("Remove");
  delButton_ = new QPushButton(delButtonText);
  assert(delButton_ != NULL);
  pFileButtonsBoxLayout->addWidget(delButton_);

  pFileBoxLayout->addWidget(pFileButtonsBox);

  connect(addButton,    SIGNAL(clicked()), SLOT(add()));
  connect(delButton_,   SIGNAL(clicked()), SLOT(del()));
}

void
FileListDialog::createDialogButtonsBox(QVBoxLayout * const pFileListDialogLayout)
{
  // Create the Widget
  QWidget * const pDialogButtonsBox = new QWidget();
  assert(pDialogButtonsBox != NULL);

  // Create the Layout
  QHBoxLayout * const pDialogButtonsBoxLayout = new QHBoxLayout;
  assert(pDialogButtonsBoxLayout != NULL);

  pDialogButtonsBox->setLayout(pDialogButtonsBoxLayout);
  // Use the value of the margin for the spacing
  pDialogButtonsBoxLayout->setSpacing(-1);

  QSpacerItem * dBSpace = new QSpacerItem(0, 0);
  QPushButton * okButton = new QPushButton("OK", this);
  QPushButton * cancelButton = new QPushButton("Cancel", this);

  pFileListDialogLayout->addSpacing(5);
  pDialogButtonsBoxLayout->addItem(dBSpace);
  pDialogButtonsBoxLayout->addWidget(okButton);
  pDialogButtonsBoxLayout->addSpacing(5);
  pDialogButtonsBoxLayout->addWidget(cancelButton);
  pDialogButtonsBoxLayout->addSpacing(5);
  okButton->setDefault(true);

  // connect the dialogs functionality
  connect(okButton,     SIGNAL(clicked()), SLOT(accept()));
  connect(cancelButton, SIGNAL(clicked()), SLOT(reject()));

  // Add the Widget to its Layout
  pFileListDialogLayout->addWidget(pDialogButtonsBox);
}

QVBoxLayout *
FileListDialog::createLayout()
{
  QVBoxLayout * const pFileListDialogLayout = new QVBoxLayout;
  assert(pFileListDialogLayout != NULL);
  const int margin = 0;
  pFileListDialogLayout->setContentsMargins(margin, margin, margin, margin);
  // The spacing is the same as the margin
  const int spacing = margin;
  pFileListDialogLayout->setSpacing(spacing);
  this->setLayout(pFileListDialogLayout);

  return pFileListDialogLayout;
}
<commit_msg>No longer display the QMessageBox when Parameter Description Files are added redundantly.<commit_after>// -*- c++ -*- ///////////////////////////////////////////////////////////////
//
// This file is part of Miro (The Middleware for Robots)
// Copyright (C) 1999-2013
// Department of Neural Information Processing, University of Ulm
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//

#include "FileListDialog.h"

#include <QGroupBox>
#include <QWidget>
#include <qlayout.h>
#include <qpushbutton.h>
#include <qmessagebox.h>
#include <QListWidget>
#include <qstringlist.h>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <cassert>

FileListDialog::FileListDialog(QWidget* parent,
			       QString const& _dialogTitle,
			       QString const& _listTitle,
			       char const * _filters[]) :
  QDialog(parent, "FileListDialog", TRUE),       // TRUE = modal dialog
  list_(NULL),
  delButton_(NULL),
  fileDialog_(NULL),
  modified_(false)
{
  resize(300, 200);
  setCaption(_dialogTitle);

  // Create and configure the layout for the FileListDialog
  QVBoxLayout * const pFileListDialogLayout = createLayout();
  assert(pFileListDialogLayout != NULL);

  // Create the upper pane, contining the ListBox of file pathnames and the
  // "Add" and "Remove" buttons
  const QString fileBoxTitle("");
  QGroupBox * const pFileBox = new QGroupBox(fileBoxTitle);
  assert(pFileBox != NULL);

  // The ListBox is above the pane that contains the buttons
  QVBoxLayout * const pFileBoxLayout = new QVBoxLayout;
  assert(pFileBoxLayout != NULL);
  pFileBox->setLayout(pFileBoxLayout);

  // Create the QListWidget that contains the file pathnames
  list_ = new QListWidget;
  // Add the List Widget to the Group Box's Layout
  pFileBoxLayout->addWidget(list_);

  createFileButtonsBox(pFileBoxLayout);

  // Create the dialog for soliciting the pathname
  createDialogBox(_dialogTitle, _filters);

  pFileListDialogLayout->addSpacing(10);
  // The ListBox goes on top
  pFileListDialogLayout->addWidget(pFileBox);
  // The title for the ListBox
  pFileBox->setTitle(_listTitle);

  pFileListDialogLayout->addSpacing(10);
  createDialogButtonsBox(pFileListDialogLayout);

  selectListItem();
}

FileListDialog::~FileListDialog()
{
}

void
FileListDialog::init(const QStringList& _list)
{
  // fill list with current parameters
  modified_ = false;
  // Remove any existing items
  list_->clear();
  // Insert at the beginning
  const int row = 0;
  // Create a ListBoxItem for each Parameter Description File pathname in _list
  list_->insertItems(row, _list);
  // Select the first item, if any
  selectListItem();
}

void
FileListDialog::selectListItem()
{
  // Precondition
  assert(list_ != NULL);
  if (list_->count() != 0)
  {
    // Select the current item, or item 0 if there is no current item
    QListWidgetItem * const pCurrentItem = list_->currentItem();
    if (pCurrentItem)
    {
      // There is a current item; select it
      pCurrentItem->setSelected(true);
    }
    else
    {
      // There is no current item; make item 0 current and select it
      list_->setCurrentRow(0);
      assert(list_->currentItem() != NULL);
      list_->currentItem()->setSelected(true);
    }
  }
  // If the list is not empty, enable the Delete button
  delButton_->setEnabled(list_->count() > 0);
}

/**
 * Return a QStringList of the Parameter Description File pathnames in list_.
 */
QStringList
FileListDialog::result()
{
  // Precondition
  assert(list_ != NULL);

  // The return value
  QStringList list;
  for (int i = 0; i < list_->count(); ++i)
  {
    // Append the QListWidgetItem's label to list
    const QListWidgetItem * const pItem = list_->item(i);
    assert(pItem != NULL);
    const QString& s = pItem->text();
    list.append(s);
  }

  return list;
}

void
FileListDialog::add()
{
  // Precondition
  assert(fileDialog_ != NULL);
  assert(list_ != NULL);

  if (fileDialog_->exec() == QDialog::Accepted ) {
    const QStringList selectedFileNames = fileDialog_->selectedFiles();
    const int count = selectedFileNames.size();
    assert(count > 0); // If accepted, there must be one

    QStringList duplicates;
    for (int i = 0; i < count; i++)
    {
      const QString& selectedFileName = selectedFileNames.at(i);

      // Search for the file name among the QListWidget items
      // This is case insensitive. Use Qt::MatchCaseSensitive or Qt::MatchExactly?
      Qt::MatchFlags flags = Qt::MatchFixedString;
      const QList<QListWidgetItem*> found =
	list_->findItems(selectedFileName, flags);
      if (found.empty())
      {
	// The selected file name was not already in the QListWidget; insert it
	// at the end
	const int endRow = list_->count();
	list_->insertItem(endRow, selectedFileName);
	// Record that the QListWidget has been modified
	modified_ = true;
      } else {
	duplicates.append(selectedFileName);
      }
    }
    if (!duplicates.isEmpty())
    {
      const QString title("Duplicated file(s)");
      QString text("The following selected files are already part of the file list:");
      for (int i = 0; i < duplicates.size(); ++i)
      {
	text.append("\n");
	text.append(duplicates.at(i));
      }
#if (0)
      /*
       * The text in the QMessageBox can be so long that the dismiss button
       * is not visible. At the request of Mark Allan, this QMessageBox is
       * no longer displayed. The text is still built in case it can be used
       * in some other way, such as writing to standard output or a log file.
       * If this feature is to be removed completely, remove the definition
       * of local variable "duplicates" and all the code that depends on
       * that definition.
       */
      QMessageBox::warning(this, title, text);
#endif
    }
  }

  selectListItem();
}

void
FileListDialog::del() {
  // Precondition
  assert(list_ != 0);

  QListWidgetItem * const pCurrentItem = list_->currentItem();
  if (pCurrentItem != NULL)
  {
    const int row = list_->row(pCurrentItem);
    const QListWidgetItem * const pItem = list_->takeItem(row);
    // Items removed from a list widget will not be managed by Qt, and will
    // need to be deleted manually.
    delete pItem;
    modified_ = true;
  }

  selectListItem();
}

void
FileListDialog::createDialogBox(const QString& title, const char * filters[])
{
  QWidget * const fdParent = this;
  const QString caption(title);
  const QString directory;
  QString filter;
  if (filters)
  {
    // A non-NULL filters argument was passed to the constructor
    for (int i = 0; filters[i] != NULL; ++i)
    {
      if (i != 0)
      {
	filter.append(";;");
      }
      filter.append(filters[i]);
    }
  }
  else
  {
    // A NULL filters aregument was passed to the constructor
    filter = "all files (*)";
  }
  fileDialog_ = new QFileDialog(fdParent, caption, directory, filter);
  assert(fileDialog_ != NULL);
  // The names of zero or more existing files
  fileDialog_->setFileMode(QFileDialog::ExistingFiles);
}

void
FileListDialog::createFileButtonsBox(QVBoxLayout * const pFileBoxLayout)
{
  // Create the widget to hold the Add and Remove buttons, arrayed horizontally
  QWidget * const pFileButtonsBox = new QWidget;
  assert(pFileButtonsBox != NULL);

  // Create and set its Layout
  QHBoxLayout * const pFileButtonsBoxLayout = new QHBoxLayout;
  assert(pFileButtonsBoxLayout != NULL);
  pFileButtonsBox->setLayout(pFileButtonsBoxLayout);

  // Create the Add button and add it to the layout
  const QString addButtonText("Add...");
  QPushButton * const addButton = new QPushButton(addButtonText);
  assert(addButton != NULL);
  pFileButtonsBoxLayout->addWidget(addButton);

  // Create the Remove button and add it to the layout
  const QString delButtonText("Remove");
  delButton_ = new QPushButton(delButtonText);
  assert(delButton_ != NULL);
  pFileButtonsBoxLayout->addWidget(delButton_);

  pFileBoxLayout->addWidget(pFileButtonsBox);

  connect(addButton,    SIGNAL(clicked()), SLOT(add()));
  connect(delButton_,   SIGNAL(clicked()), SLOT(del()));
}

void
FileListDialog::createDialogButtonsBox(QVBoxLayout * const pFileListDialogLayout)
{
  // Create the Widget
  QWidget * const pDialogButtonsBox = new QWidget();
  assert(pDialogButtonsBox != NULL);

  // Create the Layout
  QHBoxLayout * const pDialogButtonsBoxLayout = new QHBoxLayout;
  assert(pDialogButtonsBoxLayout != NULL);

  pDialogButtonsBox->setLayout(pDialogButtonsBoxLayout);
  // Use the value of the margin for the spacing
  pDialogButtonsBoxLayout->setSpacing(-1);

  QSpacerItem * dBSpace = new QSpacerItem(0, 0);
  QPushButton * okButton = new QPushButton("OK", this);
  QPushButton * cancelButton = new QPushButton("Cancel", this);

  pFileListDialogLayout->addSpacing(5);
  pDialogButtonsBoxLayout->addItem(dBSpace);
  pDialogButtonsBoxLayout->addWidget(okButton);
  pDialogButtonsBoxLayout->addSpacing(5);
  pDialogButtonsBoxLayout->addWidget(cancelButton);
  pDialogButtonsBoxLayout->addSpacing(5);
  okButton->setDefault(true);

  // connect the dialogs functionality
  connect(okButton,     SIGNAL(clicked()), SLOT(accept()));
  connect(cancelButton, SIGNAL(clicked()), SLOT(reject()));

  // Add the Widget to its Layout
  pFileListDialogLayout->addWidget(pDialogButtonsBox);
}

QVBoxLayout *
FileListDialog::createLayout()
{
  QVBoxLayout * const pFileListDialogLayout = new QVBoxLayout;
  assert(pFileListDialogLayout != NULL);
  const int margin = 0;
  pFileListDialogLayout->setContentsMargins(margin, margin, margin, margin);
  // The spacing is the same as the margin
  const int spacing = margin;
  pFileListDialogLayout->setSpacing(spacing);
  this->setLayout(pFileListDialogLayout);

  return pFileListDialogLayout;
}
<|endoftext|>


<commit_before>//===-- GraphWriter.cpp - Implements GraphWriter support routines ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements misc. GraphWriter support routines.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/GraphWriter.h"
#include "llvm/Config/config.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
using namespace llvm;

static cl::opt<bool> ViewBackground("view-background", cl::Hidden,
  cl::desc("Execute graph viewer in the background. Creates tmp file litter."));

std::string llvm::DOT::EscapeString(const std::string &Label) {
  std::string Str(Label);
  for (unsigned i = 0; i != Str.length(); ++i)
  switch (Str[i]) {
    case '\n':
      Str.insert(Str.begin()+i, '\\');  // Escape character...
      ++i;
      Str[i] = 'n';
      break;
    case '\t':
      Str.insert(Str.begin()+i, ' ');  // Convert to two spaces
      ++i;
      Str[i] = ' ';
      break;
    case '\\':
      if (i+1 != Str.length())
        switch (Str[i+1]) {
          case 'l': continue; // don't disturb \l
          case '|': case '{': case '}':
            Str.erase(Str.begin()+i); continue;
          default: break;
        }
    case '{': case '}':
    case '<': case '>':
    case '|': case '"':
      Str.insert(Str.begin()+i, '\\');  // Escape character...
      ++i;  // don't infinite loop
      break;
  }
  return Str;
}

/// \brief Get a color string for this node number. Simply round-robin selects
/// from a reasonable number of colors.
StringRef llvm::DOT::getColorString(unsigned ColorNumber) {
  static const int NumColors = 20;
  static const char* Colors[NumColors] = {
    "aaaaaa", "aa0000", "00aa00", "aa5500", "0055ff", "aa00aa", "00aaaa",
    "555555", "ff5555", "55ff55", "ffff55", "5555ff", "ff55ff", "55ffff",
    "ffaaaa", "aaffaa", "ffffaa", "aaaaff", "ffaaff", "aaffff"};
  return Colors[ColorNumber % NumColors];
}

std::string llvm::createGraphFilename(const Twine &Name, int &FD) {
  FD = -1;
  SmallString<128> Filename;
  error_code EC = sys::fs::createTemporaryFile(Name, "dot", FD, Filename);
  if (EC) {
    errs() << "Error: " << EC.message() << "\n";
    return "";
  }

  errs() << "Writing '" << Filename << "'... ";
  return Filename.str();
}

// Execute the graph viewer. Return true if there were errors.
static bool ExecGraphViewer(StringRef ExecPath, std::vector<const char *> &args,
                            StringRef Filename, bool wait,
                            std::string &ErrMsg) {
  assert(args.back() == nullptr);
  if (wait) {
    if (sys::ExecuteAndWait(ExecPath, args.data(), nullptr, nullptr, 0, 0,
                            &ErrMsg)) {
      errs() << "Error: " << ErrMsg << "\n";
      return true;
    }
    sys::fs::remove(Filename);
    errs() << " done. \n";
  } else {
    sys::ExecuteNoWait(ExecPath, args.data(), nullptr, nullptr, 0, &ErrMsg);
    errs() << "Remember to erase graph file: " << Filename.str() << "\n";
  }
  return false;
}

struct GraphSession {
  std::string LogBuffer;
  bool TryFindProgram(StringRef Names, std::string &ProgramPath) {
    raw_string_ostream Log(LogBuffer);
    SmallVector<StringRef, 8> parts;
    Names.split(parts, "|");
    for (auto Name : parts) {
      ProgramPath = sys::FindProgramByName(Name);
      if (!ProgramPath.empty())
        return true;
      Log << "  Tried '" << Name << "'\n";
    }
    return false;
  }
};

static const char *getProgramName(GraphProgram::Name program) {
  switch (program) {
  case GraphProgram::DOT:
    return "dot";
  case GraphProgram::FDP:
    return "fdp";
  case GraphProgram::NEATO:
    return "neato";
  case GraphProgram::TWOPI:
    return "twopi";
  case GraphProgram::CIRCO:
    return "circo";
  }
  llvm_unreachable("bad kind");
}

bool llvm::DisplayGraph(StringRef FilenameRef, bool wait,
                        GraphProgram::Name program) {
  std::string Filename = FilenameRef;
  wait &= !ViewBackground;
  std::string ErrMsg;
  std::string ViewerPath;
  GraphSession S;

  // Graphviz
  if (S.TryFindProgram("Graphviz", ViewerPath)) {
    std::vector<const char *> args;
    args.push_back(ViewerPath.c_str());
    args.push_back(Filename.c_str());
    args.push_back(nullptr);

    errs() << "Running 'Graphviz' program... ";
    return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg);
  }

  // xdot
  if (S.TryFindProgram("xdot|xdot.py", ViewerPath)) {
    std::vector<const char *> args;
    args.push_back(ViewerPath.c_str());
    args.push_back(Filename.c_str());

    args.push_back("-f");
    args.push_back(getProgramName(program));

    args.push_back(nullptr);

    errs() << "Running 'xdot.py' program... ";
    return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg);
  }

  enum PSViewerKind { PSV_None, PSV_OSXOpen, PSV_Ghostview };
  PSViewerKind PSViewer = PSV_None;
#ifdef __APPLE__
  if (S.TryFindProgram("open", ViewerPath))
    PSViewer = PSV_OSXOpen;
#endif
  if (!PSViewer && S.TryFindProgram("gv", ViewerPath))
    PSViewer = PSV_Ghostview;

  // PostScript graph generator + PostScript viewer
  std::string GeneratorPath;
  if (PSViewer &&
      (S.TryFindProgram(getProgramName(program), GeneratorPath) ||
       S.TryFindProgram("dot|fdp|neato|twopi|circo", GeneratorPath))) {
    std::string PSFilename = Filename + ".ps";

    std::vector<const char *> args;
    args.push_back(GeneratorPath.c_str());
    args.push_back("-Tps");
    args.push_back("-Nfontname=Courier");
    args.push_back("-Gsize=7.5,10");
    args.push_back(Filename.c_str());
    args.push_back("-o");
    args.push_back(PSFilename.c_str());
    args.push_back(nullptr);

    errs() << "Running '" << GeneratorPath << "' program... ";

    if (ExecGraphViewer(GeneratorPath, args, Filename, wait, ErrMsg))
      return true;

    args.clear();
    args.push_back(ViewerPath.c_str());
    switch (PSViewer) {
    case PSV_OSXOpen:
      args.push_back("-W");
      args.push_back(PSFilename.c_str());
      break;
    case PSV_Ghostview:
      args.push_back("--spartan");
      args.push_back(PSFilename.c_str());
      break;
    case PSV_None:
      llvm_unreachable("Invalid viewer");
    }
    args.push_back(nullptr);

    ErrMsg.clear();
    return ExecGraphViewer(ViewerPath, args, PSFilename, wait, ErrMsg);
  }

  // dotty
  if (S.TryFindProgram("dotty", ViewerPath)) {
    std::vector<const char *> args;
    args.push_back(ViewerPath.c_str());
    args.push_back(Filename.c_str());
    args.push_back(nullptr);

// Dotty spawns another app and doesn't wait until it returns
#ifdef LLVM_ON_WIN32
    wait = false;
#endif
    errs() << "Running 'dotty' program... ";
    return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg);
  }

  errs() << "Error: Couldn't find a usable graph viewer program:\n";
  errs() << S.LogBuffer << "\n";
  return true;
}
<commit_msg>GraphWriter: support the XDG open utility<commit_after>//===-- GraphWriter.cpp - Implements GraphWriter support routines ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements misc. GraphWriter support routines.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/GraphWriter.h"
#include "llvm/Config/config.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
using namespace llvm;

static cl::opt<bool> ViewBackground("view-background", cl::Hidden,
  cl::desc("Execute graph viewer in the background. Creates tmp file litter."));

std::string llvm::DOT::EscapeString(const std::string &Label) {
  std::string Str(Label);
  for (unsigned i = 0; i != Str.length(); ++i)
  switch (Str[i]) {
    case '\n':
      Str.insert(Str.begin()+i, '\\');  // Escape character...
      ++i;
      Str[i] = 'n';
      break;
    case '\t':
      Str.insert(Str.begin()+i, ' ');  // Convert to two spaces
      ++i;
      Str[i] = ' ';
      break;
    case '\\':
      if (i+1 != Str.length())
        switch (Str[i+1]) {
          case 'l': continue; // don't disturb \l
          case '|': case '{': case '}':
            Str.erase(Str.begin()+i); continue;
          default: break;
        }
    case '{': case '}':
    case '<': case '>':
    case '|': case '"':
      Str.insert(Str.begin()+i, '\\');  // Escape character...
      ++i;  // don't infinite loop
      break;
  }
  return Str;
}

/// \brief Get a color string for this node number. Simply round-robin selects
/// from a reasonable number of colors.
StringRef llvm::DOT::getColorString(unsigned ColorNumber) {
  static const int NumColors = 20;
  static const char* Colors[NumColors] = {
    "aaaaaa", "aa0000", "00aa00", "aa5500", "0055ff", "aa00aa", "00aaaa",
    "555555", "ff5555", "55ff55", "ffff55", "5555ff", "ff55ff", "55ffff",
    "ffaaaa", "aaffaa", "ffffaa", "aaaaff", "ffaaff", "aaffff"};
  return Colors[ColorNumber % NumColors];
}

std::string llvm::createGraphFilename(const Twine &Name, int &FD) {
  FD = -1;
  SmallString<128> Filename;
  error_code EC = sys::fs::createTemporaryFile(Name, "dot", FD, Filename);
  if (EC) {
    errs() << "Error: " << EC.message() << "\n";
    return "";
  }

  errs() << "Writing '" << Filename << "'... ";
  return Filename.str();
}

// Execute the graph viewer. Return true if there were errors.
static bool ExecGraphViewer(StringRef ExecPath, std::vector<const char *> &args,
                            StringRef Filename, bool wait,
                            std::string &ErrMsg) {
  assert(args.back() == nullptr);
  if (wait) {
    if (sys::ExecuteAndWait(ExecPath, args.data(), nullptr, nullptr, 0, 0,
                            &ErrMsg)) {
      errs() << "Error: " << ErrMsg << "\n";
      return true;
    }
    sys::fs::remove(Filename);
    errs() << " done. \n";
  } else {
    sys::ExecuteNoWait(ExecPath, args.data(), nullptr, nullptr, 0, &ErrMsg);
    errs() << "Remember to erase graph file: " << Filename.str() << "\n";
  }
  return false;
}

struct GraphSession {
  std::string LogBuffer;
  bool TryFindProgram(StringRef Names, std::string &ProgramPath) {
    raw_string_ostream Log(LogBuffer);
    SmallVector<StringRef, 8> parts;
    Names.split(parts, "|");
    for (auto Name : parts) {
      ProgramPath = sys::FindProgramByName(Name);
      if (!ProgramPath.empty())
        return true;
      Log << "  Tried '" << Name << "'\n";
    }
    return false;
  }
};

static const char *getProgramName(GraphProgram::Name program) {
  switch (program) {
  case GraphProgram::DOT:
    return "dot";
  case GraphProgram::FDP:
    return "fdp";
  case GraphProgram::NEATO:
    return "neato";
  case GraphProgram::TWOPI:
    return "twopi";
  case GraphProgram::CIRCO:
    return "circo";
  }
  llvm_unreachable("bad kind");
}

bool llvm::DisplayGraph(StringRef FilenameRef, bool wait,
                        GraphProgram::Name program) {
  std::string Filename = FilenameRef;
  wait &= !ViewBackground;
  std::string ErrMsg;
  std::string ViewerPath;
  GraphSession S;

  // Graphviz
  if (S.TryFindProgram("Graphviz", ViewerPath)) {
    std::vector<const char *> args;
    args.push_back(ViewerPath.c_str());
    args.push_back(Filename.c_str());
    args.push_back(nullptr);

    errs() << "Running 'Graphviz' program... ";
    return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg);
  }

  // xdot
  if (S.TryFindProgram("xdot|xdot.py", ViewerPath)) {
    std::vector<const char *> args;
    args.push_back(ViewerPath.c_str());
    args.push_back(Filename.c_str());

    args.push_back("-f");
    args.push_back(getProgramName(program));

    args.push_back(nullptr);

    errs() << "Running 'xdot.py' program... ";
    return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg);
  }

  enum PSViewerKind { PSV_None, PSV_OSXOpen, PSV_XDGOpen, PSV_Ghostview };
  PSViewerKind PSViewer = PSV_None;
#ifdef __APPLE__
  if (!PSViewer && S.TryFindProgram("open", ViewerPath))
    PSViewer = PSV_OSXOpen;
#endif
  if (!PSViewer && S.TryFindProgram("xdg-open", ViewerPath))
    PSViewer = PSV_XDGOpen;
  if (!PSViewer && S.TryFindProgram("gv", ViewerPath))
    PSViewer = PSV_Ghostview;

  // PostScript graph generator + PostScript viewer
  std::string GeneratorPath;
  if (PSViewer &&
      (S.TryFindProgram(getProgramName(program), GeneratorPath) ||
       S.TryFindProgram("dot|fdp|neato|twopi|circo", GeneratorPath))) {
    std::string PSFilename = Filename + ".ps";

    std::vector<const char *> args;
    args.push_back(GeneratorPath.c_str());
    args.push_back("-Tps");
    args.push_back("-Nfontname=Courier");
    args.push_back("-Gsize=7.5,10");
    args.push_back(Filename.c_str());
    args.push_back("-o");
    args.push_back(PSFilename.c_str());
    args.push_back(nullptr);

    errs() << "Running '" << GeneratorPath << "' program... ";

    if (ExecGraphViewer(GeneratorPath, args, Filename, wait, ErrMsg))
      return true;

    args.clear();
    args.push_back(ViewerPath.c_str());
    switch (PSViewer) {
    case PSV_OSXOpen:
      args.push_back("-W");
      args.push_back(PSFilename.c_str());
      break;
    case PSV_XDGOpen:
      wait = false;
      args.push_back(PSFilename.c_str());
      break;
    case PSV_Ghostview:
      args.push_back("--spartan");
      args.push_back(PSFilename.c_str());
      break;
    case PSV_None:
      llvm_unreachable("Invalid viewer");
    }
    args.push_back(nullptr);

    ErrMsg.clear();
    return ExecGraphViewer(ViewerPath, args, PSFilename, wait, ErrMsg);
  }

  // dotty
  if (S.TryFindProgram("dotty", ViewerPath)) {
    std::vector<const char *> args;
    args.push_back(ViewerPath.c_str());
    args.push_back(Filename.c_str());
    args.push_back(nullptr);

// Dotty spawns another app and doesn't wait until it returns
#ifdef LLVM_ON_WIN32
    wait = false;
#endif
    errs() << "Running 'dotty' program... ";
    return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg);
  }

  errs() << "Error: Couldn't find a usable graph viewer program:\n";
  errs() << S.LogBuffer << "\n";
  return true;
}
<|endoftext|>