<commit_before>/*
 * Android File Transfer for Linux: MTP client for android devices
 * Copyright (C) 2015  Vladimir Menshakov

 * 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 "mtpobjectsmodel.h"
#include <QDebug>
#include <QBrush>
#include <QColor>
#include <QFile>
#include <QFileInfo>

MtpObjectsModel::MtpObjectsModel(QObject *parent): QAbstractListModel(parent), _parentObjectId(mtp::Session::Root)
{ }

MtpObjectsModel::~MtpObjectsModel()
{ }

void MtpObjectsModel::setParent(mtp::u32 parentObjectId)
{
	beginResetModel();

	_parentObjectId = parentObjectId;
	mtp::msg::ObjectHandles handles = _session->GetObjectHandles(mtp::Session::AllStorages, mtp::Session::AllFormats, parentObjectId);
	_rows.clear();
	_rows.reserve(handles.ObjectHandles.size());
	for(size_t i = 0; i < handles.ObjectHandles.size(); ++i)
	{
		mtp::u32 oid = handles.ObjectHandles[i];
		_rows.append(Row(oid));
	}

	endResetModel();
}

bool MtpObjectsModel::enter(int idx)
{
	if (idx < 0 || idx >= _rows.size())
		return false;

	Row &row = _rows[idx];
	if (row.IsAssociation(_session))
	{
		setParent(row.ObjectId);
		return true;
	}
	else
		return false;
}

void MtpObjectsModel::setSession(mtp::SessionPtr session)
{
	beginResetModel();
	_session = session;
	setParent(mtp::Session::Root);
	endResetModel();
}

int MtpObjectsModel::rowCount(const QModelIndex &) const
{ return _rows.size(); }

mtp::msg::ObjectInfoPtr MtpObjectsModel::Row::GetInfo(mtp::SessionPtr session)
{
	if (!_info)
	{
		_info = std::make_shared<mtp::msg::ObjectInfo>();
		try
		{
			*_info = session->GetObjectInfo(ObjectId);
			//qDebug() << QString::fromUtf8(row.Info->Filename.c_str());
		}
		catch(const std::exception &ex)
		{ qDebug() << "failed to get object info " << ex.what(); }
	}
	return _info;
}

bool MtpObjectsModel::Row::IsAssociation(mtp::SessionPtr session)
{
	mtp::ObjectFormat format = GetInfo(session)->ObjectFormat;
	return format == mtp::ObjectFormat::Association || format == mtp::ObjectFormat::AudioAlbum;
}

void MtpObjectsModel::rename(int idx, const QString &fileName)
{
	qDebug() << "renaming row " << idx << " to " << fileName;
	_session->SetObjectProperty(objectIdAt(idx), mtp::ObjectProperty::ObjectFilename, fileName.toStdString());
	_rows[idx].ResetInfo();
	emit dataChanged(createIndex(idx, 0), createIndex(idx, 0));
}

bool MtpObjectsModel::removeRows (int row, int count, const QModelIndex & parent )
{
	qDebug() << "remove rows " << row << " " << count;
	beginRemoveRows(parent, row, row + count - 1);
	for(int i = 0; i < count; ++i)
	{
		mtp::u32 oid = objectIdAt(row + i);
		if (oid == 0)
			continue;
		_session->DeleteObject(oid);
	}
	_rows.remove(row, count);

	endRemoveRows();
	return false;
}

mtp::u32 MtpObjectsModel::objectIdAt(int idx)
{
	return (idx >= 0 && idx < _rows.size())? _rows[idx].ObjectId: 0;
}

QVariant MtpObjectsModel::data(const QModelIndex &index, int role) const
{
	int row_idx = index.row();
	if (row_idx < 0 || row_idx > _rows.size())
		return QVariant();

	Row &row = _rows[row_idx];

	switch(role)
	{
	case Qt::DisplayRole:
		return QString::fromUtf8(row.GetInfo(_session)->Filename.c_str());

	case Qt::ForegroundRole:
		return row.IsAssociation(_session)? QBrush(QColor(0, 0, 128)): QBrush(Qt::black);

	default:
		return QVariant();
	}
}

mtp::u32 MtpObjectsModel::createDirectory(const QString &name, bool album)
{
	mtp::msg::ObjectInfo oi;
	QByteArray filename = name.toUtf8();
	oi.Filename = filename.data();
	oi.ObjectFormat = mtp::ObjectFormat::Association;
	oi.AssociationType = album? 2: 1; //fixme: move into enum
	mtp::Session::NewObjectInfo noi = _session->SendObjectInfo(oi, 0, _parentObjectId);
	beginInsertRows(QModelIndex(), _rows.size(), _rows.size());
	_rows.push_back(Row(noi.ObjectId));
	endInsertRows();
	return noi.ObjectId;
}

bool MtpObjectsModel::uploadFile(const QString &filePath, QString filename)
{
	QFileInfo fileInfo(filePath);
	mtp::ObjectFormat objectFormat = mtp::ObjectFormatFromFilename(filePath.toStdString());

	if (filename.isEmpty())
		filename = fileInfo.fileName();
	qDebug() << "uploadFile " << fileInfo.fileName() << " as " << filename;

	mtp::ByteArray data;
	{
		QFile file(filePath);
		file.open(QFile::ReadOnly);
		if (!file.isOpen())
		{
			qWarning() << "file " << filePath << " could not be opened";
			return false;
		}
		QByteArray qdata = file.readAll();
		file.close();
		data.assign(qdata.begin(), qdata.end());
	}
	qDebug() << "sending " << data.size() << " bytes";

	mtp::msg::ObjectInfo oi;
	QByteArray filename_utf = filename.toUtf8();
	oi.Filename = filename_utf.data();
	oi.ObjectFormat = objectFormat;
	oi.ObjectCompressedSize = data.size();
	mtp::Session::NewObjectInfo noi = _session->SendObjectInfo(oi, 0, _parentObjectId);
	qDebug() << "new object id: " << noi.ObjectId << ", sending...";
	_session->SendObject(data);
	qDebug() << "ok";
	beginInsertRows(QModelIndex(), _rows.size(), _rows.size());
	_rows.push_back(Row(noi.ObjectId));
	endInsertRows();
	return true;
}

bool MtpObjectsModel::downloadFile(const QString &filePath, mtp::u32 objectId)
{
	QFile file(filePath);
	file.open(QFile::WriteOnly);
	if (!file.isOpen())
		return false;

	mtp::ByteArray data = _session->GetObject(objectId);
	file.write(reinterpret_cast<const char *>(data.data()), data.size());
	file.close();
	return true;
}

mtp::msg::ObjectInfoPtr MtpObjectsModel::getInfo(mtp::u32 objectId)
{
	return std::make_shared<mtp::msg::ObjectInfo>(_session->GetObjectInfo(objectId));
}
<commit_msg>ported qt interface to streams<commit_after>/*
 * Android File Transfer for Linux: MTP client for android devices
 * Copyright (C) 2015  Vladimir Menshakov

 * 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 "mtpobjectsmodel.h"
#include <QDebug>
#include <QBrush>
#include <QColor>
#include <QFile>
#include <QFileInfo>

namespace
{

	class QtObjectInputStream : public mtp::IObjectInputStream
	{
		QFile _file;

	public:
		QtObjectInputStream(const QString &file) : _file(file) {
			_file.open(QFile::ReadOnly);
		}

		bool Valid() const
		{ return _file.isOpen(); }

		virtual size_t GetSize() const
		{ return _file.size(); }

		virtual size_t Read(mtp::u8 *data, size_t size)
		{ return _file.read(static_cast<char *>(static_cast<void *>(data)), size); }
	};

	class QtObjectOutputStream : public mtp::IObjectOutputStream
	{
		QFile _file;
	public:
		QtObjectOutputStream(const QString &file): _file(file)
		{ _file.open(QFile::WriteOnly); }

		bool Valid() const
		{ return _file.isOpen(); }

		virtual size_t GetSize() const
		{ return _file.size(); }

		virtual size_t Write(const mtp::u8 *data, size_t size)
		{ return _file.write(static_cast<const char *>(static_cast<const void *>(data)), size); }
	};

}

MtpObjectsModel::MtpObjectsModel(QObject *parent): QAbstractListModel(parent), _parentObjectId(mtp::Session::Root)
{ }

MtpObjectsModel::~MtpObjectsModel()
{ }

void MtpObjectsModel::setParent(mtp::u32 parentObjectId)
{
	beginResetModel();

	_parentObjectId = parentObjectId;
	mtp::msg::ObjectHandles handles = _session->GetObjectHandles(mtp::Session::AllStorages, mtp::Session::AllFormats, parentObjectId);
	_rows.clear();
	_rows.reserve(handles.ObjectHandles.size());
	for(size_t i = 0; i < handles.ObjectHandles.size(); ++i)
	{
		mtp::u32 oid = handles.ObjectHandles[i];
		_rows.append(Row(oid));
	}

	endResetModel();
}

bool MtpObjectsModel::enter(int idx)
{
	if (idx < 0 || idx >= _rows.size())
		return false;

	Row &row = _rows[idx];
	if (row.IsAssociation(_session))
	{
		setParent(row.ObjectId);
		return true;
	}
	else
		return false;
}

void MtpObjectsModel::setSession(mtp::SessionPtr session)
{
	beginResetModel();
	_session = session;
	setParent(mtp::Session::Root);
	endResetModel();
}

int MtpObjectsModel::rowCount(const QModelIndex &) const
{ return _rows.size(); }

mtp::msg::ObjectInfoPtr MtpObjectsModel::Row::GetInfo(mtp::SessionPtr session)
{
	if (!_info)
	{
		_info = std::make_shared<mtp::msg::ObjectInfo>();
		try
		{
			*_info = session->GetObjectInfo(ObjectId);
			//qDebug() << QString::fromUtf8(row.Info->Filename.c_str());
		}
		catch(const std::exception &ex)
		{ qDebug() << "failed to get object info " << ex.what(); }
	}
	return _info;
}

bool MtpObjectsModel::Row::IsAssociation(mtp::SessionPtr session)
{
	mtp::ObjectFormat format = GetInfo(session)->ObjectFormat;
	return format == mtp::ObjectFormat::Association || format == mtp::ObjectFormat::AudioAlbum;
}

void MtpObjectsModel::rename(int idx, const QString &fileName)
{
	qDebug() << "renaming row " << idx << " to " << fileName;
	_session->SetObjectProperty(objectIdAt(idx), mtp::ObjectProperty::ObjectFilename, fileName.toStdString());
	_rows[idx].ResetInfo();
	emit dataChanged(createIndex(idx, 0), createIndex(idx, 0));
}

bool MtpObjectsModel::removeRows (int row, int count, const QModelIndex & parent )
{
	qDebug() << "remove rows " << row << " " << count;
	beginRemoveRows(parent, row, row + count - 1);
	for(int i = 0; i < count; ++i)
	{
		mtp::u32 oid = objectIdAt(row + i);
		if (oid == 0)
			continue;
		_session->DeleteObject(oid);
	}
	_rows.remove(row, count);

	endRemoveRows();
	return false;
}

mtp::u32 MtpObjectsModel::objectIdAt(int idx)
{
	return (idx >= 0 && idx < _rows.size())? _rows[idx].ObjectId: 0;
}

QVariant MtpObjectsModel::data(const QModelIndex &index, int role) const
{
	int row_idx = index.row();
	if (row_idx < 0 || row_idx > _rows.size())
		return QVariant();

	Row &row = _rows[row_idx];

	switch(role)
	{
	case Qt::DisplayRole:
		return QString::fromUtf8(row.GetInfo(_session)->Filename.c_str());

	case Qt::ForegroundRole:
		return row.IsAssociation(_session)? QBrush(QColor(0, 0, 128)): QBrush(Qt::black);

	default:
		return QVariant();
	}
}

mtp::u32 MtpObjectsModel::createDirectory(const QString &name, bool album)
{
	mtp::msg::ObjectInfo oi;
	QByteArray filename = name.toUtf8();
	oi.Filename = filename.data();
	oi.ObjectFormat = mtp::ObjectFormat::Association;
	oi.AssociationType = album? 2: 1; //fixme: move into enum
	mtp::Session::NewObjectInfo noi = _session->SendObjectInfo(oi, 0, _parentObjectId);
	beginInsertRows(QModelIndex(), _rows.size(), _rows.size());
	_rows.push_back(Row(noi.ObjectId));
	endInsertRows();
	return noi.ObjectId;
}

bool MtpObjectsModel::uploadFile(const QString &filePath, QString filename)
{
	QFileInfo fileInfo(filePath);
	mtp::ObjectFormat objectFormat = mtp::ObjectFormatFromFilename(filePath.toStdString());

	if (filename.isEmpty())
		filename = fileInfo.fileName();
	qDebug() << "uploadFile " << fileInfo.fileName() << " as " << filename;

	std::shared_ptr<QtObjectInputStream> object(new QtObjectInputStream(filePath));
	if (!object->Valid())
	{
		qWarning() << "file " << filePath << " could not be opened";
		return false;
	}
	qDebug() << "sending " << fileInfo.size() << " bytes";

	mtp::msg::ObjectInfo oi;
	QByteArray filename_utf = filename.toUtf8();
	oi.Filename = filename_utf.data();
	oi.ObjectFormat = objectFormat;
	oi.ObjectCompressedSize = fileInfo.size();
	mtp::Session::NewObjectInfo noi = _session->SendObjectInfo(oi, 0, _parentObjectId);
	qDebug() << "new object id: " << noi.ObjectId << ", sending...";
	_session->SendObject(object);
	qDebug() << "ok";
	beginInsertRows(QModelIndex(), _rows.size(), _rows.size());
	_rows.push_back(Row(noi.ObjectId));
	endInsertRows();
	return true;
}

bool MtpObjectsModel::downloadFile(const QString &filePath, mtp::u32 objectId)
{
	std::shared_ptr<QtObjectOutputStream> object(new QtObjectOutputStream(filePath));
	if (!object->Valid())
	{
		qWarning() << "cannot open file " << filePath;
		return false;
	}
	_session->GetObject(objectId, object);
	return true;
}

mtp::msg::ObjectInfoPtr MtpObjectsModel::getInfo(mtp::u32 objectId)
{
	return std::make_shared<mtp::msg::ObjectInfo>(_session->GetObjectInfo(objectId));
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkDebugLeaks.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkDebugLeaks.h"

#include "vtkCriticalSection.h"
#include "vtkObjectFactory.h"
#include "vtkWindows.h"

#include <string>

static const char *vtkDebugLeaksIgnoreClasses[] = {
  0
};

//----------------------------------------------------------------------------
// return 1 if the class should be ignored
static int vtkDebugLeaksIgnoreClassesCheck(const char* s)
{
  int i =0;
  while(vtkDebugLeaksIgnoreClasses[i])
    {
    if(strcmp(s, vtkDebugLeaksIgnoreClasses[i]) == 0)
      {
      return 1;
      }
    i++;
    }
  return 0;
}

vtkStandardNewMacro(vtkDebugLeaks);

//----------------------------------------------------------------------------
// A hash function for converting a string to a long
static inline size_t vtkHashString(const char* s)
{
  unsigned long h = 0;
  for ( ; *s; ++s)
    {
    h = 5*h + *s;
    }
  return size_t(h);
}

//----------------------------------------------------------------------------
class vtkDebugLeaksHashNode
{
public:
  vtkDebugLeaksHashNode()
    {
      this->Count =1; // if it goes in, then there is one of them
      this->Key = 0;
      this->Next =0;
    }
  void Print(std::string& os)
    {
      if(this->Count)
        {
        char tmp[256];
        sprintf(tmp,"\" has %i %s still around.\n",this->Count,
                (this->Count == 1) ? "instance" : "instances");
        os += "Class \"";
        os += this->Key;
        os += tmp;
        }
    }
  ~vtkDebugLeaksHashNode()
    {
      delete [] this->Key;
      delete this->Next;
    }
public:
  vtkDebugLeaksHashNode *Next;
  char *Key;
  int Count;
};

//----------------------------------------------------------------------------
class vtkDebugLeaksHashTable
{
public:
  vtkDebugLeaksHashTable();
  vtkDebugLeaksHashNode* GetNode(const char* name);
  void IncrementCount(const char *name);
  unsigned int GetCount(const char *name);
  int DecrementCount(const char* name);
  void PrintTable(std::string &os);
  int IsEmpty();
  ~vtkDebugLeaksHashTable()
    {
      for (int i = 0; i < 64; i++)
        {
        vtkDebugLeaksHashNode *pos = this->Nodes[i];
        delete pos;
        }
    }

private:
  vtkDebugLeaksHashNode* Nodes[64];
};

//----------------------------------------------------------------------------
vtkDebugLeaksHashTable::vtkDebugLeaksHashTable()
{
  int i;
  for (i = 0; i < 64; i++)
    {
    this->Nodes[i] = NULL;
    }
}

//----------------------------------------------------------------------------
void vtkDebugLeaksHashTable::IncrementCount(const char * name)
{
  vtkDebugLeaksHashNode *pos;
  vtkDebugLeaksHashNode *newpos;
  int loc;

  pos = this->GetNode(name);
  if(pos)
    {
    pos->Count++;
    return;
    }

  newpos = new vtkDebugLeaksHashNode;
  newpos->Key = strcpy(new char[strlen(name)+1], name);

  loc = (static_cast<unsigned long>(vtkHashString(name)) & 0x03f0) / 16;

  pos = this->Nodes[loc];
  if (!pos)
    {
    this->Nodes[loc] = newpos;
    return;
    }
  while (pos->Next)
    {
    pos = pos->Next;
    }
  pos->Next = newpos;
}

//----------------------------------------------------------------------------
vtkDebugLeaksHashNode* vtkDebugLeaksHashTable::GetNode(const char* key)
{
  vtkDebugLeaksHashNode *pos;
  int loc = (static_cast<unsigned long>(vtkHashString(key)) & 0x03f0) / 16;

  pos = this->Nodes[loc];

  if (!pos)
    {
    return NULL;
    }
  while ((pos) && (strcmp(pos->Key, key) != 0) )
    {
    pos = pos->Next;
    }
  return pos;
}

//----------------------------------------------------------------------------
unsigned int vtkDebugLeaksHashTable::GetCount(const char* key)
{
  vtkDebugLeaksHashNode *pos;
  int loc = (static_cast<unsigned long>(vtkHashString(key)) & 0x03f0) / 16;

  pos = this->Nodes[loc];

  if (!pos)
    {
    return 0;
    }
  while ((pos)&&(pos->Key != key))
    {
    pos = pos->Next;
    }
  if (pos)
    {
    return pos->Count;
    }
  return 0;
}

//----------------------------------------------------------------------------
int vtkDebugLeaksHashTable::IsEmpty()
{
  int count = 0;
  for(int i =0; i < 64; i++)
    {
    vtkDebugLeaksHashNode *pos = this->Nodes[i];
    if(pos)
      {
      if(!vtkDebugLeaksIgnoreClassesCheck(pos->Key))
        {
        count += pos->Count;
        }
      while(pos->Next)
        {
        pos = pos->Next;
        if(!vtkDebugLeaksIgnoreClassesCheck(pos->Key))
          {
          count += pos->Count;
          }
        }
      }
    }
  return !count;
}

//----------------------------------------------------------------------------
int vtkDebugLeaksHashTable::DecrementCount(const char *key)
{

  vtkDebugLeaksHashNode *pos = this->GetNode(key);
  if(pos)
    {
    pos->Count--;
    return 1;
    }
  else
    {
    return 0;
    }
}

//----------------------------------------------------------------------------
void vtkDebugLeaksHashTable::PrintTable(std::string &os)
{
  for(int i =0; i < 64; i++)
    {
    vtkDebugLeaksHashNode *pos = this->Nodes[i];
    if(pos)
      {
      if(!vtkDebugLeaksIgnoreClassesCheck(pos->Key))
        {
        pos->Print(os);
        }
      while(pos->Next)
        {
        pos = pos->Next;
        if(!vtkDebugLeaksIgnoreClassesCheck(pos->Key))
          {
          pos->Print(os);
          }
        }
      }
    }
}

//----------------------------------------------------------------------------
#ifdef VTK_DEBUG_LEAKS
void vtkDebugLeaks::ConstructClass(const char* name)
{
  vtkDebugLeaks::CriticalSection->Lock();
  vtkDebugLeaks::MemoryTable->IncrementCount(name);
  vtkDebugLeaks::CriticalSection->Unlock();
}
#else
void vtkDebugLeaks::ConstructClass(const char*)
{
}
#endif

//----------------------------------------------------------------------------
#ifdef VTK_DEBUG_LEAKS
void vtkDebugLeaks::DestructClass(const char* p)
{
  vtkDebugLeaks::CriticalSection->Lock();
  // Due to globals being deleted, this table may already have
  // been deleted.
  if(vtkDebugLeaks::MemoryTable &&
     !vtkDebugLeaks::MemoryTable->DecrementCount(p))
    {
    vtkDebugLeaks::CriticalSection->Unlock();
    vtkGenericWarningMacro("Deleting unknown object: " << p);
    }
  else
    {
    vtkDebugLeaks::CriticalSection->Unlock();
    }
}
#else
void vtkDebugLeaks::DestructClass(const char*)
{
}
#endif

//----------------------------------------------------------------------------
void vtkDebugLeaks::SetDebugLeaksObserver(vtkDebugLeaksObserver* observer)
{
  vtkDebugLeaks::Observer = observer;
}

//----------------------------------------------------------------------------
vtkDebugLeaksObserver* vtkDebugLeaks::GetDebugLeaksObserver()
{
  return vtkDebugLeaks::Observer;
}

//----------------------------------------------------------------------------
void vtkDebugLeaks::ConstructingObject(vtkObjectBase* object)
{
  if (vtkDebugLeaks::Observer)
    {
    vtkDebugLeaks::Observer->ConstructingObject(object);
    }
}

//----------------------------------------------------------------------------
void vtkDebugLeaks::DestructingObject(vtkObjectBase* object)
{
  if (vtkDebugLeaks::Observer)
    {
    vtkDebugLeaks::Observer->DestructingObject(object);
    }
}

//----------------------------------------------------------------------------
int vtkDebugLeaks::PrintCurrentLeaks()
{
#ifdef VTK_DEBUG_LEAKS
  if(vtkDebugLeaks::MemoryTable->IsEmpty())
    {
    return 0;
    }

  // we must not use stringstream ior strstream due to problems with
  // finalizers in MSVC
  std::string leaks;
  vtkDebugLeaks::MemoryTable->PrintTable(leaks);
#ifdef _WIN32
  fprintf(stderr,"%s",leaks.c_str());
  fflush(stderr);
  int cancel=0;
  if(getenv("DASHBOARD_TEST_FROM_CTEST") ||
     getenv("DART_TEST_FROM_DART"))
    {
    // Skip dialogs when running on dashboard.
    return 1;
    }
  std::string::size_type myPos = 0;
  int count = 0;
  std::string msg;
  msg = "vtkDebugLeaks has detected LEAKS!\n";
  while(!cancel && myPos != leaks.npos)
    {
    std::string::size_type newPos = leaks.find('\n',myPos);
    if (newPos != leaks.npos)
      {
      msg += leaks.substr(myPos,newPos-myPos);
      msg += "\n";
      myPos = newPos;
      myPos++;
      }
    else
      {
      myPos = newPos;
      }
    count++;
    if (count == 10)
      {
      count = 0;
      cancel = vtkDebugLeaks::DisplayMessageBox(msg.c_str());
      msg = "";
      }
    }
  if (!cancel && count > 0)
    {
    vtkDebugLeaks::DisplayMessageBox(msg.c_str());
    }
#else
  cout << "vtkDebugLeaks has detected LEAKS!\n";
  cout << leaks.c_str() << endl;
#endif
#endif
  return 1;
}

//----------------------------------------------------------------------------
#ifdef _WIN32
int vtkDebugLeaks::DisplayMessageBox(const char* msg)
{
#ifdef UNICODE
  wchar_t *wmsg = new wchar_t [mbstowcs(NULL, msg, 32000)+1];
  mbstowcs(wmsg, msg, 32000);
  int result = (MessageBox(NULL, wmsg, L"Error",
                           MB_ICONERROR | MB_OKCANCEL) == IDCANCEL);
  delete [] wmsg;
#else
  int result = (MessageBox(NULL, msg, "Error",
                           MB_ICONERROR | MB_OKCANCEL) == IDCANCEL);
#endif
  return result;
}
#else
int vtkDebugLeaks::DisplayMessageBox(const char*)
{
  return 0;
}
#endif

//----------------------------------------------------------------------------
int vtkDebugLeaks::GetExitError()
{
  return vtkDebugLeaks::ExitError;
}

//----------------------------------------------------------------------------
void vtkDebugLeaks::SetExitError(int flag)
{
  vtkDebugLeaks::ExitError = flag;
}

//----------------------------------------------------------------------------
void vtkDebugLeaks::ClassInitialize()
{
#ifdef VTK_DEBUG_LEAKS
  // Create the hash table.
  vtkDebugLeaks::MemoryTable = new vtkDebugLeaksHashTable;

  // Create the lock for the critical sections.
  vtkDebugLeaks::CriticalSection = new vtkSimpleCriticalSection;

  // Default to error when leaks occur while running tests.
  vtkDebugLeaks::ExitError = 1;
  vtkDebugLeaks::Observer = 0;
#else
  vtkDebugLeaks::MemoryTable = 0;
  vtkDebugLeaks::CriticalSection = 0;
  vtkDebugLeaks::ExitError = 0;
  vtkDebugLeaks::Observer = 0;
#endif
}

//----------------------------------------------------------------------------
void vtkDebugLeaks::ClassFinalize()
{
#ifdef VTK_DEBUG_LEAKS
  // Report leaks.
  int leaked = vtkDebugLeaks::PrintCurrentLeaks();

  // Destroy the hash table.
  delete vtkDebugLeaks::MemoryTable;
  vtkDebugLeaks::MemoryTable = 0;

  // Destroy the lock for the critical sections.
  delete vtkDebugLeaks::CriticalSection;
  vtkDebugLeaks::CriticalSection = 0;

  // Exit with error if leaks occurred and error mode is on.
  if(leaked && vtkDebugLeaks::ExitError)
    {
    exit(1);
    }
#endif
}

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

// Purposely not initialized.  ClassInitialize will handle it.
vtkDebugLeaksHashTable* vtkDebugLeaks::MemoryTable;

// Purposely not initialized.  ClassInitialize will handle it.
vtkSimpleCriticalSection* vtkDebugLeaks::CriticalSection;

// Purposely not initialized.  ClassInitialize will handle it.
int vtkDebugLeaks::ExitError;

// Purposely not initialized.  ClassInitialize will handle it.
vtkDebugLeaksObserver* vtkDebugLeaks::Observer;
<commit_msg>Code review of vtkDebugLeaks, misc minor improvements<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkDebugLeaks.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkDebugLeaks.h"

#include "vtkCriticalSection.h"
#include "vtkObjectFactory.h"
#include "vtkWindows.h"

#include <string>

#if defined(_MSC_VER) && (_MSC_VER < 1900)
#define snprintf _snprintf
#endif

static const char *vtkDebugLeaksIgnoreClasses[] = {
  0
};

//----------------------------------------------------------------------------
// return 1 if the class should be ignored
static int vtkDebugLeaksIgnoreClassesCheck(const char* s)
{
  int i = 0;
  while(vtkDebugLeaksIgnoreClasses[i])
    {
    if(strcmp(s, vtkDebugLeaksIgnoreClasses[i]) == 0)
      {
      return 1;
      }
    i++;
    }
  return 0;
}

vtkStandardNewMacro(vtkDebugLeaks);

//----------------------------------------------------------------------------
// A hash function for converting a string to a long
static inline size_t vtkHashString(const char* s)
{
  unsigned long h = 0;
  for ( ; *s; ++s)
    {
    h = 5*h + *s;
    }
  return static_cast<size_t>(h);
}

//----------------------------------------------------------------------------
class vtkDebugLeaksHashNode
{
public:
  vtkDebugLeaksHashNode()
    {
      this->Count = 1; // if it goes in, then there is one of them
      this->Key = 0;
      this->Next = 0;
    }
  void Print(std::string& os)
    {
      if(this->Count)
        {
        char tmp[256];
        snprintf(tmp, 256, "\" has %i %s still around.\n",this->Count,
                 (this->Count == 1) ? "instance" : "instances");
        os += "Class \"";
        os += this->Key;
        os += tmp;
        }
    }
  ~vtkDebugLeaksHashNode()
    {
      delete [] this->Key;
      delete this->Next;
    }
public:
  vtkDebugLeaksHashNode *Next;
  char *Key;
  int Count;
};

//----------------------------------------------------------------------------
class vtkDebugLeaksHashTable
{
public:
  vtkDebugLeaksHashTable();
  vtkDebugLeaksHashNode* GetNode(const char* name);
  void IncrementCount(const char *name);
  unsigned int GetCount(const char *name);
  int DecrementCount(const char* name);
  void PrintTable(std::string &os);
  int IsEmpty();
  ~vtkDebugLeaksHashTable()
    {
      for (int i = 0; i < 64; i++)
        {
        vtkDebugLeaksHashNode *pos = this->Nodes[i];
        delete pos;
        }
    }

private:
  vtkDebugLeaksHashNode* Nodes[64];
};

//----------------------------------------------------------------------------
vtkDebugLeaksHashTable::vtkDebugLeaksHashTable()
{
  for (int i = 0; i < 64; i++)
    {
    this->Nodes[i] = NULL;
    }
}

//----------------------------------------------------------------------------
void vtkDebugLeaksHashTable::IncrementCount(const char * name)
{
  vtkDebugLeaksHashNode *pos = this->GetNode(name);
  if(pos)
    {
    pos->Count++;
    return;
    }

  vtkDebugLeaksHashNode *newpos = new vtkDebugLeaksHashNode;
  newpos->Key = strcpy(new char[strlen(name)+1], name);

  unsigned long loc = (static_cast<unsigned long>(vtkHashString(name)) & 0x03f0) / 16;

  pos = this->Nodes[loc];
  if (!pos)
    {
    this->Nodes[loc] = newpos;
    return;
    }
  while (pos->Next)
    {
    pos = pos->Next;
    }
  pos->Next = newpos;
}

//----------------------------------------------------------------------------
vtkDebugLeaksHashNode* vtkDebugLeaksHashTable::GetNode(const char* key)
{
  unsigned long loc = (static_cast<unsigned long>(vtkHashString(key)) & 0x03f0) / 16;

  vtkDebugLeaksHashNode *pos = this->Nodes[loc];

  if (!pos)
    {
    return NULL;
    }
  while ((pos) && (strcmp(pos->Key, key) != 0) )
    {
    pos = pos->Next;
    }
  return pos;
}

//----------------------------------------------------------------------------
unsigned int vtkDebugLeaksHashTable::GetCount(const char* key)
{
  unsigned long loc = (static_cast<unsigned long>(vtkHashString(key)) & 0x03f0) / 16;

  vtkDebugLeaksHashNode *pos = this->Nodes[loc];

  if (!pos)
    {
    return 0;
    }
  while ((pos)&&(pos->Key != key))
    {
    pos = pos->Next;
    }
  if (pos)
    {
    return pos->Count;
    }
  return 0;
}

//----------------------------------------------------------------------------
int vtkDebugLeaksHashTable::IsEmpty()
{
  int count = 0;
  for(int i =0; i < 64; i++)
    {
    vtkDebugLeaksHashNode *pos = this->Nodes[i];
    if(pos)
      {
      if(!vtkDebugLeaksIgnoreClassesCheck(pos->Key))
        {
        count += pos->Count;
        }
      while(pos->Next)
        {
        pos = pos->Next;
        if(!vtkDebugLeaksIgnoreClassesCheck(pos->Key))
          {
          count += pos->Count;
          }
        }
      }
    }
  return !count;
}

//----------------------------------------------------------------------------
int vtkDebugLeaksHashTable::DecrementCount(const char *key)
{
  vtkDebugLeaksHashNode *pos = this->GetNode(key);
  if(pos)
    {
    pos->Count--;
    return 1;
    }
  else
    {
    return 0;
    }
}

//----------------------------------------------------------------------------
void vtkDebugLeaksHashTable::PrintTable(std::string &os)
{
  for(int i =0; i < 64; i++)
    {
    vtkDebugLeaksHashNode *pos = this->Nodes[i];
    if(pos)
      {
      if(!vtkDebugLeaksIgnoreClassesCheck(pos->Key))
        {
        pos->Print(os);
        }
      while(pos->Next)
        {
        pos = pos->Next;
        if(!vtkDebugLeaksIgnoreClassesCheck(pos->Key))
          {
          pos->Print(os);
          }
        }
      }
    }
}

//----------------------------------------------------------------------------
#ifdef VTK_DEBUG_LEAKS
void vtkDebugLeaks::ConstructClass(const char* name)
{
  vtkDebugLeaks::CriticalSection->Lock();
  vtkDebugLeaks::MemoryTable->IncrementCount(name);
  vtkDebugLeaks::CriticalSection->Unlock();
}
#else
void vtkDebugLeaks::ConstructClass(const char*)
{
}
#endif

//----------------------------------------------------------------------------
#ifdef VTK_DEBUG_LEAKS
void vtkDebugLeaks::DestructClass(const char* p)
{
  vtkDebugLeaks::CriticalSection->Lock();
  // Due to globals being deleted, this table may already have
  // been deleted.
  if(vtkDebugLeaks::MemoryTable &&
     !vtkDebugLeaks::MemoryTable->DecrementCount(p))
    {
    vtkDebugLeaks::CriticalSection->Unlock();
    vtkGenericWarningMacro("Deleting unknown object: " << p);
    }
  else
    {
    vtkDebugLeaks::CriticalSection->Unlock();
    }
}
#else
void vtkDebugLeaks::DestructClass(const char*)
{
}
#endif

//----------------------------------------------------------------------------
void vtkDebugLeaks::SetDebugLeaksObserver(vtkDebugLeaksObserver* observer)
{
  vtkDebugLeaks::Observer = observer;
}

//----------------------------------------------------------------------------
vtkDebugLeaksObserver* vtkDebugLeaks::GetDebugLeaksObserver()
{
  return vtkDebugLeaks::Observer;
}

//----------------------------------------------------------------------------
void vtkDebugLeaks::ConstructingObject(vtkObjectBase* object)
{
  if (vtkDebugLeaks::Observer)
    {
    vtkDebugLeaks::Observer->ConstructingObject(object);
    }
}

//----------------------------------------------------------------------------
void vtkDebugLeaks::DestructingObject(vtkObjectBase* object)
{
  if (vtkDebugLeaks::Observer)
    {
    vtkDebugLeaks::Observer->DestructingObject(object);
    }
}

//----------------------------------------------------------------------------
int vtkDebugLeaks::PrintCurrentLeaks()
{
#ifdef VTK_DEBUG_LEAKS
  if(vtkDebugLeaks::MemoryTable->IsEmpty())
    {
    // Log something anyway, so users know vtkDebugLeaks is active/working.
    cout << "vtkDebugLeaks has found no leaks.\n";
    return 0;
    }

  // we must not use stringstream ior strstream due to problems with
  // finalizers in MSVC
  std::string leaks;
  vtkDebugLeaks::MemoryTable->PrintTable(leaks);
#ifdef _WIN32
  fprintf(stderr,"%s",leaks.c_str());
  fflush(stderr);
  int cancel=0;
  if(getenv("DASHBOARD_TEST_FROM_CTEST") ||
     getenv("DART_TEST_FROM_DART"))
    {
    // Skip dialogs when running on dashboard.
    return 1;
    }
  std::string::size_type myPos = 0;
  int count = 0;
  std::string msg;
  msg = "vtkDebugLeaks has detected LEAKS!\n";
  while(!cancel && myPos != leaks.npos)
    {
    std::string::size_type newPos = leaks.find('\n',myPos);
    if (newPos != leaks.npos)
      {
      msg += leaks.substr(myPos,newPos-myPos);
      msg += "\n";
      myPos = newPos;
      myPos++;
      }
    else
      {
      myPos = newPos;
      }
    count++;
    if (count == 10)
      {
      count = 0;
      cancel = vtkDebugLeaks::DisplayMessageBox(msg.c_str());
      msg = "";
      }
    }
  if (!cancel && count > 0)
    {
    vtkDebugLeaks::DisplayMessageBox(msg.c_str());
    }
#else
  cout << "vtkDebugLeaks has detected LEAKS!\n";
  cout << leaks.c_str() << endl;
#endif
#endif
  return 1;
}

//----------------------------------------------------------------------------
#ifdef _WIN32
int vtkDebugLeaks::DisplayMessageBox(const char* msg)
{
#ifdef UNICODE
  wchar_t *wmsg = new wchar_t [mbstowcs(NULL, msg, 32000)+1];
  mbstowcs(wmsg, msg, 32000);
  int result = (MessageBox(NULL, wmsg, L"Error",
                           MB_ICONERROR | MB_OKCANCEL) == IDCANCEL);
  delete [] wmsg;
#else
  int result = (MessageBox(NULL, msg, "Error",
                           MB_ICONERROR | MB_OKCANCEL) == IDCANCEL);
#endif
  return result;
}
#else
int vtkDebugLeaks::DisplayMessageBox(const char*)
{
  return 0;
}
#endif

//----------------------------------------------------------------------------
int vtkDebugLeaks::GetExitError()
{
  return vtkDebugLeaks::ExitError;
}

//----------------------------------------------------------------------------
void vtkDebugLeaks::SetExitError(int flag)
{
  vtkDebugLeaks::ExitError = flag;
}

//----------------------------------------------------------------------------
void vtkDebugLeaks::ClassInitialize()
{
#ifdef VTK_DEBUG_LEAKS
  // Create the hash table.
  vtkDebugLeaks::MemoryTable = new vtkDebugLeaksHashTable;

  // Create the lock for the critical sections.
  vtkDebugLeaks::CriticalSection = new vtkSimpleCriticalSection;

  // Default to error when leaks occur while running tests.
  vtkDebugLeaks::ExitError = 1;
  vtkDebugLeaks::Observer = 0;
#else
  vtkDebugLeaks::MemoryTable = 0;
  vtkDebugLeaks::CriticalSection = 0;
  vtkDebugLeaks::ExitError = 0;
  vtkDebugLeaks::Observer = 0;
#endif
}

//----------------------------------------------------------------------------
void vtkDebugLeaks::ClassFinalize()
{
#ifdef VTK_DEBUG_LEAKS
  // Report leaks.
  int leaked = vtkDebugLeaks::PrintCurrentLeaks();

  // Destroy the hash table.
  delete vtkDebugLeaks::MemoryTable;
  vtkDebugLeaks::MemoryTable = 0;

  // Destroy the lock for the critical sections.
  delete vtkDebugLeaks::CriticalSection;
  vtkDebugLeaks::CriticalSection = 0;

  // Exit with error if leaks occurred and error mode is on.
  if(leaked && vtkDebugLeaks::ExitError)
    {
    exit(1);
    }
#endif
}

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

// Purposely not initialized.  ClassInitialize will handle it.
vtkDebugLeaksHashTable* vtkDebugLeaks::MemoryTable;

// Purposely not initialized.  ClassInitialize will handle it.
vtkSimpleCriticalSection* vtkDebugLeaks::CriticalSection;

// Purposely not initialized.  ClassInitialize will handle it.
int vtkDebugLeaks::ExitError;

// Purposely not initialized.  ClassInitialize will handle it.
vtkDebugLeaksObserver* vtkDebugLeaks::Observer;
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: tdcomp.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: kz $ $Date: 2004-03-25 14:47:54 $
 *
 *  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 _STOC_RDBTDP_BASE_HXX
#include "base.hxx"
#endif

namespace stoc_rdbtdp
{

//__________________________________________________________________________________________________
CompoundTypeDescriptionImpl::~CompoundTypeDescriptionImpl()
{
    delete _pMembers;
    delete _pMemberNames;
    g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
}

// XTypeDescription
//__________________________________________________________________________________________________
TypeClass CompoundTypeDescriptionImpl::getTypeClass()
    throw(::com::sun::star::uno::RuntimeException)
{
    return _eTypeClass;
}
//__________________________________________________________________________________________________
OUString CompoundTypeDescriptionImpl::getName()
    throw(::com::sun::star::uno::RuntimeException)
{
    return _aName;
}

// XCompoundTypeDescription
//__________________________________________________________________________________________________
Reference< XTypeDescription > CompoundTypeDescriptionImpl::getBaseType()
    throw(::com::sun::star::uno::RuntimeException)
{
    if (!_xBaseTD.is() && _aBaseType.getLength())
    {
        try
        {
            Reference< XTypeDescription > xBaseTD;
            if (_xTDMgr->getByHierarchicalName( _aBaseType ) >>= xBaseTD)
            {
                MutexGuard aGuard( getMutex() );
                if (! _xBaseTD.is())
                    _xBaseTD = xBaseTD;
                return _xBaseTD;
            }
        }
        catch (NoSuchElementException &)
        {
        }
        // never try again, if no base td was found
        _aBaseType = OUString();
    }
    return _xBaseTD;
}
//__________________________________________________________________________________________________
Sequence< Reference< XTypeDescription > > CompoundTypeDescriptionImpl::getMemberTypes()
    throw(::com::sun::star::uno::RuntimeException)
{
    if (! _pMembers)
    {
        RegistryTypeReaderLoader aLoader;
        RegistryTypeReader aReader(
            aLoader, (const sal_uInt8 *)_aBytes.getConstArray(),
            _aBytes.getLength(), sal_False );

        sal_uInt16 nFields = (sal_uInt16)aReader.getFieldCount();
        Sequence< Reference< XTypeDescription > > * pTempMembers =
            new Sequence< Reference< XTypeDescription > >( nFields );
        Reference< XTypeDescription > * pMembers = pTempMembers->getArray();

        while (nFields--)
        {
            try
            {
                _xTDMgr->getByHierarchicalName(
                    aReader.getFieldType( nFields ).replace( '/', '.' ) ) >>= pMembers[nFields];
            }
            catch (NoSuchElementException &)
            {
            }
            OSL_ENSURE( pMembers[nFields].is(), "### compound member unknown!" );
        }

        ClearableMutexGuard aGuard( getMutex() );
        if (_pMembers)
        {
            aGuard.clear();
            delete pTempMembers;
        }
        else
        {
            _pMembers = pTempMembers;
        }
    }

    return *_pMembers;
}
//__________________________________________________________________________________________________
Sequence< OUString > CompoundTypeDescriptionImpl::getMemberNames()
    throw(::com::sun::star::uno::RuntimeException)
{
    if (! _pMemberNames)
    {
        RegistryTypeReaderLoader aLoader;
        RegistryTypeReader aReader(
            aLoader, (const sal_uInt8 *)_aBytes.getConstArray(),
            _aBytes.getLength(), sal_False );

        sal_uInt16 nFields = (sal_uInt16)aReader.getFieldCount();
        Sequence< OUString > * pTempMemberNames = new Sequence< OUString >( nFields );
        OUString * pMemberNames = pTempMemberNames->getArray();

        while (nFields--)
        {
            pMemberNames[nFields] = aReader.getFieldName( nFields );
        }

        ClearableMutexGuard aGuard( getMutex() );
        if (_pMemberNames)
        {
            aGuard.clear();
            delete pTempMemberNames;
        }
        else
        {
            _pMemberNames = pTempMemberNames;
        }
    }
    return *_pMemberNames;
}

}

<commit_msg>INTEGRATION: CWS sb14 (1.6.104); FILE MERGED 2004/03/12 14:18:49 sb 1.6.104.1: #i21150# Adapted to modified registry type reader.<commit_after>/*************************************************************************
 *
 *  $RCSfile: tdcomp.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2004-03-30 16:15:57 $
 *
 *  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 _STOC_RDBTDP_BASE_HXX
#include "base.hxx"
#endif

#include "registry/reader.hxx"
#include "registry/version.h"

namespace stoc_rdbtdp
{

//__________________________________________________________________________________________________
CompoundTypeDescriptionImpl::~CompoundTypeDescriptionImpl()
{
    delete _pMembers;
    delete _pMemberNames;
    g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
}

// XTypeDescription
//__________________________________________________________________________________________________
TypeClass CompoundTypeDescriptionImpl::getTypeClass()
    throw(::com::sun::star::uno::RuntimeException)
{
    return _eTypeClass;
}
//__________________________________________________________________________________________________
OUString CompoundTypeDescriptionImpl::getName()
    throw(::com::sun::star::uno::RuntimeException)
{
    return _aName;
}

// XCompoundTypeDescription
//__________________________________________________________________________________________________
Reference< XTypeDescription > CompoundTypeDescriptionImpl::getBaseType()
    throw(::com::sun::star::uno::RuntimeException)
{
    if (!_xBaseTD.is() && _aBaseType.getLength())
    {
        try
        {
            Reference< XTypeDescription > xBaseTD;
            if (_xTDMgr->getByHierarchicalName( _aBaseType ) >>= xBaseTD)
            {
                MutexGuard aGuard( getMutex() );
                if (! _xBaseTD.is())
                    _xBaseTD = xBaseTD;
                return _xBaseTD;
            }
        }
        catch (NoSuchElementException &)
        {
        }
        // never try again, if no base td was found
        _aBaseType = OUString();
    }
    return _xBaseTD;
}
//__________________________________________________________________________________________________
Sequence< Reference< XTypeDescription > > CompoundTypeDescriptionImpl::getMemberTypes()
    throw(::com::sun::star::uno::RuntimeException)
{
    if (! _pMembers)
    {
        typereg::Reader aReader(
            _aBytes.getConstArray(), _aBytes.getLength(), false,
            TYPEREG_VERSION_1);

        sal_uInt16 nFields = aReader.getFieldCount();
        Sequence< Reference< XTypeDescription > > * pTempMembers =
            new Sequence< Reference< XTypeDescription > >( nFields );
        Reference< XTypeDescription > * pMembers = pTempMembers->getArray();

        while (nFields--)
        {
            try
            {
                _xTDMgr->getByHierarchicalName(
                    aReader.getFieldTypeName( nFields ).replace( '/', '.' ) )
                        >>= pMembers[nFields];
            }
            catch (NoSuchElementException &)
            {
            }
            OSL_ENSURE( pMembers[nFields].is(), "### compound member unknown!" );
        }

        ClearableMutexGuard aGuard( getMutex() );
        if (_pMembers)
        {
            aGuard.clear();
            delete pTempMembers;
        }
        else
        {
            _pMembers = pTempMembers;
        }
    }

    return *_pMembers;
}
//__________________________________________________________________________________________________
Sequence< OUString > CompoundTypeDescriptionImpl::getMemberNames()
    throw(::com::sun::star::uno::RuntimeException)
{
    if (! _pMemberNames)
    {
        typereg::Reader aReader(
            _aBytes.getConstArray(), _aBytes.getLength(), false,
            TYPEREG_VERSION_1);

        sal_uInt16 nFields = aReader.getFieldCount();
        Sequence< OUString > * pTempMemberNames = new Sequence< OUString >( nFields );
        OUString * pMemberNames = pTempMemberNames->getArray();

        while (nFields--)
        {
            pMemberNames[nFields] = aReader.getFieldName( nFields );
        }

        ClearableMutexGuard aGuard( getMutex() );
        if (_pMemberNames)
        {
            aGuard.clear();
            delete pTempMemberNames;
        }
        else
        {
            _pMemberNames = pTempMemberNames;
        }
    }
    return *_pMemberNames;
}

}

<|endoftext|>


<commit_before>#ifndef SOLARIZED_HPP
#define SOLARIZED_HPP
#include <wx/colour.h>

#include "ColorScheme/ColorSchemeBase.hpp"

namespace Slic3r { namespace GUI {

/// S O L A R I Z E
/// http://ethanschoonover.com/solarized
///
/// Implements a colorscheme lookup of wxColors
class Solarized : public ColorScheme {
public:
    const wxColour SELECTED_COLOR() const { return COLOR_MAGENTA(); }
    const wxColour HOVER_COLOR() const { return COLOR_VIOLET(); }
    const wxColour SUPPORT_COLOR() const { return COLOR_VIOLET(); }

    const wxColour BACKGROUND_COLOR() const { return COLOR_BASE3(); }

private:
    const wxColour COLOR_BASE0()    const {return wxColour(255*0.51373,255*0.58039,255*0.58824);}
    const wxColour COLOR_BASE00()   const {return wxColour(255*0.39608,255*0.48235,255*0.51373);}
    const wxColour COLOR_BASE01()   const {return wxColour(255*0.34510,255*0.43137,255*0.45882);}
    const wxColour COLOR_BASE02()   const {return wxColour(255*0.02745,255*0.21176,255*0.25882);}
    const wxColour COLOR_BASE03()   const {return wxColour(255*0.00000,255*0.16863,255*0.21176);}
    const wxColour COLOR_BASE1()    const {return wxColour(255*0.57647,255*0.63137,255*0.63137);}
    const wxColour COLOR_BASE2()    const {return wxColour(255*0.93333,255*0.90980,255*0.83529);}
    const wxColour COLOR_BASE3()    const {return wxColour(255*0.99216,255*0.96471,255*0.89020);}
    const wxColour COLOR_BLUE()     const {return wxColour(255*0.14902,255*0.54510,255*0.82353);}
    const wxColour COLOR_CYAN()     const {return wxColour(255*0.16471,255*0.63137,255*0.59608);}
    const wxColour COLOR_GREEN()    const {return wxColour(255*0.52157,255*0.60000,255*0.00000);}
    const wxColour COLOR_MAGENTA()  const {return wxColour(255*0.82745,255*0.21176,255*0.50980);}
    const wxColour COLOR_ORANGE()   const {return wxColour(255*0.79608,255*0.29412,255*0.08627);}
    const wxColour COLOR_RED()      const {return wxColour(255*0.86275,255*0.19608,255*0.18431);}
    const wxColour COLOR_VIOLET()   const {return wxColour(255*0.42353,255*0.44314,255*0.76863);}
    const wxColour COLOR_YELLOW()   const {return wxColour(255*0.70980,255*0.53725,255*0.00000);}

};
}} // namespace Slic3r::GUI

#endif // SOLARIZED_HPP
<commit_msg>Still playing with solarized, better setup (private constants with public functions)<commit_after>#ifndef SOLARIZED_HPP
#define SOLARIZED_HPP
#include <wx/colour.h>

#include "ColorScheme/ColorSchemeBase.hpp"

namespace Slic3r { namespace GUI {

/// S O L A R I Z E
/// http://ethanschoonover.com/solarized
///
/// Implements a colorscheme lookup of wxColors
class Solarized : public ColorScheme {
public:
    const wxColour SELECTED_COLOR() const { return COLOR_SOLAR_MAGENTA; }
    const wxColour HOVER_COLOR() const { return COLOR_SOLAR_VIOLET; }
    const wxColour SUPPORT_COLOR() const { return COLOR_SOLAR_VIOLET; }

    const wxColour BACKGROUND_COLOR() const { return COLOR_SOLAR_BASE3; }

private:
    const wxColour COLOR_SOLAR_BASE0   { wxColour(255*0.51373,255*0.58039,255*0.58824)};
    const wxColour COLOR_SOLAR_BASE00  { wxColour(255*0.39608,255*0.48235,255*0.51373)};
    const wxColour COLOR_SOLAR_BASE01  { wxColour(255*0.34510,255*0.43137,255*0.45882)};
    const wxColour COLOR_SOLAR_BASE02  { wxColour(255*0.02745,255*0.21176,255*0.25882)};
    const wxColour COLOR_SOLAR_BASE03  { wxColour(255*0.00000,255*0.16863,255*0.21176)};
    const wxColour COLOR_SOLAR_BASE1   { wxColour(255*0.57647,255*0.63137,255*0.63137)};
    const wxColour COLOR_SOLAR_BASE2   { wxColour(255*0.93333,255*0.90980,255*0.83529)};
    const wxColour COLOR_SOLAR_BASE3   { wxColour(255*0.99216,255*0.96471,255*0.89020)};
    const wxColour COLOR_SOLAR_BLUE    { wxColour(255*0.14902,255*0.54510,255*0.82353)};
    const wxColour COLOR_SOLAR_CYAN    { wxColour(255*0.16471,255*0.63137,255*0.59608)};
    const wxColour COLOR_SOLAR_GREEN   { wxColour(255*0.52157,255*0.60000,255*0.00000)};
    const wxColour COLOR_SOLAR_MAGENTA { wxColour(255*0.82745,255*0.21176,255*0.50980)};
    const wxColour COLOR_SOLAR_ORANGE  { wxColour(255*0.79608,255*0.29412,255*0.08627)};
    const wxColour COLOR_SOLAR_RED     { wxColour(255*0.86275,255*0.19608,255*0.18431)};
    const wxColour COLOR_SOLAR_VIOLET  { wxColour(255*0.42353,255*0.44314,255*0.76863)};
    const wxColour COLOR_SOLAR_YELLOW  { wxColour(255*0.70980,255*0.53725,255*0.00000)};

};
}} // namespace Slic3r::GUI

#endif // SOLARIZED_HPP
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 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 <iostream>
#include <stdexcept>
#include <QtGui>
#include <Core/Logging/Log.h>
#include <Interface/Application/Note.h>
#include <Interface/Application/NoteEditor.h>
#include <Interface/Application/SCIRunMainWindow.h>

using namespace SCIRun::Gui;
using namespace SCIRun::Core::Logging;

HasNotes::HasNotes(const std::string& name, bool positionAdjustable) : destroyed_(false)
{
  noteEditor_ = new NoteEditor(QString::fromStdString(name), positionAdjustable, SCIRunMainWindow::Instance());
}

HasNotes::~HasNotes()
{
  destroy();
}

void HasNotes::destroy()
{
  if (!destroyed_)
  {
    delete noteEditor_;
    destroyed_ = true;
  }
}

void HasNotes::connectNoteEditorToAction(QAction* action)
{
  QObject::connect(action, SIGNAL(triggered()), noteEditor_, SLOT(show()));
  QObject::connect(action, SIGNAL(triggered()), noteEditor_, SLOT(raise()));
}

void HasNotes::connectUpdateNote(QObject* obj)
{
  QObject::connect(noteEditor_, SIGNAL(noteChanged(const Note&)), obj, SLOT(updateNote(const Note&)));
}

NoteDisplayHelper::NoteDisplayHelper(NoteDisplayStrategyPtr display) : note_(0), notePosition_(Default),
  defaultNotePosition_(Top), //TODO
  item_(0),
  displayStrategy_(display),
  scene_(0),
  destroyed_(false)
{
}

NoteDisplayHelper::~NoteDisplayHelper()
{
  destroy();
}

void NoteDisplayHelper::destroy()
{
  if (!destroyed_)
  {
    if (note_ && scene_)
    {
      scene_->removeItem(note_);
    }
    delete note_;
    destroyed_ = true;
  }
}

void NoteDisplayHelper::updateNoteImpl(const Note& note)
{
  if (!note_)
  {
    setNoteGraphicsContext();
    if (!scene_)
      Log::get() << WARN << "Scene not set, network notes will not be displayed!" << std::endl;
    note_ = new QGraphicsTextItem("", 0, scene_);
  }

  note_->setHtml(note.html_);
  notePosition_ = note.position_;
  updateNotePosition();
  note_->setZValue(item_->zValue() - 1);
}

QPointF NoteDisplayHelper::relativeNotePosition()
{
  if (note_ && item_)
  {
    auto position = notePosition_ == Default ? defaultNotePosition_ : notePosition_;
    note_->setVisible(!(Tooltip == position || None == position));
    item_->setToolTip("");

    return displayStrategy_->relativeNotePosition(item_, note_, position);
  }
  return QPointF();
}

void NoteDisplayHelper::setDefaultNotePositionImpl(NotePosition position)
{
  defaultNotePosition_ = position;
  updateNotePosition();
}

void NoteDisplayHelper::updateNotePosition()
{
  if (note_ && item_)
  {
    auto position = positioner_->currentPosition() + relativeNotePosition();
    //std::cout << "updating position to: " << position.x() << " , " << position.y() << std::endl;
    note_->setPos(position);
  }
}<commit_msg>More warnings<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 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 <iostream>
#include <stdexcept>
#include <QtGui>
#include <Core/Logging/Log.h>
#include <Interface/Application/Note.h>
#include <Interface/Application/NoteEditor.h>
#include <Interface/Application/SCIRunMainWindow.h>

using namespace SCIRun::Gui;
using namespace SCIRun::Core::Logging;

HasNotes::HasNotes(const std::string& name, bool positionAdjustable) : destroyed_(false)
{
  noteEditor_ = new NoteEditor(QString::fromStdString(name), positionAdjustable, SCIRunMainWindow::Instance());
}

HasNotes::~HasNotes()
{
  destroy();
}

void HasNotes::destroy()
{
  if (!destroyed_)
  {
    delete noteEditor_;
    destroyed_ = true;
  }
}

void HasNotes::connectNoteEditorToAction(QAction* action)
{
  QObject::connect(action, SIGNAL(triggered()), noteEditor_, SLOT(show()));
  QObject::connect(action, SIGNAL(triggered()), noteEditor_, SLOT(raise()));
}

void HasNotes::connectUpdateNote(QObject* obj)
{
  QObject::connect(noteEditor_, SIGNAL(noteChanged(const Note&)), obj, SLOT(updateNote(const Note&)));
}

NoteDisplayHelper::NoteDisplayHelper(NoteDisplayStrategyPtr display) :
  item_(0), scene_(0), note_(0),
  notePosition_(Default),
  defaultNotePosition_(Top), //TODO
  displayStrategy_(display),
  destroyed_(false)
{
}

NoteDisplayHelper::~NoteDisplayHelper()
{
  destroy();
}

void NoteDisplayHelper::destroy()
{
  if (!destroyed_)
  {
    if (note_ && scene_)
    {
      scene_->removeItem(note_);
    }
    delete note_;
    destroyed_ = true;
  }
}

void NoteDisplayHelper::updateNoteImpl(const Note& note)
{
  if (!note_)
  {
    setNoteGraphicsContext();
    if (!scene_)
      Log::get() << WARN << "Scene not set, network notes will not be displayed!" << std::endl;
    note_ = new QGraphicsTextItem("", 0, scene_);
  }

  note_->setHtml(note.html_);
  notePosition_ = note.position_;
  updateNotePosition();
  note_->setZValue(item_->zValue() - 1);
}

QPointF NoteDisplayHelper::relativeNotePosition()
{
  if (note_ && item_)
  {
    auto position = notePosition_ == Default ? defaultNotePosition_ : notePosition_;
    note_->setVisible(!(Tooltip == position || None == position));
    item_->setToolTip("");

    return displayStrategy_->relativeNotePosition(item_, note_, position);
  }
  return QPointF();
}

void NoteDisplayHelper::setDefaultNotePositionImpl(NotePosition position)
{
  defaultNotePosition_ = position;
  updateNotePosition();
}

void NoteDisplayHelper::updateNotePosition()
{
  if (note_ && item_)
  {
    auto position = positioner_->currentPosition() + relativeNotePosition();
    //std::cout << "updating position to: " << position.x() << " , " << position.y() << std::endl;
    note_->setPos(position);
  }
}<|endoftext|>


<commit_before>#include <config.h>
#include <assert.h>
#include <dune/common/exceptions.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/common/parameter/validation.hh>
#include <sstream>

#include "dune/multiscale/problems/base.hh"
#include "dune/multiscale/problems/constants.hh"
#include "spe10.hh"

namespace Dune {
namespace Multiscale {
namespace Problem {
namespace SPE10 {

// default value for epsilon (if not specified in the parameter file)
CONSTANTSFUNCTION(0.05)

ModelProblemData::ModelProblemData() : IModelProblemData(constants()) {
  if (constants().get("stochastic_pertubation", false) && !(this->problemAllowsStochastics()))
    DUNE_THROW(Dune::InvalidStateException,
               "The problem does not allow stochastic perturbations. Please, switch the key off.");
}

std::string ModelProblemData::getMacroGridFile() const {
  return ("../dune/multiscale/grids/macro_grids/elliptic/spe10.dgf");
}

bool ModelProblemData::problemIsPeriodic() const { return false; }

bool ModelProblemData::problemAllowsStochastics() const { return false; }

std::pair<CommonTraits::DomainType, CommonTraits::DomainType>
ModelProblemData::gridCorners() const {
  CommonTraits::DomainType lowerLeft(0.0);
  CommonTraits::DomainType upperRight(0.0);
  switch (View::dimension /*View is defined in IModelProblemData*/) {
    case 1:
      DUNE_THROW(NotImplemented, "SPE10 is not defined in 1D!");
      break;
    case 2:
    upperRight[0] = 365.76;
    upperRight[1] = 670.56;
  break;
  case 3:
    upperRight[0] = 365.76;
    upperRight[1] = 670.56;
    upperRight[2] = 51.816;
  }
  return {lowerLeft, upperRight};
}

std::unique_ptr<ModelProblemData::BoundaryInfoType> ModelProblemData::boundaryInfo() const {
  return std::unique_ptr<ModelProblemData::BoundaryInfoType>(
      Stuff::GridboundaryNormalBased<typename View::Intersection>::create(boundary_settings()));
}

std::unique_ptr<ModelProblemData::SubBoundaryInfoType> ModelProblemData::subBoundaryInfo() const {
  return std::unique_ptr<ModelProblemData::SubBoundaryInfoType>(
      Stuff::GridboundaryNormalBased<typename SubView::Intersection>::create(boundary_settings()));
}

ParameterTree ModelProblemData::boundary_settings() const {
  Dune::ParameterTree boundarySettings;
  if (DSC_CONFIG.hasSub("problem.boundaryInfo")) {
    boundarySettings = DSC_CONFIG.sub("problem.boundaryInfo");
  } else {
    boundarySettings["default"] = "neumann";
    boundarySettings["compare_tolerance"] = "1e-10";
    switch (View::dimension /*View is defined in IModelProblemData*/) {
      case 1:
        DUNE_THROW(NotImplemented, "Boundary values are not implemented for SPE10 in 1D!");
        break;
      case 2:
        boundarySettings["dirichlet.0"] = "[-1.0; 0.0]";
        boundarySettings["dirichlet.1"] = "[1.0; 0.0]";
        break;
      case 3:
        boundarySettings["dirichlet.0"] = "[-1.0; 0.0; 0.0]";
        boundarySettings["dirichlet.1"] = "[1.0; 0.0; 0.0]";
    }
  }
  return boundarySettings;
}

void DirichletData::evaluate(const DomainType& x, RangeType& y) const {
  // use pressure gradient in x-direction in 1D and 2D and in y-direction in 3D
  //  if (x[std::max(dimDomain-2,0)]<1e-6)
  //    y = 1.0;
  //  else
  //    y = 0.0;
  y = x[0];
} // evaluate

void DirichletData::evaluate(const DomainType& x, const TimeType& /*time*/, RangeType& y) const { evaluate(x, y); }

void NeumannData::evaluate(const DomainType& /*x*/, RangeType& y) const { y = 0.0; } // evaluate

void NeumannData::evaluate(const DomainType& x, const TimeType& /*time*/, RangeType& y) const { evaluate(x, y); }

FirstSource::FirstSource() {}

void __attribute__((hot)) FirstSource::evaluate(const DomainType& /*x*/, RangeType& y) const {
  y = typename FunctionSpaceType::RangeType(1.0);
} // evaluate

void FirstSource::evaluate(const DomainType& x, const TimeType& /*time*/, RangeType& y) const { evaluate(x, y); }

Diffusion::Diffusion()
  : deltas_{6.096, 3.048, 0.6096}
  , permeability_(nullptr) {
  readPermeability();
}

Diffusion::~Diffusion() {
  delete permeability_;
  permeability_ = nullptr;
}

void Diffusion::diffusiveFlux(const DomainType& x, const JacobianRangeType& direction, JacobianRangeType& flux) const {
  assert(x.size() <= 3 && "SPE 10 model is only defined for up to three dimensions!");
  Dune::FieldMatrix<double, DomainType::dimension, DomainType::dimension> permeability(0.0);

  // TODO this class does not seem to work in 2D, when changing 'spe10.dgf' to a 2D grid?

  // 3 is the maximum space dimension
  std::vector<double> intervalls(3, 0.0);
  for (int dim = 0; dim < DomainType::dimension; ++dim)
    intervalls[dim] = std::floor(x[dim] / deltas_[dim]);

  int offset = 0;
  switch (DomainType::dimension) {
    case 1:
      offset = intervalls[0];
      permeability[0][0] = permeability_[offset];
      break;
    case 2:
      offset = intervalls[0] + intervalls[1] * 60;
      permeability[0][0] = permeability_[offset];
      permeability[1][1] = permeability_[offset + 1122000];
      break;
    case 3:
      offset = intervalls[0] + intervalls[1] * 60 + intervalls[2] * 220 * 60;
      permeability[0][0] = permeability_[offset];
      permeability[1][1] = permeability_[offset + 1122000];
      permeability[2][2] = permeability_[offset + 2244000];
      break;
  }

  permeability.mv(direction[0], flux[0]);
} // diffusiveFlux

void Diffusion::jacobianDiffusiveFlux(const DomainType& /*x*/, const JacobianRangeType& /*position_gradient*/,
                                      const JacobianRangeType& /*direction_gradient*/,
                                      JacobianRangeType& /*flux*/) const {
  DUNE_THROW(NotImplemented, "Jacobian of Flux is not implemented at the moment!");
} // jacobianDiffusiveFlux

void Diffusion::readPermeability() {
  permeability_ = new double[3366000];
  std::string filename = "../dune/multiscale/problems/elliptic/spe10_permeability.dat";
  std::ifstream file(filename.c_str());
  double val;
  if (!file) { // file couldn't be opened
    DSC_LOG_INFO_0 << "The SPE10-permeability data file could not be opened. This file does\n"
                   << "not come with the dune-multiscale repository due to file size. To download it\n"
                   << "execute\n"
                   << "wget http://www.spe.org/web/csp/datasets/por_perm_case2a.zip\n"
                   << "unzip the file and move the file 'spe_perm.dat' to\n"
                   << "dune-multiscale/dune/multiscale/problems/elliptic/spe10_permeability.dat!\n";
    DUNE_THROW(IOError, "Data file for Groundwaterflow permeability could not be opened!");
  }
  file >> val;
  int counter = 0;
  while (!file.eof()) {
    // keep reading until end-of-file
    permeability_[counter++] = val;
    file >> val; // sets EOF flag if no value found
  }
  file.close();
  return;
} /* readPermeability */

} // namespace SPE10
} // namespace Problem
} // namespace Multiscale {
} // namespace Dune {
<commit_msg>Changed boundary values for SPE10 problem<commit_after>#include <config.h>
#include <assert.h>
#include <dune/common/exceptions.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/common/parameter/validation.hh>
#include <sstream>

#include "dune/multiscale/problems/base.hh"
#include "dune/multiscale/problems/constants.hh"
#include "spe10.hh"

namespace Dune {
namespace Multiscale {
namespace Problem {
namespace SPE10 {

// default value for epsilon (if not specified in the parameter file)
CONSTANTSFUNCTION(0.05)

ModelProblemData::ModelProblemData() : IModelProblemData(constants()) {
  if (constants().get("stochastic_pertubation", false) && !(this->problemAllowsStochastics()))
    DUNE_THROW(Dune::InvalidStateException,
               "The problem does not allow stochastic perturbations. Please, switch the key off.");
}

std::string ModelProblemData::getMacroGridFile() const {
  return ("../dune/multiscale/grids/macro_grids/elliptic/spe10.dgf");
}

bool ModelProblemData::problemIsPeriodic() const { return false; }

bool ModelProblemData::problemAllowsStochastics() const { return false; }

std::pair<CommonTraits::DomainType, CommonTraits::DomainType>
ModelProblemData::gridCorners() const {
  CommonTraits::DomainType lowerLeft(0.0);
  CommonTraits::DomainType upperRight(0.0);
  switch (View::dimension /*View is defined in IModelProblemData*/) {
    case 1:
      DUNE_THROW(NotImplemented, "SPE10 is not defined in 1D!");
      break;
    case 2:
    upperRight[0] = 365.76;
    upperRight[1] = 670.56;
  break;
  case 3:
    upperRight[0] = 365.76;
    upperRight[1] = 670.56;
    upperRight[2] = 51.816;
  }
  return {lowerLeft, upperRight};
}

std::unique_ptr<ModelProblemData::BoundaryInfoType> ModelProblemData::boundaryInfo() const {
  return std::unique_ptr<ModelProblemData::BoundaryInfoType>(
      Stuff::GridboundaryNormalBased<typename View::Intersection>::create(boundary_settings()));
}

std::unique_ptr<ModelProblemData::SubBoundaryInfoType> ModelProblemData::subBoundaryInfo() const {
  return DSC::make_unique<Stuff::GridboundaryAllDirichlet<typename SubView::Intersection>>();
}

ParameterTree ModelProblemData::boundary_settings() const {
  Dune::ParameterTree boundarySettings;
  if (DSC_CONFIG.hasSub("problem.boundaryInfo")) {
    boundarySettings = DSC_CONFIG.sub("problem.boundaryInfo");
  } else {
    boundarySettings["default"] = "neumann";
    boundarySettings["compare_tolerance"] = "1e-10";
    switch (View::dimension /*View is defined in IModelProblemData*/) {
      case 1:
        DUNE_THROW(NotImplemented, "Boundary values are not implemented for SPE10 in 1D!");
        break;
      case 2:
        boundarySettings["dirichlet.0"] = "[0.0; 1.0]";
        boundarySettings["dirichlet.1"] = "[0.0; -1.0]";
        break;
      case 3:
        boundarySettings["dirichlet.0"] = "[0.0; 1.0; 0.0]";
        boundarySettings["dirichlet.1"] = "[0.0; -1.0; 0.0]";
    }
  }
  return boundarySettings;
}

void DirichletData::evaluate(const DomainType& x, RangeType& y) const {
  // use pressure gradient in x-direction in 1D and 2D and in y-direction in 3D
  //  if (x[std::max(dimDomain-2,0)]<1e-6)
  //    y = 1.0;
  //  else
  //    y = 0.0;
  y = x[1];
} // evaluate

void DirichletData::evaluate(const DomainType& x, const TimeType& /*time*/, RangeType& y) const { evaluate(x, y); }

void NeumannData::evaluate(const DomainType& /*x*/, RangeType& y) const { y = 0.0; } // evaluate

void NeumannData::evaluate(const DomainType& x, const TimeType& /*time*/, RangeType& y) const { evaluate(x, y); }

FirstSource::FirstSource() {}

void __attribute__((hot)) FirstSource::evaluate(const DomainType& /*x*/, RangeType& y) const {
  y = typename FunctionSpaceType::RangeType(1.0);
} // evaluate

void FirstSource::evaluate(const DomainType& x, const TimeType& /*time*/, RangeType& y) const { evaluate(x, y); }

Diffusion::Diffusion()
  : deltas_{6.096, 3.048, 0.6096}
  , permeability_(nullptr) {
  readPermeability();
}

Diffusion::~Diffusion() {
  delete permeability_;
  permeability_ = nullptr;
}

void Diffusion::diffusiveFlux(const DomainType& x, const JacobianRangeType& direction, JacobianRangeType& flux) const {
  assert(x.size() <= 3 && "SPE 10 model is only defined for up to three dimensions!");
  Dune::FieldMatrix<double, DomainType::dimension, DomainType::dimension> permeability(0.0);

  // TODO this class does not seem to work in 2D, when changing 'spe10.dgf' to a 2D grid?

  // 3 is the maximum space dimension
  std::vector<double> intervalls(3, 0.0);
  for (int dim = 0; dim < DomainType::dimension; ++dim)
    intervalls[dim] = std::floor(x[dim] / deltas_[dim]);

  int offset = 0;
  switch (DomainType::dimension) {
    case 1:
      offset = intervalls[0];
      permeability[0][0] = permeability_[offset];
      break;
    case 2:
      offset = intervalls[0] + intervalls[1] * 60;
      permeability[0][0] = permeability_[offset];
      permeability[1][1] = permeability_[offset + 1122000];
      break;
    case 3:
      offset = intervalls[0] + intervalls[1] * 60 + intervalls[2] * 220 * 60;
      permeability[0][0] = permeability_[offset];
      permeability[1][1] = permeability_[offset + 1122000];
      permeability[2][2] = permeability_[offset + 2244000];
      break;
  }

  permeability.mv(direction[0], flux[0]);
} // diffusiveFlux

void Diffusion::jacobianDiffusiveFlux(const DomainType& /*x*/, const JacobianRangeType& /*position_gradient*/,
                                      const JacobianRangeType& /*direction_gradient*/,
                                      JacobianRangeType& /*flux*/) const {
  DUNE_THROW(NotImplemented, "Jacobian of Flux is not implemented at the moment!");
} // jacobianDiffusiveFlux

void Diffusion::readPermeability() {
  permeability_ = new double[3366000];
  std::string filename = "../dune/multiscale/problems/elliptic/spe10_permeability.dat";
  std::ifstream file(filename.c_str());
  double val;
  if (!file) { // file couldn't be opened
    DSC_LOG_INFO_0 << "The SPE10-permeability data file could not be opened. This file does\n"
                   << "not come with the dune-multiscale repository due to file size. To download it\n"
                   << "execute\n"
                   << "wget http://www.spe.org/web/csp/datasets/por_perm_case2a.zip\n"
                   << "unzip the file and move the file 'spe_perm.dat' to\n"
                   << "dune-multiscale/dune/multiscale/problems/elliptic/spe10_permeability.dat!\n";
    DUNE_THROW(IOError, "Data file for Groundwaterflow permeability could not be opened!");
  }
  file >> val;
  int counter = 0;
  while (!file.eof()) {
    // keep reading until end-of-file
    permeability_[counter++] = val;
    file >> val; // sets EOF flag if no value found
  }
  file.close();
  return;
} /* readPermeability */

} // namespace SPE10
} // namespace Problem
} // namespace Multiscale {
} // namespace Dune {
<|endoftext|>


<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
 * CONDOR Copyright Notice
 *
 * See LICENSE.TXT for additional notices and disclaimers.
 *
 * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.
 * No use of the CONDOR Software Program Source Code is authorized
 * without the express consent of the CONDOR Team.  For more information
 * contact: CONDOR Team, Attention: Professor Miron Livny,
 * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
 * (608) 262-0856 or miron@cs.wisc.edu.
 *
 * U.S. Government Rights Restrictions: Use, duplication, or disclosure
 * by the U.S. Government is subject to restrictions as set forth in
 * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
 * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
 * (2) of Commercial Computer Software-Restricted Rights at 48 CFR
 * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
 * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
 * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
#include "ad_printmask.h"
#include "escapes.h"

static char *new_strdup (const char *);

ClassAdPrintMask::
ClassAdPrintMask ()
{
}

ClassAdPrintMask::
ClassAdPrintMask (const ClassAdPrintMask &pm)
{
	copyList (formats, (List<Formatter> &) pm.formats);
	copyList (attributes, (List<char> &) pm.attributes);
	copyList (alternates, (List<char> &) pm.alternates);
}

ClassAdPrintMask::
~ClassAdPrintMask ()
{
	clearFormats ();
}

void ClassAdPrintMask::
registerFormat (char *fmt, const char *attr, char *alternate)
{
	Formatter *newFmt = new Formatter;

	newFmt->fmtKind = PRINTF_FMT;
	newFmt->printfFmt = collapse_escapes(new_strdup(fmt));
	formats.Append (newFmt);

	attributes.Append(new_strdup (attr));
	alternates.Append(new_strdup(collapse_escapes(alternate)));
}

void ClassAdPrintMask::
registerFormat (IntCustomFmt fmt, const char *attr, char *alternate)
{
	Formatter *newFmt = new Formatter;

	newFmt->fmtKind = INT_CUSTOM_FMT;
	newFmt->df = fmt;

	formats.Append (newFmt);

	attributes.Append(new_strdup (attr));
	alternates.Append(new_strdup(collapse_escapes(alternate)));
}

void ClassAdPrintMask::
registerFormat (FloatCustomFmt fmt, const char *attr, char *alternate)
{
	Formatter *newFmt = new Formatter;

	newFmt->fmtKind = FLT_CUSTOM_FMT;
	newFmt->ff = fmt;

	formats.Append (newFmt);

	attributes.Append(new_strdup (attr));
	alternates.Append(new_strdup(collapse_escapes(alternate)));
}

void ClassAdPrintMask::
registerFormat (StringCustomFmt fmt, const char *attr, char *alternate)
{
	Formatter *newFmt = new Formatter;

	newFmt->fmtKind = STR_CUSTOM_FMT;
	newFmt->sf = fmt;

	formats.Append (newFmt);

	attributes.Append(new_strdup (attr));
	alternates.Append(new_strdup(collapse_escapes(alternate)));
}

void ClassAdPrintMask::
clearFormats (void)
{
	clearList (formats);
	clearList (attributes);
	clearList (alternates);
}

int ClassAdPrintMask::
display (FILE *file, ClassAd *ad)
{
	char * temp = display(ad);

	if (temp != NULL) {
		fputs(temp, file);
		delete [] temp;
		return 0;
	}
	return 1;

}

// returns a new char * that is your responsibility to delete.
char * ClassAdPrintMask::
display (ClassAd *ad)
{
	Formatter *fmt;
	char 	*attr, *alt;
	ExprTree *tree;
//	EvalResult result;
	Value 	result;				// NAC
	char * 	retval = new char[1024 * 8];
	int		intValue;
	float 	floatValue;
	char  	stringValue[1024];

	int 	tempInt;			// NAC
	double 	tempReal;			// NAC
	char 	tempString[1024];	// NAC

	formats.Rewind();
	attributes.Rewind();
	alternates.Rewind();

	retval[0] = '\0'; // Clear the return value;

	// for each item registered in the print mask
	while ((fmt=formats.Next()) && (attr=attributes.Next()) &&
				(alt=alternates.Next()))
	{
		switch( fmt->fmtKind )
			{
			case PRINTF_FMT:
				// get the expression tree of the attribute
				if (!(tree = ad->Lookup (attr))){
					if ( alt ) {
						sprintf( stringValue, "%s", alt );
						strcat( retval, stringValue );
					}
					continue;
				}

				// print the result
//				if (tree->EvalTree (ad, NULL, &result)){
				if(ad->EvaluateAttr(attr, result))					// NAC
				{
//					switch (result.type)
					switch (result.GetType())						// NAC
					{
//					case LX_STRING:
//						sprintf( stringValue, fmt->printfFmt,
//							collapse_escapes(result.s) );
					case (result.STRING_VALUE):					    // NAC
						result.IsStringValue( tempString, 1024 );		// NAC
						sprintf( stringValue, fmt->printfFmt,   		// NAC
								 collapse_escapes(tempString) );		// NAC
						strcat( retval, stringValue );
						break;

//					case LX_FLOAT:
//						sprintf( stringValue, fmt->printfFmt, result.f);
					case (result.REAL_VALUE):						// NAC
						result.IsRealValue( tempReal );		 			// NAC
						sprintf( stringValue, fmt->printfFmt, 			// NAC
								 (float)tempReal );						// NAC
						strcat( retval, stringValue );
						break;

//					case LX_INTEGER:
//						sprintf( stringValue, fmt->printfFmt, result.i);
					case (result.INTEGER_VALUE):					// NAC
						result.IsIntegerValue( tempInt );				// NAC
						sprintf( stringValue, fmt->printfFmt, tempInt );	// NAC
						strcat( retval, stringValue );
						break;

					default:
						strcat( retval, alt );
						continue;
					}
				}
				break;

			case INT_CUSTOM_FMT:
//				if( ad->EvalInteger( attr, NULL, intValue ) ) {
				if( ad->EvaluateAttrInt( attr, intValue ) ) {	// NAC
					strcat( retval, (fmt->df)( intValue , ad ) );
				} else {
					strcat( retval, alt );
				}
				break;

		  	case FLT_CUSTOM_FMT:
//				if( ad->EvalFloat( attr, NULL, floatValue ) ) {
				if( ad->EvaluateAttrReal( attr, tempReal ) ) {		//NAC
					floatValue = (float)tempReal;					//NAC
					strcat( retval, (fmt->ff)( floatValue , ad ) );
				} else {
					strcat( retval, alt );
				}
				break;

		  	case STR_CUSTOM_FMT:
//				if( ad->EvalString( attr, NULL, stringValue ) ) {
				if( ad->EvaluateAttrString( attr, stringValue, 1024 ) ) {
					strcat( retval, (fmt->sf)( stringValue , ad ) );
				} else {
					strcat( retval, alt );
				}
				break;

			default:
				strcat( retval, alt );
		}
	}

	return retval;
}

int ClassAdPrintMask::
display (FILE *file, ClassAdList *list)
{
	int retval = 1;
	ClassAd *ad;

	list->Open();
    while( (ad = (ClassAd *) list->Next()) ) {
		if( !display (file, ad) ) {
			retval = 0;
		}
    }
    list->Close ();

	return retval;
}

void ClassAdPrintMask::
clearList (List<char> &l)
{
    char *x;
    l.Rewind ();
    while( (x = l.Next()) ) {
        delete [] x;
        l.DeleteCurrent ();
    }
}

void ClassAdPrintMask::
clearList (List<Formatter> &l)
{
    Formatter *x;
    l.Rewind ();
    while( (x = l.Next ()) ) {
		if( x->fmtKind == PRINTF_FMT ) delete [] x->printfFmt;
		delete x;
        l.DeleteCurrent ();
    }
}

void ClassAdPrintMask::
copyList (List<Formatter> &to, List<Formatter> &from)
{
	Formatter *item, *newItem;

	clearList (to);
	from.Rewind ();
	while( (item = from.Next()) ) {
		newItem = new Formatter;
		*newItem = *item;
		if( newItem->fmtKind == PRINTF_FMT )
			newItem->printfFmt = new_strdup( item->printfFmt );
		to.Append (newItem);
	}
}

void ClassAdPrintMask::
copyList (List<char> &to, List<char> &from)
{
	char *item;

	clearList (to);
	from.Rewind ();
	while( (item = from.Next()) ) {
		to.Append (new_strdup (item));
	}
}

// strdup() which uses new
static char *new_strdup (const char *str)
{
    char *x = new char [strlen (str) + 1];
    if (!x)
    {
		return 0;
    }
    strcpy (x, str);
    return x;
}
<commit_msg>changed variable named 'list' to ca_list, since list clashed with some other identifier on Windows in the same namespace.<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
 * CONDOR Copyright Notice
 *
 * See LICENSE.TXT for additional notices and disclaimers.
 *
 * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.
 * No use of the CONDOR Software Program Source Code is authorized
 * without the express consent of the CONDOR Team.  For more information
 * contact: CONDOR Team, Attention: Professor Miron Livny,
 * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
 * (608) 262-0856 or miron@cs.wisc.edu.
 *
 * U.S. Government Rights Restrictions: Use, duplication, or disclosure
 * by the U.S. Government is subject to restrictions as set forth in
 * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
 * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
 * (2) of Commercial Computer Software-Restricted Rights at 48 CFR
 * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
 * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
 * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
#include "ad_printmask.h"
#include "escapes.h"

static char *new_strdup (const char *);

ClassAdPrintMask::
ClassAdPrintMask ()
{
}

ClassAdPrintMask::
ClassAdPrintMask (const ClassAdPrintMask &pm)
{
	copyList (formats, (List<Formatter> &) pm.formats);
	copyList (attributes, (List<char> &) pm.attributes);
	copyList (alternates, (List<char> &) pm.alternates);
}

ClassAdPrintMask::
~ClassAdPrintMask ()
{
	clearFormats ();
}

void ClassAdPrintMask::
registerFormat (char *fmt, const char *attr, char *alternate)
{
	Formatter *newFmt = new Formatter;

	newFmt->fmtKind = PRINTF_FMT;
	newFmt->printfFmt = collapse_escapes(new_strdup(fmt));
	formats.Append (newFmt);

	attributes.Append(new_strdup (attr));
	alternates.Append(new_strdup(collapse_escapes(alternate)));
}

void ClassAdPrintMask::
registerFormat (IntCustomFmt fmt, const char *attr, char *alternate)
{
	Formatter *newFmt = new Formatter;

	newFmt->fmtKind = INT_CUSTOM_FMT;
	newFmt->df = fmt;

	formats.Append (newFmt);

	attributes.Append(new_strdup (attr));
	alternates.Append(new_strdup(collapse_escapes(alternate)));
}

void ClassAdPrintMask::
registerFormat (FloatCustomFmt fmt, const char *attr, char *alternate)
{
	Formatter *newFmt = new Formatter;

	newFmt->fmtKind = FLT_CUSTOM_FMT;
	newFmt->ff = fmt;

	formats.Append (newFmt);

	attributes.Append(new_strdup (attr));
	alternates.Append(new_strdup(collapse_escapes(alternate)));
}

void ClassAdPrintMask::
registerFormat (StringCustomFmt fmt, const char *attr, char *alternate)
{
	Formatter *newFmt = new Formatter;

	newFmt->fmtKind = STR_CUSTOM_FMT;
	newFmt->sf = fmt;

	formats.Append (newFmt);

	attributes.Append(new_strdup (attr));
	alternates.Append(new_strdup(collapse_escapes(alternate)));
}

void ClassAdPrintMask::
clearFormats (void)
{
	clearList (formats);
	clearList (attributes);
	clearList (alternates);
}

int ClassAdPrintMask::
display (FILE *file, ClassAd *ad)
{
	char * temp = display(ad);

	if (temp != NULL) {
		fputs(temp, file);
		delete [] temp;
		return 0;
	}
	return 1;

}

// returns a new char * that is your responsibility to delete.
char * ClassAdPrintMask::
display (ClassAd *ad)
{
	Formatter *fmt;
	char 	*attr, *alt;
	ExprTree *tree;
//	EvalResult result;
	Value 	result;				// NAC
	char * 	retval = new char[1024 * 8];
	int		intValue;
	float 	floatValue;
	char  	stringValue[1024];

	int 	tempInt;			// NAC
	double 	tempReal;			// NAC
	char 	tempString[1024];	// NAC

	formats.Rewind();
	attributes.Rewind();
	alternates.Rewind();

	retval[0] = '\0'; // Clear the return value;

	// for each item registered in the print mask
	while ((fmt=formats.Next()) && (attr=attributes.Next()) &&
				(alt=alternates.Next()))
	{
		switch( fmt->fmtKind )
			{
			case PRINTF_FMT:
				// get the expression tree of the attribute
				if (!(tree = ad->Lookup (attr))){
					if ( alt ) {
						sprintf( stringValue, "%s", alt );
						strcat( retval, stringValue );
					}
					continue;
				}

				// print the result
//				if (tree->EvalTree (ad, NULL, &result)){
				if(ad->EvaluateAttr(attr, result))					// NAC
				{
//					switch (result.type)
					switch (result.GetType())						// NAC
					{
//					case LX_STRING:
//						sprintf( stringValue, fmt->printfFmt,
//							collapse_escapes(result.s) );
					case (result.STRING_VALUE):					    // NAC
						result.IsStringValue( tempString, 1024 );		// NAC
						sprintf( stringValue, fmt->printfFmt,   		// NAC
								 collapse_escapes(tempString) );		// NAC
						strcat( retval, stringValue );
						break;

//					case LX_FLOAT:
//						sprintf( stringValue, fmt->printfFmt, result.f);
					case (result.REAL_VALUE):						// NAC
						result.IsRealValue( tempReal );		 			// NAC
						sprintf( stringValue, fmt->printfFmt, 			// NAC
								 (float)tempReal );						// NAC
						strcat( retval, stringValue );
						break;

//					case LX_INTEGER:
//						sprintf( stringValue, fmt->printfFmt, result.i);
					case (result.INTEGER_VALUE):					// NAC
						result.IsIntegerValue( tempInt );				// NAC
						sprintf( stringValue, fmt->printfFmt, tempInt );	// NAC
						strcat( retval, stringValue );
						break;

					default:
						strcat( retval, alt );
						continue;
					}
				}
				break;

			case INT_CUSTOM_FMT:
//				if( ad->EvalInteger( attr, NULL, intValue ) ) {
				if( ad->EvaluateAttrInt( attr, intValue ) ) {	// NAC
					strcat( retval, (fmt->df)( intValue , ad ) );
				} else {
					strcat( retval, alt );
				}
				break;

		  	case FLT_CUSTOM_FMT:
//				if( ad->EvalFloat( attr, NULL, floatValue ) ) {
				if( ad->EvaluateAttrReal( attr, tempReal ) ) {		//NAC
					floatValue = (float)tempReal;					//NAC
					strcat( retval, (fmt->ff)( floatValue , ad ) );
				} else {
					strcat( retval, alt );
				}
				break;

		  	case STR_CUSTOM_FMT:
//				if( ad->EvalString( attr, NULL, stringValue ) ) {
				if( ad->EvaluateAttrString( attr, stringValue, 1024 ) ) {
					strcat( retval, (fmt->sf)( stringValue , ad ) );
				} else {
					strcat( retval, alt );
				}
				break;

			default:
				strcat( retval, alt );
		}
	}

	return retval;
}

int ClassAdPrintMask::
display (FILE *file, ClassAdList *ca_list)
{
	int retval = 1;
	ClassAd *ad;

	ca_list->Open();
    while( (ad = (ClassAd *) ca_list->Next()) ) {
		if( !display (file, ad) ) {
			retval = 0;
		}
    }
    ca_list->Close ();

	return retval;
}

void ClassAdPrintMask::
clearList (List<char> &l)
{
    char *x;
    l.Rewind ();
    while( (x = l.Next()) ) {
        delete [] x;
        l.DeleteCurrent ();
    }
}

void ClassAdPrintMask::
clearList (List<Formatter> &l)
{
    Formatter *x;
    l.Rewind ();
    while( (x = l.Next ()) ) {
		if( x->fmtKind == PRINTF_FMT ) delete [] x->printfFmt;
		delete x;
        l.DeleteCurrent ();
    }
}

void ClassAdPrintMask::
copyList (List<Formatter> &to, List<Formatter> &from)
{
	Formatter *item, *newItem;

	clearList (to);
	from.Rewind ();
	while( (item = from.Next()) ) {
		newItem = new Formatter;
		*newItem = *item;
		if( newItem->fmtKind == PRINTF_FMT )
			newItem->printfFmt = new_strdup( item->printfFmt );
		to.Append (newItem);
	}
}

void ClassAdPrintMask::
copyList (List<char> &to, List<char> &from)
{
	char *item;

	clearList (to);
	from.Rewind ();
	while( (item = from.Next()) ) {
		to.Append (new_strdup (item));
	}
}

// strdup() which uses new
static char *new_strdup (const char *str)
{
    char *x = new char [strlen (str) + 1];
    if (!x)
    {
		return 0;
    }
    strcpy (x, str);
    return x;
}
<|endoftext|>