<commit_before>// This file provides a fast implementation of common vector operations, using
// a templated and very lightweight vec class. The memory structure of a vec
// instance is just a sequence of its components.
// It also provides a vec_array class, whose memory structure is just the same
// as a sequence of N*dimensions scalars. The [] operator is overloaded
// to return vec instances.
// The goal of these classes is to achieve similar performance as a primitive
// array for the 1d case, while being able to write more general programs.

// include guard
#ifndef VEC_HPP
#define VEC_HPP

// need complex type for optimized template
#include <complex>

/* -- vec class -- */
template <int dim, typename Type>
class vec { public:
  Type x[dim];

  inline vec() {};

  // copy constructor
  template <typename otherType>
  inline vec(const vec<dim,otherType> &other_vec) {

    for (int i=0; i<dim; i++) {
      x[i] = Type(other_vec.x[i]);
    }
  };

  // intitialize with constant value
  template <typename otherType>
  inline vec(otherType val) {
    for (int i=0; i<dim; i++) {
      x[i] = Type(val);
    }
  };

  // in-place summation
  template <typename otherType>
  inline vec<dim,Type> &operator+=(const vec<dim,otherType> &v) {
    for (int i=0; i<dim; i++) {
      x[i] += Type(v.x[i]);
    }

    return *this;
  };

  // in-place subtraction
  template <typename otherType>
  inline vec<dim,Type> &operator-=(const vec<dim,otherType> &v) {
    for (int i=0; i<dim; i++) {
      x[i] -= Type(v.x[i]);
    }

    return *this;
  };

  // in-place multiplication with scalar
  template <typename otherType>
  inline vec<dim,Type> &operator*=(const otherType &v) {
    for (int i=0; i<dim; i++) {
      x[i] *= Type(v);
    }

    return *this;
  };

  // in-place division by scalar
  template <typename otherType>
  inline vec<dim,Type> &operator/=(const otherType &v) {
    for (int i=0; i<dim; i++) {
      x[i] /= Type(v);
    }

    return *this;
  };

  // element-wise application of a function
  template <typename otherType>
  inline vec<dim,otherType> element_wise(otherType& (*func)(Type&)) {
    vec<dim,otherType> r;
    for (int i=0; i<dim; i++) {
      r.x[i] = (*func)(x[i]);
    }
    return r;
  };
};

/* -- common operations on vec -- */

// sum of vec instances
template <int dim, typename Type>
inline vec<dim,Type> operator+(const vec<dim,Type> &v, const vec<dim,Type> &w) {
  vec<dim,Type> r;

  for (int i=0; i<dim; i++) {
    r.x[i] = v.x[i] + w.x[i];
  }

  return r;
};

// difference of vec instances
template <int dim, typename Type>
inline vec<dim,Type> operator-(const vec<dim,Type> &v, const vec<dim,Type> &w) {
  vec<dim,Type> r;

  for (int i=0; i<dim; i++) {
    r.x[i] = v.x[i] - w.x[i];
  }

  return r;
};

// vec times scalar
template <int dim, typename Type>
inline vec<dim,Type> operator*(const vec<dim,Type> &v, const Type &w) {
  vec<dim,Type> r;

  for (int i=0; i<dim; i++) {
    r.x[i] = v.x[i] * w;
  }

  return r;
};

// scalar times vec
template <int dim, typename Type>
inline vec<dim,Type> operator*(const Type &w, const vec<dim,Type> &v) {
  return v*w;
};

// division of vec by scalar
template <int dim, typename Type>
inline vec<dim,Type> operator/(const vec<dim,Type> &v, const Type &w) {
  vec<dim,Type> r;

  for (int i=0; i<dim; i++) {
    r.x[i] = v.x[i] / w;
  }

  return r;
};

// scalar product of vec instances
template <int dim, typename Type>
inline Type operator*(const vec<dim,Type> &v, const vec<dim,Type> &w) {
  Type r(0);

  for (int i=0; i<dim; i++) {
    r += v.x[i] * w.x[i];
  }

  return r;
};

// these more specialized templates gain some speed for scalar product of complex vec and real vec
template <int dim, typename Type>
inline std::complex<Type> operator*(const vec<dim,std::complex<Type> > &v, const vec<dim,Type> &w) {
  std::complex<Type> r(0);

  for (int i=0; i<dim; i++) {
    r += std::complex<Type>(v.x[i] * w.x[i]);
  }

  return r;
};
template <int dim, typename Type>
inline std::complex<Type> operator*(const vec<dim,Type> &w, const vec<dim,std::complex<Type> > &v) {
  return v*w;
};

// implement real part of a vec
template <int dim, typename Type>
vec<dim,Type> real(const vec<dim,std::complex<Type> > &v) {
  vec<dim,Type> r;

  for (int i=0; i<dim; i++) {
    r.x[i] = real(v.x[i]);
  }

  return r;
};

// implement imaginary part of a vec
template <int dim, typename Type>
vec<dim,Type> imag(const vec<dim,std::complex<Type> > &v) {
  vec<dim,Type> r;

  for (int i=0; i<dim; i++) {
    r.x[i] = imag(v.x[i]);
  }

  return r;
};

// implement complex conjugation of a vec
template <int dim, typename Type>
vec<dim,std::complex<Type> > conj(const vec<dim,std::complex<Type> > &v) {
  vec<dim,std::complex<Type> > r;

  for (int i=0; i<dim; i++) {
    r.x[i] = conj(v.x[i]);
  }

  return r;
};

// implement absolute value of a vec
template <int dim, typename Type>
Type abs(const vec<dim,Type> &v) {
  Type r, a;

  for (int i=0; i<dim; i++) {
    a = abs(v.x[i]);
    r += a*a;
  }

  return sqrt(r);
};

/* -- implementation of vec_array -- */
template <int dim, typename Type>
class vec_array { public:
  Type *x;

  inline vec_array() {};

  inline vec_array(Type *a) {
    x = a;
  };

  inline vec<dim,Type> &operator[](int i) {
    return *(vec<dim,Type> *)(&x[dim*i]);
  }
};

/* -- macro to compute the square of vec instances -- */
#define SQR(x) ((x)*(x))

#endif // end of include guard
<commit_msg>fix bug in vec.hpp<commit_after>// This file provides a fast implementation of common vector operations, using
// a templated and very lightweight vec class. The memory structure of a vec
// instance is just a sequence of its components.
// It also provides a vec_array class, whose memory structure is just the same
// as a sequence of N*dimensions scalars. The [] operator is overloaded
// to return vec instances.
// The goal of these classes is to achieve similar performance as a primitive
// array for the 1d case, while being able to write more general programs.

// include guard
#ifndef VEC_HPP
#define VEC_HPP

// need complex type for optimized template
#include <complex>

/* -- vec class -- */
template <int dim, typename Type>
class vec { public:
  Type x[dim];

  inline vec() {};

  // copy constructor
  template <typename otherType>
  inline vec(const vec<dim,otherType> &other_vec) {

    for (int i=0; i<dim; i++) {
      x[i] = Type(other_vec.x[i]);
    }
  };

  // intitialize with constant value
  template <typename otherType>
  inline vec(otherType val) {
    for (int i=0; i<dim; i++) {
      x[i] = Type(val);
    }
  };

  // in-place summation
  template <typename otherType>
  inline vec<dim,Type> &operator+=(const vec<dim,otherType> &v) {
    for (int i=0; i<dim; i++) {
      x[i] += Type(v.x[i]);
    }

    return *this;
  };

  // in-place subtraction
  template <typename otherType>
  inline vec<dim,Type> &operator-=(const vec<dim,otherType> &v) {
    for (int i=0; i<dim; i++) {
      x[i] -= Type(v.x[i]);
    }

    return *this;
  };

  // in-place multiplication with scalar
  template <typename otherType>
  inline vec<dim,Type> &operator*=(const otherType &v) {
    for (int i=0; i<dim; i++) {
      x[i] *= Type(v);
    }

    return *this;
  };

  // in-place division by scalar
  template <typename otherType>
  inline vec<dim,Type> &operator/=(const otherType &v) {
    for (int i=0; i<dim; i++) {
      x[i] /= Type(v);
    }

    return *this;
  };

  // element-wise application of a function
  template <typename otherType>
  inline vec<dim,otherType> element_wise(otherType& (*func)(Type&)) {
    vec<dim,otherType> r;
    for (int i=0; i<dim; i++) {
      r.x[i] = (*func)(x[i]);
    }
    return r;
  };
};

/* -- common operations on vec -- */

// sum of vec instances
template <int dim, typename Type>
inline vec<dim,Type> operator+(const vec<dim,Type> &v, const vec<dim,Type> &w) {
  vec<dim,Type> r;

  for (int i=0; i<dim; i++) {
    r.x[i] = v.x[i] + w.x[i];
  }

  return r;
};

// difference of vec instances
template <int dim, typename Type>
inline vec<dim,Type> operator-(const vec<dim,Type> &v, const vec<dim,Type> &w) {
  vec<dim,Type> r;

  for (int i=0; i<dim; i++) {
    r.x[i] = v.x[i] - w.x[i];
  }

  return r;
};

// vec times scalar
template <int dim, typename Type>
inline vec<dim,Type> operator*(const vec<dim,Type> &v, const Type &w) {
  vec<dim,Type> r;

  for (int i=0; i<dim; i++) {
    r.x[i] = v.x[i] * w;
  }

  return r;
};

// scalar times vec
template <int dim, typename Type>
inline vec<dim,Type> operator*(const Type &w, const vec<dim,Type> &v) {
  return v*w;
};

// division of vec by scalar
template <int dim, typename Type>
inline vec<dim,Type> operator/(const vec<dim,Type> &v, const Type &w) {
  vec<dim,Type> r;

  for (int i=0; i<dim; i++) {
    r.x[i] = v.x[i] / w;
  }

  return r;
};

// scalar product of vec instances
template <int dim, typename Type>
inline Type operator*(const vec<dim,Type> &v, const vec<dim,Type> &w) {
  Type r(0);

  for (int i=0; i<dim; i++) {
    r += v.x[i] * w.x[i];
  }

  return r;
};

// these more specialized templates gain some speed for scalar product of complex vec and real vec
template <int dim, typename Type>
inline std::complex<Type> operator*(const vec<dim,std::complex<Type> > &v, const vec<dim,Type> &w) {
  std::complex<Type> r(0);

  for (int i=0; i<dim; i++) {
    r += std::complex<Type>(v.x[i] * w.x[i]);
  }

  return r;
};
template <int dim, typename Type>
inline std::complex<Type> operator*(const vec<dim,Type> &w, const vec<dim,std::complex<Type> > &v) {
  return v*w;
};

// implement real part of a vec
template <int dim, typename Type>
vec<dim,Type> real(const vec<dim,std::complex<Type> > &v) {
  vec<dim,Type> r;

  for (int i=0; i<dim; i++) {
    r.x[i] = real(v.x[i]);
  }

  return r;
};

// implement imaginary part of a vec
template <int dim, typename Type>
vec<dim,Type> imag(const vec<dim,std::complex<Type> > &v) {
  vec<dim,Type> r;

  for (int i=0; i<dim; i++) {
    r.x[i] = imag(v.x[i]);
  }

  return r;
};

// implement complex conjugation of a vec
template <int dim, typename Type>
vec<dim,std::complex<Type> > conj(const vec<dim,std::complex<Type> > &v) {
  vec<dim,std::complex<Type> > r;

  for (int i=0; i<dim; i++) {
    r.x[i] = conj(v.x[i]);
  }

  return r;
};

// implement absolute value of a vec
template <int dim, typename Type>
Type abs(const vec<dim,Type> &v) {
  Type r(0), a;

  for (int i=0; i<dim; i++) {
    a = abs(v.x[i]);
    r += a*a;
  }

  return sqrt(r);
};

/* -- implementation of vec_array -- */
template <int dim, typename Type>
class vec_array { public:
  Type *x;

  inline vec_array() {};

  inline vec_array(Type *a) {
    x = a;
  };

  inline vec<dim,Type> &operator[](int i) {
    return *(vec<dim,Type> *)(&x[dim*i]);
  }
};

/* -- macro to compute the square of vec instances -- */
#define SQR(x) ((x)*(x))

#endif // end of include guard
<|endoftext|>


<commit_before>/*
* Copyright (c) 2013 Fredrik Mellbin
*
* This file is part of VapourSynth.
*
* VapourSynth is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* VapourSynth is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with VapourSynth; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

#include <QtCore/QMutex>
#include <QtCore/QMutexLocker>
#include <QtCore/QWaitCondition>
#include <QtCore/QFile>
#include <QtCore/QMap>
#include "VSScript.h"
#include "VSHelper.h"

#ifdef _WIN32
static inline QString nativeToQString(const wchar_t *str) {
	return QString::fromWCharArray(str);
}
#else
static inline QString nativeToQString(const char *str) {
	return QString::fromLocal8Bit(str);
}
#endif

const VSAPI *vsapi = NULL;
VSScript *se = NULL;
VSNodeRef *node = NULL;
FILE *outFile = NULL;

int requests = 0;
int outputIndex = 0;
int outputFrames = 0;
int requestedFrames = 0;
int completedFrames = 0;
int totalFrames = 0;
int numPlanes = 0;
bool y4m = false;
bool outputError = false;
bool showInfo = false;
QMap<int, const VSFrameRef *> reorderMap;

QString errorMessage;
QWaitCondition condition;
QMutex mutex;

void VS_CC frameDoneCallback(void *userData, const VSFrameRef *f, int n, VSNodeRef *, const char *errorMsg) {
    completedFrames++;

    if (f) {
        reorderMap.insert(n, f);
        while (reorderMap.contains(outputFrames)) {
            const VSFrameRef *frame = reorderMap.take(outputFrames);
            if (!outputError) {
				if (y4m) {
					if (!fwrite("FRAME\n", 6, 1, outFile)) {
						errorMessage = "Error: fwrite() call failed";
						totalFrames = requestedFrames;
						outputError = true;
					}
				}

				if (!outputError) {
					const VSFormat *fi = vsapi->getFrameFormat(frame);
					for (int p = 0; p < fi->numPlanes; p++) {
						int stride = vsapi->getStride(frame, p);
						const uint8_t *readPtr = vsapi->getReadPtr(frame, p);
						int rowSize = vsapi->getFrameWidth(frame, p) * fi->bytesPerSample;
						int height = vsapi->getFrameHeight(frame, p);
						for (int y = 0; y < height; y++) {
							if (!fwrite(readPtr, rowSize, 1, outFile)) {
								errorMessage = "Error: fwrite() call failed";
								totalFrames = requestedFrames;
								outputError = true;
								p = 100; // break out of the outer loop
								break;
							}
							readPtr += stride;
						}
					}
				}
			}
            vsapi->freeFrame(frame);
            outputFrames++;
        }
    } else {
        outputError = true;
        totalFrames = requestedFrames;
        if (errorMsg)
            errorMessage = QString("Error: Failed to retrieve frame ") + n + QString(" with error: ") + QString::fromUtf8(errorMsg);
        else
            errorMessage = QString("Error: Failed to retrieve frame ") + n;
    }

    if (requestedFrames < totalFrames) {
        vsapi->getFrameAsync(requestedFrames, node, frameDoneCallback, NULL);
        requestedFrames++;
    }

    if (totalFrames == completedFrames) {
        QMutexLocker lock(&mutex);
        condition.wakeOne();
    }
}

bool outputNode() {
    if (requests < 1) {
		const VSCoreInfo *info = vsapi->getCoreInfo(vseval_getCore());
        requests = info->numThreads;
	}

	const VSVideoInfo *vi = vsapi->getVideoInfo(node);
	totalFrames = vi->numFrames;

	if (y4m && (vi->format->colorFamily != cmGray && vi->format->colorFamily != cmYUV)) {
		errorMessage = "Error: Can only apply y4m headers to YUV and Gray format clips";
		fprintf(stderr, "%s", errorMessage.toUtf8().constData());
        return true;
	}

    QString y4mFormat;
    QString numBits;

    if (y4m) {
        if (vi->format->colorFamily == cmGray) {
            y4mFormat = "mono";
            if (vi->format->bitsPerSample > 8)
				y4mFormat = y4mFormat + QString::number(vi->format->bitsPerSample);
		} else if (vi->format->colorFamily == cmYUV) {
			if (vi->format->subSamplingW == 1 && vi->format->subSamplingH == 1)
                y4mFormat = "420";
			else if (vi->format->subSamplingW == 1 && vi->format->subSamplingH == 0)
                y4mFormat = "422";
			else if (vi->format->subSamplingW == 0 && vi->format->subSamplingH == 0)
                y4mFormat = "444";
			else if (vi->format->subSamplingW == 2 && vi->format->subSamplingH == 2)
                y4mFormat = "410";
			else if (vi->format->subSamplingW == 2 && vi->format->subSamplingH == 0)
                y4mFormat = "411";
			else if (vi->format->subSamplingW == 0 && vi->format->subSamplingH == 1)
                y4mFormat = "440";
			else {
				fprintf(stderr, "No y4m identifier exists for current format");
				return true;
			}

            if (vi->format->bitsPerSample > 8)
                y4mFormat = y4mFormat + "p" + QString::number(vi->format->bitsPerSample);
		} else {
			fprintf(stderr, "No y4m identifier exists for current format");
			return true;
		}
    }
	if (!y4mFormat.isEmpty())
        y4mFormat = "C" + y4mFormat + " ";

	QString header = "YUV4MPEG2 " + y4mFormat + "W" + QString::number(vi->width) + " H" + QString::number(vi->height) + " F" + QString::number(vi->fpsNum)  + ":" + QString::number(vi->fpsDen)  + " Ip A0:0\n";
    QByteArray rawHeader = header.toUtf8();

    if (y4m) {
        if (!fwrite(rawHeader.constData(), rawHeader.size(), 1, outFile)) {
            errorMessage = "Error: fwrite() call failed";
			fprintf(stderr, "%s", errorMessage.toUtf8().constData());
			outputError = true;
			return outputError;
        }
    }

	QMutexLocker lock(&mutex);

	int intitalRequestSize = std::min(requests, totalFrames);
	requestedFrames = intitalRequestSize;
	for (int n = 0; n < intitalRequestSize; n++)
		vsapi->getFrameAsync(n, node, frameDoneCallback, NULL);

	condition.wait(&mutex);

    if (outputError) {
        fprintf(stderr, "%s", errorMessage.toUtf8().constData());
    }

    return outputError;
}

const char *colorFamilyToString(int colorFamily) {
	switch (colorFamily) {
	case cmGray: return "Gray";
	case cmRGB: return "RGB";
	case cmYUV: return "YUV";
	case cmYCoCg: return "YCoCg";
	case cmCompat: return "Compat";
	}
	return "";
}

// fixme, only allow info without output
#ifdef _WIN32
int wmain(int argc, wchar_t **argv) {
#else
int main(int argc, char **argv) {
#endif

    if (argc < 3) {
        fprintf(stderr, "VSPipe usage:\n");
		fprintf(stderr, "Show script info: vspipe script.vpy - -info\n");
        fprintf(stderr, "Write to stdout: vspipe script.vpy - [options]\n");
        fprintf(stderr, "Write to file: vspipe script.vpy <outFile> [options]\n");
        fprintf(stderr, "Available options:\n");
		fprintf(stderr, "Select output index: -index N\n");
		fprintf(stderr, "Set number of concurrent frame requests: -requests N\n");
		fprintf(stderr, "Add YUV4MPEG headers: -y4m\n");
		fprintf(stderr, "Show video info: -info (overrides other options)\n");
        return 1;
    }

	QFile scriptFile(nativeToQString(argv[1]));
	if (!scriptFile.open(QIODevice::ReadOnly)) {
        fprintf(stderr, "Failed to to open script file for reading\n");
        return 1;
	}

	if (scriptFile.size() > 1024*1024*16) {
        fprintf(stderr, "Script files bigger than 16MB not allowed\n");
        return 1;
	}

    QByteArray scriptData = scriptFile.readAll();
	scriptFile.close();
    if (scriptData.isEmpty()) {
        fprintf(stderr, "Failed to read script file or file is empty\n");
        return 1;
    }

	QString outputFilename = nativeToQString(argv[2]);
	if (outputFilename == "-") {
		outFile = stdout;
	} else {
#ifdef _WIN32
		outFile = _wfopen(outputFilename.toStdWString().c_str(), L"wb");
#else
		outFile = fopen(outputFilename.toLocal8Bit(), "wb");
#endif
		if (!outFile) {
			fprintf(stderr, "Failed to open output for writing\n");
			return 1;
		}
	}

	for (int arg = 3; arg < argc; arg++) {
		QString argString = nativeToQString(argv[arg]);
		if (argString == "-y4m") {
			y4m = true;
		} else if (argString == "-info") {
			showInfo = true;
		} else if (argString == "-index") {
			bool ok = false;
			if (argc <= arg + 1) {
				fprintf(stderr, "No index number specified");
				return 1;
			}
			QString numString = nativeToQString(argv[arg+1]);
			index = numString.toInt(&ok);
			if (!ok) {
				fprintf(stderr, "Couldn't convert %s to an integer", numString.toUtf8().constData());
				return 1;
			}
			arg++;
		} else if (argString == "-requests") {
			bool ok = false;
			if (argc <= arg + 1) {
				fprintf(stderr, "No request number specified");
				return 1;
			}
			QString numString = nativeToQString(argv[arg+1]);
			requests = numString.toInt(&ok);
			if (!ok) {
				fprintf(stderr, "Couldn't convert %s to an integer", numString.toUtf8().constData());
				return 1;
			}
			arg++;
		} else {
			fprintf(stderr, "Unknown argument: %s\n", argString.toUtf8().constData());
			return 1;
		}
	}

    if (!vseval_init()) {
        fprintf(stderr, "Failed to initialize VapourSynth environment\n");
        return 1;
    }

    vsapi = vseval_getVSApi();
    if (!vsapi) {
        fprintf(stderr, "Failed to get VapourSynth API pointer\n");
        vseval_finalize();
        return 1;
    }

	if (vseval_evaluateScript(&se, scriptData.constData(), nativeToQString(argv[1]).toUtf8())) {
        fprintf(stderr, "Script evaluation failed:\n%s", vseval_getError(se));
        vseval_freeScript(se);
        vseval_finalize();
        return 1;
    }

    node = vseval_getOutput(se, outputIndex);
    if (!node) {
       fprintf(stderr, "Failed to retrieve output node. Invalid index specified?\n");
       vseval_freeScript(se);
       vseval_finalize();
       return 1;
    }

	bool error = false;
	const VSVideoInfo *vi = vsapi->getVideoInfo(node);

	if (showInfo) {
		fprintf(outFile, "Width: %d\n", vi->width);
		fprintf(outFile, "Height: %d\n", vi->height);
		fprintf(outFile, "Frames: %d\n", vi->numFrames);
		fprintf(outFile, "FPS: %d/%d\n", vi->fpsNum, vi->fpsDen);
		if (vi->format) {
			fprintf(outFile, "Format Name: %s\n", vi->format->name);
			fprintf(outFile, "Color Family: %s\n", colorFamilyToString(vi->format->colorFamily));
			fprintf(outFile, "Bits: %d\n", vi->format->bitsPerSample);
			fprintf(outFile, "SubSampling W: %d\n", vi->format->subSamplingW);
			fprintf(outFile, "SubSampling H: %d\n", vi->format->subSamplingH);
		} else {
			fprintf(outFile, "Format Name: Variable\n");
		}
	} else {
		if (!isConstantFormat(vi) || vi->numFrames == 0) {
			fprintf(stderr, "Cannot output clips with varying dimensions or unknown length\n");
			vseval_freeScript(se);
			vseval_finalize();
			return 1;
		}

		error = outputNode();
	}

	fflush(outFile);

    vseval_freeScript(se);
    vseval_finalize();

	return error;
}
<commit_msg>Fix previous commit<commit_after>/*
* Copyright (c) 2013 Fredrik Mellbin
*
* This file is part of VapourSynth.
*
* VapourSynth is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* VapourSynth is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with VapourSynth; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

#include <QtCore/QMutex>
#include <QtCore/QMutexLocker>
#include <QtCore/QWaitCondition>
#include <QtCore/QFile>
#include <QtCore/QMap>
#include "VSScript.h"
#include "VSHelper.h"

#ifdef _WIN32
static inline QString nativeToQString(const wchar_t *str) {
	return QString::fromWCharArray(str);
}
#else
static inline QString nativeToQString(const char *str) {
	return QString::fromLocal8Bit(str);
}
#endif

const VSAPI *vsapi = NULL;
VSScript *se = NULL;
VSNodeRef *node = NULL;
FILE *outFile = NULL;

int requests = 0;
int outputIndex = 0;
int outputFrames = 0;
int requestedFrames = 0;
int completedFrames = 0;
int totalFrames = 0;
int numPlanes = 0;
bool y4m = false;
bool outputError = false;
bool showInfo = false;
QMap<int, const VSFrameRef *> reorderMap;

QString errorMessage;
QWaitCondition condition;
QMutex mutex;

void VS_CC frameDoneCallback(void *userData, const VSFrameRef *f, int n, VSNodeRef *, const char *errorMsg) {
    completedFrames++;

    if (f) {
        reorderMap.insert(n, f);
        while (reorderMap.contains(outputFrames)) {
            const VSFrameRef *frame = reorderMap.take(outputFrames);
            if (!outputError) {
				if (y4m) {
					if (!fwrite("FRAME\n", 6, 1, outFile)) {
						errorMessage = "Error: fwrite() call failed";
						totalFrames = requestedFrames;
						outputError = true;
					}
				}

				if (!outputError) {
					const VSFormat *fi = vsapi->getFrameFormat(frame);
					for (int p = 0; p < fi->numPlanes; p++) {
						int stride = vsapi->getStride(frame, p);
						const uint8_t *readPtr = vsapi->getReadPtr(frame, p);
						int rowSize = vsapi->getFrameWidth(frame, p) * fi->bytesPerSample;
						int height = vsapi->getFrameHeight(frame, p);
						for (int y = 0; y < height; y++) {
							if (!fwrite(readPtr, rowSize, 1, outFile)) {
								errorMessage = "Error: fwrite() call failed";
								totalFrames = requestedFrames;
								outputError = true;
								p = 100; // break out of the outer loop
								break;
							}
							readPtr += stride;
						}
					}
				}
			}
            vsapi->freeFrame(frame);
            outputFrames++;
        }
    } else {
        outputError = true;
        totalFrames = requestedFrames;
        if (errorMsg)
            errorMessage = QString("Error: Failed to retrieve frame ") + n + QString(" with error: ") + QString::fromUtf8(errorMsg);
        else
            errorMessage = QString("Error: Failed to retrieve frame ") + n;
    }

    if (requestedFrames < totalFrames) {
        vsapi->getFrameAsync(requestedFrames, node, frameDoneCallback, NULL);
        requestedFrames++;
    }

    if (totalFrames == completedFrames) {
        QMutexLocker lock(&mutex);
        condition.wakeOne();
    }
}

bool outputNode() {
    if (requests < 1) {
		const VSCoreInfo *info = vsapi->getCoreInfo(vseval_getCore());
        requests = info->numThreads;
	}

	const VSVideoInfo *vi = vsapi->getVideoInfo(node);
	totalFrames = vi->numFrames;

	if (y4m && (vi->format->colorFamily != cmGray && vi->format->colorFamily != cmYUV)) {
		errorMessage = "Error: Can only apply y4m headers to YUV and Gray format clips";
		fprintf(stderr, "%s", errorMessage.toUtf8().constData());
        return true;
	}

    QString y4mFormat;
    QString numBits;

    if (y4m) {
        if (vi->format->colorFamily == cmGray) {
            y4mFormat = "mono";
            if (vi->format->bitsPerSample > 8)
				y4mFormat = y4mFormat + QString::number(vi->format->bitsPerSample);
		} else if (vi->format->colorFamily == cmYUV) {
			if (vi->format->subSamplingW == 1 && vi->format->subSamplingH == 1)
                y4mFormat = "420";
			else if (vi->format->subSamplingW == 1 && vi->format->subSamplingH == 0)
                y4mFormat = "422";
			else if (vi->format->subSamplingW == 0 && vi->format->subSamplingH == 0)
                y4mFormat = "444";
			else if (vi->format->subSamplingW == 2 && vi->format->subSamplingH == 2)
                y4mFormat = "410";
			else if (vi->format->subSamplingW == 2 && vi->format->subSamplingH == 0)
                y4mFormat = "411";
			else if (vi->format->subSamplingW == 0 && vi->format->subSamplingH == 1)
                y4mFormat = "440";
			else {
				fprintf(stderr, "No y4m identifier exists for current format");
				return true;
			}

            if (vi->format->bitsPerSample > 8)
                y4mFormat = y4mFormat + "p" + QString::number(vi->format->bitsPerSample);
		} else {
			fprintf(stderr, "No y4m identifier exists for current format");
			return true;
		}
    }
	if (!y4mFormat.isEmpty())
        y4mFormat = "C" + y4mFormat + " ";

	QString header = "YUV4MPEG2 " + y4mFormat + "W" + QString::number(vi->width) + " H" + QString::number(vi->height) + " F" + QString::number(vi->fpsNum)  + ":" + QString::number(vi->fpsDen)  + " Ip A0:0\n";
    QByteArray rawHeader = header.toUtf8();

    if (y4m) {
        if (!fwrite(rawHeader.constData(), rawHeader.size(), 1, outFile)) {
            errorMessage = "Error: fwrite() call failed";
			fprintf(stderr, "%s", errorMessage.toUtf8().constData());
			outputError = true;
			return outputError;
        }
    }

	QMutexLocker lock(&mutex);

	int intitalRequestSize = std::min(requests, totalFrames);
	requestedFrames = intitalRequestSize;
	for (int n = 0; n < intitalRequestSize; n++)
		vsapi->getFrameAsync(n, node, frameDoneCallback, NULL);

	condition.wait(&mutex);

    if (outputError) {
        fprintf(stderr, "%s", errorMessage.toUtf8().constData());
    }

    return outputError;
}

const char *colorFamilyToString(int colorFamily) {
	switch (colorFamily) {
	case cmGray: return "Gray";
	case cmRGB: return "RGB";
	case cmYUV: return "YUV";
	case cmYCoCg: return "YCoCg";
	case cmCompat: return "Compat";
	}
	return "";
}

// fixme, only allow info without output
#ifdef _WIN32
int wmain(int argc, wchar_t **argv) {
#else
int main(int argc, char **argv) {
#endif

    if (argc < 3) {
        fprintf(stderr, "VSPipe usage:\n");
		fprintf(stderr, "Show script info: vspipe script.vpy - -info\n");
        fprintf(stderr, "Write to stdout: vspipe script.vpy - [options]\n");
        fprintf(stderr, "Write to file: vspipe script.vpy <outFile> [options]\n");
        fprintf(stderr, "Available options:\n");
		fprintf(stderr, "Select output index: -index N\n");
		fprintf(stderr, "Set number of concurrent frame requests: -requests N\n");
		fprintf(stderr, "Add YUV4MPEG headers: -y4m\n");
		fprintf(stderr, "Show video info: -info (overrides other options)\n");
        return 1;
    }

	QFile scriptFile(nativeToQString(argv[1]));
	if (!scriptFile.open(QIODevice::ReadOnly)) {
        fprintf(stderr, "Failed to to open script file for reading\n");
        return 1;
	}

	if (scriptFile.size() > 1024*1024*16) {
        fprintf(stderr, "Script files bigger than 16MB not allowed\n");
        return 1;
	}

    QByteArray scriptData = scriptFile.readAll();
	scriptFile.close();
    if (scriptData.isEmpty()) {
        fprintf(stderr, "Failed to read script file or file is empty\n");
        return 1;
    }

	QString outputFilename = nativeToQString(argv[2]);
	if (outputFilename == "-") {
		outFile = stdout;
	} else {
#ifdef _WIN32
		outFile = _wfopen(outputFilename.toStdWString().c_str(), L"wb");
#else
		outFile = fopen(outputFilename.toLocal8Bit(), "wb");
#endif
		if (!outFile) {
			fprintf(stderr, "Failed to open output for writing\n");
			return 1;
		}
	}

	for (int arg = 3; arg < argc; arg++) {
		QString argString = nativeToQString(argv[arg]);
		if (argString == "-y4m") {
			y4m = true;
		} else if (argString == "-info") {
			showInfo = true;
		} else if (argString == "-index") {
			bool ok = false;
			if (argc <= arg + 1) {
				fprintf(stderr, "No index number specified");
				return 1;
			}
			QString numString = nativeToQString(argv[arg+1]);
			outputIndex = numString.toInt(&ok);
			if (!ok) {
				fprintf(stderr, "Couldn't convert %s to an integer", numString.toUtf8().constData());
				return 1;
			}
			arg++;
		} else if (argString == "-requests") {
			bool ok = false;
			if (argc <= arg + 1) {
				fprintf(stderr, "No request number specified");
				return 1;
			}
			QString numString = nativeToQString(argv[arg+1]);
			requests = numString.toInt(&ok);
			if (!ok) {
				fprintf(stderr, "Couldn't convert %s to an integer", numString.toUtf8().constData());
				return 1;
			}
			arg++;
		} else {
			fprintf(stderr, "Unknown argument: %s\n", argString.toUtf8().constData());
			return 1;
		}
	}

    if (!vseval_init()) {
        fprintf(stderr, "Failed to initialize VapourSynth environment\n");
        return 1;
    }

    vsapi = vseval_getVSApi();
    if (!vsapi) {
        fprintf(stderr, "Failed to get VapourSynth API pointer\n");
        vseval_finalize();
        return 1;
    }

	if (vseval_evaluateScript(&se, scriptData.constData(), nativeToQString(argv[1]).toUtf8())) {
        fprintf(stderr, "Script evaluation failed:\n%s", vseval_getError(se));
        vseval_freeScript(se);
        vseval_finalize();
        return 1;
    }

    node = vseval_getOutput(se, outputIndex);
    if (!node) {
       fprintf(stderr, "Failed to retrieve output node. Invalid index specified?\n");
       vseval_freeScript(se);
       vseval_finalize();
       return 1;
    }

	bool error = false;
	const VSVideoInfo *vi = vsapi->getVideoInfo(node);

	if (showInfo) {
		fprintf(outFile, "Width: %d\n", vi->width);
		fprintf(outFile, "Height: %d\n", vi->height);
		fprintf(outFile, "Frames: %d\n", vi->numFrames);
		fprintf(outFile, "FPS: %d/%d\n", vi->fpsNum, vi->fpsDen);
		if (vi->format) {
			fprintf(outFile, "Format Name: %s\n", vi->format->name);
			fprintf(outFile, "Color Family: %s\n", colorFamilyToString(vi->format->colorFamily));
			fprintf(outFile, "Bits: %d\n", vi->format->bitsPerSample);
			fprintf(outFile, "SubSampling W: %d\n", vi->format->subSamplingW);
			fprintf(outFile, "SubSampling H: %d\n", vi->format->subSamplingH);
		} else {
			fprintf(outFile, "Format Name: Variable\n");
		}
	} else {
		if (!isConstantFormat(vi) || vi->numFrames == 0) {
			fprintf(stderr, "Cannot output clips with varying dimensions or unknown length\n");
			vseval_freeScript(se);
			vseval_finalize();
			return 1;
		}

		error = outputNode();
	}

	fflush(outFile);

    vseval_freeScript(se);
    vseval_finalize();

	return error;
}
<|endoftext|>


<commit_before><commit_msg>Enable staking for p2sh-p2wkh.<commit_after><|endoftext|>


<commit_before>#include "GPIO.hh"

// STL
#include <iostream>
#include <chrono>

#include <unistd.h> // usleep()

using namespace std::chrono;

high_resolution_clock::time_point beg;
duration<double, std::micro> accum;

class Handler
{
public:
   void handle(GPIO::Value val)
   {
      const high_resolution_clock::time_point end = high_resolution_clock::now();

      const auto time_span = end - beg;
      accum += time_span;
      std::cout << "Latency: " << time_span.count() << " microseconds" << std::endl;
   }
};

void myisr(GPIO::Value val)
{
   const high_resolution_clock::time_point end = high_resolution_clock::now();

   const auto time_span = end - beg;
   accum += time_span;
   std::cout << "Latency: " << time_span.count() << " microseconds" << std::endl;
}

int main()
{
   Handler h;

   accum = std::chrono::duration<double, std::micro>(0.0);

   // Member functions do not take any longer to call than global functions
   std::function<void(GPIO::Value)> global(myisr);

   std::function<void(GPIO::Value)> handleisr =
      std::bind(&Handler::handle, &h, std::placeholders::_1);

   {
      // Short GPIO 15 (input) to GPIO 27 (output) for the following latency test
      GPIO gpio1(27, GPIO::Direction::OUT);
      GPIO gpio2(15, GPIO::Edge::RISING, handleisr); // will be destroyed first,
                                                     // so no spurious call to handleisr upon
                                                     // destruction of GPIO 27

      usleep(125000);

      const unsigned int nIterations = 50;
      for(unsigned int i=0;i<nIterations;++i)
      {
         beg = high_resolution_clock::now();
         gpio1.setValue(GPIO::Value::HIGH);
         usleep(31250);

         gpio1.setValue(GPIO::Value::LOW);
         usleep(31250);
      }

      std::cout << "Average: " << accum.count()/nIterations << " microseconds " << std::endl;
   }
}
<commit_msg>Ensure printed units are microseconds<commit_after>#include "GPIO.hh"

// STL
#include <iostream>
#include <chrono>

#include <unistd.h> // usleep()

using namespace std::chrono;

high_resolution_clock::time_point beg;
duration<double, std::micro> accum;

class Handler
{
public:
   void handle(GPIO::Value val)
   {
      const high_resolution_clock::time_point end = high_resolution_clock::now();

      const auto time_span = duration_cast<microseconds>(end - beg);
      accum += time_span;
      std::cout << "Latency: " << time_span.count() << " microseconds" << std::endl;
   }
};

void myisr(GPIO::Value val)
{
   const high_resolution_clock::time_point end = high_resolution_clock::now();

   const auto time_span = end - beg;
   accum += time_span;
   std::cout << "Latency: " << time_span.count() << " microseconds" << std::endl;
}

int main()
{
   Handler h;

   accum = std::chrono::duration<double, std::micro>(0.0);

   // Member functions do not take any longer to call than global functions
   std::function<void(GPIO::Value)> global(myisr);

   std::function<void(GPIO::Value)> handleisr =
      std::bind(&Handler::handle, &h, std::placeholders::_1);

   {
      // Short GPIO 15 (input) to GPIO 27 (output) for the following latency test
      GPIO gpio1(27, GPIO::Direction::OUT);
      GPIO gpio2(15, GPIO::Edge::RISING, handleisr); // will be destroyed first,
                                                     // so no spurious call to handleisr upon
                                                     // destruction of GPIO 27

      usleep(125000);

      const unsigned int nIterations = 50;
      for(unsigned int i=0;i<nIterations;++i)
      {
         beg = high_resolution_clock::now();
         gpio1.setValue(GPIO::Value::HIGH);
         usleep(31250);

         gpio1.setValue(GPIO::Value::LOW);
         usleep(31250);
      }

      std::cout << "Average: " << accum.count()/nIterations << " microseconds " << std::endl;
   }
}
<|endoftext|>


<commit_before>/*
 * Copyright 2014 Cloudius Systems
 */

#include "database.hh"
#include "core/app-template.hh"
#include "core/distributed.hh"
#include "thrift/server.hh"
#include "transport/server.hh"

namespace bpo = boost::program_options;

int main(int ac, char** av) {
    app_template app;
    app.add_options()
        ("cql-port", bpo::value<uint16_t>()->default_value(9042), "CQL port")
        ("thrift-port", bpo::value<uint16_t>()->default_value(9160), "Thrift port")
        ("datadir", bpo::value<std::string>()->default_value("/var/lib/cassandra/data"), "data directory");

    auto server = std::make_unique<distributed<thrift_server>>();;
    distributed<database> db;

    return app.run(ac, av, [&] {
        auto&& config = app.configuration();
        uint16_t thrift_port = config["thrift-port"].as<uint16_t>();
        uint16_t cql_port = config["cql-port"].as<uint16_t>();
        sstring datadir = config["datadir"].as<std::string>();

        return db.start().then([datadir, &db] {
            return db.invoke_on_all(&database::init_from_data_directory, datadir);
        }).then([&db, cql_port, thrift_port] {
            auto cserver = new distributed<cql_server>;
            cserver->start(std::ref(db)).then([server = std::move(cserver), cql_port] () mutable {
                    server->invoke_on_all(&cql_server::listen, ipv4_addr{cql_port});
            }).then([cql_port] {
                std::cout << "CQL server listening on port " << cql_port << " ...\n";
            });
            auto tserver = new distributed<thrift_server>;
            tserver->start(std::ref(db)).then([server = std::move(tserver), thrift_port] () mutable {
                    server->invoke_on_all(&thrift_server::listen, ipv4_addr{thrift_port});
            }).then([thrift_port] {
                std::cout << "Thrift server listening on port " << thrift_port << " ...\n";
            });
        }).or_terminate();
    });
}
<commit_msg>Avoid crash on ctrl-C<commit_after>/*
 * Copyright 2014 Cloudius Systems
 */

#include "database.hh"
#include "core/app-template.hh"
#include "core/distributed.hh"
#include "thrift/server.hh"
#include "transport/server.hh"

namespace bpo = boost::program_options;

int main(int ac, char** av) {
    app_template app;
    app.add_options()
        ("cql-port", bpo::value<uint16_t>()->default_value(9042), "CQL port")
        ("thrift-port", bpo::value<uint16_t>()->default_value(9160), "Thrift port")
        ("datadir", bpo::value<std::string>()->default_value("/var/lib/cassandra/data"), "data directory");

    auto server = std::make_unique<distributed<thrift_server>>();;
    distributed<database> db;

    return app.run(ac, av, [&] {
        auto&& config = app.configuration();
        uint16_t thrift_port = config["thrift-port"].as<uint16_t>();
        uint16_t cql_port = config["cql-port"].as<uint16_t>();
        sstring datadir = config["datadir"].as<std::string>();

        return db.start().then([datadir, &db] {
            engine().at_exit([&db] { return db.stop(); });
            return db.invoke_on_all(&database::init_from_data_directory, datadir);
        }).then([&db, cql_port, thrift_port] {
            auto cserver = new distributed<cql_server>;
            cserver->start(std::ref(db)).then([server = std::move(cserver), cql_port] () mutable {
                    server->invoke_on_all(&cql_server::listen, ipv4_addr{cql_port});
            }).then([cql_port] {
                std::cout << "CQL server listening on port " << cql_port << " ...\n";
            });
            auto tserver = new distributed<thrift_server>;
            tserver->start(std::ref(db)).then([server = std::move(tserver), thrift_port] () mutable {
                    server->invoke_on_all(&thrift_server::listen, ipv4_addr{thrift_port});
            }).then([thrift_port] {
                std::cout << "Thrift server listening on port " << thrift_port << " ...\n";
            });
        }).or_terminate();
    });
}
<|endoftext|>


<commit_before>#ifndef SIMPLE_IO
#define SIMPLE_IO

#include <string>
#include <iostream>
#include <fstream>
#include <memory>

#ifndef NO_ZLIB
#include "zlib.h"
#endif

class FileInputType
{
public:
    virtual bool getline(std::string &line) = 0;
    virtual ~FileInputType() { };
};

class IFStreamInput : public FileInputType
{
public:
    IFStreamInput(std::string filename) { ifstr.open(filename, std::ios_base::in); };
    ~IFStreamInput() { ifstr.close(); }
    bool getline(std::string &line) { return std::getline(ifstr, line); }
private:
    std::ifstream ifstr;
};

#ifndef NO_ZLIB
class GZipFileInput : public FileInputType
{
public:
    GZipFileInput(std::string filename);
    ~GZipFileInput();
    bool getline(std::string &line);
private:
    gzFile gzf;
};
#endif

class SimpleFileInput
{
public:
    SimpleFileInput(std::string filename);
    ~SimpleFileInput() { };
    bool getline(std::string &line) { return infs->getline(line); }
private:
    bool ends_with(std::string const &filename,
                   std::string const &suffix)
    {
        if (filename.length() < suffix.length()) return false;
        return (0 == filename.compare(filename.length()-suffix.length(), suffix.length(), suffix));
    }
    std::unique_ptr<FileInputType> infs;
};

class FileOutputType
{
public:
    virtual void close() = 0;
    virtual FileOutputType& operator<<(const std::string &str) = 0;
    virtual FileOutputType& operator<<(int) = 0;
    virtual FileOutputType& operator<<(long int) = 0;
    virtual FileOutputType& operator<<(unsigned int) = 0;
    virtual FileOutputType& operator<<(long unsigned int) = 0;
    virtual FileOutputType& operator<<(float) = 0;
    virtual FileOutputType& operator<<(double) = 0;
    virtual ~FileOutputType() { };
};

class OFStream: public FileOutputType
{
public:
    OFStream(std::string filename);
    ~OFStream();
    void close();
    OFStream& operator<<(const std::string &str);
    OFStream& operator<<(int);
    OFStream& operator<<(long int);
    OFStream& operator<<(unsigned int);
    OFStream& operator<<(long unsigned int);
    OFStream& operator<<(float);
    OFStream& operator<<(double);
private:
    std::ofstream ofstr;
};

#ifndef NO_ZLIB
class GZipFileOutput: public FileOutputType
{
public:
    GZipFileOutput(std::string filename);
    ~GZipFileOutput();
    void close();
    GZipFileOutput& operator<<(const std::string &str);
    GZipFileOutput& operator<<(int);
    GZipFileOutput& operator<<(long int);
    GZipFileOutput& operator<<(unsigned int);
    GZipFileOutput& operator<<(long unsigned int);
    GZipFileOutput& operator<<(float);
    GZipFileOutput& operator<<(double);
private:
    gzFile gzf;
    bool open;
};
#endif

class SimpleFileOutput
{
public:
    SimpleFileOutput(std::string filename);
    ~SimpleFileOutput();
    void close();
    SimpleFileOutput& operator<<(const std::string &str);
    SimpleFileOutput& operator<<(int);
    SimpleFileOutput& operator<<(long int);
    SimpleFileOutput& operator<<(unsigned int);
    SimpleFileOutput& operator<<(long unsigned int);
    SimpleFileOutput& operator<<(float);
    SimpleFileOutput& operator<<(double);
private:
    bool ends_with(std::string const &filename,
                   std::string const &suffix)
    {
        if (filename.length() < suffix.length()) return false;
        return (0 == filename.compare(filename.length()-suffix.length(), suffix.length(), suffix));
    }
    std::unique_ptr<FileOutputType> outfs;
};

#endif
<commit_msg>Explicit bool conversion for compatibility.<commit_after>#ifndef SIMPLE_IO
#define SIMPLE_IO

#include <string>
#include <iostream>
#include <fstream>
#include <memory>

#ifndef NO_ZLIB
#include "zlib.h"
#endif

class FileInputType
{
public:
    virtual bool getline(std::string &line) = 0;
    virtual ~FileInputType() { };
};

class IFStreamInput : public FileInputType
{
public:
    IFStreamInput(std::string filename) { ifstr.open(filename, std::ios_base::in); };
    ~IFStreamInput() { ifstr.close(); }
    bool getline(std::string &line) { return (bool)std::getline(ifstr,
line); }
private:
    std::ifstream ifstr;
};

#ifndef NO_ZLIB
class GZipFileInput : public FileInputType
{
public:
    GZipFileInput(std::string filename);
    ~GZipFileInput();
    bool getline(std::string &line);
private:
    gzFile gzf;
};
#endif

class SimpleFileInput
{
public:
    SimpleFileInput(std::string filename);
    ~SimpleFileInput() { };
    bool getline(std::string &line) { return infs->getline(line); }
private:
    bool ends_with(std::string const &filename,
                   std::string const &suffix)
    {
        if (filename.length() < suffix.length()) return false;
        return (0 == filename.compare(filename.length()-suffix.length(), suffix.length(), suffix));
    }
    std::unique_ptr<FileInputType> infs;
};

class FileOutputType
{
public:
    virtual void close() = 0;
    virtual FileOutputType& operator<<(const std::string &str) = 0;
    virtual FileOutputType& operator<<(int) = 0;
    virtual FileOutputType& operator<<(long int) = 0;
    virtual FileOutputType& operator<<(unsigned int) = 0;
    virtual FileOutputType& operator<<(long unsigned int) = 0;
    virtual FileOutputType& operator<<(float) = 0;
    virtual FileOutputType& operator<<(double) = 0;
    virtual ~FileOutputType() { };
};

class OFStream: public FileOutputType
{
public:
    OFStream(std::string filename);
    ~OFStream();
    void close();
    OFStream& operator<<(const std::string &str);
    OFStream& operator<<(int);
    OFStream& operator<<(long int);
    OFStream& operator<<(unsigned int);
    OFStream& operator<<(long unsigned int);
    OFStream& operator<<(float);
    OFStream& operator<<(double);
private:
    std::ofstream ofstr;
};

#ifndef NO_ZLIB
class GZipFileOutput: public FileOutputType
{
public:
    GZipFileOutput(std::string filename);
    ~GZipFileOutput();
    void close();
    GZipFileOutput& operator<<(const std::string &str);
    GZipFileOutput& operator<<(int);
    GZipFileOutput& operator<<(long int);
    GZipFileOutput& operator<<(unsigned int);
    GZipFileOutput& operator<<(long unsigned int);
    GZipFileOutput& operator<<(float);
    GZipFileOutput& operator<<(double);
private:
    gzFile gzf;
    bool open;
};
#endif

class SimpleFileOutput
{
public:
    SimpleFileOutput(std::string filename);
    ~SimpleFileOutput();
    void close();
    SimpleFileOutput& operator<<(const std::string &str);
    SimpleFileOutput& operator<<(int);
    SimpleFileOutput& operator<<(long int);
    SimpleFileOutput& operator<<(unsigned int);
    SimpleFileOutput& operator<<(long unsigned int);
    SimpleFileOutput& operator<<(float);
    SimpleFileOutput& operator<<(double);
private:
    bool ends_with(std::string const &filename,
                   std::string const &suffix)
    {
        if (filename.length() < suffix.length()) return false;
        return (0 == filename.compare(filename.length()-suffix.length(), suffix.length(), suffix));
    }
    std::unique_ptr<FileOutputType> outfs;
};

#endif
<|endoftext|>


<commit_before>#include <string>
#include <fstream>
#include <iostream>
#include "map.h"

using namespace std;

Map::Map() {}

Map::~Map() {}

void Map::LoadMap(string MapFileName){
	string Temp;
	fstream MapFile;
	int X = 0;
	int Y = 0;

	MapFile.open (MapFileName, fstream::in);
	while ( MapFile >> Temp ){
		cout << Temp;
		mapArray[X][Y] = (unsigned short int)stoi(Temp);
		X++;
		if (X > MaxX){X = 0; Y++;}
	}
	MapFile.close();
}

int Map::Point(int X, int Y){
	return (int)mapArray[X][Y];
}

bool Map::Passable(int X, int Y){
	return (mapArray[X][Y] < PassableThreshhold);
}

string Map::GetPlot(int X, int Y){
	//Returns a 20x20 chunk of the map
	string RetVal;
	string Temp;
	for (int i = X; i < X + 20; i++){
		for (int j = Y; j < Y + 20; j++){
			if (i <= MaxX && i > -1 && j <= MaxY && j > -1){
				Temp = to_string(mapArray[i][j]);
				if (Temp.length() == 1) { RetVal += "0";}
				RetVal += Temp;
			} else {
			RetVal += "-1";
			}
		}
	}
	return RetVal;
}<commit_msg>Work in progress<commit_after>#include <string>
#include <fstream>
#include <iostream>
#include "map.h"

using namespace std;

Map::Map() {}

Map::~Map() {}

void Map::LoadMap(string MapFileName){
	string Temp;
	fstream MapFile;
	int X = 0;
	int Y = 0;
	int F = 0;

	MapFile.open (MapFileName, fstream::in);
	while ( MapFile >> Temp ){
		for (int i = 0; i < Temp.length(); i++){
			if (Temp[i] == ","){
				mapArray[X][Y] = (unsigned short int)stoi(Temp.substr(F,i-F));
				F = i+1;
				cout << mapArray[X][Y];
			}
		X++;
		if (X > MaxX){X = 0; Y++;}
	}
	MapFile.close();
}

int Map::Point(int X, int Y){
	return (int)mapArray[X][Y];
}

bool Map::Passable(int X, int Y){
	return (mapArray[X][Y] < PassableThreshhold);
}

string Map::GetPlot(int X, int Y){
	//Returns a 20x20 chunk of the map
	string RetVal;
	string Temp;
	for (int i = X; i < X + 20; i++){
		for (int j = Y; j < Y + 20; j++){
			if (i <= MaxX && i > -1 && j <= MaxY && j > -1){
				Temp = to_string(mapArray[i][j]);
				if (Temp.length() == 1) { RetVal += "0";}
				RetVal += Temp;
			} else {
			RetVal += "-1";
			}
		}
	}
	return RetVal;
}<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qsystemdeviceinfo.h"
#include "qsysteminfocommon_p.h"
#include <QMetaType>

QTM_BEGIN_NAMESPACE
        Q_GLOBAL_STATIC(QSystemDeviceInfoPrivate, deviceInfoPrivate)

#ifdef QT_SIMULATOR
QSystemDeviceInfoPrivate *getSystemDeviceInfoPrivate() { return deviceInfoPrivate(); }
#endif

// device
 /*!
        \class QSystemDeviceInfo
        \ingroup systeminfo
        \inmodule QtSystemInfo
        \brief The QSystemDeviceInfo class provides access to device information from the system.

        \fn QSystemDeviceInfo::QSystemDeviceInfo(QObject *parent)

   Constructs a QSystemDeviceInfo with the given \a parent.
 */
        /*!
           \enum QSystemDisplayInfo::DisplayOrientation
          This enum describes the current orientation of the display.

             \value Unknown              Orientation could not be determined.
             \value Landscape            Orientation is in landscape.
             \value Portrait             Orientation is in portrait.
             \value InvertedLandscape    Orientation is landscape inverted.
             \value InvertedPortrait     Orientation is portrait inverted.
        */

        /*!
          \fn void QSystemDeviceInfo::batteryLevelChanged(int level)

          This signal is emitted when battery level has changed.
          \a level is the new level.
         */

        /*!
          \fn void QSystemDeviceInfo::batteryStatusChanged(QSystemDeviceInfo::BatteryStatus status)

          This signal is emitted when battery status has changed.
          \a status is the new status.
         */

           /*!
          \fn void QSystemDeviceInfo::powerStateChanged(QSystemDeviceInfo::PowerState state)

          This signal is emitted when the power state has changed, such as when a phone gets plugged in to the wall.
          \a state is the new power state.
         */

        /*!
          \fn  void QSystemDeviceInfo::currentProfileChanged(QSystemDeviceInfo::Profile profile)

          This signal is emitted whenever the users active profile changes, specified by \a profile.
        */

        /*!
            \enum QSystemDeviceInfo::BatteryStatus
            This enum describes the status of the main battery.

            \value NoBatteryLevel          Battery level undetermined.
            \value BatteryCritical         Battery level is critical 3% or less.
            \value BatteryVeryLow          Battery level is very low, 10% or less.
            \value BatteryLow              Battery level is low 40% or less.
            \value BatteryNormal           Battery level is above 40%.

          */
        /*!
            \enum QSystemDeviceInfo::PowerState
            This enum describes the power state:

            \value UnknownPower                   Power error.
            \value BatteryPower                   On battery power.
            \value WallPower                      On wall power.
            \value WallPowerChargingBattery       On wall power and charging main battery.

          */
        /*!
            \enum QSystemDeviceInfo::Profile
            This enum describes the current operating profile of the device or computer.

            \value UnknownProfile          Profile unknown or error.
            \value SilentProfile           Silent profile.
            \value NormalProfile           Normal profile.
            \value LoudProfile             Loud profile.
            \value VibProfile              Vibrate profile.
            \value OfflineProfile          Offline profile.
            \value PowersaveProfile        Powersave profile.
            \value CustomProfile           Custom profile.

          */

        /*!
            \enum QSystemDeviceInfo::SimStatus
            This enum describes the status is the sim card or cards.

            \value SimNotAvailable         SIM is not available on this device.
            \value SingleSimAvailable         One SIM card is available on this.
            \value DualSimAvailable           Two SIM cards are available on this device.
            \value SimLocked                  Device has SIM lock enabled.
        */

        /*!
            \enum QSystemDeviceInfo::InputMethod
            This enum describes the device method of user input.

            \value Keys               Device has key/buttons.
            \value Keypad             Device has keypad (1,2,3, etc).
            \value Keyboard           Device has qwerty keyboard.
            \value SingleTouch        Device has single touch screen.
            \value MultiTouch         Device has muti touch screen.
            \value Mouse              Device has a mouse.
        */
        /*!
          \fn void QSystemDeviceInfo::bluetoothStateChanged(bool on)

          This signal is emitted whenever bluetooth state changes, specified by \a on.
        */

QSystemDeviceInfo::QSystemDeviceInfo(QObject *parent)
    : QObject(parent), d(deviceInfoPrivate())
{
    qRegisterMetaType<QSystemDeviceInfo::BatteryStatus>("QSystemDeviceInfo::BatteryStatus");
    qRegisterMetaType<QSystemDeviceInfo::PowerState>("QSystemDeviceInfo::PowerState");
    qRegisterMetaType<QSystemDeviceInfo::SimStatus>("QSystemDeviceInfo::SimStatus");
    qRegisterMetaType<QSystemDeviceInfo::Profile>("QSystemDeviceInfo::Profile");
    qRegisterMetaType<QSystemDeviceInfo::InputMethodFlags>("QSystemDeviceInfo::InputMethodFlags");

    connect(d,SIGNAL(batteryLevelChanged(int)),
            this,SIGNAL(batteryLevelChanged(int)));

    connect(d,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),
            this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)));

    connect(d,SIGNAL(bluetoothStateChanged(bool)),
            this,SIGNAL(bluetoothStateChanged(bool)));

    connect(d,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),
            this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)));

    connect(d,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),
            this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)));
    }

/*!
  Destroys the QSystemDeviceInfo object.
 */
QSystemDeviceInfo::~QSystemDeviceInfo()
{
}

/*!
    \internal

    This function is called when the client connects to signals.

    \sa connectNotify()
*/

void QSystemDeviceInfo::connectNotify(const char *signal)
{
    Q_UNUSED(signal);
}

/*!
    \internal

    This function is called when the client disconnects from the signals.

    \sa connectNotify()
*/
void QSystemDeviceInfo::disconnectNotify(const char *signal)
{
    if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
            batteryLevelChanged(int))))) {
        disconnect(d,SIGNAL(batteryLevelChanged(int)),
                this,SIGNAL(batteryLevelChanged(int)));
    }
    if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
            batteryStatusChanged(QSystemDeviceInfo::BatteryStatus))))) {
        disconnect(d,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),
                this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)));
    }
    if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
            bluetoothStateChanged(bool))))) {
        disconnect(d,SIGNAL(bluetoothStateChanged(bool)),
                this,SIGNAL(bluetoothStateChanged(bool)));
    }
    if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
            currentProfileChanged(QSystemDeviceInfo::Profile))))) {
        disconnect(d,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),
                this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)));
    }
    if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
            powerStateChanged(QSystemDeviceInfo::PowerState))))) {
        disconnect(d,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),
                this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)));
    }
}

/*!
  \property QSystemDeviceInfo::inputMethodType
  \brief The supported inputmethods.

    Returns the QSystemDeviceInfo::InputMethodFlags InputMethodType that the system uses.
*/
QSystemDeviceInfo::InputMethodFlags QSystemDeviceInfo::inputMethodType()
{
 return deviceInfoPrivate()->inputMethodType();
}

/*!
  \property QSystemDeviceInfo::imei
  \brief The IMEI.

    Returns the International Mobile Equipment Identity (IMEI), or a null QString in the case of none.
*/
QString QSystemDeviceInfo::imei()
{
    return deviceInfoPrivate()->imei();
}

/*!
  \property QSystemDeviceInfo::imsi
  \brief The IMSI.

    Returns the International Mobile Subscriber Identity (IMSI), or a null QString in the case of none.
*/
QString QSystemDeviceInfo::imsi()
{
    return deviceInfoPrivate()->imsi();
}

/*!
  \property QSystemDeviceInfo::manufacturer
  \brief The manufacture's name.

    Returns the name of the manufacturer of this device. In the case of desktops, the name of the vendor
    of the motherboard.
*/
QString QSystemDeviceInfo::manufacturer()
{
    return deviceInfoPrivate()->manufacturer();
}

/*!
  \property QSystemDeviceInfo::model
  \brief The model name.

    Returns the model information of the device. In the case of desktops where no
    model information is present, the CPU architect, such as i686, and machine type, such as Server,
    Desktop or Laptop.
*/
QString QSystemDeviceInfo::model()
{
    return deviceInfoPrivate()->model();
}

/*!
  \property QSystemDeviceInfo::productName
  \brief The product name.

    Returns the product name of the device. In the case where no product information is available,

*/
QString QSystemDeviceInfo::productName()
{
    return deviceInfoPrivate()->productName();
}
/*!
  \property  QSystemDeviceInfo::batteryLevel
  \brief The battery level.

    Returns the battery charge level as percentage 1 - 100 scale.
*/
int QSystemDeviceInfo::batteryLevel() const
{
    return deviceInfoPrivate()->batteryLevel();
}

  /*!
    \property QSystemDeviceInfo::batteryStatus
    \brief The battery status.

    Returns the battery charge status.
*/
QSystemDeviceInfo::BatteryStatus QSystemDeviceInfo::batteryStatus()
{
   int level = batteryLevel();
    if(level < 4) {
        return QSystemDeviceInfo::BatteryCritical;
    }   else if(level < 11) {
        return QSystemDeviceInfo::BatteryVeryLow;
    }  else if(level < 41) {
        return QSystemDeviceInfo::BatteryLow;
    }   else if(level > 40) {
        return QSystemDeviceInfo::BatteryNormal;
    }

    return QSystemDeviceInfo::NoBatteryLevel;
}

/*!
  \property QSystemDeviceInfo::simStatus
  \brief the status of the sim card.
  Returns the QSystemDeviceInfo::simStatus status of SIM card.
*/
QSystemDeviceInfo::SimStatus QSystemDeviceInfo::simStatus()
{
    return deviceInfoPrivate()->simStatus();
}
/*!
  \property QSystemDeviceInfo::isDeviceLocked
  \brief Device lock.

  Returns true if the device is locked, otherwise false.
*/
bool QSystemDeviceInfo::isDeviceLocked()
{
    return deviceInfoPrivate()->isDeviceLocked();
}

/*!
  \property QSystemDeviceInfo::currentProfile
  \brief the device profile
  Gets the current QSystemDeviceInfo::currentProfile device profile.
*/
QSystemDeviceInfo::Profile QSystemDeviceInfo::currentProfile()
{
    return deviceInfoPrivate()->currentProfile();
}

/*!
  \property QSystemDeviceInfo::currentPowerState
  \brief the power state.

  Gets the current QSystemDeviceInfo::currentPowerState state.
*/
QSystemDeviceInfo::PowerState QSystemDeviceInfo::currentPowerState()
{
    return deviceInfoPrivate()->currentPowerState();
}

/*!
 \property QSystemDeviceInfo::currentBluetoothPowerState
 \brief bluetooth power state.

 Gets the current bluetooth power state.
 */
bool QSystemDeviceInfo::currentBluetoothPowerState()
{
    return deviceInfoPrivate()->currentBluetoothPowerState();
}

#include "moc_qsystemdeviceinfo.cpp"

QTM_END_NAMESPACE

<commit_msg>Minor fix to the documentation<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qsystemdeviceinfo.h"
#include "qsysteminfocommon_p.h"
#include <QMetaType>

QTM_BEGIN_NAMESPACE
        Q_GLOBAL_STATIC(QSystemDeviceInfoPrivate, deviceInfoPrivate)

#ifdef QT_SIMULATOR
QSystemDeviceInfoPrivate *getSystemDeviceInfoPrivate() { return deviceInfoPrivate(); }
#endif

// device
        /*!
        \class QSystemDeviceInfo
        \ingroup systeminfo
        \inmodule QtSystemInfo
        \brief The QSystemDeviceInfo class provides access to device information from the system.
        */

        /*!
        \fn QSystemDeviceInfo::QSystemDeviceInfo(QObject *parent)

        Constructs a QSystemDeviceInfo with the given \a parent.
        */

        /*!
           \enum QSystemDisplayInfo::DisplayOrientation
          This enum describes the current orientation of the display.

             \value Unknown              Orientation could not be determined.
             \value Landscape            Orientation is in landscape.
             \value Portrait             Orientation is in portrait.
             \value InvertedLandscape    Orientation is landscape inverted.
             \value InvertedPortrait     Orientation is portrait inverted.
        */

        /*!
          \fn void QSystemDeviceInfo::batteryLevelChanged(int level)

          This signal is emitted when battery level has changed.
          \a level is the new level.
         */

        /*!
          \fn void QSystemDeviceInfo::batteryStatusChanged(QSystemDeviceInfo::BatteryStatus status)

          This signal is emitted when battery status has changed.
          \a status is the new status.
         */

           /*!
          \fn void QSystemDeviceInfo::powerStateChanged(QSystemDeviceInfo::PowerState state)

          This signal is emitted when the power state has changed, such as when a phone gets plugged in to the wall.
          \a state is the new power state.
         */

        /*!
          \fn  void QSystemDeviceInfo::currentProfileChanged(QSystemDeviceInfo::Profile profile)

          This signal is emitted whenever the users active profile changes, specified by \a profile.
        */

        /*!
            \enum QSystemDeviceInfo::BatteryStatus
            This enum describes the status of the main battery.

            \value NoBatteryLevel          Battery level undetermined.
            \value BatteryCritical         Battery level is critical 3% or less.
            \value BatteryVeryLow          Battery level is very low, 10% or less.
            \value BatteryLow              Battery level is low 40% or less.
            \value BatteryNormal           Battery level is above 40%.

          */
        /*!
            \enum QSystemDeviceInfo::PowerState
            This enum describes the power state:

            \value UnknownPower                   Power error.
            \value BatteryPower                   On battery power.
            \value WallPower                      On wall power.
            \value WallPowerChargingBattery       On wall power and charging main battery.

          */
        /*!
            \enum QSystemDeviceInfo::Profile
            This enum describes the current operating profile of the device or computer.

            \value UnknownProfile          Profile unknown or error.
            \value SilentProfile           Silent profile.
            \value NormalProfile           Normal profile.
            \value LoudProfile             Loud profile.
            \value VibProfile              Vibrate profile.
            \value OfflineProfile          Offline profile.
            \value PowersaveProfile        Powersave profile.
            \value CustomProfile           Custom profile.

          */

        /*!
            \enum QSystemDeviceInfo::SimStatus
            This enum describes the status is the sim card or cards.

            \value SimNotAvailable         SIM is not available on this device.
            \value SingleSimAvailable         One SIM card is available on this.
            \value DualSimAvailable           Two SIM cards are available on this device.
            \value SimLocked                  Device has SIM lock enabled.
        */

        /*!
            \enum QSystemDeviceInfo::InputMethod
            This enum describes the device method of user input.

            \value Keys               Device has key/buttons.
            \value Keypad             Device has keypad (1,2,3, etc).
            \value Keyboard           Device has qwerty keyboard.
            \value SingleTouch        Device has single touch screen.
            \value MultiTouch         Device has muti touch screen.
            \value Mouse              Device has a mouse.
        */
        /*!
          \fn void QSystemDeviceInfo::bluetoothStateChanged(bool on)

          This signal is emitted whenever bluetooth state changes, specified by \a on.
        */

QSystemDeviceInfo::QSystemDeviceInfo(QObject *parent)
    : QObject(parent), d(deviceInfoPrivate())
{
    qRegisterMetaType<QSystemDeviceInfo::BatteryStatus>("QSystemDeviceInfo::BatteryStatus");
    qRegisterMetaType<QSystemDeviceInfo::PowerState>("QSystemDeviceInfo::PowerState");
    qRegisterMetaType<QSystemDeviceInfo::SimStatus>("QSystemDeviceInfo::SimStatus");
    qRegisterMetaType<QSystemDeviceInfo::Profile>("QSystemDeviceInfo::Profile");
    qRegisterMetaType<QSystemDeviceInfo::InputMethodFlags>("QSystemDeviceInfo::InputMethodFlags");

    connect(d,SIGNAL(batteryLevelChanged(int)),
            this,SIGNAL(batteryLevelChanged(int)));

    connect(d,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),
            this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)));

    connect(d,SIGNAL(bluetoothStateChanged(bool)),
            this,SIGNAL(bluetoothStateChanged(bool)));

    connect(d,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),
            this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)));

    connect(d,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),
            this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)));
    }

/*!
  Destroys the QSystemDeviceInfo object.
 */
QSystemDeviceInfo::~QSystemDeviceInfo()
{
}

/*!
    \internal

    This function is called when the client connects to signals.

    \sa connectNotify()
*/

void QSystemDeviceInfo::connectNotify(const char *signal)
{
    Q_UNUSED(signal);
}

/*!
    \internal

    This function is called when the client disconnects from the signals.

    \sa connectNotify()
*/
void QSystemDeviceInfo::disconnectNotify(const char *signal)
{
    if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
            batteryLevelChanged(int))))) {
        disconnect(d,SIGNAL(batteryLevelChanged(int)),
                this,SIGNAL(batteryLevelChanged(int)));
    }
    if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
            batteryStatusChanged(QSystemDeviceInfo::BatteryStatus))))) {
        disconnect(d,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),
                this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)));
    }
    if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
            bluetoothStateChanged(bool))))) {
        disconnect(d,SIGNAL(bluetoothStateChanged(bool)),
                this,SIGNAL(bluetoothStateChanged(bool)));
    }
    if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
            currentProfileChanged(QSystemDeviceInfo::Profile))))) {
        disconnect(d,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),
                this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)));
    }
    if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
            powerStateChanged(QSystemDeviceInfo::PowerState))))) {
        disconnect(d,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),
                this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)));
    }
}

/*!
  \property QSystemDeviceInfo::inputMethodType
  \brief The supported inputmethods.

    Returns the QSystemDeviceInfo::InputMethodFlags InputMethodType that the system uses.
*/
QSystemDeviceInfo::InputMethodFlags QSystemDeviceInfo::inputMethodType()
{
 return deviceInfoPrivate()->inputMethodType();
}

/*!
  \property QSystemDeviceInfo::imei
  \brief The IMEI.

    Returns the International Mobile Equipment Identity (IMEI), or a null QString in the case of none.
*/
QString QSystemDeviceInfo::imei()
{
    return deviceInfoPrivate()->imei();
}

/*!
  \property QSystemDeviceInfo::imsi
  \brief The IMSI.

    Returns the International Mobile Subscriber Identity (IMSI), or a null QString in the case of none.
*/
QString QSystemDeviceInfo::imsi()
{
    return deviceInfoPrivate()->imsi();
}

/*!
  \property QSystemDeviceInfo::manufacturer
  \brief The manufacture's name.

    Returns the name of the manufacturer of this device. In the case of desktops, the name of the vendor
    of the motherboard.
*/
QString QSystemDeviceInfo::manufacturer()
{
    return deviceInfoPrivate()->manufacturer();
}

/*!
  \property QSystemDeviceInfo::model
  \brief The model name.

    Returns the model information of the device. In the case of desktops where no
    model information is present, the CPU architect, such as i686, and machine type, such as Server,
    Desktop or Laptop.
*/
QString QSystemDeviceInfo::model()
{
    return deviceInfoPrivate()->model();
}

/*!
  \property QSystemDeviceInfo::productName
  \brief The product name.

    Returns the product name of the device. In the case where no product information is available,

*/
QString QSystemDeviceInfo::productName()
{
    return deviceInfoPrivate()->productName();
}
/*!
  \property  QSystemDeviceInfo::batteryLevel
  \brief The battery level.

    Returns the battery charge level as percentage 1 - 100 scale.
*/
int QSystemDeviceInfo::batteryLevel() const
{
    return deviceInfoPrivate()->batteryLevel();
}

  /*!
    \property QSystemDeviceInfo::batteryStatus
    \brief The battery status.

    Returns the battery charge status.
*/
QSystemDeviceInfo::BatteryStatus QSystemDeviceInfo::batteryStatus()
{
   int level = batteryLevel();
    if(level < 4) {
        return QSystemDeviceInfo::BatteryCritical;
    }   else if(level < 11) {
        return QSystemDeviceInfo::BatteryVeryLow;
    }  else if(level < 41) {
        return QSystemDeviceInfo::BatteryLow;
    }   else if(level > 40) {
        return QSystemDeviceInfo::BatteryNormal;
    }

    return QSystemDeviceInfo::NoBatteryLevel;
}

/*!
  \property QSystemDeviceInfo::simStatus
  \brief the status of the sim card.
  Returns the QSystemDeviceInfo::simStatus status of SIM card.
*/
QSystemDeviceInfo::SimStatus QSystemDeviceInfo::simStatus()
{
    return deviceInfoPrivate()->simStatus();
}
/*!
  \property QSystemDeviceInfo::isDeviceLocked
  \brief Device lock.

  Returns true if the device is locked, otherwise false.
*/
bool QSystemDeviceInfo::isDeviceLocked()
{
    return deviceInfoPrivate()->isDeviceLocked();
}

/*!
  \property QSystemDeviceInfo::currentProfile
  \brief the device profile
  Gets the current QSystemDeviceInfo::currentProfile device profile.
*/
QSystemDeviceInfo::Profile QSystemDeviceInfo::currentProfile()
{
    return deviceInfoPrivate()->currentProfile();
}

/*!
  \property QSystemDeviceInfo::currentPowerState
  \brief the power state.

  Gets the current QSystemDeviceInfo::currentPowerState state.
*/
QSystemDeviceInfo::PowerState QSystemDeviceInfo::currentPowerState()
{
    return deviceInfoPrivate()->currentPowerState();
}

/*!
 \property QSystemDeviceInfo::currentBluetoothPowerState
 \brief bluetooth power state.

 Gets the current bluetooth power state.
 */
bool QSystemDeviceInfo::currentBluetoothPowerState()
{
    return deviceInfoPrivate()->currentBluetoothPowerState();
}

#include "moc_qsystemdeviceinfo.cpp"

QTM_END_NAMESPACE

<|endoftext|>