From d5e4f7b6e91d1afbe0af12a8a33fad086b712836 Mon Sep 17 00:00:00 2001 From: Bertrand Songis Date: Wed, 23 Nov 2016 16:42:24 +0100 Subject: [PATCH] [Companion] Unix format used everywhere --- companion/src/eepromimportexport.h | 1454 ++++++++--------- companion/src/generaledit/generaledit.h | 108 +- companion/src/mainwindow.h | 480 +++--- companion/src/mdichild.h | 170 +- companion/src/modeledit/channels.h | 90 +- companion/src/modeledit/curves.h | 136 +- companion/src/modeledit/customfunctions.h | 152 +- companion/src/modeledit/edge.cpp | 178 +- companion/src/modeledit/edge.h | 68 +- companion/src/modeledit/flightmodes.h | 166 +- companion/src/modeledit/heli.h | 46 +- companion/src/modeledit/inputs.h | 104 +- companion/src/modeledit/logicalswitches.h | 96 +- companion/src/modeledit/mixerslist.cpp | 278 ++-- companion/src/modeledit/mixerslist.h | 100 +- companion/src/modeledit/mixes.h | 118 +- companion/src/modeledit/modeledit.h | 102 +- companion/src/modeledit/node.cpp | 416 ++--- companion/src/modeledit/node.h | 136 +- companion/src/modeledit/setup.h | 246 +-- companion/src/modeledit/telemetry.h | 286 ++-- companion/src/modeledit/templates.h | 40 +- companion/src/modelslist.cpp | 1060 ++++++------ companion/src/modelslist.h | 132 +- companion/src/shared/genericpanel.cpp | 208 +-- companion/src/shared/genericpanel.h | 86 +- companion/src/shared/hexspinbox.cpp | 54 +- companion/src/shared/hexspinbox.h | 42 +- companion/src/shared/verticalscrollarea.cpp | 44 +- companion/src/shared/verticalscrollarea.h | 36 +- companion/src/simulation/simulatordialog.cpp | 1524 +++++++++--------- companion/src/simulation/simulatordialog.h | 506 +++--- 32 files changed, 4331 insertions(+), 4331 deletions(-) diff --git a/companion/src/eepromimportexport.h b/companion/src/eepromimportexport.h index 76285490e..97a10d3db 100644 --- a/companion/src/eepromimportexport.h +++ b/companion/src/eepromimportexport.h @@ -20,731 +20,731 @@ #ifndef _EEPROMIMPORTEXPORT_H_ #define _EEPROMIMPORTEXPORT_H_ - -#include "customdebug.h" - -#define DIM(arr) (sizeof((arr))/sizeof((arr)[0])) - -class DataField { - public: - DataField(const char *name=""): - name(name) - { - } - virtual const char *getName() { return name; } - virtual ~DataField() { } - virtual void ExportBits(QBitArray & output) = 0; - virtual void ImportBits(const QBitArray & input) = 0; - virtual unsigned int size() = 0; - - QBitArray bytesToBits(QByteArray bytes) - { - QBitArray bits(bytes.count()*8); - // Convert from QByteArray to QBitArray - for (int i=0; i -class BaseUnsignedField: public DataField { - public: - explicit BaseUnsignedField(container & field): - DataField("Unsigned"), - field(field), - min(0), - max(std::numeric_limits::max()) - { - } - - BaseUnsignedField(container & field, const char * name): - DataField(name), - field(field), - min(0), - max(std::numeric_limits::max()) - { - } - - BaseUnsignedField(container & field, container min, container max, const char * name="Unsigned"): - DataField(name), - field(field), - min(min), - max(max) - { - } - - virtual void ExportBits(QBitArray & output) - { - container value = field; - if (value > max) value = max; - if (value < min) value = min; - - output.resize(N); - for (int i=0; i: 0x%3(%4)").arg(name).arg(N).arg(field, 0, 16).arg(field); - } - - virtual unsigned int size() - { - return N; - } - - protected: - container & field; - container min; - container max; - - private: - BaseUnsignedField(); -}; - -template -class UnsignedField : public BaseUnsignedField -{ - public: - explicit UnsignedField(unsigned int & field): - BaseUnsignedField(field) - { - } - - UnsignedField(unsigned int & field, const char *name): - BaseUnsignedField(field, name) - { - } - - UnsignedField(unsigned int & field, unsigned int min, unsigned int max, const char *name="Unsigned"): - BaseUnsignedField(field, min, max, name) - { - } -}; - -template -class BoolField: public DataField { - public: - explicit BoolField(bool & field): - DataField("Bool"), - field(field) - { - } - - virtual void ExportBits(QBitArray & output) - { - output.resize(N); - if (field) { - output.setBit(0); - } - } - - virtual void ImportBits(const QBitArray & input) - { - field = input[0] ? true : false; - eepromImportDebug() << QString("\timported %1<%2>: 0x%3(%4)").arg(name).arg(N).arg(field, 0, 16).arg(field); - } - - virtual unsigned int size() - { - return N; - } - - protected: - bool & field; - - private: - BoolField(); -}; - -template -class SignedField: public DataField { - public: - SignedField(int & field): - DataField("Signed"), - field(field), - min(INT_MIN), - max(INT_MAX) - { - } - - SignedField(int & field, const char *name): - DataField(name), - field(field), - min(INT_MIN), - max(INT_MAX) - { - } - - SignedField(int & field, int min, int max, const char *name="Signed"): - DataField(name), - field(field), - min(min), - max(max) - { - } - - virtual void ExportBits(QBitArray & output) - { - int value = field; - if (value > max) value = max; - if (value < min) value = min; - - output.resize(N); - for (int i=0; i: 0x%3(%4)").arg(name).arg(N).arg(field, 0, 16).arg(field); - } - - virtual unsigned int size() - { - return N; - } - - protected: - int & field; - int min; - int max; -}; - -template -class SpareBitsField: public UnsignedField { - public: - SpareBitsField(): - UnsignedField(spare, 0, 0, "Spare"), - spare(0) - { - } - protected: - unsigned int spare; -}; - -template -class CharField: public DataField { - public: - CharField(char *field, bool truncate=true): - DataField("Char"), - field(field), - truncate(truncate) - { - } - - virtual void ExportBits(QBitArray & output) - { - output.resize(N*8); - int b = 0; - int len = truncate ? strlen(field) : N; - for (int i=0; i=len ? 0 : field[i]); - for (int j=0; j<8; j++, b++) { - if (idx & (1<: '%3'").arg(name).arg(N).arg(field); - } - - virtual unsigned int size() - { - return 8*N; - } - - protected: - char * field; - bool truncate; -}; - -int8_t char2idx(char c); -char idx2char(int8_t idx); - -template -class ZCharField: public DataField { - public: - ZCharField(char *field): - DataField("ZChar"), - field(field) - { - } - - virtual void ExportBits(QBitArray & output) - { - output.resize(N*8); - int b = 0; - int len = strlen(field); - for (int i=0; i=len ? 0 : char2idx(field[i]); - for (int j=0; j<8; j++, b++) { - if (idx & (1<=0; i--) { - if (field[i] == ' ') - field[i] = '\0'; - else - break; - } - eepromImportDebug() << QString("\timported %1<%2>: '%3'").arg(name).arg(N).arg(field); - } - - virtual unsigned int size() - { - return 8*N; - } - - protected: - char * field; -}; - -class StructField: public DataField { - public: - StructField(const char *name="Struct"): - DataField(name) - { - } - - ~StructField() { - foreach(DataField *field, fields) { - delete field; - } - } - - inline void Append(DataField *field) { - //eepromImportDebug() << QString("StructField(%1) appending field: %2").arg(name).arg(field->getName()); - fields.append(field); - } - - virtual void ExportBits(QBitArray & output) - { - int offset = 0; - output.resize(size()); - foreach(DataField *field, fields) { - QBitArray bits; - field->ExportBits(bits); - for (int i=0; isize(); - QBitArray bits(size); - for (unsigned int i=0; iImportBits(bits); - } - } - - virtual unsigned int size() - { - unsigned int result = 0; - foreach(DataField *field, fields) { - result += field->size(); - } - return result; - } - - virtual int Dump(int level=0, int offset=0) - { - for (int i=0; iDump(level+1, offset); - } - return offset; - } - - protected: - QList fields; -}; - -class TransformedField: public DataField { - public: - TransformedField(DataField & field): - DataField(), - field(field) - { - } - - virtual ~TransformedField() - { - } - - virtual void ExportBits(QBitArray & output) - { - beforeExport(); - field.ExportBits(output); - } - - virtual void ImportBits(const QBitArray & input) - { - eepromImportDebug() << QString("\timporting TransformedField %1:").arg(field.getName()); - field.ImportBits(input); - afterImport(); - } - - - virtual const char *getName() - { - return field.getName(); - } - - virtual unsigned int size() - { - return field.size(); - } - - virtual void beforeExport() = 0; - - virtual void afterImport() = 0; - - virtual int Dump(int level=0, int offset=0) - { - beforeExport(); - return field.Dump(level, offset); - } - - protected: - DataField & field; -}; - -class ConversionTable { - - public: - bool exportValue(const int before, int &after) - { - after = 0; - - for (std::list::iterator it=exportTable.begin(); it!=exportTable.end(); it++) { - ConversionTuple tuple = *it; - if (before == tuple.a) { - after = tuple.b; - return true; - } - } - - return false; - } - - bool importValue(const int before, int &after) - { - after = 0; - - for (std::list::iterator it=importTable.begin(); it!=importTable.end(); it++) { - ConversionTuple tuple = *it; - if (before == tuple.b) { - after = tuple.a; - return true; - } - } - - return false; - } - - protected: - - class ConversionTuple { - public: - ConversionTuple(const int a, const int b): - a(a), - b(b) - { - } - - int a; - int b; - }; - - void addConversion(const int a, const int b) - { - ConversionTuple conversion(a, b); - importTable.push_back(conversion); - exportTable.push_back(conversion); - } - - void addImportConversion(const int a, const int b) - { - importTable.push_back(ConversionTuple(a, b)); - } - - void addExportConversion(const int a, const int b) - { - exportTable.push_back(ConversionTuple(a, b)); - } - - std::list importTable; - std::list exportTable; -}; - -template -class ConversionField: public TransformedField { - public: - ConversionField(int & field, ConversionTable *table, const char *name, const QString & error = ""): - TransformedField(internalField), - internalField(_field, name), - field(field), - _field(0), - table(table), - shift(0), - scale(1), - min(INT_MIN), - max(INT_MAX), - exportFunc(NULL), - importFunc(NULL), - error(error) - { - } - - ConversionField(unsigned int & field, ConversionTable *table, const char *name, const QString & error = ""): - TransformedField(internalField), - internalField((unsigned int &)_field, name), - field((int &)field), - _field(0), - table(table), - shift(0), - scale(0), - min(INT_MIN), - max(INT_MAX), - exportFunc(NULL), - importFunc(NULL), - error(error) - { - } - - ConversionField(int & field, int (*exportFunc)(int), int (*importFunc)(int)): - TransformedField(internalField), - internalField(_field), - field(field), - _field(0), - table(NULL), - shift(0), - scale(0), - min(INT_MIN), - max(INT_MAX), - exportFunc(exportFunc), - importFunc(importFunc), - error("") - { - } - - ConversionField(int & field, int shift, int scale=0, int min=INT_MIN, int max=INT_MAX, const char *name = "Signed shifted"): - TransformedField(internalField), - internalField(_field, name), - field(field), - _field(0), - table(NULL), - shift(shift), - scale(scale), - min(min), - max(max), - exportFunc(NULL), - importFunc(NULL), - error("") - { - } - - ConversionField(unsigned int & field, int shift, int scale=0): - TransformedField(internalField), - internalField((unsigned int &)_field), - field((int &)field), - _field(0), - table(NULL), - shift(shift), - scale(scale), - min(INT_MIN), - max(INT_MAX), - exportFunc(NULL), - importFunc(NULL), - error("") - { - } - - virtual void beforeExport() - { - _field = field; - - if (scale) { - _field /= scale; - } - - if (table) { - if (table->exportValue(_field, _field)) - return; - if (!error.isEmpty()) - EEPROMWarnings.push_back(error); - } - - if (shift) { - if (_field < min) _field = min + shift; - else if (_field > max) _field = max + shift; - else _field += shift; - } - - if (exportFunc) { - _field = exportFunc(_field); - } - } - - virtual void afterImport() - { - field = _field; - - if (table) { - if (table->importValue(field, field)) - return; - } - - if (shift) { - field -= shift; - } - - if (importFunc) { - field = importFunc(field); - } - - if (scale) { - field *= scale; - } - eepromImportDebug() << QString("\timported ConversionField<%1>:").arg(internalField.getName()) << QString(" before: %1, after: %2").arg(_field).arg(field); - } - - protected: - T internalField; - int & field; - int _field; - ConversionTable * table; - int shift; - int scale; - int min; - int max; - int (*exportFunc)(int); - int (*importFunc)(int); - const QString error; -}; - + +#include "customdebug.h" + +#define DIM(arr) (sizeof((arr))/sizeof((arr)[0])) + +class DataField { + public: + DataField(const char *name=""): + name(name) + { + } + virtual const char *getName() { return name; } + virtual ~DataField() { } + virtual void ExportBits(QBitArray & output) = 0; + virtual void ImportBits(const QBitArray & input) = 0; + virtual unsigned int size() = 0; + + QBitArray bytesToBits(QByteArray bytes) + { + QBitArray bits(bytes.count()*8); + // Convert from QByteArray to QBitArray + for (int i=0; i +class BaseUnsignedField: public DataField { + public: + explicit BaseUnsignedField(container & field): + DataField("Unsigned"), + field(field), + min(0), + max(std::numeric_limits::max()) + { + } + + BaseUnsignedField(container & field, const char * name): + DataField(name), + field(field), + min(0), + max(std::numeric_limits::max()) + { + } + + BaseUnsignedField(container & field, container min, container max, const char * name="Unsigned"): + DataField(name), + field(field), + min(min), + max(max) + { + } + + virtual void ExportBits(QBitArray & output) + { + container value = field; + if (value > max) value = max; + if (value < min) value = min; + + output.resize(N); + for (int i=0; i: 0x%3(%4)").arg(name).arg(N).arg(field, 0, 16).arg(field); + } + + virtual unsigned int size() + { + return N; + } + + protected: + container & field; + container min; + container max; + + private: + BaseUnsignedField(); +}; + +template +class UnsignedField : public BaseUnsignedField +{ + public: + explicit UnsignedField(unsigned int & field): + BaseUnsignedField(field) + { + } + + UnsignedField(unsigned int & field, const char *name): + BaseUnsignedField(field, name) + { + } + + UnsignedField(unsigned int & field, unsigned int min, unsigned int max, const char *name="Unsigned"): + BaseUnsignedField(field, min, max, name) + { + } +}; + +template +class BoolField: public DataField { + public: + explicit BoolField(bool & field): + DataField("Bool"), + field(field) + { + } + + virtual void ExportBits(QBitArray & output) + { + output.resize(N); + if (field) { + output.setBit(0); + } + } + + virtual void ImportBits(const QBitArray & input) + { + field = input[0] ? true : false; + eepromImportDebug() << QString("\timported %1<%2>: 0x%3(%4)").arg(name).arg(N).arg(field, 0, 16).arg(field); + } + + virtual unsigned int size() + { + return N; + } + + protected: + bool & field; + + private: + BoolField(); +}; + +template +class SignedField: public DataField { + public: + SignedField(int & field): + DataField("Signed"), + field(field), + min(INT_MIN), + max(INT_MAX) + { + } + + SignedField(int & field, const char *name): + DataField(name), + field(field), + min(INT_MIN), + max(INT_MAX) + { + } + + SignedField(int & field, int min, int max, const char *name="Signed"): + DataField(name), + field(field), + min(min), + max(max) + { + } + + virtual void ExportBits(QBitArray & output) + { + int value = field; + if (value > max) value = max; + if (value < min) value = min; + + output.resize(N); + for (int i=0; i: 0x%3(%4)").arg(name).arg(N).arg(field, 0, 16).arg(field); + } + + virtual unsigned int size() + { + return N; + } + + protected: + int & field; + int min; + int max; +}; + +template +class SpareBitsField: public UnsignedField { + public: + SpareBitsField(): + UnsignedField(spare, 0, 0, "Spare"), + spare(0) + { + } + protected: + unsigned int spare; +}; + +template +class CharField: public DataField { + public: + CharField(char *field, bool truncate=true): + DataField("Char"), + field(field), + truncate(truncate) + { + } + + virtual void ExportBits(QBitArray & output) + { + output.resize(N*8); + int b = 0; + int len = truncate ? strlen(field) : N; + for (int i=0; i=len ? 0 : field[i]); + for (int j=0; j<8; j++, b++) { + if (idx & (1<: '%3'").arg(name).arg(N).arg(field); + } + + virtual unsigned int size() + { + return 8*N; + } + + protected: + char * field; + bool truncate; +}; + +int8_t char2idx(char c); +char idx2char(int8_t idx); + +template +class ZCharField: public DataField { + public: + ZCharField(char *field): + DataField("ZChar"), + field(field) + { + } + + virtual void ExportBits(QBitArray & output) + { + output.resize(N*8); + int b = 0; + int len = strlen(field); + for (int i=0; i=len ? 0 : char2idx(field[i]); + for (int j=0; j<8; j++, b++) { + if (idx & (1<=0; i--) { + if (field[i] == ' ') + field[i] = '\0'; + else + break; + } + eepromImportDebug() << QString("\timported %1<%2>: '%3'").arg(name).arg(N).arg(field); + } + + virtual unsigned int size() + { + return 8*N; + } + + protected: + char * field; +}; + +class StructField: public DataField { + public: + StructField(const char *name="Struct"): + DataField(name) + { + } + + ~StructField() { + foreach(DataField *field, fields) { + delete field; + } + } + + inline void Append(DataField *field) { + //eepromImportDebug() << QString("StructField(%1) appending field: %2").arg(name).arg(field->getName()); + fields.append(field); + } + + virtual void ExportBits(QBitArray & output) + { + int offset = 0; + output.resize(size()); + foreach(DataField *field, fields) { + QBitArray bits; + field->ExportBits(bits); + for (int i=0; isize(); + QBitArray bits(size); + for (unsigned int i=0; iImportBits(bits); + } + } + + virtual unsigned int size() + { + unsigned int result = 0; + foreach(DataField *field, fields) { + result += field->size(); + } + return result; + } + + virtual int Dump(int level=0, int offset=0) + { + for (int i=0; iDump(level+1, offset); + } + return offset; + } + + protected: + QList fields; +}; + +class TransformedField: public DataField { + public: + TransformedField(DataField & field): + DataField(), + field(field) + { + } + + virtual ~TransformedField() + { + } + + virtual void ExportBits(QBitArray & output) + { + beforeExport(); + field.ExportBits(output); + } + + virtual void ImportBits(const QBitArray & input) + { + eepromImportDebug() << QString("\timporting TransformedField %1:").arg(field.getName()); + field.ImportBits(input); + afterImport(); + } + + + virtual const char *getName() + { + return field.getName(); + } + + virtual unsigned int size() + { + return field.size(); + } + + virtual void beforeExport() = 0; + + virtual void afterImport() = 0; + + virtual int Dump(int level=0, int offset=0) + { + beforeExport(); + return field.Dump(level, offset); + } + + protected: + DataField & field; +}; + +class ConversionTable { + + public: + bool exportValue(const int before, int &after) + { + after = 0; + + for (std::list::iterator it=exportTable.begin(); it!=exportTable.end(); it++) { + ConversionTuple tuple = *it; + if (before == tuple.a) { + after = tuple.b; + return true; + } + } + + return false; + } + + bool importValue(const int before, int &after) + { + after = 0; + + for (std::list::iterator it=importTable.begin(); it!=importTable.end(); it++) { + ConversionTuple tuple = *it; + if (before == tuple.b) { + after = tuple.a; + return true; + } + } + + return false; + } + + protected: + + class ConversionTuple { + public: + ConversionTuple(const int a, const int b): + a(a), + b(b) + { + } + + int a; + int b; + }; + + void addConversion(const int a, const int b) + { + ConversionTuple conversion(a, b); + importTable.push_back(conversion); + exportTable.push_back(conversion); + } + + void addImportConversion(const int a, const int b) + { + importTable.push_back(ConversionTuple(a, b)); + } + + void addExportConversion(const int a, const int b) + { + exportTable.push_back(ConversionTuple(a, b)); + } + + std::list importTable; + std::list exportTable; +}; + +template +class ConversionField: public TransformedField { + public: + ConversionField(int & field, ConversionTable *table, const char *name, const QString & error = ""): + TransformedField(internalField), + internalField(_field, name), + field(field), + _field(0), + table(table), + shift(0), + scale(1), + min(INT_MIN), + max(INT_MAX), + exportFunc(NULL), + importFunc(NULL), + error(error) + { + } + + ConversionField(unsigned int & field, ConversionTable *table, const char *name, const QString & error = ""): + TransformedField(internalField), + internalField((unsigned int &)_field, name), + field((int &)field), + _field(0), + table(table), + shift(0), + scale(0), + min(INT_MIN), + max(INT_MAX), + exportFunc(NULL), + importFunc(NULL), + error(error) + { + } + + ConversionField(int & field, int (*exportFunc)(int), int (*importFunc)(int)): + TransformedField(internalField), + internalField(_field), + field(field), + _field(0), + table(NULL), + shift(0), + scale(0), + min(INT_MIN), + max(INT_MAX), + exportFunc(exportFunc), + importFunc(importFunc), + error("") + { + } + + ConversionField(int & field, int shift, int scale=0, int min=INT_MIN, int max=INT_MAX, const char *name = "Signed shifted"): + TransformedField(internalField), + internalField(_field, name), + field(field), + _field(0), + table(NULL), + shift(shift), + scale(scale), + min(min), + max(max), + exportFunc(NULL), + importFunc(NULL), + error("") + { + } + + ConversionField(unsigned int & field, int shift, int scale=0): + TransformedField(internalField), + internalField((unsigned int &)_field), + field((int &)field), + _field(0), + table(NULL), + shift(shift), + scale(scale), + min(INT_MIN), + max(INT_MAX), + exportFunc(NULL), + importFunc(NULL), + error("") + { + } + + virtual void beforeExport() + { + _field = field; + + if (scale) { + _field /= scale; + } + + if (table) { + if (table->exportValue(_field, _field)) + return; + if (!error.isEmpty()) + EEPROMWarnings.push_back(error); + } + + if (shift) { + if (_field < min) _field = min + shift; + else if (_field > max) _field = max + shift; + else _field += shift; + } + + if (exportFunc) { + _field = exportFunc(_field); + } + } + + virtual void afterImport() + { + field = _field; + + if (table) { + if (table->importValue(field, field)) + return; + } + + if (shift) { + field -= shift; + } + + if (importFunc) { + field = importFunc(field); + } + + if (scale) { + field *= scale; + } + eepromImportDebug() << QString("\timported ConversionField<%1>:").arg(internalField.getName()) << QString(" before: %1, after: %2").arg(_field).arg(field); + } + + protected: + T internalField; + int & field; + int _field; + ConversionTable * table; + int shift; + int scale; + int min; + int max; + int (*exportFunc)(int); + int (*importFunc)(int); + const QString error; +}; + #endif // _EEPROMIMPORTEXPORT_H_ diff --git a/companion/src/generaledit/generaledit.h b/companion/src/generaledit/generaledit.h index baf0e4e42..1c1d096a5 100644 --- a/companion/src/generaledit/generaledit.h +++ b/companion/src/generaledit/generaledit.h @@ -20,58 +20,58 @@ #ifndef _GENERALEDIT_H_ #define _GENERALEDIT_H_ - -#include -#include "eeprominterface.h" -#include "genericpanel.h" - -namespace Ui { - class GeneralEdit; -} - -class GeneralPanel : public GenericPanel -{ - public: - GeneralPanel(QWidget *parent, GeneralSettings & generalSettings, Firmware * firmware): - GenericPanel(parent, NULL, generalSettings, firmware) - { - } -}; - -class GeneralEdit : public QDialog -{ - Q_OBJECT - - public: - GeneralEdit(QWidget * parent, RadioData & radioData, Firmware * firmware); - ~GeneralEdit(); - - private: - Ui::GeneralEdit *ui; - GeneralSettings & generalSettings; - - bool switchDefPosEditLock; - bool voiceLangEditLock; - bool mavbaudEditLock; - void getGeneralSwitchDefPos(int i, bool val); - void setSwitchDefPos(); - void updateVarioPitchRange(); - - signals: - void modified(); - - private slots: - void onTabModified(); - void on_tabWidget_currentChanged(int index); - void on_calretrieve_PB_clicked(); - void on_calstore_PB_clicked(); - - private: - Firmware * firmware; - QVector panels; - void addTab(GenericPanel *panel, QString text); - void closeEvent(QCloseEvent *event); - -}; - + +#include +#include "eeprominterface.h" +#include "genericpanel.h" + +namespace Ui { + class GeneralEdit; +} + +class GeneralPanel : public GenericPanel +{ + public: + GeneralPanel(QWidget *parent, GeneralSettings & generalSettings, Firmware * firmware): + GenericPanel(parent, NULL, generalSettings, firmware) + { + } +}; + +class GeneralEdit : public QDialog +{ + Q_OBJECT + + public: + GeneralEdit(QWidget * parent, RadioData & radioData, Firmware * firmware); + ~GeneralEdit(); + + private: + Ui::GeneralEdit *ui; + GeneralSettings & generalSettings; + + bool switchDefPosEditLock; + bool voiceLangEditLock; + bool mavbaudEditLock; + void getGeneralSwitchDefPos(int i, bool val); + void setSwitchDefPos(); + void updateVarioPitchRange(); + + signals: + void modified(); + + private slots: + void onTabModified(); + void on_tabWidget_currentChanged(int index); + void on_calretrieve_PB_clicked(); + void on_calstore_PB_clicked(); + + private: + Firmware * firmware; + QVector panels; + void addTab(GenericPanel *panel, QString text); + void closeEvent(QCloseEvent *event); + +}; + #endif // _GENERALEDIT_H_ diff --git a/companion/src/mainwindow.h b/companion/src/mainwindow.h index fe2787e1e..14a69295b 100644 --- a/companion/src/mainwindow.h +++ b/companion/src/mainwindow.h @@ -20,244 +20,244 @@ #ifndef _MAINWINDOW_H_ #define _MAINWINDOW_H_ - -#include -#include -#include "downloaddialog.h" -#include "eeprominterface.h" - -#define SPLASH_TIME 5 -#define MAX_RECENT 15 -#define MAX_PROFILES 15 - -class MdiChild; -QT_BEGIN_NAMESPACE -class QAction; -class QMenu; -class QMdiArea; -class QMdiSubWindow; -class QSignalMapper; -QT_END_NAMESPACE - -#define CHECK_COMPANION 1 -#define CHECK_FIRMWARE 2 -#define SHOW_DIALOG_WAIT 4 -#define AUTOMATIC_DOWNLOAD 8 - -class MainWindow : public QMainWindow -{ - friend class FirmwarePreferencesDialog; - - Q_OBJECT - - public: - MainWindow(); - - protected: - QString getCompanionUpdateBaseUrl(); - void dowloadLastFirmwareUpdate(); - void startFirmwareDownload(); - void closeEvent(QCloseEvent *event); - void dragEnterEvent(QDragEnterEvent *event); - void dropEvent(QDropEvent *event); - void setLanguage(const QString & langString); - QString seekCodeString(const QByteArray & qba, const QString & label); - - private slots: - void openDocURL(); - - void setSysLanguage() { setLanguage(""); }; - void setCZLanguage() { setLanguage("cs_CZ"); }; - void setDELanguage() { setLanguage("de_DE"); }; - void setENLanguage() { setLanguage("en"); }; - void setFILanguage() { setLanguage("fi_FI"); }; - void setFRLanguage() { setLanguage("fr_FR"); }; - void setITLanguage() { setLanguage("it_IT"); }; - void setHELanguage() { setLanguage("he_IL"); }; - void setPLLanguage() { setLanguage("pl_PL"); }; - void setESLanguage() { setLanguage("es_ES"); }; - void setPTLanguage() { setLanguage("pt_PT"); }; - void setRULanguage() { setLanguage("ru_RU"); }; - void setSELanguage() { setLanguage("sv_SE"); }; - void setNLLanguage() { setLanguage("nl_NL"); }; - - void setTheme(int index); - void setClassicTheme() {setTheme(0);}; - void setYericoTheme() {setTheme(1);}; - void setMonoWhiteTheme() {setTheme(2);}; - void setMonochromeTheme(){setTheme(3);}; - void setMonoBlueTheme() {setTheme(4);}; - - void setIconThemeSize(int index); - void setSmallIconThemeSize() {setIconThemeSize(0);}; - void setNormalIconThemeSize() {setIconThemeSize(1);}; - void setBigIconThemeSize() {setIconThemeSize(2);}; - void setHugeIconThemeSize() {setIconThemeSize(3);}; - - void checkForUpdates(); - void checkForFirmwareUpdate(); - - void checkForCompanionUpdateFinished(QNetworkReply * reply); - void checkForFirmwareUpdateFinished(QNetworkReply * reply); - - void displayWarnings(); - void doAutoUpdates(); - void doUpdates(); - void updateDownloaded(); - void firmwareDownloadAccepted(); - void newFile(); - void openFile(); - void save(); - void saveAs(); - void cut(); - void openRecentFile(); - void loadProfile(); - void logFile(); - void copy(); - void paste(); - void writeEeprom(); - void readEeprom(); - void writeFlash(QString fileToFlash=""); - void readFlash(); - void writeBackup(); - void readBackup(); - void burnConfig(); - void burnList(); - void burnFuses(); - void simulate(); - void contributors(); - void sdsync(); - void changelog(); - void fwchangelog(); - void customizeSplash(); - void about(); - void compare(); - void print(); - void loadBackup(); - void appPrefs(); - void fwPrefs(); - void updateMenus(); - void createProfile(); - MdiChild *createMdiChild(); - void setActiveSubWindow(QWidget *window); - QMenu * createRecentFileMenu(); - QMenu * createProfilesMenu(); - void autoClose(); - - private: - void closeUpdatesWaitDialog(); - void onUpdatesError(); - - void createActions(); - QAction * addAct(const QString &, const QString &, const QString &, enum QKeySequence::StandardKey, const char *, QObject *slotObj=NULL); - QAction * addAct(const QString &, const QString &, const QString &, const QKeySequence &, const char *, QObject *slotObj=NULL); - QAction * addAct(QActionGroup *, const QString &, const QString &, const char *); - QAction * addAct(const QString &, const QString &, const QString &, const char *); - - void createMenus(); - void createToolBars(); - void createStatusBar(); - void updateRecentFileActions(); - void updateProfilesActions(); - void updateIconSizeActions(); - void updateLanguageActions(); - void updateIconThemeActions(); - - int getFileType(const QString & fullFileName); - QString Theme; - QString ISize; - QString strippedName(const QString & fullFileName); - - MdiChild *activeMdiChild(); - QMdiSubWindow *findMdiChild(const QString & fileName); - int getEpromVersion(QString fileName); - - bool readEepromFromRadio(const QString & filename); - bool writeEepromToRadio(const QString & filename); - bool readFirmwareFromRadio(const QString & filename); - bool writeFirmwareToRadio(const QString & filename); - - QMdiArea *mdiArea; - QSignalMapper *windowMapper; - - QString installer_fileName; - downloadDialog * downloadDialog_forWait; - unsigned int checkForUpdatesState; - QString firmwareVersionString; - - QNetworkAccessManager *networkManager; - - QMenu *fileMenu; - QMenu *editMenu; - QMenu *settingsMenu; - QMenu *burnMenu; - QMenu *helpMenu; - QToolBar *fileToolBar; - QToolBar *editToolBar; - QToolBar *burnToolBar; - QToolBar *helpToolBar; - QAction *newAct; - QAction *openAct; - QAction *recentAct; - QAction *saveAct; - QAction *saveAsAct; - QAction *exitAct; - QAction *appPrefsAct; - QAction *fwPrefsAct; - QAction *checkForUpdatesAct; - QAction *contributorsAct; - QAction *sdsyncAct; - QAction *changelogAct; - QAction *fwchangelogAct; - QAction *compareAct; - QAction *editSplashAct; - QAction *cutAct; - QAction *copyAct; - QAction *pasteAct; - QAction *writeEepromAct; - QAction *readEepromAct; - QAction *burnConfigAct; - QAction *burnListAct; - QAction *burnFusesAct; - QAction *writeFlashAct; - QAction *readFlashAct; - QAction *writeBackupToRadioAct; - QAction *readBackupToFileAct; - QAction *simulateAct; - QAction *separatorAct; - QAction *aboutAct; - QAction *printAct; - QAction *loadbackupAct; - QAction *logsAct; - QAction *recentFileActs[MAX_RECENT]; - QAction *profileActs[MAX_PROFILES]; - QAction *createProfileAct; - QAction *classicThemeAct; - QAction *yericoThemeAct; - QAction *monoThemeAct; - QAction *monoBlueAct; - QAction *monoWhiteAct; - QAction *smallIconAct; - QAction *normalIconAct; - QAction *bigIconAct; - QAction *hugeIconAct; - - QAction *sysLangAct; - QAction *czechLangAct; - QAction *germanLangAct; - QAction *englishLangAct; - QAction *finnishLangAct; - QAction *frenchLangAct; - QAction *italianLangAct; - // QAction *hebrewLangAct; - QAction *polishLangAct; - // QAction *portugueseLangAct; - QAction *spanishLangAct; - QAction *swedishLangAct; - // QAction *russianLangAct; - // QAction *dutchLangAct; - - QAction *openDocURLAct; -}; - + +#include +#include +#include "downloaddialog.h" +#include "eeprominterface.h" + +#define SPLASH_TIME 5 +#define MAX_RECENT 15 +#define MAX_PROFILES 15 + +class MdiChild; +QT_BEGIN_NAMESPACE +class QAction; +class QMenu; +class QMdiArea; +class QMdiSubWindow; +class QSignalMapper; +QT_END_NAMESPACE + +#define CHECK_COMPANION 1 +#define CHECK_FIRMWARE 2 +#define SHOW_DIALOG_WAIT 4 +#define AUTOMATIC_DOWNLOAD 8 + +class MainWindow : public QMainWindow +{ + friend class FirmwarePreferencesDialog; + + Q_OBJECT + + public: + MainWindow(); + + protected: + QString getCompanionUpdateBaseUrl(); + void dowloadLastFirmwareUpdate(); + void startFirmwareDownload(); + void closeEvent(QCloseEvent *event); + void dragEnterEvent(QDragEnterEvent *event); + void dropEvent(QDropEvent *event); + void setLanguage(const QString & langString); + QString seekCodeString(const QByteArray & qba, const QString & label); + + private slots: + void openDocURL(); + + void setSysLanguage() { setLanguage(""); }; + void setCZLanguage() { setLanguage("cs_CZ"); }; + void setDELanguage() { setLanguage("de_DE"); }; + void setENLanguage() { setLanguage("en"); }; + void setFILanguage() { setLanguage("fi_FI"); }; + void setFRLanguage() { setLanguage("fr_FR"); }; + void setITLanguage() { setLanguage("it_IT"); }; + void setHELanguage() { setLanguage("he_IL"); }; + void setPLLanguage() { setLanguage("pl_PL"); }; + void setESLanguage() { setLanguage("es_ES"); }; + void setPTLanguage() { setLanguage("pt_PT"); }; + void setRULanguage() { setLanguage("ru_RU"); }; + void setSELanguage() { setLanguage("sv_SE"); }; + void setNLLanguage() { setLanguage("nl_NL"); }; + + void setTheme(int index); + void setClassicTheme() {setTheme(0);}; + void setYericoTheme() {setTheme(1);}; + void setMonoWhiteTheme() {setTheme(2);}; + void setMonochromeTheme(){setTheme(3);}; + void setMonoBlueTheme() {setTheme(4);}; + + void setIconThemeSize(int index); + void setSmallIconThemeSize() {setIconThemeSize(0);}; + void setNormalIconThemeSize() {setIconThemeSize(1);}; + void setBigIconThemeSize() {setIconThemeSize(2);}; + void setHugeIconThemeSize() {setIconThemeSize(3);}; + + void checkForUpdates(); + void checkForFirmwareUpdate(); + + void checkForCompanionUpdateFinished(QNetworkReply * reply); + void checkForFirmwareUpdateFinished(QNetworkReply * reply); + + void displayWarnings(); + void doAutoUpdates(); + void doUpdates(); + void updateDownloaded(); + void firmwareDownloadAccepted(); + void newFile(); + void openFile(); + void save(); + void saveAs(); + void cut(); + void openRecentFile(); + void loadProfile(); + void logFile(); + void copy(); + void paste(); + void writeEeprom(); + void readEeprom(); + void writeFlash(QString fileToFlash=""); + void readFlash(); + void writeBackup(); + void readBackup(); + void burnConfig(); + void burnList(); + void burnFuses(); + void simulate(); + void contributors(); + void sdsync(); + void changelog(); + void fwchangelog(); + void customizeSplash(); + void about(); + void compare(); + void print(); + void loadBackup(); + void appPrefs(); + void fwPrefs(); + void updateMenus(); + void createProfile(); + MdiChild *createMdiChild(); + void setActiveSubWindow(QWidget *window); + QMenu * createRecentFileMenu(); + QMenu * createProfilesMenu(); + void autoClose(); + + private: + void closeUpdatesWaitDialog(); + void onUpdatesError(); + + void createActions(); + QAction * addAct(const QString &, const QString &, const QString &, enum QKeySequence::StandardKey, const char *, QObject *slotObj=NULL); + QAction * addAct(const QString &, const QString &, const QString &, const QKeySequence &, const char *, QObject *slotObj=NULL); + QAction * addAct(QActionGroup *, const QString &, const QString &, const char *); + QAction * addAct(const QString &, const QString &, const QString &, const char *); + + void createMenus(); + void createToolBars(); + void createStatusBar(); + void updateRecentFileActions(); + void updateProfilesActions(); + void updateIconSizeActions(); + void updateLanguageActions(); + void updateIconThemeActions(); + + int getFileType(const QString & fullFileName); + QString Theme; + QString ISize; + QString strippedName(const QString & fullFileName); + + MdiChild *activeMdiChild(); + QMdiSubWindow *findMdiChild(const QString & fileName); + int getEpromVersion(QString fileName); + + bool readEepromFromRadio(const QString & filename); + bool writeEepromToRadio(const QString & filename); + bool readFirmwareFromRadio(const QString & filename); + bool writeFirmwareToRadio(const QString & filename); + + QMdiArea *mdiArea; + QSignalMapper *windowMapper; + + QString installer_fileName; + downloadDialog * downloadDialog_forWait; + unsigned int checkForUpdatesState; + QString firmwareVersionString; + + QNetworkAccessManager *networkManager; + + QMenu *fileMenu; + QMenu *editMenu; + QMenu *settingsMenu; + QMenu *burnMenu; + QMenu *helpMenu; + QToolBar *fileToolBar; + QToolBar *editToolBar; + QToolBar *burnToolBar; + QToolBar *helpToolBar; + QAction *newAct; + QAction *openAct; + QAction *recentAct; + QAction *saveAct; + QAction *saveAsAct; + QAction *exitAct; + QAction *appPrefsAct; + QAction *fwPrefsAct; + QAction *checkForUpdatesAct; + QAction *contributorsAct; + QAction *sdsyncAct; + QAction *changelogAct; + QAction *fwchangelogAct; + QAction *compareAct; + QAction *editSplashAct; + QAction *cutAct; + QAction *copyAct; + QAction *pasteAct; + QAction *writeEepromAct; + QAction *readEepromAct; + QAction *burnConfigAct; + QAction *burnListAct; + QAction *burnFusesAct; + QAction *writeFlashAct; + QAction *readFlashAct; + QAction *writeBackupToRadioAct; + QAction *readBackupToFileAct; + QAction *simulateAct; + QAction *separatorAct; + QAction *aboutAct; + QAction *printAct; + QAction *loadbackupAct; + QAction *logsAct; + QAction *recentFileActs[MAX_RECENT]; + QAction *profileActs[MAX_PROFILES]; + QAction *createProfileAct; + QAction *classicThemeAct; + QAction *yericoThemeAct; + QAction *monoThemeAct; + QAction *monoBlueAct; + QAction *monoWhiteAct; + QAction *smallIconAct; + QAction *normalIconAct; + QAction *bigIconAct; + QAction *hugeIconAct; + + QAction *sysLangAct; + QAction *czechLangAct; + QAction *germanLangAct; + QAction *englishLangAct; + QAction *finnishLangAct; + QAction *frenchLangAct; + QAction *italianLangAct; + // QAction *hebrewLangAct; + QAction *polishLangAct; + // QAction *portugueseLangAct; + QAction *spanishLangAct; + QAction *swedishLangAct; + // QAction *russianLangAct; + // QAction *dutchLangAct; + + QAction *openDocURLAct; +}; + #endif // _MAINWINDOW_H_ diff --git a/companion/src/mdichild.h b/companion/src/mdichild.h index b4f8c3807..2bcd0dedc 100644 --- a/companion/src/mdichild.h +++ b/companion/src/mdichild.h @@ -20,89 +20,89 @@ #ifndef _MDICHILD_H_ #define _MDICHILD_H_ - -#include -#include "eeprominterface.h" - -namespace Ui { -class mdiChild; -} -#define ER9X_EEPROM_FILE_TYPE "ER9X_EEPROM_FILE" - -#define EEPE_EEPROM_FILE_HEADER "EEPE EEPROM FILE" -#define EEPE_MODEL_FILE_HEADER "EEPE MODEL FILE" - -class MdiChild : public QWidget -{ - friend class ModelsListWidget; - - Q_OBJECT - - public: - MdiChild(); - ~MdiChild(); - - void newFile(); - bool loadFile(const QString &fileName, bool resetCurrentFile=true); - bool loadBackup(); - bool save(); - bool saveAs(bool isNew=false); - bool saveFile(const QString &fileName, bool setCurrent=true); - bool hasSelection(); - QString userFriendlyCurrentFile(); - QString currentFile() { return curFile; } - // void keyPressEvent(QKeyEvent *event); - bool hasPasteData(); - void viableModelSelected(bool viable); - void eepromInterfaceChanged(); - void setEEpromAvail(int eavail); - int getCurrentRow() const; - - signals: - void copyAvailable(bool val); - - protected: - void closeEvent(QCloseEvent *event); - - private slots: - void documentWasModified(); - void on_SimulateTxButton_clicked(); - void qSleep(int ms); - - public slots: - void checkAndInitModel(int row); - void generalEdit(); - void modelEdit(); - void wizardEdit(); - void openEditWindow(); - - void cut(); - void copy(); - void paste(); - void writeEeprom(); - void simulate(); - void print(int model=-1, QString filename=""); - void setModified(); - void updateTitle(); - - private: - bool maybeSave(); - void setCurrentFile(const QString &fileName); - QString strippedName(const QString &fullFileName); - void saveSelection(); - void restoreSelection(); - bool loadOtxFile(const QString &fileName, bool resetCurrentFile); - - Ui::mdiChild *ui; - - QString curFile; - - Firmware * firmware; - RadioData radioData; - - bool isUntitled; - bool fileChanged; - int EEPromAvail; -}; - + +#include +#include "eeprominterface.h" + +namespace Ui { +class mdiChild; +} +#define ER9X_EEPROM_FILE_TYPE "ER9X_EEPROM_FILE" + +#define EEPE_EEPROM_FILE_HEADER "EEPE EEPROM FILE" +#define EEPE_MODEL_FILE_HEADER "EEPE MODEL FILE" + +class MdiChild : public QWidget +{ + friend class ModelsListWidget; + + Q_OBJECT + + public: + MdiChild(); + ~MdiChild(); + + void newFile(); + bool loadFile(const QString &fileName, bool resetCurrentFile=true); + bool loadBackup(); + bool save(); + bool saveAs(bool isNew=false); + bool saveFile(const QString &fileName, bool setCurrent=true); + bool hasSelection(); + QString userFriendlyCurrentFile(); + QString currentFile() { return curFile; } + // void keyPressEvent(QKeyEvent *event); + bool hasPasteData(); + void viableModelSelected(bool viable); + void eepromInterfaceChanged(); + void setEEpromAvail(int eavail); + int getCurrentRow() const; + + signals: + void copyAvailable(bool val); + + protected: + void closeEvent(QCloseEvent *event); + + private slots: + void documentWasModified(); + void on_SimulateTxButton_clicked(); + void qSleep(int ms); + + public slots: + void checkAndInitModel(int row); + void generalEdit(); + void modelEdit(); + void wizardEdit(); + void openEditWindow(); + + void cut(); + void copy(); + void paste(); + void writeEeprom(); + void simulate(); + void print(int model=-1, QString filename=""); + void setModified(); + void updateTitle(); + + private: + bool maybeSave(); + void setCurrentFile(const QString &fileName); + QString strippedName(const QString &fullFileName); + void saveSelection(); + void restoreSelection(); + bool loadOtxFile(const QString &fileName, bool resetCurrentFile); + + Ui::mdiChild *ui; + + QString curFile; + + Firmware * firmware; + RadioData radioData; + + bool isUntitled; + bool fileChanged; + int EEPromAvail; +}; + #endif // _MDICHILD_H_ diff --git a/companion/src/modeledit/channels.h b/companion/src/modeledit/channels.h index 538cb93b4..80df22e6a 100644 --- a/companion/src/modeledit/channels.h +++ b/companion/src/modeledit/channels.h @@ -20,49 +20,49 @@ #ifndef _CHANNELS_H_ #define _CHANNELS_H_ - -#include "helpers.h" -#include "modeledit.h" - -class GVarGroup; - -class LimitsGroup -{ - public: - LimitsGroup(Firmware * firmware, TableLayout *tableLayout, int row, int col, int & value, const ModelData & model, int min, int max, int deflt); - ~LimitsGroup(); - - void updateMinMax(int max); - - protected: - Firmware * firmware; - QDoubleSpinBox * spinbox; - GVarGroup * gvarGroup; - int & value; - double displayStep; -}; - -class Channels : public ModelPanel -{ - Q_OBJECT - - public: - Channels(QWidget *parent, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); - ~Channels(); - - private: - QVector limitsGroups; - - public slots: - void refreshExtendedLimits(); - - private slots: - void symlimitsEdited(); - void nameEdited(); - void invEdited(); - void curveEdited(); - void ppmcenterEdited(); - -}; - + +#include "helpers.h" +#include "modeledit.h" + +class GVarGroup; + +class LimitsGroup +{ + public: + LimitsGroup(Firmware * firmware, TableLayout *tableLayout, int row, int col, int & value, const ModelData & model, int min, int max, int deflt); + ~LimitsGroup(); + + void updateMinMax(int max); + + protected: + Firmware * firmware; + QDoubleSpinBox * spinbox; + GVarGroup * gvarGroup; + int & value; + double displayStep; +}; + +class Channels : public ModelPanel +{ + Q_OBJECT + + public: + Channels(QWidget *parent, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); + ~Channels(); + + private: + QVector limitsGroups; + + public slots: + void refreshExtendedLimits(); + + private slots: + void symlimitsEdited(); + void nameEdited(); + void invEdited(); + void curveEdited(); + void ppmcenterEdited(); + +}; + #endif // _CHANNELS_H_ diff --git a/companion/src/modeledit/curves.h b/companion/src/modeledit/curves.h index 47119b109..ebf4ffa4f 100644 --- a/companion/src/modeledit/curves.h +++ b/companion/src/modeledit/curves.h @@ -20,72 +20,72 @@ #ifndef _CURVES_H_ #define _CURVES_H_ - -#include "modeledit.h" -#include "eeprominterface.h" - -enum CopyAction { - CURVE_COPY, - CURVE_PASTE, - CURVE_RESET, - CURVE_RESETALL -}; - -namespace Ui { - class Curves; -} - -typedef float (*curveFunction) (float x, float coeff, float yMin, float yMid, float yMax); - -struct CurveCreatorTemplate { - QString name; - unsigned int flags; - curveFunction function; -}; - -class Curves : public ModelPanel -{ - Q_OBJECT - - public: - Curves(QWidget *parent, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); - virtual ~Curves(); - - virtual void update(); - - private slots: - void editCurve(); - void ShowContextMenu(const QPoint& pos); - void plotCurve(bool checked); - void on_curveName_editingFinished(); - void on_curvePoints_currentIndexChanged(int index); - void on_curveCustom_currentIndexChanged(int index); - void on_curveSmooth_currentIndexChanged(int index); - void onPointEdited(); - void onNodeMoved(int x, int y); - void onNodeFocus(); - void onNodeUnfocus(); - void on_curveType_currentIndexChanged(int index); - void on_curveApply_clicked(); - - protected: - virtual void resizeEvent(QResizeEvent *event); - void addTemplate(QString name, unsigned int flags, curveFunction function); - - private: - Ui::Curves *ui; - int currentCurve; - bool visibleCurves[CPN_MAX_CURVES]; - QSpinBox * spnx[CPN_MAX_POINTS]; - QSpinBox * spny[CPN_MAX_POINTS]; - QVector templates; - void setCurrentCurve(int index); - void updateCurve(); - void updateCurveType(); - void updateCurvePoints(); - bool allowCurveType(int points, CurveData::CurveType type); - void setPointY(int i, int x, int y); - -}; - + +#include "modeledit.h" +#include "eeprominterface.h" + +enum CopyAction { + CURVE_COPY, + CURVE_PASTE, + CURVE_RESET, + CURVE_RESETALL +}; + +namespace Ui { + class Curves; +} + +typedef float (*curveFunction) (float x, float coeff, float yMin, float yMid, float yMax); + +struct CurveCreatorTemplate { + QString name; + unsigned int flags; + curveFunction function; +}; + +class Curves : public ModelPanel +{ + Q_OBJECT + + public: + Curves(QWidget *parent, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); + virtual ~Curves(); + + virtual void update(); + + private slots: + void editCurve(); + void ShowContextMenu(const QPoint& pos); + void plotCurve(bool checked); + void on_curveName_editingFinished(); + void on_curvePoints_currentIndexChanged(int index); + void on_curveCustom_currentIndexChanged(int index); + void on_curveSmooth_currentIndexChanged(int index); + void onPointEdited(); + void onNodeMoved(int x, int y); + void onNodeFocus(); + void onNodeUnfocus(); + void on_curveType_currentIndexChanged(int index); + void on_curveApply_clicked(); + + protected: + virtual void resizeEvent(QResizeEvent *event); + void addTemplate(QString name, unsigned int flags, curveFunction function); + + private: + Ui::Curves *ui; + int currentCurve; + bool visibleCurves[CPN_MAX_CURVES]; + QSpinBox * spnx[CPN_MAX_POINTS]; + QSpinBox * spny[CPN_MAX_POINTS]; + QVector templates; + void setCurrentCurve(int index); + void updateCurve(); + void updateCurveType(); + void updateCurvePoints(); + bool allowCurveType(int points, CurveData::CurveType type); + void setPointY(int i, int x, int y); + +}; + #endif // _CURVES_H_ diff --git a/companion/src/modeledit/customfunctions.h b/companion/src/modeledit/customfunctions.h index 90360a046..1bf94b913 100644 --- a/companion/src/modeledit/customfunctions.h +++ b/companion/src/modeledit/customfunctions.h @@ -20,80 +20,80 @@ #ifndef _CUSTOMFUNCTIONS_H_ #define _CUSTOMFUNCTIONS_H_ - -#include "modeledit.h" -#include "eeprominterface.h" -#include - -class RepeatComboBox: public QComboBox -{ - Q_OBJECT - - public: - RepeatComboBox(QWidget * parent, int & repeatParam); - void update(); - - signals: - void modified(); - - private slots: - void onIndexChanged(int); - - protected: - int & repeatParam; -}; - -class CustomFunctionsPanel : public GenericPanel -{ - Q_OBJECT - - public: - CustomFunctionsPanel(QWidget *parent, ModelData * mode, GeneralSettings & generalSettings, Firmware * firmware); - ~CustomFunctionsPanel(); - - virtual void update(); - - protected: - CustomFunctionData * functions; - - private slots: - void customFunctionEdited(); - void functionEdited(); - void fsw_customContextMenuRequested(QPoint pos); - void refreshCustomFunction(int index, bool modified=false); - void onChildModified(); - void playMusic(); - void onMediaPlayerStateChanged(QMediaPlayer::State state); - void onMediaPlayerError(QMediaPlayer::Error error); - void fswDelete(); - void fswCopy(); - void fswPaste(); - void fswCut(); - - private: - void populateFuncCB(QComboBox *b, unsigned int value); - void populateGVmodeCB(QComboBox *b, unsigned int value); - void populateFuncParamCB(QComboBox *b, uint function, unsigned int value, unsigned int adjustmode=0); - - QSet tracksSet; - QSet scriptsSet; - int mediaPlayerCurrent; - QComboBox * fswtchSwtch[CPN_MAX_CUSTOM_FUNCTIONS]; - QComboBox * fswtchFunc[CPN_MAX_CUSTOM_FUNCTIONS]; - QCheckBox * fswtchParamGV[CPN_MAX_CUSTOM_FUNCTIONS]; - QDoubleSpinBox * fswtchParam[CPN_MAX_CUSTOM_FUNCTIONS]; - QTimeEdit * fswtchParamTime[CPN_MAX_CUSTOM_FUNCTIONS]; - QPushButton * playBT[CPN_MAX_CUSTOM_FUNCTIONS]; - QComboBox * fswtchParamT[CPN_MAX_CUSTOM_FUNCTIONS]; - QComboBox * fswtchParamArmT[CPN_MAX_CUSTOM_FUNCTIONS]; - QCheckBox * fswtchEnable[CPN_MAX_CUSTOM_FUNCTIONS]; - RepeatComboBox * fswtchRepeat[CPN_MAX_CUSTOM_FUNCTIONS]; - QComboBox * fswtchGVmode[CPN_MAX_CUSTOM_FUNCTIONS]; - QSlider * fswtchBLcolor[CPN_MAX_CUSTOM_FUNCTIONS]; - QMediaPlayer * mediaPlayer; - - int selectedFunction; - -}; - + +#include "modeledit.h" +#include "eeprominterface.h" +#include + +class RepeatComboBox: public QComboBox +{ + Q_OBJECT + + public: + RepeatComboBox(QWidget * parent, int & repeatParam); + void update(); + + signals: + void modified(); + + private slots: + void onIndexChanged(int); + + protected: + int & repeatParam; +}; + +class CustomFunctionsPanel : public GenericPanel +{ + Q_OBJECT + + public: + CustomFunctionsPanel(QWidget *parent, ModelData * mode, GeneralSettings & generalSettings, Firmware * firmware); + ~CustomFunctionsPanel(); + + virtual void update(); + + protected: + CustomFunctionData * functions; + + private slots: + void customFunctionEdited(); + void functionEdited(); + void fsw_customContextMenuRequested(QPoint pos); + void refreshCustomFunction(int index, bool modified=false); + void onChildModified(); + void playMusic(); + void onMediaPlayerStateChanged(QMediaPlayer::State state); + void onMediaPlayerError(QMediaPlayer::Error error); + void fswDelete(); + void fswCopy(); + void fswPaste(); + void fswCut(); + + private: + void populateFuncCB(QComboBox *b, unsigned int value); + void populateGVmodeCB(QComboBox *b, unsigned int value); + void populateFuncParamCB(QComboBox *b, uint function, unsigned int value, unsigned int adjustmode=0); + + QSet tracksSet; + QSet scriptsSet; + int mediaPlayerCurrent; + QComboBox * fswtchSwtch[CPN_MAX_CUSTOM_FUNCTIONS]; + QComboBox * fswtchFunc[CPN_MAX_CUSTOM_FUNCTIONS]; + QCheckBox * fswtchParamGV[CPN_MAX_CUSTOM_FUNCTIONS]; + QDoubleSpinBox * fswtchParam[CPN_MAX_CUSTOM_FUNCTIONS]; + QTimeEdit * fswtchParamTime[CPN_MAX_CUSTOM_FUNCTIONS]; + QPushButton * playBT[CPN_MAX_CUSTOM_FUNCTIONS]; + QComboBox * fswtchParamT[CPN_MAX_CUSTOM_FUNCTIONS]; + QComboBox * fswtchParamArmT[CPN_MAX_CUSTOM_FUNCTIONS]; + QCheckBox * fswtchEnable[CPN_MAX_CUSTOM_FUNCTIONS]; + RepeatComboBox * fswtchRepeat[CPN_MAX_CUSTOM_FUNCTIONS]; + QComboBox * fswtchGVmode[CPN_MAX_CUSTOM_FUNCTIONS]; + QSlider * fswtchBLcolor[CPN_MAX_CUSTOM_FUNCTIONS]; + QMediaPlayer * mediaPlayer; + + int selectedFunction; + +}; + #endif // _CUSTOMFUNCTIONS_H_ diff --git a/companion/src/modeledit/edge.cpp b/companion/src/modeledit/edge.cpp index c39efd115..49360ffdb 100644 --- a/companion/src/modeledit/edge.cpp +++ b/companion/src/modeledit/edge.cpp @@ -18,92 +18,92 @@ * GNU General Public License for more details. */ -#include - -#include "edge.h" -#include "node.h" - -#include - -Edge::Edge(Node *sourceNode, Node *destNode) - : arrowSize(10) -{ - setAcceptedMouseButtons(0); - source = sourceNode; - dest = destNode; - source->addEdge(this); - dest->addEdge(this); - adjust(); -} - -Edge::~Edge() -{ -} - -Node *Edge::sourceNode() const -{ - return source; -} - -void Edge::setSourceNode(Node *node) -{ - source = node; - adjust(); -} - -Node *Edge::destNode() const -{ - return dest; -} - -void Edge::setDestNode(Node *node) -{ - dest = node; - adjust(); -} - -void Edge::adjust() -{ - if (!source || !dest) - return; - - QLineF line(mapFromItem(source, 0, 0), mapFromItem(dest, 0, 0)); - qreal length = line.length(); - prepareGeometryChange(); - int ballSize = source->getBallSize(); - if (length > qreal(ballSize)) { - QPointF edgeOffset((line.dx() * ballSize / 2) / length, (line.dy() * ballSize / 2) / length); - sourcePoint = line.p1() + edgeOffset; - destPoint = line.p2() - edgeOffset; - } else { - sourcePoint = destPoint = line.p1(); - } -} - -QRectF Edge::boundingRect() const -{ - if (!source || !dest) - return QRectF(); - - qreal penWidth = 1; - qreal extra = (penWidth + arrowSize) / 2.0; - - return QRectF(sourcePoint, QSizeF(destPoint.x() - sourcePoint.x(), - destPoint.y() - sourcePoint.y())) - .normalized() - .adjusted(-extra, -extra, extra, extra); -} - -void Edge::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) -{ - if (!source || !dest) - return; - - QLineF line(sourcePoint, destPoint); - if (qFuzzyCompare(line.length(), qreal(0.))) - return; - - // Draw the line itself - painter->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); - painter->drawLine(line); -} +#include + +#include "edge.h" +#include "node.h" + +#include + +Edge::Edge(Node *sourceNode, Node *destNode) + : arrowSize(10) +{ + setAcceptedMouseButtons(0); + source = sourceNode; + dest = destNode; + source->addEdge(this); + dest->addEdge(this); + adjust(); +} + +Edge::~Edge() +{ +} + +Node *Edge::sourceNode() const +{ + return source; +} + +void Edge::setSourceNode(Node *node) +{ + source = node; + adjust(); +} + +Node *Edge::destNode() const +{ + return dest; +} + +void Edge::setDestNode(Node *node) +{ + dest = node; + adjust(); +} + +void Edge::adjust() +{ + if (!source || !dest) + return; + + QLineF line(mapFromItem(source, 0, 0), mapFromItem(dest, 0, 0)); + qreal length = line.length(); + prepareGeometryChange(); + int ballSize = source->getBallSize(); + if (length > qreal(ballSize)) { + QPointF edgeOffset((line.dx() * ballSize / 2) / length, (line.dy() * ballSize / 2) / length); + sourcePoint = line.p1() + edgeOffset; + destPoint = line.p2() - edgeOffset; + } else { + sourcePoint = destPoint = line.p1(); + } +} + +QRectF Edge::boundingRect() const +{ + if (!source || !dest) + return QRectF(); + + qreal penWidth = 1; + qreal extra = (penWidth + arrowSize) / 2.0; + + return QRectF(sourcePoint, QSizeF(destPoint.x() - sourcePoint.x(), + destPoint.y() - sourcePoint.y())) + .normalized() + .adjusted(-extra, -extra, extra, extra); +} + +void Edge::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) +{ + if (!source || !dest) + return; + + QLineF line(sourcePoint, destPoint); + if (qFuzzyCompare(line.length(), qreal(0.))) + return; + + // Draw the line itself + painter->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); + painter->drawLine(line); +} diff --git a/companion/src/modeledit/edge.h b/companion/src/modeledit/edge.h index 3e330f904..7d5077639 100644 --- a/companion/src/modeledit/edge.h +++ b/companion/src/modeledit/edge.h @@ -20,38 +20,38 @@ #ifndef _EDGE_H_ #define _EDGE_H_ - -#include - -class Node; - -class Edge : public QGraphicsItem -{ -public: - Edge(Node *sourceNode, Node *destNode); - ~Edge(); - - Node *sourceNode() const; - void setSourceNode(Node *node); - - Node *destNode() const; - void setDestNode(Node *node); - - void adjust(); - - enum { Type = UserType + 2 }; - int type() const { return Type; } - -protected: - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - -private: - Node *source, *dest; - - QPointF sourcePoint; - QPointF destPoint; - qreal arrowSize; -}; - + +#include + +class Node; + +class Edge : public QGraphicsItem +{ +public: + Edge(Node *sourceNode, Node *destNode); + ~Edge(); + + Node *sourceNode() const; + void setSourceNode(Node *node); + + Node *destNode() const; + void setDestNode(Node *node); + + void adjust(); + + enum { Type = UserType + 2 }; + int type() const { return Type; } + +protected: + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + +private: + Node *source, *dest; + + QPointF sourcePoint; + QPointF destPoint; + qreal arrowSize; +}; + #endif // _EDGE_H_ diff --git a/companion/src/modeledit/flightmodes.h b/companion/src/modeledit/flightmodes.h index 1814a6943..464c9ab09 100644 --- a/companion/src/modeledit/flightmodes.h +++ b/companion/src/modeledit/flightmodes.h @@ -20,87 +20,87 @@ #ifndef _FLIGHTMODES_H_ #define _FLIGHTMODES_H_ - -#include "modeledit.h" -#include "eeprominterface.h" - -namespace Ui { - class FlightMode; -} - -class FlightModePanel : public ModelPanel -{ - Q_OBJECT - - public: - FlightModePanel(QWidget *parent, ModelData &model, int modeIdx, GeneralSettings & generalSettings, Firmware * firmware); - virtual ~FlightModePanel(); - - virtual void update(); - - signals: - void nameModified(); - - private slots: - void phaseName_editingFinished(); - void phaseSwitch_currentIndexChanged(int index); - void phaseFadeIn_editingFinished(); - void phaseFadeOut_editingFinished(); - void phaseTrimUse_currentIndexChanged(int index); - void phaseTrim_valueChanged(); - void phaseTrimSlider_valueChanged(); - void GVName_editingFinished(); - void phaseGVValue_editingFinished(); - void phaseGVUse_currentIndexChanged(int index); - void phaseGVPopupToggled(bool checked); - void phaseREValue_editingFinished(); - void phaseREUse_currentIndexChanged(int index); - void name_customContextMenuRequested(const QPoint & pos); - void fmClear(); - - private: - Ui::FlightMode *ui; - int phaseIdx; - FlightModeData & phase; - int reCount; - int gvCount; - QVector trimsLabel; - QLineEdit * gvNames[CPN_MAX_GVARS]; - QSpinBox * gvValues[CPN_MAX_GVARS]; - QCheckBox * gvPopups[CPN_MAX_GVARS]; - QComboBox * gvUse[CPN_MAX_GVARS]; - QSpinBox * reValues[CPN_MAX_ENCODERS]; - QComboBox * reUse[CPN_MAX_ENCODERS]; - QVector trimsUse; - QVector trimsValue; - QVector trimsSlider; - - void trimUpdate(unsigned int trim); - -}; - -class FlightModesPanel : public ModelPanel -{ - Q_OBJECT - - public: - FlightModesPanel(QWidget *parent, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); - virtual ~FlightModesPanel(); - - virtual void update(); - - private slots: - void onPhaseModified(); - void onPhaseNameChanged(); - void on_tabWidget_currentChanged(int index); - - private: - int modesCount; - QTabWidget *tabWidget; - QString getTabName(int index); - QVector panels; - -}; - + +#include "modeledit.h" +#include "eeprominterface.h" + +namespace Ui { + class FlightMode; +} + +class FlightModePanel : public ModelPanel +{ + Q_OBJECT + + public: + FlightModePanel(QWidget *parent, ModelData &model, int modeIdx, GeneralSettings & generalSettings, Firmware * firmware); + virtual ~FlightModePanel(); + + virtual void update(); + + signals: + void nameModified(); + + private slots: + void phaseName_editingFinished(); + void phaseSwitch_currentIndexChanged(int index); + void phaseFadeIn_editingFinished(); + void phaseFadeOut_editingFinished(); + void phaseTrimUse_currentIndexChanged(int index); + void phaseTrim_valueChanged(); + void phaseTrimSlider_valueChanged(); + void GVName_editingFinished(); + void phaseGVValue_editingFinished(); + void phaseGVUse_currentIndexChanged(int index); + void phaseGVPopupToggled(bool checked); + void phaseREValue_editingFinished(); + void phaseREUse_currentIndexChanged(int index); + void name_customContextMenuRequested(const QPoint & pos); + void fmClear(); + + private: + Ui::FlightMode *ui; + int phaseIdx; + FlightModeData & phase; + int reCount; + int gvCount; + QVector trimsLabel; + QLineEdit * gvNames[CPN_MAX_GVARS]; + QSpinBox * gvValues[CPN_MAX_GVARS]; + QCheckBox * gvPopups[CPN_MAX_GVARS]; + QComboBox * gvUse[CPN_MAX_GVARS]; + QSpinBox * reValues[CPN_MAX_ENCODERS]; + QComboBox * reUse[CPN_MAX_ENCODERS]; + QVector trimsUse; + QVector trimsValue; + QVector trimsSlider; + + void trimUpdate(unsigned int trim); + +}; + +class FlightModesPanel : public ModelPanel +{ + Q_OBJECT + + public: + FlightModesPanel(QWidget *parent, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); + virtual ~FlightModesPanel(); + + virtual void update(); + + private slots: + void onPhaseModified(); + void onPhaseNameChanged(); + void on_tabWidget_currentChanged(int index); + + private: + int modesCount; + QTabWidget *tabWidget; + QString getTabName(int index); + QVector panels; + +}; + #endif // _FLIGHTMODES_H_ - + diff --git a/companion/src/modeledit/heli.h b/companion/src/modeledit/heli.h index 1ae5f532f..dfcb0a666 100644 --- a/companion/src/modeledit/heli.h +++ b/companion/src/modeledit/heli.h @@ -20,27 +20,27 @@ #ifndef _HELI_H_ #define _HELI_H_ - -#include "modeledit.h" - -namespace Ui { - class Heli; -} - -class HeliPanel : public ModelPanel -{ - Q_OBJECT - - public: - HeliPanel(QWidget *parent, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); - ~HeliPanel(); - void update(); - - private slots: - void edited(); - - private: - Ui::Heli *ui; -}; - + +#include "modeledit.h" + +namespace Ui { + class Heli; +} + +class HeliPanel : public ModelPanel +{ + Q_OBJECT + + public: + HeliPanel(QWidget *parent, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); + ~HeliPanel(); + void update(); + + private slots: + void edited(); + + private: + Ui::Heli *ui; +}; + #endif // _HELI_H_ diff --git a/companion/src/modeledit/inputs.h b/companion/src/modeledit/inputs.h index 3bfea7d75..33904df26 100644 --- a/companion/src/modeledit/inputs.h +++ b/companion/src/modeledit/inputs.h @@ -20,56 +20,56 @@ #ifndef _INPUTS_H_ #define _INPUTS_H_ - -#include "modeledit.h" -#include "mixerslist.h" -#include "modelprinter.h" - -class InputsPanel : public ModelPanel -{ - Q_OBJECT - - public: - InputsPanel(QWidget *parent, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); - virtual ~InputsPanel(); - - virtual void update(); - - private slots: - void clearExpos(); - void moveExpoUp(); - void moveExpoDown(); - void mimeExpoDropped(int index, const QMimeData *data, Qt::DropAction action); - void expolistWidget_customContextMenuRequested(QPoint pos); - void expolistWidget_doubleClicked(QModelIndex index); - void expolistWidget_KeyPress(QKeyEvent *event); - void exposDelete(bool ask=true); - void exposCut(); - void exposCopy(); - void exposPaste(); - void exposDuplicate(); - void expoOpen(QListWidgetItem *item = NULL); - void expoAdd(); - - private: - bool expoInserted; - MixersList *ExposlistWidget; - bool firstLine; - int inputsCount; - ModelPrinter modelPrinter; - - int getExpoIndex(unsigned int dch); - bool gm_insertExpo(int idx); - void gm_deleteExpo(int index); - void gm_openExpo(int index); - int gm_moveExpo(int idx, bool dir); - void exposDeleteList(QList list); - QList createExpoListFromSelected(); - void setSelectedByExpoList(QList list); - void pasteExpoMimeData(const QMimeData * mimeData, int destIdx); - bool AddInputLine(int dest); - QString getInputText(int dest, bool * new_ch); - -}; - + +#include "modeledit.h" +#include "mixerslist.h" +#include "modelprinter.h" + +class InputsPanel : public ModelPanel +{ + Q_OBJECT + + public: + InputsPanel(QWidget *parent, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); + virtual ~InputsPanel(); + + virtual void update(); + + private slots: + void clearExpos(); + void moveExpoUp(); + void moveExpoDown(); + void mimeExpoDropped(int index, const QMimeData *data, Qt::DropAction action); + void expolistWidget_customContextMenuRequested(QPoint pos); + void expolistWidget_doubleClicked(QModelIndex index); + void expolistWidget_KeyPress(QKeyEvent *event); + void exposDelete(bool ask=true); + void exposCut(); + void exposCopy(); + void exposPaste(); + void exposDuplicate(); + void expoOpen(QListWidgetItem *item = NULL); + void expoAdd(); + + private: + bool expoInserted; + MixersList *ExposlistWidget; + bool firstLine; + int inputsCount; + ModelPrinter modelPrinter; + + int getExpoIndex(unsigned int dch); + bool gm_insertExpo(int idx); + void gm_deleteExpo(int index); + void gm_openExpo(int index); + int gm_moveExpo(int idx, bool dir); + void exposDeleteList(QList list); + QList createExpoListFromSelected(); + void setSelectedByExpoList(QList list); + void pasteExpoMimeData(const QMimeData * mimeData, int destIdx); + bool AddInputLine(int dest); + QString getInputText(int dest, bool * new_ch); + +}; + #endif // _INPUTS_H_ diff --git a/companion/src/modeledit/logicalswitches.h b/companion/src/modeledit/logicalswitches.h index be8e49e67..8ac3e3693 100644 --- a/companion/src/modeledit/logicalswitches.h +++ b/companion/src/modeledit/logicalswitches.h @@ -20,52 +20,52 @@ #ifndef _LOGICALSWITCHES_H_ #define _LOGICALSWITCHES_H_ - -#include "modeledit.h" -#include "eeprominterface.h" - -class LogicalSwitchesPanel : public ModelPanel -{ - Q_OBJECT - - public: - LogicalSwitchesPanel(QWidget *parent, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); - virtual ~LogicalSwitchesPanel(); - - virtual void update(); - - private slots: - void edited(); - void v1Edited(int value); - void v2Edited(int value); - void andEdited(int value); - void durationEdited(double duration); - void delayEdited(double delay); - void csw_customContextMenuRequested(QPoint pos); - void cswDelete(); - void cswCopy(); - void cswPaste(); - void cswCut(); - - private: - QComboBox * csw[CPN_MAX_CSW]; - QDoubleSpinBox * cswitchValue[CPN_MAX_CSW]; - QDoubleSpinBox * cswitchOffset[CPN_MAX_CSW]; - QDoubleSpinBox * cswitchOffset2[CPN_MAX_CSW]; - QTimeEdit * cswitchTOffset[CPN_MAX_CSW]; - QComboBox * cswitchAnd[CPN_MAX_CSW]; - QDoubleSpinBox * cswitchDuration[CPN_MAX_CSW]; - QDoubleSpinBox * cswitchDelay[CPN_MAX_CSW]; - QComboBox * cswitchSource1[CPN_MAX_CSW]; - QComboBox * cswitchSource2[CPN_MAX_CSW]; - void setSwitchWidgetVisibility(int i); - int selectedSwitch; - - void populateCSWCB(QComboBox *b, int value); - void populateAndSwitchCB(QComboBox *b, const RawSwitch & value); - void updateLine(int index); - void updateTimerParam(QDoubleSpinBox *sb, int timer, double minimum=0); - -}; - + +#include "modeledit.h" +#include "eeprominterface.h" + +class LogicalSwitchesPanel : public ModelPanel +{ + Q_OBJECT + + public: + LogicalSwitchesPanel(QWidget *parent, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); + virtual ~LogicalSwitchesPanel(); + + virtual void update(); + + private slots: + void edited(); + void v1Edited(int value); + void v2Edited(int value); + void andEdited(int value); + void durationEdited(double duration); + void delayEdited(double delay); + void csw_customContextMenuRequested(QPoint pos); + void cswDelete(); + void cswCopy(); + void cswPaste(); + void cswCut(); + + private: + QComboBox * csw[CPN_MAX_CSW]; + QDoubleSpinBox * cswitchValue[CPN_MAX_CSW]; + QDoubleSpinBox * cswitchOffset[CPN_MAX_CSW]; + QDoubleSpinBox * cswitchOffset2[CPN_MAX_CSW]; + QTimeEdit * cswitchTOffset[CPN_MAX_CSW]; + QComboBox * cswitchAnd[CPN_MAX_CSW]; + QDoubleSpinBox * cswitchDuration[CPN_MAX_CSW]; + QDoubleSpinBox * cswitchDelay[CPN_MAX_CSW]; + QComboBox * cswitchSource1[CPN_MAX_CSW]; + QComboBox * cswitchSource2[CPN_MAX_CSW]; + void setSwitchWidgetVisibility(int i); + int selectedSwitch; + + void populateCSWCB(QComboBox *b, int value); + void populateAndSwitchCB(QComboBox *b, const RawSwitch & value); + void updateLine(int index); + void updateTimerParam(QDoubleSpinBox *sb, int timer, double minimum=0); + +}; + #endif // _LOGICALSWITCHES_H_ diff --git a/companion/src/modeledit/mixerslist.cpp b/companion/src/modeledit/mixerslist.cpp index cc97f4735..e209615f7 100644 --- a/companion/src/modeledit/mixerslist.cpp +++ b/companion/src/modeledit/mixerslist.cpp @@ -18,142 +18,142 @@ * GNU General Public License for more details. */ -#include "mixerslist.h" - -MixersList::MixersList(QWidget *parent, bool expo) : - QListWidget(parent), - expo(expo) -{ - setFont(QFont("Courier New",12)); - setContextMenuPolicy(Qt::CustomContextMenu); - setSelectionMode(QAbstractItemView::SingleSelection); - setDragEnabled(true); - setAcceptDrops(true); - setDropIndicatorShown(true); - setItemDelegate(new MixersDelegate(parent)); //set custom paint handler -} - -void MixersList::keyPressEvent(QKeyEvent *event) -{ - emit keyWasPressed(event); -} - - -/** - @brief Override to give us different mime type for mixers and inputs -*/ -QStringList MixersList::mimeTypes () const -{ - QStringList types; - if (expo) types << "application/x-companion-expo-item"; - else types << "application/x-companion-mix-item"; - return types; -} - -void MixersList::dropEvent(QDropEvent *event) -{ - QList list; - foreach(QListWidgetItem *item, selectedItems()) { - int idx= item->data(Qt::UserRole).toByteArray().at(0); - if(idx >= 0) list << idx; - } - if (list.count()<1) return; - event->acceptProposedAction(); - dropMimeData(indexAt(event->pos()).row(),event->mimeData(),event->dropAction()); -} - -bool MixersList::dropMimeData( int index, const QMimeData * data, Qt::DropAction action ) -{ - // qDebug() << "MixersList::dropMimeData() index:" << index << "formats" << data->formats(); - QByteArray dropData = data->data(expo ? "application/x-companion-expo-item" : "application/x-companion-mix-item"); - if (dropData.isNull() ) return false; - QDataStream stream(&dropData, QIODevice::ReadOnly); - QByteArray qba; - - while (!stream.atEnd()) { - int r,c; - QMap v; - stream >> r >> c >> v; - QList lsVars; - lsVars = v.values(); - qba.append(lsVars.at(1).toByteArray().mid(1)); - // qDebug() << "MixersList::dropMimeData() added" << lsVars.count() << "items, data:" << lsVars; - } - - if(qba.length()>0) { - QMimeData *mimeData = new QMimeData; - mimeData->setData(expo ? "application/x-companion-expo" : "application/x-companion-mix", qba); - emit mimeDropped(index, mimeData, action); - delete mimeData; //is this correct? is mimeData freed elswere?? - } - - return true; -} - -/** - @brief Paints our HTML formated list item text -*/ -void MixersDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - QStyleOptionViewItem options = option; - initStyleOption(&options, index); - - painter->save(); - - //setup html document - QTextDocument doc; - SetupDocument(doc, options); - - options.text = ""; - options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter); - - if ( index.model()->data(index, GroupHeaderRole).toInt() > 0 ) { - //paint with added space - painter->translate(options.rect.left(), options.rect.top() + MIX_ROW_HEIGHT_INCREASE); - QRect clip(0, 0, options.rect.width(), options.rect.height() - MIX_ROW_HEIGHT_INCREASE); - doc.drawContents(painter, clip); - } - else { - painter->translate(options.rect.left(), options.rect.top()); - QRect clip(0, 0, options.rect.width(), options.rect.height()); - doc.drawContents(painter, clip); - } - painter->restore(); -} - - -/** - @brief Returns needed size for our HTML formated list item text -*/ -QSize MixersDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const -{ - QStyleOptionViewItem options = option; - initStyleOption(&options, index); - - //setup html document - QTextDocument doc; - SetupDocument(doc, options); - - //qDebug() << "MixersDelegate::sizeHint() UserRole-> " << index.model()->data(index, Qt::UserRole + 2); - int height = doc.size().height(); - if ( index.model()->data(index, Qt::UserRole + 2).toInt() > 0 ) { - //qDebug() << "MixersDelegate::sizeHint() detected channel head"; - height = doc.size().height() + MIX_ROW_HEIGHT_INCREASE; - } - //qDebug() << "MixersDelegate::sizeHint() options.rect " << options.rect; - //qDebug() << "MixersDelegate::sizeHint() result " << QSize(doc.idealWidth(), height) << options.rect.width(); - return QSize(doc.idealWidth(), height); -} - -void MixersDelegate::SetupDocument(QTextDocument & doc, const QStyleOptionViewItem & options) const -{ - //setup html document - doc.setHtml(options.text); - doc.setDefaultFont(options.font); - - //minimize margins (default margins look ugly) - QTextFrame *tf = doc.rootFrame(); - QTextFrameFormat tff = tf->frameFormat(); - tff.setMargin(0); - tf->setFrameFormat(tff); -} +#include "mixerslist.h" + +MixersList::MixersList(QWidget *parent, bool expo) : + QListWidget(parent), + expo(expo) +{ + setFont(QFont("Courier New",12)); + setContextMenuPolicy(Qt::CustomContextMenu); + setSelectionMode(QAbstractItemView::SingleSelection); + setDragEnabled(true); + setAcceptDrops(true); + setDropIndicatorShown(true); + setItemDelegate(new MixersDelegate(parent)); //set custom paint handler +} + +void MixersList::keyPressEvent(QKeyEvent *event) +{ + emit keyWasPressed(event); +} + + +/** + @brief Override to give us different mime type for mixers and inputs +*/ +QStringList MixersList::mimeTypes () const +{ + QStringList types; + if (expo) types << "application/x-companion-expo-item"; + else types << "application/x-companion-mix-item"; + return types; +} + +void MixersList::dropEvent(QDropEvent *event) +{ + QList list; + foreach(QListWidgetItem *item, selectedItems()) { + int idx= item->data(Qt::UserRole).toByteArray().at(0); + if(idx >= 0) list << idx; + } + if (list.count()<1) return; + event->acceptProposedAction(); + dropMimeData(indexAt(event->pos()).row(),event->mimeData(),event->dropAction()); +} + +bool MixersList::dropMimeData( int index, const QMimeData * data, Qt::DropAction action ) +{ + // qDebug() << "MixersList::dropMimeData() index:" << index << "formats" << data->formats(); + QByteArray dropData = data->data(expo ? "application/x-companion-expo-item" : "application/x-companion-mix-item"); + if (dropData.isNull() ) return false; + QDataStream stream(&dropData, QIODevice::ReadOnly); + QByteArray qba; + + while (!stream.atEnd()) { + int r,c; + QMap v; + stream >> r >> c >> v; + QList lsVars; + lsVars = v.values(); + qba.append(lsVars.at(1).toByteArray().mid(1)); + // qDebug() << "MixersList::dropMimeData() added" << lsVars.count() << "items, data:" << lsVars; + } + + if(qba.length()>0) { + QMimeData *mimeData = new QMimeData; + mimeData->setData(expo ? "application/x-companion-expo" : "application/x-companion-mix", qba); + emit mimeDropped(index, mimeData, action); + delete mimeData; //is this correct? is mimeData freed elswere?? + } + + return true; +} + +/** + @brief Paints our HTML formated list item text +*/ +void MixersDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const +{ + QStyleOptionViewItem options = option; + initStyleOption(&options, index); + + painter->save(); + + //setup html document + QTextDocument doc; + SetupDocument(doc, options); + + options.text = ""; + options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter); + + if ( index.model()->data(index, GroupHeaderRole).toInt() > 0 ) { + //paint with added space + painter->translate(options.rect.left(), options.rect.top() + MIX_ROW_HEIGHT_INCREASE); + QRect clip(0, 0, options.rect.width(), options.rect.height() - MIX_ROW_HEIGHT_INCREASE); + doc.drawContents(painter, clip); + } + else { + painter->translate(options.rect.left(), options.rect.top()); + QRect clip(0, 0, options.rect.width(), options.rect.height()); + doc.drawContents(painter, clip); + } + painter->restore(); +} + + +/** + @brief Returns needed size for our HTML formated list item text +*/ +QSize MixersDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const +{ + QStyleOptionViewItem options = option; + initStyleOption(&options, index); + + //setup html document + QTextDocument doc; + SetupDocument(doc, options); + + //qDebug() << "MixersDelegate::sizeHint() UserRole-> " << index.model()->data(index, Qt::UserRole + 2); + int height = doc.size().height(); + if ( index.model()->data(index, Qt::UserRole + 2).toInt() > 0 ) { + //qDebug() << "MixersDelegate::sizeHint() detected channel head"; + height = doc.size().height() + MIX_ROW_HEIGHT_INCREASE; + } + //qDebug() << "MixersDelegate::sizeHint() options.rect " << options.rect; + //qDebug() << "MixersDelegate::sizeHint() result " << QSize(doc.idealWidth(), height) << options.rect.width(); + return QSize(doc.idealWidth(), height); +} + +void MixersDelegate::SetupDocument(QTextDocument & doc, const QStyleOptionViewItem & options) const +{ + //setup html document + doc.setHtml(options.text); + doc.setDefaultFont(options.font); + + //minimize margins (default margins look ugly) + QTextFrame *tf = doc.rootFrame(); + QTextFrameFormat tff = tf->frameFormat(); + tff.setMargin(0); + tf->setFrameFormat(tff); +} diff --git a/companion/src/modeledit/mixerslist.h b/companion/src/modeledit/mixerslist.h index a39248d94..a42ace1d0 100644 --- a/companion/src/modeledit/mixerslist.h +++ b/companion/src/modeledit/mixerslist.h @@ -20,54 +20,54 @@ #ifndef _MIXERSLIST_H_ #define _MIXERSLIST_H_ - -#include - -#define MIX_ROW_HEIGHT_INCREASE 8 //how much space is added above mixer row (for new channel), if 0 space adding is disabled -const int GroupHeaderRole = (Qt::UserRole+2); //defines new user role for list items. If value is > 0, then space is added before that item - -class MixersList : public QListWidget -{ - Q_OBJECT - - public: - explicit MixersList(QWidget *parent, bool expo); - void keyPressEvent(QKeyEvent *event); - void dropEvent(QDropEvent *event); - - signals: - void mimeDropped(int index, const QMimeData *data, Qt::DropAction action); - void keyWasPressed(QKeyEvent *event); - - public slots: - bool dropMimeData(int index, const QMimeData *data, Qt::DropAction action); - - protected: - virtual QStringList mimeTypes() const; - - private: - QPoint dragStartPosition; - bool expo; - -}; - -/** - @brief Provides sizing and painting of items for our mixes and inputs lists - - This class draws HTML formated strings into QListWidget class -*/ -class MixersDelegate : public QStyledItemDelegate -{ - Q_OBJECT - public: - inline MixersDelegate(QObject *parent) : QStyledItemDelegate(parent) {}; - - void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; - QSize sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const; - - private: - void SetupDocument(QTextDocument & doc, const QStyleOptionViewItem & options) const; - -}; - + +#include + +#define MIX_ROW_HEIGHT_INCREASE 8 //how much space is added above mixer row (for new channel), if 0 space adding is disabled +const int GroupHeaderRole = (Qt::UserRole+2); //defines new user role for list items. If value is > 0, then space is added before that item + +class MixersList : public QListWidget +{ + Q_OBJECT + + public: + explicit MixersList(QWidget *parent, bool expo); + void keyPressEvent(QKeyEvent *event); + void dropEvent(QDropEvent *event); + + signals: + void mimeDropped(int index, const QMimeData *data, Qt::DropAction action); + void keyWasPressed(QKeyEvent *event); + + public slots: + bool dropMimeData(int index, const QMimeData *data, Qt::DropAction action); + + protected: + virtual QStringList mimeTypes() const; + + private: + QPoint dragStartPosition; + bool expo; + +}; + +/** + @brief Provides sizing and painting of items for our mixes and inputs lists + + This class draws HTML formated strings into QListWidget class +*/ +class MixersDelegate : public QStyledItemDelegate +{ + Q_OBJECT + public: + inline MixersDelegate(QObject *parent) : QStyledItemDelegate(parent) {}; + + void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; + QSize sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const; + + private: + void SetupDocument(QTextDocument & doc, const QStyleOptionViewItem & options) const; + +}; + #endif // _MIXERSLIST_H_ diff --git a/companion/src/modeledit/mixes.h b/companion/src/modeledit/mixes.h index 437a646e4..a09444b20 100644 --- a/companion/src/modeledit/mixes.h +++ b/companion/src/modeledit/mixes.h @@ -20,63 +20,63 @@ #ifndef _MIXES_H_ #define _MIXES_H_ - -#include "modeledit.h" -#include "mixerslist.h" -#include "mixerdialog.h" -#include "modelprinter.h" - -class MixesPanel : public ModelPanel -{ - Q_OBJECT - - public: - MixesPanel(QWidget *parent, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); - virtual ~MixesPanel(); - - virtual void update(); - - private slots: - // TODO all slots? - void clearMixes(); - void mixersDelete(bool ask=true); - void mixersCut(); - void mixersCopy(); - void mixersPaste(); - void mixersDuplicate(); - void mixerOpen(); - void mixerAdd(); - void moveMixUp(); - void moveMixDown(); - void mixerHighlight(); - - - void mixerlistWidget_customContextMenuRequested(QPoint pos); - void mixerlistWidget_doubleClicked(QModelIndex index); - void mixerlistWidget_KeyPress(QKeyEvent *event); - - void mimeMixerDropped(int index, const QMimeData *data, Qt::DropAction action); - void pasteMixerMimeData(const QMimeData * mimeData, int destIdx); - - void mixesEdited(); - - private: - MixersList *MixerlistWidget; - bool mixInserted; - unsigned int highlightedSource; - bool firstLine; - ModelPrinter modelPrinter; - - int getMixerIndex(unsigned int dch); - bool gm_insertMix(int idx); - void gm_deleteMix(int index); - void gm_openMix(int index); - int gm_moveMix(int idx, bool dir); - void mixersDeleteList(QList list); - QList createMixListFromSelected(); - void setSelectedByMixList(QList list); - bool AddMixerLine(int dest); - QString getMixerText(int dest, bool * new_ch); -}; - + +#include "modeledit.h" +#include "mixerslist.h" +#include "mixerdialog.h" +#include "modelprinter.h" + +class MixesPanel : public ModelPanel +{ + Q_OBJECT + + public: + MixesPanel(QWidget *parent, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); + virtual ~MixesPanel(); + + virtual void update(); + + private slots: + // TODO all slots? + void clearMixes(); + void mixersDelete(bool ask=true); + void mixersCut(); + void mixersCopy(); + void mixersPaste(); + void mixersDuplicate(); + void mixerOpen(); + void mixerAdd(); + void moveMixUp(); + void moveMixDown(); + void mixerHighlight(); + + + void mixerlistWidget_customContextMenuRequested(QPoint pos); + void mixerlistWidget_doubleClicked(QModelIndex index); + void mixerlistWidget_KeyPress(QKeyEvent *event); + + void mimeMixerDropped(int index, const QMimeData *data, Qt::DropAction action); + void pasteMixerMimeData(const QMimeData * mimeData, int destIdx); + + void mixesEdited(); + + private: + MixersList *MixerlistWidget; + bool mixInserted; + unsigned int highlightedSource; + bool firstLine; + ModelPrinter modelPrinter; + + int getMixerIndex(unsigned int dch); + bool gm_insertMix(int idx); + void gm_deleteMix(int index); + void gm_openMix(int index); + int gm_moveMix(int idx, bool dir); + void mixersDeleteList(QList list); + QList createMixListFromSelected(); + void setSelectedByMixList(QList list); + bool AddMixerLine(int dest); + QString getMixerText(int dest, bool * new_ch); +}; + #endif // _MIXES_H_ diff --git a/companion/src/modeledit/modeledit.h b/companion/src/modeledit/modeledit.h index a8b03cdfc..9571536f3 100644 --- a/companion/src/modeledit/modeledit.h +++ b/companion/src/modeledit/modeledit.h @@ -20,55 +20,55 @@ #ifndef _MODELEDIT_H_ #define _MODELEDIT_H_ - -#include -#include "genericpanel.h" - -class RadioData; - -namespace Ui { - class ModelEdit; -} - -class ModelPanel : public GenericPanel -{ - public: - ModelPanel(QWidget *parent, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware): - GenericPanel(parent, &model, generalSettings, firmware) - { - } -}; - -class ModelEdit : public QDialog -{ - Q_OBJECT - - public: - ModelEdit(QWidget * parent, RadioData & radioData, int modelId, Firmware * firmware); - ~ModelEdit(); - - protected: - void closeEvent(QCloseEvent *event); - - signals: - void modified(); - - private slots: - void onTabModified(); - void on_pushButton_clicked(); - void on_tabWidget_currentChanged(int index); - - private: - Ui::ModelEdit *ui; - int modelId; - ModelData & model; - GeneralSettings & generalSettings; - Firmware * firmware; - QVector panels; - - void addTab(GenericPanel *panel, QString text); - void launchSimulation(); - -}; - + +#include +#include "genericpanel.h" + +class RadioData; + +namespace Ui { + class ModelEdit; +} + +class ModelPanel : public GenericPanel +{ + public: + ModelPanel(QWidget *parent, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware): + GenericPanel(parent, &model, generalSettings, firmware) + { + } +}; + +class ModelEdit : public QDialog +{ + Q_OBJECT + + public: + ModelEdit(QWidget * parent, RadioData & radioData, int modelId, Firmware * firmware); + ~ModelEdit(); + + protected: + void closeEvent(QCloseEvent *event); + + signals: + void modified(); + + private slots: + void onTabModified(); + void on_pushButton_clicked(); + void on_tabWidget_currentChanged(int index); + + private: + Ui::ModelEdit *ui; + int modelId; + ModelData & model; + GeneralSettings & generalSettings; + Firmware * firmware; + QVector panels; + + void addTab(GenericPanel *panel, QString text); + void launchSimulation(); + +}; + #endif // _MODELEDIT_H_ diff --git a/companion/src/modeledit/node.cpp b/companion/src/modeledit/node.cpp index 272453fc8..4cdbd1108 100644 --- a/companion/src/modeledit/node.cpp +++ b/companion/src/modeledit/node.cpp @@ -18,213 +18,213 @@ * GNU General Public License for more details. */ -#include -#include -#include -#include - -#include "edge.h" -#include "node.h" - -Node::Node(): - minX(-100), - maxX(+100) -{ - setFlag(ItemIsMovable); - setFlag(ItemSendsGeometryChanges); - setCacheMode(DeviceCoordinateCache); - setZValue(-1); - nodecolor = QColor(Qt::yellow); - bPressed = false; - centerX = true; - centerY = true; - fixedX = false; - fixedY = false; - ballSize = DEFAULT_BALL_SIZE; -} - -void Node::addEdge(Edge *edge) -{ - edgeList << edge; - edge->adjust(); -} - -void Node::stepToCenter(qreal step) -{ - if(scene() && !bPressed) - { - QRectF qr = scene()->sceneRect(); - qreal xStep = qr.width()/step; - qreal yStep = qr.height()/step; - - QPointF p = pos(); - if(centerX) - { - qreal x = qr.right() - qr.width()/2; +#include +#include +#include +#include + +#include "edge.h" +#include "node.h" + +Node::Node(): + minX(-100), + maxX(+100) +{ + setFlag(ItemIsMovable); + setFlag(ItemSendsGeometryChanges); + setCacheMode(DeviceCoordinateCache); + setZValue(-1); + nodecolor = QColor(Qt::yellow); + bPressed = false; + centerX = true; + centerY = true; + fixedX = false; + fixedY = false; + ballSize = DEFAULT_BALL_SIZE; +} + +void Node::addEdge(Edge *edge) +{ + edgeList << edge; + edge->adjust(); +} + +void Node::stepToCenter(qreal step) +{ + if(scene() && !bPressed) + { + QRectF qr = scene()->sceneRect(); + qreal xStep = qr.width()/step; + qreal yStep = qr.height()/step; + + QPointF p = pos(); + if(centerX) + { + qreal x = qr.right() - qr.width()/2; if(fabs(x-p.x())>xStep) - p.rx() += p.x()>x ? -xStep : xStep; - else - p.rx() = x; - } - - if(centerY) - { - qreal y = qr.bottom() - qr.height()/2; + p.rx() += p.x()>x ? -xStep : xStep; + else + p.rx() = x; + } + + if(centerY) + { + qreal y = qr.bottom() - qr.height()/2; if(fabs(y-p.y())>yStep) - p.ry() += p.y()>y ? -yStep : yStep; - else - p.ry() = y; - } - setPos(p); - } - -} - -void Node::setColor(const QColor & color) -{ - nodecolor=color; -} - - -void Node::setBallSize(int size) -{ - if(size>2) ballSize = size; -} - -qreal Node::getX() -{ - if(scene()) - { - QRectF rect = scene()->sceneRect(); - return 1+((x()-rect.right())*2/rect.width()); - } - return 0; -} - -void Node::setX(qreal newX) -{ - if(scene()) - { - QRectF rect = scene()->sceneRect(); - QGraphicsObject::setX(rect.left() + (newX+1) * rect.width()/2); - } -} - -qreal Node::getY() -{ - if(scene()) - { - QRectF rect = scene()->sceneRect(); - return 1+((y()-rect.bottom())*2/rect.height()); - } - return 0; -} - -void Node::setY(qreal newY) -{ - if(scene()) - { - QRectF rect = scene()->sceneRect(); - QGraphicsObject::setY(rect.top() + (newY+1) * rect.height()/2); - } -} - -QList Node::edges() const -{ - return edgeList; -} - -QRectF Node::boundingRect() const -{ - qreal adjust = 2; - return QRectF(-ballSize/2 - adjust, -ballSize/2 - adjust, - ballSize+BALL_HEIGHT + adjust, ballSize+BALL_HEIGHT + adjust); -} - - -QPainterPath Node::shape() const -{ - QPainterPath path; - path.addEllipse(-ballSize/2, -ballSize/2, ballSize, ballSize); - return path; -} - -void Node::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *) -{ - painter->setPen(Qt::NoPen); - painter->setBrush(Qt::darkGray); - painter->drawEllipse(-ballSize/2 + BALL_HEIGHT, -ballSize/2 + BALL_HEIGHT, ballSize, ballSize); - - QRadialGradient gradient(-BALL_HEIGHT, -BALL_HEIGHT, ballSize/2); - if (option->state & QStyle::State_Sunken) { - gradient.setCenter(BALL_HEIGHT, BALL_HEIGHT); - gradient.setFocalPoint(BALL_HEIGHT, BALL_HEIGHT); - gradient.setColorAt(1, nodecolor.light(180)); - gradient.setColorAt(0, nodecolor.light(120)); - } else { - gradient.setColorAt(0, nodecolor); - gradient.setColorAt(1, nodecolor.dark(120)); - } - painter->setBrush(gradient); - painter->setPen(QPen(Qt::black, 0)); - painter->drawEllipse(-ballSize/2, -ballSize/2, ballSize, ballSize); -} - -QVariant Node::itemChange(GraphicsItemChange change, const QVariant &value) -{ - switch (change) { - case ItemPositionChange: - if (scene()) - { - // value is the new position. - QPointF newPos = value.toPointF(); - QRectF rect = scene()->sceneRect(); - if(fixedX) newPos.setX(x());//make sure x doesn't change - if(fixedY) newPos.setY(y());//make sure x doesn't change - newPos.setX(qMin(rect.right(), qMax(newPos.x(), rect.left())));// bound X - newPos.setY(qMin(rect.bottom(), qMax(newPos.y(), rect.top())));// bound Y - - int newX = -100 + ( (newPos.x()-rect.left()) * 200) / rect.width(); - int newY = 100+(rect.top()-y())*200/rect.height(); - if (newX < minX) newX = minX; - if (newX > maxX) newX = maxX; - - if (!getFixedX()) { - newPos.setX(((newX+100)*rect.width()/200+rect.left())); - } - - emit moved(newX, newY); - return newPos; - } - break; - case ItemPositionHasChanged: - foreach (Edge *edge, edgeList) - edge->adjust(); - break; - default: - break; - }; - - return QGraphicsItem::itemChange(change, value); -} - -void Node::mousePressEvent(QGraphicsSceneMouseEvent *event) -{ - update(); - bPressed = true; - QGraphicsItem::mousePressEvent(event); - emit focus(); -} - -void Node::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) -{ - update(); - bPressed = false; - if (scene()) { - QGraphicsItem::mouseReleaseEvent(event); - emit unfocus(); - } - else { - QGraphicsItem::mouseReleaseEvent(event); - } -} + p.ry() += p.y()>y ? -yStep : yStep; + else + p.ry() = y; + } + setPos(p); + } + +} + +void Node::setColor(const QColor & color) +{ + nodecolor=color; +} + + +void Node::setBallSize(int size) +{ + if(size>2) ballSize = size; +} + +qreal Node::getX() +{ + if(scene()) + { + QRectF rect = scene()->sceneRect(); + return 1+((x()-rect.right())*2/rect.width()); + } + return 0; +} + +void Node::setX(qreal newX) +{ + if(scene()) + { + QRectF rect = scene()->sceneRect(); + QGraphicsObject::setX(rect.left() + (newX+1) * rect.width()/2); + } +} + +qreal Node::getY() +{ + if(scene()) + { + QRectF rect = scene()->sceneRect(); + return 1+((y()-rect.bottom())*2/rect.height()); + } + return 0; +} + +void Node::setY(qreal newY) +{ + if(scene()) + { + QRectF rect = scene()->sceneRect(); + QGraphicsObject::setY(rect.top() + (newY+1) * rect.height()/2); + } +} + +QList Node::edges() const +{ + return edgeList; +} + +QRectF Node::boundingRect() const +{ + qreal adjust = 2; + return QRectF(-ballSize/2 - adjust, -ballSize/2 - adjust, + ballSize+BALL_HEIGHT + adjust, ballSize+BALL_HEIGHT + adjust); +} + + +QPainterPath Node::shape() const +{ + QPainterPath path; + path.addEllipse(-ballSize/2, -ballSize/2, ballSize, ballSize); + return path; +} + +void Node::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *) +{ + painter->setPen(Qt::NoPen); + painter->setBrush(Qt::darkGray); + painter->drawEllipse(-ballSize/2 + BALL_HEIGHT, -ballSize/2 + BALL_HEIGHT, ballSize, ballSize); + + QRadialGradient gradient(-BALL_HEIGHT, -BALL_HEIGHT, ballSize/2); + if (option->state & QStyle::State_Sunken) { + gradient.setCenter(BALL_HEIGHT, BALL_HEIGHT); + gradient.setFocalPoint(BALL_HEIGHT, BALL_HEIGHT); + gradient.setColorAt(1, nodecolor.light(180)); + gradient.setColorAt(0, nodecolor.light(120)); + } else { + gradient.setColorAt(0, nodecolor); + gradient.setColorAt(1, nodecolor.dark(120)); + } + painter->setBrush(gradient); + painter->setPen(QPen(Qt::black, 0)); + painter->drawEllipse(-ballSize/2, -ballSize/2, ballSize, ballSize); +} + +QVariant Node::itemChange(GraphicsItemChange change, const QVariant &value) +{ + switch (change) { + case ItemPositionChange: + if (scene()) + { + // value is the new position. + QPointF newPos = value.toPointF(); + QRectF rect = scene()->sceneRect(); + if(fixedX) newPos.setX(x());//make sure x doesn't change + if(fixedY) newPos.setY(y());//make sure x doesn't change + newPos.setX(qMin(rect.right(), qMax(newPos.x(), rect.left())));// bound X + newPos.setY(qMin(rect.bottom(), qMax(newPos.y(), rect.top())));// bound Y + + int newX = -100 + ( (newPos.x()-rect.left()) * 200) / rect.width(); + int newY = 100+(rect.top()-y())*200/rect.height(); + if (newX < minX) newX = minX; + if (newX > maxX) newX = maxX; + + if (!getFixedX()) { + newPos.setX(((newX+100)*rect.width()/200+rect.left())); + } + + emit moved(newX, newY); + return newPos; + } + break; + case ItemPositionHasChanged: + foreach (Edge *edge, edgeList) + edge->adjust(); + break; + default: + break; + }; + + return QGraphicsItem::itemChange(change, value); +} + +void Node::mousePressEvent(QGraphicsSceneMouseEvent *event) +{ + update(); + bPressed = true; + QGraphicsItem::mousePressEvent(event); + emit focus(); +} + +void Node::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) +{ + update(); + bPressed = false; + if (scene()) { + QGraphicsItem::mouseReleaseEvent(event); + emit unfocus(); + } + else { + QGraphicsItem::mouseReleaseEvent(event); + } +} diff --git a/companion/src/modeledit/node.h b/companion/src/modeledit/node.h index 5222673fb..b58437c01 100644 --- a/companion/src/modeledit/node.h +++ b/companion/src/modeledit/node.h @@ -20,72 +20,72 @@ #ifndef _NODE_H_ #define _NODE_H_ - -#include - -#define DEFAULT_BALL_SIZE 10 -#define BALL_HEIGHT 2 - -class Edge; -QT_BEGIN_NAMESPACE -class QGraphicsSceneMouseEvent; -QT_END_NAMESPACE - -class Node : public QGraphicsObject -{ - Q_OBJECT - - public: - Node(); - - void addEdge(Edge *edge); - QList edges() const; - - enum { Type = UserType + 1 }; - int type() const { return Type; } - QRectF boundingRect() const; - QPainterPath shape() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - void setBallSize(int size); - void stepToCenter(qreal step=10); - int getBallSize() {return ballSize;} - qreal getX(); - qreal getY(); - void setX(qreal newX); - void setY(qreal newX); - - void setCenteringX(bool val) {centerX = val;} - void setCenteringY(bool val) {centerY = val;} - void setFixedX(bool val) {fixedX = val;} - void setFixedY(bool val) {fixedY = val;} - bool getFixedX() {return fixedX;} - bool getFixedY() {return fixedY;} - void setMinX(int val) {minX = val;}; - void setMaxX(int val) {maxX = val;}; - void setColor(const QColor & color); - - signals: - void moved(int x, int y); - void focus(); - void unfocus(); - - protected: - QVariant itemChange(GraphicsItemChange change, const QVariant &value); - void mousePressEvent(QGraphicsSceneMouseEvent *event); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); - - private: - bool bPressed; - bool centerX; - bool centerY; - bool fixedX; - bool fixedY; - int ballSize; - int minX; - int maxX; - QList edgeList; - QPointF newPos; - QColor nodecolor; -}; - + +#include + +#define DEFAULT_BALL_SIZE 10 +#define BALL_HEIGHT 2 + +class Edge; +QT_BEGIN_NAMESPACE +class QGraphicsSceneMouseEvent; +QT_END_NAMESPACE + +class Node : public QGraphicsObject +{ + Q_OBJECT + + public: + Node(); + + void addEdge(Edge *edge); + QList edges() const; + + enum { Type = UserType + 1 }; + int type() const { return Type; } + QRectF boundingRect() const; + QPainterPath shape() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void setBallSize(int size); + void stepToCenter(qreal step=10); + int getBallSize() {return ballSize;} + qreal getX(); + qreal getY(); + void setX(qreal newX); + void setY(qreal newX); + + void setCenteringX(bool val) {centerX = val;} + void setCenteringY(bool val) {centerY = val;} + void setFixedX(bool val) {fixedX = val;} + void setFixedY(bool val) {fixedY = val;} + bool getFixedX() {return fixedX;} + bool getFixedY() {return fixedY;} + void setMinX(int val) {minX = val;}; + void setMaxX(int val) {maxX = val;}; + void setColor(const QColor & color); + + signals: + void moved(int x, int y); + void focus(); + void unfocus(); + + protected: + QVariant itemChange(GraphicsItemChange change, const QVariant &value); + void mousePressEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + + private: + bool bPressed; + bool centerX; + bool centerY; + bool fixedX; + bool fixedY; + int ballSize; + int minX; + int maxX; + QList edgeList; + QPointF newPos; + QColor nodecolor; +}; + #endif // _NODE_H_ diff --git a/companion/src/modeledit/setup.h b/companion/src/modeledit/setup.h index bc454973b..8bfe789d3 100644 --- a/companion/src/modeledit/setup.h +++ b/companion/src/modeledit/setup.h @@ -20,127 +20,127 @@ #ifndef _SETUP_H_ #define _SETUP_H_ - -#include "modeledit.h" -#include "eeprominterface.h" - -namespace Ui { - class Setup; - class Timer; - class Module; -} - -class TimerPanel : public ModelPanel -{ - Q_OBJECT - - public: - TimerPanel(QWidget *parent, ModelData & model, TimerData & timer, GeneralSettings & generalSettings, Firmware * firmware, QWidget *prevFocus); - virtual ~TimerPanel(); - - virtual void update(); - QWidget * getLastFocus(); - - private slots: - void on_mode_currentIndexChanged(int index); - void on_value_editingFinished(); - void on_minuteBeep_toggled(bool checked); - void on_name_editingFinished(); - - private: - TimerData & timer; - Ui::Timer *ui; -}; - -class ModulePanel : public ModelPanel -{ - static const int maxChannels = 16; - - struct ChannelFailsafeWidgetsGroup { - QComboBox * combo; - QDoubleSpinBox * spinbox; - QLabel * label; - }; - - Q_OBJECT - - public: - ModulePanel(QWidget *parent, ModelData & model, ModuleData & module, GeneralSettings & generalSettings, Firmware * firmware, int moduleIdx); - virtual ~ModulePanel(); - virtual void update(); - - protected: - void updateFailsafe(int channel); - - private slots: - void on_trainerMode_currentIndexChanged(int index); - void on_protocol_currentIndexChanged(int index); - void on_ppmDelay_editingFinished(); - void on_channelsCount_editingFinished(); - void on_channelsStart_editingFinished(); - void on_ppmPolarity_currentIndexChanged(int index); - void on_ppmOutputType_currentIndexChanged(int index); - void on_ppmFrameLength_editingFinished(); - void on_rxNumber_editingFinished(); - void on_failsafeMode_currentIndexChanged(int value); - void onFailsafeComboIndexChanged(int index); - void onFailsafeSpinChanged(double value); - void on_multiProtocol_currentIndexChanged(int index); - void on_multiSubType_currentIndexChanged(int index); - void on_autoBind_stateChanged(int state); - void on_lowPower_stateChanged(int state); - - private: - ModuleData & module; - int moduleIdx; - Ui::Module *ui; - ChannelFailsafeWidgetsGroup failsafeGroups[maxChannels]; -}; - -class SetupPanel : public ModelPanel -{ - Q_OBJECT - - public: - SetupPanel(QWidget *parent, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); - virtual ~SetupPanel(); - - virtual void update(); - - signals: - void extendedLimitsToggled(); - - private slots: - void on_name_editingFinished(); - void on_throttleSource_currentIndexChanged(int index); - void on_throttleTrim_toggled(bool checked); - void on_extendedLimits_toggled(bool checked); - void on_extendedTrims_toggled(bool checked); - void on_throttleWarning_toggled(bool checked); - void on_throttleReverse_toggled(bool checked); - void on_displayText_toggled(bool checked); - void on_gfEnabled_toggled(bool checked); - void on_image_currentIndexChanged(int index); - void on_trimIncrement_currentIndexChanged(int index); - void onBeepCenterToggled(bool checked); - void startupSwitchEdited(int value); - void startupSwitchToggled(bool checked); - void potWarningToggled(bool checked); - void on_potWarningMode_currentIndexChanged(int index); - void onChildModified(); - - private: - Ui::Setup *ui; - QVector startupSwitchesSliders; - QVector startupSwitchesCheckboxes; - QVector potWarningCheckboxes; - QVector centerBeepCheckboxes; - ModulePanel * modules[CPN_MAX_MODULES+1]; - TimerPanel * timers[CPN_MAX_TIMERS]; - void updateStartupSwitches(); - void updatePotWarnings(); - void updateBeepCenter(); - void populateThrottleSourceCB(); -}; - + +#include "modeledit.h" +#include "eeprominterface.h" + +namespace Ui { + class Setup; + class Timer; + class Module; +} + +class TimerPanel : public ModelPanel +{ + Q_OBJECT + + public: + TimerPanel(QWidget *parent, ModelData & model, TimerData & timer, GeneralSettings & generalSettings, Firmware * firmware, QWidget *prevFocus); + virtual ~TimerPanel(); + + virtual void update(); + QWidget * getLastFocus(); + + private slots: + void on_mode_currentIndexChanged(int index); + void on_value_editingFinished(); + void on_minuteBeep_toggled(bool checked); + void on_name_editingFinished(); + + private: + TimerData & timer; + Ui::Timer *ui; +}; + +class ModulePanel : public ModelPanel +{ + static const int maxChannels = 16; + + struct ChannelFailsafeWidgetsGroup { + QComboBox * combo; + QDoubleSpinBox * spinbox; + QLabel * label; + }; + + Q_OBJECT + + public: + ModulePanel(QWidget *parent, ModelData & model, ModuleData & module, GeneralSettings & generalSettings, Firmware * firmware, int moduleIdx); + virtual ~ModulePanel(); + virtual void update(); + + protected: + void updateFailsafe(int channel); + + private slots: + void on_trainerMode_currentIndexChanged(int index); + void on_protocol_currentIndexChanged(int index); + void on_ppmDelay_editingFinished(); + void on_channelsCount_editingFinished(); + void on_channelsStart_editingFinished(); + void on_ppmPolarity_currentIndexChanged(int index); + void on_ppmOutputType_currentIndexChanged(int index); + void on_ppmFrameLength_editingFinished(); + void on_rxNumber_editingFinished(); + void on_failsafeMode_currentIndexChanged(int value); + void onFailsafeComboIndexChanged(int index); + void onFailsafeSpinChanged(double value); + void on_multiProtocol_currentIndexChanged(int index); + void on_multiSubType_currentIndexChanged(int index); + void on_autoBind_stateChanged(int state); + void on_lowPower_stateChanged(int state); + + private: + ModuleData & module; + int moduleIdx; + Ui::Module *ui; + ChannelFailsafeWidgetsGroup failsafeGroups[maxChannels]; +}; + +class SetupPanel : public ModelPanel +{ + Q_OBJECT + + public: + SetupPanel(QWidget *parent, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); + virtual ~SetupPanel(); + + virtual void update(); + + signals: + void extendedLimitsToggled(); + + private slots: + void on_name_editingFinished(); + void on_throttleSource_currentIndexChanged(int index); + void on_throttleTrim_toggled(bool checked); + void on_extendedLimits_toggled(bool checked); + void on_extendedTrims_toggled(bool checked); + void on_throttleWarning_toggled(bool checked); + void on_throttleReverse_toggled(bool checked); + void on_displayText_toggled(bool checked); + void on_gfEnabled_toggled(bool checked); + void on_image_currentIndexChanged(int index); + void on_trimIncrement_currentIndexChanged(int index); + void onBeepCenterToggled(bool checked); + void startupSwitchEdited(int value); + void startupSwitchToggled(bool checked); + void potWarningToggled(bool checked); + void on_potWarningMode_currentIndexChanged(int index); + void onChildModified(); + + private: + Ui::Setup *ui; + QVector startupSwitchesSliders; + QVector startupSwitchesCheckboxes; + QVector potWarningCheckboxes; + QVector centerBeepCheckboxes; + ModulePanel * modules[CPN_MAX_MODULES+1]; + TimerPanel * timers[CPN_MAX_TIMERS]; + void updateStartupSwitches(); + void updatePotWarnings(); + void updateBeepCenter(); + void populateThrottleSourceCB(); +}; + #endif // _SETUP_H_ diff --git a/companion/src/modeledit/telemetry.h b/companion/src/modeledit/telemetry.h index f43a72a63..3c9233177 100644 --- a/companion/src/modeledit/telemetry.h +++ b/companion/src/modeledit/telemetry.h @@ -20,147 +20,147 @@ #ifndef _TELEMETRY_H_ #define _TELEMETRY_H_ - -#include "modeledit.h" -#include "eeprominterface.h" - -class AutoComboBox; - -namespace Ui { - class TelemetryAnalog; - class TelemetryCustomScreen; - class TelemetrySensor; - class Telemetry; -} - -class TelemetryAnalog: public ModelPanel -{ - Q_OBJECT - - friend class TelemetryPanel; - - public: - TelemetryAnalog(QWidget *parent, FrSkyChannelData & analog, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); - virtual ~TelemetryAnalog(); - - signals: - void modified(); - - private slots: - void on_UnitCB_currentIndexChanged(int index); - void on_RatioSB_editingFinished(); - void on_RatioSB_valueChanged(); - void on_CalibSB_editingFinished(); - void on_alarm1LevelCB_currentIndexChanged(int index); - void on_alarm1GreaterCB_currentIndexChanged(int index); - void on_alarm1ValueSB_editingFinished(); - void on_alarm2LevelCB_currentIndexChanged(int index); - void on_alarm2GreaterCB_currentIndexChanged(int index); - void on_alarm2ValueSB_editingFinished(); - - private: - Ui::TelemetryAnalog *ui; - FrSkyChannelData & analog; - bool lock; - - void update(); -}; - -class TelemetryCustomScreen: public ModelPanel -{ - Q_OBJECT - - public: - TelemetryCustomScreen(QWidget *parent, ModelData & model, FrSkyScreenData & screen, GeneralSettings & generalSettings, Firmware * firmware); - ~TelemetryCustomScreen(); - void update(); - - private slots: - void on_screenType_currentIndexChanged(int index); - void scriptNameEdited(); - void customFieldChanged(int index); - void barSourceChanged(int index); - void barMinChanged(double value); - void barMaxChanged(double value); - - protected: - void populateTelemetrySourceCB(QComboBox * b, RawSource & source, bool last=false); - - private: - void updateBar(int line); - Ui::TelemetryCustomScreen * ui; - FrSkyScreenData & screen; - QComboBox * fieldsCB[4][3]; - QComboBox * barsCB[4]; - QDoubleSpinBox * minSB[4]; - QDoubleSpinBox * maxSB[4]; -}; - -class TelemetrySensorPanel: public ModelPanel -{ - Q_OBJECT - - public: - TelemetrySensorPanel(QWidget *parent, SensorData & sensor, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); - ~TelemetrySensorPanel(); - void update(); - - signals: - void dataModified(); - - protected slots: - void on_name_editingFinished(); - void on_type_currentIndexChanged(int index); - void on_formula_currentIndexChanged(int index); - void on_unit_currentIndexChanged(int index); - void on_prec_valueChanged(double value); - - protected: - void updateSourcesComboBox(AutoComboBox * cb, bool negative); - - private: - Ui::TelemetrySensor * ui; - SensorData & sensor; - bool lock; -}; - -class TelemetryPanel : public ModelPanel -{ - Q_OBJECT - - public: - TelemetryPanel(QWidget *parent, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); - virtual ~TelemetryPanel(); - virtual void update(); - - private slots: - void on_telemetryProtocol_currentIndexChanged(int index); - void onModified(); - void on_frskyProtoCB_currentIndexChanged(int index); - void on_bladesCount_editingFinished(); - void on_rssiAlarm1CB_currentIndexChanged(int index); - void on_rssiAlarm2CB_currentIndexChanged(int index); - void on_rssiAlarm1SB_editingFinished(); - void on_rssiAlarm2SB_editingFinished(); - void on_varioLimitMin_DSB_editingFinished(); - void on_varioLimitMax_DSB_editingFinished(); - void on_varioLimitCenterMin_DSB_editingFinished(); - void on_varioLimitCenterMax_DSB_editingFinished(); - void on_fasOffset_DSB_editingFinished(); - void on_mahCount_SB_editingFinished(); - void on_mahCount_ChkB_toggled(bool checked); - - private: - Ui::Telemetry *ui; - TelemetryAnalog * analogs[4]; - TelemetryCustomScreen * telemetryCustomScreens[4]; - TelemetrySensorPanel * sensorPanels[CPN_MAX_SENSORS]; - - void setup(); - void telBarUpdate(); - void populateVoltsSource(); - void populateCurrentSource(); - void populateVarioSource(); -}; - + +#include "modeledit.h" +#include "eeprominterface.h" + +class AutoComboBox; + +namespace Ui { + class TelemetryAnalog; + class TelemetryCustomScreen; + class TelemetrySensor; + class Telemetry; +} + +class TelemetryAnalog: public ModelPanel +{ + Q_OBJECT + + friend class TelemetryPanel; + + public: + TelemetryAnalog(QWidget *parent, FrSkyChannelData & analog, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); + virtual ~TelemetryAnalog(); + + signals: + void modified(); + + private slots: + void on_UnitCB_currentIndexChanged(int index); + void on_RatioSB_editingFinished(); + void on_RatioSB_valueChanged(); + void on_CalibSB_editingFinished(); + void on_alarm1LevelCB_currentIndexChanged(int index); + void on_alarm1GreaterCB_currentIndexChanged(int index); + void on_alarm1ValueSB_editingFinished(); + void on_alarm2LevelCB_currentIndexChanged(int index); + void on_alarm2GreaterCB_currentIndexChanged(int index); + void on_alarm2ValueSB_editingFinished(); + + private: + Ui::TelemetryAnalog *ui; + FrSkyChannelData & analog; + bool lock; + + void update(); +}; + +class TelemetryCustomScreen: public ModelPanel +{ + Q_OBJECT + + public: + TelemetryCustomScreen(QWidget *parent, ModelData & model, FrSkyScreenData & screen, GeneralSettings & generalSettings, Firmware * firmware); + ~TelemetryCustomScreen(); + void update(); + + private slots: + void on_screenType_currentIndexChanged(int index); + void scriptNameEdited(); + void customFieldChanged(int index); + void barSourceChanged(int index); + void barMinChanged(double value); + void barMaxChanged(double value); + + protected: + void populateTelemetrySourceCB(QComboBox * b, RawSource & source, bool last=false); + + private: + void updateBar(int line); + Ui::TelemetryCustomScreen * ui; + FrSkyScreenData & screen; + QComboBox * fieldsCB[4][3]; + QComboBox * barsCB[4]; + QDoubleSpinBox * minSB[4]; + QDoubleSpinBox * maxSB[4]; +}; + +class TelemetrySensorPanel: public ModelPanel +{ + Q_OBJECT + + public: + TelemetrySensorPanel(QWidget *parent, SensorData & sensor, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); + ~TelemetrySensorPanel(); + void update(); + + signals: + void dataModified(); + + protected slots: + void on_name_editingFinished(); + void on_type_currentIndexChanged(int index); + void on_formula_currentIndexChanged(int index); + void on_unit_currentIndexChanged(int index); + void on_prec_valueChanged(double value); + + protected: + void updateSourcesComboBox(AutoComboBox * cb, bool negative); + + private: + Ui::TelemetrySensor * ui; + SensorData & sensor; + bool lock; +}; + +class TelemetryPanel : public ModelPanel +{ + Q_OBJECT + + public: + TelemetryPanel(QWidget *parent, ModelData & model, GeneralSettings & generalSettings, Firmware * firmware); + virtual ~TelemetryPanel(); + virtual void update(); + + private slots: + void on_telemetryProtocol_currentIndexChanged(int index); + void onModified(); + void on_frskyProtoCB_currentIndexChanged(int index); + void on_bladesCount_editingFinished(); + void on_rssiAlarm1CB_currentIndexChanged(int index); + void on_rssiAlarm2CB_currentIndexChanged(int index); + void on_rssiAlarm1SB_editingFinished(); + void on_rssiAlarm2SB_editingFinished(); + void on_varioLimitMin_DSB_editingFinished(); + void on_varioLimitMax_DSB_editingFinished(); + void on_varioLimitCenterMin_DSB_editingFinished(); + void on_varioLimitCenterMax_DSB_editingFinished(); + void on_fasOffset_DSB_editingFinished(); + void on_mahCount_SB_editingFinished(); + void on_mahCount_ChkB_toggled(bool checked); + + private: + Ui::Telemetry *ui; + TelemetryAnalog * analogs[4]; + TelemetryCustomScreen * telemetryCustomScreens[4]; + TelemetrySensorPanel * sensorPanels[CPN_MAX_SENSORS]; + + void setup(); + void telBarUpdate(); + void populateVoltsSource(); + void populateCurrentSource(); + void populateVarioSource(); +}; + #endif // _TELEMETRY_H_ diff --git a/companion/src/modeledit/templates.h b/companion/src/modeledit/templates.h index b98da5b86..a3e1af8fd 100644 --- a/companion/src/modeledit/templates.h +++ b/companion/src/modeledit/templates.h @@ -20,24 +20,24 @@ #ifndef _TEMPLATES_H_ #define _TEMPLATES_H_ - -#include -#include "eeprominterface.h" - -class Templates : public QWidget -{ - Q_OBJECT - - public: - Templates(QWidget *parent, ModelData & model); - ~Templates(); - - private slots: - void onDoubleClicked(QModelIndex index); - - private: - void applyNumericTemplate(uint64_t tpl); - ModelData & model; -}; - + +#include +#include "eeprominterface.h" + +class Templates : public QWidget +{ + Q_OBJECT + + public: + Templates(QWidget *parent, ModelData & model); + ~Templates(); + + private slots: + void onDoubleClicked(QModelIndex index); + + private: + void applyNumericTemplate(uint64_t tpl); + ModelData & model; +}; + #endif // _TEMPLATES_H_ diff --git a/companion/src/modelslist.cpp b/companion/src/modelslist.cpp index 5ce847075..3a7b1da6e 100644 --- a/companion/src/modelslist.cpp +++ b/companion/src/modelslist.cpp @@ -18,533 +18,533 @@ * GNU General Public License for more details. */ -#include "modelslist.h" -#include "mdichild.h" -#include "helpers.h" - -class DragDropHeader { - public: - DragDropHeader(): - general_settings(false), - models_count(0) - { - } - bool general_settings; - uint8_t models_count; - uint8_t models[CPN_MAX_MODELS]; -}; - -ModelsListWidget::ModelsListWidget(QWidget *parent): - QListWidget(parent) -{ - setFont(QFont("Courier New",12)); - radioData = &((MdiChild *)parent)->radioData; - refreshList(); - - connect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(OpenEditWindow())); - connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(ShowContextMenu(const QPoint&))); - connect(this, SIGNAL(currentRowChanged(int)), this, SLOT(viableModelSelected(int))); - - setContextMenuPolicy(Qt::CustomContextMenu); - setSelectionMode(QAbstractItemView::ExtendedSelection); - setDragEnabled(true); - setAcceptDrops(true); - setDragDropOverwriteMode(true); - setDropIndicatorShown(true); - - active_highlight_color = palette().color(QPalette::Active, QPalette::Highlight); -} - -void ModelsListWidget::ShowContextMenu(const QPoint& pos) -{ - QPoint globalPos = this->mapToGlobal(pos); - QMenu contextMenu; - if (((MdiChild *)parent())->getCurrentRow() > 0) { - // context menu for model - const QClipboard *clipboard = QApplication::clipboard(); - const QMimeData *mimeData = clipboard->mimeData(); - bool hasData = mimeData->hasFormat("application/x-companion"); - - contextMenu.addAction(CompanionIcon("edit.png"), tr("&Edit"),this,SLOT(EditModel())); - contextMenu.addAction(CompanionIcon("open.png"), tr("&Restore from backup"),this,SLOT(LoadBackup())); - contextMenu.addAction(CompanionIcon("wizard.png"), tr("&Model Wizard"),this,SLOT(OpenWizard())); - contextMenu.addSeparator(); - contextMenu.addAction(CompanionIcon("clear.png"), tr("&Delete"),this,SLOT(confirmDelete()),tr("Delete")); - contextMenu.addAction(CompanionIcon("copy.png"), tr("&Copy"),this,SLOT(copy()),tr("Ctrl+C")); - contextMenu.addAction(CompanionIcon("cut.png"), tr("&Cut"),this,SLOT(cut()),tr("Ctrl+X")); - contextMenu.addAction(CompanionIcon("paste.png"), tr("&Paste"),this,SLOT(paste()),tr("Ctrl+V"))->setEnabled(hasData); - contextMenu.addAction(CompanionIcon("duplicate.png"), tr("D&uplicate"),this,SLOT(duplicate()),tr("Ctrl+U")); - contextMenu.addSeparator(); - contextMenu.addAction(CompanionIcon("currentmodel.png"), tr("&Use as default"),this,SLOT(setdefault())); - contextMenu.addSeparator(); - contextMenu.addAction(CompanionIcon("print.png"), tr("P&rint model"),this, SLOT(print()),QKeySequence(tr("Ctrl+P"))); - contextMenu.addSeparator(); - contextMenu.addAction(CompanionIcon("simulate.png"), tr("&Simulate model"),this, SLOT(simulate()),tr("Alt+S")); - } - else { - // context menu for radio settings - contextMenu.addAction(CompanionIcon("edit.png"), tr("&Edit"),this,SLOT(EditModel())); - } - contextMenu.exec(globalPos); -} - -void ModelsListWidget::EditModel() -{ - ((MdiChild *)parent())->modelEdit(); -} - -void ModelsListWidget::OpenEditWindow() -{ - ((MdiChild *)parent())->openEditWindow(); -} - -void ModelsListWidget::OpenWizard() -{ - ((MdiChild *)parent())->wizardEdit(); -} - -void ModelsListWidget::LoadBackup() -{ - ((MdiChild *)parent())->loadBackup(); -} - -void ModelsListWidget::simulate() -{ - ((MdiChild *)parent())->simulate(); -} - -void ModelsListWidget::print() -{ - ((MdiChild *)parent())->print(); -} - -void ModelsListWidget::setdefault() -{ - if (currentRow()==0) return; - unsigned int currModel = currentRow() - 1; - if (!radioData->models[currModel].isEmpty() && radioData->generalSettings.currModel != currModel) { - radioData->generalSettings.currModel = currModel; - refreshList(); - ((MdiChild *)parent())->setModified(); - } -} - - -void ModelsListWidget::mousePressEvent(QMouseEvent *event) -{ - if (event->button() == Qt::LeftButton) - dragStartPosition = event->pos(); - - QListWidget::mousePressEvent(event); -} - -void ModelsListWidget::mouseMoveEvent(QMouseEvent *event) -{ - if (!(event->buttons() & Qt::LeftButton)) - return; - if ((event->pos() - dragStartPosition).manhattanLength() - < QApplication::startDragDistance()) - return; - - QDrag *drag = new QDrag(this); - - QByteArray gmData; - doCopy(&gmData); - - QMimeData *mimeData = new QMimeData; - mimeData->setData("application/x-companion", gmData); - - drag->setMimeData(mimeData); - - //Qt::DropAction dropAction = - drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::CopyAction); - - //if(dropAction==Qt::MoveAction) - - // QListWidget::mouseMoveEvent(event); -} - -void ModelsListWidget::saveSelection() -{ - currentSelection.current_item = currentItem(); - for (int i=0; igetMaxModels()+1; ++i) - currentSelection.selected[i] = item(i)->isSelected(); -} - -void ModelsListWidget::restoreSelection() -{ - setCurrentItem(currentSelection.current_item); - for (int i=0; igetMaxModels()+1; ++i) - item(i)->setSelected(currentSelection.selected[i]); -} - -void ModelsListWidget::dragEnterEvent(QDragEnterEvent *event) -{ - if (event->mimeData()->hasFormat("application/x-companion")) - { - event->acceptProposedAction(); - saveSelection(); - } -} - -void ModelsListWidget::dragLeaveEvent(QDragLeaveEvent *) -{ - restoreSelection(); -} - -void ModelsListWidget::dragMoveEvent(QDragMoveEvent *event) -{ - int row=this->indexAt(event->pos()).row(); - const QMimeData *mimeData = event->mimeData(); - if (mimeData->hasFormat("application/x-companion")) - { - QByteArray gmData = mimeData->data("application/x-companion"); - event->acceptProposedAction(); - clearSelection(); - DragDropHeader *header = (DragDropHeader *)gmData.data(); - if (row >= 0) { - if (header->general_settings) - item(0)->setSelected(true); - for (int i=row, end=std::min(GetEepromInterface()->getMaxModels()+1, row+header->models_count); isetSelected(true); - } - } -} - -void ModelsListWidget::dropEvent(QDropEvent *event) -{ - int row = this->indexAt(event->pos()).row(); - if (row < 0) - return; - - // QMessageBox::warning(this, tr("Companion"),tr("Index :%1").arg(row)); - const QMimeData *mimeData = event->mimeData(); - - if(mimeData->hasFormat("application/x-companion")) - { - QByteArray gmData = mimeData->data("application/x-companion"); - if (event->source() && event->dropAction() == Qt::MoveAction) - ((ModelsListWidget*)event->source())->doCut(&gmData); - doPaste(&gmData, row); - clearSelection(); - setCurrentItem(item(row)); - DragDropHeader *header = (DragDropHeader *)gmData.data(); - if (header->general_settings) - item(0)->setSelected(true); - for (int i=row, end=std::min(GetEepromInterface()->getMaxModels()+1, row+header->models_count); isetSelected(true); - } - event->acceptProposedAction(); -} - -#ifndef WIN32 -void ModelsListWidget::focusInEvent ( QFocusEvent * event ) -{ - QListWidget::focusInEvent(event); - QPalette palette = this->palette(); - palette.setColor(QPalette::Active, QPalette::Highlight, active_highlight_color); - palette.setColor(QPalette::Inactive, QPalette::Highlight, active_highlight_color); - this->setPalette(palette); -} - -void ModelsListWidget::focusOutEvent ( QFocusEvent * event ) -{ - QListWidget::focusOutEvent(event); - QPalette palette = this->palette(); - palette.setColor(QPalette::Active, QPalette::Highlight, palette.color(QPalette::Active, QPalette::Midlight)); - palette.setColor(QPalette::Inactive, QPalette::Highlight, palette.color(QPalette::Active, QPalette::Midlight)); - this->setPalette(palette); -} -#endif - -void ModelsListWidget::refreshList() -{ - clear(); - addItem(tr("General Settings")); - - EEPROMInterface * eepromInterface = GetEepromInterface(); - BoardEnum board = eepromInterface->getBoard(); - - // TODO here we calculate the size used by the RLE format, this is clearly not the right place to do that... - int availableEEpromSize = eepromInterface->getEEpromSize() - 64; // let's consider fat - div_t divresult = div(eepromInterface->getSize(radioData->generalSettings), 15); - divresult.quot += (divresult.rem != 0 ? 1 : 0); - availableEEpromSize -= divresult.quot*16; - - for (uint8_t i=0; igetMaxModels(); i++) { - QString item = QString().sprintf("%02d: ", i+1); - if (!radioData->models[i].isEmpty()) { - QString modelName; - if (strlen(radioData->models[i].name) > 0) - modelName = radioData->models[i].name; - else - modelName = QString().sprintf("Model%02d", i+1); - item += modelName; - if (!IS_SKY9X(board) && !IS_HORUS(board)) { - item += QString(GetCurrentFirmware()->getCapability(ModelName)-modelName.size(), ' '); - int size = eepromInterface->getSize(radioData->models[i]); - item += QString().sprintf("%5d", size); - divresult = div(size, 15); - divresult.quot += (divresult.rem != 0 ? 1 : 0); - availableEEpromSize -= divresult.quot*16; - if (i == radioData->generalSettings.currModel) { - // TODO why? - availableEEpromSize -= divresult.quot*16; - } - } - } - addItem(item); - } - - if (radioData->generalSettings.currModel < (unsigned int)eepromInterface->getMaxModels()) { - QFont f = QFont("Courier New", 12); - f.setBold(true); - this->item(radioData->generalSettings.currModel+1)->setFont(f); - } - - if (!IS_SKY9X(board) && !IS_HORUS(board)) { - ((MdiChild*)parent())->setEEpromAvail((availableEEpromSize/16)*15); - } -} - -void ModelsListWidget::cut() -{ - copy(); - deleteSelected(false); -} - -void ModelsListWidget::confirmDelete() { - deleteSelected(true); -} - - -void ModelsListWidget::deleteSelected(bool ask=true) -{ - bool isModel=false; - unsigned int selModel; - QMessageBox::StandardButton ret = QMessageBox::Yes; - if(ask) { - foreach(QModelIndex index, this->selectionModel()->selectedIndexes()) { - if (index.row()>0 && !radioData->models[index.row()-1].isEmpty()) { - isModel=true; - selModel=index.row()-1; - } - } - if (isModel==true) { - if (radioData->generalSettings.currModel != selModel) { - ret = QMessageBox::warning(this, "Companion", tr("Delete Selected Models?"), QMessageBox::Yes | QMessageBox::No); - } else { - ret = QMessageBox::warning(this, "Companion", tr("Cannot delete default model."), QMessageBox::Ok); - } - } - } - if (ret == QMessageBox::Yes) { - foreach(QModelIndex index, this->selectionModel()->selectedIndexes()) { - if (index.row()>0 && radioData->generalSettings.currModel!=(unsigned int)(index.row()-1)) { - radioData->models[index.row()-1].clear(); - ((MdiChild *)parent())->setModified(); - } else if (index.row()>0) { - if (ask) { - ret = QMessageBox::warning(this, "Companion", tr("Cannot delete default model."), QMessageBox::Ok); - } else { - ret = QMessageBox::warning(this, "Companion", tr("Cannot cut default model."), QMessageBox::Ok); - } - } - } - } -} - -void ModelsListWidget::doCut(QByteArray *gmData) -{ - bool modified=false; - DragDropHeader *header = (DragDropHeader *)gmData->data(); - for (int i=0; imodels_count; i++) { - if (radioData->generalSettings.currModel != (unsigned int)header->models[i]-1) { - radioData->models[header->models[i]-1].clear(); - modified=true; - } - } - if (modified) { - ((MdiChild *)parent())->setModified(); - } -} - -void ModelsListWidget::doCopy(QByteArray *gmData) -{ - DragDropHeader header; - - foreach(QModelIndex index, this->selectionModel()->selectedIndexes()) - { - char row = index.row(); - if(!row) { - header.general_settings = true; - gmData->append('G'); - gmData->append((char*)&radioData->generalSettings, sizeof(GeneralSettings)); - } - else { - header.models[header.models_count++] = row; - gmData->append('M'); - gmData->append((char*)&radioData->models[row-1], sizeof(ModelData)); - } - } - - gmData->prepend((char *)&header, sizeof(header)); -} - -void ModelsListWidget::copy() -{ - QByteArray gmData; - doCopy(&gmData); - - QMimeData *mimeData = new QMimeData; - mimeData->setData("application/x-companion", gmData); - - QClipboard *clipboard = QApplication::clipboard(); - clipboard->setMimeData(mimeData,QClipboard::Clipboard); -} - -void ModelsListWidget::doPaste(QByteArray *gmData, int index) -{ - //QByteArray gmData = mimeD->data("application/x-companion"); - char *gData = gmData->data()+sizeof(DragDropHeader);//new char[gmData.size() + 1]; - int i = sizeof(DragDropHeader); - int id = index; - int ret,modified=0; - if(!id) id++; - - while((isize()) && (id<=GetEepromInterface()->getMaxModels())) { - char c = *gData; - i++; - gData++; - if(c=='G') { //General settings - ret = QMessageBox::question(this, "Companion", tr("Do you want to overwrite radio general settings?"), - QMessageBox::Yes | QMessageBox::No); - if (ret == QMessageBox::Yes) { - radioData->generalSettings = *((GeneralSettings *)gData); - modified=1; - } - gData += sizeof(GeneralSettings); - i += sizeof(GeneralSettings); - } - else { //model data - if (!radioData->models[id-1].isEmpty()) { - ret = QMessageBox::question(this, "Companion", tr("You are pasting on an not empty model, are you sure?"), - QMessageBox::Yes | QMessageBox::No); - if (ret == QMessageBox::Yes) { - radioData->models[id-1] = *((ModelData *)gData); - gData += sizeof(ModelData); - i += sizeof(ModelData); - id++; - modified = 1; - } - else { - gData += sizeof(ModelData); - i += sizeof(ModelData); - id++; - } - } - else { - radioData->models[id-1] = *((ModelData *)gData); - gData += sizeof(ModelData); - i += sizeof(ModelData); - id++; - modified=1; - } - } - } - if (modified==1) { - ((MdiChild *)parent())->setModified(); - } -} - -bool ModelsListWidget::hasPasteData() -{ - const QClipboard *clipboard = QApplication::clipboard(); - const QMimeData *mimeData = clipboard->mimeData(); - - return mimeData->hasFormat("application/x-companion"); -} - -void ModelsListWidget::paste() -{ - if (hasPasteData()) { - const QClipboard *clipboard = QApplication::clipboard(); - const QMimeData *mimeData = clipboard->mimeData(); - - QByteArray gmData = mimeData->data("application/x-companion"); - doPaste(&gmData,this->currentRow()); - } -} - -void ModelsListWidget::duplicate() -{ - int i = this->currentRow(); - if(i && igetMaxModels()) - { - ModelData *model = &radioData->models[i-1]; - while(igetMaxModels()) { - if (radioData->models[i].isEmpty()) { - radioData->models[i] = *model; - ((MdiChild *)parent())->setModified(); - break; - } - i++; - } - if (i==GetEepromInterface()->getMaxModels()) { - QMessageBox::warning(this, "Companion", tr("No free slot available, cannot duplicate"), QMessageBox::Ok); - } - } -} - -bool ModelsListWidget::hasSelection() -{ - return (this->selectionModel()->hasSelection()); -} - -void ModelsListWidget::keyPressEvent(QKeyEvent *event) -{ - if(event->matches(QKeySequence::Delete)) - { - deleteSelected(); - return; - } - - if(event->matches(QKeySequence::Cut)) - { - cut(); - return; - } - - if(event->matches(QKeySequence::Copy)) - { - copy(); - return; - } - - if(event->matches(QKeySequence::Paste)) - { - paste(); - return; - } - - if(event->matches(QKeySequence::Underline)) - { - duplicate(); - return; - } - - QListWidget::keyPressEvent(event);//run the standard event in case we didn't catch an action -} - -void ModelsListWidget::viableModelSelected(int idx) -{ - if (!isVisible()) - ((MdiChild*)parent())->viableModelSelected(false); - else if (idx<1) - ((MdiChild*)parent())->viableModelSelected(false); - else - ((MdiChild*)parent())->viableModelSelected(!radioData->models[currentRow()-1].isEmpty()); -} - - - +#include "modelslist.h" +#include "mdichild.h" +#include "helpers.h" + +class DragDropHeader { + public: + DragDropHeader(): + general_settings(false), + models_count(0) + { + } + bool general_settings; + uint8_t models_count; + uint8_t models[CPN_MAX_MODELS]; +}; + +ModelsListWidget::ModelsListWidget(QWidget *parent): + QListWidget(parent) +{ + setFont(QFont("Courier New",12)); + radioData = &((MdiChild *)parent)->radioData; + refreshList(); + + connect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(OpenEditWindow())); + connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(ShowContextMenu(const QPoint&))); + connect(this, SIGNAL(currentRowChanged(int)), this, SLOT(viableModelSelected(int))); + + setContextMenuPolicy(Qt::CustomContextMenu); + setSelectionMode(QAbstractItemView::ExtendedSelection); + setDragEnabled(true); + setAcceptDrops(true); + setDragDropOverwriteMode(true); + setDropIndicatorShown(true); + + active_highlight_color = palette().color(QPalette::Active, QPalette::Highlight); +} + +void ModelsListWidget::ShowContextMenu(const QPoint& pos) +{ + QPoint globalPos = this->mapToGlobal(pos); + QMenu contextMenu; + if (((MdiChild *)parent())->getCurrentRow() > 0) { + // context menu for model + const QClipboard *clipboard = QApplication::clipboard(); + const QMimeData *mimeData = clipboard->mimeData(); + bool hasData = mimeData->hasFormat("application/x-companion"); + + contextMenu.addAction(CompanionIcon("edit.png"), tr("&Edit"),this,SLOT(EditModel())); + contextMenu.addAction(CompanionIcon("open.png"), tr("&Restore from backup"),this,SLOT(LoadBackup())); + contextMenu.addAction(CompanionIcon("wizard.png"), tr("&Model Wizard"),this,SLOT(OpenWizard())); + contextMenu.addSeparator(); + contextMenu.addAction(CompanionIcon("clear.png"), tr("&Delete"),this,SLOT(confirmDelete()),tr("Delete")); + contextMenu.addAction(CompanionIcon("copy.png"), tr("&Copy"),this,SLOT(copy()),tr("Ctrl+C")); + contextMenu.addAction(CompanionIcon("cut.png"), tr("&Cut"),this,SLOT(cut()),tr("Ctrl+X")); + contextMenu.addAction(CompanionIcon("paste.png"), tr("&Paste"),this,SLOT(paste()),tr("Ctrl+V"))->setEnabled(hasData); + contextMenu.addAction(CompanionIcon("duplicate.png"), tr("D&uplicate"),this,SLOT(duplicate()),tr("Ctrl+U")); + contextMenu.addSeparator(); + contextMenu.addAction(CompanionIcon("currentmodel.png"), tr("&Use as default"),this,SLOT(setdefault())); + contextMenu.addSeparator(); + contextMenu.addAction(CompanionIcon("print.png"), tr("P&rint model"),this, SLOT(print()),QKeySequence(tr("Ctrl+P"))); + contextMenu.addSeparator(); + contextMenu.addAction(CompanionIcon("simulate.png"), tr("&Simulate model"),this, SLOT(simulate()),tr("Alt+S")); + } + else { + // context menu for radio settings + contextMenu.addAction(CompanionIcon("edit.png"), tr("&Edit"),this,SLOT(EditModel())); + } + contextMenu.exec(globalPos); +} + +void ModelsListWidget::EditModel() +{ + ((MdiChild *)parent())->modelEdit(); +} + +void ModelsListWidget::OpenEditWindow() +{ + ((MdiChild *)parent())->openEditWindow(); +} + +void ModelsListWidget::OpenWizard() +{ + ((MdiChild *)parent())->wizardEdit(); +} + +void ModelsListWidget::LoadBackup() +{ + ((MdiChild *)parent())->loadBackup(); +} + +void ModelsListWidget::simulate() +{ + ((MdiChild *)parent())->simulate(); +} + +void ModelsListWidget::print() +{ + ((MdiChild *)parent())->print(); +} + +void ModelsListWidget::setdefault() +{ + if (currentRow()==0) return; + unsigned int currModel = currentRow() - 1; + if (!radioData->models[currModel].isEmpty() && radioData->generalSettings.currModel != currModel) { + radioData->generalSettings.currModel = currModel; + refreshList(); + ((MdiChild *)parent())->setModified(); + } +} + + +void ModelsListWidget::mousePressEvent(QMouseEvent *event) +{ + if (event->button() == Qt::LeftButton) + dragStartPosition = event->pos(); + + QListWidget::mousePressEvent(event); +} + +void ModelsListWidget::mouseMoveEvent(QMouseEvent *event) +{ + if (!(event->buttons() & Qt::LeftButton)) + return; + if ((event->pos() - dragStartPosition).manhattanLength() + < QApplication::startDragDistance()) + return; + + QDrag *drag = new QDrag(this); + + QByteArray gmData; + doCopy(&gmData); + + QMimeData *mimeData = new QMimeData; + mimeData->setData("application/x-companion", gmData); + + drag->setMimeData(mimeData); + + //Qt::DropAction dropAction = + drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::CopyAction); + + //if(dropAction==Qt::MoveAction) + + // QListWidget::mouseMoveEvent(event); +} + +void ModelsListWidget::saveSelection() +{ + currentSelection.current_item = currentItem(); + for (int i=0; igetMaxModels()+1; ++i) + currentSelection.selected[i] = item(i)->isSelected(); +} + +void ModelsListWidget::restoreSelection() +{ + setCurrentItem(currentSelection.current_item); + for (int i=0; igetMaxModels()+1; ++i) + item(i)->setSelected(currentSelection.selected[i]); +} + +void ModelsListWidget::dragEnterEvent(QDragEnterEvent *event) +{ + if (event->mimeData()->hasFormat("application/x-companion")) + { + event->acceptProposedAction(); + saveSelection(); + } +} + +void ModelsListWidget::dragLeaveEvent(QDragLeaveEvent *) +{ + restoreSelection(); +} + +void ModelsListWidget::dragMoveEvent(QDragMoveEvent *event) +{ + int row=this->indexAt(event->pos()).row(); + const QMimeData *mimeData = event->mimeData(); + if (mimeData->hasFormat("application/x-companion")) + { + QByteArray gmData = mimeData->data("application/x-companion"); + event->acceptProposedAction(); + clearSelection(); + DragDropHeader *header = (DragDropHeader *)gmData.data(); + if (row >= 0) { + if (header->general_settings) + item(0)->setSelected(true); + for (int i=row, end=std::min(GetEepromInterface()->getMaxModels()+1, row+header->models_count); isetSelected(true); + } + } +} + +void ModelsListWidget::dropEvent(QDropEvent *event) +{ + int row = this->indexAt(event->pos()).row(); + if (row < 0) + return; + + // QMessageBox::warning(this, tr("Companion"),tr("Index :%1").arg(row)); + const QMimeData *mimeData = event->mimeData(); + + if(mimeData->hasFormat("application/x-companion")) + { + QByteArray gmData = mimeData->data("application/x-companion"); + if (event->source() && event->dropAction() == Qt::MoveAction) + ((ModelsListWidget*)event->source())->doCut(&gmData); + doPaste(&gmData, row); + clearSelection(); + setCurrentItem(item(row)); + DragDropHeader *header = (DragDropHeader *)gmData.data(); + if (header->general_settings) + item(0)->setSelected(true); + for (int i=row, end=std::min(GetEepromInterface()->getMaxModels()+1, row+header->models_count); isetSelected(true); + } + event->acceptProposedAction(); +} + +#ifndef WIN32 +void ModelsListWidget::focusInEvent ( QFocusEvent * event ) +{ + QListWidget::focusInEvent(event); + QPalette palette = this->palette(); + palette.setColor(QPalette::Active, QPalette::Highlight, active_highlight_color); + palette.setColor(QPalette::Inactive, QPalette::Highlight, active_highlight_color); + this->setPalette(palette); +} + +void ModelsListWidget::focusOutEvent ( QFocusEvent * event ) +{ + QListWidget::focusOutEvent(event); + QPalette palette = this->palette(); + palette.setColor(QPalette::Active, QPalette::Highlight, palette.color(QPalette::Active, QPalette::Midlight)); + palette.setColor(QPalette::Inactive, QPalette::Highlight, palette.color(QPalette::Active, QPalette::Midlight)); + this->setPalette(palette); +} +#endif + +void ModelsListWidget::refreshList() +{ + clear(); + addItem(tr("General Settings")); + + EEPROMInterface * eepromInterface = GetEepromInterface(); + BoardEnum board = eepromInterface->getBoard(); + + // TODO here we calculate the size used by the RLE format, this is clearly not the right place to do that... + int availableEEpromSize = eepromInterface->getEEpromSize() - 64; // let's consider fat + div_t divresult = div(eepromInterface->getSize(radioData->generalSettings), 15); + divresult.quot += (divresult.rem != 0 ? 1 : 0); + availableEEpromSize -= divresult.quot*16; + + for (uint8_t i=0; igetMaxModels(); i++) { + QString item = QString().sprintf("%02d: ", i+1); + if (!radioData->models[i].isEmpty()) { + QString modelName; + if (strlen(radioData->models[i].name) > 0) + modelName = radioData->models[i].name; + else + modelName = QString().sprintf("Model%02d", i+1); + item += modelName; + if (!IS_SKY9X(board) && !IS_HORUS(board)) { + item += QString(GetCurrentFirmware()->getCapability(ModelName)-modelName.size(), ' '); + int size = eepromInterface->getSize(radioData->models[i]); + item += QString().sprintf("%5d", size); + divresult = div(size, 15); + divresult.quot += (divresult.rem != 0 ? 1 : 0); + availableEEpromSize -= divresult.quot*16; + if (i == radioData->generalSettings.currModel) { + // TODO why? + availableEEpromSize -= divresult.quot*16; + } + } + } + addItem(item); + } + + if (radioData->generalSettings.currModel < (unsigned int)eepromInterface->getMaxModels()) { + QFont f = QFont("Courier New", 12); + f.setBold(true); + this->item(radioData->generalSettings.currModel+1)->setFont(f); + } + + if (!IS_SKY9X(board) && !IS_HORUS(board)) { + ((MdiChild*)parent())->setEEpromAvail((availableEEpromSize/16)*15); + } +} + +void ModelsListWidget::cut() +{ + copy(); + deleteSelected(false); +} + +void ModelsListWidget::confirmDelete() { + deleteSelected(true); +} + + +void ModelsListWidget::deleteSelected(bool ask=true) +{ + bool isModel=false; + unsigned int selModel; + QMessageBox::StandardButton ret = QMessageBox::Yes; + if(ask) { + foreach(QModelIndex index, this->selectionModel()->selectedIndexes()) { + if (index.row()>0 && !radioData->models[index.row()-1].isEmpty()) { + isModel=true; + selModel=index.row()-1; + } + } + if (isModel==true) { + if (radioData->generalSettings.currModel != selModel) { + ret = QMessageBox::warning(this, "Companion", tr("Delete Selected Models?"), QMessageBox::Yes | QMessageBox::No); + } else { + ret = QMessageBox::warning(this, "Companion", tr("Cannot delete default model."), QMessageBox::Ok); + } + } + } + if (ret == QMessageBox::Yes) { + foreach(QModelIndex index, this->selectionModel()->selectedIndexes()) { + if (index.row()>0 && radioData->generalSettings.currModel!=(unsigned int)(index.row()-1)) { + radioData->models[index.row()-1].clear(); + ((MdiChild *)parent())->setModified(); + } else if (index.row()>0) { + if (ask) { + ret = QMessageBox::warning(this, "Companion", tr("Cannot delete default model."), QMessageBox::Ok); + } else { + ret = QMessageBox::warning(this, "Companion", tr("Cannot cut default model."), QMessageBox::Ok); + } + } + } + } +} + +void ModelsListWidget::doCut(QByteArray *gmData) +{ + bool modified=false; + DragDropHeader *header = (DragDropHeader *)gmData->data(); + for (int i=0; imodels_count; i++) { + if (radioData->generalSettings.currModel != (unsigned int)header->models[i]-1) { + radioData->models[header->models[i]-1].clear(); + modified=true; + } + } + if (modified) { + ((MdiChild *)parent())->setModified(); + } +} + +void ModelsListWidget::doCopy(QByteArray *gmData) +{ + DragDropHeader header; + + foreach(QModelIndex index, this->selectionModel()->selectedIndexes()) + { + char row = index.row(); + if(!row) { + header.general_settings = true; + gmData->append('G'); + gmData->append((char*)&radioData->generalSettings, sizeof(GeneralSettings)); + } + else { + header.models[header.models_count++] = row; + gmData->append('M'); + gmData->append((char*)&radioData->models[row-1], sizeof(ModelData)); + } + } + + gmData->prepend((char *)&header, sizeof(header)); +} + +void ModelsListWidget::copy() +{ + QByteArray gmData; + doCopy(&gmData); + + QMimeData *mimeData = new QMimeData; + mimeData->setData("application/x-companion", gmData); + + QClipboard *clipboard = QApplication::clipboard(); + clipboard->setMimeData(mimeData,QClipboard::Clipboard); +} + +void ModelsListWidget::doPaste(QByteArray *gmData, int index) +{ + //QByteArray gmData = mimeD->data("application/x-companion"); + char *gData = gmData->data()+sizeof(DragDropHeader);//new char[gmData.size() + 1]; + int i = sizeof(DragDropHeader); + int id = index; + int ret,modified=0; + if(!id) id++; + + while((isize()) && (id<=GetEepromInterface()->getMaxModels())) { + char c = *gData; + i++; + gData++; + if(c=='G') { //General settings + ret = QMessageBox::question(this, "Companion", tr("Do you want to overwrite radio general settings?"), + QMessageBox::Yes | QMessageBox::No); + if (ret == QMessageBox::Yes) { + radioData->generalSettings = *((GeneralSettings *)gData); + modified=1; + } + gData += sizeof(GeneralSettings); + i += sizeof(GeneralSettings); + } + else { //model data + if (!radioData->models[id-1].isEmpty()) { + ret = QMessageBox::question(this, "Companion", tr("You are pasting on an not empty model, are you sure?"), + QMessageBox::Yes | QMessageBox::No); + if (ret == QMessageBox::Yes) { + radioData->models[id-1] = *((ModelData *)gData); + gData += sizeof(ModelData); + i += sizeof(ModelData); + id++; + modified = 1; + } + else { + gData += sizeof(ModelData); + i += sizeof(ModelData); + id++; + } + } + else { + radioData->models[id-1] = *((ModelData *)gData); + gData += sizeof(ModelData); + i += sizeof(ModelData); + id++; + modified=1; + } + } + } + if (modified==1) { + ((MdiChild *)parent())->setModified(); + } +} + +bool ModelsListWidget::hasPasteData() +{ + const QClipboard *clipboard = QApplication::clipboard(); + const QMimeData *mimeData = clipboard->mimeData(); + + return mimeData->hasFormat("application/x-companion"); +} + +void ModelsListWidget::paste() +{ + if (hasPasteData()) { + const QClipboard *clipboard = QApplication::clipboard(); + const QMimeData *mimeData = clipboard->mimeData(); + + QByteArray gmData = mimeData->data("application/x-companion"); + doPaste(&gmData,this->currentRow()); + } +} + +void ModelsListWidget::duplicate() +{ + int i = this->currentRow(); + if(i && igetMaxModels()) + { + ModelData *model = &radioData->models[i-1]; + while(igetMaxModels()) { + if (radioData->models[i].isEmpty()) { + radioData->models[i] = *model; + ((MdiChild *)parent())->setModified(); + break; + } + i++; + } + if (i==GetEepromInterface()->getMaxModels()) { + QMessageBox::warning(this, "Companion", tr("No free slot available, cannot duplicate"), QMessageBox::Ok); + } + } +} + +bool ModelsListWidget::hasSelection() +{ + return (this->selectionModel()->hasSelection()); +} + +void ModelsListWidget::keyPressEvent(QKeyEvent *event) +{ + if(event->matches(QKeySequence::Delete)) + { + deleteSelected(); + return; + } + + if(event->matches(QKeySequence::Cut)) + { + cut(); + return; + } + + if(event->matches(QKeySequence::Copy)) + { + copy(); + return; + } + + if(event->matches(QKeySequence::Paste)) + { + paste(); + return; + } + + if(event->matches(QKeySequence::Underline)) + { + duplicate(); + return; + } + + QListWidget::keyPressEvent(event);//run the standard event in case we didn't catch an action +} + +void ModelsListWidget::viableModelSelected(int idx) +{ + if (!isVisible()) + ((MdiChild*)parent())->viableModelSelected(false); + else if (idx<1) + ((MdiChild*)parent())->viableModelSelected(false); + else + ((MdiChild*)parent())->viableModelSelected(!radioData->models[currentRow()-1].isEmpty()); +} + + + diff --git a/companion/src/modelslist.h b/companion/src/modelslist.h index 31462782a..692a8e7f0 100644 --- a/companion/src/modelslist.h +++ b/companion/src/modelslist.h @@ -20,70 +20,70 @@ #ifndef _MODELSLIST_H_ #define _MODELSLIST_H_ - -#include -#include "eeprominterface.h" - -struct CurrentSelection -{ - QListWidgetItem *current_item; - bool selected[CPN_MAX_MODELS+1]; -}; - -class ModelsListWidget : public QListWidget -{ - Q_OBJECT - -public: - ModelsListWidget(QWidget *parent = 0); - - bool hasSelection(); - void keyPressEvent(QKeyEvent *event); - bool hasPasteData(); - -protected: - void dropEvent(QDropEvent *event); - void mousePressEvent(QMouseEvent *event); - void mouseMoveEvent(QMouseEvent *event); - void dragEnterEvent(QDragEnterEvent *event); - void dragLeaveEvent(QDragLeaveEvent *event); - void dragMoveEvent(QDragMoveEvent *event); -#ifndef WIN32 - void focusInEvent ( QFocusEvent * event ); - void focusOutEvent ( QFocusEvent * event ); -#endif - -public slots: - void refreshList(); - void ShowContextMenu(const QPoint& pos); - void cut(); - void copy(); - void paste(); - void print(); - void EditModel(); - void OpenEditWindow(); - void LoadBackup(); - void OpenWizard(); - void simulate(); - void duplicate(); - void setdefault(); - void deleteSelected(bool ask); - void confirmDelete(); - void viableModelSelected(int idx); - -private: - void doCut(QByteArray *gmData); - void doPaste(QByteArray *gmData, int index); - void doCopy(QByteArray *gmData); - void saveSelection(); - void restoreSelection(); - - RadioData *radioData; - QPoint dragStartPosition; - - CurrentSelection currentSelection; - QColor active_highlight_color; - -}; - + +#include +#include "eeprominterface.h" + +struct CurrentSelection +{ + QListWidgetItem *current_item; + bool selected[CPN_MAX_MODELS+1]; +}; + +class ModelsListWidget : public QListWidget +{ + Q_OBJECT + +public: + ModelsListWidget(QWidget *parent = 0); + + bool hasSelection(); + void keyPressEvent(QKeyEvent *event); + bool hasPasteData(); + +protected: + void dropEvent(QDropEvent *event); + void mousePressEvent(QMouseEvent *event); + void mouseMoveEvent(QMouseEvent *event); + void dragEnterEvent(QDragEnterEvent *event); + void dragLeaveEvent(QDragLeaveEvent *event); + void dragMoveEvent(QDragMoveEvent *event); +#ifndef WIN32 + void focusInEvent ( QFocusEvent * event ); + void focusOutEvent ( QFocusEvent * event ); +#endif + +public slots: + void refreshList(); + void ShowContextMenu(const QPoint& pos); + void cut(); + void copy(); + void paste(); + void print(); + void EditModel(); + void OpenEditWindow(); + void LoadBackup(); + void OpenWizard(); + void simulate(); + void duplicate(); + void setdefault(); + void deleteSelected(bool ask); + void confirmDelete(); + void viableModelSelected(int idx); + +private: + void doCut(QByteArray *gmData); + void doPaste(QByteArray *gmData, int index); + void doCopy(QByteArray *gmData); + void saveSelection(); + void restoreSelection(); + + RadioData *radioData; + QPoint dragStartPosition; + + CurrentSelection currentSelection; + QColor active_highlight_color; + +}; + #endif // _MODELSLIST_H_ diff --git a/companion/src/shared/genericpanel.cpp b/companion/src/shared/genericpanel.cpp index 34a8cc808..66628e00f 100644 --- a/companion/src/shared/genericpanel.cpp +++ b/companion/src/shared/genericpanel.cpp @@ -18,107 +18,107 @@ * GNU General Public License for more details. */ -#include "genericpanel.h" -#include -#include -#include -#include -#include - -GenericPanel::GenericPanel(QWidget * parent, ModelData * model, GeneralSettings & generalSettings, Firmware * firmware): - QWidget(parent), - model(model), - generalSettings(generalSettings), - firmware(firmware), - lock(false) -{ -} - -GenericPanel::~GenericPanel() -{ -} - -void GenericPanel::update() -{ -} - -void GenericPanel::addLabel(QGridLayout *gridLayout, const QString &text, int col, bool minimize) -{ - QLabel *label = new QLabel(this); - label->setFrameShape(QFrame::Panel); - label->setFrameShadow(QFrame::Raised); - label->setMidLineWidth(0); - label->setAlignment(Qt::AlignCenter); - label->setMargin(5); - label->setText(text); - if (!minimize) - label->setMinimumWidth(100); - gridLayout->addWidget(label, 0, col, 1, 1); -} - -void GenericPanel::addEmptyLabel(QGridLayout * gridLayout, int col) -{ - QLabel *label = new QLabel(this); - label->setText(""); - gridLayout->addWidget(label, 0, col, 1, 1); -} - -void GenericPanel::addHSpring(QGridLayout * gridLayout, int col, int row) -{ - QSpacerItem * spacer = new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum ); - gridLayout->addItem(spacer, row, col); -} - -void GenericPanel::addVSpring(QGridLayout * gridLayout, int col, int row) -{ - QSpacerItem * spacer = new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding ); - gridLayout->addItem(spacer, row, col); -} - -void GenericPanel::addDoubleSpring(QGridLayout * gridLayout, int col, int row) -{ - QSpacerItem * spacer = new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Expanding ); - gridLayout->addItem(spacer, row, col); -} - -bool GenericPanel::eventFilter(QObject *object, QEvent * event) -{ - QWidget * widget = qobject_cast(object); - if (widget) { - if (event->type() == QEvent::Wheel) { - if (widget->focusPolicy() == Qt::WheelFocus) { - event->accept(); - return false; - } - else { - event->ignore(); - return true; - } - } - else if (event->type() == QEvent::FocusIn) { - widget->setFocusPolicy(Qt::WheelFocus); - } - else if (event->type() == QEvent::FocusOut) { - widget->setFocusPolicy(Qt::StrongFocus); - } - } - return QWidget::eventFilter(object, event); -} - -void GenericPanel::disableMouseScrolling() -{ - Q_FOREACH(QComboBox * cb, findChildren()) { - cb->installEventFilter(this); - cb->setFocusPolicy(Qt::StrongFocus); - } - - Q_FOREACH(QAbstractSpinBox * sb, findChildren()) { - sb->installEventFilter(this); - sb->setFocusPolicy(Qt::StrongFocus); - } - - Q_FOREACH(QSlider * slider, findChildren()) { - slider->installEventFilter(this); - slider->setFocusPolicy(Qt::StrongFocus); - } -} +#include "genericpanel.h" +#include +#include +#include +#include +#include + +GenericPanel::GenericPanel(QWidget * parent, ModelData * model, GeneralSettings & generalSettings, Firmware * firmware): + QWidget(parent), + model(model), + generalSettings(generalSettings), + firmware(firmware), + lock(false) +{ +} + +GenericPanel::~GenericPanel() +{ +} + +void GenericPanel::update() +{ +} + +void GenericPanel::addLabel(QGridLayout *gridLayout, const QString &text, int col, bool minimize) +{ + QLabel *label = new QLabel(this); + label->setFrameShape(QFrame::Panel); + label->setFrameShadow(QFrame::Raised); + label->setMidLineWidth(0); + label->setAlignment(Qt::AlignCenter); + label->setMargin(5); + label->setText(text); + if (!minimize) + label->setMinimumWidth(100); + gridLayout->addWidget(label, 0, col, 1, 1); +} + +void GenericPanel::addEmptyLabel(QGridLayout * gridLayout, int col) +{ + QLabel *label = new QLabel(this); + label->setText(""); + gridLayout->addWidget(label, 0, col, 1, 1); +} + +void GenericPanel::addHSpring(QGridLayout * gridLayout, int col, int row) +{ + QSpacerItem * spacer = new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum ); + gridLayout->addItem(spacer, row, col); +} + +void GenericPanel::addVSpring(QGridLayout * gridLayout, int col, int row) +{ + QSpacerItem * spacer = new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding ); + gridLayout->addItem(spacer, row, col); +} + +void GenericPanel::addDoubleSpring(QGridLayout * gridLayout, int col, int row) +{ + QSpacerItem * spacer = new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Expanding ); + gridLayout->addItem(spacer, row, col); +} + +bool GenericPanel::eventFilter(QObject *object, QEvent * event) +{ + QWidget * widget = qobject_cast(object); + if (widget) { + if (event->type() == QEvent::Wheel) { + if (widget->focusPolicy() == Qt::WheelFocus) { + event->accept(); + return false; + } + else { + event->ignore(); + return true; + } + } + else if (event->type() == QEvent::FocusIn) { + widget->setFocusPolicy(Qt::WheelFocus); + } + else if (event->type() == QEvent::FocusOut) { + widget->setFocusPolicy(Qt::StrongFocus); + } + } + return QWidget::eventFilter(object, event); +} + +void GenericPanel::disableMouseScrolling() +{ + Q_FOREACH(QComboBox * cb, findChildren()) { + cb->installEventFilter(this); + cb->setFocusPolicy(Qt::StrongFocus); + } + + Q_FOREACH(QAbstractSpinBox * sb, findChildren()) { + sb->installEventFilter(this); + sb->setFocusPolicy(Qt::StrongFocus); + } + + Q_FOREACH(QSlider * slider, findChildren()) { + slider->installEventFilter(this); + slider->setFocusPolicy(Qt::StrongFocus); + } +} diff --git a/companion/src/shared/genericpanel.h b/companion/src/shared/genericpanel.h index 772df6cf6..ceb720f53 100644 --- a/companion/src/shared/genericpanel.h +++ b/companion/src/shared/genericpanel.h @@ -20,47 +20,47 @@ #ifndef _GENERICPANEL_H_ #define _GENERICPANEL_H_ - -#include - -class ModelData; -class GeneralSettings; -class Firmware; -class QGridLayout; -class QString; - -class GenericPanel : public QWidget -{ - Q_OBJECT - - friend class AutoComboBox; - friend class AutoDoubleSpinBox; - friend class AutoCheckBox; - friend class AutoHexSpinBox; - friend class AutoLineEdit; - - public: - GenericPanel(QWidget *parent, ModelData * model, GeneralSettings & generalSettings, Firmware * firmware); - virtual ~GenericPanel(); - - signals: - void modified(); - - public slots: - virtual void update(); - - protected: - ModelData * model; - GeneralSettings & generalSettings; - Firmware * firmware; - bool lock; - void addLabel(QGridLayout * gridLayout, const QString &text, int col, bool mimimize=false); - void addEmptyLabel(QGridLayout * gridLayout, int col); - void addHSpring(QGridLayout *, int col, int row); - void addVSpring(QGridLayout *, int col, int row); - void addDoubleSpring(QGridLayout *, int col, int row); - virtual bool eventFilter(QObject *obj, QEvent *event); - void disableMouseScrolling(); -}; - + +#include + +class ModelData; +class GeneralSettings; +class Firmware; +class QGridLayout; +class QString; + +class GenericPanel : public QWidget +{ + Q_OBJECT + + friend class AutoComboBox; + friend class AutoDoubleSpinBox; + friend class AutoCheckBox; + friend class AutoHexSpinBox; + friend class AutoLineEdit; + + public: + GenericPanel(QWidget *parent, ModelData * model, GeneralSettings & generalSettings, Firmware * firmware); + virtual ~GenericPanel(); + + signals: + void modified(); + + public slots: + virtual void update(); + + protected: + ModelData * model; + GeneralSettings & generalSettings; + Firmware * firmware; + bool lock; + void addLabel(QGridLayout * gridLayout, const QString &text, int col, bool mimimize=false); + void addEmptyLabel(QGridLayout * gridLayout, int col); + void addHSpring(QGridLayout *, int col, int row); + void addVSpring(QGridLayout *, int col, int row); + void addDoubleSpring(QGridLayout *, int col, int row); + virtual bool eventFilter(QObject *obj, QEvent *event); + void disableMouseScrolling(); +}; + #endif // _GENERICPANEL_H_ diff --git a/companion/src/shared/hexspinbox.cpp b/companion/src/shared/hexspinbox.cpp index 75b463fe4..63889ef11 100644 --- a/companion/src/shared/hexspinbox.cpp +++ b/companion/src/shared/hexspinbox.cpp @@ -18,30 +18,30 @@ * GNU General Public License for more details. */ -#include "hexspinbox.h" - -HexSpinBox::HexSpinBox(QWidget *parent): - QSpinBox(parent) -{ - validator = new QRegExpValidator(QRegExp("[0-9A-Fa-f]{1,8}"), this); -} - -QValidator::State HexSpinBox::validate(QString &text, int &pos) const -{ - return validator->validate(text, pos); -} - -int HexSpinBox::valueFromText(const QString &text) const -{ - return text.toInt(0, 16); -} - -QString HexSpinBox::textFromValue(int value) const -{ - QString text; - text.sprintf("%04X", value); - return text; -} - - - +#include "hexspinbox.h" + +HexSpinBox::HexSpinBox(QWidget *parent): + QSpinBox(parent) +{ + validator = new QRegExpValidator(QRegExp("[0-9A-Fa-f]{1,8}"), this); +} + +QValidator::State HexSpinBox::validate(QString &text, int &pos) const +{ + return validator->validate(text, pos); +} + +int HexSpinBox::valueFromText(const QString &text) const +{ + return text.toInt(0, 16); +} + +QString HexSpinBox::textFromValue(int value) const +{ + QString text; + text.sprintf("%04X", value); + return text; +} + + + diff --git a/companion/src/shared/hexspinbox.h b/companion/src/shared/hexspinbox.h index 5e793d5f7..fc404d98a 100644 --- a/companion/src/shared/hexspinbox.h +++ b/companion/src/shared/hexspinbox.h @@ -20,25 +20,25 @@ #ifndef _HEXSPINBOX_H_ #define _HEXSPINBOX_H_ - -#include - -class QRegExpValidator; - -class HexSpinBox : public QSpinBox -{ - Q_OBJECT - - public: - HexSpinBox(QWidget *parent = 0); - - protected: - QValidator::State validate(QString &text, int &pos) const; - int valueFromText(const QString &text) const; - QString textFromValue(int value) const; - - private: - QRegExpValidator *validator; -}; - + +#include + +class QRegExpValidator; + +class HexSpinBox : public QSpinBox +{ + Q_OBJECT + + public: + HexSpinBox(QWidget *parent = 0); + + protected: + QValidator::State validate(QString &text, int &pos) const; + int valueFromText(const QString &text) const; + QString textFromValue(int value) const; + + private: + QRegExpValidator *validator; +}; + #endif // _HEXSPINBOX_H_ diff --git a/companion/src/shared/verticalscrollarea.cpp b/companion/src/shared/verticalscrollarea.cpp index 9ca1d7e6b..b92398f17 100644 --- a/companion/src/shared/verticalscrollarea.cpp +++ b/companion/src/shared/verticalscrollarea.cpp @@ -18,25 +18,25 @@ * GNU General Public License for more details. */ -#include "verticalscrollarea.h" -#include "genericpanel.h" -#include -#include - -VerticalScrollArea::VerticalScrollArea(QWidget * parent, GenericPanel * panel): - QScrollArea(parent), - panel(panel) -{ - setWidgetResizable(true); - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setWidget(panel); - panel->installEventFilter(this); -} - -bool VerticalScrollArea::eventFilter(QObject * o, QEvent * e) -{ - if (o == panel && e->type() == QEvent::Resize) { - setMinimumWidth(panel->minimumSizeHint().width() + verticalScrollBar()->width()); - } - return false; -} +#include "verticalscrollarea.h" +#include "genericpanel.h" +#include +#include + +VerticalScrollArea::VerticalScrollArea(QWidget * parent, GenericPanel * panel): + QScrollArea(parent), + panel(panel) +{ + setWidgetResizable(true); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setWidget(panel); + panel->installEventFilter(this); +} + +bool VerticalScrollArea::eventFilter(QObject * o, QEvent * e) +{ + if (o == panel && e->type() == QEvent::Resize) { + setMinimumWidth(panel->minimumSizeHint().width() + verticalScrollBar()->width()); + } + return false; +} diff --git a/companion/src/shared/verticalscrollarea.h b/companion/src/shared/verticalscrollarea.h index b8cad4bd1..36f564dd7 100644 --- a/companion/src/shared/verticalscrollarea.h +++ b/companion/src/shared/verticalscrollarea.h @@ -20,22 +20,22 @@ #ifndef _VERTICALSCROLLAREA_H_ #define _VERTICALSCROLLAREA_H_ - -#include - -class GenericPanel; - -class VerticalScrollArea : public QScrollArea -{ - public: - VerticalScrollArea(QWidget * parent, GenericPanel * panel); - - protected: - virtual bool eventFilter(QObject * o, QEvent * e); - - private: - GenericPanel * panel; -}; - + +#include + +class GenericPanel; + +class VerticalScrollArea : public QScrollArea +{ + public: + VerticalScrollArea(QWidget * parent, GenericPanel * panel); + + protected: + virtual bool eventFilter(QObject * o, QEvent * e); + + private: + GenericPanel * panel; +}; + #endif // _VERTICALSCROLLAREA_H_ - + diff --git a/companion/src/simulation/simulatordialog.cpp b/companion/src/simulation/simulatordialog.cpp index a419dbabb..3842df120 100644 --- a/companion/src/simulation/simulatordialog.cpp +++ b/companion/src/simulation/simulatordialog.cpp @@ -18,765 +18,765 @@ * GNU General Public License for more details. */ -#include "simulatordialog.h" -#include "appdata.h" -#include "lcdwidget.h" -#include -#include "helpers.h" -#include "simulatorinterface.h" -#include "sliderwidget.h" - -#define GBALL_SIZE 20 -#define RESX 1024 - -int SimulatorDialog::screenshotIdx = 0; -SimulatorDialog * traceCallbackInstance = 0; - -void traceCb(const char * text) -{ - // divert C callback into simulator instance - if (traceCallbackInstance) { - traceCallbackInstance->traceCallback(text); - } -} - -void SimulatorDialog::traceCallback(const char * text) -{ - // this function is called from other threads - traceMutex.lock(); - // limit the size of list - if (traceList.size() < 1000) { - traceList.append(QString(text)); - } - traceMutex.unlock(); -} - -void SimulatorDialog::updateDebugOutput() -{ - traceMutex.lock(); - while (!traceList.isEmpty()) { - QString text = traceList.takeFirst(); - traceBuffer.append(text); - // limit the size of traceBuffer - if (traceBuffer.size() > 10*1024) { - traceBuffer.remove(0, 1*1024); - } - if (DebugOut) { - DebugOut->traceCallback(QString(text)); - } - } - traceMutex.unlock(); -} - -void SimulatorDialog::wheelEvent (QWheelEvent *event) -{ - simulator->wheelEvent(event->delta() > 0 ? 1 : -1); -} - -SimulatorDialog::SimulatorDialog(QWidget * parent, SimulatorInterface *simulator, unsigned int flags): - QDialog(parent), - flags(flags), - timer(NULL), - lightOn(false), - simulator(simulator), - lastPhase(-1), - beepVal(0), - TelemetrySimu(0), - TrainerSimu(0), - DebugOut(0), - buttonPressed(0), - trimPressed (TRIM_NONE), - middleButtonPressed(false) -{ - //shorcut for telemetry simulator - // new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_T), this, SLOT(openTelemetrySimulator())); - new QShortcut(QKeySequence(Qt::Key_F4), this, SLOT(openTelemetrySimulator())); - new QShortcut(QKeySequence(Qt::Key_F5), this, SLOT(openTrainerSimulator())); - new QShortcut(QKeySequence(Qt::Key_F6), this, SLOT(openDebugOutput())); - new QShortcut(QKeySequence(Qt::Key_F7), this, SLOT(luaReload())); - traceCallbackInstance = this; -} - -SimulatorDialog::~SimulatorDialog() -{ - traceCallbackInstance = 0; - delete timer; - delete simulator; -} - -void SimulatorDialog::closeEvent (QCloseEvent *) -{ - simulator->stop(); - timer->stop(); -} - -void SimulatorDialog::mousePressEvent(QMouseEvent *event) -{ - if (event->button() == Qt::MidButton) { - middleButtonPressed = true; - } -} - -void SimulatorDialog::mouseReleaseEvent(QMouseEvent *event) -{ - if (event->button() == Qt::MidButton) { - middleButtonPressed = false; - } -} - -void SimulatorDialog::onTrimPressed() -{ - if (sender()->objectName() == QString("trimHL_L")) - trimPressed = TRIM_LH_L; - else if (sender()->objectName() == QString("trimHL_R")) - trimPressed = TRIM_LH_R; - else if (sender()->objectName() == QString("trimVL_D")) - trimPressed = TRIM_LV_DN; - else if (sender()->objectName() == QString("trimVL_U")) - trimPressed = TRIM_LV_UP; - else if (sender()->objectName() == QString("trimVR_D")) - trimPressed = TRIM_RV_DN; - else if (sender()->objectName() == QString("trimVR_U")) - trimPressed = TRIM_RV_UP; - else if (sender()->objectName() == QString("trimHR_L")) - trimPressed = TRIM_RH_L; - else if (sender()->objectName() == QString("trimHR_R")) - trimPressed = TRIM_RH_R; -} - -void SimulatorDialog::onTrimReleased() -{ - trimPressed = TRIM_NONE; -} - -void SimulatorDialog::openTelemetrySimulator() -{ - // allow only one instance - if (TelemetrySimu == 0) { - TelemetrySimu = new TelemetrySimulator(this, simulator); - TelemetrySimu->show(); - } - else if (!TelemetrySimu->isVisible()) { - TelemetrySimu->show(); - } -} - -void SimulatorDialog::openTrainerSimulator() -{ - // allow only one instance - if (TrainerSimu == 0) { - TrainerSimu = new TrainerSimulator(this, simulator); - TrainerSimu->show(); - } - else if (!TrainerSimu->isVisible()) { - TrainerSimu->show(); - } -} - -void SimulatorDialog::openDebugOutput() -{ - // allow only one instance, but install signal handler to catch dialog destruction just in case - if (DebugOut == 0) { - DebugOut = new DebugOutput(this); - QObject::connect(DebugOut, SIGNAL(destroyed()), this, SLOT(onDebugOutputClose())); - DebugOut->traceCallback(traceBuffer); - DebugOut->show(); - } - else if (!DebugOut->isVisible()) { - DebugOut->show(); - } -} - -void SimulatorDialog::luaReload() -{ - // force a reload of the lua environment (as if a standalone script were run) - simulator->setLuaStateReloadPermanentScripts(); -} - -void SimulatorDialog::onDebugOutputClose() -{ - DebugOut = 0; -} - - -void SimulatorDialog::keyPressEvent (QKeyEvent *event) -{ - switch (event->key()) { - case Qt::Key_Enter: - case Qt::Key_Return: - buttonPressed = Qt::Key_Enter; - break; - case Qt::Key_Escape: - case Qt::Key_Backspace: - buttonPressed = Qt::Key_Escape; - break; - case Qt::Key_Up: - case Qt::Key_Down: - case Qt::Key_Right: - case Qt::Key_Left: - case Qt::Key_Minus: - case Qt::Key_Plus: - case Qt::Key_PageDown: - case Qt::Key_PageUp: - buttonPressed = event->key(); - break; - } -} - -void SimulatorDialog::keyReleaseEvent(QKeyEvent * event) -{ - switch (event->key()) { - case Qt::Key_Enter: - case Qt::Key_Return: - case Qt::Key_Escape: - case Qt::Key_Backspace: - case Qt::Key_Up: - case Qt::Key_Down: - case Qt::Key_Right: - case Qt::Key_Left: - case Qt::Key_Plus: - case Qt::Key_Minus: - case Qt::Key_PageDown: - case Qt::Key_PageUp: - buttonPressed = 0; - break; - } -} - -void SimulatorDialog::setupTimer() -{ - timer = new QTimer(this); - connect(timer, SIGNAL(timeout()), this, SLOT(onTimerEvent())); - timer->start(10); -} - -template -void SimulatorDialog::initUi(T * ui) -{ - ui->setupUi(this); - - lcd = ui->lcd; - leftStick = ui->leftStick; - rightStick = ui->rightStick; - pots = findWidgets(this, "pot%1"); - potLabels = findWidgets(this, "potLabel%1"); - potValues = findWidgets(this, "potValue%1"); - sliders = findWidgets(this, "slider%1"); - - trimHLeft = ui->trimHLeft; - trimVLeft = ui->trimVLeft; - trimHRight = ui->trimHRight; - trimVRight = ui->trimVRight; - tabWidget = ui->tabWidget; - leftXPerc = ui->leftXPerc; - leftYPerc = ui->leftYPerc; - rightXPerc = ui->rightXPerc; - rightYPerc = ui->rightYPerc; - - setupSticks(); - - resize(0, 0); // to force min height, min width - setFixedSize(width(), height()); - -#ifdef JOYSTICKS - if (g.jsSupport()) { - int count=0; - for (int j=0; j<8; j++){ - int axe = g.joystick[j].stick_axe(); - if (axe>=0 && axe<8) { - jsmap[axe]=j+1; - jscal[axe][0] = g.joystick[j].stick_min(); - jscal[axe][1] = g.joystick[j].stick_med(); - jscal[axe][2] = g.joystick[j].stick_max(); - jscal[axe][3] = g.joystick[j].stick_inv(); - count++; - } - } - if (count<3) { - QMessageBox::critical(this, tr("Warning"), tr("Joystick enabled but not configured correctly")); - } - if (g.jsCtrl()!=-1) { - joystick = new Joystick(this); - if (joystick) { - if (joystick->open(g.jsCtrl())) { - int numAxes=std::min(joystick->numAxes,8); - for (int j=0; jsensitivities[j] = 0; - joystick->deadzones[j]=0; - } - nodeRight->setCenteringY(false); //mode 1,3 -> THR on right - ui->holdRightY->setChecked(true); - nodeRight->setCenteringX(false); //mode 1,3 -> THR on right - ui->holdRightX->setChecked(true); - nodeLeft->setCenteringY(false); //mode 1,3 -> THR on right - ui->holdLeftY->setChecked(true); - nodeLeft->setCenteringX(false); //mode 1,3 -> THR on right - ui->holdLeftX->setChecked(true); - connect(joystick, SIGNAL(axisValueChanged(int, int)), this, SLOT(onjoystickAxisValueChanged(int, int))); - } - else { - QMessageBox::critical(this, tr("Warning"), tr("Cannot open joystick, joystick disabled")); - } - } - } - } -#endif - - windowName = tr("Simulating Radio (%1)").arg(GetCurrentFirmware()->getName()); - setWindowTitle(windowName); - - simulator->setSdPath(g.profile[g.id()].sdPath()); - simulator->setVolumeGain(g.profile[g.id()].volumeGain()); - lcd->setData(simulator->getLcd(), lcdWidth, lcdHeight, lcdDepth); - - if (flags & SIMULATOR_FLAGS_STICK_MODE_LEFT) { - nodeLeft->setCenteringY(false); - ui->holdLeftY->setChecked(true); - } - else { - nodeRight->setCenteringY(false); - ui->holdRightY->setChecked(true); - } - - setTrims(); - - int outputs = std::min(32, GetCurrentFirmware()->getCapability(Outputs)); - if (outputs <= 16) { - // hide second Outputs tab - tabWidget->removeTab(tabWidget->indexOf(ui->outputs2)); - } - else { - tabWidget->setTabText(tabWidget->indexOf(ui->outputs), tr("Outputs") + QString(" 1-%1").arg(16)); - tabWidget->setTabText(tabWidget->indexOf(ui->outputs2), tr("Outputs") + QString(" 17-%1").arg(outputs)); - } - for (int i=0; ichannelsLayout; - int column = i / (std::min(16,outputs)/2); - int line = i % (std::min(16,outputs)/2); - if (i >= 16 ) { - outputTab = ui->channelsLayout2; - column = (i-16) / (std::min(16,outputs-16)/2); - line = (i-16) % (std::min(16,outputs-16)/2); - } - QLabel * label = new QLabel(tabWidget); - label->setText(RawSource(SOURCE_TYPE_CH, i).toString()); - outputTab->addWidget(label, line, column == 0 ? 0 : 5, 1, 1); - - QSlider * slider = new QSlider(tabWidget); - slider->setEnabled(false); - /*slider->setMaximumSize(QSize(16777215, 18)); - slider->setStyleSheet(QString::fromUtf8("QSlider::sub-page:horizontal:disabled {\n" - "border-color: #999;\n" - "}\n" - "\n" - "QSlider::add-page:horizontal:disabled {\n" - "border-color: #999;\n" - "}\n" - "\n" - "QSlider::handle:horizontal:disabled {\n" - "background: #0000CC;\n" - "border: 1px solid #aaa;\n" - "border-radius: 4px;\n" - "}")); */ - slider->setMinimum(-1024); - slider->setMaximum(1024); - slider->setPageStep(128); - slider->setTracking(false); - slider->setOrientation(Qt::Horizontal); - slider->setInvertedAppearance(false); - slider->setTickPosition(QSlider::TicksBelow); - channelSliders << slider; - outputTab->addWidget(slider, line, column == 0 ? 1 : 4, 1, 1); - - QLabel * value = new QLabel(tabWidget); - value->setMinimumSize(QSize(50, 0)); - value->setAlignment(Qt::AlignCenter); - channelValues << value; - outputTab->addWidget(value, line, column == 0 ? 2 : 3, 1, 1); - } - - int switches = GetCurrentFirmware()->getCapability(LogicalSwitches); - for (int i=0; ilogicalSwitchesLayout->addWidget(swtch, i / (switches/2), i % (switches/2), 1, 1); - if (outputs > 16) { - // repeat logical switches on second outputs tab - swtch = createLogicalSwitch(tabWidget, i, logicalSwitchLabels2); - ui->logicalSwitchesLayout2->addWidget(swtch, i / (switches/2), i % (switches/2), 1, 1); - } - } - - int fmodes = GetCurrentFirmware()->getCapability(FlightModes); - int gvars = GetCurrentFirmware()->getCapability(Gvars); - if (gvars>0) { - for (int fm=0; fmsetText(QString("FM%1").arg(fm)); - label->setAlignment(Qt::AlignCenter); - ui->gvarsLayout->addWidget(label, 0, fm+1); - } - for (int i=0; isetText(QString("GV%1").arg(i+1)); - label->setAutoFillBackground(true); - if ((i % 2) ==0 ) { - label->setStyleSheet("QLabel { background-color: rgb(220, 220, 220) }"); - } - ui->gvarsLayout->addWidget(label, i+1, 0); - for (int fm=0; fmsetAutoFillBackground(true); - value->setAlignment(Qt::AlignRight | Qt::AlignVCenter); - if ((i % 2) ==0 ) { - value->setStyleSheet("QLabel { background-color: rgb(220, 220, 220) }"); - } - gvarValues << value; - ui->gvarsLayout->addWidget(value, i+1, fm+1); - } - } - } - - if (flags & SIMULATOR_FLAGS_NOTX) { - ui->tabWidget->setCurrentWidget(ui->outputs); - } - else { - ui->tabWidget->setCurrentWidget(ui->simu); - } -} - -QFrame * SimulatorDialog::createLogicalSwitch(QWidget * parent, int switchNo, QVector & labels) -{ - QFrame * swtch = new QFrame(parent); - swtch->setAutoFillBackground(true); - swtch->setFrameShape(QFrame::Panel); - swtch->setFrameShadow(QFrame::Raised); - swtch->setLineWidth(2); - QVBoxLayout * layout = new QVBoxLayout(swtch); - layout->setContentsMargins(2, 2, 2, 2); - QLabel * label = new QLabel(swtch); - label->setText(RawSwitch(SWITCH_TYPE_VIRTUAL, switchNo+1).toString()); - label->setAlignment(Qt::AlignCenter); - labels << label; - layout->addWidget(label); - return swtch; -} - -void SimulatorDialog::onButtonPressed(int value) -{ - if (value == Qt::Key_Print) { - QString fileName = ""; - if (!g.snapToClpbrd()) { - fileName = QString("screenshot-%1.png").arg(++screenshotIdx); - } - lcd->makeScreenshot(fileName); - } - else { - buttonPressed = value; - } -} - -void SimulatorDialog::onTimerEvent() -{ - static unsigned int lcd_counter = 0; - if (!simulator->timer10ms()) { - QMessageBox::critical(this, "Companion", tr("Firmware %1 error: %2").arg(GetCurrentFirmware()->getName()).arg(simulator->getError())); - timer->stop(); - return; - } - - getValues(); - - if (tabWidget->currentIndex()==0) { - bool lightEnable; - if (simulator->lcdChanged(lightEnable)) { - lcd->onLcdChanged(lightEnable); - if (lightOn != lightEnable) { - setLightOn(lightEnable); - lightOn = lightEnable; - } - } - } - - // display current flight mode in window title - unsigned int currentPhase = simulator->getPhase(); - if (currentPhase != lastPhase) { - lastPhase = currentPhase; - const char * phase_name = simulator->getPhaseName(currentPhase); - if (phase_name && phase_name[0]) { - setWindowTitle(windowName + QString(" - Flight Mode %1").arg(QString(phase_name))); - } - else { - setWindowTitle(windowName + QString(" - Flight Mode %1").arg(simulator->getPhase())); - } - } - - if (!(lcd_counter++ % 5)) { - - setValues(); - - setTrims(); - - centerSticks(); - - updateBeepButton(); - - if (beepVal) { - beepVal = 0; - QApplication::beep(); - } - } - - updateDebugOutput(); -} - -void SimulatorDialog::centerSticks() -{ - if (leftStick->scene()) - nodeLeft->stepToCenter(); - - if (rightStick->scene()) - nodeRight->stepToCenter(); -} - -void SimulatorDialog::start(QByteArray & eeprom) -{ - lastPhase = -1; - numGvars = GetCurrentFirmware()->getCapability(Gvars); - numFlightModes = GetCurrentFirmware()->getCapability(FlightModes); - simulator->start(eeprom, (flags & SIMULATOR_FLAGS_NOTX) ? false : true); - getValues(); - setupTimer(); -} - -void SimulatorDialog::start(const char * filename) -{ - lastPhase = -1; - numGvars = GetCurrentFirmware()->getCapability(Gvars); - numFlightModes = GetCurrentFirmware()->getCapability(FlightModes); - simulator->start(filename); - getValues(); - setupTimer(); -} - -void SimulatorDialog::setTrims() -{ - Trims trims; - simulator->getTrims(trims); - - int trimMin = -125, trimMax = +125; - if (trims.extended) { - trimMin = -500; - trimMax = +500; - } - trimHLeft->setRange(trimMin, trimMax); trimHLeft->setValue(trims.values[0]); - trimVLeft->setRange(trimMin, trimMax); trimVLeft->setValue(trims.values[1]); - trimVRight->setRange(trimMin, trimMax); trimVRight->setValue(trims.values[2]); - trimHRight->setRange(trimMin, trimMax); trimHRight->setValue(trims.values[3]); -} - -inline int chVal(int val) -{ - return qMin(1024, qMax(-1024, val)); -} - -void SimulatorDialog::on_trimHLeft_valueChanged(int value) -{ - simulator->setTrim(0, value); -} - -void SimulatorDialog::on_trimVLeft_valueChanged(int value) -{ - simulator->setTrim(1, value); -} - -void SimulatorDialog::on_trimVRight_valueChanged(int value) -{ - simulator->setTrim(2, value); -} - -void SimulatorDialog::on_trimHRight_valueChanged(int value) -{ - simulator->setTrim(3, value); -} - -void SimulatorDialog::setValues() -{ - TxOutputs outputs; - simulator->getValues(outputs); - Trims trims; - simulator->getTrims(trims); - - for (int i=0; igetCapability(Outputs); i++) { - if (i < channelSliders.size()) { - channelSliders[i]->setValue(chVal(outputs.chans[i])); - channelValues[i]->setText(QString("%1").arg((qreal)outputs.chans[i]*100/1024, 0, 'f', 1)); - } - } - - leftXPerc->setText(QString("X %1%").arg((qreal)nodeLeft->getX()*100+trims.values[0]/5, 2, 'f', 0)); - leftYPerc->setText(QString("Y %1%").arg((qreal)nodeLeft->getY()*-100+trims.values[1]/5, 2, 'f', 0)); - - rightXPerc->setText(QString("X %1%").arg((qreal)nodeRight->getX()*100+trims.values[3]/5, 2, 'f', 0)); - rightYPerc->setText(QString("Y %1%").arg((qreal)nodeRight->getY()*-100+trims.values[2]/5, 2, 'f', 0)); - - QString CSWITCH_ON = "QLabel { background-color: #4CC417 }"; - QString CSWITCH_OFF = "QLabel { }"; - - for (int i=0; igetCapability(LogicalSwitches); i++) { - logicalSwitchLabels[i]->setStyleSheet(outputs.vsw[i] ? CSWITCH_ON : CSWITCH_OFF); - if (!logicalSwitchLabels2.isEmpty()) { - logicalSwitchLabels2[i]->setStyleSheet(outputs.vsw[i] ? CSWITCH_ON : CSWITCH_OFF); - } - } - - for (unsigned int gv=0; gvsetText(QString((fm==lastPhase)?"%1":"%1").arg(outputs.gvars[fm][gv])); - } - } - - if (outputs.beep) { - beepVal = outputs.beep; - } -} - -void SimulatorDialog::setupSticks() -{ - QGraphicsScene *leftScene = new QGraphicsScene(leftStick); - leftScene->setItemIndexMethod(QGraphicsScene::NoIndex); - leftStick->setScene(leftScene); - - // leftStick->scene()->addLine(0,10,20,30); - - QGraphicsScene *rightScene = new QGraphicsScene(rightStick); - rightScene->setItemIndexMethod(QGraphicsScene::NoIndex); - rightStick->setScene(rightScene); - - // rightStick->scene()->addLine(0,10,20,30); - - nodeLeft = new Node(); - nodeLeft->setPos(-GBALL_SIZE/2,-GBALL_SIZE/2); - nodeLeft->setBallSize(GBALL_SIZE); - leftScene->addItem(nodeLeft); - - nodeRight = new Node(); - nodeRight->setPos(-GBALL_SIZE/2,-GBALL_SIZE/2); - nodeRight->setBallSize(GBALL_SIZE); - rightScene->addItem(nodeRight); -} - -void SimulatorDialog::resizeEvent(QResizeEvent *event) -{ - if (leftStick->scene()) { - QRect qr = leftStick->contentsRect(); - qreal w = (qreal)qr.width() - GBALL_SIZE; - qreal h = (qreal)qr.height() - GBALL_SIZE; - qreal cx = (qreal)qr.width()/2; - qreal cy = (qreal)qr.height()/2; - leftStick->scene()->setSceneRect(-cx,-cy,w,h); - - QPointF p = nodeLeft->pos(); - p.setX(qMin(cx, qMax(p.x(), -cx))); - p.setY(qMin(cy, qMax(p.y(), -cy))); - nodeLeft->setPos(p); - } - - if (rightStick->scene()) { - QRect qr = rightStick->contentsRect(); - qreal w = (qreal)qr.width() - GBALL_SIZE; - qreal h = (qreal)qr.height() - GBALL_SIZE; - qreal cx = (qreal)qr.width()/2; - qreal cy = (qreal)qr.height()/2; - rightStick->scene()->setSceneRect(-cx,-cy,w,h); - - QPointF p = nodeRight->pos(); - p.setX(qMin(cx, qMax(p.x(), -cx))); - p.setY(qMin(cy, qMax(p.y(), -cy))); - nodeRight->setPos(p); - } - QDialog::resizeEvent(event); -} - -void SimulatorDialog::on_holdLeftX_clicked(bool checked) -{ - nodeLeft->setCenteringX(!checked); -} - -void SimulatorDialog::on_holdLeftY_clicked(bool checked) -{ - nodeLeft->setCenteringY(!checked); -} - -void SimulatorDialog::on_holdRightX_clicked(bool checked) -{ - nodeRight->setCenteringX(!checked); -} - -void SimulatorDialog::on_holdRightY_clicked(bool checked) -{ - nodeRight->setCenteringY(!checked); -} - -void SimulatorDialog::on_FixLeftX_clicked(bool checked) -{ - nodeLeft->setFixedX(checked); -} - -void SimulatorDialog::on_FixLeftY_clicked(bool checked) -{ - nodeLeft->setFixedY(checked); -} - -void SimulatorDialog::on_FixRightX_clicked(bool checked) -{ - nodeRight->setFixedX(checked); -} - -void SimulatorDialog::on_FixRightY_clicked(bool checked) -{ - nodeRight->setFixedY(checked); -} - -#ifdef JOYSTICKS -void SimulatorDialog::onjoystickAxisValueChanged(int axis, int value) -{ - int stick; - if (axis>=0 && axis<=8) { - stick=jsmap[axis]; - int stickval; - if (value>jscal[axis][1]) { - if ((jscal[axis][2]-jscal[axis][1])==0) - return; - stickval=(1024*(value-jscal[axis][1]))/(jscal[axis][2]-jscal[axis][1]); - } - else { - if ((jscal[axis][1]-jscal[axis][0])==0) - return; - stickval=(1024*(value-jscal[axis][1]))/(jscal[axis][1]-jscal[axis][0]); - } - if (jscal[axis][3]==1) { - stickval*=-1; - } - if (stick==1 ) { - nodeRight->setY(-stickval/1024.0); - } - else if (stick==2) { - nodeRight->setX(stickval/1024.0); - } - else if (stick==3) { - nodeLeft->setY(-stickval/1024.0); - } - else if (stick==4) { - nodeLeft->setX(stickval/1024.0); - } - else if (stick >= 5 && stick < 5+pots.count()) { - pots[stick-5]->setValue(stickval); - } - } -} -#endif - -#include "simulatordialog9x.cpp" -#include "simulatordialogtaranis.cpp" -#include "simulatordialogflamenco.cpp" -#include "simulatordialoghorus.cpp" +#include "simulatordialog.h" +#include "appdata.h" +#include "lcdwidget.h" +#include +#include "helpers.h" +#include "simulatorinterface.h" +#include "sliderwidget.h" + +#define GBALL_SIZE 20 +#define RESX 1024 + +int SimulatorDialog::screenshotIdx = 0; +SimulatorDialog * traceCallbackInstance = 0; + +void traceCb(const char * text) +{ + // divert C callback into simulator instance + if (traceCallbackInstance) { + traceCallbackInstance->traceCallback(text); + } +} + +void SimulatorDialog::traceCallback(const char * text) +{ + // this function is called from other threads + traceMutex.lock(); + // limit the size of list + if (traceList.size() < 1000) { + traceList.append(QString(text)); + } + traceMutex.unlock(); +} + +void SimulatorDialog::updateDebugOutput() +{ + traceMutex.lock(); + while (!traceList.isEmpty()) { + QString text = traceList.takeFirst(); + traceBuffer.append(text); + // limit the size of traceBuffer + if (traceBuffer.size() > 10*1024) { + traceBuffer.remove(0, 1*1024); + } + if (DebugOut) { + DebugOut->traceCallback(QString(text)); + } + } + traceMutex.unlock(); +} + +void SimulatorDialog::wheelEvent (QWheelEvent *event) +{ + simulator->wheelEvent(event->delta() > 0 ? 1 : -1); +} + +SimulatorDialog::SimulatorDialog(QWidget * parent, SimulatorInterface *simulator, unsigned int flags): + QDialog(parent), + flags(flags), + timer(NULL), + lightOn(false), + simulator(simulator), + lastPhase(-1), + beepVal(0), + TelemetrySimu(0), + TrainerSimu(0), + DebugOut(0), + buttonPressed(0), + trimPressed (TRIM_NONE), + middleButtonPressed(false) +{ + //shorcut for telemetry simulator + // new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_T), this, SLOT(openTelemetrySimulator())); + new QShortcut(QKeySequence(Qt::Key_F4), this, SLOT(openTelemetrySimulator())); + new QShortcut(QKeySequence(Qt::Key_F5), this, SLOT(openTrainerSimulator())); + new QShortcut(QKeySequence(Qt::Key_F6), this, SLOT(openDebugOutput())); + new QShortcut(QKeySequence(Qt::Key_F7), this, SLOT(luaReload())); + traceCallbackInstance = this; +} + +SimulatorDialog::~SimulatorDialog() +{ + traceCallbackInstance = 0; + delete timer; + delete simulator; +} + +void SimulatorDialog::closeEvent (QCloseEvent *) +{ + simulator->stop(); + timer->stop(); +} + +void SimulatorDialog::mousePressEvent(QMouseEvent *event) +{ + if (event->button() == Qt::MidButton) { + middleButtonPressed = true; + } +} + +void SimulatorDialog::mouseReleaseEvent(QMouseEvent *event) +{ + if (event->button() == Qt::MidButton) { + middleButtonPressed = false; + } +} + +void SimulatorDialog::onTrimPressed() +{ + if (sender()->objectName() == QString("trimHL_L")) + trimPressed = TRIM_LH_L; + else if (sender()->objectName() == QString("trimHL_R")) + trimPressed = TRIM_LH_R; + else if (sender()->objectName() == QString("trimVL_D")) + trimPressed = TRIM_LV_DN; + else if (sender()->objectName() == QString("trimVL_U")) + trimPressed = TRIM_LV_UP; + else if (sender()->objectName() == QString("trimVR_D")) + trimPressed = TRIM_RV_DN; + else if (sender()->objectName() == QString("trimVR_U")) + trimPressed = TRIM_RV_UP; + else if (sender()->objectName() == QString("trimHR_L")) + trimPressed = TRIM_RH_L; + else if (sender()->objectName() == QString("trimHR_R")) + trimPressed = TRIM_RH_R; +} + +void SimulatorDialog::onTrimReleased() +{ + trimPressed = TRIM_NONE; +} + +void SimulatorDialog::openTelemetrySimulator() +{ + // allow only one instance + if (TelemetrySimu == 0) { + TelemetrySimu = new TelemetrySimulator(this, simulator); + TelemetrySimu->show(); + } + else if (!TelemetrySimu->isVisible()) { + TelemetrySimu->show(); + } +} + +void SimulatorDialog::openTrainerSimulator() +{ + // allow only one instance + if (TrainerSimu == 0) { + TrainerSimu = new TrainerSimulator(this, simulator); + TrainerSimu->show(); + } + else if (!TrainerSimu->isVisible()) { + TrainerSimu->show(); + } +} + +void SimulatorDialog::openDebugOutput() +{ + // allow only one instance, but install signal handler to catch dialog destruction just in case + if (DebugOut == 0) { + DebugOut = new DebugOutput(this); + QObject::connect(DebugOut, SIGNAL(destroyed()), this, SLOT(onDebugOutputClose())); + DebugOut->traceCallback(traceBuffer); + DebugOut->show(); + } + else if (!DebugOut->isVisible()) { + DebugOut->show(); + } +} + +void SimulatorDialog::luaReload() +{ + // force a reload of the lua environment (as if a standalone script were run) + simulator->setLuaStateReloadPermanentScripts(); +} + +void SimulatorDialog::onDebugOutputClose() +{ + DebugOut = 0; +} + + +void SimulatorDialog::keyPressEvent (QKeyEvent *event) +{ + switch (event->key()) { + case Qt::Key_Enter: + case Qt::Key_Return: + buttonPressed = Qt::Key_Enter; + break; + case Qt::Key_Escape: + case Qt::Key_Backspace: + buttonPressed = Qt::Key_Escape; + break; + case Qt::Key_Up: + case Qt::Key_Down: + case Qt::Key_Right: + case Qt::Key_Left: + case Qt::Key_Minus: + case Qt::Key_Plus: + case Qt::Key_PageDown: + case Qt::Key_PageUp: + buttonPressed = event->key(); + break; + } +} + +void SimulatorDialog::keyReleaseEvent(QKeyEvent * event) +{ + switch (event->key()) { + case Qt::Key_Enter: + case Qt::Key_Return: + case Qt::Key_Escape: + case Qt::Key_Backspace: + case Qt::Key_Up: + case Qt::Key_Down: + case Qt::Key_Right: + case Qt::Key_Left: + case Qt::Key_Plus: + case Qt::Key_Minus: + case Qt::Key_PageDown: + case Qt::Key_PageUp: + buttonPressed = 0; + break; + } +} + +void SimulatorDialog::setupTimer() +{ + timer = new QTimer(this); + connect(timer, SIGNAL(timeout()), this, SLOT(onTimerEvent())); + timer->start(10); +} + +template +void SimulatorDialog::initUi(T * ui) +{ + ui->setupUi(this); + + lcd = ui->lcd; + leftStick = ui->leftStick; + rightStick = ui->rightStick; + pots = findWidgets(this, "pot%1"); + potLabels = findWidgets(this, "potLabel%1"); + potValues = findWidgets(this, "potValue%1"); + sliders = findWidgets(this, "slider%1"); + + trimHLeft = ui->trimHLeft; + trimVLeft = ui->trimVLeft; + trimHRight = ui->trimHRight; + trimVRight = ui->trimVRight; + tabWidget = ui->tabWidget; + leftXPerc = ui->leftXPerc; + leftYPerc = ui->leftYPerc; + rightXPerc = ui->rightXPerc; + rightYPerc = ui->rightYPerc; + + setupSticks(); + + resize(0, 0); // to force min height, min width + setFixedSize(width(), height()); + +#ifdef JOYSTICKS + if (g.jsSupport()) { + int count=0; + for (int j=0; j<8; j++){ + int axe = g.joystick[j].stick_axe(); + if (axe>=0 && axe<8) { + jsmap[axe]=j+1; + jscal[axe][0] = g.joystick[j].stick_min(); + jscal[axe][1] = g.joystick[j].stick_med(); + jscal[axe][2] = g.joystick[j].stick_max(); + jscal[axe][3] = g.joystick[j].stick_inv(); + count++; + } + } + if (count<3) { + QMessageBox::critical(this, tr("Warning"), tr("Joystick enabled but not configured correctly")); + } + if (g.jsCtrl()!=-1) { + joystick = new Joystick(this); + if (joystick) { + if (joystick->open(g.jsCtrl())) { + int numAxes=std::min(joystick->numAxes,8); + for (int j=0; jsensitivities[j] = 0; + joystick->deadzones[j]=0; + } + nodeRight->setCenteringY(false); //mode 1,3 -> THR on right + ui->holdRightY->setChecked(true); + nodeRight->setCenteringX(false); //mode 1,3 -> THR on right + ui->holdRightX->setChecked(true); + nodeLeft->setCenteringY(false); //mode 1,3 -> THR on right + ui->holdLeftY->setChecked(true); + nodeLeft->setCenteringX(false); //mode 1,3 -> THR on right + ui->holdLeftX->setChecked(true); + connect(joystick, SIGNAL(axisValueChanged(int, int)), this, SLOT(onjoystickAxisValueChanged(int, int))); + } + else { + QMessageBox::critical(this, tr("Warning"), tr("Cannot open joystick, joystick disabled")); + } + } + } + } +#endif + + windowName = tr("Simulating Radio (%1)").arg(GetCurrentFirmware()->getName()); + setWindowTitle(windowName); + + simulator->setSdPath(g.profile[g.id()].sdPath()); + simulator->setVolumeGain(g.profile[g.id()].volumeGain()); + lcd->setData(simulator->getLcd(), lcdWidth, lcdHeight, lcdDepth); + + if (flags & SIMULATOR_FLAGS_STICK_MODE_LEFT) { + nodeLeft->setCenteringY(false); + ui->holdLeftY->setChecked(true); + } + else { + nodeRight->setCenteringY(false); + ui->holdRightY->setChecked(true); + } + + setTrims(); + + int outputs = std::min(32, GetCurrentFirmware()->getCapability(Outputs)); + if (outputs <= 16) { + // hide second Outputs tab + tabWidget->removeTab(tabWidget->indexOf(ui->outputs2)); + } + else { + tabWidget->setTabText(tabWidget->indexOf(ui->outputs), tr("Outputs") + QString(" 1-%1").arg(16)); + tabWidget->setTabText(tabWidget->indexOf(ui->outputs2), tr("Outputs") + QString(" 17-%1").arg(outputs)); + } + for (int i=0; ichannelsLayout; + int column = i / (std::min(16,outputs)/2); + int line = i % (std::min(16,outputs)/2); + if (i >= 16 ) { + outputTab = ui->channelsLayout2; + column = (i-16) / (std::min(16,outputs-16)/2); + line = (i-16) % (std::min(16,outputs-16)/2); + } + QLabel * label = new QLabel(tabWidget); + label->setText(RawSource(SOURCE_TYPE_CH, i).toString()); + outputTab->addWidget(label, line, column == 0 ? 0 : 5, 1, 1); + + QSlider * slider = new QSlider(tabWidget); + slider->setEnabled(false); + /*slider->setMaximumSize(QSize(16777215, 18)); + slider->setStyleSheet(QString::fromUtf8("QSlider::sub-page:horizontal:disabled {\n" + "border-color: #999;\n" + "}\n" + "\n" + "QSlider::add-page:horizontal:disabled {\n" + "border-color: #999;\n" + "}\n" + "\n" + "QSlider::handle:horizontal:disabled {\n" + "background: #0000CC;\n" + "border: 1px solid #aaa;\n" + "border-radius: 4px;\n" + "}")); */ + slider->setMinimum(-1024); + slider->setMaximum(1024); + slider->setPageStep(128); + slider->setTracking(false); + slider->setOrientation(Qt::Horizontal); + slider->setInvertedAppearance(false); + slider->setTickPosition(QSlider::TicksBelow); + channelSliders << slider; + outputTab->addWidget(slider, line, column == 0 ? 1 : 4, 1, 1); + + QLabel * value = new QLabel(tabWidget); + value->setMinimumSize(QSize(50, 0)); + value->setAlignment(Qt::AlignCenter); + channelValues << value; + outputTab->addWidget(value, line, column == 0 ? 2 : 3, 1, 1); + } + + int switches = GetCurrentFirmware()->getCapability(LogicalSwitches); + for (int i=0; ilogicalSwitchesLayout->addWidget(swtch, i / (switches/2), i % (switches/2), 1, 1); + if (outputs > 16) { + // repeat logical switches on second outputs tab + swtch = createLogicalSwitch(tabWidget, i, logicalSwitchLabels2); + ui->logicalSwitchesLayout2->addWidget(swtch, i / (switches/2), i % (switches/2), 1, 1); + } + } + + int fmodes = GetCurrentFirmware()->getCapability(FlightModes); + int gvars = GetCurrentFirmware()->getCapability(Gvars); + if (gvars>0) { + for (int fm=0; fmsetText(QString("FM%1").arg(fm)); + label->setAlignment(Qt::AlignCenter); + ui->gvarsLayout->addWidget(label, 0, fm+1); + } + for (int i=0; isetText(QString("GV%1").arg(i+1)); + label->setAutoFillBackground(true); + if ((i % 2) ==0 ) { + label->setStyleSheet("QLabel { background-color: rgb(220, 220, 220) }"); + } + ui->gvarsLayout->addWidget(label, i+1, 0); + for (int fm=0; fmsetAutoFillBackground(true); + value->setAlignment(Qt::AlignRight | Qt::AlignVCenter); + if ((i % 2) ==0 ) { + value->setStyleSheet("QLabel { background-color: rgb(220, 220, 220) }"); + } + gvarValues << value; + ui->gvarsLayout->addWidget(value, i+1, fm+1); + } + } + } + + if (flags & SIMULATOR_FLAGS_NOTX) { + ui->tabWidget->setCurrentWidget(ui->outputs); + } + else { + ui->tabWidget->setCurrentWidget(ui->simu); + } +} + +QFrame * SimulatorDialog::createLogicalSwitch(QWidget * parent, int switchNo, QVector & labels) +{ + QFrame * swtch = new QFrame(parent); + swtch->setAutoFillBackground(true); + swtch->setFrameShape(QFrame::Panel); + swtch->setFrameShadow(QFrame::Raised); + swtch->setLineWidth(2); + QVBoxLayout * layout = new QVBoxLayout(swtch); + layout->setContentsMargins(2, 2, 2, 2); + QLabel * label = new QLabel(swtch); + label->setText(RawSwitch(SWITCH_TYPE_VIRTUAL, switchNo+1).toString()); + label->setAlignment(Qt::AlignCenter); + labels << label; + layout->addWidget(label); + return swtch; +} + +void SimulatorDialog::onButtonPressed(int value) +{ + if (value == Qt::Key_Print) { + QString fileName = ""; + if (!g.snapToClpbrd()) { + fileName = QString("screenshot-%1.png").arg(++screenshotIdx); + } + lcd->makeScreenshot(fileName); + } + else { + buttonPressed = value; + } +} + +void SimulatorDialog::onTimerEvent() +{ + static unsigned int lcd_counter = 0; + if (!simulator->timer10ms()) { + QMessageBox::critical(this, "Companion", tr("Firmware %1 error: %2").arg(GetCurrentFirmware()->getName()).arg(simulator->getError())); + timer->stop(); + return; + } + + getValues(); + + if (tabWidget->currentIndex()==0) { + bool lightEnable; + if (simulator->lcdChanged(lightEnable)) { + lcd->onLcdChanged(lightEnable); + if (lightOn != lightEnable) { + setLightOn(lightEnable); + lightOn = lightEnable; + } + } + } + + // display current flight mode in window title + unsigned int currentPhase = simulator->getPhase(); + if (currentPhase != lastPhase) { + lastPhase = currentPhase; + const char * phase_name = simulator->getPhaseName(currentPhase); + if (phase_name && phase_name[0]) { + setWindowTitle(windowName + QString(" - Flight Mode %1").arg(QString(phase_name))); + } + else { + setWindowTitle(windowName + QString(" - Flight Mode %1").arg(simulator->getPhase())); + } + } + + if (!(lcd_counter++ % 5)) { + + setValues(); + + setTrims(); + + centerSticks(); + + updateBeepButton(); + + if (beepVal) { + beepVal = 0; + QApplication::beep(); + } + } + + updateDebugOutput(); +} + +void SimulatorDialog::centerSticks() +{ + if (leftStick->scene()) + nodeLeft->stepToCenter(); + + if (rightStick->scene()) + nodeRight->stepToCenter(); +} + +void SimulatorDialog::start(QByteArray & eeprom) +{ + lastPhase = -1; + numGvars = GetCurrentFirmware()->getCapability(Gvars); + numFlightModes = GetCurrentFirmware()->getCapability(FlightModes); + simulator->start(eeprom, (flags & SIMULATOR_FLAGS_NOTX) ? false : true); + getValues(); + setupTimer(); +} + +void SimulatorDialog::start(const char * filename) +{ + lastPhase = -1; + numGvars = GetCurrentFirmware()->getCapability(Gvars); + numFlightModes = GetCurrentFirmware()->getCapability(FlightModes); + simulator->start(filename); + getValues(); + setupTimer(); +} + +void SimulatorDialog::setTrims() +{ + Trims trims; + simulator->getTrims(trims); + + int trimMin = -125, trimMax = +125; + if (trims.extended) { + trimMin = -500; + trimMax = +500; + } + trimHLeft->setRange(trimMin, trimMax); trimHLeft->setValue(trims.values[0]); + trimVLeft->setRange(trimMin, trimMax); trimVLeft->setValue(trims.values[1]); + trimVRight->setRange(trimMin, trimMax); trimVRight->setValue(trims.values[2]); + trimHRight->setRange(trimMin, trimMax); trimHRight->setValue(trims.values[3]); +} + +inline int chVal(int val) +{ + return qMin(1024, qMax(-1024, val)); +} + +void SimulatorDialog::on_trimHLeft_valueChanged(int value) +{ + simulator->setTrim(0, value); +} + +void SimulatorDialog::on_trimVLeft_valueChanged(int value) +{ + simulator->setTrim(1, value); +} + +void SimulatorDialog::on_trimVRight_valueChanged(int value) +{ + simulator->setTrim(2, value); +} + +void SimulatorDialog::on_trimHRight_valueChanged(int value) +{ + simulator->setTrim(3, value); +} + +void SimulatorDialog::setValues() +{ + TxOutputs outputs; + simulator->getValues(outputs); + Trims trims; + simulator->getTrims(trims); + + for (int i=0; igetCapability(Outputs); i++) { + if (i < channelSliders.size()) { + channelSliders[i]->setValue(chVal(outputs.chans[i])); + channelValues[i]->setText(QString("%1").arg((qreal)outputs.chans[i]*100/1024, 0, 'f', 1)); + } + } + + leftXPerc->setText(QString("X %1%").arg((qreal)nodeLeft->getX()*100+trims.values[0]/5, 2, 'f', 0)); + leftYPerc->setText(QString("Y %1%").arg((qreal)nodeLeft->getY()*-100+trims.values[1]/5, 2, 'f', 0)); + + rightXPerc->setText(QString("X %1%").arg((qreal)nodeRight->getX()*100+trims.values[3]/5, 2, 'f', 0)); + rightYPerc->setText(QString("Y %1%").arg((qreal)nodeRight->getY()*-100+trims.values[2]/5, 2, 'f', 0)); + + QString CSWITCH_ON = "QLabel { background-color: #4CC417 }"; + QString CSWITCH_OFF = "QLabel { }"; + + for (int i=0; igetCapability(LogicalSwitches); i++) { + logicalSwitchLabels[i]->setStyleSheet(outputs.vsw[i] ? CSWITCH_ON : CSWITCH_OFF); + if (!logicalSwitchLabels2.isEmpty()) { + logicalSwitchLabels2[i]->setStyleSheet(outputs.vsw[i] ? CSWITCH_ON : CSWITCH_OFF); + } + } + + for (unsigned int gv=0; gvsetText(QString((fm==lastPhase)?"%1":"%1").arg(outputs.gvars[fm][gv])); + } + } + + if (outputs.beep) { + beepVal = outputs.beep; + } +} + +void SimulatorDialog::setupSticks() +{ + QGraphicsScene *leftScene = new QGraphicsScene(leftStick); + leftScene->setItemIndexMethod(QGraphicsScene::NoIndex); + leftStick->setScene(leftScene); + + // leftStick->scene()->addLine(0,10,20,30); + + QGraphicsScene *rightScene = new QGraphicsScene(rightStick); + rightScene->setItemIndexMethod(QGraphicsScene::NoIndex); + rightStick->setScene(rightScene); + + // rightStick->scene()->addLine(0,10,20,30); + + nodeLeft = new Node(); + nodeLeft->setPos(-GBALL_SIZE/2,-GBALL_SIZE/2); + nodeLeft->setBallSize(GBALL_SIZE); + leftScene->addItem(nodeLeft); + + nodeRight = new Node(); + nodeRight->setPos(-GBALL_SIZE/2,-GBALL_SIZE/2); + nodeRight->setBallSize(GBALL_SIZE); + rightScene->addItem(nodeRight); +} + +void SimulatorDialog::resizeEvent(QResizeEvent *event) +{ + if (leftStick->scene()) { + QRect qr = leftStick->contentsRect(); + qreal w = (qreal)qr.width() - GBALL_SIZE; + qreal h = (qreal)qr.height() - GBALL_SIZE; + qreal cx = (qreal)qr.width()/2; + qreal cy = (qreal)qr.height()/2; + leftStick->scene()->setSceneRect(-cx,-cy,w,h); + + QPointF p = nodeLeft->pos(); + p.setX(qMin(cx, qMax(p.x(), -cx))); + p.setY(qMin(cy, qMax(p.y(), -cy))); + nodeLeft->setPos(p); + } + + if (rightStick->scene()) { + QRect qr = rightStick->contentsRect(); + qreal w = (qreal)qr.width() - GBALL_SIZE; + qreal h = (qreal)qr.height() - GBALL_SIZE; + qreal cx = (qreal)qr.width()/2; + qreal cy = (qreal)qr.height()/2; + rightStick->scene()->setSceneRect(-cx,-cy,w,h); + + QPointF p = nodeRight->pos(); + p.setX(qMin(cx, qMax(p.x(), -cx))); + p.setY(qMin(cy, qMax(p.y(), -cy))); + nodeRight->setPos(p); + } + QDialog::resizeEvent(event); +} + +void SimulatorDialog::on_holdLeftX_clicked(bool checked) +{ + nodeLeft->setCenteringX(!checked); +} + +void SimulatorDialog::on_holdLeftY_clicked(bool checked) +{ + nodeLeft->setCenteringY(!checked); +} + +void SimulatorDialog::on_holdRightX_clicked(bool checked) +{ + nodeRight->setCenteringX(!checked); +} + +void SimulatorDialog::on_holdRightY_clicked(bool checked) +{ + nodeRight->setCenteringY(!checked); +} + +void SimulatorDialog::on_FixLeftX_clicked(bool checked) +{ + nodeLeft->setFixedX(checked); +} + +void SimulatorDialog::on_FixLeftY_clicked(bool checked) +{ + nodeLeft->setFixedY(checked); +} + +void SimulatorDialog::on_FixRightX_clicked(bool checked) +{ + nodeRight->setFixedX(checked); +} + +void SimulatorDialog::on_FixRightY_clicked(bool checked) +{ + nodeRight->setFixedY(checked); +} + +#ifdef JOYSTICKS +void SimulatorDialog::onjoystickAxisValueChanged(int axis, int value) +{ + int stick; + if (axis>=0 && axis<=8) { + stick=jsmap[axis]; + int stickval; + if (value>jscal[axis][1]) { + if ((jscal[axis][2]-jscal[axis][1])==0) + return; + stickval=(1024*(value-jscal[axis][1]))/(jscal[axis][2]-jscal[axis][1]); + } + else { + if ((jscal[axis][1]-jscal[axis][0])==0) + return; + stickval=(1024*(value-jscal[axis][1]))/(jscal[axis][1]-jscal[axis][0]); + } + if (jscal[axis][3]==1) { + stickval*=-1; + } + if (stick==1 ) { + nodeRight->setY(-stickval/1024.0); + } + else if (stick==2) { + nodeRight->setX(stickval/1024.0); + } + else if (stick==3) { + nodeLeft->setY(-stickval/1024.0); + } + else if (stick==4) { + nodeLeft->setX(stickval/1024.0); + } + else if (stick >= 5 && stick < 5+pots.count()) { + pots[stick-5]->setValue(stickval); + } + } +} +#endif + +#include "simulatordialog9x.cpp" +#include "simulatordialogtaranis.cpp" +#include "simulatordialogflamenco.cpp" +#include "simulatordialoghorus.cpp" diff --git a/companion/src/simulation/simulatordialog.h b/companion/src/simulation/simulatordialog.h index 8e2676296..60c5657e1 100644 --- a/companion/src/simulation/simulatordialog.h +++ b/companion/src/simulation/simulatordialog.h @@ -20,257 +20,257 @@ #ifndef _SIMULATORDIALOG_H_ #define _SIMULATORDIALOG_H_ - -#include "modeledit/node.h" -#include "telemetrysimu.h" -#include "trainersimu.h" -#include "debugoutput.h" - -#ifdef JOYSTICKS -#include "joystick.h" -#endif - -#define TMR_OFF 0 -#define TMR_RUNNING 1 -#define TMR_BEEPING 2 -#define TMR_STOPPED 3 - -#define FLASH_DURATION 10 - -namespace Ui { - class SimulatorDialog9X; - class SimulatorDialogTaranis; - class SimulatorDialogFlamenco; - class SimulatorDialogHorus; -} - -// TODO rename + move? -class LcdWidget; -class SliderWidget; - -#define SIMULATOR_FLAGS_NOTX 1 -#define SIMULATOR_FLAGS_STICK_MODE_LEFT 2 -#define SIMULATOR_FLAGS_S1 4 -#define SIMULATOR_FLAGS_S2 8 -#define SIMULATOR_FLAGS_S3 16 -#define SIMULATOR_FLAGS_S4 32 // reserved for the future -#define SIMULATOR_FLAGS_S1_MULTI 64 -#define SIMULATOR_FLAGS_S2_MULTI 128 -#define SIMULATOR_FLAGS_S3_MULTI 256 -#define SIMULATOR_FLAGS_S4_MULTI 512 // reserved for the future - -void traceCb(const char * text); - -class SimulatorDialog : public QDialog -{ - Q_OBJECT - - public: - explicit SimulatorDialog(QWidget * parent, SimulatorInterface *simulator, unsigned int flags=0); - virtual ~SimulatorDialog(); - - void start(const char * filename); - void start(QByteArray & eeprom); - virtual void traceCallback(const char * text); - - protected: - template void initUi(T * ui); - virtual void setLightOn(bool enable) { } - virtual void updateBeepButton() { } - - unsigned int flags; - LcdWidget * lcd; - QGraphicsView * leftStick, * rightStick; - QVector pots; - QVector potLabels; - QVector potValues; - QVector sliders; - - SliderWidget * trimHLeft, * trimVLeft, * trimHRight, * trimVRight; - QLabel * leftXPerc, * rightXPerc, * leftYPerc, * rightYPerc; - QTabWidget * tabWidget; - QVector logicalSwitchLabels; - QVector logicalSwitchLabels2; - QVector channelSliders; - QVector channelValues; - QVector gvarValues; - - void init(); - Node *nodeLeft; - Node *nodeRight; - QTimer *timer; - QString windowName; - unsigned int backLight; - bool lightOn; - int switches; - unsigned int numGvars; - unsigned int numFlightModes; -#ifdef JOYSTICKS - Joystick *joystick; - int jscal[8][4]; - int jsmap[8]; -#endif - - SimulatorInterface *simulator; - unsigned int lastPhase; - - void setupSticks(); - void setupTimer(); - void resizeEvent(QResizeEvent *event = 0); - - virtual void getValues() = 0; - void setValues(); - void centerSticks(); - - int getValue(qint8 i); - bool getSwitch(int swtch, bool nc, qint8 level=0); - void setTrims(); - QFrame * createLogicalSwitch(QWidget * parent, int switchNo, QVector & labels); - - int beepVal; - - int lcdWidth; - int lcdHeight; - int lcdDepth; - TelemetrySimulator * TelemetrySimu; - TrainerSimulator * TrainerSimu; - DebugOutput * DebugOut; - - QString traceBuffer; - QMutex traceMutex; - QList traceList; - void updateDebugOutput(); - - protected: - virtual void closeEvent(QCloseEvent *); - virtual void mousePressEvent(QMouseEvent *); - virtual void mouseReleaseEvent(QMouseEvent *); - virtual void wheelEvent(QWheelEvent *); - virtual void keyPressEvent(QKeyEvent *); - virtual void keyReleaseEvent(QKeyEvent *); - static int screenshotIdx; - int buttonPressed; - int trimPressed; - bool middleButtonPressed; - - private slots: - void onButtonPressed(int value); - void on_FixRightY_clicked(bool checked); - void on_FixRightX_clicked(bool checked); - void on_FixLeftY_clicked(bool checked); - void on_FixLeftX_clicked(bool checked); - void on_holdRightY_clicked(bool checked); - void on_holdRightX_clicked(bool checked); - void on_holdLeftY_clicked(bool checked); - void on_holdLeftX_clicked(bool checked); - void on_trimHLeft_valueChanged(int); - void on_trimVLeft_valueChanged(int); - void on_trimHRight_valueChanged(int); - void on_trimVRight_valueChanged(int); - void onTimerEvent(); - void onTrimPressed(); - void onTrimReleased(); - void openTelemetrySimulator(); - void openTrainerSimulator(); - void openDebugOutput(); - void onDebugOutputClose(); - void luaReload(); - -#ifdef JOYSTICKS - void onjoystickAxisValueChanged(int axis, int value); -#endif - -}; - -class SimulatorDialog9X: public SimulatorDialog -{ - Q_OBJECT - - public: - explicit SimulatorDialog9X(QWidget * parent, SimulatorInterface *simulator, unsigned int flags=0); - virtual ~SimulatorDialog9X(); - - protected: - virtual void getValues(); - virtual void setLightOn(bool enable); - virtual void updateBeepButton(); - void saveSwitches(void); - void restoreSwitches(void); - - protected slots: - void dialChanged(int index); - - private: - Ui::SimulatorDialog9X * ui; - static uint32_t switchstatus; - int beepShow; - -}; - -class SimulatorDialogTaranis: public SimulatorDialog -{ - Q_OBJECT - - public: - explicit SimulatorDialogTaranis(QWidget * parent, SimulatorInterface *simulator, unsigned int flags=0); - virtual ~SimulatorDialogTaranis(); - - protected: - virtual void getValues(); - void saveSwitches(void); - void restoreSwitches(void); - - private: - Ui::SimulatorDialogTaranis * ui; - static uint32_t switchstatus; - - private slots: - void resetSH(); - void on_switchH_sliderReleased(); -}; - -class SimulatorDialogFlamenco: public SimulatorDialog -{ - Q_OBJECT - - public: - explicit SimulatorDialogFlamenco(QWidget * parent, SimulatorInterface *simulator, unsigned int flags=0); - virtual ~SimulatorDialogFlamenco(); - - protected: - virtual void getValues(); - void saveSwitches(void); - void restoreSwitches(void); - - private: - Ui::SimulatorDialogFlamenco * ui; - static uint32_t switchstatus; - - private slots: - void resetSH(); - void on_switchH_sliderReleased(); -}; - -class SimulatorDialogHorus: public SimulatorDialog -{ - Q_OBJECT - - public: - explicit SimulatorDialogHorus(QWidget * parent, SimulatorInterface *simulator, unsigned int flags=0); - virtual ~SimulatorDialogHorus(); - - protected: - virtual void getValues(); - void saveSwitches(void); - void restoreSwitches(void); - - private: - Ui::SimulatorDialogHorus * ui; - static uint32_t switchstatus; - - private slots: - void resetSH(); - void on_switchH_sliderReleased(); -}; - + +#include "modeledit/node.h" +#include "telemetrysimu.h" +#include "trainersimu.h" +#include "debugoutput.h" + +#ifdef JOYSTICKS +#include "joystick.h" +#endif + +#define TMR_OFF 0 +#define TMR_RUNNING 1 +#define TMR_BEEPING 2 +#define TMR_STOPPED 3 + +#define FLASH_DURATION 10 + +namespace Ui { + class SimulatorDialog9X; + class SimulatorDialogTaranis; + class SimulatorDialogFlamenco; + class SimulatorDialogHorus; +} + +// TODO rename + move? +class LcdWidget; +class SliderWidget; + +#define SIMULATOR_FLAGS_NOTX 1 +#define SIMULATOR_FLAGS_STICK_MODE_LEFT 2 +#define SIMULATOR_FLAGS_S1 4 +#define SIMULATOR_FLAGS_S2 8 +#define SIMULATOR_FLAGS_S3 16 +#define SIMULATOR_FLAGS_S4 32 // reserved for the future +#define SIMULATOR_FLAGS_S1_MULTI 64 +#define SIMULATOR_FLAGS_S2_MULTI 128 +#define SIMULATOR_FLAGS_S3_MULTI 256 +#define SIMULATOR_FLAGS_S4_MULTI 512 // reserved for the future + +void traceCb(const char * text); + +class SimulatorDialog : public QDialog +{ + Q_OBJECT + + public: + explicit SimulatorDialog(QWidget * parent, SimulatorInterface *simulator, unsigned int flags=0); + virtual ~SimulatorDialog(); + + void start(const char * filename); + void start(QByteArray & eeprom); + virtual void traceCallback(const char * text); + + protected: + template void initUi(T * ui); + virtual void setLightOn(bool enable) { } + virtual void updateBeepButton() { } + + unsigned int flags; + LcdWidget * lcd; + QGraphicsView * leftStick, * rightStick; + QVector pots; + QVector potLabels; + QVector potValues; + QVector sliders; + + SliderWidget * trimHLeft, * trimVLeft, * trimHRight, * trimVRight; + QLabel * leftXPerc, * rightXPerc, * leftYPerc, * rightYPerc; + QTabWidget * tabWidget; + QVector logicalSwitchLabels; + QVector logicalSwitchLabels2; + QVector channelSliders; + QVector channelValues; + QVector gvarValues; + + void init(); + Node *nodeLeft; + Node *nodeRight; + QTimer *timer; + QString windowName; + unsigned int backLight; + bool lightOn; + int switches; + unsigned int numGvars; + unsigned int numFlightModes; +#ifdef JOYSTICKS + Joystick *joystick; + int jscal[8][4]; + int jsmap[8]; +#endif + + SimulatorInterface *simulator; + unsigned int lastPhase; + + void setupSticks(); + void setupTimer(); + void resizeEvent(QResizeEvent *event = 0); + + virtual void getValues() = 0; + void setValues(); + void centerSticks(); + + int getValue(qint8 i); + bool getSwitch(int swtch, bool nc, qint8 level=0); + void setTrims(); + QFrame * createLogicalSwitch(QWidget * parent, int switchNo, QVector & labels); + + int beepVal; + + int lcdWidth; + int lcdHeight; + int lcdDepth; + TelemetrySimulator * TelemetrySimu; + TrainerSimulator * TrainerSimu; + DebugOutput * DebugOut; + + QString traceBuffer; + QMutex traceMutex; + QList traceList; + void updateDebugOutput(); + + protected: + virtual void closeEvent(QCloseEvent *); + virtual void mousePressEvent(QMouseEvent *); + virtual void mouseReleaseEvent(QMouseEvent *); + virtual void wheelEvent(QWheelEvent *); + virtual void keyPressEvent(QKeyEvent *); + virtual void keyReleaseEvent(QKeyEvent *); + static int screenshotIdx; + int buttonPressed; + int trimPressed; + bool middleButtonPressed; + + private slots: + void onButtonPressed(int value); + void on_FixRightY_clicked(bool checked); + void on_FixRightX_clicked(bool checked); + void on_FixLeftY_clicked(bool checked); + void on_FixLeftX_clicked(bool checked); + void on_holdRightY_clicked(bool checked); + void on_holdRightX_clicked(bool checked); + void on_holdLeftY_clicked(bool checked); + void on_holdLeftX_clicked(bool checked); + void on_trimHLeft_valueChanged(int); + void on_trimVLeft_valueChanged(int); + void on_trimHRight_valueChanged(int); + void on_trimVRight_valueChanged(int); + void onTimerEvent(); + void onTrimPressed(); + void onTrimReleased(); + void openTelemetrySimulator(); + void openTrainerSimulator(); + void openDebugOutput(); + void onDebugOutputClose(); + void luaReload(); + +#ifdef JOYSTICKS + void onjoystickAxisValueChanged(int axis, int value); +#endif + +}; + +class SimulatorDialog9X: public SimulatorDialog +{ + Q_OBJECT + + public: + explicit SimulatorDialog9X(QWidget * parent, SimulatorInterface *simulator, unsigned int flags=0); + virtual ~SimulatorDialog9X(); + + protected: + virtual void getValues(); + virtual void setLightOn(bool enable); + virtual void updateBeepButton(); + void saveSwitches(void); + void restoreSwitches(void); + + protected slots: + void dialChanged(int index); + + private: + Ui::SimulatorDialog9X * ui; + static uint32_t switchstatus; + int beepShow; + +}; + +class SimulatorDialogTaranis: public SimulatorDialog +{ + Q_OBJECT + + public: + explicit SimulatorDialogTaranis(QWidget * parent, SimulatorInterface *simulator, unsigned int flags=0); + virtual ~SimulatorDialogTaranis(); + + protected: + virtual void getValues(); + void saveSwitches(void); + void restoreSwitches(void); + + private: + Ui::SimulatorDialogTaranis * ui; + static uint32_t switchstatus; + + private slots: + void resetSH(); + void on_switchH_sliderReleased(); +}; + +class SimulatorDialogFlamenco: public SimulatorDialog +{ + Q_OBJECT + + public: + explicit SimulatorDialogFlamenco(QWidget * parent, SimulatorInterface *simulator, unsigned int flags=0); + virtual ~SimulatorDialogFlamenco(); + + protected: + virtual void getValues(); + void saveSwitches(void); + void restoreSwitches(void); + + private: + Ui::SimulatorDialogFlamenco * ui; + static uint32_t switchstatus; + + private slots: + void resetSH(); + void on_switchH_sliderReleased(); +}; + +class SimulatorDialogHorus: public SimulatorDialog +{ + Q_OBJECT + + public: + explicit SimulatorDialogHorus(QWidget * parent, SimulatorInterface *simulator, unsigned int flags=0); + virtual ~SimulatorDialogHorus(); + + protected: + virtual void getValues(); + void saveSwitches(void); + void restoreSwitches(void); + + private: + Ui::SimulatorDialogHorus * ui; + static uint32_t switchstatus; + + private slots: + void resetSH(); + void on_switchH_sliderReleased(); +}; + #endif // _SIMULATORDIALOG_H_