<commit_before>/* Copyright (C) 2003 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#define DBACC_C
#include "Dbacc.hpp"

#define DEBUG(x) { ndbout << "ACC::" << x << endl; }

void Dbacc::initData()
{
  cdirarraysize = ZDIRARRAY;
  coprecsize = ZOPRECSIZE;
  cpagesize = ZPAGESIZE;
  clcpConnectsize = ZLCP_CONNECTSIZE;
  ctablesize = ZTABLESIZE;
  cfragmentsize = ZFRAGMENTSIZE;
  crootfragmentsize = ZROOTFRAGMENTSIZE;
  cdirrangesize = ZDIRRANGESIZE;
  coverflowrecsize = ZOVERFLOWRECSIZE;
  cfsConnectsize = ZFS_CONNECTSIZE;
  cfsOpsize = ZFS_OPSIZE;
  cscanRecSize = ZSCAN_REC_SIZE;
  csrVersionRecSize = ZSR_VERSION_REC_SIZE;

  dirRange = 0;
  directoryarray = 0;
  fragmentrec = 0;
  fsConnectrec = 0;
  fsOprec = 0;
  lcpConnectrec = 0;
  operationrec = 0;
  overflowRecord = 0;
  page8 = 0;
  rootfragmentrec = 0;
  scanRec = 0;
  srVersionRec = 0;
  tabrec = 0;
  undopage = 0;

  // Records with constant sizes
}//Dbacc::initData()

void Dbacc::initRecords()
{
  // Records with dynamic sizes
  dirRange = (DirRange*)allocRecord("DirRange",
				    sizeof(DirRange),
				    cdirrangesize);

  directoryarray = (Directoryarray*)allocRecord("Directoryarray",
						sizeof(Directoryarray),
						cdirarraysize);

  fragmentrec = (Fragmentrec*)allocRecord("Fragmentrec",
					  sizeof(Fragmentrec),
					  cfragmentsize);

  fsConnectrec = (FsConnectrec*)allocRecord("FsConnectrec",
					    sizeof(FsConnectrec),
					    cfsConnectsize);

  fsOprec = (FsOprec*)allocRecord("FsOprec",
				  sizeof(FsOprec),
				  cfsOpsize);

  lcpConnectrec = (LcpConnectrec*)allocRecord("LcpConnectrec",
					      sizeof(LcpConnectrec),
					      clcpConnectsize);

  operationrec = (Operationrec*)allocRecord("Operationrec",
					    sizeof(Operationrec),
					    coprecsize);

  overflowRecord = (OverflowRecord*)allocRecord("OverflowRecord",
						sizeof(OverflowRecord),
						coverflowrecsize);

  page8 = (Page8*)allocRecord("Page8",
			      sizeof(Page8),
			      cpagesize,
			      false);

  rootfragmentrec = (Rootfragmentrec*)allocRecord("Rootfragmentrec",
						  sizeof(Rootfragmentrec),
						  crootfragmentsize);

  scanRec = (ScanRec*)allocRecord("ScanRec",
				  sizeof(ScanRec),
				  cscanRecSize);

  srVersionRec = (SrVersionRec*)allocRecord("SrVersionRec",
					    sizeof(SrVersionRec),
					    csrVersionRecSize);

  tabrec = (Tabrec*)allocRecord("Tabrec",
				sizeof(Tabrec),
				ctablesize);

  undopage = (Undopage*)allocRecord("Undopage",
				    sizeof(Undopage),
				    cundopagesize,
				    false);

  // Initialize BAT for interface to file system

  NewVARIABLE* bat = allocateBat(3);
  bat[1].WA = &page8->word32[0];
  bat[1].nrr = cpagesize;
  bat[1].ClusterSize = sizeof(Page8);
  bat[1].bits.q = 11;
  bat[1].bits.v = 5;
  bat[2].WA = &undopage->undoword[0];
  bat[2].nrr = cundopagesize;
  bat[2].ClusterSize = sizeof(Undopage);
  bat[2].bits.q = 13;
  bat[2].bits.v = 5;
}//Dbacc::initRecords()

Dbacc::Dbacc(const class Configuration & conf):
  SimulatedBlock(DBACC, conf),
  c_tup(0)
{
  Uint32 log_page_size= 0;
  BLOCK_CONSTRUCTOR(Dbacc);

  const ndb_mgm_configuration_iterator * p = conf.getOwnConfigIterator();
  ndbrequire(p != 0);

  ndb_mgm_get_int_parameter(p, CFG_DB_UNDO_INDEX_BUFFER,
			    &log_page_size);

  /**
   * Always set page size in half MBytes
   */
  cundopagesize= (log_page_size / sizeof(Undopage));
  Uint32 mega_byte_part= cundopagesize & 15;
  if (mega_byte_part != 0) {
    jam();
    cundopagesize+= (16 - mega_byte_part);
  }

  // Transit signals
  addRecSignal(GSN_DUMP_STATE_ORD, &Dbacc::execDUMP_STATE_ORD);
  addRecSignal(GSN_DEBUG_SIG, &Dbacc::execDEBUG_SIG);
  addRecSignal(GSN_CONTINUEB, &Dbacc::execCONTINUEB);
  addRecSignal(GSN_ACC_CHECK_SCAN, &Dbacc::execACC_CHECK_SCAN);
  addRecSignal(GSN_EXPANDCHECK2, &Dbacc::execEXPANDCHECK2);
  addRecSignal(GSN_SHRINKCHECK2, &Dbacc::execSHRINKCHECK2);
  addRecSignal(GSN_ACC_OVER_REC, &Dbacc::execACC_OVER_REC);
  addRecSignal(GSN_ACC_SAVE_PAGES, &Dbacc::execACC_SAVE_PAGES);
  addRecSignal(GSN_NEXTOPERATION, &Dbacc::execNEXTOPERATION);
  addRecSignal(GSN_READ_PSUEDO_REQ, &Dbacc::execREAD_PSUEDO_REQ);

  // Received signals
  addRecSignal(GSN_STTOR, &Dbacc::execSTTOR);
  addRecSignal(GSN_SR_FRAGIDREQ, &Dbacc::execSR_FRAGIDREQ);
  addRecSignal(GSN_LCP_FRAGIDREQ, &Dbacc::execLCP_FRAGIDREQ);
  addRecSignal(GSN_LCP_HOLDOPREQ, &Dbacc::execLCP_HOLDOPREQ);
  addRecSignal(GSN_END_LCPREQ, &Dbacc::execEND_LCPREQ);
  addRecSignal(GSN_ACC_LCPREQ, &Dbacc::execACC_LCPREQ);
  addRecSignal(GSN_START_RECREQ, &Dbacc::execSTART_RECREQ);
  addRecSignal(GSN_ACC_CONTOPREQ, &Dbacc::execACC_CONTOPREQ);
  addRecSignal(GSN_ACCKEYREQ, &Dbacc::execACCKEYREQ);
  addRecSignal(GSN_ACCSEIZEREQ, &Dbacc::execACCSEIZEREQ);
  addRecSignal(GSN_ACCFRAGREQ, &Dbacc::execACCFRAGREQ);
  addRecSignal(GSN_TC_SCHVERREQ, &Dbacc::execTC_SCHVERREQ);
  addRecSignal(GSN_ACC_SRREQ, &Dbacc::execACC_SRREQ);
  addRecSignal(GSN_NEXT_SCANREQ, &Dbacc::execNEXT_SCANREQ);
  addRecSignal(GSN_ACC_ABORTREQ, &Dbacc::execACC_ABORTREQ);
  addRecSignal(GSN_ACC_SCANREQ, &Dbacc::execACC_SCANREQ);
  addRecSignal(GSN_ACCMINUPDATE, &Dbacc::execACCMINUPDATE);
  addRecSignal(GSN_ACC_COMMITREQ, &Dbacc::execACC_COMMITREQ);
  addRecSignal(GSN_ACC_TO_REQ, &Dbacc::execACC_TO_REQ);
  addRecSignal(GSN_ACC_LOCKREQ, &Dbacc::execACC_LOCKREQ);
  addRecSignal(GSN_FSOPENCONF, &Dbacc::execFSOPENCONF);
  addRecSignal(GSN_FSOPENREF, &Dbacc::execFSOPENREF);
  addRecSignal(GSN_FSCLOSECONF, &Dbacc::execFSCLOSECONF);
  addRecSignal(GSN_FSCLOSEREF, &Dbacc::execFSCLOSEREF);
  addRecSignal(GSN_FSWRITECONF, &Dbacc::execFSWRITECONF);
  addRecSignal(GSN_FSWRITEREF, &Dbacc::execFSWRITEREF);
  addRecSignal(GSN_FSREADCONF, &Dbacc::execFSREADCONF);
  addRecSignal(GSN_FSREADREF, &Dbacc::execFSREADREF);
  addRecSignal(GSN_NDB_STTOR, &Dbacc::execNDB_STTOR);
  addRecSignal(GSN_DROP_TAB_REQ, &Dbacc::execDROP_TAB_REQ);
  addRecSignal(GSN_FSREMOVECONF, &Dbacc::execFSREMOVECONF);
  addRecSignal(GSN_FSREMOVEREF, &Dbacc::execFSREMOVEREF);
  addRecSignal(GSN_READ_CONFIG_REQ, &Dbacc::execREAD_CONFIG_REQ, true);
  addRecSignal(GSN_SET_VAR_REQ,  &Dbacc::execSET_VAR_REQ);

  initData();
}//Dbacc::Dbacc()

Dbacc::~Dbacc()
{
  deallocRecord((void **)&dirRange, "DirRange",
		sizeof(DirRange),
		cdirrangesize);

  deallocRecord((void **)&directoryarray, "Directoryarray",
		sizeof(Directoryarray),
		cdirarraysize);

  deallocRecord((void **)&fragmentrec, "Fragmentrec",
		sizeof(Fragmentrec),
		cfragmentsize);

  deallocRecord((void **)&fsConnectrec, "FsConnectrec",
		sizeof(FsConnectrec),
		cfsConnectsize);

  deallocRecord((void **)&fsOprec, "FsOprec",
		sizeof(FsOprec),
		cfsOpsize);

  deallocRecord((void **)&lcpConnectrec, "LcpConnectrec",
		sizeof(LcpConnectrec),
		clcpConnectsize);

  deallocRecord((void **)&operationrec, "Operationrec",
		sizeof(Operationrec),
		coprecsize);

  deallocRecord((void **)&overflowRecord, "OverflowRecord",
		sizeof(OverflowRecord),
		coverflowrecsize);

  deallocRecord((void **)&page8, "Page8",
		sizeof(Page8),
		cpagesize);

  deallocRecord((void **)&rootfragmentrec, "Rootfragmentrec",
		sizeof(Rootfragmentrec),
		crootfragmentsize);

  deallocRecord((void **)&scanRec, "ScanRec",
		sizeof(ScanRec),
		cscanRecSize);

  deallocRecord((void **)&srVersionRec, "SrVersionRec",
		sizeof(SrVersionRec),
		csrVersionRecSize);

  deallocRecord((void **)&tabrec, "Tabrec",
		sizeof(Tabrec),
		ctablesize);

  deallocRecord((void **)&undopage, "Undopage",
		sizeof(Undopage),
		cundopagesize);

}//Dbacc::~Dbacc()

BLOCK_FUNCTIONS(Dbacc)
<commit_msg>Garbage "global" local variables in Dbacc<commit_after>/* Copyright (C) 2003 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#define DBACC_C
#include "Dbacc.hpp"

#define DEBUG(x) { ndbout << "ACC::" << x << endl; }

void Dbacc::initData()
{
  cdirarraysize = ZDIRARRAY;
  coprecsize = ZOPRECSIZE;
  cpagesize = ZPAGESIZE;
  clcpConnectsize = ZLCP_CONNECTSIZE;
  ctablesize = ZTABLESIZE;
  cfragmentsize = ZFRAGMENTSIZE;
  crootfragmentsize = ZROOTFRAGMENTSIZE;
  cdirrangesize = ZDIRRANGESIZE;
  coverflowrecsize = ZOVERFLOWRECSIZE;
  cfsConnectsize = ZFS_CONNECTSIZE;
  cfsOpsize = ZFS_OPSIZE;
  cscanRecSize = ZSCAN_REC_SIZE;
  csrVersionRecSize = ZSR_VERSION_REC_SIZE;

  dirRange = 0;
  directoryarray = 0;
  fragmentrec = 0;
  fsConnectrec = 0;
  fsOprec = 0;
  lcpConnectrec = 0;
  operationrec = 0;
  overflowRecord = 0;
  page8 = 0;
  rootfragmentrec = 0;
  scanRec = 0;
  srVersionRec = 0;
  tabrec = 0;
  undopage = 0;

  // Records with constant sizes
}//Dbacc::initData()

void Dbacc::initRecords()
{
  // Records with dynamic sizes
  dirRange = (DirRange*)allocRecord("DirRange",
				    sizeof(DirRange),
				    cdirrangesize);

  directoryarray = (Directoryarray*)allocRecord("Directoryarray",
						sizeof(Directoryarray),
						cdirarraysize);

  fragmentrec = (Fragmentrec*)allocRecord("Fragmentrec",
					  sizeof(Fragmentrec),
					  cfragmentsize);

  fsConnectrec = (FsConnectrec*)allocRecord("FsConnectrec",
					    sizeof(FsConnectrec),
					    cfsConnectsize);

  fsOprec = (FsOprec*)allocRecord("FsOprec",
				  sizeof(FsOprec),
				  cfsOpsize);

  lcpConnectrec = (LcpConnectrec*)allocRecord("LcpConnectrec",
					      sizeof(LcpConnectrec),
					      clcpConnectsize);

  operationrec = (Operationrec*)allocRecord("Operationrec",
					    sizeof(Operationrec),
					    coprecsize);

  overflowRecord = (OverflowRecord*)allocRecord("OverflowRecord",
						sizeof(OverflowRecord),
						coverflowrecsize);

  page8 = (Page8*)allocRecord("Page8",
			      sizeof(Page8),
			      cpagesize,
			      false);

  rootfragmentrec = (Rootfragmentrec*)allocRecord("Rootfragmentrec",
						  sizeof(Rootfragmentrec),
						  crootfragmentsize);

  scanRec = (ScanRec*)allocRecord("ScanRec",
				  sizeof(ScanRec),
				  cscanRecSize);

  srVersionRec = (SrVersionRec*)allocRecord("SrVersionRec",
					    sizeof(SrVersionRec),
					    csrVersionRecSize);

  tabrec = (Tabrec*)allocRecord("Tabrec",
				sizeof(Tabrec),
				ctablesize);

  undopage = (Undopage*)allocRecord("Undopage",
				    sizeof(Undopage),
				    cundopagesize,
				    false);

  // Initialize BAT for interface to file system

  NewVARIABLE* bat = allocateBat(3);
  bat[1].WA = &page8->word32[0];
  bat[1].nrr = cpagesize;
  bat[1].ClusterSize = sizeof(Page8);
  bat[1].bits.q = 11;
  bat[1].bits.v = 5;
  bat[2].WA = &undopage->undoword[0];
  bat[2].nrr = cundopagesize;
  bat[2].ClusterSize = sizeof(Undopage);
  bat[2].bits.q = 13;
  bat[2].bits.v = 5;
}//Dbacc::initRecords()

Dbacc::Dbacc(const class Configuration & conf):
  SimulatedBlock(DBACC, conf),
  c_tup(0)
{
  Uint32 log_page_size= 0;
  BLOCK_CONSTRUCTOR(Dbacc);

  const ndb_mgm_configuration_iterator * p = conf.getOwnConfigIterator();
  ndbrequire(p != 0);

  ndb_mgm_get_int_parameter(p, CFG_DB_UNDO_INDEX_BUFFER,
			    &log_page_size);

  /**
   * Always set page size in half MBytes
   */
  cundopagesize= (log_page_size / sizeof(Undopage));
  Uint32 mega_byte_part= cundopagesize & 15;
  if (mega_byte_part != 0) {
    jam();
    cundopagesize+= (16 - mega_byte_part);
  }

  // Transit signals
  addRecSignal(GSN_DUMP_STATE_ORD, &Dbacc::execDUMP_STATE_ORD);
  addRecSignal(GSN_DEBUG_SIG, &Dbacc::execDEBUG_SIG);
  addRecSignal(GSN_CONTINUEB, &Dbacc::execCONTINUEB);
  addRecSignal(GSN_ACC_CHECK_SCAN, &Dbacc::execACC_CHECK_SCAN);
  addRecSignal(GSN_EXPANDCHECK2, &Dbacc::execEXPANDCHECK2);
  addRecSignal(GSN_SHRINKCHECK2, &Dbacc::execSHRINKCHECK2);
  addRecSignal(GSN_ACC_OVER_REC, &Dbacc::execACC_OVER_REC);
  addRecSignal(GSN_ACC_SAVE_PAGES, &Dbacc::execACC_SAVE_PAGES);
  addRecSignal(GSN_NEXTOPERATION, &Dbacc::execNEXTOPERATION);
  addRecSignal(GSN_READ_PSUEDO_REQ, &Dbacc::execREAD_PSUEDO_REQ);

  // Received signals
  addRecSignal(GSN_STTOR, &Dbacc::execSTTOR);
  addRecSignal(GSN_SR_FRAGIDREQ, &Dbacc::execSR_FRAGIDREQ);
  addRecSignal(GSN_LCP_FRAGIDREQ, &Dbacc::execLCP_FRAGIDREQ);
  addRecSignal(GSN_LCP_HOLDOPREQ, &Dbacc::execLCP_HOLDOPREQ);
  addRecSignal(GSN_END_LCPREQ, &Dbacc::execEND_LCPREQ);
  addRecSignal(GSN_ACC_LCPREQ, &Dbacc::execACC_LCPREQ);
  addRecSignal(GSN_START_RECREQ, &Dbacc::execSTART_RECREQ);
  addRecSignal(GSN_ACC_CONTOPREQ, &Dbacc::execACC_CONTOPREQ);
  addRecSignal(GSN_ACCKEYREQ, &Dbacc::execACCKEYREQ);
  addRecSignal(GSN_ACCSEIZEREQ, &Dbacc::execACCSEIZEREQ);
  addRecSignal(GSN_ACCFRAGREQ, &Dbacc::execACCFRAGREQ);
  addRecSignal(GSN_TC_SCHVERREQ, &Dbacc::execTC_SCHVERREQ);
  addRecSignal(GSN_ACC_SRREQ, &Dbacc::execACC_SRREQ);
  addRecSignal(GSN_NEXT_SCANREQ, &Dbacc::execNEXT_SCANREQ);
  addRecSignal(GSN_ACC_ABORTREQ, &Dbacc::execACC_ABORTREQ);
  addRecSignal(GSN_ACC_SCANREQ, &Dbacc::execACC_SCANREQ);
  addRecSignal(GSN_ACCMINUPDATE, &Dbacc::execACCMINUPDATE);
  addRecSignal(GSN_ACC_COMMITREQ, &Dbacc::execACC_COMMITREQ);
  addRecSignal(GSN_ACC_TO_REQ, &Dbacc::execACC_TO_REQ);
  addRecSignal(GSN_ACC_LOCKREQ, &Dbacc::execACC_LOCKREQ);
  addRecSignal(GSN_FSOPENCONF, &Dbacc::execFSOPENCONF);
  addRecSignal(GSN_FSOPENREF, &Dbacc::execFSOPENREF);
  addRecSignal(GSN_FSCLOSECONF, &Dbacc::execFSCLOSECONF);
  addRecSignal(GSN_FSCLOSEREF, &Dbacc::execFSCLOSEREF);
  addRecSignal(GSN_FSWRITECONF, &Dbacc::execFSWRITECONF);
  addRecSignal(GSN_FSWRITEREF, &Dbacc::execFSWRITEREF);
  addRecSignal(GSN_FSREADCONF, &Dbacc::execFSREADCONF);
  addRecSignal(GSN_FSREADREF, &Dbacc::execFSREADREF);
  addRecSignal(GSN_NDB_STTOR, &Dbacc::execNDB_STTOR);
  addRecSignal(GSN_DROP_TAB_REQ, &Dbacc::execDROP_TAB_REQ);
  addRecSignal(GSN_FSREMOVECONF, &Dbacc::execFSREMOVECONF);
  addRecSignal(GSN_FSREMOVEREF, &Dbacc::execFSREMOVEREF);
  addRecSignal(GSN_READ_CONFIG_REQ, &Dbacc::execREAD_CONFIG_REQ, true);
  addRecSignal(GSN_SET_VAR_REQ,  &Dbacc::execSET_VAR_REQ);

  initData();

#ifdef VM_TRACE
  {
    void* tmp[] = { &expDirRangePtr,
		    &gnsDirRangePtr,
		    &newDirRangePtr,
		    &rdDirRangePtr,
		    &nciOverflowrangeptr,
                    &expDirptr,
                    &rdDirptr,
                    &sdDirptr,
                    &nciOverflowDirptr,
                    &fragrecptr,
                    &fsConnectptr,
                    &fsOpptr,
                    &lcpConnectptr,
                    &operationRecPtr,
                    &idrOperationRecPtr,
                    &copyInOperPtr,
                    &copyOperPtr,
                    &mlpqOperPtr,
                    &queOperPtr,
                    &readWriteOpPtr,
                    &tgnptMainOpPtr,
                    &iopOverflowRecPtr,
                    &tfoOverflowRecPtr,
                    &porOverflowRecPtr,
                    &priOverflowRecPtr,
                    &rorOverflowRecPtr,
                    &sorOverflowRecPtr,
                    &troOverflowRecPtr,
                    &ancPageptr,
                    &colPageptr,
                    &ccoPageptr,
                    &datapageptr,
                    &delPageptr,
                    &excPageptr,
                    &expPageptr,
                    &gdiPageptr,
                    &gePageptr,
                    &gflPageptr,
                    &idrPageptr,
                    &ilcPageptr,
                    &inpPageptr,
                    &iopPageptr,
                    &lastPageptr,
                    &lastPrevpageptr,
                    &lcnPageptr,
                    &lcnCopyPageptr,
                    &lupPageptr,
                    &priPageptr,
                    &pwiPageptr,
                    &ciPageidptr,
                    &gsePageidptr,
                    &isoPageptr,
                    &nciPageidptr,
                    &rsbPageidptr,
                    &rscPageidptr,
                    &slPageidptr,
                    &sscPageidptr,
                    &rlPageptr,
                    &rlpPageptr,
                    &ropPageptr,
                    &rpPageptr,
                    &slPageptr,
                    &spPageptr,
                    &rootfragrecptr,
                    &scanPtr,
                    &srVersionPtr,
                    &tabptr,
                    &undopageptr
    };
    init_globals_list(tmp, sizeof(tmp)/sizeof(tmp[0]));
  }
#endif
}//Dbacc::Dbacc()

Dbacc::~Dbacc()
{
  deallocRecord((void **)&dirRange, "DirRange",
		sizeof(DirRange),
		cdirrangesize);

  deallocRecord((void **)&directoryarray, "Directoryarray",
		sizeof(Directoryarray),
		cdirarraysize);

  deallocRecord((void **)&fragmentrec, "Fragmentrec",
		sizeof(Fragmentrec),
		cfragmentsize);

  deallocRecord((void **)&fsConnectrec, "FsConnectrec",
		sizeof(FsConnectrec),
		cfsConnectsize);

  deallocRecord((void **)&fsOprec, "FsOprec",
		sizeof(FsOprec),
		cfsOpsize);

  deallocRecord((void **)&lcpConnectrec, "LcpConnectrec",
		sizeof(LcpConnectrec),
		clcpConnectsize);

  deallocRecord((void **)&operationrec, "Operationrec",
		sizeof(Operationrec),
		coprecsize);

  deallocRecord((void **)&overflowRecord, "OverflowRecord",
		sizeof(OverflowRecord),
		coverflowrecsize);

  deallocRecord((void **)&page8, "Page8",
		sizeof(Page8),
		cpagesize);

  deallocRecord((void **)&rootfragmentrec, "Rootfragmentrec",
		sizeof(Rootfragmentrec),
		crootfragmentsize);

  deallocRecord((void **)&scanRec, "ScanRec",
		sizeof(ScanRec),
		cscanRecSize);

  deallocRecord((void **)&srVersionRec, "SrVersionRec",
		sizeof(SrVersionRec),
		csrVersionRecSize);

  deallocRecord((void **)&tabrec, "Tabrec",
		sizeof(Tabrec),
		ctablesize);

  deallocRecord((void **)&undopage, "Undopage",
		sizeof(Undopage),
		cundopagesize);

}//Dbacc::~Dbacc()

BLOCK_FUNCTIONS(Dbacc)
<|endoftext|>


<commit_before>/*
 * LAMGGTest.cpp
 *
 *  Created on: 20.11.2014
 *      Author: Michael
 */

#include "LAMGGTest.h"
#include "../LAMG/MultiLevelSetup.h"
#include "../LAMG/SolverLamg.h"
#include "../../io/LineFileReader.h"
#include "../../auxiliary/Timer.h"

#include "../GaussSeidelRelaxation.h"

namespace NetworKit {

TEST_F(LAMGGTest, testSmallGraphs) {
	METISGraphReader reader;
	GaussSeidelRelaxation gaussSmoother;
	Smoother *smoother = new GaussSeidelRelaxation();
	MultiLevelSetup setup(gaussSmoother);
	Aux::Timer timer;
	for (index i = 0; i < GRAPH_INSTANCES.size(); ++i) {
		string graph = GRAPH_INSTANCES[i];
		Graph G = reader.read("instances/" + graph);
		ConnectedComponents con(G);
		con.run();
		Partition comps = con.getPartition();
		if (comps.numberOfSubsets() > 1) { // disconnected graphs are currently not supported
			continue;
		}

		LevelHierarchy hierarchy;
		timer.start();
		setup.setup(G, hierarchy);
		SolverLamg solver(hierarchy, *smoother);
		timer.stop();
		INFO("setup time\t ", timer.elapsedMilliseconds());

		Vector b = randZeroSum(G, 1234);

//		Vector b(G.numberOfNodes());
//		LineFileReader reader;
//		std::vector<string> lines = reader.read("instances/facebook100/Auburn71.mat.txt_b");
//		std::string input = lines[0];
//		std::string current = "";
//		int idx = 0;
//		for (int i = 0; i < input.size(); ++i) {
//			if (input[i] != ',') {
//				current += input[i];
//			} else {
//				b[idx++] = std::stod(current);
//				current = "";
//			}
//		}
//		b[b.getDimension() - 1] = std::stod(current);

//		INFO("b ", b.length());

		Vector x = randVector(G.upperNodeIdBound(), -1, 1);

//		Vector x(G.numberOfNodes());
//		lines = reader.read("instances/facebook100/Auburn71.mat.txt_x");
//		input = lines[0];
//		current = "";
//		idx = 0;
//		for (int i = 0; i < input.size(); ++i) {
//			if (input[i] != ',') {
//				current += input[i];
//			} else {
//				x[idx++] = std::stod(current);
//				current = "";
//			}
//		}
//		x[x.getDimension() - 1] = std::stod(current);
//
//		INFO("x ", x.length());

//		Vector result(G.upperNodeIdBound());

		LAMGSolverStatus status;
		status.maxConvergenceTime = 10 * 60 * 1000;
		status.desiredResidualReduction = 1e-6;

		Vector result = x;
		INFO("Solving equation system - Gauss-Seidel");
		timer.start();
		solver.solve(result, b, status);
		timer.stop();
		INFO("solve time\t ", timer.elapsedMilliseconds());
		INFO("final residual = ", status.residual);
		INFO("numIters = ", status.numIters);
		INFO("DONE");

	}

	delete smoother;
}

//TEST_F(LAMGGTest, generateGraphs) {
//	for (count size : grid2DSizes) {
//		genGrid2D(size);
//	}
//
//	for (count size : grid3DSizes) {
//		genGrid3D(size);
//	}
//
//	for (count size : barabasiSizes) {
//		genBarabasi(size);
//	}
//}

Vector LAMGGTest::randVector(count dimension, double lower, double upper) const {
	Vector randVector(dimension);
	for (index i = 0; i < dimension; ++i) {
		randVector[i] = 2.0 * Aux::Random::probability() - 1.0;
	}

	// introduce bias
	for (index i = 0; i < dimension; ++i) {
		randVector[i] = randVector[i] * randVector[i];
	}

	return randVector;
}

Vector LAMGGTest::capacitanceProblem(const Graph &graph) const {
	Vector b(graph.upperNodeIdBound(), 0.0);
	ConnectedComponents con(graph);
	count n = graph.upperNodeIdBound();
	con.run();
	Partition comps = con.getPartition();

	for (index i : comps.getSubsetIds()) {
		std::set<index> members = comps.getMembers(i);
		if (members.size() > 2) {
			count i = 0;
			for (index element : members) {
				if (i == 0) {
					b[element] = 1;
					i++;
				}

				if (i == 1) {
					b[element] = -1;
					break;
				}
			}

			break;
		}
	}

	return b;
}

Vector LAMGGTest::randZeroSum(const Graph& G, size_t seed) const {
	mt19937 rand(seed);
	auto rand_value = uniform_real_distribution<double>(-1.0, 1.0);
	ConnectedComponents con(G);
	count n = G.numberOfNodes();
	con.run();
	Partition comps = con.getPartition();

	/* Fill each component randomly such that its sum is 0 */
	Vector b(n, 0.0);

	for (int id : comps.getSubsetIds()) {
		auto indexes = comps.getMembers(id);
		assert(!indexes.empty());
		double sum = 0.0;
		for (auto entry : indexes) {
			b[entry] = rand_value(rand);
			sum += b[entry];
		}
		b[*indexes.begin()] -= sum;
	}

	return b;
}

// 2D-Grid with unit weights
void LAMGGTest::genGrid2D(count n) const {
  Graph G(n*n);
  for (index i = 0; i < n; ++i) {
    for (index j = 0; j < n; ++j) {
      if (i < n-1) {
        G.addEdge(i*n + j, (i+1)*n + j);
      }
      if (j < n-1) {
        G.addEdge(i*n + j, i*n + (j+1));
      }
    }
  }

  METISGraphWriter writer;
  writer.write(G, false, Aux::toStringF("instances/grid/Laplace_%sx%s.graph", n, n));
}

// 3D-Grid with unit weights
void LAMGGTest::genGrid3D(count n) const {
  Graph G(n*n*n);
  for (index i = 0; i < n; ++i) {
    for (index j = 0; j < n; ++j) {
      for (index k = 0; k < n; ++k) {
        if (i < n-1) {
          G.addEdge(i*n*n + j*n + k, (i+1)*n*n + j*n + k);
        }
        if (j < n-1) {
          G.addEdge(i*n*n + j*n + k, i*n*n + (j+1)*n + k);
        }
        if (k < n-1) {
          G.addEdge(i*n*n + j*n + k, i*n*n + j*n + k+1);
        }
      }
    }
  }

  METISGraphWriter writer;
  writer.write(G, false, Aux::toStringF("instances/grid3/Laplace_%sx%sx%s.graph", n, n, n));
}

/* Preferential attachment random graph with random weights */
void LAMGGTest::genBarabasi(count n, count attachment) const {
  random_device rd;
  mt19937 engine(rd());
  auto rand_weight = uniform_real_distribution<edgeweight>(0.1, 10.0);

  BarabasiAlbertGenerator gen(attachment /* degree */, n, attachment);
  Graph G = Graph(gen.generate(), true, false);
  G.forEdges([&] (node u, node v) {
    G.setWeight(u, v, rand_weight(engine));
  });

  METISGraphWriter writer;
  writer.write(G, true, Aux::toStringF("instances/barabasi/%s_att_%s_unweighted.graph", n, attachment));
}

} /* namespace NetworKit */
<commit_msg>only create new rhs if not already present<commit_after>/*
 * LAMGGTest.cpp
 *
 *  Created on: 20.11.2014
 *      Author: Michael
 */

#include "LAMGGTest.h"
#include "../LAMG/MultiLevelSetup.h"
#include "../LAMG/SolverLamg.h"
#include "../../io/LineFileReader.h"
#include "../../auxiliary/Timer.h"

#include "../GaussSeidelRelaxation.h"
#include "LAMGBenchmark.h"

namespace NetworKit {

extern bool readProblemVectors(Vector &b, Vector &x, const string &graphFilepath);

TEST_F(LAMGGTest, testSmallGraphs) {
	METISGraphReader reader;
	GaussSeidelRelaxation gaussSmoother;
	Smoother *smoother = new GaussSeidelRelaxation();
	MultiLevelSetup setup(gaussSmoother);
	Aux::Timer timer;
	for (index i = 0; i < GRAPH_INSTANCES.size(); ++i) {
		string graph = GRAPH_INSTANCES[i];
		Graph G = reader.read("instances/" + graph);
		ConnectedComponents con(G);
		con.run();
		Partition comps = con.getPartition();
		if (comps.numberOfSubsets() > 1) { // disconnected graphs are currently not supported
			continue;
		}

		LevelHierarchy hierarchy;
		timer.start();
		setup.setup(G, hierarchy);
		SolverLamg solver(hierarchy, *smoother);
		timer.stop();
		INFO("setup time\t ", timer.elapsedMilliseconds());

		Vector b(G.numberOfNodes());
		Vector x(G.numberOfNodes());

		if (!readProblemVectors(b, x, "instances/"+graph)) { // create new problem vectors if not present
			b = randZeroSum(G, 12345);
			x = randVector(G.numberOfNodes(), -1, 1);
		}

		LAMGSolverStatus status;
		status.maxConvergenceTime = 10 * 60 * 1000;
		status.desiredResidualReduction = 1e-6;

		Vector result = x;
		INFO("Solving equation system - Gauss-Seidel");
		timer.start();
		solver.solve(result, b, status);
		timer.stop();
		INFO("solve time\t ", timer.elapsedMilliseconds());
		INFO("final residual = ", status.residual);
		INFO("numIters = ", status.numIters);
		INFO("DONE");

	}

	delete smoother;
}

//TEST_F(LAMGGTest, generateGraphs) {
//	for (count size : grid2DSizes) {
//		genGrid2D(size);
//	}
//
//	for (count size : grid3DSizes) {
//		genGrid3D(size);
//	}
//
//	for (count size : barabasiSizes) {
//		genBarabasi(size);
//	}
//}

Vector LAMGGTest::randVector(count dimension, double lower, double upper) const {
	Vector randVector(dimension);
	for (index i = 0; i < dimension; ++i) {
		randVector[i] = 2.0 * Aux::Random::probability() - 1.0;
	}

	// introduce bias
	for (index i = 0; i < dimension; ++i) {
		randVector[i] = randVector[i] * randVector[i];
	}

	return randVector;
}

Vector LAMGGTest::capacitanceProblem(const Graph &graph) const {
	Vector b(graph.upperNodeIdBound(), 0.0);
	ConnectedComponents con(graph);
	count n = graph.upperNodeIdBound();
	con.run();
	Partition comps = con.getPartition();

	for (index i : comps.getSubsetIds()) {
		std::set<index> members = comps.getMembers(i);
		if (members.size() > 2) {
			count i = 0;
			for (index element : members) {
				if (i == 0) {
					b[element] = 1;
					i++;
				}

				if (i == 1) {
					b[element] = -1;
					break;
				}
			}

			break;
		}
	}

	return b;
}

Vector LAMGGTest::randZeroSum(const Graph& G, size_t seed) const {
	mt19937 rand(seed);
	auto rand_value = uniform_real_distribution<double>(-1.0, 1.0);
	ConnectedComponents con(G);
	count n = G.numberOfNodes();
	con.run();
	Partition comps = con.getPartition();

	/* Fill each component randomly such that its sum is 0 */
	Vector b(n, 0.0);

	for (int id : comps.getSubsetIds()) {
		auto indexes = comps.getMembers(id);
		assert(!indexes.empty());
		double sum = 0.0;
		for (auto entry : indexes) {
			b[entry] = rand_value(rand);
			sum += b[entry];
		}
		b[*indexes.begin()] -= sum;
	}

	return b;
}

// 2D-Grid with unit weights
void LAMGGTest::genGrid2D(count n) const {
  Graph G(n*n);
  for (index i = 0; i < n; ++i) {
    for (index j = 0; j < n; ++j) {
      if (i < n-1) {
        G.addEdge(i*n + j, (i+1)*n + j);
      }
      if (j < n-1) {
        G.addEdge(i*n + j, i*n + (j+1));
      }
    }
  }

  METISGraphWriter writer;
  writer.write(G, false, Aux::toStringF("instances/grid/Laplace_%sx%s.graph", n, n));
}

// 3D-Grid with unit weights
void LAMGGTest::genGrid3D(count n) const {
  Graph G(n*n*n);
  for (index i = 0; i < n; ++i) {
    for (index j = 0; j < n; ++j) {
      for (index k = 0; k < n; ++k) {
        if (i < n-1) {
          G.addEdge(i*n*n + j*n + k, (i+1)*n*n + j*n + k);
        }
        if (j < n-1) {
          G.addEdge(i*n*n + j*n + k, i*n*n + (j+1)*n + k);
        }
        if (k < n-1) {
          G.addEdge(i*n*n + j*n + k, i*n*n + j*n + k+1);
        }
      }
    }
  }

  METISGraphWriter writer;
  writer.write(G, false, Aux::toStringF("instances/grid3/Laplace_%sx%sx%s.graph", n, n, n));
}

/* Preferential attachment random graph with random weights */
void LAMGGTest::genBarabasi(count n, count attachment) const {
  random_device rd;
  mt19937 engine(rd());
  auto rand_weight = uniform_real_distribution<edgeweight>(0.1, 10.0);

  BarabasiAlbertGenerator gen(attachment /* degree */, n, attachment);
  Graph G = Graph(gen.generate(), true, false);
  G.forEdges([&] (node u, node v) {
    G.setWeight(u, v, rand_weight(engine));
  });

  METISGraphWriter writer;
  writer.write(G, true, Aux::toStringF("instances/barabasi/%s_att_%s_unweighted.graph", n, attachment));
}

} /* namespace NetworKit */
<|endoftext|>


<commit_before>/*
Copyright (c) 2010-2016, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the Universite de Sherbrooke nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <ros/ros.h>
#include <pluginlib/class_list_macros.h>
#include <nodelet/nodelet.h>

#include <sensor_msgs/Image.h>
#include <sensor_msgs/CompressedImage.h>
#include <sensor_msgs/image_encodings.h>
#include <sensor_msgs/CameraInfo.h>

#include <image_transport/image_transport.h>
#include <image_transport/subscriber_filter.h>

#include <message_filters/sync_policies/approximate_time.h>
#include <message_filters/sync_policies/exact_time.h>
#include <message_filters/subscriber.h>

#include <cv_bridge/cv_bridge.h>
#include <opencv2/highgui/highgui.hpp>

#include <boost/thread.hpp>

#include "rtabmap_ros/RGBDImage.h"

#include "rtabmap/core/Compression.h"
#include "rtabmap/utilite/UConversion.h"

namespace rtabmap_ros
{

class StereoSync : public nodelet::Nodelet
{
public:
	StereoSync() :
		warningThread_(0),
		callbackCalled_(false),
		approxSync_(0),
		exactSync_(0)
	{}

	virtual ~StereoSync()
	{
		if(approxSync_)
			delete approxSync_;
		if(exactSync_)
			delete exactSync_;

		if(warningThread_)
		{
			callbackCalled_=true;
			warningThread_->join();
			delete warningThread_;
		}
	}

private:
	virtual void onInit()
	{
		ros::NodeHandle & nh = getNodeHandle();
		ros::NodeHandle & pnh = getPrivateNodeHandle();

		int queueSize = 10;
		bool approxSync = false;
		pnh.param("approx_sync", approxSync, approxSync);
		pnh.param("queue_size", queueSize, queueSize);

		NODELET_INFO("%s: approx_sync = %s", getName().c_str(), approxSync?"true":"false");
		NODELET_INFO("%s: queue_size  = %d", getName().c_str(), queueSize);

		rgbdImagePub_ = nh.advertise<rtabmap_ros::RGBDImage>("rgbd_image", 1);
		rgbdImageCompressedPub_ = nh.advertise<rtabmap_ros::RGBDImage>("rgbd_image/compressed", 1);

		if(approxSync)
		{
			approxSync_ = new message_filters::Synchronizer<MyApproxSyncPolicy>(MyApproxSyncPolicy(queueSize), imageLeftSub_, imageRightSub_, cameraInfoLeftSub_, cameraInfoRightSub_);
			approxSync_->registerCallback(boost::bind(&StereoSync::callback, this, _1, _2, _3, _4));
		}
		else
		{
			exactSync_ = new message_filters::Synchronizer<MyExactSyncPolicy>(MyExactSyncPolicy(queueSize), imageLeftSub_, imageRightSub_, cameraInfoLeftSub_, cameraInfoRightSub_);
			exactSync_->registerCallback(boost::bind(&StereoSync::callback, this, _1, _2, _3, _4));
		}

		ros::NodeHandle left_nh(nh, "left");
		ros::NodeHandle right_nh(nh, "right");
		ros::NodeHandle left_pnh(pnh, "left");
		ros::NodeHandle right_pnh(pnh, "right");
		image_transport::ImageTransport rgb_it(left_nh);
		image_transport::ImageTransport depth_it(right_nh);
		image_transport::TransportHints hintsRgb("raw", ros::TransportHints(), left_pnh);
		image_transport::TransportHints hintsDepth("raw", ros::TransportHints(), right_pnh);

		imageLeftSub_.subscribe(rgb_it, left_nh.resolveName("image_rect"), 1, hintsRgb);
		imageRightSub_.subscribe(depth_it, right_nh.resolveName("image_rect"), 1, hintsDepth);
		cameraInfoLeftSub_.subscribe(left_nh, "camera_info", 1);
		cameraInfoRightSub_.subscribe(right_nh, "camera_info", 1);

		std::string subscribedTopicsMsg = uFormat("\n%s subscribed to (%s sync):\n   %s,\n   %s,\n   %s,\n   %s",
							getName().c_str(),
							approxSync?"approx":"exact",
							imageLeftSub_.getTopic().c_str(),
							imageRightSub_.getTopic().c_str(),
							cameraInfoLeftSub_.getTopic().c_str(),
							cameraInfoRightSub_.getTopic().c_str());

		warningThread_ = new boost::thread(boost::bind(&StereoSync::warningLoop, this, subscribedTopicsMsg, approxSync));
		NODELET_INFO("%s", subscribedTopicsMsg.c_str());
	}

	void warningLoop(const std::string & subscribedTopicsMsg, bool approxSync)
	{
		ros::Duration r(5.0);
		while(!callbackCalled_)
		{
			r.sleep();
			if(!callbackCalled_)
			{
				ROS_WARN("%s: Did not receive data since 5 seconds! Make sure the input topics are "
						"published (\"$ rostopic hz my_topic\") and the timestamps in their "
						"header are set. %s%s",
						getName().c_str(),
						approxSync?"":"Parameter \"approx_sync\" is false, which means that input "
							"topics should have all the exact timestamp for the callback to be called.",
						subscribedTopicsMsg.c_str());
			}
		}
	}

	void callback(
			  const sensor_msgs::ImageConstPtr& imageLeft,
			  const sensor_msgs::ImageConstPtr& imageRight,
			  const sensor_msgs::CameraInfoConstPtr& cameraInfoLeft,
			  const sensor_msgs::CameraInfoConstPtr& cameraInfoRight)
	{
		callbackCalled_ = true;
		if(rgbdImagePub_.getNumSubscribers() || rgbdImageCompressedPub_.getNumSubscribers())
		{
			double leftStamp = imageLeft->header.stamp.toSec();
			double rightStamp = imageRight->header.stamp.toSec();
			double leftInfoStamp = cameraInfoLeft->header.stamp.toSec();
			double rightInfoStamp = cameraInfoRight->header.stamp.toSec();

			rtabmap_ros::RGBDImage msg;
			msg.header.frame_id = cameraInfoLeft->header.frame_id;
			msg.header.stamp = imageLeft->header.stamp>imageRight->header.stamp?imageLeft->header.stamp:imageRight->header.stamp;
			msg.rgbCameraInfo = *cameraInfoLeft;
			msg.depthCameraInfo = *cameraInfoRight;

			if(rgbdImageCompressedPub_.getNumSubscribers())
			{
				rtabmap_ros::RGBDImage msgCompressed = msg;

				cv_bridge::CvImageConstPtr imagePtr = cv_bridge::toCvShare(imageLeft);
				imagePtr->toCompressedImageMsg(msgCompressed.rgbCompressed, cv_bridge::JPG);

				cv_bridge::CvImageConstPtr imageDepthPtr = cv_bridge::toCvShare(imageRight);
				imageDepthPtr->toCompressedImageMsg(msgCompressed.depthCompressed, cv_bridge::JPG);

				rgbdImageCompressedPub_.publish(msgCompressed);
			}

			if(rgbdImagePub_.getNumSubscribers())
			{
				msg.rgb = *imageLeft;
				msg.depth = *imageRight;
				rgbdImagePub_.publish(msg);
			}

			if( leftStamp != imageLeft->header.stamp.toSec() ||
				rightStamp != imageRight->header.stamp.toSec() ||
				leftInfoStamp != cameraInfoLeft->header.stamp.toSec() ||
				rightInfoStamp != cameraInfoRight->header.stamp.toSec())
			{
				NODELET_ERROR("Input stamps changed between the beginning and the end of the callback! Make "
						"sure the node publishing the topics doesn't override the same data after publishing them. A "
						"solution is to use this node within another nodelet manager. Stamps: "
						"left%f->%f right=%f->%f info_left=%f->%f info_right=%f->%f",
						leftStamp, imageLeft->header.stamp.toSec(),
						rightStamp, imageRight->header.stamp.toSec(),
						leftInfoStamp, cameraInfoLeft->header.stamp.toSec(),
						rightInfoStamp, cameraInfoRight->header.stamp.toSec());
			}
		}
	}

private:
	boost::thread * warningThread_;
	bool callbackCalled_;

	ros::Publisher rgbdImagePub_;
	ros::Publisher rgbdImageCompressedPub_;

	image_transport::SubscriberFilter imageLeftSub_;
	image_transport::SubscriberFilter imageRightSub_;
	message_filters::Subscriber<sensor_msgs::CameraInfo> cameraInfoLeftSub_;
	message_filters::Subscriber<sensor_msgs::CameraInfo> cameraInfoRightSub_;

	typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::Image, sensor_msgs::Image, sensor_msgs::CameraInfo, sensor_msgs::CameraInfo> MyApproxSyncPolicy;
	message_filters::Synchronizer<MyApproxSyncPolicy> * approxSync_;

	typedef message_filters::sync_policies::ExactTime<sensor_msgs::Image, sensor_msgs::Image, sensor_msgs::CameraInfo, sensor_msgs::CameraInfo> MyExactSyncPolicy;
	message_filters::Synchronizer<MyExactSyncPolicy> * exactSync_;
};

PLUGINLIB_EXPORT_CLASS(rtabmap_ros::StereoSync, nodelet::Nodelet);
}

<commit_msg>stereo_sync: added compressed_rate parameter<commit_after>/*
Copyright (c) 2010-2016, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the Universite de Sherbrooke nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <ros/ros.h>
#include <pluginlib/class_list_macros.h>
#include <nodelet/nodelet.h>

#include <sensor_msgs/Image.h>
#include <sensor_msgs/CompressedImage.h>
#include <sensor_msgs/image_encodings.h>
#include <sensor_msgs/CameraInfo.h>

#include <image_transport/image_transport.h>
#include <image_transport/subscriber_filter.h>

#include <message_filters/sync_policies/approximate_time.h>
#include <message_filters/sync_policies/exact_time.h>
#include <message_filters/subscriber.h>

#include <cv_bridge/cv_bridge.h>
#include <opencv2/highgui/highgui.hpp>

#include <boost/thread.hpp>

#include "rtabmap_ros/RGBDImage.h"

#include "rtabmap/core/Compression.h"
#include "rtabmap/utilite/UConversion.h"

namespace rtabmap_ros
{

class StereoSync : public nodelet::Nodelet
{
public:
	StereoSync() :
		compressedRate_(0),
		warningThread_(0),
		callbackCalled_(false),
		approxSync_(0),
		exactSync_(0)
	{}

	virtual ~StereoSync()
	{
		if(approxSync_)
			delete approxSync_;
		if(exactSync_)
			delete exactSync_;

		if(warningThread_)
		{
			callbackCalled_=true;
			warningThread_->join();
			delete warningThread_;
		}
	}

private:
	virtual void onInit()
	{
		ros::NodeHandle & nh = getNodeHandle();
		ros::NodeHandle & pnh = getPrivateNodeHandle();

		int queueSize = 10;
		bool approxSync = false;
		pnh.param("approx_sync", approxSync, approxSync);
		pnh.param("queue_size", queueSize, queueSize);
		pnh.param("compressed_rate", compressedRate_, compressedRate_);

		NODELET_INFO("%s: approx_sync = %s", getName().c_str(), approxSync?"true":"false");
		NODELET_INFO("%s: queue_size  = %d", getName().c_str(), queueSize);
		NODELET_INFO("%s: compressed_rate = %f", getName().c_str(), compressedRate_);

		rgbdImagePub_ = nh.advertise<rtabmap_ros::RGBDImage>("rgbd_image", 1);
		rgbdImageCompressedPub_ = nh.advertise<rtabmap_ros::RGBDImage>("rgbd_image/compressed", 1);

		if(approxSync)
		{
			approxSync_ = new message_filters::Synchronizer<MyApproxSyncPolicy>(MyApproxSyncPolicy(queueSize), imageLeftSub_, imageRightSub_, cameraInfoLeftSub_, cameraInfoRightSub_);
			approxSync_->registerCallback(boost::bind(&StereoSync::callback, this, _1, _2, _3, _4));
		}
		else
		{
			exactSync_ = new message_filters::Synchronizer<MyExactSyncPolicy>(MyExactSyncPolicy(queueSize), imageLeftSub_, imageRightSub_, cameraInfoLeftSub_, cameraInfoRightSub_);
			exactSync_->registerCallback(boost::bind(&StereoSync::callback, this, _1, _2, _3, _4));
		}

		ros::NodeHandle left_nh(nh, "left");
		ros::NodeHandle right_nh(nh, "right");
		ros::NodeHandle left_pnh(pnh, "left");
		ros::NodeHandle right_pnh(pnh, "right");
		image_transport::ImageTransport rgb_it(left_nh);
		image_transport::ImageTransport depth_it(right_nh);
		image_transport::TransportHints hintsRgb("raw", ros::TransportHints(), left_pnh);
		image_transport::TransportHints hintsDepth("raw", ros::TransportHints(), right_pnh);

		imageLeftSub_.subscribe(rgb_it, left_nh.resolveName("image_rect"), 1, hintsRgb);
		imageRightSub_.subscribe(depth_it, right_nh.resolveName("image_rect"), 1, hintsDepth);
		cameraInfoLeftSub_.subscribe(left_nh, "camera_info", 1);
		cameraInfoRightSub_.subscribe(right_nh, "camera_info", 1);

		std::string subscribedTopicsMsg = uFormat("\n%s subscribed to (%s sync):\n   %s,\n   %s,\n   %s,\n   %s",
							getName().c_str(),
							approxSync?"approx":"exact",
							imageLeftSub_.getTopic().c_str(),
							imageRightSub_.getTopic().c_str(),
							cameraInfoLeftSub_.getTopic().c_str(),
							cameraInfoRightSub_.getTopic().c_str());

		warningThread_ = new boost::thread(boost::bind(&StereoSync::warningLoop, this, subscribedTopicsMsg, approxSync));
		NODELET_INFO("%s", subscribedTopicsMsg.c_str());
	}

	void warningLoop(const std::string & subscribedTopicsMsg, bool approxSync)
	{
		ros::Duration r(5.0);
		while(!callbackCalled_)
		{
			r.sleep();
			if(!callbackCalled_)
			{
				ROS_WARN("%s: Did not receive data since 5 seconds! Make sure the input topics are "
						"published (\"$ rostopic hz my_topic\") and the timestamps in their "
						"header are set. %s%s",
						getName().c_str(),
						approxSync?"":"Parameter \"approx_sync\" is false, which means that input "
							"topics should have all the exact timestamp for the callback to be called.",
						subscribedTopicsMsg.c_str());
			}
		}
	}

	void callback(
			  const sensor_msgs::ImageConstPtr& imageLeft,
			  const sensor_msgs::ImageConstPtr& imageRight,
			  const sensor_msgs::CameraInfoConstPtr& cameraInfoLeft,
			  const sensor_msgs::CameraInfoConstPtr& cameraInfoRight)
	{
		callbackCalled_ = true;
		if(rgbdImagePub_.getNumSubscribers() || rgbdImageCompressedPub_.getNumSubscribers())
		{
			double leftStamp = imageLeft->header.stamp.toSec();
			double rightStamp = imageRight->header.stamp.toSec();
			double leftInfoStamp = cameraInfoLeft->header.stamp.toSec();
			double rightInfoStamp = cameraInfoRight->header.stamp.toSec();

			rtabmap_ros::RGBDImage msg;
			msg.header.frame_id = cameraInfoLeft->header.frame_id;
			msg.header.stamp = imageLeft->header.stamp>imageRight->header.stamp?imageLeft->header.stamp:imageRight->header.stamp;
			msg.rgbCameraInfo = *cameraInfoLeft;
			msg.depthCameraInfo = *cameraInfoRight;

			if(rgbdImageCompressedPub_.getNumSubscribers())
			{
				bool publishCompressed = true;
				if (compressedRate_ > 0.0)
				{
					if ( lastCompressedPublished_ + ros::Duration(1.0/compressedRate_) > ros::Time::now())
					{
						NODELET_DEBUG("throttle last update at %f skipping", lastCompressedPublished_.toSec());
						publishCompressed = false;
					}
				}

				if(publishCompressed)
				{
					lastCompressedPublished_ = ros::Time::now();

					rtabmap_ros::RGBDImage msgCompressed = msg;

					cv_bridge::CvImageConstPtr imagePtr = cv_bridge::toCvShare(imageLeft);
					imagePtr->toCompressedImageMsg(msgCompressed.rgbCompressed, cv_bridge::JPG);

					cv_bridge::CvImageConstPtr imageDepthPtr = cv_bridge::toCvShare(imageRight);
					imageDepthPtr->toCompressedImageMsg(msgCompressed.depthCompressed, cv_bridge::JPG);

					rgbdImageCompressedPub_.publish(msgCompressed);
				}
			}

			if(rgbdImagePub_.getNumSubscribers())
			{
				msg.rgb = *imageLeft;
				msg.depth = *imageRight;
				rgbdImagePub_.publish(msg);
			}

			if( leftStamp != imageLeft->header.stamp.toSec() ||
				rightStamp != imageRight->header.stamp.toSec() ||
				leftInfoStamp != cameraInfoLeft->header.stamp.toSec() ||
				rightInfoStamp != cameraInfoRight->header.stamp.toSec())
			{
				NODELET_ERROR("Input stamps changed between the beginning and the end of the callback! Make "
						"sure the node publishing the topics doesn't override the same data after publishing them. A "
						"solution is to use this node within another nodelet manager. Stamps: "
						"left%f->%f right=%f->%f info_left=%f->%f info_right=%f->%f",
						leftStamp, imageLeft->header.stamp.toSec(),
						rightStamp, imageRight->header.stamp.toSec(),
						leftInfoStamp, cameraInfoLeft->header.stamp.toSec(),
						rightInfoStamp, cameraInfoRight->header.stamp.toSec());
			}
		}
	}

private:
	double compressedRate_;
	boost::thread * warningThread_;
	bool callbackCalled_;
	ros::Time lastCompressedPublished_;

	ros::Publisher rgbdImagePub_;
	ros::Publisher rgbdImageCompressedPub_;

	image_transport::SubscriberFilter imageLeftSub_;
	image_transport::SubscriberFilter imageRightSub_;
	message_filters::Subscriber<sensor_msgs::CameraInfo> cameraInfoLeftSub_;
	message_filters::Subscriber<sensor_msgs::CameraInfo> cameraInfoRightSub_;

	typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::Image, sensor_msgs::Image, sensor_msgs::CameraInfo, sensor_msgs::CameraInfo> MyApproxSyncPolicy;
	message_filters::Synchronizer<MyApproxSyncPolicy> * approxSync_;

	typedef message_filters::sync_policies::ExactTime<sensor_msgs::Image, sensor_msgs::Image, sensor_msgs::CameraInfo, sensor_msgs::CameraInfo> MyExactSyncPolicy;
	message_filters::Synchronizer<MyExactSyncPolicy> * exactSync_;
};

PLUGINLIB_EXPORT_CLASS(rtabmap_ros::StereoSync, nodelet::Nodelet);
}

<|endoftext|>


<commit_before>//
// Created by dar on 11/29/15.
//

#include "Entity.h"
#include "core/map/Map.h"

Entity::Entity(Map *map, double width, double height) : id(Entity::getNextEntityId()), map(map) {
    this->width = width - 0.025;
    this->height = height - 0.025;
    bodyDef.type = b2_staticBody;
    body = this->map->getWorld()->CreateBody(&bodyDef);
    body->SetUserData(this);
    body->SetAngularDamping(30.0);
    body->SetLinearDamping(30.0);
}

void Entity::update(double deltaTime) {
    this->x = body->GetPosition().x + this->width * 0.5;
    this->y = body->GetPosition().y + this->height * 0.5;
}

void Entity::setY(double y) {
    body->SetTransform(b2Vec2(body->GetPosition().x, (float32) (y - this->height * 0.5)), body->GetAngle());
}

void Entity::setX(double x) {
    body->SetTransform(b2Vec2((float32) (x - this->width * 0.5), body->GetPosition().y), body->GetAngle());
}

Entity::~Entity() {
    this->map->getWorld()->DestroyBody(this->body);
}

unsigned int Entity::maxEntityId = 0;
unsigned int Entity::getNextEntityId() {
    Entity::maxEntityId++;
    return Entity::maxEntityId;
};<commit_msg>Added entity position change check. Bodies are now forced to wake up when they're (being) moved. This fixes overlap issue.<commit_after>//
// Created by dar on 11/29/15.
//

#include "Entity.h"
#include "core/map/Map.h"

Entity::Entity(Map *map, double width, double height) : id(Entity::getNextEntityId()), map(map) {
    this->width = width - 0.025;
    this->height = height - 0.025;
    bodyDef.type = b2_staticBody;
    body = this->map->getWorld()->CreateBody(&bodyDef);
    body->SetUserData(this);
    body->SetAngularDamping(30.0);
    body->SetLinearDamping(30.0);
}

void Entity::update(double deltaTime) {
    double newX = body->GetPosition().x + this->width * 0.5;
    double newY = body->GetPosition().y + this->height * 0.5;

    if (newX != this->x || newY != this->y) {
        this->getBody()->SetAwake(true);
    }

    this->x = newX;
    this->y = newY;
}

void Entity::setY(double y) {
    body->SetTransform(b2Vec2(body->GetPosition().x, (float32) (y - this->height * 0.5)), body->GetAngle());
}

void Entity::setX(double x) {
    body->SetTransform(b2Vec2((float32) (x - this->width * 0.5), body->GetPosition().y), body->GetAngle());
}

Entity::~Entity() {
    this->map->getWorld()->DestroyBody(this->body);
}

unsigned int Entity::maxEntityId = 0;
unsigned int Entity::getNextEntityId() {
    Entity::maxEntityId++;
    return Entity::maxEntityId;
};<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "tasklistplugin.h"

#include "stopmonitoringhandler.h"
#include "taskfile.h"
#include "taskfilefactory.h"
#include "tasklistconstants.h"

#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/project.h>
#include <projectexplorer/task.h>
#include <projectexplorer/taskhub.h>

#include <QtCore/QDir>
#include <QtCore/QStringList>
#include <QtCore/QtPlugin>

namespace {

ProjectExplorer::Task::TaskType typeFrom(const QString &typeName)
{
    ProjectExplorer::Task::TaskType type = ProjectExplorer::Task::Unknown;
    QString tmp = typeName.toLower();
    if (tmp.startsWith(QLatin1String("warn")))
        type = ProjectExplorer::Task::Warning;
    else if (tmp.startsWith(QLatin1String("err")))
        type = ProjectExplorer::Task::Error;
    return type;
}

} // namespace

using namespace TaskList;

TaskListPlugin *TaskListPlugin::m_instance = 0;

// --------------------------------------------------------------------------
// TaskListPluginPrivate
// --------------------------------------------------------------------------

class Internal::TaskListPluginPrivate {
public:
    bool parseTaskFile(QString *errorString, ProjectExplorer::Project *context, const QString &name)
    {
        QFile tf(name);
        if (!tf.open(QIODevice::ReadOnly)) {
            *errorString = TaskListPlugin::tr("Cannot open task file %1: %2").arg(
                    QDir::toNativeSeparators(name), tf.errorString());
            return false;
        }

        while (!tf.atEnd())
        {
            QStringList chunks = parseRawLine(tf.readLine());
            if (chunks.isEmpty())
                continue;

            QString description;
            QString file;
            ProjectExplorer::Task::TaskType type = ProjectExplorer::Task::Unknown;
            int line = -1;

            if (chunks.count() == 1) {
                description = chunks.at(0);
            } else if (chunks.count() == 2) {
                type = typeFrom(chunks.at(0));
                description = chunks.at(1);
            } else if (chunks.count() == 3) {
                file = chunks.at(0);
                type = typeFrom(chunks.at(1));
                description = chunks.at(2);
            } else if (chunks.count() >= 4) {
                file = chunks.at(0);
                bool ok;
                line = chunks.at(1).toInt(&ok);
                if (!ok)
                    line = -1;
                type = typeFrom(chunks.at(2));
                description = chunks.at(3);
            }
            if (!file.isEmpty()) {
                file = QDir::fromNativeSeparators(file);
                QFileInfo fi(file);
                if (fi.isRelative() && context) {
                    QString fullPath = context->projectDirectory() + '/' + file;
                    fi.setFile(fullPath);
                    file = fi.absoluteFilePath();
                }
            }

            hub->addTask(ProjectExplorer::Task(type, description, file, line, QLatin1String(Constants::TASKLISTTASK_ID)));
        }
        return true;
    }

    QStringList parseRawLine(const QByteArray &raw)
    {
        QStringList result;
        QString line = QString::fromUtf8(raw.constData());
        if (line.startsWith(QChar('#')))
            return result;

        result = line.split(QChar('\t'));
        for (int i = 0; i < result.count(); ++i)
            result[i] = unescape(result.at(i));

        return result;
    }

    QString unescape(const QString &input) const
    {
        QString result;
        for (int i = 0; i < input.count(); ++i) {
            if (input.at(i) == QChar('\\')) {
                if (i == input.count() - 1)
                    continue;
                if (input.at(i + 1) == QChar('n')) {
                    result.append(QChar('\n'));
                    ++i;
                    continue;
                } else if (input.at(i + 1) == QChar('t')) {
                    result.append(QChar('\t'));
                    ++i;
                    continue;
                } else if (input.at(i + 1) == QChar('\\')) {
                    result.append(QChar('\\'));
                    ++i;
                    continue;
                }
                continue;
            }
            result.append(input.at(i));
        }
        return result;
    }

    ProjectExplorer::TaskHub *hub;
    TaskFileFactory *fileFactory;
};

// --------------------------------------------------------------------------
// TaskListPlugin
// --------------------------------------------------------------------------

TaskListPlugin::TaskListPlugin() :
    d(new Internal::TaskListPluginPrivate)
{
    m_instance = this;
}

TaskListPlugin::~TaskListPlugin()
{
    delete d;
}

TaskListPlugin *TaskListPlugin::instance()
{
    return m_instance;
}

bool TaskListPlugin::initialize(const QStringList &arguments, QString *errorMessage)
{
    Q_UNUSED(arguments)

    ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
    d->hub = pm->getObject<ProjectExplorer::TaskHub>();

    //: Category under which tasklist tasks are listed in Issues view
    d->hub->addCategory(QLatin1String(Constants::TASKLISTTASK_ID), tr("My Tasks"));

    Core::ICore *core = Core::ICore::instance();
    if (!core->mimeDatabase()->addMimeTypes(QLatin1String(":tasklist/TaskList.mimetypes.xml"), errorMessage))
        return false;

    d->fileFactory = new Internal::TaskFileFactory(this);
    addAutoReleasedObject(d->fileFactory);
    addAutoReleasedObject(new Internal::StopMonitoringHandler);
    return true;
}

void TaskListPlugin::extensionsInitialized()
{ }

bool TaskListPlugin::loadFile(QString *errorString, ProjectExplorer::Project *context, const QString &fileName)
{
    clearTasks();
    return d->parseTaskFile(errorString, context, fileName);
}

bool TaskListPlugin::monitorFile(ProjectExplorer::Project *context, const QString &fileName)
{
    return d->fileFactory->open(context, fileName);
}

void TaskListPlugin::stopMonitoring()
{
    d->fileFactory->closeAllFiles();
}

void TaskListPlugin::clearTasks()
{
    d->hub->clearTasks(QLatin1String(Constants::TASKLISTTASK_ID));
}

Q_EXPORT_PLUGIN(TaskListPlugin)
<commit_msg>Tasklist: Backslash escapes in descriptions<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "tasklistplugin.h"

#include "stopmonitoringhandler.h"
#include "taskfile.h"
#include "taskfilefactory.h"
#include "tasklistconstants.h"

#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/project.h>
#include <projectexplorer/task.h>
#include <projectexplorer/taskhub.h>

#include <QtCore/QDir>
#include <QtCore/QStringList>
#include <QtCore/QtPlugin>

namespace {

ProjectExplorer::Task::TaskType typeFrom(const QString &typeName)
{
    ProjectExplorer::Task::TaskType type = ProjectExplorer::Task::Unknown;
    QString tmp = typeName.toLower();
    if (tmp.startsWith(QLatin1String("warn")))
        type = ProjectExplorer::Task::Warning;
    else if (tmp.startsWith(QLatin1String("err")))
        type = ProjectExplorer::Task::Error;
    return type;
}

} // namespace

using namespace TaskList;

TaskListPlugin *TaskListPlugin::m_instance = 0;

// --------------------------------------------------------------------------
// TaskListPluginPrivate
// --------------------------------------------------------------------------

class Internal::TaskListPluginPrivate {
public:
    bool parseTaskFile(QString *errorString, ProjectExplorer::Project *context, const QString &name)
    {
        QFile tf(name);
        if (!tf.open(QIODevice::ReadOnly)) {
            *errorString = TaskListPlugin::tr("Cannot open task file %1: %2").arg(
                    QDir::toNativeSeparators(name), tf.errorString());
            return false;
        }

        while (!tf.atEnd())
        {
            QStringList chunks = parseRawLine(tf.readLine());
            if (chunks.isEmpty())
                continue;

            QString description;
            QString file;
            ProjectExplorer::Task::TaskType type = ProjectExplorer::Task::Unknown;
            int line = -1;

            if (chunks.count() == 1) {
                description = chunks.at(0);
            } else if (chunks.count() == 2) {
                type = typeFrom(chunks.at(0));
                description = chunks.at(1);
            } else if (chunks.count() == 3) {
                file = chunks.at(0);
                type = typeFrom(chunks.at(1));
                description = chunks.at(2);
            } else if (chunks.count() >= 4) {
                file = chunks.at(0);
                bool ok;
                line = chunks.at(1).toInt(&ok);
                if (!ok)
                    line = -1;
                type = typeFrom(chunks.at(2));
                description = chunks.at(3);
            }
            if (!file.isEmpty()) {
                file = QDir::fromNativeSeparators(file);
                QFileInfo fi(file);
                if (fi.isRelative() && context) {
                    QString fullPath = context->projectDirectory() + '/' + file;
                    fi.setFile(fullPath);
                    file = fi.absoluteFilePath();
                }
            }
            description = unescape(description);

            hub->addTask(ProjectExplorer::Task(type, description, file, line, QLatin1String(Constants::TASKLISTTASK_ID)));
        }
        return true;
    }

    QStringList parseRawLine(const QByteArray &raw)
    {
        QStringList result;
        QString line = QString::fromUtf8(raw.constData());
        if (line.startsWith(QChar('#')))
            return result;

        return line.split(QChar('\t'));
    }

    QString unescape(const QString &input) const
    {
        QString result;
        for (int i = 0; i < input.count(); ++i) {
            if (input.at(i) == QChar('\\')) {
                if (i == input.count() - 1)
                    continue;
                if (input.at(i + 1) == QChar('n')) {
                    result.append(QChar('\n'));
                    ++i;
                    continue;
                } else if (input.at(i + 1) == QChar('t')) {
                    result.append(QChar('\t'));
                    ++i;
                    continue;
                } else if (input.at(i + 1) == QChar('\\')) {
                    result.append(QChar('\\'));
                    ++i;
                    continue;
                }
                continue;
            }
            result.append(input.at(i));
        }
        return result;
    }

    ProjectExplorer::TaskHub *hub;
    TaskFileFactory *fileFactory;
};

// --------------------------------------------------------------------------
// TaskListPlugin
// --------------------------------------------------------------------------

TaskListPlugin::TaskListPlugin() :
    d(new Internal::TaskListPluginPrivate)
{
    m_instance = this;
}

TaskListPlugin::~TaskListPlugin()
{
    delete d;
}

TaskListPlugin *TaskListPlugin::instance()
{
    return m_instance;
}

bool TaskListPlugin::initialize(const QStringList &arguments, QString *errorMessage)
{
    Q_UNUSED(arguments)

    ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
    d->hub = pm->getObject<ProjectExplorer::TaskHub>();

    //: Category under which tasklist tasks are listed in Issues view
    d->hub->addCategory(QLatin1String(Constants::TASKLISTTASK_ID), tr("My Tasks"));

    Core::ICore *core = Core::ICore::instance();
    if (!core->mimeDatabase()->addMimeTypes(QLatin1String(":tasklist/TaskList.mimetypes.xml"), errorMessage))
        return false;

    d->fileFactory = new Internal::TaskFileFactory(this);
    addAutoReleasedObject(d->fileFactory);
    addAutoReleasedObject(new Internal::StopMonitoringHandler);
    return true;
}

void TaskListPlugin::extensionsInitialized()
{ }

bool TaskListPlugin::loadFile(QString *errorString, ProjectExplorer::Project *context, const QString &fileName)
{
    clearTasks();
    return d->parseTaskFile(errorString, context, fileName);
}

bool TaskListPlugin::monitorFile(ProjectExplorer::Project *context, const QString &fileName)
{
    return d->fileFactory->open(context, fileName);
}

void TaskListPlugin::stopMonitoring()
{
    d->fileFactory->closeAllFiles();
}

void TaskListPlugin::clearTasks()
{
    d->hub->clearTasks(QLatin1String(Constants::TASKLISTTASK_ID));
}

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

#ifndef OOX_DRAWINGML_CHART_AXISMODEL_HXX
#define OOX_DRAWINGML_CHART_AXISMODEL_HXX

#include "oox/drawingml/shape.hxx"
#include "oox/drawingml/chart/titlemodel.hxx"

namespace oox {
namespace drawingml {
namespace chart {

// ============================================================================

struct AxisDispUnitsModel
{
    typedef ModelRef< Shape >       ShapeRef;
    typedef ModelRef< TextBody >    TextBodyRef;
    typedef ModelRef< LayoutModel > LayoutRef;
    typedef ModelRef< TextModel >   TextRef;

    ShapeRef            mxShapeProp;        /// Label frame formatting.
    TextBodyRef         mxTextProp;         /// Label text formatting.
    LayoutRef           mxLayout;           /// Layout/position of the axis units label.
    TextRef             mxText;             /// Text source of the axis units label.
    double              mfCustomUnit;       /// Custom unit size on value axis.
    sal_Int32           mnBuiltInUnit;      /// Built-in unit on value axis.

    explicit            AxisDispUnitsModel();
                        ~AxisDispUnitsModel();
};

// ============================================================================

struct AxisModel
{
    typedef ModelRef< Shape >               ShapeRef;
    typedef ModelRef< TextBody >            TextBodyRef;
    typedef ModelRef< TitleModel >          TitleRef;
    typedef ModelRef< AxisDispUnitsModel >  AxisDispUnitsRef;

    ShapeRef            mxShapeProp;        /// Axis line formatting.
    TextBodyRef         mxTextProp;         /// Axis label text formatting.
    TitleRef            mxTitle;            /// Axis title.
    AxisDispUnitsRef    mxDispUnits;        /// Axis units label.
    ShapeRef            mxMajorGridLines;   /// Major grid lines formatting.
    ShapeRef            mxMinorGridLines;   /// Minor grid lines formatting.
    ::rtl::OUString     maFormatCode;       /// Number format code for tick mark labels.
    OptValue< double >  mofCrossesAt;       /// Position on this axis where another axis crosses.
    OptValue< double >  mofMajorUnit;       /// Unit for major tick marks on date/value axis.
    OptValue< double >  mofMinorUnit;       /// Unit for minor tick marks on date/value axis.
    OptValue< double >  mofLogBase;         /// Logarithmic base for logarithmic axes.
    OptValue< double >  mofMax;             /// Maximum axis value.
    OptValue< double >  mofMin;             /// Minimum axis value.
    sal_Int32           mnAxisId;           /// Unique axis identifier.
    sal_Int32           mnAxisPos;          /// Position of the axis (top/bottom/left/right).
    sal_Int32           mnBaseTimeUnit;     /// Base time unit shown on a date axis.
    sal_Int32           mnCrossAxisId;      /// Identifier of a crossing axis.
    sal_Int32           mnCrossBetween;     /// This value axis crosses between or inside category.
    sal_Int32           mnCrossMode;        /// Mode this axis crosses another axis (min, max, auto).
    sal_Int32           mnLabelAlign;       /// Tick mark label alignment.
    sal_Int32           mnLabelOffset;      /// Tick mark label distance from axis.
    sal_Int32           mnMajorTickMark;    /// Major tick mark style.
    sal_Int32           mnMajorTimeUnit;    /// Time unit for major tick marks on date axis.
    sal_Int32           mnMinorTickMark;    /// Mainor tick mark style.
    sal_Int32           mnMinorTimeUnit;    /// Time unit for minor tick marks on date axis.
    sal_Int32           mnOrientation;      /// Axis orientation (value order min to max, or max to min).
    sal_Int32           mnTickLabelPos;     /// Position of tick mark labels relative to the axis.
    sal_Int32           mnTickLabelSkip;    /// Number of tick mark labels to skip.
    sal_Int32           mnTickMarkSkip;     /// Number of tick marks to skip.
    sal_Int32           mnTypeId;           /// Type identifier of this axis.
    bool                mbAuto;             /// True = automatic axis settings.
    bool                mbDeleted;          /// True = axis has been deleted manually.
    bool                mbNoMultiLevel;     /// True = no multi-level categories supported.
    bool                mbSourceLinked;     /// True = number format linked to source data.

    explicit            AxisModel( sal_Int32 nTypeId );
                        ~AxisModel();
};

// ============================================================================

} // namespace chart
} // namespace drawingml
} // namespace oox

#endif

<commit_msg>INTEGRATION: CWS xmlfilter06 (1.4.6); FILE MERGED 2008/06/25 14:58:37 dr 1.4.6.3: import chart data point labels and trendline label 2008/06/23 15:31:40 dr 1.4.6.2: more chart axis settings 2008/05/27 10:40:28 dr 1.4.6.1: joined changes from CWS xmlfilter05<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: axismodel.hxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef OOX_DRAWINGML_CHART_AXISMODEL_HXX
#define OOX_DRAWINGML_CHART_AXISMODEL_HXX

#include "oox/drawingml/shape.hxx"
#include "oox/drawingml/chart/titlemodel.hxx"

namespace oox {
namespace drawingml {
namespace chart {

// ============================================================================

struct AxisDispUnitsModel
{
    typedef ModelRef< Shape >       ShapeRef;
    typedef ModelRef< TextBody >    TextBodyRef;
    typedef ModelRef< LayoutModel > LayoutRef;
    typedef ModelRef< TextModel >   TextRef;

    ShapeRef            mxShapeProp;        /// Label frame formatting.
    TextBodyRef         mxTextProp;         /// Label text formatting.
    LayoutRef           mxLayout;           /// Layout/position of the axis units label.
    TextRef             mxText;             /// Text source of the axis units label.
    double              mfCustomUnit;       /// Custom unit size on value axis.
    sal_Int32           mnBuiltInUnit;      /// Built-in unit on value axis.

    explicit            AxisDispUnitsModel();
                        ~AxisDispUnitsModel();
};

// ============================================================================

struct AxisModel
{
    typedef ModelRef< Shape >               ShapeRef;
    typedef ModelRef< TextBody >            TextBodyRef;
    typedef ModelRef< TitleModel >          TitleRef;
    typedef ModelRef< AxisDispUnitsModel >  AxisDispUnitsRef;

    ShapeRef            mxShapeProp;        /// Axis line formatting.
    TextBodyRef         mxTextProp;         /// Axis label text formatting.
    TitleRef            mxTitle;            /// Axis title.
    AxisDispUnitsRef    mxDispUnits;        /// Axis units label.
    ShapeRef            mxMajorGridLines;   /// Major grid lines formatting.
    ShapeRef            mxMinorGridLines;   /// Minor grid lines formatting.
    NumberFormat        maNumberFormat;     /// Number format for axis tick labels.
    OptValue< double >  mofCrossesAt;       /// Position on this axis where another axis crosses.
    OptValue< double >  mofMajorUnit;       /// Unit for major tick marks on date/value axis.
    OptValue< double >  mofMinorUnit;       /// Unit for minor tick marks on date/value axis.
    OptValue< double >  mofLogBase;         /// Logarithmic base for logarithmic axes.
    OptValue< double >  mofMax;             /// Maximum axis value.
    OptValue< double >  mofMin;             /// Minimum axis value.
    sal_Int32           mnAxisId;           /// Unique axis identifier.
    sal_Int32           mnAxisPos;          /// Position of the axis (top/bottom/left/right).
    sal_Int32           mnBaseTimeUnit;     /// Base time unit shown on a date axis.
    sal_Int32           mnCrossAxisId;      /// Identifier of a crossing axis.
    sal_Int32           mnCrossBetween;     /// This value axis crosses between or inside category.
    sal_Int32           mnCrossMode;        /// Mode this axis crosses another axis (min, max, auto).
    sal_Int32           mnLabelAlign;       /// Tick mark label alignment.
    sal_Int32           mnLabelOffset;      /// Tick mark label distance from axis.
    sal_Int32           mnMajorTickMark;    /// Major tick mark style.
    sal_Int32           mnMajorTimeUnit;    /// Time unit for major tick marks on date axis.
    sal_Int32           mnMinorTickMark;    /// Mainor tick mark style.
    sal_Int32           mnMinorTimeUnit;    /// Time unit for minor tick marks on date axis.
    sal_Int32           mnOrientation;      /// Axis orientation (value order min to max, or max to min).
    sal_Int32           mnTickLabelPos;     /// Position of tick mark labels relative to the axis.
    sal_Int32           mnTickLabelSkip;    /// Number of tick mark labels to skip.
    sal_Int32           mnTickMarkSkip;     /// Number of tick marks to skip.
    sal_Int32           mnTypeId;           /// Type identifier of this axis.
    bool                mbAuto;             /// True = automatic axis settings.
    bool                mbDeleted;          /// True = axis has been deleted manually.
    bool                mbNoMultiLevel;     /// True = no multi-level categories supported.

    explicit            AxisModel( sal_Int32 nTypeId );
                        ~AxisModel();
};

// ============================================================================

} // namespace chart
} // namespace drawingml
} // namespace oox

#endif

<|endoftext|>