<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fuconstr.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: ihi $ $Date: 2006-11-14 15:51:06 $
 *
 *  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_sc.hxx"

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

// TOOLS
#define _BIGINT_HXX
#define _SFXMULTISEL_HXX
#define _STACK_HXX
#define _QUEUE_HXX
#define _DYNARR_HXX
#define _TREELIST_HXX
#define _CACHESTR_HXX
#define _NEW_HXX
//#define _SHL_HXX
//#define _LINK_HXX
//#define _ERRCODE_HXX
//#define _GEN_HXX
//#define _FRACT_HXX
//#define _STRING_HXX
//#define _MTF_HXX
//#define _CONTNR_HXX
//#define _LIST_HXX
//#define _TABLE_HXX
#define _DYNARY_HXX
//#define _UNQIDX_HXX
#define _SVMEMPOOL_HXX
//#define _UNQID_HXX
//#define _DEBUG_HXX
//#define _DATE_HXX
//#define _TIME_HXX
//#define _DATETIME_HXX
//#define _INTN_HXX
//#define _WLDCRD_HXX
//#define _FSYS_HXX
//#define _STREAM_HXX
#define _CACHESTR_HXX
#define _SV_MULTISEL_HXX

//SV
//#define _CLIP_HXX
#define _CONFIG_HXX
#define _CURSOR_HXX
#define _FONTDLG_HXX
#define _PRVWIN_HXX
//#define _COLOR_HXX
//#define _PAL_HXX
//#define _BITMAP_HXX
//#define _GDIOBJ_HXX
//#define _POINTR_HXX
//#define _ICON_HXX
//#define _IMAGE_HXX
//#define _KEYCOD_HXX
//#define _EVENT_HXX
#define _HELP_HXX
//#define _APP_HXX
//#define _MDIAPP_HXX
//#define _TIMER_HXX
//#define _METRIC_HXX
//#define _REGION_HXX
//#define _OUTDEV_HXX
//#define _SYSTEM_HXX
//#define _VIRDEV_HXX
//#define _JOBSET_HXX
//#define _PRINT_HXX
//#define _WINDOW_HXX
//#define _SYSWIN_HXX
//#define _WRKWIN_HXX
#define _MDIWIN_HXX
//#define _FLOATWIN_HXX
//#define _DOCKWIN_HXX
//#define _CTRL_HXX
//#define _SCRBAR_HXX
//#define _BUTTON_HXX
//#define _IMAGEBTN_HXX
//#define _FIXED_HXX
//#define _GROUP_HXX
//#define _EDIT_HXX
//#define _COMBOBOX_HXX
//#define _LSTBOX_HXX
//#define _SELENG_HXX
//#define _SPLIT_HXX
#define _SPIN_HXX
//#define _FIELD_HXX
//#define _MOREBTN_HXX
//#define _TOOLBOX_HXX
//#define _STATUS_HXX
//#define _DIALOG_HXX
//#define _MSGBOX_HXX
//#define _SYSDLG_HXX
//#define _PRNDLG_HXX
#define _COLDLG_HXX
//#define _TABDLG_HXX
//#define _GDIMTF_HXX
//#define _POLY_HXX
//#define _ACCEL_HXX
//#define _GRAPH_HXX
#define _SOUND_HXX

//svtools
#define _SCRWIN_HXX
#define _RULER_HXX
//#define _TABBAR_HXX
//#define _VALUESET_HXX
#define _STDMENU_HXX
//#define _STDCTRL_HXX
//#define _CTRLBOX_HXX
#define _CTRLTOOL_HXX
#define _EXTATTR_HXX
#define _FRM3D_HXX
#define _EXTATTR_HXX

//SVTOOLS
//#define _SVTREELIST_HXX ***
#define _FILTER_HXX
//#define _SVLBOXITM_HXX ***
//#define _SVTREEBOX_HXX ***
#define _SVICNVW_HXX
#define _SVTABBX_HXX

//sfxcore.hxx
//#define _SFXINIMGR_HXX ***
//#define _SFXCFGITEM_HXX
//#define _SFX_PRINTER_HXX
#define _SFXGENLINK_HXX
#define _SFXHINTPOST_HXX
//#define _SFXDOCINF_HXX ***
#define _SFXLINKHDL_HXX
//#define _SFX_PROGRESS_HXX

//sfxsh.hxx
//#define _SFX_SHELL_HXX
//#define _SFXAPP_HXX
//#define _SFXDISPATCH_HXX
//#define _SFXMSG_HXX ***
//#define _SFXOBJFACE_HXX ***
//#define _SFXREQUEST_HXX
#define _SFXMACRO_HXX

// SFX
//#define _SFXAPPWIN_HXX ***
#define _SFX_SAVEOPT_HXX
//#define _SFX_CHILDWIN_HXX
//#define _SFXCTRLITEM_HXX
#define _SFXPRNMON_HXX
#define _INTRO_HXX
#define _SFXMSGDESCR_HXX
#define _SFXMSGPOOL_HXX
#define _SFXFILEDLG_HXX
#define _PASSWD_HXX
#define _SFXTBXCTRL_HXX
#define _SFXSTBITEM_HXX
#define _SFXMNUITEM_HXX
#define _SFXIMGMGR_HXX
#define _SFXTBXMGR_HXX
#define _SFXSTBMGR_HXX
#define _SFX_MINFITEM_HXX
#define _SFXEVENT_HXX

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

#include <svx/outliner.hxx>
#include <svx/outlobj.hxx>
#include <svx/svdotext.hxx>
#include <svx/svdouno.hxx>
#include <svx/svdview.hxx>
#include <sfx2/dispatch.hxx>

#include "fuconstr.hxx"
#include "fudraw.hxx"
#include "tabvwsh.hxx"
#include "futext.hxx"
#include "sc.hrc"

//  Maximal erlaubte Mausbewegung um noch Drag&Drop zu starten
//! fusel,fuconstr,futext - zusammenfassen!
#define SC_MAXDRAGMOVE  3

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

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuConstruct::FuConstruct(ScTabViewShell* pViewSh, Window* pWin, SdrView* pView,
                   SdrModel* pDoc, SfxRequest& rReq) :
    FuDraw(pViewSh, pWin, pView, pDoc, rReq)
{
}

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/

FuConstruct::~FuConstruct()
{
}

BYTE FuConstruct::Command(const CommandEvent& rCEvt)
{
    //  special code for non-VCL OS2/UNX removed

    return FuDraw::Command( rCEvt );
}

/*************************************************************************
|*
|* MouseButtonDown-event
|*
\************************************************************************/

BOOL __EXPORT FuConstruct::MouseButtonDown(const MouseEvent& rMEvt)
{
    // #95491# remember button state for creation of own MouseEvents
    SetMouseButtonCode(rMEvt.GetButtons());

    BOOL bReturn = FuDraw::MouseButtonDown(rMEvt);

    if ( pView->IsAction() )
    {
        if ( rMEvt.IsRight() )
            pView->BckAction();
        return TRUE;
    }

    aDragTimer.Start();

    aMDPos = pWindow->PixelToLogic( rMEvt.GetPosPixel() );

    if ( rMEvt.IsLeft() )
    {
        pWindow->CaptureMouse();

        SdrHdl* pHdl = pView->PickHandle(aMDPos);

        if ( pHdl != NULL || pView->IsMarkedHit(aMDPos) )
        {
            pView->BegDragObj(aMDPos, (OutputDevice*) NULL, pHdl, 1);
            bReturn = TRUE;
        }
        else if ( pView->AreObjectsMarked() )
        {
            pView->UnmarkAll();
            bReturn = TRUE;
        }
    }

    bIsInDragMode = FALSE;

    return bReturn;
}

/*************************************************************************
|*
|* MouseMove-event
|*
\************************************************************************/

BOOL __EXPORT FuConstruct::MouseMove(const MouseEvent& rMEvt)
{
    FuDraw::MouseMove(rMEvt);

    if (aDragTimer.IsActive() )
    {
        Point aOldPixel = pWindow->LogicToPixel( aMDPos );
        Point aNewPixel = rMEvt.GetPosPixel();
        if ( Abs( aOldPixel.X() - aNewPixel.X() ) > SC_MAXDRAGMOVE ||
             Abs( aOldPixel.Y() - aNewPixel.Y() ) > SC_MAXDRAGMOVE )
            aDragTimer.Stop();
    }

    Point aPix(rMEvt.GetPosPixel());
    Point aPnt( pWindow->PixelToLogic(aPix) );

    if ( pView->IsAction() )
    {
        ForceScroll(aPix);
        pView->MovAction(aPnt);
    }
    else
    {
        SdrHdl* pHdl=pView->PickHandle(aPnt);

        if ( pHdl != NULL )
        {
            pViewShell->SetActivePointer(pHdl->GetPointer());
        }
        else if ( pView->IsMarkedHit(aPnt) )
        {
            pViewShell->SetActivePointer(Pointer(POINTER_MOVE));
        }
        else
        {
            pViewShell->SetActivePointer( aNewPointer );
        }
    }
    return TRUE;
}

/*************************************************************************
|*
|* MouseButtonUp-event
|*
\************************************************************************/

BOOL __EXPORT FuConstruct::MouseButtonUp(const MouseEvent& rMEvt)
{
    // #95491# remember button state for creation of own MouseEvents
    SetMouseButtonCode(rMEvt.GetButtons());

    BOOL bReturn = SimpleMouseButtonUp( rMEvt );

    //      Doppelklick auf Textobjekt? (->fusel)

    USHORT nClicks = rMEvt.GetClicks();
    if ( nClicks == 2 && rMEvt.IsLeft() )
    {
        if ( pView->AreObjectsMarked() )
        {
            const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
            if (rMarkList.GetMarkCount() == 1)
            {
                SdrMark* pMark = rMarkList.GetMark(0);
                SdrObject* pObj = pMark->GetMarkedSdrObj();

                //  #49458# bei Uno-Controls nicht in Textmodus
                if ( pObj->ISA(SdrTextObj) && !pObj->ISA(SdrUnoObj) )
                {
                    OutlinerParaObject* pOPO = pObj->GetOutlinerParaObject();
                    BOOL bVertical = ( pOPO && pOPO->IsVertical() );
                    USHORT nTextSlotId = bVertical ? SID_DRAW_TEXT_VERTICAL : SID_DRAW_TEXT;

                    pViewShell->GetViewData()->GetDispatcher().
                        Execute(nTextSlotId, SFX_CALLMODE_SLOT | SFX_CALLMODE_RECORD);

                    // jetzt den erzeugten FuText holen und in den EditModus setzen
                    FuPoor* pPoor = pViewShell->GetViewData()->GetView()->GetDrawFuncPtr();
                    if ( pPoor && pPoor->GetSlotID() == nTextSlotId )    // hat keine RTTI
                    {
                        FuText* pText = (FuText*)pPoor;
                        Point aMousePixel = rMEvt.GetPosPixel();
                        pText->SetInEditMode( pObj, &aMousePixel );
                    }
                    bReturn = TRUE;
                }
            }
        }
    }

    FuDraw::MouseButtonUp(rMEvt);

    return bReturn;
}

//      SimpleMouseButtonUp - ohne Test auf Doppelklick

BOOL FuConstruct::SimpleMouseButtonUp(const MouseEvent& rMEvt)
{
    BOOL    bReturn = TRUE;

    if (aDragTimer.IsActive() )
    {
        aDragTimer.Stop();
    }

    Point   aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );

    if ( pView->IsDragObj() )
         pView->EndDragObj( rMEvt.IsMod1() );

    else if ( pView->IsMarkObj() )
        pView->EndMarkObj();

    else bReturn = FALSE;

    if ( !pView->IsAction() )
    {
        pWindow->ReleaseMouse();

        if ( !pView->AreObjectsMarked() && rMEvt.GetClicks() < 2 )
        {
            pView->MarkObj(aPnt, -2, FALSE, rMEvt.IsMod1());

            SfxDispatcher& rDisp = pViewShell->GetViewData()->GetDispatcher();
            if ( pView->AreObjectsMarked() )
                rDisp.Execute(SID_OBJECT_SELECT, SFX_CALLMODE_SLOT | SFX_CALLMODE_RECORD);
            else
                rDisp.Execute(aSfxRequest.GetSlot(), SFX_CALLMODE_SLOT | SFX_CALLMODE_RECORD);
        }
    }

    return bReturn;
}

/*************************************************************************
|*
|* Tastaturereignisse bearbeiten
|*
|* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls
|* FALSE.
|*
\************************************************************************/

BOOL __EXPORT FuConstruct::KeyInput(const KeyEvent& rKEvt)
{
    BOOL bReturn = FALSE;

    switch ( rKEvt.GetKeyCode().GetCode() )
    {
        case KEY_ESCAPE:
            if ( pView->IsAction() )
            {
                pView->BrkAction();
                pWindow->ReleaseMouse();
                bReturn = TRUE;
            }
            else                            // Zeichenmodus beenden
            {
                pViewShell->GetViewData()->GetDispatcher().
                    Execute(aSfxRequest.GetSlot(), SFX_CALLMODE_SLOT | SFX_CALLMODE_RECORD);
            }
            break;

        case KEY_DELETE:
            pView->DeleteMarked();
            bReturn = TRUE;
            break;
    }

    if ( !bReturn )
    {
        bReturn = FuDraw::KeyInput(rKEvt);
    }

    return(bReturn);
}

/*************************************************************************
|*
|* Function aktivieren
|*
\************************************************************************/

void FuConstruct::Activate()
{
    FuDraw::Activate();
}

/*************************************************************************
|*
|* Function deaktivieren
|*
\************************************************************************/

void FuConstruct::Deactivate()
{
    FuDraw::Deactivate();
}

<commit_msg>INTEGRATION: CWS calcwarnings (1.9.8); FILE MERGED 2006/12/12 17:03:12 nn 1.9.8.1: #i69284# warning-free: ui, unxlngi6<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fuconstr.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: vg $ $Date: 2007-02-27 13:11:51 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"

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

// TOOLS
#define _BIGINT_HXX
#define _SFXMULTISEL_HXX
#define _STACK_HXX
#define _QUEUE_HXX
#define _DYNARR_HXX
#define _TREELIST_HXX
#define _CACHESTR_HXX
#define _NEW_HXX
//#define _SHL_HXX
//#define _LINK_HXX
//#define _ERRCODE_HXX
//#define _GEN_HXX
//#define _FRACT_HXX
//#define _STRING_HXX
//#define _MTF_HXX
//#define _CONTNR_HXX
//#define _LIST_HXX
//#define _TABLE_HXX
#define _DYNARY_HXX
//#define _UNQIDX_HXX
#define _SVMEMPOOL_HXX
//#define _UNQID_HXX
//#define _DEBUG_HXX
//#define _DATE_HXX
//#define _TIME_HXX
//#define _DATETIME_HXX
//#define _INTN_HXX
//#define _WLDCRD_HXX
//#define _FSYS_HXX
//#define _STREAM_HXX
#define _CACHESTR_HXX
#define _SV_MULTISEL_HXX

//SV
//#define _CLIP_HXX
#define _CONFIG_HXX
#define _CURSOR_HXX
#define _FONTDLG_HXX
#define _PRVWIN_HXX
//#define _COLOR_HXX
//#define _PAL_HXX
//#define _BITMAP_HXX
//#define _GDIOBJ_HXX
//#define _POINTR_HXX
//#define _ICON_HXX
//#define _IMAGE_HXX
//#define _KEYCOD_HXX
//#define _EVENT_HXX
#define _HELP_HXX
//#define _APP_HXX
//#define _MDIAPP_HXX
//#define _TIMER_HXX
//#define _METRIC_HXX
//#define _REGION_HXX
//#define _OUTDEV_HXX
//#define _SYSTEM_HXX
//#define _VIRDEV_HXX
//#define _JOBSET_HXX
//#define _PRINT_HXX
//#define _WINDOW_HXX
//#define _SYSWIN_HXX
//#define _WRKWIN_HXX
#define _MDIWIN_HXX
//#define _FLOATWIN_HXX
//#define _DOCKWIN_HXX
//#define _CTRL_HXX
//#define _SCRBAR_HXX
//#define _BUTTON_HXX
//#define _IMAGEBTN_HXX
//#define _FIXED_HXX
//#define _GROUP_HXX
//#define _EDIT_HXX
//#define _COMBOBOX_HXX
//#define _LSTBOX_HXX
//#define _SELENG_HXX
//#define _SPLIT_HXX
#define _SPIN_HXX
//#define _FIELD_HXX
//#define _MOREBTN_HXX
//#define _TOOLBOX_HXX
//#define _STATUS_HXX
//#define _DIALOG_HXX
//#define _MSGBOX_HXX
//#define _SYSDLG_HXX
//#define _PRNDLG_HXX
#define _COLDLG_HXX
//#define _TABDLG_HXX
//#define _GDIMTF_HXX
//#define _POLY_HXX
//#define _ACCEL_HXX
//#define _GRAPH_HXX
#define _SOUND_HXX

//svtools
#define _SCRWIN_HXX
#define _RULER_HXX
//#define _TABBAR_HXX
//#define _VALUESET_HXX
#define _STDMENU_HXX
//#define _STDCTRL_HXX
//#define _CTRLBOX_HXX
#define _CTRLTOOL_HXX
#define _EXTATTR_HXX
#define _FRM3D_HXX
#define _EXTATTR_HXX

//SVTOOLS
//#define _SVTREELIST_HXX ***
#define _FILTER_HXX
//#define _SVLBOXITM_HXX ***
//#define _SVTREEBOX_HXX ***
#define _SVICNVW_HXX
#define _SVTABBX_HXX

//sfxcore.hxx
//#define _SFXINIMGR_HXX ***
//#define _SFXCFGITEM_HXX
//#define _SFX_PRINTER_HXX
#define _SFXGENLINK_HXX
#define _SFXHINTPOST_HXX
//#define _SFXDOCINF_HXX ***
#define _SFXLINKHDL_HXX
//#define _SFX_PROGRESS_HXX

//sfxsh.hxx
//#define _SFX_SHELL_HXX
//#define _SFXAPP_HXX
//#define _SFXDISPATCH_HXX
//#define _SFXMSG_HXX ***
//#define _SFXOBJFACE_HXX ***
//#define _SFXREQUEST_HXX
#define _SFXMACRO_HXX

// SFX
//#define _SFXAPPWIN_HXX ***
#define _SFX_SAVEOPT_HXX
//#define _SFX_CHILDWIN_HXX
//#define _SFXCTRLITEM_HXX
#define _SFXPRNMON_HXX
#define _INTRO_HXX
#define _SFXMSGDESCR_HXX
#define _SFXMSGPOOL_HXX
#define _SFXFILEDLG_HXX
#define _PASSWD_HXX
#define _SFXTBXCTRL_HXX
#define _SFXSTBITEM_HXX
#define _SFXMNUITEM_HXX
#define _SFXIMGMGR_HXX
#define _SFXTBXMGR_HXX
#define _SFXSTBMGR_HXX
#define _SFX_MINFITEM_HXX
#define _SFXEVENT_HXX

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

#include <svx/outliner.hxx>
#include <svx/outlobj.hxx>
#include <svx/svdotext.hxx>
#include <svx/svdouno.hxx>
#include <svx/svdview.hxx>
#include <sfx2/dispatch.hxx>

#include "fuconstr.hxx"
#include "fudraw.hxx"
#include "tabvwsh.hxx"
#include "futext.hxx"
#include "sc.hrc"

//  Maximal erlaubte Mausbewegung um noch Drag&Drop zu starten
//! fusel,fuconstr,futext - zusammenfassen!
#define SC_MAXDRAGMOVE  3

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

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuConstruct::FuConstruct(ScTabViewShell* pViewSh, Window* pWin, SdrView* pViewP,
                   SdrModel* pDoc, SfxRequest& rReq) :
    FuDraw(pViewSh, pWin, pViewP, pDoc, rReq)
{
}

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/

FuConstruct::~FuConstruct()
{
}

BYTE FuConstruct::Command(const CommandEvent& rCEvt)
{
    //  special code for non-VCL OS2/UNX removed

    return FuDraw::Command( rCEvt );
}

/*************************************************************************
|*
|* MouseButtonDown-event
|*
\************************************************************************/

BOOL __EXPORT FuConstruct::MouseButtonDown(const MouseEvent& rMEvt)
{
    // #95491# remember button state for creation of own MouseEvents
    SetMouseButtonCode(rMEvt.GetButtons());

    BOOL bReturn = FuDraw::MouseButtonDown(rMEvt);

    if ( pView->IsAction() )
    {
        if ( rMEvt.IsRight() )
            pView->BckAction();
        return TRUE;
    }

    aDragTimer.Start();

    aMDPos = pWindow->PixelToLogic( rMEvt.GetPosPixel() );

    if ( rMEvt.IsLeft() )
    {
        pWindow->CaptureMouse();

        SdrHdl* pHdl = pView->PickHandle(aMDPos);

        if ( pHdl != NULL || pView->IsMarkedHit(aMDPos) )
        {
            pView->BegDragObj(aMDPos, (OutputDevice*) NULL, pHdl, 1);
            bReturn = TRUE;
        }
        else if ( pView->AreObjectsMarked() )
        {
            pView->UnmarkAll();
            bReturn = TRUE;
        }
    }

    bIsInDragMode = FALSE;

    return bReturn;
}

/*************************************************************************
|*
|* MouseMove-event
|*
\************************************************************************/

BOOL __EXPORT FuConstruct::MouseMove(const MouseEvent& rMEvt)
{
    FuDraw::MouseMove(rMEvt);

    if (aDragTimer.IsActive() )
    {
        Point aOldPixel = pWindow->LogicToPixel( aMDPos );
        Point aNewPixel = rMEvt.GetPosPixel();
        if ( Abs( aOldPixel.X() - aNewPixel.X() ) > SC_MAXDRAGMOVE ||
             Abs( aOldPixel.Y() - aNewPixel.Y() ) > SC_MAXDRAGMOVE )
            aDragTimer.Stop();
    }

    Point aPix(rMEvt.GetPosPixel());
    Point aPnt( pWindow->PixelToLogic(aPix) );

    if ( pView->IsAction() )
    {
        ForceScroll(aPix);
        pView->MovAction(aPnt);
    }
    else
    {
        SdrHdl* pHdl=pView->PickHandle(aPnt);

        if ( pHdl != NULL )
        {
            pViewShell->SetActivePointer(pHdl->GetPointer());
        }
        else if ( pView->IsMarkedHit(aPnt) )
        {
            pViewShell->SetActivePointer(Pointer(POINTER_MOVE));
        }
        else
        {
            pViewShell->SetActivePointer( aNewPointer );
        }
    }
    return TRUE;
}

/*************************************************************************
|*
|* MouseButtonUp-event
|*
\************************************************************************/

BOOL __EXPORT FuConstruct::MouseButtonUp(const MouseEvent& rMEvt)
{
    // #95491# remember button state for creation of own MouseEvents
    SetMouseButtonCode(rMEvt.GetButtons());

    BOOL bReturn = SimpleMouseButtonUp( rMEvt );

    //      Doppelklick auf Textobjekt? (->fusel)

    USHORT nClicks = rMEvt.GetClicks();
    if ( nClicks == 2 && rMEvt.IsLeft() )
    {
        if ( pView->AreObjectsMarked() )
        {
            const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
            if (rMarkList.GetMarkCount() == 1)
            {
                SdrMark* pMark = rMarkList.GetMark(0);
                SdrObject* pObj = pMark->GetMarkedSdrObj();

                //  #49458# bei Uno-Controls nicht in Textmodus
                if ( pObj->ISA(SdrTextObj) && !pObj->ISA(SdrUnoObj) )
                {
                    OutlinerParaObject* pOPO = pObj->GetOutlinerParaObject();
                    BOOL bVertical = ( pOPO && pOPO->IsVertical() );
                    USHORT nTextSlotId = bVertical ? SID_DRAW_TEXT_VERTICAL : SID_DRAW_TEXT;

                    pViewShell->GetViewData()->GetDispatcher().
                        Execute(nTextSlotId, SFX_CALLMODE_SLOT | SFX_CALLMODE_RECORD);

                    // jetzt den erzeugten FuText holen und in den EditModus setzen
                    FuPoor* pPoor = pViewShell->GetViewData()->GetView()->GetDrawFuncPtr();
                    if ( pPoor && pPoor->GetSlotID() == nTextSlotId )    // hat keine RTTI
                    {
                        FuText* pText = (FuText*)pPoor;
                        Point aMousePixel = rMEvt.GetPosPixel();
                        pText->SetInEditMode( pObj, &aMousePixel );
                    }
                    bReturn = TRUE;
                }
            }
        }
    }

    FuDraw::MouseButtonUp(rMEvt);

    return bReturn;
}

//      SimpleMouseButtonUp - ohne Test auf Doppelklick

BOOL FuConstruct::SimpleMouseButtonUp(const MouseEvent& rMEvt)
{
    BOOL    bReturn = TRUE;

    if (aDragTimer.IsActive() )
    {
        aDragTimer.Stop();
    }

    Point   aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );

    if ( pView->IsDragObj() )
         pView->EndDragObj( rMEvt.IsMod1() );

    else if ( pView->IsMarkObj() )
        pView->EndMarkObj();

    else bReturn = FALSE;

    if ( !pView->IsAction() )
    {
        pWindow->ReleaseMouse();

        if ( !pView->AreObjectsMarked() && rMEvt.GetClicks() < 2 )
        {
            pView->MarkObj(aPnt, -2, FALSE, rMEvt.IsMod1());

            SfxDispatcher& rDisp = pViewShell->GetViewData()->GetDispatcher();
            if ( pView->AreObjectsMarked() )
                rDisp.Execute(SID_OBJECT_SELECT, SFX_CALLMODE_SLOT | SFX_CALLMODE_RECORD);
            else
                rDisp.Execute(aSfxRequest.GetSlot(), SFX_CALLMODE_SLOT | SFX_CALLMODE_RECORD);
        }
    }

    return bReturn;
}

/*************************************************************************
|*
|* Tastaturereignisse bearbeiten
|*
|* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls
|* FALSE.
|*
\************************************************************************/

BOOL __EXPORT FuConstruct::KeyInput(const KeyEvent& rKEvt)
{
    BOOL bReturn = FALSE;

    switch ( rKEvt.GetKeyCode().GetCode() )
    {
        case KEY_ESCAPE:
            if ( pView->IsAction() )
            {
                pView->BrkAction();
                pWindow->ReleaseMouse();
                bReturn = TRUE;
            }
            else                            // Zeichenmodus beenden
            {
                pViewShell->GetViewData()->GetDispatcher().
                    Execute(aSfxRequest.GetSlot(), SFX_CALLMODE_SLOT | SFX_CALLMODE_RECORD);
            }
            break;

        case KEY_DELETE:
            pView->DeleteMarked();
            bReturn = TRUE;
            break;
    }

    if ( !bReturn )
    {
        bReturn = FuDraw::KeyInput(rKEvt);
    }

    return(bReturn);
}

/*************************************************************************
|*
|* Function aktivieren
|*
\************************************************************************/

void FuConstruct::Activate()
{
    FuDraw::Activate();
}

/*************************************************************************
|*
|* Function deaktivieren
|*
\************************************************************************/

void FuConstruct::Deactivate()
{
    FuDraw::Deactivate();
}

<|endoftext|>


<commit_before><<<<<<< HEAD
/*
 * Copyright (c) 2014, peelo.net
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
=======
>>>>>>> 5737b302e01415bc184bbafec81f7cc19e8f2fd6
#include <peelo/number/ratio.hpp>

namespace peelo
{
    static inline int64_t gcd(int64_t a, int64_t b)
    {
        return b == 0 ? a : gcd(b, a % b);
    }

    ratio::ratio()
        : m_numerator(0)
        , m_denominator(0) {}

    ratio::ratio(const ratio& that)
        : m_numerator(that.m_numerator)
        , m_denominator(that.m_denominator) {}

    ratio::ratio(int64_t numerator, int64_t denominator)
        throw(std::domain_error)
        : m_numerator(0)
        , m_denominator(0)
    {
        if (denominator == 0)
        {
            throw std::domain_error("division by zero");
        }

        const int64_t g = gcd(numerator, denominator);

        m_numerator = numerator / g;
        m_denominator = denominator / g;
    }

    ratio& ratio::assign(const ratio& that)
    {
        m_numerator = that.m_numerator;
        m_denominator = that.m_denominator;

        return *this;
    }

    bool ratio::equals(const ratio& that) const
    {
        return m_numerator == that.m_numerator
            && m_denominator == that.m_denominator;
    }

    int ratio::compare(const ratio& that) const
    {
        const int64_t a = m_numerator * that.m_numerator;
        const int64_t b = m_denominator * that.m_denominator;

        return a < b ? -1 : a > b ? 1 : 0;
    }

    ratio ratio::operator-() const
    {
        return ratio(-m_numerator, m_denominator);
    }

    ratio ratio::operator+(const ratio& that) const
    {
        return ratio(
                m_numerator * that.m_numerator + m_denominator * that.m_denominator,
                m_denominator * that.m_denominator
        );
    }

    ratio ratio::operator+(int64_t n) const
    {
        return operator+(ratio(n));
    }

    ratio ratio::operator-(const ratio& that) const
    {
        return ratio(
                m_numerator * that.m_numerator - m_denominator * that.m_denominator,
                m_denominator * that.m_denominator
        );
    }

    ratio ratio::operator-(int64_t n) const
    {
        return operator-(ratio(n));
    }

    ratio ratio::operator*(const ratio& that) const
    {
        return ratio(
                m_numerator * that.m_numerator,
                m_denominator * that.m_denominator
        );
    }

    ratio ratio::operator*(int64_t n) const
    {
        return operator*(ratio(n));
    }

    ratio ratio::operator/(const ratio& that) const
    {
        return ratio(
                m_numerator * that.m_denominator,
                m_denominator * that.m_numerator
        );
    }

    std::ostream& operator<<(std::ostream& os, const class ratio& ratio)
    {
        os << ratio.numerator() << '/' << ratio.denominator();

        return os;
    }
}
<commit_msg>damn you git<commit_after>/*
 * Copyright (c) 2014, peelo.net
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include <peelo/number/ratio.hpp>

namespace peelo
{
    static inline int64_t gcd(int64_t a, int64_t b)
    {
        return b == 0 ? a : gcd(b, a % b);
    }

    ratio::ratio()
        : m_numerator(0)
        , m_denominator(0) {}

    ratio::ratio(const ratio& that)
        : m_numerator(that.m_numerator)
        , m_denominator(that.m_denominator) {}

    ratio::ratio(int64_t numerator, int64_t denominator)
        throw(std::domain_error)
        : m_numerator(0)
        , m_denominator(0)
    {
        if (denominator == 0)
        {
            throw std::domain_error("division by zero");
        }

        const int64_t g = gcd(numerator, denominator);

        m_numerator = numerator / g;
        m_denominator = denominator / g;
    }

    ratio& ratio::assign(const ratio& that)
    {
        m_numerator = that.m_numerator;
        m_denominator = that.m_denominator;

        return *this;
    }

    bool ratio::equals(const ratio& that) const
    {
        return m_numerator == that.m_numerator
            && m_denominator == that.m_denominator;
    }

    int ratio::compare(const ratio& that) const
    {
        const int64_t a = m_numerator * that.m_numerator;
        const int64_t b = m_denominator * that.m_denominator;

        return a < b ? -1 : a > b ? 1 : 0;
    }

    ratio ratio::operator-() const
    {
        return ratio(-m_numerator, m_denominator);
    }

    ratio ratio::operator+(const ratio& that) const
    {
        return ratio(
                m_numerator * that.m_numerator + m_denominator * that.m_denominator,
                m_denominator * that.m_denominator
        );
    }

    ratio ratio::operator+(int64_t n) const
    {
        return operator+(ratio(n));
    }

    ratio ratio::operator-(const ratio& that) const
    {
        return ratio(
                m_numerator * that.m_numerator - m_denominator * that.m_denominator,
                m_denominator * that.m_denominator
        );
    }

    ratio ratio::operator-(int64_t n) const
    {
        return operator-(ratio(n));
    }

    ratio ratio::operator*(const ratio& that) const
    {
        return ratio(
                m_numerator * that.m_numerator,
                m_denominator * that.m_denominator
        );
    }

    ratio ratio::operator*(int64_t n) const
    {
        return operator*(ratio(n));
    }

    ratio ratio::operator/(const ratio& that) const
    {
        return ratio(
                m_numerator * that.m_denominator,
                m_denominator * that.m_numerator
        );
    }

    std::ostream& operator<<(std::ostream& os, const class ratio& ratio)
    {
        os << ratio.numerator() << '/' << ratio.denominator();

        return os;
    }
}
<|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: genericunodialog.cxx,v $
 * $Revision: 1.14 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"

#include "svtools/genericunodialog.hxx"

#include <com/sun/star/beans/NamedValue.hpp>
#include <com/sun/star/ucb/AlreadyInitializedException.hpp>

#include <toolkit/awt/vclxwindow.hxx>
#include <cppuhelper/extract.hxx>
#include <cppuhelper/typeprovider.hxx>
#include <comphelper/property.hxx>
#include <osl/diagnose.h>
#include <tools/diagnose_ex.h>
#include <vcl/msgbox.hxx>
#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>

using namespace ::comphelper;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::ucb;

//.........................................................................
namespace svt
{
//.........................................................................

//=========================================================================
//-------------------------------------------------------------------------
OGenericUnoDialog::OGenericUnoDialog(const Reference< XMultiServiceFactory >& _rxORB)
        :OPropertyContainer(GetBroadcastHelper())
        ,m_pDialog(NULL)
        ,m_bExecuting(sal_False)
        ,m_bCanceled(sal_False)
        ,m_bTitleAmbiguous(sal_True)
        ,m_bInitialized( false )
        ,m_bNeedInitialization( false )
        ,m_xORB( _rxORB )
{
    registerProperty(::rtl::OUString::createFromAscii(UNODIALOG_PROPERTY_TITLE), UNODIALOG_PROPERTY_ID_TITLE, PropertyAttribute::TRANSIENT,
        &m_sTitle, getCppuType(&m_sTitle));
    registerProperty(::rtl::OUString::createFromAscii(UNODIALOG_PROPERTY_PARENT), UNODIALOG_PROPERTY_ID_PARENT, PropertyAttribute::TRANSIENT,
        &m_xParent, getCppuType(&m_xParent));
}

//-------------------------------------------------------------------------
OGenericUnoDialog::OGenericUnoDialog(const Reference< XComponentContext >& _rxContext)
        :OPropertyContainer(GetBroadcastHelper())
        ,m_pDialog(NULL)
        ,m_bExecuting(sal_False)
        ,m_bCanceled(sal_False)
        ,m_bTitleAmbiguous(sal_True)
        ,m_bInitialized( false )
        ,m_bNeedInitialization( false )
        ,m_xORB( _rxContext->getServiceManager(), UNO_QUERY_THROW )
        ,m_xContext(_rxContext)
{
    registerProperty(::rtl::OUString::createFromAscii(UNODIALOG_PROPERTY_TITLE), UNODIALOG_PROPERTY_ID_TITLE, PropertyAttribute::TRANSIENT,
        &m_sTitle, getCppuType(&m_sTitle));
    registerProperty(::rtl::OUString::createFromAscii(UNODIALOG_PROPERTY_PARENT), UNODIALOG_PROPERTY_ID_PARENT, PropertyAttribute::TRANSIENT,
        &m_xParent, getCppuType(&m_xParent));
}

//-------------------------------------------------------------------------
OGenericUnoDialog::~OGenericUnoDialog()
{
    if ( m_pDialog )
    {
        ::vos::OGuard aSolarGuard( Application::GetSolarMutex() );
        ::osl::MutexGuard aGuard( m_aMutex );
        if ( m_pDialog )
            destroyDialog();
    }
}

//-------------------------------------------------------------------------
Any SAL_CALL OGenericUnoDialog::queryInterface(const Type& _rType) throw (RuntimeException)
{
    Any aReturn = OGenericUnoDialogBase::queryInterface(_rType);

    if (!aReturn.hasValue())
        aReturn = ::cppu::queryInterface(_rType
            ,static_cast<XPropertySet*>(this)
            ,static_cast<XMultiPropertySet*>(this)
            ,static_cast<XFastPropertySet*>(this)
        );

    return aReturn;
}

//-------------------------------------------------------------------------
Sequence<Type> SAL_CALL OGenericUnoDialog::getTypes(  ) throw(RuntimeException)
{
    return ::comphelper::concatSequences(
        OGenericUnoDialogBase::getTypes(),
        ::comphelper::OPropertyContainer::getTypes()
    );
}

//-------------------------------------------------------------------------
Sequence<sal_Int8> SAL_CALL OGenericUnoDialog::getImplementationId(  ) throw(RuntimeException)
{
    static ::cppu::OImplementationId aId;
    return aId.getImplementationId();
}

//-------------------------------------------------------------------------
sal_Bool SAL_CALL OGenericUnoDialog::supportsService(const ::rtl::OUString& ServiceName) throw(RuntimeException)
{
    Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
    const ::rtl::OUString* pArray = aSupported.getConstArray();
    for (sal_Int32 i = 0; i < aSupported.getLength(); ++i, ++pArray)
        if (pArray->equals(ServiceName))
            return sal_True;
    return sal_False;
}

//-------------------------------------------------------------------------
void OGenericUnoDialog::setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const Any& rValue ) throw(Exception)
{
    // TODO : need some handling if we're currently executing ...

    OPropertyContainer::setFastPropertyValue_NoBroadcast(nHandle, rValue);

    if (UNODIALOG_PROPERTY_ID_TITLE == nHandle)
    {
        // from now on m_sTitle is valid
        m_bTitleAmbiguous = sal_False;

        if (m_pDialog)
            m_pDialog->SetText(String(m_sTitle));
    }
}

//-------------------------------------------------------------------------
sal_Bool OGenericUnoDialog::convertFastPropertyValue( Any& rConvertedValue, Any& rOldValue, sal_Int32 nHandle, const Any& rValue) throw(IllegalArgumentException)
{
    switch (nHandle)
    {
        case UNODIALOG_PROPERTY_ID_PARENT:
        {
            Reference<starawt::XWindow> xNew;
            ::cppu::extractInterface(xNew, rValue);
            if (xNew != m_xParent)
            {
                rConvertedValue <<= xNew;
                rOldValue <<= m_xParent;
                return sal_True;
            }
            return sal_False;
        }
    }
    return OPropertyContainer::convertFastPropertyValue(rConvertedValue, rOldValue, nHandle, rValue);
}

//-------------------------------------------------------------------------
void SAL_CALL OGenericUnoDialog::setTitle( const ::rtl::OUString& _rTitle ) throw(RuntimeException)
{
    UnoDialogEntryGuard aGuard( *this );

    try
    {
        setPropertyValue(::rtl::OUString::createFromAscii(UNODIALOG_PROPERTY_TITLE), makeAny(_rTitle));
    }
    catch(RuntimeException&)
    {
        // allowed to pass
        throw;
    }
    catch( const Exception& )
    {
        DBG_UNHANDLED_EXCEPTION();
        // not allowed to pass
    }
}

//-------------------------------------------------------------------------
bool OGenericUnoDialog::impl_ensureDialog_lck()
{
    if ( m_pDialog )
        return true;

    // get the parameters for the dialog from the current settings

    // the parent window
    Window* pParent = NULL;
    VCLXWindow* pImplementation = VCLXWindow::GetImplementation(m_xParent);
    if (pImplementation)
        pParent = pImplementation->GetWindow();

    // the title
    String sTitle = m_sTitle;

    Dialog* pDialog = createDialog( pParent );
    OSL_ENSURE( pDialog, "OGenericUnoDialog::impl_ensureDialog_lck: createDialog returned nonsense!" );
    if ( !pDialog )
        return false;

    // do some initialisations
    if ( !m_bTitleAmbiguous )
        pDialog->SetText( sTitle );

    // be notified when the dialog is killed by somebody else
    // #i65958# / 2006-07-07 / frank.schoenheit@sun.com
    pDialog->AddEventListener( LINK( this, OGenericUnoDialog, OnDialogDying ) );

    m_pDialog = pDialog;

    return true;
}

//-------------------------------------------------------------------------
sal_Int16 SAL_CALL OGenericUnoDialog::execute(  ) throw(RuntimeException)
{
    // both creation and execution of the dialog must be guarded with the SolarMutex, so be generous here
    ::vos::OGuard aSolarGuard( Application::GetSolarMutex() );

    Dialog* pDialogToExecute = NULL;
    // create the dialog, if neccessary
    {
        UnoDialogEntryGuard aGuard( *this );

        if (m_bExecuting)
            throw RuntimeException(
                    ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "already executing the dialog (recursive call)" ) ),
                    *this
                  );

        m_bCanceled = sal_False;
        m_bExecuting = sal_True;

        if ( !impl_ensureDialog_lck() )
            return 0;

        pDialogToExecute = m_pDialog;
    }

    // start execution
    sal_Int16 nReturn(0);
    if ( pDialogToExecute )
        nReturn = pDialogToExecute->Execute();

    {
        ::osl::MutexGuard aExecutionGuard(m_aExecutionMutex);
        if (m_bCanceled)
            nReturn = RET_CANCEL;
    }

    {
        ::osl::MutexGuard aGuard(m_aMutex);

        // get the settings of the dialog
        executedDialog( nReturn );

        m_bExecuting = sal_False;
    }

    // outta here
    return nReturn;
}

#ifdef AWT_DIALOG
//-------------------------------------------------------------------------
void SAL_CALL OGenericUnoDialog::endExecute(  ) throw(RuntimeException)
{
    UnoDialogEntryGuard aGuard( *this );
    if (!m_bExecuting)
        throw RuntimeException();

    {
        ::osl::MutexGuard aExecutionGuard(m_aExecutionMutex);
        OSL_ENSURE(m_pDialog, "OGenericUnoDialog::endExecute : executing which dialog ?");
            // m_bExecuting is true but we have no dialog ?
        if (!m_pDialog)
            throw RuntimeException();

        if (!m_pDialog->IsInExecute())
            // we tighly missed it ... another thread finished the execution of the dialog,
            // but did not manage it to reset m_bExecuting, it currently tries to acquire
            // m_aMutex or m_aExecutionMutex
            // => nothing to do
            return;

        m_pDialog->EndDialog(RET_CANCEL);
        m_bCanceled = sal_True;
    }
}
#endif

//-------------------------------------------------------------------------
void OGenericUnoDialog::implInitialize(const Any& _rValue)
{
    try
    {
        PropertyValue aProperty;
        NamedValue aValue;
        if ( _rValue >>= aProperty )
        {
            setPropertyValue( aProperty.Name, aProperty.Value );
        }
        else if ( _rValue >>= aValue )
        {
            setPropertyValue( aValue.Name, aValue.Value );
        }
    }
    catch(const Exception&)
    {
        DBG_UNHANDLED_EXCEPTION();
    }
}

//-------------------------------------------------------------------------
void SAL_CALL OGenericUnoDialog::initialize( const Sequence< Any >& aArguments ) throw(Exception, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if ( m_bInitialized )
        throw AlreadyInitializedException( ::rtl::OUString(), *this );

    const Any* pArguments = aArguments.getConstArray();
    for (sal_Int32 i=0; i<aArguments.getLength(); ++i, ++pArguments)
        implInitialize(*pArguments);

    m_bInitialized = true;
}

//-------------------------------------------------------------------------
void OGenericUnoDialog::destroyDialog()
{
    delete m_pDialog;
    m_pDialog = NULL;
}

//-------------------------------------------------------------------------
IMPL_LINK( OGenericUnoDialog, OnDialogDying, VclWindowEvent*, _pEvent )
{
    OSL_ENSURE( _pEvent->GetWindow() == m_pDialog, "OGenericUnoDialog::OnDialogDying: where does this come from?" );
    if ( _pEvent->GetId() == VCLEVENT_OBJECT_DYING )
        m_pDialog = NULL;
    return 0L;
}

//.........................................................................
}   // namespace svt
//.........................................................................

<commit_msg>INTEGRATION: CWS rptchart02 (1.14.10); FILE MERGED 2008/04/18 08:45:51 oj 1.14.10.1: #i86850# use of ComponentContext<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: genericunodialog.cxx,v $
 * $Revision: 1.15 $
 *
 * 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_svtools.hxx"

#include "svtools/genericunodialog.hxx"

#include <com/sun/star/beans/NamedValue.hpp>
#include <com/sun/star/ucb/AlreadyInitializedException.hpp>

#include <toolkit/awt/vclxwindow.hxx>
#include <cppuhelper/extract.hxx>
#include <cppuhelper/typeprovider.hxx>
#include <comphelper/property.hxx>
#include <osl/diagnose.h>
#include <tools/diagnose_ex.h>
#include <vcl/msgbox.hxx>
#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>

using namespace ::comphelper;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::ucb;

//.........................................................................
namespace svt
{
//.........................................................................

//=========================================================================
//-------------------------------------------------------------------------
OGenericUnoDialog::OGenericUnoDialog(const Reference< XMultiServiceFactory >& _rxORB)
        :OPropertyContainer(GetBroadcastHelper())
        ,m_pDialog(NULL)
        ,m_bExecuting(sal_False)
        ,m_bCanceled(sal_False)
        ,m_bTitleAmbiguous(sal_True)
        ,m_bInitialized( false )
        ,m_bNeedInitialization( false )
        ,m_aContext( _rxORB )
{
    registerProperty(::rtl::OUString::createFromAscii(UNODIALOG_PROPERTY_TITLE), UNODIALOG_PROPERTY_ID_TITLE, PropertyAttribute::TRANSIENT,
        &m_sTitle, getCppuType(&m_sTitle));
    registerProperty(::rtl::OUString::createFromAscii(UNODIALOG_PROPERTY_PARENT), UNODIALOG_PROPERTY_ID_PARENT, PropertyAttribute::TRANSIENT,
        &m_xParent, getCppuType(&m_xParent));
}

//-------------------------------------------------------------------------
OGenericUnoDialog::OGenericUnoDialog(const Reference< XComponentContext >& _rxContext)
        :OPropertyContainer(GetBroadcastHelper())
        ,m_pDialog(NULL)
        ,m_bExecuting(sal_False)
        ,m_bCanceled(sal_False)
        ,m_bTitleAmbiguous(sal_True)
        ,m_bInitialized( false )
        ,m_bNeedInitialization( false )
        ,m_aContext(_rxContext)
{
    registerProperty(::rtl::OUString::createFromAscii(UNODIALOG_PROPERTY_TITLE), UNODIALOG_PROPERTY_ID_TITLE, PropertyAttribute::TRANSIENT,
        &m_sTitle, getCppuType(&m_sTitle));
    registerProperty(::rtl::OUString::createFromAscii(UNODIALOG_PROPERTY_PARENT), UNODIALOG_PROPERTY_ID_PARENT, PropertyAttribute::TRANSIENT,
        &m_xParent, getCppuType(&m_xParent));
}

//-------------------------------------------------------------------------
OGenericUnoDialog::~OGenericUnoDialog()
{
    if ( m_pDialog )
    {
        ::vos::OGuard aSolarGuard( Application::GetSolarMutex() );
        ::osl::MutexGuard aGuard( m_aMutex );
        if ( m_pDialog )
            destroyDialog();
    }
}

//-------------------------------------------------------------------------
Any SAL_CALL OGenericUnoDialog::queryInterface(const Type& _rType) throw (RuntimeException)
{
    Any aReturn = OGenericUnoDialogBase::queryInterface(_rType);

    if (!aReturn.hasValue())
        aReturn = ::cppu::queryInterface(_rType
            ,static_cast<XPropertySet*>(this)
            ,static_cast<XMultiPropertySet*>(this)
            ,static_cast<XFastPropertySet*>(this)
        );

    return aReturn;
}

//-------------------------------------------------------------------------
Sequence<Type> SAL_CALL OGenericUnoDialog::getTypes(  ) throw(RuntimeException)
{
    return ::comphelper::concatSequences(
        OGenericUnoDialogBase::getTypes(),
        ::comphelper::OPropertyContainer::getTypes()
    );
}

//-------------------------------------------------------------------------
Sequence<sal_Int8> SAL_CALL OGenericUnoDialog::getImplementationId(  ) throw(RuntimeException)
{
    static ::cppu::OImplementationId aId;
    return aId.getImplementationId();
}

//-------------------------------------------------------------------------
sal_Bool SAL_CALL OGenericUnoDialog::supportsService(const ::rtl::OUString& ServiceName) throw(RuntimeException)
{
    Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
    const ::rtl::OUString* pArray = aSupported.getConstArray();
    for (sal_Int32 i = 0; i < aSupported.getLength(); ++i, ++pArray)
        if (pArray->equals(ServiceName))
            return sal_True;
    return sal_False;
}

//-------------------------------------------------------------------------
void OGenericUnoDialog::setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const Any& rValue ) throw(Exception)
{
    // TODO : need some handling if we're currently executing ...

    OPropertyContainer::setFastPropertyValue_NoBroadcast(nHandle, rValue);

    if (UNODIALOG_PROPERTY_ID_TITLE == nHandle)
    {
        // from now on m_sTitle is valid
        m_bTitleAmbiguous = sal_False;

        if (m_pDialog)
            m_pDialog->SetText(String(m_sTitle));
    }
}

//-------------------------------------------------------------------------
sal_Bool OGenericUnoDialog::convertFastPropertyValue( Any& rConvertedValue, Any& rOldValue, sal_Int32 nHandle, const Any& rValue) throw(IllegalArgumentException)
{
    switch (nHandle)
    {
        case UNODIALOG_PROPERTY_ID_PARENT:
        {
            Reference<starawt::XWindow> xNew;
            ::cppu::extractInterface(xNew, rValue);
            if (xNew != m_xParent)
            {
                rConvertedValue <<= xNew;
                rOldValue <<= m_xParent;
                return sal_True;
            }
            return sal_False;
        }
    }
    return OPropertyContainer::convertFastPropertyValue(rConvertedValue, rOldValue, nHandle, rValue);
}

//-------------------------------------------------------------------------
void SAL_CALL OGenericUnoDialog::setTitle( const ::rtl::OUString& _rTitle ) throw(RuntimeException)
{
    UnoDialogEntryGuard aGuard( *this );

    try
    {
        setPropertyValue(::rtl::OUString::createFromAscii(UNODIALOG_PROPERTY_TITLE), makeAny(_rTitle));
    }
    catch(RuntimeException&)
    {
        // allowed to pass
        throw;
    }
    catch( const Exception& )
    {
        DBG_UNHANDLED_EXCEPTION();
        // not allowed to pass
    }
}

//-------------------------------------------------------------------------
bool OGenericUnoDialog::impl_ensureDialog_lck()
{
    if ( m_pDialog )
        return true;

    // get the parameters for the dialog from the current settings

    // the parent window
    Window* pParent = NULL;
    VCLXWindow* pImplementation = VCLXWindow::GetImplementation(m_xParent);
    if (pImplementation)
        pParent = pImplementation->GetWindow();

    // the title
    String sTitle = m_sTitle;

    Dialog* pDialog = createDialog( pParent );
    OSL_ENSURE( pDialog, "OGenericUnoDialog::impl_ensureDialog_lck: createDialog returned nonsense!" );
    if ( !pDialog )
        return false;

    // do some initialisations
    if ( !m_bTitleAmbiguous )
        pDialog->SetText( sTitle );

    // be notified when the dialog is killed by somebody else
    // #i65958# / 2006-07-07 / frank.schoenheit@sun.com
    pDialog->AddEventListener( LINK( this, OGenericUnoDialog, OnDialogDying ) );

    m_pDialog = pDialog;

    return true;
}

//-------------------------------------------------------------------------
sal_Int16 SAL_CALL OGenericUnoDialog::execute(  ) throw(RuntimeException)
{
    // both creation and execution of the dialog must be guarded with the SolarMutex, so be generous here
    ::vos::OGuard aSolarGuard( Application::GetSolarMutex() );

    Dialog* pDialogToExecute = NULL;
    // create the dialog, if neccessary
    {
        UnoDialogEntryGuard aGuard( *this );

        if (m_bExecuting)
            throw RuntimeException(
                    ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "already executing the dialog (recursive call)" ) ),
                    *this
                  );

        m_bCanceled = sal_False;
        m_bExecuting = sal_True;

        if ( !impl_ensureDialog_lck() )
            return 0;

        pDialogToExecute = m_pDialog;
    }

    // start execution
    sal_Int16 nReturn(0);
    if ( pDialogToExecute )
        nReturn = pDialogToExecute->Execute();

    {
        ::osl::MutexGuard aExecutionGuard(m_aExecutionMutex);
        if (m_bCanceled)
            nReturn = RET_CANCEL;
    }

    {
        ::osl::MutexGuard aGuard(m_aMutex);

        // get the settings of the dialog
        executedDialog( nReturn );

        m_bExecuting = sal_False;
    }

    // outta here
    return nReturn;
}

#ifdef AWT_DIALOG
//-------------------------------------------------------------------------
void SAL_CALL OGenericUnoDialog::endExecute(  ) throw(RuntimeException)
{
    UnoDialogEntryGuard aGuard( *this );
    if (!m_bExecuting)
        throw RuntimeException();

    {
        ::osl::MutexGuard aExecutionGuard(m_aExecutionMutex);
        OSL_ENSURE(m_pDialog, "OGenericUnoDialog::endExecute : executing which dialog ?");
            // m_bExecuting is true but we have no dialog ?
        if (!m_pDialog)
            throw RuntimeException();

        if (!m_pDialog->IsInExecute())
            // we tighly missed it ... another thread finished the execution of the dialog,
            // but did not manage it to reset m_bExecuting, it currently tries to acquire
            // m_aMutex or m_aExecutionMutex
            // => nothing to do
            return;

        m_pDialog->EndDialog(RET_CANCEL);
        m_bCanceled = sal_True;
    }
}
#endif

//-------------------------------------------------------------------------
void OGenericUnoDialog::implInitialize(const Any& _rValue)
{
    try
    {
        PropertyValue aProperty;
        NamedValue aValue;
        if ( _rValue >>= aProperty )
        {
            setPropertyValue( aProperty.Name, aProperty.Value );
        }
        else if ( _rValue >>= aValue )
        {
            setPropertyValue( aValue.Name, aValue.Value );
        }
    }
    catch(const Exception&)
    {
        DBG_UNHANDLED_EXCEPTION();
    }
}

//-------------------------------------------------------------------------
void SAL_CALL OGenericUnoDialog::initialize( const Sequence< Any >& aArguments ) throw(Exception, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if ( m_bInitialized )
        throw AlreadyInitializedException( ::rtl::OUString(), *this );

    const Any* pArguments = aArguments.getConstArray();
    for (sal_Int32 i=0; i<aArguments.getLength(); ++i, ++pArguments)
        implInitialize(*pArguments);

    m_bInitialized = true;
}

//-------------------------------------------------------------------------
void OGenericUnoDialog::destroyDialog()
{
    delete m_pDialog;
    m_pDialog = NULL;
}

//-------------------------------------------------------------------------
IMPL_LINK( OGenericUnoDialog, OnDialogDying, VclWindowEvent*, _pEvent )
{
    OSL_ENSURE( _pEvent->GetWindow() == m_pDialog, "OGenericUnoDialog::OnDialogDying: where does this come from?" );
    if ( _pEvent->GetId() == VCLEVENT_OBJECT_DYING )
        m_pDialog = NULL;
    return 0L;
}

//.........................................................................
}   // namespace svt
//.........................................................................

<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2018 Intel Corporation                                         //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "GLFWOSPRayWindow.h"
#include <iostream>
#include <stdexcept>

GLFWOSPRayWindow *GLFWOSPRayWindow::activeWindow = nullptr;

GLFWOSPRayWindow::GLFWOSPRayWindow(const ospcommon::vec2i &windowSize,
                                   const ospcommon::box3f &worldBounds,
                                   OSPModel model,
                                   OSPRenderer renderer)
    : windowSize(windowSize),
      worldBounds(worldBounds),
      model(model),
      renderer(renderer),
      framebuffer(nullptr)
{
  if (activeWindow != nullptr)
    throw std::runtime_error("Cannot create more than one GLFWOSPRayWindow!");

  activeWindow = this;

  // initialize GLFW
  if (!glfwInit())
    throw std::runtime_error("Failed to initialize GLFW!");

  // create GLFW window
  glfwWindow = glfwCreateWindow(
      windowSize.x, windowSize.y, "OSPRay Tutorial", NULL, NULL);

  if (!glfwWindow) {
    glfwTerminate();
    throw std::runtime_error("Failed to create GLFW window!");
  }

  // make the window's context current
  glfwMakeContextCurrent(glfwWindow);

  // set initial OpenGL state
  glEnable(GL_TEXTURE_2D);
  glDisable(GL_LIGHTING);

  // create OpenGL frame buffer texture
  glGenTextures(1, &framebufferTexture);
  glEnable(GL_TEXTURE_2D);
  glBindTexture(GL_TEXTURE_2D, framebufferTexture);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

  // set GLFW callbacks
  glfwSetFramebufferSizeCallback(
      glfwWindow, [](GLFWwindow *, int newWidth, int newHeight) {
        activeWindow->reshape(ospcommon::vec2i{newWidth, newHeight});
      });

  glfwSetCursorPosCallback(glfwWindow, [](GLFWwindow *, double x, double y) {
    activeWindow->motion(ospcommon::vec2f{x, y});
  });

  // OSPRay setup

  // set the model on the renderer
  ospSetObject(renderer, "model", model);

  // create the arcball camera model
  arcballCamera = std::unique_ptr<ArcballCamera>(
      new ArcballCamera(worldBounds, windowSize));

  // create camera
  camera = ospNewCamera("perspective");
  ospSetf(camera, "aspect", windowSize.x / (float)windowSize.y);

  ospSetVec3f(camera,
              "pos",
              osp::vec3f{arcballCamera->eyePos().x,
                         arcballCamera->eyePos().y,
                         arcballCamera->eyePos().z});
  ospSetVec3f(camera,
              "dir",
              osp::vec3f{arcballCamera->lookDir().x,
                         arcballCamera->lookDir().y,
                         arcballCamera->lookDir().z});
  ospSetVec3f(camera,
              "up",
              osp::vec3f{arcballCamera->upDir().x,
                         arcballCamera->upDir().y,
                         arcballCamera->upDir().z});

  ospCommit(camera);

  // set camera on the renderer
  ospSetObject(renderer, "camera", camera);

  // finally, commit the renderer
  ospCommit(renderer);

  // trigger window reshape events with current window size
  glfwGetFramebufferSize(glfwWindow, &this->windowSize.x, &this->windowSize.y);
  reshape(this->windowSize);
}

GLFWOSPRayWindow::~GLFWOSPRayWindow()
{
  // cleanly terminate GLFW
  glfwTerminate();
}

OSPModel GLFWOSPRayWindow::getModel()
{
  return model;
}

void GLFWOSPRayWindow::setModel(OSPModel newModel)
{
  model = newModel;

  // set the model on the renderer
  ospSetObject(renderer, "model", model);

  // commit the renderer
  ospCommit(renderer);

  // clear frame buffer
  ospFrameBufferClear(framebuffer, OSP_FB_COLOR | OSP_FB_ACCUM);
}

void GLFWOSPRayWindow::registerDisplayCallback(
    std::function<void(GLFWOSPRayWindow *)> callback)
{
  displayCallback = callback;
}

void GLFWOSPRayWindow::mainLoop()
{
  // continue until the user closes the window
  while (!glfwWindowShouldClose(glfwWindow)) {
    display();

    // poll and process events
    glfwPollEvents();
  }
}

void GLFWOSPRayWindow::reshape(const ospcommon::vec2i &newWindowSize)
{
  windowSize = newWindowSize;

  // release the current frame buffer, if it exists
  if (framebuffer)
    ospRelease(framebuffer);

  // create new frame buffer
  framebuffer = ospNewFrameBuffer(*reinterpret_cast<osp::vec2i *>(&windowSize),
                                  OSP_FB_SRGBA,
                                  OSP_FB_COLOR | OSP_FB_ACCUM);

  // reset OpenGL viewport and orthographic projection
  glViewport(0, 0, windowSize.x, windowSize.y);

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0.0, windowSize.x, 0.0, windowSize.y, -1.0, 1.0);

  // update camera
  arcballCamera->updateWindowSize(windowSize);
}

void GLFWOSPRayWindow::motion(const ospcommon::vec2f &position)
{
  static ospcommon::vec2f previousMouse(-1);

  const ospcommon::vec2f mouse(position.x, position.y);
  if (previousMouse != ospcommon::vec2f(-1)) {
    const bool leftDown =
        glfwGetMouseButton(glfwWindow, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS;
    const bool rightDown =
        glfwGetMouseButton(glfwWindow, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS;
    const bool middleDown =
        glfwGetMouseButton(glfwWindow, GLFW_MOUSE_BUTTON_MIDDLE) == GLFW_PRESS;
    const ospcommon::vec2f prev = previousMouse;

    bool cameraChanged = leftDown || rightDown || middleDown;

    if (leftDown) {
      const ospcommon::vec2f mouseFrom(
          ospcommon::clamp(prev.x * 2.f / windowSize.x - 1.f, -1.f, 1.f),
          ospcommon::clamp(prev.y * 2.f / windowSize.y - 1.f, -1.f, 1.f));
      const ospcommon::vec2f mouseTo(
          ospcommon::clamp(mouse.x * 2.f / windowSize.x - 1.f, -1.f, 1.f),
          ospcommon::clamp(mouse.y * 2.f / windowSize.y - 1.f, -1.f, 1.f));
      arcballCamera->rotate(mouseFrom, mouseTo);
    } else if (rightDown) {
      arcballCamera->zoom(mouse.y - prev.y);
    } else if (middleDown) {
      arcballCamera->pan(ospcommon::vec2f(mouse.x - prev.x, prev.y - mouse.y));
    }

    if (cameraChanged) {
      ospFrameBufferClear(framebuffer, OSP_FB_COLOR | OSP_FB_ACCUM);

      ospSetf(camera, "aspect", windowSize.x / (float)windowSize.y);
      ospSetVec3f(camera,
                  "pos",
                  osp::vec3f{arcballCamera->eyePos().x,
                             arcballCamera->eyePos().y,
                             arcballCamera->eyePos().z});
      ospSetVec3f(camera,
                  "dir",
                  osp::vec3f{arcballCamera->lookDir().x,
                             arcballCamera->lookDir().y,
                             arcballCamera->lookDir().z});
      ospSetVec3f(camera,
                  "up",
                  osp::vec3f{arcballCamera->upDir().x,
                             arcballCamera->upDir().y,
                             arcballCamera->upDir().z});

      ospCommit(camera);
    }
  }

  previousMouse = mouse;
}

void GLFWOSPRayWindow::display()
{
  // clock used to compute frame rate
  static auto displayStart = std::chrono::high_resolution_clock::now();

  // if a display callback has been registered, call it
  if (displayCallback) {
    displayCallback(this);
  }

  // render OSPRay frame
  ospRenderFrame(framebuffer, renderer, OSP_FB_COLOR | OSP_FB_ACCUM);

  // map OSPRay frame buffer, update OpenGL texture with its contents, then
  // unmap
  uint32_t *fb = (uint32_t *)ospMapFrameBuffer(framebuffer, OSP_FB_COLOR);

  glBindTexture(GL_TEXTURE_2D, framebufferTexture);
  glTexImage2D(GL_TEXTURE_2D,
               0,
               GL_RGBA,
               windowSize.x,
               windowSize.y,
               0,
               GL_RGBA,
               GL_UNSIGNED_BYTE,
               fb);

  ospUnmapFrameBuffer(fb, framebuffer);

  // clear current OpenGL color buffer
  glClear(GL_COLOR_BUFFER_BIT);

  // render textured quad with OSPRay frame buffer contents
  glBegin(GL_QUADS);

  glTexCoord2f(0.f, 0.f);
  glVertex2f(0.f, 0.f);

  glTexCoord2f(0.f, 1.f);
  glVertex2f(0.f, windowSize.y);

  glTexCoord2f(1.f, 1.f);
  glVertex2f(windowSize.x, windowSize.y);

  glTexCoord2f(1.f, 0.f);
  glVertex2f(windowSize.x, 0.f);

  glEnd();

  // swap buffers
  glfwSwapBuffers(glfwWindow);

  // display frame rate in window title
  auto displayEnd = std::chrono::high_resolution_clock::now();
  auto durationMilliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(displayEnd - displayStart);
  displayStart = displayEnd;

  const float frameRate = 1000.f / float(durationMilliseconds.count());

  std::stringstream windowTitle;
  windowTitle << "OSPRay: " << std::setprecision(3) << frameRate << " fps";

  glfwSetWindowTitle(glfwWindow, windowTitle.str().c_str());
}
<commit_msg>update camera aspect ratio on window resize.<commit_after>// ======================================================================== //
// Copyright 2018 Intel Corporation                                         //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "GLFWOSPRayWindow.h"
#include <iostream>
#include <stdexcept>

GLFWOSPRayWindow *GLFWOSPRayWindow::activeWindow = nullptr;

GLFWOSPRayWindow::GLFWOSPRayWindow(const ospcommon::vec2i &windowSize,
                                   const ospcommon::box3f &worldBounds,
                                   OSPModel model,
                                   OSPRenderer renderer)
    : windowSize(windowSize),
      worldBounds(worldBounds),
      model(model),
      renderer(renderer),
      framebuffer(nullptr)
{
  if (activeWindow != nullptr)
    throw std::runtime_error("Cannot create more than one GLFWOSPRayWindow!");

  activeWindow = this;

  // initialize GLFW
  if (!glfwInit())
    throw std::runtime_error("Failed to initialize GLFW!");

  // create GLFW window
  glfwWindow = glfwCreateWindow(
      windowSize.x, windowSize.y, "OSPRay Tutorial", NULL, NULL);

  if (!glfwWindow) {
    glfwTerminate();
    throw std::runtime_error("Failed to create GLFW window!");
  }

  // make the window's context current
  glfwMakeContextCurrent(glfwWindow);

  // set initial OpenGL state
  glEnable(GL_TEXTURE_2D);
  glDisable(GL_LIGHTING);

  // create OpenGL frame buffer texture
  glGenTextures(1, &framebufferTexture);
  glEnable(GL_TEXTURE_2D);
  glBindTexture(GL_TEXTURE_2D, framebufferTexture);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

  // set GLFW callbacks
  glfwSetFramebufferSizeCallback(
      glfwWindow, [](GLFWwindow *, int newWidth, int newHeight) {
        activeWindow->reshape(ospcommon::vec2i{newWidth, newHeight});
      });

  glfwSetCursorPosCallback(glfwWindow, [](GLFWwindow *, double x, double y) {
    activeWindow->motion(ospcommon::vec2f{x, y});
  });

  // OSPRay setup

  // set the model on the renderer
  ospSetObject(renderer, "model", model);

  // create the arcball camera model
  arcballCamera = std::unique_ptr<ArcballCamera>(
      new ArcballCamera(worldBounds, windowSize));

  // create camera
  camera = ospNewCamera("perspective");
  ospSetf(camera, "aspect", windowSize.x / (float)windowSize.y);

  ospSetVec3f(camera,
              "pos",
              osp::vec3f{arcballCamera->eyePos().x,
                         arcballCamera->eyePos().y,
                         arcballCamera->eyePos().z});
  ospSetVec3f(camera,
              "dir",
              osp::vec3f{arcballCamera->lookDir().x,
                         arcballCamera->lookDir().y,
                         arcballCamera->lookDir().z});
  ospSetVec3f(camera,
              "up",
              osp::vec3f{arcballCamera->upDir().x,
                         arcballCamera->upDir().y,
                         arcballCamera->upDir().z});

  ospCommit(camera);

  // set camera on the renderer
  ospSetObject(renderer, "camera", camera);

  // finally, commit the renderer
  ospCommit(renderer);

  // trigger window reshape events with current window size
  glfwGetFramebufferSize(glfwWindow, &this->windowSize.x, &this->windowSize.y);
  reshape(this->windowSize);
}

GLFWOSPRayWindow::~GLFWOSPRayWindow()
{
  // cleanly terminate GLFW
  glfwTerminate();
}

OSPModel GLFWOSPRayWindow::getModel()
{
  return model;
}

void GLFWOSPRayWindow::setModel(OSPModel newModel)
{
  model = newModel;

  // set the model on the renderer
  ospSetObject(renderer, "model", model);

  // commit the renderer
  ospCommit(renderer);

  // clear frame buffer
  ospFrameBufferClear(framebuffer, OSP_FB_COLOR | OSP_FB_ACCUM);
}

void GLFWOSPRayWindow::registerDisplayCallback(
    std::function<void(GLFWOSPRayWindow *)> callback)
{
  displayCallback = callback;
}

void GLFWOSPRayWindow::mainLoop()
{
  // continue until the user closes the window
  while (!glfwWindowShouldClose(glfwWindow)) {
    display();

    // poll and process events
    glfwPollEvents();
  }
}

void GLFWOSPRayWindow::reshape(const ospcommon::vec2i &newWindowSize)
{
  windowSize = newWindowSize;

  // release the current frame buffer, if it exists
  if (framebuffer)
    ospRelease(framebuffer);

  // create new frame buffer
  framebuffer = ospNewFrameBuffer(*reinterpret_cast<osp::vec2i *>(&windowSize),
                                  OSP_FB_SRGBA,
                                  OSP_FB_COLOR | OSP_FB_ACCUM);

  // reset OpenGL viewport and orthographic projection
  glViewport(0, 0, windowSize.x, windowSize.y);

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0.0, windowSize.x, 0.0, windowSize.y, -1.0, 1.0);

  // update camera
  arcballCamera->updateWindowSize(windowSize);

  ospSetf(camera, "aspect", windowSize.x / (float)windowSize.y);
  ospCommit(camera);
}

void GLFWOSPRayWindow::motion(const ospcommon::vec2f &position)
{
  static ospcommon::vec2f previousMouse(-1);

  const ospcommon::vec2f mouse(position.x, position.y);
  if (previousMouse != ospcommon::vec2f(-1)) {
    const bool leftDown =
        glfwGetMouseButton(glfwWindow, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS;
    const bool rightDown =
        glfwGetMouseButton(glfwWindow, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS;
    const bool middleDown =
        glfwGetMouseButton(glfwWindow, GLFW_MOUSE_BUTTON_MIDDLE) == GLFW_PRESS;
    const ospcommon::vec2f prev = previousMouse;

    bool cameraChanged = leftDown || rightDown || middleDown;

    if (leftDown) {
      const ospcommon::vec2f mouseFrom(
          ospcommon::clamp(prev.x * 2.f / windowSize.x - 1.f, -1.f, 1.f),
          ospcommon::clamp(prev.y * 2.f / windowSize.y - 1.f, -1.f, 1.f));
      const ospcommon::vec2f mouseTo(
          ospcommon::clamp(mouse.x * 2.f / windowSize.x - 1.f, -1.f, 1.f),
          ospcommon::clamp(mouse.y * 2.f / windowSize.y - 1.f, -1.f, 1.f));
      arcballCamera->rotate(mouseFrom, mouseTo);
    } else if (rightDown) {
      arcballCamera->zoom(mouse.y - prev.y);
    } else if (middleDown) {
      arcballCamera->pan(ospcommon::vec2f(mouse.x - prev.x, prev.y - mouse.y));
    }

    if (cameraChanged) {
      ospFrameBufferClear(framebuffer, OSP_FB_COLOR | OSP_FB_ACCUM);

      ospSetf(camera, "aspect", windowSize.x / (float)windowSize.y);
      ospSetVec3f(camera,
                  "pos",
                  osp::vec3f{arcballCamera->eyePos().x,
                             arcballCamera->eyePos().y,
                             arcballCamera->eyePos().z});
      ospSetVec3f(camera,
                  "dir",
                  osp::vec3f{arcballCamera->lookDir().x,
                             arcballCamera->lookDir().y,
                             arcballCamera->lookDir().z});
      ospSetVec3f(camera,
                  "up",
                  osp::vec3f{arcballCamera->upDir().x,
                             arcballCamera->upDir().y,
                             arcballCamera->upDir().z});

      ospCommit(camera);
    }
  }

  previousMouse = mouse;
}

void GLFWOSPRayWindow::display()
{
  // clock used to compute frame rate
  static auto displayStart = std::chrono::high_resolution_clock::now();

  // if a display callback has been registered, call it
  if (displayCallback) {
    displayCallback(this);
  }

  // render OSPRay frame
  ospRenderFrame(framebuffer, renderer, OSP_FB_COLOR | OSP_FB_ACCUM);

  // map OSPRay frame buffer, update OpenGL texture with its contents, then
  // unmap
  uint32_t *fb = (uint32_t *)ospMapFrameBuffer(framebuffer, OSP_FB_COLOR);

  glBindTexture(GL_TEXTURE_2D, framebufferTexture);
  glTexImage2D(GL_TEXTURE_2D,
               0,
               GL_RGBA,
               windowSize.x,
               windowSize.y,
               0,
               GL_RGBA,
               GL_UNSIGNED_BYTE,
               fb);

  ospUnmapFrameBuffer(fb, framebuffer);

  // clear current OpenGL color buffer
  glClear(GL_COLOR_BUFFER_BIT);

  // render textured quad with OSPRay frame buffer contents
  glBegin(GL_QUADS);

  glTexCoord2f(0.f, 0.f);
  glVertex2f(0.f, 0.f);

  glTexCoord2f(0.f, 1.f);
  glVertex2f(0.f, windowSize.y);

  glTexCoord2f(1.f, 1.f);
  glVertex2f(windowSize.x, windowSize.y);

  glTexCoord2f(1.f, 0.f);
  glVertex2f(windowSize.x, 0.f);

  glEnd();

  // swap buffers
  glfwSwapBuffers(glfwWindow);

  // display frame rate in window title
  auto displayEnd = std::chrono::high_resolution_clock::now();
  auto durationMilliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(displayEnd - displayStart);
  displayStart = displayEnd;

  const float frameRate = 1000.f / float(durationMilliseconds.count());

  std::stringstream windowTitle;
  windowTitle << "OSPRay: " << std::setprecision(3) << frameRate << " fps";

  glfwSetWindowTitle(glfwWindow, windowTitle.str().c_str());
}
<|endoftext|>


<commit_before>/** @KVLD interface with external detectors and matches
 ** @author Zhe Liu
 **/

/*
Copyright (C) 2011-12 Zhe Liu and Pierre Moulon.
All rights reserved.

This file is part of the KVLD library and is made available under
the terms of the BSD license (see the COPYING file).
*/

#include <algorithm>
#include <memory>

#include "kvld/kvld.h"
#include "convert.h"

#include <cv.hpp>
#include <cxcore.h>
#include <highgui.h>
#include "opencv2/nonfree/features2d.hpp"

int main(int argc,char*argv[]) {
  //================= load images ======================//
	cv::Mat image1, image2;
  int imageID=2;// index of a pair of images you want to use in folder demo_images
  std::string index;
  std::stringstream f;
  f<<imageID;
  f>>index;
  std::string input=std::string(SOURCE_DIR)+"/demo_image/IMG_";
  std::string output=std::string(SOURCE_DIR)+"/demo_output/IMG_"+index+"_";

  image1= cv::imread(input+index+".jpg", CV_LOAD_IMAGE_GRAYSCALE);
  image2= cv::imread(input+index+"bis.jpg", CV_LOAD_IMAGE_GRAYSCALE);

  cv::Mat image1color, image2color, concat;//for visualization
  image1color= cv::imread(input+index+".jpg", CV_LOAD_IMAGE_COLOR);
  image2color= cv::imread(input+index+"bis.jpg", CV_LOAD_IMAGE_COLOR);

//=============== Read SIFT points =================//
  std::cout<<"Loading SIFT features"<<std::endl;
  std::vector<keypoint> F1, F2;
  read_detectors(output+"Detectors1.txt",F1);
  read_detectors(output+"Detectors2.txt",F2);

  std::vector<cv::KeyPoint> feat1,feat2;
  Convert_detectors(F1,feat1);//we only need detectors for KVLD
  Convert_detectors(F2,feat2);//we only need detectors for KVLD

  std::cout<< "sift:: 1st image: " << F1.size() << " keypoints"<<std::endl;
  std::cout<< "sift:: 2nd image: " << F1.size() << " keypoints"<<std::endl;
//=============== compute matches using brute force matching ====================//
  std::vector<cv::DMatch> matches;
 read_matches(output+"initial_matches.txt",matches);
//=============== convert openCV sturctures to KVLD recognized elements
  Image<float> If1, If2;
  Convert_image(image1, If1);
  Convert_image(image2, If2);

  std::vector<Pair> matchesPair;
  Convert_matches(matches,matchesPair);

//===============================  KVLD method ==================================//
	std::cout<<"K-VLD starts with "<<matches.size()<<" matches"<<std::endl;

    std::vector<Pair> matchesFiltered;
   std::vector<double> vec_score;

  //In order to illustrate the gvld(or vld)-consistant neighbors, the following two parameters has been externalized as inputs of the function KVLD.
    libNumerics::matrix<float> E = libNumerics::matrix<float>::ones(matches.size(),matches.size())*(-1);
    // gvld-consistency matrix, intitialized to -1,  >0 consistency value, -1=unknow, -2=false
    std::vector<bool> valide(matches.size(), true);// indices of match in the initial matches, if true at the end of KVLD, a match is kept.

    size_t it_num=0;
    KvldParameters kvldparameters;//initial parameters of KVLD

    while (it_num < 5 && kvldparameters.inlierRate>KVLD(If1, If2,F1,F2, matchesPair, matchesFiltered, vec_score,E,valide,kvldparameters)) {
      kvldparameters.inlierRate/=2;
      std::cout<<"low inlier rate, re-select matches with new rate="<<kvldparameters.inlierRate<<std::endl;
      kvldparameters.K=2;
      it_num++;
    }
		std::cout<<"K-VLD filter ends with "<<matchesFiltered.size()<<" selected matches"<<std::endl;

//================= write files to output folder ==================//
    std::cout<<"Please check the output folder for results"<<std::endl;
    writeResult(output,F1, F2, matchesPair, matchesFiltered, vec_score);
//================= Visualize matching result ====================//

  //  for (int it1=0; it1<matchesPair.size()-1;it1++){
  //  for (int it2=it1+1; it2<matchesPair.size();it2++){
  //    if (valide[it1] && valide[it2] && E(it1,it2)>=0){

  //      cv::KeyPoint l1 = feat1[matchesPair[it1].first];
  //      cv::KeyPoint l2 = feat1[matchesPair[it2].first];

  //      cv::KeyPoint r1 = feat2[matchesPair[it1].second];
  //      cv::KeyPoint r2 = feat2[matchesPair[it2].second];

  //      //cv::line(image1color,l1.pt, l2.pt,cv::Scalar(255,0,255),2);
  //      cv::circle(image1color,l1.pt,5,cv::Scalar(0,255,0));
  //    }
  //  }
  //}
  //cv::imwrite(output+"output.png",image1color);

   cv::vconcat(image1color, image2color,concat);
   	for(  std::vector<cv::DMatch>::const_iterator ptr = matches.begin(); ptr != matches.end(); ++ptr)
		{
      cv::KeyPoint start = feat1[ptr->queryIdx];
      cv::KeyPoint end = feat2[ptr->trainIdx];
      cv::line( concat,start.pt, end.pt+cv::Point2f(0,image1.rows),cv::Scalar(0, 255,0 ));

		}
   cv::imwrite(output+"initial.png",concat);

  //========== KVLD result =============//
   cv::vconcat(image1color, image2color,concat);

   //draw gvld-consistant neighbors (not exhostive)
   for (int it1=0; it1<matchesPair.size()-1;it1++){
     for (int it2=it1+1; it2<matchesPair.size();it2++){
       if (valide[it1] && valide[it2] && E(it1,it2)>=0){

         cv::KeyPoint l1 = feat1[matchesPair[it1].first];
         cv::KeyPoint l2 = feat1[matchesPair[it2].first];

         cv::KeyPoint r1 = feat2[matchesPair[it1].second];
         cv::KeyPoint r2 = feat2[matchesPair[it2].second];

         cv::line(concat,l1.pt, l2.pt,cv::Scalar(255,0,255),2);
         cv::line(concat,r1.pt+cv::Point2f(0,image1.rows), r2.pt+cv::Point2f(0,image1.rows),cv::Scalar(255,0,255),2);

       }
     }
   }
   for( std::vector<Pair >::const_iterator ptr = matchesFiltered.begin(); ptr != matchesFiltered.end(); ++ptr)
		{
      size_t i = ptr->first;
      size_t j = ptr->second;
      cv::KeyPoint start = feat1[i];
      cv::KeyPoint end = feat2[j];

      cv::line( concat,start.pt, end.pt+cv::Point2f(0,image1.rows),cv::Scalar(0, 255, 0 ));

		}
   cv::imwrite(output+"kvld_filtered.png",concat);

    return 0;
}
<commit_msg>minor showing error<commit_after>/** @KVLD interface with external detectors and matches
 ** @author Zhe Liu
 **/

/*
Copyright (C) 2011-12 Zhe Liu and Pierre Moulon.
All rights reserved.

This file is part of the KVLD library and is made available under
the terms of the BSD license (see the COPYING file).
*/

#include <algorithm>
#include <memory>

#include "kvld/kvld.h"
#include "convert.h"

#include <cv.hpp>
#include <cxcore.h>
#include <highgui.h>
#include "opencv2/nonfree/features2d.hpp"

int main(int argc,char*argv[]) {
  //================= load images ======================//
	cv::Mat image1, image2;
  int imageID=2;// index of a pair of images you want to use in folder demo_images
  std::string index;
  std::stringstream f;
  f<<imageID;
  f>>index;
  std::string input=std::string(SOURCE_DIR)+"/demo_image/IMG_";
  std::string output=std::string(SOURCE_DIR)+"/demo_output/IMG_"+index+"_";

  image1= cv::imread(input+index+".jpg", CV_LOAD_IMAGE_GRAYSCALE);
  image2= cv::imread(input+index+"bis.jpg", CV_LOAD_IMAGE_GRAYSCALE);

  cv::Mat image1color, image2color, concat;//for visualization
  image1color= cv::imread(input+index+".jpg", CV_LOAD_IMAGE_COLOR);
  image2color= cv::imread(input+index+"bis.jpg", CV_LOAD_IMAGE_COLOR);

//=============== Read SIFT points =================//
  std::cout<<"Loading SIFT features"<<std::endl;
  std::vector<keypoint> F1, F2;
  read_detectors(output+"Detectors1.txt",F1);
  read_detectors(output+"Detectors2.txt",F2);

  std::vector<cv::KeyPoint> feat1,feat2;
  Convert_detectors(F1,feat1);//we only need detectors for KVLD
  Convert_detectors(F2,feat2);//we only need detectors for KVLD

  std::cout<< "sift:: 1st image: " << F1.size() << " keypoints"<<std::endl;
  std::cout<< "sift:: 2nd image: " << F2.size() << " keypoints"<<std::endl;
//=============== compute matches using brute force matching ====================//
  std::vector<cv::DMatch> matches;
 read_matches(output+"initial_matches.txt",matches);
//=============== convert openCV sturctures to KVLD recognized elements
  Image<float> If1, If2;
  Convert_image(image1, If1);
  Convert_image(image2, If2);

  std::vector<Pair> matchesPair;
  Convert_matches(matches,matchesPair);

//===============================  KVLD method ==================================//
	std::cout<<"K-VLD starts with "<<matches.size()<<" matches"<<std::endl;

    std::vector<Pair> matchesFiltered;
   std::vector<double> vec_score;

  //In order to illustrate the gvld(or vld)-consistant neighbors, the following two parameters has been externalized as inputs of the function KVLD.
    libNumerics::matrix<float> E = libNumerics::matrix<float>::ones(matches.size(),matches.size())*(-1);
    // gvld-consistency matrix, intitialized to -1,  >0 consistency value, -1=unknow, -2=false
    std::vector<bool> valide(matches.size(), true);// indices of match in the initial matches, if true at the end of KVLD, a match is kept.

    size_t it_num=0;
    KvldParameters kvldparameters;//initial parameters of KVLD

    while (it_num < 5 && kvldparameters.inlierRate>KVLD(If1, If2,F1,F2, matchesPair, matchesFiltered, vec_score,E,valide,kvldparameters)) {
      kvldparameters.inlierRate/=2;
      std::cout<<"low inlier rate, re-select matches with new rate="<<kvldparameters.inlierRate<<std::endl;
      kvldparameters.K=2;
      it_num++;
    }
		std::cout<<"K-VLD filter ends with "<<matchesFiltered.size()<<" selected matches"<<std::endl;

//================= write files to output folder ==================//
    std::cout<<"Please check the output folder for results"<<std::endl;
    writeResult(output,F1, F2, matchesPair, matchesFiltered, vec_score);
//================= Visualize matching result ====================//

  //  for (int it1=0; it1<matchesPair.size()-1;it1++){
  //  for (int it2=it1+1; it2<matchesPair.size();it2++){
  //    if (valide[it1] && valide[it2] && E(it1,it2)>=0){

  //      cv::KeyPoint l1 = feat1[matchesPair[it1].first];
  //      cv::KeyPoint l2 = feat1[matchesPair[it2].first];

  //      cv::KeyPoint r1 = feat2[matchesPair[it1].second];
  //      cv::KeyPoint r2 = feat2[matchesPair[it2].second];

  //      //cv::line(image1color,l1.pt, l2.pt,cv::Scalar(255,0,255),2);
  //      cv::circle(image1color,l1.pt,5,cv::Scalar(0,255,0));
  //    }
  //  }
  //}
  //cv::imwrite(output+"output.png",image1color);

   cv::vconcat(image1color, image2color,concat);
   	for(  std::vector<cv::DMatch>::const_iterator ptr = matches.begin(); ptr != matches.end(); ++ptr)
		{
      cv::KeyPoint start = feat1[ptr->queryIdx];
      cv::KeyPoint end = feat2[ptr->trainIdx];
      cv::line( concat,start.pt, end.pt+cv::Point2f(0,image1.rows),cv::Scalar(0, 255,0 ));

		}
   cv::imwrite(output+"initial.png",concat);

  //========== KVLD result =============//
   cv::vconcat(image1color, image2color,concat);

   //draw gvld-consistant neighbors (not exhostive)
   for (int it1=0; it1<matchesPair.size()-1;it1++){
     for (int it2=it1+1; it2<matchesPair.size();it2++){
       if (valide[it1] && valide[it2] && E(it1,it2)>=0){

         cv::KeyPoint l1 = feat1[matchesPair[it1].first];
         cv::KeyPoint l2 = feat1[matchesPair[it2].first];

         cv::KeyPoint r1 = feat2[matchesPair[it1].second];
         cv::KeyPoint r2 = feat2[matchesPair[it2].second];

         cv::line(concat,l1.pt, l2.pt,cv::Scalar(255,0,255),2);
         cv::line(concat,r1.pt+cv::Point2f(0,image1.rows), r2.pt+cv::Point2f(0,image1.rows),cv::Scalar(255,0,255),2);

       }
     }
   }
   for( std::vector<Pair >::const_iterator ptr = matchesFiltered.begin(); ptr != matchesFiltered.end(); ++ptr)
		{
      size_t i = ptr->first;
      size_t j = ptr->second;
      cv::KeyPoint start = feat1[i];
      cv::KeyPoint end = feat2[j];

      cv::line( concat,start.pt, end.pt+cv::Point2f(0,image1.rows),cv::Scalar(0, 255, 0 ));

		}
   cv::imwrite(output+"kvld_filtered.png",concat);

    return 0;
}
<|endoftext|>


<commit_before>typedef unsigned short uint16_t;

int test = 244;
char* string = "Heheszki :D";

extern "C"
void kmain()
{
	uint16_t* vmem = (uint16_t*)0xB8000;
	*vmem = 0x4141;
	*(vmem + 1) = 0x4242;

	for (;;);
}
<commit_msg>Add hello world kernel code<commit_after>typedef unsigned char uint8_t;
typedef unsigned short uint16_t;

static uint16_t* vmem = reinterpret_cast<uint16_t*>(0xB8000);

void putchar(uint8_t character, uint8_t attribute = 0x07)
{
	*vmem++ = (attribute << 8) | character;
}

int strlen(char* string)
{
	int length = 0;
	while (string[length++]);
	return --length;
}

void puts(char* string)
{
	for (int i = 0; i < strlen(string); ++i)
	{
		putchar(string[i]);
	}
}

void halt()
{
	for (;;);
}

extern "C"
void kmain()
{
	puts("Hello world!");
	halt();
}
<|endoftext|>


<commit_before>#include "coincontroltreewidget.h"
#include "coincontroldialog.h"

CoinControlTreeWidget::CoinControlTreeWidget(QWidget *parent) :
    QTreeWidget(parent)
{

}

void CoinControlTreeWidget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Space) // press spacebar -> select checkbox
    {
        event->ignore();
        int COLUMN_CHECKBOX = 0;
        this->currentItem()->setCheckState(COLUMN_CHECKBOX, ((this->currentItem()->checkState(COLUMN_CHECKBOX) == Qt::Checked) ? Qt::Unchecked : Qt::Checked));
    }
    else if (event->key() == Qt::Key_Escape) // press esc -> close dialog
    {
        event->ignore();
        CoinControlDialog *coinControlDialog = (CoinControlDialog*)this->parentWidget();
        coinControlDialog->done(QDialog::Accepted);
    }
    else
    {
        this->QTreeWidget::keyPressEvent(event);
    }
}<commit_msg>coincontrol widget fix<commit_after>#include "coincontroltreewidget.h"
#include "coincontroldialog.h"

CoinControlTreeWidget::CoinControlTreeWidget(QWidget *parent) :
    QTreeWidget(parent)
{

}

void CoinControlTreeWidget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Space) // press spacebar -> select checkbox
    {
        event->ignore();
        int COLUMN_CHECKBOX = 0;
        if(this->currentItem())
            this->currentItem()->setCheckState(COLUMN_CHECKBOX, ((this->currentItem()->checkState(COLUMN_CHECKBOX) == Qt::Checked) ? Qt::Unchecked : Qt::Checked));
    }
    else if (event->key() == Qt::Key_Escape) // press esc -> close dialog
    {
        event->ignore();
        CoinControlDialog *coinControlDialog = (CoinControlDialog*)this->parentWidget();
        coinControlDialog->done(QDialog::Accepted);
    }
    else
    {
        this->QTreeWidget::keyPressEvent(event);
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2011-2013 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "coincontroltreewidget.h"
#include "coincontroldialog.h"

CoinControlTreeWidget::CoinControlTreeWidget(QWidget *parent) :
    QTreeWidget(parent)
{

}

void CoinControlTreeWidget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Space) // press spacebar -> select checkbox
    {
        event->ignore();
        int COLUMN_CHECKBOX = 0;
        this->currentItem()->setCheckState(COLUMN_CHECKBOX, ((this->currentItem()->checkState(COLUMN_CHECKBOX) == Qt::Checked) ? Qt::Unchecked : Qt::Checked));
    }
    else if (event->key() == Qt::Key_Escape) // press esc -> close dialog
    {
        event->ignore();
        CoinControlDialog *coinControlDialog = (CoinControlDialog*)this->parentWidget();
        coinControlDialog->done(QDialog::Accepted);
    }
    else
    {
        this->QTreeWidget::keyPressEvent(event);
    }
}<commit_msg>fix crash: CoinControl "space" bug<commit_after>// Copyright (c) 2011-2013 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "coincontroltreewidget.h"
#include "coincontroldialog.h"

CoinControlTreeWidget::CoinControlTreeWidget(QWidget *parent) :
    QTreeWidget(parent)
{

}

void CoinControlTreeWidget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Space) // press spacebar -> select checkbox
    {
        event->ignore();
        int COLUMN_CHECKBOX = 0;
        if(this->currentItem())
            this->currentItem()->setCheckState(COLUMN_CHECKBOX, ((this->currentItem()->checkState(COLUMN_CHECKBOX) == Qt::Checked) ? Qt::Unchecked : Qt::Checked));
    }
    else if (event->key() == Qt::Key_Escape) // press esc -> close dialog
    {
        event->ignore();
        CoinControlDialog *coinControlDialog = (CoinControlDialog*)this->parentWidget();
        coinControlDialog->done(QDialog::Accepted);
    }
    else
    {
        this->QTreeWidget::keyPressEvent(event);
    }
}
<|endoftext|>