<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#ifndef _MSC_VER
#define fopen_s(pFile,filename,mode) ((*(pFile))=fopen((filename),(mode)))==NULL
#endif

unsigned char *readBMP(char *pszFilename, long *lgSize, long *offset)
{
	FILE *TARGET;
	unsigned char *mem;
	long h = 0;
	unsigned char bitmapFileHeader[14];
	unsigned char bitmapInfoHeader[40];
	unsigned int rawsize;

	fopen_s(&TARGET, pszFilename, "rb");
	if(!TARGET)
	{
		printf("readBMP(): Unable to open file %s\n", pszFilename);
		*lgSize = 0;
		return 0;
	}

	fread(&bitmapFileHeader, sizeof(unsigned char) * 14, 1, TARGET);
	fread(&bitmapInfoHeader, sizeof(unsigned char) * 40, 1, TARGET);

	if(bitmapInfoHeader[14] != 24)
	{
		printf("readBMP(): Not a 24-bit BMP File\n");
		*lgSize = 0;
		return 0;
	}

	if(offset != 0)
		*offset = bitmapFileHeader[6]         |
		          (bitmapFileHeader[7] << 8)  |
		          (bitmapFileHeader[8] << 16) |
		          (bitmapFileHeader[9] << 24);

	fseek(TARGET, 54, SEEK_SET);
	rawsize = bitmapInfoHeader[20]         |
	          (bitmapInfoHeader[21] << 8)  |
	          (bitmapInfoHeader[22] << 16) |
	          (bitmapInfoHeader[23] << 24);
	h = (long) rawsize - 54;

	//printf("%d\n", rawsize);

	mem = (unsigned char*)malloc(h+1);
	if(mem == NULL)
	{
		printf("readBMP(): Memory not allocated\n");
		*lgSize = 0;
		return 0;
	}

	fread(mem, sizeof(unsigned char), h, TARGET);
	*lgSize = h;
	fclose(TARGET);
	return mem;
}

int main(int argc, char **argv)
{
	long fileSize, stenoSize, endOffset;
	unsigned int w, h;
	FILE *writeFile;
	unsigned char xorChar = 0x3d;
	unsigned char *filecontents = 0;
	unsigned char *stenoContents = 0;

	filecontents = readBMP(argv[1], &fileSize, &endOffset);
	if(filecontents == 0)
	{
		printf("main(): bad bmp file\n");
		return -1;
	}

	endOffset *= 3;

	//printf("Offset: %d\n", endOffset);

	stenoContents = readBMP(argv[2], &stenoSize, 0);
	if(stenoContents == 0)
	{
		printf("main(): bad steno bmp file\n");
		return -1;
	}

	fopen_s(&writeFile, argv[3], "wb");
	if(!writeFile)
	{
		printf("main(): bad output file\n");
		return -1;
	}

	double divisor = 0.90;

	fileSize = fileSize >= endOffset ? endOffset : fileSize;

	for(unsigned int x = 0; x < fileSize; x += 3)
	{
		unsigned char xc1 = filecontents[x]   - (unsigned char)(stenoContents[x]   * divisor);
		unsigned char xc2 = filecontents[x+1] - (unsigned char)(stenoContents[x+1] * divisor);
		unsigned char xc3 = filecontents[x+2] - (unsigned char)(stenoContents[x+2] * divisor);
		unsigned char xc = ((xc3 << 5) & 0xE0) | ((xc2 << 3) & 0x18) | (xc1 & 0x07);
		//((xc2 << 4) & 0xF0) | (xc1 & 0x0F);
		fwrite(&xc, 1, 1, writeFile);
	}

	fclose(writeFile);
	free(filecontents);
	free(stenoContents);
}<commit_msg>Added argument options<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

#ifndef _MSC_VER
#define fopen_s(pFile,filename,mode) ((*(pFile))=fopen((filename),(mode)))==NULL
#endif

typedef struct s_params
{
	char *inputFilename;
	char *outputFilename;
	char *blendFilename;
	long fileSize;
	int canExecute; // equals 7 when true
} params;

params commandParams(char* arguments[], int argCount)
{
	char y, *command;
	params p;
	p.canExecute = 0;
	p.fileSize = 0;

	for(int CycleArguments = 1; CycleArguments < argCount; CycleArguments++)
	{
		y = (arguments[CycleArguments])[0];

		if(y == '-')
		{
			command = arguments[CycleArguments];
			++command;

			if(strcmp(command, "i") == 0)
			{
				// Get the port, it will be the next "command"
				if(CycleArguments + 1 < argCount){
					command = arguments[++CycleArguments];
					p.inputFilename = (char*)malloc(sizeof(char) * (strlen(command) + 1));
					memcpy(p.inputFilename, command, strlen(command)+1);
					p.canExecute |= 0x01;
				}
			}
			else if(strcmp(command, "o") == 0)
			{
				if(CycleArguments + 1 < argCount){
					command = arguments[++CycleArguments];
					p.outputFilename = (char*)malloc(sizeof(char) * (strlen(command) + 1));
					memcpy(p.outputFilename, command, strlen(command)+1);
					p.canExecute |= 0x02;
				}
			}
			else if(strcmp(command, "b") == 0)
			{
				if(CycleArguments + 1 < argCount){
					command = arguments[++CycleArguments];
					p.blendFilename = (char*)malloc(sizeof(char) * (strlen(command) + 1));
					memcpy(p.blendFilename, command, strlen(command)+1);
					p.canExecute |= 0x04;
				}
			}
			else if(strcmp(command, "s") == 0)
			{
				if(CycleArguments + 1 < argCount){
					command = arguments[++CycleArguments];
					p.fileSize = atoi(command);
				}
			}
		}
	}
	return p;
}

unsigned char *readBMP(char *pszFilename, long *lgSize, long *offset)
{
	FILE *TARGET;
	unsigned char *mem;
	long h = 0;
	unsigned char bitmapFileHeader[14];
	unsigned char bitmapInfoHeader[40];
	unsigned int rawsize;

	fopen_s(&TARGET, pszFilename, "rb");
	if(!TARGET)
	{
		printf("readBMP(): Unable to open file %s\n", pszFilename);
		*lgSize = 0;
		return 0;
	}

	fread(&bitmapFileHeader, sizeof(unsigned char) * 14, 1, TARGET);
	fread(&bitmapInfoHeader, sizeof(unsigned char) * 40, 1, TARGET);

	if(bitmapInfoHeader[14] != 24)
	{
		printf("readBMP(): Not a 24-bit BMP File\n");
		*lgSize = 0;
		return 0;
	}

	if(offset != 0)
		*offset = bitmapFileHeader[6]         |
		          (bitmapFileHeader[7] << 8)  |
		          (bitmapFileHeader[8] << 16) |
		          (bitmapFileHeader[9] << 24);

	fseek(TARGET, 54, SEEK_SET);
	rawsize = bitmapInfoHeader[20]         |
	          (bitmapInfoHeader[21] << 8)  |
	          (bitmapInfoHeader[22] << 16) |
	          (bitmapInfoHeader[23] << 24);
	h = (long) rawsize - 54;

	//printf("%d\n", rawsize);

	mem = (unsigned char*)malloc(h+1);
	if(mem == NULL)
	{
		printf("readBMP(): Memory not allocated\n");
		*lgSize = 0;
		return 0;
	}

	fread(mem, sizeof(unsigned char), h, TARGET);
	*lgSize = h;
	fclose(TARGET);
	return mem;
}

int main(int argc, char **argv)
{
	long fileSize, stenoSize, endOffset;
	unsigned int w, h;
	FILE *writeFile;
	unsigned char xorChar = 0x3d;
	unsigned char *filecontents = 0;
	unsigned char *stenoContents = 0;
	params p;

	p = commandParams(argv, argc);

	if(p.canExecute != 7)
	{
		printf("Incorrect parameters:\n");
		printf("-i inputfile -b blendfile -o outputfile [-s size_in_bytes]\n");
		return -1;
	}

	filecontents = readBMP(p.inputFilename, &fileSize, &endOffset);
	if(filecontents == 0)
	{
		printf("main(): bad input file\n");
		return -1;
	}

	endOffset *= 3;

	//printf("Offset: %d\n", endOffset);

	stenoContents = readBMP(p.blendFilename, &stenoSize, 0);
	if(stenoContents == 0)
	{
		printf("main(): bad blend file\n");
		return -1;
	}

	fopen_s(&writeFile, p.outputFilename, "wb");
	if(!writeFile)
	{
		printf("main(): bad output file\n");
		return -1;
	}

	double divisor = 0.90;

	if(endOffset == 0)
		printf("Embedded filesize not found. Please specify one as an argument. Decoding using full size of input file.\n",);

	if(p.fileSize <= 0){
		fileSize = fileSize >= endOffset ? endOffset : fileSize;
	} else {
		fileSize = fileSize >= p.fileSize ? p.fileSize : fileSize;
	}

	printf("Output Filesize: %u\n", fileSize);

	for(unsigned int x = 0; x < fileSize; x += 3)
	{
		unsigned char xc1 = filecontents[x]   - (unsigned char)(stenoContents[x]   * divisor);
		unsigned char xc2 = filecontents[x+1] - (unsigned char)(stenoContents[x+1] * divisor);
		unsigned char xc3 = filecontents[x+2] - (unsigned char)(stenoContents[x+2] * divisor);
		unsigned char xc = ((xc3 << 5) & 0xE0) | ((xc2 << 3) & 0x18) | (xc1 & 0x07);
		//((xc2 << 4) & 0xF0) | (xc1 & 0x0F);
		fwrite(&xc, 1, 1, writeFile);
	}

	fclose(writeFile);
	free(filecontents);
	free(stenoContents);
}<|endoftext|>


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

#ifndef __BASE_BITFIELD_HH__
#define __BASE_BITFIELD_HH__

#include "base/types.hh"

/**
 * Generate a 64-bit mask of 'nbits' 1s, right justified.
 */
inline uint64_t
mask(int nbits)
{
    return (nbits == 64) ? (uint64_t)-1LL : (1ULL << nbits) - 1;
}

/**
 * Extract the bitfield from position 'first' to 'last' (inclusive)
 * from 'val' and right justify it.  MSB is numbered 63, LSB is 0.
 */
template <class T>
inline
T
bits(T val, int first, int last)
{
    int nbits = first - last + 1;
    return (val >> last) & mask(nbits);
}

/**
 * Extract the bit from this position from 'val' and right justify it.
 */
template <class T>
inline
T
bits(T val, int bit)
{
    return bits(val, bit, bit);
}

/**
 * Mask off the given bits in place like bits() but without shifting.
 * msb = 63, lsb = 0
 */
template <class T>
inline
T
mbits(T val, int first, int last)
{
    return val & (mask(first+1) & ~mask(last));
}

inline uint64_t
mask(int first, int last)
{
    return mbits((uint64_t)-1LL, first, last);
}

/**
 * Sign-extend an N-bit value to 64 bits.
 */
template <int N>
inline
int64_t
sext(uint64_t val)
{
    int sign_bit = bits(val, N-1, N-1);
    return sign_bit ? (val | ~mask(N)) : val;
}

/**
 * Return val with bits first to last set to bit_val
 */
template <class T, class B>
inline
T
insertBits(T val, int first, int last, B bit_val)
{
    T t_bit_val = bit_val;
    T bmask = mask(first - last + 1) << last;
    return ((t_bit_val << last) & bmask) | (val & ~bmask);
}

/**
 * Overloaded for access to only one bit in value
 */
template <class T, class B>
inline
T
insertBits(T val, int bit, B bit_val)
{
    return insertBits(val, bit, bit, bit_val);
}

/**
 * A convenience function to replace bits first to last of val with bit_val
 * in place.
 */
template <class T, class B>
inline
void
replaceBits(T& val, int first, int last, B bit_val)
{
    val = insertBits(val, first, last, bit_val);
}

/** Overloaded function to allow to access only 1 bit*/
template <class T, class B>
inline
void
replaceBits(T& val, int bit, B bit_val)
{
    val = insertBits(val, bit, bit, bit_val);
}
/**
 * Returns the bit position of the MSB that is set in the input
 */
inline
int
findMsbSet(uint64_t val) {
    int msb = 0;
    if (!val)
        return 0;
    if (bits(val, 63,32)) { msb += 32; val >>= 32; }
    if (bits(val, 31,16)) { msb += 16; val >>= 16; }
    if (bits(val, 15,8))  { msb += 8;  val >>= 8;  }
    if (bits(val, 7,4))   { msb += 4;  val >>= 4;  }
    if (bits(val, 3,2))   { msb += 2;  val >>= 2;  }
    if (bits(val, 1,1))   { msb += 1; }
    return msb;
}

/**
 * Returns the bit position of the LSB that is set in the input
 */
inline int
findLsbSet(uint64_t val) {
    int lsb = 0;
    if (!val)
        return sizeof(val) * 8;
    if (!bits(val, 31,0)) { lsb += 32; val >>= 32; }
    if (!bits(val, 15,0)) { lsb += 16; val >>= 16; }
    if (!bits(val, 7,0))  { lsb += 8;  val >>= 8;  }
    if (!bits(val, 3,0))  { lsb += 4;  val >>= 4;  }
    if (!bits(val, 1,0))  { lsb += 2;  val >>= 2;  }
    if (!bits(val, 0,0))  { lsb += 1; }
    return lsb;
}

#endif // __BASE_BITFIELD_HH__
<commit_msg>misc: Add functions for doing popcount and power-of-two checking<commit_after>/*
 * Copyright (c) 2003-2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Steve Reinhardt
 *          Nathan Binkert
 */

#ifndef __BASE_BITFIELD_HH__
#define __BASE_BITFIELD_HH__

#include "base/types.hh"

/**
 * Generate a 64-bit mask of 'nbits' 1s, right justified.
 */
inline uint64_t
mask(int nbits)
{
    return (nbits == 64) ? (uint64_t)-1LL : (1ULL << nbits) - 1;
}

/**
 * Extract the bitfield from position 'first' to 'last' (inclusive)
 * from 'val' and right justify it.  MSB is numbered 63, LSB is 0.
 */
template <class T>
inline
T
bits(T val, int first, int last)
{
    int nbits = first - last + 1;
    return (val >> last) & mask(nbits);
}

/**
 * Extract the bit from this position from 'val' and right justify it.
 */
template <class T>
inline
T
bits(T val, int bit)
{
    return bits(val, bit, bit);
}

/**
 * Mask off the given bits in place like bits() but without shifting.
 * msb = 63, lsb = 0
 */
template <class T>
inline
T
mbits(T val, int first, int last)
{
    return val & (mask(first+1) & ~mask(last));
}

inline uint64_t
mask(int first, int last)
{
    return mbits((uint64_t)-1LL, first, last);
}

/**
 * Sign-extend an N-bit value to 64 bits.
 */
template <int N>
inline
int64_t
sext(uint64_t val)
{
    int sign_bit = bits(val, N-1, N-1);
    return sign_bit ? (val | ~mask(N)) : val;
}

/**
 * Return val with bits first to last set to bit_val
 */
template <class T, class B>
inline
T
insertBits(T val, int first, int last, B bit_val)
{
    T t_bit_val = bit_val;
    T bmask = mask(first - last + 1) << last;
    return ((t_bit_val << last) & bmask) | (val & ~bmask);
}

/**
 * Overloaded for access to only one bit in value
 */
template <class T, class B>
inline
T
insertBits(T val, int bit, B bit_val)
{
    return insertBits(val, bit, bit, bit_val);
}

/**
 * A convenience function to replace bits first to last of val with bit_val
 * in place.
 */
template <class T, class B>
inline
void
replaceBits(T& val, int first, int last, B bit_val)
{
    val = insertBits(val, first, last, bit_val);
}

/** Overloaded function to allow to access only 1 bit*/
template <class T, class B>
inline
void
replaceBits(T& val, int bit, B bit_val)
{
    val = insertBits(val, bit, bit, bit_val);
}
/**
 * Returns the bit position of the MSB that is set in the input
 */
inline
int
findMsbSet(uint64_t val) {
    int msb = 0;
    if (!val)
        return 0;
    if (bits(val, 63,32)) { msb += 32; val >>= 32; }
    if (bits(val, 31,16)) { msb += 16; val >>= 16; }
    if (bits(val, 15,8))  { msb += 8;  val >>= 8;  }
    if (bits(val, 7,4))   { msb += 4;  val >>= 4;  }
    if (bits(val, 3,2))   { msb += 2;  val >>= 2;  }
    if (bits(val, 1,1))   { msb += 1; }
    return msb;
}

/**
 * Returns the bit position of the LSB that is set in the input
 */
inline int
findLsbSet(uint64_t val) {
    int lsb = 0;
    if (!val)
        return sizeof(val) * 8;
    if (!bits(val, 31,0)) { lsb += 32; val >>= 32; }
    if (!bits(val, 15,0)) { lsb += 16; val >>= 16; }
    if (!bits(val, 7,0))  { lsb += 8;  val >>= 8;  }
    if (!bits(val, 3,0))  { lsb += 4;  val >>= 4;  }
    if (!bits(val, 1,0))  { lsb += 2;  val >>= 2;  }
    if (!bits(val, 0,0))  { lsb += 1; }
    return lsb;
}

/**
 * Checks if a number is a power of two, or zero.
 */
template <class T>
inline bool
isPow2(T v) {
   return (v & (v - 1)) == (T)0;
}

/**
 * Returns the number of set ones in the provided value.
 * PD algorithm from
 * http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
 */
inline int
popCount(uint64_t val) {
#ifndef __has_builtin
    #define __has_builtin(foo) 0
#endif
#if defined(__GNUC__) || (defined(__clang__) && __has_builtin(__builtin_popcountl))
    return __builtin_popcountl(val);
#else
    const uint64_t m1 = 0x5555555555555555;  // ..010101b
    const uint64_t m2 = 0x3333333333333333;  // ..110011b
    const uint64_t m4 = 0x0f0f0f0f0f0f0f0f;  // ..001111b
    const uint64_t sum = 0x0101010101010101;

    val -= (val >> 1) & m1;               // 2 bits count -> 2 bits
    val = (val & m2) + ((val >> 2) & m2); // 4 bits count -> 4 bits
    val = (val + (val >> 4)) & m4;        // 8 bits count -> 8 bits
    return (val * sum) >> 56;             // horizontal sum
#endif // defined(__GNUC__) || (defined(__clang__) && __has_builtin(__builtin_popcountl))
}
#endif // __BASE_BITFIELD_HH__
<|endoftext|>


<commit_before>/**
 * @file ct2ctml.cpp
 * Driver for the system call to the python executable that converts
 * cti files to ctml files (see \ref inputfiles).
 */
// Copyright 2001-2005  California Institute of Technology

#include "cantera/base/ct_defs.h"
#include "cantera/base/ctexceptions.h"
#include "cantera/base/ctml.h"
#include "cantera/base/global.h"
#include "cantera/base/stringUtils.h"
#include "../../ext/libexecstream/exec-stream.h"

#include <fstream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace Cantera;
using namespace std;

namespace ctml
{

//! return the full path to the Python interpreter.
/*!
 * Use the environment variable PYTHON_CMD if it is set. If not, return
 * the string 'python'.
 *
 * Note, there are hidden problems here that really direct us to use
 * a full pathname for the location of python. Basically the system
 * call will use the shell /bin/sh, in order to launch python.
 * This default shell may not be the shell that the user is employing.
 * Therefore, the default path to python may be different during
 * a system call than during the default user shell environment.
 * This is quite a headache. The answer is to always set the
 * PYTHON_CMD environmental variable in the user environment to
 * an absolute path to locate the python executable. Then this
 * issue goes away.
 */
static string pypath()
{
    string s = "python";
    const char* py = getenv("PYTHON_CMD");

    if (py) {
        string sp = stripws(string(py));
        if (sp.size() > 0) {
            s = sp;
        }
    }
    return s;
}

// Convert a cti file into a ctml file
/*
 *
 *  @param   file    Pointer to the file
 *  @param   debug   Turn on debug printing
 *
 *  @ingroup inputfiles
 */
void ct2ctml(const char* file, const int debug)
{
#ifdef HAS_NO_PYTHON
    /*
     *  Section to bomb out if python is not
     *  present in the computation environment.
     */
    string ppath = file;
    throw CanteraError("ct2ctml",
                       "python cti to ctml conversion requested for file, " + ppath +
                       ", but not available in this computational environment");
#endif

    string python_output;
    int python_exit_code;
    try {
        exec_stream_t python;
        python.set_wait_timeout(exec_stream_t::s_all, 1800000); // 30 minutes
        python.start(pypath(), "-i");
        stringstream output_stream;
        python.in() <<
                    "if True:\n" << // Use this so that the rest is a single block
                    "    import sys\n" <<
                    "    sys.stderr = sys.stdout\n" <<
                    "    import ctml_writer\n" <<
                    "    ctml_writer.convert(r'" << file << "')\n" <<
                    "    sys.exit(0)\n\n"
                    "sys.exit(7)\n";
        python.close_in();
        std::string line;
        while (python.out().good()) {
            std::getline(python.out(), line);
            output_stream << line << std::endl;;
        }
        python.close();
        python_exit_code = python.exit_code();
        python_output = stripws(output_stream.str());
    } catch (std::exception& err) {
        // Report failure to execute Python
        stringstream message;
        message << "Error executing python while converting input file:\n";
        message << "Python command was: '" << pypath() << "'\n";
        message << err.what() << std::endl;
        throw CanteraError("ct2ctml", message.str());
    }

    if (python_exit_code != 0) {
        // Report a failure in the conversion process
        stringstream message;
        message << "Error converting input file \"" << file << "\" to CTML.\n";
        message << "Python command was: '" << pypath() << "'\n";
        message << "The exit code was: " << python_exit_code << "\n";
        if (python_output.size() > 0) {
            message << "-------------- start of converter log --------------\n";
            message << python_output << std::endl;
            message << "--------------- end of converter log ---------------";
        } else {
            message << "The command did not produce any output." << endl;
        }
        throw CanteraError("ct2ctml", message.str());
    }

    if (python_output.size() > 0) {
        // Warn if there was any output from the conversion process
        stringstream message;
        message << "Warning: Unexpected output from CTI converter\n";
        message << "-------------- start of converter log --------------\n";
        message << python_output << std::endl;
        message << "--------------- end of converter log ---------------\n";
        writelog(message.str());
    }
}

void ck2cti(const std::string& in_file, const std::string& thermo_file,
            const std::string& transport_file, const std::string& id_tag)
{
#ifdef HAS_NO_PYTHON
    /*
     *  Section to bomb out if python is not
     *  present in the computation environment.
     */
    string ppath = file;
    throw CanteraError("ct2ctml",
                       "python ck to cti conversion requested for file, " + ppath +
                       ", but not available in this computational environment");
#endif

    string python_output;
    int python_exit_code;
    try {
        exec_stream_t python;
        python.set_wait_timeout(exec_stream_t::s_all, 1800000); // 30 minutes
        python.start(pypath(), "-i");
        stringstream output_stream;

        ostream& pyin = python.in();
        pyin << "if True:\n"; // Use this so that the rest is a single block
        pyin << "    import sys\n";
        pyin << "    sys.stderr = sys.stdout\n";
        pyin << "    import ck2cti\n";
        pyin << "    ck2cti.convertMech(r'" << in_file << "',";
        if (thermo_file != "" && thermo_file != "-") {
            pyin << " thermoFile=r'" << thermo_file << "',";
        }
        if (transport_file != "" && transport_file != "-") {
            pyin << " transportFile=r'" << transport_file << "',";
        }
        pyin << " phaseName='" << id_tag << "',";
        pyin << " quiet=True)\n";
        pyin << "    sys.exit(0)\n\n";
        pyin << "sys.exit(7)\n";
        python.close_in();

        std::string line;
        while (python.out().good()) {
            std::getline(python.out(), line);
            output_stream << line << std::endl;;
        }
        python.close();
        python_exit_code = python.exit_code();
        python_output = stripws(output_stream.str());
    } catch (std::exception& err) {
        // Report failure to execute Python
        stringstream message;
        message << "Error executing python while converting input file:\n";
        message << "Python command was: '" << pypath() << "'\n";
        message << err.what() << std::endl;
        throw CanteraError("ct2ctml", message.str());
    }

    if (python_exit_code != 0) {
        // Report a failure in the conversion process
        stringstream message;
        message << "Error converting input file \"" << in_file << "\" to CTI.\n";
        message << "Python command was: '" << pypath() << "'\n";
        message << "The exit code was: " << python_exit_code << "\n";
        if (python_output.size() > 0) {
            message << "-------------- start of converter log --------------\n";
            message << python_output << std::endl;
            message << "--------------- end of converter log ---------------";
        } else {
            message << "The command did not produce any output." << endl;
        }
        throw CanteraError("ck2cti", message.str());
    }

    if (python_output.size() > 0) {
        // Warn if there was any output from the conversion process
        stringstream message;
        message << "Warning: Unexpected output from CTI converter\n";
        message << "-------------- start of converter log --------------\n";
        message << python_output << std::endl;
        message << "--------------- end of converter log ---------------\n";
        writelog(message.str());
    }
}

// Read an ctml file from a file and fill up an XML tree
/*
 *  This is the main routine that reads a ctml file and puts it into
 *  an XML_Node tree
 *
 *  @param node    Root of the tree
 *  @param file    Name of the file
 *  @param debug   Turn on debugging printing
 */
void get_CTML_Tree(Cantera::XML_Node* rootPtr, const std::string file, const int debug)
{
    std::string ff, ext = "";

    // find the input file on the Cantera search path
    std::string inname = findInputFile(file);
    if (debug > 0) {
        writelog("Found file: "+inname+"\n");
    }

    if (inname == "") {
        throw CanteraError("get_CTML_Tree", "file "+file+" not found");
    }

    /*
     * Check whether or not the file is XML. If not, it will be first
     * processed with the preprocessor.
     */
    std::string::size_type idot = inname.rfind('.');
    if (idot != string::npos) {
        ext = inname.substr(idot, inname.size());
    }
    if (ext != ".xml" && ext != ".ctml") {
        try {
            ctml::ct2ctml(inname.c_str(), debug);
        } catch (std::exception& err) {
            writelog("get_CTML_Tree: caught an exception:\n");
            writelog(err.what());
        }
        string ffull = inname.substr(0,idot) + ".xml";
        ff = "./" + getBaseName(ffull) + ".xml";
        if (debug > 0) {
            writelogf("ffull name = %s\n", ffull.c_str());
            writelogf("ff name = %s\n", ff.c_str());
        }
    } else {
        ff = inname;
    }
    if (debug > 0) {
        writelog("Attempting to parse xml file " + ff + "\n");
    }
    ifstream fin(ff.c_str());
    if (!fin) {
        throw
        CanteraError("get_CTML_Tree",
                     "XML file " + ff + " not found");
    }
    rootPtr->build(fin);
    fin.close();
}

Cantera::XML_Node getCtmlTree(const std::string file)
{
    Cantera::XML_Node root;
    get_CTML_Tree(&root, file);
    return root;
}

}
<commit_msg>[cantera]: fixing a bug in file name variable. <commit_after>/**
 * @file ct2ctml.cpp
 * Driver for the system call to the python executable that converts
 * cti files to ctml files (see \ref inputfiles).
 */
// Copyright 2001-2005  California Institute of Technology

#include "cantera/base/ct_defs.h"
#include "cantera/base/ctexceptions.h"
#include "cantera/base/ctml.h"
#include "cantera/base/global.h"
#include "cantera/base/stringUtils.h"
#include "../../ext/libexecstream/exec-stream.h"

#include <fstream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace Cantera;
using namespace std;

namespace ctml
{

//! return the full path to the Python interpreter.
/*!
 * Use the environment variable PYTHON_CMD if it is set. If not, return
 * the string 'python'.
 *
 * Note, there are hidden problems here that really direct us to use
 * a full pathname for the location of python. Basically the system
 * call will use the shell /bin/sh, in order to launch python.
 * This default shell may not be the shell that the user is employing.
 * Therefore, the default path to python may be different during
 * a system call than during the default user shell environment.
 * This is quite a headache. The answer is to always set the
 * PYTHON_CMD environmental variable in the user environment to
 * an absolute path to locate the python executable. Then this
 * issue goes away.
 */
static string pypath()
{
    string s = "python";
    const char* py = getenv("PYTHON_CMD");

    if (py) {
        string sp = stripws(string(py));
        if (sp.size() > 0) {
            s = sp;
        }
    }
    return s;
}

// Convert a cti file into a ctml file
/*
 *
 *  @param   file    Pointer to the file
 *  @param   debug   Turn on debug printing
 *
 *  @ingroup inputfiles
 */
void ct2ctml(const char* file, const int debug)
{
#ifdef HAS_NO_PYTHON
    /*
     *  Section to bomb out if python is not
     *  present in the computation environment.
     */
    string ppath = file;
    throw CanteraError("ct2ctml",
                       "python cti to ctml conversion requested for file, " + ppath +
                       ", but not available in this computational environment");
#endif

    string python_output;
    int python_exit_code;
    try {
        exec_stream_t python;
        python.set_wait_timeout(exec_stream_t::s_all, 1800000); // 30 minutes
        python.start(pypath(), "-i");
        stringstream output_stream;
        python.in() <<
                    "if True:\n" << // Use this so that the rest is a single block
                    "    import sys\n" <<
                    "    sys.stderr = sys.stdout\n" <<
                    "    import ctml_writer\n" <<
                    "    ctml_writer.convert(r'" << file << "')\n" <<
                    "    sys.exit(0)\n\n"
                    "sys.exit(7)\n";
        python.close_in();
        std::string line;
        while (python.out().good()) {
            std::getline(python.out(), line);
            output_stream << line << std::endl;;
        }
        python.close();
        python_exit_code = python.exit_code();
        python_output = stripws(output_stream.str());
    } catch (std::exception& err) {
        // Report failure to execute Python
        stringstream message;
        message << "Error executing python while converting input file:\n";
        message << "Python command was: '" << pypath() << "'\n";
        message << err.what() << std::endl;
        throw CanteraError("ct2ctml", message.str());
    }

    if (python_exit_code != 0) {
        // Report a failure in the conversion process
        stringstream message;
        message << "Error converting input file \"" << file << "\" to CTML.\n";
        message << "Python command was: '" << pypath() << "'\n";
        message << "The exit code was: " << python_exit_code << "\n";
        if (python_output.size() > 0) {
            message << "-------------- start of converter log --------------\n";
            message << python_output << std::endl;
            message << "--------------- end of converter log ---------------";
        } else {
            message << "The command did not produce any output." << endl;
        }
        throw CanteraError("ct2ctml", message.str());
    }

    if (python_output.size() > 0) {
        // Warn if there was any output from the conversion process
        stringstream message;
        message << "Warning: Unexpected output from CTI converter\n";
        message << "-------------- start of converter log --------------\n";
        message << python_output << std::endl;
        message << "--------------- end of converter log ---------------\n";
        writelog(message.str());
    }
}

void ck2cti(const std::string& in_file, const std::string& thermo_file,
            const std::string& transport_file, const std::string& id_tag)
{
#ifdef HAS_NO_PYTHON
    /*
     *  Section to bomb out if python is not
     *  present in the computation environment.
     */
    string ppath = in_file;
    throw CanteraError("ct2ctml",
                       "python ck to cti conversion requested for file, " + ppath +
                       ", but not available in this computational environment");
#endif

    string python_output;
    int python_exit_code;
    try {
        exec_stream_t python;
        python.set_wait_timeout(exec_stream_t::s_all, 1800000); // 30 minutes
        python.start(pypath(), "-i");
        stringstream output_stream;

        ostream& pyin = python.in();
        pyin << "if True:\n"; // Use this so that the rest is a single block
        pyin << "    import sys\n";
        pyin << "    sys.stderr = sys.stdout\n";
        pyin << "    import ck2cti\n";
        pyin << "    ck2cti.convertMech(r'" << in_file << "',";
        if (thermo_file != "" && thermo_file != "-") {
            pyin << " thermoFile=r'" << thermo_file << "',";
        }
        if (transport_file != "" && transport_file != "-") {
            pyin << " transportFile=r'" << transport_file << "',";
        }
        pyin << " phaseName='" << id_tag << "',";
        pyin << " quiet=True)\n";
        pyin << "    sys.exit(0)\n\n";
        pyin << "sys.exit(7)\n";
        python.close_in();

        std::string line;
        while (python.out().good()) {
            std::getline(python.out(), line);
            output_stream << line << std::endl;;
        }
        python.close();
        python_exit_code = python.exit_code();
        python_output = stripws(output_stream.str());
    } catch (std::exception& err) {
        // Report failure to execute Python
        stringstream message;
        message << "Error executing python while converting input file:\n";
        message << "Python command was: '" << pypath() << "'\n";
        message << err.what() << std::endl;
        throw CanteraError("ct2ctml", message.str());
    }

    if (python_exit_code != 0) {
        // Report a failure in the conversion process
        stringstream message;
        message << "Error converting input file \"" << in_file << "\" to CTI.\n";
        message << "Python command was: '" << pypath() << "'\n";
        message << "The exit code was: " << python_exit_code << "\n";
        if (python_output.size() > 0) {
            message << "-------------- start of converter log --------------\n";
            message << python_output << std::endl;
            message << "--------------- end of converter log ---------------";
        } else {
            message << "The command did not produce any output." << endl;
        }
        throw CanteraError("ck2cti", message.str());
    }

    if (python_output.size() > 0) {
        // Warn if there was any output from the conversion process
        stringstream message;
        message << "Warning: Unexpected output from CTI converter\n";
        message << "-------------- start of converter log --------------\n";
        message << python_output << std::endl;
        message << "--------------- end of converter log ---------------\n";
        writelog(message.str());
    }
}

// Read an ctml file from a file and fill up an XML tree
/*
 *  This is the main routine that reads a ctml file and puts it into
 *  an XML_Node tree
 *
 *  @param node    Root of the tree
 *  @param file    Name of the file
 *  @param debug   Turn on debugging printing
 */
void get_CTML_Tree(Cantera::XML_Node* rootPtr, const std::string file, const int debug)
{
    std::string ff, ext = "";

    // find the input file on the Cantera search path
    std::string inname = findInputFile(file);
    if (debug > 0) {
        writelog("Found file: "+inname+"\n");
    }

    if (inname == "") {
        throw CanteraError("get_CTML_Tree", "file "+file+" not found");
    }

    /*
     * Check whether or not the file is XML. If not, it will be first
     * processed with the preprocessor.
     */
    std::string::size_type idot = inname.rfind('.');
    if (idot != string::npos) {
        ext = inname.substr(idot, inname.size());
    }
    if (ext != ".xml" && ext != ".ctml") {
        try {
            ctml::ct2ctml(inname.c_str(), debug);
        } catch (std::exception& err) {
            writelog("get_CTML_Tree: caught an exception:\n");
            writelog(err.what());
        }
        string ffull = inname.substr(0,idot) + ".xml";
        ff = "./" + getBaseName(ffull) + ".xml";
        if (debug > 0) {
            writelogf("ffull name = %s\n", ffull.c_str());
            writelogf("ff name = %s\n", ff.c_str());
        }
    } else {
        ff = inname;
    }
    if (debug > 0) {
        writelog("Attempting to parse xml file " + ff + "\n");
    }
    ifstream fin(ff.c_str());
    if (!fin) {
        throw
        CanteraError("get_CTML_Tree",
                     "XML file " + ff + " not found");
    }
    rootPtr->build(fin);
    fin.close();
}

Cantera::XML_Node getCtmlTree(const std::string file)
{
    Cantera::XML_Node root;
    get_CTML_Tree(&root, file);
    return root;
}

}
<|endoftext|>


<commit_before>/* * This file is part of qtcontacts-tracker
 * Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies). All rights reserved.
 * Contact: Aleksandar Stojiljkovic <aleksandar.stojiljkovic@nokia.com>
 * This software, including documentation, is protected by copyright controlled by
 * Nokia Corporation. All rights are reserved. Copying, including reproducing, storing,
 * adapting or translating, any or all of this material requires the prior written consent
 * of Nokia Corporation. This material also contains confidential information which may
 * not be disclosed to others without the prior written consent of Nokia.
 */

#include "tracker2qcontact.h"

#include <qcontact.h>
#include <qcontactdetails.h>

#include <QtTracker/ontologies/nco.h>

using namespace SopranoLive;

/**
   QContactPhoneNumber subtypes
 */
void setSubType(Live<nco::PhoneNumber> ncoPhone, QContactPhoneNumber& detail)
{
    //TODO pick one
    // AttributeSubTypeLandline;
    // AttributeSubTypeMobile;
    // AttributeSubTypeFacsimile;
    // AttributeSubTypePager;
    // AttributeSubTypeVoice;
    // AttributeSubTypeModem;
    // AttributeSubTypeVideo;
    // AttributeSubTypeCar;
    // AttributeSubTypeBulletinBoardSystem;
    // AttributeSubTypeMessagingCapable;

    // BUG: hasType is currently not working which means all numbers will be voice numbers.
    if( ncoPhone.hasType<nco::CellPhoneNumber>() ) {
        detail.setAttribute(QContactPhoneNumber::AttributeSubType, QContactPhoneNumber::AttributeSubTypeMobile);
    } else if ( not ncoPhone.hasType<nco::VoicePhoneNumber>() ) {
        // if it is not a voice number then no attributes are set
    } else {
        detail.setAttribute(QContactPhoneNumber::AttributeSubType, QContactPhoneNumber::AttributeSubTypeVoice);
    }
}

/**
   QContactAddress subtypes
 */
void setSubType(Live<nco::PostalAddress> ncoPostalAddress, QContactAddress& detail)
{
    //TODO pick one
    // AttributeSubTypeParcel;
    // AttributeSubTypePostal;
    // AttributeSubTypeDomestic;
    // AttributeSubTypeInternational;

    if( ncoPostalAddress.hasType<nco::PostalAddress>() ) {
        detail.setAttribute(QContactAddress::AttributeSubType, QContactAddress::AttributeSubTypePostal);
    } else {
        detail.setAttribute(QContactAddress::AttributeSubType, QContactAddress::AttributeSubTypeDomestic);
    }
}

/**
   QContactName subtypes
 */
void setSubType(Live<nco::PersonContact> ncoPersonContact, QContactName& detail)
{
    //TODO: No subtypes specified in qcontactname
    Q_UNUSED( ncoPersonContact );
    Q_UNUSED( detail );
}

/**
   QContactEmailAddress subtypes
*/
void setSubType(Live<nco::EmailAddress> ncoEmail, QContactEmailAddress& detail)
{
    //TODO pick one
    // AttributeSubTypeParcel;
    // AttributeSubTypePostal;
    // AttributeSubTypeDomestic;
    // AttributeSubTypeInternational;

    if( ncoEmail.hasType<nco::EmailAddress>() ) {
        detail.setAttribute(QContactEmailAddress::AttributeSubType, QContactEmailAddress::AttributeSubTypeInternet);
    }
}

void setSubType(Live<nfo::FileDataObject> fdo, QContactAvatar& detail)
{
    Q_UNUSED( fdo );
    detail.setAttribute(QContactAvatar::AttributeSubType, QContactAvatar::AttributeSubTypeImage);
}

/**
   Copy nco::PersonContact -> QContactName
*/
void copyDetailData(const Live<nco::PersonContact>& ncoContact, QContactName& name)
{
    name.setPrefix     ( ncoContact->getNameHonorificPrefix() );
    name.setFirst      ( ncoContact->getNameGiven() );
    name.setMiddle     ( ncoContact->getNameAdditional() );
    name.setLast       ( ncoContact->getNameFamily() );
    name.setSuffix     ( ncoContact->getNameHonorificSuffix() );
    setSubType( ncoContact, name );
}

/**
   Copy nco::PostalAddress -> QContactAddress
 */
void copyDetailData(const Live<nco::PostalAddress>& ncoPostalAddress, QContactAddress& address)
{
    //address.setDisplayLabel ("");
    address.setStreet       ( ncoPostalAddress->getStreetAddress() );
    address.setLocality     ( ncoPostalAddress->getLocality() );
    address.setRegion       ( ncoPostalAddress->getRegion() );
    address.setPostcode     ( ncoPostalAddress->getPostalcode() );
    address.setCountry      ( ncoPostalAddress->getCountry() );
    setSubType( ncoPostalAddress, address );
}

/**
   Copy nco::PhoneNumber -> QContactPhoneNumber
 */
void copyDetailData(const Live<nco::PhoneNumber>& ncoPhoneNumber, QContactPhoneNumber& detail)
{
    detail.setNumber (ncoPhoneNumber->getPhoneNumber());
    setSubType(ncoPhoneNumber, detail);
}

/**
   Copy nco::EmailAddress -> QContactEmailAddress
 */
void copyDetailData(const Live<nco::EmailAddress>& ncoEmail, QContactEmailAddress& detail)
{
    detail.setEmailAddress (ncoEmail->getEmailAddress());
    setSubType(ncoEmail, detail);
}

void copyDetailData(const Live<nfo::FileDataObject>& fdo, QContactAvatar& detail)
{
    if( fdo != 0 ) {
        QUrl url = fdo.toString();
        detail.setAvatar (url.toString());
        setSubType( fdo, detail );
    }
}

void copyDetailData(const Live< rdfs::Resource >& url, QContactUrl& detail)
{
    detail.setUrl(url.toString());
}

/*
void copyDetailData(const Live<nco::PersonContact>& ncoContact, QContactAnniversary& detail)
{
    Q_UNUSED(ncoContact);
    Q_UNUSED(detail);
    //detail.setDate (QDate());
}
*/

void copyDetailData(const Live<nco::PersonContact>& ncoContact, QContactGender& detail)
{
    Q_UNUSED(ncoContact);
    Q_UNUSED(detail);
    const Live< nfo::Gender > gender = ncoContact->getGender();
    detail.setGender(gender.toString());
}

/*
void copyDetailData(const Live<nco::PersonContact>& ncoContact, QContactBirthday& detail)
{
    detail.setDate (QDate());
}

void copyDetailData(const Live<nco::PersonContact>& ncoContact, QContactGuid& detail)
{
    detail.setGuid (QString());
}

void copyDetailData(const Live<nco::PersonContact>& ncoContact, QContactSyncTarget& detail)
{
    detail.setSyncTarget (QString());
}

void copyDetailData(const Live<nco::PersonContact>& ncoContact, QContactUrl& detail)
{
    detail.setUrl (QString());
}
*/

bool Tracker2QContact::copyContactData(const Live<nco::PersonContact>& ncoContact, QContact& qcontact )
{
    bool ok;
    QUniqueId id = QString(ncoContact->getContactUID()).toUInt(&ok);
    if( not ok ) {
        qWarning() << "Could not convert id to number";
        return false;
    }
    qcontact.setId(id);

    QContactName detail;
    copyDetailData(ncoContact, detail);
    qcontact.saveDetail(&detail);

    LiveNodes addresses = ncoContact->getHasPostalAddresss(); //Home addresses
    foreach( const Live<nco::PostalAddress>& address, addresses ) {
        QContactAddress detail;
        copyDetailData(address, detail);
        detail.setAttribute(QContactAddress::AttributeContext, QContactAddress::AttributeContextHome);
        qcontact.saveDetail(&detail);
    }

    LiveNodes phoneNumbers = ncoContact->getHasPhoneNumbers(); //Home phone numbers
    foreach( const Live<nco::PhoneNumber>& phoneNumber, phoneNumbers) {
        QContactPhoneNumber detail;
        copyDetailData(phoneNumber, detail);
        detail.setAttribute(QContactPhoneNumber::AttributeContext, QContactPhoneNumber::AttributeContextHome);
        qcontact.saveDetail(&detail);
    }

    LiveNodes emailAddresses = ncoContact->getHasEmailAddresss(); //Home email addresses
    foreach( const Live<nco::EmailAddress>& ncoEmail, emailAddresses) {
        QContactEmailAddress detail;
        copyDetailData(ncoEmail, detail);
        detail.setAttribute(QContactEmailAddress::AttributeContext, QContactEmailAddress::AttributeContextHome);
        detail.setAttribute(QContactEmailAddress::AttributeSubType, QContactEmailAddress::AttributeSubTypeInternet);
        qcontact.saveDetail(&detail);
    }

    foreach( Live<nfo::FileDataObject> fdo, ncoContact->getPhotos() ) { //Home avatars
        if( fdo != 0 ) {
            QContactAvatar detail;
            copyDetailData(fdo, detail);
            detail.setAttribute(QContactAvatar::AttributeContext, QContactAvatar::AttributeContextHome);
            qcontact.saveDetail(&detail);
        }
    }

    LiveNodes imAccounts = ncoContact->getHasIMAccounts();
    foreach (const Live<nco::IMAccount>& imAccount, imAccounts) {
        // TODo replace when QtMobility guys implement support for IMAccount
        QContactOnlineAccount account;;
        account.setValue("Account", imAccount->getImID());
        account.setValue("ServiceName", imAccount->getImAccountType());
        qcontact.saveDetail(&account);
        QContactPresence presence;
        presence.setValue(QContactPresence::FieldNickname, imAccount->getImNickname());
        presence.setValue(QContactPresence::FieldPresence, imAccount->getImStatus());
        presence.setValue(QContactPresence::FieldStatusMessage, imAccount->getImStatusMessage());
qDebug()<<Q_FUNC_INFO<<imAccount->getImStatusMessage();
        qcontact.saveDetail(&presence);

    }

    foreach( Live< rdfs::Resource > url, ncoContact->getUrls() ) { //Home homepage urls
        QContactUrl detail;
        copyDetailData(url, detail);
        detail.setAttribute(QContactUrl::AttributeContext, QContactUrl::AttributeContextHome);
        if( url.hasType<nco::websiteUrl>() ) {
            detail.setAttribute(QContactUrl::AttributeSubType, QContactUrl::AttributeSubTypeHomePage);
        } else { //TODO other subtypes when tracker supports them
        }
        qcontact.saveDetail(&detail);
    }

    // Work addresses+phonenumbers+emails+avatars

    LiveNodes affiliations = ncoContact->getHasAffiliations();
    foreach( const Live<nco::Affiliation>& affiliation, affiliations ) {
        Live<nco::OrganizationContact> org = affiliation->getOrg();
        LiveNodes addresses = org->getHasPostalAddresss();//Work addresses
        foreach( const Live<nco::PostalAddress>& address, addresses ) {
            QContactAddress detail;
            copyDetailData(address, detail);
            detail.setAttribute(QContactAddress::AttributeContext, QContactAddress::AttributeContextWork);
            qcontact.saveDetail(&detail);
        }
        LiveNodes phoneNumbers = org->getHasPhoneNumbers(); //Work phone
        foreach( const Live<nco::PhoneNumber>& phoneNumber, phoneNumbers) {
            QContactPhoneNumber detail;
            copyDetailData(phoneNumber, detail);
            detail.setAttribute(QContactPhoneNumber::AttributeContext, QContactPhoneNumber::AttributeContextWork);
            qcontact.saveDetail(&detail);
        }
        LiveNodes emailAddresses = org->getHasEmailAddresss(); //Work email addresses
        foreach( const Live<nco::EmailAddress>& ncoEmail, emailAddresses) {
            QContactEmailAddress detail;
            copyDetailData(ncoEmail, detail);
            detail.setAttribute(QContactEmailAddress::AttributeContext, QContactEmailAddress::AttributeContextWork);
            detail.setAttribute(QContactEmailAddress::AttributeSubType, QContactEmailAddress::AttributeSubTypeInternet);
            qcontact.saveDetail(&detail);
        }
        foreach( Live<nfo::FileDataObject> fdo, org->getPhotos() ) //Work avatars
        {
            if( fdo != 0 ) {
                QContactAvatar detail;
                copyDetailData(fdo, detail);
                detail.setAttribute(QContactAvatar::AttributeContext, QContactAvatar::AttributeContextWork);
                qcontact.saveDetail(&detail);
            }
        }
        foreach( Live< rdfs::Resource > url, org->getUrls() ) { //Work homepage urls
            QContactUrl detail;
            copyDetailData(url, detail);
            detail.setAttribute(QContactUrl::AttributeContext, QContactUrl::AttributeContextWork);
            if( url.hasType<nco::websiteUrl>() ) {
                detail.setAttribute(QContactUrl::AttributeSubType, QContactUrl::AttributeSubTypeHomePage);
            } else { //TODO other subtypes when tracker supports them
            }
            qcontact.saveDetail(&detail);
        }
    }

    //TODO
    /*LiveNodes genders = ncoContact->gethasGenders();
    foreach( Live< nco::Gender > ncoGender, genders->getGenders() )
        {
            QContactGender detail;
            copyDetailData(ncoGender, detail);

            qcontact.saveDetail(&detail);
        }
    {
        QContactAnniversary detail;
        copyDetailData(ncoContact, detail);
        qcontact.saveDetail(&detail);
    }{
        QContactBirthday detail;
        copyDetailData(ncoContact, detail);
        qcontact.saveDetail(&detail);
    }{
        QContactGuid detail;
        copyDetailData(ncoContact, detail);
        qcontact.saveDetail(&detail);
    }{
        QContactSyncTarget detail;
        copyDetailData(ncoContact, detail);
        qcontact.saveDetail(&detail);
    }
    */
    return true;
}

<commit_msg>removed wrong qDebug ,sorry<commit_after>/* * This file is part of qtcontacts-tracker
 * Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies). All rights reserved.
 * Contact: Aleksandar Stojiljkovic <aleksandar.stojiljkovic@nokia.com>
 * This software, including documentation, is protected by copyright controlled by
 * Nokia Corporation. All rights are reserved. Copying, including reproducing, storing,
 * adapting or translating, any or all of this material requires the prior written consent
 * of Nokia Corporation. This material also contains confidential information which may
 * not be disclosed to others without the prior written consent of Nokia.
 */

#include "tracker2qcontact.h"

#include <qcontact.h>
#include <qcontactdetails.h>

#include <QtTracker/ontologies/nco.h>

using namespace SopranoLive;

/**
   QContactPhoneNumber subtypes
 */
void setSubType(Live<nco::PhoneNumber> ncoPhone, QContactPhoneNumber& detail)
{
    //TODO pick one
    // AttributeSubTypeLandline;
    // AttributeSubTypeMobile;
    // AttributeSubTypeFacsimile;
    // AttributeSubTypePager;
    // AttributeSubTypeVoice;
    // AttributeSubTypeModem;
    // AttributeSubTypeVideo;
    // AttributeSubTypeCar;
    // AttributeSubTypeBulletinBoardSystem;
    // AttributeSubTypeMessagingCapable;

    // BUG: hasType is currently not working which means all numbers will be voice numbers.
    if( ncoPhone.hasType<nco::CellPhoneNumber>() ) {
        detail.setAttribute(QContactPhoneNumber::AttributeSubType, QContactPhoneNumber::AttributeSubTypeMobile);
    } else if ( not ncoPhone.hasType<nco::VoicePhoneNumber>() ) {
        // if it is not a voice number then no attributes are set
    } else {
        detail.setAttribute(QContactPhoneNumber::AttributeSubType, QContactPhoneNumber::AttributeSubTypeVoice);
    }
}

/**
   QContactAddress subtypes
 */
void setSubType(Live<nco::PostalAddress> ncoPostalAddress, QContactAddress& detail)
{
    //TODO pick one
    // AttributeSubTypeParcel;
    // AttributeSubTypePostal;
    // AttributeSubTypeDomestic;
    // AttributeSubTypeInternational;

    if( ncoPostalAddress.hasType<nco::PostalAddress>() ) {
        detail.setAttribute(QContactAddress::AttributeSubType, QContactAddress::AttributeSubTypePostal);
    } else {
        detail.setAttribute(QContactAddress::AttributeSubType, QContactAddress::AttributeSubTypeDomestic);
    }
}

/**
   QContactName subtypes
 */
void setSubType(Live<nco::PersonContact> ncoPersonContact, QContactName& detail)
{
    //TODO: No subtypes specified in qcontactname
    Q_UNUSED( ncoPersonContact );
    Q_UNUSED( detail );
}

/**
   QContactEmailAddress subtypes
*/
void setSubType(Live<nco::EmailAddress> ncoEmail, QContactEmailAddress& detail)
{
    //TODO pick one
    // AttributeSubTypeParcel;
    // AttributeSubTypePostal;
    // AttributeSubTypeDomestic;
    // AttributeSubTypeInternational;

    if( ncoEmail.hasType<nco::EmailAddress>() ) {
        detail.setAttribute(QContactEmailAddress::AttributeSubType, QContactEmailAddress::AttributeSubTypeInternet);
    }
}

void setSubType(Live<nfo::FileDataObject> fdo, QContactAvatar& detail)
{
    Q_UNUSED( fdo );
    detail.setAttribute(QContactAvatar::AttributeSubType, QContactAvatar::AttributeSubTypeImage);
}

/**
   Copy nco::PersonContact -> QContactName
*/
void copyDetailData(const Live<nco::PersonContact>& ncoContact, QContactName& name)
{
    name.setPrefix     ( ncoContact->getNameHonorificPrefix() );
    name.setFirst      ( ncoContact->getNameGiven() );
    name.setMiddle     ( ncoContact->getNameAdditional() );
    name.setLast       ( ncoContact->getNameFamily() );
    name.setSuffix     ( ncoContact->getNameHonorificSuffix() );
    setSubType( ncoContact, name );
}

/**
   Copy nco::PostalAddress -> QContactAddress
 */
void copyDetailData(const Live<nco::PostalAddress>& ncoPostalAddress, QContactAddress& address)
{
    //address.setDisplayLabel ("");
    address.setStreet       ( ncoPostalAddress->getStreetAddress() );
    address.setLocality     ( ncoPostalAddress->getLocality() );
    address.setRegion       ( ncoPostalAddress->getRegion() );
    address.setPostcode     ( ncoPostalAddress->getPostalcode() );
    address.setCountry      ( ncoPostalAddress->getCountry() );
    setSubType( ncoPostalAddress, address );
}

/**
   Copy nco::PhoneNumber -> QContactPhoneNumber
 */
void copyDetailData(const Live<nco::PhoneNumber>& ncoPhoneNumber, QContactPhoneNumber& detail)
{
    detail.setNumber (ncoPhoneNumber->getPhoneNumber());
    setSubType(ncoPhoneNumber, detail);
}

/**
   Copy nco::EmailAddress -> QContactEmailAddress
 */
void copyDetailData(const Live<nco::EmailAddress>& ncoEmail, QContactEmailAddress& detail)
{
    detail.setEmailAddress (ncoEmail->getEmailAddress());
    setSubType(ncoEmail, detail);
}

void copyDetailData(const Live<nfo::FileDataObject>& fdo, QContactAvatar& detail)
{
    if( fdo != 0 ) {
        QUrl url = fdo.toString();
        detail.setAvatar (url.toString());
        setSubType( fdo, detail );
    }
}

void copyDetailData(const Live< rdfs::Resource >& url, QContactUrl& detail)
{
    detail.setUrl(url.toString());
}

/*
void copyDetailData(const Live<nco::PersonContact>& ncoContact, QContactAnniversary& detail)
{
    Q_UNUSED(ncoContact);
    Q_UNUSED(detail);
    //detail.setDate (QDate());
}
*/

void copyDetailData(const Live<nco::PersonContact>& ncoContact, QContactGender& detail)
{
    Q_UNUSED(ncoContact);
    Q_UNUSED(detail);
    const Live< nfo::Gender > gender = ncoContact->getGender();
    detail.setGender(gender.toString());
}

/*
void copyDetailData(const Live<nco::PersonContact>& ncoContact, QContactBirthday& detail)
{
    detail.setDate (QDate());
}

void copyDetailData(const Live<nco::PersonContact>& ncoContact, QContactGuid& detail)
{
    detail.setGuid (QString());
}

void copyDetailData(const Live<nco::PersonContact>& ncoContact, QContactSyncTarget& detail)
{
    detail.setSyncTarget (QString());
}

void copyDetailData(const Live<nco::PersonContact>& ncoContact, QContactUrl& detail)
{
    detail.setUrl (QString());
}
*/

bool Tracker2QContact::copyContactData(const Live<nco::PersonContact>& ncoContact, QContact& qcontact )
{
    bool ok;
    QUniqueId id = QString(ncoContact->getContactUID()).toUInt(&ok);
    if( not ok ) {
        qWarning() << "Could not convert id to number";
        return false;
    }
    qcontact.setId(id);

    QContactName detail;
    copyDetailData(ncoContact, detail);
    qcontact.saveDetail(&detail);

    LiveNodes addresses = ncoContact->getHasPostalAddresss(); //Home addresses
    foreach( const Live<nco::PostalAddress>& address, addresses ) {
        QContactAddress detail;
        copyDetailData(address, detail);
        detail.setAttribute(QContactAddress::AttributeContext, QContactAddress::AttributeContextHome);
        qcontact.saveDetail(&detail);
    }

    LiveNodes phoneNumbers = ncoContact->getHasPhoneNumbers(); //Home phone numbers
    foreach( const Live<nco::PhoneNumber>& phoneNumber, phoneNumbers) {
        QContactPhoneNumber detail;
        copyDetailData(phoneNumber, detail);
        detail.setAttribute(QContactPhoneNumber::AttributeContext, QContactPhoneNumber::AttributeContextHome);
        qcontact.saveDetail(&detail);
    }

    LiveNodes emailAddresses = ncoContact->getHasEmailAddresss(); //Home email addresses
    foreach( const Live<nco::EmailAddress>& ncoEmail, emailAddresses) {
        QContactEmailAddress detail;
        copyDetailData(ncoEmail, detail);
        detail.setAttribute(QContactEmailAddress::AttributeContext, QContactEmailAddress::AttributeContextHome);
        detail.setAttribute(QContactEmailAddress::AttributeSubType, QContactEmailAddress::AttributeSubTypeInternet);
        qcontact.saveDetail(&detail);
    }

    foreach( Live<nfo::FileDataObject> fdo, ncoContact->getPhotos() ) { //Home avatars
        if( fdo != 0 ) {
            QContactAvatar detail;
            copyDetailData(fdo, detail);
            detail.setAttribute(QContactAvatar::AttributeContext, QContactAvatar::AttributeContextHome);
            qcontact.saveDetail(&detail);
        }
    }

    LiveNodes imAccounts = ncoContact->getHasIMAccounts();
    foreach (const Live<nco::IMAccount>& imAccount, imAccounts) {
        // TODo replace when QtMobility guys implement support for IMAccount
        QContactOnlineAccount account;;
        account.setValue("Account", imAccount->getImID());
        account.setValue("ServiceName", imAccount->getImAccountType());
        qcontact.saveDetail(&account);
        QContactPresence presence;
        presence.setValue(QContactPresence::FieldNickname, imAccount->getImNickname());
        presence.setValue(QContactPresence::FieldPresence, imAccount->getImStatus());
        presence.setValue(QContactPresence::FieldStatusMessage, imAccount->getImStatusMessage());
        qcontact.saveDetail(&presence);

    }

    foreach( Live< rdfs::Resource > url, ncoContact->getUrls() ) { //Home homepage urls
        QContactUrl detail;
        copyDetailData(url, detail);
        detail.setAttribute(QContactUrl::AttributeContext, QContactUrl::AttributeContextHome);
        if( url.hasType<nco::websiteUrl>() ) {
            detail.setAttribute(QContactUrl::AttributeSubType, QContactUrl::AttributeSubTypeHomePage);
        } else { //TODO other subtypes when tracker supports them
        }
        qcontact.saveDetail(&detail);
    }

    // Work addresses+phonenumbers+emails+avatars

    LiveNodes affiliations = ncoContact->getHasAffiliations();
    foreach( const Live<nco::Affiliation>& affiliation, affiliations ) {
        Live<nco::OrganizationContact> org = affiliation->getOrg();
        LiveNodes addresses = org->getHasPostalAddresss();//Work addresses
        foreach( const Live<nco::PostalAddress>& address, addresses ) {
            QContactAddress detail;
            copyDetailData(address, detail);
            detail.setAttribute(QContactAddress::AttributeContext, QContactAddress::AttributeContextWork);
            qcontact.saveDetail(&detail);
        }
        LiveNodes phoneNumbers = org->getHasPhoneNumbers(); //Work phone
        foreach( const Live<nco::PhoneNumber>& phoneNumber, phoneNumbers) {
            QContactPhoneNumber detail;
            copyDetailData(phoneNumber, detail);
            detail.setAttribute(QContactPhoneNumber::AttributeContext, QContactPhoneNumber::AttributeContextWork);
            qcontact.saveDetail(&detail);
        }
        LiveNodes emailAddresses = org->getHasEmailAddresss(); //Work email addresses
        foreach( const Live<nco::EmailAddress>& ncoEmail, emailAddresses) {
            QContactEmailAddress detail;
            copyDetailData(ncoEmail, detail);
            detail.setAttribute(QContactEmailAddress::AttributeContext, QContactEmailAddress::AttributeContextWork);
            detail.setAttribute(QContactEmailAddress::AttributeSubType, QContactEmailAddress::AttributeSubTypeInternet);
            qcontact.saveDetail(&detail);
        }
        foreach( Live<nfo::FileDataObject> fdo, org->getPhotos() ) //Work avatars
        {
            if( fdo != 0 ) {
                QContactAvatar detail;
                copyDetailData(fdo, detail);
                detail.setAttribute(QContactAvatar::AttributeContext, QContactAvatar::AttributeContextWork);
                qcontact.saveDetail(&detail);
            }
        }
        foreach( Live< rdfs::Resource > url, org->getUrls() ) { //Work homepage urls
            QContactUrl detail;
            copyDetailData(url, detail);
            detail.setAttribute(QContactUrl::AttributeContext, QContactUrl::AttributeContextWork);
            if( url.hasType<nco::websiteUrl>() ) {
                detail.setAttribute(QContactUrl::AttributeSubType, QContactUrl::AttributeSubTypeHomePage);
            } else { //TODO other subtypes when tracker supports them
            }
            qcontact.saveDetail(&detail);
        }
    }

    //TODO
    /*LiveNodes genders = ncoContact->gethasGenders();
    foreach( Live< nco::Gender > ncoGender, genders->getGenders() )
        {
            QContactGender detail;
            copyDetailData(ncoGender, detail);

            qcontact.saveDetail(&detail);
        }
    {
        QContactAnniversary detail;
        copyDetailData(ncoContact, detail);
        qcontact.saveDetail(&detail);
    }{
        QContactBirthday detail;
        copyDetailData(ncoContact, detail);
        qcontact.saveDetail(&detail);
    }{
        QContactGuid detail;
        copyDetailData(ncoContact, detail);
        qcontact.saveDetail(&detail);
    }{
        QContactSyncTarget detail;
        copyDetailData(ncoContact, detail);
        qcontact.saveDetail(&detail);
    }
    */
    return true;
}

<|endoftext|>


<commit_before>/*************************************************************************/
/*  editor_fonts.cpp                                                     */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "editor_fonts.h"

#include "builtin_fonts.gen.h"
#include "core/os/dir_access.h"
#include "editor_scale.h"
#include "editor_settings.h"
#include "scene/resources/default_theme/default_theme.h"
#include "scene/resources/dynamic_font.h"

#define MAKE_FALLBACKS(m_name)          \
	m_name->add_fallback(FontArabic);   \
	m_name->add_fallback(FontHebrew);   \
	m_name->add_fallback(FontThai);     \
	m_name->add_fallback(FontHindi);    \
	m_name->add_fallback(FontJapanese); \
	m_name->add_fallback(FontFallback);

// the custom spacings might only work with Noto Sans
#define MAKE_DEFAULT_FONT(m_name, m_size)                       \
	Ref<DynamicFont> m_name;                                    \
	m_name.instance();                                          \
	m_name->set_size(m_size);                                   \
	if (CustomFont.is_valid()) {                                \
		m_name->set_font_data(CustomFont);                      \
		m_name->add_fallback(DefaultFont);                      \
	} else {                                                    \
		m_name->set_font_data(DefaultFont);                     \
	}                                                           \
	m_name->set_spacing(DynamicFont::SPACING_TOP, -EDSCALE);    \
	m_name->set_spacing(DynamicFont::SPACING_BOTTOM, -EDSCALE); \
	MAKE_FALLBACKS(m_name);

#define MAKE_BOLD_FONT(m_name, m_size)                          \
	Ref<DynamicFont> m_name;                                    \
	m_name.instance();                                          \
	m_name->set_size(m_size);                                   \
	if (CustomFont.is_valid()) {                                \
		m_name->set_font_data(CustomFontBold);                  \
		m_name->add_fallback(DefaultFontBold);                  \
	} else {                                                    \
		m_name->set_font_data(DefaultFontBold);                 \
	}                                                           \
	m_name->set_spacing(DynamicFont::SPACING_TOP, -EDSCALE);    \
	m_name->set_spacing(DynamicFont::SPACING_BOTTOM, -EDSCALE); \
	MAKE_FALLBACKS(m_name);

#define MAKE_SOURCE_FONT(m_name, m_size)                        \
	Ref<DynamicFont> m_name;                                    \
	m_name.instance();                                          \
	m_name->set_size(m_size);                                   \
	if (CustomFontSource.is_valid()) {                          \
		m_name->set_font_data(CustomFontSource);                \
		m_name->add_fallback(dfmono);                           \
	} else {                                                    \
		m_name->set_font_data(dfmono);                          \
	}                                                           \
	m_name->set_spacing(DynamicFont::SPACING_TOP, -EDSCALE);    \
	m_name->set_spacing(DynamicFont::SPACING_BOTTOM, -EDSCALE); \
	MAKE_FALLBACKS(m_name);

void editor_register_fonts(Ref<Theme> p_theme) {
	DirAccess *dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);

	/* Custom font */

	bool font_antialiased = (bool)EditorSettings::get_singleton()->get("interface/editor/main_font_antialiased");
	DynamicFontData::Hinting font_hinting = (DynamicFontData::Hinting)(int)EditorSettings::get_singleton()->get("interface/editor/main_font_hinting");

	String custom_font_path = EditorSettings::get_singleton()->get("interface/editor/main_font");
	Ref<DynamicFontData> CustomFont;
	if (custom_font_path.length() > 0 && dir->file_exists(custom_font_path)) {
		CustomFont.instance();
		CustomFont->set_antialiased(font_antialiased);
		CustomFont->set_hinting(font_hinting);
		CustomFont->set_font_path(custom_font_path);
		CustomFont->set_force_autohinter(true); //just looks better..i think?
	} else {
		EditorSettings::get_singleton()->set_manually("interface/editor/main_font", "");
	}

	/* Custom Bold font */

	String custom_font_path_bold = EditorSettings::get_singleton()->get("interface/editor/main_font_bold");
	Ref<DynamicFontData> CustomFontBold;
	if (custom_font_path_bold.length() > 0 && dir->file_exists(custom_font_path_bold)) {
		CustomFontBold.instance();
		CustomFontBold->set_antialiased(font_antialiased);
		CustomFontBold->set_hinting(font_hinting);
		CustomFontBold->set_font_path(custom_font_path_bold);
		CustomFontBold->set_force_autohinter(true); //just looks better..i think?
	} else {
		EditorSettings::get_singleton()->set_manually("interface/editor/main_font_bold", "");
	}

	/* Custom source code font */

	String custom_font_path_source = EditorSettings::get_singleton()->get("interface/editor/code_font");
	bool font_source_antialiased = (bool)EditorSettings::get_singleton()->get("interface/editor/code_font_antialiased");
	DynamicFontData::Hinting font_source_hinting = (DynamicFontData::Hinting)(int)EditorSettings::get_singleton()->get("interface/editor/code_font_hinting");
	Ref<DynamicFontData> CustomFontSource;
	if (custom_font_path_source.length() > 0 && dir->file_exists(custom_font_path_source)) {
		CustomFontSource.instance();
		CustomFontSource->set_antialiased(font_source_antialiased);
		CustomFontSource->set_hinting(font_source_hinting);
		CustomFontSource->set_font_path(custom_font_path_source);
	} else {
		EditorSettings::get_singleton()->set_manually("interface/editor/code_font", "");
	}

	memdelete(dir);

	/* Droid Sans */

	Ref<DynamicFontData> DefaultFont;
	DefaultFont.instance();
	DefaultFont->set_antialiased(font_antialiased);
	DefaultFont->set_hinting(font_hinting);
	DefaultFont->set_font_ptr(_font_NotoSansUI_Regular, _font_NotoSansUI_Regular_size);
	DefaultFont->set_force_autohinter(true); //just looks better..i think?

	Ref<DynamicFontData> DefaultFontBold;
	DefaultFontBold.instance();
	DefaultFontBold->set_antialiased(font_antialiased);
	DefaultFontBold->set_hinting(font_hinting);
	DefaultFontBold->set_font_ptr(_font_NotoSansUI_Bold, _font_NotoSansUI_Bold_size);
	DefaultFontBold->set_force_autohinter(true); // just looks better..i think?

	Ref<DynamicFontData> FontFallback;
	FontFallback.instance();
	FontFallback->set_antialiased(font_antialiased);
	FontFallback->set_hinting(font_hinting);
	FontFallback->set_font_ptr(_font_DroidSansFallback, _font_DroidSansFallback_size);
	FontFallback->set_force_autohinter(true); //just looks better..i think?

	Ref<DynamicFontData> FontJapanese;
	FontJapanese.instance();
	FontJapanese->set_antialiased(font_antialiased);
	FontJapanese->set_hinting(font_hinting);
	FontJapanese->set_font_ptr(_font_DroidSansJapanese, _font_DroidSansJapanese_size);
	FontJapanese->set_force_autohinter(true); //just looks better..i think?

	Ref<DynamicFontData> FontArabic;
	FontArabic.instance();
	FontArabic->set_antialiased(font_antialiased);
	FontArabic->set_hinting(font_hinting);
	FontArabic->set_font_ptr(_font_NotoNaskhArabicUI_Regular, _font_NotoNaskhArabicUI_Regular_size);
	FontArabic->set_force_autohinter(true); //just looks better..i think?

	Ref<DynamicFontData> FontHebrew;
	FontHebrew.instance();
	FontHebrew->set_antialiased(font_antialiased);
	FontHebrew->set_hinting(font_hinting);
	FontHebrew->set_font_ptr(_font_NotoSansHebrew_Regular, _font_NotoSansHebrew_Regular_size);
	FontHebrew->set_force_autohinter(true); //just looks better..i think?

	Ref<DynamicFontData> FontThai;
	FontThai.instance();
	FontThai->set_antialiased(font_antialiased);
	FontThai->set_hinting(font_hinting);
	FontThai->set_font_ptr(_font_NotoSansThaiUI_Regular, _font_NotoSansThaiUI_Regular_size);
	FontThai->set_force_autohinter(true); //just looks better..i think?

	Ref<DynamicFontData> FontHindi;
	FontHindi.instance();
	FontHindi->set_antialiased(font_antialiased);
	FontHindi->set_hinting(font_hinting);
	FontHindi->set_font_ptr(_font_NotoSansDevanagariUI_Regular, _font_NotoSansDevanagariUI_Regular_size);
	FontHindi->set_force_autohinter(true); //just looks better..i think?

	/* Hack */

	Ref<DynamicFontData> dfmono;
	dfmono.instance();
	dfmono->set_antialiased(font_source_antialiased);
	dfmono->set_hinting(font_source_hinting);
	dfmono->set_font_ptr(_font_Hack_Regular, _font_Hack_Regular_size);
	//dfd->set_force_autohinter(true); //just looks better..i think?

	int default_font_size = int(EditorSettings::get_singleton()->get("interface/editor/main_font_size")) * EDSCALE;

	// Default font
	MAKE_DEFAULT_FONT(df, default_font_size);
	p_theme->set_default_theme_font(df);

	// Bold font
	MAKE_BOLD_FONT(df_bold, default_font_size);
	p_theme->set_font("bold", "EditorFonts", df_bold);

	// Title font
	MAKE_BOLD_FONT(df_title, default_font_size + 2 * EDSCALE);
	p_theme->set_font("title", "EditorFonts", df_title);

	// Doc font
	MAKE_BOLD_FONT(df_doc_title, int(EDITOR_DEF("text_editor/help/help_title_font_size", 23)) * EDSCALE);

	MAKE_DEFAULT_FONT(df_doc, int(EDITOR_DEF("text_editor/help/help_font_size", 15)) * EDSCALE);

	p_theme->set_font("doc", "EditorFonts", df_doc);
	p_theme->set_font("doc_title", "EditorFonts", df_doc_title);

	MAKE_SOURCE_FONT(df_doc_code, int(EDITOR_DEF("text_editor/help/help_source_font_size", 14)) * EDSCALE);
	p_theme->set_font("doc_source", "EditorFonts", df_doc_code);

	// Ruler font
	MAKE_DEFAULT_FONT(df_rulers, 8 * EDSCALE);
	p_theme->set_font("rulers", "EditorFonts", df_rulers);

	// Code font
	MAKE_SOURCE_FONT(df_code, int(EditorSettings::get_singleton()->get("interface/editor/code_font_size")) * EDSCALE);
	p_theme->set_font("source", "EditorFonts", df_code);

	MAKE_SOURCE_FONT(df_output_code, int(EDITOR_DEF("run/output/font_size", 13)) * EDSCALE);
	p_theme->set_font("output_source", "EditorFonts", df_output_code);

	MAKE_SOURCE_FONT(df_text_editor_status_code, 14 * EDSCALE);
	p_theme->set_font("status_source", "EditorFonts", df_text_editor_status_code);
}
<commit_msg>Editor source status font size, fixes #25039<commit_after>/*************************************************************************/
/*  editor_fonts.cpp                                                     */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "editor_fonts.h"

#include "builtin_fonts.gen.h"
#include "core/os/dir_access.h"
#include "editor_scale.h"
#include "editor_settings.h"
#include "scene/resources/default_theme/default_theme.h"
#include "scene/resources/dynamic_font.h"

#define MAKE_FALLBACKS(m_name)          \
	m_name->add_fallback(FontArabic);   \
	m_name->add_fallback(FontHebrew);   \
	m_name->add_fallback(FontThai);     \
	m_name->add_fallback(FontHindi);    \
	m_name->add_fallback(FontJapanese); \
	m_name->add_fallback(FontFallback);

// the custom spacings might only work with Noto Sans
#define MAKE_DEFAULT_FONT(m_name, m_size)                       \
	Ref<DynamicFont> m_name;                                    \
	m_name.instance();                                          \
	m_name->set_size(m_size);                                   \
	if (CustomFont.is_valid()) {                                \
		m_name->set_font_data(CustomFont);                      \
		m_name->add_fallback(DefaultFont);                      \
	} else {                                                    \
		m_name->set_font_data(DefaultFont);                     \
	}                                                           \
	m_name->set_spacing(DynamicFont::SPACING_TOP, -EDSCALE);    \
	m_name->set_spacing(DynamicFont::SPACING_BOTTOM, -EDSCALE); \
	MAKE_FALLBACKS(m_name);

#define MAKE_BOLD_FONT(m_name, m_size)                          \
	Ref<DynamicFont> m_name;                                    \
	m_name.instance();                                          \
	m_name->set_size(m_size);                                   \
	if (CustomFont.is_valid()) {                                \
		m_name->set_font_data(CustomFontBold);                  \
		m_name->add_fallback(DefaultFontBold);                  \
	} else {                                                    \
		m_name->set_font_data(DefaultFontBold);                 \
	}                                                           \
	m_name->set_spacing(DynamicFont::SPACING_TOP, -EDSCALE);    \
	m_name->set_spacing(DynamicFont::SPACING_BOTTOM, -EDSCALE); \
	MAKE_FALLBACKS(m_name);

#define MAKE_SOURCE_FONT(m_name, m_size)                        \
	Ref<DynamicFont> m_name;                                    \
	m_name.instance();                                          \
	m_name->set_size(m_size);                                   \
	if (CustomFontSource.is_valid()) {                          \
		m_name->set_font_data(CustomFontSource);                \
		m_name->add_fallback(dfmono);                           \
	} else {                                                    \
		m_name->set_font_data(dfmono);                          \
	}                                                           \
	m_name->set_spacing(DynamicFont::SPACING_TOP, -EDSCALE);    \
	m_name->set_spacing(DynamicFont::SPACING_BOTTOM, -EDSCALE); \
	MAKE_FALLBACKS(m_name);

void editor_register_fonts(Ref<Theme> p_theme) {
	DirAccess *dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);

	/* Custom font */

	bool font_antialiased = (bool)EditorSettings::get_singleton()->get("interface/editor/main_font_antialiased");
	DynamicFontData::Hinting font_hinting = (DynamicFontData::Hinting)(int)EditorSettings::get_singleton()->get("interface/editor/main_font_hinting");

	String custom_font_path = EditorSettings::get_singleton()->get("interface/editor/main_font");
	Ref<DynamicFontData> CustomFont;
	if (custom_font_path.length() > 0 && dir->file_exists(custom_font_path)) {
		CustomFont.instance();
		CustomFont->set_antialiased(font_antialiased);
		CustomFont->set_hinting(font_hinting);
		CustomFont->set_font_path(custom_font_path);
		CustomFont->set_force_autohinter(true); //just looks better..i think?
	} else {
		EditorSettings::get_singleton()->set_manually("interface/editor/main_font", "");
	}

	/* Custom Bold font */

	String custom_font_path_bold = EditorSettings::get_singleton()->get("interface/editor/main_font_bold");
	Ref<DynamicFontData> CustomFontBold;
	if (custom_font_path_bold.length() > 0 && dir->file_exists(custom_font_path_bold)) {
		CustomFontBold.instance();
		CustomFontBold->set_antialiased(font_antialiased);
		CustomFontBold->set_hinting(font_hinting);
		CustomFontBold->set_font_path(custom_font_path_bold);
		CustomFontBold->set_force_autohinter(true); //just looks better..i think?
	} else {
		EditorSettings::get_singleton()->set_manually("interface/editor/main_font_bold", "");
	}

	/* Custom source code font */

	String custom_font_path_source = EditorSettings::get_singleton()->get("interface/editor/code_font");
	bool font_source_antialiased = (bool)EditorSettings::get_singleton()->get("interface/editor/code_font_antialiased");
	DynamicFontData::Hinting font_source_hinting = (DynamicFontData::Hinting)(int)EditorSettings::get_singleton()->get("interface/editor/code_font_hinting");
	Ref<DynamicFontData> CustomFontSource;
	if (custom_font_path_source.length() > 0 && dir->file_exists(custom_font_path_source)) {
		CustomFontSource.instance();
		CustomFontSource->set_antialiased(font_source_antialiased);
		CustomFontSource->set_hinting(font_source_hinting);
		CustomFontSource->set_font_path(custom_font_path_source);
	} else {
		EditorSettings::get_singleton()->set_manually("interface/editor/code_font", "");
	}

	memdelete(dir);

	/* Droid Sans */

	Ref<DynamicFontData> DefaultFont;
	DefaultFont.instance();
	DefaultFont->set_antialiased(font_antialiased);
	DefaultFont->set_hinting(font_hinting);
	DefaultFont->set_font_ptr(_font_NotoSansUI_Regular, _font_NotoSansUI_Regular_size);
	DefaultFont->set_force_autohinter(true); //just looks better..i think?

	Ref<DynamicFontData> DefaultFontBold;
	DefaultFontBold.instance();
	DefaultFontBold->set_antialiased(font_antialiased);
	DefaultFontBold->set_hinting(font_hinting);
	DefaultFontBold->set_font_ptr(_font_NotoSansUI_Bold, _font_NotoSansUI_Bold_size);
	DefaultFontBold->set_force_autohinter(true); // just looks better..i think?

	Ref<DynamicFontData> FontFallback;
	FontFallback.instance();
	FontFallback->set_antialiased(font_antialiased);
	FontFallback->set_hinting(font_hinting);
	FontFallback->set_font_ptr(_font_DroidSansFallback, _font_DroidSansFallback_size);
	FontFallback->set_force_autohinter(true); //just looks better..i think?

	Ref<DynamicFontData> FontJapanese;
	FontJapanese.instance();
	FontJapanese->set_antialiased(font_antialiased);
	FontJapanese->set_hinting(font_hinting);
	FontJapanese->set_font_ptr(_font_DroidSansJapanese, _font_DroidSansJapanese_size);
	FontJapanese->set_force_autohinter(true); //just looks better..i think?

	Ref<DynamicFontData> FontArabic;
	FontArabic.instance();
	FontArabic->set_antialiased(font_antialiased);
	FontArabic->set_hinting(font_hinting);
	FontArabic->set_font_ptr(_font_NotoNaskhArabicUI_Regular, _font_NotoNaskhArabicUI_Regular_size);
	FontArabic->set_force_autohinter(true); //just looks better..i think?

	Ref<DynamicFontData> FontHebrew;
	FontHebrew.instance();
	FontHebrew->set_antialiased(font_antialiased);
	FontHebrew->set_hinting(font_hinting);
	FontHebrew->set_font_ptr(_font_NotoSansHebrew_Regular, _font_NotoSansHebrew_Regular_size);
	FontHebrew->set_force_autohinter(true); //just looks better..i think?

	Ref<DynamicFontData> FontThai;
	FontThai.instance();
	FontThai->set_antialiased(font_antialiased);
	FontThai->set_hinting(font_hinting);
	FontThai->set_font_ptr(_font_NotoSansThaiUI_Regular, _font_NotoSansThaiUI_Regular_size);
	FontThai->set_force_autohinter(true); //just looks better..i think?

	Ref<DynamicFontData> FontHindi;
	FontHindi.instance();
	FontHindi->set_antialiased(font_antialiased);
	FontHindi->set_hinting(font_hinting);
	FontHindi->set_font_ptr(_font_NotoSansDevanagariUI_Regular, _font_NotoSansDevanagariUI_Regular_size);
	FontHindi->set_force_autohinter(true); //just looks better..i think?

	/* Hack */

	Ref<DynamicFontData> dfmono;
	dfmono.instance();
	dfmono->set_antialiased(font_source_antialiased);
	dfmono->set_hinting(font_source_hinting);
	dfmono->set_font_ptr(_font_Hack_Regular, _font_Hack_Regular_size);
	//dfd->set_force_autohinter(true); //just looks better..i think?

	int default_font_size = int(EditorSettings::get_singleton()->get("interface/editor/main_font_size")) * EDSCALE;

	// Default font
	MAKE_DEFAULT_FONT(df, default_font_size);
	p_theme->set_default_theme_font(df);

	// Bold font
	MAKE_BOLD_FONT(df_bold, default_font_size);
	p_theme->set_font("bold", "EditorFonts", df_bold);

	// Title font
	MAKE_BOLD_FONT(df_title, default_font_size + 2 * EDSCALE);
	p_theme->set_font("title", "EditorFonts", df_title);

	// Doc font
	MAKE_BOLD_FONT(df_doc_title, int(EDITOR_DEF("text_editor/help/help_title_font_size", 23)) * EDSCALE);

	MAKE_DEFAULT_FONT(df_doc, int(EDITOR_DEF("text_editor/help/help_font_size", 15)) * EDSCALE);

	p_theme->set_font("doc", "EditorFonts", df_doc);
	p_theme->set_font("doc_title", "EditorFonts", df_doc_title);

	MAKE_SOURCE_FONT(df_doc_code, int(EDITOR_DEF("text_editor/help/help_source_font_size", 14)) * EDSCALE);
	p_theme->set_font("doc_source", "EditorFonts", df_doc_code);

	// Ruler font
	MAKE_DEFAULT_FONT(df_rulers, 8 * EDSCALE);
	p_theme->set_font("rulers", "EditorFonts", df_rulers);

	// Code font
	MAKE_SOURCE_FONT(df_code, int(EditorSettings::get_singleton()->get("interface/editor/code_font_size")) * EDSCALE);
	p_theme->set_font("source", "EditorFonts", df_code);

	MAKE_SOURCE_FONT(df_output_code, int(EDITOR_DEF("run/output/font_size", 13)) * EDSCALE);
	p_theme->set_font("output_source", "EditorFonts", df_output_code);

	MAKE_SOURCE_FONT(df_text_editor_status_code, default_font_size);
	p_theme->set_font("status_source", "EditorFonts", df_text_editor_status_code);
}
<|endoftext|>


<commit_before>// Copyright 2017 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef RCLCPP__NODE_INTERFACES__NODE_CLOCK_HPP_
#define RCLCPP__NODE_INTERFACES__NODE_CLOCK_HPP_

#include "rclcpp/clock.hpp"
#include "rclcpp/macros.hpp"
#include "rclcpp/node_interfaces/node_base_interface.hpp"
#include "rclcpp/node_interfaces/node_clock_interface.hpp"
#include "rclcpp/node_interfaces/node_graph_interface.hpp"
#include "rclcpp/node_interfaces/node_logging_interface.hpp"
#include "rclcpp/node_interfaces/node_services_interface.hpp"
#include "rclcpp/node_interfaces/node_topics_interface.hpp"
#include "rclcpp/visibility_control.hpp"

namespace rclcpp
{
namespace node_interfaces
{

/// Implementation of the NodeClock part of the Node API.
class NodeClock : public NodeClockInterface
{
public:
  RCLCPP_SMART_PTR_ALIASES_ONLY(NodeClock)

  RCLCPP_PUBLIC
  explicit NodeClock(
    rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_base,
    rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr node_topics,
    rclcpp::node_interfaces::NodeGraphInterface::SharedPtr node_graph,
    rclcpp::node_interfaces::NodeServicesInterface::SharedPtr node_services,
    rclcpp::node_interfaces::NodeLoggingInterface::SharedPtr node_logging);

  RCLCPP_PUBLIC
  virtual
  ~NodeClock();

  /// Get a clock which will be kept up to date by the node.
  RCLCPP_PUBLIC

  rclcpp::Clock::SharedPtr
  get_clock() override;

  /// Get a clock which will be kept up to date by the node.
  RCLCPP_PUBLIC
  rclcpp::Clock::ConstSharedPtr
  get_clock() const override;

private:
  RCLCPP_DISABLE_COPY(NodeClock)

  rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_base_;
  rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr node_topics_;
  rclcpp::node_interfaces::NodeGraphInterface::SharedPtr node_graph_;
  rclcpp::node_interfaces::NodeServicesInterface::SharedPtr node_services_;
  rclcpp::node_interfaces::NodeLoggingInterface::SharedPtr node_logging_;

  rclcpp::Clock::SharedPtr ros_clock_;
};

}  // namespace node_interfaces
}  // namespace rclcpp

#endif  // RCLCPP__NODE_INTERFACES__NODE_CLOCK_HPP_
<commit_msg>Remove extra vertical whitespace (#1030)<commit_after>// Copyright 2017 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef RCLCPP__NODE_INTERFACES__NODE_CLOCK_HPP_
#define RCLCPP__NODE_INTERFACES__NODE_CLOCK_HPP_

#include "rclcpp/clock.hpp"
#include "rclcpp/macros.hpp"
#include "rclcpp/node_interfaces/node_base_interface.hpp"
#include "rclcpp/node_interfaces/node_clock_interface.hpp"
#include "rclcpp/node_interfaces/node_graph_interface.hpp"
#include "rclcpp/node_interfaces/node_logging_interface.hpp"
#include "rclcpp/node_interfaces/node_services_interface.hpp"
#include "rclcpp/node_interfaces/node_topics_interface.hpp"
#include "rclcpp/visibility_control.hpp"

namespace rclcpp
{
namespace node_interfaces
{

/// Implementation of the NodeClock part of the Node API.
class NodeClock : public NodeClockInterface
{
public:
  RCLCPP_SMART_PTR_ALIASES_ONLY(NodeClock)

  RCLCPP_PUBLIC
  explicit NodeClock(
    rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_base,
    rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr node_topics,
    rclcpp::node_interfaces::NodeGraphInterface::SharedPtr node_graph,
    rclcpp::node_interfaces::NodeServicesInterface::SharedPtr node_services,
    rclcpp::node_interfaces::NodeLoggingInterface::SharedPtr node_logging);

  RCLCPP_PUBLIC
  virtual
  ~NodeClock();

  /// Get a clock which will be kept up to date by the node.
  RCLCPP_PUBLIC
  rclcpp::Clock::SharedPtr
  get_clock() override;

  /// Get a clock which will be kept up to date by the node.
  RCLCPP_PUBLIC
  rclcpp::Clock::ConstSharedPtr
  get_clock() const override;

private:
  RCLCPP_DISABLE_COPY(NodeClock)

  rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_base_;
  rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr node_topics_;
  rclcpp::node_interfaces::NodeGraphInterface::SharedPtr node_graph_;
  rclcpp::node_interfaces::NodeServicesInterface::SharedPtr node_services_;
  rclcpp::node_interfaces::NodeLoggingInterface::SharedPtr node_logging_;

  rclcpp::Clock::SharedPtr ros_clock_;
};

}  // namespace node_interfaces
}  // namespace rclcpp

#endif  // RCLCPP__NODE_INTERFACES__NODE_CLOCK_HPP_
<|endoftext|>