<commit_before>/*
The MIT License (MIT)

Copyright (c) 2016 Liav Turkia

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.
*/
#include <MACE/Utility/Process.h>
#include <MACE/Core/System.h>

#include <cstring>
#include <memory>

#ifdef MACE_POSIX
#	include <sys/wait.h>
#	include <signal.h>
#	include <cstdlib>
#endif//MACE_POSIX

namespace mc {
	void Process::init() {
		if (path == nullptr) {
			throw NullPointerError("The path can\'t be null!");
		} else if (args == nullptr) {
			throw NullPointerError("The args can\'t be null!");
		} else if (isCreated()) {
			throw InitializationFailedError("Can\'t call init() on an already initialized Process");
		}

		os::clearError();

#ifdef MACE_WINAPI
		STARTUPINFO startupInfo;

		ZeroMemory(&startupInfo, sizeof(startupInfo));
		startupInfo.cb = sizeof(startupInfo);
		ZeroMemory(&process, sizeof(process));

		startupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
		startupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
		startupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);

		/*
		Ok let me rant for a second here. CreateProcessA does not accept a const char* for its args.
		THIS IS A MASSIVE PROBLEM
		args has to be const char* because of the possibility that someone will initialize a process
		with a string literal. In fact, it is most likely going to be a string literal, like so:
		Process proc = Process("myprog", "-a --argument");
		This can't be ignored because then G++ and clang++ raise a bunch of warnings how its a deprecated conversion
		from string literal (const char*) to character array (char*)
		I mean I agree with them. You should never remove constness of a variable...
		Meaning the function declaration has to say that args is a const char*...
		BUT WINDOWS DECIDED THAT THAT IS A BAD IDEA
		POSIX is somehow reasonable by allowing const char* in the execl function but NO WINDOWS
		CANT DO THAT
		So we have to do this dumb method of copying the const char* into a temporary mutable
		buffer for the string so windows can have its way.
		This is why Linux will always be the superior platform for development, Microsoft.
		Because of things like this.
		*/

		CreateProcessA((std::string(path) + std::string(args)).c_str(), nullptr, nullptr, nullptr, false, 0, nullptr, nullptr, &startupInfo, &process);
#elif defined(MACE_POSIX)
		process = fork();

		if (process == 0) {
			execl(path, args, nullptr);
			std::exit(-1);
		} else if (process == -1) {
			os::checkError(__LINE__, __FILE__, "Failed to fork process");

			throw NullPointerError("Failed to fork process");
		}
#endif

		os::checkError(__LINE__, __FILE__, "Failed to create Process");

		created = true;

	}

	void Process::destroy() {
		os::clearError();

		if (!isCreated()) {
			throw InitializationFailedError("Can\'t destroy an unitialized Process");
		}

#ifdef MACE_WINAPI
		if (isRunning()) {
			if (!TerminateProcess(process.hProcess, 1)) {
				os::checkError(__LINE__, __FILE__, "Failed to terminate process");

				throw AssertionFailedError("Failed to terminate process");
			}
		}

		if (!CloseHandle(process.hProcess)) {
			os::checkError(__LINE__, __FILE__, "Failed to close handle to process");

			throw AssertionFailedError("Failed to close handle to process");
		}

		if (!CloseHandle(process.hThread)) {
			os::checkError(__LINE__, __FILE__, "Failed to close handle to process thread");

			throw AssertionFailedError("Failed to close handle to process thread");
		}
#elif defined(MACE_POSIX)
		if (isRunning()) {
			//hasta la vista baby
			int result = kill(process, SIGTERM);
			if (result != 0) {
				if (result == ESRCH) {
					//meaning the process never even existed or was stopped already.
					os::clearError();
				} else {
					os::checkError(__LINE__, __FILE__, "Failed to send SIGTERM to process");

					throw AssertionFailedError("Failed to kill process");

				}
			}
		}
#endif

		created = false;

		os::checkError(__LINE__, __FILE__, "Failed to destroy Process");
	}

	int Process::wait() {
		os::clearError(__LINE__, __FILE__);

		if (!isCreated()) {
			throw InitializationFailedError("Can\'t use wait() on unitialized Process");
		}

#ifdef MACE_WINAPI
		WaitForSingleObject(process.hProcess, INFINITE);

		os::checkError(__LINE__, __FILE__, "Error waiting for process to end");

		DWORD status;
		if (GetExitCodeProcess(process.hProcess, &status) == 0) {
			os::checkError(__LINE__, __FILE__, "Failed to retrieve exit code for process");

			throw AssertionFailedError("Failed to retrieve exit code for process");
		}

		os::checkError(__LINE__, __FILE__, "Error retrieving exit code for process");

		return static_cast<int>(status);
#elif defined(MACE_POSIX)
		int status;

		const pid_t result = waitpid(process, &status, WUNTRACED | WCONTINUED);
		if (result != process) {
			os::checkError(__LINE__, __FILE__, "waitpid() returned exit code " + std::to_string(result));

			throw AssertionFailedError("waitpid() returned exit code " + std::to_string(result));
		}

		os::checkError(__LINE__, __FILE__, "Error waiting for process to end");

		if (WIFEXITED(status)) {
			return WEXITSTATUS(status);
		} else if (WIFSIGNALED(status)) {
			return WTERMSIG(status);
		} else if (WIFSTOPPED(status)) {
			return WSTOPSIG(status);
		}

		os::checkError(__LINE__, __FILE__, "Error getting error code of process");

		return status;
#endif
	}

	bool Process::isRunning() const {
		if (!isCreated()) {
			return false;
		}

#ifdef MACE_WINAPI
		return WaitForSingleObject(process.hProcess, 0) == WAIT_TIMEOUT;
#elif defined(MACE_POSIX)
		return kill(process, 0) == 0;
#endif
	}

	bool Process::isCreated() const {
		return created;
	}

	void Process::setPath(const char * p) {
		path = p;
	}

	const char * Process::getPath() const {
		return path;
	}

	void Process::setArgs(const char * a) {
		args = a;
	}

	const char * Process::getArgs() const {
		return args;
	}

	Process::Process(const char * p, const char * a) : path(p), args(a) {}

	Process::Process(const std::string & path, std::string & args) : Process(path.c_str(), args.c_str()) {}

	Process::Process() : Process(nullptr, nullptr) {}

	Process::~Process() {
		if (isCreated()) {
			destroy();
		}
	}
}//mc
<commit_msg>tried again to fixed destroy() in Process<commit_after>/*
The MIT License (MIT)

Copyright (c) 2016 Liav Turkia

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.
*/
#include <MACE/Utility/Process.h>
#include <MACE/Core/System.h>

#include <cstring>
#include <memory>

#ifdef MACE_POSIX
#	include <sys/wait.h>
#	include <signal.h>
#	include <cstdlib>
#endif//MACE_POSIX

namespace mc {
	void Process::init() {
		if (path == nullptr) {
			throw NullPointerError("The path can\'t be null!");
		} else if (args == nullptr) {
			throw NullPointerError("The args can\'t be null!");
		} else if (isCreated()) {
			throw InitializationFailedError("Can\'t call init() on an already initialized Process");
		}

		os::clearError();

#ifdef MACE_WINAPI
		STARTUPINFO startupInfo;

		ZeroMemory(&startupInfo, sizeof(startupInfo));
		startupInfo.cb = sizeof(startupInfo);
		ZeroMemory(&process, sizeof(process));

		startupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
		startupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
		startupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);

		/*
		Ok let me rant for a second here. CreateProcessA does not accept a const char* for its args.
		THIS IS A MASSIVE PROBLEM
		args has to be const char* because of the possibility that someone will initialize a process
		with a string literal. In fact, it is most likely going to be a string literal, like so:
		Process proc = Process("myprog", "-a --argument");
		This can't be ignored because then G++ and clang++ raise a bunch of warnings how its a deprecated conversion
		from string literal (const char*) to character array (char*)
		I mean I agree with them. You should never remove constness of a variable...
		Meaning the function declaration has to say that args is a const char*...
		BUT WINDOWS DECIDED THAT THAT IS A BAD IDEA
		POSIX is somehow reasonable by allowing const char* in the execl function but NO WINDOWS
		CANT DO THAT
		So we have to do this dumb method of copying the const char* into a temporary mutable
		buffer for the string so windows can have its way.
		This is why Linux will always be the superior platform for development, Microsoft.
		Because of things like this.
		*/

		CreateProcessA((std::string(path) + std::string(args)).c_str(), nullptr, nullptr, nullptr, false, 0, nullptr, nullptr, &startupInfo, &process);
#elif defined(MACE_POSIX)
		process = fork();

		if (process == 0) {
			execl(path, args, nullptr);
			std::exit(-1);
		} else if (process == -1) {
			os::checkError(__LINE__, __FILE__, "Failed to fork process");

			throw NullPointerError("Failed to fork process");
		}
#endif

		os::checkError(__LINE__, __FILE__, "Failed to create Process");

		created = true;

	}

	void Process::destroy() {
		os::clearError();

		if (!isCreated()) {
			throw InitializationFailedError("Can\'t destroy an unitialized Process");
		}

#ifdef MACE_WINAPI
		if (isRunning()) {
			//hasta la vista baby
			if (!TerminateProcess(process.hProcess, 1)) {
				os::checkError(__LINE__, __FILE__, "Failed to terminate process");

				throw AssertionFailedError("Failed to terminate process");
			}
		}

		if (!CloseHandle(process.hProcess)) {
			os::checkError(__LINE__, __FILE__, "Failed to close handle to process");

			throw AssertionFailedError("Failed to close handle to process");
		}

		if (!CloseHandle(process.hThread)) {
			os::checkError(__LINE__, __FILE__, "Failed to close handle to process thread");

			throw AssertionFailedError("Failed to close handle to process thread");
		}
#elif defined(MACE_POSIX)
		int result = kill(process, SIGTERM);
		if (result != 0) {
			if (result == ESRCH) {
				//meaning the process never even existed or was stopped already.
				os::clearError();
			} else {
				os::checkError(__LINE__, __FILE__, "Failed to send SIGTERM to process");

				throw AssertionFailedError("Failed to kill process");

			}
		}

#endif

		created = false;

		os::checkError(__LINE__, __FILE__, "Failed to destroy Process");
	}

	int Process::wait() {
		os::clearError(__LINE__, __FILE__);

		if (!isCreated()) {
			throw InitializationFailedError("Can\'t use wait() on unitialized Process");
		}

#ifdef MACE_WINAPI
		WaitForSingleObject(process.hProcess, INFINITE);

		os::checkError(__LINE__, __FILE__, "Error waiting for process to end");

		DWORD status;
		if (GetExitCodeProcess(process.hProcess, &status) == 0) {
			os::checkError(__LINE__, __FILE__, "Failed to retrieve exit code for process");

			throw AssertionFailedError("Failed to retrieve exit code for process");
		}

		os::checkError(__LINE__, __FILE__, "Error retrieving exit code for process");

		return static_cast<int>(status);
#elif defined(MACE_POSIX)
		int status;

		const pid_t result = waitpid(process, &status, WUNTRACED | WCONTINUED);
		if (result != process) {
			os::checkError(__LINE__, __FILE__, "waitpid() returned exit code " + std::to_string(result));

			throw AssertionFailedError("waitpid() returned exit code " + std::to_string(result));
		}

		os::checkError(__LINE__, __FILE__, "Error waiting for process to end");

		if (WIFEXITED(status)) {
			return WEXITSTATUS(status);
		} else if (WIFSIGNALED(status)) {
			return WTERMSIG(status);
		} else if (WIFSTOPPED(status)) {
			return WSTOPSIG(status);
		}

		os::checkError(__LINE__, __FILE__, "Error getting error code of process");

		return status;
#endif
	}

	bool Process::isRunning() const {
		if (!isCreated()) {
			return false;
		}

#ifdef MACE_WINAPI
		return WaitForSingleObject(process.hProcess, 0) == WAIT_TIMEOUT;
#elif defined(MACE_POSIX)
		return kill(process, 0) == 0;
#endif
	}

	bool Process::isCreated() const {
		return created;
	}

	void Process::setPath(const char * p) {
		path = p;
	}

	const char * Process::getPath() const {
		return path;
	}

	void Process::setArgs(const char * a) {
		args = a;
	}

	const char * Process::getArgs() const {
		return args;
	}

	Process::Process(const char * p, const char * a) : path(p), args(a) {}

	Process::Process(const std::string & path, std::string & args) : Process(path.c_str(), args.c_str()) {}

	Process::Process() : Process(nullptr, nullptr) {}

	Process::~Process() {
		if (isCreated()) {
			destroy();
		}
	}
}//mc
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <cstdio>

#include <seqan/sequence.h>
#include <seqan/file.h>

using namespace seqan;
using namespace std;

int main()
{
///Create a fasta file:
/// Open a standard library stream for binary write.
/// You can use both C++ iostreams or old style FILE pointer.
	FILE * fl = fopen("testfile.fa", "wb");
    write(fl, "aacagtattagaccactaggaccct", "a test file", Fasta());
	close (fl);
///Read a fasta file into a string:
/// Open a stram for binary read.
	fstream fstrm;
	fstrm.open("testfile.fa", ios_base::in | ios_base::binary);
	String<char> fasta_tag;
	String<Dna> fasta_seq;

	readMeta(fstrm, fasta_tag, Fasta());
	cout << fasta_tag << "\n";	//prints "a test file"

	read(fstrm, fasta_seq, Fasta());
	cout << fasta_seq << "\n";	//prints the sequence
	fstrm.close();
///Opens a file using a file reader string:
	String<Dna, FileReader<Fasta> > fr("testfile.fa");
	cout << fr << "\n";			//prints the sequence

	return 0;
}

<commit_msg><commit_after>///A tutorial about the use of files and file formats.
#include <iostream>
#include <fstream>
#include <cstdio>

#include <seqan/sequence.h>
#include <seqan/file.h>

using namespace seqan;
using namespace std;

int main()
{
///Open a standard library stream for binary write.
///You can use both C++ iostreams or old style FILE pointer.
///The file format is Fasta.
	FILE * fl = fopen("testfile.fa", "wb");
    write(fl, "aacagtattagaccactaggaccct", "a test file", Fasta());
	close (fl);
///Read a fasta file.
	fstream fstrm;
	fstrm.open("testfile.fa", ios_base::in | ios_base::binary);
	String<char> fasta_tag;
	String<Dna> fasta_seq;
///Read the meta-information.
	readMeta(fstrm, fasta_tag, Fasta());
	cout << fasta_tag << "\n";	//prints "a test file"
///Read the Fasta file.
	read(fstrm, fasta_seq, Fasta());
	cout << fasta_seq << "\n";	//prints the sequence
	fstrm.close();
///Open a file using a file reader string.
	String<Dna, FileReader<Fasta> > fr("testfile.fa");
	cout << fr << "\n";			//prints the sequence
	return 0;
}

<|endoftext|>


<commit_before>//
// Created by phitherek on 20.11.15.
//
#include <iostream>
#include <cstdlib>
#include "Converter.h"
#include "ConversionError.h"

using namespace std;

int main() {
    cout << "ConversionTest for OziExplorer to UI-View Converter v. 0.2 (C) 2015 by Phitherek_ SO9PH" << endl;
    try {
        Converter c("siatka.map", "siatka.inf");
        c.convert();
    } catch(ConversionError& e) {
        cerr << "Caught ConversionError: " << e.what() << endl;
        cout << "Failure!" << endl;
        return EXIT_FAILURE;
    }
    cout << "Success!" << endl;
    return EXIT_SUCCESS;
}<commit_msg>Custom endline handler added to ConversionTest output.<commit_after>//
// Created by phitherek on 20.11.15.
//
#include <iostream>
#include <cstdlib>
#include "Converter.h"
#include "ConversionError.h"
#include "Helper.h"

using namespace std;

int main() {
    cout << "ConversionTest for OziExplorer to UI-View Converter v. 0.2 (C) 2015 by Phitherek_ SO9PH" << Helper::endline();
    try {
        Converter c("siatka.map", "siatka.inf");
        c.convert();
    } catch(ConversionError& e) {
        cerr << "Caught ConversionError: " << e.what() << Helper::endline();
        cout << "Failure!" << Helper::endline();
        return EXIT_FAILURE;
    }
    cout << "Success!" << Helper::endline();
    return EXIT_SUCCESS;
}<|endoftext|>


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

   The MIT License

   Copyright (c) 2010 Interactive Visualization and Data Analysis Group.

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

//!    File   : OBJGeoConverter.cpp
//!    Author : Jens Krueger
//!             IVCI & DFKI & MMCI, Saarbruecken
//!             SCI Institute, University of Utah
//!    Date   : July 2010
//
//!    Copyright (C) 2010 DFKI, MMCI, SCI Institute

#include "OBJGeoConverter.h"
#include "Controller/Controller.h"
#include "SysTools.h"
#include "Mesh.h"
#include <fstream>
#include "TuvokIOError.h"

using namespace tuvok;

OBJGeoConverter::OBJGeoConverter() :
  AbstrGeoConverter()
{
  m_vConverterDesc = "Wavefront Object File";
  m_vSupportedExt.push_back("OBJ");
}

inline int OBJGeoConverter::CountOccurences(const std::string& str, const std::string& substr) {
  size_t found = str.find_first_of(substr);
  int count = 0;
  while (found!=std::string::npos)
  {
    count++;
    found=str.find_first_of(substr,found+1);
  }
  return count;
}

inline std::string OBJGeoConverter::TrimToken(const std::string& Src,
                                              const std::string& c,
                                              bool bOnlyFirst)
{
  size_t off = Src.find_first_of(c);
  if (off == std::string::npos) return std::string();
  if (bOnlyFirst) {
    return Src.substr(off+1);
  } else {
    size_t p1 = Src.find_first_not_of(c,off);
    if (p1 == std::string::npos) return std::string();
    return Src.substr(p1);
  }
}

void OBJGeoConverter::AddToMesh(const VertVec& vertices,
                                IndexVec& v, IndexVec& n,
                                IndexVec& t, IndexVec& c,
                                IndexVec& VertIndices, IndexVec& NormalIndices,
                                IndexVec& TCIndices, IndexVec& COLIndices) {
  if (v.size() > 3) {
    // per OBJ definition any poly with more than 3 verices has
    // to be planar and convex, so we can savely triangulate it

    SortByGradient(vertices,v,n,t,c);

    for (size_t i = 0;i<v.size()-2;i++) {
      IndexVec mv, mn, mt, mc;
      mv.push_back(v[0]);mv.push_back(v[i+1]);mv.push_back(v[i+2]);
      if (n.size() == v.size()) {mn.push_back(n[i]);mn.push_back(n[i+1]);mn.push_back(n[i+2]);}
      if (t.size() == v.size()) {mt.push_back(t[i]);mt.push_back(t[i+1]);mt.push_back(t[i+2]);}
      if (c.size() == v.size()) {mc.push_back(c[i]);mc.push_back(c[i+1]);mc.push_back(c[i+2]);}

      AddToMesh(vertices,
                mv,mn,mt,mc,
                VertIndices,
                NormalIndices,
                TCIndices,
                COLIndices);
    }

  } else {
    for (size_t i = 0;i<v.size();i++) {
      VertIndices.push_back(v[i]);
      if (n.size() == v.size()) NormalIndices.push_back(n[i]);
      if (t.size() == v.size()) TCIndices.push_back(t[i]);
      if (c.size() == v.size()) COLIndices.push_back(c[i]);
    }
  }
}

Mesh* OBJGeoConverter::ConvertToMesh(const std::string& strFilename) {

  bool bFlipVertices = false;

  VertVec       vertices;
  NormVec       normals;
  TexCoordVec   texcoords;
  ColorVec      colors;

  IndexVec      VertIndices;
  IndexVec      NormalIndices;
  IndexVec      TCIndices;
  IndexVec      COLIndices;

	std::ifstream fs;
	std::string line;

	fs.open(strFilename.c_str());
  if (fs.fail()) {
    // hack, we really want some kind of 'file not found' exception.
    throw tuvok::io::DSOpenFailed(strFilename.c_str(), __FILE__, __LINE__);
  }

  float x,y,z;
  size_t iVerticesPerPoly = 0;

  while (!fs.fail()) {
		getline(fs, line);
		if (fs.fail()) break; // no more lines to read
    line = SysTools::ToLowerCase(SysTools::TrimStr(line));

    // remove comments
    size_t cPos = line.find_first_of('#');
    if (cPos != std::string::npos) line = line.substr(0,cPos);
    line = SysTools::TrimStr(line);
    if (line.length() == 0) continue; // skips empty and comment lines

    // find the linetpe
    size_t off = line.find_first_of(" \r\n\t");
    if (off == std::string::npos) continue;
    std::string linetype = SysTools::TrimStrRight(line.substr(0,off));

    line = SysTools::TrimStr(line.substr(linetype.length()));

    if (linetype == "o") {
      WARNING("Skipping Object Tag in OBJ file");
    } else
    if (linetype == "mtllib") {
      WARNING("Skipping Material Library Tag in OBJ file");
    } else
		if (linetype == "v") { // vertex attrib found
				x = float(atof(line.c_str()));
				line = TrimToken(line);
				y = float(atof(line.c_str()));
				line = TrimToken(line);
				z = float(atof(line.c_str()));
				vertices.push_back(FLOATVECTOR3(x,y,(bFlipVertices) ? -z : z));
  	} else
	  if (linetype == "vt") {  // vertex texcoord found
			x = float(atof(line.c_str()));
		  line = TrimToken(line);
			y = float(atof(line.c_str()));
			texcoords.push_back(FLOATVECTOR2(x,y));
		} else
    if (linetype == "vn") { // vertex normal found
			x = float(atof(line.c_str()));
      line = TrimToken(line);
			y = float(atof(line.c_str()));
      line = TrimToken(line);
      z = float(atof(line.c_str()));
      FLOATVECTOR3 n(x,y,z);
      n.normalize();
      normals.push_back(n);
		} else
    if (linetype == "f" || linetype == "l") { // face or line found
      size_t off = line.find_first_of(" \r\n\t");
      if (off == std::string::npos) continue;
      std::string analysis = SysTools::TrimStrRight(line.substr(0,off));
      int count = CountOccurences(analysis,"/");

      IndexVec v, n, t, c;

      while (line.length() > 0)  {
        switch (count) {
          case 0 : {
                int vI = atoi(line.c_str())-1;
                v.push_back(vI);
                line = TrimToken(line);
                break;
               }
          case 1 : {
                int vI = atoi(line.c_str())-1;
                v.push_back(vI);
                line = TrimToken(line,"/",true);
                int vT = atoi(line.c_str())-1;
                t.push_back(vT);
                line = TrimToken(line);
                break;
               }
          case 2 : {
                int vI = atoi(line.c_str())-1;
                v.push_back(vI);
                line = TrimToken(line,"/",true);
                if (line[0] != '/') {
                  int vT = atoi(line.c_str())-1;
                  t.push_back(vT);
                }
                line = TrimToken(line,"/",true);
                int vN = atoi(line.c_str())-1;
                n.push_back(vN);
                line = TrimToken(line);
                break;
               }
          case 3 : {
                int vI = atoi(line.c_str())-1;
                v.push_back(vI);
                line = TrimToken(line,"/",true);
                if (line[0] != '/') {
                  int vT = atoi(line.c_str())-1;
                  t.push_back(vT);
                }
                line = TrimToken(line,"/",true);
                if (line[0] != '/') {
                  int vN = atoi(line.c_str())-1;
                  n.push_back(vN);
                }
                line = TrimToken(line,"/",true);
                int vC = atoi(line.c_str())-1;
                c.push_back(vC);
                line = TrimToken(line);
                break;
               }
        }
        SysTools::TrimStrLeft(line);
      }

      if (v.size() == 1) {
        WARNING("Skipping points in OBJ file");
        continue;
      }

      if (iVerticesPerPoly == 0) iVerticesPerPoly = v.size();

      if (v.size() == 2) {
        if ( iVerticesPerPoly != 2 ) {
          WARNING("Skipping a line in a file that also contains polygons");
          continue;
        }
        AddToMesh(vertices,v,n,t,c,VertIndices,NormalIndices,TCIndices,COLIndices);
      } else {
        if ( iVerticesPerPoly == 2 ) {
          WARNING("Skipping polygon in file that also contains lines");
          continue;
        }
        AddToMesh(vertices,v,n,t,c,VertIndices,NormalIndices,TCIndices,COLIndices);
      }

    } else {
      WARNING("Skipping unknown tag %s in OBJ file", linetype.c_str());
    }
  }
	fs.close();

  std::string desc = m_vConverterDesc + " data converted from " + SysTools::GetFilename(strFilename);

  Mesh* m = new Mesh(vertices,normals,texcoords,colors,
                     VertIndices,NormalIndices,TCIndices,COLIndices,
                     false, false, desc,
                     ((iVerticesPerPoly == 2)
                            ? Mesh::MT_LINES
                            : Mesh::MT_TRIANGLES ));
  return m;
}

bool OBJGeoConverter::ConvertToNative(const Mesh& m,
                                      const std::string& strTargetFilename) {

    std::ofstream outStream(strTargetFilename.c_str());
    if (outStream.fail()) return false;
    outStream << "###############################################" << std::endl;
    outStream << "#" << m.Name() << std::endl;
    outStream << "###############################################" << std::endl << std::endl;

    // vertices
    for (size_t i = 0;i<m.GetVertices().size();i++) {
        outStream << "v "
                    << m.GetVertices()[i].x << " "
                    << m.GetVertices()[i].y << " "
                    << m.GetVertices()[i].z << std::endl;;
    }

    for (size_t i = 0;i<m.GetNormals().size();i++) {
        outStream << "vn "
                    << m.GetNormals()[i].x << " "
                    << m.GetNormals()[i].y << " "
                    << m.GetNormals()[i].z << std::endl;
    }

    for (size_t i = 0;i<m.GetTexCoords().size();i++) {
        outStream << "vt "
                    << m.GetTexCoords()[i].x << " "
                    << m.GetTexCoords()[i].y << std::endl;
    }

    // this is our own extension, originally colors are
    // not supported by OBJ files
    for (size_t i = 0;i<m.GetColors().size();i++) {
        outStream << "vc "
                    << m.GetColors()[i].x << " "
                    << m.GetColors()[i].y << " "
                    << m.GetColors()[i].z << " "
                    << m.GetColors()[i].w << std::endl;
    }

    size_t iVPP = m.GetVerticesPerPoly();
    for (size_t i = 0;i<m.GetVertexIndices().size();i+=iVPP) {
        if (iVPP == 1)
           outStream << "p "; else
        if (iVPP == 2)
           outStream << "l ";
        else
           outStream << "f ";

        for (size_t j = 0;j<iVPP;j++) {
          outStream << m.GetVertexIndices()[i+j]+1;
          if (m.GetTexCoordIndices().size() == m.GetVertexIndices().size() ||
              m.GetNormalIndices().size() == m.GetVertexIndices().size() ||
              m.GetColorIndices().size() == m.GetVertexIndices().size()) {
              outStream << "/";
              if (m.GetTexCoordIndices().size() == m.GetVertexIndices().size()) {
                outStream << m.GetTexCoordIndices()[i+j]+1;
              }
          }
          if (m.GetNormalIndices().size() == m.GetVertexIndices().size() ||
              m.GetColorIndices().size() == m.GetVertexIndices().size()) {
              outStream << "/";
              if (m.GetNormalIndices().size() == m.GetVertexIndices().size()) {
                outStream << m.GetNormalIndices()[i+j]+1;
              }
          }
          if (m.GetColorIndices().size() == m.GetVertexIndices().size()) {
              outStream << "/";
              outStream << m.GetColorIndices()[i+j]+1;
          }
          if (j+1 < iVPP) outStream << " ";
        }
        outStream << std::endl;
    }

    outStream.close();

    return true;

}
<commit_msg>added objx file type, only objx store the color channel (our own extension) to make sure obj files are always standard compliant some cosmetic changes in the OBJ comments<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2010 Interactive Visualization and Data Analysis Group.

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

//!    File   : OBJGeoConverter.cpp
//!    Author : Jens Krueger
//!             IVCI & DFKI & MMCI, Saarbruecken
//!             SCI Institute, University of Utah
//!    Date   : July 2010
//
//!    Copyright (C) 2010 DFKI, MMCI, SCI Institute

#include "OBJGeoConverter.h"
#include "Controller/Controller.h"
#include "SysTools.h"
#include "Mesh.h"
#include <fstream>
#include "TuvokIOError.h"

using namespace tuvok;

OBJGeoConverter::OBJGeoConverter() :
  AbstrGeoConverter()
{
  m_vConverterDesc = "Wavefront Object File";
  m_vSupportedExt.push_back("OBJ");
  m_vSupportedExt.push_back("OBJX");
}

inline int OBJGeoConverter::CountOccurences(const std::string& str, const std::string& substr) {
  size_t found = str.find_first_of(substr);
  int count = 0;
  while (found!=std::string::npos)
  {
    count++;
    found=str.find_first_of(substr,found+1);
  }
  return count;
}

inline std::string OBJGeoConverter::TrimToken(const std::string& Src,
                                              const std::string& c,
                                              bool bOnlyFirst)
{
  size_t off = Src.find_first_of(c);
  if (off == std::string::npos) return std::string();
  if (bOnlyFirst) {
    return Src.substr(off+1);
  } else {
    size_t p1 = Src.find_first_not_of(c,off);
    if (p1 == std::string::npos) return std::string();
    return Src.substr(p1);
  }
}

void OBJGeoConverter::AddToMesh(const VertVec& vertices,
                                IndexVec& v, IndexVec& n,
                                IndexVec& t, IndexVec& c,
                                IndexVec& VertIndices, IndexVec& NormalIndices,
                                IndexVec& TCIndices, IndexVec& COLIndices) {
  if (v.size() > 3) {
    // per OBJ definition any poly with more than 3 verices has
    // to be planar and convex, so we can savely triangulate it

    SortByGradient(vertices,v,n,t,c);

    for (size_t i = 0;i<v.size()-2;i++) {
      IndexVec mv, mn, mt, mc;
      mv.push_back(v[0]);mv.push_back(v[i+1]);mv.push_back(v[i+2]);
      if (n.size() == v.size()) {mn.push_back(n[i]);mn.push_back(n[i+1]);mn.push_back(n[i+2]);}
      if (t.size() == v.size()) {mt.push_back(t[i]);mt.push_back(t[i+1]);mt.push_back(t[i+2]);}
      if (c.size() == v.size()) {mc.push_back(c[i]);mc.push_back(c[i+1]);mc.push_back(c[i+2]);}

      AddToMesh(vertices,
                mv,mn,mt,mc,
                VertIndices,
                NormalIndices,
                TCIndices,
                COLIndices);
    }

  } else {
    for (size_t i = 0;i<v.size();i++) {
      VertIndices.push_back(v[i]);
      if (n.size() == v.size()) NormalIndices.push_back(n[i]);
      if (t.size() == v.size()) TCIndices.push_back(t[i]);
      if (c.size() == v.size()) COLIndices.push_back(c[i]);
    }
  }
}

Mesh* OBJGeoConverter::ConvertToMesh(const std::string& strFilename) {

  bool bFlipVertices = false;

  VertVec       vertices;
  NormVec       normals;
  TexCoordVec   texcoords;
  ColorVec      colors;

  IndexVec      VertIndices;
  IndexVec      NormalIndices;
  IndexVec      TCIndices;
  IndexVec      COLIndices;

	std::ifstream fs;
	std::string line;

	fs.open(strFilename.c_str());
  if (fs.fail()) {
    // hack, we really want some kind of 'file not found' exception.
    throw tuvok::io::DSOpenFailed(strFilename.c_str(), __FILE__, __LINE__);
  }

  float x,y,z;
  size_t iVerticesPerPoly = 0;

  while (!fs.fail()) {
		getline(fs, line);
		if (fs.fail()) break; // no more lines to read
    line = SysTools::ToLowerCase(SysTools::TrimStr(line));

    // remove comments
    size_t cPos = line.find_first_of('#');
    if (cPos != std::string::npos) line = line.substr(0,cPos);
    line = SysTools::TrimStr(line);
    if (line.length() == 0) continue; // skips empty and comment lines

    // find the linetpe
    size_t off = line.find_first_of(" \r\n\t");
    if (off == std::string::npos) continue;
    std::string linetype = SysTools::TrimStrRight(line.substr(0,off));

    line = SysTools::TrimStr(line.substr(linetype.length()));

    if (linetype == "o") {
      WARNING("Skipping Object Tag in OBJ file");
    } else
    if (linetype == "mtllib") {
      WARNING("Skipping Material Library Tag in OBJ file");
    } else
		if (linetype == "v") { // vertex attrib found
				x = float(atof(line.c_str()));
				line = TrimToken(line);
				y = float(atof(line.c_str()));
				line = TrimToken(line);
				z = float(atof(line.c_str()));
				vertices.push_back(FLOATVECTOR3(x,y,(bFlipVertices) ? -z : z));
  	} else
	  if (linetype == "vt") {  // vertex texcoord found
			x = float(atof(line.c_str()));
		  line = TrimToken(line);
			y = float(atof(line.c_str()));
			texcoords.push_back(FLOATVECTOR2(x,y));
		} else
    if (linetype == "vn") { // vertex normal found
			x = float(atof(line.c_str()));
      line = TrimToken(line);
			y = float(atof(line.c_str()));
      line = TrimToken(line);
      z = float(atof(line.c_str()));
      FLOATVECTOR3 n(x,y,z);
      n.normalize();
      normals.push_back(n);
		} else
    if (linetype == "f" || linetype == "l") { // face or line found
      size_t off = line.find_first_of(" \r\n\t");
      if (off == std::string::npos) continue;
      std::string analysis = SysTools::TrimStrRight(line.substr(0,off));
      int count = CountOccurences(analysis,"/");

      IndexVec v, n, t, c;

      while (line.length() > 0)  {
        switch (count) {
          case 0 : {
                int vI = atoi(line.c_str())-1;
                v.push_back(vI);
                line = TrimToken(line);
                break;
               }
          case 1 : {
                int vI = atoi(line.c_str())-1;
                v.push_back(vI);
                line = TrimToken(line,"/",true);
                int vT = atoi(line.c_str())-1;
                t.push_back(vT);
                line = TrimToken(line);
                break;
               }
          case 2 : {
                int vI = atoi(line.c_str())-1;
                v.push_back(vI);
                line = TrimToken(line,"/",true);
                if (line[0] != '/') {
                  int vT = atoi(line.c_str())-1;
                  t.push_back(vT);
                }
                line = TrimToken(line,"/",true);
                int vN = atoi(line.c_str())-1;
                n.push_back(vN);
                line = TrimToken(line);
                break;
               }
          case 3 : {
                int vI = atoi(line.c_str())-1;
                v.push_back(vI);
                line = TrimToken(line,"/",true);
                if (line[0] != '/') {
                  int vT = atoi(line.c_str())-1;
                  t.push_back(vT);
                }
                line = TrimToken(line,"/",true);
                if (line[0] != '/') {
                  int vN = atoi(line.c_str())-1;
                  n.push_back(vN);
                }
                line = TrimToken(line,"/",true);
                int vC = atoi(line.c_str())-1;
                c.push_back(vC);
                line = TrimToken(line);
                break;
               }
        }
        SysTools::TrimStrLeft(line);
      }

      if (v.size() == 1) {
        WARNING("Skipping points in OBJ file");
        continue;
      }

      if (iVerticesPerPoly == 0) iVerticesPerPoly = v.size();

      if (v.size() == 2) {
        if ( iVerticesPerPoly != 2 ) {
          WARNING("Skipping a line in a file that also contains polygons");
          continue;
        }
        AddToMesh(vertices,v,n,t,c,VertIndices,NormalIndices,TCIndices,COLIndices);
      } else {
        if ( iVerticesPerPoly == 2 ) {
          WARNING("Skipping polygon in file that also contains lines");
          continue;
        }
        AddToMesh(vertices,v,n,t,c,VertIndices,NormalIndices,TCIndices,COLIndices);
      }

    } else {
      WARNING("Skipping unknown tag %s in OBJ file", linetype.c_str());
    }
  }
	fs.close();

  std::string desc = m_vConverterDesc + " data converted from " + SysTools::GetFilename(strFilename);

  Mesh* m = new Mesh(vertices,normals,texcoords,colors,
                     VertIndices,NormalIndices,TCIndices,COLIndices,
                     false, false, desc,
                     ((iVerticesPerPoly == 2)
                            ? Mesh::MT_LINES
                            : Mesh::MT_TRIANGLES ));
  return m;
}

bool OBJGeoConverter::ConvertToNative(const Mesh& m,
                                      const std::string& strTargetFilename) {

  bool bUseExtension = SysTools::ToUpperCase(
                            SysTools::GetExt(strTargetFilename)
                                            ) == "OBJX";

  std::ofstream outStream(strTargetFilename.c_str());
  if (outStream.fail()) return false;

  std::stringstream statLine1, statLine2;
  statLine1 << "Vertices: " << m.GetVertices().size();
  statLine2 << "Primitives: " << m.GetVertexIndices().size();
  size_t iCount = std::max(m.Name().size(),
                           std::max(statLine1.str().size(),
                                    statLine2.str().size()
                           ));

  for (size_t i = 0;i<iCount+4;i++) outStream << "#";
  outStream << std::endl;
  outStream << "# " << m.Name();
  for (size_t i = m.Name().size();i<iCount;i++) outStream << " ";
  outStream << " #" << std::endl;

  outStream << "# " << statLine1.str();
  for (size_t i =statLine1.str().size();i<iCount;i++) outStream << " ";
  outStream << " #" << std::endl;

  outStream << "# " << statLine2.str();
  for (size_t i = statLine2.str().size();i<iCount;i++) outStream << " ";
  outStream << " #" << std::endl;

  for (size_t i = 0;i<iCount+4;i++) outStream << "#";
  outStream << std::endl;

  // vertices
  for (size_t i = 0;i<m.GetVertices().size();i++) {
      outStream << "v "
                  << m.GetVertices()[i].x << " "
                  << m.GetVertices()[i].y << " "
                  << m.GetVertices()[i].z << std::endl;;
  }

  for (size_t i = 0;i<m.GetNormals().size();i++) {
      outStream << "vn "
                  << m.GetNormals()[i].x << " "
                  << m.GetNormals()[i].y << " "
                  << m.GetNormals()[i].z << std::endl;
  }

  for (size_t i = 0;i<m.GetTexCoords().size();i++) {
      outStream << "vt "
                  << m.GetTexCoords()[i].x << " "
                  << m.GetTexCoords()[i].y << std::endl;
  }

  if (bUseExtension) {
    // this is our own extension, originally colors are
    // not supported by OBJ files
    for (size_t i = 0;i<m.GetColors().size();i++) {
        outStream << "vc "
                    << m.GetColors()[i].x << " "
                    << m.GetColors()[i].y << " "
                    << m.GetColors()[i].z << " "
                    << m.GetColors()[i].w << std::endl;
    }
  } else {
    if (m.GetColors().size() != 0)
      WARNING("Ignoring mesh colors for standart OBJ files, "
              "use OBJX files to also export colors.");
  }

  bool bHasTexCoords = m.GetTexCoordIndices().size() == m.GetVertexIndices().size();
  bool bHasNormals = m.GetNormalIndices().size() == m.GetVertexIndices().size();
  bool bHasColors = (bUseExtension && m.GetColorIndices().size() == m.GetVertexIndices().size());

  size_t iVPP = m.GetVerticesPerPoly();
  for (size_t i = 0;i<m.GetVertexIndices().size();i+=iVPP) {
      if (iVPP == 1)
         outStream << "p "; else
      if (iVPP == 2)
         outStream << "l ";
      else
         outStream << "f ";

      for (size_t j = 0;j<iVPP;j++) {
        outStream << m.GetVertexIndices()[i+j]+1;
        if (bHasTexCoords || bHasNormals || bHasColors) {
            outStream << "/";
            if (m.GetTexCoordIndices().size() == m.GetVertexIndices().size()) {
              outStream << m.GetTexCoordIndices()[i+j]+1;
            }
        }
        if (bHasNormals || bHasColors) {
            outStream << "/";
            if (m.GetNormalIndices().size() == m.GetVertexIndices().size()) {
              outStream << m.GetNormalIndices()[i+j]+1;
            }
        }
        if (bHasColors) {
            outStream << "/";
            outStream << m.GetColorIndices()[i+j]+1;
        }
        if (j+1 < iVPP) outStream << " ";
      }
      outStream << std::endl;
  }

  outStream.close();

  return true;
}
<|endoftext|>


<commit_before>#include <aery32/all.h>
#include "board.h"

using namespace aery;

#define LED AVR32_PIN_PC04

int main(void)
{
	/*
	 * Put your application initialization sequence here. The default
	 * board initializer defines all pins as input and sets the CPU clock
	 * speed to 66 MHz.
	 */
	board::init();

	gpio_init_pin(LED, GPIO_OUTPUT);
	gpio_set_pin_high(LED);

	for(;;) {
		/* Put your application code here */

		board::usb << "hello\r\n";
	}

	return 0;
}<commit_msg>Update usb teaser<commit_after>#include <aery32/all.h>
#include "board.h"

using namespace aery;

#define LED AVR32_PIN_PC04

int main(void)
{
	/*
	 * Put your application initialization sequence here. The default
	 * board initializer defines all pins as input and sets the CPU clock
	 * speed to 66 MHz.
	 */
	board::init();

	gpio_init_pin(LED, GPIO_OUTPUT);
	gpio_set_pin_high(LED);

	for(;;) {
		/* Put your application code here */

		board::usb << "hello\r\n";
		delay_ms(500);
	}

	return 0;
}<|endoftext|>


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

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

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

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
#include "mainwindow.h"
#include <QApplication>
#include <QMessageBox>

namespace
{
	class Application : public QApplication
	{
	public:
		Application(int &argc, char **argv, int flags = ApplicationFlags):
			QApplication(argc, argv, flags)
		{ }

		virtual bool notify ( QObject * receiver, QEvent * e )
		{
			try {
				return QApplication::notify( receiver, e );
			} catch ( const std::exception& e ) {
				QMessageBox::warning(0, "Error", e.what());
				return false;
			}
		}
	};
}

int main(int argc, char *argv[])
{
	QCoreApplication::setApplicationName("mtp-ng-qt");
	QCoreApplication::setOrganizationDomain("svalko.org");
	QCoreApplication::setOrganizationName("svalko");

	Application a(argc, argv);
	MainWindow w;
	w.show();

	if (!w.started())
		return 1;

	return a.exec();
}
<commit_msg>changed name/domain to whoozle.github.io<commit_after>/*
 * Android File Transfer for Linux: MTP client for android devices
 * Copyright (C) 2015  Vladimir Menshakov

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

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

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
#include "mainwindow.h"
#include <QApplication>
#include <QMessageBox>

namespace
{
	class Application : public QApplication
	{
	public:
		Application(int &argc, char **argv, int flags = ApplicationFlags):
			QApplication(argc, argv, flags)
		{ }

		virtual bool notify ( QObject * receiver, QEvent * e )
		{
			try {
				return QApplication::notify( receiver, e );
			} catch ( const std::exception& e ) {
				QMessageBox::warning(0, "Error", e.what());
				return false;
			}
		}
	};
}

int main(int argc, char *argv[])
{
	QCoreApplication::setApplicationName("mtp-ng-qt");
	QCoreApplication::setOrganizationDomain("whoozle.github.io");
	QCoreApplication::setOrganizationName("whoozle.github.io");

	Application a(argc, argv);
	MainWindow w;
	w.show();

	if (!w.started())
		return 1;

	return a.exec();
}
<|endoftext|>


<commit_before>/*  -*- c++ -*-
    identitydialog.cpp

    KMail, the KDE mail client.
    Copyright (c) 2002 the KMail authors.
    See file AUTHORS for details

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License,
    version 2.0, as published by the Free Software Foundation.
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software Foundation,
    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, US
*/

#include "identitydialog.h"

// other KMail headers:
#include "kmidentity.h"
#include "signatureconfigurator.h"
#include "kmfoldercombobox.h"
#include "kmkernel.h"
#include "kmfoldermgr.h"

// other kdenetwork headers:
#include <kpgpui.h>

// other KDE headers:
#include <klocale.h>
#include <kmessagebox.h>

// Qt headers:
#include <qtabwidget.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qcombobox.h>
#include <qcheckbox.h>
#include <qstring.h>
#include <qstringlist.h>
#include <qwhatsthis.h>

// other headers: (none)

namespace KMail {

  IdentityDialog::IdentityDialog( QWidget * parent, const char * name )
    : KDialogBase( Plain, i18n("Edit Identity"), Ok|Cancel|Help, Ok,
		   parent, name )
  {
    // tmp. vars:
    QWidget * tab;
    QLabel  * label;
    int row;
    QGridLayout * glay;
    QString msg;

    //
    // Tab Widget: General
    //
    row = -1;
    QTabWidget *tabWidget = new QTabWidget( plainPage(), "config-identity-tab" );
    tab = new QWidget( tabWidget );
    tabWidget->addTab( tab, i18n("&General") );
    glay = new QGridLayout( tab, 4, 2, marginHint(), spacingHint() );
    glay->setRowStretch( 3, 1 );
    glay->setColStretch( 1, 1 );

    // "Name" line edit and label:
    ++row;
    mNameEdit = new QLineEdit( tab );
    glay->addWidget( mNameEdit, row, 1 );
    glay->addWidget( new QLabel( mNameEdit, i18n("Name:"), tab ), row, 0 );

    // "Organization" line edit and label:
    ++row;
    mOrganizationEdit = new QLineEdit( tab );
    glay->addWidget( mOrganizationEdit, row, 1 );
    glay->addWidget( new QLabel( mOrganizationEdit,
				 i18n("Organi&zation:"), tab ), row, 0 );

    // "Email Address" line edit and label:
    // (row 3: spacer)
    ++row;
    mEmailEdit = new QLineEdit( tab );
    glay->addWidget( mEmailEdit, row, 1 );
    glay->addWidget( new QLabel( mEmailEdit, i18n("&Email address:"), tab ),
		     row, 0 );

    //
    // Tab Widget: Advanced
    //
    row = -1;
    tab = new QWidget( tabWidget );
    tabWidget->addTab( tab, i18n("Ad&vanced") );
    glay = new QGridLayout( tab, 7, 2, marginHint(), spacingHint() );
    // the last (empty) row takes all the remaining space
    glay->setRowStretch( 7-1, 1 );
    glay->setColStretch( 1, 1 );

    // "Reply-To Address" line edit and label:
    ++row;
    mReplyToEdit = new QLineEdit( tab );
    glay->addWidget( mReplyToEdit, row, 1 );
    glay->addWidget( new QLabel( mReplyToEdit,
				 i18n("Re&ply-To address:"), tab ), row, 0 );

    // "BCC addresses" line edit and label:
    ++row;
    mBccEdit = new QLineEdit( tab );
    glay->addWidget( mBccEdit, row, 1 );
    label = new QLabel( mBccEdit, i18n("&BCC addresses:"), tab );
    glay->addWidget( label, row, 0 );
    msg = i18n("<qt>
BCC (Blind Carbon Copy) addresses
"
	       "
The addresses that you enter here will be added to each"
	       "   outgoing mail that is sent with this identity. They will not"
	       "   be visible to other recipients.
"
	       "
This is commonly used to send a copy of each sent message to"
	       "   another account of yours.
"
	       "
If in doubt, leave this field blank.
</qt>");
    QWhatsThis::add( label, msg );
    QWhatsThis::add( mBccEdit, msg );

    // "OpenPGP Key" requester and label:
    ++row;
    mPgpKeyRequester = new Kpgp::SecretKeyRequester( tab );
    mPgpKeyRequester->dialogButton()->setText( i18n("Chang&e...") );
    mPgpKeyRequester->setDialogCaption( i18n("Your OpenPGP Key") );
    mPgpKeyRequester->setDialogMessage( i18n("Select the OpenPGP key which "
					     "should be used to sign your "
					     "messages and when encrypting to "
					     "yourself.") );
    msg = i18n("<qt>
The OpenPGP key you choose here will be used "
	       "to sign messages and to encrypt messages to "
	       "yourself.
</qt>");

    label = new QLabel( mPgpKeyRequester, i18n("OpenPGP &key:"), tab );
    QWhatsThis::add( mPgpKeyRequester, msg );
    QWhatsThis::add( label, msg );

    glay->addWidget( label, row, 0 );
    glay->addWidget( mPgpKeyRequester, row, 1 );

    // "Sent-mail Folder" combo box and label:
    ++row;
    mFccCombo = new KMFolderComboBox( tab );
    mFccCombo->showOutboxFolder( false );
    glay->addWidget( mFccCombo, row, 1 );
    glay->addWidget( new QLabel( mFccCombo, i18n("Sent-mail &folder:"), tab ),
		     row, 0 );

    // "Drafts Folder" combo box and label:
    ++row;
    mDraftsCombo = new KMFolderComboBox( tab );
    mDraftsCombo->showOutboxFolder( false );
    glay->addWidget( mDraftsCombo, row, 1 );
    glay->addWidget( new QLabel( mDraftsCombo, i18n("Drafts fo&lder:"), tab ),
		     row, 0 );

    // "Special transport" combobox and label:
    ++row;
    mTransportCheck = new QCheckBox( i18n("Special &transport:"), tab );
    glay->addWidget( mTransportCheck, row, 0 );
    mTransportCombo = new QComboBox( true, tab );
    mTransportCombo->setEnabled( false ); // since !mTransportCheck->isChecked()
    glay->addWidget( mTransportCombo, row, 1 );
    connect( mTransportCheck, SIGNAL(toggled(bool)),
	     mTransportCombo, SLOT(setEnabled(bool)) );

    // the last row is a spacer

    //
    // Tab Widget: Signature
    //
    mSignatureConfigurator = new SignatureConfigurator( tabWidget );
    mSignatureConfigurator->layout()->setMargin( KDialog::marginHint() );
    tabWidget->addTab( mSignatureConfigurator, i18n("&Signature") );
  }

  bool IdentityDialog::checkFolderExists( const QString & folderID,
					  const QString & msg ) {
    KMFolder * folder = kernel->folderMgr()->findIdString( folderID );
    if ( !folder )
      folder = kernel->imapFolderMgr()->findIdString( folderID );
    if ( !folder ) {
      KMessageBox::sorry( this, msg );
      return false;
    }
    return true;
  }

  void IdentityDialog::setIdentity( KMIdentity & ident ) {
    // "General" tab:
    mNameEdit->setText( ident.fullName() );
    mOrganizationEdit->setText( ident.organization() );
    mEmailEdit->setText( ident.emailAddr() );

    // "Advanced" tab:
    mPgpKeyRequester->setKeyIDs( Kpgp::KeyIDList() << ident.pgpIdentity() );
    mReplyToEdit->setText( ident.replyToAddr() );
    mBccEdit->setText( ident.bcc() );
    mTransportCheck->setChecked( !ident.transport().isEmpty() );
    mTransportCombo->setEditText( ident.transport() );
    mTransportCombo->setEnabled( !ident.transport().isEmpty() );

    if ( ident.fcc().isEmpty() ||
	 !checkFolderExists( ident.fcc(),
			     i18n("The custom sent-mail folder for identity "
				  "\"%1\" doesn't exist (anymore). "
				  "Therefore the default sent-mail folder "
				  "will be used.")
			     .arg( ident.identityName() ) ) )
      mFccCombo->setFolder( kernel->sentFolder() );
    else
      mFccCombo->setFolder( ident.fcc() );

    if ( ident.drafts().isEmpty() ||
	 !checkFolderExists( ident.drafts(),
			     i18n("The custom drafts folder for identity "
				  "\"%1\" doesn't exist (anymore). "
				  "Therefore the default drafts folder "
				  "will be used.")
			     .arg( ident.identityName() ) ) )
      mDraftsCombo->setFolder( kernel->draftsFolder() );
    else
      mDraftsCombo->setFolder( ident.drafts() );

    // "Signature" tab:
    mSignatureConfigurator->setSignature( ident.signature() );
  }

  void IdentityDialog::updateIdentity( KMIdentity & ident ) {
    // "General" tab:
    ident.setFullName( mNameEdit->text() );
    ident.setOrganization( mOrganizationEdit->text() );
    ident.setEmailAddr( mEmailEdit->text() );
    // "Advanced" tab:
    ident.setPgpIdentity( mPgpKeyRequester->keyIDs().first() );
    ident.setReplyToAddr( mReplyToEdit->text() );
    ident.setBcc( mBccEdit->text() );
    ident.setTransport( ( mTransportCheck->isChecked() ) ?
			mTransportCombo->currentText() : QString::null );
    ident.setFcc( mFccCombo->getFolder() ?
		  mFccCombo->getFolder()->idString() : QString::null );
    ident.setDrafts( mDraftsCombo->getFolder() ?
		     mDraftsCombo->getFolder()->idString() : QString::null );
    // "Signature" tab:
    ident.setSignature( mSignatureConfigurator->signature() );
  }

  void IdentityDialog::slotUpdateTransportCombo( const QStringList & sl ) {
    // save old setting:
    QString content = mTransportCombo->currentText();
    // update combo box:
    mTransportCombo->clear();
    mTransportCombo->insertStringList( sl );
    // restore saved setting:
    mTransportCombo->setEditText( content );
  };

};

#include "identitydialog.moc"
<commit_msg>adding missing layout<commit_after>/*  -*- c++ -*-
    identitydialog.cpp

    KMail, the KDE mail client.
    Copyright (c) 2002 the KMail authors.
    See file AUTHORS for details

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License,
    version 2.0, as published by the Free Software Foundation.
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software Foundation,
    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, US
*/

#include "identitydialog.h"

// other KMail headers:
#include "kmidentity.h"
#include "signatureconfigurator.h"
#include "kmfoldercombobox.h"
#include "kmkernel.h"
#include "kmfoldermgr.h"

// other kdenetwork headers:
#include <kpgpui.h>

// other KDE headers:
#include <klocale.h>
#include <kmessagebox.h>

// Qt headers:
#include <qtabwidget.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qcombobox.h>
#include <qcheckbox.h>
#include <qstring.h>
#include <qstringlist.h>
#include <qwhatsthis.h>

// other headers: (none)

namespace KMail {

  IdentityDialog::IdentityDialog( QWidget * parent, const char * name )
    : KDialogBase( Plain, i18n("Edit Identity"), Ok|Cancel|Help, Ok,
		   parent, name )
  {
    // tmp. vars:
    QWidget * tab;
    QLabel  * label;
    int row;
    QGridLayout * glay;
    QString msg;

    //
    // Tab Widget: General
    //
    row = -1;
    QVBoxLayout * vlay = new QVBoxLayout( plainPage(), 0, spacingHint() );
    QTabWidget *tabWidget = new QTabWidget( plainPage(), "config-identity-tab" );
    vlay->addWidget( tabWidget );

    tab = new QWidget( tabWidget );
    tabWidget->addTab( tab, i18n("&General") );
    glay = new QGridLayout( tab, 4, 2, marginHint(), spacingHint() );
    glay->setRowStretch( 3, 1 );
    glay->setColStretch( 1, 1 );

    // "Name" line edit and label:
    ++row;
    mNameEdit = new QLineEdit( tab );
    glay->addWidget( mNameEdit, row, 1 );
    glay->addWidget( new QLabel( mNameEdit, i18n("Name:"), tab ), row, 0 );

    // "Organization" line edit and label:
    ++row;
    mOrganizationEdit = new QLineEdit( tab );
    glay->addWidget( mOrganizationEdit, row, 1 );
    glay->addWidget( new QLabel( mOrganizationEdit,
				 i18n("Organi&zation:"), tab ), row, 0 );

    // "Email Address" line edit and label:
    // (row 3: spacer)
    ++row;
    mEmailEdit = new QLineEdit( tab );
    glay->addWidget( mEmailEdit, row, 1 );
    glay->addWidget( new QLabel( mEmailEdit, i18n("&Email address:"), tab ),
		     row, 0 );

    //
    // Tab Widget: Advanced
    //
    row = -1;
    tab = new QWidget( tabWidget );
    tabWidget->addTab( tab, i18n("Ad&vanced") );
    glay = new QGridLayout( tab, 7, 2, marginHint(), spacingHint() );
    // the last (empty) row takes all the remaining space
    glay->setRowStretch( 7-1, 1 );
    glay->setColStretch( 1, 1 );

    // "Reply-To Address" line edit and label:
    ++row;
    mReplyToEdit = new QLineEdit( tab );
    glay->addWidget( mReplyToEdit, row, 1 );
    glay->addWidget( new QLabel( mReplyToEdit,
				 i18n("Re&ply-To address:"), tab ), row, 0 );

    // "BCC addresses" line edit and label:
    ++row;
    mBccEdit = new QLineEdit( tab );
    glay->addWidget( mBccEdit, row, 1 );
    label = new QLabel( mBccEdit, i18n("&BCC addresses:"), tab );
    glay->addWidget( label, row, 0 );
    msg = i18n("<qt>
BCC (Blind Carbon Copy) addresses
"
	       "
The addresses that you enter here will be added to each"
	       "   outgoing mail that is sent with this identity. They will not"
	       "   be visible to other recipients.
"
	       "
This is commonly used to send a copy of each sent message to"
	       "   another account of yours.
"
	       "
If in doubt, leave this field blank.
</qt>");
    QWhatsThis::add( label, msg );
    QWhatsThis::add( mBccEdit, msg );

    // "OpenPGP Key" requester and label:
    ++row;
    mPgpKeyRequester = new Kpgp::SecretKeyRequester( tab );
    mPgpKeyRequester->dialogButton()->setText( i18n("Chang&e...") );
    mPgpKeyRequester->setDialogCaption( i18n("Your OpenPGP Key") );
    mPgpKeyRequester->setDialogMessage( i18n("Select the OpenPGP key which "
					     "should be used to sign your "
					     "messages and when encrypting to "
					     "yourself.") );
    msg = i18n("<qt>
The OpenPGP key you choose here will be used "
	       "to sign messages and to encrypt messages to "
	       "yourself.
</qt>");

    label = new QLabel( mPgpKeyRequester, i18n("OpenPGP &key:"), tab );
    QWhatsThis::add( mPgpKeyRequester, msg );
    QWhatsThis::add( label, msg );

    glay->addWidget( label, row, 0 );
    glay->addWidget( mPgpKeyRequester, row, 1 );

    // "Sent-mail Folder" combo box and label:
    ++row;
    mFccCombo = new KMFolderComboBox( tab );
    mFccCombo->showOutboxFolder( false );
    glay->addWidget( mFccCombo, row, 1 );
    glay->addWidget( new QLabel( mFccCombo, i18n("Sent-mail &folder:"), tab ),
		     row, 0 );

    // "Drafts Folder" combo box and label:
    ++row;
    mDraftsCombo = new KMFolderComboBox( tab );
    mDraftsCombo->showOutboxFolder( false );
    glay->addWidget( mDraftsCombo, row, 1 );
    glay->addWidget( new QLabel( mDraftsCombo, i18n("Drafts fo&lder:"), tab ),
		     row, 0 );

    // "Special transport" combobox and label:
    ++row;
    mTransportCheck = new QCheckBox( i18n("Special &transport:"), tab );
    glay->addWidget( mTransportCheck, row, 0 );
    mTransportCombo = new QComboBox( true, tab );
    mTransportCombo->setEnabled( false ); // since !mTransportCheck->isChecked()
    glay->addWidget( mTransportCombo, row, 1 );
    connect( mTransportCheck, SIGNAL(toggled(bool)),
	     mTransportCombo, SLOT(setEnabled(bool)) );

    // the last row is a spacer

    //
    // Tab Widget: Signature
    //
    mSignatureConfigurator = new SignatureConfigurator( tabWidget );
    mSignatureConfigurator->layout()->setMargin( KDialog::marginHint() );
    tabWidget->addTab( mSignatureConfigurator, i18n("&Signature") );
  }

  bool IdentityDialog::checkFolderExists( const QString & folderID,
					  const QString & msg ) {
    KMFolder * folder = kernel->folderMgr()->findIdString( folderID );
    if ( !folder )
      folder = kernel->imapFolderMgr()->findIdString( folderID );
    if ( !folder ) {
      KMessageBox::sorry( this, msg );
      return false;
    }
    return true;
  }

  void IdentityDialog::setIdentity( KMIdentity & ident ) {
    // "General" tab:
    mNameEdit->setText( ident.fullName() );
    mOrganizationEdit->setText( ident.organization() );
    mEmailEdit->setText( ident.emailAddr() );

    // "Advanced" tab:
    mPgpKeyRequester->setKeyIDs( Kpgp::KeyIDList() << ident.pgpIdentity() );
    mReplyToEdit->setText( ident.replyToAddr() );
    mBccEdit->setText( ident.bcc() );
    mTransportCheck->setChecked( !ident.transport().isEmpty() );
    mTransportCombo->setEditText( ident.transport() );
    mTransportCombo->setEnabled( !ident.transport().isEmpty() );

    if ( ident.fcc().isEmpty() ||
	 !checkFolderExists( ident.fcc(),
			     i18n("The custom sent-mail folder for identity "
				  "\"%1\" doesn't exist (anymore). "
				  "Therefore the default sent-mail folder "
				  "will be used.")
			     .arg( ident.identityName() ) ) )
      mFccCombo->setFolder( kernel->sentFolder() );
    else
      mFccCombo->setFolder( ident.fcc() );

    if ( ident.drafts().isEmpty() ||
	 !checkFolderExists( ident.drafts(),
			     i18n("The custom drafts folder for identity "
				  "\"%1\" doesn't exist (anymore). "
				  "Therefore the default drafts folder "
				  "will be used.")
			     .arg( ident.identityName() ) ) )
      mDraftsCombo->setFolder( kernel->draftsFolder() );
    else
      mDraftsCombo->setFolder( ident.drafts() );

    // "Signature" tab:
    mSignatureConfigurator->setSignature( ident.signature() );
  }

  void IdentityDialog::updateIdentity( KMIdentity & ident ) {
    // "General" tab:
    ident.setFullName( mNameEdit->text() );
    ident.setOrganization( mOrganizationEdit->text() );
    ident.setEmailAddr( mEmailEdit->text() );
    // "Advanced" tab:
    ident.setPgpIdentity( mPgpKeyRequester->keyIDs().first() );
    ident.setReplyToAddr( mReplyToEdit->text() );
    ident.setBcc( mBccEdit->text() );
    ident.setTransport( ( mTransportCheck->isChecked() ) ?
			mTransportCombo->currentText() : QString::null );
    ident.setFcc( mFccCombo->getFolder() ?
		  mFccCombo->getFolder()->idString() : QString::null );
    ident.setDrafts( mDraftsCombo->getFolder() ?
		     mDraftsCombo->getFolder()->idString() : QString::null );
    // "Signature" tab:
    ident.setSignature( mSignatureConfigurator->signature() );
  }

  void IdentityDialog::slotUpdateTransportCombo( const QStringList & sl ) {
    // save old setting:
    QString content = mTransportCombo->currentText();
    // update combo box:
    mTransportCombo->clear();
    mTransportCombo->insertStringList( sl );
    // restore saved setting:
    mTransportCombo->setEditText( content );
  };

};

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


<commit_before><commit_msg>tdf#92982 vcl rendercontext: set correct offset for the frame-level buffer<commit_after><|endoftext|>


<commit_before>/*
    This file is part of KMail.
    Copyright (c) 2003 Andreas Gungl <a.gungl@gmx.de>

    KMail is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "config.h"

#include "redirectdialog.h"

#include "kmkernel.h"
#include "kmlineeditspell.h"

#include <emailfunctions/email.h>
#include <addressesdialog.h>
using KPIM::AddressesDialog;
#include "recentaddresses.h"
using KRecentAddress::RecentAddresses;

#include <kiconloader.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kvbox.h>

#include <QToolTip>

#include <QLabel>
#include <QPushButton>
#include <QStringList>

#include <QFrame>

using namespace KMail;

RedirectDialog::RedirectDialog( QWidget *parent, bool immediate )
  : KDialog( parent )
{
  setCaption( i18n( "Redirect Message" ) );
  setButtons( User1|User2|Cancel );
  setDefaultButton( immediate ? User1 : User2 );
  QFrame *vbox = new KVBox( this );
  setMainWidget( vbox );
  mLabelTo = new QLabel( i18n( "Select the recipient &addresses "
                               "to redirect to:" ), vbox );

  KHBox *hbox = new KHBox( vbox );
  hbox->setSpacing(4);
  mEditTo = new KMLineEdit( true, hbox, "toLine" );
  mEditTo->setMinimumWidth( 300 );

  mBtnTo = new QPushButton( QString(), hbox );
  mBtnTo->setObjectName( "toBtn" );
  mBtnTo->setIcon( BarIconSet( "contents", K3Icon::SizeSmall ) );
  mBtnTo->setMinimumSize( mBtnTo->sizeHint() * 1.2 );
  mBtnTo->setToolTip( i18n("Use the Address-Selection Dialog") );
  mBtnTo->setWhatsThis( i18n("This button opens a separate dialog "
                                 "where you can select recipients out "
                                 "of all available addresses." ) );

  connect( mBtnTo, SIGNAL(clicked()), SLOT(slotAddrBook()) );

  mLabelTo->setBuddy( mBtnTo );
  mEditTo->setFocus();

  setButtonGuiItem( User1, KGuiItem( i18n("&Send Now"), "mail_send" ) );
  setButtonGuiItem( User2, KGuiItem( i18n("Send &Later"), "queue" ) );
}

//-----------------------------------------------------------------------------
void RedirectDialog::slotUser1()
{
  mImmediate = true;
  accept();
}

//-----------------------------------------------------------------------------
void RedirectDialog::slotUser2()
{
  mImmediate = false;
  accept();
}

//-----------------------------------------------------------------------------
void RedirectDialog::accept()
{
  mResentTo = mEditTo->text();
  if ( mResentTo.isEmpty() ) {
    KMessageBox::sorry( this,
        i18n("You cannot redirect the message without an address."),
        i18n("Empty Redirection Address") );
  }
  else done( Ok );
}

//-----------------------------------------------------------------------------
void RedirectDialog::slotAddrBook()
{
  AddressesDialog dlg( this );

  mResentTo = mEditTo->text();
  if ( !mResentTo.isEmpty() ) {
      QStringList lst = EmailAddressTools::splitAddressList( mResentTo );
      dlg.setSelectedTo( lst );
  }

  dlg.setRecentAddresses(
      RecentAddresses::self( KMKernel::config() )->kabcAddresses() );

  // Make it impossible to specify Cc or Bcc addresses as we support
  // only the Redirect-To header!
  dlg.setShowCC( false );
  dlg.setShowBCC( false );

  if (dlg.exec()==QDialog::Rejected) return;

  mEditTo->setText( dlg.to().join(", ") );
  mEditTo->setModified( true );
}

#include "redirectdialog.moc"
<commit_msg>Fix other signal/slot<commit_after>/*
    This file is part of KMail.
    Copyright (c) 2003 Andreas Gungl <a.gungl@gmx.de>

    KMail is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "config.h"

#include "redirectdialog.h"

#include "kmkernel.h"
#include "kmlineeditspell.h"

#include <emailfunctions/email.h>
#include <addressesdialog.h>
using KPIM::AddressesDialog;
#include "recentaddresses.h"
using KRecentAddress::RecentAddresses;

#include <kiconloader.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kvbox.h>

#include <QToolTip>

#include <QLabel>
#include <QPushButton>
#include <QStringList>

#include <QFrame>

using namespace KMail;

RedirectDialog::RedirectDialog( QWidget *parent, bool immediate )
  : KDialog( parent )
{
  setCaption( i18n( "Redirect Message" ) );
  setButtons( User1|User2|Cancel );
  setDefaultButton( immediate ? User1 : User2 );
  QFrame *vbox = new KVBox( this );
  setMainWidget( vbox );
  mLabelTo = new QLabel( i18n( "Select the recipient &addresses "
                               "to redirect to:" ), vbox );

  KHBox *hbox = new KHBox( vbox );
  hbox->setSpacing(4);
  mEditTo = new KMLineEdit( true, hbox, "toLine" );
  mEditTo->setMinimumWidth( 300 );

  mBtnTo = new QPushButton( QString(), hbox );
  mBtnTo->setObjectName( "toBtn" );
  mBtnTo->setIcon( BarIconSet( "contents", K3Icon::SizeSmall ) );
  mBtnTo->setMinimumSize( mBtnTo->sizeHint() * 1.2 );
  mBtnTo->setToolTip( i18n("Use the Address-Selection Dialog") );
  mBtnTo->setWhatsThis( i18n("This button opens a separate dialog "
                                 "where you can select recipients out "
                                 "of all available addresses." ) );

  connect( mBtnTo, SIGNAL(clicked()), SLOT(slotAddrBook()) );

  mLabelTo->setBuddy( mBtnTo );
  mEditTo->setFocus();

  setButtonGuiItem( User1, KGuiItem( i18n("&Send Now"), "mail_send" ) );
  setButtonGuiItem( User2, KGuiItem( i18n("Send &Later"), "queue" ) );
  connect(this,SIGNAL(user1Clicked()),this, SLOT(slotUser1()));
  connect(this,SIGNAL(user2Clicked()),this, SLOT(slotUser2()));
}

//-----------------------------------------------------------------------------
void RedirectDialog::slotUser1()
{
  mImmediate = true;
  accept();
}

//-----------------------------------------------------------------------------
void RedirectDialog::slotUser2()
{
  mImmediate = false;
  accept();
}

//-----------------------------------------------------------------------------
void RedirectDialog::accept()
{
  mResentTo = mEditTo->text();
  if ( mResentTo.isEmpty() ) {
    KMessageBox::sorry( this,
        i18n("You cannot redirect the message without an address."),
        i18n("Empty Redirection Address") );
  }
  else done( Ok );
}

//-----------------------------------------------------------------------------
void RedirectDialog::slotAddrBook()
{
  AddressesDialog dlg( this );

  mResentTo = mEditTo->text();
  if ( !mResentTo.isEmpty() ) {
      QStringList lst = EmailAddressTools::splitAddressList( mResentTo );
      dlg.setSelectedTo( lst );
  }

  dlg.setRecentAddresses(
      RecentAddresses::self( KMKernel::config() )->kabcAddresses() );

  // Make it impossible to specify Cc or Bcc addresses as we support
  // only the Redirect-To header!
  dlg.setShowCC( false );
  dlg.setShowBCC( false );

  if (dlg.exec()==QDialog::Rejected) return;

  mEditTo->setText( dlg.to().join(", ") );
  mEditTo->setModified( true );
}

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


<commit_before>/***************************************************************************
                          filter_ldif.cxx  -  description
                             -------------------
    begin                : Fri Dec 1, 2000
    copyright            : (C) 2000 by Oliver Strutynski
    email                : olistrut@gmx.de
 ***************************************************************************/

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

#include "filter_ldif.hxx"

#include <kfiledialog.h>
#include <klocale.h>
#include <qtextstream.h>
#include <stdlib.h>

filter_ldif::filter_ldif() : filter(i18n("Import Netscape LDIF Adress Book 1(.LDIF)"),"Oliver Strutynski")
{}

filter_ldif::~filter_ldif()
{}

void filter_ldif::import(filterInfo *info) {
	 QString _file;
	 char     file[1024];
   char     dir[1024];
   QWidget *parent=info->parent();
   cout << parent << "\n";

   sprintf(dir,getenv("HOME"));

   _file=KFileDialog::getOpenFileName(dir,"*.ldif *.LDIF *.Ldif",parent);
   if (_file.length()==0) {
     info->alert(name(),i18n("No Adressbook choosen"));
     return;
   }
	 strcpy(file,_file.latin1());

	 QString from=i18n("from: "),to=i18n("to: ");
   from+="\t"; from+=file;
   to+="\t"; to+=i18n("the K Address Book");
   info->from(from);
   info->to(to);
   info->current(i18n("Currently converting .LDIF address file to Kab"));

   convert(file, info);

   info->current(100.0);
   info->overall(100.0);
   info->current(i18n("Done converting .LDIF address file to Kab"));
}

bool filter_ldif::convert(const char *filename, filterInfo *info) {
		QString caption;
		caption=i18n("Import Netscape LDIF Personal Adressbook (.LDIF)");

		if (!kabStart(info)) {
			info->alert(caption,"Error starting KAB");
			return false;
		}

		QFile f(filename);

		QString firstName="", email="", lastName="";
		QString title=""; QString givenName=""; QString comment="";
		QString organization=""; QString homepage=""; QString locality="";
		QString street=""; QString zipCode=""; QString phone="";
		QString fax=""; QString country=""; QString mobile=""; QString state="";
		QString department=""; QString empty="";

		// Initializing code table for base64 decoding
		initCodeTable();

		if ( f.open(IO_ReadOnly) ) {
			QTextStream t( &f );
      QString s;
      QString fieldname;

      // We need this for calculating progress
      uint fileSize = f.size();
      uint bytesProcessed = 0;

      // Set to true if data currently read is part of
      // a list of names. Lists will be ignored.
      bool isGroup=false;

      while ( !t.eof() ) {
				s = t.readLine();
				bytesProcessed += s.length();
				if (s.isEmpty()) {
					// Newline: Write data
					if (!isGroup) {
  					kabAddress(	info,i18n("Netscape Addressbook"), givenName, email, title,firstName,empty,lastName,
												street, locality, state, zipCode, country, organization, department,
												empty, empty, phone, fax, mobile, empty, homepage, empty,
												comment,empty);

  					firstName=""; email=""; lastName=""; title="";
  					givenName=""; comment=""; organization=""; homepage="";
  					locality=""; street=""; zipCode=""; phone="";
  					fax=""; country=""; mobile=""; state=""; department="";
		   		} else {
						info->log("Warning: List data is being ignored.");
		   		}
					isGroup=false;
	   		} else {
    			int position = s.find("::");
    			if (position != -1) {
    				// String is BASE64 encoded
    				fieldname = s.left(position);
    				s = decodeBase64(s.mid(position+3, s.length()-position-2));
    			} else {
    				position = s.find(":");
    				fieldname = s.left(position);
    				// Convert Utf8 string to unicode so special characters are preserved
	    	    // We need this since we are reading normal strings from the file
	    			// which are not converted automatically
	    			s = QString::fromUtf8(s.mid(position+2, s.length()-position-2).latin1());
  	  		}

      		if (fieldname == "givenname") {
     				firstName=s;
         	} else if (fieldname == "sn") {
     				lastName=s;
	        } else if (fieldname == "mail") {
	     			email=s;
	       	} else if (fieldname == "title") {
	     			title=s;
	       	} else if (fieldname == "cn") {
	     			givenName=s;
	       	} else if (fieldname == "o") {
	     			organization=s;
	       	} else if (fieldname == "description") {
	     			comment=s;
	       	} else if (fieldname == "homeurl") {
  	   			homepage=s;
	       	} else if (fieldname == "homephone") {
  	 				if (phone.length() > 0) { info->log("Discarding Phone Number "+s); }
  	  			phone=s;
	       	} else if (fieldname == "telephonenumber") {
	     			if (phone.length() > 0) { info->log("Discarding Phone Number "+s); }
	     			phone=s;
	       	} else if (fieldname == "postalcode") {
	     			zipCode=s;
	       	} else if (fieldname == "facsimiletelephonenumber") {
	     			fax=s;
	       	} else if (fieldname == "streetaddress") {
    				street=s;
      		} else if (fieldname == "locality") {
    				locality=s;
      		} else if (fieldname == "countryname") {
	   				country=s;
      		} else if (fieldname == "cellphone") {
    				mobile=s;
      		} else if (fieldname == "st") {
	 	 				state=s;
      		} else if (fieldname == "ou") {
    				department=s;
      		} else if (fieldname == "objectclass") {
    				if (s == "groupOfNames") { isGroup = true; }
	     		}
  	  		// update progress information
    			info->current((float)bytesProcessed/fileSize*100);
    			info->overall((float)bytesProcessed/fileSize*100);
    		}
			}
     	f.close();
		} else {
			char msg[1024];
			sprintf(msg,i18n("Can't open '%s' for reading").latin1(),filename);
      info->alert(caption,msg);
      return false;
		}

    kabStop(info);
   	return true;
}

/*
* Decodes a BASE-64 encoded stream to recover the original data and compacts white space.
 * Code heavily based on java code written by Kevin Kelley (kelley@ruralnet.net)
 * published unter the GNU Library Public License
*/
QString filter_ldif::decodeBase64(QString input)
{

    // cout << "  Trying to decode base64 string: " << input << "\n";
    QString result;

    int tempLen = input.length();
    for(unsigned int i=0; i<input.length(); i++) {
        if(codes[ input[i].latin1() ] < 0) {
	   // cout << "Invalid character in base64 string: " << input[i].latin1() << "\n";
	   --tempLen; // ignore non-valid chars and padding
        }
    }

    // calculate required length:
    //  -- 3 bytes for every 4 valid base64 chars
    //  -- plus 2 bytes if there are 3 extra base64 chars,
    //     or plus 1 byte if there are 2 extra.
    int len = (tempLen / 4) * 3;
    if ((tempLen % 4) == 3) len += 2;
    if ((tempLen % 4) == 2) len += 1;

    int shift = 0; // # of excess bits stored in accum
    int accum = 0; // excess bits

    // we now loop over through the entire string
    for (unsigned int i=0; i<input.length(); i++) {
        int value = codes[ input[i].latin1() ];

        if ( value >= 0 ) {         // skip over non-code
            accum <<= 6;            // bits shift up by 6 each time thru
            shift += 6;             // loop, with new bits being put in
            accum |= value;         // at the bottom.
            if ( shift >= 8 ) {      // whenever there are 8 or more shifted in,
                shift -= 8;          // write them out (from the top, leaving any
                                    // excess at the bottom for next iteration.
                result += (char) ((accum >> shift) & 0xff);
            }
        }
    }

    // Remove any linefeeds, tabs and multiple space from decoded string and
    // convert to unicode.
    result = QString::fromUtf8(result.latin1());
    result = result.simplifyWhiteSpace();
    return result;
}

/* Initialize lookup */
void filter_ldif::initCodeTable() {
    // chars for 0..63
    for (int i=0; i<256; i++) codes[i] = -1;
    for (int i = 'A'; i <= 'Z'; i++) codes[i] = (int)(i - 'A');
    for (int i = 'a'; i <= 'z'; i++) codes[i] = (int)(26 + i - 'a');
    for (int i = '0'; i <= '9'; i++) codes[i] = (int)(52 + i - '0');
    codes['+'] = 62;
    codes['/'] = 63;
}

<commit_msg>Added iostream.h<commit_after>/***************************************************************************
                          filter_ldif.cxx  -  description
                             -------------------
    begin                : Fri Dec 1, 2000
    copyright            : (C) 2000 by Oliver Strutynski
    email                : olistrut@gmx.de
 ***************************************************************************/

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

#include <iostream.h>
#include <stdlib.h>

#include <qtextstream.h>

#include <kfiledialog.h>
#include <klocale.h>

#include "filter_ldif.hxx"

filter_ldif::filter_ldif() : filter(i18n("Import Netscape LDIF Adress Book 1(.LDIF)"),"Oliver Strutynski")
{}

filter_ldif::~filter_ldif()
{}

void filter_ldif::import(filterInfo *info) {
	 QString _file;
	 char     file[1024];
   char     dir[1024];
   QWidget *parent=info->parent();
   cout << parent << "\n";

   sprintf(dir,getenv("HOME"));

   _file=KFileDialog::getOpenFileName(dir,"*.ldif *.LDIF *.Ldif",parent);
   if (_file.length()==0) {
     info->alert(name(),i18n("No Adressbook choosen"));
     return;
   }
	 strcpy(file,_file.latin1());

	 QString from=i18n("from: "),to=i18n("to: ");
   from+="\t"; from+=file;
   to+="\t"; to+=i18n("the K Address Book");
   info->from(from);
   info->to(to);
   info->current(i18n("Currently converting .LDIF address file to Kab"));

   convert(file, info);

   info->current(100.0);
   info->overall(100.0);
   info->current(i18n("Done converting .LDIF address file to Kab"));
}

bool filter_ldif::convert(const char *filename, filterInfo *info) {
		QString caption;
		caption=i18n("Import Netscape LDIF Personal Adressbook (.LDIF)");

		if (!kabStart(info)) {
			info->alert(caption,"Error starting KAB");
			return false;
		}

		QFile f(filename);

		QString firstName="", email="", lastName="";
		QString title=""; QString givenName=""; QString comment="";
		QString organization=""; QString homepage=""; QString locality="";
		QString street=""; QString zipCode=""; QString phone="";
		QString fax=""; QString country=""; QString mobile=""; QString state="";
		QString department=""; QString empty="";

		// Initializing code table for base64 decoding
		initCodeTable();

		if ( f.open(IO_ReadOnly) ) {
			QTextStream t( &f );
      QString s;
      QString fieldname;

      // We need this for calculating progress
      uint fileSize = f.size();
      uint bytesProcessed = 0;

      // Set to true if data currently read is part of
      // a list of names. Lists will be ignored.
      bool isGroup=false;

      while ( !t.eof() ) {
				s = t.readLine();
				bytesProcessed += s.length();
				if (s.isEmpty()) {
					// Newline: Write data
					if (!isGroup) {
  					kabAddress(	info,i18n("Netscape Addressbook"), givenName, email, title,firstName,empty,lastName,
												street, locality, state, zipCode, country, organization, department,
												empty, empty, phone, fax, mobile, empty, homepage, empty,
												comment,empty);

  					firstName=""; email=""; lastName=""; title="";
  					givenName=""; comment=""; organization=""; homepage="";
  					locality=""; street=""; zipCode=""; phone="";
  					fax=""; country=""; mobile=""; state=""; department="";
		   		} else {
						info->log("Warning: List data is being ignored.");
		   		}
					isGroup=false;
	   		} else {
    			int position = s.find("::");
    			if (position != -1) {
    				// String is BASE64 encoded
    				fieldname = s.left(position);
    				s = decodeBase64(s.mid(position+3, s.length()-position-2));
    			} else {
    				position = s.find(":");
    				fieldname = s.left(position);
    				// Convert Utf8 string to unicode so special characters are preserved
	    	    // We need this since we are reading normal strings from the file
	    			// which are not converted automatically
	    			s = QString::fromUtf8(s.mid(position+2, s.length()-position-2).latin1());
  	  		}

      		if (fieldname == "givenname") {
     				firstName=s;
         	} else if (fieldname == "sn") {
     				lastName=s;
	        } else if (fieldname == "mail") {
	     			email=s;
	       	} else if (fieldname == "title") {
	     			title=s;
	       	} else if (fieldname == "cn") {
	     			givenName=s;
	       	} else if (fieldname == "o") {
	     			organization=s;
	       	} else if (fieldname == "description") {
	     			comment=s;
	       	} else if (fieldname == "homeurl") {
  	   			homepage=s;
	       	} else if (fieldname == "homephone") {
  	 				if (phone.length() > 0) { info->log("Discarding Phone Number "+s); }
  	  			phone=s;
	       	} else if (fieldname == "telephonenumber") {
	     			if (phone.length() > 0) { info->log("Discarding Phone Number "+s); }
	     			phone=s;
	       	} else if (fieldname == "postalcode") {
	     			zipCode=s;
	       	} else if (fieldname == "facsimiletelephonenumber") {
	     			fax=s;
	       	} else if (fieldname == "streetaddress") {
    				street=s;
      		} else if (fieldname == "locality") {
    				locality=s;
      		} else if (fieldname == "countryname") {
	   				country=s;
      		} else if (fieldname == "cellphone") {
    				mobile=s;
      		} else if (fieldname == "st") {
	 	 				state=s;
      		} else if (fieldname == "ou") {
    				department=s;
      		} else if (fieldname == "objectclass") {
    				if (s == "groupOfNames") { isGroup = true; }
	     		}
  	  		// update progress information
    			info->current((float)bytesProcessed/fileSize*100);
    			info->overall((float)bytesProcessed/fileSize*100);
    		}
			}
     	f.close();
		} else {
			char msg[1024];
			sprintf(msg,i18n("Can't open '%s' for reading").latin1(),filename);
      info->alert(caption,msg);
      return false;
		}

    kabStop(info);
   	return true;
}

/*
* Decodes a BASE-64 encoded stream to recover the original data and compacts white space.
 * Code heavily based on java code written by Kevin Kelley (kelley@ruralnet.net)
 * published unter the GNU Library Public License
*/
QString filter_ldif::decodeBase64(QString input)
{

    // cout << "  Trying to decode base64 string: " << input << "\n";
    QString result;

    int tempLen = input.length();
    for(unsigned int i=0; i<input.length(); i++) {
        if(codes[ input[i].latin1() ] < 0) {
	   // cout << "Invalid character in base64 string: " << input[i].latin1() << "\n";
	   --tempLen; // ignore non-valid chars and padding
        }
    }

    // calculate required length:
    //  -- 3 bytes for every 4 valid base64 chars
    //  -- plus 2 bytes if there are 3 extra base64 chars,
    //     or plus 1 byte if there are 2 extra.
    int len = (tempLen / 4) * 3;
    if ((tempLen % 4) == 3) len += 2;
    if ((tempLen % 4) == 2) len += 1;

    int shift = 0; // # of excess bits stored in accum
    int accum = 0; // excess bits

    // we now loop over through the entire string
    for (unsigned int i=0; i<input.length(); i++) {
        int value = codes[ input[i].latin1() ];

        if ( value >= 0 ) {         // skip over non-code
            accum <<= 6;            // bits shift up by 6 each time thru
            shift += 6;             // loop, with new bits being put in
            accum |= value;         // at the bottom.
            if ( shift >= 8 ) {      // whenever there are 8 or more shifted in,
                shift -= 8;          // write them out (from the top, leaving any
                                    // excess at the bottom for next iteration.
                result += (char) ((accum >> shift) & 0xff);
            }
        }
    }

    // Remove any linefeeds, tabs and multiple space from decoded string and
    // convert to unicode.
    result = QString::fromUtf8(result.latin1());
    result = result.simplifyWhiteSpace();
    return result;
}

/* Initialize lookup */
void filter_ldif::initCodeTable() {
    // chars for 0..63
    for (int i=0; i<256; i++) codes[i] = -1;
    for (int i = 'A'; i <= 'Z'; i++) codes[i] = (int)(i - 'A');
    for (int i = 'a'; i <= 'z'; i++) codes[i] = (int)(26 + i - 'a');
    for (int i = '0'; i <= '9'; i++) codes[i] = (int)(52 + i - '0');
    codes['+'] = 62;
    codes['/'] = 63;
}

<|endoftext|>