--HG--
branch : develop
This commit is contained in:
MitSchoko 2014-11-27 00:08:30 +01:00
commit 35ddb14011
123 changed files with 1544 additions and 2005 deletions

View file

@ -4,7 +4,7 @@ Valentina Web page: http://www.valentina-project.org/
Valentina user manual https://bitbucket.org/dismine/valentina/wiki/manual/Content
Valentina main repository: https://bitbucket.org/dismine/valentina/overview
Valentina mail list (forum) https://groups.google.com/forum/#!forum/valentina-project-list
PPA for Ubuntu 14.04(develop): https://launchpad.net/~dismine/+archive/valentina-dev
PPA for Ubuntu (develop): https://launchpad.net/~dismine/+archive/valentina-dev
Help translate https://www.transifex.com/organization/valentina
Valentina
@ -27,7 +27,7 @@ Building the sources requires Qt 5.2.1 or later.
Compiling Valentina
====================
Prerequisites:
* Qt 5.0.2 or later (On Unix development packages needed)
* Qt 5.2.1 or later (On Unix development packages needed)
* mercurial
* On Unix:
- ccache
@ -45,7 +45,7 @@ The installed toolchains have to match the one Qt was compiled with.
You can build Valentina with
cd $SOURCE_DIRECTORY
qmake -r
qmake Valentina.pro -r (or qmake-qt5, depending on your platform)
make (or mingw32-make or nmake or jom, depending on your platform)
Note:In order to build and use Valentina, the PATH environment variable
@ -61,6 +61,14 @@ You may also need to ensure that the locations of your compiler and
other build tools are listed in the PATH variable. This will depend on
your choice of software development environment.
Unix systems:
Default prefix for command "make install" is /usr. For using another
prefix build with qmake command:
qmake PREFIX=/usr/local Valentina.pro -r
where /usr/local is a new prefix for installation.
LICENSING
==========
Valentina is free software: you can redistribute it and/or modify
@ -73,4 +81,4 @@ but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
See LICENSE file for further information
See LICENSE file for further information

View file

@ -1,9 +1,9 @@
include(Valentina.pri)
#Check if Qt version >= 5.0.2
!minQtVersion(5, 0, 2) {
#Check if Qt version >= 5.2.1
!minQtVersion(5, 2, 1) {
message("Cannot build Valentina with Qt version $${QT_VERSION}.")
error("Use at least Qt 5.0.2.")
error("Use at least Qt 5.2.1.")
}
TEMPLATE = subdirs

12
dist/debian/control vendored
View file

@ -3,20 +3,20 @@ Section: graphics
Priority: optional
Maintainer: Roman Telezhynskyi <dismine@gmail.com>
Build-Depends: debhelper (>= 8.0.0),
qtbase5-dev (>= 5.0.2),
libqt5svg5-dev (>= 5.0.2),
qtbase5-dev (>= 5.2.1),
libqt5svg5-dev (>= 5.2.1),
ccache,
g++ (>= 4.6.0),
qt5-default (>= 5.0.2),
qttools5-dev-tools (>= 5.0.2),
libqt5xmlpatterns5-dev (>= 5.0.2)
qt5-default (>= 5.2.1),
qttools5-dev-tools (>= 5.2.1),
libqt5xmlpatterns5-dev (>= 5.2.1)
Standards-Version: 3.9.5
Homepage: http://www.valentina-project.org/
Vcs-Browser: https://bitbucket.org/dismine/valentina
Package: valentina
Architecture: i386 amd64
Depends: libc6 (>= 2.4), libgcc1 (>= 1:4.1.1), libqt5core5a (>= 5.0.2), libqt5gui5 (>= 5.0.2) | libqt5gui5-gles (>= 5.0.2), libqt5printsupport5 (>= 5.0.2), libqt5svg5 (>= 5.0.2), libqt5widgets5 (>= 5.0.2), libqt5xml5 (>= 5.0.2), libqt5xmlpatterns5 (>= 5.0.2), libstdc++6 (>= 4.6), xpdf
Depends: libc6 (>= 2.4), libgcc1 (>= 1:4.1.1), libqt5core5a (>= 5.2.0), libqt5gui5 (>= 5.2.0) | libqt5gui5-gles (>= 5.2.0), libqt5printsupport5 (>= 5.2.0), libqt5svg5 (>= 5.2.0), libqt5widgets5 (>= 5.2.0), libqt5xml5 (>= 5.2.0), libqt5xmlpatterns5 (>= 5.2.0), libstdc++6 (>= 4.6), xpdf
Description: Pattern making program.
Valentina is a cross-platform patternmaking program which allows designers
to create and model patterns of clothing. This software allows pattern

10
dist/debian/rules vendored
View file

@ -4,6 +4,14 @@
#export DH_VERBOSE=1
APPNAME := Valentina
DEB_HOST_ARCH := $(shell dpkg-architecture -qDEB_HOST_ARCH)
ifeq ($(DEB_HOST_ARCH),amd64)
LIBPATH:= /debian/tmp/usr/lib64
else
LIBPATH:= /debian/tmp/usr/lib
endif
builddir:
mkdir -p builddir
@ -48,7 +56,7 @@
dh_fixperms
dh_makeshlibs
dh_installdeb
dh_shlibdeps -Llibqmuparser2 -l$(CURDIR)/debian/tmp/usr/lib -Llibvpropertyexplorer -l$(CURDIR)/debian/tmp/usr/lib
dh_shlibdeps -Llibqmuparser2 -l$(CURDIR)$(LIBPATH) -Llibvpropertyexplorer -l$(CURDIR)$(LIBPATH)
dh_shlibdeps
dh_gencontrol
dh_md5sums

View file

@ -1,5 +1,5 @@
usr/bin/*
usr/lib/lib*
usr/lib*
usr/share/valentina/translations/*
usr/share/valentina/tables/standard/*
usr/share/pixmaps/*

View file

@ -144,7 +144,6 @@ CONFIG(debug, debug|release){
DEFINES += "LOC_REV=0"
}else{
# Release mode
DEFINES += QT_NO_DEBUG_OUTPUT
!unix:*-g++{
QMAKE_CXXFLAGS += -fno-omit-frame-pointer # Need for exchndl.dll

View file

@ -31,6 +31,7 @@
#include <QSettings>
#include "../core/vapplication.h"
#include "vcontainer.h"
#include "../core/vsettings.h"
using namespace qmu;
@ -52,6 +53,7 @@ using namespace qmu;
Calculator::Calculator(const VContainer *data)
:QmuParser(), vVarVal(nullptr), data(data)
{
SCASSERT(data != nullptr)
InitCharacterSets();
setAllowSubexpressions(false);//Only one expression per time
@ -88,6 +90,7 @@ Calculator::Calculator(const QString &formula, bool fromUser)
Eval();
}
//---------------------------------------------------------------------------------------------------------------------
Calculator::~Calculator()
{
delete [] vVarVal;
@ -112,7 +115,7 @@ qreal Calculator::EvalFormula(const QString &formula)
QMap<int, QString> tokens = this->GetTokens();
// Remove "-" from tokens list if exist. If don't do that unary minus operation will broken.
RemoveAll(tokens, "-");
RemoveAll(tokens, QStringLiteral("-"));
if (tokens.isEmpty())
{
@ -132,6 +135,7 @@ void Calculator::InitVariables(const VContainer *data, const QMap<int, QString>
vVarVal = new qreal[2];
}
SCASSERT(data != nullptr)
const QHash<QString, QSharedPointer<VInternalVariable> > *vars = data->DataVariables();
QMap<int, QString>::const_iterator i = tokens.constBegin();
@ -225,7 +229,7 @@ void Calculator::SetSepForTr(bool fromUser)
{
if (fromUser)
{
bool osSeparatorValue = qApp->getSettings()->value("configuration/osSeparator", 1).toBool();
const bool osSeparatorValue = qApp->getSettings()->GetOsSeparator();
if (osSeparatorValue)
{

View file

@ -68,7 +68,7 @@ private:
static qreal* AddVariable(const QString &a_szName, void *a_pUserData);
void SetSepForEval();
void SetSepForTr(bool fromUser);
void RemoveAll(QMap<int, QString> &map, const QString &val);
static void RemoveAll(QMap<int, QString> &map, const QString &val);
};
#endif // CALCULATOR_H

View file

@ -1,35 +1,35 @@
SOURCES += \
container/vcontainer.cpp \
container/calculator.cpp \
container/vmeasurement.cpp \
container/vincrement.cpp \
container/vvariable.cpp \
container/vinternalvariable.cpp \
container/vlineangle.cpp \
container/varclength.cpp \
container/vcurvelength.cpp \
container/vlinelength.cpp \
container/vsplinelength.cpp \
container/variables/vmeasurement.cpp \
container/variables/vincrement.cpp \
container/variables/vvariable.cpp \
container/variables/vinternalvariable.cpp \
container/variables/vlineangle.cpp \
container/variables/varclength.cpp \
container/variables/vcurvelength.cpp \
container/variables/vlinelength.cpp \
container/variables/vsplinelength.cpp \
container/vformula.cpp
HEADERS += \
container/vcontainer.h \
container/calculator.h \
container/vmeasurement.h \
container/vincrement.h \
container/vvariable.h \
container/vinternalvariable.h \
container/vlineangle.h \
container/variables/vmeasurement.h \
container/variables/vincrement.h \
container/variables/vvariable.h \
container/variables/vinternalvariable.h \
container/variables/vlineangle.h \
container/variables.h \
container/vcurvelength.h \
container/varclength.h \
container/vlinelength.h \
container/vsplinelength.h \
container/vinternalvariable_p.h \
container/vvariable_p.h \
container/vincrement_p.h \
container/vcurvelength_p.h \
container/vlineangle_p.h \
container/vlinelength_p.h \
container/vmeasurement_p.h \
container/variables/vcurvelength.h \
container/variables/varclength.h \
container/variables/vlinelength.h \
container/variables/vsplinelength.h \
container/variables/vinternalvariable_p.h \
container/variables/vvariable_p.h \
container/variables/vincrement_p.h \
container/variables/vcurvelength_p.h \
container/variables/vlineangle_p.h \
container/variables/vlinelength_p.h \
container/variables/vmeasurement_p.h \
container/vformula.h

View file

@ -29,12 +29,12 @@
#ifndef VARIABLES_H
#define VARIABLES_H
#include "vinternalvariable.h"
#include "vmeasurement.h"
#include "vincrement.h"
#include "varclength.h"
#include "vsplinelength.h"
#include "vlinelength.h"
#include "vlineangle.h"
#include "variables/vinternalvariable.h"
#include "variables/vmeasurement.h"
#include "variables/vincrement.h"
#include "variables/varclength.h"
#include "variables/vsplinelength.h"
#include "variables/vlinelength.h"
#include "variables/vlineangle.h"
#endif // VARIABLES_H

View file

@ -30,6 +30,7 @@
#include "../container/calculator.h"
#include "../container/vcontainer.h"
#include "../core/vapplication.h"
#include "../core/vsettings.h"
#include <QDebug>
//VFormula
@ -239,7 +240,7 @@ void VFormula::Eval()
else
{
QLocale loc;
if (qApp->getSettings()->value("configuration/osSeparator", 1).toBool())
if (qApp->getSettings()->GetOsSeparator())
{
loc = QLocale::system();
}

View file

@ -2,12 +2,10 @@ HEADERS += \
core/vapplication.h \
core/vtranslation.h \
core/undoevent.h \
core/qcommandlineoption.h \
core/qcommandlineparser.h
core/vsettings.h
SOURCES += \
core/vapplication.cpp \
core/vtranslation.cpp \
core/undoevent.cpp \
core/qcommandlineoption.cpp \
core/qcommandlineparser.cpp
core/vsettings.cpp

View file

@ -1,320 +0,0 @@
/****************************************************************************
**
** Copyright (C) 2013 Laszlo Papp <lpapp@kde.org>
** Copyright (C) 2013 David Faure <faure@kde.org>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qcommandlineoption.h"
#if QT_VERSION < QT_VERSION_CHECK(5, 2, 1)
#include <QSet>
#ifdef Q_CC_GNU
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
#endif
class QCommandLineOptionPrivate : public QSharedData
{
public:
inline QCommandLineOptionPrivate()
{ }
void setNames(const QStringList &nameList);
//! The list of names used for this option.
QStringList names;
//! The documentation name for the value, if one is expected
//! Example: "-o <file>" means valueName == "file"
QString valueName;
//! The description used for this option.
QString description;
//! The list of default values used for this option.
QStringList defaultValues;
};
#ifdef Q_CC_GNU
#pragma GCC diagnostic pop
#endif
/*!
\since 5.2
\class QCommandLineOption
\brief The QCommandLineOption class defines a possible command-line option.
\inmodule QtCore
\ingroup shared
\ingroup tools
This class is used to describe an option on the command line. It allows
different ways of defining the same option with multiple aliases possible.
It is also used to describe how the option is used - it may be a flag (e.g. \c{-v})
or take an argument (e.g. \c{-o file}).
Examples:
\snippet code/src_corelib_tools_qcommandlineoption.cpp 0
\sa QCommandLineParser
*/
/*!
Constructs a command line option object with the given arguments.
The name of the option is set to \a name.
The name can be either short or long. If the name is one character in
length, it is considered a short name. Option names must not be empty,
must not start with a dash or a slash character, must not contain a \c{=}
and cannot be repeated.
The description is set to \a description. It is customary to add a "."
at the end of the description.
In addition, the \a valueName can be set if the option expects a value.
The default value for the option is set to \a defaultValue.
\sa setDescription(), setValueName(), setDefaultValues()
*/
QCommandLineOption::QCommandLineOption(const QString &name, const QString &description,
const QString &valueName,
const QString &defaultValue)
: d(new QCommandLineOptionPrivate)
{
d->setNames(QStringList(name));
setValueName(valueName);
setDescription(description);
setDefaultValue(defaultValue);
}
/*!
Constructs a command line option object with the given arguments.
This overload allows to set multiple names for the option, for instance
\c{o} and \c{output}.
The names of the option are set to \a names.
The names can be either short or long. Any name in the list that is one
character in length is a short name. Option names must not be empty,
must not start with a dash or a slash character, must not contain a \c{=}
and cannot be repeated.
The description is set to \a description. It is customary to add a "."
at the end of the description.
In addition, the \a valueName can be set if the option expects a value.
The default value for the option is set to \a defaultValue.
\sa setDescription(), setValueName(), setDefaultValues()
*/
QCommandLineOption::QCommandLineOption(const QStringList &names, const QString &description,
const QString &valueName,
const QString &defaultValue)
: d(new QCommandLineOptionPrivate)
{
d->setNames(names);
setValueName(valueName);
setDescription(description);
setDefaultValue(defaultValue);
}
/*!
Constructs a QCommandLineOption object that is a copy of the QCommandLineOption
object \a other.
\sa operator=()
*/
QCommandLineOption::QCommandLineOption(const QCommandLineOption &other)
: d(other.d)
{
}
/*!
Destroys the command line option object.
*/
QCommandLineOption::~QCommandLineOption()
{
}
/*!
Makes a copy of the \a other object and assigns it to this QCommandLineOption
object.
*/
QCommandLineOption &QCommandLineOption::operator=(const QCommandLineOption &other)
{
d = other.d;
return *this;
}
/*!
Returns the names set for this option.
*/
QStringList QCommandLineOption::names() const
{
return d->names;
}
void QCommandLineOptionPrivate::setNames(const QStringList &nameList)
{
QStringList newNames;
newNames.reserve(nameList.size());
if (nameList.isEmpty())
qWarning("QCommandLineOption: Options must have at least one name");
Q_FOREACH (const QString &name, nameList) {
if (name.isEmpty()) {
qWarning("QCommandLineOption: Option names cannot be empty");
} else {
const QChar c = name.at(0);
if (c == QLatin1Char('-'))
qWarning("QCommandLineOption: Option names cannot start with a '-'");
else if (c == QLatin1Char('/'))
qWarning("QCommandLineOption: Option names cannot start with a '/'");
else if (name.contains(QLatin1Char('=')))
qWarning("QCommandLineOption: Option names cannot contain a '='");
else
newNames.append(name);
}
}
// commit
names.swap(newNames);
}
/*!
Sets the name of the expected value, for the documentation, to \a valueName.
Options without a value assigned have a boolean-like behavior:
either the user specifies --option or they don't.
Options with a value assigned need to set a name for the expected value,
for the documentation of the option in the help output. An option with names \c{o} and \c{output},
and a value name of \c{file} will appear as \c{-o, --output <file>}.
Call QCommandLineParser::argument() if you expect the option to be present
only once, and QCommandLineParser::arguments() if you expect that option
to be present multiple times.
\sa valueName()
*/
void QCommandLineOption::setValueName(const QString &valueName)
{
d->valueName = valueName;
}
/*!
Returns the name of the expected value.
If empty, the option doesn't take a value.
\sa setValueName()
*/
QString QCommandLineOption::valueName() const
{
return d->valueName;
}
/*!
Sets the description used for this option to \a description.
It is customary to add a "." at the end of the description.
The description is used by QCommandLineParser::showHelp().
\sa description()
*/
void QCommandLineOption::setDescription(const QString &description)
{
d->description = description;
}
/*!
Returns the description set for this option.
\sa setDescription()
*/
QString QCommandLineOption::description() const
{
return d->description;
}
/*!
Sets the default value used for this option to \a defaultValue.
The default value is used if the user of the application does not specify
the option on the command line.
If \a defaultValue is empty, the option has no default values.
\sa defaultValues() setDefaultValues()
*/
void QCommandLineOption::setDefaultValue(const QString &defaultValue)
{
QStringList newDefaultValues;
if (!defaultValue.isEmpty()) {
newDefaultValues.reserve(1);
newDefaultValues << defaultValue;
}
// commit:
d->defaultValues.swap(newDefaultValues);
}
/*!
Sets the list of default values used for this option to \a defaultValues.
The default values are used if the user of the application does not specify
the option on the command line.
\sa defaultValues() setDefaultValue()
*/
void QCommandLineOption::setDefaultValues(const QStringList &defaultValues)
{
d->defaultValues = defaultValues;
}
/*!
Returns the default values set for this option.
\sa setDefaultValues()
*/
QStringList QCommandLineOption::defaultValues() const
{
return d->defaultValues;
}
#endif //QT_VERSION < QT_VERSION_CHECK(5, 2, 1)

View file

@ -1,96 +0,0 @@
/****************************************************************************
**
** Copyright (C) 2013 Laszlo Papp <lpapp@kde.org>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QCOMMANDLINEOPTION_H
#define QCOMMANDLINEOPTION_H
#include <QtGlobal>
#if QT_VERSION < QT_VERSION_CHECK(5, 2, 1)
#include <QStringList>
#include <QSharedData>
#ifdef Q_CC_GNU
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
#endif
class QCommandLineOptionPrivate;
class QCommandLineOption
{
public:
explicit QCommandLineOption(const QString &name, const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString());
explicit QCommandLineOption(const QStringList &names, const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString());
QCommandLineOption(const QCommandLineOption &other);
~QCommandLineOption();
QCommandLineOption &operator=(const QCommandLineOption &other);
QStringList names() const;
void setValueName(const QString &name);
QString valueName() const;
void setDescription(const QString &description);
QString description() const;
void setDefaultValue(const QString &defaultValue);
void setDefaultValues(const QStringList &defaultValues);
QStringList defaultValues() const;
private:
QSharedDataPointer<QCommandLineOptionPrivate> d;
};
#ifdef Q_CC_GNU
#pragma GCC diagnostic pop
#endif
#endif //QT_VERSION < QT_VERSION_CHECK(5, 2, 1)
#endif // QCOMMANDLINEOPTION_H

View file

@ -1,959 +0,0 @@
/****************************************************************************
**
** Copyright (C) 2013 Laszlo Papp <lpapp@kde.org>
** Copyright (C) 2013 David Faure <faure@kde.org>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qcommandlineparser.h"
#if QT_VERSION < QT_VERSION_CHECK(5, 2, 1)
#include <QCoreApplication>
#include <QHash>
#include <QVector>
#include <stdio.h>
#include <stdlib.h>
typedef QHash<QString, int> NameHash_t;
#ifdef Q_CC_GNU
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
#pragma GCC diagnostic ignored "-Wswitch-default"
#pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn"
#endif
class QCommandLineParserPrivate
{
public:
inline QCommandLineParserPrivate()
: singleDashWordOptionMode(QCommandLineParser::ParseAsCompactedShortOptions),
builtinVersionOption(false),
builtinHelpOption(false),
needsParsing(true)
{ }
bool parse(const QStringList &args);
void checkParsed(const char *method);
QStringList aliases(const QString &name) const;
QString helpText() const;
bool registerFoundOption(const QString &optionName);
bool parseOptionValue(const QString &optionName, const QString &argument,
QStringList::const_iterator *argumentIterator,
QStringList::const_iterator argsEnd);
//! Error text set when parse() returns false
QString errorText;
//! The command line options used for parsing
QList<QCommandLineOption> commandLineOptionList;
//! Hash mapping option names to their offsets in commandLineOptionList and optionArgumentList.
NameHash_t nameHash;
//! Option values found (only for options with a value)
QHash<int, QStringList> optionValuesHash;
//! Names of options found on the command line.
QStringList optionNames;
//! Arguments which did not belong to any option.
QStringList positionalArgumentList;
//! Names of options which were unknown.
QStringList unknownOptionNames;
//! Application description
QString description;
//! Documentation for positional arguments
struct PositionalArgumentDefinition
{
QString name;
QString description;
QString syntax;
};
QVector<PositionalArgumentDefinition> positionalArgumentDefinitions;
//! The parsing mode for "-abc"
QCommandLineParser::SingleDashWordOptionMode singleDashWordOptionMode;
//! Whether addVersionOption was called
bool builtinVersionOption;
//! Whether addHelpOption was called
bool builtinHelpOption;
//! True if parse() needs to be called
bool needsParsing;
};
QStringList QCommandLineParserPrivate::aliases(const QString &optionName) const
{
const NameHash_t::const_iterator it = nameHash.find(optionName);
if (it == nameHash.end()) {
qWarning("QCommandLineParser: option not defined: \"%s\"", qPrintable(optionName));
return QStringList();
}
return commandLineOptionList.at(*it).names();
}
/*!
\since 5.2
\class QCommandLineParser
\inmodule QtCore
\ingroup tools
\brief The QCommandLineParser class provides a means for handling the
command line options.
QCoreApplication provides the command-line arguments as a simple list of strings.
QCommandLineParser provides the ability to define a set of options, parse the
command-line arguments, and store which options have actually been used, as
well as option values.
Any argument that isn't an option (i.e. doesn't start with a \c{-}) is stored
as a "positional argument".
The parser handles short names, long names, more than one name for the same
option, and option values.
Options on the command line are recognized as starting with a single or
double \c{-} character(s).
The option \c{-} (single dash alone) is a special case, often meaning standard
input, and not treated as an option. The parser will treat everything after the
option \c{--} (double dash) as positional arguments.
Short options are single letters. The option \c{v} would be specified by
passing \c{-v} on the command line. In the default parsing mode, short options
can be written in a compact form, for instance \c{-abc} is equivalent to \c{-a -b -c}.
The parsing mode for can be set to ParseAsLongOptions, in which case \c{-abc}
will be parsed as the long option \c{abc}.
Long options are more than one letter long and cannot be compacted together.
The long option \c{verbose} would be passed as \c{--verbose} or \c{-verbose}.
Passing values to options can be done using the assignment operator: \c{-v=value}
\c{--verbose=value}, or a space: \c{-v value} \c{--verbose value}, i.e. the next
argument is used as value (even if it starts with a \c{-}).
The parser does not support optional values - if an option is set to
require a value, one must be present. If such an option is placed last
and has no value, the option will be treated as if it had not been
specified.
The parser does not automatically support negating or disabling long options
by using the format \c{--disable-option} or \c{--no-option}. However, it is
possible to handle this case explicitly by making an option with \c{no-option}
as one of its names, and handling the option explicitly.
Example:
\snippet code/src_corelib_tools_qcommandlineparser_main.cpp 0
Known limitation: the parsing of Qt options inside QCoreApplication and subclasses
happens before QCommandLineParser exists, so it can't take it into account. This
means any option value that looks like a builtin Qt option, will be treated by
QCoreApplication as a builtin Qt option. Example: \c{--profile -reverse} will
lead to QGuiApplication seeing the -reverse option set, and removing it from
QCoreApplication::arguments() before QCommandLineParser defines the \c{profile}
option and parses the command line.
\sa QCommandLineOption, QCoreApplication
*/
/*!
Constructs a command line parser object.
*/
QCommandLineParser::QCommandLineParser()
: d(new QCommandLineParserPrivate)
{
}
/*!
Destroys the command line parser object.
*/
QCommandLineParser::~QCommandLineParser()
{
delete d;
}
/*!
\enum QCommandLineParser::SingleDashWordOptionMode
This enum describes the way the parser interprets command-line
options that use a single dash followed by multiple letters, as as \c{-abc}.
\value ParseAsCompactedShortOptions \c{-abc} is interpreted as \c{-a -b -c},
i.e. as three short options that have been compacted on the command-line,
if none of the options take a value. If \c{a} takes a value, then it
is interpreted as \c{-a bc}, i.e. the short option \c{a} followed by the value \c{bc}.
This is typically used in tools that behave like compilers, in order
to handle options such as \c{-DDEFINE=VALUE} or \c{-I/include/path}.
This is the default parsing mode. New applications are recommended to
use this mode.
\value ParseAsLongOptions \c{-abc} is interpreted as \c{--abc},
i.e. as the long option named \c{abc}. This is how Qt's own tools
(uic, rcc...) have always been parsing arguments. This mode should be
used for preserving compatibility in applications that were parsing
arguments in such a way.
\sa setSingleDashWordOptionMode()
*/
/*!
Sets the parsing mode to \a singleDashWordOptionMode.
This must be called before process() or parse().
*/
void QCommandLineParser::setSingleDashWordOptionMode(QCommandLineParser::SingleDashWordOptionMode singleDashWordOptionMode)
{
d->singleDashWordOptionMode = singleDashWordOptionMode;
}
/*!
Adds the option \a option to look for while parsing.
Returns \c true if adding the option was successful; otherwise returns \c false.
Adding the option fails if there is no name attached to the option, or
the option has a name that clashes with an option name added before.
*/
bool QCommandLineParser::addOption(const QCommandLineOption &option)
{
QStringList optionNames = option.names();
if (!optionNames.isEmpty()) {
Q_FOREACH (const QString &name, optionNames) {
if (d->nameHash.contains(name))
return false;
}
d->commandLineOptionList.append(option);
const int offset = d->commandLineOptionList.size() - 1;
Q_FOREACH (const QString &name, optionNames)
d->nameHash.insert(name, offset);
return true;
}
return false;
}
/*!
Adds the \c{-v} / \c{--version} option, which displays the version string of the application.
This option is handled automatically by QCommandLineParser.
You can set the actual version string by using QCoreApplication::setApplicationVersion().
Returns the option instance, which can be used to call isSet().
*/
QCommandLineOption QCommandLineParser::addVersionOption()
{
QCommandLineOption opt(QStringList() << "v" << "version", tr("Displays version information."));
addOption(opt);
d->builtinVersionOption = true;
return opt;
}
/*!
Adds the help option (\c{-h}, \c{--help} and \c{-?} on Windows)
This option is handled automatically by QCommandLineParser.
Remember to use setApplicationDescription to set the application description,
which will be displayed when this option is used.
Example:
\snippet code/src_corelib_tools_qcommandlineparser_main.cpp 0
Returns the option instance, which can be used to call isSet().
*/
QCommandLineOption QCommandLineParser::addHelpOption()
{
QCommandLineOption opt(QStringList()
#ifdef Q_OS_WIN
<< "?"
#endif
<< "h"
<< "help", tr("Displays this help."));
addOption(opt);
d->builtinHelpOption = true;
return opt;
}
/*!
Sets the application \a description shown by helpText().
*/
void QCommandLineParser::setApplicationDescription(const QString &description)
{
d->description = description;
}
/*!
Returns the application description set in setApplicationDescription().
*/
QString QCommandLineParser::applicationDescription() const
{
return d->description;
}
/*!
Defines an additional argument to the application, for the benefit of the help text.
The argument \a name and \a description will appear under the \c{Arguments:} section
of the help. If \a syntax is specified, it will be appended to the Usage line, otherwise
the \a name will be appended.
Example:
\snippet code/src_corelib_tools_qcommandlineparser.cpp 2
\sa addHelpOption(), helpText()
*/
void QCommandLineParser::addPositionalArgument(const QString &name, const QString &description, const QString &syntax)
{
QCommandLineParserPrivate::PositionalArgumentDefinition arg;
arg.name = name;
arg.description = description;
arg.syntax = syntax.isEmpty() ? name : syntax;
d->positionalArgumentDefinitions.append(arg);
}
/*!
Clears the definitions of additional arguments from the help text.
This is only needed for the special case of tools which support multiple commands
with different options. Once the actual command has been identified, the options
for this command can be defined, and the help text for the command can be adjusted
accordingly.
Example:
\snippet code/src_corelib_tools_qcommandlineparser.cpp 3
*/
void QCommandLineParser::clearPositionalArguments()
{
d->positionalArgumentDefinitions.clear();
}
/*!
Parses the command line \a arguments.
Most programs don't need to call this, a simple call to process() is enough.
parse() is more low-level, and only does the parsing. The application will have to
take care of the error handling, using errorText() if parse() returns \c false.
This can be useful for instance to show a graphical error message in graphical programs.
Calling parse() instead of process() can also be useful in order to ignore unknown
options temporarily, because more option definitions will be provided later on
(depending on one of the arguments), before calling process().
Don't forget that \a arguments must start with the name of the executable (ignored, though).
Returns \c false in case of a parse error (unknown option or missing value); returns \c true otherwise.
\sa process()
*/
bool QCommandLineParser::parse(const QStringList &arguments)
{
return d->parse(arguments);
}
/*!
Returns a translated error text for the user.
This should only be called when parse() returns \c false.
*/
QString QCommandLineParser::errorText() const
{
if (!d->errorText.isEmpty())
return d->errorText;
if (d->unknownOptionNames.count() == 1)
return tr("Unknown option '%1'.").arg(d->unknownOptionNames.first());
if (d->unknownOptionNames.count() > 1)
return tr("Unknown options: %1.").arg(d->unknownOptionNames.join(", "));
return QString();
}
/*!
Processes the command line \a arguments.
In addition to parsing the options (like parse()), this function also handles the builtin
options and handles errors.
The builtin options are \c{--version} if addVersionOption was called and \c{--help} if addHelpOption was called.
When invoking one of these options, or when an error happens (for instance an unknown option was
passed), the current process will then stop, using the exit() function.
\sa QCoreApplication::arguments(), parse()
*/
void QCommandLineParser::process(const QStringList &arguments)
{
if (!d->parse(arguments)) {
fprintf(stderr, "%s\n", qPrintable(errorText()));
::exit(EXIT_FAILURE);
}
if (d->builtinVersionOption && isSet("version")) {
printf("%s %s\n", qPrintable(QCoreApplication::applicationName()), qPrintable(QCoreApplication::applicationVersion()));
::exit(EXIT_SUCCESS);
}
if (d->builtinHelpOption && isSet("help"))
showHelp(EXIT_SUCCESS);
}
/*!
\overload
The command line is obtained from the QCoreApplication instance \a app.
*/
void QCommandLineParser::process(const QCoreApplication &app)
{
// QCoreApplication::arguments() is static, but the app instance must exist so we require it as parameter
Q_UNUSED(app);
process(QCoreApplication::arguments());
}
void QCommandLineParserPrivate::checkParsed(const char *method)
{
if (needsParsing)
qWarning("QCommandLineParser: call process() or parse() before %s", method);
}
/*!
\internal
Looks up the option \a optionName (found on the command line) and register it as found.
Returns \c true on success.
*/
bool QCommandLineParserPrivate::registerFoundOption(const QString &optionName)
{
if (nameHash.contains(optionName)) {
optionNames.append(optionName);
return true;
} else {
unknownOptionNames.append(optionName);
return false;
}
}
/*!
\internal
\brief Parse the value for a given option, if it was defined to expect one.
The value is taken from the next argument, or after the equal sign in \a argument.
\param optionName the short option name
\param argument the argument from the command line currently parsed. Only used for -k=value parsing.
\param argumentIterator iterator to the currently parsed argument. Incremented if the next argument contains the value.
\param argsEnd args.end(), to check if ++argumentIterator goes out of bounds
Returns \c true on success.
*/
bool QCommandLineParserPrivate::parseOptionValue(const QString &optionName, const QString &argument,
QStringList::const_iterator *argumentIterator, QStringList::const_iterator argsEnd)
{
const QLatin1Char assignChar('=');
const NameHash_t::const_iterator nameHashIt = nameHash.constFind(optionName);
if (nameHashIt != nameHash.constEnd()) {
const int assignPos = argument.indexOf(assignChar);
const NameHash_t::mapped_type optionOffset = *nameHashIt;
const bool withValue = !commandLineOptionList.at(optionOffset).valueName().isEmpty();
if (withValue) {
if (assignPos == -1) {
++(*argumentIterator);
if (*argumentIterator == argsEnd) {
errorText = QCommandLineParser::tr("Missing value after '%1'.").arg(argument);
return false;
}
optionValuesHash[optionOffset].append(*(*argumentIterator));
} else {
optionValuesHash[optionOffset].append(argument.mid(assignPos + 1));
}
} else {
if (assignPos != -1) {
errorText = QCommandLineParser::tr("Unexpected value after '%1'.").arg(argument.left(assignPos));
return false;
}
}
}
return true;
}
/*!
\internal
Parse the list of arguments \a args, and fills in
optionNames, optionValuesHash, unknownOptionNames, positionalArguments, and errorText.
Any results from a previous parse operation are removed.
The parser will not look for further options once it encounters the option
\c{--}; this does not include when \c{--} follows an option that requires a value.
*/
bool QCommandLineParserPrivate::parse(const QStringList &args)
{
needsParsing = false;
bool error = false;
const QString doubleDashString("--");
const QLatin1Char dashChar('-');
const QLatin1Char assignChar('=');
bool doubleDashFound = false;
errorText.clear();
positionalArgumentList.clear();
optionNames.clear();
unknownOptionNames.clear();
optionValuesHash.clear();
if (args.isEmpty()) {
qWarning("QCommandLineParser: argument list cannot be empty, it should contain at least the executable name");
return false;
}
QStringList::const_iterator argumentIterator = args.begin();
++argumentIterator; // skip executable name
for (; argumentIterator != args.end() ; ++argumentIterator) {
QString argument = *argumentIterator;
if (doubleDashFound) {
positionalArgumentList.append(argument);
} else if (argument.startsWith(doubleDashString)) {
if (argument.length() > 2) {
QString optionName = argument.mid(2).section(assignChar, 0, 0);
if (registerFoundOption(optionName)) {
if (!parseOptionValue(optionName, argument, &argumentIterator, args.end()))
error = true;
} else {
error = true;
}
} else {
doubleDashFound = true;
}
} else if (argument.startsWith(dashChar)) {
if (argument.size() == 1) { // single dash ("stdin")
positionalArgumentList.append(argument);
continue;
}
switch (singleDashWordOptionMode) {
case QCommandLineParser::ParseAsCompactedShortOptions:
{
QString optionName;
bool valueFound = false;
for (int pos = 1 ; pos < argument.size(); ++pos) {
optionName = argument.mid(pos, 1);
if (!registerFoundOption(optionName)) {
error = true;
} else {
const NameHash_t::const_iterator nameHashIt = nameHash.constFind(optionName);
Q_ASSERT(nameHashIt != nameHash.constEnd()); // checked by registerFoundOption
const NameHash_t::mapped_type optionOffset = *nameHashIt;
const bool withValue = !commandLineOptionList.at(optionOffset).valueName().isEmpty();
if (withValue) {
if (pos + 1 < argument.size()) {
if (argument.at(pos + 1) == assignChar)
++pos;
optionValuesHash[optionOffset].append(argument.mid(pos + 1));
valueFound = true;
}
break;
}
if (pos + 1 < argument.size() && argument.at(pos + 1) == assignChar)
break;
}
}
if (!valueFound && !parseOptionValue(optionName, argument, &argumentIterator, args.end()))
error = true;
break;
}
case QCommandLineParser::ParseAsLongOptions:
{
const QString optionName = argument.mid(1).section(assignChar, 0, 0);
if (registerFoundOption(optionName)) {
if (!parseOptionValue(optionName, argument, &argumentIterator, args.end()))
error = true;
} else {
error = true;
}
break;
}
}
} else {
positionalArgumentList.append(argument);
}
if (argumentIterator == args.end())
break;
}
return !error;
}
/*!
Checks whether the option \a name was passed to the application.
Returns \c true if the option \a name was set, false otherwise.
The name provided can be any long or short name of any option that was
added with \c addOption(). All the options names are treated as being
equivalent. If the name is not recognized or that option was not present,
false is returned.
Example:
\snippet code/src_corelib_tools_qcommandlineparser.cpp 0
*/
bool QCommandLineParser::isSet(const QString &name) const
{
d->checkParsed("isSet");
if (d->optionNames.contains(name))
return true;
const QStringList aliases = d->aliases(name);
Q_FOREACH (const QString &optionName, d->optionNames) {
if (aliases.contains(optionName))
return true;
}
return false;
}
/*!
Returns the option value found for the given option name \a optionName, or
an empty string if not found.
The name provided can be any long or short name of any option that was
added with \c addOption(). All the option names are treated as being
equivalent. If the name is not recognized or that option was not present, an
empty string is returned.
For options found by the parser, the last value found for
that option is returned. If the option wasn't specified on the command line,
the default value is returned.
An empty string is returned if the option does not take a value.
\sa values(), QCommandLineOption::setDefaultValue(), QCommandLineOption::setDefaultValues()
*/
QString QCommandLineParser::value(const QString &optionName) const
{
d->checkParsed("value");
const QStringList valueList = values(optionName);
if (!valueList.isEmpty())
return valueList.last();
return QString();
}
/*!
Returns a list of option values found for the given option name \a
optionName, or an empty list if not found.
The name provided can be any long or short name of any option that was
added with \c addOption(). All the options names are treated as being
equivalent. If the name is not recognized or that option was not present, an
empty list is returned.
For options found by the parser, the list will contain an entry for
each time the option was encountered by the parser. If the option wasn't
specified on the command line, the default values are returned.
An empty list is returned if the option does not take a value.
\sa value(), QCommandLineOption::setDefaultValue(), QCommandLineOption::setDefaultValues()
*/
QStringList QCommandLineParser::values(const QString &optionName) const
{
d->checkParsed("values");
const NameHash_t::const_iterator it = d->nameHash.constFind(optionName);
if (it != d->nameHash.constEnd()) {
const int optionOffset = *it;
QStringList values = d->optionValuesHash.value(optionOffset);
if (values.isEmpty())
values = d->commandLineOptionList.at(optionOffset).defaultValues();
return values;
}
qWarning("QCommandLineParser: option not defined: \"%s\"", qPrintable(optionName));
return QStringList();
}
/*!
\overload
Checks whether the \a option was passed to the application.
Returns \c true if the \a option was set, false otherwise.
This is the recommended way to check for options with no values.
Example:
\snippet code/src_corelib_tools_qcommandlineparser.cpp 1
*/
bool QCommandLineParser::isSet(const QCommandLineOption &option) const
{
// option.names() might be empty if the constructor failed
return !option.names().isEmpty() && isSet(option.names().first());
}
/*!
\overload
Returns the option value found for the given \a option, or
an empty string if not found.
For options found by the parser, the last value found for
that option is returned. If the option wasn't specified on the command line,
the default value is returned.
An empty string is returned if the option does not take a value.
\sa values(), QCommandLineOption::setDefaultValue(), QCommandLineOption::setDefaultValues()
*/
QString QCommandLineParser::value(const QCommandLineOption &option) const
{
return value(option.names().first());
}
/*!
\overload
Returns a list of option values found for the given \a option,
or an empty list if not found.
For options found by the parser, the list will contain an entry for
each time the option was encountered by the parser. If the option wasn't
specified on the command line, the default values are returned.
An empty list is returned if the option does not take a value.
\sa value(), QCommandLineOption::setDefaultValue(), QCommandLineOption::setDefaultValues()
*/
QStringList QCommandLineParser::values(const QCommandLineOption &option) const
{
return values(option.names().first());
}
/*!
Returns a list of positional arguments.
These are all of the arguments that were not recognized as part of an
option.
*/
QStringList QCommandLineParser::positionalArguments() const
{
d->checkParsed("positionalArguments");
return d->positionalArgumentList;
}
/*!
Returns a list of option names that were found.
This returns a list of all the recognized option names found by the
parser, in the order in which they were found. For any long options
that were in the form {--option=value}, the value part will have been
dropped.
The names in this list do not include the preceding dash characters.
Names may appear more than once in this list if they were encountered
more than once by the parser.
Any entry in the list can be used with \c value() or with
\c values() to get any relevant option values.
*/
QStringList QCommandLineParser::optionNames() const
{
d->checkParsed("optionNames");
return d->optionNames;
}
/*!
Returns a list of unknown option names.
This list will include both long an short name options that were not
recognized. For any long options that were in the form {--option=value},
the value part will have been dropped and only the long name is added.
The names in this list do not include the preceding dash characters.
Names may appear more than once in this list if they were encountered
more than once by the parser.
\sa optionNames()
*/
QStringList QCommandLineParser::unknownOptionNames() const
{
d->checkParsed("unknownOptionNames");
return d->unknownOptionNames;
}
/*!
Displays the help information, and exits the application.
This is automatically triggered by the --help option, but can also
be used to display the help when the user is not invoking the
application correctly.
The exit code is set to \a exitCode. It should be set to 0 if the
user requested to see the help, and to any other value in case of
an error.
\sa helpText()
*/
void QCommandLineParser::showHelp(int exitCode)
{
fprintf(stdout, "%s", qPrintable(d->helpText()));
::exit(exitCode);
}
/*!
Returns a string containing the complete help information.
\sa showHelp()
*/
QString QCommandLineParser::helpText() const
{
return d->helpText();
}
static QString wrapText(const QString &names, int longestOptionNameString, const QString &description)
{
const QLatin1Char nl('\n');
QString text = QString(" ") + names.leftJustified(longestOptionNameString) + QLatin1Char(' ');
const int indent = text.length();
int lineStart = 0;
int lastBreakable = -1;
const int max = 79 - indent;
int x = 0;
const int len = description.length();
for (int i = 0; i < len; ++i) {
++x;
const QChar c = description.at(i);
if (c.isSpace())
lastBreakable = i;
int breakAt = -1;
int nextLineStart = -1;
if (x > max && lastBreakable != -1) {
// time to break and we know where
breakAt = lastBreakable;
nextLineStart = lastBreakable + 1;
} else if ((x > max - 1 && lastBreakable == -1) || i == len - 1) {
// time to break but found nowhere [-> break here], or end of last line
breakAt = i + 1;
nextLineStart = breakAt;
} else if (c == nl) {
// forced break
breakAt = i;
nextLineStart = i + 1;
}
if (breakAt != -1) {
const int numChars = breakAt - lineStart;
//qDebug() << "breakAt=" << description.at(breakAt) << "breakAtSpace=" << breakAtSpace << lineStart << "to" << breakAt << description.mid(lineStart, numChars);
if (lineStart > 0)
text += QString(indent, QLatin1Char(' '));
text += description.mid(lineStart, numChars) + nl;
x = 0;
lastBreakable = -1;
lineStart = nextLineStart;
if (lineStart < len && description.at(lineStart).isSpace())
++lineStart; // don't start a line with a space
i = lineStart;
}
}
return text;
}
QString QCommandLineParserPrivate::helpText() const
{
const QLatin1Char nl('\n');
QString text;
const QString exeName = QCoreApplication::instance()->arguments().first();
QString usage = exeName;
if (!commandLineOptionList.isEmpty()) {
usage += QLatin1Char(' ');
usage += QCommandLineParser::tr("[options]");
}
Q_FOREACH (const PositionalArgumentDefinition &arg, positionalArgumentDefinitions) {
usage += QLatin1Char(' ');
usage += arg.syntax;
}
text += QCommandLineParser::tr("Usage: %1").arg(usage) + nl;
if (!description.isEmpty())
text += description + nl;
text += nl;
if (!commandLineOptionList.isEmpty())
text += QCommandLineParser::tr("Options:") + nl;
QStringList optionNameList;
int longestOptionNameString = 0;
Q_FOREACH (const QCommandLineOption &option, commandLineOptionList) {
QStringList optionNames;
Q_FOREACH (const QString &optionName, option.names()) {
if (optionName.length() == 1)
optionNames.append(QLatin1Char('-') + optionName);
else
optionNames.append(QString("--") + optionName);
}
QString optionNamesString = optionNames.join(", ");
if (!option.valueName().isEmpty())
optionNamesString += QString(" <") + option.valueName() + QLatin1Char('>');
optionNameList.append(optionNamesString);
longestOptionNameString = qMax(longestOptionNameString, optionNamesString.length());
}
++longestOptionNameString;
for (int i = 0; i < commandLineOptionList.count(); ++i) {
const QCommandLineOption &option = commandLineOptionList.at(i);
text += wrapText(optionNameList.at(i), longestOptionNameString, option.description());
}
if (!positionalArgumentDefinitions.isEmpty()) {
if (!commandLineOptionList.isEmpty())
text += nl;
text += QCommandLineParser::tr("Arguments:") + nl;
Q_FOREACH (const PositionalArgumentDefinition &arg, positionalArgumentDefinitions) {
text += wrapText(arg.name, longestOptionNameString, arg.description);
}
}
return text;
}
#ifdef Q_CC_GNU
#pragma GCC diagnostic pop
#endif
#endif //QT_VERSION < QT_VERSION_CHECK(5, 2, 1)

View file

@ -1,117 +0,0 @@
/****************************************************************************
**
** Copyright (C) 2013 Laszlo Papp <lpapp@kde.org>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QCOMMANDLINEPARSER_H
#define QCOMMANDLINEPARSER_H
#include <QtGlobal>
#if QT_VERSION < QT_VERSION_CHECK(5, 2, 1)
#include <QStringList>
#include <QCoreApplication>
#include "qcommandlineoption.h"
#ifdef Q_CC_GNU
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
#endif
class QCommandLineParserPrivate;
class QCoreApplication;
class QCommandLineParser
{
Q_DECLARE_TR_FUNCTIONS(QCommandLineParser)
public:
QCommandLineParser();
~QCommandLineParser();
enum SingleDashWordOptionMode {
ParseAsCompactedShortOptions,
ParseAsLongOptions
};
void setSingleDashWordOptionMode(SingleDashWordOptionMode parsingMode);
bool addOption(const QCommandLineOption &commandLineOption);
QCommandLineOption addVersionOption();
QCommandLineOption addHelpOption();
void setApplicationDescription(const QString &description);
QString applicationDescription() const;
void addPositionalArgument(const QString &name, const QString &description, const QString &syntax = QString());
void clearPositionalArguments();
void process(const QStringList &arguments);
void process(const QCoreApplication &app);
bool parse(const QStringList &arguments);
QString errorText() const;
bool isSet(const QString &name) const;
QString value(const QString &name) const;
QStringList values(const QString &name) const;
bool isSet(const QCommandLineOption &option) const;
QString value(const QCommandLineOption &option) const;
QStringList values(const QCommandLineOption &option) const;
QStringList positionalArguments() const;
QStringList optionNames() const;
QStringList unknownOptionNames() const;
void showHelp(int exitCode = 0);
QString helpText() const;
private:
Q_DISABLE_COPY(QCommandLineParser)
QCommandLineParserPrivate * const d;
};
#ifdef Q_CC_GNU
#pragma GCC diagnostic pop
#endif
#endif //QT_VERSION < QT_VERSION_CHECK(5, 2, 1)
#endif // QCOMMANDLINEPARSER_H

View file

@ -35,6 +35,7 @@
#include "vmaingraphicsview.h"
#include "../container/calculator.h"
#include "../version.h"
#include "vsettings.h"
#include <QDebug>
#include <QDir>
@ -43,6 +44,96 @@
#include <QUndoStack>
#include <QtCore/qmath.h>
#include <QTemporaryFile>
#include <QFile>
#include <QStandardPaths>
#include <QMessageBox>
#include <QLoggingCategory>
Q_LOGGING_CATEGORY(vApp, "v.application")
//---------------------------------------------------------------------------------------------------------------------
inline void noisyFailureMsgHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
// Why on earth didn't Qt want to make failed signal/slot connections qWarning?
if ((type == QtDebugMsg) && msg.contains("::connect"))
{
type = QtWarningMsg;
}
// this is another one that doesn't make sense as just a debug message. pretty serious
// sign of a problem
// http://www.developer.nokia.com/Community/Wiki/QPainter::begin:Paint_device_returned_engine_%3D%3D_0_(Known_Issue)
if ((type == QtDebugMsg) && msg.contains("QPainter::begin") && msg.contains("Paint device returned engine"))
{
type = QtWarningMsg;
}
// This qWarning about "Cowardly refusing to send clipboard message to hung application..."
// is something that can easily happen if you are debugging and the application is paused.
// As it is so common, not worth popping up a dialog.
if ((type == QtWarningMsg) && QString(msg).contains("QClipboard::event")
&& QString(msg).contains("Cowardly refusing"))
{
type = QtDebugMsg;
}
// only the GUI thread should display message boxes. If you are
// writing a multithreaded application and the error happens on
// a non-GUI thread, you'll have to queue the message to the GUI
QCoreApplication *instance = QCoreApplication::instance();
const bool isGuiThread = instance && (QThread::currentThread() == instance->thread());
if (isGuiThread)
{
QString debugdate = QDateTime::currentDateTime().toString("yyyy.MM.dd hh:mm:ss");
QMessageBox messageBox;
switch (type)
{
case QtDebugMsg:
debugdate += QString(" [Debug] %1: \"%2\" %3").arg(context.category).arg(msg).arg(context.function);
break;
case QtWarningMsg:
debugdate += QString(" [Warning] %1: \"%2\" %3").arg(context.category).arg(msg).arg(context.function);
messageBox.setIcon(QMessageBox::Warning);
messageBox.setInformativeText(msg);
messageBox.setStandardButtons(QMessageBox::Ok);
messageBox.exec();
break;
case QtCriticalMsg:
debugdate += QString(" [Critical] %1: \"%2\" %3").arg(context.category).arg(msg).arg(context.function);
messageBox.setIcon(QMessageBox::Critical);
messageBox.setInformativeText(msg);
messageBox.setStandardButtons(QMessageBox::Ok);
messageBox.exec();
break;
case QtFatalMsg:
debugdate += QString(" [Fatal] %1: \"%2\" %3").arg(context.category).arg(msg).arg(context.function);
messageBox.setIcon(QMessageBox::Critical);
messageBox.setInformativeText(msg);
messageBox.setStandardButtons(QMessageBox::Ok);
messageBox.exec();
break;
default:
break;
}
(*qApp->LogFile()) << debugdate << endl;
if (QtFatalMsg == type)
{
abort();
}
}
else
{
if (type != QtDebugMsg)
{
abort(); // be NOISY unless overridden!
}
}
}
//---------------------------------------------------------------------------------------------------------------------
const qreal VApplication::PrintDPI = 96.0;
@ -64,8 +155,8 @@ VApplication::VApplication(int &argc, char **argv)
guiTexts(QMap<QString, VTranslation>()), descriptions(QMap<QString, VTranslation>()),
variables(QMap<QString, VTranslation>()), functions(QMap<QString, VTranslation>()),
postfixOperators(QMap<QString, VTranslation>()), stDescriptions(QMap<QString, VTranslation>()),
undoStack(nullptr), sceneView(nullptr), currentScene(nullptr),
autoSaveTimer(nullptr), mainWindow(nullptr), openingPattern(false), settings(nullptr), doc(nullptr)
undoStack(nullptr), sceneView(nullptr), currentScene(nullptr), autoSaveTimer(nullptr), mainWindow(nullptr),
openingPattern(false), settings(nullptr), doc(nullptr), log(nullptr), out(nullptr)
{
undoStack = new QUndoStack(this);
@ -77,6 +168,20 @@ VApplication::VApplication(int &argc, char **argv)
InitSTDescriptions();
}
//---------------------------------------------------------------------------------------------------------------------
VApplication::~VApplication()
{
qCDebug(vApp)<<"Application closing.";
qInstallMessageHandler(0); // Resore the message handler
delete out;
if (log != nullptr)
{
log->close();
delete log;
}
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief NewValentina start Valentina in new process, send path to pattern file in argument.
@ -84,18 +189,36 @@ VApplication::VApplication(int &argc, char **argv)
*/
void VApplication::NewValentina(const QString &fileName)
{
QProcess *v = new QProcess();
QStringList arguments;
arguments << fileName;
qCDebug(vApp)<<"Open new detached process.";
if (fileName.isEmpty())
{
v->startDetached(QCoreApplication::applicationFilePath());
qCDebug(vApp)<<"New process without arguments. program ="<<QCoreApplication::applicationFilePath();
// Path can contain spaces.
if (QProcess::startDetached("\""+QCoreApplication::applicationFilePath()+"\""))
{
qCDebug(vApp)<<"The process was started successfully.";
}
else
{
qCWarning(vApp)<<"The operation timed out or an error occurred.";
}
}
else
{
v->startDetached(QCoreApplication::applicationFilePath(), arguments);
QStringList arguments;
arguments << fileName;
qCDebug(vApp)<<"New process with arguments. program ="<<QCoreApplication::applicationFilePath()
<<", arguments = "<<arguments;
// Path can contain spaces.
if(QProcess::startDetached("\""+QCoreApplication::applicationFilePath()+"\"", arguments))
{
qCDebug(vApp)<<"The process was started successfully.";
}
else
{
qCWarning(vApp)<<"The operation timed out or an error occurred.";
}
}
delete v;
}
//---------------------------------------------------------------------------------------------------------------------
@ -295,6 +418,25 @@ void VApplication::InitMeasurement(const QString &name, const VTranslation &m, c
descriptions.insert(name, d);
}
//---------------------------------------------------------------------------------------------------------------------
QString VApplication::LogDirPath() const
{
#if defined(Q_OS_WIN) || defined(Q_OS_OSX)
const QString logDirPath = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QString(),
QStandardPaths::LocateDirectory) + "Valentina";
#else
const QString logDirPath = QStandardPaths::locate(QStandardPaths::ConfigLocation, QString(),
QStandardPaths::LocateDirectory) + organizationName();
#endif
return logDirPath;
}
//---------------------------------------------------------------------------------------------------------------------
QString VApplication::LogPath() const
{
return LogDirPath() + "/valentina.log";
}
//---------------------------------------------------------------------------------------------------------------------
void VApplication::InitMeasurements()
{
@ -1523,10 +1665,8 @@ QString VApplication::FormulaFromUser(const QString &formula)
}
}
bool osSeparatorValue = getSettings()->value("configuration/osSeparator", 1).toBool();
QLocale loc = QLocale::system();
if (loc != QLocale(QLocale::C) && osSeparatorValue)
if (loc != QLocale(QLocale::C) && getSettings()->GetOsSeparator())
{
QList<int> nKeys = numbers.keys();
QList<QString> nValues = numbers.values();
@ -1639,10 +1779,8 @@ QString VApplication::FormulaToUser(const QString &formula)
}
}
bool osSeparatorValue = getSettings()->value("configuration/osSeparator", 1).toBool();
QLocale loc = QLocale::system();
if (loc != QLocale::C && osSeparatorValue)
if (loc != QLocale::C && getSettings()->GetOsSeparator())
{
QList<int> nKeys = numbers.keys();
QList<QString> nValues = numbers.values();
@ -1709,7 +1847,7 @@ void VApplication::setOpeningPattern()
*/
void VApplication::OpenSettings()
{
settings = new QSettings(QSettings::IniFormat, QSettings::UserScope, QApplication::organizationName(),
settings = new VSettings(QSettings::IniFormat, QSettings::UserScope, QApplication::organizationName(),
QApplication::applicationName(), this);
}
@ -1718,7 +1856,7 @@ void VApplication::OpenSettings()
* @brief VApplication::getSettings hide settings constructor.
* @return pointer to class for acssesing to settings in ini file.
*/
QSettings *VApplication::getSettings()
VSettings *VApplication::getSettings()
{
SCASSERT(settings != nullptr);
return settings;
@ -1802,7 +1940,7 @@ QString VApplication::STDescription(const QString &id) const
}
else
{
qWarning()<<"Unknown id number. Got"<<id;
qDebug()<<"Unknown id number. Got"<<id;
}
return QString();
}
@ -1854,6 +1992,43 @@ bool VApplication::SafeCopy(const QString &source, const QString &destination, Q
return result;
}
//---------------------------------------------------------------------------------------------------------------------
void VApplication::StartLogging()
{
#if (QT_VERSION < QT_VERSION_CHECK(5, 3, 0))
// In Qt 5.2 need manualy enable debug information for categories. This work
// because Qt doesn't provide debug information for categories itself. And in this
// case will show our messages. Another situation with Qt 5.3 that has many debug
// messages itself. We don't need this information and can turn on later if need.
// But here Qt already show our debug messages without enabling.
QLoggingCategory::setFilterRules("*.debug=true\n");
#endif
QDir logDir(LogDirPath());
if (logDir.exists() == false)
{
logDir.mkpath("."); // Create directory for log if need
}
log = new QFile(LogPath());
if (log->open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text))
{
out = new QTextStream(log);
qInstallMessageHandler(noisyFailureMsgHandler);
}
else
{
delete log;
qDebug() << "Error opening log file '" << LogPath() << "'. All debug output redirected to console.";
}
}
//---------------------------------------------------------------------------------------------------------------------
QTextStream *VApplication::LogFile()
{
return out;
}
#if defined(Q_OS_WIN) && defined(Q_CC_GNU)
//---------------------------------------------------------------------------------------------------------------------
// Catch exception and create report. Use if program build with Mingw compiler.
@ -1881,7 +2056,7 @@ void VApplication::CollectReports() const
return;// Settings was not opened.
}
if (settings->value("configuration/send_report/state", 1).toBool())
if (settings->GetSendReportState())
{ // Try send report
// Remove gist.json file before close app.
connect(this, &VApplication::aboutToQuit, this, &VApplication::CleanGist, Qt::UniqueConnection);
@ -1905,12 +2080,16 @@ void VApplication::CollectReport(const QString &reportName) const
}
const QDateTime now = QDateTime::currentDateTime();
const QString timestamp = now.toString(QLatin1String("yyyyMMdd-hhmmsszzz"));
const QString filename = QString("%1/reports/crash-%2.RPT").arg(qApp->applicationDirPath()).arg(timestamp);
const QString timestamp = now.toString(QLatin1String("yyyy.MM.dd-hh_mm_ss"));
QString filename = QString("%1/reports/crash-%2.RPT").arg(qApp->applicationDirPath()).arg(timestamp);
QFile reportFile(reportName);
reportFile.copy(filename); // Collect new crash
reportFile.remove(); // Clear after yourself
filename = QString("%1/reports/log-%2.log").arg(qApp->applicationDirPath()).arg(timestamp);
QFile logFile(LogPath());
logFile.copy(filename); // Collect log
}
//---------------------------------------------------------------------------------------------------------------------
@ -1928,23 +2107,22 @@ void VApplication::SendReport(const QString &reportName) const
{
QString content;
QFile reportFile(reportName);
if (!reportFile.open(QIODevice::ReadOnly | QIODevice::Text))
if (reportFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
return;
content = ReadFileForSending(reportFile);
reportFile.close();
}
QTextStream in(&reportFile);
while (!in.atEnd())
else
{
content.append(in.readLine()+"\r\n");// Windows end of line
content = "RPT file error:" + reportFile.errorString() + "\r\n";
}
reportFile.close();
// Additional information
content.append(QString("-------------------------------")+"\r\n");
content.append(QString("Version:%1").arg(APP_VERSION)+"\r\n");
content.append(QString("Based on Qt %2 (32 bit)").arg(QT_VERSION_STR)+"\r\n");
content.append(QString("Built on %3 at %4").arg(__DATE__).arg(__TIME__)+"\r\n");
content.append("\r\n");
// Creating json with report
// Example:
@ -1952,7 +2130,7 @@ void VApplication::SendReport(const QString &reportName) const
// "description":"Crash report",
// "public":"true",
// "files":{
// "file1.txt":{
// "valentina.RPT":{
// "content":"Report text here"
// }
// }
@ -1967,12 +2145,28 @@ void VApplication::SendReport(const QString &reportName) const
reportObject.insert(QStringLiteral("description"), QJsonValue(report));
reportObject.insert(QStringLiteral("public"), QJsonValue(QString("true")));
QJsonObject contentObject;
contentObject.insert(QStringLiteral("content"), QJsonValue(content));
content.append(QString("\r\n-------------------------------\r\n"));
content.append(QString("Log:")+"\r\n");
QFile logFile(LogPath());
if (logFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
content.append(ReadFileForSending(logFile));
logFile.close();
}
else
{
content.append("\r\n Log file error:" + logFile.errorString() + "\r\n");
}
const QString contentSection = QStringLiteral("content");
QJsonObject contentObject;
contentObject.insert(contentSection, QJsonValue(content));
const QString filesSection = QStringLiteral("files");
QJsonObject fileObject;
fileObject.insert(QFileInfo(reportName).fileName(), QJsonValue(contentObject));
reportObject.insert(QStringLiteral("files"), QJsonValue(fileObject));
reportObject.insert(filesSection, QJsonValue(fileObject));
QFile gistFile(GistFileName);
if (!gistFile.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text))
@ -2001,4 +2195,16 @@ void VApplication::SendReport(const QString &reportName) const
CollectReport(reportName);
}
}
//---------------------------------------------------------------------------------------------------------------------
QString VApplication::ReadFileForSending(QFile &file) const
{
QString content;
QTextStream in(&file);
while (!in.atEnd())
{
content.append(in.readLine()+"\r\n");// Windows end of line
}
return content;
}
#endif //defined(Q_OS_WIN) && defined(Q_CC_GNU)

View file

@ -32,7 +32,6 @@
#include <QApplication>
#include "../options.h"
#include "vtranslation.h"
#include <QSettings>
#include "../widgets/vmaingraphicsview.h"
class VApplication;// used in define
@ -40,6 +39,8 @@ class QUndoStack;
class VMainGraphicsView;
class VMainGraphicsScene;
class VPattern;
class QFile;
class VSettings;
#if defined(qApp)
#undef qApp
@ -54,7 +55,7 @@ class VApplication : public QApplication
Q_OBJECT
public:
VApplication(int &argc, char ** argv);
virtual ~VApplication() {}
virtual ~VApplication();
static void NewValentina(const QString &fileName = QString());
static void CheckFactor(qreal &oldFactor, const qreal &Newfactor);
virtual bool notify(QObject * receiver, QEvent * event);
@ -89,8 +90,10 @@ public:
void setMainWindow(QWidget *value);
bool getOpeningPattern() const;
void setOpeningPattern();
void OpenSettings();
QSettings *getSettings();
VSettings *getSettings();
VMainGraphicsScene *getCurrentScene() const;
void setCurrentScene(VMainGraphicsScene *value);
@ -103,13 +106,19 @@ public:
static QStringList LabelLanguages();
QString STDescription(const QString &id)const;
static bool SafeCopy(const QString &source, const QString &destination, QString &error);
void StartLogging();
QTextStream *LogFile();
#if defined(Q_OS_WIN) && defined(Q_CC_GNU)
static void DrMingw();
void CollectReports() const;
#endif // defined(Q_OS_WIN) && defined(Q_CC_GNU)
private slots:
#if defined(Q_OS_WIN) && defined(Q_CC_GNU)
void CleanGist() const;
#endif // defined(Q_OS_WIN) && defined(Q_CC_GNU)
private:
Q_DISABLE_COPY(VApplication)
Unit _patternUnit;
@ -140,9 +149,11 @@ private:
/**
* @brief settings pointer to settings. Help hide constructor creation settings. Make make code more readable.
*/
QSettings *settings;
VSettings *settings;
VPattern *doc;
QFile *log;
QTextStream *out;
void InitLineWidth();
void InitMeasurements();
void InitVariables();
@ -166,7 +177,11 @@ private:
void CollectReport(const QString &reportName) const;
void SendReport(const QString &reportName) const;
QString ReadFileForSending(QFile &file)const;
#endif // defined(Q_OS_WIN) && defined(Q_CC_GNU)
QString LogDirPath()const;
QString LogPath()const;
};
//---------------------------------------------------------------------------------------------------------------------

402
src/app/core/vsettings.cpp Normal file
View file

@ -0,0 +1,402 @@
/************************************************************************
**
** @file vsettings.cpp
** @author Roman Telezhynskyi <dismine(at)gmail.com>
** @date 22 11, 2014
**
** @brief
** @copyright
** This source code is part of the Valentine project, a pattern making
** program, whose allow create and modeling patterns of clothing.
** Copyright (C) 2014 Valentina project
** <https://bitbucket.org/dismine/valentina> All Rights Reserved.
**
** Valentina is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** Valentina is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Valentina. If not, see <http://www.gnu.org/licenses/>.
**
*************************************************************************/
#include "vsettings.h"
#include <QDir>
const QString VSettings::SettingConfigurationOsSeparator = QStringLiteral("configuration/osSeparator");
const QString VSettings::SettingConfigurationAutosaveState = QStringLiteral("configuration/autosave/state");
const QString VSettings::SettingConfigurationAutosaveTime = QStringLiteral("configuration/autosave/time");
const QString VSettings::SettingConfigurationSendReportState = QStringLiteral("configuration/send_report/state");
const QString VSettings::SettingConfigurationLocale = QStringLiteral("configuration/locale");
const QString VSettings::SettingConfigurationUnit = QStringLiteral("configuration/unit");
const QString VSettings::SettingConfigurationLabelLanguage = QStringLiteral("configuration/label_language");
const QString VSettings::SettingPathsIndividualMeasurements = QStringLiteral("paths/individual_measurements");
const QString VSettings::SettingPathsPattern = QStringLiteral("paths/pattern");
const QString VSettings::SettingPatternUser = QStringLiteral("pattern/user");
const QString VSettings::SettingPatternGraphicalOutput = QStringLiteral("pattern/graphicalOutput");
const QString VSettings::SettingPatternUndo = QStringLiteral("pattern/undo");
const QString VSettings::SettingGeneralRecentFileList = QStringLiteral("recentFileList");
const QString VSettings::SettingGeneralRestoreFileList = QStringLiteral("restoreFileList");
const QString VSettings::SettingGeneralGeometry = QStringLiteral("geometry");
const QString VSettings::SettingGeneralWindowState = QStringLiteral("windowState");
const QString VSettings::SettingCommunityServer = QStringLiteral("community/server");
const QString VSettings::SettingCommunityServerSecure = QStringLiteral("community/serverSecure");
const QString VSettings::SettingCommunityUseProxy = QStringLiteral("community/useProxy");
const QString VSettings::SettingCommunityProxyAddress = QStringLiteral("community/proxyAddress");
const QString VSettings::SettingCommunityProxyPort = QStringLiteral("community/proxyPort");
const QString VSettings::SettingCommunityProxyUser = QStringLiteral("community/proxyUser");
const QString VSettings::SettingCommunityProxyPass = QStringLiteral("community/proxyPass");
const QString VSettings::SettingCommunityUsername = QStringLiteral("community/username");
const QString VSettings::SettingCommunitySavePassword = QStringLiteral("community/savePassword");
const QString VSettings::SettingCommunityUserPassword = QStringLiteral("community/userpassword");
//---------------------------------------------------------------------------------------------------------------------
VSettings::VSettings(Format format, Scope scope, const QString &organization, const QString &application,
QObject *parent)
:QSettings(format, scope, organization, application, parent)
{}
//---------------------------------------------------------------------------------------------------------------------
bool VSettings::GetOsSeparator()
{
return value(SettingConfigurationOsSeparator, 1).toBool();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetOsSeparator(const bool &value)
{
setValue(SettingConfigurationOsSeparator, value);
}
//---------------------------------------------------------------------------------------------------------------------
bool VSettings::GetAutosaveState()
{
return value(SettingConfigurationAutosaveState, 1).toBool();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetAutosaveState(const bool &value)
{
setValue(SettingConfigurationAutosaveState, value);
}
//---------------------------------------------------------------------------------------------------------------------
int VSettings::GetAutosaveTime()
{
bool ok = false;
int val = value(SettingConfigurationAutosaveTime, 1).toInt(&ok);
if (ok == false)
{
qDebug()<<"Could not convert value"<<value(SettingConfigurationAutosaveTime, 1)
<<"to int. Return default value for autosave time"<<1<<"minutes.";
val = 1;
}
return val;
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetAutosaveTime(const int &value)
{
setValue(SettingConfigurationAutosaveTime, value);
}
//---------------------------------------------------------------------------------------------------------------------
bool VSettings::GetSendReportState()
{
return value(SettingConfigurationSendReportState, 1).toBool();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetSendReportState(const bool &value)
{
setValue(SettingConfigurationSendReportState, value);
}
//---------------------------------------------------------------------------------------------------------------------
QString VSettings::GetLocale()
{
return value(SettingConfigurationLocale, QLocale::system().name()).toString();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetLocale(const QString &value)
{
setValue(SettingConfigurationLocale, value);
}
//---------------------------------------------------------------------------------------------------------------------
QString VSettings::GetUnit()
{
return value(SettingConfigurationUnit, "cm").toString();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetUnit(const QString &value)
{
setValue(SettingConfigurationUnit, value);
}
//---------------------------------------------------------------------------------------------------------------------
QString VSettings::GetLabelLanguage()
{
return value(SettingConfigurationLabelLanguage, QLocale::system().bcp47Name()).toString();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetLabelLanguage(const QString &value)
{
setValue(SettingConfigurationLabelLanguage, value);
}
//---------------------------------------------------------------------------------------------------------------------
QString VSettings::GetPathIndividualMeasurements()
{
return value(SettingPathsIndividualMeasurements, QDir::homePath()).toString();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetPathIndividualMeasurements(const QString &value)
{
setValue(SettingPathsIndividualMeasurements, value);
}
//---------------------------------------------------------------------------------------------------------------------
QString VSettings::GetPathPattern()
{
return value(SettingPathsPattern, QDir::homePath()).toString();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetPathPattern(const QString &value)
{
setValue(SettingPathsPattern, value);
}
//---------------------------------------------------------------------------------------------------------------------
QString VSettings::GetUser()
{
QString user;
#ifdef Q_OS_WIN
user = value(SettingPatternUser, QString::fromLocal8Bit(qgetenv("USERNAME").constData())).toString();
#else
user = value(SettingPatternUser, QString::fromLocal8Bit(qgetenv("USER").constData())).toString();
#endif
return user;
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetUser(const QString &value)
{
setValue(SettingPatternUser, value);
}
//---------------------------------------------------------------------------------------------------------------------
bool VSettings::GetGraphicalOutput()
{
return value(SettingPatternGraphicalOutput, 1).toBool();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetGraphicalOutput(const bool &value)
{
setValue(SettingPatternGraphicalOutput, value);
}
//---------------------------------------------------------------------------------------------------------------------
int VSettings::GetUndoCount()
{
bool ok = false;
int val = value(SettingPatternUndo, 0).toInt(&ok);
if (ok == false)
{
qDebug()<<"Could not convert value"<<value(SettingPatternUndo, 0)
<<"to int. Return default value for undo counts 0 (no limit).";
val = 0;
}
return val;
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetUndoCount(const int &value)
{
setValue(SettingPatternUndo, value);
}
//---------------------------------------------------------------------------------------------------------------------
QStringList VSettings::GetRecentFileList()
{
return value(SettingGeneralRecentFileList).toStringList();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetRecentFileList(const QStringList &value)
{
setValue(SettingGeneralRecentFileList, value);
}
//---------------------------------------------------------------------------------------------------------------------
QStringList VSettings::GetRestoreFileList()
{
return value(SettingGeneralRestoreFileList).toStringList();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetRestoreFileList(const QStringList &value)
{
setValue(SettingGeneralRestoreFileList, value);
}
//---------------------------------------------------------------------------------------------------------------------
QByteArray VSettings::GetGeometry()
{
return value(SettingGeneralGeometry).toByteArray();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetGeometry(const QByteArray &value)
{
setValue(SettingGeneralGeometry, value);
}
//---------------------------------------------------------------------------------------------------------------------
QByteArray VSettings::GetWindowState()
{
return value(SettingGeneralWindowState).toByteArray();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetWindowState(const QByteArray &value)
{
setValue(SettingGeneralWindowState, value);
}
//---------------------------------------------------------------------------------------------------------------------
QString VSettings::GetServer()
{
return value(SettingCommunityServer, "community.valentina-project.org").toString();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetServer(const QString &value)
{
setValue(SettingCommunityServer, value);
}
//---------------------------------------------------------------------------------------------------------------------
bool VSettings::GetServerSecure()
{
return value(SettingCommunityServerSecure, 0).toBool();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetServerSecure(const bool &value)
{
setValue(SettingCommunityServerSecure, value);
}
//---------------------------------------------------------------------------------------------------------------------
bool VSettings::GetProxy()
{
return value(SettingCommunityUseProxy, 0).toBool();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetProxy(const bool &value)
{
setValue(SettingCommunityUseProxy, value);
}
//---------------------------------------------------------------------------------------------------------------------
QString VSettings::GetProxyAddress()
{
return value(SettingCommunityProxyAddress).toString();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetProxyAddress(const QString &value)
{
setValue(SettingCommunityProxyAddress, value);
}
//---------------------------------------------------------------------------------------------------------------------
QString VSettings::GetProxyPort()
{
return value(SettingCommunityProxyPort).toString();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetProxyPort(const QString &value)
{
setValue(SettingCommunityProxyPort, value);
}
//---------------------------------------------------------------------------------------------------------------------
QString VSettings::GetProxyUser()
{
return value(SettingCommunityProxyUser).toString();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetProxyUser(const QString &value)
{
setValue(SettingCommunityProxyUser, value);
}
//---------------------------------------------------------------------------------------------------------------------
QString VSettings::GetProxyPass()
{
return value(SettingCommunityProxyPass).toString();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetProxyPass(const QString &value)
{
setValue(SettingCommunityProxyPass, value);
}
//---------------------------------------------------------------------------------------------------------------------
QString VSettings::GetUsername()
{
return value(SettingCommunityUsername).toString();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetUsername(const QString &value)
{
setValue(SettingCommunityUsername, value);
}
//---------------------------------------------------------------------------------------------------------------------
bool VSettings::GetSavePassword()
{
return value(SettingCommunitySavePassword, 0).toBool();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetSavePassword(const bool &value)
{
setValue(SettingCommunitySavePassword, value);
}
//---------------------------------------------------------------------------------------------------------------------
QString VSettings::GetUserPassword()
{
return value(SettingCommunityUserPassword).toString();
}
//---------------------------------------------------------------------------------------------------------------------
void VSettings::SetUserPassword(const QString &value)
{
setValue(SettingCommunityUserPassword, value);
}

153
src/app/core/vsettings.h Normal file
View file

@ -0,0 +1,153 @@
/************************************************************************
**
** @file vsettings.h
** @author Roman Telezhynskyi <dismine(at)gmail.com>
** @date 22 11, 2014
**
** @brief
** @copyright
** This source code is part of the Valentine project, a pattern making
** program, whose allow create and modeling patterns of clothing.
** Copyright (C) 2014 Valentina project
** <https://bitbucket.org/dismine/valentina> All Rights Reserved.
**
** Valentina is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** Valentina is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Valentina. If not, see <http://www.gnu.org/licenses/>.
**
*************************************************************************/
#ifndef VSETTINGS_H
#define VSETTINGS_H
#include <QSettings>
class VSettings : public QSettings
{
Q_OBJECT
public:
VSettings(Format format, Scope scope, const QString &organization, const QString &application = QString(),
QObject *parent = 0);
bool GetOsSeparator();
void SetOsSeparator(const bool &value);
bool GetAutosaveState();
void SetAutosaveState(const bool &value);
int GetAutosaveTime();
void SetAutosaveTime(const int &value);
bool GetSendReportState();
void SetSendReportState(const bool &value);
QString GetLocale();
void SetLocale(const QString &value);
QString GetUnit();
void SetUnit(const QString &value);
QString GetLabelLanguage();
void SetLabelLanguage(const QString &value);
QString GetPathIndividualMeasurements();
void SetPathIndividualMeasurements(const QString &value);
QString GetPathPattern();
void SetPathPattern(const QString &value);
QString GetUser();
void SetUser(const QString &value);
bool GetGraphicalOutput();
void SetGraphicalOutput(const bool &value);
int GetUndoCount();
void SetUndoCount(const int &value);
QStringList GetRecentFileList();
void SetRecentFileList(const QStringList &value);
QStringList GetRestoreFileList();
void SetRestoreFileList(const QStringList &value);
QByteArray GetGeometry();
void SetGeometry(const QByteArray &value);
QByteArray GetWindowState();
void SetWindowState(const QByteArray &value);
QString GetServer();
void SetServer(const QString &value);
bool GetServerSecure();
void SetServerSecure(const bool &value);
bool GetProxy();
void SetProxy(const bool &value);
QString GetProxyAddress();
void SetProxyAddress(const QString &value);
QString GetProxyPort();
void SetProxyPort(const QString &value);
QString GetProxyUser();
void SetProxyUser(const QString &value);
QString GetProxyPass();
void SetProxyPass(const QString &value);
QString GetUsername();
void SetUsername(const QString &value);
bool GetSavePassword();
void SetSavePassword(const bool &value);
QString GetUserPassword();
void SetUserPassword(const QString &value);
private:
Q_DISABLE_COPY(VSettings)
static const QString SettingConfigurationOsSeparator;
static const QString SettingConfigurationAutosaveState;
static const QString SettingConfigurationAutosaveTime;
static const QString SettingConfigurationSendReportState;
static const QString SettingConfigurationLocale;
static const QString SettingConfigurationUnit;
static const QString SettingConfigurationLabelLanguage;
static const QString SettingPathsIndividualMeasurements;
static const QString SettingPathsPattern;
static const QString SettingPatternUser;
static const QString SettingPatternGraphicalOutput;
static const QString SettingPatternUndo;
static const QString SettingGeneralRecentFileList;
static const QString SettingGeneralRestoreFileList;
static const QString SettingGeneralGeometry;
static const QString SettingGeneralWindowState;
static const QString SettingCommunityServer;
static const QString SettingCommunityServerSecure;
static const QString SettingCommunityUseProxy;
static const QString SettingCommunityProxyAddress;
static const QString SettingCommunityProxyPort;
static const QString SettingCommunityProxyUser;
static const QString SettingCommunityProxyPass;
static const QString SettingCommunityUsername;
static const QString SettingCommunitySavePassword;
static const QString SettingCommunityUserPassword;
};
#endif // VSETTINGS_H

View file

@ -38,7 +38,7 @@
* I took idea from this article http://ololoepepe.blogspot.com/2013/08/qt.html.
* As you know, if wrap string to a function translate, it will be marked for translation. No matter what namespace
* contains this function. In class Translation used this circumstance.
* It is mean never change name of method translate!!!!!.
* This mean never change name of method translate!!!!!.
* Instead of using QT_TRANSLATE_NOOP3 macros we can store strings in QMap.
* Example:
* create map and fill up its

View file

@ -29,6 +29,7 @@
#include "communitypage.h"
#include "../../../options.h"
#include "../../../core/vapplication.h"
#include "../../../core/vsettings.h"
#include <QGroupBox>
#include <QLabel>
#include <QSettings>
@ -57,17 +58,17 @@ CommunityPage::CommunityPage(QWidget *parent):
//---------------------------------------------------------------------------------------------------------------------
void CommunityPage::Apply()
{
qApp->getSettings()->setValue("community/server", this->server->text());
qApp->getSettings()->setValue("community/serverSecure", this->secureComm->isChecked());
qApp->getSettings()->setValue("community/useProxy", this->useProxy->isChecked());
qApp->getSettings()->setValue("community/proxyAddress", this->proxyAddress->text());
qApp->getSettings()->setValue("community/proxyPort", this->proxyPort->text());
qApp->getSettings()->setValue("community/proxyUser", this->proxyUser->text());
qApp->getSettings()->setValue("community/proxyPass", this->proxyPass->text());
qApp->getSettings()->SetServer(this->server->text());
qApp->getSettings()->SetServerSecure(this->secureComm->isChecked());
qApp->getSettings()->SetProxy(this->useProxy->isChecked());
qApp->getSettings()->SetProxyAddress(this->proxyAddress->text());
qApp->getSettings()->SetProxyPort(this->proxyPort->text());
qApp->getSettings()->SetProxyUser(this->proxyUser->text());
qApp->getSettings()->SetProxyPass(this->proxyPass->text());
qApp->getSettings()->setValue("community/username", this->username->text());
qApp->getSettings()->setValue("community/savePassword", this->savePassword->isChecked());
qApp->getSettings()->setValue("community/userpassword", this->userpassword->text());
qApp->getSettings()->SetUsername(this->username->text());
qApp->getSettings()->SetSavePassword(this->savePassword->isChecked());
qApp->getSettings()->SetUserPassword(this->userpassword->text());
}
@ -99,17 +100,13 @@ void CommunityPage::PasswordCheckChanged()
//---------------------------------------------------------------------------------------------------------------------
QGroupBox *CommunityPage::ServerGroup()
{
QSettings *settings = qApp->getSettings();
SCASSERT(settings != nullptr);
QGroupBox *ServerGroup = new QGroupBox(tr("Server"));
QFormLayout *serverLayout = new QFormLayout;
CommunityPage::add_lineedit(&this->server, serverLayout,
settings->value("community/server", "community.valentina-project.org").toString(), tr("Server name/IP"));
CommunityPage::add_lineedit(&this->server, serverLayout, qApp->getSettings()->GetServer(), tr("Server name/IP"));
CommunityPage::add_checkbox(&this->secureComm, serverLayout,
settings->value("community/serverSecure", 0).toBool(), tr("Secure connection"));
CommunityPage::add_checkbox(&this->secureComm, serverLayout, qApp->getSettings()->GetServerSecure(),
tr("Secure connection"));
ServerGroup->setLayout(serverLayout);
return ServerGroup;
@ -140,21 +137,12 @@ QGroupBox *CommunityPage::ProxyGroup()
QFormLayout *proxyLayout = new QFormLayout;
CommunityPage::add_checkbox(&this->useProxy, proxyLayout,
qApp->getSettings()->value("community/useProxy", 0).toBool(), tr("Use Proxy"));
CommunityPage::add_lineedit(&this->proxyAddress, proxyLayout,
qApp->getSettings()->value("community/proxyAddress", "").toString(), tr("Proxy address"));
CommunityPage::add_lineedit(&this->proxyPort, proxyLayout,
qApp->getSettings()->value("community/proxyPort", "").toString(), tr("Proxy port"));
CommunityPage::add_lineedit(&this->proxyUser, proxyLayout,
qApp->getSettings()->value("community/proxyUser", "").toString(), tr("Proxy user"));
CommunityPage::add_lineedit(&this->proxyPass, proxyLayout,
qApp->getSettings()->value("community/proxyPass", "").toString(), tr("Proxy pass"));
CommunityPage::add_checkbox(&this->useProxy, proxyLayout, qApp->getSettings()->GetProxy(), tr("Use Proxy"));
CommunityPage::add_lineedit(&this->proxyAddress, proxyLayout, qApp->getSettings()->GetProxyAddress(),
tr("Proxy address"));
CommunityPage::add_lineedit(&this->proxyPort, proxyLayout, qApp->getSettings()->GetProxyPort(), tr("Proxy port"));
CommunityPage::add_lineedit(&this->proxyUser, proxyLayout, qApp->getSettings()->GetProxyUser(), tr("Proxy user"));
CommunityPage::add_lineedit(&this->proxyPass, proxyLayout, qApp->getSettings()->GetProxyPass(), tr("Proxy pass"));
connect(this->useProxy, &QCheckBox::stateChanged, this, &CommunityPage::ProxyCheckChanged);
this->ProxyCheckChanged();
@ -169,14 +157,11 @@ QGroupBox *CommunityPage::UserGroup()
QGroupBox *userGroup = new QGroupBox(tr("User settings"));
QFormLayout *userLayout = new QFormLayout;
CommunityPage::add_lineedit(&this->username, userLayout,
qApp->getSettings()->value("community/username", "").toString(), tr("User Name"));
CommunityPage::add_checkbox(&this->savePassword, userLayout,
qApp->getSettings()->value("community/savePassword", 0).toBool(), tr("Save password"));
CommunityPage::add_lineedit(&this->userpassword, userLayout,
qApp->getSettings()->value("community/userpassword", "").toString(), tr("Password"));
CommunityPage::add_lineedit(&this->username, userLayout, qApp->getSettings()->GetUsername(), tr("User Name"));
CommunityPage::add_checkbox(&this->savePassword, userLayout, qApp->getSettings()->GetSavePassword(),
tr("Save password"));
CommunityPage::add_lineedit(&this->userpassword, userLayout, qApp->getSettings()->GetUserPassword(),
tr("Password"));
connect(this->savePassword, &QCheckBox::stateChanged, this, &CommunityPage::PasswordCheckChanged);
this->PasswordCheckChanged();

View file

@ -29,6 +29,7 @@
#include "configurationpage.h"
#include "../../../options.h"
#include "../../../core/vapplication.h"
#include "../../../core/vsettings.h"
#include <QDir>
#include <QGroupBox>
#include <QLabel>
@ -62,46 +63,38 @@ ConfigurationPage::ConfigurationPage(QWidget *parent)
//---------------------------------------------------------------------------------------------------------------------
void ConfigurationPage::Apply()
{
qApp->getSettings()->setValue("configuration/autosave/state", autoSaveCheck->isChecked());
qApp->getSettings()->setValue("configuration/autosave/time", autoTime->value());
qApp->getSettings()->SetAutosaveState(autoSaveCheck->isChecked());
qApp->getSettings()->SetAutosaveTime(autoTime->value());
QTimer *autoSaveTimer = qApp->getAutoSaveTimer();
SCASSERT(autoSaveTimer);
if (autoSaveCheck->isChecked())
{
autoSaveTimer->start(autoTime->value()*60000);
}
else
{
autoSaveTimer->stop();
}
autoSaveCheck->isChecked() ? autoSaveTimer->start(autoTime->value()*60000) : autoSaveTimer->stop();
qApp->getSettings()->setValue("configuration/osSeparator", osOptionCheck->isChecked());
qApp->getSettings()->setValue("configuration/send_report/state", sendReportCheck->isChecked());
qApp->getSettings()->SetOsSeparator(osOptionCheck->isChecked());
qApp->getSettings()->SetSendReportState(sendReportCheck->isChecked());
if (langChanged)
{
QString locale = qvariant_cast<QString>(langCombo->itemData(langCombo->currentIndex()));
qApp->getSettings()->setValue("configuration/locale", locale);
const QString locale = qvariant_cast<QString>(langCombo->itemData(langCombo->currentIndex()));
qApp->getSettings()->SetLocale(locale);
langChanged = false;
QString text = QString(tr("Setup user interface language updated and will be used the next time start") + " " +
QApplication::applicationName());
const QString text = tr("Setup user interface language updated and will be used the next time start") + " " +
QApplication::applicationName();
QMessageBox::information(this, QApplication::applicationName(), text);
}
if (this->unitChanged)
{
QString unit = qvariant_cast<QString>(this->unitCombo->itemData(this->unitCombo->currentIndex()));
qApp->getSettings()->setValue("configuration/unit", unit);
const QString unit = qvariant_cast<QString>(this->unitCombo->itemData(this->unitCombo->currentIndex()));
qApp->getSettings()->SetUnit(unit);
this->unitChanged = false;
QString text = QString(tr("Default unit updated and will be used the next pattern creation"));
const QString text = tr("Default unit updated and will be used the next pattern creation");
QMessageBox::information(this, QApplication::applicationName(), text);
}
if (labelLangChanged)
{
QString locale = qvariant_cast<QString>(labelCombo->itemData(labelCombo->currentIndex()));
qApp->getSettings()->setValue("configuration/label_language", locale);
const QString locale = qvariant_cast<QString>(labelCombo->itemData(labelCombo->currentIndex()));
qApp->getSettings()->SetLabelLanguage(locale);
labelLangChanged = false;
}
}
@ -127,31 +120,19 @@ void ConfigurationPage::LabelLangChanged()
//---------------------------------------------------------------------------------------------------------------------
QGroupBox *ConfigurationPage::SaveGroup()
{
QSettings *settings = qApp->getSettings();
SCASSERT(settings != nullptr);
QGroupBox *saveGroup = new QGroupBox(tr("Save"));
autoSaveCheck = new QCheckBox(tr("Auto-save modified pattern"));
bool autoSaveValue = settings->value("configuration/autosave/state", 1).toBool();
autoSaveCheck->setChecked(autoSaveValue);
QLabel *intervalLabel = new QLabel(tr("Interval:"));
autoSaveCheck->setChecked(qApp->getSettings()->GetAutosaveState());
autoTime = new QSpinBox();
bool ok = true;
qint32 autoTimeValue = settings->value("configuration/autosave/time", 1).toInt(&ok);
if (ok == false)
{
autoTimeValue = 5;
}
autoTime->setRange(1, 60);
autoTime->setValue(autoTimeValue);
autoTime->setValue(qApp->getSettings()->GetAutosaveTime());
autoTime->setSuffix(tr("min"));
QHBoxLayout *autosaveLayout = new QHBoxLayout;
autosaveLayout->addWidget(autoSaveCheck);
autosaveLayout->addWidget(intervalLabel);
autosaveLayout->addWidget(new QLabel(tr("Interval:")));
autosaveLayout->addWidget(autoTime);
QVBoxLayout *saveLayout = new QVBoxLayout;
@ -163,19 +144,12 @@ QGroupBox *ConfigurationPage::SaveGroup()
//---------------------------------------------------------------------------------------------------------------------
QGroupBox *ConfigurationPage::LangGroup()
{
QSettings *settings = qApp->getSettings();
SCASSERT(settings != nullptr);
QGroupBox *langGroup = new QGroupBox(tr("Language"));
QLabel *guiLabel = new QLabel(tr("GUI language"));
langCombo = new QComboBox;
// format systems language
QString checkedLocale = settings->value("configuration/locale", QLocale::system().name()).toString();
QString m_langPath = qApp->translationsPath();
QDir dir(m_langPath);
QStringList fileNames = dir.entryList(QStringList("valentina_*.qm"));
QDir dir(qApp->translationsPath());
const QStringList fileNames = dir.entryList(QStringList("valentina_*.qm"));
for (int i = 0; i < fileNames.size(); ++i)
{
@ -198,7 +172,7 @@ QGroupBox *ConfigurationPage::LangGroup()
langCombo->addItem(ico, lang, "en_US");
// set default translators and language checked
qint32 index = langCombo->findData(checkedLocale);
qint32 index = langCombo->findData(qApp->getSettings()->GetLocale());
if (index != -1)
{
langCombo->setCurrentIndex(index);
@ -214,8 +188,7 @@ QGroupBox *ConfigurationPage::LangGroup()
QLabel *separatorLabel = new QLabel(tr("Decimal separator parts"));
osOptionCheck = new QCheckBox(tr("With OS options (%1)").arg(QLocale::system().decimalPoint().toLatin1()));
bool osOptionValue = settings->value("configuration/osSeparator", 1).toBool();
osOptionCheck->setChecked(osOptionValue);
osOptionCheck->setChecked(qApp->getSettings()->GetOsSeparator());
QHBoxLayout *separatorLayout = new QHBoxLayout;
separatorLayout->addWidget(separatorLabel);
@ -225,14 +198,12 @@ QGroupBox *ConfigurationPage::LangGroup()
this->unitCombo = new QComboBox;
QLabel *unitLabel = new QLabel(tr("Default unit"));
QString checkedUnit = settings->value("configuration/unit", "cm").toString();
this->unitCombo->addItem(tr("Centimeters"), "cm");
this->unitCombo->addItem(tr("Millimiters"), "mm");
this->unitCombo->addItem(tr("Inches"), "in");
// set default unit
qint32 indexUnit = this->unitCombo->findData(checkedUnit);
qint32 indexUnit = this->unitCombo->findData(qApp->getSettings()->GetUnit());
if (indexUnit != -1)
{
this->unitCombo->setCurrentIndex(indexUnit);
@ -249,12 +220,9 @@ QGroupBox *ConfigurationPage::LangGroup()
QLabel *labelName = new QLabel(tr("Label language"));
labelCombo = new QComboBox;
QString checkedLabelLocale = settings->value("configuration/label_language",
QLocale::system().bcp47Name()).toString();
SetLabelComboBox(VApplication::LabelLanguages());
index = labelCombo->findData(checkedLabelLocale);
index = labelCombo->findData(qApp->getSettings()->GetLabelLanguage());
if (index != -1)
{
labelCombo->setCurrentIndex(index);
@ -281,14 +249,10 @@ QGroupBox *ConfigurationPage::LangGroup()
//---------------------------------------------------------------------------------------------------------------------
QGroupBox *ConfigurationPage::SendGroup()
{
QSettings *settings = qApp->getSettings();
SCASSERT(settings != nullptr);
QGroupBox *sendGroup = new QGroupBox(tr("Send crash reports"));
sendReportCheck = new QCheckBox(tr("Send crash reports (recommended)"));
bool sendReportValue = settings->value("configuration/send_report/state", 1).toBool();
sendReportCheck->setChecked(sendReportValue);
sendReportCheck->setChecked(qApp->getSettings()->GetSendReportState());
QLabel *description = new QLabel(tr("After each crash Valentina collect information that may help us fix a "
"problem. We do not collect any personal information. Find more about what "

View file

@ -29,6 +29,7 @@
#include "pathpage.h"
#include "../../../options.h"
#include "../../../core/vapplication.h"
#include "../../../core/vsettings.h"
#include <QDir>
#include <QGroupBox>
#include <QLabel>
@ -61,8 +62,8 @@ PathPage::PathPage(QWidget *parent)
//---------------------------------------------------------------------------------------------------------------------
void PathPage::Apply()
{
qApp->getSettings()->setValue("paths/individual_measurements", pathTable->item(0, 1)->text());
qApp->getSettings()->setValue("paths/pattern", pathTable->item(1, 1)->text());
qApp->getSettings()->SetPathIndividualMeasurements(pathTable->item(0, 1)->text());
qApp->getSettings()->SetPathPattern(pathTable->item(1, 1)->text());
}
//---------------------------------------------------------------------------------------------------------------------
@ -138,15 +139,11 @@ void PathPage::InitTable()
QStringList tableHeader = QStringList() << tr("Type") << tr("Path");
pathTable->setHorizontalHeaderLabels(tableHeader);
QString path;
pathTable->setItem(0, 0, new QTableWidgetItem(tr("Individual measurements")));
path = qApp->getSettings()->value("paths/individual_measurements", QDir::homePath()).toString();
pathTable->setItem(0, 1, new QTableWidgetItem(path));
pathTable->setItem(0, 1, new QTableWidgetItem(qApp->getSettings()->GetPathIndividualMeasurements()));
pathTable->setItem(1, 0, new QTableWidgetItem(tr("Patterns")));
path = qApp->getSettings()->value("paths/pattern", QDir::homePath()).toString();
pathTable->setItem(1, 1, new QTableWidgetItem(path));
pathTable->setItem(1, 1, new QTableWidgetItem(qApp->getSettings()->GetPathPattern()));
pathTable->verticalHeader()->setDefaultSectionSize(20);
pathTable->resizeColumnsToContents();

View file

@ -29,6 +29,7 @@
#include "patternpage.h"
#include "../../../options.h"
#include "../../../core/vapplication.h"
#include "../../../core/vsettings.h"
#include "../../../widgets/vmaingraphicsview.h"
#include <QGroupBox>
#include <QLabel>
@ -57,35 +58,27 @@ PatternPage::PatternPage(QWidget *parent):
//---------------------------------------------------------------------------------------------------------------------
void PatternPage::Apply()
{
qApp->getSettings()->setValue("pattern/user", userName->text());
qApp->getSettings()->SetUser(userName->text());
// Scene antialiasing
qApp->getSettings()->setValue("pattern/graphicalOutput", graphOutputCheck->isChecked());
qApp->getSettings()->SetGraphicalOutput(graphOutputCheck->isChecked());
qApp->getSceneView()->setRenderHint(QPainter::Antialiasing, graphOutputCheck->isChecked());
qApp->getSceneView()->setRenderHint(QPainter::SmoothPixmapTransform, graphOutputCheck->isChecked());
/* Maximum number of commands in undo stack may only be set when the undo stack is empty, since setting it on a
* non-empty stack might delete the command at the current index. Calling setUndoLimit() on a non-empty stack
* prints a warning and does nothing.*/
qApp->getSettings()->setValue("pattern/undo", undoCount->value());
qApp->getSettings()->SetUndoCount(undoCount->value());
}
//---------------------------------------------------------------------------------------------------------------------
QGroupBox *PatternPage::UserGroup()
{
QSettings *settings = qApp->getSettings();
SCASSERT(settings != nullptr);
QGroupBox *userGroup = new QGroupBox(tr("User"));
QLabel *nameLabel = new QLabel(tr("User name"));
userName = new QLineEdit;
#ifdef Q_OS_WIN
QString user = settings->value("pattern/user", QString::fromLocal8Bit(qgetenv("USERNAME").constData())).toString();
#else
QString user = settings->value("pattern/user", QString::fromLocal8Bit(qgetenv("USER").constData())).toString();
#endif
userName->setText(user);
userName->setText(qApp->getSettings()->GetUser());
QHBoxLayout *nameLayout = new QHBoxLayout;
nameLayout->addWidget(nameLabel);
@ -103,8 +96,7 @@ QGroupBox *PatternPage::GraphOutputGroup()
QGroupBox *graphOutputGroup = new QGroupBox(tr("Graphical output"));
graphOutputCheck = new QCheckBox(tr("Use antialiasing"));
bool graphOutputValue = qApp->getSettings()->value("pattern/graphicalOutput", 1).toBool();
graphOutputCheck->setChecked(graphOutputValue);
graphOutputCheck->setChecked(qApp->getSettings()->GetGraphicalOutput());
QHBoxLayout *graphLayout = new QHBoxLayout;
graphLayout->addWidget(graphOutputCheck);
@ -122,13 +114,7 @@ QGroupBox *PatternPage::UndoGroup()
QLabel *undoLabel = new QLabel(tr("Count steps (0 - no limit)"));
undoCount = new QSpinBox;
undoCount->setMinimum(0);
bool ok = true;
qint32 count = qApp->getSettings()->value("pattern/undo", 0).toInt(&ok);
if (ok == false)
{
count = 0;
}
undoCount->setValue(count);
undoCount->setValue(qApp->getSettings()->GetUndoCount());
QHBoxLayout *countLayout = new QHBoxLayout;
countLayout->addWidget(undoLabel);

View file

@ -201,7 +201,7 @@ QString DialogHistory::Record(const VToolRecord &tool)
if (domElem.isElement() == false)
{
qDebug()<<"Can't find element by id"<<Q_FUNC_INFO;
return QString(tr("Can't create record."));
return tr("Can't create record.");
}
try
{
@ -291,7 +291,7 @@ QString DialogHistory::Record(const VToolRecord &tool)
else
{
qDebug()<<"Not enough points in splinepath"<<Q_FUNC_INFO;
return QString(tr("Can't create record."));
return tr("Can't create record.");
}
return record;
}
@ -397,14 +397,14 @@ QString DialogHistory::Record(const VToolRecord &tool)
break;
default:
qDebug()<<"Got wrong tool type. Ignore.";
return QString(tr("Can't create record."));
return tr("Can't create record.");
break;
}
}
catch (const VExceptionBadId &e)
{
qDebug()<<e.ErrorMessage()<<Q_FUNC_INFO;
return QString(tr("Can't create record."));
return tr("Can't create record.");
}
return QString();
}

View file

@ -32,6 +32,7 @@
#include "../../widgets/textdelegate.h"
#include "../../xml/vstandardmeasurements.h"
#include "../../xml/vindividualmeasurements.h"
#include "../../core/vsettings.h"
#include <QFileDialog>
#include <QDir>
@ -54,8 +55,10 @@ DialogIncrements::DialogIncrements(VContainer *data, VPattern *doc, QWidget *par
{
ui->setupUi(this);
qCDebug(vDialog)<<"Showing variables.";
if (qApp->patternType() == MeasurementsType::Individual)
{
qCDebug(vDialog)<<"Pattern with individual measurements.";
const QString filePath = doc->MPath();
try
{
@ -510,7 +513,7 @@ void DialogIncrements::OpenTable()
const QString filter(tr("Individual measurements (*.vit)"));
//Use standard path to individual measurements
QString path = qApp->getSettings()->value("paths/individual_measurements", QDir::homePath()).toString();
const QString path = qApp->getSettings()->GetPathIndividualMeasurements();
const QString filePath = QFileDialog::getOpenFileName(this, tr("Open file"), path, filter);
if (filePath.isEmpty())
@ -598,6 +601,7 @@ void DialogIncrements::OpenTable()
*/
void DialogIncrements::clickedToolButtonAdd()
{
qCDebug(vDialog)<<"Add new increment";
ui->tableWidgetIncrement->setFocus(Qt::OtherFocusReason);
ui->tableWidgetIncrement->blockSignals(true);
qint32 currentRow = ui->tableWidgetIncrement->rowCount();
@ -666,6 +670,7 @@ void DialogIncrements::clickedToolButtonRemove()
qint32 row = item->row();
QTableWidgetItem *itemName = ui->tableWidgetIncrement->item(row, 0);
qCDebug(vDialog)<<"Remove increment"<<itemName->text();
data->RemoveIncrement(itemName->text());
quint32 id = qvariant_cast<quint32>(itemName->data(Qt::UserRole));
@ -675,6 +680,10 @@ void DialogIncrements::clickedToolButtonRemove()
QDomNodeList list = doc->elementsByTagName(VPattern::TagIncrements);
list.at(0).removeChild(domElement);
}
else
{
qCDebug(vDialog)<<"Could not find object with id"<<id;
}
ui->tableWidgetIncrement->removeRow(row);
if (ui->tableWidgetIncrement->rowCount() == 0)
@ -699,6 +708,9 @@ void DialogIncrements::clickedToolButtonRemove()
void DialogIncrements::AddIncrementToFile(const quint32 &id, const QString &name, const qreal &base, const qreal &ksize,
const qreal &kheight, const QString &description)
{
qCDebug(vDialog)<<"Saving new increment to file.";
qCDebug(vDialog)<<QString("Increment: id(%1), name(%2), base(%3), ksize(%4), kheight(%5), description(%6)")
.arg(id).arg(name).arg(base).arg(ksize).arg(kheight).arg(description);
QDomElement element = doc->createElement(VPattern::TagIncrement);
doc->SetAttribute(element, VDomDocument::AttrId, id);
@ -730,42 +742,47 @@ void DialogIncrements::HideColumns(QTableWidget *table)
*/
void DialogIncrements::IncrementChanged ( qint32 row, qint32 column )
{
qCDebug(vDialog)<<"Increment changed.";
const QTableWidgetItem *itemName = ui->tableWidgetIncrement->item(row, 0);
const QTableWidgetItem *item = ui->tableWidgetIncrement->item(row, column);
const quint32 id = qvariant_cast<quint32>(itemName->data(Qt::UserRole));
QDomElement domElement = doc->elementById(QString().setNum(id));
if (domElement.isElement() == false)
{
qDebug()<<"Cant't find increment with id = "<<id<<Q_FUNC_INFO;
qCDebug(vDialog)<<"Cant't find increment with id = "<<id<<Q_FUNC_INFO;
return;
}
this->row = row;
switch (column)
{
case 0: // VPattern::IncrementName
qCDebug(vDialog)<<"Changed name to"<<item->text();
doc->SetAttribute(domElement, VPattern::IncrementName, item->text());
data->ClearVariables(VarType::Increment);
this->column = 2;
emit FullUpdateTree(Document::LiteParse);
break;
case 2: // VPattern::IncrementBase
qCDebug(vDialog)<<"Changed base to"<<item->text();
doc->SetAttribute(domElement, VPattern::IncrementBase, item->text());
this->column = 3;
emit FullUpdateTree(Document::LiteParse);
break;
case 3: // VPattern::IncrementKsize
qCDebug(vDialog)<<"Changed ksize to"<<item->text();
doc->SetAttribute(domElement, VPattern::IncrementKsize, item->text());
this->column = 4;
emit FullUpdateTree(Document::LiteParse);
break;
case 4: // VPattern::IncrementKgrowth
qCDebug(vDialog)<<"Changed kheight to"<<item->text();
doc->SetAttribute(domElement, VPattern::IncrementKgrowth, item->text());
this->column = 5;
emit FullUpdateTree(Document::LiteParse);
break;
case 5: // VPattern::IncrementDescription
{
qCDebug(vDialog)<<"Changed description to"<<item->text();
doc->SetAttribute(domElement, VPattern::IncrementDescription, item->text());
QSharedPointer<VIncrement> incr = data->GetVariable<VIncrement>(itemName->text());
incr->SetDescription(item->text());
@ -785,6 +802,7 @@ void DialogIncrements::IncrementChanged ( qint32 row, qint32 column )
//---------------------------------------------------------------------------------------------------------------------
void DialogIncrements::MeasurementChanged(qint32 row, qint32 column)
{
qCDebug(vDialog)<<"Measurement changed.";
switch (column)
{
case 2:// value column
@ -798,7 +816,7 @@ void DialogIncrements::MeasurementChanged(qint32 row, qint32 column)
QDomElement domElement = list.at(0).toElement();
if (domElement.isElement() == false)
{
qDebug()<<"Can't find measurement "<<tag<<Q_FUNC_INFO;
qCDebug(vDialog)<<"Can't find measurement "<<tag<<Q_FUNC_INFO;
return;
}
@ -808,12 +826,13 @@ void DialogIncrements::MeasurementChanged(qint32 row, qint32 column)
{
measur->SetBase(0);
item->setText("0");
qDebug()<<"Can't convert toDouble measurement value"<<Q_FUNC_INFO;
qCDebug(vDialog)<<"Can't convert toDouble measurement value"<<Q_FUNC_INFO;
}
else
{
measur->SetBase(base);
}
qCDebug(vDialog)<<"Changed value to"<<base;
// Convert value to measurements table unit
base = VAbstractMeasurements::UnitConvertor(base, qApp->patternUnit(), m->MUnit());

View file

@ -29,13 +29,15 @@
#include "dialogindividualmeasurements.h"
#include "ui_dialogindividualmeasurements.h"
#include "../../xml/vindividualmeasurements.h"
#include "../../core/vapplication.h"
#include "../../core/vsettings.h"
#include "../../container/vcontainer.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QPushButton>
#include <QSettings>
#include <QDesktopWidget>
#include "../../core/vapplication.h"
#include "../../container/vcontainer.h"
//---------------------------------------------------------------------------------------------------------------------
DialogIndividualMeasurements::DialogIndividualMeasurements(VContainer *data, const QString &patternPieceName,
@ -195,7 +197,7 @@ void DialogIndividualMeasurements::CheckState()
void DialogIndividualMeasurements::OpenTable()
{
const QString filter(tr("Individual measurements (*.vit)"));
QString path = qApp->getSettings()->value("paths/individual_measurements", QDir::homePath()).toString();
const QString path = qApp->getSettings()->GetPathIndividualMeasurements();
QString fileName = QFileDialog::getOpenFileName(this, tr("Open file"), path, filter);
if (fileName.isEmpty())
@ -251,9 +253,8 @@ void DialogIndividualMeasurements::InitUnits()
ui->comboBoxUnits->addItem(tr("Millimiters"), QVariant(VDomDocument::UnitsToStr(Unit::Mm)));
ui->comboBoxUnits->addItem(tr("Inches"), QVariant(VDomDocument::UnitsToStr(Unit::Inch)));
const QString checkedUnit = qApp->getSettings()->value("configuration/unit", "cm").toString();
// set default unit
const qint32 indexUnit = ui->comboBoxUnits->findData(checkedUnit);
const qint32 indexUnit = ui->comboBoxUnits->findData(qApp->getSettings()->GetUnit());
if (indexUnit != -1)
{
ui->comboBoxUnits->setCurrentIndex(indexUnit);

View file

@ -90,7 +90,7 @@
<item alignment="Qt::AlignHCenter">
<widget class="QLabel" name="label_2">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
@ -139,7 +139,7 @@
<item alignment="Qt::AlignHCenter">
<widget class="QLabel" name="label_4">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>

View file

@ -458,7 +458,7 @@ void DialogPatternXmlEdit::ButtonApplyChangesClicked()
Changes += currentChange->element->GettreeNodeName();
Changes += "/";
Changes += (currentChange->element->GettreeNodeValueSet()) ?
currentChange->element->GettreeNodeValue(): QString(tr("<no value>"));
currentChange->element->GettreeNodeValue(): tr("<no value>");
Changes += "\n";
}
else
@ -466,9 +466,9 @@ void DialogPatternXmlEdit::ButtonApplyChangesClicked()
if (currentChange->type == DialogPatternXmlEdit::ChangeTypeModify)
{
Changes += QString("Modified type %1 : ").arg(nodetype);
Changes += (currentChange->changedText) ? *currentChange->newText : QString(tr("Unchanged"));
Changes += (currentChange->changedText) ? *currentChange->newText : tr("Unchanged");
Changes += "/";
Changes += (currentChange->changedValue) ? *currentChange->newValue: QString(tr("Unchanged"));
Changes += (currentChange->changedValue) ? *currentChange->newValue: tr("Unchanged");
Changes += "\n";
}
else
@ -479,7 +479,7 @@ void DialogPatternXmlEdit::ButtonApplyChangesClicked()
Changes += currentChange->element->GettreeNodeName();
Changes += "/";
Changes += (currentChange->element->GettreeNodeValueSet()) ?
currentChange->element->GettreeNodeValue(): QString(tr("<no value>"));
currentChange->element->GettreeNodeValue(): tr("<no value>");
Changes += "\n";
}
}

View file

@ -34,6 +34,9 @@
#include "../../xml/vstandardmeasurements.h"
#include "../../core/vapplication.h"
#include "../../container/vcontainer.h"
#include <QLoggingCategory>
Q_LOGGING_CATEGORY(vStMeasur, "v.st.measurements")
//---------------------------------------------------------------------------------------------------------------------
DialogStandardMeasurements::DialogStandardMeasurements(VContainer *data, const QString &patternPieceName,
@ -57,6 +60,7 @@ DialogStandardMeasurements::DialogStandardMeasurements(VContainer *data, const Q
connect(bCansel, &QPushButton::clicked, this, &DialogStandardMeasurements::DialogRejected);
}
qCDebug(vStMeasur)<<"Pattern piece name"<<_name;
ui->lineEditName->setText(_name);
LoadStandardTables();
@ -143,6 +147,7 @@ void DialogStandardMeasurements::CheckState()
//---------------------------------------------------------------------------------------------------------------------
void DialogStandardMeasurements::LoadStandardTables()
{
qCDebug(vStMeasur)<<"Loading standard table.";
QStringList filters{"*.vst"};
QDir tablesDir(qApp->pathToTables());
tablesDir.setNameFilters(filters);
@ -151,11 +156,13 @@ void DialogStandardMeasurements::LoadStandardTables()
const QStringList allFiles = tablesDir.entryList(QDir::NoDotAndDotDot | QDir::Files);
if (allFiles.isEmpty() == true)
{
qCDebug(vStMeasur)<<"Can't find standard measurements in path"<<qApp->pathToTables();
ui->comboBoxTables->clear();
CheckState();
return;
}
qCDebug(vStMeasur)<<"Was found"<<allFiles.size()<<"tables.";
for (int i = 0; i < allFiles.size(); ++i)
{
QFileInfo fi(allFiles.at(i));
@ -166,24 +173,27 @@ void DialogStandardMeasurements::LoadStandardTables()
m.setContent(fi.absoluteFilePath());
if (m.MUnit() == Unit::Inch)
{
qWarning()<<"We do not support inches for standard table. Ignore table"<<fi.absoluteFilePath()<<".";
qCWarning(vStMeasur)<<"We do not support inches for standard table. Ignore table"
<<fi.absoluteFilePath()<<".";
}
else
{
const QString trDesc = qApp->STDescription(m.Id());
if (trDesc.isEmpty() == false)
{
qCDebug(vStMeasur)<<"Adding user table from"<<fi.absoluteFilePath();
ui->comboBoxTables->addItem(trDesc, QVariant(fi.absoluteFilePath()));
}
else if (m.Description().isEmpty() == false)
{
qCDebug(vStMeasur)<<"Adding table with id"<<m.Id()<<"from"<<fi.absoluteFilePath();
ui->comboBoxTables->addItem(m.Description(), QVariant(fi.absoluteFilePath()));
}
}
}
catch (VException &e)
{
qDebug()<<"File error."<<e.ErrorMessage()<<e.DetailedInformation()<<Q_FUNC_INFO;
qCDebug(vStMeasur)<<"File error."<<e.ErrorMessage()<<e.DetailedInformation()<<Q_FUNC_INFO;
continue;
}
}

View file

@ -190,6 +190,13 @@ void DialogAlongLine::SaveData()
line->RefreshGeometry();
}
//---------------------------------------------------------------------------------------------------------------------
void DialogAlongLine::closeEvent(QCloseEvent *event)
{
ui->plainTextEditFormula->blockSignals(true);
DialogTool::closeEvent(event);
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief setSecondPointId set id second point of line

View file

@ -78,6 +78,7 @@ protected:
* @brief SaveData Put dialog data in local variables
*/
virtual void SaveData();
virtual void closeEvent(QCloseEvent *event);
private:
Q_DISABLE_COPY(DialogAlongLine)

View file

@ -45,8 +45,9 @@
*/
DialogArc::DialogArc(const VContainer *data, const quint32 &toolId, QWidget *parent)
:DialogTool(data, toolId, parent), ui(new Ui::DialogArc), flagRadius(false), flagF1(false), flagF2(false),
timerRadius(nullptr), timerF1(nullptr), timerF2(nullptr), center(NULL_ID), radius(QString()), f1(QString()),
f2(QString()), formulaBaseHeight(0), formulaBaseHeightF1(0), formulaBaseHeightF2(0), path(nullptr)
timerRadius(nullptr), timerF1(nullptr), timerF2(nullptr), center(NULL_ID), radius(QString()),
f1(QString()), f2(QString()), formulaBaseHeight(0), formulaBaseHeightF1(0), formulaBaseHeightF2(0), path(nullptr),
angleF1(INT_MIN), angleF2(INT_MIN)
{
ui->setupUi(this);
@ -65,10 +66,10 @@ DialogArc::DialogArc(const VContainer *data, const quint32 &toolId, QWidget *par
connect(timerRadius, &QTimer::timeout, this, &DialogArc::EvalRadius);
timerF1 = new QTimer(this);
connect(timerF1, &QTimer::timeout, this, &DialogArc::EvalF1);
connect(timerF1, &QTimer::timeout, this, &DialogArc::EvalF);
timerF2 = new QTimer(this);
connect(timerF2, &QTimer::timeout, this, &DialogArc::EvalF2);
connect(timerF2, &QTimer::timeout, this, &DialogArc::EvalF);
InitOkCancelApply(ui);
@ -81,8 +82,8 @@ DialogArc::DialogArc(const VContainer *data, const quint32 &toolId, QWidget *par
connect(ui->toolButtonPutHereF2, &QPushButton::clicked, this, &DialogArc::PutF2);
connect(ui->toolButtonEqualRadius, &QPushButton::clicked, this, &DialogArc::EvalRadius);
connect(ui->toolButtonEqualF1, &QPushButton::clicked, this, &DialogArc::EvalF1);
connect(ui->toolButtonEqualF2, &QPushButton::clicked, this, &DialogArc::EvalF2);
connect(ui->toolButtonEqualF1, &QPushButton::clicked, this, &DialogArc::EvalF);
connect(ui->toolButtonEqualF2, &QPushButton::clicked, this, &DialogArc::EvalF);
connect(ui->plainTextEditFormula, &QPlainTextEdit::textChanged, this, &DialogArc::RadiusChanged);
connect(ui->plainTextEditF1, &QPlainTextEdit::textChanged, this, &DialogArc::F1Changed);
@ -239,6 +240,15 @@ void DialogArc::SaveData()
path->RefreshGeometry();
}
//---------------------------------------------------------------------------------------------------------------------
void DialogArc::closeEvent(QCloseEvent *event)
{
ui->plainTextEditFormula->blockSignals(true);
ui->plainTextEditF1->blockSignals(true);
ui->plainTextEditF2->blockSignals(true);
DialogTool::closeEvent(event);
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief ValChenged show description angles of lines
@ -351,27 +361,32 @@ void DialogArc::EvalRadius()
{
labelEditFormula = ui->labelEditRadius;
const QString postfix = VDomDocument::UnitsToStr(qApp->patternUnit(), true);
Eval(ui->plainTextEditFormula->toPlainText(), flagRadius, ui->labelResultRadius, postfix);
const qreal radius = Eval(ui->plainTextEditFormula->toPlainText(), flagRadius, ui->labelResultRadius, postfix);
if (radius < 0)
{
flagRadius = false;
ChangeColor(labelEditFormula, Qt::red);
ui->labelResultRadius->setText(tr("Error"));
ui->labelResultRadius->setToolTip(tr("Radius can't be negative"));
DialogArc::CheckState();
}
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief EvalF1 calculate value of first angle
* @brief EvalF1 calculate value of angle
*/
void DialogArc::EvalF1()
void DialogArc::EvalF()
{
labelEditFormula = ui->labelEditF1;
Eval(ui->plainTextEditF1->toPlainText(), flagF1, ui->labelResultF1, degreeSymbol, false);
}
angleF1 = Eval(ui->plainTextEditF1->toPlainText(), flagF1, ui->labelResultF1, degreeSymbol, false);
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief EvalF2 calculate value of second angle
*/
void DialogArc::EvalF2()
{
labelEditFormula = ui->labelEditF2;
Eval(ui->plainTextEditF2->toPlainText(), flagF2, ui->labelResultF2, degreeSymbol, false);
angleF2 = Eval(ui->plainTextEditF2->toPlainText(), flagF2, ui->labelResultF2, degreeSymbol, false);
CheckAngles();
}
//---------------------------------------------------------------------------------------------------------------------
@ -394,3 +409,27 @@ void DialogArc::ShowLineAngles()
}
ui->listWidget->setCurrentRow (0);
}
//---------------------------------------------------------------------------------------------------------------------
void DialogArc::CheckAngles()
{
if (angleF1 == INT_MIN || angleF2 == INT_MIN)
{
return;
}
if (qFuzzyCompare(angleF1 + 1, angleF2 + 1))
{
flagF1 = false;
ChangeColor(ui->labelEditF1, Qt::red);
ui->labelResultF1->setText(tr("Error"));
ui->labelResultF1->setToolTip(tr("Angles equal"));
flagF2 = false;
ChangeColor(ui->labelEditF2, Qt::red);
ui->labelResultF2->setText(tr("Error"));
ui->labelResultF2->setToolTip(tr("Angles equal"));
}
DialogArc::CheckState();
}

View file

@ -83,6 +83,7 @@ protected:
* @brief SaveData Put dialog data in local variables
*/
virtual void SaveData();
virtual void closeEvent(QCloseEvent *event);
private:
Q_DISABLE_COPY(DialogArc)
@ -126,11 +127,13 @@ private:
VisToolArc *path;
void EvalRadius();
void EvalF1();
void EvalF2();
void ShowLineAngles();
qreal angleF1;
qreal angleF2;
void EvalRadius();
void EvalF();
void ShowLineAngles();
void CheckAngles();
};
//---------------------------------------------------------------------------------------------------------------------

View file

@ -287,3 +287,10 @@ void DialogBisector::SaveData()
line->setLineStyle(VAbstractTool::LineStyle(typeLine));
line->RefreshGeometry();
}
//---------------------------------------------------------------------------------------------------------------------
void DialogBisector::closeEvent(QCloseEvent *event)
{
ui->plainTextEditFormula->blockSignals(true);
DialogTool::closeEvent(event);
}

View file

@ -83,6 +83,7 @@ protected:
* @brief SaveData Put dialog data in local variables
*/
virtual void SaveData();
virtual void closeEvent(QCloseEvent *event);
private:
Q_DISABLE_COPY(DialogBisector)

View file

@ -269,3 +269,10 @@ void DialogCurveIntersectAxis::SaveData()
line->setLineStyle(VAbstractTool::LineStyle(typeLine));
line->RefreshGeometry();
}
//---------------------------------------------------------------------------------------------------------------------
void DialogCurveIntersectAxis::closeEvent(QCloseEvent *event)
{
ui->plainTextEditFormula->blockSignals(true);
DialogTool::closeEvent(event);
}

View file

@ -73,6 +73,7 @@ protected:
* @brief SaveData Put dialog data in local variables
*/
virtual void SaveData();
virtual void closeEvent(QCloseEvent *event);
private:
Q_DISABLE_COPY(DialogCurveIntersectAxis)
Ui::DialogCurveIntersectAxis *ui;

View file

@ -137,6 +137,13 @@ void DialogCutArc::SaveData()
path->RefreshGeometry();
}
//---------------------------------------------------------------------------------------------------------------------
void DialogCutArc::closeEvent(QCloseEvent *event)
{
ui->plainTextEditFormula->blockSignals(true);
DialogTool::closeEvent(event);
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief setArcId set id of arc

View file

@ -73,6 +73,7 @@ protected:
* @brief SaveData Put dialog data in local variables
*/
virtual void SaveData();
virtual void closeEvent(QCloseEvent *event);
private:
Q_DISABLE_COPY(DialogCutArc)
/** @brief ui keeps information about user interface */

View file

@ -152,6 +152,13 @@ void DialogCutSpline::SaveData()
path->RefreshGeometry();
}
//---------------------------------------------------------------------------------------------------------------------
void DialogCutSpline::closeEvent(QCloseEvent *event)
{
ui->plainTextEditFormula->blockSignals(true);
DialogTool::closeEvent(event);
}
//---------------------------------------------------------------------------------------------------------------------
void DialogCutSpline::DeployFormulaTextEdit()
{

View file

@ -68,6 +68,7 @@ protected:
* @brief SaveData Put dialog data in local variables
*/
virtual void SaveData();
virtual void closeEvent(QCloseEvent *event);
private:
Q_DISABLE_COPY(DialogCutSpline)

View file

@ -152,6 +152,13 @@ void DialogCutSplinePath::SaveData()
path->RefreshGeometry();
}
//---------------------------------------------------------------------------------------------------------------------
void DialogCutSplinePath::closeEvent(QCloseEvent *event)
{
ui->plainTextEditFormula->blockSignals(true);
DialogTool::closeEvent(event);
}
//---------------------------------------------------------------------------------------------------------------------
void DialogCutSplinePath::DeployFormulaTextEdit()
{

View file

@ -68,6 +68,7 @@ protected:
* @brief SaveData Put dialog data in local variables
*/
virtual void SaveData();
virtual void closeEvent(QCloseEvent *event);
private:
Q_DISABLE_COPY(DialogCutSplinePath)

View file

@ -113,6 +113,13 @@ void DialogEditWrongFormula::CheckState()
bOk->setEnabled(flagFormula);
}
//---------------------------------------------------------------------------------------------------------------------
void DialogEditWrongFormula::closeEvent(QCloseEvent *event)
{
ui->plainTextEditFormula->blockSignals(true);
DialogTool::closeEvent(event);
}
//---------------------------------------------------------------------------------------------------------------------
void DialogEditWrongFormula::setFormula(const QString &value)
{

View file

@ -65,6 +65,7 @@ public slots:
virtual void EvalFormula();
protected:
virtual void CheckState();
virtual void closeEvent(QCloseEvent *event);
private:
Q_DISABLE_COPY(DialogEditWrongFormula)
Ui::DialogEditWrongFormula *ui;

View file

@ -1,4 +1,4 @@
/************************************************************************
/************************************************************************
**
** @file dialogendline.cpp
** @author Roman Telezhynskyi <dismine(at)gmail.com>
@ -291,6 +291,14 @@ void DialogEndLine::SaveData()
line->RefreshGeometry();
}
//---------------------------------------------------------------------------------------------------------------------
void DialogEndLine::closeEvent(QCloseEvent *event)
{
ui->plainTextEditFormula->blockSignals(true);
ui->plainTextEditAngle->blockSignals(true);
DialogTool::closeEvent(event);
}
//---------------------------------------------------------------------------------------------------------------------
DialogEndLine::~DialogEndLine()
{

View file

@ -83,6 +83,7 @@ protected:
* @brief SaveData Put dialog data in local variables
*/
virtual void SaveData();
virtual void closeEvent(QCloseEvent *event);
private:
Q_DISABLE_COPY(DialogEndLine)

View file

@ -336,3 +336,10 @@ void DialogLineIntersectAxis::SaveData()
line->setLineStyle(VAbstractTool::LineStyle(typeLine));
line->RefreshGeometry();
}
//---------------------------------------------------------------------------------------------------------------------
void DialogLineIntersectAxis::closeEvent(QCloseEvent *event)
{
ui->plainTextEditFormula->blockSignals(true);
DialogTool::closeEvent(event);
}

View file

@ -77,6 +77,7 @@ protected:
* @brief SaveData Put dialog data in local variables
*/
virtual void SaveData();
virtual void closeEvent(QCloseEvent *event);
private:
Q_DISABLE_COPY(DialogLineIntersectAxis)
Ui::DialogLineIntersectAxis *ui;

View file

@ -184,6 +184,13 @@ void DialogNormal::SaveData()
line->RefreshGeometry();
}
//---------------------------------------------------------------------------------------------------------------------
void DialogNormal::closeEvent(QCloseEvent *event)
{
ui->plainTextEditFormula->blockSignals(true);
DialogTool::closeEvent(event);
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief setSecondPointId set id of second point

View file

@ -82,6 +82,7 @@ protected:
* @brief SaveData Put dialog data in local variables
*/
virtual void SaveData();
virtual void closeEvent(QCloseEvent *event);
private:
Q_DISABLE_COPY(DialogNormal)

View file

@ -225,6 +225,13 @@ void DialogPointOfContact::SaveData()
line->RefreshGeometry();
}
//---------------------------------------------------------------------------------------------------------------------
void DialogPointOfContact::closeEvent(QCloseEvent *event)
{
ui->plainTextEditFormula->blockSignals(true);
DialogTool::closeEvent(event);
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief setSecondPoint set id second point

View file

@ -80,6 +80,7 @@ protected:
* @brief SaveData Put dialog data in local variables
*/
virtual void SaveData();
virtual void closeEvent(QCloseEvent *event);
private:
Q_DISABLE_COPY(DialogPointOfContact)

View file

@ -213,6 +213,13 @@ void DialogShoulderPoint::SaveData()
line->RefreshGeometry();
}
//---------------------------------------------------------------------------------------------------------------------
void DialogShoulderPoint::closeEvent(QCloseEvent *event)
{
ui->plainTextEditFormula->blockSignals(true);
DialogTool::closeEvent(event);
}
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief setPShoulder set id shoulder point

View file

@ -82,6 +82,7 @@ protected:
* @brief SaveData Put dialog data in local variables
*/
virtual void SaveData();
virtual void closeEvent(QCloseEvent *event);
private:
Q_DISABLE_COPY(DialogShoulderPoint)

View file

@ -236,8 +236,11 @@ void DialogSplinePath::ShowDialog(bool click)
{
if (click == false)
{
emit ToolTip("");
DialogAccepted();
if (path.CountPoint() >= 3)
{
emit ToolTip("");
DialogAccepted();
}
}
}

View file

@ -35,6 +35,7 @@
#include "../../tools/vabstracttool.h"
#include "../../../libs/qmuparser/qmuparsererror.h"
#include "../../core/vapplication.h"
#include "../../core/vsettings.h"
#include "../../xml/vdomdocument.h"
#include <QTimer>
#include <QCloseEvent>
@ -48,6 +49,8 @@
#include <QPushButton>
#include <QDoubleSpinBox>
Q_LOGGING_CATEGORY(vDialog, "v.dialog")
#define DIALOG_MAX_FORMULA_HEIGHT 64
//---------------------------------------------------------------------------------------------------------------------
@ -86,7 +89,7 @@ DialogTool::~DialogTool()
*/
void DialogTool::closeEvent(QCloseEvent *event)
{
DialogClosed(QDialog::Rejected);
DialogRejected();
event->accept();
}
@ -441,6 +444,7 @@ void DialogTool::ValFormulaChanged(bool &flag, QLineEdit *edit, QTimer *timer)
CheckState();
ChangeColor(labelEditFormula, Qt::red);
labelResultCalculation->setText(tr("Error"));
labelResultCalculation->setToolTip(tr("Empty field"));
return;
}
timer->start(1000);
@ -458,6 +462,7 @@ void DialogTool::ValFormulaChanged(bool &flag, QPlainTextEdit *edit, QTimer *tim
CheckState();
ChangeColor(labelEditFormula, Qt::red);
labelResultCalculation->setText(tr("Error"));
labelResultCalculation->setToolTip(tr("Empty field"));
return;
}
timer->setSingleShot(true);
@ -473,10 +478,13 @@ void DialogTool::ValFormulaChanged(bool &flag, QPlainTextEdit *edit, QTimer *tim
* @param postfix unit name
* @param checkZero true - if formula can't be equal zero
*/
void DialogTool::Eval(const QString &text, bool &flag, QLabel *label, const QString& postfix, bool checkZero)
qreal DialogTool::Eval(const QString &text, bool &flag, QLabel *label, const QString& postfix, bool checkZero)
{
SCASSERT(label != nullptr);
SCASSERT(labelEditFormula != nullptr);
qreal result = INT_MIN;//Value can be 0, so use max imposible value
if (text.isEmpty())
{
flag = false;
@ -493,7 +501,7 @@ void DialogTool::Eval(const QString &text, bool &flag, QLabel *label, const QStr
formula.replace("\n", " ");
formula = qApp->FormulaFromUser(formula);
Calculator *cal = new Calculator(data);
const qreal result = cal->EvalFormula(formula);
result = cal->EvalFormula(formula);
delete cal;
//if result equal 0
@ -507,7 +515,7 @@ void DialogTool::Eval(const QString &text, bool &flag, QLabel *label, const QStr
else
{
QLocale loc;
if (qApp->getSettings()->value("configuration/osSeparator", 1).toBool())
if (qApp->getSettings()->GetOsSeparator())
{
loc = QLocale::system();
}
@ -537,6 +545,7 @@ void DialogTool::Eval(const QString &text, bool &flag, QLabel *label, const QStr
}
}
CheckState();
return result;
}
//---------------------------------------------------------------------------------------------------------------------
@ -904,7 +913,7 @@ void DialogTool::EvalFormula()
SCASSERT(plainTextEditFormula != nullptr);
SCASSERT(labelResultCalculation != nullptr);
const QString postfix = VDomDocument::UnitsToStr(qApp->patternUnit());
Eval(plainTextEditFormula->toPlainText(), flagFormula, labelResultCalculation, postfix);
Eval(plainTextEditFormula->toPlainText(), flagFormula, labelResultCalculation, postfix, false);
}
//---------------------------------------------------------------------------------------------------------------------

View file

@ -37,6 +37,9 @@
#include "../../core/vapplication.h"
#include <QPushButton>
#include <QCheckBox>
#include <QLoggingCategory>
Q_DECLARE_LOGGING_CATEGORY(vDialog)
class QDoubleSpinBox;
class QLabel;
@ -225,7 +228,7 @@ protected:
void PutValHere(QPlainTextEdit *plainTextEdit, QListWidget *listWidget);
void ValFormulaChanged(bool &flag, QLineEdit *edit, QTimer * timer);
void ValFormulaChanged(bool &flag, QPlainTextEdit *edit, QTimer * timer);
void Eval(const QString &text, bool &flag, QLabel *label, const QString &postfix,
qreal Eval(const QString &text, bool &flag, QLabel *label, const QString &postfix,
bool checkZero = true);
void setCurrentPointId(QComboBox *box, quint32 &pointId, const quint32 &value) const;
void setCurrentSplineId(QComboBox *box, quint32 &splineId, const quint32 &value,

View file

@ -32,6 +32,9 @@
#include <QSpacerItem>
#include <QApplication>
#include "../options.h"
#include <QLoggingCategory>
Q_LOGGING_CATEGORY(vExcep, "v.excep")
//---------------------------------------------------------------------------------------------------------------------
/**
@ -100,6 +103,7 @@ void VException::CriticalMessageBox(const QString &situation, QWidget * parent)
#ifndef QT_NO_CURSOR
QApplication::restoreOverrideCursor();
#endif
qCDebug(vExcep)<<"Critical error!"<<situation<<ErrorMessage()<<DetailedInformation();
msgBox.exec();
}

View file

@ -90,8 +90,7 @@ QVector<QPointF> VAbstractCurve::IntersectLine(const QLineF &line) const
for ( qint32 i = 0; i < points.count()-1; ++i )
{
QPointF crosPoint;
QLineF::IntersectType type = QLineF::NoIntersection;
type = line.intersect(QLineF ( points.at(i), points.at(i+1)), &crosPoint);
QLineF::IntersectType type = line.intersect(QLineF ( points.at(i), points.at(i+1)), &crosPoint);
if ( type == QLineF::BoundedIntersection )
{
intersections.append(crosPoint);

View file

@ -144,6 +144,11 @@ QPointF VArc::GetP2 () const
*/
qreal VArc::AngleArc() const
{
if ((qFuzzyCompare(d->f1+1, 0+1) && qFuzzyCompare(d->f2, 360)) ||
(qFuzzyCompare(d->f1, 360) && qFuzzyCompare(d->f2+1, 0+1)))
{
return 360;
}
QLineF l1(0, 0, 100, 100);
l1.setAngle(d->f1);
QLineF l2(0, 0, 100, 100);

View file

@ -28,99 +28,16 @@
#include "mainwindow.h"
#include "core/vapplication.h"
#include <QTextCodec>
#include <QMessageBox>
#include <QThread>
#if QT_VERSION < QT_VERSION_CHECK(5, 2, 1)
#include "core/qcommandlineparser.h"
#else
#include <QCommandLineParser>
#endif
#include <QtXml>
#include <QLibraryInfo>
#include "core/vsettings.h"
#include "tablewindow.h"
#include "version.h"
//---------------------------------------------------------------------------------------------------------------------
inline void noisyFailureMsgHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
// Why on earth didn't Qt want to make failed signal/slot connections qWarning?
if ((type == QtDebugMsg) && msg.contains("::connect"))
{
type = QtWarningMsg;
}
// this is another one that doesn't make sense as just a debug message. pretty serious
// sign of a problem
// http://www.developer.nokia.com/Community/Wiki/QPainter::begin:Paint_device_returned_engine_%3D%3D_0_(Known_Issue)
if ((type == QtDebugMsg) && msg.contains("QPainter::begin") && msg.contains("Paint device returned engine"))
{
type = QtWarningMsg;
}
// This qWarning about "Cowardly refusing to send clipboard message to hung application..."
// is something that can easily happen if you are debugging and the application is paused.
// As it is so common, not worth popping up a dialog.
if ((type == QtWarningMsg) && QString(msg).contains("QClipboard::event")
&& QString(msg).contains("Cowardly refusing"))
{
type = QtDebugMsg;
}
// only the GUI thread should display message boxes. If you are
// writing a multithreaded application and the error happens on
// a non-GUI thread, you'll have to queue the message to the GUI
QCoreApplication *instance = QCoreApplication::instance();
const bool isGuiThread = instance && (QThread::currentThread() == instance->thread());
if (isGuiThread)
{
QByteArray localMsg = msg.toLocal8Bit();
QMessageBox messageBox;
switch (type)
{
case QtDebugMsg:
fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line,
context.function);
return;
case QtWarningMsg:
messageBox.setIcon(QMessageBox::Warning);
messageBox.setInformativeText(msg);
messageBox.setStandardButtons(QMessageBox::Ok);
fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line,
context.function);
messageBox.exec();
break;
case QtCriticalMsg:
messageBox.setIcon(QMessageBox::Critical);
messageBox.setInformativeText(msg);
messageBox.setStandardButtons(QMessageBox::Ok);
fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line,
context.function);
messageBox.exec();
abort();
case QtFatalMsg:
messageBox.setIcon(QMessageBox::Critical);
messageBox.setInformativeText(msg);
messageBox.setStandardButtons(QMessageBox::Ok);
fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line,
context.function);
messageBox.exec();
abort();
default:
break;
}
}
else
{
if (type != QtDebugMsg)
{
abort(); // be NOISY unless overridden!
}
}
}
#include <QTextCodec>
#include <QMessageBox>
#include <QThread>
#include <QCommandLineParser>
#include <QtXml>
#include <QLibraryInfo>
//---------------------------------------------------------------------------------------------------------------------
int main(int argc, char *argv[])
@ -130,18 +47,10 @@ int main(int argc, char *argv[])
Q_INIT_RESOURCE(schema);
Q_INIT_RESOURCE(theme);
QT_REQUIRE_VERSION(argc, argv, "5.0.2");
QT_REQUIRE_VERSION(argc, argv, "5.2.1");
VApplication app(argc, argv);
#ifdef QT_DEBUG
// Because our "noisy" message handler uses the GUI subsystem for message
// boxes, we can't install it until after the QApplication is constructed. But it
// is good to be the very next thing to run, to start catching warnings ASAP.
{
qInstallMessageHandler(noisyFailureMsgHandler);
}
#endif
app.setApplicationDisplayName(VER_PRODUCTNAME_STR);
app.setApplicationName(VER_INTERNALNAME_STR);
app.setOrganizationName(VER_COMPANYNAME_STR);
@ -152,11 +61,21 @@ int main(int argc, char *argv[])
app.OpenSettings();
#if defined(Q_OS_WIN) && defined(Q_CC_GNU)
// Catch and send report
VApplication::DrMingw();
app.CollectReports();
#endif
QString checkedLocale = qApp->getSettings()->value("configuration/locale", QLocale::system().name()).toString();
// Run creation log after sending crash report
app.StartLogging();
qDebug()<<"Version:"<<APP_VERSION;
qDebug()<<"Based on Qt "<<QT_VERSION_STR<<"(32 bit)";
qDebug()<<"Built on"<<__DATE__<<"at"<<__TIME__;
qDebug()<<"Command-line arguments:"<<app.arguments();
const QString checkedLocale = qApp->getSettings()->GetLocale();
qDebug()<<"Checked locale:"<<checkedLocale;
QTranslator qtTranslator;
#if defined(Q_OS_WIN)

View file

@ -40,6 +40,7 @@
#include "xml/vindividualmeasurements.h"
#include "core/vapplication.h"
#include "core/undoevent.h"
#include "core/vsettings.h"
#include "undocommands/renamepp.h"
#include "vtooloptionspropertybrowser.h"
#include "options.h"
@ -59,6 +60,9 @@
#include <QtGlobal>
#include <QDesktopWidget>
#include <QDesktopServices>
#include <QLoggingCategory>
Q_LOGGING_CATEGORY(vMainWindow, "v.mainwindow")
//---------------------------------------------------------------------------------------------------------------------
/**
@ -136,23 +140,30 @@ MainWindow::MainWindow(QWidget *parent)
*/
void MainWindow::ActionNewPP()
{
qCDebug(vMainWindow)<<"New PP.";
QString patternPieceName = QString(tr("Pattern piece %1")).arg(comboBoxDraws->count()+1);
qCDebug(vMainWindow)<<"Generated PP name:"<<patternPieceName;
QString path;
if (comboBoxDraws->count() == 0)
{
qCDebug(vMainWindow)<<"First PP";
DialogMeasurements measurements(this);
if (measurements.exec() == QDialog::Rejected)
{
qCDebug(vMainWindow)<<"Creation PP was canceled";
return;
}
if (measurements.type() == MeasurementsType::Standard)
{
qCDebug(vMainWindow)<<"PP with standard measurements";
qApp->setPatternType(MeasurementsType::Standard);
DialogStandardMeasurements stMeasurements(pattern, patternPieceName, this);
if (stMeasurements.exec() == QDialog::Accepted)
{
patternPieceName = stMeasurements.name();
qCDebug(vMainWindow)<<"PP name:"<<patternPieceName;
path = stMeasurements.tablePath();
qCDebug(vMainWindow)<<"Table path:"<<path;
VStandardMeasurements m(pattern);
m.setContent(path);
m.SetSize();
@ -161,11 +172,13 @@ void MainWindow::ActionNewPP()
}
else
{
qCDebug(vMainWindow)<<"Selection standard measurements canceled.";
return;
}
}
else
{
qCDebug(vMainWindow)<<"PP with individual measurements.";
QMessageBox::StandardButton ret;
ret = QMessageBox::question(this, tr("Individual measurements is under development"),
tr("There is no way create individual measurements file independent on the "
@ -182,13 +195,16 @@ void MainWindow::ActionNewPP()
if (indMeasurements.exec() == QDialog::Accepted)
{
patternPieceName = indMeasurements.name();
qCDebug(vMainWindow)<<"PP name:"<<patternPieceName;
path = indMeasurements.tablePath();
qCDebug(vMainWindow)<<"Table path:"<<path;
VIndividualMeasurements m(pattern);
m.setContent(path);
m.Measurements();
}
else
{
qCDebug(vMainWindow)<<"Selection individual measurements canceled.";
return;
}
}
@ -200,16 +216,19 @@ void MainWindow::ActionNewPP()
}
else
{
qCDebug(vMainWindow)<<"PP count"<<comboBoxDraws->count();
patternPieceName = PatternPieceName(patternPieceName);
qCDebug(vMainWindow)<<"PP name:"<<patternPieceName;
if (patternPieceName.isEmpty())
{
qCDebug(vMainWindow)<<"Name empty.";
return;
}
path = doc->MPath();
}
if (doc->appendPP(patternPieceName) == false)
{
qDebug()<<"Error creating pattern piece with the name "<<patternPieceName<<".";
qCDebug(vMainWindow)<<"Error creating pattern piece with the name "<<patternPieceName<<".";
return;
}
comboBoxDraws->blockSignals(true);
@ -795,6 +814,7 @@ void MainWindow::showEvent( QShowEvent *event )
*/
void MainWindow::closeEvent(QCloseEvent *event)
{
qCDebug(vMainWindow)<<"Closing main window";
if (MaybeSave())
{
FileClosedCorrect();
@ -804,6 +824,7 @@ void MainWindow::closeEvent(QCloseEvent *event)
}
else
{
qCDebug(vMainWindow)<<"Closing canceled.";
event->ignore();
}
}
@ -1152,6 +1173,7 @@ void MainWindow::ArrowTool()
ui->view->setCursor(cur);
helpLabel->setText("");
ui->view->setShowToolOptions(true);
qCDebug(vMainWindow)<<"Enabled arrow tool.";
}
//---------------------------------------------------------------------------------------------------------------------
@ -1217,6 +1239,7 @@ void MainWindow::ActionDraw(bool checked)
{
if (checked)
{
qCDebug(vMainWindow)<<"Show draw scene";
ui->actionDetails->setChecked(false);
SaveCurrentScene();
@ -1253,6 +1276,7 @@ void MainWindow::ActionDetails(bool checked)
{
if (checked)
{
qCDebug(vMainWindow)<<"Show details scene";
ui->actionDraw->setChecked(false);
SaveCurrentScene();
@ -1290,11 +1314,10 @@ void MainWindow::ActionDetails(bool checked)
bool MainWindow::SaveAs()
{
QString filters(tr("Pattern files (*.val)"));
QString path = qApp->getSettings()->value("paths/pattern", QDir::homePath()).toString();
QString dir;
if (curFile.isEmpty())
{
dir = path + "/" + tr("pattern") + ".val";
dir = qApp->getSettings()->GetPathPattern() + "/" + tr("pattern") + ".val";
}
else
{
@ -1311,7 +1334,19 @@ bool MainWindow::SaveAs()
{
fileName += ".val";
}
return SavePattern(fileName);
QString error;
bool result = SavePattern(fileName, error);
if (result == false)
{
QMessageBox messageBox;
messageBox.setIcon(QMessageBox::Warning);
messageBox.setInformativeText(tr("Could not save file"));
messageBox.setDefaultButton(QMessageBox::Ok);
messageBox.setDetailedText(error);
messageBox.setStandardButtons(QMessageBox::Ok);
messageBox.exec();
}
return result;
}
//---------------------------------------------------------------------------------------------------------------------
@ -1327,13 +1362,24 @@ bool MainWindow::Save()
}
else
{
bool result = SavePattern(curFile);
QString error;
bool result = SavePattern(curFile, error);
if (result)
{
QString autofile = curFile +".autosave";
QFile file(autofile);
file.remove();
}
else
{
QMessageBox messageBox;
messageBox.setIcon(QMessageBox::Warning);
messageBox.setInformativeText(tr("Could not save file"));
messageBox.setDefaultButton(QMessageBox::Ok);
messageBox.setDetailedText(error);
messageBox.setStandardButtons(QMessageBox::Ok);
messageBox.exec();
}
return result;
}
}
@ -1346,7 +1392,7 @@ void MainWindow::Open()
{
const QString filter(tr("Pattern files (*.val)"));
//Get list last open files
const QStringList files = qApp->getSettings()->value("recentFileList").toStringList();
const QStringList files = qApp->getSettings()->GetRecentFileList();
QString dir;
if (files.isEmpty())
{
@ -1357,6 +1403,7 @@ void MainWindow::Open()
//Absolute path to last open file
dir = QFileInfo(files.first()).absolutePath();
}
qCDebug(vMainWindow)<<"Run QFileDialog::getOpenFileName: dir ="<<dir<<".";
const QString filePath = QFileDialog::getOpenFileName(this, tr("Open file"), dir, filter);
OpenPattern(filePath);
}
@ -1377,6 +1424,7 @@ void MainWindow::Preferences()
//---------------------------------------------------------------------------------------------------------------------
void MainWindow::RepotBug()
{
qCDebug(vMainWindow)<<"Reporting bug";
QDesktopServices::openUrl(QUrl("https://bitbucket.org/dismine/valentina/issues/new"));
}
@ -1386,6 +1434,8 @@ void MainWindow::RepotBug()
*/
void MainWindow::Clear()
{
qCDebug(vMainWindow)<<"Reseting main window";
ui->actionDetails->setChecked(false);
ui->actionDetails->setEnabled(false);
ui->actionDraw->setChecked(true);
@ -1429,9 +1479,9 @@ void MainWindow::FileClosedCorrect()
WriteSettings();
//File was closed correct.
QStringList restoreFiles = qApp->getSettings()->value("restoreFileList").toStringList();
QStringList restoreFiles = qApp->getSettings()->GetRestoreFileList();
restoreFiles.removeAll(curFile);
qApp->getSettings()->setValue("restoreFileList", restoreFiles);
qApp->getSettings()->SetRestoreFileList(restoreFiles);
// Remove autosave file
QFile autofile(curFile +".autosave");
@ -1439,6 +1489,7 @@ void MainWindow::FileClosedCorrect()
{
autofile.remove();
}
qCDebug(vMainWindow)<<"File"<<curFile<<"closed correct.";
}
//---------------------------------------------------------------------------------------------------------------------
@ -1458,6 +1509,8 @@ void MainWindow::ResetWindow()
//---------------------------------------------------------------------------------------------------------------------
void MainWindow::FullParseFile()
{
qCDebug(vMainWindow)<<"Full parsing file";
toolOptions->ClearPropertyBrowser();
try
{
@ -1904,10 +1957,10 @@ void MainWindow::MinimumScrollBar()
* @param fileName pattern file name.
* @return true if all is good.
*/
bool MainWindow::SavePattern(const QString &fileName)
bool MainWindow::SavePattern(const QString &fileName, QString &error)
{
qCDebug(vMainWindow)<<"Saving pattern file"<<fileName<<".";
QFileInfo tempInfo(fileName);
QString error;
const bool result = doc->SaveDocument(fileName, error);
if (result)
{
@ -1915,17 +1968,12 @@ bool MainWindow::SavePattern(const QString &fileName)
{
setCurrentFile(fileName);
helpLabel->setText(tr("File saved"));
qCDebug(vMainWindow)<<"File"<<fileName<<"saved.";
}
}
else
{
QMessageBox messageBox;
messageBox.setIcon(QMessageBox::Warning);
messageBox.setInformativeText(tr("Could not save file"));
messageBox.setDefaultButton(QMessageBox::Ok);
messageBox.setDetailedText(error);
messageBox.setStandardButtons(QMessageBox::Ok);
messageBox.exec();
qCDebug(vMainWindow)<<"Could not save file"<<fileName<<"."<<error<<".";
}
return result;
}
@ -1936,13 +1984,13 @@ bool MainWindow::SavePattern(const QString &fileName)
*/
void MainWindow::AutoSavePattern()
{
qCDebug(vMainWindow)<<"Autosaving pattern.";
if (curFile.isEmpty() == false && this->isWindowModified() == true)
{
QString autofile = curFile +".autosave";
if (SavePattern(autofile) == false)
{
qDebug()<<"Can not save pattern"<<Q_FUNC_INFO;
}
QString error;
SavePattern(autofile, error);
}
}
@ -1964,7 +2012,7 @@ void MainWindow::setCurrentFile(const QString &fileName)
}
else
{
QStringList files = qApp->getSettings()->value("recentFileList").toStringList();
QStringList files = qApp->getSettings()->GetRecentFileList();
files.removeAll(fileName);
files.prepend(fileName);
while (files.size() > MaxRecentFiles)
@ -1972,13 +2020,13 @@ void MainWindow::setCurrentFile(const QString &fileName)
files.removeLast();
}
qApp->getSettings()->setValue("recentFileList", files);
qApp->getSettings()->SetRecentFileList(files);
UpdateRecentFileActions();
QStringList restoreFiles = qApp->getSettings()->value("restoreFileList").toStringList();
QStringList restoreFiles = qApp->getSettings()->GetRestoreFileList();
restoreFiles.removeAll(fileName);
restoreFiles.prepend(fileName);
qApp->getSettings()->setValue("restoreFileList", restoreFiles);
qApp->getSettings()->SetRestoreFileList(restoreFiles);
}
shownName+="[*]";
setWindowTitle(shownName);
@ -2001,22 +2049,16 @@ QString MainWindow::strippedName(const QString &fullFileName)
*/
void MainWindow::ReadSettings()
{
restoreGeometry(qApp->getSettings()->value("geometry").toByteArray());
restoreState(qApp->getSettings()->value("windowState").toByteArray());
restoreGeometry(qApp->getSettings()->GetGeometry());
restoreState(qApp->getSettings()->GetWindowState());
// Scene antialiasing
bool graphOutputValue = qApp->getSettings()->value("pattern/graphicalOutput", 1).toBool();
const bool graphOutputValue = qApp->getSettings()->GetGraphicalOutput();
ui->view->setRenderHint(QPainter::Antialiasing, graphOutputValue);
ui->view->setRenderHint(QPainter::SmoothPixmapTransform, graphOutputValue);
// Stack limit
bool ok = true;
qint32 count = qApp->getSettings()->value("pattern/undo", 0).toInt(&ok);
if (ok == false)
{
count = 0;
}
qApp->getUndoStack()->setUndoLimit(count);
qApp->getUndoStack()->setUndoLimit(qApp->getSettings()->GetUndoCount());
}
//---------------------------------------------------------------------------------------------------------------------
@ -2025,8 +2067,8 @@ void MainWindow::ReadSettings()
*/
void MainWindow::WriteSettings()
{
qApp->getSettings()->setValue("geometry", saveGeometry());
qApp->getSettings()->setValue("windowState", saveState());
qApp->getSettings()->SetGeometry(saveGeometry());
qApp->getSettings()->SetWindowState(saveState());
}
//---------------------------------------------------------------------------------------------------------------------
@ -2057,9 +2099,8 @@ bool MainWindow::MaybeSave()
//---------------------------------------------------------------------------------------------------------------------
void MainWindow::UpdateRecentFileActions()
{
QStringList files = qApp->getSettings()->value("recentFileList").toStringList();
int numRecentFiles = qMin(files.size(), static_cast<int>(MaxRecentFiles));
const QStringList files = qApp->getSettings()->GetRecentFileList();
const int numRecentFiles = qMin(files.size(), static_cast<int>(MaxRecentFiles));
for (int i = 0; i < numRecentFiles; ++i)
{
@ -2180,7 +2221,7 @@ void MainWindow::CreateActions()
//---------------------------------------------------------------------------------------------------------------------
void MainWindow::InitAutoSave()
{
//Autosaving file each 5 minutes
//Autosaving file each 1 minutes
delete autoSaveTimer;
autoSaveTimer = nullptr;
@ -2189,17 +2230,11 @@ void MainWindow::InitAutoSave()
connect(autoSaveTimer, &QTimer::timeout, this, &MainWindow::AutoSavePattern);
autoSaveTimer->stop();
bool autoSave = qApp->getSettings()->value("configuration/autosave/state", 1).toBool();
if (autoSave)
if (qApp->getSettings()->GetAutosaveState())
{
bool ok = true;
qint32 autoTime = qApp->getSettings()->value("configuration/autosave/time", 1).toInt(&ok);
if (ok == false)
{
autoTime = 5;
}
const qint32 autoTime = qApp->getSettings()->GetAutosaveTime();
autoSaveTimer->start(autoTime*60000);
qCDebug(vMainWindow)<<"Autosaving each"<<autoTime<<"minutes.";
}
qApp->setAutoSaveTimer(autoSaveTimer);
}
@ -2252,6 +2287,8 @@ MainWindow::~MainWindow()
*/
void MainWindow::LoadPattern(const QString &fileName)
{
qCDebug(vMainWindow)<<"Loading new file"<<fileName<<".";
//We have unsaved changes or load more then one file per time
OpenNewValentina(fileName);
@ -2289,6 +2326,7 @@ void MainWindow::LoadPattern(const QString &fileName)
{
QMessageBox::critical(this, tr("Wrong units."),
tr("Application doesn't support standard table with inches."));
qCDebug(vMainWindow)<<"Application doesn't support standard table with inches.";
Clear();
return;
}
@ -2324,6 +2362,7 @@ void MainWindow::LoadPattern(const QString &fileName)
PatternWasModified(!patternModified);
}
helpLabel->setText(tr("File loaded"));
qCDebug(vMainWindow)<<"File loaded.";
qApp->setOpeningPattern();// End opening file
@ -2337,9 +2376,11 @@ void MainWindow::LoadPattern(const QString &fileName)
//---------------------------------------------------------------------------------------------------------------------
void MainWindow::ReopenFilesAfterCrash(QStringList &args)
{
QStringList files = qApp->getSettings()->value("restoreFileList").toStringList();
QStringList files = qApp->getSettings()->GetRestoreFileList();
if (files.size() > 0)
{
qCDebug(vMainWindow)<<"Reopen files after crash.";
QStringList restoreFiles;
for (int i = 0; i < files.size(); ++i)
{
@ -2350,7 +2391,7 @@ void MainWindow::ReopenFilesAfterCrash(QStringList &args)
}
}
files.clear();
qApp->getSettings()->setValue("restoreFileList", files);
qApp->getSettings()->SetRestoreFileList(files);
if (restoreFiles.size() > 0)
{
@ -2361,6 +2402,8 @@ void MainWindow::ReopenFilesAfterCrash(QStringList &args)
QMessageBox::Yes);
if (reply == QMessageBox::Yes)
{
qCDebug(vMainWindow)<<"User said Yes.";
for (int i = 0; i < restoreFiles.size(); ++i)
{
QString error;
@ -2373,7 +2416,8 @@ void MainWindow::ReopenFilesAfterCrash(QStringList &args)
}
else
{
qDebug()<< "Could not copy "<<restoreFiles.at(i) +".autosave"<<"to"<<restoreFiles.at(i)<<error;
qCDebug(vMainWindow) << "Could not copy "<<restoreFiles.at(i) +".autosave"<<"to"
<<restoreFiles.at(i)<<error;
}
}
}

View file

@ -228,7 +228,7 @@ private:
void ClosedDialogWithApply(int result);
template <typename DrawTool>
void ApplyDialog();
bool SavePattern(const QString &curFile);
bool SavePattern(const QString &curFile, QString &error);
void AutoSavePattern();
void setCurrentFile(const QString &fileName);
QString strippedName(const QString &fullFileName);

View file

@ -250,7 +250,7 @@
<xs:attribute name="supplement" type="xs:unsignedInt"></xs:attribute>
<xs:attribute name="mx" type="xs:double"></xs:attribute>
<xs:attribute name="my" type="xs:double"></xs:attribute>
<xs:attribute name="width" type="xs:unsignedInt"></xs:attribute>
<xs:attribute name="width" type="xs:double"></xs:attribute>
<xs:attribute name="name" type="xs:string"></xs:attribute>
<xs:attribute name="closed" type="xs:unsignedInt"></xs:attribute>
</xs:complexType>

View file

@ -132,6 +132,7 @@ void VDrawTool::FullUpdateFromGuiApply()
//---------------------------------------------------------------------------------------------------------------------
void VDrawTool::SaveDialogChange()
{
qCDebug(vTool)<<"Saving tool options after using dialog";
QDomElement oldDomElement = doc->elementById(QString().setNum(id));
if (oldDomElement.isElement())
{
@ -144,7 +145,7 @@ void VDrawTool::SaveDialogChange()
}
else
{
qDebug()<<"Can't find tool with id ="<< id << Q_FUNC_INFO;
qCDebug(vTool)<<"Can't find tool with id ="<< id << Q_FUNC_INFO;
}
}

View file

@ -214,10 +214,13 @@ void VToolArc::setFormulaRadius(const VFormula &value)
{
if (value.error() == false)
{
QSharedPointer<VGObject> obj = VAbstractTool::data.GetGObject(id);
QSharedPointer<VArc> arc = qSharedPointerDynamicCast<VArc>(obj);
arc->SetFormulaRadius(value);
SaveOption(obj);
if (value.getDoubleValue() > 0)// Formula don't check this, but radius can't be 0 or negative
{
QSharedPointer<VGObject> obj = VAbstractTool::data.GetGObject(id);
QSharedPointer<VArc> arc = qSharedPointerDynamicCast<VArc>(obj);
arc->SetFormulaRadius(value);
SaveOption(obj);
}
}
}
@ -241,8 +244,12 @@ void VToolArc::setFormulaF1(const VFormula &value)
{
QSharedPointer<VGObject> obj = VAbstractTool::data.GetGObject(id);
QSharedPointer<VArc> arc = qSharedPointerDynamicCast<VArc>(obj);
arc->SetFormulaF1(value);
SaveOption(obj);
if (qFuzzyCompare(value.getDoubleValue() + 1, arc->GetF2() + 1)==false)// Angles can't be equal
{
arc->SetFormulaF1(value);
SaveOption(obj);
}
}
}
@ -266,8 +273,11 @@ void VToolArc::setFormulaF2(const VFormula &value)
{
QSharedPointer<VGObject> obj = VAbstractTool::data.GetGObject(id);
QSharedPointer<VArc> arc = qSharedPointerDynamicCast<VArc>(obj);
arc->SetFormulaF2(value);
SaveOption(obj);
if (qFuzzyCompare(value.getDoubleValue() + 1, arc->GetF1() + 1)==false)// Angles can't be equal
{
arc->SetFormulaF2(value);
SaveOption(obj);
}
}
}

View file

@ -241,6 +241,7 @@ int VAbstractTool::ConfirmDeletion()
//---------------------------------------------------------------------------------------------------------------------
void VAbstractTool::SaveOption(QSharedPointer<VGObject> &obj)
{
qCDebug(vTool)<<"Saving tool options";
QDomElement oldDomElement = doc->elementById(QString().setNum(id));
if (oldDomElement.isElement())
{
@ -254,7 +255,7 @@ void VAbstractTool::SaveOption(QSharedPointer<VGObject> &obj)
}
else
{
qDebug()<<"Can't find tool with id ="<< id << Q_FUNC_INFO;
qCDebug(vTool)<<"Can't find tool with id ="<< id << Q_FUNC_INFO;
}
}

View file

@ -28,6 +28,8 @@
#include "vdatatool.h"
Q_LOGGING_CATEGORY(vTool, "v.tool")
//---------------------------------------------------------------------------------------------------------------------
/**
* @brief VDataTool constructor.

View file

@ -30,6 +30,9 @@
#define VDATATOOL_H
#include "../container/vcontainer.h"
#include <QLoggingCategory>
Q_DECLARE_LOGGING_CATEGORY(vTool)
class QObject;

View file

@ -186,6 +186,8 @@ void VToolDetail::Create(DialogTool *dialog, VMainGraphicsScene *scene, VPattern
}
det.setName(detail.getName());
det.setWidth(detail.getWidth());
det.setClosed(detail.getClosed());
det.setSeamAllowance(detail.getSeamAllowance());
Create(0, det, scene, doc, data, Document::FullParse, Source::FromGui);
}

View file

@ -45,6 +45,8 @@ AddDet::~AddDet()
// cppcheck-suppress unusedFunction
void AddDet::undo()
{
qCDebug(vUndo)<<"Undo.";
QDomElement element;
if (doc->GetActivNodeElement(VPattern::TagDetails, element))
{
@ -53,19 +55,19 @@ void AddDet::undo()
{
if (element.removeChild(domElement).isNull())
{
qDebug()<<"Can't delete node";
qCDebug(vUndo)<<"Can't delete node";
return;
}
}
else
{
qDebug()<<"Can't get node by id = "<<nodeId<<Q_FUNC_INFO;
qCDebug(vUndo)<<"Can't get node by id = "<<nodeId<<".";
return;
}
}
else
{
qDebug()<<"Can't find tag"<<VPattern::TagDetails<< Q_FUNC_INFO;
qCDebug(vUndo)<<"Can't find tag"<<VPattern::TagDetails<<".";
return;
}
emit NeedFullParsing();
@ -75,6 +77,8 @@ void AddDet::undo()
// cppcheck-suppress unusedFunction
void AddDet::redo()
{
qCDebug(vUndo)<<"Redo.";
QDomElement element;
if (doc->GetActivNodeElement(VPattern::TagDetails, element))
{
@ -82,7 +86,7 @@ void AddDet::redo()
}
else
{
qDebug()<<"Can't find tag"<<VPattern::TagDetails<< Q_FUNC_INFO;
qCDebug(vUndo)<<"Can't find tag"<<VPattern::TagDetails<<".";
return;
}
RedoFullParsing();

View file

@ -44,6 +44,8 @@ AddDetNode::~AddDetNode()
//---------------------------------------------------------------------------------------------------------------------
void AddDetNode::undo()
{
qCDebug(vUndo)<<"Undo.";
QDomElement modelingElement;
if (doc->GetActivNodeElement(VPattern::TagModeling, modelingElement))
{
@ -52,19 +54,19 @@ void AddDetNode::undo()
{
if (modelingElement.removeChild(domElement).isNull())
{
qDebug()<<"Can't delete node";
qCDebug(vUndo)<<"Can't delete node.";
return;
}
}
else
{
qDebug()<<"Can't get node by id = "<<nodeId<<Q_FUNC_INFO;
qCDebug(vUndo)<<"Can't get node by id = "<<nodeId<<".";
return;
}
}
else
{
qDebug()<<"Can't find tag"<<VPattern::TagModeling<< Q_FUNC_INFO;
qCDebug(vUndo)<<"Can't find tag"<<VPattern::TagModeling<<".";
return;
}
}
@ -72,6 +74,8 @@ void AddDetNode::undo()
//---------------------------------------------------------------------------------------------------------------------
void AddDetNode::redo()
{
qCDebug(vUndo)<<"Redo.";
QDomElement modelingElement;
if (doc->GetActivNodeElement(VPattern::TagModeling, modelingElement))
{
@ -79,7 +83,7 @@ void AddDetNode::redo()
}
else
{
qDebug()<<"Can't find tag"<<VPattern::TagModeling<< Q_FUNC_INFO;
qCDebug(vUndo)<<"Can't find tag"<<VPattern::TagModeling<<".";
return;
}
}

Some files were not shown because too many files have changed in this diff Show more