<commit_before>//
//  File: rsaspeedtest.cpp
//
//  Description: aesspeedtest
//
//  Copyright (c) John Manferdelli.  All rights reserved.
//
// Use, duplication and disclosure of this file and derived works of
// this file are subject to and licensed under the Apache License dated
// January, 2004, (the "License").  This License is contained in the
// top level directory originally provided with the CloudProxy Project.
// Your right to use or distribute this file, or derived works thereof,
// is subject to your being bound by those terms and your use indicates
// consent to those terms.
//
// If you distribute this file (or portions derived therefrom), you must
// include License in or with the file and, in the event you do not include
// the entire License in the file, the file must contain a reference
// to the location of the License.

#include "jlmTypes.h"
#include "jlmcrypto.h"
#include "jlmUtility.h"
#include "sha256.h"
#include "aes.h"
#include "bignum.h"
#include "mpFunctions.h"
#include "modesandpadding.h"
#include "rsaHelper.h"

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <string.h>
#include <time.h>

#define MAXREQUESTSIZE          2048
#define MAXADDEDSIZE              64
#define MAXREQUESTSIZEWITHPAD   (MAXREQUESTSIZE+MAXADDEDSIZE)

#define DEBUG4

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

KeyInfo* ReadKeyfromFile(const char* szKeyFile)
{
    KeyInfo*    pParseKey= new KeyInfo;
    RSAKey*     pRSAKey= NULL;
    symKey*     pAESKey= NULL;
    KeyInfo*    pRetKey= NULL;
    int         iKeyType;

    TiXmlDocument* pDoc= new TiXmlDocument();
    if(pDoc==NULL) {
        printf("Cant get new an Xml Document\n");
        return NULL;
    }

    if(!pDoc->LoadFile(szKeyFile)) {
        printf("Cant load keyfile\n");
        return NULL;
    }
    iKeyType= pParseKey->getKeyType(pDoc);

    switch(iKeyType) {
      case AESKEYTYPE:
        pAESKey= new symKey();
        if(pAESKey==NULL) {
            printf("Cant new symKey\n");
            break;
        }
        else
            pAESKey->m_pDoc= pDoc;
        pAESKey->getDataFromDoc();
        pRetKey= (KeyInfo*) pAESKey;
        break;
      case RSAKEYTYPE:
        pRSAKey= new RSAKey();
        if(pRSAKey==NULL) {
            printf("Cant new RSAKey\n");
            break;
        }
        else
            pRSAKey->m_pDoc= pDoc;
        pRSAKey->getDataFromDoc();
        pRetKey= (KeyInfo*) pRSAKey;
        break;
      default:
       printf("Unknown key type in ReadFromFile\n");
       break;
    }
    delete pParseKey;
    // Dont forget to delete pDoc;

    return pRetKey;
}

bool EncryptTest(RSAKey* pKey, int numBlocks, bool fFast= false, bool fEncrypt=true)
{
    int     i;
    time_t  start, finish;
    double  elapsedseconds= 0.0;
    double  ops= 0.0;
    double  opspersecond= 0.0;

    bnum    bnIn(pKey->m_iByteSizeM);
    bnum    bnEncrypted(pKey->m_iByteSizeM);
    bnum    bnDecrypted(pKey->m_iByteSizeM);
    bnum    R(256);
    bnum    bnDP(pKey->m_iByteSizeM/2);
    bnum    bnDQ(pKey->m_iByteSizeM/2);
    bnum    bnPM1(pKey->m_iByteSizeM/2);
    bnum    bnQM1(pKey->m_iByteSizeM/2);

    memset(bnIn.m_pValue, 0, pKey->m_iByteSizeM);
    memset(bnEncrypted.m_pValue, 0, pKey->m_iByteSizeM);
    memset(bnDecrypted.m_pValue, 0, pKey->m_iByteSizeM);
    u64*    puIn= (u64*) bnIn.m_pValue;
    *puIn= 237ULL;

    if(fFast) {
        if(!mpRSACalculateFastRSAParameters(*(pKey->m_pbnE), *(pKey->m_pbnP),
                    *(pKey->m_pbnQ), bnPM1, bnDP, bnQM1, bnDQ)) {
            printf("Can't calculate RSA fast decrypt parameters\n");
            return false;
        }
    }

    time(&start);
    if(fEncrypt) {
        for(i=0; i<numBlocks; i++) {
            if(!mpRSAENC(bnIn, *(pKey->m_pbnE), *(pKey->m_pbnM), bnEncrypted)) {
                printf("Can't encrypt\n");
                return false;
            }
            (*puIn)++;
        }
    }
    else if(fFast) {
        for(i=0; i<numBlocks; i++) {
            if(!mpRSADEC(bnIn, *(pKey->m_pbnP), bnPM1, bnDP, *(pKey->m_pbnQ),
                           bnQM1, bnDQ, *(pKey->m_pbnM), bnDecrypted)) {
                printf("Can't decrypt\n");
                return false;
            }
            (*puIn)++;
        }
    }
    else {
        for(i=0; i<numBlocks; i++) {
            if(!mpRSAENC(bnIn, *(pKey->m_pbnD), *(pKey->m_pbnM), bnDecrypted)) {
                printf("Can't decrypt\n");
                return false;
            }
            (*puIn)++;
        }
    }
    time(&finish);

    elapsedseconds= difftime(finish, start);
    ops= (double)numBlocks;
    opspersecond= ops/elapsedseconds;
    printf("%10.4lf seconds %d operations %10.4lf operations per second\n",
        elapsedseconds, numBlocks, opspersecond);

    return true;
}

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

#define ENCRYPT 1
#define DECRYPT 2

int main(int an, char** av)
{
    int         i;
    int         mode= ENCRYPT;
    int         numBlocks= 1024;
    RSAKey*     pKey= NULL;
    char*       szKeyFile= NULL;
    bool        fFast= false;

    for(i=0; i<an; i++) {
        if(strcmp(av[i], "-help")==0 || an<3) {
            printf("\nUsage: rsaspeedtest keyfile -Encrypt blocks\n");
            printf("         rsaspeedtest keyfile -Decrypt blocks\n");
            printf("         rsaspeedtest -fast (other args)\n");
            return 0;
        }

        if(i<2) {
            szKeyFile= av[1];
            i= 2;
        }

        if(strcmp(av[i], "-Encrypt")==0) {
            mode= ENCRYPT;
            if(an>(i+1)) {
                numBlocks= atoi(av[++i]);
            }
        }
        if(strcmp(av[i], "-Decrypt")==0) {
            mode= DECRYPT;
            if(an>(i+1)) {
                numBlocks= atoi(av[++i]);
            }
        }
        if(strcmp(av[i], "-fast")==0) {
            fFast= true;
        }
    }

    if(mode==ENCRYPT)
        printf("RSA Encrypt, Key file %s %d blocks\n", szKeyFile, numBlocks);
    if(mode==DECRYPT) {
        if(fFast)
            printf("RSA Fast Decrypt, Key file %s %d blocks\n", szKeyFile, numBlocks);
        else
            printf("RSA Decrypt, Key file %s %d blocks\n", szKeyFile, numBlocks);
    }

    pKey= (RSAKey*) ReadKeyfromFile(szKeyFile);
    if(pKey==NULL) {
        printf("Cant read key file\n");
        return 1;
    }

    initCryptoRand();
    initBigNum();
    if(mode==ENCRYPT)
        EncryptTest(pKey, numBlocks, fFast, true);
    if(mode==DECRYPT)
        EncryptTest(pKey, numBlocks, fFast, false);
    closeCryptoRand();

    return 0;
}

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

<commit_msg>More tests.<commit_after>//
//  File: rsaspeedtest.cpp
//
//  Description: aesspeedtest
//
//  Copyright (c) John Manferdelli.  All rights reserved.
//
// Use, duplication and disclosure of this file and derived works of
// this file are subject to and licensed under the Apache License dated
// January, 2004, (the "License").  This License is contained in the
// top level directory originally provided with the CloudProxy Project.
// Your right to use or distribute this file, or derived works thereof,
// is subject to your being bound by those terms and your use indicates
// consent to those terms.
//
// If you distribute this file (or portions derived therefrom), you must
// include License in or with the file and, in the event you do not include
// the entire License in the file, the file must contain a reference
// to the location of the License.

#include "jlmTypes.h"
#include "jlmcrypto.h"
#include "jlmUtility.h"
#include "sha256.h"
#include "aes.h"
#include "bignum.h"
#include "mpFunctions.h"
#include "modesandpadding.h"
#include "rsaHelper.h"

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <string.h>
#include <time.h>

#define MAXREQUESTSIZE          2048
#define MAXADDEDSIZE              64
#define MAXREQUESTSIZEWITHPAD   (MAXREQUESTSIZE+MAXADDEDSIZE)

#define DEBUG4

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

KeyInfo* ReadKeyfromFile(const char* szKeyFile)
{
    KeyInfo*    pParseKey= new KeyInfo;
    RSAKey*     pRSAKey= NULL;
    symKey*     pAESKey= NULL;
    KeyInfo*    pRetKey= NULL;
    int         iKeyType;

    TiXmlDocument* pDoc= new TiXmlDocument();
    if(pDoc==NULL) {
        printf("Cant get new an Xml Document\n");
        return NULL;
    }

    if(!pDoc->LoadFile(szKeyFile)) {
        printf("Cant load keyfile\n");
        return NULL;
    }
    iKeyType= pParseKey->getKeyType(pDoc);

    switch(iKeyType) {
      case AESKEYTYPE:
        pAESKey= new symKey();
        if(pAESKey==NULL) {
            printf("Cant new symKey\n");
            break;
        }
        else
            pAESKey->m_pDoc= pDoc;
        pAESKey->getDataFromDoc();
        pRetKey= (KeyInfo*) pAESKey;
        break;
      case RSAKEYTYPE:
        pRSAKey= new RSAKey();
        if(pRSAKey==NULL) {
            printf("Cant new RSAKey\n");
            break;
        }
        else
            pRSAKey->m_pDoc= pDoc;
        pRSAKey->getDataFromDoc();
        pRetKey= (KeyInfo*) pRSAKey;
        break;
      default:
       printf("Unknown key type in ReadFromFile\n");
       break;
    }
    delete pParseKey;
    // Dont forget to delete pDoc;

    return pRetKey;
}

bool EncryptTest(RSAKey* pKey, int numBlocks, bool fFast= false, bool fEncrypt=true)
{
    int     i;
    time_t  start, finish;
    double  elapsedseconds= 0.0;
    double  ops= 0.0;
    double  opspersecond= 0.0;

    bnum    bnIn(pKey->m_iByteSizeM);
    bnum    bnEncrypted(pKey->m_iByteSizeM);
    bnum    bnDecrypted(pKey->m_iByteSizeM);
    bnum    R(256);
    bnum    bnDP(pKey->m_iByteSizeM/2);
    bnum    bnDQ(pKey->m_iByteSizeM/2);
    bnum    bnPM1(pKey->m_iByteSizeM/2);
    bnum    bnQM1(pKey->m_iByteSizeM/2);

    memset(bnIn.m_pValue, 0, pKey->m_iByteSizeM);
    memset(bnEncrypted.m_pValue, 0, pKey->m_iByteSizeM);
    memset(bnDecrypted.m_pValue, 0, pKey->m_iByteSizeM);
    u64*    puIn= (u64*) bnIn.m_pValue;
    *puIn= 237ULL;

    if(fFast) {
        if(!mpRSACalculateFastRSAParameters(*(pKey->m_pbnE), *(pKey->m_pbnP),
                    *(pKey->m_pbnQ), bnPM1, bnDP, bnQM1, bnDQ)) {
            printf("Can't calculate RSA fast decrypt parameters\n");
            return false;
        }
    }

    time(&start);
    if(fEncrypt) {
        for(i=0; i<numBlocks; i++) {
            if(!mpRSAENC(bnIn, *(pKey->m_pbnE), *(pKey->m_pbnM), bnEncrypted)) {
                printf("Can't encrypt\n");
                return false;
            }
            (*puIn)++;
        }
    }
    else if(fFast) {
        for(i=0; i<numBlocks; i++) {
            if(!mpRSADEC(bnIn, *(pKey->m_pbnP), bnPM1, bnDP, *(pKey->m_pbnQ),
                           bnQM1, bnDQ, *(pKey->m_pbnM), bnDecrypted)) {
                printf("Can't decrypt\n");
                return false;
            }
            (*puIn)++;
        }
    }
    else {
        for(i=0; i<numBlocks; i++) {
            if(!mpRSAENC(bnIn, *(pKey->m_pbnD), *(pKey->m_pbnM), bnDecrypted)) {
                printf("Can't decrypt\n");
                return false;
            }
            (*puIn)++;
        }
    }
    time(&finish);

    elapsedseconds= difftime(finish, start);
    ops= (double)numBlocks;
    opspersecond= ops/elapsedseconds;
    printf("%10.4lf seconds %d operations %10.4lf operations per second\n",
        elapsedseconds, numBlocks, opspersecond);

    return true;
}

bool RSASanityCheck(RSAKey* key, int file, bool fFast)
{
    bool        fRet= true;
    int         numBytes= 0;
    byte        buf[4096];
    int         blockSize= key->m_iByteSizeM;
    int         numBlocks= 0;

    time_t      start, finish;
    double      elapsedseconds= 0.0;
    double      ops= 0.0;
    double      opspersecond= 0.0;

    bnum        bnMsg(key->m_iByteSizeM/sizeof(u64));
    bnum        bnEncrypted(key->m_iByteSizeM/sizeof(u64));
    bnum        bnDecrypted(key->m_iByteSizeM/sizeof(u64));
    bnum        bnPM1(key->m_iByteSizeM/sizeof(u64));
    bnum        bnQM1(key->m_iByteSizeM/sizeof(u64));
    bnum        bnDP(key->m_iByteSizeM/sizeof(u64));
    bnum        bnDQ(key->m_iByteSizeM/sizeof(u64));

    // bnum        m_pbnM; m_pbnP; m_pbnQ; m_pbnE; m_pbnD;

    if(fFast) {
        printf("Fast RSA sanity check, block size is %d\n", blockSize);
        if(!mpRSACalculateFastRSAParameters(*(key->m_pbnE), *(key->m_pbnP),
                    *(key->m_pbnQ), bnPM1, bnDP, bnQM1, bnDQ)) {
            printf("Can't calculate RSA fast decrypt parameters\n");
            return false;
        }
    }
    else {
        printf("RSA sanity check, block size is %d\n", blockSize);
    }

    time(&start);
    for(;;) {
        numBytes= read(file, buf, blockSize);
        if(numBytes<blockSize)
            break;
        memcpy(bnMsg.m_pValue, buf, blockSize);
        bnMsg.m_pValue[blockSize-1]&= 0xffffffffULL;

        if(!mpRSAENC(bnMsg, *(key->m_pbnE), *(key->m_pbnM), bnEncrypted)) {
            printf("Can't encrypt\n");
            fRet= false;
        }
        if(fFast) {
            if(!mpRSADEC(bnEncrypted, *(key->m_pbnP), bnPM1, bnDP, *(key->m_pbnQ),
                           bnQM1, bnDQ, *(key->m_pbnM), bnDecrypted)) {
                printf("Can't decrypt\n");
                fRet= false;
            }
        }
        else {
            if(!mpRSAENC(bnEncrypted, *(key->m_pbnD), *(key->m_pbnM), bnDecrypted)) {;
                printf("Can't decrypt\n");
                fRet= false;
            }
        }
        numBlocks++;

        printf("Message\n"); printNum(bnMsg); printf("\n");
        printf("Encrypted\n"); printNum(bnEncrypted); printf("\n");
        printf("Decrypted\n"); printNum(bnDecrypted); printf("\n");

        if(memcmp(bnMsg.m_pValue,bnDecrypted.m_pValue, blockSize)==0) {
            printf("\tpassed\n\n");
        }
        else {
            fRet= false;
            printf("\tfailed\n\n");
        }
    }
    time(&finish);

    elapsedseconds= difftime(finish, start);
    ops= (double)numBlocks;
    opspersecond= ops/elapsedseconds;
    printf("%10.4lf seconds %d operations %10.4lf operations per second\n",
        elapsedseconds, numBlocks, opspersecond);
    return fRet;
}

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

#define ENCRYPT 1
#define DECRYPT 2

int main(int an, char** av)
{
    int         i;
    int         mode= ENCRYPT;
    int         numBlocks= 1024;
    RSAKey*     pKey= NULL;
    char*       szKeyFile= NULL;
    char*       szBlockFile= NULL;
    bool        fFast= false;
    bool        fSanityOnly= false;
    int         file= -1;

    for(i=0; i<an; i++) {
        if(strcmp(av[i], "-help")==0 || an<3) {
            printf("\nUsage: rsaspeedtest keyfile -Encrypt blocks\n");
            printf("         rsaspeedtest keyfile -Decrypt blocks\n");
            printf("         rsaspeedtest keyfile -sanity file\n");
            printf("         rsaspeedtest -fast (other args)\n");
            return 0;
        }

        if(i<2) {
            szKeyFile= av[1];
            i= 2;
        }

        if(strcmp(av[i], "-Encrypt")==0) {
            mode= ENCRYPT;
            if(an>(i+1)) {
                numBlocks= atoi(av[++i]);
            }
        }
        if(strcmp(av[i], "-Decrypt")==0) {
            mode= DECRYPT;
            if(an>(i+1)) {
                numBlocks= atoi(av[++i]);
            }
        }
        if(strcmp(av[i], "-fast")==0) {
            fFast= true;
        }
        if(strcmp(av[i], "-sanity")==0) {
            fSanityOnly= true;
            if(an>(i+1)) {
                szBlockFile= av[++i];
            }
        }
    }

    pKey= (RSAKey*) ReadKeyfromFile(szKeyFile);
    if(pKey==NULL) {
        printf("Cant read key file\n");
        return 1;
    }

    initCryptoRand();
    initBigNum();

    if(fSanityOnly) {
        if(szBlockFile==NULL) {
            printf("No block file\n");
            return 1;
        }
        file= open(szBlockFile, O_RDONLY);
        if(file<0) {
            printf("Cant open block file\n");
            return 1;
        }
        if(RSASanityCheck(pKey, file, fFast)) {
            printf("PASSED all sanity check operations\n");
        }
        else {
            printf("FAILED some sanity check operations\n");
        }
    }
    else {

        if(mode==ENCRYPT)
            printf("RSA Encrypt, Key file %s %d blocks\n", szKeyFile, numBlocks);
        if(mode==DECRYPT) {
            if(fFast)
                printf("RSA Fast Decrypt, Key file %s %d blocks\n", szKeyFile, numBlocks);
            else
                printf("RSA Decrypt, Key file %s %d blocks\n", szKeyFile, numBlocks);
        }
        if(mode==ENCRYPT)
            EncryptTest(pKey, numBlocks, fFast, true);
        if(mode==DECRYPT)
            EncryptTest(pKey, numBlocks, fFast, false);
    }
    closeCryptoRand();

    return 0;
}

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

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: client.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 20:21:36 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// INCLUDE ---------------------------------------------------------------

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#ifndef _COM_SUN_STAR_EMBED_XEMBEDDEDOBJECT_HPP_
#include <com/sun/star/embed/XEmbeddedObject.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_NOVISUALAREASIZEEXCEPTION_HPP_
#include <com/sun/star/embed/NoVisualAreaSizeException.hpp>
#endif

#include <toolkit/helper/vclunohelper.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/viewfrm.hxx>
#include <sot/sotref.hxx>
#include <svx/svditer.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdmodel.hxx>
#include <svx/svdpage.hxx>
#include <svx/svdoole2.hxx>
#include <svx/svdview.hxx>
#include <svx/svdograf.hxx>
#include <svtools/embedhlp.hxx>

#include "client.hxx"
#include "tabvwsh.hxx"
#include "docsh.hxx"

using namespace com::sun::star;

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

ScClient::ScClient( ScTabViewShell* pViewShell, Window* pDraw, SdrModel* pSdrModel, SdrOle2Obj* pObj ) :
    SfxInPlaceClient( pViewShell, pDraw, pObj->GetAspect() ),
    pModel( pSdrModel ),
    pGrafEdit( 0 )
{
    SetObject( pObj->GetObjRef() );
}

__EXPORT ScClient::~ScClient()
{
}

SdrOle2Obj* ScClient::GetDrawObj()
{
    uno::Reference < embed::XEmbeddedObject > xObj = GetObject();
    SdrOle2Obj* pOle2Obj = NULL;
    String aName = GetViewShell()->GetObjectShell()->GetEmbeddedObjectContainer().GetEmbeddedObjectName( xObj );

    USHORT nPages = pModel->GetPageCount();
    for (USHORT nPNr=0; nPNr<nPages && !pOle2Obj; nPNr++)
    {
        SdrPage* pPage = pModel->GetPage(nPNr);
        SdrObjListIter aIter( *pPage, IM_DEEPNOGROUPS );
        SdrObject* pObject = aIter.Next();
        while (pObject && !pOle2Obj)
        {
            if ( pObject->GetObjIdentifier() == OBJ_OLE2 )
            {
                // name from InfoObject is PersistName
                if ( ((SdrOle2Obj*)pObject)->GetPersistName() == aName )
                    pOle2Obj = (SdrOle2Obj*)pObject;
            }
            pObject = aIter.Next();
        }
    }
    return pOle2Obj;
}

void __EXPORT ScClient::RequestNewObjectArea( Rectangle& aLogicRect )
{
    SfxViewShell* pSfxViewSh = GetViewShell();
    ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
    if (!pViewSh)
    {
        DBG_ERROR("Wrong ViewShell");
        return;
    }

    BOOL bChange = FALSE;
    USHORT nTab = pViewSh->GetViewData()->GetTabNo();
    SdrPage* pPage = pModel->GetPage(static_cast<sal_uInt16>(static_cast<sal_Int16>(nTab)));
    if (pPage)
    {
        Point aPos;
        Size aSize = pPage->GetSize();
        if ( aSize.Width() < 0 )
        {
            aPos.X() = aSize.Width() + 1;       // negative
            aSize.Width() = -aSize.Width();     // positive
        }
        Rectangle aPageRect( aPos, aSize );

        if (aLogicRect.Right() > aPageRect.Right())
        {
            long nDiff = aLogicRect.Right() - aPageRect.Right();
            aLogicRect.Left() -= nDiff;
            aLogicRect.Right() -= nDiff;
            bChange = TRUE;
        }
        if (aLogicRect.Bottom() > aPageRect.Bottom())
        {
            long nDiff = aLogicRect.Bottom() - aPageRect.Bottom();
            aLogicRect.Top() -= nDiff;
            aLogicRect.Bottom() -= nDiff;
            bChange = TRUE;
        }

        if (aLogicRect.Left() < aPageRect.Left())
        {
            long nDiff = aLogicRect.Left() - aPageRect.Left();
            aLogicRect.Right() -= nDiff;
            aLogicRect.Left() -= nDiff;
            bChange = TRUE;
        }
        if (aLogicRect.Top() < aPageRect.Top())
        {
            long nDiff = aLogicRect.Top() - aPageRect.Top();
            aLogicRect.Bottom() -= nDiff;
            aLogicRect.Top() -= nDiff;
            bChange = TRUE;
        }
    }
}

void __EXPORT ScClient::ObjectAreaChanged()
{
    SfxViewShell* pSfxViewSh = GetViewShell();
    ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
    if (!pViewSh)
    {
        DBG_ERROR("Wrong ViewShell");
        return;
    }

    //  Position und Groesse ins Dokument uebernehmen
    SdrOle2Obj* pDrawObj = GetDrawObj();
    if (pDrawObj)
    {
        pDrawObj->SetLogicRect( GetScaledObjArea() );

        //  set document modified (SdrModel::SetChanged is not used)
        // TODO/LATER: is there a reason that this code is not executed in Draw?
        SfxViewShell* pSfxViewSh = GetViewShell();
        ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
        if (pViewSh)
            pViewSh->GetViewData()->GetDocShell()->SetDrawModified();
    }

    if (pDrawObj)
        pViewSh->ScrollToObject( pDrawObj );
}

void __EXPORT ScClient::ViewChanged()
{
    uno::Reference < embed::XEmbeddedObject > xObj = GetObject();

    // TODO/LEAN: working with Visual Area can switch object to running state
    awt::Size aSz;
    try {
        aSz = xObj->getVisualAreaSize( GetAspect() );
    } catch ( embed::NoVisualAreaSizeException& )
    {
        DBG_ERROR("The visual area size must be available!\n");
    }

    MapUnit aMapUnit = VCLUnoHelper::UnoEmbed2VCLMapUnit( xObj->getMapUnit( GetAspect() ) );
    Size aVisSize = OutputDevice::LogicToLogic( Size( aSz.Width, aSz.Height ), aMapUnit, MAP_100TH_MM );

    //  Groesse ins Dokument uebernehmen
    SdrOle2Obj* pDrawObj = GetDrawObj();
    if (pDrawObj)
    {
        Rectangle aLogicRect = pDrawObj->GetLogicRect();
        Fraction aFractX = GetScaleWidth();
        Fraction aFractY = GetScaleHeight();
        aFractX *= aVisSize.Width();
        aFractY *= aVisSize.Height();
        aVisSize = Size( (long) aFractX, (long) aFractY );      // skaliert fuer Draw-Model

        //  pClientData->SetObjArea vor pDrawObj->SetLogicRect, damit keine
        //  falschen Skalierungen ausgerechnet werden:
        //Rectangle aObjArea = aLogicRect;
        //aObjArea.SetSize( aVisSize );          // Dokument-Groesse vom Server
        //SetObjArea( aObjArea );

        SfxViewShell* pSfxViewSh = GetViewShell();
        ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
        if ( pViewSh )
        {
            Window* pWin = pViewSh->GetActiveWin();
            if ( pWin->LogicToPixel( aVisSize ) != pWin->LogicToPixel( aLogicRect.GetSize() ) )
            {
                aLogicRect.SetSize( aVisSize );
                pDrawObj->SetLogicRect( aLogicRect );

                //  set document modified (SdrModel::SetChanged is not used)
                pViewSh->GetViewData()->GetDocShell()->SetDrawModified();
            }
        }
    }
}

void __EXPORT ScClient::MakeVisible()
{
    SdrOle2Obj* pDrawObj = GetDrawObj();
    if (pDrawObj)
    {
        SfxViewShell* pSfxViewSh = GetViewShell();
        ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
        if (pViewSh)
            pViewSh->ScrollToObject( pDrawObj );
    }
}

<commit_msg>INTEGRATION: CWS pchfix01 (1.15.214); FILE MERGED 2006/07/12 10:02:19 kaib 1.15.214.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: client.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: kz $ $Date: 2006-07-21 13:08:16 $
 *
 *  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"

// INCLUDE ---------------------------------------------------------------

#ifndef _COM_SUN_STAR_EMBED_XEMBEDDEDOBJECT_HPP_
#include <com/sun/star/embed/XEmbeddedObject.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_NOVISUALAREASIZEEXCEPTION_HPP_
#include <com/sun/star/embed/NoVisualAreaSizeException.hpp>
#endif

#include <toolkit/helper/vclunohelper.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/viewfrm.hxx>
#include <sot/sotref.hxx>
#include <svx/svditer.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdmodel.hxx>
#include <svx/svdpage.hxx>
#include <svx/svdoole2.hxx>
#include <svx/svdview.hxx>
#include <svx/svdograf.hxx>
#include <svtools/embedhlp.hxx>

#include "client.hxx"
#include "tabvwsh.hxx"
#include "docsh.hxx"

using namespace com::sun::star;

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

ScClient::ScClient( ScTabViewShell* pViewShell, Window* pDraw, SdrModel* pSdrModel, SdrOle2Obj* pObj ) :
    SfxInPlaceClient( pViewShell, pDraw, pObj->GetAspect() ),
    pModel( pSdrModel ),
    pGrafEdit( 0 )
{
    SetObject( pObj->GetObjRef() );
}

__EXPORT ScClient::~ScClient()
{
}

SdrOle2Obj* ScClient::GetDrawObj()
{
    uno::Reference < embed::XEmbeddedObject > xObj = GetObject();
    SdrOle2Obj* pOle2Obj = NULL;
    String aName = GetViewShell()->GetObjectShell()->GetEmbeddedObjectContainer().GetEmbeddedObjectName( xObj );

    USHORT nPages = pModel->GetPageCount();
    for (USHORT nPNr=0; nPNr<nPages && !pOle2Obj; nPNr++)
    {
        SdrPage* pPage = pModel->GetPage(nPNr);
        SdrObjListIter aIter( *pPage, IM_DEEPNOGROUPS );
        SdrObject* pObject = aIter.Next();
        while (pObject && !pOle2Obj)
        {
            if ( pObject->GetObjIdentifier() == OBJ_OLE2 )
            {
                // name from InfoObject is PersistName
                if ( ((SdrOle2Obj*)pObject)->GetPersistName() == aName )
                    pOle2Obj = (SdrOle2Obj*)pObject;
            }
            pObject = aIter.Next();
        }
    }
    return pOle2Obj;
}

void __EXPORT ScClient::RequestNewObjectArea( Rectangle& aLogicRect )
{
    SfxViewShell* pSfxViewSh = GetViewShell();
    ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
    if (!pViewSh)
    {
        DBG_ERROR("Wrong ViewShell");
        return;
    }

    BOOL bChange = FALSE;
    USHORT nTab = pViewSh->GetViewData()->GetTabNo();
    SdrPage* pPage = pModel->GetPage(static_cast<sal_uInt16>(static_cast<sal_Int16>(nTab)));
    if (pPage)
    {
        Point aPos;
        Size aSize = pPage->GetSize();
        if ( aSize.Width() < 0 )
        {
            aPos.X() = aSize.Width() + 1;       // negative
            aSize.Width() = -aSize.Width();     // positive
        }
        Rectangle aPageRect( aPos, aSize );

        if (aLogicRect.Right() > aPageRect.Right())
        {
            long nDiff = aLogicRect.Right() - aPageRect.Right();
            aLogicRect.Left() -= nDiff;
            aLogicRect.Right() -= nDiff;
            bChange = TRUE;
        }
        if (aLogicRect.Bottom() > aPageRect.Bottom())
        {
            long nDiff = aLogicRect.Bottom() - aPageRect.Bottom();
            aLogicRect.Top() -= nDiff;
            aLogicRect.Bottom() -= nDiff;
            bChange = TRUE;
        }

        if (aLogicRect.Left() < aPageRect.Left())
        {
            long nDiff = aLogicRect.Left() - aPageRect.Left();
            aLogicRect.Right() -= nDiff;
            aLogicRect.Left() -= nDiff;
            bChange = TRUE;
        }
        if (aLogicRect.Top() < aPageRect.Top())
        {
            long nDiff = aLogicRect.Top() - aPageRect.Top();
            aLogicRect.Bottom() -= nDiff;
            aLogicRect.Top() -= nDiff;
            bChange = TRUE;
        }
    }
}

void __EXPORT ScClient::ObjectAreaChanged()
{
    SfxViewShell* pSfxViewSh = GetViewShell();
    ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
    if (!pViewSh)
    {
        DBG_ERROR("Wrong ViewShell");
        return;
    }

    //  Position und Groesse ins Dokument uebernehmen
    SdrOle2Obj* pDrawObj = GetDrawObj();
    if (pDrawObj)
    {
        pDrawObj->SetLogicRect( GetScaledObjArea() );

        //  set document modified (SdrModel::SetChanged is not used)
        // TODO/LATER: is there a reason that this code is not executed in Draw?
        SfxViewShell* pSfxViewSh = GetViewShell();
        ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
        if (pViewSh)
            pViewSh->GetViewData()->GetDocShell()->SetDrawModified();
    }

    if (pDrawObj)
        pViewSh->ScrollToObject( pDrawObj );
}

void __EXPORT ScClient::ViewChanged()
{
    uno::Reference < embed::XEmbeddedObject > xObj = GetObject();

    // TODO/LEAN: working with Visual Area can switch object to running state
    awt::Size aSz;
    try {
        aSz = xObj->getVisualAreaSize( GetAspect() );
    } catch ( embed::NoVisualAreaSizeException& )
    {
        DBG_ERROR("The visual area size must be available!\n");
    }

    MapUnit aMapUnit = VCLUnoHelper::UnoEmbed2VCLMapUnit( xObj->getMapUnit( GetAspect() ) );
    Size aVisSize = OutputDevice::LogicToLogic( Size( aSz.Width, aSz.Height ), aMapUnit, MAP_100TH_MM );

    //  Groesse ins Dokument uebernehmen
    SdrOle2Obj* pDrawObj = GetDrawObj();
    if (pDrawObj)
    {
        Rectangle aLogicRect = pDrawObj->GetLogicRect();
        Fraction aFractX = GetScaleWidth();
        Fraction aFractY = GetScaleHeight();
        aFractX *= aVisSize.Width();
        aFractY *= aVisSize.Height();
        aVisSize = Size( (long) aFractX, (long) aFractY );      // skaliert fuer Draw-Model

        //  pClientData->SetObjArea vor pDrawObj->SetLogicRect, damit keine
        //  falschen Skalierungen ausgerechnet werden:
        //Rectangle aObjArea = aLogicRect;
        //aObjArea.SetSize( aVisSize );          // Dokument-Groesse vom Server
        //SetObjArea( aObjArea );

        SfxViewShell* pSfxViewSh = GetViewShell();
        ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
        if ( pViewSh )
        {
            Window* pWin = pViewSh->GetActiveWin();
            if ( pWin->LogicToPixel( aVisSize ) != pWin->LogicToPixel( aLogicRect.GetSize() ) )
            {
                aLogicRect.SetSize( aVisSize );
                pDrawObj->SetLogicRect( aLogicRect );

                //  set document modified (SdrModel::SetChanged is not used)
                pViewSh->GetViewData()->GetDocShell()->SetDrawModified();
            }
        }
    }
}

void __EXPORT ScClient::MakeVisible()
{
    SdrOle2Obj* pDrawObj = GetDrawObj();
    if (pDrawObj)
    {
        SfxViewShell* pSfxViewSh = GetViewShell();
        ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
        if (pViewSh)
            pViewSh->ScrollToObject( pDrawObj );
    }
}

<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "formeditorgraphicsview.h"

#include <QWheelEvent>
#include <QApplication>
#include <QtDebug>

namespace QmlDesigner {

FormEditorGraphicsView::FormEditorGraphicsView(QWidget *parent) :
    QGraphicsView(parent)
{
    setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
    setResizeAnchor(QGraphicsView::AnchorViewCenter);
//    setCacheMode(QGraphicsView::CacheNone);
     setCacheMode(QGraphicsView::CacheBackground);
    setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
//    setViewportUpdateMode(QGraphicsView::NoViewportUpdate);
    setRenderHint(QPainter::Antialiasing, false);

    setFrameShape(QFrame::NoFrame);

    setAutoFillBackground(true);
    setBackgroundRole(QPalette::Window);

    const int checkerbordSize= 20;
    QPixmap tilePixmap(checkerbordSize * 2, checkerbordSize * 2);
    tilePixmap.fill(Qt::white);
    QPainter tilePainter(&tilePixmap);
    QColor color(220, 220, 220);
    tilePainter.fillRect(0, 0, checkerbordSize, checkerbordSize, color);
    tilePainter.fillRect(checkerbordSize, checkerbordSize, checkerbordSize, checkerbordSize, color);
    tilePainter.end();

    setBackgroundBrush(tilePixmap);

    viewport()->setMouseTracking(true);
}

void FormEditorGraphicsView::wheelEvent(QWheelEvent *event)
{
    if (event->modifiers().testFlag(Qt::ControlModifier)) {
        event->ignore();
    } else {
        QGraphicsView::wheelEvent(event);
    }

}

void FormEditorGraphicsView::mouseMoveEvent(QMouseEvent *event)
{
    if (rect().contains(event->pos())) {
        QGraphicsView::mouseMoveEvent(event);
    } else {
        QPoint position = event->pos();
        QPoint topLeft = rect().topLeft();
        QPoint bottomRight = rect().bottomRight();
        position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
        position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
        QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());

        QGraphicsView::mouseMoveEvent(mouseEvent);
        delete mouseEvent;
    }
}

void FormEditorGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
    if (rect().contains(event->pos())) {
        QGraphicsView::mouseReleaseEvent(event);
    } else {
        QPoint position = event->pos();
        QPoint topLeft = rect().topLeft();
        QPoint bottomRight = rect().bottomRight();
        position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
        position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
        QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());

        QGraphicsView::mouseReleaseEvent(mouseEvent);
        delete mouseEvent;
    }
}

void FormEditorGraphicsView::drawForeground(QPainter *painter, const QRectF &/*rect*/ )
{
    if (!m_feedbackNode.isValid())
        return;

    painter->save();

    painter->translate(mapToScene(QPoint(3, 3)));

    QColor changeColor(QColor(Qt::green).lighter(170));

    QFont font;
    font.setPixelSize(12);
    painter->setFont(font);

    painter->save();
    painter->setOpacity(0.7);

    QLinearGradient gradient(QPoint(0, 0), QPoint(100, 0));
    gradient.setColorAt(0.0, Qt::darkGray);
    gradient.setColorAt(1.0, Qt::gray);
    painter->setBrush(gradient);

    painter->setPen(Qt::black);
    int height = 40;
    if (m_feedbackNode.instanceHasAnchors())
        height += 24;
    painter->drawRoundedRect(QRect(-1, -1, 100, height), 5, 5);
    painter->restore();

    if (m_beginXHasExpression != m_feedbackNode.hasBindingProperty("x")) {
        painter->setPen(Qt::red);
    } else {
        if (m_beginX != m_feedbackNode.instanceValue("x"))
            painter->setPen(changeColor);
        else
            painter->setPen(Qt::black);
    }

    painter->drawText(QPoint(2.0, 12.0), QString("x:"));
    painter->drawText(QPoint(14.0, 12.0), m_feedbackNode.instanceValue("x").toString());

    if (m_beginYHasExpression != m_feedbackNode.hasBindingProperty("y")) {
        painter->setPen(Qt::red);
    } else {
        if (m_beginY != m_feedbackNode.instanceValue("y"))
            painter->setPen(changeColor);
        else
            painter->setPen(Qt::black);
    }

    painter->drawText(QPoint(50.0, 12.0), QString("y:"));
    painter->drawText(QPoint(60.0, 12.0), m_feedbackNode.instanceValue("y").toString());

    if (m_beginWidthHasExpression != m_feedbackNode.hasBindingProperty("width")) {
        painter->setPen(Qt::red);
    } else {
        if (m_beginWidth != m_feedbackNode.instanceValue("width"))
            painter->setPen(changeColor);
        else
            painter->setPen(Qt::black);
    }

    painter->drawText(QPoint(2.0, 24.0), QString("w:"));
    painter->drawText(QPoint(14.0, 24.0), m_feedbackNode.instanceValue("width").toString());

    if (m_beginHeightHasExpression != m_feedbackNode.hasBindingProperty("height")) {
        painter->setPen(Qt::red);
    } else {
        if (m_beginHeight != m_feedbackNode.instanceValue("height"))
            painter->setPen(changeColor);
        else
            painter->setPen(Qt::black);
    }

    painter->drawText(QPoint(50.0, 24.0), QString("h:"));
    painter->drawText(QPoint(60.0, 24.0),m_feedbackNode.instanceValue("height").toString());

    if (m_parentNode == m_feedbackNode.instanceParent()) {

        if (!m_feedbackNode.canReparent()) {
            painter->setPen(Qt::red);
            painter->drawText(QPoint(2.0, 36.0), QString("Cannot reparent"));
        }
    } else {
        painter->setPen(Qt::yellow);
        painter->drawText(QPoint(2.0, 36.0), QString("Parent changed"));

    }

    if (m_feedbackNode.instanceHasAnchors()) {
        if (m_beginTopMargin != m_feedbackNode.instanceValue("anchors.leftMargin"))
            painter->setPen(changeColor);
        else
            painter->setPen(Qt::black);

        painter->drawText(QPoint(2.0, 48.0), QString("l:"));
        painter->drawText(QPoint(14.0, 48.0), m_feedbackNode.instanceValue("anchors.leftMargin").toString());

        if (m_beginRightMargin != m_feedbackNode.instanceValue("anchors.rightMargin"))
            painter->setPen(changeColor);
        else
            painter->setPen(Qt::black);

        painter->drawText(QPoint(50.0, 48.0), QString("r:"));
        painter->drawText(QPoint(60.0, 48.0), m_feedbackNode.instanceValue("anchors.rightMargin").toString());

        if (m_beginTopMargin != m_feedbackNode.instanceValue("anchors.topMargin"))
            painter->setPen(changeColor);
        else
            painter->setPen(Qt::black);
        painter->drawText(QPoint(2.0, 60.0), QString("t:"));
        painter->drawText(QPoint(14.0, 60.0), m_feedbackNode.instanceValue("anchors.topMargin").toString());

        if (m_beginBottomMargin != m_feedbackNode.instanceValue("anchors.bottomMargin"))
            painter->setPen(changeColor);
        else
            painter->setPen(Qt::black);

        painter->drawText(QPoint(50.0, 60.0), QString("b:"));
        painter->drawText(QPoint(60.0, 60.0), m_feedbackNode.instanceValue("anchors.bottomMargin").toString());
    }

    painter->restore();
}

void FormEditorGraphicsView::setFeedbackNode(const QmlItemNode &node)
{
    if (node == m_feedbackNode)
        return;

    m_feedbackNode = node;

    if (m_feedbackNode.isValid()) {
        m_beginX = m_feedbackNode.instanceValue("x");
        m_beginY = m_feedbackNode.instanceValue("y");
        m_beginWidth = m_feedbackNode.instanceValue("width");
        m_beginHeight = m_feedbackNode.instanceValue("height");
        m_parentNode = m_feedbackNode.instanceParent();
        m_beginLeftMargin = m_feedbackNode.instanceValue("anchors.leftMargin");
        m_beginRightMargin = m_feedbackNode.instanceValue("anchors.rightMargin");
        m_beginTopMargin = m_feedbackNode.instanceValue("anchors.topMargin");
        m_beginBottomMargin = m_feedbackNode.instanceValue("anchors.bottomMargin");
        m_beginXHasExpression = m_feedbackNode.hasBindingProperty("x");
        m_beginYHasExpression = m_feedbackNode.hasBindingProperty("y");
        m_beginWidthHasExpression = m_feedbackNode.hasBindingProperty("width");
        m_beginHeightHasExpression = m_feedbackNode.hasBindingProperty("height");
    } else {
        m_beginX = QVariant();
        m_beginY = QVariant();
        m_beginWidth = QVariant();
        m_beginHeight = QVariant();
        m_parentNode = QmlObjectNode();
        m_beginLeftMargin = QVariant();
        m_beginRightMargin = QVariant();
        m_beginTopMargin = QVariant();
        m_beginBottomMargin = QVariant();
        m_beginXHasExpression = false;
        m_beginYHasExpression = false;
        m_beginWidthHasExpression = false;
        m_beginHeightHasExpression = false;
    }
}

void FormEditorGraphicsView::drawBackground(QPainter *painter, const QRectF &rect)
{
    painter->save();
    painter->setBrushOrigin(0, 0);
    painter->fillRect(rect.intersected(sceneRect()), backgroundBrush());
    // paint rect around editable area
    painter->setPen(Qt::black);
    QRectF frameRect = sceneRect().adjusted(0, 0, 0, 0);
    painter->drawRect(frameRect);
    painter->restore();
}

} // namespace QmlDesigner
<commit_msg>Improve feedback for expressions in the form editor<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "formeditorgraphicsview.h"

#include <QWheelEvent>
#include <QApplication>
#include <QtDebug>

namespace QmlDesigner {

FormEditorGraphicsView::FormEditorGraphicsView(QWidget *parent) :
    QGraphicsView(parent)
{
    setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
    setResizeAnchor(QGraphicsView::AnchorViewCenter);
//    setCacheMode(QGraphicsView::CacheNone);
     setCacheMode(QGraphicsView::CacheBackground);
    setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
//    setViewportUpdateMode(QGraphicsView::NoViewportUpdate);
    setRenderHint(QPainter::Antialiasing, false);

    setFrameShape(QFrame::NoFrame);

    setAutoFillBackground(true);
    setBackgroundRole(QPalette::Window);

    const int checkerbordSize= 20;
    QPixmap tilePixmap(checkerbordSize * 2, checkerbordSize * 2);
    tilePixmap.fill(Qt::white);
    QPainter tilePainter(&tilePixmap);
    QColor color(220, 220, 220);
    tilePainter.fillRect(0, 0, checkerbordSize, checkerbordSize, color);
    tilePainter.fillRect(checkerbordSize, checkerbordSize, checkerbordSize, checkerbordSize, color);
    tilePainter.end();

    setBackgroundBrush(tilePixmap);

    viewport()->setMouseTracking(true);
}

void FormEditorGraphicsView::wheelEvent(QWheelEvent *event)
{
    if (event->modifiers().testFlag(Qt::ControlModifier)) {
        event->ignore();
    } else {
        QGraphicsView::wheelEvent(event);
    }

}

void FormEditorGraphicsView::mouseMoveEvent(QMouseEvent *event)
{
    if (rect().contains(event->pos())) {
        QGraphicsView::mouseMoveEvent(event);
    } else {
        QPoint position = event->pos();
        QPoint topLeft = rect().topLeft();
        QPoint bottomRight = rect().bottomRight();
        position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
        position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
        QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());

        QGraphicsView::mouseMoveEvent(mouseEvent);
        delete mouseEvent;
    }
}

void FormEditorGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
    if (rect().contains(event->pos())) {
        QGraphicsView::mouseReleaseEvent(event);
    } else {
        QPoint position = event->pos();
        QPoint topLeft = rect().topLeft();
        QPoint bottomRight = rect().bottomRight();
        position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
        position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
        QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());

        QGraphicsView::mouseReleaseEvent(mouseEvent);
        delete mouseEvent;
    }
}

void FormEditorGraphicsView::drawForeground(QPainter *painter, const QRectF &/*rect*/ )
{
    if (!m_feedbackNode.isValid())
        return;

    painter->save();

    painter->translate(mapToScene(QPoint(3, 3)));

    QColor changeColor(QColor(Qt::green).lighter(170));

    QFont font;
    font.setPixelSize(12);
    painter->setFont(font);

    painter->save();
    painter->setOpacity(0.7);

    QLinearGradient gradient(QPoint(0, 0), QPoint(100, 0));
    gradient.setColorAt(0.0, Qt::darkGray);
    gradient.setColorAt(1.0, Qt::gray);
    painter->setBrush(gradient);

    painter->setPen(Qt::black);
    int height = 40;
    if (m_feedbackNode.instanceHasAnchors())
        height += 24;
    painter->drawRoundedRect(QRect(-1, -1, 100, height), 5, 5);
    painter->restore();

    if (m_beginXHasExpression) {
        if(m_feedbackNode.hasBindingProperty("x"))
            painter->setPen(Qt::blue);
        else
            painter->setPen(Qt::red);
    } else {
        if (m_beginX != m_feedbackNode.instanceValue("x"))
            painter->setPen(changeColor);
        else
            painter->setPen(Qt::black);
    }

    painter->drawText(QPoint(2.0, 12.0), QString("x:"));
    painter->drawText(QPoint(14.0, 12.0), m_feedbackNode.instanceValue("x").toString());

    if (m_beginYHasExpression) {
        if(m_feedbackNode.hasBindingProperty("y"))
            painter->setPen(Qt::blue);
        else
            painter->setPen(Qt::red);
    } else {
        if (m_beginY != m_feedbackNode.instanceValue("y"))
            painter->setPen(changeColor);
        else
            painter->setPen(Qt::black);
    }

    painter->drawText(QPoint(50.0, 12.0), QString("y:"));
    painter->drawText(QPoint(60.0, 12.0), m_feedbackNode.instanceValue("y").toString());

    if (m_beginWidthHasExpression) {
        if(m_feedbackNode.hasBindingProperty("width"))
            painter->setPen(Qt::blue);
        else
            painter->setPen(Qt::red);
    } else {
        if (m_beginWidth != m_feedbackNode.instanceValue("width"))
            painter->setPen(changeColor);
        else
            painter->setPen(Qt::black);
    }

    painter->drawText(QPoint(2.0, 24.0), QString("w:"));
    painter->drawText(QPoint(14.0, 24.0), m_feedbackNode.instanceValue("width").toString());

    if (m_beginHeightHasExpression) {
        if(m_feedbackNode.hasBindingProperty("height"))
            painter->setPen(Qt::blue);
        else
            painter->setPen(Qt::red);
    } else {
        if (m_beginHeight != m_feedbackNode.instanceValue("height"))
            painter->setPen(changeColor);
        else
            painter->setPen(Qt::black);
    }

    painter->drawText(QPoint(50.0, 24.0), QString("h:"));
    painter->drawText(QPoint(60.0, 24.0),m_feedbackNode.instanceValue("height").toString());

    if (m_parentNode == m_feedbackNode.instanceParent()) {

        if (!m_feedbackNode.canReparent()) {
            painter->setPen(Qt::red);
            painter->drawText(QPoint(2.0, 36.0), QString("Cannot reparent"));
        }
    } else {
        painter->setPen(Qt::yellow);
        painter->drawText(QPoint(2.0, 36.0), QString("Parent changed"));

    }

    if (m_feedbackNode.instanceHasAnchors()) {
        if (m_beginTopMargin != m_feedbackNode.instanceValue("anchors.leftMargin"))
            painter->setPen(changeColor);
        else
            painter->setPen(Qt::black);

        painter->drawText(QPoint(2.0, 48.0), QString("l:"));
        painter->drawText(QPoint(14.0, 48.0), m_feedbackNode.instanceValue("anchors.leftMargin").toString());

        if (m_beginRightMargin != m_feedbackNode.instanceValue("anchors.rightMargin"))
            painter->setPen(changeColor);
        else
            painter->setPen(Qt::black);

        painter->drawText(QPoint(50.0, 48.0), QString("r:"));
        painter->drawText(QPoint(60.0, 48.0), m_feedbackNode.instanceValue("anchors.rightMargin").toString());

        if (m_beginTopMargin != m_feedbackNode.instanceValue("anchors.topMargin"))
            painter->setPen(changeColor);
        else
            painter->setPen(Qt::black);
        painter->drawText(QPoint(2.0, 60.0), QString("t:"));
        painter->drawText(QPoint(14.0, 60.0), m_feedbackNode.instanceValue("anchors.topMargin").toString());

        if (m_beginBottomMargin != m_feedbackNode.instanceValue("anchors.bottomMargin"))
            painter->setPen(changeColor);
        else
            painter->setPen(Qt::black);

        painter->drawText(QPoint(50.0, 60.0), QString("b:"));
        painter->drawText(QPoint(60.0, 60.0), m_feedbackNode.instanceValue("anchors.bottomMargin").toString());
    }

    painter->restore();
}

void FormEditorGraphicsView::setFeedbackNode(const QmlItemNode &node)
{
    if (node == m_feedbackNode)
        return;

    m_feedbackNode = node;

    if (m_feedbackNode.isValid()) {
        m_beginX = m_feedbackNode.instanceValue("x");
        m_beginY = m_feedbackNode.instanceValue("y");
        m_beginWidth = m_feedbackNode.instanceValue("width");
        m_beginHeight = m_feedbackNode.instanceValue("height");
        m_parentNode = m_feedbackNode.instanceParent();
        m_beginLeftMargin = m_feedbackNode.instanceValue("anchors.leftMargin");
        m_beginRightMargin = m_feedbackNode.instanceValue("anchors.rightMargin");
        m_beginTopMargin = m_feedbackNode.instanceValue("anchors.topMargin");
        m_beginBottomMargin = m_feedbackNode.instanceValue("anchors.bottomMargin");
        m_beginXHasExpression = m_feedbackNode.hasBindingProperty("x");
        m_beginYHasExpression = m_feedbackNode.hasBindingProperty("y");
        m_beginWidthHasExpression = m_feedbackNode.hasBindingProperty("width");
        m_beginHeightHasExpression = m_feedbackNode.hasBindingProperty("height");
    } else {
        m_beginX = QVariant();
        m_beginY = QVariant();
        m_beginWidth = QVariant();
        m_beginHeight = QVariant();
        m_parentNode = QmlObjectNode();
        m_beginLeftMargin = QVariant();
        m_beginRightMargin = QVariant();
        m_beginTopMargin = QVariant();
        m_beginBottomMargin = QVariant();
        m_beginXHasExpression = false;
        m_beginYHasExpression = false;
        m_beginWidthHasExpression = false;
        m_beginHeightHasExpression = false;
    }
}

void FormEditorGraphicsView::drawBackground(QPainter *painter, const QRectF &rect)
{
    painter->save();
    painter->setBrushOrigin(0, 0);
    painter->fillRect(rect.intersected(sceneRect()), backgroundBrush());
    // paint rect around editable area
    painter->setPen(Qt::black);
    QRectF frameRect = sceneRect().adjusted(0, 0, 0, 0);
    painter->drawRect(frameRect);
    painter->restore();
}

} // namespace QmlDesigner
<|endoftext|>


<commit_before>/*
 * Copyright 2015 - 2021 gary@drinkingtea.net
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#pragma once

#if defined(__x86_64__) || defined(_M_AMD64)
#define OX_ARCH_x86_64
#elif defined(__i386__) || defined(_M_IX86)
#define OX_ARCH_x86_32
#elif defined(_M_AMD64)
#define OX_ARCH_ARM64
#elif defined(__arm__)
#define OX_ARCH_ARM
#endif

#if defined(OX_ARCH_ARM)

#if defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__)
#define OX_HW_DIV 1
#else
#define OX_HW_DIV 0
#endif

#elif defined(OX_ARCH_x86_32) || defined(OX_ARCH_x86_64) || defined(OX_ARCH_ARM64)

#define OX_HW_DIV 1

#else

#error "Undefined hardware"

#endif

<commit_msg>[ox/std] Fix OX_ARCH_ARM64 detection<commit_after>/*
 * Copyright 2015 - 2021 gary@drinkingtea.net
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#pragma once

#if defined(__x86_64__) || defined(_M_AMD64)
#define OX_ARCH_x86_64
#elif defined(__i386__) || defined(_M_IX86)
#define OX_ARCH_x86_32
#elif defined(__arm64__)
#define OX_ARCH_ARM64
#elif defined(__arm__)
#define OX_ARCH_ARM
#endif

#if defined(OX_ARCH_ARM)

#if defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__)
#define OX_HW_DIV 1
#else
#define OX_HW_DIV 0
#endif

#elif defined(OX_ARCH_x86_32) || defined(OX_ARCH_x86_64) || defined(OX_ARCH_ARM64)

#define OX_HW_DIV 1

#else

#error "Undefined hardware"

#endif

<|endoftext|>


<commit_before>/*
 *  Software License Agreement (BSD License)
 *
 *  Copyright (c) 2012, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 *  File:    FileStorageModel.cpp
 *  Author:  Hilton Bristow
 *  Created: Jul 27, 2012
 */

#include <sstream>
#include <opencv2/core/core.hpp>
#include "FileStorageModel.hpp"

bool FileStorageModel::serialize(const std::string& filename) const {

	// open the storage container for writing
	cv::FileStorage fs;
	fs.open(filename, cv::FileStorage::WRITE);

	// write the primitives
	fs << "name" 	 << name_;
	fs << "interval" << nscales_;
	fs << "thresh" 	 << thresh_;
	fs << "sbin" 	 << binsize_;
	fs << "norient"  << norient_;
	fs << "flen"     << flen_;

	// write the single depth vectors
	fs << "filtersw" << filtersw_;
	fs << "biasw"    << biasw_;
	fs << "anchors"  << anchors_;

	// write the 2D deformation weights
	fs << "defs" << "[";
	for (unsigned int n = 0; n < defw_.size(); ++n) {
		fs << defw_[n];
	}
	fs << "]";

	// write the deeper indexing vectors
	fs << "indexers" << "{";
	const unsigned int ncomponents = filterid_.size();
	for (unsigned int c = 0; c < ncomponents; ++c) {
		std::ostringstream cstr;
		cstr << "component-" << c;
		fs << cstr.str() << "{";
		const unsigned int nparts = filterid_[c].size();
		for (unsigned int p = 0; p < nparts; ++p) {
			std::ostringstream pstr;
			pstr << "part-" << p;
			fs << pstr.str() << "{";
			fs << "parentid" << parentid_[c][p];
			fs << "filterid" << filterid_[c][p];
			fs << "biasid"   << biasid_[c][p];
			fs << "defid"    << defid_[c][p];
			fs << "}";
		}
		fs << "}";
	}
	fs << "}";

	// close the file store
	fs.release();
	return true;
}

bool FileStorageModel::deserialize(const std::string& filename) {

	// open the storage container for writing
	cv::FileStorage fs;
	bool ok = fs.open(filename, cv::FileStorage::READ);
	if (!ok) return false;

	// read the primitives
	fs["name"] 	   >> name_;
	fs["interval"] >> nscales_;
	fs["thresh"]   >> thresh_;
	fs["sbin"] 	   >> binsize_;
	fs["norient"]  >> norient_;
	fs["flen"]     >> flen_;

	// read the single depth vectors
	fs["filtersw"] >> filtersw_;
	fs["biasw"]    >> biasw_;
	fs["anchors"]  >> anchors_;

	// read the 2D deformation weights
	cv::FileNode defs = fs["defs"];
	const unsigned int ndefs = defs.size();
	defw_.resize(ndefs);
	for (unsigned int n = 0; n < ndefs; ++n) {
		defs[n] >> defw_[n];
	}

	// read the indexing vectors
	cv::FileNode components = fs["indexers"];
	const unsigned int ncomponents = components.size();
	parentid_.resize(ncomponents);
	filterid_.resize(ncomponents);
	biasid_.resize(ncomponents);
	defid_.resize(ncomponents);
	for (unsigned int c = 0; c < ncomponents; ++c) {
		std::ostringstream cstr;
		cstr << "component-" << c;
		cv::FileNode parts = components[cstr.str()];
		const unsigned int nparts = parts.size();
		parentid_[c].resize(nparts);
		filterid_[c].resize(nparts);
		biasid_[c].resize(nparts);
		defid_[c].resize(nparts);
		for (unsigned int p = 0; p < nparts; ++p) {
			std::ostringstream pstr;
			pstr << "part-" << p;
			cv::FileNode part = parts[pstr.str()];
			part["parentid"] >> parentid_[c][p];
			part["filterid"] >> filterid_[c][p];
			part["biasid"]   >> biasid_[c][p];

			cv::FileNode defid = part["defid"];
			if(defid.isInt())
				defid >> defid_[c][p];
		}
	}

	// close the file store
	fs.release();
	return true;
}
<commit_msg>Read blank xml entry<commit_after>/*
 *  Software License Agreement (BSD License)
 *
 *  Copyright (c) 2012, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 *  File:    FileStorageModel.cpp
 *  Author:  Hilton Bristow
 *  Created: Jul 27, 2012
 */

#include <sstream>
#include <iostream>
#include <opencv2/core/core.hpp>
#include "FileStorageModel.hpp"

bool FileStorageModel::serialize(const std::string& filename) const {

	// open the storage container for writing
	cv::FileStorage fs;
	fs.open(filename, cv::FileStorage::WRITE);

	// write the primitives
	fs << "name" 	 << name_;
	fs << "interval" << nscales_;
	fs << "thresh" 	 << thresh_;
	fs << "sbin" 	 << binsize_;
	fs << "norient"  << norient_;
	fs << "flen"     << flen_;

	// write the single depth vectors
	fs << "filtersw" << filtersw_;
	fs << "biasw"    << biasw_;
	fs << "anchors"  << anchors_;

	// write the 2D deformation weights
	fs << "defs" << "[";
	for (unsigned int n = 0; n < defw_.size(); ++n) {
		fs << defw_[n];
	}
	fs << "]";

	// write the deeper indexing vectors
	fs << "indexers" << "{";
	const unsigned int ncomponents = filterid_.size();
	for (unsigned int c = 0; c < ncomponents; ++c) {
		std::ostringstream cstr;
		cstr << "component-" << c;
		fs << cstr.str() << "{";
		const unsigned int nparts = filterid_[c].size();
		for (unsigned int p = 0; p < nparts; ++p) {
			std::ostringstream pstr;
			pstr << "part-" << p;
			fs << pstr.str() << "{";
			fs << "parentid" << parentid_[c][p];
			fs << "filterid" << filterid_[c][p];
			fs << "biasid"   << biasid_[c][p];
			fs << "defid"    << defid_[c][p];
			fs << "}";
		}
		fs << "}";
	}
	fs << "}";

	// close the file store
	fs.release();
	return true;
}

bool FileStorageModel::deserialize(const std::string& filename) {

	// open the storage container for writing
	cv::FileStorage fs;
	bool ok = fs.open(filename, cv::FileStorage::READ);
	if (!ok) return false;

	// read the primitives
	fs["name"] 	   >> name_;
	fs["interval"] >> nscales_;
	fs["thresh"]   >> thresh_;
	fs["sbin"] 	   >> binsize_;
	fs["norient"]  >> norient_;
	fs["flen"]     >> flen_;

	// read the single depth vectors
	fs["filtersw"] >> filtersw_;
	fs["biasw"]    >> biasw_;
	fs["anchors"]  >> anchors_;

	// read the 2D deformation weights
	cv::FileNode defs = fs["defs"];
	const unsigned int ndefs = defs.size();
	defw_.resize(ndefs);
	for (unsigned int n = 0; n < ndefs; ++n) {
		defs[n] >> defw_[n];
	}

	// read the indexing vectors
	cv::FileNode components = fs["indexers"];
	const unsigned int ncomponents = components.size();
	parentid_.resize(ncomponents);
	filterid_.resize(ncomponents);
	biasid_.resize(ncomponents);
	defid_.resize(ncomponents);
	for (unsigned int c = 0; c < ncomponents; ++c) {
		std::ostringstream cstr;
		cstr << "component-" << c;
		cv::FileNode parts = components[cstr.str()];
		const unsigned int nparts = parts.size();
		parentid_[c].resize(nparts);
		filterid_[c].resize(nparts);
		biasid_[c].resize(nparts);
		defid_[c].resize(nparts);
		for (unsigned int p = 0; p < nparts; ++p) {
			std::ostringstream pstr;
			pstr << "part-" << p;
			cv::FileNode part = parts[pstr.str()];
			part["parentid"] >> parentid_[c][p];
			part["filterid"] >> filterid_[c][p];
			part["biasid"]   >> biasid_[c][p];

			cv::FileNode defid = part["defid"];
			if(defid.isInt())
				defid >> defid_[c][p];
			else
				defid_[c][p].push_back(0);
		}
	}

	// close the file store
	fs.release();
	return true;
}
<|endoftext|>


<commit_before>#include "builtin/thread.hpp"
#include "builtin/lookuptable.hpp"
#include "builtin/tuple.hpp"
#include "builtin/list.hpp"
#include "builtin/class.hpp"
#include "builtin/fixnum.hpp"
#include "builtin/symbol.hpp"
#include "builtin/float.hpp"
#include "builtin/channel.hpp"
#include "builtin/nativemethod.hpp"

#include "objectmemory.hpp"
#include "arguments.hpp"
#include "dispatch.hpp"
#include "call_frame.hpp"

#include "vm/object_utils.hpp"
#include "vm.hpp"

#include <sys/time.h>

namespace rubinius {

/* Class methods */

  void Thread::init(STATE) {
    GO(thread).set(state->new_class("Thread", G(object)));
    G(thread)->set_object_type(state, Thread::type);
  }

  Thread* Thread::create(STATE, VM* target, pthread_t tid) {
    Thread* thr = state->new_object<Thread>(G(thread));

    thr->thread_id(state, Fixnum::from(target->thread_id()));
    thr->alive(state, Qtrue);
    thr->sleep(state, Qfalse);
    thr->control_channel(state, (Channel*)Qnil);
    thr->recursive_objects(state, LookupTable::create(state));
    thr->vm_ = target;

    target->thread.set(thr);

    new(&thr->init_lock_) thread::SpinLock();

    if(tid == 0) thr->init_lock_.lock();

    return thr;
  }

/* Class primitives */

  Thread* Thread::allocate(STATE) {
    VM* vm = state->shared.new_vm();
    Thread* thread = Thread::create(state, vm);

    return thread;
  }

  Thread* Thread::current(STATE) {
    return state->thread.get();
  }

/* Instance primitives */

  void* Thread::in_new_thread(void* ptr) {
    VM* vm = reinterpret_cast<VM*>(ptr);

    int calculate_stack = 0;
    NativeMethod::init_thread(vm);
    VM::set_current(vm);

    vm->shared.gc_dependent(vm);

    if(cDebugThreading) {
      std::cerr << "[THREAD " << pthread_self() << " started thread]\n";
    }

    vm->set_stack_bounds(reinterpret_cast<uintptr_t>(&calculate_stack), 4194304);

    vm->thread->init_lock_.unlock();

    Object* ret = vm->thread.get()->send(vm, NULL, vm->symbol("__run__"));

    if(!ret) {
      if(vm->thread_state()->raise_reason() == cExit) {
        std::cerr << "Exit from thread detected.\n";
      }
    }

    vm->thread->init_lock_.lock();

    NativeMethod::cleanup_thread(vm);

    vm->thread->cleanup();
    vm->thread->init_lock_.unlock();

    vm->shared.gc_independent(vm);
    vm->shared.clear_critical(vm);

    VM::discard(vm);

    if(cDebugThreading) {
      std::cerr << "[LOCK thread " << pthread_self() << " exitted]\n";
    }

    return 0;
  }

  Object* Thread::fork(STATE) {
    pthread_attr_t attrs;
    pthread_attr_init(&attrs);
    pthread_attr_setstacksize(&attrs, 4194304);

    int error = pthread_create(&vm_->os_thread(), &attrs, in_new_thread, (void*)vm_);

    if(error) {
      Exception::thread_error(state, strerror(error));
    }
    return Qnil;
  }

  Object* Thread::pass(STATE, CallFrame* calling_environment) {
    struct timespec ts = {0, 0};
    nanosleep(&ts, NULL);
    return Qnil;
  }

  Object* Thread::priority(STATE) {
    pthread_t id = vm_->os_thread();

    if(id) {
      int _policy;
      struct sched_param params;

      pthread_check(pthread_getschedparam(id, &_policy, &params));

      return Fixnum::from(params.sched_priority);
    }

    return Qnil;
  }

  Object* Thread::raise(STATE, Exception* exc) {
    thread::SpinLock::LockGuard lg(init_lock_);

    VM* vm = vm_;
    if(!vm) return Qnil;

    vm->register_raise(state, exc);

    vm->wakeup();
    return exc;
  }

  Object* Thread::set_priority(STATE, Fixnum* new_priority) {
    return new_priority;
  }

  Thread* Thread::wakeup(STATE) {
    thread::SpinLock::LockGuard lg(init_lock_);

    if(alive() == Qfalse || !vm_) {
      return reinterpret_cast<Thread*>(kPrimitiveFailed);
    }

    VM* vm = vm_;
    if(!vm) return this;

    vm->wakeup();

    return this;
  }

  Tuple* Thread::context(STATE) {
    thread::SpinLock::LockGuard lg(init_lock_);

    VM* vm = vm_;
    if(!vm) return (Tuple*)Qnil;

    CallFrame* cf = vm->saved_call_frame();

    VariableScope* scope = cf->promote_scope(state);

    return Tuple::from(state, 3, Fixnum::from(cf->ip()), cf->cm, scope);
  }

  void Thread::detach_native_thread() {
  }

  void Thread::cleanup() {
    vm_ = NULL;
  }

  Object* Thread::join(STATE, CallFrame* calling_environment) {
    state->set_call_frame(calling_environment);

    init_lock_.lock();

    VM* vm = vm_;

    if(!vm) {
      init_lock_.unlock();
      return Qtrue;
    }

    pthread_t id = vm->os_thread();

    if(cDebugThreading) {
      std::cerr << "[THREAD joining " << id << "]\n";
    }

    init_lock_.unlock();

    state->shared.gc_independent(state);
    void* val;
    int err = pthread_join(id, &val);
    state->shared.gc_dependent(state);

    switch(err) {
    case 0:
      break;
    case EDEADLK:
      std::cerr << "Join deadlock: " << id << "/" << pthread_self() << "\n";
      break;
    case EINVAL:
      std::cerr << "Invalid thread id: " << id << "\n";
      break;
    case ESRCH:
      // This means that the thread finished execution and detached
      // itself. We treat this as having joined it.
      break;
    }

    return Qtrue;
  }

  Object* Thread::set_critical(STATE, Object* obj) {
    if(RTEST(obj)) {
      state->shared.set_critical(state);
      return Qtrue;
    } else {
      state->shared.clear_critical(state);
      return Qfalse;
    }
  }
}
<commit_msg>Wipe out the last saved call_frame to fix a GC crash<commit_after>#include "builtin/thread.hpp"
#include "builtin/lookuptable.hpp"
#include "builtin/tuple.hpp"
#include "builtin/list.hpp"
#include "builtin/class.hpp"
#include "builtin/fixnum.hpp"
#include "builtin/symbol.hpp"
#include "builtin/float.hpp"
#include "builtin/channel.hpp"
#include "builtin/nativemethod.hpp"

#include "objectmemory.hpp"
#include "arguments.hpp"
#include "dispatch.hpp"
#include "call_frame.hpp"

#include "vm/object_utils.hpp"
#include "vm.hpp"

#include <sys/time.h>

namespace rubinius {

/* Class methods */

  void Thread::init(STATE) {
    GO(thread).set(state->new_class("Thread", G(object)));
    G(thread)->set_object_type(state, Thread::type);
  }

  Thread* Thread::create(STATE, VM* target, pthread_t tid) {
    Thread* thr = state->new_object<Thread>(G(thread));

    thr->thread_id(state, Fixnum::from(target->thread_id()));
    thr->alive(state, Qtrue);
    thr->sleep(state, Qfalse);
    thr->control_channel(state, (Channel*)Qnil);
    thr->recursive_objects(state, LookupTable::create(state));
    thr->vm_ = target;

    target->thread.set(thr);

    new(&thr->init_lock_) thread::SpinLock();

    if(tid == 0) thr->init_lock_.lock();

    return thr;
  }

/* Class primitives */

  Thread* Thread::allocate(STATE) {
    VM* vm = state->shared.new_vm();
    Thread* thread = Thread::create(state, vm);

    return thread;
  }

  Thread* Thread::current(STATE) {
    return state->thread.get();
  }

/* Instance primitives */

  void* Thread::in_new_thread(void* ptr) {
    VM* vm = reinterpret_cast<VM*>(ptr);

    int calculate_stack = 0;
    NativeMethod::init_thread(vm);
    VM::set_current(vm);

    vm->set_call_frame(0);
    vm->shared.gc_dependent(vm);

    if(cDebugThreading) {
      std::cerr << "[THREAD " << pthread_self() << " started thread]\n";
    }

    vm->set_stack_bounds(reinterpret_cast<uintptr_t>(&calculate_stack), 4194304);

    vm->thread->init_lock_.unlock();

    Object* ret = vm->thread.get()->send(vm, NULL, vm->symbol("__run__"));

    if(!ret) {
      if(vm->thread_state()->raise_reason() == cExit) {
        std::cerr << "Exit from thread detected.\n";
      }
    }

    vm->thread->init_lock_.lock();

    NativeMethod::cleanup_thread(vm);

    vm->thread->cleanup();
    vm->thread->init_lock_.unlock();

    // Clear the call_frame, so that if we wait for GC going independent,
    // the GC doesn't see pointers into now-unallocated CallFrames
    vm->set_call_frame(0);
    vm->shared.gc_independent(vm);
    vm->shared.clear_critical(vm);

    VM::discard(vm);

    if(cDebugThreading) {
      std::cerr << "[LOCK thread " << pthread_self() << " exitted]\n";
    }

    return 0;
  }

  Object* Thread::fork(STATE) {
    pthread_attr_t attrs;
    pthread_attr_init(&attrs);
    pthread_attr_setstacksize(&attrs, 4194304);

    int error = pthread_create(&vm_->os_thread(), &attrs, in_new_thread, (void*)vm_);

    if(error) {
      Exception::thread_error(state, strerror(error));
    }
    return Qnil;
  }

  Object* Thread::pass(STATE, CallFrame* calling_environment) {
    struct timespec ts = {0, 0};
    nanosleep(&ts, NULL);
    return Qnil;
  }

  Object* Thread::priority(STATE) {
    pthread_t id = vm_->os_thread();

    if(id) {
      int _policy;
      struct sched_param params;

      pthread_check(pthread_getschedparam(id, &_policy, &params));

      return Fixnum::from(params.sched_priority);
    }

    return Qnil;
  }

  Object* Thread::raise(STATE, Exception* exc) {
    thread::SpinLock::LockGuard lg(init_lock_);

    VM* vm = vm_;
    if(!vm) return Qnil;

    vm->register_raise(state, exc);

    vm->wakeup();
    return exc;
  }

  Object* Thread::set_priority(STATE, Fixnum* new_priority) {
    return new_priority;
  }

  Thread* Thread::wakeup(STATE) {
    thread::SpinLock::LockGuard lg(init_lock_);

    if(alive() == Qfalse || !vm_) {
      return reinterpret_cast<Thread*>(kPrimitiveFailed);
    }

    VM* vm = vm_;
    if(!vm) return this;

    vm->wakeup();

    return this;
  }

  Tuple* Thread::context(STATE) {
    thread::SpinLock::LockGuard lg(init_lock_);

    VM* vm = vm_;
    if(!vm) return (Tuple*)Qnil;

    CallFrame* cf = vm->saved_call_frame();

    VariableScope* scope = cf->promote_scope(state);

    return Tuple::from(state, 3, Fixnum::from(cf->ip()), cf->cm, scope);
  }

  void Thread::detach_native_thread() {
  }

  void Thread::cleanup() {
    vm_ = NULL;
  }

  Object* Thread::join(STATE, CallFrame* calling_environment) {
    state->set_call_frame(calling_environment);

    init_lock_.lock();

    VM* vm = vm_;

    if(!vm) {
      init_lock_.unlock();
      return Qtrue;
    }

    pthread_t id = vm->os_thread();

    if(cDebugThreading) {
      std::cerr << "[THREAD joining " << id << "]\n";
    }

    init_lock_.unlock();

    state->shared.gc_independent(state);
    void* val;
    int err = pthread_join(id, &val);
    state->shared.gc_dependent(state);

    switch(err) {
    case 0:
      break;
    case EDEADLK:
      std::cerr << "Join deadlock: " << id << "/" << pthread_self() << "\n";
      break;
    case EINVAL:
      std::cerr << "Invalid thread id: " << id << "\n";
      break;
    case ESRCH:
      // This means that the thread finished execution and detached
      // itself. We treat this as having joined it.
      break;
    }

    return Qtrue;
  }

  Object* Thread::set_critical(STATE, Object* obj) {
    if(RTEST(obj)) {
      state->shared.set_critical(state);
      return Qtrue;
    } else {
      state->shared.clear_critical(state);
      return Qfalse;
    }
  }
}
<|endoftext|>