<commit_before>#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <set>
#include <string>
#include <sstream>

#include <cmath>

#include "filtrations/Data.hh"

#include "geometry/RipsExpander.hh"

#include "persistentHomology/ConnectedComponents.hh"

#include "topology/CliqueGraph.hh"
#include "topology/ConnectedComponents.hh"
#include "topology/Simplex.hh"
#include "topology/SimplicialComplex.hh"

#include "topology/io/EdgeLists.hh"
#include "topology/io/GML.hh"

#include "utilities/Filesystem.hh"

using DataType           = double;
using VertexType         = unsigned;
using Simplex            = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex  = aleph::topology::SimplicialComplex<Simplex>;

template <class Simplex> std::string formatSimplex( const Simplex& s )
{
  std::ostringstream stream;
  stream << "[";

  for( auto it = s.begin(); it != s.end(); ++it )
  {
    if( it != s.begin() )
      stream << ",";
    stream << *it;
  }

  stream << "]";

  return stream.str();
}

void usage()
{
  std::cerr << "Usage: clique_communities FILE THRESHOLD K\n"
            << "\n"
            << "Extracts clique communities from FILE, which is supposed to be\n"
            << "a weighted graph. In the subsequent calculation, an edge whose\n"
            << "weight is larger than THRESHOLD will be ignored. K denotes the\n"
            << "maximum dimension of a simplex for the clique graph extraction\n"
            << "and the clique community calculation. This does not correspond\n"
            << "to the dimensionality of the clique. Hence, a parameter of K=2\n"
            << "will result in calculating 3-clique communities because all of\n"
            << "the 2-simplices have 3 vertices.\n\n";
}

int main( int argc, char** argv )
{
  if( argc <= 3 )
  {
    usage();
    return -1;
  }

  std::string filename = argv[1];
  double threshold     = std::stod( argv[2] );
  unsigned maxK        = static_cast<unsigned>( std::stoul( argv[3] ) );

  SimplicialComplex K;

  // Input -------------------------------------------------------------
  //
  // TODO: This is copied from the clique persistence diagram
  // calculation. It would make sense to share some functions
  // between the two applications.

  std::cerr << "* Reading '" << filename << "'...";

  if( aleph::utilities::extension( filename ) == ".gml" )
  {
    aleph::topology::io::GMLReader reader;
    reader( filename, K );
  }
  else
  {
    aleph::io::EdgeListReader reader;
    reader.setReadWeights( true );
    reader.setTrimLines( true );

    reader( filename, K );
  }

  std::cerr << "finished\n";

  // Thresholding ------------------------------------------------------

  {
    std::cerr << "* Filtering input data to threshold epsilon=" << threshold << "...";

    std::vector<Simplex> simplices;

    std::remove_copy_if( K.begin(), K.end(), std::back_inserter( simplices ),
                         [&threshold] ( const Simplex& s )
                         {
                           return s.data() > threshold;
                         } );

    K = SimplicialComplex( simplices.begin(), simplices.end() );

    std::cerr << "finished\n";
  }

  // Expansion ---------------------------------------------------------

  aleph::geometry::RipsExpander<SimplicialComplex> ripsExpander;
  K = ripsExpander( K, maxK );
  K = ripsExpander.assignMaximumWeight( K );

  K.sort( aleph::filtrations::Data<Simplex>() );

  for( unsigned k = 1; k <= maxK; k++ )
  {
    std::cerr << "* Extracting " << k << "-cliques graph...";

    auto C
        = aleph::topology::getCliqueGraph( K, k );

    C.sort( aleph::filtrations::Data<Simplex>() );

    std::cerr << "finished\n";

    std::cerr << "* " << k << "-cliques graph has " << C.size() << " simplices\n";

    auto uf = aleph::topology::calculateConnectedComponents( C );

    std::set<VertexType> roots;
    uf.roots( std::inserter( roots, roots.begin() ) );

    std::cerr << "* " << k << "-cliques graph has " << roots.size() << " connected components\n";

    std::cout << "{\n"
              << "  \"" << threshold << "\":\n"
              << "  {\n"
              << "     \"" << k << "\": ";

    for( auto&& root : roots )
    {
      // The vertex IDs stored in the Union--Find data structure
      // correspond to the indices of the simplicial complex. It
      // thus suffices to map them back.
      std::set<VertexType> vertices;
      uf.get( root, std::inserter( vertices, vertices.begin() ) );

      std::vector<Simplex> simplices;

      std::transform( vertices.begin(), vertices.end(), std::back_inserter( simplices ),
                      [&K] ( VertexType v )
                      {
                        return K.at(v);
                      } );

      std::sort( simplices.begin(), simplices.end() );

      std::cout << "[";

      for( auto it = simplices.begin(); it != simplices.end(); ++it )
      {
        if( it != simplices.begin() )
          std::cout << ",";

        std::cout << formatSimplex( *it );
      }

      std::cout << "]\n";
    }

    std::cout << "  }\n";
  }

  std::cout << "}\n";
}
<commit_msg>Fixed JSON output<commit_after>#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <set>
#include <string>
#include <sstream>

#include <cmath>

#include "filtrations/Data.hh"

#include "geometry/RipsExpander.hh"

#include "persistentHomology/ConnectedComponents.hh"

#include "topology/CliqueGraph.hh"
#include "topology/ConnectedComponents.hh"
#include "topology/Simplex.hh"
#include "topology/SimplicialComplex.hh"

#include "topology/io/EdgeLists.hh"
#include "topology/io/GML.hh"

#include "utilities/Filesystem.hh"

using DataType           = double;
using VertexType         = unsigned;
using Simplex            = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex  = aleph::topology::SimplicialComplex<Simplex>;

template <class Simplex> std::string formatSimplex( const Simplex& s )
{
  std::ostringstream stream;
  stream << "[";

  for( auto it = s.begin(); it != s.end(); ++it )
  {
    if( it != s.begin() )
      stream << ",";
    stream << *it;
  }

  stream << "]";

  return stream.str();
}

void usage()
{
  std::cerr << "Usage: clique_communities FILE THRESHOLD K\n"
            << "\n"
            << "Extracts clique communities from FILE, which is supposed to be\n"
            << "a weighted graph. In the subsequent calculation, an edge whose\n"
            << "weight is larger than THRESHOLD will be ignored. K denotes the\n"
            << "maximum dimension of a simplex for the clique graph extraction\n"
            << "and the clique community calculation. This does not correspond\n"
            << "to the dimensionality of the clique. Hence, a parameter of K=2\n"
            << "will result in calculating 3-clique communities because all of\n"
            << "the 2-simplices have 3 vertices.\n\n";
}

int main( int argc, char** argv )
{
  if( argc <= 3 )
  {
    usage();
    return -1;
  }

  std::string filename = argv[1];
  double threshold     = std::stod( argv[2] );
  unsigned maxK        = static_cast<unsigned>( std::stoul( argv[3] ) );

  SimplicialComplex K;

  // Input -------------------------------------------------------------
  //
  // TODO: This is copied from the clique persistence diagram
  // calculation. It would make sense to share some functions
  // between the two applications.

  std::cerr << "* Reading '" << filename << "'...";

  if( aleph::utilities::extension( filename ) == ".gml" )
  {
    aleph::topology::io::GMLReader reader;
    reader( filename, K );
  }
  else
  {
    aleph::io::EdgeListReader reader;
    reader.setReadWeights( true );
    reader.setTrimLines( true );

    reader( filename, K );
  }

  std::cerr << "finished\n";

  // Thresholding ------------------------------------------------------

  {
    std::cerr << "* Filtering input data to threshold epsilon=" << threshold << "...";

    std::vector<Simplex> simplices;

    std::remove_copy_if( K.begin(), K.end(), std::back_inserter( simplices ),
                         [&threshold] ( const Simplex& s )
                         {
                           return s.data() > threshold;
                         } );

    K = SimplicialComplex( simplices.begin(), simplices.end() );

    std::cerr << "finished\n";
  }

  // Expansion ---------------------------------------------------------

  aleph::geometry::RipsExpander<SimplicialComplex> ripsExpander;
  K = ripsExpander( K, maxK );
  K = ripsExpander.assignMaximumWeight( K );

  K.sort( aleph::filtrations::Data<Simplex>() );

  std::cout << "{\n"
            << "  \"" << threshold << "\": {\n";

  for( unsigned k = 1; k <= maxK; k++ )
  {
    std::cerr << "* Extracting " << k << "-cliques graph...";

    auto C
        = aleph::topology::getCliqueGraph( K, k );

    C.sort( aleph::filtrations::Data<Simplex>() );

    std::cerr << "finished\n";

    std::cerr << "* " << k << "-cliques graph has " << C.size() << " simplices\n";

    auto uf = aleph::topology::calculateConnectedComponents( C );

    std::set<VertexType> roots;
    uf.roots( std::inserter( roots, roots.begin() ) );

    std::cerr << "* " << k << "-cliques graph has " << roots.size() << " connected components\n";

    std::cout << "    \"" << (k+1) << "\": [\n";

    for( auto&& root : roots )
    {
      // The vertex IDs stored in the Union--Find data structure
      // correspond to the indices of the simplicial complex. It
      // thus suffices to map them back.
      std::set<VertexType> vertices;
      uf.get( root, std::inserter( vertices, vertices.begin() ) );

      std::vector<Simplex> simplices;

      std::transform( vertices.begin(), vertices.end(), std::back_inserter( simplices ),
                      [&K] ( VertexType v )
                      {
                        return K.at(v);
                      } );

      std::sort( simplices.begin(), simplices.end() );

      std::cout << "            [";

      for( auto it = simplices.begin(); it != simplices.end(); ++it )
      {
        if( it != simplices.begin() )
          std::cout << ",";

        std::cout << formatSimplex( *it );
      }

      std::cout << "            ]";

      if( root != *roots.rbegin() )
        std::cout << ",";

      std::cout << "\n";
    }

    std::cout << "    ]";

    if( k < maxK )
      std::cout << "  ,";

    std::cout << "\n";
  }

  std::cout << "  }\n"
            << "}\n";
}
<|endoftext|>


<commit_before>#include "DrawUtility.h"

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <iostream>
#include <stdexcept>

using namespace std;
using namespace cv;

static Scalar drawColor = Scalar(0, 255, 0, 1);
static float pi = 3.14159265358979323846;

void DrawUtility::DrawMatches(std::vector<bool> mask, std::vector<std::vector<cv::DMatch>> matches, cv::Mat queryImage, std::vector<cv::KeyPoint> queryKeyPoints, cv::Mat trainImage, std::vector<cv::KeyPoint> trainKeyPoints)
{
	if (mask.size() == matches.size() && mask.size() == queryKeyPoints.size())
	{
		//if image is GrayScale image  then convert to rgb image
		if (queryImage.channels() != 3)	//color Image
		{
			cv::Mat queryImageRGB(queryImage.size(), CV_8UC3);

			// convert grayscale to color image
			cv::cvtColor(queryImage, queryImageRGB, CV_GRAY2RGB);
			queryImage = queryImageRGB;
		}
		if (trainImage.channels() != 3) //color image
		{
			cv::Mat trainImageRGB(trainImage.size(), CV_8UC3);

			// convert grayscale to color image
			cv::cvtColor(trainImage, trainImageRGB, CV_GRAY2RGB);
			trainImage = trainImageRGB;
		}

		//prepare match result image
		Size sz1 = queryImage.size();
		Size sz2 = trainImage.size();
		Mat imgMatches(sz1.height, sz1.width+sz2.width, queryImage.type());
		// Move right boundary to the left.
		imgMatches.adjustROI(0, 0, 0, -sz2.width);
		queryImage.copyTo(imgMatches);
		imgMatches.adjustROI(0, 0, 0, sz1.width+sz2.width);
		// Move the left boundary to the right, right boundary to the right.
		imgMatches.adjustROI(0, 0, -sz1.width, 0);
		trainImage.copyTo(imgMatches);
		imgMatches.adjustROI(0, 0, sz1.width, 0);

		for (int i = 0; i < mask.size(); i++)
		{
			if (mask[i] && matches[i].size() > 0)
			{
				DMatch currentMatch = matches[i][0];
				KeyPoint queryKeyPoint = queryKeyPoints[currentMatch.queryIdx];
				KeyPoint trainKeyPoint = trainKeyPoints[currentMatch.trainIdx];

				//1. draw query image feature circle
				circle(imgMatches, queryKeyPoint.pt, (queryKeyPoint.size / (2 * pi)), drawColor, 1, 8, 0);
				//2. Draw train image feature circle
				Point2f trainFeaturePoint = trainKeyPoint.pt;
				trainFeaturePoint.x = trainFeaturePoint.x + queryImage.size().width;
				circle(imgMatches, trainFeaturePoint, (trainKeyPoint.size / (2 * pi)), drawColor, 1, 8, 0);
				//3. Finally line two circle
				line(imgMatches, queryKeyPoint.pt, trainFeaturePoint, drawColor, 1, 8, 0);
			}
		}

		imshow("Matches of Consecutive Frames", imgMatches);
		waitKey(0);
	}
	else
	{
		string errorMessage = "DrawUtility::DrawMatches failed at \"if (mask.size() == matches.size() && mask.size() == queryKeyPoints.size())\"";
		cout << errorMessage << endl;
		throw std::invalid_argument(errorMessage );
	}
}
<commit_msg>Revert "draw utility was updated."<commit_after>#include "DrawUtility.h"

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <iostream>
#include <stdexcept>

using namespace std;
using namespace cv;

static Scalar drawColor = Scalar(0, 255, 0, 1);

void DrawUtility::DrawMatches(std::vector<bool> mask, std::vector<std::vector<cv::DMatch>> matches, cv::Mat queryImage, std::vector<cv::KeyPoint> queryKeyPoints, cv::Mat trainImage, std::vector<cv::KeyPoint> trainKeyPoints)
{
	if (mask.size() == matches.size() && mask.size() == queryKeyPoints.size())
	{
		//if image is GrayScale image  then convert to rgb image
		if (queryImage.channels() != 3)	//color Image
		{
			cv::Mat queryImageRGB(queryImage.size(), CV_8UC3);

			// convert grayscale to color image
			cv::cvtColor(queryImage, queryImageRGB, CV_GRAY2RGB);
			queryImage = queryImageRGB;
		}
		if (trainImage.channels() != 3) //color image
		{
			cv::Mat trainImageRGB(trainImage.size(), CV_8UC3);

			// convert grayscale to color image
			cv::cvtColor(trainImage, trainImageRGB, CV_GRAY2RGB);
			trainImage = trainImageRGB;
		}

		//prepare match result image
		Size sz1 = queryImage.size();
		Size sz2 = trainImage.size();
		Mat imgMatches(sz1.height, sz1.width+sz2.width, queryImage.type());
		// Move right boundary to the left.
		imgMatches.adjustROI(0, 0, 0, -sz2.width);
		queryImage.copyTo(imgMatches);
		imgMatches.adjustROI(0, 0, 0, sz1.width+sz2.width);
		// Move the left boundary to the right, right boundary to the right.
		imgMatches.adjustROI(0, 0, -sz1.width, 0);
		trainImage.copyTo(imgMatches);
		imgMatches.adjustROI(0, 0, sz1.width, 0);

		for (int i = 0; i < mask.size(); i++)
		{
			if (mask[i] && matches[i].size() > 0)
			{
				DMatch currentMatch = matches[i][0];
				KeyPoint queryKeyPoint = queryKeyPoints[currentMatch.queryIdx];
				KeyPoint trainKeyPoint = trainKeyPoints[currentMatch.trainIdx];

				//1. draw query image feature circle
				circle(imgMatches, queryKeyPoint.pt, queryKeyPoint.size, drawColor, 1, 8, 0);
				//2. Draw train image feature circle
				Point2f trainFeaturePoint = trainKeyPoint.pt;
				trainFeaturePoint.x = trainFeaturePoint.x + queryImage.size().width;
				circle(imgMatches, trainFeaturePoint, trainKeyPoint.size, drawColor, 1, 8, 0);
				//3. Finally line two circle
				line(imgMatches, queryKeyPoint.pt, trainFeaturePoint, drawColor, 1, 8, 0);
			}
		}

		imshow("Matches of Consecutive Frames", imgMatches);
		waitKey(0);
	}
	else
	{
		string errorMessage = "DrawUtility::DrawMatches failed at \"if (mask.size() == matches.size() && mask.size() == queryKeyPoints.size())\"";
		cout << errorMessage << endl;
		throw std::invalid_argument(errorMessage );
	}
}
<|endoftext|>


<commit_before><commit_msg>Fix renaming textures<commit_after><|endoftext|>


<commit_before>// 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.

#ifndef __STOUT_STRINGIFY_HPP__
#define __STOUT_STRINGIFY_HPP__

#include <iostream> // For 'std::cerr' and 'std::endl'.
#include <list>
#include <map>
#include <set>
#include <sstream> // For 'std::ostringstream'.
#include <string>
#include <vector>

#ifdef __WINDOWS__
// `codecvt` is not available on older versions of Linux. Until it is needed on
// other platforms, it's easiest to just build the UTF converter for Windows.
#include <codecvt>
#include <locale>
#endif // __WINDOWS__

#include "abort.hpp"
#include "hashmap.hpp"
#include "set.hpp"

template <typename T>
std::string stringify(const T& t)
{
  std::ostringstream out;
  out << t;
  if (!out.good()) {
    ABORT("Failed to stringify!");
  }
  return out.str();
}

// We provide an explicit overload for strings so we do not incur the overhead
// of a stringstream in generic code (e.g., when stringifying containers of
// strings below).
inline std::string stringify(const std::string& str)
{
  return str;
}

#ifdef __WINDOWS__
inline std::string stringify(const std::wstring& str)
{
  // Convert UTF-16 `wstring` to UTF-8 `string`.
  std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> converter;
  return converter.to_bytes(str);
}
#endif // __WINDOWS__

inline std::string stringify(bool b)
{
  return b ? "true" : "false";
}

template <typename T>
std::string stringify(const std::set<T>& set)
{
  std::ostringstream out;
  out << "{ ";
  typename std::set<T>::const_iterator iterator = set.begin();
  while (iterator != set.end()) {
    out << stringify(*iterator);
    if (++iterator != set.end()) {
      out << ", ";
    }
  }
  out << " }";
  return out.str();
}

template <typename T>
std::string stringify(const std::list<T>& list)
{
  std::ostringstream out;
  out << "[ ";
  typename std::list<T>::const_iterator iterator = list.begin();
  while (iterator != list.end()) {
    out << stringify(*iterator);
    if (++iterator != list.end()) {
      out << ", ";
    }
  }
  out << " ]";
  return out.str();
}

template <typename T>
std::string stringify(const std::vector<T>& vector)
{
  std::ostringstream out;
  out << "[ ";
  typename std::vector<T>::const_iterator iterator = vector.begin();
  while (iterator != vector.end()) {
    out << stringify(*iterator);
    if (++iterator != vector.end()) {
      out << ", ";
    }
  }
  out << " ]";
  return out.str();
}

template <typename K, typename V>
std::string stringify(const std::map<K, V>& map)
{
  std::ostringstream out;
  out << "{ ";
  typename std::map<K, V>::const_iterator iterator = map.begin();
  while (iterator != map.end()) {
    out << stringify(iterator->first);
    out << ": ";
    out << stringify(iterator->second);
    if (++iterator != map.end()) {
      out << ", ";
    }
  }
  out << " }";
  return out.str();
}

template <typename T>
std::string stringify(const hashset<T>& set)
{
  std::ostringstream out;
  out << "{ ";
  typename hashset<T>::const_iterator iterator = set.begin();
  while (iterator != set.end()) {
    out << stringify(*iterator);
    if (++iterator != set.end()) {
      out << ", ";
    }
  }
  out << " }";
  return out.str();
}

template <typename K, typename V>
std::string stringify(const hashmap<K, V>& map)
{
  std::ostringstream out;
  out << "{ ";
  typename hashmap<K, V>::const_iterator iterator = map.begin();
  while (iterator != map.end()) {
    out << stringify(iterator->first);
    out << ": ";
    out << stringify(iterator->second);
    if (++iterator != map.end()) {
      out << ", ";
    }
  }
  out << " }";
  return out.str();
}

#endif // __STOUT_STRINGIFY_HPP__
<commit_msg>Windows: Added a `wstring wide_stringify(string)` helper.<commit_after>// 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.

#ifndef __STOUT_STRINGIFY_HPP__
#define __STOUT_STRINGIFY_HPP__

#include <iostream> // For 'std::cerr' and 'std::endl'.
#include <list>
#include <map>
#include <set>
#include <sstream> // For 'std::ostringstream'.
#include <string>
#include <vector>

#ifdef __WINDOWS__
// `codecvt` is not available on older versions of Linux. Until it is needed on
// other platforms, it's easiest to just build the UTF converter for Windows.
#include <codecvt>
#include <locale>
#endif // __WINDOWS__

#include "abort.hpp"
#include "hashmap.hpp"
#include "set.hpp"

template <typename T>
std::string stringify(const T& t)
{
  std::ostringstream out;
  out << t;
  if (!out.good()) {
    ABORT("Failed to stringify!");
  }
  return out.str();
}

// We provide an explicit overload for strings so we do not incur the overhead
// of a stringstream in generic code (e.g., when stringifying containers of
// strings below).
inline std::string stringify(const std::string& str)
{
  return str;
}

#ifdef __WINDOWS__
inline std::string stringify(const std::wstring& str)
{
  // Convert UTF-16 `wstring` to UTF-8 `string`.
  static std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t>
    converter(
        "UTF-16 to UTF-8 conversion failed",
        L"UTF-16 to UTF-8 conversion failed");

  return converter.to_bytes(str);
}

inline std::wstring wide_stringify(const std::string& str)
{
  // Convert UTF-8 `string` to UTF-16 `wstring`.
  static std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t>
    converter(
        "UTF-8 to UTF-16 conversion failed",
        L"UTF-8 to UTF-16 conversion failed");

  return converter.from_bytes(str);
}
#endif // __WINDOWS__

inline std::string stringify(bool b)
{
  return b ? "true" : "false";
}

template <typename T>
std::string stringify(const std::set<T>& set)
{
  std::ostringstream out;
  out << "{ ";
  typename std::set<T>::const_iterator iterator = set.begin();
  while (iterator != set.end()) {
    out << stringify(*iterator);
    if (++iterator != set.end()) {
      out << ", ";
    }
  }
  out << " }";
  return out.str();
}

template <typename T>
std::string stringify(const std::list<T>& list)
{
  std::ostringstream out;
  out << "[ ";
  typename std::list<T>::const_iterator iterator = list.begin();
  while (iterator != list.end()) {
    out << stringify(*iterator);
    if (++iterator != list.end()) {
      out << ", ";
    }
  }
  out << " ]";
  return out.str();
}

template <typename T>
std::string stringify(const std::vector<T>& vector)
{
  std::ostringstream out;
  out << "[ ";
  typename std::vector<T>::const_iterator iterator = vector.begin();
  while (iterator != vector.end()) {
    out << stringify(*iterator);
    if (++iterator != vector.end()) {
      out << ", ";
    }
  }
  out << " ]";
  return out.str();
}

template <typename K, typename V>
std::string stringify(const std::map<K, V>& map)
{
  std::ostringstream out;
  out << "{ ";
  typename std::map<K, V>::const_iterator iterator = map.begin();
  while (iterator != map.end()) {
    out << stringify(iterator->first);
    out << ": ";
    out << stringify(iterator->second);
    if (++iterator != map.end()) {
      out << ", ";
    }
  }
  out << " }";
  return out.str();
}

template <typename T>
std::string stringify(const hashset<T>& set)
{
  std::ostringstream out;
  out << "{ ";
  typename hashset<T>::const_iterator iterator = set.begin();
  while (iterator != set.end()) {
    out << stringify(*iterator);
    if (++iterator != set.end()) {
      out << ", ";
    }
  }
  out << " }";
  return out.str();
}

template <typename K, typename V>
std::string stringify(const hashmap<K, V>& map)
{
  std::ostringstream out;
  out << "{ ";
  typename hashmap<K, V>::const_iterator iterator = map.begin();
  while (iterator != map.end()) {
    out << stringify(iterator->first);
    out << ": ";
    out << stringify(iterator->second);
    if (++iterator != map.end()) {
      out << ", ";
    }
  }
  out << " }";
  return out.str();
}

#endif // __STOUT_STRINGIFY_HPP__
<|endoftext|>


<commit_before>// Print the point-to log in a readable format.

#include <cstdio>
#include <cassert>

#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"

#include "rcs/typedefs.h"

#include "dyn-aa/LogProcessor.h"
#include "dyn-aa/LogCounter.h"

using namespace std;
using namespace llvm;
using namespace rcs;
using namespace dyn_aa;

namespace dyn_aa {
struct LogDumper: public LogProcessor {
  virtual void processMemAlloc(const MemAllocRecord &);
  virtual void processTopLevel(const TopLevelRecord &);
  virtual void processStore(const StoreRecord &);
  virtual void processCall(const CallRecord &);
  virtual void processReturn(const ReturnRecord &);
};
}

static DenseSet<unsigned> TouchedPointers;

void LogDumper::processMemAlloc(const MemAllocRecord &Record) {
  printf("%u: %p, %lu\n", Record.AllocatedBy, Record.Address, Record.Bound);
}

void LogDumper::processTopLevel(const TopLevelRecord &Record) {
  printf("%u => %p", Record.PointerValueID, Record.PointeeAddress);
  if (Record.LoadedFrom) {
    printf(", from %p", Record.LoadedFrom);
  }
  printf("\n");
  TouchedPointers.insert(Record.PointerValueID);
}

void LogDumper::processStore(const StoreRecord &Record) {
  printf("%u: %p => %p\n",
         Record.InstructionID, Record.PointerAddress, Record.PointeeAddress);
}

void LogDumper::processCall(const CallRecord &Record) {
  printf("%u: call\n", Record.InstructionID);
}

void LogDumper::processReturn(const ReturnRecord &Record) {
  printf("%u: return\n", Record.InstructionID);
}

int main(int argc, char *argv[]) {
  cl::ParseCommandLineOptions(argc, argv, "Dumps point-to logs");
  LogDumper LD;
  LD.processLog();
  errs() << "# of touched pointers = " << TouchedPointers.size() << "\n";
  return 0;
}
<commit_msg>Removed TouchedPointers<commit_after>// Print the point-to log in a readable format.

#include <cstdio>
#include <cassert>

#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"

#include "rcs/typedefs.h"

#include "dyn-aa/LogProcessor.h"
#include "dyn-aa/LogCounter.h"

using namespace std;
using namespace llvm;
using namespace rcs;
using namespace dyn_aa;

namespace dyn_aa {
struct LogDumper: public LogProcessor {
  virtual void processMemAlloc(const MemAllocRecord &);
  virtual void processTopLevel(const TopLevelRecord &);
  virtual void processStore(const StoreRecord &);
  virtual void processCall(const CallRecord &);
  virtual void processReturn(const ReturnRecord &);
};
}

static DenseSet<unsigned> TouchedPointers;

void LogDumper::processMemAlloc(const MemAllocRecord &Record) {
  printf("%u: %p, %lu\n", Record.AllocatedBy, Record.Address, Record.Bound);
}

void LogDumper::processTopLevel(const TopLevelRecord &Record) {
  printf("%u => %p", Record.PointerValueID, Record.PointeeAddress);
  if (Record.LoadedFrom) {
    printf(", from %p", Record.LoadedFrom);
  }
  printf("\n");
  TouchedPointers.insert(Record.PointerValueID);
}

void LogDumper::processStore(const StoreRecord &Record) {
  printf("%u: %p => %p\n",
         Record.InstructionID, Record.PointerAddress, Record.PointeeAddress);
}

void LogDumper::processCall(const CallRecord &Record) {
  printf("%u: call\n", Record.InstructionID);
}

void LogDumper::processReturn(const ReturnRecord &Record) {
  printf("%u: return\n", Record.InstructionID);
}

int main(int argc, char *argv[]) {
  cl::ParseCommandLineOptions(argc, argv, "Dumps point-to logs");
  LogDumper LD;
  LD.processLog();
  return 0;
}
<|endoftext|>


<commit_before>#define cimg_display_type 0
#include <iostream>
#include <string>
#include <Magick++.h>
#include "CImg.h"
#include <fstream>
#include <map>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <ctime>
#include <stdio.h>

using namespace cimg_library;
using namespace std;
#include "slideToolKit.h"
using namespace Magick;

#include <tclap/CmdLine.h>

//Compiling on MacOSX:
//g++ -o slideEMask slideEMask.cpp -O2 -lm -lpthread -I/usr/X11R6/include -L/usr/X11R6/lib -lm -lpthread -lX11 -ltiff `Magick++-config --cxxflags --cppflags --ldflags --libs`

void print_help()  {

	cout << "slideEMask: Determine a tissue mask image from a slide TIFF using an image entropy filter (a measure for image texture)" << endl << endl << "usage" << endl << "  slideEMask <filename> (-c/--cp/--cellprofiler)" << endl;
	cout << "  -c/--cp/--cellprofiler: " << endl << "\t Whether to prepare the image for CellProfiler (save as bmp instead of png, and prepend \"ENTROPY_\" to the filename), default 'false'" << endl << endl;
	cout << "description" << endl;
	cout << "  slideEMask determines a tissue mask image by assessing image texture. " << endl << "This information is captured by using the standard formula for information entropy to determine the image entropy at each pixel point." << endl << "This works because highly textured areas (foreground, tissue) can be considered \"chaotic\" in terms of entropy, and can thus be separated from non-texturized regions (background) using this measure." << endl << endl << "To this extent, a 3x3 pixel 'neighborhood' is defined around each pixel. The center pixel's entropy value is calculated by taking the entropy of it's surrounding 3x3 neighborhood." << endl << endl << "These values are then averaged in a 4x4 pixel neighborhood to smoothen the image (removing small gaps)." << endl << endl;
	cout << "slideEMask was written by Tim Bezemer. For questions/comments please contact t.bezemer-2@umcutrecht.nl" << endl << endl;
	cout << "slideEMask uses the CImg library, released under the CeCILL license" << endl;
}

int main(int argc,char **argv)
{
	TCLAP::CmdLine cmd("slideEMask: Determine a tissue mask image from a slide TIFF using an image entropy filter (a measure for image texture)", ' ', "0.9");

	TCLAP::ValueArg<std::string> filenameArg("f","file","The filename of the TIF file to process.", true, "", "string", cmd);
	TCLAP::ValueArg<int> layerArg("l","layer","The layer number of the image to use for processing.", false, -1, "integer", cmd);
	TCLAP::SwitchArg cellprofilerArg("c", "cellprofiler","The table file does not contain a header / column names", cmd, false);

	cmd.parse( argc, argv );

	std::string filename = filenameArg.getValue();
	std::string layer = to_string(layerArg.getValue());

	bool CellProfiler = cellprofilerArg.getValue();

	if (is_file_exist(filename.c_str()) == false) {

		cerr << "Could not access file " << filename << endl;

        return 1;

	}
	else {

		if (CellProfiler) {
			cout << "Creating entropy image for " << filename << endl;
		}
		else {

			cout << "Automasking " << filename << endl;

		}
	}

	InitializeMagick(*argv);

    // Construct the image object. Seperating image construction from the
    // the read operation ensures that a failure to read the image file
    // doesn't render the image object useless.
    Image image;

    // layer 0 = Thumbnail
    // layer 5 = Macro
    // layer 3 = default layer for slide2Tiles

	try {

		//Start the clock, to measure elapsed time:
		clock_t begin = clock();

		std::string extension = getExtension(filename);

		std::cout << "The Extension is " << extension << std::endl;
		std::string to_open = "";

		if (!CellProfiler) {

			if ( extension == "PNG" ) {

				cout << "\t...Image file is PNG, assumed macro image" << endl;
				to_open = filename;

			}
			else {

				//FIRST WE SAVE THE MACRO IMAGE, AS THE EXTRACTION IS DONE USING IMAGEMAGICK, AND THE ENTROPY PROCESSING BY CImg, A DIFFERENT LIBRARY.
				cout << "\t...Extracting macro image" << endl;

				image = getMacroLayer(filename, layer);

				//Resize the macro image to 2000x2000 pixels
				image.resize("2000x2000");

				// Write the image to a file
				std::string new_filename = replaceString(filename, "." + extension, ".macro.png");

				image.write( new_filename );

			  	to_open = new_filename;
		  	}

	  	}
	  	else {

	  		cout << "\t...Loading tile image" << endl;
	  		to_open = filename;

	  	}

	  	CImg<float> src( to_open.c_str() );

	    cout << "\t...Converting to gray scale" << endl;

	    src = src.get_RGBtoYCbCr().get_channel(0);

	  	CImg<float> dest(src,false);

	  	cout << "\t...Applying entropy filter" << endl;

	  	// Define a 3x3 neighborhood as a 3x3 image.
	  	CImg<> N(3,3);

	  	//Calculate the Entropy for a 3x3 square
	  	// 3x3 neighborhood loop (see CImg docs), loop over x,y z-slice 0 (only 1 z-layer), color channel 0 (grayscale), store in Neighborhood image 'N' (defined above), treat as array of floats
	  	cimg_for3x3(src,x,y,0,0,N,float) {

	  		float H = entropy(N, 9);

	  		dest(x,y) = H;

	  	}

	  	cout << "\t...Smoothing entropy mask" << endl;
	  	//Calculate the average gray value for a 5x5 square, to remove white spots from the tissue area
	  	CImg<> N2(5,5);

	  	// 5x5 neighborhood loop (see CImg docs), loop over x,y z-slice 0 (only 1 z-layer), color channel 0 (grayscale), store in Neighborhood image 'N2' (defined above), treat as array of floats
	  	cimg_for5x5(src,x,y,0,0,N2,float) {

	  		float avg = N2.sum()/(5*5);

	      //If the average gray value of this neighborhood exceeds value 210, set the pixel value to white, else black (this value was found empirically).
	  		if(avg > 210) { dest(x,y) = 0; }
	  		else { dest(x,y) = 255; }

	  	}

	  	//Display functions for optimization/debugging purposes
	    //!!! Only works when #define cimg_display_type 0 (line 1) is removed!!
		  //CImgList<unsigned char> visu(src,dest);
		  //visu.display("Original + Entropy");       // Display both original and filtered image.

	  	std::string new_fn = "";

	  	if (CellProfiler) {
	  		new_fn = "ENTROPY_" + replaceString(to_open, ".png", ".bmp");
	  	}
	  	else {
	  		new_fn = replaceString(to_open, ".png", ".emask.png");
	  	}

	  	//Save, but cast new filename to c_str first, because C++ doesn't accept std::string instead of const *char
	  	dest.save(new_fn.c_str());
	  	cout << "\t...Saved as " << new_fn << endl;

	  	if (CellProfiler) { remove(to_open.c_str()); }

	    clock_t end = clock();
	    double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
	    cout << "\t...Processing took " << elapsed_secs << " seconds" << endl;

	}
	catch( Exception &error_ ) {

		cout << "Caught exception: " << error_.what() << endl;
		return 1;
	}

	return 0;

}

<commit_msg>slideEMask<commit_after>#define cimg_display_type 0
#include <iostream>
#include <string>
#include <Magick++.h>
#include "CImg.h"
#include <fstream>
#include <map>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <ctime>
#include <stdio.h>

using namespace cimg_library;
using namespace std;
#include "slideToolKit.h"
using namespace Magick;

#include <tclap/CmdLine.h>

//Compiling on MacOSX:
//g++ -o slideEMask slideEMask.cpp -O2 -lm -lpthread -I/usr/X11R6/include -L/usr/X11R6/lib -lm -lpthread -lX11 -ltiff `Magick++-config --cxxflags --cppflags --ldflags --libs`

void print_help()  {

	cout << "slideEMask: Determine a tissue mask image from a slide TIFF using an image entropy filter (a measure for image texture)" << endl << endl << "usage" << endl << "  slideEMask <filename> (-c/--cp/--cellprofiler)" << endl;
	cout << "  -c/--cp/--cellprofiler: " << endl << "\t Whether to prepare the image for CellProfiler (save as bmp instead of png, and prepend \"ENTROPY_\" to the filename), default 'false'" << endl << endl;
	cout << "description" << endl;
	cout << "  slideEMask determines a tissue mask image by assessing image texture. " << endl << "This information is captured by using the standard formula for information entropy to determine the image entropy at each pixel point." << endl << "This works because highly textured areas (foreground, tissue) can be considered \"chaotic\" in terms of entropy, and can thus be separated from non-texturized regions (background) using this measure." << endl << endl << "To this extent, a 3x3 pixel 'neighborhood' is defined around each pixel. The center pixel's entropy value is calculated by taking the entropy of it's surrounding 3x3 neighborhood." << endl << endl << "These values are then averaged in a 4x4 pixel neighborhood to smoothen the image (removing small gaps)." << endl << endl;
	cout << "slideEMask was written by Tim Bezemer. For questions/comments please contact t.bezemer-2@umcutrecht.nl" << endl << endl;
	cout << "slideEMask uses the CImg library, released under the CeCILL license" << endl;
}

int main(int argc,char **argv)
{
	TCLAP::CmdLine cmd("slideEMask: Determine a tissue mask image from a slide TIFF using an image entropy filter (a measure for image texture)", ' ', "0.9");

	TCLAP::ValueArg<std::string> filenameArg("f","file","The filename of the TIF file to process.", true, "", "string", cmd);
	TCLAP::ValueArg<int> layerArg("l","layer","The layer number of the image to use for processing.", false, -1, "integer", cmd);
	TCLAP::SwitchArg cellprofilerArg("c", "cellprofiler","The table file does not contain a header / column names", cmd, false);

	cmd.parse( argc, argv );

	std::string filename = filenameArg.getValue();
	std::string layer = to_string(layerArg.getValue());

	bool CellProfiler = cellprofilerArg.getValue();

	if (is_file_exist(filename.c_str()) == false) {

		cerr << "Could not access file " << filename << endl;

        return 1;

	}
	else {

		if (CellProfiler) {
			cout << "Creating entropy image for " << filename << endl;
		}
		else {

			cout << "Automasking " << filename << endl;

		}
	}

	InitializeMagick(*argv);

    // Construct the image object. Seperating image construction from the
    // the read operation ensures that a failure to read the image file
    // doesn't render the image object useless.
    Image image;

    // layer 0 = Thumbnail
    // layer 5 = Macro
    // layer 3 = default layer for slide2Tiles

	try {

		//Start the clock, to measure elapsed time:
		clock_t begin = clock();

		std::string extension = getExtension(filename);

		std::string to_open = "";

		if (!CellProfiler) {

			if ( extension == "PNG" ) {

				cout << "\t...Image file is PNG, assumed macro image" << endl;
				to_open = filename;

			}
			else {

				//FIRST WE SAVE THE MACRO IMAGE, AS THE EXTRACTION IS DONE USING IMAGEMAGICK, AND THE ENTROPY PROCESSING BY CImg, A DIFFERENT LIBRARY.
				cout << "\t...Extracting macro image" << endl;

				image = getMacroLayer(filename, layer);

				//Resize the macro image to 2000x2000 pixels
				image.resize("2000x2000");

				// Write the image to a file
				std::string new_filename = replaceString(filename, "." + extension, ".macro.png");

				image.write( new_filename );

			  	to_open = new_filename;
		  	}

	  	}
	  	else {

	  		cout << "\t...Loading tile image" << endl;
	  		to_open = filename;

	  	}

	  	CImg<float> src( to_open.c_str() );

	    cout << "\t...Converting to gray scale" << endl;

	    src = src.get_RGBtoYCbCr().get_channel(0);

	  	CImg<float> dest(src,false);

	  	cout << "\t...Applying entropy filter" << endl;

	  	// Define a 3x3 neighborhood as a 3x3 image.
	  	CImg<> N(3,3);

	  	//Calculate the Entropy for a 3x3 square
	  	// 3x3 neighborhood loop (see CImg docs), loop over x,y z-slice 0 (only 1 z-layer), color channel 0 (grayscale), store in Neighborhood image 'N' (defined above), treat as array of floats
	  	cimg_for3x3(src,x,y,0,0,N,float) {

	  		float H = entropy(N, 9);

	  		dest(x,y) = H;

	  	}

	  	cout << "\t...Smoothing entropy mask" << endl;
	  	//Calculate the average gray value for a 5x5 square, to remove white spots from the tissue area
	  	CImg<> N2(5,5);

	  	// 5x5 neighborhood loop (see CImg docs), loop over x,y z-slice 0 (only 1 z-layer), color channel 0 (grayscale), store in Neighborhood image 'N2' (defined above), treat as array of floats
	  	cimg_for5x5(src,x,y,0,0,N2,float) {

	  		float avg = N2.sum()/(5*5);

	      //If the average gray value of this neighborhood exceeds value 210, set the pixel value to white, else black (this value was found empirically).
	  		if(avg > 210) { dest(x,y) = 0; }
	  		else { dest(x,y) = 255; }

	  	}

	  	//Display functions for optimization/debugging purposes
	    //!!! Only works when #define cimg_display_type 0 (line 1) is removed!!
		  //CImgList<unsigned char> visu(src,dest);
		  //visu.display("Original + Entropy");       // Display both original and filtered image.

	  	std::string new_fn = "";

	  	if (CellProfiler) {
	  		new_fn = "ENTROPY_" + replaceString(to_open, ".png", ".bmp");
	  	}
	  	else {
	  		new_fn = replaceString(to_open, ".png", ".emask.png");
	  	}

	  	//Save, but cast new filename to c_str first, because C++ doesn't accept std::string instead of const *char
	  	dest.save(new_fn.c_str());
	  	cout << "\t...Saved as " << new_fn << endl;

	  	if (CellProfiler) { remove(to_open.c_str()); }

	    clock_t end = clock();
	    double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
	    cout << "\t...Processing took " << elapsed_secs << " seconds" << endl;

	}
	catch( Exception &error_ ) {

		cout << "Caught exception: " << error_.what() << endl;
		return 1;
	}

	return 0;

}

<|endoftext|>


<commit_before>/*
    kopeteonlinestatus.cpp - Kopete Online Status

    Copyright (c) 2002-2004 by Olivier Goffart       <ogoffart@kde.org>
    Copyright (c) 2003      by Martijn Klingens      <klingens@kde.org>

    Kopete    (c) 2002-2004 by the Kopete developers <kopete-devel@kde.org>

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

#include <qpainter.h>

#include <klocale.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <kapplication.h>

#include <kglobalsettings.h>

#include "kopetecontactlistview.h"
#include "kopetegroupviewitem.h"
#include "kopetegroup.h"
#include "kopeteonlinestatus.h"
#include "kopetemetacontactlvi.h"
#include "kopetemetacontact.h"
#include "kopeteappearancesettings.h"

#include <memory>

//using namespace Kopete::UI;

class KopeteGroupViewItem::Private
{
public:
	Kopete::UI::ListView::ImageComponent *image;
	Kopete::UI::ListView::DisplayNameComponent *name;
	Kopete::UI::ListView::TextComponent *count;
	std::auto_ptr<Kopete::UI::ListView::ToolTipSource> toolTipSource;
};

namespace Kopete {
namespace UI {
namespace ListView {

class GroupToolTipSource : public ToolTipSource
{
public:
	GroupToolTipSource( KopeteGroupViewItem *gp )
	 : group( gp )
	{
	}
	QString operator()( ComponentBase *, const QPoint &, QRect & )
	{
		return group->toolTip();
	}
private:
	KopeteGroupViewItem *group;
};

} // END namespace ListView
} // END namespace UI
} // END namespace Kopete

KopeteGroupViewItem::KopeteGroupViewItem( Kopete::Group *group_, Q3ListView *parent )
: Kopete::UI::ListView::Item( parent, group_ )
{
	m_group = group_;
	initLVI();
}

KopeteGroupViewItem::KopeteGroupViewItem( Kopete::Group *group_, Q3ListViewItem *parent )
 : Kopete::UI::ListView::Item( parent, group_ )
{
	m_group = group_;
	initLVI();
}

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

void KopeteGroupViewItem::initLVI()
{
	d = new Private;

	d->toolTipSource.reset( new Kopete::UI::ListView::GroupToolTipSource( this ) );

	using namespace Kopete::UI::ListView;
	Component *hbox = new BoxComponent( this, BoxComponent::Horizontal );
	d->image = new ImageComponent( hbox );
	d->name = new DisplayNameComponent( hbox );
	d->count = new TextComponent( hbox );

	d->image->setToolTipSource( d->toolTipSource.get() );
	d->name->setToolTipSource( d->toolTipSource.get() );
	d->count->setToolTipSource( d->toolTipSource.get() );

	connect( m_group, SIGNAL( displayNameChanged( Kopete::Group*, const QString& ) ),
		this, SLOT( refreshDisplayName() ) );

	connect( Kopete::AppearanceSettings::self(), SIGNAL( contactListAppearanceChanged() ),
		SLOT( slotConfigChanged() ) );
	connect( KGlobalSettings::self(), SIGNAL( appearanceChanged() ),  SLOT( slotConfigChanged() ) );

	connect( m_group, SIGNAL( iconAppearanceChanged() ), SLOT( updateIcon() ) );

	refreshDisplayName();
	slotConfigChanged();
}

Kopete::Group* KopeteGroupViewItem::group() const
{
	return m_group;
}

QString KopeteGroupViewItem::toolTip() const
{
	// TODO: add icon, and some more information than that which
	// is already displayed in the list view item
	// FIXME: post-KDE-3.3, make this better i18n-able
	//  currently it can't cause more problems than the contact list itself, at least.
	return "" + d->name->text() + " " + d->count->text();
}

void KopeteGroupViewItem::slotConfigChanged()
{
	updateIcon();
	updateVisibility();

	d->name->setColor( Kopete::AppearanceSettings::self()->groupNameColor() );

	QFont font = listView()->font();
	if ( Kopete::AppearanceSettings::self()->contactListUseCustomFont() )
		font = Kopete::AppearanceSettings::self()->contactListNormalFont();
	d->name->setFont( font );

	d->count->setFont( Kopete::AppearanceSettings::self()->contactListSmallFont() );
}

void KopeteGroupViewItem::refreshDisplayName()
{
	totalMemberCount = 0;
	onlineMemberCount = 0;

	for ( Q3ListViewItem *lvi = firstChild(); lvi; lvi = lvi->nextSibling() )
	{
		if ( KopeteMetaContactLVI *kc = dynamic_cast<KopeteMetaContactLVI*>( lvi ) )
		{
			totalMemberCount++;
			if ( kc->metaContact()->isOnline() )
				onlineMemberCount++;
		}
	}

	d->name->setText( m_group->displayName() );
	d->count->setText( i18nc( "(NUMBER OF ONLINE CONTACTS/NUMBER OF CONTACTS IN GROUP)", "(%1/%2)",
	                   onlineMemberCount, totalMemberCount ) );

	updateVisibility();

	// Sorting in this slot is extremely expensive as it's called dozens of times and
	// the sorting itself is rather slow. Therefore we call delayedSort, which tries
	// to group multiple sort requests into one.
	using namespace Kopete::UI::ListView;
	if ( ListView::ListView *lv = dynamic_cast<ListView::ListView *>( listView() ) )
		lv->delayedSort();
	else
		listView()->sort();
}

QString KopeteGroupViewItem::key( int, bool ) const
{
	//Groups are placed after topLevel contact.
	//Exepted Temporary group which is the first group
	if ( group()->type() != Kopete::Group::Normal )
		return '0' + d->name->text();
	return 'M' + d->name->text();
}

void KopeteGroupViewItem::startRename( int /*col*/ )
{
	//kDebug(14000) << k_funcinfo << endl;
	K3ListViewItem::startRename( 0 );
}

void KopeteGroupViewItem::okRename( int col )
{
	//kDebug(14000) << k_funcinfo << endl;
	K3ListViewItem::okRename(col);
	setRenameEnabled( 0, false );
}

void KopeteGroupViewItem::cancelRename( int col )
{
	//kDebug(14000) << k_funcinfo << endl;
	K3ListViewItem::cancelRename(col);
	setRenameEnabled( 0, false );
}

void KopeteGroupViewItem::updateVisibility()
{
	//FIXME: A contact can ve visible if he has a unknwon status (it's not online)
	//       or if he has an event (blinking icon).  If such as contact is not with
	//       others inline contact in the group. the group will stay hidden.
	int visibleUsers = onlineMemberCount;
	if ( Kopete::AppearanceSettings::self()->showOfflineUsers() )
		visibleUsers = totalMemberCount;

	bool visible = Kopete::AppearanceSettings::self()->showEmptyGroups() || ( visibleUsers > 0 );

	if ( isVisible() != visible )
	{
		setTargetVisibility( visible );
		if ( visible )
		{
			// When calling setVisible(true) EVERY child item will be shown,
			// even if they should be hidden.
			// We just re-update the visibility of all child items
			for ( Q3ListViewItem *lvi = firstChild(); lvi; lvi = lvi->nextSibling() )
			{
				if ( KopeteMetaContactLVI *kmc = dynamic_cast<KopeteMetaContactLVI *>( lvi ) )
					kmc->updateVisibility();
			}
		}
	}
}

void KopeteGroupViewItem::updateIcon()
{
	// TODO: clever caching
	if ( isOpen() )
	{
		if ( group()->useCustomIcon() && !group()->icon( Kopete::ContactListElement::Open ).isEmpty() )
			open = SmallIcon( group()->icon( Kopete::ContactListElement::Open ) );
		else
			open = SmallIcon( KOPETE_GROUP_DEFAULT_OPEN_ICON );

		d->image->setPixmap( open );
	}
	else
	{
		if ( group()->useCustomIcon() && !group()->icon( Kopete::ContactListElement::Closed ).isEmpty() )
			closed = SmallIcon( group()->icon( Kopete::ContactListElement::Closed ) );
		else
			closed = SmallIcon( KOPETE_GROUP_DEFAULT_CLOSED_ICON );

		d->image->setPixmap( closed );
	}
}

QString KopeteGroupViewItem::text( int column ) const
{
	if ( column == 0 )
		return d->name->text();
	else
		return K3ListViewItem::text( column );
}

void KopeteGroupViewItem::setText( int column, const QString &text )
{
	if ( column == 0 )
	{
		KopeteContactListView *lv = dynamic_cast<KopeteContactListView *>( listView() );
		if ( lv )
		{
			KopeteContactListView::UndoItem *u=new KopeteContactListView::UndoItem(KopeteContactListView::UndoItem::GroupRename, 0L, m_group);
			u->args << m_group->displayName();
			lv->insertUndoItem(u);
		}
		group()->setDisplayName( text );
	}
	else
		K3ListViewItem::setText( column, text );
}

#include "kopetegroupviewitem.moc"
// vim: set noet ts=4 sts=4 sw=4:

<commit_msg>compile++<commit_after>/*
    kopeteonlinestatus.cpp - Kopete Online Status

    Copyright (c) 2002-2004 by Olivier Goffart       <ogoffart@kde.org>
    Copyright (c) 2003      by Martijn Klingens      <klingens@kde.org>

    Kopete    (c) 2002-2004 by the Kopete developers <kopete-devel@kde.org>

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

#include <qpainter.h>

#include <klocale.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <kapplication.h>

#include <kglobalsettings.h>

#include "kopetecontactlistview.h"
#include "kopetegroupviewitem.h"
#include "kopetegroup.h"
#include "kopeteonlinestatus.h"
#include "kopetemetacontactlvi.h"
#include "kopetemetacontact.h"
#include "kopeteappearancesettings.h"

#include <memory>

//using namespace Kopete::UI;

class KopeteGroupViewItem::Private
{
public:
	Kopete::UI::ListView::ImageComponent *image;
	Kopete::UI::ListView::DisplayNameComponent *name;
	Kopete::UI::ListView::TextComponent *count;
	std::auto_ptr<Kopete::UI::ListView::ToolTipSource> toolTipSource;
};

namespace Kopete {
namespace UI {
namespace ListView {

class GroupToolTipSource : public ToolTipSource
{
public:
	GroupToolTipSource( KopeteGroupViewItem *gp )
	 : group( gp )
	{
	}
	QString operator()( ComponentBase *, const QPoint &, QRect & )
	{
		return group->toolTip();
	}
private:
	KopeteGroupViewItem *group;
};

} // END namespace ListView
} // END namespace UI
} // END namespace Kopete

KopeteGroupViewItem::KopeteGroupViewItem( Kopete::Group *group_, Q3ListView *parent )
: Kopete::UI::ListView::Item( parent, group_ )
{
	m_group = group_;
	initLVI();
}

KopeteGroupViewItem::KopeteGroupViewItem( Kopete::Group *group_, Q3ListViewItem *parent )
 : Kopete::UI::ListView::Item( parent, group_ )
{
	m_group = group_;
	initLVI();
}

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

void KopeteGroupViewItem::initLVI()
{
	d = new Private;

	d->toolTipSource.reset( new Kopete::UI::ListView::GroupToolTipSource( this ) );

	using namespace Kopete::UI::ListView;
	Component *hbox = new BoxComponent( this, BoxComponent::Horizontal );
	d->image = new ImageComponent( hbox );
	d->name = new DisplayNameComponent( hbox );
	d->count = new TextComponent( hbox );

	d->image->setToolTipSource( d->toolTipSource.get() );
	d->name->setToolTipSource( d->toolTipSource.get() );
	d->count->setToolTipSource( d->toolTipSource.get() );

	connect( m_group, SIGNAL( displayNameChanged( Kopete::Group*, const QString& ) ),
		this, SLOT( refreshDisplayName() ) );

	connect( Kopete::AppearanceSettings::self(), SIGNAL( contactListAppearanceChanged() ),
		SLOT( slotConfigChanged() ) );
	connect( KGlobalSettings::self(), SIGNAL( appearanceChanged() ),  SLOT( slotConfigChanged() ) );

	connect( m_group, SIGNAL( iconAppearanceChanged() ), SLOT( updateIcon() ) );

	refreshDisplayName();
	slotConfigChanged();
}

Kopete::Group* KopeteGroupViewItem::group() const
{
	return m_group;
}

QString KopeteGroupViewItem::toolTip() const
{
	// TODO: add icon, and some more information than that which
	// is already displayed in the list view item
	// FIXME: post-KDE-3.3, make this better i18n-able
	//  currently it can't cause more problems than the contact list itself, at least.
	return "" + d->name->text() + " " + d->count->text();
}

void KopeteGroupViewItem::slotConfigChanged()
{
	updateIcon();
	updateVisibility();

	d->name->setColor( Kopete::AppearanceSettings::self()->groupNameColor() );

	QFont font = listView()->font();
	if ( Kopete::AppearanceSettings::self()->contactListUseCustomFont() )
		font = Kopete::AppearanceSettings::self()->contactListNormalFont();
	d->name->setFont( font );

	d->count->setFont( Kopete::AppearanceSettings::self()->contactListSmallFont() );
}

void KopeteGroupViewItem::refreshDisplayName()
{
	totalMemberCount = 0;
	onlineMemberCount = 0;

	for ( Q3ListViewItem *lvi = firstChild(); lvi; lvi = lvi->nextSibling() )
	{
		if ( KopeteMetaContactLVI *kc = dynamic_cast<KopeteMetaContactLVI*>( lvi ) )
		{
			totalMemberCount++;
			if ( kc->metaContact()->isOnline() )
				onlineMemberCount++;
		}
	}

	d->name->setText( m_group->displayName() );
	d->count->setText( i18nc( "(NUMBER OF ONLINE CONTACTS/NUMBER OF CONTACTS IN GROUP)", "(%1/%2)",
	                   onlineMemberCount, totalMemberCount ) );

	updateVisibility();

	// Sorting in this slot is extremely expensive as it's called dozens of times and
	// the sorting itself is rather slow. Therefore we call delayedSort, which tries
	// to group multiple sort requests into one.
	using namespace Kopete::UI::ListView;
	if ( ListView *lv = dynamic_cast<ListView *>( listView() ) )
		lv->delayedSort();
	else
		listView()->sort();
}

QString KopeteGroupViewItem::key( int, bool ) const
{
	//Groups are placed after topLevel contact.
	//Exepted Temporary group which is the first group
	if ( group()->type() != Kopete::Group::Normal )
		return '0' + d->name->text();
	return 'M' + d->name->text();
}

void KopeteGroupViewItem::startRename( int /*col*/ )
{
	//kDebug(14000) << k_funcinfo << endl;
	K3ListViewItem::startRename( 0 );
}

void KopeteGroupViewItem::okRename( int col )
{
	//kDebug(14000) << k_funcinfo << endl;
	K3ListViewItem::okRename(col);
	setRenameEnabled( 0, false );
}

void KopeteGroupViewItem::cancelRename( int col )
{
	//kDebug(14000) << k_funcinfo << endl;
	K3ListViewItem::cancelRename(col);
	setRenameEnabled( 0, false );
}

void KopeteGroupViewItem::updateVisibility()
{
	//FIXME: A contact can ve visible if he has a unknwon status (it's not online)
	//       or if he has an event (blinking icon).  If such as contact is not with
	//       others inline contact in the group. the group will stay hidden.
	int visibleUsers = onlineMemberCount;
	if ( Kopete::AppearanceSettings::self()->showOfflineUsers() )
		visibleUsers = totalMemberCount;

	bool visible = Kopete::AppearanceSettings::self()->showEmptyGroups() || ( visibleUsers > 0 );

	if ( isVisible() != visible )
	{
		setTargetVisibility( visible );
		if ( visible )
		{
			// When calling setVisible(true) EVERY child item will be shown,
			// even if they should be hidden.
			// We just re-update the visibility of all child items
			for ( Q3ListViewItem *lvi = firstChild(); lvi; lvi = lvi->nextSibling() )
			{
				if ( KopeteMetaContactLVI *kmc = dynamic_cast<KopeteMetaContactLVI *>( lvi ) )
					kmc->updateVisibility();
			}
		}
	}
}

void KopeteGroupViewItem::updateIcon()
{
	// TODO: clever caching
	if ( isOpen() )
	{
		if ( group()->useCustomIcon() && !group()->icon( Kopete::ContactListElement::Open ).isEmpty() )
			open = SmallIcon( group()->icon( Kopete::ContactListElement::Open ) );
		else
			open = SmallIcon( KOPETE_GROUP_DEFAULT_OPEN_ICON );

		d->image->setPixmap( open );
	}
	else
	{
		if ( group()->useCustomIcon() && !group()->icon( Kopete::ContactListElement::Closed ).isEmpty() )
			closed = SmallIcon( group()->icon( Kopete::ContactListElement::Closed ) );
		else
			closed = SmallIcon( KOPETE_GROUP_DEFAULT_CLOSED_ICON );

		d->image->setPixmap( closed );
	}
}

QString KopeteGroupViewItem::text( int column ) const
{
	if ( column == 0 )
		return d->name->text();
	else
		return K3ListViewItem::text( column );
}

void KopeteGroupViewItem::setText( int column, const QString &text )
{
	if ( column == 0 )
	{
		KopeteContactListView *lv = dynamic_cast<KopeteContactListView *>( listView() );
		if ( lv )
		{
			KopeteContactListView::UndoItem *u=new KopeteContactListView::UndoItem(KopeteContactListView::UndoItem::GroupRename, 0L, m_group);
			u->args << m_group->displayName();
			lv->insertUndoItem(u);
		}
		group()->setDisplayName( text );
	}
	else
		K3ListViewItem::setText( column, text );
}

#include "kopetegroupviewitem.moc"
// vim: set noet ts=4 sts=4 sw=4:

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: XMLTrackedChangesImportContext.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: dvo $ $Date: 2001-06-29 21:07:22 $
 *
 *  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 _XMLOFF_XMLTRACKEDCHANGESIMPORTCONTEXT_HXX
#include "XMLTrackedChangesImportContext.hxx"
#endif

#ifndef _XMLOFF_XMLCHANGEDREGIONIMPORTCONTEXT_HXX
#include "XMLChangedRegionImportContext.hxx"
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif

#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif

#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif

#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif

using ::rtl::OUString;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::xml::sax::XAttributeList;
using namespace ::xmloff::token;

TYPEINIT1( XMLTrackedChangesImportContext, SvXMLImportContext );

XMLTrackedChangesImportContext::XMLTrackedChangesImportContext(
    SvXMLImport& rImport,
    sal_uInt16 nPrefix,
    const OUString& rLocalName) :
        SvXMLImportContext(rImport, nPrefix, rLocalName)
{
}

XMLTrackedChangesImportContext::~XMLTrackedChangesImportContext()
{
}

void XMLTrackedChangesImportContext::StartElement(
    const Reference<XAttributeList> & xAttrList )
{
    sal_Bool bTrackChanges = sal_True;
    Sequence<sal_Int8> aProtectionKey;

    // scan for text:track-changes and text:protection-key attributes
    sal_Int16 nLength = xAttrList->getLength();
    for( sal_Int16 i = 0; i < nLength; i++ )
    {
        OUString sLocalName;
        sal_uInt16 nPrefix = GetImport().GetNamespaceMap().
            GetKeyByAttrName( xAttrList->getNameByIndex(i), &sLocalName );

        if ( XML_NAMESPACE_TEXT == nPrefix )
        {
            if ( IsXMLToken( sLocalName, XML_TRACK_CHANGES ) )
            {
                sal_Bool bTmp;
                if( SvXMLUnitConverter::convertBool(
                    bTmp, xAttrList->getValueByIndex(i)) )
                {
                    bTrackChanges = bTmp;
                }
            }
            else if ( IsXMLToken( sLocalName, XML_PROTECTION_KEY ) )            {
                Sequence<sal_Int8> aSequence;
                SvXMLUnitConverter::decodeBase64(
                    aSequence, xAttrList->getValueByIndex(i));
                if ( aSequence.getLength() > 0 )
                {
                    aProtectionKey = aSequence;
                }
            }
        }
    }

    // set tracked changes
    GetImport().GetTextImport()->SetRecordChanges( bTrackChanges );
    GetImport().GetTextImport()->SetChangesProtectionKey( aProtectionKey );
}

SvXMLImportContext* XMLTrackedChangesImportContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const OUString& rLocalName,
    const Reference<XAttributeList> & xAttrList)
{
    SvXMLImportContext* pContext = NULL;

    if ( (XML_NAMESPACE_TEXT == nPrefix) &&
         IsXMLToken( rLocalName, XML_CHANGED_REGION ) )
    {
        pContext = new XMLChangedRegionImportContext(GetImport(),
                                                     nPrefix, rLocalName);
    }

    if (NULL == pContext)
    {
        pContext = SvXMLImportContext::CreateChildContext(nPrefix, rLocalName,
                                                          xAttrList);
    }

    return pContext;
}
<commit_msg>INTEGRATION: CWS oasis (1.3.276); FILE MERGED 2004/06/23 16:01:11 mib 1.3.276.1: #i20153#: redline protection key, bug fixes<commit_after>/*************************************************************************
 *
 *  $RCSfile: XMLTrackedChangesImportContext.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-13 08:39:27 $
 *
 *  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 _XMLOFF_XMLTRACKEDCHANGESIMPORTCONTEXT_HXX
#include "XMLTrackedChangesImportContext.hxx"
#endif

#ifndef _XMLOFF_XMLCHANGEDREGIONIMPORTCONTEXT_HXX
#include "XMLChangedRegionImportContext.hxx"
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif

#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif

#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif

#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif

using ::rtl::OUString;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::xml::sax::XAttributeList;
using namespace ::xmloff::token;

TYPEINIT1( XMLTrackedChangesImportContext, SvXMLImportContext );

XMLTrackedChangesImportContext::XMLTrackedChangesImportContext(
    SvXMLImport& rImport,
    sal_uInt16 nPrefix,
    const OUString& rLocalName) :
        SvXMLImportContext(rImport, nPrefix, rLocalName)
{
}

XMLTrackedChangesImportContext::~XMLTrackedChangesImportContext()
{
}

void XMLTrackedChangesImportContext::StartElement(
    const Reference<XAttributeList> & xAttrList )
{
    sal_Bool bTrackChanges = sal_True;

    // scan for text:track-changes and text:protection-key attributes
    sal_Int16 nLength = xAttrList->getLength();
    for( sal_Int16 i = 0; i < nLength; i++ )
    {
        OUString sLocalName;
        sal_uInt16 nPrefix = GetImport().GetNamespaceMap().
            GetKeyByAttrName( xAttrList->getNameByIndex(i), &sLocalName );

        if ( XML_NAMESPACE_TEXT == nPrefix )
        {
            if ( IsXMLToken( sLocalName, XML_TRACK_CHANGES ) )
            {
                sal_Bool bTmp;
                if( SvXMLUnitConverter::convertBool(
                    bTmp, xAttrList->getValueByIndex(i)) )
                {
                    bTrackChanges = bTmp;
                }
            }
        }
    }

    // set tracked changes
    GetImport().GetTextImport()->SetRecordChanges( bTrackChanges );
}

SvXMLImportContext* XMLTrackedChangesImportContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const OUString& rLocalName,
    const Reference<XAttributeList> & xAttrList)
{
    SvXMLImportContext* pContext = NULL;

    if ( (XML_NAMESPACE_TEXT == nPrefix) &&
         IsXMLToken( rLocalName, XML_CHANGED_REGION ) )
    {
        pContext = new XMLChangedRegionImportContext(GetImport(),
                                                     nPrefix, rLocalName);
    }

    if (NULL == pContext)
    {
        pContext = SvXMLImportContext::CreateChildContext(nPrefix, rLocalName,
                                                          xAttrList);
    }

    return pContext;
}
<|endoftext|>


<commit_before>/*
    This file is part of kdepim.

    Copyright (c) 2005 Reinhold Kainhofer <reinhold@kainhofer.com>

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

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

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "exchangeglobals.h"
#include <webdavhandler.h>
#include <groupwaredataadaptor.h>
#include "exchangeconvertercalendar.h"
#include "exchangeconvertercontact.h"
#include <calendaradaptor.h>
#include <addressbookadaptor.h>

#include <libkcal/resourcecached.h>
#include <libemailfunctions/idmapper.h>
#include <kio/job.h>
#include <kio/davjob.h>
#include <kdebug.h>

KPIM::FolderLister::ContentType ExchangeGlobals::getContentType( const QDomElement &prop )
{
  const QString &contentclass = prop.namedItem("contentclass").toElement().text();
kdDebug()<<"contentclass: "<<contentclass<<endl;
  return getContentType( contentclass );
}

KPIM::FolderLister::ContentType ExchangeGlobals::getContentType( const QString &contentclass )
{
  if ( contentclass == "urn:content-classes:appointment" )
    return KPIM::FolderLister::Event;
  if ( contentclass == "urn:content-classes:task" )
    return KPIM::FolderLister::Todo;
  if ( contentclass == "urn:content-classes:message" )
    return KPIM::FolderLister::Message;
  if ( contentclass == "urn:content-classes:person" )
    return KPIM::FolderLister::Contact;
  return KPIM::FolderLister::Unknown;
}

KPIM::FolderLister::ContentType ExchangeGlobals::getContentType( const QDomNode &folderNode )
{
kdDebug()<<"ExchangeGlobals::getContentType(...)"<<endl;
  QDomNode n4;
  for( n4 = folderNode.firstChild(); !n4.isNull(); n4 = n4.nextSibling() ) {
    QDomElement e = n4.toElement();

    if ( e.tagName() == "contentclass" ) {
      QString contentclass( e.text() );
      if ( contentclass == "urn:content-classes:contactfolder" )
        return KPIM::FolderLister::Contact;
      if ( contentclass == "urn:content-classes:calendarfolder" )
        return KPIM::FolderLister::Event;
      if ( contentclass == "urn:content-classes:taskfolder" )
        return KPIM::FolderLister::Todo;
      if ( contentclass == "urn:content-classes:journalfolder" )
        return KPIM::FolderLister::Journal;
      if ( contentclass == "urn:content-classes:folder" )
        return KPIM::FolderLister::Folder;
    }
  }
  return KPIM::FolderLister::Unknown;
}

bool ExchangeGlobals::getFolderHasSubs( const QDomNode &folderNode )
{
  QString hassubs = folderNode.namedItem( "hassubs" ).toElement().text();
  return hassubs == "1";
}

KIO::Job *ExchangeGlobals::createListFoldersJob( const KURL &url )
{
  QDomDocument doc;
  QDomElement root = WebdavHandler::addDavElement(  doc, doc, "d:propfind" );
  QDomElement prop = WebdavHandler::addElement(  doc, root, "d:prop" );
  WebdavHandler::addElement( doc, prop, "d:displayname" );
  WebdavHandler::addElement( doc, prop, "d:contentclass" );
  WebdavHandler::addElement( doc, prop, "d:hassubs" );

  kdDebug(7000) << "props: " << doc.toString() << endl;
  return KIO::davPropFind( url, doc, "1", false );
}

KIO::TransferJob *ExchangeGlobals::createListItemsJob( const KURL &url )
{
  QDomDocument doc;
  QDomElement root = WebdavHandler::addDavElement(  doc, doc, "d:propfind" );
  QDomElement prop = WebdavHandler::addElement(  doc, root, "d:prop" );
  WebdavHandler::addElement( doc, prop, "d:getetag" );
  WebdavHandler::addElement( doc, prop, "d:contentclass" );
  kdDebug(5800) << "props = "<< doc.toString() << endl;
  return KIO::davPropFind( url, doc, "1", false );
}

KIO::TransferJob *ExchangeGlobals::createDownloadJob( KPIM::GroupwareDataAdaptor *adaptor,
                        const KURL &url, KPIM::FolderLister::ContentType ctype )
{
kdDebug() << "ExchangeGlobals::createDownloadJob()" << endl;
kdDebug() << "ctype=" << ctype << endl;
kdDebug() << "Person=" << KPIM::FolderLister::Contact << ", "
          << "Appointment=" << KPIM::FolderLister::Event << ", "
          << "Task=" << KPIM::FolderLister::Todo << ", "
          << "Journal=" << KPIM::FolderLister::Journal << ", "
          << "Message=" << KPIM::FolderLister::Message << endl;
  // Don't use an <allprop/> request!

  QDomDocument doc;
  QDomElement root = WebdavHandler::addDavElement( doc, doc, "d:propfind" );
  QDomElement prop = WebdavHandler::addElement( doc, root, "d:prop" );
  QDomAttr att_h = doc.createAttribute( "xmlns:h" );
  att_h.setValue( "urn:schemas:mailheader:" );
  root.setAttributeNode( att_h );

  QDomAttr att_m = doc.createAttribute( "xmlns:m" );
  att_m.setValue( "urn:schemas:httpmail:" );
  root.setAttributeNode( att_m );

  switch ( ctype ) {
    case KPIM::FolderLister::Event:
        KCal::ExchangeConverterCalendar::createRequestAppointment( doc, prop );
        break;
    case KPIM::FolderLister::Todo:
        KCal::ExchangeConverterCalendar::createRequestTask( doc, prop );
        break;
    case KPIM::FolderLister::Journal:
    case KPIM::FolderLister::Message:
        KCal::ExchangeConverterCalendar::createRequestJournal( doc, prop );
        break;
    case KPIM::FolderLister::Contact:
        KABC::ExchangeConverterContact::createRequest( doc, prop );
        break;
    default:
        break;
  }

  kdDebug(7000) << "doc: " << doc.toString() << endl;
  KURL authURL = url;
  KIO::DavJob *job = KIO::davPropFind( authURL, doc, "0", false );
/*  KURL httpurl( url );
  QString proto("http");
  httpurl.setProtocol( proto );
  KIO::TransferJob *job = KIO::get(httpurl, false, false);
  job->addMetaData("customHTTPHeader", "Translate: f");
  job->addMetaData("cache", "reload");*/
  return job;
}

KIO::Job *ExchangeGlobals::createRemoveJob( const KURL &uploadurl,
       const KPIM::GroupwareUploadItem::List &deletedItems )
{
  QStringList urls;
  KPIM::GroupwareUploadItem::List::const_iterator it;
  kdDebug() << " ExchangeGlobals::createRemoveJob: , URL="<<uploadurl.url()<<endl;
  for ( it = deletedItems.begin(); it != deletedItems.end(); ++it ) {
    //kdDebug(7000) << "Delete: " << endl << format.toICalString(*it) << endl;
    kdDebug() << "Delete: " <<   (*it)->url().url() << endl;
    KURL url( uploadurl );
    url.setPath( (*it)->url().path() );
    if ( !url.isEmpty() )
      urls << url.url();
    kdDebug() << "Delete (Mod) : " <<   url.url() << endl;
  }
  return KIO::del( urls, false, false );
}

// FIXME: This is exactly the same code as in the OGo resource, except that
// it calls getContentType of the ExchangeGlobals class, instead of the one
// from OGoGlobals!!!!
bool ExchangeGlobals::interpretListItemsJob( KPIM::GroupwareDataAdaptor *adaptor,
    KIO::Job *job, const QString &/*jobData*/ )
{
kdDebug()<<"ExchangeGlobals::interpretListItemsJob"<<endl;
  KIO::DavJob *davjob = dynamic_cast<KIO::DavJob *>(job);

  if ( !davjob ) {
    return false;
  }
  QDomDocument doc = davjob->response();

  kdDebug(7000) << " Doc: " << doc.toString() << endl;
  kdDebug(7000) << " IdMapper: " << adaptor->idMapper()->asString() << endl;

  QDomElement docElem = doc.documentElement();
  QDomNode n = docElem.firstChild();
  while( !n.isNull() ) {
    QDomElement e = n.toElement(); // try to convert the node to an element.
    n = n.nextSibling();
    if ( e.isNull() )
      continue;

    const KURL &entry( e.namedItem("href").toElement().text() );
    QDomElement propstat = e.namedItem("propstat").toElement();
    if ( propstat.isNull() )
      continue;
    QDomElement prop = propstat.namedItem( "prop" ).toElement();
    if ( prop.isNull() )
      continue;
    QDomElement elem = prop.namedItem("getetag").toElement();
    const QString &newFingerprint = elem.text();
    if ( elem.isNull() || newFingerprint.isEmpty() )
      continue;

    KPIM::FolderLister::ContentType type = getContentType( prop );

    adaptor->processDownloadListItem( entry, newFingerprint, type );
  }

  return true;
}

bool ExchangeGlobals::interpretCalendarDownloadItemsJob( KCal::CalendarAdaptor *adaptor,
                                         KIO::Job *job, const QString &/*jobData*/ )
{
  KIO::DavJob *davjob = dynamic_cast<KIO::DavJob*>(job);
  if ( !davjob || !adaptor ) return false;

kdDebug() << "ExchangeGlobals::interpretCalendarDownloadItemsJob(): QDomDocument="
          << endl << davjob->response().toString() << endl;
  KCal::ExchangeConverterCalendar conv;
  conv.setTimeZone( adaptor->resource()->timeZoneId() );
  KCal::Incidence::List incidences = conv.parseWebDAV( davjob->response() );

  bool res = false;
  KCal::Incidence::List::Iterator it = incidences.begin();
  for ( ; it != incidences.end(); ++it ) {
    QString fpr = (*it)->customProperty( "KDEPIM-Exchange-Resource", "fingerprint" );
    KURL href( (*it)->customProperty( "KDEPIM-Exchange-Resource", "href" ) );
    adaptor->calendarItemDownloaded( (*it), (*it)->uid(), href, fpr, href.prettyURL() );
    res = true;
  }
  return res;
}

bool ExchangeGlobals::interpretAddressBookDownloadItemsJob(
      KABC::AddressBookAdaptor *adaptor, KIO::Job *job, const QString &/*jobData*/ )
{
  KIO::DavJob *davjob = dynamic_cast<KIO::DavJob*>(job);
  if ( !davjob || !adaptor ) return false;

kdDebug() << "ExchangeGlobals::interpretAddressBookDownloadItemsJob(): QDomDocument="
          << endl << davjob->response().toString() << endl;
  KABC::ExchangeConverterContact conv;
  KABC::Addressee::List addressees = conv.parseWebDAV( davjob->response() );

  bool res = false;
  KABC::Addressee::List::Iterator it = addressees.begin();
  for ( ; it != addressees.end(); ++it ) {
    QString fpr = (*it).custom( "KDEPIM-Exchange-Resource", "fingerprint" );
    KURL href( (*it).custom( "KDEPIM-Exchange-Resource", "href" ) );
    adaptor->addressbookItemDownloaded( (*it), (*it).uid(), href, fpr, href.prettyURL() );
    res = true;
  }
  return res;
}

<commit_msg>Fix problem when recieving an error in the iterm listing from Exchange<commit_after>/*
    This file is part of kdepim.

    Copyright (c) 2005 Reinhold Kainhofer <reinhold@kainhofer.com>

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

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

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "exchangeglobals.h"
#include <webdavhandler.h>
#include <groupwaredataadaptor.h>
#include "exchangeconvertercalendar.h"
#include "exchangeconvertercontact.h"
#include <calendaradaptor.h>
#include <addressbookadaptor.h>

#include <libkcal/resourcecached.h>
#include <libemailfunctions/idmapper.h>
#include <kio/job.h>
#include <kio/davjob.h>
#include <kdebug.h>

KPIM::FolderLister::ContentType ExchangeGlobals::getContentType( const QDomElement &prop )
{
  const QString &contentclass = prop.namedItem("contentclass").toElement().text();
kdDebug()<<"contentclass: "<<contentclass<<endl;
  return getContentType( contentclass );
}

KPIM::FolderLister::ContentType ExchangeGlobals::getContentType( const QString &contentclass )
{
  if ( contentclass == "urn:content-classes:appointment" )
    return KPIM::FolderLister::Event;
  if ( contentclass == "urn:content-classes:task" )
    return KPIM::FolderLister::Todo;
  if ( contentclass == "urn:content-classes:message" )
    return KPIM::FolderLister::Message;
  if ( contentclass == "urn:content-classes:person" )
    return KPIM::FolderLister::Contact;
  return KPIM::FolderLister::Unknown;
}

KPIM::FolderLister::ContentType ExchangeGlobals::getContentType( const QDomNode &folderNode )
{
kdDebug()<<"ExchangeGlobals::getContentType(...)"<<endl;
  QDomNode n4;
  for( n4 = folderNode.firstChild(); !n4.isNull(); n4 = n4.nextSibling() ) {
    QDomElement e = n4.toElement();

    if ( e.tagName() == "contentclass" ) {
      QString contentclass( e.text() );
      if ( contentclass == "urn:content-classes:contactfolder" )
        return KPIM::FolderLister::Contact;
      if ( contentclass == "urn:content-classes:calendarfolder" )
        return KPIM::FolderLister::Event;
      if ( contentclass == "urn:content-classes:taskfolder" )
        return KPIM::FolderLister::Todo;
      if ( contentclass == "urn:content-classes:journalfolder" )
        return KPIM::FolderLister::Journal;
      if ( contentclass == "urn:content-classes:folder" )
        return KPIM::FolderLister::Folder;
    }
  }
  return KPIM::FolderLister::Unknown;
}

bool ExchangeGlobals::getFolderHasSubs( const QDomNode &folderNode )
{
  QString hassubs = folderNode.namedItem( "hassubs" ).toElement().text();
  return hassubs == "1";
}

KIO::Job *ExchangeGlobals::createListFoldersJob( const KURL &url )
{
  QDomDocument doc;
  QDomElement root = WebdavHandler::addDavElement(  doc, doc, "d:propfind" );
  QDomElement prop = WebdavHandler::addElement(  doc, root, "d:prop" );
  WebdavHandler::addElement( doc, prop, "d:displayname" );
  WebdavHandler::addElement( doc, prop, "d:contentclass" );
  WebdavHandler::addElement( doc, prop, "d:hassubs" );

  kdDebug(7000) << "props: " << doc.toString() << endl;
  return KIO::davPropFind( url, doc, "1", false );
}

KIO::TransferJob *ExchangeGlobals::createListItemsJob( const KURL &url )
{
  QDomDocument doc;
  QDomElement root = WebdavHandler::addDavElement(  doc, doc, "d:propfind" );
  QDomElement prop = WebdavHandler::addElement(  doc, root, "d:prop" );
  WebdavHandler::addElement( doc, prop, "d:getetag" );
  WebdavHandler::addElement( doc, prop, "d:contentclass" );
  kdDebug(5800) << "props = "<< doc.toString() << endl;
  return KIO::davPropFind( url, doc, "1", false );
}

KIO::TransferJob *ExchangeGlobals::createDownloadJob( KPIM::GroupwareDataAdaptor *adaptor,
                        const KURL &url, KPIM::FolderLister::ContentType ctype )
{
kdDebug() << "ExchangeGlobals::createDownloadJob()" << endl;
kdDebug() << "ctype=" << ctype << endl;
kdDebug() << "Person=" << KPIM::FolderLister::Contact << ", "
          << "Appointment=" << KPIM::FolderLister::Event << ", "
          << "Task=" << KPIM::FolderLister::Todo << ", "
          << "Journal=" << KPIM::FolderLister::Journal << ", "
          << "Message=" << KPIM::FolderLister::Message << endl;
  // Don't use an <allprop/> request!

  QDomDocument doc;
  QDomElement root = WebdavHandler::addDavElement( doc, doc, "d:propfind" );
  QDomElement prop = WebdavHandler::addElement( doc, root, "d:prop" );
  QDomAttr att_h = doc.createAttribute( "xmlns:h" );
  att_h.setValue( "urn:schemas:mailheader:" );
  root.setAttributeNode( att_h );

  QDomAttr att_m = doc.createAttribute( "xmlns:m" );
  att_m.setValue( "urn:schemas:httpmail:" );
  root.setAttributeNode( att_m );

  switch ( ctype ) {
    case KPIM::FolderLister::Event:
        KCal::ExchangeConverterCalendar::createRequestAppointment( doc, prop );
        break;
    case KPIM::FolderLister::Todo:
        KCal::ExchangeConverterCalendar::createRequestTask( doc, prop );
        break;
    case KPIM::FolderLister::Journal:
    case KPIM::FolderLister::Message:
        KCal::ExchangeConverterCalendar::createRequestJournal( doc, prop );
        break;
    case KPIM::FolderLister::Contact:
        KABC::ExchangeConverterContact::createRequest( doc, prop );
        break;
    default:
        break;
  }

  kdDebug(7000) << "doc: " << doc.toString() << endl;
  KURL authURL = url;
  KIO::DavJob *job = KIO::davPropFind( authURL, doc, "0", false );
/*  KURL httpurl( url );
  QString proto("http");
  httpurl.setProtocol( proto );
  KIO::TransferJob *job = KIO::get(httpurl, false, false);
  job->addMetaData("customHTTPHeader", "Translate: f");
  job->addMetaData("cache", "reload");*/
  return job;
}

KIO::Job *ExchangeGlobals::createRemoveJob( const KURL &uploadurl,
       const KPIM::GroupwareUploadItem::List &deletedItems )
{
  QStringList urls;
  KPIM::GroupwareUploadItem::List::const_iterator it;
  kdDebug() << " ExchangeGlobals::createRemoveJob: , URL="<<uploadurl.url()<<endl;
  for ( it = deletedItems.begin(); it != deletedItems.end(); ++it ) {
    //kdDebug(7000) << "Delete: " << endl << format.toICalString(*it) << endl;
    kdDebug() << "Delete: " <<   (*it)->url().url() << endl;
    KURL url( uploadurl );
    url.setPath( (*it)->url().path() );
    if ( !url.isEmpty() )
      urls << url.url();
    kdDebug() << "Delete (Mod) : " <<   url.url() << endl;
  }
  return KIO::del( urls, false, false );
}

// FIXME: This is exactly the same code as in the OGo resource, except that
// it calls getContentType of the ExchangeGlobals class, instead of the one
// from OGoGlobals!!!!
bool ExchangeGlobals::interpretListItemsJob( KPIM::GroupwareDataAdaptor *adaptor,
    KIO::Job *job, const QString &/*jobData*/ )
{
kdDebug()<<"ExchangeGlobals::interpretListItemsJob"<<endl;
  KIO::DavJob *davjob = dynamic_cast<KIO::DavJob *>(job);

  if ( !davjob ) {
    return false;
  }
  QDomDocument doc = davjob->response();

  kdDebug(7000) << " Doc: " << doc.toString() << endl;
  kdDebug(7000) << " IdMapper: " << adaptor->idMapper()->asString() << endl;

  QDomElement docElem = doc.documentElement();
  QDomNode n = docElem.firstChild();
  while( !n.isNull() ) {
    QDomElement e = n.toElement(); // try to convert the node to an element.
    n = n.nextSibling();
    if ( e.isNull() )
      continue;

    const KURL &entry( e.namedItem("href").toElement().text() );
    QDomElement propstat = e.namedItem("propstat").toElement();
    if ( propstat.isNull() )
      continue;
    QDomElement prop = propstat.namedItem( "prop" ).toElement();
    if ( prop.isNull() )
      continue;
    QDomElement elem = prop.namedItem("getetag").toElement();
    const QString &newFingerprint = elem.text();
    if ( elem.isNull() || newFingerprint.isEmpty() )
      continue;

    KPIM::FolderLister::ContentType type = getContentType( prop );

    if (type != KPIM::FolderLister::Unknown) { // Don't queue bad entries
      adaptor->processDownloadListItem( entry, newFingerprint, type );
    }
  }

  return true;
}

bool ExchangeGlobals::interpretCalendarDownloadItemsJob( KCal::CalendarAdaptor *adaptor,
                                         KIO::Job *job, const QString &/*jobData*/ )
{
  KIO::DavJob *davjob = dynamic_cast<KIO::DavJob*>(job);
  if ( !davjob || !adaptor ) return false;

kdDebug() << "ExchangeGlobals::interpretCalendarDownloadItemsJob(): QDomDocument="
          << endl << davjob->response().toString() << endl;
  KCal::ExchangeConverterCalendar conv;
  conv.setTimeZone( adaptor->resource()->timeZoneId() );
  KCal::Incidence::List incidences = conv.parseWebDAV( davjob->response() );

  bool res = false;
  KCal::Incidence::List::Iterator it = incidences.begin();
  for ( ; it != incidences.end(); ++it ) {
    QString fpr = (*it)->customProperty( "KDEPIM-Exchange-Resource", "fingerprint" );
    KURL href( (*it)->customProperty( "KDEPIM-Exchange-Resource", "href" ) );
    adaptor->calendarItemDownloaded( (*it), (*it)->uid(), href, fpr, href.prettyURL() );
    res = true;
  }
  return res;
}

bool ExchangeGlobals::interpretAddressBookDownloadItemsJob(
      KABC::AddressBookAdaptor *adaptor, KIO::Job *job, const QString &/*jobData*/ )
{
  KIO::DavJob *davjob = dynamic_cast<KIO::DavJob*>(job);
  if ( !davjob || !adaptor ) return false;

kdDebug() << "ExchangeGlobals::interpretAddressBookDownloadItemsJob(): QDomDocument="
          << endl << davjob->response().toString() << endl;
  KABC::ExchangeConverterContact conv;
  KABC::Addressee::List addressees = conv.parseWebDAV( davjob->response() );

  bool res = false;
  KABC::Addressee::List::Iterator it = addressees.begin();
  for ( ; it != addressees.end(); ++it ) {
    QString fpr = (*it).custom( "KDEPIM-Exchange-Resource", "fingerprint" );
    KURL href( (*it).custom( "KDEPIM-Exchange-Resource", "href" ) );
    adaptor->addressbookItemDownloaded( (*it), (*it).uid(), href, fpr, href.prettyURL() );
    res = true;
  }
  return res;
}

<|endoftext|>