<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                          License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation 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.
//
//M*/

#ifndef __OPENCV_CORE_EIGEN_HPP__
#define __OPENCV_CORE_EIGEN_HPP__

#ifdef __cplusplus

#include "cxcore.h"
#include <Eigen/Core>

namespace cv
{

template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols>
void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, Mat& dst )
{
    if( !(src.Flags & Eigen::RowMajorBit) )
    {
        Mat _src(src.cols(), src.rows(), DataType<_Tp>::type,
              (void*)src.data(), src.stride()*sizeof(_Tp));
        transpose(_src, dst);
    }
    else
    {
        Mat _src(src.rows(), src.cols(), DataType<_Tp>::type,
                 (void*)src.data(), src.stride()*sizeof(_Tp));
        _src.copyTo(dst);
    }
}

template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols>
void cv2eigen( const Mat& src,
               Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst )
{
    CV_DbgAssert(src.rows == _rows && src.cols == _cols);
    if( !(dst.Flags & Eigen::RowMajorBit) )
    {
        Mat _dst(src.cols, src.rows, DataType<_Tp>::type,
                 dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
        if( src.type() == _dst.type() )
            transpose(src, _dst);
        else if( src.cols == src.rows )
        {
            src.convertTo(_dst, _dst.type());
            transpose(_dst, _dst);
        }
        else
            Mat(src.t()).convertTo(_dst, _dst.type());
        CV_DbgAssert(_dst.data == (uchar*)dst.data());
    }
    else
    {
        Mat _dst(src.rows, src.cols, DataType<_Tp>::type,
                 dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
        src.convertTo(_dst, _dst.type());
        CV_DbgAssert(_dst.data == (uchar*)dst.data());
    }
}

template<typename _Tp>
void cv2eigen( const Mat& src,
               Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst )
{
    dst.resize(src.rows, src.cols);
    if( !(dst.Flags & Eigen::RowMajorBit) )
    {
        Mat _dst(src.cols, src.rows, DataType<_Tp>::type,
             dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
        if( src.type() == _dst.type() )
            transpose(src, _dst);
        else if( src.cols == src.rows )
        {
            src.convertTo(_dst, _dst.type());
            transpose(_dst, _dst);
        }
        else
            Mat(src.t()).convertTo(_dst, _dst.type());
        CV_DbgAssert(_dst.data == (uchar*)dst.data());
    }
    else
    {
        Mat _dst(src.rows, src.cols, DataType<_Tp>::type,
                 dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
        src.convertTo(_dst, _dst.type());
        CV_DbgAssert(_dst.data == (uchar*)dst.data());
    }
}

template<typename _Tp>
void cv2eigen( const Mat& src,
               Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst )
{
    CV_Assert(src.cols == 1);
    dst.resize(src.rows);

    if( !(dst.Flags & Eigen::RowMajorBit) )
    {
        Mat _dst(src.cols, src.rows, DataType<_Tp>::type,
                 dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
        if( src.type() == _dst.type() )
            transpose(src, _dst);
        else
            Mat(src.t()).convertTo(_dst, _dst.type());
        CV_DbgAssert(_dst.data == (uchar*)dst.data());
    }
    else
    {
        Mat _dst(src.rows, src.cols, DataType<_Tp>::type,
                 dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
        src.convertTo(_dst, _dst.type());
        CV_DbgAssert(_dst.data == (uchar*)dst.data());
    }
}

template<typename _Tp>
void cv2eigen( const Mat& src,
               Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst )
{
    CV_Assert(src.rows == 1);
    dst.resize(src.cols);
    if( !(dst.Flags & Eigen::RowMajorBit) )
    {
        Mat _dst(src.cols, src.rows, DataType<_Tp>::type,
                 dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
        if( src.type() == _dst.type() )
            transpose(src, _dst);
        else
            Mat(src.t()).convertTo(_dst, _dst.type());
        CV_DbgAssert(_dst.data == (uchar*)dst.data());
    }
    else
    {
        Mat _dst(src.rows, src.cols, DataType<_Tp>::type,
                 dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
        src.convertTo(_dst, _dst.type());
        CV_DbgAssert(_dst.data == (uchar*)dst.data());
    }
}

}

#endif

#endif

<commit_msg>include Eigen2/3 headers optionally, for greater flexibility<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                          License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation 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.
//
//M*/

#ifndef __OPENCV_CORE_EIGEN_HPP__
#define __OPENCV_CORE_EIGEN_HPP__

#ifdef __cplusplus

#include "cxcore.h"
#ifndef EIGEN_CORE_H
#include <Eigen/Core>
#endif

namespace cv
{

template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols>
void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, Mat& dst )
{
    if( !(src.Flags & Eigen::RowMajorBit) )
    {
        Mat _src(src.cols(), src.rows(), DataType<_Tp>::type,
              (void*)src.data(), src.stride()*sizeof(_Tp));
        transpose(_src, dst);
    }
    else
    {
        Mat _src(src.rows(), src.cols(), DataType<_Tp>::type,
                 (void*)src.data(), src.stride()*sizeof(_Tp));
        _src.copyTo(dst);
    }
}

template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols>
void cv2eigen( const Mat& src,
               Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst )
{
    CV_DbgAssert(src.rows == _rows && src.cols == _cols);
    if( !(dst.Flags & Eigen::RowMajorBit) )
    {
        Mat _dst(src.cols, src.rows, DataType<_Tp>::type,
                 dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
        if( src.type() == _dst.type() )
            transpose(src, _dst);
        else if( src.cols == src.rows )
        {
            src.convertTo(_dst, _dst.type());
            transpose(_dst, _dst);
        }
        else
            Mat(src.t()).convertTo(_dst, _dst.type());
        CV_DbgAssert(_dst.data == (uchar*)dst.data());
    }
    else
    {
        Mat _dst(src.rows, src.cols, DataType<_Tp>::type,
                 dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
        src.convertTo(_dst, _dst.type());
        CV_DbgAssert(_dst.data == (uchar*)dst.data());
    }
}

template<typename _Tp>
void cv2eigen( const Mat& src,
               Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst )
{
    dst.resize(src.rows, src.cols);
    if( !(dst.Flags & Eigen::RowMajorBit) )
    {
        Mat _dst(src.cols, src.rows, DataType<_Tp>::type,
             dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
        if( src.type() == _dst.type() )
            transpose(src, _dst);
        else if( src.cols == src.rows )
        {
            src.convertTo(_dst, _dst.type());
            transpose(_dst, _dst);
        }
        else
            Mat(src.t()).convertTo(_dst, _dst.type());
        CV_DbgAssert(_dst.data == (uchar*)dst.data());
    }
    else
    {
        Mat _dst(src.rows, src.cols, DataType<_Tp>::type,
                 dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
        src.convertTo(_dst, _dst.type());
        CV_DbgAssert(_dst.data == (uchar*)dst.data());
    }
}

template<typename _Tp>
void cv2eigen( const Mat& src,
               Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst )
{
    CV_Assert(src.cols == 1);
    dst.resize(src.rows);

    if( !(dst.Flags & Eigen::RowMajorBit) )
    {
        Mat _dst(src.cols, src.rows, DataType<_Tp>::type,
                 dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
        if( src.type() == _dst.type() )
            transpose(src, _dst);
        else
            Mat(src.t()).convertTo(_dst, _dst.type());
        CV_DbgAssert(_dst.data == (uchar*)dst.data());
    }
    else
    {
        Mat _dst(src.rows, src.cols, DataType<_Tp>::type,
                 dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
        src.convertTo(_dst, _dst.type());
        CV_DbgAssert(_dst.data == (uchar*)dst.data());
    }
}

template<typename _Tp>
void cv2eigen( const Mat& src,
               Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst )
{
    CV_Assert(src.rows == 1);
    dst.resize(src.cols);
    if( !(dst.Flags & Eigen::RowMajorBit) )
    {
        Mat _dst(src.cols, src.rows, DataType<_Tp>::type,
                 dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
        if( src.type() == _dst.type() )
            transpose(src, _dst);
        else
            Mat(src.t()).convertTo(_dst, _dst.type());
        CV_DbgAssert(_dst.data == (uchar*)dst.data());
    }
    else
    {
        Mat _dst(src.rows, src.cols, DataType<_Tp>::type,
                 dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
        src.convertTo(_dst, _dst.type());
        CV_DbgAssert(_dst.data == (uchar*)dst.data());
    }
}

}

#endif

#endif

<|endoftext|>


<commit_before><commit_msg>[ADDED] easydb TrimImage log<commit_after><|endoftext|>


<commit_before>/// \file
/// \ingroup tutorial_multicore
/// Parallel fill of a histogram
/// This tutorial shows how a histogram can be filled in parallel
/// with a multiprocess approach.
///
/// \macro_image
/// \macro_code
/// \author Danilo Piparo

// Measure time in a scope
class TimerRAII {
   TStopwatch fTimer;
   std::string fMeta;
public:
   TimerRAII(const char *meta): fMeta(meta)
   {
      fTimer.Start();
   }
   ~TimerRAII()
   {
      fTimer.Stop();
      std::cout << fMeta << " - real time elapsed " << fTimer.RealTime() << "s" << std::endl;
   }
};

Int_t mp201_parallelHistoFill(UInt_t poolSize = 4)
{
   TH1::AddDirectory(false);
   TProcPool pool(poolSize);
   auto fillRandomHisto = [](int i = 0) {
      gRandom->SetSeed(i);
      auto h = new TH1F("myHist", "Filled in parallel", 128, -8, 8);
      h->FillRandom("gaus", 1000000);
      return h;
   };

   TimerRAII timer("Filling Histogram in parallel and drawing it.");
   auto seeds = ROOT::TSeqI(23);
   auto sumRandomHisto = pool.MapReduce(fillRandomHisto, seeds, PoolUtils::ReduceObjects);

   auto c = new TCanvas();
   sumRandomHisto->Draw();
   return 0;
}
<commit_msg>Remove the global from example even if it is a Multiprocess example<commit_after>/// \file
/// \ingroup tutorial_multicore
/// Parallel fill of a histogram
/// This tutorial shows how a histogram can be filled in parallel
/// with a multiprocess approach.
///
/// \macro_image
/// \macro_code
/// \author Danilo Piparo

// Measure time in a scope
class TimerRAII {
   TStopwatch fTimer;
   std::string fMeta;
public:
   TimerRAII(const char *meta): fMeta(meta)
   {
      fTimer.Start();
   }
   ~TimerRAII()
   {
      fTimer.Stop();
      std::cout << fMeta << " - real time elapsed " << fTimer.RealTime() << "s" << std::endl;
   }
};

Int_t mp201_parallelHistoFill(UInt_t poolSize = 4)
{
   TH1::AddDirectory(false);
   TProcPool pool(poolSize);
   auto fillRandomHisto = [](int seed = 0) {
      TRandom3 rndm(seed);
      auto h = new TH1F("myHist", "Filled in parallel", 128, -8, 8);
      for (auto i : ROOT::TSeqI(1000000)) {
         h->Fill(rndm.Gaus(0,1));
      }
      return h;
   };

   TimerRAII timer("Filling Histogram in parallel and drawing it.");
   auto seeds = ROOT::TSeqI(23);
   auto sumRandomHisto = pool.MapReduce(fillRandomHisto, seeds, PoolUtils::ReduceObjects);

   auto c = new TCanvas();
   sumRandomHisto->Draw();
   return 0;
}
<|endoftext|>


<commit_before>#include "FileIO.h"
#include "Symbol.h"

#include <ee/FileHelper.h>
#include <ee/panel_msg.h>
#include <ee/SymbolMgr.h>
#include <ee/Sprite.h>
#include <ee/SpriteFactory.h>

#include <fstream>

namespace emask
{

void FileIO::Store(const char* filepath, const Symbol* sym)
{
	Json::Value value;

	std::string dir = ee::FileHelper::GetFileDir(filepath) + "\\";

	value["name"] = sym->name;

	const s2::Symbol *base = sym->GetBase()->GetSymbol(),
		             *mask = sym->GetMask()->GetSymbol();
	if (base) {
		value["base"]["filepath"] = ee::FileHelper::GetRelativePath(dir,
			dynamic_cast<const ee::Symbol*>(base)->GetFilepath());
	}
	if (mask) {
		value["mask"]["filepath"] = ee::FileHelper::GetRelativePath(dir,
			dynamic_cast<const ee::Symbol*>(mask)->GetFilepath());
	}

	Json::StyledStreamWriter writer;
	std::locale::global(std::locale(""));
	std::ofstream fout(filepath);
	std::locale::global(std::locale("C"));
	writer.write(fout, value);
	fout.close();
}

void FileIO::Load(const char* filepath, Symbol* sym)
{
	Json::Value value;
	Json::Reader reader;
	std::locale::global(std::locale(""));
	std::ifstream fin(filepath);
	std::locale::global(std::locale("C"));
	reader.parse(fin, value);
	fin.close();

	std::string dir = ee::FileHelper::GetFileDir(filepath) + "\\";

	sym->name = value["name"].asString();

	if (!value["base"].isNull()) {
		std::string filepath = ee::FileHelper::GetAbsolutePath(dir, value["base"]["filepath"].asString());
		ee::Symbol* sym = ee::SymbolMgr::Instance()->FetchSymbol(filepath);
		ee::Sprite* spr = ee::SpriteFactory::Instance()->Create(sym);
		static_cast<Symbol*>(sym)->SetBase(spr);
		spr->RemoveReference();
		sym->RemoveReference();
	}
	if (!value["mask"].isNull()) {
		std::string filepath = ee::FileHelper::GetAbsolutePath(dir, value["mask"]["filepath"].asString());
		ee::Symbol* sym = ee::SymbolMgr::Instance()->FetchSymbol(filepath);
		ee::Sprite* spr = ee::SpriteFactory::Instance()->Create(sym);
		static_cast<Symbol*>(sym)->SetMask(spr);
		spr->RemoveReference();
		sym->RemoveReference();
	}

	ee::SetCanvasDirtySJ::Instance()->SetDirty();
}

}<commit_msg>[FIXED] mask load<commit_after>#include "FileIO.h"
#include "Symbol.h"

#include <ee/FileHelper.h>
#include <ee/panel_msg.h>
#include <ee/SymbolMgr.h>
#include <ee/Sprite.h>
#include <ee/SpriteFactory.h>

#include <fstream>

namespace emask
{

void FileIO::Store(const char* filepath, const Symbol* sym)
{
	Json::Value value;

	std::string dir = ee::FileHelper::GetFileDir(filepath) + "\\";

	value["name"] = sym->name;

	const s2::Symbol *base = sym->GetBase()->GetSymbol(),
		             *mask = sym->GetMask()->GetSymbol();
	if (base) {
		value["base"]["filepath"] = ee::FileHelper::GetRelativePath(dir,
			dynamic_cast<const ee::Symbol*>(base)->GetFilepath());
	}
	if (mask) {
		value["mask"]["filepath"] = ee::FileHelper::GetRelativePath(dir,
			dynamic_cast<const ee::Symbol*>(mask)->GetFilepath());
	}

	Json::StyledStreamWriter writer;
	std::locale::global(std::locale(""));
	std::ofstream fout(filepath);
	std::locale::global(std::locale("C"));
	writer.write(fout, value);
	fout.close();
}

void FileIO::Load(const char* filepath, Symbol* sym)
{
	Json::Value value;
	Json::Reader reader;
	std::locale::global(std::locale(""));
	std::ifstream fin(filepath);
	std::locale::global(std::locale("C"));
	reader.parse(fin, value);
	fin.close();

	std::string dir = ee::FileHelper::GetFileDir(filepath) + "\\";

	sym->name = value["name"].asString();

	if (!value["base"].isNull()) {
		std::string filepath = ee::FileHelper::GetAbsolutePath(dir, value["base"]["filepath"].asString());
		ee::Symbol* base_sym = ee::SymbolMgr::Instance()->FetchSymbol(filepath);
		ee::Sprite* base_spr = ee::SpriteFactory::Instance()->Create(base_sym);
		sym->SetBase(base_spr);
		base_spr->RemoveReference();
		base_sym->RemoveReference();
	}
	if (!value["mask"].isNull()) {
		std::string filepath = ee::FileHelper::GetAbsolutePath(dir, value["mask"]["filepath"].asString());
		ee::Symbol* mask_sym = ee::SymbolMgr::Instance()->FetchSymbol(filepath);
		ee::Sprite* mask_spr = ee::SpriteFactory::Instance()->Create(mask_sym);
		sym->SetMask(mask_spr);
		mask_spr->RemoveReference();
		mask_sym->RemoveReference();
	}

	ee::SetCanvasDirtySJ::Instance()->SetDirty();
}

}<|endoftext|>


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

#include "IECore/Reader.h"
#include "IECore/FileNameParameter.h"
#include "IECore/NullObject.h"
#include "IECore/CompoundParameter.h"

#include "boost/algorithm/string/split.hpp"
#include "boost/algorithm/string/classification.hpp"
#include "boost/filesystem/convenience.hpp"

#include <iostream>

using namespace std;
using namespace IECore;
using namespace boost;
using namespace boost::filesystem;

Reader::Reader(  const std::string &name, const std::string &description, ParameterPtr resultParameter )
	: 	Op( name, description, resultParameter ? resultParameter : new Parameter( "result", "The loaded object.", new NullObject ) )
{
	m_fileNameParameter = new FileNameParameter( "fileName", "The name of the file to be loaded", "", "", false, PathParameter::MustExist );
	parameters()->addParameter( m_fileNameParameter );
}

CompoundObjectPtr Reader::readHeader()
{
	CompoundObjectPtr header = new CompoundObject();

	return header;
}

ObjectPtr Reader::read()
{
	/// \todo Perhaps we should append the fileName() to any exceptions thrown by operate() before re-raising them?
	return operate();
}

const std::string &Reader::fileName() const
{
	return m_fileNameParameter->getTypedValue();
}

ReaderPtr Reader::create( const std::string &fileName )
{
	bool knownExtension = false;
	ExtensionsToFnsMap *m = extensionsToFns();
	assert( m );
	string ext = extension(boost::filesystem::path(fileName));
	if( ext!="" )
	{
		ExtensionsToFnsMap::const_iterator it = m->find( ext );
		if( it!=m->end() )
		{
			knownExtension = true;
			if( it->second.canRead( fileName ) )
			{
				return it->second.creator( fileName );
			}
		}
	}

	// failed to find a reader based on extension. try all canRead functions
	// as a last ditch attempt.
	for( ExtensionsToFnsMap::const_iterator it=m->begin(); it!=m->end(); it++ )
	{
		if( it->second.canRead( fileName ) )
		{
			return( it->second.creator( fileName ) );
		}
	}
	if ( knownExtension )
	{
		throw Exception( string( "Unable to load file '" ) + fileName + "'!" );
	}
	else
	{
		throw Exception( string( "Unrecognized input file format '") + ext + "'!" );
	}
}

void Reader::supportedExtensions( std::vector<std::string> &extensions )
{
	ExtensionsToFnsMap *m = extensionsToFns();
	assert( m );
	for( ExtensionsToFnsMap::const_iterator it=m->begin(); it!=m->end(); it++ )
	{
		extensions.push_back( it->first.substr( 1 ) );
	}
}

void Reader::registerReader( const std::string &extensions, CanReadFn canRead, CreatorFn creator )
{
	ExtensionsToFnsMap *m = extensionsToFns();
	assert( m );
	vector<string> splitExt;
	split( splitExt, extensions, is_any_of( " " ) );
	ReaderFns r;
	r.creator = creator;
	r.canRead = canRead;
	for( vector<string>::const_iterator it=splitExt.begin(); it!=splitExt.end(); it++ )
	{
		m->insert( ExtensionsToFnsMap::value_type( "." + *it, r ) );
	}
}

Reader::ExtensionsToFnsMap *Reader::extensionsToFns()
{
	static ExtensionsToFnsMap *m = new ExtensionsToFnsMap;
	return m;
}
<commit_msg>Expanded comment<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007-2008, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "IECore/Reader.h"
#include "IECore/FileNameParameter.h"
#include "IECore/NullObject.h"
#include "IECore/CompoundParameter.h"

#include "boost/algorithm/string/split.hpp"
#include "boost/algorithm/string/classification.hpp"
#include "boost/filesystem/convenience.hpp"

#include <iostream>

using namespace std;
using namespace IECore;
using namespace boost;
using namespace boost::filesystem;

Reader::Reader(  const std::string &name, const std::string &description, ParameterPtr resultParameter )
	: 	Op( name, description, resultParameter ? resultParameter : new Parameter( "result", "The loaded object.", new NullObject ) )
{
	m_fileNameParameter = new FileNameParameter( "fileName", "The name of the file to be loaded", "", "", false, PathParameter::MustExist );
	parameters()->addParameter( m_fileNameParameter );
}

CompoundObjectPtr Reader::readHeader()
{
	CompoundObjectPtr header = new CompoundObject();

	return header;
}

ObjectPtr Reader::read()
{
	/// \todo Perhaps we should append the fileName() to any exceptions thrown by operate() before re-raising them?
	/// Use of boost.exception might make this easier.
	return operate();
}

const std::string &Reader::fileName() const
{
	return m_fileNameParameter->getTypedValue();
}

ReaderPtr Reader::create( const std::string &fileName )
{
	bool knownExtension = false;
	ExtensionsToFnsMap *m = extensionsToFns();
	assert( m );
	string ext = extension(boost::filesystem::path(fileName));
	if( ext!="" )
	{
		ExtensionsToFnsMap::const_iterator it = m->find( ext );
		if( it!=m->end() )
		{
			knownExtension = true;
			if( it->second.canRead( fileName ) )
			{
				return it->second.creator( fileName );
			}
		}
	}

	// failed to find a reader based on extension. try all canRead functions
	// as a last ditch attempt.
	for( ExtensionsToFnsMap::const_iterator it=m->begin(); it!=m->end(); it++ )
	{
		if( it->second.canRead( fileName ) )
		{
			return( it->second.creator( fileName ) );
		}
	}
	if ( knownExtension )
	{
		throw Exception( string( "Unable to load file '" ) + fileName + "'!" );
	}
	else
	{
		throw Exception( string( "Unrecognized input file format '") + ext + "'!" );
	}
}

void Reader::supportedExtensions( std::vector<std::string> &extensions )
{
	ExtensionsToFnsMap *m = extensionsToFns();
	assert( m );
	for( ExtensionsToFnsMap::const_iterator it=m->begin(); it!=m->end(); it++ )
	{
		extensions.push_back( it->first.substr( 1 ) );
	}
}

void Reader::registerReader( const std::string &extensions, CanReadFn canRead, CreatorFn creator )
{
	ExtensionsToFnsMap *m = extensionsToFns();
	assert( m );
	vector<string> splitExt;
	split( splitExt, extensions, is_any_of( " " ) );
	ReaderFns r;
	r.creator = creator;
	r.canRead = canRead;
	for( vector<string>::const_iterator it=splitExt.begin(); it!=splitExt.end(); it++ )
	{
		m->insert( ExtensionsToFnsMap::value_type( "." + *it, r ) );
	}
}

Reader::ExtensionsToFnsMap *Reader::extensionsToFns()
{
	static ExtensionsToFnsMap *m = new ExtensionsToFnsMap;
	return m;
}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File: CoupledAssemblyMap.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// 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.
//
// Description: Coupled assembly map for linear elasticity solver.
//
///////////////////////////////////////////////////////////////////////////////

#include <LinearElasticSolver/EquationSystems/CoupledAssemblyMap.h>
#include <SpatialDomains/MeshGraph.h>
#include <LocalRegions/SegExp.h>
#include <LocalRegions/Expansion1D.h>
#include <LocalRegions/Expansion2D.h>
#include <MultiRegions/GlobalLinSysDirectStaticCond.h>

#include <iomanip>

namespace Nektar
{
    /**
     * @brief Take an existing assembly map and create a coupled version
     * suitable for use in the linear elasticity solver.
     *
     * The linear elasticity solver requires a slight reordering of local and
     * global coefficients to support problems of the form
     *
     * [ A B ] [ u ] = [ f_u ]
     * [ C D ] [ v ]   [ f_v ]
     *
     * In order to support static condensation, we store everything as
     */
    CoupledAssemblyMap::CoupledAssemblyMap(
        const LibUtilities::SessionReaderSharedPtr        &pSession,
        const SpatialDomains::MeshGraphSharedPtr          &graph,
        const MultiRegions::AssemblyMapCGSharedPtr        &cgMap,
        const SpatialDomains::BoundaryConditionsSharedPtr &boundaryConditions,
        const Array<OneD, MultiRegions::ExpListSharedPtr> &fields) :
        AssemblyMapCG(pSession)
    {
        int nVel = fields[0]->GetCoordim(0);

        // Multi-level static condensation doesn't work yet.
        ASSERTL0(m_solnType != MultiRegions::eDirectMultiLevelStaticCond    &&
                 m_solnType != MultiRegions::eIterativeMultiLevelStaticCond &&
                 m_solnType != MultiRegions::eXxtMultiLevelStaticCond,
                 "Multi-level static condensation not supported.");

        // Copy various coefficient counts, and multiply by the dimension of the
        // problem to obtain our new values.
        m_numLocalDirBndCoeffs      = cgMap->GetNumLocalDirBndCoeffs()  * nVel;
        m_numLocalBndCoeffs         = cgMap->GetNumLocalBndCoeffs()     * nVel;
        m_numLocalCoeffs            = cgMap->GetNumLocalCoeffs()        * nVel;
        m_numGlobalBndCoeffs        = cgMap->GetNumGlobalBndCoeffs()    * nVel;
        m_numGlobalDirBndCoeffs     = cgMap->GetNumGlobalDirBndCoeffs() * nVel;
        m_numGlobalCoeffs           = cgMap->GetNumGlobalCoeffs()       * nVel;
        m_signChange                = cgMap->GetSignChange();
        m_systemSingular            = cgMap->GetSingularSystem();

        // Copy static condensation information. TODO: boundary and interior
        // patches need to be re-ordered in order to allow for multi-level
        // static condensation support.
        m_staticCondLevel           = cgMap->GetStaticCondLevel();
        m_numPatches                = cgMap->GetNumPatches();
        m_numLocalBndCoeffsPerPatch = cgMap->GetNumLocalBndCoeffsPerPatch();
        m_numLocalIntCoeffsPerPatch = cgMap->GetNumLocalIntCoeffsPerPatch();

        // Set up local to global and boundary condition maps.
        const int nLocBndCondDofs = cgMap->
            GetBndCondCoeffsToGlobalCoeffsMap().num_elements() * nVel;

        ASSERTL0(nLocBndCondDofs == m_numLocalDirBndCoeffs,
                 "Only Dirichlet boundary conditions are supported");

        // Allocate storage for local to global maps. TODO: Set up global to
        // universal map to support parallel execution.
        m_localToGlobalMap               =
            Array<OneD, int>(m_numLocalCoeffs,-1);
        m_localToGlobalBndMap            =
            Array<OneD, int>(m_numLocalBndCoeffs,-1);
        m_bndCondCoeffsToGlobalCoeffsMap =
            Array<OneD, int>(nLocBndCondDofs,-1);

        // Only require a sign map if we are using modal polynomials in the
        // expansion and the order is >= 3.
        if (m_signChange)
        {
            m_localToGlobalSign               =
                Array<OneD, NekDouble>(m_numLocalCoeffs,1.0);
            m_localToGlobalBndSign            =
                Array<OneD, NekDouble>(m_numLocalBndCoeffs,1.0);
            m_bndCondCoeffsToGlobalCoeffsSign =
                Array<OneD, NekDouble>(nLocBndCondDofs,1.0);
        }
        else
        {
            m_localToGlobalSign               = NullNekDouble1DArray;
            m_localToGlobalBndSign            = NullNekDouble1DArray;
            m_bndCondCoeffsToGlobalCoeffsSign = NullNekDouble1DArray;
        }

        const int nGlobBndCoeffs = cgMap->GetNumGlobalBndCoeffs();
        const int nGlobDirCoeffs = cgMap->GetNumGlobalDirBndCoeffs();
        const int nNonDirBndCoeffs = nGlobBndCoeffs - nGlobDirCoeffs;

        const LocalRegions::ExpansionVector &locExpVector = *(fields[0]->GetExp());
        map<int, int > newGlobalIds;
        int i, j, n, cnt1, cnt2;

        // Order local boundary degrees of freedom. These are basically fine; we
        // reorder storage so that we loop over each element and then each
        // component of velocity.
        cnt1 = cnt2 = 0;
        for (i = 0; i < locExpVector.size(); ++i)
        {
            const int nBndCoeffs = locExpVector[i]->NumBndryCoeffs();

            for (n = 0; n < nVel; ++n)
            {
                for (j = 0; j < nBndCoeffs; ++j, ++cnt1)
                {
                    const int l2g = cgMap->GetLocalToGlobalBndMap()[cnt2+j];
                    m_localToGlobalBndMap[cnt1] = nVel * l2g + n;

                    if (m_signChange)
                    {
                        m_localToGlobalBndSign[cnt1] =
                            cgMap->GetLocalToGlobalBndSign()[cnt2+j];
                    }

                    if (n == 0)
                    {
                        const int l2gnew = m_localToGlobalBndMap[cnt1];
                        if (newGlobalIds.count(l2g))
                        {
                            ASSERTL1(newGlobalIds[l2g] == l2gnew,
                                     "Consistency error");
                        }
                        newGlobalIds[l2g] = l2gnew;
                    }
                }
            }

            cnt2 += nBndCoeffs;
        }

        int globalId = m_numGlobalBndCoeffs;

        // Interior degrees of freedom are a bit more tricky -- global linear
        // system solve relies on them being in the same order as the BinvD, C
        // and invD matrices.
        cnt1 = cnt2 = 0;
        for (i = 0; i < locExpVector.size(); ++i)
        {
            const int nCoeffs    = locExpVector[i]->GetNcoeffs();
            const int nBndCoeffs = locExpVector[i]->NumBndryCoeffs();

            for (n = 0; n < nVel; ++n)
            {
                for (j = 0; j < nBndCoeffs; ++j, ++cnt1, ++cnt2)
                {
                    const int l2g = m_localToGlobalBndMap[cnt2];
                    m_localToGlobalMap[cnt1] = l2g;

                    if (m_signChange)
                    {
                        m_localToGlobalSign[cnt1] = m_localToGlobalBndSign[cnt2];
                    }
                }
            }

            for (n = 0; n < nVel; ++n)
            {
                for (j = 0; j < nCoeffs - nBndCoeffs; ++j, ++cnt1)
                {
                    m_localToGlobalMap[cnt1] = globalId++;
                }
            }
        }

        for (i = 0; i < m_localToGlobalMap.num_elements(); ++i)
        {
            ASSERTL1(m_localToGlobalMap[i] != -1, "Consistency error");
        }

        ASSERTL1(globalId == m_numGlobalCoeffs, "Consistency error");

        // Set up boundary condition mapping: this is straightforward since we
        // only consider Dirichlet boundary conditions.
        const Array<OneD, const MultiRegions::ExpListSharedPtr> &bndCondExp
            = fields[0]->GetBndCondExpansions();

        const int nLocalDirBndCoeffs = cgMap->GetNumLocalDirBndCoeffs();

        cnt1 = 0;
        for (n = 0; n < nVel; ++n)
        {
            for (i = 0; i < nLocalDirBndCoeffs; ++i, ++cnt1)
            {
                const int l2g = cgMap->GetBndCondCoeffsToGlobalCoeffsMap()[i];
                int newId = newGlobalIds[l2g];
                m_bndCondCoeffsToGlobalCoeffsMap[cnt1] = newId + n;

                if (m_signChange)
                {
                    m_bndCondCoeffsToGlobalCoeffsSign[cnt1] =
                        cgMap->GetBndCondCoeffsToGlobalCoeffsSign(i);
                }
            }
        }

        // Finally, set up global to universal maps. hack for now
        m_globalToUniversalBndMapUnique = Array<OneD, int>(m_numGlobalBndCoeffs, 1);

        m_hash = boost::hash_range(
            m_localToGlobalMap.begin(), m_localToGlobalMap.end());
    }
}
<commit_msg>Initial parallel implementation, fringe cases will still not work<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File: CoupledAssemblyMap.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// 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.
//
// Description: Coupled assembly map for linear elasticity solver.
//
///////////////////////////////////////////////////////////////////////////////

#include <LinearElasticSolver/EquationSystems/CoupledAssemblyMap.h>
#include <SpatialDomains/MeshGraph.h>
#include <LocalRegions/SegExp.h>
#include <LocalRegions/Expansion1D.h>
#include <LocalRegions/Expansion2D.h>
#include <MultiRegions/GlobalLinSysDirectStaticCond.h>

#include <iomanip>

namespace Nektar
{
    /**
     * @brief Take an existing assembly map and create a coupled version
     * suitable for use in the linear elasticity solver.
     *
     * The linear elasticity solver requires a slight reordering of local and
     * global coefficients to support problems of the form
     *
     * [ A B ] [ u ] = [ f_u ]
     * [ C D ] [ v ]   [ f_v ]
     *
     * In order to support static condensation, we store everything as
     */
    CoupledAssemblyMap::CoupledAssemblyMap(
        const LibUtilities::SessionReaderSharedPtr        &pSession,
        const SpatialDomains::MeshGraphSharedPtr          &graph,
        const MultiRegions::AssemblyMapCGSharedPtr        &cgMap,
        const SpatialDomains::BoundaryConditionsSharedPtr &boundaryConditions,
        const Array<OneD, MultiRegions::ExpListSharedPtr> &fields) :
        AssemblyMapCG(pSession)
    {
        int nVel = fields[0]->GetCoordim(0);

        // Multi-level static condensation doesn't work yet.
        ASSERTL0(m_solnType != MultiRegions::eDirectMultiLevelStaticCond    &&
                 m_solnType != MultiRegions::eIterativeMultiLevelStaticCond &&
                 m_solnType != MultiRegions::eXxtMultiLevelStaticCond,
                 "Multi-level static condensation not supported.");

        // Copy various coefficient counts, and multiply by the dimension of the
        // problem to obtain our new values.
        m_numLocalDirBndCoeffs      = cgMap->GetNumLocalDirBndCoeffs()  * nVel;
        m_numLocalBndCoeffs         = cgMap->GetNumLocalBndCoeffs()     * nVel;
        m_numLocalCoeffs            = cgMap->GetNumLocalCoeffs()        * nVel;
        m_numGlobalBndCoeffs        = cgMap->GetNumGlobalBndCoeffs()    * nVel;
        m_numGlobalDirBndCoeffs     = cgMap->GetNumGlobalDirBndCoeffs() * nVel;
        m_numGlobalCoeffs           = cgMap->GetNumGlobalCoeffs()       * nVel;
        m_signChange                = cgMap->GetSignChange();
        m_systemSingular            = cgMap->GetSingularSystem();

        // Copy static condensation information. TODO: boundary and interior
        // patches need to be re-ordered in order to allow for multi-level
        // static condensation support.
        m_staticCondLevel           = cgMap->GetStaticCondLevel();
        m_numPatches                = cgMap->GetNumPatches();
        m_numLocalBndCoeffsPerPatch = cgMap->GetNumLocalBndCoeffsPerPatch();
        m_numLocalIntCoeffsPerPatch = cgMap->GetNumLocalIntCoeffsPerPatch();

        // Set up local to global and boundary condition maps.
        const int nLocBndCondDofs = cgMap->
            GetBndCondCoeffsToGlobalCoeffsMap().num_elements() * nVel;

        ASSERTL0(nLocBndCondDofs == m_numLocalDirBndCoeffs,
                 "Only Dirichlet boundary conditions are supported");

        // Allocate storage for local to global maps. TODO: Set up global to
        // universal map to support parallel execution.
        m_localToGlobalMap               =
            Array<OneD, int>(m_numLocalCoeffs,-1);
        m_localToGlobalBndMap            =
            Array<OneD, int>(m_numLocalBndCoeffs,-1);
        m_bndCondCoeffsToGlobalCoeffsMap =
            Array<OneD, int>(nLocBndCondDofs,-1);

        // Only require a sign map if we are using modal polynomials in the
        // expansion and the order is >= 3.
        if (m_signChange)
        {
            m_localToGlobalSign               =
                Array<OneD, NekDouble>(m_numLocalCoeffs,1.0);
            m_localToGlobalBndSign            =
                Array<OneD, NekDouble>(m_numLocalBndCoeffs,1.0);
            m_bndCondCoeffsToGlobalCoeffsSign =
                Array<OneD, NekDouble>(nLocBndCondDofs,1.0);
        }
        else
        {
            m_localToGlobalSign               = NullNekDouble1DArray;
            m_localToGlobalBndSign            = NullNekDouble1DArray;
            m_bndCondCoeffsToGlobalCoeffsSign = NullNekDouble1DArray;
        }

        const int nGlobBndCoeffs = cgMap->GetNumGlobalBndCoeffs();
        const int nGlobDirCoeffs = cgMap->GetNumGlobalDirBndCoeffs();
        const int nNonDirBndCoeffs = nGlobBndCoeffs - nGlobDirCoeffs;

        const LocalRegions::ExpansionVector &locExpVector = *(fields[0]->GetExp());
        map<int, int> newGlobalIds;
        int i, j, n, cnt1, cnt2;

        // Order local boundary degrees of freedom. These are basically fine; we
        // reorder storage so that we loop over each element and then each
        // component of velocity.
        cnt1 = cnt2 = 0;
        for (i = 0; i < locExpVector.size(); ++i)
        {
            const int nBndCoeffs = locExpVector[i]->NumBndryCoeffs();

            for (n = 0; n < nVel; ++n)
            {
                for (j = 0; j < nBndCoeffs; ++j, ++cnt1)
                {
                    const int l2g = cgMap->GetLocalToGlobalBndMap()[cnt2+j];
                    m_localToGlobalBndMap[cnt1] = nVel * l2g + n;

                    if (m_signChange)
                    {
                        m_localToGlobalBndSign[cnt1] =
                            cgMap->GetLocalToGlobalBndSign()[cnt2+j];
                    }

                    if (n == 0)
                    {
                        const int l2gnew = m_localToGlobalBndMap[cnt1];
                        if (newGlobalIds.count(l2g))
                        {
                            ASSERTL1(newGlobalIds[l2g] == l2gnew,
                                     "Consistency error");
                        }
                        newGlobalIds[l2g] = l2gnew;
                    }
                }
            }

            cnt2 += nBndCoeffs;
        }

        int globalId = m_numGlobalBndCoeffs;

        // Interior degrees of freedom are a bit more tricky -- global linear
        // system solve relies on them being in the same order as the BinvD, C
        // and invD matrices.
        cnt1 = cnt2 = 0;
        for (i = 0; i < locExpVector.size(); ++i)
        {
            const int nCoeffs    = locExpVector[i]->GetNcoeffs();
            const int nBndCoeffs = locExpVector[i]->NumBndryCoeffs();

            for (n = 0; n < nVel; ++n)
            {
                for (j = 0; j < nBndCoeffs; ++j, ++cnt1, ++cnt2)
                {
                    const int l2g = m_localToGlobalBndMap[cnt2];
                    m_localToGlobalMap[cnt1] = l2g;

                    if (m_signChange)
                    {
                        m_localToGlobalSign[cnt1] = m_localToGlobalBndSign[cnt2];
                    }
                }
            }

            for (n = 0; n < nVel; ++n)
            {
                for (j = 0; j < nCoeffs - nBndCoeffs; ++j, ++cnt1)
                {
                    m_localToGlobalMap[cnt1] = globalId++;
                }
            }
        }

        for (i = 0; i < m_localToGlobalMap.num_elements(); ++i)
        {
            ASSERTL1(m_localToGlobalMap[i] != -1, "Consistency error");
        }

        ASSERTL1(globalId == m_numGlobalCoeffs, "Consistency error");

        // Set up boundary condition mapping: this is straightforward since we
        // only consider Dirichlet boundary conditions.
        const Array<OneD, const MultiRegions::ExpListSharedPtr> &bndCondExp
            = fields[0]->GetBndCondExpansions();

        const int nLocalDirBndCoeffs = cgMap->GetNumLocalDirBndCoeffs();

        cnt1 = 0;
        for (n = 0; n < nVel; ++n)
        {
            for (i = 0; i < nLocalDirBndCoeffs; ++i, ++cnt1)
            {
                const int l2g = cgMap->GetBndCondCoeffsToGlobalCoeffsMap()[i];
                int newId = newGlobalIds[l2g];
                m_bndCondCoeffsToGlobalCoeffsMap[cnt1] = newId + n;

                if (m_signChange)
                {
                    m_bndCondCoeffsToGlobalCoeffsSign[cnt1] =
                        cgMap->GetBndCondCoeffsToGlobalCoeffsSign(i);
                }
            }
        }

        // Finally, set up global to universal maps. hack for now
        m_globalToUniversalMap = Array<OneD, int>(
            m_numGlobalCoeffs);
        m_globalToUniversalMapUnique = Array<OneD, int>(
            m_numGlobalCoeffs);
        m_globalToUniversalBndMap = Array<OneD, int>(
            m_numGlobalBndCoeffs);
        m_globalToUniversalBndMapUnique = Array<OneD, int>(
            m_numGlobalBndCoeffs);

        for (i = 0; i < cgMap->GetNumGlobalBndCoeffs(); ++i)
        {
            for (n = 0; n < nVel; ++n)
            {
                m_globalToUniversalBndMap[i*nVel + n] =
                    cgMap->GetGlobalToUniversalBndMap()[i]*nVel + n;
                m_globalToUniversalMap[i*nVel + n] =
                    cgMap->GetGlobalToUniversalBndMap()[i]*nVel + n;
            }
        }

        Array<OneD, long> tmp(m_numGlobalCoeffs);
        Vmath::Zero(m_numGlobalCoeffs, tmp, 1);
        Array<OneD, long> tmp2(m_numGlobalBndCoeffs, tmp);
        for (unsigned int i = 0; i < m_numGlobalBndCoeffs; ++i)
        {
            tmp[i] = m_globalToUniversalBndMap[i];
        }

        LibUtilities::CommSharedPtr vCommRow = m_comm->GetRowComm();
        m_gsh    = Gs::Init(tmp,  vCommRow);
        m_bndGsh = Gs::Init(tmp2, vCommRow);
        Gs::Unique(tmp, vCommRow);
        for (unsigned int i = 0; i < m_numGlobalCoeffs; ++i)
        {
            m_globalToUniversalMapUnique[i] = (tmp[i] >= 0 ? 1 : 0);
        }
        for (unsigned int i = 0; i < m_numGlobalBndCoeffs; ++i)
        {
            m_globalToUniversalBndMapUnique[i] = (tmp2[i] >= 0 ? 1 : 0);
        }

        m_hash = boost::hash_range(
            m_localToGlobalMap.begin(), m_localToGlobalMap.end());
    }
}
<|endoftext|>


<commit_before>#include "Sprite.h"
#include "PropertySetting.h"

namespace etext
{

Sprite::Sprite()
	: m_symbol(NULL)
{
	m_width = 100;
	m_height = 20;

	m_font = 0;
	m_font_size = 16;
	m_font_color.set(1, 1, 1);

	m_edge = false;
	m_edge_size = 1;
	m_edge_color.set(0, 0, 0);

	m_align_hori = HAT_LEFT;
	m_align_vert = VAT_TOP;

	m_space_hori = 1;
	m_space_vert = 1;
}

Sprite::Sprite(const Sprite& sprite)
	: ISprite(sprite)
	, m_symbol(sprite.m_symbol)
{
	m_symbol->Retain();

	m_width = sprite.m_width;
	m_height = sprite.m_height;

	m_font = sprite.m_font;
	m_font_size = sprite.m_font_size;
	m_font_color = sprite.m_font_color;

	m_edge = sprite.m_edge;
	m_edge_size = sprite.m_edge_size;
	m_edge_color = sprite.m_edge_color;

	m_align_hori = sprite.m_align_hori;
	m_align_vert = sprite.m_align_vert;

	m_space_hori = sprite.m_space_hori;
	m_space_vert = sprite.m_space_vert;
}

Sprite::Sprite(Symbol* symbol)
	: m_symbol(symbol)
{
	m_symbol->Retain();

	m_width = symbol->m_width;
	m_height = symbol->m_height;

	m_font = symbol->m_font;
	m_font_size = symbol->m_font_size;
	m_font_color = d2d::transColor(symbol->m_font_color, d2d::PT_ARGB);

	m_edge = symbol->m_edge;
	m_edge_size = symbol->m_edge_size;
	m_edge_color = d2d::transColor(symbol->m_edge_color, d2d::PT_ARGB);

	m_align_hori = symbol->m_align_hori;
	m_align_vert = symbol->m_align_vert;

	m_space_hori = symbol->m_space_hori;
	m_space_vert = symbol->m_space_vert;

	BuildBounding();
}

Sprite::~Sprite()
{
	if (m_symbol) {
		m_symbol->Release();
	}
}

Sprite* Sprite::Clone() const
{
	Sprite* sprite = new Sprite(*this);
	d2d::SpriteFactory::Instance()->insert(sprite);
	return sprite;
}

const Symbol& Sprite::GetSymbol() const
{
	return *m_symbol;
}

void Sprite::SetSymbol(d2d::ISymbol* symbol)
{
	d2d::ISprite::SetSymbol(&m_symbol, symbol);
}

void Sprite::Load(const Json::Value& val)
{
	ISprite::Load(val);

	const Json::Value& text_val = val["text"];

	m_width = text_val["width"].asInt();
	m_height = text_val["height"].asInt();

	m_font = text_val["font"].asInt();
	m_font_size = text_val["font_size"].asInt();
	m_font_color = transColor(text_val["font_color"].asString(), d2d::PT_ARGB);

	m_edge = text_val["edge"].asBool();
	m_edge_size = text_val["edge_size"].asInt();
	m_edge_color = transColor(text_val["edge_color"].asString(), d2d::PT_ARGB);

	m_align_hori = HoriAlignType(text_val["align_hori"].asInt());
	m_align_vert = VertAlignType(text_val["align_vert"].asInt());

	m_space_hori = text_val["space_hori"].asDouble();
	m_space_vert = text_val["space_vert"].asDouble();

	m_text = text_val["text"].asString();
	m_tid = text_val["tid"].asString();

	BuildBounding();
}

void Sprite::Store(Json::Value& val) const
{
	ISprite::Store(val);

	Json::Value text_val;

	text_val["width"] = m_width;
	text_val["height"] = m_height;

	text_val["font"] = m_font;
	text_val["font_size"] = m_font_size;
	text_val["font_color"] = transColor(m_font_color, d2d::PT_ARGB);

	text_val["edge"] = m_edge;
	text_val["edge_size"] = m_edge_size;
	text_val["edge_color"] = transColor(m_edge_color, d2d::PT_ARGB);

	text_val["align_hori"] = m_align_hori;
	text_val["align_vert"] = m_align_vert;

	text_val["space_hori"] = m_space_hori;
	text_val["space_vert"] = m_space_vert;

	text_val["text"] = m_text;
	text_val["tid"] = m_tid;

	val["text"] = text_val;
}

d2d::IPropertySetting* Sprite::CreatePropertySetting(d2d::EditPanelImpl* stage)
{
	return new PropertySetting(stage, this);
}

void Sprite::GetSize(int& width, int& height) const
{
	width = m_width;
	height = m_height;
}

void Sprite::SetSize(int width, int height)
{
	m_width = width;
	m_height = height;
}

void Sprite::GetAlign(int& halign, int& valign) const
{
	halign = m_align_hori;
	valign = m_align_vert;
}

void Sprite::SetAlign(int halign, int valign)
{
	m_align_hori = HoriAlignType(halign);
	m_align_vert = VertAlignType(valign);
}

void Sprite::GetSpace(float& hori, float& vert) const
{
	hori = m_space_hori;
	vert = m_space_vert;
}

void Sprite::SetSpace(float hori, float vert)
{
	m_space_hori = hori;
	m_space_vert = vert;
}

}<commit_msg>[FIXED] font color format<commit_after>#include "Sprite.h"
#include "PropertySetting.h"

namespace etext
{

Sprite::Sprite()
	: m_symbol(NULL)
{
	m_width = 100;
	m_height = 20;

	m_font = 0;
	m_font_size = 16;
	m_font_color.set(1, 1, 1);

	m_edge = false;
	m_edge_size = 1;
	m_edge_color.set(0, 0, 0);

	m_align_hori = HAT_LEFT;
	m_align_vert = VAT_TOP;

	m_space_hori = 1;
	m_space_vert = 1;
}

Sprite::Sprite(const Sprite& sprite)
	: ISprite(sprite)
	, m_symbol(sprite.m_symbol)
{
	m_symbol->Retain();

	m_width = sprite.m_width;
	m_height = sprite.m_height;

	m_font = sprite.m_font;
	m_font_size = sprite.m_font_size;
	m_font_color = sprite.m_font_color;

	m_edge = sprite.m_edge;
	m_edge_size = sprite.m_edge_size;
	m_edge_color = sprite.m_edge_color;

	m_align_hori = sprite.m_align_hori;
	m_align_vert = sprite.m_align_vert;

	m_space_hori = sprite.m_space_hori;
	m_space_vert = sprite.m_space_vert;
}

Sprite::Sprite(Symbol* symbol)
	: m_symbol(symbol)
{
	m_symbol->Retain();

	m_width = symbol->m_width;
	m_height = symbol->m_height;

	m_font = symbol->m_font;
	m_font_size = symbol->m_font_size;
	m_font_color = d2d::transColor(symbol->m_font_color, d2d::PT_RGBA);

	m_edge = symbol->m_edge;
	m_edge_size = symbol->m_edge_size;
	m_edge_color = d2d::transColor(symbol->m_edge_color, d2d::PT_RGBA);

	m_align_hori = symbol->m_align_hori;
	m_align_vert = symbol->m_align_vert;

	m_space_hori = symbol->m_space_hori;
	m_space_vert = symbol->m_space_vert;

	BuildBounding();
}

Sprite::~Sprite()
{
	if (m_symbol) {
		m_symbol->Release();
	}
}

Sprite* Sprite::Clone() const
{
	Sprite* sprite = new Sprite(*this);
	d2d::SpriteFactory::Instance()->insert(sprite);
	return sprite;
}

const Symbol& Sprite::GetSymbol() const
{
	return *m_symbol;
}

void Sprite::SetSymbol(d2d::ISymbol* symbol)
{
	d2d::ISprite::SetSymbol(&m_symbol, symbol);
}

void Sprite::Load(const Json::Value& val)
{
	ISprite::Load(val);

	const Json::Value& text_val = val["text"];

	m_width = text_val["width"].asInt();
	m_height = text_val["height"].asInt();

	m_font = text_val["font"].asInt();
	m_font_size = text_val["font_size"].asInt();
	m_font_color = transColor(text_val["font_color"].asString(), d2d::PT_RGBA);

	m_edge = text_val["edge"].asBool();
	m_edge_size = text_val["edge_size"].asInt();
	m_edge_color = transColor(text_val["edge_color"].asString(), d2d::PT_RGBA);

	m_align_hori = HoriAlignType(text_val["align_hori"].asInt());
	m_align_vert = VertAlignType(text_val["align_vert"].asInt());

	m_space_hori = text_val["space_hori"].asDouble();
	m_space_vert = text_val["space_vert"].asDouble();

	m_text = text_val["text"].asString();
	m_tid = text_val["tid"].asString();

	BuildBounding();
}

void Sprite::Store(Json::Value& val) const
{
	ISprite::Store(val);

	Json::Value text_val;

	text_val["width"] = m_width;
	text_val["height"] = m_height;

	text_val["font"] = m_font;
	text_val["font_size"] = m_font_size;
	text_val["font_color"] = transColor(m_font_color, d2d::PT_RGBA);

	text_val["edge"] = m_edge;
	text_val["edge_size"] = m_edge_size;
	text_val["edge_color"] = transColor(m_edge_color, d2d::PT_RGBA);

	text_val["align_hori"] = m_align_hori;
	text_val["align_vert"] = m_align_vert;

	text_val["space_hori"] = m_space_hori;
	text_val["space_vert"] = m_space_vert;

	text_val["text"] = m_text;
	text_val["tid"] = m_tid;

	val["text"] = text_val;
}

d2d::IPropertySetting* Sprite::CreatePropertySetting(d2d::EditPanelImpl* stage)
{
	return new PropertySetting(stage, this);
}

void Sprite::GetSize(int& width, int& height) const
{
	width = m_width;
	height = m_height;
}

void Sprite::SetSize(int width, int height)
{
	m_width = width;
	m_height = height;
}

void Sprite::GetAlign(int& halign, int& valign) const
{
	halign = m_align_hori;
	valign = m_align_vert;
}

void Sprite::SetAlign(int halign, int valign)
{
	m_align_hori = HoriAlignType(halign);
	m_align_vert = VertAlignType(valign);
}

void Sprite::GetSpace(float& hori, float& vert) const
{
	hori = m_space_hori;
	vert = m_space_vert;
}

void Sprite::SetSpace(float hori, float vert)
{
	m_space_hori = hori;
	m_space_vert = vert;
}

}<|endoftext|>


<commit_before>/**
 * Copyright (C) 2012 TVH Group NV. <kalman.tiboldi@tvh.com>
 *
 * This file is part of the tvhgooglemapi project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 		http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "stdafx.h"
#include "tvhgooglemapi.h"
#include <string>
#include <MAPI.h>
#include <stdlib.h>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <boost/algorithm/string/replace.hpp>

using namespace std;

ULONG session;
// near the top of your CPP file
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
string dllInstallationPath;

std::wstring s2ws(const std::string& s)
{
 int len;
 int slength = (int)s.length() + 1;
 len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
 wchar_t* buf = new wchar_t[len];
 MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
 std::wstring r(buf);
 delete[] buf;
 return r;
}

std::string ws2s(const std::wstring& s)
{
 int len;
 int slength = (int)s.length() + 1;
 len = WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, 0, 0, 0, 0);
 char* buf = new char[len];
 WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, buf, len, 0, 0);
 std::string r(buf);
 delete[] buf;
 return r;
}

template <class T>
std::string to_string(T t, std::ios_base & (__cdecl *f)(std::ios_base&))
{
  std::ostringstream oss;
  oss << f << t;
  return oss.str();
}

std::string getInstallationPath(){
	LPTSTR dllInstallationPath;
	// and then, anywhere you need it:
	dllInstallationPath = new TCHAR[_MAX_PATH];
	::GetModuleFileName((HINSTANCE)&__ImageBase, dllInstallationPath, _MAX_PATH);
	string dllPath = ws2s(dllInstallationPath);
	dllPath = dllPath.substr(0,dllPath.find_last_of("/\\"));
	return dllPath;
}

#define BUFSIZE 1024

int writeTempFile(wstring fileContent, string* result){

    DWORD dwRetVal = 0;
    UINT uRetVal   = 0;

    TCHAR szTempFileName[MAX_PATH];
    TCHAR lpTempPathBuffer[MAX_PATH];

     //  Gets the temp path env string (no guarantee it's a valid path).
    dwRetVal = GetTempPath(MAX_PATH,          // length of the buffer
                           lpTempPathBuffer); // buffer for path
    if (dwRetVal > MAX_PATH || (dwRetVal == 0))
    {
        return 3;
    }

    //  Generates a temporary file name.
    uRetVal = GetTempFileName(lpTempPathBuffer, // directory for tmp files
                              TEXT("tvhgooglemapi"),     // temp file name prefix
                              0,                // create unique name
                              szTempFileName);  // buffer for name
    if (uRetVal == 0)
    {
        return (3);
    }

	wofstream tempfile;

	tempfile.open(szTempFileName);
	tempfile << fileContent ;
	tempfile.close();
	*result = ws2s(szTempFileName);
	return 0;

}

BOOL WINAPI DllMain(HINSTANCE aInstance, DWORD aReason, LPVOID aReserved)
{
	if (aReason == DLL_PROCESS_ATTACH) dllInstallationPath = getInstallationPath();
	return TRUE;
}

ULONG FAR PASCAL MAPILogon(ULONG aUIParam,
	LPSTR aProfileName,
	LPSTR aPassword,
	FLAGS aFlags,
	ULONG aReserved,
	LPLHANDLE aSession)
{
	session = 7; // We completely ignore the session stuff. Filling in any number to keep the MAPIClient happy.
	*aSession = *&session;

	return SUCCESS_SUCCESS;
}

ULONG FAR PASCAL MAPILogoff (LHANDLE aSession, ULONG aUIParam,
                                            FLAGS aFlags, ULONG aReserved)
{
	return SUCCESS_SUCCESS;
}

std::wstring ToWString( const std::string& strText )
    {
      std::wstring      wstrResult;

      wstrResult.resize( strText.length() );

      typedef std::codecvt<wchar_t, char, mbstate_t> widecvt;

      std::locale     locGlob;

      std::locale::global( locGlob );

      const widecvt& cvt( std::use_facet<widecvt>( locGlob ) );

      mbstate_t   State;

      const char* cTemp;
      wchar_t*    wTemp;

      cvt.in( State,
              &strText[0], &strText[0] + strText.length(), cTemp,
              (wchar_t*)&wstrResult[0], &wstrResult[0] + wstrResult.length(), wTemp );

      return wstrResult;
}

ULONG FAR PASCAL MAPISendMail (LHANDLE lhSession, ULONG ulUIParam, lpMapiMessage lpMessage,
                FLAGS flFlags, ULONG ulReserved )
{
	ULONG exitCode = MAPI_E_FAILURE ;
   if(lpMessage->nFileCount > 0 ) {
	   wstring subject;
	   if (lpMessage->lpszSubject != NULL) {
		   subject = ToWString(lpMessage->lpszSubject);
		   //subject = L"=?utf-8?Q?" + subject + L"?=";
	   }
	   else
		   subject = L"";

	   wstring body;
	   if (lpMessage->lpszNoteText != NULL)
			body = ToWString(lpMessage->lpszNoteText);
	   else
			body = L"";
	   boost::replace_all(subject,"\\","\\\\");
	   boost::replace_all(subject,"\"","\\\"");
	   STARTUPINFOA siStartupInfo;
	   PROCESS_INFORMATION piProcessInfo;
	   memset(&siStartupInfo, 0, sizeof(siStartupInfo));
	   memset(&piProcessInfo, 0, sizeof(piProcessInfo));
	   siStartupInfo.cb = sizeof(siStartupInfo);
	   string parameters = " /C java.exe -Dfile.encoding=UTF8 -jar \"" + dllInstallationPath + "\\gmaildrafter.jar\" ";
	   for(unsigned int i = 0; i < lpMessage->nFileCount; i++) {
		   parameters = parameters + " -a \"" +  lpMessage->lpFiles[i].lpszPathName + "\"" ;
		   if (lpMessage->lpFiles[i].lpszFileName != NULL)
			  parameters = parameters +  " -n \"" + lpMessage->lpFiles[i].lpszFileName + "\""  ;
	   }

	   for (unsigned int i = 0; i < lpMessage->nRecipCount; i++) {
		   if (lpMessage->lpRecips[i].lpszName != NULL || lpMessage->lpRecips[i].lpszAddress != NULL) {
			   parameters = parameters + " -t \"";
			   if (lpMessage->lpRecips[i].lpszName != NULL)
				    parameters = parameters + lpMessage->lpRecips[i].lpszName ;
			   if (lpMessage->lpRecips[i].lpszName != NULL && lpMessage->lpRecips[i].lpszAddress != NULL)
				    parameters = parameters + " " + parameters;
			   if (lpMessage->lpRecips[i].lpszAddress != NULL)
					parameters = parameters + "<" + lpMessage->lpRecips[i].lpszAddress  + ">" ;
			   parameters = parameters + "\"";
		   }
	   }

	   string bodyfile;
	   int writeResult = writeTempFile( body ,&bodyfile);
	   if (writeResult != 0) {
		   MessageBox(NULL,L"Could not send your mail, writing bodyfile failed!",L"MAPI Error",MB_ICONERROR | MB_TOPMOST);
		   return MAPI_E_FAILURE;
	   } else
		   parameters = parameters + " -b \"" + bodyfile + "\" -d";

	   string subjectfile ;
	   writeResult = writeTempFile(subject, &subjectfile);
	   if (writeResult != 0) {
		   MessageBox(NULL,L"Could not send your mail, writing subjectfile failed!",L"MAPI Error",MB_ICONERROR | MB_TOPMOST);
		   return MAPI_E_FAILURE;
	   } else
		   parameters = parameters + " --subjectfile \"" + subjectfile + "\" --deletesubjectfile";

	   LPSTR lpparameters = (LPSTR)(parameters.c_str());
	   if( CreateProcessA(  "c:\\windows\\system32\\cmd.exe",
							lpparameters,
							0,
							0,
							false,
							CREATE_DEFAULT_ERROR_MODE  | CREATE_NO_WINDOW ,
							0,
							0,
							&siStartupInfo,
							&piProcessInfo
							) == FALSE) {
			MessageBox(NULL,L"Could not send your mail, starting gmaildrafter failed!",L"MAPI Error",MB_ICONERROR | MB_TOPMOST);
			return MAPI_E_FAILURE;
		} else {
			WaitForSingleObject(piProcessInfo.hProcess, INFINITE);
			DWORD dwExitCode = -1;
			GetExitCodeProcess( piProcessInfo.hProcess, &dwExitCode);

			if (dwExitCode != 0)  {
				if(dwExitCode == 5)
					exitCode = MAPI_E_LOGIN_FAILURE;
				else if (dwExitCode == 3 )
					exitCode = MAPI_E_USER_ABORT;
				else {
					string errormessage = "Could not send your mail, exitcode of gmaildrafter was " + to_string<DWORD>(dwExitCode, std::hex);
					if (dwExitCode == 1)
						errormessage = errormessage + "\nMost likely reasons are that java is not installed, older than 1.7 or not in the WINDOWS PATH variable.";
					MessageBox(NULL,s2ws(errormessage).c_str(),L"MAPI Error",MB_ICONERROR | MB_TOPMOST);
					exitCode = MAPI_E_FAILURE;
				}
			} else
				exitCode = SUCCESS_SUCCESS;
		}

   }

	return exitCode ;
}

LONG FAR PASCAL MAPISendMailHelper (LHANDLE lhSession, ULONG ulUIParam, LHANDLE *lpMessage,
                FLAGS flFlags, ULONG ulReserved )
{

   MessageBox(NULL,L"Your application is using mapisendmailHelper, we don't support that!",L"MAPI tracing",NULL);
	return MAPI_E_NOT_SUPPORTED ;
}

ULONG FAR PASCAL MAPISendDocuments(ULONG ulUIParam, LPTSTR lpszDelimChar, LPTSTR lpszFilePaths,
                                LPTSTR lpszFileNames, ULONG ulReserved)
{
	MessageBox(NULL,L"Your application is using mapisenddocuments, we don't support that!",L"MAPI tracing",MB_ICONERROR);
    return MAPI_E_NOT_SUPPORTED ;
}

ULONG FAR PASCAL MAPIFindNext(LHANDLE lhSession, ULONG ulUIParam, LPTSTR lpszMessageType,
                              LPTSTR lpszSeedMessageID, FLAGS flFlags, ULONG ulReserved,
                              unsigned char lpszMessageID[64])
{
	MessageBox(NULL,L"Your application called MAPIFindNext, we don't support that!",L"MAPI tracing",MB_ICONERROR);
  return MAPI_E_NOT_SUPPORTED ;
}

ULONG FAR PASCAL MAPIReadMail(LHANDLE lhSession, ULONG ulUIParam, LPTSTR lpszMessageID,
                              FLAGS flFlags, ULONG ulReserved, LHANDLE **lppMessage)
{
	MessageBox(NULL,L"Your application called mapireadmail, we don't support that!",L"MAPI tracing",MB_ICONERROR);
 return MAPI_E_NOT_SUPPORTED ;

}

ULONG FAR PASCAL MAPISaveMail(LHANDLE lhSession, ULONG ulUIParam, LHANDLE lpMessage,
                              FLAGS flFlags, ULONG ulReserved, LPTSTR lpszMessageID)
{
	MessageBox(NULL,L"Your application called mapisavemail, we don't support that!",L"MAPI tracing",MB_ICONERROR);
  return MAPI_E_NOT_SUPPORTED ;
}

ULONG FAR PASCAL MAPIDeleteMail(LHANDLE lhSession, ULONG ulUIParam, LPTSTR lpszMessageID,
                                FLAGS flFlags, ULONG ulReserved)
{
	MessageBox(NULL,L"Your application called mapideletemail, we haven't implemented that!",L"MAPI tracing",MB_ICONERROR);
  return MAPI_E_NOT_SUPPORTED ;
}

ULONG FAR PASCAL MAPIAddress(LHANDLE lhSession, ULONG ulUIParam, LPTSTR lpszCaption,
                             ULONG nEditFields, LPTSTR lpszLabels, ULONG nRecips,
                             lpMapiRecipDesc lpRecips, FLAGS flFlags,
                             ULONG ulReserved, LPULONG lpnNewRecips,
                             lpMapiRecipDesc FAR *lppNewRecips)
{
	MessageBox(NULL,L"Your application called mapiaddress, we haven't implemented that!",L"MAPI tracing",MB_ICONERROR);
    return MAPI_E_NOT_SUPPORTED;
}

ULONG FAR PASCAL MAPIDetails(LHANDLE lhSession, ULONG ulUIParam, lpMapiRecipDesc lpRecip,
                             FLAGS flFlags, ULONG ulReserved)
{
	MessageBox(NULL,L"Your application called mapidetails, we haven't implemented that!",L"MAPI tracing",MB_ICONERROR);
    return MAPI_E_NOT_SUPPORTED;
}

ULONG FAR PASCAL MAPIResolveName(LHANDLE lhSession, ULONG ulUIParam, LPTSTR lpszName,
                                 FLAGS flFlags, ULONG ulReserved, lpMapiRecipDesc FAR *lppRecip)
{
  MessageBox(NULL,L"Your application called mapiresolvename, we haven't implemented that!",L"MAPI tracing",MB_ICONERROR);
  return MAPI_E_NOT_SUPPORTED;
}

ULONG FAR PASCAL MAPIFreeBuffer(LPVOID pv)
{
  MessageBox(NULL,L"Your application called MAPIFreeBuffer, we haven't implemented that!",L"MAPI tracing",MB_ICONERROR);
  pv = NULL;
  return SUCCESS_SUCCESS;
}

<commit_msg>- implement mapiresolvename - fix a bug if both address and name are provided, the parameters were appended to themselves where only a space should have been appended<commit_after>/**
 * Copyright (C) 2012 TVH Group NV. <kalman.tiboldi@tvh.com>
 *
 * This file is part of the tvhgooglemapi project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 		http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "stdafx.h"
#include "tvhgooglemapi.h"
#include <string>
#include <MAPI.h>
#include <stdlib.h>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <boost/algorithm/string/replace.hpp>

using namespace std;

ULONG session;
// near the top of your CPP file
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
string dllInstallationPath;

std::wstring s2ws(const std::string& s)
{
 int len;
 int slength = (int)s.length() + 1;
 len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
 wchar_t* buf = new wchar_t[len];
 MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
 std::wstring r(buf);
 delete[] buf;
 return r;
}

std::string ws2s(const std::wstring& s)
{
 int len;
 int slength = (int)s.length() + 1;
 len = WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, 0, 0, 0, 0);
 char* buf = new char[len];
 WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, buf, len, 0, 0);
 std::string r(buf);
 delete[] buf;
 return r;
}

template <class T>
std::string to_string(T t, std::ios_base & (__cdecl *f)(std::ios_base&))
{
  std::ostringstream oss;
  oss << f << t;
  return oss.str();
}

std::string getInstallationPath(){
	LPTSTR dllInstallationPath;
	// and then, anywhere you need it:
	dllInstallationPath = new TCHAR[_MAX_PATH];
	::GetModuleFileName((HINSTANCE)&__ImageBase, dllInstallationPath, _MAX_PATH);
	string dllPath = ws2s(dllInstallationPath);
	dllPath = dllPath.substr(0,dllPath.find_last_of("/\\"));
	return dllPath;
}

#define BUFSIZE 1024

int writeTempFile(wstring fileContent, string* result){

    DWORD dwRetVal = 0;
    UINT uRetVal   = 0;

    TCHAR szTempFileName[MAX_PATH];
    TCHAR lpTempPathBuffer[MAX_PATH];

     //  Gets the temp path env string (no guarantee it's a valid path).
    dwRetVal = GetTempPath(MAX_PATH,          // length of the buffer
                           lpTempPathBuffer); // buffer for path
    if (dwRetVal > MAX_PATH || (dwRetVal == 0))
    {
        return 3;
    }

    //  Generates a temporary file name.
    uRetVal = GetTempFileName(lpTempPathBuffer, // directory for tmp files
                              TEXT("tvhgooglemapi"),     // temp file name prefix
                              0,                // create unique name
                              szTempFileName);  // buffer for name
    if (uRetVal == 0)
    {
        return (3);
    }

	wofstream tempfile;

	tempfile.open(szTempFileName);
	tempfile << fileContent ;
	tempfile.close();
	*result = ws2s(szTempFileName);
	return 0;

}

bool fexists(const char *filename)
{
  ifstream ifile(filename);
  return ifile;
}

BOOL WINAPI DllMain(HINSTANCE aInstance, DWORD aReason, LPVOID aReserved)
{
	if (aReason == DLL_PROCESS_ATTACH) dllInstallationPath = getInstallationPath();
	return TRUE;
}

ULONG FAR PASCAL MAPILogon(ULONG aUIParam,
	LPSTR aProfileName,
	LPSTR aPassword,
	FLAGS aFlags,
	ULONG aReserved,
	LPLHANDLE aSession)
{
	session = 7; // We completely ignore the session stuff. Filling in any number to keep the MAPIClient happy.
	*aSession = *&session;

	return SUCCESS_SUCCESS;
}

ULONG FAR PASCAL MAPILogoff (LHANDLE aSession, ULONG aUIParam,
                                            FLAGS aFlags, ULONG aReserved)
{
	return SUCCESS_SUCCESS;
}

std::wstring ToWString( const std::string& strText )
    {
      std::wstring      wstrResult;

      wstrResult.resize( strText.length() );

      typedef std::codecvt<wchar_t, char, mbstate_t> widecvt;

      std::locale     locGlob;

      std::locale::global( locGlob );

      const widecvt& cvt( std::use_facet<widecvt>( locGlob ) );

      mbstate_t   State;

      const char* cTemp;
      wchar_t*    wTemp;

      cvt.in( State,
              &strText[0], &strText[0] + strText.length(), cTemp,
              (wchar_t*)&wstrResult[0], &wstrResult[0] + wstrResult.length(), wTemp );

      return wstrResult;
}

ULONG FAR PASCAL MAPISendMail (LHANDLE lhSession, ULONG ulUIParam, lpMapiMessage lpMessage,
                FLAGS flFlags, ULONG ulReserved )
{
	ULONG exitCode = MAPI_E_FAILURE ;
   if(lpMessage->nFileCount > 0 ) {
	   wstring subject;
	   if (lpMessage->lpszSubject != NULL) {
		   subject = ToWString(lpMessage->lpszSubject);
		   //subject = L"=?utf-8?Q?" + subject + L"?=";
	   }
	   else
		   subject = L"";

	   wstring body;
	   if (lpMessage->lpszNoteText != NULL)
			body = ToWString(lpMessage->lpszNoteText);
	   else
			body = L"";
	   boost::replace_all(subject,"\\","\\\\");
	   boost::replace_all(subject,"\"","\\\"");
	   STARTUPINFOA siStartupInfo;
	   PROCESS_INFORMATION piProcessInfo;
	   memset(&siStartupInfo, 0, sizeof(siStartupInfo));
	   memset(&piProcessInfo, 0, sizeof(piProcessInfo));
	   siStartupInfo.cb = sizeof(siStartupInfo);
	   string parameters = " /C java.exe -Dfile.encoding=UTF8 -jar \"" ;
	   parameters.append( dllInstallationPath);
	   parameters.append("\\gmaildrafter.jar\" ");
	   for(unsigned int i = 0; i < lpMessage->nFileCount; i++) {
		   parameters.append(" -a \"");
		   parameters.append(lpMessage->lpFiles[i].lpszPathName);
		   parameters.append("\"");
		   if (lpMessage->lpFiles[i].lpszFileName != NULL) {
			   parameters.append(" -n \"");
			   parameters.append(lpMessage->lpFiles[i].lpszFileName);
			   parameters.append("\"" );
		   }
	   }

	   for (unsigned int i = 0; i < lpMessage->nRecipCount; i++) {
		   if (lpMessage->lpRecips[i].lpszName != NULL || lpMessage->lpRecips[i].lpszAddress != NULL) {
			   parameters.append(" -t \"");

			   if (lpMessage->lpRecips[i].lpszName != NULL)
				   parameters.append(lpMessage->lpRecips[i].lpszName );
			   if (lpMessage->lpRecips[i].lpszName != NULL && lpMessage->lpRecips[i].lpszAddress != NULL)
				   parameters.append(" ");
			   if (lpMessage->lpRecips[i].lpszAddress != NULL){
				   parameters.append("<");
				   parameters.append(lpMessage->lpRecips[i].lpszAddress);
				   parameters.append(">");
			   }
			   parameters.append("\"");
		   }
	   }

	   string bodyfile;
	   int writeResult = writeTempFile( body ,&bodyfile);
	   if (writeResult != 0) {
		   MessageBox(NULL,L"Could not send your mail, writing bodyfile failed!",L"MAPI Error",MB_ICONERROR | MB_TOPMOST);
		   return MAPI_E_FAILURE;
	   } else
		   parameters = parameters + " -b \"" + bodyfile + "\" -d";

	   string subjectfile ;
	   writeResult = writeTempFile(subject, &subjectfile);
	   if (writeResult != 0) {
		   MessageBox(NULL,L"Could not send your mail, writing subjectfile failed!",L"MAPI Error",MB_ICONERROR | MB_TOPMOST);
		   return MAPI_E_FAILURE;
	   } else
		   parameters = parameters + " --subjectfile \"" + subjectfile + "\" --deletesubjectfile";

	   LPSTR lpparameters = (LPSTR)(parameters.c_str());
	   if (fexists("c:\\windows\\temp\\debuggmaildrafter.txt")){
		    wofstream tempfile;
			tempfile.open("c:\\windows\\temp\\debuggmaildrafter.txt",ios::app);
			tempfile << "c:\\windows\\system32\\cmd.exe ";
			tempfile << lpparameters;
			tempfile << "\n";
			tempfile.close();
			MessageBox(NULL,L"Going to execute the last command in c:\\windows\\temp\\debuggmaildrafter.txt.",L"MAPI Debugging",MB_ICONERROR | MB_TOPMOST);
	   }

	   if( CreateProcessA(  "c:\\windows\\system32\\cmd.exe",
							lpparameters,
							0,
							0,
							false,
							CREATE_DEFAULT_ERROR_MODE  | CREATE_NO_WINDOW ,
							0,
							0,
							&siStartupInfo,
							&piProcessInfo
							) == FALSE) {
			MessageBox(NULL,L"Could not send your mail, starting gmaildrafter failed!",L"MAPI Error",MB_ICONERROR | MB_TOPMOST);
			return MAPI_E_FAILURE;
		} else {
			WaitForSingleObject(piProcessInfo.hProcess, INFINITE);
			DWORD dwExitCode = -1;
			GetExitCodeProcess( piProcessInfo.hProcess, &dwExitCode);

			if (dwExitCode != 0)  {
				if(dwExitCode == 5)
					exitCode = MAPI_E_LOGIN_FAILURE;
				else if (dwExitCode == 3 )
					exitCode = MAPI_E_USER_ABORT;
				else {
					string errormessage = "Could not send your mail, exitcode of gmaildrafter was " + to_string<DWORD>(dwExitCode, std::hex);
					if (dwExitCode == 1)
						errormessage = errormessage + "\nMost likely reasons are that java is not installed, older than 1.7 or not in the WINDOWS PATH variable.";
					MessageBox(NULL,s2ws(errormessage).c_str(),L"MAPI Error",MB_ICONERROR | MB_TOPMOST);
					exitCode = MAPI_E_FAILURE;
				}
			} else
				exitCode = SUCCESS_SUCCESS;
		}

   }

	return exitCode ;
}

LONG FAR PASCAL MAPISendMailHelper (LHANDLE lhSession, ULONG ulUIParam, LHANDLE *lpMessage,
                FLAGS flFlags, ULONG ulReserved )
{

   MessageBox(NULL,L"Your application is using mapisendmailHelper, we don't support that!",L"MAPI tracing",NULL);
	return MAPI_E_NOT_SUPPORTED ;
}

ULONG FAR PASCAL MAPISendDocuments(ULONG ulUIParam, LPTSTR lpszDelimChar, LPTSTR lpszFilePaths,
                                LPTSTR lpszFileNames, ULONG ulReserved)
{
	MessageBox(NULL,L"Your application is using mapisenddocuments, we don't support that!",L"MAPI tracing",MB_ICONERROR);
    return MAPI_E_NOT_SUPPORTED ;
}

ULONG FAR PASCAL MAPIFindNext(LHANDLE lhSession, ULONG ulUIParam, LPTSTR lpszMessageType,
                              LPTSTR lpszSeedMessageID, FLAGS flFlags, ULONG ulReserved,
                              unsigned char lpszMessageID[64])
{
	MessageBox(NULL,L"Your application called MAPIFindNext, we don't support that!",L"MAPI tracing",MB_ICONERROR);
  return MAPI_E_NOT_SUPPORTED ;
}

ULONG FAR PASCAL MAPIReadMail(LHANDLE lhSession, ULONG ulUIParam, LPTSTR lpszMessageID,
                              FLAGS flFlags, ULONG ulReserved, LHANDLE **lppMessage)
{
	MessageBox(NULL,L"Your application called mapireadmail, we don't support that!",L"MAPI tracing",MB_ICONERROR);
 return MAPI_E_NOT_SUPPORTED ;

}

ULONG FAR PASCAL MAPISaveMail(LHANDLE lhSession, ULONG ulUIParam, LHANDLE lpMessage,
                              FLAGS flFlags, ULONG ulReserved, LPTSTR lpszMessageID)
{
	MessageBox(NULL,L"Your application called mapisavemail, we don't support that!",L"MAPI tracing",MB_ICONERROR);
  return MAPI_E_NOT_SUPPORTED ;
}

ULONG FAR PASCAL MAPIDeleteMail(LHANDLE lhSession, ULONG ulUIParam, LPTSTR lpszMessageID,
                                FLAGS flFlags, ULONG ulReserved)
{
	MessageBox(NULL,L"Your application called mapideletemail, we haven't implemented that!",L"MAPI tracing",MB_ICONERROR);
  return MAPI_E_NOT_SUPPORTED ;
}

ULONG FAR PASCAL MAPIAddress(LHANDLE lhSession, ULONG ulUIParam, LPTSTR lpszCaption,
                             ULONG nEditFields, LPTSTR lpszLabels, ULONG nRecips,
                             lpMapiRecipDesc lpRecips, FLAGS flFlags,
                             ULONG ulReserved, LPULONG lpnNewRecips,
                             lpMapiRecipDesc FAR *lppNewRecips)
{
	MessageBox(NULL,L"Your application called mapiaddress, we haven't implemented that!",L"MAPI tracing",MB_ICONERROR);
    return MAPI_E_NOT_SUPPORTED;
}

ULONG FAR PASCAL MAPIDetails(LHANDLE lhSession, ULONG ulUIParam, lpMapiRecipDesc lpRecip,
                             FLAGS flFlags, ULONG ulReserved)
{
	MessageBox(NULL,L"Your application called mapidetails, we haven't implemented that!",L"MAPI tracing",MB_ICONERROR);
    return MAPI_E_NOT_SUPPORTED;
}

ULONG FAR PASCAL MAPIResolveName(LHANDLE lhSession, ULONG ulUIParam, LPSTR lpszName,
                                 FLAGS flFlags, ULONG ulReserved,  lpMapiRecipDesc FAR *lppRecip)
{
	*lppRecip = new MapiRecipDesc();
	(*lppRecip)->lpszName = lpszName;
	(*lppRecip)->lpszAddress = lpszName;
	return SUCCESS_SUCCESS;
}

ULONG FAR PASCAL MAPIFreeBuffer(LPVOID pv)
{

	delete pv;
	pv = NULL;
    return SUCCESS_SUCCESS;
}

<|endoftext|>


<commit_before>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2006-2007 Torsten Rahn <tackat@kde.org>"
// Copyright 2007      Inge Wallin  <ingwa@kde.org>"
//

// Own
#include "KdeMainWindow.h"

// Qt
#include <QtGui/QProgressBar>

// KDE
#include <kaction.h>
#include <kactioncollection.h>
#include <kstatusbar.h>
#include <kparts/part.h>
#include <kparts/componentfactory.h>

#include <QtCore/QDebug>

// GeoData
#include <GeoSceneDocument.h>
#include <GeoSceneHead.h>

// Local dir
#include "ControlView.h"
#include "HttpDownloadManager.h"
#include "MarbleMap.h"
#include "MarbleModel.h"
#include "marble_part.h"

namespace Marble
{

MainWindow::MainWindow( const QString& marbleDataPath, QWidget *parent )
    : KXmlGuiWindow( parent )
{
    m_part = new MarblePart( this, this, QStringList() << marbleDataPath );

    setCentralWidget( m_part->widget() );

    insertChildClient( m_part );

    setXMLFile( "marbleui.rc" );

    setStandardToolBarMenuEnabled( true );

    createGUI( 0 );

    m_part->createInfoBoxesMenu();

    setAutoSaveSettings();

    connect( marbleWidget(), SIGNAL( themeChanged( QString ) ),
	     this, SLOT( setMapTitle() ) );
    initStatusBar();
}

MainWindow::~MainWindow()
{
    delete m_part;
}

void MainWindow::initStatusBar()
{
    initDownloadProgressBar();
}

void MainWindow::initDownloadProgressBar()
{
    // get status bar and add progress widget
    KStatusBar * const status_bar = statusBar();
    qDebug() << "got status bar:" << status_bar;
    m_downloadProgressBar = new QProgressBar;
    status_bar->addPermanentWidget( m_downloadProgressBar );

    HttpDownloadManager * const downloadManager =
        m_part->controlView()->marbleWidget()->map()->model()->downloadManager();
    qDebug() << "got download manager:" << downloadManager;

    connect( downloadManager, SIGNAL( jobAdded( int )),
             this, SLOT( downloadProgressJobAdded( int )));
    connect( downloadManager, SIGNAL( downloadComplete( QString, QString )),
             this, SLOT( downloadProgressJobCompleted( QString, QString )));
}

QProgressBar* MainWindow::downloadProgressBar() const
{
    return m_downloadProgressBar;
}

void MainWindow::downloadProgressJobAdded( int totalJobs )
{
    if ( m_downloadProgressBar->value() < 0 ) {
        m_downloadProgressBar->setMaximum( 1 );
        m_downloadProgressBar->setValue( 0 );
    } else {
        m_downloadProgressBar->setMaximum( m_downloadProgressBar->maximum() + 1 );
    }
    qDebug() << "downloadProgressJobAdded: value/maximum: "
             << m_downloadProgressBar->value() << '/' << m_downloadProgressBar->maximum();
}

void MainWindow::downloadProgressJobCompleted( QString, QString )
{
    m_downloadProgressBar->setValue( m_downloadProgressBar->value() + 1 );
    if ( m_downloadProgressBar->value() == m_downloadProgressBar->maximum() )
        m_downloadProgressBar->reset();

    qDebug() << "downloadProgressJobCompleted: value/maximum: "
             << m_downloadProgressBar->value() << '/' << m_downloadProgressBar->maximum();
}

ControlView* MainWindow::marbleControl() const
{
    return m_part->controlView();
}

MarbleWidget* MainWindow::marbleWidget() const
{
    return m_part->controlView()->marbleWidget();
}

void MainWindow::setMapTitle()
{
    GeoSceneDocument *mapTheme = marbleWidget()->mapTheme();
    if ( mapTheme ) {
        setCaption( tr( mapTheme->head()->name().toLatin1() ) );
    }
}

}

#include "KdeMainWindow.moc"
<commit_msg>disable this for now.<commit_after>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2006-2007 Torsten Rahn <tackat@kde.org>"
// Copyright 2007      Inge Wallin  <ingwa@kde.org>"
//

// Own
#include "KdeMainWindow.h"

// Qt
#include <QtGui/QProgressBar>

// KDE
#include <kaction.h>
#include <kactioncollection.h>
#include <kstatusbar.h>
#include <kparts/part.h>
#include <kparts/componentfactory.h>

#include <QtCore/QDebug>

// GeoData
#include <GeoSceneDocument.h>
#include <GeoSceneHead.h>

// Local dir
#include "ControlView.h"
#include "HttpDownloadManager.h"
#include "MarbleMap.h"
#include "MarbleModel.h"
#include "marble_part.h"

namespace Marble
{

MainWindow::MainWindow( const QString& marbleDataPath, QWidget *parent )
    : KXmlGuiWindow( parent )
{
    m_part = new MarblePart( this, this, QStringList() << marbleDataPath );

    setCentralWidget( m_part->widget() );

    insertChildClient( m_part );

    setXMLFile( "marbleui.rc" );

    setStandardToolBarMenuEnabled( true );

    createGUI( 0 );

    m_part->createInfoBoxesMenu();

    setAutoSaveSettings();

    connect( marbleWidget(), SIGNAL( themeChanged( QString ) ),
	     this, SLOT( setMapTitle() ) );
    initStatusBar();
}

MainWindow::~MainWindow()
{
    delete m_part;
}

void MainWindow::initStatusBar()
{
    initDownloadProgressBar();
}

void MainWindow::initDownloadProgressBar()
{
    // get status bar and add progress widget
    KStatusBar * const status_bar = statusBar();
    qDebug() << "got status bar:" << status_bar;
    m_downloadProgressBar = new QProgressBar;
    status_bar->addPermanentWidget( m_downloadProgressBar );

    HttpDownloadManager * const downloadManager =
        m_part->controlView()->marbleWidget()->map()->model()->downloadManager();
    qDebug() << "got download manager:" << downloadManager;

    connect( downloadManager, SIGNAL( jobAdded( int )),
             this, SLOT( downloadProgressJobAdded( int )));
    connect( downloadManager, SIGNAL( downloadComplete( QString, QString )),
             this, SLOT( downloadProgressJobCompleted( QString, QString )));
}

QProgressBar* MainWindow::downloadProgressBar() const
{
    return m_downloadProgressBar;
}

void MainWindow::downloadProgressJobAdded( int totalJobs )
{
/*    if ( m_downloadProgressBar->value() < 0 ) {
        m_downloadProgressBar->setMaximum( 1 );
        m_downloadProgressBar->setValue( 0 );
    } else {
        m_downloadProgressBar->setMaximum( m_downloadProgressBar->maximum() + 1 );
    }
    qDebug() << "downloadProgressJobAdded: value/maximum: "
             << m_downloadProgressBar->value() << '/' << m_downloadProgressBar->maximum();*/
}

void MainWindow::downloadProgressJobCompleted( QString, QString )
{
    m_downloadProgressBar->setValue( m_downloadProgressBar->value() + 1 );
    if ( m_downloadProgressBar->value() == m_downloadProgressBar->maximum() )
        m_downloadProgressBar->reset();

    qDebug() << "downloadProgressJobCompleted: value/maximum: "
             << m_downloadProgressBar->value() << '/' << m_downloadProgressBar->maximum();
}

ControlView* MainWindow::marbleControl() const
{
    return m_part->controlView();
}

MarbleWidget* MainWindow::marbleWidget() const
{
    return m_part->controlView()->marbleWidget();
}

void MainWindow::setMapTitle()
{
    GeoSceneDocument *mapTheme = marbleWidget()->mapTheme();
    if ( mapTheme ) {
        setCaption( tr( mapTheme->head()->name().toLatin1() ) );
    }
}

}

#include "KdeMainWindow.moc"
<|endoftext|>