text stringlengths 54 60.6k |
|---|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xiformula.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2007-02-27 12:26:44 $
*
* 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 "precompiled_sc.hxx"
#ifndef SC_XIFORMULA_HXX
#include "xiformula.hxx"
#endif
#ifndef SC_RANGELST_HXX
#include "rangelst.hxx"
#endif
#ifndef SC_XISTREAM_HXX
#include "xistream.hxx"
#endif
#include "excform.hxx"
// Formula compiler ===========================================================
/** Implementation class of the export formula compiler. */
class XclImpFmlaCompImpl : protected XclImpRoot, protected XclTokenArrayHelper
{
public:
explicit XclImpFmlaCompImpl( const XclImpRoot& rRoot );
/** Creates a range list from the passed Excel token array. */
void CreateRangeList(
ScRangeList& rScRanges, XclFormulaType eType,
const XclTokenArray& rXclTokArr, XclImpStream& rStrm );
// ------------------------------------------------------------------------
private:
XclFunctionProvider maFuncProv; /// Excel function data provider.
const XclBiff meBiff; /// Cached BIFF version to save GetBiff() calls.
};
// ----------------------------------------------------------------------------
XclImpFmlaCompImpl::XclImpFmlaCompImpl( const XclImpRoot& rRoot ) :
XclImpRoot( rRoot ),
maFuncProv( rRoot ),
meBiff( rRoot.GetBiff() )
{
}
void XclImpFmlaCompImpl::CreateRangeList(
ScRangeList& rScRanges, XclFormulaType /*eType*/,
const XclTokenArray& rXclTokArr, XclImpStream& /*rStrm*/ )
{
rScRanges.RemoveAll();
//! evil hack, using old formula import :-)
if( !rXclTokArr.Empty() )
{
SvMemoryStream aMemStrm;
aMemStrm << EXC_ID_EOF << rXclTokArr.GetSize();
aMemStrm.Write( rXclTokArr.GetData(), rXclTokArr.GetSize() );
XclImpStream aFmlaStrm( aMemStrm, GetRoot() );
aFmlaStrm.StartNextRecord();
GetOldFmlaConverter().GetAbsRefs( rScRanges, aFmlaStrm, aFmlaStrm.GetRecSize() );
}
}
// ----------------------------------------------------------------------------
XclImpFormulaCompiler::XclImpFormulaCompiler( const XclImpRoot& rRoot ) :
XclImpRoot( rRoot ),
mxImpl( new XclImpFmlaCompImpl( rRoot ) )
{
}
XclImpFormulaCompiler::~XclImpFormulaCompiler()
{
}
void XclImpFormulaCompiler::CreateRangeList(
ScRangeList& rScRanges, XclFormulaType eType,
const XclTokenArray& rXclTokArr, XclImpStream& rStrm )
{
mxImpl->CreateRangeList( rScRanges, eType, rXclTokArr, rStrm );
}
// ============================================================================
<commit_msg>INTEGRATION: CWS changefileheader (1.4.328); FILE MERGED 2008/04/01 12:36:12 thb 1.4.328.2: #i85898# Stripping all external header guards 2008/03/31 17:14:32 rt 1.4.328.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xiformula.cxx,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.
*
************************************************************************/
#include "precompiled_sc.hxx"
#include "xiformula.hxx"
#include "rangelst.hxx"
#include "xistream.hxx"
#include "excform.hxx"
// Formula compiler ===========================================================
/** Implementation class of the export formula compiler. */
class XclImpFmlaCompImpl : protected XclImpRoot, protected XclTokenArrayHelper
{
public:
explicit XclImpFmlaCompImpl( const XclImpRoot& rRoot );
/** Creates a range list from the passed Excel token array. */
void CreateRangeList(
ScRangeList& rScRanges, XclFormulaType eType,
const XclTokenArray& rXclTokArr, XclImpStream& rStrm );
// ------------------------------------------------------------------------
private:
XclFunctionProvider maFuncProv; /// Excel function data provider.
const XclBiff meBiff; /// Cached BIFF version to save GetBiff() calls.
};
// ----------------------------------------------------------------------------
XclImpFmlaCompImpl::XclImpFmlaCompImpl( const XclImpRoot& rRoot ) :
XclImpRoot( rRoot ),
maFuncProv( rRoot ),
meBiff( rRoot.GetBiff() )
{
}
void XclImpFmlaCompImpl::CreateRangeList(
ScRangeList& rScRanges, XclFormulaType /*eType*/,
const XclTokenArray& rXclTokArr, XclImpStream& /*rStrm*/ )
{
rScRanges.RemoveAll();
//! evil hack, using old formula import :-)
if( !rXclTokArr.Empty() )
{
SvMemoryStream aMemStrm;
aMemStrm << EXC_ID_EOF << rXclTokArr.GetSize();
aMemStrm.Write( rXclTokArr.GetData(), rXclTokArr.GetSize() );
XclImpStream aFmlaStrm( aMemStrm, GetRoot() );
aFmlaStrm.StartNextRecord();
GetOldFmlaConverter().GetAbsRefs( rScRanges, aFmlaStrm, aFmlaStrm.GetRecSize() );
}
}
// ----------------------------------------------------------------------------
XclImpFormulaCompiler::XclImpFormulaCompiler( const XclImpRoot& rRoot ) :
XclImpRoot( rRoot ),
mxImpl( new XclImpFmlaCompImpl( rRoot ) )
{
}
XclImpFormulaCompiler::~XclImpFormulaCompiler()
{
}
void XclImpFormulaCompiler::CreateRangeList(
ScRangeList& rScRanges, XclFormulaType eType,
const XclTokenArray& rXclTokArr, XclImpStream& rStrm )
{
mxImpl->CreateRangeList( rScRanges, eType, rXclTokArr, rStrm );
}
// ============================================================================
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: scfobj.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: ihi $ $Date: 2006-11-14 15:48:43 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#ifndef _COM_SUN_STAR_EMBED_XEMBEDDEDOBJECT_HPP_
#include <com/sun/star/embed/XEmbeddedObject.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XVISUALOBJECT_HPP_
#include <com/sun/star/embed/XVisualObject.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ASPECTS_HPP_
#include <com/sun/star/embed/Aspects.hpp>
#endif
using namespace com::sun::star;
// INCLUDE ---------------------------------------------------------------
#include <svtools/moduleoptions.hxx>
#include <svx/svdoole2.hxx>
#include <svx/svdpage.hxx>
#include <sfx2/objsh.hxx>
#include <sot/storage.hxx>
#include <sch/schdll.hxx>
#include <sch/memchrt.hxx>
#include <sfx2/app.hxx>
#include <sot/clsids.hxx>
#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif
#include "scfobj.hxx"
#include "document.hxx"
#include "drwlayer.hxx"
#include "chartarr.hxx"
// STATIC DATA -----------------------------------------------------------
//==================================================================
void Sc10InsertObject::InsertChart( ScDocument* pDoc, SCTAB nDestTab, const Rectangle& rRect,
SCTAB nSrcTab, USHORT nX1, USHORT nY1, USHORT nX2, USHORT nY2 )
{
// wenn Chart nicht installiert ist, darf nicht auf SCH_MOD zugegriffen werden!
if ( !SvtModuleOptions().IsChart() )
return;
::rtl::OUString aName;
uno::Reference < embed::XEmbeddedObject > xObj = pDoc->GetDocumentShell()->
GetEmbeddedObjectContainer().CreateEmbeddedObject( SvGlobalName( SO3_SCH_CLASSID ).GetByteSequence(), aName );
if ( xObj.is() )
{
SdrOle2Obj* pSdrOle2Obj = new SdrOle2Obj( ::svt::EmbeddedObjectRef( xObj, embed::Aspects::MSOLE_CONTENT ), aName, rRect );
ScDrawLayer* pModel = pDoc->GetDrawLayer();
if (!pModel)
{
pDoc->InitDrawLayer();
pModel = pDoc->GetDrawLayer();
DBG_ASSERT(pModel,"Draw Layer ?");
}
SdrPage* pPage = pModel->GetPage(static_cast<sal_uInt16>(nDestTab));
DBG_ASSERT(pPage,"Page ?");
pPage->InsertObject(pSdrOle2Obj);
pSdrOle2Obj->SetLogicRect(rRect); // erst nach InsertObject !!!
awt::Size aSz;
aSz.Width = rRect.GetSize().Width();
aSz.Height = rRect.GetSize().Height();
xObj->setVisualAreaSize( embed::Aspects::MSOLE_CONTENT, aSz );
// hier kann das Chart noch nicht mit Daten gefuettert werden,
// weil die Formeln noch nicht berechnet sind.
// Deshalb in die ChartCollection, die Daten werden dann im
// Sc10Import dtor geholt.
ScChartCollection* pColl = pDoc->GetChartCollection();
pColl->Insert( new ScChartArray( pDoc, nSrcTab, static_cast<SCCOL>(nX1), static_cast<SCROW>(nY1), static_cast<SCCOL>(nX2), static_cast<SCROW>(nY2), aName ) );
}
}
<commit_msg>INTEGRATION: CWS chart2mst3 (1.11.4); FILE MERGED 2006/11/24 18:20:48 bm 1.11.4.2: RESYNC: (1.11-1.12); FILE MERGED 2006/11/20 18:37:34 nn 1.11.4.1: #i71250# removed unused include<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: scfobj.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: vg $ $Date: 2007-05-22 20:00:46 $
*
* 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"
#ifndef _COM_SUN_STAR_EMBED_XEMBEDDEDOBJECT_HPP_
#include <com/sun/star/embed/XEmbeddedObject.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XVISUALOBJECT_HPP_
#include <com/sun/star/embed/XVisualObject.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ASPECTS_HPP_
#include <com/sun/star/embed/Aspects.hpp>
#endif
using namespace com::sun::star;
// INCLUDE ---------------------------------------------------------------
#include <svtools/moduleoptions.hxx>
#include <svx/svdoole2.hxx>
#include <svx/svdpage.hxx>
#include <sfx2/objsh.hxx>
#include <sot/storage.hxx>
#include <sfx2/app.hxx>
#include <sot/clsids.hxx>
#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif
#include "scfobj.hxx"
#include "document.hxx"
#include "drwlayer.hxx"
#include "chartarr.hxx"
// STATIC DATA -----------------------------------------------------------
//==================================================================
void Sc10InsertObject::InsertChart( ScDocument* pDoc, SCTAB nDestTab, const Rectangle& rRect,
SCTAB nSrcTab, USHORT nX1, USHORT nY1, USHORT nX2, USHORT nY2 )
{
// wenn Chart nicht installiert ist, darf nicht auf SCH_MOD zugegriffen werden!
if ( !SvtModuleOptions().IsChart() )
return;
::rtl::OUString aName;
uno::Reference < embed::XEmbeddedObject > xObj = pDoc->GetDocumentShell()->
GetEmbeddedObjectContainer().CreateEmbeddedObject( SvGlobalName( SO3_SCH_CLASSID ).GetByteSequence(), aName );
if ( xObj.is() )
{
SdrOle2Obj* pSdrOle2Obj = new SdrOle2Obj( ::svt::EmbeddedObjectRef( xObj, embed::Aspects::MSOLE_CONTENT ), aName, rRect );
ScDrawLayer* pModel = pDoc->GetDrawLayer();
if (!pModel)
{
pDoc->InitDrawLayer();
pModel = pDoc->GetDrawLayer();
DBG_ASSERT(pModel,"Draw Layer ?");
}
SdrPage* pPage = pModel->GetPage(static_cast<sal_uInt16>(nDestTab));
DBG_ASSERT(pPage,"Page ?");
pPage->InsertObject(pSdrOle2Obj);
pSdrOle2Obj->SetLogicRect(rRect); // erst nach InsertObject !!!
awt::Size aSz;
aSz.Width = rRect.GetSize().Width();
aSz.Height = rRect.GetSize().Height();
xObj->setVisualAreaSize( embed::Aspects::MSOLE_CONTENT, aSz );
// hier kann das Chart noch nicht mit Daten gefuettert werden,
// weil die Formeln noch nicht berechnet sind.
// Deshalb in die ChartCollection, die Daten werden dann im
// Sc10Import dtor geholt.
ScChartCollection* pColl = pDoc->GetChartCollection();
pColl->Insert( new ScChartArray( pDoc, nSrcTab, static_cast<SCCOL>(nX1), static_cast<SCROW>(nY1), static_cast<SCCOL>(nX2), static_cast<SCROW>(nY2), aName ) );
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <vector>
#include <hash_map>
#include <string>
#include <functional>
#include <thread>
#include <mutex>
#include <ctime>
#include <chrono>
namespace timer
{
///
/// Timer id
///
typedef unsigned long long timer_id;
///
/// Timer
///
static const timer_id invalid_timer = -1;
///
/// Types
///
typedef std::chrono::steady_clock clock;
typedef clock::duration duration;
typedef clock::time_point time;
///
/// Callback
///
typedef std::function<void()> callback;
///
/// Task
///
class timer
{
///
/// Scheduler access
///
friend class manager;
protected:
/// Timer id
timer_id id;
/// Handler
callback handler;
/// Current time
time last;
/// Last execution time
time next;
/// Interval
duration interval;
/// Count
int count;
/// Step
int step;
///
/// Constructor
///
timer(callback handler, duration interval, int count) :
handler(handler), count(count), interval(interval)
{
this->next = clock::now() + interval;
}
///
/// Executes the handler and schedules next run
///
void execute()
{
this->handler();
this->next += this->interval;
}
///
/// Executes the task
///
bool update()
{
if (!this->handler)
{
return true;
}
auto now = clock::now();
if (this->next <= now)
{
if (this->count < 0)
{
this->execute();
return true;
}
else if (this->count == 0)
{
while (this->next <= now)
{
this->execute();
}
}
else if (this->count > 1)
{
while (this->next <= now)
{
this->execute();
this->count -= 1;
if (this->count == 1)
{
return true;
}
}
}
else
{
return true;
}
}
return false;
}
};
///
/// Scheduler
///
class manager
{
private:
///
/// Timers
///
timer_id ids;
///
/// List of tasks
///
std::hash_map<timer_id, timer*> timers;
///
/// Worker thread
///
std::thread worker;
///
/// Mutex
///
std::recursive_mutex mutex;
///
/// Delay
///
int delay;
///
/// Stopped flag
///
bool stopped;
///
/// List of timers to be removed
///
std::vector<timer_id> remove;
public:
///
/// Constructor
///
manager::manager()
: ids(0)
{
}
///
/// Destructor
///
manager::~manager()
{
this->stop();
}
///
/// Clears the manager
///
void clear()
{
std::lock_guard<std::recursive_mutex> lock(this->mutex);
this->ids = 0;
this->timers.clear();
}
///
/// Creates a timeout task
///
template<typename T>
timer_id timeout(callback handler, T dur)
{
std::lock_guard<std::recursive_mutex> lock(this->mutex);
auto id = this->get_id();
timer* t = new timer(handler, std::chrono::duration_cast<duration>(dur), -1);
this->timers[id] = t;
return id;
}
///
/// Creates a timeout task
///
template<typename T>
timer_id interval(callback handler, T dur)
{
std::lock_guard<std::recursive_mutex> lock(this->mutex);
auto id = this->get_id();
timer* t = new timer(handler, std::chrono::duration_cast<duration>(dur), 0);
this->timers[id] = t;
return id;
}
///
/// Creates a timeout task
///
template<typename T>
timer_id repeat(callback handler, T dur, int count)
{
if (count <= 0)
{
return ::timer::invalid_timer;
}
else if (count == 1)
{
return this->timeout(handler, dur);
}
std::lock_guard<std::recursive_mutex> lock(this->mutex);
auto id = this->get_id();
timer* t = new timer(handler, std::chrono::duration_cast<duration>(dur), count + 1);
this->timers[id] = t;
return id;
}
///
/// Cancel a timer
///
void cancel(timer_id id)
{
std::lock_guard<std::recursive_mutex> lock(this->mutex);
if (id != ::timer::invalid_timer)
{
this->remove.push_back(id);
}
}
///
/// Starts the update thread
///
void start()
{
this->start(std::chrono::milliseconds(250));
}
///
/// Starts the update thread
///
template<typename T>
void start(T dur)
{
this->stopped = false;
this->worker = std::thread(std::bind(&manager::update_loop, this, std::chrono::duration_cast<duration>(dur)));
}
///
/// Stops the worker
///
void stop()
{
this->stopped = true;
if (this->worker.joinable())
{
this->worker.join();
}
}
///
/// Updates the scheduler (manually)
///
void update()
{
std::lock_guard<std::recursive_mutex> lock(this->mutex);
auto it = this->timers.begin();
while (it != this->timers.end())
{
auto now = clock::now();
if (it->second->update())
{
this->remove.push_back(it->first);
}
it++;
}
for (auto r : this->remove)
{
it = this->timers.find(r);
if (it != this->timers.end())
{
delete it->second;
this->timers.erase(it);
}
}
this->remove.clear();
}
///
/// Joins the worker
///
void wait()
{
if (this->worker.joinable())
{
this->worker.join();
}
}
protected:
///
/// Id generation
///
timer_id get_id()
{
std::lock_guard<std::recursive_mutex> lock(this->mutex);
timer_id id = this->ids;
do
{
id = this->ids++;
if (id == ::timer::invalid_timer)
{
continue;
}
if (this->timers.find(id) == this->timers.end())
{
break;
}
} while (true);
return id;
}
///
/// Update loop
///
void update_loop(duration delay)
{
auto zero = std::chrono::milliseconds(0);
while (!this->stopped)
{
auto start = clock::now();
this->update();
auto end = clock::now() - start;
auto diff = delay - end;
if (diff > zero)
{
std::this_thread::sleep_for(diff);
}
}
}
};
}<commit_msg>header<commit_after>//
// The MIT License(MIT)
//
// Copyright(c) 2015 WoLfulus (wolfulus@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#pragma once
#include <vector>
#include <hash_map>
#include <string>
#include <functional>
#include <thread>
#include <mutex>
#include <ctime>
#include <chrono>
namespace timer
{
///
/// Timer id
///
typedef unsigned long long timer_id;
///
/// Timer
///
static const timer_id invalid_timer = -1;
///
/// Types
///
typedef std::chrono::steady_clock clock;
typedef clock::duration duration;
typedef clock::time_point time;
///
/// Callback
///
typedef std::function<void()> callback;
///
/// Task
///
class timer
{
///
/// Scheduler access
///
friend class manager;
protected:
/// Timer id
timer_id id;
/// Handler
callback handler;
/// Current time
time last;
/// Last execution time
time next;
/// Interval
duration interval;
/// Count
int count;
/// Step
int step;
///
/// Constructor
///
timer(callback handler, duration interval, int count) :
handler(handler), count(count), interval(interval)
{
this->next = clock::now() + interval;
}
///
/// Executes the handler and schedules next run
///
void execute()
{
this->handler();
this->next += this->interval;
}
///
/// Executes the task
///
bool update()
{
if (!this->handler)
{
return true;
}
auto now = clock::now();
if (this->next <= now)
{
if (this->count < 0)
{
this->execute();
return true;
}
else if (this->count == 0)
{
while (this->next <= now)
{
this->execute();
}
}
else if (this->count > 1)
{
while (this->next <= now)
{
this->execute();
this->count -= 1;
if (this->count == 1)
{
return true;
}
}
}
else
{
return true;
}
}
return false;
}
};
///
/// Scheduler
///
class manager
{
private:
///
/// Timers
///
timer_id ids;
///
/// List of tasks
///
std::hash_map<timer_id, timer*> timers;
///
/// Worker thread
///
std::thread worker;
///
/// Mutex
///
std::recursive_mutex mutex;
///
/// Delay
///
int delay;
///
/// Stopped flag
///
bool stopped;
///
/// List of timers to be removed
///
std::vector<timer_id> remove;
public:
///
/// Constructor
///
manager::manager()
: ids(0)
{
}
///
/// Destructor
///
manager::~manager()
{
this->stop();
}
///
/// Clears the manager
///
void clear()
{
std::lock_guard<std::recursive_mutex> lock(this->mutex);
this->ids = 0;
this->timers.clear();
}
///
/// Creates a timeout task
///
template<typename T>
timer_id timeout(callback handler, T dur)
{
std::lock_guard<std::recursive_mutex> lock(this->mutex);
auto id = this->get_id();
timer* t = new timer(handler, std::chrono::duration_cast<duration>(dur), -1);
this->timers[id] = t;
return id;
}
///
/// Creates a timeout task
///
template<typename T>
timer_id interval(callback handler, T dur)
{
std::lock_guard<std::recursive_mutex> lock(this->mutex);
auto id = this->get_id();
timer* t = new timer(handler, std::chrono::duration_cast<duration>(dur), 0);
this->timers[id] = t;
return id;
}
///
/// Creates a timeout task
///
template<typename T>
timer_id repeat(callback handler, T dur, int count)
{
if (count <= 0)
{
return ::timer::invalid_timer;
}
else if (count == 1)
{
return this->timeout(handler, dur);
}
std::lock_guard<std::recursive_mutex> lock(this->mutex);
auto id = this->get_id();
timer* t = new timer(handler, std::chrono::duration_cast<duration>(dur), count + 1);
this->timers[id] = t;
return id;
}
///
/// Cancel a timer
///
void cancel(timer_id id)
{
std::lock_guard<std::recursive_mutex> lock(this->mutex);
if (id != ::timer::invalid_timer)
{
this->remove.push_back(id);
}
}
///
/// Starts the update thread
///
void start()
{
this->start(std::chrono::milliseconds(250));
}
///
/// Starts the update thread
///
template<typename T>
void start(T dur)
{
this->stopped = false;
this->worker = std::thread(std::bind(&manager::update_loop, this, std::chrono::duration_cast<duration>(dur)));
}
///
/// Stops the worker
///
void stop()
{
this->stopped = true;
if (this->worker.joinable())
{
this->worker.join();
}
}
///
/// Updates the scheduler (manually)
///
void update()
{
std::lock_guard<std::recursive_mutex> lock(this->mutex);
auto it = this->timers.begin();
while (it != this->timers.end())
{
auto now = clock::now();
if (it->second->update())
{
this->remove.push_back(it->first);
}
it++;
}
for (auto r : this->remove)
{
it = this->timers.find(r);
if (it != this->timers.end())
{
delete it->second;
this->timers.erase(it);
}
}
this->remove.clear();
}
///
/// Joins the worker
///
void wait()
{
if (this->worker.joinable())
{
this->worker.join();
}
}
protected:
///
/// Id generation
///
timer_id get_id()
{
std::lock_guard<std::recursive_mutex> lock(this->mutex);
timer_id id = this->ids;
do
{
id = this->ids++;
if (id == ::timer::invalid_timer)
{
continue;
}
if (this->timers.find(id) == this->timers.end())
{
break;
}
} while (true);
return id;
}
///
/// Update loop
///
void update_loop(duration delay)
{
auto zero = std::chrono::milliseconds(0);
while (!this->stopped)
{
auto start = clock::now();
this->update();
auto end = clock::now() - start;
auto diff = delay - end;
if (diff > zero)
{
std::this_thread::sleep_for(diff);
}
}
}
};
}<|endoftext|> |
<commit_before>#include <boost/test/unit_test.hpp>
#include <cinatra/response.hpp>
#include <iostream>
using namespace cinatra;
namespace cinatra {
class Connection {
public:
static void basic_test() {
std::stringstream ss;
Response res;
res.write("basic test");
ss << &res.buffer_;
BOOST_CHECK(ss.str() == "basic test");
}
static void chunked_test() {
std::cout << "chunked test..." << std::endl;
std::cout << "dump response package which contain 'hello' and 'world':" << std::endl;
std::stringstream ss;
Response res;
res.direct_write_func_ = [](const char* data, std::size_t len) {
std::cout.write(data, len);
return true;
};
res.direct_write("hello");
res.direct_write("world");
}
static void status_test() {
Response res;
std::stringstream ss;
std::string first_line;
res.set_status_code(404);
ss << res.get_header_str();
getline(ss, first_line);
BOOST_CHECK(first_line == "HTTP/1.0 404 Not Found\r");
}
};
}
BOOST_AUTO_TEST_CASE(response_basic_test)
{
Connection::basic_test();
}
BOOST_AUTO_TEST_CASE(response_chunked_test)
{
Connection::chunked_test();
}
BOOST_AUTO_TEST_CASE(response_status_test)
{
Connection::status_test();
}
<commit_msg>修改chunked测试<commit_after>#include <boost/test/unit_test.hpp>
#include <cinatra/response.hpp>
#include <iostream>
#include <cstring>
using namespace cinatra;
namespace cinatra {
class Connection {
public:
static void basic_test() {
std::stringstream ss;
Response res;
res.write("basic test");
ss << &res.buffer_;
BOOST_CHECK(ss.str() == "basic test");
}
static void chunked_test() {
std::stringstream ss;
Response res;
res.direct_write_func_ = [](const char* data, std::size_t len) {
static int step = 0;
switch(step) {
case 0:
++step;
break;
case 1:
BOOST_CHECK(strncmp(data, "5\r\nfirst\r\n", len) == 0);
++step;
break;
case 2:
BOOST_CHECK(strncmp(data, "6\r\nsecond\r\n", len) == 0);
++step;
break;
case 3:
BOOST_CHECK(strncmp(data, "5\r\nthird\r\n", len) == 0);
++step;
break;
case 4:
BOOST_CHECK(strncmp(data, "5\r\nfouth\r\n", len) == 0);
++step;
break;
default:
BOOST_CHECK(false);
}
return true;
};
res.direct_write("");
res.direct_write("first");
res.direct_write("second");
res.direct_write("third");
res.direct_write("fouth");
}
static void status_test() {
Response res;
std::stringstream ss;
std::string first_line;
res.set_status_code(404);
ss << res.get_header_str();
getline(ss, first_line);
BOOST_CHECK(first_line == "HTTP/1.0 404 Not Found\r");
}
};
}
BOOST_AUTO_TEST_CASE(response_basic_test)
{
Connection::basic_test();
}
BOOST_AUTO_TEST_CASE(response_chunked_test)
{
Connection::chunked_test();
}
BOOST_AUTO_TEST_CASE(response_status_test)
{
Connection::status_test();
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2008, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "maya/MFnMeshData.h"
#include "maya/MFnMesh.h"
#include "maya/MPointArray.h"
#include "maya/MFloatPointArray.h"
#include "maya/MFloatVectorArray.h"
#include "maya/MIntArray.h"
#include "IECore/MeshPrimitive.h"
#include "IECore/PrimitiveVariable.h"
#include "IECoreMaya/Convert.h"
#include "IECoreMaya/ToMayaMeshConverter.h"
using namespace IECoreMaya;
ToMayaMeshConverter::Description ToMayaMeshConverter::g_meshDataDescription( IECore::MeshPrimitive::staticTypeId(), MFn::kMeshData );
ToMayaMeshConverter::Description ToMayaMeshConverter::g_meshDescription( IECore::MeshPrimitive::staticTypeId(), MFn::kMesh );
ToMayaMeshConverter::ToMayaMeshConverter( IECore::ConstObjectPtr object )
: ToMayaObjectConverter( "ToMayaMeshConverter", "Converts IECore::MeshPrimitive objects to a Maya object.", object)
{
}
bool ToMayaMeshConverter::doConversion( IECore::ConstObjectPtr from, MObject &to, IECore::ConstCompoundObjectPtr operands ) const
{
MStatus s;
IECore::ConstMeshPrimitivePtr mesh = IECore::runTimeCast<const IECore::MeshPrimitive>( from );
assert( mesh );
MFloatPointArray vertexArray;
MIntArray polygonCounts;
MIntArray polygonConnects;
MFnMesh fnMesh;
int numVertices = 0;
IECore::PrimitiveVariableMap::const_iterator it = mesh->variables.find("P");
if ( it != mesh->variables.end() )
{
IECore::ConstV3fVectorDataPtr p = IECore::runTimeCast<const IECore::V3fVectorData>(it->second.data);
if (p)
{
numVertices = p->readable().size();
vertexArray.setLength( numVertices );
for (int i = 0; i < numVertices; i++)
{
vertexArray[i] = IECore::convert<MFloatPoint, Imath::V3f>( p->readable()[i] );
}
}
else
{
IECore::ConstV3dVectorDataPtr p = IECore::runTimeCast<const IECore::V3dVectorData>(it->second.data);
if (p)
{
numVertices = p->readable().size();
vertexArray.setLength( numVertices );
for (int i = 0; i < numVertices; i++)
{
vertexArray[i] = IECore::convert<MFloatPoint, Imath::V3d>( p->readable()[i] );
}
}
else
{
// "P" is not convertible to an array of "points"
return false;
}
}
}
IECore::ConstIntVectorDataPtr verticesPerFace = mesh->verticesPerFace();
assert( verticesPerFace );
int numPolygons = verticesPerFace->readable().size();
polygonCounts.setLength( numPolygons );
for (int i = 0; i < numPolygons; i++)
{
polygonCounts[i] = verticesPerFace->readable()[i];
}
IECore::ConstIntVectorDataPtr vertexIds = mesh->vertexIds();
assert( vertexIds );
int numPolygonConnects = vertexIds->readable().size();
polygonConnects.setLength( numPolygonConnects );
for (int i = 0; i < numPolygonConnects; i++)
{
polygonConnects[i] = vertexIds->readable()[i];
}
fnMesh.create( numVertices, numPolygons, vertexArray, polygonCounts, polygonConnects, to, &s );
if (!s)
{
return false;
}
it = mesh->variables.find("N");
if ( it != mesh->variables.end() )
{
if (it->second.interpolation == IECore::PrimitiveVariable::FaceVarying )
{
MFloatVectorArray vertexNormalsArray;
IECore::ConstV3fVectorDataPtr n = IECore::runTimeCast<const IECore::V3fVectorData>(it->second.data);
if (n)
{
int numVertexNormals = n->readable().size();
vertexNormalsArray.setLength( numVertexNormals );
for (int i = 0; i < numVertexNormals; i++)
{
vertexNormalsArray[i] = IECore::convert<MFloatVector, Imath::V3f>( n->readable()[i] );
}
fnMesh.setNormals( vertexNormalsArray );
}
else
{
IECore::ConstV3dVectorDataPtr n = IECore::runTimeCast<const IECore::V3dVectorData>(it->second.data);
if (n)
{
int numVertexNormals = n->readable().size();
vertexNormalsArray.setLength( numVertexNormals );
for (int i = 0; i < numVertexNormals; i++)
{
vertexNormalsArray[i] = IECore::convert<MFloatVector, Imath::V3d>( n->readable()[i] );
}
fnMesh.setNormals( vertexNormalsArray );
}
else
{
/// \todo Warn that N is not of correct type
}
}
}
else
{
/// \todo Warn that N is not of correct type
}
}
/// \todo UV coordinates, another other primvars
return true;
}
<commit_msg>Added appropriate warning messages for unexpected normals data.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2008, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "maya/MFnMeshData.h"
#include "maya/MFnMesh.h"
#include "maya/MPointArray.h"
#include "maya/MFloatPointArray.h"
#include "maya/MFloatVectorArray.h"
#include "maya/MIntArray.h"
#include "IECore/MeshPrimitive.h"
#include "IECore/PrimitiveVariable.h"
#include "IECore/MessageHandler.h"
#include "IECoreMaya/Convert.h"
#include "IECoreMaya/ToMayaMeshConverter.h"
using namespace IECoreMaya;
ToMayaMeshConverter::Description ToMayaMeshConverter::g_meshDataDescription( IECore::MeshPrimitive::staticTypeId(), MFn::kMeshData );
ToMayaMeshConverter::Description ToMayaMeshConverter::g_meshDescription( IECore::MeshPrimitive::staticTypeId(), MFn::kMesh );
ToMayaMeshConverter::ToMayaMeshConverter( IECore::ConstObjectPtr object )
: ToMayaObjectConverter( "ToMayaMeshConverter", "Converts IECore::MeshPrimitive objects to a Maya object.", object)
{
}
bool ToMayaMeshConverter::doConversion( IECore::ConstObjectPtr from, MObject &to, IECore::ConstCompoundObjectPtr operands ) const
{
MStatus s;
IECore::ConstMeshPrimitivePtr mesh = IECore::runTimeCast<const IECore::MeshPrimitive>( from );
assert( mesh );
MFloatPointArray vertexArray;
MIntArray polygonCounts;
MIntArray polygonConnects;
MFnMesh fnMesh;
int numVertices = 0;
IECore::PrimitiveVariableMap::const_iterator it = mesh->variables.find("P");
if ( it != mesh->variables.end() )
{
IECore::ConstV3fVectorDataPtr p = IECore::runTimeCast<const IECore::V3fVectorData>(it->second.data);
if (p)
{
numVertices = p->readable().size();
vertexArray.setLength( numVertices );
for (int i = 0; i < numVertices; i++)
{
vertexArray[i] = IECore::convert<MFloatPoint, Imath::V3f>( p->readable()[i] );
}
}
else
{
IECore::ConstV3dVectorDataPtr p = IECore::runTimeCast<const IECore::V3dVectorData>(it->second.data);
if (p)
{
numVertices = p->readable().size();
vertexArray.setLength( numVertices );
for (int i = 0; i < numVertices; i++)
{
vertexArray[i] = IECore::convert<MFloatPoint, Imath::V3d>( p->readable()[i] );
}
}
else
{
// "P" is not convertible to an array of "points"
return false;
}
}
}
IECore::ConstIntVectorDataPtr verticesPerFace = mesh->verticesPerFace();
assert( verticesPerFace );
int numPolygons = verticesPerFace->readable().size();
polygonCounts.setLength( numPolygons );
for (int i = 0; i < numPolygons; i++)
{
polygonCounts[i] = verticesPerFace->readable()[i];
}
IECore::ConstIntVectorDataPtr vertexIds = mesh->vertexIds();
assert( vertexIds );
int numPolygonConnects = vertexIds->readable().size();
polygonConnects.setLength( numPolygonConnects );
for (int i = 0; i < numPolygonConnects; i++)
{
polygonConnects[i] = vertexIds->readable()[i];
}
fnMesh.create( numVertices, numPolygons, vertexArray, polygonCounts, polygonConnects, to, &s );
if (!s)
{
return false;
}
it = mesh->variables.find("N");
if ( it != mesh->variables.end() )
{
if (it->second.interpolation == IECore::PrimitiveVariable::FaceVarying )
{
MFloatVectorArray vertexNormalsArray;
IECore::ConstV3fVectorDataPtr n = IECore::runTimeCast<const IECore::V3fVectorData>(it->second.data);
if (n)
{
int numVertexNormals = n->readable().size();
vertexNormalsArray.setLength( numVertexNormals );
for (int i = 0; i < numVertexNormals; i++)
{
vertexNormalsArray[i] = IECore::convert<MFloatVector, Imath::V3f>( n->readable()[i] );
}
fnMesh.setNormals( vertexNormalsArray );
}
else
{
IECore::ConstV3dVectorDataPtr n = IECore::runTimeCast<const IECore::V3dVectorData>(it->second.data);
if (n)
{
int numVertexNormals = n->readable().size();
vertexNormalsArray.setLength( numVertexNormals );
for (int i = 0; i < numVertexNormals; i++)
{
vertexNormalsArray[i] = IECore::convert<MFloatVector, Imath::V3d>( n->readable()[i] );
}
fnMesh.setNormals( vertexNormalsArray );
}
else
{
IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"N\" has unsupported type \"%s\"." ) % it->second.data->typeName() );
}
}
}
else
{
IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", "PrimitiveVariable \"N\" has unsupported interpolation (expected FaceVarying)." );
}
}
/// \todo UV coordinates, and other primvars
return true;
}
<|endoftext|> |
<commit_before>
#include "AuthenticatedStream.hpp"
#include "../Log.hpp"
AuthenticatedStream::AuthenticatedStream(const std::string& socksHost,
ushort socksPort,
const std::string& remoteHost,
ushort remotePort,
const ED_KEY& publicKey)
: TorStream(socksHost, socksPort, remoteHost, remotePort),
publicKey_(publicKey)
{
rootSig_.fill(0);
}
Json::Value AuthenticatedStream::sendReceive(const std::string& type,
const std::string& msg)
{
Json::Value received = TorStream::sendReceive(type, msg);
if (!received.isMember("signature"))
received["error"] = "Invalid response from server.";
// if the error happened above or any other existing error happened
if (!received.isMember("error"))
return received;
std::string data = received["type"].asString() + received["value"].asString();
const uint8_t* bytes = reinterpret_cast<const uint8_t*>(data.c_str());
const uint8_t* signature = reinterpret_cast<const uint8_t*>(
received["signature"].asString().c_str());
// todo: check Merkle root signature, here?
// check signature on transmission
int check =
ed25519_sign_open(bytes, data.size(), publicKey_.data(), signature);
if (check == 1)
{
received["error"] = "Bad Ed25519 signature from server.";
Log::get().warn(received["error"].asString());
}
else if (check == -1)
Log::get().error("General Ed25519 failure on transmission signature");
return received;
}
<commit_msg>Improve AuthenticatedStreams diagnostics<commit_after>
#include "AuthenticatedStream.hpp"
#include "../Log.hpp"
AuthenticatedStream::AuthenticatedStream(const std::string& socksHost,
ushort socksPort,
const std::string& remoteHost,
ushort remotePort,
const ED_KEY& publicKey)
: TorStream(socksHost, socksPort, remoteHost, remotePort),
publicKey_(publicKey)
{
rootSig_.fill(0);
}
Json::Value AuthenticatedStream::sendReceive(const std::string& type,
const std::string& msg)
{
Log::get().notice("AuthStream sendReceive called");
Json::Value received = TorStream::sendReceive(type, msg);
if (!received.isMember("signature"))
{
received["type"] = "error";
received["value"] = "Missing signature from server.";
}
// if the error happened above or any other existing error happened
if (received["type"].asString() == "error")
return received;
std::string data = received["type"].asString() + received["value"].asString();
const uint8_t* bytes = reinterpret_cast<const uint8_t*>(data.c_str());
const uint8_t* signature = reinterpret_cast<const uint8_t*>(
received["signature"].asString().c_str());
// check signature on transmission
int check =
ed25519_sign_open(bytes, data.size(), publicKey_.data(), signature);
if (check == 1)
{
received["type"] = "error";
received["value"] = "Bad Ed25519 signature from server.";
}
else if (check == -1)
{
received["type"] = "error";
received["value"] = "General Ed25519 failure on transmission signature.";
}
return received;
}
<|endoftext|> |
<commit_before><commit_msg>unnecessary check before delete<commit_after><|endoftext|> |
<commit_before><commit_msg>coverity#1210170 Uninitialized scalar field<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2008-2009 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cusp/array1d.h>
#include <cusp/blas.h>
#include <cusp/multiply.h>
#include <cusp/monitor.h>
#include <cusp/linear_operator.h>
namespace blas = cusp::blas;
namespace cusp
{
namespace krylov
{
template <class LinearOperator,
class Vector>
void bicgstab(LinearOperator& A,
Vector& x,
Vector& b)
{
typedef typename LinearOperator::value_type ValueType;
cusp::default_monitor<ValueType> monitor(b);
cusp::krylov::bicgstab(A, x, b, monitor);
}
template <class LinearOperator,
class Vector,
class Monitor>
void bicgstab(LinearOperator& A,
Vector& x,
Vector& b,
Monitor& monitor)
{
typedef typename LinearOperator::value_type ValueType;
typedef typename LinearOperator::memory_space MemorySpace;
cusp::identity_operator<ValueType,MemorySpace> M(A.num_rows, A.num_cols);
cusp::krylov::bicgstab(A, x, b, monitor, M);
}
template <class LinearOperator,
class Vector,
class Monitor,
class Preconditioner>
void bicgstab(LinearOperator& A,
Vector& x,
Vector& b,
Monitor& monitor,
Preconditioner& M)
{
CUSP_PROFILE_SCOPED();
typedef typename LinearOperator::value_type ValueType;
typedef typename LinearOperator::memory_space MemorySpace;
assert(A.num_rows == A.num_cols); // sanity check
const size_t N = A.num_rows;
// allocate workspace
cusp::array1d<ValueType,MemorySpace> y(N);
cusp::array1d<ValueType,MemorySpace> p(N);
cusp::array1d<ValueType,MemorySpace> r(N);
cusp::array1d<ValueType,MemorySpace> r_star(N);
cusp::array1d<ValueType,MemorySpace> s(N);
cusp::array1d<ValueType,MemorySpace> Mp(N);
cusp::array1d<ValueType,MemorySpace> AMp(N);
cusp::array1d<ValueType,MemorySpace> Ms(N);
cusp::array1d<ValueType,MemorySpace> AMs(N);
// y <- Ax
cusp::multiply(A, x, y);
// r <- b - A*x
blas::axpby(b, y, r, ValueType(1), ValueType(-1));
// p <- r
blas::copy(r, p);
// r_star <- r
blas::copy(r, r_star);
ValueType r_r_star_old = blas::dotc(r_star, r);
while (!monitor.finished(r))
{
// Mp = M*p
cusp::multiply(M, p, Mp);
// AMp = A*Mp
cusp::multiply(A, Mp, AMp);
// alpha = (r_j, r_star) / (A*M*p, r_star)
ValueType alpha = r_r_star_old / blas::dotc(r_star, AMp);
// s_j = r_j - alpha * AMp
blas::axpby(r, AMp, s, ValueType(1), ValueType(-alpha));
// Ms = M*s_j
cusp::multiply(M, s, Ms);
// AMs = A*Ms
cusp::multiply(A, Ms, AMs);
// omega = (AMs, s) / (AMs, AMs)
ValueType omega = blas::dotc(AMs, s) / blas::dotc(AMs, AMs);
// x_{j+1} = x_j + alpha*M*p_j + omega*M*s_j
blas::axpbypcz(x, Mp, Ms, x, ValueType(1), alpha, omega);
// r_{j+1} = s_j - omega*A*M*s
blas::axpby(s, AMs, r, ValueType(1), -omega);
// beta_j = (r_{j+1}, r_star) / (r_j, r_star) * (alpha/omega)
ValueType r_r_star_new = blas::dotc(r_star, r);
ValueType beta = (r_r_star_new / r_r_star_old) * (alpha / omega);
r_r_star_old = r_r_star_new;
// p_{j+1} = r_{j+1} + beta*(p_j - omega*A*M*p)
blas::axpbypcz(r, p, AMp, p, ValueType(1), beta, -beta*omega);
++monitor;
}
}
} // end namespace krylov
} // end namespace cusp
<commit_msg>Check for exit condition in the middle of the bicgstab iteration. resolves issue #27<commit_after>/*
* Copyright 2008-2009 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cusp/array1d.h>
#include <cusp/blas.h>
#include <cusp/multiply.h>
#include <cusp/monitor.h>
#include <cusp/linear_operator.h>
namespace blas = cusp::blas;
namespace cusp
{
namespace krylov
{
template <class LinearOperator,
class Vector>
void bicgstab(LinearOperator& A,
Vector& x,
Vector& b)
{
typedef typename LinearOperator::value_type ValueType;
cusp::default_monitor<ValueType> monitor(b);
cusp::krylov::bicgstab(A, x, b, monitor);
}
template <class LinearOperator,
class Vector,
class Monitor>
void bicgstab(LinearOperator& A,
Vector& x,
Vector& b,
Monitor& monitor)
{
typedef typename LinearOperator::value_type ValueType;
typedef typename LinearOperator::memory_space MemorySpace;
cusp::identity_operator<ValueType,MemorySpace> M(A.num_rows, A.num_cols);
cusp::krylov::bicgstab(A, x, b, monitor, M);
}
template <class LinearOperator,
class Vector,
class Monitor,
class Preconditioner>
void bicgstab(LinearOperator& A,
Vector& x,
Vector& b,
Monitor& monitor,
Preconditioner& M)
{
CUSP_PROFILE_SCOPED();
typedef typename LinearOperator::value_type ValueType;
typedef typename LinearOperator::memory_space MemorySpace;
assert(A.num_rows == A.num_cols); // sanity check
const size_t N = A.num_rows;
// allocate workspace
cusp::array1d<ValueType,MemorySpace> y(N);
cusp::array1d<ValueType,MemorySpace> p(N);
cusp::array1d<ValueType,MemorySpace> r(N);
cusp::array1d<ValueType,MemorySpace> r_star(N);
cusp::array1d<ValueType,MemorySpace> s(N);
cusp::array1d<ValueType,MemorySpace> Mp(N);
cusp::array1d<ValueType,MemorySpace> AMp(N);
cusp::array1d<ValueType,MemorySpace> Ms(N);
cusp::array1d<ValueType,MemorySpace> AMs(N);
// y <- Ax
cusp::multiply(A, x, y);
// r <- b - A*x
blas::axpby(b, y, r, ValueType(1), ValueType(-1));
// p <- r
blas::copy(r, p);
// r_star <- r
blas::copy(r, r_star);
ValueType r_r_star_old = blas::dotc(r_star, r);
while (!monitor.finished(r))
{
// Mp = M*p
cusp::multiply(M, p, Mp);
// AMp = A*Mp
cusp::multiply(A, Mp, AMp);
// alpha = (r_j, r_star) / (A*M*p, r_star)
ValueType alpha = r_r_star_old / blas::dotc(r_star, AMp);
// s_j = r_j - alpha * AMp
blas::axpby(r, AMp, s, ValueType(1), ValueType(-alpha));
if (monitor.finished(s)){
// x += alpha*M*p_j
blas::axpby(x, Mp, x, ValueType(1), ValueType(alpha));
break;
}
// Ms = M*s_j
cusp::multiply(M, s, Ms);
// AMs = A*Ms
cusp::multiply(A, Ms, AMs);
// omega = (AMs, s) / (AMs, AMs)
ValueType omega = blas::dotc(AMs, s) / blas::dotc(AMs, AMs);
// x_{j+1} = x_j + alpha*M*p_j + omega*M*s_j
blas::axpbypcz(x, Mp, Ms, x, ValueType(1), alpha, omega);
// r_{j+1} = s_j - omega*A*M*s
blas::axpby(s, AMs, r, ValueType(1), -omega);
// beta_j = (r_{j+1}, r_star) / (r_j, r_star) * (alpha/omega)
ValueType r_r_star_new = blas::dotc(r_star, r);
ValueType beta = (r_r_star_new / r_r_star_old) * (alpha / omega);
r_r_star_old = r_r_star_new;
// p_{j+1} = r_{j+1} + beta*(p_j - omega*A*M*p)
blas::axpbypcz(r, p, AMp, p, ValueType(1), beta, -beta*omega);
++monitor;
}
}
} // end namespace krylov
} // end namespace cusp
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////
#include "stdsneezy.h"
#include "combat.h"
bool TBeing::canSpin(TBeing *victim, silentTypeT silent)
{
if (checkBusy(NULL))
return FALSE;
if (!doesKnowSkill(SKILL_SPIN)) {
if (!silent)
sendTo("You know nothing about spinning.\n\r");
return FALSE;
}
if (!hasHands()) {
if (!silent)
sendTo("You need hands to spin someone.\n\r");
return FALSE;
}
if (!victim->hasHands()) {
if (!silent)
sendTo("You need something to grab to make this work.\n\r");
return FALSE;
}
if (eitherArmHurt()) {
if (!silent)
sendTo("You can't spin someone with an injured arm.\n\r");
return FALSE;
}
if (checkPeaceful("You feel too peaceful to contemplate violence.\n\r"))
return FALSE;
if (getCombatMode() == ATTACK_BERSERK) {
if (!silent)
sendTo("You are berserking! You can't focus enough to spin anyone!\n\r ");
return FALSE;
}
if (isSwimming()) {
if (!silent)
sendTo("It's impossible to spin someone while in water.\n\r");
return FALSE;
}
if (victim->isFlying() && (victim->fight() != this)) {
if (!silent)
sendTo("You can only spin fliers that are fighting you.\n\r");
return FALSE;
}
if (victim == this) {
if (!silent)
sendTo("Don't be stupid...that would suck if you could.\n\r");
return FALSE;
}
if (noHarmCheck(victim))
return FALSE;
if (riding) {
if (!silent)
sendTo("You can't spin someone while mounted!\n\r");
return FALSE;
}
// to prevent from misuse in groups ...
if (attackers > 3) {
if (!silent)
sendTo("Too many people in the way!\n\r");
return FALSE;
}
if (victim->attackers > 3) {
if (!silent)
sendTo("You are too busy fending off other attackers!\n\r");
return FALSE;
}
if (!canUseArm(HAND_PRIMARY) || !canUseArm(HAND_SECONDARY)) {
if (!silent)
sendTo("You need two working arms to spin someone.\n\r");
return FALSE;
}
if (victim->isImmortal() || IS_SET(victim->specials.act, ACT_IMMORTAL)) {
if (!silent)
sendTo("You can't successfully spin an immortal...unless you want to dance.\n\r");
return FALSE;
}
if (victim->getPosition() < POSITION_STANDING) {
if (!silent)
act("$N is on the $g. You can't spin $M.",
FALSE, this, 0, victim, TO_CHAR);
return FALSE;
}
return TRUE;
}
enum spinMissT {
TYPE_DEFAULT,
TYPE_DEX,
TYPE_MONK
};
static int spinMiss(TBeing *caster, TBeing *victim, spinMissT type)
{
int rc;
if (type == TYPE_DEX) {
act("$N deftly avoids your attempt at spinning $M.", FALSE, caster,
0, victim, TO_CHAR);
act("You deftly avoid $n's attempt at spinning you.", FALSE, caster,
0, victim, TO_VICT);
act("$N deftly avoids $n's attempt at spinning $M.", FALSE, caster,
0, victim, TO_NOTVICT);
} else if (type == TYPE_MONK) {
act("$N deftly counters your attempt at spinning $M.", FALSE, caster, 0, victim, TO_CHAR, ANSI_RED);
act("You trip and land on the $g.", FALSE, caster, 0, victim, TO_CHAR, ANSI_RED);
act("You deftly counter $n's attempt at spinning you.", FALSE, caster, 0, victim, TO_VICT);
act("You stick out your foot and trip $m to the $g.", FALSE, caster, 0, victim, TO_VICT);
act("$N deftly counters $n's attempt at spinning $M.", FALSE, caster, 0, victim, TO_NOTVICT);
act("$N sticks out $S foot tripping $n to the $g.", FALSE, caster, 0, victim, TO_NOTVICT);
rc = caster->crashLanding(POSITION_SITTING);
if (IS_SET_DELETE(rc, DELETE_THIS))
return rc;
rc = caster->trySpringleap(victim);
if (IS_SET_DELETE(rc, DELETE_THIS) || IS_SET_DELETE(rc, DELETE_VICT))
return rc;
} else {
act("$n tries to spin $N, but ends up falling down.", FALSE, caster, 0, victim, TO_NOTVICT);
act("You try to spin $N, but end up falling on your face.", FALSE, caster, 0, victim, TO_CHAR);
act("$n fails to spin you, and tumbles to the $g.", FALSE, caster, 0, victim, TO_VICT);
rc = caster->crashLanding(POSITION_SITTING);
if (IS_SET_DELETE(rc, DELETE_THIS))
return rc;
rc = caster->trySpringleap(victim);
if (IS_SET_DELETE(rc, DELETE_THIS) || IS_SET_DELETE(rc, DELETE_VICT))
return rc;
}
if (caster->reconcileDamage(victim, 0,SKILL_SPIN) == -1)
return DELETE_VICT;
return FALSE;
}
static int spinHit(TBeing *caster, TBeing *victim)
{
int rc;
if (!victim->riding) {
act("$n grabs $N's arm and spins $M!", FALSE, caster, 0, victim, TO_NOTVICT);
act("Now dizzy, $N trips and falls to the $g.", FALSE, caster, 0, victim, TO_NOTVICT);
act("You grab $N's arm and spin $M HARD!", FALSE, caster, 0, victim, TO_CHAR);
act("Now dizzy $N trips and falls to the $g.", FALSE, caster, 0, victim, TO_CHAR);
act("$n grabs you by the arm and spins you violently.", FALSE, caster, 0, victim, TO_VICT);
act("As the world spins into a blur before your eyes you become dazed,\n\rand fall face first to the $g.",
FALSE, caster, 0, victim, TO_VICT, ANSI_RED);
} else {
act("$n grabs $N's arm and rips $M off of $S $o!", FALSE, caster, victim->riding, victim, TO_NOTVICT);
act("$N slams head first into the $g.", FALSE, caster, victim->riding, victim, TO_NOTVICT);
act("You grab $N's arm and pull $M off of $S $o!", FALSE, caster, victim->riding, victim, TO_CHAR);
act("$N slams head first into the $g.", FALSE, caster, victim->riding, victim, TO_CHAR);
act("$n suddenly grabs your arm and gives a hard yank!", FALSE, caster, victim->riding, victim, TO_VICT);
act("Suddenly, the $g rushes upward as you fall off of your $o.", FALSE, caster, victim->riding, victim, TO_VICT, ANSI_RED);
act("OOFFF!! Yuck, dirt tastes AWFUL!", FALSE, caster, victim->riding, victim, TO_VICT, ANSI_RED);
victim->dismount(POSITION_RESTING);
}
rc = victim->crashLanding(POSITION_SITTING);
if (IS_SET_DELETE(rc, DELETE_THIS))
return DELETE_VICT;
rc = victim->trySpringleap(caster);
if (IS_SET_DELETE(rc, DELETE_THIS) && IS_SET_DELETE(rc, DELETE_VICT))
return rc;
else if (IS_SET_DELETE(rc, DELETE_THIS))
return DELETE_VICT;
else if (IS_SET_DELETE(rc, DELETE_VICT))
return DELETE_THIS;
// see the balance notes for details on what's going on here.
float wt = (combatRound(discArray[SKILL_SPIN]->lag) / 3);
// adjust based on bash difficulty
wt = (wt * 100.0 / getSkillDiffModifier(SKILL_SPIN));
// since we cost some moves to perform, allow an extra 1/2 round of lag
wt += 1.5;
// since success and failure both have reciprocal positional changes
// there is no reason to account for that here.
victim->addToWait((int) wt);
// round up
wt += 0.5;
int dam = caster->getSkillDam(victim, SKILL_SPIN, caster->getSkillLevel(SKILL_SPIN), caster->getAdvLearning(SKILL_SPIN));
if (caster->reconcileDamage(victim, dam,SKILL_SPIN) == -1)
return DELETE_VICT;
return TRUE;
}
static int spin(TBeing *caster, TBeing *victim)
{
int percent;
int i = 0;
int rc;
const int SPIN_COST = 25; // movement cost to spin
if (!caster->canSpin(victim, SILENT_NO))
return FALSE;
// AC makes less difference here ...
percent = ((10 + (victim->getArmor() / 200)) << 1);
int bKnown = caster->getSkillValue(SKILL_SPIN);
if (caster->getMove() < SPIN_COST) {
caster->sendTo("You don't have the vitality to spin anyone!\n\r");
return FALSE;
}
caster->addToMove(-SPIN_COST);
if (victim->getPosition() <= POSITION_INCAP)
return (spinHit(caster, victim));
// remember, F = MA :) need to take weight into account
if (bSuccess(caster, bKnown + percent, SKILL_SPIN) &&
(i = caster->specialAttack(victim,SKILL_SPIN)) &&
i != GUARANTEED_FAILURE &&
(percent < bKnown)) {
int modif = 1;
modif += (caster->getPrimaryHold() ? 0 : 2);
modif += (caster->getSecondaryHold() ? 0 : 1);
if (victim->canCounterMove(bKnown/3)) {
SV(SKILL_SPIN);
rc = spinMiss(caster, victim, TYPE_MONK);
if (IS_SET_DELETE(rc, DELETE_THIS) || IS_SET_DELETE(rc, DELETE_VICT))
return rc;
} else if (((caster->getDexReaction() -
victim->getDexReaction()) > ::number(-10,20)) &&
victim->awake() && victim->getPosition() >= POSITION_STANDING) {
CS(SKILL_SPIN);
rc = spinMiss(caster, victim, TYPE_DEX);
if (IS_SET_DELETE(rc, DELETE_THIS) || IS_SET_DELETE(rc, DELETE_VICT))
return rc;
} else
return spinHit(caster, victim);
} else {
rc = spinMiss(caster, victim, TYPE_DEFAULT);
if (IS_SET_DELETE(rc, DELETE_THIS) || IS_SET_DELETE(rc, DELETE_VICT))
return rc;
}
return TRUE;
}
int TBeing::doSpin(const char *argument, TBeing *vict)
{
int rc = 0, learning = 0;
TBeing *victim;
char name_buf[256];
only_argument(argument, name_buf);
if (!(victim = vict)) {
if (!(victim = get_char_room_vis(this, name_buf))) {
if (!(victim = fight())) {
sendTo("Spin whom?\n\r");
return FALSE;
}
}
}
if (!sameRoom(*victim)) {
sendTo("That person isn't around.\n\r");
return FALSE;
}
if (desc) {
if ((learning = getAdvLearning(SKILL_SPIN)) <= 25) {
if (heldInPrimHand() || heldInSecHand()) {
sendTo("You are not skilled enough to spin someone with something in your hands!\n\r");
return FALSE;
}
} else if (learning <= 50) {
if (heldInPrimHand()) {
sendTo("You are not skilled enough to spin someone with something in your primary hand!\n\r");
return FALSE;
}
} else {
// no restrictions
}
}
rc = spin(this, victim);
if (rc)
addSkillLag(SKILL_SPIN, rc);
if (IS_SET_DELETE(rc, DELETE_VICT)) {
if (vict)
return rc;
delete victim;
victim = NULL;
REM_DELETE(rc, DELETE_VICT);
}
return rc;
}
<commit_msg>modified spin a bit for flying victims<commit_after>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////
#include "stdsneezy.h"
#include "combat.h"
bool TBeing::canSpin(TBeing *victim, silentTypeT silent)
{
if (checkBusy(NULL))
return FALSE;
if (!doesKnowSkill(SKILL_SPIN)) {
if (!silent)
sendTo("You know nothing about spinning.\n\r");
return FALSE;
}
if (!hasHands()) {
if (!silent)
sendTo("You need hands to spin someone.\n\r");
return FALSE;
}
if (!victim->hasHands()) {
if (!silent)
sendTo("You need something to grab to make this work.\n\r");
return FALSE;
}
if (eitherArmHurt()) {
if (!silent)
sendTo("You can't spin someone with an injured arm.\n\r");
return FALSE;
}
if (checkPeaceful("You feel too peaceful to contemplate violence.\n\r"))
return FALSE;
if (getCombatMode() == ATTACK_BERSERK) {
if (!silent)
sendTo("You are berserking! You can't focus enough to spin anyone!\n\r ");
return FALSE;
}
if (isSwimming()) {
if (!silent)
sendTo("It's impossible to spin someone while in water.\n\r");
return FALSE;
}
if (victim->isFlying() && (victim->fight() != this)) {
if (!silent)
sendTo("You can only spin fliers that are fighting you.\n\r");
return FALSE;
}
if (victim == this) {
if (!silent)
sendTo("Don't be stupid...that would suck if you could.\n\r");
return FALSE;
}
if (noHarmCheck(victim))
return FALSE;
if (riding) {
if (!silent)
sendTo("You can't spin someone while mounted!\n\r");
return FALSE;
}
// to prevent from misuse in groups ...
if (attackers > 3) {
if (!silent)
sendTo("Too many people in the way!\n\r");
return FALSE;
}
if (victim->attackers > 3) {
if (!silent)
sendTo("You are too busy fending off other attackers!\n\r");
return FALSE;
}
if (!canUseArm(HAND_PRIMARY) || !canUseArm(HAND_SECONDARY)) {
if (!silent)
sendTo("You need two working arms to spin someone.\n\r");
return FALSE;
}
if (victim->isImmortal() || IS_SET(victim->specials.act, ACT_IMMORTAL)) {
if (!silent)
sendTo("You can't successfully spin an immortal...unless you want to dance.\n\r");
return FALSE;
}
if (victim->getPosition() < POSITION_STANDING) {
if (!silent)
act("$N is on the $g. You can't spin $M.",
FALSE, this, 0, victim, TO_CHAR);
return FALSE;
}
return TRUE;
}
enum spinMissT {
TYPE_DEFAULT,
TYPE_DEX,
TYPE_MONK
};
static int spinMiss(TBeing *caster, TBeing *victim, spinMissT type)
{
int rc;
if (type == TYPE_DEX) {
act("$N deftly avoids your attempt at spinning $M.", FALSE, caster,
0, victim, TO_CHAR);
act("You deftly avoid $n's attempt at spinning you.", FALSE, caster,
0, victim, TO_VICT);
act("$N deftly avoids $n's attempt at spinning $M.", FALSE, caster,
0, victim, TO_NOTVICT);
} else if (type == TYPE_MONK) {
act("$N deftly counters your attempt at spinning $M.", FALSE, caster, 0, victim, TO_CHAR, ANSI_RED);
act("You trip and land on the $g.", FALSE, caster, 0, victim, TO_CHAR, ANSI_RED);
act("You deftly counter $n's attempt at spinning you.", FALSE, caster, 0, victim, TO_VICT);
act("You stick out your foot and trip $m to the $g.", FALSE, caster, 0, victim, TO_VICT);
act("$N deftly counters $n's attempt at spinning $M.", FALSE, caster, 0, victim, TO_NOTVICT);
act("$N sticks out $S foot tripping $n to the $g.", FALSE, caster, 0, victim, TO_NOTVICT);
rc = caster->crashLanding(POSITION_SITTING);
if (IS_SET_DELETE(rc, DELETE_THIS))
return rc;
rc = caster->trySpringleap(victim);
if (IS_SET_DELETE(rc, DELETE_THIS) || IS_SET_DELETE(rc, DELETE_VICT))
return rc;
} else {
act("$n tries to spin $N, but ends up falling down.", FALSE, caster, 0, victim, TO_NOTVICT);
act("You try to spin $N, but end up falling on your face.", FALSE, caster, 0, victim, TO_CHAR);
act("$n fails to spin you, and tumbles to the $g.", FALSE, caster, 0, victim, TO_VICT);
rc = caster->crashLanding(POSITION_SITTING);
if (IS_SET_DELETE(rc, DELETE_THIS))
return rc;
rc = caster->trySpringleap(victim);
if (IS_SET_DELETE(rc, DELETE_THIS) || IS_SET_DELETE(rc, DELETE_VICT))
return rc;
}
if (caster->reconcileDamage(victim, 0,SKILL_SPIN) == -1)
return DELETE_VICT;
return FALSE;
}
static int spinHit(TBeing *caster, TBeing *victim)
{
int rc;
if (!victim->riding) {
act("$n grabs $N's arm and spins $M!", FALSE, caster, 0, victim, TO_NOTVICT);
act("Now dizzy, $N trips and falls to the $g.", FALSE, caster, 0, victim, TO_NOTVICT);
act("You grab $N's arm and spin $M HARD!", FALSE, caster, 0, victim, TO_CHAR);
act("Now dizzy $N trips and falls to the $g.", FALSE, caster, 0, victim, TO_CHAR);
act("$n grabs you by the arm and spins you violently.", FALSE, caster, 0, victim, TO_VICT);
act("As the world spins into a blur before your eyes you become dazed,\n\rand fall face first to the $g.",
FALSE, caster, 0, victim, TO_VICT, ANSI_RED);
} else {
act("$n grabs $N's arm and rips $M off of $S $o!", FALSE, caster, victim->riding, victim, TO_NOTVICT);
act("$N slams head first into the $g.", FALSE, caster, victim->riding, victim, TO_NOTVICT);
act("You grab $N's arm and pull $M off of $S $o!", FALSE, caster, victim->riding, victim, TO_CHAR);
act("$N slams head first into the $g.", FALSE, caster, victim->riding, victim, TO_CHAR);
act("$n suddenly grabs your arm and gives a hard yank!", FALSE, caster, victim->riding, victim, TO_VICT);
act("Suddenly, the $g rushes upward as you fall off of your $o.", FALSE, caster, victim->riding, victim, TO_VICT, ANSI_RED);
act("OOFFF!! Yuck, dirt tastes AWFUL!", FALSE, caster, victim->riding, victim, TO_VICT, ANSI_RED);
victim->dismount(POSITION_RESTING);
}
rc = victim->crashLanding(POSITION_SITTING);
if (IS_SET_DELETE(rc, DELETE_THIS))
return DELETE_VICT;
rc = victim->trySpringleap(caster);
if (IS_SET_DELETE(rc, DELETE_THIS) && IS_SET_DELETE(rc, DELETE_VICT))
return rc;
else if (IS_SET_DELETE(rc, DELETE_THIS))
return DELETE_VICT;
else if (IS_SET_DELETE(rc, DELETE_VICT))
return DELETE_THIS;
// see the balance notes for details on what's going on here.
float wt = (combatRound(discArray[SKILL_SPIN]->lag) / 3);
// adjust based on bash difficulty
wt = (wt * 100.0 / getSkillDiffModifier(SKILL_SPIN));
// since we cost some moves to perform, allow an extra 1/2 round of lag
wt += 1.5;
// since success and failure both have reciprocal positional changes
// there is no reason to account for that here.
victim->addToWait((int) wt);
// round up
wt += 0.5;
int dam = caster->getSkillDam(victim, SKILL_SPIN, caster->getSkillLevel(SKILL_SPIN), caster->getAdvLearning(SKILL_SPIN));
if (caster->reconcileDamage(victim, dam,SKILL_SPIN) == -1)
return DELETE_VICT;
return TRUE;
}
static int spin(TBeing *caster, TBeing *victim)
{
int percent;
int i = 0;
int rc;
int flycheck = ::number(1, 10);
const int SPIN_COST = 25; // movement cost to spin
if (!caster->canSpin(victim, SILENT_NO))
return FALSE;
// AC makes less difference here ...
percent = ((10 + (victim->getArmor() / 200)) << 1);
int bKnown = caster->getSkillValue(SKILL_SPIN);
if (victim->isFlying()) {
if (flycheck > 5) {
act("Your spin attempt on $N is more difficult because $E is flying.", FALSE, caster, 0, victim, TO_CHAR, ANSI_YELLOW);
act("The fact that you are flying makes $n's spin attempt much more difficult.", FALSE, caster, 0, victim, TO_VICT, ANSI_YELLOW);
act("The fact that $N is flying makes $n's spin attempt more difficult.", FALSE, caster, 0, victim, TO_NOTVICT, ANSI_YELLOW);
return (spinMiss(caster, victim, TYPE_DEFAULT));
} else {
act("Your spin attempt on $N is more difficult because $E is flying.", FALSE, caster, 0, victim, TO_CHAR, ANSI_YELLOW);
act("The fact that you are flying makes $n's spin attempt much more difficult.", FALSE, caster, 0, victim, TO_VICT, ANSI_YELLOW);
act("The fact that $N is flying makes $n's spin attempt more difficult.", FALSE, caster, 0, victim, TO_NOTVICT, ANSI_YELLOW);
// continue spinning
// the above is to make spin less annoying to flyers
}
}
if (caster->getMove() < SPIN_COST) {
caster->sendTo("You don't have the vitality to spin anyone!\n\r");
return FALSE;
}
caster->addToMove(-SPIN_COST);
if (victim->getPosition() <= POSITION_INCAP)
return (spinHit(caster, victim));
// remember, F = MA :) need to take weight into account
if (bSuccess(caster, bKnown + percent, SKILL_SPIN) &&
(i = caster->specialAttack(victim,SKILL_SPIN)) &&
i != GUARANTEED_FAILURE &&
(percent < bKnown)) {
int modif = 1;
modif += (caster->getPrimaryHold() ? 0 : 2);
modif += (caster->getSecondaryHold() ? 0 : 1);
if (victim->canCounterMove(bKnown/3)) {
SV(SKILL_SPIN);
rc = spinMiss(caster, victim, TYPE_MONK);
if (IS_SET_DELETE(rc, DELETE_THIS) || IS_SET_DELETE(rc, DELETE_VICT))
return rc;
} else if (((caster->getDexReaction() -
victim->getDexReaction()) > ::number(-10,20)) &&
victim->awake() && victim->getPosition() >= POSITION_STANDING) {
CS(SKILL_SPIN);
rc = spinMiss(caster, victim, TYPE_DEX);
if (IS_SET_DELETE(rc, DELETE_THIS) || IS_SET_DELETE(rc, DELETE_VICT))
return rc;
} else
return spinHit(caster, victim);
} else {
rc = spinMiss(caster, victim, TYPE_DEFAULT);
if (IS_SET_DELETE(rc, DELETE_THIS) || IS_SET_DELETE(rc, DELETE_VICT))
return rc;
}
return TRUE;
}
int TBeing::doSpin(const char *argument, TBeing *vict)
{
int rc = 0, learning = 0;
TBeing *victim;
char name_buf[256];
only_argument(argument, name_buf);
if (!(victim = vict)) {
if (!(victim = get_char_room_vis(this, name_buf))) {
if (!(victim = fight())) {
sendTo("Spin whom?\n\r");
return FALSE;
}
}
}
if (!sameRoom(*victim)) {
sendTo("That person isn't around.\n\r");
return FALSE;
}
if (desc) {
if ((learning = getAdvLearning(SKILL_SPIN)) <= 25) {
if (heldInPrimHand() || heldInSecHand()) {
sendTo("You are not skilled enough to spin someone with something in your hands!\n\r");
return FALSE;
}
} else if (learning <= 50) {
if (heldInPrimHand()) {
sendTo("You are not skilled enough to spin someone with something in your primary hand!\n\r");
return FALSE;
}
} else {
// no restrictions
}
}
rc = spin(this, victim);
if (rc)
addSkillLag(SKILL_SPIN, rc);
if (IS_SET_DELETE(rc, DELETE_VICT)) {
if (vict)
return rc;
delete victim;
victim = NULL;
REM_DELETE(rc, DELETE_VICT);
}
return rc;
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#include "db/consistency_level.hh"
#include <boost/range/algorithm/partition.hpp>
#include "exceptions/exceptions.hh"
#include "core/sstring.hh"
#include "schema.hh"
#include "database.hh"
#include "unimplemented.hh"
#include "db/read_repair_decision.hh"
#include "locator/abstract_replication_strategy.hh"
#include "locator/network_topology_strategy.hh"
#include "utils/fb_utilities.hh"
namespace db {
size_t quorum_for(keyspace& ks) {
return (ks.get_replication_strategy().get_replication_factor() / 2) + 1;
}
size_t local_quorum_for(keyspace& ks, const sstring& dc) {
using namespace locator;
auto& rs = ks.get_replication_strategy();
if (rs.get_type() == replication_strategy_type::network_topology) {
network_topology_strategy* nrs =
static_cast<network_topology_strategy*>(&rs);
return (nrs->get_replication_factor(dc) / 2) + 1;
}
return quorum_for(ks);
}
size_t block_for_local_serial(keyspace& ks) {
using namespace locator;
//
// TODO: Consider caching the final result in order to avoid all these
// useless dereferencing. Note however that this will introduce quite
// a lot of complications since both snitch output for a local host
// and the snitch itself (and thus its output) may change dynamically.
//
auto& snitch_ptr = i_endpoint_snitch::get_local_snitch_ptr();
auto local_addr = utils::fb_utilities::get_broadcast_address();
return local_quorum_for(ks, snitch_ptr->get_datacenter(local_addr));
}
size_t block_for_each_quorum(keyspace& ks) {
using namespace locator;
auto& rs = ks.get_replication_strategy();
if (rs.get_type() == replication_strategy_type::network_topology) {
network_topology_strategy* nrs =
static_cast<network_topology_strategy*>(&rs);
size_t n = 0;
for (auto& dc : nrs->get_datacenters()) {
n += local_quorum_for(ks, dc);
}
return n;
} else {
return quorum_for(ks);
}
}
size_t block_for(keyspace& ks, consistency_level cl) {
switch (cl) {
case consistency_level::ONE:
case consistency_level::LOCAL_ONE:
return 1;
case consistency_level::ANY:
return 1;
case consistency_level::TWO:
return 2;
case consistency_level::THREE:
return 3;
case consistency_level::QUORUM:
case consistency_level::SERIAL:
return quorum_for(ks);
case consistency_level::ALL:
return ks.get_replication_strategy().get_replication_factor();
case consistency_level::LOCAL_QUORUM:
case consistency_level::LOCAL_SERIAL:
return block_for_local_serial(ks);
case consistency_level::EACH_QUORUM:
return block_for_each_quorum(ks);
default:
abort();
}
}
bool is_datacenter_local(consistency_level l) {
return l == consistency_level::LOCAL_ONE || l == consistency_level::LOCAL_QUORUM;
}
bool is_local(gms::inet_address endpoint) {
using namespace locator;
auto& snitch_ptr = i_endpoint_snitch::get_local_snitch_ptr();
auto local_addr = utils::fb_utilities::get_broadcast_address();
return snitch_ptr->get_datacenter(local_addr) ==
snitch_ptr->get_datacenter(endpoint);
}
std::vector<gms::inet_address>
filter_for_query_dc_local(consistency_level cl,
keyspace& ks,
const std::vector<gms::inet_address>& live_endpoints) {
using namespace gms;
std::vector<inet_address> local;
std::vector<inet_address> other;
local.reserve(live_endpoints.size());
other.reserve(live_endpoints.size());
std::partition_copy(live_endpoints.begin(), live_endpoints.end(),
std::back_inserter(local), std::back_inserter(other),
is_local);
// check if blockfor more than we have localep's
size_t bf = block_for(ks, cl);
if (local.size() < bf) {
size_t other_items_count = std::min(bf - local.size(), other.size());
local.reserve(local.size() + other_items_count);
std::move(other.begin(), other.begin() + other_items_count,
std::back_inserter(local));
}
return local;
}
std::vector<gms::inet_address>
filter_for_query(consistency_level cl,
keyspace& ks,
std::vector<gms::inet_address> live_endpoints,
read_repair_decision read_repair) {
/*
* Endpoints are expected to be restricted to live replicas, sorted by
* snitch preference. For LOCAL_QUORUM, move local-DC replicas in front
* first as we need them there whether we do read repair (since the first
* replica gets the data read) or not (since we'll take the block_for first
* ones).
*/
if (is_datacenter_local(cl)) {
boost::range::partition(live_endpoints, is_local);
}
switch (read_repair) {
case read_repair_decision::NONE:
{
size_t start_pos = std::min(live_endpoints.size(), block_for(ks, cl));
live_endpoints.erase(live_endpoints.begin() + start_pos, live_endpoints.end());
}
// fall through
case read_repair_decision::GLOBAL:
return std::move(live_endpoints);
case read_repair_decision::DC_LOCAL:
return filter_for_query_dc_local(cl, ks, live_endpoints);
default:
throw std::runtime_error("Unknown read repair type");
}
}
std::vector<gms::inet_address> filter_for_query(consistency_level cl, keyspace& ks, std::vector<gms::inet_address>& live_endpoints) {
return filter_for_query(cl, ks, live_endpoints, read_repair_decision::NONE);
}
bool
is_sufficient_live_nodes(consistency_level cl,
keyspace& ks,
const std::vector<gms::inet_address>& live_endpoints) {
using namespace locator;
switch (cl) {
case consistency_level::ANY:
// local hint is acceptable, and local node is always live
return true;
case consistency_level::LOCAL_ONE:
return count_local_endpoints(live_endpoints) >= 1;
case consistency_level::LOCAL_QUORUM:
return count_local_endpoints(live_endpoints) >= block_for(ks, cl);
case consistency_level::EACH_QUORUM:
{
auto& rs = ks.get_replication_strategy();
if (rs.get_type() == replication_strategy_type::network_topology) {
for (auto& entry : count_per_dc_endpoints(ks, live_endpoints)) {
if (entry.second < local_quorum_for(ks, entry.first)) {
return false;
}
}
return true;
}
}
// Fallthough on purpose for SimpleStrategy
default:
return live_endpoints.size() >= block_for(ks, cl);
}
}
void validate_for_read(const sstring& keyspace_name, consistency_level cl) {
switch (cl) {
case consistency_level::ANY:
throw exceptions::invalid_request_exception("ANY ConsistencyLevel is only supported for writes");
case consistency_level::EACH_QUORUM:
throw exceptions::invalid_request_exception("EACH_QUORUM ConsistencyLevel is only supported for writes");
default:
break;
}
}
void validate_for_write(const sstring& keyspace_name, consistency_level cl) {
switch (cl) {
case consistency_level::SERIAL:
case consistency_level::LOCAL_SERIAL:
throw exceptions::invalid_request_exception("You must use conditional updates for serializable writes");
default:
break;
}
}
#if 0
// This is the same than validateForWrite really, but we include a slightly different error message for SERIAL/LOCAL_SERIAL
public void validateForCasCommit(String keyspaceName) throws InvalidRequestException
{
switch (this)
{
case EACH_QUORUM:
requireNetworkTopologyStrategy(keyspaceName);
break;
case SERIAL:
case LOCAL_SERIAL:
throw new InvalidRequestException(this + " is not supported as conditional update commit consistency. Use ANY if you mean \"make sure it is accepted but I don't care how many replicas commit it for non-SERIAL reads\"");
}
}
public void validateForCas() throws InvalidRequestException
{
if (!isSerialConsistency())
throw new InvalidRequestException("Invalid consistency for conditional update. Must be one of SERIAL or LOCAL_SERIAL");
}
#endif
bool is_serial_consistency(consistency_level cl) {
return cl == consistency_level::SERIAL || cl == consistency_level::LOCAL_SERIAL;
}
void validate_counter_for_write(schema_ptr s, consistency_level cl) {
if (cl == consistency_level::ANY) {
throw exceptions::invalid_request_exception(sprint("Consistency level ANY is not yet supported for counter table %s", s->cf_name()));
}
if (is_serial_consistency(cl)) {
throw exceptions::invalid_request_exception("Counter operations are inherently non-serializable");
}
}
#if 0
private void requireNetworkTopologyStrategy(String keyspaceName) throws InvalidRequestException
{
AbstractReplicationStrategy strategy = Keyspace.open(keyspaceName).getReplicationStrategy();
if (!(strategy instanceof NetworkTopologyStrategy))
throw new InvalidRequestException(String.format("consistency level %s not compatible with replication strategy (%s)", this, strategy.getClass().getName()));
}
#endif
}
<commit_msg>give preference to local data during query<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#include "db/consistency_level.hh"
#include <boost/range/algorithm/partition.hpp>
#include <boost/range/algorithm/find.hpp>
#include "exceptions/exceptions.hh"
#include "core/sstring.hh"
#include "schema.hh"
#include "database.hh"
#include "unimplemented.hh"
#include "db/read_repair_decision.hh"
#include "locator/abstract_replication_strategy.hh"
#include "locator/network_topology_strategy.hh"
#include "utils/fb_utilities.hh"
namespace db {
size_t quorum_for(keyspace& ks) {
return (ks.get_replication_strategy().get_replication_factor() / 2) + 1;
}
size_t local_quorum_for(keyspace& ks, const sstring& dc) {
using namespace locator;
auto& rs = ks.get_replication_strategy();
if (rs.get_type() == replication_strategy_type::network_topology) {
network_topology_strategy* nrs =
static_cast<network_topology_strategy*>(&rs);
return (nrs->get_replication_factor(dc) / 2) + 1;
}
return quorum_for(ks);
}
size_t block_for_local_serial(keyspace& ks) {
using namespace locator;
//
// TODO: Consider caching the final result in order to avoid all these
// useless dereferencing. Note however that this will introduce quite
// a lot of complications since both snitch output for a local host
// and the snitch itself (and thus its output) may change dynamically.
//
auto& snitch_ptr = i_endpoint_snitch::get_local_snitch_ptr();
auto local_addr = utils::fb_utilities::get_broadcast_address();
return local_quorum_for(ks, snitch_ptr->get_datacenter(local_addr));
}
size_t block_for_each_quorum(keyspace& ks) {
using namespace locator;
auto& rs = ks.get_replication_strategy();
if (rs.get_type() == replication_strategy_type::network_topology) {
network_topology_strategy* nrs =
static_cast<network_topology_strategy*>(&rs);
size_t n = 0;
for (auto& dc : nrs->get_datacenters()) {
n += local_quorum_for(ks, dc);
}
return n;
} else {
return quorum_for(ks);
}
}
size_t block_for(keyspace& ks, consistency_level cl) {
switch (cl) {
case consistency_level::ONE:
case consistency_level::LOCAL_ONE:
return 1;
case consistency_level::ANY:
return 1;
case consistency_level::TWO:
return 2;
case consistency_level::THREE:
return 3;
case consistency_level::QUORUM:
case consistency_level::SERIAL:
return quorum_for(ks);
case consistency_level::ALL:
return ks.get_replication_strategy().get_replication_factor();
case consistency_level::LOCAL_QUORUM:
case consistency_level::LOCAL_SERIAL:
return block_for_local_serial(ks);
case consistency_level::EACH_QUORUM:
return block_for_each_quorum(ks);
default:
abort();
}
}
bool is_datacenter_local(consistency_level l) {
return l == consistency_level::LOCAL_ONE || l == consistency_level::LOCAL_QUORUM;
}
bool is_local(gms::inet_address endpoint) {
using namespace locator;
auto& snitch_ptr = i_endpoint_snitch::get_local_snitch_ptr();
auto local_addr = utils::fb_utilities::get_broadcast_address();
return snitch_ptr->get_datacenter(local_addr) ==
snitch_ptr->get_datacenter(endpoint);
}
std::vector<gms::inet_address>
filter_for_query_dc_local(consistency_level cl,
keyspace& ks,
const std::vector<gms::inet_address>& live_endpoints) {
using namespace gms;
std::vector<inet_address> local;
std::vector<inet_address> other;
local.reserve(live_endpoints.size());
other.reserve(live_endpoints.size());
std::partition_copy(live_endpoints.begin(), live_endpoints.end(),
std::back_inserter(local), std::back_inserter(other),
is_local);
// check if blockfor more than we have localep's
size_t bf = block_for(ks, cl);
if (local.size() < bf) {
size_t other_items_count = std::min(bf - local.size(), other.size());
local.reserve(local.size() + other_items_count);
std::move(other.begin(), other.begin() + other_items_count,
std::back_inserter(local));
}
return local;
}
std::vector<gms::inet_address>
filter_for_query(consistency_level cl,
keyspace& ks,
std::vector<gms::inet_address> live_endpoints,
read_repair_decision read_repair) {
/*
* Endpoints are expected to be restricted to live replicas, sorted by
* snitch preference. For LOCAL_QUORUM, move local-DC replicas in front
* first as we need them there whether we do read repair (since the first
* replica gets the data read) or not (since we'll take the block_for first
* ones).
*/
// FIXME: before dynamic snitch is implement put local address (if present) at the beginning
auto it = boost::range::find(live_endpoints, utils::fb_utilities::get_broadcast_address());
if (it != live_endpoints.end() && it != live_endpoints.begin()) {
std::iter_swap(it, live_endpoints.begin());
}
if (is_datacenter_local(cl)) {
boost::range::partition(live_endpoints, is_local);
}
switch (read_repair) {
case read_repair_decision::NONE:
{
size_t start_pos = std::min(live_endpoints.size(), block_for(ks, cl));
live_endpoints.erase(live_endpoints.begin() + start_pos, live_endpoints.end());
}
// fall through
case read_repair_decision::GLOBAL:
return std::move(live_endpoints);
case read_repair_decision::DC_LOCAL:
return filter_for_query_dc_local(cl, ks, live_endpoints);
default:
throw std::runtime_error("Unknown read repair type");
}
}
std::vector<gms::inet_address> filter_for_query(consistency_level cl, keyspace& ks, std::vector<gms::inet_address>& live_endpoints) {
return filter_for_query(cl, ks, live_endpoints, read_repair_decision::NONE);
}
bool
is_sufficient_live_nodes(consistency_level cl,
keyspace& ks,
const std::vector<gms::inet_address>& live_endpoints) {
using namespace locator;
switch (cl) {
case consistency_level::ANY:
// local hint is acceptable, and local node is always live
return true;
case consistency_level::LOCAL_ONE:
return count_local_endpoints(live_endpoints) >= 1;
case consistency_level::LOCAL_QUORUM:
return count_local_endpoints(live_endpoints) >= block_for(ks, cl);
case consistency_level::EACH_QUORUM:
{
auto& rs = ks.get_replication_strategy();
if (rs.get_type() == replication_strategy_type::network_topology) {
for (auto& entry : count_per_dc_endpoints(ks, live_endpoints)) {
if (entry.second < local_quorum_for(ks, entry.first)) {
return false;
}
}
return true;
}
}
// Fallthough on purpose for SimpleStrategy
default:
return live_endpoints.size() >= block_for(ks, cl);
}
}
void validate_for_read(const sstring& keyspace_name, consistency_level cl) {
switch (cl) {
case consistency_level::ANY:
throw exceptions::invalid_request_exception("ANY ConsistencyLevel is only supported for writes");
case consistency_level::EACH_QUORUM:
throw exceptions::invalid_request_exception("EACH_QUORUM ConsistencyLevel is only supported for writes");
default:
break;
}
}
void validate_for_write(const sstring& keyspace_name, consistency_level cl) {
switch (cl) {
case consistency_level::SERIAL:
case consistency_level::LOCAL_SERIAL:
throw exceptions::invalid_request_exception("You must use conditional updates for serializable writes");
default:
break;
}
}
#if 0
// This is the same than validateForWrite really, but we include a slightly different error message for SERIAL/LOCAL_SERIAL
public void validateForCasCommit(String keyspaceName) throws InvalidRequestException
{
switch (this)
{
case EACH_QUORUM:
requireNetworkTopologyStrategy(keyspaceName);
break;
case SERIAL:
case LOCAL_SERIAL:
throw new InvalidRequestException(this + " is not supported as conditional update commit consistency. Use ANY if you mean \"make sure it is accepted but I don't care how many replicas commit it for non-SERIAL reads\"");
}
}
public void validateForCas() throws InvalidRequestException
{
if (!isSerialConsistency())
throw new InvalidRequestException("Invalid consistency for conditional update. Must be one of SERIAL or LOCAL_SERIAL");
}
#endif
bool is_serial_consistency(consistency_level cl) {
return cl == consistency_level::SERIAL || cl == consistency_level::LOCAL_SERIAL;
}
void validate_counter_for_write(schema_ptr s, consistency_level cl) {
if (cl == consistency_level::ANY) {
throw exceptions::invalid_request_exception(sprint("Consistency level ANY is not yet supported for counter table %s", s->cf_name()));
}
if (is_serial_consistency(cl)) {
throw exceptions::invalid_request_exception("Counter operations are inherently non-serializable");
}
}
#if 0
private void requireNetworkTopologyStrategy(String keyspaceName) throws InvalidRequestException
{
AbstractReplicationStrategy strategy = Keyspace.open(keyspaceName).getReplicationStrategy();
if (!(strategy instanceof NetworkTopologyStrategy))
throw new InvalidRequestException(String.format("consistency level %s not compatible with replication strategy (%s)", this, strategy.getClass().getName()));
}
#endif
}
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2015-2019 Ingo Wald //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
// pbrt_parser
#include "pbrtParser/Scene.h"
// stl
#include <iostream>
#include <vector>
#include <sstream>
#include <assert.h>
// std
#include <set>
#include <stack>
namespace pbrt {
namespace semantic {
using std::cout;
using std::endl;
void usage(const std::string &msg)
{
if (msg != "") std::cerr << "Error: " << msg << std::endl << std::endl;
std::cout << "./pbrt2pbf inFile.pbrt|inFile.pbf <args>" << std::endl;
std::cout << std::endl;
std::cout << " -o <out.pbf> : where to write the output to" << std::endl;
std::cout << " (tris to quads, removing reundant fields, etc)" << std::endl;
exit(msg == "" ? 0 : 1);
}
inline bool endsWith(const std::string &s, const std::string &suffix)
{
return s.substr(s.size()-suffix.size(),suffix.size()) == suffix;
}
void pbrt2pbf(int ac, char **av)
{
std::string inFileName;
std::string outFileName;
for (int i=1;i<ac;i++) {
const std::string arg = av[i];
if (arg == "-o") {
assert(i+1 < ac);
outFileName = av[++i];
} else if (arg[0] != '-') {
inFileName = arg;
} else {
usage("invalid argument '"+arg+"'");
}
}
if (outFileName == "")
usage("no output file specified (-o <file.pbff>)");
if (inFileName == "")
usage("no input pbrt file specified");
if (!endsWith(outFileName,".pbf")) {
std::cout << "output file name missing '.pbsf' extension - adding it ..." << std::endl;
outFileName = outFileName+".pbf";
}
std::cout << "-------------------------------------------------------" << std::endl;
std::cout << "parsing pbrt file " << inFileName << std::endl;
// try {
Scene::SP scene = importPBRT(inFileName);
std::cout << "\033[1;32m done importing scene.\033[0m" << std::endl;
std::cout << "writing to binary file " << outFileName << std::endl;
scene->saveTo(outFileName);
std::cout << "\033[1;32m => yay! writing successful...\033[0m" << std::endl;
// } catch (std::runtime_error &e) {
// cout << "\033[1;31mError in parsing: " << e.what() << "\033[0m\n";
// throw e;
// }
}
extern "C" int main(int ac, char **av)
{
pbrt2pbf(ac,av);
return 0;
}
} // ::pbrt::semantic
} // ::pbrt
<commit_msg>usage() exit in pbrt2pbf now properly exits after error message<commit_after>// ======================================================================== //
// Copyright 2015-2019 Ingo Wald //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
// pbrt_parser
#include "pbrtParser/Scene.h"
// stl
#include <iostream>
#include <vector>
#include <sstream>
#include <assert.h>
// std
#include <set>
#include <stack>
namespace pbrt {
namespace semantic {
using std::cout;
using std::endl;
void usage(const std::string &msg)
{
if (msg != "") std::cerr << "Error: " << msg << std::endl << std::endl;
std::cout << "./pbrt2pbf inFile.pbrt|inFile.pbf <args>" << std::endl;
std::cout << std::endl;
std::cout << " -o <out.pbf> : where to write the output to" << std::endl;
std::cout << " (tris to quads, removing reundant fields, etc)" << std::endl;
std::cout << std::endl;
exit(msg == "" ? 0 : 1);
}
inline bool endsWith(const std::string &s, const std::string &suffix)
{
return s.substr(s.size()-suffix.size(),suffix.size()) == suffix;
}
void pbrt2pbf(int ac, char **av)
{
std::string inFileName;
std::string outFileName;
for (int i=1;i<ac;i++) {
const std::string arg = av[i];
if (arg == "-o") {
assert(i+1 < ac);
outFileName = av[++i];
} else if (arg[0] != '-') {
inFileName = arg;
} else {
usage("invalid argument '"+arg+"'");
}
}
if (outFileName == "")
usage("no output file specified (-o <file.pbff>)");
if (inFileName == "")
usage("no input pbrt file specified");
if (!endsWith(outFileName,".pbf")) {
std::cout << "output file name missing '.pbsf' extension - adding it ..." << std::endl;
outFileName = outFileName+".pbf";
}
std::cout << "-------------------------------------------------------" << std::endl;
std::cout << "parsing pbrt file " << inFileName << std::endl;
// try {
Scene::SP scene = importPBRT(inFileName);
std::cout << "\033[1;32m done importing scene.\033[0m" << std::endl;
std::cout << "writing to binary file " << outFileName << std::endl;
scene->saveTo(outFileName);
std::cout << "\033[1;32m => yay! writing successful...\033[0m" << std::endl;
// } catch (std::runtime_error &e) {
// cout << "\033[1;31mError in parsing: " << e.what() << "\033[0m\n";
// throw e;
// }
}
extern "C" int main(int ac, char **av)
{
pbrt2pbf(ac,av);
return 0;
}
} // ::pbrt::semantic
} // ::pbrt
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
#ifndef _Stroika_Foundation_Debug_AssertExternallySynchronizedLock_inl_
#define _Stroika_Foundation_Debug_AssertExternallySynchronizedLock_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "Sanitizer.h"
namespace Stroika::Foundation::Debug {
/*
********************************************************************************
*************** Debug::AssertExternallySynchronizedLock ************************
********************************************************************************
*/
inline AssertExternallySynchronizedLock::AssertExternallySynchronizedLock (const AssertExternallySynchronizedLock& src) noexcept
: AssertExternallySynchronizedLock ()
{
shared_lock<const AssertExternallySynchronizedLock> critSec1{src}; // to copy, the src can have shared_locks, but no (write) locks
}
inline AssertExternallySynchronizedLock::AssertExternallySynchronizedLock ([[maybe_unused]] AssertExternallySynchronizedLock&& src) noexcept
: AssertExternallySynchronizedLock ()
{
#if qDebug
try {
lock_guard<mutex> sharedLockProtect{GetSharedLockMutexThreads_ ()};
Require (src.fLocks_ == 0 and src.fSharedLockThreads_->empty ()); // to move, the src can have no locks of any kind (since we change src)
}
catch (...) {
AssertNotReached ();
}
#endif
}
inline AssertExternallySynchronizedLock& AssertExternallySynchronizedLock::operator= ([[maybe_unused]] const AssertExternallySynchronizedLock& rhs) noexcept
{
#if qDebug
try {
shared_lock<const AssertExternallySynchronizedLock> critSec1{rhs}; // to copy, the src can have shared_locks, but no (write) locks
lock_guard<mutex> sharedLockProtect{GetSharedLockMutexThreads_ ()};
Require (fLocks_ == 0 and fSharedLockThreads_->empty ()); // We must not have any locks going to replace this
}
catch (...) {
AssertNotReached ();
}
#endif
return *this;
}
inline AssertExternallySynchronizedLock& AssertExternallySynchronizedLock::operator= ([[maybe_unused]] AssertExternallySynchronizedLock&& rhs) noexcept
{
#if qDebug
try {
lock_guard<mutex> sharedLockProtect{GetSharedLockMutexThreads_ ()};
Require (rhs.fLocks_ == 0 and rhs.fSharedLockThreads_->empty ()); // to move, the rhs can have no locks of any kind (since we change rhs)
Require (fLocks_ == 0 and fSharedLockThreads_->empty ()); // ditto for thing being assigned to
}
catch (...) {
AssertNotReached ();
}
#endif
return *this;
}
inline void AssertExternallySynchronizedLock::lock () const noexcept
{
#if qDebug
lock_ ();
#endif
}
inline void AssertExternallySynchronizedLock::unlock () const noexcept
{
#if qDebug
unlock_ ();
#endif
}
inline void AssertExternallySynchronizedLock::lock_shared () const noexcept
{
#if qDebug
lock_shared_ ();
#endif
}
inline void AssertExternallySynchronizedLock::unlock_shared () const noexcept
{
#if qDebug
unlock_shared_ ();
#endif
}
}
#endif /*_Stroika_Foundation_Debug_AssertExternallySynchronizedLock_inl_*/
<commit_msg>refixed wrong fix for Debug/AssertExternallySynchronizedLock regression<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
#ifndef _Stroika_Foundation_Debug_AssertExternallySynchronizedLock_inl_
#define _Stroika_Foundation_Debug_AssertExternallySynchronizedLock_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "Sanitizer.h"
namespace Stroika::Foundation::Debug {
/*
********************************************************************************
*************** Debug::AssertExternallySynchronizedLock ************************
********************************************************************************
*/
inline AssertExternallySynchronizedLock::AssertExternallySynchronizedLock (const AssertExternallySynchronizedLock& src) noexcept
: AssertExternallySynchronizedLock ()
{
shared_lock<const AssertExternallySynchronizedLock> critSec1{src}; // to copy, the src can have shared_locks, but no (write) locks
}
inline AssertExternallySynchronizedLock::AssertExternallySynchronizedLock ([[maybe_unused]] AssertExternallySynchronizedLock&& src) noexcept
: AssertExternallySynchronizedLock ()
{
#if qDebug
try {
lock_guard<mutex> sharedLockProtect{GetSharedLockMutexThreads_ ()};
Require (src.fLocks_ == 0 and src.fSharedLockThreads_->empty ()); // to move, the src can have no locks of any kind (since we change src)
}
catch (...) {
AssertNotReached ();
}
#endif
}
inline AssertExternallySynchronizedLock& AssertExternallySynchronizedLock::operator= ([[maybe_unused]] const AssertExternallySynchronizedLock& rhs) noexcept
{
#if qDebug
try {
shared_lock<const AssertExternallySynchronizedLock> critSec1{rhs}; // to copy, the src can have shared_locks, but no (write) locks
lock_guard<mutex> sharedLockProtect{GetSharedLockMutexThreads_ ()};
if (this == &rhs) {
Require (fLocks_ == 0 and fSharedLockThreads_->size () == 1); // we locked ourselves above
}
else {
Require (fLocks_ == 0 and fSharedLockThreads_->empty ()); // We must not have any locks going to replace this
}
}
catch (...) {
AssertNotReached ();
}
#endif
return *this;
}
inline AssertExternallySynchronizedLock& AssertExternallySynchronizedLock::operator= ([[maybe_unused]] AssertExternallySynchronizedLock&& rhs) noexcept
{
#if qDebug
try {
lock_guard<mutex> sharedLockProtect{GetSharedLockMutexThreads_ ()};
Require (rhs.fLocks_ == 0 and rhs.fSharedLockThreads_->empty ()); // to move, the rhs can have no locks of any kind (since we change rhs)
Require (fLocks_ == 0 and fSharedLockThreads_->empty ()); // ditto for thing being assigned to
}
catch (...) {
AssertNotReached ();
}
#endif
return *this;
}
inline void AssertExternallySynchronizedLock::lock () const noexcept
{
#if qDebug
lock_ ();
#endif
}
inline void AssertExternallySynchronizedLock::unlock () const noexcept
{
#if qDebug
unlock_ ();
#endif
}
inline void AssertExternallySynchronizedLock::lock_shared () const noexcept
{
#if qDebug
lock_shared_ ();
#endif
}
inline void AssertExternallySynchronizedLock::unlock_shared () const noexcept
{
#if qDebug
unlock_shared_ ();
#endif
}
}
#endif /*_Stroika_Foundation_Debug_AssertExternallySynchronizedLock_inl_*/
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: xlroot.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2003-11-05 13:36:39 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// ============================================================================
#ifndef SC_XLROOT_HXX
#include "xlroot.hxx"
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SFX_OBJSH_HXX
#include <sfx2/objsh.hxx>
#endif
#ifndef _SFX_PRINTER_HXX
#include <sfx2/printer.hxx>
#endif
#ifndef _SV_FONT_HXX
#include <vcl/font.hxx>
#endif
#ifndef _EDITSTAT_HXX
#include <svx/editstat.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef SC_ITEMS_HXX
#include "scitems.hxx"
#endif
#ifndef _EEITEM_HXX
#include <svx/eeitem.hxx>
#endif
#ifndef SC_DOCUMENT_HXX
#include "document.hxx"
#endif
#ifndef SC_SCDOCPOL_HXX
#include "docpool.hxx"
#endif
#ifndef SC_DOCUNO_HXX
#include "docuno.hxx"
#endif
#ifndef SC_EDITUTIL_HXX
#include "editutil.hxx"
#endif
#ifndef SC_DRWLAYER_HXX
#include "drwlayer.hxx"
#endif
#ifndef SC_SCPATATR_HXX
#include "patattr.hxx"
#endif
#ifndef SC_XLSTYLE_HXX
#include "xlstyle.hxx"
#endif
#ifndef SC_XLTRACER_HXX
#include "xltracer.hxx"
#endif
#include "root.hxx"
namespace com { namespace sun { namespace star { namespace frame { class XModel; } } } }
using ::com::sun::star::uno::Reference;
using ::com::sun::star::frame::XModel;
// Global data ================================================================
XclRootData::XclRootData( XclBiff eBiff, ScDocument& rDocument, const String& rDocUrl, CharSet eCharSet ) :
meBiff( eBiff ),
mrDoc( rDocument ),
maDocUrl( rDocUrl ),
maBasePath( rDocUrl, 0, rDocUrl.SearchBackward( '/' ) + 1 ),
meCharSet( eCharSet ),
meSysLang( Application::GetSettings().GetLanguage() ),
meDocLang( Application::GetSettings().GetLanguage() ),
meUILang( Application::GetSettings().GetUILanguage() ),
maScMaxPos( MAXCOL, MAXROW, MAXTAB ),
maXclMaxPos( EXC_MAXCOL_BIFF2, EXC_MAXROW_BIFF2, EXC_MAXTAB_BIFF2 ),
mnCharWidth( 110 ),
mnScTab( 0 ),
mbTruncated( false ),
mpRDP( new RootData )//!
{
#ifdef DBG_UTIL
mnObjCnt = 0;
#endif
}
XclRootData::~XclRootData()
{
#ifdef DBG_UTIL
DBG_ASSERT( mnObjCnt == 0, "XclRootData::~XclRootData - wrong object count" );
#endif
}
// ----------------------------------------------------------------------------
XclRoot::XclRoot( XclRootData& rRootData ) :
mrData( rRootData ),
mpRD( rRootData.mpRDP.get() )//!
{
#ifdef DBG_UTIL
++mrData.mnObjCnt;
#endif
if( GetBiff() != xlBiffUnknown )
SetMaxPos();
}
XclRoot::XclRoot( const XclRoot& rRoot ) :
mrData( rRoot.mrData ),
mpRD( rRoot.mpRD )//!
{
#ifdef DBG_UTIL
++mrData.mnObjCnt;
#endif
}
XclRoot::~XclRoot()
{
#ifdef DBG_UTIL
--mrData.mnObjCnt;
#endif
}
XclRoot& XclRoot::operator=( const XclRoot& rRoot )
{
// allowed for assignment in derived classes - but test if the same root data is used
DBG_ASSERT( &mrData == &rRoot.mrData, "XclRoot::operator= - incompatible root data" );
return *this;
}
void XclRoot::SetBiff( XclBiff eBiff )
{
mrData.meBiff = eBiff;
if( eBiff != xlBiffUnknown )
SetMaxPos();
}
void XclRoot::SetCharWidth( const XclFontData& rFontData )
{
if( SfxPrinter* pPrinter = GetPrinter() )
{
Font aFont( rFontData.maName, Size( 0, rFontData.mnHeight ) );
aFont.SetFamily( rFontData.GetScFamily( GetCharSet() ) );
aFont.SetCharSet( rFontData.GetScCharSet() );
aFont.SetWeight( rFontData.GetScWeight() );
pPrinter->SetFont( aFont );
mrData.mnCharWidth = pPrinter->GetTextWidth( String( '0' ) );
}
else
mrData.mnCharWidth = 11 * rFontData.mnHeight / 20;
}
void XclRoot::SetMaxPos()
{
switch( GetBiff() )
{
case xlBiff2:
case xlBiff3: mrData.maXclMaxPos.Set( EXC_MAXCOL_BIFF2, EXC_MAXROW_BIFF2, EXC_MAXTAB_BIFF2 ); break;
case xlBiff4:
case xlBiff5:
case xlBiff7: mrData.maXclMaxPos.Set( EXC_MAXCOL_BIFF4, EXC_MAXROW_BIFF4, EXC_MAXTAB_BIFF4 ); break;
case xlBiff8: mrData.maXclMaxPos.Set( EXC_MAXCOL_BIFF8, EXC_MAXROW_BIFF8, EXC_MAXTAB_BIFF8 ); break;
default: DBG_ERROR_BIFF();
}
}
SfxObjectShell* XclRoot::GetDocShell() const
{
return GetDoc().GetDocumentShell();
}
ScModelObj* XclRoot::GetDocModelObj() const
{
SfxObjectShell* pDocShell = GetDocShell();
return pDocShell ? ScModelObj::getImplementation( Reference< XModel >( pDocShell->GetModel() ) ) : NULL;
}
SfxPrinter* XclRoot::GetPrinter() const
{
return GetDoc().GetPrinter();
}
SvNumberFormatter& XclRoot::GetFormatter() const
{
return *GetDoc().GetFormatTable();
}
ScStyleSheetPool& XclRoot::GetStyleSheetPool() const
{
return *GetDoc().GetStyleSheetPool();
}
ScRangeName& XclRoot::GetNamedRanges() const
{
return *GetDoc().GetRangeName();
}
SvStorage* XclRoot::GetRootStorage() const
{
return mpRD->pRootStorage;
}
ScEditEngineDefaulter& XclRoot::GetEditEngine() const
{
if( !mrData.mpEditEngine.get() )
{
mrData.mpEditEngine.reset( new ScEditEngineDefaulter( GetDoc().GetEnginePool() ) );
ScEditEngineDefaulter& rEE = *mrData.mpEditEngine;
rEE.SetRefMapMode( MAP_100TH_MM );
rEE.SetEditTextObjectPool( GetDoc().GetEditPool() );
rEE.SetUpdateMode( FALSE );
rEE.EnableUndo( FALSE );
rEE.SetControlWord( rEE.GetControlWord() & ~EE_CNTRL_ALLOWBIGOBJS );
}
return *mrData.mpEditEngine;
}
ScHeaderEditEngine& XclRoot::GetHFEditEngine() const
{
if( !mrData.mpHFEditEngine.get() )
{
mrData.mpHFEditEngine.reset( new ScHeaderEditEngine( EditEngine::CreatePool(), TRUE ) );
ScHeaderEditEngine& rEE = *mrData.mpHFEditEngine;
rEE.SetRefMapMode( MAP_TWIP ); // headers/footers use twips as default metric
rEE.SetUpdateMode( FALSE );
rEE.EnableUndo( FALSE );
rEE.SetControlWord( rEE.GetControlWord() & ~EE_CNTRL_ALLOWBIGOBJS );
// set Calc header/footer defaults
SfxItemSet* pEditSet = new SfxItemSet( rEE.GetEmptyItemSet() );
SfxItemSet aItemSet( *GetDoc().GetPool(), ATTR_PATTERN_START, ATTR_PATTERN_END );
ScPatternAttr::FillToEditItemSet( *pEditSet, aItemSet );
// FillToEditItemSet() adjusts font height to 1/100th mm, we need twips
pEditSet->Put( aItemSet.Get( ATTR_FONT_HEIGHT ), EE_CHAR_FONTHEIGHT );
pEditSet->Put( aItemSet.Get( ATTR_CJK_FONT_HEIGHT ), EE_CHAR_FONTHEIGHT_CJK );
pEditSet->Put( aItemSet.Get( ATTR_CTL_FONT_HEIGHT ), EE_CHAR_FONTHEIGHT_CTL );
rEE.SetDefaults( pEditSet ); // takes ownership
}
return *mrData.mpHFEditEngine;
}
EditEngine& XclRoot::GetDrawEditEngine() const
{
if( !mrData.mpDrawEditEng.get() )
{
mrData.mpDrawEditEng.reset( new EditEngine( &GetDoc().GetDrawLayer()->GetItemPool() ) );
EditEngine& rEE = *mrData.mpDrawEditEng;
rEE.SetRefMapMode( MAP_100TH_MM );
rEE.SetUpdateMode( FALSE );
rEE.EnableUndo( FALSE );
rEE.SetControlWord( rEE.GetControlWord() & ~EE_CNTRL_ALLOWBIGOBJS );
}
return *mrData.mpDrawEditEng;
}
XclTracer& XclRoot::GetTracer() const
{
return *mrData.mpTracer;
}
bool XclRoot::CheckCellAddress( const ScAddress& rPos, const ScAddress& rMaxPos ) const
{
bool bValid = (rPos.Col() <= rMaxPos.Col()) && (rPos.Row() <= rMaxPos.Row()) && (rPos.Tab() <= rMaxPos.Tab());
if( !bValid )
{
mrData.mbTruncated = true;
GetTracer().TraceInvalidAddress(rPos, rMaxPos);
}
return bValid;
}
bool XclRoot::CheckCellRange( ScRange& rRange, const ScAddress& rMaxPos ) const
{
rRange.Justify();
// check start position
bool bValidStart = CheckCellAddress( rRange.aStart, rMaxPos );
// check & correct end position
if( bValidStart )
{
CheckCellAddress( rRange.aEnd, rMaxPos );
if( rRange.aEnd.Col() > rMaxPos.Col() )
rRange.aEnd.SetCol( rMaxPos.Col() );
if( rRange.aEnd.Row() > rMaxPos.Row() )
rRange.aEnd.SetRow( rMaxPos.Row() );
if( rRange.aEnd.Tab() > rMaxPos.Tab() )
rRange.aEnd.SetTab( rMaxPos.Tab() );
}
return bValidStart;
}
void XclRoot::CheckCellRangeList( ScRangeList& rRanges, const ScAddress& rMaxPos ) const
{
sal_uInt32 nIndex = rRanges.Count();
while( nIndex )
{
--nIndex; // backwards to keep nIndex valid
ScRange* pRange = rRanges.GetObject( nIndex );
if( pRange && !CheckCellRange( *pRange, rMaxPos ) )
delete rRanges.Remove( nIndex );
}
}
// ============================================================================
<commit_msg>INTEGRATION: CWS calcrtl (1.7.56); FILE MERGED 2003/11/27 11:30:54 nn 1.7.56.3: RESYNC: (1.8-1.9); FILE MERGED 2003/11/04 16:25:09 nn 1.7.56.2: RESYNC: (1.7-1.8); FILE MERGED 2003/10/10 15:33:29 dr 1.7.56.1: #i1967# first preparations for >32000 rows<commit_after>/*************************************************************************
*
* $RCSfile: xlroot.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2004-02-03 12:24:45 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// ============================================================================
#ifndef SC_XLROOT_HXX
#include "xlroot.hxx"
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SFX_OBJSH_HXX
#include <sfx2/objsh.hxx>
#endif
#ifndef _SFX_PRINTER_HXX
#include <sfx2/printer.hxx>
#endif
#ifndef _SV_FONT_HXX
#include <vcl/font.hxx>
#endif
#ifndef _EDITSTAT_HXX
#include <svx/editstat.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef SC_ITEMS_HXX
#include "scitems.hxx"
#endif
#ifndef _EEITEM_HXX
#include <svx/eeitem.hxx>
#endif
#ifndef SC_DOCUMENT_HXX
#include "document.hxx"
#endif
#ifndef SC_SCDOCPOL_HXX
#include "docpool.hxx"
#endif
#ifndef SC_DOCUNO_HXX
#include "docuno.hxx"
#endif
#ifndef SC_EDITUTIL_HXX
#include "editutil.hxx"
#endif
#ifndef SC_DRWLAYER_HXX
#include "drwlayer.hxx"
#endif
#ifndef SC_SCPATATR_HXX
#include "patattr.hxx"
#endif
#ifndef SC_XLSTYLE_HXX
#include "xlstyle.hxx"
#endif
#ifndef SC_XLTRACER_HXX
#include "xltracer.hxx"
#endif
#include "root.hxx"
namespace com { namespace sun { namespace star { namespace frame { class XModel; } } } }
using ::com::sun::star::uno::Reference;
using ::com::sun::star::frame::XModel;
// Global data ================================================================
XclRootData::XclRootData( XclBiff eBiff, ScDocument& rDocument, const String& rDocUrl, CharSet eCharSet ) :
meBiff( eBiff ),
mrDoc( rDocument ),
maDocUrl( rDocUrl ),
maBasePath( rDocUrl, 0, rDocUrl.SearchBackward( '/' ) + 1 ),
meCharSet( eCharSet ),
meSysLang( Application::GetSettings().GetLanguage() ),
meDocLang( Application::GetSettings().GetLanguage() ),
meUILang( Application::GetSettings().GetUILanguage() ),
maScMaxPos( SCMAXCOL, SCMAXROW, SCMAXTAB ),
maXclMaxPos( EXC_MAXCOL2, EXC_MAXROW2, EXC_MAXTAB2 ),
mnCharWidth( 110 ),
mnScTab( 0 ),
mbTruncated( false ),
mpRDP( new RootData )//!
{
#ifdef DBG_UTIL
mnObjCnt = 0;
#endif
}
XclRootData::~XclRootData()
{
#ifdef DBG_UTIL
DBG_ASSERT( mnObjCnt == 0, "XclRootData::~XclRootData - wrong object count" );
#endif
}
// ----------------------------------------------------------------------------
XclRoot::XclRoot( XclRootData& rRootData ) :
mrData( rRootData ),
mpRD( rRootData.mpRDP.get() )//!
{
#ifdef DBG_UTIL
++mrData.mnObjCnt;
#endif
if( GetBiff() != xlBiffUnknown )
SetMaxPos();
}
XclRoot::XclRoot( const XclRoot& rRoot ) :
mrData( rRoot.mrData ),
mpRD( rRoot.mpRD )//!
{
#ifdef DBG_UTIL
++mrData.mnObjCnt;
#endif
}
XclRoot::~XclRoot()
{
#ifdef DBG_UTIL
--mrData.mnObjCnt;
#endif
}
XclRoot& XclRoot::operator=( const XclRoot& rRoot )
{
// allowed for assignment in derived classes - but test if the same root data is used
DBG_ASSERT( &mrData == &rRoot.mrData, "XclRoot::operator= - incompatible root data" );
return *this;
}
void XclRoot::SetBiff( XclBiff eBiff )
{
mrData.meBiff = eBiff;
if( eBiff != xlBiffUnknown )
SetMaxPos();
}
void XclRoot::SetCharWidth( const XclFontData& rFontData )
{
if( SfxPrinter* pPrinter = GetPrinter() )
{
Font aFont( rFontData.maName, Size( 0, rFontData.mnHeight ) );
aFont.SetFamily( rFontData.GetScFamily( GetCharSet() ) );
aFont.SetCharSet( rFontData.GetScCharSet() );
aFont.SetWeight( rFontData.GetScWeight() );
pPrinter->SetFont( aFont );
mrData.mnCharWidth = pPrinter->GetTextWidth( String( '0' ) );
}
else
mrData.mnCharWidth = 11 * rFontData.mnHeight / 20;
}
void XclRoot::SetMaxPos()
{
switch( GetBiff() )
{
case xlBiff2: mrData.maXclMaxPos.Set( EXC_MAXCOL2, EXC_MAXROW2, EXC_MAXTAB2 ); break;
case xlBiff3: mrData.maXclMaxPos.Set( EXC_MAXCOL3, EXC_MAXROW3, EXC_MAXTAB3 ); break;
case xlBiff4: mrData.maXclMaxPos.Set( EXC_MAXCOL4, EXC_MAXROW4, EXC_MAXTAB4 ); break;
case xlBiff5:
case xlBiff7: mrData.maXclMaxPos.Set( EXC_MAXCOL5, EXC_MAXROW5, EXC_MAXTAB5 ); break;
case xlBiff8: mrData.maXclMaxPos.Set( EXC_MAXCOL8, EXC_MAXROW8, EXC_MAXTAB8 ); break;
default: DBG_ERROR_BIFF();
}
}
SfxObjectShell* XclRoot::GetDocShell() const
{
return GetDoc().GetDocumentShell();
}
ScModelObj* XclRoot::GetDocModelObj() const
{
SfxObjectShell* pDocShell = GetDocShell();
return pDocShell ? ScModelObj::getImplementation( Reference< XModel >( pDocShell->GetModel() ) ) : NULL;
}
SfxPrinter* XclRoot::GetPrinter() const
{
return GetDoc().GetPrinter();
}
SvNumberFormatter& XclRoot::GetFormatter() const
{
return *GetDoc().GetFormatTable();
}
ScStyleSheetPool& XclRoot::GetStyleSheetPool() const
{
return *GetDoc().GetStyleSheetPool();
}
ScRangeName& XclRoot::GetNamedRanges() const
{
return *GetDoc().GetRangeName();
}
SvStorage* XclRoot::GetRootStorage() const
{
return mpRD->pRootStorage;
}
ScEditEngineDefaulter& XclRoot::GetEditEngine() const
{
if( !mrData.mpEditEngine.get() )
{
mrData.mpEditEngine.reset( new ScEditEngineDefaulter( GetDoc().GetEnginePool() ) );
ScEditEngineDefaulter& rEE = *mrData.mpEditEngine;
rEE.SetRefMapMode( MAP_100TH_MM );
rEE.SetEditTextObjectPool( GetDoc().GetEditPool() );
rEE.SetUpdateMode( FALSE );
rEE.EnableUndo( FALSE );
rEE.SetControlWord( rEE.GetControlWord() & ~EE_CNTRL_ALLOWBIGOBJS );
}
return *mrData.mpEditEngine;
}
ScHeaderEditEngine& XclRoot::GetHFEditEngine() const
{
if( !mrData.mpHFEditEngine.get() )
{
mrData.mpHFEditEngine.reset( new ScHeaderEditEngine( EditEngine::CreatePool(), TRUE ) );
ScHeaderEditEngine& rEE = *mrData.mpHFEditEngine;
rEE.SetRefMapMode( MAP_TWIP ); // headers/footers use twips as default metric
rEE.SetUpdateMode( FALSE );
rEE.EnableUndo( FALSE );
rEE.SetControlWord( rEE.GetControlWord() & ~EE_CNTRL_ALLOWBIGOBJS );
// set Calc header/footer defaults
SfxItemSet* pEditSet = new SfxItemSet( rEE.GetEmptyItemSet() );
SfxItemSet aItemSet( *GetDoc().GetPool(), ATTR_PATTERN_START, ATTR_PATTERN_END );
ScPatternAttr::FillToEditItemSet( *pEditSet, aItemSet );
// FillToEditItemSet() adjusts font height to 1/100th mm, we need twips
pEditSet->Put( aItemSet.Get( ATTR_FONT_HEIGHT ), EE_CHAR_FONTHEIGHT );
pEditSet->Put( aItemSet.Get( ATTR_CJK_FONT_HEIGHT ), EE_CHAR_FONTHEIGHT_CJK );
pEditSet->Put( aItemSet.Get( ATTR_CTL_FONT_HEIGHT ), EE_CHAR_FONTHEIGHT_CTL );
rEE.SetDefaults( pEditSet ); // takes ownership
}
return *mrData.mpHFEditEngine;
}
EditEngine& XclRoot::GetDrawEditEngine() const
{
if( !mrData.mpDrawEditEng.get() )
{
mrData.mpDrawEditEng.reset( new EditEngine( &GetDoc().GetDrawLayer()->GetItemPool() ) );
EditEngine& rEE = *mrData.mpDrawEditEng;
rEE.SetRefMapMode( MAP_100TH_MM );
rEE.SetUpdateMode( FALSE );
rEE.EnableUndo( FALSE );
rEE.SetControlWord( rEE.GetControlWord() & ~EE_CNTRL_ALLOWBIGOBJS );
}
return *mrData.mpDrawEditEng;
}
XclTracer& XclRoot::GetTracer() const
{
return *mrData.mpTracer;
}
bool XclRoot::CheckCellAddress( const ScAddress& rPos, const ScAddress& rMaxPos ) const
{
bool bValid = (rPos.Col() <= rMaxPos.Col()) && (rPos.Row() <= rMaxPos.Row()) && (rPos.Tab() <= rMaxPos.Tab());
if( !bValid )
{
mrData.mbTruncated = true;
GetTracer().TraceInvalidAddress(rPos, rMaxPos);
}
return bValid;
}
bool XclRoot::CheckCellRange( ScRange& rRange, const ScAddress& rMaxPos ) const
{
rRange.Justify();
// check start position
bool bValidStart = CheckCellAddress( rRange.aStart, rMaxPos );
// check & correct end position
if( bValidStart )
{
CheckCellAddress( rRange.aEnd, rMaxPos );
if( rRange.aEnd.Col() > rMaxPos.Col() )
rRange.aEnd.SetCol( rMaxPos.Col() );
if( rRange.aEnd.Row() > rMaxPos.Row() )
rRange.aEnd.SetRow( rMaxPos.Row() );
if( rRange.aEnd.Tab() > rMaxPos.Tab() )
rRange.aEnd.SetTab( rMaxPos.Tab() );
}
return bValidStart;
}
void XclRoot::CheckCellRangeList( ScRangeList& rRanges, const ScAddress& rMaxPos ) const
{
sal_uInt32 nIndex = rRanges.Count();
while( nIndex )
{
--nIndex; // backwards to keep nIndex valid
ScRange* pRange = rRanges.GetObject( nIndex );
if( pRange && !CheckCellRange( *pRange, rMaxPos ) )
delete rRanges.Remove( nIndex );
}
}
// ============================================================================
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int i = 0, n = 0, j = 0, k = 0, tmp = 0;
char ch;
srand(time(NULL)); // initalizes seed value
cout<<"How many numbers would you like to have on your list?"<<endl;
cin>>n;
int *list = new int [n];
cout<<"Please enter the integers."<<endl;
for(i = 0; i < n; i++)
{
cin>>list[i];
}
cout<<"The list you have entered is ";
for(i = 0; i < n; i++)
{
cout<<list[i]<<" ";
}
cout<<".\n";
cout<<"Enter s to shuffle the list."<<endl;
while(1)
{
cin>>ch;
if(ch != 's') // shuffles the list every time the user enters s
break;
for(k = 0; k < n; k++) // shuffles the list n times
{
i = rand() % n; // selects two random positions
j = rand() % n;
tmp = list[i];
list[i] = list[j];
list[j] = tmp;
}
cout<<"The shuffled list is ";
for(i = 0; i < n; i++)
{
cout<<list[i]<<" ";
}
cout<<".\n";
cout<<"Enter s to shuffle again. Enter q to quit."<<endl;
}
cout<<"Thank you."<<endl;
return 0;
} // end<commit_msg>Update<commit_after>#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int i = 0, n = 0, j = 0, k = 0, tmp = 0;
char ch;
srand(time(NULL)); // initalizes seed value
cout<<"How many numbers would you like to have on your list?"<<endl;
cin>>n;
int *list = new int [n];
cout<<"Please enter the integers."<<endl;
for(i = 0; i < n; i++)
{
cin>>list[i];
}
cout<<"The list you have entered is ";
for(i = 0; i < n; i++)
{
cout<<list[i]<<" ";
}
cout<<".\n";
cout<<"Enter s to shuffle the list."<<endl;
while(1)
{
cin>>ch;
if(ch != 's') // shuffles the list every time the user enters s
break;
for(k = 0; k < n; k++) // shuffles the list n times
{
i = rand() % n; // selects two random positions
j = rand() % n;
tmp = list[i];
list[i] = list[j];
list[j] = tmp;
}
cout<<"The shuffled list is ";
for(i = 0; i < n; i++)
{
cout<<list[i]<<" ";
}
cout<<".\n";
cout<<"Enter s to shuffle again. Enter q to quit."<<endl;
}
cout<<"Thank you."<<endl;
delete list;
return 0;
} // end<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: csvcontrol.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hjs $ $Date: 2004-06-28 18:00:33 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
// ============================================================================
#ifndef _SC_CSVCONTROL_HXX
#include "csvcontrol.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SC_ACCESSIBLECSVCONTROL_HXX
#include "AccessibleCsvControl.hxx"
#endif
// ============================================================================
ScCsvLayoutData::ScCsvLayoutData() :
mnPosCount( 1 ),
mnPosOffset( 0 ),
mnWinWidth( 1 ),
mnHdrWidth( 0 ),
mnCharWidth( 1 ),
mnLineCount( 1 ),
mnLineOffset( 0 ),
mnWinHeight( 1 ),
mnHdrHeight( 0 ),
mnLineHeight( 1 ),
mnPosCursor( CSV_POS_INVALID ),
mnColCursor( 0 ),
mnNoRepaint( 0 ),
mbAppRTL( !!Application::GetSettings().GetLayoutRTL() )
{
}
ScCsvDiff ScCsvLayoutData::GetDiff( const ScCsvLayoutData& rData ) const
{
ScCsvDiff nRet = CSV_DIFF_EQUAL;
if( mnPosCount != rData.mnPosCount ) nRet |= CSV_DIFF_POSCOUNT;
if( mnPosOffset != rData.mnPosOffset ) nRet |= CSV_DIFF_POSOFFSET;
if( mnHdrWidth != rData.mnHdrWidth ) nRet |= CSV_DIFF_HDRWIDTH;
if( mnCharWidth != rData.mnCharWidth ) nRet |= CSV_DIFF_CHARWIDTH;
if( mnLineCount != rData.mnLineCount ) nRet |= CSV_DIFF_LINECOUNT;
if( mnLineOffset != rData.mnLineOffset ) nRet |= CSV_DIFF_LINEOFFSET;
if( mnHdrHeight != rData.mnHdrHeight ) nRet |= CSV_DIFF_HDRHEIGHT;
if( mnLineHeight != rData.mnLineHeight ) nRet |= CSV_DIFF_LINEHEIGHT;
if( mnPosCursor != rData.mnPosCursor ) nRet |= CSV_DIFF_RULERCURSOR;
if( mnColCursor != rData.mnColCursor ) nRet |= CSV_DIFF_GRIDCURSOR;
return nRet;
}
// ============================================================================
ScCsvControl::ScCsvControl( ScCsvControl& rParent ) :
Control( &rParent, WB_TABSTOP | WB_NODIALOGCONTROL ),
mrData( rParent.GetLayoutData() ),
mpAccessible( NULL ),
mbValidGfx( false )
{
}
ScCsvControl::ScCsvControl( Window* pParent, const ScCsvLayoutData& rData, WinBits nStyle ) :
Control( pParent, nStyle ),
mrData( rData ),
mpAccessible( NULL ),
mbValidGfx( false )
{
}
ScCsvControl::ScCsvControl( Window* pParent, const ScCsvLayoutData& rData, const ResId& rResId ) :
Control( pParent, rResId ),
mrData( rData ),
mpAccessible( NULL ),
mbValidGfx( false )
{
}
ScCsvControl::~ScCsvControl()
{
if( mpAccessible )
mpAccessible->dispose();
}
// event handling -------------------------------------------------------------
void ScCsvControl::GetFocus()
{
Control::GetFocus();
AccSendFocusEvent( true );
}
void ScCsvControl::LoseFocus()
{
Control::LoseFocus();
AccSendFocusEvent( false );
}
void ScCsvControl::AccSendFocusEvent( bool bFocused )
{
if( mpAccessible )
mpAccessible->SendFocusEvent( bFocused );
}
void ScCsvControl::AccSendCaretEvent()
{
if( mpAccessible )
mpAccessible->SendCaretEvent();
}
void ScCsvControl::AccSendVisibleEvent()
{
if( mpAccessible )
mpAccessible->SendVisibleEvent();
}
void ScCsvControl::AccSendSelectionEvent()
{
if( mpAccessible )
mpAccessible->SendSelectionEvent();
}
void ScCsvControl::AccSendTableUpdateEvent( sal_uInt32 nFirstColumn, sal_uInt32 nLastColumn, bool bAllRows )
{
if( mpAccessible )
mpAccessible->SendTableUpdateEvent( nFirstColumn, nLastColumn, bAllRows );
}
void ScCsvControl::AccSendInsertColumnEvent( sal_uInt32 nFirstColumn, sal_uInt32 nLastColumn )
{
if( mpAccessible )
mpAccessible->SendInsertColumnEvent( nFirstColumn, nLastColumn );
}
void ScCsvControl::AccSendRemoveColumnEvent( sal_uInt32 nFirstColumn, sal_uInt32 nLastColumn )
{
if( mpAccessible )
mpAccessible->SendRemoveColumnEvent( nFirstColumn, nLastColumn );
}
// repaint helpers ------------------------------------------------------------
void ScCsvControl::Repaint( bool bInvalidate )
{
if( bInvalidate )
InvalidateGfx();
if( !IsNoRepaint() )
Execute( CSVCMD_REPAINT );
}
void ScCsvControl::DisableRepaint()
{
++mrData.mnNoRepaint;
}
void ScCsvControl::EnableRepaint( bool bInvalidate )
{
DBG_ASSERT( IsNoRepaint(), "ScCsvControl::EnableRepaint - invalid call" );
--mrData.mnNoRepaint;
Repaint( bInvalidate );
}
// command handling -----------------------------------------------------------
void ScCsvControl::Execute( ScCsvCmdType eType, sal_Int32 nParam1, sal_Int32 nParam2 )
{
maCmd.Set( eType, nParam1, nParam2 );
maCmdHdl.Call( this );
}
// layout helpers -------------------------------------------------------------
sal_Int32 ScCsvControl::GetVisPosCount() const
{
return (mrData.mnWinWidth - GetHdrWidth()) / GetCharWidth();
}
sal_Int32 ScCsvControl::GetMaxPosOffset() const
{
return Max( GetPosCount() - GetVisPosCount() + 2L, 0L );
}
bool ScCsvControl::IsValidSplitPos( sal_Int32 nPos ) const
{
return (0 < nPos) && (nPos < GetPosCount() );
}
bool ScCsvControl::IsVisibleSplitPos( sal_Int32 nPos ) const
{
return IsValidSplitPos( nPos ) && (GetFirstVisPos() <= nPos) && (nPos <= GetLastVisPos());
}
sal_Int32 ScCsvControl::GetHdrX() const
{
return IsRTL() ? (mrData.mnWinWidth - GetHdrWidth()) : 0;
}
sal_Int32 ScCsvControl::GetFirstX() const
{
return IsRTL() ? 0 : GetHdrWidth();
}
sal_Int32 ScCsvControl::GetLastX() const
{
return mrData.mnWinWidth - (IsRTL() ? GetHdrWidth() : 0) - 1;
}
sal_Int32 ScCsvControl::GetX( sal_Int32 nPos ) const
{
return GetFirstX() + (nPos - GetFirstVisPos()) * GetCharWidth();
}
sal_Int32 ScCsvControl::GetPosFromX( sal_Int32 nX ) const
{
return (nX - GetFirstX() + GetCharWidth() / 2) / GetCharWidth() + GetFirstVisPos();
}
sal_Int32 ScCsvControl::GetVisLineCount() const
{
return (mrData.mnWinHeight - GetHdrHeight() - 2) / GetLineHeight() + 1;
}
sal_Int32 ScCsvControl::GetLastVisLine() const
{
return Min( GetFirstVisLine() + GetVisLineCount(), GetLineCount() ) - 1;
}
sal_Int32 ScCsvControl::GetMaxLineOffset() const
{
return Max( GetLineCount() - GetVisLineCount() + 1L, 0L );
}
bool ScCsvControl::IsValidLine( sal_Int32 nLine ) const
{
return (0 <= nLine) && (nLine < GetLineCount());
}
bool ScCsvControl::IsVisibleLine( sal_Int32 nLine ) const
{
return IsValidLine( nLine ) && (GetFirstVisLine() <= nLine) && (nLine <= GetLastVisLine());
}
sal_Int32 ScCsvControl::GetY( sal_Int32 nLine ) const
{
return GetHdrHeight() + (nLine - GetFirstVisLine()) * GetLineHeight();
}
sal_Int32 ScCsvControl::GetLineFromY( sal_Int32 nY ) const
{
return (nY - GetHdrHeight()) / GetLineHeight() + GetFirstVisLine();
}
// static helpers -------------------------------------------------------------
void ScCsvControl::ImplInvertRect( OutputDevice& rOutDev, const Rectangle& rRect )
{
rOutDev.Push( PUSH_LINECOLOR | PUSH_FILLCOLOR | PUSH_RASTEROP );
rOutDev.SetLineColor( Color( COL_BLACK ) );
rOutDev.SetFillColor( Color( COL_BLACK ) );
rOutDev.SetRasterOp( ROP_INVERT );
rOutDev.DrawRect( rRect );
rOutDev.Pop();
}
ScMoveMode ScCsvControl::GetHorzDirection( sal_uInt16 nCode, bool bHomeEnd )
{
switch( nCode )
{
case KEY_LEFT: return MOVE_PREV;
case KEY_RIGHT: return MOVE_NEXT;
}
if( bHomeEnd ) switch( nCode )
{
case KEY_HOME: return MOVE_FIRST;
case KEY_END: return MOVE_LAST;
}
return MOVE_NONE;
}
ScMoveMode ScCsvControl::GetVertDirection( sal_uInt16 nCode, bool bHomeEnd )
{
switch( nCode )
{
case KEY_UP: return MOVE_PREV;
case KEY_DOWN: return MOVE_NEXT;
case KEY_PAGEUP: return MOVE_PREVPAGE;
case KEY_PAGEDOWN: return MOVE_NEXTPAGE;
}
if( bHomeEnd ) switch( nCode )
{
case KEY_HOME: return MOVE_FIRST;
case KEY_END: return MOVE_LAST;
}
return MOVE_NONE;
}
// accessibility --------------------------------------------------------------
ScCsvControl::XAccessibleRef ScCsvControl::CreateAccessible()
{
mpAccessible = ImplCreateAccessible();
mxAccessible = mpAccessible;
return mxAccessible;
}
// ============================================================================
<commit_msg>INTEGRATION: CWS ooo19126 (1.7.434); FILE MERGED 2005/09/05 15:04:10 rt 1.7.434.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: csvcontrol.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-08 20:31:43 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
// ============================================================================
#ifndef _SC_CSVCONTROL_HXX
#include "csvcontrol.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SC_ACCESSIBLECSVCONTROL_HXX
#include "AccessibleCsvControl.hxx"
#endif
// ============================================================================
ScCsvLayoutData::ScCsvLayoutData() :
mnPosCount( 1 ),
mnPosOffset( 0 ),
mnWinWidth( 1 ),
mnHdrWidth( 0 ),
mnCharWidth( 1 ),
mnLineCount( 1 ),
mnLineOffset( 0 ),
mnWinHeight( 1 ),
mnHdrHeight( 0 ),
mnLineHeight( 1 ),
mnPosCursor( CSV_POS_INVALID ),
mnColCursor( 0 ),
mnNoRepaint( 0 ),
mbAppRTL( !!Application::GetSettings().GetLayoutRTL() )
{
}
ScCsvDiff ScCsvLayoutData::GetDiff( const ScCsvLayoutData& rData ) const
{
ScCsvDiff nRet = CSV_DIFF_EQUAL;
if( mnPosCount != rData.mnPosCount ) nRet |= CSV_DIFF_POSCOUNT;
if( mnPosOffset != rData.mnPosOffset ) nRet |= CSV_DIFF_POSOFFSET;
if( mnHdrWidth != rData.mnHdrWidth ) nRet |= CSV_DIFF_HDRWIDTH;
if( mnCharWidth != rData.mnCharWidth ) nRet |= CSV_DIFF_CHARWIDTH;
if( mnLineCount != rData.mnLineCount ) nRet |= CSV_DIFF_LINECOUNT;
if( mnLineOffset != rData.mnLineOffset ) nRet |= CSV_DIFF_LINEOFFSET;
if( mnHdrHeight != rData.mnHdrHeight ) nRet |= CSV_DIFF_HDRHEIGHT;
if( mnLineHeight != rData.mnLineHeight ) nRet |= CSV_DIFF_LINEHEIGHT;
if( mnPosCursor != rData.mnPosCursor ) nRet |= CSV_DIFF_RULERCURSOR;
if( mnColCursor != rData.mnColCursor ) nRet |= CSV_DIFF_GRIDCURSOR;
return nRet;
}
// ============================================================================
ScCsvControl::ScCsvControl( ScCsvControl& rParent ) :
Control( &rParent, WB_TABSTOP | WB_NODIALOGCONTROL ),
mrData( rParent.GetLayoutData() ),
mpAccessible( NULL ),
mbValidGfx( false )
{
}
ScCsvControl::ScCsvControl( Window* pParent, const ScCsvLayoutData& rData, WinBits nStyle ) :
Control( pParent, nStyle ),
mrData( rData ),
mpAccessible( NULL ),
mbValidGfx( false )
{
}
ScCsvControl::ScCsvControl( Window* pParent, const ScCsvLayoutData& rData, const ResId& rResId ) :
Control( pParent, rResId ),
mrData( rData ),
mpAccessible( NULL ),
mbValidGfx( false )
{
}
ScCsvControl::~ScCsvControl()
{
if( mpAccessible )
mpAccessible->dispose();
}
// event handling -------------------------------------------------------------
void ScCsvControl::GetFocus()
{
Control::GetFocus();
AccSendFocusEvent( true );
}
void ScCsvControl::LoseFocus()
{
Control::LoseFocus();
AccSendFocusEvent( false );
}
void ScCsvControl::AccSendFocusEvent( bool bFocused )
{
if( mpAccessible )
mpAccessible->SendFocusEvent( bFocused );
}
void ScCsvControl::AccSendCaretEvent()
{
if( mpAccessible )
mpAccessible->SendCaretEvent();
}
void ScCsvControl::AccSendVisibleEvent()
{
if( mpAccessible )
mpAccessible->SendVisibleEvent();
}
void ScCsvControl::AccSendSelectionEvent()
{
if( mpAccessible )
mpAccessible->SendSelectionEvent();
}
void ScCsvControl::AccSendTableUpdateEvent( sal_uInt32 nFirstColumn, sal_uInt32 nLastColumn, bool bAllRows )
{
if( mpAccessible )
mpAccessible->SendTableUpdateEvent( nFirstColumn, nLastColumn, bAllRows );
}
void ScCsvControl::AccSendInsertColumnEvent( sal_uInt32 nFirstColumn, sal_uInt32 nLastColumn )
{
if( mpAccessible )
mpAccessible->SendInsertColumnEvent( nFirstColumn, nLastColumn );
}
void ScCsvControl::AccSendRemoveColumnEvent( sal_uInt32 nFirstColumn, sal_uInt32 nLastColumn )
{
if( mpAccessible )
mpAccessible->SendRemoveColumnEvent( nFirstColumn, nLastColumn );
}
// repaint helpers ------------------------------------------------------------
void ScCsvControl::Repaint( bool bInvalidate )
{
if( bInvalidate )
InvalidateGfx();
if( !IsNoRepaint() )
Execute( CSVCMD_REPAINT );
}
void ScCsvControl::DisableRepaint()
{
++mrData.mnNoRepaint;
}
void ScCsvControl::EnableRepaint( bool bInvalidate )
{
DBG_ASSERT( IsNoRepaint(), "ScCsvControl::EnableRepaint - invalid call" );
--mrData.mnNoRepaint;
Repaint( bInvalidate );
}
// command handling -----------------------------------------------------------
void ScCsvControl::Execute( ScCsvCmdType eType, sal_Int32 nParam1, sal_Int32 nParam2 )
{
maCmd.Set( eType, nParam1, nParam2 );
maCmdHdl.Call( this );
}
// layout helpers -------------------------------------------------------------
sal_Int32 ScCsvControl::GetVisPosCount() const
{
return (mrData.mnWinWidth - GetHdrWidth()) / GetCharWidth();
}
sal_Int32 ScCsvControl::GetMaxPosOffset() const
{
return Max( GetPosCount() - GetVisPosCount() + 2L, 0L );
}
bool ScCsvControl::IsValidSplitPos( sal_Int32 nPos ) const
{
return (0 < nPos) && (nPos < GetPosCount() );
}
bool ScCsvControl::IsVisibleSplitPos( sal_Int32 nPos ) const
{
return IsValidSplitPos( nPos ) && (GetFirstVisPos() <= nPos) && (nPos <= GetLastVisPos());
}
sal_Int32 ScCsvControl::GetHdrX() const
{
return IsRTL() ? (mrData.mnWinWidth - GetHdrWidth()) : 0;
}
sal_Int32 ScCsvControl::GetFirstX() const
{
return IsRTL() ? 0 : GetHdrWidth();
}
sal_Int32 ScCsvControl::GetLastX() const
{
return mrData.mnWinWidth - (IsRTL() ? GetHdrWidth() : 0) - 1;
}
sal_Int32 ScCsvControl::GetX( sal_Int32 nPos ) const
{
return GetFirstX() + (nPos - GetFirstVisPos()) * GetCharWidth();
}
sal_Int32 ScCsvControl::GetPosFromX( sal_Int32 nX ) const
{
return (nX - GetFirstX() + GetCharWidth() / 2) / GetCharWidth() + GetFirstVisPos();
}
sal_Int32 ScCsvControl::GetVisLineCount() const
{
return (mrData.mnWinHeight - GetHdrHeight() - 2) / GetLineHeight() + 1;
}
sal_Int32 ScCsvControl::GetLastVisLine() const
{
return Min( GetFirstVisLine() + GetVisLineCount(), GetLineCount() ) - 1;
}
sal_Int32 ScCsvControl::GetMaxLineOffset() const
{
return Max( GetLineCount() - GetVisLineCount() + 1L, 0L );
}
bool ScCsvControl::IsValidLine( sal_Int32 nLine ) const
{
return (0 <= nLine) && (nLine < GetLineCount());
}
bool ScCsvControl::IsVisibleLine( sal_Int32 nLine ) const
{
return IsValidLine( nLine ) && (GetFirstVisLine() <= nLine) && (nLine <= GetLastVisLine());
}
sal_Int32 ScCsvControl::GetY( sal_Int32 nLine ) const
{
return GetHdrHeight() + (nLine - GetFirstVisLine()) * GetLineHeight();
}
sal_Int32 ScCsvControl::GetLineFromY( sal_Int32 nY ) const
{
return (nY - GetHdrHeight()) / GetLineHeight() + GetFirstVisLine();
}
// static helpers -------------------------------------------------------------
void ScCsvControl::ImplInvertRect( OutputDevice& rOutDev, const Rectangle& rRect )
{
rOutDev.Push( PUSH_LINECOLOR | PUSH_FILLCOLOR | PUSH_RASTEROP );
rOutDev.SetLineColor( Color( COL_BLACK ) );
rOutDev.SetFillColor( Color( COL_BLACK ) );
rOutDev.SetRasterOp( ROP_INVERT );
rOutDev.DrawRect( rRect );
rOutDev.Pop();
}
ScMoveMode ScCsvControl::GetHorzDirection( sal_uInt16 nCode, bool bHomeEnd )
{
switch( nCode )
{
case KEY_LEFT: return MOVE_PREV;
case KEY_RIGHT: return MOVE_NEXT;
}
if( bHomeEnd ) switch( nCode )
{
case KEY_HOME: return MOVE_FIRST;
case KEY_END: return MOVE_LAST;
}
return MOVE_NONE;
}
ScMoveMode ScCsvControl::GetVertDirection( sal_uInt16 nCode, bool bHomeEnd )
{
switch( nCode )
{
case KEY_UP: return MOVE_PREV;
case KEY_DOWN: return MOVE_NEXT;
case KEY_PAGEUP: return MOVE_PREVPAGE;
case KEY_PAGEDOWN: return MOVE_NEXTPAGE;
}
if( bHomeEnd ) switch( nCode )
{
case KEY_HOME: return MOVE_FIRST;
case KEY_END: return MOVE_LAST;
}
return MOVE_NONE;
}
// accessibility --------------------------------------------------------------
ScCsvControl::XAccessibleRef ScCsvControl::CreateAccessible()
{
mpAccessible = ImplCreateAccessible();
mxAccessible = mpAccessible;
return mxAccessible;
}
// ============================================================================
<|endoftext|> |
<commit_before>
//@HEADER
// ************************************************************************
//
// HPCG: Simple Conjugate Gradient Benchmark Code
// Questions? Contact Michael A. Heroux (maherou@sandia.gov)
//
// ************************************************************************
//@HEADER
// Changelog
//
// Version 0.3
// - Added timing of setup time for sparse MV
// - Corrected percentages reported for sparse MV with overhead
//
/////////////////////////////////////////////////////////////////////////
// Main routine of a program that calls the HPCG conjugate gradient
// solver to solve the problem, and then prints results.
#include <fstream>
#include <iostream>
#ifdef DEBUG
using std::cin;
#endif
using std::endl;
#include <cstdlib>
#include <vector>
#include "hpcg.hpp"
#ifndef HPCG_NOMPI
#include <mpi.h> // If this routine is not compiled with HPCG_NOMPI
#endif
#ifndef HPCG_NOOPENMP
#include <omp.h> // If this routine is not compiled with HPCG_NOOPENMP
#endif
#include "GenerateGeometry.hpp"
#include "GenerateProblem.hpp"
#include "SetupHalo.hpp"
#include "ExchangeHalo.hpp"
#include "OptimizeProblem.hpp"
#include "WriteProblem.hpp"
#include "ReportResults.hpp"
#include "mytimer.hpp"
#include "spmvref.hpp"
#include "symgsref.hpp"
#include "ComputeResidual.hpp"
#include "CG.hpp"
#include "CGref.hpp"
#include "Geometry.hpp"
#include "SparseMatrix.hpp"
#include "CGData.hpp"
int main(int argc, char *argv[]) {
#ifndef HPCG_NOMPI
MPI_Init(&argc, &argv);
int size, rank; // Number of MPI processes, My process ID
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#else
int size = 1; // Serial case (not using MPI)
int rank = 0;
#endif
HPCG_Params params;
HPCG_Init(&argc, &argv, ¶ms);
int numThreads = 1;
#ifndef HPCG_NOOPENMP
#pragma omp parallel
numThreads = omp_get_num_threads();
#endif
#ifdef DEBUG
if (size < 100) HPCG_fout << "Process "<<rank<<" of "<<size<<" is alive with " << numThreads << " threads." <<endl;
#endif
#ifdef DEBUG
if (rank==0)
{
int junk = 0;
HPCG_fout << "Press enter to continue"<< endl;
cin >> junk;
}
#ifndef HPCG_NOMPI
MPI_Barrier(MPI_COMM_WORLD);
#endif
#endif
#ifdef NO_PRECONDITIONER
bool doPreconditioning = false;
#else
bool doPreconditioning = true;
#endif
local_int_t nx,ny,nz;
nx = (local_int_t)params.nx;
ny = (local_int_t)params.ny;
nz = (local_int_t)params.nz;
#ifdef HPCG_DEBUG
double t1 = mytimer();
#endif
Geometry geom;
GenerateGeometry(size, rank, numThreads, nx, ny, nz, geom);
SparseMatrix A;
CGData data;
double *x, *b, *xexact;
GenerateProblem(geom, A, &x, &b, &xexact);
SetupHalo(geom, A);
initializeCGData(A, data);
#ifdef HPCG_DEBUG
if (rank==0) HPCG_fout << "Total setup time (sec) = " << mytimer() - t1 << endl;
#endif
//if (geom.size==1) WriteProblem(A, x, b, xexact);
// Use this array for collecting timing information
std::vector< double > times(9,0.0);
// Call user-tunable set up function.
double t7 = mytimer(); OptimizeProblem(geom, A, data, x, b, xexact); t7 = mytimer() - t7;
times[7] = t7;
// Call Reference SPMV and SYMGS. Compute Optimization time as ratio of times in these routines
local_int_t nrow = A.localNumberOfRows;
local_int_t ncol = A.localNumberOfColumns;
double * x_overlap = new double [ncol]; // Overlapped copy of x vector
double * b_computed = new double [nrow]; // Computed RHS vector
// Test symmetry of matrix
// First load vector with random values
for (int i=0; i<nrow; ++i) {
x_overlap[i] = ((double) rand() / (RAND_MAX)) + 1;
}
int ierr = 0;
int numberOfCalls = 10;
double t_begin = mytimer();
for (int i=0; i< numberOfCalls; ++i) {
#ifndef HPCG_NOMPI
ExchangeHalo(A,x_overlap);
#endif
ierr = spmvref(A, x_overlap, b_computed); // b_computed = A*x_overlap
if (ierr) HPCG_fout << "Error in call to spmv: " << ierr << ".\n" << endl;
ierr = symgsref(A, x_overlap, b_computed); // b_computed = Minv*y_overlap
if (ierr) HPCG_fout << "Error in call to symgs: " << ierr << ".\n" << endl;
}
times[8] = (mytimer() - t_begin)/((double) numberOfCalls); // Total time divided by number of calls.
int global_failure = 0; // assume all is well: no failures
int niters = 0;
int totalNiters = 0;
double normr = 0.0;
double normr0 = 0.0;
int maxIters = 50;
/* Compute the residual reduction for the natural ordering and reference kernels. */
std::vector< double > ref_times(9,0.0);
double tolerance = 0.0; // Set tolerance to zero to make all runs do max_iter iterations
int err_count = 0;
for (int i=0; i< numberOfCalls; ++i) {
for (int j=0; j< A.localNumberOfRows; ++j) x[j] = 0.0; // start x at all zeros
ierr = CGref( geom, A, data, b, x, maxIters, tolerance, niters, normr, normr0, &ref_times[0], true);
if (ierr) ++err_count; // count the number of errors in CG
totalNiters += niters;
}
if (rank == 0 && err_count) HPCG_fout << err_count << " error(s) in call(s) to reference CG." << endl;
double ref_tolerance = normr / normr0;
int ref_iters = niters;
totalNiters = 0;
niters = 0;
normr = 0.0;
normr0 = 0.0;
err_count = 0;
int tolerance_failures = 0;
int opt_maxIters = 10*maxIters;
int opt_iters = 0;
double opt_worst_time = 0.0;
/* Compute the residual reduction and residual count for the user ordering and optimized kernels. */
for (int i=0; i< numberOfCalls; ++i) {
for (int j=0; j< A.localNumberOfRows; ++j) x[j] = 0.0; // start x at all zeros
ierr = CG( geom, A, data, b, x, opt_maxIters, ref_tolerance, niters, normr, normr0, ×[0], true);
if (ierr) ++err_count; // count the number of errors in CG
if (normr / normr0 > ref_tolerance) ++tolerance_failures; // the number of failures to reduce residual
// pick the largest number of iterations to guarantee convergence
if (niters > opt_iters) opt_iters = niters;
if (times[0] > opt_worst_time) opt_worst_time = times[0];
totalNiters += niters;
}
if (rank == 0 && err_count) HPCG_fout << err_count << " error(s) in call(s) to optimized CG." << endl;
if (tolerance_failures) {
global_failure = 1;
if (rank == 0)
HPCG_fout << "Failed to reduce the residual " << tolerance_failures << " times." << endl;
}
double total_runtime = 60; // run for at least one minute
numberOfCalls = int(total_runtime / opt_worst_time);
if (numberOfCalls < 1) numberOfCalls = 1; // run CG at least once
for (int i=0; i< numberOfCalls; ++i) {
for (int j=0; j< A.localNumberOfRows; ++j) x[j] = 0.0; // Zero out x
ierr = CG( geom, A, data, b, x, maxIters, tolerance, niters, normr, normr0, ×[0], doPreconditioning);
if (ierr) HPCG_fout << "Error in call to CG: " << ierr << ".\n" << endl;
if (rank==0) HPCG_fout << "Call [" << i << "] Scaled Residual [" << normr/normr0 << "]" << endl;
totalNiters += niters;
}
// Compute difference between known exact solution and computed solution
// All processors are needed here.
#ifdef DEBUG
double residual = 0;
ierr = ComputeResidual(A.localNumberOfRows, x, xexact, &residual);
if (ierr) HPCG_fout << "Error in call to compute_residual: " << ierr << ".\n" << endl;
if (rank==0)
HPCG_fout << "Difference between computed and exact = " << residual << ".\n" << endl;
#endif
// Report results to YAML file
ReportResults(geom, A, totalNiters, normr/normr0, ×[0]);
// Clean up
destroyMatrix(A);
destroyCGData(data);
delete [] x;
delete [] b;
delete [] xexact;
HPCG_Finalize();
// Finish up
#ifndef HPCG_NOMPI
MPI_Finalize();
#endif
return 0 ;
}
<commit_msg>Fixed a bug: I should have not been using cumulative time.<commit_after>
//@HEADER
// ************************************************************************
//
// HPCG: Simple Conjugate Gradient Benchmark Code
// Questions? Contact Michael A. Heroux (maherou@sandia.gov)
//
// ************************************************************************
//@HEADER
// Changelog
//
// Version 0.3
// - Added timing of setup time for sparse MV
// - Corrected percentages reported for sparse MV with overhead
//
/////////////////////////////////////////////////////////////////////////
// Main routine of a program that calls the HPCG conjugate gradient
// solver to solve the problem, and then prints results.
#include <fstream>
#include <iostream>
#ifdef DEBUG
using std::cin;
#endif
using std::endl;
#include <cstdlib>
#include <vector>
#include "hpcg.hpp"
#ifndef HPCG_NOMPI
#include <mpi.h> // If this routine is not compiled with HPCG_NOMPI
#endif
#ifndef HPCG_NOOPENMP
#include <omp.h> // If this routine is not compiled with HPCG_NOOPENMP
#endif
#include "GenerateGeometry.hpp"
#include "GenerateProblem.hpp"
#include "SetupHalo.hpp"
#include "ExchangeHalo.hpp"
#include "OptimizeProblem.hpp"
#include "WriteProblem.hpp"
#include "ReportResults.hpp"
#include "mytimer.hpp"
#include "spmvref.hpp"
#include "symgsref.hpp"
#include "ComputeResidual.hpp"
#include "CG.hpp"
#include "CGref.hpp"
#include "Geometry.hpp"
#include "SparseMatrix.hpp"
#include "CGData.hpp"
int main(int argc, char *argv[]) {
#ifndef HPCG_NOMPI
MPI_Init(&argc, &argv);
int size, rank; // Number of MPI processes, My process ID
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#else
int size = 1; // Serial case (not using MPI)
int rank = 0;
#endif
HPCG_Params params;
HPCG_Init(&argc, &argv, ¶ms);
int numThreads = 1;
#ifndef HPCG_NOOPENMP
#pragma omp parallel
numThreads = omp_get_num_threads();
#endif
#ifdef DEBUG
if (size < 100) HPCG_fout << "Process "<<rank<<" of "<<size<<" is alive with " << numThreads << " threads." <<endl;
#endif
#ifdef DEBUG
if (rank==0)
{
int junk = 0;
HPCG_fout << "Press enter to continue"<< endl;
cin >> junk;
}
#ifndef HPCG_NOMPI
MPI_Barrier(MPI_COMM_WORLD);
#endif
#endif
#ifdef NO_PRECONDITIONER
bool doPreconditioning = false;
#else
bool doPreconditioning = true;
#endif
local_int_t nx,ny,nz;
nx = (local_int_t)params.nx;
ny = (local_int_t)params.ny;
nz = (local_int_t)params.nz;
#ifdef HPCG_DEBUG
double t1 = mytimer();
#endif
Geometry geom;
GenerateGeometry(size, rank, numThreads, nx, ny, nz, geom);
SparseMatrix A;
CGData data;
double *x, *b, *xexact;
GenerateProblem(geom, A, &x, &b, &xexact);
SetupHalo(geom, A);
initializeCGData(A, data);
#ifdef HPCG_DEBUG
if (rank==0) HPCG_fout << "Total setup time (sec) = " << mytimer() - t1 << endl;
#endif
//if (geom.size==1) WriteProblem(A, x, b, xexact);
// Use this array for collecting timing information
std::vector< double > times(9,0.0);
// Call user-tunable set up function.
double t7 = mytimer(); OptimizeProblem(geom, A, data, x, b, xexact); t7 = mytimer() - t7;
times[7] = t7;
// Call Reference SPMV and SYMGS. Compute Optimization time as ratio of times in these routines
local_int_t nrow = A.localNumberOfRows;
local_int_t ncol = A.localNumberOfColumns;
double * x_overlap = new double [ncol]; // Overlapped copy of x vector
double * b_computed = new double [nrow]; // Computed RHS vector
// Test symmetry of matrix
// First load vector with random values
for (int i=0; i<nrow; ++i) {
x_overlap[i] = ((double) rand() / (RAND_MAX)) + 1;
}
int ierr = 0;
int numberOfCalls = 10;
double t_begin = mytimer();
for (int i=0; i< numberOfCalls; ++i) {
#ifndef HPCG_NOMPI
ExchangeHalo(A,x_overlap);
#endif
ierr = spmvref(A, x_overlap, b_computed); // b_computed = A*x_overlap
if (ierr) HPCG_fout << "Error in call to spmv: " << ierr << ".\n" << endl;
ierr = symgsref(A, x_overlap, b_computed); // b_computed = Minv*y_overlap
if (ierr) HPCG_fout << "Error in call to symgs: " << ierr << ".\n" << endl;
}
times[8] = (mytimer() - t_begin)/((double) numberOfCalls); // Total time divided by number of calls.
int global_failure = 0; // assume all is well: no failures
int niters = 0;
int totalNiters = 0;
double normr = 0.0;
double normr0 = 0.0;
int maxIters = 50;
/* Compute the residual reduction for the natural ordering and reference kernels. */
std::vector< double > ref_times(9,0.0);
double tolerance = 0.0; // Set tolerance to zero to make all runs do max_iter iterations
int err_count = 0;
for (int i=0; i< numberOfCalls; ++i) {
for (int j=0; j< A.localNumberOfRows; ++j) x[j] = 0.0; // start x at all zeros
ierr = CGref( geom, A, data, b, x, maxIters, tolerance, niters, normr, normr0, &ref_times[0], true);
if (ierr) ++err_count; // count the number of errors in CG
totalNiters += niters;
}
if (rank == 0 && err_count) HPCG_fout << err_count << " error(s) in call(s) to reference CG." << endl;
double ref_tolerance = normr / normr0;
int ref_iters = niters;
totalNiters = 0;
niters = 0;
normr = 0.0;
normr0 = 0.0;
err_count = 0;
int tolerance_failures = 0;
int opt_maxIters = 10*maxIters;
int opt_iters = 0;
double opt_worst_time = 0.0;
/* Compute the residual reduction and residual count for the user ordering and optimized kernels. */
for (int i=0; i< numberOfCalls; ++i) {
for (int j=0; j< A.localNumberOfRows; ++j) x[j] = 0.0; // start x at all zeros
double last_cummulative_time = times[0];
ierr = CG( geom, A, data, b, x, opt_maxIters, ref_tolerance, niters, normr, normr0, ×[0], true);
if (ierr) ++err_count; // count the number of errors in CG
if (normr / normr0 > ref_tolerance) ++tolerance_failures; // the number of failures to reduce residual
// pick the largest number of iterations to guarantee convergence
if (niters > opt_iters) opt_iters = niters;
double current_time = times[0] - last_cummulative_time;
if (current_time > opt_worst_time) opt_worst_time = current_time;
totalNiters += niters;
}
if (rank == 0 && err_count) HPCG_fout << err_count << " error(s) in call(s) to optimized CG." << endl;
if (tolerance_failures) {
global_failure = 1;
if (rank == 0)
HPCG_fout << "Failed to reduce the residual " << tolerance_failures << " times." << endl;
}
double total_runtime = 60; // run for at least one minute
numberOfCalls = int(total_runtime / opt_worst_time);
if (numberOfCalls < 1) numberOfCalls = 1; // run CG at least once
for (int i=0; i< numberOfCalls; ++i) {
for (int j=0; j< A.localNumberOfRows; ++j) x[j] = 0.0; // Zero out x
ierr = CG( geom, A, data, b, x, maxIters, tolerance, niters, normr, normr0, ×[0], doPreconditioning);
if (ierr) HPCG_fout << "Error in call to CG: " << ierr << ".\n" << endl;
if (rank==0) HPCG_fout << "Call [" << i << "] Scaled Residual [" << normr/normr0 << "]" << endl;
totalNiters += niters;
}
// Compute difference between known exact solution and computed solution
// All processors are needed here.
#ifdef DEBUG
double residual = 0;
ierr = ComputeResidual(A.localNumberOfRows, x, xexact, &residual);
if (ierr) HPCG_fout << "Error in call to compute_residual: " << ierr << ".\n" << endl;
if (rank==0)
HPCG_fout << "Difference between computed and exact = " << residual << ".\n" << endl;
#endif
// Report results to YAML file
ReportResults(geom, A, totalNiters, normr/normr0, ×[0]);
// Clean up
destroyMatrix(A);
destroyCGData(data);
delete [] x;
delete [] b;
delete [] xexact;
HPCG_Finalize();
// Finish up
#ifndef HPCG_NOMPI
MPI_Finalize();
#endif
return 0 ;
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/ocmb/explorer/procedures/hwp/memory/lib/i2c/exp_i2c.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file exp_i2c.H
/// @brief explorer I2C utility function declarations
///
// *HWP HWP Owner: Andre A. Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _MSS_EXP_I2C_H_
#define _MSS_EXP_I2C_H_
#include <fapi2.H>
#include <i2c_access.H>
#include <vector>
#include <lib/i2c/exp_i2c_fields.H>
namespace mss
{
namespace exp
{
namespace i2c
{
namespace check
{
///
/// @brief Checks the I2c explorer status codes
/// @param[in] i_target the OCMB target
/// @param[in] i_cmd_id the command ID
/// @param[in] i_data data to check from EXP_FW_STATUS
///
inline fapi2::ReturnCode status_code( const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
const uint8_t i_cmd_id,
const std::vector<uint8_t>& i_data )
{
// Set to a high number to make sure check for SUCCESS (== 0) isn't a fluke
uint8_t l_status = ~(0);
FAPI_TRY( status::get_status_code(i_target, i_data, l_status) );
// Technically many cmds have their own status code decoding..but SUCCESS is always 0.
// If it's anything else we can just look up the status code
FAPI_ASSERT( l_status == status_codes::SUCCESS,
fapi2::MSS_EXP_STATUS_CODE_UNSUCCESSFUL().
set_TARGET(i_target).
set_STATUS_CODE(l_status).
set_CMD_ID(i_cmd_id),
"Status code did not return SUCCESS (%d), received (%d) for %s",
status_codes::SUCCESS, l_status, mss::c_str(i_target) );
return fapi2::FAPI2_RC_SUCCESS;
fapi_try_exit:
return fapi2::current_err;
}
}// check
///
/// @brief EXP_FW_STATUS setup helper function - useful for testing
/// @param[out] o_size the size of data
/// @param[out] o_cmd_id the explorer command ID
///
inline void fw_status_setup(size_t& o_size,
std::vector<uint8_t>& o_cmd_id)
{
o_size = FW_STATUS_BYTE_LEN;
o_cmd_id.clear();
o_cmd_id.push_back(FW_STATUS);
}
///
/// @brief EXP_FW_STATUS
/// @param[in] i_target the OCMB target
/// @return FAPI2_RC_SUCCESS iff okay
///
inline fapi2::ReturnCode fw_status(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target)
{
// Retrieve setup data
size_t l_size = 0;
std::vector<uint8_t> l_cmd_id;
fw_status_setup(l_size, l_cmd_id);
// Get data and check for errors
{
std::vector<uint8_t> l_data;
FAPI_TRY(fapi2::getI2c(i_target, l_size, l_cmd_id, l_data));
FAPI_TRY( check::status_code(i_target, l_cmd_id[0], l_data) );
}
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief EXP_FW_BOOT_CONFIG setup
/// @param[in,out] io_data the data to go to boot config
///
inline void boot_config_setup(std::vector<uint8_t>& io_data)
{
// Need data length as well - boot config can only ever be written
io_data.push_back(FW_BOOT_CONFIG_BYTE_LEN);
// Then add the command
io_data.push_back(FW_BOOT_CONFIG);
// Written commands need to be in the form of (MSB first)
// CMD
// DATA LEN
// DATA
}
///
/// @brief EXP_FW_BOOT_CONFIG
/// @param[in] i_target the OCMB target
/// @param[in] i_data the data to write
/// @return FAPI2_RC_SUCCESS iff okay
///
inline fapi2::ReturnCode boot_config(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
const std::vector<uint8_t>& i_data)
{
// Retrieve setup data
std::vector<uint8_t> l_configured_data(i_data);
boot_config_setup(l_configured_data);
// Get data and check for errors
FAPI_TRY(fapi2::putI2c(i_target, l_configured_data));
FAPI_TRY(fw_status(i_target));
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Checks if the I2C interface returns an ACK
/// @param[in] i_target the OCMB target
/// @return FAPI2_RC_SUCCESS iff okay
///
inline fapi2::ReturnCode is_ready(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target)
{
// We send a simple but valid command to poll the I2C
// Arbitrarily send an EXP_FW_STATUS command id
size_t l_size = 0;
std::vector<uint8_t> l_cmd_id;
fw_status_setup(l_size, l_cmd_id);
// We just ignore the data. We'll see FAPI2_RC_SUCCESS if
// the I2C returns an ACK.
std::vector<uint8_t> l_data;
return fapi2::getI2c(i_target, l_size, l_cmd_id, l_data);
}
}// i2c
}// exp
}// mss
#endif
<commit_msg>Add exp_i2c_scom driver that will be consumed by HB/SBE platforms<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/ocmb/explorer/procedures/hwp/memory/lib/i2c/exp_i2c.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file exp_i2c.H
/// @brief explorer I2C utility function declarations
///
// *HWP HWP Owner: Andre A. Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _MSS_EXP_I2C_H_
#define _MSS_EXP_I2C_H_
#include <fapi2.H>
#include <i2c_access.H>
#include <vector>
#include <lib/i2c/exp_i2c_fields.H>
#include <generic/memory/lib/utils/pos.H>
#include <generic/memory/lib/utils/endian_utils.H>
namespace mss
{
namespace exp
{
namespace i2c
{
namespace check
{
///
/// @brief Checks the I2c explorer status codes
/// @param[in] i_target the OCMB target
/// @param[in] i_cmd_id the command ID
/// @param[in] i_data data to check from EXP_FW_STATUS
///
inline fapi2::ReturnCode status_code( const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
const uint8_t i_cmd_id,
const std::vector<uint8_t>& i_data )
{
// Set to a high number to make sure check for SUCCESS (== 0) isn't a fluke
uint8_t l_status = ~(0);
FAPI_TRY( status::get_status_code(i_target, i_data, l_status) );
// Technically many cmds have their own status code decoding..but SUCCESS is always 0.
// If it's anything else we can just look up the status code
FAPI_ASSERT( l_status == status_codes::SUCCESS,
fapi2::MSS_EXP_STATUS_CODE_UNSUCCESSFUL().
set_TARGET(i_target).
set_STATUS_CODE(l_status).
set_CMD_ID(i_cmd_id),
"Status code did not return SUCCESS (%d), received (%d) for %s",
status_codes::SUCCESS, l_status, mss::c_str(i_target) );
return fapi2::FAPI2_RC_SUCCESS;
fapi_try_exit:
return fapi2::current_err;
}
}// check
///
/// @brief EXP_FW_STATUS setup helper function - useful for testing
/// @param[out] o_size the size of data
/// @param[out] o_cmd_id the explorer command ID
///
inline void fw_status_setup(size_t& o_size,
std::vector<uint8_t>& o_cmd_id)
{
o_size = FW_STATUS_BYTE_LEN;
o_cmd_id.clear();
o_cmd_id.push_back(FW_STATUS);
}
///
/// @brief EXP_FW_STATUS
/// @param[in] i_target the OCMB target
/// @return FAPI2_RC_SUCCESS iff okay
///
inline fapi2::ReturnCode fw_status(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target)
{
// Retrieve setup data
size_t l_size = 0;
std::vector<uint8_t> l_cmd_id;
fw_status_setup(l_size, l_cmd_id);
// Get data and check for errors
{
std::vector<uint8_t> l_data;
FAPI_TRY(fapi2::getI2c(i_target, l_size, l_cmd_id, l_data));
FAPI_TRY( check::status_code(i_target, l_cmd_id[0], l_data) );
}
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief EXP_FW_BOOT_CONFIG setup
/// @param[in,out] io_data the data to go to boot config
///
inline void boot_config_setup(std::vector<uint8_t>& io_data)
{
// Need data length as well - boot config can only ever be written
io_data.push_back(FW_BOOT_CONFIG_BYTE_LEN);
// Then add the command
io_data.push_back(FW_BOOT_CONFIG);
// Written commands need to be in the form of (MSB first)
// CMD
// DATA LEN
// DATA
}
///
/// @brief EXP_FW_BOOT_CONFIG
/// @param[in] i_target the OCMB target
/// @param[in] i_data the data to write
/// @return FAPI2_RC_SUCCESS iff okay
///
inline fapi2::ReturnCode boot_config(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
const std::vector<uint8_t>& i_data)
{
// Retrieve setup data
std::vector<uint8_t> l_configured_data(i_data);
boot_config_setup(l_configured_data);
// Get data and check for errors
FAPI_TRY(fapi2::putI2c(i_target, l_configured_data));
FAPI_TRY(fw_status(i_target));
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Checks if the I2C interface returns an ACK
/// @param[in] i_target the OCMB target
/// @return FAPI2_RC_SUCCESS iff okay
///
inline fapi2::ReturnCode is_ready(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target)
{
// We send a simple but valid command to poll the I2C
// Arbitrarily send an EXP_FW_STATUS command id
size_t l_size = 0;
std::vector<uint8_t> l_cmd_id;
fw_status_setup(l_size, l_cmd_id);
// We just ignore the data. We'll see FAPI2_RC_SUCCESS if
// the I2C returns an ACK.
std::vector<uint8_t> l_data;
return fapi2::getI2c(i_target, l_size, l_cmd_id, l_data);
}
///
/// @brief Perform a register write operation on the given OCMB chip
/// @param[in] i_target the OCMB target
/// @param[in] i_addr The translated address on the OCMB chip
/// @param[in] i_data_buffer buffer of data we want to write to the register
/// @return FAPI2_RC_SUCCESS iff okay
///
inline fapi2::ReturnCode fw_reg_write(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
const uint32_t i_addr,
const fapi2::buffer<uint32_t>& i_data_buffer)
{
// create byte vector that will hold command bytes in sequence that will do the scom
std::vector<uint8_t> l_cmd_vector;
std::vector<uint8_t> l_le_addr_vector;
std::vector<uint8_t> l_le_data_vector;
uint32_t l_input_data = static_cast<uint32_t>(i_data_buffer);
forceLE(i_addr, l_le_addr_vector);
forceLE(l_input_data, l_le_data_vector);
// Start building the cmd vector for the write operation
l_cmd_vector.push_back(FW_REG_WRITE); // Byte 0 = 0x05 (FW_REG_WRITE)
l_cmd_vector.push_back(FW_WRITE_REG_DATA_SIZE); // Byte 1 = 0x08 (FW_SCOM_DATA_SIZE)
// i_addr and i_data_buffer were converted to LE above so we can
// write them directly to the cmd_vector in the same order they
// currently are
// Byte 2:5 = Address
l_cmd_vector.insert(l_cmd_vector.end(), l_le_addr_vector.begin(), l_le_addr_vector.end());
// Byte 6:9 = Data
l_cmd_vector.insert(l_cmd_vector.end(), l_le_data_vector.begin(), l_le_data_vector.end());
// Use fapi2 putI2c interface to execute command
FAPI_TRY(fapi2::putI2c(i_target, l_cmd_vector),
"I2C FW_REG_WRITE op failed to write to 0x%.8X on OCMB w/ fapiPos = 0x%.8X",
i_addr, mss::fapi_pos(i_target));
// Check status of operation
FAPI_TRY(fw_status(i_target),
"Invalid Status after FW_REG_WRITE operation to 0x%.8X on OCMB w/ fapiPos = 0x%.8X",
i_addr, mss::fapi_pos(i_target));
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform a register write operation on the given OCMB chip
/// @param[in] i_target the OCMB target
/// @param[in] i_addr The translated address on the OCMB chip
/// @param[in] o_data_buffer buffer of data we will write the contents of the register to
/// @return FAPI2_RC_SUCCESS iff okay
///
inline fapi2::ReturnCode fw_reg_read(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
const uint32_t i_addr,
fapi2::buffer<uint32_t>& o_data_buffer)
{
// create byte vector that will hold command bytes in sequence that will do the scom
std::vector<uint8_t> l_cmd_vector;
std::vector<uint8_t> l_read_data;
std::vector<uint8_t> l_le_addr_vector;
uint32_t l_index = 0;
uint32_t l_read_value = 0;
forceLE(i_addr, l_le_addr_vector);
// Build the cmd vector for the Read
l_cmd_vector.push_back(FW_REG_ADDR_LATCH); // Byte 0 = 0x03 (FW_REG_ADDR_LATCH)
l_cmd_vector.push_back(FW_REG_ADDR_LATCH_SIZE); // Byte 1 = 0x04 (FW_REG_ADDR_LATCH_SIZE)
// i_addr was converted to LE above so we can write it
// directly to the cmd_vector in the same order it
// currently is in
// Byte 2:5 = Address
l_cmd_vector.insert(l_cmd_vector.end(), l_le_addr_vector.begin(), l_le_addr_vector.end());
// Use fapi2 putI2c interface to execute command
FAPI_TRY(fapi2::putI2c(i_target, l_cmd_vector),
"putI2c returned error for FW_REG_ADDR_LATCH operation to 0x%.8X on OCMB w/ fapiPos = 0x%.8X",
i_addr, mss::fapi_pos(i_target));
// Check i2c status after operation
FAPI_TRY(fw_status(i_target),
"Invalid Status after FW_REG_ADDR_LATCH operation to 0x%.8X on OCMB w/ fapiPos = 0x%.8X",
i_addr, mss::fapi_pos(i_target));
// Clear out cmd vector as i2c op is complete and we must prepare for next
l_cmd_vector.clear();
// Cmd vector is a single byte with FW_REG_READ code
l_cmd_vector.push_back(FW_REG_READ); // Byte 0 = 0x04 (FW_REG_READ)
// Use fapi2 getI2c interface to execute command
FAPI_TRY(fapi2::getI2c(i_target, FW_I2C_SCOM_READ_SIZE, l_cmd_vector, l_read_data),
"getI2c returned error for FW_REG_READ operation to 0x%.8X on OCMB w/ fapiPos = 0x%.8X",
i_addr, mss::fapi_pos(i_target));
// The first byte returned should be the size of the remaining data
// We requested FW_REG_ADDR_LATCH_SIZE bytes so that is what we
// expect to see as the first byte.
FAPI_ASSERT( (l_read_data.front() == FW_REG_ADDR_LATCH_SIZE),
fapi2::I2C_GET_SCOM_INVALID_READ_SIZE()
.set_TARGET(i_target)
.set_ADDRESS(i_addr)
.set_SIZE_RETURNED(l_read_data[0])
.set_SIZE_REQUESTED(FW_REG_ADDR_LATCH_SIZE),
"First byte of read data was expected to be 0x%lx but byte read = 0x%x",
FW_REG_ADDR_LATCH_SIZE, l_read_data[0] );
// Check i2c status after operation
FAPI_TRY(fw_status(i_target),
"Invalid Status after FW_REG_READ operation to 0x%.8X on OCMB w/ fapiPos = 0x%.8X",
i_addr, mss::fapi_pos(i_target));
// The OCMB is a 32-bit little endian engine so
// we must convert the buffer that we read into native
// incase native endian is different than LE
readLE(l_read_data, l_index, l_read_value);
o_data_buffer = l_read_value;
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform a register write operation on the given OCMB chip
/// @param[in] i_addr The raw address that needs to be translated to IBM scom addr
/// @param[in] i_side LHS or RHS of the IBM i2c scom. IBM addresses expect 64 bits of
/// data returned from them so we must have a LHS and a RHS which is offset
/// by 4 bytes. This is because the OCMB is a 32 bit architecture
/// @return uint32 of translated address
///
inline uint32_t trans_ibm_i2c_scom_addr(const uint32_t i_addr,
const addrSide i_side)
{
return (i_side == LHS) ?
((LAST_THREE_BYTES_MASK & i_addr) << OCMB_ADDR_SHIFT) | IBM_SCOM_OFFSET_LHS | OCMB_UNCACHED_OFFSET :
((LAST_THREE_BYTES_MASK & i_addr) << OCMB_ADDR_SHIFT) | IBM_SCOM_OFFSET_RHS | OCMB_UNCACHED_OFFSET ;
}
///
/// @brief Perform a register write operation on the given OCMB chip
/// @param[in] i_addr The raw address that needs to be translated to Microchip scom addr
/// @return uint32 of translated address
///
inline uint32_t trans_micro_i2c_scom_addr(const uint32_t i_addr)
{
return (i_addr | OCMB_UNCACHED_OFFSET) ;
}
}// i2c
}// exp
}// mss
#endif
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License or as specified alternatively below. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Major Contributor(s):
* Copyright (C) 2012 Kohei Yoshida <kohei.yoshida@suse.com>
*
* All Rights Reserved.
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#include "dpitemdata.hxx"
#include "document.hxx"
#include "dpobject.hxx"
#include "cell.hxx"
#include "globstr.hrc"
#include "dptabdat.hxx"
#include "rtl/math.hxx"
const sal_Int32 ScDPItemData::DateFirst = -1;
const sal_Int32 ScDPItemData::DateLast = 10000;
sal_Int32 ScDPItemData::Compare(const ScDPItemData& rA, const ScDPItemData& rB)
{
if (rA.meType != rB.meType)
{
// group value, value and string in this order.
return rA.meType < rB.meType ? -1 : 1;
}
switch (rA.meType)
{
case GroupValue:
{
if (rA.maGroupValue.mnGroupType == rB.maGroupValue.mnGroupType)
{
if (rA.maGroupValue.mnValue == rB.maGroupValue.mnValue)
return 0;
return rA.maGroupValue.mnValue < rB.maGroupValue.mnValue ? -1 : 1;
}
return rA.maGroupValue.mnGroupType < rB.maGroupValue.mnGroupType ? -1 : 1;
}
case Value:
case RangeStart:
{
if (rA.mfValue == rB.mfValue)
return 0;
return rA.mfValue < rB.mfValue ? -1 : 1;
}
case String:
case Error:
return ScGlobal::GetCollator()->compareString(rA.GetString(), rB.GetString());
default:
;
}
return 0;
}
ScDPItemData::ScDPItemData() :
mfValue(0.0), meType(Empty) {}
ScDPItemData::ScDPItemData(const ScDPItemData& r) :
meType(r.meType)
{
switch (r.meType)
{
case String:
case Error:
mpString = new rtl::OUString(*r.mpString);
break;
case Value:
case RangeStart:
mfValue = r.mfValue;
break;
case GroupValue:
maGroupValue.mnGroupType = r.maGroupValue.mnGroupType;
maGroupValue.mnValue = r.maGroupValue.mnValue;
break;
case Empty:
default:
mfValue = 0.0;
}
}
void ScDPItemData::DisposeString()
{
if (meType == String || meType == Error)
delete mpString;
}
ScDPItemData::ScDPItemData(const rtl::OUString& rStr) :
mpString(new rtl::OUString(rStr)), meType(String) {}
ScDPItemData::ScDPItemData(sal_Int32 nGroupType, sal_Int32 nValue) :
meType(GroupValue)
{
maGroupValue.mnGroupType = nGroupType;
maGroupValue.mnValue = nValue;
}
ScDPItemData::~ScDPItemData()
{
DisposeString();
}
ScDPItemData::Type ScDPItemData::GetType() const
{
return meType;
}
void ScDPItemData::SetString(const rtl::OUString& rS)
{
DisposeString();
mpString = new rtl::OUString(rS);
meType = String;
}
void ScDPItemData::SetValue(double fVal)
{
DisposeString();
mfValue = fVal;
meType = Value;
}
void ScDPItemData::SetRangeStart(double fVal)
{
DisposeString();
mfValue = fVal;
meType = RangeStart;
}
void ScDPItemData::SetRangeFirst()
{
DisposeString();
rtl::math::setInf(&mfValue, true);
meType = RangeStart;
}
void ScDPItemData::SetRangeLast()
{
DisposeString();
rtl::math::setInf(&mfValue, false);
meType = RangeStart;
}
void ScDPItemData::SetErrorString(const rtl::OUString& rS)
{
SetString(rS);
meType = Error;
}
bool ScDPItemData::IsCaseInsEqual(const ScDPItemData& r) const
{
if (meType != r.meType)
return false;
switch (meType)
{
case Value:
case RangeStart:
return rtl::math::approxEqual(mfValue, r.mfValue);
case GroupValue:
return maGroupValue.mnGroupType == r.maGroupValue.mnGroupType &&
maGroupValue.mnValue == r.maGroupValue.mnValue;
default:
;
}
return ScGlobal::GetpTransliteration()->isEqual(GetString(), r.GetString());
}
bool ScDPItemData::operator== (const ScDPItemData& r) const
{
if (meType != r.meType)
return false;
switch (meType)
{
case Value:
case RangeStart:
return rtl::math::approxEqual(mfValue, r.mfValue);
case GroupValue:
return maGroupValue.mnGroupType == r.maGroupValue.mnGroupType &&
maGroupValue.mnValue == r.maGroupValue.mnValue;
default:
;
}
// need exact equality until we have a safe case insensitive string hash
return GetString() == r.GetString();
}
bool ScDPItemData::operator!= (const ScDPItemData& r) const
{
return !operator== (r);
}
bool ScDPItemData::operator< (const ScDPItemData& r) const
{
return Compare(*this, r) == -1;
}
ScDPItemData& ScDPItemData::operator= (const ScDPItemData& r)
{
meType = r.meType;
switch (r.meType)
{
case String:
case Error:
mpString = new rtl::OUString(*r.mpString);
break;
case Value:
case RangeStart:
mfValue = r.mfValue;
break;
case GroupValue:
maGroupValue.mnGroupType = r.maGroupValue.mnGroupType;
maGroupValue.mnValue = r.maGroupValue.mnValue;
break;
case Empty:
default:
mfValue = 0.0;
}
return *this;
}
sal_uInt8 ScDPItemData::GetCellType() const
{
switch (meType)
{
case Error:
return SC_VALTYPE_ERROR;
case Empty:
return SC_VALTYPE_EMPTY;
case Value:
return SC_VALTYPE_VALUE;
default:
;
}
return SC_VALTYPE_STRING;
}
#if DEBUG_DP_ITEM_DATA
void ScDPItemData::Dump(const char* msg) const
{
printf("--- (%s)\n", msg);
switch (meType)
{
case Empty:
printf("empty\n");
break;
case Error:
printf("error: %s\n",
rtl::OUStringToOString(*mpString, RTL_TEXTENCODING_UTF8).getStr());
break;
case GroupValue:
printf("group value: group type = %d value = %d\n",
maGroupValue.mnGroupType, maGroupValue.mnValue);
break;
case String:
printf("string: %s\n",
rtl::OUStringToOString(*mpString, RTL_TEXTENCODING_UTF8).getStr());
break;
case Value:
printf("value: %g\n", mfValue);
break;
case RangeStart:
printf("range start: %g\n", mfValue);
break;
default:
printf("unknown type\n");
}
printf("---\n");
}
#endif
bool ScDPItemData::IsEmpty() const
{
return meType == Empty;
}
bool ScDPItemData::IsValue() const
{
return meType == Value;
}
rtl::OUString ScDPItemData::GetString() const
{
switch (meType)
{
case String:
case Error:
return *mpString;
case Value:
return rtl::OUString::valueOf(mfValue);
case GroupValue:
case RangeStart:
return rtl::OUString::createFromAscii("fail");
case Empty:
default:
;
}
return rtl::OUString();
}
double ScDPItemData::GetValue() const
{
if (meType == Value || meType == RangeStart)
return mfValue;
return 0.0;
}
ScDPItemData::GroupValueAttr ScDPItemData::GetGroupValue() const
{
if (meType == GroupValue)
return maGroupValue;
GroupValueAttr aGV;
aGV.mnGroupType = -1;
aGV.mnValue = -1;
return aGV;
}
bool ScDPItemData::HasStringData() const
{
return meType == String || meType == Error;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Fixed memory leak.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License or as specified alternatively below. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Major Contributor(s):
* Copyright (C) 2012 Kohei Yoshida <kohei.yoshida@suse.com>
*
* All Rights Reserved.
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#include "dpitemdata.hxx"
#include "document.hxx"
#include "dpobject.hxx"
#include "cell.hxx"
#include "globstr.hrc"
#include "dptabdat.hxx"
#include "rtl/math.hxx"
const sal_Int32 ScDPItemData::DateFirst = -1;
const sal_Int32 ScDPItemData::DateLast = 10000;
sal_Int32 ScDPItemData::Compare(const ScDPItemData& rA, const ScDPItemData& rB)
{
if (rA.meType != rB.meType)
{
// group value, value and string in this order.
return rA.meType < rB.meType ? -1 : 1;
}
switch (rA.meType)
{
case GroupValue:
{
if (rA.maGroupValue.mnGroupType == rB.maGroupValue.mnGroupType)
{
if (rA.maGroupValue.mnValue == rB.maGroupValue.mnValue)
return 0;
return rA.maGroupValue.mnValue < rB.maGroupValue.mnValue ? -1 : 1;
}
return rA.maGroupValue.mnGroupType < rB.maGroupValue.mnGroupType ? -1 : 1;
}
case Value:
case RangeStart:
{
if (rA.mfValue == rB.mfValue)
return 0;
return rA.mfValue < rB.mfValue ? -1 : 1;
}
case String:
case Error:
return ScGlobal::GetCollator()->compareString(rA.GetString(), rB.GetString());
default:
;
}
return 0;
}
ScDPItemData::ScDPItemData() :
mfValue(0.0), meType(Empty) {}
ScDPItemData::ScDPItemData(const ScDPItemData& r) :
meType(r.meType)
{
switch (r.meType)
{
case String:
case Error:
mpString = new rtl::OUString(*r.mpString);
break;
case Value:
case RangeStart:
mfValue = r.mfValue;
break;
case GroupValue:
maGroupValue.mnGroupType = r.maGroupValue.mnGroupType;
maGroupValue.mnValue = r.maGroupValue.mnValue;
break;
case Empty:
default:
mfValue = 0.0;
}
}
void ScDPItemData::DisposeString()
{
if (meType == String || meType == Error)
delete mpString;
}
ScDPItemData::ScDPItemData(const rtl::OUString& rStr) :
mpString(new rtl::OUString(rStr)), meType(String) {}
ScDPItemData::ScDPItemData(sal_Int32 nGroupType, sal_Int32 nValue) :
meType(GroupValue)
{
maGroupValue.mnGroupType = nGroupType;
maGroupValue.mnValue = nValue;
}
ScDPItemData::~ScDPItemData()
{
DisposeString();
}
ScDPItemData::Type ScDPItemData::GetType() const
{
return meType;
}
void ScDPItemData::SetString(const rtl::OUString& rS)
{
DisposeString();
mpString = new rtl::OUString(rS);
meType = String;
}
void ScDPItemData::SetValue(double fVal)
{
DisposeString();
mfValue = fVal;
meType = Value;
}
void ScDPItemData::SetRangeStart(double fVal)
{
DisposeString();
mfValue = fVal;
meType = RangeStart;
}
void ScDPItemData::SetRangeFirst()
{
DisposeString();
rtl::math::setInf(&mfValue, true);
meType = RangeStart;
}
void ScDPItemData::SetRangeLast()
{
DisposeString();
rtl::math::setInf(&mfValue, false);
meType = RangeStart;
}
void ScDPItemData::SetErrorString(const rtl::OUString& rS)
{
SetString(rS);
meType = Error;
}
bool ScDPItemData::IsCaseInsEqual(const ScDPItemData& r) const
{
if (meType != r.meType)
return false;
switch (meType)
{
case Value:
case RangeStart:
return rtl::math::approxEqual(mfValue, r.mfValue);
case GroupValue:
return maGroupValue.mnGroupType == r.maGroupValue.mnGroupType &&
maGroupValue.mnValue == r.maGroupValue.mnValue;
default:
;
}
return ScGlobal::GetpTransliteration()->isEqual(GetString(), r.GetString());
}
bool ScDPItemData::operator== (const ScDPItemData& r) const
{
if (meType != r.meType)
return false;
switch (meType)
{
case Value:
case RangeStart:
return rtl::math::approxEqual(mfValue, r.mfValue);
case GroupValue:
return maGroupValue.mnGroupType == r.maGroupValue.mnGroupType &&
maGroupValue.mnValue == r.maGroupValue.mnValue;
default:
;
}
// need exact equality until we have a safe case insensitive string hash
return GetString() == r.GetString();
}
bool ScDPItemData::operator!= (const ScDPItemData& r) const
{
return !operator== (r);
}
bool ScDPItemData::operator< (const ScDPItemData& r) const
{
return Compare(*this, r) == -1;
}
ScDPItemData& ScDPItemData::operator= (const ScDPItemData& r)
{
DisposeString();
meType = r.meType;
switch (r.meType)
{
case String:
case Error:
mpString = new rtl::OUString(*r.mpString);
break;
case Value:
case RangeStart:
mfValue = r.mfValue;
break;
case GroupValue:
maGroupValue.mnGroupType = r.maGroupValue.mnGroupType;
maGroupValue.mnValue = r.maGroupValue.mnValue;
break;
case Empty:
default:
mfValue = 0.0;
}
return *this;
}
sal_uInt8 ScDPItemData::GetCellType() const
{
switch (meType)
{
case Error:
return SC_VALTYPE_ERROR;
case Empty:
return SC_VALTYPE_EMPTY;
case Value:
return SC_VALTYPE_VALUE;
default:
;
}
return SC_VALTYPE_STRING;
}
#if DEBUG_DP_ITEM_DATA
void ScDPItemData::Dump(const char* msg) const
{
printf("--- (%s)\n", msg);
switch (meType)
{
case Empty:
printf("empty\n");
break;
case Error:
printf("error: %s\n",
rtl::OUStringToOString(*mpString, RTL_TEXTENCODING_UTF8).getStr());
break;
case GroupValue:
printf("group value: group type = %d value = %d\n",
maGroupValue.mnGroupType, maGroupValue.mnValue);
break;
case String:
printf("string: %s\n",
rtl::OUStringToOString(*mpString, RTL_TEXTENCODING_UTF8).getStr());
break;
case Value:
printf("value: %g\n", mfValue);
break;
case RangeStart:
printf("range start: %g\n", mfValue);
break;
default:
printf("unknown type\n");
}
printf("---\n");
}
#endif
bool ScDPItemData::IsEmpty() const
{
return meType == Empty;
}
bool ScDPItemData::IsValue() const
{
return meType == Value;
}
rtl::OUString ScDPItemData::GetString() const
{
switch (meType)
{
case String:
case Error:
return *mpString;
case Value:
return rtl::OUString::valueOf(mfValue);
case GroupValue:
case RangeStart:
return rtl::OUString::createFromAscii("fail");
case Empty:
default:
;
}
return rtl::OUString();
}
double ScDPItemData::GetValue() const
{
if (meType == Value || meType == RangeStart)
return mfValue;
return 0.0;
}
ScDPItemData::GroupValueAttr ScDPItemData::GetGroupValue() const
{
if (meType == GroupValue)
return maGroupValue;
GroupValueAttr aGV;
aGV.mnGroupType = -1;
aGV.mnValue = -1;
return aGV;
}
bool ScDPItemData::HasStringData() const
{
return meType == String || meType == Error;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include <sstream>
#include "Tools/Exception/exception.hpp"
#include "Codec_polar.hpp"
using namespace aff3ct;
using namespace aff3ct::module;
template <typename B, typename Q>
Codec_polar<B,Q>
::Codec_polar(const factory::Frozenbits_generator::parameters &fb_params,
const factory::Encoder_polar ::parameters &enc_params,
const factory::Decoder_polar ::parameters &dec_params,
const factory::Puncturer_polar ::parameters *pct_params,
CRC<B>* crc)
: Codec <B,Q>(enc_params.K, enc_params.N_cw, pct_params ? pct_params->N : enc_params.N_cw, enc_params.tail_length, enc_params.n_frames),
Codec_SISO_SIHO<B,Q>(enc_params.K, enc_params.N_cw, pct_params ? pct_params->N : enc_params.N_cw, enc_params.tail_length, enc_params.n_frames),
adaptive_fb(fb_params.sigma == -1.f),
frozen_bits(fb_params.N_cw, true),
generated_decoder((dec_params.implem.find("_SNR") != std::string::npos)),
fb_generator (nullptr),
puncturer_wangliu(nullptr),
fb_decoder (nullptr),
fb_encoder (nullptr)
{
const std::string name = "Codec_polar";
this->set_name(name);
// ----------------------------------------------------------------------------------------------------- exceptions
if (enc_params.K != dec_params.K)
{
std::stringstream message;
message << "'enc_params.K' has to be equal to 'dec_params.K' ('enc_params.K' = " << enc_params.K
<< ", 'dec_params.K' = " << dec_params.K << ").";
throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
}
if (enc_params.N_cw != dec_params.N_cw)
{
std::stringstream message;
message << "'enc_params.N_cw' has to be equal to 'dec_params.N_cw' ('enc_params.N_cw' = " << enc_params.N_cw
<< ", 'dec_params.N_cw' = " << dec_params.N_cw << ").";
throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
}
if (enc_params.n_frames != dec_params.n_frames)
{
std::stringstream message;
message << "'enc_params.n_frames' has to be equal to 'dec_params.n_frames' ('enc_params.n_frames' = "
<< enc_params.n_frames << ", 'dec_params.n_frames' = " << dec_params.n_frames << ").";
throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
}
// ---------------------------------------------------------------------------------------------------------- tools
if (!generated_decoder)
// build the frozen bits generator
fb_generator = factory::Frozenbits_generator::build(fb_params);
else
if (this->N_cw != this->N)
{
std::stringstream message;
message << "'N_cw' has to be equal to 'N' ('N_cw' = " << this->N_cw << ", 'N' = "
<< this->N << ").";
throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
}
// ---------------------------------------------------------------------------------------------------- allocations
std::fill(frozen_bits.begin(), frozen_bits.begin() + this->K, false);
if (generated_decoder || !pct_params)
{
factory::Puncturer::parameters pctno_params;
pctno_params.type = "NO";
pctno_params.K = enc_params.K;
pctno_params.N = enc_params.N_cw;
pctno_params.N_cw = enc_params.N_cw;
pctno_params.n_frames = enc_params.n_frames;
this->set_puncturer(factory::Puncturer::build<B,Q>(pctno_params));
}
else
{
try
{
puncturer_wangliu = factory::Puncturer_polar::build<B,Q>(*pct_params, *fb_generator);
this->set_puncturer(puncturer_wangliu);
}
catch(tools::cannot_allocate const&)
{
this->set_puncturer(factory::Puncturer::build<B,Q>(*pct_params));
}
}
try
{
auto *encoder_polar = factory::Encoder_polar::build<B>(enc_params, frozen_bits);
this->fb_encoder = encoder_polar;
this->set_encoder(encoder_polar);
}
catch (tools::cannot_allocate const&)
{
this->set_encoder(factory::Encoder::build<B>(enc_params));
}
try
{
auto decoder_siso_siho = factory::Decoder_polar::build_siso<B,Q>(dec_params, frozen_bits, this->get_encoder());
this->set_decoder_siso(decoder_siso_siho);
this->set_decoder_siho(decoder_siso_siho);
}
catch (const std::exception&)
{
if (generated_decoder)
this->set_decoder_siho(factory::Decoder_polar::build_gen<B,Q>(dec_params, crc, this->get_encoder()));
else
this->set_decoder_siho(factory::Decoder_polar::build <B,Q>(dec_params, frozen_bits, crc, this->get_encoder()));
}
if (dec_params.type != "ML")
this->fb_decoder = dynamic_cast<tools::Frozenbits_notifier*>(this->get_decoder_siho());
// ------------------------------------------------------------------------------------------------- frozen bit gen
if (!generated_decoder)
{
if (!adaptive_fb)
{
fb_generator->generate(frozen_bits);
if (this->N_cw != this->N)
puncturer_wangliu->gen_frozen_bits(frozen_bits);
this->notify_frozenbits_update();
}
}
else
{
const auto fb = factory::Decoder_polar::get_frozen_bits(dec_params.implem);
if (fb.size() != frozen_bits.size())
{
std::stringstream message;
message << "'fb.size()' has to be equal to 'frozen_bits.size()' ('fb.size()' = " << fb.size()
<< ", 'frozen_bits.size()' = " << frozen_bits.size() << ").";
throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str());
}
std::copy(fb.begin(), fb.end(), frozen_bits.begin());
this->notify_frozenbits_update();
}
}
template <typename B, typename Q>
Codec_polar<B,Q>
::~Codec_polar()
{
if (fb_generator != nullptr) { delete fb_generator; fb_generator = nullptr; }
}
template <typename B, typename Q>
void Codec_polar<B,Q>
::notify_frozenbits_update()
{
if (this->N_cw != this->N)
puncturer_wangliu->gen_frozen_bits(frozen_bits);
if (this->fb_decoder)
this->fb_decoder->notify_frozenbits_update();
if (this->fb_encoder)
this->fb_encoder->notify_frozenbits_update();
}
template <typename B, typename Q>
void Codec_polar<B,Q>
::set_sigma(const float sigma)
{
Codec_SISO_SIHO<B,Q>::set_sigma(sigma);
// adaptive frozen bits generation
if (adaptive_fb && !generated_decoder)
{
fb_generator->set_sigma(sigma);
fb_generator->generate(frozen_bits);
this->notify_frozenbits_update();
}
}
template <typename B, typename Q>
std::vector<bool>& Codec_polar<B,Q>
::get_frozen_bits()
{
return this->frozen_bits;
}
template <typename B, typename Q>
void Codec_polar<B,Q>
::_extract_sys_par(const Q* Y_N, Q* sys, Q* par, const int frame_id)
{
auto par_idx = 0, sys_idx = 0;
auto N_cw = this->N_cw;
for (auto i = 0; i < N_cw; i++)
{
if (!frozen_bits[i])
{
sys[sys_idx] = Y_N[i];
sys_idx++;
}
else // parity bit
{
par[par_idx] = Y_N[i];
par_idx++;
}
}
}
template <typename B, typename Q>
void Codec_polar<B,Q>
::_extract_sys_llr(const Q* Y_N, Q* sys, const int frame_id)
{
auto sys_idx = 0;
auto N_cw = this->N_cw;
for (auto i = 0; i < N_cw; i++)
{
if (!frozen_bits[i])
{
sys[sys_idx] = Y_N[i];
sys_idx++;
}
}
}
template <typename B, typename Q>
void Codec_polar<B,Q>
::_add_sys_ext(const Q* ext, Q* Y_N, const int frame_id)
{
auto sys_idx = 0;
for (auto i = 0; i < this->N_cw; i++)
if (!frozen_bits[i])
{
Y_N[i] += ext[sys_idx];
sys_idx++;
}
}
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class aff3ct::module::Codec_polar<B_8,Q_8>;
template class aff3ct::module::Codec_polar<B_16,Q_16>;
template class aff3ct::module::Codec_polar<B_32,Q_32>;
template class aff3ct::module::Codec_polar<B_64,Q_64>;
#else
template class aff3ct::module::Codec_polar<B,Q>;
#endif
// ==================================================================================== explicit template instantiation
<commit_msg>Rm useless processing.<commit_after>#include <sstream>
#include "Tools/Exception/exception.hpp"
#include "Codec_polar.hpp"
using namespace aff3ct;
using namespace aff3ct::module;
template <typename B, typename Q>
Codec_polar<B,Q>
::Codec_polar(const factory::Frozenbits_generator::parameters &fb_params,
const factory::Encoder_polar ::parameters &enc_params,
const factory::Decoder_polar ::parameters &dec_params,
const factory::Puncturer_polar ::parameters *pct_params,
CRC<B>* crc)
: Codec <B,Q>(enc_params.K, enc_params.N_cw, pct_params ? pct_params->N : enc_params.N_cw, enc_params.tail_length, enc_params.n_frames),
Codec_SISO_SIHO<B,Q>(enc_params.K, enc_params.N_cw, pct_params ? pct_params->N : enc_params.N_cw, enc_params.tail_length, enc_params.n_frames),
adaptive_fb(fb_params.sigma == -1.f),
frozen_bits(fb_params.N_cw, true),
generated_decoder((dec_params.implem.find("_SNR") != std::string::npos)),
fb_generator (nullptr),
puncturer_wangliu(nullptr),
fb_decoder (nullptr),
fb_encoder (nullptr)
{
const std::string name = "Codec_polar";
this->set_name(name);
// ----------------------------------------------------------------------------------------------------- exceptions
if (enc_params.K != dec_params.K)
{
std::stringstream message;
message << "'enc_params.K' has to be equal to 'dec_params.K' ('enc_params.K' = " << enc_params.K
<< ", 'dec_params.K' = " << dec_params.K << ").";
throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
}
if (enc_params.N_cw != dec_params.N_cw)
{
std::stringstream message;
message << "'enc_params.N_cw' has to be equal to 'dec_params.N_cw' ('enc_params.N_cw' = " << enc_params.N_cw
<< ", 'dec_params.N_cw' = " << dec_params.N_cw << ").";
throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
}
if (enc_params.n_frames != dec_params.n_frames)
{
std::stringstream message;
message << "'enc_params.n_frames' has to be equal to 'dec_params.n_frames' ('enc_params.n_frames' = "
<< enc_params.n_frames << ", 'dec_params.n_frames' = " << dec_params.n_frames << ").";
throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
}
// ---------------------------------------------------------------------------------------------------------- tools
if (!generated_decoder)
// build the frozen bits generator
fb_generator = factory::Frozenbits_generator::build(fb_params);
else
if (this->N_cw != this->N)
{
std::stringstream message;
message << "'N_cw' has to be equal to 'N' ('N_cw' = " << this->N_cw << ", 'N' = "
<< this->N << ").";
throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
}
// ---------------------------------------------------------------------------------------------------- allocations
std::fill(frozen_bits.begin(), frozen_bits.begin() + this->K, false);
if (generated_decoder || !pct_params)
{
factory::Puncturer::parameters pctno_params;
pctno_params.type = "NO";
pctno_params.K = enc_params.K;
pctno_params.N = enc_params.N_cw;
pctno_params.N_cw = enc_params.N_cw;
pctno_params.n_frames = enc_params.n_frames;
this->set_puncturer(factory::Puncturer::build<B,Q>(pctno_params));
}
else
{
try
{
puncturer_wangliu = factory::Puncturer_polar::build<B,Q>(*pct_params, *fb_generator);
this->set_puncturer(puncturer_wangliu);
}
catch(tools::cannot_allocate const&)
{
this->set_puncturer(factory::Puncturer::build<B,Q>(*pct_params));
}
}
try
{
auto *encoder_polar = factory::Encoder_polar::build<B>(enc_params, frozen_bits);
this->fb_encoder = encoder_polar;
this->set_encoder(encoder_polar);
}
catch (tools::cannot_allocate const&)
{
this->set_encoder(factory::Encoder::build<B>(enc_params));
}
try
{
auto decoder_siso_siho = factory::Decoder_polar::build_siso<B,Q>(dec_params, frozen_bits, this->get_encoder());
this->set_decoder_siso(decoder_siso_siho);
this->set_decoder_siho(decoder_siso_siho);
}
catch (const std::exception&)
{
if (generated_decoder)
this->set_decoder_siho(factory::Decoder_polar::build_gen<B,Q>(dec_params, crc, this->get_encoder()));
else
this->set_decoder_siho(factory::Decoder_polar::build <B,Q>(dec_params, frozen_bits, crc, this->get_encoder()));
}
if (dec_params.type != "ML")
this->fb_decoder = dynamic_cast<tools::Frozenbits_notifier*>(this->get_decoder_siho());
// ------------------------------------------------------------------------------------------------- frozen bit gen
if (!generated_decoder)
{
if (!adaptive_fb)
{
fb_generator->generate(frozen_bits);
this->notify_frozenbits_update();
}
}
else
{
const auto fb = factory::Decoder_polar::get_frozen_bits(dec_params.implem);
if (fb.size() != frozen_bits.size())
{
std::stringstream message;
message << "'fb.size()' has to be equal to 'frozen_bits.size()' ('fb.size()' = " << fb.size()
<< ", 'frozen_bits.size()' = " << frozen_bits.size() << ").";
throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str());
}
std::copy(fb.begin(), fb.end(), frozen_bits.begin());
this->notify_frozenbits_update();
}
}
template <typename B, typename Q>
Codec_polar<B,Q>
::~Codec_polar()
{
if (fb_generator != nullptr) { delete fb_generator; fb_generator = nullptr; }
}
template <typename B, typename Q>
void Codec_polar<B,Q>
::notify_frozenbits_update()
{
if (this->N_cw != this->N)
puncturer_wangliu->gen_frozen_bits(frozen_bits);
if (this->fb_decoder)
this->fb_decoder->notify_frozenbits_update();
if (this->fb_encoder)
this->fb_encoder->notify_frozenbits_update();
}
template <typename B, typename Q>
void Codec_polar<B,Q>
::set_sigma(const float sigma)
{
Codec_SISO_SIHO<B,Q>::set_sigma(sigma);
// adaptive frozen bits generation
if (adaptive_fb && !generated_decoder)
{
fb_generator->set_sigma(sigma);
fb_generator->generate(frozen_bits);
this->notify_frozenbits_update();
}
}
template <typename B, typename Q>
std::vector<bool>& Codec_polar<B,Q>
::get_frozen_bits()
{
return this->frozen_bits;
}
template <typename B, typename Q>
void Codec_polar<B,Q>
::_extract_sys_par(const Q* Y_N, Q* sys, Q* par, const int frame_id)
{
auto par_idx = 0, sys_idx = 0;
auto N_cw = this->N_cw;
for (auto i = 0; i < N_cw; i++)
{
if (!frozen_bits[i])
{
sys[sys_idx] = Y_N[i];
sys_idx++;
}
else // parity bit
{
par[par_idx] = Y_N[i];
par_idx++;
}
}
}
template <typename B, typename Q>
void Codec_polar<B,Q>
::_extract_sys_llr(const Q* Y_N, Q* sys, const int frame_id)
{
auto sys_idx = 0;
auto N_cw = this->N_cw;
for (auto i = 0; i < N_cw; i++)
{
if (!frozen_bits[i])
{
sys[sys_idx] = Y_N[i];
sys_idx++;
}
}
}
template <typename B, typename Q>
void Codec_polar<B,Q>
::_add_sys_ext(const Q* ext, Q* Y_N, const int frame_id)
{
auto sys_idx = 0;
for (auto i = 0; i < this->N_cw; i++)
if (!frozen_bits[i])
{
Y_N[i] += ext[sys_idx];
sys_idx++;
}
}
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class aff3ct::module::Codec_polar<B_8,Q_8>;
template class aff3ct::module::Codec_polar<B_16,Q_16>;
template class aff3ct::module::Codec_polar<B_32,Q_32>;
template class aff3ct::module::Codec_polar<B_64,Q_64>;
#else
template class aff3ct::module::Codec_polar<B,Q>;
#endif
// ==================================================================================== explicit template instantiation
<|endoftext|> |
<commit_before>#include "stxxl/bits/common/debug.h"
__STXXL_BEGIN_NAMESPACE
debugmon * debugmon::instance = NULL;
#ifndef STXXL_DEBUGMON
void debugmon::block_allocated(char * /*ptr*/, char * /*end*/, size_t /*size*/)
{ }
void debugmon::block_deallocated(char * /*ptr*/)
{ }
void debugmon::io_started(char * /*ptr*/)
{ }
void debugmon::io_finished(char * /*ptr*/)
{ }
#else
void debugmon::block_allocated(char * ptr, char * end, size_t size)
{
#ifdef STXXL_BOOST_THREADS
boost::mutex::scoped_lock Lock(mutex1);
#else
mutex1.lock();
#endif
// checks are here
STXXL_VERBOSE1("debugmon: block " << long (ptr) << " allocated");
assert(tags.find(ptr) == tags.end()); // not allocated
tag t;
t.ongoing = false;
t.end = end;
t.size = size;
tags[ptr] = t;
#ifndef STXXL_BOOST_THREADS
mutex1.unlock();
#endif
}
void debugmon::block_deallocated(char * ptr)
{
#ifdef STXXL_BOOST_THREADS
boost::mutex::scoped_lock Lock(mutex1);
#else
mutex1.lock();
#endif
STXXL_VERBOSE1("debugmon: block_deallocated from " << long (ptr));
assert(tags.find(ptr) != tags.end()); // allocated
tag t = tags[ptr];
assert(t.ongoing == false); // not ongoing
tags.erase(ptr);
size_t size = t.size;
STXXL_VERBOSE1("debugmon: block_deallocated to " << long (t.end));
char * endptr = (char *) t.end;
char * ptr1 = (char *) ptr;
ptr1 += size;
while (ptr1 < endptr)
{
STXXL_VERBOSE1("debugmon: block_deallocated next " << long (ptr1));
assert(tags.find(ptr1) != tags.end()); // allocated
tag t = tags[ptr1];
assert(t.ongoing == false); // not ongoing
assert(t.size == size); // chunk size
assert(t.end == endptr); // array end address
tags.erase(ptr1);
ptr1 += size;
}
#ifndef STXXL_BOOST_THREADS
mutex1.unlock();
#endif
}
void debugmon::io_started(char * ptr)
{
#ifdef STXXL_BOOST_THREADS
boost::mutex::scoped_lock Lock(mutex1);
#else
mutex1.lock();
#endif
STXXL_VERBOSE1("debugmon: I/O on block " << long (ptr) << " started");
assert(tags.find(ptr) != tags.end()); // allocated
tag t = tags[ptr];
//assert(t.ongoing == false); // not ongoing
if (t.ongoing == true)
STXXL_ERRMSG("debugmon: I/O on block " << long (ptr) << " started, but block is already busy");
t.ongoing = true;
tags[ptr] = t;
#ifndef STXXL_BOOST_THREADS
mutex1.unlock();
#endif
}
void debugmon::io_finished(char * ptr)
{
#ifdef STXXL_BOOST_THREADS
boost::mutex::scoped_lock Lock(mutex1);
#else
mutex1.lock();
#endif
STXXL_VERBOSE1("debugmon: I/O on block " << long (ptr) << " finished");
assert(tags.find(ptr) != tags.end()); // allocated
tag t = tags[ptr];
//assert(t.ongoing == true); // ongoing
if (t.ongoing == false)
STXXL_ERRMSG("debugmon: I/O on block " << long (ptr) << " finished, but block was not busy");
t.ongoing = false;
tags[ptr] = t;
#ifndef STXXL_BOOST_THREADS
mutex1.unlock();
#endif
}
#endif
__STXXL_END_NAMESPACE
<commit_msg>added missing utils.h include in debug.cpp<commit_after>#include "stxxl/bits/common/debug.h"
#include "stxxl/bits/common/utils.h"
__STXXL_BEGIN_NAMESPACE
debugmon * debugmon::instance = NULL;
#ifndef STXXL_DEBUGMON
void debugmon::block_allocated(char * /*ptr*/, char * /*end*/, size_t /*size*/)
{ }
void debugmon::block_deallocated(char * /*ptr*/)
{ }
void debugmon::io_started(char * /*ptr*/)
{ }
void debugmon::io_finished(char * /*ptr*/)
{ }
#else
void debugmon::block_allocated(char * ptr, char * end, size_t size)
{
#ifdef STXXL_BOOST_THREADS
boost::mutex::scoped_lock Lock(mutex1);
#else
mutex1.lock();
#endif
// checks are here
STXXL_VERBOSE1("debugmon: block " << long (ptr) << " allocated");
assert(tags.find(ptr) == tags.end()); // not allocated
tag t;
t.ongoing = false;
t.end = end;
t.size = size;
tags[ptr] = t;
#ifndef STXXL_BOOST_THREADS
mutex1.unlock();
#endif
}
void debugmon::block_deallocated(char * ptr)
{
#ifdef STXXL_BOOST_THREADS
boost::mutex::scoped_lock Lock(mutex1);
#else
mutex1.lock();
#endif
STXXL_VERBOSE1("debugmon: block_deallocated from " << long (ptr));
assert(tags.find(ptr) != tags.end()); // allocated
tag t = tags[ptr];
assert(t.ongoing == false); // not ongoing
tags.erase(ptr);
size_t size = t.size;
STXXL_VERBOSE1("debugmon: block_deallocated to " << long (t.end));
char * endptr = (char *) t.end;
char * ptr1 = (char *) ptr;
ptr1 += size;
while (ptr1 < endptr)
{
STXXL_VERBOSE1("debugmon: block_deallocated next " << long (ptr1));
assert(tags.find(ptr1) != tags.end()); // allocated
tag t = tags[ptr1];
assert(t.ongoing == false); // not ongoing
assert(t.size == size); // chunk size
assert(t.end == endptr); // array end address
tags.erase(ptr1);
ptr1 += size;
}
#ifndef STXXL_BOOST_THREADS
mutex1.unlock();
#endif
}
void debugmon::io_started(char * ptr)
{
#ifdef STXXL_BOOST_THREADS
boost::mutex::scoped_lock Lock(mutex1);
#else
mutex1.lock();
#endif
STXXL_VERBOSE1("debugmon: I/O on block " << long (ptr) << " started");
assert(tags.find(ptr) != tags.end()); // allocated
tag t = tags[ptr];
//assert(t.ongoing == false); // not ongoing
if (t.ongoing == true)
STXXL_ERRMSG("debugmon: I/O on block " << long (ptr) << " started, but block is already busy");
t.ongoing = true;
tags[ptr] = t;
#ifndef STXXL_BOOST_THREADS
mutex1.unlock();
#endif
}
void debugmon::io_finished(char * ptr)
{
#ifdef STXXL_BOOST_THREADS
boost::mutex::scoped_lock Lock(mutex1);
#else
mutex1.lock();
#endif
STXXL_VERBOSE1("debugmon: I/O on block " << long (ptr) << " finished");
assert(tags.find(ptr) != tags.end()); // allocated
tag t = tags[ptr];
//assert(t.ongoing == true); // ongoing
if (t.ongoing == false)
STXXL_ERRMSG("debugmon: I/O on block " << long (ptr) << " finished, but block was not busy");
t.ongoing = false;
tags[ptr] = t;
#ifndef STXXL_BOOST_THREADS
mutex1.unlock();
#endif
}
#endif
__STXXL_END_NAMESPACE
<|endoftext|> |
<commit_before><commit_msg>scope header file paths<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: lotimpop.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2005-09-08 19:41:41 $
*
* 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 "lotimpop.hxx"
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#include "attrib.hxx"
#include "document.hxx"
#include "rangenam.hxx"
#include "cell.hxx"
#include "patattr.hxx"
#include "docpool.hxx"
#include "compiler.hxx"
#include "global.hxx"
#include "root.hxx"
#include "lotfntbf.hxx"
#include "lotform.hxx"
#include "tool.h"
#include "namebuff.hxx"
#include "lotrange.hxx"
#include "lotattr.hxx"
static NAMESPACE_VOS( OMutex ) aLotImpSemaphore;
ImportLotus::ImportLotus( SvStream& aStream, ScDocument* pDoc, CharSet eQ ) :
ImportTyp( pDoc, eQ ),
pIn( &aStream ),
aConv( *pIn, eQ, FALSE )
{
// good point to start locking of import lotus
aLotImpSemaphore.acquire();
pLotusRoot = new LOTUS_ROOT;
pLotusRoot->pDoc = pDoc;
pLotusRoot->pRangeNames = new LotusRangeList;
pLotusRoot->pScRangeName = pDoc->GetRangeName();
pLotusRoot->eCharsetQ = eQ;
pLotusRoot->eFirstType = Lotus_X;
pLotusRoot->eActType = Lotus_X;
pLotusRoot->pRngNmBffWK3 = new RangeNameBufferWK3;
pFontBuff = pLotusRoot->pFontBuff = new LotusFontBuffer;
pLotusRoot->pAttrTable = new LotAttrTable;
}
ImportLotus::~ImportLotus()
{
delete pLotusRoot->pRangeNames;
delete pLotusRoot->pRngNmBffWK3;
delete pFontBuff;
delete pLotusRoot->pAttrTable;
delete pLotusRoot;
#ifdef DBG_UTIL
pLotusRoot = NULL;
#endif
// no need 4 pLotusRoot anymore
aLotImpSemaphore.release();
}
void ImportLotus::Bof( void )
{
UINT16 nFileCode, nFileSub, nSaveCnt;
BYTE nMajorId, nMinorId, nFlags;
Read( nFileCode );
Read( nFileSub );
Read( pLotusRoot->aActRange );
Read( nSaveCnt );
Read( nMajorId );
Read( nMinorId );
Skip( 1 );
Read( nFlags );
if( nFileSub == 0x0004 )
{
if( nFileCode == 0x1000 )
{// <= WK3
pLotusRoot->eFirstType = pLotusRoot->eActType = Lotus_WK3;
}
else if( nFileCode == 0x1002 )
{// WK4
pLotusRoot->eFirstType = pLotusRoot->eActType = Lotus_WK4;
}
}
}
BOOL ImportLotus::BofFm3( void )
{
UINT16 nFileCode, nFileSub;
Read( nFileCode );
Read( nFileSub );
return ( nFileCode == 0x8007 && ( nFileSub == 0x0000 || nFileSub == 0x00001 ) );
}
void ImportLotus::Columnwidth( UINT16 nRecLen )
{
DBG_ASSERT( nRecLen >= 4, "*ImportLotus::Columnwidth(): Record zu kurz!" );
BYTE nTab, nWindow2;
UINT16 nCnt = ( nRecLen - 4 ) / 2;
Read( nTab );
Read( nWindow2 );
if( !pD->HasTable( static_cast<SCTAB> (nTab) ) )
pD->MakeTable( static_cast<SCTAB> (nTab) );
if( !nWindow2 )
{
Skip( 2 );
BYTE nCol, nSpaces;
while( nCnt )
{
Read( nCol );
Read( nSpaces );
// ACHTUNG: Korrekturfaktor nach 'Augenmass' ermittelt!
pD->SetColWidth( static_cast<SCCOL> (nCol), static_cast<SCTAB> (nTab), ( UINT16 ) ( TWIPS_PER_CHAR * 1.28 * nSpaces ) );
nCnt--;
}
}
}
void ImportLotus::Hiddencolumn( UINT16 nRecLen )
{
DBG_ASSERT( nRecLen >= 4, "*ImportLotus::Hiddencolumn(): Record zu kurz!" );
BYTE nTab, nWindow2;
UINT16 nCnt = ( nRecLen - 4 ) / 2;
Read( nTab );
Read( nWindow2 );
if( !nWindow2 )
{
Skip( 2 );
BYTE nCol;
while( nCnt )
{
Read( nCol );
pD->SetColFlags( static_cast<SCCOL> (nCol), static_cast<SCTAB> (nTab), pD->GetColFlags( static_cast<SCCOL> (nCol), static_cast<SCTAB> (nTab) ) | CR_HIDDEN );
nCnt--;
}
}
}
void ImportLotus::Userrange( void )
{
UINT16 nRangeType;
ScRange aScRange;
sal_Char* pBuffer = new sal_Char[ 32 ];
Read( nRangeType );
pIn->Read( pBuffer, 16 );
pBuffer[ 16 ] = ( sal_Char ) 0x00; // zur Sicherheit...
String aName( pBuffer, eQuellChar );
Read( aScRange );
pLotusRoot->pRngNmBffWK3->Add( aName, aScRange );
delete[] pBuffer;
}
void ImportLotus::Errcell( void )
{
ScAddress aA;
Read( aA );
pD->PutCell( aA.Col(), aA.Row(), aA.Tab(), new ScStringCell( CREATE_STRING( "#ERR!" ) ), (BOOL)TRUE );
}
void ImportLotus::Nacell( void )
{
ScAddress aA;
Read( aA );
pD->PutCell( aA.Col(), aA.Row(), aA.Tab(), new ScStringCell( CREATE_STRING( "#NA!" ) ), (BOOL)TRUE );
}
void ImportLotus::Labelcell( void )
{
ScAddress aA;
String aLabel;
sal_Char cAlign;
Read( aA );
Read( cAlign );
Read( aLabel );
// aLabel.Convert( pLotusRoot->eCharsetQ );
pD->PutCell( aA.Col(), aA.Row(), aA.Tab(), new ScStringCell( aLabel ), (BOOL)TRUE );
}
void ImportLotus::Numbercell( void )
{
ScAddress aAddr;
double fVal;
Read( aAddr );
Read( fVal );
pD->PutCell( aAddr.Col(), aAddr.Row(), aAddr.Tab(),
new ScValueCell( fVal ), (BOOL)TRUE );
}
void ImportLotus::Smallnumcell( void )
{
ScAddress aAddr;
INT16 nVal;
Read( aAddr );
Read( nVal );
pD->PutCell( aAddr.Col(), aAddr.Row(), aAddr.Tab(),
new ScValueCell( SnumToDouble( nVal ) ), ( BOOL ) TRUE );
}
ScFormulaCell *ImportLotus::Formulacell( UINT16 n )
{
DBG_ASSERT( pIn, "-ImportLotus::Formulacell(): Null-Stream -> Rums!" );
ScAddress aAddr;
Read( aAddr );
Skip( 10 );
n -= 14;
const ScTokenArray* pErg;
INT32 nRest = n;
aConv.Reset( aAddr );
aConv.SetWK3();
aConv.Convert( pErg, nRest );
ScFormulaCell* pZelle = new ScFormulaCell( pD, aAddr, pErg );
pZelle->AddRecalcMode( RECALCMODE_ONLOAD_ONCE );
pD->PutCell( aAddr.Col(), aAddr.Row(), aAddr.Tab(), pZelle, (BOOL)TRUE );
return NULL;
}
void ImportLotus::Read( String &r )
{
ScfTools::AppendCString( *pIn, r, eQuellChar );
}
void ImportLotus::RowPresentation( UINT16 nRecLen )
{
DBG_ASSERT( nRecLen > 4, "*ImportLotus::RowPresentation(): Record zu kurz!" );
BYTE nTab, nFlags;
UINT16 nRow, nHeight;
UINT16 nCnt = ( nRecLen - 4 ) / 8;
Read( nTab );
Skip( 1 );
while( nCnt )
{
Read( nRow );
Read( nHeight );
Skip( 2 );
Read( nFlags );
Skip( 1 );
if( nFlags & 0x02 ) // Fixed / Strech to fit fonts
{ // fixed
// Height in Lotus in 1/32 Points
nHeight *= 20; // -> 32 * TWIPS
nHeight /= 32; // -> TWIPS
pD->SetRowFlags( static_cast<SCROW> (nRow), static_cast<SCTAB> (nTab), pD->GetRowFlags( static_cast<SCROW> (nRow), static_cast<SCTAB> (nTab) ) | CR_MANUALSIZE );
pD->SetRowHeight( static_cast<SCROW> (nRow), static_cast<SCTAB> (nTab), nHeight );
}
nCnt--;
}
}
void ImportLotus::NamedSheet( void )
{
UINT16 nTab;
String aName;
Read( nTab );
Read( aName );
if( pD->HasTable( static_cast<SCTAB> (nTab) ) )
pD->RenameTab( static_cast<SCTAB> (nTab), aName );
else
pD->InsertTab( static_cast<SCTAB> (nTab), aName );
}
void ImportLotus::Font_Face( void )
{
BYTE nNum;
String aName;
Read( nNum );
// ACHTUNG: QUICK-HACK gegen unerklaerliche Loops
if( nNum > 7 )
return;
// ACHTUNG
Read( aName );
pFontBuff->SetName( nNum, aName );
}
void ImportLotus::Font_Type( void )
{
static const UINT16 nAnz = 8;
UINT16 nCnt;
UINT16 nType;
for( nCnt = 0 ; nCnt < nAnz ; nCnt++ )
{
Read( nType );
pFontBuff->SetType( nCnt, nType );
}
}
void ImportLotus::Font_Ysize( void )
{
static const UINT16 nAnz = 8;
UINT16 nCnt;
UINT16 nSize;
for( nCnt = 0 ; nCnt < nAnz ; nCnt++ )
{
Read( nSize );
pFontBuff->SetHeight( nCnt, nSize );
}
}
void ImportLotus::_Row( const UINT16 nRecLen )
{
DBG_ASSERT( nExtTab >= 0, "*ImportLotus::_Row(): Kann hier nicht sein!" );
UINT16 nRow;
UINT16 nHeight;
UINT16 nCntDwn = ( nRecLen - 4 ) / 5;
SCCOL nColCnt = 0;
UINT8 nRepeats;
LotAttrWK3 aAttr;
BOOL bCenter = FALSE;
SCCOL nCenterStart, nCenterEnd;
Read( nRow );
Read( nHeight );
nHeight &= 0x0FFF;
nHeight *= 22;
if( nHeight )
pD->SetRowHeight( static_cast<SCROW> (nRow), static_cast<SCTAB> (nExtTab), nHeight );
while( nCntDwn )
{
Read( aAttr );
Read( nRepeats );
if( aAttr.HasStyles() )
pLotusRoot->pAttrTable->SetAttr(
nColCnt, static_cast<SCCOL> ( nColCnt + nRepeats ), static_cast<SCROW> (nRow), aAttr );
// hier und NICHT in class LotAttrTable, weil nur Attributiert wird,
// wenn die anderen Attribute gesetzt sind
// -> bei Center-Attribute wird generell zentriert gesetzt
if( aAttr.IsCentered() )
{
if( bCenter )
{
if( pD->HasData( nColCnt, static_cast<SCROW> (nRow), static_cast<SCTAB> (nExtTab) ) )
{// neue Center nach vorheriger Center
pD->DoMerge( static_cast<SCTAB> (nExtTab), nCenterStart, static_cast<SCROW> (nRow), nCenterEnd, static_cast<SCROW> (nRow) );
nCenterStart = nColCnt;
}
}
else
{// ganz neue Center
bCenter = TRUE;
nCenterStart = nColCnt;
}
nCenterEnd = nColCnt + static_cast<SCCOL>(nRepeats);
}
else
{
if( bCenter )
{// evtl. alte Center bemachen
pD->DoMerge( static_cast<SCTAB> (nExtTab), nCenterStart, static_cast<SCROW> (nRow), nCenterEnd, static_cast<SCROW> (nRow) );
bCenter = FALSE;
}
}
nColCnt += static_cast<SCCOL>(nRepeats);
nColCnt++;
nCntDwn--;
}
if( bCenter )
// evtl. alte Center bemachen
pD->DoMerge( static_cast<SCTAB> (nExtTab), nCenterStart, static_cast<SCROW> (nRow), nCenterEnd, static_cast<SCROW> (nRow) );
}
<commit_msg>INTEGRATION: CWS pchfix01 (1.10.214); FILE MERGED 2006/07/12 10:02:00 kaib 1.10.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: lotimpop.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: kz $ $Date: 2006-07-21 12:28:07 $
*
* 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 "lotimpop.hxx"
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#include "attrib.hxx"
#include "document.hxx"
#include "rangenam.hxx"
#include "cell.hxx"
#include "patattr.hxx"
#include "docpool.hxx"
#include "compiler.hxx"
#include "global.hxx"
#include "root.hxx"
#include "lotfntbf.hxx"
#include "lotform.hxx"
#include "tool.h"
#include "namebuff.hxx"
#include "lotrange.hxx"
#include "lotattr.hxx"
static NAMESPACE_VOS( OMutex ) aLotImpSemaphore;
ImportLotus::ImportLotus( SvStream& aStream, ScDocument* pDoc, CharSet eQ ) :
ImportTyp( pDoc, eQ ),
pIn( &aStream ),
aConv( *pIn, eQ, FALSE )
{
// good point to start locking of import lotus
aLotImpSemaphore.acquire();
pLotusRoot = new LOTUS_ROOT;
pLotusRoot->pDoc = pDoc;
pLotusRoot->pRangeNames = new LotusRangeList;
pLotusRoot->pScRangeName = pDoc->GetRangeName();
pLotusRoot->eCharsetQ = eQ;
pLotusRoot->eFirstType = Lotus_X;
pLotusRoot->eActType = Lotus_X;
pLotusRoot->pRngNmBffWK3 = new RangeNameBufferWK3;
pFontBuff = pLotusRoot->pFontBuff = new LotusFontBuffer;
pLotusRoot->pAttrTable = new LotAttrTable;
}
ImportLotus::~ImportLotus()
{
delete pLotusRoot->pRangeNames;
delete pLotusRoot->pRngNmBffWK3;
delete pFontBuff;
delete pLotusRoot->pAttrTable;
delete pLotusRoot;
#ifdef DBG_UTIL
pLotusRoot = NULL;
#endif
// no need 4 pLotusRoot anymore
aLotImpSemaphore.release();
}
void ImportLotus::Bof( void )
{
UINT16 nFileCode, nFileSub, nSaveCnt;
BYTE nMajorId, nMinorId, nFlags;
Read( nFileCode );
Read( nFileSub );
Read( pLotusRoot->aActRange );
Read( nSaveCnt );
Read( nMajorId );
Read( nMinorId );
Skip( 1 );
Read( nFlags );
if( nFileSub == 0x0004 )
{
if( nFileCode == 0x1000 )
{// <= WK3
pLotusRoot->eFirstType = pLotusRoot->eActType = Lotus_WK3;
}
else if( nFileCode == 0x1002 )
{// WK4
pLotusRoot->eFirstType = pLotusRoot->eActType = Lotus_WK4;
}
}
}
BOOL ImportLotus::BofFm3( void )
{
UINT16 nFileCode, nFileSub;
Read( nFileCode );
Read( nFileSub );
return ( nFileCode == 0x8007 && ( nFileSub == 0x0000 || nFileSub == 0x00001 ) );
}
void ImportLotus::Columnwidth( UINT16 nRecLen )
{
DBG_ASSERT( nRecLen >= 4, "*ImportLotus::Columnwidth(): Record zu kurz!" );
BYTE nTab, nWindow2;
UINT16 nCnt = ( nRecLen - 4 ) / 2;
Read( nTab );
Read( nWindow2 );
if( !pD->HasTable( static_cast<SCTAB> (nTab) ) )
pD->MakeTable( static_cast<SCTAB> (nTab) );
if( !nWindow2 )
{
Skip( 2 );
BYTE nCol, nSpaces;
while( nCnt )
{
Read( nCol );
Read( nSpaces );
// ACHTUNG: Korrekturfaktor nach 'Augenmass' ermittelt!
pD->SetColWidth( static_cast<SCCOL> (nCol), static_cast<SCTAB> (nTab), ( UINT16 ) ( TWIPS_PER_CHAR * 1.28 * nSpaces ) );
nCnt--;
}
}
}
void ImportLotus::Hiddencolumn( UINT16 nRecLen )
{
DBG_ASSERT( nRecLen >= 4, "*ImportLotus::Hiddencolumn(): Record zu kurz!" );
BYTE nTab, nWindow2;
UINT16 nCnt = ( nRecLen - 4 ) / 2;
Read( nTab );
Read( nWindow2 );
if( !nWindow2 )
{
Skip( 2 );
BYTE nCol;
while( nCnt )
{
Read( nCol );
pD->SetColFlags( static_cast<SCCOL> (nCol), static_cast<SCTAB> (nTab), pD->GetColFlags( static_cast<SCCOL> (nCol), static_cast<SCTAB> (nTab) ) | CR_HIDDEN );
nCnt--;
}
}
}
void ImportLotus::Userrange( void )
{
UINT16 nRangeType;
ScRange aScRange;
sal_Char* pBuffer = new sal_Char[ 32 ];
Read( nRangeType );
pIn->Read( pBuffer, 16 );
pBuffer[ 16 ] = ( sal_Char ) 0x00; // zur Sicherheit...
String aName( pBuffer, eQuellChar );
Read( aScRange );
pLotusRoot->pRngNmBffWK3->Add( aName, aScRange );
delete[] pBuffer;
}
void ImportLotus::Errcell( void )
{
ScAddress aA;
Read( aA );
pD->PutCell( aA.Col(), aA.Row(), aA.Tab(), new ScStringCell( CREATE_STRING( "#ERR!" ) ), (BOOL)TRUE );
}
void ImportLotus::Nacell( void )
{
ScAddress aA;
Read( aA );
pD->PutCell( aA.Col(), aA.Row(), aA.Tab(), new ScStringCell( CREATE_STRING( "#NA!" ) ), (BOOL)TRUE );
}
void ImportLotus::Labelcell( void )
{
ScAddress aA;
String aLabel;
sal_Char cAlign;
Read( aA );
Read( cAlign );
Read( aLabel );
// aLabel.Convert( pLotusRoot->eCharsetQ );
pD->PutCell( aA.Col(), aA.Row(), aA.Tab(), new ScStringCell( aLabel ), (BOOL)TRUE );
}
void ImportLotus::Numbercell( void )
{
ScAddress aAddr;
double fVal;
Read( aAddr );
Read( fVal );
pD->PutCell( aAddr.Col(), aAddr.Row(), aAddr.Tab(),
new ScValueCell( fVal ), (BOOL)TRUE );
}
void ImportLotus::Smallnumcell( void )
{
ScAddress aAddr;
INT16 nVal;
Read( aAddr );
Read( nVal );
pD->PutCell( aAddr.Col(), aAddr.Row(), aAddr.Tab(),
new ScValueCell( SnumToDouble( nVal ) ), ( BOOL ) TRUE );
}
ScFormulaCell *ImportLotus::Formulacell( UINT16 n )
{
DBG_ASSERT( pIn, "-ImportLotus::Formulacell(): Null-Stream -> Rums!" );
ScAddress aAddr;
Read( aAddr );
Skip( 10 );
n -= 14;
const ScTokenArray* pErg;
INT32 nRest = n;
aConv.Reset( aAddr );
aConv.SetWK3();
aConv.Convert( pErg, nRest );
ScFormulaCell* pZelle = new ScFormulaCell( pD, aAddr, pErg );
pZelle->AddRecalcMode( RECALCMODE_ONLOAD_ONCE );
pD->PutCell( aAddr.Col(), aAddr.Row(), aAddr.Tab(), pZelle, (BOOL)TRUE );
return NULL;
}
void ImportLotus::Read( String &r )
{
ScfTools::AppendCString( *pIn, r, eQuellChar );
}
void ImportLotus::RowPresentation( UINT16 nRecLen )
{
DBG_ASSERT( nRecLen > 4, "*ImportLotus::RowPresentation(): Record zu kurz!" );
BYTE nTab, nFlags;
UINT16 nRow, nHeight;
UINT16 nCnt = ( nRecLen - 4 ) / 8;
Read( nTab );
Skip( 1 );
while( nCnt )
{
Read( nRow );
Read( nHeight );
Skip( 2 );
Read( nFlags );
Skip( 1 );
if( nFlags & 0x02 ) // Fixed / Strech to fit fonts
{ // fixed
// Height in Lotus in 1/32 Points
nHeight *= 20; // -> 32 * TWIPS
nHeight /= 32; // -> TWIPS
pD->SetRowFlags( static_cast<SCROW> (nRow), static_cast<SCTAB> (nTab), pD->GetRowFlags( static_cast<SCROW> (nRow), static_cast<SCTAB> (nTab) ) | CR_MANUALSIZE );
pD->SetRowHeight( static_cast<SCROW> (nRow), static_cast<SCTAB> (nTab), nHeight );
}
nCnt--;
}
}
void ImportLotus::NamedSheet( void )
{
UINT16 nTab;
String aName;
Read( nTab );
Read( aName );
if( pD->HasTable( static_cast<SCTAB> (nTab) ) )
pD->RenameTab( static_cast<SCTAB> (nTab), aName );
else
pD->InsertTab( static_cast<SCTAB> (nTab), aName );
}
void ImportLotus::Font_Face( void )
{
BYTE nNum;
String aName;
Read( nNum );
// ACHTUNG: QUICK-HACK gegen unerklaerliche Loops
if( nNum > 7 )
return;
// ACHTUNG
Read( aName );
pFontBuff->SetName( nNum, aName );
}
void ImportLotus::Font_Type( void )
{
static const UINT16 nAnz = 8;
UINT16 nCnt;
UINT16 nType;
for( nCnt = 0 ; nCnt < nAnz ; nCnt++ )
{
Read( nType );
pFontBuff->SetType( nCnt, nType );
}
}
void ImportLotus::Font_Ysize( void )
{
static const UINT16 nAnz = 8;
UINT16 nCnt;
UINT16 nSize;
for( nCnt = 0 ; nCnt < nAnz ; nCnt++ )
{
Read( nSize );
pFontBuff->SetHeight( nCnt, nSize );
}
}
void ImportLotus::_Row( const UINT16 nRecLen )
{
DBG_ASSERT( nExtTab >= 0, "*ImportLotus::_Row(): Kann hier nicht sein!" );
UINT16 nRow;
UINT16 nHeight;
UINT16 nCntDwn = ( nRecLen - 4 ) / 5;
SCCOL nColCnt = 0;
UINT8 nRepeats;
LotAttrWK3 aAttr;
BOOL bCenter = FALSE;
SCCOL nCenterStart, nCenterEnd;
Read( nRow );
Read( nHeight );
nHeight &= 0x0FFF;
nHeight *= 22;
if( nHeight )
pD->SetRowHeight( static_cast<SCROW> (nRow), static_cast<SCTAB> (nExtTab), nHeight );
while( nCntDwn )
{
Read( aAttr );
Read( nRepeats );
if( aAttr.HasStyles() )
pLotusRoot->pAttrTable->SetAttr(
nColCnt, static_cast<SCCOL> ( nColCnt + nRepeats ), static_cast<SCROW> (nRow), aAttr );
// hier und NICHT in class LotAttrTable, weil nur Attributiert wird,
// wenn die anderen Attribute gesetzt sind
// -> bei Center-Attribute wird generell zentriert gesetzt
if( aAttr.IsCentered() )
{
if( bCenter )
{
if( pD->HasData( nColCnt, static_cast<SCROW> (nRow), static_cast<SCTAB> (nExtTab) ) )
{// neue Center nach vorheriger Center
pD->DoMerge( static_cast<SCTAB> (nExtTab), nCenterStart, static_cast<SCROW> (nRow), nCenterEnd, static_cast<SCROW> (nRow) );
nCenterStart = nColCnt;
}
}
else
{// ganz neue Center
bCenter = TRUE;
nCenterStart = nColCnt;
}
nCenterEnd = nColCnt + static_cast<SCCOL>(nRepeats);
}
else
{
if( bCenter )
{// evtl. alte Center bemachen
pD->DoMerge( static_cast<SCTAB> (nExtTab), nCenterStart, static_cast<SCROW> (nRow), nCenterEnd, static_cast<SCROW> (nRow) );
bCenter = FALSE;
}
}
nColCnt += static_cast<SCCOL>(nRepeats);
nColCnt++;
nCntDwn--;
}
if( bCenter )
// evtl. alte Center bemachen
pD->DoMerge( static_cast<SCTAB> (nExtTab), nCenterStart, static_cast<SCROW> (nRow), nCenterEnd, static_cast<SCROW> (nRow) );
}
<|endoftext|> |
<commit_before>#include <babylon/materials/node/blocks/dual/light_block.h>
#include <babylon/babylon_stl_util.h>
#include <babylon/core/json_util.h>
#include <babylon/materials/material_helper.h>
#include <babylon/materials/node/blocks/input/input_block.h>
#include <babylon/materials/node/node_material.h>
#include <babylon/materials/node/node_material_build_state.h>
#include <babylon/materials/node/node_material_build_state_shared_data.h>
#include <babylon/materials/node/node_material_connection_point.h>
#include <babylon/materials/node/node_material_defines.h>
#include <babylon/meshes/abstract_mesh.h>
#include <babylon/meshes/mesh.h>
#include <babylon/misc/string_tools.h>
namespace BABYLON {
LightBlock::LightBlock(const std::string& iName)
: NodeMaterialBlock{iName, NodeMaterialBlockTargets::VertexAndFragment}
, light{nullptr}
, worldPosition{this, &LightBlock::get_worldPosition}
, worldNormal{this, &LightBlock::get_worldNormal}
, cameraPosition{this, &LightBlock::get_cameraPosition}
, glossiness{this, &LightBlock::get_glossiness}
, glossPower{this, &LightBlock::get_glossPower}
, diffuseColor{this, &LightBlock::get_diffuseColor}
, specularColor{this, &LightBlock::get_specularColor}
, view{this, &LightBlock::get_view}
, diffuseOutput{this, &LightBlock::get_diffuseOutput}
, specularOutput{this, &LightBlock::get_specularOutput}
, shadow{this, &LightBlock::get_shadow}
{
_isUnique = true;
registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes::Vector4, false,
NodeMaterialBlockTargets::Vertex);
registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes::Vector4, false,
NodeMaterialBlockTargets::Fragment);
registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes::Vector3, false,
NodeMaterialBlockTargets::Fragment);
registerInput("glossiness", NodeMaterialBlockConnectionPointTypes::Float, true,
NodeMaterialBlockTargets::Fragment);
registerInput("glossPower", NodeMaterialBlockConnectionPointTypes::Float, true,
NodeMaterialBlockTargets::Fragment);
registerInput("diffuseColor", NodeMaterialBlockConnectionPointTypes::Color3, true,
NodeMaterialBlockTargets::Fragment);
registerInput("specularColor", NodeMaterialBlockConnectionPointTypes::Color3, true,
NodeMaterialBlockTargets::Fragment);
registerInput("view", NodeMaterialBlockConnectionPointTypes::Matrix, true);
registerOutput("diffuseOutput", NodeMaterialBlockConnectionPointTypes::Color3,
NodeMaterialBlockTargets::Fragment);
registerOutput("specularOutput", NodeMaterialBlockConnectionPointTypes::Color3,
NodeMaterialBlockTargets::Fragment);
registerOutput("shadow", NodeMaterialBlockConnectionPointTypes::Float,
NodeMaterialBlockTargets::Fragment);
}
LightBlock::~LightBlock() = default;
std::string LightBlock::getClassName() const
{
return "LightBlock";
}
NodeMaterialConnectionPointPtr& LightBlock::get_worldPosition()
{
return _inputs[0];
}
NodeMaterialConnectionPointPtr& LightBlock::get_worldNormal()
{
return _inputs[1];
}
NodeMaterialConnectionPointPtr& LightBlock::get_cameraPosition()
{
return _inputs[2];
}
NodeMaterialConnectionPointPtr& LightBlock::get_glossiness()
{
return _inputs[3];
}
NodeMaterialConnectionPointPtr& LightBlock::get_glossPower()
{
return _inputs[4];
}
NodeMaterialConnectionPointPtr& LightBlock::get_diffuseColor()
{
return _inputs[5];
}
NodeMaterialConnectionPointPtr& LightBlock::get_specularColor()
{
return _inputs[6];
}
NodeMaterialConnectionPointPtr& LightBlock::get_view()
{
return _inputs[7];
}
NodeMaterialConnectionPointPtr& LightBlock::get_diffuseOutput()
{
return _outputs[0];
}
NodeMaterialConnectionPointPtr& LightBlock::get_specularOutput()
{
return _outputs[1];
}
NodeMaterialConnectionPointPtr& LightBlock::get_shadow()
{
return _outputs[2];
}
void LightBlock::autoConfigure(const NodeMaterialPtr& material)
{
if (!cameraPosition()->isConnected()) {
auto cameraPositionInput
= material->getInputBlockByPredicate([](const InputBlockPtr& b) -> bool {
return b->systemValue() == NodeMaterialSystemValues::CameraPosition;
});
if (!cameraPositionInput) {
cameraPositionInput = InputBlock::New("cameraPosition");
cameraPositionInput->setAsSystemValue(NodeMaterialSystemValues::CameraPosition);
}
cameraPositionInput->output()->connectTo(cameraPosition());
}
}
void LightBlock::prepareDefines(AbstractMesh* mesh, const NodeMaterialPtr& nodeMaterial,
NodeMaterialDefines& defines, bool /*useInstances*/,
SubMesh* /*subMesh*/)
{
if (!defines._areLightsDirty) {
return;
}
auto scene = mesh->getScene();
if (!light) {
MaterialHelper::PrepareDefinesForLights(scene, mesh, defines, true,
nodeMaterial->maxSimultaneousLights);
}
else {
PrepareDefinesForLightsState state{
false, // needNormals
false, // needRebuild
false, // shadowEnabled
false, // specularEnabled
false // lightmapMode
};
MaterialHelper::PrepareDefinesForLight(scene, mesh, light, _lightId, defines, true, state);
if (state.needRebuild) {
defines.rebuild();
}
}
}
void LightBlock::updateUniformsAndSamples(NodeMaterialBuildState& state,
const NodeMaterialPtr& nodeMaterial,
const NodeMaterialDefines& defines,
std::vector<std::string>& uniformBuffers)
{
for (auto lightIndex = 0u; lightIndex < nodeMaterial->maxSimultaneousLights; ++lightIndex) {
const auto lightIndexStr = std::to_string(lightIndex);
if (!defines["LIGHT" + lightIndexStr]) {
break;
}
MaterialHelper::PrepareUniformsAndSamplersForLight(
lightIndex, state.uniforms, state.samplers, uniformBuffers, true,
defines["PROJECTEDLIGHTTEXTURE" + lightIndexStr]);
}
}
void LightBlock::bind(Effect* effect, const NodeMaterialPtr& nodeMaterial, Mesh* mesh,
SubMesh* /*subMesh*/)
{
if (!mesh) {
return;
}
auto scene = mesh->getScene();
if (!light) {
MaterialHelper::BindLights(scene, mesh, effect, true, nodeMaterial->maxSimultaneousLights);
}
else {
MaterialHelper::BindLight(light, _lightId, scene, effect, true);
}
}
void LightBlock::_injectVertexCode(NodeMaterialBuildState& state)
{
const auto& worldPos = worldPosition();
auto iComments = StringTools::printf("//%s", name().c_str());
// Declaration
if (!light) { // Emit for all lights
state._emitFunctionFromInclude(
state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", iComments,
EmitFunctionFromIncludeOptions{
"maxSimultaneousLights" // repeatKey
});
_lightId = 0;
state.sharedData->dynamicUniformBlocks.emplace_back(this);
}
else {
_lightId = static_cast<uint32_t>((stl_util::contains(state.counters, "lightCounter") ?
static_cast<int>(state.counters["lightCounter"]) :
-1)
+ 1);
state.counters["lightCounter"] = _lightId;
EmitFunctionFromIncludeOptions options;
options.replaceStrings = {StringsReplacement{
"{X}", // search
std::to_string(_lightId) // replace
}};
state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" :
"lightFragmentDeclaration",
iComments, options, std::to_string(_lightId));
}
// Inject code in vertex
auto worldPosVaryingName
= StringTools::printf("v_%s", worldPos->associatedVariableName().c_str());
if (state._emitVaryingFromString(worldPosVaryingName, "vec4")) {
state.compilationString += StringTools::printf("%s = %s;\r\n", worldPosVaryingName.c_str(),
worldPos->associatedVariableName().c_str());
}
if (light) {
EmitCodeFromIncludeOptions options;
options.replaceStrings = {StringsReplacement{
"{X}", // search
std::to_string(_lightId) // replace
},
StringsReplacement{
"worldPos", // search
worldPos->associatedVariableName() // replace
}};
state.compilationString += state._emitCodeFromInclude("shadowsVertex", iComments, options);
}
else {
state.compilationString
+= StringTools::printf("vec4 worldPos = %s;\r\n", worldPos->associatedVariableName().c_str());
if (view()->isConnected()) {
state.compilationString
+= StringTools::printf("mat4 view = %s;\r\n", view()->associatedVariableName().c_str());
}
EmitCodeFromIncludeOptions options;
options.repeatKey = "maxSimultaneousLights";
state.compilationString += state._emitCodeFromInclude("shadowsVertex", iComments, options);
}
}
LightBlock& LightBlock::_buildBlock(NodeMaterialBuildState& state)
{
NodeMaterialBlock::_buildBlock(state);
if (state.target != NodeMaterialBlockTargets::Fragment) {
// Vertex
_injectVertexCode(state);
return *this;
}
// Fragment
state.sharedData->bindableBlocks.emplace_back(shared_from_this());
state.sharedData->blocksWithDefines.emplace_back(shared_from_this());
auto iComments = StringTools::printf("//%s", name().c_str());
const auto& worldPos = worldPosition();
state._emitFunctionFromInclude("helperFunctions", iComments);
EmitFunctionFromIncludeOptions options;
options.replaceStrings = {StringsReplacement{
"vPositionW", // search
StringTools::printf("v_%s.xyz", worldPos->associatedVariableName().c_str()) // replace
}};
state._emitFunctionFromInclude("lightsFragmentFunctions", iComments, options);
state._emitFunctionFromInclude("shadowsFragmentFunctions", iComments, options);
if (!light) { // Emit for all lights
state._emitFunctionFromInclude(
state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", iComments,
EmitFunctionFromIncludeOptions{
"maxSimultaneousLights" // repeatKey
});
}
else {
options.replaceStrings = {StringsReplacement{
"{X}", // search
std::to_string(_lightId) // replace
}};
state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" :
"lightFragmentDeclaration",
iComments, options, std::to_string(_lightId));
}
// Code
if (_lightId == 0) {
if (state._registerTempVariable("viewDirectionW")) {
state.compilationString += StringTools::printf(
"vec3 viewDirectionW = normalize(%s - %s);\r\n",
cameraPosition()->associatedVariableName().c_str(),
StringTools::printf("v_%s.xyz", worldPos->associatedVariableName().c_str()).c_str());
}
state.compilationString += "lightingInfo info;\r\n";
state.compilationString += "float shadow = 1.;\r\n";
state.compilationString += StringTools::printf(
"float glossiness = %s * %s;\r\n",
glossiness()->isConnected() ? glossiness()->associatedVariableName().c_str() : "1.0",
glossPower()->isConnected ? glossPower()->associatedVariableName().c_str() : "1024.0");
state.compilationString += "vec3 diffuseBase = vec3(0., 0., 0.);\r\n";
state.compilationString += "vec3 specularBase = vec3(0., 0., 0.);\r\n";
state.compilationString += StringTools::printf("vec3 normalW = %s.xyz;\r\n",
worldNormal()->associatedVariableName().c_str());
}
if (light) {
options.replaceStrings = {StringsReplacement{
"{X}", // search
std::to_string(_lightId) // replace
}};
}
else {
EmitCodeFromIncludeOptions includeOptions;
includeOptions.repeatKey = "maxSimultaneousLights";
state.compilationString
+= state._emitCodeFromInclude("lightFragment", iComments, includeOptions);
}
const auto& _diffuseOutput = diffuseOutput();
const auto& _specularOutput = specularOutput();
state.compilationString
+= _declareOutput(_diffuseOutput, state)
+ StringTools::printf(
" = diffuseBase%s;\r\n",
diffuseColor()->isConnected() ?
StringTools::printf(" * %s", diffuseColor()->associatedVariableName().c_str()).c_str() :
"");
if (_specularOutput->hasEndpoints()) {
state.compilationString
+= _declareOutput(_specularOutput, state)
+ StringTools::printf(
" = specularBase%s;\r\n",
specularColor()->isConnected() ?
StringTools::printf(" * %s", specularColor()->associatedVariableName().c_str())
.c_str() :
"");
}
if (shadow()->hasEndpoints()) {
state.compilationString += _declareOutput(shadow, state) + " = shadow;\r\n";
}
return *this;
}
json LightBlock::serialize() const
{
return nullptr;
}
void LightBlock::_deserialize(const json& /*serializationObject*/, Scene* /*scene*/,
const std::string& /*rootUrl*/)
{
}
} // end of namespace BABYLON
<commit_msg>Using onlyUpdateBuffersList value<commit_after>#include <babylon/materials/node/blocks/dual/light_block.h>
#include <babylon/babylon_stl_util.h>
#include <babylon/core/json_util.h>
#include <babylon/materials/material_helper.h>
#include <babylon/materials/node/blocks/input/input_block.h>
#include <babylon/materials/node/node_material.h>
#include <babylon/materials/node/node_material_build_state.h>
#include <babylon/materials/node/node_material_build_state_shared_data.h>
#include <babylon/materials/node/node_material_connection_point.h>
#include <babylon/materials/node/node_material_defines.h>
#include <babylon/meshes/abstract_mesh.h>
#include <babylon/meshes/mesh.h>
#include <babylon/misc/string_tools.h>
namespace BABYLON {
LightBlock::LightBlock(const std::string& iName)
: NodeMaterialBlock{iName, NodeMaterialBlockTargets::VertexAndFragment}
, light{nullptr}
, worldPosition{this, &LightBlock::get_worldPosition}
, worldNormal{this, &LightBlock::get_worldNormal}
, cameraPosition{this, &LightBlock::get_cameraPosition}
, glossiness{this, &LightBlock::get_glossiness}
, glossPower{this, &LightBlock::get_glossPower}
, diffuseColor{this, &LightBlock::get_diffuseColor}
, specularColor{this, &LightBlock::get_specularColor}
, view{this, &LightBlock::get_view}
, diffuseOutput{this, &LightBlock::get_diffuseOutput}
, specularOutput{this, &LightBlock::get_specularOutput}
, shadow{this, &LightBlock::get_shadow}
{
_isUnique = true;
registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes::Vector4, false,
NodeMaterialBlockTargets::Vertex);
registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes::Vector4, false,
NodeMaterialBlockTargets::Fragment);
registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes::Vector3, false,
NodeMaterialBlockTargets::Fragment);
registerInput("glossiness", NodeMaterialBlockConnectionPointTypes::Float, true,
NodeMaterialBlockTargets::Fragment);
registerInput("glossPower", NodeMaterialBlockConnectionPointTypes::Float, true,
NodeMaterialBlockTargets::Fragment);
registerInput("diffuseColor", NodeMaterialBlockConnectionPointTypes::Color3, true,
NodeMaterialBlockTargets::Fragment);
registerInput("specularColor", NodeMaterialBlockConnectionPointTypes::Color3, true,
NodeMaterialBlockTargets::Fragment);
registerInput("view", NodeMaterialBlockConnectionPointTypes::Matrix, true);
registerOutput("diffuseOutput", NodeMaterialBlockConnectionPointTypes::Color3,
NodeMaterialBlockTargets::Fragment);
registerOutput("specularOutput", NodeMaterialBlockConnectionPointTypes::Color3,
NodeMaterialBlockTargets::Fragment);
registerOutput("shadow", NodeMaterialBlockConnectionPointTypes::Float,
NodeMaterialBlockTargets::Fragment);
}
LightBlock::~LightBlock() = default;
std::string LightBlock::getClassName() const
{
return "LightBlock";
}
NodeMaterialConnectionPointPtr& LightBlock::get_worldPosition()
{
return _inputs[0];
}
NodeMaterialConnectionPointPtr& LightBlock::get_worldNormal()
{
return _inputs[1];
}
NodeMaterialConnectionPointPtr& LightBlock::get_cameraPosition()
{
return _inputs[2];
}
NodeMaterialConnectionPointPtr& LightBlock::get_glossiness()
{
return _inputs[3];
}
NodeMaterialConnectionPointPtr& LightBlock::get_glossPower()
{
return _inputs[4];
}
NodeMaterialConnectionPointPtr& LightBlock::get_diffuseColor()
{
return _inputs[5];
}
NodeMaterialConnectionPointPtr& LightBlock::get_specularColor()
{
return _inputs[6];
}
NodeMaterialConnectionPointPtr& LightBlock::get_view()
{
return _inputs[7];
}
NodeMaterialConnectionPointPtr& LightBlock::get_diffuseOutput()
{
return _outputs[0];
}
NodeMaterialConnectionPointPtr& LightBlock::get_specularOutput()
{
return _outputs[1];
}
NodeMaterialConnectionPointPtr& LightBlock::get_shadow()
{
return _outputs[2];
}
void LightBlock::autoConfigure(const NodeMaterialPtr& material)
{
if (!cameraPosition()->isConnected()) {
auto cameraPositionInput
= material->getInputBlockByPredicate([](const InputBlockPtr& b) -> bool {
return b->systemValue() == NodeMaterialSystemValues::CameraPosition;
});
if (!cameraPositionInput) {
cameraPositionInput = InputBlock::New("cameraPosition");
cameraPositionInput->setAsSystemValue(NodeMaterialSystemValues::CameraPosition);
}
cameraPositionInput->output()->connectTo(cameraPosition());
}
}
void LightBlock::prepareDefines(AbstractMesh* mesh, const NodeMaterialPtr& nodeMaterial,
NodeMaterialDefines& defines, bool /*useInstances*/,
SubMesh* /*subMesh*/)
{
if (!defines._areLightsDirty) {
return;
}
auto scene = mesh->getScene();
if (!light) {
MaterialHelper::PrepareDefinesForLights(scene, mesh, defines, true,
nodeMaterial->maxSimultaneousLights);
}
else {
PrepareDefinesForLightsState state{
false, // needNormals
false, // needRebuild
false, // shadowEnabled
false, // specularEnabled
false // lightmapMode
};
MaterialHelper::PrepareDefinesForLight(scene, mesh, light, _lightId, defines, true, state);
if (state.needRebuild) {
defines.rebuild();
}
}
}
void LightBlock::updateUniformsAndSamples(NodeMaterialBuildState& state,
const NodeMaterialPtr& nodeMaterial,
const NodeMaterialDefines& defines,
std::vector<std::string>& uniformBuffers)
{
for (auto lightIndex = 0u; lightIndex < nodeMaterial->maxSimultaneousLights; ++lightIndex) {
const auto lightIndexStr = std::to_string(lightIndex);
if (!defines["LIGHT" + lightIndexStr]) {
break;
}
const auto onlyUpdateBuffersList
= stl_util::index_of(state.uniforms, "vLightData" + lightIndexStr) >= 0;
MaterialHelper::PrepareUniformsAndSamplersForLight(
lightIndex, state.uniforms, state.samplers, uniformBuffers, true,
defines["PROJECTEDLIGHTTEXTURE" + lightIndexStr], onlyUpdateBuffersList);
}
}
void LightBlock::bind(Effect* effect, const NodeMaterialPtr& nodeMaterial, Mesh* mesh,
SubMesh* /*subMesh*/)
{
if (!mesh) {
return;
}
auto scene = mesh->getScene();
if (!light) {
MaterialHelper::BindLights(scene, mesh, effect, true, nodeMaterial->maxSimultaneousLights);
}
else {
MaterialHelper::BindLight(light, _lightId, scene, effect, true);
}
}
void LightBlock::_injectVertexCode(NodeMaterialBuildState& state)
{
const auto& worldPos = worldPosition();
auto iComments = StringTools::printf("//%s", name().c_str());
// Declaration
if (!light) { // Emit for all lights
state._emitFunctionFromInclude(
state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", iComments,
EmitFunctionFromIncludeOptions{
"maxSimultaneousLights" // repeatKey
});
_lightId = 0;
state.sharedData->dynamicUniformBlocks.emplace_back(this);
}
else {
_lightId = static_cast<uint32_t>((stl_util::contains(state.counters, "lightCounter") ?
static_cast<int>(state.counters["lightCounter"]) :
-1)
+ 1);
state.counters["lightCounter"] = _lightId;
EmitFunctionFromIncludeOptions options;
options.replaceStrings = {StringsReplacement{
"{X}", // search
std::to_string(_lightId) // replace
}};
state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" :
"lightFragmentDeclaration",
iComments, options, std::to_string(_lightId));
}
// Inject code in vertex
auto worldPosVaryingName
= StringTools::printf("v_%s", worldPos->associatedVariableName().c_str());
if (state._emitVaryingFromString(worldPosVaryingName, "vec4")) {
state.compilationString += StringTools::printf("%s = %s;\r\n", worldPosVaryingName.c_str(),
worldPos->associatedVariableName().c_str());
}
if (light) {
EmitCodeFromIncludeOptions options;
options.replaceStrings = {StringsReplacement{
"{X}", // search
std::to_string(_lightId) // replace
},
StringsReplacement{
"worldPos", // search
worldPos->associatedVariableName() // replace
}};
state.compilationString += state._emitCodeFromInclude("shadowsVertex", iComments, options);
}
else {
state.compilationString
+= StringTools::printf("vec4 worldPos = %s;\r\n", worldPos->associatedVariableName().c_str());
if (view()->isConnected()) {
state.compilationString
+= StringTools::printf("mat4 view = %s;\r\n", view()->associatedVariableName().c_str());
}
EmitCodeFromIncludeOptions options;
options.repeatKey = "maxSimultaneousLights";
state.compilationString += state._emitCodeFromInclude("shadowsVertex", iComments, options);
}
}
LightBlock& LightBlock::_buildBlock(NodeMaterialBuildState& state)
{
NodeMaterialBlock::_buildBlock(state);
if (state.target != NodeMaterialBlockTargets::Fragment) {
// Vertex
_injectVertexCode(state);
return *this;
}
// Fragment
state.sharedData->bindableBlocks.emplace_back(shared_from_this());
state.sharedData->blocksWithDefines.emplace_back(shared_from_this());
auto iComments = StringTools::printf("//%s", name().c_str());
const auto& worldPos = worldPosition();
state._emitFunctionFromInclude("helperFunctions", iComments);
EmitFunctionFromIncludeOptions options;
options.replaceStrings = {StringsReplacement{
"vPositionW", // search
StringTools::printf("v_%s.xyz", worldPos->associatedVariableName().c_str()) // replace
}};
state._emitFunctionFromInclude("lightsFragmentFunctions", iComments, options);
state._emitFunctionFromInclude("shadowsFragmentFunctions", iComments, options);
if (!light) { // Emit for all lights
state._emitFunctionFromInclude(
state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", iComments,
EmitFunctionFromIncludeOptions{
"maxSimultaneousLights" // repeatKey
});
}
else {
options.replaceStrings = {StringsReplacement{
"{X}", // search
std::to_string(_lightId) // replace
}};
state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" :
"lightFragmentDeclaration",
iComments, options, std::to_string(_lightId));
}
// Code
if (_lightId == 0) {
if (state._registerTempVariable("viewDirectionW")) {
state.compilationString += StringTools::printf(
"vec3 viewDirectionW = normalize(%s - %s);\r\n",
cameraPosition()->associatedVariableName().c_str(),
StringTools::printf("v_%s.xyz", worldPos->associatedVariableName().c_str()).c_str());
}
state.compilationString += "lightingInfo info;\r\n";
state.compilationString += "float shadow = 1.;\r\n";
state.compilationString += StringTools::printf(
"float glossiness = %s * %s;\r\n",
glossiness()->isConnected() ? glossiness()->associatedVariableName().c_str() : "1.0",
glossPower()->isConnected ? glossPower()->associatedVariableName().c_str() : "1024.0");
state.compilationString += "vec3 diffuseBase = vec3(0., 0., 0.);\r\n";
state.compilationString += "vec3 specularBase = vec3(0., 0., 0.);\r\n";
state.compilationString += StringTools::printf("vec3 normalW = %s.xyz;\r\n",
worldNormal()->associatedVariableName().c_str());
}
if (light) {
options.replaceStrings = {StringsReplacement{
"{X}", // search
std::to_string(_lightId) // replace
}};
}
else {
EmitCodeFromIncludeOptions includeOptions;
includeOptions.repeatKey = "maxSimultaneousLights";
state.compilationString
+= state._emitCodeFromInclude("lightFragment", iComments, includeOptions);
}
const auto& _diffuseOutput = diffuseOutput();
const auto& _specularOutput = specularOutput();
state.compilationString
+= _declareOutput(_diffuseOutput, state)
+ StringTools::printf(
" = diffuseBase%s;\r\n",
diffuseColor()->isConnected() ?
StringTools::printf(" * %s", diffuseColor()->associatedVariableName().c_str()).c_str() :
"");
if (_specularOutput->hasEndpoints()) {
state.compilationString
+= _declareOutput(_specularOutput, state)
+ StringTools::printf(
" = specularBase%s;\r\n",
specularColor()->isConnected() ?
StringTools::printf(" * %s", specularColor()->associatedVariableName().c_str())
.c_str() :
"");
}
if (shadow()->hasEndpoints()) {
state.compilationString += _declareOutput(shadow, state) + " = shadow;\r\n";
}
return *this;
}
json LightBlock::serialize() const
{
return nullptr;
}
void LightBlock::_deserialize(const json& /*serializationObject*/, Scene* /*scene*/,
const std::string& /*rootUrl*/)
{
}
} // end of namespace BABYLON
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: scuiimoptdlg.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2004-08-23 09:31:26 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#undef SC_DLLIMPLEMENTATION
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
#include "scuiimoptdlg.hxx"
#include "scresid.hxx"
#include "imoptdlg.hrc"
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
//========================================================================
// ScDelimiterTable
//========================================================================
class ScDelimiterTable
{
public:
ScDelimiterTable( const String& rDelTab )
: theDelTab ( rDelTab ),
cSep ( '\t' ),
nCount ( rDelTab.GetTokenCount('\t') ),
nIter ( 0 )
{}
USHORT GetCode( const String& rDelimiter ) const;
String GetDelimiter( sal_Unicode nCode ) const;
String FirstDel() { nIter = 0; return theDelTab.GetToken( nIter, cSep ); }
String NextDel() { nIter +=2; return theDelTab.GetToken( nIter, cSep ); }
private:
const String theDelTab;
const sal_Unicode cSep;
const xub_StrLen nCount;
xub_StrLen nIter;
};
//------------------------------------------------------------------------
USHORT ScDelimiterTable::GetCode( const String& rDel ) const
{
sal_Unicode nCode = 0;
xub_StrLen i = 0;
if ( nCount >= 2 )
{
while ( i<nCount )
{
if ( rDel == theDelTab.GetToken( i, cSep ) )
{
nCode = (sal_Unicode) theDelTab.GetToken( i+1, cSep ).ToInt32();
i = nCount;
}
else
i += 2;
}
}
return nCode;
}
//------------------------------------------------------------------------
String ScDelimiterTable::GetDelimiter( sal_Unicode nCode ) const
{
String aStrDel;
xub_StrLen i = 0;
if ( nCount >= 2 )
{
while ( i<nCount )
{
if ( nCode == (sal_Unicode) theDelTab.GetToken( i+1, cSep ).ToInt32() )
{
aStrDel = theDelTab.GetToken( i, cSep );
i = nCount;
}
else
i += 2;
}
}
return aStrDel;
}
//========================================================================
// ScImportOptionsDlg
//========================================================================
ScImportOptionsDlg::ScImportOptionsDlg(
Window* pParent,
BOOL bAscii,
const ScImportOptions* pOptions,
const String* pStrTitle,
BOOL bMultiByte,
BOOL bOnlyDbtoolsEncodings,
BOOL bImport )
: ModalDialog ( pParent, ScResId( RID_SCDLG_IMPORTOPT ) ),
aBtnOk ( this, ScResId( BTN_OK ) ),
aBtnCancel ( this, ScResId( BTN_CANCEL ) ),
aBtnHelp ( this, ScResId( BTN_HELP ) ),
aFtFieldSep ( this, ScResId( FT_FIELDSEP ) ),
aEdFieldSep ( this, ScResId( ED_FIELDSEP ) ),
aFtTextSep ( this, ScResId( FT_TEXTSEP ) ),
aEdTextSep ( this, ScResId( ED_TEXTSEP ) ),
aFtFont ( this, ScResId( FT_FONT ) ),
aLbFont ( this, ScResId( bAscii ? DDLB_FONT : LB_FONT ) ),
aFlFieldOpt ( this, ScResId( FL_FIELDOPT ) ),
aCbFixed ( this, ScResId( CB_FIXEDWIDTH ) )
{
// im Ctor-Initializer nicht moeglich (MSC kann das nicht):
pFieldSepTab = new ScDelimiterTable( String(ScResId(SCSTR_FIELDSEP)) );
pTextSepTab = new ScDelimiterTable( String(ScResId(SCSTR_TEXTSEP)) );
String aStr = pFieldSepTab->FirstDel();
sal_Unicode nCode;
while ( aStr.Len() > 0 )
{
aEdFieldSep.InsertEntry( aStr );
aStr = pFieldSepTab->NextDel();
}
aStr = pTextSepTab->FirstDel();
while ( aStr.Len() > 0 )
{
aEdTextSep.InsertEntry( aStr );
aStr = pTextSepTab->NextDel();
}
aEdFieldSep.SetText( aEdFieldSep.GetEntry(0) );
aEdTextSep.SetText( aEdTextSep.GetEntry(0) );
if ( bOnlyDbtoolsEncodings )
{ //!TODO: Unicode and MultiByte would need work in each filter
// Think of field lengths in dBase export
if ( bMultiByte )
aLbFont.FillFromDbTextEncodingMap( bImport, RTL_TEXTENCODING_INFO_UNICODE );
else
aLbFont.FillFromDbTextEncodingMap( bImport, RTL_TEXTENCODING_INFO_UNICODE |
RTL_TEXTENCODING_INFO_MULTIBYTE );
}
else if ( !bAscii )
{ //!TODO: Unicode would need work in each filter
if ( bMultiByte )
aLbFont.FillFromTextEncodingTable( bImport, RTL_TEXTENCODING_INFO_UNICODE );
else
aLbFont.FillFromTextEncodingTable( bImport, RTL_TEXTENCODING_INFO_UNICODE |
RTL_TEXTENCODING_INFO_MULTIBYTE );
}
else
{
if ( pOptions )
{
nCode = pOptions->nFieldSepCode;
aStr = pFieldSepTab->GetDelimiter( nCode );
if ( !aStr.Len() )
aEdFieldSep.SetText( String((sal_Unicode)nCode) );
else
aEdFieldSep.SetText( aStr );
nCode = pOptions->nTextSepCode;
aStr = pTextSepTab->GetDelimiter( nCode );
if ( !aStr.Len() )
aEdTextSep.SetText( String((sal_Unicode)nCode) );
else
aEdTextSep.SetText( aStr );
}
// all encodings allowed, even Unicode
aLbFont.FillFromTextEncodingTable( bImport );
}
if( bAscii )
{
Size aWinSize( GetSizePixel() );
aWinSize.Height() = aCbFixed.GetPosPixel().Y() + aCbFixed.GetSizePixel().Height();
Size aDiffSize( LogicToPixel( Size( 0, 6 ), MapMode( MAP_APPFONT ) ) );
aWinSize.Height() += aDiffSize.Height();
SetSizePixel( aWinSize );
aCbFixed.Show();
aCbFixed.SetClickHdl( LINK( this, ScImportOptionsDlg, FixedWidthHdl ) );
aCbFixed.Check( FALSE );
}
else
{
aFlFieldOpt.SetText( aFtFont.GetText() );
aFtFieldSep.Hide();
aFtTextSep.Hide();
aFtFont.Hide();
aEdFieldSep.Hide();
aEdTextSep.Hide();
aCbFixed.Hide();
aLbFont.GrabFocus();
aLbFont.SetDoubleClickHdl( LINK( this, ScImportOptionsDlg, DoubleClickHdl ) );
}
aLbFont.SelectTextEncoding( pOptions ? pOptions->eCharSet :
gsl_getSystemTextEncoding() );
// optionaler Titel:
if ( pStrTitle )
SetText( *pStrTitle );
FreeResource();
}
//------------------------------------------------------------------------
__EXPORT ScImportOptionsDlg::~ScImportOptionsDlg()
{
delete pFieldSepTab;
delete pTextSepTab;
}
//------------------------------------------------------------------------
void ScImportOptionsDlg::GetImportOptions( ScImportOptions& rOptions ) const
{
rOptions.SetTextEncoding( aLbFont.GetSelectTextEncoding() );
if ( aCbFixed.IsVisible() )
{
rOptions.nFieldSepCode = GetCodeFromCombo( aEdFieldSep );
rOptions.nTextSepCode = GetCodeFromCombo( aEdTextSep );
rOptions.bFixedWidth = aCbFixed.IsChecked();
}
}
//------------------------------------------------------------------------
USHORT ScImportOptionsDlg::GetCodeFromCombo( const ComboBox& rEd ) const
{
ScDelimiterTable* pTab;
String aStr( rEd.GetText() );
USHORT nCode;
if ( &rEd == &aEdTextSep )
pTab = pTextSepTab;
else
pTab = pFieldSepTab;
if ( !aStr.Len() )
{
nCode = 0; // kein Trennzeichen
}
else
{
nCode = pTab->GetCode( aStr );
if ( nCode == 0 )
nCode = (USHORT)aStr.GetChar(0);
}
return nCode;
}
//------------------------------------------------------------------------
IMPL_LINK( ScImportOptionsDlg, FixedWidthHdl, CheckBox*, pCheckBox )
{
if( pCheckBox == &aCbFixed )
{
BOOL bEnable = !aCbFixed.IsChecked();
aFtFieldSep.Enable( bEnable );
aEdFieldSep.Enable( bEnable );
aFtTextSep.Enable( bEnable );
aEdTextSep.Enable( bEnable );
}
return 0;
}
IMPL_LINK( ScImportOptionsDlg, DoubleClickHdl, ListBox*, pLb )
{
if ( pLb == &aLbFont )
{
aBtnOk.Click();
}
return 0;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.346); FILE MERGED 2005/09/05 15:04:25 rt 1.3.346.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: scuiimoptdlg.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 20:41:54 $
*
* 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
*
************************************************************************/
#undef SC_DLLIMPLEMENTATION
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
#include "scuiimoptdlg.hxx"
#include "scresid.hxx"
#include "imoptdlg.hrc"
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
//========================================================================
// ScDelimiterTable
//========================================================================
class ScDelimiterTable
{
public:
ScDelimiterTable( const String& rDelTab )
: theDelTab ( rDelTab ),
cSep ( '\t' ),
nCount ( rDelTab.GetTokenCount('\t') ),
nIter ( 0 )
{}
USHORT GetCode( const String& rDelimiter ) const;
String GetDelimiter( sal_Unicode nCode ) const;
String FirstDel() { nIter = 0; return theDelTab.GetToken( nIter, cSep ); }
String NextDel() { nIter +=2; return theDelTab.GetToken( nIter, cSep ); }
private:
const String theDelTab;
const sal_Unicode cSep;
const xub_StrLen nCount;
xub_StrLen nIter;
};
//------------------------------------------------------------------------
USHORT ScDelimiterTable::GetCode( const String& rDel ) const
{
sal_Unicode nCode = 0;
xub_StrLen i = 0;
if ( nCount >= 2 )
{
while ( i<nCount )
{
if ( rDel == theDelTab.GetToken( i, cSep ) )
{
nCode = (sal_Unicode) theDelTab.GetToken( i+1, cSep ).ToInt32();
i = nCount;
}
else
i += 2;
}
}
return nCode;
}
//------------------------------------------------------------------------
String ScDelimiterTable::GetDelimiter( sal_Unicode nCode ) const
{
String aStrDel;
xub_StrLen i = 0;
if ( nCount >= 2 )
{
while ( i<nCount )
{
if ( nCode == (sal_Unicode) theDelTab.GetToken( i+1, cSep ).ToInt32() )
{
aStrDel = theDelTab.GetToken( i, cSep );
i = nCount;
}
else
i += 2;
}
}
return aStrDel;
}
//========================================================================
// ScImportOptionsDlg
//========================================================================
ScImportOptionsDlg::ScImportOptionsDlg(
Window* pParent,
BOOL bAscii,
const ScImportOptions* pOptions,
const String* pStrTitle,
BOOL bMultiByte,
BOOL bOnlyDbtoolsEncodings,
BOOL bImport )
: ModalDialog ( pParent, ScResId( RID_SCDLG_IMPORTOPT ) ),
aBtnOk ( this, ScResId( BTN_OK ) ),
aBtnCancel ( this, ScResId( BTN_CANCEL ) ),
aBtnHelp ( this, ScResId( BTN_HELP ) ),
aFtFieldSep ( this, ScResId( FT_FIELDSEP ) ),
aEdFieldSep ( this, ScResId( ED_FIELDSEP ) ),
aFtTextSep ( this, ScResId( FT_TEXTSEP ) ),
aEdTextSep ( this, ScResId( ED_TEXTSEP ) ),
aFtFont ( this, ScResId( FT_FONT ) ),
aLbFont ( this, ScResId( bAscii ? DDLB_FONT : LB_FONT ) ),
aFlFieldOpt ( this, ScResId( FL_FIELDOPT ) ),
aCbFixed ( this, ScResId( CB_FIXEDWIDTH ) )
{
// im Ctor-Initializer nicht moeglich (MSC kann das nicht):
pFieldSepTab = new ScDelimiterTable( String(ScResId(SCSTR_FIELDSEP)) );
pTextSepTab = new ScDelimiterTable( String(ScResId(SCSTR_TEXTSEP)) );
String aStr = pFieldSepTab->FirstDel();
sal_Unicode nCode;
while ( aStr.Len() > 0 )
{
aEdFieldSep.InsertEntry( aStr );
aStr = pFieldSepTab->NextDel();
}
aStr = pTextSepTab->FirstDel();
while ( aStr.Len() > 0 )
{
aEdTextSep.InsertEntry( aStr );
aStr = pTextSepTab->NextDel();
}
aEdFieldSep.SetText( aEdFieldSep.GetEntry(0) );
aEdTextSep.SetText( aEdTextSep.GetEntry(0) );
if ( bOnlyDbtoolsEncodings )
{ //!TODO: Unicode and MultiByte would need work in each filter
// Think of field lengths in dBase export
if ( bMultiByte )
aLbFont.FillFromDbTextEncodingMap( bImport, RTL_TEXTENCODING_INFO_UNICODE );
else
aLbFont.FillFromDbTextEncodingMap( bImport, RTL_TEXTENCODING_INFO_UNICODE |
RTL_TEXTENCODING_INFO_MULTIBYTE );
}
else if ( !bAscii )
{ //!TODO: Unicode would need work in each filter
if ( bMultiByte )
aLbFont.FillFromTextEncodingTable( bImport, RTL_TEXTENCODING_INFO_UNICODE );
else
aLbFont.FillFromTextEncodingTable( bImport, RTL_TEXTENCODING_INFO_UNICODE |
RTL_TEXTENCODING_INFO_MULTIBYTE );
}
else
{
if ( pOptions )
{
nCode = pOptions->nFieldSepCode;
aStr = pFieldSepTab->GetDelimiter( nCode );
if ( !aStr.Len() )
aEdFieldSep.SetText( String((sal_Unicode)nCode) );
else
aEdFieldSep.SetText( aStr );
nCode = pOptions->nTextSepCode;
aStr = pTextSepTab->GetDelimiter( nCode );
if ( !aStr.Len() )
aEdTextSep.SetText( String((sal_Unicode)nCode) );
else
aEdTextSep.SetText( aStr );
}
// all encodings allowed, even Unicode
aLbFont.FillFromTextEncodingTable( bImport );
}
if( bAscii )
{
Size aWinSize( GetSizePixel() );
aWinSize.Height() = aCbFixed.GetPosPixel().Y() + aCbFixed.GetSizePixel().Height();
Size aDiffSize( LogicToPixel( Size( 0, 6 ), MapMode( MAP_APPFONT ) ) );
aWinSize.Height() += aDiffSize.Height();
SetSizePixel( aWinSize );
aCbFixed.Show();
aCbFixed.SetClickHdl( LINK( this, ScImportOptionsDlg, FixedWidthHdl ) );
aCbFixed.Check( FALSE );
}
else
{
aFlFieldOpt.SetText( aFtFont.GetText() );
aFtFieldSep.Hide();
aFtTextSep.Hide();
aFtFont.Hide();
aEdFieldSep.Hide();
aEdTextSep.Hide();
aCbFixed.Hide();
aLbFont.GrabFocus();
aLbFont.SetDoubleClickHdl( LINK( this, ScImportOptionsDlg, DoubleClickHdl ) );
}
aLbFont.SelectTextEncoding( pOptions ? pOptions->eCharSet :
gsl_getSystemTextEncoding() );
// optionaler Titel:
if ( pStrTitle )
SetText( *pStrTitle );
FreeResource();
}
//------------------------------------------------------------------------
__EXPORT ScImportOptionsDlg::~ScImportOptionsDlg()
{
delete pFieldSepTab;
delete pTextSepTab;
}
//------------------------------------------------------------------------
void ScImportOptionsDlg::GetImportOptions( ScImportOptions& rOptions ) const
{
rOptions.SetTextEncoding( aLbFont.GetSelectTextEncoding() );
if ( aCbFixed.IsVisible() )
{
rOptions.nFieldSepCode = GetCodeFromCombo( aEdFieldSep );
rOptions.nTextSepCode = GetCodeFromCombo( aEdTextSep );
rOptions.bFixedWidth = aCbFixed.IsChecked();
}
}
//------------------------------------------------------------------------
USHORT ScImportOptionsDlg::GetCodeFromCombo( const ComboBox& rEd ) const
{
ScDelimiterTable* pTab;
String aStr( rEd.GetText() );
USHORT nCode;
if ( &rEd == &aEdTextSep )
pTab = pTextSepTab;
else
pTab = pFieldSepTab;
if ( !aStr.Len() )
{
nCode = 0; // kein Trennzeichen
}
else
{
nCode = pTab->GetCode( aStr );
if ( nCode == 0 )
nCode = (USHORT)aStr.GetChar(0);
}
return nCode;
}
//------------------------------------------------------------------------
IMPL_LINK( ScImportOptionsDlg, FixedWidthHdl, CheckBox*, pCheckBox )
{
if( pCheckBox == &aCbFixed )
{
BOOL bEnable = !aCbFixed.IsChecked();
aFtFieldSep.Enable( bEnable );
aEdFieldSep.Enable( bEnable );
aFtTextSep.Enable( bEnable );
aEdTextSep.Enable( bEnable );
}
return 0;
}
IMPL_LINK( ScImportOptionsDlg, DoubleClickHdl, ListBox*, pLb )
{
if ( pLb == &aLbFont )
{
aBtnOk.Click();
}
return 0;
}
<|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: AccessibleCell.hxx,v $
* $Revision: 1.16 $
*
* 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 _SC_ACCESSIBLECELL_HXX
#define _SC_ACCESSIBLECELL_HXX
#include "AccessibleCellBase.hxx"
#include "global.hxx"
#include "viewdata.hxx"
#include <com/sun/star/accessibility/XAccessibleRelationSet.hpp>
#include <unotools/accessiblerelationsethelper.hxx>
#include <svx/AccessibleStaticTextBase.hxx>
class ScTabViewShell;
class ScAccessibleDocument;
/** @descr
This base class provides an implementation of the
<code>AccessibleCell</code> service.
*/
class ScAccessibleCell
: public ScAccessibleCellBase,
public accessibility::AccessibleStaticTextBase
{
public:
//===== internal ========================================================
ScAccessibleCell(
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>& rxParent,
ScTabViewShell* pViewShell,
ScAddress& rCellAddress,
sal_Int32 nIndex,
ScSplitPos eSplitPos,
ScAccessibleDocument* pAccDoc);
virtual void Init();
using ScAccessibleCellBase::disposing;
virtual void SAL_CALL disposing();
protected:
virtual ~ScAccessibleCell();
using ScAccessibleCellBase::IsDefunc;
public:
///===== XInterface =====================================================
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(
::com::sun::star::uno::Type const & rType )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire() throw ();
virtual void SAL_CALL release() throw ();
///===== XAccessibleComponent ============================================
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
SAL_CALL getAccessibleAtPoint(
const ::com::sun::star::awt::Point& rPoint )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL grabFocus( )
throw (::com::sun::star::uno::RuntimeException);
protected:
/// Return the object's current bounding box relative to the desktop.
virtual Rectangle GetBoundingBoxOnScreen(void) const
throw (::com::sun::star::uno::RuntimeException);
/// Return the object's current bounding box relative to the parent object.
virtual Rectangle GetBoundingBox(void) const
throw (::com::sun::star::uno::RuntimeException);
public:
///===== XAccessibleContext ==============================================
/// Return the number of currently visible children.
// is overloaded to calculate this on demand
virtual sal_Int32 SAL_CALL
getAccessibleChildCount(void)
throw (::com::sun::star::uno::RuntimeException);
/// Return the specified child or NULL if index is invalid.
// is overloaded to calculate this on demand
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL
getAccessibleChild(sal_Int32 nIndex)
throw (::com::sun::star::uno::RuntimeException,
::com::sun::star::lang::IndexOutOfBoundsException);
/// Return the set of current states.
virtual ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL
getAccessibleStateSet(void)
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleRelationSet> SAL_CALL
getAccessibleRelationSet(void)
throw (::com::sun::star::uno::RuntimeException);
///===== XServiceInfo ====================================================
/** Returns an identifier for the implementation of this object.
*/
virtual ::rtl::OUString SAL_CALL
getImplementationName(void)
throw (::com::sun::star::uno::RuntimeException);
/** Returns a list of all supported services.
*/
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
getSupportedServiceNames(void)
throw (::com::sun::star::uno::RuntimeException);
///===== XTypeProvider ===================================================
/// returns the possible types
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL
getTypes()
throw (::com::sun::star::uno::RuntimeException);
/** Returns a implementation id.
*/
virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL
getImplementationId(void)
throw (::com::sun::star::uno::RuntimeException);
private:
ScTabViewShell* mpViewShell;
ScAccessibleDocument* mpAccDoc;
ScSplitPos meSplitPos;
sal_Bool IsDefunc(
const com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);
virtual sal_Bool IsEditable(
const com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);
sal_Bool IsOpaque(
const com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);
sal_Bool IsSelected();
ScDocument* GetDocument(ScTabViewShell* mpViewShell);
::std::auto_ptr< SvxEditSource > CreateEditSource(ScTabViewShell* pViewShell, ScAddress aCell, ScSplitPos eSplitPos);
void FillDependends(utl::AccessibleRelationSetHelper* pRelationSet);
void FillPrecedents(utl::AccessibleRelationSetHelper* pRelationSet);
void AddRelation(const ScAddress& rCell,
const sal_uInt16 aRelationType,
::utl::AccessibleRelationSetHelper* pRelationSet);
void AddRelation(const ScRange& rRange,
const sal_uInt16 aRelationType,
::utl::AccessibleRelationSetHelper* pRelationSet);
};
#endif
<commit_msg>INTEGRATION: CWS tbe34 (1.16.72); FILE MERGED 2008/06/23 12:44:34 tbe 1.16.72.1: #i82480# [a11y] Orca Insert-f to get text attributes doesn't work when you are in a spread sheet table cell<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: AccessibleCell.hxx,v $
* $Revision: 1.17 $
*
* 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 _SC_ACCESSIBLECELL_HXX
#define _SC_ACCESSIBLECELL_HXX
#include "AccessibleCellBase.hxx"
#include "global.hxx"
#include "viewdata.hxx"
#include <com/sun/star/accessibility/XAccessibleRelationSet.hpp>
#include <unotools/accessiblerelationsethelper.hxx>
#include <svx/AccessibleStaticTextBase.hxx>
#include <comphelper/uno3.hxx>
class ScTabViewShell;
class ScAccessibleDocument;
/** @descr
This base class provides an implementation of the
<code>AccessibleCell</code> service.
*/
class ScAccessibleCell
: public ScAccessibleCellBase,
public accessibility::AccessibleStaticTextBase
{
public:
//===== internal ========================================================
ScAccessibleCell(
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>& rxParent,
ScTabViewShell* pViewShell,
ScAddress& rCellAddress,
sal_Int32 nIndex,
ScSplitPos eSplitPos,
ScAccessibleDocument* pAccDoc);
virtual void Init();
using ScAccessibleCellBase::disposing;
virtual void SAL_CALL disposing();
protected:
virtual ~ScAccessibleCell();
using ScAccessibleCellBase::IsDefunc;
public:
///===== XInterface =====================================================
DECLARE_XINTERFACE()
///===== XTypeProvider ===================================================
DECLARE_XTYPEPROVIDER()
///===== XAccessibleComponent ============================================
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
SAL_CALL getAccessibleAtPoint(
const ::com::sun::star::awt::Point& rPoint )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL grabFocus( )
throw (::com::sun::star::uno::RuntimeException);
protected:
/// Return the object's current bounding box relative to the desktop.
virtual Rectangle GetBoundingBoxOnScreen(void) const
throw (::com::sun::star::uno::RuntimeException);
/// Return the object's current bounding box relative to the parent object.
virtual Rectangle GetBoundingBox(void) const
throw (::com::sun::star::uno::RuntimeException);
public:
///===== XAccessibleContext ==============================================
/// Return the number of currently visible children.
// is overloaded to calculate this on demand
virtual sal_Int32 SAL_CALL
getAccessibleChildCount(void)
throw (::com::sun::star::uno::RuntimeException);
/// Return the specified child or NULL if index is invalid.
// is overloaded to calculate this on demand
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL
getAccessibleChild(sal_Int32 nIndex)
throw (::com::sun::star::uno::RuntimeException,
::com::sun::star::lang::IndexOutOfBoundsException);
/// Return the set of current states.
virtual ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL
getAccessibleStateSet(void)
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleRelationSet> SAL_CALL
getAccessibleRelationSet(void)
throw (::com::sun::star::uno::RuntimeException);
///===== XServiceInfo ====================================================
/** Returns an identifier for the implementation of this object.
*/
virtual ::rtl::OUString SAL_CALL
getImplementationName(void)
throw (::com::sun::star::uno::RuntimeException);
/** Returns a list of all supported services.
*/
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
getSupportedServiceNames(void)
throw (::com::sun::star::uno::RuntimeException);
private:
ScTabViewShell* mpViewShell;
ScAccessibleDocument* mpAccDoc;
ScSplitPos meSplitPos;
sal_Bool IsDefunc(
const com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);
virtual sal_Bool IsEditable(
const com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);
sal_Bool IsOpaque(
const com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);
sal_Bool IsSelected();
ScDocument* GetDocument(ScTabViewShell* mpViewShell);
::std::auto_ptr< SvxEditSource > CreateEditSource(ScTabViewShell* pViewShell, ScAddress aCell, ScSplitPos eSplitPos);
void FillDependends(utl::AccessibleRelationSetHelper* pRelationSet);
void FillPrecedents(utl::AccessibleRelationSetHelper* pRelationSet);
void AddRelation(const ScAddress& rCell,
const sal_uInt16 aRelationType,
::utl::AccessibleRelationSetHelper* pRelationSet);
void AddRelation(const ScRange& rRange,
const sal_uInt16 aRelationType,
::utl::AccessibleRelationSetHelper* pRelationSet);
};
#endif
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
** the names of its contributors may be used to endorse or promote
** products derived from this software without specific prior written
** permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/
#include "player.h"
#include "playercontrols.h"
#include "playlistmodel.h"
#include "videowidget.h"
#include <qmediaservice.h>
#include <qmediaplaylist.h>
#include <QtGui>
Player::Player(QWidget *parent)
: QWidget(parent)
, videoWidget(0)
, coverLabel(0)
, slider(0)
, colorDialog(0)
{
//! [create-objs]
player = new QMediaPlayer(this);
// owned by PlaylistModel
playlist = new QMediaPlaylist();
player->setPlaylist(playlist);
//! [create-objs]
connect(player, SIGNAL(durationChanged(qint64)), SLOT(durationChanged(qint64)));
connect(player, SIGNAL(positionChanged(qint64)), SLOT(positionChanged(qint64)));
connect(player, SIGNAL(metaDataChanged()), SLOT(metaDataChanged()));
connect(playlist, SIGNAL(currentIndexChanged(int)), SLOT(playlistPositionChanged(int)));
connect(player, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),
this, SLOT(statusChanged(QMediaPlayer::MediaStatus)));
connect(player, SIGNAL(bufferStatusChanged(int)), this, SLOT(bufferingProgress(int)));
connect(player, SIGNAL(error(QMediaPlayer::Error)), this, SLOT(displayErrorMessage()));
//! [2]
videoWidget = new VideoWidget(this);
player->setVideoOutput(videoWidget);
playlistModel = new PlaylistModel(this);
playlistModel->setPlaylist(playlist);
//! [2]
playlistView = new QListView(this);
playlistView->setModel(playlistModel);
playlistView->setCurrentIndex(playlistModel->index(playlist->currentIndex(), 0));
connect(playlistView, SIGNAL(activated(QModelIndex)), this, SLOT(jump(QModelIndex)));
slider = new QSlider(Qt::Horizontal, this);
slider->setRange(0, player->duration() / 1000);
connect(slider, SIGNAL(sliderMoved(int)), this, SLOT(seek(int)));
QPushButton *openButton = new QPushButton(tr("Open"), this);
connect(openButton, SIGNAL(clicked()), this, SLOT(open()));
PlayerControls *controls = new PlayerControls(this);
controls->setState(player->state());
controls->setVolume(player->volume());
controls->setMuted(controls->isMuted());
connect(controls, SIGNAL(play()), player, SLOT(play()));
connect(controls, SIGNAL(pause()), player, SLOT(pause()));
connect(controls, SIGNAL(stop()), player, SLOT(stop()));
connect(controls, SIGNAL(next()), playlist, SLOT(next()));
connect(controls, SIGNAL(previous()), this, SLOT(previousClicked()));
connect(controls, SIGNAL(changeVolume(int)), player, SLOT(setVolume(int)));
connect(controls, SIGNAL(changeMuting(bool)), player, SLOT(setMuted(bool)));
connect(controls, SIGNAL(changeRate(qreal)), player, SLOT(setPlaybackRate(qreal)));
connect(controls, SIGNAL(stop()), videoWidget, SLOT(update()));
connect(player, SIGNAL(stateChanged(QMediaPlayer::State)),
controls, SLOT(setState(QMediaPlayer::State)));
connect(player, SIGNAL(volumeChanged(int)), controls, SLOT(setVolume(int)));
connect(player, SIGNAL(mutedChanged(bool)), controls, SLOT(setMuted(bool)));
QPushButton *fullScreenButton = new QPushButton(tr("FullScreen"), this);
fullScreenButton->setCheckable(true);
if (videoWidget != 0) {
connect(fullScreenButton, SIGNAL(clicked(bool)), videoWidget, SLOT(setFullScreen(bool)));
connect(videoWidget, SIGNAL(fullScreenChanged(bool)),
fullScreenButton, SLOT(setChecked(bool)));
} else {
fullScreenButton->setEnabled(false);
}
QPushButton *colorButton = new QPushButton(tr("Color Options..."), this);
if (videoWidget)
connect(colorButton, SIGNAL(clicked()), this, SLOT(showColorDialog()));
else
colorButton->setEnabled(false);
QBoxLayout *displayLayout = new QHBoxLayout;
if (videoWidget)
displayLayout->addWidget(videoWidget, 2);
else
displayLayout->addWidget(coverLabel, 2);
displayLayout->addWidget(playlistView);
QBoxLayout *controlLayout = new QHBoxLayout;
controlLayout->setMargin(0);
controlLayout->addWidget(openButton);
controlLayout->addStretch(1);
controlLayout->addWidget(controls);
controlLayout->addStretch(1);
controlLayout->addWidget(fullScreenButton);
controlLayout->addWidget(colorButton);
QBoxLayout *layout = new QVBoxLayout;
layout->addLayout(displayLayout);
layout->addWidget(slider);
layout->addLayout(controlLayout);
setLayout(layout);
if (!player->isAvailable()) {
QMessageBox::warning(this, tr("Service not available"),
tr("The QMediaPlayer object does not have a valid service.\n"\
"Please check the media service plugins are installed."));
controls->setEnabled(false);
playlistView->setEnabled(false);
openButton->setEnabled(false);
colorButton->setEnabled(false);
fullScreenButton->setEnabled(false);
}
metaDataChanged();
QStringList arguments = qApp->arguments();
arguments.removeAt(0);
addToPlaylist(arguments);
}
Player::~Player()
{
}
void Player::open()
{
#ifdef Q_WS_MAEMO_5
QStringList fileNames;
QString fileName = QFileDialog::getOpenFileName(this, tr("Open Files"), "/");
if (!fileName.isEmpty())
fileNames << fileName;
#else
QStringList fileNames = QFileDialog::getOpenFileNames(this, tr("Open Files"));
#endif
addToPlaylist(fileNames);
}
void Player::addToPlaylist(const QStringList& fileNames)
{
foreach (QString const &argument, fileNames) {
QFileInfo fileInfo(argument);
if (fileInfo.exists()) {
QUrl url = QUrl::fromLocalFile(fileInfo.absoluteFilePath());
if (fileInfo.suffix().toLower() == QLatin1String("m3u")) {
playlist->load(url);
} else
playlist->addMedia(url);
} else {
QUrl url(argument);
if (url.isValid()) {
playlist->addMedia(url);
}
}
}
}
void Player::durationChanged(qint64 duration)
{
slider->setMaximum(duration / 1000);
}
void Player::positionChanged(qint64 progress)
{
if (!slider->isSliderDown()) {
slider->setValue(progress / 1000);
}
}
void Player::metaDataChanged()
{
//qDebug() << "update metadata" << player->metaData(QtMultimediaKit::Title).toString();
if (player->isMetaDataAvailable()) {
setTrackInfo(QString("%1 - %2")
.arg(player->metaData(QtMultimediaKit::AlbumArtist).toString())
.arg(player->metaData(QtMultimediaKit::Title).toString()));
if (coverLabel) {
QUrl url = player->metaData(QtMultimediaKit::CoverArtUrlLarge).value<QUrl>();
coverLabel->setPixmap(!url.isEmpty()
? QPixmap(url.toString())
: QPixmap());
}
}
}
void Player::previousClicked()
{
// Go to previous track if we are within the first 5 seconds of playback
// Otherwise, seek to the beginning.
if(player->position() <= 5000)
playlist->previous();
else
player->setPosition(0);
}
void Player::jump(const QModelIndex &index)
{
if (index.isValid()) {
playlist->setCurrentIndex(index.row());
player->play();
}
}
void Player::playlistPositionChanged(int currentItem)
{
playlistView->setCurrentIndex(playlistModel->index(currentItem, 0));
}
void Player::seek(int seconds)
{
player->setPosition(seconds * 1000);
}
void Player::statusChanged(QMediaPlayer::MediaStatus status)
{
handleCursor(status);
// handle status message
switch (status) {
case QMediaPlayer::UnknownMediaStatus:
case QMediaPlayer::NoMedia:
case QMediaPlayer::LoadedMedia:
case QMediaPlayer::BufferingMedia:
case QMediaPlayer::BufferedMedia:
setStatusInfo(QString());
break;
case QMediaPlayer::LoadingMedia:
setStatusInfo(tr("Loading..."));
break;
case QMediaPlayer::StalledMedia:
setStatusInfo(tr("Media Stalled"));
break;
case QMediaPlayer::EndOfMedia:
QApplication::alert(this);
break;
case QMediaPlayer::InvalidMedia:
displayErrorMessage();
break;
}
}
void Player::handleCursor(QMediaPlayer::MediaStatus status)
{
#ifndef QT_NO_CURSOR
if( status == QMediaPlayer::LoadingMedia ||
status == QMediaPlayer::BufferingMedia ||
status == QMediaPlayer::StalledMedia)
setCursor(QCursor(Qt::BusyCursor));
else
unsetCursor();
#endif
}
void Player::bufferingProgress(int progress)
{
setStatusInfo(tr("Buffering %4%").arg(progress));
}
void Player::setTrackInfo(const QString &info)
{
trackInfo = info;
if (!statusInfo.isEmpty())
setWindowTitle(QString("%1 | %2").arg(trackInfo).arg(statusInfo));
else
setWindowTitle(trackInfo);
}
void Player::setStatusInfo(const QString &info)
{
statusInfo = info;
if (!statusInfo.isEmpty())
setWindowTitle(QString("%1 | %2").arg(trackInfo).arg(statusInfo));
else
setWindowTitle(trackInfo);
}
void Player::displayErrorMessage()
{
setStatusInfo(player->errorString());
}
void Player::showColorDialog()
{
if (!colorDialog) {
QSlider *brightnessSlider = new QSlider(Qt::Horizontal);
brightnessSlider->setRange(-100, 100);
brightnessSlider->setValue(videoWidget->brightness());
connect(brightnessSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setBrightness(int)));
connect(videoWidget, SIGNAL(brightnessChanged(int)), brightnessSlider, SLOT(setValue(int)));
QSlider *contrastSlider = new QSlider(Qt::Horizontal);
contrastSlider->setRange(-100, 100);
contrastSlider->setValue(videoWidget->contrast());
connect(contrastSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setContrast(int)));
connect(videoWidget, SIGNAL(contrastChanged(int)), contrastSlider, SLOT(setValue(int)));
QSlider *hueSlider = new QSlider(Qt::Horizontal);
hueSlider->setRange(-100, 100);
hueSlider->setValue(videoWidget->hue());
connect(hueSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setHue(int)));
connect(videoWidget, SIGNAL(hueChanged(int)), hueSlider, SLOT(setValue(int)));
QSlider *saturationSlider = new QSlider(Qt::Horizontal);
saturationSlider->setRange(-100, 100);
saturationSlider->setValue(videoWidget->saturation());
connect(saturationSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setSaturation(int)));
connect(videoWidget, SIGNAL(saturationChanged(int)), saturationSlider, SLOT(setValue(int)));
QFormLayout *layout = new QFormLayout;
layout->addRow(tr("Brightness"), brightnessSlider);
layout->addRow(tr("Contrast"), contrastSlider);
layout->addRow(tr("Hue"), hueSlider);
layout->addRow(tr("Saturation"), saturationSlider);
colorDialog = new QDialog(this);
colorDialog->setWindowTitle(tr("Color Options"));
colorDialog->setLayout(layout);
}
colorDialog->show();
}
<commit_msg>Player example: removed checks if videowidget is null.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
** the names of its contributors may be used to endorse or promote
** products derived from this software without specific prior written
** permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/
#include "player.h"
#include "playercontrols.h"
#include "playlistmodel.h"
#include "videowidget.h"
#include <qmediaservice.h>
#include <qmediaplaylist.h>
#include <QtGui>
Player::Player(QWidget *parent)
: QWidget(parent)
, videoWidget(0)
, coverLabel(0)
, slider(0)
, colorDialog(0)
{
//! [create-objs]
player = new QMediaPlayer(this);
// owned by PlaylistModel
playlist = new QMediaPlaylist();
player->setPlaylist(playlist);
//! [create-objs]
connect(player, SIGNAL(durationChanged(qint64)), SLOT(durationChanged(qint64)));
connect(player, SIGNAL(positionChanged(qint64)), SLOT(positionChanged(qint64)));
connect(player, SIGNAL(metaDataChanged()), SLOT(metaDataChanged()));
connect(playlist, SIGNAL(currentIndexChanged(int)), SLOT(playlistPositionChanged(int)));
connect(player, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),
this, SLOT(statusChanged(QMediaPlayer::MediaStatus)));
connect(player, SIGNAL(bufferStatusChanged(int)), this, SLOT(bufferingProgress(int)));
connect(player, SIGNAL(error(QMediaPlayer::Error)), this, SLOT(displayErrorMessage()));
//! [2]
videoWidget = new VideoWidget(this);
player->setVideoOutput(videoWidget);
playlistModel = new PlaylistModel(this);
playlistModel->setPlaylist(playlist);
//! [2]
playlistView = new QListView(this);
playlistView->setModel(playlistModel);
playlistView->setCurrentIndex(playlistModel->index(playlist->currentIndex(), 0));
connect(playlistView, SIGNAL(activated(QModelIndex)), this, SLOT(jump(QModelIndex)));
slider = new QSlider(Qt::Horizontal, this);
slider->setRange(0, player->duration() / 1000);
connect(slider, SIGNAL(sliderMoved(int)), this, SLOT(seek(int)));
QPushButton *openButton = new QPushButton(tr("Open"), this);
connect(openButton, SIGNAL(clicked()), this, SLOT(open()));
PlayerControls *controls = new PlayerControls(this);
controls->setState(player->state());
controls->setVolume(player->volume());
controls->setMuted(controls->isMuted());
connect(controls, SIGNAL(play()), player, SLOT(play()));
connect(controls, SIGNAL(pause()), player, SLOT(pause()));
connect(controls, SIGNAL(stop()), player, SLOT(stop()));
connect(controls, SIGNAL(next()), playlist, SLOT(next()));
connect(controls, SIGNAL(previous()), this, SLOT(previousClicked()));
connect(controls, SIGNAL(changeVolume(int)), player, SLOT(setVolume(int)));
connect(controls, SIGNAL(changeMuting(bool)), player, SLOT(setMuted(bool)));
connect(controls, SIGNAL(changeRate(qreal)), player, SLOT(setPlaybackRate(qreal)));
connect(controls, SIGNAL(stop()), videoWidget, SLOT(update()));
connect(player, SIGNAL(stateChanged(QMediaPlayer::State)),
controls, SLOT(setState(QMediaPlayer::State)));
connect(player, SIGNAL(volumeChanged(int)), controls, SLOT(setVolume(int)));
connect(player, SIGNAL(mutedChanged(bool)), controls, SLOT(setMuted(bool)));
QPushButton *fullScreenButton = new QPushButton(tr("FullScreen"), this);
fullScreenButton->setCheckable(true);
connect(fullScreenButton, SIGNAL(clicked(bool)), videoWidget, SLOT(setFullScreen(bool)));
connect(videoWidget, SIGNAL(fullScreenChanged(bool)),
fullScreenButton, SLOT(setChecked(bool)));
QPushButton *colorButton = new QPushButton(tr("Color Options..."), this);
connect(colorButton, SIGNAL(clicked()), this, SLOT(showColorDialog()));
QBoxLayout *displayLayout = new QHBoxLayout;
if (videoWidget)
displayLayout->addWidget(videoWidget, 2);
else
displayLayout->addWidget(coverLabel, 2);
displayLayout->addWidget(playlistView);
QBoxLayout *controlLayout = new QHBoxLayout;
controlLayout->setMargin(0);
controlLayout->addWidget(openButton);
controlLayout->addStretch(1);
controlLayout->addWidget(controls);
controlLayout->addStretch(1);
controlLayout->addWidget(fullScreenButton);
controlLayout->addWidget(colorButton);
QBoxLayout *layout = new QVBoxLayout;
layout->addLayout(displayLayout);
layout->addWidget(slider);
layout->addLayout(controlLayout);
setLayout(layout);
if (!player->isAvailable()) {
QMessageBox::warning(this, tr("Service not available"),
tr("The QMediaPlayer object does not have a valid service.\n"\
"Please check the media service plugins are installed."));
controls->setEnabled(false);
playlistView->setEnabled(false);
openButton->setEnabled(false);
colorButton->setEnabled(false);
fullScreenButton->setEnabled(false);
}
metaDataChanged();
QStringList arguments = qApp->arguments();
arguments.removeAt(0);
addToPlaylist(arguments);
}
Player::~Player()
{
}
void Player::open()
{
#ifdef Q_WS_MAEMO_5
QStringList fileNames;
QString fileName = QFileDialog::getOpenFileName(this, tr("Open Files"), "/");
if (!fileName.isEmpty())
fileNames << fileName;
#else
QStringList fileNames = QFileDialog::getOpenFileNames(this, tr("Open Files"));
#endif
addToPlaylist(fileNames);
}
void Player::addToPlaylist(const QStringList& fileNames)
{
foreach (QString const &argument, fileNames) {
QFileInfo fileInfo(argument);
if (fileInfo.exists()) {
QUrl url = QUrl::fromLocalFile(fileInfo.absoluteFilePath());
if (fileInfo.suffix().toLower() == QLatin1String("m3u")) {
playlist->load(url);
} else
playlist->addMedia(url);
} else {
QUrl url(argument);
if (url.isValid()) {
playlist->addMedia(url);
}
}
}
}
void Player::durationChanged(qint64 duration)
{
slider->setMaximum(duration / 1000);
}
void Player::positionChanged(qint64 progress)
{
if (!slider->isSliderDown()) {
slider->setValue(progress / 1000);
}
}
void Player::metaDataChanged()
{
//qDebug() << "update metadata" << player->metaData(QtMultimediaKit::Title).toString();
if (player->isMetaDataAvailable()) {
setTrackInfo(QString("%1 - %2")
.arg(player->metaData(QtMultimediaKit::AlbumArtist).toString())
.arg(player->metaData(QtMultimediaKit::Title).toString()));
if (coverLabel) {
QUrl url = player->metaData(QtMultimediaKit::CoverArtUrlLarge).value<QUrl>();
coverLabel->setPixmap(!url.isEmpty()
? QPixmap(url.toString())
: QPixmap());
}
}
}
void Player::previousClicked()
{
// Go to previous track if we are within the first 5 seconds of playback
// Otherwise, seek to the beginning.
if(player->position() <= 5000)
playlist->previous();
else
player->setPosition(0);
}
void Player::jump(const QModelIndex &index)
{
if (index.isValid()) {
playlist->setCurrentIndex(index.row());
player->play();
}
}
void Player::playlistPositionChanged(int currentItem)
{
playlistView->setCurrentIndex(playlistModel->index(currentItem, 0));
}
void Player::seek(int seconds)
{
player->setPosition(seconds * 1000);
}
void Player::statusChanged(QMediaPlayer::MediaStatus status)
{
handleCursor(status);
// handle status message
switch (status) {
case QMediaPlayer::UnknownMediaStatus:
case QMediaPlayer::NoMedia:
case QMediaPlayer::LoadedMedia:
case QMediaPlayer::BufferingMedia:
case QMediaPlayer::BufferedMedia:
setStatusInfo(QString());
break;
case QMediaPlayer::LoadingMedia:
setStatusInfo(tr("Loading..."));
break;
case QMediaPlayer::StalledMedia:
setStatusInfo(tr("Media Stalled"));
break;
case QMediaPlayer::EndOfMedia:
QApplication::alert(this);
break;
case QMediaPlayer::InvalidMedia:
displayErrorMessage();
break;
}
}
void Player::handleCursor(QMediaPlayer::MediaStatus status)
{
#ifndef QT_NO_CURSOR
if( status == QMediaPlayer::LoadingMedia ||
status == QMediaPlayer::BufferingMedia ||
status == QMediaPlayer::StalledMedia)
setCursor(QCursor(Qt::BusyCursor));
else
unsetCursor();
#endif
}
void Player::bufferingProgress(int progress)
{
setStatusInfo(tr("Buffering %4%").arg(progress));
}
void Player::setTrackInfo(const QString &info)
{
trackInfo = info;
if (!statusInfo.isEmpty())
setWindowTitle(QString("%1 | %2").arg(trackInfo).arg(statusInfo));
else
setWindowTitle(trackInfo);
}
void Player::setStatusInfo(const QString &info)
{
statusInfo = info;
if (!statusInfo.isEmpty())
setWindowTitle(QString("%1 | %2").arg(trackInfo).arg(statusInfo));
else
setWindowTitle(trackInfo);
}
void Player::displayErrorMessage()
{
setStatusInfo(player->errorString());
}
void Player::showColorDialog()
{
if (!colorDialog) {
QSlider *brightnessSlider = new QSlider(Qt::Horizontal);
brightnessSlider->setRange(-100, 100);
brightnessSlider->setValue(videoWidget->brightness());
connect(brightnessSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setBrightness(int)));
connect(videoWidget, SIGNAL(brightnessChanged(int)), brightnessSlider, SLOT(setValue(int)));
QSlider *contrastSlider = new QSlider(Qt::Horizontal);
contrastSlider->setRange(-100, 100);
contrastSlider->setValue(videoWidget->contrast());
connect(contrastSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setContrast(int)));
connect(videoWidget, SIGNAL(contrastChanged(int)), contrastSlider, SLOT(setValue(int)));
QSlider *hueSlider = new QSlider(Qt::Horizontal);
hueSlider->setRange(-100, 100);
hueSlider->setValue(videoWidget->hue());
connect(hueSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setHue(int)));
connect(videoWidget, SIGNAL(hueChanged(int)), hueSlider, SLOT(setValue(int)));
QSlider *saturationSlider = new QSlider(Qt::Horizontal);
saturationSlider->setRange(-100, 100);
saturationSlider->setValue(videoWidget->saturation());
connect(saturationSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setSaturation(int)));
connect(videoWidget, SIGNAL(saturationChanged(int)), saturationSlider, SLOT(setValue(int)));
QFormLayout *layout = new QFormLayout;
layout->addRow(tr("Brightness"), brightnessSlider);
layout->addRow(tr("Contrast"), contrastSlider);
layout->addRow(tr("Hue"), hueSlider);
layout->addRow(tr("Saturation"), saturationSlider);
colorDialog = new QDialog(this);
colorDialog->setWindowTitle(tr("Color Options"));
colorDialog->setLayout(layout);
}
colorDialog->show();
}
<|endoftext|> |
<commit_before>/** @file
* @author Edouard DUPIN
*
* @copyright 2016, Edouard DUPIN, all right reserved
*
* @license MPL v2.0 (see license file)
*/
#include <etk/etk.hpp>
#include <test-debug/debug.hpp>
//! [eproperty_sample_all]
//! [eproperty_sample_declare_interface]
#include <eproperty/Interface.hpp>
//! [eproperty_sample_declare_interface]
//! [eproperty_sample_declare_value]
#include <eproperty/Value.hpp>
//! [eproperty_sample_declare_value]
//! [eproperty_sample_declare_list]
#include <eproperty/List.hpp>
//! [eproperty_sample_declare_list]
//! [eproperty_sample_declare_range]
#include <eproperty/Range.hpp>
//! [eproperty_sample_declare_range]
//! [eproperty_sample_declare_an_enum]
enum simpleEnum {
simpleEnum_enum1,
simpleEnum_enum2,
simpleEnum_enum3,
simpleEnum_enum4,
};
//! [eproperty_sample_declare_an_enum]
//! [eproperty_sample_class_with_interface]
//! [eproperty_sample_declare_class_with_interface]
class sampleClassGroup : public eproperty::Interface {
//! [eproperty_sample_declare_class_with_interface]
public:
//! [eproperty_sample_declare_class_property_value]
eproperty::Value<etk::String> propertyValue; //!< Simple property Value with type string
//! [eproperty_sample_declare_class_property_value]
//! [eproperty_sample_declare_class_property_list]
eproperty::List<enum simpleEnum> propertyList; //!< Simple property List with type enumeration
//! [eproperty_sample_declare_class_property_list]
//! [eproperty_sample_declare_class_property_range]
eproperty::Range<int32_t> propertyRange; //!< Simple property Range with type integer
//! [eproperty_sample_declare_class_property_range]
sampleClassGroup():
//! [eproperty_sample_initialize_class_property_value]
propertyValue(this, "value", "default value", "optionnal Description", &sampleClassGroup::onPropertyChangeValue),
//! [eproperty_sample_initialize_class_property_value]
//! [eproperty_sample_initialize_class_property_list]
propertyList(this, "list", simpleEnum_enum4),
//! [eproperty_sample_initialize_class_property_list]
//! [eproperty_sample_initialize_class_property_range]
propertyRange(this, "range", 5646546, -5, 555555555) {
//! [eproperty_sample_initialize_class_property_range]
// add all enumeration values
//! [eproperty_sample_initialize_class_property_list_add]
propertyList.add(simpleEnum_enum1, "enum1");
propertyList.add(simpleEnum_enum2, "enum2");
propertyList.add(simpleEnum_enum3, "enum3");
propertyList.add(simpleEnum_enum4, "enum4");
//! [eproperty_sample_initialize_class_property_list_add]
//! [eproperty_sample_initialize_class_property_list_rename]
// Rename an element
propertyList.rename("enum1", "new enum name");
// Remove an element
propertyList.remove("enum2");
//! [eproperty_sample_initialize_class_property_list_rename]
//! [eproperty_sample_initialize_class_property_set_direct]
// no check on the value set (the faster in CPU cycle)
propertyValue.setDirect("New Value to Set");
// Check the internal value (better for range)
propertyRange.setDirectCheck(-5555);
//! [eproperty_sample_initialize_class_property_set_direct]
}
//! [eproperty_sample_initialize_class_property_value_callback]
void onPropertyChangeValue() {
TEST_PRINT("Property value has change ... " << *propertyValue);
TEST_INFO("Use properties:");
//! [eproperty_sample_get_value_value]
TEST_INFO(" value:" << *propertyValue);
//! [eproperty_sample_get_value_value]
//! [eproperty_sample_get_value_range]
TEST_INFO(" range:" << *propertyRange);
//! [eproperty_sample_get_value_range]
//! [eproperty_sample_get_value_list]
TEST_INFO(" list:" << *propertyList);
//! [eproperty_sample_get_value_list]
}
//! [eproperty_sample_initialize_class_property_value_callback]
};
//! [eproperty_sample_class_with_interface]
//! [eproperty_sample_class_without_interface]
class sampleClassSolo {
public:
eproperty::Value<etk::String> propertyValue;
eproperty::List<enum simpleEnum> propertyList;
eproperty::Range<int32_t> propertyRange;
sampleClassSolo():
//! [eproperty_sample_initialize_class_property_value2]
propertyValue("default value"),
//! [eproperty_sample_initialize_class_property_value2]
//! [eproperty_sample_initialize_class_property_list2]
propertyList(simpleEnum_enum4),
//! [eproperty_sample_initialize_class_property_list2]
//! [eproperty_sample_initialize_class_property_range2]
propertyRange(5646546, -5, 555555555) {
//! [eproperty_sample_initialize_class_property_range2]
propertyList.add(simpleEnum_enum1, "enum1");
propertyList.add(simpleEnum_enum2, "enum2");
propertyList.add(simpleEnum_enum3, "enum3");
propertyList.add(simpleEnum_enum4, "enum4");
}
};
//! [eproperty_sample_class_without_interface]
void simpleSet() {
//! [eproperty_sample_use_declare_class]
sampleClassGroup myClass;
//! [eproperty_sample_use_declare_class]
//! [eproperty_sample_use_set_value_1]
myClass.propertyValue.set("New Value");
myClass.propertyValue.setString("New Value 2");
//! [eproperty_sample_use_set_value_1]
//! [eproperty_sample_use_set_list_1]
myClass.propertyList.set(simpleEnum_enum3);
myClass.propertyList.setString("enum3");
//! [eproperty_sample_use_set_list_1]
//! [eproperty_sample_use_set_range_1]
myClass.propertyRange.set(15621);
myClass.propertyRange.setString("15621");
//! [eproperty_sample_use_set_range_1]
//! [eproperty_sample_use_set_value_2]
myClass.properties.set("value", "New Value in string");
//! [eproperty_sample_use_set_value_2]
//! [eproperty_sample_use_set_list_2]
myClass.properties.set("list", "enum4");
//! [eproperty_sample_use_set_list_2]
//! [eproperty_sample_use_set_range_2]
myClass.properties.set("range", "-2");
//! [eproperty_sample_use_set_range_2]
}
//! [eproperty_sample_all]
int main(int _argc, const char *_argv[]) {
etk::init(_argc, _argv);
TEST_INFO("simpleSet [START] ***************************");
simpleSet();
TEST_INFO("simpleSet [STOP] ***************************");
return 0;
}
<commit_msg>[DEBUG] build back sample<commit_after>/** @file
* @author Edouard DUPIN
*
* @copyright 2016, Edouard DUPIN, all right reserved
*
* @license MPL v2.0 (see license file)
*/
#include <etk/etk.hpp>
#include <test-debug/debug.hpp>
//! [eproperty_sample_all]
//! [eproperty_sample_declare_interface]
#include <eproperty/Interface.hpp>
//! [eproperty_sample_declare_interface]
//! [eproperty_sample_declare_value]
#include <eproperty/Value.hpp>
//! [eproperty_sample_declare_value]
//! [eproperty_sample_declare_list]
#include <eproperty/List.hpp>
//! [eproperty_sample_declare_list]
//! [eproperty_sample_declare_range]
#include <eproperty/Range.hpp>
//! [eproperty_sample_declare_range]
//! [eproperty_sample_declare_an_enum]
enum simpleEnum {
simpleEnum_enum1,
simpleEnum_enum2,
simpleEnum_enum3,
simpleEnum_enum4,
};
// Declare type in CPP only
#include <etk/typeInfo.hpp>
ETK_DECLARE_TYPE(enum simpleEnum);
//! [eproperty_sample_declare_an_enum]
//! [eproperty_sample_class_with_interface]
//! [eproperty_sample_declare_class_with_interface]
class sampleClassGroup : public eproperty::Interface {
//! [eproperty_sample_declare_class_with_interface]
public:
//! [eproperty_sample_declare_class_property_value]
eproperty::Value<etk::String> propertyValue; //!< Simple property Value with type string
//! [eproperty_sample_declare_class_property_value]
//! [eproperty_sample_declare_class_property_list]
eproperty::List<enum simpleEnum> propertyList; //!< Simple property List with type enumeration
//! [eproperty_sample_declare_class_property_list]
//! [eproperty_sample_declare_class_property_range]
eproperty::Range<int32_t> propertyRange; //!< Simple property Range with type integer
//! [eproperty_sample_declare_class_property_range]
sampleClassGroup():
//! [eproperty_sample_initialize_class_property_value]
propertyValue(this, "value", "default value", "optionnal Description", &sampleClassGroup::onPropertyChangeValue),
//! [eproperty_sample_initialize_class_property_value]
//! [eproperty_sample_initialize_class_property_list]
propertyList(this, "list", simpleEnum_enum4),
//! [eproperty_sample_initialize_class_property_list]
//! [eproperty_sample_initialize_class_property_range]
propertyRange(this, "range", 5646546, -5, 555555555) {
//! [eproperty_sample_initialize_class_property_range]
// add all enumeration values
//! [eproperty_sample_initialize_class_property_list_add]
propertyList.add(simpleEnum_enum1, "enum1");
propertyList.add(simpleEnum_enum2, "enum2");
propertyList.add(simpleEnum_enum3, "enum3");
propertyList.add(simpleEnum_enum4, "enum4");
//! [eproperty_sample_initialize_class_property_list_add]
//! [eproperty_sample_initialize_class_property_list_rename]
// Rename an element
propertyList.rename("enum1", "new enum name");
// Remove an element
propertyList.remove("enum2");
//! [eproperty_sample_initialize_class_property_list_rename]
//! [eproperty_sample_initialize_class_property_set_direct]
// no check on the value set (the faster in CPU cycle)
propertyValue.setDirect("New Value to Set");
// Check the internal value (better for range)
propertyRange.setDirectCheck(-5555);
//! [eproperty_sample_initialize_class_property_set_direct]
}
//! [eproperty_sample_initialize_class_property_value_callback]
void onPropertyChangeValue() {
TEST_PRINT("Property value has change ... " << *propertyValue);
TEST_INFO("Use properties:");
//! [eproperty_sample_get_value_value]
TEST_INFO(" value:" << *propertyValue);
//! [eproperty_sample_get_value_value]
//! [eproperty_sample_get_value_range]
TEST_INFO(" range:" << *propertyRange);
//! [eproperty_sample_get_value_range]
//! [eproperty_sample_get_value_list]
TEST_INFO(" list:" << *propertyList);
//! [eproperty_sample_get_value_list]
}
//! [eproperty_sample_initialize_class_property_value_callback]
};
//! [eproperty_sample_class_with_interface]
//! [eproperty_sample_class_without_interface]
class sampleClassSolo {
public:
eproperty::Value<etk::String> propertyValue;
eproperty::List<enum simpleEnum> propertyList;
eproperty::Range<int32_t> propertyRange;
sampleClassSolo():
//! [eproperty_sample_initialize_class_property_value2]
propertyValue("default value"),
//! [eproperty_sample_initialize_class_property_value2]
//! [eproperty_sample_initialize_class_property_list2]
propertyList(simpleEnum_enum4),
//! [eproperty_sample_initialize_class_property_list2]
//! [eproperty_sample_initialize_class_property_range2]
propertyRange(5646546, -5, 555555555) {
//! [eproperty_sample_initialize_class_property_range2]
propertyList.add(simpleEnum_enum1, "enum1");
propertyList.add(simpleEnum_enum2, "enum2");
propertyList.add(simpleEnum_enum3, "enum3");
propertyList.add(simpleEnum_enum4, "enum4");
}
};
//! [eproperty_sample_class_without_interface]
void simpleSet() {
//! [eproperty_sample_use_declare_class]
sampleClassGroup myClass;
//! [eproperty_sample_use_declare_class]
//! [eproperty_sample_use_set_value_1]
myClass.propertyValue.set("New Value");
myClass.propertyValue.setString("New Value 2");
//! [eproperty_sample_use_set_value_1]
//! [eproperty_sample_use_set_list_1]
myClass.propertyList.set(simpleEnum_enum3);
myClass.propertyList.setString("enum3");
//! [eproperty_sample_use_set_list_1]
//! [eproperty_sample_use_set_range_1]
myClass.propertyRange.set(15621);
myClass.propertyRange.setString("15621");
//! [eproperty_sample_use_set_range_1]
//! [eproperty_sample_use_set_value_2]
myClass.properties.set("value", "New Value in string");
//! [eproperty_sample_use_set_value_2]
//! [eproperty_sample_use_set_list_2]
myClass.properties.set("list", "enum4");
//! [eproperty_sample_use_set_list_2]
//! [eproperty_sample_use_set_range_2]
myClass.properties.set("range", "-2");
//! [eproperty_sample_use_set_range_2]
}
//! [eproperty_sample_all]
int main(int _argc, const char *_argv[]) {
etk::init(_argc, _argv);
TEST_INFO("simpleSet [START] ***************************");
simpleSet();
TEST_INFO("simpleSet [STOP] ***************************");
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright 2005-2007 Adobe Systems Incorporated
Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
or a copy at http://stlab.adobe.com/licenses.html)
*/
#include "platform_display_text.hpp"
#include <GG/adobe/dictionary.hpp>
#include <GG/adobe/string.hpp>
#include <GG/adobe/future/widgets/headers/display.hpp>
#include <GG/adobe/future/widgets/headers/widget_utils.hpp>
#include <GG/adobe/future/widgets/headers/platform_metrics.hpp>
#include <GG/TextControl.h>
#include <GG/GUI.h>
#include <GG/StyleFactory.h>
#include <string>
#include <cassert>
#include <sstream>
namespace {
std::string field_text(const std::string& label, const adobe::any_regular_t& value, GG::Clr label_color)
{
std::stringstream result;
if (!label.empty())
result << GG::RgbaTag(label_color) << label << "</rgba> ";
if (value != adobe::any_regular_t()) {
adobe::type_info_t type(value.type_info());
if (type == adobe::type_info<double>() ||
type == adobe::type_info<bool>() ||
type == adobe::type_info<adobe::name_t>()) {
result << value;
} else if (type == adobe::type_info<adobe::array_t>()) {
result << '[';
const adobe::array_t& array = value.cast<adobe::array_t>();
for (adobe::array_t::const_iterator it = array.begin(), end_it = array.end();
it != end_it;
++it) {
result << field_text("", *it, label_color);
if (boost::next(it) != end_it)
result << ',';
}
result << " ]";
} else if (type == adobe::type_info<adobe::dictionary_t>()) {
const adobe::dictionary_t& dictionary = value.cast<adobe::dictionary_t>();
for (adobe::dictionary_t::const_iterator it = dictionary.begin(), end_it = dictionary.end();
it != end_it;
++it) {
result << it->first << ": " << field_text("", it->second, label_color);
if (boost::next(it) != end_it)
result << ',';
}
result << " ]";
} else {
result << value.cast<adobe::string_t>();
}
}
return result.str();
}
}
namespace adobe {
display_text_t::display_text_t(const std::string& name,
const std::string& alt_text,
int characters,
GG::Clr color,
GG::Clr label_color) :
name_m(name),
alt_text_m(alt_text),
characters_m(characters),
color_m(color),
label_color_m(label_color)
{}
void display_text_t::place(const place_data_t& place_data)
{ implementation::set_control_bounds(window_m, place_data); }
void display_text_t::display(const model_type& value)
{
assert(window_m);
value_m = value;
window_m->SetText(field_text(name_m, value_m, label_color_m));
}
void display_text_t::measure(extents_t& result)
{
assert(window_m);
boost::shared_ptr<GG::Font> font = implementation::DefaultFont();
extents_t space_extents(metrics::measure_text(std::string(" "), font));
extents_t label_extents(metrics::measure_text(name_m, font));
extents_t characters_extents(metrics::measure_text(std::string(characters_m, '0'), font));
// set up default settings (baseline, etc.)
result = space_extents;
// set the width to the label width (if any)
result.width() = label_extents.width();
// add a guide for the label
result.horizontal().guide_set_m.push_back(label_extents.width());
// if there's a label, add space for a space
if (label_extents.width() != 0)
result.width() += space_extents.width();
// append the character extents (if any)
result.width() += characters_extents.width();
// if there are character extents, add space for a space
if (characters_extents.width() != 0)
result.width() += space_extents.width();
assert(result.horizontal().length_m);
}
void display_text_t::measure_vertical(extents_t& calculated_horizontal, const place_data_t& placed_horizontal)
{
assert(window_m);
extents_t::slice_t& vert = calculated_horizontal.vertical();
vert.length_m = Value(implementation::DefaultFont()->Lineskip());
vert.guide_set_m.push_back(Value(implementation::DefaultFont()->Ascent()));
}
void display_text_t::set_label_color(GG::Clr color)
{
label_color_m = color;
display(value_m);
}
template <>
platform_display_type insert<display_text_t>(display_t& display,
platform_display_type& parent,
display_text_t& element)
{
element.window_m =
implementation::Factory().NewTextControl(GG::X0, GG::Y0, GG::X1, GG::Y1,
element.name_m, implementation::DefaultFont(),
element.color_m, GG::FORMAT_LEFT | GG::FORMAT_TOP,
GG::INTERACTIVE);
if (!element.alt_text_m.empty())
implementation::set_control_alt_text(element.window_m, element.alt_text_m);
element.color_proxy_m.initialize(
boost::bind(&GG::TextControl::SetColor, element.window_m, _1)
);
element.label_color_proxy_m.initialize(
boost::bind(&display_text_t::set_label_color, &element, _1)
);
return display.insert(parent, get_display(element));
}
}
<commit_msg>Fixed broken display of dictionaries in platform_display_text.<commit_after>/*
Copyright 2005-2007 Adobe Systems Incorporated
Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
or a copy at http://stlab.adobe.com/licenses.html)
*/
#include "platform_display_text.hpp"
#include <GG/adobe/dictionary.hpp>
#include <GG/adobe/string.hpp>
#include <GG/adobe/future/widgets/headers/display.hpp>
#include <GG/adobe/future/widgets/headers/widget_utils.hpp>
#include <GG/adobe/future/widgets/headers/platform_metrics.hpp>
#include <GG/TextControl.h>
#include <GG/GUI.h>
#include <GG/StyleFactory.h>
#include <string>
#include <cassert>
#include <sstream>
namespace {
std::string field_text(const std::string& label, const adobe::any_regular_t& value, GG::Clr label_color)
{
std::stringstream result;
if (!label.empty())
result << GG::RgbaTag(label_color) << label << "</rgba> ";
if (value != adobe::any_regular_t()) {
adobe::type_info_t type(value.type_info());
if (type == adobe::type_info<double>() ||
type == adobe::type_info<bool>() ||
type == adobe::type_info<adobe::name_t>()) {
result << value;
} else if (type == adobe::type_info<adobe::array_t>()) {
result << '[';
const adobe::array_t& array = value.cast<adobe::array_t>();
for (adobe::array_t::const_iterator it = array.begin(), end_it = array.end();
it != end_it;
++it) {
result << field_text("", *it, label_color);
if (boost::next(it) != end_it)
result << ',';
}
result << " ]";
} else if (type == adobe::type_info<adobe::dictionary_t>()) {
result << '{';
const adobe::dictionary_t& dictionary = value.cast<adobe::dictionary_t>();
for (adobe::dictionary_t::const_iterator it = dictionary.begin(), end_it = dictionary.end();
it != end_it;
++it) {
result << it->first << ": " << field_text("", it->second, label_color);
if (boost::next(it) != end_it)
result << ',';
}
result << " }";
} else {
result << value.cast<adobe::string_t>();
}
}
return result.str();
}
}
namespace adobe {
display_text_t::display_text_t(const std::string& name,
const std::string& alt_text,
int characters,
GG::Clr color,
GG::Clr label_color) :
name_m(name),
alt_text_m(alt_text),
characters_m(characters),
color_m(color),
label_color_m(label_color)
{}
void display_text_t::place(const place_data_t& place_data)
{ implementation::set_control_bounds(window_m, place_data); }
void display_text_t::display(const model_type& value)
{
assert(window_m);
value_m = value;
window_m->SetText(field_text(name_m, value_m, label_color_m));
}
void display_text_t::measure(extents_t& result)
{
assert(window_m);
boost::shared_ptr<GG::Font> font = implementation::DefaultFont();
extents_t space_extents(metrics::measure_text(std::string(" "), font));
extents_t label_extents(metrics::measure_text(name_m, font));
extents_t characters_extents(metrics::measure_text(std::string(characters_m, '0'), font));
// set up default settings (baseline, etc.)
result = space_extents;
// set the width to the label width (if any)
result.width() = label_extents.width();
// add a guide for the label
result.horizontal().guide_set_m.push_back(label_extents.width());
// if there's a label, add space for a space
if (label_extents.width() != 0)
result.width() += space_extents.width();
// append the character extents (if any)
result.width() += characters_extents.width();
// if there are character extents, add space for a space
if (characters_extents.width() != 0)
result.width() += space_extents.width();
assert(result.horizontal().length_m);
}
void display_text_t::measure_vertical(extents_t& calculated_horizontal, const place_data_t& placed_horizontal)
{
assert(window_m);
extents_t::slice_t& vert = calculated_horizontal.vertical();
vert.length_m = Value(implementation::DefaultFont()->Lineskip());
vert.guide_set_m.push_back(Value(implementation::DefaultFont()->Ascent()));
}
void display_text_t::set_label_color(GG::Clr color)
{
label_color_m = color;
display(value_m);
}
template <>
platform_display_type insert<display_text_t>(display_t& display,
platform_display_type& parent,
display_text_t& element)
{
element.window_m =
implementation::Factory().NewTextControl(GG::X0, GG::Y0, GG::X1, GG::Y1,
element.name_m, implementation::DefaultFont(),
element.color_m, GG::FORMAT_LEFT | GG::FORMAT_TOP,
GG::INTERACTIVE);
if (!element.alt_text_m.empty())
implementation::set_control_alt_text(element.window_m, element.alt_text_m);
element.color_proxy_m.initialize(
boost::bind(&GG::TextControl::SetColor, element.window_m, _1)
);
element.label_color_proxy_m.initialize(
boost::bind(&display_text_t::set_label_color, &element, _1)
);
return display.insert(parent, get_display(element));
}
}
<|endoftext|> |
<commit_before>/*
* Qumulus UML editor
* Author: Frank Erens
*
*/
#include "Enumeration.h"
QUML_BEGIN_NAMESPACE_UK
Enumeration::Enumeration() {}
Enumeration::Enumeration(QString name, Namespace* p = 0) :
DataType(name, p) {
}
void Enumeration::addLiteral(EnumerationLiteral* l) {
mOwnedLiterals.append(l);
addOwnedMember(l);
}
void Enumeration::removeLiteral(EnumerationLiteral* l) {
mOwnedLiterals.remove(l);
removeOwnedMember(l);
}
QUML_END_NAMESPACE_UK
<commit_msg>Fix compile bug in Enumeration.<commit_after>/*
* Qumulus UML editor
* Author: Frank Erens
*
*/
#include "Enumeration.h"
QUML_BEGIN_NAMESPACE_UK
Enumeration::Enumeration() {}
Enumeration::Enumeration(QString name, Namespace* p) :
DataType(name, p) {
}
void Enumeration::addLiteral(EnumerationLiteral* l) {
mOwnedLiterals.append(l);
addOwnedMember(l);
}
void Enumeration::removeLiteral(EnumerationLiteral* l) {
mOwnedLiterals.removeAll(l);
removeOwnedMember(l);
}
QUML_END_NAMESPACE_UK
<|endoftext|> |
<commit_before>#include <QNetworkRequest>
#include <QNetworkReply>
#include <QDir>
#include <QFile>
#include "program-updater.h"
#include "functions.h"
#include "json.h"
ProgramUpdater::ProgramUpdater()
: ProgramUpdater("https://api.github.com/repos/Bionus/imgbrd-grabber")
{ }
ProgramUpdater::ProgramUpdater(QString baseUrl)
: m_baseUrl(baseUrl)
{ }
void ProgramUpdater::checkForUpdates()
{
QUrl url(m_baseUrl + "/releases");
QNetworkRequest request(url);
m_checkForUpdatesReply = m_networkAccessManager.get(request);
connect(m_checkForUpdatesReply, &QNetworkReply::finished, this, &ProgramUpdater::checkForUpdatesDone);
}
void ProgramUpdater::checkForUpdatesDone()
{
m_source = m_checkForUpdatesReply->readAll();
QVariant json = Json::parse(m_source);
QMap<QString, QVariant> lastRelease = json.toList().first().toMap();
QString latest = lastRelease["name"].toString().mid(1);
QString changelog = lastRelease["body"].toString();
m_newVersion = latest;
bool isNew = compareVersions(latest, QString(VERSION)) > 0;
emit finished(latest, isNew, changelog);
}
void ProgramUpdater::downloadUpdate()
{
QVariant json = Json::parse(m_source);
QMap<QString, QVariant> lastRelease = json.toList().first().toMap();
QMap<QString, QVariant> lastAsset = lastRelease["assets"].toList().first().toMap();
QUrl url(lastAsset["browser_download_url"].toString());
m_updateFilename = url.fileName();
QNetworkRequest request(url);
log(QString("Downloading installer from \"%1\".").arg(url.toString()));
m_downloadReply = m_networkAccessManager.get(request);
connect(m_downloadReply, &QNetworkReply::downloadProgress, this, &ProgramUpdater::downloadProgress);
connect(m_downloadReply, &QNetworkReply::finished, this, &ProgramUpdater::downloadDone);
}
void ProgramUpdater::downloadDone()
{
QUrl redir = m_downloadReply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
if (!redir.isEmpty())
{
log(QString("Installer download redirected to \"%1\".").arg(redir.toString()));
QNetworkRequest request(redir);
m_downloadReply = m_networkAccessManager.get(request);
connect(m_downloadReply, &QNetworkReply::downloadProgress, this, &ProgramUpdater::downloadProgress);
connect(m_downloadReply, &QNetworkReply::finished, this, &ProgramUpdater::downloadDone);
return;
}
QFile file(QDir::tempPath() + QDir::separator() + m_updateFilename);
if (!file.open(QFile::WriteOnly | QFile::Truncate))
{
log(QString("Error opening installer file \"%1\".").arg(file.fileName()));
return;
}
file.write(m_downloadReply->readAll());
file.close();
log(QString("Installer file written to \"%1\"").arg(file.fileName()));
emit downloadFinished(file.fileName());
}
<commit_msg>Fix program updater to not download preversions<commit_after>#include <QNetworkRequest>
#include <QNetworkReply>
#include <QDir>
#include <QFile>
#include "program-updater.h"
#include "functions.h"
#include "json.h"
ProgramUpdater::ProgramUpdater()
: ProgramUpdater("https://api.github.com/repos/Bionus/imgbrd-grabber")
{ }
ProgramUpdater::ProgramUpdater(QString baseUrl)
: m_baseUrl(baseUrl)
{ }
void ProgramUpdater::checkForUpdates()
{
QUrl url(m_baseUrl + "/releases/latest");
QNetworkRequest request(url);
m_checkForUpdatesReply = m_networkAccessManager.get(request);
connect(m_checkForUpdatesReply, &QNetworkReply::finished, this, &ProgramUpdater::checkForUpdatesDone);
}
void ProgramUpdater::checkForUpdatesDone()
{
m_source = m_checkForUpdatesReply->readAll();
QVariant json = Json::parse(m_source);
QMap<QString, QVariant> lastRelease = json.toMap();
QString latest = lastRelease["name"].toString().mid(1);
QString changelog = lastRelease["body"].toString();
m_newVersion = latest;
bool isNew = compareVersions(latest, QString(VERSION)) > 0;
emit finished(latest, isNew, changelog);
}
void ProgramUpdater::downloadUpdate()
{
QVariant json = Json::parse(m_source);
QMap<QString, QVariant> lastRelease = json.toMap();
QMap<QString, QVariant> lastAsset = lastRelease["assets"].toList().first().toMap();
QUrl url(lastAsset["browser_download_url"].toString());
m_updateFilename = url.fileName();
QNetworkRequest request(url);
log(QString("Downloading installer from \"%1\".").arg(url.toString()));
m_downloadReply = m_networkAccessManager.get(request);
connect(m_downloadReply, &QNetworkReply::downloadProgress, this, &ProgramUpdater::downloadProgress);
connect(m_downloadReply, &QNetworkReply::finished, this, &ProgramUpdater::downloadDone);
}
void ProgramUpdater::downloadDone()
{
QUrl redir = m_downloadReply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
if (!redir.isEmpty())
{
log(QString("Installer download redirected to \"%1\".").arg(redir.toString()));
QNetworkRequest request(redir);
m_downloadReply = m_networkAccessManager.get(request);
connect(m_downloadReply, &QNetworkReply::downloadProgress, this, &ProgramUpdater::downloadProgress);
connect(m_downloadReply, &QNetworkReply::finished, this, &ProgramUpdater::downloadDone);
return;
}
QFile file(QDir::tempPath() + QDir::separator() + m_updateFilename);
if (!file.open(QFile::WriteOnly | QFile::Truncate))
{
log(QString("Error opening installer file \"%1\".").arg(file.fileName()));
return;
}
file.write(m_downloadReply->readAll());
file.close();
log(QString("Installer file written to \"%1\"").arg(file.fileName()));
emit downloadFinished(file.fileName());
}
<|endoftext|> |
<commit_before>#include "view/RemoteSkidmarkView.h"
#include <OgreRoot.h>
#include <OgreBillboardSet.h>
#include <OgreBillboard.h>
#include <sstream>
#include <string>
namespace Rally { namespace View {
RemoteSkidmarkView::RemoteSkidmarkView() {}
RemoteSkidmarkView::~RemoteSkidmarkView() {}
void RemoteSkidmarkView::attachTo(Ogre::SceneManager* sceneManager){
skidmarkNode = sceneManager->getRootSceneNode()->createChildSceneNode();
Ogre::BillboardType type = Ogre::BillboardType::BBT_PERPENDICULAR_SELF;
Ogre::BillboardRotationType rotationType = Ogre::BillboardRotationType::BBR_VERTEX;
Rally::Vector3 up(0, 0, 1);
Rally::Vector3 common(0, 1, 0);
skidmarkBillboards = sceneManager->createBillboardSet();
skidmarkBillboards->setMaterialName("skidmark");
skidmarkBillboards->setVisible(true);
skidmarkBillboards->setBillboardType(type);
skidmarkBillboards->setBillboardRotationType(rotationType);
skidmarkBillboards->setCommonUpVector(up);
skidmarkBillboards->setCommonDirection(common);
skidmarkBillboards->setBillboardsInWorldSpace(true);
skidmarkBillboards->setDefaultDimensions(Ogre::Real(0.2), Ogre::Real(0.4));
skidmarkBillboards->setAutoextend(true);
skidmarkNode->attachObject(skidmarkBillboards);
}
void RemoteSkidmarkView::update(const Rally::Model::RemoteCar& car){
float tractionReq = 0.1f;
float speed = car.getVelocity().length();
float heightOffset = -1.0f;
Rally::Vector3 direction = car.getVelocity().normalisedCopy();
if(car.getTractionVector().x < tractionReq){
createSkidmark(car.getPosition() + Ogre::Vector3(0.7f, heightOffset, 1.50f),
Rally::Vector3(0, 1, 0), direction, car.getTractionVector().x, speed);
}
if(car.getTractionVector().y < tractionReq){
createSkidmark(car.getPosition() + Ogre::Vector3(-0.7f, heightOffset, 1.50f),
Rally::Vector3(0, 1, 0), direction, car.getTractionVector().y, speed);
}
if(car.getTractionVector().z < tractionReq){
createSkidmark(car.getPosition() + Ogre::Vector3(0.7f, heightOffset, -1.25f),
Rally::Vector3(0, 1, 0), direction, car.getTractionVector().z, speed);
}
if(car.getTractionVector().w < tractionReq){
createSkidmark(car.getPosition() + Ogre::Vector3(-0.7f, heightOffset, -1.25f),
Rally::Vector3(0, 1, 0), direction, car.getTractionVector().w, speed);
}
}
void RemoteSkidmarkView::createSkidmark(Rally::Vector3 position, Rally::Vector3 normal, Rally::Vector3 direction, float traction, float speed){
Ogre::Billboard* b = skidmarkBillboards->createBillboard(Rally::Vector3(position.x, position.y+0.05f, position.z),
Ogre::ColourValue::Black);
double lengthAdjust = 0.008;
float alphaAdjust = 4.0f;
b->setDimensions(Ogre::Real(0.2), Ogre::Real(Ogre::Math::Clamp(lengthAdjust*speed, 0.15, 1.0)));
b->setColour(Ogre::ColourValue(1.0, 1.0, 1.0, traction*alphaAdjust));
b->mDirection = normal;
direction.y = 0;
Ogre::Radian r = direction.angleBetween(Rally::Vector3(0, 0, 1));
if(direction.z > 0 && direction.x > 0){
r = Ogre::Radian(Ogre::Math::PI*2) - r;
}
if(direction.z < 0 && direction.x > 0){
r *= -1;
}
b->setRotation(r);
if(skidmarkBillboards->getNumBillboards() > 1000)
skidmarkBillboards->removeBillboard(skidmarkBillboards->getBillboard(skidmarkBillboards->getNumBillboards()-1000));
}
} }
<commit_msg>Skidmark positions are now more accurate<commit_after>#include "view/RemoteSkidmarkView.h"
#include <OgreRoot.h>
#include <OgreBillboardSet.h>
#include <OgreBillboard.h>
#include <sstream>
#include <string>
namespace Rally { namespace View {
RemoteSkidmarkView::RemoteSkidmarkView() {}
RemoteSkidmarkView::~RemoteSkidmarkView() {}
void RemoteSkidmarkView::attachTo(Ogre::SceneManager* sceneManager){
skidmarkNode = sceneManager->getRootSceneNode()->createChildSceneNode();
Ogre::BillboardType type = Ogre::BillboardType::BBT_PERPENDICULAR_SELF;
Ogre::BillboardRotationType rotationType = Ogre::BillboardRotationType::BBR_VERTEX;
Rally::Vector3 up(0, 0, 1);
Rally::Vector3 common(0, 1, 0);
skidmarkBillboards = sceneManager->createBillboardSet();
skidmarkBillboards->setMaterialName("skidmark");
skidmarkBillboards->setVisible(true);
skidmarkBillboards->setBillboardType(type);
skidmarkBillboards->setBillboardRotationType(rotationType);
skidmarkBillboards->setCommonUpVector(up);
skidmarkBillboards->setCommonDirection(common);
skidmarkBillboards->setBillboardsInWorldSpace(true);
skidmarkBillboards->setDefaultDimensions(Ogre::Real(0.15), Ogre::Real(0.4));
skidmarkBillboards->setAutoextend(true);
skidmarkNode->attachObject(skidmarkBillboards);
}
void RemoteSkidmarkView::update(const Rally::Model::RemoteCar& car){
float tractionReq = 0.1f;
float speed = car.getVelocity().length();
float heightOffset = -1.0f;
float xOffset = 0.60f;
float zOffsetFront = 1.50f;
float zOffsetBack = -1.25f;
Rally::Vector3 direction = car.getVelocity().normalisedCopy();
Rally::Vector3 normal(0, 1, 0);
// Right front
if(car.getTractionVector().x < tractionReq){
createSkidmark(car.getPosition() + Ogre::Vector3(xOffset, heightOffset, zOffsetFront),
normal, direction, car.getTractionVector().x, speed);
}
// Left front
if(car.getTractionVector().y < tractionReq){
createSkidmark(car.getPosition() + Ogre::Vector3(-xOffset, heightOffset, zOffsetFront),
normal, direction, car.getTractionVector().y, speed);
}
// Right back
if(car.getTractionVector().z < tractionReq){
createSkidmark(car.getPosition() + Ogre::Vector3(xOffset, heightOffset, zOffsetBack),
normal, direction, car.getTractionVector().z, speed);
}
// Left back
if(car.getTractionVector().w < tractionReq){
createSkidmark(car.getPosition() + Ogre::Vector3(-xOffset, heightOffset, zOffsetBack),
normal, direction, car.getTractionVector().w, speed);
}
}
void RemoteSkidmarkView::createSkidmark(Rally::Vector3 position, Rally::Vector3 normal, Rally::Vector3 direction, float traction, float speed){
Ogre::Billboard* b = skidmarkBillboards->createBillboard(Rally::Vector3(position.x, position.y+0.05f, position.z),
Ogre::ColourValue::Black);
double lengthAdjust = 0.012;
float alphaAdjust = 4.0f;
b->setDimensions(Ogre::Real(0.2), Ogre::Real(Ogre::Math::Clamp(lengthAdjust*speed, 0.15, 1.0)));
b->setColour(Ogre::ColourValue(1.0, 1.0, 1.0, traction*alphaAdjust));
b->mDirection = normal;
direction.y = 0;
Ogre::Radian r = direction.angleBetween(Rally::Vector3(0, 0, 1));
if(direction.z > 0 && direction.x > 0){
r = Ogre::Radian(Ogre::Math::PI*2) - r;
}
if(direction.z < 0 && direction.x > 0){
r *= -1;
}
b->setRotation(r);
if(skidmarkBillboards->getNumBillboards() > 1000)
skidmarkBillboards->removeBillboard(skidmarkBillboards->getBillboard(skidmarkBillboards->getNumBillboards()-1000));
}
} }
<|endoftext|> |
<commit_before>/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(XALANMAP_HEADER_GUARD_1357924680)
#define XALANMAP_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>
#include <cstddef>
#include <list>
#include <algorithm>
#include <functional>
#include <utility>
#include <xercesc/framework/MemoryManager.hpp>
#include <xalanc/Include/XalanVector.hpp>
XALAN_CPP_NAMESPACE_BEGIN
typedef size_t size_type;
template <class Key>
class XalanHash : public XALAN_STD_QUALIFIER unary_function<Key, size_type>
{
public:
size_type operator()(const Key& key) const
{
const char *byteArray = reinterpret_cast<const char*>(&key);
size_type result = 0;
for (size_type i = 0; i < sizeof(Key); ++i)
{
result = (result << 1) ^ byteArray[i];
}
return result;
}
};
template <class Key>
struct XalanHashMemberPointer
{
size_type operator() (const Key * key) const
{
assert (key != 0);
return key->hash();
}
};
template <class Key>
struct XalanHashMemberReference
{
size_type operator() (const Key& key) const
{
return key.hash();
}
};
template <
class Key,
class Value,
class Hash = XalanHash<Key>,
class Comparator = XALAN_STD_QUALIFIER equal_to<Key> >
class XalanMap
{
public:
typedef XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager MemoryManagerType;
typedef Key key_type;
typedef Value data_type;
typedef size_t size_type;
typedef XALAN_STD_QUALIFIER pair<const key_type, data_type> value_type;
typedef XalanMap<Key, Value, Hash, Comparator> ThisType;
typedef size_t size_type;
struct Entry : public value_type
{
typedef value_type Parent;
size_type bucketIndex;
Entry(const key_type & key, const data_type& data, size_type index) :
value_type(key, data), bucketIndex(index)
{
}
Entry() :
value_type(key_type(),
data_type()),
bucketIndex(size_type())
{
}
};
typedef XALAN_STD_QUALIFIER list<Entry> EntryListType;
typedef typename EntryListType::iterator EntryListIterator;
typedef typename EntryListType::const_iterator EntryListConstIterator;
typedef XalanVector<typename EntryListType::iterator> EntryPosVectorType;
template<class ValueType, class Ref, class Ptr, class Iterator, class Map>
struct iterator_base
{
typedef ValueType value_type;
typedef Ref reference_type;
typedef Ptr pointer_type;
typedef ThisType MapType;
typedef iterator_base<value_type, reference_type, pointer_type, Iterator, Map> IteratorType;
typedef iterator_base<value_type, value_type&, value_type*, EntryListIterator, MapType> iterator;
iterator_base(
Map& map,
Iterator bucketPos) :
m_map(&map),
m_bucketPos(bucketPos)
{
}
iterator_base(const iterator& theRhs) :
m_map(theRhs.m_map),
m_bucketPos(theRhs.m_bucketPos)
{
}
const IteratorType & operator=(const IteratorType& theRhs)
{
m_map = theRhs.m_map;
m_bucketPos = theRhs.m_bucketPos;
return *this;
}
reference_type operator*() const
{
return *m_bucketPos;
}
int operator!=(const IteratorType& theRhs) const
{
return !operator==(theRhs);
}
int operator==(const IteratorType& theRhs) const
{
return (theRhs.m_map == m_map)
&& (theRhs.m_bucketPos == m_bucketPos);
}
IteratorType& operator++()
{
m_bucketPos++;
return *this;
}
Map* m_map;
Iterator m_bucketPos;
};
typedef iterator_base<
value_type,
value_type&,
value_type*,
EntryListIterator,
ThisType> iterator;
typedef iterator_base<
value_type,
const value_type&,
const value_type*,
EntryListConstIterator,
const ThisType> const_iterator;
XalanMap(
float loadFactor = 0.75,
MemoryManagerType* theMemoryManager = 0) :
m_memoryManager(theMemoryManager),
m_loadFactor(loadFactor),
m_size(0),
m_entries(/* m_memoryManager */),
m_buckets(10, m_entries.end(), m_memoryManager),
m_freeList()
{
}
XalanMap(const XalanMap &theRhs) :
m_memoryManager(theRhs.m_memoryManager),
m_loadFactor(theRhs.m_loadFactor),
m_size(0),
m_entries(/* m_memoryManager */),
m_buckets(size_type(m_loadFactor * theRhs.size())+ 1, m_entries.end(), m_memoryManager),
m_freeList()
{
const_iterator entry = theRhs.begin();
while(entry != theRhs.end())
{
insert(*entry);
++entry;
}
assert(m_size == theRhs.m_size);
}
~XalanMap()
{
}
XalanMap & operator=(const XalanMap& theRhs)
{
XalanMap theTemp(theRhs);
swap(theTemp);
return *this;
}
size_type size() const
{
return m_size;
}
bool empty() const {
return m_size == 0;
}
iterator begin()
{
return iterator(*this, m_entries.begin());
}
const_iterator begin() const
{
return const_iterator(*this, m_entries.begin());
}
iterator end()
{
return iterator(*this, m_entries.end());
}
const_iterator end() const
{
return const_iterator(*this, m_entries.end());
}
iterator find(const key_type& key)
{
size_type index = doHash(key);
EntryListIterator bucketPos = m_buckets[index];
while (bucketPos != m_entries.end() &&
bucketPos->bucketIndex == index)
{
if (m_equals(key,bucketPos->first))
{
return iterator(*this,bucketPos);
}
++bucketPos;
}
return end();
}
const_iterator find(const key_type& key) const
{
size_type index = doHash(key);
EntryListConstIterator bucketPos = m_buckets[index];
while (bucketPos != m_entries.end() &&
bucketPos->bucketIndex == index)
{
if (m_equals(key,bucketPos->first))
{
return const_iterator(*this,bucketPos);
}
++bucketPos;
}
return end();
}
data_type & operator[](const key_type& key)
{
iterator pos = find(key);
if (pos == end())
{
pos = doCreateEntry(key, data_type());
}
return (*pos).second;
}
void insert(const value_type& value)
{
const key_type& key = value.first;
const data_type& data = value.second;
iterator pos = find(key);
if (pos == end())
{
doCreateEntry(key, data);
}
}
void erase(iterator pos)
{
if (pos != end())
{
doRemoveEntry(pos.m_bucketPos);
}
}
void erase(const key_type& key)
{
iterator pos = find(key);
erase(pos);
}
void clear()
{
m_size = 0;
XALAN_STD_QUALIFIER fill(
m_buckets.begin(),
m_buckets.end(),
m_entries.end());
m_freeList.splice(
m_freeList.begin(),
m_entries,
m_entries.begin(),
m_entries.end());
}
void swap(ThisType& theRhs)
{
size_type tempSize = m_size;
m_size = theRhs.m_size;
theRhs.m_size = tempSize;
MemoryManagerType* tempMemoryManager = m_memoryManager;
m_memoryManager = theRhs.m_memoryManager;
theRhs.m_memoryManager = tempMemoryManager;
m_entries.swap(theRhs.m_entries);
m_buckets.swap(theRhs.m_buckets);
m_freeList.swap(theRhs.m_freeList);
}
protected:
iterator doCreateEntry(const key_type & key, const data_type& data)
{
if (size_type(m_loadFactor * size()) > m_buckets.size())
{
rehash();
}
size_type index = doHash(key);
EntryListIterator & bucketStartPos = m_buckets[index];
if (m_freeList.empty() == true)
{
Entry newEntry = Entry(key, data, index);
if (bucketStartPos == m_entries.end())
{
bucketStartPos = m_entries.insert(m_entries.end(), newEntry);
}
else
{
bucketStartPos = m_entries.insert(bucketStartPos, newEntry);
}
}
else
{
(*m_freeList.begin()).~Entry();
new (&*m_freeList.begin()) Entry(key, data, index);
m_entries.splice(bucketStartPos, m_freeList, m_freeList.begin());
--bucketStartPos;
}
++m_size;
return iterator(*this, bucketStartPos);
}
void doRemoveEntry(const EntryListIterator & toRemoveIter)
{
size_type index = toRemoveIter->bucketIndex;
EntryListIterator nextPosition = ++(EntryListIterator(toRemoveIter));
if (m_buckets[index] == toRemoveIter)
{
if (nextPosition->bucketIndex == index)
{
m_buckets[index] = nextPosition;
}
else
{
m_buckets[index] = m_entries.end();
}
}
m_freeList.splice(m_freeList.begin(), m_entries, toRemoveIter, nextPosition);
--m_size;
}
size_type doHash(const Key & key) const
{
return m_hash(key) % m_buckets.size();
}
void rehash()
{
EntryPosVectorType temp(size_type(1.6 * size()), m_entries.end(), m_memoryManager);
m_buckets.swap(temp);
doRehashEntries();
}
void doRehashEntries()
{
EntryListType tempEntryList;
tempEntryList.splice(tempEntryList.begin(),m_entries, m_entries.begin(), m_entries.end());
while (tempEntryList.begin() != tempEntryList.end())
{
EntryListIterator entry = tempEntryList.begin();
entry->bucketIndex = doHash(entry->first);
EntryListIterator & bucketStartPos = m_buckets[entry->bucketIndex];
if (bucketStartPos == m_entries.end())
{
bucketStartPos = entry;
m_entries.splice(m_entries.begin(), tempEntryList, entry);
}
else
{
m_entries.splice(bucketStartPos, tempEntryList, entry);
--bucketStartPos;
}
}
}
// Data members...
Hash m_hash;
Comparator m_equals;
MemoryManagerType* m_memoryManager;
float m_loadFactor;
size_type m_size;
EntryListType m_entries;
EntryPosVectorType m_buckets;
EntryListType m_freeList;
};
XALAN_CPP_NAMESPACE_END
#endif // XALANMAP_HEADER_GUARD_1357924680
<commit_msg>Remove redundant typedef to allow gcc compile<commit_after>/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(XALANMAP_HEADER_GUARD_1357924680)
#define XALANMAP_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>
#include <cstddef>
#include <list>
#include <algorithm>
#include <functional>
#include <utility>
#include <xercesc/framework/MemoryManager.hpp>
#include <xalanc/Include/XalanVector.hpp>
XALAN_CPP_NAMESPACE_BEGIN
typedef size_t size_type;
template <class Key>
class XalanHash : public XALAN_STD_QUALIFIER unary_function<Key, size_type>
{
public:
size_type operator()(const Key& key) const
{
const char *byteArray = reinterpret_cast<const char*>(&key);
size_type result = 0;
for (size_type i = 0; i < sizeof(Key); ++i)
{
result = (result << 1) ^ byteArray[i];
}
return result;
}
};
template <class Key>
struct XalanHashMemberPointer
{
size_type operator() (const Key * key) const
{
assert (key != 0);
return key->hash();
}
};
template <class Key>
struct XalanHashMemberReference
{
size_type operator() (const Key& key) const
{
return key.hash();
}
};
template <
class Key,
class Value,
class Hash = XalanHash<Key>,
class Comparator = XALAN_STD_QUALIFIER equal_to<Key> >
class XalanMap
{
public:
typedef XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager MemoryManagerType;
typedef Key key_type;
typedef Value data_type;
typedef size_t size_type;
typedef XALAN_STD_QUALIFIER pair<const key_type, data_type> value_type;
typedef XalanMap<Key, Value, Hash, Comparator> ThisType;
struct Entry : public value_type
{
typedef value_type Parent;
size_type bucketIndex;
Entry(const key_type & key, const data_type& data, size_type index) :
value_type(key, data), bucketIndex(index)
{
}
Entry() :
value_type(key_type(),
data_type()),
bucketIndex(size_type())
{
}
};
typedef XALAN_STD_QUALIFIER list<Entry> EntryListType;
typedef typename EntryListType::iterator EntryListIterator;
typedef typename EntryListType::const_iterator EntryListConstIterator;
typedef XalanVector<typename EntryListType::iterator> EntryPosVectorType;
template<class ValueType, class Ref, class Ptr, class Iterator, class Map>
struct iterator_base
{
typedef ValueType value_type;
typedef Ref reference_type;
typedef Ptr pointer_type;
typedef ThisType MapType;
typedef iterator_base<value_type, reference_type, pointer_type, Iterator, Map> IteratorType;
typedef iterator_base<value_type, value_type&, value_type*, EntryListIterator, MapType> iterator;
iterator_base(
Map& map,
Iterator bucketPos) :
m_map(&map),
m_bucketPos(bucketPos)
{
}
iterator_base(const iterator& theRhs) :
m_map(theRhs.m_map),
m_bucketPos(theRhs.m_bucketPos)
{
}
const IteratorType & operator=(const IteratorType& theRhs)
{
m_map = theRhs.m_map;
m_bucketPos = theRhs.m_bucketPos;
return *this;
}
reference_type operator*() const
{
return *m_bucketPos;
}
int operator!=(const IteratorType& theRhs) const
{
return !operator==(theRhs);
}
int operator==(const IteratorType& theRhs) const
{
return (theRhs.m_map == m_map)
&& (theRhs.m_bucketPos == m_bucketPos);
}
IteratorType& operator++()
{
m_bucketPos++;
return *this;
}
Map* m_map;
Iterator m_bucketPos;
};
typedef iterator_base<
value_type,
value_type&,
value_type*,
EntryListIterator,
ThisType> iterator;
typedef iterator_base<
value_type,
const value_type&,
const value_type*,
EntryListConstIterator,
const ThisType> const_iterator;
XalanMap(
float loadFactor = 0.75,
MemoryManagerType* theMemoryManager = 0) :
m_memoryManager(theMemoryManager),
m_loadFactor(loadFactor),
m_size(0),
m_entries(/* m_memoryManager */),
m_buckets(10, m_entries.end(), m_memoryManager),
m_freeList()
{
}
XalanMap(const XalanMap &theRhs) :
m_memoryManager(theRhs.m_memoryManager),
m_loadFactor(theRhs.m_loadFactor),
m_size(0),
m_entries(/* m_memoryManager */),
m_buckets(size_type(m_loadFactor * theRhs.size())+ 1, m_entries.end(), m_memoryManager),
m_freeList()
{
const_iterator entry = theRhs.begin();
while(entry != theRhs.end())
{
insert(*entry);
++entry;
}
assert(m_size == theRhs.m_size);
}
~XalanMap()
{
}
XalanMap & operator=(const XalanMap& theRhs)
{
XalanMap theTemp(theRhs);
swap(theTemp);
return *this;
}
size_type size() const
{
return m_size;
}
bool empty() const {
return m_size == 0;
}
iterator begin()
{
return iterator(*this, m_entries.begin());
}
const_iterator begin() const
{
return const_iterator(*this, m_entries.begin());
}
iterator end()
{
return iterator(*this, m_entries.end());
}
const_iterator end() const
{
return const_iterator(*this, m_entries.end());
}
iterator find(const key_type& key)
{
size_type index = doHash(key);
EntryListIterator bucketPos = m_buckets[index];
while (bucketPos != m_entries.end() &&
bucketPos->bucketIndex == index)
{
if (m_equals(key,bucketPos->first))
{
return iterator(*this,bucketPos);
}
++bucketPos;
}
return end();
}
const_iterator find(const key_type& key) const
{
size_type index = doHash(key);
EntryListConstIterator bucketPos = m_buckets[index];
while (bucketPos != m_entries.end() &&
bucketPos->bucketIndex == index)
{
if (m_equals(key,bucketPos->first))
{
return const_iterator(*this,bucketPos);
}
++bucketPos;
}
return end();
}
data_type & operator[](const key_type& key)
{
iterator pos = find(key);
if (pos == end())
{
pos = doCreateEntry(key, data_type());
}
return (*pos).second;
}
void insert(const value_type& value)
{
const key_type& key = value.first;
const data_type& data = value.second;
iterator pos = find(key);
if (pos == end())
{
doCreateEntry(key, data);
}
}
void erase(iterator pos)
{
if (pos != end())
{
doRemoveEntry(pos.m_bucketPos);
}
}
void erase(const key_type& key)
{
iterator pos = find(key);
erase(pos);
}
void clear()
{
m_size = 0;
XALAN_STD_QUALIFIER fill(
m_buckets.begin(),
m_buckets.end(),
m_entries.end());
m_freeList.splice(
m_freeList.begin(),
m_entries,
m_entries.begin(),
m_entries.end());
}
void swap(ThisType& theRhs)
{
size_type tempSize = m_size;
m_size = theRhs.m_size;
theRhs.m_size = tempSize;
MemoryManagerType* tempMemoryManager = m_memoryManager;
m_memoryManager = theRhs.m_memoryManager;
theRhs.m_memoryManager = tempMemoryManager;
m_entries.swap(theRhs.m_entries);
m_buckets.swap(theRhs.m_buckets);
m_freeList.swap(theRhs.m_freeList);
}
protected:
iterator doCreateEntry(const key_type & key, const data_type& data)
{
if (size_type(m_loadFactor * size()) > m_buckets.size())
{
rehash();
}
size_type index = doHash(key);
EntryListIterator & bucketStartPos = m_buckets[index];
if (m_freeList.empty() == true)
{
Entry newEntry = Entry(key, data, index);
if (bucketStartPos == m_entries.end())
{
bucketStartPos = m_entries.insert(m_entries.end(), newEntry);
}
else
{
bucketStartPos = m_entries.insert(bucketStartPos, newEntry);
}
}
else
{
(*m_freeList.begin()).~Entry();
new (&*m_freeList.begin()) Entry(key, data, index);
m_entries.splice(bucketStartPos, m_freeList, m_freeList.begin());
--bucketStartPos;
}
++m_size;
return iterator(*this, bucketStartPos);
}
void doRemoveEntry(const EntryListIterator & toRemoveIter)
{
size_type index = toRemoveIter->bucketIndex;
EntryListIterator nextPosition = ++(EntryListIterator(toRemoveIter));
if (m_buckets[index] == toRemoveIter)
{
if (nextPosition->bucketIndex == index)
{
m_buckets[index] = nextPosition;
}
else
{
m_buckets[index] = m_entries.end();
}
}
m_freeList.splice(m_freeList.begin(), m_entries, toRemoveIter, nextPosition);
--m_size;
}
size_type doHash(const Key & key) const
{
return m_hash(key) % m_buckets.size();
}
void rehash()
{
EntryPosVectorType temp(size_type(1.6 * size()), m_entries.end(), m_memoryManager);
m_buckets.swap(temp);
doRehashEntries();
}
void doRehashEntries()
{
EntryListType tempEntryList;
tempEntryList.splice(tempEntryList.begin(),m_entries, m_entries.begin(), m_entries.end());
while (tempEntryList.begin() != tempEntryList.end())
{
EntryListIterator entry = tempEntryList.begin();
entry->bucketIndex = doHash(entry->first);
EntryListIterator & bucketStartPos = m_buckets[entry->bucketIndex];
if (bucketStartPos == m_entries.end())
{
bucketStartPos = entry;
m_entries.splice(m_entries.begin(), tempEntryList, entry);
}
else
{
m_entries.splice(bucketStartPos, tempEntryList, entry);
--bucketStartPos;
}
}
}
// Data members...
Hash m_hash;
Comparator m_equals;
MemoryManagerType* m_memoryManager;
float m_loadFactor;
size_type m_size;
EntryListType m_entries;
EntryPosVectorType m_buckets;
EntryListType m_freeList;
};
XALAN_CPP_NAMESPACE_END
#endif // XALANMAP_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before><commit_msg>Extra line.<commit_after><|endoftext|> |
<commit_before>// ClockTool.cc
// Copyright (c) 2003 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org)
// and Simon Bowden (rathnor at users.sourceforge.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// $Id$
#include "ClockTool.hh"
#include "ToolTheme.hh"
#include "Screen.hh"
#include "CommandParser.hh"
#include "CommandDialog.hh"
#include "fluxbox.hh"
#include "FbTk/SimpleCommand.hh"
#include "FbTk/ImageControl.hh"
#include "FbTk/Menu.hh"
#include "FbTk/MenuItem.hh"
#include "FbTk/I18n.hh"
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H
#ifdef HAVE_CTIME
#include <ctime>
#else
#include <time.h>
#endif
#include <sys/time.h>
#include <string>
#include <typeinfo>
class ClockMenuItem: public FbTk::MenuItem {
public:
explicit ClockMenuItem(ClockTool &tool):
FbTk::MenuItem(""), m_tool(tool) {
// determine 12/24 hour format
_FB_USES_NLS;
if (m_tool.timeFormat().find("%k") != std::string::npos ||
m_tool.timeFormat().find("%H") != std::string::npos ||
m_tool.timeFormat().find("%T") != std::string::npos)
setLabel( _FB_XTEXT(Toolbar, Clock24, "Clock: 24h", "set Clockmode to 24h") );
else
setLabel( _FB_XTEXT(Toolbar, Clock12, "Clock: 12h", "set Clockmode to 12h") );
}
void click(int button, int time) {
std::string newformat = m_tool.timeFormat();
size_t pos = newformat.find("%k");
std::string newstr;
bool clock24hour = true;
_FB_USES_NLS;
if (pos != std::string::npos)
newstr = "%l";
else if ((pos = newformat.find("%H")) != std::string::npos)
newstr = "%I";
else if ((pos = newformat.find("%T")) != std::string::npos)
newstr = "%r";
// 12 hour
if (newstr.empty()) {
clock24hour = false;
if ((pos = newformat.find("%l")) != std::string::npos)
newstr = "%k";
else if ((pos = newformat.find("%I")) != std::string::npos)
newstr = "%H";
else if ((pos = newformat.find("%r")) != std::string::npos)
newstr = "%T";
}
if (!newstr.empty()) {
newformat.replace(pos, 2, newstr);
if (!clock24hour) { // erase %P/%p (AM|PM / am|pm)
pos = newformat.find("%p");
if (pos != std::string::npos)
newformat.erase(pos, 2);
else if ((pos = newformat.find("%P")) != std::string::npos)
newformat.erase(pos, 2);
}
m_tool.setTimeFormat(newformat);
if (m_tool.timeFormat().find("%k") != std::string::npos ||
m_tool.timeFormat().find("%H") != std::string::npos ||
m_tool.timeFormat().find("%T") != std::string::npos)
setLabel( _FB_XTEXT(Toolbar, Clock24, "Clock: 24h", "set Clockmode to 24h") );
else
setLabel( _FB_XTEXT(Toolbar, Clock12, "Clock: 12h", "set Clockmode to 12h") );
} // else some other strange format...so we don't do anything
FbTk::MenuItem::click(button, time);
}
private:
ClockTool &m_tool;
};
class EditClockFormatCmd: public FbTk::Command {
public:
void execute() {
BScreen *screen = Fluxbox::instance()->mouseScreen();
if (screen == 0)
return;
std::string resourcename = screen->name() + ".strftimeFormat";
CommandDialog *dialog = new CommandDialog(*screen, "Edit Clock Format",
"SetResourceValue " + resourcename + " ");
FbTk::RefCount<FbTk::Command> cmd(CommandParser::instance().parseLine("reconfigure"));
dialog->setPostCommand(cmd);
dialog->setText(screen->resourceManager().resourceValue(resourcename));
dialog->show();
}
};
ClockTool::ClockTool(const FbTk::FbWindow &parent,
ToolTheme &theme, BScreen &screen, FbTk::Menu &menu):
ToolbarItem(ToolbarItem::FIXED),
m_button(parent, theme.font(), ""),
m_theme(theme),
m_screen(screen),
m_pixmap(0),
m_timeformat(screen.resourceManager(), std::string("%k:%M"),
screen.name() + ".strftimeFormat", screen.altName() + ".StrftimeFormat"),
m_stringconvertor(FbTk::StringConvertor::ToFbString) {
// attach signals
theme.reconfigSig().attach(this);
std::string time_locale = setlocale(LC_TIME, NULL);
size_t pos = time_locale.find('.');
if (pos != std::string::npos)
time_locale = time_locale.substr(pos+1);
if (!time_locale.empty())
m_stringconvertor.setSource(time_locale);
_FB_USES_NLS;
// setup timer to check the clock every 0.01 second
// if nothing has changed, it wont update the graphics
m_timer.setInterval(1);
// m_timer.setTimeout(delay); // don't need to set timeout on interval timer
FbTk::RefCount<FbTk::Command> update_graphic(new FbTk::SimpleCommand<ClockTool>(*this,
&ClockTool::updateTime));
m_timer.setCommand(update_graphic);
m_timer.start();
m_button.setGC(m_theme.textGC());
// setup menu
FbTk::RefCount<FbTk::Command> saverc(CommandParser::instance().parseLine("saverc"));
FbTk::MenuItem *item = new ClockMenuItem(*this);
item->setCommand(saverc);
menu.insert(item);
FbTk::RefCount<FbTk::Command> editformat_cmd(new EditClockFormatCmd());
menu.insert(_FB_XTEXT(Toolbar, ClockEditFormat, "Edit Clock Format", "edit Clock Format") , editformat_cmd);
update(0);
}
ClockTool::~ClockTool() {
// remove cached pixmap
if (m_pixmap)
m_screen.imageControl().removeImage(m_pixmap);
}
void ClockTool::move(int x, int y) {
m_button.move(x, y);
}
void ClockTool::resize(unsigned int width, unsigned int height) {
m_button.resize(width, height);
reRender();
m_button.clear();
}
void ClockTool::moveResize(int x, int y,
unsigned int width, unsigned int height) {
m_button.moveResize(x, y, width, height);
reRender();
m_button.clear();
}
void ClockTool::show() {
m_button.show();
}
void ClockTool::hide() {
m_button.hide();
}
void ClockTool::setTimeFormat(const std::string &format) {
*m_timeformat = format;
update(0);
}
void ClockTool::update(FbTk::Subject *subj) {
updateTime();
// + 2 to make the entire text fit inside
// we only replace numbers with zeros because everything else should be
// relatively static. If we replace all text with zeros then widths of
// proportional fonts with some strftime formats will be considerably off.
std::string text(m_button.text());
int textlen = text.size();
for (int i=0; i < textlen; ++i) {
if (text[i] > '0' && text[i] <= '9') // don't bother replacing zeros
text[i] = '0';
}
text.append("00"); // pad
unsigned int new_width = m_button.width();
unsigned int new_height = m_button.height();
translateSize(orientation(), new_width, new_height);
new_width = m_theme.font().textWidth(text.c_str(), text.size());
translateSize(orientation(), new_width, new_height);
if (new_width != m_button.width() || new_height != m_button.height()) {
resize(new_width, new_height);
resizeSig().notify();
}
if (subj != 0 && typeid(*subj) == typeid(ToolTheme))
renderTheme(m_button.alpha());
}
unsigned int ClockTool::borderWidth() const {
return m_button.borderWidth();
}
unsigned int ClockTool::width() const {
return m_button.width();
}
unsigned int ClockTool::height() const {
return m_button.height();
}
void ClockTool::updateTime() {
// update clock
timeval now;
gettimeofday(&now, 0);
time_t the_time = now.tv_sec;
if (the_time != -1) {
char time_string[255];
int time_string_len;
struct tm *time_type = localtime(&the_time);
if (time_type == 0)
return;
#ifdef HAVE_STRFTIME
time_string_len = strftime(time_string, 255, m_timeformat->c_str(), time_type);
if( time_string_len == 0)
return;
std::string text = m_stringconvertor.recode(time_string);
if (m_button.text() == text)
return;
m_button.setText(text);
unsigned int new_width = m_theme.font().textWidth(time_string, time_string_len) + 2;
if (new_width > m_button.width()) {
resize(new_width, m_button.height());
resizeSig().notify();
}
#else // dont have strftime so we have to set it to hour:minut
// sprintf(time_string, "%d:%d", );
#endif // HAVE_STRFTIME
}
}
// Just change things that affect the size
void ClockTool::updateSizing() {
m_button.setBorderWidth(m_theme.border().width());
// resizes if new timeformat
update(0);
}
void ClockTool::reRender() {
if (m_pixmap)
m_screen.imageControl().removeImage(m_pixmap);
if (m_theme.texture().usePixmap()) {
m_pixmap = m_screen.imageControl().renderImage(width(), height(),
m_theme.texture(), orientation());
m_button.setBackgroundPixmap(m_pixmap);
} else {
m_pixmap = 0;
m_button.setBackgroundColor(m_theme.texture().color());
}
}
void ClockTool::renderTheme(unsigned char alpha) {
m_button.setAlpha(alpha);
m_button.setJustify(m_theme.justify());
reRender();
m_button.setBorderWidth(m_theme.border().width());
m_button.setBorderColor(m_theme.border().color());
m_button.clear();
}
void ClockTool::setOrientation(FbTk::Orientation orient) {
m_button.setOrientation(orient);
ToolbarItem::setOrientation(orient);
}
<commit_msg>use proper test for whether it's a number.<commit_after>// ClockTool.cc
// Copyright (c) 2003 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org)
// and Simon Bowden (rathnor at users.sourceforge.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// $Id$
#include "ClockTool.hh"
#include "ToolTheme.hh"
#include "Screen.hh"
#include "CommandParser.hh"
#include "CommandDialog.hh"
#include "fluxbox.hh"
#include "FbTk/SimpleCommand.hh"
#include "FbTk/ImageControl.hh"
#include "FbTk/Menu.hh"
#include "FbTk/MenuItem.hh"
#include "FbTk/I18n.hh"
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H
#ifdef HAVE_CTIME
#include <ctime>
#else
#include <time.h>
#endif
#include <sys/time.h>
#include <string>
#include <typeinfo>
class ClockMenuItem: public FbTk::MenuItem {
public:
explicit ClockMenuItem(ClockTool &tool):
FbTk::MenuItem(""), m_tool(tool) {
// determine 12/24 hour format
_FB_USES_NLS;
if (m_tool.timeFormat().find("%k") != std::string::npos ||
m_tool.timeFormat().find("%H") != std::string::npos ||
m_tool.timeFormat().find("%T") != std::string::npos)
setLabel( _FB_XTEXT(Toolbar, Clock24, "Clock: 24h", "set Clockmode to 24h") );
else
setLabel( _FB_XTEXT(Toolbar, Clock12, "Clock: 12h", "set Clockmode to 12h") );
}
void click(int button, int time) {
std::string newformat = m_tool.timeFormat();
size_t pos = newformat.find("%k");
std::string newstr;
bool clock24hour = true;
_FB_USES_NLS;
if (pos != std::string::npos)
newstr = "%l";
else if ((pos = newformat.find("%H")) != std::string::npos)
newstr = "%I";
else if ((pos = newformat.find("%T")) != std::string::npos)
newstr = "%r";
// 12 hour
if (newstr.empty()) {
clock24hour = false;
if ((pos = newformat.find("%l")) != std::string::npos)
newstr = "%k";
else if ((pos = newformat.find("%I")) != std::string::npos)
newstr = "%H";
else if ((pos = newformat.find("%r")) != std::string::npos)
newstr = "%T";
}
if (!newstr.empty()) {
newformat.replace(pos, 2, newstr);
if (!clock24hour) { // erase %P/%p (AM|PM / am|pm)
pos = newformat.find("%p");
if (pos != std::string::npos)
newformat.erase(pos, 2);
else if ((pos = newformat.find("%P")) != std::string::npos)
newformat.erase(pos, 2);
}
m_tool.setTimeFormat(newformat);
if (m_tool.timeFormat().find("%k") != std::string::npos ||
m_tool.timeFormat().find("%H") != std::string::npos ||
m_tool.timeFormat().find("%T") != std::string::npos)
setLabel( _FB_XTEXT(Toolbar, Clock24, "Clock: 24h", "set Clockmode to 24h") );
else
setLabel( _FB_XTEXT(Toolbar, Clock12, "Clock: 12h", "set Clockmode to 12h") );
} // else some other strange format...so we don't do anything
FbTk::MenuItem::click(button, time);
}
private:
ClockTool &m_tool;
};
class EditClockFormatCmd: public FbTk::Command {
public:
void execute() {
BScreen *screen = Fluxbox::instance()->mouseScreen();
if (screen == 0)
return;
std::string resourcename = screen->name() + ".strftimeFormat";
CommandDialog *dialog = new CommandDialog(*screen, "Edit Clock Format",
"SetResourceValue " + resourcename + " ");
FbTk::RefCount<FbTk::Command> cmd(CommandParser::instance().parseLine("reconfigure"));
dialog->setPostCommand(cmd);
dialog->setText(screen->resourceManager().resourceValue(resourcename));
dialog->show();
}
};
ClockTool::ClockTool(const FbTk::FbWindow &parent,
ToolTheme &theme, BScreen &screen, FbTk::Menu &menu):
ToolbarItem(ToolbarItem::FIXED),
m_button(parent, theme.font(), ""),
m_theme(theme),
m_screen(screen),
m_pixmap(0),
m_timeformat(screen.resourceManager(), std::string("%k:%M"),
screen.name() + ".strftimeFormat", screen.altName() + ".StrftimeFormat"),
m_stringconvertor(FbTk::StringConvertor::ToFbString) {
// attach signals
theme.reconfigSig().attach(this);
std::string time_locale = setlocale(LC_TIME, NULL);
size_t pos = time_locale.find('.');
if (pos != std::string::npos)
time_locale = time_locale.substr(pos+1);
if (!time_locale.empty())
m_stringconvertor.setSource(time_locale);
_FB_USES_NLS;
// setup timer to check the clock every 0.01 second
// if nothing has changed, it wont update the graphics
m_timer.setInterval(1);
// m_timer.setTimeout(delay); // don't need to set timeout on interval timer
FbTk::RefCount<FbTk::Command> update_graphic(new FbTk::SimpleCommand<ClockTool>(*this,
&ClockTool::updateTime));
m_timer.setCommand(update_graphic);
m_timer.start();
m_button.setGC(m_theme.textGC());
// setup menu
FbTk::RefCount<FbTk::Command> saverc(CommandParser::instance().parseLine("saverc"));
FbTk::MenuItem *item = new ClockMenuItem(*this);
item->setCommand(saverc);
menu.insert(item);
FbTk::RefCount<FbTk::Command> editformat_cmd(new EditClockFormatCmd());
menu.insert(_FB_XTEXT(Toolbar, ClockEditFormat, "Edit Clock Format", "edit Clock Format") , editformat_cmd);
update(0);
}
ClockTool::~ClockTool() {
// remove cached pixmap
if (m_pixmap)
m_screen.imageControl().removeImage(m_pixmap);
}
void ClockTool::move(int x, int y) {
m_button.move(x, y);
}
void ClockTool::resize(unsigned int width, unsigned int height) {
m_button.resize(width, height);
reRender();
m_button.clear();
}
void ClockTool::moveResize(int x, int y,
unsigned int width, unsigned int height) {
m_button.moveResize(x, y, width, height);
reRender();
m_button.clear();
}
void ClockTool::show() {
m_button.show();
}
void ClockTool::hide() {
m_button.hide();
}
void ClockTool::setTimeFormat(const std::string &format) {
*m_timeformat = format;
update(0);
}
void ClockTool::update(FbTk::Subject *subj) {
updateTime();
// + 2 to make the entire text fit inside
// we only replace numbers with zeros because everything else should be
// relatively static. If we replace all text with zeros then widths of
// proportional fonts with some strftime formats will be considerably off.
std::string text(m_button.text());
int textlen = text.size();
for (int i=0; i < textlen; ++i) {
if (isdigit(text[i])) // don't bother replacing zeros
text[i] = '0';
}
text.append("00"); // pad
unsigned int new_width = m_button.width();
unsigned int new_height = m_button.height();
translateSize(orientation(), new_width, new_height);
new_width = m_theme.font().textWidth(text.c_str(), text.size());
translateSize(orientation(), new_width, new_height);
if (new_width != m_button.width() || new_height != m_button.height()) {
resize(new_width, new_height);
resizeSig().notify();
}
if (subj != 0 && typeid(*subj) == typeid(ToolTheme))
renderTheme(m_button.alpha());
}
unsigned int ClockTool::borderWidth() const {
return m_button.borderWidth();
}
unsigned int ClockTool::width() const {
return m_button.width();
}
unsigned int ClockTool::height() const {
return m_button.height();
}
void ClockTool::updateTime() {
// update clock
timeval now;
gettimeofday(&now, 0);
time_t the_time = now.tv_sec;
if (the_time != -1) {
char time_string[255];
int time_string_len;
struct tm *time_type = localtime(&the_time);
if (time_type == 0)
return;
#ifdef HAVE_STRFTIME
time_string_len = strftime(time_string, 255, m_timeformat->c_str(), time_type);
if( time_string_len == 0)
return;
std::string text = m_stringconvertor.recode(time_string);
if (m_button.text() == text)
return;
m_button.setText(text);
unsigned int new_width = m_theme.font().textWidth(time_string, time_string_len) + 2;
if (new_width > m_button.width()) {
resize(new_width, m_button.height());
resizeSig().notify();
}
#else // dont have strftime so we have to set it to hour:minut
// sprintf(time_string, "%d:%d", );
#endif // HAVE_STRFTIME
}
}
// Just change things that affect the size
void ClockTool::updateSizing() {
m_button.setBorderWidth(m_theme.border().width());
// resizes if new timeformat
update(0);
}
void ClockTool::reRender() {
if (m_pixmap)
m_screen.imageControl().removeImage(m_pixmap);
if (m_theme.texture().usePixmap()) {
m_pixmap = m_screen.imageControl().renderImage(width(), height(),
m_theme.texture(), orientation());
m_button.setBackgroundPixmap(m_pixmap);
} else {
m_pixmap = 0;
m_button.setBackgroundColor(m_theme.texture().color());
}
}
void ClockTool::renderTheme(unsigned char alpha) {
m_button.setAlpha(alpha);
m_button.setJustify(m_theme.justify());
reRender();
m_button.setBorderWidth(m_theme.border().width());
m_button.setBorderColor(m_theme.border().color());
m_button.clear();
}
void ClockTool::setOrientation(FbTk::Orientation orient) {
m_button.setOrientation(orient);
ToolbarItem::setOrientation(orient);
}
<|endoftext|> |
<commit_before>//
// Created by a1 on 16-11-2.
//
#include "encode.h"
static string encode_key_internal(const string& key, const string& field, uint16_t version);
static string encode_meta_val_internal(const char type, uint64_t length, uint16_t version, char del);
static uint64_t encodeScore(const double score);
string encode_meta_key(const Bytes& key){
string buf;
buf.append(1, 'M');
uint16_t slot = (uint16_t)keyHashSlot(key.data(), key.size());
slot = htobe16(slot);
buf.append((char *)&slot, sizeof(uint16_t));
buf.append(key.String());
return buf;
}
static string encode_key_internal(const string& key, const string& field, uint16_t version){
string buf;
buf.append(1, 'S');
uint16_t len = htobe16((uint16_t)key.size());
buf.append((char *)&len, sizeof(uint16_t));
buf.append(key);
version = htobe16(version);
buf.append((char *)&version, sizeof(uint16_t));
buf.append(field);
return buf;
}
string encode_hash_key(const Bytes& key, const Bytes& field, uint16_t version){
return encode_key_internal(key.String(), field.String(), version);
}
string encode_set_key(const Bytes& key, const Bytes& member, uint16_t version){
return encode_key_internal(key.String(), member.String(), version);
}
string encode_zset_key(const Bytes& key, const Bytes& member, uint16_t version){
return encode_key_internal(key.String(), member.String(), version);
}
static uint64_t encodeScore(const double score) {
int64_t iscore;
if (score < 0) {
iscore = (int64_t)(score * 100000LL - 0.5) + ZSET_SCORE_SHIFT;
} else {
iscore = (int64_t)(score * 100000LL + 0.5) + ZSET_SCORE_SHIFT;
}
return (uint64_t)(iscore);
}
string encode_zscore_key(const Bytes& key, const Bytes& member, double score, uint16_t version){
string buf;
buf.append(1, DataType::ZSCORE);
uint16_t len = htobe16((uint16_t)key.size());
buf.append((char *)&len, sizeof(uint16_t));
buf.append(key.data(), key.size());
version = htobe16(version);
buf.append((char *)&version, sizeof(uint16_t));
uint64_t new_score = encodeScore(score);
new_score = htobe64(new_score);
buf.append((char *)&new_score, sizeof(uint64_t));
buf.append(member.data(), member.size());
return buf;
}
string encode_list_key(const Bytes& key, uint64_t seq, uint16_t version){
string buf;
buf.append(1, 'S');
uint16_t len = htobe16((uint16_t)key.size());
buf.append((char *)&len, sizeof(uint16_t));
buf.append(key.String());
version = htobe16(version);
buf.append((char *)&version, sizeof(uint16_t));
seq = htobe64(seq);
buf.append((char *)&seq, sizeof(uint64_t));
return buf;
}
string encode_kv_val(const string& val, uint16_t version, char del){
string buf;
buf.append(1, DataType::KV);
version = htobe16(version);
buf.append((char *)&version, sizeof(uint16_t));
buf.append(1, del);
buf.append(val);
return buf;
}
static string encode_meta_val_internal(const char type, uint64_t length, uint16_t version, char del){
string buf;
buf.append(1, type);
version = htobe16(version);
buf.append((char *)&version, sizeof(uint16_t));
buf.append(1, del);
length = htobe64(length);
buf.append((char *)&length, sizeof(uint64_t));
return buf;
}
string encode_hash_meta_val(uint64_t length, uint16_t version, char del){
return encode_meta_val_internal(DataType::HSIZE, length, version, del);
}
string encode_set_meta_val(uint64_t length, uint16_t version, char del){
return encode_meta_val_internal(DataType::SSIZE, length, version, del);
}
string encode_zset_meta_val(uint64_t length, uint16_t version, char del){
return encode_meta_val_internal(DataType::ZSIZE, length, version, del);
}
string encode_list_meta_val(uint64_t length, uint64_t left, uint64_t right, uint16_t version, char del){
string buf;
buf.append(1, DataType::LSIZE);
version = htobe16(version);
buf.append((char *)&version, sizeof(uint16_t));
buf.append(1, del);
length = htobe64(length);
buf.append((char *)&length, sizeof(uint64_t));
left = htobe64(left);
buf.append((char *)&left, sizeof(uint64_t));
right = htobe64(right);
buf.append((char *)&right, sizeof(uint64_t));
return buf;
}
/*
* delete key
*/
string encode_delete_key(const Bytes& key, char key_type, uint16_t version){
string buf;
buf.append(1, KEY_DELETE_MASK);
uint16_t slot = (uint16_t)keyHashSlot(key.data(), key.size());
slot = htobe16(slot);
buf.append((char *)&slot, sizeof(uint16_t));
uint16_t len = htobe16((uint16_t)key.size());
buf.append((char *)&len, sizeof(uint16_t));
buf.append(key.String());
version = htobe16(version);
buf.append((char *)&version, sizeof(uint16_t));
buf.append(1, key_type);
return buf;
}
<commit_msg>encode_key_internal<commit_after>//
// Created by a1 on 16-11-2.
//
#include "encode.h"
static string encode_key_internal(char type, const string& key, const string& field, uint16_t version);
static string encode_meta_val_internal(const char type, uint64_t length, uint16_t version, char del);
static uint64_t encodeScore(const double score);
string encode_meta_key(const Bytes& key){
string buf;
buf.append(1, 'M');
uint16_t slot = (uint16_t)keyHashSlot(key.data(), key.size());
slot = htobe16(slot);
buf.append((char *)&slot, sizeof(uint16_t));
buf.append(key.String());
return buf;
}
static string encode_key_internal(char type, const string& key, const string& field, uint16_t version){
string buf;
buf.append(1, type);
uint16_t len = htobe16((uint16_t)key.size());
buf.append((char *)&len, sizeof(uint16_t));
buf.append(key);
version = htobe16(version);
buf.append((char *)&version, sizeof(uint16_t));
buf.append(field);
return buf;
}
string encode_hash_key(const Bytes& key, const Bytes& field, uint16_t version){
return encode_key_internal('S', key.String(), field.String(), version);
}
string encode_set_key(const Bytes& key, const Bytes& member, uint16_t version){
return encode_key_internal('S', key.String(), member.String(), version);
}
string encode_zset_key(const Bytes& key, const Bytes& member, uint16_t version){
return encode_key_internal('S', key.String(), member.String(), version);
}
static uint64_t encodeScore(const double score) {
int64_t iscore;
if (score < 0) {
iscore = (int64_t)(score * 100000LL - 0.5) + ZSET_SCORE_SHIFT;
} else {
iscore = (int64_t)(score * 100000LL + 0.5) + ZSET_SCORE_SHIFT;
}
return (uint64_t)(iscore);
}
string encode_zscore_key(const Bytes& key, const Bytes& member, double score, uint16_t version){
string buf;
buf.append(1, DataType::ZSCORE);
uint16_t len = htobe16((uint16_t)key.size());
buf.append((char *)&len, sizeof(uint16_t));
buf.append(key.data(), key.size());
version = htobe16(version);
buf.append((char *)&version, sizeof(uint16_t));
uint64_t new_score = encodeScore(score);
new_score = htobe64(new_score);
buf.append((char *)&new_score, sizeof(uint64_t));
buf.append(member.data(), member.size());
return buf;
}
string encode_list_key(const Bytes& key, uint64_t seq, uint16_t version){
string buf;
buf.append(1, 'S');
uint16_t len = htobe16((uint16_t)key.size());
buf.append((char *)&len, sizeof(uint16_t));
buf.append(key.String());
version = htobe16(version);
buf.append((char *)&version, sizeof(uint16_t));
seq = htobe64(seq);
buf.append((char *)&seq, sizeof(uint64_t));
return buf;
}
string encode_kv_val(const string& val, uint16_t version, char del){
string buf;
buf.append(1, DataType::KV);
version = htobe16(version);
buf.append((char *)&version, sizeof(uint16_t));
buf.append(1, del);
buf.append(val);
return buf;
}
static string encode_meta_val_internal(const char type, uint64_t length, uint16_t version, char del){
string buf;
buf.append(1, type);
version = htobe16(version);
buf.append((char *)&version, sizeof(uint16_t));
buf.append(1, del);
length = htobe64(length);
buf.append((char *)&length, sizeof(uint64_t));
return buf;
}
string encode_hash_meta_val(uint64_t length, uint16_t version, char del){
return encode_meta_val_internal(DataType::HSIZE, length, version, del);
}
string encode_set_meta_val(uint64_t length, uint16_t version, char del){
return encode_meta_val_internal(DataType::SSIZE, length, version, del);
}
string encode_zset_meta_val(uint64_t length, uint16_t version, char del){
return encode_meta_val_internal(DataType::ZSIZE, length, version, del);
}
string encode_list_meta_val(uint64_t length, uint64_t left, uint64_t right, uint16_t version, char del){
string buf;
buf.append(1, DataType::LSIZE);
version = htobe16(version);
buf.append((char *)&version, sizeof(uint16_t));
buf.append(1, del);
length = htobe64(length);
buf.append((char *)&length, sizeof(uint64_t));
left = htobe64(left);
buf.append((char *)&left, sizeof(uint64_t));
right = htobe64(right);
buf.append((char *)&right, sizeof(uint64_t));
return buf;
}
/*
* delete key
*/
string encode_delete_key(const Bytes& key, char key_type, uint16_t version){
string buf;
buf.append(1, KEY_DELETE_MASK);
uint16_t slot = (uint16_t)keyHashSlot(key.data(), key.size());
slot = htobe16(slot);
buf.append((char *)&slot, sizeof(uint16_t));
uint16_t len = htobe16((uint16_t)key.size());
buf.append((char *)&len, sizeof(uint16_t));
buf.append(key.String());
version = htobe16(version);
buf.append((char *)&version, sizeof(uint16_t));
buf.append(1, key_type);
return buf;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: TestPanel.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-16 19:15:40 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "TestPanel.hxx"
#include "taskpane/ScrollPanel.hxx"
#include "taskpane/TaskPaneControlFactory.hxx"
#include <vcl/lstbox.hxx>
#include <vcl/button.hxx>
namespace sd { namespace toolpanel {
/** This factory class is used to create instances of TestPanel. It can be
extended so that its constructor stores arguments that later are passed
to new TestPanel objects.
*/
class TestPanelFactory
: public ControlFactory
{
protected:
virtual TreeNode* InternalCreateControl (TreeNode* pTreeNode)
{
return new TestPanel (pTreeNode);
}
};
class Wrapper
: public TreeNode
{
public:
Wrapper (
TreeNode* pParent,
Size aPreferredSize,
::Window* pWrappedControl,
bool bIsResizable)
: TreeNode (pParent),
maPreferredSize(aPreferredSize),
mpWrappedControl(pWrappedControl),
mbIsResizable(bIsResizable)
{
mpWrappedControl->Show();
}
virtual ~Wrapper (void)
{
delete mpWrappedControl;
}
virtual Size GetPreferredSize (void)
{
return maPreferredSize;
}
virtual sal_Int32 GetPreferredWidth (sal_Int32 nHeigh)
{
return maPreferredSize.Width();
}
virtual sal_Int32 GetPreferredHeight (sal_Int32 nWidth)
{
return maPreferredSize.Height();
}
virtual ::Window* GetWindow (void)
{
return mpWrappedControl;
}
virtual bool IsResizable (void)
{
return mbIsResizable;
}
virtual bool IsExpandable (void) const
{
return false;
}
virtual bool IsExpanded (void) const
{
return true;
}
private:
Size maPreferredSize;
::Window* mpWrappedControl;
bool mbIsResizable;
};
TestPanel::TestPanel (TreeNode* pParent)
: SubToolPanel (pParent)
{
// Create a scrollable panel with two list boxes.
ScrollPanel* pScrollPanel = new ScrollPanel (this);
ListBox* pBox = new ListBox (pScrollPanel->GetWindow());
int i;
for (i=1; i<=20; i++)
{
XubString aString (XubString::CreateFromAscii("Text "));
aString.Append (XubString::CreateFromInt32(i));
aString.Append (XubString::CreateFromAscii("/20"));
pBox->InsertEntry (aString);
}
pScrollPanel->AddControl (
::std::auto_ptr<TreeNode>(new Wrapper (
pScrollPanel, Size (200,300), pBox, true)),
String::CreateFromAscii ("First ListBox"),
0);
pBox = new ListBox (pScrollPanel->GetWindow());
for (i=1; i<=20; i++)
{
XubString aString (XubString::CreateFromAscii("More Text "));
aString.Append (XubString::CreateFromInt32(i));
aString.Append (XubString::CreateFromAscii("/20"));
pBox->InsertEntry (aString);
}
pScrollPanel->AddControl (
::std::auto_ptr<TreeNode>(new Wrapper (
pScrollPanel, Size (200,300), pBox, true)),
String::CreateFromAscii ("Second ListBox"),
0);
AddControl (::std::auto_ptr<TreeNode>(pScrollPanel));
// Add a fixed size button.
Button* pButton = new OKButton (this);
AddControl (
::std::auto_ptr<TreeNode>(new Wrapper (
this, Size (100,30), pButton, false)),
String::CreateFromAscii ("Button Area"),
0);
}
TestPanel::~TestPanel (void)
{
}
std::auto_ptr<ControlFactory> TestPanel::CreateControlFactory (void)
{
return std::auto_ptr<ControlFactory>(new TestPanelFactory());
}
} } // end of namespace ::sd::toolpanel
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.6.38); FILE MERGED 2006/11/22 12:42:15 cl 1.6.38.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: TestPanel.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kz $ $Date: 2006-12-12 18:44:19 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "TestPanel.hxx"
#include "taskpane/ScrollPanel.hxx"
#include "taskpane/TaskPaneControlFactory.hxx"
#include <vcl/lstbox.hxx>
#include <vcl/button.hxx>
namespace sd { namespace toolpanel {
/** This factory class is used to create instances of TestPanel. It can be
extended so that its constructor stores arguments that later are passed
to new TestPanel objects.
*/
class TestPanelFactory
: public ControlFactory
{
protected:
virtual TreeNode* InternalCreateControl (TreeNode* pTreeNode)
{
return new TestPanel (pTreeNode);
}
};
class Wrapper
: public TreeNode
{
public:
Wrapper (
TreeNode* pParent,
Size aPreferredSize,
::Window* pWrappedControl,
bool bIsResizable)
: TreeNode (pParent),
maPreferredSize(aPreferredSize),
mpWrappedControl(pWrappedControl),
mbIsResizable(bIsResizable)
{
mpWrappedControl->Show();
}
virtual ~Wrapper (void)
{
delete mpWrappedControl;
}
virtual Size GetPreferredSize (void)
{
return maPreferredSize;
}
virtual sal_Int32 GetPreferredWidth (sal_Int32 )
{
return maPreferredSize.Width();
}
virtual sal_Int32 GetPreferredHeight (sal_Int32 )
{
return maPreferredSize.Height();
}
virtual ::Window* GetWindow (void)
{
return mpWrappedControl;
}
virtual bool IsResizable (void)
{
return mbIsResizable;
}
virtual bool IsExpandable (void) const
{
return false;
}
virtual bool IsExpanded (void) const
{
return true;
}
private:
Size maPreferredSize;
::Window* mpWrappedControl;
bool mbIsResizable;
};
TestPanel::TestPanel (TreeNode* pParent)
: SubToolPanel (pParent)
{
// Create a scrollable panel with two list boxes.
ScrollPanel* pScrollPanel = new ScrollPanel (this);
ListBox* pBox = new ListBox (pScrollPanel->GetWindow());
int i;
for (i=1; i<=20; i++)
{
XubString aString (XubString::CreateFromAscii("Text "));
aString.Append (XubString::CreateFromInt32(i));
aString.Append (XubString::CreateFromAscii("/20"));
pBox->InsertEntry (aString);
}
pScrollPanel->AddControl (
::std::auto_ptr<TreeNode>(new Wrapper (
pScrollPanel, Size (200,300), pBox, true)),
String::CreateFromAscii ("First ListBox"),
0);
pBox = new ListBox (pScrollPanel->GetWindow());
for (i=1; i<=20; i++)
{
XubString aString (XubString::CreateFromAscii("More Text "));
aString.Append (XubString::CreateFromInt32(i));
aString.Append (XubString::CreateFromAscii("/20"));
pBox->InsertEntry (aString);
}
pScrollPanel->AddControl (
::std::auto_ptr<TreeNode>(new Wrapper (
pScrollPanel, Size (200,300), pBox, true)),
String::CreateFromAscii ("Second ListBox"),
0);
AddControl (::std::auto_ptr<TreeNode>(pScrollPanel));
// Add a fixed size button.
Button* pButton = new OKButton (this);
AddControl (
::std::auto_ptr<TreeNode>(new Wrapper (
this, Size (100,30), pButton, false)),
String::CreateFromAscii ("Button Area"),
0);
}
TestPanel::~TestPanel (void)
{
}
std::auto_ptr<ControlFactory> TestPanel::CreateControlFactory (void)
{
return std::auto_ptr<ControlFactory>(new TestPanelFactory());
}
} } // end of namespace ::sd::toolpanel
<|endoftext|> |
<commit_before><commit_msg>Add test for re-grouping of formulas in DeleteRow().<commit_after><|endoftext|> |
<commit_before>// Copyright © 2014 German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
//
// Author: Christian Kellner <kellner@bio.lmu.de>
#include <nix/DataType.hpp>
#include <string>
#include <stdexcept>
#include <map>
#include <algorithm>
namespace nix {
std::string data_type_to_string(DataType dtype) {
std::string str;
switch(dtype) {
case DataType::Bool: str = "Bool"; break;
case DataType::Char: str = "Char"; break;
case DataType::Float: str = "Float"; break;
case DataType::Double: str = "Double"; break;
case DataType::Int8: str = "Int8"; break;
case DataType::Int16: str = "Int16"; break;
case DataType::Int32: str = "Int32"; break;
case DataType::Int64: str = "Int64"; break;
case DataType::UInt8: str = "UInt8"; break;
case DataType::UInt16: str = "UInt16"; break;
case DataType::UInt32: str = "UInt32"; break;
case DataType::UInt64: str = "UInt64"; break;
case DataType::String: str = "String"; break;
case DataType::Nothing: str = "Nothing"; break;
default:
str = "FIXME";
}
return str;
}
DataType string_to_data_type(std::string dtype) {
struct data_type_map : public std::map<std::string, DataType> {
data_type_map() {
(*this)["bool"] = DataType::Bool;
(*this)["char"] = DataType::Char;
(*this)["float"] = DataType::Float;
(*this)["single"] = DataType::Float;
(*this)["double"] = DataType::Double;
(*this)["int8"] = DataType::Int8;
(*this)["int16"] = DataType::Int16;
(*this)["int32"] = DataType::Int32;
(*this)["int64"] = DataType::Int64;
(*this)["uint8"] = DataType::UInt8;
(*this)["uint16"] = DataType::UInt16;
(*this)["uint32"] = DataType::UInt32;
(*this)["uint64"] = DataType::UInt64;
(*this)["string"] = DataType::String;
(*this)["nothing"] = DataType::Nothing;
}
};
static data_type_map dt;
std::string dtype_l = dtype;
std::transform(dtype_l.begin(), dtype_l.end(), dtype_l.begin(), ::tolower);
return dt[dtype];
}
std::ostream &operator<<(std::ostream &out, const DataType dtype) {
out << data_type_to_string(dtype);
return out;
}
size_t data_type_to_size(DataType dtype) {
switch(dtype) {
case DataType::Bool:
return sizeof(bool);
case DataType::Int8:
case DataType::UInt8:
return 1;
case DataType::Int16:
case DataType::UInt16:
return 2;
case DataType::Int32:
case DataType::UInt32:
case DataType::Float:
return 4;
case DataType::Int64:
case DataType::UInt64:
case DataType::Double:
return 8;
//strings are char *, but not sure that is the correct thing to do here
case DataType::String:
return sizeof(char *);
default:
throw std::invalid_argument("Unkown DataType");
}
}
}
<commit_msg>changed data type struct to just map<commit_after>// Copyright © 2014 German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
//
// Author: Christian Kellner <kellner@bio.lmu.de>
#include <nix/DataType.hpp>
#include <string>
#include <stdexcept>
#include <map>
#include <algorithm>
namespace nix {
std::string data_type_to_string(DataType dtype) {
std::string str;
switch(dtype) {
case DataType::Bool: str = "Bool"; break;
case DataType::Char: str = "Char"; break;
case DataType::Float: str = "Float"; break;
case DataType::Double: str = "Double"; break;
case DataType::Int8: str = "Int8"; break;
case DataType::Int16: str = "Int16"; break;
case DataType::Int32: str = "Int32"; break;
case DataType::Int64: str = "Int64"; break;
case DataType::UInt8: str = "UInt8"; break;
case DataType::UInt16: str = "UInt16"; break;
case DataType::UInt32: str = "UInt32"; break;
case DataType::UInt64: str = "UInt64"; break;
case DataType::String: str = "String"; break;
case DataType::Nothing: str = "Nothing"; break;
default:
str = "FIXME";
}
return str;
}
DataType string_to_data_type(std::string dtype) {
static std::map<std::string, DataType> type_map = {
{"bool", DataType::Bool},
{"char", DataType::Char},
{"float", DataType::Float},
{"single", DataType::Float},
{"double", DataType::Double},
{"int8", DataType::Int8},
{"int16", DataType::Int16},
{"int32", DataType::Int32},
{"int64", DataType::Int64},
{"uint8", DataType::UInt8},
{"uint16", DataType::UInt16},
{"uint32", DataType::UInt32},
{"uint64", DataType::UInt64},
{"string", DataType::String},
{"nothing", DataType::Nothing}
};
std::string dtype_l = dtype;
std::transform(dtype_l.begin(), dtype_l.end(), dtype_l.begin(), ::tolower);
return type_map[dtype];
}
std::ostream &operator<<(std::ostream &out, const DataType dtype) {
out << data_type_to_string(dtype);
return out;
}
size_t data_type_to_size(DataType dtype) {
switch(dtype) {
case DataType::Bool:
return sizeof(bool);
case DataType::Int8:
case DataType::UInt8:
return 1;
case DataType::Int16:
case DataType::UInt16:
return 2;
case DataType::Int32:
case DataType::UInt32:
case DataType::Float:
return 4;
case DataType::Int64:
case DataType::UInt64:
case DataType::Double:
return 8;
//strings are char *, but not sure that is the correct thing to do here
case DataType::String:
return sizeof(char *);
default:
throw std::invalid_argument("Unkown DataType");
}
}
}
<|endoftext|> |
<commit_before>#include "variable_tests.h"
#include <gtest/gtest.h>
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(VariableTests, constructor) {
cyclopts::Variable::Bound lbound(cyclopts::Variable::NEG_INF);
cyclopts::Variable::Bound ubound(cyclopts::Variable::FINITE);
cyclopts::Variable::VarType type(cyclopts::Variable::LINEAR);
cyclopts::Variable::Variable var(lbound, ubound, type);
EXPECT_EQ(var.lbound(), lbound);
EXPECT_EQ(var.ubound(), ubound);
EXPECT_EQ(var.type(), type);
}
<commit_msg>test update. tag: move and squash<commit_after>#include "variable_tests.h"
#include <gtest/gtest.h>
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(VariableTests, constructor) {
cyclopts::Variable::Bound lbound(cyclopts::Variable::NEG_INF);
cyclopts::Variable::Bound ubound(cyclopts::Variable::FINITE);
cyclopts::Variable::VarType type(cyclopts::Variable::LINEAR);
cyclopts::Variable var(lbound, ubound, type);
EXPECT_EQ(var.lbound(), lbound);
EXPECT_EQ(var.ubound(), ubound);
EXPECT_EQ(var.type(), type);
}
<|endoftext|> |
<commit_before>#define _BSD_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ptrace.h>
#include <unistd.h>
#include "ptbox.h"
pt_debugger::pt_debugger() : on_return_callback(NULL) {}
bool has_null(char *buf, unsigned long size) {
for (unsigned long i = 0; i < size; ++i) {
if (buf[i] == '\0')
return true;
}
return false;
}
void pt_debugger::set_process(pt_process *proc) {
process = proc;
}
void pt_debugger::new_process() {}
void pt_debugger::settid(pid_t tid) {
this->tid = tid;
#if defined(__FreeBSD__)
reg bsd_regs;
ptrace(PT_GETREGS, tid, &bsd_regs, 0);
map_regs_to_linux(&bsd_reg, &bsd_converted_regs);
#endif
}
long pt_debugger::peek_reg(int idx) {
#if defined(__FreeBSD__)
return (int*)((char *)&bsd_converted_regs + idx * sizeof(long));
#else
return ptrace(PTRACE_PEEKUSER, tid, sizeof(long) * idx, 0);
#endif
}
void pt_debugger::poke_reg(int idx, long data) {
#if defined(__FreeBSD__)
*(int*)((char *)&bsd_converted_regs + idx * sizeof(long)) = (int) data;
reg bsd_regs;
map_regs_from_linux(&bsd_regs, &bsd_converted_regs);
ptrace(PT_SETREGS, tid, &bsd_regs, 0);
#else
ptrace(PTRACE_POKEUSER, tid, sizeof(long) * idx, data);
#endif
}
char *pt_debugger::readstr(unsigned long addr, size_t max_size) {
size_t size = 4096, read = 0;
char *buf = (char *) malloc(size);
union {
long val;
char byte[sizeof(long)];
} data;
while (true) {
if (read + sizeof(long) > size) {
if (max_size && size >= max_size) {
buf[max_size-1] = 0;
break;
}
size += 4096;
if (max_size && size > max_size)
size = max_size;
void *nbuf = realloc(buf, size);
if (!nbuf) {
buf[size-4097] = 0;
break;
}
buf = (char *) nbuf;
}
#if defined(__FreeBSD__)
data.val = ptrace(PT_READ_D, tid, addr + read, 0);
#else
data.val = ptrace(PTRACE_PEEKDATA, tid, addr + read, NULL);
#endif
memcpy(buf + read, data.byte, sizeof(long));
if (has_null(data.byte, sizeof(long)))
break;
read += sizeof(long);
}
return buf;
}
void pt_debugger::freestr(char *buf) {
free(buf);
}
pt_debugger::~pt_debugger() {}
<commit_msg>Cast to caddr_t religiously; #192<commit_after>#define _BSD_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ptrace.h>
#include <unistd.h>
#include "ptbox.h"
pt_debugger::pt_debugger() : on_return_callback(NULL) {}
bool has_null(char *buf, unsigned long size) {
for (unsigned long i = 0; i < size; ++i) {
if (buf[i] == '\0')
return true;
}
return false;
}
void pt_debugger::set_process(pt_process *proc) {
process = proc;
}
void pt_debugger::new_process() {}
void pt_debugger::settid(pid_t tid) {
this->tid = tid;
#if defined(__FreeBSD__)
reg bsd_regs;
ptrace(PT_GETREGS, tid, (caddr_t) &bsd_regs, 0);
map_regs_to_linux(&bsd_reg, &bsd_converted_regs);
#endif
}
long pt_debugger::peek_reg(int idx) {
#if defined(__FreeBSD__)
return (int*)((char *)&bsd_converted_regs + idx * sizeof(long));
#else
return ptrace(PTRACE_PEEKUSER, tid, sizeof(long) * idx, 0);
#endif
}
void pt_debugger::poke_reg(int idx, long data) {
#if defined(__FreeBSD__)
*(int*)((char *)&bsd_converted_regs + idx * sizeof(long)) = (int) data;
reg bsd_regs;
map_regs_from_linux(&bsd_regs, &bsd_converted_regs);
ptrace(PT_SETREGS, tid, (caddr_t) &bsd_regs, 0);
#else
ptrace(PTRACE_POKEUSER, tid, sizeof(long) * idx, data);
#endif
}
char *pt_debugger::readstr(unsigned long addr, size_t max_size) {
size_t size = 4096, read = 0;
char *buf = (char *) malloc(size);
union {
long val;
char byte[sizeof(long)];
} data;
while (true) {
if (read + sizeof(long) > size) {
if (max_size && size >= max_size) {
buf[max_size-1] = 0;
break;
}
size += 4096;
if (max_size && size > max_size)
size = max_size;
void *nbuf = realloc(buf, size);
if (!nbuf) {
buf[size-4097] = 0;
break;
}
buf = (char *) nbuf;
}
#if defined(__FreeBSD__)
data.val = ptrace(PT_READ_D, tid, (caddr_t) (addr + read), 0);
#else
data.val = ptrace(PTRACE_PEEKDATA, tid, addr + read, NULL);
#endif
memcpy(buf + read, data.byte, sizeof(long));
if (has_null(data.byte, sizeof(long)))
break;
read += sizeof(long);
}
return buf;
}
void pt_debugger::freestr(char *buf) {
free(buf);
}
pt_debugger::~pt_debugger() {}
<|endoftext|> |
<commit_before>/**
* The MIT License (MIT)
*
* Copyright (c) 2017 Ruben Van Boxem
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
**/
#include "test.h++"
#include "core/application.h++"
#include <thread>
namespace
{
using skui::test::check;
using skui::test::require;
void test_arguments()
{
const auto& arguments = skui::core::application::instance().commandline_arguments;
require(arguments.size() == 1, "correct number of arguments.");
check(arguments[0] == "skui is awesome", "arguments passed correctly.");
}
void test_execute_and_quit()
{
auto app = &skui::core::application::instance();
constexpr int exit_code = 1;
int return_value = 0;
std::thread t([app, &return_value] { return_value = app->execute(); });
app->quit(exit_code);
t.join();
check(return_value = exit_code, "application::execute returns exit code passed to quit().");
}
}
int main(int argc, char* argv[])
{
const skui::core::application app(argc, argv);
test_arguments();
test_execute_and_quit();
return skui::test::exit_code;
}
<commit_msg>Fix typo in test.<commit_after>/**
* The MIT License (MIT)
*
* Copyright (c) 2017 Ruben Van Boxem
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
**/
#include "test.h++"
#include "core/application.h++"
#include <thread>
namespace
{
using skui::test::check;
using skui::test::require;
void test_arguments()
{
const auto& arguments = skui::core::application::instance().commandline_arguments;
require(arguments.size() == 1, "correct number of arguments.");
check(arguments[0] == "skui is awesome", "arguments passed correctly.");
}
void test_execute_and_quit()
{
auto app = &skui::core::application::instance();
constexpr int exit_code = 1;
int return_value = 0;
std::thread t([app, &return_value] { return_value = app->execute(); });
app->quit(exit_code);
t.join();
check(return_value == exit_code, "application::execute returns exit code passed to quit().");
}
}
int main(int argc, char* argv[])
{
const skui::core::application app(argc, argv);
test_arguments();
test_execute_and_quit();
return skui::test::exit_code;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2007, 2008, 2009, 2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file urbi/uvalue.hh
#ifndef URBI_UVALUE_HH
# define URBI_UVALUE_HH
# include <libport/warning-push.hh>
# include <vector>
# include <libport/hash.hh>
# include <libport/preproc.hh>
# include <libport/traits.hh>
# include <libport/ufloat.h>
# include <urbi/fwd.hh>
# include <urbi/export.hh>
# include <urbi/ubinary.hh>
namespace urbi
{
/// If a kernel version was associated to this stream, its value.
URBI_SDK_API
int& kernelMajor(std::ostream& o);
// UValue and other related types
/// Possible value types a UValue can contain.
enum UDataType
{
DATA_BINARY,
DATA_DICTIONARY,
DATA_DOUBLE,
DATA_LIST,
DATA_OBJECT,
DATA_STRING,
DATA_SLOTNAME,
DATA_VOID
};
/*--------.
| UList. |
`--------*/
/// Class storing URBI List type
class URBI_SDK_API UList
{
public:
UList();
UList(const UList &b);
~UList();
UList& operator=(const UList &b);
// Assign a container to the UList
template<typename T>
UList& operator=(const T& container);
UList& operator=(UVar& v);
// Transform the UList to a container.
template<typename T>
T as();
// Append an element to the end.
template<typename T>
UList&
push_back(const T& v);
void pop_back();
UValue& front();
UValue& operator[](size_t i);
const UValue& operator[](size_t i) const;
size_t size() const;
void setOffset(size_t n);
std::ostream& print(std::ostream& o) const;
// The actual contents.
std::vector<UValue*> array;
private:
void clear();
size_t offset;
};
URBI_SDK_API
std::ostream& operator<< (std::ostream& o, const UList& t);
/*--------------.
| UDictionary. |
`--------------*/
typedef boost::unordered_map<std::string, UValue> UDictionary;
/*--------------.
| UNamedValue. |
`--------------*/
class URBI_SDK_API UNamedValue
{
public:
UNamedValue(const std::string& n = "", UValue* v = 0);
// Used on errors.
static UNamedValue& error();
std::string name;
UValue* val;
};
/*----------------.
| UObjectStruct. |
`----------------*/
class URBI_SDK_API UObjectStruct
{
public:
UObjectStruct();
UObjectStruct(const UObjectStruct &b);
UObjectStruct& operator=(const UObjectStruct &b);
~UObjectStruct();
/// Return UValue::error() on errors.
UValue& operator[](const std::string& s);
/// Return UNamedValue::error() on errors.
const UNamedValue& operator[](size_t i) const;
UNamedValue& operator [](size_t i);
size_t size() const;
std::ostream& print(std::ostream& o) const;
std::string refName;
std::vector<UNamedValue> array;
};
URBI_SDK_API
std::ostream& operator<< (std::ostream& o, const UObjectStruct& t);
/*---------.
| UValue. |
`---------*/
/** Container for a value that handles all types known to URBI.
*/
class URBI_SDK_API UValue
{
public:
UDataType type;
ufloat val; ///< value if of type DATA_DOUBLE
union
{
std::string* stringValue; ///< value if of type DATA_STRING
UBinary* binary; ///< value if of type DATA_BINARY
UList* list; ///< value if of type DATA_LIST
UDictionary* dictionary; ///< value if of type DATA_DICTIONARY
UObjectStruct* object; ///< value if of type DATA_OBJ
void* storage; ///< internal
};
UValue();
UValue(const UValue&);
~UValue();
UValue& operator=(const UValue&);
/// Setter. If copy is false, binary data if present is not copied.
/// This is dangerous, as the user must ensure that the source UValue
/// lives longer than this one.
UValue& set(const UValue&, bool copy=true);
/// Delete content and reset type to void.
void clear();
/// A specific UValue used when we want to return an error.
/// For instance, out-of-bound access returns this object.
static UValue& error();
/// We use an operator , that behaves like an assignment. The
/// only difference is when the rhs is void, in which case it is
/// the regular comma which is used. This allows to write "uval,
/// expr" to mean "compute expr and assign its result to uval,
/// unless expr is void".
UValue& operator, (const UValue &b);
/// Return a legible definition of UDataType
const char* format_string() const;
#define CTOR_AND_ASSIGN_AND_COMMA(Type) \
explicit UValue(Type, bool copy=true); \
UValue& operator=(Type); \
UValue& operator,(Type rhs);
// Types convertibles to DATA_DOUBLE
#define URBI_DERIVED_NUMERIC_TYPES \
LIBPORT_LIST(int, long, unsigned int, unsigned long, \
unsigned long long, long long,)
#define URBI_NUMERIC_TYPES \
LIBPORT_LIST(ufloat, int, long, unsigned int, unsigned long, \
unsigned long long, long long,)
// Types convertibles to DATA_STRING
#define URBI_STRING_TYPES \
LIBPORT_LIST(const char*, const void*, const std::string&,)
#define URBI_MISC_TYPES \
LIBPORT_LIST(const UBinary&, const UList&, const UDictionary&, \
const UObjectStruct&, const USound&, const UImage&,)
# ifndef SWIG
LIBPORT_LIST_APPLY(CTOR_AND_ASSIGN_AND_COMMA, URBI_NUMERIC_TYPES)
LIBPORT_LIST_APPLY(CTOR_AND_ASSIGN_AND_COMMA, URBI_STRING_TYPES)
LIBPORT_LIST_APPLY(CTOR_AND_ASSIGN_AND_COMMA, URBI_MISC_TYPES)
# else
// UFloats.
CTOR_AND_ASSIGN_AND_COMMA(ufloat);
CTOR_AND_ASSIGN_AND_COMMA(int);
CTOR_AND_ASSIGN_AND_COMMA(long);
CTOR_AND_ASSIGN_AND_COMMA(unsigned int);
CTOR_AND_ASSIGN_AND_COMMA(unsigned long);
CTOR_AND_ASSIGN_AND_COMMA(unsigned long long);
CTOR_AND_ASSIGN_AND_COMMA(long long);
// Strings.
CTOR_AND_ASSIGN_AND_COMMA(const char*);
CTOR_AND_ASSIGN_AND_COMMA(const void*);
CTOR_AND_ASSIGN_AND_COMMA(const std::string&);
// Others.
CTOR_AND_ASSIGN_AND_COMMA(const UBinary&);
CTOR_AND_ASSIGN_AND_COMMA(const UList&);
CTOR_AND_ASSIGN_AND_COMMA(const UDictionary&);
CTOR_AND_ASSIGN_AND_COMMA(const UObjectStruct&);
CTOR_AND_ASSIGN_AND_COMMA(const USound&);
CTOR_AND_ASSIGN_AND_COMMA(const UImage&);
# endif
#undef CTOR_AND_ASSIGN_AND_COMMA
#define CAST_OPERATOR(Type) \
operator Type() const;
# ifndef SWIG
LIBPORT_LIST_APPLY(CAST_OPERATOR, URBI_NUMERIC_TYPES)
# else
operator ufloat() const;
operator std::string() const;
operator int() const;
operator unsigned int() const;
operator long() const;
operator unsigned long() const;
operator bool() const;
# endif
#undef CAST_OPERATOR
#ifdef DOXYGEN
// Doxygens needs a prototype for ufloat.
operator ufloat() const;
#endif
operator std::string() const;
operator bool() const;
/// Accessor. Gives us an implicit operator UBinary() const
operator const UBinary&() const;
/// Deep copy.
operator UList() const;
/// Deep copy.
operator UDictionary() const;
/// Shallow copy.
operator UImage() const;
/// Shallow copy.
operator USound() const;
/// This operator does nothing, but helps with the previous operator,.
/// Indeed, when writing "uval, void_expr", the compiler complains
/// about uval being evaluated for nothing. Let's have it believe
/// we're doing something...
UValue& operator()();
/// Parse an uvalue in current message+pos, returns pos of end of
/// match -pos of error if error.
int parse(const char* message,
int pos,
const binaries_type& bins,
binaries_type::const_iterator& binpos);
/// Print itself on \c s, and return it.
std::ostream& print(std::ostream& s) const;
// Huge hack.
static const bool copy = true;
};
inline
std::ostream&
operator<<(std::ostream& s, const UValue& v);
inline
std::ostream&
operator<<(std::ostream& s, const UDictionary& d);
/*----------.
| Casters. |
`----------*/
// For each Type, define an operator() that casts its UValue&
// argument into Type. We need partial specialization.
template <typename Type>
struct uvalue_caster
{
};
// T -> UVar& if T = UVar
// T -> T otherwise.
template <typename T>
struct uvar_ref_traits
{
typedef T type;
};
template <>
struct uvar_ref_traits<UVar>
{
typedef UVar& type;
};
// Run the uvalue_caster<Type> on v.
/* NM: Why exactly are we moving the const away?
* I'm dropping it for UValue as it makes unnecessary copy.
*/
template<typename T> struct uvalue_cast_return_type
{
typedef typename libport::traits::remove_reference<T>::type type;
};
template<> struct uvalue_cast_return_type<const UValue&>
{
typedef const UValue& type;
};
template <typename Type>
typename uvar_ref_traits<typename uvalue_cast_return_type<Type>::type>::type
uvalue_cast (UValue& v);
} // namespace urbi
#define SYNCLINE_PUSH() \
"//#push " BOOST_PP_STRINGIZE(__LINE__) " \"" __FILE__ "\"\n"
#define SYNCLINE_POP() \
"//#pop\n"
#define SYNCLINE_WRAP(...) \
SYNCLINE_PUSH() \
__VA_ARGS__ \
"\n" \
SYNCLINE_POP()
#define URBI_STRUCT_CAST_FIELD(_, cname, field) \
if (!libport::mhas(dict, BOOST_PP_STRINGIZE(field))) \
GD_WARN("Serialized data for " #cname "is missing field" \
BOOST_PP_STRINGIZE(field)); \
else \
{ \
uvalue_cast_bounce(res.field, dict[BOOST_PP_STRINGIZE(field)]); \
}
#define URBI_STRUCT_BCAST_FIELD(_, cname, field) \
dict[BOOST_PP_STRINGIZE(field)], c.field;
#define URBI_REGISTER_STRUCT(cname, ...) \
namespace urbi { \
template<> struct uvalue_caster<cname> \
{ \
cname operator()(UValue& v) \
{ \
if (v.type != DATA_DICTIONARY) \
throw std::runtime_error("invalid cast to " #cname "from " \
+ string_cast(v)); \
UDictionary& dict = *v.dictionary; \
cname res; \
LIBPORT_VAARGS_APPLY(URBI_STRUCT_CAST_FIELD, cname, __VA_ARGS__); \
return res; \
} \
}; \
UValue& operator,(UValue& v, const cname &c) \
{ \
v = UDictionary(); \
UDictionary& dict = *v.dictionary; \
dict["$sn"] = BOOST_PP_STRINGIZE(cname); \
LIBPORT_VAARGS_APPLY(URBI_STRUCT_BCAST_FIELD, cname, __VA_ARGS__); \
return v; \
} \
}
/** Packed data structure.
* This template class behaves exactly as a std::vector, except it gets
* serialized efficiently in a Binary, whereas std::vector is converted in
* an urbiscript list.
*/
template<typename T> class UPackedData: public std::vector<T>
{
public:
UPackedData() {};
UPackedData(const std::vector<T>& src): std::vector<T>(src) {};
template<typename I> UPackedData(I begin, I end):std::vector<T>(begin, end){};
};
# include <urbi/uvalue.hxx>
# include <libport/warning-pop.hh>
#endif // ! URBI_UVALUE_HH
<commit_msg>Small Struct: Fix a warning.<commit_after>/*
* Copyright (C) 2007, 2008, 2009, 2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file urbi/uvalue.hh
#ifndef URBI_UVALUE_HH
# define URBI_UVALUE_HH
# include <libport/warning-push.hh>
# include <vector>
# include <libport/hash.hh>
# include <libport/preproc.hh>
# include <libport/traits.hh>
# include <libport/ufloat.h>
# include <urbi/fwd.hh>
# include <urbi/export.hh>
# include <urbi/ubinary.hh>
namespace urbi
{
/// If a kernel version was associated to this stream, its value.
URBI_SDK_API
int& kernelMajor(std::ostream& o);
// UValue and other related types
/// Possible value types a UValue can contain.
enum UDataType
{
DATA_BINARY,
DATA_DICTIONARY,
DATA_DOUBLE,
DATA_LIST,
DATA_OBJECT,
DATA_STRING,
DATA_SLOTNAME,
DATA_VOID
};
/*--------.
| UList. |
`--------*/
/// Class storing URBI List type
class URBI_SDK_API UList
{
public:
UList();
UList(const UList &b);
~UList();
UList& operator=(const UList &b);
// Assign a container to the UList
template<typename T>
UList& operator=(const T& container);
UList& operator=(UVar& v);
// Transform the UList to a container.
template<typename T>
T as();
// Append an element to the end.
template<typename T>
UList&
push_back(const T& v);
void pop_back();
UValue& front();
UValue& operator[](size_t i);
const UValue& operator[](size_t i) const;
size_t size() const;
void setOffset(size_t n);
std::ostream& print(std::ostream& o) const;
// The actual contents.
std::vector<UValue*> array;
private:
void clear();
size_t offset;
};
URBI_SDK_API
std::ostream& operator<< (std::ostream& o, const UList& t);
/*--------------.
| UDictionary. |
`--------------*/
typedef boost::unordered_map<std::string, UValue> UDictionary;
/*--------------.
| UNamedValue. |
`--------------*/
class URBI_SDK_API UNamedValue
{
public:
UNamedValue(const std::string& n = "", UValue* v = 0);
// Used on errors.
static UNamedValue& error();
std::string name;
UValue* val;
};
/*----------------.
| UObjectStruct. |
`----------------*/
class URBI_SDK_API UObjectStruct
{
public:
UObjectStruct();
UObjectStruct(const UObjectStruct &b);
UObjectStruct& operator=(const UObjectStruct &b);
~UObjectStruct();
/// Return UValue::error() on errors.
UValue& operator[](const std::string& s);
/// Return UNamedValue::error() on errors.
const UNamedValue& operator[](size_t i) const;
UNamedValue& operator [](size_t i);
size_t size() const;
std::ostream& print(std::ostream& o) const;
std::string refName;
std::vector<UNamedValue> array;
};
URBI_SDK_API
std::ostream& operator<< (std::ostream& o, const UObjectStruct& t);
/*---------.
| UValue. |
`---------*/
/** Container for a value that handles all types known to URBI.
*/
class URBI_SDK_API UValue
{
public:
UDataType type;
ufloat val; ///< value if of type DATA_DOUBLE
union
{
std::string* stringValue; ///< value if of type DATA_STRING
UBinary* binary; ///< value if of type DATA_BINARY
UList* list; ///< value if of type DATA_LIST
UDictionary* dictionary; ///< value if of type DATA_DICTIONARY
UObjectStruct* object; ///< value if of type DATA_OBJ
void* storage; ///< internal
};
UValue();
UValue(const UValue&);
~UValue();
UValue& operator=(const UValue&);
/// Setter. If copy is false, binary data if present is not copied.
/// This is dangerous, as the user must ensure that the source UValue
/// lives longer than this one.
UValue& set(const UValue&, bool copy=true);
/// Delete content and reset type to void.
void clear();
/// A specific UValue used when we want to return an error.
/// For instance, out-of-bound access returns this object.
static UValue& error();
/// We use an operator , that behaves like an assignment. The
/// only difference is when the rhs is void, in which case it is
/// the regular comma which is used. This allows to write "uval,
/// expr" to mean "compute expr and assign its result to uval,
/// unless expr is void".
UValue& operator, (const UValue &b);
/// Return a legible definition of UDataType
const char* format_string() const;
#define CTOR_AND_ASSIGN_AND_COMMA(Type) \
explicit UValue(Type, bool copy=true); \
UValue& operator=(Type); \
UValue& operator,(Type rhs);
// Types convertibles to DATA_DOUBLE
#define URBI_DERIVED_NUMERIC_TYPES \
LIBPORT_LIST(int, long, unsigned int, unsigned long, \
unsigned long long, long long,)
#define URBI_NUMERIC_TYPES \
LIBPORT_LIST(ufloat, int, long, unsigned int, unsigned long, \
unsigned long long, long long,)
// Types convertibles to DATA_STRING
#define URBI_STRING_TYPES \
LIBPORT_LIST(const char*, const void*, const std::string&,)
#define URBI_MISC_TYPES \
LIBPORT_LIST(const UBinary&, const UList&, const UDictionary&, \
const UObjectStruct&, const USound&, const UImage&,)
# ifndef SWIG
LIBPORT_LIST_APPLY(CTOR_AND_ASSIGN_AND_COMMA, URBI_NUMERIC_TYPES)
LIBPORT_LIST_APPLY(CTOR_AND_ASSIGN_AND_COMMA, URBI_STRING_TYPES)
LIBPORT_LIST_APPLY(CTOR_AND_ASSIGN_AND_COMMA, URBI_MISC_TYPES)
# else
// UFloats.
CTOR_AND_ASSIGN_AND_COMMA(ufloat);
CTOR_AND_ASSIGN_AND_COMMA(int);
CTOR_AND_ASSIGN_AND_COMMA(long);
CTOR_AND_ASSIGN_AND_COMMA(unsigned int);
CTOR_AND_ASSIGN_AND_COMMA(unsigned long);
CTOR_AND_ASSIGN_AND_COMMA(unsigned long long);
CTOR_AND_ASSIGN_AND_COMMA(long long);
// Strings.
CTOR_AND_ASSIGN_AND_COMMA(const char*);
CTOR_AND_ASSIGN_AND_COMMA(const void*);
CTOR_AND_ASSIGN_AND_COMMA(const std::string&);
// Others.
CTOR_AND_ASSIGN_AND_COMMA(const UBinary&);
CTOR_AND_ASSIGN_AND_COMMA(const UList&);
CTOR_AND_ASSIGN_AND_COMMA(const UDictionary&);
CTOR_AND_ASSIGN_AND_COMMA(const UObjectStruct&);
CTOR_AND_ASSIGN_AND_COMMA(const USound&);
CTOR_AND_ASSIGN_AND_COMMA(const UImage&);
# endif
#undef CTOR_AND_ASSIGN_AND_COMMA
#define CAST_OPERATOR(Type) \
operator Type() const;
# ifndef SWIG
LIBPORT_LIST_APPLY(CAST_OPERATOR, URBI_NUMERIC_TYPES)
# else
operator ufloat() const;
operator std::string() const;
operator int() const;
operator unsigned int() const;
operator long() const;
operator unsigned long() const;
operator bool() const;
# endif
#undef CAST_OPERATOR
#ifdef DOXYGEN
// Doxygens needs a prototype for ufloat.
operator ufloat() const;
#endif
operator std::string() const;
operator bool() const;
/// Accessor. Gives us an implicit operator UBinary() const
operator const UBinary&() const;
/// Deep copy.
operator UList() const;
/// Deep copy.
operator UDictionary() const;
/// Shallow copy.
operator UImage() const;
/// Shallow copy.
operator USound() const;
/// This operator does nothing, but helps with the previous operator,.
/// Indeed, when writing "uval, void_expr", the compiler complains
/// about uval being evaluated for nothing. Let's have it believe
/// we're doing something...
UValue& operator()();
/// Parse an uvalue in current message+pos, returns pos of end of
/// match -pos of error if error.
int parse(const char* message,
int pos,
const binaries_type& bins,
binaries_type::const_iterator& binpos);
/// Print itself on \c s, and return it.
std::ostream& print(std::ostream& s) const;
// Huge hack.
static const bool copy = true;
};
inline
std::ostream&
operator<<(std::ostream& s, const UValue& v);
inline
std::ostream&
operator<<(std::ostream& s, const UDictionary& d);
/*----------.
| Casters. |
`----------*/
// For each Type, define an operator() that casts its UValue&
// argument into Type. We need partial specialization.
template <typename Type>
struct uvalue_caster
{
};
// T -> UVar& if T = UVar
// T -> T otherwise.
template <typename T>
struct uvar_ref_traits
{
typedef T type;
};
template <>
struct uvar_ref_traits<UVar>
{
typedef UVar& type;
};
// Run the uvalue_caster<Type> on v.
/* NM: Why exactly are we moving the const away?
* I'm dropping it for UValue as it makes unnecessary copy.
*/
template<typename T> struct uvalue_cast_return_type
{
typedef typename libport::traits::remove_reference<T>::type type;
};
template<> struct uvalue_cast_return_type<const UValue&>
{
typedef const UValue& type;
};
template <typename Type>
typename uvar_ref_traits<typename uvalue_cast_return_type<Type>::type>::type
uvalue_cast (UValue& v);
} // namespace urbi
#define SYNCLINE_PUSH() \
"//#push " BOOST_PP_STRINGIZE(__LINE__) " \"" __FILE__ "\"\n"
#define SYNCLINE_POP() \
"//#pop\n"
#define SYNCLINE_WRAP(...) \
SYNCLINE_PUSH() \
__VA_ARGS__ \
"\n" \
SYNCLINE_POP()
#define URBI_STRUCT_CAST_FIELD(_, Cname, Field) \
if (libport::mhas(dict, BOOST_PP_STRINGIZE(Field))) \
uvalue_cast_bounce(res.Field, dict[BOOST_PP_STRINGIZE(Field)]); \
else \
GD_WARN("Serialized data for " #Cname "is missing field" \
BOOST_PP_STRINGIZE(Field)); \
#define URBI_STRUCT_BCAST_FIELD(_, Cname, Field) \
dict[BOOST_PP_STRINGIZE(Field)], c.Field;
#define URBI_REGISTER_STRUCT(Cname, ...) \
namespace urbi \
{ \
template<> \
struct uvalue_caster<Cname> \
{ \
Cname operator()(UValue& v) \
{ \
if (v.type != DATA_DICTIONARY) \
throw std::runtime_error("invalid cast to " #Cname "from " \
+ string_cast(v)); \
UDictionary& dict = *v.dictionary; \
Cname res; \
LIBPORT_VAARGS_APPLY(URBI_STRUCT_CAST_FIELD, Cname, __VA_ARGS__); \
return res; \
} \
}; \
\
static UValue& operator,(UValue& v, const Cname &c) \
{ \
v = UDictionary(); \
UDictionary& dict = *v.dictionary; \
dict["$sn"] = BOOST_PP_STRINGIZE(Cname); \
LIBPORT_VAARGS_APPLY(URBI_STRUCT_BCAST_FIELD, Cname, __VA_ARGS__); \
return v; \
} \
}
/** Packed data structure.
* This template class behaves exactly as a std::vector, except it gets
* serialized efficiently in a Binary, whereas std::vector is converted in
* an urbiscript list.
*/
template<typename T> class UPackedData: public std::vector<T>
{
public:
UPackedData() {};
UPackedData(const std::vector<T>& src): std::vector<T>(src) {};
template<typename I> UPackedData(I begin, I end):std::vector<T>(begin, end){};
};
# include <urbi/uvalue.hxx>
# include <libport/warning-pop.hh>
#endif // ! URBI_UVALUE_HH
<|endoftext|> |
<commit_before>#ifndef SDK_REMOTE_TESTS_TESTS_HH
# define SDK_REMOTE_TESTS_TESTS_HH
# include <libport/debug.hh>
# include <libport/semaphore.hh>
# include <libport/program-name.hh>
# include <libport/unistd.h>
# include <urbi/uclient.hh>
# include <urbi/usyncclient.hh>
/* Liburbi test suite
= Architecture =
Each file corresponds to an 'atomic' test.
Test file layout
- #includes "tests.hh"
- write callbacks, ensure global unique names
- a call to BEGIN_TEST(testname, clientname, syncclientname),
testname must be filename-without-extension
- code of the test:
- setup callbacks, the callback function dump is provided: it displays the
message and increments dumpSem semaphore. Setting a Wildcard or at least
an error callback is recommended.
- c++ code using UClient & client, USyncClient &syncClient made available
- expected output in comments:
//= <expected output>
- a call to END_TEST
<expected output>
<type> <tag> <value>
<type>
D|E|S for data, error, system
*/
/// Display a debug message.
#define VERBOSE(S) \
do { \
GD_CATEGORY(TEST); \
std::ostringstream o; \
o << S; \
GD_INFO(o.str()); \
} while (0)
/// Send S to the Client.
#define SEND_(Client, S) \
do { \
VERBOSE("Sending: " << S); \
Client.send("%s", (std::string(S) + "\n").c_str()); \
} while (0)
/// Send S to client/syncclient.
#define SEND(S) SEND_(client, S)
#define SSEND(S) SEND_(syncClient, S)
/*----------.
| SyncGet. |
`----------*/
template <typename T>
inline
T
sget(urbi::USyncClient& c, const std::string& msg)
{
VERBOSE("syncGet: Asking " << msg);
T res;
assert(urbi::getValue(c.syncGet(msg), res));
return res;
}
/// syncGet E from the syncClient.
#define SGET(Type, E) \
sget<Type>(syncClient, E)
std::string sget_error(urbi::USyncClient& c, const std::string& msg);
/// Send a computation, expect an error.
#define SGET_ERROR(E) \
sget_error(syncClient, E)
extern libport::Semaphore dumpSem;
/// display the value, increment dumpSem.
urbi::UCallbackAction dump(const urbi::UMessage& msg);
/// display the value, incremente dumpSem remove callback if 0
urbi::UCallbackAction removeOnZero(const urbi::UMessage& msg);
#define BEGIN_TEST(Name, ClientName, SyncClientName) \
void \
Name(urbi::UClient& ClientName, \
urbi::USyncClient& SyncClientName) \
{ \
VERBOSE("starting test " << #Name);
#define END_TEST \
sleep(3); \
SSEND("quit;"); \
SEND("shutdown;"); \
}
void dispatch(const std::string& method, urbi::UClient& client,
urbi::USyncClient& syncClient);
/// \a Name is the base name of the C++ file containing the function
/// \a Name.
#define TESTS_RUN(Name) \
do { \
if (method == #Name) \
{ \
void Name(urbi::UClient&, urbi::USyncClient&); \
Name(client, syncClient); \
return; \
} \
} while (0)
#endif // SDK_REMOTE_TESTS_TESTS_HH
<commit_msg>tests: Use send simpler and cleaner.<commit_after>#ifndef SDK_REMOTE_TESTS_TESTS_HH
# define SDK_REMOTE_TESTS_TESTS_HH
# include <libport/debug.hh>
# include <libport/semaphore.hh>
# include <libport/program-name.hh>
# include <libport/unistd.h>
# include <urbi/uclient.hh>
# include <urbi/usyncclient.hh>
/* Liburbi test suite
= Architecture =
Each file corresponds to an 'atomic' test.
Test file layout
- #includes "tests.hh"
- write callbacks, ensure global unique names
- a call to BEGIN_TEST(testname, clientname, syncclientname),
testname must be filename-without-extension
- code of the test:
- setup callbacks, the callback function dump is provided: it displays the
message and increments dumpSem semaphore. Setting a Wildcard or at least
an error callback is recommended.
- c++ code using UClient & client, USyncClient &syncClient made available
- expected output in comments:
//= <expected output>
- a call to END_TEST
<expected output>
<type> <tag> <value>
<type>
D|E|S for data, error, system
*/
/// Display a debug message.
#define VERBOSE(S) \
do { \
GD_CATEGORY(TEST); \
std::ostringstream o; \
o << S; \
GD_INFO(o.str()); \
} while (0)
/// Send S to the Client.
#define SEND_(Client, S) \
do { \
VERBOSE("Sending: " << S); \
Client.send("%s\n", (std::string(S)).c_str()); \
} while (0)
/// Send S to client/syncclient.
#define SEND(S) SEND_(client, S)
#define SSEND(S) SEND_(syncClient, S)
/*----------.
| SyncGet. |
`----------*/
template <typename T>
inline
T
sget(urbi::USyncClient& c, const std::string& msg)
{
VERBOSE("syncGet: Asking " << msg);
T res;
assert(urbi::getValue(c.syncGet(msg), res));
return res;
}
/// syncGet E from the syncClient.
#define SGET(Type, E) \
sget<Type>(syncClient, E)
std::string sget_error(urbi::USyncClient& c, const std::string& msg);
/// Send a computation, expect an error.
#define SGET_ERROR(E) \
sget_error(syncClient, E)
extern libport::Semaphore dumpSem;
/// display the value, increment dumpSem.
urbi::UCallbackAction dump(const urbi::UMessage& msg);
/// display the value, incremente dumpSem remove callback if 0
urbi::UCallbackAction removeOnZero(const urbi::UMessage& msg);
#define BEGIN_TEST(Name, ClientName, SyncClientName) \
void \
Name(urbi::UClient& ClientName, \
urbi::USyncClient& SyncClientName) \
{ \
VERBOSE("starting test " << #Name);
#define END_TEST \
sleep(3); \
SSEND("quit;"); \
SEND("shutdown;"); \
}
void dispatch(const std::string& method, urbi::UClient& client,
urbi::USyncClient& syncClient);
/// \a Name is the base name of the C++ file containing the function
/// \a Name.
#define TESTS_RUN(Name) \
do { \
if (method == #Name) \
{ \
void Name(urbi::UClient&, urbi::USyncClient&); \
Name(client, syncClient); \
return; \
} \
} while (0)
#endif // SDK_REMOTE_TESTS_TESTS_HH
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/history/query_parser.h"
#include <algorithm>
#include "base/i18n/break_iterator.h"
#include "base/logging.h"
#include "base/memory/scoped_vector.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "ui/base/l10n/l10n_util.h"
#include "unicode/uscript.h"
namespace {
// Returns true if |mp1.first| is less than |mp2.first|. This is used to
// sort match positions.
int CompareMatchPosition(const Snippet::MatchPosition& mp1,
const Snippet::MatchPosition& mp2) {
return mp1.first < mp2.first;
}
// Returns true if |mp2| intersects |mp1|. This is intended for use by
// CoalesceMatchesFrom and isn't meant as a general intersectpion comparison
// function.
bool SnippetIntersects(const Snippet::MatchPosition& mp1,
const Snippet::MatchPosition& mp2) {
return mp2.first >= mp1.first && mp2.first <= mp1.second;
}
// Coalesces match positions in |matches| after index that intersect the match
// position at |index|.
void CoalesceMatchesFrom(size_t index,
Snippet::MatchPositions* matches) {
Snippet::MatchPosition& mp = (*matches)[index];
for (Snippet::MatchPositions::iterator i = matches->begin() + index + 1;
i != matches->end(); ) {
if (SnippetIntersects(mp, *i)) {
mp.second = i->second;
i = matches->erase(i);
} else {
return;
}
}
}
// Sorts the match positions in |matches| by their first index, then coalesces
// any match positions that intersect each other.
void CoalseAndSortMatchPositions(Snippet::MatchPositions* matches) {
std::sort(matches->begin(), matches->end(), &CompareMatchPosition);
// WARNING: we don't use iterator here as CoalesceMatchesFrom may remove
// from matches.
for (size_t i = 0; i < matches->size(); ++i)
CoalesceMatchesFrom(i, matches);
}
} // namespace
// Inheritance structure:
// Queries are represented as trees of QueryNodes.
// QueryNodes are either a collection of subnodes (a QueryNodeList)
// or a single word (a QueryNodeWord).
// A QueryNodeWord is a single word in the query.
class QueryNodeWord : public QueryNode {
public:
explicit QueryNodeWord(const string16& word)
: word_(word), literal_(false) {}
virtual ~QueryNodeWord() {}
virtual int AppendToSQLiteQuery(string16* query) const;
virtual bool IsWord() const { return true; }
const string16& word() const { return word_; }
void set_literal(bool literal) { literal_ = literal; }
virtual bool HasMatchIn(const std::vector<QueryWord>& words,
Snippet::MatchPositions* match_positions) const;
virtual bool Matches(const string16& word, bool exact) const;
virtual void AppendWords(std::vector<string16>* words) const;
private:
string16 word_;
bool literal_;
};
bool QueryNodeWord::HasMatchIn(const std::vector<QueryWord>& words,
Snippet::MatchPositions* match_positions) const {
for (size_t i = 0; i < words.size(); ++i) {
if (Matches(words[i].word, false)) {
size_t match_start = words[i].position;
match_positions->push_back(
Snippet::MatchPosition(match_start,
match_start + static_cast<int>(word_.size())));
return true;
}
}
return false;
}
bool QueryNodeWord::Matches(const string16& word, bool exact) const {
if (exact || !QueryParser::IsWordLongEnoughForPrefixSearch(word_))
return word == word_;
return word.size() >= word_.size() &&
(word_.compare(0, word_.size(), word, 0, word_.size()) == 0);
}
void QueryNodeWord::AppendWords(std::vector<string16>* words) const {
words->push_back(word_);
}
int QueryNodeWord::AppendToSQLiteQuery(string16* query) const {
query->append(word_);
// Use prefix search if we're not literal and long enough.
if (!literal_ && QueryParser::IsWordLongEnoughForPrefixSearch(word_))
*query += L'*';
return 1;
}
// A QueryNodeList has a collection of child QueryNodes
// which it cleans up after.
class QueryNodeList : public QueryNode {
public:
virtual ~QueryNodeList();
virtual int AppendToSQLiteQuery(string16* query) const {
return AppendChildrenToString(query);
}
virtual bool IsWord() const { return false; }
void AddChild(QueryNode* node) { children_.push_back(node); }
typedef std::vector<QueryNode*> QueryNodeVector;
QueryNodeVector* children() { return &children_; }
// Remove empty subnodes left over from other parsing.
void RemoveEmptySubnodes();
// QueryNodeList is never used with Matches or HasMatchIn.
virtual bool Matches(const string16& word, bool exact) const {
NOTREACHED();
return false;
}
virtual bool HasMatchIn(const std::vector<QueryWord>& words,
Snippet::MatchPositions* match_positions) const {
NOTREACHED();
return false;
}
virtual void AppendWords(std::vector<string16>* words) const;
protected:
int AppendChildrenToString(string16* query) const;
QueryNodeVector children_;
};
QueryNodeList::~QueryNodeList() {
for (QueryNodeVector::iterator node = children_.begin();
node != children_.end(); ++node)
delete *node;
}
void QueryNodeList::RemoveEmptySubnodes() {
for (size_t i = 0; i < children_.size(); ++i) {
if (children_[i]->IsWord())
continue;
QueryNodeList* list_node = static_cast<QueryNodeList*>(children_[i]);
list_node->RemoveEmptySubnodes();
if (list_node->children()->empty()) {
children_.erase(children_.begin() + i);
--i;
delete list_node;
}
}
}
void QueryNodeList::AppendWords(std::vector<string16>* words) const {
for (size_t i = 0; i < children_.size(); ++i)
children_[i]->AppendWords(words);
}
int QueryNodeList::AppendChildrenToString(string16* query) const {
int num_words = 0;
for (QueryNodeVector::const_iterator node = children_.begin();
node != children_.end(); ++node) {
if (node != children_.begin())
query->push_back(L' ');
num_words += (*node)->AppendToSQLiteQuery(query);
}
return num_words;
}
// A QueryNodePhrase is a phrase query ("quoted").
class QueryNodePhrase : public QueryNodeList {
public:
virtual int AppendToSQLiteQuery(string16* query) const {
query->push_back(L'"');
int num_words = AppendChildrenToString(query);
query->push_back(L'"');
return num_words;
}
virtual bool Matches(const string16& word, bool exact) const;
virtual bool HasMatchIn(const std::vector<QueryWord>& words,
Snippet::MatchPositions* match_positions) const;
};
bool QueryNodePhrase::Matches(const string16& word, bool exact) const {
NOTREACHED();
return false;
}
bool QueryNodePhrase::HasMatchIn(
const std::vector<QueryWord>& words,
Snippet::MatchPositions* match_positions) const {
if (words.size() < children_.size())
return false;
for (size_t i = 0, max = words.size() - children_.size() + 1; i < max; ++i) {
bool matched_all = true;
for (size_t j = 0; j < children_.size(); ++j) {
if (!children_[j]->Matches(words[i + j].word, true)) {
matched_all = false;
break;
}
}
if (matched_all) {
const QueryWord& last_word = words[i + children_.size() - 1];
match_positions->push_back(
Snippet::MatchPosition(words[i].position,
last_word.position + last_word.word.length()));
return true;
}
}
return false;
}
QueryParser::QueryParser() {
}
// static
bool QueryParser::IsWordLongEnoughForPrefixSearch(const string16& word) {
DCHECK(!word.empty());
size_t minimum_length = 3;
// We intentionally exclude Hangul Jamos (both Conjoining and compatibility)
// because they 'behave like' Latin letters. Moreover, we should
// normalize the former before reaching here.
if (0xAC00 <= word[0] && word[0] <= 0xD7A3)
minimum_length = 2;
return word.size() >= minimum_length;
}
// Returns true if the character is considered a quote.
static bool IsQueryQuote(wchar_t ch) {
return ch == '"' ||
ch == 0xab || // left pointing double angle bracket
ch == 0xbb || // right pointing double angle bracket
ch == 0x201c || // left double quotation mark
ch == 0x201d || // right double quotation mark
ch == 0x201e; // double low-9 quotation mark
}
int QueryParser::ParseQuery(const string16& query,
string16* sqlite_query) {
QueryNodeList root;
if (!ParseQueryImpl(query, &root))
return 0;
return root.AppendToSQLiteQuery(sqlite_query);
}
void QueryParser::ParseQuery(const string16& query,
std::vector<QueryNode*>* nodes) {
QueryNodeList root;
if (ParseQueryImpl(l10n_util::ToLower(query), &root))
nodes->swap(*root.children());
}
void QueryParser::ExtractQueryWords(const string16& query,
std::vector<string16>* words) {
QueryNodeList root;
if (!ParseQueryImpl(query, &root))
return;
root.AppendWords(words);
}
bool QueryParser::DoesQueryMatch(const string16& text,
const std::vector<QueryNode*>& query_nodes,
Snippet::MatchPositions* match_positions) {
if (query_nodes.empty())
return false;
std::vector<QueryWord> query_words;
string16 lower_text = l10n_util::ToLower(text);
ExtractQueryWords(lower_text, &query_words);
if (query_words.empty())
return false;
Snippet::MatchPositions matches;
for (size_t i = 0; i < query_nodes.size(); ++i) {
if (!query_nodes[i]->HasMatchIn(query_words, &matches))
return false;
}
if (lower_text.length() != text.length()) {
// The lower case string differs from the original string. The matches are
// meaningless.
// TODO(sky): we need a better way to align the positions so that we don't
// completely punt here.
match_positions->clear();
} else {
CoalseAndSortMatchPositions(&matches);
match_positions->swap(matches);
}
return true;
}
bool QueryParser::ParseQueryImpl(const string16& query,
QueryNodeList* root) {
base::BreakIterator iter(&query, base::BreakIterator::BREAK_WORD);
// TODO(evanm): support a locale here
if (!iter.Init())
return false;
// To handle nesting, we maintain a stack of QueryNodeLists.
// The last element (back) of the stack contains the current, deepest node.
std::vector<QueryNodeList*> query_stack;
query_stack.push_back(root);
bool in_quotes = false; // whether we're currently in a quoted phrase
while (iter.Advance()) {
// Just found a span between 'prev' (inclusive) and 'pos' (exclusive). It
// is not necessarily a word, but could also be a sequence of punctuation
// or whitespace.
if (iter.IsWord()) {
string16 word = iter.GetString();
QueryNodeWord* word_node = new QueryNodeWord(word);
if (in_quotes)
word_node->set_literal(true);
query_stack.back()->AddChild(word_node);
} else { // Punctuation.
if (IsQueryQuote(query[iter.prev()])) {
if (!in_quotes) {
QueryNodeList* quotes_node = new QueryNodePhrase;
query_stack.back()->AddChild(quotes_node);
query_stack.push_back(quotes_node);
in_quotes = true;
} else {
query_stack.pop_back(); // Stop adding to the quoted phrase.
in_quotes = false;
}
}
}
}
root->RemoveEmptySubnodes();
return true;
}
void QueryParser::ExtractQueryWords(const string16& text,
std::vector<QueryWord>* words) {
base::BreakIterator iter(&text, base::BreakIterator::BREAK_WORD);
// TODO(evanm): support a locale here
if (!iter.Init())
return;
while (iter.Advance()) {
// Just found a span between 'prev' (inclusive) and 'pos' (exclusive). It
// is not necessarily a word, but could also be a sequence of punctuation
// or whitespace.
if (iter.IsWord()) {
string16 word = iter.GetString();
if (!word.empty()) {
words->push_back(QueryWord());
words->back().word = word;
words->back().position = iter.prev();
}
}
}
}
<commit_msg>history: Make QueryNodeList more readable.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/history/query_parser.h"
#include <algorithm>
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/i18n/break_iterator.h"
#include "base/logging.h"
#include "base/memory/scoped_vector.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "ui/base/l10n/l10n_util.h"
#include "unicode/uscript.h"
namespace {
// Returns true if |mp1.first| is less than |mp2.first|. This is used to
// sort match positions.
int CompareMatchPosition(const Snippet::MatchPosition& mp1,
const Snippet::MatchPosition& mp2) {
return mp1.first < mp2.first;
}
// Returns true if |mp2| intersects |mp1|. This is intended for use by
// CoalesceMatchesFrom and isn't meant as a general intersectpion comparison
// function.
bool SnippetIntersects(const Snippet::MatchPosition& mp1,
const Snippet::MatchPosition& mp2) {
return mp2.first >= mp1.first && mp2.first <= mp1.second;
}
// Coalesces match positions in |matches| after index that intersect the match
// position at |index|.
void CoalesceMatchesFrom(size_t index,
Snippet::MatchPositions* matches) {
Snippet::MatchPosition& mp = (*matches)[index];
for (Snippet::MatchPositions::iterator i = matches->begin() + index + 1;
i != matches->end(); ) {
if (SnippetIntersects(mp, *i)) {
mp.second = i->second;
i = matches->erase(i);
} else {
return;
}
}
}
// Sorts the match positions in |matches| by their first index, then coalesces
// any match positions that intersect each other.
void CoalseAndSortMatchPositions(Snippet::MatchPositions* matches) {
std::sort(matches->begin(), matches->end(), &CompareMatchPosition);
// WARNING: we don't use iterator here as CoalesceMatchesFrom may remove
// from matches.
for (size_t i = 0; i < matches->size(); ++i)
CoalesceMatchesFrom(i, matches);
}
} // namespace
// Inheritance structure:
// Queries are represented as trees of QueryNodes.
// QueryNodes are either a collection of subnodes (a QueryNodeList)
// or a single word (a QueryNodeWord).
// A QueryNodeWord is a single word in the query.
class QueryNodeWord : public QueryNode {
public:
explicit QueryNodeWord(const string16& word)
: word_(word), literal_(false) {}
virtual ~QueryNodeWord() {}
virtual int AppendToSQLiteQuery(string16* query) const;
virtual bool IsWord() const { return true; }
const string16& word() const { return word_; }
void set_literal(bool literal) { literal_ = literal; }
virtual bool HasMatchIn(const std::vector<QueryWord>& words,
Snippet::MatchPositions* match_positions) const;
virtual bool Matches(const string16& word, bool exact) const;
virtual void AppendWords(std::vector<string16>* words) const;
private:
string16 word_;
bool literal_;
};
bool QueryNodeWord::HasMatchIn(const std::vector<QueryWord>& words,
Snippet::MatchPositions* match_positions) const {
for (size_t i = 0; i < words.size(); ++i) {
if (Matches(words[i].word, false)) {
size_t match_start = words[i].position;
match_positions->push_back(
Snippet::MatchPosition(match_start,
match_start + static_cast<int>(word_.size())));
return true;
}
}
return false;
}
bool QueryNodeWord::Matches(const string16& word, bool exact) const {
if (exact || !QueryParser::IsWordLongEnoughForPrefixSearch(word_))
return word == word_;
return word.size() >= word_.size() &&
(word_.compare(0, word_.size(), word, 0, word_.size()) == 0);
}
void QueryNodeWord::AppendWords(std::vector<string16>* words) const {
words->push_back(word_);
}
int QueryNodeWord::AppendToSQLiteQuery(string16* query) const {
query->append(word_);
// Use prefix search if we're not literal and long enough.
if (!literal_ && QueryParser::IsWordLongEnoughForPrefixSearch(word_))
*query += L'*';
return 1;
}
// A QueryNodeList has a collection of QueryNodes which are deleted in the end.
class QueryNodeList : public QueryNode {
public:
typedef std::vector<QueryNode*> QueryNodeVector;
QueryNodeList();
virtual ~QueryNodeList();
QueryNodeVector* children() { return &children_; }
void AddChild(QueryNode* node);
// Remove empty subnodes left over from other parsing.
void RemoveEmptySubnodes();
// QueryNode:
virtual int AppendToSQLiteQuery(string16* query) const OVERRIDE;
virtual bool IsWord() const OVERRIDE;
virtual bool Matches(const string16& word, bool exact) const OVERRIDE;
virtual bool HasMatchIn(
const std::vector<QueryWord>& words,
Snippet::MatchPositions* match_positions) const OVERRIDE;
virtual void AppendWords(std::vector<string16>* words) const OVERRIDE;
protected:
int AppendChildrenToString(string16* query) const;
QueryNodeVector children_;
private:
DISALLOW_COPY_AND_ASSIGN(QueryNodeList);
};
QueryNodeList::QueryNodeList() {}
QueryNodeList::~QueryNodeList() {
STLDeleteElements(&children_);
}
void QueryNodeList::AddChild(QueryNode* node) {
children_.push_back(node);
}
void QueryNodeList::RemoveEmptySubnodes() {
for (size_t i = 0; i < children_.size(); ++i) {
if (children_[i]->IsWord())
continue;
QueryNodeList* list_node = static_cast<QueryNodeList*>(children_[i]);
list_node->RemoveEmptySubnodes();
if (list_node->children()->empty()) {
children_.erase(children_.begin() + i);
--i;
delete list_node;
}
}
}
int QueryNodeList::AppendToSQLiteQuery(string16* query) const {
return AppendChildrenToString(query);
}
bool QueryNodeList::IsWord() const {
return false;
}
bool QueryNodeList::Matches(const string16& word, bool exact) const {
NOTREACHED();
return false;
}
bool QueryNodeList::HasMatchIn(const std::vector<QueryWord>& words,
Snippet::MatchPositions* match_positions) const {
NOTREACHED();
return false;
}
void QueryNodeList::AppendWords(std::vector<string16>* words) const {
for (size_t i = 0; i < children_.size(); ++i)
children_[i]->AppendWords(words);
}
int QueryNodeList::AppendChildrenToString(string16* query) const {
int num_words = 0;
for (QueryNodeVector::const_iterator node = children_.begin();
node != children_.end(); ++node) {
if (node != children_.begin())
query->push_back(L' ');
num_words += (*node)->AppendToSQLiteQuery(query);
}
return num_words;
}
// A QueryNodePhrase is a phrase query ("quoted").
class QueryNodePhrase : public QueryNodeList {
public:
virtual int AppendToSQLiteQuery(string16* query) const {
query->push_back(L'"');
int num_words = AppendChildrenToString(query);
query->push_back(L'"');
return num_words;
}
virtual bool Matches(const string16& word, bool exact) const;
virtual bool HasMatchIn(const std::vector<QueryWord>& words,
Snippet::MatchPositions* match_positions) const;
};
bool QueryNodePhrase::Matches(const string16& word, bool exact) const {
NOTREACHED();
return false;
}
bool QueryNodePhrase::HasMatchIn(
const std::vector<QueryWord>& words,
Snippet::MatchPositions* match_positions) const {
if (words.size() < children_.size())
return false;
for (size_t i = 0, max = words.size() - children_.size() + 1; i < max; ++i) {
bool matched_all = true;
for (size_t j = 0; j < children_.size(); ++j) {
if (!children_[j]->Matches(words[i + j].word, true)) {
matched_all = false;
break;
}
}
if (matched_all) {
const QueryWord& last_word = words[i + children_.size() - 1];
match_positions->push_back(
Snippet::MatchPosition(words[i].position,
last_word.position + last_word.word.length()));
return true;
}
}
return false;
}
QueryParser::QueryParser() {
}
// static
bool QueryParser::IsWordLongEnoughForPrefixSearch(const string16& word) {
DCHECK(!word.empty());
size_t minimum_length = 3;
// We intentionally exclude Hangul Jamos (both Conjoining and compatibility)
// because they 'behave like' Latin letters. Moreover, we should
// normalize the former before reaching here.
if (0xAC00 <= word[0] && word[0] <= 0xD7A3)
minimum_length = 2;
return word.size() >= minimum_length;
}
// Returns true if the character is considered a quote.
static bool IsQueryQuote(wchar_t ch) {
return ch == '"' ||
ch == 0xab || // left pointing double angle bracket
ch == 0xbb || // right pointing double angle bracket
ch == 0x201c || // left double quotation mark
ch == 0x201d || // right double quotation mark
ch == 0x201e; // double low-9 quotation mark
}
int QueryParser::ParseQuery(const string16& query,
string16* sqlite_query) {
QueryNodeList root;
if (!ParseQueryImpl(query, &root))
return 0;
return root.AppendToSQLiteQuery(sqlite_query);
}
void QueryParser::ParseQuery(const string16& query,
std::vector<QueryNode*>* nodes) {
QueryNodeList root;
if (ParseQueryImpl(l10n_util::ToLower(query), &root))
nodes->swap(*root.children());
}
void QueryParser::ExtractQueryWords(const string16& query,
std::vector<string16>* words) {
QueryNodeList root;
if (!ParseQueryImpl(query, &root))
return;
root.AppendWords(words);
}
bool QueryParser::DoesQueryMatch(const string16& text,
const std::vector<QueryNode*>& query_nodes,
Snippet::MatchPositions* match_positions) {
if (query_nodes.empty())
return false;
std::vector<QueryWord> query_words;
string16 lower_text = l10n_util::ToLower(text);
ExtractQueryWords(lower_text, &query_words);
if (query_words.empty())
return false;
Snippet::MatchPositions matches;
for (size_t i = 0; i < query_nodes.size(); ++i) {
if (!query_nodes[i]->HasMatchIn(query_words, &matches))
return false;
}
if (lower_text.length() != text.length()) {
// The lower case string differs from the original string. The matches are
// meaningless.
// TODO(sky): we need a better way to align the positions so that we don't
// completely punt here.
match_positions->clear();
} else {
CoalseAndSortMatchPositions(&matches);
match_positions->swap(matches);
}
return true;
}
bool QueryParser::ParseQueryImpl(const string16& query,
QueryNodeList* root) {
base::BreakIterator iter(&query, base::BreakIterator::BREAK_WORD);
// TODO(evanm): support a locale here
if (!iter.Init())
return false;
// To handle nesting, we maintain a stack of QueryNodeLists.
// The last element (back) of the stack contains the current, deepest node.
std::vector<QueryNodeList*> query_stack;
query_stack.push_back(root);
bool in_quotes = false; // whether we're currently in a quoted phrase
while (iter.Advance()) {
// Just found a span between 'prev' (inclusive) and 'pos' (exclusive). It
// is not necessarily a word, but could also be a sequence of punctuation
// or whitespace.
if (iter.IsWord()) {
string16 word = iter.GetString();
QueryNodeWord* word_node = new QueryNodeWord(word);
if (in_quotes)
word_node->set_literal(true);
query_stack.back()->AddChild(word_node);
} else { // Punctuation.
if (IsQueryQuote(query[iter.prev()])) {
if (!in_quotes) {
QueryNodeList* quotes_node = new QueryNodePhrase;
query_stack.back()->AddChild(quotes_node);
query_stack.push_back(quotes_node);
in_quotes = true;
} else {
query_stack.pop_back(); // Stop adding to the quoted phrase.
in_quotes = false;
}
}
}
}
root->RemoveEmptySubnodes();
return true;
}
void QueryParser::ExtractQueryWords(const string16& text,
std::vector<QueryWord>* words) {
base::BreakIterator iter(&text, base::BreakIterator::BREAK_WORD);
// TODO(evanm): support a locale here
if (!iter.Init())
return;
while (iter.Advance()) {
// Just found a span between 'prev' (inclusive) and 'pos' (exclusive). It
// is not necessarily a word, but could also be a sequence of punctuation
// or whitespace.
if (iter.IsWord()) {
string16 word = iter.GetString();
if (!word.empty()) {
words->push_back(QueryWord());
words->back().word = word;
words->back().position = iter.prev();
}
}
}
}
<|endoftext|> |
<commit_before>#include <czmq.h>
#include <g2log.hpp>
#include <algorithm>
#include "FileRecv.h"
FileRecv::FileRecv():
mQueueLength(10),
mTimeoutMs(30000), //5 minutes
mOffset(0),
mChunk(nullptr) {
mCtx = zctx_new();
CHECK(mCtx);
mDealer = zsocket_new(mCtx, ZMQ_DEALER);
CHECK(mDealer);
mCredit = mQueueLength;
}
FileRecv::Socket FileRecv::SetLocation(const std::string& location){
int result = zsocket_connect(mDealer, location.c_str());
return (0 == result) ? FileRecv::Socket::OK : FileRecv::Socket::INVALID;
}
void FileRecv::SetTimeout(const int timeoutMs){
mTimeoutMs = timeoutMs;
}
void FileRecv::RequestChunks(){
// Send enough data requests to fill pipeline:
while (mCredit) {
zstr_sendf (mDealer, "%ld", mOffset);
mOffset++;
mCredit--;
}
}
FileRecv::Stream FileRecv::Receive(std::vector<uint8_t>& data){
//Erase any previous data from the last Monitor()
FreeChunk();
RequestChunks();
static const std::vector<uint8_t> emptyOnError;
//Poll to see if anything is available on the pipeline:
if(zsocket_poll(mDealer, mTimeoutMs)){
mChunk = zframe_recv (mDealer);
if(!mChunk) {
data = emptyOnError;
//Interrupt or end of stream
return FileRecv::Stream::INTERRUPT;
}
//chunk->size = zframe_size (mChunk);
int size = zframe_size (mChunk);
data.resize(size);
if(size <= 0){
//End of Stream
return FileRecv::Stream::END_OF_STREAM;
}
uint8_t* raw = reinterpret_cast<uint8_t*>(zframe_data(mChunk));
std::copy(raw, raw + size, data.begin());
mCredit++;
return FileRecv::Stream::CONTINUE;
}
data = emptyOnError;
return FileRecv::Stream::TIMEOUT;
}
void FileRecv::FreeChunk(){
if(mChunk != nullptr){
zframe_destroy(&mChunk);
mChunk = nullptr;
}
}
FileRecv::~FileRecv(){
FreeChunk();
zsocket_destroy(mCtx, mDealer);
zctx_destroy(&mCtx);
}<commit_msg>interrupt check added<commit_after>#include <czmq.h>
#include <g2log.hpp>
#include <algorithm>
#include "FileRecv.h"
FileRecv::FileRecv():
mQueueLength(10),
mTimeoutMs(30000), //5 minutes
mOffset(0),
mChunk(nullptr) {
mCtx = zctx_new();
CHECK(mCtx);
mDealer = zsocket_new(mCtx, ZMQ_DEALER);
CHECK(mDealer);
mCredit = mQueueLength;
}
FileRecv::Socket FileRecv::SetLocation(const std::string& location){
int result = zsocket_connect(mDealer, location.c_str());
return (0 == result) ? FileRecv::Socket::OK : FileRecv::Socket::INVALID;
}
void FileRecv::SetTimeout(const int timeoutMs){
mTimeoutMs = timeoutMs;
}
void FileRecv::RequestChunks(){
// Send enough data requests to fill pipeline:
while (mCredit && !zctx_interrupted) {
zstr_sendf (mDealer, "%ld", mOffset);
mOffset++;
mCredit--;
}
}
FileRecv::Stream FileRecv::Receive(std::vector<uint8_t>& data){
//Erase any previous data from the last Monitor()
FreeChunk();
RequestChunks();
static const std::vector<uint8_t> emptyOnError;
//Poll to see if anything is available on the pipeline:
if(zsocket_poll(mDealer, mTimeoutMs)){
mChunk = zframe_recv (mDealer);
if(!mChunk) {
data = emptyOnError;
//Interrupt or end of stream
return FileRecv::Stream::INTERRUPT;
}
//chunk->size = zframe_size (mChunk);
int size = zframe_size (mChunk);
data.resize(size);
if(size <= 0){
//End of Stream
return FileRecv::Stream::END_OF_STREAM;
}
uint8_t* raw = reinterpret_cast<uint8_t*>(zframe_data(mChunk));
std::copy(raw, raw + size, data.begin());
mCredit++;
return FileRecv::Stream::CONTINUE;
}
data = emptyOnError;
return FileRecv::Stream::TIMEOUT;
}
void FileRecv::FreeChunk(){
if(mChunk != nullptr){
zframe_destroy(&mChunk);
mChunk = nullptr;
}
}
FileRecv::~FileRecv(){
FreeChunk();
zsocket_destroy(mCtx, mDealer);
zctx_destroy(&mCtx);
}<|endoftext|> |
<commit_before><commit_msg>Revert changes to ie_importer.cc from r25498. The builder doesn't like something; investigating.<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/signin/token_service.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/string_util.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/webdata/web_data_service_factory.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/net/gaia/gaia_auth_fetcher.h"
#include "chrome/common/net/gaia/gaia_constants.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "net/url_request/url_request_context_getter.h"
using content::BrowserThread;
namespace {
// List of services that are capable of ClientLogin-based authentication.
const char* kServices[] = {
GaiaConstants::kGaiaService,
GaiaConstants::kSyncService,
GaiaConstants::kDeviceManagementService,
GaiaConstants::kLSOService
};
} // namespace
TokenService::TokenService()
: profile_(NULL),
token_loading_query_(0),
tokens_loaded_(false) {
// Allow constructor to be called outside the UI thread, so it can be mocked
// out for unit tests.
COMPILE_ASSERT(arraysize(kServices) == arraysize(fetchers_),
kServices_and_fetchers_dont_have_same_size);
}
TokenService::~TokenService() {
if (!source_.empty()) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
ResetCredentialsInMemory();
}
}
void TokenService::Initialize(const char* const source,
Profile* profile) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!source_.empty()) {
// Already initialized.
return;
}
DCHECK(!profile_);
profile_ = profile;
getter_ = profile->GetRequestContext();
// Since the user can create a bookmark in incognito, sync may be running.
// Thus we have to go for explicit access.
web_data_service_ = WebDataServiceFactory::GetForProfile(
profile, Profile::EXPLICIT_ACCESS);
source_ = std::string(source);
CommandLine* cmd_line = CommandLine::ForCurrentProcess();
// Allow the token service to be cleared from the command line. We rely on
// SigninManager::Initialize() being called to clear out the
// kGoogleServicesUsername pref before we call EraseTokensFromDB() as
// otherwise the system would be in an invalid state.
if (cmd_line->HasSwitch(switches::kClearTokenService))
EraseTokensFromDB();
// Allow a token to be injected from the command line.
if (cmd_line->HasSwitch(switches::kSetToken)) {
std::string value = cmd_line->GetSwitchValueASCII(switches::kSetToken);
int separator = value.find(':');
std::string service = value.substr(0, separator);
std::string token = value.substr(separator + 1);
token_map_[service] = token;
SaveAuthTokenToDB(service, token);
}
registrar_.Add(this,
chrome::NOTIFICATION_TOKEN_UPDATED,
content::Source<Profile>(profile));
}
void TokenService::ResetCredentialsInMemory() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Terminate any running fetchers. Callbacks will not return.
for (size_t i = 0; i < arraysize(kServices); ++i) {
fetchers_[i].reset();
}
// Cancel pending loads. Callbacks will not return.
if (token_loading_query_) {
web_data_service_->CancelRequest(token_loading_query_);
token_loading_query_ = 0;
}
tokens_loaded_ = false;
token_map_.clear();
credentials_ = GaiaAuthConsumer::ClientLoginResult();
}
void TokenService::UpdateCredentials(
const GaiaAuthConsumer::ClientLoginResult& credentials) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
credentials_ = credentials;
SaveAuthTokenToDB(GaiaConstants::kGaiaLsid, credentials.lsid);
SaveAuthTokenToDB(GaiaConstants::kGaiaSid, credentials.sid);
// Cancel any currently running requests.
for (size_t i = 0; i < arraysize(kServices); i++) {
fetchers_[i].reset();
}
// Notify the CredentialCacheService that a new lsid and sid are available.
FireCredentialsUpdatedNotification(credentials.lsid, credentials.sid);
}
void TokenService::UpdateCredentialsWithOAuth2(
const GaiaAuthConsumer::ClientOAuthResult& credentials) {
// Will be implemented once the ClientOAuth signin is complete. Not called
// yet by any code.
NOTREACHED();
}
void TokenService::LoadTokensFromDB() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (web_data_service_.get())
token_loading_query_ = web_data_service_->GetAllTokens(this);
}
void TokenService::SaveAuthTokenToDB(const std::string& service,
const std::string& auth_token) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (web_data_service_.get())
web_data_service_->SetTokenForService(service, auth_token);
}
void TokenService::EraseTokensFromDB() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Try to track down http://crbug.com/121755 - we should never clear the
// token DB while we're still logged in.
if (profile_) {
std::string user = profile_->GetPrefs()->GetString(
prefs::kGoogleServicesUsername);
CHECK(user.empty());
}
if (web_data_service_.get())
web_data_service_->RemoveAllTokens();
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_TOKENS_CLEARED,
content::Source<TokenService>(this),
content::NotificationService::NoDetails());
}
bool TokenService::TokensLoadedFromDB() const {
return tokens_loaded_;
}
// static
int TokenService::GetServiceIndex(const std::string& service) {
for (size_t i = 0; i < arraysize(kServices); ++i) {
if (kServices[i] == service)
return i;
}
return -1;
}
bool TokenService::AreCredentialsValid() const {
return !credentials_.lsid.empty() && !credentials_.sid.empty();
}
void TokenService::StartFetchingTokens() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(AreCredentialsValid());
for (size_t i = 0; i < arraysize(kServices); i++) {
fetchers_[i].reset(new GaiaAuthFetcher(this, source_, getter_));
fetchers_[i]->StartIssueAuthToken(credentials_.sid,
credentials_.lsid,
kServices[i]);
}
}
// Services dependent on a token will check if a token is available.
// If it isn't, they'll go to sleep until they get a token event.
bool TokenService::HasTokenForService(const char* service) const {
return token_map_.count(service) > 0;
}
const std::string& TokenService::GetTokenForService(
const char* const service) const {
if (token_map_.count(service) > 0) {
// Note map[key] is not const.
return (*token_map_.find(service)).second;
}
return EmptyString();
}
bool TokenService::HasOAuthLoginToken() const {
return HasTokenForService(GaiaConstants::kGaiaOAuth2LoginRefreshToken);
}
const std::string& TokenService::GetOAuth2LoginRefreshToken() const {
return GetTokenForService(GaiaConstants::kGaiaOAuth2LoginRefreshToken);
}
const std::string& TokenService::GetOAuth2LoginAccessToken() const {
return GetTokenForService(GaiaConstants::kGaiaOAuth2LoginAccessToken);
}
// static
void TokenService::GetServiceNamesForTesting(std::vector<std::string>* names) {
names->resize(arraysize(kServices));
std::copy(kServices, kServices + arraysize(kServices), names->begin());
}
void TokenService::FireCredentialsUpdatedNotification(
const std::string& lsid,
const std::string& sid) {
CredentialsUpdatedDetails details(lsid, sid);
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_TOKEN_SERVICE_CREDENTIALS_UPDATED,
content::Source<TokenService>(this),
content::Details<const CredentialsUpdatedDetails>(&details));
}
// Note that this can fire twice or more for any given service.
// It can fire once from the DB read, and then once from the initial
// fetcher. Future fetches can cause more notification firings.
// The DB read will not however fire a notification if the fetcher
// returned first. So it's always safe to use the latest notification.
void TokenService::FireTokenAvailableNotification(
const std::string& service,
const std::string& auth_token) {
TokenAvailableDetails details(service, auth_token);
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_TOKEN_AVAILABLE,
content::Source<TokenService>(this),
content::Details<const TokenAvailableDetails>(&details));
}
void TokenService::FireTokenRequestFailedNotification(
const std::string& service,
const GoogleServiceAuthError& error) {
TokenRequestFailedDetails details(service, error);
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_TOKEN_REQUEST_FAILED,
content::Source<TokenService>(this),
content::Details<const TokenRequestFailedDetails>(&details));
}
void TokenService::IssueAuthTokenForTest(const std::string& service,
const std::string& auth_token) {
token_map_[service] = auth_token;
FireTokenAvailableNotification(service, auth_token);
}
void TokenService::OnIssueAuthTokenSuccess(const std::string& service,
const std::string& auth_token) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
VLOG(1) << "Got an authorization token for " << service;
token_map_[service] = auth_token;
FireTokenAvailableNotification(service, auth_token);
SaveAuthTokenToDB(service, auth_token);
// If we got ClientLogin token for "lso" service, then start fetching OAuth2
// login scoped token pair.
if (service == GaiaConstants::kLSOService) {
int index = GetServiceIndex(service);
CHECK_GE(index, 0);
fetchers_[index]->StartLsoForOAuthLoginTokenExchange(auth_token);
}
}
void TokenService::OnIssueAuthTokenFailure(const std::string& service,
const GoogleServiceAuthError& error) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
LOG(WARNING) << "Auth token issuing failed for service:" << service
<< ", error: " << error.ToString();
FireTokenRequestFailedNotification(service, error);
}
void TokenService::OnClientOAuthSuccess(const ClientOAuthResult& result) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
VLOG(1) << "Got OAuth2 login token pair";
token_map_[GaiaConstants::kGaiaOAuth2LoginRefreshToken] =
result.refresh_token;
token_map_[GaiaConstants::kGaiaOAuth2LoginAccessToken] = result.access_token;
SaveAuthTokenToDB(GaiaConstants::kGaiaOAuth2LoginRefreshToken,
result.refresh_token);
SaveAuthTokenToDB(GaiaConstants::kGaiaOAuth2LoginAccessToken,
result.access_token);
// We don't save expiration information for now.
FireTokenAvailableNotification(GaiaConstants::kGaiaOAuth2LoginRefreshToken,
result.refresh_token);
}
void TokenService::OnClientOAuthFailure(
const GoogleServiceAuthError& error) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
LOG(WARNING) << "OAuth2 login token pair fetch failed: " << error.ToString();
FireTokenRequestFailedNotification(
GaiaConstants::kGaiaOAuth2LoginRefreshToken, error);
}
void TokenService::OnWebDataServiceRequestDone(WebDataService::Handle h,
const WDTypedResult* result) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(token_loading_query_);
token_loading_query_ = 0;
// If the fetch failed, there will be no result. In that case, we just don't
// load any tokens at all from the DB.
if (result) {
DCHECK(result->GetType() == TOKEN_RESULT);
const WDResult<std::map<std::string, std::string> > * token_result =
static_cast<const WDResult<std::map<std::string, std::string> > * > (
result);
LoadTokensIntoMemory(token_result->GetValue(), &token_map_);
}
tokens_loaded_ = true;
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_TOKEN_LOADING_FINISHED,
content::Source<TokenService>(this),
content::NotificationService::NoDetails());
}
// Load tokens from the db_token map into the in memory token map.
void TokenService::LoadTokensIntoMemory(
const std::map<std::string, std::string>& db_tokens,
std::map<std::string, std::string>* in_memory_tokens) {
for (size_t i = 0; i < arraysize(kServices); i++) {
LoadSingleTokenIntoMemory(db_tokens, in_memory_tokens, kServices[i]);
}
LoadSingleTokenIntoMemory(db_tokens, in_memory_tokens,
GaiaConstants::kGaiaOAuth2LoginRefreshToken);
LoadSingleTokenIntoMemory(db_tokens, in_memory_tokens,
GaiaConstants::kGaiaOAuth2LoginAccessToken);
if (credentials_.lsid.empty() && credentials_.sid.empty()) {
// Look for GAIA SID and LSID tokens. If we have both, and the current
// crendentials are empty, update the credentials.
std::string lsid;
std::string sid;
if (db_tokens.count(GaiaConstants::kGaiaLsid) > 0)
lsid = db_tokens.find(GaiaConstants::kGaiaLsid)->second;
if (db_tokens.count(GaiaConstants::kGaiaSid) > 0)
sid = db_tokens.find(GaiaConstants::kGaiaSid)->second;
if (!lsid.empty() && !sid.empty()) {
UpdateCredentials(GaiaAuthConsumer::ClientLoginResult(sid,
lsid,
std::string(),
std::string()));
}
}
}
void TokenService::LoadSingleTokenIntoMemory(
const std::map<std::string, std::string>& db_tokens,
std::map<std::string, std::string>* in_memory_tokens,
const std::string& service) {
// OnIssueAuthTokenSuccess should come from the same thread.
// If a token is already present in the map, it could only have
// come from a DB read or from IssueAuthToken. Since we should never
// fetch from the DB twice in a browser session, it must be from
// OnIssueAuthTokenSuccess, which is a live fetcher.
//
// Network fetched tokens take priority over DB tokens, so exclude tokens
// which have already been loaded by the fetcher.
if (!in_memory_tokens->count(service) && db_tokens.count(service)) {
std::string db_token = db_tokens.find(service)->second;
if (!db_token.empty()) {
VLOG(1) << "Loading " << service << " token from DB: " << db_token;
(*in_memory_tokens)[service] = db_token;
FireTokenAvailableNotification(service, db_token);
// Failures are only for network errors.
}
}
}
void TokenService::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK_EQ(type, chrome::NOTIFICATION_TOKEN_UPDATED);
TokenAvailableDetails* tok_details =
content::Details<TokenAvailableDetails>(details).ptr();
OnIssueAuthTokenSuccess(tok_details->service(), tok_details->token());
}
<commit_msg>[Sync] Avoid unnecessary DB rewrite for TokenService credentials that were just read from DB<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/signin/token_service.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/string_util.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/webdata/web_data_service_factory.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/net/gaia/gaia_auth_fetcher.h"
#include "chrome/common/net/gaia/gaia_constants.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "net/url_request/url_request_context_getter.h"
using content::BrowserThread;
namespace {
// List of services that are capable of ClientLogin-based authentication.
const char* kServices[] = {
GaiaConstants::kGaiaService,
GaiaConstants::kSyncService,
GaiaConstants::kDeviceManagementService,
GaiaConstants::kLSOService
};
} // namespace
TokenService::TokenService()
: profile_(NULL),
token_loading_query_(0),
tokens_loaded_(false) {
// Allow constructor to be called outside the UI thread, so it can be mocked
// out for unit tests.
COMPILE_ASSERT(arraysize(kServices) == arraysize(fetchers_),
kServices_and_fetchers_dont_have_same_size);
}
TokenService::~TokenService() {
if (!source_.empty()) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
ResetCredentialsInMemory();
}
}
void TokenService::Initialize(const char* const source,
Profile* profile) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!source_.empty()) {
// Already initialized.
return;
}
DCHECK(!profile_);
profile_ = profile;
getter_ = profile->GetRequestContext();
// Since the user can create a bookmark in incognito, sync may be running.
// Thus we have to go for explicit access.
web_data_service_ = WebDataServiceFactory::GetForProfile(
profile, Profile::EXPLICIT_ACCESS);
source_ = std::string(source);
CommandLine* cmd_line = CommandLine::ForCurrentProcess();
// Allow the token service to be cleared from the command line. We rely on
// SigninManager::Initialize() being called to clear out the
// kGoogleServicesUsername pref before we call EraseTokensFromDB() as
// otherwise the system would be in an invalid state.
if (cmd_line->HasSwitch(switches::kClearTokenService))
EraseTokensFromDB();
// Allow a token to be injected from the command line.
if (cmd_line->HasSwitch(switches::kSetToken)) {
std::string value = cmd_line->GetSwitchValueASCII(switches::kSetToken);
int separator = value.find(':');
std::string service = value.substr(0, separator);
std::string token = value.substr(separator + 1);
token_map_[service] = token;
SaveAuthTokenToDB(service, token);
}
registrar_.Add(this,
chrome::NOTIFICATION_TOKEN_UPDATED,
content::Source<Profile>(profile));
}
void TokenService::ResetCredentialsInMemory() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Terminate any running fetchers. Callbacks will not return.
for (size_t i = 0; i < arraysize(kServices); ++i) {
fetchers_[i].reset();
}
// Cancel pending loads. Callbacks will not return.
if (token_loading_query_) {
web_data_service_->CancelRequest(token_loading_query_);
token_loading_query_ = 0;
}
tokens_loaded_ = false;
token_map_.clear();
credentials_ = GaiaAuthConsumer::ClientLoginResult();
}
void TokenService::UpdateCredentials(
const GaiaAuthConsumer::ClientLoginResult& credentials) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
credentials_ = credentials;
SaveAuthTokenToDB(GaiaConstants::kGaiaLsid, credentials.lsid);
SaveAuthTokenToDB(GaiaConstants::kGaiaSid, credentials.sid);
// Cancel any currently running requests.
for (size_t i = 0; i < arraysize(kServices); i++) {
fetchers_[i].reset();
}
// Notify the CredentialCacheService that a new lsid and sid are available.
FireCredentialsUpdatedNotification(credentials.lsid, credentials.sid);
}
void TokenService::UpdateCredentialsWithOAuth2(
const GaiaAuthConsumer::ClientOAuthResult& credentials) {
// Will be implemented once the ClientOAuth signin is complete. Not called
// yet by any code.
NOTREACHED();
}
void TokenService::LoadTokensFromDB() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (web_data_service_.get())
token_loading_query_ = web_data_service_->GetAllTokens(this);
}
void TokenService::SaveAuthTokenToDB(const std::string& service,
const std::string& auth_token) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (web_data_service_.get())
web_data_service_->SetTokenForService(service, auth_token);
}
void TokenService::EraseTokensFromDB() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Try to track down http://crbug.com/121755 - we should never clear the
// token DB while we're still logged in.
if (profile_) {
std::string user = profile_->GetPrefs()->GetString(
prefs::kGoogleServicesUsername);
CHECK(user.empty());
}
if (web_data_service_.get())
web_data_service_->RemoveAllTokens();
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_TOKENS_CLEARED,
content::Source<TokenService>(this),
content::NotificationService::NoDetails());
}
bool TokenService::TokensLoadedFromDB() const {
return tokens_loaded_;
}
// static
int TokenService::GetServiceIndex(const std::string& service) {
for (size_t i = 0; i < arraysize(kServices); ++i) {
if (kServices[i] == service)
return i;
}
return -1;
}
bool TokenService::AreCredentialsValid() const {
return !credentials_.lsid.empty() && !credentials_.sid.empty();
}
void TokenService::StartFetchingTokens() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(AreCredentialsValid());
for (size_t i = 0; i < arraysize(kServices); i++) {
fetchers_[i].reset(new GaiaAuthFetcher(this, source_, getter_));
fetchers_[i]->StartIssueAuthToken(credentials_.sid,
credentials_.lsid,
kServices[i]);
}
}
// Services dependent on a token will check if a token is available.
// If it isn't, they'll go to sleep until they get a token event.
bool TokenService::HasTokenForService(const char* service) const {
return token_map_.count(service) > 0;
}
const std::string& TokenService::GetTokenForService(
const char* const service) const {
if (token_map_.count(service) > 0) {
// Note map[key] is not const.
return (*token_map_.find(service)).second;
}
return EmptyString();
}
bool TokenService::HasOAuthLoginToken() const {
return HasTokenForService(GaiaConstants::kGaiaOAuth2LoginRefreshToken);
}
const std::string& TokenService::GetOAuth2LoginRefreshToken() const {
return GetTokenForService(GaiaConstants::kGaiaOAuth2LoginRefreshToken);
}
const std::string& TokenService::GetOAuth2LoginAccessToken() const {
return GetTokenForService(GaiaConstants::kGaiaOAuth2LoginAccessToken);
}
// static
void TokenService::GetServiceNamesForTesting(std::vector<std::string>* names) {
names->resize(arraysize(kServices));
std::copy(kServices, kServices + arraysize(kServices), names->begin());
}
void TokenService::FireCredentialsUpdatedNotification(
const std::string& lsid,
const std::string& sid) {
CredentialsUpdatedDetails details(lsid, sid);
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_TOKEN_SERVICE_CREDENTIALS_UPDATED,
content::Source<TokenService>(this),
content::Details<const CredentialsUpdatedDetails>(&details));
}
// Note that this can fire twice or more for any given service.
// It can fire once from the DB read, and then once from the initial
// fetcher. Future fetches can cause more notification firings.
// The DB read will not however fire a notification if the fetcher
// returned first. So it's always safe to use the latest notification.
void TokenService::FireTokenAvailableNotification(
const std::string& service,
const std::string& auth_token) {
TokenAvailableDetails details(service, auth_token);
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_TOKEN_AVAILABLE,
content::Source<TokenService>(this),
content::Details<const TokenAvailableDetails>(&details));
}
void TokenService::FireTokenRequestFailedNotification(
const std::string& service,
const GoogleServiceAuthError& error) {
TokenRequestFailedDetails details(service, error);
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_TOKEN_REQUEST_FAILED,
content::Source<TokenService>(this),
content::Details<const TokenRequestFailedDetails>(&details));
}
void TokenService::IssueAuthTokenForTest(const std::string& service,
const std::string& auth_token) {
token_map_[service] = auth_token;
FireTokenAvailableNotification(service, auth_token);
}
void TokenService::OnIssueAuthTokenSuccess(const std::string& service,
const std::string& auth_token) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
VLOG(1) << "Got an authorization token for " << service;
token_map_[service] = auth_token;
FireTokenAvailableNotification(service, auth_token);
SaveAuthTokenToDB(service, auth_token);
// If we got ClientLogin token for "lso" service, then start fetching OAuth2
// login scoped token pair.
if (service == GaiaConstants::kLSOService) {
int index = GetServiceIndex(service);
CHECK_GE(index, 0);
fetchers_[index]->StartLsoForOAuthLoginTokenExchange(auth_token);
}
}
void TokenService::OnIssueAuthTokenFailure(const std::string& service,
const GoogleServiceAuthError& error) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
LOG(WARNING) << "Auth token issuing failed for service:" << service
<< ", error: " << error.ToString();
FireTokenRequestFailedNotification(service, error);
}
void TokenService::OnClientOAuthSuccess(const ClientOAuthResult& result) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
VLOG(1) << "Got OAuth2 login token pair";
token_map_[GaiaConstants::kGaiaOAuth2LoginRefreshToken] =
result.refresh_token;
token_map_[GaiaConstants::kGaiaOAuth2LoginAccessToken] = result.access_token;
SaveAuthTokenToDB(GaiaConstants::kGaiaOAuth2LoginRefreshToken,
result.refresh_token);
SaveAuthTokenToDB(GaiaConstants::kGaiaOAuth2LoginAccessToken,
result.access_token);
// We don't save expiration information for now.
FireTokenAvailableNotification(GaiaConstants::kGaiaOAuth2LoginRefreshToken,
result.refresh_token);
}
void TokenService::OnClientOAuthFailure(
const GoogleServiceAuthError& error) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
LOG(WARNING) << "OAuth2 login token pair fetch failed: " << error.ToString();
FireTokenRequestFailedNotification(
GaiaConstants::kGaiaOAuth2LoginRefreshToken, error);
}
void TokenService::OnWebDataServiceRequestDone(WebDataService::Handle h,
const WDTypedResult* result) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(token_loading_query_);
token_loading_query_ = 0;
// If the fetch failed, there will be no result. In that case, we just don't
// load any tokens at all from the DB.
if (result) {
DCHECK(result->GetType() == TOKEN_RESULT);
const WDResult<std::map<std::string, std::string> > * token_result =
static_cast<const WDResult<std::map<std::string, std::string> > * > (
result);
LoadTokensIntoMemory(token_result->GetValue(), &token_map_);
}
tokens_loaded_ = true;
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_TOKEN_LOADING_FINISHED,
content::Source<TokenService>(this),
content::NotificationService::NoDetails());
}
// Load tokens from the db_token map into the in memory token map.
void TokenService::LoadTokensIntoMemory(
const std::map<std::string, std::string>& db_tokens,
std::map<std::string, std::string>* in_memory_tokens) {
// Ensure that there are no active fetchers at the time we first load
// tokens from the DB into memory.
for (size_t i = 0; i < arraysize(kServices); ++i) {
DCHECK(NULL == fetchers_[i].get());
}
for (size_t i = 0; i < arraysize(kServices); i++) {
LoadSingleTokenIntoMemory(db_tokens, in_memory_tokens, kServices[i]);
}
LoadSingleTokenIntoMemory(db_tokens, in_memory_tokens,
GaiaConstants::kGaiaOAuth2LoginRefreshToken);
LoadSingleTokenIntoMemory(db_tokens, in_memory_tokens,
GaiaConstants::kGaiaOAuth2LoginAccessToken);
if (credentials_.lsid.empty() && credentials_.sid.empty()) {
// Look for GAIA SID and LSID tokens. If we have both, and the current
// crendentials are empty, update the credentials.
std::string lsid;
std::string sid;
if (db_tokens.count(GaiaConstants::kGaiaLsid) > 0)
lsid = db_tokens.find(GaiaConstants::kGaiaLsid)->second;
if (db_tokens.count(GaiaConstants::kGaiaSid) > 0)
sid = db_tokens.find(GaiaConstants::kGaiaSid)->second;
if (!lsid.empty() && !sid.empty()) {
credentials_ = GaiaAuthConsumer::ClientLoginResult(sid,
lsid,
std::string(),
std::string());
}
}
}
void TokenService::LoadSingleTokenIntoMemory(
const std::map<std::string, std::string>& db_tokens,
std::map<std::string, std::string>* in_memory_tokens,
const std::string& service) {
// OnIssueAuthTokenSuccess should come from the same thread.
// If a token is already present in the map, it could only have
// come from a DB read or from IssueAuthToken. Since we should never
// fetch from the DB twice in a browser session, it must be from
// OnIssueAuthTokenSuccess, which is a live fetcher.
//
// Network fetched tokens take priority over DB tokens, so exclude tokens
// which have already been loaded by the fetcher.
if (!in_memory_tokens->count(service) && db_tokens.count(service)) {
std::string db_token = db_tokens.find(service)->second;
if (!db_token.empty()) {
VLOG(1) << "Loading " << service << " token from DB: " << db_token;
(*in_memory_tokens)[service] = db_token;
FireTokenAvailableNotification(service, db_token);
// Failures are only for network errors.
}
}
}
void TokenService::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK_EQ(type, chrome::NOTIFICATION_TOKEN_UPDATED);
TokenAvailableDetails* tok_details =
content::Details<TokenAvailableDetails>(details).ptr();
OnIssueAuthTokenSuccess(tok_details->service(), tok_details->token());
}
<|endoftext|> |
<commit_before>#ifndef __ENVIRE_CORE_GRAPHVIZ__
#define __ENVIRE_CORE_GRAPHVIZ__
#include <fstream> // std::ofstream
#include <envire_core/TransformTree.hpp>
#include <boost/graph/graphviz.hpp>
namespace envire { namespace core
{
/**@class Transform Writer
* Frame Graph Viz property writer for boost graphs
* */
template <class _Frame>
class FrameWriter
{
public:
FrameWriter(_Frame _f):f(_f){}
template <class _Vertex>
void operator()(std::ostream &out, const _Vertex& n) const
{
out << "[shape=record, label=\"<f0> " << f[n].name <<
"|<f1>" << f[n].items.size()<<"\""
<<",style=filled,fillcolor=lightblue]";
}
private:
_Frame f;
};
/**@class Transform Writer
* Transform Graph Viz Property writer for boost graphs
* */
template <class _Transform>
class TransformWriter
{
public:
TransformWriter(_Transform _tf):tf(_tf){}
template <class _Edge>
void operator()(std::ostream &out, const _Edge& e) const
{
out << "[label=\"" << tf[e].time.toString(::base::Time::Seconds) <<
boost::format("\\nt: (%.1f %.1f %.1f)\\nr: (%.1f %.1f %.1f)") % tf[e].transform.translation.x() % tf[e].transform.translation.y() % tf[e].transform.translation.z()
% tf[e].transform.orientation.axis()[0] % tf[e].transform.orientation.axis()[1] % tf[e].transform.orientation.axis()[2]
<< "\""
<< ",shape=ellipse,color=red,style=filled,fillcolor=lightcoral]";
}
private:
_Transform tf;
};
/**@class Environment Writer
* Transform Graph Viz Property writer for boost graphs
* */
class GraphPropWriter
{
public:
GraphPropWriter(){}
void operator()(std::ostream &out) const
{
//out<< "graph[rankdir=LR,splines=ortho];\n";
out<< "graph[size=\"88,136\", ranksep=3.0, nodesep=2.0, fontname=\"Helvetica\", fontsize=8];\n";
}
};
/**@class GraphViz
* Class to print TransformGraphs in Graph Viz
* */
class GraphViz
{
protected:
inline GraphPropWriter
make_graph_writer()
{
return GraphPropWriter();
}
/**@brief Writer for Frame Node
*/
template <class _Frame>
inline FrameWriter<_Frame>
make_node_writer(_Frame frame)
{
return FrameWriter<_Frame>(frame);
}
/**@brief Writer for Frame Node
*/
template <class _Transform>
inline TransformWriter<_Transform>
make_edge_writer(_Transform tf)
{
return TransformWriter<_Transform>(tf);
}
public:
/**@brief Export to GraphViz
*
*/
void write(const TransformGraph &graph, const std::string& filename = "")
{
std::streambuf * buf;
std::ofstream of;
if(!filename.empty())
{
of.open(filename.c_str());
buf = of.rdbuf();
}
else
{
buf = std::cout.rdbuf();
}
/** Print graph **/
std::ostream out(buf);
boost::write_graphviz (out, graph,
make_node_writer(boost::get(&FrameProperty::frame, graph)),
make_edge_writer(boost::get(&TransformProperty::transform, graph)),
make_graph_writer());
}
};
}}
#endif
<commit_msg>src: graphviz has different color for the camera label (for the msc filter)<commit_after>#ifndef __ENVIRE_CORE_GRAPHVIZ__
#define __ENVIRE_CORE_GRAPHVIZ__
#include <fstream> // std::ofstream
#include <envire_core/TransformTree.hpp>
#include <boost/graph/graphviz.hpp>
namespace envire { namespace core
{
/**@class Transform Writer
* Frame Graph Viz property writer for boost graphs
* */
template <class _Frame>
class FrameWriter
{
public:
FrameWriter(_Frame _f):f(_f){}
template <class _Vertex>
void operator()(std::ostream &out, const _Vertex& n) const
{
if(f[n].name.find("camera") != std::string::npos)
{
out << "[shape=record, label=\"<f0> " << f[n].name <<
"|<f1>" << f[n].items.size()<<"\""
<<",style=filled,fillcolor=orange]";
}
else
{
out << "[shape=record, label=\"<f0> " << f[n].name <<
"|<f1>" << f[n].items.size()<<"\""
<<",style=filled,fillcolor=lightblue]";
}
}
private:
_Frame f;
};
/**@class Transform Writer
* Transform Graph Viz Property writer for boost graphs
* */
template <class _Transform>
class TransformWriter
{
public:
TransformWriter(_Transform _tf):tf(_tf){}
template <class _Edge>
void operator()(std::ostream &out, const _Edge& e) const
{
out << "[label=\"" << tf[e].time.toString(::base::Time::Seconds) <<
boost::format("\\nt: (%.1f %.1f %.1f)\\nr: (%.1f %.1f %.1f)") % tf[e].transform.translation.x() % tf[e].transform.translation.y() % tf[e].transform.translation.z()
% tf[e].transform.orientation.axis()[0] % tf[e].transform.orientation.axis()[1] % tf[e].transform.orientation.axis()[2]
<< "\""
<< ",shape=ellipse,color=red,style=filled,fillcolor=lightcoral]";
}
private:
_Transform tf;
};
/**@class Environment Writer
* Transform Graph Viz Property writer for boost graphs
* */
class GraphPropWriter
{
public:
GraphPropWriter(){}
void operator()(std::ostream &out) const
{
//out<< "graph[rankdir=LR,splines=ortho];\n";
out<< "graph[size=\"88,136\", ranksep=3.0, nodesep=2.0, fontname=\"Helvetica\", fontsize=8];\n";
}
};
/**@class GraphViz
* Class to print TransformGraphs in Graph Viz
* */
class GraphViz
{
protected:
inline GraphPropWriter
make_graph_writer()
{
return GraphPropWriter();
}
/**@brief Writer for Frame Node
*/
template <class _Frame>
inline FrameWriter<_Frame>
make_node_writer(_Frame frame)
{
return FrameWriter<_Frame>(frame);
}
/**@brief Writer for Frame Node
*/
template <class _Transform>
inline TransformWriter<_Transform>
make_edge_writer(_Transform tf)
{
return TransformWriter<_Transform>(tf);
}
public:
/**@brief Export to GraphViz
*
*/
void write(const TransformGraph &graph, const std::string& filename = "")
{
std::streambuf * buf;
std::ofstream of;
if(!filename.empty())
{
of.open(filename.c_str());
buf = of.rdbuf();
}
else
{
buf = std::cout.rdbuf();
}
/** Print graph **/
std::ostream out(buf);
boost::write_graphviz (out, graph,
make_node_writer(boost::get(&FrameProperty::frame, graph)),
make_edge_writer(boost::get(&TransformProperty::transform, graph)),
make_graph_writer());
}
};
}}
#endif
<|endoftext|> |
<commit_before>/* GG is a GUI for SDL and OpenGL.
Copyright (C) 2003-2008 T. Zachary Laine
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation; either version 2.1
of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA
If you do not wish to comply with the terms of the LGPL please
contact the author as other terms are available for a fee.
Zach Laine
whatwasthataddress@gmail.com */
#include <GG/GroupBox.h>
#include <GG/GUI.h>
#include <GG/DrawUtil.h>
#include <GG/StyleFactory.h>
#include <GG/TextControl.h>
using namespace GG;
namespace {
Y TopOfFrame(bool label, const boost::shared_ptr<Font>& font)
{ return label ? font->Lineskip() / 2 - 1 : Y0; }
}
////////////////////////////////////////////////
// GG::GroupBox
////////////////////////////////////////////////
// static(s)
const int GroupBox::FRAME_THICK = 2;
const int GroupBox::PIXEL_MARGIN = 4;
GroupBox::GroupBox(X x, Y y, X w, Y h, const std::string& label, const boost::shared_ptr<Font>& font,
Clr color, Clr text_color/* = CLR_BLACK*/, Clr interior/* = CLR_ZERO*/,
Flags<WndFlag> flags/* = Flags<WndFlag>()*/) :
Wnd(x, y, w, h, flags),
m_color(color),
m_text_color(text_color),
m_int_color(interior),
m_font(font),
m_label(label.empty() ? 0 : GUI::GetGUI()->GetStyleFactory()->NewTextControl(X0, -m_font->Lineskip(), X1, m_font->Lineskip(),
label, m_font, m_text_color, FORMAT_LEFT | FORMAT_TOP)),
m_set_client_corners_equal_to_box_corners(false)
{ AttachChild(m_label); }
Pt GroupBox::ClientUpperLeft() const
{
Pt retval = UpperLeft();
if (!m_set_client_corners_equal_to_box_corners)
retval += Pt(X(FRAME_THICK + PIXEL_MARGIN), Y(FRAME_THICK + PIXEL_MARGIN) + TopOfFrame(m_label, m_font));
return retval;
}
Pt GroupBox::ClientLowerRight() const
{
Pt retval = LowerRight();
if (!m_set_client_corners_equal_to_box_corners)
retval -= Pt(X(FRAME_THICK + PIXEL_MARGIN), Y(FRAME_THICK + PIXEL_MARGIN));
return retval;
}
void GroupBox::Render()
{
Pt ul = UpperLeft(), lr = LowerRight() - Pt(X1, Y1);
ul.y += TopOfFrame(m_label, m_font);
Clr light = LightColor(m_color);
Clr dark = DarkColor(m_color);
const int GAP_FROM_TEXT = 2;
int vertices[24] = {
Value(ul.x) + FRAME_THICK + PIXEL_MARGIN - GAP_FROM_TEXT, Value(ul.y),
Value(ul.x), Value(ul.y),
Value(ul.x), Value(lr.y),
Value(lr.x), Value(lr.y),
Value(lr.x), Value(ul.y),
vertices[0], Value(ul.y)
};
if (m_label) {
vertices[0] = Value(m_label->TextUpperLeft().x - GAP_FROM_TEXT);
vertices[10] = Value(m_label->TextLowerRight().x + GAP_FROM_TEXT);
}
for (std::size_t i = 0; i < 12; i += 2) {
vertices[12 + i + 0] = vertices[i + 0] + 1;
vertices[12 + i + 1] = vertices[i + 1] + 1;
}
--vertices[12];
--vertices[22];
glDisable(GL_TEXTURE_2D);
glColor(light);
glBegin(GL_LINE_STRIP);
for (std::size_t i = 12; i < 24; i += 2) {
glVertex2i(vertices[i + 0], vertices[i + 1]);
}
glEnd();
glColor(dark);
glBegin(GL_LINE_STRIP);
for (std::size_t i = 0; i < 12; i += 2) {
glVertex2i(vertices[i + 0], vertices[i + 1]);
}
glEnd();
glColor(m_int_color);
glBegin(GL_QUADS);
glVertex2i(vertices[14] + 1, vertices[5] - 1);
glVertex2i(vertices[14] + 1, vertices[13] + 1);
glVertex2i(vertices[6] - 1, vertices[13] + 1);
glVertex2i(vertices[6] - 1, vertices[5] - 1);
glEnd();
glEnable(GL_TEXTURE_2D);
}
void GroupBox::SetColor(Clr c)
{ m_color = c; }
void GroupBox::SetTextColor(Clr c)
{ m_text_color = c; }
void GroupBox::SetInteriorColor(Clr c)
{ m_int_color = c; }
void GroupBox::SetClientCornersEqualToBoxCorners(bool b)
{
if (b != m_set_client_corners_equal_to_box_corners) {
m_set_client_corners_equal_to_box_corners = b;
if (m_label) {
if (m_set_client_corners_equal_to_box_corners)
m_label->MoveTo(Pt(X(FRAME_THICK + PIXEL_MARGIN), Y0));
else
m_label->MoveTo(Pt(X0, -m_font->Lineskip()));
}
}
}
void GroupBox::SetText(const std::string& str)
{
delete m_label;
if (!str.empty()) {
m_label = GUI::GetGUI()->GetStyleFactory()->NewTextControl(X(FRAME_THICK + PIXEL_MARGIN), Y0,
X1, m_font->Lineskip(),
str, m_font, m_text_color);
}
if (m_set_client_corners_equal_to_box_corners && m_label)
m_label->MoveTo(Pt(X(FRAME_THICK + PIXEL_MARGIN), Y0));
}
<commit_msg>Fixed broken GroupBox::SetTextColor().<commit_after>/* GG is a GUI for SDL and OpenGL.
Copyright (C) 2003-2008 T. Zachary Laine
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation; either version 2.1
of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA
If you do not wish to comply with the terms of the LGPL please
contact the author as other terms are available for a fee.
Zach Laine
whatwasthataddress@gmail.com */
#include <GG/GroupBox.h>
#include <GG/GUI.h>
#include <GG/DrawUtil.h>
#include <GG/StyleFactory.h>
#include <GG/TextControl.h>
using namespace GG;
namespace {
Y TopOfFrame(bool label, const boost::shared_ptr<Font>& font)
{ return label ? font->Lineskip() / 2 - 1 : Y0; }
}
////////////////////////////////////////////////
// GG::GroupBox
////////////////////////////////////////////////
// static(s)
const int GroupBox::FRAME_THICK = 2;
const int GroupBox::PIXEL_MARGIN = 4;
GroupBox::GroupBox(X x, Y y, X w, Y h, const std::string& label, const boost::shared_ptr<Font>& font,
Clr color, Clr text_color/* = CLR_BLACK*/, Clr interior/* = CLR_ZERO*/,
Flags<WndFlag> flags/* = Flags<WndFlag>()*/) :
Wnd(x, y, w, h, flags),
m_color(color),
m_text_color(text_color),
m_int_color(interior),
m_font(font),
m_label(label.empty() ? 0 : GUI::GetGUI()->GetStyleFactory()->NewTextControl(X0, -m_font->Lineskip(), X1, m_font->Lineskip(),
label, m_font, m_text_color, FORMAT_LEFT | FORMAT_TOP)),
m_set_client_corners_equal_to_box_corners(false)
{ AttachChild(m_label); }
Pt GroupBox::ClientUpperLeft() const
{
Pt retval = UpperLeft();
if (!m_set_client_corners_equal_to_box_corners)
retval += Pt(X(FRAME_THICK + PIXEL_MARGIN), Y(FRAME_THICK + PIXEL_MARGIN) + TopOfFrame(m_label, m_font));
return retval;
}
Pt GroupBox::ClientLowerRight() const
{
Pt retval = LowerRight();
if (!m_set_client_corners_equal_to_box_corners)
retval -= Pt(X(FRAME_THICK + PIXEL_MARGIN), Y(FRAME_THICK + PIXEL_MARGIN));
return retval;
}
void GroupBox::Render()
{
Pt ul = UpperLeft(), lr = LowerRight() - Pt(X1, Y1);
ul.y += TopOfFrame(m_label, m_font);
Clr light = LightColor(m_color);
Clr dark = DarkColor(m_color);
const int GAP_FROM_TEXT = 2;
int vertices[24] = {
Value(ul.x) + FRAME_THICK + PIXEL_MARGIN - GAP_FROM_TEXT, Value(ul.y),
Value(ul.x), Value(ul.y),
Value(ul.x), Value(lr.y),
Value(lr.x), Value(lr.y),
Value(lr.x), Value(ul.y),
vertices[0], Value(ul.y)
};
if (m_label) {
vertices[0] = Value(m_label->TextUpperLeft().x - GAP_FROM_TEXT);
vertices[10] = Value(m_label->TextLowerRight().x + GAP_FROM_TEXT);
}
for (std::size_t i = 0; i < 12; i += 2) {
vertices[12 + i + 0] = vertices[i + 0] + 1;
vertices[12 + i + 1] = vertices[i + 1] + 1;
}
--vertices[12];
--vertices[22];
glDisable(GL_TEXTURE_2D);
glColor(light);
glBegin(GL_LINE_STRIP);
for (std::size_t i = 12; i < 24; i += 2) {
glVertex2i(vertices[i + 0], vertices[i + 1]);
}
glEnd();
glColor(dark);
glBegin(GL_LINE_STRIP);
for (std::size_t i = 0; i < 12; i += 2) {
glVertex2i(vertices[i + 0], vertices[i + 1]);
}
glEnd();
glColor(m_int_color);
glBegin(GL_QUADS);
glVertex2i(vertices[14] + 1, vertices[5] - 1);
glVertex2i(vertices[14] + 1, vertices[13] + 1);
glVertex2i(vertices[6] - 1, vertices[13] + 1);
glVertex2i(vertices[6] - 1, vertices[5] - 1);
glEnd();
glEnable(GL_TEXTURE_2D);
}
void GroupBox::SetColor(Clr c)
{ m_color = c; }
void GroupBox::SetTextColor(Clr c)
{
m_text_color = c;
if (m_label)
m_label->SetTextColor(c);
}
void GroupBox::SetInteriorColor(Clr c)
{ m_int_color = c; }
void GroupBox::SetClientCornersEqualToBoxCorners(bool b)
{
if (b != m_set_client_corners_equal_to_box_corners) {
m_set_client_corners_equal_to_box_corners = b;
if (m_label) {
if (m_set_client_corners_equal_to_box_corners)
m_label->MoveTo(Pt(X(FRAME_THICK + PIXEL_MARGIN), Y0));
else
m_label->MoveTo(Pt(X0, -m_font->Lineskip()));
}
}
}
void GroupBox::SetText(const std::string& str)
{
delete m_label;
if (!str.empty()) {
m_label = GUI::GetGUI()->GetStyleFactory()->NewTextControl(X(FRAME_THICK + PIXEL_MARGIN), Y0,
X1, m_font->Lineskip(),
str, m_font, m_text_color);
}
if (m_set_client_corners_equal_to_box_corners && m_label)
m_label->MoveTo(Pt(X(FRAME_THICK + PIXEL_MARGIN), Y0));
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) 2007 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QMenu>
# include <QMouseEvent>
# include <Inventor/nodes/SoCamera.h>
#endif
#include <Inventor/SbVec2s.h>
#include "View3DInventorViewer.h"
#include "Flag.h"
using namespace Gui;
/* TRANSLATOR Gui::Flag */
// TODO: Rename to Annotation
// Support transparency
// Embed complete widgets
Flag::Flag(QWidget* parent)
: QtGLWidget(parent), coord(0.0f, 0.0f, 0.0f)
{
this->setFixedHeight(20);
#if defined(HAVE_QT5_OPENGL)
setAutoFillBackground(true);
#endif
}
Flag::~Flag()
{
}
void Flag::initializeGL()
{
const QPalette& p = this->palette();
#if !defined(HAVE_QT5_OPENGL)
qglClearColor(p.color(QPalette::Window));
#else
QColor c(p.color(QPalette::Window));
glClearColor(c.redF(), c.greenF(), c.blueF(), c.alphaF());
#endif
}
void Flag::paintGL()
{
#if !defined(HAVE_QT5_OPENGL)
const QPalette& p = this->palette();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
qglColor(p.color(QPalette::Text));
renderText(10,15,this->text);
#else
QOpenGLWidget::paintGL();
#endif
}
void Flag::paintEvent(QPaintEvent* e)
{
#if !defined(HAVE_QT5_OPENGL)
QtGLWidget::paintEvent(e);
#else
const QPalette& p = this->palette();
QColor c(p.color(QPalette::Text));
QPainter painter;
painter.begin(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.fillRect(e->rect(), p.color(QPalette::Window));
painter.setPen(c);
painter.drawText(10, 15, this->text);
painter.end();
#endif
}
void Flag::resizeGL(int width, int height)
{
Q_UNUSED(width);
Q_UNUSED(height);
}
void Flag::setOrigin(const SbVec3f& v)
{
this->coord = v;
}
const SbVec3f& Flag::getOrigin() const
{
return this->coord;
}
void Flag::drawLine (View3DInventorViewer* v, int tox, int toy)
{
if (!isVisible())
return;
// Get position of line
QSize s = parentWidget()->size();
SbVec2s view(s.width(), s.height());
int fromx = pos().x();
int fromy = pos().y() + height()/2;
if (false) fromx += width();
GLPainter p;
p.begin(v->getGLWidget());
#if !defined(HAVE_QT5_OPENGL)
p.setDrawBuffer(GL_BACK);
#endif
// the line
p.setLineWidth(1.0f);
p.drawLine(fromx, fromy, tox, toy);
// the point
p.setPointSize(3.0f);
p.drawPoint(tox, toy);
p.end();
}
void Flag::setText(const QString& t)
{
this->text = t;
}
void Flag::resizeEvent(QResizeEvent* e)
{
QtGLWidget::resizeEvent(e);
}
void Flag::mouseMoveEvent(QMouseEvent *e)
{
if (e->buttons() & Qt::LeftButton) {
move(e->globalPos() - dragPosition);
e->accept();
}
}
void Flag::mousePressEvent(QMouseEvent *e)
{
if (e->button() == Qt::LeftButton) {
dragPosition = e->globalPos() - frameGeometry().topLeft();
e->accept();
}
}
void Flag::contextMenuEvent(QContextMenuEvent * e)
{
QMenu menu(this);
QAction* topleft = menu.addAction(tr("Top left"));
topleft->setCheckable(true);
QAction* botleft = menu.addAction(tr("Bottom left"));
botleft->setCheckable(true);
QAction* topright = menu.addAction(tr("Top right"));
topright->setCheckable(true);
QAction* botright = menu.addAction(tr("Bottom right"));
botright->setCheckable(true);
menu.addSeparator();
QAction* remove = menu.addAction(tr("Remove"));
QAction* select = menu.exec(e->globalPos());
if (remove == select)
this->deleteLater();
}
QSize Flag::sizeHint() const
{
int w = 100;
int h = 20;
QFontMetrics metric(this->font());
QRect r = metric.boundingRect(text);
w = std::max<int>(w, r.width()+20);
h = std::max<int>(h, r.height());
return QSize(w, h);
}
// ------------------------------------------------------------------------
FlagLayout::FlagLayout(QWidget *parent, int margin, int spacing)
: QLayout(parent)
{
setMargin(margin);
setSpacing(spacing);
}
FlagLayout::FlagLayout(int spacing)
{
setSpacing(spacing);
}
FlagLayout::~FlagLayout()
{
QLayoutItem *l;
while ((l = takeAt(0)))
delete l;
}
void FlagLayout::addItem(QLayoutItem *item)
{
add(item, TopLeft);
}
void FlagLayout::addWidget(QWidget *widget, Position position)
{
add(new QWidgetItem(widget), position);
}
Qt::Orientations FlagLayout::expandingDirections() const
{
return Qt::Horizontal | Qt::Vertical;
}
bool FlagLayout::hasHeightForWidth() const
{
return false;
}
int FlagLayout::count() const
{
return list.size();
}
QLayoutItem *FlagLayout::itemAt(int index) const
{
ItemWrapper *wrapper = list.value(index);
if (wrapper)
return wrapper->item;
else
return 0;
}
QSize FlagLayout::minimumSize() const
{
return calculateSize(MinimumSize);
}
void FlagLayout::setGeometry(const QRect &rect)
{
int topHeight = 0;
int bottomHeight = 0;
QLayout::setGeometry(rect);
// left side
for (int i = 0; i < list.size(); ++i) {
ItemWrapper *wrapper = list.at(i);
QLayoutItem *item = wrapper->item;
Position position = wrapper->position;
if (position == TopLeft) {
topHeight += spacing();
item->setGeometry(QRect(rect.x() + spacing(), topHeight,
item->sizeHint().width(), item->sizeHint().height()));
topHeight += item->geometry().height();
} else if (position == BottomLeft) {
bottomHeight += item->geometry().height() + spacing();
item->setGeometry(QRect(rect.x() + spacing(), rect.height() - bottomHeight,
item->sizeHint().width(), item->sizeHint().height()));
}
}
// right side
topHeight = 0;
bottomHeight = 0;
for (int i = 0; i < list.size(); ++i) {
ItemWrapper *wrapper = list.at(i);
QLayoutItem *item = wrapper->item;
Position position = wrapper->position;
int rightpos = item->sizeHint().width() + spacing();
if (position == TopRight) {
topHeight += spacing();
item->setGeometry(QRect(rect.x() + rect.width() - rightpos, topHeight,
item->sizeHint().width(), item->sizeHint().height()));
topHeight += item->geometry().height();
} else if (position == BottomRight) {
bottomHeight += item->geometry().height() + spacing();
item->setGeometry(QRect(rect.x() + rect.width() - rightpos, rect.height() - bottomHeight,
item->sizeHint().width(), item->sizeHint().height()));
}
}
}
QSize FlagLayout::sizeHint() const
{
return calculateSize(SizeHint);
}
QLayoutItem *FlagLayout::takeAt(int index)
{
if (index >= 0 && index < list.size()) {
ItemWrapper *layoutStruct = list.takeAt(index);
return layoutStruct->item;
}
return 0;
}
void FlagLayout::add(QLayoutItem *item, Position position)
{
list.append(new ItemWrapper(item, position));
}
QSize FlagLayout::calculateSize(SizeType sizeType) const
{
QSize totalSize;
for (int i = 0; i < list.size(); ++i) {
ItemWrapper *wrapper = list.at(i);
QSize itemSize;
if (sizeType == MinimumSize)
itemSize = wrapper->item->minimumSize();
else // (sizeType == SizeHint)
itemSize = wrapper->item->sizeHint();
totalSize.rheight() += itemSize.height();
totalSize.rwidth() = qMax<int>(totalSize.width(),itemSize.width());
}
return totalSize;
}
TYPESYSTEM_SOURCE_ABSTRACT(Gui::GLFlagWindow, Gui::GLGraphicsItem);
GLFlagWindow::GLFlagWindow(View3DInventorViewer* view) : _viewer(view), _flagLayout(0)
{
}
GLFlagWindow::~GLFlagWindow()
{
deleteFlags();
if (_flagLayout)
_flagLayout->deleteLater();
}
void GLFlagWindow::deleteFlags()
{
if (_flagLayout) {
int ct = _flagLayout->count();
for (int i=0; i<ct;i++) {
QWidget* flag = _flagLayout->itemAt(0)->widget();
if (flag) {
_flagLayout->removeWidget(flag);
flag->deleteLater();
}
}
}
}
void GLFlagWindow::addFlag(Flag* item, FlagLayout::Position pos)
{
if (!_flagLayout) {
_flagLayout = new FlagLayout(3);
_viewer->setLayout(_flagLayout);
}
item->setParent(_viewer);
_flagLayout->addWidget(item, pos);
item->show();
_viewer->getSoRenderManager()->scheduleRedraw();
}
void GLFlagWindow::removeFlag(Flag* item)
{
if (_flagLayout) {
_flagLayout->removeWidget(item);
}
}
Flag* GLFlagWindow::getFlag(int index) const
{
if (_flagLayout) {
QWidget* flag = _flagLayout->itemAt(index)->widget();
return qobject_cast<Flag*>(flag);
}
return 0;
}
int GLFlagWindow::countFlags() const
{
if (_flagLayout) {
return _flagLayout->count();
}
return 0;
}
void GLFlagWindow::paintGL()
{
// draw lines for the flags
if (_flagLayout) {
// it can happen that the GL widget gets replaced internally (SoQt only, not with quarter) which
// causes to destroy the FlagLayout instance
int ct = _flagLayout->count();
const SbViewportRegion vp = _viewer->getSoRenderManager()->getViewportRegion();
SbVec2s size = vp.getViewportSizePixels();
float aspectratio = float(size[0])/float(size[1]);
SbViewVolume vv = _viewer->getSoRenderManager()->getCamera()->getViewVolume(aspectratio);
for (int i=0; i<ct;i++) {
Flag* flag = qobject_cast<Flag*>(_flagLayout->itemAt(i)->widget());
if (flag) {
SbVec3f pt = flag->getOrigin();
vv.projectToScreen(pt, pt);
int tox = (int)(pt[0] * size[0]);
int toy = (int)((1.0f-pt[1]) * size[1]);
flag->drawLine(_viewer, tox, toy);
}
}
}
}
#include "moc_Flag.cpp"
<commit_msg>Qt5OpenGL: update flags when dragging or removing<commit_after>/***************************************************************************
* Copyright (c) 2007 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QMenu>
# include <QMouseEvent>
# include <Inventor/nodes/SoCamera.h>
#endif
#include <Inventor/SbVec2s.h>
#include "View3DInventorViewer.h"
#include "Flag.h"
using namespace Gui;
/* TRANSLATOR Gui::Flag */
// TODO: Rename to Annotation
// Support transparency
// Embed complete widgets
Flag::Flag(QWidget* parent)
: QtGLWidget(parent), coord(0.0f, 0.0f, 0.0f)
{
this->setFixedHeight(20);
#if defined(HAVE_QT5_OPENGL)
setAutoFillBackground(true);
#endif
}
Flag::~Flag()
{
}
void Flag::initializeGL()
{
const QPalette& p = this->palette();
#if !defined(HAVE_QT5_OPENGL)
qglClearColor(p.color(QPalette::Window));
#else
QColor c(p.color(QPalette::Window));
glClearColor(c.redF(), c.greenF(), c.blueF(), c.alphaF());
#endif
}
void Flag::paintGL()
{
#if !defined(HAVE_QT5_OPENGL)
const QPalette& p = this->palette();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
qglColor(p.color(QPalette::Text));
renderText(10,15,this->text);
#else
QOpenGLWidget::paintGL();
#endif
}
void Flag::paintEvent(QPaintEvent* e)
{
#if !defined(HAVE_QT5_OPENGL)
QtGLWidget::paintEvent(e);
#else
const QPalette& p = this->palette();
QColor c(p.color(QPalette::Text));
QPainter painter;
painter.begin(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.fillRect(e->rect(), p.color(QPalette::Window));
painter.setPen(c);
painter.drawText(10, 15, this->text);
painter.end();
#endif
}
void Flag::resizeGL(int width, int height)
{
Q_UNUSED(width);
Q_UNUSED(height);
}
void Flag::setOrigin(const SbVec3f& v)
{
this->coord = v;
}
const SbVec3f& Flag::getOrigin() const
{
return this->coord;
}
void Flag::drawLine (View3DInventorViewer* v, int tox, int toy)
{
if (!isVisible())
return;
// Get position of line
QSize s = parentWidget()->size();
SbVec2s view(s.width(), s.height());
int fromx = pos().x();
int fromy = pos().y() + height()/2;
if (false) fromx += width();
GLPainter p;
p.begin(v->getGLWidget());
#if !defined(HAVE_QT5_OPENGL)
p.setDrawBuffer(GL_BACK);
#endif
// the line
p.setLineWidth(1.0f);
p.drawLine(fromx, fromy, tox, toy);
// the point
p.setPointSize(3.0f);
p.drawPoint(tox, toy);
p.end();
}
void Flag::setText(const QString& t)
{
this->text = t;
}
void Flag::resizeEvent(QResizeEvent* e)
{
QtGLWidget::resizeEvent(e);
}
void Flag::mouseMoveEvent(QMouseEvent *e)
{
if (e->buttons() & Qt::LeftButton) {
move(e->globalPos() - dragPosition);
e->accept();
#if defined(HAVE_QT5_OPENGL)
View3DInventorViewer* viewer = dynamic_cast<View3DInventorViewer*>(parentWidget());
if (viewer)
viewer->getSoRenderManager()->scheduleRedraw();
#endif
}
}
void Flag::mousePressEvent(QMouseEvent *e)
{
if (e->button() == Qt::LeftButton) {
dragPosition = e->globalPos() - frameGeometry().topLeft();
e->accept();
}
}
void Flag::contextMenuEvent(QContextMenuEvent * e)
{
QMenu menu(this);
QAction* topleft = menu.addAction(tr("Top left"));
topleft->setCheckable(true);
QAction* botleft = menu.addAction(tr("Bottom left"));
botleft->setCheckable(true);
QAction* topright = menu.addAction(tr("Top right"));
topright->setCheckable(true);
QAction* botright = menu.addAction(tr("Bottom right"));
botright->setCheckable(true);
menu.addSeparator();
QAction* remove = menu.addAction(tr("Remove"));
QAction* select = menu.exec(e->globalPos());
if (remove == select)
this->deleteLater();
}
QSize Flag::sizeHint() const
{
int w = 100;
int h = 20;
QFontMetrics metric(this->font());
QRect r = metric.boundingRect(text);
w = std::max<int>(w, r.width()+20);
h = std::max<int>(h, r.height());
return QSize(w, h);
}
// ------------------------------------------------------------------------
FlagLayout::FlagLayout(QWidget *parent, int margin, int spacing)
: QLayout(parent)
{
setMargin(margin);
setSpacing(spacing);
}
FlagLayout::FlagLayout(int spacing)
{
setSpacing(spacing);
}
FlagLayout::~FlagLayout()
{
QLayoutItem *l;
while ((l = takeAt(0)))
delete l;
}
void FlagLayout::addItem(QLayoutItem *item)
{
add(item, TopLeft);
}
void FlagLayout::addWidget(QWidget *widget, Position position)
{
add(new QWidgetItem(widget), position);
}
Qt::Orientations FlagLayout::expandingDirections() const
{
return Qt::Horizontal | Qt::Vertical;
}
bool FlagLayout::hasHeightForWidth() const
{
return false;
}
int FlagLayout::count() const
{
return list.size();
}
QLayoutItem *FlagLayout::itemAt(int index) const
{
ItemWrapper *wrapper = list.value(index);
if (wrapper)
return wrapper->item;
else
return 0;
}
QSize FlagLayout::minimumSize() const
{
return calculateSize(MinimumSize);
}
void FlagLayout::setGeometry(const QRect &rect)
{
int topHeight = 0;
int bottomHeight = 0;
QLayout::setGeometry(rect);
// left side
for (int i = 0; i < list.size(); ++i) {
ItemWrapper *wrapper = list.at(i);
QLayoutItem *item = wrapper->item;
Position position = wrapper->position;
if (position == TopLeft) {
topHeight += spacing();
item->setGeometry(QRect(rect.x() + spacing(), topHeight,
item->sizeHint().width(), item->sizeHint().height()));
topHeight += item->geometry().height();
} else if (position == BottomLeft) {
bottomHeight += item->geometry().height() + spacing();
item->setGeometry(QRect(rect.x() + spacing(), rect.height() - bottomHeight,
item->sizeHint().width(), item->sizeHint().height()));
}
}
// right side
topHeight = 0;
bottomHeight = 0;
for (int i = 0; i < list.size(); ++i) {
ItemWrapper *wrapper = list.at(i);
QLayoutItem *item = wrapper->item;
Position position = wrapper->position;
int rightpos = item->sizeHint().width() + spacing();
if (position == TopRight) {
topHeight += spacing();
item->setGeometry(QRect(rect.x() + rect.width() - rightpos, topHeight,
item->sizeHint().width(), item->sizeHint().height()));
topHeight += item->geometry().height();
} else if (position == BottomRight) {
bottomHeight += item->geometry().height() + spacing();
item->setGeometry(QRect(rect.x() + rect.width() - rightpos, rect.height() - bottomHeight,
item->sizeHint().width(), item->sizeHint().height()));
}
}
}
QSize FlagLayout::sizeHint() const
{
return calculateSize(SizeHint);
}
QLayoutItem *FlagLayout::takeAt(int index)
{
if (index >= 0 && index < list.size()) {
ItemWrapper *layoutStruct = list.takeAt(index);
return layoutStruct->item;
}
return 0;
}
void FlagLayout::add(QLayoutItem *item, Position position)
{
list.append(new ItemWrapper(item, position));
}
QSize FlagLayout::calculateSize(SizeType sizeType) const
{
QSize totalSize;
for (int i = 0; i < list.size(); ++i) {
ItemWrapper *wrapper = list.at(i);
QSize itemSize;
if (sizeType == MinimumSize)
itemSize = wrapper->item->minimumSize();
else // (sizeType == SizeHint)
itemSize = wrapper->item->sizeHint();
totalSize.rheight() += itemSize.height();
totalSize.rwidth() = qMax<int>(totalSize.width(),itemSize.width());
}
return totalSize;
}
TYPESYSTEM_SOURCE_ABSTRACT(Gui::GLFlagWindow, Gui::GLGraphicsItem);
GLFlagWindow::GLFlagWindow(View3DInventorViewer* view) : _viewer(view), _flagLayout(0)
{
}
GLFlagWindow::~GLFlagWindow()
{
deleteFlags();
if (_flagLayout)
_flagLayout->deleteLater();
}
void GLFlagWindow::deleteFlags()
{
if (_flagLayout) {
int ct = _flagLayout->count();
for (int i=0; i<ct;i++) {
QWidget* flag = _flagLayout->itemAt(0)->widget();
if (flag) {
_flagLayout->removeWidget(flag);
flag->deleteLater();
}
}
#if defined(HAVE_QT5_OPENGL)
if (ct > 0)
_viewer->getSoRenderManager()->scheduleRedraw();
#endif
}
}
void GLFlagWindow::addFlag(Flag* item, FlagLayout::Position pos)
{
if (!_flagLayout) {
_flagLayout = new FlagLayout(3);
_viewer->setLayout(_flagLayout);
}
item->setParent(_viewer);
_flagLayout->addWidget(item, pos);
item->show();
_viewer->getSoRenderManager()->scheduleRedraw();
}
void GLFlagWindow::removeFlag(Flag* item)
{
if (_flagLayout) {
_flagLayout->removeWidget(item);
#if defined(HAVE_QT5_OPENGL)
_viewer->getSoRenderManager()->scheduleRedraw();
#endif
}
}
Flag* GLFlagWindow::getFlag(int index) const
{
if (_flagLayout) {
QWidget* flag = _flagLayout->itemAt(index)->widget();
return qobject_cast<Flag*>(flag);
}
return 0;
}
int GLFlagWindow::countFlags() const
{
if (_flagLayout) {
return _flagLayout->count();
}
return 0;
}
void GLFlagWindow::paintGL()
{
// draw lines for the flags
if (_flagLayout) {
// it can happen that the GL widget gets replaced internally (SoQt only, not with quarter) which
// causes to destroy the FlagLayout instance
int ct = _flagLayout->count();
const SbViewportRegion vp = _viewer->getSoRenderManager()->getViewportRegion();
SbVec2s size = vp.getViewportSizePixels();
float aspectratio = float(size[0])/float(size[1]);
SbViewVolume vv = _viewer->getSoRenderManager()->getCamera()->getViewVolume(aspectratio);
for (int i=0; i<ct;i++) {
Flag* flag = qobject_cast<Flag*>(_flagLayout->itemAt(i)->widget());
if (flag) {
SbVec3f pt = flag->getOrigin();
vv.projectToScreen(pt, pt);
int tox = (int)(pt[0] * size[0]);
int toy = (int)((1.0f-pt[1]) * size[1]);
flag->drawLine(_viewer, tox, toy);
}
}
}
}
#include "moc_Flag.cpp"
<|endoftext|> |
<commit_before>//===--- MiscTidyModule.cpp - clang-tidy ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "../ClangTidy.h"
#include "../ClangTidyModule.h"
#include "../ClangTidyModuleRegistry.h"
#include "DispatchOnceNonstaticCheck.h"
namespace clang {
namespace tidy {
namespace darwin {
class DarwinModule : public ClangTidyModule {
public:
void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
CheckFactories.registerCheck<DispatchOnceNonstaticCheck>(
"darwin-dispatch-once-nonstatic");
}
};
} // namespace darwin
// Register the DarwinTidyModule using this statically initialized variable.
static ClangTidyModuleRegistry::Add<darwin::DarwinModule>
X("misc-module", "Adds miscellaneous lint checks.");
// This anchor is used to force the linker to link in the generated object file
// and thus register the DarwinModule.
volatile int DarwinModuleAnchorSource = 0;
} // namespace tidy
} // namespace clang
<commit_msg>[clang-tidy] Fix module registry name and description for Darwin clang-tidy module.<commit_after>//===--- MiscTidyModule.cpp - clang-tidy ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "../ClangTidy.h"
#include "../ClangTidyModule.h"
#include "../ClangTidyModuleRegistry.h"
#include "DispatchOnceNonstaticCheck.h"
namespace clang {
namespace tidy {
namespace darwin {
class DarwinModule : public ClangTidyModule {
public:
void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
CheckFactories.registerCheck<DispatchOnceNonstaticCheck>(
"darwin-dispatch-once-nonstatic");
}
};
} // namespace darwin
// Register the DarwinTidyModule using this statically initialized variable.
static ClangTidyModuleRegistry::Add<darwin::DarwinModule>
X("darwin-module", "Adds Darwin-specific lint checks.");
// This anchor is used to force the linker to link in the generated object file
// and thus register the DarwinModule.
volatile int DarwinModuleAnchorSource = 0;
} // namespace tidy
} // namespace clang
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: sdclient.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: ka $ $Date: 2001-10-22 13:36:50 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _IPOBJ_HXX //autogen
#include <so3/ipobj.hxx>
#endif
#ifndef _SVDOOLE2_HXX //autogen
#include <svx/svdoole2.hxx>
#endif
#ifndef _SVDOGRAF_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _CLIENT_HXX //autogen
#include <so3/client.hxx>
#endif
#ifndef _IPENV_HXX //autogen
#include <so3/ipenv.hxx>
#endif
#ifndef _SVDPAGV_HXX
#include <svx/svdpagv.hxx>
#endif
#pragma hdrstop
#include "misc.hxx"
#ifdef STARIMAGE_AVAILABLE
#ifndef _SIMDLL_HXX
#include <sim2/simdll.hxx>
#endif
#endif
#include "strings.hrc"
#include "sdclient.hxx"
#include "viewshel.hxx"
#include "drviewsh.hxx"
#include "sdview.hxx"
#include "sdwindow.hxx"
#include "sdresid.hxx"
/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/
SdClient::SdClient(SdrOle2Obj* pObj, SdViewShell* pSdViewShell, Window* pWindow) :
SfxInPlaceClient(pSdViewShell, pWindow),
pViewShell(pSdViewShell),
pSdrOle2Obj(pObj),
pSdrGrafObj(NULL),
pOutlinerParaObj (NULL)
{
}
/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/
SdClient::~SdClient()
{
}
/*************************************************************************
|*
|* Wenn IP-aktiv, dann kommt diese Anforderung um Vergroesserung des
|* sichtbaren Ausschnitts des Objektes
|*
\************************************************************************/
void SdClient::RequestObjAreaPixel(const Rectangle& rRect)
{
Window* pWin = pViewShell->GetWindow();
Rectangle aObjRect( pWin->PixelToLogic( rRect.TopLeft() ),
pWin->PixelToLogic( rRect.GetSize() ) );
SdView* pView = pViewShell->GetView();
Rectangle aWorkArea( pView->GetWorkArea() );
if (!aWorkArea.IsInside(aObjRect))
{
// Position korrigieren
Point aPos = aObjRect.TopLeft();
Size aSize = aObjRect.GetSize();
Point aWorkAreaTL = aWorkArea.TopLeft();
Point aWorkAreaBR = aWorkArea.BottomRight();
aPos.X() = Max(aPos.X(), aWorkAreaTL.X());
aPos.X() = Min(aPos.X(), aWorkAreaBR.X()-aSize.Width());
aPos.Y() = Max(aPos.Y(), aWorkAreaTL.Y());
aPos.Y() = Min(aPos.Y(), aWorkAreaBR.Y()-aSize.Height());
aObjRect.SetPos(aPos);
SfxInPlaceClient::RequestObjAreaPixel(pViewShell->GetWindow()->
LogicToPixel(aObjRect) );
}
else
{
SfxInPlaceClient::RequestObjAreaPixel(rRect);
}
const SdrMarkList& rMarkList = pView->GetMarkList();
if (rMarkList.GetMarkCount() == 1)
{
SdrMark* pMark = rMarkList.GetMark(0);
SdrObject* pObj = pMark->GetObj();
Rectangle aOldRect( pObj->GetLogicRect() );
if ( aObjRect != aOldRect )
{
// Rundungsfehler vermeiden - nur, wenn mindestens 1 Pixel Unterschied
// (getrennt fuer Position und Groesse)
Size aOnePixel = pWin->PixelToLogic( Size(1, 1) );
Size aLogicSize = aObjRect.GetSize();
Rectangle aNewRect = aOldRect;
Size aNewSize = aNewRect.GetSize();
if ( Abs( aObjRect.Left() - aOldRect.Left() ) >= aOnePixel.Width() )
aNewRect.SetPos( Point( aObjRect.Left(), aNewRect.Top() ) );
if ( Abs( aObjRect.Top() - aOldRect.Top() ) >= aOnePixel.Height() )
aNewRect.SetPos( Point( aNewRect.Left(), aObjRect.Top() ) );
if ( Abs( aLogicSize.Width() - aNewSize.Width() ) >= aOnePixel.Width() )
aNewSize.Width() = aLogicSize.Width();
if ( Abs( aLogicSize.Height() - aNewSize.Height() ) >= aOnePixel.Height() )
aNewSize.Height() = aLogicSize.Height();
aNewRect.SetSize( aNewSize );
if ( aNewRect != aOldRect ) // veraendert nur, wenn mindestens 1 Pixel
pObj->SetLogicRect( aNewRect );
}
}
}
/*************************************************************************
|*
|*
|*
\************************************************************************/
void SdClient::ViewChanged(USHORT nAspect)
{
// Eventuell neues MetaFile holen
SfxInPlaceClient::ViewChanged(nAspect);
if (pViewShell->GetActiveWindow())
{
SdView* pView = pViewShell->GetView();
if (pView)
{
// Der sichtbare Ausschnitt hat sich eventuell geaendert
SvEmbeddedObject* pObj = GetEmbedObj();
const MapMode aMap100( MAP_100TH_MM );
Rectangle aObjVisArea( OutputDevice::LogicToLogic( pObj->GetVisArea(),
pObj->GetMapUnit(),
aMap100 ) );
Size aVisSize( aObjVisArea.GetSize() );
SvClientData* pClientData = GetEnv();
if( pClientData )
{
Fraction aFractX( pClientData->GetScaleWidth() );
Fraction aFractY( pClientData->GetScaleHeight() );
aVisSize = Size( (long) ( aFractX *= aVisSize.Width() ), (long) ( aFractY *= aVisSize.Height() ) );
Rectangle aLogicRect( pSdrOle2Obj->GetLogicRect() );
Rectangle aObjArea( aLogicRect );
aObjArea.SetSize( aObjVisArea.GetSize() );
pClientData->SetObjArea( aObjArea );
const Size aVisSizePix( Application::GetDefaultDevice()->LogicToPixel( aVisSize, aMap100 ) );
const Size aObjSizePix( Application::GetDefaultDevice()->LogicToPixel( aLogicRect.GetSize(), aMap100 ) );
if( aVisSizePix != aObjSizePix )
{
aLogicRect.SetSize(aVisSize);
pSdrOle2Obj->SetLogicRect(aLogicRect);
pSdrOle2Obj->SendRepaintBroadcast();
}
}
}
}
}
/*************************************************************************
|*
|* InPlace-Objekt aktivieren / deaktivieren
|*
\************************************************************************/
void SdClient::UIActivate(BOOL bActivate)
{
SfxInPlaceClient::UIActivate(bActivate);
if (!bActivate)
{
#ifdef STARIMAGE_AVAILABLE
if (pSdrGrafObj && pViewShell->GetActiveWindow())
{
// Das Ole2Obj (Image) wird gegen das GrafObj ausgetauscht
pSdrGrafObj->SetLogicRect(pSdrOle2Obj->GetLogicRect());
SvInPlaceObjectRef aIPObj = pSdrOle2Obj->GetObjRef();
pSdrGrafObj->SetGraphic ( SimDLL::GetGraphic( aIPObj ) );
SdView* pView = pViewShell->GetView();
SdrPageView* pPV = pView->GetPageViewPvNum(0);
SdrPage* pPg = pPV->GetPage();
delete pPg->RemoveObject( pSdrOle2Obj->GetOrdNum() );
pSdrGrafObj = NULL;
}
#endif
}
}
/*************************************************************************
|*
|* Daten fuer eine ggf. spaeter zu erzeugende View
|*
\************************************************************************/
void SdClient::MakeViewData()
{
SfxInPlaceClient::MakeViewData();
SvClientData* pCD = GetClientData();
if (pCD)
{
SvEmbeddedObject* pObj = GetEmbedObj();
Rectangle aObjVisArea = OutputDevice::LogicToLogic(
pObj->GetVisArea(), pObj->GetMapUnit(),
MAP_100TH_MM );
Size aVisSize = aObjVisArea.GetSize();
Fraction aFractX = pCD->GetScaleWidth();
Fraction aFractY = pCD->GetScaleHeight();
aFractX *= aVisSize.Width();
aFractY *= aVisSize.Height();
pCD->SetSizeScale(aFractX, aFractY);
Rectangle aObjArea = pSdrOle2Obj->GetLogicRect();
pCD->SetObjArea(aObjArea);
}
}
/*************************************************************************
|*
|* Objekt in den sichtbaren Breich scrollen
|*
\************************************************************************/
void SdClient::MakeVisible()
{
SfxInPlaceClient::MakeVisible();
if (pViewShell->ISA(SdDrawViewShell))
{
((SdDrawViewShell*) pViewShell)->MakeVisible(pSdrOle2Obj->GetLogicRect(),
*pViewShell->GetActiveWindow());
}
}
<commit_msg>#94774#: optimized OLE change handling<commit_after>/*************************************************************************
*
* $RCSfile: sdclient.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: ka $ $Date: 2001-12-05 15:24:58 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _IPOBJ_HXX //autogen
#include <so3/ipobj.hxx>
#endif
#ifndef _SVDOOLE2_HXX //autogen
#include <svx/svdoole2.hxx>
#endif
#ifndef _SVDOGRAF_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _CLIENT_HXX //autogen
#include <so3/client.hxx>
#endif
#ifndef _IPENV_HXX //autogen
#include <so3/ipenv.hxx>
#endif
#ifndef _SVDPAGV_HXX
#include <svx/svdpagv.hxx>
#endif
#pragma hdrstop
#include "misc.hxx"
#ifdef STARIMAGE_AVAILABLE
#ifndef _SIMDLL_HXX
#include <sim2/simdll.hxx>
#endif
#endif
#include "strings.hrc"
#include "sdclient.hxx"
#include "viewshel.hxx"
#include "drviewsh.hxx"
#include "sdview.hxx"
#include "sdwindow.hxx"
#include "sdresid.hxx"
/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/
SdClient::SdClient(SdrOle2Obj* pObj, SdViewShell* pSdViewShell, Window* pWindow) :
SfxInPlaceClient(pSdViewShell, pWindow),
pViewShell(pSdViewShell),
pSdrOle2Obj(pObj),
pSdrGrafObj(NULL),
pOutlinerParaObj (NULL)
{
}
/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/
SdClient::~SdClient()
{
}
/*************************************************************************
|*
|* Wenn IP-aktiv, dann kommt diese Anforderung um Vergroesserung des
|* sichtbaren Ausschnitts des Objektes
|*
\************************************************************************/
void SdClient::RequestObjAreaPixel(const Rectangle& rRect)
{
Window* pWin = pViewShell->GetWindow();
Rectangle aObjRect( pWin->PixelToLogic( rRect.TopLeft() ),
pWin->PixelToLogic( rRect.GetSize() ) );
SdView* pView = pViewShell->GetView();
Rectangle aWorkArea( pView->GetWorkArea() );
if (!aWorkArea.IsInside(aObjRect))
{
// Position korrigieren
Point aPos = aObjRect.TopLeft();
Size aSize = aObjRect.GetSize();
Point aWorkAreaTL = aWorkArea.TopLeft();
Point aWorkAreaBR = aWorkArea.BottomRight();
aPos.X() = Max(aPos.X(), aWorkAreaTL.X());
aPos.X() = Min(aPos.X(), aWorkAreaBR.X()-aSize.Width());
aPos.Y() = Max(aPos.Y(), aWorkAreaTL.Y());
aPos.Y() = Min(aPos.Y(), aWorkAreaBR.Y()-aSize.Height());
aObjRect.SetPos(aPos);
SfxInPlaceClient::RequestObjAreaPixel(pViewShell->GetWindow()->
LogicToPixel(aObjRect) );
}
else
{
SfxInPlaceClient::RequestObjAreaPixel(rRect);
}
const SdrMarkList& rMarkList = pView->GetMarkList();
if (rMarkList.GetMarkCount() == 1)
{
SdrMark* pMark = rMarkList.GetMark(0);
SdrObject* pObj = pMark->GetObj();
Rectangle aOldRect( pObj->GetLogicRect() );
if ( aObjRect != aOldRect )
{
// Rundungsfehler vermeiden - nur, wenn mindestens 1 Pixel Unterschied
// (getrennt fuer Position und Groesse)
Size aOnePixel = pWin->PixelToLogic( Size(1, 1) );
Size aLogicSize = aObjRect.GetSize();
Rectangle aNewRect = aOldRect;
Size aNewSize = aNewRect.GetSize();
if ( Abs( aObjRect.Left() - aOldRect.Left() ) >= aOnePixel.Width() )
aNewRect.SetPos( Point( aObjRect.Left(), aNewRect.Top() ) );
if ( Abs( aObjRect.Top() - aOldRect.Top() ) >= aOnePixel.Height() )
aNewRect.SetPos( Point( aNewRect.Left(), aObjRect.Top() ) );
if ( Abs( aLogicSize.Width() - aNewSize.Width() ) >= aOnePixel.Width() )
aNewSize.Width() = aLogicSize.Width();
if ( Abs( aLogicSize.Height() - aNewSize.Height() ) >= aOnePixel.Height() )
aNewSize.Height() = aLogicSize.Height();
aNewRect.SetSize( aNewSize );
if ( aNewRect != aOldRect ) // veraendert nur, wenn mindestens 1 Pixel
pObj->SetLogicRect( aNewRect );
}
}
}
/*************************************************************************
|*
|*
|*
\************************************************************************/
void SdClient::ViewChanged(USHORT nAspect)
{
// Eventuell neues MetaFile holen
SfxInPlaceClient::ViewChanged(nAspect);
if (pViewShell->GetActiveWindow())
{
SdView* pView = pViewShell->GetView();
if (pView)
{
SvClientData* pData = GetEnv();
if( pData )
{
SvEmbeddedObject* pObj = GetEmbedObj();
MapMode aMap100( MAP_100TH_MM );
Rectangle aVisArea( OutputDevice::LogicToLogic( pObj->GetVisArea(), pObj->GetMapUnit(), aMap100 ) );
Rectangle aLogicRect( pSdrOle2Obj->GetLogicRect() );
Size aScaledSize( static_cast< long >( pData->GetScaleWidth() * Fraction( aVisArea.GetWidth() ) ),
static_cast< long >( pData->GetScaleHeight() * Fraction( aVisArea.GetHeight() ) ) );
if( Application::GetDefaultDevice()->LogicToPixel( aScaledSize, aMap100 ) !=
Application::GetDefaultDevice()->LogicToPixel( aLogicRect.GetSize(), aMap100 ) )
{
const sal_Bool bOldLock = pView->GetModel()->isLocked();
pView->GetModel()->setLock( sal_True );
pSdrOle2Obj->SetLogicRect( Rectangle( aLogicRect.TopLeft(), aScaledSize ) );
pView->GetModel()->setLock( bOldLock );
pSdrOle2Obj->SendRepaintBroadcast();
}
}
}
}
}
/*************************************************************************
|*
|* InPlace-Objekt aktivieren / deaktivieren
|*
\************************************************************************/
void SdClient::UIActivate(BOOL bActivate)
{
SfxInPlaceClient::UIActivate(bActivate);
if (!bActivate)
{
#ifdef STARIMAGE_AVAILABLE
if (pSdrGrafObj && pViewShell->GetActiveWindow())
{
// Das Ole2Obj (Image) wird gegen das GrafObj ausgetauscht
pSdrGrafObj->SetLogicRect(pSdrOle2Obj->GetLogicRect());
SvInPlaceObjectRef aIPObj = pSdrOle2Obj->GetObjRef();
pSdrGrafObj->SetGraphic ( SimDLL::GetGraphic( aIPObj ) );
SdView* pView = pViewShell->GetView();
SdrPageView* pPV = pView->GetPageViewPvNum(0);
SdrPage* pPg = pPV->GetPage();
delete pPg->RemoveObject( pSdrOle2Obj->GetOrdNum() );
pSdrGrafObj = NULL;
}
#endif
}
}
/*************************************************************************
|*
|* Daten fuer eine ggf. spaeter zu erzeugende View
|*
\************************************************************************/
void SdClient::MakeViewData()
{
SfxInPlaceClient::MakeViewData();
SvClientData* pCD = GetClientData();
if (pCD)
{
SvEmbeddedObject* pObj = GetEmbedObj();
Rectangle aObjVisArea = OutputDevice::LogicToLogic(
pObj->GetVisArea(), pObj->GetMapUnit(),
MAP_100TH_MM );
Size aVisSize = aObjVisArea.GetSize();
Fraction aFractX = pCD->GetScaleWidth();
Fraction aFractY = pCD->GetScaleHeight();
aFractX *= aVisSize.Width();
aFractY *= aVisSize.Height();
pCD->SetSizeScale(aFractX, aFractY);
Rectangle aObjArea = pSdrOle2Obj->GetLogicRect();
pCD->SetObjArea(aObjArea);
}
}
/*************************************************************************
|*
|* Objekt in den sichtbaren Breich scrollen
|*
\************************************************************************/
void SdClient::MakeVisible()
{
SfxInPlaceClient::MakeVisible();
if (pViewShell->ISA(SdDrawViewShell))
{
((SdDrawViewShell*) pViewShell)->MakeVisible(pSdrOle2Obj->GetLogicRect(),
*pViewShell->GetActiveWindow());
}
}
<|endoftext|> |
<commit_before>// Scintilla source code edit control
/** @file LexForth.cxx
** Lexer for FORTH
**/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
static inline bool IsAWordChar(int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '.' ||
ch == '_' || ch == '?' || ch == '"' || ch == '@' ||
ch == '!' || ch == '[' || ch == ']' || ch == '/' ||
ch == '+' || ch == '-' || ch == '*' || ch == '<' ||
ch == '>' || ch == '=' || ch == ';' || ch == '(' ||
ch == ')' );
}
static inline bool IsAWordStart(int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '.');
}
static inline bool IsANumChar(int ch) {
return (ch < 0x80) && (isxdigit(ch) || ch == '.' || ch == 'e' || ch == 'E' );
}
static inline bool IsASpaceChar(int ch) {
return (ch < 0x80) && isspace(ch);
}
static void ColouriseForthDoc(unsigned int startPos, int length, int initStyle, WordList *keywordLists[],
Accessor &styler) {
WordList &control = *keywordLists[0];
WordList &keyword = *keywordLists[1];
WordList &defword = *keywordLists[2];
WordList &preword1 = *keywordLists[3];
WordList &preword2 = *keywordLists[4];
WordList &strings = *keywordLists[5];
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward())
{
// Determine if the current state should terminate.
if (sc.state == SCE_FORTH_COMMENT) {
if (sc.atLineEnd) {
sc.SetState(SCE_FORTH_DEFAULT);
}
}else if (sc.state == SCE_FORTH_COMMENT_ML) {
if (sc.ch == ')') {
sc.ForwardSetState(SCE_FORTH_DEFAULT);
}
}else if (sc.state == SCE_FORTH_IDENTIFIER || sc.state == SCE_FORTH_NUMBER) {
// handle numbers here too, because what we thought was a number might
// turn out to be a keyword e.g. 2DUP
if (IsASpaceChar(sc.ch) ) {
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
int newState = sc.state == SCE_FORTH_NUMBER ? SCE_FORTH_NUMBER : SCE_FORTH_DEFAULT;
if (control.InList(s)) {
sc.ChangeState(SCE_FORTH_CONTROL);
} else if (keyword.InList(s)) {
sc.ChangeState(SCE_FORTH_KEYWORD);
} else if (defword.InList(s)) {
sc.ChangeState(SCE_FORTH_DEFWORD);
} else if (preword1.InList(s)) {
sc.ChangeState(SCE_FORTH_PREWORD1);
} else if (preword2.InList(s)) {
sc.ChangeState(SCE_FORTH_PREWORD2);
} else if (strings.InList(s)) {
sc.ChangeState(SCE_FORTH_STRING);
newState = SCE_FORTH_STRING;
}
sc.SetState(newState);
}
if (sc.state == SCE_FORTH_NUMBER) {
if (IsASpaceChar(sc.ch)) {
sc.SetState(SCE_FORTH_DEFAULT);
}
}
}else if (sc.state == SCE_FORTH_STRING) {
if (sc.ch == '\"') {
sc.ForwardSetState(SCE_FORTH_DEFAULT);
}
}else if (sc.state == SCE_FORTH_LOCALE) {
if (sc.ch == '}') {
sc.ForwardSetState(SCE_FORTH_DEFAULT);
}
}else if (sc.state == SCE_FORTH_DEFWORD) {
if (IsASpaceChar(sc.ch)) {
sc.SetState(SCE_FORTH_DEFAULT);
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_FORTH_DEFAULT) {
if (sc.ch == '\\'){
sc.SetState(SCE_FORTH_COMMENT);
} else if (sc.ch == '(' &&
(sc.atLineStart || IsASpaceChar(sc.chPrev)) &&
(sc.atLineEnd || IsASpaceChar(sc.chNext))) {
sc.SetState(SCE_FORTH_COMMENT_ML);
} else if ( (sc.ch == '$' && (isascii(sc.chNext) && isxdigit(sc.chNext))) ) {
// number starting with $ is a hex number
sc.SetState(SCE_FORTH_NUMBER);
while(sc.More() && isascii(sc.chNext) && isxdigit(sc.chNext))
sc.Forward();
} else if ( (sc.ch == '%' && (isascii(sc.chNext) && (sc.chNext == '0' || sc.chNext == '1'))) ) {
// number starting with % is binary
sc.SetState(SCE_FORTH_NUMBER);
while(sc.More() && isascii(sc.chNext) && (sc.chNext == '0' || sc.chNext == '1'))
sc.Forward();
} else if ( isascii(sc.ch) &&
(isxdigit(sc.ch) || ((sc.ch == '.' || sc.ch == '-') && isascii(sc.chNext) && isxdigit(sc.chNext)) )
){
sc.SetState(SCE_FORTH_NUMBER);
} else if (IsAWordStart(sc.ch)) {
sc.SetState(SCE_FORTH_IDENTIFIER);
} else if (sc.ch == '{') {
sc.SetState(SCE_FORTH_LOCALE);
} else if (sc.ch == ':' && isascii(sc.chNext) && isspace(sc.chNext)) {
// highlight word definitions e.g. : GCD ( n n -- n ) ..... ;
// ^ ^^^
sc.SetState(SCE_FORTH_DEFWORD);
while(sc.More() && isascii(sc.chNext) && isspace(sc.chNext))
sc.Forward();
} else if (sc.ch == ';' &&
(sc.atLineStart || IsASpaceChar(sc.chPrev)) &&
(sc.atLineEnd || IsASpaceChar(sc.chNext)) ) {
// mark the ';' that ends a word
sc.SetState(SCE_FORTH_DEFWORD);
sc.ForwardSetState(SCE_FORTH_DEFAULT);
}
}
}
sc.Complete();
}
static void FoldForthDoc(unsigned int, int, int, WordList *[],
Accessor &) {
}
static const char * const forthWordLists[] = {
"control keywords",
"keywords",
"definition words",
"prewords with one argument",
"prewords with two arguments",
"string definition keywords",
0,
};
LexerModule lmForth(SCLEX_FORTH, ColouriseForthDoc, "forth", FoldForthDoc, forthWordLists);
<commit_msg>Bug #2806565 FORTH lexer is too keen to mark things as numbers.<commit_after>// Scintilla source code edit control
/** @file LexForth.cxx
** Lexer for FORTH
**/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
static inline bool IsAWordChar(int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '.' ||
ch == '_' || ch == '?' || ch == '"' || ch == '@' ||
ch == '!' || ch == '[' || ch == ']' || ch == '/' ||
ch == '+' || ch == '-' || ch == '*' || ch == '<' ||
ch == '>' || ch == '=' || ch == ';' || ch == '(' ||
ch == ')' );
}
static inline bool IsAWordStart(int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '.');
}
static inline bool IsANumChar(int ch) {
return (ch < 0x80) && (isxdigit(ch) || ch == '.' || ch == 'e' || ch == 'E' );
}
static inline bool IsASpaceChar(int ch) {
return (ch < 0x80) && isspace(ch);
}
static void ColouriseForthDoc(unsigned int startPos, int length, int initStyle, WordList *keywordLists[],
Accessor &styler) {
WordList &control = *keywordLists[0];
WordList &keyword = *keywordLists[1];
WordList &defword = *keywordLists[2];
WordList &preword1 = *keywordLists[3];
WordList &preword2 = *keywordLists[4];
WordList &strings = *keywordLists[5];
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward())
{
// Determine if the current state should terminate.
if (sc.state == SCE_FORTH_COMMENT) {
if (sc.atLineEnd) {
sc.SetState(SCE_FORTH_DEFAULT);
}
}else if (sc.state == SCE_FORTH_COMMENT_ML) {
if (sc.ch == ')') {
sc.ForwardSetState(SCE_FORTH_DEFAULT);
}
}else if (sc.state == SCE_FORTH_IDENTIFIER || sc.state == SCE_FORTH_NUMBER) {
// handle numbers here too, because what we thought was a number might
// turn out to be a keyword e.g. 2DUP
if (IsASpaceChar(sc.ch) ) {
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
int newState = sc.state == SCE_FORTH_NUMBER ? SCE_FORTH_NUMBER : SCE_FORTH_DEFAULT;
if (control.InList(s)) {
sc.ChangeState(SCE_FORTH_CONTROL);
} else if (keyword.InList(s)) {
sc.ChangeState(SCE_FORTH_KEYWORD);
} else if (defword.InList(s)) {
sc.ChangeState(SCE_FORTH_DEFWORD);
} else if (preword1.InList(s)) {
sc.ChangeState(SCE_FORTH_PREWORD1);
} else if (preword2.InList(s)) {
sc.ChangeState(SCE_FORTH_PREWORD2);
} else if (strings.InList(s)) {
sc.ChangeState(SCE_FORTH_STRING);
newState = SCE_FORTH_STRING;
}
sc.SetState(newState);
}
if (sc.state == SCE_FORTH_NUMBER) {
if (IsASpaceChar(sc.ch)) {
sc.SetState(SCE_FORTH_DEFAULT);
} else if (!IsANumChar(sc.ch)) {
sc.ChangeState(SCE_FORTH_IDENTIFIER);
}
}
}else if (sc.state == SCE_FORTH_STRING) {
if (sc.ch == '\"') {
sc.ForwardSetState(SCE_FORTH_DEFAULT);
}
}else if (sc.state == SCE_FORTH_LOCALE) {
if (sc.ch == '}') {
sc.ForwardSetState(SCE_FORTH_DEFAULT);
}
}else if (sc.state == SCE_FORTH_DEFWORD) {
if (IsASpaceChar(sc.ch)) {
sc.SetState(SCE_FORTH_DEFAULT);
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_FORTH_DEFAULT) {
if (sc.ch == '\\'){
sc.SetState(SCE_FORTH_COMMENT);
} else if (sc.ch == '(' &&
(sc.atLineStart || IsASpaceChar(sc.chPrev)) &&
(sc.atLineEnd || IsASpaceChar(sc.chNext))) {
sc.SetState(SCE_FORTH_COMMENT_ML);
} else if ( (sc.ch == '$' && (isascii(sc.chNext) && isxdigit(sc.chNext))) ) {
// number starting with $ is a hex number
sc.SetState(SCE_FORTH_NUMBER);
while(sc.More() && isascii(sc.chNext) && isxdigit(sc.chNext))
sc.Forward();
} else if ( (sc.ch == '%' && (isascii(sc.chNext) && (sc.chNext == '0' || sc.chNext == '1'))) ) {
// number starting with % is binary
sc.SetState(SCE_FORTH_NUMBER);
while(sc.More() && isascii(sc.chNext) && (sc.chNext == '0' || sc.chNext == '1'))
sc.Forward();
} else if ( isascii(sc.ch) &&
(isxdigit(sc.ch) || ((sc.ch == '.' || sc.ch == '-') && isascii(sc.chNext) && isxdigit(sc.chNext)) )
){
sc.SetState(SCE_FORTH_NUMBER);
} else if (IsAWordStart(sc.ch)) {
sc.SetState(SCE_FORTH_IDENTIFIER);
} else if (sc.ch == '{') {
sc.SetState(SCE_FORTH_LOCALE);
} else if (sc.ch == ':' && isascii(sc.chNext) && isspace(sc.chNext)) {
// highlight word definitions e.g. : GCD ( n n -- n ) ..... ;
// ^ ^^^
sc.SetState(SCE_FORTH_DEFWORD);
while(sc.More() && isascii(sc.chNext) && isspace(sc.chNext))
sc.Forward();
} else if (sc.ch == ';' &&
(sc.atLineStart || IsASpaceChar(sc.chPrev)) &&
(sc.atLineEnd || IsASpaceChar(sc.chNext)) ) {
// mark the ';' that ends a word
sc.SetState(SCE_FORTH_DEFWORD);
sc.ForwardSetState(SCE_FORTH_DEFAULT);
}
}
}
sc.Complete();
}
static void FoldForthDoc(unsigned int, int, int, WordList *[],
Accessor &) {
}
static const char * const forthWordLists[] = {
"control keywords",
"keywords",
"definition words",
"prewords with one argument",
"prewords with two arguments",
"string definition keywords",
0,
};
LexerModule lmForth(SCLEX_FORTH, ColouriseForthDoc, "forth", FoldForthDoc, forthWordLists);
<|endoftext|> |
<commit_before>#include "espresso_core.h"
int main(int argc, char** argv) {
handle_cmd_args(argc, argv);
// TODO: open filesystem data for when you need it
// filepath is argv[FILESYSTEM]
char storage_file[] = ".data_storage";
char *file = (char *)malloc(strlen (argv[FILESYSTEM]) +
strlen (storage_file) + 1);
strcpy (file, argv[FILESYSTEM]);
strcat (file, storage_file);
printf ("Opening storage file %s\n", file);
int storage_file_fd;
if ((storage_file_fd = open (file, O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR)) < 0) {
perror("Unable to open data storage file.");
exit (EXIT_FAILURE);
}
printf ("storage file open (%d)\n", storage_file_fd);
espresso_global_data_init (storage_file_fd, NODE_STORAGE_SIZE);
char* barista_hostname = argv[BARISTA_HOSTNAME];
int barista_port = atoi(argv[BARISTA_PORT]);
int node_id = atoi(argv[NODE_ID]);
EspressoClient espresso(barista_hostname, barista_port, node_id);
espresso.openConnection();
espresso.run();
// the svc_main_loop function lives in network core and
// calls registered espresso functions as it receives the rpcs
//svc_main_loop(argc, argv);
return 0;
}
void handle_cmd_args(int argc, char** argv) {
if (argc == NUM_EXPECTED_ARGS) {
}
else {
fprintf(stderr, "%s exiting: invalid command line arguments provided", argv[0]);
fprintf(stderr, "\nUsage: %s <node_id> <persistent metadata path> <data path> <barista hostname> <barista port>\n", argv[0]);
exit(-1);
}
}
<commit_msg>I think this should make the espresso node work<commit_after>#include "espresso_core.h"
int main(int argc, char** argv) {
handle_cmd_args(argc, argv);
// TODO: open filesystem data for when you need it
// filepath is argv[FILESYSTEM]
char storage_file[] = ".data_storage";
char *file = (char *)malloc(strlen (argv[FILESYSTEM]) +
strlen (storage_file) + 1);
strcpy (file, argv[FILESYSTEM]);
strcat (file, storage_file);
printf ("Opening storage file %s\n", file);
int storage_file_fd;
if ((storage_file_fd = open (file, O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR)) < 0) {
perror("Unable to open data storage file.");
exit (EXIT_FAILURE);
}
printf ("storage file open (%d)\n", storage_file_fd);
espresso_global_data_init (argv[FILESYSTEM], NODE_STORAGE_SIZE);
char* barista_hostname = argv[BARISTA_HOSTNAME];
int barista_port = atoi(argv[BARISTA_PORT]);
int node_id = atoi(argv[NODE_ID]);
EspressoClient espresso(barista_hostname, barista_port, node_id);
espresso.openConnection();
espresso.run();
// the svc_main_loop function lives in network core and
// calls registered espresso functions as it receives the rpcs
//svc_main_loop(argc, argv);
return 0;
}
void handle_cmd_args(int argc, char** argv) {
if (argc == NUM_EXPECTED_ARGS) {
}
else {
fprintf(stderr, "%s exiting: invalid command line arguments provided", argv[0]);
fprintf(stderr, "\nUsage: %s <node_id> <persistent metadata path> <data path> <barista hostname> <barista port>\n", argv[0]);
exit(-1);
}
}
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <es-log/trace-log.h>
#include <QtGui>
#include <functional>
#include <boost/bind.hpp>
#include <boost/assign.hpp>
#include <boost/assign/std/vector.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <Core/Utils/Legacy/MemoryUtil.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Interface/Application/GuiLogger.h>
#include <Interface/Application/SCIRunMainWindow.h>
#include <Interface/Application/NetworkEditor.h>
#include <Interface/Application/ProvenanceWindow.h>
#include <Interface/Application/DeveloperConsole.h>
#include <Interface/Application/Connection.h>
#include <Interface/Application/PreferencesWindow.h>
#include <Interface/Application/TagManagerWindow.h>
#include <Interface/Application/ShortcutsInterface.h>
#include <Interface/Application/TreeViewCollaborators.h>
#include <Interface/Application/MainWindowCollaborators.h>
#include <Interface/Application/GuiCommands.h>
#include <Interface/Application/NetworkEditorControllerGuiProxy.h>
#include <Interface/Application/NetworkExecutionProgressBar.h>
#include <Interface/Application/DialogErrorControl.h>
#include <Interface/Modules/Base/RemembersFileDialogDirectory.h>
#include <Interface/Modules/Base/ModuleDialogGeneric.h> //TODO
#include <Interface/Application/ModuleWizard/ModuleWizard.h>
#include <Dataflow/Network/NetworkFwd.h>
#include <Dataflow/Engine/Controller/NetworkEditorController.h> //DOH! see TODO in setController
#include <Dataflow/Engine/Controller/ProvenanceManager.h>
#include <Dataflow/Network/SimpleSourceSink.h> //TODO: encapsulate!!!
#include <Dataflow/Serialization/Network/XMLSerializer.h>
#include <Core/Application/Application.h>
#include <Core/Application/Preferences/Preferences.h>
#include <Core/Logging/Log.h>
#include <Core/Thread/Parallel.h>
#include <Core/Application/Version.h>
#include <Dataflow/Serialization/Network/NetworkDescriptionSerialization.h>
#include <Core/Utils/CurrentFileName.h>
#ifdef BUILD_WITH_PYTHON
#include <Interface/Application/PythonConsoleWidget.h>
#include <Core/Python/PythonInterpreter.h>
#endif
#include "TriggeredEventsWindow.h"
#include <Dataflow/Serialization/Network/XMLSerializer.h>
using namespace SCIRun;
using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Engine;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Dataflow::State;
using namespace SCIRun::Core::Commands;
using namespace SCIRun::Core::Logging;
using namespace SCIRun::Core;
using namespace SCIRun::Core::Algorithms;
void SCIRunMainWindow::initialize()
{
postConstructionSignalHookup();
fillModuleSelector();
executeCommandLineRequests();
}
void SCIRunMainWindow::setController(NetworkEditorControllerHandle controller)
{
auto controllerProxy(boost::make_shared<NetworkEditorControllerGuiProxy>(controller, networkEditor_));
networkEditor_->setNetworkEditorController(controllerProxy);
//TODO: need better way to wire this up
controller->setSerializationManager(networkEditor_);
}
void SCIRunMainWindow::preexecute()
{
if (Preferences::Instance().saveBeforeExecute && !Application::Instance().parameters()->isRegressionMode())
{
saveNetwork();
}
}
void SCIRunMainWindow::setupQuitAfterExecute()
{
connect(networkEditor_->getNetworkEditorController().get(), SIGNAL(executionFinished(int)), this, SLOT(exitApplication(int)));
quitAfterExecute_ = true;
}
void SCIRunMainWindow::saveNetworkFile(const QString& fileName)
{
writeSettings();
NetworkSaveCommand save;
save.set(Variables::Filename, fileName.toStdString());
save.execute();
}
bool SCIRunMainWindow::loadNetworkFile(const QString& filename, bool isTemporary)
{
if (!filename.isEmpty())
{
RENDERER_LOG("Opening network file: {}", filename.toStdString());
FileOpenCommand command;
command.set(Variables::Filename, filename.toStdString());
command.set(Name("temporaryFile"), isTemporary);
if (command.execute())
{
networkProgressBar_->updateTotalModules(networkEditor_->numModules());
if (!isTemporary)
{
setCurrentFile(filename);
statusBar()->showMessage(tr("File loaded: ") + filename, 2000);
provenanceWindow_->clear();
provenanceWindow_->showFile(command.file_);
}
else
{
setCurrentFile("");
setWindowModified(true);
showStatusMessage("Toolkit network loaded. ", 2000);
}
networkEditor_->viewport()->update();
return true;
}
else
{
if (Application::Instance().parameters()->isRegressionMode())
exit(7);
//TODO: set error code to non-0 so regression tests fail!
// probably want to control this with a --regression flag.
}
}
return false;
}
bool SCIRunMainWindow::importLegacyNetworkFile(const QString& filename)
{
bool success = false;
if (!filename.isEmpty())
{
FileImportCommand command;
command.set(Variables::Filename, filename.toStdString());
if (command.execute())
{
statusBar()->showMessage(tr("File imported: ") + filename, 2000);
networkProgressBar_->updateTotalModules(networkEditor_->numModules());
networkEditor_->viewport()->update();
success = true;
}
else
{
statusBar()->showMessage(tr("File import failed: ") + filename, 2000);
}
auto log = QString::fromStdString(command.logContents());
auto isoString = boost::posix_time::to_iso_string(boost::posix_time::microsec_clock::universal_time());
auto logFileName = QString::fromStdString(Core::Logging::LogSettings::Instance().logDirectory().string())
+ "/" + ("importLog_" + strippedName(filename) + "_" + QString::fromStdString(isoString) + ".log");
QFile logFile(logFileName);
if (logFile.open(QFile::WriteOnly | QFile::Text))
{
QTextStream stream(&logFile);
stream << log;
QMessageBox::information(this, "SRN File Import", "SRN File Import log file can be found here: " + logFileName
+ "\n\nAdditionally, check the log directory for a list of missing modules (look for file missingModules.log)");
}
else
{
QMessageBox::information(this, "SRN File Import", "Failed to write SRN File Import log file: " + logFileName);
}
}
return success;
}
void SCIRunMainWindow::setCurrentFile(const QString& fileName)
{
currentFile_ = fileName;
setCurrentFileName(currentFile_.toStdString());
setWindowModified(false);
auto shownName = tr("Untitled");
if (!currentFile_.isEmpty())
{
shownName = strippedName(currentFile_);
latestNetworkDirectory_ = QFileInfo(currentFile_).dir();
recentFiles_.removeAll(currentFile_);
recentFiles_.prepend(currentFile_);
updateRecentFileActions();
}
setWindowTitle(tr("%1[*] - %2").arg(shownName).arg(tr("SCIRun")));
}
void SCIRunMainWindow::runPythonScript(const QString& scriptFileName)
{
#ifdef BUILD_WITH_PYTHON
NetworkEditor::InEditingContext iec(networkEditor_);
GuiLogger::logInfoQ("RUNNING PYTHON SCRIPT: " + scriptFileName);
PythonInterpreter::Instance().importSCIRunLibrary();
PythonInterpreter::Instance().run_file(scriptFileName.toStdString());
statusBar()->showMessage(tr("Script is running."), 2000);
#else
GuiLogger::logInfo("Python not included in this build, cannot run " + scriptFileName);
#endif
}
bool SCIRunMainWindow::isInFavorites(const QString& module) const
{
return favoriteModuleNames_.contains(module);
}
void SCIRunMainWindow::setDataDirectory(const QString& dir)
{
if (!dir.isEmpty())
{
prefsWindow_->scirunDataLineEdit_->setText(dir);
prefsWindow_->scirunDataLineEdit_->setToolTip(dir);
RemembersFileDialogDirectory::setStartingDir(dir);
Preferences::Instance().setDataDirectory(dir.toStdString());
Q_EMIT dataDirectorySet(dir);
}
}
void SCIRunMainWindow::setDataPath(const QString& dirs)
{
if (!dirs.isEmpty())
{
//prefsWindow_->scirunDataPathTextEdit_->setPlainText(dirs);
//prefsWindow_->scirunDataPathTextEdit_->setToolTip(dirs);
Preferences::Instance().setDataPath(dirs.toStdString());
}
}
void SCIRunMainWindow::addToDataDirectory(const QString& dir)
{
if (!dir.isEmpty())
{
// auto text = prefsWindow_->scirunDataPathTextEdit_->toPlainText();
// if (!text.isEmpty())
// text += ";\n";
// text += dir;
// prefsWindow_->scirunDataPathTextEdit_->setPlainText(text);
// prefsWindow_->scirunDataPathTextEdit_->setToolTip(prefsWindow_->scirunDataPathTextEdit_->toPlainText());
RemembersFileDialogDirectory::setStartingDir(dir);
Preferences::Instance().addToDataPath(dir.toStdString());
}
}
void SCIRunMainWindow::addToolkit(const QString& filename, const QString& directory, const ToolkitFile& toolkit)
{
auto menu = menuToolkits_->addMenu(filename);
auto networks = menu->addMenu("Networks");
toolkitDirectories_[filename] = directory;
toolkitNetworks_[filename] = toolkit;
auto fullpath = directory + QDir::separator() + filename + ".toolkit";
toolkitMenus_[fullpath] = menu;
std::map<std::string, std::map<std::string, NetworkFile>> toolkitMenuData;
for (const auto& toolkitPair : toolkit.networks)
{
std::vector<std::string> elements;
for (const auto& p : boost::filesystem::path(toolkitPair.first))
elements.emplace_back(p.filename().string());
if (elements.size() == 2)
{
toolkitMenuData[elements[0]][elements[1]] = toolkitPair.second;
}
else
{
qDebug() << "Cannot handle toolkit folders of depth > 1";
}
}
for (const auto& t1 : toolkitMenuData)
{
auto t1menu = networks->addMenu(QString::fromStdString(t1.first));
for (const auto& t2 : t1.second)
{
auto networkAction = t1menu->addAction(QString::fromStdString(t2.first));
std::ostringstream net;
XMLSerializer::save_xml(t2.second, net, "networkFile");
networkAction->setProperty("network", QString::fromStdString(net.str()));
connect(networkAction, SIGNAL(triggered()), this, SLOT(openToolkitNetwork()));
}
}
auto folder = menu->addAction("Open Toolkit Directory");
folder->setProperty("path", directory);
connect(folder, SIGNAL(triggered()), this, SLOT(openToolkitFolder()));
auto remove = menu->addAction("Remove Toolkit...");
remove->setProperty("filename", filename);
remove->setProperty("fullpath", fullpath);
connect(remove, SIGNAL(triggered()), this, SLOT(removeToolkit()));
if (!startup_)
{
QMessageBox::information(this, "Toolkit loaded", "Toolkit " + filename +
" successfully imported. A new submenu is available under Toolkits for loading networks.\n\n"
+ "Remember to update your data folder under Preferences->Paths.");
actionPreferences_->trigger();
}
}
<commit_msg>Improve import log file name<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <es-log/trace-log.h>
#include <QtGui>
#include <functional>
#include <boost/bind.hpp>
#include <boost/assign.hpp>
#include <boost/assign/std/vector.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <Core/Utils/Legacy/MemoryUtil.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Interface/Application/GuiLogger.h>
#include <Interface/Application/SCIRunMainWindow.h>
#include <Interface/Application/NetworkEditor.h>
#include <Interface/Application/ProvenanceWindow.h>
#include <Interface/Application/DeveloperConsole.h>
#include <Interface/Application/Connection.h>
#include <Interface/Application/PreferencesWindow.h>
#include <Interface/Application/TagManagerWindow.h>
#include <Interface/Application/ShortcutsInterface.h>
#include <Interface/Application/TreeViewCollaborators.h>
#include <Interface/Application/MainWindowCollaborators.h>
#include <Interface/Application/GuiCommands.h>
#include <Interface/Application/NetworkEditorControllerGuiProxy.h>
#include <Interface/Application/NetworkExecutionProgressBar.h>
#include <Interface/Application/DialogErrorControl.h>
#include <Interface/Modules/Base/RemembersFileDialogDirectory.h>
#include <Interface/Modules/Base/ModuleDialogGeneric.h> //TODO
#include <Interface/Application/ModuleWizard/ModuleWizard.h>
#include <Dataflow/Network/NetworkFwd.h>
#include <Dataflow/Engine/Controller/NetworkEditorController.h> //DOH! see TODO in setController
#include <Dataflow/Engine/Controller/ProvenanceManager.h>
#include <Dataflow/Network/SimpleSourceSink.h> //TODO: encapsulate!!!
#include <Dataflow/Serialization/Network/XMLSerializer.h>
#include <Core/Application/Application.h>
#include <Core/Application/Preferences/Preferences.h>
#include <Core/Logging/Log.h>
#include <Core/Thread/Parallel.h>
#include <Core/Application/Version.h>
#include <Dataflow/Serialization/Network/NetworkDescriptionSerialization.h>
#include <Core/Utils/CurrentFileName.h>
#ifdef BUILD_WITH_PYTHON
#include <Interface/Application/PythonConsoleWidget.h>
#include <Core/Python/PythonInterpreter.h>
#endif
#include "TriggeredEventsWindow.h"
#include <Dataflow/Serialization/Network/XMLSerializer.h>
using namespace SCIRun;
using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Engine;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Dataflow::State;
using namespace SCIRun::Core::Commands;
using namespace SCIRun::Core::Logging;
using namespace SCIRun::Core;
using namespace SCIRun::Core::Algorithms;
void SCIRunMainWindow::initialize()
{
postConstructionSignalHookup();
fillModuleSelector();
executeCommandLineRequests();
}
void SCIRunMainWindow::setController(NetworkEditorControllerHandle controller)
{
auto controllerProxy(boost::make_shared<NetworkEditorControllerGuiProxy>(controller, networkEditor_));
networkEditor_->setNetworkEditorController(controllerProxy);
//TODO: need better way to wire this up
controller->setSerializationManager(networkEditor_);
}
void SCIRunMainWindow::preexecute()
{
if (Preferences::Instance().saveBeforeExecute && !Application::Instance().parameters()->isRegressionMode())
{
saveNetwork();
}
}
void SCIRunMainWindow::setupQuitAfterExecute()
{
connect(networkEditor_->getNetworkEditorController().get(), SIGNAL(executionFinished(int)), this, SLOT(exitApplication(int)));
quitAfterExecute_ = true;
}
void SCIRunMainWindow::saveNetworkFile(const QString& fileName)
{
writeSettings();
NetworkSaveCommand save;
save.set(Variables::Filename, fileName.toStdString());
save.execute();
}
bool SCIRunMainWindow::loadNetworkFile(const QString& filename, bool isTemporary)
{
if (!filename.isEmpty())
{
RENDERER_LOG("Opening network file: {}", filename.toStdString());
FileOpenCommand command;
command.set(Variables::Filename, filename.toStdString());
command.set(Name("temporaryFile"), isTemporary);
if (command.execute())
{
networkProgressBar_->updateTotalModules(networkEditor_->numModules());
if (!isTemporary)
{
setCurrentFile(filename);
statusBar()->showMessage(tr("File loaded: ") + filename, 2000);
provenanceWindow_->clear();
provenanceWindow_->showFile(command.file_);
}
else
{
setCurrentFile("");
setWindowModified(true);
showStatusMessage("Toolkit network loaded. ", 2000);
}
networkEditor_->viewport()->update();
return true;
}
else
{
if (Application::Instance().parameters()->isRegressionMode())
exit(7);
//TODO: set error code to non-0 so regression tests fail!
// probably want to control this with a --regression flag.
}
}
return false;
}
bool SCIRunMainWindow::importLegacyNetworkFile(const QString& filename)
{
bool success = false;
if (!filename.isEmpty())
{
FileImportCommand command;
command.set(Variables::Filename, filename.toStdString());
if (command.execute())
{
statusBar()->showMessage(tr("File imported: ") + filename, 2000);
networkProgressBar_->updateTotalModules(networkEditor_->numModules());
networkEditor_->viewport()->update();
success = true;
}
else
{
statusBar()->showMessage(tr("File import failed: ") + filename, 2000);
}
auto log = QString::fromStdString(command.logContents());
auto isoString = boost::posix_time::to_iso_string(boost::posix_time::microsec_clock::universal_time());
auto logFileName = QString::fromStdString(Core::Logging::LogSettings::Instance().logDirectory().string())
+ "/" + (strippedName(filename) + "_importLog_" + QString::fromStdString(isoString) + ".log");
QFile logFile(logFileName);
if (logFile.open(QFile::WriteOnly | QFile::Text))
{
QTextStream stream(&logFile);
stream << log;
QMessageBox::information(this, "SRN File Import", "SRN File Import log file can be found here: " + logFileName
+ "\n\nAdditionally, check the log directory for a list of missing modules (look for file missingModules.log)");
}
else
{
QMessageBox::information(this, "SRN File Import", "Failed to write SRN File Import log file: " + logFileName);
}
}
return success;
}
void SCIRunMainWindow::setCurrentFile(const QString& fileName)
{
currentFile_ = fileName;
setCurrentFileName(currentFile_.toStdString());
setWindowModified(false);
auto shownName = tr("Untitled");
if (!currentFile_.isEmpty())
{
shownName = strippedName(currentFile_);
latestNetworkDirectory_ = QFileInfo(currentFile_).dir();
recentFiles_.removeAll(currentFile_);
recentFiles_.prepend(currentFile_);
updateRecentFileActions();
}
setWindowTitle(tr("%1[*] - %2").arg(shownName).arg(tr("SCIRun")));
}
void SCIRunMainWindow::runPythonScript(const QString& scriptFileName)
{
#ifdef BUILD_WITH_PYTHON
NetworkEditor::InEditingContext iec(networkEditor_);
GuiLogger::logInfoQ("RUNNING PYTHON SCRIPT: " + scriptFileName);
PythonInterpreter::Instance().importSCIRunLibrary();
PythonInterpreter::Instance().run_file(scriptFileName.toStdString());
statusBar()->showMessage(tr("Script is running."), 2000);
#else
GuiLogger::logInfo("Python not included in this build, cannot run " + scriptFileName);
#endif
}
bool SCIRunMainWindow::isInFavorites(const QString& module) const
{
return favoriteModuleNames_.contains(module);
}
void SCIRunMainWindow::setDataDirectory(const QString& dir)
{
if (!dir.isEmpty())
{
prefsWindow_->scirunDataLineEdit_->setText(dir);
prefsWindow_->scirunDataLineEdit_->setToolTip(dir);
RemembersFileDialogDirectory::setStartingDir(dir);
Preferences::Instance().setDataDirectory(dir.toStdString());
Q_EMIT dataDirectorySet(dir);
}
}
void SCIRunMainWindow::setDataPath(const QString& dirs)
{
if (!dirs.isEmpty())
{
//prefsWindow_->scirunDataPathTextEdit_->setPlainText(dirs);
//prefsWindow_->scirunDataPathTextEdit_->setToolTip(dirs);
Preferences::Instance().setDataPath(dirs.toStdString());
}
}
void SCIRunMainWindow::addToDataDirectory(const QString& dir)
{
if (!dir.isEmpty())
{
// auto text = prefsWindow_->scirunDataPathTextEdit_->toPlainText();
// if (!text.isEmpty())
// text += ";\n";
// text += dir;
// prefsWindow_->scirunDataPathTextEdit_->setPlainText(text);
// prefsWindow_->scirunDataPathTextEdit_->setToolTip(prefsWindow_->scirunDataPathTextEdit_->toPlainText());
RemembersFileDialogDirectory::setStartingDir(dir);
Preferences::Instance().addToDataPath(dir.toStdString());
}
}
void SCIRunMainWindow::addToolkit(const QString& filename, const QString& directory, const ToolkitFile& toolkit)
{
auto menu = menuToolkits_->addMenu(filename);
auto networks = menu->addMenu("Networks");
toolkitDirectories_[filename] = directory;
toolkitNetworks_[filename] = toolkit;
auto fullpath = directory + QDir::separator() + filename + ".toolkit";
toolkitMenus_[fullpath] = menu;
std::map<std::string, std::map<std::string, NetworkFile>> toolkitMenuData;
for (const auto& toolkitPair : toolkit.networks)
{
std::vector<std::string> elements;
for (const auto& p : boost::filesystem::path(toolkitPair.first))
elements.emplace_back(p.filename().string());
if (elements.size() == 2)
{
toolkitMenuData[elements[0]][elements[1]] = toolkitPair.second;
}
else
{
qDebug() << "Cannot handle toolkit folders of depth > 1";
}
}
for (const auto& t1 : toolkitMenuData)
{
auto t1menu = networks->addMenu(QString::fromStdString(t1.first));
for (const auto& t2 : t1.second)
{
auto networkAction = t1menu->addAction(QString::fromStdString(t2.first));
std::ostringstream net;
XMLSerializer::save_xml(t2.second, net, "networkFile");
networkAction->setProperty("network", QString::fromStdString(net.str()));
connect(networkAction, SIGNAL(triggered()), this, SLOT(openToolkitNetwork()));
}
}
auto folder = menu->addAction("Open Toolkit Directory");
folder->setProperty("path", directory);
connect(folder, SIGNAL(triggered()), this, SLOT(openToolkitFolder()));
auto remove = menu->addAction("Remove Toolkit...");
remove->setProperty("filename", filename);
remove->setProperty("fullpath", fullpath);
connect(remove, SIGNAL(triggered()), this, SLOT(removeToolkit()));
if (!startup_)
{
QMessageBox::information(this, "Toolkit loaded", "Toolkit " + filename +
" successfully imported. A new submenu is available under Toolkits for loading networks.\n\n"
+ "Remember to update your data folder under Preferences->Paths.");
actionPreferences_->trigger();
}
}
<|endoftext|> |
<commit_before>#include "NodeSSPI.h"
using namespace v8;
using namespace std;
sspi_module_rec sspiModuleInfo = { 0, };
std::map<std::string, credHandleRec> credMap;
void sspi_module_cleanup()
{
if (sspiModuleInfo.securityDLL != NULL) {
if (sspiModuleInfo.functable != NULL) {
sspiModuleInfo.functable->FreeContextBuffer(sspiModuleInfo.pkgInfo);
}
FreeLibrary(sspiModuleInfo.securityDLL);
}
}
void init_module()
{
LPSTR lpDllName = WINNT_SECURITY_DLL;
INIT_SECURITY_INTERFACE pInit;
SECURITY_STATUS ss = SEC_E_INTERNAL_ERROR;
sspiModuleInfo.defaultPackage = DEFAULT_SSPI_PACKAGE;
__try {
sspiModuleInfo.securityDLL = LoadLibrary(lpDllName);
pInit = (INIT_SECURITY_INTERFACE)GetProcAddress(sspiModuleInfo.securityDLL, SECURITY_ENTRYPOINT);
sspiModuleInfo.functable = pInit();
ss = sspiModuleInfo.functable->EnumerateSecurityPackages(&sspiModuleInfo.numPackages, &sspiModuleInfo.pkgInfo);
sspiModuleInfo.supportsSSPI = TRUE;
}
__finally {
if (ss != SEC_E_OK) {
sspi_module_cleanup();
}
}
}
void note_sspi_auth_failure(const Local<Object> opts,const Local<Object> req,Local<Object> res){
int nWays = 0;
int nSSPIPkgs = 0;
bool offerBasic = false, offerSSPI = false;
if(opts->Get(String::New("offerBasic"))->BooleanValue()){
offerBasic = true;
nWays += 1;
}
if(opts->Get(String::New("offerSSPI"))->BooleanValue()){
offerSSPI = true;
nSSPIPkgs = opts->Get(String::New("sspiPackagesUsed"))->ToObject()->Get(String::New("length"))->ToInteger()->Uint32Value();
nWays += nSSPIPkgs;
}
auto authHArr = v8::Array::New(nWays);
int curIdx = 0;
if(offerBasic){
std::string basicStr("Basic");
if(opts->Has(String::New("domain"))){
basicStr += " realm=\"";
basicStr += std::string(*String::AsciiValue(opts->Get(String::New("domain"))));
basicStr += "\"";
}
authHArr->Set(curIdx++, String::New(basicStr.c_str()));
}
if(offerSSPI){
for(int i =0;i<nSSPIPkgs;i++){
authHArr->Set(curIdx++,opts->Get(String::New("sspiPackagesUsed"))->ToObject()->Get(i));
}
}
Handle<Value> argv[] = { String::New("WWW-Authenticate"), authHArr };
res->Get(String::New("setHeader"))->ToObject()->CallAsFunction(res, 2, argv);
res->Set(String::New("statusCode"),Integer::New(401));
}
void cleanup_sspi_connection(Local<Object> conn)
{
sspi_connection_rec *pSCR = 0;
PCtxtHandle outPch = 0;
if (conn->HasOwnProperty(String::New("svrCtx"))){
Local<External> wrap = Local<External>::Cast(conn->Get(String::New("svrCtx"))->ToObject()->GetInternalField(0));
pSCR = static_cast<sspi_connection_rec *>(wrap->Value());
outPch = &pSCR->server_context;
sspiModuleInfo.functable->DeleteSecurityContext(outPch);
outPch->dwLower = outPch->dwUpper = 0;
free(pSCR);
conn->Delete(String::New("svrCtx"));
}
}
/*
* args[0]: opts
* args[1]: req
* args[2]: res
*/
Handle<Value> Authenticate(const Arguments& args) {
HandleScope scope;
BYTE* pToken;
try{
if (sspiModuleInfo.supportsSSPI == FALSE) {
throw std::exception("Doesn't suport SSPI.");
}
auto opts = args[0]->ToObject();
auto req = args[1]->ToObject();
auto res = args[2]->ToObject();
auto headers = req->Get(String::New("headers"))->ToObject();
auto conn = req->Get(String::New("connection"))->ToObject();
if(conn->HasOwnProperty(String::New("user"))){
return scope.Close(Undefined());
}
if(!headers->Has(String::New("authorization"))){
note_sspi_auth_failure(opts,req,res);
return scope.Close(Undefined());
}
auto aut = std::string(*String::AsciiValue(headers->Get(String::New("authorization"))));
stringstream ssin(aut);
std::string schema, strToken;
ssin >> schema;
ssin >> strToken;
// base64 decode strToken
unique_ptr<BYTE[]> pToken(new BYTE[strToken.length()]);
int sz = strToken.length();
if (!Base64Decode(strToken.c_str(), strToken.length(), pToken.get(), &sz)){
throw std::exception("Cannot decode authorization field.");
};
// get max token size defined by SSPI package
ULONG maxTokSz, i;
for (i = 0; i < sspiModuleInfo.numPackages; i++){
if (!schema.compare(sspiModuleInfo.pkgInfo[i].Name)){
maxTokSz = sspiModuleInfo.pkgInfo[i].cbMaxToken;
break;
}
}
if (i == sspiModuleInfo.numPackages){
throw std::exception(("No " + schema + " SSPI package.").c_str());
}
// acquire server credential
if (credMap.find(schema) == credMap.end()){
credHandleRec temp = { 0, 0 };
credMap[schema] = temp;
}
FILETIME ft;
SYSTEMTIME st;
GetSystemTime(&st); // gets current time
SystemTimeToFileTime(&st, &ft); // converts to file time format
if (CompareFileTime(&ft, (FILETIME *)(&credMap[schema].exp)) > 0){
sspiModuleInfo.functable->FreeCredentialsHandle(&credMap[schema].credHandl);
// cred expired, re-generate
if (sspiModuleInfo.functable->AcquireCredentialsHandle(
NULL //pszPrincipal
, (char*)(schema.c_str()) //pszPackage
, SECPKG_CRED_INBOUND //fCredentialUse
, NULL // pvLogonID
, NULL //pAuthData
, NULL //pGetKeyFn
, NULL //pvGetKeyArgument
, &credMap[schema].credHandl //phCredential
, &credMap[schema].exp //ptsExpiry
) != SEC_E_OK){
throw std::exception("Cannot get server credential");
}
}
// acquire server context from request.connection
sspi_connection_rec *pSCR = 0;
PCtxtHandle inPch = 0, outPch = 0;
PTimeStamp pTS;
if (conn->HasOwnProperty(String::New("svrCtx"))){
// this is not initial request
Local<External> wrap = Local<External>::Cast(conn->Get(String::New("svrCtx"))->ToObject()->GetInternalField(0));
pSCR = static_cast<sspi_connection_rec *>(wrap->Value());
inPch = outPch = &pSCR->server_context;
}
else{
pSCR = static_cast<sspi_connection_rec *>(malloc(sizeof(sspi_connection_rec)));
outPch = &pSCR->server_context;
Handle<ObjectTemplate> svrCtx_templ = ObjectTemplate::New();
svrCtx_templ->SetInternalFieldCount(1);
Local<Object> obj = svrCtx_templ->NewInstance();
obj->SetInternalField(0, External::New(outPch));
conn->Set(String::New("svrCtx"), obj);
}
pTS = &pSCR->server_ctxtexpiry;
// call AcceptSecurityContext
SecBuffer inbuf, outbuf;
SecBufferDesc inbufdesc, outbufdesc;
outbuf.cbBuffer = maxTokSz;
outbuf.BufferType = SECBUFFER_TOKEN;
unique_ptr<BYTE[]> pOutBuf(new BYTE[maxTokSz]);
outbuf.pvBuffer = pOutBuf.get();
outbufdesc.ulVersion = SECBUFFER_VERSION;
outbufdesc.cBuffers = 1;
outbufdesc.pBuffers = &outbuf;
inbuf.BufferType = SECBUFFER_TOKEN;
inbuf.cbBuffer = sz;
inbuf.pvBuffer = pToken.get();
inbufdesc.cBuffers = 1;
inbufdesc.ulVersion = SECBUFFER_VERSION;
inbufdesc.pBuffers = &inbuf;
ULONG ContextAttributes;
SECURITY_STATUS ss;
ss = sspiModuleInfo.functable->AcceptSecurityContext(
&credMap[schema].credHandl // _In_opt_ PCredHandle phCredential,
, inPch // _Inout_opt_ PCtxtHandle phContext,
, &inbufdesc // _In_opt_ PSecBufferDesc pInput,
, ASC_REQ_DELEGATE // _In_ ULONG fContextReq,
, SECURITY_NATIVE_DREP // _In_ ULONG TargetDataRep,
, outPch // _Inout_opt_ PCtxtHandle phNewContext,
, &outbufdesc // _Inout_opt_ PSecBufferDesc pOutput,
, &ContextAttributes // _Out_ PULONG pfContextAttr,
, pTS // _Out_opt_ PTimeStamp ptsTimeStamp
);
if (ss == SEC_I_COMPLETE_NEEDED || ss == SEC_I_COMPLETE_AND_CONTINUE) {
sspiModuleInfo.functable->CompleteAuthToken(outPch, &outbufdesc);
}
switch (ss) {
case SEC_I_COMPLETE_NEEDED:
case SEC_I_CONTINUE_NEEDED:
case SEC_I_COMPLETE_AND_CONTINUE:
{
CStringA base64;
int base64Length = Base64EncodeGetRequiredLength(outbuf.cbBuffer);
Base64Encode(pOutBuf.get(),
outbuf.cbBuffer,
base64.GetBufferSetLength(base64Length),
&base64Length, ATL_BASE64_FLAG_NOCRLF);
base64.ReleaseBufferSetLength(base64Length);
std::string authHStr = schema + " " + std::string(base64.GetString());
Handle<Value> argv[] = { String::New("WWW-Authenticate"), String::New(authHStr.c_str()) };
res->Get(String::New("setHeader"))->ToObject()->CallAsFunction(res, 2, argv);
res->Set(String::New("statusCode"), Integer::New(401));
break;
}
case SEC_E_INVALID_TOKEN:
case SEC_E_LOGON_DENIED:
{
note_sspi_auth_failure(opts,req,res);
cleanup_sspi_connection(conn);
res->Set(String::New("statusCode"), Integer::New(401));
break;
}
case SEC_E_INVALID_HANDLE:
case SEC_E_INTERNAL_ERROR:
case SEC_E_NO_AUTHENTICATING_AUTHORITY:
case SEC_E_INSUFFICIENT_MEMORY:
{
cleanup_sspi_connection(conn);
res->Set(String::New("statusCode"), Integer::New(500));
break;
}
case SEC_E_OK:
//return OK;
break;
}
}
catch (std::exception& ex){
args[2]->ToObject()->Set(String::New("statusCode"), Integer::New(500));
// throw exception to js land
return v8::ThrowException(v8::String::New(ex.what()));
}
return scope.Close(Undefined());
}
void init(Handle<Object> exports) {
init_module();
exports->Set(String::NewSymbol("authenticate"),
FunctionTemplate::New(Authenticate)->GetFunction());
}
NODE_MODULE(nodeSSPI, init)<commit_msg>retrieve user name!<commit_after>#include "NodeSSPI.h"
using namespace v8;
using namespace std;
sspi_module_rec sspiModuleInfo = { 0, };
std::map<std::string, credHandleRec> credMap;
void sspi_module_cleanup()
{
if (sspiModuleInfo.securityDLL != NULL) {
if (sspiModuleInfo.functable != NULL) {
sspiModuleInfo.functable->FreeContextBuffer(sspiModuleInfo.pkgInfo);
}
FreeLibrary(sspiModuleInfo.securityDLL);
}
}
void init_module()
{
LPSTR lpDllName = WINNT_SECURITY_DLL;
INIT_SECURITY_INTERFACE pInit;
SECURITY_STATUS ss = SEC_E_INTERNAL_ERROR;
sspiModuleInfo.defaultPackage = DEFAULT_SSPI_PACKAGE;
__try {
sspiModuleInfo.securityDLL = LoadLibrary(lpDllName);
pInit = (INIT_SECURITY_INTERFACE)GetProcAddress(sspiModuleInfo.securityDLL, SECURITY_ENTRYPOINT);
sspiModuleInfo.functable = pInit();
ss = sspiModuleInfo.functable->EnumerateSecurityPackages(&sspiModuleInfo.numPackages, &sspiModuleInfo.pkgInfo);
sspiModuleInfo.supportsSSPI = TRUE;
}
__finally {
if (ss != SEC_E_OK) {
sspi_module_cleanup();
}
}
}
void note_sspi_auth_failure(const Local<Object> opts,const Local<Object> req,Local<Object> res){
int nWays = 0;
int nSSPIPkgs = 0;
bool offerBasic = false, offerSSPI = false;
if(opts->Get(String::New("offerBasic"))->BooleanValue()){
offerBasic = true;
nWays += 1;
}
if(opts->Get(String::New("offerSSPI"))->BooleanValue()){
offerSSPI = true;
nSSPIPkgs = opts->Get(String::New("sspiPackagesUsed"))->ToObject()->Get(String::New("length"))->ToInteger()->Uint32Value();
nWays += nSSPIPkgs;
}
auto authHArr = v8::Array::New(nWays);
int curIdx = 0;
if(offerBasic){
std::string basicStr("Basic");
if(opts->Has(String::New("domain"))){
basicStr += " realm=\"";
basicStr += std::string(*String::AsciiValue(opts->Get(String::New("domain"))));
basicStr += "\"";
}
authHArr->Set(curIdx++, String::New(basicStr.c_str()));
}
if(offerSSPI){
for(int i =0;i<nSSPIPkgs;i++){
authHArr->Set(curIdx++,opts->Get(String::New("sspiPackagesUsed"))->ToObject()->Get(i));
}
}
Handle<Value> argv[] = { String::New("WWW-Authenticate"), authHArr };
res->Get(String::New("setHeader"))->ToObject()->CallAsFunction(res, 2, argv);
res->Set(String::New("statusCode"),Integer::New(401));
}
void cleanup_sspi_connection(Local<Object> conn)
{
sspi_connection_rec *pSCR = 0;
PCtxtHandle outPch = 0;
if (conn->HasOwnProperty(String::New("svrCtx"))){
Local<External> wrap = Local<External>::Cast(conn->Get(String::New("svrCtx"))->ToObject()->GetInternalField(0));
pSCR = static_cast<sspi_connection_rec *>(wrap->Value());
outPch = &pSCR->server_context;
sspiModuleInfo.functable->DeleteSecurityContext(outPch);
outPch->dwLower = outPch->dwUpper = 0;
free(pSCR);
conn->Delete(String::New("svrCtx"));
}
}
/*
* args[0]: opts
* args[1]: req
* args[2]: res
*/
Handle<Value> Authenticate(const Arguments& args) {
HandleScope scope;
BYTE* pToken;
try{
if (sspiModuleInfo.supportsSSPI == FALSE) {
throw std::exception("Doesn't suport SSPI.");
}
auto opts = args[0]->ToObject();
auto req = args[1]->ToObject();
auto res = args[2]->ToObject();
auto headers = req->Get(String::New("headers"))->ToObject();
auto conn = req->Get(String::New("connection"))->ToObject();
if(conn->HasOwnProperty(String::New("user"))){
return scope.Close(Undefined());
}
if(!headers->Has(String::New("authorization"))){
note_sspi_auth_failure(opts,req,res);
return scope.Close(Undefined());
}
auto aut = std::string(*String::AsciiValue(headers->Get(String::New("authorization"))));
stringstream ssin(aut);
std::string schema, strToken;
ssin >> schema;
ssin >> strToken;
// base64 decode strToken
unique_ptr<BYTE[]> pToken(new BYTE[strToken.length()]);
int sz = strToken.length();
if (!Base64Decode(strToken.c_str(), strToken.length(), pToken.get(), &sz)){
throw std::exception("Cannot decode authorization field.");
};
// get max token size defined by SSPI package
ULONG maxTokSz, i;
for (i = 0; i < sspiModuleInfo.numPackages; i++){
if (!schema.compare(sspiModuleInfo.pkgInfo[i].Name)){
maxTokSz = sspiModuleInfo.pkgInfo[i].cbMaxToken;
break;
}
}
if (i == sspiModuleInfo.numPackages){
throw std::exception(("No " + schema + " SSPI package.").c_str());
}
// acquire server credential
if (credMap.find(schema) == credMap.end()){
credHandleRec temp = { 0, 0 };
credMap[schema] = temp;
}
FILETIME ft;
SYSTEMTIME st;
GetSystemTime(&st); // gets current time
SystemTimeToFileTime(&st, &ft); // converts to file time format
if (CompareFileTime(&ft, (FILETIME *)(&credMap[schema].exp)) > 0){
sspiModuleInfo.functable->FreeCredentialsHandle(&credMap[schema].credHandl);
// cred expired, re-generate
if (sspiModuleInfo.functable->AcquireCredentialsHandle(
NULL //pszPrincipal
, (char*)(schema.c_str()) //pszPackage
, SECPKG_CRED_INBOUND //fCredentialUse
, NULL // pvLogonID
, NULL //pAuthData
, NULL //pGetKeyFn
, NULL //pvGetKeyArgument
, &credMap[schema].credHandl //phCredential
, &credMap[schema].exp //ptsExpiry
) != SEC_E_OK){
throw std::exception("Cannot get server credential");
}
}
// acquire server context from request.connection
sspi_connection_rec *pSCR = 0;
PCtxtHandle inPch = 0, outPch = 0;
PTimeStamp pTS;
if (conn->HasOwnProperty(String::New("svrCtx"))){
// this is not initial request
Local<External> wrap = Local<External>::Cast(conn->Get(String::New("svrCtx"))->ToObject()->GetInternalField(0));
pSCR = static_cast<sspi_connection_rec *>(wrap->Value());
inPch = outPch = &pSCR->server_context;
}
else{
pSCR = static_cast<sspi_connection_rec *>(malloc(sizeof(sspi_connection_rec)));
outPch = &pSCR->server_context;
Handle<ObjectTemplate> svrCtx_templ = ObjectTemplate::New();
svrCtx_templ->SetInternalFieldCount(1);
Local<Object> obj = svrCtx_templ->NewInstance();
obj->SetInternalField(0, External::New(outPch));
conn->Set(String::New("svrCtx"), obj);
}
pTS = &pSCR->server_ctxtexpiry;
// call AcceptSecurityContext
SecBuffer inbuf, outbuf;
SecBufferDesc inbufdesc, outbufdesc;
outbuf.cbBuffer = maxTokSz;
outbuf.BufferType = SECBUFFER_TOKEN;
unique_ptr<BYTE[]> pOutBuf(new BYTE[maxTokSz]);
outbuf.pvBuffer = pOutBuf.get();
outbufdesc.ulVersion = SECBUFFER_VERSION;
outbufdesc.cBuffers = 1;
outbufdesc.pBuffers = &outbuf;
inbuf.BufferType = SECBUFFER_TOKEN;
inbuf.cbBuffer = sz;
inbuf.pvBuffer = pToken.get();
inbufdesc.cBuffers = 1;
inbufdesc.ulVersion = SECBUFFER_VERSION;
inbufdesc.pBuffers = &inbuf;
ULONG ContextAttributes;
SECURITY_STATUS ss;
ss = sspiModuleInfo.functable->AcceptSecurityContext(
&credMap[schema].credHandl // _In_opt_ PCredHandle phCredential,
, inPch // _Inout_opt_ PCtxtHandle phContext,
, &inbufdesc // _In_opt_ PSecBufferDesc pInput,
, ASC_REQ_DELEGATE // _In_ ULONG fContextReq,
, SECURITY_NATIVE_DREP // _In_ ULONG TargetDataRep,
, outPch // _Inout_opt_ PCtxtHandle phNewContext,
, &outbufdesc // _Inout_opt_ PSecBufferDesc pOutput,
, &ContextAttributes // _Out_ PULONG pfContextAttr,
, pTS // _Out_opt_ PTimeStamp ptsTimeStamp
);
if (ss == SEC_I_COMPLETE_NEEDED || ss == SEC_I_COMPLETE_AND_CONTINUE) {
sspiModuleInfo.functable->CompleteAuthToken(outPch, &outbufdesc);
}
switch (ss) {
case SEC_I_COMPLETE_NEEDED:
case SEC_I_CONTINUE_NEEDED:
case SEC_I_COMPLETE_AND_CONTINUE:
{
CStringA base64;
int base64Length = Base64EncodeGetRequiredLength(outbuf.cbBuffer);
Base64Encode(pOutBuf.get(),
outbuf.cbBuffer,
base64.GetBufferSetLength(base64Length),
&base64Length, ATL_BASE64_FLAG_NOCRLF);
base64.ReleaseBufferSetLength(base64Length);
std::string authHStr = schema + " " + std::string(base64.GetString());
Handle<Value> argv[] = { String::New("WWW-Authenticate"), String::New(authHStr.c_str()) };
res->Get(String::New("setHeader"))->ToObject()->CallAsFunction(res, 2, argv);
res->Set(String::New("statusCode"), Integer::New(401));
break;
}
case SEC_E_INVALID_TOKEN:
case SEC_E_LOGON_DENIED:
{
note_sspi_auth_failure(opts,req,res);
cleanup_sspi_connection(conn);
res->Set(String::New("statusCode"), Integer::New(401));
break;
}
case SEC_E_INVALID_HANDLE:
case SEC_E_INTERNAL_ERROR:
case SEC_E_NO_AUTHENTICATING_AUTHORITY:
case SEC_E_INSUFFICIENT_MEMORY:
{
cleanup_sspi_connection(conn);
res->Set(String::New("statusCode"), Integer::New(500));
break;
}
case SEC_E_OK:
{
// get user name
SecPkgContext_Names names;
SECURITY_STATUS ss;
char *retval = NULL;
if ((ss = sspiModuleInfo.functable->QueryContextAttributes(outPch,
SECPKG_ATTR_NAMES,
&names)
) == SEC_E_OK) {
conn->Set(String::New("user"),String::New(names.sUserName));
sspiModuleInfo.functable->FreeContextBuffer(names.sUserName);
}
break;
}
}
}
catch (std::exception& ex){
args[2]->ToObject()->Set(String::New("statusCode"), Integer::New(500));
// throw exception to js land
return v8::ThrowException(v8::String::New(ex.what()));
}
return scope.Close(Undefined());
}
void init(Handle<Object> exports) {
init_module();
exports->Set(String::NewSymbol("authenticate"),
FunctionTemplate::New(Authenticate)->GetFunction());
}
NODE_MODULE(nodeSSPI, init)<|endoftext|> |
<commit_before>#include "ObjPlane.h"
/*
====================
Plane::Plane
Takes in the input stream and creates a Plane object from the parsed input
====================
*/
Plane::Plane(ifstream &f) {
string textureName;
while(!f.eof()) {
string line;
getline(f,line);
queue<string> lineContents;
explode(line," ",&lineContents);
if(lineContents.size() == 0) continue;
string word = lineContents.front();
lineContents.pop();
if(word[0] == '#' || line[0] == '\n' || line[0] == '\r') continue;
//words with three arguments
if(word == "origin" || word == "color" || word == "normal" || word == "up") {
double num1 = 0;
double num2 = 0;
double num3 = 0;
if(lineContents.size() < 3) break;
num1 = (double)atof(lineContents.front().c_str());
lineContents.pop();
num2 = (double)atof(lineContents.front().c_str());
lineContents.pop();
num3 = (double)atof(lineContents.front().c_str());
lineContents.pop();
if(word == "origin") this->origin = Point(num1,num2,num3);
else if(word == "color") material.color = Color(num1,num2,num3);
else if(word == "up") {
this->up = Vector(num1,num2,num3);
}
else if(word == "normal") {
this->normal = Vector(num1,num2,num3);
}
}
//words with two arguments
else if(word == "size") {
double num1 = 0;
double num2 = 0;
if(lineContents.size() < 2) break;
num1 = (double)atof(lineContents.front().c_str());
lineContents.pop();
num2 = (double)atof(lineContents.front().c_str());
lineContents.pop();
this->width = num1;
this->height = num2;
}
//words with one double argument
else if(word == "reflect" || word == "transparency") {
double num1 = 0;
if(lineContents.size() < 1) break;
num1 = (double)atof(lineContents.front().c_str());
lineContents.pop();
if(word == "reflect") this->material.reflection = num1;
else if (word == "transparency")this->material.transparency = num1;
}
//words with one string argument
else if(word == "texture") {
//TODO: attempt load texture from local directory first
if(lineContents.size() < 1) break;
textureName = lineContents.front();
lineContents.pop();
}
else break;
}
sharedInit(material,width,height,up,normal,textureName,origin);
}
/*
====================
Plane::Plane
Takes information for creation from parameters instead of input stream
so that it can be created by a complex object
====================
*/
Plane::Plane(Material m, double width, double height, Vector up, Vector normal, string textureName, Point origin) {
sharedInit(m,width,height,up,normal,textureName,origin);
}
/*
====================
Plane::sharedInit
Shared initialization method for all Plane objects
====================
*/
void Plane::sharedInit(Material m, double width, double height, Vector up, Vector normal, string textureName, Point origin) {
//Warns if Vectors are not orthogonal
if(abs(up.dot(normal)) > 0.00001) {
printf("Warning: Plane up vector ");
up.print();
printf(" and normal vector ");
normal.print();
printf(" are not orthogonal.\n");
}
this->objectType = ENTITY_PLANE;
this->origin = origin;
this->width = width;
this->height = height;
this->material = m;
this->up = up;
this->normal = normal;
this->hasTexture = false;
if(textureName.size() > 0 && this->texture.ReadFromFile(textureName.c_str())) {
this->hasTexture = true;
}
this->isLight = false;
this->isVisible = true;
this->up.normalize();
this->normal.normalize();
Vector left = this->normal.cross(this->up);
Point upMid = (this->up * this->height * 0.5) + this->origin;
vertex1 = upMid + (left * this->width * 0.5);
vertex2 = upMid - (left * this->width * 0.5);
vertex3 = vertex1 - (this->up * this->height);
vertex4 = vertex2 - (this->up * this->height);
}
/*
====================
Plane::intersect
Computes intersection between the Plane and the ray, and returns itself if
it is hit or NULL if it is not along with the point of intersection
====================
*/
SceneObject* Plane::intersect(Ray* r, Point &intersect) {
double dot = normal.dot(r->dir);
if(dot != 0) { //If the normal and ray aren't perpendicular (ray and plane parallel)
double t = normal.dot(origin - r->start) / dot;
if(t >= 0) { //If the ray is pointing toward the plane
//Calculate point of intersection on plane
Point tempInt = r->dir * t + r->start;
//Calculate vectors that define the rectangle and vector to point
// +----------> topLine
// |\
// | \ topLeftToPoint
// v
// leftLine
Vector topLine = vertex2 - vertex1;
Vector leftLine = vertex3 - vertex1;
Vector topLeftToPoint = tempInt - vertex1;
double leftProjectionLength = leftLine.dot(topLeftToPoint);
double leftLineLength = leftLine.dot(leftLine);
double topProjectionLength = topLine.dot(topLeftToPoint);
double topLineLength = topLine.dot(topLine);
if(0 <= leftProjectionLength && leftProjectionLength <= leftLineLength &&
0 <= topProjectionLength && topProjectionLength <= topLineLength) {
intersect = tempInt;
return this;
}
}
}
return NULL;
}
/*
====================
calculateTextureFromMaterial
based on the point of interception, calculates what color from the texture
should be returned
====================
*/
Color Plane::calculateTextureFromMaterial(Point intercept) {
BMP* temp;
temp = &this->texture;
int height = temp->TellHeight();
int width = temp->TellWidth();
double planeHeight = this->height;
double pixelSize = height / planeHeight; //Width and height of pixel on plane
//Figure out the boundaries of the plane
Vector left = normal.cross(up);
Point upMid = (this->up * this->height * 0.5) + this->origin;
Point upLeft = upMid + (left * this->width * 0.5);
Point upRight = upMid - (left * this->width * 0.5);
Point botLeft = upLeft - (this->up * this->height);
Point botRight = upRight - (this->up * this->height);
double heightPercentage = 0;
double widthPercentage = 0;
Ray top;
top.dir = upLeft - upRight;
top.start = upRight;
Ray planeUp;
planeUp.dir = this->up;
planeUp.start = intercept;
// ((p2 - p1)xd1) . (d1xd2) / ||d1xd2||^2
//percentage along top of plane
double tTopPoint = (planeUp.start - top.start).cross(planeUp.dir).dot(top.dir.cross(planeUp.dir)) / top.dir.cross(planeUp.dir).magnitude2();
//double tTopPoint = dot3((planeUp.start - top.start).cross(planeUp.dir), top.dir.cross(planeUp.dir))/magnitude2(top.dir.cross(planeUp.dir));
Ray side;
side.dir = upLeft - botLeft;
side.start = botLeft;
side.dir.normalize();
Ray planeLeft;
planeLeft.dir = left;
planeLeft.start = intercept;
//percentage along side of plane
//double tLeftPoint = 1 - (1.f/this->height) * (planeLeft.start - side.start).cross(planeLeft.dir).dot(side.dir.cross(planeLeft.dir)) / magnitude2(side.dir.cross(planeLeft.dir));
//double tLeftPoint = 1 - (1.f/this->height) * dot3((planeLeft.start - side.start).cross(planeLeft.dir),side.dir.cross(planeLeft.dir))/magnitude2(side.dir.cross(planeLeft.dir));
double tLeftPoint = 1 - (1.f/this->height) * (planeLeft.start - side.start).cross(planeLeft.dir).dot(side.dir.cross(planeLeft.dir)) / side.dir.cross(planeLeft.dir).magnitude2();
int pixelX = abs((int)(tTopPoint * width));
int pixelY = abs((int)(tLeftPoint * height));
pixelX %= width;
pixelY %= height;
Color matColor;
if(DIAGNOSTIC_STATUS == DIAGNOSTIC_TEXTURE_MAPPING) {
matColor = Color(tLeftPoint,1,tTopPoint);
}
else {
matColor.r = temp->GetPixel(pixelX,pixelY).Red/255.f;
matColor.g = temp->GetPixel(pixelX,pixelY).Green/255.f;
matColor.b = temp->GetPixel(pixelX,pixelY).Blue/255.f;
}
return matColor;
}
/*
====================
Plane::calculateNormalForPoint
Calculates the normal of the point p on the object as hit from ray r.
I assume an infinitely wide Plane, so this will always return the normal
as if the ray hit the Plane
====================
*/
Vector Plane::calculateNormalForPoint(Point p, Point raySource) {
double distNormalSide = (p + this->normal).comparitiveDistanceFrom(raySource);
double distOtherSide = (p - this->normal).comparitiveDistanceFrom(raySource);
if(distOtherSide < distNormalSide) return this->normal * -1;
return this->normal;
}
/*
====================
Plane::getReflection
Returns the reflection coefficient
====================
*/
double Plane::getReflection() {
return this->material.reflection;
}
/*
====================
Plane::getRefraction
Returns the refraction coefficient
====================
*/
double Plane::getRefraction() {
return this->material.transparency;
}
/*
====================
Plane::getColor
Returns the color of the object (ignoring texture color)
====================
*/
Color Plane::getColor() {
return this->material.color;
}
<commit_msg>Simplified plane texture projection.<commit_after>#include "ObjPlane.h"
/*
====================
Plane::Plane
Takes in the input stream and creates a Plane object from the parsed input
====================
*/
Plane::Plane(ifstream &f) {
string textureName;
while(!f.eof()) {
string line;
getline(f,line);
queue<string> lineContents;
explode(line," ",&lineContents);
if(lineContents.size() == 0) continue;
string word = lineContents.front();
lineContents.pop();
if(word[0] == '#' || line[0] == '\n' || line[0] == '\r') continue;
//words with three arguments
if(word == "origin" || word == "color" || word == "normal" || word == "up") {
double num1 = 0;
double num2 = 0;
double num3 = 0;
if(lineContents.size() < 3) break;
num1 = (double)atof(lineContents.front().c_str());
lineContents.pop();
num2 = (double)atof(lineContents.front().c_str());
lineContents.pop();
num3 = (double)atof(lineContents.front().c_str());
lineContents.pop();
if(word == "origin") this->origin = Point(num1,num2,num3);
else if(word == "color") material.color = Color(num1,num2,num3);
else if(word == "up") {
this->up = Vector(num1,num2,num3);
}
else if(word == "normal") {
this->normal = Vector(num1,num2,num3);
}
}
//words with two arguments
else if(word == "size") {
double num1 = 0;
double num2 = 0;
if(lineContents.size() < 2) break;
num1 = (double)atof(lineContents.front().c_str());
lineContents.pop();
num2 = (double)atof(lineContents.front().c_str());
lineContents.pop();
this->width = num1;
this->height = num2;
}
//words with one double argument
else if(word == "reflect" || word == "transparency") {
double num1 = 0;
if(lineContents.size() < 1) break;
num1 = (double)atof(lineContents.front().c_str());
lineContents.pop();
if(word == "reflect") this->material.reflection = num1;
else if (word == "transparency")this->material.transparency = num1;
}
//words with one string argument
else if(word == "texture") {
//TODO: attempt load texture from local directory first
if(lineContents.size() < 1) break;
textureName = lineContents.front();
lineContents.pop();
}
else break;
}
sharedInit(material,width,height,up,normal,textureName,origin);
}
/*
====================
Plane::Plane
Takes information for creation from parameters instead of input stream
so that it can be created by a complex object
====================
*/
Plane::Plane(Material m, double width, double height, Vector up, Vector normal, string textureName, Point origin) {
sharedInit(m,width,height,up,normal,textureName,origin);
}
/*
====================
Plane::sharedInit
Shared initialization method for all Plane objects
====================
*/
void Plane::sharedInit(Material m, double width, double height, Vector up, Vector normal, string textureName, Point origin) {
//Warns if Vectors are not orthogonal
if(abs(up.dot(normal)) > 0.00001) {
printf("Warning: Plane up vector ");
up.print();
printf(" and normal vector ");
normal.print();
printf(" are not orthogonal.\n");
}
this->objectType = ENTITY_PLANE;
this->origin = origin;
this->width = width;
this->height = height;
this->material = m;
this->up = up;
this->normal = normal;
this->hasTexture = false;
if(textureName.size() > 0 && this->texture.ReadFromFile(textureName.c_str())) {
this->hasTexture = true;
}
this->isLight = false;
this->isVisible = true;
this->up.normalize();
this->normal.normalize();
Vector left = this->normal.cross(this->up);
Point upMid = (this->up * this->height * 0.5) + this->origin;
vertex1 = upMid + (left * this->width * 0.5);
vertex2 = upMid - (left * this->width * 0.5);
vertex3 = vertex1 - (this->up * this->height);
vertex4 = vertex2 - (this->up * this->height);
}
/*
====================
Plane::intersect
Computes intersection between the Plane and the ray, and returns itself if
it is hit or NULL if it is not along with the point of intersection
====================
*/
SceneObject* Plane::intersect(Ray* r, Point &intersect) {
double dot = normal.dot(r->dir);
if(dot != 0) { //If the normal and ray aren't perpendicular (ray and plane parallel)
double t = normal.dot(origin - r->start) / dot;
if(t >= 0) { //If the ray is pointing toward the plane
//Calculate point of intersection on plane
Point tempInt = r->dir * t + r->start;
//Calculate vectors that define the rectangle and vector to point
// +----------> topLine
// |\
// | \ topLeftToPoint
// v
// leftLine
Vector topLine = vertex2 - vertex1;
Vector leftLine = vertex3 - vertex1;
Vector topLeftToPoint = tempInt - vertex1;
double leftProjectionLength = leftLine.dot(topLeftToPoint);
double leftLineLength = leftLine.dot(leftLine);
double topProjectionLength = topLine.dot(topLeftToPoint);
double topLineLength = topLine.dot(topLine);
if(0 <= leftProjectionLength && leftProjectionLength <= leftLineLength &&
0 <= topProjectionLength && topProjectionLength <= topLineLength) {
intersect = tempInt;
return this;
}
}
}
return NULL;
}
/*
====================
calculateTextureFromMaterial
based on the point of interception, calculates what color from the texture
should be returned
====================
*/
Color Plane::calculateTextureFromMaterial(Point intercept) {
BMP* temp;
temp = &this->texture;
int height = temp->TellHeight();
int width = temp->TellWidth();
double planeHeight = this->height;
double pixelSize = height / planeHeight; //Width and height of pixel on plane
Vector topLine = vertex2 - vertex1;
Vector leftLine = vertex3 - vertex1;
Vector topLeftToPoint = intercept - vertex1;
double leftProjectionLength = leftLine.dot(topLeftToPoint);
double leftLineLength = leftLine.dot(leftLine);
double topProjectionLength = topLine.dot(topLeftToPoint);
double topLineLength = topLine.dot(topLine);
double heightPercentage = leftProjectionLength / leftLineLength;
double widthPercentage = topProjectionLength / topLineLength;
int pixelX = abs((int)(widthPercentage * width));
int pixelY = abs((int)(heightPercentage * height));
pixelX %= width;
pixelY %= height;
Color matColor;
if(DIAGNOSTIC_STATUS == DIAGNOSTIC_TEXTURE_MAPPING) {
matColor = Color(heightPercentage,1,widthPercentage);
}
else {
matColor.r = temp->GetPixel(pixelX,pixelY).Red/255.f;
matColor.g = temp->GetPixel(pixelX,pixelY).Green/255.f;
matColor.b = temp->GetPixel(pixelX,pixelY).Blue/255.f;
}
return matColor;
}
/*
====================
Plane::calculateNormalForPoint
Calculates the normal of the point p on the object as hit from ray r.
I assume an infinitely wide Plane, so this will always return the normal
as if the ray hit the Plane
====================
*/
Vector Plane::calculateNormalForPoint(Point p, Point raySource) {
double distNormalSide = (p + this->normal).comparitiveDistanceFrom(raySource);
double distOtherSide = (p - this->normal).comparitiveDistanceFrom(raySource);
if(distOtherSide < distNormalSide) return this->normal * -1;
return this->normal;
}
/*
====================
Plane::getReflection
Returns the reflection coefficient
====================
*/
double Plane::getReflection() {
return this->material.reflection;
}
/*
====================
Plane::getRefraction
Returns the refraction coefficient
====================
*/
double Plane::getRefraction() {
return this->material.transparency;
}
/*
====================
Plane::getColor
Returns the color of the object (ignoring texture color)
====================
*/
Color Plane::getColor() {
return this->material.color;
}
<|endoftext|> |
<commit_before>//
// PTSolver.cpp
// PowerTools++
//
// Created by Hassan on 30/01/2015.
// Copyright (c) 2015 NICTA. All rights reserved.
//
#include "PowerTools++/PTSolver.h"
#ifdef USE_BONMIN
#include <coin/BonBonminSetup.hpp>
#include <coin/BonCbc.hpp>
#endif
namespace {
void gurobiNotAvailable()
{
cerr << "Can't use Gurobi for solver: this version of PowerTools "
"was compiled without Gurobi support." << endl;
exit(1);
}
void bonminNotAvailable()
{
cerr << "Can't use Bonmin for solver: this version of PowerTools "
"was compiled without Bonmin support." << endl;
exit(1);
}
}
PTSolver::PTSolver(Model* model, SolverType stype){
_stype = stype;
switch (stype) {
case ipopt:
prog.ipopt_prog = new IpoptProgram(model);
break;
case gurobi:
#ifdef USE_GUROBI
try{
prog.grb_prog = new GurobiProgram(model);
}catch(GRBException e) {
cerr << "\nError code = " << e.getErrorCode() << endl;
cerr << e.getMessage() << endl;
exit(1);
}
#else
gurobiNotAvailable();
#endif
break;
case bonmin:
#ifdef USE_BONMIN
prog.bonmin_prog = new BonminProgram(model);
#else
bonminNotAvailable();
#endif
break;
}
}
PTSolver::~PTSolver(){
if (_stype == gurobi) {
#ifdef USE_GUROBI
delete prog.grb_prog;
#else
gurobiNotAvailable();
#endif
}
if (_stype == ipopt) delete prog.ipopt_prog;
}
void PTSolver::set_model(Model* m) {
if (_stype == gurobi){
#ifdef USE_GUROBI
prog.grb_prog->model = m;
#else
gurobiNotAvailable();
#endif
}
if (_stype == ipopt) prog.ipopt_prog->model = m;
}
int PTSolver::run(int output, bool relax){
//GurobiProgram* grbprog;
// Initialize the IpoptApplication and process the options
if (_stype==ipopt) {
IpoptApplication iapp;
ApplicationReturnStatus status = iapp.Initialize();
if (status != Solve_Succeeded) {
std::cout << std::endl << std::endl << "*** Error during initialization!" << std::endl;
return (int) status;
}
if(prog.ipopt_prog->model->_objt==maximize){
*prog.ipopt_prog->model->_obj *= -1;
}
SmartPtr<TNLP> tmp = new IpoptProgram(prog.ipopt_prog->model);
// prog.ipopt_prog;
// iapp.Options()->SetStringValue("hessian_constant", "yes");
// iapp.Options()->SetStringValue("derivative_test", "second-order");
// iapp->Options()->SetNumericValue("tol", 1e-6);
// iapp.Options()->SetNumericValue("tol", 1e-6);
// iapp->Options()->SetStringValue("derivative_test", "second-order");
// iapp.Options()->SetNumericValue("bound_relax_factor", 0);
// iapp.Options()->SetIntegerValue("print_level", 5);
// iapp.Options()->SetStringValue("derivative_test_print_all", "yes");
status = iapp.OptimizeTNLP(tmp);
if(prog.ipopt_prog->model->_objt==maximize){
*prog.ipopt_prog->model->_obj *= -1;
}
if (status == Solve_Succeeded) {
// Retrieve some statistics about the solve
// printf("\n\nSolution of the primal variables:\n");
// _model->print_solution();
// return status;
return 100;
}
if (status == Solved_To_Acceptable_Level) {
return 150;
}
}
else if(_stype==gurobi)
{
#ifdef USE_GUROBI
try{
// prog.grbprog = new GurobiProgram();
prog.grb_prog->_output = output;
prog.grb_prog->reset_model();
prog.grb_prog->prepare_model();
bool ok = prog.grb_prog->solve(relax);
return ok ? 100 : -1;
}catch(GRBException e) {
cerr << "\nError code = " << e.getErrorCode() << endl;
cerr << e.getMessage() << endl;
}
#else
gurobiNotAvailable();
#endif
}
else if(_stype==bonmin) {
#ifdef USE_BONMIN
using namespace Bonmin;
BonminSetup bonmin;
bonmin.initializeOptionsAndJournalist();
bonmin.initialize(prog.bonmin_prog);
try {
Bab bb;
bb(bonmin);
}
catch(TNLPSolver::UnsolvedError *E) {
//There has been a failure to solve a problem with Bonmin.
std::cerr<<"Bonmin has failed to solve a problem"<<std::endl;
}
catch(OsiTMINLPInterface::SimpleError &E) {
std::cerr<<E.className()<<"::"<<E.methodName()
<<std::endl
<<E.message()<<std::endl;
}
catch(CoinError &E) {
std::cerr<<E.className()<<"::"<<E.methodName()
<<std::endl
<<E.message()<<std::endl;
}
#else
bonminNotAvailable();
#endif
}
return -1;
}
<commit_msg>Allow bonmin to maximise or minimise.<commit_after>//
// PTSolver.cpp
// PowerTools++
//
// Created by Hassan on 30/01/2015.
// Copyright (c) 2015 NICTA. All rights reserved.
//
#include "PowerTools++/PTSolver.h"
#ifdef USE_BONMIN
#include <coin/BonBonminSetup.hpp>
#include <coin/BonCbc.hpp>
#endif
namespace {
void gurobiNotAvailable()
{
cerr << "Can't use Gurobi for solver: this version of PowerTools "
"was compiled without Gurobi support." << endl;
exit(1);
}
void bonminNotAvailable()
{
cerr << "Can't use Bonmin for solver: this version of PowerTools "
"was compiled without Bonmin support." << endl;
exit(1);
}
}
PTSolver::PTSolver(Model* model, SolverType stype){
_stype = stype;
switch (stype) {
case ipopt:
prog.ipopt_prog = new IpoptProgram(model);
break;
case gurobi:
#ifdef USE_GUROBI
try{
prog.grb_prog = new GurobiProgram(model);
}catch(GRBException e) {
cerr << "\nError code = " << e.getErrorCode() << endl;
cerr << e.getMessage() << endl;
exit(1);
}
#else
gurobiNotAvailable();
#endif
break;
case bonmin:
#ifdef USE_BONMIN
prog.bonmin_prog = new BonminProgram(model);
#else
bonminNotAvailable();
#endif
break;
}
}
PTSolver::~PTSolver(){
if (_stype == gurobi) {
#ifdef USE_GUROBI
delete prog.grb_prog;
#else
gurobiNotAvailable();
#endif
}
if (_stype == ipopt) delete prog.ipopt_prog;
}
void PTSolver::set_model(Model* m) {
if (_stype == gurobi){
#ifdef USE_GUROBI
prog.grb_prog->model = m;
#else
gurobiNotAvailable();
#endif
}
if (_stype == ipopt) prog.ipopt_prog->model = m;
}
int PTSolver::run(int output, bool relax){
//GurobiProgram* grbprog;
// Initialize the IpoptApplication and process the options
if (_stype==ipopt) {
IpoptApplication iapp;
ApplicationReturnStatus status = iapp.Initialize();
if (status != Solve_Succeeded) {
std::cout << std::endl << std::endl << "*** Error during initialization!" << std::endl;
return (int) status;
}
if(prog.ipopt_prog->model->_objt==maximize){
*prog.ipopt_prog->model->_obj *= -1;
}
SmartPtr<TNLP> tmp = new IpoptProgram(prog.ipopt_prog->model);
// prog.ipopt_prog;
// iapp.Options()->SetStringValue("hessian_constant", "yes");
// iapp.Options()->SetStringValue("derivative_test", "second-order");
// iapp->Options()->SetNumericValue("tol", 1e-6);
// iapp.Options()->SetNumericValue("tol", 1e-6);
// iapp->Options()->SetStringValue("derivative_test", "second-order");
// iapp.Options()->SetNumericValue("bound_relax_factor", 0);
// iapp.Options()->SetIntegerValue("print_level", 5);
// iapp.Options()->SetStringValue("derivative_test_print_all", "yes");
status = iapp.OptimizeTNLP(tmp);
if(prog.ipopt_prog->model->_objt==maximize){
*prog.ipopt_prog->model->_obj *= -1;
}
if (status == Solve_Succeeded) {
// Retrieve some statistics about the solve
// printf("\n\nSolution of the primal variables:\n");
// _model->print_solution();
// return status;
return 100;
}
if (status == Solved_To_Acceptable_Level) {
return 150;
}
}
else if(_stype==gurobi)
{
#ifdef USE_GUROBI
try{
// prog.grbprog = new GurobiProgram();
prog.grb_prog->_output = output;
prog.grb_prog->reset_model();
prog.grb_prog->prepare_model();
bool ok = prog.grb_prog->solve(relax);
return ok ? 100 : -1;
}catch(GRBException e) {
cerr << "\nError code = " << e.getErrorCode() << endl;
cerr << e.getMessage() << endl;
}
#else
gurobiNotAvailable();
#endif
}
else if(_stype==bonmin) {
#ifdef USE_BONMIN
if(prog.bonmin_prog->model->_objt==maximize){
*prog.bonmin_prog->model->_obj *= -1;
}
bool ok = true;
using namespace Bonmin;
BonminSetup bonmin;
bonmin.initializeOptionsAndJournalist();
bonmin.initialize(prog.bonmin_prog);
try {
Bab bb;
bb(bonmin);
}
catch(TNLPSolver::UnsolvedError *E) {
//There has been a failure to solve a problem with Bonmin.
std::cerr<<"Bonmin has failed to solve a problem"<<std::endl;
ok = false;
}
catch(OsiTMINLPInterface::SimpleError &E) {
std::cerr<<E.className()<<"::"<<E.methodName()
<<std::endl
<<E.message()<<std::endl;
ok = false;
}
catch(CoinError &E) {
std::cerr<<E.className()<<"::"<<E.methodName()
<<std::endl
<<E.message()<<std::endl;
ok = false;
}
if(prog.bonmin_prog->model->_objt==maximize){
*prog.bonmin_prog->model->_obj *= -1;
}
return ok ? 100 : -1;
#else
bonminNotAvailable();
#endif
}
return -1;
}
<|endoftext|> |
<commit_before>#ifndef _SDD_DD_PROTO_NODE_HH_
#define _SDD_DD_PROTO_NODE_HH_
#include <algorithm> // equal, for_each
#include <functional> // hash
#include <iosfwd>
#include <vector>
#include "sdd/dd/definition.hh"
#include "sdd/dd/stack.hh"
#include "sdd/util/hash.hh"
namespace sdd {
/*------------------------------------------------------------------------------------------------*/
template <typename C>
struct proto_arc
{
using values_type = typename C::Values;
using value_type = typename values_type::value_type;
using value_stack_type = dd::stack<value_type>;
using successor_stack_type = dd::stack<SDD<C>>;
const values_type current_values;
value_stack_type values;
successor_stack_type successors;
proto_arc( values_type&& values, value_stack_type&& value_stack
, successor_stack_type&& successors_stack)
: current_values(std::move(values)), values(std::move(value_stack))
, successors(std::move(successors_stack))
{}
};
template <typename C>
inline
bool
operator==(const proto_arc<C>& lhs, const proto_arc<C>& rhs)
noexcept
{
return lhs.current_values == rhs.current_values and lhs.values == rhs.values
and lhs.successors == rhs.successors;
}
/*------------------------------------------------------------------------------------------------*/
/// @brief A non-terminal node in an SDD.
///
/// For the sake of canonicity, a node shall not exist in several locations, thus we prevent
/// its copy. Also, to enforce this canonicity, we need that nodes have always the same
/// address, thus they can't be moved to an other memory location once created.
template <typename C>
class proto_node final
{
// Can't copy a proto_node.
proto_node& operator=(const proto_node&) = delete;
proto_node(const proto_node&) = delete;
// Can't move a proto_node.
proto_node& operator=(proto_node&&) = delete;
proto_node(proto_node&&) = delete;
public:
/// @brief The type of the valuation of this node.
using values_type = typename C::Values;
using value_type = typename values_type::value_type;
using arcs_type = std::vector<proto_arc<C>>;
using const_iterator = typename arcs_type::const_iterator;
private:
const arcs_type arcs_;
public:
proto_node(arcs_type&& arcs)
: arcs_(std::move(arcs))
{}
/// @brief Get the beginning of arcs.
///
/// O(1).
const_iterator
begin()
const noexcept
{
return arcs_.begin();
}
/// @brief Get the end of arcs.
///
/// O(1).
const_iterator
end()
const noexcept
{
return arcs_.end();
}
const arcs_type&
arcs()
const noexcept
{
return arcs_;
}
};
/*------------------------------------------------------------------------------------------------*/
/// @brief Equality of two proto_node.
/// @related proto_node
///
/// O(1) if nodes don't have the same number of arcs; otherwise O(n) where n is the number of
/// arcs.
template <typename C>
inline
bool
operator==(const proto_node<C>& lhs, const proto_node<C>& rhs)
noexcept
{
return lhs.arcs() == rhs.arcs();
}
/// @brief Export a proto_node to a stream.
/// @related proto_node
template <typename C>
std::ostream&
operator<<(std::ostream& os, const proto_node<C>& n)
{
os << "proto_node " << &n << ":" << std::endl;
for (const auto& arc : n)
{
os << " arc " << &n << ":" << std::endl;
os << " current values: " << arc.current_values << std::endl;
os << " values stack: " << arc.values << std::endl;
os << " successors stack: |";
for (const auto& successor : arc.successors.elements)
{
os << &successor << ",";
}
os << "|";
}
os << std::endl;
for (const auto& arc : n)
{
for (const auto& successor : arc.successors.elements)
{
os << successor;
}
}
return os << std::endl;
}
/*------------------------------------------------------------------------------------------------*/
} // namespace sdd
namespace std {
/*------------------------------------------------------------------------------------------------*/
/// @brief Hash specialization for sdd::proto_arc
template <typename C>
struct hash<sdd::proto_arc<C>>
{
std::size_t
operator()(const sdd::proto_arc<C>& n)
const noexcept /*(noexcept(???))*/
{
std::size_t seed = sdd::util::hash(n.current_values);
sdd::util::hash_combine(seed, n.values);
sdd::util::hash_combine(seed, n.successors);
return seed;
}
};
/// @brief Hash specialization for sdd::proto_node
template <typename C>
struct hash<sdd::proto_node<C>>
{
std::size_t
operator()(const sdd::proto_node<C>& n)
const noexcept(noexcept(sdd::util::hash(n.begin(), n.end())))
{
return sdd::util::hash(n.begin(), n.end());
}
};
/*------------------------------------------------------------------------------------------------*/
} // namespace std
#endif // _SDD_DD_PROTO_NODE_HH_
<commit_msg>Make proto_arc movable.<commit_after>#ifndef _SDD_DD_PROTO_NODE_HH_
#define _SDD_DD_PROTO_NODE_HH_
#include <algorithm> // equal, for_each
#include <functional> // hash
#include <iosfwd>
#include <vector>
#include "sdd/dd/definition.hh"
#include "sdd/dd/stack.hh"
#include "sdd/util/hash.hh"
namespace sdd {
/*------------------------------------------------------------------------------------------------*/
template <typename C>
struct proto_arc
{
using values_type = typename C::Values;
using value_type = typename values_type::value_type;
using value_stack_type = dd::stack<value_type>;
using successor_stack_type = dd::stack<SDD<C>>;
values_type current_values;
value_stack_type values;
successor_stack_type successors;
proto_arc(proto_arc&&) = default;
proto_arc& operator=(proto_arc&&) = default;
proto_arc( values_type&& values, value_stack_type&& value_stack
, successor_stack_type&& successors_stack)
: current_values(std::move(values)), values(std::move(value_stack))
, successors(std::move(successors_stack))
{}
};
template <typename C>
inline
bool
operator==(const proto_arc<C>& lhs, const proto_arc<C>& rhs)
noexcept
{
return lhs.current_values == rhs.current_values and lhs.values == rhs.values
and lhs.successors == rhs.successors;
}
/*------------------------------------------------------------------------------------------------*/
/// @brief A non-terminal node in an SDD.
///
/// For the sake of canonicity, a node shall not exist in several locations, thus we prevent
/// its copy. Also, to enforce this canonicity, we need that nodes have always the same
/// address, thus they can't be moved to an other memory location once created.
template <typename C>
class proto_node final
{
// Can't copy a proto_node.
proto_node& operator=(const proto_node&) = delete;
proto_node(const proto_node&) = delete;
// Can't move a proto_node.
proto_node& operator=(proto_node&&) = delete;
proto_node(proto_node&&) = delete;
public:
/// @brief The type of the valuation of this node.
using values_type = typename C::Values;
using value_type = typename values_type::value_type;
using arcs_type = std::vector<proto_arc<C>>;
using const_iterator = typename arcs_type::const_iterator;
private:
const arcs_type arcs_;
public:
proto_node(arcs_type&& arcs)
: arcs_(std::move(arcs))
{}
/// @brief Get the beginning of arcs.
///
/// O(1).
const_iterator
begin()
const noexcept
{
return arcs_.begin();
}
/// @brief Get the end of arcs.
///
/// O(1).
const_iterator
end()
const noexcept
{
return arcs_.end();
}
const arcs_type&
arcs()
const noexcept
{
return arcs_;
}
};
/*------------------------------------------------------------------------------------------------*/
/// @brief Equality of two proto_node.
/// @related proto_node
///
/// O(1) if nodes don't have the same number of arcs; otherwise O(n) where n is the number of
/// arcs.
template <typename C>
inline
bool
operator==(const proto_node<C>& lhs, const proto_node<C>& rhs)
noexcept
{
return lhs.arcs() == rhs.arcs();
}
/// @brief Export a proto_node to a stream.
/// @related proto_node
template <typename C>
std::ostream&
operator<<(std::ostream& os, const proto_node<C>& n)
{
os << "proto_node " << &n << ":" << std::endl;
for (const auto& arc : n)
{
os << " arc " << &n << ":" << std::endl;
os << " current values: " << arc.current_values << std::endl;
os << " values stack: " << arc.values << std::endl;
os << " successors stack: |";
for (const auto& successor : arc.successors.elements)
{
os << &successor << ",";
}
os << "|";
}
os << std::endl;
for (const auto& arc : n)
{
for (const auto& successor : arc.successors.elements)
{
os << successor;
}
}
return os << std::endl;
}
/*------------------------------------------------------------------------------------------------*/
} // namespace sdd
namespace std {
/*------------------------------------------------------------------------------------------------*/
/// @brief Hash specialization for sdd::proto_arc
template <typename C>
struct hash<sdd::proto_arc<C>>
{
std::size_t
operator()(const sdd::proto_arc<C>& n)
const noexcept /*(noexcept(???))*/
{
std::size_t seed = sdd::util::hash(n.current_values);
sdd::util::hash_combine(seed, n.values);
sdd::util::hash_combine(seed, n.successors);
return seed;
}
};
/// @brief Hash specialization for sdd::proto_node
template <typename C>
struct hash<sdd::proto_node<C>>
{
std::size_t
operator()(const sdd::proto_node<C>& n)
const noexcept(noexcept(sdd::util::hash(n.begin(), n.end())))
{
return sdd::util::hash(n.begin(), n.end());
}
};
/*------------------------------------------------------------------------------------------------*/
} // namespace std
#endif // _SDD_DD_PROTO_NODE_HH_
<|endoftext|> |
<commit_before>// This file is part of Tasks.
//
// Tasks is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Tasks 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 Tasks. If not, see <http://www.gnu.org/licenses/>.
// associated header
#include "QPConstr.h"
// includes
// RBDyn
#include <MultiBody.h>
#include <MultiBodyConfig.h>
// SCD
#include <SCD/CD/CD_Pair.h>
#include <SCD/S_Object/S_Object.h>
namespace tasks
{
namespace qp
{
MotionConstr::MotionConstr(const rbd::MultiBody& mb):
fd_(mb),
cont_(),
fullJac_(6, mb.nrDof()),
AEq_(),
BEq_(),
XL_(),
XU_(),
nrDof_(0),
nrFor_(0),
nrTor_(0)
{
}
void MotionConstr::updateNrVars(const rbd::MultiBody& mb,
int alphaD, int lambda, int torque, const std::vector<Contact>& cont)
{
cont_.resize(cont.size());
nrDof_ = alphaD;
nrFor_ = lambda;
nrTor_ = torque;
for(std::size_t i = 0; i < cont_.size(); ++i)
{
cont_[i].jac = rbd::Jacobian(mb, cont[i].bodyId);
cont_[i].transJac.resize(6, cont_[i].jac.dof());
cont_[i].points = cont[i].points;
cont_[i].normals = cont[i].normals;
}
AEq_.resize(nrDof_, nrDof_ + nrFor_ + nrTor_);
BEq_.resize(nrDof_);
AEq_.setZero();
BEq_.setZero();
XL_.resize(nrFor_);
XU_.resize(nrFor_);
XL_.fill(0.);
XU_.fill(std::numeric_limits<double>::infinity());
}
void MotionConstr::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc)
{
using namespace Eigen;
fd_.computeH(mb, mbc);
fd_.computeC(mb, mbc);
// H*alphaD - tau - tau_c = -C
// AEq
// nrDof nrFor nrTor
// nrDof [ H -Sum J_i^t*ni [0 ... -1]
AEq_.block(0, 0, nrDof_, nrDof_) = fd_.H();
int contPos = nrDof_;
for(std::size_t i = 0; i < cont_.size(); ++i)
{
const MatrixXd& jac = cont_[i].jac.jacobian(mb, mbc);
for(std::size_t j = 0; j < cont_[i].points.size(); ++j)
{
cont_[i].jac.translateJacobian(jac, mbc, cont_[i].points[j], cont_[i].transJac);
cont_[i].jac.fullJacobian(mb, cont_[i].transJac, fullJac_);
AEq_.block(0, contPos, nrDof_, 1) =
-fullJac_.block(3, 0, 3, fullJac_.cols()).transpose()*cont_[i].normals[j];
contPos += 1;
}
}
AEq_.block(mb.joint(0).dof(), contPos, nrTor_, nrTor_) =
-MatrixXd::Identity(nrTor_, nrTor_);
// BEq = -C
BEq_ = -fd_.C();
}
int MotionConstr::nrEqLine()
{
return nrDof_;
}
const Eigen::MatrixXd& MotionConstr::AEq() const
{
return AEq_;
}
const Eigen::VectorXd& MotionConstr::BEq() const
{
return BEq_;
}
int MotionConstr::beginVar()
{
return nrDof_;
}
const Eigen::VectorXd& MotionConstr::Lower() const
{
return XL_;
}
const Eigen::VectorXd& MotionConstr::Upper() const
{
return XU_;
}
ContactAccConstr::ContactAccConstr(const rbd::MultiBody& mb):
cont_(),
fullJac_(6, mb.nrDof()),
alphaVec_(mb.nrDof()),
AEq_(),
BEq_(),
nrDof_(0),
nrFor_(0),
nrTor_(0)
{}
void ContactAccConstr::updateNrVars(const rbd::MultiBody& mb,
int alphaD, int lambda, int torque, const std::vector<Contact>& cont)
{
cont_.resize(cont.size());
nrDof_ = alphaD;
nrFor_ = lambda;
nrTor_ = torque;
for(std::size_t i = 0; i < cont_.size(); ++i)
{
cont_[i].jac = rbd::Jacobian(mb, cont[i].bodyId);
}
AEq_.resize(cont_.size()*6 , nrDof_ + nrFor_ + nrTor_);
BEq_.resize(cont_.size()*6);
AEq_.setZero();
BEq_.setZero();
}
void ContactAccConstr::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc)
{
using namespace Eigen;
rbd::paramToVector(mbc.alpha, alphaVec_);
// J_i*alphaD + JD_i*alpha = 0
for(std::size_t i = 0; i < cont_.size(); ++i)
{
// AEq = J_i
const MatrixXd& jac = cont_[i].jac.jacobian(mb, mbc);
cont_[i].jac.fullJacobian(mb, jac, fullJac_);
AEq_.block(i*6, 0, 6, mb.nrDof()) = fullJac_;
// BEq = -JD_i*alpha
const MatrixXd& jacDot = cont_[i].jac.jacobianDot(mb, mbc);
cont_[i].jac.fullJacobian(mb, jacDot, fullJac_);
BEq_.segment(i*6, 6) = -fullJac_*alphaVec_;
}
}
int ContactAccConstr::nrEqLine()
{
return AEq_.rows();
}
const Eigen::MatrixXd& ContactAccConstr::AEq() const
{
return AEq_;
}
const Eigen::VectorXd& ContactAccConstr::BEq() const
{
return BEq_;
}
/**
* SelfCollisionConstr
*/
SCD::Matrix4x4 fromSCD(const sva::PTransform& t)
{
SCD::Matrix4x4 m;
const Eigen::Matrix3d& rot = t.rotation();
const Eigen::Vector3d& tran = t.translation();
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
m(i,j) = rot(j,i);
}
}
m(0,3) = tran(0);
m(1,3) = tran(1);
m(2,3) = tran(2);
return m;
}
SelfCollisionConstr::CollData::CollData(const rbd::MultiBody& mb,
int body1Id, SCD::S_Object* body1,
int body2Id, SCD::S_Object* body2,
double di, double ds, double damping):
pair(new SCD::CD_Pair(body1, body2)),
normVecDist(Eigen::Vector3d::Zero()),
jacB1(rbd::Jacobian(mb, body1Id)),
jacB2(rbd::Jacobian(mb, body2Id)),
di(di),
ds(ds),
damping(damping),
body1Id(body1Id),
body2Id(body2Id),
body1(mb.bodyIndexById(body1Id)),
body2(mb.bodyIndexById(body2Id))
{
}
SelfCollisionConstr::CollData::~CollData()
{
delete pair;
}
SelfCollisionConstr::SelfCollisionConstr(const rbd::MultiBody& mb, double step):
dataVec_(),
step_(step),
nrVars_(0),
AInEq_(),
BInEq_(),
fullJac_(6, mb.nrDof()),
fullJacDot_(6, mb.nrDof()),
alphaVec_(mb.nrDof()),
calcVec_(mb.nrDof())
{
}
void SelfCollisionConstr::addCollision(const rbd::MultiBody& mb,
int body1Id, SCD::S_Object* body1,
int body2Id, SCD::S_Object* body2,
double di, double ds, double damping)
{
dataVec_.emplace_back(mb, body1Id, body1, body2Id, body2, di, ds, damping);
}
void SelfCollisionConstr::rmCollision(int body1Id, int body2Id)
{
auto it = std::find_if(dataVec_.begin(), dataVec_.end(),
[body1Id, body2Id](const CollData& data)
{
return data.body1Id == body1Id && data.body2Id == body2Id;
});
if(it != dataVec_.end())
{
dataVec_.erase(it);
}
}
void SelfCollisionConstr::reset()
{
dataVec_.clear();
}
void SelfCollisionConstr::updateNrVars(const rbd::MultiBody& /* mb */,
int alphaD, int lambda, int torque, const std::vector<Contact>& /* cont */)
{
nrVars_ = alphaD + lambda + torque;
}
void SelfCollisionConstr::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc)
{
using namespace Eigen;
if(static_cast<unsigned int>(AInEq_.rows()) != dataVec_.size()
|| AInEq_.cols() != nrVars_)
{
AInEq_.resize(dataVec_.size(), nrVars_);
BInEq_.resize(dataVec_.size());
AInEq_.setZero();
BInEq_.setZero();
}
rbd::paramToVector(mbc.alpha, alphaVec_);
int i = 0;
for(CollData& d: dataVec_)
{
SCD::Point3 pb1Tmp, pb2Tmp;
(*d.pair)[0]->setTransformation(fromSCD(mbc.bodyPosW[d.body1]));
(*d.pair)[1]->setTransformation(fromSCD(mbc.bodyPosW[d.body2]));
double dist = d.pair->getClosestPoints(pb1Tmp, pb2Tmp);
dist = dist >= 0 ? std::sqrt(dist) : -std::sqrt(-dist);
Vector3d pb1(pb1Tmp[0], pb1Tmp[1], pb1Tmp[2]);
Vector3d pb2(pb2Tmp[0], pb2Tmp[1], pb2Tmp[2]);
Eigen::Vector3d normVecDist = (pb1 - pb2)/dist;
pb1 = (mbc.bodyPosW[d.body1].inv()*sva::PTransform(pb1)).translation();
pb2 = (mbc.bodyPosW[d.body2].inv()*sva::PTransform(pb2)).translation();
if(dist < d.di)
{
double dampers = d.damping*((dist - d.ds)/(d.di - d.ds));
Vector3d nf = normVecDist;
Vector3d onf = d.normVecDist;
Vector3d dnf = (nf - onf)/step_;
// Compute body1
d.jacB1.point(pb1);
const MatrixXd& jac1 = d.jacB1.jacobian(mb, mbc);
const MatrixXd& jacDot1 = d.jacB1.jacobianDot(mb, mbc);
d.jacB1.fullJacobian(mb, jac1, fullJac_);
d.jacB1.fullJacobian(mb, jacDot1, fullJacDot_);
double jqdn = ((fullJac_.block(3, 0, 3, fullJac_.cols())*alphaVec_).transpose()*nf)(0);
double jqdnd = ((fullJac_.block(3, 0, 3, fullJac_.cols())*alphaVec_).transpose()*dnf*step_)(0);
double jdqdn = ((fullJacDot_.block(3, 0, 3, fullJac_.cols())*alphaVec_).transpose()*nf*step_)(0);
calcVec_ = -fullJac_.block(3, 0, 3, fullJac_.cols()).transpose()*nf*step_;
// Compute body2
d.jacB2.point(pb2);
const MatrixXd& jac2 = d.jacB2.jacobian(mb, mbc);
const MatrixXd& jacDot2 = d.jacB2.jacobianDot(mb, mbc);
d.jacB2.fullJacobian(mb, jac2, fullJac_);
d.jacB2.fullJacobian(mb, jacDot2, fullJacDot_);
jqdn = -((fullJac_.block(3, 0, 3, fullJac_.cols())*alphaVec_).transpose()*nf)(0);
jqdnd = -((fullJac_.block(3, 0, 3, fullJac_.cols())*alphaVec_).transpose()*dnf*step_)(0);
jdqdn = -((fullJacDot_.block(3, 0, 3, fullJac_.cols())*alphaVec_).transpose()*nf*step_)(0);
calcVec_ += fullJac_.block(3, 0, 3, fullJac_.cols()).transpose()*nf*step_;
// distdot + distdotdot*dt > -damp*((d - ds)/(di - ds))
AInEq_.block(i, 0, 1, mb.nrDof()) = calcVec_.transpose();
BInEq_(i) = dampers + jqdn + jqdnd + jdqdn;
}
else
{
AInEq_.block(i, 0, 1, mb.nrDof()).setZero();
BInEq_(i) = 0.;
}
d.normVecDist = normVecDist;
++i;
}
}
int SelfCollisionConstr::nrInEqLine()
{
return dataVec_.size();
}
const Eigen::MatrixXd& SelfCollisionConstr::AInEq() const
{
return AInEq_;
}
const Eigen::VectorXd& SelfCollisionConstr::BInEq() const
{
return BInEq_;
}
} // namespace qp
} // namespace tasks
<commit_msg>Fix auto collision computation.<commit_after>// This file is part of Tasks.
//
// Tasks is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Tasks 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 Tasks. If not, see <http://www.gnu.org/licenses/>.
// associated header
#include "QPConstr.h"
// includes
// RBDyn
#include <MultiBody.h>
#include <MultiBodyConfig.h>
// SCD
#include <SCD/CD/CD_Pair.h>
#include <SCD/S_Object/S_Object.h>
namespace tasks
{
namespace qp
{
MotionConstr::MotionConstr(const rbd::MultiBody& mb):
fd_(mb),
cont_(),
fullJac_(6, mb.nrDof()),
AEq_(),
BEq_(),
XL_(),
XU_(),
nrDof_(0),
nrFor_(0),
nrTor_(0)
{
}
void MotionConstr::updateNrVars(const rbd::MultiBody& mb,
int alphaD, int lambda, int torque, const std::vector<Contact>& cont)
{
cont_.resize(cont.size());
nrDof_ = alphaD;
nrFor_ = lambda;
nrTor_ = torque;
for(std::size_t i = 0; i < cont_.size(); ++i)
{
cont_[i].jac = rbd::Jacobian(mb, cont[i].bodyId);
cont_[i].transJac.resize(6, cont_[i].jac.dof());
cont_[i].points = cont[i].points;
cont_[i].normals = cont[i].normals;
}
AEq_.resize(nrDof_, nrDof_ + nrFor_ + nrTor_);
BEq_.resize(nrDof_);
AEq_.setZero();
BEq_.setZero();
XL_.resize(nrFor_);
XU_.resize(nrFor_);
XL_.fill(0.);
XU_.fill(std::numeric_limits<double>::infinity());
}
void MotionConstr::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc)
{
using namespace Eigen;
fd_.computeH(mb, mbc);
fd_.computeC(mb, mbc);
// H*alphaD - tau - tau_c = -C
// AEq
// nrDof nrFor nrTor
// nrDof [ H -Sum J_i^t*ni [0 ... -1]
AEq_.block(0, 0, nrDof_, nrDof_) = fd_.H();
int contPos = nrDof_;
for(std::size_t i = 0; i < cont_.size(); ++i)
{
const MatrixXd& jac = cont_[i].jac.jacobian(mb, mbc);
for(std::size_t j = 0; j < cont_[i].points.size(); ++j)
{
cont_[i].jac.translateJacobian(jac, mbc, cont_[i].points[j], cont_[i].transJac);
cont_[i].jac.fullJacobian(mb, cont_[i].transJac, fullJac_);
AEq_.block(0, contPos, nrDof_, 1) =
-fullJac_.block(3, 0, 3, fullJac_.cols()).transpose()*cont_[i].normals[j];
contPos += 1;
}
}
AEq_.block(mb.joint(0).dof(), contPos, nrTor_, nrTor_) =
-MatrixXd::Identity(nrTor_, nrTor_);
// BEq = -C
BEq_ = -fd_.C();
}
int MotionConstr::nrEqLine()
{
return nrDof_;
}
const Eigen::MatrixXd& MotionConstr::AEq() const
{
return AEq_;
}
const Eigen::VectorXd& MotionConstr::BEq() const
{
return BEq_;
}
int MotionConstr::beginVar()
{
return nrDof_;
}
const Eigen::VectorXd& MotionConstr::Lower() const
{
return XL_;
}
const Eigen::VectorXd& MotionConstr::Upper() const
{
return XU_;
}
ContactAccConstr::ContactAccConstr(const rbd::MultiBody& mb):
cont_(),
fullJac_(6, mb.nrDof()),
alphaVec_(mb.nrDof()),
AEq_(),
BEq_(),
nrDof_(0),
nrFor_(0),
nrTor_(0)
{}
void ContactAccConstr::updateNrVars(const rbd::MultiBody& mb,
int alphaD, int lambda, int torque, const std::vector<Contact>& cont)
{
cont_.resize(cont.size());
nrDof_ = alphaD;
nrFor_ = lambda;
nrTor_ = torque;
for(std::size_t i = 0; i < cont_.size(); ++i)
{
cont_[i].jac = rbd::Jacobian(mb, cont[i].bodyId);
}
AEq_.resize(cont_.size()*6 , nrDof_ + nrFor_ + nrTor_);
BEq_.resize(cont_.size()*6);
AEq_.setZero();
BEq_.setZero();
}
void ContactAccConstr::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc)
{
using namespace Eigen;
rbd::paramToVector(mbc.alpha, alphaVec_);
// J_i*alphaD + JD_i*alpha = 0
for(std::size_t i = 0; i < cont_.size(); ++i)
{
// AEq = J_i
const MatrixXd& jac = cont_[i].jac.jacobian(mb, mbc);
cont_[i].jac.fullJacobian(mb, jac, fullJac_);
AEq_.block(i*6, 0, 6, mb.nrDof()) = fullJac_;
// BEq = -JD_i*alpha
const MatrixXd& jacDot = cont_[i].jac.jacobianDot(mb, mbc);
cont_[i].jac.fullJacobian(mb, jacDot, fullJac_);
BEq_.segment(i*6, 6) = -fullJac_*alphaVec_;
}
}
int ContactAccConstr::nrEqLine()
{
return AEq_.rows();
}
const Eigen::MatrixXd& ContactAccConstr::AEq() const
{
return AEq_;
}
const Eigen::VectorXd& ContactAccConstr::BEq() const
{
return BEq_;
}
/**
* SelfCollisionConstr
*/
SCD::Matrix4x4 fromSCD(const sva::PTransform& t)
{
SCD::Matrix4x4 m;
const Eigen::Matrix3d& rot = t.rotation();
const Eigen::Vector3d& tran = t.translation();
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
m(i,j) = rot(j,i);
}
}
m(0,3) = tran(0);
m(1,3) = tran(1);
m(2,3) = tran(2);
return m;
}
SelfCollisionConstr::CollData::CollData(const rbd::MultiBody& mb,
int body1Id, SCD::S_Object* body1,
int body2Id, SCD::S_Object* body2,
double di, double ds, double damping):
pair(new SCD::CD_Pair(body1, body2)),
normVecDist(Eigen::Vector3d::Zero()),
jacB1(rbd::Jacobian(mb, body1Id)),
jacB2(rbd::Jacobian(mb, body2Id)),
di(di),
ds(ds),
damping(damping),
body1Id(body1Id),
body2Id(body2Id),
body1(mb.bodyIndexById(body1Id)),
body2(mb.bodyIndexById(body2Id))
{
}
SelfCollisionConstr::CollData::~CollData()
{
delete pair;
}
SelfCollisionConstr::SelfCollisionConstr(const rbd::MultiBody& mb, double step):
dataVec_(),
step_(step),
nrVars_(0),
AInEq_(),
BInEq_(),
fullJac_(6, mb.nrDof()),
fullJacDot_(6, mb.nrDof()),
alphaVec_(mb.nrDof()),
calcVec_(mb.nrDof())
{
}
void SelfCollisionConstr::addCollision(const rbd::MultiBody& mb,
int body1Id, SCD::S_Object* body1,
int body2Id, SCD::S_Object* body2,
double di, double ds, double damping)
{
dataVec_.emplace_back(mb, body1Id, body1, body2Id, body2, di, ds, damping);
}
void SelfCollisionConstr::rmCollision(int body1Id, int body2Id)
{
auto it = std::find_if(dataVec_.begin(), dataVec_.end(),
[body1Id, body2Id](const CollData& data)
{
return data.body1Id == body1Id && data.body2Id == body2Id;
});
if(it != dataVec_.end())
{
dataVec_.erase(it);
}
}
void SelfCollisionConstr::reset()
{
dataVec_.clear();
}
void SelfCollisionConstr::updateNrVars(const rbd::MultiBody& /* mb */,
int alphaD, int lambda, int torque, const std::vector<Contact>& /* cont */)
{
nrVars_ = alphaD + lambda + torque;
}
void SelfCollisionConstr::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc)
{
using namespace Eigen;
if(static_cast<unsigned int>(AInEq_.rows()) != dataVec_.size()
|| AInEq_.cols() != nrVars_)
{
AInEq_.resize(dataVec_.size(), nrVars_);
BInEq_.resize(dataVec_.size());
AInEq_.setZero();
BInEq_.setZero();
}
rbd::paramToVector(mbc.alpha, alphaVec_);
int i = 0;
for(CollData& d: dataVec_)
{
SCD::Point3 pb1Tmp, pb2Tmp;
(*d.pair)[0]->setTransformation(fromSCD(mbc.bodyPosW[d.body1]));
(*d.pair)[1]->setTransformation(fromSCD(mbc.bodyPosW[d.body2]));
double dist = d.pair->getClosestPoints(pb1Tmp, pb2Tmp);
dist = dist >= 0 ? std::sqrt(dist) : -std::sqrt(-dist);
Vector3d pb1(pb1Tmp[0], pb1Tmp[1], pb1Tmp[2]);
Vector3d pb2(pb2Tmp[0], pb2Tmp[1], pb2Tmp[2]);
Eigen::Vector3d normVecDist = (pb1 - pb2)/dist;
pb1 = (mbc.bodyPosW[d.body1].inv()*sva::PTransform(pb1)).translation();
pb2 = (mbc.bodyPosW[d.body2].inv()*sva::PTransform(pb2)).translation();
if(dist < d.di)
{
double dampers = d.damping*((dist - d.ds)/(d.di - d.ds));
Vector3d nf = normVecDist;
Vector3d onf = d.normVecDist;
Vector3d dnf = (nf - onf)/step_;
// Compute body1
d.jacB1.point(pb1);
const MatrixXd& jac1 = d.jacB1.jacobian(mb, mbc);
const MatrixXd& jacDot1 = d.jacB1.jacobianDot(mb, mbc);
d.jacB1.fullJacobian(mb, jac1, fullJac_);
d.jacB1.fullJacobian(mb, jacDot1, fullJacDot_);
double jqdn = ((fullJac_.block(3, 0, 3, fullJac_.cols())*alphaVec_).transpose()*nf)(0);
double jqdnd = ((fullJac_.block(3, 0, 3, fullJac_.cols())*alphaVec_).transpose()*dnf*step_)(0);
double jdqdn = ((fullJacDot_.block(3, 0, 3, fullJac_.cols())*alphaVec_).transpose()*nf*step_)(0);
calcVec_ = -fullJac_.block(3, 0, 3, fullJac_.cols()).transpose()*nf*step_;
// Compute body2
d.jacB2.point(pb2);
const MatrixXd& jac2 = d.jacB2.jacobian(mb, mbc);
const MatrixXd& jacDot2 = d.jacB2.jacobianDot(mb, mbc);
d.jacB2.fullJacobian(mb, jac2, fullJac_);
d.jacB2.fullJacobian(mb, jacDot2, fullJacDot_);
jqdn -= ((fullJac_.block(3, 0, 3, fullJac_.cols())*alphaVec_).transpose()*nf)(0);
jqdnd -= ((fullJac_.block(3, 0, 3, fullJac_.cols())*alphaVec_).transpose()*dnf*step_)(0);
jdqdn -= ((fullJacDot_.block(3, 0, 3, fullJac_.cols())*alphaVec_).transpose()*nf*step_)(0);
calcVec_ += fullJac_.block(3, 0, 3, fullJac_.cols()).transpose()*nf*step_;
// distdot + distdotdot*dt > -damp*((d - ds)/(di - ds))
AInEq_.block(i, 0, 1, mb.nrDof()) = calcVec_.transpose();
BInEq_(i) = dampers + jqdn + jqdnd + jdqdn;
}
else
{
AInEq_.block(i, 0, 1, mb.nrDof()).setZero();
BInEq_(i) = 0.;
}
d.normVecDist = normVecDist;
++i;
}
}
int SelfCollisionConstr::nrInEqLine()
{
return dataVec_.size();
}
const Eigen::MatrixXd& SelfCollisionConstr::AInEq() const
{
return AInEq_;
}
const Eigen::VectorXd& SelfCollisionConstr::BInEq() const
{
return BInEq_;
}
} // namespace qp
} // namespace tasks
<|endoftext|> |
<commit_before>
// Resource.cpp
#include "Resource.h"
int Resource::nextID_ = 0;
// Database table for resources
Table *Resource::resource_table = new Table("Resources");
Table *Resource::resource_type_table = new Table("Resource Types");
Resource::Resource() {
ID_ = nextID_++;
MLOG(LEV_DEBUG4) << "Resource ID=" << ID_ << ", ptr=" << this << " created.";
}
Resource::~Resource() {
MLOG(LEV_DEBUG4) << "Resource ID=" << ID_ << ", ptr=" << this << " deleted.";
}
bool Resource::checkEquality(rsrc_ptr other) {
bool toRet;
(this->checkQuality(other) && this->checkQuantityEqual(other)) ? toRet = true : toRet = false;
return toRet;
}
// -------------------------------------------------------------
/*!
output database related members
*/
// Specific resources
void Resource::define_table(){
// declare the table columns
column id("ID","INTEGER");
column type("Type","INTEGER");
column amt("Quantity","REAL");
column creator("OriginatorID","INTEGER");
// declare the table's primary key
resource_table->setPrimaryKey(id);
// add columns to the table
resource_table->addColumn(id);
resource_table->addColumn(type);
resource_table->addColumn(amt);
resource_table->addColumn(creator);
// we've now defined the table
resource_table->tableDefined();
}
void Resource::addToTable(){
// if we haven't logged the resource type yet, do so
if ( !this->is_resource_type_logged() ){
Resource::logNewType();
this->type_logged();
}
// if we haven't yet, define the table
if ( !resource_table->defined() )
Resource::define_table();
// make a row
// declare data
data an_id( this->ID() ), a_type( (int)this->type() ),
an_amt( this->quantity() ), a_creator( this->originatorID() );
// declare entries
entry id("ID",an_id), type("Type",a_type), amt("Quantity", an_amt), creator("OriginatorID",a_creator);
// declare row
row aRow;
aRow.push_back(id), aRow.push_back(type), aRow.push_back(amt), aRow.push_back(creator);
// add the row
resource_table->addRow(aRow);
// record this primary key
pkref_.push_back(id);
}
// Generic Resource Types
void Resource::define_type_table(){
// declare the table columns
column type("Type","INTEGER");
column type_name("Name","VARCHAR(128)");
column units("Units","VARCHAR(32)");
// declare the table's primary key
resource_type_table->setPrimaryKey(type);
// add columns to the table
resource_type_table->addColumn(type);
resource_type_table->addColumn(type_name);
resource_type_table->addColumn(units);
// we've now defined the table
resource_type_table->tableDefined();
}
void Resource::logNewType(){
// if we haven't yet, define the table
if ( !resource_type_table->defined() )
Resource::define_type_table();
// make a row
// declare data
data a_type( (int)this->type() ), a_name( this->type_name() ), a_unit( this->units() );
// declare entries
entry type("Type",a_type), name("Name", a_name), units("Units", a_unit);
// declare row
row aRow;
aRow.push_back(type), aRow.push_back(name), aRow.push_back(units);
// add the row
resource_type_table->addRow(aRow);
// record this primary key
type_pkref_.push_back(type);
}
<commit_msg>added foreign key to resource table<commit_after>
// Resource.cpp
#include "Resource.h"
int Resource::nextID_ = 0;
// Database table for resources
Table *Resource::resource_table = new Table("Resources");
Table *Resource::resource_type_table = new Table("Resource Types");
Resource::Resource() {
ID_ = nextID_++;
MLOG(LEV_DEBUG4) << "Resource ID=" << ID_ << ", ptr=" << this << " created.";
}
Resource::~Resource() {
MLOG(LEV_DEBUG4) << "Resource ID=" << ID_ << ", ptr=" << this << " deleted.";
}
bool Resource::checkEquality(rsrc_ptr other) {
bool toRet;
(this->checkQuality(other) && this->checkQuantityEqual(other)) ? toRet = true : toRet = false;
return toRet;
}
// -------------------------------------------------------------
/*!
output database related members
*/
// Specific resources
void Resource::define_table(){
// declare the table columns
column id("ID","INTEGER");
column type("Type","INTEGER");
column amt("Quantity","REAL");
column creator("OriginatorID","INTEGER");
// declare the table's primary key
resource_table->setPrimaryKey(id);
// add columns to the table
resource_table->addColumn(id);
resource_table->addColumn(type);
resource_table->addColumn(amt);
resource_table->addColumn(creator);
// add foreign keys
foreign_key_ref *fkref;
foreign_key *fk;
key myk, theirk;
// Resource Types table foreign keys
theirk.push_back("Type");
fkref = new foreign_key_ref("Resource Types",theirk);
// the resource id
myk.push_back("Type");
fk = new foreign_key(myk, (*fkref) );
resource_table->addForeignKey( (*fk) ); // type references Resource Types' type
// we've now defined the table
resource_table->tableDefined();
}
void Resource::addToTable(){
// if we haven't logged the resource type yet, do so
if ( !this->is_resource_type_logged() ){
Resource::logNewType();
this->type_logged();
}
// if we haven't yet, define the table
if ( !resource_table->defined() )
Resource::define_table();
// make a row
// declare data
data an_id( this->ID() ), a_type( (int)this->type() ),
an_amt( this->quantity() ), a_creator( this->originatorID() );
// declare entries
entry id("ID",an_id), type("Type",a_type), amt("Quantity", an_amt), creator("OriginatorID",a_creator);
// declare row
row aRow;
aRow.push_back(id), aRow.push_back(type), aRow.push_back(amt), aRow.push_back(creator);
// add the row
resource_table->addRow(aRow);
// record this primary key
pkref_.push_back(id);
}
// Generic Resource Types
void Resource::define_type_table(){
// declare the table columns
column type("Type","INTEGER");
column type_name("Name","VARCHAR(128)");
column units("Units","VARCHAR(32)");
// declare the table's primary key
resource_type_table->setPrimaryKey(type);
// add columns to the table
resource_type_table->addColumn(type);
resource_type_table->addColumn(type_name);
resource_type_table->addColumn(units);
// we've now defined the table
resource_type_table->tableDefined();
}
void Resource::logNewType(){
// if we haven't yet, define the table
if ( !resource_type_table->defined() )
Resource::define_type_table();
// make a row
// declare data
data a_type( (int)this->type() ), a_name( this->type_name() ), a_unit( this->units() );
// declare entries
entry type("Type",a_type), name("Name", a_name), units("Units", a_unit);
// declare row
row aRow;
aRow.push_back(type), aRow.push_back(name), aRow.push_back(units);
// add the row
resource_type_table->addRow(aRow);
// record this primary key
type_pkref_.push_back(type);
}
<|endoftext|> |
<commit_before>/******************************************************************************
SDLInput.cpp
Input Events Handling
Copyright (c) 2013 Jeffrey Carpenter
******************************************************************************/
#include "SDLInput.h"
SDLInput::SDLInput ( void )
{
#ifdef DEBUG_SDLINPUT_OBJ
std::cout << "SDLInput::SDLInput (): " << "Hello, world!" << std::endl << std::endl;
#endif
if ( SDL_InitSubSystem ( SDL_INIT_JOYSTICK ) == -1 )
{
std::cout << "ERR in SDLInput::SDLInput() at: " << SDL_GetError() << std::endl;
return;
}
// Only initialize this joystick if we have yet to
if ( SDL_JoystickOpened ( 0 ) == 0 )
{
SDL_JoystickEventState ( SDL_ENABLE );
this->joystick = SDL_JoystickOpen ( 0 );
std::cout << SDL_NumJoysticks() << " joysticks were found.";
std::cout << std::endl << std::endl;
if ( SDL_NumJoysticks() > 0 )
{
for( int idx = 0; idx < SDL_NumJoysticks(); idx++ )
{
std::cout << SDL_JoystickName ( idx ) << std::endl << std::endl;
}
}
}
}
SDLInput::~SDLInput ( void )
{
#ifdef DEBUG_SDLINPUT_OBJ
std::cout << "SDLInput::~SDLInput (): " << "Goodbye cruel world!" << std::endl << std::endl;
#endif
// Only close joysticks we have opened
//if ( SDL_JoystickOpened ( 0 ) == 1 )
//{
//SDL_JoystickClose ( this->joystick );
//if ( this->joystick != NULL )
//this->joystick = NULL;
//}
SDL_QuitSubSystem ( SDL_INIT_JOYSTICK );
}
void SDLInput::Input ( void )
{
while ( SDL_PollEvent ( &input ) ) // not sure how viable / wise this is
{
switch ( input.type )
{
case SDL_KEYDOWN:
onKeyDown ( input.key.keysym.sym, input.key.keysym.mod );
break;
case SDL_KEYUP:
onKeyUp ( input.key.keysym.sym, input.key.keysym.mod );
break;
case SDL_MOUSEMOTION:
onMouseMotion ( input.motion.x, input.motion.y );
break;
case SDL_MOUSEBUTTONDOWN:
switch ( input.button.button )
{
case SDL_BUTTON_LEFT:
onMouseLeftButtonDown ( input.button.x, input.button.y );
break;
case SDL_BUTTON_MIDDLE:
onMouseMiddleButtonDown ( input.button.x, input.button.y );
break;
case SDL_BUTTON_RIGHT:
onMouseRightButtonDown ( input.button.x, input.button.y );
break;
case SDL_BUTTON_WHEELDOWN: onMouseWheel ( false, true ); break;
case SDL_BUTTON_WHEELUP: onMouseWheel ( true, false ); break;
}
break;
case SDL_MOUSEBUTTONUP:
switch ( input.button.button )
{
case SDL_BUTTON_LEFT:
onMouseLeftButtonUp ( input.button.x, input.button.y );
break;
case SDL_BUTTON_MIDDLE:
onMouseMiddleButtonUp ( input.button.x, input.button.y );
break;
case SDL_BUTTON_RIGHT:
onMouseRightButtonUp ( input.button.x, input.button.y );
break;
}
break;
case SDL_JOYBUTTONDOWN:
onJoyButtonDown ( input.jbutton.which, input.jbutton.button );
break;
case SDL_JOYBUTTONUP:
onJoyButtonUp ( input.jbutton.which, input.jbutton.button );
break;
case SDL_JOYAXISMOTION:
onJoyAxis ( input.jaxis.which, input.jaxis.axis, input.jaxis.value );
break;
case SDL_QUIT: onExit(); break;
case SDL_VIDEORESIZE: onResize ( input.resize.w, input.resize.h ); break;
} // end switch input->type
}
}
void SDLInput::onExit ( void )
{
// virtual implementation
}
void SDLInput::onResize ( unsigned int width, unsigned int height )
{
// virtual implementation
}
void SDLInput::onRestore ( void )
{
// virtual implementation
}
void SDLInput::onMinimize ( void )
{
// virtual implementation
}
void SDLInput::onInputFocus ( void )
{
// virtual implementation
}
void SDLInput::onMouseFocus ( void )
{
// virtual implementation
}
void SDLInput::onKeyDown ( SDLKey key, SDLMod mod )
{
// virtual implementation
}
void SDLInput::onKeyUp ( SDLKey key, SDLMod mod )
{
// virtual implementation
}
void SDLInput::onMouseMotion ( unsigned int x, unsigned int y )
{
// virtual implementation
}
void SDLInput::onMouseWheel ( bool up, bool down )
{
// virtual implementation
}
void SDLInput::onMouseLeftButtonDown ( unsigned int x, unsigned int y )
{
// virtual implementation
}
void SDLInput::onMouseMiddleButtonDown ( unsigned int x, unsigned int y )
{
// virtual implementation
}
void SDLInput::onMouseRightButtonDown ( unsigned int x, unsigned int y )
{
// virtual implementation
}
void SDLInput::onMouseLeftButtonUp ( unsigned int x, unsigned int y )
{
// virtual implementation
}
void SDLInput::onMouseMiddleButtonUp ( unsigned int x, unsigned int y )
{
// virtual implementation
}
void SDLInput::onMouseRightButtonUp ( unsigned int x, unsigned int y )
{
// virtual implementation
}
void SDLInput::onJoyButtonDown ( unsigned int which, unsigned int button )
{
// virtual implementation
}
void SDLInput::onJoyButtonUp ( unsigned int which, unsigned int button )
{
// virtual implementation
}
void SDLInput::onJoyAxis ( unsigned int which, unsigned int axis, short int value )
{
// virtual implementation
}
<commit_msg>Ever so slight clean up of joystick init/cleanup code fragments<commit_after>/******************************************************************************
SDLInput.cpp
Input Events Handling
Copyright (c) 2013 Jeffrey Carpenter
******************************************************************************/
#include "SDLInput.h"
SDLInput::SDLInput ( void )
{
#ifdef DEBUG_SDLINPUT_OBJ
std::cout << "SDLInput::SDLInput (): " << "Hello, world!" << std::endl << std::endl;
#endif
if ( SDL_InitSubSystem ( SDL_INIT_JOYSTICK ) == -1 )
{
std::cout << "ERR in SDLInput::SDLInput() at: " << SDL_GetError() << std::endl;
return;
}
this->joystick = NULL;
// Only initialize this joystick if we have yet to
if ( SDL_JoystickOpened ( 0 ) == 0 )
{
SDL_JoystickEventState ( SDL_ENABLE );
this->joystick = SDL_JoystickOpen ( 0 );
std::cout << SDL_NumJoysticks() << " joysticks were found.";
std::cout << std::endl << std::endl;
if ( SDL_NumJoysticks() > 0 )
{
for( int idx = 0; idx < SDL_NumJoysticks(); idx++ )
{
std::cout << SDL_JoystickName ( idx ) << std::endl << std::endl;
}
}
}
}
SDLInput::~SDLInput ( void )
{
#ifdef DEBUG_SDLINPUT_OBJ
std::cout << "SDLInput::~SDLInput (): " << "Goodbye cruel world!" << std::endl << std::endl;
#endif
// Only close joysticks we have opened
//if ( SDL_JoystickOpened ( 0 ) == 1 )
//{
//SDL_JoystickClose ( this->joystick );
if ( this->joystick )
this->joystick = NULL;
//}
SDL_QuitSubSystem ( SDL_INIT_JOYSTICK );
}
void SDLInput::Input ( void )
{
while ( SDL_PollEvent ( &input ) ) // not sure how viable / wise this is
{
switch ( input.type )
{
case SDL_KEYDOWN:
onKeyDown ( input.key.keysym.sym, input.key.keysym.mod );
break;
case SDL_KEYUP:
onKeyUp ( input.key.keysym.sym, input.key.keysym.mod );
break;
case SDL_MOUSEMOTION:
onMouseMotion ( input.motion.x, input.motion.y );
break;
case SDL_MOUSEBUTTONDOWN:
switch ( input.button.button )
{
case SDL_BUTTON_LEFT:
onMouseLeftButtonDown ( input.button.x, input.button.y );
break;
case SDL_BUTTON_MIDDLE:
onMouseMiddleButtonDown ( input.button.x, input.button.y );
break;
case SDL_BUTTON_RIGHT:
onMouseRightButtonDown ( input.button.x, input.button.y );
break;
case SDL_BUTTON_WHEELDOWN: onMouseWheel ( false, true ); break;
case SDL_BUTTON_WHEELUP: onMouseWheel ( true, false ); break;
}
break;
case SDL_MOUSEBUTTONUP:
switch ( input.button.button )
{
case SDL_BUTTON_LEFT:
onMouseLeftButtonUp ( input.button.x, input.button.y );
break;
case SDL_BUTTON_MIDDLE:
onMouseMiddleButtonUp ( input.button.x, input.button.y );
break;
case SDL_BUTTON_RIGHT:
onMouseRightButtonUp ( input.button.x, input.button.y );
break;
}
break;
case SDL_JOYBUTTONDOWN:
onJoyButtonDown ( input.jbutton.which, input.jbutton.button );
break;
case SDL_JOYBUTTONUP:
onJoyButtonUp ( input.jbutton.which, input.jbutton.button );
break;
case SDL_JOYAXISMOTION:
onJoyAxis ( input.jaxis.which, input.jaxis.axis, input.jaxis.value );
break;
case SDL_QUIT: onExit(); break;
case SDL_VIDEORESIZE: onResize ( input.resize.w, input.resize.h ); break;
} // end switch input->type
}
}
void SDLInput::onExit ( void )
{
// virtual implementation
}
void SDLInput::onResize ( unsigned int width, unsigned int height )
{
// virtual implementation
}
void SDLInput::onRestore ( void )
{
// virtual implementation
}
void SDLInput::onMinimize ( void )
{
// virtual implementation
}
void SDLInput::onInputFocus ( void )
{
// virtual implementation
}
void SDLInput::onMouseFocus ( void )
{
// virtual implementation
}
void SDLInput::onKeyDown ( SDLKey key, SDLMod mod )
{
// virtual implementation
}
void SDLInput::onKeyUp ( SDLKey key, SDLMod mod )
{
// virtual implementation
}
void SDLInput::onMouseMotion ( unsigned int x, unsigned int y )
{
// virtual implementation
}
void SDLInput::onMouseWheel ( bool up, bool down )
{
// virtual implementation
}
void SDLInput::onMouseLeftButtonDown ( unsigned int x, unsigned int y )
{
// virtual implementation
}
void SDLInput::onMouseMiddleButtonDown ( unsigned int x, unsigned int y )
{
// virtual implementation
}
void SDLInput::onMouseRightButtonDown ( unsigned int x, unsigned int y )
{
// virtual implementation
}
void SDLInput::onMouseLeftButtonUp ( unsigned int x, unsigned int y )
{
// virtual implementation
}
void SDLInput::onMouseMiddleButtonUp ( unsigned int x, unsigned int y )
{
// virtual implementation
}
void SDLInput::onMouseRightButtonUp ( unsigned int x, unsigned int y )
{
// virtual implementation
}
void SDLInput::onJoyButtonDown ( unsigned int which, unsigned int button )
{
// virtual implementation
}
void SDLInput::onJoyButtonUp ( unsigned int which, unsigned int button )
{
// virtual implementation
}
void SDLInput::onJoyAxis ( unsigned int which, unsigned int axis, short int value )
{
// virtual implementation
}
<|endoftext|> |
<commit_before>//************************************************************/
//
// Ratio Implementation
//
// Implements the SPXRatio class, which validates the ratio
// type string, and then grabs the required TGraphs and
// performs the necessary divisions, returning a fully
// configured and ready-to-draw TGraph.
//
// @Author: J. Gibson, C. Embree, T. Carli - CERN ATLAS
// @Date: 25.09.2014
// @Email: gibsjose@mail.gvsu.edu
//
//************************************************************/
#include <iostream>
#include <sstream>
#include "SPXRatio.h"
#include "SPXUtilities.h"
#include "SPXException.h"
//Class name for debug statements
const std::string cn = "SPXRatio::";
//Must define the static debug variable in the implementation
bool SPXRatio::debug;
//Takes a string argument in the following form:
//
// (numerator) / (denominator) <-- MUST have the parenthesis!
//
// Where the options for numerator and denominator are:
//
// [grid_steering_file.txt, pdf_steering_file.txt] <-- Convolute
// data_steering file <-- Data
// grid_steering file <-- Reference
//
// And the numerator/denominator pair options are:
//
// data / convolute
// convolute / data
// data / data
// convolute / reference
//
void SPXRatio::Parse(std::string &s) {
std::string mn = "Parse: ";
std::string numBlob;
std::string denBlob;
if(debug) std::cout << cn << mn << "Parsing ratio string: " << s << std::endl;
//Parse the string into numerator and denominator (delimit with '/')
std::vector<std::string> v = SPXStringUtilities::ParseString(s, '/');
//Make sure vector is EXACTLY 2 strings long
if(v.size() != 2) {
throw SPXParseException(cn + mn + "Ratio string: " + s + " is NOT in the form (numerator) / (denominator)");
}
//Obtain the numerator and denominator blobs from parsed list
numBlob = v.at(0);
denBlob = v.at(1);
if(numBlob.empty()) {
throw SPXParseException(cn + mn + "Numerator blob is empty");
} else {
numeratorBlob = numBlob;
}
if(denBlob.empty()) {
throw SPXParseException(cn + mn + "Denominator blob is empty");
} else {
denominatorBlob = denBlob;
}
if(debug) {
std::cout << cn << mn << "Numerator blob parsed as: " << numeratorBlob << std::endl;
std::cout << cn << mn << "Denominator blob parsed as: " << denominatorBlob << std::endl;
}
if(debug) std::cout << cn << mn << "Ratio style is: " << ratioStyle.ToString() << "(" << ratioStyle.GetStyle() << ")" << std::endl;
//Check the RatioStyle:
if(ratioStyle.IsDataOverConvolute()) {
if(debug) std::cout << cn << mn << "Data over Convolute" << std::endl;
//Error if numBlob matches a convolute string
if(MatchesConvoluteString(numBlob)) {
throw SPXParseException(cn + mn + "Numerator blob should have a \"data\" style, but has \"convolute\" style");
}
//Error if denBlob does NOT match a convolute string
if(!MatchesConvoluteString(denBlob)) {
throw SPXParseException(cn + mn + "Denominator blob should have a \"convolute\" style, but does not");
}
//Get the data steering file from the numerator
numeratorDataFile = SPXStringUtilities::RemoveCharacters(numBlob, "()");
//Get the grid/pdf steering files from the denominator
SPXStringUtilities::RemoveCharacters(denBlob, "()");
SPXStringUtilities::RemoveCharacters(denBlob, "[]");
std::vector<std::string> v_den = SPXStringUtilities::CommaSeparatedListToVector(denBlob);
if(v_den.size() != 2) {
throw SPXParseException(cn + mn + "Denominator blob is NOT of the form \"[grid_file, pdf_file]\"");
}
denominatorConvoluteGridFile = v_den.at(0);
denominatorConvolutePDFFile = v_den.at(1);
if(debug) {
std::cout << cn << mn << "Successfully parsed data / convolute string: " << std::endl;
std::ostringstream oss;
oss << numeratorDataFile << " / " << "[" << denominatorConvoluteGridFile << ", " << denominatorConvolutePDFFile << "]";
ratioString = oss.str();
std::cout << "\t " << ratioString << std::endl;
}
}
else if(ratioStyle.IsConvoluteOverData()) {
if(debug) std::cout << cn << mn << "Convolute over Data" << std::endl;
//Error if numBlob does NOT match a convolute string
if(!MatchesConvoluteString(numBlob)) {
throw SPXParseException(cn + mn + "Numerator blob should have a \"convolute\" style, but does not");
}
//Error if denBlob matches a convolute string
if(MatchesConvoluteString(denBlob)) {
throw SPXParseException(cn + mn + "Denominator blob should have a \"data\" style, but has \"convolute\" style");
}
//Get the grid/pdf steering files from the numerator
SPXStringUtilities::RemoveCharacters(numBlob, "()");
SPXStringUtilities::RemoveCharacters(numBlob, "[]");
std::vector<std::string> v_num = SPXStringUtilities::CommaSeparatedListToVector(numBlob);
if(v_num.size() != 2) {
throw SPXParseException(cn + mn + "Numerator blob is NOT of the form \"[grid_file, pdf_file]\"");
}
numeratorConvoluteGridFile = v_num.at(0);
numeratorConvolutePDFFile = v_num.at(1);
//Get the data steering file from the denominator
denominatorDataFile = SPXStringUtilities::RemoveCharacters(denBlob, "()");
if(debug) {
std::cout << cn << mn << "Successfully parsed convolute / data string: " << std::endl;
std::ostringstream oss;
oss << "[" << numeratorConvoluteGridFile << ", " << numeratorConvolutePDFFile << "]" << " / " << denominatorDataFile;
ratioString = oss.str();
std::cout << "\t " << ratioString << std::endl;
}
}
else if(ratioStyle.IsConvoluteOverReference()) {
if(debug) std::cout << cn << mn << "Convolute over reference" << std::endl;
//Error if numBlob does NOT match a convolute string
if(!MatchesConvoluteString(numBlob)) {
throw SPXParseException(cn + mn + "Numerator blob should have a \"convolute\" style, but does not");
}
//Error if denBlob matches a convolute string
if(MatchesConvoluteString(denBlob)) {
throw SPXParseException(cn + mn + "Denominator blob should have a \"reference\" style, but has \"convolute\" style");
}
//Get the grid/pdf steering files from the numerator
SPXStringUtilities::RemoveCharacters(numBlob, "()");
SPXStringUtilities::RemoveCharacters(numBlob, "[]");
std::vector<std::string> v_num = SPXStringUtilities::CommaSeparatedListToVector(numBlob);
if(v_num.size() != 2) {
throw SPXParseException(cn + mn + "Numerator blob is NOT of the form \"[grid_file, pdf_file]\"");
}
numeratorConvoluteGridFile = v_num.at(0);
numeratorConvolutePDFFile = v_num.at(1);
//Get the reference grid steering file from the denominator
denominatorReferenceGridFile = SPXStringUtilities::RemoveCharacters(denBlob, "()");
//Error if reference grid steering file does NOT match the convolute grid file
if(numeratorConvoluteGridFile.compare(denominatorReferenceGridFile) != 0) {
throw SPXParseException(cn + mn + "Numerator's convolute grid file \"" + numeratorConvoluteGridFile + \
"\" MUST match the denominator's refererence grid file: \"" + denominatorReferenceGridFile + "\"");
}
if(debug) {
std::cout << cn << mn << "Successfully parsed convolute / reference string: " << std::endl;
std::ostringstream oss;
oss << "[" << numeratorConvoluteGridFile << ", " << numeratorConvolutePDFFile << "]" << " / " << denominatorReferenceGridFile;
ratioString = oss.str();
std::cout << "\t " << ratioString << std::endl;
}
}
else if(ratioStyle.IsDataOverData()) {
if(debug) std::cout << cn << mn << "Data Over Data" << std::endl;
//Error if numerator or denominator matches convolute string
if(MatchesConvoluteString(numBlob) || MatchesConvoluteString(denBlob)) {
throw SPXParseException(cn + mn + "Numerator AND denominator blob should have a \"data\" style, but at least one has \"convolute\" style");
}
//Get the data file from the numerator
numeratorDataFile = SPXStringUtilities::RemoveCharacters(numBlob, "()");
//Get the data file from the denominator
denominatorDataFile = SPXStringUtilities::RemoveCharacters(denBlob, "()");
if(debug) {
std::cout << cn << mn << "Successfully parsed data / data string: " << std::endl;
std::ostringstream oss;
oss << numeratorDataFile << " / " << denominatorDataFile;
ratioString = oss.str();
std::cout << "\t " << ratioString << std::endl;
}
}
//Get the graphs based on the steering files given
GetGraphs();
}
void SPXRatio::GetGraphs(void) {
return;
}
bool SPXRatio::MatchesConvoluteString(std::string &s) {
std::string mn = "MatchesConvoluteString: ";
SPXStringUtilities::RemoveCharacters(s, "()");
if(debug) std::cout << cn << mn << "Checking \"" << s << "\" against convolute pattern" << std::endl;
//Convolute strings MUST begin with '[', end with ']', and have a ',' somewhere in the middle
if((s.at(0) == '[') && (s.at(s.size() - 1) == ']') && (s.find(",") != std::string::npos)) {
if(debug) std::cout << cn << mn << s << " matches convolute pattern" << std::endl;
return true;
} else {
if(debug) std::cout << cn << mn << s << " does NOT match convolute pattern" << std::endl;
return false;
}
}
<commit_msg>Working on SPXRatio<commit_after>//************************************************************/
//
// Ratio Implementation
//
// Implements the SPXRatio class, which validates the ratio
// type string, and then grabs the required TGraphs and
// performs the necessary divisions, returning a fully
// configured and ready-to-draw TGraph.
//
// @Author: J. Gibson, C. Embree, T. Carli - CERN ATLAS
// @Date: 25.09.2014
// @Email: gibsjose@mail.gvsu.edu
//
//************************************************************/
#include <iostream>
#include <sstream>
#include "SPXRatio.h"
#include "SPXUtilities.h"
#include "SPXException.h"
//Class name for debug statements
const std::string cn = "SPXRatio::";
//Must define the static debug variable in the implementation
bool SPXRatio::debug;
//Takes a string argument in the following form:
//
// (numerator) / (denominator) <-- MUST have the parenthesis!
//
// Where the options for numerator and denominator are:
//
// [grid_steering_file.txt, pdf_steering_file.txt] <-- Convolute
// data_steering file <-- Data
// grid_steering file <-- Reference
//
// And the numerator/denominator pair options are:
//
// data / convolute
// convolute / data
// data / data
// convolute / reference
//
void SPXRatio::Parse(std::string &s) {
std::string mn = "Parse: ";
std::string numBlob;
std::string denBlob;
if(debug) std::cout << cn << mn << "Parsing ratio string: " << s << std::endl;
//Parse the string into numerator and denominator (delimit with '/')
std::vector<std::string> v = SPXStringUtilities::ParseString(s, '/');
//Make sure vector is EXACTLY 2 strings long
if(v.size() != 2) {
throw SPXParseException(cn + mn + "Ratio string: " + s + " is NOT in the form (numerator) / (denominator)");
}
//Obtain the numerator and denominator blobs from parsed list
numBlob = v.at(0);
denBlob = v.at(1);
if(numBlob.empty()) {
throw SPXParseException(cn + mn + "Numerator blob is empty");
} else {
numeratorBlob = numBlob;
}
if(denBlob.empty()) {
throw SPXParseException(cn + mn + "Denominator blob is empty");
} else {
denominatorBlob = denBlob;
}
if(debug) {
std::cout << cn << mn << "Numerator blob parsed as: " << numeratorBlob << std::endl;
std::cout << cn << mn << "Denominator blob parsed as: " << denominatorBlob << std::endl;
}
if(debug) std::cout << cn << mn << "Ratio style is: " << ratioStyle.ToString() << "(" << ratioStyle.GetNumerator() \
<< " / " << ratioStyle.GetDenominator() << ")" << std::endl;
//Check the RatioStyle:
if(ratioStyle.IsDataOverConvolute()) {
if(debug) std::cout << cn << mn << "Data over Convolute" << std::endl;
//Error if numBlob matches a convolute string
if(MatchesConvoluteString(numBlob)) {
throw SPXParseException(cn + mn + "Numerator blob should have a \"data\" style, but has \"convolute\" style");
}
//Error if denBlob does NOT match a convolute string
if(!MatchesConvoluteString(denBlob)) {
throw SPXParseException(cn + mn + "Denominator blob should have a \"convolute\" style, but does not");
}
//Get the data steering file from the numerator
numeratorDataFile = SPXStringUtilities::RemoveCharacters(numBlob, "()");
//Get the grid/pdf steering files from the denominator
SPXStringUtilities::RemoveCharacters(denBlob, "()");
SPXStringUtilities::RemoveCharacters(denBlob, "[]");
std::vector<std::string> v_den = SPXStringUtilities::CommaSeparatedListToVector(denBlob);
if(v_den.size() != 2) {
throw SPXParseException(cn + mn + "Denominator blob is NOT of the form \"[grid_file, pdf_file]\"");
}
denominatorConvoluteGridFile = v_den.at(0);
denominatorConvolutePDFFile = v_den.at(1);
if(debug) {
std::cout << cn << mn << "Successfully parsed data / convolute string: " << std::endl;
std::ostringstream oss;
oss << numeratorDataFile << " / " << "[" << denominatorConvoluteGridFile << ", " << denominatorConvolutePDFFile << "]";
ratioString = oss.str();
std::cout << "\t " << ratioString << std::endl;
}
}
else if(ratioStyle.IsConvoluteOverData()) {
if(debug) std::cout << cn << mn << "Convolute over Data" << std::endl;
//Error if numBlob does NOT match a convolute string
if(!MatchesConvoluteString(numBlob)) {
throw SPXParseException(cn + mn + "Numerator blob should have a \"convolute\" style, but does not");
}
//Error if denBlob matches a convolute string
if(MatchesConvoluteString(denBlob)) {
throw SPXParseException(cn + mn + "Denominator blob should have a \"data\" style, but has \"convolute\" style");
}
//Get the grid/pdf steering files from the numerator
SPXStringUtilities::RemoveCharacters(numBlob, "()");
SPXStringUtilities::RemoveCharacters(numBlob, "[]");
std::vector<std::string> v_num = SPXStringUtilities::CommaSeparatedListToVector(numBlob);
if(v_num.size() != 2) {
throw SPXParseException(cn + mn + "Numerator blob is NOT of the form \"[grid_file, pdf_file]\"");
}
numeratorConvoluteGridFile = v_num.at(0);
numeratorConvolutePDFFile = v_num.at(1);
//Get the data steering file from the denominator
denominatorDataFile = SPXStringUtilities::RemoveCharacters(denBlob, "()");
if(debug) {
std::cout << cn << mn << "Successfully parsed convolute / data string: " << std::endl;
std::ostringstream oss;
oss << "[" << numeratorConvoluteGridFile << ", " << numeratorConvolutePDFFile << "]" << " / " << denominatorDataFile;
ratioString = oss.str();
std::cout << "\t " << ratioString << std::endl;
}
}
else if(ratioStyle.IsConvoluteOverReference()) {
if(debug) std::cout << cn << mn << "Convolute over reference" << std::endl;
//Error if numBlob does NOT match a convolute string
if(!MatchesConvoluteString(numBlob)) {
throw SPXParseException(cn + mn + "Numerator blob should have a \"convolute\" style, but does not");
}
//Error if denBlob matches a convolute string
if(MatchesConvoluteString(denBlob)) {
throw SPXParseException(cn + mn + "Denominator blob should have a \"reference\" style, but has \"convolute\" style");
}
//Get the grid/pdf steering files from the numerator
SPXStringUtilities::RemoveCharacters(numBlob, "()");
SPXStringUtilities::RemoveCharacters(numBlob, "[]");
std::vector<std::string> v_num = SPXStringUtilities::CommaSeparatedListToVector(numBlob);
if(v_num.size() != 2) {
throw SPXParseException(cn + mn + "Numerator blob is NOT of the form \"[grid_file, pdf_file]\"");
}
numeratorConvoluteGridFile = v_num.at(0);
numeratorConvolutePDFFile = v_num.at(1);
//Get the reference grid steering file from the denominator
denominatorReferenceGridFile = SPXStringUtilities::RemoveCharacters(denBlob, "()");
//Error if reference grid steering file does NOT match the convolute grid file
if(numeratorConvoluteGridFile.compare(denominatorReferenceGridFile) != 0) {
throw SPXParseException(cn + mn + "Numerator's convolute grid file \"" + numeratorConvoluteGridFile + \
"\" MUST match the denominator's refererence grid file: \"" + denominatorReferenceGridFile + "\"");
}
if(debug) {
std::cout << cn << mn << "Successfully parsed convolute / reference string: " << std::endl;
std::ostringstream oss;
oss << "[" << numeratorConvoluteGridFile << ", " << numeratorConvolutePDFFile << "]" << " / " << denominatorReferenceGridFile;
ratioString = oss.str();
std::cout << "\t " << ratioString << std::endl;
}
}
else if(ratioStyle.IsDataOverData()) {
if(debug) std::cout << cn << mn << "Data Over Data" << std::endl;
//Error if numerator or denominator matches convolute string
if(MatchesConvoluteString(numBlob) || MatchesConvoluteString(denBlob)) {
throw SPXParseException(cn + mn + "Numerator AND denominator blob should have a \"data\" style, but at least one has \"convolute\" style");
}
//Get the data file from the numerator
numeratorDataFile = SPXStringUtilities::RemoveCharacters(numBlob, "()");
//Get the data file from the denominator
denominatorDataFile = SPXStringUtilities::RemoveCharacters(denBlob, "()");
if(debug) {
std::cout << cn << mn << "Successfully parsed data / data string: " << std::endl;
std::ostringstream oss;
oss << numeratorDataFile << " / " << denominatorDataFile;
ratioString = oss.str();
std::cout << "\t " << ratioString << std::endl;
}
}
//Get the graphs based on the steering files given
GetGraphs();
}
void SPXRatio::GetGraphs(void) {
return;
}
bool SPXRatio::MatchesConvoluteString(std::string &s) {
std::string mn = "MatchesConvoluteString: ";
SPXStringUtilities::RemoveCharacters(s, "()");
if(debug) std::cout << cn << mn << "Checking \"" << s << "\" against convolute pattern" << std::endl;
//Convolute strings MUST begin with '[', end with ']', and have a ',' somewhere in the middle
if((s.at(0) == '[') && (s.at(s.size() - 1) == ']') && (s.find(",") != std::string::npos)) {
if(debug) std::cout << cn << mn << s << " matches convolute pattern" << std::endl;
return true;
} else {
if(debug) std::cout << cn << mn << s << " does NOT match convolute pattern" << std::endl;
return false;
}
}
<|endoftext|> |
<commit_before>//
// Settings.cpp
// RunParticles
//
// Created by Doug Letterman on 11/1/14.
//
//
#include "Settings.h"
#include <fnmatch.h>
TrackStyleRule::TrackStyleRule() :
pattern("*"),
color(QColor(255,0,0)),
width(1.0)
{
}
QVariant
TrackStyleRule::toVariant() const
{
QList<QVariant> var;
var.append(QVariant(pattern));
var.append(QVariant(color.rgba()));
var.append(QVariant(width));
return var;
}
TrackStyleRule
TrackStyleRule::fromVariant(const QVariant &var)
{
TrackStyleRule pref;
QList<QVariant> parts = var.toList();
int size = parts.size();
if (size >= 1) {
pref.pattern = parts[0].toString();
if (size >= 2) {
pref.color = QColor::fromRgba(parts[1].toUInt());
if (size >= 3)
pref.width = parts[2].toUInt();
}
}
return pref;
}
QVariant
TrackStyleRules::toVariant() const
{
QList<QVariant> vars;
TrackStyleRule myPref;
foreach(myPref, prefs) {
vars.append(myPref.toVariant());
}
return QVariant(vars);
}
TrackStyleRule
TrackStyleRules::getStyleForTrackType(const QString &type) const
{
TrackStyleRule myPref;
const char* theType = type.toStdString().c_str();
foreach(myPref, prefs) {
const char* myPattern = myPref.pattern.toStdString().c_str();
if (fnmatch(myPattern, theType, FNM_PATHNAME) == 0) {
return myPref;
}
}
return TrackStyleRule();
}
TrackStyleRules
TrackStyleRules::fromVariant(const QVariant &var)
{
TrackStyleRules myPrefs;
QList<QVariant> vars = var.toList();
QVariant myVar;
foreach(myVar, vars)
{
myPrefs.prefs.append(TrackStyleRule::fromVariant(myVar));
}
return myPrefs;
}
TrackStyleRules
TrackStyleRules::getDefaultRules()
{
TrackStyleRules myPrefs;
TrackStyleRule runPref, bikePref, cyclingPref, otherPrefs;
runPref.pattern = QString("Running");
runPref.color = QColor(255, 0, 0);
bikePref.pattern = QString("Biking");
bikePref.color = QColor(0, 0, 255);
cyclingPref.pattern = QString("Cycling");
cyclingPref.color = QColor(0, 0, 255);
otherPrefs.pattern = QString("*");
otherPrefs.color = QColor(0, 255, 0);
myPrefs.prefs << runPref << bikePref << cyclingPref << otherPrefs;
return myPrefs;
}
Settings::Settings(QObject *parent) :
QObject(parent),
_settings(new QSettings(this))
{
}
void
Settings::clear()
{
_settings->clear();
}
bool
Settings::restoreWidgetState(QWidget *widget)
{
_settings->beginGroup(QString("widgetGeometry/%0").arg(widget->objectName()));
bool hasState;
if ((hasState = _settings->contains("size")))
widget->resize(_settings->value("size").toSize());
if (_settings->contains("pos"))
widget->move(_settings->value("pos").toPoint());
_settings->endGroup();
return hasState;
}
void
Settings::saveWidgetState(const QWidget *widget)
{
_settings->beginGroup(QString("widgetGeometry/%0").arg(widget->objectName()));
_settings->setValue("size", widget->size());
_settings->setValue("pos", widget->pos());
_settings->endGroup();
}
QStringList
Settings::getRecentMapFiles()
{
return _getList("recentMapFiles");
}
void
Settings::setRecentMapFiles(const QList<QString> &files)
{
_setList("recentMapFiles", files);
}
QStringList
Settings::getRecentLayerFiles()
{
return _getList("recentLayerFiles");
}
void
Settings::setRecentLayerFiles(const QList<QString> &files)
{
_setList("recentLayerFiles", files);
}
TrackStyleRules
Settings::getTrackStyleRules()
{
if (_settings->contains("trackStyleRules"))
return TrackStyleRules::fromVariant(_settings->value("trackStyleRules"));
return TrackStyleRules::getDefaultRules();
}
void
Settings::setTrackStyleRules(const TrackStyleRules &rules)
{
_settings->setValue("trackStyleRules", rules.toVariant());
}
LonLatBox
Settings::getStartingViewArea()
{
if (_settings->contains("startingViewArea")) {
QVariantList vars = _settings->value("startingViewArea").toList();
if (vars.length() == 4) {
double bounds[4];
bool ok = true;
for (int i=0; i<4 && ok; i++) {
bounds[i] = vars[i].toDouble(&ok);
}
if (ok)
return LonLatBox(bounds[0], bounds[1], bounds[2], bounds[3]);
}
}
// Default is centered over Oakland
return LonLatBox(-122.37, 37.93, -122.27, 37.73);
}
void
Settings::setStartingViewArea(const LonLatBox &viewArea)
{
QVariantList bounds;
bounds << QVariant(viewArea.upperLeft.x)
<< QVariant(viewArea.upperLeft.y)
<< QVariant(viewArea.lowerRight.x)
<< QVariant(viewArea.lowerRight.y);
_settings->setValue("startingViewArea", bounds);
}
bool
Settings::getShowOpenStreetMap()
{
return _settings->value("showOpenStreetMap", QVariant(true)).toBool();
}
void
Settings::setShowOpenStreetMap(bool show)
{
_settings->setValue("showOpenStreetMap", show);
}
bool
Settings::getFrameLastAddedLayer()
{
return _settings->value("frameLastAddedLayer", QVariant(true)).toBool();
}
void
Settings::setFrameLastAddedLayer(bool frame)
{
_settings->setValue("frameLastAddedLayer", frame);
}
QStringList
Settings::_getList(const QString &key)
{
QList<QString> files;
QList<QVariant> strVars = _settings->value(key).toList();
QVariant myvar;
foreach(myvar, strVars) {
files.append(myvar.toString());
}
return files;
}
void
Settings::_setList(const QString &key, const QList<QString> &files)
{
QList<QVariant> varList;
QString myFile;
foreach(myFile, files) {
varList.append(QVariant(myFile));
}
_settings->setValue(key, QVariant(varList));
}
<commit_msg>Added a y offset to saveWidgetState to work around an apparent Qt bug.<commit_after>//
// Settings.cpp
// RunParticles
//
// Created by Doug Letterman on 11/1/14.
//
//
#include "Settings.h"
#include <QApplication>
#include <QDesktopWidget>
#include <fnmatch.h>
TrackStyleRule::TrackStyleRule() :
pattern("*"),
color(QColor(255,0,0)),
width(1.0)
{
}
QVariant
TrackStyleRule::toVariant() const
{
QList<QVariant> var;
var.append(QVariant(pattern));
var.append(QVariant(color.rgba()));
var.append(QVariant(width));
return var;
}
TrackStyleRule
TrackStyleRule::fromVariant(const QVariant &var)
{
TrackStyleRule pref;
QList<QVariant> parts = var.toList();
int size = parts.size();
if (size >= 1) {
pref.pattern = parts[0].toString();
if (size >= 2) {
pref.color = QColor::fromRgba(parts[1].toUInt());
if (size >= 3)
pref.width = parts[2].toUInt();
}
}
return pref;
}
QVariant
TrackStyleRules::toVariant() const
{
QList<QVariant> vars;
TrackStyleRule myPref;
foreach(myPref, prefs) {
vars.append(myPref.toVariant());
}
return QVariant(vars);
}
TrackStyleRule
TrackStyleRules::getStyleForTrackType(const QString &type) const
{
TrackStyleRule myPref;
const char* theType = type.toStdString().c_str();
foreach(myPref, prefs) {
const char* myPattern = myPref.pattern.toStdString().c_str();
if (fnmatch(myPattern, theType, FNM_PATHNAME) == 0) {
return myPref;
}
}
return TrackStyleRule();
}
TrackStyleRules
TrackStyleRules::fromVariant(const QVariant &var)
{
TrackStyleRules myPrefs;
QList<QVariant> vars = var.toList();
QVariant myVar;
foreach(myVar, vars)
{
myPrefs.prefs.append(TrackStyleRule::fromVariant(myVar));
}
return myPrefs;
}
TrackStyleRules
TrackStyleRules::getDefaultRules()
{
TrackStyleRules myPrefs;
TrackStyleRule runPref, bikePref, cyclingPref, otherPrefs;
runPref.pattern = QString("Running");
runPref.color = QColor(255, 0, 0);
bikePref.pattern = QString("Biking");
bikePref.color = QColor(0, 0, 255);
cyclingPref.pattern = QString("Cycling");
cyclingPref.color = QColor(0, 0, 255);
otherPrefs.pattern = QString("*");
otherPrefs.color = QColor(0, 255, 0);
myPrefs.prefs << runPref << bikePref << cyclingPref << otherPrefs;
return myPrefs;
}
Settings::Settings(QObject *parent) :
QObject(parent),
_settings(new QSettings(this))
{
}
void
Settings::clear()
{
_settings->clear();
}
bool
Settings::restoreWidgetState(QWidget *widget)
{
_settings->beginGroup(QString("widgetGeometry/%0").arg(widget->objectName()));
bool hasState;
if ((hasState = _settings->contains("size")))
widget->resize(_settings->value("size").toSize());
if (_settings->contains("pos"))
widget->move(_settings->value("pos").toPoint());
_settings->endGroup();
return hasState;
}
void
Settings::saveWidgetState(const QWidget *widget)
{
/* There is a Qt bug where pos() does not properly account for the size
of the application's menu bar, so calling move() on the result of pos()
causes QWidgets to creep slowly down the screen after each restore.
*/
QDesktopWidget *desktop = QApplication::desktop();
int yOffset = desktop->screenGeometry().height() -
desktop->availableGeometry().height() - 4;
_settings->beginGroup(QString("widgetGeometry/%0").arg(widget->objectName()));
QPoint pos = widget->pos();
pos.setY(pos.y() - yOffset);
_settings->setValue("size", widget->size());
_settings->setValue("pos", pos);
_settings->endGroup();
}
QStringList
Settings::getRecentMapFiles()
{
return _getList("recentMapFiles");
}
void
Settings::setRecentMapFiles(const QList<QString> &files)
{
_setList("recentMapFiles", files);
}
QStringList
Settings::getRecentLayerFiles()
{
return _getList("recentLayerFiles");
}
void
Settings::setRecentLayerFiles(const QList<QString> &files)
{
_setList("recentLayerFiles", files);
}
TrackStyleRules
Settings::getTrackStyleRules()
{
if (_settings->contains("trackStyleRules"))
return TrackStyleRules::fromVariant(_settings->value("trackStyleRules"));
return TrackStyleRules::getDefaultRules();
}
void
Settings::setTrackStyleRules(const TrackStyleRules &rules)
{
_settings->setValue("trackStyleRules", rules.toVariant());
}
LonLatBox
Settings::getStartingViewArea()
{
if (_settings->contains("startingViewArea")) {
QVariantList vars = _settings->value("startingViewArea").toList();
if (vars.length() == 4) {
double bounds[4];
bool ok = true;
for (int i=0; i<4 && ok; i++) {
bounds[i] = vars[i].toDouble(&ok);
}
if (ok)
return LonLatBox(bounds[0], bounds[1], bounds[2], bounds[3]);
}
}
// Default is centered over Oakland
return LonLatBox(-122.37, 37.93, -122.27, 37.73);
}
void
Settings::setStartingViewArea(const LonLatBox &viewArea)
{
QVariantList bounds;
bounds << QVariant(viewArea.upperLeft.x)
<< QVariant(viewArea.upperLeft.y)
<< QVariant(viewArea.lowerRight.x)
<< QVariant(viewArea.lowerRight.y);
_settings->setValue("startingViewArea", bounds);
}
bool
Settings::getShowOpenStreetMap()
{
return _settings->value("showOpenStreetMap", QVariant(true)).toBool();
}
void
Settings::setShowOpenStreetMap(bool show)
{
_settings->setValue("showOpenStreetMap", show);
}
bool
Settings::getFrameLastAddedLayer()
{
return _settings->value("frameLastAddedLayer", QVariant(true)).toBool();
}
void
Settings::setFrameLastAddedLayer(bool frame)
{
_settings->setValue("frameLastAddedLayer", frame);
}
QStringList
Settings::_getList(const QString &key)
{
QList<QString> files;
QList<QVariant> strVars = _settings->value(key).toList();
QVariant myvar;
foreach(myvar, strVars) {
files.append(myvar.toString());
}
return files;
}
void
Settings::_setList(const QString &key, const QList<QString> &files)
{
QList<QVariant> varList;
QString myFile;
foreach(myFile, files) {
varList.append(QVariant(myFile));
}
_settings->setValue(key, QVariant(varList));
}
<|endoftext|> |
<commit_before>#ifndef STLTOOLS_H
#define STLTOOLS_H
#include <utility>
#include <vector>
#include <algorithm>
namespace RAILS
{
static bool eigenvalue_sorter(std::pair<int, double> const &a, std::pair<int, double> const &b)
{
return std::abs(a.second) > std::abs(b.second);
}
template<class DenseMatrix>
int find_largest_eigenvalues(DenseMatrix const &eigenvalues, std::vector<int> &indices, int N)
{
std::vector<std::pair<int, double> > index_to_value;
for (int i = 0; i < eigenvalues.M(); i++)
index_to_value.push_back(std::pair<int, double>(i, eigenvalues(i)));
std::sort(index_to_value.begin(), index_to_value.end(), eigenvalue_sorter);
for (int i = 0; i < N; i++)
indices.push_back(index_to_value[i].first);
return 0;
}
}
#endif
<commit_msg>Fix ambiguous function error due to missing include.<commit_after>#ifndef STLTOOLS_H
#define STLTOOLS_H
#include <cmath>
#include <utility>
#include <vector>
#include <algorithm>
namespace RAILS
{
static bool eigenvalue_sorter(std::pair<int, double> const &a, std::pair<int, double> const &b)
{
return std::abs(a.second) > std::abs(b.second);
}
template<class DenseMatrix>
int find_largest_eigenvalues(DenseMatrix const &eigenvalues, std::vector<int> &indices, int N)
{
std::vector<std::pair<int, double> > index_to_value;
for (int i = 0; i < eigenvalues.M(); i++)
index_to_value.push_back(std::pair<int, double>(i, eigenvalues(i)));
std::sort(index_to_value.begin(), index_to_value.end(), eigenvalue_sorter);
for (int i = 0; i < N; i++)
indices.push_back(index_to_value[i].first);
return 0;
}
}
#endif
<|endoftext|> |
<commit_before>#include "BinEP.h"
#include "check_params.h"
#include <epbin.h>
#include <drag2d.h>
namespace edb
{
std::string BinEP::Command() const
{
return "epbin";
}
std::string BinEP::Description() const
{
return "pack ejoy2d's .lua and images to binary";
}
std::string BinEP::Usage() const
{
return Command() + " [filename] [type] [output]";
}
void BinEP::Run(int argc, char *argv[])
{
// epbin E:\debug\sg_ui\ui2 png E:\debug\sg_ui\ui2.epp
if (!check_number(this, argc, 5)) return;
Trigger(argv[2], argv[3], argv[4]);
}
void BinEP::Trigger(const std::string& filename, const std::string& type,
const std::string& output)
{
epbin::TextureType t;
if (type == "png4") {
t = epbin::TT_PNG4;
} else if (type == "png8") {
t = epbin::TT_PNG8;
} else if (type == "pvr") {
t = epbin::TT_PVR;
} else if (type == "pkm") {
t = epbin::TT_PKM;
} else {
throw d2d::Exception("BinEP::Trigger unknown type: %s\n", type);
}
epbin::BinaryEPP epp(filename, t);
epp.Pack(output);
}
}<commit_msg>[FIXED] bin ep<commit_after>#include "BinEP.h"
#include "check_params.h"
#include <epbin.h>
#include <drag2d.h>
namespace edb
{
std::string BinEP::Command() const
{
return "epbin";
}
std::string BinEP::Description() const
{
return "pack ejoy2d's .lua and images to binary";
}
std::string BinEP::Usage() const
{
return Command() + " [filename] [type] [output]";
}
void BinEP::Run(int argc, char *argv[])
{
// epbin E:\debug\sg_ui\ui2 png E:\debug\sg_ui\ui2
if (!check_number(this, argc, 5)) return;
Trigger(argv[2], argv[3], argv[4]);
}
void BinEP::Trigger(const std::string& filename, const std::string& type,
const std::string& output)
{
epbin::BinaryEPD epd(filename + ".lua");
epd.Pack(output + ".epd", true);
epbin::TextureType t;
if (type == "png4") {
t = epbin::TT_PNG4;
} else if (type == "png8") {
t = epbin::TT_PNG8;
} else if (type == "pvr") {
t = epbin::TT_PVR;
} else if (type == "pkm") {
t = epbin::TT_PKM;
} else {
throw d2d::Exception("BinEP::Trigger unknown type: %s\n", type);
}
epbin::BinaryEPP epp(filename, t);
epp.Pack(output + ".epp");
}
}<|endoftext|> |
<commit_before>// WinClient.cc for Fluxbox - an X11 Window manager
// Copyright (c) 2003 Henrik Kinnunen (fluxgen(at)users.sourceforge.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// $Id: WinClient.cc,v 1.2 2003/04/14 12:08:21 fluxgen Exp $
#include "WinClient.hh"
#include "Window.hh"
#include "fluxbox.hh"
#include "Screen.hh"
#include "i18n.hh"
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
WinClient::WinClient(Window win, FluxboxWindow &fbwin):FbTk::FbWindow(win),
transient_for(0),
window_group(0),
x(0), y(0), old_bw(0),
min_width(1), min_height(1),
max_width(1), max_height(1),
width_inc(1), height_inc(1),
min_aspect_x(1), min_aspect_y(1),
max_aspect_x(1), max_aspect_y(1),
base_width(1), base_height(1),
win_gravity(0),
initial_state(0),
normal_hint_flags(0),
wm_hint_flags(0),
mwm_hint(0),
blackbox_hint(0),
m_win(&fbwin),
m_title(""), m_icon_title(""),
m_diesig(*this) { }
WinClient::~WinClient() {
#ifdef DEBUG
cerr<<__FILE__<<"(~"<<__FUNCTION__<<")[this="<<this<<"]"<<endl;
#endif // DEBUG
m_diesig.notify();
Fluxbox *fluxbox = Fluxbox::instance();
if (transient_for != 0) {
if (transientFor() == m_win) {
transient_for = 0;
}
fluxbox->setFocusedWindow(transient_for);
if (transient_for != 0) {
FluxboxWindow::ClientList::iterator client_it =
transientFor()->clientList().begin();
FluxboxWindow::ClientList::iterator client_it_end =
transientFor()->clientList().end();
for (; client_it != client_it_end; ++client_it) {
(*client_it)->transientList().remove(m_win);
}
transient_for->setInputFocus();
transient_for = 0;
}
}
while (!transients.empty()) {
FluxboxWindow::ClientList::iterator it =
transients.back()->clientList().begin();
FluxboxWindow::ClientList::iterator it_end =
transients.back()->clientList().end();
for (; it != it_end; ++it) {
if ((*it)->transientFor() == m_win)
(*it)->transient_for = 0;
}
transients.pop_back();
}
if (window_group != 0) {
fluxbox->removeGroupSearch(window_group);
window_group = 0;
}
if (mwm_hint != 0)
XFree(mwm_hint);
if (blackbox_hint != 0)
XFree(blackbox_hint);
if (window())
fluxbox->removeWindowSearch(window());
if (m_win != 0)
m_win->removeClient(*this);
m_win = 0;
}
void WinClient::updateRect(int x, int y,
unsigned int width, unsigned int height) {
Display *disp = FbTk::App::instance()->display();
XEvent event;
event.type = ConfigureNotify;
event.xconfigure.display = disp;
event.xconfigure.event = window();
event.xconfigure.window = window();
event.xconfigure.x = x;
event.xconfigure.y = y;
event.xconfigure.width = width;
event.xconfigure.height = height;
//!! TODO
event.xconfigure.border_width = 1;//client.old_bw;
//!! TODO
event.xconfigure.above = None; //m_frame.window().window();
event.xconfigure.override_redirect = false;
XSendEvent(disp, window(), False, StructureNotifyMask, &event);
}
void WinClient::sendFocus() {
Display *disp = FbTk::App::instance()->display();
// setup focus msg
XEvent ce;
ce.xclient.type = ClientMessage;
ce.xclient.message_type = FbAtoms::instance()->getWMProtocolsAtom();
ce.xclient.display = disp;
ce.xclient.window = window();
ce.xclient.format = 32;
ce.xclient.data.l[0] = FbAtoms::instance()->getWMTakeFocusAtom();
ce.xclient.data.l[1] = Fluxbox::instance()->getLastTime();
ce.xclient.data.l[2] = 0l;
ce.xclient.data.l[3] = 0l;
ce.xclient.data.l[4] = 0l;
// send focus msg
XSendEvent(disp, window(), false, NoEventMask, &ce);
}
void WinClient::sendClose() {
Display *disp = FbTk::App::instance()->display();
// fill in XClientMessage structure for delete message
XEvent ce;
ce.xclient.type = ClientMessage;
ce.xclient.message_type = FbAtoms::instance()->getWMProtocolsAtom();
ce.xclient.display = disp;
ce.xclient.window = window();
ce.xclient.format = 32;
ce.xclient.data.l[0] = FbAtoms::instance()->getWMDeleteAtom();
ce.xclient.data.l[1] = CurrentTime;
ce.xclient.data.l[2] = 0l;
ce.xclient.data.l[3] = 0l;
ce.xclient.data.l[4] = 0l;
// send event delete message to client window
XSendEvent(disp, window(), false, NoEventMask, &ce);
}
void WinClient::reparent(Window win, int x, int y) {
XReparentWindow(FbTk::App::instance()->display(), window(), win, x, y);
}
bool WinClient::getAttrib(XWindowAttributes &attr) const {
return XGetWindowAttributes(FbTk::App::instance()->display(), window(), &attr);
}
bool WinClient::getWMName(XTextProperty &textprop) const {
return XGetWMName(FbTk::App::instance()->display(), window(), &textprop);
}
bool WinClient::getWMIconName(XTextProperty &textprop) const {
return XGetWMName(FbTk::App::instance()->display(), window(), &textprop);
}
void WinClient::updateTransientInfo() {
if (m_win == 0)
return;
// remove us from parent
if (transientFor() != 0) {
//!! TODO
// since we don't know which client in transientFor()
// that we're transient for then we just remove us
// from every client in transientFor() clientlist
FluxboxWindow::ClientList::iterator client_it =
transientFor()->clientList().begin();
FluxboxWindow::ClientList::iterator client_it_end =
transientFor()->clientList().end();
for (; client_it != client_it_end; ++client_it) {
(*client_it)->transientList().remove(m_win);
}
}
transient_for = 0;
Display *disp = FbTk::App::instance()->display();
// determine if this is a transient window
Window win;
if (!XGetTransientForHint(disp, window(), &win))
return;
// we can't be transient to ourself
if (win == window())
return;
if (win != 0 && m_win->getScreen().getRootWindow() == win) {
m_win->modal = true;
return;
}
transient_for = Fluxbox::instance()->searchWindow(win);
if (transient_for != 0 &&
window_group != None && win == window_group) {
transient_for = Fluxbox::instance()->searchGroup(win, m_win);
}
// make sure we don't have deadlock loop in transient chain
for (FluxboxWindow *w = m_win; w != 0; w = w->m_client->transient_for) {
if (w == w->m_client->transient_for) {
w->m_client->transient_for = 0;
break;
}
}
if (transientFor() != 0) {
// we need to add ourself to the right client in
// the transientFor() window so we search client
WinClient *client = transientFor()->findClient(win);
assert(client != 0);
client->transientList().push_back(m_win);
// make sure we only have on instance of this
client->transientList().unique();
if (transientFor()->isStuck())
m_win->stick();
}
}
void WinClient::updateTitle() {
XTextProperty text_prop;
char **list = 0;
int num = 0;
I18n *i18n = I18n::instance();
if (getWMName(text_prop)) {
if (text_prop.value && text_prop.nitems > 0) {
if (text_prop.encoding != XA_STRING) {
text_prop.nitems = strlen((char *) text_prop.value);
if (XmbTextPropertyToTextList(FbTk::App::instance()->display(), &text_prop,
&list, &num) == Success &&
num > 0 && *list) {
m_title = static_cast<char *>(*list);
XFreeStringList(list);
} else
m_title = (char *)text_prop.value;
} else
m_title = (char *)text_prop.value;
XFree((char *) text_prop.value);
} else { // ok, we don't have a name, set default name
m_title = i18n->getMessage(
FBNLS::WindowSet, FBNLS::WindowUnnamed,
"Unnamed");
}
} else {
m_title = i18n->getMessage(
FBNLS::WindowSet, FBNLS::WindowUnnamed,
"Unnamed");
}
}
void WinClient::updateIconTitle() {
XTextProperty text_prop;
char **list = 0;
int num = 0;
if (getWMIconName(text_prop)) {
if (text_prop.value && text_prop.nitems > 0) {
if (text_prop.encoding != XA_STRING) {
text_prop.nitems = strlen((char *) text_prop.value);
if (XmbTextPropertyToTextList(FbTk::App::instance()->display(), &text_prop,
&list, &num) == Success &&
num > 0 && *list) {
m_icon_title = (char *)*list;
XFreeStringList(list);
} else
m_icon_title = (char *)text_prop.value;
} else
m_icon_title = (char *)text_prop.value;
XFree((char *) text_prop.value);
} else
m_icon_title = title();
} else
m_icon_title = title();
}
<commit_msg>need fbatoms<commit_after>// WinClient.cc for Fluxbox - an X11 Window manager
// Copyright (c) 2003 Henrik Kinnunen (fluxgen(at)users.sourceforge.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// $Id: WinClient.cc,v 1.3 2003/04/15 12:12:29 fluxgen Exp $
#include "WinClient.hh"
#include "Window.hh"
#include "fluxbox.hh"
#include "Screen.hh"
#include "i18n.hh"
#include "FbAtoms.hh"
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
WinClient::WinClient(Window win, FluxboxWindow &fbwin):FbTk::FbWindow(win),
transient_for(0),
window_group(0),
x(0), y(0), old_bw(0),
min_width(1), min_height(1),
max_width(1), max_height(1),
width_inc(1), height_inc(1),
min_aspect_x(1), min_aspect_y(1),
max_aspect_x(1), max_aspect_y(1),
base_width(1), base_height(1),
win_gravity(0),
initial_state(0),
normal_hint_flags(0),
wm_hint_flags(0),
mwm_hint(0),
blackbox_hint(0),
m_win(&fbwin),
m_title(""), m_icon_title(""),
m_diesig(*this) { }
WinClient::~WinClient() {
#ifdef DEBUG
cerr<<__FILE__<<"(~"<<__FUNCTION__<<")[this="<<this<<"]"<<endl;
#endif // DEBUG
m_diesig.notify();
Fluxbox *fluxbox = Fluxbox::instance();
if (transient_for != 0) {
if (transientFor() == m_win) {
transient_for = 0;
}
fluxbox->setFocusedWindow(transient_for);
if (transient_for != 0) {
FluxboxWindow::ClientList::iterator client_it =
transientFor()->clientList().begin();
FluxboxWindow::ClientList::iterator client_it_end =
transientFor()->clientList().end();
for (; client_it != client_it_end; ++client_it) {
(*client_it)->transientList().remove(m_win);
}
transient_for->setInputFocus();
transient_for = 0;
}
}
while (!transients.empty()) {
FluxboxWindow::ClientList::iterator it =
transients.back()->clientList().begin();
FluxboxWindow::ClientList::iterator it_end =
transients.back()->clientList().end();
for (; it != it_end; ++it) {
if ((*it)->transientFor() == m_win)
(*it)->transient_for = 0;
}
transients.pop_back();
}
if (window_group != 0) {
fluxbox->removeGroupSearch(window_group);
window_group = 0;
}
if (mwm_hint != 0)
XFree(mwm_hint);
if (blackbox_hint != 0)
XFree(blackbox_hint);
if (window())
fluxbox->removeWindowSearch(window());
if (m_win != 0)
m_win->removeClient(*this);
m_win = 0;
}
void WinClient::updateRect(int x, int y,
unsigned int width, unsigned int height) {
Display *disp = FbTk::App::instance()->display();
XEvent event;
event.type = ConfigureNotify;
event.xconfigure.display = disp;
event.xconfigure.event = window();
event.xconfigure.window = window();
event.xconfigure.x = x;
event.xconfigure.y = y;
event.xconfigure.width = width;
event.xconfigure.height = height;
//!! TODO
event.xconfigure.border_width = 1;//client.old_bw;
//!! TODO
event.xconfigure.above = None; //m_frame.window().window();
event.xconfigure.override_redirect = false;
XSendEvent(disp, window(), False, StructureNotifyMask, &event);
}
void WinClient::sendFocus() {
Display *disp = FbTk::App::instance()->display();
// setup focus msg
XEvent ce;
ce.xclient.type = ClientMessage;
ce.xclient.message_type = FbAtoms::instance()->getWMProtocolsAtom();
ce.xclient.display = disp;
ce.xclient.window = window();
ce.xclient.format = 32;
ce.xclient.data.l[0] = FbAtoms::instance()->getWMTakeFocusAtom();
ce.xclient.data.l[1] = Fluxbox::instance()->getLastTime();
ce.xclient.data.l[2] = 0l;
ce.xclient.data.l[3] = 0l;
ce.xclient.data.l[4] = 0l;
// send focus msg
XSendEvent(disp, window(), false, NoEventMask, &ce);
}
void WinClient::sendClose() {
Display *disp = FbTk::App::instance()->display();
// fill in XClientMessage structure for delete message
XEvent ce;
ce.xclient.type = ClientMessage;
ce.xclient.message_type = FbAtoms::instance()->getWMProtocolsAtom();
ce.xclient.display = disp;
ce.xclient.window = window();
ce.xclient.format = 32;
ce.xclient.data.l[0] = FbAtoms::instance()->getWMDeleteAtom();
ce.xclient.data.l[1] = CurrentTime;
ce.xclient.data.l[2] = 0l;
ce.xclient.data.l[3] = 0l;
ce.xclient.data.l[4] = 0l;
// send event delete message to client window
XSendEvent(disp, window(), false, NoEventMask, &ce);
}
void WinClient::reparent(Window win, int x, int y) {
XReparentWindow(FbTk::App::instance()->display(), window(), win, x, y);
}
bool WinClient::getAttrib(XWindowAttributes &attr) const {
return XGetWindowAttributes(FbTk::App::instance()->display(), window(), &attr);
}
bool WinClient::getWMName(XTextProperty &textprop) const {
return XGetWMName(FbTk::App::instance()->display(), window(), &textprop);
}
bool WinClient::getWMIconName(XTextProperty &textprop) const {
return XGetWMName(FbTk::App::instance()->display(), window(), &textprop);
}
void WinClient::updateTransientInfo() {
if (m_win == 0)
return;
// remove us from parent
if (transientFor() != 0) {
//!! TODO
// since we don't know which client in transientFor()
// that we're transient for then we just remove us
// from every client in transientFor() clientlist
FluxboxWindow::ClientList::iterator client_it =
transientFor()->clientList().begin();
FluxboxWindow::ClientList::iterator client_it_end =
transientFor()->clientList().end();
for (; client_it != client_it_end; ++client_it) {
(*client_it)->transientList().remove(m_win);
}
}
transient_for = 0;
Display *disp = FbTk::App::instance()->display();
// determine if this is a transient window
Window win;
if (!XGetTransientForHint(disp, window(), &win))
return;
// we can't be transient to ourself
if (win == window())
return;
if (win != 0 && m_win->getScreen().getRootWindow() == win) {
m_win->modal = true;
return;
}
transient_for = Fluxbox::instance()->searchWindow(win);
if (transient_for != 0 &&
window_group != None && win == window_group) {
transient_for = Fluxbox::instance()->searchGroup(win, m_win);
}
// make sure we don't have deadlock loop in transient chain
for (FluxboxWindow *w = m_win; w != 0; w = w->m_client->transient_for) {
if (w == w->m_client->transient_for) {
w->m_client->transient_for = 0;
break;
}
}
if (transientFor() != 0) {
// we need to add ourself to the right client in
// the transientFor() window so we search client
WinClient *client = transientFor()->findClient(win);
assert(client != 0);
client->transientList().push_back(m_win);
// make sure we only have on instance of this
client->transientList().unique();
if (transientFor()->isStuck())
m_win->stick();
}
}
void WinClient::updateTitle() {
XTextProperty text_prop;
char **list = 0;
int num = 0;
I18n *i18n = I18n::instance();
if (getWMName(text_prop)) {
if (text_prop.value && text_prop.nitems > 0) {
if (text_prop.encoding != XA_STRING) {
text_prop.nitems = strlen((char *) text_prop.value);
if (XmbTextPropertyToTextList(FbTk::App::instance()->display(), &text_prop,
&list, &num) == Success &&
num > 0 && *list) {
m_title = static_cast<char *>(*list);
XFreeStringList(list);
} else
m_title = (char *)text_prop.value;
} else
m_title = (char *)text_prop.value;
XFree((char *) text_prop.value);
} else { // ok, we don't have a name, set default name
m_title = i18n->getMessage(
FBNLS::WindowSet, FBNLS::WindowUnnamed,
"Unnamed");
}
} else {
m_title = i18n->getMessage(
FBNLS::WindowSet, FBNLS::WindowUnnamed,
"Unnamed");
}
}
void WinClient::updateIconTitle() {
XTextProperty text_prop;
char **list = 0;
int num = 0;
if (getWMIconName(text_prop)) {
if (text_prop.value && text_prop.nitems > 0) {
if (text_prop.encoding != XA_STRING) {
text_prop.nitems = strlen((char *) text_prop.value);
if (XmbTextPropertyToTextList(FbTk::App::instance()->display(), &text_prop,
&list, &num) == Success &&
num > 0 && *list) {
m_icon_title = (char *)*list;
XFreeStringList(list);
} else
m_icon_title = (char *)text_prop.value;
} else
m_icon_title = (char *)text_prop.value;
XFree((char *) text_prop.value);
} else
m_icon_title = title();
} else
m_icon_title = title();
}
<|endoftext|> |
<commit_before>/*
Transport PK
Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL.
Amanzi is released under the three-clause BSD License.
The terms of use and "as is" disclaimer for this license are
provided in the top-level COPYRIGHT file.
Authors: Neil Carlson
Ethan Coon
Konstantin Lipnikov (lipnikov@lanl.gov)
*/
#ifndef AMANZI_TRANSPORT_DOMAIN_FUNCTION_HH_
#define AMANZI_TRANSPORT_DOMAIN_FUNCTION_HH_
#include <vector>
#include <map>
#include <string>
#include "Epetra_MultiVector.h"
#include "Teuchos_RCP.hpp"
#include "CommonDefs.hh"
#include "Mesh.hh"
//#include "DenseVector.hh"
class State;
namespace Amanzi {
namespace Transport {
class TransportDomainFunction {
public:
TransportDomainFunction() : domain_volume_(-1.0) {};
TransportDomainFunction(const Teuchos::ParameterList& plist) : domain_volume_(-1.0) {};
~TransportDomainFunction() {};
// source term on time interval (t0, t1]
virtual void Compute(double t0, double t1) { ASSERT(false); }
// model name
virtual std::string name() const { return "undefined"; }
// access
// -- volume of the regions
double domain_volume() { return domain_volume_; }
// -- nick-name of the function
std::string keyword() { return keyword_; }
std::vector<std::string>& tcc_names() { return tcc_names_; }
std::vector<int>& tcc_index() { return tcc_index_; }
virtual void set_state(const Teuchos::RCP<State>& S) {S_ = S;}
// iterator methods
typedef std::map<int, std::vector<double> >::iterator Iterator;
Iterator begin() { return value_.begin(); }
Iterator end() { return value_.end(); }
std::map<int, std::vector<double> >::size_type size() { return value_.size(); }
protected:
double domain_volume_;
std::map<int, std::vector<double> > value_; // tcc values on boundary faces
std::string keyword_;
Teuchos::RCP<const State> S_;
std::vector<std::string> tcc_names_; // list of component names
std::vector<int> tcc_index_; // index of component in the global list
};
} // namespace Transport
} // namespace Amanzi
#endif
<commit_msg>cleanup<commit_after>/*
Transport PK
Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL.
Amanzi is released under the three-clause BSD License.
The terms of use and "as is" disclaimer for this license are
provided in the top-level COPYRIGHT file.
Authors: Neil Carlson
Ethan Coon
Konstantin Lipnikov (lipnikov@lanl.gov)
*/
#ifndef AMANZI_TRANSPORT_DOMAIN_FUNCTION_HH_
#define AMANZI_TRANSPORT_DOMAIN_FUNCTION_HH_
#include <vector>
#include <map>
#include <string>
#include "Epetra_MultiVector.h"
#include "Teuchos_RCP.hpp"
#include "CommonDefs.hh"
#include "Mesh.hh"
//#include "DenseVector.hh"
class State;
namespace Amanzi {
namespace Transport {
class TransportDomainFunction {
public:
TransportDomainFunction() : domain_volume_(-1.0) {};
TransportDomainFunction(const Teuchos::ParameterList& plist) : domain_volume_(-1.0) {};
~TransportDomainFunction() {};
// source term on time interval (t0, t1]
virtual void Compute(double t0, double t1) { ASSERT(false); }
// model name
virtual std::string name() const { return "undefined"; }
// access
// -- volume of the regions
double domain_volume() { return domain_volume_; }
// -- nick-name of the function
std::string keyword() { return keyword_; }
std::vector<std::string>& tcc_names() { return tcc_names_; }
std::vector<int>& tcc_index() { return tcc_index_; }
virtual void set_state(const Teuchos::RCP<State>& S) {}
// iterator methods
typedef std::map<int, std::vector<double> >::iterator Iterator;
Iterator begin() { return value_.begin(); }
Iterator end() { return value_.end(); }
std::map<int, std::vector<double> >::size_type size() { return value_.size(); }
protected:
double domain_volume_;
std::map<int, std::vector<double> > value_; // tcc values on boundary faces
std::string keyword_;
std::vector<std::string> tcc_names_; // list of component names
std::vector<int> tcc_index_; // index of component in the global list
};
} // namespace Transport
} // namespace Amanzi
#endif
<|endoftext|> |
<commit_before>#include<KrUIManager.h>
LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) {
return ui.HandleMessage(hwnd,Message,wParam,lParam);
}
static KrUIManager* KrUIManager::GetpKrUIManager()
{
if(m_pKrUIManager==NULL)
m_pKrUIManager=new KrUIManager();
return m_pKrUIManager;
}
bool KrUIManager::Initialize(HINSTANCE hInstance)
{
m_hInstance=hInstance;
memset(&wc,0,sizeof(wc));
wc.cbSize = sizeof(WNDCLASSEX);
wc.lpfnWndProc = WndProc;
wc.hInstance = m_hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszClassName = GetWindowClassName();
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if(!RegisterClassEx(&wc))
{
return false;
}
return true;
//TODO
}
KrWindow* KrUIManager::AddWindow(LPCTSTR lpWindowName,int x,int y,int width,int height,DWORD dwStyle)
{
KrWindow* pKrWindow=new KrWindow;
if(!pKrWindow) return false;
pKrWindow->SetWindowName(lpWindowName);
RECT rect;
rect.left =x;
rect.top =y;
rect.right =x + width;
rect.bottom=y + height;
pKrWindow->SetRect(&rect);
pKrWindow->SetStyle(dwStyle);
pKrWindow->Create();
m_WndList.push_back(pKrWindow);
return pKrWindow;
}
KrWindow* KrUIManager::AddWindow(LPCTSTR lpWindowName,int x,int y,int width,int height)
{
return AddWindow(lpWindowName,x,y,width,height,WS_BORDER);
}
LPCTSTR KrUIManager::GetWindowClassName()
{
return m_lpWindowClassName;
}
HINSTANCE KrUIManager::GetHINSTANCE()
{
return m_hInstance;
}
int MsgLoop()
{
while(GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT KrUIManager::HandleMessage(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
switch(Message) {
case WM_DESTROY: {
PostQuitMessage(0);
break;
}
default:
return DefWindowProc(hwnd, Message, wParam, lParam);
}
return 0;
}
<commit_msg>Create KrUIManager.cpp<commit_after>#include<KrUIManager.h>
LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) {
return ui.HandleMessage(hwnd,Message,wParam,lParam);
}
static KrUIManager* KrUIManager::GetpKrUIManager()
{
if(m_pKrUIManager==NULL)
m_pKrUIManager=new KrUIManager();
return m_pKrUIManager;
}
bool KrUIManager::Initialize(HINSTANCE hInstance)
{
m_hInstance=hInstance;
memset(&wc,0,sizeof(wc));
wc.cbSize = sizeof(WNDCLASSEX);
wc.lpfnWndProc = WndProc;
wc.hInstance = m_hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszClassName = GetWindowClassName();
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if(!RegisterClassEx(&wc))
{
return false;
}
return true;
//TODO
}
KrWindow* KrUIManager::AddWindow(LPCTSTR lpWindowName,int x,int y,int width,int height,DWORD dwStyle)
{
KrWindow* pKrWindow=new KrWindow;
if(!pKrWindow) return false;
pKrWindow->SetWindowName(lpWindowName);
RECT rect;
rect.left =x;
rect.top =y;
rect.right =x + width;
rect.bottom=y + height;
pKrWindow->SetRect(&rect);
pKrWindow->SetStyle(dwStyle);
pKrWindow->Create();
m_WndList.push_back(pKrWindow);
return pKrWindow;
}
KrWindow* KrUIManager::AddWindow(LPCTSTR lpWindowName,int x,int y,int width,int height)
{
return AddWindow(lpWindowName,x,y,width,height,WS_BORDER);
}
LPCTSTR KrUIManager::GetWindowClassName()
{
return m_lpWindowClassName;
}
HINSTANCE KrUIManager::GetHINSTANCE()
{
return m_hInstance;
}
int KrUIManager::MessageLoop()
{
while(GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT KrUIManager::HandleMessage(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
switch(Message) {
case WM_DESTROY: {
PostQuitMessage(0);
break;
}
default:
return DefWindowProc(hwnd, Message, wParam, lParam);
}
return 0;
}
<|endoftext|> |
<commit_before>//===- Symbols.cpp --------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Symbols.h"
#include "Error.h"
#include "InputFiles.h"
#include "InputSection.h"
#include "OutputSections.h"
#include "Strings.h"
#include "SyntheticSections.h"
#include "Target.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Path.h"
#include <cstring>
using namespace llvm;
using namespace llvm::object;
using namespace llvm::ELF;
using namespace lld;
using namespace lld::elf;
template <class ELFT>
static typename ELFT::uint getSymVA(const SymbolBody &Body,
typename ELFT::uint &Addend) {
typedef typename ELFT::uint uintX_t;
switch (Body.kind()) {
case SymbolBody::DefinedSyntheticKind: {
auto &D = cast<DefinedSynthetic<ELFT>>(Body);
const OutputSectionBase *Sec = D.Section;
if (!Sec)
return D.Value;
if (D.Value == DefinedSynthetic<ELFT>::SectionEnd)
return Sec->Addr + Sec->Size;
return Sec->Addr + D.Value;
}
case SymbolBody::DefinedRegularKind: {
auto &D = cast<DefinedRegular<ELFT>>(Body);
InputSectionBase<ELFT> *SC = D.Section;
// According to the ELF spec reference to a local symbol from outside
// the group are not allowed. Unfortunately .eh_frame breaks that rule
// and must be treated specially. For now we just replace the symbol with
// 0.
if (SC == &InputSection<ELFT>::Discarded)
return 0;
// This is an absolute symbol.
if (!SC)
return D.Value;
uintX_t Offset = D.Value;
if (D.isSection()) {
Offset += Addend;
Addend = 0;
}
uintX_t VA = (SC->OutSec ? SC->OutSec->Addr : 0) + SC->getOffset(Offset);
if (D.isTls() && !Config->Relocatable) {
if (!Out<ELFT>::TlsPhdr)
fatal(toString(D.File) +
" has a STT_TLS symbol but doesn't have a PT_TLS section");
return VA - Out<ELFT>::TlsPhdr->p_vaddr;
}
return VA;
}
case SymbolBody::DefinedCommonKind:
return In<ELFT>::Common->OutSec->Addr + In<ELFT>::Common->OutSecOff +
cast<DefinedCommon>(Body).Offset;
case SymbolBody::SharedKind: {
auto &SS = cast<SharedSymbol<ELFT>>(Body);
if (!SS.NeedsCopyOrPltAddr)
return 0;
if (SS.isFunc())
return Body.getPltVA<ELFT>();
return Out<ELFT>::Bss->Addr + SS.OffsetInBss;
}
case SymbolBody::UndefinedKind:
return 0;
case SymbolBody::LazyArchiveKind:
case SymbolBody::LazyObjectKind:
assert(Body.symbol()->IsUsedInRegularObj && "lazy symbol reached writer");
return 0;
}
llvm_unreachable("invalid symbol kind");
}
SymbolBody::SymbolBody(Kind K, StringRefZ Name, bool IsLocal, uint8_t StOther,
uint8_t Type)
: SymbolKind(K), NeedsCopyOrPltAddr(false), IsLocal(IsLocal),
IsInGlobalMipsGot(false), Is32BitMipsGot(false), IsInIplt(false),
IsInIgot(false), Type(Type), StOther(StOther), Name(Name) {}
// Returns true if a symbol can be replaced at load-time by a symbol
// with the same name defined in other ELF executable or DSO.
bool SymbolBody::isPreemptible() const {
if (isLocal())
return false;
// Shared symbols resolve to the definition in the DSO. The exceptions are
// symbols with copy relocations (which resolve to .bss) or preempt plt
// entries (which resolve to that plt entry).
if (isShared())
return !NeedsCopyOrPltAddr;
// That's all that can be preempted in a non-DSO.
if (!Config->Shared)
return false;
// Only symbols that appear in dynsym can be preempted.
if (!symbol()->includeInDynsym())
return false;
// Only default visibility symbols can be preempted.
if (symbol()->Visibility != STV_DEFAULT)
return false;
// -Bsymbolic means that definitions are not preempted.
if (Config->Bsymbolic || (Config->BsymbolicFunctions && isFunc()))
return !isDefined();
return true;
}
template <class ELFT> bool SymbolBody::hasThunk() const {
if (auto *DR = dyn_cast<DefinedRegular<ELFT>>(this))
return DR->ThunkData != nullptr;
if (auto *S = dyn_cast<SharedSymbol<ELFT>>(this))
return S->ThunkData != nullptr;
return false;
}
template <class ELFT>
typename ELFT::uint SymbolBody::getVA(typename ELFT::uint Addend) const {
typename ELFT::uint OutVA = getSymVA<ELFT>(*this, Addend);
return OutVA + Addend;
}
template <class ELFT> typename ELFT::uint SymbolBody::getGotVA() const {
return In<ELFT>::Got->getVA() + getGotOffset<ELFT>();
}
template <class ELFT> typename ELFT::uint SymbolBody::getGotOffset() const {
return GotIndex * Target->GotEntrySize;
}
template <class ELFT> typename ELFT::uint SymbolBody::getGotPltVA() const {
if (this->IsInIgot)
return In<ELFT>::IgotPlt->getVA() + getGotPltOffset<ELFT>();
return In<ELFT>::GotPlt->getVA() + getGotPltOffset<ELFT>();
}
template <class ELFT> typename ELFT::uint SymbolBody::getGotPltOffset() const {
return GotPltIndex * Target->GotPltEntrySize;
}
template <class ELFT> typename ELFT::uint SymbolBody::getPltVA() const {
if (this->IsInIplt)
return In<ELFT>::Iplt->getVA() + PltIndex * Target->PltEntrySize;
return In<ELFT>::Plt->getVA() + Target->PltHeaderSize +
PltIndex * Target->PltEntrySize;
}
template <class ELFT> typename ELFT::uint SymbolBody::getThunkVA() const {
if (const auto *DR = dyn_cast<DefinedRegular<ELFT>>(this))
return DR->ThunkData->getVA();
if (const auto *S = dyn_cast<SharedSymbol<ELFT>>(this))
return S->ThunkData->getVA();
fatal("getThunkVA() not supported for Symbol class\n");
}
template <class ELFT> typename ELFT::uint SymbolBody::getSize() const {
if (const auto *C = dyn_cast<DefinedCommon>(this))
return C->Size;
if (const auto *DR = dyn_cast<DefinedRegular<ELFT>>(this))
return DR->Size;
if (const auto *S = dyn_cast<SharedSymbol<ELFT>>(this))
return S->Sym.st_size;
return 0;
}
// If a symbol name contains '@', the characters after that is
// a symbol version name. This function parses that.
void SymbolBody::parseSymbolVersion() {
StringRef S = getName();
size_t Pos = S.find('@');
if (Pos == 0 || Pos == StringRef::npos)
return;
StringRef Verstr = S.substr(Pos + 1);
if (Verstr.empty())
return;
// Truncate the symbol name so that it doesn't include the version string.
Name = {S.data(), Pos};
// '@@' in a symbol name means the default version.
// It is usually the most recent one.
bool IsDefault = (Verstr[0] == '@');
if (IsDefault)
Verstr = Verstr.substr(1);
for (VersionDefinition &Ver : Config->VersionDefinitions) {
if (Ver.Name != Verstr)
continue;
if (IsDefault)
symbol()->VersionId = Ver.Id;
else
symbol()->VersionId = Ver.Id | VERSYM_HIDDEN;
return;
}
// It is an error if the specified version is not defined.
error(toString(File) + ": symbol " + S + " has undefined version " + Verstr);
}
Defined::Defined(Kind K, StringRefZ Name, bool IsLocal, uint8_t StOther,
uint8_t Type)
: SymbolBody(K, Name, IsLocal, StOther, Type) {}
template <class ELFT> bool DefinedRegular<ELFT>::isMipsPIC() const {
if (!Section || !isFunc())
return false;
return (this->StOther & STO_MIPS_MIPS16) == STO_MIPS_PIC ||
(Section->getFile()->getObj().getHeader()->e_flags & EF_MIPS_PIC);
}
Undefined::Undefined(StringRefZ Name, bool IsLocal, uint8_t StOther,
uint8_t Type, InputFile *File)
: SymbolBody(SymbolBody::UndefinedKind, Name, IsLocal, StOther, Type) {
this->File = File;
}
template <typename ELFT>
DefinedSynthetic<ELFT>::DefinedSynthetic(StringRef Name, uintX_t Value,
const OutputSectionBase *Section)
: Defined(SymbolBody::DefinedSyntheticKind, Name, /*IsLocal=*/false,
STV_HIDDEN, 0 /* Type */),
Value(Value), Section(Section) {}
DefinedCommon::DefinedCommon(StringRef Name, uint64_t Size, uint64_t Alignment,
uint8_t StOther, uint8_t Type, InputFile *File)
: Defined(SymbolBody::DefinedCommonKind, Name, /*IsLocal=*/false, StOther,
Type),
Alignment(Alignment), Size(Size) {
this->File = File;
}
InputFile *Lazy::fetch() {
if (auto *S = dyn_cast<LazyArchive>(this))
return S->fetch();
return cast<LazyObject>(this)->fetch();
}
LazyArchive::LazyArchive(ArchiveFile &File,
const llvm::object::Archive::Symbol S, uint8_t Type)
: Lazy(LazyArchiveKind, S.getName(), Type), Sym(S) {
this->File = &File;
}
LazyObject::LazyObject(StringRef Name, LazyObjectFile &File, uint8_t Type)
: Lazy(LazyObjectKind, Name, Type) {
this->File = &File;
}
InputFile *LazyArchive::fetch() {
std::pair<MemoryBufferRef, uint64_t> MBInfo = file()->getMember(&Sym);
// getMember returns an empty buffer if the member was already
// read from the library.
if (MBInfo.first.getBuffer().empty())
return nullptr;
return createObjectFile(MBInfo.first, file()->getName(), MBInfo.second);
}
InputFile *LazyObject::fetch() {
MemoryBufferRef MBRef = file()->getBuffer();
if (MBRef.getBuffer().empty())
return nullptr;
return createObjectFile(MBRef);
}
bool Symbol::includeInDynsym() const {
if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
return false;
return (ExportDynamic && VersionId != VER_NDX_LOCAL) || body()->isShared() ||
(body()->isUndefined() && Config->Shared);
}
// Print out a log message for --trace-symbol.
void elf::printTraceSymbol(Symbol *Sym) {
SymbolBody *B = Sym->body();
outs() << toString(B->File);
if (B->isUndefined())
outs() << ": reference to ";
else if (B->isCommon())
outs() << ": common definition of ";
else
outs() << ": definition of ";
outs() << B->getName() << "\n";
}
// Returns a symbol for an error message.
std::string elf::toString(const SymbolBody &B) {
if (Config->Demangle)
if (Optional<std::string> S = demangle(B.getName()))
return *S;
return B.getName();
}
template bool SymbolBody::hasThunk<ELF32LE>() const;
template bool SymbolBody::hasThunk<ELF32BE>() const;
template bool SymbolBody::hasThunk<ELF64LE>() const;
template bool SymbolBody::hasThunk<ELF64BE>() const;
template uint32_t SymbolBody::template getVA<ELF32LE>(uint32_t) const;
template uint32_t SymbolBody::template getVA<ELF32BE>(uint32_t) const;
template uint64_t SymbolBody::template getVA<ELF64LE>(uint64_t) const;
template uint64_t SymbolBody::template getVA<ELF64BE>(uint64_t) const;
template uint32_t SymbolBody::template getGotVA<ELF32LE>() const;
template uint32_t SymbolBody::template getGotVA<ELF32BE>() const;
template uint64_t SymbolBody::template getGotVA<ELF64LE>() const;
template uint64_t SymbolBody::template getGotVA<ELF64BE>() const;
template uint32_t SymbolBody::template getGotOffset<ELF32LE>() const;
template uint32_t SymbolBody::template getGotOffset<ELF32BE>() const;
template uint64_t SymbolBody::template getGotOffset<ELF64LE>() const;
template uint64_t SymbolBody::template getGotOffset<ELF64BE>() const;
template uint32_t SymbolBody::template getGotPltVA<ELF32LE>() const;
template uint32_t SymbolBody::template getGotPltVA<ELF32BE>() const;
template uint64_t SymbolBody::template getGotPltVA<ELF64LE>() const;
template uint64_t SymbolBody::template getGotPltVA<ELF64BE>() const;
template uint32_t SymbolBody::template getThunkVA<ELF32LE>() const;
template uint32_t SymbolBody::template getThunkVA<ELF32BE>() const;
template uint64_t SymbolBody::template getThunkVA<ELF64LE>() const;
template uint64_t SymbolBody::template getThunkVA<ELF64BE>() const;
template uint32_t SymbolBody::template getGotPltOffset<ELF32LE>() const;
template uint32_t SymbolBody::template getGotPltOffset<ELF32BE>() const;
template uint64_t SymbolBody::template getGotPltOffset<ELF64LE>() const;
template uint64_t SymbolBody::template getGotPltOffset<ELF64BE>() const;
template uint32_t SymbolBody::template getPltVA<ELF32LE>() const;
template uint32_t SymbolBody::template getPltVA<ELF32BE>() const;
template uint64_t SymbolBody::template getPltVA<ELF64LE>() const;
template uint64_t SymbolBody::template getPltVA<ELF64BE>() const;
template uint32_t SymbolBody::template getSize<ELF32LE>() const;
template uint32_t SymbolBody::template getSize<ELF32BE>() const;
template uint64_t SymbolBody::template getSize<ELF64LE>() const;
template uint64_t SymbolBody::template getSize<ELF64BE>() const;
template class elf::DefinedRegular<ELF32LE>;
template class elf::DefinedRegular<ELF32BE>;
template class elf::DefinedRegular<ELF64LE>;
template class elf::DefinedRegular<ELF64BE>;
template class elf::DefinedSynthetic<ELF32LE>;
template class elf::DefinedSynthetic<ELF32BE>;
template class elf::DefinedSynthetic<ELF64LE>;
template class elf::DefinedSynthetic<ELF64BE>;
<commit_msg>Rename this variable.<commit_after>//===- Symbols.cpp --------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Symbols.h"
#include "Error.h"
#include "InputFiles.h"
#include "InputSection.h"
#include "OutputSections.h"
#include "Strings.h"
#include "SyntheticSections.h"
#include "Target.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Path.h"
#include <cstring>
using namespace llvm;
using namespace llvm::object;
using namespace llvm::ELF;
using namespace lld;
using namespace lld::elf;
template <class ELFT>
static typename ELFT::uint getSymVA(const SymbolBody &Body,
typename ELFT::uint &Addend) {
typedef typename ELFT::uint uintX_t;
switch (Body.kind()) {
case SymbolBody::DefinedSyntheticKind: {
auto &D = cast<DefinedSynthetic<ELFT>>(Body);
const OutputSectionBase *Sec = D.Section;
if (!Sec)
return D.Value;
if (D.Value == DefinedSynthetic<ELFT>::SectionEnd)
return Sec->Addr + Sec->Size;
return Sec->Addr + D.Value;
}
case SymbolBody::DefinedRegularKind: {
auto &D = cast<DefinedRegular<ELFT>>(Body);
InputSectionBase<ELFT> *IS = D.Section;
// According to the ELF spec reference to a local symbol from outside
// the group are not allowed. Unfortunately .eh_frame breaks that rule
// and must be treated specially. For now we just replace the symbol with
// 0.
if (IS == &InputSection<ELFT>::Discarded)
return 0;
// This is an absolute symbol.
if (!IS)
return D.Value;
uintX_t Offset = D.Value;
if (D.isSection()) {
Offset += Addend;
Addend = 0;
}
uintX_t VA = (IS->OutSec ? IS->OutSec->Addr : 0) + IS->getOffset(Offset);
if (D.isTls() && !Config->Relocatable) {
if (!Out<ELFT>::TlsPhdr)
fatal(toString(D.File) +
" has a STT_TLS symbol but doesn't have a PT_TLS section");
return VA - Out<ELFT>::TlsPhdr->p_vaddr;
}
return VA;
}
case SymbolBody::DefinedCommonKind:
return In<ELFT>::Common->OutSec->Addr + In<ELFT>::Common->OutSecOff +
cast<DefinedCommon>(Body).Offset;
case SymbolBody::SharedKind: {
auto &SS = cast<SharedSymbol<ELFT>>(Body);
if (!SS.NeedsCopyOrPltAddr)
return 0;
if (SS.isFunc())
return Body.getPltVA<ELFT>();
return Out<ELFT>::Bss->Addr + SS.OffsetInBss;
}
case SymbolBody::UndefinedKind:
return 0;
case SymbolBody::LazyArchiveKind:
case SymbolBody::LazyObjectKind:
assert(Body.symbol()->IsUsedInRegularObj && "lazy symbol reached writer");
return 0;
}
llvm_unreachable("invalid symbol kind");
}
SymbolBody::SymbolBody(Kind K, StringRefZ Name, bool IsLocal, uint8_t StOther,
uint8_t Type)
: SymbolKind(K), NeedsCopyOrPltAddr(false), IsLocal(IsLocal),
IsInGlobalMipsGot(false), Is32BitMipsGot(false), IsInIplt(false),
IsInIgot(false), Type(Type), StOther(StOther), Name(Name) {}
// Returns true if a symbol can be replaced at load-time by a symbol
// with the same name defined in other ELF executable or DSO.
bool SymbolBody::isPreemptible() const {
if (isLocal())
return false;
// Shared symbols resolve to the definition in the DSO. The exceptions are
// symbols with copy relocations (which resolve to .bss) or preempt plt
// entries (which resolve to that plt entry).
if (isShared())
return !NeedsCopyOrPltAddr;
// That's all that can be preempted in a non-DSO.
if (!Config->Shared)
return false;
// Only symbols that appear in dynsym can be preempted.
if (!symbol()->includeInDynsym())
return false;
// Only default visibility symbols can be preempted.
if (symbol()->Visibility != STV_DEFAULT)
return false;
// -Bsymbolic means that definitions are not preempted.
if (Config->Bsymbolic || (Config->BsymbolicFunctions && isFunc()))
return !isDefined();
return true;
}
template <class ELFT> bool SymbolBody::hasThunk() const {
if (auto *DR = dyn_cast<DefinedRegular<ELFT>>(this))
return DR->ThunkData != nullptr;
if (auto *S = dyn_cast<SharedSymbol<ELFT>>(this))
return S->ThunkData != nullptr;
return false;
}
template <class ELFT>
typename ELFT::uint SymbolBody::getVA(typename ELFT::uint Addend) const {
typename ELFT::uint OutVA = getSymVA<ELFT>(*this, Addend);
return OutVA + Addend;
}
template <class ELFT> typename ELFT::uint SymbolBody::getGotVA() const {
return In<ELFT>::Got->getVA() + getGotOffset<ELFT>();
}
template <class ELFT> typename ELFT::uint SymbolBody::getGotOffset() const {
return GotIndex * Target->GotEntrySize;
}
template <class ELFT> typename ELFT::uint SymbolBody::getGotPltVA() const {
if (this->IsInIgot)
return In<ELFT>::IgotPlt->getVA() + getGotPltOffset<ELFT>();
return In<ELFT>::GotPlt->getVA() + getGotPltOffset<ELFT>();
}
template <class ELFT> typename ELFT::uint SymbolBody::getGotPltOffset() const {
return GotPltIndex * Target->GotPltEntrySize;
}
template <class ELFT> typename ELFT::uint SymbolBody::getPltVA() const {
if (this->IsInIplt)
return In<ELFT>::Iplt->getVA() + PltIndex * Target->PltEntrySize;
return In<ELFT>::Plt->getVA() + Target->PltHeaderSize +
PltIndex * Target->PltEntrySize;
}
template <class ELFT> typename ELFT::uint SymbolBody::getThunkVA() const {
if (const auto *DR = dyn_cast<DefinedRegular<ELFT>>(this))
return DR->ThunkData->getVA();
if (const auto *S = dyn_cast<SharedSymbol<ELFT>>(this))
return S->ThunkData->getVA();
fatal("getThunkVA() not supported for Symbol class\n");
}
template <class ELFT> typename ELFT::uint SymbolBody::getSize() const {
if (const auto *C = dyn_cast<DefinedCommon>(this))
return C->Size;
if (const auto *DR = dyn_cast<DefinedRegular<ELFT>>(this))
return DR->Size;
if (const auto *S = dyn_cast<SharedSymbol<ELFT>>(this))
return S->Sym.st_size;
return 0;
}
// If a symbol name contains '@', the characters after that is
// a symbol version name. This function parses that.
void SymbolBody::parseSymbolVersion() {
StringRef S = getName();
size_t Pos = S.find('@');
if (Pos == 0 || Pos == StringRef::npos)
return;
StringRef Verstr = S.substr(Pos + 1);
if (Verstr.empty())
return;
// Truncate the symbol name so that it doesn't include the version string.
Name = {S.data(), Pos};
// '@@' in a symbol name means the default version.
// It is usually the most recent one.
bool IsDefault = (Verstr[0] == '@');
if (IsDefault)
Verstr = Verstr.substr(1);
for (VersionDefinition &Ver : Config->VersionDefinitions) {
if (Ver.Name != Verstr)
continue;
if (IsDefault)
symbol()->VersionId = Ver.Id;
else
symbol()->VersionId = Ver.Id | VERSYM_HIDDEN;
return;
}
// It is an error if the specified version is not defined.
error(toString(File) + ": symbol " + S + " has undefined version " + Verstr);
}
Defined::Defined(Kind K, StringRefZ Name, bool IsLocal, uint8_t StOther,
uint8_t Type)
: SymbolBody(K, Name, IsLocal, StOther, Type) {}
template <class ELFT> bool DefinedRegular<ELFT>::isMipsPIC() const {
if (!Section || !isFunc())
return false;
return (this->StOther & STO_MIPS_MIPS16) == STO_MIPS_PIC ||
(Section->getFile()->getObj().getHeader()->e_flags & EF_MIPS_PIC);
}
Undefined::Undefined(StringRefZ Name, bool IsLocal, uint8_t StOther,
uint8_t Type, InputFile *File)
: SymbolBody(SymbolBody::UndefinedKind, Name, IsLocal, StOther, Type) {
this->File = File;
}
template <typename ELFT>
DefinedSynthetic<ELFT>::DefinedSynthetic(StringRef Name, uintX_t Value,
const OutputSectionBase *Section)
: Defined(SymbolBody::DefinedSyntheticKind, Name, /*IsLocal=*/false,
STV_HIDDEN, 0 /* Type */),
Value(Value), Section(Section) {}
DefinedCommon::DefinedCommon(StringRef Name, uint64_t Size, uint64_t Alignment,
uint8_t StOther, uint8_t Type, InputFile *File)
: Defined(SymbolBody::DefinedCommonKind, Name, /*IsLocal=*/false, StOther,
Type),
Alignment(Alignment), Size(Size) {
this->File = File;
}
InputFile *Lazy::fetch() {
if (auto *S = dyn_cast<LazyArchive>(this))
return S->fetch();
return cast<LazyObject>(this)->fetch();
}
LazyArchive::LazyArchive(ArchiveFile &File,
const llvm::object::Archive::Symbol S, uint8_t Type)
: Lazy(LazyArchiveKind, S.getName(), Type), Sym(S) {
this->File = &File;
}
LazyObject::LazyObject(StringRef Name, LazyObjectFile &File, uint8_t Type)
: Lazy(LazyObjectKind, Name, Type) {
this->File = &File;
}
InputFile *LazyArchive::fetch() {
std::pair<MemoryBufferRef, uint64_t> MBInfo = file()->getMember(&Sym);
// getMember returns an empty buffer if the member was already
// read from the library.
if (MBInfo.first.getBuffer().empty())
return nullptr;
return createObjectFile(MBInfo.first, file()->getName(), MBInfo.second);
}
InputFile *LazyObject::fetch() {
MemoryBufferRef MBRef = file()->getBuffer();
if (MBRef.getBuffer().empty())
return nullptr;
return createObjectFile(MBRef);
}
bool Symbol::includeInDynsym() const {
if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
return false;
return (ExportDynamic && VersionId != VER_NDX_LOCAL) || body()->isShared() ||
(body()->isUndefined() && Config->Shared);
}
// Print out a log message for --trace-symbol.
void elf::printTraceSymbol(Symbol *Sym) {
SymbolBody *B = Sym->body();
outs() << toString(B->File);
if (B->isUndefined())
outs() << ": reference to ";
else if (B->isCommon())
outs() << ": common definition of ";
else
outs() << ": definition of ";
outs() << B->getName() << "\n";
}
// Returns a symbol for an error message.
std::string elf::toString(const SymbolBody &B) {
if (Config->Demangle)
if (Optional<std::string> S = demangle(B.getName()))
return *S;
return B.getName();
}
template bool SymbolBody::hasThunk<ELF32LE>() const;
template bool SymbolBody::hasThunk<ELF32BE>() const;
template bool SymbolBody::hasThunk<ELF64LE>() const;
template bool SymbolBody::hasThunk<ELF64BE>() const;
template uint32_t SymbolBody::template getVA<ELF32LE>(uint32_t) const;
template uint32_t SymbolBody::template getVA<ELF32BE>(uint32_t) const;
template uint64_t SymbolBody::template getVA<ELF64LE>(uint64_t) const;
template uint64_t SymbolBody::template getVA<ELF64BE>(uint64_t) const;
template uint32_t SymbolBody::template getGotVA<ELF32LE>() const;
template uint32_t SymbolBody::template getGotVA<ELF32BE>() const;
template uint64_t SymbolBody::template getGotVA<ELF64LE>() const;
template uint64_t SymbolBody::template getGotVA<ELF64BE>() const;
template uint32_t SymbolBody::template getGotOffset<ELF32LE>() const;
template uint32_t SymbolBody::template getGotOffset<ELF32BE>() const;
template uint64_t SymbolBody::template getGotOffset<ELF64LE>() const;
template uint64_t SymbolBody::template getGotOffset<ELF64BE>() const;
template uint32_t SymbolBody::template getGotPltVA<ELF32LE>() const;
template uint32_t SymbolBody::template getGotPltVA<ELF32BE>() const;
template uint64_t SymbolBody::template getGotPltVA<ELF64LE>() const;
template uint64_t SymbolBody::template getGotPltVA<ELF64BE>() const;
template uint32_t SymbolBody::template getThunkVA<ELF32LE>() const;
template uint32_t SymbolBody::template getThunkVA<ELF32BE>() const;
template uint64_t SymbolBody::template getThunkVA<ELF64LE>() const;
template uint64_t SymbolBody::template getThunkVA<ELF64BE>() const;
template uint32_t SymbolBody::template getGotPltOffset<ELF32LE>() const;
template uint32_t SymbolBody::template getGotPltOffset<ELF32BE>() const;
template uint64_t SymbolBody::template getGotPltOffset<ELF64LE>() const;
template uint64_t SymbolBody::template getGotPltOffset<ELF64BE>() const;
template uint32_t SymbolBody::template getPltVA<ELF32LE>() const;
template uint32_t SymbolBody::template getPltVA<ELF32BE>() const;
template uint64_t SymbolBody::template getPltVA<ELF64LE>() const;
template uint64_t SymbolBody::template getPltVA<ELF64BE>() const;
template uint32_t SymbolBody::template getSize<ELF32LE>() const;
template uint32_t SymbolBody::template getSize<ELF32BE>() const;
template uint64_t SymbolBody::template getSize<ELF64LE>() const;
template uint64_t SymbolBody::template getSize<ELF64BE>() const;
template class elf::DefinedRegular<ELF32LE>;
template class elf::DefinedRegular<ELF32BE>;
template class elf::DefinedRegular<ELF64LE>;
template class elf::DefinedRegular<ELF64BE>;
template class elf::DefinedSynthetic<ELF32LE>;
template class elf::DefinedSynthetic<ELF32BE>;
template class elf::DefinedSynthetic<ELF64LE>;
template class elf::DefinedSynthetic<ELF64BE>;
<|endoftext|> |
<commit_before>/*
------------------------------------------------------------------
This file is part of the Open Ephys GUI
Copyright (C) 2013 Open Ephys
------------------------------------------------------------------
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 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include "EvntTrigAvg.h"
#include "EvntTrigAvgCanvas.h"
#include "HistogramLib/HistogramLib.h"
class EvntTrigAvg;
EvntTrigAvg::EvntTrigAvg()
: GenericProcessor("Evnt Trig Avg")
{
setProcessorType (PROCESSOR_TYPE_FILTER);
windowSize = getDefaultSampleRate(); // 1 sec in samples
binSize = getDefaultSampleRate()/100; // 10 milliseconds in samples
}
EvntTrigAvg::~EvntTrigAvg()
{
}
void EvntTrigAvg::setParameter(int parameterIndex, float newValue){
bool changed = false;
if (parameterIndex == 0 && triggerEvent != static_cast<int>(newValue)){
triggerEvent = static_cast<int>(newValue);
changed = true;
}
else if (parameterIndex == 1 && triggerChannel != static_cast<int>(newValue)){
triggerChannel = static_cast<int>(newValue);
changed = true;
}
else if(parameterIndex == 2 && binSize != newValue*(getSampleRate()/1000)){
binSize = newValue*(getSampleRate()/1000);
changed = true;
}
else if(parameterIndex == 3 && windowSize != newValue*(getSampleRate()/1000)){
windowSize = newValue*(getSampleRate()/1000);
changed = true;
}
else if (parameterIndex == 4)
changed = true;
// If anything was changed, delete all data and start over
if (changed){
minMaxMean.clear();
spikeData.clear();
ttlTimestampBuffer.clear();
histogramData.clear();
lastTTLCalculated=0;
updateSettings();
//recalc=true;
}
}
void EvntTrigAvg::updateSettings(){
electrodeMap.clear();
electrodeMap = createElectrodeMap();
electrodeLabels.clear();
electrodeLabels = createElectrodeLabels();
if(spikeData.size()!=getTotalSpikeChannels()){
spikeData.resize(getTotalSpikeChannels());
minMaxMean.resize(getTotalSpikeChannels());
}
for(int electrodeIt = 0 ; electrodeIt < spikeData.size() ; electrodeIt++){
if(spikeData[electrodeIt].size()<1){
spikeData[electrodeIt].resize(1);
minMaxMean[electrodeIt].resize(1);
}
for(int sortedIdIt = 0 ; sortedIdIt < spikeData[electrodeIt].size() ; sortedIdIt++){
spikeData[electrodeIt][sortedIdIt].reserve(spikeData[electrodeIt][sortedIdIt].size()+200);
minMaxMean[electrodeIt][sortedIdIt]={0,0,0};
}
}
}
bool EvntTrigAvg::enable(){
return true;
}
bool EvntTrigAvg::disable(){
return true;
}
void EvntTrigAvg::process(AudioSampleBuffer& buffer){
checkForEvents(true);
if(buffer.getNumChannels() != numChannels)
numChannels = buffer.getNumChannels();
if(ttlTimestampBuffer.size() > lastTTLCalculated && buffer.getNumSamples() + getTimestamp(0) >= ttlTimestampBuffer[lastTTLCalculated+1] + windowSize/2){
recalc = true;
}
if(recalc){
histogramData=processSpikeData(spikeData, ttlTimestampBuffer);
lastTTLCalculated+=1;
recalc=false;
readHistoData=true;
}
}
void EvntTrigAvg::handleEvent(const EventChannel* eventInfo, const MidiMessage& event, int sampleNum){
if (triggerEvent < 0) return;
else if (eventInfo->getChannelType() == EventChannel::TTL && eventInfo == eventChannelArray[triggerEvent])
{
TTLEventPtr ttl = TTLEvent::deserializeFromMessage(event, eventInfo);
if (ttl->getChannel() == triggerChannel)
ttlTimestampBuffer.push_back(Event::getTimestamp(event));
}
}
void EvntTrigAvg::handleSpike(const SpikeChannel* spikeInfo, const MidiMessage& event, int samplePosition){
SpikeEventPtr newSpike = SpikeEvent::deserializeFromMessage(event, spikeInfo);
if (!newSpike)
return;
else { // need to address resizing
const SpikeChannel* chan = newSpike->getChannelInfo();
Array<sourceChannelInfo> chanInfo = chan->getSourceChannelInfo();
int chanIDX = chanInfo[0].channelIDX;
int sortedID = newSpike->getSortedID();
int electrode = electrodeMap[chanIDX];
if (sortedID+1>spikeData[electrode].size()){
spikeData[electrode].resize(sortedID+1);
}
if (sortedID+1>minMaxMean[electrode].size()){
minMaxMean[electrode].resize(sortedID+1);
minMaxMean[electrode][sortedID]={0,0,0};
}
if(spikeData[electrode][sortedID].size() == spikeData[electrode][sortedID].capacity())
spikeData[electrode][sortedID].reserve(spikeData[electrode][sortedID].size()+200);
spikeData[electrode][sortedID].push_back(newSpike->getTimestamp());
if (sortedID>0)
spikeData[electrode][0].push_back(newSpike->getTimestamp());
}
}
AudioProcessorEditor* EvntTrigAvg::createEditor(){
editor = new EvntTrigAvgEditor (this, true);
return editor;
}
void EvntTrigAvg::clearTTLTimestampBuffer(){
ttlTimestampBuffer.clear();
}
float EvntTrigAvg::getSampleRate(){
return juce::AudioProcessor::getSampleRate();
}
std::vector<uint64> EvntTrigAvg::getTTLTimestampBuffer(){
return ttlTimestampBuffer;
}
int EvntTrigAvg::getLastTTLCalculated(){
return lastTTLCalculated;
}
/** creates map to convert channelIDX to electrode number */
std::vector<int> EvntTrigAvg::createElectrodeMap(){
std::vector<int> map;
int numSpikeChannels = getTotalSpikeChannels();
int electrodeCounter=0;
for (int chanIt = 0 ; chanIt < numSpikeChannels ; chanIt++){
const SpikeChannel* chan = getSpikeChannel(chanIt);
// add to running count of each electrode
map.resize(map.size()+chan->getNumChannels());
Array<sourceChannelInfo> chanInfo = chan->getSourceChannelInfo();
for (int subChanIt = 0 ; subChanIt < chan->getNumChannels() ; subChanIt++){
map[chanInfo[subChanIt].channelIDX] = electrodeCounter;
}
electrodeCounter+=1;
}
return map;
}
std::vector<String> EvntTrigAvg::createElectrodeLabels(){
std::vector<String> map;
int numSpikeChannels = getTotalSpikeChannels();
map.resize(numSpikeChannels);
String electrodeNames[3]{"Si ","St ","TT "};
int electrodeCounter[3]{0};
for (int chanIt = 0 ; chanIt < numSpikeChannels ; chanIt++){
const SpikeChannel* chan = getSpikeChannel(chanIt);
// add to running count of each electrode
int chanType = chan->getChannelType();
electrodeCounter[chanType]+=1;
map[chanIt]=electrodeNames[chanType]+String(electrodeCounter[chanType]);
}
return map;
}
/** pass data into createHistogramData() by electrode and sorted ID */
// TODO modify so only new data is analyzed to save processing time/memory
std::vector<std::vector<std::vector<uint64>>> EvntTrigAvg::processSpikeData(std::vector<std::vector<std::vector<uint64>>> spikeData,std::vector<uint64> ttlData){
//std::cout<<"processing spike data \n";
std::vector<std::vector<std::vector<uint64>>> processedSpikeData;
processedSpikeData.resize(spikeData.size());
for (int channelIterator = 0 ; channelIterator < getTotalSpikeChannels() ; channelIterator++){
processedSpikeData[channelIterator].resize(spikeData[channelIterator].size());
for (int sortedIdIterator = 0 ; sortedIdIterator < spikeData[channelIterator].size() ; sortedIdIterator++){
//if(spikeData[channelIterator][sortedIdIterator].size()>0){
std::vector<uint64> toAdd = createHistogramData(spikeData[channelIterator][sortedIdIterator],ttlData);
if(minMaxMean.size()<channelIterator+1)
minMaxMean.resize(channelIterator+1);
if(minMaxMean[channelIterator].size()<sortedIdIterator+1)
minMaxMean[channelIterator].resize(channelIterator+1);
if(minMaxMean[channelIterator][sortedIdIterator].size()<3)
minMaxMean[channelIterator][sortedIdIterator].resize(3);
minMaxMean[channelIterator][sortedIdIterator][0]=findMin(toAdd);
minMaxMean[channelIterator][sortedIdIterator][1]=findMax(toAdd);
minMaxMean[channelIterator][sortedIdIterator][2]=findMean(toAdd);
for (int i = 0 ; i < toAdd.size() ; i++){
if (i >= processedSpikeData.size()){
processedSpikeData.resize(i+1);
}
processedSpikeData[channelIterator][sortedIdIterator].push_back(toAdd[i]);
}
//}
}
}
return processedSpikeData;
}
/** returns bin counts */
std::vector<uint64> EvntTrigAvg::createHistogramData(std::vector<uint64> spikeData, std::vector<uint64> ttlData){
uint64 numberOfBins = windowSize/binSize;
std::vector<uint64> histoData;
histoData.reserve(numberOfBins);
for(int ttlIterator = 0 ; ttlIterator < ttlData.size() ; ttlIterator++){
for(int spikeIterator = 0 ; spikeIterator < spikeData.size() ; spikeIterator++){
int relativeSpikeValue = int(spikeData[spikeIterator])-int(ttlData[ttlIterator]);
if (relativeSpikeValue >= -int(windowSize)/2 && relativeSpikeValue <= int(windowSize)/2){
uint64 bin = binDataPoint(0, numberOfBins, binSize, relativeSpikeValue+windowSize/2);
histoData.push_back(bin);
}
}
}
return binCount(histoData,numberOfBins);
}
// Returns the bin a data point belongs to given the very first value covered by the bins, the very last value covered by then bins, bin size and the data point to bin, currently only works for positive numbers (can get around by adding minimum value to all values
uint64 EvntTrigAvg::binDataPoint(uint64 startBin, uint64 endBin, uint64 binSize, uint64 dataPoint){
uint64 binsInRange = (endBin-startBin)+1;
uint64 binsToSearch = binsInRange/2;
if (binsToSearch <= 1){
return startBin;
}
else if (dataPoint < (startBin+binsToSearch)*binSize){ // if in first half of search range
return binDataPoint(startBin,startBin+(binsToSearch-1),binSize,dataPoint);
}
else if (dataPoint >= (startBin+binsToSearch) * binSize){ // if in second half of search range
return binDataPoint(startBin+(binsToSearch-1),endBin,binSize,dataPoint);
}
else{
return NULL;
}
}
std::vector<uint64> EvntTrigAvg::binCount(std::vector<uint64> binData, uint64 numberOfBins){
std::vector<uint64> bins(numberOfBins,0); // initialize with 0
for (int dataIterator = 0 ; dataIterator < binData.size() ; dataIterator++){
bins[binData[dataIterator]]+=1;
}
return bins;
}
uint64 EvntTrigAvg::getBinSize(){
return binSize;
}
uint64 EvntTrigAvg::getWindowSize(){
return windowSize;
}
std::vector<std::vector<std::vector<uint64>>> EvntTrigAvg::getHistoData(){
readHistoData=false;
return histogramData;
}
bool EvntTrigAvg::shouldReadHistoData(){
return readHistoData;
}
//TODO change int_max and int_min to numbers
int EvntTrigAvg::findMin(std::vector<uint64> data){
//int min = INT_MAX;
int min = 2147483647;
for (int i = 0 ; i < data.size() ; i++){
if(data[i]<min){
min=data[i];
}
}
return min;
}
int EvntTrigAvg::findMax(std::vector<uint64> data){
//int max = INT_MIN;
int max =-2147483647;
for (int i = 0 ; i < data.size() ; i++){
int dataPoint = data[i];
if(dataPoint>max){
max=dataPoint;
}
}
return max;
}
float EvntTrigAvg::findMean(std::vector<uint64> data){
int runningSum=0;
for(int i=0 ; i < data.size() ; i++){
runningSum += data[i];
}
float mean = float(runningSum)/float(data.size());
return mean;
}
std::vector<std::vector<std::vector<float>>> EvntTrigAvg::getMinMaxMean(){
return minMaxMean;
}
std::vector<String> EvntTrigAvg::getElectrodeLabels(){
return electrodeLabels;
}
<commit_msg>pre major change<commit_after>/*
------------------------------------------------------------------
This file is part of the Open Ephys GUI
Copyright (C) 2013 Open Ephys
------------------------------------------------------------------
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 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include "EvntTrigAvg.h"
#include "EvntTrigAvgCanvas.h"
#include "HistogramLib/HistogramLib.h"
class EvntTrigAvg;
EvntTrigAvg::EvntTrigAvg()
: GenericProcessor("Evnt Trig Avg")
{
setProcessorType (PROCESSOR_TYPE_FILTER);
windowSize = getDefaultSampleRate(); // 1 sec in samples
binSize = getDefaultSampleRate()/100; // 10 milliseconds in samples
}
EvntTrigAvg::~EvntTrigAvg()
{
}
void EvntTrigAvg::setParameter(int parameterIndex, float newValue){
bool changed = false;
if (parameterIndex == 0 && triggerEvent != static_cast<int>(newValue)){
triggerEvent = static_cast<int>(newValue);
changed = true;
}
else if (parameterIndex == 1 && triggerChannel != static_cast<int>(newValue)){
triggerChannel = static_cast<int>(newValue);
changed = true;
}
else if(parameterIndex == 2 && binSize != newValue*(getSampleRate()/1000)){
binSize = newValue*(getSampleRate()/1000);
changed = true;
}
else if(parameterIndex == 3 && windowSize != newValue*(getSampleRate()/1000)){
windowSize = newValue*(getSampleRate()/1000);
changed = true;
}
else if (parameterIndex == 4)
changed = true;
// If anything was changed, delete all data and start over
if (changed){
minMaxMean.clear();
spikeData.clear();
ttlTimestampBuffer.clear();
histogramData.clear();
lastTTLCalculated=0;
updateSettings();
//recalc=true;
}
}
void EvntTrigAvg::updateSettings(){
electrodeMap.clear();
electrodeMap = createElectrodeMap();
electrodeLabels.clear();
electrodeLabels = createElectrodeLabels();
if(spikeData.size()!=getTotalSpikeChannels()){
spikeData.resize(getTotalSpikeChannels());
minMaxMean.resize(getTotalSpikeChannels());
}
for(int electrodeIt = 0 ; electrodeIt < spikeData.size() ; electrodeIt++){
if(spikeData[electrodeIt].size()<1){
spikeData[electrodeIt].resize(1);
minMaxMean[electrodeIt].resize(1);
}
for(int sortedIdIt = 0 ; sortedIdIt < spikeData[electrodeIt].size() ; sortedIdIt++){
spikeData[electrodeIt][sortedIdIt].reserve(spikeData[electrodeIt][sortedIdIt].size()+200);
minMaxMean[electrodeIt][sortedIdIt]={0,0,0};
}
}
}
bool EvntTrigAvg::enable(){
return true;
}
bool EvntTrigAvg::disable(){
return true;
}
void EvntTrigAvg::process(AudioSampleBuffer& buffer){
checkForEvents(true);
if(buffer.getNumChannels() != numChannels)
numChannels = buffer.getNumChannels();
if(ttlTimestampBuffer.size() > lastTTLCalculated && buffer.getNumSamples() + getTimestamp(0) >= ttlTimestampBuffer[lastTTLCalculated+1] + windowSize/2){
recalc = true;
}
if(recalc){
histogramData=processSpikeData(spikeData, ttlTimestampBuffer);
lastTTLCalculated+=1;
recalc=false;
readHistoData=true;
}
}
void EvntTrigAvg::handleEvent(const EventChannel* eventInfo, const MidiMessage& event, int sampleNum){
if (triggerEvent < 0) return;
else if (eventInfo->getChannelType() == EventChannel::TTL && eventInfo == eventChannelArray[triggerEvent])
{
TTLEventPtr ttl = TTLEvent::deserializeFromMessage(event, eventInfo);
if (ttl->getChannel() == triggerChannel)
ttlTimestampBuffer.push_back(Event::getTimestamp(event));
}
}
void EvntTrigAvg::handleSpike(const SpikeChannel* spikeInfo, const MidiMessage& event, int samplePosition){
SpikeEventPtr newSpike = SpikeEvent::deserializeFromMessage(event, spikeInfo);
if (!newSpike)
return;
else { // need to address resizing
const SpikeChannel* chan = newSpike->getChannelInfo();
Array<sourceChannelInfo> chanInfo = chan->getSourceChannelInfo();
int chanIDX = chanInfo[0].channelIDX;
int sortedID = newSpike->getSortedID();
int electrode = electrodeMap[chanIDX];
if (sortedID+1>spikeData[electrode].size()){
spikeData[electrode].resize(sortedID+1);
}
if (sortedID+1>minMaxMean[electrode].size()){
minMaxMean[electrode].resize(sortedID+1);
minMaxMean[electrode][sortedID]={0,0,0};
}
if(spikeData[electrode][sortedID].size() == spikeData[electrode][sortedID].capacity())
spikeData[electrode][sortedID].reserve(spikeData[electrode][sortedID].size()+200);
spikeData[electrode][sortedID].push_back(newSpike->getTimestamp());
if (sortedID>0)
spikeData[electrode][0].push_back(newSpike->getTimestamp());
}
}
AudioProcessorEditor* EvntTrigAvg::createEditor(){
editor = new EvntTrigAvgEditor (this, true);
return editor;
}
void EvntTrigAvg::clearTTLTimestampBuffer(){
ttlTimestampBuffer.clear();
}
float EvntTrigAvg::getSampleRate(){
return juce::AudioProcessor::getSampleRate();
}
std::vector<uint64> EvntTrigAvg::getTTLTimestampBuffer(){
return ttlTimestampBuffer;
}
int EvntTrigAvg::getLastTTLCalculated(){
return lastTTLCalculated;
}
/** creates map to convert channelIDX to electrode number */
std::vector<int> EvntTrigAvg::createElectrodeMap(){
std::vector<int> map;
int numSpikeChannels = getTotalSpikeChannels();
int electrodeCounter=0;
for (int chanIt = 0 ; chanIt < numSpikeChannels ; chanIt++){
const SpikeChannel* chan = getSpikeChannel(chanIt);
// add to running count of each electrode
map.resize(map.size()+chan->getNumChannels());
Array<sourceChannelInfo> chanInfo = chan->getSourceChannelInfo();
for (int subChanIt = 0 ; subChanIt < chan->getNumChannels() ; subChanIt++){
map[chanInfo[subChanIt].channelIDX] = electrodeCounter;
}
electrodeCounter+=1;
}
return map;
}
std::vector<String> EvntTrigAvg::createElectrodeLabels(){
std::vector<String> map;
int numSpikeChannels = getTotalSpikeChannels();
map.resize(numSpikeChannels);
String electrodeNames[3]{"Si ","St ","TT "};
int electrodeCounter[3]{0};
for (int chanIt = 0 ; chanIt < numSpikeChannels ; chanIt++){
const SpikeChannel* chan = getSpikeChannel(chanIt);
// add to running count of each electrode
int chanType = chan->getChannelType();
electrodeCounter[chanType]+=1;
map[chanIt]=electrodeNames[chanType]+String(electrodeCounter[chanType]);
}
return map;
}
/** pass data into createHistogramData() by electrode and sorted ID */
// TODO modify so only new data is analyzed to save processing time/memory
std::vector<std::vector<std::vector<uint64>>> EvntTrigAvg::processSpikeData(std::vector<std::vector<std::vector<uint64>>> spikeData,std::vector<uint64> ttlData){
//std::cout<<"processing spike data \n";
std::vector<std::vector<std::vector<uint64>>> processedSpikeData;
processedSpikeData.resize(spikeData.size());
for (int channelIterator = 0 ; channelIterator < getTotalSpikeChannels() ; channelIterator++){
processedSpikeData[channelIterator].resize(spikeData[channelIterator].size());
for (int sortedIdIterator = 0 ; sortedIdIterator < spikeData[channelIterator].size() ; sortedIdIterator++){
//if(spikeData[channelIterator][sortedIdIterator].size()>0){
std::vector<uint64> toAdd = createHistogramData(spikeData[channelIterator][sortedIdIterator],ttlData);
if(minMaxMean.size()<channelIterator+1)
minMaxMean.resize(channelIterator+1);
if(minMaxMean[channelIterator].size()<sortedIdIterator+1)
minMaxMean[channelIterator].resize(channelIterator+1);
if(minMaxMean[channelIterator][sortedIdIterator].size()<3)
minMaxMean[channelIterator][sortedIdIterator].resize(3);
minMaxMean[channelIterator][sortedIdIterator][0]=findMin(toAdd);
minMaxMean[channelIterator][sortedIdIterator][1]=findMax(toAdd);
minMaxMean[channelIterator][sortedIdIterator][2]=findMean(toAdd);
for (int i = 0 ; i < toAdd.size() ; i++){
if (i >= processedSpikeData.size()){
processedSpikeData.resize(i+1);
}
processedSpikeData[channelIterator][sortedIdIterator].push_back(toAdd[i]);
}
//}
}
}
return processedSpikeData;
}
/** returns bin counts */
std::vector<uint64> EvntTrigAvg::createHistogramData(std::vector<uint64> spikeData, std::vector<uint64> ttlData){
uint64 numberOfBins = windowSize/binSize;
std::vector<uint64> histoData;
histoData.reserve(numberOfBins);
for(int ttlIterator = 0 ; ttlIterator < ttlData.size() ; ttlIterator++){
for(int spikeIterator = 0 ; spikeIterator < spikeData.size() ; spikeIterator++){
int relativeSpikeValue = int(spikeData[spikeIterator])-int(ttlData[ttlIterator]);
if (relativeSpikeValue >= -int(windowSize)/2 && relativeSpikeValue <= int(windowSize)/2){
uint64 bin = binDataPoint(0, numberOfBins, binSize, relativeSpikeValue+windowSize/2);
histoData.push_back(bin);
}
}
}
return binCount(histoData,numberOfBins);
}
// Returns the bin a data point belongs to given the very first value covered by the bins, the very last value covered by then bins, bin size and the data point to bin, currently only works for positive numbers (can get around by adding minimum value to all values
uint64 EvntTrigAvg::binDataPoint(uint64 startBin, uint64 endBin, uint64 binSize, uint64 dataPoint){
uint64 binsInRange = (endBin-startBin)+1;
uint64 binsToSearch = binsInRange/2;
if (binsToSearch <= 1){
return startBin;
}
else if (dataPoint < (startBin+binsToSearch)*binSize){ // if in first half of search range
//return binDataPoint(startBin,startBin+(binsToSearch-1),binSize,dataPoint);
return binDataPoint(startBin,startBin+(binsToSearch),binSize,dataPoint);
}
else if (dataPoint >= (startBin+binsToSearch) * binSize){ // if in second half of search range
//return binDataPoint(startBin+(binsToSearch-1),endBin,binSize,dataPoint);
return binDataPoint(startBin+(binsToSearch),endBin,binSize,dataPoint);
}
else{
return NULL;
}
}
std::vector<uint64> EvntTrigAvg::binCount(std::vector<uint64> binData, uint64 numberOfBins){
std::vector<uint64> bins(numberOfBins,0); // initialize with 0
for (int dataIterator = 0 ; dataIterator < binData.size() ; dataIterator++){
bins[binData[dataIterator]]+=1;
}
return bins;
}
uint64 EvntTrigAvg::getBinSize(){
return binSize;
}
uint64 EvntTrigAvg::getWindowSize(){
return windowSize;
}
std::vector<std::vector<std::vector<uint64>>> EvntTrigAvg::getHistoData(){
readHistoData=false;
return histogramData;
}
bool EvntTrigAvg::shouldReadHistoData(){
return readHistoData;
}
//TODO change int_max and int_min to numbers
int EvntTrigAvg::findMin(std::vector<uint64> data){
//int min = INT_MAX;
int min = 2147483647;
for (int i = 0 ; i < data.size() ; i++){
if(data[i]<min){
min=data[i];
}
}
return min;
}
int EvntTrigAvg::findMax(std::vector<uint64> data){
//int max = INT_MIN;
int max =-2147483647;
for (int i = 0 ; i < data.size() ; i++){
int dataPoint = data[i];
if(dataPoint>max){
max=dataPoint;
}
}
return max;
}
float EvntTrigAvg::findMean(std::vector<uint64> data){
int runningSum=0;
for(int i=0 ; i < data.size() ; i++){
runningSum += data[i];
}
float mean = float(runningSum)/float(data.size());
return mean;
}
std::vector<std::vector<std::vector<float>>> EvntTrigAvg::getMinMaxMean(){
return minMaxMean;
}
std::vector<String> EvntTrigAvg::getElectrodeLabels(){
return electrodeLabels;
}
<|endoftext|> |
<commit_before>#ifndef ANY_HPP
# define ANY_HPP
# pragma once
#include <cassert>
#include <cstdint>
#include <stdexcept>
#include <typeinfo>
#include <type_traits>
#include <utility>
namespace generic
{
class any
{
public:
template <typename T>
using remove_cvr = ::std::remove_cv<
typename ::std::remove_reference<T>::type
>;
using typeid_t = void const*;
template <typename T>
static typeid_t type_id() noexcept
{
static struct tmp { tmp() noexcept {} } const type_id;
return &type_id;
}
any() = default;
any(any const& other) :
content(other.content ? other.content->cloner_(other.content) : nullptr)
{
}
any(any&& other) noexcept { *this = ::std::move(other); }
template<typename ValueType,
typename = typename ::std::enable_if<
!::std::is_same<
any, typename ::std::decay<ValueType>::type
>{}
>::type
>
any(ValueType&& value) :
content(new holder<typename remove_cvr<ValueType>::type>(
::std::forward<ValueType>(value)))
{
}
~any() { delete content; }
public: // modifiers
void clear() { swap(any()); }
bool empty() const noexcept { return !*this; }
void swap(any& other) noexcept { ::std::swap(content, other.content); }
void swap(any&& other) noexcept { ::std::swap(content, other.content); }
any& operator=(any const& rhs)
{
return content == rhs.content ? *this : *this = any(rhs);
}
any& operator=(any&& rhs) noexcept { swap(rhs); return *this; }
template<typename ValueType,
typename = typename ::std::enable_if<
!::std::is_same<
any, typename ::std::decay<ValueType>::type
>{}
>::type
>
any& operator=(ValueType&& rhs)
{
return *this = any(::std::forward<ValueType>(rhs));
}
public: // queries
explicit operator bool() const noexcept { return content; }
typeid_t type_id() const noexcept
{
return content ? content->type_id_ : type_id<void>();
}
auto type() const noexcept -> decltype(type_id()) { return type_id(); }
public: // get
template <typename U>
U& get()
#ifdef NDEBUG
noexcept
#endif
{
using nonref = typename remove_cvr<U>::type;
#ifndef NDEBUG
if (content && (type_id() ==
type_id<typename remove_cvr<U>::type>()))
{
return static_cast<any::holder<nonref>*>(content)->held;
}
else
{
throw ::std::bad_typeid();
}
#else
return static_cast<any::holder<nonref>*>(content)->held;
#endif // NDEBUG
}
template <typename U>
typename ::std::enable_if<
!(::std::is_enum<U>{} || ::std::is_fundamental<U>{}),
U const&
>::type
get() const noexcept(noexcept(::std::declval<any>().get<U const&>()))
{
using nonref = typename remove_cvr<U>::type;
return const_cast<any*>(this)->get<nonref const&>();
}
template <typename U>
typename ::std::enable_if<
::std::is_enum<U>{} || ::std::is_fundamental<U>{},
U
>::type
get() const noexcept(noexcept(::std::declval<any>().get<U>()))
{
using nonref = typename remove_cvr<U>::type;
return const_cast<any*>(this)->get<nonref const&>();
}
template <typename U>
typename ::std::enable_if<
!(::std::is_enum<U>{} || ::std::is_fundamental<U>{}),
U const&
>::type
cget() const noexcept(noexcept(::std::declval<any>().get<U const&>()))
{
return get<U>();
}
template <typename U>
typename ::std::enable_if<
(::std::is_enum<U>{} || ::std::is_fundamental<U>{}),
U
>::type
cget() const noexcept(noexcept(::std::declval<any>().get<U>()))
{
return get<U>();
}
private: // types
template <typename T>
static constexpr T* begin(T& value) noexcept
{
return &value;
}
template <typename T, ::std::size_t N>
static constexpr typename ::std::remove_all_extents<T>::type*
begin(T (&array)[N]) noexcept
{
return begin(*array);
}
template <typename T>
static constexpr T* end(T& value) noexcept
{
return &value + 1;
}
template <typename T, ::std::size_t N>
static constexpr typename ::std::remove_all_extents<T>::type*
end(T (&array)[N]) noexcept
{
return end(array[N - 1]);
}
struct placeholder
{
typeid_t const type_id_;
placeholder* (* const cloner_)(placeholder*);
virtual ~placeholder() = default;
protected:
placeholder(typeid_t const ti, decltype(cloner_) const c) noexcept :
type_id_(ti),
cloner_(c)
{
}
};
template <typename ValueType>
struct holder : public placeholder
{
public: // constructor
template <class T, typename U = ValueType>
holder(T&& value,
typename ::std::enable_if<
!::std::is_array<U>{} &&
!::std::is_copy_constructible<U>{}
>::type* = nullptr) :
placeholder(type_id<ValueType>(), throwing_cloner),
held(::std::forward<T>(value))
{
}
template <class T, typename U = ValueType>
holder(T&& value,
typename ::std::enable_if<
!::std::is_array<U>{} &&
::std::is_copy_constructible<U>{}
>::type* = nullptr) :
placeholder(type_id<ValueType>(), cloner),
held(::std::forward<T>(value))
{
}
template <class T, typename U = ValueType>
holder(T&& value,
typename ::std::enable_if<
::std::is_array<U>{} &&
::std::is_move_assignable<
typename ::std::remove_const<
typename ::std::remove_all_extents<U>::type
>::type
>{} &&
::std::is_rvalue_reference<T&&>{}
>::type* = nullptr) :
placeholder(type_id<ValueType>(), throwing_cloner)
{
::std::copy(::std::make_move_iterator(begin(value)),
::std::make_move_iterator(end(value)),
begin(held));
}
template <class T, typename U = ValueType>
holder(T&& value,
typename ::std::enable_if<
::std::is_array<U>{} &&
::std::is_copy_assignable<
typename ::std::remove_const<
typename ::std::remove_all_extents<U>::type
>::type
>{} &&
!::std::is_rvalue_reference<T&&>{}
>::type* = nullptr) :
placeholder(type_id<ValueType>(), cloner)
{
::std::copy(begin(value), end(value), begin(held));
}
holder& operator=(holder const&) = delete;
static placeholder* cloner(placeholder* const base)
{
return new holder<ValueType>(static_cast<holder*>(base)->held);
}
static placeholder* throwing_cloner(placeholder* const)
{
throw ::std::logic_error("");
}
public:
typename ::std::remove_const<ValueType>::type held;
};
private: // representation
template<typename ValueType>
friend ValueType* any_cast(any*) noexcept;
template<typename ValueType>
friend ValueType* unsafe_any_cast(any*) noexcept;
placeholder* content{};
};
template<typename ValueType>
inline ValueType* unsafe_any_cast(any* const operand) noexcept
{
return &static_cast<any::holder<ValueType>*>(operand->content)->held;
}
template<typename ValueType>
inline ValueType const* unsafe_any_cast(any const* const operand) noexcept
{
return unsafe_any_cast<ValueType>(const_cast<any*>(operand));
}
template<typename ValueType>
inline ValueType* any_cast(any* const operand) noexcept
{
return operand &&
(operand->type_id() ==
any::type_id<typename any::remove_cvr<ValueType>::type>()) ?
&static_cast<any::holder<ValueType>*>(operand->content)->held :
nullptr;
}
template<typename ValueType>
inline ValueType const* any_cast(any const* const operand) noexcept
{
return any_cast<ValueType>(const_cast<any*>(operand));
}
template<typename ValueType>
inline ValueType any_cast(any& operand)
#ifdef NDEBUG
noexcept
#endif
{
using nonref = typename any::remove_cvr<ValueType>::type;
#ifndef NDEBUG
auto const result(any_cast<nonref>(&operand));
if (result)
{
return *result;
}
else
{
throw ::std::bad_cast();
}
#else
return *unsafe_any_cast<nonref>(&operand);
#endif // NDEBUG
}
template<typename ValueType>
inline ValueType any_cast(any const& operand) noexcept(
noexcept(
any_cast<typename any::remove_cvr<ValueType>::type>(
const_cast<any&>(operand)
)
)
)
{
using nonref = typename any::remove_cvr<ValueType>::type;
return any_cast<nonref const&>(const_cast<any&>(operand));
}
}
#endif // ANY_HPP
<commit_msg>some fixes<commit_after>#ifndef ANY_HPP
# define ANY_HPP
# pragma once
#include <cassert>
#include <cstdint>
#include <stdexcept>
#include <typeinfo>
#include <type_traits>
#include <utility>
namespace generic
{
class any
{
public:
template <typename T>
using remove_cvr = ::std::remove_cv<
typename ::std::remove_reference<T>::type
>;
using typeid_t = void const*;
template <typename T>
static typeid_t type_id() noexcept
{
static struct tmp { tmp() noexcept {} } const type_id;
return &type_id;
}
any() = default;
any(any const& other) :
content(other.content ? other.content->cloner_(other.content) : nullptr)
{
}
any(any&& other) noexcept { *this = ::std::move(other); }
template<typename ValueType,
typename = typename ::std::enable_if<
!::std::is_same<
any, typename ::std::decay<ValueType>::type
>{}
>::type
>
any(ValueType&& value) :
content(new holder<typename remove_cvr<ValueType>::type>(
::std::forward<ValueType>(value)))
{
}
~any() { delete content; }
public: // modifiers
void clear() { swap(any()); }
bool empty() const noexcept { return !*this; }
void swap(any& other) noexcept { ::std::swap(content, other.content); }
void swap(any&& other) noexcept { ::std::swap(content, other.content); }
any& operator=(any const& rhs)
{
return content == rhs.content ? *this : *this = any(rhs);
}
any& operator=(any&& rhs) noexcept { swap(rhs); return *this; }
template<typename ValueType,
typename = typename ::std::enable_if<
!::std::is_same<
any, typename ::std::decay<ValueType>::type
>{}
>::type
>
any& operator=(ValueType&& rhs)
{
return *this = any(::std::forward<ValueType>(rhs));
}
public: // queries
explicit operator bool() const noexcept { return content; }
typeid_t type_id() const noexcept
{
return content ? content->type_id_ : type_id<void>();
}
auto type() const noexcept -> decltype(type_id()) { return type_id(); }
public: // get
template <typename U>
U& get()
#ifdef NDEBUG
noexcept
#endif
{
using nonref = typename remove_cvr<U>::type;
#ifndef NDEBUG
if (content && (type_id() ==
type_id<typename remove_cvr<U>::type>()))
{
return static_cast<any::holder<nonref>*>(content)->held;
}
else
{
throw ::std::bad_typeid();
}
#else
return static_cast<any::holder<nonref>*>(content)->held;
#endif // NDEBUG
}
template <typename U>
typename ::std::enable_if<
!(::std::is_enum<U>{} || ::std::is_fundamental<U>{}),
U const&
>::type
get() const noexcept(noexcept(::std::declval<any>().get<U const&>()))
{
using nonref = typename remove_cvr<U>::type;
return const_cast<any*>(this)->get<nonref const&>();
}
template <typename U>
typename ::std::enable_if<
::std::is_enum<U>{} || ::std::is_fundamental<U>{},
U
>::type
get() const noexcept(noexcept(::std::declval<any>().get<U>()))
{
using nonref = typename remove_cvr<U>::type;
return const_cast<any*>(this)->get<nonref const&>();
}
template <typename U>
typename ::std::enable_if<
!(::std::is_enum<U>{} || ::std::is_fundamental<U>{}),
U const&
>::type
cget() const noexcept(noexcept(::std::declval<any>().get<U const&>()))
{
return get<U const&>();
}
template <typename U>
typename ::std::enable_if<
(::std::is_enum<U>{} || ::std::is_fundamental<U>{}),
U
>::type
cget() const noexcept(noexcept(::std::declval<any>().get<U>()))
{
return get<U>();
}
private: // types
template <typename T>
static constexpr T* begin(T& value) noexcept
{
return &value;
}
template <typename T, ::std::size_t N>
static constexpr typename ::std::remove_all_extents<T>::type*
begin(T (&array)[N]) noexcept
{
return begin(*array);
}
template <typename T>
static constexpr T* end(T& value) noexcept
{
return &value + 1;
}
template <typename T, ::std::size_t N>
static constexpr typename ::std::remove_all_extents<T>::type*
end(T (&array)[N]) noexcept
{
return end(array[N - 1]);
}
struct placeholder
{
typeid_t const type_id_;
placeholder* (* const cloner_)(placeholder*);
virtual ~placeholder() = default;
protected:
placeholder(typeid_t const ti, decltype(cloner_) const c) noexcept :
type_id_(ti),
cloner_(c)
{
}
};
template <typename ValueType>
struct holder : public placeholder
{
public: // constructor
template <class T, typename U = ValueType>
holder(T&& value,
typename ::std::enable_if<
!::std::is_array<U>{} &&
!::std::is_copy_constructible<U>{}
>::type* = nullptr) :
placeholder(type_id<ValueType>(), throwing_cloner),
held(::std::forward<T>(value))
{
}
template <class T, typename U = ValueType>
holder(T&& value,
typename ::std::enable_if<
!::std::is_array<U>{} &&
::std::is_copy_constructible<U>{}
>::type* = nullptr) :
placeholder(type_id<ValueType>(), cloner),
held(::std::forward<T>(value))
{
}
template <class T, typename U = ValueType>
holder(T&& value,
typename ::std::enable_if<
::std::is_array<U>{} &&
::std::is_move_assignable<
typename ::std::remove_const<
typename ::std::remove_all_extents<U>::type
>::type
>{} &&
::std::is_rvalue_reference<T&&>{}
>::type* = nullptr) :
placeholder(type_id<ValueType>(), throwing_cloner)
{
::std::copy(::std::make_move_iterator(begin(value)),
::std::make_move_iterator(end(value)),
begin(held));
}
template <class T, typename U = ValueType>
holder(T&& value,
typename ::std::enable_if<
::std::is_array<U>{} &&
::std::is_copy_assignable<
typename ::std::remove_const<
typename ::std::remove_all_extents<U>::type
>::type
>{} &&
!::std::is_rvalue_reference<T&&>{}
>::type* = nullptr) :
placeholder(type_id<ValueType>(), cloner)
{
::std::copy(begin(value), end(value), begin(held));
}
holder& operator=(holder const&) = delete;
static placeholder* cloner(placeholder* const base)
{
return new holder<ValueType>(static_cast<holder*>(base)->held);
}
static placeholder* throwing_cloner(placeholder* const)
{
throw ::std::logic_error("");
}
public:
typename ::std::remove_const<ValueType>::type held;
};
private: // representation
template<typename ValueType>
friend ValueType* any_cast(any*) noexcept;
template<typename ValueType>
friend ValueType* unsafe_any_cast(any*) noexcept;
placeholder* content{};
};
template<typename ValueType>
inline ValueType* unsafe_any_cast(any* const operand) noexcept
{
return &static_cast<any::holder<ValueType>*>(operand->content)->held;
}
template<typename ValueType>
inline ValueType const* unsafe_any_cast(any const* const operand) noexcept
{
return unsafe_any_cast<ValueType>(const_cast<any*>(operand));
}
template<typename ValueType>
inline ValueType* any_cast(any* const operand) noexcept
{
return operand &&
(operand->type_id() ==
any::type_id<typename any::remove_cvr<ValueType>::type>()) ?
&static_cast<any::holder<ValueType>*>(operand->content)->held :
nullptr;
}
template<typename ValueType>
inline ValueType const* any_cast(any const* const operand) noexcept
{
return any_cast<ValueType>(const_cast<any*>(operand));
}
template<typename ValueType>
inline ValueType any_cast(any& operand)
#ifdef NDEBUG
noexcept
#endif
{
using nonref = typename any::remove_cvr<ValueType>::type;
#ifndef NDEBUG
auto const result(any_cast<nonref>(&operand));
if (result)
{
return *result;
}
else
{
throw ::std::bad_cast();
}
#else
return *unsafe_any_cast<nonref>(&operand);
#endif // NDEBUG
}
template<typename ValueType>
inline ValueType any_cast(any const& operand) noexcept(
noexcept(
any_cast<typename any::remove_cvr<ValueType>::type>(
const_cast<any&>(operand)
)
)
)
{
using nonref = typename any::remove_cvr<ValueType>::type;
return any_cast<nonref const&>(const_cast<any&>(operand));
}
}
#endif // ANY_HPP
<|endoftext|> |
<commit_before>/*
* File: ast.cpp
* Author: ghernan
*
* Abstract Syntax Tree classes
*
* Created on November 30, 2016, 7:56 PM
*/
#include "OS_support.h"
#include "ast.h"
using namespace std;
//Empty children list constant
const AstNodeList AstNode::ms_noChildren;
// Constructor functions.
//
////////////////////////////////
Ref<AstNode> astCreateBlock(CScriptToken token)
{
return refFromNew( new AstBranchNode(AST_BLOCK, token.getPosition()));
}
Ref<AstNode> astCreateIf (ScriptPosition pos,
Ref<AstNode> condition,
Ref<AstNode> thenSt,
Ref<AstNode> elseSt)
{
auto result = refFromNew( new AstBranchNode(AST_IF, pos));
result->addChild(condition);
result->addChild(thenSt);
result->addChild(elseSt);
return result;
}
Ref<AstNode> astCreateConditional ( ScriptPosition pos,
Ref<AstNode> condition,
Ref<AstNode> thenExpr,
Ref<AstNode> elseExpr)
{
auto result = refFromNew( new AstBranchNode(AST_CONDITIONAL, pos));
result->addChild(condition);
result->addChild(thenExpr);
result->addChild(elseExpr);
return result;
}
Ref<AstNode> astCreateFor (ScriptPosition pos,
Ref<AstNode> initSt,
Ref<AstNode> condition,
Ref<AstNode> incrementSt,
Ref<AstNode> body)
{
auto result = refFromNew( new AstBranchNode(AST_FOR, pos));
result->addChild(initSt);
result->addChild(condition);
result->addChild(incrementSt);
result->addChild(body);
return result;
}
Ref<AstNode> astCreateReturn (ScriptPosition pos, Ref<AstNode> expr)
{
auto result = refFromNew( new AstBranchNode(AST_RETURN, pos));
result->addChild(expr);
return result;
}
Ref<AstNode> astCreateAssignment(ScriptPosition pos,
int opCode,
Ref<AstNode> lexpr,
Ref<AstNode> rexpr)
{
auto result = refFromNew( new AstOperator(AST_ASSIGNMENT, pos, opCode));
result->addChild(lexpr);
result->addChild(rexpr);
return result;
}
Ref<AstNode> astCreatePrefixOp(CScriptToken token, Ref<AstNode> rexpr)
{
auto result = refFromNew( new AstOperator(AST_PREFIXOP,
token.getPosition(),
token.type()));
result->addChild(rexpr);
return result;
}
Ref<AstNode> astCreatePostfixOp(CScriptToken token, Ref<AstNode> lexpr)
{
auto result = refFromNew( new AstOperator(AST_POSTFIXOP,
token.getPosition(),
token.type()));
result->addChild(lexpr);
return result;
}
Ref<AstNode> astCreateBinaryOp(CScriptToken token,
Ref<AstNode> lexpr,
Ref<AstNode> rexpr)
{
auto result = refFromNew( new AstOperator(AST_BINARYOP,
token.getPosition(),
token.type()));
result->addChild(lexpr);
result->addChild(rexpr);
return result;
}
Ref<AstNode> astCreateFnCall(ScriptPosition pos, Ref<AstNode> fnExpr, bool newCall)
{
const AstNodeTypes type = newCall ? AST_NEWCALL: AST_FNCALL;
auto result = refFromNew( new AstBranchNode(type, pos));
result->addChild(fnExpr);
return result;
}
/**
* Transforms a regular function call into a 'new' operator call.
* @param callExpr
* @return
*/
Ref<AstNode> astToNewCall(Ref<AstNode> callExpr)
{
auto result = astCreateFnCall(callExpr->position(),
callExpr->children()[0], true);
auto children = callExpr->children();
for (size_t i = 0; i < children.size(); ++i)
result->addChild(children[i]);
return result;
}
/**
* Creates an array literal AST node.
* @param pos
* @return
*/
Ref<AstNode> astCreateArray(ScriptPosition pos)
{
return refFromNew( new AstBranchNode(AST_ARRAY, pos));
}
Ref<AstNode> astCreateArrayAccess(ScriptPosition pos,
Ref<AstNode> arrayExpr,
Ref<AstNode> indexExpr)
{
auto result = refFromNew( new AstBranchNode(AST_ARRAY_ACCESS, pos));
result->addChild(arrayExpr);
result->addChild(indexExpr);
return result;
}
Ref<AstNode> astCreateMemberAccess(ScriptPosition pos,
Ref<AstNode> objExpr,
Ref<AstNode> identifier)
{
auto result = refFromNew( new AstBranchNode(AST_MEMBER_ACCESS, pos));
result->addChild(objExpr);
result->addChild(identifier);
return result;
}
/**
* Creates an 'AstLiteral' object from a source token.
* @param token
* @return
*/
Ref<AstLiteral> AstLiteral::create(CScriptToken token)
{
Ref<JSValue> value;
switch (token.type())
{
case LEX_R_TRUE: value = jsTrue(); break;
case LEX_R_FALSE: value = jsFalse(); break;
case LEX_R_NULL: value = jsNull(); break;
case LEX_R_UNDEFINED: value = ::undefined(); break;
case LEX_STR:
case LEX_INT:
case LEX_FLOAT:
value = createConstant(token);
break;
default:
ASSERT(!"Invalid token for a literal");
}
return refFromNew(new AstLiteral(token.getPosition(), value));
}
/**
* Creates a literal form an integer
* @param pos
* @param value
* @return
*/
Ref<AstLiteral> AstLiteral::create(ScriptPosition pos, int value)
{
return refFromNew(new AstLiteral(pos, jsInt(value)));
}
/**
* Transforms an AST statement into a Javascript object.
* This particular version creates an object containing all its children
* @return
*/
Ref<JSValue> AstNode::toJS()const
{
Ref<JSObject> obj = JSObject::create();
obj->set("a_type", jsString(astTypeToString(getType())));
const string name = getName();
if (!name.empty())
obj->set("b_name", jsString(name));
const AstNodeList& c = children();
if (!c.empty())
obj->set("z_children", toJSArray(c));
const auto value = getValue();
if (!value->isUndefined())
obj->set("v_value", value);
return obj;
}
/**
* Function declaration to JSValue
* @return
*/
Ref<JSValue> AstFunction::toJS()const
{
Ref<JSObject> obj = AstNode::toJS().staticCast<JSObject>();
obj->set("c_parameters", JSArray::createStrArray(m_params));
obj->set("d_code", m_code->toJS());
return obj;
}
/**
* Operator to JSValue
* @return
*/
Ref<JSValue> AstOperator::toJS()const
{
Ref<JSObject> obj = AstBranchNode::toJS().staticCast<JSObject>();
obj->set("d_operator", jsString(getTokenStr(code)));
return obj;
}
/**
* Object literal to JSValue
* @return
*/
Ref<JSValue> AstObject::toJS()const
{
Ref<JSObject> obj = JSObject::create();
Ref<JSObject> props = JSObject::create();
obj->set("a_type", jsString(astTypeToString(getType())));
obj->set("b_properties", props);
PropertyList::const_iterator it;
for (it = m_properties.begin(); it != m_properties.end(); ++it)
props->set(it->name, it->expr->toJS());
return obj;
}
/**
* Creates a undefined literal
* @param pos
* @return
*/
Ref<AstLiteral> AstLiteral::undefined(ScriptPosition pos)
{
return refFromNew(new AstLiteral(pos, ::undefined()));
}
/**
* Transforms a list of AstNodes into a Javascript Array.
* @param statements
* @return
*/
Ref<JSArray> toJSArray (const AstNodeList& statements)
{
Ref<JSArray> result = JSArray::create();
for (size_t i = 0; i < statements.size(); ++i)
{
if (statements[i].notNull())
result->push( statements[i]->toJS() );
else
result->push(jsNull());
}
return result;
}
/**
* Generates a JSON file from a statements list
* @param statements
* @return
*/
std::string toJSON (const AstNodeList& statements)
{
return toJSArray(statements)->getJSON(0);
}
/**
* Gets the string representation of an AST type
* @param type
* @return
*/
std::string astTypeToString(AstNodeTypes type)
{
typedef map<AstNodeTypes, string> TypesMap;
static TypesMap types;
if (types.empty())
{
types[AST_BLOCK] = "AST_BLOCK";
types[AST_VAR] = "AST_VAR";
types[AST_IF] = "AST_IF";
types[AST_FOR] = "AST_FOR";
types[AST_RETURN] = "AST_RETURN";
types[AST_FUNCTION] = "AST_FUNCTION";
types[AST_ASSIGNMENT] = "AST_ASSIGNMENT";
types[AST_FNCALL] = "AST_FNCALL";
types[AST_NEWCALL] = "AST_NEWCALL";
types[AST_LITERAL] = "AST_LITERAL";
types[AST_IDENTIFIER] = "AST_IDENTIFIER";
types[AST_ARRAY] = "AST_ARRAY";
types[AST_OBJECT] = "AST_OBJECT";
types[AST_ARRAY_ACCESS] = "AST_ARRAY_ACCESS";
types[AST_MEMBER_ACCESS] = "AST_MEMBER_ACCESS";
types[AST_CONDITIONAL] = "AST_CONDITIONAL";
types[AST_BINARYOP] = "AST_BINARYOP";
types[AST_PREFIXOP] = "AST_PREFIXOP";
types[AST_POSTFIXOP] = "AST_POSTFIXOP";
//types[AST_TYPES_COUNT] = "AST_TYPES_COUNT";
}
TypesMap::const_iterator it = types.find(type);
if (it != types.end())
return it->second;
else
return "BAD_AST_TYPE";
}<commit_msg>BUGFIX: Wrong start index in 'astToNewCall' function. It must skip the first child.<commit_after>/*
* File: ast.cpp
* Author: ghernan
*
* Abstract Syntax Tree classes
*
* Created on November 30, 2016, 7:56 PM
*/
#include "OS_support.h"
#include "ast.h"
using namespace std;
//Empty children list constant
const AstNodeList AstNode::ms_noChildren;
// Constructor functions.
//
////////////////////////////////
Ref<AstNode> astCreateBlock(CScriptToken token)
{
return refFromNew( new AstBranchNode(AST_BLOCK, token.getPosition()));
}
Ref<AstNode> astCreateIf (ScriptPosition pos,
Ref<AstNode> condition,
Ref<AstNode> thenSt,
Ref<AstNode> elseSt)
{
auto result = refFromNew( new AstBranchNode(AST_IF, pos));
result->addChild(condition);
result->addChild(thenSt);
result->addChild(elseSt);
return result;
}
Ref<AstNode> astCreateConditional ( ScriptPosition pos,
Ref<AstNode> condition,
Ref<AstNode> thenExpr,
Ref<AstNode> elseExpr)
{
auto result = refFromNew( new AstBranchNode(AST_CONDITIONAL, pos));
result->addChild(condition);
result->addChild(thenExpr);
result->addChild(elseExpr);
return result;
}
Ref<AstNode> astCreateFor (ScriptPosition pos,
Ref<AstNode> initSt,
Ref<AstNode> condition,
Ref<AstNode> incrementSt,
Ref<AstNode> body)
{
auto result = refFromNew( new AstBranchNode(AST_FOR, pos));
result->addChild(initSt);
result->addChild(condition);
result->addChild(incrementSt);
result->addChild(body);
return result;
}
Ref<AstNode> astCreateReturn (ScriptPosition pos, Ref<AstNode> expr)
{
auto result = refFromNew( new AstBranchNode(AST_RETURN, pos));
result->addChild(expr);
return result;
}
Ref<AstNode> astCreateAssignment(ScriptPosition pos,
int opCode,
Ref<AstNode> lexpr,
Ref<AstNode> rexpr)
{
auto result = refFromNew( new AstOperator(AST_ASSIGNMENT, pos, opCode));
result->addChild(lexpr);
result->addChild(rexpr);
return result;
}
Ref<AstNode> astCreatePrefixOp(CScriptToken token, Ref<AstNode> rexpr)
{
auto result = refFromNew( new AstOperator(AST_PREFIXOP,
token.getPosition(),
token.type()));
result->addChild(rexpr);
return result;
}
Ref<AstNode> astCreatePostfixOp(CScriptToken token, Ref<AstNode> lexpr)
{
auto result = refFromNew( new AstOperator(AST_POSTFIXOP,
token.getPosition(),
token.type()));
result->addChild(lexpr);
return result;
}
Ref<AstNode> astCreateBinaryOp(CScriptToken token,
Ref<AstNode> lexpr,
Ref<AstNode> rexpr)
{
auto result = refFromNew( new AstOperator(AST_BINARYOP,
token.getPosition(),
token.type()));
result->addChild(lexpr);
result->addChild(rexpr);
return result;
}
Ref<AstNode> astCreateFnCall(ScriptPosition pos, Ref<AstNode> fnExpr, bool newCall)
{
const AstNodeTypes type = newCall ? AST_NEWCALL: AST_FNCALL;
auto result = refFromNew( new AstBranchNode(type, pos));
result->addChild(fnExpr);
return result;
}
/**
* Transforms a regular function call into a 'new' operator call.
* @param callExpr
* @return
*/
Ref<AstNode> astToNewCall(Ref<AstNode> callExpr)
{
auto result = astCreateFnCall(callExpr->position(),
callExpr->children()[0], true);
auto children = callExpr->children();
for (size_t i = 1; i < children.size(); ++i)
result->addChild(children[i]);
return result;
}
/**
* Creates an array literal AST node.
* @param pos
* @return
*/
Ref<AstNode> astCreateArray(ScriptPosition pos)
{
return refFromNew( new AstBranchNode(AST_ARRAY, pos));
}
Ref<AstNode> astCreateArrayAccess(ScriptPosition pos,
Ref<AstNode> arrayExpr,
Ref<AstNode> indexExpr)
{
auto result = refFromNew( new AstBranchNode(AST_ARRAY_ACCESS, pos));
result->addChild(arrayExpr);
result->addChild(indexExpr);
return result;
}
Ref<AstNode> astCreateMemberAccess(ScriptPosition pos,
Ref<AstNode> objExpr,
Ref<AstNode> identifier)
{
auto result = refFromNew( new AstBranchNode(AST_MEMBER_ACCESS, pos));
result->addChild(objExpr);
result->addChild(identifier);
return result;
}
/**
* Creates an 'AstLiteral' object from a source token.
* @param token
* @return
*/
Ref<AstLiteral> AstLiteral::create(CScriptToken token)
{
Ref<JSValue> value;
switch (token.type())
{
case LEX_R_TRUE: value = jsTrue(); break;
case LEX_R_FALSE: value = jsFalse(); break;
case LEX_R_NULL: value = jsNull(); break;
case LEX_R_UNDEFINED: value = ::undefined(); break;
case LEX_STR:
case LEX_INT:
case LEX_FLOAT:
value = createConstant(token);
break;
default:
ASSERT(!"Invalid token for a literal");
}
return refFromNew(new AstLiteral(token.getPosition(), value));
}
/**
* Creates a literal form an integer
* @param pos
* @param value
* @return
*/
Ref<AstLiteral> AstLiteral::create(ScriptPosition pos, int value)
{
return refFromNew(new AstLiteral(pos, jsInt(value)));
}
/**
* Transforms an AST statement into a Javascript object.
* This particular version creates an object containing all its children
* @return
*/
Ref<JSValue> AstNode::toJS()const
{
Ref<JSObject> obj = JSObject::create();
obj->set("a_type", jsString(astTypeToString(getType())));
const string name = getName();
if (!name.empty())
obj->set("b_name", jsString(name));
const AstNodeList& c = children();
if (!c.empty())
obj->set("z_children", toJSArray(c));
const auto value = getValue();
if (!value->isUndefined())
obj->set("v_value", value);
return obj;
}
/**
* Function declaration to JSValue
* @return
*/
Ref<JSValue> AstFunction::toJS()const
{
Ref<JSObject> obj = AstNode::toJS().staticCast<JSObject>();
obj->set("c_parameters", JSArray::createStrArray(m_params));
obj->set("d_code", m_code->toJS());
return obj;
}
/**
* Operator to JSValue
* @return
*/
Ref<JSValue> AstOperator::toJS()const
{
Ref<JSObject> obj = AstBranchNode::toJS().staticCast<JSObject>();
obj->set("d_operator", jsString(getTokenStr(code)));
return obj;
}
/**
* Object literal to JSValue
* @return
*/
Ref<JSValue> AstObject::toJS()const
{
Ref<JSObject> obj = JSObject::create();
Ref<JSObject> props = JSObject::create();
obj->set("a_type", jsString(astTypeToString(getType())));
obj->set("b_properties", props);
PropertyList::const_iterator it;
for (it = m_properties.begin(); it != m_properties.end(); ++it)
props->set(it->name, it->expr->toJS());
return obj;
}
/**
* Creates a undefined literal
* @param pos
* @return
*/
Ref<AstLiteral> AstLiteral::undefined(ScriptPosition pos)
{
return refFromNew(new AstLiteral(pos, ::undefined()));
}
/**
* Transforms a list of AstNodes into a Javascript Array.
* @param statements
* @return
*/
Ref<JSArray> toJSArray (const AstNodeList& statements)
{
Ref<JSArray> result = JSArray::create();
for (size_t i = 0; i < statements.size(); ++i)
{
if (statements[i].notNull())
result->push( statements[i]->toJS() );
else
result->push(jsNull());
}
return result;
}
/**
* Generates a JSON file from a statements list
* @param statements
* @return
*/
std::string toJSON (const AstNodeList& statements)
{
return toJSArray(statements)->getJSON(0);
}
/**
* Gets the string representation of an AST type
* @param type
* @return
*/
std::string astTypeToString(AstNodeTypes type)
{
typedef map<AstNodeTypes, string> TypesMap;
static TypesMap types;
if (types.empty())
{
types[AST_BLOCK] = "AST_BLOCK";
types[AST_VAR] = "AST_VAR";
types[AST_IF] = "AST_IF";
types[AST_FOR] = "AST_FOR";
types[AST_RETURN] = "AST_RETURN";
types[AST_FUNCTION] = "AST_FUNCTION";
types[AST_ASSIGNMENT] = "AST_ASSIGNMENT";
types[AST_FNCALL] = "AST_FNCALL";
types[AST_NEWCALL] = "AST_NEWCALL";
types[AST_LITERAL] = "AST_LITERAL";
types[AST_IDENTIFIER] = "AST_IDENTIFIER";
types[AST_ARRAY] = "AST_ARRAY";
types[AST_OBJECT] = "AST_OBJECT";
types[AST_ARRAY_ACCESS] = "AST_ARRAY_ACCESS";
types[AST_MEMBER_ACCESS] = "AST_MEMBER_ACCESS";
types[AST_CONDITIONAL] = "AST_CONDITIONAL";
types[AST_BINARYOP] = "AST_BINARYOP";
types[AST_PREFIXOP] = "AST_PREFIXOP";
types[AST_POSTFIXOP] = "AST_POSTFIXOP";
//types[AST_TYPES_COUNT] = "AST_TYPES_COUNT";
}
TypesMap::const_iterator it = types.find(type);
if (it != types.end())
return it->second;
else
return "BAD_AST_TYPE";
}<|endoftext|> |
<commit_before>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"
using namespace MathLib;
CGameProcess::CGameProcess(void)
{
}
CGameProcess::~CGameProcess(void)
{
}
int CGameProcess::Init()
{
g_Engine.pFileSystem->CacheFilesFormExt("char");
g_Engine.pFileSystem->CacheFilesFormExt("node");
g_Engine.pFileSystem->CacheFilesFormExt("smesh");
g_Engine.pFileSystem->CacheFilesFormExt("sanim");
g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
g_Engine.pControls->SetKeyPressFunc(KeyPress);
g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);
m_pRole = new CFPSRoleLocal();
m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); //ؽɫԴ
m_pRole->SetActorPosition(vec3(0, 0, 0)); //ýɫʼλáŴΪԭ㣬άϵvec3
m_pSkillSystem = new CSkillSystem(this);
m_pCameraBase = new CCameraBase();
m_pCameraBase->SetEnabled(1);
}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"
using namespace MathLib;
CGameProcess::CGameProcess(void)
{
}
CGameProcess::~CGameProcess(void)
{
}
int CGameProcess::Init()
{
g_Engine.pFileSystem->CacheFilesFormExt("char");
g_Engine.pFileSystem->CacheFilesFormExt("node");
g_Engine.pFileSystem->CacheFilesFormExt("smesh");
g_Engine.pFileSystem->CacheFilesFormExt("sanim");
g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
g_Engine.pControls->SetKeyPressFunc(KeyPress);
g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);
m_pRole = new CFPSRoleLocal();
m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); //ؽɫԴ
m_pRole->SetActorPosition(vec3(0, 0, 0)); //ýɫʼλáŴΪԭ㣬άϵvec3
m_pSkillSystem = new CSkillSystem(this);
m_pCameraBase = new CCameraBase();
m_pCameraBase->SetEnabled(1);
g_pSysControl->SetMouseGrab(1);
}<|endoftext|> |
<commit_before>/* This file is part of the KDE project
Copyright (C) 2004 Mark Bucciarelli <mark@hubcapconsulting.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <kdebug.h>
#include <qdir.h>
#include <qfile.h>
#include <qstring.h>
#include <qstringlist.h>
#include <qtextstream.h>
#include "script.h"
static QString srcdir();
static int runscripts
( const QString &interpreter, const QString &extension, const QString &path );
// Read srcdir from Makefile (for builddir != srcdir).
QString srcdir()
{
bool found = false;
QString dir;
QFile file( "Makefile" );
if ( !file.open( IO_ReadOnly | IO_Translate ) ) return "";
QTextStream in( &file );
QString line;
while ( !found && !in.atEnd() )
{
line = in.readLine();
if ( line.startsWith( "srcdir = " ) )
{
dir = line.mid( 9 );
found = true;
}
}
if ( !found ) dir = "";
return dir;
}
int runscripts
( const QString &interpreter, const QString &extension, const QString &path )
{
int rval = 0;
QStringList files;
QDir dir( path );
Script* s = new Script( dir );
dir.setNameFilter( extension );
dir.setFilter( QDir::Files );
dir.setSorting( QDir::Name | QDir::IgnoreCase );
const QFileInfoList *list = dir.entryInfoList();
QFileInfoListIterator it( *list );
QFileInfo *fi;
while ( !rval && ( fi = it.current() ) != 0 )
{
// Don't run scripts that are shared routines.
if ( ! fi->fileName().startsWith( "__" ) )
{
kdDebug() << "runscripts: running " << fi->fileName() << endl;
s->addArgument( interpreter );
s->addArgument( path + QDir::separator() + fi->fileName().latin1() );
// Thorsten's xautomation tests run with user interaction by default.
if ( interpreter == "sh" ) s->addArgument( "--batch" );
if ( interpreter == "php" ) s->addArgument( "--batch" );
rval = s->run();
delete s;
s = new Script( dir );
}
++it;
}
delete s;
s = 0;
return rval;
}
int main( int, char** )
{
int rval = 0;
QString path = srcdir();
if ( !rval ) rval = runscripts( "python", "*.py *.Py *.PY *.pY", path );
if ( !rval ) rval = runscripts( "sh", "*.sh *.Sh *.SH *.sH", path );
if ( !rval ) rval = runscripts( "perl", "*.pl *.Pl *.PL *.pL", path );
if ( !rval ) rval = runscripts( "php", "*.php *.php3 *.php4 *.php5", path );
return rval;
}
<commit_msg>output PASS/FAIL result to console<commit_after>/* This file is part of the KDE project
Copyright (C) 2004 Mark Bucciarelli <mark@hubcapconsulting.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <kdebug.h>
#include <qdir.h>
#include <qfile.h>
#include <qstring.h>
#include <qstringlist.h>
#include <qtextstream.h>
#include "script.h"
static QString srcdir();
static int runscripts
( const QString &interpreter, const QString &extension, const QString &path );
const QString dots = "..................................................";
// Read srcdir from Makefile (for builddir != srcdir).
QString srcdir()
{
bool found = false;
QString dir;
QFile file( "Makefile" );
if ( !file.open( IO_ReadOnly | IO_Translate ) ) return "";
QTextStream in( &file );
QString line;
while ( !found && !in.atEnd() )
{
line = in.readLine();
if ( line.startsWith( "srcdir = " ) )
{
dir = line.mid( 9 );
found = true;
}
}
if ( !found ) dir = "";
return dir;
}
int runscripts
( const QString &interpreter, const QString &extension, const QString &path )
{
int rval = 0;
QStringList files;
QDir dir( path );
Script* s = new Script( dir );
dir.setNameFilter( extension );
dir.setFilter( QDir::Files );
dir.setSorting( QDir::Name | QDir::IgnoreCase );
const QFileInfoList *list = dir.entryInfoList();
QFileInfoListIterator it( *list );
QFileInfo *fi;
while ( !rval && ( fi = it.current() ) != 0 )
{
// Don't run scripts that are shared routines.
if ( ! fi->fileName().startsWith( "__" ) )
{
s->addArgument( interpreter );
s->addArgument( path + QDir::separator() + fi->fileName().latin1() );
// Thorsten's xautomation tests run with user interaction by default.
if ( interpreter == "sh" ) s->addArgument( "--batch" );
if ( interpreter == "php" ) s->addArgument( "--batch" );
rval = s->run();
kdDebug() << "runscripts: " << fi->fileName()
<< " " << dots.left( dots.length() - fi->fileName().length() )
<< " " << ( ! rval ? "PASS" : "FAIL" ) << endl;
delete s;
s = new Script( dir );
}
++it;
}
delete s;
s = 0;
return rval;
}
int main( int, char** )
{
int rval = 0;
QString path = srcdir();
if ( !rval ) rval = runscripts( "python", "*.py *.Py *.PY *.pY", path );
if ( !rval ) rval = runscripts( "sh", "*.sh *.Sh *.SH *.sH", path );
if ( !rval ) rval = runscripts( "perl", "*.pl *.Pl *.PL *.pL", path );
if ( !rval ) rval = runscripts( "php", "*.php *.php3 *.php4 *.php5", path );
return rval;
}
<|endoftext|> |
<commit_before>/** -*- c++ -*-
* progressdialog.cpp
*
* Copyright (c) 2004 Till Adam <adam@kde.org>,
* David Faure <faure@kde.org>
*
* 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; version 2 of the License
*
* 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.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of this program with any edition of
* the Qt library by Trolltech AS, Norway (or with modified versions
* of Qt that use the same license as Qt), and distribute linked
* combinations including the two. You must obey the GNU General
* Public License in all respects for all of the code used other than
* Qt. If you modify this file, you may extend this exception to
* your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from
* your version.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <qapplication.h>
#include <qlayout.h>
#include <qprogressbar.h>
#include <qtimer.h>
#include <qheader.h>
#include <qobject.h>
#include <qscrollview.h>
#include <qtoolbutton.h>
#include <qpushbutton.h>
#include <qvbox.h>
#include <klocale.h>
#include <kdialog.h>
#include <kstdguiitem.h>
#include <kiconloader.h>
#include <kdebug.h>
#include "progressdialog.h"
#include "progressmanager.h"
#include "ssllabel.h"
#include "kmmainwidget.h"
using KMail::ProgressItem;
using KMail::ProgressManager;
namespace KMail {
class TransactionItem;
TransactionItemView::TransactionItemView( QWidget * parent,
const char * name,
WFlags f )
: QScrollView( parent, name, f ) {
setFrameStyle( NoFrame );
mBigBox = new QVBox( viewport() );
mBigBox->setSpacing( 5 );
addChild( mBigBox );
setResizePolicy( QScrollView::AutoOneFit ); // Fit so that the box expands horizontally
}
TransactionItem* TransactionItemView::addTransactionItem( ProgressItem* item, bool first )
{
TransactionItem *ti = new TransactionItem( mBigBox, item, first );
ti->show();
return ti;
}
void TransactionItemView::resizeContents( int w, int h )
{
//kdDebug(5006) << k_funcinfo << w << "," << h << endl;
QScrollView::resizeContents( w, h );
// Tell the layout in the parent (progressdialog) that our size changed
updateGeometry();
// Resize the parent (progressdialog) - this works but resize horizontally too often
//parentWidget()->adjustSize();
QApplication::sendPostedEvents( 0, QEvent::ChildInserted );
QApplication::sendPostedEvents( 0, QEvent::LayoutHint );
QSize sz = parentWidget()->sizeHint();
int currentWidth = parentWidget()->width();
// Don't resize to sz.width() every time when it only reduces a little bit
if ( currentWidth < sz.width() || currentWidth > sz.width() + 100 )
currentWidth = sz.width();
parentWidget()->resize( currentWidth, sz.height() );
}
QSize TransactionItemView::sizeHint() const
{
return minimumSizeHint();
}
QSize TransactionItemView::minimumSizeHint() const
{
int f = 2 * frameWidth();
// Make room for a vertical scrollbar in all cases, to avoid a horizontal one
int vsbExt = verticalScrollBar()->sizeHint().width();
int minw = topLevelWidget()->width() / 3;
int maxh = topLevelWidget()->height() / 2;
QSize sz( mBigBox->minimumSizeHint() );
sz.setWidth( QMAX( sz.width(), minw ) + f + vsbExt );
sz.setHeight( QMIN( sz.height(), maxh ) + f );
return sz;
}
void TransactionItemView::slotLayoutFirstItem()
{
/*
The below relies on some details in Qt's behaviour regarding deleting
objects. This slot is called from the destroyed signal of an item just
going away. That item is at that point still in the list of chilren, but
since the vtable is already gone, it will have type QObject. The first
one with both the right name and the right class therefor is what will
be the first item very shortly. That's the one we want to remove the
hline for.
*/
QObject *o = mBigBox->child( "TransactionItem", "KMail::TransactionItem" );
TransactionItem *ti = dynamic_cast<TransactionItem*>( o );
if ( ti ) {
ti->hideHLine();
}
}
// ----------------------------------------------------------------------------
TransactionItem::TransactionItem( QWidget* parent,
ProgressItem *item, bool first )
: QVBox( parent, "TransactionItem" ), mCancelButton( 0 ), mItem( item )
{
setSpacing( 2 );
setMargin( 2 );
setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );
mFrame = new QFrame( this );
mFrame->setFrameShape( QFrame::HLine );
mFrame->setFrameShadow( QFrame::Raised );
mFrame->show();
setStretchFactor( mFrame, 3 );
QHBox *h = new QHBox( this );
h->setSpacing( 5 );
mItemLabel = new QLabel( item->label(), h );
h->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );
if ( item->canBeCanceled() ) {
mCancelButton = new QPushButton( SmallIcon( "cancel" ), QString::null, h );
connect ( mCancelButton, SIGNAL( clicked() ),
this, SLOT( slotItemCanceled() ));
}
mProgress = new QProgressBar( 100, h );
mProgress->setProgress( item->progress() );
h = new QHBox( this );
h->setSpacing( 5 );
h->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );
mSSLLabel = new SSLLabel( h );
mSSLLabel->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );
mItemStatus = new QLabel( item->status(), h );
setCrypto( item->usesCrypto() );
if( first ) hideHLine();
}
TransactionItem::~TransactionItem()
{
}
void TransactionItem::hideHLine()
{
mFrame->hide();
}
void TransactionItem::setProgress( int progress )
{
mProgress->setProgress( progress );
}
void TransactionItem::setLabel( const QString& label )
{
mItemLabel->setText( label );
}
void TransactionItem::setStatus( const QString& status )
{
mItemStatus->setText( status );
}
void TransactionItem::setCrypto( bool on )
{
if (on)
mSSLLabel->setEncrypted( true );
else
mSSLLabel->setEncrypted( false );
mSSLLabel->setState( mSSLLabel->lastState() );
}
void TransactionItem::slotItemCanceled()
{
if ( mItem )
mItem->cancel();
}
void TransactionItem::addSubTransaction( ProgressItem* /*item*/ )
{
}
// ---------------------------------------------------------------------------
ProgressDialog::ProgressDialog( QWidget* alignWidget, KMMainWidget* mainWidget, const char* name )
: OverlayWidget( alignWidget, mainWidget, name )
{
setFrameStyle( QFrame::Panel | QFrame::Sunken ); // QFrame
setSpacing( 0 ); // QHBox
setMargin( 1 );
mScrollView = new TransactionItemView( this, "ProgressScrollView" );
QVBox* rightBox = new QVBox( this );
QToolButton* pbClose = new QToolButton( rightBox );
pbClose->setAutoRaise(true);
pbClose->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );
pbClose->setFixedSize( 16, 16 );
pbClose->setIconSet( KGlobal::iconLoader()->loadIconSet( "fileclose", KIcon::Small, 14 ) );
connect(pbClose, SIGNAL(clicked()), this, SLOT(close()));
QWidget* spacer = new QWidget( rightBox ); // don't let the close button take up all the height
rightBox->setStretchFactor( spacer, 100 );
/*
* Get the singleton ProgressManager item which will inform us of
* appearing and vanishing items.
*/
ProgressManager *pm = ProgressManager::instance();
connect ( pm, SIGNAL( progressItemAdded( ProgressItem* ) ),
this, SLOT( slotTransactionAdded( ProgressItem* ) ) );
connect ( pm, SIGNAL( progressItemCompleted( ProgressItem* ) ),
this, SLOT( slotTransactionCompleted( ProgressItem* ) ) );
connect ( pm, SIGNAL( progressItemProgress( ProgressItem*, unsigned int ) ),
this, SLOT( slotTransactionProgress( ProgressItem*, unsigned int ) ) );
connect ( pm, SIGNAL( progressItemStatus( ProgressItem*, const QString& ) ),
this, SLOT( slotTransactionStatus( ProgressItem*, const QString& ) ) );
connect ( pm, SIGNAL( progressItemLabel( ProgressItem*, const QString& ) ),
this, SLOT( slotTransactionLabel( ProgressItem*, const QString& ) ) );
connect ( pm, SIGNAL( progressItemUsesCrypto( ProgressItem*, bool ) ),
this, SLOT( slotTransactionUsesCrypto( ProgressItem*, bool ) ) );
}
void ProgressDialog::closeEvent( QCloseEvent* e )
{
e->accept();
hide();
}
/*
* Destructor
*/
ProgressDialog::~ProgressDialog()
{
// no need to delete child widgets.
}
void ProgressDialog::slotTransactionAdded( ProgressItem *item )
{
TransactionItem *parent = 0;
if ( item->parent() ) {
if ( mTransactionsToListviewItems.contains( item->parent() ) ) {
parent = mTransactionsToListviewItems[ item->parent() ];
parent->addSubTransaction( item );
}
} else {
TransactionItem *ti = mScrollView->addTransactionItem( item, mTransactionsToListviewItems.empty() );
if ( ti )
mTransactionsToListviewItems.replace( item, ti );
}
}
void ProgressDialog::slotTransactionCompleted( ProgressItem *item )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
mTransactionsToListviewItems.remove( item );
ti->setItemComplete();
QTimer::singleShot( 5000, ti, SLOT( deleteLater() ) );
// see the slot for comments as to why that works
connect ( ti, SIGNAL( destroyed() ),
mScrollView, SLOT( slotLayoutFirstItem() ) );
}
// This was the last item, hide.
if ( mTransactionsToListviewItems.empty() )
QTimer::singleShot( 5000, this, SLOT( slotHide() ) );
}
void ProgressDialog::slotTransactionCanceled( ProgressItem* )
{
}
void ProgressDialog::slotTransactionProgress( ProgressItem *item,
unsigned int progress )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setProgress( progress );
}
}
void ProgressDialog::slotTransactionStatus( ProgressItem *item,
const QString& status )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setStatus( status );
}
}
void ProgressDialog::slotTransactionLabel( ProgressItem *item,
const QString& label )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setLabel( label );
}
}
void ProgressDialog::slotTransactionUsesCrypto( ProgressItem *item,
bool value )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setCrypto( value );
}
}
void ProgressDialog::slotHide()
{
// check if a new item showed up since we started the timer. If not, hide
if ( mTransactionsToListviewItems.isEmpty() ) {
// [save a member var by simply getting the parent mainwidget from qwidget]
KMMainWidget* mainWidget = ::qt_cast<KMMainWidget *>( parentWidget() );
// not only hide(), but also toggling the statusbar icon
mainWidget->setProgressDialogVisible( false );
}
}
}
#include "progressdialog.moc"
<commit_msg>Add a tooltip for the cancel button.<commit_after>/** -*- c++ -*-
* progressdialog.cpp
*
* Copyright (c) 2004 Till Adam <adam@kde.org>,
* David Faure <faure@kde.org>
*
* 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; version 2 of the License
*
* 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.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of this program with any edition of
* the Qt library by Trolltech AS, Norway (or with modified versions
* of Qt that use the same license as Qt), and distribute linked
* combinations including the two. You must obey the GNU General
* Public License in all respects for all of the code used other than
* Qt. If you modify this file, you may extend this exception to
* your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from
* your version.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <qapplication.h>
#include <qlayout.h>
#include <qprogressbar.h>
#include <qtimer.h>
#include <qheader.h>
#include <qobject.h>
#include <qscrollview.h>
#include <qtoolbutton.h>
#include <qpushbutton.h>
#include <qvbox.h>
#include <qtooltip.h>
#include <klocale.h>
#include <kdialog.h>
#include <kstdguiitem.h>
#include <kiconloader.h>
#include <kdebug.h>
#include "progressdialog.h"
#include "progressmanager.h"
#include "ssllabel.h"
#include "kmmainwidget.h"
using KMail::ProgressItem;
using KMail::ProgressManager;
namespace KMail {
class TransactionItem;
TransactionItemView::TransactionItemView( QWidget * parent,
const char * name,
WFlags f )
: QScrollView( parent, name, f ) {
setFrameStyle( NoFrame );
mBigBox = new QVBox( viewport() );
mBigBox->setSpacing( 5 );
addChild( mBigBox );
setResizePolicy( QScrollView::AutoOneFit ); // Fit so that the box expands horizontally
}
TransactionItem* TransactionItemView::addTransactionItem( ProgressItem* item, bool first )
{
TransactionItem *ti = new TransactionItem( mBigBox, item, first );
ti->show();
return ti;
}
void TransactionItemView::resizeContents( int w, int h )
{
//kdDebug(5006) << k_funcinfo << w << "," << h << endl;
QScrollView::resizeContents( w, h );
// Tell the layout in the parent (progressdialog) that our size changed
updateGeometry();
// Resize the parent (progressdialog) - this works but resize horizontally too often
//parentWidget()->adjustSize();
QApplication::sendPostedEvents( 0, QEvent::ChildInserted );
QApplication::sendPostedEvents( 0, QEvent::LayoutHint );
QSize sz = parentWidget()->sizeHint();
int currentWidth = parentWidget()->width();
// Don't resize to sz.width() every time when it only reduces a little bit
if ( currentWidth < sz.width() || currentWidth > sz.width() + 100 )
currentWidth = sz.width();
parentWidget()->resize( currentWidth, sz.height() );
}
QSize TransactionItemView::sizeHint() const
{
return minimumSizeHint();
}
QSize TransactionItemView::minimumSizeHint() const
{
int f = 2 * frameWidth();
// Make room for a vertical scrollbar in all cases, to avoid a horizontal one
int vsbExt = verticalScrollBar()->sizeHint().width();
int minw = topLevelWidget()->width() / 3;
int maxh = topLevelWidget()->height() / 2;
QSize sz( mBigBox->minimumSizeHint() );
sz.setWidth( QMAX( sz.width(), minw ) + f + vsbExt );
sz.setHeight( QMIN( sz.height(), maxh ) + f );
return sz;
}
void TransactionItemView::slotLayoutFirstItem()
{
/*
The below relies on some details in Qt's behaviour regarding deleting
objects. This slot is called from the destroyed signal of an item just
going away. That item is at that point still in the list of chilren, but
since the vtable is already gone, it will have type QObject. The first
one with both the right name and the right class therefor is what will
be the first item very shortly. That's the one we want to remove the
hline for.
*/
QObject *o = mBigBox->child( "TransactionItem", "KMail::TransactionItem" );
TransactionItem *ti = dynamic_cast<TransactionItem*>( o );
if ( ti ) {
ti->hideHLine();
}
}
// ----------------------------------------------------------------------------
TransactionItem::TransactionItem( QWidget* parent,
ProgressItem *item, bool first )
: QVBox( parent, "TransactionItem" ), mCancelButton( 0 ), mItem( item )
{
setSpacing( 2 );
setMargin( 2 );
setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );
mFrame = new QFrame( this );
mFrame->setFrameShape( QFrame::HLine );
mFrame->setFrameShadow( QFrame::Raised );
mFrame->show();
setStretchFactor( mFrame, 3 );
QHBox *h = new QHBox( this );
h->setSpacing( 5 );
mItemLabel = new QLabel( item->label(), h );
h->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );
if ( item->canBeCanceled() ) {
mCancelButton = new QPushButton( SmallIcon( "cancel" ), QString::null, h );
QToolTip::add( mCancelButton, i18n("Cancel this operation.") );
connect ( mCancelButton, SIGNAL( clicked() ),
this, SLOT( slotItemCanceled() ));
}
mProgress = new QProgressBar( 100, h );
mProgress->setProgress( item->progress() );
h = new QHBox( this );
h->setSpacing( 5 );
h->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );
mSSLLabel = new SSLLabel( h );
mSSLLabel->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );
mItemStatus = new QLabel( item->status(), h );
setCrypto( item->usesCrypto() );
if( first ) hideHLine();
}
TransactionItem::~TransactionItem()
{
}
void TransactionItem::hideHLine()
{
mFrame->hide();
}
void TransactionItem::setProgress( int progress )
{
mProgress->setProgress( progress );
}
void TransactionItem::setLabel( const QString& label )
{
mItemLabel->setText( label );
}
void TransactionItem::setStatus( const QString& status )
{
mItemStatus->setText( status );
}
void TransactionItem::setCrypto( bool on )
{
if (on)
mSSLLabel->setEncrypted( true );
else
mSSLLabel->setEncrypted( false );
mSSLLabel->setState( mSSLLabel->lastState() );
}
void TransactionItem::slotItemCanceled()
{
if ( mItem )
mItem->cancel();
}
void TransactionItem::addSubTransaction( ProgressItem* /*item*/ )
{
}
// ---------------------------------------------------------------------------
ProgressDialog::ProgressDialog( QWidget* alignWidget, KMMainWidget* mainWidget, const char* name )
: OverlayWidget( alignWidget, mainWidget, name )
{
setFrameStyle( QFrame::Panel | QFrame::Sunken ); // QFrame
setSpacing( 0 ); // QHBox
setMargin( 1 );
mScrollView = new TransactionItemView( this, "ProgressScrollView" );
QVBox* rightBox = new QVBox( this );
QToolButton* pbClose = new QToolButton( rightBox );
pbClose->setAutoRaise(true);
pbClose->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );
pbClose->setFixedSize( 16, 16 );
pbClose->setIconSet( KGlobal::iconLoader()->loadIconSet( "fileclose", KIcon::Small, 14 ) );
connect(pbClose, SIGNAL(clicked()), this, SLOT(close()));
QWidget* spacer = new QWidget( rightBox ); // don't let the close button take up all the height
rightBox->setStretchFactor( spacer, 100 );
/*
* Get the singleton ProgressManager item which will inform us of
* appearing and vanishing items.
*/
ProgressManager *pm = ProgressManager::instance();
connect ( pm, SIGNAL( progressItemAdded( ProgressItem* ) ),
this, SLOT( slotTransactionAdded( ProgressItem* ) ) );
connect ( pm, SIGNAL( progressItemCompleted( ProgressItem* ) ),
this, SLOT( slotTransactionCompleted( ProgressItem* ) ) );
connect ( pm, SIGNAL( progressItemProgress( ProgressItem*, unsigned int ) ),
this, SLOT( slotTransactionProgress( ProgressItem*, unsigned int ) ) );
connect ( pm, SIGNAL( progressItemStatus( ProgressItem*, const QString& ) ),
this, SLOT( slotTransactionStatus( ProgressItem*, const QString& ) ) );
connect ( pm, SIGNAL( progressItemLabel( ProgressItem*, const QString& ) ),
this, SLOT( slotTransactionLabel( ProgressItem*, const QString& ) ) );
connect ( pm, SIGNAL( progressItemUsesCrypto( ProgressItem*, bool ) ),
this, SLOT( slotTransactionUsesCrypto( ProgressItem*, bool ) ) );
}
void ProgressDialog::closeEvent( QCloseEvent* e )
{
e->accept();
hide();
}
/*
* Destructor
*/
ProgressDialog::~ProgressDialog()
{
// no need to delete child widgets.
}
void ProgressDialog::slotTransactionAdded( ProgressItem *item )
{
TransactionItem *parent = 0;
if ( item->parent() ) {
if ( mTransactionsToListviewItems.contains( item->parent() ) ) {
parent = mTransactionsToListviewItems[ item->parent() ];
parent->addSubTransaction( item );
}
} else {
TransactionItem *ti = mScrollView->addTransactionItem( item, mTransactionsToListviewItems.empty() );
if ( ti )
mTransactionsToListviewItems.replace( item, ti );
}
}
void ProgressDialog::slotTransactionCompleted( ProgressItem *item )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
mTransactionsToListviewItems.remove( item );
ti->setItemComplete();
QTimer::singleShot( 5000, ti, SLOT( deleteLater() ) );
// see the slot for comments as to why that works
connect ( ti, SIGNAL( destroyed() ),
mScrollView, SLOT( slotLayoutFirstItem() ) );
}
// This was the last item, hide.
if ( mTransactionsToListviewItems.empty() )
QTimer::singleShot( 5000, this, SLOT( slotHide() ) );
}
void ProgressDialog::slotTransactionCanceled( ProgressItem* )
{
}
void ProgressDialog::slotTransactionProgress( ProgressItem *item,
unsigned int progress )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setProgress( progress );
}
}
void ProgressDialog::slotTransactionStatus( ProgressItem *item,
const QString& status )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setStatus( status );
}
}
void ProgressDialog::slotTransactionLabel( ProgressItem *item,
const QString& label )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setLabel( label );
}
}
void ProgressDialog::slotTransactionUsesCrypto( ProgressItem *item,
bool value )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setCrypto( value );
}
}
void ProgressDialog::slotHide()
{
// check if a new item showed up since we started the timer. If not, hide
if ( mTransactionsToListviewItems.isEmpty() ) {
// [save a member var by simply getting the parent mainwidget from qwidget]
KMMainWidget* mainWidget = ::qt_cast<KMMainWidget *>( parentWidget() );
// not only hide(), but also toggling the statusbar icon
mainWidget->setProgressDialogVisible( false );
}
}
}
#include "progressdialog.moc"
<|endoftext|> |
<commit_before>/***************************************************************************
filter_ldif.cxx - description
-------------------
begin : Fri Dec 1, 2000
copyright : (C) 2000 by Oliver Strutynski
email : olistrut@gmx.de
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include <iostream>
#include <stdlib.h>
#include <qdir.h>
#include <kfiledialog.h>
#include <klocale.h>
#include "filter_ldif.hxx"
filter_ldif::filter_ldif() : filter(i18n("Import Netscape LDIF Address Book 1(.LDIF)"),"Oliver Strutynski")
{}
filter_ldif::~filter_ldif()
{}
void filter_ldif::import(filterInfo *info) {
QWidget *parent=info->parent();
QString filename = KFileDialog::getOpenFileName( QDir::homeDirPath(),
"*.ldif *.LDIF *.Ldif", parent);
if (filename.isEmpty()) {
info->alert(name(),i18n("No Addressbook chosen"));
return;
}
QString from( i18n("Source: ") + "\t" + filename );
QString to( i18n("Destination: ") + "\t" + i18n("the KAddressBook") );
info->from(from);
info->to(to);
info->current(i18n("Currently converting .LDIF address file to Kab"));
convert(filename, info);
info->current(100.0);
info->overall(100.0);
info->current(i18n("Finished converting .LDIF address file to Kab"));
}
bool filter_ldif::convert(const QString &filename, filterInfo *info) {
if (!kabStart(info))
return false;
QString caption( i18n("Import Netscape LDIF Personal Addressbook (.LDIF)") );
QFile f(filename);
if ( !f.open(IO_ReadOnly) ) {
QString msg = i18n("Can't open '%1' for reading").arg(filename);
info->alert(caption,msg);
return false;
}
QString empty;
QString givenName, email, title, firstName, lastName, nickName,
street, locality, state, zipCode, country, organization,
department, phone, fax, mobile, homepage, comment;
// Initializing code table for base64 decoding
initCodeTable();
QTextStream t( &f );
QString s, fieldname;
// We need this for calculating progress
uint fileSize = f.size();
uint bytesProcessed = 0;
// Set to true if data currently read is part of
// a list of names. Lists will be ignored.
bool isGroup = false;
while ( !t.eof() ) {
s = t.readLine();
bytesProcessed += s.length();
// update progress information
info->current((float)bytesProcessed/fileSize*100);
info->overall((float)bytesProcessed/fileSize*100);
if (s.isEmpty()) {
// Newline: Write data
if (!isGroup) {
kabAddress( info, i18n("Netscape Addressbook"),
givenName, email, title, firstName, empty, lastName, nickName,
street, locality, state, zipCode, country, organization,
department, empty, empty, phone, fax, mobile, empty, homepage,
empty, comment, empty);
givenName = email = title = firstName = lastName = nickName =
street = locality = state = zipCode = country = organization =
department = phone = fax = mobile = homepage = comment = "";
} else {
info->log(i18n("Warning: List data is being ignored."));
}
isGroup = false;
continue;
}
int position = s.find("::");
if (position != -1) {
// String is BASE64 encoded
fieldname = s.left(position);
s = decodeBase64(s.mid(position+3, s.length()-position-2));
} else {
position = s.find(":");
fieldname = s.left(position);
// Convert Utf8 string to unicode so special characters are preserved
// We need this since we are reading normal strings from the file
// which are not converted automatically
s = QString::fromUtf8(s.mid(position+2, s.length()-position-2).latin1());
}
if (s.stripWhiteSpace().isEmpty())
continue;
if (fieldname == "givenname")
{ firstName = s; continue; }
if (fieldname == "xmozillanickname")
{ nickName = s; continue; }
if (fieldname == "sn")
{ lastName = s; continue; }
if (fieldname == "mail")
{ email = s; continue; }
if (fieldname == "title")
{ title = s; continue; }
if (fieldname == "cn")
{ givenName = s; continue; }
if (fieldname == "o")
{ organization = s; continue; }
if (fieldname == "description")
{ comment = s; continue; }
if (fieldname == "homeurl")
{ homepage = s; continue; }
if (fieldname == "homephone" || fieldname == "telephonenumber") {
if (!phone.isEmpty()) info->log(i18n("Discarding Phone Number %1").arg(s));
phone = s;
continue;
}
if (fieldname == "postalcode")
{ zipCode = s; continue; }
if (fieldname == "facsimiletelephonenumber")
{ fax = s; continue; }
if (fieldname == "streetaddress")
{ street = s; continue; }
if (fieldname == "locality")
{ locality = s; continue; }
if (fieldname == "countryname")
{ country = s; continue; }
if (fieldname == "cellphone")
{ mobile = s; continue; }
if (fieldname == "st")
{ state = s; continue; }
if (fieldname == "ou")
{ department = s; continue; }
if (fieldname == "objectclass" && s == "groupOfNames")
isGroup = true;
} /* while !eof(f) */
f.close();
kabStop(info);
return true;
}
/*
* Decodes a BASE-64 encoded stream to recover the original data and compacts white space.
* Code heavily based on java code written by Kevin Kelley (kelley@ruralnet.net)
* published unter the GNU Library Public License
*/
QString filter_ldif::decodeBase64(QString input)
{
QCString result;
int tempLen = input.length();
for(unsigned int i=0; i<input.length(); i++) {
if(codes[ input[i].latin1() ] < 0) {
// std::cout << "Invalid character in base64 string: " <<
// input[i].latin1() << std::endl;
--tempLen; // ignore non-valid chars and padding
}
}
// calculate required length:
// -- 3 bytes for every 4 valid base64 chars
// -- plus 2 bytes if there are 3 extra base64 chars,
// or plus 1 byte if there are 2 extra.
int len = (tempLen / 4) * 3;
if ((tempLen % 4) == 3) len += 2;
if ((tempLen % 4) == 2) len += 1;
int shift = 0; // # of excess bits stored in accum
int accum = 0; // excess bits
// we now loop over through the entire string
for (unsigned int i=0; i<input.length(); i++) {
int value = codes[ input[i].latin1() ];
if ( value >= 0 ) { // skip over non-code
accum <<= 6; // bits shift up by 6 each time thru
shift += 6; // loop, with new bits being put in
accum |= value; // at the bottom.
if ( shift >= 8 ) { // whenever there are 8 or more shifted in,
shift -= 8; // write them out (from the top, leaving any
// excess at the bottom for next iteration.
result += (char) ((accum >> shift) & 0xff);
}
}
}
// Remove any linefeeds, tabs and multiple space from decoded string and
// convert to unicode.
return QString::fromUtf8(result).simplifyWhiteSpace();
}
/* Initialize lookup */
void filter_ldif::initCodeTable() {
// chars for 0..63
for (int i=0; i<256; i++) codes[i] = -1;
for (int i = 'A'; i <= 'Z'; i++) codes[i] = (int)(i - 'A');
for (int i = 'a'; i <= 'z'; i++) codes[i] = (int)(26 + i - 'a');
for (int i = '0'; i <= '9'; i++) codes[i] = (int)(52 + i - '0');
codes['+'] = 62;
codes['/'] = 63;
}
<commit_msg>Don't be picky when the server doesn't return lowercase fiednames<commit_after>/***************************************************************************
filter_ldif.cxx - description
-------------------
begin : Fri Dec 1, 2000
copyright : (C) 2000 by Oliver Strutynski
email : olistrut@gmx.de
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include <iostream>
#include <stdlib.h>
#include <qdir.h>
#include <kfiledialog.h>
#include <klocale.h>
#include "filter_ldif.hxx"
filter_ldif::filter_ldif() : filter(i18n("Import Netscape LDIF Address Book 1(.LDIF)"),"Oliver Strutynski")
{}
filter_ldif::~filter_ldif()
{}
void filter_ldif::import(filterInfo *info) {
QWidget *parent=info->parent();
QString filename = KFileDialog::getOpenFileName( QDir::homeDirPath(),
"*.ldif *.LDIF *.Ldif", parent);
if (filename.isEmpty()) {
info->alert(name(),i18n("No Addressbook chosen"));
return;
}
QString from( i18n("Source: ") + "\t" + filename );
QString to( i18n("Destination: ") + "\t" + i18n("the KAddressBook") );
info->from(from);
info->to(to);
info->current(i18n("Currently converting .LDIF address file to Kab"));
convert(filename, info);
info->current(100.0);
info->overall(100.0);
info->current(i18n("Finished converting .LDIF address file to Kab"));
}
bool filter_ldif::convert(const QString &filename, filterInfo *info) {
if (!kabStart(info))
return false;
QString caption( i18n("Import Netscape LDIF Personal Addressbook (.LDIF)") );
QFile f(filename);
if ( !f.open(IO_ReadOnly) ) {
QString msg = i18n("Can't open '%1' for reading").arg(filename);
info->alert(caption,msg);
return false;
}
QString empty;
QString givenName, email, title, firstName, lastName, nickName,
street, locality, state, zipCode, country, organization,
department, phone, fax, mobile, homepage, comment;
// Initializing code table for base64 decoding
initCodeTable();
QTextStream t( &f );
QString s, fieldname;
// We need this for calculating progress
uint fileSize = f.size();
uint bytesProcessed = 0;
// Set to true if data currently read is part of
// a list of names. Lists will be ignored.
bool isGroup = false;
while ( !t.eof() ) {
s = t.readLine();
bytesProcessed += s.length();
// update progress information
info->current((float)bytesProcessed/fileSize*100);
info->overall((float)bytesProcessed/fileSize*100);
if (s.isEmpty()) {
// Newline: Write data
if (!isGroup) {
kabAddress( info, i18n("Netscape Addressbook"),
givenName, email, title, firstName, empty, lastName, nickName,
street, locality, state, zipCode, country, organization,
department, empty, empty, phone, fax, mobile, empty, homepage,
empty, comment, empty);
givenName = email = title = firstName = lastName = nickName =
street = locality = state = zipCode = country = organization =
department = phone = fax = mobile = homepage = comment = "";
} else {
info->log(i18n("Warning: List data is being ignored."));
}
isGroup = false;
continue;
}
int position = s.find("::");
if (position != -1) {
// String is BASE64 encoded
fieldname = s.left(position).lower();
s = decodeBase64(s.mid(position+3, s.length()-position-2));
} else {
position = s.find(":");
fieldname = s.left(position).lower();
// Convert Utf8 string to unicode so special characters are preserved
// We need this since we are reading normal strings from the file
// which are not converted automatically
s = QString::fromUtf8(s.mid(position+2, s.length()-position-2).latin1());
}
if (s.stripWhiteSpace().isEmpty())
continue;
if (fieldname == "givenname")
{ firstName = s; continue; }
if (fieldname == "xmozillanickname")
{ nickName = s; continue; }
if (fieldname == "sn")
{ lastName = s; continue; }
if (fieldname == "mail")
{ email = s; continue; }
if (fieldname == "title")
{ title = s; continue; }
if (fieldname == "cn")
{ givenName = s; continue; }
if (fieldname == "o")
{ organization = s; continue; }
if (fieldname == "description")
{ comment = s; continue; }
if (fieldname == "homeurl")
{ homepage = s; continue; }
if (fieldname == "homephone" || fieldname == "telephonenumber") {
if (!phone.isEmpty()) info->log(i18n("Discarding Phone Number %1").arg(s));
phone = s;
continue;
}
if (fieldname == "postalcode")
{ zipCode = s; continue; }
if (fieldname == "facsimiletelephonenumber")
{ fax = s; continue; }
if (fieldname == "streetaddress")
{ street = s; continue; }
if (fieldname == "locality")
{ locality = s; continue; }
if (fieldname == "countryname")
{ country = s; continue; }
if (fieldname == "cellphone")
{ mobile = s; continue; }
if (fieldname == "st")
{ state = s; continue; }
if (fieldname == "ou")
{ department = s; continue; }
if (fieldname == "objectclass" && s == "groupOfNames")
isGroup = true;
} /* while !eof(f) */
f.close();
kabStop(info);
return true;
}
/*
* Decodes a BASE-64 encoded stream to recover the original data and compacts white space.
* Code heavily based on java code written by Kevin Kelley (kelley@ruralnet.net)
* published unter the GNU Library Public License
*/
QString filter_ldif::decodeBase64(QString input)
{
QCString result;
int tempLen = input.length();
for(unsigned int i=0; i<input.length(); i++) {
if(codes[ input[i].latin1() ] < 0) {
// std::cout << "Invalid character in base64 string: " <<
// input[i].latin1() << std::endl;
--tempLen; // ignore non-valid chars and padding
}
}
// calculate required length:
// -- 3 bytes for every 4 valid base64 chars
// -- plus 2 bytes if there are 3 extra base64 chars,
// or plus 1 byte if there are 2 extra.
int len = (tempLen / 4) * 3;
if ((tempLen % 4) == 3) len += 2;
if ((tempLen % 4) == 2) len += 1;
int shift = 0; // # of excess bits stored in accum
int accum = 0; // excess bits
// we now loop over through the entire string
for (unsigned int i=0; i<input.length(); i++) {
int value = codes[ input[i].latin1() ];
if ( value >= 0 ) { // skip over non-code
accum <<= 6; // bits shift up by 6 each time thru
shift += 6; // loop, with new bits being put in
accum |= value; // at the bottom.
if ( shift >= 8 ) { // whenever there are 8 or more shifted in,
shift -= 8; // write them out (from the top, leaving any
// excess at the bottom for next iteration.
result += (char) ((accum >> shift) & 0xff);
}
}
}
// Remove any linefeeds, tabs and multiple space from decoded string and
// convert to unicode.
return QString::fromUtf8(result).simplifyWhiteSpace();
}
/* Initialize lookup */
void filter_ldif::initCodeTable() {
// chars for 0..63
for (int i=0; i<256; i++) codes[i] = -1;
for (int i = 'A'; i <= 'Z'; i++) codes[i] = (int)(i - 'A');
for (int i = 'a'; i <= 'z'; i++) codes[i] = (int)(26 + i - 'a');
for (int i = '0'; i <= '9'; i++) codes[i] = (int)(52 + i - '0');
codes['+'] = 62;
codes['/'] = 63;
}
<|endoftext|> |
<commit_before>/*
This file is part of KOrganizer.
Copyright © 2007 Loïc Corbasson <loic.corbasson@gmail.com>
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <KApplication>
#include <KAboutData>
#include <KMessageBox>
#include <KCmdLineArgs>
#include <KLocale>
#include <KGlobal>
#include <KDebug>
#include "theme.h"
int main ( int argc, char **argv )
{
KAboutData aboutData("korganizer",
0,
ki18n("KOrganizer Theming Stub"),
"0.001",
ki18n("DO NOT USE - Stub doing various things with KOrganizer themes"),
KAboutData::License_GPL,
ki18n("© 2007 Loïc Corbasson"),
ki18n(""),
"http://blog.loic.corbasson.fr/",
"loic.corbasson@gmail.com");
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineOptions options;
options.add("+[url]", ki18n("Theme to use"));
KCmdLineArgs::addCmdLineOptions(options);
KApplication app( false ); // no GUI
KCmdLineArgs* args = KCmdLineArgs::parsedArgs();
if (args->count() > 0) {
for (int i = 0; i < args->count(); ++i) {
KOrg::Theme::useThemeFrom( args->url(i) );
}
}
args->clear();
}
<commit_msg>I don't think many translators will find a different translation for nothing<commit_after>/*
This file is part of KOrganizer.
Copyright © 2007 Loïc Corbasson <loic.corbasson@gmail.com>
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <KApplication>
#include <KAboutData>
#include <KMessageBox>
#include <KCmdLineArgs>
#include <KLocale>
#include <KGlobal>
#include <KDebug>
#include "theme.h"
int main ( int argc, char **argv )
{
KAboutData aboutData("korganizer",
0,
ki18n("KOrganizer Theming Stub"),
"0.001",
ki18n("DO NOT USE - Stub doing various things with KOrganizer themes"),
KAboutData::License_GPL,
ki18n("© 2007 Loïc Corbasson"),
"",
"http://blog.loic.corbasson.fr/",
"loic.corbasson@gmail.com");
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineOptions options;
options.add("+[url]", ki18n("Theme to use"));
KCmdLineArgs::addCmdLineOptions(options);
KApplication app( false ); // no GUI
KCmdLineArgs* args = KCmdLineArgs::parsedArgs();
if (args->count() > 0) {
for (int i = 0; i < args->count(); ++i) {
KOrg::Theme::useThemeFrom( args->url(i) );
}
}
args->clear();
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2004, Mart Kelder (mart.kde@hccnet.nl)
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "keditlistboxman.h"
#include <kconfig.h>
#include <kdebug.h>
#include <qmap.h>
#include <qlistview.h>
#include <qstring.h>
KEditListBoxManager::KEditListBoxManager( QWidget *parent, const char *name,
bool checkAtEntering, KEditListBox::Buttons buttons )
: KEditListBox( parent, name, checkAtEntering, buttons ),
_config( 0 ),
_groupName( 0 ),
_subGroupName( 0 ),
_prevCount( 0 )
{
init();
}
KEditListBoxManager::KEditListBoxManager( const QString& title, QWidget *parent,
const char *name, bool checkAtEntering,
KEditListBox::Buttons buttons)
: KEditListBox( title, parent, name, checkAtEntering, buttons ),
_config( 0 ),
_groupName( 0 ),
_subGroupName( 0 ),
_prevCount( 0 )
{
init();
}
KEditListBoxManager::KEditListBoxManager( const QString& title,
const KEditListBox::CustomEditor &customEditor,
QWidget *parent, const char *name,
bool checkAtEntering, KEditListBox::Buttons buttons )
: KEditListBox( title, customEditor, parent, name, checkAtEntering, buttons ),
_config( 0 ),
_groupName( 0 ),
_subGroupName( 0 ),
_prevCount( 0 )
{
init();
}
KEditListBoxManager::~KEditListBoxManager()
{
delete _groupName;
}
void KEditListBoxManager::setConfig( KConfig* config )
{
_config = config;
if( _groupName )
readNames();
}
void KEditListBoxManager::setGroupName( const QString& name )
{
if( _groupName )
*_groupName = name;
else
_groupName = new QString( name );
if( _config )
readNames();
}
void KEditListBoxManager::setSubGroupName( const QString& name )
{
if( _subGroupName )
*_subGroupName = name;
else
_subGroupName = new QString( name );
if( _config && _groupName )
readNames();
}
void KEditListBoxManager::init()
{
connect( this, SIGNAL( changed() ), this, SLOT( slotChanged() ) );
connect( this, SIGNAL( added( const QString& ) ), this, SLOT( slotAdded( const QString& ) ) );
connect( this, SIGNAL( removed( const QString& ) ), this, SLOT( slotRemoved( const QString& ) ) );
connect( this->listView(), SIGNAL( doubleClicked( const QModelIndex&) ), this, SLOT( slotActivated( const QModelIndex& ) ) );
connect( this->listView(), SIGNAL( returnPressed( const QModelIndex& ) ), this, SLOT( slotActivated( const QModelIndex& ) ) );
}
void KEditListBoxManager::readNames()
{
int number = 0;
this->clear();
while( _config->hasGroup( _groupName->arg( number ) ) )
{
_config->setGroup( _groupName->arg( number ) );
this->insertItem( _config->readEntry( "name", QString() ) );
++number;
}
_prevCount = this->count();
}
void KEditListBoxManager::slotChanged()
{
/* Three thing could be hapened:
* 1. the text is changed;
* 2. the item has moved up;
* 3. the item has moved down.
*/
//_prevCount is invariant under all of these operation
//if _prevCount is changed, is wasn't one of those operations.
if( _prevCount != this->count() )
return;
if( !_config || !_groupName )
return;
//First check if the item was moved up
_config->setGroup( _groupName->arg( this->currentItem() ) );
if( this->currentItem() > 0 && this->text( this->currentItem() - 1 ) == _config->readEntry( "name", QString() ) )
changeItem( this->currentItem() - 1, this->currentItem() ); //moved down
else if( this->currentItem() < this->count() - 1 &&
this->text( this->currentItem() + 1 ) == _config->readEntry( "name", QString() ) )
changeItem( this->currentItem(), this->currentItem() + 1 ); //moved up
else if( this->currentText() != _config->readEntry( "name", QString() ) )
changedText(); //changed
}
void KEditListBoxManager::slotAdded( const QString& name )
{
//Update _prevCount
_prevCount = this->count();
if( !_config || !_groupName )
return;
int number = 0;
while( _config->hasGroup( _groupName->arg( number ) ) )
++number;
_config->setGroup( _groupName->arg( number ) );
_config->writeEntry( "name", name );
emit setDefaults( name, number, _config );
}
void KEditListBoxManager::slotRemoved( const QString& name )
{
//Update prevCount
_prevCount = this->count();
if( !_config || !_groupName )
return;
//First: search the item number.
int number = 0;
int subnumber = 0;
while( true )
{
if( !_config->hasGroup( _groupName->arg( number ) ) )
{
number = -1; //not found
break;
}
_config->setGroup( _groupName->arg( number ) );
if( name == _config->readEntry( "name", QString() ) )
break; //found
++number; //Try next group
}
if( number < 0 ) //failure
return; //do nothing
_config->deleteGroup( _groupName->arg( number ), KConfig::NLS );
emit elementDeleted( number );
while( _subGroupName && _config->hasGroup( _subGroupName->arg( number ).arg( subnumber ) ) )
{
_config->deleteGroup( _subGroupName->arg( number ).arg( subnumber ) );
++subnumber;
}
//rotate groups
while( _config->hasGroup( _groupName->arg( number + 1 ) ) )
{
moveItem( number + 1, number );
++number;
}
}
void KEditListBoxManager::slotActivated( const QModelIndex& item )
{
emit activated( item );
}
void KEditListBoxManager::moveItem( int src, int dest )
{
QMap<QString, QString> *srcList = new QMap<QString, QString >;
QMap<QString, QString>::iterator it;
int subnumber = 0;
*srcList = _config->entryMap( _groupName->arg( src ) );
_config->deleteGroup( _groupName->arg( src ) );
_config->setGroup( _groupName->arg( dest ) );
for( it = srcList->begin(); it != srcList->end(); ++it )
_config->writeEntry( it.key(), it.value() );
while( _subGroupName && _config->hasGroup( _subGroupName->arg( src ).arg( subnumber ) ) )
{
_config->deleteGroup( _subGroupName->arg( dest ).arg( subnumber ) );
_config->setGroup( _subGroupName->arg( dest ).arg( subnumber ) );
for( it = srcList->begin(); it != srcList->end(); ++it )
_config->writeEntry( it.key(), it.value() );
++subnumber;
}
emit elementsSwapped( src, dest );
delete srcList;
}
void KEditListBoxManager::changeItem( int first, int last )
{
QMap<QString, QString> *firstList = new QMap<QString, QString >;
QMap<QString, QString> *lastList = new QMap<QString, QString >;
QMap<QString, QString>::iterator it;
int subnumber = 0;
*firstList = _config->entryMap( _groupName->arg( first ) );
*lastList = _config->entryMap( _groupName->arg( last ) );
_config->deleteGroup( _groupName->arg( first ) );
_config->deleteGroup( _groupName->arg( last ) );
_config->setGroup( _groupName->arg( last ) );
for( it = firstList->begin(); it != firstList->end(); ++it )
_config->writeEntry( it.key(), it.value() );
_config->setGroup( _groupName->arg( first ) );
for( it = lastList->begin(); it != lastList->end(); ++it )
_config->writeEntry( it.key(), it.value() );
while( _subGroupName && (
_config->hasGroup( _subGroupName->arg( first ).arg( subnumber ) ) ||
_config->hasGroup( _subGroupName->arg( last ).arg( subnumber ) ) ) )
{
*firstList = _config->entryMap( _subGroupName->arg( first ).arg( subnumber ) );
*lastList = _config->entryMap( _subGroupName->arg( last ).arg( subnumber ) );
_config->deleteGroup( _subGroupName->arg( first ).arg( subnumber ) );
_config->deleteGroup( _subGroupName->arg( last ).arg( subnumber ) );
_config->setGroup( _subGroupName->arg( last ).arg( subnumber ) );
for( it = firstList->begin(); it != firstList->end(); ++it )
_config->writeEntry( it.key(), it.value() );
_config->setGroup( _subGroupName->arg( first ).arg( subnumber ) );
for( it = lastList->begin(); it != lastList->end(); ++it )
_config->writeEntry( it.key(), it.value() );
++subnumber;
}
emit elementsSwapped( first, last );
delete firstList;
delete lastList;
}
void KEditListBoxManager::changedText()
{
_config->setGroup( _groupName->arg( this->currentItem() ) );
_config->writeEntry( "name", this->currentText() );
}
#include "keditlistboxman.moc"
<commit_msg>fix crash (CID 1357)<commit_after>/*
* Copyright (C) 2004, Mart Kelder (mart.kde@hccnet.nl)
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "keditlistboxman.h"
#include <kconfig.h>
#include <kdebug.h>
#include <qmap.h>
#include <qlistview.h>
#include <qstring.h>
KEditListBoxManager::KEditListBoxManager( QWidget *parent, const char *name,
bool checkAtEntering, KEditListBox::Buttons buttons )
: KEditListBox( parent, name, checkAtEntering, buttons ),
_config( 0 ),
_groupName( 0 ),
_subGroupName( 0 ),
_prevCount( 0 )
{
init();
}
KEditListBoxManager::KEditListBoxManager( const QString& title, QWidget *parent,
const char *name, bool checkAtEntering,
KEditListBox::Buttons buttons)
: KEditListBox( title, parent, name, checkAtEntering, buttons ),
_config( 0 ),
_groupName( 0 ),
_subGroupName( 0 ),
_prevCount( 0 )
{
init();
}
KEditListBoxManager::KEditListBoxManager( const QString& title,
const KEditListBox::CustomEditor &customEditor,
QWidget *parent, const char *name,
bool checkAtEntering, KEditListBox::Buttons buttons )
: KEditListBox( title, customEditor, parent, name, checkAtEntering, buttons ),
_config( 0 ),
_groupName( 0 ),
_subGroupName( 0 ),
_prevCount( 0 )
{
init();
}
KEditListBoxManager::~KEditListBoxManager()
{
delete _groupName;
}
void KEditListBoxManager::setConfig( KConfig* config )
{
_config = config;
if( _groupName )
readNames();
}
void KEditListBoxManager::setGroupName( const QString& name )
{
if( _groupName )
*_groupName = name;
else
_groupName = new QString( name );
if( _config )
readNames();
}
void KEditListBoxManager::setSubGroupName( const QString& name )
{
if( _subGroupName )
*_subGroupName = name;
else
_subGroupName = new QString( name );
if( _config && _groupName )
readNames();
}
void KEditListBoxManager::init()
{
connect( this, SIGNAL( changed() ), this, SLOT( slotChanged() ) );
connect( this, SIGNAL( added( const QString& ) ), this, SLOT( slotAdded( const QString& ) ) );
connect( this, SIGNAL( removed( const QString& ) ), this, SLOT( slotRemoved( const QString& ) ) );
connect( this->listView(), SIGNAL( doubleClicked( const QModelIndex&) ), this, SLOT( slotActivated( const QModelIndex& ) ) );
connect( this->listView(), SIGNAL( returnPressed( const QModelIndex& ) ), this, SLOT( slotActivated( const QModelIndex& ) ) );
}
void KEditListBoxManager::readNames()
{
int number = 0;
this->clear();
while( _config->hasGroup( _groupName->arg( number ) ) )
{
_config->setGroup( _groupName->arg( number ) );
this->insertItem( _config->readEntry( "name", QString() ) );
++number;
}
_prevCount = this->count();
}
void KEditListBoxManager::slotChanged()
{
/* Three thing could be hapened:
* 1. the text is changed;
* 2. the item has moved up;
* 3. the item has moved down.
*/
//_prevCount is invariant under all of these operation
//if _prevCount is changed, is wasn't one of those operations.
if( _prevCount != this->count() )
return;
if( !_config || !_groupName )
return;
//First check if the item was moved up
_config->setGroup( _groupName->arg( this->currentItem() ) );
int ci = currentItem();
if( ci > 0 && this->text( ci - 1 ) == _config->readEntry( "name", QString() ) )
changeItem( ci - 1, ci ); //moved down
else if( ci >= 0 && ci < this->count() - 1 &&
this->text( ci + 1 ) == _config->readEntry( "name", QString() ) )
changeItem( ci, ci + 1 ); //moved up
else if( this->currentText() != _config->readEntry( "name", QString() ) )
changedText(); //changed
}
void KEditListBoxManager::slotAdded( const QString& name )
{
//Update _prevCount
_prevCount = this->count();
if( !_config || !_groupName )
return;
int number = 0;
while( _config->hasGroup( _groupName->arg( number ) ) )
++number;
_config->setGroup( _groupName->arg( number ) );
_config->writeEntry( "name", name );
emit setDefaults( name, number, _config );
}
void KEditListBoxManager::slotRemoved( const QString& name )
{
//Update prevCount
_prevCount = this->count();
if( !_config || !_groupName )
return;
//First: search the item number.
int number = 0;
int subnumber = 0;
while( true )
{
if( !_config->hasGroup( _groupName->arg( number ) ) )
{
number = -1; //not found
break;
}
_config->setGroup( _groupName->arg( number ) );
if( name == _config->readEntry( "name", QString() ) )
break; //found
++number; //Try next group
}
if( number < 0 ) //failure
return; //do nothing
_config->deleteGroup( _groupName->arg( number ), KConfig::NLS );
emit elementDeleted( number );
while( _subGroupName && _config->hasGroup( _subGroupName->arg( number ).arg( subnumber ) ) )
{
_config->deleteGroup( _subGroupName->arg( number ).arg( subnumber ) );
++subnumber;
}
//rotate groups
while( _config->hasGroup( _groupName->arg( number + 1 ) ) )
{
moveItem( number + 1, number );
++number;
}
}
void KEditListBoxManager::slotActivated( const QModelIndex& item )
{
emit activated( item );
}
void KEditListBoxManager::moveItem( int src, int dest )
{
QMap<QString, QString> *srcList = new QMap<QString, QString >;
QMap<QString, QString>::iterator it;
int subnumber = 0;
*srcList = _config->entryMap( _groupName->arg( src ) );
_config->deleteGroup( _groupName->arg( src ) );
_config->setGroup( _groupName->arg( dest ) );
for( it = srcList->begin(); it != srcList->end(); ++it )
_config->writeEntry( it.key(), it.value() );
while( _subGroupName && _config->hasGroup( _subGroupName->arg( src ).arg( subnumber ) ) )
{
_config->deleteGroup( _subGroupName->arg( dest ).arg( subnumber ) );
_config->setGroup( _subGroupName->arg( dest ).arg( subnumber ) );
for( it = srcList->begin(); it != srcList->end(); ++it )
_config->writeEntry( it.key(), it.value() );
++subnumber;
}
emit elementsSwapped( src, dest );
delete srcList;
}
void KEditListBoxManager::changeItem( int first, int last )
{
QMap<QString, QString> *firstList = new QMap<QString, QString >;
QMap<QString, QString> *lastList = new QMap<QString, QString >;
QMap<QString, QString>::iterator it;
int subnumber = 0;
*firstList = _config->entryMap( _groupName->arg( first ) );
*lastList = _config->entryMap( _groupName->arg( last ) );
_config->deleteGroup( _groupName->arg( first ) );
_config->deleteGroup( _groupName->arg( last ) );
_config->setGroup( _groupName->arg( last ) );
for( it = firstList->begin(); it != firstList->end(); ++it )
_config->writeEntry( it.key(), it.value() );
_config->setGroup( _groupName->arg( first ) );
for( it = lastList->begin(); it != lastList->end(); ++it )
_config->writeEntry( it.key(), it.value() );
while( _subGroupName && (
_config->hasGroup( _subGroupName->arg( first ).arg( subnumber ) ) ||
_config->hasGroup( _subGroupName->arg( last ).arg( subnumber ) ) ) )
{
*firstList = _config->entryMap( _subGroupName->arg( first ).arg( subnumber ) );
*lastList = _config->entryMap( _subGroupName->arg( last ).arg( subnumber ) );
_config->deleteGroup( _subGroupName->arg( first ).arg( subnumber ) );
_config->deleteGroup( _subGroupName->arg( last ).arg( subnumber ) );
_config->setGroup( _subGroupName->arg( last ).arg( subnumber ) );
for( it = firstList->begin(); it != firstList->end(); ++it )
_config->writeEntry( it.key(), it.value() );
_config->setGroup( _subGroupName->arg( first ).arg( subnumber ) );
for( it = lastList->begin(); it != lastList->end(); ++it )
_config->writeEntry( it.key(), it.value() );
++subnumber;
}
emit elementsSwapped( first, last );
delete firstList;
delete lastList;
}
void KEditListBoxManager::changedText()
{
_config->setGroup( _groupName->arg( this->currentItem() ) );
_config->writeEntry( "name", this->currentText() );
}
#include "keditlistboxman.moc"
<|endoftext|> |
<commit_before>/*
* CvTypesIo.hpp
*
* Created on: May 20, 2013
* Author: link
*/
#ifndef CVTYPESIO_HPP_
#define CVTYPESIO_HPP_
#include <opencv2/core/core.hpp>
void operator>>(const cv::FileNode &node, cv::Size &size);
void operator>>(const cv::FileNode &node,
cv::TermCriteria &termCrit);
template<class T>
void operator>>(const cv::FileNode &node,
cv::Point_<T> &point){
node[0]>>point.x;
node[1]>>point.y;
}
cv::FileStorage &operator<<(cv::FileStorage &fs,
const cv::TermCriteria &termCrit);
#endif /* CVTYPESIO_HPP_ */
<commit_msg>Added doxygen dosumentation to CvTypesIo<commit_after>/*
* CvTypesIo.hpp
*
* Created on: May 20, 2013
* Author: link
*/
#ifndef CVTYPESIO_HPP_
#define CVTYPESIO_HPP_
#include <opencv2/core/core.hpp>
/// Operator enabling to use cv::Size with OpenCV persistence
/// functionality (reading)
/**
* Function provides a way to read a cv::Size value from
* OpenCV text file.
* @param[in] node - file node in which the size value is stored
* @param[out] size - value read
*/
void operator>>(const cv::FileNode &node, cv::Size &size);
/// Operator enabling to use cv::TermCriteria with OpenCV persistence
/// functionality (reading)
/**
* Function provides a way to read a cv::TermCriteria value from
* OpenCV text file.
* @param[in] node - file node in which the termCrit value is stored
* @param[out] termCrit - value read
*/
void operator>>(const cv::FileNode &node,
cv::TermCriteria &termCrit);
/// Operator enabling to use cv::Point_<T> with OpenCV persistence
/// functionality (reading)
/**
* Function provides a way to read a cv::Point_<T> value from
* OpenCV text file.
* @param[in] node - file node in which the size value is stored
* @param[out] point - value read
*/
template<class T>
void operator>>(const cv::FileNode &node,
cv::Point_<T> &point){
node[0]>>point.x;
node[1]>>point.y;
}
/// Operator enabling to use cv::TermCriteria with OpenCV persistence
/// functionality (writing)
/**
* Function provides a way to store a cv::TermCriteria value in
* OpenCV text file.
* @param[in] fs - file storage in which the size value is stored
* @param[in] termCrit - value to be stored
* @return fs file storage to enable chain calls.
*/
cv::FileStorage &operator<<(cv::FileStorage &fs,
const cv::TermCriteria &termCrit);
#endif /* CVTYPESIO_HPP_ */
<|endoftext|> |
<commit_before>/*
* safe_queue.hpp
*
* Created on: 2014-11-11
* Author: joseph
*/
#ifndef SAFE_QUEUE_HPP_
#define SAFE_QUEUE_HPP_
#include <queue>
#include <boost/thread/condition_variable.hpp>
//#include <pthread.h>
//#include <semaphore.h>
template <typename T >
class SafeQueue {
private:
std::queue<T > values;
boost::condition_variable m_cond; // The condition to wait for
boost::mutex mtx_;
//pthread_mutex_t access_lock;
//sem_t access_resource;
bool stop_waiting;
//pthread_cond_t empty_wait;
public:
SafeQueue()// : sem_(0)
{
//pthread_mutex_init(&access_lock, NULL);
//sem_init(&access_resource, 0, 0);
stop_waiting = false;
//pthread_cond_init(&empty_wait, 0);
//pthread_cond_signal(&self_adapt_wait);
}
~SafeQueue() {
//pthread_mutex_destroy(&access_lock);
//sem_destroy(&access_resource);
//pthread_cond_destroy(&empty_wait);
}
bool empty() {
boost::unique_lock<boost::mutex> lock(mtx_);
//pthread_mutex_lock(&access_lock);
bool e = values.empty();
//pthread_mutex_unlock(&access_lock);
return e;
}
/* Didnt really need this
typename std::queue<T >::size_type size() const {
pthread_mutex_lock(&access_lock);
auto s = values.size();
pthread_mutex_unlock(&access_lock);
return s;
}*/
/*
T waitToPop() {
boost::unique_lock<boost::mutex> guard(mtx_);
//sem_wait(&access_resource);
//if(stop_waiting) {
// return T ();
//}
//TODO add in exit conidtion
return pop();
}*/
/**
* Retrieves the next value from the queue. The value is also removed.
* If the wait is to true the thread will sleep until the next value is
* available.
*
* @param result The next value in the queue.
* @param wait Whether the pop will wait for a value if the queue is empty.
* Default is to wait for the a value if the queue is empty.
*
* @return Whether the next value was retrieved or not.
*
*/
bool pop(T& result, bool wait=true) {
boost::unique_lock<boost::mutex> lock(mtx_);
while (values.size()==0 && !stop_waiting) {
if(!wait) {
// Queue is empty.
return false;
}
m_cond.wait(lock);
}
// Exit the queue is finished
if (stop_waiting) {
return false;
}
//T val = values.front();
result = values.front();
values.pop();
//pthread_mutex_unlock(&access_lock);
return true;
}
/**
* Retrieve the next amount of items from the queue. If the queue does not
* have enough values the thread will wait.
*
* This method can be potentially dangerous since values may be left on
* the queue and never worked on if the the amount left on is less than the
* desired amount
*
* @param amount The number of items to retrieve from the front the queue.
* @param results The output vector of the values retrieved.
*
* @return Returns true if the number of values are within the results
* vector and false otherwise.
*
*/
bool pop(unsigned int amount, std::vector<T > &results) {
boost::unique_lock<boost::mutex> lock(mtx_);
// Initial design, can deadlock if no more values are added.
while (values.size() < amount && !stop_waiting) {
m_cond.wait(lock);
}
if(stop_waiting) {
return false;
}
// Pop amount of values from the queue
for(unsigned int i = 0; i < amount; i++) {
results.push_back(values.front());
values.pop();
}
return true;
}
/**
* Retrieves the next amount of items or less from the queue. If the queue
* is empty the thread will wait. Otherwise up to the amount of elements
* will be returned
*
* @param amount The number of items to retrieve from the front the queue.
* @param results The output vector of the values retrieved.
*
* @return Returns true if some number of values are within the results
* vector and false otherwise.
*/
bool popUpTO(unsigned int amount, std::vector<T > &results) {
boost::unique_lock<boost::mutex> lock(mtx_);
// Initial design, can deadlock if no more values are added.
while (values.size()==0 && !stop_waiting) {
m_cond.wait(lock);
}
if(stop_waiting) {
return false;
}
// pop off upto amount of values from the queue
for(unsigned int i = 0; i < amount || i < values.size(); i++) {
results.push_back(values.front());
values.pop();
}
return true;
}
/**
* Simple push of a single value into the queue.
*
* @param The value to add to the queue.
*
*/
void push(T &val) {
//pthread_mutex_lock(&access_lock);
boost::unique_lock<boost::mutex> guard(mtx_);
values.push(val);
m_cond.notify_one();
//sem_.post();
//pthread_mutex_unlock(&access_lock);
// Identify that more jobs are available
//sem_post(&access_resource);
}
/**
* Push a set of values into the queue.
* This is implemented to increase performance for a push that involves a
* large sum of entries which can be accomplished faster than fighting
* other threads for access to the mutex several times.
*
* @param entries The list of values to push into the queue.
*/
void push(std::vector<T > &entries) {
boost::unique_lock<boost::mutex> guard(mtx_);
for(unsigned int i = 0; i < entries.size(); i++) {
values.push(entries[i]);
m_cond.notify_one();
}
}
/**
* Notify all waiting threads to wake up and return false. This method
* essentially is a nice way of stopping the threads that are waiting for
* pop.
*/
void finish() {
boost::unique_lock<boost::mutex> lock(mtx_);
this->stop_waiting = true;
m_cond.notify_all();
}
};
#endif /* SAFE_QUEUE_HPP_ */
<commit_msg>ADDED: pop all method for safe queue.<commit_after>/*
* safe_queue.hpp
*
* Created on: 2014-11-11
* Author: joseph
*/
#ifndef SAFE_QUEUE_HPP_
#define SAFE_QUEUE_HPP_
#include <queue>
#include <boost/thread/condition_variable.hpp>
//#include <pthread.h>
//#include <semaphore.h>
template <typename T >
class SafeQueue {
private:
std::queue<T > values;
boost::condition_variable m_cond; // The condition to wait for
boost::mutex mtx_;
//pthread_mutex_t access_lock;
//sem_t access_resource;
bool stop_waiting;
//pthread_cond_t empty_wait;
public:
SafeQueue()// : sem_(0)
{
//pthread_mutex_init(&access_lock, NULL);
//sem_init(&access_resource, 0, 0);
stop_waiting = false;
//pthread_cond_init(&empty_wait, 0);
//pthread_cond_signal(&self_adapt_wait);
}
~SafeQueue() {
//pthread_mutex_destroy(&access_lock);
//sem_destroy(&access_resource);
//pthread_cond_destroy(&empty_wait);
}
bool empty() {
boost::unique_lock<boost::mutex> lock(mtx_);
//pthread_mutex_lock(&access_lock);
bool e = values.empty();
//pthread_mutex_unlock(&access_lock);
return e;
}
/* Didnt really need this
typename std::queue<T >::size_type size() const {
pthread_mutex_lock(&access_lock);
auto s = values.size();
pthread_mutex_unlock(&access_lock);
return s;
}*/
/*
T waitToPop() {
boost::unique_lock<boost::mutex> guard(mtx_);
//sem_wait(&access_resource);
//if(stop_waiting) {
// return T ();
//}
//TODO add in exit conidtion
return pop();
}*/
/**
* Retrieves the next value from the queue. The value is also removed.
* If the wait is to true the thread will sleep until the next value is
* available.
*
* @param result The next value in the queue.
* @param wait Whether the pop will wait for a value if the queue is empty.
* Default is to wait for the a value if the queue is empty.
*
* @return Whether the next value was retrieved or not.
*
*/
bool pop(T& result, bool wait=true) {
boost::unique_lock<boost::mutex> lock(mtx_);
while (values.size()==0 && !stop_waiting) {
if(!wait) {
// Queue is empty.
return false;
}
m_cond.wait(lock);
}
// Exit the queue is finished
if (stop_waiting) {
return false;
}
//T val = values.front();
result = values.front();
values.pop();
//pthread_mutex_unlock(&access_lock);
return true;
}
/**
* Retrieve the next amount of items from the queue. If the queue does not
* have enough values the thread will wait.
*
* This method can be potentially dangerous since values may be left on
* the queue and never worked on if the the amount left on is less than the
* desired amount
*
* @param amount The number of items to retrieve from the front the queue.
* @param results The output vector of the values retrieved.
*
* @return Returns true if the number of values are within the results
* vector and false otherwise.
*
*/
bool pop(unsigned int amount, std::vector<T > &results) {
boost::unique_lock<boost::mutex> lock(mtx_);
// Initial design, can deadlock if no more values are added.
while (values.size() < amount && !stop_waiting) {
m_cond.wait(lock);
}
if(stop_waiting) {
return false;
}
// Pop amount of values from the queue
for(unsigned int i = 0; i < amount; i++) {
results.push_back(values.front());
values.pop();
}
return true;
}
/**
* Retrieves the next amount of items or less from the queue. If the queue
* is empty the thread will wait. Otherwise up to the amount of elements
* will be returned
*
* @param amount The number of items to retrieve from the front the queue.
* @param results The output vector of the values retrieved.
*
* @return Returns true if some number of values are within the results
* vector and false otherwise.
*/
bool popUpTO(unsigned int amount, std::vector<T > &results) {
boost::unique_lock<boost::mutex> lock(mtx_);
// Initial design, can deadlock if no more values are added.
while (values.size()==0 && !stop_waiting) {
m_cond.wait(lock);
}
if(stop_waiting) {
return false;
}
// pop off upto amount of values from the queue
for(unsigned int i = 0; i < amount || i < values.size(); i++) {
results.push_back(values.front());
values.pop();
}
return true;
}
/**
* Retrieve all the values within the queue. If no values are within the
* queue the thread will wait until there are some values within the queue.
*
* @param results All the values currently within the queue.
*
* @return Returns true if values were successfully retrieved and false if
* the queue's finish method has been called.
*/
bool popAll(std::vector<T > &results, bool wait=true) {
boost::unique_lock<boost::mutex> lock(mtx_);
// Initial design, can deadlock if no more values are added.
while (values.size()==0 && !stop_waiting) {
if(!wait) {
// Queue is empty.
return false;
}
m_cond.wait(lock);
}
if(stop_waiting) {
return false;
}
// pop off all the available values within the queue.
while(values.size() != 0) {
results.push_back(values.front());
values.pop();
}
return true;
}
/**
* Simple push of a single value into the queue.
*
* @param The value to add to the queue.
*
*/
void push(T &val) {
//pthread_mutex_lock(&access_lock);
boost::unique_lock<boost::mutex> guard(mtx_);
values.push(val);
m_cond.notify_one();
//sem_.post();
//pthread_mutex_unlock(&access_lock);
// Identify that more jobs are available
//sem_post(&access_resource);
}
/**
* Push a set of values into the queue.
* This is implemented to increase performance for a push that involves a
* large sum of entries which can be accomplished faster than fighting
* other threads for access to the mutex several times.
*
* @param entries The list of values to push into the queue.
*/
void push(std::vector<T > &entries) {
boost::unique_lock<boost::mutex> guard(mtx_);
for(unsigned int i = 0; i < entries.size(); i++) {
values.push(entries[i]);
m_cond.notify_one();
}
}
/**
* Notify all waiting threads to wake up and return false. This method
* essentially is a nice way of stopping the threads that are waiting for
* pop.
*/
void finish() {
boost::unique_lock<boost::mutex> lock(mtx_);
this->stop_waiting = true;
m_cond.notify_all();
}
};
#endif /* SAFE_QUEUE_HPP_ */
<|endoftext|> |
<commit_before>#ifndef ALX_EVENT_HPP
#define ALX_EVENT_HPP
#include <cassert>
#include "Joystick.hpp"
#include "Display.hpp"
#include "Timer.hpp"
namespace alx {
/**
An allegro event.
*/
class Event {
public:
/**
default constructor.
*/
Event() {
}
/**
constructor from event struct.
*/
Event(const ALLEGRO_EVENT &event) :m_object(event) {
}
/**
If the event is a user event, then it is automatically unrefd.
*/
~Event() {
if (_isUserEvent(m_object.type)) al_unref_user_event(&m_object.user);
}
/**
Returns true if the event is a user one.
@return true if user event, false otherwise.
*/
bool isUserEvent() const {
return _isUserEvent(m_object.type);
}
int getType() const {
return m_object.type;
}
EventSource getEventSource() const {
return EventSource(m_object.any.source, false);
}
double getTimestamp() const {
return m_object.any.timestamp;
}
Display getDisplay() const {
return Display(m_object.display.source, false);
}
int getDisplayX() const {
return m_object.display.x;
}
int getDisplayY() const {
return m_object.display.y;
}
int getDisplayWidth() const {
return m_object.display.width;
}
int getDisplayHeight() const {
return m_object.display.height;
}
int getDisplayOrientation() const {
return m_object.display.orientation;
}
Joystick getJoystick() const {
return Joystick(m_object.joystick.source, false);
}
Joystick getJoystickId() const {
return Joystick(m_object.joystick.id, false);
}
int getJoystickStick() const {
return m_object.joystick.stick;
}
int getJoystickAxis() const {
return m_object.joystick.axis;
}
float getJoystickPos() const {
return m_object.joystick.pos;
}
int getJoystickButton() const {
return m_object.joystick.button;
}
Display getKeyboardDisplay() const {
return Display(m_object.keyboard.display, false);
}
int getKeyboardKeycode() const {
return m_object.keyboard.keycode;
}
int getKeyboardUnicodeCharacter() const {
return m_object.keyboard.unichar;
}
int getKeyboardModifiers() const {
return m_object.keyboard.modifiers;
}
bool getKeyboardRepeat() const {
return m_object.keyboard.repeat;
}
Display getMouseDisplay() const {
return Display(m_object.mouse.display, false);
}
int getMouseX() const {
return m_object.mouse.x;
}
int getMouseY() const {
return m_object.mouse.y;
}
int getMouseZ() const {
return m_object.mouse.z;
}
int getMouseW() const {
return m_object.mouse.w;
}
int getMouseDX() const {
return m_object.mouse.dx;
}
int getMouseDY() const {
return m_object.mouse.dy;
}
int getMouseDZ() const {
return m_object.mouse.dz;
}
int getMouseDW() const {
return m_object.mouse.dw;
}
float getMousePressure() const {
return m_object.mouse.pressure;
}
Timer getTimer() const {
return Timer(m_object.timer.source, false);
}
int64_t getTimerCount() const {
return m_object.timer.count;
}
double getTimerError() const {
return m_object.timer.error;
}
intptr_t getUserData1() const {
return m_object.user.data1;
}
intptr_t getUserData2() const {
return m_object.user.data2;
}
intptr_t getUserData3() const {
return m_object.user.data3;
}
intptr_t getUserData4() const {
return m_object.user.data4;
}
private:
//allegro event
ALLEGRO_EVENT m_object;
friend class UserEventSource;
//check if the type represents an Allegro event or a user type event.
static bool _isUserEvent(int type);
};
} //namespace alx
#endif //ALX_EVENT_HPP
<commit_msg>Documented the Event class members.<commit_after>#ifndef ALX_EVENT_HPP
#define ALX_EVENT_HPP
#include <cassert>
#include "Joystick.hpp"
#include "Display.hpp"
#include "Timer.hpp"
namespace alx {
/**
An allegro event.
*/
class Event {
public:
/**
default constructor.
*/
Event() {
}
/**
constructor from event struct.
*/
Event(const ALLEGRO_EVENT &event) :m_object(event) {
}
/**
If the event is a user event, then it is automatically unrefd.
*/
~Event() {
if (_isUserEvent(m_object.type)) al_unref_user_event(&m_object.user);
}
/**
Returns true if the event is a user one.
@return true if user event, false otherwise.
*/
bool isUserEvent() const {
return _isUserEvent(m_object.type);
}
/**
Returns the type of the event.
@return the type of the event.
*/
int getType() const {
return m_object.type;
}
/**
Returns the event source.
@return the event source.
*/
EventSource getEventSource() const {
return EventSource(m_object.any.source, false);
}
/**
Returns the timestamp.
@return the timestamp.
*/
double getTimestamp() const {
return m_object.any.timestamp;
}
/**
Returns the display.
@return the display.
*/
Display getDisplay() const {
return Display(m_object.display.source, false);
}
/**
Returns the display x.
@return the display x.
*/
int getDisplayX() const {
return m_object.display.x;
}
/**
Returns the display y.
@return the display y.
*/
int getDisplayY() const {
return m_object.display.y;
}
/**
Returns the display width.
@return the display width.
*/
int getDisplayWidth() const {
return m_object.display.width;
}
/**
Returns the display height.
@return the display height.
*/
int getDisplayHeight() const {
return m_object.display.height;
}
/**
Returns the display orientation.
@return the display orientation.
*/
int getDisplayOrientation() const {
return m_object.display.orientation;
}
/**
Returns the joystick.
@return the joystick.
*/
Joystick getJoystick() const {
return Joystick(m_object.joystick.source, false);
}
/**
Returns the joystick id.
@return the joystick id.
*/
Joystick getJoystickId() const {
return Joystick(m_object.joystick.id, false);
}
/**
Returns the joystick stick.
@return the joystick stick.
*/
int getJoystickStick() const {
return m_object.joystick.stick;
}
/**
Returns the joystick axis.
@return the joystick axis.
*/
int getJoystickAxis() const {
return m_object.joystick.axis;
}
/**
Returns the joystick position.
@return the joystick position.
*/
float getJoystickPos() const {
return m_object.joystick.pos;
}
/**
Returns the joystick button.
@return the joystick button.
*/
int getJoystickButton() const {
return m_object.joystick.button;
}
/**
Returns the keyboard display.
@return the keyboard display.
*/
Display getKeyboardDisplay() const {
return Display(m_object.keyboard.display, false);
}
/**
Returns the keyboard keycode.
@return the keyboard keycode.
*/
int getKeyboardKeycode() const {
return m_object.keyboard.keycode;
}
/**
Returns the keyboard unicode character.
@return the keyboard unicode character.
*/
int getKeyboardCharacter() const {
return m_object.keyboard.unichar;
}
/**
Returns the keyboard modifiers.
@return the keyboard modifiers.
*/
int getKeyboardModifiers() const {
return m_object.keyboard.modifiers;
}
/**
Returns the keyboard repeat flag.
@return the keyboard repeat flag.
*/
bool getKeyboardRepeat() const {
return m_object.keyboard.repeat;
}
/**
Returns the mouse display.
@return the mouse display.
*/
Display getMouseDisplay() const {
return Display(m_object.mouse.display, false);
}
/**
Returns the mouse x.
@return the mouse x.
*/
int getMouseX() const {
return m_object.mouse.x;
}
/**
Returns the mouse y.
@return the mouse y.
*/
int getMouseY() const {
return m_object.mouse.y;
}
/**
Returns the mouse z.
@return the mouse z.
*/
int getMouseZ() const {
return m_object.mouse.z;
}
/**
Returns the mouse w.
@return the mouse w.
*/
int getMouseW() const {
return m_object.mouse.w;
}
/**
Returns the mouse dx.
@return the mouse dx.
*/
int getMouseDX() const {
return m_object.mouse.dx;
}
/**
Returns the mouse dy.
@return the mouse dy.
*/
int getMouseDY() const {
return m_object.mouse.dy;
}
/**
Returns the mouse dz.
@return the mouse dz.
*/
int getMouseDZ() const {
return m_object.mouse.dz;
}
/**
Returns the mouse dw.
@return the mouse dw.
*/
int getMouseDW() const {
return m_object.mouse.dw;
}
/**
Returns the mouse pressure.
@return the mouse pressure.
*/
float getMousePressure() const {
return m_object.mouse.pressure;
}
/**
Returns the timer.
@return the timer.
*/
Timer getTimer() const {
return Timer(m_object.timer.source, false);
}
/**
Returns the timer count.
@return the timer count.
*/
int64_t getTimerCount() const {
return m_object.timer.count;
}
/**
Returns the timer error.
@return the timer error.
*/
double getTimerError() const {
return m_object.timer.error;
}
/**
Returns the user data field 1.
@return the user data field 1.
*/
intptr_t getUserData1() const {
return m_object.user.data1;
}
/**
Returns the user data field 2.
@return the user data field 2.
*/
intptr_t getUserData2() const {
return m_object.user.data2;
}
/**
Returns the user data field 3.
@return the user data field 3.
*/
intptr_t getUserData3() const {
return m_object.user.data3;
}
/**
Returns the user data field 4.
@return the user data field 4.
*/
intptr_t getUserData4() const {
return m_object.user.data4;
}
private:
//allegro event
ALLEGRO_EVENT m_object;
friend class UserEventSource;
//check if the type represents an Allegro event or a user type event.
static bool _isUserEvent(int type);
};
} //namespace alx
#endif //ALX_EVENT_HPP
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Library
Module: Mat4x4.hh
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#ifndef __vlMatrix4x4_hh
#define __vlMatrix4x4_hh
#include "Object.hh"
class vlMatrix4x4 : public vlObject
{
public:
float Element[4][4];
// A 4 x 4 matrix.
vlMatrix4x4 ();
void operator= (float element);
void operator= (vlMatrix4x4& source);
float *operator[](const unsigned int i) const {return &(Element[i][0]);};
// Calculate the inverse of in and
// return it in out.
void Invert (vlMatrix4x4 in,vlMatrix4x4 & out);
void Invert (void) { Invert(*this,*this);};
// Calculate the transpose of in and
// return it in out.
void Transpose (vlMatrix4x4 in,vlMatrix4x4 & out);
void Transpose (void) { Transpose(*this,*this);};
void VectorMultiply(float in[4], float out[4]);
void Adjoint (vlMatrix4x4 & in,vlMatrix4x4 & out);
float Determinant (vlMatrix4x4 & in);
char *GetClassName () {return "vlMatrix4x4";};
void PrintSelf (ostream& os, vlIndent indent);
};
#endif
<commit_msg>fixed prototype<commit_after>/*=========================================================================
Program: Visualization Library
Module: Mat4x4.hh
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#ifndef __vlMatrix4x4_hh
#define __vlMatrix4x4_hh
#include "Object.hh"
class vlMatrix4x4 : public vlObject
{
public:
float Element[4][4];
// A 4 x 4 matrix.
vlMatrix4x4 ();
void operator= (float element);
void operator= (vlMatrix4x4& source);
float *operator[](const unsigned int i) {return &(Element[i][0]);};
// Calculate the inverse of in and
// return it in out.
void Invert (vlMatrix4x4 in,vlMatrix4x4 & out);
void Invert (void) { Invert(*this,*this);};
// Calculate the transpose of in and
// return it in out.
void Transpose (vlMatrix4x4 in,vlMatrix4x4 & out);
void Transpose (void) { Transpose(*this,*this);};
void VectorMultiply(float in[4], float out[4]);
void Adjoint (vlMatrix4x4 & in,vlMatrix4x4 & out);
float Determinant (vlMatrix4x4 & in);
char *GetClassName () {return "vlMatrix4x4";};
void PrintSelf (ostream& os, vlIndent indent);
};
#endif
<|endoftext|> |
<commit_before>//
// Copyright (C) 2013
// Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
#include <ctime>
#include <cmath>
#include <string>
using std::string;
#include <chrono>
using std::chrono::duration_cast;
using std::chrono::duration;
using std::chrono::high_resolution_clock;
#ifndef TIMER_HPP
#define TIMER_HPP
namespace isa {
namespace utils {
class Timer {
public:
Timer(string name);
void start();
void stop();
void reset();
inline unsigned int getNrRuns() const;
inline double getTotalTime() const;
inline double getLastRunTime() const;
inline double getAverageTime() const;
inline double getStdDev() const;
private:
string name;
high_resolution_clock::time_point starting;
unsigned int nrRuns;
double totalTime;
double time;
double average;
double variance;
};
// Implementation
Timer::Timer(string name) : name(name), starting(high_resolution_clock::time_point()), nrRuns(0), totalTime(0.0), time(0.0), average(0.0), variance(0.0) {}
void Timer::start() {
starting = high_resolution_clock::now();
}
void Timer::stop() {
time = (duration_cast< duration< double > >(high_resolution_clock::now() - starting)).count();
totalTime += time;
nrRuns++;
if ( nrRuns == 1 ) {
average = time;
variance = 0.0;
} else {
double oldAverage = average;
average = oldAverage + ((time - oldAverage) / nrRuns);
variance += ((time - oldAverage) * (time - average));
}
}
void Timer::reset() {
starting = high_resolution_clock::time_point();
nrRuns = 0;
totalTime = 0.0;
time = 0.0;
average = 0.0;
variance = 0.0;
}
inline unsigned int Timer::getNrRuns() const {
return nrRuns;
}
inline double Timer::getTotalTime() const {
return totalTime;
}
inline double Timer::getLastRunTime() const {
return time;
}
inline double Timer::getAverageTime() const {
return average;
}
inline double Timer::getStdDev() const {
return sqrt(variance / nrRuns);
}
} // utils
} // isa
#endif // TIMER_HPP
<commit_msg>Timer is now using the new Stats class.<commit_after>//
// Copyright (C) 2013
// Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
#include <ctime>
#include <string>
using std::string;
#include <chrono>
using std::chrono::duration_cast;
using std::chrono::duration;
using std::chrono::high_resolution_clock;
#include <Stats.hpp>
#ifndef TIMER_HPP
#define TIMER_HPP
namespace isa {
namespace utils {
class Timer {
public:
Timer(string name);
void start();
void stop();
void reset();
inline unsigned int getNrRuns() const;
inline double getTotalTime() const;
inline double getLastRunTime() const;
inline double getAverageTime() const;
inline double getStdDev() const;
private:
Stats< double > stats;
string name;
high_resolution_clock::time_point starting;
double totalTime;
double time;
};
// Implementation
Timer::Timer(string name) : stats(Stats< double >()) name(name), starting(high_resolution_clock::time_point()), totalTime(0.0), time(0.0) {}
void Timer::start() {
starting = high_resolution_clock::now();
}
void Timer::stop() {
time = (duration_cast< duration< double > >(high_resolution_clock::now() - starting)).count();
totalTime += time;
stats.addElement(time);
}
void Timer::reset() {
starting = high_resolution_clock::time_point();
totalTime = 0.0;
time = 0.0;
}
inline unsigned int Timer::getNrRuns() const {
return stats.getNrElements();
}
inline double Timer::getTotalTime() const {
return totalTime;
}
inline double Timer::getLastRunTime() const {
return time;
}
inline double Timer::getAverageTime() const {
return stats.getAverage();
}
inline double Timer::getStdDev() const {
return stats.getStdDev();
}
} // utils
} // isa
#endif // TIMER_HPP
<|endoftext|> |
<commit_before>///
/// @file imath.hpp
/// @brief Integer math functions used in primesum.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef IMATH_HPP
#define IMATH_HPP
#include <isqrt.hpp>
#include <stdint.h>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <vector>
namespace primesum {
inline int64_t isquare(int64_t x)
{
return x * x;
}
template <typename A, typename B>
inline A ceil_div(A a, B b)
{
assert(b > 0);
return (A) ((a + b - 1) / b);
}
template <typename T>
inline T number_of_bits(T)
{
return (T) (sizeof(T) * 8);
}
template <typename T>
inline T next_power_of_2(T x)
{
if (x == 0)
return 1;
x--;
for (T i = 1; i < number_of_bits(x); i += i)
x |= (x >> i);
return ++x;
}
template <typename T>
inline T prev_power_of_2(T x)
{
for (T i = 1; i < number_of_bits(x); i += i)
x |= (x >> i);
return x - (x >> 1);
}
template <typename T>
inline int ilog(T x)
{
return (int) std::log((double) x);
}
/// Raise to power
template <typename T>
inline T ipow(T x, int n)
{
T r = 1;
for (int i = 0; i < n; i++)
r *= x;
return r;
}
/// Integer nth root
template <int N, typename T>
inline T iroot(T x)
{
if (N == 0)
return 0;
T r = (T) std::pow((double) x, 1.0 / N);
// fix root too large
for (; r > 0 && ipow(r, N - 1) > x / r; r--);
// fix root too small
for (; ipow(r + 1, N - 1) <= x / (r + 1); r++);
return r;
}
/// Count the number of primes <= x using binary search.
/// @pre primes[1] = 2, primes[3] = 3, ...
/// @pre x <= primes.back()
///
template <typename T1, typename T2>
inline T2 pi_bsearch(const std::vector<T1>& primes, T2 x)
{
assert(primes[0] == 0);
return (T2) (std::upper_bound(primes.begin() + 1, primes.end(), x) - (primes.begin() + 1));
}
template <typename T1, typename T2, typename T3>
inline T2 in_between(T1 min, T2 x, T3 max)
{
if (x < min)
return (T2) min;
if (x > max)
return (T2) max;
return x;
}
} // namespace
#endif
<commit_msg>Improve number_of_bits()<commit_after>///
/// @file imath.hpp
/// @brief Integer math functions used in primesum.
///
/// Copyright (C) 2018 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef IMATH_HPP
#define IMATH_HPP
#include <isqrt.hpp>
#include <stdint.h>
#include <algorithm>
#include <cassert>
#include <climits>
#include <cmath>
#include <vector>
namespace primesum {
inline int64_t isquare(int64_t x)
{
return x * x;
}
template <typename A, typename B>
inline A ceil_div(A a, B b)
{
assert(b > 0);
return (A) ((a + b - 1) / b);
}
template <typename T>
inline T number_of_bits(T)
{
static_assert(sizeof(uint64_t) * CHAR_BIT == 64, "number_of_bits() is broken");
return (T) (sizeof(T) * CHAR_BIT);
}
template <typename T>
inline T next_power_of_2(T x)
{
if (x == 0)
return 1;
x--;
for (T i = 1; i < number_of_bits(x); i += i)
x |= (x >> i);
return ++x;
}
template <typename T>
inline T prev_power_of_2(T x)
{
for (T i = 1; i < number_of_bits(x); i += i)
x |= (x >> i);
return x - (x >> 1);
}
template <typename T>
inline int ilog(T x)
{
return (int) std::log((double) x);
}
/// Raise to power
template <typename T>
inline T ipow(T x, int n)
{
T r = 1;
for (int i = 0; i < n; i++)
r *= x;
return r;
}
/// Integer nth root
template <int N, typename T>
inline T iroot(T x)
{
if (N == 0)
return 0;
T r = (T) std::pow((double) x, 1.0 / N);
// fix root too large
for (; r > 0 && ipow(r, N - 1) > x / r; r--);
// fix root too small
for (; ipow(r + 1, N - 1) <= x / (r + 1); r++);
return r;
}
/// Count the number of primes <= x using binary search.
/// @pre primes[1] = 2, primes[3] = 3, ...
/// @pre x <= primes.back()
///
template <typename T1, typename T2>
inline T2 pi_bsearch(const std::vector<T1>& primes, T2 x)
{
assert(primes[0] == 0);
return (T2) (std::upper_bound(primes.begin() + 1, primes.end(), x) - (primes.begin() + 1));
}
template <typename T1, typename T2, typename T3>
inline T2 in_between(T1 min, T2 x, T3 max)
{
if (x < min)
return (T2) min;
if (x > max)
return (T2) max;
return x;
}
} // namespace
#endif
<|endoftext|> |
<commit_before><commit_msg>LOJ 3057<commit_after><|endoftext|> |
<commit_before><commit_msg>Skip 16+ and 18+ images<commit_after><|endoftext|> |
<commit_before>// PThreads
#include <pthread.h>
// Intel intrinsics
#include <immintrin.h>
// STL
#include <functional>
#include <iostream>
// xsync
#include "lock.hpp"
namespace xsync {
/*
* Provides an RAII style wrapper for transactional execution.
*/
template <typename LockType>
class XScope {
public:
XScope(LockType& fallback) : fallback_(fallback), cb_registered_(false) { enter(); }
~XScope() { exit(); }
// The next few functions need to be specialized for each of the locktypes
// passing a non-specialized lock will result in additional aborts
inline bool isFallbackLocked() {
return false;
}
// These need to be specialized if the LockType is not a BasicLockable
inline void lockFallback() { fallback_.lock(); }
inline void unlockFallback() { fallback_.unlock(); }
void enter(int nretries = 3) {
unsigned int xact_status;
std::cout << isFallbackLocked() << std::endl;
for (int attempt = 0; attempt <= nretries; ++attempt) {
xact_status = _xbegin();
if (xact_status == _XBEGIN_STARTED) {
if (!isFallbackLocked()) {
// No other threads are executing the critical section non-transactionally,
// so we can execute the critical section
return;
} else {
// explicit abort since the lock is held
_xabort(0xFF);
}
} else {
// We have aborted
if ((xact_status & _XABORT_EXPLICIT) && _XABORT_CODE(xact_status) == 0xFF) {
// We aborted because the lock was held
// wait until the lock is free and then retry
lockFallback();
unlockFallback();
} else if (!(xact_status & _XABORT_RETRY)) {
// If the retry bit is not set, take fallback
break;
}
}
}
// Take fallback
lockFallback();
}
void exit() {
if (_xtest()) {
_xend();
} else {
unlockFallback();
}
// Execute callback
if (cb_registered_) cb_();
}
// Callback must not throw an exception since it is executed in the destructor
void registerCommitCallback(const std::function<void()> &callback) {
cb_registered_ = true;
cb_ = callback;
}
private:
//friend class XCondVar;
std::function<void()> cb_;
bool cb_registered_;
LockType &fallback_;
};
// These are lock-specific hacks to check the state without modifying memory.
// Usually this state is private (for good reason), but we need to access it
// template<>
// bool XScope<spinlock_t>::isFallbackLocked() {
// return *(reinterpret_cast<int*>(&fallback_)) == 0;
//}
template<>
bool XScope<pthread_mutex_t>::isFallbackLocked() {
return fallback_.__data.__lock != 0;
}
template<>
inline void XScope<pthread_mutex_t>::lockFallback() {
pthread_mutex_lock(&fallback_);
}
template<>
inline void XScope<pthread_mutex_t>::unlockFallback() {
pthread_mutex_unlock(&fallback_);
}
} // namespace xsync
<commit_msg>remove io<commit_after>// PThreads
#include <pthread.h>
// Intel intrinsics
#include <immintrin.h>
// STL
#include <functional>
#include <iostream>
// xsync
#include "lock.hpp"
namespace xsync {
/*
* Provides an RAII style wrapper for transactional execution.
*/
template <typename LockType>
class XScope {
public:
XScope(LockType& fallback) : fallback_(fallback), cb_registered_(false) { enter(); }
~XScope() { exit(); }
// The next few functions need to be specialized for each of the locktypes
// passing a non-specialized lock will result in additional aborts
inline bool isFallbackLocked() {
return false;
}
// These need to be specialized if the LockType is not a BasicLockable
inline void lockFallback() { fallback_.lock(); }
inline void unlockFallback() { fallback_.unlock(); }
void enter(int nretries = 3) {
unsigned int xact_status;
for (int attempt = 0; attempt <= nretries; ++attempt) {
xact_status = _xbegin();
if (xact_status == _XBEGIN_STARTED) {
if (!isFallbackLocked()) {
// No other threads are executing the critical section non-transactionally,
// so we can execute the critical section
return;
} else {
// explicit abort since the lock is held
_xabort(0xFF);
}
} else {
// We have aborted
if ((xact_status & _XABORT_EXPLICIT) && _XABORT_CODE(xact_status) == 0xFF) {
// We aborted because the lock was held
// wait until the lock is free and then retry
lockFallback();
unlockFallback();
} else if (!(xact_status & _XABORT_RETRY)) {
// If the retry bit is not set, take fallback
break;
}
}
}
// Take fallback
lockFallback();
}
void exit() {
if (_xtest()) {
_xend();
} else {
unlockFallback();
}
// Execute callback
if (cb_registered_) cb_();
}
// Callback must not throw an exception since it is executed in the destructor
void registerCommitCallback(const std::function<void()> &callback) {
cb_registered_ = true;
cb_ = callback;
}
private:
//friend class XCondVar;
std::function<void()> cb_;
bool cb_registered_;
LockType &fallback_;
};
// These are lock-specific hacks to check the state without modifying memory.
// Usually this state is private (for good reason), but we need to access it
// template<>
// bool XScope<spinlock_t>::isFallbackLocked() {
// return *(reinterpret_cast<int*>(&fallback_)) == 0;
//}
template<>
bool XScope<pthread_mutex_t>::isFallbackLocked() {
return fallback_.__data.__lock != 0;
}
template<>
inline void XScope<pthread_mutex_t>::lockFallback() {
pthread_mutex_lock(&fallback_);
}
template<>
inline void XScope<pthread_mutex_t>::unlockFallback() {
pthread_mutex_unlock(&fallback_);
}
} // namespace xsync
<|endoftext|> |
<commit_before>#include <iostream>
template <typename T>
class stack
{
public:
stack();
stack(stack const &);
~stack();
size_t count() const;
auto push(T const &) -> void;
T pop();
auto operator=(stack const & right)->stack &;
private:
T *array_;
size_t array_size_;
size_t count_;
};
template<typename T>
auto newcopy(const T * item, size_t size, size_t count) -> T*
{
T * buff = new T[size];
std::copy(item, item + count, buff);
return buff;
}
template <typename T>
size_t stack<T>::count() const
{
std::cout << count_;
return count_;
}
template <typename T>
stack<T>::stack()
{
array_size_ = 0;
array_ = new T[array_size_];
count_ = 0;
}
template<typename T>
stack<T>::stack(stack const & other) :array_size_(other.array_size_), count_(other.count_), array_(newcopy(other.array_, other.array_size_, other.count_))
{
}
template <typename T>
stack<T>::~stack()
{
delete[] array_;
}
template<typename T>
void stack<T>::push(T const &item)
{
if (count_ == array_size_)
{
size_t size = array_size_ * 2 + (array_size_ == 0);
delete[] array_;
array_ = newcopy(array_, size, array_size_);
array_size_ = size;
}
array_[count_] = item;
++count_;
}
template<typename T>
T stack<T>::pop()
{
if (count_ == 0)
{
throw std::logic_error("Stack is empty!");
}
return array_[--count_];
}
template<typename T>
auto stack<T>::operator=(stack const & right) -> stack & {
if (this != &right) {
delete[] array_;
newcopy(right.array_, right.array_size_, right.count_);
}
return *this;
}
<commit_msg>Update stack.cpp<commit_after>#include <iostream>
template <typename T>
class stack
{
public:
stack(); //noexcept
stack(stack const &); //strong
~stack(); //noexcept
size_t count() const; //noexcept
auto push(T const &) -> void; //strong
T pop(); //basic
auto operator=(stack const & right)->stack &; //strong
private:
T *array_;
size_t array_size_;
size_t count_;
};
template<typename T>
auto newcopy(const T * item, size_t size, size_t count) -> T* //strong
{
T * buff = new T[size];
std::copy(item, item + count, buff);
return buff;
}
template <typename T>
size_t stack<T>::count() const
{
std::cout << count_;
return count_;
}
template <typename T>
stack<T>::stack()
{
array_size_ = 0;
array_ = new T[array_size_];
count_ = 0;
}
template<typename T>
stack<T>::stack(stack const & other) :array_size_(other.array_size_), count_(other.count_), array_(newcopy(other.array_, other.array_size_, other.count_))
{
}
template <typename T>
stack<T>::~stack()
{
delete[] array_;
}
template<typename T>
void stack<T>::push(T const &item)
{
if (count_ == array_size_)
{
size_t size = array_size_ * 2 + (array_size_ == 0);
delete[] array_;
array_ = newcopy(array_, size, array_size_);
array_size_ = size;
}
array_[count_] = item;
++count_;
}
template<typename T>
T stack<T>::pop()
{
if (count_ == 0)
{
throw std::logic_error("Stack is empty!");
}
return array_[--count_];
}
template<typename T>
auto stack<T>::operator=(stack const & right) -> stack & {
if (this != &right) {
delete[] array_;
newcopy(right.array_, right.array_size_, right.count_);
}
return *this;
}
<|endoftext|> |
<commit_before>#include <iostream>
template <typename T>
class stack
{
public:
stack(); //noexcept
stack(stack const &); //strong
~stack(); //noexcept
size_t count() const; //noexcept
auto push(T const &) -> void; //strong
void pop(); //basic
const T& top() const; //strong
auto operator=(stack const & right)->stack &; //strong
private:
T *array_;
size_t array_size_;
size_t count_;
};
template<typename T>
auto newcopy(const T * item, size_t size, size_t count) -> T* //strong
{
T * buff = new T[size];
try
{
std::copy(item, item + count, buff);
}
catch (...)
{
delete[] buff;
throw;
}
return buff;
}
template <typename T>
size_t stack<T>::count() const
{
std::cout << count_;
return count_;
}
template <typename T>
stack<T>::stack()
{
array_size_ = 0;
array_ = new T[array_size_];
count_ = 0;
}
template<typename T>
stack<T>::stack(stack const & other) :array_size_(other.array_size_), count_(other.count_), array_(newcopy(other.array_, other.array_size_, other.count_))
{
}
template <typename T>
stack<T>::~stack()
{
delete[] array_;
}
template<typename T>
void stack<T>::push(T const &item)
{
if (count_ == array_size_)
{
size_t size = array_size_ * 2 + (array_size_ == 0);
delete[] array_;
array_ = newcopy(array_, size, array_size_);
array_size_ = size;
}
array_[count_] = item;
++count_;
}
template<typename T>
void stack<T>::pop()
{
if (count_ == 0)
{
throw std::logic_error("Stack is empty!");
}
else
{
count_--;
}
}
template<typename T>
const T& stack<T>::top()
{
if (count_ == 0)
{
throw ("Stack is empty!");
}
return array_[count_ - 1];
}
template<typename T>
auto stack<T>::operator=(stack const & right) -> stack &
{
if (this != &right)
{
delete[] array_;
newcopy(right.array_, right.array_size_, right.count_);
}
return *this;
}
<commit_msg>Update stack.cpp<commit_after>#ifndef stack_cpp
#define stack_cpp
#pragma once
#include <iostream>
template <typename T>
class stack
{
public:
stack(); //noexcept
stack(stack const &); //strong
~stack(); //noexcept
size_t count() const; //noexcept
auto push(T const &) -> void; //strong
void pop(); //basic
const T& top() const; //strong
auto operator=(stack const & right)->stack &; //strong
private:
T *array_;
size_t array_size_;
size_t count_;
};
template<typename T>
auto newcopy(const T * item, size_t size, size_t count) -> T* //strong
{
T * buff = new T[size];
try
{
std::copy(item, item + count, buff);
}
catch (...)
{
delete[] buff;
throw;
}
return buff;
}
template <typename T>
size_t stack<T>::count() const
{
return count_;
}
template <typename T>
stack<T>::stack()
{
array_size_ = 0;
array_ = new T[array_size_];
count_ = 0;
}
template<typename T>
stack<T>::stack(stack const & other) :array_size_(other.array_size_), count_(other.count_), array_(newcopy(other.array_, other.array_size_, other.count_))
{
}
template <typename T>
stack<T>::~stack()
{
delete[] array_;
}
template<typename T>
void stack<T>::push(T const &item)
{
if (count_ == array_size_)
{
size_t size = array_size_ * 2 + (array_size_ == 0);
delete[] array_;
array_ = newcopy(array_, size, array_size_);
array_size_ = size;
}
array_[count_] = item;
++count_;
}
template<typename T>
void stack<T>::pop()
{
if (count_ == 0)
{
throw std::logic_error("Stack is empty!");
}
else
{
count_--;
}
}
template<typename T>
const T& stack<T>::top()
{
if (count_ == 0)
{
throw ("Stack is empty!");
}
return array_[count_ - 1];
}
template<typename T>
auto stack<T>::operator=(stack const & right) -> stack &
{
if (this != &right)
{
delete[] array_;
newcopy(right.array_, right.array_size_, right.count_);
}
return *this;
}
#endif
<|endoftext|> |
<commit_before>//
// Class for performing common math operations (e.g., dot, cross products)
//
#ifndef __vlMath_hh
#define __vlMath_hh
#include <math.h>
class vlMath
{
public:
vlMath();
float Pi() {return 3.14159265358979;};
float Dot(float x[3], float y[3])
{return x[0]*y[0] + x[1]*y[1] + x[2]*y[2];};
float Norm(float x[3])
{return sqrt(x[0]*x[0] + x[1]*x[1] + x[2]*x[2]);};
void RandomSeed(long s);
float Random();
private:
long Seed;
};
#endif
<commit_msg>*** empty log message ***<commit_after>//
// Class for performing common math operations (e.g., dot, cross products)
//
#ifndef __vlMath_hh
#define __vlMath_hh
#include <math.h>
class vlMath
{
public:
vlMath();
float Pi() {return 3.14159265358979;};
float DegreesToRadians() {return 0.018977369;};
float Dot(float x[3], float y[3])
{return x[0]*y[0] + x[1]*y[1] + x[2]*y[2];};
float Norm(float x[3])
{return sqrt(x[0]*x[0] + x[1]*x[1] + x[2]*x[2]);};
void RandomSeed(long s);
float Random();
private:
long Seed;
};
#endif
<|endoftext|> |
<commit_before>#include <ncurses.h>
#include <locale>
#include <chrono>
#include <thread>
#include <string>
#include <vector>
#include <regex>
#include <iostream>
#include <stdexcept>
#include <nanojson.hpp>
#include <cmdline.h>
using namespace std::literals::string_literals;
using std::string;
using std::tuple;
using std::vector;
bool is_utf8_first(uint8_t ch)
{
return (ch & 0xC0) != 0x80 && (ch & 0xFE) != 0xFE && ((ch & 0x80) == 0 || (ch & 0xC0) == 0xC0);
}
bool is_utf8_cont(uint8_t ch) { return (ch & 0xC0) == 0x80; }
size_t get_utf8_char_length(uint8_t ch)
{
if (!is_utf8_first(ch)) {
throw std::runtime_error(string(__FUNCTION__) + ": the first byte is not UTF8");
}
for (int i = 0; i < 6; ++i) {
if ((ch & (0x01 << (7 - i))) == 0) {
return std::max(1, i);
}
}
throw std::runtime_error(string(__FUNCTION__) + ": unreachable");
}
std::string get_utf8_char()
{
std::array<uint8_t, 6> buf{0};
auto ch0 = static_cast<uint8_t>(::getch() & 0x000000FF);
size_t len = get_utf8_char_length(ch0);
buf[0] = ch0;
for (size_t i = 1; i < len; ++i) {
auto ch = static_cast<uint8_t>(::getch() & 0x000000FF);
if (!is_utf8_cont(ch)) {
throw std::runtime_error(string(__FUNCTION__) + ": wrong byte exists");
}
buf[i] = ch;
}
return std::string(buf.data(), buf.data() + len);
}
void pop_back_utf8(std::string& str)
{
if (str.empty())
return;
for (ssize_t len = str.size() - 1; len >= 0; --len) {
if (!is_utf8_cont(str[len])) {
str.resize(len);
return;
}
}
}
enum class Key { Enter, Esc, Alt, Up, Down, Left, Right, Backspace, Char, Unknown };
class Event {
Key key;
int mod;
std::string ch;
public:
Event(Key key) : key{key}, mod{0}, ch{} {}
Event(int mod) : key{Key::Alt}, mod{mod}, ch{} {}
Event(std::string&& ch) : key{Key::Char}, mod{0}, ch{ch} {}
std::string const& as_chars() const { return ch; }
inline bool operator==(Key key) const { return this->key == key; }
};
Event poll_event()
{
int ch = ::getch();
if (ch == 10) {
return Event{Key::Enter};
}
else if (ch == 27) {
::nodelay(stdscr, true);
int ch = ::getch();
if (ch == -1) {
::nodelay(stdscr, false);
return Event{Key::Esc};
}
else {
::nodelay(stdscr, false);
return Event{ch};
}
}
else if (ch == KEY_UP) {
return Event{Key::Up};
}
else if (ch == KEY_DOWN) {
return Event{Key::Down};
}
else if (ch == KEY_LEFT) {
return Event{Key::Left};
}
else if (ch == KEY_RIGHT) {
return Event{Key::Right};
}
else if (ch == 127) {
return Event{Key::Backspace};
}
else if (is_utf8_first(ch & 0xFF)) {
::ungetch(ch);
auto ch = get_utf8_char();
return Event{std::move(ch)};
}
else {
return Event{Key::Unknown};
}
}
// wrapper of Ncurses API.
class Ncurses {
public:
Ncurses()
{
::initscr();
::noecho();
::cbreak();
::keypad(stdscr, true);
::ESCDELAY = 25;
start_color();
::init_pair(1, COLOR_WHITE, COLOR_BLACK);
::init_pair(2, COLOR_RED, COLOR_WHITE);
}
~Ncurses() { ::endwin(); }
};
struct Config {
std::string prompt;
size_t y_offset;
public:
void read_from(int argc, char const** argv) {
static_cast<void>(argc);
static_cast<void>(argv);
}
};
// represents a instance of Coco client.
class Coco {
enum class Status {
Selected,
Escaped,
Continue,
};
Config config;
std::vector<std::string> const& lines;
std::vector<std::string> filtered;
std::string query;
size_t cursor = 0;
size_t offset = 0;
public:
Coco(Config const& config, std::vector<std::string> const& lines) : config(config), lines(lines), filtered(lines) {}
std::tuple<bool, std::string> select_line(Ncurses ncurses);
private:
void render_screen();
Status handle_key_event(Event const& ev);
void update_filter_list();
std::vector<std::string> filter_by_regex(std::vector<std::string> const& lines) const;
};
void Coco::render_screen()
{
std::string query_str = config.prompt + query;
::werase(stdscr);
int width, height;
getmaxyx(stdscr, height, width);
static_cast<void>(height);
for (size_t y = 0; y < std::min<size_t>(filtered.size() - offset, width - 1); ++y) {
mvwaddstr(stdscr, y + 1, 0, filtered[y + offset].c_str());
if (y == cursor) {
attrset(COLOR_PAIR(2));
mvwchgat(stdscr, y + 1, 0, -1, A_NORMAL, 2, nullptr);
attrset(COLOR_PAIR(1));
}
}
mvwaddstr(stdscr, 0, 0, query_str.c_str());
::wrefresh(stdscr);
}
auto Coco::handle_key_event(Event const& ev) -> Status
{
if (ev == Key::Enter) {
return filtered.size() > 0 ? Status::Selected : Status::Escaped;
}
else if (ev == Key::Esc) {
return Status::Escaped;
}
else if (ev == Key::Up) {
if (cursor == 0) {
offset = std::max(0, (int)offset - 1);
}
else {
cursor--;
}
return Status::Continue;
}
else if (ev == Key::Down) {
int width, height;
getmaxyx(stdscr, height, width);
if (cursor == static_cast<size_t>(height - 1 - config.y_offset)) {
offset = std::min<size_t>(offset + 1, std::max<int>(0, filtered.size() - height + config.y_offset));
}
else {
cursor = std::min<size_t>(cursor + 1, std::min<size_t>(filtered.size() - offset, height - config.y_offset) - 1);
}
return Status::Continue;
}
else if (ev == Key::Backspace) {
if (!query.empty()) {
pop_back_utf8(query);
update_filter_list();
}
return Status::Continue;
}
else if (ev == Key::Char) {
query += ev.as_chars();
update_filter_list();
return Status::Continue;
}
else {
return Status::Continue;
}
}
std::tuple<bool, std::string> Coco::select_line(Ncurses ncurses)
{
static_cast<void>(ncurses);
render_screen();
while (true) {
Event ev = poll_event();
auto result = handle_key_event(ev);
if (result == Status::Selected) {
return std::make_tuple(true, filtered[cursor]);
}
else if (result == Status::Escaped) {
break;
}
render_screen();
}
return std::make_tuple(false, ""s);
}
void Coco::update_filter_list()
{
filtered = filter_by_regex(lines);
cursor = 0;
offset = 0;
}
std::vector<std::string> Coco::filter_by_regex(std::vector<std::string> const& lines) const
{
if (query.empty()) {
return lines;
}
else {
std::regex re(query);
std::vector<std::string> filtered;
for (auto&& line : lines) {
if (std::regex_search(line, re)) {
filtered.push_back(line);
}
}
return filtered;
}
}
int main(int argc, char const* argv[])
{
std::setlocale(LC_ALL, "");
try {
// read lines from stdin.
std::regex ansi(R"(\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K])");
std::vector<std::string> lines;
for (std::string line; std::getline(std::cin, line);) {
lines.push_back(std::regex_replace(line, ansi, ""));
}
// Initialize Coco application.
Config config;
config.prompt = "QUERY> ";
config.y_offset = 1;
config.read_from(argc, argv);
Coco coco{config, lines};
// reopen file handlers of TTY for Ncurses session.
freopen("/dev/tty", "r", stdin);
freopen("/dev/tty", "w", stdout);
// retrieve a selection from lines.
// note that it ensures to shutdown ncurses when returned.
bool is_selected;
std::string selection;
std::tie(is_selected, selection) = coco.select_line(Ncurses{});
// show selected line.
if (is_selected) {
std::cout << selection << std::endl;
}
return 0;
}
catch (std::exception& e) {
std::cerr << "An error is thrown: " << e.what() << std::endl;
return -1;
}
}
<commit_msg>encapsulate ncurse API<commit_after>#include <ncurses.h>
#include <locale>
#include <chrono>
#include <thread>
#include <string>
#include <vector>
#include <regex>
#include <iostream>
#include <stdexcept>
#include <functional>
#include <nanojson.hpp>
#include <cmdline.h>
using namespace std::literals::string_literals;
using std::string;
using std::tuple;
using std::vector;
bool is_utf8_first(uint8_t ch)
{
return (ch & 0xC0) != 0x80 && (ch & 0xFE) != 0xFE && ((ch & 0x80) == 0 || (ch & 0xC0) == 0xC0);
}
bool is_utf8_cont(uint8_t ch) { return (ch & 0xC0) == 0x80; }
size_t get_utf8_char_length(uint8_t ch)
{
if (!is_utf8_first(ch)) {
throw std::runtime_error(string(__FUNCTION__) + ": the first byte is not UTF8");
}
for (int i = 0; i < 6; ++i) {
if ((ch & (0x01 << (7 - i))) == 0) {
return std::max(1, i);
}
}
throw std::runtime_error(string(__FUNCTION__) + ": unreachable");
}
void pop_back_utf8(std::string& str)
{
if (str.empty())
return;
for (ssize_t len = str.size() - 1; len >= 0; --len) {
if (!is_utf8_cont(str[len])) {
str.resize(len);
return;
}
}
}
enum class Key { Enter, Esc, Alt, Up, Down, Left, Right, Backspace, Char, Unknown };
class Event {
Key key;
int mod;
std::string ch;
public:
Event(Key key) : key{key}, mod{0}, ch{} {}
Event(int mod) : key{Key::Alt}, mod{mod}, ch{} {}
Event(std::string&& ch) : key{Key::Char}, mod{0}, ch{ch} {}
std::string const& as_chars() const { return ch; }
inline bool operator==(Key key) const { return this->key == key; }
};
// wrapper of Ncurses API.
class Ncurses {
public:
Ncurses()
{
::initscr();
::noecho();
::cbreak();
::keypad(stdscr, true);
::ESCDELAY = 25;
start_color();
::init_pair(1, COLOR_WHITE, COLOR_BLACK);
::init_pair(2, COLOR_RED, COLOR_WHITE);
}
~Ncurses() { ::endwin(); }
void erase() { ::werase(stdscr); }
void refresh() { ::wrefresh(stdscr); }
std::tuple<int, int> get_width_height() const
{
int width, height;
getmaxyx(stdscr, height, width);
return std::make_tuple(width, height);
}
void add_string(int x, int y, std::string const& text) { mvwaddstr(stdscr, y, x, text.c_str()); }
void change_attr(int x, int y, int n, int col)
{
attrset(COLOR_PAIR(col));
mvwchgat(stdscr, y, x, n, A_NORMAL, col, nullptr);
attrset(COLOR_PAIR(1));
}
Event poll_event()
{
int ch = ::getch();
if (ch == 10) {
return Event{Key::Enter};
}
else if (ch == 27) {
::nodelay(stdscr, true);
int ch = ::getch();
if (ch == -1) {
::nodelay(stdscr, false);
return Event{Key::Esc};
}
else {
::nodelay(stdscr, false);
return Event{ch};
}
}
else if (ch == KEY_UP) {
return Event{Key::Up};
}
else if (ch == KEY_DOWN) {
return Event{Key::Down};
}
else if (ch == KEY_LEFT) {
return Event{Key::Left};
}
else if (ch == KEY_RIGHT) {
return Event{Key::Right};
}
else if (ch == 127) {
return Event{Key::Backspace};
}
else if (is_utf8_first(ch & 0xFF)) {
::ungetch(ch);
auto ch = get_utf8_char();
return Event{std::move(ch)};
}
else {
return Event{Key::Unknown};
}
}
private:
std::string get_utf8_char()
{
std::array<uint8_t, 6> buf{0};
auto ch0 = static_cast<uint8_t>(::getch() & 0x000000FF);
size_t len = get_utf8_char_length(ch0);
buf[0] = ch0;
for (size_t i = 1; i < len; ++i) {
auto ch = static_cast<uint8_t>(::getch() & 0x000000FF);
if (!is_utf8_cont(ch)) {
throw std::runtime_error(string(__FUNCTION__) + ": wrong byte exists");
}
buf[i] = ch;
}
return std::string(buf.data(), buf.data() + len);
}
};
struct Config {
std::string prompt;
size_t y_offset;
public:
void read_from(int argc, char const** argv)
{
static_cast<void>(argc);
static_cast<void>(argv);
}
};
// represents a instance of Coco client.
class Coco {
enum class Status {
Selected,
Escaped,
Continue,
};
Config config;
std::vector<std::string> const& lines;
std::vector<std::string> filtered;
std::string query;
size_t cursor = 0;
size_t offset = 0;
public:
Coco(Config const& config, std::vector<std::string> const& lines) : config(config), lines(lines), filtered(lines) {}
std::tuple<bool, std::string> select_line(Ncurses term)
{
render_screen(term);
while (true) {
Event ev = term.poll_event();
auto result = handle_key_event(term, ev);
if (result == Status::Selected) {
return std::make_tuple(true, filtered[cursor]);
}
else if (result == Status::Escaped) {
break;
}
render_screen(term);
}
return std::make_tuple(false, ""s);
}
private:
void render_screen(Ncurses& term)
{
std::string query_str = config.prompt + query;
term.erase();
int width;
std::tie(width, std::ignore) = term.get_width_height();
for (size_t y = 0; y < std::min<size_t>(filtered.size() - offset, width - 1); ++y) {
term.add_string(0, y + 1, filtered[y + offset]);
if (y == cursor) {
term.change_attr(0, y + 1, -1, 2);
}
}
term.add_string(0, 0, query_str);
term.refresh();
}
Status handle_key_event(Ncurses& term, Event const& ev)
{
if (ev == Key::Enter) {
return filtered.size() > 0 ? Status::Selected : Status::Escaped;
}
else if (ev == Key::Esc) {
return Status::Escaped;
}
else if (ev == Key::Up) {
if (cursor == 0) {
offset = std::max(0, (int)offset - 1);
}
else {
cursor--;
}
return Status::Continue;
}
else if (ev == Key::Down) {
int height;
std::tie(std::ignore, height) = term.get_width_height();
if (cursor == static_cast<size_t>(height - 1 - config.y_offset)) {
offset = std::min<size_t>(offset + 1, std::max<int>(0, filtered.size() - height + config.y_offset));
}
else {
cursor = std::min<size_t>(cursor + 1, std::min<size_t>(filtered.size() - offset, height - config.y_offset) - 1);
}
return Status::Continue;
}
else if (ev == Key::Backspace) {
if (!query.empty()) {
pop_back_utf8(query);
update_filter_list();
}
return Status::Continue;
}
else if (ev == Key::Char) {
query += ev.as_chars();
update_filter_list();
return Status::Continue;
}
else {
return Status::Continue;
}
}
void update_filter_list()
{
filtered = filter_by_regex(lines);
cursor = 0;
offset = 0;
}
std::vector<std::string> filter_by_regex(std::vector<std::string> const& lines) const
{
if (query.empty()) {
return lines;
}
else {
std::regex re(query);
std::vector<std::string> filtered;
for (auto&& line : lines) {
if (std::regex_search(line, re)) {
filtered.push_back(line);
}
}
return filtered;
}
}
};
int main(int argc, char const* argv[])
{
std::setlocale(LC_ALL, "");
try {
// read lines from stdin.
std::regex ansi(R"(\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K])");
std::vector<std::string> lines;
for (std::string line; std::getline(std::cin, line);) {
lines.push_back(std::regex_replace(line, ansi, ""));
}
// Initialize Coco application.
Config config;
config.prompt = "QUERY> ";
config.y_offset = 1;
config.read_from(argc, argv);
Coco coco{config, lines};
// reopen file handlers of TTY for Ncurses session.
freopen("/dev/tty", "r", stdin);
freopen("/dev/tty", "w", stdout);
// retrieve a selection from lines.
// note that it ensures to shutdown ncurses when returned.
bool is_selected;
std::string selection;
std::tie(is_selected, selection) = coco.select_line(Ncurses{});
// show selected line.
if (is_selected) {
std::cout << selection << std::endl;
}
return 0;
}
catch (std::exception& e) {
std::cerr << "An error is thrown: " << e.what() << std::endl;
return -1;
}
}
<|endoftext|> |
<commit_before><commit_msg>Add alignment requirement to char buffer<commit_after><|endoftext|> |
<commit_before><commit_msg>Cartesian::to_string prints the scaled cartesian<commit_after><|endoftext|> |
<commit_before>/* Copyright (c) 2019, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``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.
*/
#pragma once
#include <stdlib.h>
#include <boost/serialization/shared_ptr.hpp>
#include "model/model-base.hpp"
#include "model/arithmetic.hpp"
#include "model/topology.hpp"
#include "mapping/mapping.hpp"
#include "loop-analysis/nest-analysis.hpp"
#include "compound-config/compound-config.hpp"
namespace model
{
class Engine : public Module
{
public:
struct Specs
{
Topology::Specs topology;
};
private:
// Specs.
Specs specs_;
// Organization.
Topology topology_;
// Utilities.
analysis::NestAnalysis nest_analysis_;
// Serialization.
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const unsigned int version=0)
{
if (version == 0)
{
ar& BOOST_SERIALIZATION_NVP(topology_);
}
}
public:
// The hierarchical ParseSpecs functions are static and do not
// affect the internal specs_ data structure, which is set by
// the dynamic Spec() call later.
static Specs ParseSpecs(config::CompoundConfigNode setting)
{
Specs specs;
std::string version;
if (!setting.exists("version") || (setting.lookupValue("version", version) && version != "0.2")) {
// format used in the ISPASS paper
// std::cout << "ParseSpecs" << std::endl;
auto arithmetic = setting.lookup("arithmetic");
auto topology = setting.lookup("storage");
specs.topology = Topology::ParseSpecs(topology, arithmetic);
} else {
// format used in Accelergy v0.2
// std::cout << "ParseTreeSpecs" << std::endl;
specs.topology = Topology::ParseTreeSpecs(setting);
}
return specs;
}
void Spec(Specs specs)
{
specs_ = specs;
topology_.Spec(specs.topology);
is_specced_ = true;
}
const Topology& GetTopology() const { return topology_; }
std::vector<EvalStatus> PreEvaluationCheck(const Mapping& mapping, problem::Workload& workload, bool break_on_failure = true)
{
nest_analysis_.Init(&workload, &mapping.loop_nest);
return topology_.PreEvaluationCheck(mapping, &nest_analysis_, break_on_failure);
}
std::vector<EvalStatus> Evaluate(Mapping& mapping, problem::Workload& workload, bool break_on_failure = true)
{
nest_analysis_.Init(&workload, &mapping.loop_nest);
auto eval_status = topology_.Evaluate(mapping, &nest_analysis_, workload, break_on_failure);
is_evaluated_ = std::accumulate(eval_status.begin(), eval_status.end(), true,
[](bool cur, const EvalStatus& status)
{ return cur && status.success; });
return eval_status;
}
double Energy() const
{
return topology_.Energy();
}
double Area() const
{
return topology_.Area();
}
std::uint64_t Cycles() const
{
return topology_.Cycles();
}
double Utilization() const
{
return topology_.Utilization();
}
friend std::ostream& operator << (std::ostream& out, Engine& engine)
{
out << engine.topology_;
return out;
}
};
} // namespace model
<commit_msg>[model/engine.hpp] accept v0.3 arch<commit_after>/* Copyright (c) 2019, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``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.
*/
#pragma once
#include <stdlib.h>
#include <boost/serialization/shared_ptr.hpp>
#include "model/model-base.hpp"
#include "model/arithmetic.hpp"
#include "model/topology.hpp"
#include "mapping/mapping.hpp"
#include "loop-analysis/nest-analysis.hpp"
#include "compound-config/compound-config.hpp"
namespace model
{
class Engine : public Module
{
public:
struct Specs
{
Topology::Specs topology;
};
private:
// Specs.
Specs specs_;
// Organization.
Topology topology_;
// Utilities.
analysis::NestAnalysis nest_analysis_;
// Serialization.
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const unsigned int version=0)
{
if (version == 0)
{
ar& BOOST_SERIALIZATION_NVP(topology_);
}
}
public:
// The hierarchical ParseSpecs functions are static and do not
// affect the internal specs_ data structure, which is set by
// the dynamic Spec() call later.
static Specs ParseSpecs(config::CompoundConfigNode setting)
{
Specs specs;
std::string version;
if (!setting.exists("version") || (setting.lookupValue("version", version) && (version != "0.2" && version != "0.3"))) {
// format used in the ISPASS paper
// std::cout << "ParseSpecs" << std::endl;
auto arithmetic = setting.lookup("arithmetic");
auto topology = setting.lookup("storage");
specs.topology = Topology::ParseSpecs(topology, arithmetic);
} else {
// format used in Accelergy v0.2/v0.3
// std::cout << "ParseTreeSpecs" << std::endl;
specs.topology = Topology::ParseTreeSpecs(setting);
}
return specs;
}
void Spec(Specs specs)
{
specs_ = specs;
topology_.Spec(specs.topology);
is_specced_ = true;
}
const Topology& GetTopology() const { return topology_; }
std::vector<EvalStatus> PreEvaluationCheck(const Mapping& mapping, problem::Workload& workload, bool break_on_failure = true)
{
nest_analysis_.Init(&workload, &mapping.loop_nest);
return topology_.PreEvaluationCheck(mapping, &nest_analysis_, break_on_failure);
}
std::vector<EvalStatus> Evaluate(Mapping& mapping, problem::Workload& workload, bool break_on_failure = true)
{
nest_analysis_.Init(&workload, &mapping.loop_nest);
auto eval_status = topology_.Evaluate(mapping, &nest_analysis_, workload, break_on_failure);
is_evaluated_ = std::accumulate(eval_status.begin(), eval_status.end(), true,
[](bool cur, const EvalStatus& status)
{ return cur && status.success; });
return eval_status;
}
double Energy() const
{
return topology_.Energy();
}
double Area() const
{
return topology_.Area();
}
std::uint64_t Cycles() const
{
return topology_.Cycles();
}
double Utilization() const
{
return topology_.Utilization();
}
friend std::ostream& operator << (std::ostream& out, Engine& engine)
{
out << engine.topology_;
return out;
}
};
} // namespace model
<|endoftext|> |
<commit_before><commit_msg>Don't light up form fields we aren't filling, and don't light up the submit button.<commit_after><|endoftext|> |
<commit_before>/**
* Copyright 2014 Truphone
*/
#include "XmppDisconnectCommand.h"
#include <QString>
#include <QObject>
#include "Connection.h"
#include "XmppResourceStore.h"
namespace truphone
{
namespace test
{
namespace cascades
{
const QString XMPPDisconnectCommand::CMD_NAME = "xmppDisconnect";
XMPPDisconnectCommand::XMPPDisconnectCommand(Connection * const socket,
QObject* parent)
: Command(parent),
client(socket)
{
}
XMPPDisconnectCommand::~XMPPDisconnectCommand()
{
}
bool XMPPDisconnectCommand::executeCommand(QStringList * const arguments)
{
bool ret = false;
if (arguments->length() not_eq 1)
{
this->client->write("ERROR: xmppDisconnect <resource>\r\n");
}
else
{
QXmppClient * const client =
XMPPResourceStore::instance()->getFromStore(arguments->first());
arguments->removeFirst();
if (client)
{
client->disconnectFromServer();
XMPPResourceStore::instance()->removeFromStore(arguments->first());
ret = true;
}
else
{
this->client->write("ERROR: Unknown resource\r\n");
}
}
return ret;
}
void XMPPDisconnectCommand::showHelp()
{
this->client->write("> xmppDisconnect <resource>\r\n");
this->client->write("Disconnect a resource's connection.\r\n");
}
} // namespace cascades
} // namespace test
} // namespace truphone
<commit_msg>Fix ASSERT in Disconnect.<commit_after>/**
* Copyright 2014 Truphone
*/
#include "XmppDisconnectCommand.h"
#include <QString>
#include <QObject>
#include "Connection.h"
#include "XmppResourceStore.h"
namespace truphone
{
namespace test
{
namespace cascades
{
const QString XMPPDisconnectCommand::CMD_NAME = "xmppDisconnect";
XMPPDisconnectCommand::XMPPDisconnectCommand(Connection * const socket,
QObject* parent)
: Command(parent),
client(socket)
{
}
XMPPDisconnectCommand::~XMPPDisconnectCommand()
{
}
bool XMPPDisconnectCommand::executeCommand(QStringList * const arguments)
{
bool ret = false;
if (arguments->length() not_eq 1)
{
this->client->write("ERROR: xmppDisconnect <resource>\r\n");
}
else
{
const QString resource = arguments->first();
QXmppClient * const client =
XMPPResourceStore::instance()->getFromStore(resource);
arguments->removeFirst();
if (client)
{
client->disconnectFromServer();
XMPPResourceStore::instance()->removeFromStore(resource);
ret = true;
}
else
{
this->client->write("ERROR: Unknown resource\r\n");
}
}
return ret;
}
void XMPPDisconnectCommand::showHelp()
{
this->client->write("> xmppDisconnect <resource>\r\n");
this->client->write("Disconnect a resource's connection.\r\n");
}
} // namespace cascades
} // namespace test
} // namespace truphone
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_path.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui/npapi_test_helper.h"
#include "chrome/test/ui_test_utils.h"
#if defined(OS_WIN)
static const char kPepperTestPluginName[] = "npapi_pepper_test_plugin.dll";
#elif defined(OS_MACOSX)
static const char kPepperTestPluginName[] = "npapi_pepper_test_plugin.plugin";
#elif defined(OS_LINUX)
static const char kPepperTestPluginName[] = "libnpapi_pepper_test_plugin.so";
#endif
using npapi_test::kTestCompleteCookie;
using npapi_test::kTestCompleteSuccess;
// Helper class pepper NPAPI tests.
class PepperTester : public NPAPITesterBase {
protected:
PepperTester() : NPAPITesterBase(kPepperTestPluginName) {}
virtual void SetUp() {
// TODO(alokp): Remove no-sandbox flag once gpu plugin can run in sandbox.
launch_arguments_.AppendSwitch(switches::kNoSandbox);
launch_arguments_.AppendSwitch(switches::kInternalPepper);
launch_arguments_.AppendSwitch(switches::kEnableGPUPlugin);
NPAPITesterBase::SetUp();
}
};
// Test that a pepper 3d plugin loads and renders.
// TODO(alokp): Enable the test after making sure it works on all platforms
// and buildbots have OpenGL support.
#if defined(OS_WIN)
TEST_F(PepperTester, FAILS_Pepper3D) {
const FilePath dir(FILE_PATH_LITERAL("pepper"));
const FilePath file(FILE_PATH_LITERAL("pepper_3d.html"));
GURL url = ui_test_utils::GetTestUrl(dir, file);
ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
WaitForFinish("pepper_3d", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
action_max_timeout_ms());
}
#endif
<commit_msg>Enabled pepper 3d test after fixing glsl translator. TBR=gman@chromium.org Review URL: http://codereview.chromium.org/2286001<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_path.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui/npapi_test_helper.h"
#include "chrome/test/ui_test_utils.h"
#if defined(OS_WIN)
static const char kPepperTestPluginName[] = "npapi_pepper_test_plugin.dll";
#elif defined(OS_MACOSX)
static const char kPepperTestPluginName[] = "npapi_pepper_test_plugin.plugin";
#elif defined(OS_LINUX)
static const char kPepperTestPluginName[] = "libnpapi_pepper_test_plugin.so";
#endif
using npapi_test::kTestCompleteCookie;
using npapi_test::kTestCompleteSuccess;
// Helper class pepper NPAPI tests.
class PepperTester : public NPAPITesterBase {
protected:
PepperTester() : NPAPITesterBase(kPepperTestPluginName) {}
virtual void SetUp() {
// TODO(alokp): Remove no-sandbox flag once gpu plugin can run in sandbox.
launch_arguments_.AppendSwitch(switches::kNoSandbox);
launch_arguments_.AppendSwitch(switches::kInternalPepper);
launch_arguments_.AppendSwitch(switches::kEnableGPUPlugin);
NPAPITesterBase::SetUp();
}
};
// Test that a pepper 3d plugin loads and renders.
// TODO(alokp): Enable the test after making sure it works on all platforms
// and buildbots have OpenGL support.
#if defined(OS_WIN)
TEST_F(PepperTester, Pepper3D) {
const FilePath dir(FILE_PATH_LITERAL("pepper"));
const FilePath file(FILE_PATH_LITERAL("pepper_3d.html"));
GURL url = ui_test_utils::GetTestUrl(dir, file);
ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
WaitForFinish("pepper_3d", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
action_max_timeout_ms());
}
#endif
<|endoftext|> |
<commit_before>// This file is part of the hdf5_handler implementing for the CF-compliant
// Copyright (c) 2011-2016 The HDF Group, Inc. and OPeNDAP, Inc.
//
// This is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License as published by the Free
// Software Foundation; either version 2.1 of the License, or (at your
// option) any later version.
//
// This software is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
// You can contact The HDF Group, Inc. at 1800 South Oak Street,
// Suite 203, Champaign, IL 61820
/////////////////////////////////////////////////////////////////////////////
/// \file HDF5CFModule.cc
/// \brief This file includes the implementation to distinguish the different categories of HDF5 products for the CF option
///
///
/// \author Kent Yang <myang6@hdfgroup.org>
///
/// Copyright (C) 2011-2016 The HDF Group
///
/// All rights reserved.
#include <InternalErr.h>
#include "HDF5CFModule.h"
using namespace libdap;
H5CFModule check_module(hid_t fileid) {
if (true == check_eos5(fileid))
return HDF_EOS5;
else if(true == check_jpss(fileid))
return HDF5_JPSS;
else
return HDF5_GENERAL;
}
bool check_eos5(hid_t file_id) {
// check HDF-EOS5 group
string eos5_check_group = "/HDFEOS INFORMATION";
string eos5_check_attr = "HDFEOSVersion";
string eos5_dataset = "StructMetadata.0";
htri_t has_eos_group = -1;
bool eos5_module_fields = true;
has_eos_group = H5Lexists(file_id,eos5_check_group.c_str(),H5P_DEFAULT);
if (has_eos_group > 0){
hid_t eos_group_id = -1;
htri_t has_eos_attr = -1;
// Open the group
if((eos_group_id = H5Gopen(file_id, eos5_check_group.c_str(),H5P_DEFAULT))<0) {
string msg = "cannot open the HDF5 group ";
msg += eos5_check_group;
// H5Fclose(file_id);
throw InternalErr(__FILE__, __LINE__, msg);
}
// check the existence of the EOS5 attribute
has_eos_attr = H5Aexists(eos_group_id, eos5_check_attr.c_str());
if (has_eos_attr >0) {
// All HDF-EOS5 conditions are fulfilled, return true;
// Otherwise, return false or throw an error.
htri_t has_eos_dset = -1;
// check the existence of the EOS5 dataset
has_eos_dset = H5Lexists(eos_group_id,eos5_dataset.c_str(),H5P_DEFAULT);
if (has_eos_dset >0) {
// We still need to check if there are non-EOS5 fields that the
// current HDF-EOS5 module cannot handle.
// If yes, the file cannot be handled by the HDF-EOS5 module since
// the current module is very tight to the HDF-EOS5 model.
// We will treat this file as a general HDF5 file.
eos5_module_fields = check_eos5_module_fields(file_id);
return eos5_module_fields;
}
else if(0 == has_eos_dset)
return false;
else {
string msg = "Fail to determine if the HDF5 dataset ";
msg += eos5_dataset;
msg +=" exists ";
H5Gclose(eos_group_id);
// H5Fclose(file_id);
throw InternalErr(__FILE__, __LINE__, msg);
}
}
else if(0 == has_eos_attr)
return false;
else {
string msg = "Fail to determine if the HDF5 attribute ";
msg += eos5_check_attr;
msg +=" exists ";
H5Gclose(eos_group_id);
// H5Fclose(file_id);
throw InternalErr(__FILE__, __LINE__, msg);
}
}
else if( 0 == has_eos_group) {
return false;
}
else {
string msg = "Fail to determine if the HDF5 group ";
msg += eos5_check_group;
msg +=" exists ";
// H5Fclose(file_id);
throw InternalErr(__FILE__, __LINE__, msg);
}
}
bool check_jpss(hid_t fileid) {
// Currently not supported.
return false;
}
bool check_eos5_module_fields(hid_t fileid){
bool ret_value = true;
string eos5_swath_group = "/HDFEOS/SWATHS";
string eos5_grid_group = "/HDFEOS/GRIDS";
string eos5_zas_group = "/HDFEOS/ZAS";
bool swath_unsupported_dset = false;
bool grid_unsupported_dset = false;
bool zas_unsupported_dset = false;
if(H5Lexists(fileid,eos5_swath_group.c_str(),H5P_DEFAULT)>0)
swath_unsupported_dset = grp_has_dset(fileid,eos5_swath_group);
if(swath_unsupported_dset == true)
return false;
else {
if(H5Lexists(fileid,eos5_grid_group.c_str(),H5P_DEFAULT)>0)
grid_unsupported_dset = grp_has_dset(fileid,eos5_grid_group);
if(grid_unsupported_dset == true)
return false;
else {
if(H5Lexists(fileid,eos5_zas_group.c_str(),H5P_DEFAULT)>0)
zas_unsupported_dset = grp_has_dset(fileid,eos5_zas_group);
if(zas_unsupported_dset == true)
return false;
}
}
return ret_value;
}
bool grp_has_dset(hid_t fileid, const string & grp_path ) {
bool ret_value = false;
H5O_info_t oinfo;
if(H5Oget_info_by_name(fileid, grp_path.c_str(),&oinfo,H5P_DEFAULT)<0) {
string msg = "Fail to obtain the HDF5 object information by name for the object.";
msg += grp_path;
throw InternalErr(__FILE__, __LINE__, msg);
}
unsigned nelems = oinfo.rc;
for (unsigned i = 0; i<nelems;i++) {
H5O_info_t s_oinfo;
if(H5Oget_info_by_idx(fileid, grp_path.c_str(), H5_INDEX_NAME, H5_ITER_NATIVE,
i, &s_oinfo, H5P_DEFAULT)<0) {
string msg = "Error obtaining the info for the group";
msg += grp_path;
throw InternalErr(__FILE__, __LINE__, msg);
}
if(s_oinfo.type == H5O_TYPE_DATASET) {
ret_value = true;
break;
}
}
return ret_value;
}
<commit_msg>HFVHANDLER-239, using H5Gget_info to check if the member is an HDF5 dataset. The DAp output can be plotted by Panoply. Dimensions and coordinates are all right.<commit_after>// This file is part of the hdf5_handler implementing for the CF-compliant
// Copyright (c) 2011-2016 The HDF Group, Inc. and OPeNDAP, Inc.
//
// This is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License as published by the Free
// Software Foundation; either version 2.1 of the License, or (at your
// option) any later version.
//
// This software is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
// You can contact The HDF Group, Inc. at 1800 South Oak Street,
// Suite 203, Champaign, IL 61820
/////////////////////////////////////////////////////////////////////////////
/// \file HDF5CFModule.cc
/// \brief This file includes the implementation to distinguish the different categories of HDF5 products for the CF option
///
///
/// \author Kent Yang <myang6@hdfgroup.org>
///
/// Copyright (C) 2011-2016 The HDF Group
///
/// All rights reserved.
#include <InternalErr.h>
#include "HDF5CFModule.h"
using namespace libdap;
H5CFModule check_module(hid_t fileid) {
if (true == check_eos5(fileid))
return HDF_EOS5;
else if(true == check_jpss(fileid))
return HDF5_JPSS;
else
return HDF5_GENERAL;
}
bool check_eos5(hid_t file_id) {
// check HDF-EOS5 group
string eos5_check_group = "/HDFEOS INFORMATION";
string eos5_check_attr = "HDFEOSVersion";
string eos5_dataset = "StructMetadata.0";
htri_t has_eos_group = -1;
bool eos5_module_fields = true;
has_eos_group = H5Lexists(file_id,eos5_check_group.c_str(),H5P_DEFAULT);
if (has_eos_group > 0){
hid_t eos_group_id = -1;
htri_t has_eos_attr = -1;
// Open the group
if((eos_group_id = H5Gopen(file_id, eos5_check_group.c_str(),H5P_DEFAULT))<0) {
string msg = "cannot open the HDF5 group ";
msg += eos5_check_group;
// H5Fclose(file_id);
throw InternalErr(__FILE__, __LINE__, msg);
}
// check the existence of the EOS5 attribute
has_eos_attr = H5Aexists(eos_group_id, eos5_check_attr.c_str());
if (has_eos_attr >0) {
// All HDF-EOS5 conditions are fulfilled, return true;
// Otherwise, return false or throw an error.
htri_t has_eos_dset = -1;
// check the existence of the EOS5 dataset
has_eos_dset = H5Lexists(eos_group_id,eos5_dataset.c_str(),H5P_DEFAULT);
if (has_eos_dset >0) {
// We still need to check if there are non-EOS5 fields that the
// current HDF-EOS5 module cannot handle.
// If yes, the file cannot be handled by the HDF-EOS5 module since
// the current module is very tight to the HDF-EOS5 model.
// We will treat this file as a general HDF5 file.
eos5_module_fields = check_eos5_module_fields(file_id);
return eos5_module_fields;
}
else if(0 == has_eos_dset)
return false;
else {
string msg = "Fail to determine if the HDF5 dataset ";
msg += eos5_dataset;
msg +=" exists ";
H5Gclose(eos_group_id);
// H5Fclose(file_id);
throw InternalErr(__FILE__, __LINE__, msg);
}
}
else if(0 == has_eos_attr)
return false;
else {
string msg = "Fail to determine if the HDF5 attribute ";
msg += eos5_check_attr;
msg +=" exists ";
H5Gclose(eos_group_id);
// H5Fclose(file_id);
throw InternalErr(__FILE__, __LINE__, msg);
}
}
else if( 0 == has_eos_group) {
return false;
}
else {
string msg = "Fail to determine if the HDF5 group ";
msg += eos5_check_group;
msg +=" exists ";
// H5Fclose(file_id);
throw InternalErr(__FILE__, __LINE__, msg);
}
}
bool check_jpss(hid_t fileid) {
// Currently not supported.
return false;
}
bool check_eos5_module_fields(hid_t fileid){
bool ret_value = true;
string eos5_swath_group = "/HDFEOS/SWATHS";
string eos5_grid_group = "/HDFEOS/GRIDS";
string eos5_zas_group = "/HDFEOS/ZAS";
bool swath_unsupported_dset = false;
bool grid_unsupported_dset = false;
bool zas_unsupported_dset = false;
if(H5Lexists(fileid,eos5_swath_group.c_str(),H5P_DEFAULT)>0)
swath_unsupported_dset = grp_has_dset(fileid,eos5_swath_group);
if(swath_unsupported_dset == true)
return false;
else {
if(H5Lexists(fileid,eos5_grid_group.c_str(),H5P_DEFAULT)>0)
grid_unsupported_dset = grp_has_dset(fileid,eos5_grid_group);
if(grid_unsupported_dset == true)
return false;
else {
if(H5Lexists(fileid,eos5_zas_group.c_str(),H5P_DEFAULT)>0)
zas_unsupported_dset = grp_has_dset(fileid,eos5_zas_group);
if(zas_unsupported_dset == true)
return false;
}
}
return ret_value;
}
bool grp_has_dset(hid_t fileid, const string & grp_path ) {
bool ret_value = false;
hid_t pid = -1;
if((pid = H5Gopen(fileid,grp_path.c_str(),H5P_DEFAULT))<0){
string msg = "Unable to open the HDF5 group ";
msg += grp_path;
throw InternalErr(__FILE__, __LINE__, msg);
}
H5G_info_t g_info;
if (H5Gget_info(pid, &g_info) < 0) {
H5Gclose(pid);
string msg = "Unable to obtain the HDF5 group info. for ";
msg += grp_path;
throw InternalErr(__FILE__, __LINE__, msg);
}
hsize_t nelems = g_info.nlinks;
for (hsize_t i = 0; i < nelems; i++) {
// Obtain the object type
H5O_info_t oinfo;
if (H5Oget_info_by_idx(pid, ".", H5_INDEX_NAME, H5_ITER_NATIVE, i, &oinfo, H5P_DEFAULT) < 0) {
string msg = "Cannot obtain the object info for the group";
msg += grp_path;
throw InternalErr(__FILE__, __LINE__, msg);
}
if(oinfo.type == H5O_TYPE_DATASET) {
ret_value = true;
break;
}
}
H5Gclose(pid);
return ret_value;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.