<commit_before>// DXGL
// Copyright (C) 2013 William Feely

// 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include "common.h"
#include "glDirect3DExecuteBuffer.h"

glDirect3DExecuteBuffer::glDirect3DExecuteBuffer(LPD3DEXECUTEBUFFERDESC lpDesc)
{
	locked = false;
	inuse = false;
	data = NULL;
	desc = *lpDesc;
	if(!(desc.dwFlags & D3DDEB_CAPS))
	{
		desc.dwFlags |= D3DDEB_CAPS;
		desc.dwCaps = D3DDEBCAPS_MEM;
	}
	ZeroMemory(&datadesc,sizeof(D3DEXECUTEDATA));
	datadesc.dwSize = sizeof(D3DEXECUTEDATA);
}
glDirect3DExecuteBuffer::~glDirect3DExecuteBuffer()
{
	if(data) free(data);
}

HRESULT WINAPI glDirect3DExecuteBuffer::QueryInterface(REFIID riid, void** ppvObj)
{
	if(!this) return DDERR_INVALIDOBJECT;
	if((riid == IID_IUnknown) || (riid == IID_IDirect3DExecuteBuffer))
	{
		this->AddRef();
		*ppvObj = this;
		return D3D_OK;
	}
	return E_NOINTERFACE;
}

ULONG WINAPI glDirect3DExecuteBuffer::AddRef()
{
	if(!this) return 0;
	refcount++;
	return refcount;
}

ULONG WINAPI glDirect3DExecuteBuffer::Release()
{
	if(!this) return 0;
	ULONG ret;
	refcount--;
	ret = refcount;
	if(refcount == 0) delete this;
	return ret;
}

HRESULT WINAPI glDirect3DExecuteBuffer::GetExecuteData(LPD3DEXECUTEDATA lpData)
{
	if(!this) return DDERR_INVALIDOBJECT;
	if(!lpData) return DDERR_INVALIDPARAMS;
	if(locked) return D3DERR_EXECUTE_LOCKED;
	if(lpData->dwSize < sizeof(D3DEXECUTEDATA)) return DDERR_INVALIDPARAMS;
	memcpy(lpData,&datadesc,sizeof(D3DEXECUTEDATA));
	return D3D_OK;
}

HRESULT WINAPI glDirect3DExecuteBuffer::Initialize(LPDIRECT3DDEVICE lpDirect3DDevice,
	LPD3DEXECUTEBUFFERDESC lpDesc)
{
	if(!this) return DDERR_INVALIDOBJECT;
	return DDERR_ALREADYINITIALIZED;
}

HRESULT WINAPI glDirect3DExecuteBuffer::Lock(LPD3DEXECUTEBUFFERDESC lpDesc)
{
	if(!this) return  DDERR_INVALIDOBJECT;
	if(!lpDesc) return DDERR_INVALIDPARAMS;
	if(lpDesc->dwSize < sizeof(D3DEXECUTEBUFFERDESC)) return DDERR_INVALIDPARAMS;
	if(inuse) return DDERR_WASSTILLDRAWING;
	if(locked) return D3DERR_EXECUTE_LOCKED;
	desc.dwCaps = lpDesc->dwCaps;
	desc.dwFlags |= D3DDEB_LPDATA;
	if(!data)
	{
		data = (unsigned char *)malloc(desc.dwBufferSize);
		if(!data) return DDERR_OUTOFMEMORY;
	}
	desc.lpData = data;
	memcpy(lpDesc,&desc,sizeof(D3DEXECUTEBUFFERDESC));
	locked = true;
	return D3D_OK;
}

HRESULT WINAPI glDirect3DExecuteBuffer::Optimize(DWORD dwDummy)
{
	if(!this) return DDERR_INVALIDOBJECT;
	return DDERR_UNSUPPORTED;
}

HRESULT WINAPI glDirect3DExecuteBuffer::SetExecuteData(LPD3DEXECUTEDATA lpData)
{
	if(!this) return DDERR_INVALIDOBJECT;
	if(!lpData) return DDERR_INVALIDPARAMS;
	if(lpData->dwSize != sizeof(D3DEXECUTEDATA)) return DDERR_INVALIDPARAMS;
	memcpy(&data,lpData,sizeof(D3DEXECUTEDATA));
	return D3D_OK;
}

HRESULT WINAPI glDirect3DExecuteBuffer::Unlock()
{
	if(!this) return DDERR_INVALIDOBJECT;
	if(inuse) return D3DERR_EXECUTE_NOT_LOCKED;
	if(!locked) return D3DERR_EXECUTE_NOT_LOCKED;
	locked = false;
	return D3D_OK;
}

HRESULT glDirect3DExecuteBuffer::ExecuteLock(LPD3DEXECUTEBUFFERDESC lpDesc,LPD3DEXECUTEDATA lpData)
{
	if(!this) return DDERR_INVALIDOBJECT;
	if(inuse) return DDERR_WASSTILLDRAWING;
	if(locked) return D3DERR_EXECUTE_LOCKED;
	if(!lpDesc) return DDERR_INVALIDPARAMS;
	if(!lpData) return DDERR_INVALIDPARAMS;
	desc.dwFlags |= D3DDEB_LPDATA;
	if(!data)
	{
		data = (unsigned char *)malloc(desc.dwBufferSize);
		if(!data) return DDERR_OUTOFMEMORY;
	}
	desc.lpData = data;
	memcpy(lpDesc,&desc,sizeof(D3DEXECUTEBUFFERDESC));
	memcpy(lpData,&datadesc,sizeof(D3DEXECUTEDATA));
	locked = true;
	inuse = true;
	return D3D_OK;
}

HRESULT glDirect3DExecuteBuffer::ExecuteUnlock()
{
	if(!this) return DDERR_INVALIDOBJECT;
	if(!inuse) return D3DERR_EXECUTE_NOT_LOCKED;
	inuse = false;
	locked = false;
	return D3D_OK;
}<commit_msg>Add missing Validate stub to IDirect3DExecuteBuffer.<commit_after>// DXGL
// Copyright (C) 2013 William Feely

// 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include "common.h"
#include "glDirect3DExecuteBuffer.h"

glDirect3DExecuteBuffer::glDirect3DExecuteBuffer(LPD3DEXECUTEBUFFERDESC lpDesc)
{
	locked = false;
	inuse = false;
	data = NULL;
	desc = *lpDesc;
	if(!(desc.dwFlags & D3DDEB_CAPS))
	{
		desc.dwFlags |= D3DDEB_CAPS;
		desc.dwCaps = D3DDEBCAPS_MEM;
	}
	ZeroMemory(&datadesc,sizeof(D3DEXECUTEDATA));
	datadesc.dwSize = sizeof(D3DEXECUTEDATA);
}
glDirect3DExecuteBuffer::~glDirect3DExecuteBuffer()
{
	if(data) free(data);
}

HRESULT WINAPI glDirect3DExecuteBuffer::QueryInterface(REFIID riid, void** ppvObj)
{
	if(!this) return DDERR_INVALIDOBJECT;
	if((riid == IID_IUnknown) || (riid == IID_IDirect3DExecuteBuffer))
	{
		this->AddRef();
		*ppvObj = this;
		return D3D_OK;
	}
	return E_NOINTERFACE;
}

ULONG WINAPI glDirect3DExecuteBuffer::AddRef()
{
	if(!this) return 0;
	refcount++;
	return refcount;
}

ULONG WINAPI glDirect3DExecuteBuffer::Release()
{
	if(!this) return 0;
	ULONG ret;
	refcount--;
	ret = refcount;
	if(refcount == 0) delete this;
	return ret;
}

HRESULT WINAPI glDirect3DExecuteBuffer::GetExecuteData(LPD3DEXECUTEDATA lpData)
{
	if(!this) return DDERR_INVALIDOBJECT;
	if(!lpData) return DDERR_INVALIDPARAMS;
	if(locked) return D3DERR_EXECUTE_LOCKED;
	if(lpData->dwSize < sizeof(D3DEXECUTEDATA)) return DDERR_INVALIDPARAMS;
	memcpy(lpData,&datadesc,sizeof(D3DEXECUTEDATA));
	return D3D_OK;
}

HRESULT WINAPI glDirect3DExecuteBuffer::Initialize(LPDIRECT3DDEVICE lpDirect3DDevice,
	LPD3DEXECUTEBUFFERDESC lpDesc)
{
	if(!this) return DDERR_INVALIDOBJECT;
	return DDERR_ALREADYINITIALIZED;
}

HRESULT WINAPI glDirect3DExecuteBuffer::Lock(LPD3DEXECUTEBUFFERDESC lpDesc)
{
	if(!this) return  DDERR_INVALIDOBJECT;
	if(!lpDesc) return DDERR_INVALIDPARAMS;
	if(lpDesc->dwSize < sizeof(D3DEXECUTEBUFFERDESC)) return DDERR_INVALIDPARAMS;
	if(inuse) return DDERR_WASSTILLDRAWING;
	if(locked) return D3DERR_EXECUTE_LOCKED;
	desc.dwCaps = lpDesc->dwCaps;
	desc.dwFlags |= D3DDEB_LPDATA;
	if(!data)
	{
		data = (unsigned char *)malloc(desc.dwBufferSize);
		if(!data) return DDERR_OUTOFMEMORY;
	}
	desc.lpData = data;
	memcpy(lpDesc,&desc,sizeof(D3DEXECUTEBUFFERDESC));
	locked = true;
	return D3D_OK;
}

HRESULT WINAPI glDirect3DExecuteBuffer::Optimize(DWORD dwDummy)
{
	if(!this) return DDERR_INVALIDOBJECT;
	return DDERR_UNSUPPORTED;
}

HRESULT WINAPI glDirect3DExecuteBuffer::SetExecuteData(LPD3DEXECUTEDATA lpData)
{
	if(!this) return DDERR_INVALIDOBJECT;
	if(!lpData) return DDERR_INVALIDPARAMS;
	if(lpData->dwSize != sizeof(D3DEXECUTEDATA)) return DDERR_INVALIDPARAMS;
	memcpy(&data,lpData,sizeof(D3DEXECUTEDATA));
	return D3D_OK;
}

HRESULT WINAPI glDirect3DExecuteBuffer::Unlock()
{
	if(!this) return DDERR_INVALIDOBJECT;
	if(inuse) return D3DERR_EXECUTE_NOT_LOCKED;
	if(!locked) return D3DERR_EXECUTE_NOT_LOCKED;
	locked = false;
	return D3D_OK;
}

HRESULT WINAPI glDirect3DExecuteBuffer::Validate(LPDWORD lpdwOffset, LPD3DVALIDATECALLBACK lpFunc, LPVOID lpUserArg, DWORD dwReserved)
{
	if(!this) return DDERR_INVALIDOBJECT;
	return DDERR_UNSUPPORTED;
}

HRESULT glDirect3DExecuteBuffer::ExecuteLock(LPD3DEXECUTEBUFFERDESC lpDesc,LPD3DEXECUTEDATA lpData)
{
	if(!this) return DDERR_INVALIDOBJECT;
	if(inuse) return DDERR_WASSTILLDRAWING;
	if(locked) return D3DERR_EXECUTE_LOCKED;
	if(!lpDesc) return DDERR_INVALIDPARAMS;
	if(!lpData) return DDERR_INVALIDPARAMS;
	desc.dwFlags |= D3DDEB_LPDATA;
	if(!data)
	{
		data = (unsigned char *)malloc(desc.dwBufferSize);
		if(!data) return DDERR_OUTOFMEMORY;
	}
	desc.lpData = data;
	memcpy(lpDesc,&desc,sizeof(D3DEXECUTEBUFFERDESC));
	memcpy(lpData,&datadesc,sizeof(D3DEXECUTEDATA));
	locked = true;
	inuse = true;
	return D3D_OK;
}

HRESULT glDirect3DExecuteBuffer::ExecuteUnlock()
{
	if(!this) return DDERR_INVALIDOBJECT;
	if(!inuse) return D3DERR_EXECUTE_NOT_LOCKED;
	inuse = false;
	locked = false;
	return D3D_OK;
}<|endoftext|>


<commit_before>/*
    Copyright (c) 2009 Stephen Kelly <steveire@gmail.com>
*/

#include "for.h"

#include <QStringList>

#include "parser.h"

#include <QDebug>

ForNodeFactory::ForNodeFactory()
{

}

Node* ForNodeFactory::getNode(const QString &tagContent, Parser *p, QObject *parent) const
{
  QStringList expr = smartSplit(tagContent);

  expr.takeAt(0);
  QList<QString> vars;

  int reversed = ForNode::IsNotReversed;
  if (expr.last() == "reversed")
  {
    reversed = ForNode::IsReversed;
    expr.removeLast();
  }

  foreach(const QString &arg, expr.mid(0, expr.size() -2))
  {
    vars << arg.split(",", QString::SkipEmptyParts);
  }

  FilterExpression fe(expr.last(), p);

  NodeList loopNodes = p->parse(QStringList() << "empty" << "endfor", parent);
  NodeList emptyNodes;
  if (p->nextToken().content.trimmed() == "empty")
  {
    emptyNodes = p->parse(QStringList() << "endfor", parent);
    // skip past the endfor tag
    p->deleteNextToken();
  }

  return new ForNode(vars, fe, reversed, loopNodes, emptyNodes, parent);
}

ForNode::ForNode( QStringList loopVars,
                  FilterExpression fe,
                  int reversed,
                  NodeList loopNodeList,
                  NodeList emptyNodes,
                  QObject *parent )
  : Node(parent),
  m_loopVars(loopVars),
  m_filterExpression(fe),
  m_isReversed(reversed),
  m_loopNodeList(loopNodeList),
  m_emptyNodeList(emptyNodes)
{

}

// some magic variables injected into the context while rendering.
const QString forloop("forloop");
const QString parentloop("parentloop");
const QString counter0("counter0");
const QString counter("counter");
const QString revcounter0("revcounter0");
const QString revcounter("revcounter");
const QString first("first");
const QString last("last");

void ForNode::insertLoopVariables(Context *c, int listSize, int i)
{
  QVariantMap forloopMap = c->lookup("forloop").toMap();
  forloopMap.insert(counter0, i);
  forloopMap.insert(counter, i + 1);
  forloopMap.insert(revcounter, listSize - i );
  forloopMap.insert(revcounter0, listSize - i -1 );
  forloopMap.insert(first, ( i == 0 ) );
  forloopMap.insert(last, ( i == listSize - 1 ) );
  c->insert(forloop, forloopMap);
}

QString ForNode::renderLoop(Context *c)
{
  QString result;
  for (int j = 0; j < m_loopNodeList.size();j++)
  {
    result += m_loopNodeList[j]->render(c);
  }
  return result;
}

QString ForNode::handleMapItem(Context *c, QString key, QVariant value, int listSize, int i, bool unpack)
{
  QVariantList list;
  insertLoopVariables(c, listSize, i);

  if (!unpack)
  {
    // Iterating over a map but not unpacking it.
    // convert each key-value pair to a list and insert it in the context.
    list << key << value;
    c->insert(m_loopVars.at(0), list);
    list.clear();
  } else {
    c->insert(m_loopVars.at(0), key);
    c->insert(m_loopVars.at(1), value);
  }
  return renderLoop(c);
}

QString ForNode::iterateMap(Context *c, QVariantMap varMap, bool unpack)
{
  QString result;

  int listSize = varMap.size();
  int i = 0;
  QVariantList list;

  QMapIterator<QString, QVariant> it(varMap);
  if (m_isReversed == IsReversed)
  {
    while (it.hasPrevious())
    {
      it.previous();
      result += handleMapItem(c, it.key(), it.value(), listSize, i, unpack);
      ++i;
    }
  } else {
    while (it.hasNext())
    {
      it.next();
      result += handleMapItem(c, it.key(), it.value(), listSize, i, unpack);
      ++i;
    }
  }
  return result;
}

QString ForNode::render(Context *c)
{
  QString result;
  QMap<QString, QVariant> forloopMap;

  QVariant parentLoopVariant = c->lookup(forloop);
  QMap<QString, QVariant> parentLoopMap;
  if (parentLoopVariant.isValid())
  {
    // This is a nested loop.
    forloopMap = parentLoopVariant.toMap();
    forloopMap.insert(parentloop, parentLoopVariant.toMap());
    c->insert(forloop, forloopMap);
  }

  bool unpack = m_loopVars.size() > 1;

  QVariant var = m_filterExpression.resolve(c);

  c->push();

  if (var.type() == QVariant::Map)
  {
    QVariantMap varMap = var.toMap();
    result = iterateMap(c, varMap, unpack);
    c->pop();
    return result;
  }

  // If it's an iterable type, iterate, otherwise it's a list of one.
  QVariantList varList = m_filterExpression.toList(c);
  NodeList nodeList;
  int listSize = varList.size();

  if (listSize < 1)
  {
    c->pop();
    return m_emptyNodeList.render(c);
  }

  for (int i = 0; i < listSize; i++)
  {
    insertLoopVariables(c, listSize, i);

    int index = i;
    if (m_isReversed == IsReversed)
    {
      index = listSize - i - 1;
    }

    if (unpack)
    {
      if (varList[index].type() == QVariant::List)
      {
        QVariantList vList = varList[index].toList();
        int varsSize = qMin(m_loopVars.size(), vList.size());
        for (int j = 0; j < varsSize; ++j)
        {
          c->insert(m_loopVars.at(j), vList.at(j));
        }

      } else {
        // We don't have a map, but we have to unpack several values from each item
        // in the list. And each item in the list is not itself a list.
        // Probably have a list of objects that we're taking properties from.
        foreach(const QString &loopVar, m_loopVars)
        {
          c->push();
          c->insert("var", varList[index]);
          QVariant v = FilterExpression("var." + loopVar, 0).resolve(c);
          c->pop();
          c->insert(loopVar, v);
        }
      }
    } else {
      c->insert(m_loopVars[0], varList[index]);
    }
    result += renderLoop(c);
  }
  c->pop();
  return result;
}
<commit_msg>Handle special case of missing variables when unpacking items from lists.<commit_after>/*
    Copyright (c) 2009 Stephen Kelly <steveire@gmail.com>
*/

#include "for.h"

#include <QStringList>

#include "parser.h"

#include <QDebug>

ForNodeFactory::ForNodeFactory()
{

}

Node* ForNodeFactory::getNode(const QString &tagContent, Parser *p, QObject *parent) const
{
  QStringList expr = smartSplit(tagContent);

  expr.takeAt(0);
  QList<QString> vars;

  int reversed = ForNode::IsNotReversed;
  if (expr.last() == "reversed")
  {
    reversed = ForNode::IsReversed;
    expr.removeLast();
  }

  foreach(const QString &arg, expr.mid(0, expr.size() -2))
  {
    vars << arg.split(",", QString::SkipEmptyParts);
  }

  FilterExpression fe(expr.last(), p);

  NodeList loopNodes = p->parse(QStringList() << "empty" << "endfor", parent);
  NodeList emptyNodes;
  if (p->nextToken().content.trimmed() == "empty")
  {
    emptyNodes = p->parse(QStringList() << "endfor", parent);
    // skip past the endfor tag
    p->deleteNextToken();
  }

  return new ForNode(vars, fe, reversed, loopNodes, emptyNodes, parent);
}

ForNode::ForNode( QStringList loopVars,
                  FilterExpression fe,
                  int reversed,
                  NodeList loopNodeList,
                  NodeList emptyNodes,
                  QObject *parent )
  : Node(parent),
  m_loopVars(loopVars),
  m_filterExpression(fe),
  m_isReversed(reversed),
  m_loopNodeList(loopNodeList),
  m_emptyNodeList(emptyNodes)
{

}

// some magic variables injected into the context while rendering.
const QString forloop("forloop");
const QString parentloop("parentloop");
const QString counter0("counter0");
const QString counter("counter");
const QString revcounter0("revcounter0");
const QString revcounter("revcounter");
const QString first("first");
const QString last("last");

void ForNode::insertLoopVariables(Context *c, int listSize, int i)
{
  QVariantMap forloopMap = c->lookup("forloop").toMap();
  forloopMap.insert(counter0, i);
  forloopMap.insert(counter, i + 1);
  forloopMap.insert(revcounter, listSize - i );
  forloopMap.insert(revcounter0, listSize - i -1 );
  forloopMap.insert(first, ( i == 0 ) );
  forloopMap.insert(last, ( i == listSize - 1 ) );
  c->insert(forloop, forloopMap);
}

QString ForNode::renderLoop(Context *c)
{
  QString result;
  for (int j = 0; j < m_loopNodeList.size();j++)
  {
    result += m_loopNodeList[j]->render(c);
  }
  return result;
}

QString ForNode::handleMapItem(Context *c, QString key, QVariant value, int listSize, int i, bool unpack)
{
  QVariantList list;
  insertLoopVariables(c, listSize, i);

  if (!unpack)
  {
    // Iterating over a map but not unpacking it.
    // convert each key-value pair to a list and insert it in the context.
    list << key << value;
    c->insert(m_loopVars.at(0), list);
    list.clear();
  } else {
    c->insert(m_loopVars.at(0), key);
    c->insert(m_loopVars.at(1), value);
  }
  return renderLoop(c);
}

QString ForNode::iterateMap(Context *c, QVariantMap varMap, bool unpack)
{
  QString result;

  int listSize = varMap.size();
  int i = 0;
  QVariantList list;

  QMapIterator<QString, QVariant> it(varMap);
  if (m_isReversed == IsReversed)
  {
    while (it.hasPrevious())
    {
      it.previous();
      result += handleMapItem(c, it.key(), it.value(), listSize, i, unpack);
      ++i;
    }
  } else {
    while (it.hasNext())
    {
      it.next();
      result += handleMapItem(c, it.key(), it.value(), listSize, i, unpack);
      ++i;
    }
  }
  return result;
}

QString ForNode::render(Context *c)
{
  QString result;
  QMap<QString, QVariant> forloopMap;

  QVariant parentLoopVariant = c->lookup(forloop);
  QMap<QString, QVariant> parentLoopMap;
  if (parentLoopVariant.isValid())
  {
    // This is a nested loop.
    forloopMap = parentLoopVariant.toMap();
    forloopMap.insert(parentloop, parentLoopVariant.toMap());
    c->insert(forloop, forloopMap);
  }

  bool unpack = m_loopVars.size() > 1;

  QVariant var = m_filterExpression.resolve(c);

  c->push();

  if (var.type() == QVariant::Map)
  {
    QVariantMap varMap = var.toMap();
    result = iterateMap(c, varMap, unpack);
    c->pop();
    return result;
  }

  // If it's an iterable type, iterate, otherwise it's a list of one.
  QVariantList varList = m_filterExpression.toList(c);
  NodeList nodeList;
  int listSize = varList.size();

  if (listSize < 1)
  {
    c->pop();
    return m_emptyNodeList.render(c);
  }

  for (int i = 0; i < listSize; i++)
  {
    insertLoopVariables(c, listSize, i);

    int index = i;
    if (m_isReversed == IsReversed)
    {
      index = listSize - i - 1;
    }

    if (unpack)
    {
      if (varList[index].type() == QVariant::List)
      {
        QVariantList vList = varList[index].toList();
        int varsSize = qMin(m_loopVars.size(), vList.size());
        int j = 0;
        for ( ; j < varsSize; ++j)
        {
          c->insert(m_loopVars.at(j), vList.at(j));
        }
        // If any of the named vars don't have an item in the context,
        // insert an invalid object for them.
        for ( ; j < m_loopVars.size(); ++j)
        {
          c->insert(m_loopVars.at(j), QVariant());
        }

      } else {
        // We don't have a map, but we have to unpack several values from each item
        // in the list. And each item in the list is not itself a list.
        // Probably have a list of objects that we're taking properties from.
        foreach(const QString &loopVar, m_loopVars)
        {
          c->push();
          c->insert("var", varList[index]);
          QVariant v = FilterExpression("var." + loopVar, 0).resolve(c);
          c->pop();
          c->insert(loopVar, v);
        }
      }
    } else {
      c->insert(m_loopVars[0], varList[index]);
    }
    result += renderLoop(c);
  }
  c->pop();
  return result;
}
<|endoftext|>


<commit_before>/* KPilot
**
** Copyright (C) 2001 by Dan Pilone
** Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>
**
** This file specializes SyncAction to a kind that can have interaction
** with the user without the Sync timing out.
*/

/*
** 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 in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org.
*/

static const char *interactivesync_id =
	"$Id$";

#include "options.h"

#include <time.h>
#include <unistd.h>
#include <stdio.h>

#include <pi-socket.h>
#include <pi-file.h>

#include <qtimer.h>
#include <qvbox.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qmessagebox.h>
#include <qdir.h>
#include <qfile.h>
#include <qfileinfo.h>
#include <qtl.h>
#include <qstyle.h>
#include <qtextcodec.h>

#include <kdialogbase.h>
#include <kglobal.h>
#include <kstandarddirs.h>
#include <kmessagebox.h>

#include <kapplication.h>

#include "pilotUser.h"
#include "pilotAppCategory.h"
#include "pilotLocalDatabase.h"
#include "kpilotConfig.h"
#include "kpilotlink.h"

#include "interactiveSync.moc"

CheckUser::CheckUser(KPilotDeviceLink * p, QWidget * vp):
	SyncAction(p, vp, "userCheck")
{
	FUNCTIONSETUP;

	(void) interactivesync_id;
}

CheckUser::~CheckUser()
{
	FUNCTIONSETUP;
}

/* virtual */ bool CheckUser::exec()
{
	FUNCTIONSETUP;

	QString guiUserName = KPilotSettings::userName();
	QString pilotUserName = PilotAppCategory::codec()->
		toUnicode(fHandle->getPilotUser()->getUserName());
	bool pilotUserEmpty = pilotUserName.isEmpty();
	// 4 cases to handle:
	//    guiUserName empty / not empty
	//    pilotUserName empty / not empty
	//
	//
	if (guiUserName.isEmpty())
	{
		if (pilotUserEmpty)
		{
			QString defaultUserName =
				i18n("A common name", "John Doe");

			QString q = i18n("<qt>Neither KPilot nor the "
				"handheld have a username set. "
				"They should be set. "
				"Should KPilot set them to a default value "
				"(%1)?</qt>").arg(defaultUserName);

			if (questionYesNo(q, i18n("User Unknown") /* ,"askUserNone" */) ==
				KMessageBox::Yes)
			{
				KPilotSettings::setUserName(defaultUserName);
				fHandle->getPilotUser()->
					setUserName(PilotAppCategory::codec()->fromUnicode(defaultUserName));
				guiUserName=defaultUserName;
				pilotUserName=defaultUserName;
			}

		}
		else
		{
			QString q = i18n("<qt>The handheld has a username set "
				"(%1) but KPilot does not. Should "
				"KPilot use this username in future?").
				arg(pilotUserName);

			if (questionYesNo(q, i18n("User Unknown") /* ,"askUserSome" */ ) ==
				KMessageBox::Yes)
			{
				KPilotSettings::setUserName(pilotUserName);
				guiUserName=pilotUserName;
			}
		}
	}
	else
	{
		if (pilotUserEmpty)
		{
			QString q = i18n("<qt>KPilot has a username set "
				"(%1) but the handheld does not. "
				"Should KPilot's username be set in the "
				"handheld as well?").arg(guiUserName);

			if (questionYesNo(q, i18n("User Unknown") /* ,"askUserSome" */) ==
				KMessageBox::Yes)
			{
#ifdef DEBUG
				DEBUGDAEMON << fname
					<< ": Setting user name in pilot"
					<< endl;
#endif

				const char *l1 = PilotAppCategory::codec()->fromUnicode(guiUserName);

#ifdef DEBUG
				DEBUGDAEMON << fname
					<< ": Setting to " << l1 << endl;
#endif

				fHandle->getPilotUser()->setUserName(l1);
				pilotUserName=guiUserName;
			}
		}
		else
		{
			if (guiUserName != pilotUserName)
			{
				QString q = i18n("<qt>The handheld thinks that "
					"the username is %1; "
					"however, KPilot says you are %2."
					"Which of these is the correct name?\n"
					"If you click on Cancel, the sync will proceed, "
					"but the usernames will not be changed.").
					arg(pilotUserName).
					arg(guiUserName);

				int r = questionYesNoCancel(q,
					i18n("User Mismatch"),
					QString::null,
					20,
					i18n("Use KPilot Name"),
					i18n("Use Handheld Name"));
				switch (r)
				{
				case KMessageBox::Yes:
					fHandle->getPilotUser()->setUserName(
						PilotAppCategory::codec()->fromUnicode(guiUserName));
					pilotUserName=guiUserName;
					break;
				case KMessageBox::No:
					KPilotSettings::setUserName(pilotUserName);
					guiUserName=pilotUserName;
					break;
				case KMessageBox::Cancel:
				default:
					// TODO: cancel the sync... Or just don't change any user name?
					break;
				}
			}
		}
	}

#ifdef DEBUG
	DEBUGCONDUIT << fname
		<< ": User name set to <"
		<< guiUserName
		<< ">"
		<< endl;
#endif

	KPilotSettings::writeConfig();

	// Now we've established which user will be used,
	// fix the database location for local databases.
	//
	//
	QString pathName = KGlobal::dirs()->saveLocation("data",
		CSL1("kpilot/DBBackup/"));
	if (!guiUserName.isEmpty())
	{
		pathName.append(guiUserName);
		pathName.append(CSL1("/"));
	}
	PilotLocalDatabase::setDBPath(pathName);

	emit syncDone(this);
	return true;
}

class RestoreInfo
{
public:
	struct db DBInfo;
	QString path;
} ;

class RestoreAction::RestoreActionPrivate
{
public:
	QString fDatabaseDir;
	QValueList<RestoreInfo *> fDBList;
	QTimer fTimer;
	QValueList<RestoreInfo *>::ConstIterator fDBIterator;
	int fDBIndex;
};

RestoreAction::RestoreAction(KPilotDeviceLink * p, QWidget * visible ) :
	SyncAction(p, visible, "restoreAction")
{
	FUNCTIONSETUP;

	fP = new RestoreActionPrivate;
	fP->fDatabaseDir = KGlobal::dirs()->saveLocation("data",
		CSL1("kpilot/DBBackup/"));
}

/* virtual */ bool RestoreAction::exec()
{
	FUNCTIONSETUP;

#ifdef DEBUG
	DEBUGDAEMON << fname
		<< ": Restoring from base directory "
		<< *(PilotLocalDatabase::getDBPath()) << endl;
#endif

	QString dirname = *(PilotLocalDatabase::getDBPath());

#ifdef DEBUG
	DEBUGDAEMON << fname << ": Restoring user " << dirname << endl;
#endif

	if (questionYesNo(i18n("<qt>Are you sure you want to completely "
				"restore your Pilot from the backup directory "
				"(%1)? This will erase any information "
				"you currently have on your Pilot.</qt>").
			arg(dirname),
			i18n("Restore Pilot")) != KMessageBox::Yes)
	{
		emit logError(i18n("Restore not performed."));

		addSyncLogEntry(i18n("Canceled by user.") + CSL1(" ") +
			i18n("Restore not performed."));
		emit syncDone(this);

		return true;
	}

	QDir dir(dirname, QString::null, QDir::Name,
		QDir::Files | QDir::Readable | QDir::NoSymLinks);

	if (!dir.exists())
	{
		kdWarning() << k_funcinfo
			<< ": Restore directory "
			<< dirname << " does not exist." << endl;
		fActionStatus = Error;
		addSyncLogEntry(i18n("Restore directory does not exist.") +
			CSL1(" ") + i18n("Restore not performed."));
		return false;
	}

	emit logProgress(i18n("Restoring %1...").arg(QString::null),1);

	for (unsigned int i = 0; i < dir.count(); i++)
	{
		QString s;
		RestoreInfo *dbi;
		struct DBInfo info;
		struct pi_file *f;

		s = dir[i];

#ifdef DEBUG
		DEBUGDAEMON << fname
			<< ": Adding " << s << " to restore list." << endl;
#endif

    char * fileName = qstrdup( QFile::encodeName(dirname + s) );
    f = pi_file_open( fileName );
    delete fileName;
		if (!f)
		{
			kdWarning() << k_funcinfo
				<< ": Can't open " << s << endl;
			logMessage(i18n("File `%1' cannot be read.").arg(s));
			continue;
		}

#if PILOT_LINK_NUMBER < PILOT_LINK_0_12_0
		if (!pi_file_get_info(f, &info))
#else
		pi_file_get_info(f,&info);
		if (true)
#endif
		{
			dbi = new RestoreInfo;
			memcpy(&dbi->DBInfo,&info,sizeof(struct DBInfo));
			dbi->path = dirname + s;
			fP->fDBList.append(dbi);
		}
		else
		{
			kdWarning() << k_funcinfo
				<< ": Can't open " << s << endl;
			logMessage(i18n("File `%1' cannot be read.").arg(s));
		}

		pi_file_close(f);
		f = 0L;
	}

	fP->fDBIndex = 0;
	fP->fDBIterator = fP->fDBList.begin();
	fActionStatus = GettingFileInfo;

	QObject::connect(&(fP->fTimer), SIGNAL(timeout()),
		this, SLOT(getNextFileInfo()));

	fP->fTimer.start(0, false);
	return true;
}

/* slot */ void RestoreAction::getNextFileInfo()
{
	FUNCTIONSETUP;

	Q_ASSERT(fActionStatus == GettingFileInfo);

	QObject::disconnect(&(fP->fTimer), SIGNAL(timeout()),
		this, SLOT(getNextFileInfo()));
	fP->fTimer.stop();

	qBubbleSort(fP->fDBList);

	fP->fDBIndex = 0;
	fP->fDBIterator = fP->fDBList.begin();
	fActionStatus = InstallingFiles;

	QObject::connect(&(fP->fTimer), SIGNAL(timeout()),
		this, SLOT(installNextFile()));
	fP->fTimer.start(0, false);
}

/* slot */ void RestoreAction::installNextFile()
{
	FUNCTIONSETUP;

	Q_ASSERT(fActionStatus == InstallingFiles);

	const RestoreInfo *dbi = 0L;

	if (fP->fDBIterator == fP->fDBList.end())
	{
		QObject::disconnect(&(fP->fTimer), SIGNAL(timeout()),
			this, SLOT(getNextFileInfo()));
		fP->fTimer.stop();

		fActionStatus = Done;
		addSyncLogEntry(i18n("OK."));
		delayDone();
		return;
	}

	dbi = *fP->fDBIterator;
	++(fP->fDBIterator);
	++(fP->fDBIndex);
#ifdef DEBUG
	DEBUGDAEMON << fname << ": Trying to install " << dbi->path << endl;
#endif

	if (openConduit() < 0)
	{
		kdWarning() << k_funcinfo
			<< ": Restore apparently canceled." << endl;
		logMessage(i18n("Restore incomplete."));
		fActionStatus = Done;
		emit syncDone(this);

		return;
	}

	QFileInfo databaseInfo(dbi->path);
	addSyncLogEntry(databaseInfo.fileName());
	emit logProgress(i18n("Restoring %1...").arg(databaseInfo.fileName()),
		(100*fP->fDBIndex) / (fP->fDBList.count()+1)) ;

	char * fileName = qstrdup( dbi->path.utf8() );
	pi_file *f  = pi_file_open( fileName );
	delete fileName;

	if (!f)
	{
		kdWarning() << k_funcinfo
			<< ": Can't open "
			<< dbi->path << " for restore." << endl;
		logError(i18n("Cannot open file `%1' for restore.")
			.arg(databaseInfo.fileName()));
		return;
	}

#if PILOT_LINK_NUMBER < PILOT_LINK_0_12_0
	if (pi_file_install(f, pilotSocket(), 0) < 0)
#else
	if (pi_file_install(f, pilotSocket(), 0, NULL) < 0)
#endif
	{
		kdWarning() << k_funcinfo
			<< ": Couldn't  restore " << dbi->path << endl;
		logError(i18n("Cannot restore file `%1'.")
			.arg(databaseInfo.fileName()));
	}

	pi_file_close(f);
}

/* virtual */ QString RestoreAction::statusString() const
{
	FUNCTIONSETUP;
	QString s;

	switch (status())
	{
	case InstallingFiles:
		s.append(CSL1("Installing Files ("));
		s.append(QString::number(fP->fDBIndex));
		s.append(CSL1(")"));
		break;
	case GettingFileInfo:
		s.append(CSL1("Getting File Info ("));
		s.append(QString::number(fP->fDBIndex));
		s.append(CSL1(")"));
		break;
	default:
		return SyncAction::statusString();
	}

	return s;
}

<commit_msg>CVS_SILENT Typographical corrections and changes<commit_after>/* KPilot
**
** Copyright (C) 2001 by Dan Pilone
** Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>
**
** This file specializes SyncAction to a kind that can have interaction
** with the user without the Sync timing out.
*/

/*
** 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 in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org.
*/

static const char *interactivesync_id =
	"$Id$";

#include "options.h"

#include <time.h>
#include <unistd.h>
#include <stdio.h>

#include <pi-socket.h>
#include <pi-file.h>

#include <qtimer.h>
#include <qvbox.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qmessagebox.h>
#include <qdir.h>
#include <qfile.h>
#include <qfileinfo.h>
#include <qtl.h>
#include <qstyle.h>
#include <qtextcodec.h>

#include <kdialogbase.h>
#include <kglobal.h>
#include <kstandarddirs.h>
#include <kmessagebox.h>

#include <kapplication.h>

#include "pilotUser.h"
#include "pilotAppCategory.h"
#include "pilotLocalDatabase.h"
#include "kpilotConfig.h"
#include "kpilotlink.h"

#include "interactiveSync.moc"

CheckUser::CheckUser(KPilotDeviceLink * p, QWidget * vp):
	SyncAction(p, vp, "userCheck")
{
	FUNCTIONSETUP;

	(void) interactivesync_id;
}

CheckUser::~CheckUser()
{
	FUNCTIONSETUP;
}

/* virtual */ bool CheckUser::exec()
{
	FUNCTIONSETUP;

	QString guiUserName = KPilotSettings::userName();
	QString pilotUserName = PilotAppCategory::codec()->
		toUnicode(fHandle->getPilotUser()->getUserName());
	bool pilotUserEmpty = pilotUserName.isEmpty();
	// 4 cases to handle:
	//    guiUserName empty / not empty
	//    pilotUserName empty / not empty
	//
	//
	if (guiUserName.isEmpty())
	{
		if (pilotUserEmpty)
		{
			QString defaultUserName =
				i18n("A common name", "John Doe");

			QString q = i18n("<qt>Neither KPilot nor the "
				"handheld have a username set. "
				"They should be set. "
				"Should KPilot set them to a default value "
				"(%1)?</qt>").arg(defaultUserName);

			if (questionYesNo(q, i18n("User Unknown") /* ,"askUserNone" */) ==
				KMessageBox::Yes)
			{
				KPilotSettings::setUserName(defaultUserName);
				fHandle->getPilotUser()->
					setUserName(PilotAppCategory::codec()->fromUnicode(defaultUserName));
				guiUserName=defaultUserName;
				pilotUserName=defaultUserName;
			}

		}
		else
		{
			QString q = i18n("<qt>The handheld has a username set "
				"(%1) but KPilot does not. Should "
				"KPilot use this username in future?").
				arg(pilotUserName);

			if (questionYesNo(q, i18n("User Unknown") /* ,"askUserSome" */ ) ==
				KMessageBox::Yes)
			{
				KPilotSettings::setUserName(pilotUserName);
				guiUserName=pilotUserName;
			}
		}
	}
	else
	{
		if (pilotUserEmpty)
		{
			QString q = i18n("<qt>KPilot has a username set "
				"(%1) but the handheld does not. "
				"Should KPilot's username be set in the "
				"handheld as well?").arg(guiUserName);

			if (questionYesNo(q, i18n("User Unknown") /* ,"askUserSome" */) ==
				KMessageBox::Yes)
			{
#ifdef DEBUG
				DEBUGDAEMON << fname
					<< ": Setting user name in pilot"
					<< endl;
#endif

				const char *l1 = PilotAppCategory::codec()->fromUnicode(guiUserName);

#ifdef DEBUG
				DEBUGDAEMON << fname
					<< ": Setting to " << l1 << endl;
#endif

				fHandle->getPilotUser()->setUserName(l1);
				pilotUserName=guiUserName;
			}
		}
		else
		{
			if (guiUserName != pilotUserName)
			{
				QString q = i18n("<qt>The handheld thinks that "
					"the username is %1; "
					"however, KPilot says you are %2."
					"Which of these is the correct name?\n"
					"If you click on Cancel, the sync will proceed, "
					"but the usernames will not be changed.").
					arg(pilotUserName).
					arg(guiUserName);

				int r = questionYesNoCancel(q,
					i18n("User Mismatch"),
					QString::null,
					20,
					i18n("Use KPilot Name"),
					i18n("Use Handheld Name"));
				switch (r)
				{
				case KMessageBox::Yes:
					fHandle->getPilotUser()->setUserName(
						PilotAppCategory::codec()->fromUnicode(guiUserName));
					pilotUserName=guiUserName;
					break;
				case KMessageBox::No:
					KPilotSettings::setUserName(pilotUserName);
					guiUserName=pilotUserName;
					break;
				case KMessageBox::Cancel:
				default:
					// TODO: cancel the sync... Or just don't change any user name?
					break;
				}
			}
		}
	}

#ifdef DEBUG
	DEBUGCONDUIT << fname
		<< ": User name set to <"
		<< guiUserName
		<< ">"
		<< endl;
#endif

	KPilotSettings::writeConfig();

	// Now we've established which user will be used,
	// fix the database location for local databases.
	//
	//
	QString pathName = KGlobal::dirs()->saveLocation("data",
		CSL1("kpilot/DBBackup/"));
	if (!guiUserName.isEmpty())
	{
		pathName.append(guiUserName);
		pathName.append(CSL1("/"));
	}
	PilotLocalDatabase::setDBPath(pathName);

	emit syncDone(this);
	return true;
}

class RestoreInfo
{
public:
	struct db DBInfo;
	QString path;
} ;

class RestoreAction::RestoreActionPrivate
{
public:
	QString fDatabaseDir;
	QValueList<RestoreInfo *> fDBList;
	QTimer fTimer;
	QValueList<RestoreInfo *>::ConstIterator fDBIterator;
	int fDBIndex;
};

RestoreAction::RestoreAction(KPilotDeviceLink * p, QWidget * visible ) :
	SyncAction(p, visible, "restoreAction")
{
	FUNCTIONSETUP;

	fP = new RestoreActionPrivate;
	fP->fDatabaseDir = KGlobal::dirs()->saveLocation("data",
		CSL1("kpilot/DBBackup/"));
}

/* virtual */ bool RestoreAction::exec()
{
	FUNCTIONSETUP;

#ifdef DEBUG
	DEBUGDAEMON << fname
		<< ": Restoring from base directory "
		<< *(PilotLocalDatabase::getDBPath()) << endl;
#endif

	QString dirname = *(PilotLocalDatabase::getDBPath());

#ifdef DEBUG
	DEBUGDAEMON << fname << ": Restoring user " << dirname << endl;
#endif

	if (questionYesNo(i18n("<qt>Are you sure you want to completely "
				"restore your Pilot from the backup directory "
				"(%1)? This will erase any information "
				"you currently have on your Pilot.</qt>").
			arg(dirname),
			i18n("Restore Pilot")) != KMessageBox::Yes)
	{
		emit logError(i18n("Restore not performed."));

		addSyncLogEntry(i18n("Canceled by user.") + CSL1(" ") +
			i18n("Restore not performed."));
		emit syncDone(this);

		return true;
	}

	QDir dir(dirname, QString::null, QDir::Name,
		QDir::Files | QDir::Readable | QDir::NoSymLinks);

	if (!dir.exists())
	{
		kdWarning() << k_funcinfo
			<< ": Restore directory "
			<< dirname << " does not exist." << endl;
		fActionStatus = Error;
		addSyncLogEntry(i18n("Restore directory does not exist.") +
			CSL1(" ") + i18n("Restore not performed."));
		return false;
	}

	emit logProgress(i18n("Restoring %1...").arg(QString::null),1);

	for (unsigned int i = 0; i < dir.count(); i++)
	{
		QString s;
		RestoreInfo *dbi;
		struct DBInfo info;
		struct pi_file *f;

		s = dir[i];

#ifdef DEBUG
		DEBUGDAEMON << fname
			<< ": Adding " << s << " to restore list." << endl;
#endif

    char * fileName = qstrdup( QFile::encodeName(dirname + s) );
    f = pi_file_open( fileName );
    delete fileName;
		if (!f)
		{
			kdWarning() << k_funcinfo
				<< ": Can't open " << s << endl;
			logMessage(i18n("File '%1' cannot be read.").arg(s));
			continue;
		}

#if PILOT_LINK_NUMBER < PILOT_LINK_0_12_0
		if (!pi_file_get_info(f, &info))
#else
		pi_file_get_info(f,&info);
		if (true)
#endif
		{
			dbi = new RestoreInfo;
			memcpy(&dbi->DBInfo,&info,sizeof(struct DBInfo));
			dbi->path = dirname + s;
			fP->fDBList.append(dbi);
		}
		else
		{
			kdWarning() << k_funcinfo
				<< ": Can't open " << s << endl;
			logMessage(i18n("File '%1' cannot be read.").arg(s));
		}

		pi_file_close(f);
		f = 0L;
	}

	fP->fDBIndex = 0;
	fP->fDBIterator = fP->fDBList.begin();
	fActionStatus = GettingFileInfo;

	QObject::connect(&(fP->fTimer), SIGNAL(timeout()),
		this, SLOT(getNextFileInfo()));

	fP->fTimer.start(0, false);
	return true;
}

/* slot */ void RestoreAction::getNextFileInfo()
{
	FUNCTIONSETUP;

	Q_ASSERT(fActionStatus == GettingFileInfo);

	QObject::disconnect(&(fP->fTimer), SIGNAL(timeout()),
		this, SLOT(getNextFileInfo()));
	fP->fTimer.stop();

	qBubbleSort(fP->fDBList);

	fP->fDBIndex = 0;
	fP->fDBIterator = fP->fDBList.begin();
	fActionStatus = InstallingFiles;

	QObject::connect(&(fP->fTimer), SIGNAL(timeout()),
		this, SLOT(installNextFile()));
	fP->fTimer.start(0, false);
}

/* slot */ void RestoreAction::installNextFile()
{
	FUNCTIONSETUP;

	Q_ASSERT(fActionStatus == InstallingFiles);

	const RestoreInfo *dbi = 0L;

	if (fP->fDBIterator == fP->fDBList.end())
	{
		QObject::disconnect(&(fP->fTimer), SIGNAL(timeout()),
			this, SLOT(getNextFileInfo()));
		fP->fTimer.stop();

		fActionStatus = Done;
		addSyncLogEntry(i18n("OK."));
		delayDone();
		return;
	}

	dbi = *fP->fDBIterator;
	++(fP->fDBIterator);
	++(fP->fDBIndex);
#ifdef DEBUG
	DEBUGDAEMON << fname << ": Trying to install " << dbi->path << endl;
#endif

	if (openConduit() < 0)
	{
		kdWarning() << k_funcinfo
			<< ": Restore apparently canceled." << endl;
		logMessage(i18n("Restore incomplete."));
		fActionStatus = Done;
		emit syncDone(this);

		return;
	}

	QFileInfo databaseInfo(dbi->path);
	addSyncLogEntry(databaseInfo.fileName());
	emit logProgress(i18n("Restoring %1...").arg(databaseInfo.fileName()),
		(100*fP->fDBIndex) / (fP->fDBList.count()+1)) ;

	char * fileName = qstrdup( dbi->path.utf8() );
	pi_file *f  = pi_file_open( fileName );
	delete fileName;

	if (!f)
	{
		kdWarning() << k_funcinfo
			<< ": Can't open "
			<< dbi->path << " for restore." << endl;
		logError(i18n("Cannot open file `%1' for restore.")
			.arg(databaseInfo.fileName()));
		return;
	}

#if PILOT_LINK_NUMBER < PILOT_LINK_0_12_0
	if (pi_file_install(f, pilotSocket(), 0) < 0)
#else
	if (pi_file_install(f, pilotSocket(), 0, NULL) < 0)
#endif
	{
		kdWarning() << k_funcinfo
			<< ": Couldn't  restore " << dbi->path << endl;
		logError(i18n("Cannot restore file `%1'.")
			.arg(databaseInfo.fileName()));
	}

	pi_file_close(f);
}

/* virtual */ QString RestoreAction::statusString() const
{
	FUNCTIONSETUP;
	QString s;

	switch (status())
	{
	case InstallingFiles:
		s.append(CSL1("Installing Files ("));
		s.append(QString::number(fP->fDBIndex));
		s.append(CSL1(")"));
		break;
	case GettingFileInfo:
		s.append(CSL1("Getting File Info ("));
		s.append(QString::number(fP->fDBIndex));
		s.append(CSL1(")"));
		break;
	default:
		return SyncAction::statusString();
	}

	return s;
}

<|endoftext|>


<commit_before><commit_msg>DOM Storage: Simplified filename -> utf8 conversion.<commit_after><|endoftext|>


<commit_before>/*
 *
 * pdb.cxx - Display PDB file
 *
 * Author: Randy Heiland, NCSA,UIUC
 *
 * Usage:
 *  pdb <pdbfile> <atomRadius> <bondRadius> <sphereRes> <cylRes> <bondsFlag>
 *
 * Example:
 *    pdb caffeine.pdb .5 .1 10 6 1
 *    pdb nanotube.pdb .5 .1 10 6 1
 *    pdb wheel.pdb .3 .05 10 8 1
 *    pdb diffGear.pdb 1 .05 6 6 0
 *    pdb fineMotion.pdb 2.5 .05 6 6 0
 *
 *

01234567890123456789012345678901234567890123456789012345678901234567890123456789
Sample PDB file:

ATOM   1849  C1  A77   800       3.484   3.332  10.744 12.0 1.91 .11  0.0 NP --
ATOM   1850  O2  A77   800 HD    3.336   4.024  11.730 16.0 1.60 .20  0.0 PA HD
ATOM   1851  N3  A77   800 HA    3.986   3.834   9.598 14.0 1.72 .17 -0.1 PA HA
ATOM   1852  C4  A77   800       4.186   3.015   8.397 12.0 2.00 .15  0.0 NP --

CONECT 1962 1895                                                        1HVI2148
CONECT 1963 1895

*/

#undef DEBUG

#include "SaveImage.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "vtkRenderWindow.h"
#include "vtkPolyData.h"
#include "vtkFloatPoints.h"
#include "vtkRenderer.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkFloatPoints.h"
#include "vtkSphereSource.h"
#include "vtkLineSource.h"
#include "vtkCylinderSource.h"
#include "vtkGlyph3D.h"
#include "vtkTubeFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkLookupTable.h"
#include "vtkActor.h"
#include "vtkScalars.h"

// "Known" atoms...
char atomType[] = {'H','C','N','O','S'};
static unsigned char colorMap[5][3] =
{{255,255,255}, {125,125,125}, {58,144,255}, {255,0,0}, {255,246,0}};
#define MINSCALAR 0.0
#define MAXSCALAR 5.0
#define MAXTYPE 5
static unsigned char unknownAtomColor[3] = {0,255,0};

#define MAXATOM 8300
static float atomPos[MAXATOM][3];
static float atomVal[MAXATOM];

#define MAXBOND 1000
static int bondAtomIdx[MAXBOND][2];
vtkLineSource *bond[MAXBOND];
vtkTubeFilter *bondTube[MAXBOND];

// Global variables to allow access by UserMethod (if necessary)
vtkRenderWindow *renWin;
vtkPolyData *atomsPolyData, *bondsPolyData;

int getLine(FILE *fp, char *s, int lim)
{
  int c, i;

  for (i=0; i<=lim-1 && (c=fgetc(fp))!=EOF && c!='\n'; ++i)
    s[i]=c;
  s[i]='\0';
  return(i);
}

void main(int argc, char **argv)
{
  FILE *fp;
  char lbuf[128],keywd[16],atomId[16],atomSym[8],tok[16],*charPtr;
  int idx, atomIdNum[MAXATOM], atomIdx1,atomIdx2,
    srcAtomIdx,srcAtom,dstAtom, bondsFlag;
  float atomRadius, sphereResolution, bondRadius, cylResolution;
  double xval,yval,zval;

  // This if is to set defaults if we're regression testing
  if( (argc >= 2) && (strcmp("-S", argv[argc-1]) == 0) )
    {
    fp = fopen("../../../vtkdata/finemotion.pdb", "r");
    atomRadius = 2.5;
    bondRadius = .05;
    sphereResolution = 6;
    cylResolution = 6;
    bondsFlag = 0;
    }
  else if (argc < 7)
    {
    printf("Usage: %s <pdbfile> <atomRadius> <bondRadius> <sphereRes> <cylRes> <bondsFlag>\n", argv[0]);
    exit(-1);
    }
  else
    {
    atomRadius = atof(argv[2]);
    bondRadius = atof(argv[3]);
    sphereResolution = atoi(argv[4]);
    cylResolution = atoi(argv[5]);
    bondsFlag = atoi(argv[6]);

    fp = fopen(argv[1],"r");
    }

  int nchars;
  int nAtoms = 0;
  int nBonds = 0;
  while (1)
    {
    nchars = getLine(fp,lbuf,128);
    if (nchars == 0) break;

#ifdef DEBUG
    printf("from getLine, lbuf=%s\n",lbuf);
    printf("keywd=%s\n",strtok(lbuf, " "));
#endif

    strcpy(keywd,strtok(lbuf, " "));
    if (!strcmp(keywd,"ATOM") || !strcmp(keywd,"HETATM"))
      {
      strcpy(atomId,strtok(&lbuf[5], " "));
      atomIdNum[nAtoms] = atoi(atomId);
      strcpy(atomSym,strtok(&lbuf[12], " "));

#ifdef DEBUG
      printf("atomId=%s\n",atomId);
      printf("atomIdNum=%d\n",atomIdNum[nAtoms]);
      printf("atomSym=%s\n",atomSym);
      printf("atomSym[0]=%c\n",atomSym[0]);
#endif
      // Default: any unknown atom will take on the MAXSCALAR value
      atomVal[nAtoms] = MAXSCALAR;
      for (int itype=0; itype<MAXTYPE; itype++)
	{
        if (atomSym[0] == atomType[itype])
	  {
          atomVal[nAtoms] = (float)itype;
          break;
	  }
	}
      xval = atof(strtok(&lbuf[29], " "));
      yval = atof(strtok(&lbuf[39], " "));
      zval = atof(strtok(&lbuf[47], " "));
#ifdef DEBUG
      printf("atomVal[nAtoms]= %f\n",atomVal[nAtoms]);
      printf("x,y,z=%f %f %f\n",xval,yval,zval);
#endif
      atomPos[nAtoms][0] = xval;
      atomPos[nAtoms][1] = yval;
      atomPos[nAtoms][2] = zval;
      nAtoms++;

      if (nAtoms > MAXATOM)
	{
        printf("\n\n   Oops - you need to increase MAXATOM and recompile...\n\n");
        exit(-1);
	}
      }
    else if (!strcmp(keywd,"CONECT"))
      {
      if (bondsFlag)
	{

#ifdef DEBUG
	printf("--- Got CONECT:\n");
	printf("lbuf=%s\n",lbuf);
#endif
	// The 1st atom id following the CONECT is the "source" atom for a bond
	srcAtom = atoi(strtok(&lbuf[7], " "));
#ifdef DEBUG
	printf("srcAtom=%d\n",srcAtom);
#endif
	for (idx=0; idx<nAtoms; idx++)
	  {
	  if (srcAtom == atomIdNum[idx])
	    {
	    srcAtomIdx = idx;
	    break;
	    }
	  }
	// The remaining atom ids are the "destination" atoms for bonds
	while (1)
	  {
	  if (!(charPtr=strtok(NULL," "))) break;
	  strcpy(tok, charPtr);
	  dstAtom = atoi(tok);
#ifdef DEBUG
	  printf("=%s, %d\n", tok,dstAtom);
#endif
	  bondAtomIdx[nBonds][0] = srcAtomIdx;
	  for (idx=0; idx<nAtoms; idx++)
	    {
	    if (dstAtom == atomIdNum[idx])
	      {
	      bondAtomIdx[nBonds][1] = idx;
	      break;
	      }
	    }
	  nBonds++;
	  if (nBonds > MAXBOND)
	    {
	    printf("\n\n   Oops - you need to increase MAXBOND and recompile...\n\n");
	    exit(-1);
	    }
	  }
	}
      }
    else if (!strcmp(keywd,"END"))
      {
      }
    else
      {
      printf("unknown keyword = %s\n", keywd);
      printf("lbuf=%s\n",lbuf);
      }
    }

#ifdef DEBUG
  printf("# of atoms= %d\n",nAtoms);
  for (idx=0; idx<nAtoms; idx++)
    printf("%d) %f %f %f\n",idx,atomPos[idx][0],atomPos[idx][1],atomPos[idx][2]);
  printf("# of bonds= %d\n",nBonds);
  for (idx=0; idx<nBonds; idx++)
    printf("%d) %d %d\n",idx,bondAtomIdx[idx][0],bondAtomIdx[idx][1]);
#endif

  //===  VTK-specific  =======================================================
  // Create the vtk renderer stuff
  vtkRenderer *ren = vtkRenderer::New();
  renWin = vtkRenderWindow::New();
  renWin->AddRenderer(ren);
  renWin->SetSize (300,300);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
  iren->SetRenderWindow(renWin);

  // ---- Atoms (as spheres) -----

  // Create points for the starting positions of the particles
  vtkFloatPoints *atomPoints = vtkFloatPoints::New();
  vtkScalars *atomScalars = vtkScalars::New();

  for (int i=0; i<nAtoms; i++)
    {
    atomPoints->InsertNextPoint(atomPos[i]);
    // Weird... the first works (range [0,1]), the latter doesn't
    // Color sequentially by atom
    atomScalars->InsertScalar(i, (float)i/nAtoms);

    // Color by atomVal (symbol)
    atomScalars->InsertScalar(i, atomVal[i]);
#ifdef DEBUG
    printf("  setting atomScalar = %f\n",atomVal[i]);
#endif
    }

  // Create a data set for the atoms.
  atomsPolyData = vtkPolyData::New();
  atomsPolyData->SetPoints(atomPoints);
  atomPoints->Delete();

  float range[2];
  atomsPolyData->GetPointData()->SetScalars(atomScalars);
  atomsPolyData->GetPointData()->GetScalars()->GetRange(range);

  // Create a vtkSphereSource object to represent an atom
  vtkSphereSource *sphereSource = vtkSphereSource::New();
  // Increase the values here for a smoother sphere
  sphereSource->SetThetaResolution(sphereResolution);
  sphereSource->SetPhiResolution(sphereResolution);
  sphereSource->SetRadius(atomRadius);

  vtkLookupTable *lut = vtkLookupTable::New();
  lut->SetNumberOfColors(MAXTYPE+1);
  for (idx=0; idx<MAXTYPE; idx++)
    {
    lut->SetTableValue(idx,colorMap[idx][0]/255.0,colorMap[idx][1]/255.0,
		       colorMap[idx][2]/255.0, 1.0);

    }
  // Make the "unknown" atom color
  lut->SetTableValue(MAXTYPE, unknownAtomColor[0]/255.0,unknownAtomColor[1]/255.0,unknownAtomColor[2]/255.0,1.0);

  // Create atoms, using a vtkGlyph3D object
  vtkGlyph3D *atoms = vtkGlyph3D::New();
  atoms->SetInput(atomsPolyData);
  atoms->SetSource(sphereSource->GetOutput());
  atoms->SetScaleFactor(0.7);
  //    atoms->SetScaleModeToScaleByScalar();
  // To make all atoms the same size
  atoms->SetScaleModeToDataScalingOff();
  atoms->SetColorModeToColorByScalar();
  atoms->SetRange(MINSCALAR,MAXSCALAR);
  atoms->GetRange(range);

  // Create the mapper and actor and finish up the visualization pipeline
  vtkPolyDataMapper *atomsMapper = vtkPolyDataMapper::New();
  atomsMapper->SetInput(atoms->GetOutput());
  atomsMapper->SetScalarRange(MINSCALAR,MAXSCALAR);
  atomsMapper->SetLookupTable(lut);
  vtkActor *atomsActor = vtkActor::New();
  atomsActor->SetMapper(atomsMapper);

  // Make them all one color
  //    atomsActor->GetProperty()->SetColor(0, 1, 1);
  ren->AddActor(atomsActor);

  // ---- Bonds (as lines or tubes) -----
  //#ifdef notdef
  if (bondsFlag)
    {
    for (idx=0; idx<nBonds; idx++)
      {
      //  vtkLineSource *bond[idx] = vtkLineSource::New();
      bond[idx] = vtkLineSource::New();
      bond[idx]->SetResolution(4);
      atomIdx1 = bondAtomIdx[idx][0];
      atomIdx2 = bondAtomIdx[idx][1];
      bond[idx]->SetPoint1(atomPos[atomIdx1][0],atomPos[atomIdx1][1],atomPos[atomIdx1][2]);
      bond[idx]->SetPoint2(atomPos[atomIdx2][0],atomPos[atomIdx2][1],atomPos[atomIdx2][2]);

      if (bondRadius > 0.0)
	{
	bondTube[idx] = vtkTubeFilter::New();
	bondTube[idx]->SetInput(bond[idx]->GetOutput());
	bondTube[idx]->SetRadius(bondRadius);
	bondTube[idx]->SetNumberOfSides(cylResolution);
	}

      // Create the mapper and actor and finish up the visualization pipeline
      vtkPolyDataMapper *bondsMapper = vtkPolyDataMapper::New();
      if (bondRadius > 0.0)
	bondsMapper->SetInput(bondTube[idx]->GetOutput());
      else
	bondsMapper->SetInput(bond[idx]->GetOutput());

      vtkActor *bondsActor = vtkActor::New();
      bondsActor->SetMapper(bondsMapper);

      // Make them all one color
      //    atomsActor->GetProperty()->SetColor(0, 1, 1);
      ren->AddActor(bondsActor);
      }
    }
  //#endif

  // ----------------------------------
  //   ren->SetBackground(1,1,1);
  ren->SetBackground(0,0,0);

  // interact with data
  renWin->Render();

  SAVEIMAGE( renWin );

  iren->Start();

  // Clean up
  ren->Delete();
  renWin->Delete();
  atomsPolyData->Delete();
  sphereSource->Delete();
  atoms->Delete();
  atomsMapper->Delete();
  atomsActor->Delete();
}
<commit_msg>ERR: removed obsolete vtkFloatpoints.<commit_after>/*
 *
 * pdb.cxx - Display PDB file
 *
 * Author: Randy Heiland, NCSA,UIUC
 *
 * Usage:
 *  pdb <pdbfile> <atomRadius> <bondRadius> <sphereRes> <cylRes> <bondsFlag>
 *
 * Example:
 *    pdb caffeine.pdb .5 .1 10 6 1
 *    pdb nanotube.pdb .5 .1 10 6 1
 *    pdb wheel.pdb .3 .05 10 8 1
 *    pdb diffGear.pdb 1 .05 6 6 0
 *    pdb fineMotion.pdb 2.5 .05 6 6 0
 *
 *

01234567890123456789012345678901234567890123456789012345678901234567890123456789
Sample PDB file:

ATOM   1849  C1  A77   800       3.484   3.332  10.744 12.0 1.91 .11  0.0 NP --
ATOM   1850  O2  A77   800 HD    3.336   4.024  11.730 16.0 1.60 .20  0.0 PA HD
ATOM   1851  N3  A77   800 HA    3.986   3.834   9.598 14.0 1.72 .17 -0.1 PA HA
ATOM   1852  C4  A77   800       4.186   3.015   8.397 12.0 2.00 .15  0.0 NP --

CONECT 1962 1895                                                        1HVI2148
CONECT 1963 1895

*/

#undef DEBUG

#include "SaveImage.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "vtkRenderWindow.h"
#include "vtkPolyData.h"
#include "vtkRenderer.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSphereSource.h"
#include "vtkLineSource.h"
#include "vtkCylinderSource.h"
#include "vtkGlyph3D.h"
#include "vtkTubeFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkLookupTable.h"
#include "vtkActor.h"
#include "vtkScalars.h"

// "Known" atoms...
char atomType[] = {'H','C','N','O','S'};
static unsigned char colorMap[5][3] =
{{255,255,255}, {125,125,125}, {58,144,255}, {255,0,0}, {255,246,0}};
#define MINSCALAR 0.0
#define MAXSCALAR 5.0
#define MAXTYPE 5
static unsigned char unknownAtomColor[3] = {0,255,0};

#define MAXATOM 8300
static float atomPos[MAXATOM][3];
static float atomVal[MAXATOM];

#define MAXBOND 1000
static int bondAtomIdx[MAXBOND][2];
vtkLineSource *bond[MAXBOND];
vtkTubeFilter *bondTube[MAXBOND];

// Global variables to allow access by UserMethod (if necessary)
vtkRenderWindow *renWin;
vtkPolyData *atomsPolyData, *bondsPolyData;

int getLine(FILE *fp, char *s, int lim)
{
  int c, i;

  for (i=0; i<=lim-1 && (c=fgetc(fp))!=EOF && c!='\n'; ++i)
    s[i]=c;
  s[i]='\0';
  return(i);
}

void main(int argc, char **argv)
{
  FILE *fp;
  char lbuf[128],keywd[16],atomId[16],atomSym[8],tok[16],*charPtr;
  int idx, atomIdNum[MAXATOM], atomIdx1,atomIdx2,
    srcAtomIdx,srcAtom,dstAtom, bondsFlag;
  float atomRadius, sphereResolution, bondRadius, cylResolution;
  double xval,yval,zval;

  // This if is to set defaults if we're regression testing
  if( (argc >= 2) && (strcmp("-S", argv[argc-1]) == 0) )
    {
    fp = fopen("../../../vtkdata/finemotion.pdb", "r");
    atomRadius = 2.5;
    bondRadius = .05;
    sphereResolution = 6;
    cylResolution = 6;
    bondsFlag = 0;
    }
  else if (argc < 7)
    {
    printf("Usage: %s <pdbfile> <atomRadius> <bondRadius> <sphereRes> <cylRes> <bondsFlag>\n", argv[0]);
    exit(-1);
    }
  else
    {
    atomRadius = atof(argv[2]);
    bondRadius = atof(argv[3]);
    sphereResolution = atoi(argv[4]);
    cylResolution = atoi(argv[5]);
    bondsFlag = atoi(argv[6]);

    fp = fopen(argv[1],"r");
    }

  int nchars;
  int nAtoms = 0;
  int nBonds = 0;
  while (1)
    {
    nchars = getLine(fp,lbuf,128);
    if (nchars == 0) break;

#ifdef DEBUG
    printf("from getLine, lbuf=%s\n",lbuf);
    printf("keywd=%s\n",strtok(lbuf, " "));
#endif

    strcpy(keywd,strtok(lbuf, " "));
    if (!strcmp(keywd,"ATOM") || !strcmp(keywd,"HETATM"))
      {
      strcpy(atomId,strtok(&lbuf[5], " "));
      atomIdNum[nAtoms] = atoi(atomId);
      strcpy(atomSym,strtok(&lbuf[12], " "));

#ifdef DEBUG
      printf("atomId=%s\n",atomId);
      printf("atomIdNum=%d\n",atomIdNum[nAtoms]);
      printf("atomSym=%s\n",atomSym);
      printf("atomSym[0]=%c\n",atomSym[0]);
#endif
      // Default: any unknown atom will take on the MAXSCALAR value
      atomVal[nAtoms] = MAXSCALAR;
      for (int itype=0; itype<MAXTYPE; itype++)
	{
        if (atomSym[0] == atomType[itype])
	  {
          atomVal[nAtoms] = (float)itype;
          break;
	  }
	}
      xval = atof(strtok(&lbuf[29], " "));
      yval = atof(strtok(&lbuf[39], " "));
      zval = atof(strtok(&lbuf[47], " "));
#ifdef DEBUG
      printf("atomVal[nAtoms]= %f\n",atomVal[nAtoms]);
      printf("x,y,z=%f %f %f\n",xval,yval,zval);
#endif
      atomPos[nAtoms][0] = xval;
      atomPos[nAtoms][1] = yval;
      atomPos[nAtoms][2] = zval;
      nAtoms++;

      if (nAtoms > MAXATOM)
	{
        printf("\n\n   Oops - you need to increase MAXATOM and recompile...\n\n");
        exit(-1);
	}
      }
    else if (!strcmp(keywd,"CONECT"))
      {
      if (bondsFlag)
	{

#ifdef DEBUG
	printf("--- Got CONECT:\n");
	printf("lbuf=%s\n",lbuf);
#endif
	// The 1st atom id following the CONECT is the "source" atom for a bond
	srcAtom = atoi(strtok(&lbuf[7], " "));
#ifdef DEBUG
	printf("srcAtom=%d\n",srcAtom);
#endif
	for (idx=0; idx<nAtoms; idx++)
	  {
	  if (srcAtom == atomIdNum[idx])
	    {
	    srcAtomIdx = idx;
	    break;
	    }
	  }
	// The remaining atom ids are the "destination" atoms for bonds
	while (1)
	  {
	  if (!(charPtr=strtok(NULL," "))) break;
	  strcpy(tok, charPtr);
	  dstAtom = atoi(tok);
#ifdef DEBUG
	  printf("=%s, %d\n", tok,dstAtom);
#endif
	  bondAtomIdx[nBonds][0] = srcAtomIdx;
	  for (idx=0; idx<nAtoms; idx++)
	    {
	    if (dstAtom == atomIdNum[idx])
	      {
	      bondAtomIdx[nBonds][1] = idx;
	      break;
	      }
	    }
	  nBonds++;
	  if (nBonds > MAXBOND)
	    {
	    printf("\n\n   Oops - you need to increase MAXBOND and recompile...\n\n");
	    exit(-1);
	    }
	  }
	}
      }
    else if (!strcmp(keywd,"END"))
      {
      }
    else
      {
      printf("unknown keyword = %s\n", keywd);
      printf("lbuf=%s\n",lbuf);
      }
    }

#ifdef DEBUG
  printf("# of atoms= %d\n",nAtoms);
  for (idx=0; idx<nAtoms; idx++)
    printf("%d) %f %f %f\n",idx,atomPos[idx][0],atomPos[idx][1],atomPos[idx][2]);
  printf("# of bonds= %d\n",nBonds);
  for (idx=0; idx<nBonds; idx++)
    printf("%d) %d %d\n",idx,bondAtomIdx[idx][0],bondAtomIdx[idx][1]);
#endif

  //===  VTK-specific  =======================================================
  // Create the vtk renderer stuff
  vtkRenderer *ren = vtkRenderer::New();
  renWin = vtkRenderWindow::New();
  renWin->AddRenderer(ren);
  renWin->SetSize (300,300);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
  iren->SetRenderWindow(renWin);

  // ---- Atoms (as spheres) -----

  // Create points for the starting positions of the particles
  vtkPoints *atomPoints = vtkPoints::New();
  vtkScalars *atomScalars = vtkScalars::New();

  atomPoints->SetDataTypeToFloat();

  for (int i=0; i<nAtoms; i++)
    {
    atomPoints->InsertNextPoint(atomPos[i]);
    // Weird... the first works (range [0,1]), the latter doesn't
    // Color sequentially by atom
    atomScalars->InsertScalar(i, (float)i/nAtoms);

    // Color by atomVal (symbol)
    atomScalars->InsertScalar(i, atomVal[i]);
#ifdef DEBUG
    printf("  setting atomScalar = %f\n",atomVal[i]);
#endif
    }

  // Create a data set for the atoms.
  atomsPolyData = vtkPolyData::New();
  atomsPolyData->SetPoints(atomPoints);
  atomPoints->Delete();

  float range[2];
  atomsPolyData->GetPointData()->SetScalars(atomScalars);
  atomsPolyData->GetPointData()->GetScalars()->GetRange(range);

  // Create a vtkSphereSource object to represent an atom
  vtkSphereSource *sphereSource = vtkSphereSource::New();
  // Increase the values here for a smoother sphere
  sphereSource->SetThetaResolution(sphereResolution);
  sphereSource->SetPhiResolution(sphereResolution);
  sphereSource->SetRadius(atomRadius);

  vtkLookupTable *lut = vtkLookupTable::New();
  lut->SetNumberOfColors(MAXTYPE+1);
  for (idx=0; idx<MAXTYPE; idx++)
    {
    lut->SetTableValue(idx,colorMap[idx][0]/255.0,colorMap[idx][1]/255.0,
		       colorMap[idx][2]/255.0, 1.0);

    }
  // Make the "unknown" atom color
  lut->SetTableValue(MAXTYPE, unknownAtomColor[0]/255.0,unknownAtomColor[1]/255.0,unknownAtomColor[2]/255.0,1.0);

  // Create atoms, using a vtkGlyph3D object
  vtkGlyph3D *atoms = vtkGlyph3D::New();
  atoms->SetInput(atomsPolyData);
  atoms->SetSource(sphereSource->GetOutput());
  atoms->SetScaleFactor(0.7);
  //    atoms->SetScaleModeToScaleByScalar();
  // To make all atoms the same size
  atoms->SetScaleModeToDataScalingOff();
  atoms->SetColorModeToColorByScalar();
  atoms->SetRange(MINSCALAR,MAXSCALAR);
  atoms->GetRange(range);

  // Create the mapper and actor and finish up the visualization pipeline
  vtkPolyDataMapper *atomsMapper = vtkPolyDataMapper::New();
  atomsMapper->SetInput(atoms->GetOutput());
  atomsMapper->SetScalarRange(MINSCALAR,MAXSCALAR);
  atomsMapper->SetLookupTable(lut);
  vtkActor *atomsActor = vtkActor::New();
  atomsActor->SetMapper(atomsMapper);

  // Make them all one color
  //    atomsActor->GetProperty()->SetColor(0, 1, 1);
  ren->AddActor(atomsActor);

  // ---- Bonds (as lines or tubes) -----
  //#ifdef notdef
  if (bondsFlag)
    {
    for (idx=0; idx<nBonds; idx++)
      {
      //  vtkLineSource *bond[idx] = vtkLineSource::New();
      bond[idx] = vtkLineSource::New();
      bond[idx]->SetResolution(4);
      atomIdx1 = bondAtomIdx[idx][0];
      atomIdx2 = bondAtomIdx[idx][1];
      bond[idx]->SetPoint1(atomPos[atomIdx1][0],atomPos[atomIdx1][1],atomPos[atomIdx1][2]);
      bond[idx]->SetPoint2(atomPos[atomIdx2][0],atomPos[atomIdx2][1],atomPos[atomIdx2][2]);

      if (bondRadius > 0.0)
	{
	bondTube[idx] = vtkTubeFilter::New();
	bondTube[idx]->SetInput(bond[idx]->GetOutput());
	bondTube[idx]->SetRadius(bondRadius);
	bondTube[idx]->SetNumberOfSides(cylResolution);
	}

      // Create the mapper and actor and finish up the visualization pipeline
      vtkPolyDataMapper *bondsMapper = vtkPolyDataMapper::New();
      if (bondRadius > 0.0)
	bondsMapper->SetInput(bondTube[idx]->GetOutput());
      else
	bondsMapper->SetInput(bond[idx]->GetOutput());

      vtkActor *bondsActor = vtkActor::New();
      bondsActor->SetMapper(bondsMapper);

      // Make them all one color
      //    atomsActor->GetProperty()->SetColor(0, 1, 1);
      ren->AddActor(bondsActor);
      }
    }
  //#endif

  // ----------------------------------
  //   ren->SetBackground(1,1,1);
  ren->SetBackground(0,0,0);

  // interact with data
  renWin->Render();

  SAVEIMAGE( renWin );

  iren->Start();

  // Clean up
  ren->Delete();
  renWin->Delete();
  atomsPolyData->Delete();
  sphereSource->Delete();
  atoms->Delete();
  atomsMapper->Delete();
  atomsActor->Delete();
}
<|endoftext|>


<commit_before>#include <QUrl>
#include <QtNetwork>

#include "api-client.h"

namespace {

const char *kContentTypeForm = "application/x-www-form-urlencoded";
const char *kAuthHeader = "Authorization";

} // namespace

QNetworkAccessManager* SeafileApiClient::na_mgr_ = NULL;

SeafileApiClient::SeafileApiClient()
{
    if (!na_mgr_) {
        na_mgr_ = new QNetworkAccessManager();
    }
}

SeafileApiClient::~SeafileApiClient()
{
    if (reply_) {
        reply_->deleteLater();
    }
}

void SeafileApiClient::get(const QUrl& url)
{
    QNetworkRequest request(url);

    if (token_.length() > 0) {
        char buf[1024];
        qsnprintf(buf, sizeof(buf), "Token %s", token_.toUtf8().data());
        request.setRawHeader(kAuthHeader, buf);
    }

    // qDebug("send request, url = %s\n, token = %s\n",
    //        request.url().toString().toUtf8().data(),
    //        request.rawHeader(kAuthHeader).data());

    reply_ = na_mgr_->get(request);

    connect(reply_, SIGNAL(sslErrors(const QList<QSslError>&)),
            this, SLOT(onSslErrors(const QList<QSslError>&)));

    connect(reply_, SIGNAL(finished()), this, SLOT(httpRequestFinished()));
}

void SeafileApiClient::post(const QUrl& url, const QByteArray& encodedParams)
{
    QNetworkRequest request(url);
    if (token_.length() > 0) {
        char buf[1024];
        qsnprintf(buf, sizeof(buf), "Token %s", token_.toUtf8().data());
        request.setRawHeader(kAuthHeader, buf);
    }
    request.setHeader(QNetworkRequest::ContentTypeHeader, kContentTypeForm);

    reply_ = na_mgr_->post(request, encodedParams);

    connect(reply_, SIGNAL(finished()), this, SLOT(httpRequestFinished()));

    connect(reply_, SIGNAL(sslErrors(const QList<QSslError>&)),
            this, SLOT(onSslErrors(const QList<QSslError>&)));
}

void SeafileApiClient::onSslErrors(const QList<QSslError>& errors)
{
    emit sslErrors(reply_, errors);
}

void SeafileApiClient::httpRequestFinished()
{
    int code = reply_->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    if (reply_->error() != QNetworkReply::NoError) {
        qDebug("http request failed: %s\n", reply_->errorString().toUtf8().data());
        emit requestFailed(code);
        return;
    }

    if ((code / 100) != 2) {
        qDebug("request failed : status code %d\n", code);
        emit requestFailed(code);
    }

    emit requestSuccess(*reply_);
}
<commit_msg>fixed a bug in api request<commit_after>#include <QUrl>
#include <QtNetwork>

#include "api-client.h"

namespace {

const char *kContentTypeForm = "application/x-www-form-urlencoded";
const char *kAuthHeader = "Authorization";

} // namespace

QNetworkAccessManager* SeafileApiClient::na_mgr_ = NULL;

SeafileApiClient::SeafileApiClient()
{
    if (!na_mgr_) {
        na_mgr_ = new QNetworkAccessManager();
    }
}

SeafileApiClient::~SeafileApiClient()
{
    if (reply_) {
        reply_->deleteLater();
    }
}

void SeafileApiClient::get(const QUrl& url)
{
    QNetworkRequest request(url);

    if (token_.length() > 0) {
        char buf[1024];
        qsnprintf(buf, sizeof(buf), "Token %s", token_.toUtf8().data());
        request.setRawHeader(kAuthHeader, buf);
    }

    // qDebug("send request, url = %s\n, token = %s\n",
    //        request.url().toString().toUtf8().data(),
    //        request.rawHeader(kAuthHeader).data());

    reply_ = na_mgr_->get(request);

    connect(reply_, SIGNAL(sslErrors(const QList<QSslError>&)),
            this, SLOT(onSslErrors(const QList<QSslError>&)));

    connect(reply_, SIGNAL(finished()), this, SLOT(httpRequestFinished()));
}

void SeafileApiClient::post(const QUrl& url, const QByteArray& encodedParams)
{
    QNetworkRequest request(url);
    if (token_.length() > 0) {
        char buf[1024];
        qsnprintf(buf, sizeof(buf), "Token %s", token_.toUtf8().data());
        request.setRawHeader(kAuthHeader, buf);
    }
    request.setHeader(QNetworkRequest::ContentTypeHeader, kContentTypeForm);

    reply_ = na_mgr_->post(request, encodedParams);

    connect(reply_, SIGNAL(finished()), this, SLOT(httpRequestFinished()));

    connect(reply_, SIGNAL(sslErrors(const QList<QSslError>&)),
            this, SLOT(onSslErrors(const QList<QSslError>&)));
}

void SeafileApiClient::onSslErrors(const QList<QSslError>& errors)
{
    emit sslErrors(reply_, errors);
}

void SeafileApiClient::httpRequestFinished()
{
    int code = reply_->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    if (reply_->error() != QNetworkReply::NoError) {
        qDebug("http request failed: %s\n", reply_->errorString().toUtf8().data());
        emit requestFailed(code);
        return;
    }

    if ((code / 100) == 4 || (code / 100) == 5) {
        qDebug("request failed : status code %d\n", code);
        emit requestFailed(code);
        return;
    }

    emit requestSuccess(*reply_);
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkOpenGLCamera.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

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 REGENTS 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 <math.h>

#include "vtkRenderWindow.h"
#include "vtkOpenGLRenderer.h"
#include "vtkOpenGLCamera.h"
#ifndef VTK_IMPLEMENT_MESA_CXX
#include <GL/gl.h>
#endif
#include "vtkObjectFactory.h"
#include "vtkOutputWindow.h"
#include "vtkgluPickMatrix.h"

//------------------------------------------------------------------------------
vtkOpenGLCamera* vtkOpenGLCamera::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkOpenGLCamera");
  if(ret)
    {
    return (vtkOpenGLCamera*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkOpenGLCamera;
}

// Implement base class method.
void vtkOpenGLCamera::Render(vtkRenderer *ren)
{
  float aspect[2];
  float *vport;
  int  *size, lowerLeft[2], upperRight[2];
  vtkMatrix4x4 *matrix = vtkMatrix4x4::New();

  // get the bounds of the window
  size = (ren->GetRenderWindow())->GetSize();

  // find out if we should stereo render
  this->Stereo = (ren->GetRenderWindow())->GetStereoRender();
  vport = ren->GetViewport();

  lowerLeft[0] = (int)(vport[0]*size[0] + 0.5);
  lowerLeft[1] = (int)(vport[1]*size[1] + 0.5);
  upperRight[0] = (int)(vport[2]*size[0] + 0.5);
  upperRight[1] = (int)(vport[3]*size[1] + 0.5);
  upperRight[0]--;
  upperRight[1]--;

  // if were on a stereo renderer draw to special parts of screen
  if (this->Stereo)
    {
    switch ((ren->GetRenderWindow())->GetStereoType())
      {
      case VTK_STEREO_CRYSTAL_EYES:
        if (this->LeftEye)
          {
          glDrawBuffer(GL_BACK_LEFT);
          }
        else
          {
          glDrawBuffer(GL_BACK_RIGHT);
          }
        break;
      default:
        break;
      }
    }
  else
    {
    if (ren->GetRenderWindow()->GetDoubleBuffer())
      {
      glDrawBuffer(GL_BACK);
      }
    else
      {
      glDrawBuffer(GL_FRONT);
      }
    }

  glViewport(lowerLeft[0],lowerLeft[1],
	     (upperRight[0]-lowerLeft[0]+1),
	     (upperRight[1]-lowerLeft[1]+1));
  glEnable( GL_SCISSOR_TEST );
  glScissor(lowerLeft[0],lowerLeft[1],
	    (upperRight[0]-lowerLeft[0]+1),
	    (upperRight[1]-lowerLeft[1]+1));

  /* for stereo we have to fiddle with aspect */
  aspect[0] = (float)(upperRight[0]-lowerLeft[0]+1)/
    (float)(upperRight[1]-lowerLeft[1]+1);
  aspect[1] = 1.0;

  ren->SetAspect(aspect);

  glMatrixMode( GL_PROJECTION);
  matrix->DeepCopy(this->GetPerspectiveTransformMatrix(aspect[0]/aspect[1],
						       -1,1));
  matrix->Transpose();
  if(ren->GetIsPicking())
    {
    GLint viewport[4];
    glGetIntegerv( GL_VIEWPORT, viewport);
    glLoadIdentity();
    vtkgluPickMatrix(ren->GetPickX(), ren->GetPickY(), 1, 1, viewport);
    glMultMatrixd(matrix->Element[0]);
    }
  else
    {
    // insert camera view transformation
    glLoadMatrixd(matrix->Element[0]);
    }

  // since lookat modifies the model view matrix do a push
  // first and set the mmode.  This will be undone in the
  // render action after the actors! message sis sent
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();

  matrix->DeepCopy(this->GetViewTransformMatrix());
  matrix->Transpose();

  // insert camera view transformation
  glMultMatrixd(matrix->Element[0]);

  if ((ren->GetRenderWindow())->GetErase())
    {
    ren->Clear();
    }

  // if we have a stereo renderer, draw other eye next time
  if (this->Stereo)
    {
    if (this->LeftEye)
      {
      this->LeftEye = 0;
      }
    else
      {
      this->LeftEye = 1;
      }
    }

  matrix->Delete();
}
<commit_msg>ERR: StereoModeLeft and StereoModeRight were broken<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkOpenGLCamera.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

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 REGENTS 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 <math.h>

#include "vtkRenderWindow.h"
#include "vtkOpenGLRenderer.h"
#include "vtkOpenGLCamera.h"
#ifndef VTK_IMPLEMENT_MESA_CXX
#include <GL/gl.h>
#endif
#include "vtkObjectFactory.h"
#include "vtkOutputWindow.h"
#include "vtkgluPickMatrix.h"

//------------------------------------------------------------------------------
vtkOpenGLCamera* vtkOpenGLCamera::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkOpenGLCamera");
  if(ret)
    {
    return (vtkOpenGLCamera*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkOpenGLCamera;
}

// Implement base class method.
void vtkOpenGLCamera::Render(vtkRenderer *ren)
{
  float aspect[2];
  float *vport;
  int  *size, lowerLeft[2], upperRight[2];
  vtkMatrix4x4 *matrix = vtkMatrix4x4::New();

  // get the bounds of the window
  size = (ren->GetRenderWindow())->GetSize();

  // find out if we should stereo render
  this->Stereo = (ren->GetRenderWindow())->GetStereoRender();
  vport = ren->GetViewport();

  lowerLeft[0] = (int)(vport[0]*size[0] + 0.5);
  lowerLeft[1] = (int)(vport[1]*size[1] + 0.5);
  upperRight[0] = (int)(vport[2]*size[0] + 0.5);
  upperRight[1] = (int)(vport[3]*size[1] + 0.5);
  upperRight[0]--;
  upperRight[1]--;

  // if were on a stereo renderer draw to special parts of screen
  if (this->Stereo)
    {
    switch ((ren->GetRenderWindow())->GetStereoType())
      {
      case VTK_STEREO_CRYSTAL_EYES:
        if (this->LeftEye)
          {
          glDrawBuffer(GL_BACK_LEFT);
          }
        else
          {
          glDrawBuffer(GL_BACK_RIGHT);
          }
        break;
      case VTK_STEREO_LEFT:
	this->LeftEye = 1;
	break;
      case VTK_STEREO_RIGHT:
	this->LeftEye = 0;
	break;
      default:
        break;
      }
    }
  else
    {
    if (ren->GetRenderWindow()->GetDoubleBuffer())
      {
      glDrawBuffer(GL_BACK);
      }
    else
      {
      glDrawBuffer(GL_FRONT);
      }
    }

  glViewport(lowerLeft[0],lowerLeft[1],
	     (upperRight[0]-lowerLeft[0]+1),
	     (upperRight[1]-lowerLeft[1]+1));
  glEnable( GL_SCISSOR_TEST );
  glScissor(lowerLeft[0],lowerLeft[1],
	    (upperRight[0]-lowerLeft[0]+1),
	    (upperRight[1]-lowerLeft[1]+1));

  /* for stereo we have to fiddle with aspect */
  aspect[0] = (float)(upperRight[0]-lowerLeft[0]+1)/
    (float)(upperRight[1]-lowerLeft[1]+1);
  aspect[1] = 1.0;

  ren->SetAspect(aspect);

  glMatrixMode( GL_PROJECTION);
  matrix->DeepCopy(this->GetPerspectiveTransformMatrix(aspect[0]/aspect[1],
						       -1,1));
  matrix->Transpose();
  if(ren->GetIsPicking())
    {
    GLint viewport[4];
    glGetIntegerv( GL_VIEWPORT, viewport);
    glLoadIdentity();
    vtkgluPickMatrix(ren->GetPickX(), ren->GetPickY(), 1, 1, viewport);
    glMultMatrixd(matrix->Element[0]);
    }
  else
    {
    // insert camera view transformation
    glLoadMatrixd(matrix->Element[0]);
    }

  // since lookat modifies the model view matrix do a push
  // first and set the mmode.  This will be undone in the
  // render action after the actors! message sis sent
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();

  matrix->DeepCopy(this->GetViewTransformMatrix());
  matrix->Transpose();

  // insert camera view transformation
  glMultMatrixd(matrix->Element[0]);

  if ((ren->GetRenderWindow())->GetErase())
    {
    ren->Clear();
    }

  // if we have a stereo renderer, draw other eye next time
  if (this->Stereo)
    {
    if (this->LeftEye)
      {
      this->LeftEye = 0;
      }
    else
      {
      this->LeftEye = 1;
      }
    }

  matrix->Delete();
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */
/* $Log $ */

//-----------------------------------------------------------------
//           Implementation of the ESD Calorimeter cluster class
//   ESD = Event Summary Data
//   This is the class to deal with during the phisics analysis of data
//
//   J.L. Klay (LLNL)
//-----------------------------------------------------------------

#include "AliESDCaloCluster.h"

ClassImp(AliESDCaloCluster)

//_______________________________________________________________________
AliESDCaloCluster::AliESDCaloCluster() :
  fID(0),
  fClusterType(-1),
  fEMCALCluster(kFALSE),
  fEnergy(-1),
  fDispersion(-1),
  fChi2(-1),
  fNumberOfDigits(0),
  fDigitAmplitude(0),
  fDigitTime(0),
  fDigitIndex(0)
{
  //
  // The default ESD constructor
  //
  fGlobalPos[0] = fGlobalPos[1] = fGlobalPos[2] = 0.;
  for(Int_t i=0; i<AliPID::kSPECIESN; i++) fPID[i] = 0.;
}

//_______________________________________________________________________
AliESDCaloCluster::AliESDCaloCluster(const AliESDCaloCluster& clus) :
  TObject(clus),
  fID(clus.fID),
  fClusterType(clus.fClusterType),
  fEMCALCluster(clus.fEMCALCluster),
  fEnergy(clus.fEnergy),
  fDispersion(clus.fDispersion),
  fChi2(clus.fChi2),
  fNumberOfDigits(clus.fNumberOfDigits)
{
  //
  // The copy constructor
  //
  fGlobalPos[0] = clus.fGlobalPos[0];
  fGlobalPos[1] = clus.fGlobalPos[1];
  fGlobalPos[2] = clus.fGlobalPos[2];

  for(Int_t i=0; i<AliPID::kSPECIESN; i++) fPID[i] = clus.fPID[i];

  fDigitAmplitude = clus.fDigitAmplitude;
  fDigitTime = clus.fDigitTime;
  fDigitIndex = clus.fDigitIndex;

}

//_______________________________________________________________________
AliESDCaloCluster::~AliESDCaloCluster(){
  //
  // This is destructor according Coding Conventrions
  //
  //printf("Delete cluster\n");

  //Not sure why but it won't let me delete these in the dtor here.
  //The Reconstruction gives me the error
  //*** glibc detected *** double free or corruption (!prev):
  //0x0c1550b0 ***
  /*
  if(fDigitAmplitude)
    delete[] fDigitAmplitude;
  if(fDigitTime)
    delete[] fDigitTime;
  if(fDigitIndex)
    delete[] fDigitIndex;
  */
}

//_______________________________________________________________________
void AliESDCaloCluster::SetPid(const Float_t *p) {
  // Sets the probability of each particle type
  // Copied from AliESDtrack SetPIDValues
  // This function copies "n" PID weights from "scr" to "dest"
  // and normalizes their sum to 1 thus producing conditional
  // probabilities.
  // The negative weights are set to 0.
  // In case all the weights are non-positive they are replaced by
  // uniform probabilities

  Int_t n = AliPID::kSPECIESN;

  Float_t uniform = 1./(Float_t)n;

  Float_t sum = 0;
  for (Int_t i=0; i<n; i++)
    if (p[i]>=0) {
      sum+=p[i];
      fPID[i] = p[i];
    }
    else {
      fPID[i] = 0;
    }

  if(sum>0)
    for (Int_t i=0; i<n; i++) fPID[i] /= sum;
  else
    for (Int_t i=0; i<n; i++) fPID[i] = uniform;

}
<commit_msg>Initialization of data members<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */
/* $Log $ */

//-----------------------------------------------------------------
//           Implementation of the ESD Calorimeter cluster class
//   ESD = Event Summary Data
//   This is the class to deal with during the phisics analysis of data
//
//   J.L. Klay (LLNL)
//-----------------------------------------------------------------

#include "AliESDCaloCluster.h"

ClassImp(AliESDCaloCluster)

//_______________________________________________________________________
AliESDCaloCluster::AliESDCaloCluster() :
  fID(0),
  fClusterType(-1),
  fEMCALCluster(kFALSE),
  fEnergy(-1),
  fDispersion(-1),
  fChi2(-1),
  fPrimaryIndex(-1),
  fM20(0),
  fM02(0),
  fM11(0),
  fNExMax(0),
  fEmcCpvDistance(9999),
  fNumberOfDigits(0),
  fDigitAmplitude(0),
  fDigitTime(0),
  fDigitIndex(0)
{
  //
  // The default ESD constructor
  //
  fGlobalPos[0] = fGlobalPos[1] = fGlobalPos[2] = 0.;
  for(Int_t i=0; i<AliPID::kSPECIESN; i++) fPID[i] = 0.;
}

//_______________________________________________________________________
AliESDCaloCluster::AliESDCaloCluster(const AliESDCaloCluster& clus) :
  TObject(clus),
  fID(clus.fID),
  fClusterType(clus.fClusterType),
  fEMCALCluster(clus.fEMCALCluster),
  fEnergy(clus.fEnergy),
  fDispersion(clus.fDispersion),
  fChi2(clus.fChi2),
  fPrimaryIndex(clus.fPrimaryIndex),
  fM20(clus.fM20),
  fM02(clus.fM02),
  fM11(clus.fNExMax),
  fNExMax(clus.fNExMax),
  fEmcCpvDistance(clus.fEmcCpvDistance),
  fNumberOfDigits(clus.fNumberOfDigits)
{
  //
  // The copy constructor
  //
  fGlobalPos[0] = clus.fGlobalPos[0];
  fGlobalPos[1] = clus.fGlobalPos[1];
  fGlobalPos[2] = clus.fGlobalPos[2];

  for(Int_t i=0; i<AliPID::kSPECIESN; i++) fPID[i] = clus.fPID[i];

  fDigitAmplitude = clus.fDigitAmplitude;
  fDigitTime = clus.fDigitTime;
  fDigitIndex = clus.fDigitIndex;

}

//_______________________________________________________________________
AliESDCaloCluster::~AliESDCaloCluster(){
  //
  // This is destructor according Coding Conventrions
  //
  //printf("Delete cluster\n");

  //Not sure why but it won't let me delete these in the dtor here.
  //The Reconstruction gives me the error
  //*** glibc detected *** double free or corruption (!prev):
  //0x0c1550b0 ***
  /*
  if(fDigitAmplitude)
    delete[] fDigitAmplitude;
  if(fDigitTime)
    delete[] fDigitTime;
  if(fDigitIndex)
    delete[] fDigitIndex;
  */
}

//_______________________________________________________________________
void AliESDCaloCluster::SetPid(const Float_t *p) {
  // Sets the probability of each particle type
  // Copied from AliESDtrack SetPIDValues
  // This function copies "n" PID weights from "scr" to "dest"
  // and normalizes their sum to 1 thus producing conditional
  // probabilities.
  // The negative weights are set to 0.
  // In case all the weights are non-positive they are replaced by
  // uniform probabilities

  Int_t n = AliPID::kSPECIESN;

  Float_t uniform = 1./(Float_t)n;

  Float_t sum = 0;
  for (Int_t i=0; i<n; i++)
    if (p[i]>=0) {
      sum+=p[i];
      fPID[i] = p[i];
    }
    else {
      fPID[i] = 0;
    }

  if(sum>0)
    for (Int_t i=0; i<n; i++) fPID[i] /= sum;
  else
    for (Int_t i=0; i<n; i++) fPID[i] = uniform;

}
<|endoftext|>