--- /dev/null
+TEMPLATE = subdirs
+CONFIG += ordered
+
+SUBDIRS = src
AC_REQUIRE([CHECK_SIP])dnl
AC_REQUIRE([AC_LINKER_OPTIONS])dnl
-AC_LANG_SAVE
-AC_LANG_CPLUSPLUS
+dnl AC_LANG_SAVE
+dnl AC_LANG_CPLUSPLUS
AC_ARG_WITH(pyqt,
[ --with-pyqt=DIR root directory path to PyQt installation ],
[PYQTDIR="$withval"
- AC_MSG_RESULT("select $withval as path to PyQt")
+ AC_MSG_RESULT([Try $withval as path to the PyQt])
])
AC_ARG_WITH(pyqt_sips,
[ --with-pyqt_sips=DIR a directory path to PyQt sips installation ],
[PYQT_SIPS="$withval"
- AC_MSG_RESULT("select $withval as path to PyQt sips")
+ AC_MSG_RESULT([Try $withval as path to the PyQt sip files])
])
-
-AC_ARG_WITH(pyuic,
- [ --with-pyuic=EXEC pyuic executable ],
+AC_ARG_WITH(pyuic4,
+ [ --with-pyuic4=EXEC pyuic4 executable ],
[PYUIC="$withval"
- AC_MSG_RESULT("select $withval as pyqt executable")
+ AC_MSG_RESULT([Try $withval as pyuic4 executable])
])
AC_CHECKING(for pyqt)
-pyqt_ok=yes
-
-dnl look for pyuic
-pyqt_uic_ok=no
-if test "x$PYUIC" != x; then
- dnl try withval value
- AC_CHECK_FILE($PYUIC,pyqt_uic_ok=yes,pyqt_uic_ok=no)
-fi
-if test "x$pyqt_uic_ok" == "xno"; then
- dnl try ${PYQTDIR}
- if test "x${PYQTDIR}" != "x"; then
- if test -d ${PYQTDIR} ; then
- AC_CHECK_FILE(${PYQTDIR}/pyuic,pyqt_uic_ok=yes,pyqt_uic_ok=no)
- if test "x$pyqt_uic_ok" == "xyes"; then
- PYUIC="${PYQTDIR}/pyuic"
- fi
- fi
- fi
-fi
-if test "x$pyqt_uic_ok" == "xno"; then
- dnl try in $PATH
- AC_PATH_PROG(PYUIC, pyuic)
- if test "x$PYUIC" != x; then
- PYQTDIR=$PYUIC
- PYQTDIR=`dirname $PYQTDIR`
- PYQTDIR=`dirname $PYQTDIR`
- pyqt_uic_ok=yes
- fi
-fi
-if test "x$pyqt_uic_ok" == "xno"; then
- dnl try ${SIPDIR}
- if test "x${SIPDIR}" != "x"; then
- if test -d ${SIPDIR} ; then
- AC_CHECK_FILE(${SIPDIR}/pyuic,pyqt_uic_ok=yes,pyqt_uic_ok=no)
- if test "x$pyqt_uic_ok" == "xyes"; then
- PYUIC="${SIPDIR}/pyuic"
- fi
- fi
- fi
-fi
-if test "x$pyqt_uic_ok" == "xno"; then
- dnl try ${PYTHONHOME}/bin
- if test "x${PYTHONHOME}" != "x"; then
- if test -d ${PYTHONHOME}/bin ; then
- AC_CHECK_FILE(${PYTHONHOME}/bin/pyuic,pyqt_uic_ok=yes,pyqt_uic_ok=no)
- if test "x$pyqt_uic_ok" == "xyes"; then
- PYUIC="${PYTHONHOME}/bin/pyuic"
- fi
- fi
- fi
-fi
-if test "x$pyqt_uic_ok" == "xno"; then
- dnl try /usr/bin
- AC_CHECK_FILE(/usr/bin/pyuic,pyqt_uic_ok=yes,pyqt_uic_ok=no)
- if test "x$pyqt_uic_ok" == "xyes"; then
- PYUIC="/usr/bin/pyuic"
- fi
-fi
-if test "x$pyqt_uic_ok" == "xno"; then
- pyqt_ok=no
-fi
+pyqt_ok=no
-dnl look for PyQt libs
-pyqt_lib_ok=no
-if test "x${PYQTDIR}" != "x"; then
- dnl try {PYQTDIR}
- AC_CHECK_FILE(${PYQTDIR}/libqtcmodule.so,pyqt_lib_ok=yes,pyqt_lib_ok=no)
- if test "x$pyqt_lib_ok" == "xyes"; then
- if test "x${PYQTDIR}" = "x/usr/lib"
- then
- PYQT_LIBS="-lqtcmodule"
- else
- PYQT_LIBS="-L${PYQTDIR} -lqtcmodule"
- fi
- else
- AC_CHECK_FILE(${PYQTDIR}/qt.so,pyqt_lib_ok=yes,pyqt_lib_ok=no)
- if test "x$pyqt_lib_ok" == "xyes"; then
- if test "x${PYQTDIR}" = "x/usr/lib"
- then
- PYQT_LIBS=""
- else
- PYQT_LIBS="-L${PYQTDIR}"
- fi
+dnl check pyuic4
+if test "x$PYUIC" != "x" ; then
+ dnl try $withval value
+ AC_CHECK_FILE($PYUIC,pyqt_ok=yes,pyqt_ok=no)
+else
+ TEST_BIN_DIRS=""
+ if test "x${PYQTDIR}" != "x" ; then
+ TEST_BIN_DIRS="${TEST_BIN_DIRS} ${PYQTDIR} ${PYQTDIR}/bin"
fi
- fi
- if test "x$pyqt_lib_ok" == "xno"; then
- dnl try ${PYQTDIR}/lib
- if test -d ${PYQTDIR}/lib; then
- AC_CHECK_FILE(${PYQTDIR}/lib/libqtcmodule.so,pyqt_lib_ok=yes,pyqt_lib_ok=no)
- if test "x$pyqt_lib_ok" == "xyes"; then
- PYQT_LIBS="-L${PYQTDIR}/lib -lqtcmodule"
- else
- AC_CHECK_FILE(${PYQTDIR}/lib/qt.so,pyqt_lib_ok=yes,pyqt_lib_ok=no)
- if test "x$pyqt_lib_ok" == "xyes"; then
- PYQT_LIBS="-L${PYQTDIR}/lib"
- fi
- fi
+ TEST_BIN_DIRS="${TEST_BIN_DIRS} __CHECK__PATH__"
+ if test "x${SIPDIR}" != "x" ; then
+ TEST_BIN_DIRS="${TEST_BIN_DIRS} ${SIPDIR} ${SIPDIR}/bin"
fi
- fi
- if test "x$pyqt_lib_ok" == "xno"; then
- dnl try ${PYQTDIR}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages
- if test -d ${PYQTDIR}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages; then
- AC_CHECK_FILE(${PYQTDIR}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages/libqtcmodule.so,pyqt_lib_ok=yes,pyqt_lib_ok=no)
- if test "x$pyqt_lib_ok" == "xyes"; then
- PYQT_LIBS="-L${PYQTDIR}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages -lqtcmodule"
- else
- AC_CHECK_FILE(${PYQTDIR}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages/qt.so,pyqt_lib_ok=yes,pyqt_lib_ok=no)
- if test "x$pyqt_lib_ok" == "xyes"; then
- PYQT_LIBS="-L${PYQTDIR}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages"
- fi
- fi
+ if test "x${PYTHONHOME}" != "x" ; then
+ TEST_BIN_DIRS="${TEST_BIN_DIRS} ${PYTHONHOME}/bin"
fi
- fi
-fi
-if test "x$pyqt_lib_ok" == "xno"; then
- dnl try ${SIPDIR}
- if test "x${SIPDIR}" != "x"; then
- if test -d ${SIPDIR} ; then
- AC_CHECK_FILE(${SIPDIR}/libqtcmodule.so,pyqt_lib_ok=yes,pyqt_lib_ok=no)
- if test "x$pyqt_lib_ok" == "xyes"; then
- if test "x${SIPDIR}" = "x/usr/lib"
- then
- PYQT_LIBS="-lqtcmodule"
+ TEST_BIN_DIRS="${TEST_BIN_DIRS} /usr/bin"
+
+ dnl search pyuic4
+ pyqt_ok=no
+ for d in ${TEST_BIN_DIRS} ; do
+ if test "x${d}" = "x__CHECK__PATH__" ; then
+ AC_PATH_PROG(TEMP, pyuic4)
+ if test "x${TEMP}" != "x" ; then
+ PYUIC=${TEMP}
+ if test "x$PYQTDIR" = "x" ; then
+ PYQTDIR=`dirname ${PYUIC}`
+ PYQTDIR=`dirname ${PYQTDIR}`
+ fi
+ pyqt_ok=yes
+ break
+ fi
else
- PYQT_LIBS="-L${SIPDIR} -lqtcmodule"
- fi
- else
- AC_CHECK_FILE(${SIPDIR}/qt.so,pyqt_lib_ok=yes,pyqt_lib_ok=no)
- if test "x$pyqt_lib_ok" == "xyes"; then
- if test "x${SIPDIR}" = "x/usr/lib"
- then
- PYQT_LIBS=""
- else
- PYQT_LIBS="-L${SIPDIR}"
- fi
+ if test -d $d ; then
+ AC_CHECK_FILE(${d}/pyuic4,pyqt_ok=yes,pyqt_ok=no)
+ if test "x$pyqt_ok" == "xyes" ; then
+ PYUIC=${d}/pyuic4
+ break
+ fi
+ fi
fi
- fi
- fi
- fi
+ done
fi
-if test "x$pyqt_lib_ok" == "xno"; then
- dnl try ${PYTHONHOME}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages
- if test "x${PYTHONHOME}" != "x"; then
- if test -d ${PYTHONHOME}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages ; then
- AC_CHECK_FILE(${PYTHONHOME}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages/libqtcmodule.so,pyqt_lib_ok=yes,pyqt_lib_ok=no)
- if test "x$pyqt_lib_ok" == "xyes"; then
- PYQT_LIBS="-L${PYTHONHOME}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages -lqtcmodule"
- else
- AC_CHECK_FILE(${PYTHONHOME}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages/qt.so,pyqt_lib_ok=yes,pyqt_lib_ok=no)
- if test "x$pyqt_lib_ok" == "xyes"; then
- PYQT_LIBS="-L${PYTHONHOME}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages"
- fi
- fi
+
+dnl check PyQt version
+if test "x$pyqt_ok" == "xyes" ; then
+ AC_MSG_CHECKING(whether PyQt version >= 4.2)
+ PYQT_VERSION=`${PYUIC} --version 2>&1 | grep "Python User Interface Compiler"`
+ if test "$?" != "0" ; then
+ PYQT_VERSION=`${PYUIC} -version 2>&1 | grep "Python User Interface Compiler"`
fi
- fi
-fi
-if test "x$pyqt_lib_ok" == "xno"; then
- dnl try /usr/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages
- AC_CHECK_FILE(/usr/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages/libqtcmodule.so,pyqt_lib_ok=yes,pyqt_lib_ok=no)
- if test "x$pyqt_lib_ok" == "xyes"; then
- PYQT_LIBS="-L/usr/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages -lqtcmodule"
- else
- AC_CHECK_FILE(/usr/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages/qt.so,pyqt_lib_ok=yes,pyqt_lib_ok=no)
- if test "x$pyqt_lib_ok" == "xyes"; then
- PYQT_LIBS="-L/usr/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages"
+ if test "x${PYQT_VERSION}" != "x" ; then
+ PYQT_VERSION=`echo $PYQT_VERSION | sed -e 's%[[[:alpha:][:space:]]]*\([[[:digit:].]]*\).*%\1%g'`
+ PYQT_VERSION_ID=`echo $PYQT_VERSION | awk -F. '{v=$[1]*10000+$[2]*100+$[3];print v}'`
+ else
+ PYQT_VERSION="<unknown>"
+ PYQT_VERSION_ID=0
fi
- fi
-fi
-if test "x$pyqt_lib_ok" == "xno"; then
- pyqt_ok=no
+ if test $PYQT_VERSION_ID -ge 40200 ; then
+ AC_MSG_RESULT(yes)
+ AC_MSG_RESULT(PyQt version is $PYQT_VERSION)
+ else
+ AC_MSG_RESULT(no)
+ AC_MSG_RESULT(WARNING! PyQt version $PYQT_VERSION is not supported (at least 4.2 is required)!)
+ pyqt_ok=no
+ fi
+else
+ AC_MSG_RESULT(Warning! pyuic4 is not found!)
fi
-dnl look for PyQt sips
-pyqt_sips_ok=no
-dnl try ${PYQT_SIPS} or ${PYQT_SIPS}/qt
-if test "x${PYQT_SIPS}" != "x"; then
- AC_CHECK_FILE(${PYQT_SIPS}/qglobal.sip,pyqt_sips_ok=yes,pyqt_sips_ok=no)
- if test "x$pyqt_sips_ok" == "xno"; then
- AC_CHECK_FILE(${PYQT_SIPS}/qt/qglobal.sip,pyqt_sips_ok=yes,pyqt_sips_ok=no)
- if test "x$pyqt_sips_ok" == "xyes"; then
- PYQT_SIPS="${PYQT_SIPS}/qt"
+if test "x$pyqt_ok" == "xyes" ; then
+ TESTLIBFILE=QtCore.so
+ TESTSIPFILE=QtCore/QtCoremod.sip
+ TEST_LIB_DIRS=""
+ TEST_SIPS_DIRS=""
+ if test "x${PYQT_SIPS}" != "x" ; then
+ TEST_SIPS_DIRS="${TEST_SIPS_DIRS} ${PYQT_SIPS}"
fi
- fi
-fi
-if test "x$pyqt_sips_ok" == "xno"; then
- dnl try ${PYQTDIR}/sip
- if test "x${PYQTDIR}" != "x"; then
- if test -d ${PYQTDIR}/sip ; then
- AC_CHECK_FILE(${PYQTDIR}/sip/qglobal.sip,pyqt_sips_ok=yes,pyqt_sips_ok=no)
- if test "x$pyqt_sips_ok" == "xyes"; then
- PYQT_SIPS="${PYQTDIR}/sip"
- else
- AC_CHECK_FILE(${PYQTDIR}/sip/qt/qglobal.sip,pyqt_sips_ok=yes,pyqt_sips_ok=no)
- if test "x$pyqt_sips_ok" == "xyes"; then
- PYQT_SIPS="${PYQTDIR}/sip/qt"
- fi
- fi
+ if test "x${PYQTDIR}" != "x" ; then
+ TEST_LIB_DIRS="${TEST_LIB_DIRS} ${PYQTDIR} ${PYQTDIR}/lib ${PYQTDIR}/PyQt4"
+ TEST_LIB_DIRS="${TEST_LIB_DIRS} ${PYQTDIR}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages"
+ TEST_LIB_DIRS="${TEST_LIB_DIRS} ${PYQTDIR}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages/PyQt4"
+ TEST_SIPS_DIRS="${TEST_SIPS_DIRS} ${PYQTDIR} ${PYQTDIR}/sip"
+ TEST_SIPS_DIRS="${TEST_SIPS_DIRS} ${PYQTDIR}/share ${PYQTDIR}/share/sip"
fi
- fi
-fi
-if test "x$pyqt_sips_ok" == "xno"; then
- dnl try ${PYQTDIR}/share/sip/qt
- if test "x${PYQTDIR}" != "x"; then
- if test -d ${PYQTDIR}/share/sip/qt ; then
- AC_CHECK_FILE(${PYQTDIR}/share/sip/qt/qglobal.sip,pyqt_sips_ok=yes,pyqt_sips_ok=no)
- if test "x$pyqt_sips_ok" == "xyes"; then
- PYQT_SIPS="${PYQTDIR}/share/sip/qt"
- fi
+ if test "x${SIPDIR}" != "x" ; then
+ TEST_LIB_DIRS="${TEST_LIB_DIRS} ${SIPDIR} ${SIPDIR}/lib ${SIPDIR}/PyQt4"
+ TEST_LIB_DIRS="${TEST_LIB_DIRS} ${SIPDIR}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages"
+ TEST_LIB_DIRS="${TEST_LIB_DIRS} ${SIPDIR}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages/PyQt4"
+ TEST_SIPS_DIRS="${TEST_SIPS_DIRS} ${SIPDIR} ${SIPDIR}/sip"
+ TEST_SIPS_DIRS="${TEST_SIPS_DIRS} ${SIPDIR}/share ${SIPDIR}/share/sip"
fi
- fi
-fi
-if test "x$pyqt_sips_ok" == "xno"; then
- dnl try ${SIPDIR}/sip
- if test "x${SIPDIR}" != "x"; then
- if test -d ${SIPDIR}/sip ; then
- AC_CHECK_FILE(${SIPDIR}/sip/qglobal.sip,pyqt_sips_ok=yes,pyqt_sips_ok=no)
- if test "x$pyqt_sips_ok" == "xyes"; then
- PYQT_SIPS="${SIPDIR}/sip"
- else
- AC_CHECK_FILE(${SIPDIR}/sip/qt/qglobal.sip,pyqt_sips_ok=yes,pyqt_sips_ok=no)
- if test "x$pyqt_sips_ok" == "xyes"; then
- PYQT_SIPS="${SIPDIR}/sip/qt"
- fi
- fi
+ if test "x${PYTHONHOME}" != "x" ; then
+ TEST_LIB_DIRS="${TEST_LIB_DIRS} ${PYTHONHOME}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages"
+ TEST_LIB_DIRS="${TEST_LIB_DIRS} ${PYTHONHOME}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages/PyQt4"
fi
- fi
-fi
-if test "x$pyqt_sips_ok" == "xno"; then
- dnl try /usr/share/sip
- if test -d /usr/share/sip ; then
- AC_CHECK_FILE(/usr/share/sip/qglobal.sip,pyqt_sips_ok=yes,pyqt_sips_ok=no)
- if test "x$pyqt_sips_ok" == "xyes"; then
- PYQT_SIPS="/usr/share/sip"
- else
- AC_CHECK_FILE(/usr/share/sip/qt/qglobal.sip,pyqt_sips_ok=yes,pyqt_sips_ok=no)
- if test "x$pyqt_sips_ok" == "xyes"; then
- PYQT_SIPS="/usr/share/sip/qt"
- fi
+ TEST_LIB_DIRS="${TEST_LIB_DIRS} /usr/lib${LIB_LOCATION_SUFFIX} /usr/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages"
+ TEST_LIB_DIRS="${TEST_LIB_DIRS} /usr/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages/PyQt4"
+ TEST_SIPS_DIRS="${TEST_SIPS_DIRS} /usr/share/sip"
+
+ dnl check PyQt libs
+ pyqt_ok=no
+ for d in ${TEST_LIB_DIRS} ; do
+ if test -d $d ; then
+ AC_CHECK_FILE(${d}/${TESTLIBFILE},pyqt_ok=yes,pyqt_ok=no)
+ if test "x$pyqt_ok" == "xyes" ; then
+ if test "x${d}" = "x/usr/lib${LIB_LOCATION_SUFFIX}" ; then
+ PYQT_LIBS=""
+ else
+ PYQT_LIBS="-L${d}"
+ fi
+ break
+ fi
+ fi
+ done
+
+ dnl check PyQt sips
+ if test "x$pyqt_ok" == "xyes" ; then
+ pyqt_ok=no
+ for d in ${TEST_SIPS_DIRS} ; do
+ if test -d $d ; then
+ AC_CHECK_FILE(${d}/${TESTSIPFILE},pyqt_ok=yes,pyqt_ok=no)
+ if test "x$pyqt_ok" == "xyes" ; then
+ PYQT_SIPS=${d}
+ PYQT_INCLUDES="-I ${d}"
+ PYQT_INCLUDES="${PYQT_INCLUDES} -I ${d}/QtCore -I ${d}/QtGui"
+ PYQT_INCLUDES="${PYQT_INCLUDES} -I ${d}/QtXml -I ${d}/QtOpenGL"
+ PYQT_INCLUDES="${PYQT_INCLUDES} -I ${d}/QtAssistant -I ${d}/QtDesigner"
+ PYQT_INCLUDES="${PYQT_INCLUDES} -I ${d}/QtNetwork -I ${d}/QtSql"
+ PYQT_INCLUDES="${PYQT_INCLUDES} -I ${d}/QtSvg -I ${d}/QtTest"
+
+ # check compatibility with Qt
+ SUPPORTED=`grep -e "[[[:space:]]]*Qt_[[[:digit:]_]]\+}" ${PYQT_SIPS}/QtCore/QtCoremod.sip | sed -e "s/\(.*\)[[[:space:]]]*\(Qt_[[[:digit:]_]]\+\)}/\2/g"`
+ SUPPORTED=`echo $SUPPORTED | sed -e "s/Qt_//g" -e "s/_/./g"`
+ SUPPORTED_ID=`echo $SUPPORTED | awk -F. '{v=$[1]*10000+$[2]*100+$[3];print v}'`
+ if test $SUPPORTED_ID -lt $QT_VERSION_ID ; then
+ AC_MSG_RESULT(Warning! Used Qt version ($QT_VERSION) is not supported by PyQt)
+ AC_MSG_RESULT(Latest supported Qt version is ${SUPPORTED})
+ else
+ SUPPORTED=${QT_VERSION}
+ fi
+ SUPPORTED="Qt_`echo ${SUPPORTED} | sed -e 's/\./_/g'`"
+ PYQT_SIPFLAGS="-x VendorID -x PyQt_NoPrintRangeBug -t WS_X11 -t ${SUPPORTED} -g -s ".cc" -c . ${PYQT_INCLUDES}"
+ break
+ fi
+ fi
+ done
fi
- fi
-fi
-if test "x$pyqt_sips_ok" == "xno"; then
- pyqt_ok=no
-else
- PYQT_INCLUDES="-I$PYQT_SIPS"
-
- dnl Additional sip flags required for correct wrappers compilation
- AC_MSG_CHECKING(which qt classes should be excluded)
-
- PYQT_SIPFLAGS=""
-
- CXXFLAGS_old=$CXXFLAGS
- CXXFLAGS="$CXXFLAGS $QT_INCLUDES"
- LIBS_old=$LIBS
- LIBS="$LIBS $QT_LIBS"
-
- AC_TRY_COMPILE([#include <qcdestyle.h>],
- [new QCDEStyle();],,PYQT_SIPFLAGS="$PYQT_SIPFLAGS -x Qt_STYLE_CDE")
- AC_TRY_COMPILE([#include <qinterlacestyle.h>],
- [new QInterlaceStyle();],,PYQT_SIPFLAGS="$PYQT_SIPFLAGS -x Qt_STYLE_INTERLACE")
- AC_TRY_COMPILE([#include <qmotifstyle.h>],
- [new QMotifStyle();],,PYQT_SIPFLAGS="$PYQT_SIPFLAGS -x Qt_STYLE_MOTIF")
- AC_TRY_COMPILE([#include <qmotifplusstyle.h>],
- [new QMotifPlusStyle();],,PYQT_SIPFLAGS="$PYQT_SIPFLAGS -x Qt_STYLE_MOTIFPLUS")
- AC_TRY_COMPILE([#include <qplatinumstyle.h>],
- [new QPlatinumStyle();],,PYQT_SIPFLAGS="$PYQT_SIPFLAGS -x Qt_STYLE_PLATINUM")
- AC_TRY_COMPILE([#include <qsgistyle.h>],
- [new QSGIStyle();],,PYQT_SIPFLAGS="$PYQT_SIPFLAGS -x Qt_STYLE_SGI")
- AC_TRY_COMPILE([#include <qwindowsstyle.h>],
- [new QWindowsStyle();],,PYQT_SIPFLAGS="$PYQT_SIPFLAGS -x Qt_STYLE_WINDOWS")
- AC_TRY_COMPILE([#include <qwindowsxpstyle.h>],
- [new QWindowsXPStyle();],,PYQT_SIPFLAGS="$PYQT_SIPFLAGS -x Qt_STYLE_WINDOWSXP")
-
- LIBS="$LIBS -lqassistantclient"
- AC_TRY_LINK([#include <qassistantclient.h>],
- [new QAssistantClient("foo");],,PYQT_SIPFLAGS="$PYQT_SIPFLAGS -x Qt_ASSISTANTCLIENT")
-
- AC_MSG_RESULT(done)
-
- CXXFLAGS=$CXXFLAGS_old
- LIBS=$LIBS_old
fi
-# get latest Qt version supported
-QT_VERS=`grep -e "[[[:space:]]]*Qt_[[[:digit:]_]]\+}" ${PYQT_SIPS}/versions.sip | sed -e "s/\(.*\)[[[:space:]]]*\(Qt_[[[:digit:]_]]\+\)}/\2/g"`
-AC_MSG_RESULT(Latest Qt version supported by PyQt is $QT_VERS)
AC_SUBST(PYQT_INCLUDES)
AC_SUBST(PYQT_LIBS)
AC_SUBST(PYQT_SIPS)
AC_SUBST(PYUIC)
AC_SUBST(PYQT_SIPFLAGS)
-AC_SUBST(QT_VERS)
-AC_LANG_RESTORE
+dnl AC_LANG_RESTORE
AC_MSG_RESULT(for pyqt: $pyqt_ok)
AC_LANG_SAVE
AC_LANG_CPLUSPLUS
+#
+# check QTDIR environment variable
+#
if test "x$QTDIR" = "x"
then
AC_MSG_RESULT(please define QTDIR variable)
qt_ok=no
else
AC_MSG_RESULT(QTDIR is $QTDIR)
+fi
+
+#
+# check Qt version
+#
+if test "x$qt_ok" = "xyes"
+then
qt_inc_ok=no
QTINC=""
- AC_CHECK_FILE(${QTDIR}/include/qt3/qglobal.h,QTINC="/qt3",QTINC="")
- QT_VERSION=`grep "QT_VERSION_STR" ${QTDIR}/include${QTINC}/qglobal.h | sed -e 's%^#define QT_VERSION_STR\([[:space:]]*\)%%g' -e 's%\"%%g'`
- AC_MSG_RESULT(Qt version is $QT_VERSION)
+ AC_CHECK_FILE(${QTDIR}/include/qt4/QtCore/qglobal.h,QTINC="/qt4",QTINC="")
+ if test "x$QTINC" = "x"
+ then
+ AC_CHECK_FILE(${QTDIR}/include${QTINC}/QtCore/qglobal.h,qt_inc_ok=yes,qt_inc_ok=no)
+ else
+ qt_inc_ok=yes
+ fi
+ if test "x$qt_inc_ok" = "xyes"
+ then
+ AC_MSG_CHECKING(whether Qt version >= 4.0)
+ QT_VERSION=`grep "QT_VERSION_STR" ${QTDIR}/include${QTINC}/QtCore/qglobal.h | sed -e 's%^#define QT_VERSION_STR[[:space:]]*\"\([[:digit:]\.]*\)\"%\1%g'`
+ QT_VERSION_ID=`echo $QT_VERSION | awk -F. '{v=$[1]*10000+$[2]*100+$[3];print v}'`
+ if test $QT_VERSION_ID -ge 40000
+ then
+ AC_MSG_RESULT(yes)
+ else
+ AC_MSG_RESULT(no)
+ qt_ok=no
+ fi
+ AC_MSG_CHECKING(Qt version)
+ AC_MSG_RESULT($QT_VERSION)
+ else
+ qt_ok=no
+ fi
fi
+#
+# check moc presence (meta-object compiler)
+#
if test "x$qt_ok" = "xyes"
then
if test -f ${QTDIR}/bin/moc
if test "x$MOC" = "x"
then
qt_ok=no
- AC_MSG_RESULT(moc qt-compiler not in PATH variable)
+ AC_MSG_RESULT(moc (Qt meta-object compiler) is not in the PATH variable)
else
qt_ok=yes
- AC_MSG_RESULT(moc found)
+ AC_MSG_RESULT(moc (Qt meta-object compiler) is found)
fi
fi
+#
+# check uic presence (user interface compiler)
+#
if test "x$qt_ok" = "xyes"
then
if test -f ${QTDIR}/bin/uic
if test "x$UIC" = "x"
then
qt_ok=no
- AC_MSG_RESULT(uic qt-interface compiler not in PATH variable)
+ AC_MSG_RESULT(uic (Qt user interface compiler) is not in the PATH variable)
else
qt_ok=yes
- AC_MSG_RESULT(uic found)
+ AC_MSG_RESULT(uic (Qt user interface compiler) is found)
fi
fi
-AC_SUBST(QTDIR)
-QT_ROOT=$QTDIR
+#
+# check rcc presence (resources compiler)
+#
+if test "x$qt_ok" = "xyes"
+then
+ if test -f ${QTDIR}/bin/rcc
+ then
+ QRCC=${QTDIR}/bin/rcc
+ else
+ AC_PATH_PROG(QRCC, rcc)
+ fi
+ if test "x$QRCC" = "x"
+ then
+ qt_ok=no
+ AC_MSG_RESULT(rcc (Qt resources compiler) is not in the PATH variable)
+ else
+ qt_ok=yes
+ AC_MSG_RESULT(rcc (Qt resources compiler) is found)
+ fi
+fi
+#
+# check lrelease presence (translation files compiler)
+#
if test "x$qt_ok" = "xyes"
then
- CPPFLAGS_old=$CPPFLAGS
- CPPFLAGS="$CPPFLAGS -I$QTDIR/include${QTINC}"
+ if test -f ${QTDIR}/bin/lrelease
+ then
+ LRELEASE=${QTDIR}/bin/lrelease
+ else
+ AC_PATH_PROG(LRELEASE, lrelease)
+ fi
+ if test "x$LRELEASE" = "x"
+ then
+ qt_ok=no
+ AC_MSG_RESULT(lrelease (Qt translation files compiler) is not in the PATH variable)
+ else
+ qt_ok=yes
+ AC_MSG_RESULT(lrelease (Qt translation files compiler) is found)
+ fi
+fi
- AC_LANG_CPLUSPLUS
- AC_CHECK_HEADER(qaction.h,qt_ok=yes ,qt_ok=no)
+QT_ROOT=$QTDIR
- CPPFLAGS=$CPPFLAGS_old
+#
+# check Qt header files
+#
+if test "x$qt_ok" = "xyes"
+then
+ AC_CHECKING(include Qt header files)
- AC_MSG_CHECKING(include of qt headers)
+ CPPFLAGS_old=$CPPFLAGS
+ CPPFLAGS="$CPPFLAGS -I${QTDIR}/include${QTINC} -I${QTDIR}/include${QTINC}/QtCore"
+ AC_CHECK_HEADER(QObject,qt_ok=yes,qt_ok=no)
+ CPPFLAGS=$CPPFLAGS_old
if test "x$qt_ok" = "xno"
then
- AC_MSG_RESULT(qt headers not found, or too old qt version, in $QTDIR/include)
- AC_MSG_RESULT(QTDIR environment variable may be wrong)
+ AC_MSG_RESULT(qt header files are not found in $QTDIR/include${QTINC}/QtCore)
+ AC_MSG_RESULT(QTDIR environment variable may be wrong (probably too old Qt version))
else
- AC_MSG_RESULT(yes)
- QT_INCLUDES="-I${QT_ROOT}/include${QTINC} -DQT_THREAD_SUPPORT -DQT_CLEAN_NAMESPACE"
- QT_MT_INCLUDES="-I${QT_ROOT}/include${QTINC} -DQT_THREAD_SUPPORT -DQT_CLEAN_NAMESPACE"
+ AC_MSG_RESULT(qt header files seem to be OK)
+ QT_INCLUDES="-I${QTDIR}/include${QTINC}"
+ # user header files
+ QT_INCLUDES="${QT_INCLUDES} -I${QTDIR}/include${QTINC}/QtCore"
+ QT_INCLUDES="${QT_INCLUDES} -I${QTDIR}/include${QTINC}/QtGui"
+ QT_INCLUDES="${QT_INCLUDES} -I${QTDIR}/include${QTINC}/QtOpenGL"
+ QT_INCLUDES="${QT_INCLUDES} -I${QTDIR}/include${QTINC}/QtXml"
+ # not used currently header files (uncomment if required)
+ #QT_INCLUDES="${QT_INCLUDES} -I$(QTDIR)/include${QTINC}/QtAssistant"
+ #QT_INCLUDES="${QT_INCLUDES} -I$(QTDIR)/include${QTINC}/QtDBus"
+ #QT_INCLUDES="${QT_INCLUDES} -I$(QTDIR)/include${QTINC}/QtDesigner"
+ #QT_INCLUDES="${QT_INCLUDES} -I$(QTDIR)/include${QTINC}/QtNetwork"
+ #QT_INCLUDES="${QT_INCLUDES} -I$(QTDIR)/include${QTINC}/QtSql"
+ #QT_INCLUDES="${QT_INCLUDES} -I$(QTDIR)/include${QTINC}/QtSvg"
+ #QT_INCLUDES="${QT_INCLUDES} -I$(QTDIR)/include${QTINC}/QtTest"
+ #QT_INCLUDES="${QT_INCLUDES} -I$(QTDIR)/include${QTINC}/QtUiTools"
+
+ # this flag is obsolete with Qt 4
+ QT_MT_INCLUDES="$QT_INCLUDES"
fi
fi
+#
+# test Qt libraries
+#
if test "x$qt_ok" = "xyes"
then
- AC_MSG_CHECKING(linking qt library)
+ AC_MSG_CHECKING(linking against Qt library)
+
+ CXXFLAGS_old=$CXXFLAGS
+ CXXFLAGS="$CXXFLAGS $QT_INCLUDES"
+
LIBS_old=$LIBS
if test "x$QTDIR" = "x/usr"
then
- LIBS="$LIBS -lqt-mt $OGL_LIBS"
+ QT_LIB_DIR=""
else
- LIBS="$LIBS -L$QTDIR/lib${LIB_LOCATION_SUFFIX} -lqt-mt $OGL_LIBS"
+ QT_LIB_DIR="-L$QTDIR/lib${LIB_LOCATION_SUFFIX}"
fi
-
- CXXFLAGS_old=$CXXFLAGS
- CXXFLAGS="$CXXFLAGS $QT_INCLUDES"
+ LIBS="$LIBS $QT_LIB_DIR -lQtCore"
AC_CACHE_VAL(salome_cv_lib_qt,[
AC_TRY_LINK(
-#include <qapplication.h>
+#include <QCoreApplication>
, int n;
char **s;
- QApplication a(n, s);
+ QCoreApplication a(n, s);
a.exec();,
eval "salome_cv_lib_qt=yes",eval "salome_cv_lib_qt=no")
])
qt_ok="$salome_cv_lib_qt"
+ # BEGIN: for CCRT (installation of qt have only a "lib" directory)
+ if test "x$qt_ok" = "xno"
+ then
+ QT_LIB_DIR="-L$QTDIR/lib"
+ LIBS="$LIBS_old $QT_LIB_DIR -lQtCore"
+
+ AC_CACHE_VAL(salome_cv_lib_qt,[
+ AC_TRY_LINK(
+#include <QCoreApplication>
+, int n;
+ char **s;
+ QCoreApplication a(n, s);
+ a.exec();,
+ eval "salome_cv_lib_qt=yes",eval "salome_cv_lib_qt=no")
+ ])
+ qt_ok="$salome_cv_lib_qt"
+ fi
+ # END: for CCRT
+
if test "x$qt_ok" = "xno"
then
+ AC_MSG_RESULT(no)
AC_MSG_RESULT(unable to link with qt library)
- AC_MSG_RESULT(QTDIR environment variable may be wrong)
+ AC_MSG_RESULT(QTDIR environment variable may be wrong (probably too old Qt version))
else
AC_MSG_RESULT(yes)
- if test "x$QTDIR" = "x/usr"
- then
- QT_LIBS=" -lqt-mt"
- QT_MT_LIBS=" -lqt-mt"
- else
- QT_LIBS="-L$QTDIR/lib${LIB_LOCATION_SUFFIX} -lqt-mt"
- QT_MT_LIBS="-L$QTDIR/lib${LIB_LOCATION_SUFFIX} -lqt-mt"
- fi
+ # core libs
+ QT_CORE_LIBS="$QT_LIB_DIR -lQtCore -lQtXml"
+ # gui libs
+ QT_GUI_LIBS="$QT_LIB_DIR -lQtGui -lQtOpenGL"
+ # other libs (currently not used)
+ QT_OTHER_LIBS="$QT_LIB_DIR"
+ # other libs (can be used if necessary)
+ #QT_OTHER_LIBS="$QT_LIB_DIR -lQt3Support -lQtAssistantClient -lQtDesigner -lQtNetwork -lQtSql -lQtSvg -lQtTest -ltQtUiTools"
+ # all libs
+ QT_LIBS="$QT_CORE_LIBS $QT_GUI_LIBS $QT_OTHER_LIBS"
+ # this flag is obsolete with Qt 4
+ QT_MT_LIBS="$QT_LIBS"
fi
-
LIBS=$LIBS_old
CXXFLAGS=$CXXFLAGS_old
-
fi
+AC_SUBST(QTDIR)
AC_SUBST(MOC)
AC_SUBST(UIC)
+AC_SUBST(QRCC)
+AC_SUBST(LRELEASE)
AC_SUBST(QT_ROOT)
AC_SUBST(QT_INCLUDES)
AC_SUBST(QT_MT_INCLUDES)
+AC_SUBST(QT_LIB_DIR)
+AC_SUBST(QT_CORE_LIBS)
+AC_SUBST(QT_GUI_LIBS)
+AC_SUBST(QT_OTHER_LIBS)
AC_SUBST(QT_LIBS)
AC_SUBST(QT_MT_LIBS)
AC_SUBST(QT_VERSION)
+AC_SUBST(QT_VERSION_ID)
AC_LANG_RESTORE
qwt_ok=yes
fi
+#
+# test Qwt libraries
+#
if test "x$qwt_ok" = "xyes"
then
AC_MSG_CHECKING(linking qwt library)
LIBS_old=$LIBS
if test "x$QTDIR" = "x/usr"
then
- LIBS="$LIBS -lqt-mt"
+ QT_LIB_DIR=""
else
- LIBS="$LIBS -L$QTDIR/lib${LIB_LOCATION_SUFFIX} -lqt-mt"
+ QT_LIB_DIR="-L$QTDIR/lib${LIB_LOCATION_SUFFIX}"
fi
+ LIBS="$LIBS $QT_LIB_DIR -lQtCore -lQtGui"
+
if test "x$QWTHOME" = "x/usr"
then
LIBS="$LIBS -lqwt"
AC_CACHE_VAL(salome_cv_lib_qwt,[
AC_TRY_LINK(
-#include <qapplication.h>
+#include <QApplication>
#include <qwt_plot.h>
, int n;
char **s;
QApplication a(n, s);
- QwtPlot* p;
- a.setMainWidget(p);
+ QwtPlot p;
+ p.resize( 600, 400 );
+ p.show();
a.exec();,
eval "salome_cv_lib_qwt=yes",eval "salome_cv_lib_qwt=no")
])
AC_ARG_WITH(sip,
[ --with-sip=EXEC sip executable ],
[SIP="$withval"
- AC_MSG_RESULT("select $withval as sip executable")
+ AC_MSG_RESULT([Try $withval as sip executable])
], [
AC_PATH_PROG(SIP, sip)
])
if test "x$SIP" = "x" ; then
sip_ok=no
- AC_MSG_RESULT(sip not in PATH variable)
+ AC_MSG_RESULT(sip is not in the PATH variable)
else
- version=`$SIP -V`
- AC_MSG_RESULT(sip version is $version)
- case "$version" in
- 3.2*)
- SIP_VERS=v3_old ;;
- 3.3*)
- SIP_VERS=v3_old ;;
- 3.4*)
- SIP_VERS=v3_old ;;
- 3.5*)
- SIP_VERS=v3_old ;;
- 3.6*)
- SIP_VERS=v3_old ;;
- 3.7*)
- SIP_VERS=v3_old ;;
- 3.8*)
- SIP_VERS=v3_old ;;
- 3.9*)
- SIP_VERS=v3_old ;;
- 3.10*)
- SIP_VERS=v3_new ;;
- 4.1*)
- SIP_VERS=v4_old ;;
- 4.2*)
- SIP_VERS=v4_new ;;
- 4.3*)
- SIP_VERS=v4_new ;;
- 4.4*)
- SIP_VERS=v4_new ;;
- 4.5*)
- SIP_VERS=v4_new ;;
- *)
- AC_MSG_RESULT(sip version $version not supported)
- SIP_VERS=unsupported ;;
- esac
+ AC_MSG_CHECKING(whether sip version >= 4.6)
+ SIP_VERSION=`$SIP -V | awk '{print $[1]}'`
+ SIP_VERSION_ID=`echo $SIP_VERSION | awk -F. '{v=$[1]*10000+$[2]*100+$[3];print v}'`
+ if test $SIP_VERSION_ID -ge 40600 ; then
+ AC_MSG_RESULT(yes)
+ AC_MSG_RESULT(sip version is $SIP_VERSION)
+ else
+ AC_MSG_RESULT(no)
+ AC_MSG_RESULT(WARNING! sip version $SIP_VERSION is not supported (at least 4.6 is required)!)
+ sip_ok=no
+ fi
+fi
+if test "x$sip_ok" = "xyes" ; then
if test "x$SIPDIR" = "x" ; then
SIPDIR=`dirname $SIP`
SIPDIR=`dirname $SIPDIR`
fi
- sip_ok=no
- dnl Search sip.h file
- if test "x$SIPDIR" != "x" ; then
- dnl look for sip.h in ${SIPDIR}
- AC_CHECK_FILE(${SIPDIR}/sip.h,sip_ok=yes,sip_ok=no)
- if test "x$sip_ok" == "xyes" ; then
- SIP_INCLUDES="-I${SIPDIR}"
- fi
- if test "x$sip_ok" == "xno" ; then
- dnl look for sip.h in ${SIPDIR}/include/python${PYTHON_VERSION}
- if test -d ${SIPDIR}/include/python${PYTHON_VERSION} ; then
- AC_CHECK_FILE(${SIPDIR}/include/python${PYTHON_VERSION}/sip.h,sip_ok=yes,sip_ok=no)
- if test "x$sip_ok" == "xyes" ; then
- SIP_INCLUDES="-I${SIPDIR}/include/python${PYTHON_VERSION}"
- fi
- fi
- fi
+ TEST_INC_DIRS=""
+ TEST_LIB_DIRS=""
+ if test "x${SIPDIR}" != "x" ; then
+ TEST_INC_DIRS="${TEST_INC_DIRS} ${SIPDIR} ${SIPDIR}/include"
+ TEST_INC_DIRS="${TEST_INC_DIRS} ${SIPDIR}/include/python${PYTHON_VERSION}"
+ TEST_LIB_DIRS="${TEST_LIB_DIRS} ${SIPDIR} ${SIPDIR}/lib"
+ TEST_LIB_DIRS="${TEST_LIB_DIRS} ${SIPDIR}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages"
fi
- if test "x$sip_ok" == "xno" ; then
- dnl look for sip.h in ${PYTHON_PREFIX}/include/python${PYTHON_VERSION}
- if test -d ${PYTHON_PREFIX}/include/python${PYTHON_VERSION} ; then
- AC_CHECK_FILE(${PYTHON_PREFIX}/include/python${PYTHON_VERSION}/sip.h,sip_ok=yes,sip_ok=no)
- if test "x$sip_ok" == "xyes" ; then
- SIP_INCLUDES="${PYTHON_INCLUDES}"
- fi
- fi
+ if test "x${PYTHONHOME}" != "x" ; then
+ TEST_INC_DIRS="${TEST_INC_DIRS} ${PYTHONHOME}/include/python${PYTHON_VERSION}"
+ TEST_LIB_DIRS="${TEST_LIB_DIRS} ${PYTHONHOME}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages"
fi
- if test "x$sip_ok" == "xno" ; then
- dnl look for sip.h in /usr/include/python${PYTHON_VERSION}
- if test -d /usr/include/python${PYTHON_VERSION} ; then
- AC_CHECK_FILE(/usr/include/python${PYTHON_VERSION}/sip.h,sip_ok=yes,sip_ok=no)
- if test "x$sip_ok" == "xyes" ; then
- SIP_INCLUDES="/usr/include/python${PYTHON_VERSION}"
- fi
- fi
- fi
-
- dnl Search (lib)sip.so file
- sip_lib_ok=no
- if test "x$SIPDIR" != "x" ; then
- dnl look for (lib)sip.so in ${SIPDIR}
- AC_CHECK_FILE(${SIPDIR}/libsip.so,sip_lib_ok=yes,sip_lib_ok=no)
- if test "x$sip_lib_ok" == "xyes" ; then
- if test "x${SIPDIR}" = "x/usr/lib"
- then
- SIP_LIBS="-lsip"
- else
- SIP_LIBS="-L${SIPDIR} -lsip"
+ TEST_INC_DIRS="${TEST_INC_DIRS} /usr/include /usr/include/python${PYTHON_VERSION}"
+ TEST_LIB_DIRS="${TEST_LIB_DIRS} /usr/lib${LIB_LOCATION_SUFFIX} /usr/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages"
+
+ dnl Search sip.h file
+ sip_ok=no
+ for d in ${TEST_INC_DIRS} ; do
+ if test -d $d ; then
+ AC_CHECK_FILE(${d}/sip.h,sip_ok=yes,sip_ok=no)
+ if test "x$sip_ok" == "xyes" ; then
+ SIP_INCLUDES="-I${d}"
+ break
fi
- else
- AC_CHECK_FILE(${SIPDIR}/sip.so,sip_lib_ok=yes,sip_lib_ok=no)
- if test "x$sip_lib_ok" == "xyes" ; then
- if test "x${SIPDIR}" = "x/usr/lib"
- then
- SIP_LIBS=""
- else
- SIP_LIBS="-L${SIPDIR}"
- fi
- fi
- fi
+ fi
+ done
- if test "x$sip_lib_ok" == "xno" ; then
- dnl look for (lib)sip.so in ${SIPDIR}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages
- if test -d ${SIPDIR}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages ; then
- AC_CHECK_FILE(${SIPDIR}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages/libsip.so,sip_lib_ok=yes,sip_lib_ok=no)
- if test "x$sip_lib_ok" == "xyes" ; then
- SIP_LIBS="-L${SIPDIR}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages -lsip"
- else
- AC_CHECK_FILE(${SIPDIR}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages/sip.so,sip_lib_ok=yes,sip_lib_ok=no)
- if test "x$sip_lib_ok" == "xyes" ; then
- SIP_LIBS="-L${SIPDIR}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages"
- fi
- fi
- fi
- fi
- fi
- if test "x$sip_lib_ok" == "xno" ; then
- dnl look for (lib)sip.so in ${PYTHON_PREFIX}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages
- if test -d ${PYTHON_PREFIX}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages ; then
- AC_CHECK_FILE(${PYTHON_PREFIX}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages/libsip.so,sip_lib_ok=yes,sip_lib_ok=no)
- if test "x$sip_lib_ok" == "xyes" ; then
- SIP_LIBS="-L${PYTHON_PREFIX}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages -lsip"
- else
- AC_CHECK_FILE(${PYTHON_PREFIX}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages/sip.so,sip_lib_ok=yes,sip_lib_ok=no)
- if test "x$sip_lib_ok" == "xyes" ; then
- SIP_LIBS="-L${PYTHON_PREFIX}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages"
+ if test "x$sip_ok" == "xyes" ; then
+ dnl Search sip.so file
+ sip_ok=no
+ for d in ${TEST_LIB_DIRS} ; do
+ if test -d $d ; then
+ AC_CHECK_FILE(${d}/sip.so,sip_ok=yes,sip_ok=no)
+ if test "x$sip_ok" == "xyes" ; then
+ if test "x${d}" = "x/usr/lib${LIB_LOCATION_SUFFIX}" ; then
+ SIP_LIBS=""
+ else
+ SIP_LIBS="-L${d}"
+ fi
+ break
fi
- fi
- fi
- fi
- if test "x$sip_lib_ok" == "xno" ; then
- dnl look for (lib)sip.so in /usr/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages
- if test -d /usr/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages ; then
- AC_CHECK_FILE(/usr/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages/libsip.so,sip_lib_ok=yes,sip_lib_ok=no)
- if test "x$sip_lib_ok" == "xyes" ; then
- SIP_LIBS="-L$/usr/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages -lsip"
- else
- AC_CHECK_FILE(/usr/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages/sip.so,sip_lib_ok=yes,sip_lib_ok=no)
- if test "x$sip_lib_ok" == "xyes" ; then
- SIP_LIBS="-L/usr/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/site-packages"
- fi
fi
- fi
- fi
- if test "x$sip_lib_ok" == "xno" ; then
- sip_ok=no
+ done
fi
fi
AC_SUBST(SIP)
AC_SUBST(SIP_INCLUDES)
AC_SUBST(SIP_LIBS)
-AC_SUBST(SIP_VERS)
-
-AM_CONDITIONAL(IS_SIP_V4, [test $SIP_VERS == v4_old || test $SIP_VERS == v4_new])
-AM_CONDITIONAL(IS_SIP_NEW, [test $SIP_VERS == v3_new || test $SIP_VERS == v4_new])
+AC_SUBST(SIP_VERSION)
+AC_SUBST(SIP_VERSION_ID)
AC_MSG_RESULT(for sip: $sip_ok)
$(MOC) $< -o $@
# qm-files generation
-%.qm: resources/%.po
- $(MSG2QM) $< $@
+%.qm: resources/%.ts
+ $(LRELEASE) $< -qm $@
-EXTRA_DIST=$(MOC_FILES:%_moc.cxx=%.h) $(nodist_salomeres_DATA:%.qm=resources/%.po)
+EXTRA_DIST=$(MOC_FILES:%_moc.cxx=%.h) $(nodist_salomeres_DATA:%.qm=resources/%.ts)
mostlyclean-local:
rm -f @builddir@/*_moc.cxx
#
-AC_INIT([Salome2 Project GUI module], [3.2.2], [gboulant@CS], [salome])
+AC_INIT([Salome2 Project GUI module], [4.0.0], [gboulant@CS], [salome])
AC_CONFIG_AUX_DIR(salome_adm/unix/config_files)
AC_CANONICAL_HOST
AC_CANONICAL_TARGET
AM_INIT_AUTOMAKE
-PACKAGE=salome
-AC_SUBST(PACKAGE)
-
-VERSION=4.0.0
-XVERSION=0x040000
-AC_SUBST(VERSION)
+XVERSION=`echo $VERSION | awk -F. '{printf("0x%02x%02x%02x",$1,$2,$3)}'`
AC_SUBST(XVERSION)
# set up MODULE_NAME variable for dynamic construction of directories (resources, etc.)
CHECK_QT
-echo
-echo ---------------------------------------------
-echo testing msg2qm
-echo ---------------------------------------------
-echo
-
-CHECK_MSG2QM
-
echo
echo ---------------------------------------------
echo testing VTK
if test "$GUI_DISABLE_CORBA" != "yes"; then
-variables="cc_ok lex_yacc_ok python_ok swig_ok threads_ok OpenGL_ok qt_ok msg2qm_ok vtk_ok hdf5_ok
+variables="cc_ok lex_yacc_ok python_ok swig_ok threads_ok OpenGL_ok qt_ok vtk_ok hdf5_ok
omniORB_ok boost_ok occ_ok sip_ok pyqt_ok qwt_ok doxygen_ok graphviz_ok Kernel_ok"
else
-variables="cc_ok lex_yacc_ok python_ok threads_ok OpenGL_ok qt_ok msg2qm_ok vtk_ok hdf5_ok boost_ok
+variables="cc_ok lex_yacc_ok python_ok threads_ok OpenGL_ok qt_ok vtk_ok hdf5_ok boost_ok
occ_ok sip_ok pyqt_ok qwt_ok doxygen_ok graphviz_ok Kernel_ok"
fi
./src/OCCViewer/Makefile \
./src/SOCC/Makefile \
./src/PyInterp/Makefile \
- ./src/PythonConsole/Makefile \
+ ./src/PyConsole/Makefile \
./src/Plot2d/Makefile \
./src/SPlot2d/Makefile \
./src/SUPERVGraph/Makefile \
./src/QxGraph/Makefile \
./src/LightApp/Makefile \
./src/ResExporter/Makefile \
- ./src/RegistryDisplay/Makefile \
./src/TOOLSGUI/Makefile \
./src/Event/Makefile \
./src/Session/Makefile \
./src/SALOME_PY/Makefile \
./src/SALOME_PYQT/Makefile \
./src/SALOME_PYQT/SALOME_PYQT_GUI/Makefile \
- ./src/SALOME_PYQT/SALOME_PYQT_GUI/SALOME_PYQT_SipDefs.h \
./src/SALOME_PYQT/SalomePyQt/Makefile \
./resources/Makefile \
./idl/Makefile \
#ifndef CAF_H
#define CAF_H
-#if defined CAF_EXPORTS
-#if defined WNT
-#define CAF_EXPORT __declspec( dllexport )
+#if defined WIN32
+# if defined CAF_EXPORTS
+# define CAF_EXPORT __declspec( dllexport )
+# else
+# define CAF_EXPORT __declspec( dllimport )
+# endif
#else
-#define CAF_EXPORT
-#endif
-#else
-#if defined WNT
-#define CAF_EXPORT __declspec( dllimport )
-#else
-#define CAF_EXPORT
-#endif
+# define CAF_EXPORT
#endif
#if defined SOLARIS
#define true 1
#endif
-#if defined WNT
+#if defined WIN32
#pragma warning ( disable: 4251 )
#endif
--- /dev/null
+TEMPLATE = lib
+TARGET = caf
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+INCLUDEPATH += ../../include ../Qtx ../SUIT ../STD
+LIBS += -L../../lib -lqtx -lsuit -lstd
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += CAF_EXPORTS
+
+HEADERS = CAF.h
+HEADERS += CAF_Application.h
+HEADERS += CAF_Operation.h
+HEADERS += CAF_Study.h
+HEADERS += CAF_Tools.h
+
+SOURCES = CAF_Application.cxx
+SOURCES += CAF_Operation.cxx
+SOURCES += CAF_Study.cxx
+SOURCES += CAF_Tools.cxx
+
+TRANSLATIONS = resources/CAF_images.ts \
+ resources/CAF_msg_en.ts
+
+ICONS = resources/*.png
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+resources.files = $$ICONS resources/*.qm resources/*.xml resources/*.ini
+resources.path = ../../resources
+
+INSTALLS += includes resources
#include "CAF_Study.h"
#include <SUIT_Desktop.h>
-#include <SUIT_Session.h>
-#include <SUIT_ViewModel.h>
-#include <SUIT_Operation.h>
#include <SUIT_MessageBox.h>
#include <SUIT_ResourceMgr.h>
+#include <QtxAction.h>
#include <QtxListAction.h>
-#include <qtoolbar.h>
-#include <qmenubar.h>
-#include <qpopupmenu.h>
-#include <qstatusbar.h>
-#include <qapplication.h>
+#include <QMap>
+#include <QStringList>
#include <Resource_Manager.hxx>
-
#include <TColStd_SequenceOfExtendedString.hxx>
+/*!
+ \brief Create new instance of CAF_Application.
+ \return new instance of CAF_Application class
+*/
extern "C" CAF_EXPORT SUIT_Application* createApplication()
{
return new CAF_Application();
}
/*!
- Default constructor
+ \class CAF_Application
+ \brief OCC OCAF-based application.
+
+ Defines application configuration and behaviour for application using
+ standard OCC OCAF data model. Allows using OCC OCAF serives
+ (for example, undo/redo mechanizm).
+*/
+
+/*!
+ \brief Default constructor.
*/
CAF_Application::CAF_Application()
: STD_Application()
}
/*!
- Constructor with OCAF application
- \param app - OCAF application
+ \brief Constructor.
+ \param app OCAF application
*/
CAF_Application::CAF_Application( const Handle( TDocStd_Application )& app )
: STD_Application(),
-myStdApp( app )
+ myStdApp( app )
{
}
/*!
- Destructor
+ \brief Destructor.
*/
CAF_Application::~CAF_Application()
{
}
/*!
+ \brief Get application name.
\return application name
*/
QString CAF_Application::applicationName() const
}
/*!
- \return OCAF application
+ \brief Get OCAF application.
+ \return handle to OCAF application object
*/
Handle( TDocStd_Application ) CAF_Application::stdApp() const
{
}
/*!
- \return file filters for open/save document
+ \brief Get file extension filter.
+
+ The file extension filter is used in Open/Save dialog boxes.
+
+ \return file filters for open/save document dialog box
*/
QString CAF_Application::getFileFilter() const
{
{
QString extension;
QString extResStr = CAF_Tools::toQString( formats.Value( i ) ) + QString( ".FileExtension" );
- if ( resMgr->Find( (char*)extResStr.latin1() ) )
- extension = QString( resMgr->Value( (char*)extResStr.latin1() ) );
+ if ( resMgr->Find( extResStr.toLatin1().data() ) )
+ extension = QString( resMgr->Value( extResStr.toLatin1().data() ) );
QString descr;
QString descrResStr = CAF_Tools::toQString( formats.Value( i ) ) + QString( ".Description" );
- if ( resMgr->Find( (char*)descrResStr.latin1() ) )
- descr = QString( resMgr->Value( (char*)descrResStr.latin1() ) );
+ if ( resMgr->Find( (char*)descrResStr.toLatin1().data() ) )
+ descr = QString( resMgr->Value( (char*)descrResStr.toLatin1().data() ) );
if ( !descr.isEmpty() && !extension.isEmpty() )
{
QStringList filters;
for ( QMap<QString, QStringList>::ConstIterator it = wildCards.begin(); it != wildCards.end(); ++it )
- filters.append( QString( "%1 (%2)" ).arg( it.key() ).arg( it.data().join( "; " ) ) );
+ filters.append( QString( "%1 (%2)" ).arg( it.key() ).arg( it.value().join( "; " ) ) );
if ( wildCards.count() > 1 )
filters.prepend( QString( "%1 (%2)" ).arg( tr( "INF_ALL_DOCUMENTS_FILTER" ) ).arg( allWC.join( "; " ) ) );
}
/*!
- Creates actions of application
+ \brief Create menu and toolbars actions.
*/
void CAF_Application::createActions()
{
SUIT_Desktop* desk = desktop();
SUIT_ResourceMgr* resMgr = resourceMgr();
- QtxListAction* editUndo =
- new QtxListAction( tr( "TOT_APP_EDIT_UNDO" ), resMgr->loadPixmap( "CAF", tr( "ICON_APP_EDIT_UNDO" ) ),
- tr( "MEN_APP_EDIT_UNDO" ), CTRL+Key_Z, desk );
+ QtxListAction* editUndo =
+ new QtxListAction( tr( "TOT_APP_EDIT_UNDO" ),
+ resMgr->loadPixmap( "CAF", tr( "ICON_APP_EDIT_UNDO" ) ),
+ tr( "MEN_APP_EDIT_UNDO" ), Qt::CTRL+Qt::Key_Z, desk );
+ editUndo->setStatusTip( tr( "PRP_APP_EDIT_UNDO" ) );
registerAction( EditUndoId, editUndo );
QtxListAction* editRedo =
- new QtxListAction( tr( "TOT_APP_EDIT_REDO" ), resMgr->loadPixmap( "CAF", tr( "ICON_APP_EDIT_REDO" ) ),
- tr( "MEN_APP_EDIT_REDO" ), CTRL+Key_Y, desk );
+ new QtxListAction( tr( "TOT_APP_EDIT_REDO" ),
+ resMgr->loadPixmap( "CAF", tr( "ICON_APP_EDIT_REDO" ) ),
+ tr( "MEN_APP_EDIT_REDO" ), Qt::CTRL+Qt::Key_Y, desk );
+ editRedo->setStatusTip( tr( "PRP_APP_EDIT_REDO" ) );
registerAction( EditRedoId, editRedo );
editUndo->setComment( tr( "INF_APP_UNDOACTIONS" ) );
connect( editUndo, SIGNAL( activated( int ) ), this, SLOT( onUndo( int ) ) );
connect( editRedo, SIGNAL( activated( int ) ), this, SLOT( onRedo( int ) ) );
-
int editMenu = createMenu( tr( "MEN_DESK_EDIT" ), -1, -1, 10 );
createMenu( EditUndoId, editMenu, 0 );
}
/*!
- Undo operation on the given document. [ virtual protected ]
+ \brief Undo latest command operation for specified document.
+ \param doc OCAF document
+ \return \c true on success
*/
bool CAF_Application::undo( CAF_Study* doc )
{
}
/*!
- Redo operation on the given document. [ virtual protected ]
+ \brief Redo latest command operation undo for specified document.
+ \param doc OCAF document
+ \return \c true on success
*/
bool CAF_Application::redo(CAF_Study* doc)
{
}
/*!
- Undo operation on the active document. [ virtual protected slot ]
+ \brief Called when user activates "Undo" menu action.
+
+ Undo operation on the active document.
+
+ \param numActions undo depth (number of commands)
+ \return \c true on success
*/
bool CAF_Application::onUndo( int numActions )
{
bool ok = true;
while ( numActions > 0 )
{
- CAF_Study* cafStudy = dynamic_cast<CAF_Study*>( activeStudy() );
- if ( cafStudy )
+ CAF_Study* cafStudy = dynamic_cast<CAF_Study*>( activeStudy() );
+ if ( cafStudy )
{
- if ( !undo( cafStudy ) )
- {
- ok = false;
- break;
- }
- numActions--;
- }
+ if ( !undo( cafStudy ) )
+ {
+ ok = false;
+ break;
+ }
+ numActions--;
+ }
}
updateCommandsStatus(); /* enable/disable undo/redo */
return ok;
}
/*!
- Redo operation on the active document. [ virtual protected slot ]
+ \brief Called when user activates "Redo" menu action.
+
+ Redo latest undo commands on the active document.
+
+ \param numActions redo depth (number of commands)
+ \return \c true on success
*/
bool CAF_Application::onRedo( int numActions )
{
bool ok = true;
while ( numActions > 0 )
{
- CAF_Study* cafStudy = dynamic_cast<CAF_Study*>( activeStudy() );
- if ( cafStudy )
+ CAF_Study* cafStudy = dynamic_cast<CAF_Study*>( activeStudy() );
+ if ( cafStudy )
{
- if ( !redo( cafStudy ) )
- {
- ok = false;
- break;
- }
- numActions--;
- }
+ if ( !redo( cafStudy ) )
+ {
+ ok = false;
+ break;
+ }
+ numActions--;
+ }
}
updateCommandsStatus(); /* enable/disable undo/redo */
return ok;
}
/*!
- Enables / disables the actions according to the application state. [ virtual protected ]
+ \brief Update actions state (Undo/Redo).
*/
void CAF_Application::updateCommandsStatus()
{
- STD_Application::updateCommandsStatus();
+ STD_Application::updateCommandsStatus();
CAF_Study* cafStudy = 0;
if ( activeStudy() && activeStudy()->inherits( "CAF_Study" ) )
cafStudy = (CAF_Study*)activeStudy();
- QAction* undo = action( EditUndoId );
+ QtxListAction* undo = qobject_cast<QtxListAction*>( action( EditUndoId ) );
if ( cafStudy && undo )
- undo->setProperty( "names", cafStudy->undoNames() );
+ undo->addNames( cafStudy->undoNames() );
- QAction* redo = action( EditRedoId );
+ QtxListAction* redo = qobject_cast<QtxListAction*>( action( EditRedoId ) );
if ( cafStudy && redo )
- redo->setProperty( "names", cafStudy->redoNames() );
+ redo->addNames( cafStudy->redoNames() );
if ( undo )
undo->setEnabled( cafStudy && cafStudy->canUndo() );
}
/*!
- SLOT: called by clicking on Help->About in main menu
+ \brief Called when user activatees Help->About main menu command.
*/
void CAF_Application::onHelpAbout()
{
- SUIT_MessageBox::info1( desktop(), tr( "About" ), tr( "ABOUT_INFO" ), "&OK" );
+ SUIT_MessageBox::information( desktop(), tr( "About" ), tr( "ABOUT_INFO" ) );
}
/*!
- Creates new study
+ \brief Create new empty study.
+ \return new study
*/
SUIT_Study* CAF_Application::createNewStudy()
{
}
/*!
- Sets OCAF application
+ \brief Set OCAF application.
+ \param app new OCAF application
*/
void CAF_Application::setStdApp( const Handle(TDocStd_Application)& app )
{
#include "STD_Application.h"
-#include <qmap.h>
-#include <qptrlist.h>
-
#include <TDocStd_Application.hxx>
-class QtxAction;
class CAF_Study;
#if defined WIN32
#pragma warning ( disable: 4251 )
#endif
-/*!
- \class CAF_Application
- Defines application configuration and behaviour for application with
- link to standard OCC OCAF data model. Allows to use OCC OCAF serives
- (for example, undo/redo)
-*/
class CAF_EXPORT CAF_Application : public STD_Application
{
Q_OBJECT
virtual SUIT_Study* createNewStudy();
- bool undo( CAF_Study* doc );
- bool redo( CAF_Study* doc );
+ bool undo( CAF_Study* doc );
+ bool redo( CAF_Study* doc );
virtual void setStdApp( const Handle(TDocStd_Application)& );
#include <TDocStd_Document.hxx>
/*!
- Default constructor
+ \class CAF_Operation
+ \brief Base operation class for all operations used in CAF package.
+
+ Operation interacts with OCC OCAF std document.
+*/
+
+/*!
+ \brief Constructor.
+ \param theApp application
*/
CAF_Operation::CAF_Operation(SUIT_Application* theApp)
-:SUIT_Operation(theApp)
+: SUIT_Operation(theApp)
{
}
/*!
- Destructor
+ \brief Destructor.
*/
CAF_Operation::~CAF_Operation()
{
}
/*!
- \return OCAF document
+ \brief Get OCAF document.
+ \return handle to the OCAF document object
*/
Handle(TDocStd_Document) CAF_Operation::stdDoc() const
{
Handle(TDocStd_Document) doc;
- CAF_Study* s = ::qt_cast<CAF_Study*>( study() );
+ CAF_Study* s = qobject_cast<CAF_Study*>( study() );
if ( s )
doc = s->stdDoc();
return doc;
#include "SUIT_Operation.h"
-#include <qobject.h>
-#include <qstring.h>
-
#include <Standard.hxx>
class CAF_Study;
-//! OCC OCAF Std document
class Handle(TDocStd_Document);
-/*!
- \class CAF_Operation
- Base operation for all operations used in CAF package
- Operation has link to OCC OCAF std document
-*/
class CAF_EXPORT CAF_Operation : public SUIT_Operation
{
- Q_OBJECT
+ Q_OBJECT
public:
- CAF_Operation( SUIT_Application* );
- virtual ~CAF_Operation();
+ CAF_Operation( SUIT_Application* );
+ virtual ~CAF_Operation();
protected:
Handle(TDocStd_Document) stdDoc() const;
#include "CAF_Study.h"
#include "CAF_Tools.h"
-#include "CAF_Operation.h"
#include "CAF_Application.h"
#include <SUIT_Desktop.h>
#include <SUIT_MessageBox.h>
#include <SUIT_Application.h>
-#include <qdir.h>
+#include <QDir>
#include <TDF_Delta.hxx>
#include <TDF_ListIteratorOfDeltaList.hxx>
+#include <TDocStd_Application.hxx>
#include <Standard_Failure.hxx>
#include <Standard_ErrorHandler.hxx>
/*!
- Constructor
+ \class CAF_Study
+ \brief Represents study for using in CAF module.
+
+ A study contains reference to OCAF std document and allows using OCAF services.
+ Provides necessary functionality for OCC transactions management.
+*/
+
+/*!
+ \brief Constructor.
+ \param theApp application
*/
CAF_Study::CAF_Study(SUIT_Application* theApp)
: SUIT_Study( theApp ),
-myModifiedCnt( 0 )
+ myModifiedCnt( 0 )
{
}
/*!
- Constructor
+ \brief Constructor.
+ \param theApp application
+ \param aStdDoc OCAF document
*/
CAF_Study::CAF_Study(SUIT_Application* theApp, Handle (TDocStd_Document)& aStdDoc)
: SUIT_Study( theApp ),
-myStdDoc( aStdDoc ),
-myModifiedCnt( 0 )
+ myStdDoc( aStdDoc ),
+ myModifiedCnt( 0 )
{
}
/*!
- Destructor
+ \brief Destructor.
*/
CAF_Study::~CAF_Study()
{
}
/*!
- \return OCAF document
+ \brief Get OCAF document.
+ \return handle to the OCAF document object
*/
Handle(TDocStd_Document) CAF_Study::stdDoc() const
{
}
/*!
- Sets new OCAF document
- \param aStdDoc - new OCAF document
+ \brief Set OCAF document.
+ \param aStdDoc new OCAF document
*/
void CAF_Study::setStdDoc( Handle(TDocStd_Document)& aStdDoc )
{
}
/*!
- Custom document initialization
+ \brief Customize document initialization.
+ \param doc study name
+ \return \c true on success and \c false on error
*/
-void CAF_Study::createDocument()
+bool CAF_Study::createDocument( const QString& doc )
{
- SUIT_Study::createDocument();
+ bool res = SUIT_Study::createDocument( doc );
CAF_Application* app = cafApplication();
- if ( app && !app->stdApp().IsNull() )
+ if ( res && app && !app->stdApp().IsNull() )
{
try {
#if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
app->stdApp()->NewDocument( formats.First(), myStdDoc );
}
catch ( Standard_Failure ) {
+ res = false;
}
}
+ return res;
}
/*!
- Close document
+ \brief Close document.
+ \param permanently if \c true, a document is closed permanently
*/
-void CAF_Study::closeDocument( bool permanent )
+void CAF_Study::closeDocument( bool permanently )
{
Handle(TDocStd_Application) app = stdApp();
if ( !app.IsNull() && !stdDoc().IsNull() )
app->Close( stdDoc() );
- SUIT_Study::closeDocument( permanent );
+ SUIT_Study::closeDocument( permanently );
}
/*!
- Open document
- \param fname - name of file
+ \brief Open document.
+ \param fname study file name
+ \return \c true on success and \c false if document cannot be opened
*/
bool CAF_Study::openDocument( const QString& fname )
{
}
/*!
- Save document with other name
- \param fname - name of file
+ \brief Save document with other name.
+ \param fname study file name
*/
bool CAF_Study::saveDocumentAs( const QString& fname )
{
}
/*!
- Open OCAF transaction
+ \brief Open OCAF transaction.
+ \return \c true if transaction is opened successfully
*/
bool CAF_Study::openTransaction()
{
}
/*!
- Abort OCAF transaction
+ \brief Abort OCAF transaction.
+ \return \c true if transaction is aborted successfully
*/
bool CAF_Study::abortTransaction()
{
}
/*!
- Commit OCAF transaction
+ \brief Commit OCAF transaction
+ \return \c true if transaction is committed successfully
*/
bool CAF_Study::commitTransaction( const QString& name )
{
}
/*!
- \return true, if there is opened OCAF transaction
+ \brief Check if there is any transaction opened.
+ \return \c true if there is opened OCAF transaction
*/
bool CAF_Study::hasTransaction() const
{
}
/*!
- \return whether the document was saved in file. [ public ]
+ \brief Check if the study is saved.
+ \return \c true if the document has been saved to file
*/
bool CAF_Study::isSaved() const
{
}
/*!
- \return whether the document is modified. [ public ]
+ \brief Check if the study is modified.
+ \return \c true if the document has been modified
*/
bool CAF_Study::isModified() const
{
}
/*!
- Increments modification count. If 'undoable' is 'true', this modification
- can be rolled back by 'undoModified' otherwise the document will be marked
- as 'modiifed' until saved. [ protected ]
+ \brief Increment modifications count.
+
+ If \a undoable is \c true, this modification can be rolled back by
+ undoModified(), otherwise the document will be marked as \c modified
+ until it is saved.
+
+ \param undoable if \c true the operation is undoable
+ \sa undoModified(), clearModified()
*/
void CAF_Study::doModified( bool undoable )
{
- if ( myStdDoc.IsNull() )
+ if ( myStdDoc.IsNull() )
return;
- myModifiedCnt++;
+ myModifiedCnt++;
- /* Assumed that number of available undos / redos is NOT changed dynamically */
- if ( !undoable )
+ /* Assumed that number of available undos / redos is NOT changed dynamically */
+ if ( !undoable )
myModifiedCnt += myStdDoc->GetAvailableUndos();
}
/*!
- Decrements modification count. [ protected ]
+ \brief Decrement modifications count.
+ \sa doModified(), clearModified()
*/
void CAF_Study::undoModified()
{
}
/*!
- Clears modification count. [ public ]
+ \brief Clear modifications count.
+ \sa doModified(), undoModified()
*/
void CAF_Study::clearModified()
{
}
/*!
- Undoes the last command. [ public ]
+ \brief Undo the last command.
+ \return \c true on success and \c false on error
*/
bool CAF_Study::undo()
{
undoModified(); /* decrement modification counter */
}
catch ( Standard_Failure ) {
- SUIT_MessageBox::error1(application()->desktop(), tr( "ERR_ERROR" ),
- tr( "ERR_DOC_UNDO" ), tr ( "BUT_OK" ));
+ SUIT_MessageBox::critical(application()->desktop(), tr( "ERR_ERROR" ),
+ tr( "ERR_DOC_UNDO" ));
return false;
}
return true;
}
/*!
- Redoes the last undo. [ public ]
+ \brief Redo the last undo.
+ \return \c true on success and \c false on error
*/
bool CAF_Study::redo()
{
doModified(); /* increment modification counter */
}
catch ( Standard_Failure ) {
- SUIT_MessageBox::error1( application()->desktop(), tr( "ERR_ERROR" ),
- tr( "ERR_DOC_REDO" ), tr ( "BUT_OK" ) );
+ SUIT_MessageBox::critical( application()->desktop(), tr( "ERR_ERROR" ),
+ tr( "ERR_DOC_REDO" ) );
return false;
}
return true;
}
/*!
- \return true if possible to perform 'undo' command. [ public ]
+ \brief Check if it is possible to undo last command.
+ \return \c true if undo is avaiable
*/
bool CAF_Study::canUndo() const
{
}
/*!
- \return true if possible to perform 'redo' command. [ public ]
+ \brief Check if it is possible to redo last undo.
+ \return \c true if redo is avaiable
*/
bool CAF_Study::canRedo() const
{
}
/*!
- \return the list of names of 'undo' actions available. [ public ]
+ \brief Get names of available undo commands.
+ \return list of commands names
*/
QStringList CAF_Study::undoNames() const
{
}
/*!
- \return the list of names of 'redo' actions available. [ public ]
+ \brief Get names of available redo commands.
+ \return list of commands names
*/
QStringList CAF_Study::redoNames() const
{
}
/*!
- \return the standard OCAF application from owner application. [ protected ]
+ \brief Get OCAF application.
+ \return handle to the OCAF application object
*/
Handle(TDocStd_Application) CAF_Study::stdApp() const
{
}
/*!
- \return the application casted to type CAF_Application. [ protected ]
+ \brief Get application.
+ \return application object (CAF_Application)
*/
CAF_Application* CAF_Study::cafApplication() const
{
- return ::qt_cast<CAF_Application*>( application() );
+ return qobject_cast<CAF_Application*>( application() );
}
#include "SUIT_Study.h"
-#include <qobject.h>
-
#include <TDocStd_Document.hxx>
-#include <TDocStd_Application.hxx>
class CAF_Application;
+class Handle(TDocStd_Application);
-#if defined WNT
+#if defined WIN32
#pragma warning ( disable: 4251 )
#endif
-/*!
- \class CAF_Study
- Represents study for using in CAF, contains reference
- to OCAF std document and allows to use OCAF services.
- Provides necessary functionality for OCC transactions management.
-*/
class CAF_EXPORT CAF_Study : public SUIT_Study
{
Q_OBJECT
public:
- CAF_Study( SUIT_Application* theApp );
- CAF_Study( SUIT_Application* theApp, Handle(TDocStd_Document)& aStdDoc );
- virtual ~CAF_Study();
+ CAF_Study( SUIT_Application* theApp );
+ CAF_Study( SUIT_Application* theApp, Handle(TDocStd_Document)& aStdDoc );
+ virtual ~CAF_Study();
- virtual void createDocument();
+ virtual bool createDocument( const QString& );
virtual void closeDocument( bool = true );
virtual bool openDocument( const QString& );
virtual bool saveDocumentAs( const QString& );
bool isSaved() const;
- bool isModified() const;
- void doModified( bool = true );
- void undoModified();
- void clearModified();
-
+ bool isModified() const;
+ void doModified( bool = true );
+ void undoModified();
+ void clearModified();
+
bool undo();
- bool redo();
- bool canUndo() const;
- bool canRedo() const;
- QStringList undoNames() const;
- QStringList redoNames() const;
-
+ bool redo();
+ bool canUndo() const;
+ bool canRedo() const;
+ QStringList undoNames() const;
+ QStringList redoNames() const;
+
Handle(TDocStd_Document) stdDoc() const;
protected:
virtual void setStdDoc( Handle(TDocStd_Document)& );
private:
- Handle(TDocStd_Document) myStdDoc;
- int myModifiedCnt;
+ Handle(TDocStd_Document) myStdDoc;
+ int myModifiedCnt;
friend class CAF_Operation;
};
-#if defined WNT
+#if defined WIN32
#pragma warning ( default: 4251 )
#endif
#include "CAF_Tools.h"
-#include <string.h>
-#include <TCollection_ExtendedString.hxx>
+/*!
+ \class CAF_Tools
+ \brief Prodives a set of helpful static methods.
+*/
/*!
- Converts TCollection_ExtendedString 'src' to Qt string. [ static ]
+ \brief Convert TCollection_ExtendedString \a src to QString.
+ \param src string to be converted
+ \return resulting QString object
*/
QString CAF_Tools::toQString ( const TCollection_ExtendedString& src )
{
}
/*!
- Converts TCollection_AsciiString'src' to Qt string. [ static ]
+ \brief Convert TCollection_AsciiString \a src to QString.
+ \param src string to be converted
+ \return resulting QString object
*/
QString CAF_Tools::toQString( const TCollection_AsciiString& src )
{
}
/*!
- Converts Qt string to TCollection_AsciiString. [ static ]
+ \brief Convert QString \a src to TCollection_AsciiString.
+ \param src string to be converted
+ \return resulting TCollection_AsciiString object
*/
TCollection_AsciiString CAF_Tools::toAsciiString( const QString& src )
{
TCollection_AsciiString res;
if ( !src.isEmpty() )
- res = TCollection_AsciiString( (char*)src.latin1() );
+ res = TCollection_AsciiString( src.toLatin1().data() );
return res;
}
/*!
- Converts Qt string to TCollection_ExtendedString. [ static ]
+ \brief Convert QString \a src to TCollection_ExtendedString.
+ \param src string to be converted
+ \return resulting TCollection_ExtendedString object
*/
TCollection_ExtendedString CAF_Tools::toExtString ( const QString& src )
{
}
/*!
- Converts Qt color to OCC color
+ \brief Convert QColor object to Quantity_Color object.
+ \param c color object in Qt format
+ \return color object in OCC format
*/
Quantity_Color CAF_Tools::color( const QColor& c )
{
}
/*!
- Converts OCC color to Qt color
+ \brief Convert Quantity_Color object to QColor object.
+ \param c color object in OCC format
+ \return color object in Qt format
*/
QColor CAF_Tools::color( const Quantity_Color& c )
{
#include <SUIT_Tools.h>
-#include <qcolor.h>
+#include <QColor>
#include <Quantity_Color.hxx>
#include <TCollection_AsciiString.hxx>
#include <TCollection_ExtendedString.hxx>
-/*!
- \class CAF_Tools
- Prodives set of auxiliary static methods
-*/
class CAF_EXPORT CAF_Tools : public SUIT_Tools
{
public:
CAF_images.qm \
CAF_msg_en.qm
-libcaf_la_CPPFLAGS=$(QT_INCLUDES) $(CAS_CPPFLAGS) -I${QTDIR}/src/kernel -I$(QTDIR)/mkspecs/linux-g++ \
- -I$(srcdir)/../STD -I$(srcdir)/../SUIT -I$(srcdir)/../Qtx
+libcaf_la_CPPFLAGS=$(QT_INCLUDES) $(CAS_CPPFLAGS) -I$(srcdir)/../STD -I$(srcdir)/../SUIT -I$(srcdir)/../Qtx
libcaf_la_LDFLAGS=$(QT_MT_LIBS) $(CAS_OCAF) $(CAS_OCAFVIS)
-libcaf_la_LIBADD=../STD/libstd.la ../SUIT/libsuit.la
+libcaf_la_LIBADD=../Qtx/libqtx.la ../SUIT/libsuit.la ../STD/libstd.la
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>ICON_APP_EDIT_REDO</source>
+ <translation>redo.png</translation>
+ </message>
+ <message>
+ <source>ICON_APP_EDIT_UNDO</source>
+ <translation>undo.png</translation>
+ </message>
+</context>
+</TS>
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>CAF_Application</name>
+ <message>
+ <source>MEN_APP_EDIT</source>
+ <translation>&Edit</translation>
+ </message>
+ <message>
+ <source>INF_ALL_FILTER</source>
+ <translation>All Files (*.*)</translation>
+ </message>
+ <message>
+ <source>INF_ALL_DOCUMENTS_FILTER</source>
+ <translation>All Readable Documents</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_EDIT</source>
+ <translation>&Edit</translation>
+ </message>
+ <message>
+ <source>MEN_APP_EDIT_UNDO</source>
+ <translation>&Undo</translation>
+ </message>
+ <message>
+ <source>MEN_APP_EDIT_REDO</source>
+ <translation>&Redo</translation>
+ </message>
+ <message>
+ <source>PRP_APP_EDIT_REDO</source>
+ <translation>Redoes the last operation</translation>
+ </message>
+ <message>
+ <source>PRP_APP_EDIT_UNDO</source>
+ <translation>Undoes the last operation</translation>
+ </message>
+ <message>
+ <source>TOT_APP_EDIT_REDO</source>
+ <translation>Redo</translation>
+ </message>
+ <message>
+ <source>TOT_APP_EDIT_UNDO</source>
+ <translation>Undo</translation>
+ </message>
+ <message>
+ <source>INF_APP_REDOACTIONS</source>
+ <translation> Redoes %1 action(s) </translation>
+ </message>
+ <message>
+ <source>INF_APP_UNDOACTIONS</source>
+ <translation> Undoes %1 action(s) </translation>
+ </message>
+ <message>
+ <source>ABOUT_INFO</source>
+ <translation>SUIT Caf application</translation>
+ </message>
+</context>
+</TS>
#ifndef CAM_H
#define CAM_H
-#if defined CAM_EXPORTS
-#if defined WNT
-#define CAM_EXPORT __declspec( dllexport )
+#if defined WIN32
+# if defined CAM_EXPORTS
+# define CAM_EXPORT __declspec( dllexport )
+# else
+# define CAM_EXPORT __declspec( dllimport )
+# endif
#else
-#define CAM_EXPORT
-#endif
-#else
-#if defined WNT
-#define CAM_EXPORT __declspec( dllimport )
-#else
-#define CAM_EXPORT
-#endif
+# define CAM_EXPORT
#endif
#if defined SOLARIS
#define true 1
#endif
-#if defined WNT
+#if defined WIN32
#pragma warning ( disable: 4251 )
#endif
--- /dev/null
+TEMPLATE = lib
+TARGET = CAM
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+INCLUDEPATH += ../../include ../Qtx ../SUIT ../STD
+LIBS += -L../../lib -lqtx -lsuit -lstd
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += CAM_EXPORTS
+
+HEADERS = CAM.h
+HEADERS += CAM_Application.h
+HEADERS += CAM_DataModel.h
+HEADERS += CAM_DataObject.h
+HEADERS += CAM_Module.h
+HEADERS += CAM_RootObject.h
+HEADERS += CAM_Study.h
+
+SOURCES = CAM_Application.cxx
+SOURCES += CAM_DataModel.cxx
+SOURCES += CAM_DataObject.cxx
+SOURCES += CAM_Module.cxx
+SOURCES += CAM_RootObject.cxx
+SOURCES += CAM_Study.cxx
+
+TRANSLATIONS = resources/CAM_images.ts \
+ resources/CAM_msg_en.ts
+
+ICONS = resources/*.png
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+resources.files = $$ICONS resources/*.qm resources/*.xml resources/*.ini
+resources.path = ../../resources
+
+INSTALLS += includes resources
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
+
#include "CAM_Application.h"
#include "CAM_Study.h"
#include "CAM_Module.h"
#include <SUIT_Tools.h>
+#include <SUIT_Desktop.h>
#include <SUIT_Session.h>
#include <SUIT_MessageBox.h>
+#include <SUIT_ResourceMgr.h>
-#include <qfile.h>
-#include <qfileinfo.h>
-#include <qtextstream.h>
-#include <qlabel.h>
-#include <qfont.h>
-#include <qapplication.h>
-#include <qregexp.h>
+#include <QApplication>
+#include <QRegExp>
#ifdef WIN32
#include <windows.h>
#include <dlfcn.h>
#endif
-/*!Create new instance of CAM_Application*/
+/*!
+ \brief Create new instance of CAM_Application.
+ \return new instance of CAM_Application class
+*/
extern "C" CAM_EXPORT SUIT_Application* createApplication()
{
return new CAM_Application();
}
-/*!Constructor. read module list.
- * \param autoLoad - auto load flag.
- */
+/*!
+ \class CAM_Application
+ \brief Introduces an application class which provides modular architecture.
+
+ This class defines multi-modular application configuration and behaviour.
+ Each module (CAM_Module) can have own data model, document windows and
+ viewers, etc.
+
+ An application provides all necessary functionality for modules management,
+ like
+ - loading of modules
+ - modules activation/deactivation
+ - etc
+*/
+
+/*!
+ \brief Constructor.
+
+ Read modules list (from command line or from resource file).
+ If \a autoLoad parameter is \c true all the modules will be loaded
+ immediately after application starting, otherwise each module will
+ be loaded by demand (with activateModule()).
+
+ \param autoLoad auto loading flag
+*/
CAM_Application::CAM_Application( const bool autoLoad )
: STD_Application(),
-myModule( 0 ),
-myAutoLoad( autoLoad )
+ myModule( 0 ),
+ myAutoLoad( autoLoad )
{
readModuleList();
}
-/*!Destructor. Do nothing.*/
+/*!
+ \brief Destructor.
+
+ Does nothing currently.
+*/
CAM_Application::~CAM_Application()
{
}
-/*! Load modules, if \a myAutoLoad flag is true.\n
- * Start application - call start() method from parent class.
- */
+/*!
+ \brief Start an application.
+
+ Load all modules, if "auto loading" flag has been set to \c true.
+
+ \sa CAM_Application()
+*/
void CAM_Application::start()
{
if ( myAutoLoad )
STD_Application::start();
}
-/*!Get active module.
- * \retval CAM_Module - active module.
- */
+/*!
+ \brief Get active module.
+ \return active module or 0 if there are no any
+*/
CAM_Module* CAM_Application::activeModule() const
{
return myModule;
}
-/*!Get module with name \a modName from modules list.
- * \retval CAM_Module pointer - module.
- */
+/*!
+ \brief Get the module with specified name.
+ \return module or 0 if not found
+*/
CAM_Module* CAM_Application::module( const QString& modName ) const
{
CAM_Module* mod = 0;
- for ( ModuleListIterator it( myModules ); it.current() && !mod; ++it )
- if ( it.current()->moduleName() == modName )
- mod = it.current();
+ for ( QList<CAM_Module*>::const_iterator it = myModules.begin();
+ it != myModules.end() && !mod; ++it )
+ if ( (*it)->moduleName() == modName )
+ mod = *it;
return mod;
}
-/*!Gets modules iterator.*/
-CAM_Application::ModuleListIterator CAM_Application::modules() const
+/*!
+ \brief Get all loaded modules.
+ \return list of modules
+*/
+CAM_Application::ModuleList CAM_Application::modules() const
{
- return ModuleListIterator( myModules );
+ return myModules;
}
-/*!Gets modules list.
- * \param out - output list of modules.
- */
+/*!
+ \brief Get all loaded modules.
+ \param returning list of modules
+*/
void CAM_Application::modules( CAM_Application::ModuleList& out ) const
{
- out.setAutoDelete( false );
out.clear();
- for ( ModuleListIterator it( myModules ); it.current(); ++it )
- out.append( it.current() );
+ for ( QList<CAM_Module*>::const_iterator it = myModules.begin();
+ it != myModules.end(); ++it )
+ out.append( *it );
}
-/*!Gets list of names for modules.\n
- * Get loaded modules names, if \a loaded is true, else \n
- * get names from information list.
- * \param lst - output list of names.
- * \param loaded - boolean flag.
- */
+/*!
+ \brief Get names of all modules.
+
+ Get loaded modules names if \a loaded is \c true,
+ otherwise get all avaiable modules names.
+
+ \param lst output list of modules names
+ \param loaded boolean flag, defines what modules names to return
+*/
void CAM_Application::modules( QStringList& lst, const bool loaded ) const
{
lst.clear();
if ( loaded )
- for ( ModuleListIterator it( myModules ); it.current(); ++it )
- lst.append( it.current()->moduleName() );
+ {
+ for ( QList<CAM_Module*>::const_iterator it = myModules.begin();
+ it != myModules.end(); ++it )
+ lst.append( (*it)->moduleName() );
+ }
else
- for ( ModuleInfoList::const_iterator it = myInfoList.begin(); it != myInfoList.end(); ++it )
+ {
+ for ( ModuleInfoList::const_iterator it = myInfoList.begin();
+ it != myInfoList.end(); ++it )
lst.append( (*it).title );
+ }
}
-/*!Adding module \a mod to list.
- *\param mod - module.
- */
+/*!
+ \brief Add module \a mod to the modules list.
+
+ Performes module initialization. Does nothing if the module
+ is already added.
+
+ \param mod module being added
+ \sa CAM_Module::initialize()
+*/
void CAM_Application::addModule( CAM_Module* mod )
{
if ( !mod || myModules.contains( mod ) )
QMap<CAM_Module*, int> map;
ModuleList newList;
- for ( ModuleInfoList::const_iterator it = myInfoList.begin(); it != myInfoList.end(); ++it )
+ for ( ModuleInfoList::const_iterator it = myInfoList.begin();
+ it != myInfoList.end(); ++it )
{
if ( (*it).title == mod->moduleName() )
newList.append( mod );
if ( curMod )
newList.append( curMod );
}
- if ( !newList.isEmpty() )
- map.insert( newList.getLast(), 0 );
}
- for ( ModuleListIterator itr( myModules ); itr.current(); ++itr )
+ for ( QList<CAM_Module*>::const_iterator it = myModules.begin();
+ it != myModules.end(); ++it )
{
- if ( !map.contains( itr.current() ) )
- newList.append( itr.current() );
+ if ( !newList.contains( *it ) )
+ newList.append( *it );
}
- if ( !map.contains( mod ) )
+ if ( !newList.contains( mod ) )
newList.append( mod );
myModules = newList;
moduleAdded( mod );
}
-/*!Load modules from information list.
- * \warning If some of modules not loaded, error message appear on desktop.
- */
+/*!
+ \brief Load modules from the modules information list.
+
+ If some module can not be loaded, an error message is shown.
+*/
void CAM_Application::loadModules()
{
for ( ModuleInfoList::const_iterator it = myInfoList.begin(); it != myInfoList.end(); ++it )
if ( mod )
addModule( mod );
else {
- if ( desktop() && desktop()->isShown() )
- SUIT_MessageBox::error1( desktop(), tr( "Loading modules" ),
- tr( "Can not load module %1" ).arg( (*it).title ), tr( "Ok" ) );
+ if ( desktop() && desktop()->isVisible() )
+ SUIT_MessageBox::critical( desktop(), tr( "Loading modules" ),
+ tr( "Can not load module %1" ).arg( (*it).title ) );
else
- qWarning( tr( "Can not load module %1" ).arg( (*it).title ).latin1() );
+ qWarning( tr( "Can not load module %1" ).arg( (*it).title ).toLatin1().data() );
}
}
}
-/*!Load module with name \a modName.
- *\param modName - module name for loading.
- *\warning If information list is empty.
- *\warning If module library (for module with \a modName) is empty.
- *\warning If module library is not loaded.
- */
+/*!
+ \brief Load module \a modName.
+
+ The function prints warning message if:
+ - modules information list is empty
+ - modules information list does not include specified module info
+ - module library can not be loaded by some reason
+
+ \param modName module name
+ \return module object pointer or 0 if module could not be loaded
+*/
CAM_Module* CAM_Application::loadModule( const QString& modName )
{
if ( myInfoList.isEmpty() )
{
- qWarning( tr( "Modules configuration is not defined." ) );
+ qWarning( tr( "Modules configuration is not defined." ).toLatin1().data() );
return 0;
}
QString libName = moduleLibrary( modName );
if ( libName.isEmpty() )
{
- qWarning( tr( "Information about module \"%1\" doesn't exist." ).arg( modName ) );
+ qWarning( tr( "Information about module \"%1\" doesn't exist." ).arg( modName ).toLatin1().data() );
return 0;
}
GET_MODULE_FUNC crtInst = 0;
#ifdef WIN32
- HINSTANCE modLib = ::LoadLibrary( libName );
+ HINSTANCE modLib = ::LoadLibrary( libName.toLatin1() );
if ( !modLib )
{
LPVOID lpMsgBuf;
}
}
#else
- void* modLib = dlopen( (char*)libName.latin1(), RTLD_LAZY );
+ void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY );
if ( !modLib )
err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
else
}
if ( !err.isEmpty() ) {
- if ( desktop() && desktop()->isShown() )
- SUIT_MessageBox::warn1( desktop(), tr( "Error" ), err, tr( "Ok" ) );
+ if ( desktop() && desktop()->isVisible() )
+ SUIT_MessageBox::warning( desktop(), tr( "Error" ), err );
else
- qWarning( err.latin1() );
+ qWarning( err.toLatin1().data() );
}
return module;
}
-/*! @name Activate module group. */
-//@{
-/*!Activate module with name \a modName.
- *\param modName - module name.
- *\ratval true, if module loaded and activated successful, else false.
- */
+/*!
+ \brief Activate module \a modName.
+ \param modName module name
+ \return \c true, if module is loaded and activated successfully and \c false otherwise
+*/
bool CAM_Application::activateModule( const QString& modName )
{
if ( !modName.isEmpty() && !activeStudy() )
return res;
}
-/*!Activate module \a mod
- *\param mod - module for activation.
- *\retval true - if all sucessful.
- *\warning Error message if module not activated in active study.
- */
+/*!
+ \brief Activate module \a mod.
+
+ Shows error message if module could not be activated in the current study.
+
+ \param mod module object pointer
+ \return \c true, if module is loaded and activated successfully and \c false otherwise
+*/
bool CAM_Application::activateModule( CAM_Module* mod )
{
if ( mod && !activeStudy() )
{
myModule->setMenuShown( false );
myModule->setToolShown( false );
- if ( desktop() && desktop()->isShown() )
- SUIT_MessageBox::error1( desktop(), tr( "ERROR_TLT" ), tr( "ERROR_ACTIVATE_MODULE_MSG" ).arg( myModule->moduleName() ), tr( "BUT_OK" ) );
+ if ( desktop() && desktop()->isVisible() )
+ SUIT_MessageBox::critical( desktop(), tr( "ERROR_TLT" ), tr( "ERROR_ACTIVATE_MODULE_MSG" ).arg( myModule->moduleName() ) );
else
- qWarning( tr( "ERROR_ACTIVATE_MODULE_MSG" ).arg( myModule->moduleName() ).latin1() );
+ qWarning( tr( "ERROR_ACTIVATE_MODULE_MSG" ).arg( myModule->moduleName() ).toLatin1().data() );
myModule = 0;
return false;
}
return true;
}
-//@}
-/*!Create new study for current application.
- *\retval study pointer.
- */
+/*!
+ \brief Create new study.
+ \return study object pointer
+*/
SUIT_Study* CAM_Application::createNewStudy()
{
return new CAM_Study( this );
}
-/*!Update commands status for parent class and for current class(if module is active)*/
+/*!
+ \brief Update menu commands status.
+*/
void CAM_Application::updateCommandsStatus()
{
STD_Application::updateCommandsStatus();
activeModule()->updateCommandsStatus();
}
-/*!Close all modules in study \a theDoc.
- *\param theDoc - study
- */
+/*!
+ \brief Prepare application to study closing.
+
+ Closes all modules in study \a theDoc.
+
+ \param theDoc study
+*/
void CAM_Application::beforeCloseDoc( SUIT_Study* theDoc )
{
- for ( ModuleListIterator it( myModules ); it.current(); ++it )
- it.current()->studyClosed( theDoc );
+ for ( QList<CAM_Module*>::iterator it = myModules.begin(); it != myModules.end(); ++it )
+ (*it)->studyClosed( theDoc );
}
-/*!Sets active study for parent class.
- *\param study - study.
- */
+/*!
+ \brief Set active study.
+ \param study study to be made active
+*/
void CAM_Application::setActiveStudy( SUIT_Study* study )
{
STD_Application::setActiveStudy( study );
}
-/*!Do nothing.*/
-void CAM_Application::moduleAdded( CAM_Module* mod )
-{
-// CAM_Study* study = dynamic_cast<CAM_Study*>( activeStudy() );
-// if ( !study )
-// return;
+/*!
+ \brief Callback function, called when the module is added to the application.
+
+ This virtual method can be re-implemented in the successors. Base implementation
+ does nothing.
-// study->insertDataModel( mod->dataModel() );
+ \param mod module being added
+*/
+void CAM_Application::moduleAdded( CAM_Module* /*mod*/ )
+{
}
-/*!Gets module name by title \a title
- *\param title - title name
- *\retval QString module name.
- */
+/*!
+ \brief Get module name by its title (user name).
+ \param title module title (user name)
+ \return module name or null QString if module is not found
+*/
QString CAM_Application::moduleName( const QString& title ) const
{
QString res;
return res;
}
-/*!Gets module title by module name \a name
- *\param name - module name
- *\retval QString module title.
- */
+/*!
+ \brief Get module title (user name) by its name.
+ \param name module name
+ \return module title (user name) or null QString if module is not found
+*/
QString CAM_Application::moduleTitle( const QString& name ) const
{
QString res;
return res;
}
-/*!Get library name for module with title \a title.
- *\param title - module title name.
- *\param full - boolean flag (if true - return full library name, else internal name)
- *\retval QString - library name.
+/*!
+ \brief Get module library name by its title (user name).
+ \param title module title (user name)
+ \param full if \c true, return full library name, otherwise return its internal name
+ \return module library name or null QString if module is not found
*/
QString CAM_Application::moduleLibrary( const QString& title, const bool full ) const
{
return res;
}
-/*!Read modules list*/
+/*!
+ \brief Read modules information list
+
+ This function first tries to get the modules names list by parsing
+ the application command line arguments, looking for the
+ "--modules ( <mod_name>[:<mod_name>...] )" option.
+ List of modules is separated by colon symbol (":").
+
+ If "--modules" command line option is not used, the list of modules
+ is retrieved from the application resource file: parameter "modules" of
+ the section "launch".
+
+ Then the information about each module (module title (user name),
+ library name) is retrieved from the corresponding section of resource
+ file with help of resources manager.
+
+ Shows the warning message, if module information list is empty.
+
+ \sa SUIT_ResourceMgr
+*/
void CAM_Application::readModuleList()
{
if ( !myInfoList.isEmpty() )
QStringList modList;
- QStringList args;
- for (int i = 1; i < qApp->argc(); i++)
- args.append( qApp->argv()[i] );
+ QStringList args = QApplication::arguments();
QRegExp rx("--modules\\s+\\(\\s*(.*)\\s*\\)");
rx.setMinimal( true );
- if ( rx.search( args.join(" ") ) >= 0 && rx.capturedTexts().count() > 0 ) {
- QString modules = rx.capturedTexts()[1];
- QStringList mods = QStringList::split(":",modules,false);
- for ( uint i = 0; i < mods.count(); i++ ) {
- if ( !mods[i].stripWhiteSpace().isEmpty() )
- modList.append( mods[i].stripWhiteSpace() );
+ if ( rx.indexIn( args.join(" ") ) >= 0 && rx.numCaptures() > 0 ) {
+ QString modules = rx.cap(1);
+ QStringList mods = modules.split( ":", QString::SkipEmptyParts );
+ for ( int i = 0; i < mods.count(); i++ ) {
+ if ( !mods[i].trimmed().isEmpty() )
+ modList.append( mods[i].trimmed() );
}
}
if ( modList.isEmpty() ) {
QString mods = resMgr->stringValue( "launch", "modules", QString::null );
- modList = QStringList::split( ",", mods );
+ modList = mods.split( ",", QString::SkipEmptyParts );
}
for ( QStringList::const_iterator it = modList.begin(); it != modList.end(); ++it )
{
- QString modName = (*it).stripWhiteSpace();
+ QString modName = (*it).trimmed();
if ( modName.isEmpty() )
continue;
- QString modTitle = resMgr->stringValue( *it, QString( "name" ), QString::null );
+ QString modTitle = resMgr->stringValue( *it, "name", QString::null );
if ( modTitle.isEmpty() )
{
printf( "****************************************************************\n" );
- printf( "* Warning: %s not found in resources.\n", (*it).latin1() );
+ printf( "* Warning: %s not found in resources.\n", (*it).toLatin1().data() );
printf( "* Module will not be available\n" );
printf( "****************************************************************\n" );
continue;
}
- QString modLibrary = resMgr->stringValue( *it, QString( "library" ), QString::null ).stripWhiteSpace();
+ QString modLibrary = resMgr->stringValue( *it, "library", QString::null ).trimmed();
if ( !modLibrary.isEmpty() )
{
- QString libExt;
- modLibrary = SUIT_Tools::file( modLibrary.stripWhiteSpace() );
- libExt = QString( "so" );
- if ( SUIT_Tools::extension( modLibrary ).lower() == libExt )
- modLibrary = modLibrary.mid( 0, modLibrary.length() - libExt.length() - 1 );
- libExt = QString( "dll" );
- if ( SUIT_Tools::extension( modLibrary ).lower() == libExt )
- modLibrary = modLibrary.mid( 0, modLibrary.length() - libExt.length() - 1 );
+ modLibrary = SUIT_Tools::file( modLibrary.trimmed() );
+#ifdef WIN32
+ QString libExt = QString( "dll" );
+#else
+ QString libExt = QString( "so" );
+#endif
+ if ( SUIT_Tools::extension( modLibrary ).toLower() == libExt )
+ modLibrary.truncate( modLibrary.length() - libExt.length() - 1 );
#ifndef WIN32
- if ( modLibrary.startsWith( "lib" ) )
- modLibrary = modLibrary.mid( 3 );
+ QString prefix = QString( "lib" );
+ if ( modLibrary.startsWith( prefix ) )
+ modLibrary.remove( 0, prefix.length() );
#endif
}
else
}
if ( myInfoList.isEmpty() ) {
- if ( desktop() && desktop()->isShown() )
- SUIT_MessageBox::warn1( desktop(), tr( "Warning" ), tr( "Modules list is empty" ), tr( "&OK" ) );
+ if ( desktop() && desktop()->isVisible() )
+ SUIT_MessageBox::warning( desktop(), tr( "Warning" ), tr( "Modules list is empty" ) );
else
{
printf( "****************************************************************\n" );
}
}
-/*!Add common items for popup menu ( if they are exist )
- *\param type - type of popup menu
- *\param thePopup - popup menu
- *\param title - title of popup menu
- */
-void CAM_Application::contextMenuPopup( const QString& type, QPopupMenu* thePopup, QString& title )
+/*!
+ \brief Add common menu items to the popup menu.
+
+ Menu items list is defined by the active module.
+
+ \param type popup menu context
+ \param menu popup menu
+ \param title popup menu title, which can be set by the module if required
+*/
+void CAM_Application::contextMenuPopup( const QString& type, QMenu* menu, QString& title )
{
// to do : add common items for popup menu ( if they are exist )
if ( activeModule() )
- activeModule()->contextMenuPopup( type, thePopup, title );
+ activeModule()->contextMenuPopup( type, menu, title );
}
-/*!Create empty study.*/
+/*!
+ \brief Create new empty study.
+*/
void CAM_Application::createEmptyStudy()
{
/*SUIT_Study* study = */activeStudy();
#ifndef CAM_APPLICATION_H
#define CAM_APPLICATION_H
-#include "STD_Application.h"
+#include "CAM.h"
-#include "CAM_Module.h"
+#include <STD_Application.h>
+#include <QList>
-#include <qptrlist.h>
-
-class QPopupMenu;
+class QMenu;
+class CAM_Module;
#ifdef WIN32
#pragma warning( disable:4251 )
#endif
-/*!
- \class CAM_Application
- Defines application configuration and behaviour for application with modules.
- Every module has own data model, necessary windows and viewers, etc.
- Application provides all necessary functionality for module management
- (loading of modules/activation/deactivation, etc)
-*/
class CAM_EXPORT CAM_Application : public STD_Application
{
Q_OBJECT
public:
- typedef QPtrList<CAM_Module> ModuleList;
- typedef QPtrListIterator<CAM_Module> ModuleListIterator;
+ typedef QList<CAM_Module*> ModuleList;
public:
CAM_Application( const bool = true );
virtual void start();
CAM_Module* activeModule() const;
- CAM_Module* module( const QString& ) const;
+ CAM_Module* module( const QString& ) const;
- /** @name Modules lists.*/
- //@{
- ModuleListIterator modules() const;
+ ModuleList modules() const;
void modules( ModuleList& ) const;
void modules( QStringList&, const bool loaded = true ) const;
- //@}
virtual void addModule( CAM_Module* );
virtual bool activateModule( const QString& );
- virtual void contextMenuPopup( const QString&, QPopupMenu*, QString& );
+ virtual void contextMenuPopup( const QString&, QMenu*, QString& );
QString moduleName( const QString& ) const;
QString moduleTitle( const QString& ) const;
private:
typedef struct { QString name, title, internal; } ModuleInfo;
- typedef QValueList<ModuleInfo> ModuleInfoList;
+ typedef QList<ModuleInfo> ModuleInfoList;
private:
- CAM_Module* myModule;
- ModuleList myModules;
- ModuleInfoList myInfoList;
- bool myAutoLoad;
+ CAM_Module* myModule; //!< active module
+ ModuleList myModules; //!< loaded modules list
+ ModuleInfoList myInfoList; //!< modules info list
+ bool myAutoLoad; //!< auto loading flag
};
#ifdef WIN32
#include "CAM_DataModel.h"
#include "CAM_Module.h"
-#include "CAM_RootObject.h"
+#include "CAM_DataObject.h"
-/*!Constructor. Initialise module by \a module.*/
+/*!
+ \class CAM_DataModel
+ \brief Base class for all data models used in CAM-based applications.
+
+ Represents data model of the CAM module. Provides necessary interface
+ (default implementation is empty).
+*/
+
+/*!
+ \brief Constructor.
+
+ Initialise data module by specified \a module.
+*/
CAM_DataModel::CAM_DataModel( CAM_Module* module )
: myRoot( 0 ),
-myModule( module )
+ myModule( module )
{
}
-/*!Destructor. Do nothing.*/
+/*!
+ \brief Destructor.
+
+ Does nothing.
+*/
CAM_DataModel::~CAM_DataModel()
{
}
/*!
- Default implementation, does nothing.
- Can be used for creation of root object.
+ \brief Initialize data model.
+
+ This method should be re-implemented in the successor classes
+ and can be used for creation of root data object.
+ Default implementation does nothing.
*/
void CAM_DataModel::initialize()
{
}
-/*!Get root object.
- *\retval CAM_DataObject pointer - root object.
- */
+/*!
+ \brief Get data model root object.
+ \return root object
+ \sa setRoot()
+*/
CAM_DataObject* CAM_DataModel::root() const
{
return myRoot;
}
-/*!Sets root object to \a newRoot.\n
- *Emit root changed, if it was.
- *\param newRoot - new root object
- */
+/*!
+ \brief Set data model root object.
+
+ This method should be used to specify custom root object instance.
+
+ Root object can be created in several ways, depending on application or module needs:
+ - in initialize() method
+ - while the data model is being loaded
+ - when the data model is updated and becomes non-empty
+
+ If root object is changed, this method emits rootChanged() signal.
+
+ \param newRoot new root object
+*/
void CAM_DataModel::setRoot( const CAM_DataObject* newRoot )
{
if ( myRoot == newRoot )
emit rootChanged( this );
}
-/*!Gets module.
- *\retval CAM_Module pointer - module.
- */
+/*!
+ \brief Get module.
+ \return module owning this data model
+*/
CAM_Module* CAM_DataModel::module() const
{
return myModule;
}
-/*!Nullify root, if \a obj equal root.*/
+/*!
+ \brief Called when data object is destroyed.
+
+ Nullifies the root object if it is detroyed to avoid crashes.
+
+ \param obj object being destroyed
+*/
void CAM_DataModel::onDestroyed( SUIT_DataObject* obj )
{
if ( myRoot == obj )
myRoot = 0;
}
+
+/*!
+ \brief Load data model.
+
+ This method should be re-implemented in the successor classes.
+ Default implementation returns \c true.
+
+ \param name study name
+ \param study study
+ \param files list of file names from which data should be loaded
+ \return \c true if data model is loaded successfully
+*/
+bool CAM_DataModel::open( const QString& /*name*/,
+ CAM_Study* /*study*/,
+ QStringList /*files*/ )
+{
+ return true;
+}
+
+/*!
+ \brief Save data model.
+
+ This method should be re-implemented in the successor classes.
+ Default implementation returns \c true.
+
+ \param files list of file names to which data should be saved
+ \return \c true if data model is saved successfully
+*/
+bool CAM_DataModel::save( QStringList& )
+{
+ return true;
+}
+
+/*!
+ \brief Save data to the new file.
+
+ This method should be re-implemented in the successor classes.
+ Default implementation returns \c true.
+
+ \param name study name
+ \param study study
+ \param files resulting list of file names to which data is saved
+ \return \c true if data model is saved successfully
+*/
+bool CAM_DataModel::saveAs( const QString& /*name*/,
+ CAM_Study* /*study*/,
+ QStringList& /*files*/ )
+{
+ return true;
+}
+
+/*!
+ \brief Close data model.
+
+ This method should be re-implemented in the successor classes.
+ Default implementation returns \c true.
+
+ \return \c true if data model is closed successfully
+*/
+bool CAM_DataModel::close()
+{
+ return true;
+}
+
+/*!
+ \brief Create empty data model.
+
+ This method should be re-implemented in the successor classes.
+ Default implementation returns \c true.
+
+ \return \c true if data model is created successfully
+*/
+bool CAM_DataModel::create( CAM_Study* )
+{
+ return true;
+}
+
+/*!
+ \fn void CAM_DataModel::rootChanged( const CAM_DataModel* root );
+ \brief Emitted when the root data object is changed.
+ \param root new root data object
+*/
#include "CAM.h"
-#include <qobject.h>
-#include <qstringlist.h>
+#include <QObject>
+#include <QStringList>
class CAM_Module;
class CAM_DataObject;
class CAM_Study;
class SUIT_DataObject;
-/*!
- \class CAM_DataModel
- Base class for all data models used in CAM-based applications.
- Represents data model of CAM module. Provides necessary interface (default implementation is empty)
-*/
class CAM_EXPORT CAM_DataModel : public QObject
{
Q_OBJECT
CAM_DataObject* root() const;
CAM_Module* module() const;
- /** @name These methods should be redefined in successors.*/
- //@{
- virtual bool open( const QString&, CAM_Study*, QStringList ) { return true; }//!< return true
- virtual bool save( QStringList& ) { return true; };
- virtual bool saveAs( const QString&, CAM_Study*, QStringList& ) { return true; };
- virtual bool close() { return true; };
- virtual bool create( CAM_Study* ) { return true; }
- //@}
+ virtual bool open( const QString&, CAM_Study*, QStringList );
+ virtual bool save( QStringList& );
+ virtual bool saveAs( const QString&, CAM_Study*, QStringList& );
+ virtual bool close();
+ virtual bool create( CAM_Study* );
protected:
- /*! setRoot() should be used to specify custom root object instance.\n
- * Such an object can be created in several ways, depending on application or module needs:\n
- * \li by initialize()
- * \li while the model is being loaded
- * \li when the model is updated and becomes non-empty
- */
virtual void setRoot( const CAM_DataObject* );
private slots:
void rootChanged( const CAM_DataModel* );
private:
- CAM_DataObject* myRoot;
- CAM_Module* myModule;
+ CAM_DataObject* myRoot; //!< root data object
+ CAM_Module* myModule; //!< module
};
#endif
#include "CAM_Module.h"
#include "CAM_DataModel.h"
-/*!Constructor. Sets parent object.*/
+/*!
+ \class CAM_DataObject
+ \brief CAM-based implementation of data object.
+
+ In addition to base implementation provides integration
+ with CAM_DataModel.
+*/
+
+/*!
+ \brief Constructor.
+ \param parent parent data object
+*/
CAM_DataObject::CAM_DataObject( SUIT_DataObject* parent )
: SUIT_DataObject( parent )
{
}
-/*!Destructor.Do nothing*/
+/*!
+ \brief Destructor.
+
+ Does nothing.
+*/
CAM_DataObject::~CAM_DataObject()
{
}
-/*!Get module.
- *\retval const CAM_Module pointer - module
- */
+/*!
+ \brief Get CAM module.
+ \return parent module object pointer
+*/
CAM_Module* CAM_DataObject::module() const
{
CAM_Module* mod = 0;
return mod;
}
-/*!Get data model.
- *Return 0 - if no parent obbject.
- *\retval const CAM_DataModel pointer - data model
- */
+/*!
+ \brief Get CAM data model.
+ \return data model or 0 if it is not set
+ \sa CAM_RootObject class
+*/
CAM_DataModel* CAM_DataObject::dataModel() const
{
CAM_DataObject* parentObj = dynamic_cast<CAM_DataObject*>( parent() );
class CAM_Module;
class CAM_DataModel;
-/*!
- \class CAM_DataObject
- Provides only additional link to CAM_DataModel
-*/
class CAM_EXPORT CAM_DataObject : public SUIT_DataObject
{
public:
#include <QtxActionMenuMgr.h>
#include <QtxActionToolMgr.h>
+#include <SUIT_Desktop.h>
#include <SUIT_Session.h>
-#include <SUIT_Application.h>
-/*!Icon.*/
+/*! Default module icon data set */
static const char* ModuleIcon[] = {
"20 20 2 1",
" c None",
" .. .. .. .. .. .. ",
" ... ... ... "};
+/*! Default module icon pixmap */
QPixmap MYPixmap( ModuleIcon );
-/*!Constructor.*/
+/*!
+ \class CAM_Module
+ \brief Base implementation of the module in the CAM application architecture.
+
+ Provides support of menu/toolbars management.
+*/
+
+/*!
+ \brief Default constructor.
+
+ Creates unnamed module.
+*/
CAM_Module::CAM_Module()
: QObject(),
-myApp( 0 ),
-myIcon( MYPixmap ),
-myDataModel( 0 )
+ myApp( 0 ),
+ myIcon( MYPixmap ),
+ myDataModel( 0 )
{
}
-/*!Constructor. initialize \a name.*/
+/*!
+ \brief Constructor.
+
+ Creates module with the specified \a name.
+
+ \param name module name
+*/
CAM_Module::CAM_Module( const QString& name )
: QObject(),
-myApp( 0 ),
-myName( name ),
-myIcon( MYPixmap ),
-myDataModel( 0 )
+ myApp( 0 ),
+ myName( name ),
+ myIcon( MYPixmap ),
+ myDataModel( 0 )
{
}
-/*!Destructor. Remove data model.*/
+/*!
+ \brief Destructor.
+
+ Destroy data model.
+*/
CAM_Module::~CAM_Module()
{
delete myDataModel;
myDataModel = 0;
}
-/*!Initialize application.*/
+/*!
+ \brief Initialize module.
+
+ This method is usually called when the module is created (for example,
+ on the module library loading).
+ Successor classes can use this method to create menu/toolbar actions
+ and perform other module initialization.
+
+ \param app parent application object
+ \sa activateModule(), deactivateModule()
+*/
void CAM_Module::initialize( CAM_Application* app )
{
myApp = app;
}
}
-/*!\retval Module icon.*/
+/*!
+ \brief Get module icon.
+ \return module icon pixmap
+ \sa setModuleIcon(), iconName()
+*/
QPixmap CAM_Module::moduleIcon() const
{
return myIcon;
}
-/*!\retval Module icon name.*/
+/*!
+ \brief Get module icon's name.
+
+ This function is used to get module icon's file name.
+ Default implementation returns empty string.
+
+ \return module icon's name.
+ \sa moduleIcon(), setModuleIcon()
+*/
QString CAM_Module::iconName() const
{
return "";
}
-/*!\retval Module name.*/
+/*!
+ \brief Get module (internal) name
+ \return module name
+ \sa setName(), moduleName(), setModuleName()
+*/
+QString CAM_Module::name() const
+{
+ return objectName();
+}
+
+/*!
+ \brief Get module title (user name)
+ \return module title
+ \sa setModuleName(), name(), setName()
+*/
QString CAM_Module::moduleName() const
{
return myName;
}
-/*! \brief Return data model.
- * Create data model, if it was't created before.
- */
+/*!
+ \brief Get data model.
+
+ Creates data model, if it is not yet created.
+
+ \return data model pointer
+ \sa createDataModel()
+*/
CAM_DataModel* CAM_Module::dataModel() const
{
if ( !myDataModel )
return myDataModel;
}
-/*!\retval CAM_Application pointer - application.*/
+/*!
+ \brief Get application.
+ \return application pointer
+*/
CAM_Application* CAM_Module::application() const
{
return myApp;
}
-/*!Public slot
- * \retval true.
+/*!
+ \brief Activate module.
+
+ This method is called when the user activates module.
+ Successor classes can use this method to customize module activation process,
+ for example, to show own menus, toolbars, etc.
+
+ Default implementation always returns \c true.
+
+ \return \c true if module is activated successfully.
+ \sa initialize(), deactivateModule()
*/
-bool CAM_Module::activateModule( SUIT_Study* study )
+bool CAM_Module::activateModule( SUIT_Study* /*study*/ )
{
return true;
}
-/*!Public slot
- * \retval true.
+/*!
+ \brief Deactivate module.
+
+ This method is called when the user deactivates module.
+ Successor classes can use this method to customize module deactivation process,
+ for example, to hide own menus, toolbars, etc.
+
+ Default implementation always returns \c true.
+
+ \return \c true if module is deactivated successfully.
+ \sa initialize(), activateModule()
*/
bool CAM_Module::deactivateModule( SUIT_Study* )
{
return true;
}
-/*!Public slot, remove data model from \a study.*/
+/*!
+ \brief Called when study is closed.
+
+ Removes data model from the \a study.
+
+ \param study study being closed
+*/
void CAM_Module::studyClosed( SUIT_Study* study )
{
CAM_Study* camDoc = dynamic_cast<CAM_Study*>( study );
}
}
-/*!Public slot, do nothing.*/
-void CAM_Module::studyChanged( SUIT_Study* , SUIT_Study* )
+/*!
+ \brief Called when study is changed (obsolete).
+
+ Default implementation does nothing.
+
+ \param oldStudy old study
+ \param newStudy new study
+*/
+void CAM_Module::studyChanged( SUIT_Study* /*oldStudy*/, SUIT_Study* /*newStudy*/ )
{
}
-/*!Return true if module is active.*/
+/*!
+ \brief Check if the module is active.
+ \return \c true if module is active.
+*/
bool CAM_Module::isActiveModule() const
{
return application() ? application()->activeModule() == this : false;
}
/*!
- Put the message into the status bar of the desktop. Message will be displayed
- during specified \amscec milliseconds. If parameter \amsec is negative then
- message will be persistently displayed when module is active.
+ \brief Put the text message into the status bar of the application main window.
+
+ If \a msec > 0, the message will be shown \a msec milliseconds.
+ If \a msec < 0, the message will be constantly displayed until module is active.
+
+ \param msg text message
+ \param msec message displaying duration in milliseconds
*/
void CAM_Module::putInfo( const QString& msg, const int msec )
{
}
/*!
- Restore persistently displayed info string when previos information status string erasing
- if module is active.
+ \brief Restore message info.
+
+ Restores constant text message when previous information status message is removed.
+
+ \param txt previous message (being removed)
+ \sa putInfo()
*/
void CAM_Module::onInfoChanged( QString txt )
{
application()->putInfo( myInfo );
}
+/*!
+ \brief Called when application is closed.
+ Nullify application pointer if the application is being closed.
-/*!Public slot, nullify application pointer if the application was closed.*/
+ \param theApp application
+*/
void CAM_Module::onApplicationClosed( SUIT_Application* theApp )
{
if (myApp == theApp)
myApp = NULL;
}
-/*!Create and return new instance of CAM_DataModel.*/
+/*!
+ \brief Create data model.
+ \return created data model object or 0 if it could not be created
+*/
CAM_DataModel* CAM_Module::createDataModel()
{
return new CAM_DataModel( this );
}
-/*!Sets module name to \a name.
- * \param name - new name for module.
+/*!
+ \brief Set module (internal) name
+ \param name new module name
+ \sa name(), moduleName(), setModuleName()
+ */
+void CAM_Module::setName( const QString& name )
+{
+ setObjectName( name );
+}
+
+/*!
+ \brief Set module title (user name)
+ \param name new module title
+ \sa moduleName(), name(), setName()
*/
void CAM_Module::setModuleName( const QString& name )
{
myName = name;
}
-/*!Sets module icon to \a icon.
- * \param icon - new icon for module.
- */
+/*!
+ \brief Set module icon.
+ \param icon new module icon
+ \sa moduleIcon(), iconName()
+*/
void CAM_Module::setModuleIcon( const QPixmap& icon )
{
myIcon = icon;
}
-/*! Return menu manager pointer.
- * \retval QtxActionMenuMgr pointer - menu manager.
- */
+/*!
+ \brief Get menu manager.
+ \return menu manager pointer
+*/
QtxActionMenuMgr* CAM_Module::menuMgr() const
{
QtxActionMenuMgr* mgr = 0;
return mgr;
}
-/*! Return tool manager pointer.
- * \retval QtxActionToolMgr pointer - tool manager.
- */
+/*!
+ \brief Get toolbar manager.
+ \return toolbar manager pointer
+*/
QtxActionToolMgr* CAM_Module::toolMgr() const
{
QtxActionToolMgr* mgr = 0;
return mgr;
}
-/*! Create tool bar with name \a name, if it was't created before.
- * \retval -1 - if tool manager was't be created.
- */
+/*!
+ \brief Create toolbar with speicifed \a name.
+
+ If the toolbar has been already created, its ID is just returned.
+
+ \param name toolbar name
+ \return toolbar ID or -1 if toolbar could not be created
+*/
int CAM_Module::createTool( const QString& name )
{
if ( !toolMgr() )
return toolMgr()->createToolBar( name );
}
-/*! Create tool. Register action \a a with id \a id.
- * Insert QAction to tool manager.
- *\param a - QAction
- *\param tBar - integer
- *\param id - integer
- *\param idx - integer
- *\retval integer id of new action in tool manager.
- *\retval Return -1 if something wrong.
- */
+/*!
+ \brief Add toolbar item.
+
+ Insert action \a to the toolbar manager and register it with specified \a id.
+ Resulting action ID may differ from the requested one. This can happen if
+ requested ID is already in use.
+
+ If action has been already added previously, its ID is just returned.
+
+ If \a id < 0, the action ID is generated automatically.
+
+ If \a idx < 0, the action is added to the end of the toolbar.
+
+ \param a action
+ \param tBar toolbar ID
+ \param id requested action ID
+ \param idx action index (desired position in the toolbar)
+ \return action ID or -1 if toolbar item could not be added
+*/
int CAM_Module::createTool( QAction* a, const int tBar, const int id, const int idx )
{
if ( !toolMgr() )
return intId != -1 ? regId : -1;
}
-/*! Create tool. Register action \a a with id \a id.
- * Insert QAction to tool manager.
- *\param a - QAction
- *\param tBar - QString&
- *\param id - integer
- *\param idx - integer
- *\retval integer id of new action in tool manager.
- *\retval Return -1 if something wrong.
- */
+/*!
+ \brief Add toolbar item.
+
+ Insert action \a to the toolbar manager and register it with specified \a id.
+ Resulting action ID may differ from the requested one. This can happen if
+ requested ID is already in use.
+
+ If action has been already added previously, its ID is just returned.
+
+ If \a id < 0, the action ID is generated automatically.
+
+ If \a idx < 0, the action is added to the end of the toolbar.
+
+ \param a action
+ \param tBar toolbar name
+ \param id requested action ID
+ \param idx action index (desired position in the toolbar)
+ \return action ID or -1 if toolbar item could not be added
+*/
int CAM_Module::createTool( QAction* a, const QString& tBar, const int id, const int idx )
{
if ( !toolMgr() )
return intId != -1 ? regId : -1;
}
-/*! Create tool.
- * Insert QAction with id \a id from action map(myActionMap) to tool manager.
- *\param id - integer
- *\param tBar - integer
- *\param idx - integer
- *\retval integer id of new action in tool manager.
- *\retval Return -1 if something wrong.
- */
+/*!
+ \brief Add toolbar item.
+
+ Insert action with \a id identifier to the toolbar manager.
+ It is assumed that action has been already registered.
+
+ Resulting action ID may differ from the requested one. This can happen if
+ requested ID is already in use.
+
+ If action has been already added previously, its ID is just returned.
+
+ If \a idx < 0, the action is added to the end of the toolbar.
+
+ \param id action ID
+ \param tBar toolbar ID
+ \param idx action index (desired position in the toolbar)
+ \return action ID or -1 if toolbar item could not be added
+*/
int CAM_Module::createTool( const int id, const int tBar, const int idx )
{
if ( !toolMgr() )
return intId != -1 ? id : -1;
}
-/*! Create tool.
- * Insert QAction with id \a id from action map(myActionMap) to tool manager.
- *\param id - integer
- *\param tBar - QString&
- *\param idx - integer
- *\retval integer id of new action in tool manager.
- *\retval Return -1 if something wrong.
- */
+/*!
+ \brief Add toolbar item.
+
+ Insert action with \a id identifier to the toolbar manager.
+ It is assumed that action has been already registered.
+
+ Resulting action ID may differ from the requested one. This can happen if
+ requested ID is already in use.
+
+ If action has been already added previously, its ID is just returned.
+
+ If \a idx < 0, the action is added to the end of the toolbar.
+
+ \param id action ID
+ \param tBar toolbar name
+ \param idx action index (desired position in the toolbar)
+ \return action ID or -1 if toolbar item could not be added
+*/
int CAM_Module::createTool( const int id, const QString& tBar, const int idx )
{
if ( !toolMgr() )
return intId != -1 ? id : -1;
}
-/*! Create menu.
- * Insert submenu \a subMenu to menu manager.
- *\param subMenu - QString&
- *\param menu - integer
- *\param id - integer
- *\param group - integer
- *\param index - integer
- *\retval integer id of new menu in tool manager.
- *\retval Return -1 if something wrong.
- */
+/*!
+ \brief Create menu or submenu.
+
+ Create main menu or popup submenu and register it with specified \a id.
+ Resulting action ID may differ from the requested one. This can happen if
+ requested ID is already in use.
+
+ If \a id < 0, the menu ID is generated automatically.
+ If menu has been already created previously, its ID is just returned.
+
+ The \a menu parameter represents the menu name - it could be a sequence
+ of strings, separated by '|' symbol. For example, "File|Edit" means
+ File->Edit submenu. If menu doesn't exist, it is created automatically.
+
+ Parameter \a idx defines the index of the menu item in the menu group which
+ is defined by the \a group. If \a idx < 0, the menu/submenu is added to the
+ end of the menu group.
+
+ \param subMenu subMenu name
+ \param menu parent menu ID
+ \param id requested menu ID
+ \param group menu group ID
+ \param idx menu item index (desired position in the menu group)
+ \return menu item ID or -1 if menu item could not be added
+*/
int CAM_Module::createMenu( const QString& subMenu, const int menu,
- const int id, const int group, const int index,
- const bool enableEmpty )
+ const int id, const int group, const int idx )
{
if ( !menuMgr() )
return -1;
- return menuMgr()->insert( subMenu, menu, group, id, index, enableEmpty );
+ return menuMgr()->insert( subMenu, menu, group, id, idx );
}
-/*! Create menu.
- * Insert submenu \a subMenu to menu manager.
- *\param subMenu - QString&
- *\param menu - QString&
- *\param id - integer
- *\param group - integer
- *\param index - integer
- *\retval integer id of new menu in tool manager.
- *\retval Return -1 if something wrong.
- */
+/*!
+ \brief Create menu or submenu.
+
+ Create main menu or popup submenu and register it with specified \a id.
+ Resulting action ID may differ from the requested one. This can happen if
+ requested ID is already in use.
+
+ If \a id < 0, the menu ID is generated automatically.
+ If menu has been already created previously, its ID is just returned.
+
+ The \a menu parameter represents the menu name - it could be a sequence
+ of strings, separated by '|' symbol. For example, "File|Edit" means
+ File->Edit submenu. If menu doesn't exist, it is created automatically.
+
+ Parameter \a idx defines the index of the menu item in the menu group which
+ is defined by the \a group. If \a idx < 0, the menu/submenu is added to the
+ end of the menu group.
+
+ \param subMenu subMenu name
+ \param menu parent menu name(s)
+ \param id requested menu ID
+ \param group menu group ID
+ \param idx menu item index (desired position in the menu group)
+ \return menu item ID or -1 if menu item could not be added
+*/
int CAM_Module::createMenu( const QString& subMenu, const QString& menu,
- const int id, const int group, const int index,
- const bool enableEmpty )
+ const int id, const int group, const int idx )
{
if ( !menuMgr() )
return -1;
- return menuMgr()->insert( subMenu, menu, group, id, index, enableEmpty );
+ return menuMgr()->insert( subMenu, menu, group, id, idx );
}
+/*!
+ \brief Add menu item.
-/*! Create menu. Register action \a a with id \a id.
- * Insert QAction to menu manager.
- *\param a - Qaction
- *\param menu - integer
- *\param id - integer
- *\param group - integer
- *\param index - integer
- *\retval integer id of new menu in tool manager.
- *\retval Return -1 if something wrong.
- */
-int CAM_Module::createMenu( QAction* a, const int menu, const int id, const int group, const int index )
+ Insert action \a to the menu manager and register it with specified \a id.
+ Resulting action ID may differ from the requested one. This can happen if
+ requested ID is already in use.
+
+ If \a id < 0, the action ID is generated automatically.
+
+ If action has been already added previously, its ID is just returned.
+
+ Parameter \a idx defines the index of the menu item in the menu group which
+ is defined by the \a group. If \a idx < 0, the action is added to the
+ end of the menu group.
+
+ \param a action
+ \param menu menu ID
+ \param id requested action ID
+ \param group menu group ID
+ \param idx action index (desired position in the menu group)
+ \return action ID or -1 if menu item could not be added
+*/
+int CAM_Module::createMenu( QAction* a, const int menu, const int id, const int group, const int idx )
{
if ( !a || !menuMgr() )
return -1;
int regId = registerAction( id, a );
- int intId = menuMgr()->insert( a, menu, group, index );
+ int intId = menuMgr()->insert( a, menu, group, idx );
return intId != -1 ? regId : -1;
}
-/*! Create menu. Register action \a a with id \a id.
- * Insert QAction to menu manager.
- *\param a - Qaction
- *\param menu - QString&
- *\param id - integer
- *\param group - integer
- *\param index - integer
- *\retval integer id of new menu in tool manager.
- *\retval Return -1 if something wrong.
- */
-int CAM_Module::createMenu( QAction* a, const QString& menu, const int id, const int group, const int index )
+/*!
+ \brief Add menu item.
+
+ Insert action \a to the menu manager and register it with specified \a id.
+ Resulting action ID may differ from the requested one. This can happen if
+ requested ID is already in use.
+
+ If \a id < 0, the action ID is generated automatically.
+
+ If action has been already added previously, its ID is just returned.
+
+ The \a menu parameter represents the menu name - it could be a sequence
+ of strings, separated by '|' symbol. For example, "File|Edit" means
+ File->Edit submenu. If menu doesn't exist, it is created automatically.
+
+ Parameter \a idx defines the index of the menu item in the menu group which
+ is defined by the \a group. If \a idx < 0, the action is added to the
+ end of the menu group.
+
+ \param a action
+ \param menu menu name(s)
+ \param id requested action ID
+ \param group menu group ID
+ \param idx action index (desired position in the menu group)
+ \return action ID or -1 if menu item could not be added
+*/
+int CAM_Module::createMenu( QAction* a, const QString& menu, const int id, const int group, const int idx )
{
if ( !a || !menuMgr() )
return -1;
int regId = registerAction( id, a );
- int intId = menuMgr()->insert( a, menu, group, index );
+ int intId = menuMgr()->insert( a, menu, group, idx );
return intId != -1 ? regId : -1;
}
-/*! Create menu.
- * Insert QAction with id \a id from action map(myActionMap) to menu manager.
- *\param menu - integer
- *\param id - integer
- *\param group - integer
- *\param index - integer
- *\retval integer id of new menu in tool manager.
- *\retval Return -1 if something wrong.
- */
-int CAM_Module::createMenu( const int id, const int menu, const int group, const int index )
+/*!
+ \brief Add menu item.
+
+ Insert action with \a id identifier to the menu manager.
+ It is assumed that action has been already registered.
+
+ Resulting action ID may differ from the requested one. This can happen if
+ requested ID is already in use.
+
+ If action has been already added previously, its ID is just returned.
+
+ Parameter \a idx defines the index of the menu item in the menu group which
+ is defined by the \a group. If \a idx < 0, the action is added to the
+ end of the menu group.
+
+ \param id action ID
+ \param menu menu ID
+ \param group menu group ID
+ \param idx action index (desired position in the menu group)
+ \return action ID or -1 if menu item could not be added
+*/
+int CAM_Module::createMenu( const int id, const int menu, const int group, const int idx )
{
if ( !menuMgr() )
return -1;
- int intId = menuMgr()->insert( action( id ), menu, group, index );
+ int intId = menuMgr()->insert( action( id ), menu, group, idx );
return intId != -1 ? id : -1;
}
-/*! Create menu.
- * Insert QAction with id \a id from action map(myActionMap) to menu manager.
- *\param menu - QString&
- *\param id - integer
- *\param group - integer
- *\param index - integer
- *\retval integer id of new menu in tool manager.
- *\retval Return -1 if something wrong.
- */
-int CAM_Module::createMenu( const int id, const QString& menu, const int group, const int index )
+/*!
+ \brief Add menu item.
+
+ Insert action with \a id identifier to the menu manager.
+ It is assumed that action has been already registered.
+
+ Resulting action ID may differ from the requested one. This can happen if
+ requested ID is already in use.
+
+ If action has been already added previously, its ID is just returned.
+
+ The \a menu parameter represents the menu name - it could be a sequence
+ of strings, separated by '|' symbol. For example, "File|Edit" means
+ File->Edit submenu. If menu doesn't exist, it is created automatically.
+
+ Parameter \a idx defines the index of the menu item in the menu group which
+ is defined by the \a group. If \a idx < 0, the action is added to the
+ end of the menu group.
+
+ \param id action ID
+ \param menu menu name(s)
+ \param group menu group ID
+ \param idx action index (desired position in the menu group)
+ \return action ID or -1 if menu item could not be added
+*/
+int CAM_Module::createMenu( const int id, const QString& menu, const int group, const int idx )
{
if ( !menuMgr() )
return -1;
- int intId = menuMgr()->insert( action( id ), menu, group, index );
+ int intId = menuMgr()->insert( action( id ), menu, group, idx );
return intId != -1 ? id : -1;
}
-/*!Sets menus shown to \a on floag.
- *\param on - flag.
- */
+/*!
+ \brief Show/hide all module's menus.
+ \param on if \c true, show menus, otherwise, hide all menus
+ \sa setToolShown()
+*/
void CAM_Module::setMenuShown( const bool on )
{
QtxActionMenuMgr* mMgr = menuMgr();
QAction* sep = separator();
for ( QMap<int, QAction*>::Iterator it = myActionMap.begin(); it != myActionMap.end(); ++it )
{
- if ( it.data() != sep )
- mMgr->setShown( mMgr->actionId( it.data() ), on );
+ if ( it.value() != sep )
+ mMgr->setShown( mMgr->actionId( it.value() ), on );
}
mMgr->setUpdatesEnabled( upd );
mMgr->update();
}
-/*!Sets menu shown for QAction \a a to \a on flag.
- * \param a - QAction
- * \param on - flag
- */
+/*!
+ \brief Show/hide specified menu item.
+ \param a action
+ \param on if \c true, show menu item, otherwise, hide it
+*/
void CAM_Module::setMenuShown( QAction* a, const bool on )
{
if ( menuMgr() )
menuMgr()->setShown( menuMgr()->actionId( a ), on );
}
-/*!Sets menu shown for action with id=\a id to \a on flag.
- * \param id - id of action
- * \param on - flag
- */
+/*!
+ \brief Show/hide specified menu item.
+ \param id menu item ID
+ \param on if \c true, show menu item, otherwise, hide it
+*/
void CAM_Module::setMenuShown( const int id, const bool on )
{
setMenuShown( action( id ), on );
}
-/*!Set tools shown to \a on flag.
- *\param on - boolean flag.
- */
+/*!
+ \brief Show/hide all module's toolbars.
+ \param on if \c true, show toolbars, otherwise, hide all toolbars
+ \sa setMenuShown()
+*/
void CAM_Module::setToolShown( const bool on )
{
QtxActionToolMgr* tMgr = toolMgr();
QAction* sep = separator();
for ( QMap<int, QAction*>::Iterator it = myActionMap.begin(); it != myActionMap.end(); ++it )
{
- if ( it.data() != sep )
- tMgr->setShown( tMgr->actionId( it.data() ), on );
+ if ( it.value() != sep )
+ tMgr->setShown( tMgr->actionId( it.value() ), on );
}
tMgr->setUpdatesEnabled( upd );
tMgr->update();
}
-/*!Set tools shown for QAction \a a to \a on flag.
- * \param a - QAction
- * \param on - boolean flag
- */
+/*!
+ \brief Show/hide specified toolbar item.
+ \param a action
+ \param on if \c true, show toolbar item, otherwise, hide it
+*/
void CAM_Module::setToolShown( QAction* a, const bool on )
{
if ( toolMgr() )
toolMgr()->setShown( toolMgr()->actionId( a ), on );
}
-/*!Set tools shown for action with id=\a id to \a on flag.
- * \param id - integer action id
- * \param on - boolean flag
- */
+/*!
+ \brief Show/hide specified toolbar item.
+ \param id toolbar item ID
+ \param on if \c true, show toolbar item, otherwise, hide it
+*/
void CAM_Module::setToolShown( const int id, const bool on )
{
setToolShown( action( id ), on );
}
-/*! Return action by id.
- * \param id - id of action.
- * \retval QAction.
- */
+/*!
+ \brief Get action by specified \a id.
+ \param id action ID
+ \return action or 0 if not found
+*/
QAction* CAM_Module::action( const int id ) const
{
QAction* a = 0;
return a;
}
-/*! Return id by action.
- * \param a - QAction.
- * \retval id of action.
- */
+/*!
+ \brief Get action ID.
+ \param a action
+ \return action ID or -1 if not found
+*/
int CAM_Module::actionId( const QAction* a ) const
{
int id = -1;
for ( QMap<int, QAction*>::ConstIterator it = myActionMap.begin(); it != myActionMap.end() && id == -1; ++it )
{
- if ( it.data() == a )
+ if ( it.value() == a )
id = it.key();
}
return id;
}
-/*! Create new instance of QtxAction and register action with \a id.
- * \param id - id for new action.
- * \param text - parameter for creation QtxAction
- * \param icon - parameter for creation QtxAction
- * \param menu - parameter for creation QtxAction
- * \param tip - tip status for QtxAction action.
- * \param key - parameter for creation QtxAction
- * \param parent - parent for action
- * \param toggle - parameter for creation QtxAction
- * \param reciever -
- * \param member -
- */
-QAction* CAM_Module::createAction( const int id, const QString& text, const QIconSet& icon,
+/*!
+ \brief Create new instance of QtxAction and register action with specified \a id.
+
+ Resulting action ID may differ from the requested one. This can happen if
+ requested ID is already in use.
+
+ If \a id < 0, the action ID is generated automatically.
+
+ \param id required action ID
+ \param text tooltip text
+ \param icon action icon
+ \param menu menu text
+ \param tip status bar tip
+ \param key keyboard accelerator
+ \param parent parent object
+ \param toggle if \c true, the action will be toggled
+ \param reciever action activation signal receiver object
+ \param member action activation signal receiver slot
+*/
+QAction* CAM_Module::createAction( const int id, const QString& text, const QIcon& icon,
const QString& menu, const QString& tip, const int key,
QObject* parent, const bool toggle, QObject* reciever, const char* member )
{
- QtxAction* a = new QtxAction( text, icon, menu, key, parent, 0, toggle );
+ QtxAction* a = new QtxAction( text, icon, menu, key, parent, toggle );
a->setStatusTip( tip );
if ( reciever && member )
return a;
}
-/*! Register action in action map.
- * \param id - id for action.
- * \param a - action
- * \retval new id for action.
- */
+/*!
+ \brief Register action in the internal action map.
+
+ If action has been already added previously, its ID is just returned.
+ If \a id < 0, the action ID is generated automatically.
+
+ \param id action required ID
+ \param a action
+ \return action ID
+*/
int CAM_Module::registerAction( const int id, QAction* a )
{
int ident = -1;
for ( QMap<int, QAction*>::ConstIterator it = myActionMap.begin(); it != myActionMap.end() && ident == -1; ++it )
- if ( it.data() == a )
+ if ( it.value() == a )
ident = it.key();
if ( ident != -1 )
return ident;
}
-/*! Unregister an action.
- * \param id - id for action.
- * \retval true if succeded, false if action is used
- */
+/*!
+ \brief Unregister action from the internal action map.
+
+ \param id action ID
+ \return \c true on success or \c false if action is in use
+*/
bool CAM_Module::unregisterAction( const int id )
{
return unregisterAction( action( id ) );
}
-/*! Unregister an action.
- * \param a - action
- * \retval true if succeded, false if action is used
- */
+/*!
+ \brief Unregister action from the internal action map.
+
+ \param a action
+ \return \c true on success or \c false if action is in use
+*/
bool CAM_Module::unregisterAction( QAction* a )
{
if ( !a )
return true;
}
-/*! Return qt action manager separator.*/
+/*!
+ \brief Create separator action.
+
+ Separator action can be used in menus or toolbars.
+
+ \return new separator action
+*/
QAction* CAM_Module::separator()
{
return QtxActionMgr::separator();
}
-/*! Connect data model of module with active study */
+/*!
+ \brief Connect data model of the module to the active study
+ \param camStudy CAM study object
+*/
void CAM_Module::connectToStudy( CAM_Study* camStudy )
{
CAM_Application* app = camStudy ? dynamic_cast<CAM_Application*>( camStudy->application() ) : 0;
return;
CAM_DataModel* prev = 0;
- for( CAM_Application::ModuleListIterator it = app->modules(); it.current(); ++it )
+ CAM_Application::ModuleList mods = app->modules();
+ for( QList<CAM_Module*>::const_iterator it = mods.begin(); it != mods.end(); ++it )
{
- CAM_DataModel* dm = it.current()->dataModel();
- if( it.current() == this && !camStudy->containsDataModel( dm ) )
+ CAM_DataModel* dm = (*it)->dataModel();
+ if( (*it) == this && !camStudy->containsDataModel( dm ) )
{
if ( prev )
- camStudy->insertDataModel( it.current()->dataModel(), prev );
+ camStudy->insertDataModel( (*it)->dataModel(), prev );
else
- camStudy->insertDataModel( it.current()->dataModel(), 0 );
+ camStudy->insertDataModel( (*it)->dataModel(), 0 );
}
prev = dm;
}
}
+
+/*!
+ \fn void CAM_Module::contextMenuPopup( const QString& type, QMenu* menu, QString& title );
+ \brief Create context popup menu.
+ \param type popup menu context
+ \param menu popup menu
+ \param title popup menu title, which can be set by the module if required
+*/
+
+/*!
+ \fn void CAM_Module::updateCommandsStatus();
+ \brief Update menu/toolbar actions.
+*/
#include "CAM.h"
-#include <qpixmap.h>
-#include <qobject.h>
-#include <qpopupmenu.h>
-#include <qstring.h>
+#include <QObject>
+#include <QPixmap>
+#include <QString>
+#include <QMap>
class QAction;
+class QMenu;
+class QIcon;
+
+class QtxActionMenuMgr;
+class QtxActionToolMgr;
class SUIT_Study;
class SUIT_Application;
class CAM_Study;
class CAM_DataModel;
class CAM_Application;
-class QtxActionMenuMgr;
-class QtxActionToolMgr;
#ifdef WIN32
#pragma warning( disable: 4251 )
#endif
-/*!
- * Class provide support of tool and menu managers.
- */
class CAM_EXPORT CAM_Module : public QObject
{
Q_OBJECT
virtual void initialize( CAM_Application* );
+ QString name() const;
QString moduleName() const;
QPixmap moduleIcon() const;
virtual QString iconName() const;
- virtual void contextMenuPopup( const QString&, QPopupMenu*, QString& title ) {};
+ virtual void contextMenuPopup( const QString&, QMenu*, QString& ) {};
virtual void updateCommandsStatus() {};
virtual void putInfo( const QString&, const int = -1 );
bool isActiveModule() const;
- /** @name Set Menu Shown*/
- //@{
virtual void setMenuShown( const bool );
void setMenuShown( QAction*, const bool );
void setMenuShown( const int, const bool );
- //@}
- /** @name Set Tool Shown*/
- //@{
virtual void setToolShown( const bool );
void setToolShown( QAction*, const bool );
void setToolShown( const int, const bool );
- //@}
public slots:
virtual bool activateModule( SUIT_Study* );
protected:
virtual CAM_DataModel* createDataModel();
+ void setName( const QString& );
virtual void setModuleName( const QString& );
virtual void setModuleIcon( const QPixmap& );
QtxActionMenuMgr* menuMgr() const;
QtxActionToolMgr* toolMgr() const;
- /** @name Create tool methods.*/
- //@{
int createTool( const QString& );
int createTool( const int, const int, const int = -1 );
int createTool( const int, const QString&, const int = -1 );
int createTool( QAction*, const int, const int = -1, const int = -1 );
int createTool( QAction*, const QString&, const int = -1, const int = -1 );
- //@}
- /** @name Create menu methods.*/
- //@{
- int createMenu( const QString&, const int, const int = -1, const int = -1, const int = -1, const bool = false );
- int createMenu( const QString&, const QString&, const int = -1, const int = -1, const int = -1, const bool = false );
+ int createMenu( const QString&, const int, const int = -1, const int = -1, const int = -1 );
+ int createMenu( const QString&, const QString&, const int = -1, const int = -1, const int = -1 );
int createMenu( const int, const int, const int = -1, const int = -1 );
int createMenu( const int, const QString&, const int = -1, const int = -1 );
int createMenu( QAction*, const int, const int = -1, const int = -1, const int = -1 );
int createMenu( QAction*, const QString&, const int = -1, const int = -1, const int = -1 );
- //@}
static QAction* separator();
- /**Action ids methods.*/
- //@{
QAction* action( const int ) const;
int actionId( const QAction* ) const;
- //@}
int registerAction( const int, QAction* );
bool unregisterAction( const int );
bool unregisterAction( QAction* );
- QAction* createAction( const int, const QString&, const QIconSet&, const QString&,
+ QAction* createAction( const int, const QString&, const QIcon&, const QString&,
const QString&, const int, QObject* = 0,
const bool = false, QObject* = 0, const char* = 0 );
private:
- CAM_Application* myApp;
- QString myName;
- QPixmap myIcon;
- QString myInfo;
- CAM_DataModel* myDataModel;
- QMap<int, QAction*> myActionMap;
+ CAM_Application* myApp; //!< parent application object
+ QString myName; //!< module title (user name)
+ QPixmap myIcon; //!< module icon
+ QString myInfo; //!< latest info message
+ CAM_DataModel* myDataModel; //!< data model
+ QMap<int, QAction*> myActionMap; //!< menu actions
friend class CAM_Application;
};
#include "CAM_DataModel.h"
#include "CAM_Module.h"
-/*!Constructor. Initialize by \a parent.
- * Set data model to 0.
- */
+/*!
+ \class CAM_RootObject
+ \brief CAM data model root object.
+
+ This class is intended for optimized access to CAM_DataModel instance
+ from CAM_DataObject instances.
+
+ To take advantage of this class in a specific application,
+ custom data model root object class should be derived from both CAM_RootObject
+ and application-specific DataObject implementation using virtual inheritance.
+*/
+
+/*!
+ \brief Constructor.
+ \param parent parent data object
+*/
CAM_RootObject::CAM_RootObject( SUIT_DataObject* parent )
: CAM_DataObject( parent ),
-myDataModel( 0 )
+ myDataModel( 0 )
{
}
-/*!Constructor. Initialize by \a parent and \a data - data object
- *\param data - data object
- *\param parent - parent data object
- */
+/*!
+ \brief Constructor.
+ \param data data model
+ \param parent parent data object
+*/
CAM_RootObject::CAM_RootObject( CAM_DataModel* data, SUIT_DataObject* parent )
: CAM_DataObject( parent ),
-myDataModel( data )
+ myDataModel( data )
{
}
-/*!Destructor. Do nothing.*/
+/*!
+ \brief Destructor.
+
+ Does nothing.
+*/
CAM_RootObject::~CAM_RootObject()
{
}
/*!
- Returns module name
+ \brief Get root object name.
+
+ If the data model is set, this method returns module name.
+ Otherwise returns empty string.
+
+ \return root object name
*/
QString CAM_RootObject::name() const
{
return aName;
}
-/*!Get data model
- *\retval const CAM_DataModel pointer to data model.
- */
+/*!
+ \brief Get data model.
+ \return data model pointer or 0 if it is not set
+*/
CAM_DataModel* CAM_RootObject::dataModel() const
{
return myDataModel;
}
-/*!Set data model.
- *\param dm - data model to set.
- */
+/*!
+ \brief Set data model.
+ \param dm data model
+*/
void CAM_RootObject::setDataModel( CAM_DataModel* dm )
{
myDataModel = dm;
#include "CAM_DataObject.h"
-/*!
- CAM_RootObject - class intended for optimized access to CAM_DataModel instance
- from CAM_DataObject instances.
-
- To take advantage of this class in a specific application,
- custom data model root object class should be derived from both CAM_RootObject
- and application-specific DataObject implementation using virtual inheritance.
- */
class CAM_EXPORT CAM_RootObject : public virtual CAM_DataObject
{
public:
#include "CAM_RootObject.h"
#include "CAM_Module.h"
-/*!Constructor.*/
+/*!
+ \class CAM_Study
+ \brief Represents document object in the CAM application architecture.
+
+ For each loaded module study contains the data model instance reference.
+ Provides all necessary functionality for data models management.
+*/
+
+/*!
+ \brief Constructor.
+ \param app parent application
+*/
CAM_Study::CAM_Study( SUIT_Application* app )
: SUIT_Study( app )
{
}
-/*!Destructor*/
+/*!
+ \brief Destructor.
+*/
CAM_Study::~CAM_Study()
{
}
-/*!Closing all data models and close document permanently(if \a permanently = true.)
- * \param permanently - flag
- */
-void CAM_Study::closeDocument(bool permanently)
+/*!
+ \brief Called when study is closed.
+
+ Closes all data models.
+
+ \param permanently if \c true close study permanently (not used in the base implemetation)
+*/
+void CAM_Study::closeDocument( bool permanently )
{
- for ( ModelListIterator it( myDataModels ); it.current(); ++it )
- it.current()->close();
+ for( QList<CAM_DataModel*>::const_iterator it = myDataModels.begin();
+ it != myDataModels.end(); ++it )
+ (*it)->close();
- SUIT_Study::closeDocument(permanently);
+ SUIT_Study::closeDocument( permanently );
}
-/*!Append data model to list.
- * \param dm - data model for adding
- */
+/*!
+ \brief Append data model to the study.
+ \param dm data model being added
+ \return \c true on success and \c false on error
+*/
bool CAM_Study::appendDataModel( const CAM_DataModel* dm )
{
return insertDataModel( dm, myDataModels.count() );
}
-/*!Insert data model \a dm after \a other
- * \param dm - data model for adding
- * \param other - previus data model for \a dm
- */
+/*!
+ \brief Insert data model \a dm after data model \a other
+
+ If \a other is 0, the data model is added to the end of list.
+
+ \param dm data model being added
+ \param other data model to be previous in the list
+ \return \c true on success and \c false on error
+*/
bool CAM_Study::insertDataModel( const CAM_DataModel* dm, const CAM_DataModel* other )
{
- int idx = myDataModels.findRef( other );
+ int idx = myDataModels.indexOf( (CAM_DataModel*)other );
return insertDataModel( dm, idx < 0 ? idx : idx + 1 );
}
-/*!Insert data model with index \a idx. \n
- * \param dm - data model
- * \param idx - index for inserting(must be no less zero)
- * \retval true - if model added successful, else false.
- */
+/*!
+ \brief Insert data model \a dm with index \a idx.
+
+ \param dm data model being added
+ \param idx data model required index
+ \return \c true on success and \c false on error
+*/
bool CAM_Study::insertDataModel( const CAM_DataModel* dm, const int idx )
{
- if ( !dm || myDataModels.findRef( dm ) != -1 )
+ if ( !dm || myDataModels.indexOf( (CAM_DataModel*)dm ) != -1 )
return false;
int pos = idx < 0 ? myDataModels.count() : idx;
- myDataModels.insert( QMIN( pos, (int)myDataModels.count() ), dm );
+ myDataModels.insert( qMin( pos, (int)myDataModels.count() ), (CAM_DataModel*)dm );
connect( dm, SIGNAL( rootChanged( const CAM_DataModel* ) ), SLOT( updateModelRoot( const CAM_DataModel* ) ) );
return true;
}
-/*! Remove data model from list
- * \param dm data model
- * \retval true - if all ok, else false.
- */
+/*!
+ \brief Remove data model from the study.
+ \param dm data model being removed
+ \return \c true on success and \c false on error
+*/
bool CAM_Study::removeDataModel( const CAM_DataModel* dm )
{
if ( !dm )
if ( aModelRoot )
aModelRoot->setDataModel( 0 );
- return myDataModels.remove( dm );
+ return myDataModels.removeAll( (CAM_DataModel*)dm );
}
-/*!Check data model contains in list.
- * \param dm - data model
- * \retval true - if data model in list, else false.
- */
+/*!
+ \brief Check if data model is contained in the list.
+ \param dm data model
+ \return \c true if data model is in the list and \c false otherwise.
+*/
bool CAM_Study::containsDataModel( const CAM_DataModel* dm ) const
{
- return myDataModels.contains( dm );
+ return myDataModels.contains( (CAM_DataModel*)dm );
}
-/*!Gets list of all data models.
- * \param lst - output data model list.
- */
+/*!
+ \brief Get all data models.
+ \param lst returning list of data model.
+*/
void CAM_Study::dataModels( ModelList& lst ) const
{
lst.clear();
- for ( ModelListIterator it( myDataModels ); it.current(); ++it )
- lst.append( it.current() );
+ for( QList<CAM_DataModel*>::const_iterator it = myDataModels.begin();
+ it != myDataModels.end(); ++it )
+ lst.append( *it );
}
-/*! Open data model \a dModel, if it saved*/
+/*!
+ \brief Called when data model is inserted in the study.
+
+ Open data model \a dModel, if it is saved and update data tree.
+
+ \param dModel data model
+*/
void CAM_Study::dataModelInserted( const CAM_DataModel* dModel )
{
CAM_DataModel* dm = (CAM_DataModel*)dModel;
updateModelRoot( dm );
}
-/*! \retval false*/
+/*!
+ \brief Called when data model is opened.
+
+ Base implementation does nothing and returns \c false.
+
+ \return \c true on success and \c false on error
+*/
bool CAM_Study::openDataModel( const QString&, CAM_DataModel* )
{
return false;
}
-/*! \retval false*/
+/*!
+ \brief Called when data model is saved.
+
+ Base implementation does nothing and returns \c false.
+
+ \return \c true on success and \c false on error
+*/
bool CAM_Study::saveDataModel( const QString&, CAM_DataModel* )
{
return false;
}
-/*! Public slot. Update model root.*/
+/*!
+ \brief Update data model root object.
+ \param dm data model being updated.
+*/
void CAM_Study::updateModelRoot( const CAM_DataModel* dm )
{
if ( !root() )
if ( curRoot )
root()->replaceChild( curRoot, dm->root(), true );
else {
- int idx = myDataModels.findRef( dm );
+ int idx = myDataModels.indexOf( (CAM_DataModel*)dm );
if ( idx != -1 )
root()->insertChild( dm->root(), idx );
}
#include "CAM.h"
-#include "CAM_DataModel.h"
-
#include <SUIT_Study.h>
+#include <QList>
-#include <qptrlist.h>
+class CAM_DataModel;
#ifdef WIN32
#pragma warning( disable:4251 )
#endif
-/*!
- \class CAM_Study
- Represents study for using in CAM, contains list of
- data model references from all modules. Provides
- necessary functionality for data models management.
-*/
class CAM_EXPORT CAM_Study : public SUIT_Study
{
Q_OBJECT
public:
- typedef QPtrList<CAM_DataModel> ModelList;
- typedef QPtrListIterator<CAM_DataModel> ModelListIterator;
+ typedef QList<CAM_DataModel*> ModelList;
public:
CAM_Study( SUIT_Application* );
virtual ~CAM_Study();
- virtual void closeDocument(bool permanently = true);
+ virtual void closeDocument( bool permanently = true );
- /** @name Insert data model methods.*/
- //@{
bool appendDataModel( const CAM_DataModel* );
virtual bool insertDataModel( const CAM_DataModel*, const int = -1 );
bool insertDataModel( const CAM_DataModel*, const CAM_DataModel* );
- //@}
virtual bool removeDataModel( const CAM_DataModel* );
virtual void updateModelRoot( const CAM_DataModel* );
private:
- //! Data model list
- ModelList myDataModels;
+ ModelList myDataModels; //!< data models list
};
#ifdef WIN32
lib_LTLIBRARIES = libCAM.la
salomeinclude_HEADERS= \
+ CAM.h \
CAM_Application.h \
CAM_DataModel.h \
CAM_DataObject.h \
- CAM.h \
CAM_Module.h \
CAM_Study.h \
CAM_RootObject.h
libCAM_la_CPPFLAGS=$(QT_INCLUDES) -I$(srcdir)/../SUIT -I$(srcdir)/../STD -I$(srcdir)/../Qtx
libCAM_la_LDFLAGS=$(QT_MT_LIBS)
-libCAM_la_LIBS=../SUIT/libsuit.la ../STD/libstd.la
+libCAM_la_LIBADD=../Qtx/libqtx.la ../SUIT/libsuit.la ../STD/libstd.la
# what is that?
#LDFLAGSFORBIN= -lSUITApp
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>ERROR_TLT</source>
+ <translation>Error</translation>
+ </message>
+ <message>
+ <source>ERROR_ACTIVATE_MODULE_MSG</source>
+ <translation>Failed to activate module %1</translation>
+ </message>
+</context>
+</TS>
--- /dev/null
+TEMPLATE = lib
+TARGET = DDS
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+CASROOT = $$(CASROOT)
+CAS_CPPFLAGS = $${CASROOT}/inc
+
+CAS_KERNEL = -L$${CASROOT}/Linux/lib -lTKernel
+
+CAS_OCAF = -L$${CASROOT}/Linux/lib -lPTKernel -lTKernel -lTKCDF -lTKLCAF -lTKPCAF -lTKStdSchema
+
+INCLUDEPATH += ../../include $${CAS_CPPFLAGS}
+LIBS += $${CAS_KERNEL} $${CAS_OCAF}
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += OCC_VERSION_MAJOR=6 OCC_VERSION_MINOR=2 OCC_VERSION_MAINTENANCE=0 LIN LINTEL CSFDB No_exception HAVE_CONFIG_H HAVE_LIMITS_H HAVE_WOK_CONFIG_H OCC_CONVERT_SIGNALS
+
+HEADERS = DDS.h
+HEADERS += DDS_DicGroup.h
+HEADERS += DDS_DicItem.h
+HEADERS += DDS_Dictionary.h
+HEADERS += DDS_KeyWords.h
+
+SOURCES = DDS_DicGroup.cxx
+SOURCES += DDS_DicItem.cxx
+SOURCES += DDS_Dictionary.cxx
+SOURCES += DDS_KeyWords.cxx
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+INSTALLS += includes
/*!
\class DDS_DicGroup
-
- This class to provide set of DDS_DicItem objects from one component.
+ \brief This class provides a set of DDS_DicItem objects from one component.
*/
/*!
- Constructor. Create the group with name \aname.
+ \brief Constructor.
+
+ Create the group with name \a name.
+
+ \param name group name
*/
DDS_DicGroup::DDS_DicGroup( const TCollection_AsciiString& name )
: MMgt_TShared(),
-myName( name ),
-myActiveSystem( UNIT_SYSTEM_SI )
+ myName( name ),
+ myActiveSystem( UNIT_SYSTEM_SI )
{
}
/*!
- Copy constructor.
+ \brief Copy constructor (put in private section to prevent object copying).
*/
DDS_DicGroup::DDS_DicGroup( const DDS_DicGroup& )
{
}
/*!
- Get the name of group (component).
+ \brief Get the name of group (component).
+ \return group name
*/
TCollection_AsciiString DDS_DicGroup::GetName() const
{
}
/*!
- Returns the names list of defined unit systems.
- Parameter \atheSystems will contains the sequence of string names.
+ \brief Get the names of all defined units systems.
+ \param theSystemsSeq returning sequence of names
*/
void DDS_DicGroup::GetUnitSystems( TColStd_SequenceOfAsciiString& theSystemSeq ) const
{
}
/*!
- Returns the label of unit system \aname. If unit system not found then empty string returned.
+ \brief Get the label of units system \a name.
+
+ If units system is not found, empty string is returned.
+
+ \param make units system name
+ \return units system label
*/
TCollection_ExtendedString DDS_DicGroup::GetUnitSystemLabel( const TCollection_AsciiString& name ) const
{
}
/*!
- Gets the name of active unit system.
+ \brief Get the name of active units system.
+ \return active units system name
*/
TCollection_AsciiString DDS_DicGroup::GetActiveUnitSystem() const
{
}
/*!
- Sets the name of active unit system.
+ \brief Set the active unit system.
+ \param theSystem name of the units system to be made active
*/
void DDS_DicGroup::SetActiveUnitSystem( const TCollection_AsciiString& theSystem )
{
}
/*!
- Assignment operator.
+ \brief Assignment operator (put in private section to prevent object copying).
*/
void DDS_DicGroup::operator=( const DDS_DicGroup& )
{
}
/*!
- Fill the internal data structures from XML parsed structures. Internal.
+ \brief Fill the internal data structures from XML parsed structures.
+ \param theComponentData component data DOM node
+ \param theDocElement document element DOM node
*/
void DDS_DicGroup::FillDataMap( const LDOM_Element& theComponentData, const LDOM_Element& theDocElement )
{
}
/*!
- Gets dictionary item with specified identifier \atheID.
- If dictionary item not found then null handle returned.
+ \brief Get the dictionary item with specified identifier \a theID.
+
+ If dictionary item is not found, null handle is returned.
+
+ \param theID item identifier
+ \return dictionary item
*/
-Handle(DDS_DicItem) DDS_DicGroup::GetDicItem( const TCollection_AsciiString& theID ) const
+Handle_DDS_DicItem DDS_DicGroup::GetDicItem( const TCollection_AsciiString& theID ) const
{
Handle(DDS_DicItem) aDicItem;
// get dictionary item by id
/*!
\class DDS_DicItem
-
- This class to provide information about datum (phisical characteristic parameter).
+ \brief This class provides an information about datum (phisical characteristic parameter).
*/
/*!
- Constructor. Creates the instance of empty dictionary item.
+ \brief Constructor.
+
+ Creates the instance of empty dictionary item.
*/
DDS_DicItem::DDS_DicItem()
: myType( 0 ),
-myDefValue( 0 ),
-myMax( 0 ),
-myMin( 0 ),
-myMinZoom( 0.1 ),
-myMaxZoom( 10 ),
-myZoomOrder( 2 )
+ myMax( 0 ),
+ myMin( 0 ),
+ myDefValue( 0 ),
+ myMinZoom( 0.1 ),
+ myMaxZoom( 10 ),
+ myZoomOrder( 2 )
{
}
/*!
- Copy constructor. Internal.
+ \brief Copy constructor (put in private section to prevent object copying).
*/
DDS_DicItem::DDS_DicItem( const DDS_DicItem& )
{
}
/*!
- Assignment operator. Internal.
+ \brief Assignment operator (put in private section to prevent object copying).
*/
void DDS_DicItem::operator=( const DDS_DicItem& )
{
}
/*!
- Gets the identifier of parameter.
+ \brief Get the identifier of parameter.
+ \return parameter ID
*/
TCollection_AsciiString DDS_DicItem::GetId() const
{
}
/*!
- Gets the type of parameter.
+ \brief Get the type of parameter.
+ \return parameter type
*/
DDS_DicItem::Type DDS_DicItem::GetType() const
{
}
/*!
- Gets the label of the parameter.
+ \brief Get the label of the parameter.
+ \return parameter label
*/
TCollection_ExtendedString DDS_DicItem::GetLabel() const
{
}
/*!
- Gets the filter (regular expression) for the parameter values.
+ \brief Get the filter (regular expression) for the parameter values.
+ \return parameter filter
*/
TCollection_ExtendedString DDS_DicItem::GetFilter() const
{
}
/*!
- Gets the Required attribute of the parameter.
+ \brief Get the Required attribute of the parameter.
+ \return Required attribute
*/
TCollection_ExtendedString DDS_DicItem::GetRequired() const
{
}
/*!
- Gets the wrong value warning level of the parameter.
+ \brief Get the wrong value warning level of the parameter.
+ \return warning level
*/
DDS_MsgType DDS_DicItem::GetWarningLevel() const
{
}
/*!
- Gets the long description of the parameter.
+ \brief Get the long description of the parameter.
+ \return long description
*/
TCollection_ExtendedString DDS_DicItem::GetLongDescription() const
{
}
/*!
- Gets the short description of the parameter.
+ \brief Get the short description of the parameter.
+ \return short description
*/
TCollection_ExtendedString DDS_DicItem::GetShortDescription() const
{
}
/*!
- Gets the name of component - owner of parameter.
+ \brief Get the name of the component (parameter owner).
+ \return component name
*/
TCollection_AsciiString DDS_DicItem::GetComponent() const
{
}
/*!
- Gets the parameter unit of measure for active unit system.
+ \brief Get the parameter measure units for active units system.
+ \return parameter units
*/
TCollection_AsciiString DDS_DicItem::GetUnits() const
{
}
/*!
- Gets the parameter unit of measure for specified unit system \atheSystem.
- If specified unit system doesn't exist then empty string returned.
+ \brief Get the parameter measure units for specified units system \a theSystem.
+
+ If specified units system doesn't exist, empty string is returned.
+
+ \param theSystem units system
+ \return parameter units
*/
TCollection_AsciiString DDS_DicItem::GetUnits( const UnitSystem& theSystem ) const
{
}
/*!
- Gets the minimum value of parameter for active unit system.
- Returned value converted to SI.
+ \brief Get the minimum value of the parameter for active units system.
+
+ Returned value is converted to SI.
+
+ \return minimum value
*/
Standard_Real DDS_DicItem::GetMinValue() const
{
}
/*!
- Gets the minimum value of parameter for specified unit system \atheSystem.
- Returned value converted to SI.
+ \brief Get the minimum value of the parameter for the specified
+ units system \a theSystem.
+
+ Returned value is converted to SI.
+
+ \param theUnitsSystem units system
+ \return minimum value
*/
Standard_Real DDS_DicItem::GetMinValue( const UnitSystem& theUnitsSystem ) const
{
}
/*!
- Gets the maximum value of parameter for active unit system.
+ \brief Get the maximum value of the parameter for active units system.
+
Returned value converted to SI.
+
+ \return maximum value
*/
Standard_Real DDS_DicItem::GetMaxValue() const
{
}
/*!
- Gets the maximum value of parameter for specified unit system \atheSystem.
+ \brief Get the maximum value of the parameter for specified
+ units system \a theSystem.
+
Returned value converted to SI.
+
+ \param theUnitsSystem units system
+ \return maximum value
*/
Standard_Real DDS_DicItem::GetMaxValue( const UnitSystem& theUnitsSystem ) const
{
}
/*!
- Gets the precision (number of digit after decimal point) of parameter for active unit system.
+ \brief Get the precision (number of digits after decimal point)
+ of the parameter for active units system.
+ \return parameter precision
*/
Standard_Integer DDS_DicItem::GetPrecision() const
{
}
/*!
- Gets the precision (number of digit after decimal point) of parameter for specified
- unit system \atheSystem. If specified unit system doesn't exist then zero returned.
+ \brief Get the precision (number of digits after decimal point) of the parameter
+ for specified units system \a theSystem.
+
+ If specified units system doesn't exist, zero is returned.
+
+ \param theSystem units system
+ \return parameter precision
*/
Standard_Integer DDS_DicItem::GetPrecision( const UnitSystem& theSystem ) const
{
}
/*!
- Gets the default value of parameter for active unit system. Default value returned as string.
- If type of value is numeric (Float or Integer) and default value defined then returned number
- converted to SI.
+ \brief Get the default value of the parameter for active units system.
+
+ Default value is returned as string.
+ If type of the value is numerical (Float or Integer) and default value
+ is defined, then the returning value is converted to SI.
+
+ \return default value
*/
TCollection_ExtendedString DDS_DicItem::GetDefaultValue() const
{
}
/*!
- Gets the default value of parameter for specified unit system \atheSystem. Default value returned
- as string. If type of value is numeric (Float or Integer) and default value defined then returned
- number converted to SI.
+ \brief Get the default value of the parameter for specified
+ units system \a theSystem.
+
+ Default value is returned as string.
+ If type of the value is numerical (Float or Integer) and default value
+ is defined, then the returning value is converted to SI.
+
+ \param theSystem units system
+ \return default value
*/
TCollection_ExtendedString DDS_DicItem::GetDefaultValue( const UnitSystem& theSystem ) const
{
}
/*!
- Gets the format string of parameter for active unit system. If argument \atheCanonical
- is true then format string will be reduced to sprintf() specification (without extra
- non standard qualifiers).
+ \brief Get the format string of the parameter for active units system.
+
+ If argument \a theCanonical is \c true, format string is reduced according
+ to the sprintf() specification (without extra non standard qualifiers).
+
+ \param theCanonical 'canonical form' flag
+ \return format string
*/
TCollection_AsciiString DDS_DicItem::GetFormat( const Standard_Boolean theCanonical ) const
{
}
/*!
- Gets the format string of parameter for specified unit system \atheSystem. If argument
- \atheCanonical is true then format string will be reduced to sprintf() specification
- (without extra non standard qualifiers).
+ \brief Get the format string of the parameter for specified
+ units system \a theSystem.
+
+ If argument \a theCanonical is \c true, format string is reduced according
+ to the sprintf() specification (without extra non standard qualifiers).
+
+ \param theSystem units system
+ \param theCanonical 'canonical form' flag
+ \return format string
*/
TCollection_AsciiString DDS_DicItem::GetFormat( const UnitSystem& theSystem,
const Standard_Boolean theCanonical ) const
}
/*!
- Gets name of a list referenced by the parameter. This string is empty if the list
- refernce is not defined - then use other properties: Type, DefaultValue, MaxValue, MinValue
+ \brief Get the name of a list referenced by the parameter.
+
+ This string is empty if the list reference is not defined.
+ In this case, other properties (Type, DefaultValue, MaxValue, MinValue)
+ should be used.
+
+ \return referenced list name
+ \sa GetListOfValues()
*/
TCollection_ExtendedString DDS_DicItem::GetNameOfValues() const
{
}
/*!
- Gets item names and item ids of a list referenced by the parameter. This sequences is empty if
- the list reference is not defined - then use other properties: Type, DefaultValue, MaxValue, MinValue
+ \brief Get item names and item identifiers of a list referenced
+ by the parameter.
+
+ These sequences are empty if the list reference is not defined.
+ In this case, other properties (Type, DefaultValue, MaxValue, MinValue)
+ should be used.
+
+ \param theStrings returning items names
+ \param theIntegers returning items identifiers
+ \return \c true if returning lists are not empty
+ \sa GetNameOfValues()
*/
Standard_Boolean DDS_DicItem::GetListOfValues( Handle(TColStd_HArray1OfExtendedString)& theStrings,
Handle(TColStd_HArray1OfInteger)& theIntegers ) const
}
/*!
- Gets item names, item ids and item icons of a list referenced by the parameter. This sequences is empty
- if the list reference is not defined - then use other properties: Type, DefaultValue, MaxValue, MinValue
+ \brief Get item names, item identifiers and item icons of a list
+ referenced by the parameter.
+
+ \overload
+
+ These sequences are empty if the list reference is not defined.
+ In this case, other properties (Type, DefaultValue, MaxValue, MinValue)
+ should be used.
+
+ \param theStrings returning items names
+ \param theIntegers returning items identifiers
+ \param theIcons returning items icons
+ \return \c true if returning lists are not empty
+ \sa GetNameOfValues()
*/
Standard_Boolean DDS_DicItem::GetListOfValues( Handle(TColStd_HArray1OfExtendedString)& theStrings,
Handle(TColStd_HArray1OfInteger)& theIntegers,
/*!
- Gets special values of the parameter.
+ \brief Get special values of the parameter.
+ \param theMap returning map of the special values
+ \return \c true if returning map is not empty
*/
Standard_Boolean DDS_DicItem::GetSpecialValues( TColStd_MapOfReal& theMap ) const
{
}
/*!
- Gets minimum value of lateral zooming
+ \brief Get minimum value of lateral zooming.
+ \return lateral zooming minimum value
*/
Standard_Real DDS_DicItem::GetMinZoom() const
{
}
/*!
- Gets maximum value of lateral zooming
+ \brief Get maximum value of lateral zooming.
+ \return lateral zooming maximum value
*/
Standard_Real DDS_DicItem::GetMaxZoom() const
{
}
/*!
- Gets order of lateral zooming
+ \brief Get order of lateral zooming.
+ \return lateral zooming order
*/
Standard_Real DDS_DicItem::GetZoomOrder() const
{
}
/*!
- Convert value \atheVal to default SI units according to active unit system.
+ \brief Convert value \a theVal to the default SI units
+ according to the active units system.
+ \param theVal value being converted
+ \return value converted to SI
*/
Standard_Real DDS_DicItem::ToSI( const Standard_Real theVal ) const
{
}
/*!
- Convert value \atheVal from default SI units according to active unit system.
+ \brief Convert value \a theVal from the default SI units
+ according to the active units system.
+ \param theVal value being converted
+ \return value converted from SI
*/
Standard_Real DDS_DicItem::FromSI( const Standard_Real theVal ) const
{
}
/*!
- Convert value to default SI units according to unit system \atheUnitsSystem.
+ \brief Convert value to the default SI units according to the
+ units system \a theUnitsSystem.
+ \param theVal value being converted
+ \param theUnitsSystem units system
+ \return value converted to the specified units system
*/
Standard_Real DDS_DicItem::ToSI( const Standard_Real theVal, const UnitSystem& theUnitsSystem ) const
{
}
/*!
- Convert value from default SI units according to unit system \atheUnitsSystem.
+ \brief Convert value from the default SI units according to the
+ units system \a theUnitsSystem.
+ \param theVal value being converted
+ \param theUnitsSystem units system
+ \return value converted from the specified units system
*/
Standard_Real DDS_DicItem::FromSI( const Standard_Real theVal, const UnitSystem& theUnitsSystem ) const
{
}
/*!
- Returns 'true' if data specified by \aflag exist.
+ \brief Check data existence.
+ \param flag data flag
+ \return \c true if data specified by \a flag exists
*/
Standard_Boolean DDS_DicItem::HasData( const Standard_Integer flag ) const
{
}
/*!
- Returns options for specified name \aname. If option not found then empty string returned.
+ \brief Get option for specified name \a name.
+
+ If option is not found, empty string is returned.
+
+ \param name option name
+ \return option value
*/
TCollection_ExtendedString DDS_DicItem::GetOption( const TCollection_AsciiString& name ) const
{
}
/*!
- Returns names list of existing options in the specified sequence \anames.
- If list not empty retunrs 'true' otherwise 'false'.
+ \brief Get names of all existing options.
+ \param names returning list of options
+ \return \c true if list is not empty
*/
Standard_Boolean DDS_DicItem::GetOptionNames( TColStd_SequenceOfAsciiString& names ) const
{
/*!
- Parse record in XML file and retrieve information relevant for this dictionary item
+ \brief Parse record from XML file and retrieve information relevant for
+ the dictionary item.
+ \param theID item identifier
+ \param theDatum datum XML node
+ \param theCompElement component XML node
+ \param theDocElement document XML node
+ \param theSystems units system names
*/
void DDS_DicItem::FillDataMap( TCollection_AsciiString theID, const LDOM_Element& theDatum,
const LDOM_Element& theCompElement, const LDOM_Element& theDocElement,
}
/*!
- Returns default formats for each unit systems
+ \brief Restore default formats for all the units systems.
*/
void DDS_DicItem::GetDefaultFormat()
{
}
/*!
- Returns format for the string
+ \brief Get format for the string.
+ \param theFlags format flags
+ \param theWidth field width
+ \param thePrecision precision
+ \param theTypePrefix type prefix
+ \param theFormat returning format string
*/
void DDS_DicItem::GetStringFormat( const TCollection_AsciiString& theFlags,
const TCollection_AsciiString& theWidth,
}
/*!
- Returns format for the integer
+ \brief Get format for the integer.
+ \param theFlags format flags
+ \param theWidth field width
+ \param thePrecision precision
+ \param theTypePrefix type prefix
+ \param theType integer value type
+ \param theFormat returning format string
*/
void DDS_DicItem::GetIntegerFormat( const TCollection_AsciiString& theFlags,
const TCollection_AsciiString& theWidth,
}
/*!
- Returns format for the float
+ \brief Returns format for the float.
+ \param theFlags format flags
+ \param theWidth field width
+ \param thePrecision precision
+ \param theTypePrefix type prefix
+ \param theType floating point value type
+ \param theFormat returning format string
*/
void DDS_DicItem::GetFloatFormat( const TCollection_AsciiString& theFlags,
const TCollection_AsciiString& theWidth,
}
/*!
- Prepares formats for each unit systems
+ \brief Prepare formats for all units systems.
+ \param theFormat format string
*/
-void DDS_DicItem::PrepareFormats( const TCollection_AsciiString& theFormat )
+void DDS_DicItem::PrepareFormats( const TCollection_AsciiString& theFormat )
{
for ( NCollection_DataMap<UnitSystem, UnitData>::Iterator it( myUnitData ); it.More(); it.Next() )
{
}
/*!
- Split the string \atheStr by spaces and returns substrings in array \aaRes.
+ \brief Split the string \a theStr separated by spaces.
+ \param theStr source string
+ \param aRes returning substrings array
*/
void DDS_DicItem::Split( const TCollection_AsciiString& theStr, Handle(TColStd_HArray1OfExtendedString)& aRes )
{
}
/*!
- Returns unit structure for given unit system \asys.
+ \brief Get units structure for specified units system \a sys.
+ \param sys units system
+ \return units system information structure
*/
DDS_DicItem::UnitData* DDS_DicItem::GetUnitData( const UnitSystem& sys ) const
{
}
/*!
- Gets the active unit system.
+ \brief Get the active units system.
+ \return active units system
*/
DDS_DicItem::UnitSystem DDS_DicItem::GetActiveUnitSystem() const
{
/*!
\class DDS_Dictionary
-
- This class to provide information about used datums, reading them from 'xml' file
+ \brief This class provides an information about used datums,
+ reading them from XML file.
- Datum is the set of parameters described a phisical characteristic. These parameters loaded from
- special XML which has following format:
+ There is the only instance of the class DDS_Dictionary in the application
+ which can be retrieved by method Get().
- \hr
+ Datum is a set of parameters describing a phisical characteristic.
+ These parameters are loaded from the XML file which has the following format:
+ \verbatim
<D_URI>
<COMPONENT COMPONENT_NAME="component_name">
<UNIT_SYSTEMS>
</COMPONENT>
</D_URI>
- \hr
-
- In description of datum file format used internal keys as XML tag and attributes names.
- Concrete XML keywords defined by DDS_KeyWords class.
-
- Describe datum file format more detailed. XML file should have one main tag named as "dictionary" (key "D_URI").
- This tag should contains one or several components. Component is a independent set of datums and unit systems.
- Components defined as XML tag named "component" (key "COMPONENT") with attribute "name" (key COMPONENT_NAME).
- Component name used as component identifier and should be unique. Component tag can contains:
-
- \li Tag "unit_systems" (key UNIT_SYSTEMS) defines set of used unit systems. Should exist at least one unit
- system named SI ("System International"). If this system not exist then it will be defined automatically.
- Each unit system defined by XML tag "unit system" (key UNIT_SYSTEM) under tag "unit_systems" with attributes
- "name" (key UNIT_SYSTEM_NAME) and "label" (key UNIT_SYSTEM_LABEL). Name is identifier of unit system. Label is
- human readable description.
-
- \li One or several tag "datum" (key DATUM). For this tag can be defined following attributes:
-
- \lo Identifier (key DATUM_ID) specify the unique id string for the datum.
- \lo Label (key DATUM_LABEL) specify human readable name of the datum.
- \lo Units of measure (key DATUM_UNITS) for given unit system. Attribute name consist of a name
- of unit system and a keyword got from DDS_KeyWords by key DATUM_UNITS. For example for unit system
- named SI and default keyword attribute name will be "SIunits". This attribute should be specified
- for each deaclared unit system. Value of this attribute should be string describs units of measure.
- Possible designations for units of measure and their multiple prefixes see in package UnitsAPI of
- library OpenCascade (files Units.dat and Lexi_Expr.dat). Units of measure will be used for numeric
- value conversion from one unit system to another one.
- \lo Format (key DATUM_FORMAT) specify the format string which will be used during initial formatting
- of value. This string should be specified in sprintf() format.
- \lo Filter (key DATUM_FILTER) specify the regualr expression. Each user entered string will be checked up
- on matching to this expression (if it defined). Non matched strings will be rejected.
- \lo Required value (key DATUM_REQUIRED). If this attributed defined and value is true then user can't
- leave a input filed blank (parameter must be always entered).
-
- Tag "description" (key DESCR) can be defined under the tag "datum". This tag contains two sub tags:
- \lo "short description" (key SHORT_D) specify a brief datum description text
- \lo "long description" (key LONG_D) specify a detailed description text
-
- Tag "options" (key OPTIONS) can be defined under the tag "datum". This tag contains one or more sub
- tags "option" (key OPTION). Each of these XML elements should contain text option value and attribute
- "name" (key OPTION_NAME) which specified option name.
-
- Each tag "datum" define most common parameters of phisical characteristic.
- This parameters placed in two groups:
- \lo Domain parameters under tag "domain" (key DY_DOMAIN). This tag can contains value description tag
- (key VALUE_DESCR) for discrete data or list reference tag (key VALUE_LIST_REF) for enumerable data.
- Discrete data described following parameters:
- default value (key VD_DEFV)
- maximum value (key VD_MAXV)
- minimum value (key VD_MINV)
- type of value (key VD_TYPE) - possible values: String, Integer, Float, List
- Enumerable data described by "list reference" attribute (key VLR_LIST) which reference on
- list (see "list definition" tag) by list id.
-
- \li One or several tag "list definition" (key VALUE_LIST). This tag define the list of items for enumerable
- data. Attribute "list id" (key VALUE_LIST_ID) specify the identifier string for the list and attribute
- "list name" (key VALUE_LIST_NAME) define a list name string. Each list item described by tag "list value"
- (key VALUE_LIST_VALUE) under tag "list definition". Each this tag contains item string text and have
- following attributes:
- \lo "list item id" (key VALUE_LIST_VALUEID) - integer numerical identifier for item
- \lo "list item icon" (key VALUE_LIST_VALUEICON) - icon file name for item
-
- Below the example of a XML file with use default keywords.
+ \endverbatim
+
+ In above description of the datum XML file format internal keys are used as XML tags
+ and attributes names. Real XML keywords are defined by DDS_KeyWords class.
+ XML file should have one main tag named "dictionary" (key "D_URI"). This tag
+ should contain one or several components.
+ Component is an independent set of datums and units systems.
+ Components are defined by XML tag named "component" (key "COMPONENT") with
+ attribute "name" (key COMPONENT_NAME).
+ Component name is used as component identifier and should be unique.
+
+ Component tag can contain:
+
+ - Tag "unit_systems" (key UNIT_SYSTEMS) defines a set of used units systems.
+ At least one unit system named SI ("System International") should exist.
+ If this system does not exist, it will be created automatically.
+ Each units system is defined by XML tag "unit system" (key UNIT_SYSTEM) under
+ the tag "unit_systems" with attributes "name" (key UNIT_SYSTEM_NAME)
+ and "label" (key UNIT_SYSTEM_LABEL). Name is an identifier of the units system and
+ label is its human readable description.
+
+ - One or several tags "datum" (key DATUM). For this tag the following attributes
+ can be defined:
+ -# Identifier (key DATUM_ID) specifies the unique id string for the datum.
+ -# Label (key DATUM_LABEL) specifies human readable name of the datum.
+ -# Measure units (key DATUM_UNITS) for the given units system. Attribute name
+ defines a name of units system and a keyword got from DDS_KeyWords by key DATUM_UNITS.
+ For example, for "SI" units system and default keyword the attribute name is "SIunits".
+ This attribute should be specified for each declared units system.
+ Value of this attribute should be a string describing measure units.
+ For possible designations for measure units and their multiple prefixes
+ please refer to the UnitsAPI package of the OpenCascade library
+ (files Units.dat and Lexi_Expr.dat). Measure units are used for numerical
+ values conversion from one units system to another one.
+ -# Format (key DATUM_FORMAT) specifies the format string which will be used
+ during initial formatting of the value. This string should be specified
+ in sprintf() format.
+ -# Filter (key DATUM_FILTER) specifies the regualr expression. The value (string)
+ entered by the user will be checked up to match to this regular expression
+ (if it defined). Non matched strings will be rejected.
+ -# Required value (key DATUM_REQUIRED). If this attributed si defined and its value
+ is \c true then user can't leave an input non-filled - parameter must be explicitly
+ entered by the user).
+
+ - One or several tags "list definition" (key VALUE_LIST). Each such tag defines
+ the list of items for enumerable data. Attribute "list id" (key VALUE_LIST_ID)
+ specifies the identifier string for the list and attribute "list name"
+ (key VALUE_LIST_NAME) defines a list name string. Each list item is described
+ by tag "list value" (key VALUE_LIST_VALUE) under the tag "list definition".
+ Each this tag contains item string text and have the following attributes:
+ -# "list item id" (key VALUE_LIST_VALUEID) - integer numerical identifier for
+ the item
+ -# "list item icon" (key VALUE_LIST_VALUEICON) - icon file name for the item
+
+ Tag "datum" can have child subtags "description" and "options".
+
+ - Tag "description" (key DESCR) contains two sub tags:
+ -# "short description" (key SHORT_D) specifies a brief datum description text
+ -# "long description" (key LONG_D) specifies a detailed description text
+
+ - Tag "options" (key OPTIONS) contains one or more sub tags "option" (key OPTION).
+ Each of these XML elements should contain text option value and attribute
+ "name" (key OPTION_NAME) which specifies option name.
+
+ Each tag "datum" defines most common parameters of phisical characteristic.
+ These parameters are placed in two groups:
+ -# Domain parameters under the tag "domain" (key DY_DOMAIN). This tag can
+ contain value description tag (key VALUE_DESCR) for descrete data which is
+ described by following parameters:
+ - default value (key VD_DEFV)
+ - maximum value (key VD_MAXV)
+ - minimum value (key VD_MINV)
+ - type of value (key VD_TYPE), possible values are String, Integer, Float, List
+ -# list reference tag (key VALUE_LIST_REF) for enumerable data described by
+ "list reference" attribute (key VLR_LIST) which references to the list
+ (see "list definition" tag) by list id.
+
+ Below is an example of the XML file using default keywords.
+
+ \verbatim
<datadictionary version="1.0">
<component name="My Component">
</component>
</datadictionary>
-
-
+ \endverbatim
*/
/*!
- Constructor. Creates the instance of dictionary. Private method. Use DDS_Dictionary::Get() instead.
+ \brief Constructor.
+
+ Create an instance of the dictionary. Can not be used directly.
+ Use Get() method instead.
*/
DDS_Dictionary::DDS_Dictionary()
: MMgt_TShared()
}
/*!
- Copy constructor. Internal.
+ \brief Copy constructor (put in private section to prevent object copying).
*/
DDS_Dictionary::DDS_Dictionary( const DDS_Dictionary& )
{
}
/*!
- Assigment operator. Internal.
+ \brief Assignment operator (put in private section to prevent object copying).
*/
void DDS_Dictionary::operator=( const DDS_Dictionary& )
{
}
/*!
- Returns the names list of defined unit systems from all components.
- Parameter \atheSystems will contains the sequence of string names.
+ \brief Get the names of defined units systems from all components.
+ \param theSystems returning sequence of units systems names.
*/
void DDS_Dictionary::GetUnitSystems( TColStd_SequenceOfAsciiString& theSystems ) const
{
}
/*!
- Returns the names list of defined unit systems from the specified component \atheComponent.
- Parameter \atheSystems will contains the sequence of string names. If component not found then
- empty list returned.
+ \brief Get the names of defined units systems from the specified component
+ \a theComponent.
+
+ If component is not found, empty list is returned.
+
+ \param theSystems returning sequence of units systems names.
+ \param theComponent component name
*/
void DDS_Dictionary::GetUnitSystems( TColStd_SequenceOfAsciiString& theSystems,
const TCollection_AsciiString& theComponent ) const
}
/*!
- Returns the label of unit system \atheSystem. Function find the given unit system in
- all components. If unit system not found in any component then empty string returned.
+ \brief Get the label of the units system \a theSystem.
+
+ Searches the given units system in all components. If units system is not found
+ in any component, empty string is returned.
+
+ \param theSystem units system
+ \return units system label
*/
TCollection_ExtendedString DDS_Dictionary::GetUnitSystemLabel( const TCollection_AsciiString& theSystem ) const
{
}
/*!
- Returns the label of unit system \atheSystem from component \atheComponent. Function find
- the given unit system in the specified component only. If unit system not found in the
- component then empty string returned.
+ \brief Get the label of the units system \a theSystem from the
+ component \a theComponent.
+
+ Searches the specified units system in the specified component only.
+ If units system is not found, empty string is returned.
+
+ \param theSystem units system
+ \param theComponent component name
+ \return units system label
*/
TCollection_ExtendedString DDS_Dictionary::GetUnitSystemLabel( const TCollection_AsciiString& theSystem,
const TCollection_AsciiString& theComponent ) const
}
/*!
- Gets the name of active unit system from first got component. If any component exist then
- active unit system name returned or empty string otherwise.
+ \brief Get the name of active units system from the first found component.
+
+ If at least one component exists, then its active units system name
+ is returned. Otherwise, empty string is returned.
+
+ \return active units system name
*/
TCollection_AsciiString DDS_Dictionary::GetActiveUnitSystem() const
{
}
/*!
- Gets the name of active unit system from component \atheComponent. If this component exist
- active unit system name returned or empty string otherwise.
+ \brief Get the name of active units system from the component \a theComponent.
+
+ If this component exists, its active units system name is returned.
+ Otherwise, empty string is returned.
+
+ \param theComponent component name
+ \return active units system name
*/
TCollection_AsciiString DDS_Dictionary::GetActiveUnitSystem( const TCollection_AsciiString& theComponent ) const
{
}
/*!
- Sets the active unit system named \atheSystem. This unit system will be activated in all
- existing components if component have it.
+ \brief Set the active units system.
+
+ This units system will be activated in each existing component,
+ if it component has this units system.
+
+ \param theSystem units system to be made active
*/
void DDS_Dictionary::SetActiveUnitSystem( const TCollection_AsciiString& theSystem )
{
}
/*!
- Sets the active unit system named \atheSystem for component \atheComponent. If specified unit
- system doesn't exist in the component then function do nothing.
+ \brief Set the active units system for the component \a theComponent.
+
+ If specified units system doesn't exist in the component, nothing happens.
+
+ \param theSystem units system to be made active
+ \param theComponent component name
*/
void DDS_Dictionary::SetActiveUnitSystem( const TCollection_AsciiString& theSystem,
const TCollection_AsciiString& theComponent )
}
/*!
- Returns the instance of dictionary. Create instance if it is NULL.
+ \brief Get the only instance of the data dictionary.
+ \return the only instance of the data dictionary
*/
-Handle(DDS_Dictionary) DDS_Dictionary::Get()
+Handle_DDS_Dictionary DDS_Dictionary::Get()
{
static Handle(DDS_Dictionary) sDictionary;
}
/*!
- Load datum definitions in the dictionary from XML file \atheFileName. Returns true if load
- successed or false otherwise.
+ \brief Load datum definitions in the dictionary from the XML file
+ \a theFileName.
+ \param theFileName XML file name
+ \return \c true if loading is succeded or \c false otherwise.
*/
Standard_Boolean DDS_Dictionary::Load( const TCollection_AsciiString theFileName )
{
}
/*!
- Gets XML keyword as LDOMString by specified \akey. If key doesn't exist then empty string
- returned. This function provided for convenience.
+ \brief Get XML keyword as LDOMString by specified \a key.
+
+ If key doesn't exist, empty string is returned.
+ This function is provided for convenience.
+
+ \param key keyword name
+ \return keyword value
*/
LDOMString DDS_Dictionary::KeyWord( const TCollection_AsciiString& key )
{
}
/*!
- Gets dictionary item with specified identifier \atheID from specified component \atheComponent.
- If component or item not found then null handle returned.
+ \brief Get the data dictionary item by specified identifier \a theID
+ from the component \a theComponent.
+
+ If the component or item is not found, null handle is returned.
+ \param theID data dictionary item ID
+ \param theComponent component name
+ \return handle to the data dictionary item
*/
-Handle(DDS_DicItem) DDS_Dictionary::GetDicItem( const TCollection_AsciiString& theID,
+Handle_DDS_DicItem DDS_Dictionary::GetDicItem( const TCollection_AsciiString& theID,
const TCollection_AsciiString& theComponent ) const
{
Handle(DDS_DicItem) aDicItem;
}
/*!
- Gets dictionary item with specified identifier \atheID. Function find the item in all components.
- If item not found in any component then null handle returned.
+ \brief Get the data dictionary item by specified identifier \a theID.
+
+ Function searches the item in all components. If item is not found
+ in all components, null handle is returned.
+
+ \param theID data dictionary item ID
+ \return handle to the data dictionary item
*/
-Handle(DDS_DicItem) DDS_Dictionary::GetDicItem( const TCollection_AsciiString& theID ) const
+Handle_DDS_DicItem DDS_Dictionary::GetDicItem( const TCollection_AsciiString& theID ) const
{
Handle(DDS_DicItem) aDicItem;
for ( Standard_Integer i = 1; i <= myGroupMap.Extent() && aDicItem.IsNull(); i++ )
}
/*!
- Fill the internal data structures from XML parsed structures. Internal.
+ \brief Fill the internal data structures from the XML node.
+ \param theComponentData component XML node
+ \param theDocElement document XML node
*/
void DDS_Dictionary::FillDataMap( const LDOM_Element& theComponentData, const LDOM_Element& theDocElement )
{
}
/*!
- Convert numeric value \atheValue from specified unit of measure \atheUnits to SI unit of measure
- (mm for Length, radians for Angles, etc). Converted value returned.
+ \brief Convert numeric value \a theValue from specified measure units
+ \a theUnits to "SI" measure units (mm for Length, radians for Angles, etc).
+ \param theValue value being converted
+ \param theUnits measure units
+ \return converted value
*/
Standard_Real DDS_Dictionary::ToSI( const Standard_Real theValue, const Standard_CString theUnits )
{
}
/*!
- Convert numeric value \atheValue to specified unit of measure \atheUnits from SI unit of measure
- (mm for Length, radians for Angles, etc). Converted value returned.
+ \brief Convert numeric value \a theValue to specified measure units
+ \a theUnits from "SI" measure units (mm for Length, radians for Angles, etc).
+ \param theValue value being converted
+ \param theUnits measure units
+ \return converted value
*/
Standard_Real DDS_Dictionary::FromSI( const Standard_Real theValue, const Standard_CString theUnits )
{
/*!
\class DDS_KeyWords
+ \brief This class defines the pairs of internal keys and XML tags or
+ attributes names.
- This object contains the pairs of internal keys and XML tag or attribute names. This class allow to user
- define set of XML keywords used in datums definition file.
+ This class allows user to define a set of XML keywords used in the datums
+ definition (XML) file.
Default keywords table:
- \li D_URI - dictionary
- \li COMPONENT - component
- \li COMPONENT_NAME - name
- \li UNIT_SYSTEMS - unitSystems
- \li UNIT_SYSTEM - system
- \li UNIT_SYSTEM_NAME - name
- \li UNIT_SYSTEM_LABEL - label
- \li DATUM - datum
- \li DATUM_ID - id
- \li DATUM_LABEL - label
- \li DATUM_UNITS - units
- \li DATUM_FORMAT - format
- \li DATUM_FILTER - filter
- \li DATUM_REQUIRED - required
- \li VALUE_LIST - valueList
- \li VALUE_LIST_ID - listid
- \li VALUE_LIST_NAME - name
- \li VALUE_LIST_TYPE - type
- \li VALUE_LIST_VALUE - value
- \li VALUE_LIST_VALUEID - id
- \li VALUE_LIST_VALUEICON - icon
- \li DY_DOMAIN - domain
- \li WARNING_LEVEL - warningLevel
- \li WRONG_VALUE - wrongValue
- \li VALUE_DESCR - valueDescr
- \li VALUE_LIST_REF - listRef
- \li DESCR - description
- \li LONG_D - longDescr
- \li SHORT_D - shortDescr
- \li VD_TYPE - type
- \li VD_DEFV - default
- \li VD_MAXV - max
- \li VD_MINV - min
- \li VD_SPEC - specVal
- \li VLR_LIST - list
- \li PRS - presentation
- \li LATERAL_ZOOM - lateralZoom
- \li LZ_MINV - min
- \li LZ_MAXV - max
- \li LZ_ORDER - order
- \li OPTIONS - options
- \li OPTION - option
- \li OPTION_NAME - name
+ - \c D_URI - dictionary
+ - \c COMPONENT - component
+ - \c COMPONENT_NAME - name
+ - \c UNIT_SYSTEMS - unitSystems
+ - \c UNIT_SYSTEM - system
+ - \c UNIT_SYSTEM_NAME - name
+ - \c UNIT_SYSTEM_LABEL - label
+ - \c DATUM - datum
+ - \c DATUM_ID - id
+ - \c DATUM_LABEL - label
+ - \c DATUM_UNITS - units
+ - \c DATUM_FORMAT - format
+ - \c DATUM_FILTER - filter
+ - \c DATUM_REQUIRED - required
+ - \c VALUE_LIST - valueList
+ - \c VALUE_LIST_ID - listid
+ - \c VALUE_LIST_NAME - name
+ - \c VALUE_LIST_TYPE - type
+ - \c VALUE_LIST_VALUE - value
+ - \c VALUE_LIST_VALUEID - id
+ - \c VALUE_LIST_VALUEICON - icon
+ - \c DY_DOMAIN - domain
+ - \c WARNING_LEVEL - warningLevel
+ - \c WRONG_VALUE - wrongValue
+ - \c VALUE_DESCR - valueDescr
+ - \c VALUE_LIST_REF - listRef
+ - \c DESCR - description
+ - \c LONG_D - longDescr
+ - \c SHORT_D - shortDescr
+ - \c VD_TYPE - type
+ - \c VD_DEFV - default
+ - \c VD_MAXV - max
+ - \c VD_MINV - min
+ - \c VD_SPEC - specVal
+ - \c VLR_LIST - list
+ - \c PRS - presentation
+ - \c LATERAL_ZOOM - lateralZoom
+ - \c LZ_MINV - min
+ - \c LZ_MAXV - max
+ - \c LZ_ORDER - order
+ - \c OPTIONS - options
+ - \c OPTION - option
+ - \c OPTION_NAME - name
+
+ There is the only instance of the class DDS_KeyWords in the application
+ which can be retrieved by method Get().
*/
/*!
- Constructor
+ \brief Constructor.
+ Create an instance of the object. Can not be used directly.
+ Use Get() method instead.
*/
-
DDS_KeyWords::DDS_KeyWords()
: MMgt_TShared()
{
}
/*!
- Returns the static instance of the class DDS_KeyWords
+ \brief Get the only instance of the class DDS_KeyWords.
+ \return the only instance of the class
*/
-
-Handle(DDS_KeyWords) DDS_KeyWords::Get()
+Handle_DDS_KeyWords DDS_KeyWords::Get()
{
static Handle(DDS_KeyWords) keyWords;
}
/*!
- Returns the XML keyword by specified internal key \a key. If the internal key isn't registered
- then empty string will be returned.
-*/
+ \brief Get the XML keyword by specified internal key \a key.
+ If the internal key is not registered, empty string is returned.
+ \param key internal key
+ \return XML keyword
+*/
TCollection_AsciiString DDS_KeyWords::GetKeyWord( const TCollection_AsciiString& key ) const
{
TCollection_AsciiString keyWord;
}
/*!
- Register the pair of the internal key \a key and XML keyword \a keyWord.
+ \brief Register the pair of the internal key \a key and XML keyword \a keyWord.
+ \param key internal key
+ \param keyWord XML keyword
*/
-
void DDS_KeyWords::SetKeyWord( const TCollection_AsciiString& key,
const TCollection_AsciiString& keyWord )
{
lib_LTLIBRARIES = libDDS.la
-salomeinclude_HEADERS = DDS.h \
- DDS_DicGroup.h \
- DDS_DicItem.h \
- DDS_Dictionary.h \
+salomeinclude_HEADERS = \
+ DDS.h \
+ DDS_DicGroup.h \
+ DDS_DicItem.h \
+ DDS_Dictionary.h \
DDS_KeyWords.h
-dist_libDDS_la_SOURCES = DDS_DicGroup.cxx \
- DDS_DicItem.cxx \
- DDS_Dictionary.cxx \
+dist_libDDS_la_SOURCES = \
+ DDS_DicGroup.cxx \
+ DDS_DicItem.cxx \
+ DDS_Dictionary.cxx \
DDS_KeyWords.cxx
libDDS_la_CPPFLAGS=$(CAS_CPPFLAGS)
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-//
-//
-// File: SalomeApp.h
-// Created: November, 2004
-// Author: OCC team
-// Copyright (C) CEA 2004
-
-
-// The following ifdef block is the standard way of creating macros which make exporting
-// from a DLL simpler. All files within this DLL are compiled with the SalomeApp_EXPORTS
-// symbol defined on the command line. this symbol should not be defined on any project
-// that uses this DLL. This way any other project whose source files include this file see
-// SalomeApp_API functions as being imported from a DLL, wheras this DLL sees symbols
-// defined with this macro as being exported.
-#ifdef WNT
-
-#ifdef EVENT_EXPORTS
-#define EVENT_EXPORT __declspec(dllexport)
-#else
-#define EVENT_EXPORT __declspec(dllimport)
-#endif
-#else
-#define EVENT_EXPORT
-#endif //WNT
+#if !defined ( EVENT_H )
+#define EVENT_H
-#define APP_VERSION "0.1"
+#ifdef WIN32
+# ifdef EVENT_EXPORTS
+# define EVENT_EXPORT __declspec(dllexport)
+# else
+# define EVENT_EXPORT __declspec(dllimport)
+# endif
+#else //WIN32
+# define EVENT_EXPORT
+#endif //WIN32
-#if defined WNT
+#if defined WIN32
#pragma warning ( disable: 4251 )
#endif
+#endif // EVENT_H
--- /dev/null
+TEMPLATE = lib
+TARGET = Event
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+INCLUDEPATH += ../../include
+LIBS +=
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += EVENT_EXPORTS
+
+HEADERS = Event.h
+HEADERS += SALOME_Event.h
+
+SOURCES = SALOME_Event.cxx
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+INSTALLS += includes
salomeinclude_HEADERS= \
Event.h \
- SALOME_Event.hxx
+ SALOME_Event.h
dist_libEvent_la_SOURCES = SALOME_Event.cxx
-libEvent_la_CPPFLAGS=$(QT_INCLUDES) @KERNEL_CXXFLAGS@
+libEvent_la_CPPFLAGS=$(QT_INCLUDES)
libEvent_la_LDFLAGS=$(QT_MT_LIBS)
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-//
-//
// File : SALOME_Event.cxx
// Author : Sergey ANIKIN
-// Module : KERNEL
-// $Header$
-#include "SALOME_Event.hxx"
+#include "SALOME_Event.h"
-//#include "utilities.h"
-
-#include <qsemaphore.h>
-#include <qapplication.h>
-#include <qthread.h>
+#include <QSemaphore>
+#include <QApplication>
// asv 21.02.05 : introducing multi-platform approach of thread comparison
-// on Unix using pthread_t type for storing ThreadId
-// on Win32 using integer type for storing ThreadId
+// - on Unix using pthread_t type for storing ThreadId
+// - on Win32 using integer type for storing ThreadId
// NOT using integer ThreadId on both Unix and Win32 because (from documentation):
// "...Do not allow your program to rely on the internal structure or size of the pthread_t..."
#ifdef WIN32
#include <windows.h>
-
static DWORD myThread;
#else
-#include <qthread.h>
#include <pthread.h>
-
static pthread_t myThread;
#endif
/*!
- \return thread id
+ \class SALOME_CustomEvent
+ \brief Generic event class for user-defined events
+
+ This class contains a generic void* data member that may be used
+ for transferring event-specific data to the receiver.
+
+ \warning The internal data is not destroyed by the class destructor.
+*/
+
+/*!
+ \brief Constructor.
+ \param type event type
+*/
+SALOME_CustomEvent::SALOME_CustomEvent( int type )
+: QEvent( (QEvent::Type)type ), d( 0 )
+{
+}
+
+/*!
+ \brief Constructor.
+ \param type event type
+ \param data custom data
+*/
+SALOME_CustomEvent::SALOME_CustomEvent( QEvent::Type type, void* data )
+: QEvent( type ), d( data )
+{
+}
+
+/*!
+ \brief Get custom data.
+ \return pointer to the internal data
+*/
+void* SALOME_CustomEvent::data() const
+{
+ return d;
+}
+
+/*!
+ \brief Set custom data.
+ \param data pointer to the internal data
+*/
+void SALOME_CustomEvent::setData( void* data )
+{
+ d = data;
+}
+
+/*!
+ \class SALOME_Event
+ \brief The class which encapsulates data and functionality required for
+ posting component-specific events to perform arbitrary operations
+ in the main GUI thread.
+
+ SALOME_Event objects can be posted by any thread belonging to the GUI process.
+
+ It is necessary to derive a custom event class from SALOME_Event and
+ re-implement virtual Execute() method. This method should actually perform
+ the desirable operation. To pass all the required data to Execute() and
+ store a return value, arbitrary data fields can be added to the custom
+ event class. There is no need to protect such fields with a mutex, for only
+ one thread working with a SALOME_Event object is active at any moment.
+
+ Usage:
+ - Create SALOME_Event. Components can derive their own event class from
+ SALOME_Event in order to pass custom data to the event handler.
+ - Call process() method to post the event. After process() execution
+ it is possible to examine fields of your custom event object.
+ - Perform delete operator on the event to wake up the desktop (you can also
+ set <autoRelease> parameter to \c true to automatically wake up desktop after
+ process().
+
+ The method processed() is used by the desktop to signal that event processing
+ has been completed.
+
+ To make all this work, it is necessary to call static method GetSessionThread()
+ during the application initialization, i.e. from main() function.
+ It is important to call this method from the primary application thread.
+
+ Caveats:
+ - there are no.
+*/
+
+//! Total number of semaphore resources
+const int NumberOfResources = 2;
+
+/*!
+ \brief Initialize event mechanism.
+
+ This function sets up the main application thread. It should be called
+ during the application initialization, i.e. main() function.
*/
void SALOME_Event::GetSessionThread(){
#ifdef WIN32
}
/*!
- \return true if it is session thread
+ \brief Check if the processing is in the main application thread.
+ \return \c true if this method is called from the main application thread
*/
bool SALOME_Event::IsSessionThread(){
bool aResult = false;
#else
aResult = myThread == pthread_self();
#endif
-// if(MYDEBUG) INFOS("IsSessionThread() - "<<aResult);
return aResult;
}
-
/*!
- Constructor
+ \brief Constructor.
*/
SALOME_Event::SALOME_Event(){
-// if(MYDEBUG) MESSAGE( "SALOME_Event::SALOME_Event(): this = "<<this );
// Prepare the semaphore
- mySemaphore = new QSemaphore( 2 );
- *mySemaphore += 2;
+ mySemaphore = new QSemaphore( NumberOfResources );
+ mySemaphore->acquire( NumberOfResources );
}
/*!
- Destructor
+ \brief Destructor.
*/
SALOME_Event::~SALOME_Event(){
-// if(MYDEBUG) MESSAGE( "SALOME_Event::~SALOME_Event(): this = "<<this );
- if ( mySemaphore->available() < mySemaphore->total() )
- *mySemaphore -= mySemaphore->total() - mySemaphore->available();
+ if ( mySemaphore->available() < NumberOfResources )
+ mySemaphore->release( NumberOfResources - mySemaphore->available() );
delete mySemaphore;
}
/*!
- Posts the event and optionally waits for its completion
+ \brief Post the event and wait for its completion.
+ \sa processed()
*/
void SALOME_Event::process()
{
- QThread::postEvent( qApp, new QCustomEvent( SALOME_EVENT, (void*)this ) );
-// if(MYDEBUG) MESSAGE( "SALOME_Event::process(): this = "<<this<<", *mySemaphore += 1 " );
- *mySemaphore += 1;
-// if(MYDEBUG) MESSAGE( "SALOME_Event::process(): this = "<<this<<" - COMPLETED" );
+ QApplication::postEvent( qApp, new SALOME_CustomEvent( SALOME_EVENT, (void*)this ) );
+ mySemaphore->acquire( 1 );
}
/*!
- Signals that this event has been processed
+ \brief Use this method to signal that this event has been processed.
*/
void SALOME_Event::processed()
{
-// if(MYDEBUG) MESSAGE( "SALOME_Event::processed(): this = "<<this );
- // process() takes control over mySemaphore after the next line is executed
- *mySemaphore -= 1;
+ mySemaphore->release( 1 );
}
+
+/*!
+ \fn virtual void SALOME_Event::Execute();
+ \brief This method should be redefined in the successor classes
+ to do real work.
+*/
+
+/*!
+ \class TMemFunEvent
+ \brief Template class for event which calls the function
+ without arguments and returning result.
+*/
+
+/*!
+ \class TVoidMemFunEvent
+ \brief Template class for event which calls the function
+ without arguments and without return value.
+*/
+
+/*!
+ \class TMemFun1ArgEvent
+ \brief Template class for event which calls the function
+ with one argument and returning result.
+*/
+
+/*!
+ \class TVoidMemFun1ArgEvent
+ \brief Template class for event which calls the function
+ with one argument and without return value.
+*/
+
+/*!
+ \class TMemFun2ArgEvent
+ \brief Template class for event which calls the function
+ with two arguments and returning result.
+*/
+
+/*!
+ \class TVoidMemFun2ArgEvent
+ \brief Template class for event which calls the function
+ with two arguments and without return value.
+*/
+
+/*!
+ \fn ProcessEvent
+ \brief Template function for processing events with return value.
+*/
+
+/*!
+ \fn ProcessVoidEvent
+ \brief Template function for processing events without return value.
+*/
--- /dev/null
+// KERNEL SALOME_Event : Define event posting mechanism
+//
+// Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
+// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File : SALOME_Event.h
+// Author : Sergey ANIKIN
+
+#ifndef SALOME_EVENT_H
+#define SALOME_EVENT_H
+
+#include <Event.h>
+
+#include <QEvent>
+
+//! SALOME custom event type
+#define SALOME_EVENT QEvent::Type( QEvent::User + 10000 )
+
+class EVENT_EXPORT SALOME_CustomEvent : public QEvent
+{
+public:
+ SALOME_CustomEvent( int type );
+ SALOME_CustomEvent( QEvent::Type type, void* data );
+
+ void* data() const;
+ void setData( void* data );
+
+private:
+ void *d; //!< internal data
+};
+
+class QSemaphore;
+
+class EVENT_EXPORT SALOME_Event
+{
+public:
+ SALOME_Event();
+ virtual ~SALOME_Event();
+
+ virtual void Execute() = 0;
+
+ static bool IsSessionThread();
+ void process();
+
+protected:
+ void processed();
+ friend class SalomeApp_EventFilter;
+
+ static void GetSessionThread();
+ friend int main(int, char **);
+
+private:
+ QSemaphore* mySemaphore; //!< internal semaphore
+};
+
+template<class TObject, typename TRes> class TMemFunEvent : public SALOME_Event
+{
+public:
+ typedef TRes TResult;
+ TResult myResult;
+ typedef TResult (TObject::* TAction)();
+ TMemFunEvent(TObject* theObject, TAction theAction,
+ TResult theResult = TResult()):
+ myObject(theObject),
+ myAction(theAction),
+ myResult(theResult)
+ {}
+ virtual void Execute()
+ {
+ myResult = (myObject->*myAction)();
+ }
+private:
+ TObject* myObject;
+ TAction myAction;
+};
+
+template<class TObject> class TVoidMemFunEvent : public SALOME_Event
+{
+public:
+ typedef void (TObject::* TAction)();
+ TVoidMemFunEvent(TObject* theObject, TAction theAction):
+ myObject(theObject),
+ myAction(theAction)
+ {}
+ virtual void Execute()
+ {
+ (myObject->*myAction)();
+ }
+private:
+ TObject* myObject;
+ TAction myAction;
+};
+
+template<class TObject, typename TRes, typename TArg, typename TStoreArg = TArg>
+class TMemFun1ArgEvent : public SALOME_Event
+{
+public:
+ typedef TRes TResult;
+ TResult myResult;
+ typedef TResult (TObject::* TAction)(TArg);
+ TMemFun1ArgEvent(TObject* theObject, TAction theAction, TArg theArg,
+ TResult theResult = TResult()):
+ myObject(theObject),
+ myAction(theAction),
+ myResult(theResult),
+ myArg(theArg)
+ {}
+ virtual void Execute()
+ {
+ myResult = (myObject->*myAction)(myArg);
+ }
+private:
+ TObject* myObject;
+ TAction myAction;
+ TStoreArg myArg;
+};
+
+template<class TObject, typename TArg, typename TStoreArg = TArg>
+class TVoidMemFun1ArgEvent : public SALOME_Event
+{
+public:
+ typedef void (TObject::* TAction)(TArg);
+ TVoidMemFun1ArgEvent(TObject* theObject, TAction theAction, TArg theArg):
+ myObject(theObject),
+ myAction(theAction),
+ myArg(theArg)
+ {}
+ virtual void Execute()
+ {
+ (myObject->*myAction)(myArg);
+ }
+private:
+ TObject* myObject;
+ TAction myAction;
+ TStoreArg myArg;
+};
+
+template<class TObject, typename TRes, typename TArg, typename TArg1, typename TStoreArg = TArg, typename TStoreArg1 = TArg1>
+class TMemFun2ArgEvent: public SALOME_Event
+{
+public:
+ typedef TRes TResult;
+ TResult myResult;
+ typedef TResult (TObject::* TAction)(TArg,TArg1);
+ TMemFun2ArgEvent(TObject* theObject, TAction theAction,
+ TArg theArg, TArg1 theArg1,
+ TResult theResult = TResult()):
+ myObject(theObject),
+ myAction(theAction),
+ myResult(theResult),
+ myArg(theArg),
+ myArg1(theArg1)
+ {}
+ virtual void Execute()
+ {
+ myResult = (myObject->*myAction)(myArg,myArg1);
+ }
+private:
+ TObject* myObject;
+ TAction myAction;
+ TStoreArg myArg;
+ TStoreArg1 myArg1;
+};
+
+template<class TObject, typename TArg, typename TArg1, typename TStoreArg = TArg, typename TStoreArg1 = TArg1>
+class TVoidMemFun2ArgEvent : public SALOME_Event
+{
+public:
+ typedef void (TObject::* TAction)(TArg,TArg1);
+ TVoidMemFun2ArgEvent(TObject* theObject, TAction theAction, TArg theArg, TArg1 theArg1):
+ myObject(theObject),
+ myAction(theAction),
+ myArg(theArg),
+ myArg1(theArg1)
+ {}
+ virtual void Execute()
+ {
+ (myObject->*myAction)(myArg,myArg1);
+ }
+private:
+ TObject* myObject;
+ TAction myAction;
+ TStoreArg myArg;
+ TStoreArg1 myArg1;
+};
+
+template<class TEvent> inline typename TEvent::TResult ProcessEvent(TEvent* theEvent)
+{
+ typename TEvent::TResult aResult;
+ if(SALOME_Event::IsSessionThread()) {
+ theEvent->Execute();
+ aResult = theEvent->myResult;
+ }
+ else {
+ theEvent->process();
+ aResult = theEvent->myResult;
+ }
+ delete theEvent;
+ return aResult;
+}
+
+inline void ProcessVoidEvent(SALOME_Event* theEvent)
+{
+ if(SALOME_Event::IsSessionThread()) {
+ theEvent->Execute();
+ }
+ else {
+ theEvent->process();
+ }
+ delete theEvent;
+}
+
+#endif // SALOME_EVENT_H
+++ /dev/null
-// KERNEL SALOME_Event : Define event posting mechanism
-//
-// Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-//
-//
-// File : SALOME_Event.hxx
-// Author : Sergey ANIKIN
-// Module : KERNEL
-// $Header$
-
-
-#ifndef SALOME_Event_HeaderFile
-#define SALOME_Event_HeaderFile
-
-#include <qevent.h>
-
-#define SALOME_EVENT QEvent::Type( QEvent::User + 10000 )
-
-class QSemaphore;
-
-/*!
- * \class SALOME_Event
- * Description:
- * This class encapsulates data and functionality required for
- * posting component-specific events to perform arbitrary operations in main GUI thread.
- * SALOME_Event objects can be posted by any thread belonging to the GUI process.
- *
- * It is necessary to derive a custom event class from SALOME_Event and
- * re-implement virtual Execute() method. This method should actually perform
- * the desirable operation. To pass all the required data to Execute() and store a return value,
- * arbitrary data fields can be added to the custom event class. There is
- * no need to protect such fields with a mutex, for only one thread working with
- * a SALOME_Event object is active at any moment.
- *
- * Usage:
- * - create SALOME_Event.
- * Components can derive their own event class from SALOME_Event
- * in order to pass custom data to the event handler.
- * - call process() method to post the event. After process() execution
- * it is possible to examine fields of your custom event object.
- * - perform delete operator on the event to wake up the desktop (you can also set <autoRelease>
- * parameter to TRUE to automatically wake up desktop after process()
- *
- * processed() method is used by the desktop to signal that event processing
- * has been completed.
- *
- * Caveats:
- * There is no.
- */
-
-#include <Event.h>
-
-class EVENT_EXPORT SALOME_Event{
-public:
- SALOME_Event();
- virtual ~SALOME_Event();
-
- // To do real work
- virtual void Execute() = 0;
-
- static bool IsSessionThread();
- void process();
-
-protected:
- void processed();
- friend class SalomeApp_EventFilter;
-
- static void GetSessionThread();
- friend int main(int, char **);
-
-private:
- QSemaphore* mySemaphore;
-};
-
-
-/*!
- \class TMemFunEvent
- \brief Template class for member function
-*/
-template<class TObject, typename TRes> class /*EVENT_EXPORT */TMemFunEvent: public SALOME_Event{
-public:
- typedef TRes TResult;
- TResult myResult;
- typedef TResult (TObject::* TAction)();
- TMemFunEvent(TObject* theObject, TAction theAction,
- TResult theResult = TResult()):
- myObject(theObject),
- myAction(theAction),
- myResult(theResult)
- {}
- virtual void Execute(){
- myResult = (myObject->*myAction)();
- }
-private:
- TObject* myObject;
- TAction myAction;
-};
-
-
-/*!
- \class TVoidMemFunEvent
- \brief Template class for member function
-*/
-template<class TObject> class /*EVENT_EXPORT */TVoidMemFunEvent: public SALOME_Event{
-public:
- typedef void (TObject::* TAction)();
- TVoidMemFunEvent(TObject* theObject, TAction theAction):
- myObject(theObject),
- myAction(theAction)
- {}
- virtual void Execute(){
- (myObject->*myAction)();
- }
-private:
- TObject* myObject;
- TAction myAction;
-};
-
-
-/*!
- \class TMemFun1ArgEvent
- \brief Template for member function with one argument
-*/
-template<class TObject, typename TRes, typename TArg, typename TStoreArg = TArg> class/* EVENT_EXPORT */TMemFun1ArgEvent:
-public SALOME_Event{
-public:
- typedef TRes TResult;
- TResult myResult;
- typedef TResult (TObject::* TAction)(TArg);
- TMemFun1ArgEvent(TObject* theObject, TAction theAction, TArg theArg,
- TResult theResult = TResult()):
- myObject(theObject),
- myAction(theAction),
- myResult(theResult),
- myArg(theArg)
- {}
- virtual void Execute(){
- myResult = (myObject->*myAction)(myArg);
- }
-private:
- TObject* myObject;
- TAction myAction;
- TStoreArg myArg;
-};
-
-
-/*!
- \class TVoidMemFun1ArgEvent
- \brief Template for member function with one argument
-*/
-template<class TObject, typename TArg, typename TStoreArg = TArg> class /*EVENT_EXPORT */TVoidMemFun1ArgEvent: public SALOME_Event{
-public:
- typedef void (TObject::* TAction)(TArg);
- TVoidMemFun1ArgEvent(TObject* theObject, TAction theAction, TArg theArg):
- myObject(theObject),
- myAction(theAction),
- myArg(theArg)
- {}
- virtual void Execute(){
- (myObject->*myAction)(myArg);
- }
-private:
- TObject* myObject;
- TAction myAction;
- TStoreArg myArg;
-};
-
-
-/*!
- \class TMemFun2ArgEvent
- \brief Template for member function with two arguments
-*/
-template<class TObject, typename TRes, typename TArg, typename TArg1, typename TStoreArg = TArg, typename TStoreArg1 = TArg1> class
-/*EVENT_EXPORT */TMemFun2ArgEvent: public SALOME_Event{
-public:
- typedef TRes TResult;
- TResult myResult;
- typedef TResult (TObject::* TAction)(TArg,TArg1);
- TMemFun2ArgEvent(TObject* theObject, TAction theAction,
- TArg theArg, TArg1 theArg1,
- TResult theResult = TResult()):
- myObject(theObject),
- myAction(theAction),
- myResult(theResult),
- myArg(theArg),
- myArg1(theArg1)
- {}
- virtual void Execute(){
- myResult = (myObject->*myAction)(myArg,myArg1);
- }
-private:
- TObject* myObject;
- TAction myAction;
- TStoreArg myArg;
- TStoreArg1 myArg1;
-};
-
-
-/*!
- \class TVoidMemFun2ArgEvent
- \brief Template for member function with two arguments
-*/
-template<class TObject, typename TArg, typename TArg1, typename TStoreArg = TArg, typename TStoreArg1 = TArg1> class
-/*EVENT_EXPORT*/ TVoidMemFun2ArgEvent: public SALOME_Event{
-public:
- typedef void (TObject::* TAction)(TArg,TArg1);
- TVoidMemFun2ArgEvent(TObject* theObject, TAction theAction, TArg theArg, TArg1 theArg1):
- myObject(theObject),
- myAction(theAction),
- myArg(theArg),
- myArg1(theArg1)
- {}
- virtual void Execute(){
- (myObject->*myAction)(myArg,myArg1);
- }
-private:
- TObject* myObject;
- TAction myAction;
- TStoreArg myArg;
- TStoreArg1 myArg1;
-};
-
-
-/*!
- \fn ProcessEvent
- \brief Template function for processing events with result returing
-*/
-template<class TEvent> inline typename TEvent::TResult ProcessEvent(TEvent* theEvent){
- typename TEvent::TResult aResult;
- if(SALOME_Event::IsSessionThread()){
- theEvent->Execute();
- aResult = theEvent->myResult;
- }else{
- theEvent->process();
- aResult = theEvent->myResult;
- }
- delete theEvent;
- return aResult;
-}
-
-
-/*!
- \fn ProcessEvent
- \brief Template function for processing events without result
-*/
-inline void ProcessVoidEvent(SALOME_Event* theEvent){
- if(SALOME_Event::IsSessionThread()){
- theEvent->Execute();
- }else{
- theEvent->process();
- }
- delete theEvent;
-}
-
-
-#endif
// Created: November, 2004
//! Macro for exports
-#ifdef WNT
+#ifdef WIN32
#ifdef GLVIEWER_EXPORTS
#define GLVIEWER_API __declspec(dllexport)
#else
#define GLVIEWER_API
-#endif // WNT
+#endif // WIN32
--- /dev/null
+TEMPLATE = lib
+TARGET = GLViewer
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+CASROOT = $$(CASROOT)
+CAS_CPPFLAGS = $${CASROOT}/inc
+
+CAS_KERNEL = -L$${CASROOT}/Linux/lib -lTKernel
+
+GL_LIBS = -L/usr/X11R6/lib$$(LIB_LOCATION_SUFFIX) -lGLU
+
+INCLUDEPATH += $$(QTDIR)/include/QtOpenGL ../../include $${CAS_CPPFLAGS} ../Qtx ../SUIT
+LIBS += -L../../lib -lqtx -lsuit $${GL_LIBS} $${CAS_KERNEL}
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += GLVIEWER_EXPORTS OCC_VERSION_MAJOR=6 OCC_VERSION_MINOR=1 OCC_VERSION_MAINTENANCE=1 LIN LINTEL CSFDB No_exception HAVE_CONFIG_H HAVE_LIMITS_H HAVE_WOK_CONFIG_H OCC_CONVERT_SIGNALS
+
+HEADERS = GLViewer.h
+HEADERS += GLViewer_AspectLine.h
+HEADERS += GLViewer_BaseDrawers.h
+HEADERS += GLViewer_BaseObjects.h
+HEADERS += GLViewer_Compass.h
+HEADERS += GLViewer_Context.h
+HEADERS += GLViewer_CoordSystem.h
+HEADERS += GLViewer_Defs.h
+HEADERS += GLViewer_Drawer.h
+HEADERS += GLViewer_Geom.h
+HEADERS += GLViewer_Grid.h
+HEADERS += GLViewer_Group.h
+HEADERS += GLViewer_MimeData.h
+HEADERS += GLViewer_Object.h
+HEADERS += GLViewer_Selector.h
+HEADERS += GLViewer_Selector2d.h
+HEADERS += GLViewer_Text.h
+HEADERS += GLViewer_Tools.h
+HEADERS += GLViewer_ToolTip.h
+HEADERS += GLViewer_ViewFrame.h
+HEADERS += GLViewer_ViewManager.h
+HEADERS += GLViewer_ViewPort.h
+HEADERS += GLViewer_ViewPort2d.h
+HEADERS += GLViewer_Viewer.h
+HEADERS += GLViewer_Viewer2d.h
+HEADERS += GLViewer_Widget.h
+
+SOURCES = GLViewer_AspectLine.cxx
+SOURCES += GLViewer_BaseDrawers.cxx
+SOURCES += GLViewer_BaseObjects.cxx
+SOURCES += GLViewer_Compass.cxx
+SOURCES += GLViewer_Context.cxx
+SOURCES += GLViewer_CoordSystem.cxx
+SOURCES += GLViewer_Drawer.cxx
+SOURCES += GLViewer_Geom.cxx
+SOURCES += GLViewer_Grid.cxx
+SOURCES += GLViewer_Group.cxx
+SOURCES += GLViewer_MimeData.cxx
+SOURCES += GLViewer_Object.cxx
+SOURCES += GLViewer_Selector.cxx
+SOURCES += GLViewer_Selector2d.cxx
+SOURCES += GLViewer_Text.cxx
+SOURCES += GLViewer_Tools.cxx
+SOURCES += GLViewer_ToolTip.cxx
+SOURCES += GLViewer_ViewFrame.cxx
+SOURCES += GLViewer_ViewManager.cxx
+SOURCES += GLViewer_ViewPort.cxx
+SOURCES += GLViewer_ViewPort2d.cxx
+SOURCES += GLViewer_Viewer.cxx
+SOURCES += GLViewer_Viewer2d.cxx
+SOURCES += GLViewer_Widget.cxx
+
+TRANSLATIONS = resources/GLViewer_images.ts \
+ resources/GLViewer_msg_en.ts
+
+ICONS = resources/*.png
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+resources.files = $$ICONS resources/*.qm
+resources.path = ../../resources
+
+INSTALLS += includes resources
int aHR = myHColor.red(), aHG = myHColor.green(), aHB = myHColor.blue();
int aSR = mySColor.red(), aSG = mySColor.green(), aSB = mySColor.blue();
- QByteArray aResult( anISize * 10 + aFSize );
+ QByteArray aResult;
+ aResult.resize( anISize * 10 + aFSize );
int i = 0;
#include "GLViewer.h"
-#include <qcolor.h>
+#include <QColor>
-#ifdef WNT
+#ifdef WIN32
#pragma warning( disable:4251 )
#endif
int myLineType;
};
-#ifdef WNT
+#ifdef WIN32
#pragma warning ( default:4251 )
#endif
#include "GLViewer_AspectLine.h"
#include "GLViewer_BaseObjects.h"
+// Qt includes
+#include <QColor>
+
+
#ifndef WIN32
#include <GL/glx.h>
#endif
*/
void GLViewer_MarkerDrawer::create( float xScale, float yScale, bool onlyUpdate )
{
- QValueList<int>::Iterator it;
- QValueList<int>::Iterator EndIt;
- QValueList<GLViewer_Object*>::Iterator anObjectIt = myObjects.begin();
- QValueList<GLViewer_Object*>::Iterator anEndObjectIt = myObjects.end();
+ QList<int>::Iterator it;
+ QList<int>::Iterator EndIt;
+ QList<GLViewer_Object*>::Iterator anObjectIt = myObjects.begin();
+ QList<GLViewer_Object*>::Iterator anEndObjectIt = myObjects.end();
myXScale = xScale;
myYScale = yScale;
float* anYCoord = aMarkerSet->getYCoord();
float aRadius = aMarkerSet->getMarkerSize();
- QValueList<int> aHNumbers, anUHNumbers, aSelNumbers, anUSelNumbers;
+ QList<int> aHNumbers, anUHNumbers, aSelNumbers, anUSelNumbers;
aMarkerSet->exportNumbers( aHNumbers, anUHNumbers, aSelNumbers, anUSelNumbers );
if( onlyUpdate )
*/
void GLViewer_PolylineDrawer::create( float xScale, float yScale, bool onlyUpdate )
{
- QValueList<GLViewer_Object*>::Iterator aObjectIt = myObjects.begin();
- QValueList<GLViewer_Object*>::Iterator aObjectEndIt = myObjects.end();
+ QList<GLViewer_Object*>::Iterator aObjectIt = myObjects.begin();
+ QList<GLViewer_Object*>::Iterator aObjectEndIt = myObjects.end();
myXScale = xScale;
myYScale = yScale;
*/
void GLViewer_TextDrawer::create( float xScale, float yScale, bool onlyUpdate )
{
- QValueList<GLViewer_Object*>::Iterator aObjectIt = myObjects.begin();
- QValueList<GLViewer_Object*>::Iterator aObjectEndIt = myObjects.end();
+ QList<GLViewer_Object*>::Iterator aObjectIt = myObjects.begin();
+ QList<GLViewer_Object*>::Iterator aObjectEndIt = myObjects.end();
myXScale = xScale;
myYScale = yScale;
*/
void GLViewer_TextDrawer::updateObjects()
{
- QValueList<GLViewer_Object*>::Iterator aObjectIt = myObjects.begin();
- QValueList<GLViewer_Object*>::Iterator aObjectEndIt = myObjects.end();
+ QList<GLViewer_Object*>::Iterator aObjectIt = myObjects.begin();
+ QList<GLViewer_Object*>::Iterator aObjectEndIt = myObjects.end();
for( ; aObjectIt != aObjectEndIt; aObjectIt++ )
(*aObjectIt)->compute();
}
#ifndef GLVIEWER_BASEDRAWERS_H
#define GLVIEWER_BASEDRAWERS_H
-#include <qcolor.h>
-#include <qobject.h>
-#include <qfile.h>
-#include <qfont.h>
-#include <qgl.h>
+class QColor;
#include "GLViewer.h"
#include "GLViewer_Drawer.h"
class GLViewer_AspectLine;
-#ifdef WNT
+#ifdef WIN32
#pragma warning( disable:4251 )
#endif
void updateObjects();
};
-#ifdef WNT
+#ifdef WIN32
#pragma warning ( default:4251 )
#endif
#include "GLViewer_Drawer.h"
+#include <QFile>
+
//#include <cmath>
//using namespace std;
}
aBuffer+="closepath\nstroke\n";
- hFile.writeBlock( aBuffer.ascii(), aBuffer.length() );
+ hFile.write( aBuffer.toAscii() );
return true;
}
}
aBuffer+="PU;\n";
- hFile.writeBlock( aBuffer.ascii(), aBuffer.length() );
+ hFile.write( aBuffer.toAscii() );
}
return true;
for ( int i = 0; i < myNumber; i++ )
{
- xa = QMIN( xa, myXCoord[i] );
- xb = QMAX( xb, myXCoord[i] );
- ya = QMIN( ya, myYCoord[i] );
- yb = QMAX( yb, myYCoord[i] );
+ xa = qMin( xa, myXCoord[i] );
+ xb = qMax( xb, myXCoord[i] );
+ ya = qMin( ya, myYCoord[i] );
+ yb = qMax( yb, myYCoord[i] );
}
myXGap = ( xb - xa ) / 10;
// cout << "GLViewer_MarkerSet::highlight " << x <<" " << y << " " << tol << endl;
int count = 0;
GLfloat xdist, ydist, radius;
- QValueList<int>::Iterator it;
- QValueList<int> curHNumbers;
+ QList<int>::Iterator it;
+ QList<int> curHNumbers;
bool isFound;
GLboolean update;
int cnt = 0;
// cout << "GLViewer_MarkerSet::select " << x << " " << y << endl;
int count = 0;
GLfloat xdist, ydist, radius;
- QValueList<int>::Iterator it;
- QValueList<int>::Iterator it1;
- QValueList<int>::Iterator remIt;
- QValueList<int>::Iterator curIt;
+ QList<int>::Iterator it;
+ QList<int>::Iterator it1;
+ QList<int>::Iterator remIt;
+ QList<int>::Iterator curIt;
radius = tol - myMarkerSize / 2.;
for ( it1 = myHNumbers.begin(); it1 != myHNumbers.end(); ++it1 )
if( i == *it1 )
{
- myHNumbers.remove( it1 );
+ myHNumbers.erase( it1 );
break;
}
for ( it1 = myUHNumbers.begin(); it1 != myUHNumbers.end(); ++it1 )
if( i == *it1 )
{
- myUHNumbers.remove( it1 );
+ myUHNumbers.erase( it1 );
break;
}
}
else
{
- mySelNumbers.remove( remIt );
+ mySelNumbers.erase( remIt );
for ( curIt = myCurSelNumbers.begin(); curIt != myCurSelNumbers.end(); ++curIt )
if( *curIt == *remIt)
{
- myCurSelNumbers.remove( curIt );
+ myCurSelNumbers.erase( curIt );
break;
}
for ( it1 = myHNumbers.begin(); it1 != myHNumbers.end(); ++it1 )
if( i == *it1 )
{
- myHNumbers.remove( it1 );
+ myHNumbers.erase( it1 );
break;
}
for ( it1 = myUHNumbers.begin(); it1 != myUHNumbers.end(); ++it1 )
if( i == *it1 )
{
- myUHNumbers.remove( it1 );
+ myUHNumbers.erase( it1 );
break;
}
}
for ( it1 = myHNumbers.begin(); it1 != myHNumbers.end(); ++it1 )
if( i == *it1 )
{
- myHNumbers.remove( it1 );
+ myHNumbers.erase( it1 );
break;
}
for ( it1 = myUHNumbers.begin(); it1 != myUHNumbers.end(); ++it1 )
if( i == *it1 )
{
- myUHNumbers.remove( it1 );
+ myUHNumbers.erase( it1 );
break;
}
}
for( it1 = myUSelNumbers.begin(); it1 != myUSelNumbers.end(); ++it1 )
if( *it == *it1 )
{
- it1 = myUSelNumbers.remove( it1 );
+ it1 = myUSelNumbers.erase( it1 );
it1--;
}
/*!
Export numbers of highlighted/selected lines
*/
-void GLViewer_MarkerSet::exportNumbers( QValueList<int>& highlight,
- QValueList<int>& unhighlight,
- QValueList<int>& select,
- QValueList<int>& unselect )
+void GLViewer_MarkerSet::exportNumbers( QList<int>& highlight,
+ QList<int>& unhighlight,
+ QList<int>& select,
+ QList<int>& unselect )
{
highlight = myHNumbers;
unhighlight = myUHNumbers;
if( index < 0 || index > myNumber )
return FALSE;
- int n = mySelNumbers.findIndex( index );
+ int n = mySelNumbers.indexOf( index );
if( n == -1 )
mySelNumbers.append( index );
else
{
- QValueList<int>::Iterator it;
- it = mySelNumbers.at( n );
- mySelNumbers.remove( it );
+ mySelNumbers.removeAt(n);
myUSelNumbers.append( index );
}
return TRUE;
void GLViewer_MarkerSet::addSelected( const TColStd_SequenceOfInteger& seq )
{
for ( int i = 1; i <= seq.Length(); i++ )
- if( mySelNumbers.findIndex( seq.Value( i ) ) == -1 )
+ if( mySelNumbers.indexOf( seq.Value( i ) ) == -1 )
mySelNumbers.append( seq.Value( i ) - 1 );
}
*/
void GLViewer_MarkerSet::setSelected( const TColStd_SequenceOfInteger& seq )
{
-// for( QValueList<int>::Iterator it = mySelNumbers.begin(); it != mySelNumbers.end(); ++it )
+// for( QList<int>::Iterator it = mySelNumbers.begin(); it != mySelNumbers.end(); ++it )
// if( myUSelNumbers.findIndex( *it ) == -1 )
// myUSelNumbers.append( *it );
QByteArray aObject = GLViewer_Object::getByteCopy();
- QByteArray aResult( anISize + 2*aFSize*myNumber + aFSize + aObject.size());
+ QByteArray aResult;
+ aResult.resize( anISize + 2*aFSize*myNumber + aFSize + aObject.size());
char* aPointer = (char*)&myNumber;
for( i = 0; i < anISize; i++, aPointer++ )
*aPointer = theArray[i];
int aCurIndex = anISize + 2*aFSize*myNumber + aFSize;
- QByteArray aObject( aSize - aCurIndex );
+ QByteArray aObject;
+ aObject.resize( aSize - aCurIndex );
for( ; i < aSize; i++ )
aObject[i - aCurIndex] = theArray[i];
aBuffer+="closepath\nstroke\n";
- hFile.writeBlock( aBuffer.ascii(), aBuffer.length() );
+ hFile.write( aBuffer.toAscii() );
return true;
}
aBuffer+="PU;\n";
- hFile.writeBlock( aBuffer.ascii(), aBuffer.length() );
+ hFile.write( aBuffer.toAscii() );
return true;
}
for ( int i = 0; i < myNumber; i++ )
{
- xa = QMIN( xa, myXCoord[i] );
- xb = QMAX( xb, myXCoord[i] );
- ya = QMIN( ya, myYCoord[i] );
- yb = QMAX( yb, myYCoord[i] );
+ xa = qMin( xa, myXCoord[i] );
+ xb = qMax( xb, myXCoord[i] );
+ ya = qMin( ya, myYCoord[i] );
+ yb = qMax( yb, myYCoord[i] );
}
GLfloat xGap = ( xb - xa ) / 10;
/*!
Export numbers of highlighted/selected lines
*/
-void GLViewer_Polyline::exportNumbers( QValueList<int>& highlight,
- QValueList<int>& unhighlight,
- QValueList<int>& select,
- QValueList<int>& unselect )
+void GLViewer_Polyline::exportNumbers( QList<int>& highlight,
+ QList<int>& unhighlight,
+ QList<int>& select,
+ QList<int>& unselect )
{
highlight = myHNumbers;
unhighlight = myUHNumbers;
QByteArray aObject = GLViewer_Object::getByteCopy();
- QByteArray aResult( aFSize*myNumber*2 + anISize + 2*aBSize + aObject.size());
+ QByteArray aResult;
+ aResult.resize( aFSize*myNumber*2 + anISize + 2*aBSize + aObject.size());
char* aPointer = (char*)&myNumber;
for( i = 0; i < anISize; i++, aPointer++ )
*aPointer = theArray[i];
int aCurIndex = anISize + 2*aFSize*myNumber + 2*aBSize;
- QByteArray aObject( aSize - aCurIndex );
+ QByteArray aObject;
+ aObject.resize( aSize - aCurIndex );
for( ; i < aSize; i++ )
aObject[i - aCurIndex] = theArray[i];
AddCoordsToPS( aBuffer, "moveto", aViewerCS, aPSCS, double(xPos), double(yPos) );
aBuffer += "(" + aText + ") show\n";
- hFile.writeBlock( aBuffer.ascii(), aBuffer.length() );
+ hFile.write( aBuffer.toAscii() );
return true;
}
aBuffer = "LB" + aText + "#;";
- hFile.writeBlock( aBuffer.ascii(), aBuffer.length() );
+ hFile.write( aBuffer.toAscii() );
return true;
}
y = double( yPos );
aViewerCS->transform( *aEMFCS, x, y );
- const char* str = aText.ascii();
+ const char* str = aText.toAscii();
int nHeight = 35*14; // height of font
int nWidth = 35*12; // average character width
#include "GLViewer.h"
#include "GLViewer_Object.h"
-#include <qcolor.h>
-#include <qvaluelist.h>
+#include <QColor>
#include <TColStd_SequenceOfInteger.hxx>
-#ifdef WNT
+#ifdef WIN32
#pragma warning( disable:4251 )
#endif
float getMarkerSize() const { return myMarkerSize; }
//! Export numbers of heghlighted/selected markers
- void exportNumbers( QValueList<int>& high, QValueList<int>& unhigh,
- QValueList<int>& sel, QValueList<int>& unsel );
+ void exportNumbers( QList<int>& high, QList<int>& unhigh,
+ QList<int>& sel, QList<int>& unsel );
//! Returns selected numbers
- QValueList<int> getSelectedElements() { return mySelNumbers; }
+ QList<int> getSelectedElements() { return mySelNumbers; }
//! Adds or remove selected number
bool addOrRemoveSelected( int index );
//! Adds selected numbers
GLfloat* myXCoord;
GLfloat* myYCoord;
GLfloat myMarkerSize;
- QValueList<int> myHNumbers;
- QValueList<int> myUHNumbers;
- QValueList<int> mySelNumbers;
- QValueList<int> myCurSelNumbers;
- QValueList<int> myUSelNumbers;
- QValueList<int> myPrevHNumbers;
+ QList<int> myHNumbers;
+ QList<int> myUHNumbers;
+ QList<int> mySelNumbers;
+ QList<int> myCurSelNumbers;
+ QList<int> myUSelNumbers;
+ QList<int> myPrevHNumbers;
TColStd_SequenceOfInteger mySelectedIndexes;
};
GLboolean isHighSelAll() const { return myHighSelAll; }
//! Export numbers of highlighted/selected lines
- void exportNumbers( QValueList<int>& high, QValueList<int>& unhigh,
- QValueList<int>& sel, QValueList<int>& unsel );
+ void exportNumbers( QList<int>& high, QList<int>& unhigh,
+ QList<int>& sel, QList<int>& unsel );
//! Returns numbers of selected lines
- QValueList<int> getSelectedElements() { return mySelNumbers; }
+ QList<int> getSelectedElements() { return mySelNumbers; }
protected:
GLfloat* myXCoord;
GLboolean myIsClosed;
GLboolean myHighSelAll;
- QValueList<int> myHNumbers;
- QValueList<int> myUHNumbers;
- QValueList<int> mySelNumbers;
- QValueList<int> myUSelNumbers;
- QValueList<int> myCurSelNumbers;
- QValueList<int> myPrevHNumbers;
+ QList<int> myHNumbers;
+ QList<int> myUHNumbers;
+ QList<int> mySelNumbers;
+ QList<int> myUSelNumbers;
+ QList<int> myCurSelNumbers;
+ QList<int> myPrevHNumbers;
TColStd_SequenceOfInteger mySelectedIndexes;
GLboolean myHighFlag;
int myHeight;
};
-#ifdef WNT
+#ifdef WIN32
#pragma warning ( default:4251 )
#endif
#include "GLViewer.h"
-#include <qcolor.h>
+#include <QColor>
-#ifdef WNT
+class QFont;
+
+#ifdef WIN32
#pragma warning( disable:4251 )
#endif
bool isGenereted;
};
-#ifdef WNT
+#ifdef WIN32
#pragma warning ( default:4251 )
#endif
#include "GLViewer_Object.h"
#include "GLViewer_Viewer2d.h"
#include "GLViewer_ViewPort2d.h"
+#include "GLViewer_ViewFrame.h"
+
+//QT includes
+#include <QRect>
#include <TColStd_SequenceOfInteger.hxx>
}
else if( myLastPicked->isSelected() && status != SS_LocalChanged )
{
- mySelectedObjects.remove( myLastPicked );
+ mySelectedObjects.removeAll( myLastPicked );
myLastPicked->unselect();
myGLViewer2d->updateAll();
}
if ( myLastPicked->select( myXhigh, myYhigh, myTolerance, GLViewer_Rect(), false, byCircle, Append )
- && mySelectedObjects.findIndex( myLastPicked ) == -1 )
+ && mySelectedObjects.indexOf( myLastPicked ) == -1 )
{
mySelectedObjects.append( myLastPicked );
myGLViewer2d->activateDrawer( myLastPicked, TRUE, TRUE );
isSel = (*it)->isSelected();
}
- if( isSel && mySelectedObjects.findIndex( *it ) == -1 )
+ if( isSel && mySelectedObjects.indexOf( *it ) == -1 )
{
aList.append( *it );
mySelectedObjects.append( *it );
if( myActiveObjects.contains( oldObject ) )
{
- myActiveObjects.remove( oldObject );
+ myActiveObjects.removeAll( oldObject );
myActiveObjects.append( newObject );
return true;
}
if( myInactiveObjects.contains( oldObject ) )
{
- myInactiveObjects.remove( oldObject );
+ myInactiveObjects.removeAll( oldObject );
myInactiveObjects.append( newObject );
return true;
}
if( !object || !mySelectedObjects.contains( object ) )
return;
- mySelectedObjects.remove( object );
+ mySelectedObjects.removeAll( object );
object->unselect();
if( updateViewer )
return;
if( myActiveObjects.contains( theObject ) )
- myActiveObjects.remove( theObject );
+ myActiveObjects.removeAll( theObject );
else if( myInactiveObjects.contains( theObject ) )
- myInactiveObjects.remove( theObject );
+ myInactiveObjects.removeAll( theObject );
else
return;
if( mySelectedObjects.contains( theObject ) )
- mySelectedObjects.remove( theObject );
+ mySelectedObjects.removeAll( theObject );
GLViewer_Group* aGroup = theObject->getGroup();
if( aGroup )
if( !theObject || !myInactiveObjects.contains( theObject ) )
return false;
- myInactiveObjects.remove( theObject );
+ myInactiveObjects.removeAll( theObject );
myActiveObjects.append( theObject );
return true;
}
if( !theObject || !myActiveObjects.contains( theObject ) )
return false;
- myActiveObjects.remove( theObject );
+ myActiveObjects.removeAll( theObject );
myInactiveObjects.append( theObject );
return true;
}
#ifndef GLVIEWER_CONTEXT_H
#define GLVIEWER_CONTEXT_H
-#ifdef WNT
+#ifdef WIN32
#include "windows.h"
#endif
#include "GLViewer_Defs.h"
#include "GLViewer_Object.h"
-#include <qrect.h>
-#include <qobject.h>
-#include <qregion.h>
+class QRect;
#include <Quantity_NameOfColor.hxx>
#include <Quantity_Color.hxx>
class GLViewer_Viewer2d;
-#ifdef WNT
+#ifdef WIN32
#pragma warning( disable:4251 )
#endif
int myTolerance;
};
-#ifdef WNT
+#ifdef WIN32
#pragma warning ( default:4251 )
#endif
#include "GLViewer.h"
-#ifdef WNT
+#ifdef WIN32
#pragma warning( disable:4251 )
#endif
virtual void fromReference( double& x, double& y );
};
-#ifdef WNT
+#ifdef WIN32
#pragma warning ( default:4251 )
#endif
#ifndef GLVIEWER_DEFS_H
#define GLVIEWER_DEFS_H
-#include <qmap.h>
-#include <qvaluelist.h>
+#include <QMap>
+#include <QList>
class GLViewer_Object;
//Selection staus
};
typedef QMap<GLViewer_Object*,int> ObjectMap;
-typedef QValueList<GLViewer_Object*> ObjList;
+typedef QList<GLViewer_Object*> ObjList;
#define SEGMENTS 32
#define PI 3.14159265359
#include "GLViewer_ViewFrame.h"
#include "GLViewer_ViewPort2d.h"
+#include <QApplication>
+#include <QImage>
+#include <QPainter>
+#include <QFile>
+
#ifndef WIN32
#include <GL/glx.h>
#endif
#include <gp_Pnt2d.hxx>
-#include <qimage.h>
-#include <qpainter.h>
-
#define TEXT_GAP 5
// Two texture components for texmapped fonts: luminance and alpha
#define NB_TEX_COMP 2
GLViewer_TexFont::GLViewer_TexFont()
: myMaxRowWidth( 0 ), myFontHeight( 0 )
{
- myQFont = QFont::defaultFont();
+ myQFont = QApplication::font();//QFont::defaultFont();
mySeparator = 2;
myIsResizeable = false;
myMinMagFilter = GL_LINEAR;
aPainter.drawText( myPositions[l], ( row + 1 ) * aRowPixelHeight - aDescent, aLetter );
}
- QImage aImage = aPixmap.convertToImage();
+ QImage aImage = aPixmap.toImage();
//int qqq = 0;
//if (qqq)
int aLettIndex, row;
for ( int i = 0; i < (int)theStr.length(); i++ )
{
- aLetter = theStr.data()[i];
+ aLetter = theStr.data()[i].toLatin1();
aLettIndex = (int)aLetter - FirstSymbolNumber;
row = aLettIndex / TEX_ROW_LEN;
int aWidth = 0;
for ( int i = 0; i < (int)theStr.length(); i ++ )
{
- char aLetter = theStr.data()[i];
+ char aLetter = theStr.data()[i].toLatin1();
int aLettIndex = (int)aLetter - FirstSymbolNumber;
aWidth += myWidths[aLettIndex] + mySeparator;
}
QMap<GLViewer_TexFindId, GLuint>::iterator it = GLViewer_TexFont::BitmapFontCache.begin();
for ( ; it != GLViewer_TexFont::BitmapFontCache.end(); ++it )
{
- if ( it.key().myViewPortId == (int)ctx && it.data() > listBase )
- listBase = it.data();
+ if ( it.key().myViewPortId == (int)ctx && it.value() > listBase )
+ listBase = it.value();
}
listBase += 256;
QMap<GLViewer_TexFindId, GLuint>::iterator it = GLViewer_TexFont::BitmapFontCache.begin();
for ( ; it != GLViewer_TexFont::BitmapFontCache.end(); ++it )
{
- if ( it.key().myViewPortId == size_t(aCont) && it.data() > listBase )
- listBase = it.data();
+ if ( it.key().myViewPortId == size_t(aCont) && it.value() > listBase )
+ listBase = it.value();
}
listBase += 256;
//glXUseXFont( (Font)(theFont->handle()), 0, 256, listBase );
int aFontCont = 0;
QString aFontDef = theFont->toString();
- char** xFontList = XListFonts( aDisp, aFontDef.latin1()/*aFindFont.myFontString.data()*/, 1, &aFontCont );
+ char** xFontList = XListFonts( aDisp, aFontDef.toLatin1()/*aFindFont.myFontString.data()*/, 1, &aFontCont );
if( !theFont->handle() )
{
#ifdef _DEBUG_
- printf( "Can't load font %s. loading default font....\n", aFontDef.latin1()/*aFindFont.myFontString.data()*/ );
+ printf( "Can't load font %s. loading default font....\n", aFontDef.toLatin1().data()/*aFindFont.myFontString.data()*/ );
#endif
QString aFontMask ("-*-*-*-r-*-*-");
aFontMask += aFontDef/*aFindFont.myFontString*/.section( ',', 1, 1 );
printf( "Height of Default font: %s\n", aFontDef/*aFindFont.myFontString*/.section( ',', 1, 1 ).data() );
#endif
aFontMask += "-*-*-*-m-*-*-*";
- xFontList = XListFonts( aDisp, aFontMask.data()/*"-*-*-*-r-*-*-12-*-*-*-m-*-*-*"*/, 1, &aFontCont );
+ xFontList = XListFonts( aDisp, aFontMask.toLatin1().constData()/*"-*-*-*-r-*-*-12-*-*-*-m-*-*-*"*/, 1, &aFontCont );
if( aFontCont == 0 )
{
#ifdef _DEBUG_
QMap<GLViewer_TexFindId,GLViewer_TexIdStored>::Iterator anEndIt= GLViewer_TexFont::TexFontBase.end();
for( ; anIt != anEndIt; anIt++ )
- glDeleteTextures( 1, &(anIt.data().myTexFontId) );
+ glDeleteTextures( 1, &(anIt.value().myTexFontId) );
}
/*!
{
glRasterPos2f( xPos, yPos );
glListBase( displayListBase( theFont ) );
- glCallLists( text.length(), GL_UNSIGNED_BYTE, text.local8Bit().data() );
+ glCallLists( text.length(), GL_UNSIGNED_BYTE, text.toLocal8Bit().data() );
}
}
glLineWidth( lineWidth );
glBegin( GL_LINES );
- QValueList<GLViewer_Pnt>::const_iterator it = pntList.begin();
+ QList<GLViewer_Pnt>::const_iterator it = pntList.begin();
for( ; it != pntList.end(); ++it )
glVertex2f( (*it).x(), (*it).y() );
glEnd();
( GLfloat )color.green() / 255,
( GLfloat )color.blue() / 255 );
glBegin( GL_POLYGON );
- QValueList<GLViewer_Pnt>::const_iterator it = pntList.begin();
+ QList<GLViewer_Pnt>::const_iterator it = pntList.begin();
for( ; it != pntList.end(); ++it )
glVertex2f( (*it).x(), (*it).y() );
glEnd();
#ifndef GLVIEWER_DRAWER_H
#define GLVIEWER_DRAWER_H
-#ifdef WNT
+#ifdef WIN32
#include "windows.h"
#endif
-#include <qcolor.h>
-#include <qobject.h>
-#include <qfile.h>
-#include <qfont.h>
-#include <qgl.h>
+#include <QColor>
+#include <QFont>
+
+class QFile;
#include <GL/gl.h>
class GLViewer_Rect;
class GLViewer_CoordSystem;
-#ifdef WNT
+#ifdef WIN32
#pragma warning( disable:4251 )
#endif
/*!
float myYScale;
//! List of objects
- QValueList<GLViewer_Object*> myObjects;
+ QList<GLViewer_Object*> myObjects;
//! List generated textures
GLuint myTextList;
GLfloat myTextScale;
};
-#ifdef WNT
+#ifdef WIN32
#pragma warning ( default:4251 )
#endif
#include "GLViewer.h"
-#include <qrect.h>
-#include <qvaluelist.h>
-#include <qgl.h>
+#include <QRect>
+#include <QtOpenGL>
#include <math.h>
+//using namespace QGL;
-#ifdef WNT
+#ifdef WIN32
#pragma warning( disable:4251 )
#endif
GLfloat myY;
};
-typedef QValueList<GLViewer_Pnt> GLViewer_PntList;
+typedef QList<GLViewer_Pnt> GLViewer_PntList;
/*! Class GLViewer_Rect
* Substitution of QRect for OpenGL
GLViewer_PntList* myPoints;
};
-#ifdef WNT
+#ifdef WIN32
#pragma warning ( default:4251 )
#endif
#include "GLViewer_Defs.h"
#include <Precision.hxx>
-#include <qglobal.h>
/*!
Default constructor
#ifndef GLVIEWER_GRID_H
#define GLVIEWER_GRID_H
-#ifdef WNT
+#ifdef WIN32
#include "windows.h"
#endif
#include <GL/gl.h>
#include <GL/glu.h>
-#ifdef WNT
+#ifdef WIN32
#pragma warning( disable:4251 )
#endif
GLboolean myIsUpdate;
};
-#ifdef WNT
+#ifdef WIN32
#pragma warning ( default:4251 )
#endif
#include <list>
#include "GLViewer.h"
-#ifdef WNT
+#ifdef WIN32
#pragma warning( disable:4251 )
#endif
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// Author : OPEN CASCADE
+//
+
+//#include <GLViewerAfx.h>
+#include "GLViewer_MimeData.h"
+#include "GLViewer_BaseObjects.h"
+
+//#include <cmath>
+//using namespace std;
+
+/*!
+ Destructor
+*/
+GLViewer_MimeData::~GLViewer_MimeData()
+{
+}
+
+/*!
+ Translate objects to byte array
+ \param theObjects - list of objects
+*/
+bool GLViewer_MimeData::setObjects( QList<GLViewer_Object*> theObjects )
+{
+ if( !theObjects.empty() )
+ {
+ QStringList aObjectsType;
+ QList<QByteArray> aObjects;
+ QList<GLViewer_Object*>::const_iterator anIt = theObjects.begin();
+ QList<GLViewer_Object*>::const_iterator anEndIt = theObjects.end();
+
+ int aObjByteSize = 0;
+ for( ; anIt != anEndIt; anIt++ )
+ {
+ aObjects.append( (*anIt)->getByteCopy() );
+ aObjByteSize += aObjects.last().size();
+ aObjectsType.append( (*anIt)->getObjectType() );
+ }
+
+ int anISize = sizeof( int );
+ QString aTypes = aObjectsType.join("");
+ int aStrByteSize = aTypes.length();
+ int aObjNum = aObjects.count();
+
+ myByteArray.resize( anISize * (1 + 2*aObjNum) + aStrByteSize + aObjByteSize );
+
+ int anIndex = 0, j = 0;
+ char* aPointer = (char*)&aObjNum;
+ for( anIndex = 0; anIndex < anISize; anIndex++, aPointer++ )
+ myByteArray[anIndex] = *aPointer;
+
+ QStringList::const_iterator aStrIt = aObjectsType.begin();
+ QStringList::const_iterator aEndStrIt = aObjectsType.end();
+ for( j = 1; aStrIt != aEndStrIt; aStrIt++, j++ )
+ {
+ int aStrLen = (*aStrIt).length();
+ aPointer = (char*)&aStrLen;
+ for( ; anIndex < anISize*( 1 + j ); anIndex++, aPointer++ )
+ myByteArray[anIndex] = *aPointer;
+ }
+
+ int aCurIndex = anIndex;
+ const char* aStr = aTypes.toLatin1().constData();
+
+ for( j = 0 ; anIndex < aCurIndex + aStrByteSize; aPointer++, anIndex++, j++ )
+ myByteArray[anIndex] = aStr[j];
+
+ aCurIndex = anIndex;
+ QList<QByteArray>::iterator anObjIt = aObjects.begin();
+ QList<QByteArray>::iterator anEndObjIt = aObjects.end();
+ for( j = 1; anObjIt != anEndObjIt; anObjIt++, j++ )
+ {
+ int aObjLen = (int)((*anObjIt).size());
+ aPointer = (char*)&aObjLen;
+ for( ; anIndex < aCurIndex + anISize*j; anIndex++, aPointer++ )
+ myByteArray[anIndex] = *aPointer;
+ }
+
+ aCurIndex = anIndex;
+ anObjIt = aObjects.begin();
+
+ for( ; anObjIt != anEndObjIt; anObjIt++ )
+ {
+ int aObjLen = (int)((*anObjIt).size());
+ for( j = 0 ; anIndex < aCurIndex + aObjLen; anIndex++, aPointer++, j++ )
+ myByteArray[anIndex] = (*anObjIt)[j];
+ aCurIndex = anIndex;
+ }
+
+ return true;
+ }
+
+ return false;
+}
+
+/*!
+ Creates object by it's representation (byte array)
+ \param theArray - byte array
+ \param theType - type of object
+*/
+GLViewer_Object* GLViewer_MimeData::getObject( QByteArray theArray, QString theType )
+{
+ if( !theArray.isEmpty() )
+ {
+ if( theType == "GLViewer_MarkerSet" )
+ {
+ GLViewer_MarkerSet* aObject = new GLViewer_MarkerSet( 0, (float)0.0, 0 );
+ if( aObject->initializeFromByteCopy( theArray ) )
+ return aObject;
+ }
+ else if ( theType == "GLViewer_Polyline" )
+ {
+ GLViewer_Polyline* aObject = new GLViewer_Polyline( 0, (float)0.0, 0 );
+ if( aObject->initializeFromByteCopy( theArray ) )
+ return aObject;
+ }
+ else if( theType == "GLViewer_TextObject" )
+ {
+ GLViewer_TextObject* aObject = new GLViewer_TextObject( 0, 0, 0, QColor(255,255,255), 0 );
+ if( aObject->initializeFromByteCopy( theArray ) )
+ return aObject;
+ }
+ }
+
+ return NULL;
+}
+
+/*!
+ Creates list of objects by its representation (byte array)
+ \param theArray - byte array
+ \param theType - type of object
+*/
+QList<GLViewer_Object*> GLViewer_MimeData::getObjects( QByteArray theArray, QString theType )
+{
+ if( !theArray.isEmpty() )
+ {
+ int anISize = sizeof( int );
+ if( theType == "GLViewer_Objects" )
+ {
+ QStringList aTypeList;
+ QList<QByteArray> aObjects;
+ QList<GLViewer_Object*> aObjectList;
+
+ QList<int> aTypeSizeList;
+ QList<int> aObjSizeList;
+ int aObjNum = 0;
+ char* aPointer = (char*)&aObjNum;
+
+ int anIndex = 0, j = 0;
+ for( anIndex = 0; anIndex < anISize; anIndex++, aPointer++ )
+ *aPointer = theArray[anIndex];
+
+ for( j = 0; j < aObjNum; j++ )
+ {
+ int aTempVal = 0;
+ aPointer = (char*)&aTempVal;
+ for( ; anIndex < anISize*(j+2); anIndex++, aPointer++ )
+ *aPointer = theArray[anIndex];
+ aTypeSizeList.append( aTempVal );
+ }
+
+ int aCurIndex = anIndex;
+ for( j = 0; j < aObjNum; j++ )
+ {
+ QString aTempStr;
+ for( ; anIndex < aCurIndex + aTypeSizeList[j]; anIndex++ )
+ {
+ char aLetter = theArray[anIndex];
+ aTempStr.append( aLetter );
+ }
+ aTypeList.append( aTempStr );
+ aCurIndex = anIndex;
+ }
+
+ for( j = 0; j < aObjNum; j++ )
+ {
+ int aTempVal = 0;
+ aPointer = (char*)&aTempVal;
+ for( ; anIndex < aCurIndex + anISize*(j+1); anIndex++, aPointer++ )
+ *aPointer = theArray[anIndex];
+ aObjSizeList.append( aTempVal );
+ }
+
+ aCurIndex = anIndex;
+ for( j = 0; j < aObjNum; j++ )
+ {
+ QByteArray aTempArray;
+ aTempArray.resize(aObjSizeList[j]);
+ for( ; anIndex < aCurIndex + aObjSizeList[j]; anIndex++ )
+ aTempArray[anIndex-aCurIndex] = theArray[anIndex];
+ aObjects.append( aTempArray );
+ aCurIndex = anIndex;
+ }
+
+ for( j = 0; j < aObjNum; j++ )
+ aObjectList.append( getObject( aObjects[j], aTypeList[j] ) );
+
+ return aObjectList;
+ }
+ }
+
+ return QList<GLViewer_Object*>();
+}
+
+/*!
+ \return format by index
+ \param theIndex - index
+*/
+const char* GLViewer_MimeData::format( int theIndex ) const
+{
+ switch( theIndex )
+ {
+ case 0: return "GLViewer_Objects";
+ //case 1: return "GLViewer_MarkerSet";
+ //case 2: return "GLViewer_Polyline";
+ //case 3: return "GLViewer_TextObject";
+ default: return 0;
+ }
+
+}
+
+/*!
+ \return internal byte array
+*/
+QByteArray GLViewer_MimeData::encodedData( const char* theObjectType ) const
+{
+ if( theObjectType == "GLViewer_Objects" )
+ return myByteArray;
+
+ return QByteArray();
+}
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// Author : OPEN CASCADE
+//
+
+// File: GLViewer_MimeData.h
+// Created: November, 2004
+
+#ifndef GLVIEWER_MIMEDATA_H
+#define GLVIEWER_MIMEDATA_H
+
+#ifdef WIN32
+#include <windows.h>
+#endif
+
+#include "GLViewer.h"
+
+#include <QMimeData>
+
+#ifdef WIN32
+#pragma warning( disable:4251 )
+#endif
+
+class GLViewer_Object;
+
+/*!
+ \class GLViewer_MimeData
+ Needs for a work with QClipboard
+*/
+class GLVIEWER_API GLViewer_MimeData: public QMimeData
+{
+public:
+ GLViewer_MimeData():QMimeData(){};
+ ~GLViewer_MimeData();
+
+ //! Translate objects to byte array
+ bool setObjects( QList<GLViewer_Object*> );
+ //! Gets objects from byte array
+ /*If you want to use new class, following two method must be redefined*/
+ static QList<GLViewer_Object*> getObjects( QByteArray, QString theType);
+ //! Get object from byte array
+ /*If you want to use new class, following two method must be redefined*/
+ static GLViewer_Object* getObject( QByteArray, QString theType);
+
+ const char* format( int theIndex = 0 ) const;
+ QByteArray encodedData( const char* ) const;
+
+private:
+ QByteArray myByteArray;
+};
+
+#ifdef WIN32
+#pragma warning ( default:4251 )
+#endif
+
+#endif
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-// Author : OPEN CASCADE
-//
-
-//#include <GLViewerAfx.h>
-#include "GLViewer_MimeSource.h"
-#include "GLViewer_BaseObjects.h"
-
-//#include <cmath>
-//using namespace std;
-
-/*!
- Destructor
-*/
-GLViewer_MimeSource::~GLViewer_MimeSource()
-{
-}
-
-/*!
- Translate objects to byte array
- \param theObjects - list of objects
-*/
-bool GLViewer_MimeSource::setObjects( QValueList<GLViewer_Object*> theObjects )
-{
- if( !theObjects.empty() )
- {
- QStringList aObjectsType;
- QValueList<QByteArray> aObjects;
- QValueList<GLViewer_Object*>::const_iterator anIt = theObjects.begin();
- QValueList<GLViewer_Object*>::const_iterator anEndIt = theObjects.end();
-
- int aObjByteSize = 0;
- for( ; anIt != anEndIt; anIt++ )
- {
- aObjects.append( (*anIt)->getByteCopy() );
- aObjByteSize += aObjects.last().size();
- aObjectsType.append( (*anIt)->getObjectType() );
- }
-
- int anISize = sizeof( int );
- QString aTypes = aObjectsType.join("");
- int aStrByteSize = aTypes.length();
- int aObjNum = aObjects.count();
-
- myByteArray = QByteArray( anISize * (1 + 2*aObjNum) + aStrByteSize + aObjByteSize );
-
- int anIndex = 0, j = 0;
- char* aPointer = (char*)&aObjNum;
- for( anIndex = 0; anIndex < anISize; anIndex++, aPointer++ )
- myByteArray[anIndex] = *aPointer;
-
- QStringList::const_iterator aStrIt = aObjectsType.begin();
- QStringList::const_iterator aEndStrIt = aObjectsType.end();
- for( j = 1; aStrIt != aEndStrIt; aStrIt++, j++ )
- {
- int aStrLen = (*aStrIt).length();
- aPointer = (char*)&aStrLen;
- for( ; anIndex < anISize*( 1 + j ); anIndex++, aPointer++ )
- myByteArray[anIndex] = *aPointer;
- }
-
- int aCurIndex = anIndex;
- const char* aStr = aTypes.data();
-
- for( j = 0 ; anIndex < aCurIndex + aStrByteSize; aPointer++, anIndex++, j++ )
- myByteArray[anIndex] = aStr[j];
-
- aCurIndex = anIndex;
- QValueList<QByteArray>::iterator anObjIt = aObjects.begin();
- QValueList<QByteArray>::iterator anEndObjIt = aObjects.end();
- for( j = 1; anObjIt != anEndObjIt; anObjIt++, j++ )
- {
- int aObjLen = (int)((*anObjIt).size());
- aPointer = (char*)&aObjLen;
- for( ; anIndex < aCurIndex + anISize*j; anIndex++, aPointer++ )
- myByteArray[anIndex] = *aPointer;
- }
-
- aCurIndex = anIndex;
- anObjIt = aObjects.begin();
-
- for( ; anObjIt != anEndObjIt; anObjIt++ )
- {
- int aObjLen = (int)((*anObjIt).size());
- for( j = 0 ; anIndex < aCurIndex + aObjLen; anIndex++, aPointer++, j++ )
- myByteArray[anIndex] = (*anObjIt)[j];
- aCurIndex = anIndex;
- }
-
- return true;
- }
-
- return false;
-}
-
-/*!
- Creates object by it's representation (byte array)
- \param theArray - byte array
- \param theType - type of object
-*/
-GLViewer_Object* GLViewer_MimeSource::getObject( QByteArray theArray, QString theType )
-{
- if( !theArray.isEmpty() )
- {
- if( theType == "GLViewer_MarkerSet" )
- {
- GLViewer_MarkerSet* aObject = new GLViewer_MarkerSet( 0, (float)0.0, 0 );
- if( aObject->initializeFromByteCopy( theArray ) )
- return aObject;
- }
- else if ( theType == "GLViewer_Polyline" )
- {
- GLViewer_Polyline* aObject = new GLViewer_Polyline( 0, (float)0.0, 0 );
- if( aObject->initializeFromByteCopy( theArray ) )
- return aObject;
- }
- else if( theType == "GLViewer_TextObject" )
- {
- GLViewer_TextObject* aObject = new GLViewer_TextObject( 0, 0, 0, QColor(255,255,255), 0 );
- if( aObject->initializeFromByteCopy( theArray ) )
- return aObject;
- }
- }
-
- return NULL;
-}
-
-/*!
- Creates list of objects by its representation (byte array)
- \param theArray - byte array
- \param theType - type of object
-*/
-QValueList<GLViewer_Object*> GLViewer_MimeSource::getObjects( QByteArray theArray, QString theType )
-{
- if( !theArray.isEmpty() )
- {
- int anISize = sizeof( int );
- if( theType == "GLViewer_Objects" )
- {
- QStringList aTypeList;
- QValueList<QByteArray> aObjects;
- QValueList<GLViewer_Object*> aObjectList;
-
- QValueList<int> aTypeSizeList;
- QValueList<int> aObjSizeList;
- int aObjNum = 0;
- char* aPointer = (char*)&aObjNum;
-
- int anIndex = 0, j = 0;
- for( anIndex = 0; anIndex < anISize; anIndex++, aPointer++ )
- *aPointer = theArray[anIndex];
-
- for( j = 0; j < aObjNum; j++ )
- {
- int aTempVal = 0;
- aPointer = (char*)&aTempVal;
- for( ; anIndex < anISize*(j+2); anIndex++, aPointer++ )
- *aPointer = theArray[anIndex];
- aTypeSizeList.append( aTempVal );
- }
-
- int aCurIndex = anIndex;
- for( j = 0; j < aObjNum; j++ )
- {
- QString aTempStr;
- for( ; anIndex < aCurIndex + aTypeSizeList[j]; anIndex++ )
- {
- char aLetter = theArray[anIndex];
- aTempStr.append( aLetter );
- }
- aTypeList.append( aTempStr );
- aCurIndex = anIndex;
- }
-
- for( j = 0; j < aObjNum; j++ )
- {
- int aTempVal = 0;
- aPointer = (char*)&aTempVal;
- for( ; anIndex < aCurIndex + anISize*(j+1); anIndex++, aPointer++ )
- *aPointer = theArray[anIndex];
- aObjSizeList.append( aTempVal );
- }
-
- aCurIndex = anIndex;
- for( j = 0; j < aObjNum; j++ )
- {
- QByteArray aTempArray(aObjSizeList[j]);
- for( ; anIndex < aCurIndex + aObjSizeList[j]; anIndex++ )
- aTempArray[anIndex-aCurIndex] = theArray[anIndex];
- aObjects.append( aTempArray );
- aCurIndex = anIndex;
- }
-
- for( j = 0; j < aObjNum; j++ )
- aObjectList.append( getObject( aObjects[j], aTypeList[j] ) );
-
- return aObjectList;
- }
- }
-
- return QValueList<GLViewer_Object*>();
-}
-
-/*!
- \return format by index
- \param theIndex - index
-*/
-const char* GLViewer_MimeSource::format( int theIndex ) const
-{
- switch( theIndex )
- {
- case 0: return "GLViewer_Objects";
- //case 1: return "GLViewer_MarkerSet";
- //case 2: return "GLViewer_Polyline";
- //case 3: return "GLViewer_TextObject";
- default: return 0;
- }
-
-}
-
-/*!
- \return internal byte array
-*/
-QByteArray GLViewer_MimeSource::encodedData( const char* theObjectType ) const
-{
- if( theObjectType == "GLViewer_Objects" )
- return myByteArray;
-
- return QByteArray();
-}
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-// Author : OPEN CASCADE
-//
-
-// File: GLViewer_MimeSource.h
-// Created: November, 2004
-
-#ifndef GLVIEWER_MIMESOURCE_H
-#define GLVIEWER_MIMESOURCE_H
-
-#ifdef WNT
-#include <windows.h>
-#endif
-
-#include "GLViewer.h"
-
-#include <qmime.h>
-#include <qvaluelist.h>
-
-#ifdef WNT
-#pragma warning( disable:4251 )
-#endif
-
-class GLViewer_Object;
-
-/*!
- \class GLViewer_MimeSource
- Needs for a work with QClipboard
-*/
-class GLVIEWER_API GLViewer_MimeSource: public QMimeSource
-{
-public:
- GLViewer_MimeSource():QMimeSource(){};
- ~GLViewer_MimeSource();
-
- //! Translate objects to byte array
- bool setObjects( QValueList<GLViewer_Object*> );
- //! Gets objects from byte array
- /*If you want to use new class, following two method must be redefined*/
- static QValueList<GLViewer_Object*> getObjects( QByteArray, QString theType);
- //! Get object from byte array
- /*If you want to use new class, following two method must be redefined*/
- static GLViewer_Object* getObject( QByteArray, QString theType);
-
- // Redefined methods
- virtual const char* format( int theIndex = 0 ) const;
- virtual QByteArray encodedData( const char* ) const;
-
-private:
- QByteArray myByteArray;
-};
-
-#ifdef WNT
-#pragma warning ( default:4251 )
-#endif
-
-#endif
#include "GLViewer_Object.h"
#include "GLViewer_Drawer.h"
#include "GLViewer_AspectLine.h"
-#include "GLViewer_Geom.h"
#include "GLViewer_Text.h"
#include "GLViewer_Group.h"
+#include <SUIT_DataOwner.h>
+
//#include <cmath>
//using namespace std;
int i = 0;
int anISize = sizeof( int );
- const char* aTypeStr = myType.data();
- const char* aToolTipStr = myToolTipText.data();
+ const char* aTypeStr = myType.toLatin1().constData();
+ const char* aToolTipStr = myToolTipText.toLatin1().constData();
int aTypeLength = myType.length();
int aToolTipLength = myToolTipText.length();
int sizeOf8Float = sizeof( aRectData );
- QByteArray aResult( 2*anISize + sizeOf8Float +
- aTypeLength + aToolTipLength +
- aGLText.size() + aAspect.size() );
+ QByteArray aResult;
+ aResult.resize( 2*anISize + sizeOf8Float +
+ aTypeLength + aToolTipLength +
+ aGLText.size() + aAspect.size() );
// puts 8 float values into the byte array
char* aPointer = (char*)&aRectData;
for( i = 0; i < sizeOf8Float; i++, aPointer++ )
GLViewer_AspectLine* aAspectLine = new GLViewer_AspectLine();
int aGLAspLineSize = (aAspectLine->getByteCopy()).size();
- QByteArray aGLTextArray, aAspect( aGLAspLineSize );
+ QByteArray aGLTextArray, aAspect;
+ aGLTextArray.resize( aGLAspLineSize );
+ aAspect.resize( aGLAspLineSize );
if( aSize < 2*anISize + 8*aFSize + aGLTextMinSize + aGLAspLineSize )
return false;
#ifndef GLVIEWER_OBJECT_H
#define GLVIEWER_OBJECT_H
-#ifdef WNT
+#ifdef WIN32
#include <windows.h>
#endif
#include "GLViewer.h"
-#include "GLViewer_Defs.h"
#include "GLViewer_Geom.h"
-#include <SUIT_DataOwner.h>
-
#include <GL/gl.h>
-#include <qfile.h>
-#include <qstring.h>
-#include <qrect.h>
+#include <QString>
+
+class QFile;
-#ifdef WNT
+#ifdef WIN32
#pragma warning( disable:4251 )
#endif
class GLViewer_Text;
//class GLViewer_Owner;
+class SUIT_DataOwner;
+
/*!
* Class GLViewer_Object
* Base Object for all GLViewer objects
GLViewer_Group* myGroup;
};
-#ifdef WNT
+#ifdef WIN32
#pragma warning ( default:4251 )
#endif
#include "GLViewer_Viewer.h"
-int GLViewer_Selector::apppendKey = Qt::ShiftButton;
+int GLViewer_Selector::apppendKey = Qt::ShiftModifier;
/*!
Constructor
#include "GLViewer.h"
#include "GLViewer_Defs.h"
-#include <qsize.h>
-#include <qobject.h>
+#include <QSize>
+#include <QObject>
+
+class QRect;
#include <Quantity_NameOfColor.hxx>
#include "GLViewer_Selector2d.h"
#include "GLViewer_Viewer2d.h"
#include "GLViewer_Context.h"
-#include "GLViewer_ViewPort2d.h"
+#include "GLViewer_ViewPort.h"
+#include "GLViewer_ViewFrame.h"
/*!
Constructor
#ifndef GLVIEWER_SELECTOR2D_H
#define GLVIEWER_SELECTOR2D_H
-#ifdef WNT
+#ifdef WIN32
#include "windows.h"
#endif
//#include <GLViewerAfx.h>
#include "GLViewer_Text.h"
+#include <QApplication>
+#include <QFontMetrics>
+
/*!
Constructor
*/
myXPos = xPos;
myYPos = yPos;
myColor = color;
- myQFont = QFont::defaultFont();
+ myQFont = QApplication::font();//QFont::defaultFont();
mySeparator = 2;
myDTF = DTF_BITMAP;
}
int aR = myColor.red();
int aG = myColor.green();
int aB = myColor.blue();
- const char* aStr = myText.data();
+ const char* aStr = myText.toLatin1().constData();
int anISize = sizeof( int );
- QByteArray aResult( aSize );
+ QByteArray aResult;
+ aResult.resize( aSize );
char* aPointer = (char*)&myXPos;
for( i = 0; i < anISize; i++, aPointer++ )
for( ; i < 7*anISize + aTextSize; i++, aPointer++ )
aResult[i] = *aPointer;
- const char* aFontStr = myQFont.toString().data();
+ const char* aFontStr = myQFont.toString().toLatin1().constData();
int aFontSize = myQFont.toString().length();
for( i = 0; i < aFontSize; i++ )
#ifndef GLVIEWER_TEXT_H
#define GLVIEWER_TEXT_H
-#ifdef WNT
+#ifdef WIN32
#include <windows.h>
#endif
#include <GL/gl.h>
-#include <qfont.h>
-#include <qstring.h>
-#include <qcolor.h>
-#include <qfontmetrics.h>
+#include <QFont>
+#include <QString>
+#include <QColor>
-#ifdef WNT
+#ifdef WIN32
#pragma warning( disable:4251 )
#endif
DisplayTextFormat myDTF;
};
-#ifdef WNT
+#ifdef WIN32
#pragma warning ( default:4251 )
#endif
#include "GLViewer_ToolTip.h"
#include "GLViewer_Viewer2d.h"
#include "GLViewer_ViewPort2d.h"
+#include "GLViewer_ViewFrame.h"
-#include <qlabel.h>
-#include <qtimer.h>
-#include <qbitmap.h>
-#include <qapplication.h>
-#include <qtooltip.h>
+#include <QLabel>
+#include <QTimer>
+#include <QBitmap>
+#include <QApplication>
+#include <QToolTip>
+#include <QMouseEvent>
/*!
constructor
{
mypViewPort = theParent;
//mypLabel = NULL;
- mypLabel = new QLabel( "Test", NULL, "ObjectTipText",
- WStyle_StaysOnTop | WStyle_Customize | WStyle_NoBorder | WStyle_Tool | WX11BypassWM );
- mypLabel->setMargin( 1 );
- mypLabel->setAutoMask( FALSE );
+ mypLabel = new QLabel( "Test", NULL,
+ Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::Tool | Qt::X11BypassWindowManagerHint );
+ mypLabel->setObjectName("ObjectTipText");
+ mypLabel->setMargin( 1 );
+ //mypLabel->setAutoMask( FALSE );
mypLabel->setFrameStyle( QFrame::Plain | QFrame::Box );
mypLabel->setLineWidth( 1 );
- mypLabel->setAlignment( AlignAuto | AlignTop );
+ mypLabel->setAlignment( Qt::AlignAbsolute | Qt::AlignTop );
mypLabel->setIndent( 0 );
- mypLabel->polish();
+ mypLabel->ensurePolished();
//mypLabel->setPalette( QToolTip::palette() );
//#include <qtooltip.h>
//#include <QtxToolTip.h>
-#include <qobject.h>
+#include <QObject>
+#include <QPoint>
#define TIP_TIME 1000
class GLViewer_ViewPort2d;
class QLabel;
+class QTimer;
/*!
\class GLViewer_ObjectTip
ToolTip of GLViewer_Objects
#ifndef GLVIEWER_TOOLS_H
#define GLVIEWER_TOOLS_H
-#ifdef WNT
+#ifdef WIN32
#include "windows.h"
#endif
#include "GLViewer.h"
-#include "GLViewer_Defs.h"
-
-class GLViewer_LineField;
/*!
\class GLViewer_Tools
//#include <GLViewerAfx.h>
#include "GLViewer_ViewFrame.h"
#include "GLViewer_Viewer.h"
-#include "GLViewer_Viewer2d.h"
#include "GLViewer_ViewPort2d.h"
#include <SUIT_Desktop.h>
#include <SUIT_ResourceMgr.h>
#include <SUIT_MessageBox.h>
-#include <qcolor.h>
-#include <qfiledialog.h>
-#include <qimage.h>
-#include <qlayout.h>
-#include <qstring.h>
+#include <QColor>
+#include <QFileDialog>
+#include <QImage>
+#include <QHBoxLayout>
+#include <QString>
+#include <QFrame>
+#include <QToolBar>
+#include <QMouseEvent>
+#include <QKeyEvent>
+#include <QWheelEvent>
+
+#ifdef WIN32
+#include <Standard_Integer.hxx>
+#include <iostream>
+using namespace std;
+#endif
/*!
Constructor
QFrame* client = new QFrame( this );
setCentralWidget( client );
- QBoxLayout* layout = new QHBoxLayout( client, 1, 1 );
- layout->setAutoAdd( true );
+ QBoxLayout* layout = new QHBoxLayout( client );
+ layout->setMargin(1);
+ layout->setSpacing(1);
GLViewer_ViewPort2d* vp = new GLViewer_ViewPort2d( client, this );
//vp->turnGrid( true );
//vp->enablePopup( false );
setViewPort( vp );
setBackgroundColor( Qt::white );
+ layout->addWidget( vp );
myToolBar = new QToolBar(this);
- myToolBar->setCloseMode(QDockWindow::Undocked);
- myToolBar->setLabel(tr("LBL_TOOLBAR_LABEL"));
+ //myToolBar->setCloseMode(QDockWindow::Undocked);
+ myToolBar->setWindowTitle(tr("LBL_TOOLBAR_LABEL"));
createActions();
createToolBar();
}
{
if (!myActionsMap.isEmpty()) return;
SUIT_ResourceMgr* aResMgr = SUIT_Session::session()->resourceMgr();
- QAction* aAction;
+ QtxAction* aAction;
// Dump view
- aAction = new QAction(tr("MNU_DUMP_VIEW"), aResMgr->loadPixmap( "GLViewer", tr( "ICON_GL_DUMP" ) ),
- tr( "MNU_DUMP_VIEW" ), 0, this);
+ aAction = new QtxAction(tr("MNU_DUMP_VIEW"), aResMgr->loadPixmap( "GLViewer", tr( "ICON_GL_DUMP" ) ),
+ tr( "MNU_DUMP_VIEW" ), 0, this);
aAction->setStatusTip(tr("DSC_DUMP_VIEW"));
connect(aAction, SIGNAL(activated()), this, SLOT(onViewDump()));
myActionsMap[ DumpId ] = aAction;
// FitAll
- aAction = new QAction(tr("MNU_FITALL"), aResMgr->loadPixmap( "GLViewer", tr( "ICON_GL_FITALL" ) ),
- tr( "MNU_FITALL" ), 0, this);
+ aAction = new QtxAction(tr("MNU_FITALL"), aResMgr->loadPixmap( "GLViewer", tr( "ICON_GL_FITALL" ) ),
+ tr( "MNU_FITALL" ), 0, this);
aAction->setStatusTip(tr("DSC_FITALL"));
connect(aAction, SIGNAL(activated()), this, SLOT(onViewFitAll()));
myActionsMap[ FitAllId ] = aAction;
// FitRect
- aAction = new QAction(tr("MNU_FITRECT"), aResMgr->loadPixmap( "GLViewer", tr( "ICON_GL_FITAREA" ) ),
- tr( "MNU_FITRECT" ), 0, this);
+ aAction = new QtxAction(tr("MNU_FITRECT"), aResMgr->loadPixmap( "GLViewer", tr( "ICON_GL_FITAREA" ) ),
+ tr( "MNU_FITRECT" ), 0, this);
aAction->setStatusTip(tr("DSC_FITRECT"));
connect(aAction, SIGNAL(activated()), this, SLOT(onViewFitArea()));
myActionsMap[ FitRectId ] = aAction;
// FitSelect
- aAction = new QAction(tr("MNU_FITSELECT"), aResMgr->loadPixmap( "GLViewer", tr( "ICON_GL_FITSELECT" ) ),
- tr( "MNU_FITSELECT" ), 0, this);
+ aAction = new QtxAction(tr("MNU_FITSELECT"), aResMgr->loadPixmap( "GLViewer", tr( "ICON_GL_FITSELECT" ) ),
+ tr( "MNU_FITSELECT" ), 0, this);
aAction->setStatusTip(tr("DSC_FITSELECT"));
connect(aAction, SIGNAL(activated()), this, SLOT(onViewFitSelect()));
myActionsMap[ FitSelectId ] = aAction;
// Zoom
- aAction = new QAction(tr("MNU_ZOOM_VIEW"), aResMgr->loadPixmap( "GLViewer", tr( "ICON_GL_ZOOM" ) ),
- tr( "MNU_ZOOM_VIEW" ), 0, this);
+ aAction = new QtxAction(tr("MNU_ZOOM_VIEW"), aResMgr->loadPixmap( "GLViewer", tr( "ICON_GL_ZOOM" ) ),
+ tr( "MNU_ZOOM_VIEW" ), 0, this);
aAction->setStatusTip(tr("DSC_ZOOM_VIEW"));
connect(aAction, SIGNAL(activated()), this, SLOT(onViewZoom()));
myActionsMap[ ZoomId ] = aAction;
// Panning
- aAction = new QAction(tr("MNU_PAN_VIEW"), aResMgr->loadPixmap( "GLViewer", tr( "ICON_GL_PAN" ) ),
- tr( "MNU_PAN_VIEW" ), 0, this);
+ aAction = new QtxAction(tr("MNU_PAN_VIEW"), aResMgr->loadPixmap( "GLViewer", tr( "ICON_GL_PAN" ) ),
+ tr( "MNU_PAN_VIEW" ), 0, this);
aAction->setStatusTip(tr("DSC_PAN_VIEW"));
connect(aAction, SIGNAL(activated()), this, SLOT(onViewPan()));
myActionsMap[ PanId ] = aAction;
// Global Panning
- aAction = new QAction(tr("MNU_GLOBALPAN_VIEW"), aResMgr->loadPixmap( "GLViewer", tr( "ICON_GL_GLOBALPAN" ) ),
- tr( "MNU_GLOBALPAN_VIEW" ), 0, this);
+ aAction = new QtxAction(tr("MNU_GLOBALPAN_VIEW"), aResMgr->loadPixmap( "GLViewer", tr( "ICON_GL_GLOBALPAN" ) ),
+ tr( "MNU_GLOBALPAN_VIEW" ), 0, this);
aAction->setStatusTip(tr("DSC_GLOBALPAN_VIEW"));
connect(aAction, SIGNAL(activated()), this, SLOT(onViewGlobalPan()));
myActionsMap[ GlobalPanId ] = aAction;
- aAction = new QAction(tr("MNU_RESET_VIEW"), aResMgr->loadPixmap( "GLViewer", tr( "ICON_GL_RESET" ) ),
- tr( "MNU_RESET_VIEW" ), 0, this);
+ aAction = new QtxAction(tr("MNU_RESET_VIEW"), aResMgr->loadPixmap( "GLViewer", tr( "ICON_GL_RESET" ) ),
+ tr( "MNU_RESET_VIEW" ), 0, this);
aAction->setStatusTip(tr("DSC_RESET_VIEW"));
connect(aAction, SIGNAL(activated()), this, SLOT(onViewReset()));
myActionsMap[ ResetId ] = aAction;
{
if ( myVP )
return myVP->backgroundColor();
- return QMainWindow::backgroundColor();
+ return palette().color( backgroundRole() );
}
/*!
imageBits = new unsigned char[imageSize];
-#ifdef WNT
+#ifdef WIN32
int num;
HBITMAP hBmp;
#endif
unsigned int* aPix = NULL;
- QImage anImage( width, height, 32 );
+ QImage anImage( width, height, QImage::Format_RGB32 );
for( int i = 0; i < height; i++ )
{
memset( anImage.scanLine( i ), 0, sizeof(unsigned int)*width );
QString aFilter( "*.bmp\n*.png" );
- QFileDialog aFileDlg( QDir::current().absPath(), aFilter, this );
- aFileDlg.setCaption( tr( "DUMP_VIEW_SAVE_FILE_DLG_CAPTION" ) );
- aFileDlg.setMode( QFileDialog::AnyFile );
+ QFileDialog aFileDlg( this, tr( "DUMP_VIEW_SAVE_FILE_DLG_CAPTION" ), QDir::current().absolutePath(), aFilter );
+ aFileDlg.setFileMode( QFileDialog::AnyFile );
if( !aFileDlg.exec() )
return;
- QString aFileName = aFileDlg.selectedFile();
+ QStringList files = aFileDlg.selectedFiles();
+ QString aFileName;
+ if ( !files.isEmpty() ) aFileName = files[0];
+
QString aFileExt = aFileDlg.selectedFilter();
if( aFileName.isEmpty() )
{
- SUIT_MessageBox::error1( this,
- tr( "DUMP_VIEW_ERROR_DLG_CAPTION" ),
- tr( "DUMP_VIEW_ERROR_DLG_TEXT" ),
- tr( "BUT_OK" ) );
+ SUIT_MessageBox::critical( this,
+ tr( "DUMP_VIEW_ERROR_DLG_CAPTION" ),
+ tr( "DUMP_VIEW_ERROR_DLG_TEXT" ) );
}
QString aSaveOp = "BMP";
- QString aTypedFileExt = QFileInfo( aFileName ).extension( false ).lower();
+ QString aTypedFileExt = QFileInfo( aFileName ).suffix().toLower();
if( aFileExt == "*.bmp" )
{
aFileName += ".png";
aSaveOp = "PNG";
-//#ifdef WNT
+//#ifdef WIN32
// if( !anImage.save( aFileName, aSaveOp ) )
//#else
- if( !aWidget->grabFrameBuffer().save( aFileName, aSaveOp ) )
+ if( !aWidget->grabFrameBuffer().save( aFileName, aSaveOp.toLatin1().constData() ) )
//#endif
{
- SUIT_MessageBox::error1( this,
- tr( "DUMP_VIEW_ERROR_DLG_CAPTION" ),
- tr( "DUMP_VIEW_ERROR_DLG_TEXT" ),
- tr( "BUT_OK" ) );
+ SUIT_MessageBox::critical( this,
+ tr( "DUMP_VIEW_ERROR_DLG_CAPTION" ),
+ tr( "DUMP_VIEW_ERROR_DLG_TEXT" ) );
}
}
*/
void GLViewer_ViewFrame::setVisualParameters( const QString& parameters )
{
- QStringList paramsLst = QStringList::split( '*', parameters, true );
+ QStringList paramsLst = parameters.split( '*' );
if ( myVP && myVP->inherits( "GLViewer_ViewPort2d" ) && paramsLst.size() == 4) {
GLViewer_ViewPort2d* vp2d = (GLViewer_ViewPort2d*)myVP;
class GLViewer_Viewer;
class GLViewer_ViewPort;
-#include <qaction.h>
+#include <QtxAction.h>
-#ifdef WNT
+#ifdef WIN32
#pragma warning( disable:4251 )
#endif
private:
//! Actions ID
enum { DumpId, FitAllId, FitRectId, FitSelectId, ZoomId, PanId, GlobalPanId, ResetId };
- typedef QMap<int, QAction*> ActionsMap;
+ typedef QMap<int, QtxAction*> ActionsMap;
private:
ActionsMap myActionsMap;
};
-#ifdef WNT
+#ifdef WIN32
#pragma warning ( default:4251 )
#endif
//#include <GLViewerAfx.h>
#include "GLViewer_ViewManager.h"
-#include "GLViewer_ViewFrame.h"
#include "GLViewer_Viewer2d.h"
#include "SUIT_Desktop.h"
}
/*!Context menu popup for \a popup.*/
-void GLViewer_ViewManager::contextMenuPopup( QPopupMenu* popup )
+void GLViewer_ViewManager::contextMenuPopup( QMenu* popup )
{
SUIT_ViewManager::contextMenuPopup( popup );
// if it is necessary invoke method CreatePopup of ViewPort
GLViewer_Viewer* getGLViewer() { return (GLViewer_Viewer*) myViewModel; }
- virtual void contextMenuPopup( QPopupMenu* );
+ virtual void contextMenuPopup( QMenu* );
};
#endif // GLVIEWER_VIEWMANAGER_H
//#include <GLViewerAfx.h>
-#if !(defined WNT) && !(defined QT_CLEAN_NAMESPACE)
-#define QT_CLEAN_NAMESPACE /* avoid definition of INT32 and INT8 */
-#endif
-
#include "GLViewer_ViewPort.h"
#include "SUIT_ResourceMgr.h"
#include "SUIT_Session.h"
-#include <qrect.h>
-#include <qcursor.h>
-#include <qpixmap.h>
-#include <qpainter.h>
-#include <qintdict.h>
-#include <qpopupmenu.h>
-#include <qcolordialog.h>
+#include <QRect>
+#include <QCursor>
+#include <QPainter>
+#include <QMultiHash>
+//#include <QMenu>
+#include <QColorDialog>
+#include <QColormap>
+#include <QMouseEvent>
+#include <QCoreApplication>
#include <stdlib.h>
-#if !defined WNT
+#if !defined WIN32
+#include <QX11Info>
#include <GL/glx.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
CMapEntry::~CMapEntry()
{
if ( alloc )
- XFreeColormap( QPaintDevice::x11AppDisplay(), cmap );
+ XFreeColormap( QX11Info::display(), cmap );
}
-static QIntDict<CMapEntry> *cmap_dict = 0;
+static QMultiHash<int,CMapEntry> *cmap_dict = 0;
static bool mesa_gl = false;
static void cleanup_cmaps()
{
if ( !cmap_dict )
return;
- cmap_dict->setAutoDelete( true );
+ //while (!cmap_dict->isEmpty())
+ // cmap_dict->erase(cmap_dict->begin());
+ cmap_dict->clear();
delete cmap_dict;
cmap_dict = 0;
}
{
if ( !cmap_dict )
{
- cmap_dict = new QIntDict<CMapEntry>;
+ cmap_dict = new QMultiHash<int,CMapEntry>;
const char *v = glXQueryServerString( dpy, vi->screen, GLX_VERSION );
mesa_gl = strstr( v,"Mesa" ) != 0;
qAddPostRoutine( cleanup_cmaps );
}
- CMapEntry *x = cmap_dict->find( (long)vi->visualid );
- if ( x ) // found colormap for visual
- return x->cmap;
+ QHash<int,CMapEntry>::iterator itH = cmap_dict->find( (long)vi->visualid );
+ if ( itH != cmap_dict->end() ) // found colormap for visual
+ return itH.value().cmap;
- x = new CMapEntry();
+ CMapEntry x;
XStandardColormap *c;
int n, i;
cout << "Choosing cmap for vID = " << vi->visualid << endl;
#endif
- if ( vi->visualid == XVisualIDFromVisual( (Visual*)QPaintDevice::x11AppVisual() ) )
+ if ( vi->visualid == XVisualIDFromVisual( (Visual*)QX11Info::appVisual() ) )
{
#ifdef DEBUG
cout << "Using x11AppColormap" << endl;
#endif
- return QPaintDevice::x11AppColormap();
+ return QX11Info::appColormap();
}
if ( mesa_gl )
if ( XGetRGBColormaps( dpy, RootWindow( dpy, vi->screen ), &c, &n, hp_cmaps ) )
{
i = 0;
- while ( i < n && x->cmap == 0 )
+ while ( i < n && x.cmap == 0 )
{
if ( c[i].visualid == vi->visual->visualid )
{
- x->cmap = c[i].colormap;
- x->scmap = c[i];
+ x.cmap = c[i].colormap;
+ x.scmap = c[i];
}
i++;
}
}
}
#if !defined( _OS_SOLARIS_ )
- if ( !x->cmap )
+ if ( !x.cmap )
{
if ( XmuLookupStandardColormap( dpy, vi->screen, vi->visualid, vi->depth, XA_RGB_DEFAULT_MAP, false, true ) )
{
if ( XGetRGBColormaps( dpy, RootWindow( dpy, vi->screen ), &c, &n, XA_RGB_DEFAULT_MAP ) )
{
i = 0;
- while ( i < n && x->cmap == 0 )
+ while ( i < n && x.cmap == 0 )
{
if ( c[i].visualid == vi->visualid )
{
- x->cmap = c[i].colormap;
- x->scmap = c[i];
+ x.cmap = c[i].colormap;
+ x.scmap = c[i];
}
i++;
}
}
}
#endif
- if ( !x->cmap )
+ if ( !x.cmap )
{
// no shared cmap found
- x->cmap = XCreateColormap( dpy, RootWindow( dpy, vi->screen ), vi->visual, AllocNone );
- x->alloc = true;
+ x.cmap = XCreateColormap( dpy, RootWindow( dpy, vi->screen ), vi->visual, AllocNone );
+ x.alloc = true;
}
cmap_dict->insert( (long)vi->visualid, x ); // associate cmap with visualid
- return x->cmap;
+ return x.cmap;
}
#endif
*/
void GLViewer_ViewPort::createCursors ()
{
- defCursor = new QCursor( ArrowCursor );
- panglCursor = new QCursor( CrossCursor );
- handCursor = new QCursor( PointingHandCursor );
- panCursor = new QCursor( SizeAllCursor );
+ defCursor = new QCursor( Qt::ArrowCursor );
+ panglCursor = new QCursor( Qt::CrossCursor );
+ handCursor = new QCursor( Qt::PointingHandCursor );
+ panCursor = new QCursor( Qt::SizeAllCursor );
SUIT_ResourceMgr* rmgr = SUIT_Session::session()->resourceMgr();
zoomCursor = new QCursor( rmgr->loadPixmap( "GLViewer", tr( "ICON_GL_CURSOR_ZOOM" ) ) );
Constructor
*/
GLViewer_ViewPort::GLViewer_ViewPort( QWidget* parent )
-: QWidget( parent, 0, WRepaintNoErase | WResizeNoErase )
+: QWidget( parent, 0 )
{
initialize();
}
myEnableTransform = true;
setMouseTracking( true );
- setBackgroundMode( NoBackground );
+ setBackgroundRole( QPalette::NoRole );//NoBackground );
- setFocusPolicy( StrongFocus );
+ setFocusPolicy( Qt::StrongFocus );
}
/*!
*/
void GLViewer_ViewPort::selectVisualId( ViewType type )
{
-#if !defined WNT
+#if !defined WIN32
XVisualInfo* pVisualInfo;
- if ( x11Display() )
+ if ( QX11Info::display() )
{
/* Initialization with the default VisualID */
//Visual *v = DefaultVisual( x11Display(), DefaultScreen( x11Display() ) );
int visualAttr[] = { GLX_RGBA, GLX_DEPTH_SIZE, 1, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1,
GLX_BLUE_SIZE, 1, GLX_DOUBLEBUFFER, None };
- pVisualInfo = ::glXChooseVisual( x11Display(), DefaultScreen( x11Display() ), visualAttr );
+ pVisualInfo = ::glXChooseVisual( QX11Info::display(), DefaultScreen( QX11Info::display() ), visualAttr );
if ( isVisible() )
hide();
XSetWindowAttributes a;
- a.colormap = choose_cmap( x11Display(), pVisualInfo ); /* find best colormap */
- a.background_pixel = backgroundColor().pixel();
- a.border_pixel = black.pixel();
- Window p = RootWindow( x11Display(), DefaultScreen( x11Display() ) );
+ a.colormap = choose_cmap( QX11Info::display(), pVisualInfo ); /* find best colormap */
+ a.background_pixel = QColormap::instance().pixel( backgroundColor() );
+ a.border_pixel = QColormap::instance().pixel( Qt::black );
+ Window p = RootWindow( QX11Info::display(), DefaultScreen( QX11Info::display() ) );
if ( parentWidget() )
p = parentWidget()->winId();
if ( type == Type2D ) // creating simple X window for 2d
{
unsigned long xbackground =
- BlackPixel( x11Display(), DefaultScreen( x11Display() ) );
+ BlackPixel( QX11Info::display(), DefaultScreen( QX11Info::display() ) );
unsigned long xforeground =
- WhitePixel( x11Display(), DefaultScreen( x11Display() ) );
+ WhitePixel( QX11Info::display(), DefaultScreen( QX11Info::display() ) );
- w = XCreateSimpleWindow ( x11Display(), p, x(), y(), width(),
+ w = XCreateSimpleWindow ( QX11Info::display(), p, x(), y(), width(),
height(), 0, xforeground, xbackground );
}
else if ( type == Type3D )
{
- w = XCreateWindow( x11Display(), p, x(), y(), width(), height(),
+ w = XCreateWindow( QX11Info::display(), p, x(), y(), width(), height(),
0, pVisualInfo->depth, InputOutput, pVisualInfo->visual,
CWBackPixel | CWBorderPixel | CWColormap, &a );
}
Window *cmw;
Window *cmwret;
int count;
- if ( XGetWMColormapWindows( x11Display(), topLevelWidget()->winId(), &cmwret, &count ) )
+ if ( XGetWMColormapWindows( QX11Info::display(), topLevelWidget()->winId(), &cmwret, &count ) )
{
cmw = new Window[count+1];
memcpy( (char*)cmw, (char*)cmwret, sizeof(Window) * count );
/* Creating new window (with good VisualID) for this widget */
create(w);
- XSetWMColormapWindows( x11Display(), topLevelWidget()->winId(), cmw, count );
+ XSetWMColormapWindows( QX11Info::display(), topLevelWidget()->winId(), cmw, count );
delete[] cmw;
if ( isVisible() )
{
XFree( (char *)pVisualInfo );
}
- XFlush( x11Display() );
+ XFlush( QX11Info::display() );
}
#endif
}
void GLViewer_ViewPort::setBackgroundColor( const QColor& color )
{
QPalette pal = palette();
- pal.setColor( QColorGroup::Background, color );
+ pal.setColor( QPalette::Background, color );
setPalette( pal );
repaint();
}
*/
QColor GLViewer_ViewPort::backgroundColor() const
{
- return palette().active().background();
+ return palette().color( QPalette::Active, QPalette::Background );
}
/*!
#include "GLViewer.h"
-#include <qlist.h>
-#include <qcolor.h>
-#include <qaction.h>
-#include <qwidget.h>
+//#include <QList>
+#include <QColor>
+//#include <QAction>
+#include <QWidget>
-#include <Aspect_Window.hxx>
+//#include <Aspect_Window.hxx>
class QRect;
class QCursor;
class GLViewer_ViewSketcher;
class GLViewer_ViewTransformer;
-#ifdef WNT
+#ifdef WIN32
#pragma warning( disable:4251 )
#endif
static QCursor* sketchCursor;
};
-#ifdef WNT
+#ifdef WIN32
#pragma warning ( default:4251 )
#endif
#include "GLViewer_ViewPort2d.h"
#include "GLViewer_Viewer2d.h"
#include "GLViewer_ViewFrame.h"
-#include "GLViewer_MimeSource.h"
+#include "GLViewer_MimeData.h"
#include "GLViewer_Context.h"
#include "GLViewer_Compass.h"
#include "GLViewer_Grid.h"
-
-#include <QtxToolTip.h>
-
-#include <qlayout.h>
-#include <qevent.h>
-#include <qrect.h>
-#include <qpopupmenu.h>
-#include <qtooltip.h>
-#include <qapplication.h>
-#include <qclipboard.h>
-#include <qpainter.h>
-#include <qbitmap.h>
-#include <qlabel.h>
+#include "GLViewer_Drawer.h"
+
+// TODO: Porting to Qt4
+//#include <QtxToolTip.h>
+
+#include <QHBoxLayout>
+#include <QMouseEvent>
+#include <QRect>
+//#include <QMenu>
+//#include <QToolTip>
+#include <QApplication>
+#include <QClipboard>
+#include <QBitmap>
+#include <QLabel>
+#include <QWidget>
+#include <QRubberBand>
#define WIDTH 640
#define HEIGHT 480
myMargin( MARGIN ), myWidth( WIDTH ), myHeight( HEIGHT ),
myXScale( 1.0 ), myYScale( 1.0 ), myXOldScale( 1.0 ), myYOldScale( 1.0 ),
myXPan( 0.0 ), myYPan( 0.0 ),
- myIsMouseReleaseBlock( false )
+ myIsMouseReleaseBlock( false ),
+ myRectBand(0)
{
if( theViewFrame == NULL )
myViewFrame = ( GLViewer_ViewFrame* )parent;
mypFirstPoint = NULL;
mypLastPoint = NULL;
- myObjectTip = new QtxToolTip( myGLWidget );///GLViewer_ObjectTip( this );
+ // TODO: Porting to Qt4
+ /*myObjectTip = new QtxToolTip( myGLWidget );///GLViewer_ObjectTip( this );
myObjectTip->setShowDelayTime( 60000 );
connect( myObjectTip, SIGNAL( maybeTip( QPoint, QString&, QFont&, QRect&, QRect& ) ),
- this, SLOT( onMaybeTip( QPoint, QString&, QFont&, QRect&, QRect& ) ) );
+ this, SLOT( onMaybeTip( QPoint, QString&, QFont&, QRect&, QRect& ) ) );*/
// myGLWidget->installEventFilter( myObjectTip );
}
delete myBorder;
delete myGLWidget;
+
+ if ( myRectBand ) myRectBand->hide();
+ delete myRectBand;
}
/*!
int aObjNum = aContext->NbSelected();
if( aObjNum > 0 )
{
- QValueList<GLViewer_Object*> aObjects;
- GLViewer_MimeSource* aMimeSource = new GLViewer_MimeSource();
+ QList<GLViewer_Object*> aObjects;
+ GLViewer_MimeData* aMimeData = new GLViewer_MimeData();
aContext->InitSelected();
for( ; aContext->MoreSelected(); aContext->NextSelected() )
aObjects.append( aContext->SelectedObject() );
- //aMimeSource->setObjects( aObjects ); ouv 6.05.04
+ //aMimeData->setObjects( aObjects ); ouv 6.05.04
QClipboard *aClipboard = QApplication::clipboard();
aClipboard->clear();
- aClipboard->setData( aMimeSource );
+ aClipboard->setMimeData( aMimeData );
for( int i = 0; i < aObjNum; i++ )
aContext->deleteObject( aObjects[i] );
int aObjNum = aContext->NbSelected();
if( aObjNum > 0 )
{
- QValueList<GLViewer_Object*> aObjects;
- GLViewer_MimeSource* aMimeSource = new GLViewer_MimeSource();
+ QList<GLViewer_Object*> aObjects;
+ GLViewer_MimeData* aMimeData = new GLViewer_MimeData();
aContext->InitSelected();
for( ; aContext->MoreSelected(); aContext->NextSelected() )
aObjects.append( aContext->SelectedObject() );
- //aMimeSource->setObjects( aObjects ); ouv 6.05.04
+ //aMimeData->setObjects( aObjects ); ouv 6.05.04
QClipboard *aClipboard = QApplication::clipboard();
aClipboard->clear();
- aClipboard->setData( aMimeSource );
+ aClipboard->setMimeData( aMimeData );
}
}
if( aMimeSource->provides( "GLViewer_Objects" ) )
{
QByteArray anArray = aMimeSource->encodedData( "GLViewer_Objects" );
- QValueList<GLViewer_Object*> aObjects = GLViewer_MimeSource::getObjects( anArray, "GLViewer_Objects" );
+ QList<GLViewer_Object*> aObjects = GLViewer_MimeSource::getObjects( anArray, "GLViewer_Objects" );
if( aObjects.empty() )
return;
GLViewer_Context* aContext = ((GLViewer_Viewer2d*)getViewFrame()->getViewer())->getGLContext();
//QPoint aNewPos = e->pos();
//GLViewer_Viewer2d* aViewer = (GLViewer_Viewer2d*)getViewFrame()->getViewer();
- if( anObject && (e->state() & LeftButton ) )
+ if( anObject && (e->buttons() & Qt::LeftButton ) )
{
if( aContext->isSelected( anObject ) )
{
else
anObject->moveObject( aX - *myCurDragPosX, anY - *myCurDragPosY);
}
- else if( aContext->NbSelected() && (e->state() & MidButton ) )
+ else if( aContext->NbSelected() && (e->buttons() & Qt::MidButton ) )
for( aContext->InitSelected(); aContext->MoreSelected(); aContext->NextSelected() )
(aContext->SelectedObject())->moveObject( aX - *myCurDragPosX, anY - *myCurDragPosY);
if( aContext )
anObject = aContext->getCurrentObject();
- bool accel = e->state() & GLViewer_ViewTransformer::accelKey();
+ bool accel = e->modifiers() & GLViewer_ViewTransformer::accelKey();
if( ( anObject && !( accel || e->button() == Qt::RightButton ) ) ||
( aContext->NbSelected() && !accel && e->button() == Qt::MidButton ) )
{
float dx, dy, zm;
float xScale, yScale;
- myMargin = QMAX( myBorder->width(), myBorder->height() ) / 5;
+ myMargin = qMax( myBorder->width(), myBorder->height() ) / 5;
xa = myBorder->left() - myMargin;
xb = myBorder->right() + myMargin;
mypFirstPoint = new QPoint( x, y );
mypLastPoint = new QPoint( x, y );
}
+
+ if ( !myRectBand ) {
+ myRectBand = new QRubberBand( QRubberBand::Rectangle, this );
+ QPalette palette;
+ palette.setColor(myRectBand->foregroundRole(), Qt::white);
+ myRectBand->setPalette(palette);
+ }
+ myRectBand->hide();
}
/*!
{
if( mypFirstPoint && mypLastPoint )
{
-
- QPainter p( getPaintDevice() );
- p.setPen( Qt::white );
- p.setRasterOp( Qt::XorROP );
-
- p.drawRect( selectionRect() ); /* erase */
-
- mypLastPoint->setX( x );
+ myRectBand->hide(); /* erase */
+
+ mypLastPoint->setX( x );
mypLastPoint->setY( y );
- p.drawRect( selectionRect() ); /* draw */
+ QRect aRect = selectionRect();
+ myRectBand->setGeometry( aRect ); /* draw */
+ myRectBand->setVisible( aRect.isValid() );
}
}
if( mypFirstPoint && mypLastPoint )
{
- QPainter p( getPaintDevice() );
- p.setPen( Qt::white );
- p.setRasterOp( Qt::XorROP );
- p.drawRect( selectionRect() ); /* erase */
+ if ( myRectBand ) myRectBand->hide(); /* erase */
delete mypFirstPoint;
delete mypLastPoint;
mypFirstPoint = NULL;
mypLastPoint = NULL;
+
+ delete myRectBand;
+ myRectBand = 0;
}
}
QRect aRect;
if( mypFirstPoint && mypLastPoint )
{
- aRect.setLeft( QMIN( mypFirstPoint->x(), mypLastPoint->x() ) );
- aRect.setTop( QMIN( mypFirstPoint->y(), mypLastPoint->y() ) );
- aRect.setRight( QMAX( mypFirstPoint->x(), mypLastPoint->x() ) );
- aRect.setBottom( QMAX( mypFirstPoint->y(), mypLastPoint->y() ) );
+ aRect.setLeft( qMin( mypFirstPoint->x(), mypLastPoint->x() ) );
+ aRect.setTop( qMin( mypFirstPoint->y(), mypLastPoint->y() ) );
+ aRect.setRight( qMax( mypFirstPoint->x(), mypLastPoint->x() ) );
+ aRect.setBottom( qMax( mypFirstPoint->y(), mypLastPoint->y() ) );
}
return aRect;
QStringList aList;
if( anObj->isTooTipHTML() )
- aList = QStringList::split( "<br>", theText );
+ aList = theText.split( "<br>", QString::SkipEmptyParts );
else
- aList = QStringList::split( "\n", theText );
+ aList = theText.split( "\n", QString::SkipEmptyParts );
if( !aList.isEmpty() )
{
#ifndef GLVIEWER_VIEWPORT2D_H
#define GLVIEWER_VIEWPORT2D_H
-#ifdef WNT
+#ifdef WIN32
#include <windows.h>
#endif
#include "GLViewer_Widget.h"
#include "GLViewer_Geom.h"
-#include <qgl.h>
-#include <qcolor.h>
-#include <qwidget.h>
-#include <qpaintdevice.h>
+#include <QtOpenGL>
+#include <QColor>
+#include <QPaintDevice>
-#ifdef WNT
+#ifdef WIN32
#pragma warning( disable:4251 )
#endif
class GLViewer_ViewFrame;
class QtxToolTip;
+
+class QWidget;
+class QRubberBand;
+
/*!
* Class GLViewer_ViewPort
* 2D visualisation canvas of GLViewer
QtxToolTip* myObjectTip;
//! flag to block mouse release event just after mouse double-click
bool myIsMouseReleaseBlock;
+
+ QRubberBand* myRectBand; //!< selection rectangle rubber band
};
-#ifdef WNT
+#ifdef WIN32
#pragma warning ( default:4251 )
#endif
#include "GLViewer_ViewPort.h"
#include "GLViewer_ViewFrame.h"
-#include "SUIT_Desktop.h"
+//#include "SUIT_Desktop.h"
#include "SUIT_ViewWindow.h"
+#include "SUIT_ViewManager.h"
-#include <qapplication.h>
-#include <qpainter.h>
-#include <qpopupmenu.h>
-#include <qcolordialog.h>
+#include <QApplication>
+#include <QMenu>
+#include <QColorDialog>
+#include <QMouseEvent>
+#include <QWheelEvent>
+#include <QRect>
+#include <QRubberBand>
/* used for sketching */
static QEvent* l_mbPressEvent = 0;
/*!
Builds popup for GL viewer
*/
-void GLViewer_Viewer::contextMenuPopup( QPopupMenu* thePopup )
+void GLViewer_Viewer::contextMenuPopup( QMenu* thePopup )
{
- if( thePopup->count() > 0 )
- thePopup->insertSeparator();
+ if( thePopup->actions().count() > 0 )
+ thePopup->addSeparator();
- thePopup->insertItem( tr( "CHANGE_BGCOLOR" ), this, SLOT( onChangeBgColor() ) );
+ thePopup->addAction( tr( "CHANGE_BGCOLOR" ), this, SLOT( onChangeBgColor() ) );
}
/*!
void GLViewer_Viewer::onSelectionModeChanged()
{
bool enable = ( mySelMode == Multiple );
- QPtrVector<SUIT_ViewWindow> views = getViewManager()->getViews();
+ QVector<SUIT_ViewWindow*> views = getViewManager()->getViews();
for ( int i = 0, n = views.count(); i < n; i++ )
{
GLViewer_ViewPort* vp = ((GLViewer_ViewFrame*)views[i])->getViewPort();
*/
void GLViewer_Viewer::update( int flags )
{
- QPtrVector<SUIT_ViewWindow> views = getViewManager()->getViews();
+ QVector<SUIT_ViewWindow*> views = getViewManager()->getViews();
for ( int i = 0, n = views.count(); i < n; i++ )
((GLViewer_ViewFrame*)views[i])->onUpdate( flags );
}
void GLViewer_Viewer::handleMousePress( QMouseEvent* e )
{
/* test accel for transforms */
- if ( e->state() & GLViewer_ViewTransformer::accelKey() )
+ if ( e->modifiers() & GLViewer_ViewTransformer::accelKey() )
{
- ButtonState bs = e->button();
+ Qt::MouseButton bs = e->button();
if ( bs == GLViewer_ViewTransformer::zoomButton() )
activateTransform( Zoom );
else if ( bs == GLViewer_ViewTransformer::panButton() )
void GLViewer_Viewer::handleMouseMove( QMouseEvent* e )
{
/* Highlight for selection */
- bool dragged = ( e->state() & ( LeftButton | MidButton | RightButton ) );
+ bool dragged = ( e->buttons() & ( Qt::LeftButton | Qt::MidButton | Qt::RightButton ) );
if ( !dragged )
{
if ( getSelector() )
}
/* Try to activate default sketching
*/
- else if ( e->state() == GLViewer_ViewSketcher::sketchButton() )
+ else if ( e->button() == GLViewer_ViewSketcher::sketchButton() )
{
activateSketching( Rect );
if ( mySketcher )
{
/* selection */
/* tmp - in handleMousePress*/
- if( e->button() == LeftButton && !(getActiveView()->getViewPort()->currentBlock() & BS_Selection) )
+ if( e->button() == Qt::LeftButton && !(getActiveView()->getViewPort()->currentBlock() & BS_Selection) )
{
if ( getSelector() )
{
- bool append = bool ( e->state() & GLViewer_Selector::appendKey() );
+ bool append = bool ( e->modifiers() & GLViewer_Selector::appendKey() );
getSelector()->select( append );
}
}
int GLViewer_ViewTransformer::zoomBtn = Qt::LeftButton;
int GLViewer_ViewTransformer::fitRectBtn = Qt::LeftButton;
int GLViewer_ViewTransformer::panGlobalBtn = Qt::LeftButton;
-int GLViewer_ViewTransformer::acccelKey = Qt::ControlButton;
+int GLViewer_ViewTransformer::acccelKey = Qt::ControlModifier;
/*!
Constructor
: QObject( 0 ),
myViewer( v ),
myType( type ),
-myMajorBtn( NoButton ),
-myButtonState( 0 )
+myMajorBtn( Qt::NoButton ),
+myButtonState( 0 ),
+myRectBand( 0 )
{
if ( myType == GLViewer_Viewer::Pan ||
myType == GLViewer_Viewer::Zoom ||
}
//QAD_Application::getDesktop()->clearInfo();
+
+ endDrawRect();
}
/*!
TransformState state = EnTrain;
QMouseEvent* me = ( QMouseEvent* )e;
- myButtonState = me->state();
+ myButtonState = me->modifiers();
if ( e->type() == QEvent::MouseButtonPress )
myButtonState |= me->button(); /* add pressed button */
- int mouseOnlyState = ( myButtonState & ( LeftButton | MidButton | RightButton ) );
+ int mouseOnlyState = ( myButtonState & ( Qt::LeftButton | Qt::MidButton | Qt::RightButton ) );
if ( myStart.isNull() )
{
state = Debut;
{
if ( doTrsf )
{
- QRect rect( QMIN( myStart.x(), myCurr.x() ), QMIN( myStart.y(), myCurr.y() ),
- QABS( myStart.x() - myCurr.x() ), QABS( myStart.y() - myCurr.y() ) );
+ QRect rect( qMin( myStart.x(), myCurr.x() ), qMin( myStart.y(), myCurr.y() ),
+ qAbs( myStart.x() - myCurr.x() ), qAbs( myStart.y() - myCurr.y() ) );
if ( !rect.isEmpty() )
{
switch ( state )
break;
default:
{
- QPainter p( avp->getPaintDevice() ); // for QAD_GLWidget
- p.setPen( Qt::white );
- p.setRasterOp( Qt::XorROP );
- if ( !myDrawRect.isEmpty() )
- p.drawRect( myDrawRect ); /* erase */
- p.drawRect( rect );
- myDrawRect = rect;
+ drawRect( rect );
break;
}
}
myViewer->activateTransform( GLViewer_Viewer::NoTransform );
}
+/*!
+ Draws rectangle by starting and current points
+*/
+void GLViewer_ViewTransformer::drawRect(const QRect& theRect)
+{
+ if ( !myRectBand ) {
+ myRectBand = new QRubberBand( QRubberBand::Rectangle, myViewer->getActiveView()->getViewPort() );
+ QPalette palette;
+ palette.setColor(myRectBand->foregroundRole(), Qt::white);
+ myRectBand->setPalette(palette);
+ }
+ myRectBand->hide();
+
+ myRectBand->setGeometry( theRect );
+ myRectBand->setVisible( theRect.isValid() );
+}
+
+/*!
+ \brief Delete rubber band on the end on the dragging operation.
+*/
+void GLViewer_ViewTransformer::endDrawRect()
+{
+ if ( myRectBand ) myRectBand->hide();
+
+ delete myRectBand;
+ myRectBand = 0;
+}
+
/*!
Returns the type of the transformer. [ public ]
*/
}
-int GLViewer_ViewSketcher::sketchBtn = LeftButton;
+int GLViewer_ViewSketcher::sketchBtn = Qt::LeftButton;
/*!
Constructor
: QObject( 0 ),
myViewer( viewer ),
myData( 0 ),
-myType( type )
+myType( type ),
+myRectBand( 0 )
{
if( !myViewer )
return;
if ( myType == GLViewer_Viewer::Rect )
delete ( QRect* ) myData;
+
+ endDrawRect();
}
/*!
SketchState state = EnTrain;
QMouseEvent* me = (QMouseEvent*)e;
- myButtonState = me->state();
+ myButtonState = me->modifiers();
if ( e->type() == QEvent::MouseButtonPress )
myButtonState |= me->button(); /* add pressed button */
myStart = me->pos();
}
- int mouseOnlyState = ( myButtonState & ( LeftButton | MidButton | RightButton ) );
+ int mouseOnlyState = ( myButtonState & ( Qt::LeftButton | Qt::MidButton | Qt::RightButton ) );
if ( e->type() == QEvent::MouseButtonRelease && mouseOnlyState == sketchButton() )
{
state = Fin;
QRect* sketchRect = ( QRect* )data();
if ( myButtonState & sketchButton() )
{
- QRect rect( QMIN( myStart.x(), myCurr.x() ), QMIN( myStart.y(), myCurr.y() ),
- QABS( myStart.x() - myCurr.x() ), QABS( myStart.y() - myCurr.y() ) );
+ QRect rect( qMin( myStart.x(), myCurr.x() ), qMin( myStart.y(), myCurr.y() ),
+ qAbs( myStart.x() - myCurr.x() ), qAbs( myStart.y() - myCurr.y() ) );
if ( !rect.isEmpty() )
{
- QPainter p( avp );
- p.setPen( Qt::white );
- p.setRasterOp( Qt::XorROP );
- if ( !sketchRect->isEmpty() )
- p.drawRect( *sketchRect ); /* erase */
+ if ( !sketchRect->isEmpty() && myRectBand )
+ myRectBand->hide(); /* erase */
*sketchRect = rect;
if ( state != Fin )
- p.drawRect( *sketchRect );
+ drawRect( *sketchRect );
}
}
}
myViewer->activateSketching( GLViewer_Viewer::NoSketching );
}
}
+
+/*!
+ Draws rectangle by starting and current points
+*/
+void GLViewer_ViewSketcher::drawRect(const QRect& theRect)
+{
+ if ( !myRectBand ) {
+ myRectBand = new QRubberBand( QRubberBand::Rectangle, myViewer->getActiveView()->getViewPort() );
+ QPalette palette;
+ palette.setColor(myRectBand->foregroundRole(), Qt::white);
+ myRectBand->setPalette(palette);
+ }
+ myRectBand->hide();
+
+ myRectBand->setGeometry( theRect );
+ myRectBand->setVisible( theRect.isValid() );
+}
+
+/*!
+ \brief Delete rubber band on the end on the dragging operation.
+*/
+void GLViewer_ViewSketcher::endDrawRect()
+{
+ if ( myRectBand ) myRectBand->hide();
+
+ delete myRectBand;
+ myRectBand = 0;
+}
#ifndef GLVIEWER_VIEWER_H
#define GLVIEWER_VIEWER_H
+#include "GLViewer.h"
#include "GLViewer_Defs.h"
-#include "GLViewer_ViewFrame.h"
#include <SUIT_ViewModel.h>
-#include <qlist.h>
-#include <qcursor.h>
-#include <qobject.h>
-#include <qpixmap.h>
+#include <QCursor>
+#include <QObject>
+
+class QMouseEvent;
+class QKeyEvent;
+class QWheelEvent;
+class QRect;
+class QRubberBand;
class GLViewer_Selector;
class GLViewer_ViewSketcher;
class GLViewer_ViewTransformer;
+class GLViewer_ViewFrame;
-class SUIT_Desktop;
+//class SUIT_Desktop;
class SUIT_ViewWindow;
-#ifdef WNT
+#ifdef WIN32
#pragma warning( disable:4251 )
#endif
virtual QString getType() const { return Type(); }
static QString Type() { return "GLViewer_ViewModel"; }
- virtual void contextMenuPopup( QPopupMenu* );
+ virtual void contextMenuPopup( QMenu* );
public:
void setSelectionMode( SelectionMode );
virtual void onTransform( TransformState );
void initTransform( bool );
+ void drawRect(const QRect& theRect);
+ void endDrawRect();
+
protected:
static int panBtn;
static int zoomBtn;
bool mySavedMouseTrack;
QPoint myStart, myCurr;
int myButtonState;
- QRect myDrawRect;
int myMajorBtn;
+
+ QRubberBand* myRectBand; //!< selection rectangle rubber band
};
class GLVIEWER_API GLViewer_ViewSketcher : public QObject
enum SketchState { Debut, EnTrain, Fin };
virtual void onSketch( SketchState );
+ void drawRect(const QRect& theRect);
+ void endDrawRect();
+
protected:
static int sketchBtn;
GLViewer_Viewer* myViewer;
QCursor mySavedCursor;
QPoint myStart, myCurr;
int myButtonState;
+
+ QRubberBand* myRectBand; //!< selection rectangle rubber band
};
-#ifdef WNT
+#ifdef WIN32
#pragma warning ( default:4251 )
#endif
//#include <GLViewerAfx.h>
#include "GLViewer_Viewer2d.h"
#include "GLViewer_Object.h"
+#include "GLViewer_ViewFrame.h"
#include "GLViewer_BaseObjects.h"
#include "GLViewer_CoordSystem.h"
#include "GLViewer_Context.h"
#include "SUIT_Desktop.h"
#include "SUIT_ViewWindow.h"
+#include "SUIT_ViewManager.h"
-#include "OSD_Timer.hxx"
-#include <TColStd_MapOfInteger.hxx>
-
-#include <qpopupmenu.h>
-#include <qpointarray.h>
-#include <qcolordialog.h>
+#include <QMenu>
+#include <QPolygon>
+#include <QColorDialog>
+#include <QRect>
+#include <QFile>
+#include <QMouseEvent>
/*!
Constructor
Adds item for change background color
\param thePopup - menu
*/
-void GLViewer_Viewer2d::addPopupItems( QPopupMenu* thePopup )
+void GLViewer_Viewer2d::addPopupItems( QMenu* thePopup )
{
// CTH8434. "Change background color" menu item is available if there are no selected objects
if ( getSelector() == 0 || getSelector()->numSelected() == 0 )
{
- if( thePopup->count() > 0 )
- thePopup->insertSeparator();
- thePopup->insertItem( tr( "CHANGE_BGCOLOR" ), this, SLOT( onChangeBgColor() ) );
+ if( thePopup->actions().count() > 0 )
+ thePopup->addSeparator();
+ thePopup->addAction( tr( "CHANGE_BGCOLOR" ), this, SLOT( onChangeBgColor() ) );
}
}
*/
void GLViewer_Viewer2d::updateBorders( GLViewer_Rect* theRect )
{
- QPtrVector<SUIT_ViewWindow> views = getViewManager()->getViews();
+ QVector<SUIT_ViewWindow*> views = getViewManager()->getViews();
for ( int i = 0, n = views.count(); i < n; i++ )
{
GLViewer_Rect* border = ( ( GLViewer_ViewPort2d* )((GLViewer_ViewFrame*)views[i])->getViewPort() )->getBorder();
- border->setLeft( QMIN( border->left(), theRect->left() ) );
- border->setRight( QMAX( border->right(), theRect->right() ) );
- border->setBottom( QMIN( border->bottom(), theRect->bottom() ) );
- border->setTop( QMAX( border->top(), theRect->top() ) );
+ border->setLeft( qMin( border->left(), theRect->left() ) );
+ border->setRight( qMax( border->right(), theRect->right() ) );
+ border->setBottom( qMin( border->bottom(), theRect->bottom() ) );
+ border->setTop( qMax( border->top(), theRect->top() ) );
}
}
*/
void GLViewer_Viewer2d::updateBorders()
{
- QPtrVector<SUIT_ViewWindow> views = getViewManager()->getViews();
+ QVector<SUIT_ViewWindow*> views = getViewManager()->getViews();
ObjList anObjects = myGLContext->getObjects();
ObjList::Iterator beginIt = anObjects.begin();
}
else
{
- border->setLeft( QMIN( border->left(), aRect->left() ) );
- border->setRight( QMAX( border->right(), aRect->right() ) );
- border->setBottom( QMIN( border->bottom(), aRect->bottom() ) );
- border->setTop( QMAX( border->top(), aRect->top() ) );
+ border->setLeft( qMin( border->left(), aRect->left() ) );
+ border->setRight( qMax( border->right(), aRect->right() ) );
+ border->setBottom( qMin( border->bottom(), aRect->bottom() ) );
+ border->setTop( qMax( border->top(), aRect->top() ) );
}
}
}
if ( !getActiveView() )
return;
- QPtrVector<SUIT_ViewWindow> views = getViewManager()->getViews();
+ QVector<SUIT_ViewWindow*> views = getViewManager()->getViews();
for ( int i = 0, n = views.count(); i < n; i++ )
( ( GLViewer_ViewPort2d* )( ( GLViewer_ViewFrame* )views[i] )->getViewPort() )->getGLWidget()->updateGL();
}
/*!
Activates drawers for objects from list \param theObjects only
*/
-void GLViewer_Viewer2d::activateDrawers( QValueList<GLViewer_Object*>& theObjects, bool onlyUpdate, GLboolean swap )
+void GLViewer_Viewer2d::activateDrawers( QList<GLViewer_Object*>& theObjects, bool onlyUpdate, GLboolean swap )
{
//cout << "GLViewer_Viewer2d::activateDrawers " << (int)onlyUpdate << " " << (int)swap << endl;
- QValueList<GLViewer_Drawer*>::Iterator anIt = myDrawers.begin();
- QValueList<GLViewer_Drawer*>::Iterator endDIt = myDrawers.end();
+ QList<GLViewer_Drawer*>::Iterator anIt = myDrawers.begin();
+ QList<GLViewer_Drawer*>::Iterator endDIt = myDrawers.end();
for( ; anIt != endDIt; anIt++ )
(*anIt)->clear();
- QValueList<GLViewer_Drawer*> anActiveDrawers;
- QValueList<GLViewer_Object*>::Iterator endOIt = theObjects.end();
+ QList<GLViewer_Drawer*> anActiveDrawers;
+ QList<GLViewer_Object*>::Iterator endOIt = theObjects.end();
- for( QValueList<GLViewer_Object*>::Iterator oit = theObjects.begin(); oit != endOIt; ++oit )
+ for( QList<GLViewer_Object*>::Iterator oit = theObjects.begin(); oit != endOIt; ++oit )
{
GLViewer_Drawer* aDrawer = (*oit)->getDrawer();
if( !aDrawer )
int aPriority = aDrawer->getPriority();
- if( anActiveDrawers.findIndex( aDrawer ) != -1 )
+ if( anActiveDrawers.indexOf( aDrawer ) != -1 )
continue;
- QValueList<GLViewer_Drawer*>::Iterator aDIt = anActiveDrawers.begin();
- QValueList<GLViewer_Drawer*>::Iterator aDEndIt = anActiveDrawers.end();
+ QList<GLViewer_Drawer*>::Iterator aDIt = anActiveDrawers.begin();
+ QList<GLViewer_Drawer*>::Iterator aDEndIt = anActiveDrawers.end();
for( ; aDIt != aDEndIt; ++aDIt )
if( (*aDIt)->getPriority() > aPriority )
break;
anActiveDrawers.insert( aDIt, aDrawer );
}
- QValueList<GLViewer_Drawer*>::Iterator aDIt = anActiveDrawers.begin();
- QValueList<GLViewer_Drawer*>::Iterator aDEndIt = anActiveDrawers.end();
+ QList<GLViewer_Drawer*>::Iterator aDIt = anActiveDrawers.begin();
+ QList<GLViewer_Drawer*>::Iterator aDEndIt = anActiveDrawers.end();
- QPtrVector<SUIT_ViewWindow> views = getViewManager()->getViews();
+ QVector<SUIT_ViewWindow*> views = getViewManager()->getViews();
for ( int i = 0, n = views.count(); i < n; i++ )
{
float xScale, yScale;
GLfloat anAngle = curvp->getGLWidget()->getRotationAngle() * PI / 180.;
- QPointArray aPointArray(4);
+ QPolygon aPointArray(4);
aPointArray[0] = QPoint( (int)(aLeft*cos(anAngle) - aTop*sin(anAngle)),
(int)(aLeft*sin(anAngle) + aTop*cos(anAngle)) );
aPointArray[1] = QPoint( (int)(aRight*cos(anAngle) - aTop*sin(anAngle)),
{
int x = aPointArray[i].x();
int y = aPointArray[i].y();
- aMinLeft = QMIN( aMinLeft,x );
- aMaxRight = QMAX( aMaxRight, x );
- aMinTop = QMIN( aMinTop, y );
- aMaxBottom = QMAX( aMaxBottom, y );
+ aMinLeft = qMin( aMinLeft,x );
+ aMaxRight = qMax( aMaxRight, x );
+ aMinTop = qMin( aMinTop, y );
+ aMaxBottom = qMax( aMaxBottom, y );
}
aLeft = (aMinLeft/* + xPan*/)*xScale + aWidth / 2;
{
if ( ( e->button() == GLViewer_View2dTransformer::rotateButton() ) &&
( e->type() == QEvent::MouseButtonPress ) &&
- ( e->state() & GLViewer_ViewTransformer::accelKey() ) )
+ ( e->modifiers() & GLViewer_ViewTransformer::accelKey() ) )
{
activateTransform( GLViewer_Viewer::Rotate );
return true;
header += "%%Pages: 1\n";
header += "%%Page: 1\n\n";
- hFile.writeBlock( header.ascii(), header.length() );
+ hFile.write( header.toAscii() );
}
else if( aType == HPGL )
{
header += "LT;\n";
header += "VS36;\n";
- hFile.writeBlock( header.ascii(), header.length() );
+ hFile.write( header.toAscii() );
}
}
if( aType == POST_SCRIPT )
{
QString ending = "showpage\n\n%%EOF";
- hFile.writeBlock( ending.ascii(), ending.length() );
+ hFile.write( ending.toAscii() );
}
else if( aType == HPGL )
{
QString ending = "PU;PA0,0;SP;EC;PG1;EC1;OE\n";
- hFile.writeBlock( ending.ascii(), ending.length() );
+ hFile.write( ending.toAscii() );
}
}
if ( !getActiveView() )
return false;
- QFile hFile( FileName.ascii() );
+ QFile hFile( FileName.toAscii() );
#ifdef WIN32
HDC hMetaFileDC;
if( aType==POST_SCRIPT || aType==HPGL )
{
- hFile.open( IO_ReadWrite | IO_Truncate );
- hFile.at( 0 );
+ hFile.open( QIODevice::ReadWrite | QIODevice::Truncate );
+ hFile.seek( 0 );
insertHeader( aType, hFile );
}
#ifdef WIN32
HDC screen_dc = GetDC( 0 ); //The screen device context
HDC bitDC = CreateCompatibleDC ( screen_dc ); //The context compatible with screen
- hMetaFileDC = CreateEnhMetaFile( bitDC, FileName.ascii(), &r, "" );
+ hMetaFileDC = CreateEnhMetaFile( bitDC, FileName.toAscii(), &r, "" );
SetMapMode( hMetaFileDC, MM_HIMETRIC );
SetWindowOrgEx( hMetaFileDC, 0, r.bottom, NULL );
HRGN ClipRgn = CreateRectRgn( 0, 0, AW, AH );
arg( AW-mmLeft-mmRight ).arg( AH-mmBottom-mmTop );
//It is set clipping path
- hFile.writeBlock( aBuffer.ascii(), aBuffer.length() );
+ hFile.write( aBuffer.toAscii() );
aCurVP->getGLWidget()->translateBackgroundToPS( hFile, &aViewerCS, &aPaperCS );
}
float xScale;
float yScale;
- QValueList<GLViewer_Drawer*>::Iterator anIt = myDrawers.begin();
- QValueList<GLViewer_Drawer*>::Iterator endDIt = myDrawers.end();
+ QList<GLViewer_Drawer*>::Iterator anIt = myDrawers.begin();
+ QList<GLViewer_Drawer*>::Iterator endDIt = myDrawers.end();
for( ; anIt != endDIt; anIt++ )
(*anIt)->clear();
- QValueList<GLViewer_Drawer*> anActiveDrawers;
- QValueList<GLViewer_Object*>::Iterator endOIt = anActiveObjs.end();
+ QList<GLViewer_Drawer*> anActiveDrawers;
+ QList<GLViewer_Object*>::Iterator endOIt = anActiveObjs.end();
- for( QValueList<GLViewer_Object*>::Iterator oit = anActiveObjs.begin(); oit != endOIt; ++oit )
+ for( QList<GLViewer_Object*>::Iterator oit = anActiveObjs.begin(); oit != endOIt; ++oit )
{
GLViewer_Drawer* aDrawer = (*oit)->getDrawer();
if( !aDrawer )
}
}
aDrawer->addObject( (*oit) );
- if( anActiveDrawers.findIndex( aDrawer ) == -1 )
+ if( anActiveDrawers.indexOf( aDrawer ) == -1 )
anActiveDrawers.append( aDrawer );
}
- QValueList<GLViewer_Drawer*>::Iterator aDIt = anActiveDrawers.begin();
- QValueList<GLViewer_Drawer*>::Iterator aDEndIt = anActiveDrawers.end();
+ QList<GLViewer_Drawer*>::Iterator aDIt = anActiveDrawers.begin();
+ QList<GLViewer_Drawer*>::Iterator aDEndIt = anActiveDrawers.end();
GLViewer_ViewPort2d* vp = ( GLViewer_ViewPort2d* )aCurView->getViewPort();
vp->getScale( xScale, yScale );
vp->finishSelectByRect();
if ( getSelector() && !aSelRect.isNull() )
{
- bool append = bool ( e->state() & GLViewer_Selector::appendKey() );
+ bool append = bool ( e->modifiers() & GLViewer_Selector::appendKey() );
getSelector()->select( aSelRect, append );
}
}
}
-int GLViewer_View2dTransformer::rotateBtn = RightButton;
+int GLViewer_View2dTransformer::rotateBtn = Qt::RightButton;
/*!
Constructor
#ifndef GLVIEWER_VIEWER2D_H
#define GLVIEWER_VIEWER2D_H
-#ifdef WNT
+#ifdef WIN32
#include <windows.h>
#endif
-#include <qmap.h>
-#include <qrect.h>
+class QRect;
+class QFile;
#include "GLViewer_Viewer.h"
-#include "GLViewer_Object.h"
-#include "GLViewer_ViewFrame.h"
-#include "GLViewer_Drawer.h"
#include <TColStd_SequenceOfInteger.hxx>
#include <GL/gl.h>
class GLViewer_Object;
+class GLViewer_ViewFrame;
+class GLViewer_Drawer;
class GLViewer_Context;
-class GLViewer_Selector2d;
+class GLViewer_Rect;
//class GLViewer_Sketcher;
class SUIT_Desktop;
/* A5 */ 148.5, 210.0
};
-#ifdef WNT
+#ifdef WIN32
#pragma warning( disable:4251 )
#endif
virtual SUIT_ViewWindow* createView( SUIT_Desktop* );
//! Adds item for change background color
- void addPopupItems( QPopupMenu* );
+ void addPopupItems( QMenu* );
//void activateGLSketching( int );
//! Returns all drawers
- const QValueList<GLViewer_Drawer*>& getDrawers() const { return myDrawers; }
+ const QList<GLViewer_Drawer*>& getDrawers() const { return myDrawers; }
//! Returns context
GLViewer_Context* getGLContext() const { return myGLContext; }
/* \param onlyUpdate is passed to method activateAllDrawersdrawers*/
void updateDrawers( GLboolean onlyUpdate, GLfloat scX = 0.0, GLfloat scY = 0.0 );
//! Activates drawers for objects from list \param theObjects only
- void activateDrawers( QValueList<GLViewer_Object*>& theObjects, bool onlyUpdate, GLboolean swap = GL_FALSE );
+ void activateDrawers( QList<GLViewer_Object*>& theObjects, bool onlyUpdate, GLboolean swap = GL_FALSE );
//! Activates drawer for \param theObject
void activateDrawer( GLViewer_Object* theObject, bool onlyUpdate, GLboolean swap = GL_FALSE );
//! Updates all drawers with new scale factor
//! Current context
GLViewer_Context* myGLContext;
//! Map of active drawers
- QValueList<GLViewer_Drawer*> myDrawers;
+ QList<GLViewer_Drawer*> myDrawers;
//GLViewer_Sketcher* myGLSketcher;
};
static int rotateBtn;
};
-#ifdef WNT
+#ifdef WIN32
#pragma warning ( default:4251 )
#endif
#include "GLViewer_Widget.h"
#include "GLViewer_ViewPort2d.h"
#include "GLViewer_Viewer2d.h"
-#include "GLViewer_Compass.h"
+//#include "GLViewer_Compass.h"
#include "GLViewer_Grid.h"
-#include "GLViewer_Object.h"
+//#include "GLViewer_Object.h"
#include "GLViewer_CoordSystem.h"
+#include "GLViewer_ViewFrame.h"
#include <cmath>
using namespace std;
-#include <qevent.h>
-#include <qrect.h>
+#include <QEvent>
+#include <QPaintEvent>
+#include <QRect>
-#include <qpixmap.h>
-#include <qimage.h>
-#include <qapplication.h>
-#include <qintdict.h>
-#include <qpaintdevicemetrics.h>
-#include <qsize.h>
-#include <qtooltip.h>
+#include <QFile>
+//#include <qpixmap.h>
+#include <QImage>
+#include <QApplication>
+//#include <qintdict.h>
+//#include <qpaintdevicemetrics.h>
+//#include <qsize.h>
+#include <QToolTip>
/*!
A constructor
void GLViewer_Widget::addToolTip( QString theString, QRect theRect )
{
myToolTipRect = theRect;
- QToolTip::add( this, myToolTipRect, theString );
+ setToolTip(theString);
+ //QToolTip::add( this, myToolTipRect, theString );
}
/*!
*/
void GLViewer_Widget::removeToolTip()
{
- QToolTip::remove( this, myToolTipRect );
+ setToolTip("");
+ //QToolTip::remove( this, myToolTipRect );
}
/*!
updateGL();
}
+/*!
+ Custom leave event handler
+*/
+bool GLViewer_Widget::event ( QEvent* e )
+{
+ if (e->type() == QEvent::ToolTip) {
+ QHelpEvent *helpEvent = static_cast<QHelpEvent *>(e);
+ if ( myToolTipRect.contains(helpEvent->pos()) )
+ QToolTip::showText(helpEvent->globalPos(), toolTip());
+ }
+ return QGLWidget::event(e);
+}
/*!
\return the hex code of digit < 16
aBuffer += "> false 3 colorimage\n\n";
- hFile.writeBlock( aBuffer.ascii(), aBuffer.length() );
+ hFile.write( aBuffer.toAscii() );
}
}
const int max = 133000; //The maximum length of string in PS
int dh = int( floor( double( max ) / ( 3.0*2.0*width ) ) );
for( int k=buf.height()-1; k>=0; k-=dh )
- AddImagePart( hFile, buf, 0, buf.width()-1, QMAX( k-dh+1, 0 ), k,
+ AddImagePart( hFile, buf, 0, buf.width()-1, qMax( k-dh+1, 0 ), k,
aViewerCS, aPSCS, a, b, c, d, dx, dy-(buf.height()-1-k) );
}
}
#include "GLViewer.h"
-#include <qgl.h>
-#include <qfile.h>
+#include <QtOpenGL>
+
+class QFile;
class GLViewer_ViewPort2d;
class GLViewer_CoordSystem;
virtual void enterEvent( QEvent* );
/* Needs to redefine because Window must be updated highlight presentation when mouse leave window */
virtual void leaveEvent( QEvent* );
+
+ virtual bool event ( QEvent* );
private:
//! width of window
GLViewer_Geom.h \
GLViewer_Grid.h \
GLViewer_Group.h \
- GLViewer_MimeSource.h \
+ GLViewer_MimeData.h \
GLViewer_Object.h \
GLViewer_Selector.h \
GLViewer_Selector2d.h \
GLViewer_Geom.cxx \
GLViewer_Grid.cxx \
GLViewer_Group.cxx \
- GLViewer_MimeSource.cxx \
+ GLViewer_MimeData.cxx \
GLViewer_Object.cxx \
GLViewer_Selector.cxx \
GLViewer_Selector2d.cxx \
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>ICON_GL_DUMP</source>
+ <translation>view_dump.png</translation>
+ </message>
+ <message>
+ <source>ICON_GL_ZOOM</source>
+ <translation>view_zoom.png</translation>
+ </message>
+ <message>
+ <source>ICON_GL_PAN</source>
+ <translation>view_pan.png</translation>
+ </message>
+ <message>
+ <source>ICON_GL_GLOBALPAN</source>
+ <translation>view_glpan.png</translation>
+ </message>
+ <message>
+ <source>ICON_GL_CURSOR_ROTATE</source>
+ <translation>cursor_rotate.png</translation>
+ </message>
+ <message>
+ <source>ICON_GL_CURSOR_SKETCH</source>
+ <translation>cursor_sketch.png</translation>
+ </message>
+ <message>
+ <source>ICON_GL_CURSOR_ZOOM</source>
+ <translation>cursor_zoom.png</translation>
+ </message>
+ <message>
+ <source>ICON_GL_FITALL</source>
+ <translation>view_fitall.png</translation>
+ </message>
+ <message>
+ <source>ICON_GL_FITSELECT</source>
+ <translation>view_fitselect.png</translation>
+ </message>
+ <message>
+ <source>ICON_GL_RESET</source>
+ <translation>view_reset.png</translation>
+ </message>
+ <message>
+ <source>ICON_GL_FITAREA</source>
+ <translation>view_fitarea.png</translation>
+ </message>
+</context>
+</TS>
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>DSC_FITSELECT</source>
+ <translation>Fit area of selection within the view frame</translation>
+ </message>
+ <message>
+ <source>ERROR</source>
+ <translation>Error</translation>
+ </message>
+ <message>
+ <source>MNU_DUMP_VIEW</source>
+ <translation>Dump</translation>
+ </message>
+ <message>
+ <source>MNU_PAN_VIEW</source>
+ <translation>Panning</translation>
+ </message>
+ <message>
+ <source>DSC_GLOBALPAN_VIEW</source>
+ <translation>Selection of a new center of the view</translation>
+ </message>
+ <message>
+ <source>MNU_ZOOM_VIEW</source>
+ <translation>Zoom</translation>
+ </message>
+ <message>
+ <source>DSC_PAN_VIEW</source>
+ <translation>Panning the view</translation>
+ </message>
+ <message>
+ <source>DSC_FITALL</source>
+ <translation>Fit all objects inside the view frame</translation>
+ </message>
+ <message>
+ <source>MNU_FITALL</source>
+ <translation>Fit All</translation>
+ </message>
+ <message>
+ <source>MNU_GLOBALPAN_VIEW</source>
+ <translation>Global Panning</translation>
+ </message>
+ <message>
+ <source>INF_APP_DUMP_VIEW</source>
+ <translation>Dump view</translation>
+ </message>
+ <message>
+ <source>GL_IMAGE_FILES</source>
+ <translation>Images Files (*.bmp *.png)</translation>
+ </message>
+ <message>
+ <source>MNU_RESET_VIEW</source>
+ <translation>Reset</translation>
+ </message>
+ <message>
+ <source>DSC_FITRECT</source>
+ <translation>Fit area within the view frame</translation>
+ </message>
+ <message>
+ <source>MNU_FITRECT</source>
+ <translation>Fit Area</translation>
+ </message>
+ <message>
+ <source>CHANGE_BGCOLOR</source>
+ <translation>Change background...</translation>
+ </message>
+ <message>
+ <source>DSC_DUMP_VIEW</source>
+ <translation>Saves the active view in the image file</translation>
+ </message>
+ <message>
+ <source>MNU_FITSELECT</source>
+ <translation>Fit Selection</translation>
+ </message>
+ <message>
+ <source>DSC_ZOOM_VIEW</source>
+ <translation>Zoom the view</translation>
+ </message>
+ <message>
+ <source>DSC_RESET_VIEW</source>
+ <translation>Reset View Point</translation>
+ </message>
+ <message>
+ <source>ERR_DOC_CANT_SAVE_FILE</source>
+ <translation>Cannot save file</translation>
+ </message>
+ <message>
+ <source>LBL_TOOLBAR_LABEL</source>
+ <translation>View Operations</translation>
+ </message>
+</context>
+<context>
+ <name>GLViewer_ViewFrame</name>
+ <message>
+ <source>DUMP_VIEW_SAVE_FILE_DLG_CAPTION</source>
+ <translation>Save Dump View in file</translation>
+ </message>
+ <message>
+ <source>DUMP_VIEW_ERROR_DLG_TEXT</source>
+ <translation>Can't save Dump View in file</translation>
+ </message>
+ <message>
+ <source>DUMP_VIEW_ERROR_DLG_CAPTION</source>
+ <translation>Error</translation>
+ </message>
+</context>
+<context>
+ <name>GLViewer_ViewManager</name>
+ <message>
+ <source>GL_VIEW_TITLE</source>
+ <translation>GL Scene:%M - viewer:%V</translation>
+ </message>
+</context>
+</TS>
// that uses this DLL. This way any other project whose source files include this file see
// LightApp_API functions as being imported from a DLL, wheras this DLL sees symbols
// defined with this macro as being exported.
-#ifdef WNT
+#ifdef WIN32
#ifdef LIGHTAPP_EXPORTS
#define LIGHTAPP_EXPORT __declspec(dllexport)
#else
#define LIGHTAPP_EXPORT
-#endif //WNT
+#endif //WIN32
#define APP_VERSION "0.1"
--- /dev/null
+TEMPLATE = lib
+TARGET = LightApp
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+PYTHON_INCLUDES = $$(PYTHONHOME)/include/python2.4
+
+QT_INCLUDES = $$(QTDIR)/include $$(QTDIR)/include/QtCore $$(QTDIR)/include/QtGui $$(QTDIR)/include/QtOpenGL $$(QTDIR)/include/QtXml
+
+CASROOT = $$(CASROOT)
+CAS_CPPFLAGS = $${CASROOT}/inc
+
+HDF5_INCLUDES = $$(HDF5HOME)/include
+
+KERNEL_CXXFLAGS = $$(KERNEL_ROOT_DIR)/include/salome
+
+VTK_INCLUDES = $$(VTKHOME)/include/vtk
+
+QWT_INCLUDES = $$(QWTHOME)/include
+
+PYTHON_INCLUDES = $$(PYTHONHOME)/include/python2.4
+
+INCLUDEPATH += $${PYTHON_INCLUDES} $${QT_INCLUDES} $${CAS_CPPFLAGS} $${HDF5_INCLUDES} $${KERNEL_CXXFLAGS} ../SUIT ../STD ../CAM ../LogWindow ../Prs ../Qtx ../Event #../ObjBrowser
+
+#if ENABLE_VTKVIEWER
+ INCLUDEPATH += $${VTK_INCLUDES} ../VTKViewer
+#else
+# DEFINES += DISABLE_VTKVIEWER
+#endif
+
+#if ENABLE_PLOT2DVIEWER
+ INCLUDEPATH += $${QWT_INCLUDES} ../Plot2d
+#else
+# DEFINES += DISABLE_PLOT2DVIEWER
+#endif
+
+#if ENABLE_OCCVIEWER
+ INCLUDEPATH += ../OCCViewer
+#else !ENABLE_OCCVIEWER
+# DEFINES += DISABLE_OCCVIEWER
+#endif
+
+#if ENABLE_PYCONSOLE
+ INCLUDEPATH += $${PYTHON_INCLUDES} ../PyConsole ../PyInterp
+#else !ENABLE_PYCONSOLE
+# DEFINES += DISABLE_PYCONSOLE
+#endif
+
+#if ENABLE_GLVIEWER
+ INCLUDEPATH += ../GLViewer
+#else !ENABLE_GLVIEWER
+# DEFINES += DISABLE_GLVIEWER
+#endif
+
+#if ENABLE_SUPERVGRAPHVIEWER
+ INCLUDEPATH += ../SUPERVGraph
+#else !ENABLE_SUPERVGRAPHVIEWER
+# DEFINES += DISABLE_SUPERVGRAPHVIEWER
+#endif
+
+#if ENABLE_SALOMEOBJECT
+
+ INCLUDEPATH += ../OBJECT
+#if ENABLE_PLOT2DVIEWER
+ INCLUDEPATH += ../SPlot2d
+#endif
+
+#if ENABLE_OCCVIEWER
+ INCLUDEPATH += ../SOCC
+#endif
+
+#if ENABLE_VTKVIEWER
+ INCLUDEPATH += ../SVTK
+#endif
+
+#else !ENABLE_SALOMEOBJECT
+# DEFINES += DISABLE_SALOMEOBJECT
+
+#endif
+
+QT_MT_LIBS = -L$$(QTDIR)/lib -lQtCore -lQtXml -lQtGui -lQtOpenGL
+
+CAS_KERNEL = -L$${CASROOT}/Linux/lib -lTKernel
+
+HDF5_LIBS = -L$$(HDF5HOME)/lib -lhdf5
+
+KERNEL_LDFLAGS = -L$$(KERNEL_ROOT_DIR)/lib/salome
+
+PYTHON_LIBS = -L$$(PYTHONHOME)/lib/python2.4/config -lpython2.4 -ldl -lutil
+
+LIBS += $${QT_MT_LIBS} -L../../lib -lsuit -lstd -lCAM -lLogWindow $${CAS_KERNEL} -lSalomePrs $${HDF5_LIBS} $${KERNEL_LDFLAGS} -lSalomeHDFPersist #-lObjBrowser
+
+#if ENABLE_PYCONSOLE
+ LIBS += $${PYTHON_LIBS}
+#endif
+
+#if ENABLE_SALOMEOBJECT
+ LIBS += -lSalomeObject
+#endif
+
+#if ENABLE_VTKVIEWER
+ LIBS += -lVTKViewer
+#if ENABLE_SALOMEOBJECT
+ LIBS += -lSVTK
+#endif
+#endif
+
+#if ENABLE_OCCVIEWER
+ LIBS += -lOCCViewer
+#if ENABLE_SALOMEOBJECT
+ LIBS += -lSOCC
+#endif
+#endif
+
+#if ENABLE_GLVIEWER
+ LIBS += -lGLViewer
+#endif
+
+#if ENABLE_PLOT2DVIEWER
+ LIBS += -lPlot2d
+#if ENABLE_SALOMEOBJECT
+ LIBS += -lSPlot2d
+#endif
+#endif
+
+#if ENABLE_PYCONSOLE
+ LIBS += -lPyInterp -lPyConsole
+#endif
+
+#if ENABLE_SUPERVGRAPHVIEWER
+ LIBS += -lSUPERVGraph
+#endif
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += LIGHTAPP_EXPORTS OCC_VERSION_MAJOR=6 OCC_VERSION_MINOR=1 OCC_VERSION_MAINTENANCE=1 LIN LINTEL CSFDB No_exception HAVE_CONFIG_H HAVE_LIMITS_H HAVE_WOK_CONFIG_H OCC_CONVERT_SIGNALS
+
+HEADERS = LightApp.h
+HEADERS += LightApp_AboutDlg.h
+HEADERS += LightApp_Application.h
+HEADERS += LightApp_DataModel.h
+HEADERS += LightApp_DataObject.h
+HEADERS += LightApp_DataOwner.h
+HEADERS += LightApp_DataSubOwner.h
+HEADERS += LightApp_Dialog.h
+HEADERS += LightApp_Displayer.h
+HEADERS += LightApp_Driver.h
+HEADERS += LightApp_EventFilter.h
+HEADERS += LightApp_HDFDriver.h
+HEADERS += LightApp_Module.h
+HEADERS += LightApp_ModuleAction.h
+HEADERS += LightApp_ModuleDlg.h
+HEADERS += LightApp_NameDlg.h
+#HEADERS += LightApp_OBFilter.h
+HEADERS += LightApp_OBSelector.h
+HEADERS += LightApp_Operation.h
+HEADERS += LightApp_Selection.h
+HEADERS += LightApp_SelectionMgr.h
+HEADERS += LightApp_ShowHideOp.h
+HEADERS += LightApp_Study.h
+HEADERS += LightApp_SwitchOp.h
+HEADERS += LightApp_Preferences.h
+HEADERS += LightApp_PreferencesDlg.h
+HEADERS += LightApp_RootObject.h
+HEADERS += LightApp_UpdateFlags.h
+HEADERS += LightApp_WidgetContainer.h
+
+#if ENABLE_VTKVIEWER
+#if ENABLE_SALOMEOBJECT
+ HEADERS += LightApp_VTKSelector.h
+#endif
+#endif
+#if ENABLE_OCCVIEWER
+ HEADERS += LightApp_OCCSelector.h
+#endif
+#if ENABLE_GLVIEWER
+ HEADERS += LightApp_GLSelector.h
+#endif
+
+SOURCES = LightApp_AboutDlg.cxx
+SOURCES += LightApp_Application.cxx
+SOURCES += LightApp_DataModel.cxx
+SOURCES += LightApp_DataObject.cxx
+SOURCES += LightApp_DataOwner.cxx
+SOURCES += LightApp_DataSubOwner.cxx
+SOURCES += LightApp_Dialog.cxx
+SOURCES += LightApp_Displayer.cxx
+SOURCES += LightApp_Driver.cxx
+SOURCES += LightApp_EventFilter.cxx
+SOURCES += LightApp_HDFDriver.cxx
+SOURCES += LightApp_Module.cxx
+SOURCES += LightApp_ModuleAction.cxx
+SOURCES += LightApp_ModuleDlg.cxx
+SOURCES += LightApp_NameDlg.cxx
+#SOURCES += LightApp_OBFilter.cxx
+SOURCES += LightApp_OBSelector.cxx
+SOURCES += LightApp_Operation.cxx
+SOURCES += LightApp_Selection.cxx
+SOURCES += LightApp_SelectionMgr.cxx
+SOURCES += LightApp_ShowHideOp.cxx
+SOURCES += LightApp_Study.cxx
+SOURCES += LightApp_SwitchOp.cxx
+SOURCES += LightApp_Preferences.cxx
+SOURCES += LightApp_PreferencesDlg.cxx
+SOURCES += LightApp_WidgetContainer.cxx
+
+#if ENABLE_VTKVIEWER
+#if ENABLE_SALOMEOBJECT
+ SOURCES += LightApp_VTKSelector.cxx
+#endif
+#endif
+#if ENABLE_OCCVIEWER
+ SOURCES += LightApp_OCCSelector.cxx
+#endif
+#if ENABLE_GLVIEWER
+ SOURCES += LightApp_GLSelector.cxx
+#endif
+
+TRANSLATIONS = resources/LightApp_images.ts \
+ resources/LightApp_msg_en.ts
+
+ICONS = resources/*.png
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+resources.files = $$ICONS resources/*.qm
+resources.path = ../../resources
+
+INSTALLS += includes resources
#include <SUIT_Session.h>
#include <SUIT_ResourceMgr.h>
-#include <qlabel.h>
-#include <qlayout.h>
-#include <qpixmap.h>
-#include <qgroupbox.h>
+#include <QtxGridBox.h>
+
+#include <QLabel>
+#include <QVBoxLayout>
+#include <QPixmap>
+#include <QIcon>
+#include <QGroupBox>
/*!Constructor.*/
LightApp_AboutDlg::LightApp_AboutDlg( const QString& defName, const QString& defVer, QWidget* parent )
-: QtxDialog( parent, "salome_about_dialog", true, false, None )
+: QtxDialog( parent, true, false, None )
{
+ setObjectName( "salome_about_dialog" );
+
SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
QPixmap ico = resMgr->loadPixmap( "LightApp", tr( "ICO_ABOUT" ), false );
if ( !ico.isNull() )
- setIcon( ico );
+ setWindowIcon( ico );
QPalette pal = palette();
- QColorGroup cg = pal.active();
- cg.setColor( QColorGroup::Foreground, Qt::darkBlue );
- cg.setColor( QColorGroup::Background, Qt::white );
- pal.setActive( cg ); pal.setInactive( cg ); pal.setDisabled( cg );
+
+ pal.setBrush( QPalette::Active, QPalette::WindowText, QBrush( Qt::darkBlue ) );
+ pal.setBrush( QPalette::Active, QPalette::Window, QBrush( Qt::white ) );
+
+ pal.setBrush( QPalette::Inactive, QPalette::WindowText, QBrush( Qt::darkBlue ) );
+ pal.setBrush( QPalette::Inactive, QPalette::Window, QBrush( Qt::white ) );
+
+ pal.setBrush( QPalette::Disabled, QPalette::WindowText, QBrush( Qt::darkBlue ) );
+ pal.setBrush( QPalette::Disabled, QPalette::Window, QBrush( Qt::white ) );
+
setPalette(pal);
QVBoxLayout* main = new QVBoxLayout( mainFrame() );
- QGroupBox* base = new QGroupBox( 1, Qt::Horizontal, "", mainFrame() );
- base->setFrameStyle( QFrame::NoFrame );
+ QtxGridBox* base = new QtxGridBox( 1, Qt::Horizontal, mainFrame(), 0, 0 );
base->setInsideMargin( 0 );
main->addWidget( base );
QString capText = tr( "ABOUT_CAPTION" );
if ( capText.contains( "%1" ) )
capText = capText.arg( defName );
- setCaption( capText );
+ setWindowTitle( capText );
setSizeGripEnabled( false );
}
if ( !lab )
return;
- bool vis = !lab->text().stripWhiteSpace().isEmpty() ||
+ bool vis = !lab->text().trimmed().isEmpty() ||
( lab->pixmap() && !lab->pixmap()->isNull() );
vis ? lab->show() : lab->hide();
}
// Copyright (C) CEA 2005
#ifndef DISABLE_PYCONSOLE
- #include "PythonConsole_PyInterp.h" // WARNING! This include must be the first!
- #include <PythonConsole_PyConsole.h>
+ #include <PyConsole_Interp.h> // WARNING! This include must be the first!
+ #include <PyConsole_Console.h>
#endif
#include "LightApp_Application.h"
#include "LightApp_PreferencesDlg.h"
#include "LightApp_ModuleDlg.h"
#include "LightApp_AboutDlg.h"
+#include "LightApp_ModuleAction.h"
-#include "LightApp_OBFilter.h"
+// temporary commented
+//#include "LightApp_OBFilter.h"
#include "LightApp_EventFilter.h"
#include "LightApp_SelectionMgr.h"
#include "LightApp_DataObject.h"
+#include <SALOME_Event.h>
+
#include <CAM_Module.h>
#include <CAM_DataModel.h>
#include <CAM_Study.h>
#include <SUIT_ResourceMgr.h>
#include <SUIT_Tools.h>
#include <SUIT_Accel.h>
+#include <SUIT_MessageBox.h>
#include <QtxMRUAction.h>
#include <QtxDockAction.h>
#include <QtxToolBar.h>
-#include <qprocess.h>
+#include <QProcess>
#include <LogWindow.h>
-#include <OB_Browser.h>
-#include <OB_ListView.h>
+// temporary commented
+//#include <OB_Browser.h>
+//#include <OB_ListView.h>
#ifndef DISABLE_GLVIEWER
#include <GLViewer_Viewer.h>
#include <QxGraph_ViewManager.h>
#endif
-#include <QtxWorkstack.h>
-
-#include <qdir.h>
-#include <qimage.h>
-#include <qstring.h>
-#include <qwidget.h>
-#include <qstringlist.h>
-#include <qfile.h>
-#include <qapplication.h>
-#include <qmap.h>
-#include <qstatusbar.h>
-#include <qthread.h>
-#include <qobjectlist.h>
-#include <qcombobox.h>
-#include <qinputdialog.h>
-#include <qmessagebox.h>
-#include <qfontdatabase.h>
+#include <QDir>
+#include <QImage>
+#include <QString>
+#include <QWidget>
+#include <QStringList>
+#include <QFile>
+#include <QApplication>
+#include <QMap>
+#include <QStatusBar>
+#include <QThread>
+#include <QObjectList>
+#include <QComboBox>
+#include <QInputDialog>
+#include <QFontDatabase>
+#include <QIcon>
+#include <QByteArray>
+#include <QMenu>
+
+using namespace Qt;
#define FIRST_HELP_ID 1000000
#ifndef DISABLE_SALOMEOBJECT
- #include "SALOME_InteractiveObject.hxx"
- #include "SALOME_ListIO.hxx"
+ #include <SALOME_InteractiveObject.hxx>
+ #include <SALOME_ListIO.hxx>
#endif
static const char* imageEmptyIcon[] = {
SUIT_ResourceMgr* aResMgr = SUIT_Session::session()->resourceMgr();
QPixmap aLogo = aResMgr->loadPixmap( "LightApp", tr( "APP_DEFAULT_ICO" ), false );
- desktop()->setIcon( aLogo );
+ desktop()->setWindowIcon( aLogo );
desktop()->setDockableMenuBar( true );
desktop()->setDockableStatusBar( false );
// base logo (salome itself)
- desktop()->addLogo( "_app_base", aResMgr->loadPixmap( "LightApp", tr( "APP_BASE_LOGO" ), false ) );
+ desktop()->logoInsert( "_app_base", aResMgr->loadPixmap( "LightApp", tr( "APP_BASE_LOGO" ), false ) );
// extra logo (salome-based application)
- desktop()->addLogo( "_app_extra", aResMgr->loadPixmap( "LightApp", tr( "APP_EXTRA_LOGO" ), false ) );
+ desktop()->logoInsert( "_app_extra", aResMgr->loadPixmap( "LightApp", tr( "APP_EXTRA_LOGO" ), false ) );
clearViewManagers();
if ( famdb.contains(f.family()) || !aResMgr->hasValue( "PyConsole", "additional_families" ) )
return;
- QStringList anAddFamilies = QStringList::split( ";", aResMgr->stringValue( "PyConsole", "additional_families" ) );
+ QStringList anAddFamilies = aResMgr->stringValue( "PyConsole", "additional_families" ).split( ";", QString::SkipEmptyParts );
QString aFamily;
for ( QStringList::Iterator it = anAddFamilies.begin(); it != anAddFamilies.end(); ++it )
{
/*!Start application.*/
void LightApp_Application::start()
{
- if ( desktop() )
- desktop()->loadGeometry( resourceMgr(), "desktop" );
-
+ if ( desktop() ) {
+ desktop()->retrieveGeometry( resourceMgr()->stringValue( "desktop", "geometry", "(800%)x(800%) (+400%) (+400%) :(full)" ) );
+ //desktop()->retrieveGeometry( SUIT_Session::session()->resourceMgr()->stringValue( "desktop", "state", "normal" ));
+ //desktop()->retrieveGeometry( SUIT_Session::session()->resourceMgr()->stringValue( "desktop", "pos_x", "center" ));
+ //desktop()->retrieveGeometry( SUIT_Session::session()->resourceMgr()->stringValue( "desktop", "pos_y", "center" ));
+ //desktop()->retrieveGeometry( SUIT_Session::session()->resourceMgr()->stringValue( "desktop", "widht", "800" ));
+ //desktop()->retrieveGeometry( SUIT_Session::session()->resourceMgr()->stringValue( "desktop", "height", "800" ));
+ }
+
CAM_Application::start();
- QAction* a = action( ViewWindowsId );
- if ( a && a->inherits( "QtxDockAction" ) )
- ((QtxDockAction*)a)->setAutoPlace( true );
-
updateWindows();
updateViewManagers();
putInfo( "" );
- desktop()->statusBar()->message( "" );
+ desktop()->statusBar()->showMessage( "" );
LightApp_EventFilter::Init();
}
path += QString( "bin/salome/VERSION" );
QFile vf( path );
- if ( vf.open( IO_ReadOnly ) )
+ if ( vf.open( QIODevice::ReadOnly ) )
{
- QString line;
- vf.readLine( line, 1024 );
+ QString line( vf.readLine( 1024 ) );
vf.close();
if ( !line.isEmpty() )
while ( !line.isEmpty() && line.at( line.length() - 1 ) == QChar( '\n' ) )
line.remove( line.length() - 1, 1 );
- int idx = line.findRev( ":" );
+ int idx = line.lastIndexOf( ":" );
if ( idx != -1 )
- _app_version = line.mid( idx + 1 ).stripWhiteSpace();
+ _app_version = line.mid( idx + 1 ).trimmed();
}
}
}
const QString& suffix,
const int accel )
{
- QAction* a = createAction( id, tr( QString( "NEW_WINDOW_%1" ).arg( suffix ) ), QIconSet(),
- tr( QString( "NEW_WINDOW_%1" ).arg( suffix ) ),
- tr( QString( "NEW_WINDOW_%1" ).arg( suffix ) ),
+ QAction* a = createAction( id, tr( QString( "NEW_WINDOW_%1" ).arg( suffix ).toLatin1().constData() ), QIcon(),
+ tr( QString( "NEW_WINDOW_%1" ).arg( suffix ).toLatin1().constData() ),
+ tr( QString( "NEW_WINDOW_%1" ).arg( suffix ).toLatin1().constData() ),
accel, desktop(), false, this, SLOT( onNewWindow() ) );
createMenu( a, parentId, -1 );
}
SUIT_ResourceMgr* resMgr = resourceMgr();
//! Preferences
- createAction( PreferencesId, tr( "TOT_DESK_PREFERENCES" ), QIconSet(),
+ createAction( PreferencesId, tr( "TOT_DESK_PREFERENCES" ), QIcon(),
tr( "MEN_DESK_PREFERENCES" ), tr( "PRP_DESK_PREFERENCES" ),
CTRL+Key_F, desk, false, this, SLOT( onPreferences() ) );
int id = LightApp_Application::UserID + FIRST_HELP_ID;
// help for KERNEL and GUI
- QCString dir;
+ QString dir;//QByteArray dir;
QString aFileName = "index.htm";
QString root;
QAction* a;
- if (dir = getenv("GUI_ROOT_DIR")) {
+ dir = getenv("GUI_ROOT_DIR");
+ if ( !dir.isEmpty() ) {
root = Qtx::addSlash( Qtx::addSlash(dir) + Qtx::addSlash("share") + Qtx::addSlash("doc") +
Qtx::addSlash("salome") + Qtx::addSlash("gui") + Qtx::addSlash("GUI") );
if ( QFileInfo( root + aFileName ).exists() ) {
- a = createAction( id, tr( QString("GUI Help") ), QIconSet(),
- tr( QString("GUI Help") ),
- tr( QString("GUI Help") ),
+ a = createAction( id, tr( QString("GUI Help").toLatin1().constData() ), QIcon(),
+ tr( QString("GUI Help").toLatin1().constData() ),
+ tr( QString("GUI Help").toLatin1().constData() ),
0, desk, false, this, SLOT( onHelpContentsModule() ) );
- a->setName( QString("GUI") );
+ a->setObjectName( QString("GUI") );
createMenu( a, helpModuleMenu, -1 );
id++;
}
}
- if (dir = getenv("KERNEL_ROOT_DIR")) {
+ dir = getenv("KERNEL_ROOT_DIR");
+ if ( !dir.isEmpty() ) {
QString aFN = "index.html";
root = Qtx::addSlash( Qtx::addSlash(dir) + Qtx::addSlash("share") + Qtx::addSlash("doc") +
Qtx::addSlash("salome") );
if ( QFileInfo( root + aFN ).exists() ) {
- a = createAction( id, tr( QString("KERNEL Help") ), QIconSet(),
- tr( QString("KERNEL Help") ),
- tr( QString("KERNEL Help") ),
+ a = createAction( id, tr( QString("KERNEL Help").toLatin1().constData() ), QIcon(),
+ tr( QString("KERNEL Help").toLatin1().constData() ),
+ tr( QString("KERNEL Help").toLatin1().constData() ),
0, desk, false, this, SLOT( onHelpContentsModule() ) );
- a->setName( QString("KERNEL") );
+ a->setObjectName( QString("KERNEL") );
createMenu( a, helpModuleMenu, -1 );
id++;
}
QString modName = moduleName( *it );
- if (dir = getenv( modName + "_ROOT_DIR")) {
+ dir = getenv( (modName + "_ROOT_DIR").toLatin1().constData() );
+ if ( !dir.isEmpty() ) {
root = Qtx::addSlash( Qtx::addSlash(dir) + Qtx::addSlash("share") + Qtx::addSlash("doc") +
Qtx::addSlash("salome") + Qtx::addSlash("gui") + Qtx::addSlash(modName) );
if ( QFileInfo( root + aFileName ).exists() ) {
- QAction* a = createAction( id, tr( moduleTitle(modName) + QString(" Help") ), QIconSet(),
- tr( moduleTitle(modName) + QString(" Help") ),
- tr( moduleTitle(modName) + QString(" Help") ),
+ QAction* a = createAction( id, tr( (moduleTitle(modName) + QString(" Help")).toLatin1().constData() ), QIcon(),
+ tr( (moduleTitle(modName) + QString(" Help")).toLatin1().constData() ),
+ tr( (moduleTitle(modName) + QString(" Help")).toLatin1().constData() ),
0, desk, false, this, SLOT( onHelpContentsModule() ) );
- a->setName( modName );
+ a->setObjectName( modName );
createMenu( a, helpModuleMenu, -1 );
id++;
}
if( modList.count()>1 )
{
QToolBar* modTBar = new QtxToolBar( true, desk );
- modTBar->setLabel( tr( "INF_TOOLBAR_MODULES" ) );
+ modTBar->setObjectName( "ModuleToolBar" );
+ modTBar->setWindowTitle( tr( "INF_TOOLBAR_MODULES" ) );
+ desktop()->addToolBar( Qt::TopToolBarArea, modTBar );
- QActionGroup* modGroup = new QActionGroup( this );
- modGroup->setExclusive( true );
- modGroup->setUsesDropDown( true );
-
- a = createAction( -1, tr( "APP_NAME" ), defIcon, tr( "APP_NAME" ),
- tr( "PRP_APP_MODULE" ), 0, desk, true );
- modGroup->add( a );
- myActions.insert( QString(), a );
+ myModuleAction = new LightApp_ModuleAction( tr( "APP_NAME" ), defIcon, desk );
QMap<QString, QString> iconMap;
moduleIconNames( iconMap );
const int iconSize = 20;
- modGroup->addTo( modTBar );
- QObjectList *l = modTBar->queryList( "QComboBox" );
- QObjectListIt oit( *l );
- while ( QObject* obj = oit.current() ) {
- QComboBox* cb = (QComboBox*)obj;
- if ( cb ) cb->setFocusPolicy( QWidget::NoFocus );
- ++oit;
- }
- delete l;
-
- modTBar->addSeparator();
-
for ( it = modList.begin(); it != modList.end(); ++it )
{
if ( !isLibExists( *it ) )
{
icon = modIcon;
printf( "****************************************************************\n" );
- printf( "* Icon for %s not found. Using the default one.\n", (*it).latin1() );
+ printf( "* Icon for %s not found. Using the default one.\n", (*it).toLatin1().constData() );
printf( "****************************************************************\n" );
}
- icon.convertFromImage( icon.convertToImage().smoothScale( iconSize, iconSize, QImage::ScaleMin ) );
-
- QAction* a = createAction( -1, *it, icon, *it, tr( "PRP_MODULE" ).arg( *it ), 0, desk, true );
- a->addTo( modTBar );
- modGroup->add( a );
-
- myActions.insert( *it, a );
+ icon.fromImage( icon.toImage().scaled( iconSize, iconSize, Qt::KeepAspectRatio, Qt::SmoothTransformation ) );
+
+ myModuleAction->insertModule( *it, icon );
}
- SUIT_Tools::simplifySeparators( modTBar );
- connect( modGroup, SIGNAL( selected( QAction* ) ), this, SLOT( onModuleActivation( QAction* ) ) );
+ connect( myModuleAction, SIGNAL( moduleActivated( const QString& ) ), this, SLOT( onModuleActivation( const QString& ) ) );
}
// New window
#endif
- createAction( RenameId, tr( "TOT_RENAME" ), QIconSet(), tr( "MEN_DESK_RENAME" ), tr( "PRP_RENAME" ),
+ createAction( RenameId, tr( "TOT_RENAME" ), QIcon(), tr( "MEN_DESK_RENAME" ), tr( "PRP_RENAME" ),
SHIFT+Key_R, desk, false, this, SLOT( onRenameWindow() ) );
createMenu( RenameId, windowMenu, -1 );
}
/*!On module activation action.*/
-void LightApp_Application::onModuleActivation( QAction* a )
+void LightApp_Application::onModuleActivation( const QString& modName )
{
- if ( !a )
- return;
-
- QString modName = a->menuText();
- if ( modName == tr( "APP_NAME" ) )
- modName = QString::null;
-
// Force user to create/open a study before module activation
QMap<QString, QString> iconMap;
moduleIconNames( iconMap );
case 0:
default:
putInfo( tr("INF_CANCELLED") );
- myActions[QString()]->setOn( true );
+ myModuleAction->setActiveModule( QString() );
cancelled = true;
}
}
}
}
-#include "SUIT_MessageBox.h"
-
/*!
SLOT: Opens new document.
\param aName - name of file
// Look among opened studies
if (activeStudy()) { // at least one study is opened
SUIT_Session* aSession = SUIT_Session::session();
- QPtrList<SUIT_Application> aAppList = aSession->applications();
- QPtrListIterator<SUIT_Application> it (aAppList);
+ QList<SUIT_Application*> aAppList = aSession->applications();
+ QListIterator<SUIT_Application*> it (aAppList);
SUIT_Application* aApp = 0;
// iterate on all applications
- for (; (aApp = it.current()) && !isAlreadyOpen; ++it) {
+ while ( it.hasNext() && !isAlreadyOpen ) {
+ if ( !(aApp = it.next()) ) break;
if (aApp->activeStudy()->studyName() == aName) {
isAlreadyOpen = true; // Already opened, ask user what to do
// The document ... is already open.
// Do you want to reload it?
- int aAnswer = SUIT_MessageBox::warn2(desktop(), tr("WRN_WARNING"),
- tr("QUE_DOC_ALREADYOPEN").arg(aName),
- tr("BUT_YES"), tr("BUT_NO"), 1, 2, 2);
- if (aAnswer == 1) { // reload
+ int aAnswer = SUIT_MessageBox::question(desktop(), tr("WRN_WARNING"),
+ tr("QUE_DOC_ALREADYOPEN").arg(aName),
+ SUIT_MessageBox::Yes | SUIT_MessageBox::No,
+ SUIT_MessageBox::No );
+ if (aAnswer == SUIT_MessageBox::Yes) { // reload
if (activeStudy()->studyName() == aName && aAppList.count() > 1) {
// Opened in THIS (active) application.
STD_Application* app1 = (STD_Application*)aAppList.at(0);
if ( !myApp.isEmpty())
{
- aCommand.sprintf("%s %s %s",myApp.latin1(),myParams.latin1(),myHelpFile.latin1());
+ aCommand.sprintf("%s %s %s",myApp.toLatin1().constData(),myParams.toLatin1().constData(),myHelpFile.toLatin1().constData());
QProcess* proc = new QProcess();
- proc->addArgument( aCommand );
//myStatus = system(aCommand);
//if(myStatus != 0)
- if(!proc->start())
+ proc->start(aCommand);
+ if (proc->waitForStarted())
{
- QCustomEvent* ce2000 = new QCustomEvent( 2000 );
+ SALOME_CustomEvent* ce2000 = new SALOME_CustomEvent( 2000 );
QString* msg = new QString( QObject::tr("EXTERNAL_BROWSER_CANNOT_SHOW_PAGE").arg(myApp).arg(myHelpFile) );
ce2000->setData( msg );
- postEvent( myLApp, ce2000 );
+ QApplication::postEvent( myLApp, ce2000 );
}
}
}
{
const QAction* obj = (QAction*) sender();
- QString aComponentName = obj->name();
+ QString aComponentName = obj->objectName();
QString aFileName = "index.htm";
QString aFileNameKernel = "index.html";
- QCString dir = getenv( aComponentName + "_ROOT_DIR");
+ QString dir = getenv( (aComponentName + "_ROOT_DIR").toLatin1().constData() );
QString homeDir = !aComponentName.compare(QString("KERNEL")) ?
Qtx::addSlash( Qtx::addSlash(dir) + Qtx::addSlash("share") + Qtx::addSlash("doc") + Qtx::addSlash("salome") ) :
Qtx::addSlash( Qtx::addSlash(dir) + Qtx::addSlash("share") + Qtx::addSlash("doc") + Qtx::addSlash("salome") + Qtx::addSlash("gui") + Qtx::addSlash(aComponentName) );
- QString helpFile = QFileInfo( homeDir + (!aComponentName.compare(QString("KERNEL")) ? aFileNameKernel : aFileName) ).absFilePath();
+ QString helpFile = QFileInfo( homeDir + (!aComponentName.compare(QString("KERNEL")) ? aFileNameKernel : aFileName) ).absoluteFilePath();
SUIT_ResourceMgr* resMgr = resourceMgr();
QString platform;
#ifdef WIN32
rs->start();
}
else {
- if( SUIT_MessageBox::warn2(desktop(), tr("WRN_WARNING"),
- tr("DEFINE_EXTERNAL_BROWSER"),
- tr("BUT_OK"),tr("BUT_CANCEL"),0,1,0 )==0 )
+ if( SUIT_MessageBox::question(desktop(), tr("WRN_WARNING"),
+ tr("DEFINE_EXTERNAL_BROWSER"),
+ SUIT_MessageBox::Yes | SUIT_MessageBox::No,
+ SUIT_MessageBox::Yes ) == SUIT_MessageBox::Yes )
onPreferences();
}
}
*/
void LightApp_Application::onHelpContextModule(const QString& theComponentName, const QString& theFileName)
{
- QCString dir = getenv( theComponentName + "_ROOT_DIR");
+ QString dir = getenv( (theComponentName + "_ROOT_DIR").toLatin1().constData() );
QString homeDir = Qtx::addSlash(Qtx::addSlash(dir)+Qtx::addSlash("share")+Qtx::addSlash("doc")+Qtx::addSlash("salome")+Qtx::addSlash("gui")+Qtx::addSlash(theComponentName));
- QString helpFile = QFileInfo( homeDir + theFileName ).absFilePath();
+ QString helpFile = QFileInfo( homeDir + theFileName ).absoluteFilePath();
SUIT_ResourceMgr* resMgr = resourceMgr();
QString platform;
#ifdef WIN32
rs->start();
}
else {
- if( SUIT_MessageBox::warn2(desktop(), tr("WRN_WARNING"),
- tr("DEFINE_EXTERNAL_BROWSER"),
- tr("BUT_OK"), tr("BUT_CANCEL"),0,1,0)==0 )
+ if( SUIT_MessageBox::question(desktop(), tr("WRN_WARNING"),
+ tr("DEFINE_EXTERNAL_BROWSER"),
+ SUIT_MessageBox::Yes | SUIT_MessageBox::No,
+ SUIT_MessageBox::Yes ) == SUIT_MessageBox::Yes )
onPreferences();
}
}
// asv: connecting a slot for storing visibility flag of a window
connect( newWC, SIGNAL( visibilityChanged ( bool ) ), SLOT( onVisibilityChanged( bool ) ) );
myWindows.insert( flag, newWC );
- if ( winMap.contains( flag ) )
- desktop()->moveDockWindow( myWindows[flag], (Dock)winMap[flag] );
-
- myWindows[flag]->setResizeEnabled( true );
- myWindows[flag]->setCloseMode( QDockWindow::Always );
- myWindows[flag]->setName( QString( "dock_window_%1" ).arg( flag ) );
- myWindows[flag]->setFixedExtentWidth( wid->width() );
- myWindows[flag]->setFixedExtentHeight( wid->height() );
+ if ( winMap.contains( flag ) ) {
+ desktop()->removeDockWidget( myWindows[flag] );
+ desktop()->addDockWidget( (DockWidgetArea)winMap[flag], myWindows[flag] );
+ }
+
+ //myWindows[flag]->setResizeEnabled( true );
+ myWindows[flag]->setFeatures( QDockWidget::DockWidgetClosable );
+ myWindows[flag]->setObjectName( QString( "dock_window_%1" ).arg( flag ) );
+ //myWindows[flag]->setFixedExtentWidth( wid->width() );
+ //myWindows[flag]->setFixedExtentHeight( wid->height() );
+ myWindows[flag]->resize( wid->width(), wid->height() );
}
QFont f;
#ifndef DISABLE_PYCONSOLE
- if( wid->inherits( "PythonConsole" ) )
+ if( wid->inherits( "PyConsole_Console" ) )
{
if( resourceMgr()->hasValue( "PyConsole", "font" ) )
f = resourceMgr()->fontValue( "PyConsole", "font" );
else
{
- f = ( ( PythonConsole* )wid )->font();
+ f = ( ( PyConsole_Console* )wid )->font();
resourceMgr()->setValue( "PyConsole", "font", f );
}
}
bool res = false;
if ( myWindows.contains( type ) )
{
- SUIT_Desktop* desk = ((LightApp_Application*)this)->desktop();
- res = desk && desk->appropriate( myWindows[type] );
+ //SUIT_Desktop* desk = ((LightApp_Application*)this)->desktop();
+ //res = desk && desk->appropriate( myWindows[type] );
+ res = myWindows[type]->isVisible();
}
return res;
}
if ( !desktop() || !myWindows.contains( type ) )
return;
- QDockWindow* dw = myWindows[type];
- desktop()->setAppropriate( dw, on );
+ QDockWidget* dw = myWindows[type];
+ //desktop()->setAppropriate( dw, on );
if( on )
dw->show();
- else if( dw->isShown() )
+ else if( dw->isVisible() )
{
dw->hide();
myWindowsVisible[ type ] = true;
/*!
\return Object Browser
*/
-OB_Browser* LightApp_Application::objectBrowser()
+// temporary commented
+/*OB_Browser* LightApp_Application::objectBrowser()
{
OB_Browser* ob = 0;
QWidget* wid = window( WT_ObjectBrowser );
if ( wid && wid->inherits( "OB_Browser" ) )
ob = (OB_Browser*)wid;
return ob;
-}
+}*/
/*!
\return Log Window
/*!
\return Python Console
*/
-PythonConsole* LightApp_Application::pythonConsole()
+PyConsole_Console* LightApp_Application::pythonConsole()
{
- PythonConsole* console = 0;
+ PyConsole_Console* console = 0;
QWidget* wid = getWindow( WT_PyConsole );
- if ( wid->inherits( "PythonConsole" ) )
- console = (PythonConsole*)wid;
+ if ( wid->inherits( "PyConsole_Console" ) )
+ console = (PyConsole_Console*)wid;
return console;
}
#endif
// update existing data models
if ( updateModels )
{
- const bool isAutoUpdate = objectBrowser() ? objectBrowser()->isAutoUpdate() : true;
+ // temporary commented
+ /*const bool isAutoUpdate = objectBrowser() ? objectBrowser()->isAutoUpdate() : true;
if( objectBrowser() )
- objectBrowser()->setAutoUpdate( false );
+ objectBrowser()->setAutoUpdate( false );*/
LightApp_Study* study = dynamic_cast<LightApp_Study*>(activeStudy());
if ( study ) {
CAM_Study::ModelList dm_list;
study->dataModels( dm_list );
- for ( CAM_Study::ModelListIterator it( dm_list ); it.current(); ++it ) {
- CAM_DataModel* camDM = it.current();
+ QListIterator<CAM_DataModel*> it( dm_list );
+ while ( it.hasNext() ) {
+ CAM_DataModel* camDM = it.next();
if ( camDM && camDM->inherits( "LightApp_DataModel" ) )
((LightApp_DataModel*)camDM)->update();
}
}
- if( objectBrowser() )
- objectBrowser()->setAutoUpdate( isAutoUpdate );
+ // temporary commented
+ /*if( objectBrowser() )
+ objectBrowser()->setAutoUpdate( isAutoUpdate );*/
}
- if ( objectBrowser() )
+ // temporary commented
+ /*if ( objectBrowser() )
{
objectBrowser()->updateGeometry();
objectBrowser()->updateTree( 0, false );
- }
+ }*/
}
/*!
//aRoot->setName( tr( "DATA_MODELS" ) );
}
getWindow( WT_ObjectBrowser );
- if ( objectBrowser() != 0 )
- objectBrowser()->setRootObject( aRoot );
+ // temporary commented
+ /*if ( objectBrowser() != 0 )
+ objectBrowser()->setRootObject( aRoot );*/
activateModule( defaultModule() );
- if ( objectBrowser() )
- objectBrowser()->openLevels();
+ // temporary commented
+ /*if ( objectBrowser() )
+ objectBrowser()->openLevels();*/
activateWindows();
}
//aRoot->dump();
}
getWindow( WT_ObjectBrowser );
- if ( objectBrowser() )
- objectBrowser()->setRootObject( aRoot );
+ // temporary commented
+ /*if ( objectBrowser() )
+ objectBrowser()->setRootObject( aRoot );*/
activateModule( defaultModule() );
- if ( objectBrowser() )
- objectBrowser()->openLevels();
+ // temporary commented
+ /*if ( objectBrowser() )
+ objectBrowser()->openLevels();*/
activateWindows();
{
if ( !parent )
parent = desktop();
- QStringList fls = QStringList::split( ";;", filters, false );
+ QStringList fls = filters.split( ";;", QString::SkipEmptyParts );
return SUIT_FileDlg::getFileName( parent, initial, fls, caption, open, true );
}
{
if ( !parent )
parent = desktop();
- QStringList fls = QStringList::split( ";;", filters, false );
+ QStringList fls = filters.split( ";;", QString::SkipEmptyParts );
return SUIT_FileDlg::getOpenFileNames( parent, initial, fls, caption, true );
}
/*!Private SLOT. On preferences.*/
void LightApp_Application::onPreferences()
{
- QApplication::setOverrideCursor( Qt::waitCursor );
+ QApplication::setOverrideCursor( Qt::WaitCursor );
LightApp_PreferencesDlg* prefDlg = new LightApp_PreferencesDlg( preferences( true ), desktop());
if ( ( prefDlg->exec() == QDialog::Accepted || prefDlg->isSaved() ) && resourceMgr() ) {
if ( desktop() )
- desktop()->saveGeometry( resourceMgr(), "desktop" );
+ resourceMgr()->setValue( "desktop", "geometry", desktop()->storeGeometry() );
resourceMgr()->save();
}
QWidget* wid = 0;
if ( flag == WT_ObjectBrowser )
{
- OB_Browser* ob = new OB_Browser( desktop() );
+ // temporary commented
+ /*OB_Browser* ob = new OB_Browser( desktop() );
ob->setAutoUpdate( true );
//ob->setAutoOpenLevel( 1 ); // commented by ASV as a fix to bug IPAL10107
ob->setCaption( tr( "OBJECT_BROWSER" ) );
wid = ob;
ob->connectPopupRequest( this, SLOT( onConnectPopupRequest( SUIT_PopupClient*, QContextMenuEvent* ) ) );
+ */
}
#ifndef DISABLE_PYCONSOLE
else if ( flag == WT_PyConsole )
{
- PythonConsole* pyCons = new PythonConsole( desktop() );
- pyCons->setCaption( tr( "PYTHON_CONSOLE" ) );
+ PyConsole_Console* pyCons = new PyConsole_Console( desktop() );
+ pyCons->setWindowTitle( tr( "PYTHON_CONSOLE" ) );
wid = pyCons;
// pyCons->connectPopupRequest( this, SLOT( onConnectPopupRequest( SUIT_PopupClient*, QContextMenuEvent* ) ) );
}
else if ( flag == WT_LogWindow )
{
LogWindow* logWin = new LogWindow( desktop() );
- logWin->setCaption( tr( "LOG_WINDOW" ) );
+ logWin->setWindowTitle( tr( "LOG_WINDOW" ) );
wid = logWin;
logWin->connectPopupRequest( this, SLOT( onConnectPopupRequest( SUIT_PopupClient*, QContextMenuEvent* ) ) );
}
*/
void LightApp_Application::defaultWindows( QMap<int, int>& aMap ) const
{
- aMap.insert( WT_ObjectBrowser, Qt::DockLeft );
+ aMap.insert( WT_ObjectBrowser, Qt::LeftDockWidgetArea );
#ifndef DISABLE_PYCONSOLE
- aMap.insert( WT_PyConsole, Qt::DockBottom );
+ aMap.insert( WT_PyConsole, Qt::BottomDockWidgetArea );
#endif
// aMap.insert( WT_LogWindow, Qt::DockBottom );
}
that->myPrefs = _prefs_;
- QPtrList<SUIT_Application> appList = SUIT_Session::session()->applications();
- for ( QPtrListIterator<SUIT_Application> appIt ( appList ); appIt.current(); ++appIt )
+ QList<SUIT_Application*> appList = SUIT_Session::session()->applications();
+ QListIterator<SUIT_Application*> appIt ( appList );
+ while ( appIt.hasNext() )
{
- if ( !appIt.current()->inherits( "LightApp_Application" ) )
+ SUIT_Application* anItem = appIt.next();
+ if ( !anItem->inherits( "LightApp_Application" ) )
continue;
- LightApp_Application* app = (LightApp_Application*)appIt.current();
+ LightApp_Application* app = (LightApp_Application*)anItem;
QStringList modNameList;
app->modules( modNameList, false );
ModuleList modList;
app->modules( modList );
- for ( ModuleListIterator itr( modList ); itr.current(); ++itr )
+ QListIterator<CAM_Module*> itr( modList );
+ while ( itr.hasNext() )
{
LightApp_Module* mod = 0;
- if ( itr.current()->inherits( "LightApp_Module" ) )
- mod = (LightApp_Module*)itr.current();
+
+ CAM_Module* anItem = itr.next();
+ if ( anItem->inherits( "LightApp_Module" ) )
+ mod = (LightApp_Module*)anItem;
if ( mod && !_prefs_->hasModule( mod->moduleName() ) )
{
int modCat = _prefs_->addPreference( mod->moduleName() );
- _prefs_->setItemProperty( modCat, "info", QString::null );
+ _prefs_->setItemProperty( modCat, "info", QString() );
if( toCreate )
mod->createPreferences();
}
if ( myPrefs && lightMod && !myPrefs->hasModule( lightMod->moduleName() ))
{
int modCat = myPrefs->addPreference( mod->moduleName() );
- myPrefs->setItemProperty( modCat, "info", QString::null );
+ myPrefs->setItemProperty( modCat, "info", QString() );
lightMod->createPreferences();
}
}
#endif
int apppref = pref->addPreference( tr( "PREF_APP" ), extgroup, LightApp_Preferences::File, "ExternalBrowser", platform );
pref->setItemProperty( apppref, "existing", true );
- pref->setItemProperty( apppref, "flags", QFileInfo::ExeUser );
+ pref->setItemProperty( apppref, "flags", QFile::ExeUser );
pref->setItemProperty( apppref, "readOnly", false );
pref->addPreference( tr( "PREF_PARAM" ), extgroup, LightApp_Preferences::String, "ExternalBrowser", "parameters" );
aLegendPosList.append( tr("PREF_TOP") );
aLegendPosList.append( tr("PREF_BOTTOM") );
- QValueList<QVariant> anIndexesList;
+ QList<QVariant> anIndexesList;
anIndexesList.append(0);
anIndexesList.append(1);
anIndexesList.append(2);
if ( sec == QString( "OCCViewer" ) && param == QString( "trihedron_size" ) )
{
double sz = resMgr->doubleValue( sec, param, -1 );
- QPtrList<SUIT_ViewManager> lst;
+ QList<SUIT_ViewManager*> lst;
viewManagers( OCCViewer_Viewer::Type(), lst );
- for ( QPtrListIterator<SUIT_ViewManager> it( lst ); it.current() && sz >= 0; ++it )
+ QListIterator<SUIT_ViewManager*> it( lst );
+ while ( it.hasNext() && sz >= 0 )
{
- SUIT_ViewModel* vm = it.current()->getViewModel();
+ SUIT_ViewModel* vm = it.next()->getViewModel();
if ( !vm || !vm->inherits( "OCCViewer_Viewer" ) )
continue;
{
double sz = resMgr->doubleValue( "VTKViewer", "trihedron_size", -1 );
bool isRelative = resMgr->booleanValue( "VTKViewer", "relative_size", true );
- QPtrList<SUIT_ViewManager> lst;
+ QList<SUIT_ViewManager*> lst;
#ifndef DISABLE_SALOMEOBJECT
viewManagers( SVTK_Viewer::Type(), lst );
- for ( QPtrListIterator<SUIT_ViewManager> it( lst ); it.current() && sz >= 0; ++it )
+ QListIterator<SUIT_ViewManager*> it( lst );
+ while ( it.hasNext() && sz >= 0 )
{
- SUIT_ViewModel* vm = it.current()->getViewModel();
+ SUIT_ViewModel* vm = it.next()->getViewModel();
if ( !vm || !vm->inherits( "SVTK_Viewer" ) )
continue;
#ifndef DISABLE_OCCVIEWER
if ( sec == QString( "OCCViewer" ) && ( param == QString( "iso_number_u" ) || param == QString( "iso_number_v" ) ) )
{
- QPtrList<SUIT_ViewManager> lst;
+ QList<SUIT_ViewManager*> lst;
viewManagers( OCCViewer_Viewer::Type(), lst );
int u = resMgr->integerValue( sec, "iso_number_u" );
int v = resMgr->integerValue( sec, "iso_number_v" );
- for ( QPtrListIterator<SUIT_ViewManager> it( lst ); it.current(); ++it )
+ QListIterator<SUIT_ViewManager*> it( lst );
+ while ( it.hasNext() )
{
- OCCViewer_ViewManager* mgr = dynamic_cast<OCCViewer_ViewManager*>( it.current() );
+ OCCViewer_ViewManager* mgr = dynamic_cast<OCCViewer_ViewManager*>( it.next() );
if( mgr && mgr->getOCCViewer() )
mgr->getOCCViewer()->setIsos( u, v );
}
{
if( param=="auto_size" || param=="auto_size_first" )
{
- OB_Browser* ob = objectBrowser();
+ // temporary commented
+ /*OB_Browser* ob = objectBrowser();
if( !ob )
return;
for( int i=1; i<ob->listView()->columns(); i++ )
if( ob->listView()->columnWidth( i )>0 )
ob->listView()->adjustColumn( i );
- updateObjectBrowser( false );
+ updateObjectBrowser( false );*/
}
}
if ( resourceMgr() )
{
if ( desktop() )
- desktop()->saveGeometry( resourceMgr(), "desktop" );
+ resourceMgr()->setValue( "desktop", "geometry", desktop()->storeGeometry() );
resourceMgr()->save();
}
}
aTitle += QString( " " ) + aVer;
if ( activeStudy() ) {
- QString sName = SUIT_Tools::file( activeStudy()->studyName().stripWhiteSpace(), false );
+ QString sName = SUIT_Tools::file( activeStudy()->studyName().trimmed(), false );
aTitle += QString( " - [%1]" ).arg( sName );
}
- desktop()->setCaption( aTitle );
+ desktop()->setWindowTitle( aTitle );
}
/*!
if ( activeModule() )
modName = activeModule()->moduleName();
- if ( myActions.contains( modName ) )
- myActions[modName]->setOn( true );
+ myModuleAction->setActiveModule( modName );
}
/*!
for ( QMap<int, int>::ConstIterator it = winMap.begin(); it != winMap.end(); ++it ) {
getWindow( it.key() );
- Dock dock; int index, extraOffset; bool nl;
- if ( desktop()->getLocation( myWindows[it.key()], dock, index, nl, extraOffset )
+ DockWidgetArea dock = desktop()->dockWidgetArea( myWindows[it.key()] );
+ if ( dock != NoDockWidgetArea
&&
- dock != (Dock)it.data() )
- desktop()->moveDockWindow( myWindows[it.key()], (Dock)it.data() );
+ dock != (DockWidgetArea)it.value() ) {
+ desktop()->removeDockWidget( myWindows[it.key()] );
+ desktop()->addDockWidget( (DockWidgetArea)it.value(), myWindows[it.key()] );
+ }
}
loadWindowsGeometry();
!myWindowsVisible[ itr.key() ] )
continue;
- setWindowShown( itr.key(), !itr.data()->isEmpty() && winMap.contains( itr.key() ) );
+ setWindowShown( itr.key(), !itr.value()->isEmpty() && winMap.contains( itr.key() ) );
}
}
if( !store )
return;
- QtxDockAction* dockMgr = 0;
-
- QAction* a = action( ViewWindowsId );
- if ( a && a->inherits( "QtxDockAction" ) )
- dockMgr = (QtxDockAction*)a;
-
- if ( !dockMgr )
- return;
-
QString modName;
if ( activeModule() )
- modName = activeModule()->name("");
-
- QString section = QString( "windows_geometry" );
- if ( !modName.isEmpty() )
- section += QString( "." ) + modName;
+ modName = activeModule()->objectName();
- dockMgr->loadGeometry( resourceMgr(), section, false );
- dockMgr->restoreGeometry();
+ desktop()->restoreState( resourceMgr()->stringValue( "windows_geometry", modName ).toLatin1() );
}
/*!
if( !store )
return;
- QtxDockAction* dockMgr = 0;
-
- QAction* a = action( ViewWindowsId );
- if ( a && a->inherits( "QtxDockAction" ) )
- dockMgr = (QtxDockAction*)a;
-
- if ( !dockMgr )
- return;
-
QString modName;
if ( activeModule() )
- modName = activeModule()->name("");
+ modName = activeModule()->objectName();
- QString section = QString( "windows_geometry" );
- if ( !modName.isEmpty() )
- section += QString( "." ) + modName;
-
- dockMgr->storeGeometry();
- dockMgr->saveGeometry( resourceMgr(), section, false );
+ resourceMgr()->setValue( "windows_geometry", modName, desktop()->saveState() );
}
/*!
if ( activeStudy() )
{
for ( WindowMap::Iterator itr = myWindows.begin(); itr != myWindows.end(); ++itr )
- itr.data()->activate( activeStudy()->id() );
+ itr.value()->activate( activeStudy()->id() );
}
}
/*!
Inserts items in popup, which necessary for current application
*/
-void LightApp_Application::contextMenuPopup( const QString& type, QPopupMenu* thePopup, QString& title )
+void LightApp_Application::contextMenuPopup( const QString& type, QMenu* thePopup, QString& title )
{
CAM_Application::contextMenuPopup( type, thePopup, title );
- OB_Browser* ob = objectBrowser();
+ // temporary commented
+ /*OB_Browser* ob = objectBrowser();
if ( !ob || type != ob->popupClientType() )
- return;
+ return;*/
- thePopup->insertSeparator();
- thePopup->insertItem( tr( "MEN_REFRESH" ), this, SLOT( onRefresh() ) );
+ thePopup->addSeparator();
+ thePopup->addAction( tr( "MEN_REFRESH" ), this, SLOT( onRefresh() ) );
}
/*!
void LightApp_Application::createEmptyStudy()
{
CAM_Application::createEmptyStudy();
- if ( objectBrowser() )
- objectBrowser()->updateTree();
+ // temporary commented
+ /*if ( objectBrowser() )
+ objectBrowser()->updateTree();*/
}
/*!
bool LightApp_Application::activateModule( CAM_Module* mod )
{
bool res = CAM_Application::activateModule( mod );
- if ( objectBrowser() )
- objectBrowser()->updateTree();
+ // temporary commented
+ /*if ( objectBrowser() )
+ objectBrowser()->updateTree();*/
return res;
}
// remove destroyed widget container from windows map
for ( WindowMap::ConstIterator itr = myWindows.begin(); itr != myWindows.end(); ++itr )
{
- if ( itr.data() != ob )
+ if ( itr.value() != ob )
continue;
int key = itr.key();
return;
bool ok;
- QString name = QInputDialog::getText( tr( "TOT_RENAME" ), tr( "PRP_RENAME" ), QLineEdit::Normal, w->caption(), &ok, w );
+ QString name = QInputDialog::getText( w, tr( "TOT_RENAME" ), tr( "PRP_RENAME" ), QLineEdit::Normal, w->windowTitle(), &ok );
if( ok && !name.isEmpty() )
- w->setCaption( name );
+ w->setWindowTitle( name );
}
/*!
QStringList paths;
#ifdef WIN32
- paths = QStringList::split( ";", ::getenv( "PATH" ) );
+ paths = QString(::getenv( "PATH" )).split( ";", QString::SkipEmptyParts );
#else
- paths = QStringList::split( ":", ::getenv( "LD_LIBRARY_PATH" ) );
+ paths = QString(::getenv( "LD_LIBRARY_PATH" )).split( ":", QString::SkipEmptyParts );
#endif
bool isLibFound = false;
if ( !isLibFound )
{
printf( "****************************************************************\n" );
- printf( "* Warning: library %s cannot be found\n", moduleTitle.latin1() );
+ printf( "* Warning: library %s cannot be found\n", moduleTitle.toLatin1().constData() );
printf( "* Module will not be available\n" );
printf( "****************************************************************\n" );
}
// Check the python library
#ifdef WIN32
- paths = QStringList::split( ";", ::getenv( "PATH" ) );
+ paths = QString(::getenv( "PATH" )).split( ";", QString::SkipEmptyParts );
#else
- paths = QStringList::split( ":", ::getenv( "PYTHONPATH" ) );
+ paths = QString(::getenv( "PYTHONPATH" )).split( ":", QString::SkipEmptyParts );
#endif
bool isPyLib = false, isPyGuiLib = false;
QStringList::const_iterator anIt = paths.begin(), aLast = paths.end();
}
printf( "****************************************************************\n" );
- printf( "* Warning: python library for %s cannot be found:\n", moduleTitle.latin1() );
+ printf( "* Warning: python library for %s cannot be found:\n", moduleTitle.toLatin1().constData() );
if (!isPyLib)
- printf( "* No module named %s\n", moduleName( moduleTitle ).latin1() );
+ printf( "* No module named %s\n", moduleName( moduleTitle ).toLatin1().constData() );
if (!isPyGuiLib)
- printf( "* No module named %s\n", (moduleName( moduleTitle ) + QString("GUI")).latin1() );
+ printf( "* No module named %s\n", (moduleName( moduleTitle ) + QString("GUI")).toLatin1().constData() );
printf( "****************************************************************\n" );
return true;
}
const QObject* win = sender();
for ( WindowMap::ConstIterator itr = myWindows.begin(); itr != myWindows.end(); ++itr )
- if ( itr.data() == win )
+ if ( itr.value() == win )
{
myWindowsVisible[ itr.key() ] = visible;
return;
{
if( e && e->type()==2000 )
{
- QCustomEvent* ce = ( QCustomEvent* )e;
+ SALOME_CustomEvent* ce = ( SALOME_CustomEvent* )e;
QString* d = ( QString* )ce->data();
- if( SUIT_MessageBox::warn2(0, tr("WRN_WARNING"),
- d ? *d : "",
- tr("BUT_OK"), tr("BUT_CANCEL"), 0, 1, 0 )==0 )
+ if( SUIT_MessageBox::question(0, tr("WRN_WARNING"),
+ d ? *d : "",
+ SUIT_MessageBox::Yes | SUIT_MessageBox::No,
+ SUIT_MessageBox::Yes ) == SUIT_MessageBox::Yes )
onPreferences();
if( d )
delete d;
#include <CAM_Application.h>
class LogWindow;
-class OB_Browser;
+//class OB_Browser;
#ifndef DISABLE_PYCONSOLE
- class PythonConsole;
+ class PyConsole_Console;
#endif
-class STD_Application;
+//class STD_Application;
class LightApp_WidgetContainer;
class LightApp_Preferences;
class LightApp_SelectionMgr;
class LightApp_DataObject;
+class LightApp_ModuleAction;
class SUIT_Study;
class SUIT_Accel;
class CAM_Module;
class QString;
class QWidget;
class QStringList;
-class QPixmap;
+//class QPixmap;
#ifdef WIN32
#pragma warning( disable:4251 )
LightApp_SelectionMgr* selectionMgr() const;
LogWindow* logWindow();
- OB_Browser* objectBrowser();
+ //OB_Browser* objectBrowser();
#ifndef DISABLE_PYCONSOLE
- PythonConsole* pythonConsole();
+ PyConsole_Console* pythonConsole();
#endif
virtual void updateObjectBrowser( const bool = true );
virtual void start();
- virtual void contextMenuPopup( const QString&, QPopupMenu*, QString& );
+ virtual void contextMenuPopup( const QString&, QMenu*, QString& );
virtual void createEmptyStudy();
virtual void onDesktopActivated();
void onNewWindow();
- void onModuleActivation( QAction* );
+ void onModuleActivation( const QString& );
void onCloseView( SUIT_ViewManager* );
void onStudyCreated( SUIT_Study* );
bool isLibExists( const QString& ) const;
protected:
- typedef QMap<QString, QAction*> ActionMap;
typedef QMap<int, LightApp_WidgetContainer*> WindowMap;
typedef QMap<int, bool> WindowVisibilityMap;
protected:
LightApp_Preferences* myPrefs;
LightApp_SelectionMgr* mySelMgr;
- ActionMap myActions;
+ LightApp_ModuleAction* myModuleAction;
WindowMap myWindows;
WindowVisibilityMap myWindowsVisible;
#include "LightApp_Module.h"
#include "LightApp_Application.h"
-#include <OB_Browser.h>
+// temporary commented
+//#include <OB_Browser.h>
-#include <SUIT_Application.h>
-#include <SUIT_ResourceMgr.h>
-#include <SUIT_Session.h>
#include <SUIT_DataObject.h>
/*!
void LightApp_DataModel::updateWidgets()
{
LightApp_Application* app = dynamic_cast<LightApp_Application*>( module()->application() );
- if( app )
- app->objectBrowser()->updateTree( 0, false );
+ // temporary commented
+ /*if( app )
+ app->objectBrowser()->updateTree( 0, false );*/
}
/*!
if( modelRoot )
{
ch = modelRoot->children();
- for ( DataObjectListIterator it( ch ); it.current(); ++it )
- it.current()->setParent( 0 );
+ QListIterator<SUIT_DataObject*> it( ch );
+ while ( it.hasNext() )
+ it.next()->setParent( 0 );
}
build();
if( modelRoot )
{
DataObjectList new_ch = modelRoot->children();
- for ( DataObjectListIterator it1( new_ch ); it1.current(); ++it1 )
- aMap.insert( it1.current(), 0 );
+ QListIterator<SUIT_DataObject*> it1( new_ch );
+ while ( it1.hasNext() )
+ aMap.insert( it1.next(), 0 );
}
updateWidgets();
- for( DataObjectListIterator it( ch ); it.current(); ++it )
- if( !aMap.contains( it.current() ) )
- delete it.current();
+ QListIterator<SUIT_DataObject*> it( ch );
+ while ( it.hasNext() ) {
+ SUIT_DataObject* aDO = it.next();
+ if( !aMap.contains( aDO ) )
+ delete aDO;
+ }
}
/*!
#include "CAM_DataModel.h"
#include "CAM_Module.h"
-#include <SUIT_Application.h>
-#include <SUIT_ResourceMgr.h>
#include <SUIT_DataObjectKey.h>
-#include <qobject.h>
-
/*!
Class: LightApp_DataObject::Key
Level: Internal
#include "LightApp.h"
#include "CAM_DataObject.h"
-#include "CAM_DataModel.h"
#include "CAM_RootObject.h"
+class CAM_DataModel;
+
class LightApp_Study;
/*!Description : Data Object has empty entry so it's children must redefine metod entry() and return some unique string*/
#include "LightApp_DataOwner.h"
-#include "LightApp_DataObject.h"
-
-#include <iostream>
-
/*!Constructor. Initialize by \a theEntry.*/
LightApp_DataOwner::LightApp_DataOwner( const QString& theEntry )
: myEntry( theEntry )
//
#include "LightApp_DataSubOwner.h"
-#include "LightApp_DataObject.h"
-
/*!Constructor.Initialize by \a entry and \a index*/
LightApp_DataSubOwner::LightApp_DataSubOwner( const QString& entry, const int index )
: LightApp_DataOwner( entry ),
#include <LightApp_Dialog.h>
#include <SUIT_Session.h>
+#include <SUIT_ResourceMgr.h>
-#include <qtoolbutton.h>
-#include <qlineedit.h>
-#include <qlabel.h>
+#include <QAbstractButton>
+#include <QToolButton>
+#include <QLineEdit>
+#include <QLabel>
/*!
Constructor
*/
LightApp_Dialog::LightApp_Dialog( QWidget* parent, const char* name, bool modal,
- bool allowResize, const int f, WFlags wf )
-: QtxDialog( parent, name, modal, allowResize, f, wf ),
+ bool allowResize, const int f, Qt::WindowFlags wf )
+: QtxDialog( parent, modal, allowResize, f, wf ),
myIsExclusive( true ),
myIsBusy( false )
{
+ setObjectName( name );
setObjectPixmap( "LightApp", tr( "ICON_SELECT" ) );
}
aLast = myObjects.end();
for( ; anIt!=aLast; anIt++ )
{
- QToolButton* but = (QToolButton*)anIt.data().myBtn;
- if( but && but->isOn() )
+ QToolButton* but = (QToolButton*)anIt.value().myBtn;
+ if( but && but->isChecked() )
{
if( id==-1 )
id = anIt.key();
if( anIt.key()!=id )
- but->setOn( false );
+ but->setChecked( false );
}
}
}
obj.myBtn->setShown( shown );
obj.myLabel->setShown( shown );
if( !shown )
- ( ( QToolButton* )obj.myBtn )->setOn( false );
+ ( ( QToolButton* )obj.myBtn )->setChecked( false );
}
}
*/
bool LightApp_Dialog::isObjectShown( const int id ) const
{
- return myObjects.contains( id ) && myObjects[ id ].myEdit->isShown();
+ return myObjects.contains( id ) && myObjects[ id ].myEdit->isVisible();
}
/*!
obj.myBtn->setEnabled( en );
// obj.myLabel->setEnabled( en );
if( !en )
- ( ( QToolButton* )obj.myBtn )->setOn( false );
+ ( ( QToolButton* )obj.myBtn )->setChecked( false );
}
}
ObjectMap::iterator anIt = myObjects.begin(),
aLast = myObjects.end();
for( ; anIt!=aLast; anIt++ )
- if( anIt.data().myBtn->isOn() )
+ if( anIt.value().myBtn->isChecked() )
selectObject( anIt.key(), _names, _types, _ids, update );
}
myObjects[ nid ].myLabel = lab;
QToolButton* but = new QToolButton( parent );
- but->setIconSet( QIconSet( myPixmap ) );
- but->setToggleButton( true );
+ but->setIcon( QIcon( myPixmap ) );
+ but->setCheckable( true );
but->setMaximumWidth( but->height() );
but->setMinimumWidth( but->height() );
connect( but, SIGNAL( toggled( bool ) ), this, SLOT( onToggled( bool ) ) );
*/
void LightApp_Dialog::onToggled( bool on )
{
- QButton* but = ( QButton* )sender();
+ QAbstractButton* but = ( QAbstractButton* )sender();
int id = -1;
if( !but )
ObjectMap::const_iterator anIt = myObjects.begin(),
aLast = myObjects.end();
for( ; anIt!=aLast && id==-1; anIt++ )
- if( anIt.data().myBtn==but )
+ if( anIt.value().myBtn==but )
id = anIt.key();
if( id!=-1 )
ObjectMap::const_iterator anIt = myObjects.begin(),
aLast = myObjects.end();
for( ; anIt!=aLast; anIt++ )
- ( ( QToolButton* )anIt.data().myBtn )->setIconSet( p );
+ ( ( QToolButton* )anIt.value().myBtn )->setIcon( p );
}
/*!
aLast = myObjects.end();
for( ; anIt!=aLast; anIt++ )
{
- anIt.data().myNI = ni;
+ anIt.value().myNI = ni;
setReadOnly( anIt.key(), isReadOnly( anIt.key() ) );
aNext = anIt; aNext++;
updateObject( anIt.key(), aNext==aLast );
QMap<int,int>::const_iterator aMIt = typesCount.begin(),
aMLast = typesCount.end();
for( ; aMIt!=aMLast; aMIt++ )
- typeCount.append( QString( "%1 %2" ).arg( aMIt.data() ).arg( typeName( aMIt.key() ) ) );
+ typeCount.append( QString( "%1 %2" ).arg( aMIt.value() ).arg( typeName( aMIt.key() ) ) );
return typeCount.join( ", " );
}
*/
void LightApp_Dialog::activateObject( const int theId )
{
- if ( myObjects.contains( theId ) && !myObjects[ theId ].myBtn->isOn() )
+ if ( myObjects.contains( theId ) && !myObjects[ theId ].myBtn->isChecked() )
myObjects[ theId ].myBtn->toggle();
}
aLast = myObjects.end();
for( ; anIt!=aLast; anIt++ )
{
- QToolButton* btn = ( QToolButton* )anIt.data().myBtn;
- btn->setOn( false );
+ QToolButton* btn = ( QToolButton* )anIt.value().myBtn;
+ btn->setChecked( false );
}
}
ObjectMap::const_iterator anIt = myObjects.begin(),
aLast = myObjects.end();
for( ; anIt!=aLast; anIt++ )
- if( anIt.data().myEdit == edit )
+ if( anIt.value().myEdit == edit )
id = anIt.key();
if( id>=0 && !isReadOnly( id ) )
{
- QStringList list = QStringList::split( " ", text );
+ QStringList list = text.split( " ", QString::SkipEmptyParts );
emit objectChanged( id, list );
}
}
#include "LightApp.h"
#include <QtxDialog.h>
-#include <qvaluelist.h>
-#include <qmap.h>
-#include <qpixmap.h>
+#include <QList>
+#include <QMap>
+#include <QPixmap>
class QLineEdit;
-class QButton;
+class QAbstractButton;
class QLabel;
class SUIT_ResourceMgr;
Q_OBJECT
public:
- typedef QValueList<int> TypesList;
+ typedef QList<int> TypesList;
typedef QMap<int,QStringList> SelectedObjects;
enum ObjectWg
public:
LightApp_Dialog( QWidget* = 0, const char* = 0, bool = false,
- bool = false, const int = Standard, WFlags = 0 );
+ bool = false, const int = Standard, Qt::WindowFlags = 0 );
virtual ~LightApp_Dialog();
virtual void show();
private:
typedef struct
{
- QLineEdit* myEdit;
- QButton* myBtn;
- QLabel* myLabel;
- QStringList myNames, myIds;
- TypesList myTypes, myPossibleTypes;
- NameIndication myNI;
+ QLineEdit* myEdit;
+ QAbstractButton* myBtn;
+ QLabel* myLabel;
+ QStringList myNames, myIds;
+ TypesList myTypes, myPossibleTypes;
+ NameIndication myNI;
} Object;
#include <SUIT_ViewModel.h>
#include <SUIT_ViewWindow.h>
-#include <qstring.h>
+#include <QString>
#ifndef DISABLE_SALOMEOBJECT
#include "SALOME_InteractiveObject.hxx"
#endif
if ( app )
{
SUIT_Desktop* desk = app->desktop();
- QPtrList<SUIT_ViewWindow> wnds = desk->windows();
- SUIT_ViewWindow* wnd;
- for ( wnd = wnds.first(); wnd; wnd = wnds.next() )
+ QListIterator<SUIT_ViewWindow*> itWnds( desk->windows() );
+ while ( itWnds.hasNext() )
{
- SUIT_ViewManager* vman = wnd->getViewManager();
+ SUIT_ViewManager* vman = itWnds.next()->getViewManager();
if( !vman )
continue;
SALOME_View* vf = theViewFrame ? theViewFrame : GetActiveView();
if ( vf ) {
- SALOME_Prs* prs = vf->CreatePrs( entry.latin1() );
+ SALOME_Prs* prs = vf->CreatePrs( entry.toLatin1() );
if ( prs ) {
vf->Erase( prs, forced );
if ( updateViewer )
{
#ifndef DISABLE_SALOMEOBJECT
Handle( SALOME_InteractiveObject ) temp = new SALOME_InteractiveObject();
- temp->setEntry( entry.latin1() );
+ temp->setEntry( entry.toLatin1() );
res = vf->isVisible( temp );
#endif
}
SALOME_View* vf = theViewFrame ? theViewFrame : GetActiveView();
if ( vf )
- prs = vf->CreatePrs( entry.latin1() );
+ prs = vf->CreatePrs( entry.toLatin1() );
return prs;
}
#include <OSD_Path.hxx>
#include <OSD_File.hxx>
#include <OSD_Directory.hxx>
-#include <OSD_Process.hxx>
-#include <OSD_Directory.hxx>
#include <OSD_Protection.hxx>
-#include <OSD_SingleProtection.hxx>
#include <OSD_FileIterator.hxx>
-#include <qfileinfo.h>
-#include <qdir.h>
+#include <QFileInfo>
+#include <QDir>
#ifdef WIN32
#include <time.h>
if(aFileBuffer == NULL)
return false;
- myTmpDir = QDir::convertSeparators( QFileInfo( theFileName ).dirPath( true ) + "/" ).latin1() ;
+ myTmpDir = QDir::convertSeparators( QFileInfo( theFileName ).absolutePath() + "/" ).toLatin1().constData() ;
int aCurrentPos = 0;
aCurrentPos += aBufferSize[i];
}
-#ifdef WNT
+#ifdef WIN32
ofstream aFile(theFileName, ios::out | ios::binary);
#else
ofstream aFile(theFileName);
*/
bool LightApp_Driver::ReadDatasFromFile( const char* theFileName, bool isMultiFile )
{
-#ifdef WNT
+#ifdef WIN32
ifstream aFile(theFileName, ios::binary);
#else
ifstream aFile(theFileName);
#endif
- myTmpDir = QDir::convertSeparators( QFileInfo( theFileName ).dirPath( true ) + "/" ).latin1() ;
+ myTmpDir = QDir::convertSeparators( QFileInfo( theFileName ).absolutePath() + "/" ).toLatin1().constData() ;
aFile.seekg(0, ios::end);
int aFileBufferSize = aFile.tellg();
OSD_Path anOSDPath(aFullPath);
OSD_File anOSDFile(anOSDPath);
if(!anOSDFile.Exists()) continue;
-#ifdef WNT
+#ifdef WIN32
ifstream aFile(aFullPath.ToCString(), ios::binary);
#else
ifstream aFile(aFullPath.ToCString());
OSD_Path anOSDPath(aFullPath);
OSD_File anOSDFile(anOSDPath);
if(!anOSDFile.Exists()) continue;
-#ifdef WNT
+#ifdef WIN32
aFile = new ifstream(aFullPath.ToCString(), ios::binary);
#else
aFile = new ifstream(aFullPath.ToCString());
TCollection_AsciiString aFullPath = aTmpDir + aFileName;
-#ifdef WNT
+#ifdef WIN32
ofstream aFile(aFullPath.ToCString(), ios::out | ios::binary);
#else
ofstream aFile(aFullPath.ToCString());
#include <SUIT_Desktop.h>
-#include <qapplication.h>
+#include <QApplication>
LightApp_EventFilter* LightApp_EventFilter::myFilter = NULL;
#include "LightApp.h"
-#include <qobject.h>
+#include <QObject>
-#if defined WNT
+#if defined WIN32
#pragma warning( disable: 4251 )
#endif
static LightApp_EventFilter* myFilter;
};
-#if defined WNT
+#if defined WIN32
#pragma warning( default: 4251 )
#endif
#include "LightApp_GLSelector.h"
#include "LightApp_DataOwner.h"
-#include "LightApp_DataObject.h"
#include <GLViewer_Context.h>
+#include <GLViewer_Object.h>
/*!Constructor. Initialize by GLViewer_Viewer2d and SUIT_SelectionMgr.*/
LightApp_GLSelector::LightApp_GLSelector( GLViewer_Viewer2d* viewer, SUIT_SelectionMgr* mgr )
#include <GLViewer_Viewer2d.h>
-#include <string>
-#include <GLViewer_Object.h>
+#include <QObject>
class LightApp_DataObject;
\class LightApp_GLSelector
Custom selector to get/set selection from GL viewer
*/
-class LIGHTAPP_EXPORT LightApp_GLSelector : public SUIT_Selector
+class LIGHTAPP_EXPORT LightApp_GLSelector : public QObject, public SUIT_Selector
{
Q_OBJECT
//
#include "LightApp_HDFDriver.h"
-#include "HDFexplorer.hxx"
#include "HDFOI.hxx"
// OCCT Includes
#include "LightApp_UpdateFlags.h"
#include "LightApp_ShowHideOp.h"
-#include "SUIT_Operation.h"
#include <SUIT_Study.h>
#include <SUIT_DataObject.h>
+#include <SUIT_Operation.h>
+#include <SUIT_ViewManager.h>
#include <SUIT_ResourceMgr.h>
+#include <SUIT_Desktop.h>
#ifndef DISABLE_VTKVIEWER
#ifndef DISABLE_SALOMEOBJECT
#endif
#endif
-#include <OB_Browser.h>
+// temporary commented
+//#include <OB_Browser.h>
#include <QtxPopupMgr.h>
-#include <qvariant.h>
-#include <qstring.h>
-#include <qstringlist.h>
+#include <QVariant>
+#include <QString>
+#include <QStringList>
/*!Constructor.*/
LightApp_Module::LightApp_Module( const QString& name )
}
/*!Context menu popup.*/
-void LightApp_Module::contextMenuPopup( const QString& client, QPopupMenu* menu, QString& /*title*/ )
+void LightApp_Module::contextMenuPopup( const QString& client, QMenu* menu, QString& /*title*/ )
{
- LightApp_Selection* sel = createSelection();
- sel->init( client, getApp()->selectionMgr() );
- popupMgr()->updatePopup( menu, sel );
+ LightApp_Selection* sel = createSelection( client, getApp()->selectionMgr() );
+ popupMgr()->setSelection( sel );
+ popupMgr()->setMenu( menu );
+ popupMgr()->updateMenu();
delete sel;
}
void LightApp_Module::updateObjBrowser( bool theIsUpdateDataModel,
SUIT_DataObject* theDataObject )
{
- bool upd = getApp()->objectBrowser()->isAutoUpdate();
- getApp()->objectBrowser()->setAutoUpdate( false );
+ // temporary commented
+ /*bool upd = getApp()->objectBrowser()->isAutoUpdate();
+ getApp()->objectBrowser()->setAutoUpdate( false );*/
if( theIsUpdateDataModel ){
if( CAM_DataModel* aDataModel = dataModel() ){
}
}
}
- getApp()->objectBrowser()->setAutoUpdate( upd );
- getApp()->objectBrowser()->updateTree( 0, false );
+ // temporary commented
+ /*getApp()->objectBrowser()->setAutoUpdate( upd );
+ getApp()->objectBrowser()->updateTree( 0, false );*/
}
/*!NOT IMPLEMENTED*/
// abort all operations
MapOfOperation::const_iterator anIt;
for( anIt = myOperations.begin(); anIt != myOperations.end(); anIt++ ) {
- anIt.data()->abort();
+ anIt.value()->abort();
}
return CAM_Module::activateModule( study );
if( LightApp_DataModel* aModel = dynamic_cast<LightApp_DataModel*>( aDataModel ) )
aModel->update( 0, dynamic_cast<LightApp_Study*>( getApp()->activeStudy() ) );
}
- if ( theFlags & UF_ObjBrowser )
- getApp()->objectBrowser()->updateTree( 0 );
+ // temporary commented
+ /*if ( theFlags & UF_ObjBrowser )
+ getApp()->objectBrowser()->updateTree( 0 );*/
if ( theFlags & UF_Controls )
updateControls();
if ( theFlags & UF_Viewer )
}
/*!Create and return instance of LightApp_Selection.*/
-LightApp_Selection* LightApp_Module::createSelection() const
+LightApp_Selection* LightApp_Module::createSelection( const QString& client, LightApp_SelectionMgr* mgr ) const
{
- return new LightApp_Selection();
+ return new LightApp_Selection( client, mgr );
}
/*!NOT IMPLEMENTED*/
QString oneAndNotActive = "( count( $component ) = 1 ) and ( not( activeModule in $component ) )";
QString uniform = "true in $canBeDisplayed and %1 and ( activeModule = '%2' )";
uniform = uniform.arg( oneAndNotActive ).arg( name() );
- myPopupMgr->setRule( disp, /*QString( "( not isVisible ) and " ) + */ uniform, true );
- myPopupMgr->setRule( erase, /*QString( "( isVisible ) and " ) + */ uniform, true );
- myPopupMgr->setRule( dispOnly, uniform, true );
+ myPopupMgr->setRule( disp, /*QString( "( not isVisible ) and " ) + */ uniform, QtxPopupMgr::VisibleRule );
+ myPopupMgr->setRule( erase, /*QString( "( isVisible ) and " ) + */ uniform, QtxPopupMgr::VisibleRule );
+ myPopupMgr->setRule( dispOnly, uniform, QtxPopupMgr::VisibleRule );
QStringList viewers;
for( ; anIt!=aLast; anIt++ )
strViewers+=temp.arg( *anIt );
strViewers+="}";
- myPopupMgr->setRule( eraseAll, QString( "client in %1" ).arg( strViewers ), true );
+ myPopupMgr->setRule( eraseAll, QString( "client in %1" ).arg( strViewers ), QtxPopupMgr::VisibleRule );
}
}
return myPopupMgr;
MapOfOperation::const_iterator anIt = myOperations.begin(),
aLast = myOperations.end();
for( ; anIt!=aLast; anIt++ )
- if( anIt.data()==op )
+ if( anIt.value()==op )
{
myOperations.remove( anIt.key() );
break;
class LightApp_Selection;
class LightApp_Operation;
class LightApp_SwitchOp;
-class LightApp_ShowHideOp;
class LightApp_Displayer;
+class LightApp_SelectionMgr;
class SUIT_Study;
class SUIT_DataObject;
virtual void windows( QMap<int, int>& ) const;
virtual void viewManagers( QStringList& ) const;
- virtual void contextMenuPopup( const QString&, QPopupMenu*, QString& );
+ virtual void contextMenuPopup( const QString&, QMenu*, QString& );
virtual void createPreferences();
virtual void studyActivated() {};
virtual LightApp_Displayer* displayer();
- virtual LightApp_Selection* createSelection() const;
+ virtual LightApp_Selection* createSelection( const QString&, LightApp_SelectionMgr* ) const;
public slots:
virtual bool activateModule( SUIT_Study* );
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File : LightApp_ModuleAction.cxx
+// Author : Sergey TELKOV, Vadim SANDLER
+//
+
+#include "LightApp_ModuleAction.h"
+
+#include <QtxComboBox.h>
+#include <QtxActionSet.h>
+#include <QHBoxLayout>
+
+/*!
+ \class LightApp_ModuleAction::ActionSet
+ \brief Internal class to represent list of modules buttons.
+ \internal
+*/
+
+class LightApp_ModuleAction::ActionSet : public QtxActionSet
+{
+public:
+ ActionSet( QObject* );
+ QAction* moduleAction( const QString& ) const;
+ int moduleId( const QString& ) const;
+ int moduleId( QAction* ) const;
+ void setVisible( bool );
+};
+
+/*!
+ \brief Constructor.
+ \internal
+ \param parent parent object
+*/
+LightApp_ModuleAction::ActionSet::ActionSet( QObject* parent )
+: QtxActionSet( parent )
+{
+}
+
+/*!
+ \brief Get action corresponding to the specified module.
+ \internal
+ \param name module name
+ \return module action or 0 if \a name is invalid
+*/
+QAction* LightApp_ModuleAction::ActionSet::moduleAction( const QString& name ) const
+{
+ QAction* a = 0;
+
+ QList<QAction*> alist = actions();
+ for ( QList<QAction*>::const_iterator it = alist.begin(); it != alist.end() && !a; ++it )
+ {
+ if ( (*it)->text() == name )
+ a = *it;
+ }
+
+ return a;
+}
+
+/*!
+ \brief Get module action identifier.
+ \internal
+ \param name module name
+ \return module action ID or -1 if \a name is invalid
+*/
+int LightApp_ModuleAction::ActionSet::moduleId( const QString& name ) const
+{
+ int id = -1;
+
+ QList<QAction*> alist = actions();
+ for ( QList<QAction*>::const_iterator it = alist.begin(); it != alist.end() && id == -1; ++it )
+ {
+ if ( (*it)->text() == name )
+ id = actionId( *it );
+ }
+
+ return id;
+}
+
+/*!
+ \brief Get module action identifier.
+ \internal
+ \param a module action
+ \return module action ID or -1 if \a a is null or invalid
+*/
+int LightApp_ModuleAction::ActionSet::moduleId( QAction* a ) const
+{
+ return actionId( a );
+}
+
+/*!
+ \brief Show/hide modules actions.
+ \internal
+ \param on new visibility state
+*/
+void LightApp_ModuleAction::ActionSet::setVisible( bool on )
+{
+ QList<QAction*> alist = actions();
+ for ( QList<QAction*>::const_iterator it = alist.begin(); it != alist.end(); ++it )
+ (*it)->setVisible( on );
+
+ QtxActionSet::setVisible( on );
+}
+
+/*!
+ \class LightApp_ModuleAction::ComboAction
+ \brief Internal class to represent combo box with the list of modules in the toolbar.
+ \internal
+*/
+
+/*!
+ \brief Constructor.
+ \internal
+ \param parent parent object
+*/
+LightApp_ModuleAction::ComboAction::ComboAction( QObject* parent )
+: QtxAction( parent )
+{
+}
+
+/*!
+ \brief Get list of associated widgets.
+ \internal
+ \return list of created widgets (QtxComboBox)
+*/
+QList<QtxComboBox*> LightApp_ModuleAction::ComboAction::widgets() const
+{
+ QList<QtxComboBox*> lst;
+
+ QList<QWidget*> wlist = createdWidgets();
+ for ( QList<QWidget*>::const_iterator wit = wlist.begin(); wit != wlist.end(); ++wit )
+ lst += qFindChildren<QtxComboBox *>(*wit);
+
+ return lst;
+}
+
+/*!
+ \brief Create combo box widget by request from the toolbar.
+ \internal
+ \param parent parent widget (should be QToolBar or its successor)
+ \return new custom widget, containing combo box
+*/
+QWidget* LightApp_ModuleAction::ComboAction::createWidget( QWidget* parent )
+{
+ if ( !parent->inherits( "QToolBar" ) )
+ return 0;
+
+ QWidget* dumb = new QWidget( parent );
+ QHBoxLayout* l = new QHBoxLayout( dumb );l->setSpacing(0);l->setMargin(0);
+ QtxComboBox* cb = new QtxComboBox( dumb );
+ cb->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Preferred );
+ cb->setFocusPolicy( Qt::NoFocus );
+ l->addWidget( cb );
+
+ connect( cb, SIGNAL( activatedId( int ) ), this, SIGNAL( activatedId( int ) ) );
+
+ return dumb;
+}
+
+/*!
+ \fn void LightApp_ModuleAction::ComboAction::activatedId( int id );
+ \internal
+ \brief Emitted when the combo box item is activated
+ \param item identifier
+*/
+
+/*!
+ \class LightApp_ModuleAction
+ \brief An action, representing the list of modules to be inserted to the
+ toolbar.
+
+ This action is represented in the toolbar as combo box and a set of buttons
+ for each module. In addition to the modules items, the combo box contains
+ an item corresponding to the "neutral point" of the application
+ (when there is no active module).
+
+ The action can be constructed with up to two parameters, defining the text
+ and icon to be displayed for the "neutral point".
+
+ Only one module can be active at the moment. It can be set programmatically
+ with setActiveModule() function. Use this method with empty string to turn
+ to the "neutral point". To get active module, use activeModule() function.
+
+ When user activates/deactivates any module, the signal moduleActivated()
+ is emitted.
+
+ The action can be represented in the toolbar in different modes:
+ * as combo box only (Qtx::ComboItem)
+ * as set of modules buttons only (Qtx::Buttons)
+ * as combo box followed by the set of modules buttons (Qtx::All)
+ * as none (Qtx::None)
+ By default, both combo box and buttons set are shown. Use method
+ setMode() to change this behavior.
+
+ An action can be also added to the popup menu, but combo box is never shown
+ in this case, only modules buttons.
+*/
+
+/*!
+ \brief Constructor
+
+ Creates an module action with "neutral point" item described by \a text.
+
+ \param text "neutral point" item's text
+ \param parent parent object
+*/
+LightApp_ModuleAction::LightApp_ModuleAction( const QString& text, QObject* parent )
+: QtxAction( parent )
+{
+ setText( text );
+ init();
+}
+
+/*!
+ \brief Constructor
+
+ Creates an module action with "neutral point" item described by \a text and \a ico.
+
+ \param text "neutral point" item's text
+ \param ico "neutral point" item's icon
+ \param parent parent object
+*/
+LightApp_ModuleAction::LightApp_ModuleAction( const QString& text, const QIcon& ico, QObject* parent )
+: QtxAction( parent )
+{
+ setText( text );
+ setIcon( ico );
+ init();
+}
+
+/*!
+ \brief Destructor
+*/
+LightApp_ModuleAction::~LightApp_ModuleAction()
+{
+}
+
+/*!
+ \brief Get list of modules.
+ \return modules names list
+*/
+QStringList LightApp_ModuleAction::modules() const
+{
+ QStringList lst;
+
+ QList<QAction*> alist = mySet->actions();
+ for ( QList<QAction*>::const_iterator it = alist.begin(); it != alist.end(); ++it )
+ lst.append( (*it)->text() );
+
+ return lst;
+}
+
+/*!
+ \brief Get module icon.
+ \param name module name
+ \return module icon
+ \sa setModuleIcon()
+*/
+QIcon LightApp_ModuleAction::moduleIcon( const QString& name ) const
+{
+ QAction* a = mySet->moduleAction( name );
+ return a ? a->icon() : QIcon();
+}
+
+/*!
+ \brief Set module icon.
+ \param name module name
+ \param ico new module icon
+ \sa moduleIcon()
+*/
+void LightApp_ModuleAction::setModuleIcon( const QString& name, const QIcon& ico )
+{
+ QAction* a = mySet->moduleAction( name );
+ if ( !a )
+ return;
+
+ a->setIcon( ico );
+ update();
+}
+
+/*!
+ \brief Add module into the list.
+ \param name module name
+ \param ico module icon
+ \param idx position in the module list (if -1, the module is added to the end of list)
+ \sa removeModule()
+*/
+void LightApp_ModuleAction::insertModule( const QString& name, const QIcon& ico,
+ const int idx )
+{
+ QtxAction* a = new QtxAction( name, ico, name, 0, this, true );
+ a->setStatusTip( tr( "Activate/deactivate %1 module" ).arg( name ) );
+
+ mySet->insertAction( a, -1, idx );
+ update();
+}
+
+/*!
+ \brief Remove module from the list.
+ \param name module name
+ \sa insertModule()
+*/
+void LightApp_ModuleAction::removeModule( const QString& name )
+{
+ int id = mySet->moduleId( name );
+ if ( id == -1 )
+ return;
+
+ mySet->removeAction( id );
+ update();
+}
+
+/*!
+ \brief Get active module.
+
+ If there is no active module ("neutral point"), then the null string
+ is returned.
+
+ \return active module name
+ \sa setActiveModule()
+*/
+QString LightApp_ModuleAction::activeModule() const
+{
+ QAction* a = active();
+ return a ? a->text() : QString();
+}
+
+/*!
+ \brief Set active module.
+
+ To turn to the "neutral point" (no active module), pass empty string.
+
+ \param name new active module name
+ \sa activeModule()
+*/
+void LightApp_ModuleAction::setActiveModule( const QString& name )
+{
+ if ( name == activeModule() )
+ return;
+
+ int id = mySet->moduleId( name );
+ if ( name.isEmpty() || id != -1 )
+ activate( id, false );
+}
+
+/*!
+ \brief Set action display mode.
+
+ Action can be represented in the toolbar as
+ * combo box only (Qtx::ComboItem)
+ * set of modules buttons only (Qtx::Buttons)
+ * combo box followed by the set of modules buttons (Qtx::All)
+ * none (Qtx::None)
+
+ \param mode action display mode
+ \sa mode()
+*/
+void LightApp_ModuleAction::setMode( const int mode )
+{
+ myMode = mode;
+ update();
+}
+
+/*!
+ \brief Get action display mode.
+ \param mode action display mode
+ \sa setMode()
+*/
+int LightApp_ModuleAction::mode() const
+{
+ return myMode;
+}
+
+/*!
+ \brief Add action to the widget.
+ \param w widget (menu or toolbar)
+ \return \c true if the action is added successfully and \c false otherwise.
+ \sa removeFrom()
+*/
+bool LightApp_ModuleAction::addTo( QWidget* w )
+{
+ bool ok = QtxAction::addTo( w );
+ if ( w->inherits( "QToolBar" ) )
+ ok = ok && myCombo->addTo( w );
+ return ok && mySet->addTo( w );
+}
+
+/*!
+ \brief Remove action from widget.
+ \param w widget (menu or toolbar)
+ \return \c true if the action is removed successfully and \c false otherwise.
+ \sa addTo()
+*/
+bool LightApp_ModuleAction::removeFrom( QWidget* w )
+{
+ bool ok = mySet->removeFrom( w );
+ if ( w->inherits( "QToolBar" ) )
+ ok = ok && myCombo->removeFrom( w );
+ return ok && QtxAction::removeFrom( w );
+}
+
+/*!
+ \brief Called when the action is added to the widget.
+ \param w widget (not used)
+*/
+void LightApp_ModuleAction::addedTo( QWidget* /*w*/ )
+{
+ update();
+}
+
+/*!
+ \fn void LightApp_ModuleAction::moduleActivated( const QString& name );
+ \brief Emitted when the module is activated
+ \param name module name (empty string for neutral point)
+*/
+
+/*!
+ \brief Initialize an action,
+ \internal
+*/
+void LightApp_ModuleAction::init()
+{
+ setVisible( false );
+
+ myMode = All;
+ myCombo = new ComboAction( this );
+ mySet = new ActionSet( this );
+
+ connect( this, SIGNAL( changed() ), this, SLOT( onChanged() ) );
+ connect( mySet, SIGNAL( triggered( int ) ), this, SLOT( onTriggered( int ) ) );
+ connect( myCombo, SIGNAL( activatedId( int ) ), this, SLOT( onComboActivated( int ) ) );
+}
+
+/*!
+ \brief Update an action.
+ \internal
+*/
+void LightApp_ModuleAction::update()
+{
+ QList<QtxComboBox*> lst = myCombo->widgets();
+ for ( QList<QtxComboBox*>::const_iterator it = lst.begin(); it != lst.end(); ++it )
+ update( *it );
+
+ myCombo->setVisible( myMode & ComboItem );
+ mySet->setVisible( myMode & Buttons );
+}
+
+/*!
+ \brief Update combo box.
+ \internal
+ \param cb combo box
+*/
+void LightApp_ModuleAction::update( QtxComboBox* cb )
+{
+ if ( !cb )
+ return;
+
+ int curId = mySet->moduleId( active() );
+ QList<QAction*> alist = mySet->actions();
+ cb->clear();
+
+ cb->addItem( icon(), text() );
+ cb->setId( 0, -1 );
+
+ for ( QList<QAction*>::const_iterator it = alist.begin(); it != alist.end(); ++it )
+ {
+ QAction* a = *it;
+ int id = mySet->moduleId( a );
+ cb->addItem( a->icon(), a->text() );
+ cb->setId( cb->count() - 1, id );
+ }
+
+ cb->setCurrentId( curId );
+}
+
+/*!
+ \brief Get an action corresponding to the active module.
+ \internal
+ \return active module action or 0 if there is no active module
+*/
+QAction* LightApp_ModuleAction::active() const
+{
+ QAction* a = 0;
+
+ QList<QAction*> alist = mySet->actions();
+ for ( QList<QAction*>::const_iterator it = alist.begin(); it != alist.end() && !a; ++it )
+ {
+ if ( (*it)->isChecked() )
+ a = *it;
+ }
+
+ return a;
+}
+
+/*!
+ \brief Activate a module item.
+ \internal
+ \param id module identifier
+ \param fromAction \c true if function is called from the module button
+*/
+void LightApp_ModuleAction::activate( int id, bool fromAction )
+{
+ bool checked = false;
+
+ QList<QAction*> alist = mySet->actions();
+ for ( QList<QAction*>::const_iterator it = alist.begin(); it != alist.end(); ++it )
+ {
+ if ( mySet->moduleId( *it ) != id ) {
+ (*it)->setChecked( false );
+ }
+ else {
+ if ( !fromAction )
+ (*it)->setChecked( true );
+ checked = (*it)->isChecked();
+ }
+ }
+
+ QList<QtxComboBox*> widgets = myCombo->widgets();
+ for ( QList<QtxComboBox*>::const_iterator wit = widgets.begin(); wit != widgets.end(); ++wit )
+ {
+ QtxComboBox* cb = *wit;
+ bool blocked = cb->signalsBlocked();
+ cb->blockSignals( true );
+ cb->setCurrentId( checked ? id : -1 );
+ cb->blockSignals( blocked );
+ }
+
+ emit moduleActivated( activeModule() );
+}
+
+/*!
+ \brief Called when module button is triggered.
+ \internal
+ \param id module identifier
+*/
+void LightApp_ModuleAction::onTriggered( int id )
+{
+ activate( id );
+}
+
+/*!
+ \brief Called when action state is changed.
+ \internal
+
+ This slot is used to prevent making the parent action visible.
+*/
+void LightApp_ModuleAction::onChanged()
+{
+ if ( !isVisible() )
+ return;
+
+ bool block = signalsBlocked();
+ blockSignals( true );
+ setVisible( false );
+ blockSignals( block );
+}
+
+/*!
+ \brief Called when combo box item is activated.
+ \param id module identifier
+*/
+void LightApp_ModuleAction::onComboActivated( int id )
+{
+ activate( id, false );
+}
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File : LightApp_ModuleAction.h
+// Author : Sergey TELKOV, Vadim SANDLER
+//
+
+#ifndef LIGHTAPP_MODULEACTION_H
+#define LIGHTAPP_MODULEACTION_H
+
+#include "LightApp.h"
+
+#include <QtxAction.h>
+
+#ifdef WIN32
+#pragma warning ( disable:4251 )
+#endif
+
+class QtxComboBox;
+
+class LIGHTAPP_EXPORT LightApp_ModuleAction : public QtxAction
+{
+ Q_OBJECT
+
+private:
+ class ActionSet;
+ class ComboAction;
+
+public:
+ enum { None = 0x00, Buttons = 0x01, ComboItem = 0x02, All = Buttons | ComboItem };
+
+public:
+ LightApp_ModuleAction( const QString&, QObject* = 0 );
+ LightApp_ModuleAction( const QString&, const QIcon&, QObject* = 0 );
+ virtual ~LightApp_ModuleAction();
+
+ QStringList modules() const;
+
+ QIcon moduleIcon( const QString& ) const;
+ void setModuleIcon( const QString&, const QIcon& );
+
+ void insertModule( const QString&, const QIcon&, const int = -1 );
+ void removeModule( const QString& );
+
+ QString activeModule() const;
+ void setActiveModule( const QString& );
+
+ void setMode( const int );
+ int mode() const;
+
+ virtual bool addTo( QWidget* );
+ virtual bool removeFrom( QWidget* );
+
+protected:
+ virtual void addedTo( QWidget* );
+
+signals:
+ void moduleActivated( const QString& );
+
+private:
+ void init();
+
+ void update();
+ void update( QtxComboBox* );
+
+ QAction* active() const;
+ void activate( int, bool = true );
+
+private slots:
+ void onChanged();
+ void onTriggered( int );
+ void onComboActivated( int );
+
+private:
+ ComboAction* myCombo;
+ ActionSet* mySet;
+ int myMode;
+};
+
+class LightApp_ModuleAction::ComboAction : public QtxAction
+{
+ Q_OBJECT
+
+public:
+ ComboAction( QObject* parent );
+
+ QList<QtxComboBox*> widgets() const;
+
+protected:
+ virtual QWidget* createWidget( QWidget* );
+
+signals:
+ void activatedId( int );
+};
+
+#endif // LIGHTAPP_MODULEACTION_H
#include <LightApp_ModuleDlg.h>
-#include <qframe.h>
-#include <qlabel.h>
-#include <qpushbutton.h>
-#include <qlayout.h>
-#include <qpixmap.h>
+#include <QFrame>
+#include <QLabel>
+#include <QPushButton>
+#include <QGridLayout>
#ifndef WIN32
using namespace std;
*/
//==============================================================================================================================
LightApp_ModuleDlg::LightApp_ModuleDlg ( QWidget * parent, const QString& component, const QPixmap icon )
- : QDialog ( parent, "ActivateModuleDlg", true, WStyle_Customize | WStyle_NormalBorder | WStyle_Title | WStyle_SysMenu )
+ : QDialog ( parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint )
{
+ setObjectName( "ActivateModuleDlg" );
+ setModal( true );
+
QPixmap defaultIcon( ( const char** ) default_icon );
- setCaption( tr( "CAPTION" ) );
+ setWindowTitle( tr( "CAPTION" ) );
setSizeGripEnabled( TRUE );
QGridLayout* ActivateModuleDlgLayout = new QGridLayout( this );
ActivateModuleDlgLayout->setMargin( 11 ); ActivateModuleDlgLayout->setSpacing( 6 );
// Module's name and icon
- myComponentFrame = new QFrame( this, "myComponentFrame" );
+ myComponentFrame = new QFrame( this );
+ myComponentFrame->setObjectName( "myComponentFrame" );
myComponentFrame->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Expanding ) );
myComponentFrame->setMinimumHeight( 100 );
myComponentFrame->setFrameStyle( QFrame::Box | QFrame::Sunken );
myComponentFrameLayout->setMargin( 11 ); myComponentFrameLayout->setSpacing( 6 );
// --> icon
- myComponentIcon = new QLabel( myComponentFrame, "myComponentIcon" );
+ myComponentIcon = new QLabel( myComponentFrame );
+ myComponentIcon->setObjectName( "myComponentIcon" );
myComponentIcon->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );
myComponentIcon->setPixmap( !icon.isNull() ? icon : defaultIcon );
myComponentIcon->setScaledContents( false );
- myComponentIcon->setAlignment( AlignCenter );
+ myComponentIcon->setAlignment( Qt::AlignCenter );
// --> name
- myComponentLab = new QLabel( component, myComponentFrame, "myComponentLab" );
+ myComponentLab = new QLabel( component, myComponentFrame );
+ myComponentLab->setObjectName( "myComponentLab" );
QFont fnt = myComponentLab->font(); fnt.setBold( TRUE ); myComponentLab->setFont( fnt );
- myComponentLab->setAlignment( AlignCenter );
+ myComponentLab->setAlignment( Qt::AlignCenter );
myComponentFrameLayout->addWidget( myComponentIcon, 0, 0 );
myComponentFrameLayout->addWidget( myComponentLab, 0, 1 );
infoLayout->setMargin( 0 ); infoLayout->setSpacing( 6 );
// --> top line
- QFrame* myLine1 = new QFrame( this, "myLine1" );
+ QFrame* myLine1 = new QFrame( this );
+ myLine1->setObjectName( "myLine1" );
myLine1->setFrameStyle( QFrame::HLine | QFrame::Plain );
// --> info label
- myInfoLabel = new QLabel( tr ("ActivateComponent_DESCRIPTION"), this, "myInfoLabel" );
- myInfoLabel->setAlignment( AlignCenter );
+ myInfoLabel = new QLabel( tr ("ActivateComponent_DESCRIPTION"), this );
+ myInfoLabel->setObjectName( "myInfoLabel" );
+ myInfoLabel->setAlignment( Qt::AlignCenter );
// --> bottom line
- QFrame* myLine2 = new QFrame( this, "myLine2" );
+ QFrame* myLine2 = new QFrame( this );
+ myLine2->setObjectName( "myLine2" );
myLine2->setFrameStyle( QFrame::HLine | QFrame::Plain );
infoLayout->addStretch();
btnLayout->setMargin( 0 ); btnLayout->setSpacing( 6 );
// --> New
- myNewBtn = new QPushButton( tr( "NEW" ), this, "myNewBtn" );
+ myNewBtn = new QPushButton( tr( "NEW" ), this );
+ myNewBtn->setObjectName( "myNewBtn" );
myNewBtn->setDefault( true ); myNewBtn->setAutoDefault( true );
// --> Open
- myOpenBtn = new QPushButton( tr( "OPEN" ), this, "myOpenBtn" );
+ myOpenBtn = new QPushButton( tr( "OPEN" ), this );
+ myOpenBtn->setObjectName( "myOpenBtn" );
myOpenBtn->setAutoDefault( true );
// --> Load
- myLoadBtn = new QPushButton( tr( "LOAD" ), this, "myLoadBtn" );
+ myLoadBtn = new QPushButton( tr( "LOAD" ), this );
+ myLoadBtn->setObjectName( "myLoadBtn" );
myLoadBtn->setAutoDefault( true );
// --> Cancel
- myCancelBtn = new QPushButton( tr( "CANCEL" ), this, "myCancelBtn" );
+ myCancelBtn = new QPushButton( tr( "CANCEL" ), this );
+ myCancelBtn->setObjectName( "myCancelBtn" );
myCancelBtn->setAutoDefault( true );
btnLayout->addWidget( myNewBtn );
btnLayout->addStretch();
btnLayout->addWidget( myCancelBtn );
- ActivateModuleDlgLayout->addWidget( myComponentFrame, 0, 0 );
- ActivateModuleDlgLayout->addLayout( infoLayout, 0, 1 );
- ActivateModuleDlgLayout->addMultiCellLayout( btnLayout, 1, 1, 0, 1 );
+ ActivateModuleDlgLayout->addWidget( myComponentFrame, 0, 0 );
+ ActivateModuleDlgLayout->addLayout( infoLayout, 0, 1 );
+ ActivateModuleDlgLayout->addLayout( btnLayout, 1, 0, 1, 2 );
// signals and slots connections
connect( myNewBtn, SIGNAL( clicked() ), this, SLOT( onButtonClicked() ) );
#define LIGHTAPP_MODULEDLG_H
#include "LightApp.h"
-#include <qdialog.h>
-#include <qpixmap.h>
+#include <QDialog>
+#include <QPixmap>
class QFrame;
class QLabel;
// $Header$
#include <LightApp_NameDlg.h>
-#include <SUIT_Application.h>
-#include <SUIT_Desktop.h>
#include <SUIT_Tools.h>
-#include <qgroupbox.h>
-#include <qlabel.h>
-#include <qlineedit.h>
-#include <qpushbutton.h>
-#include <qlayout.h>
+#include <QGroupBox>
+#include <QLabel>
+#include <QLineEdit>
+#include <QPushButton>
+#include <QHBoxLayout>
+#include <QVBoxLayout>
#ifndef WIN32
using namespace std;
*/
LightApp_NameDlg::LightApp_NameDlg( QWidget* parent )
: QDialog( parent ? parent : NULL,//application()->desktop(),
-"LightApp_NameDlg",
-true,
-WStyle_Customize | WStyle_NormalBorder | WStyle_Title | WStyle_SysMenu )
+Qt::WindowTitleHint | Qt::WindowSystemMenuHint )
{
- setCaption( tr("TLT_RENAME") );
+ setObjectName( "LightApp_NameDlg" );
+ setModal( true );
+
+ setWindowTitle( tr("TLT_RENAME") );
setSizeGripEnabled( TRUE );
QVBoxLayout* topLayout = new QVBoxLayout( this );
topLayout->setMargin( 11 ); topLayout->setSpacing( 6 );
/***************************************************************/
- QGroupBox* GroupC1 = new QGroupBox( this, "GroupC1" );
- GroupC1->setColumnLayout(0, Qt::Vertical );
- GroupC1->layout()->setMargin( 0 ); GroupC1->layout()->setSpacing( 0 );
- QHBoxLayout* GroupC1Layout = new QHBoxLayout( GroupC1->layout() );
+ QGroupBox* GroupC1 = new QGroupBox( this );
+ GroupC1->setObjectName( "GroupC1" );
+ QHBoxLayout* GroupC1Layout = new QHBoxLayout( GroupC1 );
GroupC1Layout->setAlignment( Qt::AlignTop );
GroupC1Layout->setMargin( 11 ); GroupC1Layout->setSpacing( 6 );
- QLabel* TextLabel = new QLabel( GroupC1, "TextLabel1" );
+ QLabel* TextLabel = new QLabel( GroupC1 );
+ TextLabel->setObjectName( "TextLabel1" );
TextLabel->setText( tr( "NAME_LBL" ) );
GroupC1Layout->addWidget( TextLabel );
- myLineEdit = new QLineEdit( GroupC1, "LineEdit1" );
+ myLineEdit = new QLineEdit( GroupC1 );
+ myLineEdit->setObjectName( "LineEdit1" );
myLineEdit->setMinimumSize( 250, 0 );
GroupC1Layout->addWidget( myLineEdit );
/***************************************************************/
- QGroupBox* GroupButtons = new QGroupBox( this, "GroupButtons" );
- GroupButtons->setColumnLayout(0, Qt::Vertical );
- GroupButtons->layout()->setMargin( 0 ); GroupButtons->layout()->setSpacing( 0 );
- QHBoxLayout* GroupButtonsLayout = new QHBoxLayout( GroupButtons->layout() );
+ QGroupBox* GroupButtons = new QGroupBox( this );
+ GroupButtons->setObjectName( "GroupButtons" );
+ QHBoxLayout* GroupButtonsLayout = new QHBoxLayout( GroupButtons );
GroupButtonsLayout->setAlignment( Qt::AlignTop );
GroupButtonsLayout->setMargin( 11 ); GroupButtonsLayout->setSpacing( 6 );
- myButtonOk = new QPushButton( GroupButtons, "buttonOk" );
+ myButtonOk = new QPushButton( GroupButtons );
+ myButtonOk->setObjectName( "buttonOk" );
myButtonOk->setText( tr( "BUT_OK" ) );
myButtonOk->setAutoDefault( TRUE ); myButtonOk->setDefault( TRUE );
GroupButtonsLayout->addWidget( myButtonOk );
GroupButtonsLayout->addStretch();
- myButtonCancel = new QPushButton( GroupButtons, "buttonCancel" );
+ myButtonCancel = new QPushButton( GroupButtons );
+ myButtonCancel->setObjectName( "buttonCancel" );
myButtonCancel->setText( tr( "BUT_CANCEL" ) );
myButtonCancel->setAutoDefault( TRUE );
GroupButtonsLayout->addWidget( myButtonCancel );
*/
void LightApp_NameDlg::accept()
{
- if ( name().stripWhiteSpace().isEmpty() )
+ if ( name().trimmed().isEmpty() )
return;
QDialog::accept();
}
#define LIGHTAPP_NAMEDLG_H
#include "LightApp.h"
-#include <qdialog.h>
+#include <QDialog>
class QLineEdit;
class QPushButton;
#include "LightApp_DataObject.h"
#include "LightApp_Application.h"
-#include <OB_Browser.h>
+// temporary commented
+//#include <OB_Browser.h>
#include <SUIT_Session.h>
#include <SUIT_DataObjectIterator.h>
-#include <qdatetime.h>
+#include <QTime>
#include <time.h>
Constructor
*/
LightApp_OBSelector::LightApp_OBSelector( OB_Browser* ob, SUIT_SelectionMgr* mgr )
-: SUIT_Selector( mgr, ob ),
- myBrowser( ob )
+ : SUIT_Selector( mgr/* temporary commented : , ob */ )/*,*/
+ // temporary commented : myBrowser( ob )
{
- if ( myBrowser ) {
+ // temporary commented
+ /*if ( myBrowser ) {
connect( myBrowser, SIGNAL( selectionChanged() ), this, SLOT( onSelectionChanged() ) );
- }
+ }*/
setModified();
}
if ( !myBrowser )
return;
DataObjectList objlist;
- myBrowser->getSelected( objlist );
+ // temporary commented
+ //myBrowser->getSelected( objlist );
LightApp_OBSelector* that = (LightApp_OBSelector*)this;
- for ( DataObjectListIterator it( objlist ); it.current(); ++it )
+ QListIterator<SUIT_DataObject*> it( objlist );
+ while ( it.hasNext() )
{
- LightApp_DataObject* obj = dynamic_cast<LightApp_DataObject*>( it.current() );
+ LightApp_DataObject* obj = dynamic_cast<LightApp_DataObject*>( it.next() );
if ( obj && app->checkDataObject(obj) )
{
#ifndef DISABLE_SALOMEOBJECT
Handle(SALOME_InteractiveObject) aSObj = new SALOME_InteractiveObject
- ( obj->entry(), obj->componentDataType(), obj->name() );
+ ( obj->entry().toLatin1().constData(),
+ obj->componentDataType().toLatin1().constData(),
+ obj->name().toLatin1().constData() );
LightApp_DataOwner* owner = new LightApp_DataOwner( aSObj );
#else
LightApp_DataOwner* owner = new LightApp_DataOwner( obj->entry() );
if ( !myBrowser )
return;
- if( myEntries.count() == 0 ||
- myModifiedTime < myBrowser->getModifiedTime() )
+ if( myEntries.count() == 0
+ // temporary commented
+ /*||
+ myModifiedTime < myBrowser->getModifiedTime()*/ )
fillEntries( myEntries );
DataObjectList objList;
objList.append( myEntries[owner->entry()] );
}
- myBrowser->setSelected( objList );
+ // temporary commented
+ //myBrowser->setSelected( objList );
mySelectedList.clear();
}
mySelectedList.clear();
selectionChanged();
QTime t2 = QTime::currentTime();
- qDebug( QString( "selection time = %1 msecs" ).arg( t1.msecsTo( t2 ) ) );
+ qDebug( QString( "selection time = %1 msecs" ).arg( t1.msecsTo( t2 ) ).toLatin1().constData() );
}
/*!Fill entries.*/
if ( !myBrowser )
return;
- for ( SUIT_DataObjectIterator it( myBrowser->getRootObject(),
+ // temporary commented
+ /*for ( SUIT_DataObjectIterator it( myBrowser->getRootObject(),
SUIT_DataObjectIterator::DepthLeft ); it.current(); ++it )
{
LightApp_DataObject* obj = dynamic_cast<LightApp_DataObject*>( it.current() );
if ( obj )
entires.insert( obj->entry(), obj );
- }
+ }*/
setModified();
}
#include <SUIT_Selector.h>
#include <SUIT_DataOwner.h>
+#include <QObject>
+
class OB_Browser;
class LightApp_DataObject;
\class LightApp_OBSelector
Custom selector to get/set selection from object browser
*/
-class LIGHTAPP_EXPORT LightApp_OBSelector : public SUIT_Selector
+class LIGHTAPP_EXPORT LightApp_OBSelector : public QObject, public SUIT_Selector
{
Q_OBJECT
#include <SUIT_Selector.h>
#include <SUIT_DataOwner.h>
+#include <QObject>
+
#include <OCCViewer_ViewModel.h>
class Handle_AIS_InteractiveObject;
\class LightApp_OCCSelector
Custom selector to get/set selection from OCC viewer
*/
-class LIGHTAPP_EXPORT LightApp_OCCSelector : public SUIT_Selector
+class LIGHTAPP_EXPORT LightApp_OCCSelector : public QObject, public SUIT_Selector
{
Q_OBJECT
#include <LightApp_Operation.h>
#include <LightApp_Module.h>
#include <LightApp_Application.h>
-#include <LightApp_Operation.h>
#include <LightApp_SelectionMgr.h>
#include <LightApp_Dialog.h>
#include <SUIT_Desktop.h>
-
-#include <qapplication.h>
-
+#include <SUIT_Study.h>
/*!
* \brief Constructor
if( active )
{
activateSelection();
- dlg()->setActiveWindow();
+ dlg()->activateWindow();
}
}
}
#include <SUIT_Operation.h>
class LightApp_Module;
-class LightApp_Application;
-class LightApp_Operation;
class LightApp_SelectionMgr;
class LightApp_Dialog;
class SUIT_Desktop;
#include "LightApp_Preferences.h"
-#include <QtxListResourceEdit.h>
-
-#include <qlayout.h>
-
/*!
Constructor.Initialize by resource manager and parent QWidget.
*/
{
bool res = false;
for ( PrefModuleMap::ConstIterator it = myPrefMod.begin(); it != myPrefMod.end() && !res; ++it )
- res = it.data() == mod;
+ res = it.value() == mod;
return res;
}
#define LIGHTAPP_PREFERENCES_H
#include <LightApp.h>
-
-#include <QtxDialog.h>
#include <QtxListResourceEdit.h>
-#include <qmap.h>
+#include <QMap>
class QtxResourceMgr;
#include "QtxResourceMgr.h"
-#include <qbutton.h>
-#include <qlayout.h>
-#include <qmessagebox.h>
-#include <qvbox.h>
-#include <qfiledialog.h>
+#include <SUIT_MessageBox.h>
+
+#include <QAbstractButton>
+#include <QVBoxLayout>
+#include <QFileDialog>
/*!
Constructor.
*/
LightApp_PreferencesDlg::LightApp_PreferencesDlg( LightApp_Preferences* prefs, QWidget* parent )
-: QtxDialog( parent, 0, true, true, OK | Close | Apply ),
+: QtxDialog( parent, true, true, OK | Close | Apply ),
myPrefs( prefs ), mySaved ( false )
{
- setCaption( tr( "CAPTION" ) );
+ setWindowTitle( tr( "CAPTION" ) );
- QVBoxLayout* main = new QVBoxLayout( mainFrame(), 5 );
+ QVBoxLayout* main = new QVBoxLayout( mainFrame() );
+ main->setMargin( 5 );
+ main->setSpacing( 5 );
- QVBox* base = new QVBox( mainFrame() );
- main->addWidget( base );
+ QWidget* vbox = new QWidget( mainFrame() );
+ main->addWidget( vbox );
- myPrefs->reparent( base, QPoint( 0, 0 ), true );
+ QVBoxLayout *base = new QVBoxLayout( vbox );
+
+ myPrefs->setParent( vbox );
+ myPrefs->move( QPoint( 0, 0 ) );
+ myPrefs->show();
setFocusProxy( myPrefs );
+ base->addWidget( myPrefs );
+
setButtonPosition( Right, Close );
setDialogFlags( AlignOnce );
connect( this, SIGNAL( dlgHelp() ), this, SLOT( onHelp() ) );
connect( this, SIGNAL( dlgApply() ), this, SLOT( onApply() ) );
- QButton* defBtn = userButton( insertButton( tr( "DEFAULT_BTN_TEXT" ) ) );
+ QAbstractButton* defBtn = userButton( insertButton( tr( "DEFAULT_BTN_TEXT" ) ) );
if ( defBtn )
connect( defBtn, SIGNAL( clicked() ), this, SLOT( onDefault() ) );
- QButton* impBtn = userButton( insertButton( tr( "IMPORT_BTN_TEXT" ) ) );
+ QAbstractButton* impBtn = userButton( insertButton( tr( "IMPORT_BTN_TEXT" ) ) );
if( impBtn )
connect( impBtn, SIGNAL( clicked() ), this, SLOT( onImportPref() ) );
}
if ( !myPrefs )
return;
- myPrefs->reparent( 0, QPoint( 0, 0 ), false );
+ myPrefs->setParent( 0 );
+ myPrefs->move( QPoint( 0, 0 ) );
+ myPrefs->hide();
myPrefs = 0;
}
/*! Restore default preferences*/
void LightApp_PreferencesDlg::onDefault()
{
- if( QMessageBox::Ok == QMessageBox::information( this, tr( "WARNING" ), tr( "DEFAULT_QUESTION" ), QMessageBox::Ok, QMessageBox::Cancel ) )
+ if( SUIT_MessageBox::Ok == SUIT_MessageBox::question( this, tr( "WARNING" ), tr( "DEFAULT_QUESTION" ),
+ SUIT_MessageBox::Ok | SUIT_MessageBox::Cancel,
+ SUIT_MessageBox::Ok ) )
{
if ( myPrefs && myPrefs->resourceMgr() )
{
if( !mgr )
return;
- QFileDialog dlg( ".", "*", this, "" );
- dlg.setCaption( tr("IMPORT_PREFERENCES") );
- dlg.setShowHiddenFiles( true );
+ QFileDialog dlg( this, tr("IMPORT_PREFERENCES"), ".", "*" );
+ dlg.setObjectName( "" );
+ //dlg.setShowHiddenFiles( true );
dlg.exec();
- QString fname = dlg.selectedFile();
- if( fname.isEmpty() )
+
+ QStringList files = dlg.selectedFiles();
+ if ( files.isEmpty() )
return;
+ QString fname = files[0];
if( mgr->import( fname ) )
{
myPrefs->retrieve();
#include "LightApp_Application.h"
#include "LightApp_Displayer.h"
+#include "CAM_Module.h"
+
#include "SUIT_Session.h"
#include "SUIT_ViewWindow.h"
+#include "SUIT_ViewManager.h"
+#include "SUIT_Desktop.h"
+#include "SUIT_Selector.h"
/*!
Constructor
*/
-LightApp_Selection::LightApp_Selection()
+LightApp_Selection::LightApp_Selection( const QString& client, LightApp_SelectionMgr* mgr )
: myStudy( 0 )
-{
-}
-
-/*!
- Destructor.
-*/
-LightApp_Selection::~LightApp_Selection()
-{
-}
-
-/*!
- Initialization.
-*/
-void LightApp_Selection::init( const QString& client, LightApp_SelectionMgr* mgr)
{
myPopupClient = client;
- myStudy = 0;
if( mgr )
{
mgr->selected( sel, client );
//2) to take such owners from other popup clients that it's entry is different with every entry from current list
- QPtrList<SUIT_Selector> aSelectors;
+ QList<SUIT_Selector*> aSelectors;
mgr->selectors( aSelectors );
- for( SUIT_Selector* selector = aSelectors.first(); selector; selector = aSelectors.next() )
+ QListIterator<SUIT_Selector*> it( aSelectors );
+ while ( it.hasNext() )
{
- qDebug( selector->type() );
+ SUIT_Selector* selector = it.next();
+ qDebug( selector->type().toLatin1().constData() );
if( selector->type()!=client )
{
mgr->selected( cur_sel, selector->type() );
}
}
+/*!
+ Destructor.
+*/
+LightApp_Selection::~LightApp_Selection()
+{
+}
+
QString LightApp_Selection::referencedToEntry( const QString& entry ) const
{
return myStudy->referencedToEntry( entry );
}
/*!
- Gets QtxValue();
+ Gets QVariant();
*/
-QtxValue LightApp_Selection::param( const int ind, const QString& p ) const
+QVariant LightApp_Selection::parameter( const int ind, const QString& p ) const
{
LightApp_Application* app = dynamic_cast<LightApp_Application*>( myStudy ? myStudy->application() : 0 );
if( !( ind>=0 && ind<count() ) || !app )
- return QtxValue();
+ return QVariant();
if( p=="isVisible" )
{
- QString mod_name = app->moduleTitle( param( ind, "component" ).toString() );
+ QString mod_name = app->moduleTitle( parameter( ind, "component" ).toString() );
LightApp_Displayer* d = LightApp_Displayer::FindDisplayer( mod_name, false );
// false in last parameter means that now we doesn't load module, if it isn't loaded
LightApp_Displayer local_d;
vis = local_d.IsDisplayed( myEntries[ ind ] );
}
- return QtxValue( vis, 0 );
+ return QVariant( vis );
}
else if( p=="component" )
else if( p=="isComponent" )
{
- return QtxValue( myStudy->isComponent( myEntries[ ind ] ), 0 );
+ return QVariant( myStudy->isComponent( myEntries[ ind ] ) );
}
else if( p=="isReference" )
- return QtxValue( isReference( ind ), false );
+ return QVariant( isReference( ind ) );
else if( p=="displayer" )
- return param( ind, "component" );
+ return parameter( ind, "component" );
else if( p=="canBeDisplayed" )
{
- QString mod_name = app->moduleTitle( param( ind, "component" ).toString() );
+ QString mod_name = app->moduleTitle( parameter( ind, "component" ).toString() );
LightApp_Displayer* d = LightApp_Displayer::FindDisplayer( mod_name, false );
// false in last parameter means that now we doesn't load module, if it isn't loaded
//operations under object
}
- return QtxValue();
+ return QVariant();
}
/*!
Gets global parameters. client, isActiveView, activeView etc.
*/
-QtxValue LightApp_Selection::globalParam( const QString& p ) const
+QVariant LightApp_Selection::parameter( const QString& p ) const
{
- if ( p == "client" ) return QtxValue( myPopupClient );
+ if ( p == "client" ) return QVariant( myPopupClient );
else if ( p == "activeModule" )
{
LightApp_Application* app = dynamic_cast<LightApp_Application*>( myStudy->application() );
if( !mod_name.isEmpty() )
return mod_name;
else
- return QtxValue();
+ return QVariant();
}
- else if ( p == "isActiveView" ) return QtxValue( (bool)activeVW() );
- else if ( p == "activeView" ) return QtxValue( activeViewType() );
-#ifndef WNT
- else return QtxPopupMgr::Selection::globalParam( p );
+ else if ( p == "isActiveView" ) return QVariant( (bool)activeVW() );
+ else if ( p == "activeView" ) return QVariant( activeViewType() );
+#ifndef WIN32
+ else return QtxPopupSelection::parameter( p );
#else
- else return Selection::globalParam( p );
+ else return QtxPopupSelection::parameter( p ); //Selection::parameter( p ); //?
#endif
}
It is able to return values of standard object properties
(isVisible,isComponent,canBeDisplayed,isReference, etc)
*/
-class LIGHTAPP_EXPORT LightApp_Selection : public QtxPopupMgr::Selection
+class LIGHTAPP_EXPORT LightApp_Selection : public QtxPopupSelection
{
public:
- LightApp_Selection();
+ LightApp_Selection( const QString&, LightApp_SelectionMgr* );
virtual ~LightApp_Selection();
- virtual void init( const QString&, LightApp_SelectionMgr* );
virtual void processOwner( const LightApp_DataOwner* );
virtual int count() const;
- virtual QtxValue param( const int, const QString& ) const;
- virtual QtxValue globalParam( const QString& ) const;
+ virtual QVariant parameter( const int, const QString& ) const;
+ virtual QVariant parameter( const QString& ) const;
void setModuleName( const QString );
protected:
#include <TColStd_MapOfInteger.hxx>
#include <TColStd_MapIteratorOfMapOfInteger.hxx>
#include <TColStd_IndexedMapOfInteger.hxx>
+ #include <TCollection_AsciiString.hxx>
#endif
/*!
if ( !entryMap.contains( checkEntry ) ) {
if ( refEntry != entry ) {
QString component = study->componentDataType( refEntry );
- theList.Append( new SALOME_InteractiveObject( refEntry, component, ""/*refobj->Name().c_str()*/ ) );
+ theList.Append( new SALOME_InteractiveObject( refEntry.toLatin1().constData(), component.toLatin1().constData(), ""/*refobj->Name().c_str()*/ ) );
}
else if( !owner->IO().IsNull() )
theList.Append( owner->IO() );
{
SUIT_DataOwnerPtrList aList;
- MapIOOfMapOfInteger::Iterator it;
- for ( it = theMapIO.begin(); it != theMapIO.end(); ++it )
+ MapIOOfMapOfInteger::Iterator it(theMapIO);
+ for ( ; it.More(); it.Next() )
{
- if ( it.data().IsEmpty() )
- aList.append( new LightApp_DataOwner( QString(it.key()->getEntry()) ) );
+ if ( it.Value().IsEmpty() )
+ aList.append( new LightApp_DataOwner( QString(it.Key()->getEntry()) ) );
else
{
int i;
- for ( i = 1; i <= it.data().Extent(); i++ )
- aList.append( new LightApp_DataSubOwner( QString(it.key()->getEntry()), it.data()( i ) ) );
+ for ( i = 1; i <= it.Value().Extent(); i++ )
+ aList.append( new LightApp_DataSubOwner( QString(it.Key()->getEntry()), it.Value()( i ) ) );
}
}
*/
void LightApp_SelectionMgr::selectedSubOwners( MapEntryOfMapOfInteger& theMap )
{
- theMap.clear();
+ theMap.Clear();
TColStd_IndexedMapOfInteger anIndexes;
const LightApp_DataSubOwner* subOwner = dynamic_cast<const LightApp_DataSubOwner*>( (*itr).operator->() );
if ( subOwner )
{
- if ( !theMap.contains( subOwner->entry() ) )
+#ifndef WNT
+ if ( !theMap.IsBound( TCollection_AsciiString(subOwner->entry().toLatin1().data()) ) )
+#else
+ if ( !theMap.IsBound( subOwner->entry().toLatin1().data() ) )
+#endif
{
anIndexes.Clear();
GetIndexes( subOwner->entry(), anIndexes );
- theMap.insert( subOwner->entry(), anIndexes );
+ theMap.Bind( subOwner->entry().toLatin1().data(), anIndexes );
}
}
}
#ifndef DISABLE_SALOMEOBJECT
#include <SALOME_InteractiveObject.hxx>
- #include <qmap.h>
+ #include <QMap>
+ #include <NCollection_DataMap.hxx>
class SALOME_ListIO;
class TColStd_IndexedMapOfInteger;
class TColStd_MapOfInteger;
+ class TCollection_AsciiString;
#else
-#include <qstringlist.h>
+#include <QStringList>
#endif
class LightApp_Application;
LightApp_Application* application() const;
#ifndef DISABLE_SALOMEOBJECT
- typedef QMap< Handle(SALOME_InteractiveObject), TColStd_IndexedMapOfInteger > MapIOOfMapOfInteger;
- typedef QMap< QString, TColStd_IndexedMapOfInteger > MapEntryOfMapOfInteger;
+ typedef NCollection_DataMap< Handle(SALOME_InteractiveObject), TColStd_IndexedMapOfInteger > MapIOOfMapOfInteger;
+ typedef NCollection_DataMap< TCollection_AsciiString, TColStd_IndexedMapOfInteger > MapEntryOfMapOfInteger;
void selectedObjects( SALOME_ListIO&, const QString& = QString::null, const bool = true ) const;
void setSelectedObjects( const SALOME_ListIO&, const bool = false );
#include "LightApp_ShowHideOp.h"
#include "LightApp_Application.h"
-#include "LightApp_DataOwner.h"
#include "LightApp_Module.h"
#include "LightApp_Study.h"
#include "LightApp_Displayer.h"
-#include "CAM_Study.h"
#include "LightApp_SelectionMgr.h"
#include "LightApp_Selection.h"
if( !mod )
return;
- LightApp_Selection* sel = mod->createSelection();
+ LightApp_Selection* sel = mod->createSelection( "", mgr );
if( !sel )
return;
- sel->init( "", mgr );
if( sel->count()==0 && myActionType!=ERASE_ALL )
{
abort();
QString mod_name;
if( sel->count()>0 )
{
- QString aStr = sel->param( 0, "displayer" ).toString();
+ QString aStr = sel->parameter( 0, "displayer" ).toString();
mod_name = app->moduleTitle( aStr );
}
else if( app->activeModule() )
#include "LightApp_Operation.h"
-class LightApp_Displayer;
-
/*!
\class LightApp_ShowHideOp
Standard operation allowing to show/hide selected objects
#include "LightApp_Study.h"
#include "CAM_DataModel.h"
+#include "CAM_Module.h"
#include "LightApp_Application.h"
#include "LightApp_DataModel.h"
#include "LightApp_DataObject.h"
#include "SUIT_ResourceMgr.h"
#include "SUIT_DataObjectIterator.h"
-#include <OB_Browser.h>
-
-#include <TCollection_AsciiString.hxx>
-
-#include <OSD_Path.hxx>
-#include <OSD_File.hxx>
-#include <OSD_Directory.hxx>
-#include <OSD_Process.hxx>
-#include <OSD_Directory.hxx>
-#include <OSD_Protection.hxx>
-#include <OSD_SingleProtection.hxx>
-#include <OSD_FileIterator.hxx>
-
#include <set>
-#include <qstring.h>
+#include <QString>
/*!
Constructor.
/*!
Create document.
*/
-void LightApp_Study::createDocument()
+bool LightApp_Study::createDocument( const QString& theStr )
{
setStudyName( QString( "Study%1" ).arg( LightApp_Application::studyId() ) );
// create myRoot
setRoot( new LightApp_RootObject( this ) );
- CAM_Study::createDocument();
+ bool aRet = CAM_Study::createDocument( theStr );
emit created( this );
+
+ return aRet;
}
/*!
// update loaded data models: call open() and update() on them.
ModelList dm_s;
dataModels( dm_s );
- for ( ModelListIterator it( dm_s ); it.current(); ++it )
- openDataModel( studyName(), it.current() );
+ QListIterator<CAM_DataModel*> it( dm_s );
+ while ( it.hasNext() )
+ openDataModel( studyName(), it.next() );
// this will build a SUIT_DataObject-s tree under myRoot member field
// passing "false" in order NOT to rebuild existing data models' trees - it was done in previous step
// but tree that corresponds to not-loaded data models will be updated any way.
ModelList dm_s;
dataModels( dm_s );
- for ( ModelListIterator it( dm_s ); it.current(); ++it )
- openDataModel( studyName(), it.current() );
+ QListIterator<CAM_DataModel*> it( dm_s );
+ while ( it.hasNext() )
+ openDataModel( studyName(), it.next() );
// this will build a SUIT_DataObject-s tree under myRoot member field
// passing "false" in order NOT to rebuild existing data models' trees - it was done in previous step
ModelList list;
dataModels( list );
- LightApp_DataModel* aModel = (LightApp_DataModel*)list.first();
-
QStringList listOfFiles;
bool isMultiFile = resMgr->booleanValue( "Study", "multi_file", false );
- for ( ; aModel; aModel = (LightApp_DataModel*)list.next() )
+ QListIterator<CAM_DataModel*> itList( list );
+ while ( itList.hasNext() )
{
- std::vector<std::string> anOldList = myDriver->GetListOfFiles( aModel->module()->name() );
+ LightApp_DataModel* aModel = (LightApp_DataModel*)itList.next();
+ if ( !aModel ) continue;
+
+ std::vector<std::string> anOldList = myDriver->GetListOfFiles( aModel->module()->name().toLatin1().constData() );
listOfFiles.clear();
aModel->saveAs( theFileName, this, listOfFiles );
if ( !listOfFiles.isEmpty() )
// removing previous temporary files. These files are not removed before saving
// because they may be required for it.
- std::vector<std::string> aNewList = myDriver->GetListOfFiles( aModel->module()->name() );
+ std::vector<std::string> aNewList = myDriver->GetListOfFiles( aModel->module()->name().toLatin1().constData() );
std::set<std::string> aNewNames;
std::set<std::string> toRemove;
{
ModelList list; dataModels( list );
- LightApp_DataModel* aModel = (LightApp_DataModel*)list.first();
-
myDriver->ClearDriverContents();
QStringList listOfFiles;
- for ( ; aModel; aModel = (LightApp_DataModel*)list.next() ) {
+ QListIterator<CAM_DataModel*> itList( list );
+ while ( itList.hasNext() ) {
+ LightApp_DataModel* aModel = (LightApp_DataModel*)itList.next();
+ if ( !aModel ) continue;
+
listOfFiles.clear();
aModel->save( listOfFiles );
saveModuleData(aModel->module()->name(), listOfFiles);
ModelList list; dataModels( list );
LightApp_DataModel* aModel = 0;
- for ( QPtrListIterator<CAM_DataModel> it( list ); it.current() && !isAnyChanged; ++it ){
- aModel = dynamic_cast<LightApp_DataModel*>( it.current() );
+ QListIterator<CAM_DataModel*> it( list );
+ while ( it.hasNext() && !isAnyChanged ) {
+ aModel = dynamic_cast<LightApp_DataModel*>( it.next() );
if ( aModel )
isAnyChanged = aModel->isModified();
}
for ( QStringList::Iterator it = theListOfFiles.begin(); it != theListOfFiles.end(); ++it ) {
if ( (*it).isEmpty() )
continue;
- aListOfFiles[anIndex] = (*it).latin1();
+ aListOfFiles[anIndex] = (*it).toLatin1().constData();
anIndex++;
}
- myDriver->SetListOfFiles(theModuleName, aListOfFiles);
+ myDriver->SetListOfFiles(theModuleName.toLatin1().constData(), aListOfFiles);
}
/*!
*/
void LightApp_Study::openModuleData(QString theModuleName, QStringList& theListOfFiles)
{
- std::vector<std::string> aListOfFiles = myDriver->GetListOfFiles(theModuleName);
+ std::vector<std::string> aListOfFiles = myDriver->GetListOfFiles(theModuleName.toLatin1().constData());
int i, aLength = aListOfFiles.size() - 1;
if (aLength < 0)
return;
return false;
bool isMultiFile = resMgr->booleanValue( "Study", "multi_file", false );
- bool aRes = myDriver->SaveDatasInFile(theFileName.latin1(), isMultiFile);
+ bool aRes = myDriver->SaveDatasInFile(theFileName.toLatin1(), isMultiFile);
return aRes;
}
return false;
bool isMultiFile = resMgr->booleanValue( "Study", "multi_file", false );
- bool aRes = myDriver->ReadDatasFromFile(theFileName.latin1(), isMultiFile);
+ bool aRes = myDriver->ReadDatasFromFile(theFileName.toLatin1(), isMultiFile);
return aRes;
}
#include <LightApp_Driver.h>
#include <CAM_Study.h>
-#include <CAM_DataModel.h>
-#include <SUIT_Study.h>
#include "string"
#include "vector"
+class SUIT_Study;
class SUIT_Application;
class CAM_DataModel;
LightApp_Study( SUIT_Application* );
virtual ~LightApp_Study();
- virtual void createDocument();
+ virtual bool createDocument( const QString& );
virtual bool openDocument( const QString& );
virtual bool loadDocument( const QString& );
#include <CAM_Application.h>
#include <SUIT_Operation.h>
#include <SUIT_Study.h>
-#include <qevent.h>
-#include <qwidget.h>
-#include <qptrlist.h>
-#include <qapplication.h>
+
+#include <QEvent>
+#include <QWidget>
+#include <QList>
+#include <QApplication>
/*!
* \brief Constructor
// try to find operation corresponding to the dialog
if ( aDlg != 0 && study() != 0 )
{
- QPtrListIterator<SUIT_Operation> anIter( study()->operations() );
- while( SUIT_Operation* anOp = anIter.current() )
+ QListIterator<SUIT_Operation*> anIter( study()->operations() );
+ while( anIter.hasNext() )
{
- if ( anOp->inherits( "LightApp_Operation" ) &&
+ SUIT_Operation* anOp = anIter.next();
+
+ if ( anOp &&
+ anOp->inherits( "LightApp_Operation" ) &&
((LightApp_Operation*)anOp)->dlg() == aDlg )
return ((LightApp_Operation*)anOp);
- ++anIter;
- }
+ }
}
return 0;
#define LightApp_SwitchOp_H
#include "LightApp.h"
-#include <qobject.h>
+#include <QObject>
class LightApp_Module;
class LightApp_Operation;
#include "LightApp_VTKSelector.h"
#include "LightApp_DataOwner.h"
+#include "SUIT_Desktop.h"
+
#ifndef DISABLE_VTKVIEWER
#include "SVTK_ViewModelBase.h"
#include "SVTK_ViewManager.h"
aSelector->AddOrRemoveIndex(anIO,anOwner->GetIds(),false);
}else if(const LightApp_DataOwner* anOwner = dynamic_cast<const LightApp_DataOwner*>(aDataOwner)){
Handle(SALOME_InteractiveObject) anIO =
- new SALOME_InteractiveObject(anOwner->entry().latin1(),"");
+ new SALOME_InteractiveObject(anOwner->entry().toLatin1(),"");
aSelector->AddIObject(anIO);
anAppendList.Append(anIO);
}
QMap< QString, Handle( SALOME_InteractiveObject )>::const_iterator RIt = toRemove.begin(),
REnd = toRemove.end();
for( ; RIt!=REnd; RIt++ )
- aSelector->RemoveIObject( RIt.data() );
+ aSelector->RemoveIObject( RIt.value() );
aView->onSelectionChanged();
}
#include "LightApp.h"
#include "LightApp_DataOwner.h"
+#include <QObject>
+
class SUIT_Desktop;
#ifndef DISABLE_VTKVIEWER
- #include <vtkSmartPointer.h>
#include <TColStd_IndexedMapOfInteger.hxx>
#include "SVTK_Selection.h"
#ifndef DISABLE_SALOMEOBJECT
\class LightApp_VTKSelector
Custom selector to get/set selection from object browser
*/
-class LIGHTAPP_EXPORT LightApp_VTKSelector : public SUIT_Selector
+class LIGHTAPP_EXPORT LightApp_VTKSelector : public QObject, public SUIT_Selector
{
Q_OBJECT;
//
#include "LightApp_WidgetContainer.h"
-#include <qobjectlist.h>
-#include <qwidgetstack.h>
+#include <QList>
+#include <QStackedWidget>
/*!
Constructor.
*/
LightApp_WidgetContainer::LightApp_WidgetContainer( const int type, QWidget* parent )
-: QDockWindow( QDockWindow::InDock, parent ),
-myType( type )
+ : QDockWidget( /*QDockWindow::InDock,*/ parent ),
+ myType( type )
{
- setWidget( myStack = new QWidgetStack( this ) );
+ setObjectName(QString("WC_%1").arg(type));
+ setWidget( myStack = new QStackedWidget( this ) );
myStack->show();
}
*/
bool LightApp_WidgetContainer::isEmpty() const
{
- const QObjectList* lst = myStack->children();
- if ( !lst )
+ const QList<QObject*> lst = myStack->children();
+ if ( lst.isEmpty() )
return true;
bool res = true;
- for ( QObjectListIt it( *lst ); it.current() && res; ++it )
+ QListIterator<QObject*> it( lst );
+ while ( it.hasNext() && res )
{
- if ( it.current()->isWidgetType() && myStack->id( (QWidget*)it.current() ) != -1 )
+ QObject* anItem = it.next();
+ if ( anItem->isWidgetType() && myStack->indexOf( (QWidget*)anItem ) != -1 )
res = false;
}
return res;
if ( contains( id ) )
remove( id );
- int stackId = myStack->addWidget( wid, id );
- if ( !myStack->visibleWidget() )
- myStack->raiseWidget( wid );
+ int stackId = myStack->insertWidget( id, wid );
+ if ( !myStack->currentWidget() )
+ myStack->setCurrentWidget( wid );
- setCaption( myStack->visibleWidget() ? myStack->visibleWidget()->caption() : QString::null );
+ setWindowTitle( myStack->currentWidget() ? myStack->currentWidget()->windowTitle() : QString::null );
return stackId;
}
{
remove( myStack->widget( id ) );
- setCaption( myStack->visibleWidget() ? myStack->visibleWidget()->caption() : QString::null );
+ setWindowTitle( myStack->currentWidget() ? myStack->currentWidget()->windowTitle() : QString::null );
}
/*!
{
myStack->removeWidget( wid );
- setCaption( myStack->visibleWidget() ? myStack->visibleWidget()->caption() : QString::null );
+ setWindowTitle( myStack->currentWidget() ? myStack->currentWidget()->windowTitle() : QString::null );
}
/*!
*/
void LightApp_WidgetContainer::activate( const int id )
{
- myStack->raiseWidget( id );
+ myStack->setCurrentIndex( id );
- setCaption( myStack->visibleWidget() ? myStack->visibleWidget()->caption() : QString::null );
+ setWindowTitle( myStack->currentWidget() ? myStack->currentWidget()->windowTitle() : QString::null );
}
/*!
*/
void LightApp_WidgetContainer::activate( QWidget* wid )
{
- myStack->raiseWidget( wid );
+ myStack->setCurrentWidget( wid );
- setCaption( myStack->visibleWidget() ? myStack->visibleWidget()->caption() : QString::null );
+ setWindowTitle( myStack->currentWidget() ? myStack->currentWidget()->windowTitle() : QString::null );
}
/*!
*/
QWidget* LightApp_WidgetContainer::active() const
{
- return myStack->visibleWidget();
+ return myStack->currentWidget();
}
#include "LightApp.h"
-#include <qdockwindow.h>
+#include <QDockWidget>
class QWidget;
-class QWidgetStack;
+class QStackedWidget;
/*!
Class which privade widget container.
*/
-class LIGHTAPP_EXPORT LightApp_WidgetContainer : public QDockWindow
+class LIGHTAPP_EXPORT LightApp_WidgetContainer : public QDockWidget
{
Q_OBJECT
QWidget* widget( const int ) const;
private:
- int myType;
- QWidgetStack* myStack;
+ int myType;
+ QStackedWidget* myStack;
};
#endif
LightApp_EventFilter.h \
LightApp_HDFDriver.h \
LightApp_Module.h \
+ LightApp_ModuleAction.h \
LightApp_ModuleDlg.h \
LightApp_NameDlg.h \
LightApp_OBFilter.h \
LightApp_EventFilter.cxx \
LightApp_HDFDriver.cxx \
LightApp_Module.cxx \
+ LightApp_ModuleAction.cxx \
LightApp_ModuleDlg.cxx \
LightApp_NameDlg.cxx \
LightApp_OBFilter.cxx \
LightApp_OBSelector_moc.cxx \
LightApp_Operation_moc.cxx \
LightApp_Module_moc.cxx \
+ LightApp_ModuleAction_moc.cxx \
LightApp_ModuleDlg_moc.cxx \
LightApp_NameDlg_moc.cxx \
LightApp_SelectionMgr_moc.cxx \
libLightApp_la_CPPFLAGS=$(PYTHON_INCLUDES) $(QT_INCLUDES) $(CAS_CPPFLAGS) \
$(HDF5_INCLUDES) @KERNEL_CXXFLAGS@ -I$(srcdir)/../SUIT -I$(srcdir)/../STD \
-I$(srcdir)/../CAM -I$(srcdir)/../ObjBrowser -I$(srcdir)/../LogWindow \
- -I$(srcdir)/../Prs -I$(srcdir)/../Qtx
+ -I$(srcdir)/../Prs -I$(srcdir)/../Qtx -I$(srcdir)/../Event
libLightApp_la_LDFLAGS=$(QT_MT_LIBS)
if ENABLE_VTKVIEWER
libLightApp_la_CPPFLAGS+= -DDISABLE_OCCVIEWER
endif
if ENABLE_PYCONSOLE
- libLightApp_la_CPPFLAGS+= $(PYTHON_INCLUDES) -I$(srcdir)/../PythonConsole -I$(srcdir)/../PyInterp
+ libLightApp_la_CPPFLAGS+= $(PYTHON_INCLUDES) -I$(srcdir)/../PyConsole -I$(srcdir)/../PyInterp
libLightApp_la_LDFLAGS+= $(PYTHON_LIBS)
else !ENABLE_PYCONSOLE
libLightApp_la_CPPFLAGS+= -DDISABLE_PYCONSOLE
endif
libLightApp_la_LIBADD= ../SUIT/libsuit.la ../STD/libstd.la ../CAM/libCAM.la \
- ../ObjBrowser/libObjBrowser.la ../LogWindow/libLogWindow.la $(CAS_KERNEL) \
+ ../LogWindow/libLogWindow.la $(CAS_KERNEL) \
../Prs/libSalomePrs.la $(HDF5_LIBS) $(KERNEL_LDFLAGS) -lSalomeHDFPersist
+#../ObjBrowser/libObjBrowser.la
if ENABLE_SALOMEOBJECT
libLightApp_la_LIBADD+= ../OBJECT/libSalomeObject.la
endif
endif
if ENABLE_PYCONSOLE
- libLightApp_la_LIBADD+= ../PyInterp/libPyInterp.la ../PythonConsole/libPythonConsole.la
+ libLightApp_la_LIBADD+= ../PyInterp/libPyInterp.la ../PyConsole/libPyConsole.la
endif
if ENABLE_SUPERVGRAPHVIEWER
libLightApp_la_LIBADD+= ../SUPERVGraph/libSUPERVGraph.la
</section>
<section name="desktop" >
<!-- Default GUI desktop state, position, size -->
+ <parameter name="geometry" value="(800%)x(800%) (+400%) (+400%) :(full)"/>
<parameter name="state" value="normal"/>
<parameter name="pos_x" value="center"/>
<parameter name="pos_y" value="center"/>
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>APP_DEFAULT_ICO</source>
+ <translation>icon_default.png</translation>
+ </message>
+ <message>
+ <source>ABOUT</source>
+ <translation>icon_about.png</translation>
+ </message>
+ <message>
+ <source>ABOUT_SPLASH</source>
+ <translation>icon_about.png</translation>
+ </message>
+ <message>
+ <source>APP_MODULE_BIG_ICO</source>
+ <translation>icon_module_big.png</translation>
+ </message>
+ <message>
+ <source>APP_BASE_LOGO</source>
+ <translation>icon_applogo.png</translation>
+ </message>
+ <message>
+ <source>ICON_SELECT</source>
+ <translation>icon_select.png</translation>
+ </message>
+ <message>
+ <source>APP_MODULE_ICO</source>
+ <translation>icon_module.png</translation>
+ </message>
+</context>
+</TS>
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>EXTERNAL_BROWSER_CANNOT_SHOW_PAGE</source>
+ <translation>External browser "%1" can not show help page "%2". Do you want to change it in preferences?</translation>
+ </message>
+ <message>
+ <source>ABOUT_COPYRIGHT</source>
+ <translation>Copyright (C) 2003-2006 OPEN CASCADE, EADS/CCR, LIP6,
+CEA/DEN, CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS</translation>
+ </message>
+ <message>
+ <source>ABOUT_CAPTION</source>
+ <translation>About %1</translation>
+ </message>
+ <message>
+ <source>APP_NAME</source>
+ <translation>SALOME</translation>
+ </message>
+ <message>
+ <source>ABOUT_LICENSE</source>
+ <translation>GNU LGPL</translation>
+ </message>
+ <message>
+ <source>ABOUT_VERSION</source>
+ <translation>Version %1</translation>
+ </message>
+</context>
+<context>
+ <name>LightApp_Application</name>
+ <message>
+ <source>INF_TOOLBAR_MODULES</source>
+ <translation>Modules</translation>
+ </message>
+ <message>
+ <source>PREF_SHOW_LEGEND</source>
+ <translation>Show legend</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_RENAME</source>
+ <translation>&Rename</translation>
+ </message>
+ <message>
+ <source>PREF_MULTI_FILE</source>
+ <translation>Multi file save</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_PREFERENCES</source>
+ <translation>Pre&ferences...</translation>
+ </message>
+ <message>
+ <source>PREF_TRIHEDRON_SHOW</source>
+ <translation>Show trihedron</translation>
+ </message>
+ <message>
+ <source>PREF_TRIHEDRON_SIZE</source>
+ <translation>Trihedron size</translation>
+ </message>
+ <message>
+ <source>OBJECT_BROWSER</source>
+ <translation>Object Browser</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_PREFERENCES</source>
+ <translation>Allow to change the preferences</translation>
+ </message>
+ <message>
+ <source>PREF_GROUP_DIRECTORIES</source>
+ <translation>Quick directory list</translation>
+ </message>
+ <message>
+ <source>PREF_GROUP_VTKVIEWER</source>
+ <translation>VTK Viewer 3d</translation>
+ </message>
+ <message>
+ <source>PREF_STORE_POS</source>
+ <translation>Store positions of windows</translation>
+ </message>
+ <message>
+ <source>PREF_BOTTOM</source>
+ <translation>Bottom</translation>
+ </message>
+ <message>
+ <source>PREF_CURVE_TYPE</source>
+ <translation>Curve type:</translation>
+ </message>
+ <message>
+ <source>PREF_ISOS_U</source>
+ <translation>Number of isolines along U</translation>
+ </message>
+ <message>
+ <source>PREF_ISOS_V</source>
+ <translation>Number of isolines along V</translation>
+ </message>
+ <message>
+ <source>PREF_POINTS</source>
+ <translation>Points</translation>
+ </message>
+ <message>
+ <source>PRP_MODULE</source>
+ <translation>Switch to the module "%1"</translation>
+ </message>
+ <message>
+ <source>PREF_ASCII_FILE</source>
+ <translation>ASCII save</translation>
+ </message>
+ <message>
+ <source>PREFERENCES_NOT_LOADED</source>
+ <translation>Preferences for module "<b>%1</b>" will be available when the module will be loaded</translation>
+ </message>
+ <message>
+ <source>PREF_LINEAR</source>
+ <translation>Linear</translation>
+ </message>
+ <message>
+ <source>DATA_MODELS</source>
+ <translation>Data models</translation>
+ </message>
+ <message>
+ <source>PRP_RENAME</source>
+ <translation>Rename active window</translation>
+ </message>
+ <message>
+ <source>TOT_RENAME</source>
+ <translation>Rename</translation>
+ </message>
+ <message>
+ <source>LOG_WINDOW</source>
+ <translation>Message Window</translation>
+ </message>
+ <message>
+ <source>PREF_SPLINE</source>
+ <translation>Spline</translation>
+ </message>
+ <message>
+ <source>PREF_OBJ_BROWSER_SETTINGS</source>
+ <translation>Object browser settings</translation>
+ </message>
+ <message>
+ <source>PRP_APP_MODULE</source>
+ <translation>Switch to SALOME platform neutral point</translation>
+ </message>
+ <message>
+ <source>PREF_GROUP_PY_CONSOLE</source>
+ <translation>Python console properties</translation>
+ </message>
+ <message>
+ <source>PREF_MARKER_SIZE</source>
+ <translation>Marker size:</translation>
+ </message>
+ <message>
+ <source>PREF_TAB_VIEWERS</source>
+ <translation>Viewers</translation>
+ </message>
+ <message>
+ <source>PREF_APP</source>
+ <translation>Application</translation>
+ </message>
+ <message>
+ <source>PREF_TOP</source>
+ <translation>Top</translation>
+ </message>
+ <message>
+ <source>MEN_REFRESH</source>
+ <translation>Refresh</translation>
+ </message>
+ <message>
+ <source>PREF_AUTO_SIZE_FIRST</source>
+ <translation>Auto size for first column</translation>
+ </message>
+ <message>
+ <source>PREF_GROUP_SUPERV</source>
+ <translation>Graph Supervisor</translation>
+ </message>
+ <message>
+ <source>PREF_TAB_OBJBROWSER</source>
+ <translation>Object browser</translation>
+ </message>
+ <message>
+ <source>PREF_TAB_GENERAL</source>
+ <translation>General</translation>
+ </message>
+ <message>
+ <source>NEW_WINDOW_0</source>
+ <translation>&GL view</translation>
+ </message>
+ <message>
+ <source>NEW_WINDOW_1</source>
+ <translation>&Plot2d view</translation>
+ </message>
+ <message>
+ <source>NEW_WINDOW_2</source>
+ <translation>&OCC view</translation>
+ </message>
+ <message>
+ <source>NEW_WINDOW_3</source>
+ <translation>VT&K view</translation>
+ </message>
+ <message>
+ <source>OBJ_BROWSER_NAME</source>
+ <translation>Object</translation>
+ </message>
+ <message>
+ <source>PREF_LEGEND_POSITION</source>
+ <translation>Legend position:</translation>
+ </message>
+ <message>
+ <source>PREF_RELATIVE_SIZE</source>
+ <translation>Relative size</translation>
+ </message>
+ <message>
+ <source>PREF_VIEWER_BACKGROUND</source>
+ <translation>Background color</translation>
+ </message>
+ <message>
+ <source>PREF_FONT</source>
+ <translation>Font</translation>
+ </message>
+ <message>
+ <source>PREF_LEFT</source>
+ <translation>Left</translation>
+ </message>
+ <message>
+ <source>PREF_TAB_DIRECTORIES</source>
+ <translation>Directories</translation>
+ </message>
+ <message>
+ <source>ACTIVATING_MODULE</source>
+ <translation>Trying to activate module "%1"</translation>
+ </message>
+ <message>
+ <source>PREF_VERT_AXIS_SCALE</source>
+ <translation>Vertical axis scale:</translation>
+ </message>
+ <message>
+ <source>PREF_HOR_AXIS_SCALE</source>
+ <translation>Horizontal axis scale:</translation>
+ </message>
+ <message>
+ <source>PREF_GROUP_STUDY</source>
+ <translation>Study properties</translation>
+ </message>
+ <message>
+ <source>PREF_CATEGORY_SALOME</source>
+ <translation>SALOME</translation>
+ </message>
+ <message>
+ <source>PREF_GROUP_OCCVIEWER</source>
+ <translation>OCC Viewer 3d</translation>
+ </message>
+ <message>
+ <source>PREF_LOGARITHMIC</source>
+ <translation>Logarithmic</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_MODULE_HELP</source>
+ <translation>Module help</translation>
+ </message>
+ <message>
+ <source>PREF_SUPERV_TITLE_COLOR</source>
+ <translation>Title color</translation>
+ </message>
+ <message>
+ <source>PREF_PARAM</source>
+ <translation>Parameters</translation>
+ </message>
+ <message>
+ <source>PREF_RIGHT</source>
+ <translation>Right</translation>
+ </message>
+ <message>
+ <source>PREF_LINES</source>
+ <translation>Lines</translation>
+ </message>
+ <message>
+ <source>INF_CANCELLED</source>
+ <translation>Module activation cancelled</translation>
+ </message>
+ <message>
+ <source>PREF_GROUP_EXT_BROWSER</source>
+ <translation>External browser</translation>
+ </message>
+ <message>
+ <source>PREF_SUPERV_CTRL_COLOR</source>
+ <translation>Ctrl color</translation>
+ </message>
+ <message>
+ <source>PREF_GROUP_DEF_COLUMNS</source>
+ <translation>Default columns</translation>
+ </message>
+ <message>
+ <source>PREF_GROUP_PLOT2DVIEWER</source>
+ <translation>Plot2d Viewer</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_MRU</source>
+ <translation>Most recently used</translation>
+ </message>
+ <message>
+ <source>TOT_DESK_PREFERENCES</source>
+ <translation>Preferences</translation>
+ </message>
+ <message>
+ <source>DEFINE_EXTERNAL_BROWSER</source>
+ <translation>External browser is not found. Do you want to define it in preferences?</translation>
+ </message>
+ <message>
+ <source>PREF_AUTO_SIZE</source>
+ <translation>Auto size for other columns</translation>
+ </message>
+ <message>
+ <source>TOT_DESK_MRU</source>
+ <translation>Most recently used</translation>
+ </message>
+</context>
+<context>
+ <name>LightApp_Module</name>
+ <message>
+ <source>MEN_ERASE</source>
+ <translation>Erase</translation>
+ </message>
+ <message>
+ <source>TOP_DISPLAY_ONLY</source>
+ <translation>Display only</translation>
+ </message>
+ <message>
+ <source>STB_DISPLAY_ONLY</source>
+ <translation>Display only</translation>
+ </message>
+ <message>
+ <source>MEN_DISPLAY_ONLY</source>
+ <translation>Display only</translation>
+ </message>
+ <message>
+ <source>TOP_ERASE</source>
+ <translation>Erase</translation>
+ </message>
+ <message>
+ <source>MEN_ERASE_ALL</source>
+ <translation>Erase all</translation>
+ </message>
+ <message>
+ <source>STB_ERASE</source>
+ <translation>Erase</translation>
+ </message>
+ <message>
+ <source>STB_DISPLAY</source>
+ <translation>Display</translation>
+ </message>
+ <message>
+ <source>TOP_DISPLAY</source>
+ <translation>Display</translation>
+ </message>
+ <message>
+ <source>MEN_DISPLAY</source>
+ <translation>Display</translation>
+ </message>
+ <message>
+ <source>STB_ERASE_ALL</source>
+ <translation>Erase all</translation>
+ </message>
+ <message>
+ <source>TOP_ERASE_ALL</source>
+ <translation>Erase all</translation>
+ </message>
+</context>
+<context>
+ <name>LightApp_ModuleDlg</name>
+ <message>
+ <source>NEW</source>
+ <translation>&New</translation>
+ </message>
+ <message>
+ <source>LOAD</source>
+ <translation>&Load</translation>
+ </message>
+ <message>
+ <source>OPEN</source>
+ <translation>&Open</translation>
+ </message>
+ <message>
+ <source>ActivateComponent_DESCRIPTION</source>
+ <translation>Create, open or load study.</translation>
+ </message>
+ <message>
+ <source>CANCEL</source>
+ <translation>&Cancel</translation>
+ </message>
+ <message>
+ <source>CAPTION</source>
+ <translation>Activate module</translation>
+ </message>
+</context>
+<context>
+ <name>LightApp_NameDlg</name>
+ <message>
+ <source>TLT_RENAME</source>
+ <translation>Rename</translation>
+ </message>
+ <message>
+ <source>NAME_LBL</source>
+ <translation>Name: </translation>
+ </message>
+</context>
+<context>
+ <name>LightApp_PreferencesDlg</name>
+ <message>
+ <source>IMPORT_PREFERENCES</source>
+ <translation>Import preferences</translation>
+ </message>
+ <message>
+ <source>CAPTION</source>
+ <translation>Preferences</translation>
+ </message>
+ <message>
+ <source>WARNING</source>
+ <translation>Warning</translation>
+ </message>
+ <message>
+ <source>IMPORT_BTN_TEXT</source>
+ <translation>Import</translation>
+ </message>
+ <message>
+ <source>DEFAULT_QUESTION</source>
+ <translation>Do you want to retrieve default preferences?</translation>
+ </message>
+ <message>
+ <source>DEFAULT_BTN_TEXT</source>
+ <translation>Defaults</translation>
+ </message>
+</context>
+</TS>
// KERNEL SALOME_Event : Define event posting mechanism
//
// Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
+// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File : LogWindow.cxx
+// Author : Vadim SANDLER, Open CASCADE S.A. (vadim.sandler@opencascade.com)
+// Module : SALOME
#include "LogWindow.h"
-#include <qfile.h>
-#include <qlayout.h>
-#include <qaction.h>
-#include <qpopupmenu.h>
-#include <qtextbrowser.h>
-#include <qapplication.h>
-#include <qdatetime.h>
+#include <QAction>
+#include <QApplication>
+#include <QDate>
+#include <QFile>
+#include <QMenu>
+#include <QTextEdit>
+#include <QTextStream>
+#include <QTime>
+#include <QVBoxLayout>
-#include <SUIT_Tools.h>
-#include <SUIT_Session.h>
#include <SUIT_MessageBox.h>
#include <SUIT_ResourceMgr.h>
+#include <SUIT_Session.h>
+#include <SUIT_Tools.h>
#define DEFAULT_SEPARATOR "***"
/*!
- Converts rich text to plain text
+ \brief Convert rich text to plain text.
+ \internal
+ \param richText rich text string
+ \return converted plain text string
*/
static QString plainText( const QString& richText )
{
QString aText = richText;
- int startTag = aText.find('<');
- while ( 1 ) {
+ int startTag = aText.indexOf( '<' );
+ while ( true )
+ {
if ( startTag < 0 )
break;
- int finishTag = aText.find('>',startTag);
- if (finishTag < 0)
+
+ int finishTag = aText.indexOf( '>', startTag );
+ if ( finishTag < 0 )
break;
- aText = aText.remove(startTag, finishTag-startTag+1);
- startTag = aText.find('<');
+
+ aText = aText.remove( startTag, finishTag - startTag + 1 );
+ startTag = aText.indexOf( '<' );
}
return aText;
}
/*!
- Default constructor
+ \class LogWindow
+ \brief Widget, displaying log messages.
+
+ The log messages window provides operations like:
+ - show messages
+ - display timestamps at the message beginning
+ - color messages according to their purposes (e.g., errors/warning)
+ - clear log output
+ - copy messages to clipvoard
+ - save message log to to the text file
+*/
+
+/*!
+ \brief Constructor.
+
+ Creates new messages log window widget.
+ \param parent parent widget
*/
LogWindow::LogWindow( QWidget* parent )
: QFrame( parent ),
-SUIT_PopupClient()
+ SUIT_PopupClient()
{
SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
setFont( SUIT_Tools::stringToFont( fntSet ) );
- myView = new QTextBrowser(this,"myView");
-#if QT_VERSION>0x030007
- myView->setTextFormat( Qt::LogText );
-#endif
+ myView = new QTextEdit( this );
+ myView->setReadOnly( true );
myView->viewport()->installEventFilter( this );
QVBoxLayout* main = new QVBoxLayout( this );
+ main->setMargin( 5 );
main->addWidget( myView );
myBannerSize = 0;
}
/*!
- Destructor
+ \brief Destructor.
+
+ Does nothing for the moment.
*/
LogWindow::~LogWindow()
{
}
/*!
- Custom event handler
+ \brief Get current banner (message log window header text).
+ \return string representing the current banner
*/
-bool LogWindow::eventFilter( QObject* o, QEvent* e )
+QString LogWindow::banner() const
{
- if ( o == myView->viewport() && e->type() == QEvent::ContextMenu )
- {
- contextMenuRequest( (QContextMenuEvent*)e );
- return true;
- }
- return QFrame::eventFilter( o, e );
+ return myBanner;
}
/*!
- Sets banner (title of message log)
- \param banner - new title
+ \brief Get current separator (text which is printed between messages).
+ \return string representing the current separator
+*/
+QString LogWindow::separator() const
+{
+ return mySeparator;
+}
+
+/*!
+ \brief Set current banner (message log window header text).
+ \param banner new banner
*/
void LogWindow::setBanner( const QString& banner )
{
}
/*!
- Set separator (line printing between messages)
- \param separator - new separator
+ Set current separator (text which is printed between messages).
+ \param separator new separator
*/
void LogWindow::setSeparator( const QString& separator )
{
}
/*!
- Puts message to log window
- \param message - text of message
- \addSeparator - if it is true, then separator is added to tail of message log
+ \brief Custom event handler.
+
+ Process context popup menu request event.
+
+ \param o object
+ \param e event
+ \return True if the event is processed and further processing should be stopped
*/
-void LogWindow::putMessage( const QString& message, bool addSeparator )
+bool LogWindow::eventFilter( QObject* o, QEvent* e )
{
- myView->append( message );
+ if ( o == myView->viewport() && e->type() == QEvent::ContextMenu )
+ {
+ contextMenuRequest( (QContextMenuEvent*)e );
+ return true;
+ }
+ return QFrame::eventFilter( o, e );
+}
+
+/*!
+ \brief Put new message to the log window.
+ \param message text of the message
+ \param flags ORed flags which define how the message should be printed
+*/
+void LogWindow::putMessage( const QString& message, const int flags )
+{
+ putMessage( message, QColor(), flags );
+}
+
+/*!
+ \brief Put new message to the log window.
+ \param message text of the message
+ \param color text color of the message
+ \param flags ORed flags which define how the message should be printed
+*/
+void LogWindow::putMessage( const QString& message, const QColor& color, const int flags )
+{
+ QString msg = message;
+ if ( msg.isEmpty() )
+ return;
+
+ bool noColor = flags & DisplayNoColor;
+
+ if ( color.isValid() )
+ msg = QString( "<font color=\"%1\">%2</font>" ).arg( color.name() ).arg( msg );
+
+ QString dStr;
+ if ( flags & DisplayDate )
+ {
+ dStr = QDate::currentDate().toString( Qt::SystemLocaleDate );
+ if ( !noColor )
+ dStr = QString( "<font color=\"#003380\">%1</font>" ).arg( dStr );
+ }
+
+ QString tStr;
+ if ( flags & DisplayTime )
+ {
+ tStr = QTime::currentTime().toString( Qt::SystemLocaleDate );
+ if ( !noColor )
+ tStr = QString( "<font color=\"#008033\">%1</font>" ).arg( tStr );
+ }
+
+ QString dateTime = QString( "%1 %2" ).arg( dStr ).arg( tStr ).trimmed();
+ if ( !dateTime.isEmpty() )
+ msg = QString( "[%1] %2" ).arg( dateTime ).arg( msg );
+
+ myView->append( msg );
myHistory.append( plainText( message ) );
- if ( addSeparator && !mySeparator.isNull() )
+ if ( flags & DisplaySeparator && !mySeparator.isEmpty() )
{
myView->append( mySeparator ); // add separator
myHistory.append( plainText( mySeparator ) );
}
- myView->scrollToBottom();
+ myView->moveCursor( QTextCursor::End );
}
/*!
- Clears message log
- \param clearHistory - if it is true, then also history is cleared
+ \brief Clear message log.
+ \param clearHistory if True, clear also the messages history
*/
void LogWindow::clear( bool clearHistory )
{
if ( !myBanner.isEmpty() )
{
myView->append( myBanner );
- myBannerSize = myView->paragraphs();
+ myBannerSize = myView->document()->blockCount();
}
else
myBannerSize = 0;
}
/*!
- Saves log to file
- \param fileName - name of file
+ \brief Save messages log to the file.
+ \param fileName name of the file
+ \return \c true on success and \c false on error
*/
bool LogWindow::saveLog( const QString& fileName )
{
QFile file( fileName );
- if ( !file.open( IO_WriteOnly ) )
+ if ( !file.open( QFile::WriteOnly ) )
return false;
QTextStream stream( &file );
stream << QTime::currentTime().toString( "hh:mm:ss" ) << endl;
stream << "*****************************************" << endl;
- for ( uint i = 0; i < myHistory.count(); i++ )
+ for ( int i = 0; i < myHistory.count(); i++ )
stream << myHistory[ i ] << endl;
file.close();
}
/*!
- Creates actions
+ \brief Create context popup menu actions.
*/
void LogWindow::createActions()
{
- QAction* a = new QAction( "", tr( "&Copy" ), 0, this );
- a->setStatusTip( tr( "&Copy" ) );
- connect( a, SIGNAL( activated() ), SLOT( onCopy()));
+ QAction* a = new QAction( tr( "EDIT_COPY_CMD" ), this );
+ a->setStatusTip( tr( "EDIT_COPY_CMD" ) );
+ connect( a, SIGNAL( triggered( bool ) ), SLOT( onCopy() ) );
myActions.insert( CopyId, a );
- a = new QAction( "", tr( "Clea&r" ), 0, this );
- a->setStatusTip( tr( "Clea&r" ) );
- connect( a, SIGNAL( activated() ), SLOT( onClear()));
+ a = new QAction( tr( "EDIT_CLEAR_CMD" ), this );
+ a->setStatusTip( tr( "EDIT_CLEAR_CMD" ) );
+ connect( a, SIGNAL( triggered( bool ) ), SLOT( onClear() ) );
myActions.insert( ClearId, a );
- a = new QAction( "", tr( "Select &All" ), 0, this );
- a->setStatusTip( tr( "Select &All" ) );
- connect( a, SIGNAL( activated() ), SLOT( onSelectAll()));
+ a = new QAction( tr( "EDIT_SELECTALL_CMD" ), this );
+ a->setStatusTip( tr( "EDIT_SELECTALL_CMD" ) );
+ connect( a, SIGNAL( triggered( bool ) ), SLOT( onSelectAll() ) );
myActions.insert( SelectAllId, a );
- a = new QAction( "", tr( "&Save log to file..." ), 0, this );
- a->setStatusTip( tr( "&Save log to file..." ) );
- connect( a, SIGNAL( activated() ), SLOT( onSaveToFile()));
+ a = new QAction( tr( "EDIT_SAVETOFILE_CMD" ), this );
+ a->setStatusTip( tr( "EDIT_SAVETOFILE_CMD" ) );
+ connect( a, SIGNAL( triggered( bool ) ), SLOT( onSaveToFile() ) );
myActions.insert( SaveToFileId, a );
}
/*!
- Redefined virtual method for popup filling
+ \brief Create the context popup menu.
+
+ Fill in the popup menu with the commands.
+
+ \param menu context popup menu
*/
-void LogWindow::contextMenuPopup( QPopupMenu* popup )
+void LogWindow::contextMenuPopup( QMenu* popup )
{
- myActions[ CopyId ]->addTo( popup );
- myActions[ ClearId ]->addTo( popup );
-
- popup->insertSeparator();
-
- myActions[ SelectAllId ]->addTo( popup );
-
- popup->insertSeparator();
-
- myActions[ SaveToFileId ]->addTo( popup );
+ popup->addAction( myActions[ CopyId ] );
+ popup->addAction( myActions[ ClearId ] );
+ popup->addSeparator();
+ popup->addAction( myActions[ SelectAllId ] );
+ popup->addSeparator();
+ popup->addAction( myActions[ SaveToFileId ] );
+
+ Qtx::simplifySeparators( popup );
updateActions();
}
/*!
- Updates enable status of actions
+ \brief Update menu actions.
+
+ Update context popup menu action state.
*/
void LogWindow::updateActions()
{
- int paraFrom, paraTo, indexFrom, indexTo;
- myView->getSelection( ¶From, &indexFrom, ¶To, &indexTo );
- bool allSelected = myView->hasSelectedText() &&
- !paraFrom && paraTo == myView->paragraphs() - 1 &&
- !indexFrom && indexTo == myView->paragraphLength( paraTo );
- myActions[ CopyId ]->setEnabled( myView->hasSelectedText() );
- myActions[ ClearId ]->setEnabled( myView->paragraphs() > myBannerSize );
- myActions[ SelectAllId ]->setEnabled( !allSelected );
+ myActions[CopyId]->setEnabled( myView->textCursor().hasSelection() );
+ myActions[ ClearId ]->setEnabled( myView->document()->blockCount() > myBannerSize );
+ myActions[SelectAllId]->setEnabled( !myView->document()->isEmpty() );
myActions[ SaveToFileId ]->setEnabled( myHistory.count() > 0 );
}
/*!
- SLOT: called if user click "Save" in popup
+ \brief Called when user selects "Save To File" command in the popup menu.
*/
void LogWindow::onSaveToFile()
{
if ( aName.isNull() )
return;
- QApplication::setOverrideCursor( Qt::waitCursor );
-
+ QApplication::setOverrideCursor( Qt::WaitCursor );
+
bool bOk = saveLog( aName );
QApplication::restoreOverrideCursor();
if ( !bOk )
- SUIT_MessageBox::error1( this, tr( "Error" ), tr( "Can't save file" ), tr( "OK" ) );
+ SUIT_MessageBox::critical( this, tr( "ERR_ERROR" ), tr( "ERR_CANT_SAVE_FILE" ) );
}
/*!
- SLOT: called if user click "Select all" in popup
+ \brief Called when user selects "Select all" command in the popup menu.
*/
void LogWindow::onSelectAll()
{
}
/*!
- SLOT: called if user click "Clear" in popup
+ \brief Called when user click "Clear" command in the popup menu.
*/
void LogWindow::onClear()
{
}
/*!
- SLOT: called if user click "Copy" in popup
+ \brief Called when user click "Copy" command in the popup menu.
*/
void LogWindow::onCopy()
{
if ( myView )
myView->copy();
}
+
+/*!
+ \brief Set actions to be visible in the context popup menu.
+
+ Actions, which IDs are set in \a flags parameter, will be shown in the
+ context popup menu. Other actions will not be shown.
+
+ \param flags ORed together actions flags
+*/
+void LogWindow::setMenuActions( const int flags )
+{
+ myActions[CopyId]->setVisible( flags & CopyId );
+ myActions[ClearId]->setVisible( flags & ClearId );
+ myActions[SelectAllId]->setVisible( flags & SelectAllId );
+ myActions[SaveToFileId]->setVisible( flags & SaveToFileId );
+}
+
+/*!
+ \brief Get menu actions which are currently visible in the context popup menu.
+ \return ORed together actions flags
+ \sa setMenuActions()
+*/
+int LogWindow::menuActions() const
+{
+ int ret = 0;
+ ret = ret | ( myActions[CopyId]->isVisible() ? CopyId : 0 );
+ ret = ret | ( myActions[ClearId]->isVisible() ? ClearId : 0 );
+ ret = ret | ( myActions[SelectAllId]->isVisible() ? SelectAllId : 0 );
+ ret = ret | ( myActions[SaveToFileId]->isVisible() ? SaveToFileId : 0 );
+ return ret;
+}
+
+/*!
+ \fn virtual QString LogWindow::popupClientType() const;
+ \brief Get popup client symbolic name, used in popup menu management system.
+ \return symbolic name
+*/
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
// File : LogWindow.h
-// Author :
-// Module : KERNEL
+// Author : Vadim SANDLER, Open CASCADE S.A. (vadim.sandler@opencascade.com)
+// Module : SALOME
-#ifndef LogWindow_HeaderFile
-#define LogWindow_HeaderFile
+#ifndef LOGWINDOW_H
+#define LOGWINDOW_H
-#if defined LOGWINDOW_EXPORTS
#if defined WIN32
-#define LOGWINDOW_EXPORT __declspec( dllexport )
+# if defined LOGWINDOW_EXPORTS
+# define LOGWINDOW_EXPORT __declspec( dllexport )
+# else
+# define LOGWINDOW_EXPORT __declspec( dllimport )
+# endif
#else
-#define LOGWINDOW_EXPORT
-#endif
-#else
-#if defined WIN32
-#define LOGWINDOW_EXPORT __declspec( dllimport )
-#else
-#define LOGWINDOW_EXPORT
-#endif
+# define LOGWINDOW_EXPORT
#endif
#include <SUIT_PopupClient.h>
-#include <qframe.h>
-#include <qstringlist.h>
+#include <QFrame>
+#include <QMap>
+#include <QStringList>
#ifdef WIN32
#pragma warning( disable:4251 )
#endif
class QAction;
-class QTextBrowser;
+class QTextEdit;
-/*!
- \class LogWindow
- Widget, showing logs message. Allows to show, to clear, to copy messages and to save then to file
-*/
class LOGWINDOW_EXPORT LogWindow : public QFrame, public SUIT_PopupClient
{
Q_OBJECT
- enum { CopyId, ClearId, SelectAllId, SaveToFileId };
+public:
+ //! Context popup menu actions flags
+ enum
+ {
+ CopyId = 0x01, //!< "Copy" menu action
+ ClearId = 0x02, //!< "Clear" menu action
+ SelectAllId = 0x04, //!< "Select All" menu action
+ SaveToFileId = 0x08, //!< "Save To File" menu action
+ All = CopyId | ClearId | SelectAllId | SaveToFileId //!< all menu actions
+ };
+
+ //! Display messages flags
+ enum
+ {
+ DisplayNormal = 0x00, //!< do not display extra data
+ DisplayDate = 0x01, //!< display message date
+ DisplayTime = 0x02, //!< display message time
+ DisplaySeparator = 0x04, //!< display separator between messages
+ DisplayNoColor = 0x08, //!< display colored message
+ DisplayDateTime = DisplayDate | DisplayTime //!< display date & time
+ };
public:
- LogWindow( QWidget* theParent );
- virtual ~LogWindow();
+ LogWindow( QWidget* theParent );
+ virtual ~LogWindow();
virtual QString popupClientType() const { return QString( "LogWindow" ); }
- virtual void contextMenuPopup( QPopupMenu* );
+ virtual void contextMenuPopup( QMenu* );
+
+ virtual bool eventFilter( QObject*, QEvent* );
- bool eventFilter( QObject* o, QEvent* e );
+ QString banner() const;
+ QString separator() const;
- void setBanner( const QString& banner );
- void setSeparator( const QString& separator );
+ void setBanner( const QString& );
+ void setSeparator( const QString& );
- virtual void putMessage( const QString& message, bool addSeparator = true );
- void clear( bool clearHistory = false );
+ void putMessage( const QString&, const int = DisplayNormal );
+ virtual void putMessage( const QString&, const QColor&, const int = DisplayNormal );
+ void clear( const bool = false );
- bool saveLog( const QString& fileName );
+ bool saveLog( const QString& );
+
+ void setMenuActions( const int );
+ int menuActions() const;
protected slots:
void onSaveToFile();
void updateActions();
private:
- QTextBrowser* myView;
- QString myBanner;
- QString mySeparator;
- QStringList myHistory;
- int myBannerSize;
- QMap<int, QAction*> myActions;
+ QTextEdit* myView; //!< internal view window
+ QString myBanner; //!< current banner
+ QStringList myHistory; //!< messages history
+ QString mySeparator; //!< current separator
+ int myBannerSize; //!< current banner's size
+ QMap<int, QAction*> myActions; //!< popup menu actions
};
#ifdef WIN32
#pragma warning( default:4251 )
#endif
-#endif
+#endif // LOGWINDOW_H
--- /dev/null
+TEMPLATE = lib
+TARGET = LogWindow
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+INCLUDEPATH += ../../include ../Qtx ../SUIT
+LIBS += -L../../lib -lqtx -lsuit
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += LOGWINDOW_EXPORTS
+
+HEADERS = LogWindow.h
+
+SOURCES = LogWindow.cxx
+
+TRANSLATIONS = resources/LogWindow_msg_en.ts
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+resources.files = resources/*.qm
+resources.path = ../../resources
+
+INSTALLS += includes resources
libLogWindow_la_CPPFLAGS=$(QT_INCLUDES) -I$(srcdir)/../SUIT -I$(srcdir)/../Qtx
-libLogWindow_la_LDFLAGS=$(QT_MT_LIBS) ../SUIT/libsuit.la ../Qtx/libqtx.la
+libLogWindow_la_LDFLAGS=$(QT_MT_LIBS)
+libLogWindow_la_LIBADD=../Qtx/libqtx.la ../SUIT/libsuit.la
# Module : SALOME
# $Header$
-SUBDIRS = Qtx Style DDS QDS SUIT STD CAF CAM SUITApp LogWindow ObjBrowser Prs
+# VSR: this is the original packages list
+#SUBDIRS = Qtx Style DDS QDS SUIT STD CAF CAM SUITApp LogWindow ObjBrowser Prs
+# VSR: already migrated to Qt4 packages
+SUBDIRS = Qtx DDS QDS SUIT SUITApp STD CAF CAM LogWindow Prs
if ENABLE_SALOMEOBJECT
SUBDIRS += OBJECT
if ENABLE_VTKVIEWER
SUBDIRS += VTKViewer
if ENABLE_SALOMEOBJECT
- SUBDIRS += SVTK
+ SUBDIRS += SVTK
endif
endif
if ENABLE_OCCVIEWER
- SUBDIRS += OCCViewer
+ SUBDIRS += OCCViewer
if ENABLE_SALOMEOBJECT
- SUBDIRS += SOCC
+ SUBDIRS += SOCC
endif
endif
if ENABLE_PYCONSOLE
- SUBDIRS += PyInterp PythonConsole
+ SUBDIRS += PyInterp PyConsole
endif
if ENABLE_PLOT2DVIEWER
SUBDIRS += Plot2d
if ENABLE_SALOMEOBJECT
- SUBDIRS += SPlot2d
+ SUBDIRS += SPlot2d
endif
endif
if ENABLE_SUPERVGRAPHVIEWER
if ENABLE_QXGRAPHVIEWER
SUBDIRS += QxGraph
endif
-SUBDIRS += LightApp ResExporter
+SUBDIRS += Event LightApp ResExporter
if GUI_ENABLE_CORBA
- SUBDIRS += RegistryDisplay TOOLSGUI \
- Event Session SalomeApp SALOME_SWIG SALOME_PY SALOME_PYQT
+# VSR: this is the original packages list
+# SUBDIRS += TOOLSGUI Session SalomeApp SALOME_SWIG SALOME_PY SALOME_PYQT
+# VSR: already migrated to Qt4 packages
+ SUBDIRS += TOOLSGUI Session SalomeApp
endif
--- /dev/null
+TEMPLATE = lib
+TARGET = SalomeObject
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+CASROOT = $$(CASROOT)
+CAS_CPPFLAGS = $${CASROOT}/inc
+
+CAS_LDPATH = -L$${CASROOT}/Linux/lib -lTKV3d
+
+INCLUDEPATH += ../../include $${CAS_CPPFLAGS}
+LIBS += $${CAS_LDPATH}
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += OCC_VERSION_MAJOR=6 OCC_VERSION_MINOR=1 OCC_VERSION_MAINTENANCE=1 LIN LINTEL CSFDB No_exception HAVE_CONFIG_H HAVE_LIMITS_H HAVE_WOK_CONFIG_H OCC_CONVERT_SIGNALS
+
+HEADERS = SALOME_InteractiveObject.hxx
+HEADERS += Handle_SALOME_InteractiveObject.hxx
+HEADERS += SALOME_AISShape.hxx
+HEADERS += Handle_SALOME_AISShape.hxx
+HEADERS += SALOME_AISObject.hxx
+HEADERS += Handle_SALOME_AISObject.hxx
+HEADERS += SALOME_ListIO.hxx
+HEADERS += SALOME_ListIteratorOfListIO.hxx
+HEADERS += Handle_SALOME_ListNodeOfListIO.hxx
+HEADERS += SALOME_ListNodeOfListIO.hxx
+HEADERS += Handle_SALOME_Filter.hxx
+HEADERS += SALOME_Filter.hxx
+HEADERS += Handle_SALOME_TypeFilter.hxx
+HEADERS += SALOME_TypeFilter.hxx
+HEADERS += SALOME_DataMapOfIOMapOfInteger.hxx
+HEADERS += SALOME_DataMapIteratorOfDataMapOfIOMapOfInteger.hxx
+HEADERS += Handle_SALOME_DataMapNodeOfDataMapOfIOMapOfInteger.hxx
+HEADERS += SALOME_Selection.h
+HEADERS += SALOME_AISObject.ixx
+HEADERS += SALOME_AISObject.jxx
+HEADERS += SALOME_AISShape.ixx
+HEADERS += SALOME_AISShape.jxx
+HEADERS += SALOME_Filter.ixx
+HEADERS += SALOME_Filter.jxx
+HEADERS += SALOME_InteractiveObject.ixx
+HEADERS += SALOME_InteractiveObject.jxx
+HEADERS += SALOME_TypeFilter.ixx
+HEADERS += SALOME_TypeFilter.jxx
+HEADERS += SALOME_DataMapNodeOfDataMapOfIOMapOfInteger.hxx
+
+SOURCES = SALOME_InteractiveObject.cxx
+SOURCES += SALOME_AISShape.cxx
+SOURCES += SALOME_AISObject.cxx
+SOURCES += SALOME_ListIO_0.cxx
+SOURCES += SALOME_ListIteratorOfListIO_0.cxx
+SOURCES += SALOME_ListNodeOfListIO_0.cxx
+SOURCES += SALOME_Filter.cxx
+SOURCES += SALOME_TypeFilter.cxx
+SOURCES += SALOME_DataMapOfIOMapOfInteger_0.cxx
+SOURCES += SALOME_DataMapNodeOfDataMapOfIOMapOfInteger_0.cxx
+SOURCES += SALOME_DataMapIteratorOfDataMapOfIOMapOfInteger_0.cxx
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+INSTALLS += includes
libOCCViewer_la_CPPFLAGS=$(QT_INCLUDES) $(OGL_INCLUDES) $(CAS_CPPFLAGS) \
-I$(srcdir)/../SUIT -I$(srcdir)/../Qtx
-libOCCViewer_la_LDFLAGS=$(OGL_LIBS) $(QT_MT_LIBS) $(CAS_KERNEL) $(CAS_VIEWER) ../SUIT/libsuit.la
+libOCCViewer_la_LDFLAGS=$(OGL_LIBS) $(QT_MT_LIBS) $(CAS_KERNEL) $(CAS_VIEWER)
+libOCCViewer_la_LIBADD=../Qtx/libqtx.la ../SUIT/libsuit.la
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-#ifdef WNT
+#ifdef WIN32
#ifdef OCCVIEWER_EXPORTS
#define OCCVIEWER_EXPORT __declspec(dllexport)
#else
#define OCCVIEWER_EXPORT
#endif
-#if defined WNT
+#if defined WIN32
#pragma warning ( disable: 4251 )
#endif
--- /dev/null
+TEMPLATE = lib
+TARGET = OCCViewer
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+OGL_INCLUDES =
+
+OGL_LIBS = -lGL -L/usr/X11R6/lib -lGLU
+
+CASROOT = $$(CASROOT)
+CAS_CPPFLAGS = $${CASROOT}/inc
+
+CAS_KERNEL = -L$${CASROOT}/Linux/lib -lTKernel
+
+CAS_VIEWER = -L$${CASROOT}/Linux/lib -lTKV3d -lTKService
+
+INCLUDEPATH += ../../include $${OGL_INCLUDES} $${CAS_CPPFLAGS} ../Qtx ../SUIT
+LIBS += -L../../lib -lqtx -lsuit $${OGL_LIBS} $${CAS_KERNEL} $${CAS_VIEWER}
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += OCCVIEWER_EXPORTS OCC_VERSION_MAJOR=6 OCC_VERSION_MINOR=1 OCC_VERSION_MAINTENANCE=1 LIN LINTEL CSFDB No_exception HAVE_CONFIG_H HAVE_LIMITS_H HAVE_WOK_CONFIG_H OCC_CONVERT_SIGNALS
+
+HEADERS = OCCViewer_AISSelector.h
+HEADERS += OCCViewer_ViewManager.h
+HEADERS += OCCViewer_ViewModel.h
+HEADERS += OCCViewer_ViewPort3d.h
+HEADERS += OCCViewer_ViewPort.h
+HEADERS += OCCViewer_ViewWindow.h
+HEADERS += OCCViewer_VService.h
+HEADERS += OCCViewer_CreateRestoreViewDlg.h
+HEADERS += OCCViewer.h
+HEADERS += OCCViewer_ClippingDlg.h
+HEADERS += OCCViewer_SetRotationPointDlg.h
+
+SOURCES = OCCViewer_AISSelector.cxx
+SOURCES += OCCViewer_ViewManager.cxx
+SOURCES += OCCViewer_ViewModel.cxx
+SOURCES += OCCViewer_ViewPort3d.cxx
+SOURCES += OCCViewer_ViewPort.cxx
+SOURCES += OCCViewer_ViewWindow.cxx
+SOURCES += OCCViewer_VService.cxx
+SOURCES += OCCViewer_CreateRestoreViewDlg.cxx
+SOURCES += OCCViewer_SetRotationPointDlg.cxx
+SOURCES += OCCViewer_ClippingDlg.cxx
+
+TRANSLATIONS = resources/OCCViewer_images.ts \
+ resources/OCCViewer_msg_en.ts
+
+ICONS = resources/*.png
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+resources.files = $$ICONS resources/*.qm
+resources.path = ../../resources
+
+INSTALLS += includes resources
#define OCCVIEWER_AISSELECTOR_H
#include "OCCViewer.h"
-#include <qobject.h>
+#include <QObject>
#include <Quantity_NameOfColor.hxx>
#include <AIS_InteractiveContext.hxx>
//
#include "OCCViewer_ClippingDlg.h"
-#include <QtxDblSpinBox.h>
+#include <QtxDoubleSpinBox.h>
#include <QtxAction.h>
#include "SUIT_Session.h"
#include "SUIT_ViewWindow.h"
+#include "SUIT_ViewManager.h"
#include "OCCViewer_ViewWindow.h"
#include "OCCViewer_ViewPort3d.h"
#include <V3d_View.hxx>
-//#include <V3d.hxx>
#include <Geom_Plane.hxx>
#include <Prs3d_Presentation.hxx>
#include <AIS_ListIteratorOfListOfInteractive.hxx>
#include <gp_Pln.hxx>
// QT Includes
-#include <qapplication.h>
-#include <qgroupbox.h>
-#include <qlayout.h>
-#include <qlabel.h>
-#include <qpushbutton.h>
-#include <qcombobox.h>
-#include <qcheckbox.h>
+#include <QApplication>
+#include <QGroupBox>
+#include <QHBoxLayout>
+#include <QVBoxLayout>
+#include <QGridLayout>
+#include <QLabel>
+#include <QPushButton>
+#include <QComboBox>
+#include <QCheckBox>
/*!
Constructor
\param modal - is this dialog modal
\param fl - flags
*/
-OCCViewer_ClippingDlg::OCCViewer_ClippingDlg( OCCViewer_ViewWindow* view, QWidget* parent, const char* name, bool modal, WFlags fl )
-: QDialog( parent, "OCCViewer_ClippingDlg", modal, WStyle_Customize | WStyle_NormalBorder | WStyle_Title | WStyle_SysMenu ),
+OCCViewer_ClippingDlg::OCCViewer_ClippingDlg( OCCViewer_ViewWindow* view, QWidget* parent, const char* name, bool modal, Qt::WindowFlags fl )
+: QDialog( parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint ),
myView( view )
{
- setCaption( tr( "Clipping" ) );
+ setObjectName( "OCCViewer_ClippingDlg" );
+ setModal( modal );
+
+ setWindowTitle( tr( "Clipping" ) );
QVBoxLayout* topLayout = new QVBoxLayout( this );
topLayout->setMargin( 11 ); topLayout->setSpacing( 6 );
/***************************************************************/
- GroupPoint = new QGroupBox( this, "GroupPoint" );
+ GroupPoint = new QGroupBox( this );
+ GroupPoint->setObjectName( "GroupPoint" );
GroupPoint->setTitle( tr("Base point") );
- GroupPoint->setColumnLayout(0, Qt::Vertical );
- GroupPoint->layout()->setSpacing( 0 );
- GroupPoint->layout()->setMargin( 0 );
- QGridLayout* GroupPointLayout = new QGridLayout( GroupPoint->layout() );
+ QGridLayout* GroupPointLayout = new QGridLayout( GroupPoint );
GroupPointLayout->setAlignment( Qt::AlignTop );
GroupPointLayout->setSpacing( 6 );
GroupPointLayout->setMargin( 11 );
const double max = 1e+16;
const double step = 5;
const int precision = -6; // PAL12789. Minus is for using 'g' double->string conversion specifier,
- // see QtxDblSpinBox::mapValueToText( double v )
+ // see QtxDoubleSpinBox::mapValueToText( double v )
- TextLabelX = new QLabel( GroupPoint, "TextLabelX" );
+ TextLabelX = new QLabel( GroupPoint );
+ TextLabelX->setObjectName( "TextLabelX" );
TextLabelX->setText( tr("X:") );
GroupPointLayout->addWidget( TextLabelX, 0, 0 );
- SpinBox_X = new QtxDblSpinBox( min, max, step, GroupPoint, "SpinBox_X" );
- SpinBox_X->setPrecision( precision );
+ SpinBox_X = new QtxDoubleSpinBox( min, max, step, GroupPoint );
+ SpinBox_X->setObjectName("SpinBox_X" );
+ SpinBox_X->setDecimals( precision );
GroupPointLayout->addWidget( SpinBox_X, 0, 1 );
- TextLabelY = new QLabel( GroupPoint, "TextLabelY" );
+ TextLabelY = new QLabel( GroupPoint );
+ TextLabelY->setObjectName( "TextLabelY" );
TextLabelY->setText( tr("Y:") );
GroupPointLayout->addWidget( TextLabelY, 0, 2 );
- SpinBox_Y = new QtxDblSpinBox( min, max, step, GroupPoint, "SpinBox_Y" );
- SpinBox_Y->setPrecision( precision );
+ SpinBox_Y = new QtxDoubleSpinBox( min, max, step, GroupPoint );
+ SpinBox_Y->setObjectName("SpinBox_Y" );
+ SpinBox_Y->setDecimals( precision );
GroupPointLayout->addWidget( SpinBox_Y, 0, 3 );
- TextLabelZ = new QLabel( GroupPoint, "TextLabelZ" );
+ TextLabelZ = new QLabel( GroupPoint );
+ TextLabelZ->setObjectName( "TextLabelZ" );
TextLabelZ->setText( tr("Z:") );
GroupPointLayout->addWidget( TextLabelZ, 0, 4 );
- SpinBox_Z = new QtxDblSpinBox( min, max, step, GroupPoint, "SpinBox_Z" );
- SpinBox_Z->setPrecision( precision );
+ SpinBox_Z = new QtxDoubleSpinBox( min, max, step, GroupPoint );
+ SpinBox_Z->setObjectName("SpinBox_Z" );
+ SpinBox_Z->setDecimals( precision );
GroupPointLayout->addWidget( SpinBox_Z, 0, 5 );
- resetButton = new QPushButton( GroupPoint, "resetButton" );
+ resetButton = new QPushButton( GroupPoint );
+ resetButton->setObjectName( "resetButton" );
resetButton->setText( tr( "Reset" ) );
GroupPointLayout->addWidget( resetButton, 0, 6 );
/***************************************************************/
- GroupDirection = new QGroupBox( this, "GroupDirection" );
+ GroupDirection = new QGroupBox( this );
+ GroupDirection->setObjectName( "GroupDirection" );
GroupDirection->setTitle( tr("Direction") );
- GroupDirection->setColumnLayout(0, Qt::Vertical );
- GroupDirection->layout()->setSpacing( 0 );
- GroupDirection->layout()->setMargin( 0 );
- QGridLayout* GroupDirectionLayout = new QGridLayout( GroupDirection->layout() );
+ QGridLayout* GroupDirectionLayout = new QGridLayout( GroupDirection );
GroupDirectionLayout->setAlignment( Qt::AlignTop );
GroupDirectionLayout->setSpacing( 6 );
GroupDirectionLayout->setMargin( 11 );
// Controls
- TextLabelDx = new QLabel( GroupDirection, "TextLabelDx" );
+ TextLabelDx = new QLabel( GroupDirection );
+ TextLabelDx->setObjectName( "TextLabelDx" );
TextLabelDx->setText( tr("Dx:") );
GroupDirectionLayout->addWidget( TextLabelDx, 0, 0 );
- SpinBox_Dx = new QtxDblSpinBox( min, max, step, GroupDirection, "SpinBox_Dx" );
- SpinBox_Dx->setPrecision( precision );
+ SpinBox_Dx = new QtxDoubleSpinBox( min, max, step, GroupDirection );
+ SpinBox_Dx->setObjectName("SpinBox_Dx" );
+ SpinBox_Dx->setDecimals( precision );
GroupDirectionLayout->addWidget( SpinBox_Dx, 0, 1 );
- TextLabelDy = new QLabel( GroupDirection, "TextLabelDy" );
+ TextLabelDy = new QLabel( GroupDirection );
+ TextLabelDy->setObjectName( "TextLabelDy" );
TextLabelDy->setText( tr("Dy:") );
GroupDirectionLayout->addWidget( TextLabelDy, 0, 2 );
- SpinBox_Dy = new QtxDblSpinBox( min, max, step, GroupDirection, "SpinBox_Dy" );
- SpinBox_Dy->setPrecision( precision );
+ SpinBox_Dy = new QtxDoubleSpinBox( min, max, step, GroupDirection );
+ SpinBox_Dy->setObjectName("SpinBox_Dy" );
+ SpinBox_Dy->setDecimals( precision );
GroupDirectionLayout->addWidget( SpinBox_Dy, 0, 3 );
- TextLabelDz = new QLabel( GroupDirection, "TextLabelDz" );
+ TextLabelDz = new QLabel( GroupDirection );
+ TextLabelDz->setObjectName( "TextLabelDz" );
TextLabelDz->setText( tr("Dz:") );
GroupDirectionLayout->addWidget( TextLabelDz, 0, 4 );
- SpinBox_Dz = new QtxDblSpinBox( min, max, step, GroupDirection, "SpinBox_Dz" );
- SpinBox_Dz->setPrecision( precision );
+ SpinBox_Dz = new QtxDoubleSpinBox( min, max, step, GroupDirection );
+ SpinBox_Dz->setObjectName("SpinBox_Dz" );
+ SpinBox_Dz->setDecimals( precision );
GroupDirectionLayout->addWidget( SpinBox_Dz, 0, 5 );
- invertButton = new QPushButton( GroupDirection, "invertButton" );
+ invertButton = new QPushButton( GroupDirection );
+ invertButton->setObjectName( "invertButton" );
invertButton->setText( tr( "Invert" ) );
GroupDirectionLayout->addWidget( invertButton, 0, 6 );
- DirectionCB = new QComboBox( GroupDirection, "DirectionCB" );
- DirectionCB->insertItem(tr("CUSTOM"));
- DirectionCB->insertItem(tr("||X-Y"));
- DirectionCB->insertItem(tr("||Y-Z"));
- DirectionCB->insertItem(tr("||Z-X"));
- GroupDirectionLayout->addMultiCellWidget( DirectionCB, 1, 1, 0, 5 );
+ DirectionCB = new QComboBox( GroupDirection );
+ DirectionCB->setObjectName( "DirectionCB" );
+ DirectionCB->insertItem(DirectionCB->count(),tr("CUSTOM"));
+ DirectionCB->insertItem(DirectionCB->count(),tr("||X-Y"));
+ DirectionCB->insertItem(DirectionCB->count(),tr("||Y-Z"));
+ DirectionCB->insertItem(DirectionCB->count(),tr("||Z-X"));
+ GroupDirectionLayout->addWidget( DirectionCB, 1, 0, 1, 6 );
/***************************************************************/
- PreviewChB = new QCheckBox( tr("Preview") ,this, "PreviewChB" );
+ PreviewChB = new QCheckBox( tr("Preview") ,this );
+ PreviewChB->setObjectName( "PreviewChB" );
PreviewChB->setChecked( true );
/***************************************************************/
- QGroupBox* GroupButtons = new QGroupBox( this, "GroupButtons" );
- GroupButtons->setColumnLayout(0, Qt::Vertical );
- GroupButtons->layout()->setMargin( 0 ); GroupButtons->layout()->setSpacing( 0 );
- QHBoxLayout* GroupButtonsLayout = new QHBoxLayout( GroupButtons->layout() );
+ QGroupBox* GroupButtons = new QGroupBox( this );
+ GroupButtons->setObjectName( "GroupButtons" );
+ QHBoxLayout* GroupButtonsLayout = new QHBoxLayout( GroupButtons );
GroupButtonsLayout->setAlignment( Qt::AlignTop );
GroupButtonsLayout->setMargin( 11 ); GroupButtonsLayout->setSpacing( 6 );
- buttonApply = new QPushButton( GroupButtons, "buttonApply" );
+ buttonApply = new QPushButton( GroupButtons );
+ buttonApply->setObjectName( "buttonApply" );
buttonApply->setText( tr( "BUT_APPLY" ) );
buttonApply->setAutoDefault( TRUE );
buttonApply->setDefault( TRUE );
GroupButtonsLayout->addStretch();
- buttonClose = new QPushButton( GroupButtons, "buttonClose" );
+ buttonClose = new QPushButton( GroupButtons );
+ buttonClose->setObjectName( "buttonClose" );
buttonClose->setText( tr( "BUT_CLOSE" ) );
buttonClose->setAutoDefault( TRUE );
GroupButtonsLayout->addWidget( buttonClose );
+
/***************************************************************/
topLayout->addWidget( GroupPoint );
aView3d->SetPlaneOn( myClippingPlane );
if (!myView->isCuttingPlane())
- myAction->setOn( false );
+ myAction->setChecked( false );
QDialog::closeEvent( e );
}
aView3d->SetPlaneOn( myClippingPlane );
if (!myView->isCuttingPlane())
- myAction->setOn( false );
+ myAction->setChecked( false );
reject();
}
isFound = true;
double xmin, ymin, zmin, xmax, ymax, zmax;
aPrs->MinMaxValues( xmin, ymin, zmin, xmax, ymax, zmax );
- aXMin = QMIN( aXMin, xmin ); aXMax = QMAX( aXMax, xmax );
- aYMin = QMIN( aYMin, ymin ); aYMax = QMAX( aYMax, ymax );
- aZMin = QMIN( aZMin, zmin ); aZMax = QMAX( aZMax, zmax );
+ aXMin = qMin( aXMin, xmin ); aXMax = qMax( aXMax, xmax );
+ aYMin = qMin( aYMin, ymin ); aYMax = qMax( aYMax, ymax );
+ aZMin = qMin( aZMin, zmin ); aZMax = qMax( aZMax, zmax );
}
}
}
void OCCViewer_ClippingDlg::onViewShow()
{
- if(myAction->isOn())
+ if(myAction->isChecked())
show();
else
hide();
#include "OCCViewer.h"
-#include <qdialog.h>
+#include <QDialog>
#include <AIS_Plane.hxx>
#include <V3d_Plane.hxx>
class QPushButton;
class QComboBox;
class QCheckBox;
-class QtxDblSpinBox;
+class QtxDoubleSpinBox;
class QtxAction;
class OCCViewer_ViewWindow;
Q_OBJECT
public:
- OCCViewer_ClippingDlg(OCCViewer_ViewWindow* , QWidget* parent = 0, const char* name = 0, bool modal = FALSE, WFlags fl = 0);
+ OCCViewer_ClippingDlg(OCCViewer_ViewWindow* , QWidget* parent = 0, const char* name = 0, bool modal = FALSE, Qt::WindowFlags fl = 0);
~OCCViewer_ClippingDlg();
void SetAction( QtxAction* theAction ) { myAction = theAction; }
QLabel* TextLabelX;
QLabel* TextLabelY;
QLabel* TextLabelZ;
- QtxDblSpinBox* SpinBox_X;
- QtxDblSpinBox* SpinBox_Y;
- QtxDblSpinBox* SpinBox_Z;
+ QtxDoubleSpinBox* SpinBox_X;
+ QtxDoubleSpinBox* SpinBox_Y;
+ QtxDoubleSpinBox* SpinBox_Z;
QPushButton* resetButton;
QGroupBox* GroupDirection;
QLabel* TextLabelDx;
QLabel* TextLabelDy;
QLabel* TextLabelDz;
- QtxDblSpinBox* SpinBox_Dx;
- QtxDblSpinBox* SpinBox_Dy;
- QtxDblSpinBox* SpinBox_Dz;
+ QtxDoubleSpinBox* SpinBox_Dx;
+ QtxDoubleSpinBox* SpinBox_Dy;
+ QtxDoubleSpinBox* SpinBox_Dz;
QPushButton* invertButton;
QComboBox* DirectionCB;
#include "OCCViewer_ViewModel.h"
#include "OCCViewer_ViewPort3d.h"
-#include <qpushbutton.h>
-#include <qlayout.h>
-#include <qpainter.h>
-#include <qimage.h>
+#include <QPushButton>
+#include <QGridLayout>
+#include <QHBoxLayout>
+#include <QListWidgetItem>
+#include <QEvent>
+#include <QKeyEvent>
/*!
Constructor
OCCViewer_CreateRestoreViewDlg::OCCViewer_CreateRestoreViewDlg( QWidget* aWin, OCCViewer_Viewer* curModel )
: QDialog( aWin )
{
- setCaption( tr( "CAPTION" ) );
+ setWindowTitle( tr( "CAPTION" ) );
myParametersMap = curModel->getViewAspects();
setFixedSize( 400, 300 );
- QGridLayout* aGrid = new QGridLayout( this, 2, 1, 5, 10 );
+ QGridLayout* aGrid = new QGridLayout( this );
+ aGrid->setMargin( 5 );
+ aGrid->setSpacing( 10 );
QWidget* aWidget1 = new QWidget( this );
QWidget* aWidget2 = new QWidget( this );
QHBoxLayout* aLayout = new QHBoxLayout( aWidget1 );
- myListBox = new QtxListBox( aWidget1 );
+ myListBox = new QListWidget( aWidget1 );
myListBox->installEventFilter( this );
myCurViewPort = new OCCViewer_ViewPort3d( aWidget1, curModel->getViewer3d(), V3d_ORTHOGRAPHIC );
myCurViewPort->getView()->SetBackgroundColor( Quantity_NOC_BLACK );
- myListBox->setEditEnabled( 1 );
+ myListBox->setEditTriggers( QAbstractItemView::DoubleClicked );
if ( aQuantityOfItems )
{
myListBox->clear();
- for( int i = 0; i < aQuantityOfItems; i++ )
- myListBox->insertItem( myParametersMap[ i ].name );
+ for( int i = 0; i < aQuantityOfItems; i++ ) {
+ myListBox->insertItem( i, myParametersMap[ i ].name );
+ myListBox->item( i )->setFlags( myListBox->item( i )->flags() | Qt::ItemIsEditable );
+ }
changeImage( myListBox->item( 0 ) );
}
else
{
myListBox->clear();
- myListBox->insertItem( "No Items", 0 );
- myListBox->setEditEnabled( 0 );
+ myListBox->insertItem( 0, "No Items" );
}
- connect( myListBox, SIGNAL( clicked( QListBoxItem* ) ), this, SLOT( changeImage( QListBoxItem* ) ) );
- connect( myListBox, SIGNAL( itemEdited( QListBoxItem* ) ), this, SLOT( editItemText( QListBoxItem* ) ) );
+ connect( myListBox, SIGNAL( itemClicked( QListBoxItem* ) ), this, SLOT( changeImage( QListBoxItem* ) ) );
+ connect( myListBox, SIGNAL( itemChanged( QListBoxItem* ) ), this, SLOT( editItemText( QListBoxItem* ) ) );
aLayout->addWidget( myListBox );
aLayout->addWidget( myCurViewPort, 30 );
- QHBoxLayout* aButtonLayout = new QHBoxLayout( aWidget2, 0, 5 );
+ QHBoxLayout* aButtonLayout = new QHBoxLayout( aWidget2 );
+ aButtonLayout->setMargin( 0 );
+ aButtonLayout->setSpacing( 5 );
QPushButton* theOk = new QPushButton( tr( "Ok" ), aWidget2 ); theOk->setAutoDefault( false );
QPushButton* theCancel = new QPushButton( tr( "Cancel" ), aWidget2 ); theCancel->setAutoDefault( false );
Changes image in accordance with item
\param curItem - item contains info about view parameters
*/
-void OCCViewer_CreateRestoreViewDlg::changeImage( QListBoxItem* curItem )
+void OCCViewer_CreateRestoreViewDlg::changeImage( QListWidgetItem* curItem )
{
- if( curItem && myListBox->isEditEnabled() )
+ if( curItem && ( curItem->flags() & Qt::ItemIsEditable ) )
+ {
+ int lowLevel = -1;
+ int highLevel = -1;
+ int index = curItem->listWidget()->row( curItem );
+ if( myKeyFlag == 2 )
+ {
+ for( int i = 0; i < (int)myListBox->count(); i++ )
+ {
+ if( myListBox->item( i )->isSelected() && i != index )
{
- int lowLevel = -1;
- int highLevel = -1;
- int index = curItem->listBox()->index( curItem );
- if( myKeyFlag == 2 )
- {
- for( int i = 0; i < (int)myListBox->count(); i++ )
- {
- if( myListBox->isSelected( i ) && i != index )
- {
- myListBox->clearSelection();
- if( i > index )
- {
- lowLevel = index;
- highLevel = i;
- }
- else
- {
- lowLevel = i;
- highLevel = index;
- }
- for( int j = lowLevel; j <= highLevel; j++ )
- myListBox->setSelected( j, TRUE );
- break;
- }
- if( myListBox->isSelected( i ) && i == index )
- myListBox->setSelected( i, TRUE );
- }
- }
-
- Handle(V3d_View) aView3d = myCurViewPort->getView();
- myCurrentItem = myParametersMap[ index ];
-
- Standard_Boolean prev = aView3d->SetImmediateUpdate( Standard_False );
- aView3d->SetScale( myCurrentItem.scale );
- aView3d->SetCenter( myCurrentItem.centerX, myCurrentItem.centerY );
- aView3d->SetProj( myCurrentItem.projX, myCurrentItem.projY, myCurrentItem.projZ );
- aView3d->SetTwist( myCurrentItem.twist );
- aView3d->SetAt( myCurrentItem.atX, myCurrentItem.atY, myCurrentItem.atZ );
- aView3d->SetImmediateUpdate( prev );
- aView3d->SetEye( myCurrentItem.eyeX, myCurrentItem.eyeY, myCurrentItem.eyeZ );
- }
+ myListBox->clearSelection();
+ if( i > index )
+ {
+ lowLevel = index;
+ highLevel = i;
+ }
+ else
+ {
+ lowLevel = i;
+ highLevel = index;
+ }
+ for( int j = lowLevel; j <= highLevel; j++ )
+ myListBox->item( j )->setSelected( TRUE );
+ break;
+ }
+ if( myListBox->item( i )->isSelected() && i == index )
+ myListBox->item( i )->setSelected( TRUE );
+ }
+ }
+
+ Handle(V3d_View) aView3d = myCurViewPort->getView();
+ myCurrentItem = myParametersMap[ index ];
+
+ Standard_Boolean prev = aView3d->SetImmediateUpdate( Standard_False );
+ aView3d->SetScale( myCurrentItem.scale );
+ aView3d->SetCenter( myCurrentItem.centerX, myCurrentItem.centerY );
+ aView3d->SetProj( myCurrentItem.projX, myCurrentItem.projY, myCurrentItem.projZ );
+ aView3d->SetTwist( myCurrentItem.twist );
+ aView3d->SetAt( myCurrentItem.atX, myCurrentItem.atY, myCurrentItem.atZ );
+ aView3d->SetImmediateUpdate( prev );
+ aView3d->SetEye( myCurrentItem.eyeX, myCurrentItem.eyeY, myCurrentItem.eyeZ );
+ }
}
/*!
*/
viewAspect OCCViewer_CreateRestoreViewDlg::currentItem() const
{
- return myCurrentItem;
+ return myCurrentItem;
}
/*!
*/
void OCCViewer_CreateRestoreViewDlg::deleteSelectedItems()
{
- if( myListBox->count() && myListBox->isEditEnabled() )
- {
- int curIndex = -1;
- for( int i = 0; i < (int)myListBox->count(); i++ )
- if( myListBox->isSelected( i ) )
- {
- myListBox->removeItem( i );
- for( int j = i; j < (int)myParametersMap.count(); j++ )
- if( j != myParametersMap.count() - 1 )
- myParametersMap[ j ] = myParametersMap[ j + 1 ];
- else
- myParametersMap.remove( myParametersMap.at(j) );
- if( i != myListBox->count() )
- curIndex = i;
- else
- curIndex = i - 1;
- i--;
- }
- if( curIndex >= 0 )
- {
- myListBox->setCurrentItem( curIndex );
- changeImage( myListBox->item( curIndex ) );
- }
- }
- if( !myListBox->count() )
- {
- myListBox->clear();
- myListBox->insertItem( "No Items", 0 );
- myListBox->setEditEnabled( 0 );
- }
+ if( myListBox->count() )
+ {
+ int curIndex = -1;
+ for( int i = 0; i < (int)myListBox->count(); i++ )
+ if( myListBox->item( i )->isSelected() && ( myListBox->item( i )->flags() & Qt::ItemIsEditable ) )
+ {
+ QListWidgetItem* anItemToDelete = myListBox->takeItem( i );
+ delete anItemToDelete;
+ for( int j = i; j < (int)myParametersMap.count(); j++ )
+ if( j != myParametersMap.count() - 1 )
+ myParametersMap[ j ] = myParametersMap[ j + 1 ];
+ else
+ myParametersMap.removeAt( j );
+ if( i != myListBox->count() )
+ curIndex = i;
+ else
+ curIndex = i - 1;
+ i--;
+ }
+ if( curIndex >= 0 )
+ {
+ myListBox->setCurrentItem( myListBox->item( curIndex ) );
+ changeImage( myListBox->item( curIndex ) );
+ }
+ }
+ if( !myListBox->count() )
+ {
+ myListBox->clear();
+ myListBox->insertItem( 0, "No Items" );
+ }
}
/*!
*/
void OCCViewer_CreateRestoreViewDlg::clearList()
{
- myListBox->clear();
- myListBox->insertItem( "No Items", 0 );
- myListBox->setEditEnabled( 0 );
-
- myParametersMap.clear();
+ myListBox->clear();
+ myListBox->insertItem( 0, "No Items" );
+
+ myParametersMap.clear();
}
/*!
*/
const viewAspectList& OCCViewer_CreateRestoreViewDlg::parameters() const
{
- return myParametersMap;
+ return myParametersMap;
}
/*!
Renames key of view aspect map in accordance with item name
\param anItem - item
*/
-void OCCViewer_CreateRestoreViewDlg::editItemText( QListBoxItem* anItem )
+void OCCViewer_CreateRestoreViewDlg::editItemText( QListWidgetItem* anItem )
{
- int index = anItem->listBox()->index( anItem );
- myParametersMap[ index ].name = anItem->text().latin1();
+ int index = anItem->listWidget()->row( anItem );
+ myParametersMap[ index ].name = anItem->text().toLatin1();
}
/*!
*/
bool OCCViewer_CreateRestoreViewDlg::eventFilter( QObject* anObj, QEvent* anEv )
{
- if( anEv->type() == QEvent::KeyPress )
- {
- QKeyEvent* aKeyEv = ( QKeyEvent* )anEv;
- if( aKeyEv->key() == Qt::Key_Control )
- {
- myKeyFlag = 1;
- myListBox->setSelectionMode( QListBox::Multi );
- }
- else if( aKeyEv->key() == Qt::Key_Shift )
- {
- myKeyFlag = 2;
- myListBox->setSelectionMode( QListBox::Multi );
- }
- else
- myListBox->setSelectionMode( QListBox::Single );
- }
- if( anEv->type() == QEvent::KeyRelease )
- myKeyFlag = 0;
-
- if( !myKeyFlag )
- {
- if( anEv->type() == QEvent::KeyPress || anEv->type() == QEvent::MouseButtonPress )
- myListBox->setSelectionMode( QListBox::Single );
- }
- return QWidget::eventFilter( anObj, anEv );
+ if( anEv->type() == QEvent::KeyPress )
+ {
+ QKeyEvent* aKeyEv = ( QKeyEvent* )anEv;
+ if( aKeyEv->key() == Qt::Key_Control )
+ {
+ myKeyFlag = 1;
+ myListBox->setSelectionMode( QAbstractItemView::MultiSelection );
+ }
+ else if( aKeyEv->key() == Qt::Key_Shift )
+ {
+ myKeyFlag = 2;
+ myListBox->setSelectionMode( QAbstractItemView::MultiSelection );
+ }
+ else
+ myListBox->setSelectionMode( QAbstractItemView::SingleSelection );
+ }
+ if( anEv->type() == QEvent::KeyRelease )
+ myKeyFlag = 0;
+
+ if( !myKeyFlag )
+ {
+ if( anEv->type() == QEvent::KeyPress || anEv->type() == QEvent::MouseButtonPress )
+ myListBox->setSelectionMode( QAbstractItemView::SingleSelection );
+ }
+ return QWidget::eventFilter( anObj, anEv );
}
/*!
*/
void OCCViewer_CreateRestoreViewDlg::OKpressed()
{
- emit dlgOk();
- accept();
+ emit dlgOk();
+ accept();
}
#include "OCCViewer_ViewWindow.h"
#include <QtxDialog.h>
-#include <QtxListBox.h>
#include <SUIT_Application.h>
-#include <qmap.h>
-#include <qvbox.h>
-#include <qdialog.h>
-#include <qlistbox.h>
-#include <qstringlist.h>
+#include <QDialog>
+#include <QListWidget>
class OCCViewer_ViewPort3d;
+class QListWidgetItem;
+
#ifdef WIN32
#pragma warning( disable:4251 )
#endif
OCCViewer_CreateRestoreViewDlg( QWidget*, OCCViewer_Viewer* );
virtual ~OCCViewer_CreateRestoreViewDlg();
- const viewAspectList& parameters() const;
- viewAspect currentItem() const;
- virtual bool eventFilter( QObject*, QEvent* );
+ const viewAspectList& parameters() const;
+ viewAspect currentItem() const;
+ virtual bool eventFilter( QObject*, QEvent* );
public slots:
void OKpressed();
void clearList();
- void editItemText( QListBoxItem* );
- void changeImage( QListBoxItem* );
+ void editItemText( QListWidgetItem* );
+ void changeImage( QListWidgetItem* );
void deleteSelectedItems();
signals:
void dlgOk();
private:
- int myKeyFlag;
- QtxListBox* myListBox;
+ int myKeyFlag;
+ QListWidget* myListBox;
OCCViewer_ViewPort3d* myCurViewPort;
- viewAspect myCurrentItem;
- viewAspectList myParametersMap;
+ viewAspect myCurrentItem;
+ viewAspectList myParametersMap;
};
#ifdef WIN32
#include "OCCViewer_ViewWindow.h"
-#include <qlineedit.h>
-#include <qgroupbox.h>
-#include <qlabel.h>
-#include <qpushbutton.h>
-#include <qlayout.h>
-#include <qvalidator.h>
-#include <qbuttongroup.h>
-#include <qobjectlist.h>
-#include <qcheckbox.h>
-#include <qhbox.h>
+#include <QLineEdit>
+#include <QGroupBox>
+#include <QLabel>
+#include <QPushButton>
+#include <QGridLayout>
+#include <QDoubleValidator>
+#include <QCheckBox>
+#include <QHBoxLayout>
/*!
Constructor
\param modal - is this dialog modal
\param fl - flags
*/
-OCCViewer_SetRotationPointDlg::OCCViewer_SetRotationPointDlg( OCCViewer_ViewWindow* view, QWidget* parent, const char* name, bool modal, WFlags fl )
-: QDialog( parent, "OCCViewer_SetRotationPointDlg", modal, WStyle_Customize | WStyle_NormalBorder | WStyle_Title | WStyle_SysMenu ),
+OCCViewer_SetRotationPointDlg::OCCViewer_SetRotationPointDlg( OCCViewer_ViewWindow* view, QWidget* parent, const char* name, bool modal, Qt::WindowFlags fl )
+: QDialog( parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint ),
myView( view )
{
- setCaption(tr("CAPTION"));
+ setObjectName( "OCCViewer_SetRotationPointDlg" );
+ setModal( modal );
+
+ setWindowTitle(tr("CAPTION"));
setSizeGripEnabled(TRUE);
// Create layout for this dialog
layoutDlg->setMargin(11);
// Create check box "Use Bounding Box Center"
- QHBox* aCheckBox = new QHBox(this);
+ QHBoxLayout* aCheckBox = new QHBoxLayout(this);
- myIsBBCenter = new QCheckBox(tr("USE_BBCENTER"), aCheckBox);
+ myIsBBCenter = new QCheckBox(tr("USE_BBCENTER"));
myIsBBCenter->setChecked(true);
+ aCheckBox->addWidget(myIsBBCenter);
connect(myIsBBCenter, SIGNAL(stateChanged(int)), SLOT(onBBCenterChecked()));
// Create croup button with radio buttons
- myGroupSelButton = new QButtonGroup(2,Qt::Vertical,"",this);
- myGroupSelButton->setMargin(11);
+ myGroupBoxSel = new QGroupBox( "", this );
+ QVBoxLayout *vbox = new QVBoxLayout;
+ vbox->setMargin(11);
+ vbox->addStretch(1);
// Create "Set to Origin" button
- myToOrigin = new QPushButton(myGroupSelButton);
- myToOrigin->setText(tr("LBL_TOORIGIN"));
+ myToOrigin = new QPushButton(tr("LBL_TOORIGIN"));
+ vbox->addWidget(myToOrigin);
connect(myToOrigin, SIGNAL(clicked()), this, SLOT(onToOrigin()));
// Create "Select Point from View" button
- mySelectPoint = new QPushButton(myGroupSelButton);
- mySelectPoint->setText(tr("LBL_SELECTPOINT"));
- mySelectPoint->setToggleButton(true);
+ mySelectPoint = new QPushButton(tr("LBL_SELECTPOINT"));
+ mySelectPoint->setCheckable(true);
+ vbox->addWidget(mySelectPoint);
connect(mySelectPoint, SIGNAL(clicked()), this, SLOT(onSelectPoint()));
+ myGroupBoxSel->setLayout(vbox);
+
// Create croup box with grid layout
- myGroupBoxCoord = new QGroupBox(this, "GroupBox");
+ myGroupBoxCoord = new QGroupBox(this);
+ myGroupBoxCoord->setObjectName("GroupBox");
QHBoxLayout* aHBoxLayout = new QHBoxLayout(myGroupBoxCoord);
aHBoxLayout->setMargin(11);
aHBoxLayout->setSpacing(6);
// "X" coordinate
- QLabel* TextLabelX = new QLabel (tr("LBL_X"), myGroupBoxCoord, "TextLabelX");
+ QLabel* TextLabelX = new QLabel (tr("LBL_X"), myGroupBoxCoord );
+ TextLabelX->setObjectName("TextLabelX");
TextLabelX->setFixedWidth(15);
myX = new QLineEdit(myGroupBoxCoord);
myX->setValidator(new QDoubleValidator(myX));
connect(myX, SIGNAL(textChanged(const QString&)), this, SLOT(onCoordChanged()));
// "Y" coordinate
- QLabel* TextLabelY = new QLabel (tr("LBL_Y"), myGroupBoxCoord, "TextLabelY");
+ QLabel* TextLabelY = new QLabel (tr("LBL_Y"), myGroupBoxCoord );
+ TextLabelY->setObjectName("TextLabelY");
TextLabelY->setFixedWidth(15);
myY = new QLineEdit(myGroupBoxCoord);
myY->setValidator(new QDoubleValidator(myY));
connect(myY, SIGNAL(textChanged(const QString&)), this, SLOT(onCoordChanged()));
// "Z" coordinate
- QLabel* TextLabelZ = new QLabel (tr("LBL_Z"), myGroupBoxCoord, "TextLabelZ");
+ QLabel* TextLabelZ = new QLabel (tr("LBL_Z"), myGroupBoxCoord );
+ TextLabelZ->setObjectName("TextLabelZ");
TextLabelZ->setFixedWidth(15);
myZ = new QLineEdit(myGroupBoxCoord);
myZ->setValidator(new QDoubleValidator(myZ));
aHBoxLayout2->setMargin(11);
aHBoxLayout2->setSpacing(6);
- QPushButton* m_bClose = new QPushButton(tr("&Close"), aGroupBox, "m_bClose");
+ QPushButton* m_bClose = new QPushButton(tr("&Close"), aGroupBox );
+ m_bClose->setObjectName("m_bClose");
m_bClose->setAutoDefault(TRUE);
m_bClose->setFixedSize(m_bClose->sizeHint());
connect(m_bClose, SIGNAL(clicked()), this, SLOT(onClickClose()));
aHBoxLayout2->addWidget(m_bClose);
// Layout top level widgets
- layoutDlg->addWidget(aCheckBox,0,0);
- layoutDlg->addWidget(myGroupSelButton,1,0);
+ layoutDlg->addLayout(aCheckBox,0,0);
+ layoutDlg->addWidget(myGroupBoxSel,1,0);
layoutDlg->addWidget(myGroupBoxCoord,2,0);
layoutDlg->addWidget(aGroupBox,3,0);
- setEnabled(myGroupSelButton,!myIsBBCenter->isChecked());
+ setEnabled(myGroupBoxSel,!myIsBBCenter->isChecked());
setEnabled(myGroupBoxCoord,!myIsBBCenter->isChecked());
this->resize(400, this->sizeHint().height());
OCCViewer_SetRotationPointDlg
::setEnabled(QGroupBox* theGrp, const bool theState)
{
- QObjectList aChildren(*theGrp->children());
+ QObjectList aChildren(theGrp->children());
QObject* anObj;
- for(anObj = aChildren.first(); anObj !=0; anObj = aChildren.next())
+ for(int i = 0; i < aChildren.size(); i++)
{
+ anObj = aChildren.at(i);
if (anObj !=0 && anObj->inherits("QLineEdit"))
((QLineEdit*)anObj)->setReadOnly(!theState);
if (anObj !=0 && anObj->inherits("QPushButton"))
OCCViewer_SetRotationPointDlg
::onBBCenterChecked()
{
- setEnabled(myGroupSelButton,!myIsBBCenter->isChecked());
+ setEnabled(myGroupBoxSel,!myIsBBCenter->isChecked());
setEnabled(myGroupBoxCoord,!myIsBBCenter->isChecked());
if ( myIsBBCenter->isChecked() )
{
- if ( mySelectPoint->state() == QButton::On )
+ if ( mySelectPoint->isChecked() )
mySelectPoint->toggle();
myView->activateSetRotationGravity();
}
OCCViewer_SetRotationPointDlg
::onToOrigin()
{
- if ( mySelectPoint->state() == QButton::On )
+ if ( mySelectPoint->isChecked() )
mySelectPoint->toggle();
setCoords();
myView->activateSetRotationSelected(myX->text().toDouble(),
OCCViewer_SetRotationPointDlg
::onSelectPoint()
{
- if ( mySelectPoint->state() == QButton::On )
+ if ( mySelectPoint->isChecked() )
myView->activateStartPointSelection();
else
mySelectPoint->toggle();
{
if ( !myIsBBCenter->isChecked() )
{
- if ( mySelectPoint->state() == QButton::On
+ if ( mySelectPoint->isChecked()
&&
( myX->hasFocus() || myY->hasFocus() || myZ->hasFocus() ) )
mySelectPoint->toggle();
OCCViewer_SetRotationPointDlg
::onClickClose()
{
- myAction->setOn( false );
+ myAction->setChecked( false );
reject();
}
OCCViewer_SetRotationPointDlg
::onViewShow()
{
- if(myAction->isOn())
+ if(myAction->isChecked())
show();
else
hide();
#include "OCCViewer.h"
-#include <qdialog.h>
+#include <QDialog>
class QtxAction;
class QLineEdit;
class QPushButton;
class QGroupBox;
-class QButtonGroup;
class QCheckBox;
class OCCViewer_ViewWindow;
public:
OCCViewer_SetRotationPointDlg(OCCViewer_ViewWindow* , QWidget* parent = 0,
- const char* name = 0, bool modal = FALSE, WFlags fl = 0);
+ const char* name = 0, bool modal = FALSE, Qt::WindowFlags fl = 0);
~OCCViewer_SetRotationPointDlg();
void SetAction( QtxAction* theAction ) { myAction = theAction; }
QCheckBox* myIsBBCenter;
- QButtonGroup* myGroupSelButton;
+ QGroupBox * myGroupBoxSel;
QPushButton* myToOrigin;
QPushButton* mySelectPoint;
Fills popup menu with custom actions
\param popup - popup menu to be filled with
*/
-void OCCViewer_ViewManager::contextMenuPopup( QPopupMenu* popup )
+void OCCViewer_ViewManager::contextMenuPopup( QMenu* popup )
{
SUIT_ViewManager::contextMenuPopup( popup );
// if it is necessary invoke method CreatePopup of ViewPort
OCCViewer_Viewer* getOCCViewer() { return (OCCViewer_Viewer*) myViewModel; }
- virtual void contextMenuPopup( QPopupMenu* );
+ virtual void contextMenuPopup( QMenu* );
};
#endif
#include "OCCViewer_ViewPort3d.h"
#include "SUIT_ViewWindow.h"
+#include "SUIT_ViewManager.h"
#include "SUIT_Desktop.h"
#include "SUIT_Session.h"
-#include <qpainter.h>
-#include <qapplication.h>
-#include <qcolordialog.h>
-#include <qpalette.h>
-#include <qpopupmenu.h>
+#include <QPainter>
+#include <QApplication>
+#include <QColorDialog>
+#include <QPalette>
+#include <QMenu>
+#include <QMouseEvent>
+#include <QToolBar>
#include <AIS_Axis.hxx>
#include <AIS_Drawer.hxx>
+#include <AIS_ListOfInteractive.hxx>
#include <AIS_ListIteratorOfListOfInteractive.hxx>
#include <Geom_Axis2Placement.hxx>
SUIT_ViewModel::setViewManager(theViewManager);
if (theViewManager) {
connect(theViewManager, SIGNAL(mousePress(SUIT_ViewWindow*, QMouseEvent*)),
- this, SLOT(onMousePress(SUIT_ViewWindow*, QMouseEvent*)));
+ this, SLOT(onMousePress(SUIT_ViewWindow*, QMouseEvent*)));
connect(theViewManager, SIGNAL(mouseMove(SUIT_ViewWindow*, QMouseEvent*)),
this, SLOT(onMouseMove(SUIT_ViewWindow*, QMouseEvent*)));
myEndPnt.setX(theEvent->x()); myEndPnt.setY(theEvent->y());
OCCViewer_ViewWindow* aView = (OCCViewer_ViewWindow*) theWindow;
- bool aHasShift = (theEvent->state() & Qt::ShiftButton);
+ bool aHasShift = (theEvent->modifiers() & Qt::ShiftModifier);
if (!aHasShift) emit deselection();
if ( !myViewManager )
return;
- QPtrVector<SUIT_ViewWindow> wins = myViewManager->getViews();
+ QVector<SUIT_ViewWindow*> wins = myViewManager->getViews();
for ( int i = 0; i < (int)wins.count(); i++ )
{
- OCCViewer_ViewWindow* win = ::qt_cast<OCCViewer_ViewWindow*>( wins.at( i ) );
+ OCCViewer_ViewWindow* win = ::qobject_cast<OCCViewer_ViewWindow*>( wins.at( i ) );
if ( win )
win->updateEnabledDrawMode();
}
if ( !myViewManager )
return;
- QPtrVector<SUIT_ViewWindow> wins = myViewManager->getViews();
+ QVector<SUIT_ViewWindow*> wins = myViewManager->getViews();
for ( int i = 0; i < (int)wins.count(); i++ )
{
- OCCViewer_ViewWindow* win = ::qt_cast<OCCViewer_ViewWindow*>( wins.at( i ) );
+ OCCViewer_ViewWindow* win = ::qobject_cast<OCCViewer_ViewWindow*>( wins.at( i ) );
if ( win )
win->updateEnabledDrawMode();
}
/*!
Builds popup for occ viewer
*/
-void OCCViewer_Viewer::contextMenuPopup(QPopupMenu* thePopup)
+void OCCViewer_Viewer::contextMenuPopup(QMenu* thePopup)
{
- thePopup->insertItem( tr( "MEN_DUMP_VIEW" ), this, SLOT( onDumpView() ) );
- thePopup->insertItem( tr( "MEN_CHANGE_BACKGROUD" ), this, SLOT( onChangeBgColor() ) );
+ thePopup->addAction( tr( "MEN_DUMP_VIEW" ), this, SLOT( onDumpView() ) );
+ thePopup->addAction( tr( "MEN_CHANGE_BACKGROUD" ), this, SLOT( onChangeBgColor() ) );
- thePopup->insertSeparator();
+ thePopup->addSeparator();
OCCViewer_ViewWindow* aView = (OCCViewer_ViewWindow*)(myViewManager->getActiveView());
if ( aView && !aView->getToolBar()->isVisible() )
- thePopup->insertItem( tr( "MEN_SHOW_TOOLBAR" ), this, SLOT( onShowToolbar() ) );
+ thePopup->addAction( tr( "MEN_SHOW_TOOLBAR" ), this, SLOT( onShowToolbar() ) );
}
/*!
#ifndef OCCVIEWER_VIEWMODEL_H
#define OCCVIEWER_VIEWMODEL_H
-#include <qcolor.h>
-#include <qcursor.h>
+#include <QColor>
+#include <QPoint>
#include "OCCViewer.h"
#include <V3d_View.hxx>
#include <AIS_Trihedron.hxx>
-#include <AIS_ListOfInteractive.hxx>
#include <AIS_InteractiveContext.hxx>
+class QMouseEvent;
+
class SUIT_ViewWindow;
class SUIT_Desktop;
class OCCViewer_ViewWindow;
+class AIS_ListOfInteractive;
+
struct viewAspect
{
public:
QString name;
};
-typedef QValueList<viewAspect> viewAspectList;
+typedef QList<viewAspect> viewAspectList;
#ifdef WIN32
#pragma warning( disable:4251 )
void update();
- virtual SUIT_ViewWindow* createView(SUIT_Desktop* theDesktop);
-
- virtual void setViewManager(SUIT_ViewManager* theViewManager);
+ virtual SUIT_ViewWindow* createView(SUIT_Desktop* theDesktop);
+
+ virtual void setViewManager(SUIT_ViewManager* theViewManager);
virtual QString getType() const { return Type(); }
- virtual void contextMenuPopup(QPopupMenu*);
+ virtual void contextMenuPopup(QMenu*);
void getSelectedObjects(AIS_ListOfInteractive& theList);
void setObjectsSelected(const AIS_ListOfInteractive& theList);
- void setSelected(const Handle(AIS_InteractiveObject)& theIO)
- { myAISContext->SetSelected(theIO);}
+ void setSelected(const Handle(AIS_InteractiveObject)& theIO) { myAISContext->SetSelected(theIO);}
void performSelectionChanged();
// emit signal selectionChanged
Handle(AIS_Trihedron) getTrihedron() const { return myTrihedron; }
void enableSelection(bool isEnabled);
- bool isSelectionEnabled() const
- { return mySelectionEnabled; }
+ bool isSelectionEnabled() const { return mySelectionEnabled; }
void enableMultiselection(bool isEnable);
- bool isMultiSelectionEnabled() const
- { return myMultiSelectionEnabled; }
+ bool isMultiSelectionEnabled() const { return myMultiSelectionEnabled; }
- int getSelectionCount() const
- { return (!myAISContext.IsNull())? myAISContext->NbSelected():0; }
+ int getSelectionCount() const { return (!myAISContext.IsNull())? myAISContext->NbSelected():0; }
/* Selection management */
- bool highlight( const Handle(AIS_InteractiveObject)&, bool, bool=true );
- bool unHighlightAll( bool=true );
+ bool highlight( const Handle(AIS_InteractiveObject)&, bool, bool=true );
+ bool unHighlightAll( bool=true );
bool isInViewer( const Handle(AIS_InteractiveObject)&, bool=false );
bool isVisible( const Handle(AIS_InteractiveObject)& );
#include "SUIT_Session.h"
-#include <qrect.h>
-#include <qcursor.h>
-#include <qpixmap.h>
-#include <qpainter.h>
-#include <qintdict.h>
-#include <qpopupmenu.h>
-#include <qcolordialog.h>
+#include <QColor>
+#include <QRect>
+#include <QPixmap>
+#include <QPainter>
+#include <QMultiHash>
+#include <QMenu>
+#include <QColorDialog>
+#include <QColormap>
+#include <QCoreApplication>
+#include <QX11Info>
#include <stdlib.h>
CMapEntry::~CMapEntry()
{
if ( alloc )
- XFreeColormap( QPaintDevice::x11AppDisplay(), cmap );
+ XFreeColormap( QX11Info::display(), cmap );
}
-static QIntDict<CMapEntry> *cmap_dict = 0;
+static QMultiHash<int,CMapEntry> *cmap_dict = 0;
static bool mesa_gl = false;
static void cleanup_cmaps()
{
if ( !cmap_dict )
return;
- cmap_dict->setAutoDelete( true );
+ //while (!cmap_dict->isEmpty())
+ // cmap_dict->erase(cmap_dict->begin());
+ cmap_dict->clear();
delete cmap_dict;
cmap_dict = 0;
}
static Colormap choose_cmap( Display *dpy, XVisualInfo *vi )
{
- if ( !cmap_dict )
- {
- cmap_dict = new QIntDict<CMapEntry>;
- const char *v = glXQueryServerString( dpy, vi->screen, GLX_VERSION );
- mesa_gl = strstr( v,"Mesa" ) != 0;
- qAddPostRoutine( cleanup_cmaps );
- }
-
- CMapEntry *x = cmap_dict->find( (long)vi->visualid );
- if ( x ) // found colormap for visual
- return x->cmap;
-
- x = new CMapEntry();
-
- XStandardColormap *c;
- int n, i;
+ if ( !cmap_dict )
+ {
+ cmap_dict = new QMultiHash<int,CMapEntry>;
+ const char *v = glXQueryServerString( dpy, vi->screen, GLX_VERSION );
+ mesa_gl = strstr( v,"Mesa" ) != 0;
+ qAddPostRoutine( cleanup_cmaps );
+ }
+
+ QHash<int,CMapEntry>::iterator itH = cmap_dict->find( (long)vi->visualid );
+ if ( itH != cmap_dict->end() ) // found colormap for visual
+ return itH.value().cmap;
+
+ CMapEntry x;
+
+ XStandardColormap *c;
+ int n, i;
- //#ifdef DEBUG
- //cout << "Choosing cmap for vID = " << vi->visualid << endl;
- //#endif
+ //#ifdef DEBUG
+ //cout << "Choosing cmap for vID = " << vi->visualid << endl;
+ //#endif
- if ( vi->visualid == XVisualIDFromVisual( (Visual*)QPaintDevice::x11AppVisual() ) )
- {
+ if ( vi->visualid == XVisualIDFromVisual( (Visual*)QX11Info::appVisual() ) )
+ {
#ifdef DEBUG
- cout << "Using x11AppColormap" << endl;
+ cout << "Using x11AppColormap" << endl;
#endif
- return QPaintDevice::x11AppColormap();
- }
+ return QX11Info::appColormap();
+ }
- if ( mesa_gl )
+ if ( mesa_gl )
+ {
+ Atom hp_cmaps = XInternAtom( dpy, "_HP_RGB_SMOOTH_MAP_LIST", true );
+ if ( hp_cmaps && vi->visual->c_class == TrueColor && vi->depth == 8 )
+ {
+ if ( XGetRGBColormaps( dpy, RootWindow( dpy, vi->screen ), &c, &n, hp_cmaps ) )
+ {
+ i = 0;
+ while ( i < n && x.cmap == 0 )
{
- Atom hp_cmaps = XInternAtom( dpy, "_HP_RGB_SMOOTH_MAP_LIST", true );
- if ( hp_cmaps && vi->visual->c_class == TrueColor && vi->depth == 8 )
- {
- if ( XGetRGBColormaps( dpy, RootWindow( dpy, vi->screen ), &c, &n, hp_cmaps ) )
- {
- i = 0;
- while ( i < n && x->cmap == 0 )
- {
- if ( c[i].visualid == vi->visual->visualid )
- {
- x->cmap = c[i].colormap;
- x->scmap = c[i];
- }
- i++;
- }
- XFree( (char*)c );
- }
- }
+ if ( c[i].visualid == vi->visual->visualid )
+ {
+ x.cmap = c[i].colormap;
+ x.scmap = c[i];
+ }
+ i++;
}
+ XFree( (char*)c );
+ }
+ }
+ }
#if !defined( _OS_SOLARIS_ )
- if ( !x->cmap )
+ if ( !x.cmap )
+ {
+ if ( XmuLookupStandardColormap( dpy, vi->screen, vi->visualid, vi->depth, XA_RGB_DEFAULT_MAP, false, true ) )
{
- if ( XmuLookupStandardColormap( dpy, vi->screen, vi->visualid, vi->depth, XA_RGB_DEFAULT_MAP, false, true ) )
- {
- if ( XGetRGBColormaps( dpy, RootWindow( dpy, vi->screen ), &c, &n, XA_RGB_DEFAULT_MAP ) )
- {
- i = 0;
- while ( i < n && x->cmap == 0 )
- {
- if ( c[i].visualid == vi->visualid )
- {
- x->cmap = c[i].colormap;
- x->scmap = c[i];
- }
- i++;
- }
- XFree( (char *)c );
- }
- }
- }
-#endif
- if ( !x->cmap )
+ if ( XGetRGBColormaps( dpy, RootWindow( dpy, vi->screen ), &c, &n, XA_RGB_DEFAULT_MAP ) )
+ {
+ i = 0;
+ while ( i < n && x.cmap == 0 )
{
- // no shared cmap found
- x->cmap = XCreateColormap( dpy, RootWindow( dpy, vi->screen ), vi->visual, AllocNone );
- x->alloc = true;
+ if ( c[i].visualid == vi->visualid )
+ {
+ x.cmap = c[i].colormap;
+ x.scmap = c[i];
+ }
+ i++;
}
-
- cmap_dict->insert( (long)vi->visualid, x ); // associate cmap with visualid
- return x->cmap;
+ XFree( (char *)c );
+ }
+ }
+ }
+#endif
+ if ( !x.cmap )
+ {
+ // no shared cmap found
+ x.cmap = XCreateColormap( dpy, RootWindow( dpy, vi->screen ), vi->visual, AllocNone );
+ x.alloc = true;
+ }
+
+ cmap_dict->insert( (long)vi->visualid, x ); // associate cmap with visualid
+ return x.cmap;
}
#endif
Constructor
*/
OCCViewer_ViewPort::OCCViewer_ViewPort( QWidget* parent )
-: QWidget( parent, 0, WRepaintNoErase | WResizeNoErase )
+: QWidget( parent )
{
initialize();
}
*/
void OCCViewer_ViewPort::initialize()
{
- myPopupActions.setAutoDelete( true );
myPaintersRedrawing = false;
myEnableSketching = false;
myEnableTransform = true;
setMouseTracking( true );
- setBackgroundMode( NoBackground );
+ setBackgroundRole( QPalette::NoRole );//NoBackground );
// set focus policy to threat QContextMenuEvent from keyboard
- setFocusPolicy( StrongFocus );
+ setFocusPolicy( Qt::StrongFocus );
}
/*!
{
#if !defined WNT
XVisualInfo* pVisualInfo;
- if ( x11Display() )
+ if ( QX11Info::display() )
{
/* Initialization with the default VisualID */
- Visual *v = DefaultVisual( x11Display(), DefaultScreen( x11Display() ) );
+ Visual *v = DefaultVisual( QX11Info::display(), DefaultScreen( QX11Info::display() ) );
int visualID = XVisualIDFromVisual( v );
/* Here we use the settings from Optimizer_ViewInfo::TxglCreateWindow() */
int visualAttr[] = { GLX_RGBA, GLX_DEPTH_SIZE, 1, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1,
GLX_BLUE_SIZE, 1, GLX_DOUBLEBUFFER, None };
- pVisualInfo = ::glXChooseVisual( x11Display(), DefaultScreen( x11Display() ), visualAttr );
+ pVisualInfo = ::glXChooseVisual( QX11Info::display(), DefaultScreen( QX11Info::display() ), visualAttr );
if ( isVisible() )
- hide();
+ hide();
XSetWindowAttributes a;
- a.colormap = choose_cmap( x11Display(), pVisualInfo ); /* find best colormap */
- a.background_pixel = backgroundColor().pixel();
- a.border_pixel = black.pixel();
- Window p = RootWindow( x11Display(), DefaultScreen( x11Display() ) );
+ a.colormap = choose_cmap( QX11Info::display(), pVisualInfo ); /* find best colormap */
+ a.background_pixel = QColormap::instance().pixel( backgroundColor() );
+ a.border_pixel = QColormap::instance().pixel( Qt::black );
+ Window p = RootWindow( QX11Info::display(), DefaultScreen( QX11Info::display() ) );
if ( parentWidget() )
- p = parentWidget()->winId();
+ p = parentWidget()->winId();
- Window w;
+ Window w;
/* if ( type == Type2D ) // creating simple X window for 2d
{
unsigned long xbackground =
- BlackPixel( x11Display(), DefaultScreen( x11Display() ) );
+ BlackPixel( QX11Info::display(), DefaultScreen( QX11Info::display() ) );
unsigned long xforeground =
- WhitePixel( x11Display(), DefaultScreen( x11Display() ) );
+ WhitePixel( QX11Info::display(), DefaultScreen( QX11Info::display() ) );
- w = XCreateSimpleWindow ( x11Display(), p, x(), y(), width(),
+ w = XCreateSimpleWindow ( QX11Info::display(), p, x(), y(), width(),
height(), 0, xforeground, xbackground );
}
else if ( type == Type3D )
{
- w = XCreateWindow( x11Display(), p, x(), y(), width(), height(),
+ w = XCreateWindow( QX11Info::display(), p, x(), y(), width(), height(),
0, pVisualInfo->depth, InputOutput, pVisualInfo->visual,
CWBackPixel | CWBorderPixel | CWColormap, &a );
}
else
return;*/
- w = XCreateWindow( x11Display(), p, x(), y(), width(), height(),
+ w = XCreateWindow( QX11Info::display(), p, x(), y(), width(), height(),
0, pVisualInfo->depth, InputOutput, pVisualInfo->visual,
CWBackPixel | CWBorderPixel | CWColormap, &a );
Window *cmw;
Window *cmwret;
int count;
- if ( XGetWMColormapWindows( x11Display(), topLevelWidget()->winId(), &cmwret, &count ) )
+ if ( XGetWMColormapWindows( QX11Info::display(), topLevelWidget()->winId(), &cmwret, &count ) )
{
cmw = new Window[count+1];
memcpy( (char*)cmw, (char*)cmwret, sizeof(Window) * count );
/* Creating new window (with good VisualID) for this widget */
create(w);
- XSetWMColormapWindows( x11Display(), topLevelWidget()->winId(), cmw, count );
+ XSetWMColormapWindows( QX11Info::display(), topLevelWidget()->winId(), cmw, count );
delete[] cmw;
if ( isVisible() )
{
XFree( (char *)pVisualInfo );
}
- XFlush( x11Display() );
+ XFlush( QX11Info::display() );
}
#endif
}
void OCCViewer_ViewPort::setBackgroundColor( const QColor& color )
{
QPalette pal = palette();
- pal.setColor( QColorGroup::Background, color );
+ pal.setColor( QPalette::Background, color );
setPalette( pal );
repaint();
emit vpChangeBGColor( color );
*/
QColor OCCViewer_ViewPort::backgroundColor() const
{
- return palette().active().background();
+ return palette().color( QPalette::Active, QPalette::Background );
}
/*!
{
for ( QtxAction* a = myPopupActions.first(); a; a = myPopupActions.next() )
a->removeFrom( popup );
+ //while (!myPopupActions.isEmpty())
+ // delete myPopupActions.takeFirst();
myPopupActions.clear();
}
}*/
#include "QtxAction.h"
-#include <qlist.h>
-#include <qcolor.h>
-#include <qwidget.h>
+#include <QList>
+#include <QWidget>
#include <Aspect_Window.hxx>
+class QColor;
class QRect;
-class QCursor;
class QPainter;
class OCCViewer_ViewSketcher;
-class OCCViewer_ViewTransformer;
#ifdef WIN32
#pragma warning ( disable:4251 )
*/
class OCCVIEWER_EXPORT OCCViewer_ViewPort : public QWidget
{
- Q_OBJECT
+ Q_OBJECT
friend class OCCViewer_ViewSketcher;
public:
OCCViewer_ViewPort( QWidget* parent );
- virtual ~OCCViewer_ViewPort();
+ virtual ~OCCViewer_ViewPort();
public:
- void setSketchingEnabled( bool );
+ void setSketchingEnabled( bool );
bool isSketchingEnabled() const;
void setTransformEnabled( bool );
bool isTransformEnabled() const;
- virtual QColor backgroundColor() const;
- virtual void setBackgroundColor( const QColor& );
+ virtual QColor backgroundColor() const;
+ virtual void setBackgroundColor( const QColor& );
void redrawPainters();
- virtual void onUpdate();
+ virtual void onUpdate();
protected:
// enum ViewType { Type2D, Type3D };
- void selectVisualId();
+ void selectVisualId();
// EVENTS
- virtual void paintEvent( QPaintEvent *);
- virtual void mouseMoveEvent( QMouseEvent *);
- virtual void mouseReleaseEvent( QMouseEvent *);
- virtual void mousePressEvent( QMouseEvent *);
- virtual void mouseDoubleClickEvent( QMouseEvent *);
- virtual void keyPressEvent( QKeyEvent *);
- virtual void keyReleaseEvent( QKeyEvent *);
+ virtual void paintEvent( QPaintEvent *);
+ virtual void mouseMoveEvent( QMouseEvent *);
+ virtual void mouseReleaseEvent( QMouseEvent *);
+ virtual void mousePressEvent( QMouseEvent *);
+ virtual void mouseDoubleClickEvent( QMouseEvent *);
+ virtual void keyPressEvent( QKeyEvent *);
+ virtual void keyReleaseEvent( QKeyEvent *);
// TO BE REDEFINED
virtual void reset() = 0;
virtual void pan( int, int ) = 0;
- virtual void setCenter( int, int ) = 0;
- virtual void fitRect( const QRect& ) = 0;
+ virtual void setCenter( int, int ) = 0;
+ virtual void fitRect( const QRect& ) = 0;
virtual void zoom( int, int, int, int ) = 0;
virtual void fitAll( bool keepScale = false, bool withZ = true, bool upd = true ) = 0;
// POPUP
// void onCreatePopup( QPopupMenu* );
-// void onDestroyPopup( QPopupMenu* );
+// void onDestroyPopup( QPopupMenu* );
protected slots:
virtual void onChangeBgColor();
signals:
- void vpKeyEvent( QKeyEvent* );
- void vpMouseEvent( QMouseEvent* );
- void vpDrawExternal( QPainter* );
+ void vpKeyEvent( QKeyEvent* );
+ void vpMouseEvent( QMouseEvent* );
+ void vpDrawExternal( QPainter* );
void vpChangeBGColor( QColor );
private:
- void initialize();
- void cleanup();
+ void initialize();
+ void cleanup();
protected:
- Handle(Aspect_Window) myWindow;
- bool myEnableSketching;
- bool myEnableTransform;
- bool myPaintersRedrawing; /* set to draw externally */
- QPtrList<QtxAction> myPopupActions;
+ Handle(Aspect_Window) myWindow;
+ bool myEnableSketching;
+ bool myEnableTransform;
+ bool myPaintersRedrawing; /* set to draw externally */
+ QList<QtxAction*> myPopupActions;
private:
- static int nCounter; /* objects counter */
+ static int nCounter; /* objects counter */
};
#ifdef WIN32
#include "OCCViewer_VService.h"
#include "OCCViewer_ViewWindow.h"
-#include <qrect.h>
-#include <qevent.h>
-#include <qapplication.h>
+#include <QColor>
+#include <QRect>
+#include <QPaintEvent>
+#include <QResizeEvent>
+#include <QApplication>
#include <Visual3d_View.hxx>
+#include <V3d_Viewer.hxx>
#include <V3d_PerspectiveView.hxx>
#include <V3d_OrthographicView.hxx>
#include "OCCViewer_ViewPort.h"
-#include <qcolor.h>
-
#include <V3d_View.hxx>
-#include <V3d_Viewer.hxx>
+class QColor;
class QRect;
+class Handle(V3d_Viewer);
+
#ifdef WIN32
#pragma warning ( disable:4251 )
#endif
class OCCVIEWER_EXPORT OCCViewer_ViewPort3d: public OCCViewer_ViewPort
{
- Q_OBJECT
+ Q_OBJECT
friend class OCCViewer_ViewTransformer;
public:
- OCCViewer_ViewPort3d( QWidget*, const Handle(V3d_Viewer)&, V3d_TypeOfView = V3d_ORTHOGRAPHIC );
- virtual ~OCCViewer_ViewPort3d();
+ OCCViewer_ViewPort3d( QWidget*, const Handle(V3d_Viewer)&, V3d_TypeOfView = V3d_ORTHOGRAPHIC );
+ virtual ~OCCViewer_ViewPort3d();
public:
- Handle(V3d_View) getView() const;
- Handle(V3d_View) setView( const Handle(V3d_View)& );
- Handle(V3d_Viewer) getViewer() const;
+ Handle(V3d_View) getView() const;
+ Handle(V3d_View) setView( const Handle(V3d_View)& );
+ Handle(V3d_Viewer) getViewer() const;
void setAnimationMode(bool theDegenerated);
- virtual void setBackgroundColor( const QColor& color);
+ virtual void setBackgroundColor( const QColor& color);
virtual QColor backgroundColor() const;
// void setActive( V3d_TypeOfView );
// TRANSFORMATIONS
virtual void reset();
virtual void pan( int , int );
- virtual void setCenter( int , int );
- virtual void fitRect( const QRect& );
- virtual void zoom( int, int, int, int );
+ virtual void setCenter( int , int );
+ virtual void fitRect( const QRect& );
+ virtual void zoom( int, int, int, int );
virtual void fitAll( bool keepScale = false, bool withZ = true, bool upd = true );
- void startRotation( int, int, int, const gp_Pnt& );
- void rotate( int, int, int, const gp_Pnt& );
- void endRotation();
+ void startRotation( int, int, int, const gp_Pnt& );
+ void rotate( int, int, int, const gp_Pnt& );
+ void endRotation();
protected:
// EVENTS
- virtual void paintEvent( QPaintEvent* );
- virtual void resizeEvent( QResizeEvent* );
+ virtual void paintEvent( QPaintEvent* );
+ virtual void resizeEvent( QResizeEvent* );
private:
- Handle(V3d_View) activeView() const;
- Handle(V3d_View) inactiveView() const;
- bool mapView( const Handle(V3d_View)& );
- bool setWindow( const Handle(V3d_View)& );
- bool mapped( const Handle(V3d_View)& ) const;
+ Handle(V3d_View) activeView() const;
+ Handle(V3d_View) inactiveView() const;
+ bool mapView( const Handle(V3d_View)& );
+ bool setWindow( const Handle(V3d_View)& );
+ bool mapped( const Handle(V3d_View)& ) const;
private:
- Handle(V3d_View) myOrthoView;
- Handle(V3d_View) myPerspView;
- Handle(V3d_View) myActiveView;
- bool myDegenerated;
- bool myAnimate;
- double myScale;
+ Handle(V3d_View) myOrthoView;
+ Handle(V3d_View) myPerspView;
+ Handle(V3d_View) myActiveView;
+ bool myDegenerated;
+ bool myAnimate;
+ double myScale;
};
#ifdef WIN32
#include "SUIT_Desktop.h"
#include "SUIT_Session.h"
#include "SUIT_ToolButton.h"
+#include "SUIT_ViewManager.h"
#include "SUIT_Tools.h"
#include "SUIT_ResourceMgr.h"
#include "SUIT_MessageBox.h"
-#include <qptrlist.h>
-#include <qhbox.h>
-#include <qlabel.h>
-#include <qcolor.h>
-#include <qpainter.h>
-#include <qapplication.h>
-#include <qdatetime.h>
-#include <qimage.h>
+#include <QPainter>
+#include <QTime>
+#include <QImage>
+#include <QToolBar>
+#include <QMouseEvent>
+#include <QRubberBand>
#include <V3d_Plane.hxx>
#include <gp_Dir.hxx>
#include <gp_Pln.hxx>
+#include <AIS_ListOfInteractive.hxx>
#include <AIS_ListIteratorOfListOfInteractive.hxx>
#include <AIS_Shape.hxx>
updateEnabledDrawMode();
myClippingDlg = 0;
mySetRotationPointDlg = 0;
+ myRectBand = 0;
+}
+
+/*!
+ \brief Destructor.
+*/
+OCCViewer_ViewWindow::~OCCViewer_ViewWindow()
+{
+ endDrawRect();
}
/*!
void OCCViewer_ViewWindow::initLayout()
{
myViewPort = new OCCViewer_ViewPort3d( this, myModel->getViewer3d(), V3d_ORTHOGRAPHIC );
- myViewPort->setBackgroundColor(black);
+ myViewPort->setBackgroundColor(Qt::black);
myViewPort->installEventFilter(this);
setCentralWidget(myViewPort);
myOperation = NOTHING;
setTransformInProcess ( false );
myToolBar = new QToolBar(this);
- myToolBar->setCloseMode(QDockWindow::Undocked);
- myToolBar->setLabel(tr("LBL_TOOLBAR_LABEL"));
+ //myToolBar->setCloseMode(QDockWindow::Undocked); // toolbar has "Close" (X) button only if it's undocked, but there is no such functionality in Qt4
+ myToolBar->setWindowTitle(tr("LBL_TOOLBAR_LABEL"));
createActions();
createToolBar();
OCCViewer_ViewWindow::OperationType OCCViewer_ViewWindow::getButtonState(QMouseEvent* theEvent)
{
OperationType aOp = NOTHING;
- if( (theEvent->state() == SUIT_ViewModel::myStateMap[SUIT_ViewModel::ZOOM]) &&
+ if( (theEvent->modifiers() == SUIT_ViewModel::myStateMap[SUIT_ViewModel::ZOOM]) &&
(theEvent->button() == SUIT_ViewModel::myButtonMap[SUIT_ViewModel::ZOOM]) )
aOp = ZOOMVIEW;
- else if( (theEvent->state() == SUIT_ViewModel::myStateMap[SUIT_ViewModel::PAN]) &&
+ else if( (theEvent->modifiers() == SUIT_ViewModel::myStateMap[SUIT_ViewModel::PAN]) &&
(theEvent->button() == SUIT_ViewModel::myButtonMap[SUIT_ViewModel::PAN]) )
aOp = PANVIEW;
- else if( (theEvent->state() == SUIT_ViewModel::myStateMap[SUIT_ViewModel::ROTATE]) &&
+ else if( (theEvent->modifiers() == SUIT_ViewModel::myStateMap[SUIT_ViewModel::ROTATE]) &&
(theEvent->button() == SUIT_ViewModel::myButtonMap[SUIT_ViewModel::ROTATE]) )
aOp = ROTATE;
*/
void OCCViewer_ViewWindow::updateGravityCoords()
{
- if ( mySetRotationPointDlg && mySetRotationPointDlg->isShown() && myCurrPointType == GRAVITY )
+ if ( mySetRotationPointDlg && mySetRotationPointDlg->isVisible() && myCurrPointType == GRAVITY )
{
Standard_Real Xcenter, Ycenter, Zcenter;
if ( computeGravityCenter( Xcenter, Ycenter, Zcenter ) )
emit mouseMoving( this, theEvent );
else
{
- int aState = theEvent->state();
- //int aButton = theEvent->button();
- if ( aState == Qt::LeftButton ||
- aState == ( Qt::LeftButton | Qt::ShiftButton) ) {
+ int aState = theEvent->modifiers();
+ int aButton = theEvent->button();
+ if ( aButton == Qt::LeftButton ||
+ ( aButton == Qt::LeftButton && aState == Qt::ShiftModifier ) ) {
myDrawRect = myEnableDrawMode;
if ( myDrawRect ) {
drawRect();
case NOTHING:
{
emit mouseReleased(this, theEvent);
- if(theEvent->button() == RightButton)
+ if(theEvent->button() == Qt::RightButton)
{
QContextMenuEvent aEvent( QContextMenuEvent::Mouse,
- theEvent->pos(), theEvent->globalPos(),
- theEvent->state() );
+ theEvent->pos(), theEvent->globalPos() );
emit contextMenuRequested( &aEvent );
}
}
break;
case WINDOWFIT:
- if ( theEvent->state() == Qt::LeftButton ) {
+ if ( theEvent->button() == Qt::LeftButton ) {
myCurrX = theEvent->x();
myCurrY = theEvent->y();
QRect rect = SUIT_Tools::makeRect(myStartX, myStartY, myCurrX, myCurrY);
if ( theEvent->button() == Qt::LeftButton && myDrawRect ) {
myDrawRect = false;
drawRect();
+ endDrawRect();
resetState();
myViewPort->update();
}
{
myDrawRect = false;
- /* make rectangle empty (left > right) */
- myRect.setLeft(2);
- myRect.setRight(0);
-
if ( myRotationPointSelection )
{
QCursor handCursor (Qt::PointingHandCursor);
*/
void OCCViewer_ViewWindow::drawRect()
{
- QPainter aPainter(myViewPort);
- aPainter.setRasterOp(Qt::XorROP);
- aPainter.setPen(Qt::white);
+ if ( !myRectBand ) {
+ myRectBand = new QRubberBand( QRubberBand::Rectangle, myViewPort );
+ QPalette palette;
+ palette.setColor(myRectBand->foregroundRole(), Qt::white);
+ myRectBand->setPalette(palette);
+ }
+ myRectBand->hide();
+
QRect aRect = SUIT_Tools::makeRect(myStartX, myStartY, myCurrX, myCurrY);
- if ( !myRect.isEmpty() )
- aPainter.drawRect( myRect );
- aPainter.drawRect(aRect);
- myRect = aRect;
+ myRectBand->setGeometry( aRect );
+ myRectBand->setVisible( aRect.isValid() );
+}
+
+/*!
+ \brief Delete rubber band on the end on the dragging operation.
+*/
+void OCCViewer_ViewWindow::endDrawRect()
+{
+ delete myRectBand;
+ myRectBand = 0;
}
/*!
mySetRotationPointAction = new QtxAction(tr("MNU_CHANGINGROTATIONPOINT_VIEW"), aResMgr->loadPixmap( "OCCViewer", tr( "ICON_OCCVIEWER_VIEW_ROTATION_POINT" ) ),
tr( "MNU_CHANGINGROTATIONPOINT_VIEW" ), 0, this);
mySetRotationPointAction->setStatusTip(tr("DSC_CHANGINGROTATIONPOINT_VIEW"));
- mySetRotationPointAction->setToggleAction( true );
+ mySetRotationPointAction->setCheckable( true );
connect(mySetRotationPointAction, SIGNAL(toggled( bool )), this, SLOT(onSetRotationPoint( bool )));
myActionsMap[ ChangeRotationPointId ] = mySetRotationPointAction;
myClippingAction = new QtxAction(tr("MNU_CLIPPING"), aResMgr->loadPixmap( "OCCViewer", tr( "ICON_OCCVIEWER_CLIPPING" ) ),
tr( "MNU_CLIPPING" ), 0, this);
myClippingAction->setStatusTip(tr("DSC_CLIPPING"));
- myClippingAction->setToggleAction( true );
+ myClippingAction->setCheckable( true );
connect(myClippingAction, SIGNAL(toggled( bool )), this, SLOT(onClipping( bool )));
myActionsMap[ ClippingId ] = myClippingAction;
mySetRotationPointDlg->SetAction( mySetRotationPointAction );
}
- if ( !mySetRotationPointDlg->isShown() )
+ if ( !mySetRotationPointDlg->isVisible() )
{
if ( mySetRotationPointDlg->IsFirstShown() )
{
}
else
{
- if ( mySetRotationPointDlg->isShown() )
+ if ( mySetRotationPointDlg->isVisible() )
mySetRotationPointDlg->hide();
}
}
{
SUIT_ResourceMgr* aResMgr = SUIT_Session::session()->resourceMgr();
if ( on )
- myActionsMap[ ClippingId ]->setIconSet(aResMgr->loadPixmap( "OCCViewer", tr( "ICON_OCCVIEWER_CLIPPING_PRESSED" )));
+ myActionsMap[ ClippingId ]->setIcon(aResMgr->loadPixmap( "OCCViewer", tr( "ICON_OCCVIEWER_CLIPPING_PRESSED" )));
else
- myActionsMap[ ClippingId ]->setIconSet(aResMgr->loadPixmap( "OCCViewer", tr( "ICON_OCCVIEWER_CLIPPING" )));
+ myActionsMap[ ClippingId ]->setIcon(aResMgr->loadPixmap( "OCCViewer", tr( "ICON_OCCVIEWER_CLIPPING" )));
if ( on )
{
myClippingDlg->SetAction( myClippingAction );
}
- if ( !myClippingDlg->isShown() )
+ if ( !myClippingDlg->isVisible() )
myClippingDlg->show();
}
else
{
- if ( myClippingDlg->isShown() )
+ if ( myClippingDlg->isVisible() )
myClippingDlg->hide();
setCuttingPlane(false);
}
QImage OCCViewer_ViewWindow::dumpView()
{
QPixmap px = QPixmap::grabWindow( myViewPort->winId() );
- return px.convertToImage();
+ return px.toImage();
}
/*!
*/
void OCCViewer_ViewWindow::setVisualParameters( const QString& parameters )
{
- QStringList paramsLst = QStringList::split( '*', parameters, true );
+ QStringList paramsLst = parameters.split( '*' );
if ( paramsLst.size() == 13 ) {
viewAspect params;
params.scale = paramsLst[0].toDouble();
#include "QtxAction.h"
-#include <qcursor.h>
-#include <qvaluelist.h>
+#include <QCursor>
+
+class QRubberBand;
class SUIT_Desktop;
class OCCViewer_ViewPort3d;
enum RotationPointType{ GRAVITY, SELECTED };
OCCViewer_ViewWindow(SUIT_Desktop* theDesktop, OCCViewer_Viewer* theModel);
- virtual ~OCCViewer_ViewWindow() {};
+ virtual ~OCCViewer_ViewWindow();
OCCViewer_ViewPort3d* getViewPort() { return myViewPort; }
void resetState();
void drawRect();
+ void endDrawRect();
void createActions();
void createToolBar();
bool myEnableDrawMode;
bool myPaintersRedrawing; // set to draw with external painters
- QRect myRect;
QCursor myCursor;
QToolBar* myToolBar;
OCCViewer_SetRotationPointDlg* mySetRotationPointDlg;
QtxAction* mySetRotationPointAction;
-
+
+ QRubberBand* myRectBand; //!< selection rectangle rubber band
};
#ifdef WIN32
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>ICON_OCCVIEWER_VIEW_GLOBALPAN</source>
+ <translation>view_glpan.png</translation>
+ </message>
+ <message>
+ <source>ICON_OCCVIEWER_CLIPPING_PRESSED</source>
+ <translation>view_clipping_pressed.png</translation>
+ </message>
+ <message>
+ <source>ICON_OCCVIEWER_VIEW_FITAREA</source>
+ <translation>view_fitarea.png</translation>
+ </message>
+ <message>
+ <source>ICON_OCCVIEWER_CLONE_VIEW</source>
+ <translation>view_clone.png</translation>
+ </message>
+ <message>
+ <source>ICON_OCCVIEWER_PRESETS_VIEW</source>
+ <translation>view_presets.png</translation>
+ </message>
+ <message>
+ <source>ICON_OCCVIEWER_VIEW_TOP</source>
+ <translation>view_top.png</translation>
+ </message>
+ <message>
+ <source>ICON_OCCVIEWER_VIEW_PAN</source>
+ <translation>view_pan.png</translation>
+ </message>
+ <message>
+ <source>ICON_OCCVIEWER_SHOOT_VIEW</source>
+ <translation>view_shoot.png</translation>
+ </message>
+ <message>
+ <source>ICON_OCCVIEWER_VIEW_ROTATION_POINT</source>
+ <translation>view_rotation_point.png</translation>
+ </message>
+ <message>
+ <source>ICON_OCCVIEWER_VIEW_DUMP</source>
+ <translation>view_camera_dump.png</translation>
+ </message>
+ <message>
+ <source>ICON_OCCVIEWER_VIEW_BACK</source>
+ <translation>view_back.png</translation>
+ </message>
+ <message>
+ <source>ICON_OCCVIEWER_VIEW_ZOOM</source>
+ <translation>view_zoom.png</translation>
+ </message>
+ <message>
+ <source>ICON_OCCVIEWER_VIEW_LEFT</source>
+ <translation>view_left.png</translation>
+ </message>
+ <message>
+ <source>ICON_OCCVIEWER_VIEW_FITALL</source>
+ <translation>view_fitall.png</translation>
+ </message>
+ <message>
+ <source>ICON_OCCVIEWER_VIEW_BOTTOM</source>
+ <translation>view_bottom.png</translation>
+ </message>
+ <message>
+ <source>ICON_OCCVIEWER_VIEW_ROTATE</source>
+ <translation>view_rotate.png</translation>
+ </message>
+ <message>
+ <source>ICON_OCCVIEWER_VIEW_FRONT</source>
+ <translation>view_front.png</translation>
+ </message>
+ <message>
+ <source>ICON_OCCVIEWER_VIEW_RESET</source>
+ <translation>view_reset.png</translation>
+ </message>
+ <message>
+ <source>ICON_OCCVIEWER_VIEW_RIGHT</source>
+ <translation>view_right.png</translation>
+ </message>
+ <message>
+ <source>ICON_OCCVIEWER_CLIPPING</source>
+ <translation>view_clipping.png</translation>
+ </message>
+ <message>
+ <source>ICON_OCCVIEWER_VIEW_TRIHEDRON</source>
+ <translation>view_triedre.png</translation>
+ </message>
+</context>
+</TS>
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>MNU_FRONT_VIEW</source>
+ <translation>Front</translation>
+ </message>
+ <message>
+ <source>ERROR</source>
+ <translation>Error</translation>
+ </message>
+ <message>
+ <source>MNU_DUMP_VIEW</source>
+ <translation>Dump view</translation>
+ </message>
+ <message>
+ <source>DSC_TOP_VIEW</source>
+ <translation>Top View</translation>
+ </message>
+ <message>
+ <source>MNU_PAN_VIEW</source>
+ <translation>Panning</translation>
+ </message>
+ <message>
+ <source>MNU_CLONE_VIEW</source>
+ <translation>Clone View</translation>
+ </message>
+ <message>
+ <source>DSC_SHOW_TRIHEDRE</source>
+ <translation>Show/Hide trihedron in the current view</translation>
+ </message>
+ <message>
+ <source>MNU_SHOW_TRIHEDRE</source>
+ <translation>Show/Hide trihedron</translation>
+ </message>
+ <message>
+ <source>MNU_TOP_VIEW</source>
+ <translation>Top</translation>
+ </message>
+ <message>
+ <source>DSC_GLOBALPAN_VIEW</source>
+ <translation>Selection of a new center of the view</translation>
+ </message>
+ <message>
+ <source>DSC_ROTATE_VIEW</source>
+ <translation>Rotation of the point of view around the scene center</translation>
+ </message>
+ <message>
+ <source>MNU_ZOOM_VIEW</source>
+ <translation>Zoom</translation>
+ </message>
+ <message>
+ <source>DSC_PAN_VIEW</source>
+ <translation>Panning the view</translation>
+ </message>
+ <message>
+ <source>DSC_LEFT_VIEW</source>
+ <translation>Left View</translation>
+ </message>
+ <message>
+ <source>DSC_SHOOT_VIEW</source>
+ <translation>Memorizes the state of the active view and adds it to the list</translation>
+ </message>
+ <message>
+ <source>DSC_FITALL</source>
+ <translation>Fit all objects inside the view frame</translation>
+ </message>
+ <message>
+ <source>MNU_FITALL</source>
+ <translation>Fit All</translation>
+ </message>
+ <message>
+ <source>MNU_ROTATE_VIEW</source>
+ <translation>Rotation</translation>
+ </message>
+ <message>
+ <source>OCC_IMAGE_FILES</source>
+ <translation>Images Files (*.bmp *.png *.jpg *.jpeg)</translation>
+ </message>
+ <message>
+ <source>DSC_FRONT_VIEW</source>
+ <translation>Front View</translation>
+ </message>
+ <message>
+ <source>MNU_ROTATIONPOINTGRAVITY_VIEW</source>
+ <translation>Rotation Point : the gravity center</translation>
+ </message>
+ <message>
+ <source>MNU_GLOBALPAN_VIEW</source>
+ <translation>Global Panning</translation>
+ </message>
+ <message>
+ <source>INF_APP_DUMP_VIEW</source>
+ <translation>Dump view</translation>
+ </message>
+ <message>
+ <source>DSC_CLIPPING</source>
+ <translation>Set clipping plane</translation>
+ </message>
+ <message>
+ <source>DSC_CLONE_VIEW</source>
+ <translation>Create new OCC viewer for the active scene</translation>
+ </message>
+ <message>
+ <source>INF_APP_SHOOT_VIEW</source>
+ <translation>Memorize view</translation>
+ </message>
+ <message>
+ <source>MNU_CLIPPING</source>
+ <translation>Clipping</translation>
+ </message>
+ <message>
+ <source>MNU_BACK_VIEW</source>
+ <translation>Back</translation>
+ </message>
+ <message>
+ <source>MNU_SHOOT_VIEW</source>
+ <translation>Memorize View</translation>
+ </message>
+ <message>
+ <source>DSC_CHANGINGROTATIONPOINT_VIEW</source>
+ <translation>Change the point, around which the rotation is performed</translation>
+ </message>
+ <message>
+ <source>MNU_BOTTOM_VIEW</source>
+ <translation>Bottom</translation>
+ </message>
+ <message>
+ <source>MNU_RESET_VIEW</source>
+ <translation>Reset</translation>
+ </message>
+ <message>
+ <source>MNU_LEFT_VIEW</source>
+ <translation>Left</translation>
+ </message>
+ <message>
+ <source>DSC_RIGHT_VIEW</source>
+ <translation>Right View</translation>
+ </message>
+ <message>
+ <source>MNU_CHANGINGROTATIONPOINT_VIEW</source>
+ <translation>Change Rotation Point</translation>
+ </message>
+ <message>
+ <source>DSC_FITRECT</source>
+ <translation>Fit area within the view frame</translation>
+ </message>
+ <message>
+ <source>MNU_FITRECT</source>
+ <translation>Fit Area</translation>
+ </message>
+ <message>
+ <source>DSC_BOTTOM_VIEW</source>
+ <translation>Bottom View</translation>
+ </message>
+ <message>
+ <source>DSC_DUMP_VIEW</source>
+ <translation>Saves the active view in the image file</translation>
+ </message>
+ <message>
+ <source>DSC_ZOOM_VIEW</source>
+ <translation>Zoom the view</translation>
+ </message>
+ <message>
+ <source>MNU_ROTATIONPOINT000_VIEW</source>
+ <translation>Rotation Point : (0,0,0)</translation>
+ </message>
+ <message>
+ <source>MNU_ROTATIONPOINTSELECTED_VIEW</source>
+ <translation>Rotation Point : the point selected by the user</translation>
+ </message>
+ <message>
+ <source>DSC_RESET_VIEW</source>
+ <translation>Reset View Point</translation>
+ </message>
+ <message>
+ <source>ERR_DOC_CANT_SAVE_FILE</source>
+ <translation>Cannot save file</translation>
+ </message>
+ <message>
+ <source>DSC_PRESETS_VIEW</source>
+ <translation>Selection of the memorized state of the active view</translation>
+ </message>
+ <message>
+ <source>MNU_PRESETS_VIEW</source>
+ <translation>Restore View</translation>
+ </message>
+ <message>
+ <source>MNU_RIGHT_VIEW</source>
+ <translation>Right</translation>
+ </message>
+ <message>
+ <source>INF_APP_PRESETS_VIEW</source>
+ <translation>Restore view</translation>
+ </message>
+ <message>
+ <source>LBL_TOOLBAR_LABEL</source>
+ <translation>View Operations</translation>
+ </message>
+ <message>
+ <source>DSC_BACK_VIEW</source>
+ <translation>Back View</translation>
+ </message>
+</context>
+<context>
+ <name>OCCViewer_CreateRestoreViewDlg</name>
+ <message>
+ <source>CAPTION</source>
+ <translation>Restore view</translation>
+ </message>
+</context>
+<context>
+ <name>OCCViewer_SetRotationPointDlg</name>
+ <message>
+ <source>LBL_X</source>
+ <translation>X :</translation>
+ </message>
+ <message>
+ <source>LBL_Y</source>
+ <translation>Y :</translation>
+ </message>
+ <message>
+ <source>LBL_Z</source>
+ <translation>Z :</translation>
+ </message>
+ <message>
+ <source>USE_BBCENTER</source>
+ <translation>Use Bounding Box Center</translation>
+ </message>
+ <message>
+ <source>LBL_TOORIGIN</source>
+ <translation>Set to Origin</translation>
+ </message>
+ <message>
+ <source>CAPTION</source>
+ <translation>Set Rotation Point</translation>
+ </message>
+ <message>
+ <source>LBL_SELECTPOINT</source>
+ <translation>Select Point from View</translation>
+ </message>
+</context>
+<context>
+ <name>OCCViewer_ViewManager</name>
+ <message>
+ <source>OCC_VIEW_TITLE</source>
+ <translation>OCC scene:%M - viewer:%V</translation>
+ </message>
+</context>
+<context>
+ <name>OCCViewer_Viewer</name>
+ <message>
+ <source>MEN_DUMP_VIEW</source>
+ <translation>Dump view...</translation>
+ </message>
+ <message>
+ <source>MEN_SHOW_TOOLBAR</source>
+ <translation>Show toolbar</translation>
+ </message>
+ <message>
+ <source>MEN_CHANGE_BACKGROUD</source>
+ <translation>Change background...</translation>
+ </message>
+</context>
+</TS>
#define OB_H
#if defined OB_EXPORTS
-#if defined WNT
+#if defined WIN32
#define OB_EXPORT __declspec( dllexport )
#else
#define OB_EXPORT
#endif
#else
-#if defined WNT
+#if defined WIN32
#define OB_EXPORT __declspec( dllimport )
#else
#define OB_EXPORT
#define true 1
#endif
-#if defined WNT
+#if defined WIN32
#pragma warning ( disable: 4251 )
#endif
#include <SUIT_DataObjectKey.h>
#include <SUIT_PopupClient.h>
-#ifdef WNT
+#ifdef WIN32
#pragma warning( disable:4251 )
#endif
#include <iostream>
using namespace std;
-#ifdef WNT
+#ifdef WIN32
#define min(a, b) (((a) < (b)) ? (a) : (b))
#endif
*/
OB_CheckListItem::OB_CheckListItem( SUIT_DataObject* obj, QListView* parent, QListViewItem* after, Type type )
: ListItemF<QCheckListItem>( this, obj),
-#if defined(QT_VERSION) && QT_VERSION >= 0x030101
QCheckListItem( parent, after, "", type )
-#else
- QCheckListItem( parent, "", type )
-#endif
{
update();
}
*/
OB_CheckListItem::OB_CheckListItem( SUIT_DataObject* obj, QListViewItem* parent, QListViewItem* after, Type type )
: ListItemF<QCheckListItem>( this, obj),
-#if defined(QT_VERSION) && QT_VERSION >= 0x030101
QCheckListItem( parent, after, "", type )
-#else
- QCheckListItem( parent, "", type )
-#endif
{
update();
}
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>MEN_EXPAND_ALL</source>
+ <translation>Expand All</translation>
+ </message>
+</context>
+</TS>
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-#ifdef WNT
+#ifdef WIN32
#ifdef PLOT2D_EXPORTS
#define PLOT2D_EXPORT __declspec(dllexport)
#else
#define PLOT2D_EXPORT
#endif
-#if defined WNT
+#if defined WIN32
#pragma warning ( disable: 4251 )
#endif
--- /dev/null
+TEMPLATE = lib
+TARGET = Plot2d
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+PYTHONVER=2.4
+PYTHONHOME=$$(PYTHONHOME)
+PYTHONINC=$${PYTHONHOME}/include/python$${PYTHONVER}
+
+QWTHOME=$$(QWTHOME)
+QWTINC=$${QWTHOME}/include
+QWTLIB=$${QWTHOME}/lib
+
+INCLUDEPATH += ../../include $${QWTINC} $${PYTHONINC}
+INCLUDEPATH += ../Qtx ../SUIT
+unix:LIBS += -L$${QWTLIB} -lqwt
+win32:LIBS += /LIBPATH:$$(QWTLIB)
+LIBS += -L../../lib -lqtx -lsuit
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += PLOT2D_EXPORTS
+
+HEADERS = Plot2d.h
+HEADERS += Plot2d_Curve.h
+HEADERS += Plot2d_FitDataDlg.h
+HEADERS += Plot2d_Prs.h
+HEADERS += Plot2d_SetupViewDlg.h
+HEADERS += Plot2d_ViewFrame.h
+HEADERS += Plot2d_ViewManager.h
+HEADERS += Plot2d_ViewModel.h
+HEADERS += Plot2d_ViewWindow.h
+HEADERS += Plot2d_SetupCurveDlg.h
+HEADERS += Plot2d_ToolTip.h
+
+SOURCES = Plot2d_Curve.cxx
+SOURCES += Plot2d_FitDataDlg.cxx
+SOURCES += Plot2d_Prs.cxx
+SOURCES += Plot2d_SetupViewDlg.cxx
+SOURCES += Plot2d_ViewFrame.cxx
+SOURCES += Plot2d_ViewManager.cxx
+SOURCES += Plot2d_ViewModel.cxx
+SOURCES += Plot2d_ViewWindow.cxx
+SOURCES += Plot2d_SetupCurveDlg.cxx
+SOURCES += Plot2d_ToolTip.cxx
+
+TRANSLATIONS = resources/Plot2d_msg_en.ts \
+ resources/Plot2d_images.ts
+
+ICONS = resources/*.png
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+resources.files = $$ICONS resources/*.qm
+resources.path = ../../resources
+
+INSTALLS += includes resources
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
#include "Plot2d_Curve.h"
-#include <qcolor.h>
+#include <QColor>
/*!
Constructor
aPoint.y = theY;
aPoint.text = txt;
- QValueList<Plot2d_Point>::iterator aIt;
+ QList<Plot2d_Point>::iterator aIt;
int aCurrent = 0;
for(aIt = myPoints.begin(); aIt != myPoints.end(); ++aIt) {
if (thePos == aCurrent) {
*/
void Plot2d_Curve::deletePoint(int thePos)
{
- QValueList<Plot2d_Point>::iterator aIt;
- int aCurrent = 0;
- for(aIt = myPoints.begin(); aIt != myPoints.end(); ++aIt) {
- if (thePos == aCurrent) {
- myPoints.remove(aIt);
- return;
- }
- aCurrent++;
- }
+ if ( thePos >= 0 && thePos < myPoints.count() )
+ myPoints.removeAt( thePos );
}
/*!
*/
double Plot2d_Curve::getMinX() const
{
- QValueList<Plot2d_Point>::const_iterator aIt;
+ QList<Plot2d_Point>::const_iterator aIt;
double aMinX = 1e150;
//int aCurrent = 0;
for(aIt = myPoints.begin(); aIt != myPoints.end(); ++aIt) {
*/
double Plot2d_Curve::getMinY() const
{
- QValueList<Plot2d_Point>::const_iterator aIt;
+ QList<Plot2d_Point>::const_iterator aIt;
double aMinY = 1e150;
//int aCurrent = 0;
for(aIt = myPoints.begin(); aIt != myPoints.end(); ++aIt) {
#define PLOT2D_CURVE_H
#include "Plot2d.h"
-#include <qvaluelist.h>
-#include <qptrlist.h>
+#include <QList>
#include <qwt_plot.h>
class QColor;
QString text;
} Plot2d_Point;
-typedef QValueList<Plot2d_Point> pointList;
+typedef QList<Plot2d_Point> pointList;
class PLOT2D_EXPORT Plot2d_Curve
{
pointList myPoints;
};
-typedef QPtrList<Plot2d_Curve> curveList;
+typedef QList<Plot2d_Curve*> curveList;
#endif
// $Header$
#include "Plot2d_FitDataDlg.h"
-#include <qlabel.h>
-#include <qlayout.h>
-#include <qvalidator.h>
-#include <qpushbutton.h>
-#include <qradiobutton.h>
-#include <qbuttongroup.h>
-#include <qlineedit.h>
+#include <QLabel>
+#include <QLayout>
+#include <QValidator>
+#include <QPushButton>
+#include <QRadioButton>
+#include <QGroupBox>
+#include <QLineEdit>
#define SPACING_SIZE 6
#define MARGIN_SIZE 11
*/
Plot2d_FitDataDlg::Plot2d_FitDataDlg( QWidget* parent, bool secondAxisY )
: QDialog( parent ? parent : 0,
- "Plot2d_FitDataDlg",
- true,
- WStyle_Customize | WStyle_NormalBorder | WStyle_Title | WStyle_SysMenu ),
- myY2MinEdit( 0 ), myY2MaxEdit( 0 ), mySecondAxisY( secondAxisY )
+ Qt::WindowTitleHint | Qt::WindowSystemMenuHint ),
+ myY2MinEdit( 0 ), myY2MaxEdit( 0 ), mySecondAxisY( secondAxisY )
{
- setCaption( tr( "FIT_DATA_TLT" ) );
+ setObjectName( "Plot2d_FitDataDlg" );
+ setModal( true );
+ setWindowTitle( tr( "FIT_DATA_TLT" ) );
setSizeGripEnabled( TRUE );
QGridLayout* topLayout = new QGridLayout( this );
topLayout->setSpacing( SPACING_SIZE );
topLayout->setMargin( MARGIN_SIZE );
// 'Range' group
- myRangeGrp = new QButtonGroup( this );
- myRangeGrp->setColumnLayout( 0, Qt::Vertical );
- myRangeGrp->layout()->setSpacing( 0 );
- myRangeGrp->layout()->setMargin( 0 );
- QGridLayout* aGridLayout = new QGridLayout( myRangeGrp->layout() );
+ myRangeGrp = new QGroupBox( this );
+ QGridLayout* aGridLayout = new QGridLayout( myRangeGrp );
+ myRangeGrp->setLayout( aGridLayout );
aGridLayout->setAlignment( Qt::AlignTop );
aGridLayout->setMargin( MARGIN_SIZE );
aGridLayout->setSpacing( SPACING_SIZE );
QFont font = horLab->font(); font.setBold( true );
horLab->setFont( font ); verLab->setFont( font );
- aGridLayout->addMultiCellLayout( aModeLayout, 0, 0, 0, 4 );
- aGridLayout->addMultiCellWidget( aHLine, 1, 1, 0, 4 );
- aGridLayout->addWidget ( horLab, 2, 0 );
- aGridLayout->addWidget ( new QLabel( tr( "MIN_VALUE_LAB" ), myRangeGrp ),
- 2, 1 );
- aGridLayout->addWidget ( myXMinEdit, 2, 2 );
- aGridLayout->addWidget ( new QLabel( tr( "MAX_VALUE_LAB" ), myRangeGrp ),
- 2, 3 );
- aGridLayout->addWidget ( myXMaxEdit, 2, 4 );
- aGridLayout->addWidget ( verLab, 3, 0 );
- aGridLayout->addWidget ( new QLabel( tr( "MIN_VALUE_LAB" ), myRangeGrp ),
- 3, 1 );
- aGridLayout->addWidget ( myYMinEdit, 3, 2 );
- aGridLayout->addWidget ( new QLabel( tr( "MAX_VALUE_LAB" ), myRangeGrp ),
- 3, 3 );
- aGridLayout->addWidget ( myYMaxEdit, 3, 4 );
+ aGridLayout->addLayout( aModeLayout, 0, 0, 1, 5 );
+ aGridLayout->addWidget( aHLine, 1, 0, 1, 5 );
+ aGridLayout->addWidget( horLab, 2, 0 );
+ aGridLayout->addWidget( new QLabel( tr( "MIN_VALUE_LAB" ), myRangeGrp ),
+ 2, 1 );
+ aGridLayout->addWidget( myXMinEdit, 2, 2 );
+ aGridLayout->addWidget( new QLabel( tr( "MAX_VALUE_LAB" ), myRangeGrp ),
+ 2, 3 );
+ aGridLayout->addWidget( myXMaxEdit, 2, 4 );
+ aGridLayout->addWidget( verLab, 3, 0 );
+ aGridLayout->addWidget( new QLabel( tr( "MIN_VALUE_LAB" ), myRangeGrp ),
+ 3, 1 );
+ aGridLayout->addWidget( myYMinEdit, 3, 2 );
+ aGridLayout->addWidget( new QLabel( tr( "MAX_VALUE_LAB" ), myRangeGrp ),
+ 3, 3 );
+ aGridLayout->addWidget( myYMaxEdit, 3, 4 );
if (mySecondAxisY) {
QLabel* ver2Lab = new QLabel(tr( "VERTICAL_RIGHT_AXIS" ), myRangeGrp );
ver2Lab->setFont( font );
- aGridLayout->addWidget ( ver2Lab, 4, 0 );
- aGridLayout->addWidget ( new QLabel( tr( "MIN_VALUE_LAB" ), myRangeGrp ),
- 4, 1 );
- aGridLayout->addWidget ( myY2MinEdit, 4, 2 );
- aGridLayout->addWidget ( new QLabel( tr( "MAX_VALUE_LAB" ), myRangeGrp ),
- 4, 3 );
- aGridLayout->addWidget ( myY2MaxEdit, 4, 4 );
+ aGridLayout->addWidget( ver2Lab, 4, 0 );
+ aGridLayout->addWidget( new QLabel( tr( "MIN_VALUE_LAB" ), myRangeGrp ),
+ 4, 1 );
+ aGridLayout->addWidget( myY2MinEdit, 4, 2 );
+ aGridLayout->addWidget( new QLabel( tr( "MAX_VALUE_LAB" ), myRangeGrp ),
+ 4, 3 );
+ aGridLayout->addWidget( myY2MaxEdit, 4, 4 );
}
// OK/Cancel buttons
- myOkBtn = new QPushButton( tr( "BUT_OK" ), this, "buttonOk" );
+ myOkBtn = new QPushButton( tr( "BUT_OK" ), this );
+ myOkBtn->setObjectName( "buttonOk" );
myOkBtn->setAutoDefault( TRUE );
myOkBtn->setDefault( TRUE );
- myCancelBtn = new QPushButton( tr( "BUT_CANCEL" ), this, "buttonCancel" );
+ myCancelBtn = new QPushButton( tr( "BUT_CANCEL" ), this );
+ myCancelBtn->setObjectName( "buttonCancel" );
myCancelBtn->setAutoDefault( TRUE );
- topLayout->addMultiCellWidget( myRangeGrp, 0, 0, 0, 2 );
+ topLayout->addWidget( myRangeGrp, 0, 0, 1, 3 );
topLayout->addWidget( myOkBtn, 1, 0 );
- topLayout->setColStretch( 1, 5 );
+ topLayout->setColumnStretch( 1, 5 );
topLayout->addWidget( myCancelBtn, 1, 2 );
// connect signals
#define PLOT2D_FITDATADLG_H
#include "Plot2d.h"
-#include <qdialog.h>
+#include <QDialog>
-class QButtonGroup;
+class QGroupBox;
class QRadioButton;
class QLineEdit;
class QPushButton;
void onModeChanged(int);
private:
- QButtonGroup* myRangeGrp;
+ QGroupBox* myRangeGrp;
QRadioButton* myModeAllRB;
QRadioButton* myModeHorRB;
QRadioButton* myModeVerRB;
Default constructor
*/
Plot2d_Prs::Plot2d_Prs( bool theDelete )
-: mySecondY( false)
+: mySecondY( false), myIsAutoDel( theDelete )
{
- setAutoDel(theDelete);
}
/*!
Standard constructor
*/
Plot2d_Prs::Plot2d_Prs( const Plot2d_Curve* obj, bool theDelete )
-: mySecondY( false)
+: mySecondY( false), myIsAutoDel( theDelete )
{
- setAutoDel(theDelete);
AddObject( obj );
}
*/
Plot2d_Prs::~Plot2d_Prs()
{
+ if ( myIsAutoDel )
+ qDeleteAll( myCurves );
}
/*!
*/
void Plot2d_Prs::setAutoDel(bool theDel)
{
- myCurves.setAutoDelete(theDel);
+ myIsAutoDel = theDel;
}
protected:
curveList myCurves;
bool mySecondY;
+ bool myIsAutoDel;
};
#endif
#include <qgroupbox.h>
#include <qcolordialog.h>
-#ifndef WNT
+#ifndef WIN32
using namespace std;
#endif
Constructor
*/
Plot2d_SetupCurveDlg::Plot2d_SetupCurveDlg( QWidget* parent )
- : QDialog( parent, "Plot2d_SetupCurveDlg", true, WStyle_Customize | WStyle_NormalBorder | WStyle_Title | WStyle_SysMenu )
+ : QDialog( parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint )
{
- setCaption( tr("TLT_SETUP_CURVE") );
+ setObjectName( "Plot2d_SetupCurveDlg" );
+ setModal( true );
+ setWindowTitle( tr("TLT_SETUP_CURVE") );
setSizeGripEnabled( TRUE );
QGridLayout* topLayout = new QGridLayout( this );
topLayout->setSpacing( SPACING_SIZE );
topLayout->setMargin( MARGIN_SIZE );
QGroupBox* TopGroup = new QGroupBox( this );
- TopGroup->setColumnLayout( 0, Qt::Vertical );
- TopGroup->layout()->setSpacing( 0 ); TopGroup->layout()->setMargin( 0 );
- QGridLayout* TopGroupLayout = new QGridLayout( TopGroup->layout() );
+ QGridLayout* TopGroupLayout = new QGridLayout( TopGroup );
+ TopGroup->setLayout( TopGroupLayout );
TopGroupLayout->setAlignment( Qt::AlignTop );
TopGroupLayout->setSpacing( SPACING_SIZE ); TopGroupLayout->setMargin( MARGIN_SIZE );
QLabel* aLineTypeLab = new QLabel( tr( "CURVE_LINE_TYPE_LAB" ), TopGroup );
- myLineCombo = new QComboBox( false, TopGroup );
+ myLineCombo = new QComboBox( TopGroup );
+ myLineCombo->setEditable( false );
myLineCombo->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myLineCombo->setMinimumWidth( MIN_COMBO_WIDTH );
- myLineCombo->insertItem( tr( "NONE_LINE_LBL" ) );
- myLineCombo->insertItem( tr( "SOLID_LINE_LBL" ) );
- myLineCombo->insertItem( tr( "DASH_LINE_LBL" ) );
- myLineCombo->insertItem( tr( "DOT_LINE_LBL" ) );
- myLineCombo->insertItem( tr( "DASHDOT_LINE_LBL" ) );
- myLineCombo->insertItem( tr( "DAHSDOTDOT_LINE_LBL" ) );
- myLineCombo->setCurrentItem( 1 ); // SOLID by default
+ myLineCombo->addItem( tr( "NONE_LINE_LBL" ) );
+ myLineCombo->addItem( tr( "SOLID_LINE_LBL" ) );
+ myLineCombo->addItem( tr( "DASH_LINE_LBL" ) );
+ myLineCombo->addItem( tr( "DOT_LINE_LBL" ) );
+ myLineCombo->addItem( tr( "DASHDOT_LINE_LBL" ) );
+ myLineCombo->addItem( tr( "DAHSDOTDOT_LINE_LBL" ) );
+ myLineCombo->setCurrentIndex( 1 ); // SOLID by default
QLabel* aLineWidthLab = new QLabel( tr( "CURVE_LINE_WIDTH_LAB" ), TopGroup );
- myLineSpin = new QSpinBox( 0, MAX_LINE_WIDTH, 1, TopGroup );
+ myLineSpin = new QSpinBox( TopGroup );
+ myLineSpin->setMinimum( 0 );
+ myLineSpin->setMaximum( MAX_LINE_WIDTH );
+ myLineSpin->setSingleStep( 1 );
myLineSpin->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myLineSpin->setMinimumWidth( MIN_SPIN_WIDTH );
myLineSpin->setValue( 0 ); // default width is 0
QLabel* aMarkerLab = new QLabel( tr( "CURVE_MARKER_TYPE_LAB" ), TopGroup );
- myMarkerCombo = new QComboBox( false, TopGroup );
+ myMarkerCombo = new QComboBox( TopGroup );
+ myMarkerCombo->setEditable( false );
myMarkerCombo->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myMarkerCombo->setMinimumWidth( MIN_COMBO_WIDTH );
- myMarkerCombo->insertItem( tr( "NONE_MARKER_LBL" ) );
- myMarkerCombo->insertItem( tr( "CIRCLE_MARKER_LBL" ) );
- myMarkerCombo->insertItem( tr( "RECTANGLE_MARKER_LBL" ) );
- myMarkerCombo->insertItem( tr( "DIAMOND_MARKER_LBL" ) );
- myMarkerCombo->insertItem( tr( "DTRIANGLE_MARKER_LBL" ) );
- myMarkerCombo->insertItem( tr( "UTRIANGLE_MARKER_LBL" ) );
- myMarkerCombo->insertItem( tr( "LTRIANGLE_MARKER_LBL" ) );
- myMarkerCombo->insertItem( tr( "RTRIANGLE_MARKER_LBL" ) );
- myMarkerCombo->insertItem( tr( "CROSS_MARKER_LBL" ) );
- myMarkerCombo->insertItem( tr( "XCROSS_MARKER_LBL" ) );
- myMarkerCombo->setCurrentItem( 1 ); // CIRCLE by default
+ myMarkerCombo->addItem( tr( "NONE_MARKER_LBL" ) );
+ myMarkerCombo->addItem( tr( "CIRCLE_MARKER_LBL" ) );
+ myMarkerCombo->addItem( tr( "RECTANGLE_MARKER_LBL" ) );
+ myMarkerCombo->addItem( tr( "DIAMOND_MARKER_LBL" ) );
+ myMarkerCombo->addItem( tr( "DTRIANGLE_MARKER_LBL" ) );
+ myMarkerCombo->addItem( tr( "UTRIANGLE_MARKER_LBL" ) );
+ myMarkerCombo->addItem( tr( "LTRIANGLE_MARKER_LBL" ) );
+ myMarkerCombo->addItem( tr( "RTRIANGLE_MARKER_LBL" ) );
+ myMarkerCombo->addItem( tr( "CROSS_MARKER_LBL" ) );
+ myMarkerCombo->addItem( tr( "XCROSS_MARKER_LBL" ) );
+ myMarkerCombo->setCurrentIndex( 1 ); // CIRCLE by default
QLabel* aColorLab = new QLabel( tr( "CURVE_COLOR_LAB" ), TopGroup );
myColorBtn = new QToolButton( TopGroup );
myColorBtn->setMinimumSize(25, 25);
TopGroupLayout->addWidget( aLineTypeLab, 0, 0 );
- TopGroupLayout->addMultiCellWidget( myLineCombo, 0, 0, 1, 2 );
+ TopGroupLayout->addWidget( myLineCombo, 0, 1, 1, 2 );
TopGroupLayout->addWidget( aLineWidthLab, 1, 0 );
- TopGroupLayout->addMultiCellWidget( myLineSpin, 1, 1, 1, 2 );
+ TopGroupLayout->addWidget( myLineSpin, 1, 1, 1, 2 );
TopGroupLayout->addWidget( aMarkerLab, 2, 0 );
- TopGroupLayout->addMultiCellWidget( myMarkerCombo, 2, 2, 1, 2 );
+ TopGroupLayout->addWidget( myMarkerCombo, 2, 1, 1, 2 );
TopGroupLayout->addWidget( aColorLab, 3, 0 );
TopGroupLayout->addWidget( myColorBtn, 3, 1 );
- TopGroupLayout->setColStretch( 2, 5 );
+ TopGroupLayout->setColumnStretch( 2, 5 );
QGroupBox* GroupButtons = new QGroupBox( this );
- GroupButtons->setColumnLayout( 0, Qt::Vertical );
- GroupButtons->layout()->setSpacing( 0 ); GroupButtons->layout()->setMargin( 0 );
- QHBoxLayout* GroupButtonsLayout = new QHBoxLayout( GroupButtons->layout() );
+ QHBoxLayout* GroupButtonsLayout = new QHBoxLayout( GroupButtons );
+ GroupButtons->setLayout( GroupButtonsLayout );
GroupButtonsLayout->setAlignment( Qt::AlignTop );
GroupButtonsLayout->setSpacing( SPACING_SIZE ); GroupButtonsLayout->setMargin( MARGIN_SIZE );
*/
void Plot2d_SetupCurveDlg::setLine( const int line, const int width )
{
- myLineCombo->setCurrentItem( line );
+ myLineCombo->setCurrentIndex( line );
myLineSpin->setValue( width );
}
/*!
*/
int Plot2d_SetupCurveDlg::getLine() const
{
- return myLineCombo->currentItem();
+ return myLineCombo->currentIndex();
}
/*!
Gets line width
*/
void Plot2d_SetupCurveDlg::setMarker( const int marker )
{
- myMarkerCombo->setCurrentItem( marker );
+ myMarkerCombo->setCurrentIndex( marker );
}
/*!
Gets marker style
*/
int Plot2d_SetupCurveDlg::getMarker() const
{
- return myMarkerCombo->currentItem();
+ return myMarkerCombo->currentIndex();
}
/*!
Sets color
void Plot2d_SetupCurveDlg::setColor( const QColor& color )
{
QPalette pal = myColorBtn->palette();
- QColorGroup ca = pal.active();
- ca.setColor( QColorGroup::Button, color );
- QColorGroup ci = pal.inactive();
- ci.setColor( QColorGroup::Button, color );
- pal.setActive( ca );
- pal.setInactive( ci );
+ pal.setColor( QPalette::Active, QPalette::Button, color );
+ pal.setColor( QPalette::Inactive, QPalette::Button, color );
+
myColorBtn->setPalette( pal );
}
/*!
*/
QColor Plot2d_SetupCurveDlg::getColor() const
{
- return myColorBtn->palette().active().button();
+ return myColorBtn->palette().color( QPalette::Active, QPalette::Button );
}
/*!
<Color> button slot, invokes color selection dialog box
#include "Plot2d_SetupViewDlg.h"
-#include <qcheckbox.h>
-#include <qlineedit.h>
-#include <qcombobox.h>
-#include <qspinbox.h>
-#include <qtoolbutton.h>
-#include <qlayout.h>
-#include <qgroupbox.h>
-#include <qlabel.h>
-#include <qpushbutton.h>
-#include <qcolordialog.h>
-#include <qtabwidget.h>
+#include <QCheckBox>
+#include <QLineEdit>
+#include <QComboBox>
+#include <QSpinBox>
+#include <QToolButton>
+#include <QLayout>
+#include <QGroupBox>
+#include <QLabel>
+#include <QPushButton>
+#include <QColorDialog>
+#include <QTabWidget>
#define MARGIN_SIZE 11
#define SPACING_SIZE 6
Constructor
*/
Plot2d_SetupViewDlg::Plot2d_SetupViewDlg( QWidget* parent, bool showDefCheck, bool secondAxisY )
- : QDialog( parent, "Plot2d_SetupViewDlg", true,
- WStyle_Customize | WStyle_NormalBorder | WStyle_Title | WStyle_SysMenu )
+ : QDialog( parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint )
{
+ setObjectName( "Plot2d_SetupViewDlg" );
+ setModal( true );
mySecondAxisY = secondAxisY;
- setCaption( tr("TLT_SETUP_PLOT2D_VIEW") );
+ setWindowTitle( tr("TLT_SETUP_PLOT2D_VIEW") );
setSizeGripEnabled( TRUE );
QGridLayout* topLayout = new QGridLayout( this );
topLayout->setSpacing( SPACING_SIZE );
myTitleEdit->setMinimumWidth( MIN_EDIT_WIDTH );
// curve type : points, lines, spline
QLabel* aCurveLab = new QLabel( tr( "PLOT2D_CURVE_TYPE_LBL" ), this );
- myCurveCombo = new QComboBox( false, this );
+ myCurveCombo = new QComboBox( this );
+ myCurveCombo->setEditable( false );
myCurveCombo->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myCurveCombo->setMinimumWidth( MIN_COMBO_WIDTH );
- myCurveCombo->insertItem( tr( "PLOT2D_CURVE_TYPE_POINTS" ) );
- myCurveCombo->insertItem( tr( "PLOT2D_CURVE_TYPE_LINES" ) );
- myCurveCombo->insertItem( tr( "PLOT2D_CURVE_TYPE_SPLINE" ) );
+ myCurveCombo->addItem( tr( "PLOT2D_CURVE_TYPE_POINTS" ) );
+ myCurveCombo->addItem( tr( "PLOT2D_CURVE_TYPE_LINES" ) );
+ myCurveCombo->addItem( tr( "PLOT2D_CURVE_TYPE_SPLINE" ) );
// legend
myLegendCheck = new QCheckBox( tr( "PLOT2D_ENABLE_LEGEND" ), this );
- myLegendCombo = new QComboBox( false, this );
+ myLegendCombo = new QComboBox( this );
+ myCurveCombo->setEditable( false );
myLegendCombo->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myLegendCombo->setMinimumWidth( MIN_COMBO_WIDTH );
- myLegendCombo->insertItem( tr( "PLOT2D_LEGEND_POSITION_LEFT" ) );
- myLegendCombo->insertItem( tr( "PLOT2D_LEGEND_POSITION_RIGHT" ) );
- myLegendCombo->insertItem( tr( "PLOT2D_LEGEND_POSITION_TOP" ) );
- myLegendCombo->insertItem( tr( "PLOT2D_LEGEND_POSITION_BOTTOM" ) );
+ myLegendCombo->addItem( tr( "PLOT2D_LEGEND_POSITION_LEFT" ) );
+ myLegendCombo->addItem( tr( "PLOT2D_LEGEND_POSITION_RIGHT" ) );
+ myLegendCombo->addItem( tr( "PLOT2D_LEGEND_POSITION_TOP" ) );
+ myLegendCombo->addItem( tr( "PLOT2D_LEGEND_POSITION_BOTTOM" ) );
// marker size
QLabel* aMarkerLab = new QLabel( tr( "PLOT2D_MARKER_SIZE_LBL" ), this );
- myMarkerSpin = new QSpinBox( 0, 100, 1, this );
+ myMarkerSpin = new QSpinBox( this );
+ myMarkerSpin->setMinimum( 0 );
+ myMarkerSpin->setMaximum( 100 );
+ myMarkerSpin->setSingleStep( 1 );
myMarkerSpin->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myMarkerSpin->setMinimumWidth( MIN_SPIN_WIDTH );
// scale mode
QGroupBox* aScaleGrp = new QGroupBox( tr( "PLOT2D_SCALE_TLT" ), this );
- aScaleGrp->setColumnLayout(0, Qt::Vertical );
- aScaleGrp->layout()->setSpacing( 0 ); aScaleGrp->layout()->setMargin( 0 );
- QGridLayout* aScaleLayout = new QGridLayout( aScaleGrp->layout() );
+ QGridLayout* aScaleLayout = new QGridLayout( aScaleGrp );
aScaleLayout->setMargin( MARGIN_SIZE ); aScaleLayout->setSpacing( SPACING_SIZE );
+ aScaleGrp->setLayout( aScaleLayout );
QLabel* xScaleLab = new QLabel( tr( "PLOT2D_SCALE_MODE_HOR" ), aScaleGrp );
- myXModeCombo = new QComboBox( false, aScaleGrp );
+ myXModeCombo = new QComboBox( aScaleGrp );
+ myCurveCombo->setEditable( false );
myXModeCombo->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myXModeCombo->setMinimumWidth( MIN_COMBO_WIDTH );
- myXModeCombo->insertItem( tr( "PLOT2D_SCALE_MODE_LINEAR" ) );
- myXModeCombo->insertItem( tr( "PLOT2D_SCALE_MODE_LOGARITHMIC" ) );
+ myXModeCombo->addItem( tr( "PLOT2D_SCALE_MODE_LINEAR" ) );
+ myXModeCombo->addItem( tr( "PLOT2D_SCALE_MODE_LOGARITHMIC" ) );
QLabel* yScaleLab = new QLabel( tr( "PLOT2D_SCALE_MODE_VER" ), aScaleGrp );
- myYModeCombo = new QComboBox( false, aScaleGrp );
+ myYModeCombo = new QComboBox( aScaleGrp );
+ myCurveCombo->setEditable( false );
myYModeCombo->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myYModeCombo->setMinimumWidth( MIN_COMBO_WIDTH );
- myYModeCombo->insertItem( tr( "PLOT2D_SCALE_MODE_LINEAR" ) );
- myYModeCombo->insertItem( tr( "PLOT2D_SCALE_MODE_LOGARITHMIC" ) );
+ myYModeCombo->addItem( tr( "PLOT2D_SCALE_MODE_LINEAR" ) );
+ myYModeCombo->addItem( tr( "PLOT2D_SCALE_MODE_LOGARITHMIC" ) );
aScaleLayout->addWidget( xScaleLab, 0, 0 );
aScaleLayout->addWidget( myXModeCombo, 0, 1 );
aScaleLayout->addWidget( myYModeCombo, 0, 3 );
// tab widget for choose properties of axis
- QTabWidget* aTabWidget = new QTabWidget( this, "tabWidget" );
+ QTabWidget* aTabWidget = new QTabWidget( this );
+ aTabWidget->setObjectName( "tabWidget" );
// widget for parameters on Ox
QWidget* aXWidget = new QWidget(aTabWidget);
myTitleXEdit = new QLineEdit( aXWidget );
myTitleXEdit->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myTitleXEdit->setMinimumWidth( MIN_EDIT_WIDTH );
- aXLayout->addWidget( myTitleXCheck, 1, 0 );
- aXLayout->addMultiCellWidget( myTitleXEdit, 1, 1, 1, 3 );
+ aXLayout->addWidget( myTitleXCheck,1, 0 );
+ aXLayout->addWidget( myTitleXEdit, 1, 1, 1, 3 );
// grid
QGroupBox* aGridGrpX = new QGroupBox( tr( "PLOT2D_GRID_TLT" ), aXWidget );
- aGridGrpX->setColumnLayout(0, Qt::Vertical );
- aGridGrpX->layout()->setSpacing( 0 ); aGridGrpX->layout()->setMargin( 0 );
- QGridLayout* aGridLayoutX = new QGridLayout( aGridGrpX->layout() );
+ QGridLayout* aGridLayoutX = new QGridLayout( aGridGrpX );
+ aGridGrpX->setLayout( aGridLayoutX );
aGridLayoutX->setMargin( MARGIN_SIZE ); aGridLayoutX->setSpacing( SPACING_SIZE );
myXGridCheck = new QCheckBox( tr( "PLOT2D_GRID_ENABLE_HOR_MAJOR" ), aGridGrpX );
QLabel* aXMajLbl = new QLabel( tr( "PLOT2D_MAX_INTERVALS" ), aGridGrpX);
- myXGridSpin = new QSpinBox( 1, 100, 1, aGridGrpX );
+ myXGridSpin = new QSpinBox( aGridGrpX );
+ myXGridSpin->setMinimum( 1 );
+ myXGridSpin->setMaximum( 100 );
+ myXGridSpin->setSingleStep( 1 );
myXGridSpin->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myXGridSpin->setMinimumWidth( MIN_SPIN_WIDTH );
myXMinGridCheck = new QCheckBox( tr( "PLOT2D_GRID_ENABLE_HOR_MINOR" ), aGridGrpX );
QLabel* aXMinLbl = new QLabel( tr( "PLOT2D_MAX_INTERVALS" ), aGridGrpX);
- myXMinGridSpin = new QSpinBox( 1, 100, 1, aGridGrpX );
+ myXMinGridSpin = new QSpinBox( aGridGrpX );
+ myXMinGridSpin->setMinimum( 1 );
+ myXMinGridSpin->setMaximum( 100 );
+ myXMinGridSpin->setSingleStep( 1 );
myXMinGridSpin->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myXMinGridSpin->setMinimumWidth( MIN_SPIN_WIDTH );
aGridLayoutX->addWidget( myXMinGridCheck, 1, 0 );
aGridLayoutX->addWidget( aXMinLbl, 1, 1 );
aGridLayoutX->addWidget( myXMinGridSpin, 1, 2 );
- aXLayout->addMultiCellWidget( aGridGrpX, 3, 3, 0, 3 );
+ aXLayout->addWidget( aGridGrpX, 3, 0, 1, 4 );
aTabWidget->addTab( aXWidget, tr( "INF_AXES_X" ) );
myTitleYEdit = new QLineEdit( aYWidget );
myTitleYEdit->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myTitleYEdit->setMinimumWidth( MIN_EDIT_WIDTH );
- aYLayout->addWidget( myTitleYCheck, 1, 0 );
- aYLayout->addMultiCellWidget( myTitleYEdit, 1, 1, 1, 3 );
+ aYLayout->addWidget( myTitleYCheck,1, 0 );
+ aYLayout->addWidget( myTitleYEdit, 1, 1, 1, 3 );
// grid
QGroupBox* aGridGrpY = new QGroupBox( tr( "PLOT2D_GRID_TLT" ), aYWidget );
- aGridGrpY->setColumnLayout(0, Qt::Vertical );
- aGridGrpY->layout()->setSpacing( 0 ); aGridGrpY->layout()->setMargin( 0 );
- QGridLayout* aGridLayoutY = new QGridLayout( aGridGrpY->layout() );
+ QGridLayout* aGridLayoutY = new QGridLayout( aGridGrpY );
+ aGridGrpY->setLayout( aGridLayoutY );
aGridLayoutY->setMargin( MARGIN_SIZE ); aGridLayoutY->setSpacing( SPACING_SIZE );
myYGridCheck = new QCheckBox( tr( "PLOT2D_GRID_ENABLE_VER_MAJOR" ), aGridGrpY );
QLabel* aYMajLbl = new QLabel( tr( "PLOT2D_MAX_INTERVALS" ), aGridGrpY);
- myYGridSpin = new QSpinBox( 1, 100, 1, aGridGrpY );
+ myYGridSpin = new QSpinBox( aGridGrpY );
+ myYGridSpin->setMinimum( 1 );
+ myYGridSpin->setMaximum( 100 );
+ myYGridSpin->setSingleStep( 1 );
myYGridSpin->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myYGridSpin->setMinimumWidth( MIN_SPIN_WIDTH );
myYMinGridCheck = new QCheckBox( tr( "PLOT2D_GRID_ENABLE_VER_MINOR" ), aGridGrpY );
QLabel* aYMinLbl = new QLabel( tr( "PLOT2D_MAX_INTERVALS" ), aGridGrpY);
- myYMinGridSpin = new QSpinBox( 1, 100, 1, aGridGrpY );
+ myYMinGridSpin = new QSpinBox( aGridGrpY );
+ myYMinGridSpin->setMinimum( 1 );
+ myYMinGridSpin->setMaximum( 100 );
+ myYMinGridSpin->setSingleStep( 1 );
myYMinGridSpin->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myYMinGridSpin->setMinimumWidth( MIN_SPIN_WIDTH );
aGridLayoutY->addWidget( myYMinGridCheck, 1, 0 );
aGridLayoutY->addWidget( aYMinLbl, 1, 1 );
aGridLayoutY->addWidget( myYMinGridSpin, 1, 2 );
- aYLayout->addMultiCellWidget( aGridGrpY, 3, 3, 0, 3 );
+ aYLayout->addWidget( aGridGrpY, 3, 0, 1, 4 );
aTabWidget->addTab( aYWidget, tr( "INF_AXES_Y_LEFT" ) );
myTitleY2Edit = new QLineEdit( aYWidget2 );
myTitleY2Edit->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myTitleY2Edit->setMinimumWidth( MIN_EDIT_WIDTH );
- aYLayout2->addWidget( myTitleY2Check, 1, 0 );
- aYLayout2->addMultiCellWidget( myTitleY2Edit, 1, 1, 1, 3 );
+ aYLayout2->addWidget( myTitleY2Check,1, 0 );
+ aYLayout2->addWidget( myTitleY2Edit, 1, 1, 1, 3 );
// grid
QGroupBox* aGridGrpY2 = new QGroupBox( tr( "PLOT2D_GRID_TLT" ), aYWidget2 );
- aGridGrpY2->setColumnLayout(0, Qt::Vertical );
- aGridGrpY2->layout()->setSpacing( 0 ); aGridGrpY2->layout()->setMargin( 0 );
- QGridLayout* aGridLayoutY2 = new QGridLayout( aGridGrpY2->layout() );
+ QGridLayout* aGridLayoutY2 = new QGridLayout( aGridGrpY2 );
+ aGridGrpY2->setLayout( aGridLayoutY2 );
aGridLayoutY2->setMargin( MARGIN_SIZE ); aGridLayoutY2->setSpacing( SPACING_SIZE );
myY2GridCheck = new QCheckBox( tr( "PLOT2D_GRID_ENABLE_VER_MAJOR" ), aGridGrpY2 );
QLabel* aY2MajLbl = new QLabel( tr( "PLOT2D_MAX_INTERVALS" ), aGridGrpY2);
- myY2GridSpin = new QSpinBox( 1, 100, 1, aGridGrpY2 );
+ myY2GridSpin = new QSpinBox( aGridGrpY2 );
+ myY2GridSpin->setMinimum( 1 );
+ myY2GridSpin->setMaximum( 100 );
+ myY2GridSpin->setSingleStep( 1 );
myY2GridSpin->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myY2GridSpin->setMinimumWidth( MIN_SPIN_WIDTH );
myY2MinGridCheck = new QCheckBox( tr( "PLOT2D_GRID_ENABLE_VER_MINOR" ), aGridGrpY2 );
QLabel* aY2MinLbl = new QLabel( tr( "PLOT2D_MAX_INTERVALS" ), aGridGrpY2);
- myY2MinGridSpin = new QSpinBox( 1, 100, 1, aGridGrpY2 );
+ myY2MinGridSpin = new QSpinBox( aGridGrpY2 );
+ myY2MinGridSpin->setMinimum( 1 );
+ myY2MinGridSpin->setMaximum( 100 );
+ myY2MinGridSpin->setSingleStep( 1 );
myY2MinGridSpin->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myY2MinGridSpin->setMinimumWidth( MIN_SPIN_WIDTH );
aGridLayoutY2->addWidget( myY2MinGridCheck, 1, 0 );
aGridLayoutY2->addWidget( aY2MinLbl, 1, 1 );
aGridLayoutY2->addWidget( myY2MinGridSpin, 1, 2 );
- aYLayout2->addMultiCellWidget( aGridGrpY2, 3, 3, 0, 3 );
+ aYLayout2->addWidget( aGridGrpY2, 3, 0, 1, 4 );
aTabWidget->addTab( aYWidget2, tr( "INF_AXES_Y_RIGHT" ) );
}
myY2MinGridSpin = 0;
myY2ModeCombo = 0;
}
- aTabWidget->setCurrentPage( 0 );
+ aTabWidget->setCurrentIndex( 0 );
/* "Set as default" check box */
myDefCheck = new QCheckBox( tr( "PLOT2D_SET_AS_DEFAULT_CHECK" ), this );
/* OK/Cancel buttons */
btnLayout->addWidget( myCancelBtn );
// layout widgets
- topLayout->addWidget( myTitleCheck, 0, 0 );
- topLayout->addMultiCellWidget( myTitleEdit, 0, 0, 1, 3 );
- topLayout->addWidget( aCurveLab, 1, 0 );
- topLayout->addWidget( myCurveCombo, 1, 1 );
- topLayout->addWidget( myLegendCheck, 1, 2 );
- topLayout->addWidget( myLegendCombo, 1, 3 );
- topLayout->addWidget( aMarkerLab, 2, 0 );
- topLayout->addWidget( myMarkerSpin, 2, 1 );
+ topLayout->addWidget( myTitleCheck, 0, 0 );
+ topLayout->addWidget( myTitleEdit, 0, 1, 1, 3 );
+ topLayout->addWidget( aCurveLab, 1, 0 );
+ topLayout->addWidget( myCurveCombo, 1, 1 );
+ topLayout->addWidget( myLegendCheck, 1, 2 );
+ topLayout->addWidget( myLegendCombo, 1, 3 );
+ topLayout->addWidget( aMarkerLab, 2, 0 );
+ topLayout->addWidget( myMarkerSpin, 2, 1 );
QHBoxLayout* bgLayout = new QHBoxLayout;
bgLayout->addWidget( myBackgroundBtn ); bgLayout->addStretch();
- topLayout->addWidget( aBGLab, 2, 2 );
- topLayout->addLayout( bgLayout, 2, 3 );
- topLayout->addMultiCellWidget( aScaleGrp, 3, 3, 0, 3 );
- topLayout->addMultiCellWidget( aTabWidget, 4, 4, 0, 3 );
- topLayout->addMultiCellWidget( myDefCheck, 5, 5, 0, 3 );
+ topLayout->addWidget( aBGLab, 2, 2 );
+ topLayout->addLayout( bgLayout, 2, 3 );
+ topLayout->addWidget( aScaleGrp, 3, 0, 1, 4 );
+ topLayout->addWidget( aTabWidget, 4, 0, 1, 4 );
+ topLayout->addWidget( myDefCheck, 5, 0, 1, 4 );
topLayout->setRowStretch( 5, 5 );
- topLayout->addMultiCellLayout( btnLayout, 6, 6, 0, 3 );
+ topLayout->addLayout( btnLayout, 6, 0, 1, 4 );
if ( !showDefCheck )
myDefCheck->hide();
*/
void Plot2d_SetupViewDlg::setCurveType( const int type )
{
- myCurveCombo->setCurrentItem( type );
+ myCurveCombo->setCurrentIndex( type );
}
/*!
Gets curve type : 0 - points, 1 - lines, 2 - splines
*/
int Plot2d_SetupViewDlg::getCurveType()
{
- return myCurveCombo->currentItem();
+ return myCurveCombo->currentIndex();
}
/*!
Sets legend attributes : pos = 0 - left, 1 - right, 2 - top, 3 - bottom
void Plot2d_SetupViewDlg::setLegend( bool enable, int pos )
{
myLegendCheck->setChecked( enable );
- myLegendCombo->setCurrentItem( pos );
+ myLegendCombo->setCurrentIndex( pos );
onLegendChecked();
}
/*!
*/
int Plot2d_SetupViewDlg::getLegendPos()
{
- return myLegendCombo->currentItem();
+ return myLegendCombo->currentIndex();
}
/*!
Sets marker size
void Plot2d_SetupViewDlg::setBackgroundColor( const QColor& color )
{
QPalette pal = myBackgroundBtn->palette();
- QColorGroup ca = pal.active();
- ca.setColor( QColorGroup::Button, color );
- QColorGroup ci = pal.inactive();
- ci.setColor( QColorGroup::Button, color );
- pal.setActive( ca );
- pal.setInactive( ci );
+ pal.setColor( QPalette::Active, QPalette::Button, color );
+ pal.setColor( QPalette::Inactive, QPalette::Button, color );
+
myBackgroundBtn->setPalette( pal );
}
/*!
*/
QColor Plot2d_SetupViewDlg::getBackgroundColor()
{
- return myBackgroundBtn->palette().active().button();
+ return myBackgroundBtn->palette().color( QPalette::Active, QPalette::Button );
}
/*!
Sets major grid parameters
*/
void Plot2d_SetupViewDlg::setScaleMode( const int xMode, const int yMode )
{
- myXModeCombo->setCurrentItem( xMode );
- myYModeCombo->setCurrentItem( yMode );
+ myXModeCombo->setCurrentIndex( xMode );
+ myYModeCombo->setCurrentIndex( yMode );
}
/*!
Gets scale mode for hor. axis : 0 - linear, 1 - logarithmic
*/
int Plot2d_SetupViewDlg::getXScaleMode()
{
- return myXModeCombo->currentItem();
+ return myXModeCombo->currentIndex();
}
/*!
Gets scale mode for hor. axis : 0 - linear, 1 - logarithmic
*/
int Plot2d_SetupViewDlg::getYScaleMode()
{
- return myYModeCombo->currentItem();
+ return myYModeCombo->currentIndex();
}
/*!
Slot, called when user clicks "Show main title" check box
#define PLOT2D_SETUPVIEWDLG_H
#include "Plot2d.h"
-#include <qdialog.h>
+#include <QDialog>
class QSpinBox;
class QCheckBox;
#include <Plot2d_ViewFrame.h>
#include <Plot2d_Curve.h>
-#include <qfontmetrics.h>
+#include <QFontMetrics>
+#include <QEvent>
+#include <QMouseEvent>
#include <qwt_plot.h>
#include <qwt_plot_canvas.h>
void Plot2d_ToolTip::onToolTip( QPoint p, QString& str, QFont& f, QRect& txtRect, QRect& rect )
{
- int curInd, pInd, dist;
- double x, y;
- curInd = myPlot->closestCurve( p.x(), p.y(), dist, x, y, pInd );
+ int pInd;
+ double dist;
- if( dist>maxDist )
- return;
-
- Plot2d_Curve* c = myFrame->getCurves().find( curInd );
- if( !c )
+ Plot2d_Curve* c = myPlot->getClosestCurve( p, dist, pInd );
+ if( !c || dist>maxDist )
return;
str = c->text( pInd );
- if( !str )
+ if( str.isEmpty() )
return;
QFontMetrics m( f );
- QStringList lst = QStringList::split( "\n", str );
+ QStringList lst = str.split( "\n", QString::SkipEmptyParts );
QStringList::const_iterator anIt = lst.begin(), aLast = lst.end();
int w = 0, h = 0;
for( ; anIt!=aLast; anIt++ )
if( e && e->type() == QEvent::MouseMove )
{
QMouseEvent* me = ( QMouseEvent* )e;
- if( me->state()==0 )
+ if( me->modifiers()==0 )
return true;
}
return res;
Plot2d_ToolTip( Plot2d_ViewFrame*, Plot2d_Plot2d* );
virtual ~Plot2d_ToolTip();
+ virtual bool eventFilter( QObject*, QEvent* );
+
public slots:
void onToolTip( QPoint, QString&, QFont&, QRect&, QRect& );
-protected:
- virtual bool eventFilter( QObject*, QEvent* );
-
private:
Plot2d_ViewFrame* myFrame;
Plot2d_Plot2d* myPlot;
#include "SUIT_ResourceMgr.h"
#include "SUIT_Application.h"
-#include "qapplication.h"
-#include <qtoolbar.h>
-#include <qtoolbutton.h>
-#include <qcursor.h>
-#include <qcolordialog.h>
-#include <qptrlist.h>
-#include <qlayout.h>
-#include <qmap.h>
-#include <qpainter.h>
-#include <qpaintdevicemetrics.h>
-#include <qevent.h>
+#include <QApplication>
+#include <QToolBar>
+#include <QToolButton>
+#include <QCursor>
+#include <QColorDialog>
+#include <QLayout>
+#include <QMap>
+#include <QPainter>
+#include <QPaintDevice>
+#include <QEvent>
+#include <QMouseEvent>
+#include <QContextMenuEvent>
+#include <QPrinter>
+#include <QPalette>
#include <qwt_math.h>
#include <qwt_plot_canvas.h>
+#include <qwt_scale_div.h>
+#include <qwt_plot_curve.h>
+#include <qwt_plot_grid.h>
+#include <qwt_scale_engine.h>
+#include <qwt_plot_zoomer.h>
+#include <qwt_curve_fitter.h>
+
#include <iostream>
#include <stdlib.h>
#include <qprinter.h>
Constructor
*/
Plot2d_ViewFrame::Plot2d_ViewFrame( QWidget* parent, const QString& title )
- : QWidget (parent, title, 0),
+ : QWidget (parent, 0),
myOperation( NoOpId ),
myCurveType( 1 ),
myShowLegend( true ), myLegendPos( 1 ),
myMarkerSize( DEFAULT_MARKER_SIZE ),
myTitle( "" ), myXTitle( "" ), myYTitle( "" ), myY2Title( "" ),
- myBackground( white ),
+ myBackground( Qt::white ),
myTitleEnabled( true ), myXTitleEnabled( true ),
myYTitleEnabled( true ), myY2TitleEnabled (true),
myXGridMajorEnabled( true ), myYGridMajorEnabled( true ), myY2GridMajorEnabled( true ),
myXGridMaxMinor( 5 ), myYGridMaxMinor( 5 ), myY2GridMaxMinor( 5 ),
myXMode( 0 ), myYMode( 0 ), mySecondY( false )
{
+ setObjectName( title );
/* Plot 2d View */
QVBoxLayout* aLayout = new QVBoxLayout( this );
myPlot = new Plot2d_Plot2d( this );
aLayout->addWidget( myPlot );
// createActions();
-
- connect( myPlot, SIGNAL( plotMouseMoved( const QMouseEvent& ) ),
- this, SLOT( plotMouseMoved( const QMouseEvent& ) ) );
- connect( myPlot, SIGNAL( plotMousePressed( const QMouseEvent& ) ),
- this, SLOT( plotMousePressed( const QMouseEvent& ) ) );
- connect( myPlot, SIGNAL( plotMouseReleased( const QMouseEvent& ) ),
- this, SLOT( plotMouseReleased( const QMouseEvent& ) ) );
//connect( myPlot, SIGNAL( legendClicked( long ) ),
// this, SLOT( onLegendClicked( long ) ) );
if ( parent ) {
resize( (int)(0.8 * parent->width()), (int)(0.8 * parent->height()) );
}
- QwtDiMap xMap = myPlot->canvasMap( QwtPlot::xBottom );
- QwtDiMap yMap = myPlot->canvasMap( QwtPlot::yLeft );
- myXDistance = xMap.d2() - xMap.d1();
- myYDistance = yMap.d2() - yMap.d1();
+ QwtScaleMap xMap = myPlot->canvasMap( QwtPlot::xBottom );
+ QwtScaleMap yMap = myPlot->canvasMap( QwtPlot::yLeft );
+ myXDistance = xMap.s2() - xMap.s1();
+ myYDistance = yMap.s2() - yMap.s1();
myYDistance2 = 0;
if (mySecondY) {
- QwtDiMap yMap2 = myPlot->canvasMap( QwtPlot::yRight );
- myYDistance2 = yMap2.d2() - yMap2.d1();
+ QwtScaleMap yMap2 = myPlot->canvasMap( QwtPlot::yRight );
+ myYDistance2 = yMap2.s2() - yMap2.s1();
}
+ myPlot->canvas()->installEventFilter( this );
}
/*!
Destructor
*/
void Plot2d_ViewFrame::DisplayAll()
{
- QList<Plot2d_Curve> clist;
+ QList<Plot2d_Curve*> clist;
getCurves( clist );
for ( int i = 0; i < (int)clist.count(); i++ ) {
updateCurve( clist.at( i ), false );
void Plot2d_ViewFrame::EraseAll()
{
myPlot->clear();
- myCurves.clear();
+ myPlot->getCurves().clear();
myPlot->replot();
}
/*!
eraseCurves( aCurves );
}
+bool Plot2d_ViewFrame::eventFilter( QObject* watched, QEvent* e )
+{
+ if ( watched == myPlot->canvas() ) {
+ int aType = e->type();
+ switch( aType ) {
+ case QEvent::MouseMove: {
+ QMouseEvent* me = (QMouseEvent*)e;
+ if ( me && ( me->buttons() != 0 || me->button() != 0 ) ) {
+ QMouseEvent m( QEvent::MouseMove, me->pos(), me->button(),
+ me->buttons(), me->modifiers() );
+ if ( plotMouseMoved( m ) )
+ return true;
+ }
+ break;
+ }
+ case QEvent::MouseButtonPress: {
+ QMouseEvent* me = (QMouseEvent*)e;
+ if ( me && ( me->buttons() != 0 || me->button() != 0 ) ) {
+ QMouseEvent m( QEvent::MouseButtonPress, me->pos(), me->button(),
+ me->buttons(), me->modifiers() );
+ plotMousePressed( m );
+ }
+ break;
+ }
+ case QEvent::MouseButtonRelease: {
+ QMouseEvent* me = (QMouseEvent*)e;
+ if ( me && ( me->buttons() != 0 || me->button() != 0 ) ) {
+ QMouseEvent m( QEvent::MouseButtonRelease, me->pos(), me->button(),
+ me->buttons(), me->modifiers() );
+ plotMouseReleased( m );
+ }
+ break;
+ }
+ }
+ }
+ return QWidget::eventFilter( watched, e );
+}
+
/*!
Sets title
*/
myY2GridMaxMinor = resMgr->integerValue( "Plot2d", "VerMinorGridMax", myY2GridMaxMinor );
myXMode = resMgr->integerValue( "Plot2d", "HorScaleMode", myXMode );
- myXMode = QMAX( 0, QMIN( 1, myXMode ) );
+ myXMode = qMax( 0, qMin( 1, myXMode ) );
myYMode = resMgr->integerValue( "Plot2d", "VerScaleMode", myYMode );
- myYMode = QMAX( 0, QMIN( 1, myYMode ) );
+ myYMode = qMax( 0, qMin( 1, myYMode ) );
}
/*!
QString Plot2d_ViewFrame::getInfo( const QPoint& pnt )
{
int i;
+ QwtValueList aTicks;
bool xFound = false, yFound = false;
double xCoord, yCoord;
- const QwtScaleDiv* aXscale = myPlot->axisScale( QwtPlot::xBottom );
- for ( i = 0; i < aXscale->majCnt(); i++ ) {
- double majXmark = aXscale->majMark( i );
+ const QwtScaleDiv* aXscale = myPlot->axisScaleDiv( QwtPlot::xBottom );
+ aTicks = aXscale->ticks( QwtScaleDiv::MajorTick );
+ for ( i = 0; i < aTicks.count(); i++ ) {
+ double majXmark = aTicks[i];
int xmark = myPlot->transform( QwtPlot::xBottom, majXmark );
if ( xmark-2 == pnt.x() ) {
xCoord = majXmark;
}
}
if ( !xFound ) {
- for ( i = 0; i < aXscale->minCnt(); i++ ) {
- double minXmark = aXscale->minMark( i );
+ aTicks = aXscale->ticks( QwtScaleDiv::MinorTick );
+ for ( i = 0; i < aTicks.count(); i++ ) {
+ double minXmark = aTicks[i];
int xmark = myPlot->transform( QwtPlot::xBottom, minXmark );
if ( xmark-2 == pnt.x() ) {
xCoord = minXmark;
}
}
}
- const QwtScaleDiv* aYscale = myPlot->axisScale( QwtPlot::yLeft );
- for ( i = 0; i < aYscale->majCnt(); i++ ) {
- double majYmark = aYscale->majMark( i );
+ const QwtScaleDiv* aYscale = myPlot->axisScaleDiv( QwtPlot::yLeft );
+ aTicks = aYscale->ticks( QwtScaleDiv::MajorTick );
+ for ( i = 0; i < aTicks.count(); i++ ) {
+ double majYmark = aTicks[i];
int ymark = myPlot->transform( QwtPlot::yLeft, majYmark );
if ( ymark-2 == pnt.y() ) {
yCoord = majYmark;
}
}
if ( !yFound ) {
- for ( i = 0; i < aYscale->minCnt(); i++ ) {
- double minYmark = aYscale->minMark( i );
+ aTicks = aYscale->ticks( QwtScaleDiv::MinorTick );
+ for ( i = 0; i < aTicks.count(); i++ ) {
+ double minYmark = aTicks[i];
int ymark = myPlot->transform( QwtPlot::yLeft, minYmark );
if ( ymark-2 == pnt.y() ) {
yCoord = minYmark;
}
}
- QString strX = QString::number( xFound ? xCoord : myPlot->invTransform( QwtPlot::xBottom, pnt.x() ) ).stripWhiteSpace();
+ QString strX = QString::number( xFound ? xCoord : myPlot->invTransform( QwtPlot::xBottom, pnt.x() ) ).trimmed();
if ( strX == "-0" )
strX = "0";
- QString strY = QString::number( yFound ? yCoord : myPlot->invTransform( QwtPlot::yLeft, pnt.y() ) ).stripWhiteSpace();
+ QString strY = QString::number( yFound ? yCoord : myPlot->invTransform( QwtPlot::yLeft, pnt.y() ) ).trimmed();
if ( strY == "-0" )
strY = "0";
QString info = "";
bool yFound2 = false;
double yCoord2;
- const QwtScaleDiv* aYscale2 = myPlot->axisScale( QwtPlot::yRight );
- for ( i = 0; i < aYscale2->majCnt(); i++ ) {
- double majYmark = aYscale2->majMark( i );
+ const QwtScaleDiv* aYscale2 = myPlot->axisScaleDiv( QwtPlot::yRight );
+ aTicks = aYscale2->ticks( QwtScaleDiv::MajorTick );
+ for ( i = 0; i < aTicks.count(); i++ ) {
+ double majYmark = aTicks[i];
int ymark = myPlot->transform( QwtPlot::yRight, majYmark );
if ( ymark-2 == pnt.y() ) {
yCoord2 = majYmark;
}
}
if ( !yFound2 ) {
- for ( i = 0; i < aYscale2->minCnt(); i++ ) {
- double minYmark = aYscale2->minMark( i );
+ aTicks = aYscale2->ticks( QwtScaleDiv::MinorTick );
+ for ( i = 0; i < aTicks.count(); i++ ) {
+ double minYmark = aTicks[i];
int ymark = myPlot->transform( QwtPlot::yRight, minYmark );
if ( ymark-2 == pnt.y() ) {
yCoord2 = minYmark;
}
}
QString strY2 = QString::number( yFound2 ? yCoord2 :
- myPlot->invTransform( QwtPlot::yRight, pnt.y() ) ).stripWhiteSpace();
+ myPlot->invTransform( QwtPlot::yRight, pnt.y() ) ).trimmed();
if ( strY2 == "-0" )
strY2 = "0";
info = tr("INF_COORDINATES_SOME_Y").arg( strX ).arg( strY ).arg( strY2 );
*/
static QwtSymbol::Style plot2qwtMarker( Plot2d_Curve::MarkerType m )
{
- QwtSymbol::Style ms = QwtSymbol::None;
+ QwtSymbol::Style ms = QwtSymbol::NoSymbol;
switch ( m ) {
case Plot2d_Curve::Circle:
ms = QwtSymbol::Ellipse; break;
ms = QwtSymbol::XCross; break;
case Plot2d_Curve::None:
default:
- ms = QwtSymbol::None; break;
+ ms = QwtSymbol::NoSymbol; break;
}
return ms;
}
ms = Plot2d_Curve::Cross; break;
case QwtSymbol::XCross:
ms = Plot2d_Curve::XCross; break;
- case QwtSymbol::None:
+ case QwtSymbol::NoSymbol:
default:
ms = Plot2d_Curve::None; break;
}
if ( myYMode && curve->getMinY() <= 0. )
setVerScaleMode( 0, false );
- if ( hasCurve( curve ) ) {
+ if ( hasPlotCurve( curve ) ) {
updateCurve( curve, update );
}
else {
- long curveKey = myPlot->insertCurve( curve->getVerTitle() );
- myPlot->setCurveYAxis(curveKey, curve->getYAxis());
+ QwtPlotCurve* aPCurve = new QwtPlotCurve( curve->getVerTitle() );
+ aPCurve->attach( myPlot );
+ //myPlot->setCurveYAxis(curveKey, curve->getYAxis());
- myCurves.insert( curveKey, curve );
+ myPlot->getCurves().insert( aPCurve, curve );
if ( curve->isAutoAssign() ) {
QwtSymbol::Style typeMarker;
QColor color;
Qt::PenStyle typeLine;
+
myPlot->getNextMarker( typeMarker, color, typeLine );
- myPlot->setCurvePen( curveKey, QPen( color, DEFAULT_LINE_WIDTH, typeLine ) );
- myPlot->setCurveSymbol( curveKey, QwtSymbol( typeMarker,
+ aPCurve->setPen( QPen( color, DEFAULT_LINE_WIDTH, typeLine ) );
+ aPCurve->setSymbol( QwtSymbol( typeMarker,
QBrush( color ),
QPen( color ),
QSize( myMarkerSize, myMarkerSize ) ) );
else {
Qt::PenStyle ps = plot2qwtLine( curve->getLine() );
QwtSymbol::Style ms = plot2qwtMarker( curve->getMarker() );
- myPlot->setCurvePen( curveKey, QPen( curve->getColor(), curve->getLineWidth(), ps ) );
- myPlot->setCurveSymbol( curveKey, QwtSymbol( ms,
+ aPCurve->setPen( QPen( curve->getColor(), curve->getLineWidth(), ps ) );
+ aPCurve->setSymbol( QwtSymbol( ms,
QBrush( curve->getColor() ),
QPen( curve->getColor() ),
QSize( myMarkerSize, myMarkerSize ) ) );
}
- if ( myCurveType == 0 )
- myPlot->setCurveStyle( curveKey, QwtCurve::NoCurve );
- else if ( myCurveType == 1 )
- myPlot->setCurveStyle( curveKey, QwtCurve::Lines );
- else if ( myCurveType == 2 )
- myPlot->setCurveStyle( curveKey, QwtCurve::Spline );
- myPlot->setCurveData( curveKey, curve->horData(), curve->verData(), curve->nbPoints() );
+ setCurveType( aPCurve, myCurveType );
+ aPCurve->setData( curve->horData(), curve->verData(), curve->nbPoints() );
}
updateTitles();
if ( update )
*/
void Plot2d_ViewFrame::displayCurves( const curveList& curves, bool update )
{
- myPlot->setUpdatesEnabled( false );
- QPtrListIterator<Plot2d_Curve> it(curves);
+ //myPlot->setUpdatesEnabled( false ); // call this function deprecate update of legend
+ QList<Plot2d_Curve*>::const_iterator it = curves.begin();
Plot2d_Curve* aCurve;
- while( (aCurve = it.current()) ) {
+ for (; it != curves.end(); ++it ) {
+ aCurve = *it;
displayCurve( aCurve, false );
- ++it;
}
-
fitAll();
- myPlot->setUpdatesEnabled( true );
+ //myPlot->setUpdatesEnabled( true );
+// update legend
if ( update )
myPlot->replot();
}
{
if ( !curve )
return;
- int curveKey = hasCurve( curve );
- if ( curveKey ) {
- myPlot->removeCurve( curveKey );
- myCurves.remove( curveKey );
+ if ( hasPlotCurve( curve ) ) {
+ QwtPlotCurve* aPCurve = getPlotCurve( curve );
+ aPCurve->hide();
+ aPCurve->detach();
+ myPlot->getCurves().remove( aPCurve );
updateTitles();
if ( update )
myPlot->replot();
*/
void Plot2d_ViewFrame::eraseCurves( const curveList& curves, bool update )
{
- QPtrListIterator<Plot2d_Curve> it(curves);
+ QList<Plot2d_Curve*>::const_iterator it = curves.begin();
Plot2d_Curve* aCurve;
- while( (aCurve = it.current()) ) {
+ for (; it != curves.end(); ++it ) {
+ aCurve = *it;
eraseCurve( aCurve, false );
- ++it;
}
// fitAll();
if ( update )
{
if ( !curve )
return;
- int curveKey = hasCurve( curve );
- if ( curveKey ) {
+ if ( hasPlotCurve( curve ) ) {
+ QwtPlotCurve* aPCurve = getPlotCurve( curve );
if ( !curve->isAutoAssign() ) {
Qt::PenStyle ps = plot2qwtLine( curve->getLine() );
QwtSymbol::Style ms = plot2qwtMarker( curve->getMarker() );
- myPlot->setCurvePen( curveKey, QPen( curve->getColor(), curve->getLineWidth(), ps ) );
- myPlot->setCurveSymbol( curveKey, QwtSymbol( ms,
+ aPCurve->setPen ( QPen( curve->getColor(), curve->getLineWidth(), ps ) );
+ aPCurve->setSymbol( QwtSymbol( ms,
QBrush( curve->getColor() ),
QPen( curve->getColor() ),
QSize( myMarkerSize, myMarkerSize ) ) );
- myPlot->setCurveData( curveKey, curve->horData(), curve->verData(), curve->nbPoints() );
+ aPCurve->setData( curve->horData(), curve->verData(), curve->nbPoints() );
}
- myPlot->setCurveTitle( curveKey, curve->getVerTitle() );
- myPlot->curve( curveKey )->setEnabled( true );
+ aPCurve->setTitle( curve->getVerTitle() );
+ aPCurve->setVisible( true );
if ( update )
myPlot->replot();
}
}
-/*!
- Returns curve key if is is displayed in the viewer and 0 otherwise
-*/
-int Plot2d_ViewFrame::hasCurve( Plot2d_Curve* curve )
-{
- QIntDictIterator<Plot2d_Curve> it( myCurves );
- for ( ; it.current(); ++it ) {
- if ( it.current() == curve )
- return it.currentKey();
- }
- return 0;
-}
-
/*!
Gets lsit of displayed curves
*/
-int Plot2d_ViewFrame::getCurves( QList<Plot2d_Curve>& clist )
+int Plot2d_ViewFrame::getCurves( curveList& clist )
{
clist.clear();
- clist.setAutoDelete( false );
- QIntDictIterator<Plot2d_Curve> it( myCurves );
- for ( ; it.current(); ++it ) {
- clist.append( it.current() );
- }
+
+ CurveDict::iterator it = myPlot->getCurves().begin();
+ for ( ; it != myPlot->getCurves().end(); it++ )
+ clist.append( it.value() );
return clist.count();
}
+const CurveDict& Plot2d_ViewFrame::getCurves()
+{
+ return myPlot->getCurves();
+}
+
/*!
Returns true if the curve is visible
*/
bool Plot2d_ViewFrame::isVisible( Plot2d_Curve* curve )
{
if(curve) {
- int key = hasCurve( curve );
- if ( key )
- return myPlot->curve( key )->enabled();
+ if ( hasPlotCurve( curve ) ) {
+ return getPlotCurve( curve )->isVisible();
+ }
}
return false;
}
return;
curveList aCurves = prs->getCurves();
- QPtrListIterator<Plot2d_Curve> it(aCurves);
+ QList<Plot2d_Curve*>::iterator it = aCurves.begin();
Plot2d_Curve* aCurve;
- while( (aCurve = it.current()) ) {
- int curveKey = hasCurve( aCurve );
- if ( curveKey )
- myPlot->setCurveTitle( curveKey, aCurve->getVerTitle() );
- ++it;
+ for (; it != aCurves.end(); ++it ) {
+ aCurve = *it;
+ if ( hasPlotCurve( aCurve ) )
+ getPlotCurve( aCurve )->setTitle( aCurve->getVerTitle() );
}
}
// Postpone fitAll operation until QwtPlot geometry
// has been fully defined
if ( !myPlot->polished() ){
- QApplication::postEvent( this, new QCustomEvent( FITALL_EVENT ) );
+ QApplication::postEvent( this, new QEvent( (QEvent::Type)FITALL_EVENT ) );
return;
}
- QwtDiMap xMap1 = myPlot->canvasMap( QwtPlot::xBottom );
-
myPlot->setAxisAutoScale( QwtPlot::yLeft );
myPlot->setAxisAutoScale( QwtPlot::xBottom );
myPlot->replot();
// for existing grid
- QwtDiMap xMap = myPlot->canvasMap( QwtPlot::xBottom );
- QwtDiMap yMap = myPlot->canvasMap( QwtPlot::yLeft );
+ QwtScaleMap xMap = myPlot->canvasMap( QwtPlot::xBottom );
+ QwtScaleMap yMap = myPlot->canvasMap( QwtPlot::yLeft );
- myPlot->setAxisScale( QwtPlot::xBottom,
- myPlot->invTransform( QwtPlot::xBottom, xMap.i1() ),
- myPlot->invTransform( QwtPlot::xBottom, xMap.i2() ) );
- myPlot->setAxisScale( QwtPlot::yLeft,
- myPlot->invTransform( QwtPlot::yLeft, yMap.i1() ),
- myPlot->invTransform( QwtPlot::yLeft, yMap.i2() ) );
+ myPlot->setAxisScale( QwtPlot::xBottom, xMap.s1(), xMap.s2() );
+ myPlot->setAxisScale( QwtPlot::yLeft, yMap.s1(), yMap.s2() );
if (mySecondY) {
myPlot->setAxisAutoScale( QwtPlot::yRight );
myPlot->replot();
- QwtDiMap yMap2 = myPlot->canvasMap( QwtPlot::yRight );
- myPlot->setAxisScale( QwtPlot::yRight,
- myPlot->invTransform( QwtPlot::yRight, yMap2.i1() ),
- myPlot->invTransform( QwtPlot::yRight, yMap2.i2() ) );
+ QwtScaleMap yMap2 = myPlot->canvasMap( QwtPlot::yRight );
+ myPlot->setAxisScale( QwtPlot::yRight, yMap2.s1(), yMap2.s2() );
}
myPlot->replot();
}
*/
void Plot2d_ViewFrame::fitArea( const QRect& area )
{
- QRect rect = area.normalize();
+ QRect rect = area.normalized();
if ( rect.width() < MIN_RECT_SIZE ) {
rect.setWidth( MIN_RECT_SIZE );
rect.setLeft( rect.left() - MIN_RECT_SIZE/2 );
double y2Min, double y2Max)
{
if ( mode == 0 || mode == 2 ) {
- myPlot->setAxisScale( QwtPlot::yLeft, yMax, yMin );
+ myPlot->setAxisScale( QwtPlot::yLeft, yMin, yMax );
if (mySecondY)
- myPlot->setAxisScale( QwtPlot::yRight, y2Max, y2Min );
+ myPlot->setAxisScale( QwtPlot::yRight, y2Min, y2Max );
}
if ( mode == 0 || mode == 1 )
myPlot->setAxisScale( QwtPlot::xBottom, xMin, xMax );
double& yMin, double& yMax,
double& y2Min, double& y2Max)
{
- int ixMin = myPlot->canvasMap( QwtPlot::xBottom ).i1();
- int ixMax = myPlot->canvasMap( QwtPlot::xBottom ).i2();
- int iyMin = myPlot->canvasMap( QwtPlot::yLeft ).i1();
- int iyMax = myPlot->canvasMap( QwtPlot::yLeft ).i2();
+ int ixMin = myPlot->canvasMap( QwtPlot::xBottom ).transform( myPlot->canvasMap( QwtPlot::xBottom ).s1() );
+ int ixMax = myPlot->canvasMap( QwtPlot::xBottom ).transform( myPlot->canvasMap( QwtPlot::xBottom ).s2() );
+ int iyMin = myPlot->canvasMap( QwtPlot::yLeft ).transform( myPlot->canvasMap( QwtPlot::yLeft ).s1() );
+ int iyMax = myPlot->canvasMap( QwtPlot::yLeft ).transform( myPlot->canvasMap( QwtPlot::yLeft ).s2() );
xMin = myPlot->invTransform(QwtPlot::xBottom, ixMin);
xMax = myPlot->invTransform(QwtPlot::xBottom, ixMax);
yMin = myPlot->invTransform(QwtPlot::yLeft, iyMin);
y2Min = 0;
y2Max = 0;
if (mySecondY) {
- int iyMin = myPlot->canvasMap( QwtPlot::yRight ).i1();
- int iyMax = myPlot->canvasMap( QwtPlot::yRight ).i2();
+ int iyMin = myPlot->canvasMap( QwtPlot::yRight ).transform( myPlot->canvasMap( QwtPlot::yRight ).s1() );
+ int iyMax = myPlot->canvasMap( QwtPlot::yRight ).transform( myPlot->canvasMap( QwtPlot::yRight ).s2() );
y2Min = myPlot->invTransform(QwtPlot::yRight, iyMin);
y2Max = myPlot->invTransform(QwtPlot::yRight, iyMax);
}
*/
int Plot2d_ViewFrame::testOperation( const QMouseEvent& me )
{
- int btn = me.button() | me.state();
- const int zoomBtn = ControlButton | LeftButton;
- const int panBtn = ControlButton | MidButton;
- const int fitBtn = ControlButton | RightButton;
+ int btn = me.button() | me.modifiers();
+ const int zoomBtn = Qt::ControlModifier | Qt::LeftButton;
+ const int panBtn = Qt::ControlModifier | Qt::MidButton;
+ const int fitBtn = Qt::ControlModifier | Qt::RightButton;
switch (btn)
{
void Plot2d_ViewFrame::setCurveType( int curveType, bool update )
{
myCurveType = curveType;
- QArray<long> keys = myPlot->curveKeys();
- for ( int i = 0; i < (int)keys.count(); i++ ) {
- if ( myCurveType == 0 )
- myPlot->setCurveStyle( keys[i], QwtCurve::Dots );//QwtCurve::NoCurve
- else if ( myCurveType == 1 )
- myPlot->setCurveStyle( keys[i], QwtCurve::Lines );
- else if ( myCurveType == 2 )
- myPlot->setCurveStyle( keys[i], QwtCurve::Spline );
+ CurveDict::iterator it = myPlot->getCurves().begin();
+ for ( ; it != myPlot->getCurves().end(); it++ ) {
+ QwtPlotCurve* crv = it.key();
+ if ( crv )
+ setCurveType( crv, myCurveType );
}
if ( update )
myPlot->replot();
\param curveKey - curve id
\param title - new title
*/
-void Plot2d_ViewFrame::setCurveTitle( int curveKey, const QString& title )
+void Plot2d_ViewFrame::setCurveTitle( Plot2d_Curve* curve, const QString& title )
{
- if(myPlot) myPlot->setCurveTitle(curveKey, title);
+ if ( curve && hasPlotCurve( curve ) )
+ getPlotCurve( curve )->setTitle( title );
}
/*!
void Plot2d_ViewFrame::showLegend( bool show, bool update )
{
myShowLegend = show;
- myPlot->setAutoLegend( myShowLegend );
- myPlot->enableLegend( myShowLegend );
+ if ( myShowLegend ) {
+ QwtLegend* legend = myPlot->legend();
+ if ( !legend ) {
+ legend = new QwtLegend( myPlot );
+ legend->setFrameStyle( QFrame::Box | QFrame::Sunken );
+ }
+ myPlot->insertLegend( legend );
+ setLegendPos( myLegendPos );
+ }
+ else
+ myPlot->insertLegend( 0 );
if ( update )
myPlot->replot();
}
void Plot2d_ViewFrame::setLegendPos( int pos )
{
myLegendPos = pos;
+ QwtLegend* legend = myPlot->legend();
switch( pos ) {
case 0:
- myPlot->setLegendPos( Qwt::Left );
+ myPlot->insertLegend( legend, QwtPlot::LeftLegend );
break;
case 1:
- myPlot->setLegendPos( Qwt::Right );
+ myPlot->insertLegend( legend, QwtPlot::RightLegend );
break;
case 2:
- myPlot->setLegendPos( Qwt::Top );
+ myPlot->insertLegend( legend, QwtPlot::TopLegend );
break;
case 3:
- myPlot->setLegendPos( Qwt::Bottom );
+ myPlot->insertLegend( legend, QwtPlot::BottomLegend );
break;
}
}
if ( myMarkerSize != size )
{
myMarkerSize = size;
- QArray<long> keys = myPlot->curveKeys();
- for ( int i = 0; i < (int)keys.count(); i++ )
- {
- QwtPlotCurve* crv = myPlot->curve( keys[i] );
+ CurveDict::iterator it = myPlot->getCurves().begin();
+ for ( ; it != myPlot->getCurves().end(); it++ ) {
+ QwtPlotCurve* crv = it.key();
if ( crv )
{
QwtSymbol aSymbol = crv->symbol();
aSymbol.setSize( myMarkerSize, myMarkerSize );
- myPlot->setCurveSymbol( keys[i], aSymbol );
+ crv->setSymbol( aSymbol );
}
}
if ( update )
void Plot2d_ViewFrame::setBackgroundColor( const QColor& color )
{
myBackground = color;
- //myPlot->setCanvasBackground( myBackground );
myPlot->canvas()->setPalette( myBackground );
myPlot->setPalette( myBackground );
- QPalette aPal = myPlot->getLegend()->palette();
- for ( int i = 0; i < QPalette::NColorGroups; i++ ) {
- QPalette::ColorGroup cg = (QPalette::ColorGroup)i;
- aPal.setColor( cg, QColorGroup::Base, myBackground );
- aPal.setColor( cg, QColorGroup::Background, myBackground );
+ if ( myPlot->getLegend() ) {
+ QPalette aPal = myPlot->getLegend()->palette();
+ for ( int i = 0; i < QPalette::NColorGroups; i++ ) {
+ aPal.setColor( QPalette::Base, myBackground );
+ aPal.setColor( QPalette::Background, myBackground );
+ }
+ myPlot->getLegend()->setPalette( aPal );
}
- myPlot->getLegend()->setPalette( aPal );
Repaint();
}
/*!
myXGridMinorEnabled = xMinorEnabled;
myXGridMaxMajor = xMajorMax;
myXGridMaxMinor = xMinorMax;
+
myPlot->setAxisMaxMajor( QwtPlot::xBottom, myXGridMaxMajor );
myPlot->setAxisMaxMinor( QwtPlot::xBottom, myXGridMaxMinor );
- myPlot->setGridXAxis(QwtPlot::xBottom);
- myPlot->enableGridX( myXGridMajorEnabled );
- myPlot->enableGridXMin( myXGridMinorEnabled );
+
+ QwtPlotGrid* grid = myPlot->grid();
+ if ( myPlot->axisScaleDiv( QwtPlot::xBottom ) )
+ grid->setXDiv( *myPlot->axisScaleDiv( QwtPlot::xBottom ) );
+ grid->enableX( myXGridMajorEnabled );
+ grid->enableXMin( myXGridMinorEnabled );
+
if ( update )
myPlot->replot();
}
myPlot->setAxisMaxMinor( QwtPlot::yRight, myY2GridMaxMinor );
}
- myPlot->setGridYAxis(QwtPlot::yLeft);
+ QwtPlotGrid* grid = myPlot->grid();
+ if ( myPlot->axisScaleDiv( QwtPlot::yLeft ) )
+ grid->setYDiv( *myPlot->axisScaleDiv( QwtPlot::yLeft ) );
if (mySecondY) {
if (myYGridMajorEnabled) {
- myPlot->enableGridYMin(myYGridMinorEnabled);
- myPlot->enableGridY( myYGridMajorEnabled);
+ grid->enableY( myYGridMajorEnabled );
+ grid->enableYMin( myYGridMinorEnabled );
}
else if (myY2GridMajorEnabled) {
- myPlot->setGridYAxis(QwtPlot::yRight);
- myPlot->enableGridYMin(myY2GridMinorEnabled);
- myPlot->enableGridY(myY2GridMajorEnabled);
+ if ( myPlot->axisScaleDiv( QwtPlot::yRight ) )
+ grid->setYDiv( *myPlot->axisScaleDiv( QwtPlot::yRight ) );
+ grid->enableY( myY2GridMajorEnabled );
+ grid->enableYMin( myY2GridMinorEnabled );
}
else {
- myPlot->enableGridYMin(false);
- myPlot->enableGridY(false);
+ grid->enableY( false );
+ grid->enableYMin( false );
}
}
else {
- myPlot->enableGridY( myYGridMajorEnabled );
- myPlot->enableGridYMin( myYGridMinorEnabled );
+ grid->enableY( myYGridMajorEnabled );
+ grid->enableYMin( myYGridMinorEnabled );
}
if ( update )
myPlot->replot();
{
switch (type) {
case MainTitle:
- myPlot->setTitleFont(font);
+ myPlot->title().setFont(font);
break;
case XTitle:
- myPlot->setAxisTitleFont(QwtPlot::xBottom, font); break;
+ myPlot->axisTitle(QwtPlot::xBottom).setFont(font); break;
case YTitle:
- myPlot->setAxisTitleFont(QwtPlot::yLeft, font); break;
+ myPlot->axisTitle(QwtPlot::yLeft).setFont(font); break;
case Y2Title:
- myPlot->setAxisTitleFont(QwtPlot::yRight, font); break;
+ myPlot->axisTitle(QwtPlot::yRight).setFont(font); break;
case XAxis:
- myPlot->setAxisFont(QwtPlot::xBottom, font); break;
+ myPlot->setAxisFont(QwtPlot::xBottom, font); break;
case YAxis:
- myPlot->setAxisFont(QwtPlot::yLeft, font); break;
+ myPlot->setAxisFont(QwtPlot::yLeft, font); break;
case Y2Axis:
- myPlot->setAxisFont(QwtPlot::yRight, font); break;
+ myPlot->setAxisFont(QwtPlot::yRight, font); break;
}
if ( update )
myPlot->replot();
// it crashes if switched to X/Y logarithmic mode, when one or more points have
// non-positive X/Y coordinate
if ( mode && !isXLogEnabled() ){
- SUIT_MessageBox::warn1(this, tr("WARNING"), tr("WRN_XLOG_NOT_ALLOWED"), tr("BUT_OK"));
+ SUIT_MessageBox::warning(this, tr("WARNING"), tr("WRN_XLOG_NOT_ALLOWED"));
return;
}
myXMode = mode;
- myPlot->changeAxisOptions( QwtPlot::xBottom, QwtAutoScale::Logarithmic, myXMode != 0 );
+ myPlot->setLogScale(QwtPlot::xBottom, myXMode != 0);
if ( update )
fitAll();
// it crashes if switched to X/Y logarithmic mode, when one or more points have
// non-positive X/Y coordinate
if ( mode && !isYLogEnabled() ){
- SUIT_MessageBox::warn1(this, tr("WARNING"), tr("WRN_YLOG_NOT_ALLOWED"), tr("BUT_OK"));
+ SUIT_MessageBox::warning(this, tr("WARNING"), tr("WRN_YLOG_NOT_ALLOWED"));
return;
}
myYMode = mode;
- myPlot->changeAxisOptions( QwtPlot::yLeft, QwtAutoScale::Logarithmic, myYMode != 0 );
+ myPlot->setLogScale(QwtPlot::yLeft, myYMode != 0);
if (mySecondY)
- myPlot->changeAxisOptions( QwtPlot::yRight, QwtAutoScale::Logarithmic, myYMode != 0 );
+ myPlot->setLogScale( QwtPlot::yRight, myYMode != 0 );
if ( update )
fitAll();
/*!
Slot, called when user presses mouse button
*/
-void Plot2d_ViewFrame::plotMousePressed(const QMouseEvent& me )
+void Plot2d_ViewFrame::plotMousePressed( const QMouseEvent& me )
{
Plot2d_ViewWindow* aParent = dynamic_cast<Plot2d_ViewWindow*>(parent());
- if (aParent)
+ if (aParent)
aParent->putInfo(getInfo(me.pos()));
if ( myOperation == NoOpId )
myOperation = testOperation( me );
if ( myOperation != NoOpId ) {
myPnt = me.pos();
- if ( myOperation == FitAreaId ) {
- myPlot->setOutlineStyle( Qwt::Rect );
- }
- else if ( myOperation == GlPanId ) {
+ if ( myOperation == GlPanId ) {
myPlot->setAxisScale( QwtPlot::yLeft,
- myPlot->invTransform( QwtPlot::yLeft, myPnt.y() ) + myYDistance/2,
- myPlot->invTransform( QwtPlot::yLeft, myPnt.y() ) - myYDistance/2 );
+ myPlot->invTransform( QwtPlot::yLeft, myPnt.y() ) - myYDistance/2,
+ myPlot->invTransform( QwtPlot::yLeft, myPnt.y() ) + myYDistance/2 );
myPlot->setAxisScale( QwtPlot::xBottom,
myPlot->invTransform( QwtPlot::xBottom, myPnt.x() ) - myXDistance/2,
myPlot->invTransform( QwtPlot::xBottom, myPnt.x() ) + myXDistance/2 );
if (mySecondY)
myPlot->setAxisScale( QwtPlot::yRight,
- myPlot->invTransform( QwtPlot::yRight, myPnt.y() ) + myYDistance2/2,
- myPlot->invTransform( QwtPlot::yRight, myPnt.y() ) - myYDistance2/2 );
+ myPlot->invTransform( QwtPlot::yRight, myPnt.y() ) - myYDistance2/2,
+ myPlot->invTransform( QwtPlot::yRight, myPnt.y() ) + myYDistance2/2 );
myPlot->replot();
}
}
else {
- int btn = me.button() | me.state();
- if (btn == RightButton) {
+ int btn = me.button() | me.modifiers();
+ if (btn == Qt::RightButton) {
QMouseEvent* aEvent = new QMouseEvent(QEvent::MouseButtonPress,
- me.pos(), btn, me.state());
+ me.pos(), me.button(), me.buttons(), me.modifiers() );
// QMouseEvent 'me' has the 'MouseButtonDblClick' type. In this case we create new event 'aEvent'.
parent()->eventFilter(this, aEvent);
}
/*!
Slot, called when user moves mouse
*/
-void Plot2d_ViewFrame::plotMouseMoved( const QMouseEvent& me )
+bool Plot2d_ViewFrame::plotMouseMoved( const QMouseEvent& me )
{
int dx = me.pos().x() - myPnt.x();
int dy = me.pos().y() - myPnt.y();
+ bool aRes = false;
if ( myOperation != NoOpId) {
if ( myOperation == ZoomId ) {
this->incrementalZoom( dx, dy );
myPnt = me.pos();
+ aRes = true;
}
else if ( myOperation == PanId ) {
this->incrementalPan( dx, dy );
myPnt = me.pos();
+ aRes = true;
}
}
else {
if (aParent)
aParent->putInfo(getInfo(me.pos()));
}
+ return aRes;
}
/*!
Slot, called when user releases mouse
*/
void Plot2d_ViewFrame::plotMouseReleased( const QMouseEvent& me )
{
- if ( myOperation == NoOpId && me.button() == RightButton )
+ if ( myOperation == NoOpId && me.button() == Qt::RightButton && me.modifiers() != Qt::ControlModifier )
{
QContextMenuEvent aEvent( QContextMenuEvent::Mouse,
- me.pos(), me.globalPos(),
- me.state() );
+ me.pos(), me.globalPos() );
emit contextMenuRequested( &aEvent );
}
- if ( myOperation == FitAreaId ) {
- QRect rect( myPnt, me.pos() );
- fitArea( rect );
- }
myPlot->canvas()->setCursor( QCursor( Qt::CrossCursor ) );
- myPlot->setOutlineStyle( Qwt::Triangle );
+ myPlot->defaultPicker();
Plot2d_ViewWindow* aParent = dynamic_cast<Plot2d_ViewWindow*>(parent());
if (aParent)
double aDelta = event->delta();
double aScale = (aDelta < 0) ? 100./(-aDelta) : aDelta/100.;
- QwtDiMap xMap = myPlot->canvasMap( QwtPlot::xBottom );
- QwtDiMap yMap = myPlot->canvasMap( QwtPlot::yLeft );
+ QwtScaleMap xMap = myPlot->canvasMap( QwtPlot::xBottom );
+ QwtScaleMap yMap = myPlot->canvasMap( QwtPlot::yLeft );
- myPlot->setAxisScale( QwtPlot::yLeft,
- myPlot->invTransform( QwtPlot::yLeft, yMap.i1() ),
- myPlot->invTransform( QwtPlot::yLeft, yMap.i2() )*aScale );
- myPlot->setAxisScale( QwtPlot::xBottom,
- myPlot->invTransform( QwtPlot::xBottom, xMap.i1() ),
- myPlot->invTransform( QwtPlot::xBottom, xMap.i2() )*aScale );
+ myPlot->setAxisScale( QwtPlot::yLeft, yMap.s1(), yMap.s2()*aScale );
+ myPlot->setAxisScale( QwtPlot::xBottom, xMap.s1(), xMap.s2()*aScale );
if (mySecondY) {
- QwtDiMap y2Map = myPlot->canvasMap( QwtPlot::yRight );
- myPlot->setAxisScale( QwtPlot::yRight,
- myPlot->invTransform( QwtPlot::yRight, y2Map.i1() ),
- myPlot->invTransform( QwtPlot::yRight, y2Map.i2() )*aScale );
+ QwtScaleMap y2Map = myPlot->canvasMap( QwtPlot::yRight );
+ myPlot->setAxisScale( QwtPlot::yRight, y2Map.s1(), y2Map.s2()*aScale );
}
myPlot->replot();
myPnt = event->pos();
}
+
+/*!
+ Returns qwt plot curve if it is existed in map of curves and 0 otherwise
+*/
+QwtPlotCurve* Plot2d_ViewFrame::getPlotCurve( Plot2d_Curve* curve )
+{
+ CurveDict::iterator it = myPlot->getCurves().begin();
+ for ( ; it != myPlot->getCurves().end(); it++ ) {
+ if ( it.value() == curve )
+ return it.key();
+ }
+ return 0;
+}
+/*!
+ Returns true if qwt plot curve is existed in map of curves and false otherwise
+*/
+bool Plot2d_ViewFrame::hasPlotCurve( Plot2d_Curve* curve )
+{
+ CurveDict::iterator it = myPlot->getCurves().begin();
+ for ( ; it != myPlot->getCurves().end(); it++ ) {
+ if ( it.value() == curve )
+ return true;
+ }
+ return false;
+}
+
+/*!
+ Sets curve type
+*/
+void Plot2d_ViewFrame::setCurveType( QwtPlotCurve* curve, int curveType )
+{
+ if ( !curve )
+ return;
+ if ( myCurveType == 0 )
+ curve->setStyle( QwtPlotCurve::Dots );//QwtCurve::NoCurve
+ else if ( myCurveType == 1 ) {
+ curve->setStyle( QwtPlotCurve::Lines );
+ curve->setCurveAttribute( QwtPlotCurve::Fitted, false );
+ }
+ else if ( myCurveType == 2 ) {
+ curve->setStyle( QwtPlotCurve::Lines );
+ QwtSplineCurveFitter* fitter = new QwtSplineCurveFitter();
+ fitter->setSplineSize( 250 );
+ curve->setCurveAttribute( QwtPlotCurve::Fitted, true );
+ curve->setCurveFitter( fitter );
+ }
+}
+
/*!
View operations : Pan view
*/
QCursor panCursor (Qt::SizeAllCursor);
myPlot->canvas()->setCursor( panCursor );
myOperation = PanId;
- qApp->installEventFilter( this );
}
/*!
View operations : Zoom view
QCursor zoomCursor (zoomPixmap);
myPlot->canvas()->setCursor( zoomCursor );
myOperation = ZoomId;
- qApp->installEventFilter( this );
}
/*!
View operations : Fot All
{
myPlot->canvas()->setCursor( QCursor( Qt::PointingHandCursor ) );
myOperation = FitAreaId;
- qApp->installEventFilter( this );
+ myPlot->setPickerMousePattern( Qt::LeftButton );
}
/*!
View operations : Global panning
QPixmap globalPanPixmap (imageCrossCursor);
QCursor glPanCursor (globalPanPixmap);
myPlot->canvas()->setCursor( glPanCursor );
- myPlot->changeAxisOptions( QwtPlot::xBottom, QwtAutoScale::Logarithmic, false );
- myPlot->changeAxisOptions( QwtPlot::yLeft, QwtAutoScale::Logarithmic, false );
+ myPlot->setLogScale(QwtPlot::xBottom, false);
+ myPlot->setLogScale(QwtPlot::yLeft, false);
if (mySecondY)
- myPlot->changeAxisOptions( QwtPlot::yRight, QwtAutoScale::Logarithmic, false );
+ myPlot->setLogScale(QwtPlot::yRight, false);
myPlot->replot();
- QwtDiMap xMap = myPlot->canvasMap( QwtPlot::xBottom );
- QwtDiMap yMap = myPlot->canvasMap( QwtPlot::yLeft );
+ QwtScaleMap xMap = myPlot->canvasMap( QwtPlot::xBottom );
+ QwtScaleMap yMap = myPlot->canvasMap( QwtPlot::yLeft );
- myXDistance = xMap.d2() - xMap.d1();
- myYDistance = yMap.d2() - yMap.d1();
+ myXDistance = xMap.s2() - xMap.s1();
+ myYDistance = yMap.s2() - yMap.s1();
if (mySecondY) {
- QwtDiMap yMap2 = myPlot->canvasMap( QwtPlot::yRight );
- myYDistance2 = yMap2.d2() - yMap2.d1();
+ QwtScaleMap yMap2 = myPlot->canvasMap( QwtPlot::yRight );
+ myYDistance2 = yMap2.s2() - yMap2.s1();
}
fitAll();
myOperation = GlPanId;
- qApp->installEventFilter( this );
}
/*!
bool Plot2d_ViewFrame::isXLogEnabled() const
{
bool allPositive = true;
- QIntDictIterator<Plot2d_Curve> it( myCurves );
- for ( ; allPositive && it.current(); ++it ) {
- allPositive = ( it.current()->getMinX() > 0. );
- }
+ CurveDict::const_iterator it = myPlot->getCurves().begin();
+ for ( ; allPositive && it != myPlot->getCurves().end(); it++ )
+ allPositive = ( it.value()->getMinX() > 0. );
return allPositive;
}
bool Plot2d_ViewFrame::isYLogEnabled() const
{
bool allPositive = true;
- QIntDictIterator<Plot2d_Curve> it( myCurves );
- for ( ; allPositive && it.current(); ++it ) {
- allPositive = ( it.current()->getMinY() > 0. );
- }
+ CurveDict::const_iterator it = myPlot->getCurves().begin();
+ for ( ; allPositive && it != myPlot->getCurves().end(); it++ )
+ allPositive = ( it.value()->getMinY() > 0. );
return allPositive;
}
+class Plot2d_QwtPlotZoomer : public QwtPlotZoomer
+{
+public:
+ Plot2d_QwtPlotZoomer( int xAxis, int yAxis, QwtPlotCanvas* canvas )
+ : QwtPlotZoomer( xAxis, yAxis, canvas )
+ {
+ qApp->installEventFilter( this );
+ // now picker working after only a button pick.
+ // after click on button FitArea in toolbar of the ViewFrame.
+ };
+ ~Plot2d_QwtPlotZoomer() {};
+};
+
/*!
Constructor
*/
: QwtPlot( parent ),
myIsPolished( false )
{
- // outline
- enableOutline( true );
- setOutlineStyle( Qwt::Triangle );
- setOutlinePen( green );
- // legend
- setAutoLegend( false );
- setLegendFrameStyle( QFrame::Box | QFrame::Sunken );
- enableLegend( false );
- // grid
- enableGridX( false );
- enableGridXMin( false );
- enableGridY( false );
- enableGridYMin( false );
+ myPlotZoomer = new Plot2d_QwtPlotZoomer( QwtPlot::xBottom, QwtPlot::yLeft, canvas() );
+ myPlotZoomer->setSelectionFlags( QwtPicker::DragSelection | QwtPicker::CornerToCorner );
+ myPlotZoomer->setTrackerMode( QwtPicker::AlwaysOff );
+ myPlotZoomer->setRubberBand( QwtPicker::RectRubberBand );
+ myPlotZoomer->setRubberBandPen( QColor( Qt::green ) );
+
+ defaultPicker();
+
// auto scaling by default
setAxisAutoScale( QwtPlot::yLeft );
setAxisAutoScale( QwtPlot::yRight );
setAxisAutoScale( QwtPlot::xBottom );
+
+// grid
+ myGrid = new QwtPlotGrid();
+ QPen aMajPen = myGrid->majPen();
+ aMajPen.setStyle( Qt::DashLine );
+ myGrid->setPen( aMajPen );
+
+ myGrid->enableX( false );
+ myGrid->enableXMin( false );
+ myGrid->enableY( false );
+ myGrid->enableYMin( false );
+
+ myGrid->attach( this );
+
+ setMouseTracking( false );
+ canvas()->setMouseTracking( true );
+
+ myPlotZoomer->setEnabled( true );
}
+
+/*!
+ \set axis scale engine - linear or log10
+*/
+void Plot2d_Plot2d::setLogScale( int axisId, bool log10 )
+{
+ if ( log10 )
+ setAxisScaleEngine( axisId, new QwtLog10ScaleEngine() );
+ else
+ setAxisScaleEngine( axisId, new QwtLinearScaleEngine() );
+}
+
/*!
Recalculates and redraws Plot 2d view
*/
// QSize aSize = QwtPlot::minimumSizeHint();
// return QSize(aSize.width()*3/4, aSize.height());
}
+
+void Plot2d_Plot2d::defaultPicker()
+{
+ myPlotZoomer->setMousePattern( QwtEventPattern::MouseSelect1,
+ Qt::RightButton, Qt::ControlModifier ); // zooming button
+ for ( int i = QwtEventPattern::MouseSelect2; i < QwtEventPattern::MouseSelect6; i++ )
+ myPlotZoomer->setMousePattern( i, Qt::NoButton, Qt::NoButton );
+}
+
+void Plot2d_Plot2d::setPickerMousePattern( int button, int state )
+{
+ myPlotZoomer->setMousePattern( QwtEventPattern::MouseSelect1, button, state );
+}
+
+/*!
+ return closest curve if it exist, else 0
+*/
+Plot2d_Curve* Plot2d_Plot2d::getClosestCurve( QPoint p, double& distance, int& index )
+{
+ CurveDict::iterator it = getCurves().begin();
+ QwtPlotCurve* aCurve;
+ for ( ; it != getCurves().end(); it++ ) {
+ aCurve = it.key();
+ if ( !aCurve )
+ continue;
+ index = aCurve->closestPoint( p, &distance );
+ if ( index > -1 )
+ return it.value();
+ }
+ return 0;
+}
+
/*!
Checks if marker belongs to any enitity
*/
bool Plot2d_Plot2d::existMarker( const QwtSymbol::Style typeMarker, const QColor& color, const Qt::PenStyle typeLine )
{
- // getting all curves
- QArray<long> keys = curveKeys();
- //QColor aRgbColor;
-
- if ( closeColors( color, backgroundColor() ) )
+ QColor aColor = palette().color( QPalette::Background );
+ if ( closeColors( color, aColor ) )
return true;
- for ( int i = 0; i < (int)keys.count(); i++ )
- {
- QwtPlotCurve* crv = curve( keys[i] );
+
+ CurveDict::iterator it = myCurves.begin();
+ for ( ; it != myCurves.end(); it++ ) {
+ QwtPlotCurve* crv = it.key();
if ( crv ) {
QwtSymbol::Style aStyle = crv->symbol().style();
QColor aColor = crv->pen().color();
Qt::PenStyle aLine = crv->pen().style();
// if ( aStyle == typeMarker && aColor == color && aLine == typeLine )
if ( aStyle == typeMarker && closeColors( aColor,color ) && aLine == typeLine )
- return true;
+ return true;
}
}
return false;
#define BRACKETIZE(x) QString( "[ " ) + x + QString( " ]" )
void Plot2d_ViewFrame::updateTitles()
{
- QIntDictIterator<Plot2d_Curve> it( myCurves );
+ CurveDict::iterator it = myPlot->getCurves().begin();
+ //QIntDictIterator<Plot2d_Curve> it( myCurves );
QStringList aXTitles;
QStringList aYTitles;
QStringList aXUnits;
QStringList aYUnits;
QStringList aTables;
int i = 0;
- while ( it.current() ) {
+
+ Plot2d_Curve* aCurve;
+ for ( ; it != myPlot->getCurves().end(); it++ ) {
// collect titles and units from all curves...
- QString xTitle = it.current()->getHorTitle().stripWhiteSpace();
- QString yTitle = it.current()->getVerTitle().stripWhiteSpace();
- QString xUnits = it.current()->getHorUnits().stripWhiteSpace();
- QString yUnits = it.current()->getVerUnits().stripWhiteSpace();
+ aCurve = it.value();
+ QString xTitle = aCurve->getHorTitle().trimmed();
+ QString yTitle = aCurve->getVerTitle().trimmed();
+ QString xUnits = aCurve->getHorUnits().trimmed();
+ QString yUnits = aCurve->getVerUnits().trimmed();
aYTitles.append( yTitle );
- if ( aXTitles.find( xTitle ) == aXTitles.end() )
+ if ( !aXTitles.contains( xTitle ) )
aXTitles.append( xTitle );
- if ( aXUnits.find( xUnits ) == aXUnits.end() )
+ if ( !aXUnits.contains( xUnits ) )
aXUnits.append( xUnits );
- if ( aYUnits.find( yUnits ) == aYUnits.end() )
+ if ( !aYUnits.contains( yUnits ) )
aYUnits.append( yUnits );
- QString aName = it.current()->getTableTitle();
- if( !aName.isEmpty() && aTables.find( aName ) == aTables.end() )
+ QString aName = aCurve->getTableTitle();
+ if( !aName.isEmpty() && !aTables.contains( aName ) )
aTables.append( aName );
-
- ++it;
++i;
}
// ... and update plot 2d view
{
QPrinter* pr = new QPrinter( QPrinter::HighResolution );
pr->setPageSize( QPrinter::A4 );
- pr->setOutputToFile( true );
pr->setOutputFileName( file );
pr->setPrintProgram( "" );
pd = pr;
*/
void Plot2d_ViewFrame::setVisualParameters( const QString& parameters )
{
- QStringList paramsLst = QStringList::split( '*', parameters, true );
+ QStringList paramsLst = parameters.split( '*' );
if ( paramsLst.size() == 9 ) {
double xmin, xmax, ymin, ymax, y2min, y2max;
myXMode = paramsLst[0].toInt();
setVerScaleMode( myYMode, /*update=*/false );
if (mySecondY) {
- QwtDiMap yMap2 = myPlot->canvasMap( QwtPlot::yRight );
- myYDistance2 = yMap2.d2() - yMap2.d1();
+ QwtScaleMap yMap2 = myPlot->canvasMap( QwtPlot::yRight );
+ myYDistance2 = yMap2.s2() - yMap2.s1();
}
fitData( 0, xmin, xmax, ymin, ymax, y2min, y2max );
Incremental zooming operation
*/
void Plot2d_ViewFrame::incrementalPan( const int incrX, const int incrY ) {
- QwtDiMap xMap = myPlot->canvasMap( QwtPlot::xBottom );
- QwtDiMap yMap = myPlot->canvasMap( QwtPlot::yLeft );
+ QwtScaleMap xMap = myPlot->canvasMap( QwtPlot::xBottom );
+ QwtScaleMap yMap = myPlot->canvasMap( QwtPlot::yLeft );
myPlot->setAxisScale( QwtPlot::yLeft,
- myPlot->invTransform( QwtPlot::yLeft, yMap.i1()-incrY ),
- myPlot->invTransform( QwtPlot::yLeft, yMap.i2()-incrY ) );
+ myPlot->invTransform( QwtPlot::yLeft, yMap.transform( yMap.s1() )-incrY ),
+ myPlot->invTransform( QwtPlot::yLeft, yMap.transform( yMap.s2() )-incrY ) );
myPlot->setAxisScale( QwtPlot::xBottom,
- myPlot->invTransform( QwtPlot::xBottom, xMap.i1()-incrX ),
- myPlot->invTransform( QwtPlot::xBottom, xMap.i2()-incrX ) );
+ myPlot->invTransform( QwtPlot::xBottom, xMap.transform( xMap.s1() )-incrX ),
+ myPlot->invTransform( QwtPlot::xBottom, xMap.transform( xMap.s2() )-incrX ) );
if (mySecondY) {
- QwtDiMap y2Map = myPlot->canvasMap( QwtPlot::yRight );
+ QwtScaleMap y2Map = myPlot->canvasMap( QwtPlot::yRight );
myPlot->setAxisScale( QwtPlot::yRight,
- myPlot->invTransform( QwtPlot::yRight, y2Map.i1()-incrY ),
- myPlot->invTransform( QwtPlot::yRight, y2Map.i2()-incrY ) );
+ myPlot->invTransform( QwtPlot::yRight, y2Map.transform( y2Map.s1() )-incrY ),
+ myPlot->invTransform( QwtPlot::yRight, y2Map.transform( y2Map.s2() )-incrY ) );
}
myPlot->replot();
}
Incremental panning operation
*/
void Plot2d_ViewFrame::incrementalZoom( const int incrX, const int incrY ) {
- QwtDiMap xMap = myPlot->canvasMap( QwtPlot::xBottom );
- QwtDiMap yMap = myPlot->canvasMap( QwtPlot::yLeft );
+ QwtScaleMap xMap = myPlot->canvasMap( QwtPlot::xBottom );
+ QwtScaleMap yMap = myPlot->canvasMap( QwtPlot::yLeft );
- myPlot->setAxisScale( QwtPlot::yLeft,
- myPlot->invTransform( QwtPlot::yLeft, yMap.i1() ),
- myPlot->invTransform( QwtPlot::yLeft, yMap.i2() + incrY ) );
- myPlot->setAxisScale( QwtPlot::xBottom,
- myPlot->invTransform( QwtPlot::xBottom, xMap.i1() ),
- myPlot->invTransform( QwtPlot::xBottom, xMap.i2() - incrX ) );
+ myPlot->setAxisScale( QwtPlot::yLeft, yMap.s1(),
+ myPlot->invTransform( QwtPlot::yLeft, yMap.transform( yMap.s2() ) + incrY ) );
+ myPlot->setAxisScale( QwtPlot::xBottom, xMap.s1(),
+ myPlot->invTransform( QwtPlot::xBottom, xMap.transform( xMap.s2() ) - incrX ) );
if (mySecondY) {
- QwtDiMap y2Map = myPlot->canvasMap( QwtPlot::yRight );
- myPlot->setAxisScale( QwtPlot::yRight,
- myPlot->invTransform( QwtPlot::yRight, y2Map.i1() ),
- myPlot->invTransform( QwtPlot::yRight, y2Map.i2() + incrY ) );
+ QwtScaleMap y2Map = myPlot->canvasMap( QwtPlot::yRight );
+ myPlot->setAxisScale( QwtPlot::yRight, y2Map.s1(),
+ myPlot->invTransform( QwtPlot::yRight, y2Map.transform( y2Map.s2() ) + incrY ) );
}
myPlot->replot();
}
event queue. This ensures that other important events (show, resize, etc.)
are processed first.
*/
-void Plot2d_ViewFrame::customEvent( QCustomEvent* ce )
+void Plot2d_ViewFrame::customEvent( QEvent* ce )
{
if ( ce->type() == FITALL_EVENT )
fitAll();
#define PLOT2D_VIEWFRAME_H
#include "Plot2d_Curve.h"
-#include <qwidget.h>
-#include <qintdict.h>
+#include <QWidget>
+#include <QMultiHash>
+#include <QList>
+#include <qwt_symbol.h>
class Plot2d_Plot2d;
class Plot2d_Prs;
class QCustomEvent;
+class QwtPlotCurve;
+class QwtPlotGrid;
+class QwtPlotZoomer;
-typedef QIntDict<Plot2d_Curve> CurveDict;
+typedef QMultiHash<QwtPlotCurve*, Plot2d_Curve*> CurveDict;
class PLOT2D_EXPORT Plot2d_ViewFrame : public QWidget
{
void Erase( const Plot2d_Prs*, const bool = false );
Plot2d_Prs* CreatePrs( const char* entry = 0 );
+ virtual bool eventFilter(QObject* watched, QEvent* e);
+
/* operations */
void updateTitles();
void setTitle( const QString& title );
void eraseCurve( Plot2d_Curve* curve, bool update = false );
void eraseCurves( const curveList& curves, bool update = false );
int getCurves( curveList& clist );
- const CurveDict& getCurves() { return myCurves; }
- int hasCurve( Plot2d_Curve* curve );
+ const CurveDict& getCurves();
bool isVisible( Plot2d_Curve* curve );
void updateCurve( Plot2d_Curve* curve, bool update = false );
void updateLegend( const Plot2d_Prs* prs );
void copyPreferences( Plot2d_ViewFrame* );
void setCurveType( int curveType, bool update = true );
int getCurveType() const { return myCurveType; }
- void setCurveTitle( int curveKey, const QString& title );
+ void setCurveTitle( Plot2d_Curve* curve, const QString& title );
void showLegend( bool show, bool update = true );
void setLegendPos( int pos );
int getLegendPos() const { return myLegendPos; }
void writePreferences();
QString getInfo( const QPoint& pnt );
virtual void wheelEvent( QWheelEvent* );
+ QwtPlotCurve* getPlotCurve( Plot2d_Curve* curve );
+ bool hasPlotCurve( Plot2d_Curve* curve );
+ void setCurveType( QwtPlotCurve* curve, int curveType );
public slots:
void onViewPan();
void onZoomOut();
protected:
- virtual void customEvent( QCustomEvent* );
-
-protected slots:
+ virtual void customEvent( QEvent* );
void plotMousePressed( const QMouseEvent& );
- void plotMouseMoved( const QMouseEvent& );
+ bool plotMouseMoved( const QMouseEvent& );
void plotMouseReleased( const QMouseEvent& );
signals:
Plot2d_Plot2d* myPlot;
int myOperation;
QPoint myPnt;
- CurveDict myCurves;
int myCurveType;
bool myShowLegend;
public:
Plot2d_Plot2d( QWidget* parent );
+ void setLogScale( int axisId, bool log10 );
+
void replot();
void getNextMarker( QwtSymbol::Style& typeMarker, QColor& color, Qt::PenStyle& typeLine );
QwtLegend* getLegend() {
virtual QSize sizeHint() const;
virtual QSizePolicy sizePolicy() const;
virtual QSize minimumSizeHint() const;
+ void defaultPicker();
+ void setPickerMousePattern( int button, int state = Qt::NoButton );
bool polished() const { return myIsPolished; }
+ QwtPlotGrid* grid() { return myGrid; };
+ CurveDict& getCurves() { return myCurves; }
+ Plot2d_Curve* getClosestCurve( QPoint p, double& distance, int& index );
public slots:
virtual void polish();
bool existMarker( const QwtSymbol::Style typeMarker, const QColor& color, const Qt::PenStyle typeLine );
protected:
- QValueList<QColor> myColors;
+ CurveDict myCurves;
+ QwtPlotGrid* myGrid;
+ QList<QColor> myColors;
bool myIsPolished;
+ QwtPlotZoomer* myPlotZoomer;
};
#endif
#include "Plot2d_ViewFrame.h"
#include "Plot2d_Prs.h"
-#include <qpopupmenu.h>
+#include <QMenu>
+#include <QToolBar>
+#include <QVector>
/*!
Constructor
Adds custom items to popup menu
\param thePopup - popup menu
*/
-void Plot2d_Viewer::contextMenuPopup(QPopupMenu* thePopup)
+void Plot2d_Viewer::contextMenuPopup(QMenu* thePopup)
{
Plot2d_ViewWindow* aView = (Plot2d_ViewWindow*)(myViewManager->getActiveView());
if ( aView )
aView->contextMenuPopup(thePopup);
- if (thePopup->count() > 0) thePopup->insertSeparator();
- thePopup->insertItem( tr( "MNU_DUMP_VIEW" ), this, SLOT(onDumpView()));
- thePopup->insertItem( tr( "MEN_PLOT2D_CHANGE_BACKGROUND" ), this, SLOT(onChangeBgColor()));
+ if (!thePopup->isEmpty())
+ thePopup->addSeparator();
+ thePopup->addAction( tr( "MNU_DUMP_VIEW" ), this, SLOT(onDumpView()));
+ thePopup->addAction( tr( "MEN_PLOT2D_CHANGE_BACKGROUND" ), this, SLOT(onChangeBgColor()));
if ( aView ) {
if ( !aView->getToolBar()->isVisible() ) {
- if (thePopup->count() > 0) thePopup->insertSeparator();
- thePopup->insertItem("Show toolbar", this, SLOT(onShowToolbar()));
+ if (!thePopup->isEmpty())
+ thePopup->addSeparator();
+ thePopup->addAction("Show toolbar", this, SLOT(onShowToolbar()));
}
aView->RefreshDumpImage();
}
void Plot2d_Viewer::update()
{
SUIT_ViewManager* aMgr = getViewManager();
- QPtrVector<SUIT_ViewWindow> aViews = aMgr->getViews();
+ QVector<SUIT_ViewWindow*> aViews = aMgr->getViews();
unsigned int aSize = aViews.size();
for (uint i = 0; i < aSize; i++) {
Plot2d_ViewWindow* aView = (Plot2d_ViewWindow*)aViews[i];
void Plot2d_Viewer::clearPrs()
{
SUIT_ViewManager* aMgr = getViewManager();
- QPtrVector<SUIT_ViewWindow> aViews = aMgr->getViews();
+ QVector<SUIT_ViewWindow*> aViews = aMgr->getViews();
unsigned int aSize = aViews.size();
for (uint i = 0; i < aSize; i++) {
Plot2d_ViewWindow* aView = (Plot2d_ViewWindow*)aViews[i];
class Plot2d_ViewFrame;
class Plot2d_Prs;
class QString;
-class QPopupMenu;
+class QMenu;
class PLOT2D_EXPORT Plot2d_Viewer: public SUIT_ViewModel
{
virtual void setViewManager( SUIT_ViewManager* );
virtual SUIT_ViewWindow* createView(SUIT_Desktop* theDesktop);
virtual QString getType() const { return Type(); }
- virtual void contextMenuPopup(QPopupMenu*);
+ virtual void contextMenuPopup(QMenu*);
Plot2d_Prs* getPrs() const { return myPrs; };
void setPrs(Plot2d_Prs* thePrs);
void update();
#include "QtxAction.h"
-#include <qstatusbar.h>
-#include <qlayout.h>
-#include <qapplication.h>
-#include <qpopupmenu.h>
+#include <QStatusBar>
+#include <QLayout>
+#include <QApplication>
+#include <QMenu>
+#include <QImage>
+#include <QToolBar>
+#include <QPaintEvent>
/*!
Constructor
: SUIT_ViewWindow(theDesktop)
{
myModel = theModel;
-
myDumpImage = QImage();
myViewFrame = new Plot2d_ViewFrame(this, "plotView");
setCentralWidget(myViewFrame);
- myToolBar = new QToolBar(this);
- myToolBar->setCloseMode(QDockWindow::Undocked);
- myToolBar->setLabel(tr("LBL_TOOLBAR_LABEL"));
+ myToolBar = addToolBar( tr("LBL_TOOLBAR_LABEL") );
+ //myToolBar->setCloseMode(QDockWindow::Undocked); // toolbar has "Close" (X) button only if it's undocked, but there is no such functionality in Qt4
createActions();
createToolBar();
connect(myViewFrame, SIGNAL(contextMenuRequested( QContextMenuEvent * )),
this, SIGNAL(contextMenuRequested( QContextMenuEvent * )) );
+ myViewFrame->installEventFilter( this );
}
/*!
void Plot2d_ViewWindow::putInfo(QString theMsg)
{
QStatusBar* aStatusBar = myDesktop->statusBar();
- aStatusBar->message(theMsg/*, 3000*/);
+ aStatusBar->showMessage(theMsg/*, 3000*/);
}
/*!
Fills popup menu with custom actions
\param popup - popup menu to be filled with
*/
-void Plot2d_ViewWindow::contextMenuPopup( QPopupMenu* thePopup )
+void Plot2d_ViewWindow::contextMenuPopup( QMenu* thePopup )
{
// scaling
- QPopupMenu* scalingPopup = new QPopupMenu( thePopup );
+ QMenu* scalingPopup = new QMenu( thePopup );
+ scalingPopup->addAction( myActionsMap[ PModeXLinearId ] );
myActionsMap[ PModeXLinearId ]->addTo( scalingPopup );
myActionsMap[ PModeXLogarithmicId ]->addTo( scalingPopup );
onChangeHorMode();
- scalingPopup->insertSeparator();
+ scalingPopup->addSeparator();
myActionsMap[ PModeYLinearId ]->addTo( scalingPopup );
myActionsMap[ PModeYLogarithmicId ]->addTo( scalingPopup );
- thePopup->insertItem( tr( "SCALING_POPUP" ), scalingPopup );
+ scalingPopup->setTitle( tr( "SCALING_POPUP" ) );
+ thePopup->addMenu( scalingPopup );
onChangeVerMode();
- thePopup->insertItem(tr("TOT_PLOT2D_FITDATA"), myViewFrame, SLOT(onFitData()));
+ thePopup->addAction(tr("TOT_PLOT2D_FITDATA"), myViewFrame, SLOT(onFitData()));
// curve type
- QPopupMenu* curTypePopup = new QPopupMenu( thePopup );
+ QMenu* curTypePopup = new QMenu( thePopup );
myActionsMap[ CurvPointsId ]->addTo( curTypePopup );
myActionsMap[ CurvLinesId ]->addTo( curTypePopup );
myActionsMap[ CurvSplinesId ]->addTo( curTypePopup );
- thePopup->insertItem( tr( "CURVE_TYPE_POPUP" ), curTypePopup );
+ curTypePopup->setTitle( tr( "CURVE_TYPE_POPUP" ) );
+ thePopup->addMenu( curTypePopup );
// legend
myActionsMap[ LegendId ]->addTo(thePopup);
tr("MEN_PLOT2D_CURVES_POINTS"), 0, this);
aAction->setStatusTip(tr("PRP_PLOT2D_CURVES_POINTS"));
connect(aAction, SIGNAL(activated()), this, SLOT(onCurves()));
- aAction->setToggleAction(true);
+ aAction->setCheckable(true);
myActionsMap[ CurvPointsId ] = aAction;
// Curve type - lines
tr("MEN_PLOT2D_CURVES_LINES"), 0, this);
aAction->setStatusTip(tr("PRP_PLOT2D_CURVES_LINES"));
connect(aAction, SIGNAL(activated()), this, SLOT(onCurves()));
- aAction->setToggleAction(true);
+ aAction->setCheckable(true);
myActionsMap[ CurvLinesId ] = aAction;
// Curve type - splines
tr("MEN_PLOT2D_CURVES_SPLINES"), 0, this);
aAction->setStatusTip(tr("PRP_PLOT2D_CURVES_SPLINES"));
connect(aAction, SIGNAL(activated()), this, SLOT(onCurves()));
- aAction->setToggleAction(true);
+ aAction->setCheckable(true);
myActionsMap[ CurvSplinesId ] = aAction;
// Mode for X (linear or logarithmic)
tr("MEN_PLOT2D_SHOW_LEGEND"), 0, this);
aAction->setStatusTip(tr("PRP_PLOT2D_SHOW_LEGEND"));
connect(aAction, SIGNAL(activated()), this, SLOT(onLegend()));
- aAction->setToggleAction(true);
+ aAction->setCheckable(true);
myActionsMap[ LegendId ] = aAction;
// Settings
aResMgr->loadPixmap("Plot2d", tr("ICON_PLOT2D_MODE_LINEAR_HOR")),
tr("MEN_PLOT2D_MODE_LINEAR_HOR"), 0, this);
aAction->setStatusTip (tr("PRP_PLOT2D_MODE_LINEAR_HOR"));
- aAction->setToggleAction(true);
+ aAction->setCheckable(true);
myActionsMap[PModeXLinearId] = aAction;
connect(aAction, SIGNAL(activated()), this, SLOT(onViewHorMode()));
aResMgr->loadPixmap("Plot2d", tr("ICON_PLOT2D_MODE_LOGARITHMIC_HOR")),
tr("MEN_PLOT2D_MODE_LOGARITHMIC_HOR"), 0, this);
aAction->setStatusTip(tr("PRP_PLOT2D_MODE_LOGARITHMIC_HOR"));
- aAction->setToggleAction(true);
+ aAction->setCheckable(true);
myActionsMap[PModeXLogarithmicId] = aAction;
connect(aAction, SIGNAL(activated()), this, SLOT(onViewHorMode()));
aResMgr->loadPixmap("Plot2d", tr("ICON_PLOT2D_MODE_LINEAR_VER")),
tr("MEN_PLOT2D_MODE_LINEAR_VER" ), 0, this);
aAction->setStatusTip(tr("PRP_PLOT2D_MODE_LINEAR_VER"));
- aAction->setToggleAction(true);
+ aAction->setCheckable(true);
myActionsMap[PModeYLinearId] = aAction;
connect(aAction, SIGNAL(activated()), this, SLOT(onViewVerMode()));
aResMgr->loadPixmap("Plot2d", tr("ICON_PLOT2D_MODE_LOGARITHMIC_VER")),
tr("MEN_PLOT2D_MODE_LOGARITHMIC_VER" ), 0, this);
aAction->setStatusTip(tr("PRP_PLOT2D_MODE_LOGARITHMIC_VER"));
- aAction->setToggleAction(true);
+ aAction->setCheckable(true);
myActionsMap[PModeYLogarithmicId] = aAction;
connect(aAction, SIGNAL(activated()), this, SLOT(onViewVerMode()));
-
}
/*!
aScaleBtn->AddAction(myActionsMap[FitAllId]);
aScaleBtn->AddAction(myActionsMap[FitRectId]);
aScaleBtn->AddAction(myActionsMap[ZoomId]);
+ myToolBar->addWidget( aScaleBtn );
SUIT_ToolButton* aPanBtn = new SUIT_ToolButton(myToolBar);
aPanBtn->AddAction(myActionsMap[PanId]);
aPanBtn->AddAction(myActionsMap[GlobalPanId]);
+ myToolBar->addWidget( aPanBtn );
myCurveBtn = new SUIT_ToolButton(myToolBar);
myCurveBtn->AddAction(myActionsMap[CurvPointsId]);
myCurveBtn->AddAction(myActionsMap[CurvLinesId]);
myCurveBtn->AddAction(myActionsMap[CurvSplinesId]);
- myActionsMap[CurvLinesId]->setOn(true);
+ myToolBar->addWidget( myCurveBtn );
+ myActionsMap[CurvLinesId]->setChecked(true);
onChangeCurveMode();
myActionsMap[HorId]->addTo(myToolBar);
bool aLinear = myViewFrame->isModeHorLinear();
SUIT_ResourceMgr* aResMgr = SUIT_Session::session()->resourceMgr();
- myActionsMap[PModeXLinearId]->setOn( aLinear );
- myActionsMap[PModeXLogarithmicId]->setOn( !aLinear );
+ myActionsMap[PModeXLinearId]->setChecked( aLinear );
+ myActionsMap[PModeXLogarithmicId]->setChecked( !aLinear );
QPixmap pix = aResMgr->loadPixmap( "Plot2d", tr( aLinear ? "ICON_PLOT2D_MODE_LOGARITHMIC_HOR" :
"ICON_PLOT2D_MODE_LINEAR_HOR" ) );
- myActionsMap[HorId]->setIconSet( pix );
+ myActionsMap[HorId]->setIcon( pix );
myActionsMap[HorId]->setToolTip( tr( aLinear ? "TOT_PLOT2D_MODE_LOGARITHMIC_HOR" :
"TOT_PLOT2D_MODE_LINEAR_HOR" ) );
myActionsMap[HorId]->setStatusTip( tr( aLinear ? "PRP_PLOT2D_MODE_LOGARITHMIC_HOR" :
bool aLinear = myViewFrame->isModeVerLinear();
SUIT_ResourceMgr* aResMgr = SUIT_Session::session()->resourceMgr();
- myActionsMap[PModeYLinearId]->setOn( aLinear );
- myActionsMap[PModeYLogarithmicId]->setOn( !aLinear );
+ myActionsMap[PModeYLinearId]->setChecked( aLinear );
+ myActionsMap[PModeYLogarithmicId]->setChecked( !aLinear );
QPixmap pix = aResMgr->loadPixmap( "Plot2d", tr( aLinear ? "ICON_PLOT2D_MODE_LOGARITHMIC_VER" :
"ICON_PLOT2D_MODE_LINEAR_VER" ) );
- myActionsMap[VerId]->setIconSet( pix );
+ myActionsMap[VerId]->setIcon( pix );
myActionsMap[VerId]->setToolTip( tr( aLinear ? "TOT_PLOT2D_MODE_LOGARITHMIC_VER" :
"TOT_PLOT2D_MODE_LINEAR_VER" ) );
myActionsMap[VerId]->setStatusTip( tr( aLinear ? "PRP_PLOT2D_MODE_LOGARITHMIC_VER" :
int aCurveType = myViewFrame->getCurveType();
myCurveBtn->SetItem(aCurveType);
- myActionsMap[CurvPointsId]->setOn(aCurveType == 0);
- myActionsMap[CurvLinesId]->setOn(aCurveType == 1);
- myActionsMap[CurvSplinesId]->setOn(aCurveType == 2);
+ myActionsMap[CurvPointsId]->setChecked(aCurveType == 0);
+ myActionsMap[CurvLinesId]->setChecked(aCurveType == 1);
+ myActionsMap[CurvSplinesId]->setChecked(aCurveType == 2);
}
/*!
*/
void Plot2d_ViewWindow::onChangeLegendMode()
{
- myActionsMap[ LegendId ]->setOn(myViewFrame->isLegendShow());
+ myActionsMap[ LegendId ]->setChecked(myViewFrame->isLegendShow());
}
/*!
*/
void Plot2d_ViewWindow::onDumpView()
{
- qApp->postEvent( myViewFrame, new QPaintEvent( QRect( 0, 0, myViewFrame->width(), myViewFrame->height() ), TRUE ) );
+ qApp->postEvent( myViewFrame, new QPaintEvent( QRect( 0, 0, myViewFrame->width(), myViewFrame->height() ) ) );
SUIT_ViewWindow::onDumpView();
}
*/
QImage Plot2d_ViewWindow::dumpView()
{
- if ( getToolBar()->hasMouse() || myDumpImage.isNull() )
+ if ( getToolBar()->underMouse() || myDumpImage.isNull() )
{
QPixmap px = QPixmap::grabWindow( myViewFrame->winId() );
- return px.convertToImage();
+ return px.toImage();
}
return myDumpImage;
void Plot2d_ViewWindow::RefreshDumpImage()
{
QPixmap px = QPixmap::grabWindow( myViewFrame->winId() );
- myDumpImage = px.convertToImage();
+ myDumpImage = px.toImage();
}
#include "Plot2d.h"
#include <SUIT_ViewWindow.h>
+#include <QMap>
-#include <qimage.h>
#ifdef WIN32
#pragma warning( disable:4251 )
class Plot2d_ViewFrame;
class QtxAction;
class SUIT_ToolButton;
+class QImage;
+class QMenu;
+class QToolBar;
class PLOT2D_EXPORT Plot2d_ViewWindow : public SUIT_ViewWindow
{
void putInfo(QString theMsg);
Plot2d_ViewFrame* getViewFrame() { return myViewFrame; };
QToolBar* getToolBar() { return myToolBar; };
- void contextMenuPopup( QPopupMenu* thePopup );
+ void contextMenuPopup( QMenu* thePopup );
virtual QString getVisualParameters();
virtual void setVisualParameters( const QString& parameters );
virtual void RefreshDumpImage();
+ virtual bool eventFilter(QObject* watched, QEvent* e);
protected:
virtual QImage dumpView();
virtual QString filter() const;
virtual bool dumpViewToFormat( const QImage&, const QString& fileName, const QString& format );
-private:
- bool eventFilter(QObject* watched, QEvent* e);
-
void createActions();
void createToolBar();
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>ICON_PLOT2D_GLOBALPAN</source>
+ <translation>plot2d_glpan.png</translation>
+ </message>
+ <message>
+ <source>ICON_PLOT2D_CLONE_VIEW</source>
+ <translation>plot2d_clone.png</translation>
+ </message>
+ <message>
+ <source>ICON_PLOT2D_CURVES_POINTS</source>
+ <translation>plot2d_points.png</translation>
+ </message>
+ <message>
+ <source>ICON_PLOT2D_FIT_AREA</source>
+ <translation>plot2d_fitarea.png</translation>
+ </message>
+ <message>
+ <source>ICON_PLOT2D_DUMP</source>
+ <translation>plot2d_camera_dump.png</translation>
+ </message>
+ <message>
+ <source>ICON_PLOT2D_ZOOM</source>
+ <translation>plot2d_zoom.png</translation>
+ </message>
+ <message>
+ <source>ICON_PLOT2D_MODE_LINEAR_VER</source>
+ <translation>plot2d_linear_y.png</translation>
+ </message>
+ <message>
+ <source>ICON_PLOT2D_MODE_LINEAR_HOR</source>
+ <translation>plot2d_linear.png</translation>
+ </message>
+ <message>
+ <source>ICON_PLOT2D_PAN</source>
+ <translation>plot2d_pan.png</translation>
+ </message>
+ <message>
+ <source>ICON_PLOT2D_FIT_ALL</source>
+ <translation>plot2d_fitall.png</translation>
+ </message>
+ <message>
+ <source>ICON_PLOT2D_MODE_LOGARITHMIC_HOR</source>
+ <translation>plot2d_log.png</translation>
+ </message>
+ <message>
+ <source>ICON_PLOT2D_MODE_LOGARITHMIC_VER</source>
+ <translation>plot2d_log_y.png</translation>
+ </message>
+ <message>
+ <source>ICON_PLOT2D_SETTINGS</source>
+ <translation>plot2d_settings.png</translation>
+ </message>
+ <message>
+ <source>ICON_PLOT2D_CURVES_LINES</source>
+ <translation>plot2d_lines.png</translation>
+ </message>
+ <message>
+ <source>ICON_PLOT2D_CURVES_SPLINES</source>
+ <translation>plot2d_splines.png</translation>
+ </message>
+ <message>
+ <source>ICON_PLOT2D_SHOW_LEGEND</source>
+ <translation>plot2d_legend.png</translation>
+ </message>
+</context>
+</TS>
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>PLOT2D_CURVE_TYPE_LBL</source>
+ <translation>Curve type:</translation>
+ </message>
+ <message>
+ <source>ERROR</source>
+ <translation>Error</translation>
+ </message>
+ <message>
+ <source>PLOT2D_SET_AS_DEFAULT_CHECK</source>
+ <translation>Save settings as default</translation>
+ </message>
+ <message>
+ <source>TLT_SETUP_CURVE</source>
+ <translation>Setup Curve</translation>
+ </message>
+ <message>
+ <source>MNU_DUMP_VIEW</source>
+ <translation>Dump view...</translation>
+ </message>
+ <message>
+ <source>PLOT2D_SCALE_MODE_HOR</source>
+ <translation>Horizontal axis:</translation>
+ </message>
+ <message>
+ <source>PLOT2D_SCALE_MODE_VER</source>
+ <translation>Vertical axis:</translation>
+ </message>
+ <message>
+ <source>MNU_PAN_VIEW</source>
+ <translation>Panning</translation>
+ </message>
+ <message>
+ <source>MNU_CLONE_VIEW</source>
+ <translation>Clone View</translation>
+ </message>
+ <message>
+ <source>POSTSCRIPT_FILES</source>
+ <translation>PostScript files (*.ps)</translation>
+ </message>
+ <message>
+ <source>DSC_GLOBALPAN_VIEW</source>
+ <translation>Selection of a new center of the view</translation>
+ </message>
+ <message>
+ <source>PRP_PLOT2D_MODE_LINEAR_VER</source>
+ <translation>Switches view to linear scaling mode along vertical axis</translation>
+ </message>
+ <message>
+ <source>PRP_PLOT2D_MODE_LINEAR_HOR</source>
+ <translation>Switches view to linear scaling mode along horizontal axis</translation>
+ </message>
+ <message>
+ <source>CURVE_LINE_WIDTH_LAB</source>
+ <translation>Line width:</translation>
+ </message>
+ <message>
+ <source>CURVE_TYPE_POPUP</source>
+ <translation>Curve type</translation>
+ </message>
+ <message>
+ <source>TOT_PLOT2D_MODE_LINEAR_VER</source>
+ <translation>Vertical axis: linear</translation>
+ </message>
+ <message>
+ <source>TOT_PLOT2D_MODE_LINEAR_HOR</source>
+ <translation>Horizontal axis: linear</translation>
+ </message>
+ <message>
+ <source>FIT_DATA_TLT</source>
+ <translation>Fit Data Range</translation>
+ </message>
+ <message>
+ <source>MNU_ZOOM_VIEW</source>
+ <translation>Zoom</translation>
+ </message>
+ <message>
+ <source>PLOT2D_GRID_TLT</source>
+ <translation>Grid / Axes marks</translation>
+ </message>
+ <message>
+ <source>DSC_PAN_VIEW</source>
+ <translation>Panning the view</translation>
+ </message>
+ <message>
+ <source>DASHDOT_LINE_LBL</source>
+ <translation>DashDot</translation>
+ </message>
+ <message>
+ <source>PRP_PLOT2D_CURVES_SPLINES</source>
+ <translation>Switches view to splines mode</translation>
+ </message>
+ <message>
+ <source>INF_AXES_X</source>
+ <translation>Axis X</translation>
+ </message>
+ <message>
+ <source>PLOT2D_SCALE_TLT</source>
+ <translation>Scale mode</translation>
+ </message>
+ <message>
+ <source>DSC_FITALL</source>
+ <translation>Fit all objects inside the view frame</translation>
+ </message>
+ <message>
+ <source>MNU_FITALL</source>
+ <translation>Fit All</translation>
+ </message>
+ <message>
+ <source>TOT_PLOT2D_MODE_LOGARITHMIC_HOR</source>
+ <translation>Horizontal axis: logarithmic</translation>
+ </message>
+ <message>
+ <source>TOT_PLOT2D_MODE_LOGARITHMIC_VER</source>
+ <translation>Vertical axis: logarithmic</translation>
+ </message>
+ <message>
+ <source>MNU_GLOBALPAN_VIEW</source>
+ <translation>Global Panning</translation>
+ </message>
+ <message>
+ <source>INF_APP_DUMP_VIEW</source>
+ <translation>Dump view</translation>
+ </message>
+ <message>
+ <source>PLOT2D_LEGEND_POSITION_BOTTOM</source>
+ <translation>Bottom</translation>
+ </message>
+ <message>
+ <source>INF_COORDINATES</source>
+ <translation>Coordinates: X : %1, Y : %2</translation>
+ </message>
+ <message>
+ <source>DSC_CLONE_VIEW</source>
+ <translation>Create new OCC viewer for the active scene</translation>
+ </message>
+ <message>
+ <source>DASH_LINE_LBL</source>
+ <translation>Dash</translation>
+ </message>
+ <message>
+ <source>DTRIANGLE_MARKER_LBL</source>
+ <translation>Downward triangle</translation>
+ </message>
+ <message>
+ <source>UTRIANGLE_MARKER_LBL</source>
+ <translation>Upward triangle</translation>
+ </message>
+ <message>
+ <source>LTRIANGLE_MARKER_LBL</source>
+ <translation>Leftward triangle</translation>
+ </message>
+ <message>
+ <source>RTRIANGLE_MARKER_LBL</source>
+ <translation>Rightward triangle</translation>
+ </message>
+ <message>
+ <source>RECTANGLE_MARKER_LBL</source>
+ <translation>Rectangle</translation>
+ </message>
+ <message>
+ <source>TLT_SETUP_PLOT2D_VIEW</source>
+ <translation>Plot 2d View Settings</translation>
+ </message>
+ <message>
+ <source>CURVE_LINE_TYPE_LAB</source>
+ <translation>Line type:</translation>
+ </message>
+ <message>
+ <source>CROSS_MARKER_LBL</source>
+ <translation>Cross</translation>
+ </message>
+ <message>
+ <source>XCROSS_MARKER_LBL</source>
+ <translation>Diagonal cross</translation>
+ </message>
+ <message>
+ <source>PLOT2D_ENABLE_VER_TITLE</source>
+ <translation>Vertical axis title</translation>
+ </message>
+ <message>
+ <source>PLOT2D_ENABLE_HOR_TITLE</source>
+ <translation>Horizontal axis title</translation>
+ </message>
+ <message>
+ <source>TOT_PLOT2D_SETTINGS</source>
+ <translation>Settings</translation>
+ </message>
+ <message>
+ <source>PLOT2D_CURVE_TYPE_LINES</source>
+ <translation>Lines</translation>
+ </message>
+ <message>
+ <source>MEN_PLOT2D_CURVES_SPLINES</source>
+ <translation>Draw splines</translation>
+ </message>
+ <message>
+ <source>PRP_PLOT2D_MODE_LOGARITHMIC_HOR</source>
+ <translation>Switches view to logarithmic scaling mode along horizontal axis</translation>
+ </message>
+ <message>
+ <source>PRP_PLOT2D_MODE_LOGARITHMIC_VER</source>
+ <translation>Switches view to logarithmic scaling mode along vertical axis</translation>
+ </message>
+ <message>
+ <source>PLOT2D_IMAGE_FILES</source>
+ <translation>Images Files (*.bmp *.png *.jpg *.jpeg)</translation>
+ </message>
+ <message>
+ <source>PLOT2D_MAX_INTERVALS</source>
+ <translation>Max intervals</translation>
+ </message>
+ <message>
+ <source>INF_AXES_Y_LEFT</source>
+ <translation>Axis Y Left</translation>
+ </message>
+ <message>
+ <source>CURVE_COLOR_LAB</source>
+ <translation>Color:</translation>
+ </message>
+ <message>
+ <source>DIAMOND_MARKER_LBL</source>
+ <translation>Diamond</translation>
+ </message>
+ <message>
+ <source>PLOT2D_LEGEND_POSITION_TOP</source>
+ <translation>Top</translation>
+ </message>
+ <message>
+ <source>TOT_PLOT2D_CHANGE_BACKGROUND</source>
+ <translation>Change background</translation>
+ </message>
+ <message>
+ <source>MEN_PLOT2D_CHANGE_BACKGROUND</source>
+ <translation>Change background...</translation>
+ </message>
+ <message>
+ <source>PRP_PLOT2D_CHANGE_BACKGROUND</source>
+ <translation>Change background color</translation>
+ </message>
+ <message>
+ <source>SOLID_LINE_LBL</source>
+ <translation>Solid</translation>
+ </message>
+ <message>
+ <source>PLOT2D_GRID_ENABLE_VER_MAJOR</source>
+ <translation>Vertical major</translation>
+ </message>
+ <message>
+ <source>PLOT2D_GRID_ENABLE_HOR_MAJOR</source>
+ <translation>Horizontal major</translation>
+ </message>
+ <message>
+ <source>PLOT2D_GRID_ENABLE_VER_MINOR</source>
+ <translation>Vertical minor</translation>
+ </message>
+ <message>
+ <source>TOT_PLOT2D_CURVES_POINTS</source>
+ <translation>Draw points</translation>
+ </message>
+ <message>
+ <source>PLOT2D_GRID_ENABLE_HOR_MINOR</source>
+ <translation>Horizontal minor</translation>
+ </message>
+ <message>
+ <source>PLOT2D_BACKGROUND_COLOR_LBL</source>
+ <translation>Background color:</translation>
+ </message>
+ <message>
+ <source>WRN_XLOG_NOT_ALLOWED</source>
+ <translation>Some points with non-positive abscissa values have been detected.
+Logarithmic scale for abscissa axis is not allowed.</translation>
+ </message>
+ <message>
+ <source>WRN_YLOG_NOT_ALLOWED</source>
+ <translation>Some points with non-positive ordinate values have been detected.
+Logarithmic scale for ordinate axis is not allowed.</translation>
+ </message>
+ <message>
+ <source>DSC_FITRECT</source>
+ <translation>Fit area within the view frame</translation>
+ </message>
+ <message>
+ <source>PLOT2D_LEGEND_POSITION_LEFT</source>
+ <translation>Left</translation>
+ </message>
+ <message>
+ <source>MNU_FITRECT</source>
+ <translation>Fit Area</translation>
+ </message>
+ <message>
+ <source>DOT_LINE_LBL</source>
+ <translation>Dot</translation>
+ </message>
+ <message>
+ <source>MEN_PLOT2D_CURVES_POINTS</source>
+ <translation>Draw points</translation>
+ </message>
+ <message>
+ <source>PRP_PLOT2D_CURVES_POINTS</source>
+ <translation>Switches view to points mode</translation>
+ </message>
+ <message>
+ <source>PLOT2D_SCALE_MODE_LOGARITHMIC</source>
+ <translation>Logarithmic</translation>
+ </message>
+ <message>
+ <source>PLOT2D_LEGEND_POSITION_RIGHT</source>
+ <translation>Right</translation>
+ </message>
+ <message>
+ <source>DSC_DUMP_VIEW</source>
+ <translation>Saves the active view in the image file</translation>
+ </message>
+ <message>
+ <source>WARNING</source>
+ <translation>Warning</translation>
+ </message>
+ <message>
+ <source>PLOT2D_ENABLE_LEGEND</source>
+ <translation>Show legend</translation>
+ </message>
+ <message>
+ <source>DSC_ZOOM_VIEW</source>
+ <translation>Zoom the view</translation>
+ </message>
+ <message>
+ <source>PRP_PLOT2D_SETTINGS</source>
+ <translation>Setups view properties</translation>
+ </message>
+ <message>
+ <source>INF_COORDINATES_SOME_Y</source>
+ <translation>Coordinates: X : %1, Y : %2 ( %3 )</translation>
+ </message>
+ <message>
+ <source>SCALING_POPUP</source>
+ <translation>Scaling</translation>
+ </message>
+ <message>
+ <source>PLOT2D_SCALE_MODE_LINEAR</source>
+ <translation>Linear</translation>
+ </message>
+ <message>
+ <source>TOT_PLOT2D_FITDATA</source>
+ <translation>Fit range</translation>
+ </message>
+ <message>
+ <source>PLOT2D_CURVE_TYPE_POINTS</source>
+ <translation>Points</translation>
+ </message>
+ <message>
+ <source>PLOT2D_CURVE_TYPE_SPLINE</source>
+ <translation>Spline</translation>
+ </message>
+ <message>
+ <source>MEN_PLOT2D_FITDATA</source>
+ <translation>Fit &Range</translation>
+ </message>
+ <message>
+ <source>MEN_PLOT2D_MODE_LOGARITHMIC_HOR</source>
+ <translation>Horizontal axis: logarithmic</translation>
+ </message>
+ <message>
+ <source>MEN_PLOT2D_MODE_LOGARITHMIC_VER</source>
+ <translation>Vertical axis: logarithmic</translation>
+ </message>
+ <message>
+ <source>PRP_PLOT2D_FITDATA</source>
+ <translation>Fits view to the given data range</translation>
+ </message>
+ <message>
+ <source>MEN_PLOT2D_MODE_LINEAR_VER</source>
+ <translation>Vertical axis: linear</translation>
+ </message>
+ <message>
+ <source>MEN_PLOT2D_MODE_LINEAR_HOR</source>
+ <translation>Horizontal axis: linear</translation>
+ </message>
+ <message>
+ <source>NONE_MARKER_LBL</source>
+ <translation>None</translation>
+ </message>
+ <message>
+ <source>ERR_DOC_CANT_SAVE_FILE</source>
+ <translation>Cannot save file</translation>
+ </message>
+ <message>
+ <source>MEN_PLOT2D_SHOW_LEGEND</source>
+ <translation>Show &Legend</translation>
+ </message>
+ <message>
+ <source>PRP_PLOT2D_SHOW_LEGEND</source>
+ <translation>Enables/disables legend</translation>
+ </message>
+ <message>
+ <source>TOT_PLOT2D_SHOW_LEGEND</source>
+ <translation>Show Legend</translation>
+ </message>
+ <message>
+ <source>INF_AXES_Y_RIGHT</source>
+ <translation>Axis Y Right</translation>
+ </message>
+ <message>
+ <source>DAHSDOTDOT_LINE_LBL</source>
+ <translation>DashDotDot</translation>
+ </message>
+ <message>
+ <source>TOT_PLOT2D_CURVES_SPLINES</source>
+ <translation>Draw splines</translation>
+ </message>
+ <message>
+ <source>CURVE_MARKER_TYPE_LAB</source>
+ <translation>Marker type:</translation>
+ </message>
+ <message>
+ <source>MEN_PLOT2D_SETTINGS</source>
+ <translation>&Settings</translation>
+ </message>
+ <message>
+ <source>CIRCLE_MARKER_LBL</source>
+ <translation>Circle</translation>
+ </message>
+ <message>
+ <source>LBL_TOOLBAR_LABEL</source>
+ <translation>View Operations</translation>
+ </message>
+ <message>
+ <source>NONE_LINE_LBL</source>
+ <translation>None</translation>
+ </message>
+ <message>
+ <source>PLOT2D_MARKER_SIZE_LBL</source>
+ <translation>Marker size:</translation>
+ </message>
+ <message>
+ <source>PLOT2D_ENABLE_MAIN_TITLE</source>
+ <translation>Main title</translation>
+ </message>
+ <message>
+ <source>TOT_PLOT2D_CURVES_LINES</source>
+ <translation>Draw lines</translation>
+ </message>
+ <message>
+ <source>PRP_PLOT2D_CURVES_LINES</source>
+ <translation>Switches view to lines mode</translation>
+ </message>
+ <message>
+ <source>MEN_PLOT2D_CURVES_LINES</source>
+ <translation>Draw lines</translation>
+ </message>
+</context>
+<context>
+ <name>Plot2d_FitDataDlg</name>
+ <message>
+ <source>FIT_HORIZONTAL</source>
+ <translation>Fit horizontally</translation>
+ </message>
+ <message>
+ <source>MIN_VALUE_LAB</source>
+ <translation>Min:</translation>
+ </message>
+ <message>
+ <source>VERTICAL_AXIS</source>
+ <translation>Vertical axis</translation>
+ </message>
+ <message>
+ <source>MAX_VALUE_LAB</source>
+ <translation>Max:</translation>
+ </message>
+ <message>
+ <source>HORIZONTAL_AXIS</source>
+ <translation>Horizontal axis</translation>
+ </message>
+ <message>
+ <source>VERTICAL_LEFT_AXIS</source>
+ <translation>Vertical left axis</translation>
+ </message>
+ <message>
+ <source>FIT_ALL</source>
+ <translation>Fit both</translation>
+ </message>
+ <message>
+ <source>VERTICAL_RIGHT_AXIS</source>
+ <translation>Vertical right axis</translation>
+ </message>
+ <message>
+ <source>FIT_VERTICAL</source>
+ <translation>Fit vertically</translation>
+ </message>
+</context>
+<context>
+ <name>Plot2d_ViewManager</name>
+ <message>
+ <source>PLOT2D_VIEW_TITLE</source>
+ <translation>Plot2d scene:%M - viewer:%V</translation>
+ </message>
+</context>
+</TS>
--- /dev/null
+TEMPLATE = lib
+TARGET = SalomePrs
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += PRS_EXPORTS
+
+HEADERS = SALOME_Prs.h
+
+SOURCES = SALOME_Prs.cxx
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+INSTALLS += includes
*/
void SALOME_View::LocalSelection( const SALOME_OCCPrs*, const int )
{
-// MESSAGE( "SALOME_View::LocalSelection( const SALOME_OCCPrs* ) called! \
+// MESSAGE( "SALOME_View::LocalSelection( const SALOME_OCCPrs* ) called!
// Probably, selection is being activated in uncompatible viewframe." );
}
*/
void SALOME_View::LocalSelection( const SALOME_VTKPrs*, const int )
{
-// MESSAGE( "SALOME_View::LocalSelection( const SALOME_VTKPrs* ) called! \
+// MESSAGE( "SALOME_View::LocalSelection( const SALOME_VTKPrs* ) called!
// Probably, selection is being activated in uncompatible viewframe." );
}
*/
void SALOME_View::LocalSelection( const SALOME_Prs2d*, const int )
{
-// MESSAGE( "SALOME_View::LocalSelection( const SALOME_Prs2d* ) called! \
+// MESSAGE( "SALOME_View::LocalSelection( const SALOME_Prs2d* ) called!
// Probably, selection is being activated in uncompatible viewframe." );
}
*/
void SALOME_View::GlobalSelection( const bool ) const
{
-// MESSAGE( "SALOME_View::GlobalSelection() called! \
+// MESSAGE( "SALOME_View::GlobalSelection() called!
// Probably, selection is being activated in uncompatible viewframe." );
}
#ifndef SALOME_PRS_H
#define SALOME_PRS_H
-#ifdef WNT
+#ifdef WIN32
#ifdef PRS_EXPORTS
#define PRS_EXPORT __declspec(dllexport)
#else
virtual void GlobalSelection( const bool = false ) const;
//! Creates empty presenation of corresponding type
- virtual SALOME_Prs* CreatePrs( const char* entry = 0 ) { return 0; }
+ virtual SALOME_Prs* CreatePrs( const char* /*entry*/ = 0 ) { return 0; }
// Axiluary methods called before and after displaying of objects
- virtual void BeforeDisplay( SALOME_Displayer* d ) {} //!< Null body here
- virtual void AfterDisplay ( SALOME_Displayer* d ) {} //!< Null body here
+ virtual void BeforeDisplay( SALOME_Displayer* ) {} //!< Null body here
+ virtual void AfterDisplay ( SALOME_Displayer* ) {} //!< Null body here
// New methods (asv)
//! \retval Return false.
lib_LTLIBRARIES = libPyInterp.la
-salomeinclude_HEADERS= \
- PyInterp.h \
- PyInterp_base.h \
+salomeinclude_HEADERS= \
+ PyInterp.h \
+ PyInterp_Interp.h \
PyInterp_Dispatcher.h
-dist_libPyInterp_la_SOURCES= \
- PyInterp_base.cxx \
+dist_libPyInterp_la_SOURCES= \
+ PyInterp_Interp.cxx \
PyInterp_Dispatcher.cxx
MOC_FILES= PyInterp_Watcher_moc.cxx
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-#if !defined ( _PYINTERP_H )
-#define _PYINTERP_H
+// File : PyInterp.h
+// Author : Vadim SANDLER
+// Module : SALOME
+
+#if !defined ( PYINTERP_H )
+#define PYINTERP_H
// ========================================================
// set dllexport type for Win platform
-#ifdef WNT
-
-#ifdef PYINTERP_EXPORTS
-#define PYINTERP_EXPORT __declspec(dllexport)
-#else
-#define PYINTERP_EXPORT __declspec(dllimport)
-#endif
-
-#else // WNT
-
-#define PYINTERP_EXPORT
-
-#endif // WNT
+#ifdef WIN32
+# ifdef PYINTERP_EXPORTS
+# define PYINTERP_EXPORT __declspec(dllexport)
+# else
+# define PYINTERP_EXPORT __declspec(dllimport)
+# endif
+#else // WIN32
+# define PYINTERP_EXPORT
+#endif // WIN32
// ========================================================
// little trick - if we do not have debug python libraries
// ========================================================
// avoid warning messages
-#ifdef WNT
+#ifdef WIN32
#pragma warning (disable : 4786)
#pragma warning (disable : 4251)
#endif
-#endif // _PYINTERP_H
+#endif // PYINTERP_H
--- /dev/null
+TEMPLATE = lib
+TARGET = PyInterp
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+PYTHONVER=2.4
+PYTHONHOME=$$(PYTHONHOME)
+PYTHONINC=$${PYTHONHOME}/include/python$${PYTHONVER}
+PYTHONLIB=$${PYTHONHOME}/lib
+
+INCLUDEPATH += ../../include $${PYTHONINC}
+unix:LIBS += -L$${PYTHONLIB} -lpython$${PYTHONVER}
+win32:LIBS += /LIBPATH:$${PYTHONLIB}
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += PYINTERP_EXPORTS
+
+HEADERS = PyInterp.h
+HEADERS += PyInterp_Dispatcher.h
+HEADERS += PyInterp_Watcher.h
+HEADERS += PyInterp_Interp.h
+
+SOURCES = PyInterp_Dispatcher.cxx
+SOURCES += PyInterp_Interp.cxx
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+INSTALLS += includes
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-// SALOME SALOMEGUI : implementation of desktop and GUI kernel
-//
// File : PyInterp_Dispatcher.cxx
// Author : Sergey ANIKIN, OCC
// Module : GUI
-// $Header$
-
-#include <PyInterp_base.h>
-#include <PyInterp_Dispatcher.h>
-#include <PyInterp_Watcher.h>
+#include "PyInterp_Dispatcher.h" // !!! WARNING !!! THIS INCLUDE MUST BE THE VERY FIRST !!!
+#include "PyInterp_Interp.h"
+#include "PyInterp_Watcher.h"
-#include <qapplication.h>
-#include <qobject.h>
+#include <QObject>
+#include <QCoreApplication>
-//#include <utilities.h>
using namespace std;
PyInterp_Dispatcher* PyInterp_Dispatcher::myInstance = 0;
{
safeExecute();
- myMutex.lock();
- //if ( !IsSync() && getListener() && getEvent() )
- if ( getListener() && getEvent() )
- postEvent();
- myMutex.unlock();
+ bool isSync = IsSync();
+
+ if ( !isSync )
+ myMutex.lock();
+
+ if ( listener() )
+ processEvent( listener() );
+
+ if ( !isSync )
+ myMutex.unlock();
}
void PyInterp_Request::safeExecute()
return new PyInterp_Event( PyInterp_Event::NOTIFY, (PyInterp_Request*)this );
}
-QEvent* PyInterp_Request::getEvent()
+void PyInterp_Request::processEvent( QObject* o )
{
- //if ( !myEvent && !IsSync() )
- if ( !myEvent )
- myEvent = createEvent();
- return myEvent;
-}
+ if ( !o )
+ return;
-void PyInterp_Request::postEvent()
-{
-#if QT_VERSION >= 0x030303
-// MESSAGE("*** PyInterp_Request::postEvent(): for Qt 3.3.3")
- QApplication::postEvent( getListener(), getEvent() );
-#else
-// MESSAGE("*** PyInterp_Request::postEvent(): for Qt 3.0.5")
- QThread::postEvent( getListener(), getEvent() );
-#endif
+ QEvent* e = createEvent();
+ if ( !e )
+ return;
+
+ if ( !IsSync() )
+ QCoreApplication::postEvent( o, e );
+ else
+ {
+ QCoreApplication::sendEvent( o, e );
+ delete e;
+ }
}
void PyInterp_Request::setListener( QObject* o )
// Clear the request queue
myQueueMutex.lock();
- for ( std::list<PyInterp_Request*>::iterator it = myQueue.begin(); it != myQueue.end(); ++it )
- PyInterp_Request::Destroy( *it );
+ QListIterator<RequestPtr> it( myQueue );
+ while ( it.hasNext() )
+ PyInterp_Request::Destroy( it.next() );
myQueue.clear();
myQueueMutex.unlock();
bool PyInterp_Dispatcher::IsBusy() const
{
- return running();
+ return isRunning();
}
void PyInterp_Dispatcher::Exec( PyInterp_Request* theRequest )
//if ( theRequest->IsSync() && !IsBusy() ) // synchronous processing - nothing is done if dispatcher is busy!
if ( theRequest->IsSync() ) // synchronous processing - nothing is done if dispatcher is busy!
processRequest( theRequest );
- else { // asynchronous processing
+ else // asynchronous processing
+ {
myQueueMutex.lock();
- myQueue.push_back( theRequest );
- if ( theRequest->getListener() )
- QObject::connect( theRequest->getListener(), SIGNAL( destroyed( QObject* ) ), myWatcher, SLOT( onDestroyed( QObject* ) ) );
+ myQueue.enqueue( theRequest );
+ if ( theRequest->listener() )
+ QObject::connect( theRequest->listener(), SIGNAL( destroyed( QObject* ) ), myWatcher, SLOT( onDestroyed( QObject* ) ) );
myQueueMutex.unlock();
if ( !IsBusy() )
while( myQueue.size() ) {
// MESSAGE("*** PyInterp_Dispatcher::run(): next request taken from the queue")
- aRequest = myQueue.front();
+ aRequest = myQueue.head();
// let other threads append their requests to the end of the queue
myQueueMutex.unlock();
// prepare for removal of the first request in the queue
myQueueMutex.lock();
// IMPORTANT: the first item could have been removed by objectDestroyed() --> we have to check it
- if ( myQueue.front() == aRequest ) // It's still here --> remove it
- myQueue.pop_front();
+ if ( myQueue.head() == aRequest ) // It's still here --> remove it
+ myQueue.dequeue();
// MESSAGE("*** PyInterp_Dispatcher::run(): request processed")
}
// prepare for modification of the queue
myQueueMutex.lock();
- for ( std::list<RequestPtr>::iterator it = myQueue.begin(); it != myQueue.end(); ++it ){
- if ( o == (*it)->getListener() ){
- (*it)->setListener( 0 ); // to prevent event posting
- it = myQueue.erase( it );
+ QMutableListIterator<RequestPtr> it( myQueue );
+ while ( it.hasNext() )
+ {
+ RequestPtr r = it.next();
+ if ( o == r->listener() )
+ {
+ r->setListener( 0 ); // to prevent event posting
+ it.remove();
}
}
myQueueMutex.unlock();
}
-
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-// SALOME SALOMEGUI : implementation of desktop and GUI kernel
-//
// File : PyInterp_Dispatcher.h
// Author : Sergey Anikin, OCC
// Module : SALOME
-#ifndef _PYINTERP_DISPATCHER_H_
-#define _PYINTERP_DISPATCHER_H_
-
-#include "PyInterp.h"
+#ifndef PYINTERP_DISPATCHER_H
+#define PYINTERP_DISPATCHER_H
-#include <qthread.h>
-#include <qevent.h>
+#include "PyInterp.h" // !!! WARNING !!! THIS INCLUDE MUST BE THE VERY FIRST !!!
-#include <list>
+#include <QMutex>
+#include <QThread>
+#include <QEvent>
+#include <QQueue>
class QObject;
-class PyInterp_base;
+class PyInterp_Interp;
class PyInterp_Watcher;
class PyInterp_Dispatcher;
PyInterp_Request( const PyInterp_Request& );
protected:
- virtual ~PyInterp_Request() {};
+ virtual ~PyInterp_Request() {};
// protected destructor - to control deletion of requests
public:
PyInterp_Request( QObject* listener, bool sync = false )
- : myIsSync( sync ), myListener( listener ), myEvent( 0 ) {};
+ : myIsSync( sync ), myListener( listener ) {};
static void Destroy( PyInterp_Request* );
// Deletes a request
virtual QEvent* createEvent() const;
// This method can be overridden to customize notification event creation
+ virtual void processEvent( QObject* );
+
private:
void process();
- QObject* getListener() const { return myListener; }
+ QObject* listener() const { return myListener; }
void setListener( QObject* );
- QEvent* getEvent();
- void postEvent();
private:
+ QMutex myMutex;
bool myIsSync;
QObject* myListener;
- QEvent* myEvent;
- QMutex myMutex;
};
class PYINTERP_EXPORT PyInterp_LockRequest : public PyInterp_Request
{
public:
- PyInterp_LockRequest( PyInterp_base* interp, QObject* listener = 0, bool sync = false )
+ PyInterp_LockRequest( PyInterp_Interp* interp, QObject* listener = 0, bool sync = false )
: PyInterp_Request( listener, sync ), myInterp( interp ) {}
protected:
- PyInterp_base* getInterp() const { return myInterp; }
+ PyInterp_Interp* getInterp() const { return myInterp; }
- virtual void safeExecute();
+ virtual void safeExecute();
private:
- PyInterp_base* myInterp;
+ PyInterp_Interp* myInterp;
};
-class PYINTERP_EXPORT PyInterp_Event : public QCustomEvent
+class PYINTERP_EXPORT PyInterp_Event : public QEvent
{
PyInterp_Event();
PyInterp_Event( const PyInterp_Event& );
enum { NOTIFY = QEvent::User + 5000, OK, ERROR, INCOMPLETE, LAST };
PyInterp_Event( int type, PyInterp_Request* request )
- : QCustomEvent( (QEvent::Type)type ), myRequest( request ) {}
+ : QEvent( (QEvent::Type)type ), myRequest( request ) {}
virtual ~PyInterp_Event();
private:
typedef PyInterp_Request* RequestPtr;
- std::list<RequestPtr> myQueue;
+ QQueue<RequestPtr> myQueue;
QMutex myQueueMutex;
PyInterp_Watcher* myWatcher;
friend class PyInterp_Watcher;
};
-#endif
+#endif // PYINTERP_DISPATCHER_H
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File : PyInterp_Interp.cxx
+// Author : Christian CAREMOLI, Paul RASCLE, EDF
+// Module : SALOME
+
+#include "PyInterp_Interp.h" // !!! WARNING !!! THIS INCLUDE MUST BE THE VERY FIRST !!!
+
+#include <cStringIO.h>
+
+#include <string>
+#include <vector>
+
+using namespace std;
+
+#define TOP_HISTORY_PY "--- top of history ---"
+#define BEGIN_HISTORY_PY "--- begin of history ---"
+
+PyLockWrapper::PyLockWrapper(PyThreadState* theThreadState):
+ myThreadState(theThreadState),
+ mySaveThreadState(0)
+{
+ if (myThreadState->interp == PyInterp_Interp::_interp)
+ _savestate = PyGILState_Ensure();
+ else
+ PyEval_AcquireThread(myThreadState);
+}
+
+PyLockWrapper::~PyLockWrapper()
+{
+ if (myThreadState->interp == PyInterp_Interp::_interp)
+ PyGILState_Release(_savestate);
+ else
+ PyEval_ReleaseThread(myThreadState);
+}
+
+PyLockWrapper PyInterp_Interp::GetLockWrapper()
+{
+ return _tstate;
+}
+
+/*!
+ \class PyInterp_Interp
+ \brief Generic embedded Python interpreter.
+*/
+
+int PyInterp_Interp::_argc = 1;
+char* PyInterp_Interp::_argv[] = {""};
+PyObject* PyInterp_Interp::builtinmodule = NULL;
+PyThreadState* PyInterp_Interp::_gtstate = NULL;
+PyInterpreterState* PyInterp_Interp::_interp = NULL;
+
+/*!
+ \brief Basic constructor.
+
+ After construction the interpreter instance successor classes
+ must call virtual method initalize().
+*/
+PyInterp_Interp::PyInterp_Interp():
+ _tstate(0), _vout(0), _verr(0), _g(0)
+{
+}
+
+/*!
+ \brief Destructor.
+*/
+PyInterp_Interp::~PyInterp_Interp()
+{
+}
+
+/*!
+ \brief Initialize embedded interpreter.
+
+ This method shoud be called after construction of the interpreter.
+ The method initialize() calls virtuals methods
+ - initPython() to initialize global Python interpreter
+ - initState() to initialize embedded interpreter state
+ - initContext() to initialize interpreter internal context
+ - initRun() to prepare interpreter for running commands
+ which should be implemented in the successor classes, according to the
+ embedded Python interpreter policy (mono or multi interpreter, etc).
+*/
+void PyInterp_Interp::initialize()
+{
+ _history.clear(); // start a new list of user's commands
+ _ith = _history.begin();
+
+ initPython();
+ // Here the global lock is released
+
+ initState();
+
+ PyLockWrapper aLock = GetLockWrapper();
+
+ initContext();
+
+ // used to interpret & compile commands
+ PyObjWrapper m(PyImport_ImportModule("codeop"));
+ if(!m) {
+ PyErr_Print();
+ return;
+ }
+
+ // Create cStringIO to capture stdout and stderr
+ PycString_IMPORT;
+ if (PycStringIO) { // CTH11627 : additional check
+ _vout = PycStringIO->NewOutput(128);
+ _verr = PycStringIO->NewOutput(128);
+ }
+
+ // All the initRun outputs are redirected to the standard output (console)
+ initRun();
+}
+
+/*!
+ \brief Initialize Python interpreter.
+
+ Set program name, initialize interpreter, set program arguments,
+ initiaize threads.
+ */
+void PyInterp_Interp::initPython()
+{
+ if (Py_IsInitialized())
+ return;
+
+ // Python is not initialized
+ Py_SetProgramName(_argv[0]);
+ Py_Initialize(); // Initialize the interpreter
+ PySys_SetArgv(_argc, _argv);
+ PyEval_InitThreads(); // Create (and acquire) the interpreter lock
+ _interp = PyThreadState_Get()->interp;
+ _gtstate = PyEval_SaveThread(); // Release global thread state
+}
+
+/*!
+ \brief Get embedded Python interpreter banner.
+ \return banner string
+ */
+string PyInterp_Interp::getbanner()
+{
+ // Should we take the lock ?
+ // PyEval_RestoreThread(_tstate);
+ string aBanner("Python ");
+ aBanner = aBanner + Py_GetVersion() + " on " + Py_GetPlatform() ;
+ aBanner = aBanner + "\ntype help to get general information on environment\n";
+ //PyEval_SaveThread();
+ return aBanner;
+}
+
+/*!
+ \brief Initialize run command.
+
+ This method is used to prepare interpreter for running
+ Python commands.
+
+ \return \c true on success and \c false on error
+*/
+bool PyInterp_Interp::initRun()
+{
+ PySys_SetObject("stderr",_verr);
+ PySys_SetObject("stdout",_vout);
+
+ PyObjWrapper verr(PyObject_CallMethod(_verr,"reset",""));
+ PyObjWrapper vout(PyObject_CallMethod(_vout,"reset",""));
+
+ //PyObject *m = PyImport_GetModuleDict();
+
+ PySys_SetObject("stdout",PySys_GetObject("__stdout__"));
+ PySys_SetObject("stderr",PySys_GetObject("__stderr__"));
+
+ return true;
+}
+
+/*!
+ \brief Compile Python command and evaluate it in the
+ python dictionary context if possible.
+ \internal
+ \param command Python command string
+ \param context Python context (dictionary)
+ \return -1 on fatal error, 1 if command is incomplete and 0
+ if command is executed successfully
+ */
+static int compile_command(const char *command,PyObject *context)
+{
+ PyObject *m = PyImport_AddModule("codeop");
+ if(!m) { // Fatal error. No way to go on.
+ PyErr_Print();
+ return -1;
+ }
+ PyObjWrapper v(PyObject_CallMethod(m,"compile_command","s",command));
+ if(!v) {
+ // Error encountered. It should be SyntaxError,
+ //so we don't write out traceback
+ PyObjWrapper exception, value, tb;
+ PyErr_Fetch(&exception, &value, &tb);
+ PyErr_NormalizeException(&exception, &value, &tb);
+ PyErr_Display(exception, value, NULL);
+ return -1;
+ }
+ else if (v == Py_None) {
+ // Incomplete text we return 1 : we need a complete text to execute
+ return 1;
+ }
+ else {
+ // Complete and correct text. We evaluate it.
+ //#if PY_VERSION_HEX < 0x02040000 // python version earlier than 2.4.0
+ // PyObjWrapper r(PyEval_EvalCode(v,context,context));
+ //#else
+ PyObjWrapper r(PyEval_EvalCode((PyCodeObject *)(void *)v,context,context));
+ //#endif
+ if(!r) {
+ // Execution error. We return -1
+ PyErr_Print();
+ return -1;
+ }
+ // The command has been successfully executed. Return 0
+ return 0;
+ }
+}
+
+/*!
+ \brief Run Python command.
+ \param command Python command
+ \return command status
+*/
+int PyInterp_Interp::run(const char *command)
+{
+ beforeRun();
+ return simpleRun(command);
+}
+
+/*!
+ \brief Run Python command (used internally).
+ \param command Python command
+ \param addToHistory if \c true (default), the command is added to the commands history
+ \return command status
+*/
+int PyInterp_Interp::simpleRun(const char *command, const bool addToHistory)
+{
+ if( addToHistory && strcmp(command,"") != 0 ) {
+ _history.push_back(command);
+ _ith = _history.end();
+ }
+
+ // We come from C++ to enter Python world
+ // We need to acquire the Python global lock
+ //PyLockWrapper aLock(_tstate); // san - lock is centralized now
+
+ // Reset redirected outputs before treatment
+ PySys_SetObject("stderr",_verr);
+ PySys_SetObject("stdout",_vout);
+
+ PyObjWrapper verr(PyObject_CallMethod(_verr,"reset",""));
+ PyObjWrapper vout(PyObject_CallMethod(_vout,"reset",""));
+
+ int ier = compile_command(command,_g);
+
+ // Outputs are redirected on standards outputs (console)
+ PySys_SetObject("stdout",PySys_GetObject("__stdout__"));
+ PySys_SetObject("stderr",PySys_GetObject("__stderr__"));
+
+ return ier;
+}
+
+/*!
+ \brief Get previous command in the commands history.
+ \return previous command
+*/
+const char * PyInterp_Interp::getPrevious()
+{
+ if(_ith != _history.begin()){
+ _ith--;
+ return (*_ith).c_str();
+ }
+ else
+ return BEGIN_HISTORY_PY;
+}
+
+/*!
+ \brief Get next command in the commands history.
+ \return next command
+*/
+const char * PyInterp_Interp::getNext()
+{
+ if(_ith != _history.end()){
+ _ith++;
+ }
+ if (_ith == _history.end())
+ return TOP_HISTORY_PY;
+ else
+ return (*_ith).c_str();
+}
+
+/*!
+ \brief Get standard error output.
+ \return standard error output
+*/
+string PyInterp_Interp::getverr(){
+ //PyLockWrapper aLock(_tstate);
+ PyObjWrapper v(PycStringIO->cgetvalue(_verr));
+ string aRet(PyString_AsString(v));
+ return aRet;
+}
+
+/*!
+ \brief Get standard output.
+ \return standard output
+*/
+string PyInterp_Interp::getvout(){
+ //PyLockWrapper aLock(_tstate);
+ PyObjWrapper v(PycStringIO->cgetvalue(_vout));
+ string aRet(PyString_AsString(v));
+ return aRet;
+}
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File : PyInterp_Interp.h
+// Author : Christian CAREMOLI, Paul RASCLE, EDF
+// Module : SALOME
+
+#ifndef PYINTERP_INTERP_H
+#define PYINTERP_INTERP_H
+
+#include "PyInterp.h" // !!! WARNING !!! THIS INCLUDE MUST BE THE VERY FIRST !!!
+
+#include <list>
+#include <string>
+
+class PYINTERP_EXPORT PyLockWrapper
+{
+ PyThreadState* myThreadState;
+ PyThreadState* mySaveThreadState;
+ PyGILState_STATE _savestate;
+public:
+ PyLockWrapper(PyThreadState* theThreadState);
+ ~PyLockWrapper();
+};
+
+class PYINTERP_EXPORT PyInterp_Interp
+{
+public:
+ static int _argc;
+ static char* _argv[];
+ static PyObject *builtinmodule;
+ static PyThreadState *_gtstate;
+ static PyInterpreterState *_interp;
+
+ PyInterp_Interp();
+ virtual ~PyInterp_Interp();
+
+ void initialize();
+
+ virtual int run(const char *command);
+
+ PyLockWrapper GetLockWrapper();
+
+ std::string getbanner();
+ std::string getverr();
+ std::string getvout();
+
+ const char * getPrevious();
+ const char * getNext();
+
+protected:
+ PyThreadState * _tstate;
+ PyObject * _vout;
+ PyObject * _verr;
+ PyObject * _g;
+ PyObject * _codeop;
+ std::list<std::string> _history;
+ std::list<std::string>::iterator _ith;
+
+ virtual int beforeRun() { return 0; }
+ int simpleRun(const char* command, const bool addToHistory = true);
+
+ virtual bool initRun();
+ virtual void initPython();
+ virtual bool initState() = 0;
+ virtual bool initContext() = 0;
+};
+
+class PYINTERP_EXPORT PyObjWrapper
+{
+ PyObject* myObject;
+public:
+ PyObjWrapper(PyObject* theObject) : myObject(theObject) {}
+ PyObjWrapper() : myObject(0) {}
+ virtual ~PyObjWrapper() { Py_XDECREF(myObject); }
+
+ operator PyObject*() { return myObject; }
+ PyObject* operator->() { return myObject; }
+ PyObject* get() { return myObject; }
+ bool operator!() { return !myObject; }
+ bool operator==(PyObject* theObject) { return myObject == theObject; }
+ PyObject** operator&() { return &myObject; }
+ PyObjWrapper& operator=(PyObjWrapper* theObjWrapper)
+ {
+ Py_XDECREF(myObject);
+ myObject = theObjWrapper->myObject;
+ return *this;
+ }
+};
+
+#endif // PYINTERP_INTERP_H
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-#ifndef _PYINTERP_WATCHER_H_
-#define _PYINTERP_WATCHER_H_
+// File : PyInterp_Watcher.h
+// Author : Sergey Anikin, OCC
+// Module : SALOME
-#include <PyInterp.h>
+#ifndef PYINTERP_WATCHER_H
+#define PYINTERP_WATCHER_H
-#include <PyInterp_Dispatcher.h>
+#include "PyInterp.h" // !!! WARNING !!! THIS INCLUDE MUST BE THE VERY FIRST !!!
-#include <qobject.h>
+#include "PyInterp_Dispatcher.h"
+
+#include <QObject>
// Private class that keeps track of destructions of request listeners
class PYINTERP_EXPORT PyInterp_Watcher : public QObject
void onDestroyed( QObject* o ) { PyInterp_Dispatcher::Get()->objectDestroyed( o ); }
};
-#endif // _PYINTERP_WATCHER_H_
+#endif // PYINTERP_WATCHER_H
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-// SALOME SALOMEGUI : implementation of desktop and GUI kernel
-//
-// File : PyInterp_base.cxx
-// Author : Christian CAREMOLI, Paul RASCLE, EDF
-// Module : SALOME
-// $Header$
-
-
-#include <string>
-#include <vector>
-
-#include "PyInterp_base.h" // this include must be first (see PyInterp_base.h)!
-#include <cStringIO.h>
-
-using namespace std;
-
-PyLockWrapper::PyLockWrapper(PyThreadState* theThreadState):
- myThreadState(theThreadState),
- mySaveThreadState(0)
-{
-#if defined(USE_GILSTATE)
- if (myThreadState->interp == PyInterp_base::_interp) {
- _savestate = PyGILState_Ensure();
- } else {
- PyEval_AcquireThread(myThreadState);
- }
-#else
- PyEval_AcquireThread(myThreadState);
-#endif
-}
-
-PyLockWrapper::~PyLockWrapper()
-{
-#if defined(USE_GILSTATE)
- if (myThreadState->interp == PyInterp_base::_interp) {
- PyGILState_Release(_savestate);
- } else {
- PyEval_ReleaseThread(myThreadState);
- }
-#else
- PyEval_ReleaseThread(myThreadState);
-#endif
-}
-
-class PyReleaseLock{
-public:
- ~PyReleaseLock(){
- PyEval_ReleaseLock();
- }
-};
-
-
-PyLockWrapper PyInterp_base::GetLockWrapper(){
- return _tstate;
-}
-
-
-// main python interpreter (static attributes)
-
-int PyInterp_base::_argc = 1;
-char* PyInterp_base::_argv[] = {""};
-
-PyObject *PyInterp_base::builtinmodule = NULL;
-
-PyThreadState *PyInterp_base::_gtstate = NULL;
-PyInterpreterState *PyInterp_base::_interp = NULL;
-
-
-/*!
- * basic constructor here : herited classes constructors must call initalize() method
- * defined here.
- */
-PyInterp_base::PyInterp_base(): _tstate(0), _vout(0), _verr(0), _g(0), _atFirst(true)
-{
-}
-
-PyInterp_base::~PyInterp_base()
-{
-}
-
-
-/*!
- * Must be called by herited classes constructors. initialize() calls virtuals methods
- * initstate & initcontext, not defined here in base class. initstate & initcontext methods
- * must be implemented in herited classes, following the Python interpreter policy
- * (mono or multi interpreter...).
- */
-void PyInterp_base::initialize()
-{
- _history.clear(); // start a new list of user's commands
- _ith = _history.begin();
-
- init_python();
- // Here the global lock is released
-
- initState();
-
- PyLockWrapper aLock= GetLockWrapper();
-
- initContext();
-
- // used to interpret & compile commands
- PyObjWrapper m(PyImport_ImportModule("codeop"));
- if(!m){
- PyErr_Print();
- return;
- }
-
- // Create cStringIO to capture stdout and stderr
- PycString_IMPORT;
- if (PycStringIO) { // CTH11627 : additional check
- _vout = PycStringIO->NewOutput(128);
- _verr = PycStringIO->NewOutput(128);
- }
-
- // All the initRun outputs are redirected to the standard output (console)
- initRun();
-}
-
-void PyInterp_base::init_python()
-{
- _atFirst = false;
- if (Py_IsInitialized())
- return;
-
- // Python is not initialized
- Py_SetProgramName(_argv[0]);
- Py_Initialize(); // Initialize the interpreter
- PySys_SetArgv(_argc, _argv);
- PyEval_InitThreads(); // Create (and acquire) the interpreter lock
- _interp = PyThreadState_Get()->interp;
- _gtstate = PyEval_SaveThread(); // Release global thread state
-}
-
-string PyInterp_base::getbanner()
-{
- // Should we take the lock ?
- // PyEval_RestoreThread(_tstate);
- string aBanner("Python ");
- aBanner = aBanner + Py_GetVersion() + " on " + Py_GetPlatform() ;
- aBanner = aBanner + "\ntype help to get general information on environment\n";
- //PyEval_SaveThread();
- return aBanner;
-}
-
-
-int PyInterp_base::initRun()
-{
- PySys_SetObject("stderr",_verr);
- PySys_SetObject("stdout",_vout);
-
- PyObjWrapper verr(PyObject_CallMethod(_verr,"reset",""));
- PyObjWrapper vout(PyObject_CallMethod(_vout,"reset",""));
-
- //PyObject *m = PyImport_GetModuleDict();
-
- PySys_SetObject("stdout",PySys_GetObject("__stdout__"));
- PySys_SetObject("stderr",PySys_GetObject("__stderr__"));
-
- return 0;
-}
-
-
-/*!
- * This function compiles a string (command) and then evaluates it in the dictionnary
- * context if possible.
- * Returns :
- * -1 : fatal error
- * 1 : incomplete text
- * 0 : complete text executed with success
- */
-int compile_command(const char *command,PyObject *context)
-{
- PyObject *m = PyImport_AddModule("codeop");
- if(!m){ // Fatal error. No way to go on.
- PyErr_Print();
- return -1;
- }
- PyObjWrapper v(PyObject_CallMethod(m,"compile_command","s",command));
- if(!v){
- // Error encountered. It should be SyntaxError,
- //so we don't write out traceback
- PyObjWrapper exception, value, tb;
- PyErr_Fetch(&exception, &value, &tb);
- PyErr_NormalizeException(&exception, &value, &tb);
- PyErr_Display(exception, value, NULL);
- return -1;
- }else if (v == Py_None){
- // Incomplete text we return 1 : we need a complete text to execute
- return 1;
- }else{
- // Complete and correct text. We evaluate it.
- //#if PY_VERSION_HEX < 0x02040000 // python version earlier than 2.4.0
- // PyObjWrapper r(PyEval_EvalCode(v,context,context));
- //#else
- PyObjWrapper r(PyEval_EvalCode((PyCodeObject *)(void *)v,context,context));
- //#endif
- if(!r){
- // Execution error. We return -1
- PyErr_Print();
- return -1;
- }
- // The command has been successfully executed. Return 0
- return 0;
- }
-}
-
-
-int PyInterp_base::run(const char *command)
-{
- if(_atFirst){
- int ret = 0;
- ret = simpleRun("from Help import *");
- if (ret) {
- _atFirst = false;
- return ret;
- }
- ret = simpleRun("import salome");
- if (ret) {
- _atFirst = false;
- return ret;
- }
- ret = simpleRun("salome.salome_init(0,1)");
- if (ret) {
- _atFirst = false;
- return ret;
- }
- _atFirst = false;
- }
- return simpleRun(command);
-}
-
-
-int PyInterp_base::simpleRun(const char *command)
-{
- if( !_atFirst && strcmp(command,"") != 0 ) {
- _history.push_back(command);
- _ith = _history.end();
- }
-
- // We come from C++ to enter Python world
- // We need to acquire the Python global lock
- //PyLockWrapper aLock(_tstate); // san - lock is centralized now
-
- // Reset redirected outputs before treatment
- PySys_SetObject("stderr",_verr);
- PySys_SetObject("stdout",_vout);
-
- PyObjWrapper verr(PyObject_CallMethod(_verr,"reset",""));
- PyObjWrapper vout(PyObject_CallMethod(_vout,"reset",""));
-
- int ier = compile_command(command,_g);
-
- // Outputs are redirected on standards outputs (console)
- PySys_SetObject("stdout",PySys_GetObject("__stdout__"));
- PySys_SetObject("stderr",PySys_GetObject("__stderr__"));
-
- return ier;
-}
-
-
-const char * PyInterp_base::getPrevious()
-{
- if(_ith != _history.begin()){
- _ith--;
- return (*_ith).c_str();
- }
- else
- return BEGIN_HISTORY_PY;
-}
-
-
-const char * PyInterp_base::getNext()
-{
- if(_ith != _history.end()){
- _ith++;
- }
- if (_ith == _history.end())
- return TOP_HISTORY_PY;
- else
- return (*_ith).c_str();
-}
-
-
-string PyInterp_base::getverr(){
- //PyLockWrapper aLock(_tstate);
- PyObjWrapper v(PycStringIO->cgetvalue(_verr));
- string aRet(PyString_AsString(v));
- return aRet;
-}
-
-
-string PyInterp_base::getvout(){
- //PyLockWrapper aLock(_tstate);
- PyObjWrapper v(PycStringIO->cgetvalue(_vout));
- string aRet(PyString_AsString(v));
- return aRet;
-}
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-// SALOME SALOMEGUI : implementation of desktop and GUI kernel
-//
-// File : PyInterp_base.h
-// Author : Christian CAREMOLI, Paul RASCLE, EDF
-// Module : SALOME
-
-#ifndef _PYINTERP_BASE_H_
-#define _PYINTERP_BASE_H_
-
-#include "PyInterp.h"
-
-#include <list>
-#include <string>
-#include <iostream>
-
-// include order important!
-// pthread then python then qt
-//#include <pthread.h> // must be before Python.h !
-
-#include <Python.h> // must be before qt includes ...
-#include <compile.h> // Python include needed for versions before 2.4. Included in Python.h now.
-#include <eval.h> // Python include needed for versions before 2.4. Included in Python.h now.
-
-//#if PY_VERSION_HEX < 0x02040000 // python version earlier than 2.4.0
-//extern "C" PyObject * PyEval_EvalCode(PyObject *co, PyObject *g, PyObject *l);
-//#endif
-
-/* For 2.3, use the PyGILState_ calls */
-#if (PY_VERSION_HEX >= 0x02030000)
-#define USE_GILSTATE
-#endif
-
-#define TOP_HISTORY_PY "--- top of history ---"
-#define BEGIN_HISTORY_PY "--- begin of history ---"
-
-class PYINTERP_EXPORT PyLockWrapper
-{
- PyThreadState* myThreadState;
- PyThreadState* mySaveThreadState;
-#if defined(USE_GILSTATE)
- PyGILState_STATE _savestate ;
-#endif
- public:
- PyLockWrapper(PyThreadState* theThreadState);
- ~PyLockWrapper();
-};
-
-class PYINTERP_EXPORT PyInterp_base{
- public:
- static int _argc;
- static char* _argv[];
- static PyObject *builtinmodule;
- static PyThreadState *_gtstate;
- static PyInterpreterState *_interp;
-
- PyInterp_base();
- ~PyInterp_base();
-
- virtual void initialize();
- virtual void init_python();
- // init_python() made virtual to:
- // 1. Remove dependency on KERNEL in light SALOME configuration
- // 2. Allow redefinition of this method in SalomeApp_PyInterp class (it should be empty there and rely on KERNEL_PYTHON)
-
- virtual int run(const char *command);
-
- PyLockWrapper GetLockWrapper();
-
- std::string getbanner();
- std::string getverr();
- std::string getvout();
-
- const char * getPrevious();
- const char * getNext();
-
- protected:
- PyThreadState * _tstate;
- PyObject * _vout;
- PyObject * _verr;
- PyObject * _g;
- PyObject * _codeop;
- std::list<std::string> _history;
- std::list<std::string>::iterator _ith;
- bool _atFirst;
-
- int simpleRun(const char* command);
- int initRun();
-
- virtual bool initState() = 0;
- virtual bool initContext() = 0;
-};
-
-
-class PYINTERP_EXPORT PyObjWrapper{
- PyObject* myObject;
-public:
- PyObjWrapper(PyObject* theObject): myObject(theObject) {}
- PyObjWrapper(): myObject(0) {}
- operator PyObject*(){
- return myObject;
- }
- PyObject* operator->(){
- return myObject;
- }
- PyObject* get(){
- return myObject;
- }
- bool operator!(){
- return !myObject;
- }
- bool operator==(PyObject* theObject){
- return myObject == theObject;
- }
- PyObject** operator&(){
- return &myObject;
- }
- PyObjWrapper& operator=(PyObjWrapper* theObjWrapper){
- Py_XDECREF(myObject);
- myObject = theObjWrapper->myObject;
- return *this;
- }
- virtual ~PyObjWrapper(){
- Py_XDECREF(myObject);
- }
-};
-
-#endif
+++ /dev/null
-# Copyright (C) 2005 CEA/DEN, EDF R&D, OPEN CASCADE, PRINCIPIA R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-# File : Makefile.in
-# Author : Vladimir Klyachin (OCN)
-# Module : PythonConsole
-# $Header$
-
-include $(top_srcdir)/adm_local/unix/make_common_starter.am
-
-lib_LTLIBRARIES = libPythonConsole.la
-
-salomeinclude_HEADERS= \
- PythonConsole.h \
- PythonConsole_PyConsole.h \
- PythonConsole_PyEditor.h \
- PythonConsole_PyInterp.h
-
-dist_libPythonConsole_la_SOURCES= \
- PythonConsole_PyConsole.cxx \
- PythonConsole_PyEditor.cxx \
- PythonConsole_PyInterp.cxx
-
-MOC_FILES= \
- PythonConsole_PyEditor_moc.cxx \
- PythonConsole_PyConsole_moc.cxx
-nodist_libPythonConsole_la_SOURCES= $(MOC_FILES)
-
-
-libPythonConsole_la_CPPFLAGS= $(PYTHON_INCLUDES) $(QT_INCLUDES) \
- -I$(srcdir)/../PyInterp -I$(srcdir)/../SUIT -I$(srcdir)/../Qtx
-
-libPythonConsole_la_LDFLAGS= $(PYTHON_LIBS) $(QT_MT_LIBS)
-
-
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-#if !defined ( _PYTHONCONSOLE_H )
-#define _PYTHONCONSOLE_H
-
-// ========================================================
-// set dllexport type for Win platform
-#ifdef WNT
-
-#ifdef PYTHONCONSOLE_EXPORTS
-#define PYCONSOLE_EXPORT __declspec(dllexport)
-#else
-#define PYCONSOLE_EXPORT __declspec(dllimport)
-#endif
-
-#else // WNT
-
-#define PYCONSOLE_EXPORT
-
-#endif // WNT
-
-// ========================================================
-// little trick - if we do not have debug python libraries
-#ifdef _DEBUG
-#ifndef HAVE_DEBUG_PYTHON
-#undef _DEBUG
-#endif
-#endif
-
-//#include <Python.h>
-
-#ifdef _DEBUG
-#ifndef HAVE_DEBUG_PYTHON
-#define _DEBUG
-#endif
-#endif
-
-// ========================================================
-// avoid warning messages
-#ifdef WNT
-#pragma warning (disable : 4786)
-#pragma warning (disable : 4251)
-#endif
-
-#endif // _PYTHONCONSOLE_H
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-
-#include <Python.h>
-#include "PythonConsole_PyConsole.h"
-#include "PythonConsole_PyEditor.h"
-#include "PyInterp_base.h"
-
-#include "SUIT_Desktop.h"
-
-#include <qlayout.h>
-
-using namespace std;
-
-/*!
- Constructor
-*/
-PythonConsole::PythonConsole(QWidget* parent, PyInterp_base* interp)
-: QWidget(parent), myEditor( 0 )
-{
- // create python interpreter
- myInterp = interp;
- if ( !myInterp )
- myInterp = new PythonConsole_PyInterp();
-
- // initialize Python interpretator
- myInterp->initialize();
-
- // create editor console
- QVBoxLayout* lay = new QVBoxLayout( this );
- myEditor = new PythonConsole_PyEditor(myInterp, this,"Python Interpreter");
- lay->addWidget( myEditor );
-}
-
-/*!
- Destructor
-*/
-PythonConsole::~PythonConsole()
-{
-}
-
-/*!
- Executes command
- \param command - string with command and arguments
-*/
-void PythonConsole::exec( const QString& command )
-{
- if ( myEditor )
- myEditor->exec( command );
-}
-
-/*!
- Blocks execution of main application until command is executed
- \param command - string with command and arguments
-*/
-void PythonConsole::execAndWait( const QString& command )
-{
- if ( myEditor )
- myEditor->execAndWait( command );
-}
-
-/*!
- Changes font of python console
- \param f - new font
-*/
-void PythonConsole::setFont( const QFont& f )
-{
- if( myEditor )
- myEditor->setFont( f );
-}
-
-/*!
- \return font of python console
-*/
-QFont PythonConsole::font() const
-{
- QFont res;
- if( myEditor )
- res = myEditor->font();
- return res;
-}
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-#ifndef PythonConsole_PyConsole_H
-#define PythonConsole_PyConsole_H
-
-#include "PythonConsole.h"
-
-#include <qwidget.h>
-
-class PythonConsole_PyEditor;
-class PyInterp_base;
-
-class PYCONSOLE_EXPORT PythonConsole: public QWidget
-{
- Q_OBJECT;
-
-public:
- PythonConsole(QWidget* parent, PyInterp_base* interp = 0 );
- virtual ~PythonConsole();
-
- PyInterp_base* getInterp() { return myInterp; }
- QFont font() const;
- virtual void setFont( const QFont& );
-
- void exec( const QString& command );
- void execAndWait( const QString& command );
-protected:
- PyInterp_base* myInterp;
- PythonConsole_PyEditor* myEditor;
-};
-
-
-#endif
+++ /dev/null
-// SALOME SALOMEGUI : implementation of desktop and GUI kernel
-//
-// Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-//
-//
-// File : PythonConsole_PyEditor.cxx
-// Author : Nicolas REJNERI
-// Module : SALOME
-
-#include <PythonConsole_PyEditor.h> // this include must be first (see PyInterp_base.h)!
-
-#include <PyInterp_Dispatcher.h>
-
-#include <SUIT_Tools.h>
-#include <SUIT_Session.h>
-
-#include <qmap.h>
-#include <qclipboard.h>
-#include <qdragobject.h>
-#include <qapplication.h>
-#include <qpopupmenu.h>
-
-using namespace std;
-
-//#ifdef _DEBUG_
-//static int MYDEBUG = 1;
-//#else
-//static int MYDEBUG = 0;
-//#endif
-
-
-enum { IdCopy, IdPaste, IdClear, IdSelectAll };
-
-
-static QString READY_PROMPT = ">>> ";
-static QString DOTS_PROMPT = "... ";
-
-#define PROMPT_SIZE (int)_currentPrompt.length()
-
-class ExecCommand : public PyInterp_LockRequest
-{
-public:
- ExecCommand(PyInterp_base* theInterp, const char* theCommand,
- PythonConsole_PyEditor* theListener, bool sync = false)
- : PyInterp_LockRequest( theInterp, theListener, sync ),
- myCommand( theCommand ), myState( PyInterp_Event::OK )
- {}
-
-protected:
- virtual void execute(){
- if(myCommand != ""){
-// if(MYDEBUG) MESSAGE("*** ExecCommand::execute() started");
- SUIT_Session::SetPythonExecuted(true); // disable GUI user actions
- int ret = getInterp()->run( myCommand.latin1() );
- SUIT_Session::SetPythonExecuted(false); // enable GUI user actions
-// if(MYDEBUG) MESSAGE("ExecCommand::execute() - myInterp = "<<getInterp()<<"; myCommand = '"<<myCommand.latin1()<<"' - "<<ret);
- if(ret < 0)
- myState = PyInterp_Event::ERROR;
- else if(ret > 0)
- myState = PyInterp_Event::INCOMPLETE;
- myError = getInterp()->getverr().c_str();
- myOutput = getInterp()->getvout().c_str();
-// if(MYDEBUG) MESSAGE("*** ExecCommand::execute() finished");
- }else{
- myError = "";
- myOutput = "";
- }
- }
-
- virtual QEvent* createEvent() const
- {
- return new PyInterp_Event( myState, (PyInterp_Request*)this );
- }
-
-public:
- QString myError;
- QString myOutput;
-
-private:
- QString myCommand;
- int myState;
-};
-
-
-/*!
- Constructor
-*/
-PythonConsole_PyEditor::PythonConsole_PyEditor(PyInterp_base* theInterp, QWidget *theParent, const char* theName):
- QTextEdit(theParent,theName),
- myInterp( 0 ),
- myIsInLoop( false )
-{
- QString fntSet( "" );
- QFont aFont = SUIT_Tools::stringToFont( fntSet );
- setFont(aFont);
- //setTextFormat(QTextEdit::PlainText);
- setUndoRedoEnabled( false );
-
- _currentPrompt = READY_PROMPT;
- setWordWrap(NoWrap);
-
- connect(this,SIGNAL(returnPressed()),this,SLOT(handleReturn()) );
-
- // san - This is necessary for troubleless initialization
- onPyInterpChanged( theInterp );
-}
-
-/*!
- Destructor
-*/
-PythonConsole_PyEditor::~PythonConsole_PyEditor()
-{
-// if(MYDEBUG) MESSAGE("PythonConsole_PyEditor::~PythonConsole_PyEditor()");
-}
-
-/*!
- Called to insert a string s
-*/
-void PythonConsole_PyEditor::setText(QString s)
-{
- int para=paragraphs()-1;
- int col=paragraphLength(para);
- insertAt(s,para,col);
- int n = paragraphs()-1;
- setCursorPosition( n, paragraphLength(n));
-}
-
-/*!
- Convenient method for executing a Python command,
- as if the user typed it manually
-*/
-void PythonConsole_PyEditor::exec( const QString& command )
-{
- // Some interactive command is being executed in this editor -> do nothing
- if ( isReadOnly() ) {
- myQueue.push_back( command );
- return;
- }
- int para=paragraphs()-1;
- removeParagraph( para );
- _currentPrompt = READY_PROMPT;
- _buf.truncate(0);
- _isInHistory = false;
- setText( "\n" + _currentPrompt);
- setText( command + "\n" );
- handleReturn();
-}
-
-void PythonConsole_PyEditor::execAndWait( const QString& command )
-{
- if( myIsInLoop )
- return;
-
- myIsInLoop = true;
- exec( command );
- qApp->enter_loop();
- myIsInLoop = false;
-}
-
-/*!
- Called when an handleReturn
-*/
-void PythonConsole_PyEditor::handleReturn()
-{
- int para=paragraphs()-2;
- _buf.append(text(para).remove(0,PROMPT_SIZE));
- _buf.truncate( _buf.length() - 1 );
- setReadOnly( true );
- viewport()->setCursor( waitCursor );
-
- // Post a request to execute Python command
- // Editor will be informed via a custom event that execution has been completed
- PyInterp_Dispatcher::Get()->Exec( new ExecCommand( myInterp, _buf.latin1(), this ) );
-}
-
-/*!
- Processes drop event: paste dragged text
-*/
-void PythonConsole_PyEditor::contentsDropEvent( QDropEvent* event )
-{
- event->acceptAction();
- QString text;
- if ( QTextDrag::decode( event, text ) ) {
- int par, col;
- int endLine = paragraphs() -1;
- col = charAt( event->pos(), &par );
-
- if ( col >= 0 && par >= 0 ) {
- if ( par != endLine || col < PROMPT_SIZE ) {
- par = endLine;
- col = paragraphLength( endLine );
- }
- setCursorPosition( par, col );
- insertAt( text, par, col );
- removeSelection();
- }
- }
-}
-
-/*!
- Processes middle button release event - paste clipboard's contents
-*/
-void PythonConsole_PyEditor::contentsMouseReleaseEvent( QMouseEvent* event )
-{
- if ( event->button() == LeftButton ) {
- QTextEdit::contentsMouseReleaseEvent(event);
- copy();
- }
- if ( event->button() == MidButton ) {
- if (QApplication::clipboard()->supportsSelection()) {
- int par, col;
- int endLine = paragraphs() -1;
- col = charAt( event->pos(), &par );
- if ( col >= 0 && par >= 0 ) {
- // PAL12896 -->
- if ( par != endLine || col < PROMPT_SIZE ) {
- QPoint aPos = paragraphRect(endLine).bottomRight();
- QMouseEvent* e = new QMouseEvent(event->type(),aPos,event->button(),event->state());
- QTextEdit::contentsMouseReleaseEvent(e);
- }
- else
- QTextEdit::contentsMouseReleaseEvent(event);
- // PAL12896 <--
- }
- }
- }
- else {
- QTextEdit::contentsMouseReleaseEvent(event);
- }
-}
-
-/*
- Processes own popup menu
-*/
-void PythonConsole_PyEditor::mousePressEvent (QMouseEvent* event)
-{
- if ( event->button() == RightButton ) {
- QPopupMenu *popup = new QPopupMenu( this );
- QMap<int, int> idMap;
-
- int para1, col1, para2, col2;
- getSelection(¶1, &col1, ¶2, &col2);
- bool allSelected = hasSelectedText() &&
- para1 == 0 && para2 == paragraphs()-1 && col1 == 0 && para2 == paragraphLength(para2);
- int id;
- id = popup->insertItem( tr( "EDIT_COPY_CMD" ) );
- idMap.insert(IdCopy, id);
- id = popup->insertItem( tr( "EDIT_PASTE_CMD" ) );
- idMap.insert(IdPaste, id);
- id = popup->insertItem( tr( "EDIT_CLEAR_CMD" ) );
- idMap.insert(IdClear, id);
- popup->insertSeparator();
- id = popup->insertItem( tr( "EDIT_SELECTALL_CMD" ) );
- idMap.insert(IdSelectAll, id);
- popup->setItemEnabled( idMap[ IdCopy ], hasSelectedText() );
- popup->setItemEnabled( idMap[ IdPaste ],
- !isReadOnly() && (bool)QApplication::clipboard()->text().length() );
- popup->setItemEnabled( idMap[ IdSelectAll ],
- (bool)text().length() && !allSelected );
-
- int r = popup->exec( event->globalPos() );
- delete popup;
-
- if ( r == idMap[ IdCopy ] ) {
- copy();
- }
- else if ( r == idMap[ IdPaste ] ) {
- paste();
- }
- else if ( r == idMap[ IdClear ] ) {
- clear();
- setText(myBanner);
- _currentPrompt = READY_PROMPT;
- setText(_currentPrompt);
- }
- else if ( r == idMap[ IdSelectAll ] ) {
- selectAll();
- }
- }
- else {
- QTextEdit::mousePressEvent(event);
- }
-}
-
-/*!
- Checks, is the string a command line or not.
-*/
-
-bool PythonConsole_PyEditor::isCommand( const QString& str) const
-{
- // prompt may be '>>> ' or for '... '
- return ( str.find( READY_PROMPT ) == 0 || str.find( DOTS_PROMPT ) == 0 );
-}
-
-
-/*!
- Called when a keyPress event
-*/
-void PythonConsole_PyEditor::keyPressEvent( QKeyEvent* e )
-{
- // get cursor position
- int curLine, curCol;
- getCursorPosition(&curLine, &curCol);
-
- // get last edited line
- int endLine = paragraphs() -1;
-
- // get pressed key code
- int aKey = e->key();
-
- // check if <Ctrl> is pressed
- bool ctrlPressed = e->state() & ControlButton;
- // check if <Shift> is pressed
- bool shftPressed = e->state() & ShiftButton;
-
- // process <Ctrl>+<C> key-bindings
- if ( aKey == Key_C && ctrlPressed ) {
- _buf.truncate(0);
- setText("\n");
- _currentPrompt = READY_PROMPT;
- setText(_currentPrompt);
- return;
- }
-
- // check for printed key
- aKey = ( aKey < Key_Space || aKey > Key_ydiaeresis ) ? aKey : 0;
-
- switch ( aKey ) {
- case 0 :
- // any printed key
- {
- if ( curLine < endLine || curCol < PROMPT_SIZE )
- moveCursor( QTextEdit::MoveEnd, false );
- QTextEdit::keyPressEvent( e );
- break;
- }
- case Key_Return:
- case Key_Enter:
- // <Enter> key
- {
- moveCursor( QTextEdit::MoveEnd, false );
- QTextEdit::keyPressEvent( e );
- break;
- }
- case Key_Up:
- // <Up> arrow key: process as follows:
- // - without <Ctrl>, <Shift> modifiers: previous command in history
- // - with <Ctrl> modifier key pressed: move cursor one row up without selection
- // - with <Shift> modifier key pressed: move cursor one row up with selection
- // - with <Ctrl>+<Shift> modifier keys pressed: scroll one row up
- {
- if ( ctrlPressed && shftPressed ) {
- scrollBy( 0, -QFontMetrics( font() ).lineSpacing() );
- }
- else if ( shftPressed ) {
- if ( curLine > 0 )
- moveCursor( QTextEdit::MoveUp, true );
- }
- else if ( ctrlPressed ) {
- moveCursor( QTextEdit::MoveUp, false );
- }
- else {
- QString histLine = _currentPrompt;
- if ( ! _isInHistory ) {
- _isInHistory = true;
- _currentCommand = text( endLine ).remove( 0, PROMPT_SIZE );
- _currentCommand.truncate( _currentCommand.length() - 1 );
- }
- QString previousCommand = myInterp->getPrevious();
- if ( previousCommand.compare( BEGIN_HISTORY_PY ) != 0 )
- {
- removeParagraph( endLine );
- histLine.append( previousCommand );
- append( histLine );
- }
- moveCursor( QTextEdit::MoveEnd, false );
- }
- break;
- }
- case Key_Down:
- // <Down> arrow key: process as follows:
- // - without <Ctrl>, <Shift> modifiers: next command in history
- // - with <Ctrl> modifier key pressed: move cursor one row down without selection
- // - with <Shift> modifier key pressed: move cursor one row down with selection
- // - with <Ctrl>+<Shift> modifier keys pressed: scroll one row down
- {
- if ( ctrlPressed && shftPressed ) {
- scrollBy( 0, QFontMetrics( font() ).lineSpacing() );
- }
- else if ( shftPressed ) {
- if ( curLine < endLine )
- moveCursor( QTextEdit::MoveDown, true );
- }
- else if ( ctrlPressed ) {
- moveCursor( QTextEdit::MoveDown, false );
- }
- else {
- QString histLine = _currentPrompt;
- QString nextCommand = myInterp->getNext();
- if ( nextCommand.compare( TOP_HISTORY_PY ) != 0 ) {
- removeParagraph( endLine );
- histLine.append( nextCommand );
- append( histLine );
- }
- else {
- if (_isInHistory) {
- _isInHistory = false;
- removeParagraph( endLine );
- histLine.append( _currentCommand );
- append( histLine );
- }
- }
- moveCursor( QTextEdit::MoveEnd, false );
- }
- break;
- }
- case Key_Left:
- // <Left> arrow key: process as follows:
- // - without <Ctrl>, <Shift> modifiers: move one symbol left (taking into account prompt)
- // - with <Ctrl> modifier key pressed: move one word left (taking into account prompt)
- // - with <Shift> modifier key pressed: move one symbol left with selection
- // - with <Ctrl>+<Shift> modifier keys pressed: move one word left with selection
- {
- if ( !shftPressed && isCommand( text( curLine ) ) && curCol <= PROMPT_SIZE ) {
- setCursorPosition( curLine-1, 0 );
- moveCursor( QTextEdit::MoveLineEnd, false );
- }
- else {
- QTextEdit::keyPressEvent( e );
- }
- break;
- }
- case Key_Right:
- // <Right> arrow key: process as follows:
- // - without <Ctrl>, <Shift> modifiers: move one symbol right (taking into account prompt)
- // - with <Ctrl> modifier key pressed: move one word right (taking into account prompt)
- // - with <Shift> modifier key pressed: move one symbol right with selection
- // - with <Ctrl>+<Shift> modifier keys pressed: move one word right with selection
- {
- if ( !shftPressed ) {
- if ( curCol < paragraphLength( curLine ) ) {
- if ( isCommand( text( curLine ) ) && curCol < PROMPT_SIZE ) {
- setCursorPosition( curLine, PROMPT_SIZE );
- break;
- }
- }
- else {
- if ( curLine < endLine && isCommand( text( curLine+1 ) ) ) {
- setCursorPosition( curLine+1, PROMPT_SIZE );
- break;
- }
- }
- }
- QTextEdit::keyPressEvent( e );
- break;
- }
- case Key_PageUp:
- // <PageUp> key: process as follows:
- // - without <Ctrl>, <Shift> modifiers: first command in history
- // - with <Ctrl> modifier key pressed: move cursor one page up without selection
- // - with <Shift> modifier key pressed: move cursor one page up with selection
- // - with <Ctrl>+<Shift> modifier keys pressed: scroll one page up
- {
- if ( ctrlPressed && shftPressed ) {
- scrollBy( 0, -visibleHeight() );
- }
- else if ( shftPressed ) {
- if ( curLine > 0 )
- moveCursor( QTextEdit::MovePgUp, true );
- }
- else if ( ctrlPressed ) {
- moveCursor( QTextEdit::MovePgUp, false );
- }
- else {
- QString histLine = _currentPrompt;
- if ( ! _isInHistory ) {
- _isInHistory = true;
- _currentCommand = text( endLine ).remove( 0, PROMPT_SIZE );
- _currentCommand.truncate( _currentCommand.length() - 1 );
- }
- QString firstCommand = myInterp->getPrevious();
- QString pcmd;
- while ( ( pcmd = QString( myInterp->getPrevious() ) ).compare( BEGIN_HISTORY_PY ) != 0 )
- firstCommand = pcmd;
- if ( firstCommand.compare( BEGIN_HISTORY_PY ) != 0 ) {
- removeParagraph( endLine );
- histLine.append( firstCommand );
- insertParagraph( histLine, -1 );
- }
- moveCursor( QTextEdit::MoveEnd, false );
- }
- break;
- }
- case Key_PageDown:
- // <PageDown> key: process as follows:
- // - without <Ctrl>, <Shift> modifiers: last command in history
- // - with <Ctrl> modifier key pressed: move cursor one page down without selection
- // - with <Shift> modifier key pressed: move cursor one page down with selection
- // - with <Ctrl>+<Shift> modifier keys pressed: scroll one page down
- {
- if ( ctrlPressed && shftPressed ) {
- scrollBy( 0, visibleHeight() );
- }
- else if ( shftPressed ) {
- if ( curLine < endLine )
- moveCursor( QTextEdit::MovePgDown, true );
- }
- else if ( ctrlPressed ) {
- moveCursor( QTextEdit::MovePgDown, false );
- }
- else {
- if ( _isInHistory ) {
- QString histLine = _currentPrompt;
- while ( QString( myInterp->getNext() ).compare( TOP_HISTORY_PY ) != 0 );
- _isInHistory = false;
- removeParagraph( endLine );
- histLine.append( _currentCommand );
- insertParagraph( histLine, -1 );
- }
- moveCursor( QTextEdit::MoveEnd, false );
- }
- break;
- }
- case Key_Home:
- // <Home> key: process as follows:
- // - without <Ctrl>, <Shift> modifiers: move cursor to the beginning of the current line without selection
- // - with <Ctrl> modifier key pressed: move cursor to the very first symbol without selection
- // - with <Shift> modifier key pressed: move cursor to the beginning of the current line with selection
- // - with <Ctrl>+<Shift> modifier keys pressed: move cursor to the very first symbol with selection
- {
- if ( ctrlPressed ) {
- moveCursor( QTextEdit::MoveHome, shftPressed );
- }
- else {
- if ( isCommand( text( curLine ) ) ) {
- int ps1, ps2, cs1, cs2;
- bool hasSelection = hasSelectedText();
- if ( hasSelection )
- getSelection( &ps1, &cs1, &ps2, &cs2 );
- removeSelection();
- horizontalScrollBar()->setValue( horizontalScrollBar()->minValue() );
- if ( curCol > PROMPT_SIZE && shftPressed )
- setSelection( curLine, PROMPT_SIZE, curLine, ( hasSelection && ps1 == ps2 && ps1 == curLine && cs2 > PROMPT_SIZE ) ? cs2 : curCol );
- setCursorPosition( curLine, PROMPT_SIZE );
- }
- else {
- moveCursor( QTextEdit::MoveLineStart, shftPressed );
- }
- }
- break;
- }
- case Key_End:
- // <End> key: process as follows:
- // - without <Ctrl>, <Shift> modifiers: move cursor to the end of the current line without selection
- // - with <Ctrl> modifier key pressed: move cursor to the very last symbol without selection
- // - with <Shift> modifier key pressed: move cursor to the end of the current line with selection
- // - with <Ctrl>+<Shift> modifier keys pressed: move cursor to the very last symbol with selection
- {
- if ( ctrlPressed ) {
- moveCursor( QTextEdit::MoveEnd, shftPressed );
- }
- else {
- moveCursor( QTextEdit::MoveLineEnd, shftPressed );
- }
- break;
- }
- case Key_Backspace :
- // <Backspace> key: process as follows
- // - without any modifiers : delete symbol before the cursor / selection (taking into account prompt)
- // - with <Ctrl> modifier key pressed: delete previous word
- // works only for last (command) line
- {
- if ( curLine == endLine && ( curCol > PROMPT_SIZE || curCol >= PROMPT_SIZE && hasSelectedText() ) ) {
- if ( ctrlPressed && !hasSelectedText() ) {
- QString txt = text( curLine );
- int ind = curCol-1;
- while ( ind > 0 && txt[ ind ] == ' ' ) ind--;
- ind = txt.findRev( ' ', ind ) + 1;
- if ( ind > PROMPT_SIZE-1 ) {
- setSelection( curLine, ind, curLine, curCol );
- removeSelectedText();
- }
- else {
- QTextEdit::keyPressEvent( e );
- }
- }
- else {
- QTextEdit::keyPressEvent( e );
- }
- }
- break;
- }
- case Key_Delete :
- // <Delete> key: process as follows
- // - without any modifiers : delete symbol after the cursor / selection (taking into account prompt)
- // - with <Ctrl> modifier key pressed: delete next word
- // works only for last (command) line
- {
- if ( curLine == endLine && curCol > PROMPT_SIZE-1 ) {
- if ( ctrlPressed && !hasSelectedText() ) {
- QString txt = text( curLine );
- int ind = curCol;
- while ( ind < (int)( txt.length() - 1 ) && txt[ind] == ' ' ) ind++;
- ind = txt.find( ' ', ind );
- while ( ind < (int)( txt.length() - 1 ) && txt[ ind ] == ' ' ) ind++;
- if ( ind > PROMPT_SIZE-1 ) {
- setSelection( curLine, curCol, curLine, ind );
- removeSelectedText();
- }
- else {
- QTextEdit::keyPressEvent( e );
- }
- }
- else {
- QTextEdit::keyPressEvent( e );
- }
- }
- break;
- }
- case Key_Insert :
- // <Insert> key: process as follows
- // - with <Ctrl> modifier key pressed: copy()
- // - with <Shift> modifier key pressed: paste() to the command line
- {
- if ( ctrlPressed ) {
- copy();
- }
- else if ( shftPressed ) {
- if ( curLine != endLine || curCol < PROMPT_SIZE )
- moveCursor( QTextEdit::MoveEnd, false );
- paste();
- }
- else
- QTextEdit::keyPressEvent( e );
- break;
- }
- }
-}
-
-/*!
- Handles notifications coming from Python dispatcher
-*/
-void PythonConsole_PyEditor::customEvent(QCustomEvent* e)
-{
- switch( e->type() ) {
- case PyInterp_Event::OK:
- case PyInterp_Event::ERROR:
- {
- PyInterp_Event* pe = dynamic_cast<PyInterp_Event*>( e );
- if ( pe ){
- ExecCommand* ec = dynamic_cast<ExecCommand*>( pe->GetRequest() );
- if ( ec ){
- // The next line has appeared dangerous in case if
- // Python command execution has produced very large output.
- // A more clever approach is needed...
- setText(ec->myOutput);
- setText(ec->myError);
- }
- }
- _buf.truncate(0);
- _currentPrompt = READY_PROMPT;
- setText(_currentPrompt);
- viewport()->unsetCursor();
- if( myIsInLoop )
- qApp->exit_loop();
- break;
- }
- case PyInterp_Event::INCOMPLETE:
- {
- _buf.append("\n");
- _currentPrompt = DOTS_PROMPT;
- setText(_currentPrompt);
- viewport()->unsetCursor();
- if( myIsInLoop )
- qApp->exit_loop();
- break;
- }
- default:
- QTextEdit::customEvent( e );
- }
-
- setReadOnly( false );
- _isInHistory = false;
-
- if ( e->type() == PyInterp_Event::OK && myQueue.count() > 0 ) {
- QString nextcmd = myQueue[0];
- myQueue.pop_front();
- exec( nextcmd );
- }
-}
-
-/*!
- Handles Python interpreter change
-*/
-void PythonConsole_PyEditor::onPyInterpChanged( PyInterp_base* interp )
-{
- if ( myInterp != interp
- // Force read-only state and wait cursor when myInterp is NULL
- || !myInterp ){
- myInterp = interp;
- if ( myInterp ){
- myBanner = myInterp->getbanner().c_str();
- setText(myBanner);
- _buf.truncate(0);
- setReadOnly( false );
- _isInHistory = false;
- setText(_currentPrompt);
- viewport()->unsetCursor();
- if( myIsInLoop )
- qApp->exit_loop();
- }
- else {
- clear();
- setReadOnly( true );
- viewport()->setCursor( waitCursor );
- }
- }
-}
-
-/*!
- Creates popup menu
-*/
-QPopupMenu* PythonConsole_PyEditor::createPopupMenu( const QPoint& pos )
-{
- QPopupMenu* popup = QTextEdit::createPopupMenu( pos );
-
- QValueList<int> ids;
- for ( int i = 0; popup && i < (int)popup->count(); i++ )
- {
- if ( !popup->isItemEnabled( popup->idAt( i ) ) )
- ids.append( popup->idAt( i ) );
- }
-
- for ( QValueList<int>::const_iterator it = ids.begin(); it != ids.end(); ++it )
- popup->removeItem( *it );
-
- SUIT_Tools::simplifySeparators( popup );
-
- if ( !popup->count() )
- {
- delete popup;
- popup = 0;
- }
-
- return popup;
-}
+++ /dev/null
-// SALOME SALOMEGUI : implementation of desktop and GUI kernel
-//
-// Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-//
-//
-// File : PythonConsole_PyEditor.h
-// Author : Nicolas REJNERI
-// Module : SALOME
-
-#ifndef PythonConsole_PyEditor_H
-#define PythonConsole_PyEditor_H
-
-#include "PythonConsole_PyInterp.h" // this include must be first (see PyInterp_base.h)!
-
-#include <qevent.h>
-#include <qtextedit.h>
-
-class PythonConsole_PyInterp;
-
-class PYCONSOLE_EXPORT PythonConsole_PyEditor : public QTextEdit
-{
- Q_OBJECT;
-
-public:
- PythonConsole_PyEditor(PyInterp_base* theInterp, QWidget *theParent = 0, const char* theName = "");
- ~PythonConsole_PyEditor();
-
- virtual void setText(QString s);
- bool isCommand(const QString& str) const;
-
- virtual void exec( const QString& command );
- void execAndWait( const QString& command );
-
-protected:
- virtual void contentsDropEvent( QDropEvent* event );
- virtual void contentsMouseReleaseEvent( QMouseEvent* event );
- virtual void keyPressEvent (QKeyEvent* event);
- virtual void mousePressEvent (QMouseEvent* event);
- virtual void customEvent (QCustomEvent* event);
-
-public slots:
- void handleReturn();
- void onPyInterpChanged( PyInterp_base* );
-
- virtual QPopupMenu* createPopupMenu( const QPoint& );
-
-private:
- QString _buf;
- QString _currentCommand;
- QString _currentPrompt;
- bool _isInHistory, myIsInLoop;
-
- PyInterp_base* myInterp;
-
- QString myBanner;
- QString myOutput;
- QString myError;
- QStringList myQueue;
-};
-
-#endif
+++ /dev/null
-// SALOME SALOMEGUI : implementation of desktop and GUI kernel
-//
-// Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-//
-//
-// File : PythonConsole_PyInterp.cxx
-// Author : Nicolas REJNERI
-// Module : SALOME
-// $Header$
-
-#include "PythonConsole_PyInterp.h"
-//#include "utilities.h"
-
-using namespace std;
-
-
-//#ifdef _DEBUG_
-//static int MYDEBUG = 0;
-//#else
-//static int MYDEBUG = 0;
-//#endif
-
-
-/*!
- * constructor : multi Python interpreter, one per SALOME study.
- * calls initialize method defined in base class, which calls virtual methods
- * initstate & initcontext redefined here.
- */
-PythonConsole_PyInterp::PythonConsole_PyInterp(): PyInterp_base()
-{
-}
-
-/*!
- Destructor
-*/
-PythonConsole_PyInterp::~PythonConsole_PyInterp()
-{
-}
-
-/*!
- * EDF-CCAR
- * When SALOME uses multi Python interpreter feature,
- * Every study has its own interpreter and thread state (_tstate = Py_NewInterpreter())
- * This is fine because every study has its own modules (sys.modules) stdout and stderr
- * BUT some Python modules must be imported only once. In multi interpreter context Python
- * modules (*.py) are imported several times.
- * The pyqt module must be imported only once because it registers classes in a C module.
- * It's quite the same with omniorb modules (internals and generated with omniidl)
- * This problem is handled with "shared modules" defined in salome_shared_modules.py
- * These "shared modules" are imported only once and only copied in all the other interpreters
- * BUT it's not the only problem. Every interpreter has its own __builtin__ module. That's fine
- * but if we have copied some modules and imported others problems may arise with operations that
- * are not allowed in restricted execution environment. So we must impose that all interpreters
- * have identical __builtin__ module.
- * That's all, for the moment ...
- */
-
-bool PythonConsole_PyInterp::initState()
-{
- /*
- * The GIL is acquired and will be held on initState output
- * It is the caller responsability to release the lock if needed
- */
- PyEval_AcquireLock();
-#ifdef WNT
- _tstate = PyGILState_GetThisThreadState();
- // if no thread state defined
- if ( _tstate )
- PyThreadState_Swap(_tstate);
- else
-#endif
- {
- _tstate = Py_NewInterpreter(); // create an interpreter and save current state
- PySys_SetArgv(PyInterp_base::_argc,PyInterp_base::_argv); // initialize sys.argv
- //if(MYDEBUG) MESSAGE("PythonConsole_PyInterp::initState - this = "<<this<<"; _tstate = "<<_tstate);
- }
-
- /*
- * If builtinmodule has been initialized all the sub interpreters
- * will have the same __builtin__ module
- */
-
- if(builtinmodule)
- {
- PyObject *m = PyImport_GetModuleDict();
- PyDict_SetItemString(m, "__builtin__", builtinmodule);
-// SCRUTE(builtinmodule->ob_refcnt); // builtinmodule reference counter
- _tstate->interp->builtins = PyModule_GetDict(builtinmodule);
- Py_INCREF(_tstate->interp->builtins);
- }
- PyEval_ReleaseThread(_tstate);
- return true;
-}
-
-/*!
- The GIL is assumed to be held
- It is the caller responsability caller to acquire the GIL
- It will still be held on initContext output
-*/
-bool PythonConsole_PyInterp::initContext()
-{
- PyObject *m = PyImport_AddModule("__main__"); // interpreter main module (module context)
- if(!m){
-// if(MYDEBUG) MESSAGE("problem...");
- PyErr_Print();
-// ASSERT(0);
- return false;
- }
- _g = PyModule_GetDict(m); // get interpreter dictionnary context
-// if(MYDEBUG) MESSAGE("PythonConsole_PyInterp::initContext - this = "<<this<<"; _g = "<<_g);
-
- if(builtinmodule){
- PyDict_SetItemString(_g, "__builtins__", builtinmodule); // assign singleton __builtin__ module
- }
- return true;
-}
+++ /dev/null
-// SALOME SALOMEGUI : implementation of desktop and GUI kernel
-//
-// Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-//
-//
-// File : PythonConsole_PyInterp.h
-// Author : Nicolas REJNERI
-// Module : SALOME
-// $Header$
-
-#ifndef _PythonConsole_PYINTERP_H_
-#define _PythonConsole_PYINTERP_H_
-
-#include "PythonConsole.h"
-
-#include <PyInterp_base.h> // this include must be first (see PyInterp_base.h)!
-
-class PYCONSOLE_EXPORT PythonConsole_PyInterp : public PyInterp_base
-{
-public:
- PythonConsole_PyInterp();
- ~PythonConsole_PyInterp();
-
-protected:
- virtual bool initState();
- virtual bool initContext();
-};
-
-#endif
lib_LTLIBRARIES = libQDS.la
# header files
-salomeinclude_HEADERS= QDS.h \
- QDS_CheckBox.h \
- QDS_ComboBox.h \
- QDS_Datum.h \
- QDS_LineEdit.h \
- QDS_SpinBox.h \
- QDS_SpinBoxDbl.h \
- QDS_TextEdit.h \
- QDS_Validator.h
-dist_libQDS_la_SOURCES= \
- QDS.cxx \
- QDS_CheckBox.cxx \
- QDS_ComboBox.cxx \
- QDS_Datum.cxx \
- QDS_LineEdit.cxx \
- QDS_SpinBox.cxx \
- QDS_SpinBoxDbl.cxx \
- QDS_TextEdit.cxx \
- QDS_Validator.cxx
-
+#MKR: already migrated to Qt4 files
+salomeinclude_HEADERS= \
+ QDS.h \
+ QDS_CheckBox.h \
+ QDS_ComboBox.h \
+ QDS_Datum.h \
+ QDS_LineEdit.h \
+ QDS_SpinBox.h \
+ QDS_SpinBoxDbl.h \
+ QDS_TextEdit.h \
+ QDS_Validator.h \
+ QDS_RadioBox.h
+
+#MKR: not yet migrated to Qt4 files
+# \
+ QDS_Table.h
+
+#MKR: already migrated to Qt4 files
+dist_libQDS_la_SOURCES= \
+ QDS.cxx \
+ QDS_CheckBox.cxx \
+ QDS_ComboBox.cxx \
+ QDS_Datum.cxx \
+ QDS_LineEdit.cxx \
+ QDS_SpinBox.cxx \
+ QDS_SpinBoxDbl.cxx \
+ QDS_TextEdit.cxx \
+ QDS_Validator.cxx \
+ QDS_RadioBox.cxx
+
+#MKR: not yet migrated to Qt4 files
+# \
+ QDS_Table.cxx
+
+#MKR: already migrated to Qt4 files
MOC_FILES= \
QDS_CheckBox_moc.cxx \
QDS_ComboBox_moc.cxx \
QDS_LineEdit_moc.cxx \
QDS_SpinBox_moc.cxx \
QDS_SpinBoxDbl_moc.cxx \
- QDS_TextEdit_moc.cxx
+ QDS_TextEdit_moc.cxx \
+ QDS_RadioBox_moc.cxx
+
+#MKR: not yet migrated to Qt4 files
+# \
+ QDS_Table_moc.cxx
+
nodist_libQDS_la_SOURCES= $(MOC_FILES)
# may be neccessary for the external projects or future improvements
#include "QDS_Datum.h"
-#include <qtextcodec.h>
+#include <QTextCodec>
#include <DDS_DicItem.h>
#include <DDS_Dictionary.h>
#include <TCollection_HAsciiString.hxx>
#include <TCollection_HExtendedString.hxx>
-QValueList<QDS_Datum*> QDS::_datumList;
+QList<QDS_Datum*> QDS::_datumList;
/*!
- Convert the OpenCascade ascii string to Qt string.
+ \class QDS
+ \brief A set of usefull static functions.
+*/
+
+/*!
+ \brief Convert the OpenCascade ASCII string to Qt string.
+ \param src OCC ASCII string
+ \return Qt string
*/
QString QDS::toQString( const TCollection_AsciiString& src )
{
}
/*!
- Convert the OpenCascade unicode string to Qt string.
+ \brief Convert the OpenCascade Unicode string to Qt string.
+ \param src OCC Unicode string
+ \return Qt string
*/
QString QDS::toQString( const TCollection_ExtendedString& src )
{
}
/*!
- Convert the OpenCascade ascii string to Qt string.
+ \brief Convert the OpenCascade ASCII string to Qt string.
+ \param src handle to OCC ASCII string
+ \return Qt string
*/
QString QDS::toQString( const Handle(TCollection_HAsciiString)& src )
{
}
/*!
- Convert the OpenCascade unicode string to Qt string.
+ \brief Convert the OpenCascade Unicode string to Qt string.
+ \param src handle to OCC Unicode string
+ \return Qt string
*/
QString QDS::toQString( const Handle(TCollection_HExtendedString)& src )
{
}
/*!
- Convert the Qt string to OpenCascade ascii string.
+ \brief Convert the Qt string to OpenCascade ASCII string.
+ \param src Qt string
+ \return OCC ASCII string
*/
TCollection_AsciiString QDS::toAsciiString( const QString& src )
{
TCollection_AsciiString res;
- if ( src.latin1() )
+ if ( src.toLatin1().constData() )
{
QTextCodec* codec = QTextCodec::codecForLocale();
if ( codec )
{
- int len = -1;
- QCString str = codec->fromUnicode( src, len );
- res = TCollection_AsciiString( (Standard_CString)(const char*)str, len );
+ QByteArray str = codec->fromUnicode( src );
+ res = TCollection_AsciiString( (Standard_CString)(const char*)str, str.size() );
}
else
- res = TCollection_AsciiString( (char*)src.latin1() );
+ res = TCollection_AsciiString( (char*)src.toLatin1().constData() );
}
return res;
}
/*!
- Convert the OpenCascade unicode string to OpenCascade ascii string.
+ \brief Convert the OpenCascade Unicode string to OpenCascade ASCII string.
+ \param src OCC Unicode string
+ \return OCC ASCII string
*/
TCollection_AsciiString QDS::toAsciiString( const TCollection_ExtendedString& src )
{
}
/*!
- Convert the OpenCascade unicode string to OpenCascade ascii string.
+ \brief Convert the OpenCascade Unicode string to OpenCascade ASCII string.
+ \param src handle to OCC Unicode string
+ \return OCC ASCII string
*/
TCollection_AsciiString QDS::toAsciiString( const Handle(TCollection_HExtendedString)& src )
{
}
/*!
- Convert the Qt string to OpenCascade unicode string.
+ \brief Convert the Qt string to OpenCascade Unicode string.
+ \param src Qt string
+ \return OCC Unicode string
*/
TCollection_ExtendedString QDS::toExtString( const QString& src )
{
}
/*!
- Convert the OpenCascade ascii string to OpenCascade unicode string.
+ \brief Convert the OpenCascade ASCII string to OpenCascade Unicode string.
+ \param src OCC ASCII string
+ \return OCC Unicode string
*/
TCollection_ExtendedString QDS::toExtString( const TCollection_AsciiString& src )
{
}
/*!
- Load datum definitions in the dictionary from XML file \adictPath.
- Returns true if load successed or false otherwise.
+ \brief Load datum definitions from XML file \a dictPath to the dictionary.
+ \return \c true if loading is successed or \c false otherwise.
*/
bool QDS::load( const QString& dictPath )
{
}
/*!
- Returns the label of unit system \asys. If component \acomp specified and not empty then
- function find the given unit system in the given component otherwise all components will be searched.
- If unit system not found then empty string returned.
+ \brief Get the label of unit system \a sys.
+
+ If component \a comp is specified and not empty then the function
+ searches the given unit system in the specified component, otherwise
+ all components will be searched.
+
+ \param sys unit system
+ \param comp component
+ \return unit system lavel or empty string if unit system is not found
*/
QString QDS::unitSystemLabel( const QString& sys, const QString& comp )
{
}
/*!
- Gets the name of active unit system from the specified component \acomp.
- If component not specified or component is empty string then first got component will be used.
- If component exist then active unit system name returned or empty string otherwise.
+ \brief Get the name of active unit system from the specified component \a comp.
+
+ If component is not specified or empty string, then the first found
+ component will be used.
+
+ If component exists, then active unit system name is returned. Otherwise,
+ empty string is returned.
+
+ \param comp component
+ \return name of the active unit system
*/
QString QDS::activeUnitSystem( const QString& comp )
{
}
/*!
- Sets the active unit system named \asys. If not empty component name \acomp specified then
- unit system will be activated in the given component otherwise all components will be processed.
+ \brief Set the active unit system.
- After the changing of active unit system function notify about it to all registered datums
- from processed components using method QDS_Datum::unitSystemChanged();
+ If not empty component name \a comp is specified, then the unit system
+ will be activated in the given component, otherwise all components
+ will be processed.
+
+ After the changing of active unit system function notifies about it all
+ registered datums from processed components using method
+ QDS_Datum::unitSystemChanged()
+
+ \param unit system to be set active
+ \param comp component
*/
void QDS::setActiveUnitSystem( const QString& sys, const QString& comp )
{
return;
TCollection_AsciiString aComp = toAsciiString( comp );
- for ( QValueList<QDS_Datum*>::iterator it = _datumList.begin(); it != _datumList.end(); ++it )
+ for ( QList<QDS_Datum*>::iterator it = _datumList.begin(); it != _datumList.end(); ++it )
{
QDS_Datum* datum = *it;
if ( !datum )
}
/*!
- Register given datum \adatum in the static list.
- This function invoked by QDS_Datum constructor.
+ \brief Register given datum \a datum in the global list.
+
+ This function is invoked automatically by QDS_Datum constructor.
+
+ \param datum datum being registered
*/
void QDS::insertDatum( QDS_Datum* datum )
{
}
/*!
- Remove given datum \adatum from the static list.
- This function invoked by QDS_Datum destructor.
+ \brief Remove given datum \a datum from the global list.
+
+ This function is invoked automatically by QDS_Datum destructor.
+
+ \param datum datum being unregistered
*/
void QDS::removeDatum( QDS_Datum* datum )
{
if ( !datum )
return;
- _datumList.remove( datum );
+ _datumList.removeAt( _datumList.indexOf(datum) );
}
#pragma warning ( disable:4786 )
#endif
-#include <qstring.h>
-#include <qvaluelist.h>
-
-#include <TCollection_AsciiString.hxx>
+#include <QString>
+#include <QList>
#include <TCollection_ExtendedString.hxx>
class QDS_EXPORT QDS
{
public:
- /*! Enum describes bit flags of the Qt datum view and behaviour */
+ //! Enum describes bit flags of the Qt datum view and behaviour
typedef enum
{
None = 0x00, //!< Non specified any flags (Default behaviour)
static void removeDatum( QDS_Datum* );
private:
- static QValueList<QDS_Datum*> _datumList;
+ static QList<QDS_Datum*> _datumList;
};
#endif
--- /dev/null
+TEMPLATE = lib
+TARGET = QDS
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+CASROOT = $$(CASROOT)
+CAS_CPPFLAGS = $${CASROOT}/inc
+
+CAS_KERNEL = -L$${CASROOT}/Linux/lib -lTKernel
+
+INCLUDEPATH += ../../include $${CAS_CPPFLAGS} ../Qtx ../DDS
+LIBS += -L../../lib -lqtx -lDDS $${CAS_KERNEL}
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += QDS_EXPORTS OCC_VERSION_MAJOR=6 OCC_VERSION_MINOR=1 OCC_VERSION_MAINTENANCE=1 LIN LINTEL CSFDB No_exception HAVE_CONFIG_H HAVE_LIMITS_H HAVE_WOK_CONFIG_H OCC_CONVERT_SIGNALS
+
+HEADERS = QDS.h
+HEADERS += QDS_CheckBox.h
+HEADERS += QDS_ComboBox.h
+HEADERS += QDS_Datum.h
+HEADERS += QDS_LineEdit.h
+HEADERS += QDS_SpinBox.h
+HEADERS += QDS_SpinBoxDbl.h
+HEADERS += QDS_TextEdit.h
+HEADERS += QDS_Validator.h
+HEADERS += QDS_RadioBox.h
+#HEADERS += QDS_Table.h
+
+SOURCES = QDS.cxx
+SOURCES += QDS_CheckBox.cxx
+SOURCES += QDS_ComboBox.cxx
+SOURCES += QDS_Datum.cxx
+SOURCES += QDS_LineEdit.cxx
+SOURCES += QDS_SpinBox.cxx
+SOURCES += QDS_SpinBoxDbl.cxx
+SOURCES += QDS_TextEdit.cxx
+SOURCES += QDS_Validator.cxx
+SOURCES += QDS_RadioBox.cxx
+#SOURCES += QDS_Table.cxx
+
+TRANSLATIONS = resources/QDS_msg_en.ts
+
+ICONS = resources/*.png
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+resources.files = $$ICONS resources/*.qm
+resources.path = ../../resources
+
+INSTALLS += includes resources
//
#include "QDS_CheckBox.h"
-#include <qcheckbox.h>
+#include <QCheckBox>
/*
\class QDS_CheckBox
-
- Datum with control corresponding to check box. This control can have only two states:
- 1 (on/true) or 0 (off/false). QDS_CheckBox don't take into account standard parameter
- properties (minimum, maximum, filter, etc).
+ \brief Datum with control corresponding to check box.
+
+ This control can have only two states:
+ - 1 (on/true)
+ - 0 (off/false).
+
+ QDS_CheckBox don't take into account standard parameter properties
+ (minimum, maximum, filter, etc).
QDS_CheckBox can set and get following values for access methods (setStringValue(),
setIntegerValue(), setDoubleValue(), stringValue(), integerValue(), doubleValue()):
- \li "1" - check box state is setted as on.
- \li "0" - check box state is setted as off.
- \li "-1" - check box state is setted as "NoChage" (undefined).
+ - "1" - check box state is switched on.
+ - "0" - check box state is switched off.
+ - "-1" - check box state is "PartiallyChecked" (undefined).
- User can set and check a state "NoChange" using methods clear() and isEmpty() accordingly.
+ User can set and test "PartiallyChecked" check using methods clear()
+ and isEmpty() correspondingly.
*/
/*!
- Constructor. Create check box datum object with datum identifier \aid under widget \aparent.
- Parameter \aflags define behaviour of datum and set of created subwidgets. Default value of
- this parameter is QDS::All. Parameter \acomp specify the component name which will be used
- during search of dictionary item.
+ \brief Constructor.
+
+ Create check box datum object with datum identifier \a id
+ and parent widget \a parent.
+
+ Parameter \a flags defines behaviour of datum and set of created
+ subwidgets. Default value of this parameter is QDS::All.
+
+ Parameter \a comp specifies the component name which will be used
+ when searching the dictionary item.
+
+ \param id datum identifier
+ \param parent parent widget
+ \param flags datum flags
+ \param comp component
*/
QDS_CheckBox::QDS_CheckBox( const QString& id, QWidget* parent, const int flags, const QString& comp )
: QDS_Datum( id, parent, flags, comp )
}
/*!
- Destructor.
+ \brief Destructor.
*/
QDS_CheckBox::~QDS_CheckBox()
{
}
/*!
- Sets the state "NoChange" for checkbox.
+ \brief Set the state "PartiallyChecked" (undefined) for checkbox.
*/
void QDS_CheckBox::clear()
{
}
/*!
- Returns string from QCheckBox widget. If the check box state is on then 1 returned otherwise 0.
+ \brief Get string value from the widget.
+ \return "1" if check box is checked on and "0" otherwise
*/
QString QDS_CheckBox::getString() const
{
QString val;
- if ( checkBox() && checkBox()->state() != QButton::NoChange )
+ if ( checkBox() && checkBox()->checkState() != Qt::PartiallyChecked )
val = checkBox()->isChecked() ? "1" : "0";
return val;
}
/*!
- Sets the string into QCheckBox widget. If argument \atxt is string with number "1" then check box
- state is setted as on. If argument \atxt is string with number "0" then state is setted as off.
- If argument \atxt is string with number "-1" then state is setted as "NoChage" (undefined).
+ \brief Set the string value into the widget.
+
+ If string \a txt contains "1", then check box state is switched on.
+ If string \a txt contains "0", then check box state is switched on.
+ If string \a txt contains "-1", then check box is reset to
+ "PartiallyChecked" (undefined) state.
+
+ \param txt string value
*/
void QDS_CheckBox::setString( const QString& txt )
{
if ( isOk && val < 0 )
{
checkBox()->setTristate();
- checkBox()->setNoChange();
+ checkBox()->setCheckState(Qt::PartiallyChecked);
}
else
checkBox()->setChecked( isOk && val != 0 );
}
/*!
- Returns pointer to QCheckBox widget.
+ \brief Get internal check box.
+ \return pointer to QCheckBox widget
*/
QCheckBox* QDS_CheckBox::checkBox() const
{
- return ::qt_cast<QCheckBox*>( controlWidget() );
+ return ::qobject_cast<QCheckBox*>( controlWidget() );
}
/*!
- Create QCheckBox widget as control subwidget.
+ \brief Create internal check box as control widget.
+ \param parent parent widget
+ \return created check box widget
*/
QWidget* QDS_CheckBox::createControl( QWidget* parent )
{
}
/*!
- Notify about ñhanging of control state
+ \brief Called when check box is switched.
+
+ Emits signal paramChanged() to notify about changing of the control state.
*/
void QDS_CheckBox::onParamChanged()
{
}
/*!
- Notify about ñhanging of control state. Switch off check box property "tristate" when
- state changed by user.
+ \brief Called when check box is switched.
+
+ Switch off check box property "tristate" when state is changed by the user.
+
+ \param state new check box state
*/
void QDS_CheckBox::onStateChanged( int state )
{
- if ( state != QButton::NoChange && checkBox() )
+ if ( state != Qt::PartiallyChecked && checkBox() )
checkBox()->setTristate( false );
}
/*!
- Sets the check box state \atheState.
+ \brief Set the check box state to \a theState.
+ \param theState new check box state
*/
void QDS_CheckBox::setChecked( const bool theState )
{
}
/*!
- Returns current check box state.
+ \brief Get current check box state.
+ \return check box state
*/
bool QDS_CheckBox::isChecked() const
{
return checkBox() ? checkBox()->isChecked() : false;
}
+
+/*!
+ \fn void QDS_CheckBox::toggled( bool on );
+ \brief Emitted when the check box state is toggled.
+ \param on new check box state
+*/
//
#include "QDS_ComboBox.h"
-#include <DDS_Dictionary.h>
+#include <QtxComboBox.h>
-#include <TCollection_AsciiString.hxx>
#include <TColStd_HArray1OfInteger.hxx>
#include <TColStd_HArray1OfExtendedString.hxx>
-#include <qlineedit.h>
+#include <QLineEdit>
/*
\class QDS_ComboBox
- Datum with control corresponding to combo box. This control used for datum with enumerable values.
- It can be used for datum which has type of value 'List'. Each item of combobox defined two properties:
- integer identifier and string name. All operations on items performed via identifier.
+ \brief Datum with control corresponding to the combo box.
+
+ This control is used for datum with enumerable values.
+ It can be used for datum which has type of value 'List'.
+
+ Each item of the combobox is defined by two properties: integer identifier
+ and string name. All operations on items are performed via identifier.
*/
/*!
- Constructor. Create combobox datum object with datum identifier \aid under widget \aparent. Parameter \aflags
- define behaviour of datum and set of created subwidgets. Default value of this parameter is QDS::All.
- Parameter \acomp specify the component name which will be used during search of dictionary item.
+ \brief Constructor.
+
+ Create combobox datum object with datum identifier \a id
+ and parent widget \a parent.
+
+ Parameter \a flags defines behaviour of datum and set of created
+ subwidgets. Default value of this parameter is QDS::All.
+
+ Parameter \a comp specifies the component name which will be used
+ when searching the dictionary item.
+
+ \param id datum identifier
+ \param parent parent widget
+ \param flags datum flags
+ \param comp component
*/
QDS_ComboBox::QDS_ComboBox( const QString& id, QWidget* parent, const int flags, const QString& comp )
: QDS_Datum( id, parent, flags, comp )
}
/*!
- Destructor.
+ \brief Destructor.
*/
QDS_ComboBox::~QDS_ComboBox()
{
}
/*!
- Returns true if ComboBox allow to edit current text.
+ \brief Check if combo box allows text editing.
+ \return \c true if combo box is editable
*/
bool QDS_ComboBox::editable() const
{
}
/*!
- Sets the possibily of current text editing.
+ \brief Enable/disable text editing.
+ \param on if \c true, combo box is made editable
*/
void QDS_ComboBox::setEditable( const bool on )
{
if ( aCombo && aCombo->lineEdit() )
{
aCombo->lineEdit()->setReadOnly( !on );
- aCombo->clearValidator();
+ aCombo->setValidator(0);
if ( on )
aCombo->setValidator( validator() );
}
}
/*!
- Returns number of items in ComboBox. If \atotal is 'false' then only
- visible items are taken into account otherwise all items.
+ \brief Get number of items in the combo box.
+
+ \param total if \c false, only visible items are taken into account,
+ otherwise get total number of items
+ \return number of items
*/
int QDS_ComboBox::count( bool total ) const
{
}
/*!
- Returns list of list item identifiers \aids. If \atotal is 'false' then only visible items
- are taken into account otherwise all items.
+ \brief Get items identifiers.
+
+ \param ids returned list of items IDs
+ \param total if \c false, only visible items are taken into account,
+ otherwise get total number of items
*/
-void QDS_ComboBox::values( QValueList<int>& ids, bool total ) const
+void QDS_ComboBox::values( QList<int>& ids, bool total ) const
{
ids.clear();
for ( QIntList::const_iterator it = myDataIds.begin(); it != myDataIds.end(); ++it )
}
/*!
- Returns the current id as integer. Reimplemented.
+ \brief Get the current item ID as integer value.
+ \return current item ID converted to integer
*/
int QDS_ComboBox::integerValue() const
{
QComboBox* cb = comboBox();
QString cur = getString();
- if ( cb && cb->count() > 0 && cb->currentItem() >= 0 )
- cur = cb->text( cb->currentItem() );
+ if ( cb && cb->count() > 0 && cb->currentIndex() >= 0 )
+ cur = cb->itemText( cb->currentIndex() );
if ( cb && cur == getString() )
- return getId( cb->currentItem() );
+ return getId( cb->currentIndex() );
else
return getId( getString() );
}
/*!
- Returns the current id as double. Reimplemented.
+ \brief Get the current item ID as double value.
+ \return current item ID converted to double
*/
double QDS_ComboBox::doubleValue() const
{
QComboBox* cb = comboBox();
QString cur = getString();
- if ( cb && cb->count() > 0 && cb->currentItem() >= 0 )
- cur = cb->text( cb->currentItem() );
+ if ( cb && cb->count() > 0 && cb->currentIndex() >= 0 )
+ cur = cb->itemText( cb->currentIndex() );
if ( cb && cur == getString() )
- return getId( cb->currentItem() );
+ return getId( cb->currentIndex() );
else
return getId( getString() );
}
/*!
- Set the current item acording to specified id. Reimplemented.
+ \brief Set the current item acording to the specified \a id.
+ \param id item ID
*/
void QDS_ComboBox::setIntegerValue( const int id )
{
}
/*!
- Get the integer part of specified value and use it as new current identifier. Reimplemented.
+ \brief Set the current item acording to the specified \a id.
+ \overload
+
+ Integer part of \a val is used as new current ID.
+
+ \param val item ID
*/
void QDS_ComboBox::setDoubleValue( const double val )
{
}
/*!
- Returns visible state of item specified by \aid.
+ \brief Get visibility state of the item specified by \a id.
+ \param id item ID
+ \return item visibility state
*/
bool QDS_ComboBox::state( const int id ) const
{
}
/*!
- Sets the visible state of item specified by \aid. If \aid is -1 then specified
- state will be set to all items. If \aappend is set then keep status for other items
- otherwise status of other items will be cleared.
+ \brief Set the visibility state of the item specified by \a id.
+
+ If \a id is -1 then specified state will be set to all items.
+
+ If \a append is set to \c true, keep current status for other items,
+ otherwise status of other items is cleared.
+
+ \param on new visibility state
+ \param id item ID
+ \param append if \c true, keep original status for other items
*/
void QDS_ComboBox::setState( const bool on, const int id, const bool append )
{
- QValueList<int> lst;
+ QList<int> lst;
if ( id < 0 )
{
for ( IdStateMap::Iterator it = myState.begin(); it != myState.end(); ++it )
}
/*!
- Sets the visible state of items specified by list of identifiers \aids.
- If \aappend is set then keep status for other items otherwise status of other
- items will be cleared.
+ \brief Set the visibility state of items specified by \a ids.
+
+ If \a append is set to \c true, keep current status for other items,
+ otherwise status of other items is cleared.
+
+ \param on new visibility state
+ \param ids items IDs list
+ \param append if \c true, keep original status for other items
*/
-void QDS_ComboBox::setState( const bool on, const QValueList<int>& ids, const bool append )
+void QDS_ComboBox::setState( const bool on, const QList<int>& ids, const bool append )
{
initDatum();
QMap<int, int> aMap;
for ( uint i = 0; i < ids.count(); i++ )
- aMap.insert( *ids.at( i ), 0 );
+ aMap.insert( ids.at( i ), 0 );
for ( IdStateMap::Iterator it = myState.begin(); it != myState.end(); ++it )
{
if ( aMap.contains( it.key() ) )
{
- if ( it.data() != on )
+ if ( it.value() != on )
{
- it.data() = on;
+ it.value() = on;
changed = true;
}
}
- else if ( !append && it.data() == on )
+ else if ( !append && it.value() == on )
{
- it.data() = !on;
+ it.value() = !on;
changed = true;
}
}
}
/*!
- Sets the custom user items into the combo box. User items like standard dictionary
- list items will be added into the combobox. This functionality allow to user override
+ \brief Set the custom user items into the combo box.
+
+ User items like standard dictionary list items will be added
+ into the combobox. This function allows user to override
items.
+
+ \param ids items IDs
+ \param names items names
*/
-void QDS_ComboBox::setValues( const QValueList<int>& ids, const QStringList& names )
+void QDS_ComboBox::setValues( const QList<int>& ids, const QStringList& names )
{
initDatum();
}
/*!
- This is an overloaded member function, provided for convenience.
- It behaves essentially like the above function. It creates
- QValueList (0, 1, 2 ... ) and call previous method.
+ \brief Set the custom user items into the combo box.
+ \overload
+
+ User items like standard dictionary list items will be added
+ into the combobox. This function allows user to override
+ items.
+
+ Uses (0, 1, 2 ... ) as items IDs.
+
+ \param names items names
*/
void QDS_ComboBox::setValues( const QStringList& names )
{
initDatum();
- QValueList< int > ids;
+ QList< int > ids;
for ( int i = 0, n = names.count(); i < n; i++ )
ids.append( i );
setValues( ids, names );
}
/*!
- Sets the active item as item with default id. If default
- not defined then first item will be used.
+ \brief Reset the datum.
+
+ Set the active item as item with default ID. If default ID is not defined
+ then the first item is used.
*/
void QDS_ComboBox::reset()
{
}
/*!
- Returns identifier from given ComboBox string item.
+ \brief Convert string to integer value.
+ \param str item
+ \return item ID or -1 if not found
*/
int QDS_ComboBox::stringToValue( const QString& str ) const
{
}
/*!
- Returns ComboBox string item from given identifier.
+ \brief Convert integer to string value.
+ \param val item ID
+ \return item value or empty string if \c val is invalid
*/
QString QDS_ComboBox::valueToString( const int val ) const
{
}
/*!
- Returns string from QComboBox widget. Reimplemented.
+ \brief Get string from the combo box.
+ \return string value
*/
QString QDS_ComboBox::getString() const
{
QtxComboBox* cb = comboBox();
if ( cb )
{
- if ( !cb->editable() )
+ if ( !cb->isEditable() )
{
if ( !cb->isCleared() )
res = cb->currentText();
}
/*!
- Sets the string into QComboBox widget. Reimplemented.
+ \brief Set the string value to the combo box widget.
+ \param txt string value
*/
void QDS_ComboBox::setString( const QString& txt )
{
int idx = -1;
for ( int i = 0; i < cb->count() && idx == -1; i++ )
- if ( cb->text( i ) == txt )
+ if ( cb->itemText( i ) == txt )
idx = i;
- int old = cb->currentItem();
+ int old = cb->currentIndex();
if ( idx != -1 )
- cb->setCurrentItem( idx );
+ cb->setCurrentIndex( idx );
else if ( txt.isEmpty() )
{
- if ( !cb->editable() )
- cb->setCurrentText( txt );
+ if ( !cb->isEditable() )
+ cb->setItemText( cb->currentIndex(), txt );
else
cb->lineEdit()->setText( txt );
}
- if ( isClear != txt.isEmpty() || ( !isClear && old != cb->currentItem() ) )
+ if ( isClear != txt.isEmpty() || ( !isClear && old != cb->currentIndex() ) )
{
onParamChanged();
QString str = getString();
}
/*!
- Returns pointer to QtxComboBox widget.
+ \brief Get combo box widget.
+ \return internal combo box widget
*/
QtxComboBox* QDS_ComboBox::comboBox() const
{
- return ::qt_cast<QtxComboBox*>( controlWidget() );
+ return ::qobject_cast<QtxComboBox*>( controlWidget() );
}
/*!
- Create QComboBox widget as control subwidget. Reimplemented.
+ \brief Create internal combo box as control widget.
+ \param parent parent widget
+ \return created combo box widget
*/
QWidget* QDS_ComboBox::createControl( QWidget* parent )
{
}
/*!
- Notification about active unit system changing. Reimplemented from QDS_Datum.
- Update combobox content.
+ \brief Process notification about active units system changing.
+
+ Update combobox contents.
+
+ \param system new active units system
*/
void QDS_ComboBox::unitSystemChanged( const QString& system )
{
}
/*!
- Notify about text changing in line edit of ComboBox.
+ \brief Called when text in the combo box (editable) is modified by the user.
+ \param txt current text in the combo box editor (not used)
*/
-void QDS_ComboBox::onTextChanged( const QString& )
+void QDS_ComboBox::onTextChanged( const QString& /*txt*/ )
{
onParamChanged();
emit paramChanged();
}
/*!
- Notify about activation combobox item.
+ \brief Called when combo box item is activated.
+ \param idx index of teh item being activated
*/
void QDS_ComboBox::onActivated( int idx )
{
if ( comboBox() )
- comboBox()->setCurrentItem( comboBox()->currentItem() );
+ comboBox()->setCurrentIndex( comboBox()->currentIndex() );
int id = getId( idx );
if ( id != -1 )
}
/*!
- Updates ComboBox after have change of visible state or items have been inserted/removed.
+ \brief Update combo box.
*/
void QDS_ComboBox::updateComboBox()
{
{
isClear = cb->isCleared();
- curId = getId( cb->currentItem() );
+ curId = getId( cb->currentIndex() );
cb->clear();
}
if ( cb )
{
if ( myIcons.contains( id ) )
- cb->insertItem( myIcons[id], myValue[id] );
+ cb->insertItem( -1, QIcon(myIcons[id]), myValue[id] );
else
- cb->insertItem( myValue[id] );
+ cb->insertItem( -1, myValue[id] );
}
}
cb->updateGeometry();
if ( isClear )
- cb->setCurrentText( "" );
+ cb->setItemText( cb->currentIndex(), "" );
else
{
if ( getIndex( curId ) != -1 )
- cb->setCurrentItem( getIndex( curId ) );
- if ( curId != getId( cb->currentItem() ) )
- onActivated( cb->currentItem() );
+ cb->setCurrentIndex( getIndex( curId ) );
+ if ( curId != getId( cb->currentIndex() ) )
+ onActivated( cb->currentIndex() );
}
}
}
/*!
- Returns index of ComboBox item according to id.
+ \brief Get index of the combo box item according to its identifier.
+ \param id item ID
+ \return item index or -1 if not found
*/
int QDS_ComboBox::getIndex( const int id ) const
{
}
/*!
- Returns index of ComboBox item according to string.
+ \brief Get index of the combo box item.
+ \param str combo box item
+ \return item index or -1 if not found
*/
int QDS_ComboBox::getIndex( const QString& str ) const
{
if ( cb )
{
for ( int i = 0; i < cb->count() && idx == -1; i++ )
- if ( cb->text( i ) == str )
+ if ( cb->itemText( i ) == str )
idx = i;
}
return idx;
}
/*!
- Returns id according to ComboBox item index.
+ \brief Get item identifier according to the specified index.
+ \param idx item index
+ \return item ID or -1 if index is out of range
*/
int QDS_ComboBox::getId( const int idx ) const
{
int id = -1;
IdIndexMap::ConstIterator it = myIndex.begin();
for (; it != myIndex.end() && id == -1; ++it )
- if ( it.data() == idx )
+ if ( it.value() == idx )
id = it.key();
return id;
}
/*!
- Returns id according to ComboBox item string.
+ \brief Get item identifier.
+ \param str combo box item
+ \return item ID or -1 if not found
*/
int QDS_ComboBox::getId( const QString& str ) const
{
IdValueMap::ConstIterator it = myValue.begin();
for (; it != myValue.end() && id == -1; ++it )
{
- if ( it.data() == str )
+ if ( it.value() == str )
{
if ( state( it.key() ) )
id = it.key();
return id;
}
+
+/*!
+ \fn void QDS_ComboBox::activated( int id );
+ \brief Emitted when the current item in the combo box is changed.
+ \param id current item ID
+*/
+
+/*!
+ \fn void QDS_ComboBox::activated( const QString& txt );
+ \brief Emitted when the current item in the combo box is changed.
+ \param txt current item text
+*/
#include "QDS_Datum.h"
-#include <qmap.h>
-#include <qpixmap.h>
-#include <qstringlist.h>
+#include <QMap>
+#include <QPixmap>
+#include <QStringList>
-#include <QtxComboBox.h>
+#include <Qtx.h>
-#ifdef WNT
+class QtxComboBox;
+
+#ifdef WIN32
#pragma warning( disable:4251 )
#endif
void setEditable( const bool );
int count( bool = false ) const;
- void values( QValueList<int>&, bool = false ) const;
+ void values( QList<int>&, bool = false ) const;
virtual int integerValue() const;
virtual double doubleValue() const;
bool state( const int ) const;
void setState( const bool, const int, const bool = true );
- void setState( const bool, const QValueList<int>&, const bool = true );
- void setValues( const QValueList<int>&, const QStringList& );
+ void setState( const bool, const QList<int>&, const bool = true );
+ void setValues( const QList<int>&, const QStringList& );
void setValues( const QStringList& );
virtual void reset();
QStringList myUserNames;
};
-#ifdef WNT
+#ifdef WIN32
#pragma warning( default:4251 )
#endif
#include <DDS_Dictionary.h>
-#include <qtimer.h>
-#include <qlabel.h>
-#include <qwidget.h>
-#include <qlayout.h>
-#include <qtooltip.h>
-#include <qwhatsthis.h>
-#include <qvalidator.h>
-#include <qmessagebox.h>
+#include <QTimer>
+#include <QLabel>
+#include <QWidget>
+#include <QHBoxLayout>
+#include <QVBoxLayout>
+#include <QGridLayout>
+#include <QMessageBox>
+#include <QEvent>
#include <TColStd_SequenceOfAsciiString.hxx>
/*!
- class: QDS_Datum::Wrapper
- descr: Wrapper widget for sub widgets. [internal]
+ \class QDS_Datum::Wrapper
+ \internal
+ \brief Wrapper for sub widgets.
*/
class QDS_Datum::Wrapper : public QWidget
private:
QWidget* myWid;
+ QHBoxLayout* myBase;
};
+/*!
+ \brief Constructor.
+ \param parent parent widget
+*/
QDS_Datum::Wrapper::Wrapper( QWidget* parent )
: QWidget( parent ),
-myWid( 0 )
+ myWid( 0 )
{
- QHBoxLayout* base = new QHBoxLayout( this );
- base->setAutoAdd( true );
- setFocusPolicy( StrongFocus );
+ //QHBoxLayout* base = new QHBoxLayout( this );
+ //base->setAutoAdd( true );
+ myBase = new QHBoxLayout( this );
+ setFocusPolicy( Qt::StrongFocus );
}
+/*!
+ \brief Destructor.
+*/
QDS_Datum::Wrapper::~Wrapper()
{
}
+/*!
+ \brief Get widget.
+ \return widget
+*/
QWidget* QDS_Datum::Wrapper::widget() const
{
return myWid;
}
+/*!
+ \brief Set widget.
+ \param wid widget
+*/
void QDS_Datum::Wrapper::setWidget( QWidget* wid )
{
if ( myWid == wid )
if ( !myWid )
return;
- if ( myWid->parent() != this )
- myWid->reparent( this, QPoint( 0, 0 ) );
+ if ( myWid->parent() != this ) {
+ myWid->setParent( this );
+ myWid->move( QPoint( 0, 0 ) );
+ myWid->hide();
+ myBase->addWidget( myWid );
+ }
setTabOrder( this, myWid );
setFocusProxy( myWid );
updateGeometry();
}
+/*!
+ \brief Set size policy of the widget.
+ \param sp new size policy
+*/
void QDS_Datum::Wrapper::setSizePolicy( QSizePolicy sp )
{
QWidget::setSizePolicy( sp );
widget()->setSizePolicy( sp );
}
+/*!
+ \brief Set widget geometry.
+ \param x horizontal position
+ \param y vertical position
+ \param w widget width
+ \param h widget height
+*/
void QDS_Datum::Wrapper::setGeometry( int x, int y, int w, int h )
{
QWidget::setGeometry( x, y, w, h );
/*!
\class QDS_Datum
-
- This is a base class for control using the data dictionary. Datum is successor of QObject (not QWidget).
- This object can have three sub widgets named as Label, Control and Units. User can skip creation of
- some of them manipulate by parameter \aflags. Label widget display label of datum, Control widget allow
- to input value, Units widget display units of measure in the active system.
+ \brief Base class for all controls using the data dictionary.
+
+ Datum is successor of QObject (not QWidget). This object can have up to three
+ sub widgets named as QDS::Label, QDS::Control and QDS::Units.
+ User can prevent creation of any of them by setting corresponding subwidgets IDs
+ in the parameter \a flags of the constructor.
+ QDS::Label widget displays label of datum, QDS::Control widget allows
+ entering the value and QDS::Units widget displays measure units in the active
+ units system.
- These widgets constructs under parent of datum. If this parent has layout which can automaticaly add child
- widgets (see QLayout::setAutoAdd()) then these subwidgets will be placed in following order: first widget
- is Label, second - Control, third - Unints. User can add these widgets to layout manually using methods
- QDS_Datum::addTo() or QDS_Datum::widget(). In last case User can retrieve desired widget and place it into
- layout.
+ These widgets are constructed under the parent widget of the datum.
+ The sub widgets are layouted in the parent widget in the following order: first widget
+ is QDS::Label, it is followed by QDS::Control, and in the end is QDS::Units.
+ User can add these widgets to layout manually using method addTo().
+ Method widget() can be used to retrieve desired widget and place it into layout.
- If use QGroupBox as parent widget for datum object then all subwidgets will be arranged automatically by
- group box according to column and orientation properties of QGroupBox.
+ When QGroupBox is used as parent widget for datum object, all subwidgets are
+ arranged automatically by the group box according to the column and orientation
+ properties of the QGroupBox.
- For example:
- QGroupBox* box = new QGroupBox( 3, Qt::Horizontal, "datum box" );
- QDS_Datum* d1 = new QDS_Datum( "datum_1", box, All );
- QDS_Datum* d2 = new QDS_Datum( "datum_2", box, All );
- QDS_Datum* d3 = new QDS_Datum( "datum_3", box, All );
+ Example:
+ \code
+ QGroupBox* box = new QGroupBox( 3, Qt::Horizontal, "datum box" );
+ QDS_Datum* d1 = new QDS_Datum( "datum_1", box, All );
+ QDS_Datum* d2 = new QDS_Datum( "datum_2", box, All );
+ QDS_Datum* d3 = new QDS_Datum( "datum_3", box, All );
+ \endcode
- In this example we create the QGroupBox with 3 horizontal columns. All created datum widgets will be
- placed automatically three widgets in a row. Each datum will be placed from up to bottom one by one.
+ In this example we create the QGroupBox with 3 horizontal columns.
+ All the created datum widgets will be placed automatically in 3 rows.
+ Datums will be placed from top to bottom one by one and aligned in he grid.
- Datum value is stored as string. User can get/set this value in different kinds:
- \liAs string - methods stringValue()/setStringValue().
- \liAs integer - methods integerValue()/setIntegerValue(). Given value converted to/from SI.
- \liAs double - methods doubleValue()/setDoubleValue(). Given value converted to/from SI.
- \liAs variant - methods value()/setValue().
+ Datum value is stored as string. User can get/set this value:
+ - As string : stringValue()/setStringValue().
+ - As integer : integerValue()/setIntegerValue(). Value is converted to/from SI.
+ - As double : doubleValue()/setDoubleValue(). Value is converted to/from SI.
+ - As variant : value()/setValue().
- User can perform some actions on datum subwidgets using following methods: isEnabled(),
- setEnabled(), show(), hide(), setShown(), setFocus(), setAlignment().
+ User can enable/disable datum subwidgets with setEnabled() method, show/hide them
+ with show()/hide() methods, set input focus to datum with setFocus(), set widgets
+ alignment with setAlignment(), etc.
*/
/*!
- Constructor. Create datum object with datum identifier \aid under widget \aparent. Parameter \aflags
- define behaviour of datum and set of created subwidgets. Default value of this parameter is QDS::All.
- Parameter \acomp specify the component name which will be used during search of dictionary item.
+ \brief Constructor.
+
+ Create datum object with datum identifier \a id and parent widget \a parent.
- Datum register self in the static list by QDS::insertDatum().
+ Parameter \a flags defines behaviour of datum and set of created
+ subwidgets. Default value of this parameter is QDS::All.
+
+ Parameter \a comp specifies the component name which will be used
+ when searching the dictionary item.
+
+ Datum is self-registered in the global list by QDS::insertDatum().
+
+ \param id datum identifier
+ \param parent parent widget
+ \param flags datum flags
+ \param comp component
*/
QDS_Datum::QDS_Datum( const QString& id, QWidget* parent, const int flags, const QString& comp )
: QObject( parent ),
-myId( id ),
-myLabel( 0 ),
-myUnits( 0 ),
-myControl( 0 ),
-myFlags( flags ),
-myInitialised( false )
+ myId( id ),
+ myLabel( 0 ),
+ myUnits( 0 ),
+ myControl( 0 ),
+ myFlags( flags ),
+ myInitialised( false )
{
if ( myFlags & Label )
myWrapper.insert( Label, new Wrapper( parent ) );
myWrapper.insert( Units, new Wrapper( parent ) );
for ( QMap<int, Wrapper*>::Iterator it = myWrapper.begin(); it != myWrapper.end(); ++it )
- connect( it.data(), SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
+ connect( it.value(), SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
Handle(DDS_Dictionary) aDict = DDS_Dictionary::Get();
if ( aDict.IsNull() )
}
/*!
- Destructor. Destroy all subwidget.
- Datum unregister self from the static list by QDS::removeDatum().
+ \brief Destructor.
+
+ Destroy all subwidget. Datum is unregistered from the global list
+ by QDS::removeDatum().
*/
QDS_Datum::~QDS_Datum()
{
}
/*!
- Overloaded operator allow to retrieve main subwidget named Control.
+ \brief Overloaded operator used to retrieve main subwidget named QDS::Control.
+ \return QDS::Control subwidget
*/
QDS_Datum::operator QWidget*() const
{
}
/*!
- Returns the datum id.
+ \brief Get the datum ID.
+ \return datum ID
*/
QString QDS_Datum::id() const
{
}
/*!
- Returns the datum type of value.
+ \brief Get the datum value type.
+ \return datum value type
*/
int QDS_Datum::type() const
{
}
/*!
- Returns the datum label string.
+ \brief Get the datum label text.
+ \return label text
*/
QString QDS_Datum::label() const
{
}
/*!
- Returns the datum units string.
+ \brief Get the datum units text.
+ \return units text
*/
QString QDS_Datum::units() const
{
}
/*!
- Returns the datum value filter string.
+ \brief Get the datum filter string.
+ \return filter string
*/
QString QDS_Datum::filter() const
{
}
/*!
- Returns the datum value format string.
+ \brief Get the datum format string
+ \return format string
*/
QString QDS_Datum::format() const
{
}
/*!
- Returns the datum default value string.
+ \brief Get the datum default value
+ \return default value
*/
QString QDS_Datum::defaultValue() const
{
if ( !myDicItem.IsNull() )
def = toQString( myDicItem->GetDefaultValue() );
- QString aDef = def.stripWhiteSpace();
+ QString aDef = def.trimmed();
if ( !pref.isEmpty() && aDef.left( pref.length() ) == pref )
aDef = aDef.mid( pref.length() );
}
/*!
- Returns the datum minimum value string.
+ \brief Get the datum minimum value.
+ \return minimum value
*/
QString QDS_Datum::minimumValue() const
{
}
/*!
- Returns the datum maximum value string.
+ \brief Get the datum maximum value.
+ \return maximum value
*/
QString QDS_Datum::maximumValue() const
{
}
/*!
- Returns the datum long description.
+ \brief Get the datum long description.
+ \return datum long description
*/
QString QDS_Datum::longDescription() const
{
}
/*!
- Returns the datum short description.
+ \brief Get the datum short description.
+ \return datum short description
*/
QString QDS_Datum::shortDescription() const
{
}
/*!
- Returns the list of option names.
+ \brief Get the datum options names.
+ \return datum options
*/
QStringList QDS_Datum::options() const
{
}
/*!
- Returns the option specified by \aname as QVariant.
- If option not exist then not valid QVariant returned.
+ \brief Get datum option specified by \a name as QVariant.
+ \return the option value or invalid QVariant if the option does not exist
*/
QVariant QDS_Datum::option( const QString& name ) const
{
}
/*!
- Returns the option specified by \aname as QString.
- If option not exist then empty string returned.
+ \brief Get datum option specified by \a name as string.
+ \return the option value or null QString if the option does not exist
*/
QString QDS_Datum::optionString( const QString& name ) const
{
}
/*!
- Returns the option specified by \aname as double.
- If option not exist then 0 returned.
+ \brief Get datum option specified by \a name as double.
+ \return the option value or 0 if the option does not exist
*/
double QDS_Datum::optionDouble( const QString& name ) const
{
double res = 0;
QVariant opt = option( name );
- if ( opt.isValid() && opt.canCast( QVariant::Double ) )
+ if ( opt.isValid() && opt.canConvert( QVariant::Double ) )
res = opt.toDouble();
return res;
}
/*!
- Returns the option specified by \aname as integer.
- If option not exist then 0 returned.
+ \brief Get datum option specified by \a name as integer.
+ \return the option value or 0 if the option does not exist
*/
int QDS_Datum::optionInteger( const QString& name ) const
{
int res = 0;
QVariant opt = option( name );
- if ( opt.isValid() && opt.canCast( QVariant::Int ) )
+ if ( opt.isValid() && opt.canConvert( QVariant::Int ) )
res = opt.toInt();
return res;
}
/*!
- Returns the datum value as variant (QVariant object).
+ \brief Get the datum value as QVariant.
+ \return datum value
*/
QVariant QDS_Datum::value() const
{
}
/*!
- Returns the datum value as string (QString object).
+ \brief Get the datum value as string.
+ \return datum value converted to string
*/
QString QDS_Datum::stringValue() const
{
}
/*!
- Returns the datum value as double. This value converted from units of measure in active unit system
- to units of measure in unit system "SI".
+ \brief Get the datum value as double.
+
+ The value is converted according to the measure units in the active units system
+ to measure units in "SI" units system.
+
+ \return datum value converted to double
*/
double QDS_Datum::doubleValue() const
{
}
/*!
- Returns the datum value as integer. This value converted from units of measure in active unit system
- to units of measure in unit system "SI".
+ \brief Get the datum value as integer.
+
+ The value is converted according to the measure units in the active units system
+ to measure units in "SI" units system.
+
+ \return datum value converted to integer
*/
int QDS_Datum::integerValue() const
{
}
/*!
- Returns the text from datum. Text consist of label, string value and units.
+ \brief Get the text data from datum.
+
+ Text consists of label, string value and units.
+
+ \return datum text data
*/
QString QDS_Datum::text() const
{
}
/*!
- Returns false if datum control has inputted value.
+ \brief Check if the datum is empty.
+ \return \c false if datum control has value entered
*/
bool QDS_Datum::isEmpty() const
{
}
/*!
- Reset datum state and set default value as current.
+ \brief Reset datum state and set default value as current.
*/
void QDS_Datum::reset()
{
}
/*!
- Clear the control.
+ \brief Clear the control.
*/
void QDS_Datum::clear()
{
}
/*!
- Set varian value (QVariant object) into datum.
+ \brief Set datum value from QVariant object.
+ \param val new value
*/
void QDS_Datum::setValue( const QVariant& val )
{
- if ( val.isValid() && val.canCast( QVariant::String ) )
+ if ( val.isValid() && val.canConvert( QVariant::String ) )
setStringValue( val.toString() );
else
clear();
}
/*!
- Set string value (QString object) into datum.
+ \brief Set datum value from string data.
+ \param txt new value
*/
void QDS_Datum::setStringValue( const QString& txt )
{
}
/*!
- Set double value into datum. This value converted from units of measure in unit system "SI"
- to units of measure in active unit system. Format the value using datum format if it required.
+ \brief Set datum value from double data.
+
+ The value is converted from measure units in "SI" units system
+ to the measure units in the active units system.
+ Format the value using datum format internal if it is required.
+
+ \param num new value
*/
void QDS_Datum::setDoubleValue( const double num )
{
}
/*!
- Set integer value into datum. This value converted from units of measure in unit system "SI"
- to units of measure in active unit system. Format the value using datum format if it required.
+ \brief Set datum value from integer data.
+
+ The value is converted from measure units in "SI" units system
+ to the measure units in the active units system.
+ Format the value using datum format if it is required.
+
+ \param num new value
*/
void QDS_Datum::setIntegerValue( const int num )
{
}
/*!
- Returns true if all subwidgets specified by \aelement enabled.
+ \brief Get 'enabled' state of the specified subwidget.
+ \param element ORed subwidget flags (QDS::DatumFlags)
+ \return \c true if all subwidgets specified by \a element are enabled
+ \sa setEnabled()
*/
bool QDS_Datum::isEnabled( const int element ) const
{
}
/*!
- Enable/Disable subwidgets specified by \aelement.
- Possible values of \aelement: Label, Control, Units or their combinations.
+ \brief Enable/disable subwidgets specified by \a element.
+
+ Possible values of \a element: QDS::Label, QDS::Control, QDS::Units
+ or their ORed combinations.
+
+ \param on new 'enabled' state
+ \param element ORed subwidget flags (QDS::DatumFlags)
+ \sa isEnabled()
*/
void QDS_Datum::setEnabled( const bool on, const int element )
{
}
/*!
- Enable/Disable control.
+ \brief Enable/disable main control subwidget (QDS::Control).
+ \param on new 'enabled' state
*/
void QDS_Datum::setEnabled( bool on )
{
}
/*!
- Show/hide subwidgets specified by \aelement.
- Possible values of \aelement: Label, Control, Units or their combinations.
+ \brief Show/hide subwidgets specified by \a flags.
+
+ Possible values of \a flags: QDS::Label, QDS::Control, QDS::Units
+ or their ORed combinations.
+
+ \param visible new 'visibility' state
+ \param flags ORed subwidget flags (QDS::DatumFlags)
+ \sa show(), hide()
*/
void QDS_Datum::setShown( const bool visible, const int flags )
{
}
/*!
- Show subwidgets specified by \aelement.
- Possible values of \aelement: Label, Control, Units or their combinations.
+ \brief Show subwidgets specified by \a element.
+
+ Possible values of \a element: QDS::Label, QDS::Control, QDS::Units
+ or their ORed combinations.
+
+ \param element ORed subwidget flags (QDS::DatumFlags)
+ \sa hide(), setShown()
*/
void QDS_Datum::show( const int element )
{
}
/*!
- Hide subwidgets specified by \aelement.
- Possible values of \aelement: Label, Control, Units or their combinations.
+ \brief Hide subwidgets specified by \a element.
+
+ Possible values of \a element: QDS::Label, QDS::Control, QDS::Units
+ or their ORed combinations.
+
+ \param element ORed subwidget flags (QDS::DatumFlags)
+ \sa show(), setShown()
*/
void QDS_Datum::hide( const int element )
{
}
/*!
- Returns subwidget specified by \aelement.
- Possible values of \aelement: Label, Control, Units.
+ \brief Get subwidget specified by \a element.
+
+ Possible values of \a element: QDS::Label, QDS::Control, QDS::Units.
+
+ \param element subwidget
+ \return widget
*/
QWidget* QDS_Datum::widget( const int element ) const
{
}
/*!
- Set the input focus on the control widget.
+ \brief Set the input focus to the control widget.
*/
void QDS_Datum::setFocus()
{
}
/*!
- Returns true if control contains valid value otherwise returns false
- and display warning message box if parameter \amsgBox is set.
+ \brief Check if input data is valid.
+
+ If data is invalid and \a msgBox is \c true, the warning message box is shown.
+
+ \param msgBox if \c true, show warning message box if input is invalid
+ \param extMsg warning message
+ \param extLabel optional name of the variable (if QDS::Label control is not used)
+ \return \c true if input data is valid
*/
bool QDS_Datum::isValid( const bool msgBox, const QString& extMsg, const QString& extLabel ) const
{
}
/*!
- Add widgets to the vertical box layout.
+ \brief Add widgets to the vertical box layout.
+ \param l layout
*/
void QDS_Datum::addTo( QVBoxLayout* l )
{
}
/*!
- Add widgets to the horizaontal box layout.
+ \brief Add widgets to the horizontal box layout.
+ \param l layout
*/
void QDS_Datum::addTo( QHBoxLayout* l )
{
}
/*!
- Add widgets to the grid layout.
+ \brief Add widgets to the grid layout.
+ \param theLay layout
+ \param theRow layout row index
+ \param theCol layout column index
+ \param vertical if \c true subwidgets are layouted vertically, otherwise - horizontally
*/
void QDS_Datum::addTo( QGridLayout* theLay, const int theRow, const int theCol, bool vertical )
{
}
/*!
- Set the aligment of Label or Units. For Control nothing happens.
+ \brief Set the aligment for QDS::Label and/or QDS::Units subwidgets.
+ \param align alignment type (Qt::Alignment)
+ \param type ORed subwidget flags
*/
void QDS_Datum::setAlignment( const int align, const int type )
{
initDatum();
if ( ( type & Label ) && labelWidget() )
- labelWidget()->setAlignment( align );
+ labelWidget()->setAlignment( Qt::Alignment(align) );
if ( ( type & Units ) && unitsWidget() )
- unitsWidget()->setAlignment( align );
+ unitsWidget()->setAlignment( Qt::Alignment(align) );
}
/*!
+ \brief Event filter.
+
Perform delayed initialisation. Reimplemented for internal reasons.
+
+ \param o event reciever object
+ \param e event
+ \return \c true if event should be filtered
*/
bool QDS_Datum::eventFilter( QObject* o, QEvent* e )
{
if ( o == parent() )
{
if ( e->type() == QEvent::Show || e->type() == QEvent::ShowToParent ||
- ( e->type() == QEvent::ChildInserted && ((QChildEvent*)e)->child() == this ) )
+ ( e->type() == QEvent::ChildAdded && ((QChildEvent*)e)->child() == this ) )
initDatum();
}
return QObject::eventFilter( o, e );
}
/*!
- Notify about parameter value changing.
+ \brief Called when datum value is changed.
*/
void QDS_Datum::onParamChanged()
{
}
/*!
- Perform delayed initialization.
+ \brief Perform delayed initialization.
*/
void QDS_Datum::onInitDatum()
{
}
/*!
- Notify about subwidgets destroying. Allow to avoid repeated deleting in destructor.
+ \brief Called when child subwidget is destroued.
+
+ Allows avoiding crash of extra calling of the child subwidget destructor.
+
+ \param obj object being destroyed
*/
void QDS_Datum::onDestroyed( QObject* obj )
{
}
/*!
- Returns QLabel widget which contains dictionary item label.
+ \brief Get QDS::Label widget.
+ \return label widget
*/
QLabel* QDS_Datum::labelWidget() const
{
}
/*!
- Returns QLabel widget which contains dictionary item units.
+ \brief Get QDS::Units widget.
+ \return units widget
*/
QLabel* QDS_Datum::unitsWidget() const
{
}
/*!
- Returns QWidget which contains user input data.
+ \brief Get QDS::Control widget.
+ \return control widget
*/
QWidget* QDS_Datum::controlWidget() const
{
}
/*!
- Returns the dictionary item from the datum.
+ \brief Get the dictionary item from the datum.
+ \return handle to data dictionary item
*/
Handle(DDS_DicItem) QDS_Datum::dicItem() const
{
}
/*!
- Set the dictionary item in to the datum.
+ \brief Set the dictionary item to the datum.
+ \param item handle to data dictionary item
*/
void QDS_Datum::setDicItem( const Handle(DDS_DicItem)& item )
{
}
/*!
- Creates QLabel widget for dictionary item label.
+ \brief Create QDS::Label widget.
+ \param parent parent widget
+ \return label widget
*/
QLabel* QDS_Datum::createLabel( QWidget* parent )
{
}
/*!
- Creates QLabel widget for dictionary item units.
+ \brief Create QDS::Units widget.
+ \param parent parent widget
+ \return units widget
*/
QLabel* QDS_Datum::createUnits( QWidget* parent )
{
}
/*!
- Creates and returns validator accordance to datum type of value.
+ \fn QWidget* QDS_Datum::createControl( QWidget* parent );
+ \brief Create QDS::Control widget.
+
+ This method should be implemented in the successor classes.
+
+ \param parent parent widget
+ \return control widget
+*/
+
+/*!
+ \fn QString QDS_Datum::getString() const;
+ \brief Get string value from datum.
+
+ This method should be implemented in the successor classes.
+
+ \return datum string value
+*/
+
+/*
+ \fn void QDS_Datum::setString( const QString& txt );
+ \brief Set string value to datum.
+
+ This method should be implemented in the successor classes.
+
+ \param txt new datum string value
+*/
+
+/*!
+ \brief Create validator according to the datum type of value.
+ \param limits if \c true use minimum and maximum value limits
+ \return validator
*/
QValidator* QDS_Datum::validator( const bool limits ) const
{
QString aFormat = canonicalFormat( format(), aFlags );
int len = -1;
- int pos = aFormat.find( "." );
+ int pos = aFormat.indexOf( "." );
if ( pos != -1 )
{
QString numStr = aFormat.mid( pos + 1, aFormat.length() - pos - 2 );
}
/*!
- Checks the given string are valid or not.
+ \brief Validate the specified string.
+ \param txt string to be validated
+ \return \c true if string contains valid data
*/
bool QDS_Datum::validate( const QString& txt ) const
{
}
/*!
- Retrieves information from dictionary and create subwidgets using virtual mechanism.
- Virtual mechanism doesn't work in constructor and destructor, therefore this method should
+ \brief Initialize datum.
+
+ Retrieve information from data dictionary and create subwidgets
+ using virtual mechanism.
+
+ Virtual mechanism doesn't work in the constructor, therefore this method should
be called outside the constructor.
*/
void QDS_Datum::initialize()
QString lDescr = longDescription();
QString sDescr = shortDescription();
if ( !sDescr.isEmpty() )
- QToolTip::add( ctrl, sDescr );
+ ctrl->setToolTip( sDescr );
if ( !lDescr.isEmpty() )
- QWhatsThis::add( ctrl, lDescr );
+ ctrl->setWhatsThis( lDescr );
}
if ( labelWidget() && ctrl && !( flags() & NotAccel ) )
}
/*!
- Notification about active unit system changing. Update label and units texts.
+ \brief Process notification about active units system changing.
+
+ Update label and units widgets.
+
+ \param unitSystem new active units system
*/
void QDS_Datum::unitSystemChanged( const QString& unitSystem )
{
}
/*!
- Covert units into text presentation.
+ \brief Convert units into text presentation.
+ \param uni units to be converted
+ \return text presentation of units (rich-text)
*/
QString QDS_Datum::unitsToText( const QString& uni )
{
int pos = -1;
QString aUnits = uni;
- while ( ( pos = aUnits.find( "**" ) ) != -1 )
+ while ( ( pos = aUnits.indexOf( "**" ) ) != -1 )
{
aUnits = aUnits.mid( 0, pos ) + QString( "<tt><font size=+2><sup>" ) +
aUnits.mid( pos + 2, 1 ) + QString( "</sup></font></tt>" ) +
}
/*!
- Covert text presentation into internal units format.
+ \brief Convert text presentation into internal units format.
+ \param txt text presentation of units (rich-text)
+ \return units value
*/
QString QDS_Datum::textToUnits( const QString& txt )
{
int pos = -1;
QString aUnits = txt;
- while ( ( pos = aUnits.find( "<sup>" ) ) != -1 )
+ while ( ( pos = aUnits.indexOf( "<sup>" ) ) != -1 )
{
aUnits.remove( pos, 5 );
aUnits.insert( pos, "**" );
}
- while ( ( pos = aUnits.find( "</sup>" ) ) != -1 )
+ while ( ( pos = aUnits.indexOf( "</sup>" ) ) != -1 )
aUnits.remove( pos, 6 );
return aUnits;
}
/*!
- Format the specified integer as dictionary item value.
+ \brief Format the specified integer as dictionary item value.
+ \param num integer value being formatted
+ \param id data dictionary ID
+ \param convert if \c true, perform conversion from "SI" units system
+ \return formatted value
*/
QString QDS_Datum::format( const int num, const QString& id, const bool convert )
{
}
/*!
- Format the specified double as dictionary item value.
+ \brief Format the specified double as dictionary item value.
+ \param num double value being formatted
+ \param id data dictionary ID
+ \param convert if \c true, perform conversion from "SI" units system
+ \return formatted value
*/
QString QDS_Datum::format( const double num, const QString& id, const bool convert )
{
}
/*!
- Format the specified string as dictionary item value.
+ \brief Format the specified string as dictionary item value.
+ \param str string value being formatted
+ \param id data dictionary ID
+ \param convert if \c true, perform conversion from "SI" units system
+ \return formatted value
*/
QString QDS_Datum::format( const QString& str, const QString& id, const bool convert )
{
}
/*!
- Format the given string accordance to dictionary item format.
+ \brief Format the given value according to the data dictionary item type.
+ \param aFormat format string
+ \param aType data dictionary item type
+ \param aValue integer value being formatted
+ \return formatted value
*/
QString QDS_Datum::format( const QString& aFormat, const int aType, const int aValue )
{
{
case DDS_DicItem::Float:
txt = sprintf( aFormat, (double)aValue );
- txt = txt.stripWhiteSpace();
+ txt = txt.trimmed();
break;
case DDS_DicItem::Integer:
txt = sprintf( aFormat, aValue );
- txt = txt.stripWhiteSpace();
+ txt = txt.trimmed();
break;
case DDS_DicItem::String:
default:
}
/*!
- Format the given string accordance to dictionary item format.
+ \brief Format the given value according to the data dictionary item type.
+ \param aFormat format string
+ \param aType data dictionary item type
+ \param aValue double value being formatted
+ \return formatted value
*/
QString QDS_Datum::format( const QString& aFormat, const int aType, const double aValue )
{
switch ( aType )
{
case DDS_DicItem::Float:
- txt = QString().sprintf( aFormat, aValue );
- txt = txt.stripWhiteSpace();
+ txt = QString().sprintf( aFormat.toLatin1().constData(), aValue );
+ txt = txt.trimmed();
break;
case DDS_DicItem::Integer:
- txt = QString().sprintf( aFormat, (int)aValue );
- txt = txt.stripWhiteSpace();
+ txt = QString().sprintf( aFormat.toLatin1().constData(), (int)aValue );
+ txt = txt.trimmed();
break;
case DDS_DicItem::String:
default:
- txt = QString().sprintf( aFormat, aValue );
+ txt = QString().sprintf( aFormat.toLatin1().constData(), aValue );
break;
}
}
}
/*!
- Format the given string accordance to dictionary item format.
+ \brief Format the given value according to the data dictionary item type.
+ \param aFormat format string
+ \param aType data dictionary item type
+ \param aValue string value being formatted
+ \return formatted value
*/
QString QDS_Datum::format( const QString& aFormat, const int aType, const QString& aValue )
{
QString txt = aValue;
if ( aType != DDS_DicItem::String )
- txt = txt.stripWhiteSpace();
+ txt = txt.trimmed();
if ( aFormat.isEmpty() || txt.isEmpty() )
return txt;
case DDS_DicItem::Float:
txt = txt.replace( 'd', 'e' ).replace( 'D', 'E' );
txt = sprintf( aFormat, txt.toDouble() );
- txt = txt.stripWhiteSpace();
+ txt = txt.trimmed();
break;
case DDS_DicItem::Integer:
txt = sprintf( aFormat, txt.toInt() );
- txt = txt.stripWhiteSpace();
+ txt = txt.trimmed();
break;
case DDS_DicItem::String:
txt = sprintf( aFormat, txt );
}
/*!
- Wrapper around the standard sprintf function.
+ \brief Wrapper around the standard sprintf() function.
+
Process some non standard flags from format string.
+
+ \param fmt string format
+ \param val value
+ \return formatted value
*/
QString QDS_Datum::sprintf( const QString& fmt, const int val )
{
- return QString().sprintf( canonicalFormat( fmt ), val );
+ return QString().sprintf( canonicalFormat( fmt ).toLatin1().constData(), val );
}
/*!
- Wrapper around the standard sprintf function.
+ \brief Wrapper around the standard sprintf() function.
+ \overload
+
Process some non standard flags from format string.
+
+ \param fmt string format
+ \param val value
+ \return formatted value
*/
QString QDS_Datum::sprintf( const QString& fmt, const double val )
{
- return QString().sprintf( canonicalFormat( fmt ), val );
+ return QString().sprintf( canonicalFormat( fmt ).toLatin1().constData(), val );
}
/*!
- Wrapper around the standard sprintf function.
+ \brief Wrapper around the standard sprintf() function.
+ \overload
+
Process some non standard flags from format string.
+
+ \param fmt string format
+ \param val value
+ \return formatted value
*/
QString QDS_Datum::sprintf( const QString& fmt, const QString& val )
{
QString txt = val;
QRegExp rx( "^(%[0-9]*.?[0-9]*s)$" );
- if ( aFormat.find( rx ) != -1 )
+ if ( aFormat.indexOf( rx ) != -1 )
{
// QString().sprintf() always expects string in UTF8 encoding, so we cannot use it here
char* buf = new char[txt.length() + 1];
- ::sprintf( buf, aFormat.latin1(), (const char*)(txt.local8Bit()) );
+ ::sprintf( buf, aFormat.toLatin1().constData(), (const char*)(txt.toLocal8Bit()) );
txt = QString::fromLocal8Bit( buf );
delete[] buf;
}*/
}
- if ( aFlags.contains( "u", false ) )
- txt = txt.upper();
- if ( aFlags.contains( "l", false ) )
- txt = txt.lower();
+ if ( aFlags.contains( "u", Qt::CaseInsensitive ) )
+ txt = txt.toUpper();
+ if ( aFlags.contains( "l", Qt::CaseInsensitive ) )
+ txt = txt.toLower();
return txt;
}
/*!
- Returns the canonical sprintf format.
+ \brief Get the canonical sprintf() format.
+ \param fmt string format
+ \return canonical sprintf() format
*/
QString QDS_Datum::canonicalFormat( const QString& fmt )
{
}
/*!
- Returns the canonical sprintf format and non standard flags.
+ \brief Get the canonical sprintf() format and non standard flags.
+ \param fmt string format
+ \param flags format flags
+ \return canonical sprintf() format
*/
QString QDS_Datum::canonicalFormat( const QString& fmt, QString& flags )
{
flags = QString::null;
QRegExp rx( "^(%[0-9]*.?[0-9]*)([a-z,A-Z]+)[g|c|d|i|o|u|x|e|f|n|p|s|X|E|G]$" );
- if ( rx.search( newFmt ) >= 0 )
+ if ( rx.indexIn( newFmt ) >= 0 )
{
flags = rx.cap( 2 );
newFmt.remove( rx.pos( 2 ), flags.length() );
}
/*!
- Returns displayable units string for given dictionary item id
+ \brief Get displayable units string for specified data dictionary item.
+ \param id data dictionary item ID
+ \return units string
*/
QString QDS_Datum::units( const QString& id )
{
}
/*!
- Get prefix string from format.
+ \brief Get prefix string from format.
+ \return current implementation returns null string
*/
QString QDS_Datum::prefix() const
{
}
/*!
- Get suffix string from format.
+ \brief Get suffix string from format.
+ \return current implementation returns null string
*/
QString QDS_Datum::suffix() const
{
}
/*!
- Get min value.
+ \brief Get minimum value.
+ \return minimum value
*/
QString QDS_Datum::minValue() const
{
QString pref = prefix();
QString suff = suffix();
- QString aMin = minimumValue().stripWhiteSpace();
+ QString aMin = minimumValue().trimmed();
if ( !pref.isEmpty() && aMin.left( pref.length() ) == pref )
aMin = aMin.mid( pref.length() );
}
/*!
- Get max value.
+ \brief Get maximum value.
+ \return maximum value
*/
QString QDS_Datum::maxValue() const
{
QString pref = prefix();
QString suff = suffix();
- QString aMax = maximumValue().stripWhiteSpace();
+ QString aMax = maximumValue().trimmed();
if ( !pref.isEmpty() && aMax.left( pref.length() ) == pref )
aMax = aMax.mid( pref.length() );
}
/*!
- Reset the numeric value cache.
+ \brief Reset the numeric value cache.
*/
void QDS_Datum::invalidateCache()
{
}
/*!
- Remove the acceleartor tags '&' from specified label string \asrc.
+ \brief Remove the acceleartor tags '&' from specified label string \a src.
+ \param src processed string
+ \return string after removing '&' symbols
*/
QString QDS_Datum::removeAccel( const QString& src )
{
}
/*!
- Returns true if given format string \atheFormat has specificator for double values.
+ \brief Check if given format specified doube value.
+ \param theFormat format string
+ \return \c true if \a theFormat has specificator for double values
*/
bool QDS_Datum::isDoubleFormat( const QString& theFormat )
{
}
/*!
- Returns datum flags.
+ \brief Get datum flags.
+ \return datum flags (QDS::DatumFlags)
*/
int QDS_Datum::flags() const
{
}
/*!
- Perform intialization if it needed. [internal]
+ \brief Perform initialization if it needed.
+ \internal
*/
void QDS_Datum::initDatum() const
{
that->initialize();
if ( parent() )
- parent()->removeEventFilter( this );
+ parent()->removeEventFilter( (QObject*)this );
}
/*!
- Return wrapper for specified subwidget. [internal]
+ \brief Get wrapper for specified subwidget.
+ \internal
+ \param wid subwidget
+ \return wrapper
*/
QDS_Datum::Wrapper* QDS_Datum::wrapper( QWidget* wid ) const
{
Wrapper* wrap = 0;
for ( QMap<int, Wrapper*>::ConstIterator it = myWrapper.begin(); it != myWrapper.end() && !wrap; ++it )
{
- if ( it.data() && it.data()->widget() == wid )
- wrap = it.data();
+ if ( it.value() && it.value()->widget() == wid )
+ wrap = it.value();
}
return wrap;
}
/*!
- Return wrapper for specified subwidget name. [internal]
+ \brief Get wrapper for specified subwidget.
+ \internal
+ \param id subwidget ID
+ \return wrapper
*/
QDS_Datum::Wrapper* QDS_Datum::wrapper( const int id ) const
{
}
/*!
- Return subwidget name for specified wrapper. [internal]
+ \brief Get subwidget type for specified wrapper.
+ \internal
+ \param wrap wrapper
+ \return subwidget ID
*/
int QDS_Datum::wrapperType( QDS_Datum::Wrapper* wrap ) const
{
int id = -1;
for ( QMap<int, Wrapper*>::ConstIterator it = myWrapper.begin(); it != myWrapper.end() && id == -1; ++it )
{
- if ( it.data() == wrap )
+ if ( it.value() == wrap )
id = it.key();
}
return id;
}
+
+/*!
+ \fn void QDS_Datum::paramChanged();
+ \brief The signal is emitted when the datum value is changed.
+*/
+
+/*!
+ void QDS_Datum::paramChanged( QString& txt );
+ \brief The signal is emitted when the datum value is changed.
+ \param txt new datum value
+*/
+
#include "QDS.h"
-#include <qwidget.h>
-#include <qstring.h>
-#include <qvariant.h>
-#include <qguardedptr.h>
+#include <QString>
+#include <QVariant>
+#include <QPointer>
#include <DDS_DicItem.h>
class QHBoxLayout;
class QGridLayout;
-class Handle(DDS_Dictionary);
-
class QDS_EXPORT QDS_Datum : public QObject, public QDS
{
Q_OBJECT
static QString canonicalFormat( const QString&, QString& );
private:
- typedef QGuardedPtr<QLabel> GuardedLabel;
- typedef QGuardedPtr<QWidget> GuardedWidget;
+ typedef QPointer<QLabel> GuardedLabel;
+ typedef QPointer<QWidget> GuardedWidget;
private:
QString myId;
//
#include "QDS_LineEdit.h"
-#include <qlineedit.h>
-#include <qvalidator.h>
+#include <QLineEdit>
+#include <QValidator>
-/*
- class: QDS_LineEdit::Editor
- descr: Internal class inherited from line edit
+/*!
+ \class QDS_LineEdit::Editor
+ \internal
+ \brief Improved version of QLineEdit.
*/
class QDS_LineEdit::Editor : public QLineEdit
/*
\class QDS_LineEdit
- Datum with control corresponding to line edit. User can enter parameter value in single line editor.
- User inputted values will be checked by validator according to type if value and parameter properties
- (minimum, maximum, filter, precision, etc). If user input not valid value then this value will be
- displayed in red color.
+ \brief Datum with control corresponding to the line edit.
+
+ User can enter parameter value in single line editor.
+ The value entered by the user is checked by the validator according to item type
+ according to the item properties (minimum, maximum, filter, precision, etc).
+
+ If user input is not valid, the value is displayed in red color.
*/
/*!
- Constructor. Create line edit datum object with datum identifier \aid under widget \aparent. Parameter \aflags
- define behaviour of datum and set of created subwidgets. Default value of this parameter is QDS::All.
- Parameter \acomp specify the component name which will be used during search of dictionary item.
+ \brief Constructor.
+
+ Create line edit datum object with datum identifier \a id and parent widget \a parent.
+
+ Parameter \a flags defines behaviour of datum and set of created
+ subwidgets. Default value of this parameter is QDS::All.
+
+ Parameter \a comp specifies the component name which will be used
+ when searching the dictionary item.
+
+ \param id datum identifier
+ \param parent parent widget
+ \param flags datum flags
+ \param comp component
*/
QDS_LineEdit::QDS_LineEdit( const QString& id, QWidget* parent, const int flags, const QString& comp )
: QDS_Datum( id, parent, flags, comp )
}
/*!
- Destructor.
+ \brief Destructor.
*/
QDS_LineEdit::~QDS_LineEdit()
{
}
/*!
- Notification about active unit system changing. Reimplemented from QDS_Datum.
+ \brief Process notification about active units system changing.
+
Update validator settings for line edit.
+
+ \param system new active units system
*/
void QDS_LineEdit::unitSystemChanged( const QString& system )
{
return;
delete le->validator();
- le->clearValidator();
+ le->setValidator(0);
QValidator* valid = validator();
if ( valid )
le->setValidator( valid );
QString aFormat = format();
int num = 0;
- int pos = aFormat.find( '%' );
+ int pos = aFormat.indexOf( '%' );
if ( pos != -1 )
{
pos++;
int minLen = format( format(), type(), minValue() ).length();
int maxLen = format( format(), type(), maxValue() ).length();
- num = QMAX( QMAX( num, zeroLen ), QMAX( minLen, maxLen ) );
+ num = qMax( qMax( num, zeroLen ), qMax( minLen, maxLen ) );
((Editor*)le)->setNumber( num );
}
/*!
- Select all text in the editor.
+ \brief Select all text in the editor.
*/
void QDS_LineEdit::selectAll()
{
}
/*!
- Deselect all text in the editor.
+ \brief Deselect all text in the editor.
*/
void QDS_LineEdit::deselect()
{
}
/*!
- Select or deselect all text in the editor.
+ \brief Select/deselect all text in the editor.
+ \param on select text if \c true and deselect if \c false
*/
void QDS_LineEdit::setSelection( const bool on )
{
}
/*!
- Returns true if the editor has selected text.
+ \brief Check if there is selection in the editor.
+ \return \c true if the editor has selected text
*/
bool QDS_LineEdit::hasSelection() const
{
}
/*!
- Set the aligment of line edit. Reimplemented from QDS_Datum.
+ \brief Set the aligment for the line edit.
+ \param align alignment type (Qt::Alignment)
+ \param type ORed subwidget flags
*/
void QDS_LineEdit::setAlignment( const int align, const int type )
{
if ( ( type & Control ) && lineEdit() )
- lineEdit()->setAlignment( align );
+ lineEdit()->setAlignment( Qt::Alignment(align) );
QDS_Datum::setAlignment( align, type );
}
/*!
- Returns string value from QLineEdit widget. Reimplemented from QDS_Datum.
+ \brief Get string value from datum.
+ \return datum string value
*/
QString QDS_LineEdit::getString() const
{
}
/*!
- Sets the string value into QLineEdit widget. Reimplemented from QDS_Datum.
+ \brief Set string value to datum.
+ \param txt new datum string value
*/
void QDS_LineEdit::setString( const QString& txt )
{
}
/*!
- Returns pointer to QLineEdit widget.
+ \brief Get line edit widget.
+ \return pointer to the QLineEdit widget
*/
QLineEdit* QDS_LineEdit::lineEdit() const
{
- return ::qt_cast<QLineEdit*>( controlWidget() );
+ return ::qobject_cast<QLineEdit*>( controlWidget() );
}
/*!
- Create QLineEdit widget as control subwidget. Reimplemented from QDS_Datum.
+ \brief Create line edit widget as control subwidget.
+ \param parent parent widget
+ \return created line edit widget
*/
QWidget* QDS_LineEdit::createControl( QWidget* parent )
{
}
/*!
- Notify about text changing in line edit.
+ \brief Called when text in the edit box is modified by the user.
+
+ Notify about text changing in the line edit.
+
+ \param txt current text in the line edit widget (not used)
*/
-void QDS_LineEdit::onTextChanged( const QString& )
+void QDS_LineEdit::onTextChanged( const QString& /*txt*/ )
{
invalidateCache();
}
/*!
- Checks the current parameter value on validity. If value is not valid then set text color as red.
+ \brief Called when text is changed.
+
+ Validate the current parameter value. If value is not valid then set text color as red.
+
+ Emits signal paramChanged() to notify about changing of the control state.
*/
void QDS_LineEdit::onParamChanged()
{
QPalette aPal = anEdit->palette();
if ( !aValid )
- aPal.setColor( QPalette::Active, QColorGroup::Text, QColor( 255, 0, 0 ) );
+ aPal.setColor( QPalette::Active, QPalette::Text, QColor( 255, 0, 0 ) );
else
- aPal.setColor( QPalette::Active, QColorGroup::Text, QColor( 0, 0, 0 ) );
+ aPal.setColor( QPalette::Active, QPalette::Text, QColor( 0, 0, 0 ) );
anEdit->setPalette( aPal );
}
+
+/*!
+ \brief void QDS_LineEdit::returnPressed();
+ \brief The signal is emitted when user presses \c Enter key in the line edit.
+*/
//
#include "QDS_RadioBox.h"
-#include <DDS_Dictionary.h>
-
-#include <TCollection_AsciiString.hxx>
#include <TColStd_HArray1OfInteger.hxx>
#include <TColStd_HArray1OfExtendedString.hxx>
-#include <qobjectlist.h>
-#include <qbuttongroup.h>
-#include <qradiobutton.h>
+#include <QButtonGroup>
+#include <QGroupBox>
+#include <QVBoxLayout>
+#include <QRadioButton>
/*
\class QDS_RadioBox
-
- Datum with control corresponding to button group with set of exclusive radio buttons.
+ \brief Datum with control corresponding to button group with set of exclusive radio buttons.
+
This control used for datum with enumerable values. It can be used for datum which has
- type of value 'List'. Each radio button of combobox defined two properties:
- integer identifier and string name. All operations on radio buttons performed via identifier.
+ type of value 'List'. Each radio button of group box is defined by two properties:
+ integer identifier and string name. All operations on radio buttons are performed via identifier.
- If datum label text is specified then it displayed in group box title.
+ If datum label text is specified, then it is displayed in the group box title.
*/
/*!
- Constructor. Create radio button box datum object with datum identifier \aid under widget \aparent.
- Parameter \aflags define behaviour of datum and set of created subwidgets. Default value of this
- parameter is QDS::Control. Parameter \acomp specify the component name which will be used during
- search of dictionary item.
+ \brief Constructor.
+
+ Create radio button box datum object with datum identifier \a id and parent widget \a parent.
+
+ Parameter \a flags defines behaviour of datum and set of created
+ subwidgets. Default value of this parameter is QDS::All.
+
+ Parameter \a comp specifies the component name which will be used
+ when searching the dictionary item.
+
+ \param id datum identifier
+ \param parent parent widget
+ \param flags datum flags
+ \param comp component
*/
QDS_RadioBox::QDS_RadioBox( const QString& id, QWidget* parent, const int flags, const QString& comp )
-: QDS_Datum( id, parent, flags & ~( Label | Units ), comp )
+: QDS_Datum( id, parent, flags & ~( Label | Units ), comp ),
+ myButtonGroup( 0 )
{
}
/*!
- Destructor.
+ \brief Destructor.
*/
QDS_RadioBox::~QDS_RadioBox()
{
}
/*!
- Returns number of buttons in radio box. If total is 'false' then only
- visible buttons are taken into account otherwise all buttons.
+ \brief Get number of buttons in radio box.
+
+ If \a total is \c false, only visible buttons are taken into account;
+ otherwise total number of buttons is returned
+
+ \param total get number of visible buttons if \c true and total number of buttons if \c false
+ \return requested number of items
*/
int QDS_RadioBox::count( bool total ) const
{
return myValue.count();
else
{
- QPtrList<QRadioButton> bList;
+ QList<QRadioButton*> bList;
buttons( bList );
return bList.count();
}
}
/*!
- Returns list of button identifiers \aids. If \atotal is 'false' then only visible
- buttons are taken into account otherwise all buttons.
+ \brief Get buttons identifiers.
+ \param ids returned list of buttons IDs
+ \param total take into account only visible buttons if \c true and all buttons if \c false
*/
-void QDS_RadioBox::values( QValueList<int>& ids, bool total ) const
+void QDS_RadioBox::values( QList<int>& ids, bool total ) const
{
ids.clear();
for ( QIntList::const_iterator it = myDataIds.begin(); it != myDataIds.end(); ++it )
}
/*!
- Returns visible state of button specified by \aid.
+ \brief Get visibility state of the button specified by \a id.
+ \param id button ID
+ \return item visibility state
*/
bool QDS_RadioBox::state( const int id ) const
{
}
/*!
- Sets the visible state of button specified by \aid. If \aid is -1 then specified
- state will be set to all buttons. If \aappend is set then keep status for other
- buttons otherwise status of other buttons will be cleared.
+ \brief Set the visibility state of the button specified by \a id.
+
+ If \a id is -1 then specified state will be set to all buttons.
+
+ If \a append is set to \c true, keep current status for other buttons,
+ otherwise status of other buttons is cleared.
+
+ \param on new visibility state
+ \param id button ID
+ \param append if \c true, keep original status for other buttons
*/
void QDS_RadioBox::setState( const bool on, const int id, const bool append )
{
- QValueList<int> lst;
+ QList<int> lst;
if ( id < 0 )
{
for ( IdStateMap::Iterator it = myState.begin(); it != myState.end(); ++it )
}
/*!
- Sets the visible state of buttons specified by list of identifiers \aids.
- If \aappend is set then keep status for other buttons otherwise status of other
- buttons will be cleared.
+ \brief Set the visibility state of buttons specified by \a ids.
+
+ If \a append is set to \c true, keep the current status for other buttons,
+ otherwise status of other buttons is cleared.
+
+ \param on new visibility state
+ \param ids buttons IDs list
+ \param append if \c true, keep original status for other buttons
*/
-void QDS_RadioBox::setState( const bool on, const QValueList<int>& ids, const bool append )
+void QDS_RadioBox::setState( const bool on, const QList<int>& ids, const bool append )
{
if ( ids.isEmpty() && append )
return;
QMap<int, int> aMap;
for ( uint i = 0; i < ids.count(); i++ )
- aMap.insert( *ids.at( i ), 0 );
+ aMap.insert( ids.at( i ), 0 );
for ( IdStateMap::Iterator it = myState.begin(); it != myState.end(); ++it )
{
if ( aMap.contains( it.key() ) )
{
- if ( it.data() != on )
+ if ( it.value() != on )
{
- it.data() = on;
+ it.value() = on;
changed = true;
}
}
- else if ( !append && it.data() == on )
+ else if ( !append && it.value() == on )
{
- it.data() = !on;
+ it.value() = !on;
changed = true;
}
}
}
/*!
- Sets the custom user buttons into the radio box. User buttons like standard dictionary
- button from list will be added into the radio box. This functionality allow to user override
+ \brief Set the custom user buttons into the radio box.
+
+ User items like standard dictionary buttons will be added
+ into the radio box. This function allows user to customize
buttons.
+
+ \param ids buttons IDs
+ \param names buttons names
*/
-void QDS_RadioBox::setValues( const QValueList<int>& ids, const QStringList& names )
+void QDS_RadioBox::setValues( const QList<int>& ids, const QStringList& names )
{
if ( ids.count() != names.count() )
return;
}
/*!
- This is an overloaded member function, provided for convenience.
- It behaves essentially like the above function. It creates
- QValueList (0, 1, 2 ... ) and call previous method
+ \brief Set the custom user buttons into the radio box.
+ \overload
+
+ User buttons like standard dictionary buttons will be added
+ into the radio box. This function allows user to customize
+ buttons.
+
+ Uses (0, 1, 2 ... ) as buttons IDs.
+
+ \param names buttons names
*/
void QDS_RadioBox::setValues( const QStringList& names )
{
- QValueList< int > ids;
+ QList< int > ids;
for ( int i = 0, n = names.count(); i < n; i++ )
ids.append( i );
setValues( ids, names );
}
/*!
- Returns string from radio box. Reimplemented. String which contains identifier of
- currently selected button returned.
+ \brief Get string from the radio box.
+
+ String which contains identifier of the currently selected button is returned.
+ \return identifier of the current button converted to string
*/
QString QDS_RadioBox::getString() const
{
QButtonGroup* bg = buttonGroup();
if ( bg )
{
- int id = bg->selectedId();
+ int id = bg->checkedId();
if ( id != -1 )
res = QString::number( id );
}
}
/*!
- Sets the string into radio box. Reimplemented. Button with identifier from specified
- string \atxt became selected in radio box.
+ \brief Set the string value to the radio box widget.
+
+ Button with the identifier from specified string \a txt becomes selected in the radio box.
+
+ \param txt string value
*/
void QDS_RadioBox::setString( const QString& txt )
{
if ( !bg )
return;
- int oldId = bg->selectedId();
+ int oldId = bg->checkedId();
if ( txt.isEmpty() )
{
- QPtrList<QRadioButton> bList;
+ QList<QRadioButton*> bList;
buttons( bList );
- for ( QPtrListIterator<QRadioButton> it( bList ); it.current(); ++it )
- it.current()->setChecked( false );
+ QListIterator<QRadioButton*> it( bList );
+ while ( it.hasNext() )
+ it.next()->setChecked( false );
}
else
{
bool block = signalsBlocked();
blockSignals( true );
- bg->setButton( id );
+ bg->button(id)->setChecked(true);
blockSignals( block );
}
- int newId = bg->selectedId();
+ int newId = bg->checkedId();
if ( oldId != newId )
{
}
/*!
- Returns pointer to QButtonGroup widget.
+ \brief Get internal button group.
+ \return pointer to the QButtonGroup object
*/
QButtonGroup* QDS_RadioBox::buttonGroup() const
{
- return ::qt_cast<QButtonGroup*>( controlWidget() );
+ return myButtonGroup;
+}
+
+/*!
+ \brief Get internal group box widget.
+ \return pointer to the QGroupBox widget
+*/
+QGroupBox* QDS_RadioBox::groupBox() const
+{
+ return ::qobject_cast<QGroupBox*>( controlWidget() );
}
/*!
- Create QButtonGroup widget as control subwidget.
+ \brief Get radio button group box widget.
+ \return internal group box widget
*/
QWidget* QDS_RadioBox::createControl( QWidget* parent )
{
- QButtonGroup* bg = new QButtonGroup( 1, Qt::Vertical, "", parent );
- bg->setExclusive( true );
- bg->setRadioButtonExclusive( true );
- return bg;
+ myButtonGroup = new QButtonGroup( parent );
+ myButtonGroup->setExclusive( true );
+
+ QGroupBox *gb = new QGroupBox( "", parent );
+ QVBoxLayout *vbox = new QVBoxLayout;
+ vbox->addStretch(1);
+ gb->setLayout(vbox);
+ return gb;
}
/*!
- Notification about active unit system changing. Reimplemented from QDS_Datum.
- Update radio box content.
+ \brief Process notification about active units system changing.
+
+ Update radio box contents.
+
+ \param system new active units system
*/
void QDS_RadioBox::unitSystemChanged( const QString& system )
{
for ( QIntList::iterator iter2 = add.begin(); iter2 != add.end(); ++iter2 )
myState.insert( *iter2, true );
- QButtonGroup* bg = buttonGroup();
- if ( bg )
- bg->setTitle( label() );
+ QGroupBox* gb = groupBox();
+ if ( gb ) gb->setTitle( label() );
updateRadioBox();
}
/*!
- Notify about activation radio button.
+ \brief Called when user toggles any radio button.
+ \param on new radio button state
*/
void QDS_RadioBox::onToggled( bool on )
{
}
/*!
- Updates RadioBox after have change of visible state or buttons have been inserted/removed.
+ \brief Update radio box.
*/
void QDS_RadioBox::updateRadioBox()
{
if ( !bg )
return;
- int curId = bg->selectedId();
+ QGroupBox* gb = groupBox();
+ if ( !gb )
+ return;
+
+ int curId = bg->checkedId();
- QPtrList<QRadioButton> bList;
+ QList<QRadioButton*> bList;
buttons( bList );
- for ( QPtrListIterator<QRadioButton> itr( bList ); itr.current(); ++itr )
- delete itr.current();
+ QListIterator<QRadioButton*> itr( bList );
+ while ( itr.hasNext() ) {
+ QRadioButton* aButton = itr.next();
+ if ( gb->layout() ) gb->layout()->removeWidget(aButton);
+ delete aButton;
+ }
for ( QIntList::const_iterator it = myDataIds.begin(); it != myDataIds.end(); ++it )
{
if ( !myValue.contains( id ) || !myState.contains( id ) || !myState[id] )
continue;
- QRadioButton* rb = new QRadioButton( myValue[id], bg );
- bg->insert( rb, id );
+ QRadioButton* rb = new QRadioButton( myValue[id] );
+ ((QObject*)rb)->setParent( bg );
+ bg->addButton( rb, id );
+ if ( gb->layout() ) gb->layout()->addWidget(rb);
connect( rb, SIGNAL( toggled( bool ) ), this, SLOT( onToggled( bool ) ) );
}
if ( curId != -1 )
{
int id = curId;
- if ( !bg->find( id ) )
+ if ( !bg->button( id ) )
{
- QPtrList<QRadioButton> bList;
+ QList<QRadioButton*> bList;
buttons( bList );
if ( !bList.isEmpty() )
- id = bg->id( bList.getFirst() );
+ id = bg->id( bList.empty() ? 0 : bList.first() );
}
bool block = signalsBlocked();
blockSignals( true );
- bg->setButton( id );
+ bg->button(id)->setChecked(true);
blockSignals( block );
}
- if ( curId != bg->selectedId() )
+ if ( curId != bg->checkedId() )
{
onParamChanged();
emit paramChanged();
- emit paramChanged( getString() );
+ QString str = getString();
+ emit paramChanged( str );
}
}
/*!
- Returns the list of the radio buttons from the button group.
+ \brief Get all the radio buttons from the radio box.
+ \param lst returned list of radio buttons
*/
-void QDS_RadioBox::buttons( QPtrList<QRadioButton>& lst ) const
+void QDS_RadioBox::buttons( QList<QRadioButton*>& lst ) const
{
- lst.setAutoDelete( false );
lst.clear();
QButtonGroup* bg = buttonGroup();
if ( !bg )
return;
- QObjectList* objs = bg->queryList( "QRadioButton" );
- if ( objs )
- {
- for ( QObjectListIt it( *objs ); it.current(); ++it )
- {
- QRadioButton* rb = ::qt_cast<QRadioButton*>( it.current() );
- if ( rb )
- lst.append( rb );
- }
- }
- delete objs;
+ QList<QRadioButton*> objs = bg->findChildren<QRadioButton*>();
+ QListIterator<QRadioButton*> it( objs );
+ while ( it.hasNext() )
+ lst.append( it.next() );
}
+
+/*!
+ \fn void QDS_RadioBox::activated( int id );
+ \brief The signal is emitted when any radio button is toggled.
+ \param id button ID
+*/
#include <Qtx.h>
-#include <qmap.h>
-#include <qpixmap.h>
-#include <qstringlist.h>
+#include <QMap>
+#include <QStringList>
-#ifdef WNT
+#ifdef WIN32
#pragma warning( disable:4251 )
#endif
class QButtonGroup;
+class QGroupBox;
class QRadioButton;
class QDS_EXPORT QDS_RadioBox : public QDS_Datum
virtual ~QDS_RadioBox();
int count( bool = false ) const;
- void values( QValueList<int>&, bool = false ) const;
+ void values( QList<int>&, bool = false ) const;
int columns() const;
void setColumns( const int );
bool state( const int ) const;
void setState( const bool, const int, const bool = true );
- void setState( const bool, const QValueList<int>&, const bool = true );
- void setValues( const QValueList<int>&, const QStringList& );
+ void setState( const bool, const QList<int>&, const bool = true );
+ void setValues( const QList<int>&, const QStringList& );
void setValues( const QStringList& );
signals:
protected:
QButtonGroup* buttonGroup() const;
+ QGroupBox* groupBox() const;
virtual QWidget* createControl( QWidget* );
- void buttons( QPtrList<QRadioButton>& ) const;
+ void buttons( QList<QRadioButton*>& ) const;
virtual QString getString() const;
virtual void setString( const QString& );
QIntList myDataIds;
QIntList myUserIds;
QStringList myUserNames;
+
+ QButtonGroup* myButtonGroup;
};
-#ifdef WNT
+#ifdef WIN32
#pragma warning( default:4251 )
#endif
#include <QtxIntSpinBox.h>
-#include <qvalidator.h>
-
/*
\class QDS_SpinBox
-
- Datum with control corresponding to spin box. This control used for integer numbers.
- User can input data directly in spin box or can modify current value with given
- increment.
+ \brief Datum with control corresponding to spin box.
+
+ This control used for integer numbers. User can input data directly in the spin box
+ or can modify current value by clicking arrow (+/-) buttons.
*/
/*!
- Constructor. Create spin box datum object with datum identifier \aid under widget \aparent. Parameter \aflags
- define behaviour of datum and set of created subwidgets. Default value of this parameter is QDS::All.
- Parameter \acomp specify the component name which will be used during search of dictionary item.
+ \brief Constructor.
+
+ Create spin box datum object with datum identifier \a id and parent widget \a parent.
+
+ Parameter \a flags defines behaviour of datum and set of created
+ subwidgets. Default value of this parameter is QDS::All.
+
+ Parameter \a comp specifies the component name which will be used
+ when searching the dictionary item.
+
+ \param id datum identifier
+ \param parent parent widget
+ \param flags datum flags
+ \param comp component
*/
QDS_SpinBox::QDS_SpinBox( const QString& id, QWidget* parent, const int flags, const QString& comp )
: QDS_Datum( id, parent, flags, comp )
}
/*!
- Destructor.
+ \brief Destructor.
*/
QDS_SpinBox::~QDS_SpinBox()
{
}
/*!
- Returns string from QSpinBox widget. Reimplemented.
+ \brief Get string from the spin box.
+ \return string value
*/
QString QDS_SpinBox::getString() const
{
{
res = aSpinBox->text();
if ( !aSpinBox->suffix().isEmpty() )
- res.remove( res.find( aSpinBox->suffix() ), aSpinBox->suffix().length() );
+ res.remove( res.indexOf( aSpinBox->suffix() ), aSpinBox->suffix().length() );
if ( !aSpinBox->prefix().isEmpty() )
- res.remove( res.find( aSpinBox->prefix() ), aSpinBox->prefix().length() );
+ res.remove( res.indexOf( aSpinBox->prefix() ), aSpinBox->prefix().length() );
}
return res;
}
/*!
- Sets the string into QSpinBox widget. Reimplemented.
+ \brief Set the string value to the spin box widget.
+ \param txt string value
*/
void QDS_SpinBox::setString( const QString& txt )
{
}
/*!
- Returns pointer to QSpinBox widget.
+ \brief Get spin box widget.
+ \return internal spin box widget.
*/
QtxIntSpinBox* QDS_SpinBox::spinBox() const
{
- return ::qt_cast<QtxIntSpinBox*>( controlWidget() );
+ return ::qobject_cast<QtxIntSpinBox*>( controlWidget() );
}
/*!
- Create QSpinBox widget as control subwidget. Reimplemented.
+ \brief Create internal spin box as control widget.
+ \param parent parent widget
+ \return created spin box widget
*/
QWidget* QDS_SpinBox::createControl( QWidget* parent )
{
}
/*!
- Notify about value changing in spin box.
+ \brief Called when value in the spin box is changed.
+
+ Emit signals to notify about value changing in the spin box.
+
+ \param val current spin box value
*/
void QDS_SpinBox::onValueChanged( int val )
{
}
/*!
- Sets the increment step.
+ \brief Set the spin box increment value.
+ \param step new increment value
*/
void QDS_SpinBox::setStep( const int step )
{
if ( spinBox() )
- spinBox()->setLineStep( step );
+ spinBox()->setSingleStep( step );
}
/*!
- Returns the increment step.
+ \brief Get the spin box increment value.
+ \return current increment value
*/
int QDS_SpinBox::step() const
{
int s = 0;
if ( spinBox() )
- s = spinBox()->lineStep();
+ s = spinBox()->singleStep();
return s;
}
/*!
- Notification about active unit system changing. Reimplemented from QDS_Datum.
- Update validator and spin box parameters: suffix, prefix, minimum, maximum.
+ \brief Process notification about active units system changing.
+
+ Update spin box contents according to the data dictionary item properties: suffix, prefix, minimum, maximum
+
+ \param system new active units system
*/
void QDS_SpinBox::unitSystemChanged( const QString& system )
{
QSpinBox* sb = spinBox();
if ( sb )
{
- delete sb->validator();
- QValidator* valid = validator();
- sb->setValidator( valid );
+ // not porting this code to qt4, only commented, since from the task context
+ // the new setted validator accepts all integers
+ //delete sb->validator();
+ //QValidator* valid = validator();
+ //sb->setValidator( valid );
sb->setSuffix( suffix() );
sb->setPrefix( prefix() );
- sb->setMinValue( minValue().toInt() );
- sb->setMaxValue( maxValue().toInt() );
+ sb->setMinimum( minValue().toInt() );
+ sb->setMaximum( maxValue().toInt() );
}
}
//
#include "QDS_SpinBoxDbl.h"
-#include <DDS_Dictionary.h>
-
-#include <qvalidator.h>
-
-#include <QtxDblSpinBox.h>
+#include <QtxDoubleSpinBox.h>
/*
\class QDS_SpinBoxDbl
+ \brief Datum with control corresponding to spin box.
- Datum with control corresponding to spin box. This control used for double numbers.
- User can input data directly in spin box or can modify current value with given
- increment.
+ This control is suitable for double numbers. User can input data directly in the spin box
+ or can modify current value by clicking arrow (+/-) buttons.
*/
/*!
- Constructor. Create spin box datum object with datum identifier \aid under widget \aparent. Parameter \aflags
- define behaviour of datum and set of created subwidgets. Default value of this parameter is QDS::All.
- Parameter \acomp specify the component name which will be used during search of dictionary item.
+ \brief Constructor.
+
+ Create spin box datum object with datum identifier \a id and parent widget \a parent.
+
+ Parameter \a flags defines behaviour of datum and set of created
+ subwidgets. Default value of this parameter is QDS::All.
+
+ Parameter \a comp specifies the component name which will be used
+ when searching the dictionary item.
+
+ \param id datum identifier
+ \param parent parent widget
+ \param flags datum flags
+ \param comp component
*/
QDS_SpinBoxDbl::QDS_SpinBoxDbl( const QString& id, QWidget* parent, const int flags, const QString& comp )
: QDS_Datum( id, parent, flags, comp )
}
/*!
- Destructor.
+ \brief Destructor.
*/
QDS_SpinBoxDbl::~QDS_SpinBoxDbl()
{
}
/*!
- Returns string from QSpinBox widget. Reimplemented.
+ \brief Get string from the spin box.
+ \return string value
*/
QString QDS_SpinBoxDbl::getString() const
{
QString res;
- QtxDblSpinBox* sb = spinBox();
+ QtxDoubleSpinBox* sb = spinBox();
if ( sb && !sb->isCleared() )
{
bool hasFocus = sb->hasFocus();
res = sb->text();
if ( !sb->suffix().isEmpty() )
- res.remove( res.find( sb->suffix() ), sb->suffix().length() );
+ res.remove( res.indexOf( sb->suffix() ), sb->suffix().length() );
if ( !sb->prefix().isEmpty() )
- res.remove( res.find( sb->prefix() ), sb->prefix().length() );
+ res.remove( res.indexOf( sb->prefix() ), sb->prefix().length() );
if ( hasFocus )
sb->setFocus();
}
/*!
- Sets the string into QSpinBox widget. Reimplemented.
+ \brief Set the string value to the spin box widget.
+ \param txt string value
*/
void QDS_SpinBoxDbl::setString( const QString& txt )
{
}
/*!
- Returns pointer to QtxDblSpinBox widget.
+ \brief Get spin box widget.
+ \return internal spin box widget.
*/
-QtxDblSpinBox* QDS_SpinBoxDbl::spinBox() const
+QtxDoubleSpinBox* QDS_SpinBoxDbl::spinBox() const
{
- return ::qt_cast<QtxDblSpinBox*>( controlWidget() );
+ return ::qobject_cast<QtxDoubleSpinBox*>( controlWidget() );
}
/*!
- Create QSpinBox widget as control subwidget. Reimplemented.
+ \brief Create internal spin box as control widget.
+ \param parent parent widget
+ \return created spin box widget
*/
QWidget* QDS_SpinBoxDbl::createControl( QWidget* parent )
{
- QtxDblSpinBox* aSpinBox = new QtxDblSpinBox( parent );
+ QtxDoubleSpinBox* aSpinBox = new QtxDoubleSpinBox( parent );
aSpinBox->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
connect( aSpinBox, SIGNAL( valueChanged( double ) ), this, SLOT( onValueChanged( double ) ) );
return aSpinBox;
}
/*!
- Notify about value changing in spin box.
+ \brief Called when value in the spin box is changed.
+
+ Emit signals to notify about value changing in the spin box.
+
+ \param val current spin box value
*/
void QDS_SpinBoxDbl::onValueChanged( double )
{
}
/*!
- Returns the increment step.
+ \brief Get the spin box increment value.
+ \return current increment value
*/
double QDS_SpinBoxDbl::step() const
{
double s = 0;
if ( spinBox() )
- s = spinBox()->lineStep();
+ s = spinBox()->singleStep();
return s;
}
/*!
- Sets the increment step.
+ \brief Set the spin box increment value.
+ \param step new increment value
*/
void QDS_SpinBoxDbl::setStep( const double step )
{
if ( spinBox() )
- spinBox()->setLineStep( step );
+ spinBox()->setSingleStep( step );
}
/*!
- Notification about active unit system changing. Reimplemented from QDS_Datum.
- Update validator and spin box parameters: suffix, prefix, minimum, maximum.
+ \brief Process notification about active units system changing.
+
+ Update spin box contents according to the data dictionary item properties: suffix, prefix, minimum, maximum
+
+ \param system new active units system
*/
void QDS_SpinBoxDbl::unitSystemChanged( const QString& system )
{
QDS_Datum::unitSystemChanged( system );
- QtxDblSpinBox* sb = spinBox();
+ QtxDoubleSpinBox* sb = spinBox();
if ( !sb )
return;
- delete sb->validator();
- QValidator* valid = validator();
- sb->setValidator( valid );
+ // not porting this code to qt4, only commented, since from the task context
+ // the new setted validator accepts any double
+ //delete sb->validator();
+ //QValidator* valid = validator();
+ //sb->setValidator( valid );
sb->setSuffix( suffix() );
sb->setPrefix( prefix() );
if ( !aDicItem.IsNull() )
aPreci = aDicItem->GetPrecision();
- sb->setPrecision( aPreci );
+ sb->setDecimals( aPreci );
- sb->setLineStep( .1 );
- sb->setMinValue( minValue().isEmpty() ? -DBL_MAX : minValue().toDouble() );
- sb->setMaxValue( maxValue().isEmpty() ? DBL_MAX : maxValue().toDouble() );
+ sb->setSingleStep( .1 );
+ sb->setMinimum( minValue().isEmpty() ? -DBL_MAX : minValue().toDouble() );
+ sb->setMaximum( maxValue().isEmpty() ? DBL_MAX : maxValue().toDouble() );
}
#include "QDS_Datum.h"
-class QtxDblSpinBox;
+class QtxDoubleSpinBox;
class QDS_EXPORT QDS_SpinBoxDbl : public QDS_Datum
{
QDS_SpinBoxDbl( const QString&, QWidget* = 0, const int = All, const QString& = QString::null );
virtual ~QDS_SpinBoxDbl();
- double step() const;
- void setStep( const double );
+ double step() const;
+ void setStep( const double );
private slots:
- void onValueChanged( double );
+ void onValueChanged( double );
protected:
- QtxDblSpinBox* spinBox() const;
- virtual QWidget* createControl( QWidget* );
+ QtxDoubleSpinBox* spinBox() const;
+ virtual QWidget* createControl( QWidget* );
- virtual QString getString() const;
- virtual void setString( const QString& );
+ virtual QString getString() const;
+ virtual void setString( const QString& );
- virtual void unitSystemChanged( const QString& );
+ virtual void unitSystemChanged( const QString& );
};
#endif
#include "QDS_Table.h"
-#include "QDS_LineEdit.h"
-
class QDS_Table::DeleteFilter : public QObject
{
public:
#include <QtxTable.h>
-#include <qmap.h>
-#include <qptrvector.h>
+#include <QMap>
+#include <QVector>
class QDS_EXPORT QDS_Table : public QtxTable
{
QDS_Datum* datum( const QWidget* ) const;
private:
- typedef QPtrVector<QDS_Datum> DatumVector;
+ typedef QVector<QDS_Datum*> DatumVector;
typedef QMap<int, QDS_Datum*> DatumMap;
typedef QMap<int, DatumMap> CellMap;
//
#include "QDS_TextEdit.h"
-#include <qtextedit.h>
+#include <QTextEdit>
/*
\class QDS_TextEdit
+ \brief Datum with control corresponding to the text edit.
- Datum with control corresponding to text edit. User can enter parameter value in multiple line editor.
+ User can enter parameter value in multi line editor.
*/
/*!
- Constructor. Create text edit datum object with datum identifier \aid under widget \aparent.
- Parameter \aflags define behaviour of datum and set of created subwidgets. Default value of this
- parameter is QDS::All. Parameter \acomp specify the component name which will be used during search
- of dictionary item.
+ \brief Constructor.
+
+ Create combobox datum object with datum identifier \a id
+ and parent widget \a parent.
+
+ Parameter \a flags defines behaviour of datum and set of created
+ subwidgets. Default value of this parameter is QDS::All.
+
+ Parameter \a comp specifies the component name which will be used
+ when searching the dictionary item.
+
+ \param id datum identifier
+ \param parent parent widget
+ \param flags datum flags
+ \param comp component
*/
QDS_TextEdit::QDS_TextEdit( const QString& id, QWidget* parent, const int flags, const QString& comp )
: QDS_Datum( id, parent, flags, comp )
}
/*!
- Destructor.
+ \brief Destructor.
*/
QDS_TextEdit::~QDS_TextEdit()
{
}
/*!
- Returns string from QTextEdit widget. Reimplemented from QDS_Datum.
+ \brief Get string value from datum.
+ \return datum string value
*/
QString QDS_TextEdit::getString() const
{
QString res;
if ( textEdit() )
- res = textEdit()->text();
+ res = textEdit()->toPlainText();
return res;
}
/*!
- Sets the string into QTextEdit widget. Reimplemented from QDS_Datum.
+ \brief Set string value to datum.
+ \param txt new datum string value
*/
void QDS_TextEdit::setString( const QString& txt )
{
}
/*!
- Returns pointer to QTextEdit widget.
+ \brief Get text edit widget.
+ \return internaltext edit widget
*/
QTextEdit* QDS_TextEdit::textEdit() const
{
- return ::qt_cast<QTextEdit*>( controlWidget() );
+ return ::qobject_cast<QTextEdit*>( controlWidget() );
}
/*!
- Create QTextEdit widget as control subwidget.
+ \brief Create text edit widget as control subwidget.
+ \param parent parent widget
+ \return created text edit widget
*/
QWidget* QDS_TextEdit::createControl( QWidget* parent )
{
}
/*!
+ \brief Called when text is changed by the user.
+
Notify about text changing in text edit.
*/
void QDS_TextEdit::onTextChanged()
emit paramChanged();
emit paramChanged( str );
}
+
+/*!
+ \fn void QDS_TextEdit::returnPressed();
+ \brief The signal is emitted when user presses \c Enter key in the text edit.
+*/
/*!
\class QDS_IntegerValidator
+ \brief A validator for integer values.
- This class to provide validation of user inputted string for datum with 'Integer'
+ This class provides validation of the strings entered by the user for datum with 'Integer'
value type according to datum properties: minimum value, maximum value, filter.
- Inherits from QIntValidator.
+ Inherits QIntValidator.
*/
/*!
- Constructor. Create empty validator object.
+ \brief Constructor.
+
+ Create empty validator object.
+
+ \param p parent object
*/
QDS_IntegerValidator::QDS_IntegerValidator( QObject* p )
: QIntValidator( p )
}
/*!
- Constructor. Create validator object with filter string \af.
+ \brief Constructor.
+
+ Create validator object with filter string \a f.
+
+ \param f filter string
+ \param p parent object
*/
QDS_IntegerValidator::QDS_IntegerValidator( const QString& f, QObject* p )
: QIntValidator( p ),
-myFilter( f )
+ myFilter( f )
{
}
/*!
- Destructor.
+ \brief Destructor.
*/
QDS_IntegerValidator::~QDS_IntegerValidator()
{
}
/*!
- Validate the inputed string \ainput. Reimplemented from QIntValidator. Perform
- standard check by QIntValidator::validate(). If returned state is not Invalid and
- filter specified then perform validation with filter by QRegExpValidator.
+ \brief Validate the entered string \a input.
+
+ Reimplemented from QIntValidator.
+
+ Perform standard check by QIntValidator::validate(). If returned state
+ is not \c QValidator::Invalid and filter is specified then perform validation
+ with filter by QRegExpValidator.
+
+ Returns \c QValidator::Invalid if input is invalid according to this validator's rules,
+ \c QValidator::Intermediate if it is likely that a little more editing will make the
+ input acceptable and \c QValidator::Acceptable if the input is valid.
- Returns Invalid if input is invalid according to this validator's rules,
- Intermediate if it is likely that a little more editing will make the input acceptable
- and Acceptable if the input is valid.
+ \param input string being validated
+ \param pos cursor position
+ \return validation state (\c QValidator::State)
*/
QValidator::State QDS_IntegerValidator::validate( QString& input, int& pos ) const
{
if ( ivState != Invalid && !myFilter.isEmpty() )
rgState = QRegExpValidator( QRegExp( myFilter ), 0 ).validate( input, pos );
- ivState = QMIN( ivState, rgState );
+ ivState = qMin( ivState, rgState );
return ivState;
}
/*!
\class QDS_DoubleValidator
+ \brief A validator for floating point values.
- This class to provide validation of user inputted string for datum with 'Float'
+ This class provides validation of the strings entered by the user for datum with 'Float'
value type according to datum properties: minimum value, maximum value, precision, filter.
- Inherits from QDoubleValidator.
+ Inherits QDoubleValidator.
*/
/*!
- Constructor. Create empty validator object.
+ \brief Constructor.
+
+ Create empty validator object.
+
+ \param p parent object
*/
QDS_DoubleValidator::QDS_DoubleValidator( QObject* p )
: QDoubleValidator( p )
}
/*!
- Constructor. Create validator object with filter string \af.
+ \brief Constructor.
+
+ Create validator object with filter string \a f.
+
+ \param f filter string
+ \param p parent object
*/
QDS_DoubleValidator::QDS_DoubleValidator( const QString& f, QObject* p )
: QDoubleValidator( p ),
-myFilter( f )
+ myFilter( f )
{
}
/*!
- Destructor.
+ \brief Destructor.
*/
QDS_DoubleValidator::~QDS_DoubleValidator()
{
}
/*!
- Validate the inputed string \ainput. Reimplemented from QDoubleValidator. Perform
- standard check by QDoubleValidator::validate(). If returned state is not Invalid and
- filter specified then perform validation with filter by QRegExpValidator.
+ \brief Validate the entered string \a input.
- Returns Invalid if input is invalid according to this validator's rules,
- Intermediate if it is likely that a little more editing will make the input acceptable
- and Acceptable if the input is valid.
+ Reimplemented from QDoubleValidator.
+
+ Perform standard check by QDoubleValidator::validate(). If returned state
+ is not \c QValidator::Invalid and filter is specified then perform validation
+ with filter by QRegExpValidator.
+
+ Returns \c QValidator::Invalid if input is invalid according to this validator's rules,
+ \c QValidator::Intermediate if it is likely that a little more editing will make the
+ input acceptable and \c QValidator::Acceptable if the input is valid.
+
+ \param input string being validated
+ \param pos cursor position
+ \return validation state (\c QValidator::State)
*/
QValidator::State QDS_DoubleValidator::validate( QString& input, int& pos ) const
{
if ( dvState != Invalid && !myFilter.isEmpty() )
rgState = QRegExpValidator( QRegExp( myFilter ), 0 ).validate( input, pos );
- dvState = QMIN( dvState, rgState );
+ dvState = qMin( dvState, rgState );
return dvState;
}
/*!
\class QDS_StringValidator
+ \brief A validator for string values.
- This class to provide validation of user inputted string for datum with 'String'
+ This class provides validation of the strings entered by the user for datum with 'String'
value type according to datum properties: format, filter.
- Inherits from QDoubleValidator.
+ Inherits from QValidator.
*/
/*!
- Constructor. Create empty validator object.
+ \brief Constructor.
+
+ Create empty validator object.
+
+ \param p parent object
*/
QDS_StringValidator::QDS_StringValidator( QObject* p )
: QValidator( p ),
-myLen( -1 )
+ myLen( -1 )
{
}
/*!
- Constructor. Create validator object with filter string \af.
+ \brief Constructor.
+
+ Create validator object with filter string \a f.
+
+ \param f filter string
+ \param p parent object
*/
QDS_StringValidator::QDS_StringValidator( const QString& f, QObject* p )
: QValidator( p ),
-myFlags( f ),
-myLen( -1 )
+ myFlags( f ),
+ myLen( -1 )
{
}
/*!
- Constructor. Create validator object with filter string \aft and format flags \afg.
+ \brief Constructor.
+
+ Create validator object with filter string \a ft and format flags \a fg.
+ \param ft filter string
+ \param fg format string
+ \param p parent object
*/
QDS_StringValidator::QDS_StringValidator( const QString& ft, const QString& fg, QObject* p )
: QValidator( p ),
-myLen( -1 ),
-myFilter( ft ),
-myFlags( fg )
+ myLen( -1 ),
+ myFilter( ft ),
+ myFlags( fg )
{
}
/*!
- Destructor.
+ \brief Destructor.
*/
QDS_StringValidator::~QDS_StringValidator()
{
}
/*!
- Returns valid string length. If length not specified -1 returned.
+ \brief Get maximum valid string length.
+
+ If maximum length is not specified, -1 is returned.
+
+ \return maximum string length
*/
int QDS_StringValidator::length() const
{
}
/*!
- Sets the valid string length \al. If value less than zero valid string
- length not specified.
+ \brief Set maximum valid string length.
+
+ If l <= 0 is not specified, maximum valid length is reset
+ (any string length is valid).
+
+ \param l maximum strin length
*/
void QDS_StringValidator::setLength( const int l )
{
}
/*!
- Validate the inputed string \ainput. Reimplemented from QValidator. Convert specified
- string to upper/lower case if the format flags contains specificator 'u'/'l'.
- If valid string lenght is specified then check given string length. If
- filter specified then perform validation with filter by QRegExpValidator.
-
- Returns Invalid if input is invalid according to this validator's rules,
- Intermediate if it is likely that a little more editing will make the input acceptable
- and Acceptable if the input is valid.
+ \brief Validate the entered string \a input.
+
+ Reimplemented from QValidator.
+
+ Convert specified string to the upper/lower case if the format flags contains
+ specificator 'u'/'l' correspondingly. If valid string length is specified,
+ then check given string length. If filter is specified, then perform also
+ validation with filter by QRegExpValidator.
+
+ Returns \c QValidator::Invalid if input is invalid according to this validator's rules,
+ \c QValidator::Intermediate if it is likely that a little more editing will make the
+ input acceptable and \c QValidator::Acceptable if the input is valid.
+
+ \param input string being validated
+ \param pos cursor position
+ \return validation state (\c QValidator::State)
*/
QValidator::State QDS_StringValidator::validate( QString& input, int& pos ) const
{
return Acceptable;
QString orig = input;
- if ( myFlags.contains( 'u', false ) )
- input = input.upper();
- if ( myFlags.contains( 'l', false ) )
- input = input.lower();
+ if ( myFlags.contains( 'u', Qt::CaseInsensitive ) )
+ input = input.toUpper();
+ if ( myFlags.contains( 'l', Qt::CaseInsensitive ) )
+ input = input.toLower();
State rgState = Acceptable;
State svState = orig == input ? Acceptable : Intermediate;
if ( !myFilter.isEmpty() )
rgState = QRegExpValidator( QRegExp( myFilter ), 0 ).validate( input, pos );
- svState = QMIN( svState, rgState );
+ svState = qMin( svState, rgState );
return svState;
}
#include "QDS.h"
-#include <qvalidator.h>
+#include <QValidator>
-/*!
- class QDS_IntegerValidator
-*/
class QDS_EXPORT QDS_IntegerValidator : public QIntValidator
{
public:
virtual State validate( QString&, int& ) const;
private:
- QString myFilter;
+ QString myFilter; //!< string filter
};
-/*!
- class QDS_DoubleValidator
-*/
class QDS_DoubleValidator : public QDoubleValidator
{
public:
virtual State validate( QString&, int& ) const;
private:
- QString myFilter;
+ QString myFilter; //!< string filter
};
-/*!
- class QDS_StringValidator
-*/
class QDS_EXPORT QDS_StringValidator : public QValidator
{
public:
void setLength( const int );
private:
- int myLen;
- QString myFlags;
- QString myFilter;
+ int myLen; //!< string length
+ QString myFlags; //!< string format flags
+ QString myFilter; //!< string filter
};
#endif
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>QDS_Datum</name>
+ <message>
+ <source>DATA_ERR_TITLE</source>
+ <translation>Incorrect parameter value</translation>
+ </message>
+ <message>
+ <source>DATA_STRING</source>
+ <translation> non-empty string</translation>
+ </message>
+ <message>
+ <source>DATA_NON_EMPTY</source>
+ <translation> non-empty</translation>
+ </message>
+ <message>
+ <source>DATA_MIN_LIMIT</source>
+ <translation> is greater than %1</translation>
+ </message>
+ <message>
+ <source>DATA_FLOAT</source>
+ <translation> real</translation>
+ </message>
+ <message>
+ <source>DATA_RANGE</source>
+ <translation> in range [%1, %2]</translation>
+ </message>
+ <message>
+ <source>DATA_SHOULD_BE_VALUE</source>
+ <translation>Should be%1 value</translation>
+ </message>
+ <message>
+ <source>DATA_INTEGER</source>
+ <translation> integer</translation>
+ </message>
+ <message>
+ <source>DATA_INCORRECT_VALUE</source>
+ <translation>Value of parameter "%1" is incorrect.</translation>
+ </message>
+ <message>
+ <source>DATA_MAX_LIMIT</source>
+ <translation> is less than %1</translation>
+ </message>
+ <message>
+ <source>DATA_INPUT_VALUE</source>
+ <translation>Please, input correct value.</translation>
+ </message>
+</context>
+</TS>
# header files
-salomeinclude_HEADERS= Qtx.h \
- QtxAction.h \
- QtxColorScale.h \
- QtxComboBox.h \
- QtxDblSpinBox.h \
- QtxDialog.h \
- QtxDockAction.h \
- QtxDockWindow.h \
- QtxGroupBox.h \
- QtxIntSpinBox.h \
- QtxListAction.h \
- QtxListBox.h \
- QtxListOfOperations.h \
- QtxLogoMgr.h \
- QtxMenuButton.h \
- QtxMRUAction.h \
- QtxOperations.h \
- QtxPathDialog.h \
- QtxPopupMgr.h \
- QtxResourceMgr.h \
- QtxStdOperations.h \
- QtxTable.h \
- QtxToolBar.h \
- QtxToolTip.h \
- QtxParser.h \
- QtxPopupMenu.h \
- QtxActionMgr.h \
- QtxActionMenuMgr.h \
- QtxActionToolMgr.h \
- QtxMainWindow.h \
- QtxWorkspaceAction.h \
- QtxWorkstackAction.h \
- QtxListResourceEdit.h \
- QtxWorkstack.h \
- QtxResourceEdit.h \
- QtxListView.h \
- QtxDirListEditor.h \
- QtxDblValidator.h \
- QtxSplash.h
+#VSR: already migrated to Qt4 files
+salomeinclude_HEADERS= \
+ Qtx.h \
+ QtxAction.h \
+ QtxActionMenuMgr.h \
+ QtxActionMgr.h \
+ QtxActionSet.h \
+ QtxActionToolMgr.h \
+ QtxColorScale.h \
+ QtxComboBox.h \
+ QtxDialog.h \
+ QtxDockAction.h \
+ QtxDockWidget.h \
+ QtxDoubleSpinBox.h \
+ QtxEvalExpr.h \
+ QtxGridBox.h \
+ QtxGroupBox.h \
+ QtxIntSpinBox.h \
+ QtxListAction.h \
+ QtxLogoMgr.h \
+ QtxMainWindow.h \
+ QtxMap.h \
+ QtxMRUAction.h \
+ QtxPathDialog.h \
+ QtxPopupMgr.h \
+ QtxResourceMgr.h \
+ QtxSplash.h \
+ QtxToolBar.h \
+ QtxToolTip.h \
+ QtxValidator.h \
+ QtxWorkspace.h \
+ QtxWorkspaceAction.h \
+ QtxWorkstack.h \
+ QtxWorkstackAction.h
+
+#VSR: not yet migrated to Qt4 files
+# \
+ QtxDirListEditor.h \
+ QtxListBox.h \
+ QtxListResourceEdit.h \
+ QtxListView.h \
+ QtxPopupMenu.h \
+ QtxResourceEdit.h \
+ QtxTable.h
# Libraries targets
lib_LTLIBRARIES= libqtx.la
-dist_libqtx_la_SOURCES= \
- Qtx.cxx \
- QtxAction.cxx \
- QtxColorScale.cxx \
- QtxComboBox.cxx \
- QtxDblSpinBox.cxx \
- QtxDialog.cxx \
- QtxDockAction.cxx \
- QtxDockWindow.cxx \
- QtxGroupBox.cxx \
- QtxIntSpinBox.cxx \
- QtxListAction.cxx \
- QtxListBox.cxx \
- QtxListOfOperations.cxx \
- QtxLogoMgr.cxx \
- QtxMenuButton.cxx \
- QtxMRUAction.cxx \
- QtxPathDialog.cxx \
- QtxPopupMgr.cxx \
- QtxResourceMgr.cxx \
- QtxStdOperations.cxx \
- QtxTable.cxx \
- QtxToolBar.cxx \
- QtxToolTip.cxx \
- QtxOperations.cxx \
- QtxParser.cxx \
- QtxPopupMenu.cxx \
- QtxActionMgr.cxx \
- QtxActionMenuMgr.cxx \
- QtxActionToolMgr.cxx \
- QtxMainWindow.cxx \
- QtxWorkspaceAction.cxx \
- QtxWorkstackAction.cxx \
- QtxListResourceEdit.cxx \
- QtxResourceEdit.cxx \
- QtxWorkstack.cxx \
- QtxListView.cxx \
- QtxDirListEditor.cxx \
- QtxDblValidator.cxx \
- QtxSplash.cxx
+#VSR: already migrated to Qt4 files
+dist_libqtx_la_SOURCES= \
+ Qtx.cxx \
+ QtxAction.cxx \
+ QtxActionMenuMgr.cxx \
+ QtxActionMgr.cxx \
+ QtxActionSet.cxx \
+ QtxActionToolMgr.cxx \
+ QtxColorScale.cxx \
+ QtxComboBox.cxx \
+ QtxDialog.cxx \
+ QtxDockAction.cxx \
+ QtxDockWidget.cxx \
+ QtxDoubleSpinBox.cxx \
+ QtxEvalExpr.cxx \
+ QtxGridBox.cxx \
+ QtxGroupBox.cxx \
+ QtxIntSpinBox.cxx \
+ QtxListAction.cxx \
+ QtxLogoMgr.cxx \
+ QtxMainWindow.cxx \
+ QtxMRUAction.cxx \
+ QtxPathDialog.cxx \
+ QtxPopupMgr.cxx \
+ QtxResourceMgr.cxx \
+ QtxSplash.cxx \
+ QtxToolBar.cxx \
+ QtxToolTip.cxx \
+ QtxValidator.cxx \
+ QtxWorkspace.cxx \
+ QtxWorkspaceAction.cxx \
+ QtxWorkstack.cxx \
+ QtxWorkstackAction.cxx
+
+#VSR: not yet migrated to Qt4 files
+# \
+ QtxDirListEditor.cxx \
+ QtxListBox.cxx \
+ QtxListResourceEdit.cxx \
+ QtxListView.cxx \
+ QtxPopupMenu.cxx \
+ QtxResourceEdit.cxx \
+ QtxTable.cxx
+
+#VSR: already migrated to Qt4 files
+MOC_FILES= \
+ QtxAction_moc.cxx \
+ QtxActionMenuMgr_moc.cxx \
+ QtxActionMgr_moc.cxx \
+ QtxActionSet_moc.cxx \
+ QtxActionToolMgr_moc.cxx \
+ QtxColorScale_moc.cxx \
+ QtxComboBox_moc.cxx \
+ QtxDialog_moc.cxx \
+ QtxDockAction_moc.cxx \
+ QtxDockWidget_moc.cxx \
+ QtxDoubleSpinBox_moc.cxx \
+ QtxGridBox_moc.cxx \
+ QtxGroupBox_moc.cxx \
+ QtxIntSpinBox_moc.cxx \
+ QtxListAction_moc.cxx \
+ QtxLogoMgr_moc.cxx \
+ QtxMainWindow_moc.cxx \
+ QtxMRUAction_moc.cxx \
+ QtxPathDialog_moc.cxx \
+ QtxPopupMgr_moc.cxx \
+ QtxSplash_moc.cxx \
+ QtxToolBar_moc.cxx \
+ QtxToolTip_moc.cxx \
+ QtxValidator_moc.cxx \
+ QtxWorkspace_moc.cxx \
+ QtxWorkspaceAction_moc.cxx \
+ QtxWorkstack_moc.cxx \
+ QtxWorkstackAction_moc.cxx
+
+#VSR: not yet migrated to Qt4 files
+# \
+ QtxDirListEditor_moc.cxx \
+ QtxListBox_moc.cxx \
+ QtxListResourceEdit_moc.cxx \
+ QtxListView_moc.cxx \
+ QtxPopupMenu_moc.cxx \
+ QtxTable_moc.cxx
-MOC_FILES= \
- QtxAction_moc.cxx \
- QtxColorScale_moc.cxx \
- QtxComboBox_moc.cxx \
- QtxDblSpinBox_moc.cxx \
- QtxDialog_moc.cxx \
- QtxDockAction_moc.cxx \
- QtxDockWindow_moc.cxx \
- QtxGroupBox_moc.cxx \
- QtxIntSpinBox_moc.cxx \
- QtxListAction_moc.cxx \
- QtxListBox_moc.cxx \
- QtxLogoMgr_moc.cxx \
- QtxMenuButton_moc.cxx \
- QtxMRUAction_moc.cxx \
- QtxPathDialog_moc.cxx \
- QtxPopupMgr_moc.cxx \
- QtxPopupMenu_moc.cxx \
- QtxTable_moc.cxx \
- QtxToolBar_moc.cxx \
- QtxToolTip_moc.cxx \
- QtxActionMgr_moc.cxx \
- QtxActionMenuMgr_moc.cxx \
- QtxActionToolMgr_moc.cxx \
- QtxMainWindow_moc.cxx \
- QtxWorkspaceAction_moc.cxx \
- QtxWorkstackAction_moc.cxx \
- QtxWorkstack_moc.cxx \
- QtxListView_moc.cxx \
- QtxListResourceEdit_moc.cxx \
- QtxDirListEditor_moc.cxx \
- QtxDblValidator_moc.cxx \
- QtxSplash_moc.cxx
nodist_libqtx_la_SOURCES= $(MOC_FILES)
libqtx_la_CPPFLAGS=$(QT_INCLUDES)
// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
+//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
+// License as published by the Free Software Foundation; either
// version 2.1 of the License.
-//
-// This library 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
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#include "Qtx.h"
-#include <qdir.h>
-#include <qbitmap.h>
-#include <qstring.h>
-#include <qwidget.h>
-#include <qlayout.h>
-#include <qpainter.h>
-#include <qtoolbar.h>
-#include <qgroupbox.h>
-#include <qfileinfo.h>
-#include <qpopupmenu.h>
-#include <qobjectlist.h>
-#include <qwidgetlist.h>
-#include <qapplication.h>
+#include <QDir>
+#include <QFileInfo>
+#include <QMenu>
+#include <QBitmap>
+#include <QWidget>
+#include <QLayout>
+#include <QPainter>
+#include <QApplication>
+#include <QDesktopWidget>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
/*!
- Name: setTabOrder [static public]
- Desc: Set tab order for specified list of widgets. Last parameter should be null pointer.
+ \class Qtx
+ \brief Set of helpful utility functions.
+
+ The class implements set of static functions which can be used for different purpuses:
+ - define tab order for set of widgets: setTabOrder()
+ - align one widget to the other widget: alignWidget()
+ - remove extra separators from menu or toolbar: simplifySeparators()
+ - retrieve directory, file name and extension parts of the path: dir(), file(), extension()
+ - get temporary directory name: tmpDir()
+ - create and remove directory (recursively): mkDir(), rmDir()
+ - convert text file from DOS to UNIX native format: dos2unix()
+ - convert picture to the gray scale: grayscale()
+ - and other
*/
+/*!
+ \brief Convert character array (ASCII string) to the QString.
+ \param str character array
+ \param len array length, if < 0, the array should be zero-terminated
+ \return QString object
+ */
+QString Qtx::toQString( const char* str, const int len )
+{
+ return toQString( (unsigned char*)str, len );
+}
+
+/*!
+ \brief Convert integer array (UNICODE string) to the QString.
+ \param str integer array
+ \param len array length, if < 0, the array should be zero-terminated
+ \return QString object
+ */
+QString Qtx::toQString( const short* str, const int len )
+{
+ return toQString( (unsigned short*)str, len );
+}
+
+/*!
+ \brief Convert character array (ASCII string) to the QString.
+ \param str character array
+ \param len array length, if < 0, the array should be zero-terminated
+ \return QString object
+ */
+QString Qtx::toQString( const unsigned char* str, const int len )
+{
+ QString res;
+ const unsigned char* s = str;
+ while ( len < 0 || res.length() < len )
+ {
+ if ( *s == '\0' )
+ break;
+
+ res.append( QChar( *s ) );
+ s++;
+ }
+ return res;
+}
+
+/*!
+ \brief Convert integer array (UNICODE string) to the QString.
+ \param str integer array
+ \param len array length, if < 0, the array should be zero-terminated
+ \return QString object
+ */
+QString Qtx::toQString( const unsigned short* str, const int len )
+{
+ QString res;
+ const unsigned short* s = str;
+ while ( len < 0 || res.length() < len )
+ {
+ if ( *s == '\0' )
+ break;
+
+ res.append( QChar( *s ) );
+ s++;
+ }
+ return res;
+}
+
+/*!
+ \brief Set tab order for specified list of widgets.
+
+ The function has arbitrary number of parameters, each should be
+ hovewer of QWidget* type. Last parameter should be null pointer.
+
+ \param first first widget in the sequence
+*/
void Qtx::setTabOrder( QWidget* first, ... )
{
va_list wids;
- va_start( wids, first );
+ va_start( wids, first );
- QWidgetList widList;
+ QWidgetList widList;
- QWidget* cur = first;
- while ( cur )
- {
- widList.append( cur );
- cur = va_arg( wids, QWidget* );
+ QWidget* cur = first;
+ while ( cur )
+ {
+ widList.append( cur );
+ cur = va_arg( wids, QWidget* );
}
- setTabOrder( widList );
+ setTabOrder( widList );
}
/*!
- Name: setTabOrder [static public]
- Desc: Set tab order for specified list of widgets.
+ \brief Set tab order for specified list of widgets.
+ \param widgets list of widgets
*/
-
void Qtx::setTabOrder( const QWidgetList& widgets )
{
if ( widgets.count() < 2 )
return;
QWidget* prev = 0;
- for ( QWidgetListIt it( widgets ); it.current(); ++it )
+ for ( QWidgetList::const_iterator it = widgets.begin(); it!= widgets.end(); ++it )
{
- QWidget* next = it.current();
+ QWidget* next = *it;
if ( prev && next )
QWidget::setTabOrder( prev, next );
prev = next;
}
/*!
- Name: alignWidget [static public]
- Desc: Align widget 'src' relative to widget 'ref' acording to alignment flags.
- Alignment flags:
- Qtx::AlignLeft - Align left side of 'src' to left side of 'ref'.
- Qtx::AlignRight - Align right side of 'src' to right side of 'ref'.
- Qtx::AlignTop - Align top side of 'src' to top side of 'ref'.
- Qtx::AlignBottom - Align bottom side of 'src' to bottom side of 'ref'.
- Qtx::AlignHCenter - Align 'src' to center of 'ref' in horizontal dimension.
- Qtx::AlignVCenter - Align 'src' to center of 'ref' in vertical dimension.
- Qtx::AlignCenter - Align 'src' to center of 'ref' in both dimensions.
- Qtx::AlignOutLeft - Align right side of 'src' to left side of 'ref'.
- Qtx::AlignOutRight - Align left side of 'src' to right side of 'ref'.
- Qtx::AlignOutTop - Align bottom side of 'src' to top side of 'ref'.
- Qtx::AlignOutBottom - Align top side of 'src' to bottom side of 'ref'.
+ \brief Align widget \a src relative to widget \a ref acording to the
+ alignment flags \a alignFlags.
+ \param src source widget (being aligned)
+ \param ref reference widget (source widget being aligned to)
+ \param alignFlags alignment flags (Qtx::AlignmentFlags)
*/
-
void Qtx::alignWidget( QWidget* src, const QWidget* ref, const int alignFlags )
{
- if ( !src || !ref || !alignFlags )
- return;
-
- QPoint srcOri = src->pos();
- QPoint refOri = ref->pos();
- if ( src->parentWidget() && !src->isTopLevel() )
- srcOri = src->parentWidget()->mapToGlobal( srcOri );
- if ( ref->parentWidget() && !ref->isTopLevel() )
- refOri = ref->parentWidget()->mapToGlobal( refOri );
-
- int x = srcOri.x(), y = srcOri.y();
- int refWidth = ref->frameGeometry().width(), refHei = ref->frameGeometry().height();
- int srcWidth = src->frameGeometry().width(), srcHei = src->frameGeometry().height();
-
- if ( srcWidth <= 0 )
- srcWidth = src->sizeHint().width();
+ if ( !src || !ref || !alignFlags )
+ return;
+
+ QPoint srcOri = src->pos();
+ QPoint refOri = ref->pos();
+ if ( src->parentWidget() && !src->isTopLevel() )
+ srcOri = src->parentWidget()->mapToGlobal( srcOri );
+ if ( ref->parentWidget() && !ref->isTopLevel() )
+ refOri = ref->parentWidget()->mapToGlobal( refOri );
+
+ int x = srcOri.x(), y = srcOri.y();
+ int refWidth = ref->frameGeometry().width(), refHei = ref->frameGeometry().height();
+ int srcWidth = src->frameGeometry().width(), srcHei = src->frameGeometry().height();
+
+ if ( srcWidth <= 0 )
+ srcWidth = src->sizeHint().width();
if ( srcHei <= 0 )
srcHei = src->sizeHint().height();
- int border = 0;
+ int border = 0;
if ( ref->isTopLevel() && ref->isMaximized() &&
src->isTopLevel() && !src->isMaximized() )
border = ( src->frameGeometry().width() - src->width() ) / 2;
- if ( alignFlags & Qtx::AlignLeft )
- x = refOri.x() + border;
- if ( alignFlags & Qtx::AlignOutLeft )
- x = refOri.x() - srcWidth - border;
- if ( alignFlags & Qtx::AlignRight )
- x = refOri.x() + refWidth - srcWidth - border;
- if ( alignFlags & Qtx::AlignOutRight )
- x = refOri.x() + refWidth + border;
- if ( alignFlags & Qtx::AlignTop )
- y = refOri.y() + border;
- if ( alignFlags & Qtx::AlignOutTop )
- y = refOri.y() - srcHei - border;
- if ( alignFlags & Qtx::AlignBottom )
- y = refOri.y() + refHei - srcHei - border;
- if ( alignFlags & Qtx::AlignOutBottom )
- y = refOri.y() + refHei + border;
- if ( alignFlags & Qtx::AlignHCenter )
- x = refOri.x() + ( refWidth - srcWidth ) / 2;
- if ( alignFlags & Qtx::AlignVCenter )
- y = refOri.y() + ( refHei - srcHei ) / 2;
-
- if ( src->parentWidget() && !src->isTopLevel() )
- {
- QPoint pos = src->parentWidget()->mapFromGlobal( QPoint( x, y ) );
- x = pos.x();
- y = pos.y();
- }
-
- QWidget* desk = QApplication::desktop();
- if ( desk && x + srcWidth + border > desk->width() )
- x = desk->width() - srcWidth - border;
- if ( desk && y + srcHei + border > desk->height() )
- y = desk->height() - srcHei - border;
-
- x = QMAX( x, 0 );
- y = QMAX( y, 0 );
-
- src->move( x, y );
-}
-
-/*!
- Name: simplifySeparators [static public]
- Desc: Checks toolbar for unnecessary separators and removes them
-*/
-void Qtx::simplifySeparators( QToolBar* toolbar )
-{
- if ( !toolbar )
- return;
-
- const QObjectList* objList = toolbar->children();
- if ( !objList )
- return;
-
- QObjectList delList;
-
- bool isPrevSep = true;
- for ( QObjectListIt it( *objList ); it.current(); ++it )
+ if ( alignFlags & Qtx::AlignLeft )
+ x = refOri.x() + border;
+ if ( alignFlags & Qtx::AlignOutLeft )
+ x = refOri.x() - srcWidth - border;
+ if ( alignFlags & Qtx::AlignRight )
+ x = refOri.x() + refWidth - srcWidth - border;
+ if ( alignFlags & Qtx::AlignOutRight )
+ x = refOri.x() + refWidth + border;
+ if ( alignFlags & Qtx::AlignTop )
+ y = refOri.y() + border;
+ if ( alignFlags & Qtx::AlignOutTop )
+ y = refOri.y() - srcHei - border;
+ if ( alignFlags & Qtx::AlignBottom )
+ y = refOri.y() + refHei - srcHei - border;
+ if ( alignFlags & Qtx::AlignOutBottom )
+ y = refOri.y() + refHei + border;
+ if ( alignFlags & Qtx::AlignHCenter )
+ x = refOri.x() + ( refWidth - srcWidth ) / 2;
+ if ( alignFlags & Qtx::AlignVCenter )
+ y = refOri.y() + ( refHei - srcHei ) / 2;
+
+ if ( src->parentWidget() && !src->isTopLevel() )
{
- bool isSep = it.current()->isA( "QToolBarSeparator" );
- if ( isPrevSep && isSep )
- delList.append( it.current() );
- isPrevSep = isSep;
+ QPoint pos = src->parentWidget()->mapFromGlobal( QPoint( x, y ) );
+ x = pos.x();
+ y = pos.y();
}
- for ( QObjectListIt itr( delList ); itr.current(); ++itr )
- delete itr.current();
+ QWidget* desk = QApplication::desktop();
+ if ( desk && x + srcWidth + border > desk->width() )
+ x = desk->width() - srcWidth - border;
+ if ( desk && y + srcHei + border > desk->height() )
+ y = desk->height() - srcHei - border;
- if ( toolbar->children() && !toolbar->children()->isEmpty() &&
- toolbar->children()->getFirst()->isA( "QToolBarSeparator" ) )
- delete toolbar->children()->getFirst();
+ x = qMax( x, 0 );
+ y = qMax( y, 0 );
- if ( toolbar->children() && !toolbar->children()->isEmpty() &&
- toolbar->children()->getLast()->isA( "QToolBarSeparator" ) )
- delete toolbar->children()->getLast();
+ src->move( x, y );
}
/*!
- Name: simplifySeparators [static public]
- Desc: Checks popup menu recursively for unnecessary separators and removes them
+ \brief Remove (recursively) unnecessary separators from the menu or toolbar.
+ \param wid widget, should be of QMenu* or QToolBar* class
*/
-void Qtx::simplifySeparators( QPopupMenu* popup, const bool recursive )
+void Qtx::simplifySeparators( QWidget* wid, const bool recursive )
{
- if ( !popup || !popup->count() )
+ if ( !wid )
+ return;
+
+ QList<QAction*> items = wid->actions();
+ if ( items.isEmpty() )
return;
- QIntList idRemove;
- for ( uint i = 1; i < popup->count(); i++ )
+ QList<QAction*> toRemove;
+ for ( int i = 1; i < items.count(); i++ )
{
- if ( popup->findItem( popup->idAt( i ) )->isSeparator() &&
- popup->findItem( popup->idAt( i - 1 ) )->isSeparator() )
- idRemove.append( popup->idAt( i ) );
+ if ( items[i]->isSeparator() && items[i - 1]->isSeparator() )
+ toRemove.append( items[i] );
- if ( recursive )
- simplifySeparators( popup->findItem( popup->idAt( i ) )->popup() );
+ if ( recursive && items[i]->menu() )
+ simplifySeparators( items[i]->menu(), recursive );
}
- for ( QIntList::const_iterator it = idRemove.begin(); it != idRemove.end(); ++it )
- popup->removeItem( *it );
+ for ( QList<QAction*>::iterator it = toRemove.begin(); it != toRemove.end(); ++it )
+ wid->removeAction( *it );
- if ( popup->count() > 0 && popup->findItem( popup->idAt( 0 ) )->isSeparator() )
- popup->removeItem( popup->idAt( 0 ) );
+ items = wid->actions();
+ if ( !items.isEmpty() && items[0]->isSeparator() )
+ wid->removeAction( items[0] );
- if ( popup->count() > 0 && popup->findItem( popup->idAt( popup->count() - 1 ) )->isSeparator() )
- popup->removeItem( popup->idAt( popup->count() - 1 ) );
+ items = wid->actions();
+ if ( !items.isEmpty() && items[items.count() - 1]->isSeparator() )
+ wid->removeAction( items[items.count() - 1] );
}
/*!
- Name: isParent [static public]
- Desc: Returns 'true' if specified 'parent' is parent object of given 'child'.
+ \brief Return \c true if specified \a parent is a parent object
+ of given \a child (in terms of QObject).
+
+ This function works recursively. It means that \a true is also
+ returned if \a parent is a grand-father, grand-grand-father, etc
+ of \a child. If the same object is given as both \a parent and
+ \a child, \c true is also returned.
+
+ \param child child object
+ \param parent parent object
+ \return \c true if the \a parent is a parent of \a child
*/
bool Qtx::isParent( QObject* child, QObject* parent )
{
}
/*!
- Name: dir [static public]
- Desc: Returns dir name or null string.
+ \brief Return directory part of the file path.
+
+ If the file path does not include directory part (the file is in the
+ current directory), null string is returned.
+
+ \param path file path
+ \param abs if true (default) \a path parameter is treated as absolute file path
+ \return directory part of the file path
*/
QString Qtx::dir( const QString& path, const bool abs )
{
- QString dirPath = QFileInfo( path ).dirPath( abs );
+ QDir aDir = QFileInfo( path ).dir();
+ QString dirPath = abs ? aDir.absolutePath() : aDir.path();
if ( dirPath == QString( "." ) )
- dirPath = QString::null;
+ dirPath = QString();
return dirPath;
}
/*!
- Name: file [static public]
- Desc: Returns file with or without extension.
+ \brief Return file name part of the file path.
+
+ \param path file path
+ \param withExt if true (default) complete file name (with all
+ extension except the last) is returned, otherwise only base name
+ is returned
+ \return file name part of the file path
*/
QString Qtx::file( const QString& path, bool withExt )
{
+ QString fPath = path;
+ while ( !fPath.isEmpty() && ( fPath[fPath.length() - 1] == '\\' || fPath[fPath.length() - 1] == '/' ) )
+ fPath.remove( fPath.length() - 1, 1 );
+
if ( withExt )
- return QFileInfo( path ).fileName();
+ return QFileInfo( fPath ).fileName();
else
- return QFileInfo( path ).baseName();
+ return QFileInfo( fPath ).baseName();
}
/*!
- Name: extension [static public]
- Desc: Returns the file extension only or null string.
+ \brief Return extension part of the file path.
+
+ \param path file path
+ \param full if true complete extension (all extensions, dot separated)
+ is returned, otherwise (default) only last extension is returned
+ \return extension part of the file path
*/
-QString Qtx::extension( const QString& path )
+QString Qtx::extension( const QString& path, const bool full )
{
- return QFileInfo( path ).extension(false); // after the last dot
+ return full ? QFileInfo( path ).completeSuffix() : QFileInfo( path ).suffix();
}
/*!
- Name: library [static public]
- Desc: Generate library file name.
- Append required prefix (lib) and suffix (.dll/.so) to the library file name.
+ \brief Convert the given parameter to the platform-specific library name.
+
+ The function appends platform-specific prefix (lib) and suffix (.dll/.so)
+ to the library file name.
+ For example, if \a str = "mylib", "libmylib.so" is returned for Linux and
+ mylib.dll for Windows.
+
+ \param str short library name
+ \return full library name
*/
QString Qtx::library( const QString& str )
{
QString libExt( "so" );
#endif
- if ( ext.lower() != QString( "so" ) && ext.lower() != QString( "dll" ) )
+ if ( ext.toLower() != QString( "so" ) && ext.toLower() != QString( "dll" ) )
{
if ( !name.isEmpty() && !ext.isEmpty() )
name += QString( "." );
}
/*!
- Name: tmpDir [static public]
- Desc: Returns path to temporary directory.
+ \brief Get the temporary directory name.
+ \return temporary directory (platform specific)
*/
QString Qtx::tmpDir()
{
- char* tmpdir = ::getenv( "TEMP" );
- if ( !tmpdir )
- tmpdir = ::getenv ( "TMP" );
- if ( !tmpdir )
- {
+ char* tmpdir = ::getenv( "TEMP" );
+ if ( !tmpdir )
+ tmpdir = ::getenv ( "TMP" );
+ if ( !tmpdir )
+ {
#ifdef WIN32
- tmpdir = "C:\\";
+ tmpdir = "C:\\";
#else
- tmpdir = "/tmp";
+ tmpdir = "/tmp";
#endif
- }
- return QString( tmpdir );
+ }
+ return QString( tmpdir );
}
/*!
- Name: mkDir [static public]
- Desc: Creates directory with intermediate perent directories.
- Returns true in successfull case.
+ \brief Create directory recursively including all intermediate sub directories.
+ \return \c true if the directory is successfully created and \c false otherwise
*/
bool Qtx::mkDir( const QString& dirPath )
{
- QString path = QDir::convertSeparators( dirPath );
-
-#ifdef WIN32
- while ( !path.isEmpty() && path.at( path.length() - 1 ) == QDir::separator() )
- path.remove( path.length() - 1, 1 );
-
- if ( path.at( path.length() - 1 ) == ':' )
- return QFileInfo( path ).exists();
-#endif
-
- QFileInfo fInfo( path );
- if ( fInfo.exists() )
- return fInfo.isDir();
-
- if ( !mkDir( fInfo.dirPath() ) )
- return false;
-
- return QDir( fInfo.dirPath() ).mkdir( fInfo.fileName() );
+ return QDir().mkpath( dirPath );
}
/*!
- Name: rmDir [static public]
- Desc: Removes directory with its subdirectories and files.
- Returns true in successfull case.
+ \brief Remove directory recursively including all subdirectories and files.
+ \return \c true if the directory is successfully removed and \c false otherwise
*/
bool Qtx::rmDir( const QString& thePath )
{
- QFileInfo fi( thePath );
- if ( !fi.exists() )
- return true;
-
- bool stat = true;
- if ( fi.isFile() )
- stat = QFile::remove( thePath );
- else if ( fi.isDir() )
- {
- QDir aDir( thePath );
- const QFileInfoList* anEntries = aDir.entryInfoList();
- if ( anEntries )
- {
- for ( QPtrListIterator<QFileInfo> it( *anEntries ); it.current(); ++it )
- {
- if ( it.current()->fileName() == "." || it.current()->fileName() == ".." )
- continue;
- stat = stat && rmDir( it.current()->absFilePath() );
- }
- }
- stat = stat && aDir.rmdir( thePath );
- }
- return stat;
+ QFileInfo fi( thePath );
+ if ( !fi.exists() )
+ return true;
+
+ bool stat = true;
+ if ( fi.isFile() )
+ stat = QFile::remove( thePath );
+ else if ( fi.isDir() )
+ {
+ QDir aDir( thePath );
+ QFileInfoList anEntries = aDir.entryInfoList();
+ for ( QFileInfoList::iterator it = anEntries.begin(); it != anEntries.end(); ++it )
+ {
+ QFileInfo inf = *it;
+ if ( inf.fileName() == "." || inf.fileName() == ".." )
+ continue;
+ stat = stat && rmDir( inf.absoluteFilePath() );
+ }
+ stat = stat && aDir.rmdir( thePath );
+ }
+ return stat;
}
/*!
- Name: addSlash [static public]
- Desc: Adds a slash to the end of 'path' if it is not already there.
+ \brief Add a slash (platform-specific) to the end of \a path
+ if it is not already there.
+ \param path directory path
+ \return modified path (with slash added to the end)
*/
QString Qtx::addSlash( const QString& path )
{
- QString res = path;
+ QString res = path;
if ( !res.isEmpty() && res.at( res.length() - 1 ) != QChar( '/' ) &&
- res.at( res.length() - 1 ) != QChar( '\\' ) )
+ res.at( res.length() - 1 ) != QChar( '\\' ) )
res += QDir::separator();
return res;
}
/*!
- Name: dos2unix [static public]
- Desc: Convert text file. Replace symbols "LF/CR" by symbol "LF".
+ \brief Convert text file from DOS format to UNIX.
+
+ The function replaces "LF/CR" symbols sequence by "LF" symbol.
+
+ \param absName file name
+ \return \c true if the file is converted successfully and \c false in
+ case of any error
*/
bool Qtx::dos2unix( const QString& absName )
{
- FILE* src = ::fopen( absName, "rb" );
+ FILE* src = ::fopen( absName.toLatin1(), "rb" );
if ( !src )
- return false;
+ return false;
/* we'll use temporary file */
char temp[512] = { '\0' };
QString dir = Qtx::dir( absName );
- FILE* tgt = ::fopen( strcpy( temp, ::tempnam( dir, "__x" ) ), "wb" );
+ FILE* tgt = ::fopen( strcpy( temp, ::tempnam( dir.toLatin1(), "__x" ) ), "wb" );
if ( !tgt )
- return false;
+ return false;
/* temp -> result of conversion */
const char CR = 0x0d;
break; /* converted ok */
}
::fclose( src );
- ::fclose( tgt );
+ ::fclose( tgt );
/* rename temp -> src */
if ( !QFile::remove( absName ) )
}
/*!
- Name: rgbSet [static public]
- Desc: Pack the specified color into one integer RGB set.
+ \brief Pack the specified color into integer RGB set.
+ \param c unpacked color
+ \return packed color
*/
int Qtx::rgbSet( const QColor& c )
{
}
/*!
- Name: rgbSet [static public]
- Desc: Pack the specified color components into one integer RGB set.
+ \brief Pack the specified RGB color components into integer RGB set.
+ \param r red component
+ \param g green component
+ \param b blue component
+ \return packed color
*/
int Qtx::rgbSet( const int r, const int g, const int b )
{
}
/*!
- Name: rgbSet [static public]
- Desc: Unpack the specified integer RGB set into the color.
+ \brief Unpack the specified integer RGB set to the color.
+ \param rgb packed color
+ \return unpacked color (QColor)
*/
-void Qtx::rgbSet( const int rgb, QColor& c )
+QColor Qtx::rgbSet( const int rgb )
{
int r, g, b;
rgbSet( rgb, r, g, b );
- c = QColor( r, g, b );
+ return QColor( r, g, b );
}
/*!
- Name: rgbSet [static public]
- Desc: Unpack the specified integer RGB set into the color components.
+ \brief Unpack the specified integer RGB set to the three RGB components.
+ \param rgb packed color
+ \param r returned unpacked red component
+ \param g returned unpacked green component
+ \param b returned unpacked blue component
*/
void Qtx::rgbSet( const int rgb, int& r, int& g, int& b )
{
}
/*!
- Name: scaleColor [static public]
- Desc: Returns the color specified by the index between min (blue) and max (red).
+ \brief Return the color specified by the index between min (blue) and max (red).
+ \param index color index
+ \param min required minimum hue value
+ \param max required maximum hue value
+ \return resulting color
*/
QColor Qtx::scaleColor( const int index, const int min, const int max )
{
int hue = HUE[0];
- if ( min != max )
+ if ( min != max )
{
double aPosition = 9.0 * ( index - min ) / ( max - min );
if ( aPosition > 0.0 )
}
}
- return QColor( hue, 255, 255, QColor::Hsv );
+ return QColor::fromHsv( hue, 255, 255 );
}
/*!
- Name: scaleColors [static public]
- Desc: Returns the 'num' number of colors from blue to red.
+ \brief Generate required number of colors aligned from blue to red.
+ \param num required number of colors
+ \param lst returned set of colors
*/
-void Qtx::scaleColors( const int num, QValueList<QColor>& lst )
+void Qtx::scaleColors( const int num, QColorList& lst )
{
lst.clear();
for ( int i = 0; i < num; i++ )
}
/*!
- Name: grayscale [static public]
- Desc: Convert color image to grayscale image.
+ \brief Convert given image to the grayscale format.
+ \param img initial image
+ \return converted to the grayscale image
*/
QImage Qtx::grayscale( const QImage& img )
{
}
/*!
- Name: grayscale [static public]
- Desc: Convert color pixmap to grayscale pixmap.
+ \brief Convert given pixmap to the grayscale format.
+ \param pix initial pixmap
+ \return converted to the grayscale pixmap
*/
QPixmap Qtx::grayscale( const QPixmap& pix )
{
QPixmap res;
- res.convertFromImage( grayscale( pix.convertToImage() ) );
+ res.fromImage( grayscale( pix.toImage() ) );
return res;
}
/*!
- Name: transparentImage [static public]
- Desc: Create transparent image with specified width \aw, height \ah and color depth \ad.
+ \brief Create transparent image.
+ \param w required image width
+ \param h required image height
+ \param d required image depth
+ \return generated image
*/
QImage Qtx::transparentImage( const int w, const int h, const int d )
{
- QImage img;
- if ( img.create( w, h, d < 0 ? QPixmap::defaultDepth() : d ) )
+ QImage::Format fmt;
+ switch ( d )
+ {
+ case 1:
+ fmt = QImage::Format_Mono;
+ break;
+ case 8:
+ fmt = QImage::Format_Indexed8;
+ break;
+ case 16:
+ case 24:
+ case 32:
+ default:
+ fmt = QImage::Format_ARGB32;
+ break;
+ }
+
+ QImage img( w, h, fmt );
+ if ( !img.isNull() )
{
- img.setAlphaBuffer( true );
+// img.setAlphaBuffer( true );
for ( int i = 0; i < img.height(); i++ )
for ( int j = 0; j < img.width(); j++ )
img.setPixel( j, i, qRgba( 0, 0, 0, 0 ) );
}
/*!
- Name: transparentPixmap [static public]
- Desc: Create transparent pixmap with specified width \aw, height \ah and color depth \ad.
+ \brief Create transparent pixmap.
+ \param w required image width
+ \param h required pixmap height
+ \param d required pixmap depth
+ \return generated pixmap
*/
QPixmap Qtx::transparentPixmap( const int w, const int h, const int d )
{
QPixmap pix;
QImage img = transparentImage( w, h, d );
if ( !img.isNull() )
- pix.convertFromImage( img );
+ pix.fromImage( img );
return pix;
}
/*!
- Name: composite [static public]
- Desc: Create composite pixmap. Pixmap 'pix' draws over pixmap 'dest' with coordinates
- specified relative upper left corner of 'dest'. If 'dest' not given then new empty
- pixmap with appropriate size created.
+ \brief Create composite pixmap.
+
+ Pixmap \a pix is drawn over pixmap \a dest with coordinates
+ specified relatively to the upper left corner of \a dest.
+ If \a dest is not given, the new empty pixmap with appropriate size created instead.
+
+ \param pix source pixmap
+ \param x horizontal shift
+ \param y vertical shift
+ \param dest background pixmap
+ \return resulting pixmap
*/
QPixmap Qtx::composite( const QPixmap& pix, const int x, const int y, const QPixmap& dest )
{
if ( pix.isNull() )
return dest;
- int width = QMAX( pix.width() + x, dest.width() );
- int height = QMAX( pix.height() + y, dest.height() );
+ int width = qMax( pix.width() + x, dest.width() );
+ int height = qMax( pix.height() + y, dest.height() );
QPixmap res( width, height );
QImage img = transparentImage( width, height, 32 );
QPainter p;
p.begin( &res );
- p.fillRect( 0, 0, width, height, QBrush( white ) );
+ p.fillRect( 0, 0, width, height, QBrush( Qt::white ) );
if ( !dest.isNull() )
{
p.drawPixmap( 0, 0, dest );
- QImage temp = dest.convertToImage();
+ QImage temp = dest.toImage();
for ( int i = 0; i < temp.width() && i < img.width(); i++ )
{
for ( int j = 0; j < temp.height() && j < img.height(); j++ )
{
- if ( temp.hasAlphaBuffer() )
+ if ( temp.hasAlphaChannel() )
img.setPixel( i, j, temp.pixel( i, j ) );
else
{
}
p.drawPixmap( x, y, pix );
- QImage temp = pix.convertToImage();
+ QImage temp = pix.toImage();
for ( int c = x; c < temp.width() + x && c < img.width(); c++ )
{
for ( int r = y; r < temp.height() + y && r < img.height(); r++ )
}
QBitmap bmp( width, height );
- bmp.convertFromImage( img, Qt::ColorMode_Mask | Qt::ThresholdDither );
+ bmp.fromImage( img, Qt::ColorMode_Mask | Qt::ThresholdDither );
res.setMask( bmp );
return res;
#define true 1
#endif
-#ifndef INCLUDE_MENUITEM_DEF
-#define INCLUDE_MENUITEM_DEF
-#endif
-
-#include <qnamespace.h>
-
-#ifndef QT_VERSION
-#define QT_VER 0
-#else
-#if QT_VERSION >= 0x30000
-#define QT_VER 3
-#else
-#if QT_VERSION >= 300
-#define QT_VER 3
-#else
-#if QT_VERSION >= 200
-#define QT_VER 2
-#else
-#if QT_VERSION >= 100
-#define QT_VER 1
-#endif
-#endif
-#endif
-#endif
-#endif
-
-#include <qimage.h>
-#include <qpixmap.h>
+#include <QString>
+#include <QList>
+#include <QColor>
+#include <QImage>
+#include <QPixmap>
class QObject;
-class QString;
class QWidget;
-class QToolBar;
-class QGroupBox;
-class QPopupMenu;
-class QWidgetList;
-template <class> class QValueList;
+typedef QList<int> QIntList; //!< list of int values
+typedef QList<short> QShortList; //!< list of short int values
+typedef QList<double> QDoubleList; //!< list of double values
+typedef QList<QColor> QColorList; //!< list of colors
-#if QT_VER < 3
-#define QPtrList QList
-#define QPtrListIterator QListIterator
-#endif
-
-typedef QValueList<int> QIntList;
-typedef QValueList<short> QShortList;
-typedef QValueList<double> QDoubleList;
-
-/*!
- \class Qtx
- \brief Set of auxiliary static methods
-*/
-class QTX_EXPORT Qtx : public Qt
+class QTX_EXPORT Qtx
{
public:
+ //! Widget alignment flags
enum AlignmentFlags
{
- AlignOutLeft = AlignVCenter << 2,
- AlignOutRight = AlignOutLeft << 2,
- AlignOutTop = AlignOutRight << 2,
- AlignOutBottom = AlignOutTop << 2
+ AlignLeft = Qt::AlignLeft, //!< align left side of one widget to the left side of another widget
+ AlignLeading = Qt::AlignLeading, //!< synonim for AlignLeft
+ AlignRight = Qt::AlignRight, //!< align right side of one widget to the right side of another widget
+ AlignTrailing = Qt::AlignTrailing, //!< synonim for AlignRight
+ AlignHCenter = Qt::AlignHCenter, //!< align one widget to the center of another widget in horizontal dimension
+ AlignJustify = Qt::AlignJustify, //!< synonym of Qt::AlignJustify
+ AlignAbsolute = Qt::AlignAbsolute, //!< synonym of Qt::AlignAbsolute
+ AlignHorizontal_Mask = Qt::AlignHorizontal_Mask, //!< synonym of Qt::AlignHorizontal_Mask
+
+ AlignTop = Qt::AlignTop, //!< align top side of one widget to the top side of another widget
+ AlignBottom = Qt::AlignBottom, //!< align bottom side of one widget to the bottom side of another widget
+ AlignVCenter = Qt::AlignVCenter, //!< align one widget to the center of another widget in vertical dimension
+ AlignVertical_Mask = Qt::AlignVertical_Mask, //!< synonym of Qt::AlignVertical_Mask
+
+ AlignCenter = Qt::AlignCenter, //!< align one widget to the center of another widget in both dimensions
+
+ AlignOutLeft = Qt::AlignVCenter << 2, //!< align right side of one widget to the left side of another widget
+ AlignOutRight = AlignOutLeft << 2, //!< align left side of one widget to the right side of another widget
+ AlignOutTop = AlignOutRight << 2, //!< align bottom side of one widget to the top side of another widget
+ AlignOutBottom = AlignOutTop << 2 //!< align top side of one widget to the bottom side of another widget
};
+ static QString toQString( const char*, const int = -1 );
+ static QString toQString( const short*, const int = -1 );
+ static QString toQString( const unsigned char*, const int = -1 );
+ static QString toQString( const unsigned short*, const int = -1 );
+
static void setTabOrder( QWidget*, ... );
static void setTabOrder( const QWidgetList& );
static void alignWidget( QWidget*, const QWidget*, const int );
- static void simplifySeparators( QToolBar* );
- static void simplifySeparators( QPopupMenu*, const bool = true );
+ static void simplifySeparators( QWidget*, const bool = true );
static bool isParent( QObject*, QObject* );
- static QString extension( const QString& );
static QString dir( const QString&, const bool = true );
static QString file( const QString&, const bool = true );
+ static QString extension( const QString&, const bool = false );
static QString library( const QString& );
static int rgbSet( const QColor& );
static int rgbSet( const int, const int, const int );
- static void rgbSet( const int, QColor& );
+ static QColor rgbSet( const int );
static void rgbSet( const int, int&, int&, int& );
static QColor scaleColor( const int, const int, const int );
- static void scaleColors( const int, QValueList<QColor>& );
+ static void scaleColors( const int, QColorList& );
static QImage grayscale( const QImage& );
static QPixmap grayscale( const QPixmap& );
--- /dev/null
+TEMPLATE = lib
+TARGET = qtx
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+QT += xml
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += QTX_EXPORTS
+
+HEADERS = Qtx.h
+HEADERS += QtxAction.h
+HEADERS += QtxActionMenuMgr.h
+HEADERS += QtxActionMgr.h
+HEADERS += QtxActionSet.h
+HEADERS += QtxActionToolMgr.h
+HEADERS += QtxColorScale.h
+HEADERS += QtxComboBox.h
+HEADERS += QtxDialog.h
+HEADERS += QtxDockAction.h
+HEADERS += QtxDockWidget.h
+HEADERS += QtxDoubleSpinBox.h
+HEADERS += QtxEvalExpr.h
+HEADERS += QtxGridBox.h
+HEADERS += QtxGroupBox.h
+HEADERS += QtxIntSpinBox.h
+HEADERS += QtxListAction.h
+HEADERS += QtxLogoMgr.h
+HEADERS += QtxMainWindow.h
+HEADERS += QtxMap.h
+HEADERS += QtxMRUAction.h
+HEADERS += QtxPathDialog.h
+HEADERS += QtxPopupMgr.h
+HEADERS += QtxResourceMgr.h
+HEADERS += QtxSplash.h
+HEADERS += QtxToolBar.h
+HEADERS += QtxToolTip.h
+HEADERS += QtxValidator.h
+HEADERS += QtxWorkspace.h
+HEADERS += QtxWorkspaceAction.h
+HEADERS += QtxWorkstack.h
+HEADERS += QtxWorkstackAction.h
+#HEADERS += QtxDirListEditor.h
+#HEADERS += QtxListBox.h
+#HEADERS += QtxListResourceEdit.h
+#HEADERS += QtxListView.h
+#HEADERS += QtxPopupMenu.h
+#HEADERS += QtxResourceEdit.h
+#HEADERS += QtxTable.h
+
+SOURCES = Qtx.cxx
+SOURCES += QtxAction.cxx
+SOURCES += QtxActionMenuMgr.cxx
+SOURCES += QtxActionMgr.cxx
+SOURCES += QtxActionSet.cxx
+SOURCES += QtxActionToolMgr.cxx
+SOURCES += QtxColorScale.cxx
+SOURCES += QtxComboBox.cxx
+SOURCES += QtxDialog.cxx
+SOURCES += QtxDockAction.cxx
+SOURCES += QtxDockWidget.cxx
+SOURCES += QtxDoubleSpinBox.cxx
+SOURCES += QtxEvalExpr.cxx
+SOURCES += QtxGridBox.cxx
+SOURCES += QtxGroupBox.cxx
+SOURCES += QtxIntSpinBox.cxx
+SOURCES += QtxListAction.cxx
+SOURCES += QtxLogoMgr.cxx
+SOURCES += QtxMainWindow.cxx
+SOURCES += QtxMRUAction.cxx
+SOURCES += QtxPathDialog.cxx
+SOURCES += QtxPopupMgr.cxx
+SOURCES += QtxResourceMgr.cxx
+SOURCES += QtxSplash.cxx
+SOURCES += QtxToolBar.cxx
+SOURCES += QtxToolTip.cxx
+SOURCES += QtxValidator.cxx
+SOURCES += QtxWorkspace.cxx
+SOURCES += QtxWorkspaceAction.cxx
+SOURCES += QtxWorkstack.cxx
+SOURCES += QtxWorkstackAction.cxx
+#SOURCES += QtxDirListEditor.cxx
+#SOURCES += QtxListBox.cxx
+#SOURCES += QtxListResourceEdit.cxx
+#SOURCES += QtxListView.cxx
+#SOURCES += QtxPopupMenu.cxx
+#SOURCES += QtxResourceEdit.cxx
+#SOURCES += QtxTable.cxx
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+INSTALLS += includes
#include "QtxAction.h"
-#include <qpopupmenu.h>
-#include <qmenubar.h>
+#include <QEvent>
+#include <QActionEvent>
+#include <QApplication>
+
+class QtxAction::ActionNotify : public QEvent
+{
+public:
+ ActionNotify( bool add, QWidget* wid ) : QEvent( QEvent::User ), myAdd( add ), myWidget( wid ) {};
+ ~ActionNotify() {};
+
+ bool isAdded() const { return myAdd; }
+ QWidget* widget() const { return myWidget; }
+
+private:
+ bool myAdd;
+ QWidget* myWidget;
+};
/*!
- Name: QtxAction [public]
- Desc: Constructs an action with given parent and name. If toggle is true the
- action will be a toggle action, otherwise it will be a command action.
+ \class QtxAction
+ \brief Generic action class.
*/
-QtxAction::QtxAction( QObject* parent, const char* name, bool toggle )
- : QAction( parent, name, toggle )
+/*!
+ \brief Constructor.
+
+ Create an action.
+
+ \param parent parent object
+ \param name action name (in terms of QObject)
+ \param toggle if \c true the action is a toggle action
+*/
+QtxAction::QtxAction( QObject* parent, bool toggle )
+: QWidgetAction( parent )
{
+ setCheckable( toggle );
+
+ QApplication::instance()->installEventFilter( this );
}
/*!
- Name: QtxAction [public]
- Desc: This constructor creates an action with the following properties: the
- description text, the icon or iconset icon, the menu text and keyboard
- accelerator. It is a child of given parent and named specified name.
- If toggle is true the action will be a toggle action, otherwise it will
- be a command action.
-*/
+ \brief Constructor.
+
+ Create an action.
-QtxAction::QtxAction( const QString& text, const QIconSet& icon,
- const QString& menuText, int accel,
- QObject* parent, const char* name, bool toggle )
- : QAction( text, icon, menuText, accel, parent, name, toggle )
+ \param text tooltip text
+ \param icon iconset
+ \param menuText menu text
+ \param accel shortcut key sequence
+ \param parent parent object
+ \param name action name (in terms of QObject)
+ \param toggle if \c true the action is a toggle action
+*/
+QtxAction::QtxAction( const QString& text, const QIcon& icon,
+ const QString& menuText, int accel, QObject* parent, bool toggle )
+: QWidgetAction( parent )
{
+ setIcon( icon );
+ setText( menuText );
+ setToolTip( text );
+ setShortcut( accel );
+ setCheckable( toggle );
+
+ QApplication::instance()->installEventFilter( this );
}
/*!
- Name: QtxAction [public]
- Desc: This constructor creates an action with the following properties: the
- description text, the menu text and keyboard accelerator. It is a child
- of given parent and named specified name. If toggle is true the action
- will be a toggle action, otherwise it will be a command action.
-*/
+ \brief Constructor.
-QtxAction::QtxAction( const QString& text, const QString& menuText, int accel,
- QObject* parent, const char* name, bool toggle )
- : QAction( text, menuText, accel, parent, name, toggle )
+ Create an action.
+
+ \param text tooltip text
+ \param menuText menu text
+ \param accel shortcut key sequence
+ \param parent parent object
+ \param name action name (in terms of QObject)
+ \param toggle if \c true the action is a toggle action
+*/
+QtxAction::QtxAction( const QString& text, const QString& menuText,
+ int accel, QObject* parent, bool toggle )
+: QWidgetAction( parent )
{
+ setText( menuText );
+ setToolTip( text );
+ setShortcut( accel );
+ setCheckable( toggle );
+
+ QApplication::instance()->installEventFilter( this );
}
/*!
- Name: ~QtxAction [virtual public]
- Desc: Destructor.
+ \brief Destructor.
+
+ Does nothing for the moment.
*/
-
QtxAction::~QtxAction()
{
}
/*!
- Name: addTo [virtual public]
- Desc: Adds this action to widget. Returns true if the action was added
- successfully and false otherwise.
+ \brief Event filter.
+
+ Redefined from QObject. Calls virtual methods when the action is added to
+ the widget or removed from it in order to perform custom processing.
+ \param o object
+ \param e event
+ \return default implementation
*/
-
-bool QtxAction::addTo( QWidget* w )
+bool QtxAction::eventFilter( QObject* o, QEvent* e )
{
- if ( w->inherits( "QMenuBar" ) ) {
- // --- Add action to the QMenuBar ---
- // n.b. currently for the actions inserted to the menu bar
- // the following properties are not supported:
- // * tooltips
- // * what's this info
- // * toggle mode
- QMenuBar* mb = (QMenuBar*)w;
- if ( myMenuIds.find( w ) != myMenuIds.end() )
- return false; // already added
- if ( name() == "qt_separator_action" ) // separator
- myMenuIds[ w ] = mb->insertSeparator();
- else if ( iconSet().isNull() ) // has no icon
- myMenuIds[ w ] = mb->insertItem( menuText(), this, SIGNAL( activated() ), accel() );
- else // has icon
- myMenuIds[ w ] = mb->insertItem( iconSet(), menuText(), this, SIGNAL( activated() ), accel() );
- mb->setItemEnabled( myMenuIds[ w ], isEnabled() );
- mb->setItemVisible( myMenuIds[ w ], isVisible() );
- return true;
+ if ( o && o->isWidgetType() )
+ {
+ if ( e->type() == QEvent::ActionAdded && ((QActionEvent*)e)->action() == this )
+ QApplication::postEvent( this, new ActionNotify( true, (QWidget*)o ) );
+ if ( e->type() == QEvent::ActionRemoved && ((QActionEvent*)e)->action() == this )
+ QApplication::postEvent( this, new ActionNotify( false, (QWidget*)o ) );
}
- return QAction::addTo( w );
+ return QWidgetAction::eventFilter( o, e );
}
/*!
- Name: addTo [virtual public]
- Desc: Adds this action to widget. If widget is QPopupMenu given index will
- be used for menu item inserting. Returns true if the action was added
- successfully and false otherwise.
+ \brief Add action to widget.
+ \param w widget (menu or toolbar)
+ \return \c true if the action is added successfully and \c false otherwise.
*/
+bool QtxAction::addTo( QWidget* w )
+{
+ if ( !w )
+ return false;
+ w->addAction( this );
+ return true;
+}
+
+/*!
+ \brief Add action to widget.
+
+ The function adds the action to the menu or toolbar widget at the
+ specified \a index. If \a index is negative or greater than number of
+ items in the menu/toolbar, the action is added to the end of list.
+
+ \param w widget (menu or toolbar)
+ \param index index of the action in the action list
+ \return \c true if the action is added successfully and \c false otherwise.
+*/
bool QtxAction::addTo( QWidget* w, const int index )
{
- if ( !addTo( w ) )
+ if ( !w )
return false;
- if ( w->inherits( "QPopupMenu" ) ) {
- // --- Add action to the QPopupMenu ---
- QPopupMenu* popup = (QPopupMenu*)w;
- if ( index >= 0 && index < (int)popup->count() - 1 ) {
- int id = popup->idAt( popup->count() - 1 );
- if ( id != -1 ) {
- QMenuItem* item = popup->findItem( id );
- if ( item && item->isSeparator() ) {
- popup->removeItem( id );
- popup->insertSeparator( index );
- }
- else {
- QPopupMenu* p = item ? item->popup() : 0;
- int accel = popup->accel( id );
- bool isOn = popup->isItemEnabled( id );
- bool isVisible = popup->isItemVisible( id );
- bool isChecked = popup->isItemChecked( id );
- QString text = popup->text( id );
- QIconSet icon;
- if ( popup->iconSet( id ) )
- icon = *popup->iconSet( id );
- popup->removeItem( id );
- int pos;
- if ( icon.isNull() )
- if ( p )
- pos = popup->indexOf( popup->insertItem( text, p, id, index ) );
- else
- pos = popup->indexOf( popup->insertItem( text, id, index ) );
- else
- if ( p )
- pos = popup->indexOf( popup->insertItem( icon, text, p, id, index ) );
- else
- pos = popup->indexOf( popup->insertItem( icon, text, p, id, index ) );
- popup->setId( pos, id );
- popup->setAccel( accel, id );
- popup->setItemEnabled( id, isOn );
- popup->setItemVisible( id, isVisible );
- popup->setItemChecked( id, isChecked );
- if ( !whatsThis().isEmpty() )
- popup->setWhatsThis( id, whatsThis() );
- if ( !p )
- popup->connectItem( id, this, SLOT( internalActivation() ) );
- }
- }
- }
- }
- else if ( w->inherits( "QMenuBar" ) ) {
- // --- Add action to the QMenuBar ---
- QMenuBar* mb = (QMenuBar*)w;
- if ( index >= 0 && index < (int)mb->count() - 1 ) {
- int id = mb->idAt( mb->count() - 1 );
- if ( id != -1 ) {
- QMenuItem* item = mb->findItem( id );
- if ( item && item->isSeparator() ) {
- mb->removeItem( id );
- mb->insertSeparator( index );
- }
- else {
- QPopupMenu* p = item ? item->popup() : 0;
- int accel = mb->accel( id );
- bool isOn = mb->isItemEnabled( id );
- bool isVisible = mb->isItemVisible( id );
- QString text = mb->text( id );
- QIconSet icon;
- if ( mb->iconSet( id ) )
- icon = *mb->iconSet( id );
- mb->removeItem( id );
- int pos;
- if ( icon.isNull() )
- if ( p )
- pos = mb->indexOf( mb->insertItem( text, p, id, index ) );
- else
- pos = mb->indexOf( mb->insertItem( text, id, index ) );
- else
- if ( p )
- pos = mb->indexOf( mb->insertItem( icon, text, p, id, index ) );
- else
- pos = mb->indexOf( mb->insertItem( icon, text, p, id, index ) );
- mb->setId( pos, id );
- mb->setAccel( accel, id );
- mb->setItemEnabled( id, isOn );
- mb->setItemVisible( id, isVisible );
- if ( !p )
- mb->connectItem( id, this, SIGNAL( activated() ) );
- }
- }
- }
- }
+ QAction* b = 0;
+ if ( 0 <= index && index < w->actions().count() )
+ b = w->actions().at( index );
+
+ w->insertAction( b, this );
+
return true;
}
/*!
- Name: removeFrom [virtual public]
- Desc: Removes this action from widget. Returns true if the action was removed
- successfully and false otherwise.
+ \brief Remove action from widget.
+ \param w widget (menu or toolbar)
+ \return \c true if the action is removed successfully and \c false otherwise.
*/
-
bool QtxAction::removeFrom( QWidget* w )
{
- // check if widget is QMenuBar
- if ( w->inherits( "QMenuBar" ) ) {
- QMenuBar* mb = (QMenuBar*)w;
- if ( myMenuIds.find( w ) == myMenuIds.end() )
- return false; // not yet added
- mb->removeItem( myMenuIds[ w ] );
- myMenuIds.remove( w );
- return true;
- }
- return QAction::removeFrom( w );
+ if ( !w )
+ return false;
+
+ w->removeAction( this );
+ return true;
}
/*!
- Name: setPopup [virtual public]
- Desc: Set or unset the sub popup menu for item with specified id in the given popup.
-*/
+ \brief Called when the action is added to the widget.
+
+ Base implementation does nothing. Can be redefined in the successor
+ class to customize the behavior.
-void QtxAction::setPopup( QWidget* w, const int id, QPopupMenu* subPopup ) const
+ \param w widget (menu or toolbar)
+*/
+void QtxAction::addedTo( QWidget* )
{
- if ( !w )
- return;
-
- QMenuData* pmd = 0;
-
- if ( w->inherits( "QPopupMenu" ) )
- pmd = ::qt_cast<QPopupMenu*>( w );
- else if ( w->inherits( "QMenuBar" ) )
- pmd = ::qt_cast<QMenuBar*>( w );
-
- if ( !pmd )
- return; // bad widget
-
- QMenuData* md = 0;
- QMenuItem* item = pmd->findItem( id, &md );
- if ( !item || md != pmd )
- return; // item is not found
-
- QPopupMenu* oldPopup = item->popup();
- if ( oldPopup == subPopup )
- return; // popup is not changed
-
- // get properties
- int accel = pmd->accel( id );
- bool isOn = pmd->isItemEnabled( id );
- bool isVisible = pmd->isItemVisible( id );
- int pos = pmd->indexOf( id );
- QString text = pmd->text( id );
- QIconSet icon;
- if ( pmd->iconSet( id ) )
- icon = *pmd->iconSet( id );
-
- // remove previous item
- pmd->removeItem( id );
-
- // add new item
- if ( w->inherits( "QPopupMenu" ) ) {
- // --- QPopupMenu ---
- QPopupMenu* popup = (QPopupMenu*)w;
- if ( icon.isNull() )
- pos = popup->indexOf( subPopup ? popup->insertItem( text, subPopup, id, pos ) :
- popup->insertItem( text, id, pos ) );
- else
- pos = popup->indexOf( subPopup ? popup->insertItem( icon, text, subPopup, id, pos ) :
- popup->insertItem( icon, text, id, pos ) );
- }
- else {
- // --- QMenuBar ---
- QMenuBar* mb = (QMenuBar*)w;
- if ( icon.isNull() )
- pos = mb->indexOf( subPopup ? mb->insertItem( text, subPopup, id, pos ) :
- mb->insertItem( text, id, pos ) );
- else
- pos = mb->indexOf( subPopup ? mb->insertItem( icon, text, subPopup, id, pos ) :
- mb->insertItem( icon, text, id, pos ) );
- }
+}
- // restore properties
- pmd->setId( pos, id ); // for sure (if id < 0)
- pmd->setAccel( accel, id );
- pmd->setItemEnabled( id, isOn );
- pmd->setItemVisible( id, isVisible );
+/*!
+ \brief Called when the action is removed from the widget.
+
+ Base implementation does nothing. Can be redefined in the successor
+ class to customize the behavior.
- // delete old popup
- delete oldPopup;
+ \param w widget (menu or toolbar)
+*/
+void QtxAction::removedFrom( QWidget* )
+{
}
+void QtxAction::customEvent( QEvent* e )
+{
+ ActionNotify* ae = (ActionNotify*)e;
+ if ( ae->isAdded() )
+ addedTo( ae->widget() );
+ else
+ removedFrom( ae->widget() );
+}
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-// File: QtxAction.hxx
+// File: QtxAction.h
// Author: Sergey TELKOV
#ifndef QTXACTION_H
#include "Qtx.h"
-#include <qaction.h>
-#include <qmap.h>
+#include <QWidgetAction>
+
+class QIcon;
#ifdef WIN32
#pragma warning ( disable:4251 )
#endif
-class QTX_EXPORT QtxAction : public QAction
+class QTX_EXPORT QtxAction : public QWidgetAction
{
- Q_OBJECT
+ Q_OBJECT
+
+ class ActionNotify;
public:
- QtxAction( QObject* = 0, const char* = 0, bool = false );
- QtxAction( const QString&, const QString&, int, QObject*, const char* = 0, bool = false );
- QtxAction( const QString&, const QIconSet&, const QString&, int, QObject*, const char* = 0, bool = false );
- virtual ~QtxAction();
+ QtxAction( QObject* = 0, bool = false );
+ QtxAction( const QString&, const QString&, int, QObject*, bool = false );
+ QtxAction( const QString&, const QIcon&, const QString&, int, QObject*, bool = false );
+ virtual ~QtxAction();
+
+ virtual bool eventFilter( QObject*, QEvent* );
- virtual bool addTo( QWidget* );
- virtual bool addTo( QWidget*, const int );
- virtual bool removeFrom( QWidget* );
+ virtual bool addTo( QWidget* );
+ virtual bool addTo( QWidget*, const int );
+ virtual bool removeFrom( QWidget* );
protected:
- void setPopup( QWidget*, const int, QPopupMenu* ) const;
+ virtual void addedTo( QWidget* );
+ virtual void removedFrom( QWidget* );
-private:
- QMap<QWidget*,int> myMenuIds;
+ virtual void customEvent( QEvent* );
};
#ifdef WIN32
// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
+//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
+// License as published by the Free Software Foundation; either
// version 2.1 of the License.
-//
-// This library 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
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#include "QtxAction.h"
-#include <qwidget.h>
-#include <qmenubar.h>
-#include <qpopupmenu.h>
-#include <qwidgetlist.h>
-#include <qobjectlist.h>
-#include <qmainwindow.h>
-#include <qfile.h>
-#include <qdom.h>
-#include <qvaluelist.h>
+#include <QMenu>
+#include <QMenuBar>
+#include <QWidget>
+#include <QMainWindow>
// VSR: Uncomment this #define in order to allow dynamic menus support
// (emit signals when popup menu is pre-activated)
// Currently this support is disabled.
//#define ENABLE_DYNAMIC_MENU
-
-/*!
- Service functions
- Level: Internal
-*/
-namespace {
- QValueList<int> prepareIds( const QWidget* w )
- {
- QValueList<int> l;
- const QMenuData* md = 0;
- if ( w->inherits( "QMenuBar" ) )
- md = ::qt_cast<QMenuBar*>( w );
- else if ( w->inherits( "QPopupMenu" ) )
- md = ::qt_cast<QPopupMenu*>( w );
- if ( md ) {
- for ( uint i = 0; i < md->count(); i++ )
- l.append( md->idAt( i ) );
- }
- return l;
- }
-
- int getNewId( const QWidget* w, const QValueList<int>& l, bool retId = true )
- {
- const QMenuData* md = 0;
- if ( w->inherits( "QMenuBar" ) )
- md = ::qt_cast<QMenuBar*>( w );
- else if ( w->inherits( "QPopupMenu" ) )
- md = ::qt_cast<QPopupMenu*>( w );
- if ( md )
- {
- for ( uint i = 0, j = 0; i < md->count() && j < l.count(); i++, j++ )
- if ( md->idAt( i ) != l[ j ] )
- return retId ? md->idAt( i ) : i;
- if ( md->count() > l.count() )
- return retId ? md->idAt( md->count()-1 ) : md->count() - 1;
- }
- return -1;
- }
-
- void dumpMenu( QWidget* w, bool before )
- {
- if ( !w )
- return;
-
- QMenuData* md = 0;
- if ( w->inherits( "QMenuBar" ) )
- md = ::qt_cast<QMenuBar*>( w );
- else if ( w->inherits( "QPopupMenu" ) )
- md = ::qt_cast<QPopupMenu*>( w );
-
- if ( !md )
- return;
-
- printf( ">>> start dump menu (%s) >>>\n", before ? "before" : "after" );
- for ( uint i = 0; i < md->count(); i++ )
- printf( "%d: %d: %s\n", i, md->idAt( i ), md->text( md->idAt( i ) ).latin1() );
- printf( "<<< end dump menu (%s) <<<\n", before ? "before" : "after" );
- }
-};
/*!
- Class: QtxActionMenuMgr::MenuAction
- Level: Internal
+ \class QtxActionMenuMgr::MenuNode
+ \internal
+ \brief Represents a menu item inside main menu structure.
*/
-class QtxActionMenuMgr::MenuAction : public QtxAction
-{
+class QtxActionMenuMgr::MenuNode {
public:
- MenuAction( const QString&, const QString&, QObject*, const int = -1, const bool = false );
- virtual ~MenuAction();
-
- virtual bool addTo( QWidget* );
-
- virtual bool removeFrom( QWidget* );
-
- QPopupMenu* popup() const;
-
-private:
- int myId;
- QPopupMenu* myPopup;
- bool myEmptyEnabled;
- QMap<QWidget*,int> myIds;
+ MenuNode();
+ MenuNode( MenuNode*, const int, const int, const int );
+ ~MenuNode();
+
+ MenuNode* parent; //!< parent menu node
+ int id; //!< menu nodeID
+ int idx; //!< menu node index
+ int group; //!< menu group ID
+ bool visible; //!< visibility status
+ NodeList children; //!< children menu nodes list
};
-
/*!
- Constructor for menu action
- \param text - description text
- \param menutext - menu text
- \param parent - parent object
- \param id - integer identificator of action
- \param allowEmpty - if it is true, it makes possible to add this action with empty popup to menu
+ \brief Default constructor.
*/
-
-QtxActionMenuMgr::MenuAction::MenuAction( const QString& text,
- const QString& menuText,
- QObject* parent,
- const int id,
- const bool allowEmpty )
-: QtxAction( text, menuText, 0, parent ),
- myId( id ),
- myPopup( 0 ),
- myEmptyEnabled( allowEmpty )
+QtxActionMenuMgr::MenuNode::MenuNode()
+: parent( 0 ), id( -1 ), idx( -1 ), group( -1 ), visible( true )
{
- myPopup = new QPopupMenu();
}
/*!
- Destructor: deletes internal popup
+ \brief Constructor.
+ \param p parent menu node
+ \param _id menu node ID
+ \param _idx menu node index
+ \param _group menu node group ID
*/
-QtxActionMenuMgr::MenuAction::~MenuAction()
+QtxActionMenuMgr::MenuNode::MenuNode( MenuNode* p,
+ const int _id,
+ const int _idx,
+ const int _group )
+: parent( p ), id( _id ), idx( _idx ), group( _group ), visible( true )
{
- delete myPopup;
+ if ( p )
+ p->children.append( this );
}
/*!
- Adds action to widget, for example, to popup menu or menu bar
+ \brief Destructor.
*/
-bool QtxActionMenuMgr::MenuAction::addTo( QWidget* w )
+QtxActionMenuMgr::MenuNode::~MenuNode()
{
- if ( !w )
- return false; // bad widget
-
- if ( !w->inherits( "QPopupMenu" ) && !w->inherits( "QMenuBar" ) )
- return false; // not allowed widget type
-
- if ( myIds.find( w ) != myIds.end() )
- return false; // already added
-
- if ( !myPopup )
- return false; // bad own popup menu
-
- if ( !myEmptyEnabled && !myPopup->count() )
- return false; // not allowed empty menu
-
- if ( w->inherits( "QPopupMenu" ) ) {
- QValueList<int> l = prepareIds( w );
- int idx;
- if ( QtxAction::addTo( w ) && ( idx = getNewId( w, l, false ) ) != -1 ) {
- QPopupMenu* pm = (QPopupMenu*)w;
- myIds[ w ] = pm->idAt( idx );
- if ( myId != -1 )
- pm->setId( idx, myId );
- setPopup( pm, myId != -1 ? myId : myIds[ w ], myPopup );
- }
- }
- else if ( w->inherits( "QMenuBar" ) ) {
- QValueList<int> l = prepareIds( w );
- int idx;
- if ( QtxAction::addTo( w ) && ( idx = getNewId( w, l, false ) ) != -1 ) {
- QMenuBar* mb = (QMenuBar*)w;
- myIds[ w ] = mb->idAt( idx );
- if ( myId != -1 )
- mb->setId( idx, myId );
- setPopup( mb, myId != -1 ? myId : myIds[ w ], myPopup );
- }
- }
- else
- return false;
-
- return true;
+ for ( NodeList::iterator it = children.begin(); it != children.end(); ++it )
+ delete *it;
}
/*!
- Removes action from widget, for example, from popup menu or menu bar
-*/
-bool QtxActionMenuMgr::MenuAction::removeFrom( QWidget* w )
-{
- if ( !w )
- return false; // bad widget
+ \class QtxActionMenuMgr
+ \brief Main menu actions manager.
- if ( !w->inherits( "QPopupMenu" ) && !w->inherits( "QMenuBar" ) )
- return false; // not allowed widget type
+ Menu manager allows using of set of action for automatic generating of
+ application main menu and dynamic update of its contents.
- if ( myIds.find( w ) == myIds.end() )
- return false; // not yet added
+ Use insert(), append() and remove() methods to create main menu.
+ Methods show(), hide() allow displaying/erasing of specified menu items.
- if ( w->inherits( "QPopupMenu" ) ) {
- if ( myId != -1 ) {
- QPopupMenu* pm = (QPopupMenu*)w;
- int idx = pm->indexOf( myId );
- if ( idx != -1 ) pm->setId( idx, myIds[ w ] );
- }
- myIds.remove( w );
- return QtxAction::removeFrom( w );;
- }
- else if ( w->inherits( "QMenuBar" ) )
- {
- if ( myId != -1 ) {
- QMenuBar* mb = (QMenuBar*)w;
- int idx = mb->indexOf( myId );
- if ( idx != -1 ) mb->setId( idx, myIds[ w ] );
- }
- myIds.remove( w );
- return QtxAction::removeFrom( w );
- }
- return false;
-}
+ Actions can be grouped with help of group identificator. Inside the popup
+ or main menu bar menu items are ordered by the group ID (ascending).
-/*!
- \return internal popup of action
+ Menu manager automatically optimizes the menu by removing extra separators,
+ hiding empty popup menus etc.
*/
-QPopupMenu* QtxActionMenuMgr::MenuAction::popup() const
-{
- return myPopup;
-}
/*!
- Class: QtxActionMenuMgr
- Level: Public
+ \brief Constructor.
+ \param p parent main window
*/
QtxActionMenuMgr::QtxActionMenuMgr( QMainWindow* p )
-: QtxActionMgr( p ),
+: QtxActionMgr( p ),
+ myRoot( new MenuNode() ),
myMenu( p ? p->menuBar() : 0 )
{
- myRoot.id = -1;
- myRoot.group = -1;
-
if ( myMenu ) {
connect( myMenu, SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
#ifdef ENABLE_DYNAMIC_MENU
}
/*!
- Constructor
+ \brief Constructor.
+ \param mw menu widget
+ \param p parent object
*/
QtxActionMenuMgr::QtxActionMenuMgr( QWidget* mw, QObject* p )
-: QtxActionMgr( p ),
+: QtxActionMgr( p ),
+ myRoot( new MenuNode() ),
myMenu( mw )
{
- myRoot.id = -1;
- myRoot.group = -1;
-
- if ( myMenu )
+ if ( myMenu ) {
connect( myMenu, SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
+#ifdef ENABLE_DYNAMIC_MENU
+ if ( myMenu->inherits( "QMenuBar" ) )
+ connect( myMenu, SIGNAL( highlighted( int ) ), this, SLOT( onHighlighted( int ) ) );
+#endif
+ }
}
/*!
- Destructor
+ \brief Destructor.
*/
QtxActionMenuMgr::~QtxActionMenuMgr()
{
- for ( NodeListIterator it( myRoot.children ); it.current() && myMenu; ++it )
+ for ( MenuMap::Iterator itr = myMenus.begin(); itr != myMenus.end(); ++itr )
{
- QAction* a = itemAction( it.current()->id );
- if ( !a )
- a = menuAction( it.current()->id );
-
- if ( a )
- a->removeFrom( myMenu );
+ delete itr.value()->menu();
+ delete itr.value();
}
- for ( MenuMap::Iterator itr = myMenus.begin(); itr != myMenus.end(); ++itr )
- delete itr.data();
+ delete myRoot;
}
/*!
- \return whether menu item corresponding to action is visible
- \param actId - identificator of action
- \param place - identificator of some parent action
+ \brief Check if an action with given ID \a actId is visible to
+ the parent action with given ID \a place.
+ \param actId action ID
+ \param place some parent action ID
+ \return \c true if an action is visible
*/
bool QtxActionMenuMgr::isVisible( const int actId, const int place ) const
{
}
/*!
- Sets visible state of action
- \param actId - identificator of action
- \param place - identificator of some parent action
- \param v - visibility state
+ \brief Set action visibility flag.
+ \param actId action ID
+ \param place some parent action ID
+ \param on visibility state
*/
void QtxActionMenuMgr::setVisible( const int actId, const int place, const bool v )
{
}
/*!
- Insert action as children menu item
- \param id - identificator of action
- \param menus - few names of parent menu items, separated by '|'. It means sequence of menu items,
- for example "File|Edit" means File->Edit submenu. If submenu doesn't exist, it will be created.
- \param group - group identificator
- \param idx - index inside Qt menu
+ \brief Insert action to the menu.
+
+ Insert an action to the named menu. The \a menus parameter represents
+ the menu name: it is a sequence of strings, separated by '|' symbol.
+ For example, "File|Edit" means File->Edit submenu.
+ If submenu doesn't exist, it will be created.
+
+ \param id action ID
+ \param menus menu name
+ \param group group ID
+ \param idx menu index inside the menu group
+ \return action ID
*/
int QtxActionMenuMgr::insert( const int id, const QString& menus, const int group, const int idx )
{
- return insert( id, QStringList::split( "|", menus ), group, idx );
+ return insert( id, menus.split( "|", QString::SkipEmptyParts ), group, idx );
}
/*!
- Insert action as children menu item
- \param a - action
- \param menus - few names of parent menu items, separated by '|'. It means sequence of menu items,
- for example "File|Edit" means File->Edit submenu. If submenu doesn't exist, it will be created.
- \param group - group identificator
- \param idx - index inside Qt menu
+ \brief Insert action to the menu.
+
+ Insert an action to the named menu. The \a menus parameter represents
+ the menu name: it is a sequence of strings, separated by '|' symbol.
+ For example, "File|Edit" means File->Edit submenu.
+ If submenu doesn't exist, it will be created.
+
+ \param a action
+ \param menus menu name
+ \param group group ID
+ \param idx menu index inside the menu group
+ \return action ID
*/
int QtxActionMenuMgr::insert( QAction* a, const QString& menus, const int group, const int idx )
{
- return insert( a, QStringList::split( "|", menus ), group, idx );
+ return insert( a, menus.split( "|", QString::SkipEmptyParts ), group, idx );
}
/*!
- Insert action as children menu item
- \param id - identificator of action
- \param menus - list of names of parent menu items, separated by |. It means sequence of menu items,
- for example "File|Edit" means File->Edit submenu. If submenu doesn't exist, it will be created.
- \param group - group identificator
- \param idx - index inside Qt menu
+ \brief Insert action to the menu.
+
+ Insert an action to the named menu. The \a menus parameter represents
+ the menu names list.
+ For example, string list consisting from two items "File" and "Edit"
+ means File->Edit submenu.
+ If submenu doesn't exist, it will be created.
+
+ \param id action ID
+ \param menus menu names list
+ \param group group ID
+ \param idx menu index inside the menu group
+ \return action ID
*/
int QtxActionMenuMgr::insert( const int id, const QStringList& menus, const int group, const int idx )
{
}
/*!
- Insert action as children menu item
- \param a - action
- \param menus - list of names of parent menu items. It means sequence of menu items,
- for example "File|Edit" means File->Edit submenu. If submenu doesn't exist, it will be created.
- \param group - group identificator
- \param idx - index inside Qt menu
+ \brief Insert action to the menu.
+
+ Insert an action to the named menu. The \a menus parameter represents
+ the menu names list.
+ For example, string list consisting from two items "File" and "Edit"
+ means File->Edit submenu.
+ If submenu doesn't exist, it will be created.
+
+ \param a action
+ \param menus menu names list
+ \param group group ID
+ \param idx menu index inside the menu group
+ \return action ID
*/
int QtxActionMenuMgr::insert( QAction* a, const QStringList& menus, const int group, const int idx )
{
}
/*!
- Insert action as children menu item
- \param id - identificator of action
- \param pId - identificator of action corresponding to parent menu item
- \param group - group identificator
- \param idx - index inside Qt menu
+ \brief Insert action to the menu.
+ \param id action ID
+ \param pId parent menu action ID
+ \param group group ID
+ \param idx menu index inside the menu group
+ \return action ID
*/
int QtxActionMenuMgr::insert( const int id, const int pId, const int group, const int idx )
{
if ( id == -1 )
return -1;
- MenuNode* pNode = pId == -1 ? &myRoot : find( pId );
+ MenuNode* pNode = pId == -1 ? myRoot : find( pId );
if ( !pNode )
return -1;
- MenuNode* node = new MenuNode( pNode );
- node->id = id;
- node->idx = idx;
- node->group = group;
+ MenuNode* node = new MenuNode( pNode, id, idx, group );
- pNode->children.append( node );
-
- updateMenu( pNode, false );
+ triggerUpdate( pNode->id, false );
return node->id;
}
/*!
- Insert action as children menu item
- \param a - action
- \param pId - identificator of action corresponding to parent menu item
- \param group - group identificator
- \param idx - index inside Qt menu
+ \brief Insert action to the menu.
+ \param a action
+ \param pId parent menu action ID
+ \param group group ID
+ \param idx menu index inside the menu group
+ \return action ID
*/
int QtxActionMenuMgr::insert( QAction* a, const int pId, const int group, const int idx )
{
}
/*!
- Create and insert action as children menu item
- \return identificator of inserted action
- \param title - menu text of action
- \param pId - identificator of action corresponding to parent menu item
- \param group - group identificator
- \param id - identificator of new action
- \param idx - index inside Qt menu
- \param allowEmpty - indicates, that it is possible to add this action with empty popup menu to other menu
+ \brief Create and insert menu item action to the menu.
+ \param title menu text
+ \param pId parent menu action ID
+ \param group group ID
+ \param id action ID
+ \param idx menu index inside the menu group
+ \return action ID
*/
-int QtxActionMenuMgr::insert( const QString& title, const int pId, const int group, const int id, const int idx, const bool allowEmpty )
+int QtxActionMenuMgr::insert( const QString& title, const int pId, const int group, const int id, const int idx )
{
- MenuNode* pNode = pId == -1 ? &myRoot : find( pId );
+ MenuNode* pNode = pId == -1 ? myRoot : find( pId );
if ( !pNode )
return -1;
MenuNode* eNode = id == -1 ? 0 : find( id );
int fid = -1;
- for ( NodeListIterator it( pNode->children ); it.current() && fid == -1; ++it )
+ for ( NodeList::iterator it = pNode->children.begin(); it != pNode->children.end() && fid == -1; ++it )
{
- if ( myMenus.contains( it.current()->id ) &&
- clearTitle( myMenus[it.current()->id]->menuText() ) == clearTitle( title ) )
- fid = it.current()->id;
+ if ( myMenus.contains( (*it)->id ) &&
+ clearTitle( myMenus[(*it)->id]->text() ) == clearTitle( title ) )
+ fid = (*it)->id;
}
if ( fid != -1 )
int gid = (id == -1 || eNode ) ? generateId() : id;
- MenuAction* ma = new MenuAction( clearTitle( title ), title, this, gid, allowEmpty );
+ QAction* ma = new QAction( title, this );
+ ma->setMenu( new QMenu( 0 ) );
+
+ connect( ma->menu(), SIGNAL( aboutToShow() ), this, SLOT( onAboutToShow() ) );
+ connect( ma->menu(), SIGNAL( aboutToHide() ), this, SLOT( onAboutToHide() ) );
#ifdef ENABLE_DYNAMIC_MENU
- connect( ma->popup(), SIGNAL( highlighted( int ) ), this, SLOT( onHighlighted( int ) ) );
+ connect( ma->menu(), SIGNAL( highlighted( int ) ), this, SLOT( onHighlighted( int ) ) );
#endif
- MenuNode* node = new MenuNode( pNode );
- node->group = group;
- node->idx = idx;
- node->id = myMenus.insert( gid, ma ).key();
+ MenuNode* node = new MenuNode( pNode, myMenus.insert( gid, ma ).key(), idx, group );
- pNode->children.append( node );
-
- updateMenu( pNode, false );
+ triggerUpdate( pNode->id, false );
return node->id;
}
/*!
- Create and insert action as children menu item
- \return identificator of inserted action
- \param title - menu text of action
- \param menus - string list of parents' menu texts, separated by |
- \param group - group identificator
- \param id - identificator of new action
- \param idx - index inside Qt menu
- \param allowEmpty - indicates, that it is possible to add this action with empty popup menu to other menu
+ \brief Create and insert menu item action to the menu.
+
+ Insert an action to the named menu. The \a menus parameter represents
+ the menu name: it is a sequence of strings, separated by '|' symbol.
+ For example, "File|Edit" means File->Edit submenu.
+ If submenu doesn't exist, it will be created.
+
+ \param title menu text
+ \param menus menu name
+ \param group group ID
+ \param id action ID
+ \param idx menu index inside the menu group
+ \return action ID
*/
-int QtxActionMenuMgr::insert( const QString& title, const QString& menus, const int group, const int id, const int idx, const bool allowEmpty )
+int QtxActionMenuMgr::insert( const QString& title, const QString& menus, const int group, const int id, const int idx )
{
- return insert( title, QStringList::split( "|", menus ), group, id, idx, allowEmpty );
+ return insert( title, menus.split( "|", QString::SkipEmptyParts ), group, id, idx );
}
/*!
- Create and insert action as children menu item
- \return identificator of inserted action
- \param title - menu text of action
- \param menus - list of parents menu items
- \param group - group identificator
- \param id - identificator of new action
- \param idx - index inside Qt menu
- \param allowEmpty - indicates, that it is possible to add this action with empty popup menu to other menu
+ \brief Create and insert menu item action to the menu.
+
+ Insert an action to the named menu. The \a menus parameter represents
+ the menu names list.
+ For example, string list consisting from two items "File" and "Edit"
+ means File->Edit submenu.
+ If submenu doesn't exist, it will be created.
+
+ \param title menu text
+ \param menus menu names list
+ \param group group ID
+ \param id action ID
+ \param idx menu index inside the menu group
+ \return action ID
*/
-int QtxActionMenuMgr::insert( const QString& title, const QStringList& menus, const int group, const int id, const int idx, const bool allowEmpty )
+int QtxActionMenuMgr::insert( const QString& title, const QStringList& menus, const int group, const int id, const int idx )
{
int pId = createMenu( menus, -1 );
- return insert( title, pId, group, id, idx, allowEmpty );
+ return insert( title, pId, group, id, idx );
}
/*!
- Create and append action as last children
- \return identificator of inserted action
- \param title - menu text of action
- \param pId - id of action corresponding to parent menu item
- \param group - group identificator
- \param id - identificator of new action
- \param allowEmpty - indicates, that it is possible to add this action with empty popup menu to other menu
+ \brief Create and add menu item action to the end of menu.
+ \param title menu text
+ \param pId parent menu action ID
+ \param group group ID
+ \param id action ID
+ \return action ID
*/
-int QtxActionMenuMgr::append( const QString& title, const int pId, const int group, const int id, const bool allowEmpty )
+int QtxActionMenuMgr::append( const QString& title, const int pId, const int group, const int id )
{
- return insert( title, pId, group, id, allowEmpty );
+ return insert( title, pId, group, id );
}
/*!
- Create and append action as last children
- \return identificator of inserted action
- \param id - identificator of existing action
- \param pId - id of action corresponding to parent menu item
- \param group - group identificator
+ \brief Create and add menu item action to the end of menu.
+ \param id action ID
+ \param pId parent menu action ID
+ \param group group ID
+ \return action ID
*/
int QtxActionMenuMgr::append( const int id, const int pId, const int group )
{
}
/*!
- Create and append action as last children
- \return identificator of inserted action
- \param a - action
- \param pId - id of action corresponding to parent menu item
- \param group - group identificator
+ \brief Create and add menu item action to the end of menu.
+ \param a action
+ \param pId parent menu action ID
+ \param group group ID
+ \return action ID
*/
int QtxActionMenuMgr::append( QAction* a, const int pId, const int group )
{
}
/*!
- Create and insert action as first children
- \return identificator of inserted action
- \param title - menu text of action
- \param pId - id of action corresponding to parent menu item
- \param group - group identificator
- \param id - identificator of new action
- \param allowEmpty - indicates, that it is possible to add this action with empty popup menu to other menu
+ \brief Create and add menu item action to the beginning of menu.
+ \param title menu text
+ \param pId parent menu action ID
+ \param group group ID
+ \param id action ID
+ \return action ID
*/
-int QtxActionMenuMgr::prepend( const QString& title, const int pId, const int group, const int id, const bool allowEmpty )
+int QtxActionMenuMgr::prepend( const QString& title, const int pId, const int group, const int id )
{
- return insert( title, pId, group, id, 0, allowEmpty );
+ return insert( title, pId, group, id, 0 );
}
/*!
- Create and insert action as last children
- \return identificator of inserted action
- \param id - identificator of existing action
- \param pId - id of action corresponding to parent menu item
- \param group - group identificator
+ \brief Create and add menu item action to the beginning of menu.
+ \param id action ID
+ \param pId parent menu action ID
+ \param group group ID
+ \return action ID
*/
int QtxActionMenuMgr::prepend( const int id, const int pId, const int group )
{
}
/*!
- Create and insert action as last children
- \return identificator of inserted action
- \param a - action
- \param pId - id of action corresponding to parent menu item
- \param group - group identificator
+ \brief Create and add menu item action to the beginning of menu.
+ \param a action
+ \param pId parent menu action ID
+ \param group group ID
+ \return action ID
*/
int QtxActionMenuMgr::prepend( QAction* a, const int pId, const int group )
{
}
/*!
- Removes menu item corresponding to action
- \param id - identificator of action
+ \brief Remove menu item with given \a id.
+ \param id menu action ID
*/
void QtxActionMenuMgr::remove( const int id )
{
}
/*!
- Removes menu item
- \param id - identificator of action
- \param pId - identificator of action corresponding to parent menu item
- \param group - group identificator
+ \brief Remove menu item with given \a id.
+ \param id menu action ID
+ \param pId parent menu action ID
+ \param group group ID
*/
void QtxActionMenuMgr::remove( const int id, const int pId, const int group )
{
- MenuNode* pNode = pId == -1 ? &myRoot : find( pId );
+ MenuNode* pNode = pId == -1 ? myRoot : find( pId );
if ( !pNode )
return;
NodeList delNodes;
- for ( NodeListIterator it( pNode->children ); it.current(); ++it )
+ for ( NodeList::iterator it = pNode->children.begin(); it != pNode->children.end(); ++it )
{
- if ( it.current()->id == id && ( it.current()->group == group || group == -1 ) )
- delNodes.append( it.current() );
+ if ( (*it)->id == id && ( (*it)->group == group || group == -1 ) )
+ delNodes.append( *it );
}
- for ( NodeListIterator itr( delNodes ); itr.current(); ++itr )
- pNode->children.remove( itr.current() );
+ for ( NodeList::iterator itr = delNodes.begin(); itr != delNodes.end(); ++itr )
+ pNode->children.removeAll( *itr );
- updateMenu( pNode, false );
+ triggerUpdate( pNode->id, false );
}
/*!
- Shows menu item corresponding to action
- \param id - identificator of action
+ \brief Show menu item with given \a id.
+ \param id menu action ID
*/
void QtxActionMenuMgr::show( const int id )
{
}
/*!
- Hides menu item corresponding to action
- \param id - identificator of action
+ \brief Hide menu item with given \a id.
+ \param id menu action ID
*/
void QtxActionMenuMgr::hide( const int id )
{
}
/*!
- \return shown status of menu item corresponding to action
- \param id - identificator of action
+ \brief Get visibility status for menu item with given \a id.
+ \param id menu action ID
+ \return \c true if an item is shown
*/
bool QtxActionMenuMgr::isShown( const int id ) const
{
}
/*!
- Sets shown status of menu item corresponding to action
- \param id - identificator of action
- \param on - new shown status
+ \brief Set visibility status for menu item with given \a id.
+ \param id menu action ID
+ \param on new visibility status
*/
void QtxActionMenuMgr::setShown( const int id, const bool on )
{
NodeList aNodes;
find( id, aNodes );
- QMap<MenuNode*, int> updMap;
- for ( NodeListIterator it( aNodes ); it.current(); ++it )
+ for ( NodeList::iterator it = aNodes.begin(); it != aNodes.end(); ++it )
{
- if ( it.current()->visible != on )
+ if ( (*it)->visible != on )
{
- it.current()->visible = on;
- updMap.insert( it.current()->parent, 0 );
+ (*it)->visible = on;
+ triggerUpdate( (*it)->parent ? (*it)->parent->id : myRoot->id, false );
}
}
+}
+
+/*!
+ \brief Change menu title fot the action with given \a id.
+ \param id menu action ID
+ \param title new menu title
+*/
+void QtxActionMenuMgr::change( const int id, const QString& title )
+{
+ QAction* a = menuAction( id );
+ if ( a )
+ a->setText( title );
+}
+
+/*!
+ \brief Called when the submenu is about to show.
+
+ Emits the signal menuAboutToShow(QMenu*).
+*/
+void QtxActionMenuMgr::onAboutToShow()
+{
+ QMenu* m = ::qobject_cast<QMenu*>( sender() );
+ if ( m )
+ emit menuAboutToShow( m );
+}
- for ( QMap<MenuNode*, int>::ConstIterator itr = updMap.begin(); itr != updMap.end(); ++itr )
- updateMenu( itr.key(), false );
+/*!
+ \brief Called when the submenu is about to hide.
+
+ Emits the signal menuAboutToHide(QMenu*).
+*/
+void QtxActionMenuMgr::onAboutToHide()
+{
+ QMenu* m = ::qobject_cast<QMenu*>( sender() );
+ if ( m )
+ emit menuAboutToHide( m );
}
/*!
- SLOT: called when corresponding menu is destroyed, clears internal pointer to menu
+ \brief Called when the corresponding menu object is destroyed.
+
+ Clears internal pointer to menu to disable crashes.
+
+ \param obj (menu) object being destroyed
*/
void QtxActionMenuMgr::onDestroyed( QObject* obj )
{
}
/*!
- SLOT: called when menu item is highlighted
+ \brief Called when menu item is highlighted.
+ \param id menu item being highlighted ID
*/
void QtxActionMenuMgr::onHighlighted( int id )
{
int pid = 0, realId;
if ( myMenu && snd == myMenu )
pid = -1;
- else {
- for ( MenuMap::Iterator itr = myMenus.begin(); itr != myMenus.end(); ++itr ) {
- if ( itr.data()->popup() && itr.data()->popup() == snd )
- pid = itr.key();
+ else
+ {
+ for ( MenuMap::Iterator itr = myMenus.begin(); itr != myMenus.end(); ++itr )
+ {
+ if ( itr.value()->menu() && itr.value()->menu() == snd )
+ pid = itr.key();
}
}
- if ( pid ) {
+ if ( pid )
+ {
realId = findId( id, pid );
- if ( realId != -1 ) {
- bool updatesEnabled = isUpdatesEnabled();
- setUpdatesEnabled( false );
+ if ( realId != -1 )
+ {
emit menuHighlighted( pid, realId );
- setUpdatesEnabled( updatesEnabled );
- updateMenu( find( realId ) );
+ triggerUpdate( realId );
}
}
}
/*!
- Assignes new menu with manager
- \param mw - new menu
+ \brief Returns the menu widget.
*/
-void QtxActionMenuMgr::setWidget( QWidget* mw )
+QWidget* QtxActionMenuMgr::menuWidget() const
+{
+ return myMenu;
+}
+
+/*!
+ \brief Assign new menu widget to the menu manager.
+ \param mw new menu widget
+*/
+void QtxActionMenuMgr::setMenuWidget( QWidget* mw )
{
if ( myMenu == mw )
return;
if ( myMenu )
connect( myMenu, SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
+
+ triggerUpdate( -1, true );
}
/*!
- \return menu node by it's place description
- \param actId - identificator of action
- \param pId - identificator of action corresponding to start menu item
- \param rec - recursive search
+ \brief Search menu node.
+ \param id menu action ID
+ \param pId parent menu item ID
+ \param rec if \c true perform recursive search
+ \return menu node or 0 if not found
*/
-QtxActionMenuMgr::MenuNode* QtxActionMenuMgr::find( const int actId, const int pId, const bool rec ) const
+QtxActionMenuMgr::MenuNode* QtxActionMenuMgr::find( const int id, const int pId, const bool rec ) const
{
- return find( actId, find( pId ), rec );
+ return find( id, find( pId ), rec );
}
/*!
- \return menu node by it's place description
- \param actId - identificator of action
- \param startNode - start menu item
- \param rec - recursive search
+ \brief Search menu node.
+ \param id menu action ID
+ \param startNode start menu node (if 0, search from root node)
+ \param rec if \c true perform recursive search
+ \return menu node or 0 if not found
*/
QtxActionMenuMgr::MenuNode* QtxActionMenuMgr::find( const int id, MenuNode* startNode, const bool rec ) const
{
MenuNode* node = 0;
- MenuNode* start = startNode ? startNode : (MenuNode*)&myRoot;
- for ( NodeListIterator it( start->children ); it.current() && !node; ++it )
+ MenuNode* start = startNode ? startNode : myRoot;
+ for ( NodeList::iterator it = start->children.begin(); it != start->children.end() && !node; ++it )
{
- if ( it.current()->id == id )
- node = it.current();
+ if ( (*it)->id == id )
+ node = *it;
else if ( rec )
- node = find( id, it.current(), rec );
+ node = find( id, *it, rec );
}
return node;
}
/*!
- Finds menu node
- \return true if at least one node is found
- \param id - identificator of action
- \param lst - list to be filled with found nodes
- \param startNode - start menu item
+ \brief Search recursively all menu nodes with given \a id.
+ \param id menu action ID
+ \param NodeList resulting list of menu nodes
+ \param startNode start menu node (if 0, search from root node)
+ \return \c true if at least one node is found
*/
bool QtxActionMenuMgr::find( const int id, NodeList& lst, MenuNode* startNode ) const
{
- MenuNode* start = startNode ? startNode : (MenuNode*)&myRoot;
- for ( NodeListIterator it( start->children ); it.current(); ++it )
+ MenuNode* start = startNode ? startNode : myRoot;
+ for ( NodeList::iterator it = start->children.begin(); it != start->children.end(); ++it )
{
- if ( it.current()->id == id )
- lst.prepend( it.current() );
+ MenuNode* node = *it;
+ if ( node->id == id )
+ lst.prepend( node );
- find( id, lst, it.current() );
+ find( id, lst, node );
}
return !lst.isEmpty();
}
/*!
- Finds menu node
- \return menu node
- \param title - menu text of searched node
- \param pId - id of action corresponding to start menu item
- \param rec - recursive searching
+ \brief Search menu node.
+ \param title menu item title
+ \param pId parent menu item ID
+ \param rec if \c true perform recursive search
+ \return menu node or 0 if not found
*/
QtxActionMenuMgr::MenuNode* QtxActionMenuMgr::find( const QString& title, const int pId, const bool rec ) const
{
}
/*!
- Finds menu node
- \return true if at least one node is found
- \param title - menu text of node
- \param lst - list to be filled with found nodes
- \param startNode - start menu item
+ \brief Search recursively all menu nodes with given \a title.
+ \param title menu item title
+ \param NodeList resulting list of menu nodes
+ \param startNode start menu node (if 0, search from root node)
+ \return \c true if at least one node is found
*/
bool QtxActionMenuMgr::find( const QString& title, NodeList& lst, MenuNode* startNode ) const
{
- MenuNode* start = startNode ? startNode : (MenuNode*)&myRoot;
- for ( NodeListIterator it( start->children ); it.current(); ++it )
+ MenuNode* start = startNode ? startNode : myRoot;
+ for ( NodeList::iterator it = start->children.begin(); it != start->children.end(); ++it )
{
- QAction* a = itemAction( it.current()->id );
+ QAction* a = itemAction( (*it)->id );
if ( !a )
- a = menuAction( it.current()->id );
- if ( a && clearTitle( a->menuText() ) == clearTitle( title ) )
- lst.prepend( it.current() );
+ a = menuAction( (*it)->id );
+ if ( a && clearTitle( a->text() ) == clearTitle( title ) )
+ lst.prepend( *it );
- find( title, lst, it.current() );
+ find( title, lst, *it );
}
return !lst.isEmpty();
}
/*!
- Finds menu node
- \return menu node
- \param title - menu text of searched node
- \param startNode - start menu item
- \param rec - recursive searching
+ \brief Search menu node.
+ \param title menu item title
+ \param startNode start menu node (if 0, search from root node)
+ \param rec if \c true perform recursive search
+ \return menu node or 0 if not found
*/
QtxActionMenuMgr::MenuNode* QtxActionMenuMgr::find( const QString& title, MenuNode* startNode, const bool rec ) const
{
MenuNode* node = 0;
- MenuNode* start = startNode ? startNode : (MenuNode*)&myRoot;
- for ( NodeListIterator it( start->children ); it.current() && !node; ++it )
+ MenuNode* start = startNode ? startNode : myRoot;
+ for ( NodeList::iterator it = start->children.begin(); it != start->children.end() && !node; ++it )
{
- QAction* a = itemAction( it.current()->id );
+ QAction* a = itemAction( (*it)->id );
if ( !a )
- a = menuAction( it.current()->id );
- if ( a && clearTitle( a->menuText() ) == clearTitle( title ) )
- node = it.current();
+ a = menuAction( (*it)->id );
+ if ( a && clearTitle( a->text() ) == clearTitle( title ) )
+ node = *it;
if ( !node && rec )
- node = find( title, it.current(), rec );
+ node = find( title, *it, rec );
}
return node;
}
/*!
- Find id among children
- \return id (>0) if on success or -1 on fail
- \param id - id to be searched
- \param pid - id of parent, among children of that 'id' must be searched
+ \brief Find menu item by given ID (one-level only).
+ \param id menu action ID
+ \param pid parent meun item ID
+ \return id (>0) on success or -1 if menu item is not found
*/
int QtxActionMenuMgr::findId( const int id, const int pid ) const
{
- MenuNode* start = pid != -1 ? find( pid ) : (MenuNode*)&myRoot;
- if ( start ) {
- for ( NodeListIterator it( start->children ); it.current(); ++it ) {
- if ( it.current()->id == id ) return id;
+ MenuNode* start = pid != -1 ? find( pid ) : myRoot;
+ if ( start )
+ {
+ for ( NodeList::iterator it = start->children.begin(); it != start->children.end(); ++it )
+ {
+ if ( (*it)->id == id )
+ return id;
}
}
return -1;
}
/*!
- Removes child
- \param id - id of child to be removed
- \param startNode - parent menu item
+ \brief Removes menu node (with all its children).
+ \param id menu action ID
+ \param startNode parent menu node which search starts from (if 0, search starts from root)
*/
void QtxActionMenuMgr::removeMenu( const int id, MenuNode* startNode )
{
- MenuNode* start = startNode ? startNode : &myRoot;
- for ( NodeListIterator it( start->children ); it.current(); ++it )
+ MenuNode* start = startNode ? startNode : myRoot;
+ for ( NodeList::iterator it = start->children.begin(); it != start->children.end(); ++it )
{
- if ( it.current()->id == id )
- start->children.remove( it.current() );
+ if ( (*it)->id == id )
+ start->children.removeAll( *it );
else
- removeMenu( id, it.current() );
+ removeMenu( id, *it );
}
}
/*!
- \return menu item action by id
- \param id - id of action
+ \brief Get action by \a id.
+ \param id action ID
+ \return action or 0 if not found
*/
QAction* QtxActionMenuMgr::itemAction( const int id ) const
{
}
/*!
- \return menu action by id
- \param id - id of action
+ \brief Get submenu action by \a id.
+ \param id submenu ID
+ \return submenu action or 0 if not found
*/
-QtxActionMenuMgr::MenuAction* QtxActionMenuMgr::menuAction( const int id ) const
+QAction* QtxActionMenuMgr::menuAction( const int id ) const
{
- MenuAction* a = 0;
+ QAction* a = 0;
if ( myMenus.contains( id ) )
a = myMenus[id];
}
/*!
- Updates menu ( isUpdatesEnabled() must return true )
- \param startNode - first menu item to be updated
- \param rec - recursive update
- \param updParent - update also parent item (without recursion)
- \sa isUpdatesEnabled()
+ \brief Update menu.
+
+ Does nothing if update is disabled.
+
+ \param startNode start menu item to be updated
+ \param rec if \c true, perform recursive update
+ \param updParent if \c true update also parent item (without recursion)
+
+ \sa isUpdatesEnabled() and setUpdatesEnabled()
*/
void QtxActionMenuMgr::updateMenu( MenuNode* startNode, const bool rec, const bool updParent )
{
if ( !isUpdatesEnabled() )
return;
- MenuNode* node = startNode ? startNode : &myRoot;
+ MenuNode* node = startNode ? startNode : myRoot;
QWidget* mw = menuWidget( node );
if ( !mw )
bool filled = checkWidget( mw );
- for ( NodeListIterator it1( node->children ); it1.current(); ++it1 )
+ for ( NodeList::iterator it1 = node->children.begin(); it1 != node->children.end(); ++it1 )
{
- QAction* a = itemAction( it1.current()->id );
+ QAction* a = itemAction( (*it1)->id );
if ( !a )
- a = menuAction( it1.current()->id );
+ a = menuAction( (*it1)->id );
- if ( a )
- a->removeFrom( mw );
+ mw->removeAction( a );
+// if ( a )
+// a->removeFrom( mw );
}
- /* VSR: commented to allow direct creating of menus by calling insertItem() methods
- if ( mw->inherits( "QMenuBar" ) )
- ((QMenuBar*)mw)->clear();
- else if ( mw->inherits( "QPopupMenu" ) )
- ((QPopupMenu*)mw)->clear();
- */
+
QMap<int, NodeList> idMap;
- for ( NodeListIterator it2( node->children ); it2.current(); ++it2 )
+ for ( NodeList::iterator it2 = node->children.begin(); it2 != node->children.end(); ++it2 )
{
- NodeList& lst = idMap[it2.current()->group];
- int idx = it2.current()->idx;
+ NodeList& lst = idMap[(*it2)->group];
+ int idx = (*it2)->idx;
if ( idx < 0 || idx >= (int)lst.count() )
- lst.append( it2.current() );
+ lst.append( *it2 );
else
- lst.insert( idx, it2.current() );
+ lst.insert( idx, *it2 );
}
QIntList groups = idMap.keys();
- qHeapSort( groups );
+ qSort( groups );
- groups.remove( -1 );
+ groups.removeAll( -1 );
groups.append( -1 );
for ( QIntList::const_iterator gIt = groups.begin(); gIt != groups.end(); ++gIt )
continue;
const NodeList& lst = idMap[*gIt];
- for ( NodeListIterator iter( lst ); iter.current(); ++iter )
+ for ( NodeList::const_iterator iter = lst.begin(); iter != lst.end(); ++iter )
{
- MenuNode* par = iter.current()->parent;
- if ( !isVisible( iter.current()->id, par ? par->id : -1 ) )
- continue;
+ MenuNode* node = *iter;
if ( rec )
- updateMenu( iter.current(), rec, false );
+ updateMenu( node, rec, false );
- QAction* a = itemAction( iter.current()->id );
+ MenuNode* par = node->parent;
+ if ( !isVisible( node->id, par ? par->id : -1 ) )
+ continue;
+
+ bool isMenu = false;
+ QAction* a = itemAction( node->id );
if ( !a )
- a = menuAction( iter.current()->id );
- if ( a )
- a->addTo( mw );
+ {
+ isMenu = true;
+ a = menuAction( node->id );
+ }
+
+ if ( !isMenu || !a->menu()->isEmpty() )
+ mw->addAction( a );
}
}
}
/*!
- Updates menu (virtual variant). To be redefined for custom activity on menu updating
+ \brief Internal update.
+
+ Customizes the menu update processing.
*/
void QtxActionMenuMgr::internalUpdate()
{
- if ( isUpdatesEnabled() )
- updateMenu();
+ if ( !isUpdatesEnabled() )
+ return;
+
+ updateMenu();
+ myUpdateIds.clear();
}
/*!
- \return true if widget is non-empty menu
- \param wid - widget to be checked
+ \brief Check if menu widget has any actions.
+ \param wid widget to be checked
+ \return \c true if widget contains action(s)
*/
bool QtxActionMenuMgr::checkWidget( QWidget* wid ) const
{
if ( !wid )
return false;
- QMenuData* md = 0;
- if ( wid->inherits( "QPopupMenu" ) )
- md = (QPopupMenu*)wid;
- else if ( wid->inherits( "QMenuBar" ) )
- md = (QMenuBar*)wid;
-
- return md ? md->count() : false;
+ return !wid->actions().isEmpty();
}
/*!
- \return popup of menu item
- \param node - menu item
+ \brief Get menu widget for the given \a node.
+ \param node menu node
+ \return popup menu or main menu corresponding to the menu node (or 0 if not found)
*/
QWidget* QtxActionMenuMgr::menuWidget( MenuNode* node) const
{
- if ( !node || node == &myRoot )
+ if ( !node || node == myRoot )
return myMenu;
if ( !myMenus.contains( node->id ) || !myMenus[node->id] )
return 0;
- return myMenus[node->id]->popup();
+ return myMenus[node->id]->menu();
}
/*!
- Removes excess separators of menu
- \param wid - menu to be processed
+ \brief Remove extra separators from menu widget.
+ \param wid menu widget to be processed
*/
void QtxActionMenuMgr::simplifySeparators( QWidget* wid )
{
- if ( wid && wid->inherits( "QPopupMenu" ) )
- Qtx::simplifySeparators( (QPopupMenu*)wid, false );
+ Qtx::simplifySeparators( wid, false );
}
/*!
- Removes special symbols (&) from string
- \param txt - string to be processed
- \return clear variant of string
+ \brief Remove special symbols (&) from string to get clear menu title.
+ \param txt string to be processed
+ \return clear title
*/
QString QtxActionMenuMgr::clearTitle( const QString& txt ) const
{
}
/*!
- Creates and inserts many menu items
- \param lst - list of menu texts
- \param pId - id of action corresponding to parent menu item
+ \brief Create and inserts menu item recursively.
+ \param lst list of menu names
+ \param pId parent menu item ID
+ \return created menu item ID (last in the chain)
*/
int QtxActionMenuMgr::createMenu( const QStringList& lst, const int pId )
{
QStringList sl( lst );
- QString title = sl.last().stripWhiteSpace();
- sl.remove( sl.fromLast() );
+ QString title = sl.last().trimmed();
+ sl.removeLast();
int parentId = sl.isEmpty() ? pId : createMenu( sl, pId );
}
/*!
- Loads actions description from file
- \param fname - name of file
- \param r - reader of file
- \return true on success
+ \brief Load actions description from the file.
+ \param fname file name
+ \param r action reader
+ \return \c true on success and \c false on error
*/
bool QtxActionMenuMgr::load( const QString& fname, QtxActionMgr::Reader& r )
{
}
/*!
- \return true if item has such child
- \param title - menu text of child
- \param pid - id of action corresponding to item
+ \brief Check if the parent menu contains menu item with given \a title.
+ \param title menu title
+ \param pid parent menu item ID
+ \return \c true if parent menu item contains such child item
*/
bool QtxActionMenuMgr::containsMenu( const QString& title, const int pid ) const
{
}
/*!
- \return true if item has such child
- \param id - id of action corresponding to child
- \param pid - id of action corresponding to item
+ \brief Check if the parent menu contains menu item with given \a id.
+ \param id menu item ID
+ \param pid parent menu item ID
+ \return \c true if parent menu item contains such child item
*/
bool QtxActionMenuMgr::containsMenu( const int id, const int pid ) const
{
return (bool)find( id, pid, false );
}
+/*!
+ \brief Perform delayed menu update.
+ \param id menu item ID
+ \param rec if \c true, perform recursive update
+*/
+void QtxActionMenuMgr::triggerUpdate( const int id, const bool rec )
+{
+ bool isRec = rec;
+ if ( myUpdateIds.contains( id ) )
+ isRec = isRec || myUpdateIds[ id ];
+ myUpdateIds.insert( id, isRec );
+
+ QtxActionMgr::triggerUpdate();
+}
/*!
- Constructor
- \param r - menu reader
- \param mgr - menu manager
+ \brief Called when delayed content update is performed.
+
+ Customizes the content update operation.
*/
-QtxActionMenuMgr::MenuCreator::MenuCreator( QtxActionMgr::Reader* r,
- QtxActionMenuMgr* mgr )
+void QtxActionMenuMgr::updateContent()
+{
+ // Warning: For correct updating it is necessary to update the most enclosed submenu in first turn
+ // because not updated empty submenu will be skipped. Now the submenus are iterated in
+ // ascending order according to their identifiers. For a submenus with automatically generated
+ // identifiers this will work correctly since the uppermost submenus have the biggest number
+ // (identifiers are generated by decrementing 1 starting from -1). In general, if any submenu
+ // have positive identifiers this method might not work correctly. In this case it would be
+ // necessary to improve this method and to add preliminary sorting a submenus by depth of an
+ // enclosure.
+ for ( QMap<int, bool>::const_iterator it = myUpdateIds.constBegin(); it != myUpdateIds.constEnd(); ++it )
+ {
+ MenuNode* node = it.key() == -1 ? myRoot : find( it.key() );
+ if ( node )
+ updateMenu( node, it.value() );
+ }
+ myUpdateIds.clear();
+}
+
+/*!
+ \class QtxActionMenuMgr::MenuCreator
+ \brief Menu actions creator.
+
+ Used by Reader to create actions by reading descriptions from the file
+ and fill in the action manager with the actions.
+*/
+
+/*!
+ \brief Constructor.
+ \param r menu actions reader
+ \param mgr menu manager
+*/
+QtxActionMenuMgr::MenuCreator::MenuCreator( QtxActionMgr::Reader* r, QtxActionMenuMgr* mgr )
: QtxActionMgr::Creator( r ),
- myMgr( mgr )
+myMgr( mgr )
{
}
/*!
- Destructor
+ \brief Creator destructor.
+
+ Does nothing for the moment.
*/
QtxActionMenuMgr::MenuCreator::~MenuCreator()
{
}
/*!
- Appends new menu items
- \param tag - tag of item
- \param subMenu - it has submenu
- \param attr - list of attributes
- \param pId - id of action corresponding to parent item
+ \brief Create and append to the action manager a new action.
+ \param tag item tag name
+ \param subMenu \c true if this item is submenu
+ \param attr attributes map
+ \param pId parent action ID
+ \return menu action ID
*/
int QtxActionMenuMgr::MenuCreator::append( const QString& tag, const bool subMenu,
const ItemAttributes& attr, const int pId )
res = myMgr->insert( separator(), pId, intValue( attr, group, 0 ), intValue( attr, pos, -1 ) );
else
{
- QPixmap pix; QIconSet set;
+ QIcon set;
+ QPixmap pix;
QString name = strValue( attr, icon );
if( !name.isEmpty() && loadPixmap( name, pix ) )
- set = QIconSet( pix );
+ set = QIcon( pix );
QtxAction* newAct = new QtxAction( strValue( attr, tooltip ), set,
- strValue( attr, label ),
+ strValue( attr, label ),
QKeySequence( strValue( attr, accel ) ),
myMgr );
newAct->setToolTip( strValue( attr, tooltip ) );
QString toggleact = strValue( attr, toggle );
- newAct->setToggleAction( !toggleact.isEmpty() );
- newAct->setOn( toggleact.lower()=="true" );
-
+ newAct->setCheckable( !toggleact.isEmpty() );
+ newAct->setChecked( toggleact.toLower() == "true" );
+
connect( newAct );
int aid = myMgr->registerAction( newAct, actId );
res = myMgr->insert( aid, pId, intValue( attr, group, 0 ), intValue( attr, pos, -1 ) );
return res;
}
+
+/*!
+ \fn void QtxActionMenuMgr::menuAboutToShow( QMenu* m )
+ \brief Emitted when the menu is about to be shown.
+ \param m menu being shown
+*/
+
+/*!
+ \fn void QtxActionMenuMgr::menuAboutToHide( QMenu* m )
+ \brief Emitted when the menu is about to be hidden.
+ \param m menu being hidden
+*/
+
+/*!
+ \fn void QtxActionMenuMgr::menuHighlighted( int, int )
+ \brief Emitted when the menu is hightlighted [obsolete].
+*/
#include "Qtx.h"
#include "QtxActionMgr.h"
-#include <qptrlist.h>
-#include <qstringlist.h>
+#include <QList>
-class QPopupMenu;
+class QMenu;
class QMainWindow;
+class QStringList;
#ifdef WIN32
#pragma warning( disable:4251 )
#endif
-/*!
- \class QtxActionMenuMgr
- Allows to use set of action to automatically build main menu.
- With help of methods insert/append/remove it is possible to
- describe whole structure of menu. Method hide allows
- to temporary remove some items from menu, method show allows to
- recreate them.
- Actions can be grouped with help of group identifictor.
- Inside popup or menu bar items have order by increasing group id.
- This manager is able to attune menu: to remove excess separators,
- to remove empty popup menu etc.
-*/
class QTX_EXPORT QtxActionMenuMgr : public QtxActionMgr
{
Q_OBJECT
class MenuNode;
- typedef QPtrList<MenuNode> NodeList;
- typedef QPtrListIterator<MenuNode> NodeListIterator;
-
- /*!
- \class MenuNode
- Represents a menu item inside main menu structure.
- For internal purposes only
- */
- class MenuNode
- {
- public:
- MenuNode() : parent( 0 ), visible( true ) { children.setAutoDelete( true ); };
- MenuNode( MenuNode* p ) : parent( p ), visible( true ) { children.setAutoDelete( true ); };
-
- int id;
- int idx;
- int group;
- MenuNode* parent;
- bool visible;
- NodeList children;
- };
-
- class MenuAction;
+ typedef QList<MenuNode*> NodeList; //!< menu nodes list
protected:
class MenuCreator;
QtxActionMenuMgr( QWidget*, QObject* );
virtual ~QtxActionMenuMgr();
+ QWidget* menuWidget() const;
+
virtual bool isVisible( const int, const int ) const;
virtual void setVisible( const int, const int, const bool );
virtual int insert( const int, const int, const int, const int = -1 );
int insert( QAction*, const int, const int, const int = -1 );
- int insert( const QString&, const QString&, const int, const int = -1, const int = -1, const bool = false );
- int insert( const QString&, const QStringList&, const int, const int = -1, const int = -1, const bool = false );
- virtual int insert( const QString&, const int, const int, const int = -1, const int = -1, const bool = false );
+ int insert( const QString&, const QString&, const int, const int = -1, const int = -1 );
+ int insert( const QString&, const QStringList&, const int, const int = -1, const int = -1 );
+ virtual int insert( const QString&, const int, const int, const int = -1, const int = -1 );
int append( const int, const int, const int );
int append( QAction*, const int, const int );
- int append( const QString&, const int, const int, const int = -1, const bool = false );
+ int append( const QString&, const int, const int, const int = -1 );
int prepend( const int, const int, const int );
int prepend( QAction*, const int, const int );
- int prepend( const QString&, const int, const int, const int = -1, const bool = false );
+ int prepend( const QString&, const int, const int, const int = -1 );
void remove( const int );
void remove( const int, const int, const int = -1 );
bool isShown( const int ) const;
void setShown( const int, const bool );
+ virtual void change( const int, const QString& );
+
virtual bool load( const QString&, QtxActionMgr::Reader& );
bool containsMenu( const QString&, const int ) const;
bool containsMenu( const int, const int ) const;
-
private slots:
- void onDestroyed( QObject* );
+ void onAboutToShow();
+ void onAboutToHide();
void onHighlighted( int );
+ void onDestroyed( QObject* );
signals:
+ void menuAboutToShow( QMenu* );
+ void menuAboutToHide( QMenu* );
+
void menuHighlighted( int, int );
protected:
- void setWidget( QWidget* );
+ void setMenuWidget( QWidget* );
+
MenuNode* find( const int, const int, const bool = true ) const;
MenuNode* find( const int, MenuNode* = 0, const bool = true ) const;
bool find( const int, NodeList&, MenuNode* = 0 ) const;
void removeMenu( const int, MenuNode* );
QAction* itemAction( const int ) const;
- MenuAction* menuAction( const int ) const;
+ QAction* menuAction( const int ) const;
void updateMenu( MenuNode* = 0, const bool = true, const bool = true );
- virtual void internalUpdate();
+ virtual void internalUpdate();
+ virtual void updateContent();
private:
bool checkWidget( QWidget* ) const;
QString clearTitle( const QString& ) const;
int createMenu( const QStringList&, const int );
-private:
- typedef QMap<int, MenuAction*> MenuMap;
+ void triggerUpdate( const int, const bool rec = true );
private:
- MenuNode myRoot;
- QWidget* myMenu;
- MenuMap myMenus;
+ typedef QMap<int, QAction*> MenuMap; //!< actions map
+
+private:
+ MenuNode* myRoot; //!< root menu node
+ QWidget* myMenu; //!< menu widget
+ MenuMap myMenus; //!< actions map
+ QMap<int, bool> myUpdateIds; //!< list of actions ID being updated
};
-/*!
- \class QtxActionMenuMgr::MenuCreator
- Allows to create automatically main menu by data read from file
-*/
class QtxActionMenuMgr::MenuCreator : public QtxActionMgr::Creator
{
public:
const ItemAttributes&, const int );
private:
- QtxActionMenuMgr* myMgr;
+ QtxActionMenuMgr* myMgr; //!< menu manager
};
// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
+//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
+// License as published by the Free Software Foundation; either
// version 2.1 of the License.
-//
-// This library 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
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#include "Qtx.h"
#include "QtxActionMgr.h"
#include "QtxAction.h"
+#include <QFile>
+#include <QTimer>
+#ifndef QT_NO_DOM
+#include <QDomDocument>
+#include <QDomNode>
+#include <QCoreApplication>
+#endif
-#include <qwidget.h>
-#include <qtoolbar.h>
-#include <qpopupmenu.h>
-#include <qwidgetlist.h>
-#include <qobjectlist.h>
-#include <qfile.h>
-#include <qdom.h>
-
-static QAction* qtx_separator_action = 0;
+typedef QList< QPointer<QAction> > qtx_actionlist;
+static qtx_actionlist qtx_separator_actions;
+/*!
+ \internal
+ \brief Clean all cashed separator actions.
+ */
void qtxSeparatorActionCleanup()
{
- delete qtx_separator_action;
- qtx_separator_action = 0;
+ for ( qtx_actionlist::iterator it = qtx_separator_actions.begin(); it != qtx_separator_actions.end(); ++it )
+ delete *it;
}
/*!
- Class: QtxActionMenuMgr::SeparatorAction
- Level: Internal
+ \class QtxActionMgr::SeparatorAction
+ \internal
+ \brief Separator action class.
*/
class QtxActionMgr::SeparatorAction : public QtxAction
public:
SeparatorAction( QObject* = 0 );
virtual ~SeparatorAction();
-
- virtual bool addTo( QWidget* );
- virtual bool removeFrom( QWidget* );
-
-private:
- QMap<QPopupMenu*, QIntList> myMenus;
- QMap<QToolBar*, QWidgetList> myTools;
};
/*!
- Constructor
+ \brief Separator action constructor.
+ \param parent parent object
*/
QtxActionMgr::SeparatorAction::SeparatorAction( QObject* parent )
: QtxAction( parent )
{
+ setSeparator( true );
}
/*!
- Destructor
-*/
-QtxActionMgr::SeparatorAction::~SeparatorAction()
-{
-}
+ \brief Separator action destructor.
-/*!
- Adds action to widget
- \param wid - widget
+ Does nothing for the moment.
*/
-bool QtxActionMgr::SeparatorAction::addTo( QWidget* wid )
+QtxActionMgr::SeparatorAction::~SeparatorAction()
{
- if ( !wid )
- return false;
-
- bool res = true;
- if ( wid->inherits( "QPopupMenu" ) )
- {
- QPopupMenu* popup = (QPopupMenu*)wid;
- myMenus[popup].append( popup->insertSeparator() );
- }
- else if ( wid->inherits( "QToolBar" ) )
- {
- QToolBar* tb = (QToolBar*)wid;
- tb->addSeparator();
- myTools[tb].append( (QWidget*)tb->children()->getLast() );
- }
- else
- res = false;
-
- return res;
}
-/*!
- Removes action from widget
- \param wid - widget
-*/
-bool QtxActionMgr::SeparatorAction::removeFrom( QWidget* wid )
-{
- if ( !wid )
- return false;
-
- bool res = true;
- if ( wid->inherits( "QPopupMenu" ) )
- {
- QPopupMenu* popup = (QPopupMenu*)wid;
- if ( myMenus.contains( popup ) )
- {
- const QIntList& list = myMenus[popup];
- for ( QIntList::const_iterator it = list.begin(); it != list.end(); ++it )
- popup->removeItem( *it );
-
- myMenus.remove( popup );
- }
- }
- else if ( wid->inherits( "QToolBar" ) )
- {
- QToolBar* tb = (QToolBar*)wid;
- if ( myTools.contains( tb ) )
- {
- QMap<QObject*, int> childMap;
- if ( tb->children() )
- {
- for ( QObjectListIt it( *tb->children() ); it.current(); ++it )
- childMap.insert( it.current(), 0 );
- }
- const QWidgetList& list = myTools[tb];
- for ( QWidgetListIt it( list ); it.current(); ++it )
- {
- if ( childMap.contains( it.current() ) )
- delete it.current();
- }
-
- myTools.remove( tb );
- }
- }
- else
- res = false;
-
- return res;
-}
/*!
- Class: QtxActionMgr
- Level: Public
+ \class QtxActionMgr
+ \brief Manages a set of actions accessible by unique ID.
+
+ Base class for menu, toolbar action containers and popup menu creators.
*/
/*!
- Constructor
+ \brief Action manager constructor.
+ \param parent parent object
*/
QtxActionMgr::QtxActionMgr( QObject* parent )
: QObject( parent ),
-myUpdate( true )
+ myUpdate( true ),
+ myUpdTimer( 0 )
{
}
/*!
- Destructor
+ \brief Action manager destructor.
+
+ Does nothing for the moment.
*/
QtxActionMgr::~QtxActionMgr()
{
}
/*!
- Stores action in internal map
- If action with such id is registered already, then it will be unregistered
- \param a - action to be registered
- \param userId - proposed id (if it is less than 0, then id will be generated automatically)
+ \brief Register action in the internal map.
+
+ If \a userId is less than 0, the ID for the action is generated automatically.
+ If action with given \a userId is already registered, it will be re-registered.
+
+ \param a action to be registered
+ \param userId action ID
+ \return action ID (the same as userId or generated one)
*/
int QtxActionMgr::registerAction( QAction* a, const int userId )
{
}
/*!
- Removes action from internal map
- \param id - action id
+ \brief Unregister action from internal map.
+ \param id action ID
*/
void QtxActionMgr::unRegisterAction( const int id )
{
}
/*!
- \return action by id
- \param id - action id
+ \brief Get action by \a id.
+ \param id action ID
+ \return action (0 if action is not found)
*/
QAction* QtxActionMgr::action( const int id ) const
{
}
/*!
- \return id by action
- \param a - action
+ \brief Get action ID.
+ \param a action
+ \return action ID (-1 if action is not found)
*/
int QtxActionMgr::actionId( const QAction* a ) const
{
int theId = -1;
for ( ActionMap::ConstIterator it = myActions.begin(); it != myActions.end() && theId == -1; ++it )
{
- if ( it.data() == a )
+ if ( it.value() == a )
theId = it.key();
}
}
/*!
- \return true if internal map contains such id
- \param id - action id
+ \brief Check if an action with given \a id is registered in the action manager.
+ \param id action ID
+ \return \c true if internal map contains action with such ID
*/
bool QtxActionMgr::contains( const int id ) const
{
}
/*!
- \return count of actions in internal map
+ \brief Get number of registered actions.
+ \return number of actions in the internal map
*/
int QtxActionMgr::count() const
{
}
/*!
- \return true if internal map is empty
+ \brief Check if there are no actions registered in the action manager.
+ \return \c true if internal map is empty
*/
bool QtxActionMgr::isEmpty() const
{
}
/*!
- Fills list with ids of registered actions
+ \brief Get all registered actions IDs.
+ \param list of actions IDs to be fiiled in
*/
void QtxActionMgr::idList( QIntList& lst ) const
{
}
/*!
- \return true if updates are enabled
+ \brief Check if update is enabled.
+ \return \c true if update is enabled
*/
bool QtxActionMgr::isUpdatesEnabled() const
{
}
/*!
- Enables/disables updates
- \param upd - new state
+ \brief Enable/disable update operation.
+ \param upd new state
*/
void QtxActionMgr::setUpdatesEnabled( const bool upd )
{
}
/*!
- \return true if action is visible (by default \return always true)
+ \brief Check if an action with given ID \a actId is visible to
+ the parent action with given ID \a place.
+
+ Base implementatin always returns \c true.
+
+ \param actId action ID
+ \param place some parent action ID
+ \return \c true if an action is visible
*/
-bool QtxActionMgr::isVisible( const int, const int ) const
+bool QtxActionMgr::isVisible( const int /*actId*/, const int /*place*/ ) const
{
return true;
}
/*!
- Sets visibility of action (by default, empty implementation)
+ \brief Set action visibility flag.
+
+ Base implementatin does nothing.
+
+ \param actId action ID
+ \param place some parent action ID
+ \param on visibility state
*/
-void QtxActionMgr::setVisible( const int, const int, const bool )
+void QtxActionMgr::setVisible( const int /*actId*/, const int /*place*/, const bool /*on*/ )
{
}
/*!
- Updates actions, check isUpdatesEnabled() and call internalUpdate()
+ \brief Update actions.
+
+ Does nothing if update is disabled.
+
\sa isUpdatesEnabled(), internalUpdate()
*/
void QtxActionMgr::update()
{
- if ( isUpdatesEnabled() )
- internalUpdate();
+ if ( !isUpdatesEnabled() )
+ return;
+
+ internalUpdate();
+ if ( myUpdTimer )
+ myUpdTimer->stop();
}
/*!
- Real update (to be redefined in successors)
+ \brief Internal update.
+
+ This method is called by update() function and should be redefined in successors.
*/
void QtxActionMgr::internalUpdate()
{
}
/*!
- \return global free id
+ \brief Generate unique action ID.
+ \return new ID
*/
int QtxActionMgr::generateId() const
{
}
/*!
- \return true if action is enabled
- \param id - action id
+ \brief Check is action with given \a id is enabled.
+ \param id action ID
+ \return \c true if action is enabled
*/
bool QtxActionMgr::isEnabled( const int id ) const
{
}
/*!
- Enables/disables action
- \param id - action id
- \param en - new state
+ Enable/disable action with given \a id.
+ \param id action ID
+ \param enable new state
*/
-void QtxActionMgr::setEnabled( const int id, const bool en )
+void QtxActionMgr::setEnabled( const int id, const bool enable )
{
QAction* a = action( id );
if ( a )
- a->setEnabled( en );
+ a->setEnabled( enable );
}
/*!
- \return action for separator
- If this action doesn't exist, then it will be created
- \param individual - if it is false, then action will be shared, otherwise it will be created on every call
+ \brief Create new separator action.
+
+ If \a own is \c true, that the caller is responsible for the action
+ deleting. If \a own is \c false, new separator action is owned by the
+ action manager which destroys it on application exit.
+
+ \param own ownership flag
+ \return new separator action
*/
-QAction* QtxActionMgr::separator( const bool individual )
+QAction* QtxActionMgr::separator( const bool own )
{
- if ( individual )
+ if ( own )
return new SeparatorAction();
- if ( !qtx_separator_action )
- {
- qtx_separator_action = new SeparatorAction();
+ if ( qtx_separator_actions.isEmpty() )
qAddPostRoutine( qtxSeparatorActionCleanup );
+
+ SeparatorAction* a = new SeparatorAction();
+ qtx_separator_actions.append( a );
+
+ return a;
+}
+
+/*!
+ \brief Perform delayed update.
+
+ Does nothing if update is disabled.
+*/
+void QtxActionMgr::triggerUpdate()
+{
+ if ( !isUpdatesEnabled() )
+ return;
+
+ if ( !myUpdTimer )
+ {
+ myUpdTimer = new QTimer( this );
+ myUpdTimer->setSingleShot( true );
+ connect( myUpdTimer, SIGNAL( timeout() ), this, SLOT( onUpdateContent() ) );
}
- return qtx_separator_action;
+ myUpdTimer->stop();
+ // add timer event to event list
+ myUpdTimer->start( 0 );
+}
+
+/*!
+ \brief Internal content update operation.
+
+ Called automatically by onUpdateContent() when the delayed update
+ id triggered. Default implementation does nothing.
+
+ \sa triggerUpdate(), onUpdateContent()
+*/
+void QtxActionMgr::updateContent()
+{}
+
+/*!
+ \brief Called when delayed update is performed (via timer event).
+
+ Calls virtual method updateContent() which can customize the
+ content update operation.
+*/
+void QtxActionMgr::onUpdateContent()
+{
+ updateContent();
}
/*!
- Class: QtxActionMgr::Reader
- Level: Public
+ \class QtxActionMgr::Reader
+ \brief Generic actions description files reader class.
+
+ This class is used to read files of some format to create actions
+ and fill an action manager with actions automatically.
*/
/*!
- Constructor
+ \brief Reader constructor.
+
+ Does nothing for the moment.
*/
QtxActionMgr::Reader::Reader()
{
}
/*!
- Destructor
+ \brief Reader destructor
+
+ Does nothing for the moment.
*/
QtxActionMgr::Reader::~Reader()
{
}
/*!
- \return list of options
+ \brief Get list of options.
+ \return options list
*/
QStringList QtxActionMgr::Reader::options() const
{
}
/*!
- \return value of option
- \param name - option name
- \param def - default option value (is returned, if there is no such option)
+ \brief Get option value.
+
+ If there is no such option the default value is returned.
+
+ \param name option name
+ \param def default option value
+ \return option value
*/
QString QtxActionMgr::Reader::option( const QString& name, const QString& def ) const
{
}
/*!
- Sets value of option
- \param name - option name
- \param value - option value
+ \brief Set option value.
+ \param name option name
+ \param value new option value
*/
void QtxActionMgr::Reader::setOption( const QString& name, const QString& value )
{
myOptions[ name ] = value;
}
+/*!
+ \fn bool QtxActionMgr::Reader::read( const QString& fname, Creator& cr ) const
+ \brief Read the file and fill and action manager with actions
+ by using help actions creator.
+
+ Default implementation is pure virtual.
+
+ \param fname XML file name
+ \param cr actions creator
+ \return \c true in success and \c false in case of error
+*/
+
+/*!
+ \class QtxActionMgr::XMLReader
+ \brief XML file reader.
+
+ This class is used to read files of XML format to create
+ actions and fill an action manager with actions automatically.
+*/
/*!
- Constructor
+ \brief XML reader constructor.
+
+ \param root root XML tag name
+ \param item menu item XML tag name
+ \param dir resources directory (containing icons, etc)
*/
QtxActionMgr::XMLReader::XMLReader( const QString& root,
const QString& item,
}
/*!
- Destructor
+ \brief XML reader destructor.
+
+ Does nothing for the moment.
*/
QtxActionMgr::XMLReader::~XMLReader()
{
}
/*!
- Reads file and fills action manager with help of creator
- \param fname - file name
- \param cr - creator
+ \brief Read the file and fill and action manager with actions
+ by using help actions creator.
+ \param fname XML file name
+ \param cr actions creator
+ \return \c true in success and \c false in case of error
*/
bool QtxActionMgr::XMLReader::read( const QString& fname, Creator& cr ) const
{
- bool res = false;
+ bool res = false;
#ifndef QT_NO_DOM
QFile file( fname );
- if ( !file.open( IO_ReadOnly ) )
+ if ( !file.open( QFile::ReadOnly ) )
return res;
QDomDocument doc;
}
/*!
- Create item by xml node
- \param parent_node - parent node
- \param parent_id - parent id
- \param cr - creator
+ \brief Read XML mode and create an item if requied.
+ \param parent_node parent XML file node
+ \param parent_id parent action ID
+ \param cr actions creator
*/
void QtxActionMgr::XMLReader::read( const QDomNode& parent_node,
const int parent_id,
if( parent_node.isNull() )
return;
- QStringList items = QStringList::split( "|", option( QString( "menu_item" ) ) );
+ QStringList items = option( "menu_item" ).split( "|", QString::SkipEmptyParts );
const QDomNodeList& children = parent_node.childNodes();
for( int i=0, n=children.count(); i<n; i++ )
}
/*!
- \return true if node satisfies pattern
+ \brief Check node name correspondance to some pattern.
+ \param node XML file node
+ \param pattern node name pattern
+ \return \c true if node satisfies pattern
*/
bool QtxActionMgr::XMLReader::isNodeSimilar( const QDomNode& node,
const QString& pattern ) const
{
if( node.nodeName()==pattern )
return true;
-
+
QDomDocument temp;
QString mes;
temp.setContent( pattern, true, &mes );
return ok;
}
+/*!
+ \class QtxActionMgr::Creator
+ \brief Generic actions creator class.
+
+ Used by Reader to create actions and fill in the action
+ manager with the actions.
+*/
/*!
- \return integer value by attributes
- \param attrs - attributes
- \param name - name of attribute
- \param def - default value (is returned on fail)
+ \brief Get integer attribute value from the attribute map.
+
+ Returns default value if the attribute is not found.
+
+ \param attrs attributes map
+ \param name attribute name
+ \param def default attribute value
+ \return attribute value
*/
int QtxActionMgr::Creator::intValue( const ItemAttributes& attrs,
const QString& name, int def )
{
if( attrs.contains( name ) )
{
- bool ok;
+ bool ok;
int res = attrs[ name ].toInt( &ok );
if( ok )
return res;
}
/*!
- \return string value by attributes
- \param attrs - attributes
- \param name - name of attribute
- \param def - default value (is returned on fail)
+ \brief Get string attribute value from the attribute map.
+
+ Returns default value if the attribute is not found.
+
+ \param attrs attributes map
+ \param name attribute name
+ \param def default attribute value
+ \return attribute value
*/
QString QtxActionMgr::Creator::strValue( const ItemAttributes& attrs,
const QString& name,
}
/*!
- Constructor
+ \brief Creator constructor.
+ \param r action reader
*/
QtxActionMgr::Creator::Creator( QtxActionMgr::Reader* r )
: myReader( r )
}
/*!
- Destructor
+ \brief Creator destructor.
+
+ Does nothing for the moment.
*/
QtxActionMgr::Creator::~Creator()
{
}
/*!
- \return corresponding reader
+ \brief Get actions reader.
+ \return actions reader
*/
QtxActionMgr::Reader* QtxActionMgr::Creator::reader() const
{
}
/*!
- Connects action to some slots (default implementation is empty)
+ \brief Connect action to some specific slot(s)
+
+ Default implementation does nothing.
+
+ \param a action
*/
-void QtxActionMgr::Creator::connect( QAction* ) const
+void QtxActionMgr::Creator::connect( QAction* /*a*/ ) const
{
}
/*!
- Loads pixmap
- \param fname - file name
- \param pix - to return loaded pixmap
+ \brief Load pixmap from the file.
+ \param fname file name
+ \param pix uaed to return pixmap
+ \return \c true if pixmap is loaded successfully and \c false in case of error
*/
bool QtxActionMgr::Creator::loadPixmap( const QString& fname, QPixmap& pix ) const
{
if( !reader() )
return false;
- QStringList dirlist = QStringList::split( ";", reader()->option( "icons_dir", "." ) );
+ QStringList dirlist = reader()->option( "icons_dir", "." ).split( ";", QString::SkipEmptyParts );
QStringList::const_iterator anIt = dirlist.begin(),
aLast = dirlist.end();
bool res = false;
return res;
}
+
+/*!
+ \fn int QtxActionMgr::Creator::append( const QString& tag,
+ const bool subMenu,
+ const ItemAttributes& attr,
+ const int pId )
+ \brief Create (and probably append to the action manager) new action.
+
+ Default implementation is pure virtual.
+
+ \param tag item tag name
+ \param subMenu \c true if this item is submenu
+ \param attr attributes map
+ \param pId parent action ID
+ \return item (for example action) ID
+*/
#include "Qtx.h"
-#include <qmap.h>
-#include <qobject.h>
-#include <qguardedptr.h>
+#include <QMap>
+#include <QObject>
+#include <QPointer>
+class QTimer;
class QAction;
class QDomNode;
-
#ifdef WIN32
#pragma warning( disable:4251 )
#endif
-/*!
- \class QtxActionMgr
- Contains set of actions accessible by id.
- Base class for menu, popup creators and other action containers.
-*/
class QTX_EXPORT QtxActionMgr : public QObject
{
Q_OBJECT
virtual void internalUpdate();
int generateId() const;
+ void triggerUpdate();
+ virtual void updateContent();
+
+private slots:
+ void onUpdateContent();
+
private:
- typedef QGuardedPtr<QAction> ActionPtr;
- typedef QMap<int, ActionPtr> ActionMap;
+ typedef QPointer<QAction> ActionPtr; //!< Action guarded pointer
+ typedef QMap<int, ActionPtr> ActionMap; //!< Actions map
private:
- bool myUpdate;
- ActionMap myActions;
+ bool myUpdate; //!< update flag
+ ActionMap myActions; //!< actions map
+ QTimer* myUpdTimer; //!< update timer
};
-QTX_EXPORT typedef QMap<QString, QString> ItemAttributes;
+QTX_EXPORT typedef QMap<QString, QString> ItemAttributes; //!< attributes map
-/*!
- \class QtxActionMgr::Creator
- Allows to fill automatically action manager with actions created by data from file
-*/
-class QtxActionMgr::Creator
+class QTX_EXPORT QtxActionMgr::Creator
{
public:
Creator( QtxActionMgr::Reader* );
Reader* reader() const;
- virtual int append( const QString&, const bool,
- const ItemAttributes&, const int ) = 0;
- virtual void connect( QAction* ) const;
+ virtual int append( const QString&, const bool,
+ const ItemAttributes&, const int ) = 0;
+ virtual void connect( QAction* ) const;
- virtual bool loadPixmap( const QString&, QPixmap& ) const;
+ virtual bool loadPixmap( const QString&, QPixmap& ) const;
protected:
static int intValue( const ItemAttributes&, const QString&, const int );
static QString strValue( const ItemAttributes&, const QString&,
- const QString& = QString::null );
+ const QString& = QString::null );
private:
- QtxActionMgr::Reader* myReader;
+ QtxActionMgr::Reader* myReader; //!< actions reader
};
-/*!
- \class QtxActionMgr::Reader
- This class is used to read files of some format
- to create actions and to fill action manager automatically
-*/
-class QtxActionMgr::Reader
+class QTX_EXPORT QtxActionMgr::Reader
{
public:
- QTX_EXPORT Reader();
- QTX_EXPORT virtual ~Reader();
+ Reader();
+ virtual ~Reader();
- QTX_EXPORT QStringList options() const;
- QTX_EXPORT QString option( const QString&, const QString& = QString::null ) const;
- QTX_EXPORT void setOption( const QString&, const QString& );
+ QStringList options() const;
+ QString option( const QString&, const QString& = QString::null ) const;
+ void setOption( const QString&, const QString& );
- QTX_EXPORT virtual bool read( const QString&, Creator& ) const = 0;
+ virtual bool read( const QString&, Creator& ) const = 0;
private:
- QMap< QString, QString > myOptions;
+ QMap< QString, QString > myOptions; //!< options map
};
-/*!
- \class QtxActionMgr::Reader
- This class is used to read files of XML format
- to create actions and to fill action manager automatically
-*/
-class QtxActionMgr::XMLReader : public Reader
+class QTX_EXPORT QtxActionMgr::XMLReader : public Reader
{
public:
- QTX_EXPORT XMLReader( const QString&, const QString&, const QString& );
- QTX_EXPORT virtual ~XMLReader();
+ XMLReader( const QString&, const QString&, const QString& );
+ virtual ~XMLReader();
- QTX_EXPORT virtual bool read( const QString&, Creator& ) const;
+ virtual bool read( const QString&, Creator& ) const;
protected:
- QTX_EXPORT virtual void read( const QDomNode&, const int, Creator& ) const;
- QTX_EXPORT virtual bool isNodeSimilar( const QDomNode&, const QString& ) const;
+ virtual void read( const QDomNode&, const int, Creator& ) const;
+ virtual bool isNodeSimilar( const QDomNode&, const QString& ) const;
};
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File: QtxActionSet.cxx
+// Author: Sergey TELKOV
+
+#include "QtxActionSet.h"
+
+/*!
+ \class QtxActionSet
+ \brief An action class which is represented in the menu bar (or toolbar) as
+ a group of items (which can be customized).
+
+ Example: Window menu in the MDI application with menu items:
+ - Cascade
+ - Tile vertically
+ - Tile horizontally
+ - <separator>
+ - Window1
+ - Window2
+*/
+
+/*!
+ \brief Constructor.
+ \param parent parent object
+*/
+QtxActionSet::QtxActionSet( QObject* parent )
+: QtxAction( parent )
+{
+ connect( this, SIGNAL( changed() ), this, SLOT( onChanged() ) );
+
+ setVisible( false );
+
+ update();
+}
+
+/*!
+ \brief Destructor.
+*/
+QtxActionSet::~QtxActionSet()
+{
+}
+
+/*!
+ \brief Get list of child actions.
+ \return list of assigned actions.
+*/
+QList<QAction*> QtxActionSet::actions() const
+{
+ return mySet;
+}
+
+/*!
+ \brief Assign child actions.
+ \param lst list of actions
+*/
+void QtxActionSet::setActions( const QList<QAction*>& lst )
+{
+ for ( ActionList::iterator it = mySet.begin(); it != mySet.end(); ++it )
+ {
+ if ( !lst.contains( *it ) )
+ delete *it;
+ }
+
+ mySet.clear();
+
+ insertActions( lst );
+}
+
+/*!
+ \brief Insert actions at the specified position.
+ \param lst list of actions
+ \param index position in the action list (if < 0, items are appended to the end of list)
+*/
+void QtxActionSet::insertActions( const QList<QAction*>& lst, const int index )
+{
+ int idx = qMin( index < 0 ? mySet.count() : index, mySet.count() );
+
+ for ( QList<QAction*>::const_iterator it = lst.begin(); it != lst.end(); ++it )
+ {
+ QAction* a = *it;
+ int ident = generateId();
+
+ a->setParent( this );
+ mySet.insert( idx++, a );
+ a->setData( ident );
+
+ connect( a, SIGNAL( triggered( bool ) ), this, SLOT( onActionTriggered( bool ) ) );
+ }
+
+ update();
+}
+
+/*!
+ \brief Insert action at the specified position.
+
+ If \a id < 0, it is generated automatically.
+
+ \param a action being inserted
+ \param id action ID
+ \param index position in the action list (if < 0, item is appended to the end of list)
+ \return action identifier
+*/
+int QtxActionSet::insertAction( QAction* a, const int id, const int index )
+{
+ if ( !a )
+ return -1;
+
+ int ident = id < 0 ? generateId() : id;
+ int idx = qMin( index < 0 ? mySet.count() : index, mySet.count() );
+
+ a->setParent( this );
+ mySet.insert( idx, a );
+ a->setData( ident );
+
+ connect( a, SIGNAL( triggered( bool ) ), this, SLOT( onActionTriggered( bool ) ) );
+
+ update();
+
+ return ident;
+}
+
+/*!
+ \brief Insert action at the specified position.
+
+ If \a id < 0, it is generated automatically.
+
+ \param txt action text
+ \param id action ID
+ \param index position in the action list (if < 0, item is appended to the end of list)
+ \return action identifier
+*/
+int QtxActionSet::insertAction( const QString& txt, const int id, const int index )
+{
+ return insertAction( new QtxAction( txt, txt, 0, this ), id, index );
+}
+
+/*!
+ \brief Insert action at the specified position.
+
+ If \a id < 0, it is generated automatically.
+
+ \param txt action text
+ \param icon action icon
+ \param id action ID
+ \param index position in the action list (if < 0, item is appended to the end of list)
+ \return action identifier
+*/
+int QtxActionSet::insertAction( const QString& txt, const QIcon& icon, const int id, const int index )
+{
+ return insertAction( new QtxAction( txt, icon, txt, 0, this ), id, index );
+}
+
+/*!
+ \brief Remove specified action.
+
+ An action is removed from the action list and destroyed.
+
+ \param a action to be removed.
+*/
+void QtxActionSet::removeAction( QAction* a )
+{
+ if ( !mySet.contains( a ) )
+ return;
+
+ mySet.removeAll( a );
+ delete a;
+}
+
+/*!
+ \brief Remove specified action.
+
+ An action is removed from the action list and destroyed.
+
+ \param id action identifier
+*/
+void QtxActionSet::removeAction( const int id )
+{
+ removeAction( action( id ) );
+}
+
+/*!
+ \brief Remove all actions.
+
+ An actions list is cleared and all actions are destroyed.
+*/
+void QtxActionSet::clear()
+{
+ qDeleteAll( mySet );
+ mySet.clear();
+
+ update();
+}
+
+/*!
+ \brief Called when action is changed.
+
+ Update action state.
+*/
+void QtxActionSet::onChanged()
+{
+ if ( !isVisible() || !isEmptyAction() )
+ return;
+
+ bool block = signalsBlocked();
+ blockSignals( true );
+ setVisible( false );
+ blockSignals( block );
+}
+
+/*!
+ \brief Called when some action is activated by the user.
+ \param on toggled state (not used)
+*/
+void QtxActionSet::onActionTriggered( bool )
+{
+ QAction* a = ::qobject_cast<QAction*>( sender() );
+ if ( !a )
+ return;
+
+ int id = actionId( a );
+ if ( id != -1 )
+ emit triggered( id );
+ emit triggered( a );
+}
+
+/*!
+ \brief Called when this action set is added to the menu bar (or toolbar).
+ \param w widget this action set is added to
+*/
+void QtxActionSet::addedTo( QWidget* w )
+{
+ QtxAction::addedTo( w );
+
+ update( w );
+}
+
+/*!
+ \brief Called when this action set is removed from the menu bar (or toolbar).
+ \param w widget this action set is removed from
+*/
+void QtxActionSet::removedFrom( QWidget* w )
+{
+ QtxAction::removedFrom( w );
+
+ update( w );
+}
+
+/*!
+ \brief Get action by specified identifier.
+ \param id action ID
+ \return action or 0 if not found
+*/
+QAction* QtxActionSet::action( int id ) const
+{
+ QAction* a = 0;
+ for ( ActionList::const_iterator it = mySet.begin(); it != mySet.end() && !a; ++it )
+ {
+ if ( actionId( *it ) == id )
+ a = *it;
+ }
+ return a;
+}
+
+/*!
+ \brief Get action identifier for the action.
+ \param a action
+ \return action ID or -1 if not found
+*/
+int QtxActionSet::actionId( QAction* a ) const
+{
+ int id = -1;
+ if ( a && a->data().canConvert( QVariant::Int ) )
+ id = a->data().toInt();
+ return id;
+}
+
+/*!
+ \brief Set action identifier for the action.
+ \param a action
+ \param id new action ID
+*/
+void QtxActionSet::setActionId( QAction* a, const int id )
+{
+ if ( !a || id == -1 )
+ return;
+
+ a->setData( id );
+}
+
+/*!
+ \brief Getneration unique action identifier
+ \return generation action ID
+*/
+int QtxActionSet::generateId() const
+{
+ QMap<int, int> map;
+ for ( ActionList::const_iterator it = mySet.begin(); it != mySet.end(); ++it )
+ map.insert( (*it)->data().toInt(), 0 );
+
+ int id = -2;
+ while ( map.contains( id ) )
+ id--;
+
+ return id;
+}
+
+/*!
+ \brief Update action set.
+*/
+void QtxActionSet::update()
+{
+ QList<QWidget*> lst = associatedWidgets();
+ for ( QList<QWidget*>::iterator it = lst.begin(); it != lst.end(); ++it )
+ update( *it );
+}
+
+/*!
+ \brief Update action set for the specified widget.
+ \param w a widget this action is added to
+*/
+void QtxActionSet::update( QWidget* w )
+{
+ if ( !w )
+ return;
+
+ for ( ActionList::iterator it = mySet.begin(); it != mySet.end(); ++it )
+ w->removeAction( *it );
+
+ if ( !associatedWidgets().contains( w ) )
+ return;
+
+ for ( int i = 0; i < mySet.count(); i++ )
+ {
+ QAction* a = mySet.at( i );
+ w->insertAction( this, a );
+ }
+}
+
+bool QtxActionSet::isEmptyAction() const
+{
+ return true;
+}
+
+/*!
+ \fn void QtxActionSet::triggered( int id );
+ \brief Emitted when some child action is activated by the user.
+ \param action ID
+*/
+
+/*!
+ \fn void QtxActionSet::triggered( QAction* a );
+ \brief Emitted when some child action is activated by the user.
+ \param a action being activated
+*/
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File: QtxActionSet.h
+// Author: Sergey TELKOV
+
+#ifndef QTXACTIONSET_H
+#define QTXACTIONSET_H
+
+#include "QtxAction.h"
+
+#include <QList>
+
+#ifdef WIN32
+#pragma warning( disable:4251 )
+#endif
+
+class QTX_EXPORT QtxActionSet : public QtxAction
+{
+ Q_OBJECT
+
+public:
+ QtxActionSet( QObject* = 0 );
+ virtual ~QtxActionSet();
+
+ QList<QAction*> actions() const;
+ void setActions( const QList<QAction*>& );
+
+ void insertActions( const QList<QAction*>&, const int = -1 );
+
+ int insertAction( QAction*, const int id = -1, const int = -1 );
+ int insertAction( const QString&, const int id = -1, const int = -1 );
+ int insertAction( const QString&, const QIcon&, const int id = -1, const int = -1 );
+
+ void removeAction( QAction* );
+ void removeAction( const int );
+
+ void clear();
+
+signals:
+ void triggered( int );
+ void triggered( QAction* );
+
+private slots:
+ void onChanged();
+ void onActionTriggered( bool = false );
+
+protected:
+ virtual void addedTo( QWidget* );
+ virtual void removedFrom( QWidget* );
+
+ QAction* action( int ) const;
+ int actionId( QAction* ) const;
+ void setActionId( QAction*, const int );
+
+ virtual bool isEmptyAction() const;
+
+private:
+ void update();
+ void update( QWidget* );
+ int generateId() const;
+
+private:
+ typedef QList<QAction*> ActionList;
+
+private:
+ ActionList mySet; //!< actions list
+};
+
+#ifdef WIN32
+#pragma warning( default:4251 )
+#endif
+
+#endif
#include "QtxAction.h"
#include "QtxToolBar.h"
-#include <qmainwindow.h>
-#include <qobjectlist.h>
+#include <QMainWindow>
/*!
- Constructor
+ \class QtxActionToolMgr::ToolNode
+ \internal
+ \brief Represents a toolbutton inside toolbar structure.
+*/
+
+/*!
+ \fn QtxActionToolMgr::ToolNode::ToolNode()
+ \brief Default constructor.
+*/
+
+/*!
+ \fn QtxActionToolMgr::ToolNode::ToolNode( const int _id )
+ \brief Constructor.
+ \param _id toolbar node ID
+*/
+
+
+/*!
+ \class QtxActionToolMgr
+ \brief Toolbar actions manager.
+
+ Toolbar manager allows using of set of action for automatic generating of
+ application toolbars and dynamic update of toolbars contents.
+
+ Use insert(), append() and remove() methods to create toolbar and add actions to it.
+ Methods show(), hide() allow displaying/erasing of specified toolbar items.
+
+ Toolbar manager automatically optimizes toolbars by removing extra separators, etc.
+*/
+
+/*!
+ \brief Constructor.
+ \param p parent main window
*/
QtxActionToolMgr::QtxActionToolMgr( QMainWindow* p )
: QtxActionMgr( p ),
-myMainWindow( p )
+ myMainWindow( p )
{
}
/*!
- Destructor
+ \brief Destructor.
*/
QtxActionToolMgr::~QtxActionToolMgr()
{
}
/*!
- \return desktop
+ \brief Get parent main window.
+ \return main window pointer
*/
QMainWindow* QtxActionToolMgr::mainWindow() const
{
}
/*!
- Creates toolbar
- \return id of just created toolbar
- \param name - name of toolbar
- \param tid - proposed id (if such id is used already, then it will be returned without creation)
+ \brief Create toolbar and assign \a id to it.
+
+ If \a tid is less than 0, the ID is generated automatically.
+ If toolbar with given \a tid is already registered, the toolbar will not be created.
+
+ \param title toolbar title
+ \param tid requested toolbar ID
+ \return id of created/found toolbar
*/
-int QtxActionToolMgr::createToolBar( const QString& name, const int tid )
+int QtxActionToolMgr::createToolBar( const QString& title, const int tid )
{
static int _toolBarId = -1;
int tbId = -1;
for ( ToolBarMap::ConstIterator it = myToolBars.begin(); it != myToolBars.end() && tbId == -1; ++it )
{
- if ( it.data().toolBar->label().lower() == name.lower() )
+ if ( it.value().toolBar->windowTitle().toLower() == title.toLower() )
tbId = it.key();
}
if ( tbId != -1 )
return tbId;
- QToolBar* tb = find( name, mainWindow() );
+ QToolBar* tb = find( title, mainWindow() );
tbId = tid < 0 ? --_toolBarId : tid;
if ( !tb )
{
tb = new QtxToolBar( true, mainWindow() );
- tb->setLabel( name );
+ mainWindow()->addToolBar( tb );
+ tb->setWindowTitle( title );
}
tInfo.toolBar = tb;
}
/*!
- \return toolbar by title
- \param label - toolbar title
- \param mw - desktop
+ \brief Search toolbar with given \a title owned by main window \mw.
+ \param title toolbar title
+ \param mw main window
+ \return toolbar or 0 if not found
*/
-QToolBar* QtxActionToolMgr::find( const QString& label, QMainWindow* mw ) const
+QToolBar* QtxActionToolMgr::find( const QString& title, QMainWindow* mw ) const
{
if ( !mw )
return 0;
- QString pattern = label.lower();
+ QString pattern = title.toLower();
QToolBar* res = 0;
- QPtrList<QDockWindow> lst = mw->dockWindows();
- for ( QPtrListIterator<QDockWindow> it( lst ); it.current() && !res; ++it )
+ QList<QToolBar*> toolbars = qFindChildren<QToolBar*>( mw );
+ for ( QList<QToolBar*>::iterator it = toolbars.begin(); it != toolbars.end() && !res; ++it )
{
- if ( !it.current()->inherits( "QToolBar" ) )
- continue;
-
- QToolBar* cur = (QToolBar*)it.current();
- if ( cur->label().lower() == pattern )
- res = cur;
+ if ( (*it)->windowTitle().toLower() == pattern )
+ res = *it;
}
return res;
}
/*!
- Removes toolbar
- \param tid - toolbar id
+ \brief Remove toolbar.
+ \param tid toolbar ID
*/
void QtxActionToolMgr::removeToolBar( const int tid )
{
}
/*!
- Removes toolbar
- \param tname - toolbar name
+ \brief Remove toolbar.
+ \param title toolbar title
*/
-void QtxActionToolMgr::removeToolBar( const QString& tname )
+void QtxActionToolMgr::removeToolBar( const QString& title )
{
- removeToolBar( find( tname ) );
+ removeToolBar( find( title ) );
}
/*!
- Insert action into toolbar
- \param id - identificator of action
- \param tId - identificator of toolbar
- \param idx - position inside toolbar
+ \brief Insert action into toolbar.
+ \param id action ID
+ \param tid toolbar ID
+ \param idx action index in the toolbar (if < 0, action is appended to the end)
+ \return action ID
*/
int QtxActionToolMgr::insert( const int id, const int tid, const int idx )
{
if ( !contains( id ) || !hasToolBar( tid ) )
return -1;
-
+/*
if ( containsAction( id, tid ) )
remove( id, tid );
-
- ToolNode node;
- node.id = id;
+*/
+ ToolNode node( id );
NodeList& list = myToolBars[tid].nodes;
- int index = idx < 0 ? list.count() : QMIN( idx, (int)list.count() );
- list.insert( list.at( index ), node );
- updateToolBar( tid );
+ int index = idx < 0 ? list.count() : qMin( idx, (int)list.count() );
+ list.insert( index, node );
+ triggerUpdate( tid );
return id;
}
/*!
- Insert action into toolbar
- \param act - action
- \param tId - identificator of toolbar
- \param pos - position inside toolbar
+ \brief Insert action into toolbar.
+ \param a action
+ \param tid toolbar ID
+ \param idx action index in the toolbar (if < 0, action is appended to the end)
+ \return action ID
*/
-int QtxActionToolMgr::insert( QAction* act, const int tid, const int pos )
+int QtxActionToolMgr::insert( QAction* a, const int tid, const int idx )
{
- return insert( registerAction( act ), tid, pos );
+ return insert( registerAction( a ), tid, idx );
}
/*!
- Insert action into toolbar
- \param id - identificator of action
- \param tname - name of toolbar
- \param pos - position inside toolbar
+ \brief Insert action into toolbar.
+ \param id action ID
+ \param title toolbar title
+ \param idx action index in the toolbar (if < 0, action is appended to the end)
+ \return action ID
*/
-int QtxActionToolMgr::insert( const int id, const QString& tname, const int pos )
+int QtxActionToolMgr::insert( const int id, const QString& title, const int idx )
{
- return insert( id, createToolBar( tname ), pos );
+ return insert( id, createToolBar( title ), idx );
}
/*!
- Insert action into toolbar
- \param act - action
- \param tname - name of toolbar
- \param pos - position inside toolbar
+ \brief Insert action into toolbar.
+ \param a action
+ \param title toolbar title
+ \param idx action index in the toolbar (if < 0, action is appended to the end)
+ \return action ID
*/
-int QtxActionToolMgr::insert( QAction* act, const QString& tname, const int pos )
+int QtxActionToolMgr::insert( QAction* a, const QString& title, const int idx )
{
- return insert( registerAction( act ), createToolBar( tname ), pos );
+ return insert( registerAction( a ), createToolBar( title ), idx );
}
/*!
- Append action into toolbar as last toolbutton
- \param id - identificator of action
- \param tId - identificator of toolbar
+ \brief Append action to the end of toolbar.
+ \param id action ID
+ \param tid toolbar ID
+ \return action ID
*/
int QtxActionToolMgr::append( const int id, const int tid )
{
}
/*!
- Append action into toolbar as last toolbutton
- \param act - action
- \param tId - identificator of toolbar
+ \brief Append action to the end of toolbar.
+ \param a action
+ \param tid toolbar ID
+ \return action ID
*/
-int QtxActionToolMgr::append( QAction* act, const int tid )
+int QtxActionToolMgr::append( QAction* a, const int tid )
{
- return insert( act, tid );
+ return insert( a, tid );
}
/*!
- Append action into toolbar as last toolbutton
- \param id - identificator of action
- \param tname - toolbar name
+ \brief Append action to the end of toolbar.
+ \param id action ID
+ \param title toolbar title
+ \return action ID
*/
-int QtxActionToolMgr::append( const int id, const QString& tname )
+int QtxActionToolMgr::append( const int id, const QString& title )
{
- return insert( id, tname );
+ return insert( id, title );
}
/*!
- Append action into toolbar as last toolbutton
- \param act - action
- \param tname - toolbar name
+ \brief Append action to the end of toolbar.
+ \param a action
+ \param title toolbar title
+ \return action ID
*/
-int QtxActionToolMgr::append( QAction* act, const QString& tname )
+int QtxActionToolMgr::append( QAction* a, const QString& title )
{
- return insert( act, tname );
+ return insert( a, title );
}
/*!
- Append action into toolbar as first toolbutton
- \param id - identificator of action
- \param tId - identificator of toolbar
+ \brief Insert action to the beginning of toolbar.
+ \param id action ID
+ \param tid toolbar ID
+ \return action ID
*/
int QtxActionToolMgr::prepend( const int id, const int tid )
{
}
/*!
- Append action into toolbar as first toolbutton
- \param act - action
- \param tId - identificator of toolbar
+ \brief Insert action to the beginning of toolbar.
+ \param a action
+ \param tid toolbar ID
+ \return action ID
*/
-int QtxActionToolMgr::prepend( QAction* act, const int tid )
+int QtxActionToolMgr::prepend( QAction* a, const int tid )
{
- return insert( act, tid, 0 );
+ return insert( a, tid, 0 );
}
/*!
- Append action into toolbar as first toolbutton
- \param id - identificator of action
- \param tname - toolbar name
+ \brief Insert action to the beginning of toolbar.
+ \param id action ID
+ \param title toolbar title
+ \return action ID
*/
-int QtxActionToolMgr::prepend( const int id, const QString& tname )
+int QtxActionToolMgr::prepend( const int id, const QString& title )
{
- return insert( id, tname, 0 );
+ return insert( id, title, 0 );
}
/*!
- Append action into toolbar as first toolbutton
- \param act - action
- \param tname - toolbar name
+ \brief Insert action to the beginning of toolbar.
+ \param a action ID
+ \param title toolbar title
+ \return action ID
*/
-int QtxActionToolMgr::prepend( QAction* act, const QString& tname )
+int QtxActionToolMgr::prepend( QAction* a, const QString& tname )
{
- return insert( act, tname, 0 );
+ return insert( a, tname, 0 );
}
/*!
- Remove action from toolbar
- \param id - identificator of action
- \param tId - identificator of toolbar
+ \brief Remove action from toolbar.
+ \param id action ID
+ \param tid toolbar ID
*/
void QtxActionToolMgr::remove( const int id, const int tid )
{
myToolBars[tid].nodes = newList;
- updateToolBar( tid );
+ triggerUpdate( tid );
}
/*!
- Remove action from toolbar
- \param id - identificator of action
- \param tname - name of toolbar
+ \brief Remove action from toolbar.
+ \param id action ID
+ \param title toolbar title
*/
-void QtxActionToolMgr::remove( const int id, const QString& tname )
+void QtxActionToolMgr::remove( const int id, const QString& title )
{
- remove( id, find( tname ) );
+ remove( id, find( title ) );
}
/*!
- \return toolbar by it's id
- \param tId - identificator of toolbar
+ \brief Get toolbar by given \a tid.
+ \param tid toolbar ID
+ \return toolbar or 0 if not found
*/
QToolBar* QtxActionToolMgr::toolBar( const int tid ) const
{
}
/*!
- \return toolbar by it's name
- \param tname - name of toolbar
+ \brief Get toolbar by given \a title.
+ \param title toolbar title
+ \return toolbar or 0 if not found
*/
-QToolBar* QtxActionToolMgr::toolBar( const QString& tname ) const
+QToolBar* QtxActionToolMgr::toolBar( const QString& title ) const
{
- return toolBar( find( tname ) );
+ return toolBar( find( title ) );
}
/*!
- \return true if manager contains toolbar with such id
- \param tId - identificator of toolbar
+ \brief Check if toolbar with given \a id already registered.
+ \param tid toolbar ID
+ \return \c true if toolbar is registered in the toolbar manager
*/
bool QtxActionToolMgr::hasToolBar( const int tid ) const
{
}
/*!
- \return true if manager contains toolbar with such name
- \param tname - name of toolbar
+ \brief Check if toolbar with given \a id already registered.
+ \param title toolbar title
+ \return \c true if toolbar is registered in the toolbar manager
*/
-bool QtxActionToolMgr::hasToolBar( const QString& tname ) const
+bool QtxActionToolMgr::hasToolBar( const QString& title ) const
{
- return find( tname ) != -1;
+ return find( title ) != -1;
}
/*!
- \return true if toolbar contains action
- \param id - identificator of action
- \param tId - identificator of toolbar
+ \brief Check if toolbar contains given action.
+ \param id action ID
+ \param tid toolbar ID
+ \return \c true if toolbar contains action
*/
bool QtxActionToolMgr::containsAction( const int id, const int tid ) const
{
for ( ToolBarMap::ConstIterator it = myToolBars.begin(); it != myToolBars.end(); ++it )
{
- if ( tid == -1 || it.key() == tid ) {
- const NodeList& list = it.data().nodes;
+ if ( tid == -1 || it.key() == tid )
+ {
+ const NodeList& list = it.value().nodes;
for ( NodeList::const_iterator nit = list.begin(); nit != list.end(); ++nit )
if ( (*nit).id == id )
return true;
}
/*!
- SLOT: called when toolbar is destroyed, removes just destroyed toolbar from map
+ \brief Called when toolbar is destroyed.
+
+ Clears internal pointer to the toolbar to disable crashes.
*/
void QtxActionToolMgr::onToolBarDestroyed()
{
}
/*!
- \return id of toolbar by it's name
- \param tname - name of toolbar
+ \brief Search toolbar by given \a name.
+ \param title toolbar title
+ \return toolbar ID or -1 if not found
*/
-int QtxActionToolMgr::find( const QString& tname ) const
+int QtxActionToolMgr::find( const QString& title ) const
{
int id = -1;
for ( ToolBarMap::ConstIterator it = myToolBars.begin(); it != myToolBars.end() && id == -1; ++it )
{
- if ( it.data().toolBar->label() == tname )
+ if ( it.value().toolBar->windowTitle() == title )
id = it.key();
}
return id;
}
/*!
- \return id of toolbar
- \param t - toolbar
+ \brief Get toolbar ID.
+ \param tb toolbar
+ \return toolbar ID or -1 if toolbar is not registered
*/
-int QtxActionToolMgr::find( QToolBar* t ) const
+int QtxActionToolMgr::find( QToolBar* tb ) const
{
int id = -1;
for ( ToolBarMap::ConstIterator it = myToolBars.begin(); it != myToolBars.end() && id == -1; ++it )
{
- if ( it.data().toolBar == t )
+ if ( it.value().toolBar == tb )
id = it.key();
}
return id;
}
/*!
- Updates toolbar
- \param tId - toolbar id
+ \brief Update toolbar.
+ \param tid toolbar ID
*/
-void QtxActionToolMgr::updateToolBar( const int tId )
+void QtxActionToolMgr::updateToolBar( const int tid )
{
if ( !isUpdatesEnabled() )
return;
- if ( !myToolBars.contains( tId ) )
+ if ( !myToolBars.contains( tid ) )
return;
- QToolBar* tb = myToolBars[tId].toolBar;
- const NodeList& list = myToolBars[tId].nodes;
+ QToolBar* tb = myToolBars[tid].toolBar;
+ const NodeList& list = myToolBars[tid].nodes;
for ( NodeList::const_iterator it = list.begin(); it != list.end(); ++it )
{
QAction* a = action( (*it).id );
- if ( a )
- a->removeFrom( tb );
+ tb->removeAction( a );
+// if ( a )
+// a->removeFrom( tb );
}
tb->clear();
for ( NodeList::const_iterator itr = list.begin(); itr != list.end(); ++itr )
{
- if ( !isVisible( (*itr).id, tId ) )
+ if ( !isVisible( (*itr).id, tid ) )
continue;
QAction* a = action( (*itr).id );
- if ( a )
- a->addTo( tb );
+ tb->addAction( a );
+// if ( a )
+// a->addTo( tb );
}
simplifySeparators( tb );
}
/*!
- Updates all toolbars
+ \brief Update all registered toolbars.
*/
void QtxActionToolMgr::internalUpdate()
{
+ if ( !isUpdatesEnabled() )
+ return;
+
for ( ToolBarMap::ConstIterator it1 = myToolBars.begin(); it1 != myToolBars.end(); ++it1 )
updateToolBar( it1.key() );
+
+ myUpdateIds.clear();
}
/*!
- Removes excess separators from toolbar
+ \brief Remove extra separators from toolbar.
+ \param tb toolbar
*/
-void QtxActionToolMgr::simplifySeparators( QToolBar* t )
+void QtxActionToolMgr::simplifySeparators( QToolBar* tb )
{
- if ( t )
- Qtx::simplifySeparators( t );
+ Qtx::simplifySeparators( tb );
}
/*!
- Shows action in all toolbars
- \param actId - action id
+ \brief Show action (in all toolbars)
+ \param id action ID
*/
-void QtxActionToolMgr::show( const int actId )
+void QtxActionToolMgr::show( const int id )
{
- setShown( actId, true );
+ setShown( id, true );
}
/*!
- Hides action in all toolbars
- \param actId - action id
+ \brief Hide action (in all toolbars)
+ \param id action ID
*/
-void QtxActionToolMgr::hide( const int actId )
+void QtxActionToolMgr::hide( const int id )
{
- setShown( actId, false );
+ setShown( id, false );
}
/*!
- Changes shown status of action in all toolbars
- \param id - action id
- \param on - new shown status
+ \brief Set visibility status for toolbar action with given \a id.
+ \param id action ID
+ \param on new visibility status
*/
void QtxActionToolMgr::setShown( const int id, const bool on )
{
}
/*!
- \return true if action is shown in all toolbars
- \param id - action id
+ \brief Get visibility status for toolbar action with given \a id.
+ \param id action ID
+ \return \c true if action is shown in all toolbars
*/
bool QtxActionToolMgr::isShown( const int id ) const
{
- QPtrList<ToolNode> nodes;
+ QList<const ToolNode*> nodes;
for ( ToolBarMap::ConstIterator it = myToolBars.begin(); it != myToolBars.end(); ++it )
{
- const NodeList& nl = it.data().nodes;
+ const NodeList& nl = it.value().nodes;
for ( NodeList::const_iterator itr = nl.begin(); itr != nl.end(); ++itr )
{
const ToolNode& node = *itr;
return false;
bool vis = true;
- for ( QPtrListIterator<ToolNode> itr( nodes ); itr.current() && vis; ++itr )
- vis = itr.current()->visible;
+ for ( QList<const ToolNode*>::iterator itr = nodes.begin(); itr != nodes.end() && vis; ++itr )
+ vis = (*itr)->visible;
return vis;
}
/*!
- \return shown status of action in toolbar
- \param id - action id
- \param tId - toolbar id
+ \brief Check if an action with given \a id is visible in the toolbar \a tid.
+ \param id action ID
+ \param tid toolbar ID
+ \return \c true if action is shown in the toolbar
*/
-bool QtxActionToolMgr::isVisible( const int id, const int tId ) const
+bool QtxActionToolMgr::isVisible( const int id, const int tid ) const
{
- if ( !myToolBars.contains( tId ) )
+ if ( !myToolBars.contains( tid ) )
return false;
bool vis = false;
- const NodeList& lst = myToolBars[tId].nodes;
+ const NodeList& lst = myToolBars[tid].nodes;
for ( NodeList::const_iterator it = lst.begin(); it != lst.end() && !vis; ++it )
{
const ToolNode& node = *it;
if ( node.id == id )
+
vis = node.visible;
}
return vis;
}
/*!
- Changes action shown status in certain toolbar
- \param id - action id
- \param tId - toolbar id
- \param on - new shown status
+ \brief Show/hide action with given \a id in the toolbar \a tid.
+ \param id action ID
+ \param tid toolbar ID
+ \param on new visibility status
*/
-void QtxActionToolMgr::setVisible( const int id, const int tId, const bool on )
+void QtxActionToolMgr::setVisible( const int id, const int tid, const bool on )
{
- if ( !myToolBars.contains( tId ) )
+ if ( !myToolBars.contains( tid ) )
return;
bool changed = false;
- NodeList& lst = myToolBars[tId].nodes;
+ NodeList& lst = myToolBars[tid].nodes;
for ( NodeList::iterator it = lst.begin(); it != lst.end(); ++it )
{
ToolNode& node = *it;
}
if ( changed )
- updateToolBar( tId );
+ triggerUpdate( tid );
}
/*!
- Loads toolbar content from file
- \param fname - file name
- \param r - reader
+ \brief Load toolbar contents from the file.
+ \param fname file name
+ \param r actions reader
+ \return \c true on success and \c false on error
*/
bool QtxActionToolMgr::load( const QString& fname, QtxActionMgr::Reader& r )
{
return r.read( fname, cr );
}
+/*!
+ \brief Called when delayed content update is performed.
+
+ Customizes the content update operation.
+*/
+void QtxActionToolMgr::updateContent()
+{
+ if ( !isUpdatesEnabled() )
+ return;
+
+ for ( QMap<int,int>::const_iterator it = myUpdateIds.constBegin(); it != myUpdateIds.constEnd(); ++it )
+ updateToolBar( it.key() );
+ myUpdateIds.clear();
+}
+
+/*!
+ \brief Perform delayed toolbar update.
+ \param tid toolbar ID
+*/
+void QtxActionToolMgr::triggerUpdate( const int tid )
+{
+ myUpdateIds.insert( tid, 0 );
+ QtxActionMgr::triggerUpdate();
+}
+
/*!
- Constructor
+ \class QtxActionToolMgr::ToolCreator
+ \brief Toolbars creator.
+
+ Used by Reader to create actions by reading descriptions from the file,
+ create toolbars and fill in the toolbara with the actions.
+*/
+
+/*!
+ \brief Constructor.
+ \param r actions reader
+ \param mgr toolbar manager
*/
QtxActionToolMgr::ToolCreator::ToolCreator( QtxActionMgr::Reader* r,
QtxActionToolMgr* mgr )
}
/*!
- Destructor
+ \brief Creator destructor.
+
+ Does nothing for the moment.
*/
QtxActionToolMgr::ToolCreator::~ToolCreator()
{
}
/*!
- Appends new tool buttons
- \param tag - tag of toolmenu
- \param subMenu - it has submenu (not used here)
- \param attr - list of attributes
- \param pId - id of action corresponding to parent item
+ \brief Create and append to the action manager a new toolbar or toolbar action.
+ \param tag item tag name
+ \param subMenu \c true if this item is submenu (not used)
+ \param attr attributes map
+ \param tid toolbar ID
+ \return toolbar or toolbar action ID
*/
-int QtxActionToolMgr::ToolCreator::append( const QString& tag, const bool subMenu,
- const ItemAttributes& attr, const int tId )
+int QtxActionToolMgr::ToolCreator::append( const QString& tag, const bool /*subMenu*/,
+ const ItemAttributes& attr, const int tid )
{
if( !myMgr || !reader() )
return -1;
toggle = reader()->option( "toggle", "toggle" );
int res = -1, actId = intValue( attr, id, -1 );
- if( tId==-1 )
+ if( tid==-1 )
res = myMgr->createToolBar( strValue( attr, label ), intValue( attr, id, -1 ) );
else if( tag==sep )
- res = myMgr->insert( separator(), tId, intValue( attr, pos, -1 ) );
+ res = myMgr->insert( separator(), tid, intValue( attr, pos, -1 ) );
else
{
- QPixmap pix; QIconSet set;
+ QIcon set;
+ QPixmap pix;
QString name = strValue( attr, icon );
if( !name.isEmpty() && loadPixmap( name, pix ) )
- set = QIconSet( pix );
+ set = QIcon( pix );
- QtxAction* newAct = new QtxAction( strValue( attr, tooltip ), set,
- strValue( attr, label ),
- QKeySequence( strValue( attr, accel ) ),
- myMgr );
+ QtxAction* newAct = new QtxAction( strValue( attr, tooltip ), set, strValue( attr, label ),
+ QKeySequence( strValue( attr, accel ) ), myMgr );
QString toggleact = strValue( attr, toggle );
- newAct->setToggleAction( !toggleact.isEmpty() );
- newAct->setOn( toggleact.lower()=="true" );
+ newAct->setCheckable( !toggleact.isEmpty() );
+ newAct->setChecked( toggleact.toLower() == "true" );
connect( newAct );
int aid = myMgr->registerAction( newAct, actId );
- res = myMgr->insert( aid, tId, intValue( attr, pos, -1 ) );
+ res = myMgr->insert( aid, tid, intValue( attr, pos, -1 ) );
}
return res;
}
-
-
#define QTXACTIONTOOLMGR_H
#include "Qtx.h"
-
-#include <qaction.h>
-
#include "QtxActionMgr.h"
+#include <QMap>
+#include <QList>
+
class QToolBar;
class QMainWindow;
+class QAction;
#ifdef WIN32
#pragma warning( disable:4251 )
#endif
-/*!
- \class QtxActionToolMgr
- Allows to use set of action to automatically build set of toolbars.
- With help of methods insert/append/remove it is possible to
- describe toolbars and its internal structure.
- This manager is able to attune toolbar by removing excess separators
-*/
class QTX_EXPORT QtxActionToolMgr : public QtxActionMgr
{
Q_OBJECT
- /*!
- \class ToolNode
- Represents a toolbutton inside toolbar
- For internal purposes only
- */
class ToolNode
{
public:
ToolNode() : id( -1 ), visible( true ) {};
+ ToolNode( const int _id ) : id( _id ), visible( true ) {};
- int id;
- bool visible;
+ int id; //!< tool node ID
+ bool visible; //!< visibility status
};
- typedef QValueList<ToolNode> NodeList;
+ typedef QList<ToolNode> NodeList; //!< toolbar nodes list
protected:
class ToolCreator;
virtual void internalUpdate();
void updateToolBar( const int );
+ virtual void updateContent();
+
private:
void simplifySeparators( QToolBar* );
+ void triggerUpdate( const int );
private:
- typedef struct { NodeList nodes; QToolBar* toolBar; } ToolBarInfo;
- typedef QMap<int, ToolBarInfo> ToolBarMap;
+ typedef struct { NodeList nodes; QToolBar* toolBar; } ToolBarInfo; //!< toolbar info
+ typedef QMap<int, ToolBarInfo> ToolBarMap; //!< toolbars map
private:
- ToolBarMap myToolBars;
- QMainWindow* myMainWindow;
+ ToolBarMap myToolBars; //!< toobars map
+ QMainWindow* myMainWindow; //!< parent main window
+ QMap<int,int> myUpdateIds; //!< list of actions ID being updated
};
-/*!
- \class QtxActionToolMgr::ToolCreator
- Allows to create automatically toolbar by data read from file
-*/
class QtxActionToolMgr::ToolCreator : public QtxActionMgr::Creator
{
public:
const ItemAttributes&, const int );
private:
- QtxActionToolMgr* myMgr;
+ QtxActionToolMgr* myMgr; //!< toolbar manager
};
#endif
#include "QtxColorScale.h"
-#include <qmap.h>
-#include <qimage.h>
-#include <qregexp.h>
-#include <qpixmap.h>
-#include <qbitmap.h>
-#include <qpainter.h>
-#include <qmainwindow.h>
-#include <qstringlist.h>
-#include <qstylesheet.h>
-#include <qsimplerichtext.h>
+#include <QMap>
+#include <QRegExp>
+#include <QStringList>
+#include <QPixmap>
+#include <QPainter>
+#include <QTextDocument>
#include <math.h>
/*!
- Constructor
+ \class QtxColorScale
+ \brief Color Scale widget.
*/
-QtxColorScale::QtxColorScale( QWidget* parent, const char* name, WFlags f )
-: QFrame( parent, name, f | WResizeNoErase | WRepaintNoErase ),
-myDock( 0 ),
-myMin( 0.0 ),
-myMax( 1.0 ),
-myTitle( "" ),
-myInterval( 10 ),
-myStyleSheet( 0 ),
-myFormat( "%.4g" ),
-myColorMode( Auto ),
-myLabelMode( Auto ),
-myLabelPos( Right ),
-myTitlePos( Center ),
-myDumpMode( NoDump ),
-myFlags( AtBorder | WrapTitle )
-{
- setCaption( tr ( "Color scale" ) );
-}
/*!
- Constructor
+ \brief Constructor.
+ \param parent parent widget
+ \param f widget flags
*/
-QtxColorScale::QtxColorScale( const int num, QWidget* parent, const char* name, WFlags f )
-: QFrame( parent, name, f | WResizeNoErase | WRepaintNoErase ),
-myDock( 0 ),
-myMin( 0.0 ),
-myMax( 1.0 ),
-myTitle( "" ),
-myInterval( num ),
-myStyleSheet( 0 ),
-myFormat( "%.4g" ),
-myColorMode( Auto ),
-myLabelMode( Auto ),
-myLabelPos( Right ),
-myTitlePos( Center ),
-myDumpMode( NoDump ),
-myFlags( AtBorder | WrapTitle )
+QtxColorScale::QtxColorScale( QWidget* parent, Qt::WindowFlags f )
+: QFrame( parent, f ),
+ myMin( 0.0 ),
+ myMax( 1.0 ),
+ myTitle( "" ),
+ myFormat( "%.4g" ),
+ myInterval( 10 ),
+ myDumpMode( NoDump ),
+ myColorMode( Auto ),
+ myLabelMode( Auto ),
+ myFlags( AtBorder | WrapTitle ),
+ myLabelPos( Right ),
+ myTitlePos( Center )
{
- setCaption( tr ( "Color scale" ) );
+ setWindowTitle( tr ( "Color scale" ) );
}
-#if QT_VER == 3
-
/*!
- Constructor
+ \brief Constructor.
+ \param num number of color scale intervals
+ \param parent parent widget
+ \param f widget flags
*/
-QtxColorScale::QtxColorScale( Dock* dock, const char* name, WFlags f )
-: QFrame( dock, name, f | WResizeNoErase | WRepaintNoErase ),
-myMin( 0.0 ),
-myMax( 1.0 ),
-myTitle( "" ),
-myDock( dock ),
-myInterval( 10 ),
-myStyleSheet( 0 ),
-myFormat( "%.4g" ),
-myColorMode( Auto ),
-myLabelMode( Auto ),
-myLabelPos( Right ),
-myTitlePos( Center ),
-myDumpMode( NoDump ),
-myFlags( AtBorder | WrapTitle )
+QtxColorScale::QtxColorScale( const int num, QWidget* parent, Qt::WindowFlags f )
+: QFrame( parent, f ),
+ myMin( 0.0 ),
+ myMax( 1.0 ),
+ myTitle( "" ),
+ myFormat( "%.4g" ),
+ myInterval( num ),
+ myDumpMode( NoDump ),
+ myColorMode( Auto ),
+ myLabelMode( Auto ),
+ myFlags( AtBorder | WrapTitle ),
+ myLabelPos( Right ),
+ myTitlePos( Center )
{
- setCaption( tr ( "Color scale" ) );
+ setWindowTitle( tr ( "Color scale" ) );
}
-#endif
-
/*!
- Destructor
+ \brief Destructor.
+
+ Does nothing for the moment.
*/
QtxColorScale::~QtxColorScale()
{
}
/*!
- \returns minimal limit of scale.
+ \brief Get color scale minimum value.
+ \return lower limit of the color scale
*/
double QtxColorScale::minimum() const
{
- return myMin;
+ return myMin;
}
/*!
- \return maximal limit of scale.
+ \brief Get color scale maximum value.
+ \return upper limit of the color scale
*/
double QtxColorScale::maximum() const
{
- return myMax;
+ return myMax;
}
/*!
- \return range (minimal and maximal limits) of scale.
+ \brief Get color scale range.
+ \param min returning lower limit of the color scale
+ \param max returning upper limit of the color scale
*/
void QtxColorScale::range( double& min, double& max ) const
{
- min = myMin;
- max = myMax;
+ min = myMin;
+ max = myMax;
}
/*!
- \return the current title string.
+ \brief Get color scale title.
+ \return current title
*/
QString QtxColorScale::title() const
{
- return myTitle;
+ return myTitle;
}
/*!
- \returns the current format of number presentation in labels for Auto label mode (sprintf specification).
+ \brief Get current format of the number presentation.
+
+ This format is used to output values in the color scale labels
+ in "Auto" label mode. The format uses sprintf specification.
+
+ \return current format
*/
QString QtxColorScale::format() const
{
- return myFormat;
+ return myFormat;
}
/*!
- \return dump mode.
+ \brief Get Color scale dump mode.
+ \return current dump mode (QtxColorScale::DumpMode)
*/
int QtxColorScale::dumpMode() const
{
- return myDumpMode;
+ return myDumpMode;
}
/*!
- \return label mode.
+ \brief Get label mode.
+ \return current label mode (QtxColorScale::Mode)
*/
int QtxColorScale::labelMode() const
{
- return myLabelMode;
+ return myLabelMode;
}
/*!
- \return color mode.
+ \brief Get color mode.
+ \return current color mode (QtxColorScale::Mode)
*/
int QtxColorScale::colorMode() const
{
- return myColorMode;
+ return myColorMode;
}
/*!
- \return intervals number of color scale.
+ \brief Get number of color scale intervals.
+ \return number of intervals
*/
int QtxColorScale::intervalsNumber() const
{
- return myInterval;
+ return myInterval;
}
/*!
- \return the user label of specified interval.
+ \brief Get user label for the specified color scale interval.
+ \param idx interval index
+ \return user label for specified interval
*/
QString QtxColorScale::label( const int idx ) const
{
- QString res;
- if ( idx >= 0 && idx < (int)myLabels.count() )
- res = *myLabels.at( idx );
- return res;
+ QString res;
+ if ( idx >= 0 && idx < (int)myLabels.count() )
+ res = myLabels[idx];
+ return res;
}
/*!
- \return the user color of specified interval.
+ \brief Get user color for the specified color scale interval.
+ \param idx interval index
+ \return user color for specified interval
*/
QColor QtxColorScale::color( const int idx ) const
{
- QColor res;
- if ( idx >= 0 && idx < (int)myColors.count() )
- res = *myColors.at( idx );
- return res;
+ QColor res;
+ if ( idx >= 0 && idx < (int)myColors.count() )
+ res = myColors[idx];
+ return res;
}
/*!
- \return the user labels.
+ \brief Get user labels for all color scale intervals.
+ \param list returning labels list
*/
void QtxColorScale::labels( QStringList& list ) const
{
- list = myLabels;
+ list = myLabels;
}
/*!
- \return the user color.
+ \brief Get user colors for all color scale intervals.
+ \param list returning colors list
*/
-void QtxColorScale::colors( QValueList<QColor>& list ) const
+void QtxColorScale::colors( QList<QColor>& list ) const
{
- list = myColors;
+ list = myColors;
}
/*!
- \return the label position.
+ \brief Get label position.
+ \return label position (QtxColorScale::Position)
*/
int QtxColorScale::labelPosition() const
{
- return myLabelPos;
+ return myLabelPos;
}
/*!
- \return the title position.
+ \brief Get title position.
+ \return title position (QtxColorScale::Position)
*/
int QtxColorScale::titlePosition() const
{
- return myTitlePos;
+ return myTitlePos;
}
/*!
- Sets the minimum limit.
+ \brief Set color scale minimum value.
+ \param val lower limit of the color scale
*/
void QtxColorScale::setMinimum( const double val )
{
- setRange( val, maximum() );
+ setRange( val, maximum() );
}
/*!
- Sets the maximum limit.
+ \brief Set color scale maximum value.
+ \param val upper limit of the color scale
*/
void QtxColorScale::setMaximum( const double val )
{
- setRange( minimum(), val );
+ setRange( minimum(), val );
}
/*!
- Sets the minimum and maximum limits.
+ \brief Set color scale range.
+ \param min lower limit of the color scale
+ \param max upper limit of the color scale
*/
void QtxColorScale::setRange( const double min, const double max )
{
- if ( myMin == min && myMax == max )
- return;
-
- myMin = min;
- myMax = max;
-
- myPrecise = QString::null;
+ if ( myMin == min && myMax == max )
+ return;
+
+ myMin = min;
+ myMax = max;
+
+ myPrecise = QString::null;
- if ( colorMode() == Auto || labelMode() == Auto )
- updateScale();
+ if ( colorMode() == Auto || labelMode() == Auto )
+ updateScale();
}
/*!
- Sets the title string.
+ \brief Set color scale title.
+ \param str new title
*/
void QtxColorScale::setTitle( const QString& str )
{
- if ( myTitle == str )
- return;
-
- myTitle = str;
- updateScale();
+ if ( myTitle == str )
+ return;
+
+ myTitle = str;
+ updateScale();
}
/*!
- Sets the format of number presentation in labels for
- Auto label mode (sprintf specification).
+ \brief Set current format of the number presentation.
+ \sa format()
+ \param format new number presentation format
*/
void QtxColorScale::setFormat( const QString& format )
{
- if ( myFormat == format )
- return;
+ if ( myFormat == format )
+ return;
- myFormat = format;
- myPrecise = QString::null;
- if ( colorMode() == Auto )
- updateScale();
+ myFormat = format;
+ myPrecise = QString::null;
+ if ( colorMode() == Auto )
+ updateScale();
}
/*!
- Sets the number of intervals.
+ \brief Set number of color scale intervals.
+ \param num number of intervals
*/
void QtxColorScale::setIntervalsNumber( const int num )
{
- if ( myInterval == num || num < 1 )
- return;
-
- myInterval = num;
- myPrecise = QString::null;
-
- updateScale();
+ if ( myInterval == num || num < 1 )
+ return;
+
+ myInterval = num;
+ myPrecise = QString::null;
+
+ updateScale();
}
/*!
- Sets the user label for specified interval. If number
- of interval is negative then user label will be added
- as new at the end of list.
+ \brief Set user label for the specified color scale interval.
+
+ If number of interval is negative then user label will be added
+ as new to the end of list.
+
+ \param txt user label
+ \param idx interval index
*/
void QtxColorScale::setLabel( const QString& txt, const int idx )
{
- bool changed = false;
- uint i = idx < 0 ? myLabels.count() : idx;
- if ( i < myLabels.count() )
- {
- changed = *myLabels.at( i ) != txt;
- myLabels[i] = txt;
- }
- else
- {
- changed = true;
- while ( i >= myLabels.count() )
- myLabels.append( "" );
- myLabels[i] = txt;
- }
- if ( changed )
- updateScale();
+ bool changed = false;
+ int i = idx < 0 ? myLabels.count() : idx;
+ if ( i < myLabels.count() )
+ {
+ changed = myLabels[i] != txt;
+ myLabels[i] = txt;
+ }
+ else
+ {
+ changed = true;
+ while ( i >= myLabels.count() )
+ myLabels.append( "" );
+ myLabels[i] = txt;
+ }
+ if ( changed )
+ updateScale();
}
/*!
- Sets the user color for specified interval. If number
- of interval is negative then user color will be added
- as new at the end of list.
+ \brief Set user color for the specified color scale interval.
+
+ If number of interval is negative then user color will be added
+ as new to the end of list.
+
+ \param clr user color
+ \param idx interval index
*/
void QtxColorScale::setColor( const QColor& clr, const int idx )
{
- bool changed = false;
- uint i = idx < 0 ? myColors.count() : idx;
- if ( i < myColors.count() )
- {
- changed = *myColors.at( i ) != clr;
- myColors[i] = clr;
- }
- else
- {
- changed = true;
- while ( i >= myColors.count() )
- myColors.append( QColor() );
- myColors[i] = clr;
- }
- if ( changed )
- updateScale();
+ bool changed = false;
+ int i = idx < 0 ? myColors.count() : idx;
+ if ( i < myColors.count() )
+ {
+ changed = myColors[i] != clr;
+ myColors[i] = clr;
+ }
+ else
+ {
+ changed = true;
+ while ( i >= myColors.count() )
+ myColors.append( QColor() );
+ myColors[i] = clr;
+ }
+ if ( changed )
+ updateScale();
}
/*!
- Replace the all user label with specified list.
+ \brief Set user labels for all color scale intervals.
+ \param list new labels list
*/
void QtxColorScale::setLabels( const QStringList& list )
{
- if ( list.isEmpty() )
- return;
+ if ( list.isEmpty() )
+ return;
- myLabels = list;
- updateScale();
+ myLabels = list;
+ updateScale();
}
/*!
- Replace the all user colors with specified list.
+ \brief Set user colors for all color scale intervals.
+ \param list new colors list
*/
-void QtxColorScale::setColors( const QValueList<QColor>& list )
+void QtxColorScale::setColors( const QList<QColor>& list )
{
- if ( list.isEmpty() )
- return;
+ if ( list.isEmpty() )
+ return;
- myColors = list;
- updateScale();
+ myColors = list;
+ updateScale();
}
/*!
- Sets the color mode (Auto or User).
+ \brief Set color scale color mode.
+ \param mode new color mode (QtxColorScale::Mode)
*/
void QtxColorScale::setColorMode( const int mode )
{
- if ( myColorMode == mode )
- return;
-
- myColorMode = mode;
- updateScale();
+ if ( myColorMode == mode )
+ return;
+
+ myColorMode = mode;
+ updateScale();
}
/*!
- Sets the dump mode.
+ \brief Set color scale dump mode.
+ \param mode new dump mode (QtxColorScale::DumpMode)
*/
void QtxColorScale::setDumpMode( const int mode )
{
- myDumpMode = mode;
+ myDumpMode = mode;
}
/*!
- Sets the label mode (Auto or User).
+ \brief Set color scale label mode.
+ \param mode new label mode (QtxColorScale::Mode)
*/
void QtxColorScale::setLabelMode( const int mode )
{
- if ( myLabelMode != mode )
- {
- myLabelMode = mode;
- updateScale();
- }
+ if ( myLabelMode != mode )
+ {
+ myLabelMode = mode;
+ updateScale();
+ }
}
/*!
- Sets the label position.
+ \brief Set label position.
+ \param pos new label position (QtxColorScale::Position)
*/
void QtxColorScale::setLabelPosition( const int pos )
{
- if ( myLabelPos != pos && pos >= None && pos <= Center )
- {
- myLabelPos = pos;
- updateScale();
- }
+ if ( myLabelPos != pos && pos >= None && pos <= Center )
+ {
+ myLabelPos = pos;
+ updateScale();
+ }
}
/*!
- Sets the title position.
+ \brief Set title position.
+ \param pos new title position (QtxColorScale::Position)
*/
void QtxColorScale::setTitlePosition( const int pos )
{
- if ( myTitlePos != pos && pos >= None && pos <= Center )
- {
- myTitlePos = pos;
- updateScale();
- }
+ if ( myTitlePos != pos && pos >= None && pos <= Center )
+ {
+ myTitlePos = pos;
+ updateScale();
+ }
}
/*!
- Set the specified flags.
+ \brief Set color scale flags.
+ \param flags new flags
*/
void QtxColorScale::setFlags( const int flags )
{
- int prev = myFlags;
- myFlags |= flags;
- if ( prev != myFlags )
- updateScale();
+ int prev = myFlags;
+ myFlags |= flags;
+ if ( prev != myFlags )
+ updateScale();
}
/*!
- \return true if specified flags are setted.
+ \brief Test color scale flags.
+ \return \c true if specified flags are set
*/
bool QtxColorScale::testFlags( const int flags ) const
{
- return ( myFlags & flags ) == flags;
+ return ( myFlags & flags ) == flags;
}
/*!
- Clear (reset) the specified flags.
+ \brief Clear (reset) color scale flags.
+ \param flags color scale flags to be cleared
*/
void QtxColorScale::clearFlags( const int flags )
{
- int prev = myFlags;
- myFlags &= ~flags;
- if ( prev != myFlags )
- updateScale();
+ int prev = myFlags;
+ myFlags &= ~flags;
+ if ( prev != myFlags )
+ updateScale();
}
/*!
+ \brief Get widget's minumum size hint.
\return minimum size hint
*/
QSize QtxColorScale::minimumSizeHint() const
{
QSize sz = calculateSize( true, myFlags, titlePosition() != None, labelPosition() != None, true );
- return sz + QSize( frameWidth(), frameWidth() );
+ return sz + QSize( frameWidth(), frameWidth() );
}
/*!
+ \brief Get widget's default size hint.
\return size hint
*/
QSize QtxColorScale::sizeHint() const
{
QSize sz = calculateSize( false, myFlags, titlePosition() != None, labelPosition() != None, true );
- return sz + QSize( frameWidth(), frameWidth() );
+ return sz + QSize( frameWidth(), frameWidth() );
}
/*!
- Dump color scale into pixmap with current size.
+ \brief Calculate color scale size.
+ \param min if \c true, color scale size is calculated to be as smallest as possible
+ \param flags color scale flags
+ \param title color scale title
+ \param labels if \c true take into account labels
+ \param colors if \c true take into account colors
+ \return color scale size
*/
QSize QtxColorScale::calculateSize( const bool min, const int flags, const bool title,
- const bool labels, const bool colors ) const
+ const bool labels, const bool colors ) const
{
- int num = intervalsNumber();
-
- int spacer = 5;
- int textWidth = 0;
- int textHeight = fontMetrics().height();
- int colorWidth = 20;
-
- if ( labels && colors )
+ int num = intervalsNumber();
+
+ int spacer = 5;
+ int textWidth = 0;
+ int textHeight = fontMetrics().height();
+ int colorWidth = 20;
+
+ if ( labels && colors )
{
QtxColorScale* that = (QtxColorScale*)this;
QString fmt = that->myFormat;
- for ( int idx = 0; idx < num; idx++ )
- textWidth = QMAX( textWidth, fontMetrics().width( getLabel( idx ) ) );
-
+ for ( int idx = 0; idx < num; idx++ )
+ textWidth = qMax( textWidth, fontMetrics().width( getLabel( idx ) ) );
+
if ( !min )
that->myFormat = that->myFormat.replace( QRegExp( "g" ), "f" );
-
- for ( int index = 0; index < num; index++ )
- textWidth = QMAX( textWidth, fontMetrics().width( getLabel( index ) ) );
-
+
+ for ( int index = 0; index < num; index++ )
+ textWidth = qMax( textWidth, fontMetrics().width( getLabel( index ) ) );
+
that->myFormat = fmt;
}
+
+ int scaleWidth = 0;
+ int scaleHeight = 0;
+
+ int titleWidth = 0;
+ int titleHeight = 0;
+
+ if ( flags & AtBorder )
+ {
+ num++;
+ if ( min && title && !myTitle.isEmpty() )
+ titleHeight += 10;
+ }
+
+ if ( colors )
+ {
+ scaleWidth = colorWidth + textWidth + ( textWidth ? 3 : 2 ) * spacer;
+ if ( min )
+ scaleHeight = qMax( 2 * num, 3 * textHeight );
+ else
+ scaleHeight = (int)( 1.5 * ( num + 1 ) * textHeight );
+ }
- int scaleWidth = 0;
- int scaleHeight = 0;
-
- int titleWidth = 0;
- int titleHeight = 0;
-
- if ( flags & AtBorder )
- {
- num++;
- if ( min && title && !myTitle.isEmpty() )
- titleHeight += 10;
- }
-
- if ( colors )
- {
- scaleWidth = colorWidth + textWidth + ( textWidth ? 3 : 2 ) * spacer;
- if ( min )
- scaleHeight = QMAX( 2 * num, 3 * textHeight );
- else
- scaleHeight = (int)( 1.5 * ( num + 1 ) * textHeight );
- }
-
- if ( title )
- {
- QSimpleRichText* srt = simpleRichText( flags );
- if ( srt )
- {
- QPainter p( this );
- if ( scaleWidth )
- srt->setWidth( &p, scaleWidth );
-
- titleHeight = srt->height() + spacer;
- titleWidth = srt->widthUsed() + 10;
-
- delete srt;
- }
- }
-
- int W = QMAX( titleWidth, scaleWidth ) + width() - contentsRect().width();
- int H = scaleHeight + titleHeight + height() - contentsRect().height();
-
- return QSize( W, H );
+ if ( title )
+ {
+ QTextDocument* srt = textDocument( flags );
+ if ( srt )
+ {
+ QPainter p( (QtxColorScale*)this );
+ if ( scaleWidth )
+ srt->setTextWidth( scaleWidth );
+
+ titleHeight = (int)srt->size().height() + spacer;
+ titleWidth = (int)srt->size().width() + 10;
+
+ }
+ delete srt;
+ }
+
+ int W = qMax( titleWidth, scaleWidth ) + width() - contentsRect().width();
+ int H = scaleHeight + titleHeight + height() - contentsRect().height();
+
+ return QSize( W, H );
}
/*!
- Dump color scale into pixmap with current size.
+ \brief Dump color scale into pixmap with current size.
+ \return generated pixmap
*/
QPixmap QtxColorScale::dump() const
{
- QPixmap aPix;
+ QPixmap aPix;
- if ( dumpMode() != NoDump )
- {
- aPix = QPixmap( size() );
- if ( !aPix.isNull() )
- {
- bool scale = ( myDumpMode == ScaleDump || myDumpMode == FullDump );
- bool label = ( myDumpMode == ScaleDump || myDumpMode == FullDump ) &&
- labelPosition() != None;
- bool title = ( myDumpMode == TitleDump || myDumpMode == FullDump ) &&
- titlePosition() != None;
-
-#if QT_VER < 3
- QColor bgc = backgroundColor();
-#else
- QColor bgc = paletteBackgroundColor();
-#endif
- QPainter p;
- p.begin( &aPix );
- p.fillRect( 0, 0, aPix.width(), aPix.height(), bgc );
- drawScale( &p, bgc, false, 0, 0, aPix.width(), aPix.height(), title, label, scale );
- p.end();
- }
- }
-
- return aPix;
+ if ( dumpMode() != NoDump )
+ {
+ aPix = QPixmap( size() );
+ if ( !aPix.isNull() )
+ {
+ bool scale = ( myDumpMode == ScaleDump || myDumpMode == FullDump );
+ bool label = ( myDumpMode == ScaleDump || myDumpMode == FullDump ) &&
+ labelPosition() != None;
+ bool title = ( myDumpMode == TitleDump || myDumpMode == FullDump ) &&
+ titlePosition() != None;
+ QColor bgc = palette().color( backgroundRole() );
+ QPainter p;
+ p.begin( &aPix );
+ p.fillRect( 0, 0, aPix.width(), aPix.height(), bgc );
+ drawScale( &p, bgc, false, 0, 0, aPix.width(), aPix.height(), title, label, scale );
+ p.end();
+ }
+ }
+
+ return aPix;
}
/*!
- Dump color scale into pixmap with specified size.
+ \brief Dump color scale into pixmap with the specified size.
+ \param w pixmap width
+ \param h pixmap height
+ \return generated pixmap
*/
QPixmap QtxColorScale::dump( const int w, const int h ) const
{
-#if QT_VER < 3
- return dump( backgroundColor(), w, h );
-#else
- return dump( paletteBackgroundColor(), w, h );
-#endif
+ return dump( palette().color( backgroundRole() ), w, h );
}
/*!
- Dump color scale into pixmap with specified size and background color.
+ \brief Dump color scale into pixmap with the specified size and background color.
+ \param bg pixmap background color
+ \param w pixmap width
+ \param h pixmap height
+ \return generated pixmap
*/
QPixmap QtxColorScale::dump( const QColor& bg, const int w, const int h ) const
{
- QPixmap aPix;
- if ( dumpMode() != NoDump )
- {
- bool scale = ( myDumpMode == ScaleDump || myDumpMode == FullDump );
- bool label = ( myDumpMode == ScaleDump || myDumpMode == FullDump ) &&
- labelPosition() != None;
- bool title = ( myDumpMode == TitleDump || myDumpMode == FullDump ) &&
- titlePosition() != None;
-
- int W = w;
- int H = h;
- if ( W < 0 || H < 0 )
- {
- QSize sz = calculateSize( false, myFlags & ~WrapTitle, title, label, scale );
-
- if ( W < 0 )
- W = sz.width();
- if ( H < 0 )
- H = sz.height();
- }
-
- aPix = QPixmap( W, H );
- if ( !aPix.isNull() )
- {
- QPainter p;
- p.begin( &aPix );
- p.fillRect( 0, 0, aPix.width(), aPix.height(), bg );
- drawScale( &p, bg, false, 0, 0, aPix.width(), aPix.height(), title, label, scale );
- p.end();
- }
- }
-
- return aPix;
+ QPixmap aPix;
+ if ( dumpMode() != NoDump )
+ {
+ bool scale = ( myDumpMode == ScaleDump || myDumpMode == FullDump );
+ bool label = ( myDumpMode == ScaleDump || myDumpMode == FullDump ) &&
+ labelPosition() != None;
+ bool title = ( myDumpMode == TitleDump || myDumpMode == FullDump ) &&
+ titlePosition() != None;
+
+ int W = w;
+ int H = h;
+ if ( W < 0 || H < 0 )
+ {
+ QSize sz = calculateSize( false, myFlags & ~WrapTitle, title, label, scale );
+
+ if ( W < 0 )
+ W = sz.width();
+ if ( H < 0 )
+ H = sz.height();
+ }
+
+ aPix = QPixmap( W, H );
+ if ( !aPix.isNull() )
+ {
+ QPainter p;
+ p.begin( &aPix );
+ p.fillRect( 0, 0, aPix.width(), aPix.height(), bg );
+ drawScale( &p, bg, false, 0, 0, aPix.width(), aPix.height(), title, label, scale );
+ p.end();
+ }
+ }
+
+ return aPix;
}
/*!
- Show the color scale. [Reimplemented]
+ \brief Show color scale (reimplemented from QFrame).
*/
void QtxColorScale::show()
{
-#if QT_VER == 3
- if ( myDock )
- myDock->activate();
- else
-#endif
- QFrame::show();
+ QFrame::show();
}
/*!
- Hides the color scale. [Reimplemented]
+ \brief Hide color scale (reimplemented from QFrame).
*/
void QtxColorScale::hide()
{
-#if QT_VER == 3
- if ( myDock )
- myDock->deactivate();
- else
-#endif
- QFrame::hide();
+ QFrame::hide();
}
/*!
- Draw color scale contents. [Reimplemented]
+ \brief Draw color scale (reimplemented from QFrame).
+ \param p painter
*/
void QtxColorScale::drawContents( QPainter* p )
{
- if ( !isUpdatesEnabled() )
- return;
-
- QRect aDrawRect = contentsRect();
-
- drawScale( p, false/*testFlags( Transparent )*/, aDrawRect.x(),
- aDrawRect.y(), aDrawRect.width(), aDrawRect.height(),
- titlePosition() != None, labelPosition() != None, true );
+ if ( !updatesEnabled() )
+ return;
+
+ QRect aDrawRect = contentsRect();
+
+ drawScale( p, false/*testFlags( Transparent )*/, aDrawRect.x(),
+ aDrawRect.y(), aDrawRect.width(), aDrawRect.height(),
+ titlePosition() != None, labelPosition() != None, true );
}
/*!
- Draw color scale contents.
+ \brief Draw color scale contents.
+ \param p painter
+ \param transp if \c true color scale is drawn on transparent background
+ \param X color scale x coordinate
+ \param Y color scale y coordinate
+ \param W color scale width
+ \param H color scale height
+ \param drawTitle if \c true, draw title
+ \param drawLabel if \c true, draw labels
+ \param drawColors if \c true, draw colors
*/
void QtxColorScale::drawScale( QPainter* p, const bool transp, const int X, const int Y,
- const int W, const int H, const bool title,
- const bool label, const bool scale ) const
+ const int W, const int H, const bool drawTitle,
+ const bool drawLabel, const bool drawColors ) const
{
- QPixmap cache( W, H );
- QPainter cp( &cache );
-
-#if QT_VER < 3
- drawScale( &cp, backgroundColor(), transp, 0, 0, W, H, title, label, scale );
-#else
- drawScale( &cp, paletteBackgroundColor(), transp, 0, 0, W, H, title, label, scale );
-#endif
- cp.end();
-
- p->drawPixmap( X, Y, cache );
+ QPixmap cache( W, H );
+ QPainter cp( &cache );
+
+ drawScale( &cp, palette().color( backgroundRole() ), transp, 0, 0, W, H, drawTitle, drawLabel, drawColors );
+ cp.end();
+
+ p->drawPixmap( X, Y, cache );
}
/*!
- Draw color scale contents.
+ \brief Draw color scale contents.
+ \param p painter
+ \param bg background color
+ \param transp if \c true color scale is drawn on transparent background
+ \param X color scale x coordinate
+ \param Y color scale y coordinate
+ \param W color scale width
+ \param H color scale height
+ \param drawTitle if \c true, draw title
+ \param drawLabel if \c true, draw labels
+ \param drawColors if \c true, draw colors
*/
void QtxColorScale::drawScale( QPainter* p, const QColor& bg, const bool transp,
const int X, const int Y, const int W, const int H,
const bool drawTitle, const bool drawLabel, const bool drawColors ) const
{
- if ( !transp )
- p->fillRect( X, Y, W, H, bg );
-
- int num = intervalsNumber();
-
- int labPos = labelPosition();
-
- int spacer = 5;
- int textWidth = 0;
- int textHeight = p->fontMetrics().height();
-
- QString aTitle = title();
-
- int titleWidth = 0;
- int titleHeight = 0;
-
- if ( qGray( bg.rgb() ) < 128 )
- p->setPen( QColor( 255, 255, 255 ) );
- else
- p->setPen( QColor( 0, 0, 0 ) );
-
- // Draw title
- if ( drawTitle )
- {
- QSimpleRichText* srt = simpleRichText( myFlags );
- if ( srt )
- {
- srt->setWidth( p, W - 10 );
- titleHeight = srt->height() + spacer;
- titleWidth = srt->widthUsed();
- QColorGroup cg = colorGroup();
- cg.setColor( QColorGroup::Text, p->pen().color() );
- srt->draw( p, X + 5, Y, QRect( 0, 0, srt->width(), srt->height() ), cg );
-
- delete srt;
- }
- }
-
- bool reverse = testFlags( Reverse );
-
- QValueList<QColor> colors;
- QValueList<QString> labels;
- for ( int idx = 0; idx < num; idx++ )
- {
- if ( reverse )
- {
- colors.append( getColor( idx ) );
- labels.append( getLabel( idx ) );
- }
- else
- {
- colors.prepend( getColor( idx ) );
- labels.prepend( getLabel( idx ) );
- }
- }
-
- if ( testFlags( AtBorder ) )
- {
- if ( reverse )
- labels.append( getLabel( num ) );
- else
- labels.prepend( getLabel( num ) );
- if ( drawLabel )
- textWidth = QMAX( textWidth, p->fontMetrics().width( labels.last() ) );
- }
-
- if ( drawLabel )
- {
- const QFontMetrics& fm = p->fontMetrics();
- for ( QStringList::ConstIterator it = labels.begin(); it != labels.end(); ++it )
- textWidth = QMAX( textWidth, fm.width( *it) );
- }
-
- int lab = labels.count();
-
- double spc = ( H - ( ( QMIN( lab, 2 ) + QABS( lab - num - 1 ) ) * textHeight ) - titleHeight );
- double val = spc != 0 ? 1.0 * ( lab - QMIN( lab, 2 ) ) * textHeight / spc : 0;
- double iPart;
- double fPart = modf( val, &iPart );
- int filter = (int)iPart + ( fPart != 0 ? 1 : 0 );
- filter = QMAX( filter, 1 );
-
- double step = 1.0 * ( H - ( lab - num + QABS( lab - num - 1 ) ) * textHeight - titleHeight ) / num;
-
- int ascent = p->fontMetrics().ascent();
- int colorWidth = QMAX( 5, QMIN( 20, W - textWidth - 3 * spacer ) );
- if ( labPos == Center || !drawLabel )
- colorWidth = W - 2 * spacer;
-
- // Draw colors
- int x = X + spacer;
- switch ( labPos )
- {
- case Left:
- x += textWidth + ( textWidth ? 1 : 0 ) * spacer;
- break;
- }
-
- double offset = 1.0 * textHeight / 2 * ( lab - num + QABS( lab - num - 1 ) ) + titleHeight;
- QValueList<QColor>::Iterator cit = colors.begin();
+ if ( !transp )
+ p->fillRect( X, Y, W, H, bg );
+
+ int num = intervalsNumber();
+
+ int labPos = labelPosition();
+
+ int spacer = 5;
+ int textWidth = 0;
+ int textHeight = p->fontMetrics().height();
+
+ QString aTitle = title();
+
+ int titleWidth = 0;
+ int titleHeight = 0;
+
+ if ( qGray( bg.rgb() ) < 128 )
+ p->setPen( QColor( 255, 255, 255 ) );
+ else
+ p->setPen( QColor( 0, 0, 0 ) );
+
+ // Draw title
+ if ( drawTitle )
+ {
+ QTextDocument* srt = textDocument( myFlags );
+ if ( srt )
+ {
+ srt->setTextWidth( W - 10 );
+ titleHeight = (int)srt->size().height() + spacer;
+ titleWidth = (int)srt->size().width();
+ p->save();
+ p->translate( X + 5, Y );
+ srt->drawContents( p );
+ p->restore();
+ }
+ delete srt;
+ }
+
+ bool reverse = testFlags( Reverse );
+
+ QList<QColor> colors;
+ QList<QString> labels;
+ for ( int idx = 0; idx < num; idx++ )
+ {
+ if ( reverse )
+ {
+ colors.append( getColor( idx ) );
+ labels.append( getLabel( idx ) );
+ }
+ else
+ {
+ colors.prepend( getColor( idx ) );
+ labels.prepend( getLabel( idx ) );
+ }
+ }
+
+ if ( testFlags( AtBorder ) )
+ {
+ if ( reverse )
+ labels.append( getLabel( num ) );
+ else
+ labels.prepend( getLabel( num ) );
+ if ( drawLabel )
+ textWidth = qMax( textWidth, p->fontMetrics().width( labels.last() ) );
+ }
+
+ if ( drawLabel )
+ {
+ const QFontMetrics& fm = p->fontMetrics();
+ for ( QStringList::ConstIterator it = labels.begin(); it != labels.end(); ++it )
+ textWidth = qMax( textWidth, fm.width( *it) );
+ }
+
+ int lab = labels.count();
+
+ double spc = ( H - ( ( qMin( lab, 2 ) + qAbs( lab - num - 1 ) ) * textHeight ) - titleHeight );
+ double val = spc != 0 ? 1.0 * ( lab - qMin( lab, 2 ) ) * textHeight / spc : 0;
+ double iPart;
+ double fPart = modf( val, &iPart );
+ int filter = (int)iPart + ( fPart != 0 ? 1 : 0 );
+ filter = qMax( filter, 1 );
+
+ double step = 1.0 * ( H - ( lab - num + qAbs( lab - num - 1 ) ) * textHeight - titleHeight ) / num;
+
+ int ascent = p->fontMetrics().ascent();
+ int colorWidth = qMax( 5, qMin( 20, W - textWidth - 3 * spacer ) );
+ if ( labPos == Center || !drawLabel )
+ colorWidth = W - 2 * spacer;
+
+ // Draw colors
+ int x = X + spacer;
+ switch ( labPos )
+ {
+ case Left:
+ x += textWidth + ( textWidth ? 1 : 0 ) * spacer;
+ break;
+ }
+
+ double offset = 1.0 * textHeight / 2 * ( lab - num + qAbs( lab - num - 1 ) ) + titleHeight;
+ QList<QColor>::Iterator cit = colors.begin();
uint ci = 0;
- for ( ci = 0; cit != colors.end() && drawColors; ++cit, ci++ )
- {
- int y = (int)( Y + ci * step + offset );
- int h = (int)( Y + ( ci + 1 ) * step + offset ) - y;
- p->fillRect( x, y, colorWidth, h, *cit );
- }
-
- if ( drawColors )
- p->drawRect( int( x - 1 ), int( Y + offset - 1 ), int( colorWidth + 2 ), int( ci * step + 2 ) );
-
- // Draw labels
- offset = 1.0 * QABS( lab - num - 1 ) * ( step - textHeight ) / 2 +
- 1.0 * QABS( lab - num - 1 ) * textHeight / 2;
- offset += titleHeight;
- if ( drawLabel && !labels.isEmpty() )
- {
- int i1 = 0;
- int i2 = lab - 1;
- int last1( i1 ), last2( i2 );
- int x = X + spacer;
- switch ( labPos )
- {
- case Center:
- x += ( colorWidth - textWidth ) / 2;
- break;
- case Right:
- x += colorWidth + spacer;
- break;
- }
- while ( i2 - i1 >= filter || ( i2 == 0 && i1 == 0 ) )
- {
- int pos1 = i1;
- int pos2 = lab - 1 - i2;
- if ( filter && !( pos1 % filter ) )
- {
- p->drawText( x, (int)( Y + i1 * step + ascent + offset ), *labels.at( i1 ) );
- last1 = i1;
- }
- if ( filter && !( pos2 % filter ) )
- {
- p->drawText( x, (int)( Y + i2 * step + ascent + offset ), *labels.at( i2 ) );
- last2 = i2;
- }
- i1++;
- i2--;
- }
- int pos = i1;
- int i0 = -1;
- while ( pos <= i2 && i0 == -1 )
- {
- if ( filter && !( pos % filter ) &&
- QABS( pos - last1 ) >= filter && QABS( pos - last2 ) >= filter )
- i0 = pos;
- pos++;
- }
-
- if ( i0 != -1 )
- p->drawText( x, (int)( Y + i0 * step + ascent + offset ), *labels.at( i0 ) );
- }
+ for ( ci = 0; cit != colors.end() && drawColors; ++cit, ci++ )
+ {
+ int y = (int)( Y + ci * step + offset );
+ int h = (int)( Y + ( ci + 1 ) * step + offset ) - y;
+ p->fillRect( x, y, colorWidth, h, *cit );
+ }
+
+ if ( drawColors )
+ p->drawRect( int( x - 1 ), int( Y + offset - 1 ), int( colorWidth + 2 ), int( ci * step + 2 ) );
+
+ // Draw labels
+ offset = 1.0 * qAbs( lab - num - 1 ) * ( step - textHeight ) / 2 +
+ 1.0 * qAbs( lab - num - 1 ) * textHeight / 2;
+ offset += titleHeight;
+ if ( drawLabel && !labels.isEmpty() )
+ {
+ int i1 = 0;
+ int i2 = lab - 1;
+ int last1( i1 ), last2( i2 );
+ int x = X + spacer;
+ switch ( labPos )
+ {
+ case Center:
+ x += ( colorWidth - textWidth ) / 2;
+ break;
+ case Right:
+ x += colorWidth + spacer;
+ break;
+ }
+ while ( i2 - i1 >= filter || ( i2 == 0 && i1 == 0 ) )
+ {
+ int pos1 = i1;
+ int pos2 = lab - 1 - i2;
+ if ( filter && !( pos1 % filter ) )
+ {
+ p->drawText( x, (int)( Y + i1 * step + ascent + offset ), labels[i1] );
+ last1 = i1;
+ }
+ if ( filter && !( pos2 % filter ) )
+ {
+ p->drawText( x, (int)( Y + i2 * step + ascent + offset ), labels[i2] );
+ last2 = i2;
+ }
+ i1++;
+ i2--;
+ }
+ int pos = i1;
+ int i0 = -1;
+ while ( pos <= i2 && i0 == -1 )
+ {
+ if ( filter && !( pos % filter ) &&
+ qAbs( pos - last1 ) >= filter && qAbs( pos - last2 ) >= filter )
+ i0 = pos;
+ pos++;
+ }
+
+ if ( i0 != -1 )
+ p->drawText( x, (int)( Y + i0 * step + ascent + offset ), labels[i0] );
+ }
}
/*!
- \return the format for number labels.
+ \brief Generate number presentation format.
+ \return format for number labels
*/
QString QtxColorScale::getFormat() const
{
- QString aFormat = format();
-
- if ( !testFlags( PreciseFormat ) || testFlags( Integer ) )
- return aFormat;
-
- if ( !myPrecise.isEmpty() )
- return myPrecise;
-
- if ( aFormat.find( QRegExp( "^(%[0-9]*.?[0-9]*[fegFEG])$" ) ) != 0 )
- return aFormat;
-
- int pos1 = aFormat.find( '.' );
- int pos2 = aFormat.find( QRegExp( "[fegFEG]") );
-
- QString aLocFormat;
- int precision = 1;
- if ( pos1 > 0 )
- {
- aLocFormat = aFormat.mid( 0, pos1 + 1 );
- precision = aFormat.mid( pos1 + 1, pos2 - pos1 - 1 ).toInt();
- if ( precision < 1 )
- precision = 1;
- }
- else
- return aFormat;
+ QString aFormat = format();
+
+ if ( !testFlags( PreciseFormat ) || testFlags( Integer ) )
+ return aFormat;
+
+ if ( !myPrecise.isEmpty() )
+ return myPrecise;
+
+ if ( !aFormat.contains( QRegExp( "^(%[0-9]*.?[0-9]*[fegFEG])$" ) ) )
+ return aFormat;
+
+ int pos1 = aFormat.indexOf( '.' );
+ int pos2 = aFormat.indexOf( QRegExp( "[fegFEG]") );
- QtxColorScale* that = (QtxColorScale*)this;
-
- // calculate format, maximum precision limited
- // to 7 digits after the decimal point.
- while ( myPrecise.isEmpty() && precision < 7 )
- {
- QString aTmpFormat = aLocFormat;
- aTmpFormat += QString( "%1" ).arg( precision );
- aTmpFormat += aFormat.mid( pos2 );
-
- QMap<QString, int> map;
- bool isHasTwinz = false;
-
- for ( int idx = 0; idx < intervalsNumber() && !isHasTwinz; idx++ )
- {
- double val = getNumber( idx );
- QString tmpname = QString().sprintf( aTmpFormat, val );
- isHasTwinz = map.contains( tmpname );
- map.insert( tmpname, 1 );
- }
-
- if ( !isHasTwinz )
- that->myPrecise = aTmpFormat;
- precision++;
- }
-
- if ( !myPrecise.isEmpty() )
- aFormat = myPrecise;
-
- return aFormat;
+ QString aLocFormat;
+ int precision = 1;
+ if ( pos1 > 0 )
+ {
+ aLocFormat = aFormat.mid( 0, pos1 + 1 );
+ precision = aFormat.mid( pos1 + 1, pos2 - pos1 - 1 ).toInt();
+ if ( precision < 1 )
+ precision = 1;
+ }
+ else
+ return aFormat;
+
+ QtxColorScale* that = (QtxColorScale*)this;
+
+ // calculate format, maximum precision limited
+ // to 7 digits after the decimal point.
+ while ( myPrecise.isEmpty() && precision < 7 )
+ {
+ QString aTmpFormat = aLocFormat;
+ aTmpFormat += QString( "%1" ).arg( precision );
+ aTmpFormat += aFormat.mid( pos2 );
+
+ QMap<QString, int> map;
+ bool isHasTwinz = false;
+
+ for ( int idx = 0; idx < intervalsNumber() && !isHasTwinz; idx++ )
+ {
+ double val = getNumber( idx );
+ QString tmpname = QString().sprintf( aTmpFormat.toLatin1(), val );
+ isHasTwinz = map.contains( tmpname );
+ map.insert( tmpname, 1 );
+ }
+
+ if ( !isHasTwinz )
+ that->myPrecise = aTmpFormat;
+ precision++;
+ }
+
+ if ( !myPrecise.isEmpty() )
+ aFormat = myPrecise;
+
+ return aFormat;
}
/*!
- \return the number for specified interval.
+ \brief Get color scale value corresponding to the specified interval.
+ \param idx interval index
+ \return color scale value
*/
double QtxColorScale::getNumber( const int idx ) const
{
- double val = 0;
- if ( intervalsNumber() > 0 )
- val = minimum() + idx * ( QABS( maximum() - minimum() ) / intervalsNumber() );
- return val;
+ double val = 0;
+ if ( intervalsNumber() > 0 )
+ val = minimum() + idx * ( qAbs( maximum() - minimum() ) / intervalsNumber() );
+ return val;
}
/*!
- \return the label for specified interval according to the current label mode.
+ \brief Get color scale label text corresponding to the specified interval.
+ \param idx interval index
+ \return color scale label text
*/
QString QtxColorScale::getLabel( const int idx ) const
{
- QString res;
- if ( labelMode() == User )
- res = label( idx );
- else
- {
- double val = getNumber( idx );
- res = QString().sprintf( getFormat(), testFlags( Integer ) ? (int)val : val );
- }
- return res;
+ QString res;
+ if ( labelMode() == User )
+ res = label( idx );
+ else
+ {
+ double val = getNumber( idx );
+ res = QString().sprintf( getFormat().toLatin1(), testFlags( Integer ) ? (int)val : val );
+ }
+ return res;
}
/*!
- \return the color for specified interval according to the current color mode.
+ \brief Get color scale color corresponding to the specified interval.
+ \param idx interval index
+ \return color scale color
*/
QColor QtxColorScale::getColor( const int idx ) const
{
- QColor res;
- if ( colorMode() == User )
- res = color( idx );
- else
+ QColor res;
+ if ( colorMode() == User )
+ res = color( idx );
+ else
res = Qtx::scaleColor( idx, 0, intervalsNumber() - 1 );
- return res;
+ return res;
}
/*!
- Update color scale if it required.
+ \brief Update color scale.
*/
void QtxColorScale::updateScale()
{
update();
- updateGeometry();
+ updateGeometry();
}
/*!
- \return QSimpleRichText object for title. If title
- not defined (empty string) then return null pointer.
- Object should be deleted by caller function.
-*/
-QSimpleRichText* QtxColorScale::simpleRichText( const int flags ) const
-{
- QSimpleRichText* srt = 0;
-
- QString aTitle;
- switch ( titlePosition() )
- {
- case Left:
- aTitle = QString( "<p align=\"left\">%1</p>" );
- break;
- case Right:
- aTitle = QString( "<p align=\"right\">%1</p>" );
- break;
- case Center:
- aTitle = QString( "<p align=\"center\">%1</p>" );
- break;
- case None:
- default:
- break;
- }
-
- if ( !aTitle.isEmpty() && !title().isEmpty() )
- {
- if ( !myStyleSheet )
- {
- QtxColorScale* that = (QtxColorScale*)this;
- that->myStyleSheet = new QStyleSheet( that );
- }
-
- if ( myStyleSheet )
- {
- QStyleSheetItem* item = myStyleSheet->item( "p" );
- if ( item )
- item->setWhiteSpaceMode( flags & WrapTitle ? QStyleSheetItem::WhiteSpaceNormal :
- QStyleSheetItem::WhiteSpaceNoWrap );
- }
-
- aTitle = aTitle.arg( title() );
- srt = new QSimpleRichText( aTitle, font(), QString::null, myStyleSheet );
- }
-
- return srt;
-}
-
-#if QT_VER == 3
-
-/*!
- \class QtxColorScale::Dock
- Dockable window contains the color scale.
-*/
-
-/*!
- Constructor
-*/
-QtxColorScale::Dock::Dock( Place p, QWidget* parent, const char* name, WFlags f )
-: QDockWindow( p, parent, name, f ),
-myBlockShow( false ),
-myBlockResize( false )
-{
- myScale = new QtxColorScale( this );
-
- setWidget( myScale );
+ \brief Get text document (rich text) for the color scale title representation.
- setCloseMode( Always );
- setMovingEnabled( true );
- setResizeEnabled( true );
- setHorizontalStretchable( false );
+ If title is not defined (empty string) then null pointer is returned.
+ The calling function is responsible for the returning object deleting.
- setCaption( tr ( "Color scale" ) );
-}
-
-/*!
- Destructor.
+ \param flags color scale flags (not used)
+ \return text document or 0 if title is not set
*/
-QtxColorScale::Dock::~Dock()
+QTextDocument* QtxColorScale::textDocument( const int /*flags*/ ) const
{
-}
+ QTextDocument* doc = 0;
-/*!
- \return color scale widget.
-*/
-QtxColorScale* QtxColorScale::Dock::colorScale() const
-{
- return myScale;
-}
-
-/*!
- Set the dockable window is visible for main window.
-*/
-void QtxColorScale::Dock::activate()
-{
- if ( myBlockShow )
- return;
-
- QMainWindow* mw = 0;
- QWidget* p = parentWidget();
- while ( !mw && p )
- {
- if ( p->inherits( "QMainWindow" ) )
- mw = (QMainWindow*)p;
- p = p->parentWidget();
- }
- if ( mw )
- mw->setAppropriate( this, true );
-}
-
-/*!
- Set the dockable window is hidden for main window.
-*/
-void QtxColorScale::Dock::deactivate()
-{
- if ( myBlockShow )
- return;
-
- QMainWindow* mw = 0;
- QWidget* p = parentWidget();
- while ( !mw && p )
- {
- if ( p->inherits( "QMainWindow" ) )
- mw = (QMainWindow*)p;
- p = p->parentWidget();
- }
- if ( mw )
- mw->setAppropriate( this, false );
-}
-
-/*!
- \return true if the dockable window is visible.
-*/
-bool QtxColorScale::Dock::isActive() const
-{
- QMainWindow* mw = 0;
- QWidget* p = parentWidget();
- while ( !mw && p )
- {
- if ( p->inherits( "QMainWindow" ) )
- mw = (QMainWindow*)p;
- p = p->parentWidget();
- }
- if ( mw )
- return mw->appropriate( (QDockWindow*)this );
- else
- return false;
-}
-
-/*!
- Redefined show
-*/
-void QtxColorScale::Dock::show()
-{
- bool f = myBlockShow;
- myBlockShow = true;
- QDockWindow::show();
- myBlockShow = f;
-}
-
-/*!
- Redefined hide
-*/
-void QtxColorScale::Dock::hide()
-{
- bool f = myBlockShow;
- myBlockShow = false;
- QDockWindow::hide();
- myBlockShow = f;
-}
-
-/*!
- Make extent width as maximum value of widget width.
-*/
-void QtxColorScale::Dock::resize( int w, int h )
-{
- QDockWindow::resize( w, h );
-
- if ( myBlockResize )
- return;
-
- if ( orientation() == Qt::Vertical )
- setFixedExtentWidth( QMAX( fixedExtent().width(), w ) );
- else if ( orientation() == Qt::Horizontal )
- setFixedExtentHeight( QMAX( fixedExtent().height(), h ) );
-}
+ QString aTitle;
+ switch ( titlePosition() )
+ {
+ case Left:
+ aTitle = QString( "<p align=\"left\">%1</p>" );
+ break;
+ case Right:
+ aTitle = QString( "<p align=\"right\">%1</p>" );
+ break;
+ case Center:
+ aTitle = QString( "<p align=\"center\">%1</p>" );
+ break;
+ case None:
+ default:
+ break;
+ }
+
+ if ( !aTitle.isEmpty() && !title().isEmpty() )
+ {
+ /*
+ if ( !myStyleSheet )
+ {
+ QtxColorScale* that = (QtxColorScale*)this;
+ that->myStyleSheet = new QStyleSheet( that );
+ }
+
+ if ( myStyleSheet )
+ {
+ QStyleSheetItem* item = myStyleSheet->item( "p" );
+ if ( item )
+ item->setWhiteSpaceMode( flags & WrapTitle ? QStyleSheetItem::WhiteSpaceNormal :
+ QStyleSheetItem::WhiteSpaceNoWrap );
+ }
+ */
+ aTitle = aTitle.arg( title() );
+ doc = new QTextDocument( aTitle );
+ }
-/*!
- Set orientation
- \param o - new orientation
-*/
-void QtxColorScale::Dock::setOrientation( Orientation o )
-{
- bool b = myBlockResize;
- myBlockResize = true;
- QDockWindow::setOrientation( o );
- myBlockResize = b;
+ return doc;
}
-
-#endif
#include "Qtx.h"
-#include <qframe.h>
-#include <qvaluelist.h>
+#include <QFrame>
+#include <QList>
-#if QT_VER == 3
-#include <qdockwindow.h>
-#endif
-
-class QStyleSheet;
-class QSimpleRichText;
+class QTextDocument;
#ifdef WIN32
#pragma warning( disable:4251 )
#endif
-/*!
- \class QtxColorScale
- Color Scale widget.
-*/
class QTX_EXPORT QtxColorScale : public QFrame
{
- Q_OBJECT
+ Q_OBJECT
public:
- typedef enum { Auto, User } Mode;
- typedef enum { None, Left, Right, Center } Position;
- typedef enum { NoDump, TitleDump, ScaleDump, FullDump } DumpMode;
- typedef enum { AtBorder = 0x001, Reverse = 0x002, Integer = 0x004,
- WrapTitle = 0x008, PreciseFormat = 0x010, Transparent = 0x020 } Flags;
-
-#if QT_VER == 3
- class Dock : public QDockWindow
- {
- public:
- Dock( Place = InDock, QWidget* = 0, const char* = 0, WFlags = 0 );
- virtual ~Dock();
-
- QtxColorScale* colorScale() const;
-
- void activate();
- void deactivate();
-
- bool isActive() const;
-
- virtual void show();
- virtual void hide();
-
- virtual void resize( int, int );
- virtual void setOrientation( Orientation );
-
- private:
- QtxColorScale* myScale;
- bool myBlockShow;
- bool myBlockResize;
- };
-
-private:
- QtxColorScale( Dock*, const char* = 0, WFlags = 0 );
-#endif
+ //! Color scale color/label mode.
+ typedef enum {
+ Auto, //!< auto
+ User //!< user defined
+ } Mode;
+ //! Color scale title, label position.
+ typedef enum {
+ None, //!< do not draw
+ Left, //!< draw at the left
+ Right, //!< draw at the right
+ Center //!< draw at the center
+ } Position;
+ //! Dump mode.
+ typedef enum {
+ NoDump, //!< do not dump
+ TitleDump, //!< dump title
+ ScaleDump, //!< dump scale
+ FullDump //!< dump all
+ } DumpMode;
+ //! Color scale flags (bitwise).
+ typedef enum {
+ AtBorder = 0x001,
+ Reverse = 0x002,
+ Integer = 0x004,
+ WrapTitle = 0x008,
+ PreciseFormat = 0x010,
+ Transparent = 0x020
+ } Flags;
public:
- QtxColorScale( QWidget* = 0, const char* = 0, WFlags = 0 );
- QtxColorScale( const int, QWidget* = 0, const char* = 0, WFlags = 0 );
- virtual ~QtxColorScale();
-
- double minimum() const;
- double maximum() const;
- void range( double&, double& ) const;
- int dumpMode() const;
- int labelMode() const;
- int colorMode() const;
- int intervalsNumber() const;
-
- QString title() const;
- QString format() const;
- QString label( const int ) const;
- QColor color( const int ) const;
- void labels( QStringList& ) const;
- void colors( QValueList<QColor>& ) const;
-
- int labelPosition() const;
- int titlePosition() const;
-
- void setMinimum( const double );
- void setMaximum( const double );
- void setRange( const double, const double );
- void setDumpMode( const int );
- void setColorMode( const int );
- void setLabelMode( const int );
- void setIntervalsNumber( const int );
-
- void setTitle( const QString& );
- void setFormat( const QString& );
- void setLabel( const QString&, const int = -1 );
- void setColor( const QColor&, const int = -1 );
- void setLabels( const QStringList& );
- void setColors( const QValueList<QColor>& );
-
- void setLabelPosition( const int );
- void setTitlePosition( const int );
-
- void setFlags( const int );
- bool testFlags( const int ) const;
- void clearFlags( const int );
-
- QPixmap dump() const;
- QPixmap dump( const int = -1, const int = -1 ) const;
- QPixmap dump( const QColor&, const int = -1, const int = -1 ) const;
-
- virtual QSize minimumSizeHint() const;
- virtual QSize sizeHint() const;
-
- virtual void show();
- virtual void hide();
+ QtxColorScale( QWidget* = 0, Qt::WindowFlags = 0 );
+ QtxColorScale( const int, QWidget* = 0, Qt::WindowFlags = 0 );
+ virtual ~QtxColorScale();
+
+ double minimum() const;
+ double maximum() const;
+ void range( double&, double& ) const;
+ int dumpMode() const;
+ int labelMode() const;
+ int colorMode() const;
+ int intervalsNumber() const;
+
+ QString title() const;
+ QString format() const;
+ QString label( const int ) const;
+ QColor color( const int ) const;
+ void labels( QStringList& ) const;
+ void colors( QList<QColor>& ) const;
+
+ int labelPosition() const;
+ int titlePosition() const;
+
+ void setMinimum( const double );
+ void setMaximum( const double );
+ void setRange( const double, const double );
+ void setDumpMode( const int );
+ void setColorMode( const int );
+ void setLabelMode( const int );
+ void setIntervalsNumber( const int );
+
+ void setTitle( const QString& );
+ void setFormat( const QString& );
+ void setLabel( const QString&, const int = -1 );
+ void setColor( const QColor&, const int = -1 );
+ void setLabels( const QStringList& );
+ void setColors( const QList<QColor>& );
+
+ void setLabelPosition( const int );
+ void setTitlePosition( const int );
+
+ void setFlags( const int );
+ bool testFlags( const int ) const;
+ void clearFlags( const int );
+
+ QPixmap dump() const;
+ QPixmap dump( const int = -1, const int = -1 ) const;
+ QPixmap dump( const QColor&, const int = -1, const int = -1 ) const;
+
+ virtual QSize minimumSizeHint() const;
+ virtual QSize sizeHint() const;
+
+ virtual void show();
+ virtual void hide();
protected:
- virtual void drawContents( QPainter* );
+ virtual void drawContents( QPainter* );
private:
- void updateScale();
- QString getFormat() const;
- QString getLabel( const int ) const;
- QColor getColor( const int ) const;
- double getNumber( const int ) const;
- QSimpleRichText* simpleRichText( const int ) const;
- void drawScale( QPainter*, const bool, const int, const int,
- const int, const int, const bool, const bool, const bool ) const;
- void drawScale( QPainter*, const QColor&, const bool,
- const int, const int, const int, const int,
- const bool, const bool, const bool ) const;
- QSize calculateSize( const bool, const int,
- const bool, const bool, const bool ) const;
-
-#if QT_VER == 3
- friend class QtxColorScale::Dock;
-#endif
+ void updateScale();
+ QString getFormat() const;
+ QString getLabel( const int ) const;
+ QColor getColor( const int ) const;
+ double getNumber( const int ) const;
+ QTextDocument* textDocument( const int ) const;
+ void drawScale( QPainter*, const bool, const int, const int,
+ const int, const int, const bool, const bool, const bool ) const;
+ void drawScale( QPainter*, const QColor&, const bool,
+ const int, const int, const int, const int,
+ const bool, const bool, const bool ) const;
+ QSize calculateSize( const bool, const int,
+ const bool, const bool, const bool ) const;
private:
- double myMin;
- double myMax;
- QString myTitle;
- QString myFormat;
- QString myPrecise;
- int myInterval;
- int myDumpMode;
- int myColorMode;
- int myLabelMode;
-
- QValueList<QColor> myColors;
- QValueList<QString> myLabels;
-
- Dock* myDock;
- int myFlags;
- int myLabelPos;
- int myTitlePos;
- QStyleSheet* myStyleSheet;
+ double myMin; //!< lower limit
+ double myMax; //!< upper limit
+ QString myTitle; //!< title
+ QString myFormat; //!< number presentation format
+ QString myPrecise; //!< double values precision format
+ int myInterval; //!< number of color scale intervals
+ int myDumpMode; //!< dump mode (QtxColorScale::DumpMode)
+ int myColorMode; //!< color mode (QtxColorScale::Mode)
+ int myLabelMode; //!< label mode (QtxColorScale::Mode)
+
+ QList<QColor> myColors; //!< list of colors
+ QList<QString> myLabels; //!< list of labels
+
+ int myFlags; //!< color scale flags (QtxColorScale::Flags)
+ int myLabelPos; //!< label position (QtxColorScale::Position)
+ int myTitlePos; //!< title position (QtxColorScale::Position)
};
#ifdef WIN32
#pragma warning( default:4251 )
#endif
-#endif
+#endif // QTXCOLORSCALE_H
#include "QtxComboBox.h"
-#include <qpixmap.h>
-#include <qlineedit.h>
-#include <qvaluelist.h>
+#include <QLineEdit>
/*!
- Constructor
+ \class QtxComboBox
+ \brief Enhanced version of Qt combo box class.
+
+ In addition to the QComboBox class, QtxComboBox supports
+ adding/removing the items with the associated unique identifiers.
+ It also provides a way to set "cleared" state to the combo box -
+ when no item is selected.
*/
-QtxComboBox::QtxComboBox( QWidget* parent, const char* name )
-: QComboBox( parent, name ),
-myCleared( false )
-{
- connect( this, SIGNAL( activated( int ) ), this, SLOT( onActivated( int ) ) );
- connect( this, SIGNAL( activated( const QString& ) ), this, SLOT( onActivated( const QString& ) ) );
-}
/*!
- Constructor
+ \brief Constructor.
+ \param parent parent widget
*/
-QtxComboBox::QtxComboBox( bool rw, QWidget* parent, const char* name )
-: QComboBox( rw, parent, name ),
-myCleared( false )
+QtxComboBox::QtxComboBox( QWidget* parent )
+: QComboBox( parent ),
+ myCleared( false )
{
- connect( this, SIGNAL( activated( int ) ), this, SLOT( onActivated( int ) ) );
- connect( this, SIGNAL( activated( const QString& ) ), this, SLOT( onActivated( const QString& ) ) );
+ connect( this, SIGNAL( activated( int ) ), this, SLOT( onActivated( int ) ) );
+ connect( this, SIGNAL( activated( const QString& ) ), this, SLOT( onActivated( const QString& ) ) );
}
/*!
- Destructor
+ \brief Destructor.
+
+ Does nothing currently.
*/
QtxComboBox::~QtxComboBox()
{
}
/*!
- \return true if combobox is cleared
+ \brief Check if the combo box is in the "cleared" state.
+ \return \c true if combobox is in the "cleared" state
*/
bool QtxComboBox::isCleared() const
{
- return myCleared;
+ return myCleared;
}
/*!
- Sets cleared status
- \param isClear - new status
+ \brief Set "cleared" state.
+ \param isClear new "cleared" state
*/
void QtxComboBox::setCleared( const bool isClear )
{
- if ( myCleared == isClear )
- return;
+ if ( myCleared == isClear )
+ return;
- myCleared = isClear;
+ myCleared = isClear;
- if ( editable() )
- {
- if ( myCleared )
- lineEdit()->setText( "" );
- else
- lineEdit()->setText( text( currentItem() ) );
- }
+ if ( isEditable() )
+ {
+ if ( myCleared )
+ lineEdit()->setText( "" );
+ else
+ lineEdit()->setText( itemText( currentIndex() ) );
+ }
- update();
+ update();
}
/*!
- Sets currently selected item
- \param idx - index of item
+ \brief Set current item.
+
+ Does nothing if the item index is out of range.
+
+ \param idx item index
*/
-void QtxComboBox::setCurrentItem( int idx )
+void QtxComboBox::setCurrentIndex( int idx )
{
- if ( idx < 0 || idx >= count() )
- return;
+ if ( idx < 0 || idx >= count() )
+ return;
- myCleared = false;
- QComboBox::setCurrentItem( idx );
+ myCleared = false;
+ QComboBox::setCurrentIndex( idx );
}
/*!
- Sets current text
- \param txt - new current text
+ \brief Get current item ID.
+ \return item id
*/
-void QtxComboBox::setCurrentText( const QString& txt )
+int QtxComboBox::currentId() const
{
- myCleared = false;
-#if QT_VER < 3
- int i = -1;
- for ( int j = 0; j < count() && i == -1; j++ )
- if ( text( j ) == txt )
- i = j;
- if ( i >= 0 && i < count() )
- setCurrentItem( i );
- else if ( editable() )
- lineEdit()->setText( txt );
- else
- changeItem( txt, currentItem() );
-#else
- QComboBox::setCurrentText( txt );
-#endif
+ return id( currentIndex() );
}
/*!
- \return current selected id
+ \brief Set current item by ID.
+ \param num item ID
*/
-int QtxComboBox::currentId() const
+void QtxComboBox::setCurrentId( int num )
{
- return id( currentItem() );
+ setCurrentIndex( index( num ) );
}
/*!
- Sets current selected id
+ \brief Set the identifier to specified item.
+ \param index - index of the item
+ \param id - identifier of the item
*/
-void QtxComboBox::setCurrentId( int num )
+void QtxComboBox::setId( const int index, const int id )
{
- setCurrentItem( index( num ) );
+ setItemData( index, QVariant( id ), (Qt::ItemDataRole)IdRole );
}
/*!
- Custom paint event handler
+ \brief Customize paint event.
+ \param e paint event
*/
void QtxComboBox::paintEvent( QPaintEvent* e )
{
- if ( !count() || !myCleared || editable() )
- QComboBox::paintEvent( e );
- else
- paintClear( e );
+ if ( !count() || !myCleared || isEditable() )
+ QComboBox::paintEvent( e );
+ else
+ paintClear( e );
}
/*!
- SLOT: called if some item is activated
- \param idx - index of activated item
+ \brief Called when any item is activated by the user.
+ \param idx activated item index
*/
void QtxComboBox::onActivated( int idx )
{
- resetClear();
-
- if ( myIndexId.contains( idx ) )
- emit activatedId( myIndexId[idx] );
+ resetClear();
+
+ emit activatedId( id( idx ) );
}
/*!
- SLOT: called if some item is activated
-*/void QtxComboBox::onActivated( const QString& )
+ \brief Called when any item is activated by the user.
+ \param txt activated item text (not used)
+*/
+void QtxComboBox::onActivated( const QString& /*txt*/ )
{
- resetClear();
+ resetClear();
}
/*!
- Strips "cleared" state and updates
+ \brief Reset "cleared" state and update the combo box.
*/
void QtxComboBox::resetClear()
{
- if ( !myCleared )
- return;
-
- myCleared = false;
- update();
+ if ( !myCleared )
+ return;
+
+ myCleared = false;
+ update();
}
/*!
- Draws combobox when it is cleared or isn't editable
+ \brief Draw combobox in the "cleared" state.
+ \param e paint event
*/
void QtxComboBox::paintClear( QPaintEvent* e )
{
- int curIndex = currentItem();
- QString curText = text( curIndex );
+ int curIndex = currentIndex();
+ QString curText = itemText( curIndex );
+ QIcon curIcon = itemIcon( curIndex );
- QPixmap curPix;
- if ( pixmap( curIndex ) )
- curPix = *pixmap( curIndex );
+ bool upd = updatesEnabled();
+ setUpdatesEnabled( false );
- bool upd = isUpdatesEnabled();
- setUpdatesEnabled( false );
-
- changeItem( "", curIndex );
- QComboBox::paintEvent( e );
+ setItemIcon( curIndex, QIcon() );
+ setItemText( curIndex, QString::null );
+
+ QComboBox::paintEvent( e );
- if ( curPix.isNull() )
- changeItem( curText, curIndex );
- else
- changeItem( curPix, curText, curIndex );
+ setItemText( curIndex, curText );
+ setItemIcon( curIndex, curIcon );
- setUpdatesEnabled( upd );
+ setUpdatesEnabled( upd );
}
/*!
- \return id by index
+ \brief Get item ID by the index.
+ \param idx item index
+ \return item ID or -1 if index is invalid.
*/
int QtxComboBox::id( const int idx ) const
{
- int id = -1;
- if ( myIndexId.contains( idx ) )
- id = myIndexId[idx];
- return id;
+ int id = -1;
+ QVariant v = itemData( idx, (Qt::ItemDataRole)IdRole );
+ if ( v.canConvert( QVariant::Int ) )
+ id = v.toInt();
+ return id;
}
/*!
- \return index by id
+ \brief Get item index by the ID.
+ \param id item ID
+ \return item index or -1 if ID is invalid.
*/
-int QtxComboBox::index( const int id ) const
+int QtxComboBox::index( const int ident ) const
{
- int idx = -1;
- for ( IndexIdMap::ConstIterator it = myIndexId.begin();
- it != myIndexId.end() && idx == -1; ++it )
- if ( it.data() == id )
- idx = it.key();
- return idx;
+ int idx = -1;
+ for ( int i = 0; i < (int)count() && idx == -1; i++ )
+ {
+ if ( id( i ) == ident )
+ idx = i;
+ }
+ return idx;
}
+
+/*!
+ \fn void QtxComboBox::activatedId( int id )
+ \brief Emitted when the item with identificator \a id is activated.
+ \param id item ID
+*/
+
+/*!
+ \fn void QtxComboBox::highlightedId( int id )
+ \brief Emitted when the item with identificator \a id is highlighted.
+ \param id item ID
+*/
#include "Qtx.h"
-#include <qmap.h>
-#include <qcombobox.h>
+#include <QMap>
+#include <QComboBox>
#ifdef WIN32
#pragma warning( disable:4251 )
class QTX_EXPORT QtxComboBox : public QComboBox
{
- Q_OBJECT
-
- typedef QMap<int, int> IndexIdMap;
+ Q_OBJECT
public:
- QtxComboBox( QWidget* = 0, const char* = 0 );
- QtxComboBox( bool, QWidget* = 0, const char* = 0 );
- virtual ~QtxComboBox();
+ QtxComboBox( QWidget* = 0 );
+ virtual ~QtxComboBox();
+
+ bool isCleared() const;
+ void setCleared( const bool );
- bool isCleared() const;
- void setCleared( const bool );
+ virtual void setCurrentIndex( int );
- virtual void setCurrentItem( int );
- virtual void setCurrentText( const QString& );
+ int currentId() const;
+ void setCurrentId( int );
- int currentId() const;
- void setCurrentId( int );
+ int id( const int ) const;
+ int index( const int ) const;
+
+ void setId( const int, const int );
signals:
- void activatedId( int );
- void highlightedId( int );
+ void activatedId( int );
+ void highlightedId( int );
private slots:
- void onActivated( int );
- void onActivated( const QString& );
+ void onActivated( int );
+ void onActivated( const QString& );
protected:
- virtual void paintEvent( QPaintEvent* );
+ virtual void paintEvent( QPaintEvent* );
private:
- int id( const int ) const;
- int index( const int ) const;
+ void resetClear();
+ void paintClear( QPaintEvent* );
- void resetClear();
- void paintClear( QPaintEvent* );
+private:
+ enum { IdRole = Qt::UserRole + 10 };
private:
- bool myCleared;
- IndexIdMap myIndexId;
+ bool myCleared; //!< "cleared" state
};
#ifdef WIN32
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-// File: QtxDblSpinBox.cxx
-// Author: Sergey TELKOV
-
-#include "QtxDblSpinBox.h"
-
-#include <qlineedit.h>
-#include <qvalidator.h>
-#include <qapplication.h>
-
-#include <float.h>
-
-/*!
- \class QtxDblSpinBox::Validator [internal]
- Validator for QtxDblSpinBox (getted from Trolltech Qt - SpinBoxValidator)
-*/
-class QtxDblSpinBox::Validator : public QDoubleValidator
-{
-public:
- Validator( QtxDblSpinBox* sb, const char* name )
- : QDoubleValidator( sb, name ), spinBox( sb ) {}
-
- virtual State validate( QString& str, int& pos ) const;
-
-private:
- QtxDblSpinBox* spinBox;
-};
-
-
-/*!
- Checks string and \return QValidator::State
-*/
-QValidator::State QtxDblSpinBox::Validator::validate( QString& str, int& pos ) const
-{
- QString pref = spinBox->prefix();
- QString suff = spinBox->suffix();
- uint overhead = pref.length() + suff.length();
- State state = Invalid;
-
- if ( overhead == 0 )
- state = QDoubleValidator::validate( str, pos );
- else
- {
- if ( str.length() >= overhead && str.startsWith( pref ) &&
- str.right( suff.length() ) == suff )
- {
- QString core = str.mid( pref.length(), str.length() - overhead );
- int corePos = pos - pref.length();
- state = QDoubleValidator::validate( core, corePos );
- pos = corePos + pref.length();
- str.replace( pref.length(), str.length() - overhead, core );
- }
- else
- {
- state = QDoubleValidator::validate( str, pos );
- if ( state == Invalid )
- {
- QString special = spinBox->specialValueText().stripWhiteSpace();
- QString candidate = str.stripWhiteSpace();
- if ( special.startsWith( candidate ) )
- {
- if ( candidate.length() == special.length() )
- state = Acceptable;
- else
- state = Intermediate;
- }
- }
- }
- }
- return state;
-}
-
-/*!
- Constructor
-*/
-QtxDblSpinBox::QtxDblSpinBox( QWidget* parent, const char* name )
-: QSpinBox( parent, name ),
-myCleared( false ),
-myBlocked( false ),
-myPrecision( 0 )
-{
- myMin = -DBL_MAX;
- myMax = DBL_MAX;
- myStep = QRangeControl::lineStep();
- myValue = 0;
- setValidator( new Validator( this, "double_spinbox_validator" ) );
- rangeChange();
- updateDisplay();
-
- connect( editor(), SIGNAL( textChanged( const QString& ) ), this, SLOT( onTextChanged( const QString& ) ) );
-}
-
-/*!
- Constructor
-*/
-QtxDblSpinBox::QtxDblSpinBox( double min, double max, double step, QWidget* parent, const char* name )
-: QSpinBox( parent, name ),
-myMin( min ),
-myMax( max ),
-myStep( step ),
-myCleared( false ),
-myBlocked( false ),
-myPrecision( 0 )
-{
- myValue = myMin;
- setValidator( new Validator( this, "double_spinbox_validator" ) );
- rangeChange();
- updateDisplay();
-
- connect( editor(), SIGNAL( textChanged( const QString& ) ), this, SLOT( onTextChanged( const QString& ) ) );
-}
-
-/*!
- Destructor
-*/
-QtxDblSpinBox::~QtxDblSpinBox()
-{
-}
-
-/*!
- \return min value of spin box
-*/
-double QtxDblSpinBox::minValue() const
-{
- return myMin;
-}
-
-/*!
- \return max value of spin box
-*/
-double QtxDblSpinBox::maxValue() const
-{
- return myMax;
-}
-
-/*!
- Changes min value of spin box
- \param min - new min value
-*/
-void QtxDblSpinBox::setMinValue( int min )
-{
- setMinValue( (double)min );
-}
-
-/*!
- Changes min value of spin box
- \param min - new min value
-*/
-void QtxDblSpinBox::setMinValue( double min )
-{
- if ( myMin != min )
- {
- myMin = min;
- rangeChange();
- }
-}
-
-/*!
- Changes max value of spin box
- \param max - new max value
-*/
-void QtxDblSpinBox::setMaxValue( int max )
-{
- setMaxValue( (double)max );
-}
-
-/*!
- Changes max value of spin box
- \param max - new max value
-*/
-void QtxDblSpinBox::setMaxValue( double max )
-{
- if ( myMax != max )
- {
- myMax = max;
- rangeChange();
- }
-}
-
-/*!
- Changes min and max value of spin box
- \param min - new min value
- \param max - new max value
-*/
-void QtxDblSpinBox::setRange( int min, int max )
-{
- setRange( (double)min, (double)max );
-}
-
-/*!
- Changes min and max value of spin box
- \param min - new min value
- \param max - new max value
-*/
-void QtxDblSpinBox::setRange( double min, double max )
-{
- if ( myMin != min || myMax != max )
- {
- myMin = min;
- myMax = max;
- rangeChange();
- }
-}
-
-/*!
- \return step of spin box
-*/
-double QtxDblSpinBox::lineStep() const
-{
- return myStep;
-}
-
-/*!
- Changes step of spin box
- \param step - new step
-*/
-void QtxDblSpinBox::setLineStep( int step )
-{
- setLineStep( (double)step );
-}
-
-/*!
- Changes step of spin box
- \param step - new step
-*/
-void QtxDblSpinBox::setLineStep( double step )
-{
- myStep = step;
-}
-
-/*!
- \return value of spin box
-*/
-double QtxDblSpinBox::value() const
-{
- QSpinBox::value();
-
- return myValue;
-}
-
-/*!
- Changes value of spin box
- \param val - new value of spin box
-*/
-void QtxDblSpinBox::setValue( int val )
-{
- setValue( (double)val );
-}
-
-/*!
- Changes value of spin box
- \param val - new value of spin box
-*/
-void QtxDblSpinBox::setValue( double val )
-{
- myCleared = false;
- double prevVal = myValue;
- myValue = bound( val );
- if ( prevVal != myValue )
- valueChange();
-}
-
-/*!
- Adds step to value
-*/
-void QtxDblSpinBox::stepUp()
-{
- interpretText();
- if ( wrapping() && myValue + myStep > myMax )
- setValue( myMin );
- else
- setValue( myValue + myStep );
-}
-
-/*!
- Subtracks step from value
-*/
-void QtxDblSpinBox::stepDown()
-{
- interpretText();
- if ( wrapping() && myValue - myStep < myMin )
- setValue( myMax );
- else
- setValue( myValue - myStep );
-}
-
-/*!
- \return number of digit after comma
-*/
-int QtxDblSpinBox::precision() const
-{
- return myPrecision;
-}
-
-/*!
- Changes number of digit after comma
- \param prec - new digit number
-*/
-void QtxDblSpinBox::setPrecision( const int prec )
-{
- int newPrec = QMAX( prec, 0 );
- int oldPrec = QMAX( myPrecision, 0 );
- myPrecision = prec;
- if ( newPrec != oldPrec )
- updateDisplay();
-}
-
-/*!
- \return true if spin box is cleared
-*/
-bool QtxDblSpinBox::isCleared() const
-{
- return myCleared;
-}
-
-/*!
- Changes cleared status of spin box
- \param on - new status
-*/
-void QtxDblSpinBox::setCleared( const bool on )
-{
- if ( myCleared == on )
- return;
-
- myCleared = on;
- updateDisplay();
-}
-
-/*!
- Selects all content of spin box editor
-*/
-void QtxDblSpinBox::selectAll()
-{
-#if QT_VER >= 3
- QSpinBox::selectAll();
-#else
- editor()->selectAll();
-#endif
-}
-
-/*!
- Custom event filter, updates text of spin box editor
-*/
-bool QtxDblSpinBox::eventFilter( QObject* o, QEvent* e )
-{
- if ( !myCleared || o != editor() || !editor()->text().stripWhiteSpace().isEmpty() )
- {
- bool state = QSpinBox::eventFilter( o, e );
- if ( e->type() == QEvent::FocusOut && o == editor() )
- updateDisplay();
- return state;
- }
-
- if ( e->type() == QEvent::FocusOut || e->type() == QEvent::Leave || e->type() == QEvent::Hide )
- return false;
-
- if ( e->type() == QEvent::KeyPress &&
- ( ((QKeyEvent*)e)->key() == Key_Tab || ((QKeyEvent*)e)->key() == Key_BackTab ) )
- {
- QApplication::sendEvent( this, e );
- return true;
- }
-
- return QSpinBox::eventFilter( o, e );
-}
-
-/*!
- Updates text of editor
-*/
-void QtxDblSpinBox::updateDisplay()
-{
- if ( myBlocked )
- return;
-
- bool upd = editor()->isUpdatesEnabled();
- editor()->setUpdatesEnabled( false );
-
- bool isBlock = myBlocked;
- myBlocked = true;
-
- QString txt = currentValueText();
-
- if ( myValue >= myMax )
- QSpinBox::setValue( QSpinBox::maxValue() );
- else if ( myValue <= myMin )
- QSpinBox::setValue( QSpinBox::minValue() );
- else
- QSpinBox::setValue( ( QSpinBox::minValue() + QSpinBox::maxValue() ) / 2 );
-
- QSpinBox::updateDisplay();
-
- editor()->setUpdatesEnabled( upd );
-
- editor()->setText( myCleared ? QString::null : txt );
- if ( !myCleared && editor()->hasFocus() )
- {
- if ( editor()->text() == specialValueText() )
- editor()->selectAll();
- else
- editor()->setSelection( prefix().length(), editor()->text().length() - prefix().length() - suffix().length() );
- }
- else
- editor()->setCursorPosition( 0 );
-
- myBlocked = isBlock;
-}
-
-/*!
- Sets double value by text in editor
-*/
-void QtxDblSpinBox::interpretText()
-{
- myCleared = false;
-
- bool ok = true;
- bool done = false;
- double newVal = 0;
- if ( !specialValueText().isEmpty() )
- {
- QString s = QString( text() ).stripWhiteSpace();
- QString t = QString( specialValueText() ).stripWhiteSpace();
- if ( s == t )
- {
- newVal = minValue();
- done = true;
- }
- }
- if ( !done )
- newVal = mapTextToDoubleValue( &ok );
- if ( ok )
- setValue( newVal );
- updateDisplay();
-}
-
-/*!
- Emits signal "valueChanged"
-*/
-void QtxDblSpinBox::valueChange()
-{
- updateDisplay();
- emit valueChanged( myValue );
- emit valueChanged( currentValueText() );
-}
-
-/*!
- Attune parameters on range changing
-*/
-void QtxDblSpinBox::rangeChange()
-{
- double min = QMIN( myMin, myMax );
- double max = QMAX( myMin, myMax );
- myMin = min;
- myMax = max;
- QDoubleValidator* v = ::qt_cast<QDoubleValidator*>( validator() );
- if ( v )
- v->setRange( myMin, myMax );
-
- if ( myMin == myMax )
- QSpinBox::setRange( 0, 0 );
- else
- QSpinBox::setRange( 0, 2 );
-
- setValue( myValue );
- updateDisplay();
-}
-
-/*!
- \return text of editor
-*/
-QString QtxDblSpinBox::currentValueText()
-{
- QString s;
- if ( (myValue == minValue()) && !specialValueText().isEmpty() )
- s = specialValueText();
- else
- {
- s = prefix();
- s.append( mapValueToText( myValue ) );
- s.append( suffix() );
- }
- return s;
-}
-
-/*!
- Converts number to string
- \param v - number to be converted
-*/
-QString QtxDblSpinBox::mapValueToText( double v )
-{
- QString s;
- s.setNum( v, myPrecision >= 0 ? 'f' : 'g', myPrecision == 0 ? 6 : QABS( myPrecision ) );
- return removeTrailingZeroes( s );
-}
-
-/*!
- Converts value to string
-*/
-QString QtxDblSpinBox::mapValueToText( int )
-{
- QString s;
- s.setNum( myValue, myPrecision >= 0 ? 'f' : 'g', myPrecision == 0 ? 6 : QABS( myPrecision ) );
- return removeTrailingZeroes( s );
-}
-
-/*!
- Converts current text of editor to double
-*/
-double QtxDblSpinBox::mapTextToDoubleValue( bool* ok )
-{
- QString s = text();
- double newVal = s.toDouble( ok );
- if ( !(*ok) && !( !prefix() && !suffix() ) )
- {
- s = cleanText();
- newVal = s.toDouble( ok );
- }
- return newVal;
-}
-
-/*!
- \return value corrected in accordance with borders
- \param val - value to be corrected
-*/
-double QtxDblSpinBox::bound( double val )
-{
- double newVal = val;
- if ( newVal > myMax )
- newVal = myMax;
- if ( newVal < myMin )
- newVal = myMin;
- return newVal;
-}
-
-/*!
- Custom handler for leave event
-*/
-void QtxDblSpinBox::leaveEvent( QEvent* e )
-{
- if ( !myCleared )
- QSpinBox::leaveEvent( e );
-}
-
-/*!
- Custom handler for wheel event
-*/
-void QtxDblSpinBox::wheelEvent( QWheelEvent* e )
-{
- if ( !isEnabled() )
- return;
-
- QSpinBox::wheelEvent( e );
- updateDisplay();
-}
-
-/*!
- SLOT: called if text is changed
-*/
-void QtxDblSpinBox::onTextChanged( const QString& str )
-{
- if ( !myBlocked )
- myCleared = false;
-}
-
-/*!
- \return string without excess zeros in start and in end
-*/
-QString QtxDblSpinBox::removeTrailingZeroes( const QString& src ) const
-{
- QString delim( "." );
-
- int idx = src.findRev( delim );
- if ( idx == -1 )
- return src;
-
- QString iPart = src.left( idx );
- QString fPart = src.mid( idx + 1 );
-
- while ( !fPart.isEmpty() && fPart.at( fPart.length() - 1 ) == '0' )
- fPart.remove( fPart.length() - 1, 1 );
-
- QString res = iPart;
- if ( !fPart.isEmpty() )
- res += delim + fPart;
-
- return res;
-}
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-// File: QtxDblSpinBox.h
-// Author: Sergey TELKOV
-
-#ifndef QTXDBLSPINBOX_H
-#define QTXDBLSPINBOX_H
-
-#include "Qtx.h"
-
-#include <qspinbox.h>
-
-/*!
- \class QtxDblSpinBox
- Spin box for real numbers.
-*/
-class QTX_EXPORT QtxDblSpinBox : public QSpinBox
-{
- Q_OBJECT
-
- class Validator;
-
-public:
- typedef enum QSpinBox::ButtonSymbols ButtonSymbols;
-
-public:
- QtxDblSpinBox( QWidget* = 0, const char* = 0 );
- QtxDblSpinBox( double, double, double = 1, QWidget* = 0, const char* = 0 );
- virtual ~QtxDblSpinBox();
-
- double minValue() const;
- double maxValue() const;
- void setMinValue( int );
- void setMaxValue( int );
- void setMinValue( double );
- void setMaxValue( double );
- void setRange( int, int );
- virtual void setRange( double, double );
-
- double lineStep() const;
- void setLineStep( int );
- virtual void setLineStep( double );
-
- double value() const;
-
- int precision() const;
- virtual void setPrecision( const int );
-
- bool isCleared() const;
- virtual void setCleared( const bool );
-
- virtual bool eventFilter( QObject*, QEvent* );
-
-signals:
- void valueChanged( double );
- void valueChanged( const QString& );
-
-public slots:
- virtual void stepUp();
- virtual void stepDown();
- virtual void selectAll();
- virtual void setValue( int );
- virtual void setValue( double );
-
-protected slots:
- virtual void onTextChanged( const QString& );
-
-protected:
- virtual void updateDisplay();
- virtual void interpretText();
-
- virtual void valueChange();
- virtual void rangeChange();
-
- QString currentValueText();
- virtual QString mapValueToText( int );
- virtual QString mapValueToText( double );
- virtual double mapTextToDoubleValue( bool* );
-
- virtual void leaveEvent( QEvent* );
- virtual void wheelEvent( QWheelEvent* );
-
- double bound( double );
-
- QString removeTrailingZeroes( const QString& ) const;
-
-private:
- double myMin;
- double myMax;
- double myStep;
- double myValue;
- bool myCleared;
- bool myBlocked;
- int myPrecision;
-};
-
-#endif
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-// File: QtxDblValidator.cxx
-// Author: Alexandre SOLOVYOV
-
-#include "QtxDblValidator.h"
-
-/*!
- Constructor
- \param bot - minimal possible value
- \param top - maximal possible value
- \param dec - number of digits
- \param o - parent object
- \param name - name of validator
-*/
-QtxDblValidator::QtxDblValidator( const double bot, const double top, const int dec,
- QObject* o, const char* name )
-: QDoubleValidator( bot, top, dec, o, name )
-{
-}
-
-/*!
- Destructor
-*/
-QtxDblValidator::~QtxDblValidator()
-{
-}
-
-/*!
- Corrects string: if it represent double value less then bottom, it becomes equal to bottom,
- if it is more then top, it becomes equal to top, if it isn't number is becomes '0'
-*/
-void QtxDblValidator::fixup( QString& str ) const
-{
- bool ok = false;
- double d = str.toDouble( &ok );
- if( ok )
- {
- if( d<bottom() )
- str = QString::number( bottom() );
- else if( d>top() )
- str = QString::number( top() );
- }
- else
- str = "0";
-}
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-// File: QtxDblValidator.h
-// Author: Alexandre SOLOVYOV
-
-#ifndef QTX_DOUBLE_VALIDATOR
-#define QTX_DOUBLE_VALIDATOR
-
-#include "Qtx.h"
-
-#include <qvalidator.h>
-
-class QTX_EXPORT QtxDblValidator : public QDoubleValidator
-{
- Q_OBJECT
-
-public:
- QtxDblValidator( const double, const double, const int,
- QObject*, const char* = 0 );
- ~QtxDblValidator();
-
- virtual void fixup( QString& ) const;
-};
-
-#endif
#include "QtxDialog.h"
-#include "QtxGroupBox.h"
-
-#include <qlabel.h>
-#include <qframe.h>
-#include <qlayout.h>
-#include <qpushbutton.h>
-#include <qapplication.h>
+#include <QLabel>
+#include <QLayout>
+#include <QKeyEvent>
+#include <QFrame>
+#include <QTabWidget>
+#include <QPushButton>
+#include <QApplication>
/*!
- Class: QtxDialog::Area
- Level: Internal
+ \class QtxDialog::Area
+ \internal
+ \brief Area containing dialog box buttons.
*/
+
class QtxDialog::Area : public QFrame
{
public:
- Area( Orientation, QtxDialog*, QWidget* = 0 );
- virtual ~Area();
+ Area( Qt::Orientation, QtxDialog*, QWidget* = 0 );
+ virtual ~Area();
- bool isBorderEnabled() const;
- void setBorderEnabled( const bool );
+ bool isBorderEnabled() const;
+ void setBorderEnabled( const bool );
- void setBorderWidget( QLabel* );
+ void setBorderWidget( QLabel* );
- void insertButton( QButton* );
- void removeButton( QButton* );
- bool contains( QButton* ) const;
+ void insertButton( QAbstractButton* );
+ void removeButton( QAbstractButton* );
+ bool contains( QAbstractButton* ) const;
- int policy() const;
- void setPolicy( const int );
+ int policy() const;
+ void setPolicy( const int );
- void layoutButtons();
+ void layoutButtons();
- const QPtrList<QButton>& buttons() const;
+ const QList<QAbstractButton*>& buttons() const;
private:
- void updateBorder();
+ void updateBorder();
private:
- QtxDialog* myDlg;
- QLabel* myLine;
- bool myBorder;
- int myPolicy;
- QPtrList<QButton> myButtons;
- Orientation myOrientation;
+ QtxDialog* myDlg; //!< parent dialog box
+ QLabel* myLine; //!< border widget
+ bool myBorder; //!< "has border" flag
+ int myPolicy; //!< button layout type (QtxDialog::PlacePolicy)
+ QList<QAbstractButton*> myButtons; //!< buttons list
+ Qt::Orientation myOrientation; //!< buttons orientation (Qt::Orientation)
};
/*!
- Contructor
+ \brief Constructor.
+ \param o buttons orientation
+ \param dlg dialog box owning this area
+ \param parent parent widget
*/
-QtxDialog::Area::Area( Orientation o, QtxDialog* dlg, QWidget* parent )
+QtxDialog::Area::Area( Qt::Orientation o, QtxDialog* dlg, QWidget* parent )
: QFrame( parent ),
-myDlg( dlg ),
-myLine( 0 ),
-myBorder( false ),
-myPolicy( Position ),
-myOrientation( o )
+ myDlg( dlg ),
+ myLine( 0 ),
+ myBorder( false ),
+ myPolicy( Position ),
+ myOrientation( o )
{
- if ( myOrientation == Qt::Horizontal )
- setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Maximum ) );
- else
- setSizePolicy( QSizePolicy( QSizePolicy::Maximum, QSizePolicy::Preferred ) );
+ if ( myOrientation == Qt::Horizontal )
+ setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Maximum ) );
+ else
+ setSizePolicy( QSizePolicy( QSizePolicy::Maximum, QSizePolicy::Preferred ) );
- hide();
+ hide();
}
/*!
- Destructor
+ \brief Destructor.
*/
QtxDialog::Area::~Area()
{
}
/*!
- Inserts button to area
- \param b - button
+ \brief Insert button to the area.
+ \param b button to be added
+ \sa removeButton()
*/
-void QtxDialog::Area::insertButton( QButton* b )
+void QtxDialog::Area::insertButton( QAbstractButton* b )
{
- if ( !b || myButtons.findRef( b ) != -1 )
- return;
+ if ( !b || myButtons.contains( b ) )
+ return;
- QWidget* parent = b->parentWidget();
- if ( parent != this )
- b->reparent( this, 0, QPoint( 0, 0 ), b->isVisibleTo( parent ) );
+ QWidget* parent = b->parentWidget();
+ if ( parent != this )
+ b->setParent( this );
- myButtons.append( b );
+ myButtons.append( b );
- if ( myDlg )
- myDlg->adjustButtons();
- layoutButtons();
+ if ( myDlg )
+ myDlg->adjustButtons();
+ layoutButtons();
- show();
+ show();
- updateBorder();
+ updateBorder();
}
/*!
- Removes button from area
- \param b - button
+ \brief Remove button from the area.
+ \param b button to be removed
+ \sa insertButton()
*/
-void QtxDialog::Area::removeButton( QButton* b )
+void QtxDialog::Area::removeButton( QAbstractButton* b )
{
- if ( !b )
- return;
+ if ( !b )
+ return;
- myButtons.removeRef( b );
+ myButtons.removeAll( b );
- if ( myButtons.isEmpty() )
- hide();
+ if ( myButtons.isEmpty() )
+ hide();
- updateBorder();
+ updateBorder();
- if ( myDlg )
- myDlg->adjustButtons();
+ if ( myDlg )
+ myDlg->adjustButtons();
- layoutButtons();
+ layoutButtons();
}
/*!
- \return true if area contains button
- \param b - button
+ \brief Check if area owns the button specified.
+ \param b button to be checked
+ \return \c true if area contains button
*/
-bool QtxDialog::Area::contains( QButton* b ) const
+bool QtxDialog::Area::contains( QAbstractButton* b ) const
{
- return myButtons.containsRef( b );
+ return myButtons.contains( b );
}
/*!
- \return policy of button layouting.
+ \brief Get buttons layout policy.
+ \return policy of button layouting (Qtx::PlacePolicy)
+ \sa setPolicy()
*/
int QtxDialog::Area::policy() const
{
- return myPolicy;
+ return myPolicy;
}
/*!
- Changes policy of button layouting.
- \param p - new policy
+ \brief Set buttons layout policy.
+ \param p new policy
*/
void QtxDialog::Area::setPolicy( const int p )
{
- if ( myPolicy == p )
- return;
+ if ( myPolicy == p )
+ return;
- myPolicy = p;
- layoutButtons();
+ myPolicy = p;
+ layoutButtons();
}
/*!
- \return true if border enabled
+ \brief Check of the border is enabled.
+ \return \c true if border is enabled
+ \sa setBorderEnabled(), setBorderWidget()
*/
bool QtxDialog::Area::isBorderEnabled() const
{
- return myLine && myBorder;
+ return myLine && myBorder;
}
/*!
- Enables/disable separator between main frame and button frame
- \param on - new state
+ \brief Enable/disable border (separator between main frame and button frame)
+ \param on new state
*/
void QtxDialog::Area::setBorderEnabled( const bool on )
{
- if ( !myLine || myBorder == on )
- return;
+ if ( !myLine || myBorder == on )
+ return;
- myBorder = on;
- updateBorder();
+ myBorder = on;
+ updateBorder();
}
/*!
- Sets label as separator between main frame and button frame
- \param line - new separator
+ \brief Set border widget (separator between main frame and button frame).
+ \param line new separator widget
*/
void QtxDialog::Area::setBorderWidget( QLabel* line )
{
- if ( myLine == line )
- return;
+ if ( myLine == line )
+ return;
- delete myLine;
- myLine = line;
- updateBorder();
+ delete myLine;
+ myLine = line;
+ updateBorder();
}
/*!
- \return const reference to list of buttons
+ \brief Get all area buttons.
+ \return const reference to the list of buttons
*/
-const QPtrList<QButton>& QtxDialog::Area::buttons() const
+const QList<QAbstractButton*>& QtxDialog::Area::buttons() const
{
- return myButtons;
+ return myButtons;
}
/*!
- Updates visibility of border
+ \brief Update border visibility.
*/
void QtxDialog::Area::updateBorder()
{
- if ( !myLine )
- return;
+ if ( !myLine )
+ return;
- bool isVis = isVisibleTo( parentWidget() );
-#if QT_VER >= 3
- if ( isVis )
-#else
- if ( isVis && myBorder )
-#endif
- myLine->show();
- else
- myLine->hide();
+ bool isVis = isVisibleTo( parentWidget() );
+ myLine->setVisible( isVis );
- myLine->setLineWidth( myBorder ? 1 : 0 );
+ myLine->setLineWidth( myBorder ? 1 : 0 );
}
/*!
- Installs buttons into layout
+ \brief Layout buttons in the area.
*/
void QtxDialog::Area::layoutButtons()
{
- int aPolicy = policy();
-
- QMap<QButton*, int> buttonId;
- for ( QPtrListIterator<QButton> it1( myButtons ); it1.current(); ++it1 )
- buttonId.insert( it1.current(), 0 );
-
- QPtrList<QButton> src;
- for ( ButtonMap::Iterator mit = myDlg->myButton.begin();
- mit != myDlg->myButton.end(); ++mit )
- {
- if ( buttonId.contains( mit.data() ) )
- {
- buttonId[mit.data()] = mit.key();
- if ( mit.key() >= 0 )
- src.append( mit.data() );
- }
- }
-
- for ( QPtrListIterator<QButton> it2( myButtons ); it2.current(); ++it2 )
- if ( buttonId[it2.current()] < 0 )
- src.append( it2.current() );
-
- QPtrList<QButton> left, right, center, other;
- for ( QPtrListIterator<QButton> it( src ); it.current(); ++it )
- {
- if ( !it.current()->isVisibleTo( this ) )
- continue;
-
- int aPosition = myDlg->buttonPosition( it.current() );
- if ( aPosition == -1 )
- continue;
-
- if ( aPolicy != QtxDialog::Position )
- other.append( it.current() );
- else if ( aPosition == QtxDialog::Left )
- left.append( it.current() );
- else if ( aPosition == QtxDialog::Right )
- right.append( it.current() );
- else if ( aPosition == QtxDialog::Center )
- center.append( it.current() );
- }
+ int aPolicy = policy();
+
+ QMap<QAbstractButton*, int> buttonId;
+ for ( QList<QAbstractButton*>::iterator it1 = myButtons.begin(); it1 != myButtons.end(); ++it1 )
+ buttonId.insert( *it1, 0 );
+
+ QList<QAbstractButton*> src;
+ for ( ButtonMap::Iterator mit = myDlg->myButton.begin(); mit != myDlg->myButton.end(); ++mit )
+ {
+ if ( buttonId.contains( mit.value() ) )
+ {
+ buttonId[mit.value()] = mit.key();
+ if ( mit.key() >= 0 )
+ src.append( mit.value() );
+ }
+ }
+
+ for ( QList<QAbstractButton*>::iterator it2 = myButtons.begin(); it2 != myButtons.end(); ++it2 )
+ {
+ if ( buttonId[*it2] < 0 )
+ src.append( *it2 );
+ }
+
+ QList<QAbstractButton*> left, right, center, other;
+ for ( QList<QAbstractButton*>::iterator it = src.begin(); it != src.end(); ++it )
+ {
+ if ( !(*it)->isVisibleTo( this ) )
+ continue;
+
+ int aPosition = myDlg->buttonPosition( *it );
+ if ( aPosition == -1 )
+ continue;
+
+ if ( aPolicy != QtxDialog::Position )
+ other.append( *it );
+ else if ( aPosition == QtxDialog::Left )
+ left.append( *it );
+ else if ( aPosition == QtxDialog::Right )
+ right.append( *it );
+ else if ( aPosition == QtxDialog::Center )
+ center.append( *it );
+ }
delete layout();
- QBoxLayout* buttonLayout = 0;
- if ( myOrientation == Qt::Vertical )
- buttonLayout = new QVBoxLayout( this, 0, 5 );
- else
- buttonLayout = new QHBoxLayout( this, 0, 5 );
-
- if ( !buttonLayout )
- return;
-
- if ( aPolicy == QtxDialog::Position )
- {
- for ( QPtrListIterator<QButton> lit( left ); lit.current(); ++lit )
- buttonLayout->addWidget( lit.current() );
- buttonLayout->addStretch( 1 );
- for ( QPtrListIterator<QButton> cit( center ); cit.current(); ++cit )
- buttonLayout->addWidget( cit.current() );
- buttonLayout->addStretch( 1 );
- for ( QPtrListIterator<QButton> rit( right ); rit.current(); ++rit )
- buttonLayout->addWidget( rit.current() );
- }
- else
- {
- for ( QPtrListIterator<QButton> oit( other ); oit.current(); ++oit )
- {
- buttonLayout->addWidget( oit.current() );
- if ( aPolicy == QtxDialog::Uniform && !oit.atLast() )
- buttonLayout->addStretch( 1 );
- }
- }
+ QBoxLayout* buttonLayout = 0;
+ if ( myOrientation == Qt::Vertical )
+ buttonLayout = new QVBoxLayout( this );
+ else
+ buttonLayout = new QHBoxLayout( this );
+
+ if ( !buttonLayout )
+ return;
+
+ buttonLayout->setMargin( 0 );
+ buttonLayout->setSpacing( 5 );
+
+ if ( aPolicy == QtxDialog::Position )
+ {
+ for ( QList<QAbstractButton*>::iterator lit = left.begin(); lit != left.end(); ++lit )
+ buttonLayout->addWidget( *lit );
+ buttonLayout->addStretch( 1 );
+ for ( QList<QAbstractButton*>::iterator cit = center.begin(); cit != center.end(); ++cit )
+ buttonLayout->addWidget( *cit );
+ buttonLayout->addStretch( 1 );
+ for ( QList<QAbstractButton*>::iterator rit = right.begin(); rit != right.end(); ++rit )
+ buttonLayout->addWidget( *rit );
+ }
+ else
+ {
+ for ( int i = 0; i < (int)other.count(); i++ )
+ {
+ buttonLayout->addWidget( other[i] );
+ if ( aPolicy == QtxDialog::Uniform && i < (int)other.count() - 1 )
+ buttonLayout->addStretch( 1 );
+ }
+ }
QWidgetList wids;
if ( layout() )
{
- for ( QLayoutIterator it = layout()->iterator(); it.current(); ++it )
+ for ( int i = 0; i < layout()->count(); i++ )
{
- if ( !it.current()->widget() )
+ if ( !layout()->itemAt( i ) || layout()->itemAt( i )->widget() )
continue;
- if ( QApplication::reverseLayout() )
- wids.prepend( it.current()->widget() );
+ if ( QApplication::layoutDirection() == Qt::RightToLeft )
+ wids.prepend( layout()->itemAt( i )->widget() );
else
- wids.append( it.current()->widget() );
+ wids.append( layout()->itemAt( i )->widget() );
}
}
Qtx::setTabOrder( wids );
/*!
\class QtxDialog::Border
-
- Special label used as separator between main frame and button frame
+ \internal
+ \brief Special label used as border widget (separator
+ between main frame and button frame).
*/
+
class QtxDialog::Border : public QLabel
{
public:
- Border( QWidget* = 0 );
- virtual ~Border();
+ Border( QWidget* = 0 );
+ virtual ~Border();
- virtual void setLineWidth( int );
+ virtual void setLineWidth( int );
- virtual QSize sizeHint() const;
- virtual QSize minimumSizeHint() const;
+ virtual QSize sizeHint() const;
+ virtual QSize minimumSizeHint() const;
};
/*!
- Constructor
+ \brief Constructor.
+ \param parent parent widget
*/
QtxDialog::Border::Border( QWidget* parent )
: QLabel( parent )
{
- setAlignment( Qt::AlignCenter );
+ setAlignment( Qt::AlignCenter );
}
/*!
- Destructor
+ \brief Destructor.
*/
QtxDialog::Border::~Border()
{
}
/*!
- Set line width of separator
- \param lw - new line width
+ \brief Set separator line width.
+ \param lw new line width
*/
void QtxDialog::Border::setLineWidth( int lw )
{
}
/*!
- \return the recommended size for the widget
+ \brief Get recommended size for the widget.
+ \return recommended size for the widget
*/
QSize QtxDialog::Border::sizeHint() const
{
QSize sz( 5, 5 );
-#if QT_VER >= 3
if ( lineWidth() > 0 )
- {
+ {
if ( frameShape() == VLine )
sz += QSize( 5 + lineWidth(), 0 );
- else if ( frameShape() == HLine )
+ else if ( frameShape() == HLine )
sz += QSize( 0, 5 + lineWidth() );
- }
-#endif
+ }
return sz;
}
/*!
- \return the recommended minimum size for the widget
+ \brief Get recommended minimum size for the widget.
+ \return recommended minimum size for the widget
*/
QSize QtxDialog::Border::minimumSizeHint() const
{
- return sizeHint();
+ return sizeHint();
}
/*!
- Constructor
+ \class QtxDialog
+ \brief Generic dialog box class.
+*/
+
+/*!
+ \brief Constructor.
+
Construct a dialog with specified parent and name.
- \param modal define modal status of dialog (default non modal dialog created).
- \param allowResize - if it is true then dialog can be resize by user (default non resizable dialog created).
- \param Button flags specified control buttons for dialog (default buttons is OK, Cancel and Help).
- \param Widget flags used as in any widget.
-*/
-QtxDialog::QtxDialog( QWidget* parent, const char* name,
- bool modal, bool allowResize, const int f, WFlags wf )
-: QDialog( parent, name, modal,
- wf | WStyle_Customize | WStyle_Title | WStyle_SysMenu |
+ By default non-modal, non-resizable with the OK, Cancel and Help buttons
+ dialog box is created.
+
+ \param parent parent widget
+ \param modal if \c true dialog box is modal
+ \param allowResize if \c true then dialog can be resized by user
+ \param f specified control buttons for dialog box (QtxDialog::ButtonFlags)
+ \param wf dialog box flags (Qt::WindowFlags)
+*/
+QtxDialog::QtxDialog( QWidget* parent, bool modal, bool allowResize, const int f, Qt::WindowFlags wf )
+: QDialog( parent, (Qt::WindowFlags)( wf | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::Dialog |
#ifdef WIN32
- ( allowResize ? WStyle_NormalBorder : WStyle_NoBorderEx ) |
-#else
- WStyle_NormalBorder |
+ ( allowResize ? 0 : Qt::FramelessWindowHint ) |
#endif
- ( allowResize ? WStyle_Maximize : 0 ) ),
-mySender( 0 ),
-myAlignment( 0 ),
-myInited( false ),
-myDialogFlags( Accept | SetFocus )
-{
- QVBoxLayout* base = new QVBoxLayout( this, 5, 0 );
- QtxGroupBox* main = new QtxGroupBox( 1, Qt::Horizontal, "", this );
- main->setFrameStyle( QFrame::NoFrame );
- main->setInsideMargin( 0 );
- main->setInsideSpacing( 0 );
- base->addWidget( main );
-
- Area* topArea = new Area( Qt::Horizontal, this, main );
- QLabel* topLine = new Border( main );
- QtxGroupBox* midGroup = new QtxGroupBox( 1, Qt::Vertical, "", main );
- QLabel* botLine = new Border( main );
- Area* botArea = new Area( Qt::Horizontal, this, main );
-
- midGroup->setFrameStyle( QFrame::NoFrame );
- midGroup->setInsideMargin( 0 );
- midGroup->setInsideSpacing( 0 );
-
- Area* leftArea = new Area( Qt::Vertical, this, midGroup );
- QLabel* leftLine = new Border( midGroup );
- myMainFrame = new QFrame( midGroup );
- QLabel* rightLine = new Border( midGroup );
- Area* rightArea = new Area( Qt::Vertical, this, midGroup );
-
- myMainFrame->setSizePolicy( QSizePolicy( QSizePolicy::Expanding,
- QSizePolicy::Expanding ) );
-
- topLine->setFrameStyle( QFrame::Sunken | QFrame::HLine );
- botLine->setFrameStyle( QFrame::Sunken | QFrame::HLine );
- leftLine->setFrameStyle( QFrame::Sunken | QFrame::VLine );
- rightLine->setFrameStyle( QFrame::Sunken | QFrame::VLine );
- topArea->setBorderWidget( topLine );
- botArea->setBorderWidget( botLine );
- leftArea->setBorderWidget( leftLine );
- rightArea->setBorderWidget( rightLine );
-
- myArea.insert( TopArea, topArea );
- myArea.insert( BottomArea, botArea );
- myArea.insert( LeftArea, leftArea );
- myArea.insert( RightArea, rightArea );
-
- for ( AreaMap::Iterator itr = myArea.begin(); itr != myArea.end(); ++ itr )
- itr.data()->setBorderEnabled( false );
-
- myButton.insert( OK, new QPushButton( tr( "&OK" ), this ) );
- myButton.insert( Cancel, new QPushButton( tr( "&Cancel" ), this ) );
- myButton.insert( Close, new QPushButton( tr( "C&lose" ), this ) );
- myButton.insert( Help, new QPushButton( tr( "&Help" ), this ) );
- myButton.insert( Apply, new QPushButton( tr( "&Apply" ), this ) );
- myButton.insert( Yes, new QPushButton( tr( "&Yes" ), this ) );
- myButton.insert( No, new QPushButton( tr( "&No" ), this ) );
-
- for ( ButtonMap::Iterator it = myButton.begin(); it != myButton.end(); ++it )
- {
- ((QPushButton*)it.data())->setAutoDefault( false );
-#if QT_VER >= 3
- connect( it.data(), SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
+ ( ( allowResize
+#ifdef WIN32
+ // in qwidget_win.cpp flag WStyle_ContextHelp will be unset in WStyle_MinMax in switched ON
+ && !( wf & Qt::WindowContextHelpButtonHint )
#endif
- }
+ ) ? Qt::WindowMaximizeButtonHint : 0 ) ) ),
+ myInited( false ),
+ mySender( 0 ),
+ myAlignment( 0 ),
+ myDialogFlags( Accept | SetFocus )
+{
+ setModal( modal );
+
+ QVBoxLayout* base = new QVBoxLayout( this );
+ base->setMargin( 5 );
+ base->setSpacing( 0 );
+
+ QWidget* main = new QWidget( this );
+ base->addWidget( main );
+
+ QVBoxLayout* lMain = new QVBoxLayout( main );
+ lMain->setMargin( 0 );
+ lMain->setSpacing( 0 );
+
+ Area* topArea = new Area( Qt::Horizontal, this, main );
+ QLabel* topLine = new Border( main );
+ lMain->addWidget( topArea );
+ lMain->addWidget( topLine );
+
+ QWidget* midGroup = new QWidget( main );
+ lMain->addWidget( midGroup );
+
+ QVBoxLayout* midLyout = new QVBoxLayout( midGroup );
+ midLyout->setMargin( 0 );
+ midLyout->setSpacing( 0 );
+
+ QLabel* botLine = new Border( main );
+ Area* botArea = new Area( Qt::Horizontal, this, main );
+ lMain->addWidget( botLine );
+ lMain->addWidget( botArea );
+
+ Area* leftArea = new Area( Qt::Vertical, this, midGroup );
+ QLabel* leftLine = new Border( midGroup );
+ midLyout->addWidget( leftArea );
+ midLyout->addWidget( leftLine );
+
+ myMainFrame = new QFrame( midGroup );
+ midLyout->addWidget( myMainFrame );
+
+ QLabel* rightLine = new Border( midGroup );
+ Area* rightArea = new Area( Qt::Vertical, this, midGroup );
+ midLyout->addWidget( rightLine );
+ midLyout->addWidget( rightArea );
+
+ myMainFrame->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ) );
+
+ topLine->setFrameStyle( QFrame::Sunken | QFrame::HLine );
+ botLine->setFrameStyle( QFrame::Sunken | QFrame::HLine );
+ leftLine->setFrameStyle( QFrame::Sunken | QFrame::VLine );
+ rightLine->setFrameStyle( QFrame::Sunken | QFrame::VLine );
+
+ topArea->setBorderWidget( topLine );
+ botArea->setBorderWidget( botLine );
+ leftArea->setBorderWidget( leftLine );
+ rightArea->setBorderWidget( rightLine );
+
+ myArea.insert( TopArea, topArea );
+ myArea.insert( BottomArea, botArea );
+ myArea.insert( LeftArea, leftArea );
+ myArea.insert( RightArea, rightArea );
+
+ for ( AreaMap::Iterator itr = myArea.begin(); itr != myArea.end(); ++ itr )
+ itr.value()->setBorderEnabled( false );
+
+ myButton.insert( OK, new QPushButton( tr( "&OK" ), this ) );
+ myButton.insert( Cancel, new QPushButton( tr( "&Cancel" ), this ) );
+ myButton.insert( Close, new QPushButton( tr( "C&lose" ), this ) );
+ myButton.insert( Help, new QPushButton( tr( "&Help" ), this ) );
+ myButton.insert( Apply, new QPushButton( tr( "&Apply" ), this ) );
+ myButton.insert( Yes, new QPushButton( tr( "&Yes" ), this ) );
+ myButton.insert( No, new QPushButton( tr( "&No" ), this ) );
+
+ for ( ButtonMap::Iterator it = myButton.begin(); it != myButton.end(); ++it )
+ {
+ ((QPushButton*)it.value())->setAutoDefault( false );
+ connect( it.value(), SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
+ }
- setButtonPosition( Left, OK | Cancel | Apply );
- setButtonPosition( Center, Yes | No | Close );
- setButtonPosition( Right, Help );
- setButtonPlace( BottomArea, All );
+ setButtonPosition( Left, OK | Cancel | Apply );
+ setButtonPosition( Center, Yes | No | Close );
+ setButtonPosition( Right, Help );
+ setButtonPlace( BottomArea, All );
- connect( myButton[Apply], SIGNAL( clicked() ), this, SIGNAL( dlgApply() ) );
- connect( myButton[Help], SIGNAL( clicked() ), this, SIGNAL( dlgHelp() ) );
+ connect( myButton[Apply], SIGNAL( clicked() ), this, SIGNAL( dlgApply() ) );
+ connect( myButton[Help], SIGNAL( clicked() ), this, SIGNAL( dlgHelp() ) );
- connect( myButton[OK], SIGNAL( clicked() ), this, SLOT( onAccept() ) );
- connect( myButton[Cancel], SIGNAL( clicked() ), this, SLOT( onReject() ) );
- connect( myButton[Yes], SIGNAL( clicked() ), this, SLOT( onAccept() ) );
- connect( myButton[No], SIGNAL( clicked() ), this, SLOT( onReject() ) );
- connect( myButton[Close], SIGNAL( clicked() ), this, SLOT( onReject() ) );
+ connect( myButton[OK], SIGNAL( clicked() ), this, SLOT( onAccept() ) );
+ connect( myButton[Cancel], SIGNAL( clicked() ), this, SLOT( onReject() ) );
+ connect( myButton[Yes], SIGNAL( clicked() ), this, SLOT( onAccept() ) );
+ connect( myButton[No], SIGNAL( clicked() ), this, SLOT( onReject() ) );
+ connect( myButton[Close], SIGNAL( clicked() ), this, SLOT( onReject() ) );
- QPixmap icon;
- if ( qApp && qApp->mainWidget() && qApp->mainWidget()->icon() )
- setIcon( *qApp->mainWidget()->icon() );
+ QIcon icon;
+ QWidget* p = parentWidget();
+ while( p && p->parentWidget() )
+ p = p->parentWidget();
- myButtonFlags = f;
+ if ( p )
+ setWindowIcon( p->windowIcon() );
+
+ myButtonFlags = f;
#ifndef WIN32
- if ( !allowResize )
- setMaximumSize( minimumSize() );
+ if ( !allowResize )
+ setMaximumSize( minimumSize() );
#endif
- update();
+ update();
}
/*!
- Name: ~QtxDialog [public]
- Desc: Destructor
+ \brief Destructor.
*/
-
QtxDialog::~QtxDialog()
{
}
/*!
- Name: setButtonFlags [public]
- Desc: Allow to set specified control button(s) into dialog.
+ \brief Add specified control button(s) to the dialog box.
+ \param f ORed buttons flags (Qtx::ButtonFlags)
+ \sa clearButtonFlags(), testButtonFlags()
*/
-
void QtxDialog::setButtonFlags( const int f )
{
- int old = myButtonFlags;
- myButtonFlags = myButtonFlags | f;
- if ( old != myButtonFlags )
- update();
+ int old = myButtonFlags;
+ myButtonFlags = myButtonFlags | f;
+ if ( old != myButtonFlags )
+ update();
}
/*!
- Name: clearButtonFlags [public]
- Desc: Allow to unset specified control button(s) from dialog.
+ \brief Remove specified control button(s) from the dialog box.
+ \param f ORed buttons flags (Qtx::ButtonFlags)
+ \sa setButtonFlags(), testButtonFlags()
*/
-
void QtxDialog::clearButtonFlags( const int f )
{
- int old = myButtonFlags;
- myButtonFlags = myButtonFlags & ~f;
- if ( old != myButtonFlags )
- update();
+ int old = myButtonFlags;
+ myButtonFlags = myButtonFlags & ~f;
+ if ( old != myButtonFlags )
+ update();
}
/*!
- Name: testButtonFlags [public]
- Desc: Return true if specified control button is used in dialog.
+ \brief Test specified buttons.
+ \return \c true if specified control buttons are used in the dialog box
+ \sa setButtonFlags(), clearButtonFlags()
*/
-
bool QtxDialog::testButtonFlags( const int f ) const
{
- return ( myButtonFlags & f ) == f;
+ return ( myButtonFlags & f ) == f;
}
/*!
- Name: setDialogFlags [public]
- Desc: Allow to set the dialog flags.
-
- Following flags can be used:
- Accept - Allow to control dialog accepting. See also acceptData().
- Reject - Allow to control dialog rejecting. See also rejectData().
- AlignOnce - Allow to align dialog only when it first time shown.
- SetFocus - Allow to set focus on dialog when it shown. User can use
- setFocusProxy() and specify own initial focus widget.
+ \brief Set specified dialog box flags.
+ \param f dialog box flags (QtxDialog::DialogFlags)
+ \sa clearDialogFlags(), testDialogFlags(), acceptData(), rejectData()
*/
-
void QtxDialog::setDialogFlags( const int f )
{
- myDialogFlags = myDialogFlags | f;
+ myDialogFlags = myDialogFlags | f;
}
/*!
- Name: clearDialogFlags [public]
- Desc: Allow to clear the dialog flags. See also setDialogFlags().
+ \brief Clear specified the dialog flags.
+ \param f dialog box flags (QtxDialog::DialogFlags)
+ \sa setDialogFlags(), testDialogFlags()
*/
-
void QtxDialog::clearDialogFlags( const int f )
{
- myDialogFlags = myDialogFlags & ~f;
+ myDialogFlags = myDialogFlags & ~f;
}
/*!
- Name: testDialogFlags [public]
- Desc: Returns true if specified dialog flag is setted (see setDialogFlags()).
+ \brief Test specified dialog flags.
+ \return \c true if specified dialog box falgs are set
+ \sa setDialogFlags(), clearDialogFlags()
*/
-
bool QtxDialog::testDialogFlags( const int f ) const
{
- return ( myDialogFlags & f ) == f;
+ return ( myDialogFlags & f ) == f;
}
/*!
- Name: mainFrame [public]
- Desc: Returns main frame of dialog. Main frame should contains all
- elements of dialog except control buttons.
-*/
+ \brief Get dialog box main frame widget.
+
+ Main frame is an internal widget which should contains all
+ elements of dialog box except control buttons.
+ \return main frame widget
+*/
QFrame* QtxDialog::mainFrame() const
{
- return myMainFrame;
+ return myMainFrame;
}
/*!
- Name: buttonPosition [public]
- Desc: Returns position of specified button.
+ \brief Get specified control button position
+ \param id control button ID (QtxDialog::ButtonFlags)
+ \return button's position (QtxDialog::ButtonPosition) or -1 if it is not set or invalid \a id is given
+ \sa setButtonPosition()
*/
-
int QtxDialog::buttonPosition( const int id ) const
{
- int pos = -1;
- if ( myPosition.contains( id ) )
- pos = myPosition[id];
- return pos;
+ int pos = -1;
+ if ( myPosition.contains( id ) )
+ pos = myPosition[id];
+ return pos;
}
-
/*!
- Name: setButtonPosition [public]
- Desc: Sets the position for specified button(s). Following positions
- may be used: Left, Right, Center, Top, Bottom.
+ \brief Set the specified control button(s) position.
+ \param id control button(s) ID (QtxDialog::ButtonFlags)
+ \param pos button(s) position (QtxDialog::ButtonPosition)
*/
-
void QtxDialog::setButtonPosition( const int pos, const int id )
{
- ButtonMap map = buttons( id );
+ ButtonMap map = buttons( id );
- QMap<QObject*, int> changed;
- for ( ButtonMap::Iterator it = map.begin(); it != map.end(); ++it )
- {
- if ( myPosition[it.key()] == pos )
- continue;
+ QMap<QObject*, int> changed;
+ for ( ButtonMap::Iterator it = map.begin(); it != map.end(); ++it )
+ {
+ if ( myPosition[it.key()] == pos )
+ continue;
- myPosition[it.key()] = pos;
- if ( button( it.key() ) )
- changed.insert( button( it.key() )->parent(), 0 );
- }
-
- for ( AreaMap::Iterator itr = myArea.begin(); itr != myArea.end(); ++itr )
- if ( changed.contains( itr.data() ) )
- itr.data()->layoutButtons();
+ myPosition[it.key()] = pos;
+ if ( button( it.key() ) )
+ changed.insert( button( it.key() )->parent(), 0 );
+ }
+
+ for ( AreaMap::Iterator itr = myArea.begin(); itr != myArea.end(); ++itr )
+ {
+ if ( changed.contains( itr.value() ) )
+ itr.value()->layoutButtons();
+ }
}
/*!
- Name: setPlacePosition [public]
- Desc: Sets button position for all buttons in given place.
+ \brief Set button position for all buttons in specified \a area.
+ \param pos button(s) position (QtxDialog::ButtonPosition)
+ \param area buttons area (QtxDialog::ButtonArea)
+ \sa setButtonPosition()
*/
-
void QtxDialog::setPlacePosition( const int pos, const int area )
{
- if ( !myArea.contains( area ) )
- return;
+ if ( !myArea.contains( area ) )
+ return;
- Area* anArea = myArea[area];
+ Area* anArea = myArea[area];
- bool changed = false;
- for ( ButtonMap::Iterator it = myButton.begin(); it != myButton.end(); ++it )
- {
- if ( !anArea->contains( it.data() ) )
- continue;
+ bool changed = false;
+ for ( ButtonMap::Iterator it = myButton.begin(); it != myButton.end(); ++it )
+ {
+ if ( !anArea->contains( it.value() ) )
+ continue;
- changed = changed && myPosition[it.key()] != pos;
+ changed = changed && myPosition[it.key()] != pos;
- myPosition[it.key()] = pos;
- }
+ myPosition[it.key()] = pos;
+ }
- if ( changed )
- anArea->layoutButtons();
+ if ( changed )
+ anArea->layoutButtons();
}
/*!
- Name: placePolicy [public]
- Desc: Returns policy of button layouting for specified place.
-
- Following place may be used:
- TopArea - Horizontal area in the top side of dialog.
- BottomArea - Horizontal area in the bottom side of dialog.
- LeftArea - Vertical area in the left side of dialog.
- RightArea - Vertical area in the right side of dialog.
-
- Following policy may be used:
- Position - Buttons placed according their position.
- Expand - Buttons fills all available space.
- Uniform - Buttons uniformly placed in area.
+ \brief Get buttons layouting policy for the specified \a area.
+ \param area buttons area (QtxDialog::ButtonArea)
+ \sa setPlacePolicy()
*/
-
int QtxDialog::placePolicy( const int area ) const
{
- int res = -1;
- if ( myArea.contains( area ) )
- res = myArea[area]->policy();
- return res;
+ int res = -1;
+ if ( myArea.contains( area ) )
+ res = myArea[area]->policy();
+ return res;
}
/*!
- Name: setPlacePolicy [public]
- Desc: Sets the policy of button layouting for specified place.
- See also placePolicy().
+ \brief set buttons layouting policy for the specified \a area.
+ \param policy buttons layouting policy (QtxDialog::PlacePolicy)
+ \param area buttons area (QtxDialog::ButtonArea)
+ \sa placePolicy()
*/
-
void QtxDialog::setPlacePolicy( const int policy, const int area )
{
- if ( area < 0 )
- for ( AreaMap::Iterator itr = myArea.begin(); itr != myArea.end(); ++itr )
- itr.data()->setPolicy( policy );
- else if ( myArea.contains( area ) )
- myArea[area]->setPolicy( policy );
+ if ( area < 0 )
+ {
+ for ( AreaMap::Iterator itr = myArea.begin(); itr != myArea.end(); ++itr )
+ itr.value()->setPolicy( policy );
+ }
+ else if ( myArea.contains( area ) )
+ myArea[area]->setPolicy( policy );
}
/*!
- Name: setButtonPlace [public]
- Desc: Move given button(s) into specified place.
+ \brief Move specified button(s) into specified area.
+ \param area buttons area (QtxDialog::ButtonArea)
+ \param id control button(s) ID (QtxDialog::ButtonFlags)
*/
-
-void QtxDialog::setButtonPlace( const int area, const int ids )
+void QtxDialog::setButtonPlace( const int area, const int id )
{
- if ( !myArea.contains( area ) )
- return;
-
- Area* anArea = myArea[area];
-
- ButtonMap map = buttons( ids );
+ if ( !myArea.contains( area ) )
+ return;
- QMap<Area*, int> areaMap;
- for ( AreaMap::ConstIterator aIt = myArea.begin(); aIt != myArea.end(); ++aIt )
- areaMap.insert( aIt.data(), 0 );
+ Area* anArea = myArea[area];
+ ButtonMap map = buttons( id );
+ QMap<Area*, int> areaMap;
+ for ( AreaMap::ConstIterator aIt = myArea.begin(); aIt != myArea.end(); ++aIt )
+ areaMap.insert( aIt.value(), 0 );
- for ( ButtonMap::Iterator it = map.begin(); it != map.end(); ++it )
- {
- Area* old = (Area*)it.data()->parent();
- if ( old == anArea )
- continue;
+ for ( ButtonMap::Iterator it = map.begin(); it != map.end(); ++it )
+ {
+ Area* old = (Area*)it.value()->parent();
+ if ( old == anArea )
+ continue;
- if ( areaMap.contains( old ) )
- old->removeButton( it.data() );
- anArea->insertButton( it.data() );
- }
+ if ( areaMap.contains( old ) )
+ old->removeButton( it.value() );
+ anArea->insertButton( it.value() );
+ }
}
/*!
- Name: isBorderEnabled [public]
- Desc: Returns true if border is shown for specified button area.
+ \brief Check if border is enabled.
+ \param area buttons area (QtxDialog::ButtonArea)
+ \return \c true if border is enabled for specified button area.
+ \sa setBorderEnabled()
*/
-
bool QtxDialog::isBorderEnabled( const int area ) const
{
- bool res = false;
- if ( myArea.contains( area ) )
- res = myArea[area]->isBorderEnabled();
- return res;
+ bool res = false;
+ if ( myArea.contains( area ) )
+ res = myArea[area]->isBorderEnabled();
+ return res;
}
/*!
- Name: setBorderEnabled [public]
- Desc: Show/hide border for specified button area. Border are
- line which separate main frame and control buttons.
-*/
+ \brief Show/hide border for the specified button area.
+
+ Border is a line which separate main frame and control buttons.
+ \param area buttons area (QtxDialog::ButtonArea)
+ \param on enable border flag
+ \sa isBorderEnabled()
+*/
void QtxDialog::setBorderEnabled( const bool on, const int area )
{
- if ( !myArea.contains( area ) )
- return;
+ if ( !myArea.contains( area ) )
+ return;
- if ( myArea[area]->isBorderEnabled() == on )
- return;
+ if ( myArea[area]->isBorderEnabled() == on )
+ return;
- myArea[area]->setBorderEnabled( on );
+ myArea[area]->setBorderEnabled( on );
- if ( isVisible() )
- {
- QApplication::sendPostedEvents();
- adjustSize();
- }
+ if ( isVisible() )
+ {
+ QApplication::sendPostedEvents();
+ adjustSize();
+ }
}
/*!
- Name: isButtonEnabled [public]
- Desc: Returns true if all specified button(s) is enabled.
+ \brief Get "enabled" status of the specified button(s).
+ \param id control button(s) ID (QtxDialog::ButtonFlags)
+ \return \c true if all specified buttons are enabled.
+ \sa setButtonEnabled()
*/
-
-bool QtxDialog::isButtonEnabled( const int f ) const
+bool QtxDialog::isButtonEnabled( const int id ) const
{
- ButtonMap map = buttons( f );
- bool result = !map.isEmpty();
- for ( ButtonMap::Iterator it = map.begin(); it != map.end(); ++it )
- result = result && it.data()->isEnabled();
- return result;
+ ButtonMap map = buttons( id );
+ bool result = !map.isEmpty();
+ for ( ButtonMap::Iterator it = map.begin(); it != map.end(); ++it )
+ result = result && it.value()->isEnabled();
+ return result;
}
/*!
- Name: setButtonEnabled [public]
- Desc: Enable/disable specified button(s).
+ \brief Enable/disable specified button(s).
+ \param on enable button(s) flag
+ \param id control button(s) ID (QtxDialog::ButtonFlags)
+ \sa isButtonEnabled()
*/
-
-void QtxDialog::setButtonEnabled( const bool on, const int ids )
+void QtxDialog::setButtonEnabled( const bool on, const int id )
{
- ButtonMap map = buttons( ids );
- for ( ButtonMap::Iterator it = map.begin(); it != map.end(); ++it )
- it.data()->setEnabled( on );
+ ButtonMap map = buttons( id );
+ for ( ButtonMap::Iterator it = map.begin(); it != map.end(); ++it )
+ it.value()->setEnabled( on );
}
/*!
- Name: hasButtonFocus [public]
- Desc: Retruns true if specified button has keyboard focus.
+ \brief Check if specified button has keyboard focus.
+ \param id control button ID (QtxDialog::ButtonFlags)
+ \return \c true if specified button has keyboard focus
+ \sa setButtonFocus()
*/
-
bool QtxDialog::hasButtonFocus( const int id ) const
{
- bool res = false;
- QButton* pb = button( id );
- if ( pb )
- res = pb->hasFocus();
- return res;
+ bool res = false;
+ QAbstractButton* pb = button( id );
+ if ( pb )
+ res = pb->hasFocus();
+ return res;
}
/*!
- Name: setButtonFocus [public]
- Desc: Sets the keyboard focus on specified button.
+ \brief Sets the keyboard focus to the specified button.
+ \param id control button ID (QtxDialog::ButtonFlags)
+ \sa hasButtonFocus()
*/
-
void QtxDialog::setButtonFocus( const int id )
{
- QButton* pb = button( id );
- if ( pb )
- pb->setFocus();
+ QAbstractButton* pb = button( id );
+ if ( pb )
+ pb->setFocus();
}
/*!
- Name: buttonText [public]
- Desc: Return text of specified button.
+ \brief Get specified button's text.
+ \param id control button ID (QtxDialog::ButtonFlags)
+ \return button's text
+ \sa setButtonText()
*/
-
QString QtxDialog::buttonText( const int id )
{
- QString retval;
- QButton* but = button( id );
- if ( but )
- retval = but->text();
- return retval;
+ QString retval;
+ QAbstractButton* but = button( id );
+ if ( but )
+ retval = but->text();
+ return retval;
}
/*!
- Name: setButtonText [public]
- Desc: Sets text to specified button.
+ \brief Set specified button's text.
+ \param id control button ID (QtxDialog::ButtonFlags)
+ \param text button's text
+ \sa buttonText()
*/
-
void QtxDialog::setButtonText( const int id, const QString& text )
{
- QButton* but = button( id );
- if ( but && but->text() != text )
- {
- but->setText( text );
- adjustButtons();
- }
-}
-
-/*!
- Name: setAlignment [public]
- Desc: Sets alignment policy. Returns the previous alignment.
- Use the function before the first show of the dialog.
- If dialog flag AlignOnce is setted then align will performed
- only one time otherwise dialog will be aligned every time
- when it shown. Dialog will be aligned relative to it parent.
-
- Following align flags may be used:
- Qtx::AlignAuto - Align to center of desktop (default).
- Qtx::AlignLeft - Align left side of dialog to left side of parent.
- Qtx::AlignRight - Align right side of dialog to right side of parent.
- Qtx::AlignTop - Align top side of dialog to top side of parent.
- Qtx::AlignBottom - Align bottom side of dialog to bottom side of parent.
- Qtx::AlignHCenter - Align dialog to center of parent in horizontal dimension.
- Qtx::AlignVCenter - Align dialog to center of parent in vertical dimension.
- Qtx::AlignCenter - Align dialog to center of parent in both dimensions.
- Qtx::AlignOutLeft - Align right side of dialog to left side of parent.
- Qtx::AlignOutRight - Align left side of dialog to right side of parent.
- Qtx::AlignOutTop - Align bottom side of dialog to top side of parent.
- Qtx::AlignOutBottom - Align top side of dialog to bottom side of parent.
-*/
+ QAbstractButton* but = button( id );
+ if ( but && but->text() != text )
+ {
+ but->setText( text );
+ adjustButtons();
+ }
+}
+/*!
+ \brief Sets alignment policy.
+
+ Use the function before the the dialog is first time shown.
+ If dialog flag AlignOnce is set then alignment is performed
+ only once, otherwise the dialog is aligned each time when it
+ is shown.
+ Dialog box is aligned relatively to its parent.
+ By default, dialog box is aligned to the center of the parent
+ widget (usually desktop or another dialog box).
+
+ \param align alignment flag(s) (Qtx::AlignmentFlags)
+ \return previous alignment policy
+*/
uint QtxDialog::setAlignment( uint align )
{
uint oldAlign = myAlignment;
}
/*!
- Name: update [virtual public slot]
- Desc: Updates dialog, show selected buttons and hide unselected.
+ \brief Update dialog box.
*/
-
void QtxDialog::update()
{
- for ( ButtonMap::Iterator it = myButton.begin(); it != myButton.end(); ++it )
- if ( it.key() >= 0 )
- testButtonFlags( it.key() ) ? it.data()->show() : it.data()->hide();
+ for ( ButtonMap::Iterator it = myButton.begin(); it != myButton.end(); ++it )
+ if ( it.key() >= 0 )
+ it.value()->setVisible( testButtonFlags( it.key() ) );
- for ( AreaMap::Iterator itr = myArea.begin(); itr != myArea.end(); ++itr )
- itr.data()->layoutButtons();
+ for ( AreaMap::Iterator itr = myArea.begin(); itr != myArea.end(); ++itr )
+ itr.value()->layoutButtons();
- adjustButtons();
+ adjustButtons();
- QDialog::update();
+ QDialog::update();
}
/*!
- Name: show [virtual public]
- Desc: Show dialog, set keyboard focus on dialog.
+ \brief Show/hide dialog box, set keyboard focus to the dialog.
+
+ Re-implemented from Qt.
+
+ \param on show/hide flag
*/
-
-void QtxDialog::show()
+void QtxDialog::setVisible( bool on )
{
- QDialog::show();
+ resize( sizeHint() );
- if ( testDialogFlags( SetFocus ) )
- setFocus();
+ QDialog::setVisible( on );
- myInited = true;
+ if ( on )
+ {
+ if ( testDialogFlags( SetFocus ) )
+ setFocus();
+ myInited = true;
+ }
+ else
+ QApplication::instance()->processEvents();
}
/*!
- Name: hide [virtual public]
- Desc: Hides dialog, processed all posted events.
+ \brief Get user button by the specified \a id.
+ \param id user button ID
+ \return user button or 0 if it is not found
+ \sa insertButton(), removeButton(), userButtonIds()
*/
-
-void QtxDialog::hide()
+QAbstractButton* QtxDialog::userButton( const int id ) const
{
- QDialog::hide();
- qApp->processEvents();
+ QAbstractButton* b = 0;
+ if ( id < -1 && myButton.contains( id ) )
+ b = myButton[id];
+ return b;
}
/*!
- Name: userButton [public]
- Desc: Return user dialog button using specified identificator.
+ \brief Get all user button IDs.
+ \return list of user buttons identificators
+ \sa insertButton(), removeButton(), userButton()
*/
-
-QButton* QtxDialog::userButton( const int id ) const
+QIntList QtxDialog::userButtonIds() const
{
- QButton* b = 0;
- if ( id < -1 && myButton.contains( id ) )
- b = myButton[id];
- return b;
+ QIntList retlist;
+ for ( ButtonMap::ConstIterator it = myButton.begin(); it != myButton.end(); ++it )
+ if ( it.key() < 0 )
+ retlist.append( it.key() );
+ return retlist;
}
/*!
- Name: userButtonIds [public]
- Desc: Return list of user dialog button identificators.
-*/
+ \brief Add user button to the dialog box.
-QValueList<int> QtxDialog::userButtonIds() const
-{
- QValueList<int> retlist;
- for ( ButtonMap::ConstIterator it = myButton.begin(); it != myButton.end(); ++it )
- if ( it.key() < 0 )
- retlist.append( it.key() );
- return retlist;
-}
+ The button is inserted to the specified dialog box area.
+ if the button is added successfully, the unique identificator of
+ the added button is returned, otherwise -1 is returned.
-/*!
- Name: insertButton [public]
- Desc: Add new user dialog button. Function return identificator of
- newly added button in successfull case otherwise -1 will be returned.
+ \param text text of the added button
+ \param area buttons area (QtxDialog::ButtonArea)
+ \return button ID
+ \sa removeButton(), userButton(), userButtonIds()
*/
-
int QtxDialog::insertButton( const QString& text, const int area )
{
- if ( !myArea.contains( area ) )
- return -1;
-
- int id = -2;
- while ( myButton.contains( id ) )
- id--;
+ if ( !myArea.contains( area ) )
+ return -1;
- Area* anArea = myArea[area];
- QButton* b = createButton( this );
- if ( b )
- {
- b->setText( text );
- myButton.insert( id, b );
- myPosition.insert( id, Left );
+ int id = -2;
+ while ( myButton.contains( id ) )
+ id--;
- connect( b, SIGNAL( clicked() ), this, SLOT( onButton() ) );
-#if QT_VER >= 3
- connect( b, SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
-#endif
+ Area* anArea = myArea[area];
+ QAbstractButton* b = createButton( this );
+ if ( b )
+ {
+ b->setText( text );
+ myButton.insert( id, b );
+ myPosition.insert( id, Left );
+
+ connect( b, SIGNAL( clicked() ), this, SLOT( onButton() ) );
+ connect( b, SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
- anArea->insertButton( b );
- update();
- }
- else
- id = -1;
+ anArea->insertButton( b );
+ update();
+ }
+ else
+ id = -1;
- return id;
+ return id;
}
/*!
- Name: removeButton [public]
- Desc: Remove user dialog button with specified identificator. If
- identificator equal -1 then method will remove all user dialog buttons.
-*/
+ \brief Remove user button.
+ If \c id is -1, all user buttons are removed.
+
+ \param id user button ID
+ \sa insertButton(), userButton(), userButtonIds()
+*/
void QtxDialog::removeButton( const int id )
{
- if ( id >= 0 )
- return;
-
- ButtonMap map;
- if ( id == -1 )
- {
- for ( ButtonMap::Iterator it = myButton.begin(); it != myButton.end(); ++it )
- {
- if ( it.key() < 0 )
- map.insert( it.key(), it.data() );
- }
- }
- else if ( myButton.contains( id ) )
- map.insert( id, myButton[id] );
-
- for ( ButtonMap::Iterator itr = map.begin(); itr != map.end(); ++itr )
- {
- for ( AreaMap::Iterator it = myArea.begin(); it != myArea.end(); ++it )
- it.data()->removeButton( itr.data() );
-
- myButton.remove( itr.key() );
- myPosition.remove( itr.key() );
-
- delete itr.data();
- }
- update();
+ if ( id >= 0 )
+ return;
+
+ ButtonMap map;
+ if ( id == -1 )
+ {
+ for ( ButtonMap::Iterator it = myButton.begin(); it != myButton.end(); ++it )
+ {
+ if ( it.key() < 0 )
+ map.insert( it.key(), it.value() );
+ }
+ }
+ else if ( myButton.contains( id ) )
+ map.insert( id, myButton[id] );
+
+ for ( ButtonMap::Iterator itr = map.begin(); itr != map.end(); ++itr )
+ {
+ for ( AreaMap::Iterator it = myArea.begin(); it != myArea.end(); ++it )
+ it.value()->removeButton( itr.value() );
+
+ myButton.remove( itr.key() );
+ myPosition.remove( itr.key() );
+
+ delete itr.value();
+ }
+ update();
}
/*!
- Name: setUnits [static public]
- Desc: Sets specified measure units in given label. Measure units close
- in braces. If measure units not exist then they will be added.
- For example:
- 1. Label contains text 'Radius'.
- setUnits( aLabel, "mm" ) => aLabel contains 'Radius (mm)'
- setUnits( aLabel, "cm" ) => aLabel contains 'Radius (cm)'
- 2. Label "aLabel" contains text 'Radius ():'.
- setUnits( aLabel, "mm" ) => aLabel contains 'Radius (mm):'
- setUnits( aLabel, "cm" ) => aLabel contains 'Radius (cm):'
-*/
+ \brief Set measure units to the specified label.
+
+ In the dialog box label the measure units are closed in braces.
+ If measure units do not exist they will be added.
+
+ For example:
+ \code
+ // create label "Radius"
+ QLabel* aLabel = new QLabel( "Radius", mainFrame() );
+ // set measure units to "mm"
+ setUnits( aLabel, "mm" ) // => aLabel contains 'Radius (mm)'
+ // set measure units to "cm"
+ setUnits( aLabel, "cm" ) // => aLabel contains 'Radius (cm)'
+
+ // create label "Radius" with initially not set measure units
+ QLabel* aLabel = new QLabel( "Radius ():", mainFrame() );
+ // set measure units to "mm"
+ setUnits( aLabel, "mm" ) // => aLabel contains 'Radius (mm):'
+ // set measure units to "cm"
+ setUnits( aLabel, "cm" ) // => aLabel contains 'Radius (cm):'
+ \endcode
+ \param aLabel label widget
+ \param aUnits measure units
+*/
void QtxDialog::setUnits( QLabel* aLabel, const QString& aUnits )
{
- QString label = aLabel->text();
- int begin;
- int end = label.findRev( ')' );
-
- QString startLabel = label;
- QString finalLabel;
-
- if ( end != -1 )
- {
- begin = label.left( end ).findRev( '(' );
- if ( begin != -1 )
- {
- startLabel = label.mid( 0, begin );
- finalLabel = label.mid( end + 1 );
- }
- }
- else
- {
- startLabel = startLabel.stripWhiteSpace();
- if ( startLabel.at( startLabel.length() - 1 ) == ':' )
- {
- finalLabel = startLabel.mid( startLabel.length() - 1 );
- startLabel = startLabel.mid( 0, startLabel.length() - 1 );
- }
- }
- if ( aUnits.length() )
- label = startLabel.stripWhiteSpace() +
- " (" + aUnits + ") " + finalLabel.stripWhiteSpace();
- else
- label = startLabel.stripWhiteSpace() +
- " " + finalLabel.stripWhiteSpace();
- aLabel->setText( label );
-}
-
-/*!
- Name: acceptData [virtual protected]
- Desc: If returns true dialog will be accepted and closed. This method
- called if dialog flag Accept is setted.
-*/
+ QString label = aLabel->text();
+
+ int begin;
+ int end = label.lastIndexOf( ')' );
+
+ QString startLabel = label;
+ QString finalLabel;
+ if ( end != -1 )
+ {
+ begin = label.left( end ).lastIndexOf( '(' );
+ if ( begin != -1 )
+ {
+ startLabel = label.mid( 0, begin );
+ finalLabel = label.mid( end + 1 );
+ }
+ }
+ else
+ {
+ startLabel = startLabel.trimmed();
+ if ( startLabel.at( startLabel.length() - 1 ) == ':' )
+ {
+ finalLabel = startLabel.mid( startLabel.length() - 1 );
+ startLabel = startLabel.mid( 0, startLabel.length() - 1 );
+ }
+ }
+ if ( aUnits.length() )
+ label = startLabel.trimmed() + " (" + aUnits + ") " + finalLabel.trimmed();
+ else
+ label = startLabel.trimmed() + " " + finalLabel.trimmed();
+ aLabel->setText( label );
+}
+
+/*!
+ \brief Check if data entered by the user is valid.
+
+ This method can be re-implemented in the successor class if it
+ requires to check user input consistency.
+ Default implementation returns \c true.
+
+ This method is called if dialog flag QtxDialog::Accept is set.
+ If this method returns \c true, then dialog will be accepted and closed.
+
+ \return \c true if user input is valid
+ \sa accept()
+*/
bool QtxDialog::acceptData() const
{
return true;
}
/*!
- Name: rejectData [virtual protected]
- Desc: If returns true dialog will be rejected and closed. This method
- called if dialog flag Reject is setted.
-*/
+ \brief Check if dialog box can be cancelled.
+ This method can be re-implemented in the successor class if it
+ requires to check possibility to cancel dialog box safely.
+ Default implementation returns \c true.
+
+ This method is called if dialog flag QtxDialog::Reject is set.
+ If this method returns \c true, then dialog will be rejected and closed.
+
+ \return \c true if dialog box can be cancelled
+ \sa reject()
+*/
bool QtxDialog::rejectData() const
{
- return true;
+ return true;
}
/*!
- Name: createButton [virtual protected]
- Desc: Create new user button. Invoked from method "insertButton".
-*/
+ \brief Create new user button.
-QButton* QtxDialog::createButton( QWidget* parent )
+ This method is invoked from method insertButton().
+
+ \param parent parent widget
+ \return new user button
+*/
+QAbstractButton* QtxDialog::createButton( QWidget* parent )
{
- QPushButton* pb = new QPushButton( parent );
- pb->setAutoDefault( false );
- return pb;
+ QPushButton* pb = new QPushButton( parent );
+ pb->setAutoDefault( false );
+ return pb;
}
/*!
- Name: button [protected]
- Desc: Return pointer on control button specified by identifier.
- If identifier is wrong then null pointer will returned.
+ \brief Get button by the specified ID.
+ \param f control button ID (QtxDialog::ButtonFlags)
+ \return button or 0 if \a id is invalid
*/
-
-QButton* QtxDialog::button( const int f ) const
+QAbstractButton* QtxDialog::button( const int f ) const
{
- QButton* retval = 0;
- if ( myButton.contains( f ) )
- retval = myButton[f];
- return retval;
+ QAbstractButton* retval = 0;
+ if ( myButton.contains( f ) )
+ retval = myButton[f];
+ return retval;
}
/*!
- Name: buttons [protected]
- Desc: Return map with control dialog buttons accordance to given button flags.
+ \brief Get buttons by the specified IDs.
+ \param f control button(s) ID(s) (QtxDialog::ButtonFlags)
+ \return button map
*/
-
QtxDialog::ButtonMap QtxDialog::buttons( const int f ) const
{
- ButtonMap retmap;
- if ( f < -1 )
- {
- if ( myButton.contains( f ) )
- retmap.insert( f, myButton[f] );
- }
- else
- {
- for ( ButtonMap::ConstIterator it = myButton.begin(); it != myButton.end(); ++it )
- if ( f == -1 || ( it.key() >= 0 && f & it.key() ) )
- retmap.insert( it.key(), it.data() );
- }
-
- return retmap;
+ ButtonMap retmap;
+ if ( f < -1 )
+ {
+ if ( myButton.contains( f ) )
+ retmap.insert( f, myButton[f] );
+ }
+ else
+ {
+ for ( ButtonMap::ConstIterator it = myButton.begin(); it != myButton.end(); ++it )
+ if ( f == -1 || ( it.key() >= 0 && f & it.key() ) )
+ retmap.insert( it.key(), it.value() );
+ }
+ return retmap;
}
/*!
- Name: buttonId [protected]
- Desc: Return identifier of specified button.
+ \brief Get specified button's identifier.
+ \param b button
+ \return button ID
*/
-
-int QtxDialog::buttonId( const QButton* b ) const
+int QtxDialog::buttonId( const QAbstractButton* b ) const
{
- int id = -1;
- for ( ButtonMap::ConstIterator it = myButton.begin(); it != myButton.end() && id == -1; ++it )
- if ( it.data() == b )
- id = it.key();
- return id;
+ int id = -1;
+ for ( ButtonMap::ConstIterator it = myButton.begin(); it != myButton.end() && id == -1; ++it )
+ if ( it.value() == b )
+ id = it.key();
+ return id;
}
/*!
- Name: buttonPosition
- Desc: Returns position of specified button. [protected]
+ \brief Get position of specified button.
+ \param b button
+ \return button position (QtxDialog::ButtonPosition)
*/
-
-int QtxDialog::buttonPosition( QButton* b ) const
+int QtxDialog::buttonPosition( QAbstractButton* b ) const
{
- return buttonPosition( buttonId( b ) );
+ return buttonPosition( buttonId( b ) );
}
/*!
- Name: showEvent [virtual protected]
- Desc: Aligns this dialog according the parent widget and alignment
- policy before the show.
-*/
+ \brief Align this dialog according to the parent widget and alignment
+ policy before the dialog box is shown.
+
+ Re-implemented from Qt.
+ \param e show event
+*/
void QtxDialog::showEvent( QShowEvent* e )
{
- if ( !testDialogFlags( AlignOnce ) || !myInited )
- Qtx::alignWidget( this, parentWidget(), myAlignment );
- QDialog::showEvent( e );
+ if ( !testDialogFlags( AlignOnce ) || !myInited )
+ Qtx::alignWidget( this, parentWidget(), myAlignment );
+ QDialog::showEvent( e );
}
/*!
- Name: hideEvent [virtual protected]
- Desc: Process all existing events when dialog is closed.
-*/
+ \brief Process all existing events when dialog box is hidden.
+ Re-implemented from Qt.
+
+ \param e hide event
+*/
void QtxDialog::hideEvent( QHideEvent* e )
{
- qApp->processEvents();
- QDialog::hideEvent( e );
+ QApplication::instance()->processEvents();
+ QDialog::hideEvent( e );
}
/*!
- Name: childEvent [virtual protected]
- Desc: Setting up layout when size grip is added.
-*/
+ \brief Update dialog box layout when the size grip is added.
+
+ Re-implemented from Qt.
+ \param e child event
+*/
void QtxDialog::childEvent( QChildEvent* e )
{
- QDialog::childEvent( e );
- if ( layout() && e->inserted() && e->child()->inherits( "QSizeGrip" ) )
- {
- layout()->setMargin( 12 );
-#if QT_VER >= 3
- connect( e->child(), SIGNAL( destroyed() ), this, SLOT( onSizeGripDestroyed() ) );
-#endif
- }
+ QDialog::childEvent( e );
+ if ( layout() && e->added() && e->child()->inherits( "QSizeGrip" ) )
+ {
+ layout()->setMargin( 12 );
+ connect( e->child(), SIGNAL( destroyed() ), this, SLOT( onSizeGripDestroyed() ) );
+ }
}
/*!
- Name: keyPressEvent [virtual protected]
- Desc: Calls reject() if key Escape is pressed.
- Calls accept() if key "Ctrl+Enter" is pressed.
- Process key "F1" and emit signal dlgHelp().
- Transfer key "Ctrl+(Shift+)Tab" press event to Tab Widget.
-*/
+ \brief Process key pressing event.
+
+ Re-implemented from Qt.
+ Call reject() if "Escape" key is pressed.
+ Call accept() if "Ctrl+Enter" key-sequence is pressed.
+ Process "F1" key and emit signal dlgHelp().
+ Transfer "Ctrl+(Shift+)Tab" key-sequence press event
+ to the child Tab widget (if there is any).
+
+ \param e key press event
+*/
void QtxDialog::keyPressEvent( QKeyEvent* e )
{
- QDialog::keyPressEvent( e );
- if ( e->isAccepted() )
- return;
+ QDialog::keyPressEvent( e );
- if ( ( e->state() == 0 ) && ( e->key() == Key_Escape ) )
- reject();
+ if ( e->isAccepted() )
+ return;
- if ( ( e->state() == ControlButton ) && ( e->key() == Key_Return ) )
- {
- if ( testButtonFlags( OK ) || testButtonFlags( Yes ) )
- accept();
- else if ( testButtonFlags( Apply ) && isButtonEnabled( Apply ) )
- emit dlgApply();
- e->accept();
- }
+ if ( !e->modifiers() && e->key() == Qt::Key_Escape )
+ reject();
- if ( e->key() == Key_F1 && testButtonFlags( Help ) && isButtonEnabled( Help ) )
- {
- e->accept();
- emit dlgHelp();
- }
+ if ( e->modifiers() == Qt::ControlModifier && e->key() == Qt::Key_Return )
+ {
+ if ( testButtonFlags( OK ) || testButtonFlags( Yes ) )
+ accept();
+ else if ( testButtonFlags( Apply ) && isButtonEnabled( Apply ) )
+ emit dlgApply();
+ e->accept();
+ }
+
+ if ( e->key() == Qt::Key_F1 && testButtonFlags( Help ) && isButtonEnabled( Help ) )
+ {
+ e->accept();
+ emit dlgHelp();
+ }
- if ( ( e->key() == Key_Tab ) && ( e->state() & ControlButton ) )
- {
- QObject* tab = child( 0, "QTabWidget" );
- if ( tab )
- tab->event( e );
- }
+ if ( e->key() == Qt::Key_Tab && e->modifiers() & Qt::ControlModifier )
+ {
+ QObject* tab = qFindChild<QTabWidget*>( this );
+ if ( tab )
+ QApplication::sendEvent( tab, e );
+ }
}
/*!
- Name: closeEvent [virtual protected]
- Desc: Reject the dialog.
+ \brief Called when user closes dialog box.
+
+ Call reject() method.
+
+ \param e close event (not used)
*/
-
-void QtxDialog::closeEvent( QCloseEvent* )
+void QtxDialog::closeEvent( QCloseEvent* /*e*/ )
{
- reject();
+ reject();
}
/*!
- Name: accept [virtual protected slot]
- Desc: Invoke function acceptData() if it needed and if acceptData() return
- false does nothing. Otherwise hides the dialog and sets the result code
- to Accepted. Emit signal according to the pressed control button.
-*/
+ \brief Accept the dialog box.
+
+ This method is used when any accept button is pressed (usually
+ "OK", "Yes", etc).
+
+ If dialog flag QtxDialog::Accept is set, this function invokes
+ acceptData() method, which should in this case return \c true to
+ allow further processing.
+
+ If acceptData() returns \c false, this function just returns.
+ If acceptData() returns \c true, the Accepted result is set
+ and signal according to the pressed control button is emitted.
+ Then the default implementation of accept() method is called
+ (which hides the dialog box and, depending on the dialog box flags,
+ can close and destroy it).
+
+ \sa acceptData()
+*/
void QtxDialog::accept()
{
- if ( !mySender )
- {
- if ( testButtonFlags( OK ) )
- mySender = button( OK );
- else if ( testButtonFlags( Yes ) )
- mySender = button( Yes );
- else
- mySender = button( Close );
- }
+ if ( !mySender )
+ {
+ if ( testButtonFlags( OK ) )
+ mySender = button( OK );
+ else if ( testButtonFlags( Yes ) )
+ mySender = button( Yes );
+ else
+ mySender = button( Close );
+ }
if ( !mySender || !mySender->isWidgetType() ||
!((QWidget*)mySender)->isEnabled() )
- return;
+ return;
- if ( testDialogFlags( Accept ) && !acceptData() )
- return;
+ if ( testDialogFlags( Accept ) && !acceptData() )
+ return;
- QDialog::accept();
+ QDialog::accept();
- emitSignal();
+ emitSignal();
}
/*!
- Name: reject [virtual protected slot]
- Desc: Invoke function rejectData() if it needed and if rejectData() return
- false does nothing. Otherwise hides the dialog and sets the result code
- to Rejected. Emit signal according to the pressed control button. (If
- dialog was closed by key Escape or by close event emit signal dlgCancel(),
- or dlgClose(), or dlgNo().
-*/
+ \brief Reject the dialog box.
+
+ This method is used when any reject button is pressed (usually
+ "Close", "Cancel", "No", etc).
+
+ If dialog flag QtxDialog::Reject is set, this function invokes
+ rejectData() method, which should in this case return \c true to
+ allow further processing.
+
+ If rejectData() returns \c false, this function just returns.
+ If rejectData() returns \c true, the Rejected result is set
+ and signal according to the pressed control button is emitted.
+ Then the default implementation of reject() method is called
+ (which hides the dialog box and, depending on the dialog box flags,
+ can close and destroy it).
+
+ \sa rejectData()
+*/
void QtxDialog::reject()
{
- if ( testDialogFlags( Reject ) && !rejectData() )
- return;
+ if ( testDialogFlags( Reject ) && !rejectData() )
+ return;
- if ( !mySender )
- {
- if ( testButtonFlags( Cancel ) )
- mySender = button( Cancel );
- else if ( testButtonFlags( No ) )
- mySender = button( No );
- else
- mySender = button( Close );
- }
+ if ( !mySender )
+ {
+ if ( testButtonFlags( Cancel ) )
+ mySender = button( Cancel );
+ else if ( testButtonFlags( No ) )
+ mySender = button( No );
+ else
+ mySender = button( Close );
+ }
- if ( !mySender || !mySender->isWidgetType() ||
- !((QWidget*)mySender)->isEnabled() )
- return;
+ if ( !mySender || !mySender->isWidgetType() ||
+ !((QWidget*)mySender)->isEnabled() )
+ return;
- QDialog::reject();
+ QDialog::reject();
- emitSignal();
+ emitSignal();
}
/*!
- Name: reject [private]
- Desc: Emit signal appropriate to control button.
+ \brief Emit signal correspondingly to the control button.
*/
-
void QtxDialog::emitSignal()
{
- qApp->processEvents();
- QApplication::syncX();
+ QApplication::instance()->processEvents();
+ QApplication::syncX();
- int id = buttonId( (QButton*)mySender );
- mySender = 0;
+ int id = buttonId( (QAbstractButton*)mySender );
+ mySender = 0;
- switch ( id )
- {
- case OK:
- emit dlgOk();
- break;
- case Cancel:
- emit dlgCancel();
- break;
- case Close:
- emit dlgClose();
- break;
- case Yes:
- emit dlgYes();
- break;
- case No:
- emit dlgNo();
- break;
- }
+ switch ( id )
+ {
+ case OK:
+ emit dlgOk();
+ break;
+ case Cancel:
+ emit dlgCancel();
+ break;
+ case Close:
+ emit dlgClose();
+ break;
+ case Yes:
+ emit dlgYes();
+ break;
+ case No:
+ emit dlgNo();
+ break;
+ }
}
/*!
- Name: onAccept [private slot]
- Desc: Process signals "clicked()" from control buttons "OK", "Yes". Invoke accept().
-*/
+ \brief This slot is called when user presses on of the buttons
+ "OK", "Yes", etc.
+ Call accept() method.
+*/
void QtxDialog::onAccept()
{
- const QObject* obj = sender();
- mySender = obj;
- accept();
+ const QObject* obj = sender();
+ mySender = obj;
+ accept();
}
/*!
- Name: onReject [private slot]
- Desc: Process signals "clicked()" from control buttons "Cancel", "No", "Close".
- Invoke reject().
+ \brief This slot is called when user presses on of the buttons
+ "Cancel", "No", "Close".
+
+ Call reject() method.
*/
void QtxDialog::onReject()
}
/*!
- Name: onButton [private slot]
- Desc: Receive signal "clicked()" from user buttons and emit signal
- "dlgButton( int )" with identificator of clicked user button.
+ \brief Process user button click event.
+
+ This method is called when user presses one of custom user buttons.
+ Emits signal dlgButton(int) with identificator of the clicked user
+ button passed as parameter.
*/
-
void QtxDialog::onButton()
{
- int id = buttonId( (QButton*)sender() );
- if ( id != -1 )
- emit dlgButton( id );
+ int id = buttonId( (QAbstractButton*)sender() );
+ if ( id != -1 )
+ emit dlgButton( id );
}
/*!
- Name: onDestroyed [private slot]
- Desc: Remove user button if it was destroyed.
+ \brief Watch for the user button destroying.
+ \param obj button being destroyed
*/
-
void QtxDialog::onDestroyed( QObject* obj )
{
- QButton* b = (QButton*)obj;
- int id = buttonId( b );
- if ( id == -1 )
- return;
+ QAbstractButton* b = (QAbstractButton*)obj;
+ int id = buttonId( b );
+ if ( id == -1 )
+ return;
- myButton.remove( id );
- myPosition.remove( id );
- for ( AreaMap::Iterator it = myArea.begin(); it != myArea.end(); ++it )
- it.data()->removeButton( b );
+ myButton.remove( id );
+ myPosition.remove( id );
+ for ( AreaMap::Iterator it = myArea.begin(); it != myArea.end(); ++it )
+ it.value()->removeButton( b );
}
/*!
- Name: onSizeGripDestroyed [private slot]
- Desc: Setting up layout when size grip is destroyed.
+ \brief Update dialog box layout when the size grip is destroyed.
*/
-
void QtxDialog::onSizeGripDestroyed()
{
- if ( layout() )
- layout()->setMargin( 5 );
+ if ( layout() )
+ layout()->setMargin( 5 );
}
/*!
- Name: adjustButtons [private]
- Desc: Setting the equal with for all buttons.
+ \brief Adjust buttons (set equal size for all buttons).
*/
-
void QtxDialog::adjustButtons()
{
- int minWidth = 0;
- for ( AreaMap::Iterator aIt = myArea.begin(); aIt != myArea.end(); ++aIt )
- for ( QPtrListIterator<QButton> bIt( aIt.data()->buttons() ); bIt.current(); ++bIt )
- if ( bIt.current()->isVisibleTo( this ) )
- minWidth = QMAX( minWidth, bIt.current()->sizeHint().width() );
+ int minWidth = 0;
+ for ( AreaMap::Iterator aIt = myArea.begin(); aIt != myArea.end(); ++aIt )
+ {
+ const QList<QAbstractButton*>& lst = aIt.value()->buttons();
+ for ( QList<QAbstractButton*>::const_iterator bIt = lst.begin(); bIt != lst.end(); ++bIt )
+ if ( (*bIt)->isVisibleTo( this ) )
+ minWidth = qMax( minWidth, (*bIt)->sizeHint().width() );
+ }
- for ( AreaMap::Iterator aItr = myArea.begin(); aItr != myArea.end(); ++aItr )
- for ( QPtrListIterator<QButton> bItr( aItr.data()->buttons() ); bItr.current(); ++bItr )
- if ( bItr.current()->isVisibleTo( this ) )
- bItr.current()->setMinimumWidth( minWidth );
+ for ( AreaMap::Iterator aItr = myArea.begin(); aItr != myArea.end(); ++aItr )
+ {
+ const QList<QAbstractButton*>& lst = aItr.value()->buttons();
+ for ( QList<QAbstractButton*>::const_iterator bItr = lst.begin(); bItr != lst.end(); ++bItr )
+ if ( (*bItr)->isVisibleTo( this ) )
+ (*bItr)->setMinimumWidth( minWidth );
+ }
}
+
+/*!
+ \fn void QtxDialog::dlgButton( int id )
+ \brief Emitted when the user button is clicked.
+ \param id user button identificator
+*/
+/*!
+ \fn void QtxDialog::dlgParamChanged()
+ \brief This signal can be used in successor classes to signalize about
+ some dialog parameter changing.
+*/
+/*!
+ \fn void QtxDialog::dlgHelp()
+ \brief Emitted when the "Help" button is clicked.
+*/
+/*!
+ \fn void QtxDialog::dlgApply()
+ \brief Emitted when the "Apply" button is clicked.
+*/
+/*!
+ \fn void QtxDialog::dlgOk()
+ \brief Emitted when the "OK" button is clicked.
+*/
+/*!
+ \fn void QtxDialog::dlgNo()
+ \brief Emitted when the "No" button is clicked.
+*/
+/*!
+ \fn void QtxDialog::dlgYes()
+ \brief Emitted when the "Yes" button is clicked.
+*/
+/*!
+ \fn void QtxDialog::dlgClose()
+ \brief Emitted when the "Close" button is clicked.
+*/
+/*!
+ \fn void QtxDialog::dlgCancel()
+ \brief Emitted when the "Cancel" button is clicked.
+*/
// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
+//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
+// License as published by the Free Software Foundation; either
// version 2.1 of the License.
-//
-// This library 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
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#include "Qtx.h"
-#include <qmap.h>
-#include <qdialog.h>
-#include <qvaluelist.h>
+#include <QDialog>
+#include <QMap>
class QFrame;
class QLabel;
-class QButton;
+class QAbstractButton;
#ifdef WIN32
#pragma warning( disable:4251 )
class QTX_EXPORT QtxDialog : public QDialog
{
- Q_OBJECT
+ Q_OBJECT
- class Area;
- class Border;
+ class Area;
+ class Border;
public:
- typedef enum { Position, Expand, Uniform } PlacePolicy;
- typedef enum { TopArea, BottomArea, LeftArea, RightArea } ButtonArea;
- typedef enum { Left, Right, Center, Top = Left, Bottom = Right } ButtonPosition;
-
- typedef enum { None = 0x00000000,
- OK = 0x00000001,
- Apply = 0x00000002,
- Cancel = 0x00000004,
- Yes = 0x00000008,
- No = 0x00000010,
- Close = 0x00000020,
- Help = 0x00000040,
- OKCancel = OK | Cancel,
- YesNo = Yes | No,
- Standard = OK | Cancel | Help,
- All = Standard | YesNo | Apply | Close } ButtonFlags;
-
- typedef enum { Accept = 0x000001,
- Reject = 0x000002,
- AlignOnce = 0x000004,
- SetFocus = 0x000008 } DialogFlags;
-
+ //! Buttons alignment type
+ typedef enum { Position, //!< buttons are placed according their position
+ Expand, //!< buttons occupy all available space
+ Uniform //!< buttons are uniformly placed in the area
+ } PlacePolicy;
+ //! Buttons area
+ typedef enum { TopArea, //!< horizontal area at the top side of the dialog box
+ BottomArea, //!< horizontal area at the bottom side of the dialog box
+ LeftArea, //!< vertical area at the left side of the dialog box
+ RightArea //!< vertical area at the right side of the dialog box
+ } ButtonArea;
+ //! Button position
+ typedef enum { Left, //!< set button left-most
+ Right, //!< set button right-most
+ Center, //!< place button in the center
+ Top = Left, //!< set button top-most
+ Bottom = Right //!< set button bottom-most
+ } ButtonPosition;
+ //! Button ID flags
+ typedef enum { None = 0x00000000, //!< no button used
+ OK = 0x00000001, //!< OK button
+ Apply = 0x00000002, //!< Apply button
+ Cancel = 0x00000004, //!< Cancel button
+ Yes = 0x00000008, //!< Yes button
+ No = 0x00000010, //!< No button
+ Close = 0x00000020, //!< Close button
+ Help = 0x00000040, //!< Help button
+ OKCancel = OK | Cancel, //!< OK & Cancel button
+ YesNo = Yes | No, //!< Yes & No buttons
+ Standard = OK | Cancel | Help, //!< OK, Cancel & Help buttons
+ All = Standard | YesNo | Apply | Close //!< all buttons
+ } ButtonFlags;
+ //! Dialog box flags
+ typedef enum { Accept = 0x000001, //!< allow dialog box accepting control
+ Reject = 0x000002, //!< allow dialog box rejecting control
+ AlignOnce = 0x000004, //!< align dialog box only when it is first time shown
+ SetFocus = 0x000008 //!< allow to set focus on dialog box when it is shown (user can use setFocusProxy() and specify own initial focus widget)
+ } DialogFlags;
+
public:
- QtxDialog( QWidget* = 0, const char* = 0, bool = false,
- bool = false, const int = Standard, WFlags = 0 );
- virtual ~QtxDialog();
-
- void setDialogFlags( const int );
- void clearDialogFlags( const int );
- bool testDialogFlags( const int ) const;
-
- void setButtonFlags( const int );
- void clearButtonFlags( const int );
- bool testButtonFlags( const int ) const;
-
- int buttonPosition( const int ) const;
- void setButtonPosition( const int, const int = -1 );
- void setPlacePosition( const int, const int );
-
- int placePolicy( const int ) const;
- void setPlacePolicy( const int, const int );
- void setButtonPlace( const int, const int );
-
- QString buttonText( const int );
- void setButtonText( const int, const QString& text );
-
- void setButtonFocus( const int );
- bool hasButtonFocus( const int ) const;
-
- bool isButtonEnabled( const int ) const;
- void setButtonEnabled( const bool, const int );
-
- bool isBorderEnabled( const int ) const;
- void setBorderEnabled( const bool, const int );
-
- void removeButton( const int );
- int insertButton( const QString&, const int = BottomArea );
-
- QValueList<int> userButtonIds() const;
- QButton* userButton( const int ) const;
-
- virtual void show();
- virtual void hide();
-
- uint setAlignment( uint align );
- static void setUnits( QLabel*, const QString& );
-
+ QtxDialog( QWidget* = 0, bool = false, bool = false, const int = Standard, Qt::WindowFlags = 0 );
+ virtual ~QtxDialog();
+
+ void setDialogFlags( const int );
+ void clearDialogFlags( const int );
+ bool testDialogFlags( const int ) const;
+
+ void setButtonFlags( const int );
+ void clearButtonFlags( const int );
+ bool testButtonFlags( const int ) const;
+
+ int buttonPosition( const int ) const;
+ void setButtonPosition( const int, const int = -1 );
+ void setPlacePosition( const int, const int );
+
+ int placePolicy( const int ) const;
+ void setPlacePolicy( const int, const int );
+ void setButtonPlace( const int, const int );
+
+ QString buttonText( const int );
+ void setButtonText( const int, const QString& text );
+
+ void setButtonFocus( const int );
+ bool hasButtonFocus( const int ) const;
+
+ bool isButtonEnabled( const int ) const;
+ void setButtonEnabled( const bool, const int );
+
+ bool isBorderEnabled( const int ) const;
+ void setBorderEnabled( const bool, const int );
+
+ void removeButton( const int );
+ int insertButton( const QString&, const int = BottomArea );
+
+ QIntList userButtonIds() const;
+ QAbstractButton* userButton( const int ) const;
+
+ uint setAlignment( uint align );
+ static void setUnits( QLabel*, const QString& );
+
signals:
- void dlgButton( int );
- void dlgParamChanged();
-
- void dlgHelp();
- void dlgApply();
-
- void dlgOk();
- void dlgNo();
- void dlgYes();
- void dlgClose();
- void dlgCancel();
-
+ void dlgButton( int );
+ void dlgParamChanged();
+
+ void dlgHelp();
+ void dlgApply();
+
+ void dlgOk();
+ void dlgNo();
+ void dlgYes();
+ void dlgClose();
+ void dlgCancel();
+
public slots:
- void update();
+ void update();
+ virtual void setVisible( bool );
protected slots:
- virtual void accept();
- virtual void reject();
+ virtual void accept();
+ virtual void reject();
private slots:
- void onAccept();
- void onReject();
- void onButton();
- void onSizeGripDestroyed();
- void onDestroyed( QObject* );
+ void onAccept();
+ void onReject();
+ void onButton();
+ void onSizeGripDestroyed();
+ void onDestroyed( QObject* );
protected:
- typedef QMap<int, QButton*> ButtonMap;
+ typedef QMap<int, QAbstractButton*> ButtonMap; //!< button map
protected:
- QFrame* mainFrame() const;
-
- virtual bool acceptData() const;
- virtual bool rejectData() const;
-
- virtual QButton* createButton( QWidget* );
-
- QButton* button( const int ) const;
- ButtonMap buttons( const int = All ) const;
- int buttonId( const QButton* ) const;
- int buttonPosition( QButton* ) const;
-
- virtual void showEvent( QShowEvent* );
- virtual void hideEvent( QHideEvent* );
- virtual void closeEvent( QCloseEvent* );
- virtual void childEvent( QChildEvent* );
- virtual void keyPressEvent( QKeyEvent* );
-
+ QFrame* mainFrame() const;
+
+ virtual bool acceptData() const;
+ virtual bool rejectData() const;
+
+ virtual QAbstractButton* createButton( QWidget* );
+
+ QAbstractButton* button( const int ) const;
+ ButtonMap buttons( const int = All ) const;
+ int buttonId( const QAbstractButton* ) const;
+ int buttonPosition( QAbstractButton* ) const;
+
+ virtual void showEvent( QShowEvent* );
+ virtual void hideEvent( QHideEvent* );
+ virtual void closeEvent( QCloseEvent* );
+ virtual void childEvent( QChildEvent* );
+ virtual void keyPressEvent( QKeyEvent* );
+
private:
- void adjustButtons();
- void emitSignal();
-
+ void adjustButtons();
+ void emitSignal();
+
private:
- typedef QMap<int, Area*> AreaMap;
- typedef QMap<int, int> PositionMap;
-
- friend class Area;
+ typedef QMap<int, Area*> AreaMap; //!< button area map
+ typedef QMap<int, int> PositionMap; //!< button position map
+
+ friend class Area;
private:
- AreaMap myArea;
- ButtonMap myButton;
- PositionMap myPosition;
-
- bool myInited;
- const QObject* mySender;
- uint myAlignment;
- QFrame* myMainFrame;
- int myButtonFlags;
- int myDialogFlags;
+ AreaMap myArea; //!< buttons areas map
+ ButtonMap myButton; //!< buttons map
+ PositionMap myPosition; //!< buttons position map
+
+ bool myInited; //!< dialog's "initialized" flag
+ const QObject* mySender; //!< signal sender
+ uint myAlignment; //!< dialog box alignment type
+ QFrame* myMainFrame; //!< main frame
+ int myButtonFlags; //!< button flags
+ int myDialogFlags; //!< dialog flags
};
#ifdef WIN32
{
QString dirPath = QFileInfo( myEdit->text().stripWhiteSpace() ).filePath();
/*
-#ifndef WNT
+#ifndef WIN32
if ( dirPath.startsWith( "~") ) {
dirPath = dirPath.remove(0,1);
QString user;
/*!
* \brief The GUI implementation of the directory list
*/
-class QTX_EXPORT QtxDirListEditor : public QWidget {
+class QTX_EXPORT QtxDirListEditor : public QWidget
+{
Q_OBJECT
#include "QtxDockAction.h"
-#include "QtxResourceMgr.h"
-
-#include <qevent.h>
-#include <qtoolbar.h>
-#include <qdockarea.h>
-#include <qdockwindow.h>
-#include <qmainwindow.h>
-#include <qobjectlist.h>
-#include <qapplication.h>
-
-/*!
- Name: QtxDockAction [public]
- Desc: Constructs an Dock action with given main window and name.
-*/
-
-QtxDockAction::QtxDockAction( QMainWindow* mw, const char* name )
-: QtxAction( "Windows and Toolbars", "Windows and Toolbars", 0, mw, name ),
-myMain( mw ),
-myAutoAdd( true ),
-mySeparate( true ),
-myAutoPlace( false )
-{
- initialize( mw );
-}
-
-/*!
- Name: QtxDockAction [public]
- Desc: This constructor creates an action with the following properties: the
- description text, the menu text and. It is a child of given main window
- and named specified name.
-*/
-
-QtxDockAction::QtxDockAction( const QString& text, const QString& menuText, QMainWindow* mw, const char* name )
-: QtxAction( text, menuText, 0, mw, name ),
-myMain( mw ),
-myAutoAdd( true ),
-mySeparate( true ),
-myAutoPlace( false )
-{
- initialize( mw );
-}
-
-/*!
- Name: QtxDockAction [public]
- Desc: This constructor creates an action with the following properties: the
- description text, the menu text, the icon or iconset icon and keyboard
- accelerator. It is a child of given main window and named specified name.
-*/
-
-QtxDockAction::QtxDockAction( const QString& text, const QIconSet& icon, const QString& menuText, QMainWindow* mw, const char* name )
-: QtxAction( text, icon, menuText, 0, mw, name ),
-myMain( mw ),
-myAutoAdd( true ),
-mySeparate( true ),
-myAutoPlace( false )
-{
- initialize( mw );
-}
-
-/*!
- Name: ~QtxDockAction [public]
- Desc: Removes all added popup items.
-*/
-
-QtxDockAction::~QtxDockAction()
-{
- for ( MenuMap::ConstIterator mIt = myMenu.begin(); mIt != myMenu.end(); ++mIt )
- removeFrom( mIt.key() );
-
- for ( InfoMap::ConstIterator iIt = myInfo.begin(); iIt != myInfo.end(); ++iIt )
- delete iIt.data().a;
-}
-
-/*!
- Name: mainWindow [public]
- Desc: Returns the main window which contains managed dock windows.
-*/
-
-QMainWindow* QtxDockAction::mainWindow() const
-{
- return myMain;
-}
-
-/*!
- Name: isAutoAdd [public]
- Desc: Returns the auto add property. If this property is setted then all newly
- appeared dock windows will be automatically added.
-*/
-
-bool QtxDockAction::isAutoAdd() const
-{
- return myAutoAdd;
-}
-
-/*!
- Name: setAutoAdd [public]
- Desc: Sets the auto add property. If this property is setted then all newly
- appeared dock windows will be automatically added.
-*/
-
-void QtxDockAction::setAutoAdd( const bool on )
-{
- myAutoAdd = on;
-}
-
-/*!
- Name: isAutoPlace [public]
- Desc: Returns the auto place property. If this property is setted then all newly
- added dock windows will be automatically placed according stored place information.
-*/
-
-bool QtxDockAction::isAutoPlace() const
-{
- return myAutoPlace;
-}
-
-/*!
- Name: setAutoPlace [public]
- Desc: Sets the auto place property. If this property is setted then all newly
- added dock windows will be automatically placed according stored place
- information.
-*/
-
-void QtxDockAction::setAutoPlace( const bool on )
-{
- myAutoPlace = on;
-}
-
-/*!
- Name: isSeparate [public]
- Desc: Returns the 'separate' property.
-*/
-
-bool QtxDockAction::isSeparate() const
-{
- return mySeparate;
-}
-
-/*!
- Name: setSeparate [public]
- Desc: Sets the 'separate' property. If this property is 'true' then toolbars and
- dock windows menu items will be placed in different popup menus otherwise
- their will be placed in one common popup menu. This property will be
- affected in next method 'addTo'.
-*/
-
-void QtxDockAction::setSeparate( const bool on )
-{
- if ( mySeparate == on )
- return;
-
- mySeparate = on;
- updateMenus();
-}
-
-/*!
- Name: addTo [public]
- Desc: Add the dock windows sub menu item to the end of specified popup.
-*/
-
-bool QtxDockAction::addTo( QWidget* wid )
-{
- return addTo( wid, -1 );
-}
-
-/*!
- Name: addTo [public]
- Desc: Add the dock windows sub menu item to specified popup at the given index.
-*/
-
-bool QtxDockAction::addTo( QWidget* wid, const int idx )
-{
- if ( !wid || !wid->inherits( "QPopupMenu" ) )
- return false;
-
- QPopupMenu* pm = (QPopupMenu*)wid;
- checkPopup( pm );
-
- if ( myMenu.contains( pm ) )
- return false;
-
- MenuInfo mInfo;
- mInfo.dock = new QPopupMenu( pm );
- mInfo.tool = isSeparate() ? new QPopupMenu( pm ) : 0;
-
- QString dock, tool;
- splitMenuText( dock, tool );
-
- myMenu.insert( pm, mInfo );
-
- int index = idx;
-
- if ( mInfo.dock )
- iconSet().isNull() ? pm->insertItem ( dock, mInfo.dock, -1, index ) :
- pm->insertItem ( iconSet(), dock, mInfo.dock, -1, index );
-
- if ( index >= 0 )
- index++;
-
- if ( mInfo.tool )
- iconSet().isNull() ? pm->insertItem ( tool, mInfo.tool, -1, index ) :
- pm->insertItem ( iconSet(), tool, mInfo.tool, -1, index );
-
- connect( pm, SIGNAL( aboutToShow() ), this, SLOT( onAboutToShow() ) );
- connect( pm, SIGNAL( destroyed( QObject* ) ), this, SLOT( onPopupDestroyed( QObject* ) ) );
-
- return true;
-}
+#include <QMenu>
+#include <QToolBar>
+#include <QDockWidget>
+#include <QMainWindow>
/*!
- Name: removeFrom [public]
- Desc: Removes dock window sub menu from specified popup.
-*/
-
-bool QtxDockAction::removeFrom( QWidget* wid )
-{
- QPopupMenu* pm = (QPopupMenu*)wid;
-
- if ( myMenu.contains( pm ) )
- {
- pm->removeItem( findId( pm, myMenu[pm].dock ) );
- pm->removeItem( findId( pm, myMenu[pm].tool ) );
-
- delete myMenu[pm].dock;
- delete myMenu[pm].tool;
- myMenu.remove( pm );
+ \class QtxDockAction
+ \brief Dockable windows & toolbars list action.
- disconnect( pm, SIGNAL( aboutToShow() ), this, SLOT( onAboutToShow() ) );
- disconnect( pm, SIGNAL( destroyed( QObject* ) ), this, SLOT( onPopupDestroyed( QObject* ) ) );
- }
-
- return QtxAction::removeFrom( wid );
-}
-
-/*!
- Sets menu text of action
- \param txt - new menu text
+ Implements the action which provides the popup menu with the list
+ of toolbars and/or dockable windows list owned by the main window.
+ This action can be used, for example, in the menu "Windows".
*/
-void QtxDockAction::setMenuText( const QString& txt )
-{
- if ( menuText() == txt )
- return;
-
- QtxAction::setMenuText( txt );
- updateMenus();
-}
/*!
- Name: addDockWindow [public]
- Desc: Add dock window to internal data structures. Action will be include all added
- dock windows in to menu and manage their place configuration.
+ \brief Constructor.
+ \param mw parent main window
*/
-
-bool QtxDockAction::addDockWindow( QDockWindow* dw )
+QtxDockAction::QtxDockAction( QMainWindow* mw )
+: QtxAction( "Windows and Toolbars", "Windows and Toolbars", 0, mw ),
+ myType( Both ),
+ myMain( mw )
{
- if ( !dw || !mainWindow() )
- return false;
-
- if ( myInfo.contains( dw ) )
- return false;
-
- myInfo.insert( dw, DockInfo() );
-
- DockInfo& inf = myInfo[dw];
- inf.name = windowName( dw );
- QAction* a = inf.a = new QAction( mainWindow(), 0, true );
-
- autoLoadPlaceInfo( dw );
-
- bool block = a->signalsBlocked();
- a->blockSignals( true );
- a->setOn( dw->isVisibleTo( mainWindow() ) );
- a->blockSignals( block );
-
- updateInfo( dw );
- savePlaceInfo( dw );
-
- dw->installEventFilter( this );
-
- connect( a, SIGNAL( toggled( bool ) ), this, SLOT( onToggled( bool ) ) );
- connect( dw, SIGNAL( destroyed( QObject* ) ), this, SLOT( onWindowDestroyed( QObject* ) ) );
- connect( dw, SIGNAL( visibilityChanged( bool ) ), this, SLOT( onVisibilityChanged( bool ) ) );
-
- return true;
+ initialize();
}
/*!
- Name: removeDockWindow [public]
- Desc: Remove dock window from internal data structures. Action will not manage this window.
+ \brief Constructor.
+ \param text description (tooltip) text
+ \param menuText menu text
+ \param mw parent main window
*/
-
-bool QtxDockAction::removeDockWindow( QDockWindow* dw )
+QtxDockAction::QtxDockAction( const QString& text, const QString& menuText, QMainWindow* mw )
+: QtxAction( text, menuText, 0, mw ),
+ myType( Both ),
+ myMain( mw )
{
- if ( !myInfo.contains( dw ) )
- return false;
-
- myGeom.remove( myInfo[dw].name );
-
- delete myInfo[dw].a;
- myInfo.remove( dw );
-
- dw->removeEventFilter( this );
-
- disconnect( dw, SIGNAL( destroyed( QObject* ) ), this, SLOT( onWindowDestroyed( QObject* ) ) );
- disconnect( dw, SIGNAL( visibilityChanged( bool ) ), this, SLOT( onVisibilityChanged( bool ) ) );
-
- return true;
+ initialize();
}
/*!
- Name: eventFilter [public]
- Desc: Event filter process caption and icon changing of managed dock windows
- and try to add newly appeared dock windows.
+ \brief Constructor.
+ \param text description (tooltip) text
+ \param icon action icon
+ \param menuText menu text
+ \param mw parent main window
*/
-
-bool QtxDockAction::eventFilter( QObject* o, QEvent* e )
+QtxDockAction::QtxDockAction( const QString& text, const QIcon& icon, const QString& menuText, QMainWindow* mw )
+: QtxAction( text, icon, menuText, 0, mw ),
+ myType( Both ),
+ myMain( mw )
{
- if ( o->inherits( "QDockWindow" ) && ( e->type() == QEvent::CaptionChange ||
- e->type() == QEvent::IconChange ) )
- updateInfo( (QDockWindow*)o );
-
- if ( o->inherits( "QDockArea" ) && e->type() == QEvent::ChildRemoved )
- {
- QChildEvent* ce = (QChildEvent*)e;
- if ( ce->child() && ce->child()->inherits( "QDockWindow" ) )
- savePlaceInfo( (QDockWindow*)ce->child() );
- }
-
- if ( o->inherits( "QDockArea" ) && e->type() == QEvent::ChildInserted )
- {
- QChildEvent* ce = (QChildEvent*)e;
- if ( ce->child() && ce->child()->inherits( "QDockWindow" ) )
- QApplication::postEvent( this, new QCustomEvent( (QEvent::Type)AutoAdd, ce->child() ) );
- }
-
- return false;
+ initialize();
}
/*!
- Name: restoreGeometry [public]
- Desc: Retrieve the dock window geometry. If dock window specified as 0
- then all windows geometry will be restored.
+ \brief Desctructor
+
+ Does nothing currently.
*/
-
-void QtxDockAction::restoreGeometry( QDockWindow* dw ) const
+QtxDockAction::~QtxDockAction()
{
- if ( !dw )
- loadPlaceInfo();
- else
- loadPlaceInfo( dw );
}
/*!
- Name: storeGeometry [public]
- Desc: Store the dock window geometry. If dock window specified as 0
- then all windows geometry will be stored.
+ \brief Get parent main window.
+ \return main window pointer.
*/
-
-void QtxDockAction::storeGeometry( QDockWindow* dw )
+QMainWindow* QtxDockAction::mainWindow() const
{
- QPtrList<QDockWindow> dwList;
-
- if ( dw )
- dwList.append( dw );
- else
- dockWindows( dwList );
-
- for ( QPtrListIterator<QDockWindow> it( dwList ); it.current(); ++it )
- savePlaceInfo( it.current() );
+ return myMain;
}
/*!
- Name: loadGeometry [public]
- Desc: Retrieve the dock windows geometry information from the specified resource manager section.
+ \brief Get dock action type.
+ \return dock type (QtxDockAction::DockType)
*/
-
-void QtxDockAction::loadGeometry( QtxResourceMgr* resMgr, const QString& section, const bool clear )
+int QtxDockAction::dockType() const
{
- QString sec = section.stripWhiteSpace();
- if ( !resMgr || sec.isEmpty() )
- return;
-
- myNames = QStringList::split( "|", resMgr->stringValue( sec, "windows_list", QString::null ) );
-
- QMap<QString, int> map;
- QStringList params = resMgr->parameters( sec );
- for ( QStringList::const_iterator it = params.begin(); it != params.end(); ++it )
- {
- QString p = QStringList::split( ".", *it, true ).first().stripWhiteSpace();
- if ( !p.isEmpty() )
- map.insert( p, 0 );
- }
-
- for ( QMap<QString, int>::ConstIterator itr = map.begin(); itr != map.end(); ++itr )
- {
- GeomInfo inf;
- if ( !clear && myGeom.contains( itr.key() ) )
- inf = myGeom[itr.key()];
- else
- {
- inf.vis = true; inf.newLine = false; inf.place = DockTop;
- inf.index = 0; inf.offset = 0;
- inf.x = 0; inf.y = 0; inf.w = 0; inf.h = 0;
- inf.fixW = -1; inf.fixH = -1;
- }
- if ( loadGeometry( resMgr, sec, itr.key(), inf ) )
- myGeom.insert( itr.key(), inf );
- }
+ return myType;
}
/*!
- Name: saveGeometry [public]
- Desc: Store the dock windows geometry information into the specified resource manager section.
+ \brief Set dock action type.
+ \param type dock type (QtxDockAction::DockType)
*/
-
-void QtxDockAction::saveGeometry( QtxResourceMgr* resMgr, const QString& section, const bool clear ) const
+void QtxDockAction::setDockType( const int type )
{
- QString sec = section.stripWhiteSpace();
- if ( !resMgr || sec.isEmpty() )
- return;
-
- QtxDockAction* that = (QtxDockAction*)this;
- that->storeGeometry();
-
- that->myNames.clear();
- collectNames( Minimized, that->myNames );
- for ( int i = DockTornOff; i < Minimized; i++ )
- collectNames( i, that->myNames );
-
- if ( clear )
- resMgr->remove( sec );
-
- resMgr->setValue( sec, "windows_list", myNames.join( "|" ) );
-
- for ( GeomMap::ConstIterator it = myGeom.begin(); it != myGeom.end(); ++it )
- saveGeometry( resMgr, sec, it.key(), it.data() );
+ myType = type;
}
/*!
- Name: onAboutToShow [private slots]
- Desc: Prepare sub popup with dock windows list when parent popup is shown.
+ \brief Prepare popup menu with dock windows list when
+ parent popup menu is shown.
*/
-
void QtxDockAction::onAboutToShow()
{
- const QObject* obj = sender();
- if ( obj && obj->inherits( "QPopupMenu" ) )
- {
- QPopupMenu* pm = (QPopupMenu*)obj;
- fillPopup( pm );
- pm->setItemEnabled( findId( pm, myMenu[pm].dock ), isEnabled() && myMenu[pm].dock && myMenu[pm].dock->count() );
- pm->setItemEnabled( findId( pm, myMenu[pm].tool ), isEnabled() && myMenu[pm].tool && myMenu[pm].tool->count() );
- }
-}
-
-/*!
- Name: onToggled [private slots]
- Desc: Show or hide dock window when user toggled window item in popup.
-*/
-
-void QtxDockAction::onToggled( bool on )
-{
- QDockWindow* dw = dockWindow( (QAction*)sender() );
- if ( dw )
- on ? dw->show() : dw->hide();
-}
-
-/*!
- Name: onPopupDestroyed [private slots]
- Desc: Remove destroyed popup from data structures.
-*/
-
-void QtxDockAction::onPopupDestroyed( QObject* obj )
-{
- myMenu.remove( (QPopupMenu*)obj );
-}
-
-/*!
- Name: onWindowDestroyed [private slots]
- Desc: Remove information about destroyed dock window.
-*/
-
-void QtxDockAction::onWindowDestroyed( QObject* obj )
-{
- QDockWindow* dw = (QDockWindow*)obj;
- if ( !myInfo.contains( dw ) )
- return;
-
- delete myInfo[dw].a;
- myInfo.remove( dw );
-}
-
-/*!
- Name: onVisibilityChanged [private slots]
- Desc: Toggle corresponded action when visibility state of dock window changed.
-*/
-
-void QtxDockAction::onVisibilityChanged( bool on )
-{
- const QObject* obj = sender();
- if ( !obj || !obj->inherits( "QDockWindow" ) )
- return;
-
- QDockWindow* dw = (QDockWindow*)obj;
-
- QAction* a = action( dw );
- if ( a && a->isOn() != on )
- {
- bool block = a->signalsBlocked();
- a->blockSignals( true );
- a->setOn( on );
- a->blockSignals( block );
- }
-
- savePlaceInfo( dw );
-}
-
-/*!
- Name: onDockWindowPositionChanged [private slots]
- Desc: Update dock window place information
-*/
-
-void QtxDockAction::onDockWindowPositionChanged( QDockWindow* dw )
-{
- savePlaceInfo( dw );
-}
-
-/*!
- Name: event [protected]
- Desc: Check consistency the popup content and internal datas.
- Synchronize internal data structures with popup content.
-*/
-
-bool QtxDockAction::event( QEvent* e )
-{
- if ( e->type() == (int)AutoAdd )
- {
- QCustomEvent* ce = (QCustomEvent*)e;
- QDockWindow* dw = (QDockWindow*)ce->data();
- if ( !myInfo.contains( dw ) )
- {
- autoAddDockWindow( dw );
- autoLoadPlaceInfo( dw );
- }
- }
-
- return QtxAction::event( e );
+ updateMenu();
+ setVisible( menu() && !menu()->isEmpty() );
}
/*!
- Name: checkPopup [private]
- Desc: Check consistency the popup content and internal datas.
- Synchronize internal data structures with popup content.
+ \brief Get all toolbars owned by parent main window.
+ \param lst returned list of all toolbars owned by main window
*/
-
-void QtxDockAction::checkPopup( QPopupMenu* pm )
+void QtxDockAction::toolBars( QList<QToolBar*>& lst ) const
{
- if ( !myMenu.contains( pm ) )
- return;
-
- int id = findId( pm, myMenu[pm].dock );
- if ( id == -1 )
- {
- delete myMenu[pm].dock;
- myMenu[pm].dock = 0;
- }
- id = findId( pm, myMenu[pm].tool );
- if ( id == -1 )
- {
- delete myMenu[pm].tool;
- myMenu[pm].tool = 0;
- }
-
- if ( !myMenu[pm].dock )
- {
- delete myMenu[pm].tool;
- myMenu.remove( pm );
- disconnect( pm, SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
- }
-}
-
-/*!
- Name: fillPopup [private]
- Desc: Clear the popup and the add to it required actions.
-*/
-
-void QtxDockAction::fillPopup( QPopupMenu* pm ) const
-{
- if ( !pm || !mainWindow() )
- return;
-
- if ( !myMenu.contains( pm ) )
- return;
-
- QPopupMenu* dockMenu = myMenu[pm].dock;
- QPopupMenu* toolMenu = myMenu[pm].tool;
-
- for ( InfoMap::ConstIterator mit = myInfo.begin(); mit != myInfo.end(); ++mit )
- {
- mit.data().a->removeFrom( dockMenu );
- mit.data().a->removeFrom( toolMenu );
- }
-
- if ( dockMenu )
- dockMenu->clear();
-
- if ( toolMenu )
- toolMenu->clear();
-
- QPtrList<QDockWindow> dockList;
- dockWindows( dockList, mainWindow() );
+ lst.clear();
- if ( dockList.isEmpty() )
+ QMainWindow* mw = mainWindow();
+ if ( !mw )
return;
- QPtrList<QAction> toolBars, windows;
- for ( QPtrListIterator<QDockWindow> it( dockList ); it.current(); ++it )
- {
- if ( !myInfo.contains( it.current() ) )
- {
- QtxDockAction* that = (QtxDockAction*)this;
- that->autoAddDockWindow( it.current() );
- }
-
- if ( !mainWindow()->appropriate( it.current() ) ||
- it.current()->caption().isEmpty() || !action( it.current() ) )
- continue;
-
- if ( isToolBar( it.current() ) )
- toolBars.append( action( it.current() ) );
- else
- windows.append( action( it.current() ) );
- }
-
- for ( QPtrListIterator<QAction> wit( windows ); wit.current(); ++wit )
- wit.current()->addTo( dockMenu );
-
- dockMenu->insertSeparator();
-
- for ( QPtrListIterator<QAction> tit( toolBars ); tit.current(); ++tit )
- tit.current()->addTo( toolMenu ? toolMenu : dockMenu );
-
- Qtx::simplifySeparators( dockMenu );
- Qtx::simplifySeparators( toolMenu );
-}
-
-/*!
- Name: isToolBar [private]
- Desc: Returns 'true' if dock window is a toolbar.
-*/
-
-bool QtxDockAction::isToolBar( QDockWindow* dw ) const
-{
- return dw && dw->inherits( "QToolBar" );
-}
-
-/*!
- Name: findId [private]
- Desc: Returns identificator of popup item which contains sub popup 'pm' in the popup 'cont'.
-*/
-
-int QtxDockAction::findId( QPopupMenu* cont, QPopupMenu* pm ) const
-{
- if ( !cont || !pm )
- return -1;
-
- int id = -1;
-
- for ( int i = 0; i < (int)cont->count() && id == -1; i++ )
+ QList<QToolBar*> toolbars = qFindChildren<QToolBar*>( mw );
+ for ( QList<QToolBar*>::iterator it = toolbars.begin(); it != toolbars.end(); ++it )
{
- QMenuData* md = 0;
- QMenuItem* item = cont->findItem( cont->idAt( i ), &md );
- if ( item && md == cont && item->popup() == pm )
- id = item->id();
+ QToolBar* tb = *it;
+ if ( tb->parentWidget() == mw )
+ lst.append( tb );
}
- return id;
}
/*!
- Name: dockWindows [private]
- Desc: Returns all dock windows of the main window.
+ \brief Get all dockable windows owned by parent main window.
+ \param lst returned list of all dockable windows owned by main window
*/
-
-void QtxDockAction::dockWindows( QPtrList<QDockWindow>& lst, QMainWindow* main ) const
+void QtxDockAction::dockWidgets( QList<QDockWidget*>& lst ) const
{
lst.clear();
- QMainWindow* mw = main ? main : mainWindow();
+ QMainWindow* mw = mainWindow();
if ( !mw )
return;
- QObjectList* objs = mw->queryList( "QDockWindow" );
- if ( objs )
+ QList<QDockWidget*> dockwidgets = qFindChildren<QDockWidget*>( mw );
+ for ( QList<QDockWidget*>::iterator it = dockwidgets.begin(); it != dockwidgets.end(); ++it )
{
- for ( QObjectListIt it( *objs ); it.current(); ++it )
- {
- QDockWindow* dockWin = ::qt_cast<QDockWindow*>( it.current() );
- if ( dockWin && dockMainWindow( mw, dockWin ) )
- lst.append( dockWin );
- }
+ QDockWidget* dw = *it;
+ if ( dw->parentWidget() == mw )
+ lst.append( dw );
}
- delete objs;
}
-/*!
- \return true if main window is parent of object
- \param mw - main window
- \param win - object
-*/
-bool QtxDockAction::dockMainWindow( QMainWindow* mw, QObject* win ) const
-{
- if ( !mw || !win )
- return false;
-
- while ( win )
- {
- if ( win->parent() && win->parent() == mw )
- return true;
-
- if ( ::qt_cast<QMainWindow*>( win->parent() ) )
- return false;
-
- win = win->parent();
- }
-
- return false;
-}
-
-/*!
- Name: updateInfo [private]
- Desc: Updates icon and caption info of dock window in the corresponded action.
-*/
-
+/*
void QtxDockAction::updateInfo( QDockWindow* dw )
{
QAction* a = action( dw );
if ( icon )
a->setIconSet( *icon );
}
-
-/*!
- Name: savePlaceInfo [private]
- Desc: Store the place and geometry information from specified dock window.
-*/
-
-void QtxDockAction::savePlaceInfo( QDockWindow* dw )
-{
- if ( !myInfo.contains( dw ) )
- return;
-
- if ( !myGeom.contains( myInfo[dw].name ) )
- myGeom.insert( myInfo[dw].name, GeomInfo() );
-
- GeomInfo& inf = myGeom[myInfo[dw].name];
-
- Dock dock;
- inf.vis = dw->isVisibleTo( mainWindow() );
- mainWindow()->getLocation( dw, dock, inf.index, inf.newLine, inf.offset );
-
- inf.place = dock;
- inf.x = dw->x();
- inf.y = dw->y();
- inf.w = dw->width();
- inf.h = dw->height();
- inf.fixW = dw->fixedExtent().width();
- inf.fixH = dw->fixedExtent().height();
-}
-
-/*!
- Name: loadPlaceInfo [private]
- Desc: Retrieve the stored place and geometry information to specified dock window.
-*/
-
-void QtxDockAction::loadPlaceInfo( QDockWindow* dw ) const
-{
- if ( !myInfo.contains( dw ) )
- return;
-
- QMainWindow* mw = mainWindow();
- if ( !mw )
- return;
-
- QObject* p = dw->parent();
- if ( !( !p || p == mw || ( p->parent() && p->parent() == mw ) ) )
- return;
-
- QString winName = myInfo[dw].name;
- if ( winName.isEmpty() || !myGeom.contains( winName ) )
- return;
-
- GeomInfo inf = myGeom[myInfo[dw].name];
-
- mainWindow()->moveDockWindow( dw, (Qt::Dock)inf.place, inf.newLine, inf.index, inf.offset );
- dw->setGeometry( inf.x, inf.y, inf.w, inf.h );
-
- dw->setFixedExtentWidth( inf.fixW );
- dw->setFixedExtentHeight( inf.fixH );
-
- QtxDockAction* that = (QtxDockAction*)this;
- that->myGeom.insert( myInfo[dw].name, inf );
-}
-
-/*!
- Name: loadPlaceInfo [private]
- Desc: Retrieve the stored place and geometry information to all dock windows.
-*/
-
-void QtxDockAction::loadPlaceInfo() const
-{
- QMainWindow* mw = mainWindow();
- if ( !mw )
- return;
-
- typedef QPtrList<QDockWindow> DockWinList;
-
- DockWinList lst;
- dockWindows( lst, mw );
-
- QMap<QString, QDockWindow*> nameMap;
- for ( QPtrListIterator<QDockWindow> itr( lst ); itr.current(); ++itr )
- {
- QObject* p = itr.current()->parent();
- if ( !( !p || p == mw || ( p->parent() && p->parent() == mw ) ) )
- continue;
-
- QString name;
- if ( myInfo.contains( itr.current() ) )
- name = myInfo[itr.current()].name;
-
- if ( !myGeom.contains( name ) )
- continue;
-
- nameMap.insert( name, itr.current() );
- }
-
- DockWinList winList;
- for ( QStringList::const_iterator iter = myNames.begin(); iter != myNames.end(); ++iter )
- {
- if ( nameMap.contains( *iter ) )
- winList.append( nameMap[*iter] );
- nameMap.remove( *iter );
- }
-
- for ( QMap<QString, QDockWindow*>::ConstIterator mIt = nameMap.begin(); mIt != nameMap.end(); ++mIt )
- winList.append( mIt.data() );
-
- QMap<int, DockWinList> winMap;
- QMap<QDockWindow*, GeomInfo*> geomMap;
-
- for ( QPtrListIterator<QDockWindow> it( winList ); it.current(); ++it )
- {
- QString name;
- if ( myInfo.contains( it.current() ) )
- name = myInfo[it.current()].name;
-
- if ( !myGeom.contains( name ) )
- continue;
-
- //! collect pointer of info to have fresh info data after processEvents();
- GeomInfo* inf = (GeomInfo*)&( myGeom[name] );
- geomMap.insert( it.current(), inf );
- if ( !winMap.contains( inf->place ) )
- winMap.insert( inf->place, DockWinList() );
- winMap[inf->place].append( it.current() );
- }
-
- loadPlaceArea( DockMinimized, mw, 0,
- winMap.contains( DockMinimized ) ? winMap[DockMinimized] : DockWinList(), geomMap );
- for ( int i = DockTornOff; i < DockMinimized; i++ )
- {
- loadPlaceArea( i, mw, dockArea( i ), winMap.contains( i ) ? winMap[i] : DockWinList(), geomMap );
- }
-}
-
-/*!
- Name: loadPlaceArea [private]
- Desc: Set the place and geometry information to all dock windows in the area.
-*/
-
-void QtxDockAction::loadPlaceArea( const int place, QMainWindow* mw, QDockArea* area,
- const QPtrList<QDockWindow>& dockList,
- const QMap<QDockWindow*, GeomInfo*>& geomMap ) const
-{
- for ( QPtrListIterator<QDockWindow> it( dockList ); it.current(); ++it )
- {
- if ( !geomMap.contains( it.current() ) )
- continue;
-
- GeomInfo* inf = geomMap[it.current()];
- mw->moveDockWindow( it.current(), (Qt::Dock)place, inf->newLine, inf->index, inf->offset );
- }
-
- if ( !area )
- return;
-
- qApp->processEvents();
-
- for ( QPtrListIterator<QDockWindow> itr( dockList ); itr.current(); ++itr )
- {
- QDockWindow* dw = itr.current();
- if ( !geomMap.contains( dw ) )
- continue;
-
- GeomInfo* inf = geomMap[dw];
- if ( place != DockTornOff )
- {
- dw->setNewLine( inf->newLine );
- dw->setOffset( inf->offset );
- dw->setFixedExtentWidth( inf->fixW );
- dw->setFixedExtentHeight( inf->fixH );
- }
- dw->setGeometry( inf->x, inf->y, inf->w, inf->h );
-
- QAction* a = action( dw );
- if ( a )
- {
- bool block = a->signalsBlocked();
- a->blockSignals( true );
- a->setOn( inf->vis );
- a->blockSignals( block );
- }
-
- if ( mainWindow() && mainWindow()->appropriate( dw ) )
- inf->vis ? dw->show() : dw->hide();
- }
-
- QWidget* wid = area;
- if ( wid->layout() )
- {
- wid->layout()->invalidate();
- wid->layout()->activate();
- }
-}
-
-/*!
- Name: action [private]
- Desc: Returns action for the given dock window.
*/
-QAction* QtxDockAction::action( QDockWindow* dw ) const
-{
- QAction* a = 0;
- if ( myInfo.contains( dw ) )
- a = myInfo[dw].a;
- return a;
-}
-
/*!
- Name: dockWindow [private]
- Desc: Returns dock window for the given action.
-*/
-
-QDockWindow* QtxDockAction::dockWindow( const QAction* a ) const
-{
- QDockWindow* dw = 0;
- for ( InfoMap::ConstIterator it = myInfo.begin(); it != myInfo.end() && !dw; ++it )
- {
- if ( it.data().a == a )
- dw = it.key();
- }
- return dw;
-}
+ \brief Customize action adding to the widget operation.
+
+ Called when the action is added to the widget.
+ Reimplemented from QtxAction class.
-/*!
- Name: initialize [private]
- Desc: Initialisation of the object. Sets the event filters and add existing dock windows.
+ \param w widget this action is added to (menu or toolbar)
*/
-
-void QtxDockAction::initialize( QMainWindow* mw )
+void QtxDockAction::addedTo( QWidget* w )
{
- if ( !mw )
- return;
-
- QPtrList<QDockWindow> lst;
- dockWindows( lst, mw );
-
- for ( QPtrListIterator<QDockWindow> it( lst ); it.current(); ++it )
- QApplication::postEvent( this, new QCustomEvent( (QEvent::Type)AutoAdd, it.current() ) );
-
- if ( mw->topDock() )
- mw->topDock()->installEventFilter( this );
- if ( mw->leftDock() )
- mw->leftDock()->installEventFilter( this );
- if ( mw->rightDock() )
- mw->rightDock()->installEventFilter( this );
- if ( mw->bottomDock() )
- mw->bottomDock()->installEventFilter( this );
-
- connect( mw, SIGNAL( dockWindowPositionChanged( QDockWindow* ) ),
- this, SLOT( onDockWindowPositionChanged( QDockWindow* ) ) );
+ if ( w->inherits( "QMenu" ) )
+ connect( w, SIGNAL( aboutToShow() ), this, SLOT( onAboutToShow() ) );
}
/*!
- Name: windowName [private]
- Desc: Generate the dock window name.
-*/
-
-QString QtxDockAction::windowName( QDockWindow* dw ) const
-{
- QString name;
+ \brief Customize action removing from the widget operation.
+
+ Called when the action is removed from the widget.
+ Reimplemented from QtxAction class.
- if ( dw )
- {
- name = dw->name( "" );
- if ( name.isEmpty() )
- name = dw->caption();
- }
-
- return name;
-}
-
-/*!
- Name: autoAddDockWindow [private]
- Desc: Add the dock window if auto add property is setted.
+ \param w widget this action is removed from to (menu or toolbar)
*/
-
-bool QtxDockAction::autoAddDockWindow( QDockWindow* dw )
+void QtxDockAction::removedFrom( QWidget* w )
{
- if ( !isAutoAdd() )
- return false;
-
- return addDockWindow( dw );
+ if ( w->inherits( "QMenu" ) )
+ disconnect( w, SIGNAL( aboutToShow() ), this, SLOT( onAboutToShow() ) );
}
/*!
- Name: autoLoadPlaceInfo [private]
- Desc: Retieve the dock window place geometry if auto place property is setted.
+ \brief Initialize the action.
*/
-
-void QtxDockAction::autoLoadPlaceInfo( QDockWindow* dw )
+void QtxDockAction::initialize()
{
- if ( isAutoPlace() )
- loadPlaceInfo( dw );
+ setMenu( new QMenu( 0 ) );
}
/*!
- Name: splitMenuText [private]
- Desc:
+ \brief Update action child popup menu.
*/
-
-void QtxDockAction::splitMenuText( QString& dock, QString& tool ) const
+void QtxDockAction::updateMenu()
{
- dock = tool = menuText();
- if ( !isSeparate() )
+ QMenu* pm = menu();
+ if ( !pm )
return;
- QStringList lst = splitText( menuText(), "|" );
- if ( lst.count() < 2 )
- lst = splitText( menuText(), "and" );
-
- dock = lst.first();
- tool = lst.last();
-}
-
-/*!
- Name: splitText [private]
- Desc:
-*/
-
-QStringList QtxDockAction::splitText( const QString& str, const QString& sep ) const
-{
- QStringList res;
-
- int idx = str.lower().find( sep.lower() );
- if ( idx != -1 )
- {
- res.append( str.mid( 0, idx ).stripWhiteSpace() );
- res.append( str.mid( idx + sep.length() ).stripWhiteSpace() );
- }
-
- return res;
-}
-
-/*!
- Name: dockPlace [private]
- Desc:
-*/
-
-int QtxDockAction::dockPlace( const QString& dockName ) const
-{
- static QMap<QString, int> dockNameMap;
- if ( dockNameMap.isEmpty() )
- {
- dockNameMap["top"] = DockTop;
- dockNameMap["bottom"] = DockBottom;
- dockNameMap["left"] = DockLeft;
- dockNameMap["right"] = DockRight;
- dockNameMap["tornoff"] = DockTornOff;
- dockNameMap["torn_off"] = DockTornOff;
- dockNameMap["outside"] = DockTornOff;
- dockNameMap["undock"] = DockTornOff;
- dockNameMap["minimized"] = DockMinimized;
- dockNameMap["unmanaged"] = DockUnmanaged;
- }
-
- int res = -1;
- if ( dockNameMap.contains( dockName.lower() ) )
- res = dockNameMap[dockName.lower()];
- return res;
-}
+ pm->clear();
-/*!
- Name: dockArea [private]
- Desc:
-*/
-
-QDockArea* QtxDockAction::dockArea( const int place ) const
-{
- if ( !mainWindow() )
- return 0;
-
- QDockArea* area = 0;
- switch ( place )
+ if ( dockType() == DockWidget || dockType() == Both )
{
- case DockTop:
- area = mainWindow()->topDock();
- break;
- case DockBottom:
- area = mainWindow()->bottomDock();
- break;
- case DockLeft:
- area = mainWindow()->leftDock();
- break;
- case DockRight:
- area = mainWindow()->rightDock();
- break;
+ QList<QDockWidget*> dwList;
+ dockWidgets( dwList );
+ for ( QList<QDockWidget*>::iterator it = dwList.begin(); it != dwList.end(); ++it )
+ pm->addAction( (*it)->toggleViewAction() );
}
- return area;
-}
-
-/*!
- Name: loadGeometry [private]
- Desc:
-*/
-
-bool QtxDockAction::loadGeometry( QtxResourceMgr* resMgr, const QString& sec,
- const QString& name, GeomInfo& inf ) const
-{
- if ( !resMgr || sec.isEmpty() || name.isEmpty() )
- return false;
-
- QString tmpl = QString( "%1.%2" ).arg( name );
-
- inf.vis = resMgr->booleanValue( sec, tmpl.arg( "visible" ), inf.vis );
- inf.newLine = resMgr->booleanValue( sec, tmpl.arg( "new_line" ), inf.newLine );
-
- inf.index = resMgr->integerValue( sec, tmpl.arg( "index" ), inf.index );
- inf.offset = resMgr->integerValue( sec, tmpl.arg( "offset" ), inf.offset );
-
- inf.x = resMgr->integerValue( sec, tmpl.arg( "x" ), inf.x );
- inf.y = resMgr->integerValue( sec, tmpl.arg( "y" ), inf.y );
- inf.w = resMgr->integerValue( sec, tmpl.arg( "width" ), inf.w );
- inf.h = resMgr->integerValue( sec, tmpl.arg( "height" ), inf.h );
-
- inf.fixW = resMgr->integerValue( sec, tmpl.arg( "fixed_width" ), inf.fixW );
- inf.fixH = resMgr->integerValue( sec, tmpl.arg( "fixed_height" ), inf.fixH );
-
- int place = -1;
- if ( !resMgr->value( sec, tmpl.arg( "place" ), place ) )
- {
- QString placeStr;
- if ( resMgr->value( sec, tmpl.arg( "place" ), placeStr ) )
- place = dockPlace( placeStr );
- }
-
- if ( place >= DockUnmanaged && place <= DockMinimized )
- inf.place = place;
-
- return true;
-}
-
-/*!
- Name: saveGeometry [private]
- Desc:
-*/
-
-bool QtxDockAction::saveGeometry( QtxResourceMgr* resMgr, const QString& sec,
- const QString& name, const GeomInfo& inf ) const
-{
- if ( !resMgr || sec.isEmpty() || name.isEmpty() )
- return false;
- QString tmpl = QString( "%1.%2" ).arg( name );
+ pm->addSeparator();
- resMgr->setValue( sec, tmpl.arg( "visible" ), inf.vis );
- resMgr->setValue( sec, tmpl.arg( "new_line" ), inf.newLine );
- resMgr->setValue( sec, tmpl.arg( "index" ), inf.index );
- resMgr->setValue( sec, tmpl.arg( "offset" ), inf.offset );
- resMgr->setValue( sec, tmpl.arg( "x" ), inf.x );
- resMgr->setValue( sec, tmpl.arg( "y" ), inf.y );
- resMgr->setValue( sec, tmpl.arg( "width" ), inf.w );
- resMgr->setValue( sec, tmpl.arg( "height" ), inf.h );
- resMgr->setValue( sec, tmpl.arg( "fixed_width" ), inf.fixW );
- resMgr->setValue( sec, tmpl.arg( "fixed_height" ), inf.fixH );
- resMgr->setValue( sec, tmpl.arg( "place" ), inf.place );
-
- return true;
-}
-
-/*!
- Name: collectNames [private]
- Desc:
-*/
-
-void QtxDockAction::collectNames( const int place, QStringList& lst ) const
-{
- QPtrList<QDockWindow> winList;
- QDockArea* area = dockArea( place );
- if ( area )
- winList = area->dockWindowList();
- else
- winList = mainWindow()->dockWindows( (Qt::Dock)place );
-
- for ( QPtrListIterator<QDockWindow> it( winList ); it.current(); ++it )
+ if ( dockType() == ToolBar || dockType() == Both )
{
- QString name;
- if ( myInfo.contains( it.current() ) )
- name = myInfo[it.current()].name;
- if ( name.isEmpty() )
- name = windowName( it.current() );
- if ( name.isEmpty() )
- continue;
-
- lst.append( name );
+ QList<QToolBar*> tbList;
+ toolBars( tbList );
+ for ( QList<QToolBar*>::iterator it = tbList.begin(); it != tbList.end(); ++it )
+ pm->addAction( (*it)->toggleViewAction() );
}
-}
-/*!
- Updates menu of action
-*/
-void QtxDockAction::updateMenus()
-{
- for ( MenuMap::Iterator it = myMenu.begin(); it != myMenu.end(); ++it )
- {
- QPopupMenu* pm = it.key();
- MenuInfo& inf = it.data();
-
- int toolId = findId( pm, inf.tool );
- int dockId = findId( pm, inf.dock );
-
- int index = pm->indexOf( dockId );
-
- if ( isSeparate() && !inf.tool )
- inf.tool = new QPopupMenu( pm );
-
- pm->removeItem( dockId );
- pm->removeItem( toolId );
-
- if ( !isSeparate() && inf.tool )
- {
- delete inf.tool;
- inf.tool = 0;
- }
-
- QString dock, tool;
- splitMenuText( dock, tool );
-
- if ( inf.dock )
- iconSet().isNull() ? pm->insertItem ( dock, inf.dock, -1, index ) :
- pm->insertItem ( iconSet(), dock, inf.dock, -1, index );
-
- if ( index >= 0 )
- index++;
-
- if ( inf.tool )
- iconSet().isNull() ? pm->insertItem ( tool, inf.tool, -1, index ) :
- pm->insertItem ( iconSet(), tool, inf.tool, -1, index );
- }
+ Qtx::simplifySeparators( pm );
}
#include "QtxAction.h"
-#include <qevent.h>
-#include <qptrlist.h>
-#include <qpopupmenu.h>
+#include <QList>
-class QAction;
-class QDockArea;
-class QDockWindow;
+class QIcon;
+class QString;
+class QToolBar;
+class QDockWidget;
class QMainWindow;
-class QtxResourceMgr;
#ifdef WIN32
#pragma warning( disable:4251 )
{
Q_OBJECT
- Q_PROPERTY( bool autoAdd READ isAutoAdd WRITE setAutoAdd )
- Q_PROPERTY( bool autoPlace READ isAutoPlace WRITE setAutoPlace )
- Q_PROPERTY( bool separate READ isSeparate WRITE setSeparate )
+public:
+ //! Dock windows type.
+ enum { ToolBar, //!< list toolbars only
+ DockWidget, //!< list dockable windows only
+ Both //!< list toolbars and dockable windows
+ } DockType;
public:
- QtxDockAction( QMainWindow*, const char* = 0 );
- QtxDockAction( const QString&, const QString&, QMainWindow*, const char* = 0 );
- QtxDockAction( const QString&, const QIconSet&, const QString&, QMainWindow*, const char* = 0 );
+ QtxDockAction( QMainWindow* );
+ QtxDockAction( const QString&, const QString&, QMainWindow* );
+ QtxDockAction( const QString&, const QIcon&, const QString&, QMainWindow* );
virtual ~QtxDockAction();
- QMainWindow* mainWindow() const;
-
- bool isAutoAdd() const;
- void setAutoAdd( const bool );
-
- bool isAutoPlace() const;
- void setAutoPlace( const bool );
-
- bool isSeparate() const;
- void setSeparate( const bool );
-
- virtual bool addTo( QWidget* );
- virtual bool addTo( QWidget*, const int );
- virtual bool removeFrom( QWidget* );
- virtual void setMenuText( const QString& );
-
- bool addDockWindow( QDockWindow* );
- bool removeDockWindow( QDockWindow* );
+ int dockType() const;
+ void setDockType( const int );
- virtual bool eventFilter( QObject*, QEvent* );
-
- virtual void storeGeometry( QDockWindow* = 0 );
- virtual void restoreGeometry( QDockWindow* = 0 ) const;
-
- virtual void loadGeometry( QtxResourceMgr*, const QString&, const bool = true );
- virtual void saveGeometry( QtxResourceMgr*, const QString&, const bool = true ) const;
+ QMainWindow* mainWindow() const;
private slots:
void onAboutToShow();
- void onToggled( bool );
- void onVisibilityChanged( bool );
- void onPopupDestroyed( QObject* );
- void onWindowDestroyed( QObject* );
- void onDockWindowPositionChanged( QDockWindow* );
protected:
- virtual bool event( QEvent* );
+ virtual void addedTo( QWidget* );
+ virtual void removedFrom( QWidget* );
private:
- QAction* action( QDockWindow* ) const;
- QDockWindow* dockWindow( const QAction* ) const;
-
- void checkPopup( QPopupMenu* );
- void fillPopup( QPopupMenu* ) const;
- int findId( QPopupMenu*, QPopupMenu* ) const;
-
- void initialize( QMainWindow* );
- void updateInfo( QDockWindow* );
- bool isToolBar( QDockWindow* ) const;
- void dockWindows( QPtrList<QDockWindow>&, QMainWindow* = 0 ) const;
-
- QString windowName( QDockWindow* ) const;
- void savePlaceInfo( QDockWindow* );
- void loadPlaceInfo( QDockWindow* ) const;
- void loadPlaceInfo() const;
+ void initialize();
+ void updateMenu();
- bool autoAddDockWindow( QDockWindow* );
- void autoLoadPlaceInfo( QDockWindow* );
-
- void splitMenuText( QString&, QString& ) const;
- QStringList splitText( const QString&, const QString& ) const;
-
- QDockArea* dockArea( const int ) const;
- int dockPlace( const QString& ) const;
-
- void collectNames( const int, QStringList& ) const;
-
- void updateMenus();
-
- bool dockMainWindow( QMainWindow*, QObject* ) const;
-
-private:
- enum { AutoAdd = QEvent::User, LoadArea };
-
- typedef struct { bool vis, newLine;
- int place, index, offset;
- int x, y, w, h, fixW, fixH; } GeomInfo;
- typedef struct { QString name; QAction* a; } DockInfo;
- typedef struct { QPopupMenu *dock, *tool; } MenuInfo;
-
- typedef QMap<QDockWindow*, DockInfo> InfoMap;
- typedef QMap<QString, GeomInfo> GeomMap;
- typedef QMap<QPopupMenu*, MenuInfo> MenuMap;
+ void toolBars( QList<QToolBar*>& ) const;
+ void dockWidgets( QList<QDockWidget*>& ) const;
private:
- bool loadGeometry( QtxResourceMgr*, const QString&,
- const QString&, GeomInfo& ) const;
- bool saveGeometry( QtxResourceMgr*, const QString&,
- const QString&, const GeomInfo& ) const;
- void loadPlaceArea( const int, QMainWindow*, QDockArea*,
- const QPtrList<QDockWindow>&,
- const QMap<QDockWindow*, GeomInfo*>& ) const;
-
-private:
- InfoMap myInfo;
- MenuMap myMenu;
- GeomMap myGeom;
- QMainWindow* myMain;
- QStringList myNames;
-
- bool myAutoAdd;
- bool mySeparate;
- bool myAutoPlace;
+ int myType; //!< dock action type
+ QMainWindow* myMain; //!< parent main window
};
#ifdef WIN32
#pragma warning( default:4251 )
#endif
-#endif
+#endif // QTX_DOCKACTION_H
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File: QtxDockWidget.cxx
+// Author: Sergey TELKOV
+
+#include "QtxDockWidget.h"
+
+#include <QAction>
+#include <QLayout>
+#include <QMainWindow>
+#include <QResizeEvent>
+#include <QApplication>
+
+/*!
+ \class QtxDockWidget::Watcher
+ \internal
+ \brief Internal class which goal is to watch parent dockable widget state changing.
+*/
+
+class QtxDockWidget::Watcher : public QObject
+{
+public:
+ Watcher( QtxDockWidget* );
+
+ void shown( QtxDockWidget* );
+ void hidden( QtxDockWidget* );
+
+ virtual bool eventFilter( QObject*, QEvent* );
+
+protected:
+ virtual void customEvent( QEvent* );
+
+private:
+ void installFilters();
+
+ void showContainer();
+ void hideContainer();
+
+ void updateIcon();
+ void updateCaption();
+ void updateVisibility();
+
+private:
+ QtxDockWidget* myCont;
+ bool myState;
+ bool myEmpty;
+ bool myVisible;
+};
+
+/*!
+ \brief Constructor.
+ \param cont dockable widget to be watched
+*/
+QtxDockWidget::Watcher::Watcher( QtxDockWidget* cont )
+: QObject( cont ), myCont( cont ),
+ myState( true ),
+ myEmpty( false )
+{
+ myCont->installEventFilter( this );
+ myVisible = myCont->isVisibleTo( myCont->parentWidget() );
+
+ installFilters();
+}
+
+/*!
+ \brief Custom event filter.
+ \param o event receiver object
+ \param e event sent to object
+ \return \c true if further event processing should be stopped
+*/
+bool QtxDockWidget::Watcher::eventFilter( QObject* o, QEvent* e )
+{
+ if ( o == myCont && ( e->type() == QEvent::Show || e->type() == QEvent::ShowToParent ||
+ e->type() == QEvent::Hide || e->type() == QEvent::HideToParent ) )
+ {
+ installFilters();
+ QApplication::postEvent( this, new QEvent( QEvent::User ) );
+ }
+
+ if ( o == myCont && e->type() == QEvent::ChildAdded )
+ {
+ QChildEvent* ce = (QChildEvent*)e;
+ if ( ce->child()->isWidgetType() )
+ ce->child()->installEventFilter( this );
+
+ QApplication::postEvent( this, new QEvent( QEvent::User ) );
+ }
+
+ if ( o != myCont && e->type() == QEvent::WindowIconChange )
+ updateIcon();
+
+ if ( o != myCont && e->type() == QEvent::WindowTitleChange )
+ updateCaption();
+
+ if ( ( o != myCont && ( e->type() == QEvent::Hide || e->type() == QEvent::HideToParent ) ) ||
+ ( o == myCont && ( e->type() == QEvent::ChildRemoved ) ) ||
+ ( e->type() == QEvent::Show || e->type() == QEvent::ShowToParent ) )
+ updateVisibility();
+
+ return false;
+}
+
+/*!
+ \brief Set internal status to "shown"
+ \param dw dockable widget
+*/
+void QtxDockWidget::Watcher::shown( QtxDockWidget* dw )
+{
+ if ( dw != myCont )
+ return;
+
+ myVisible = true;
+}
+
+/*!
+ \brief Set internal status to "hidden"
+ \param dw dockable widget
+*/
+void QtxDockWidget::Watcher::hidden( QtxDockWidget* dw )
+{
+ if ( dw != myCont )
+ return;
+
+ myVisible = false;
+}
+
+/*!
+ \brief Show the dock window being watched
+*/
+void QtxDockWidget::Watcher::showContainer()
+{
+ if ( !myCont )
+ return;
+
+ QtxDockWidget* cont = myCont;
+ myCont = 0;
+ cont->show();
+ myCont = cont;
+}
+
+/*!
+ \brief Hide the dock window being watched
+*/
+void QtxDockWidget::Watcher::hideContainer()
+{
+ if ( !myCont )
+ return;
+
+ QtxDockWidget* cont = myCont;
+ myCont = 0;
+ cont->hide();
+ myCont = cont;
+}
+
+/*!
+ \brief Proces custom events.
+ \param e custom event (not used)
+*/
+void QtxDockWidget::Watcher::customEvent( QEvent* /*e*/ )
+{
+ updateIcon();
+ updateCaption();
+ updateVisibility();
+}
+
+/*!
+ \brief Install this object as event filter to all children widgets
+ of the dockable widget being watched.
+*/
+void QtxDockWidget::Watcher::installFilters()
+{
+ if ( !myCont )
+ return;
+
+ QLayout* l = myCont->layout();
+ if ( !l )
+ return;
+
+ for ( int i = 0; i < (int)l->count(); i++ )
+ {
+ if ( l->itemAt( i ) && l->itemAt( i )->widget() )
+ l->itemAt( i )->widget()->installEventFilter( this );
+ }
+}
+
+/*!
+ \brief Update visibility state of all children widgets of the dockable widget
+ being watched.
+*/
+void QtxDockWidget::Watcher::updateVisibility()
+{
+ if ( !myCont )
+ return;
+
+ QLayout* l = myCont->layout();
+ if ( !l )
+ return;
+
+ bool vis = false;
+ for ( int i = 0; i < (int)l->count() && !vis; i++ )
+ vis = l->itemAt( i ) && l->itemAt( i )->widget() && l->itemAt( i )->widget()->isVisibleTo( myCont );
+
+ if ( myEmpty == vis )
+ {
+ myEmpty = !vis;
+ if ( !myEmpty )
+ myCont->toggleViewAction()->setVisible( myState );
+ else
+ {
+ myState = myCont->toggleViewAction()->isVisible();
+ myCont->toggleViewAction()->setVisible( false );
+ }
+ }
+
+ vis = !myEmpty && myVisible;
+ if ( vis != myCont->isVisibleTo( myCont->parentWidget() ) )
+ vis ? showContainer() : hideContainer();
+}
+
+/*!
+ \brief Update the icon of dockable window being watched
+*/
+void QtxDockWidget::Watcher::updateIcon()
+{
+ if ( !myCont || !myCont->widget() )
+ return;
+
+ myCont->setWindowIcon( myCont->widget()->windowIcon() );
+}
+
+/*!
+ \brief Update the title of dockable window being watched
+*/
+void QtxDockWidget::Watcher::updateCaption()
+{
+ if ( myCont && myCont->widget() && !myCont->widget()->windowTitle().isNull() )
+ myCont->setWindowTitle( myCont->widget()->windowTitle() );
+}
+
+/*!
+ \class QtxDockWidget
+ \brief Enhanced dockable widget class.
+*/
+
+/*!
+ \brief Constructor.
+ \param title dockable widget title
+ \param parent parent widget
+ \param f widget flags
+*/
+QtxDockWidget::QtxDockWidget( const QString& title, QWidget* parent, Qt::WindowFlags f )
+: QDockWidget( title, parent, f ),
+ myWatcher( 0 ),
+ myOrientation( (Qt::Orientation)-1 )
+{
+ updateState();
+}
+
+/*!
+ \brief Constructor.
+ \param watch if \c true the event filter is installed to watch wigdet state changes
+ to update it properly
+ \param parent parent widget
+ \param f widget flags
+*/
+QtxDockWidget::QtxDockWidget( const bool watch, QWidget* parent, Qt::WindowFlags f )
+: QDockWidget( parent, f ),
+ myWatcher( 0 ),
+ myOrientation( (Qt::Orientation)-1 )
+{
+ if ( watch )
+ myWatcher = new Watcher( this );
+
+ updateState();
+}
+
+/*!
+ \brief Constructor.
+ \param parent parent widget
+ \param f widget flags
+*/
+QtxDockWidget::QtxDockWidget( QWidget* parent, Qt::WindowFlags f )
+: QDockWidget( parent, f ),
+myWatcher( 0 )
+{
+}
+
+/*!
+ \brief Destructor.
+*/
+QtxDockWidget::~QtxDockWidget()
+{
+}
+
+/*!
+ \brief Get the recommended size for the widget.
+ \return recommended dockable widget size
+*/
+QSize QtxDockWidget::sizeHint() const
+{
+ QSize sz = QDockWidget::sizeHint();
+/*
+ if ( place() == InDock && isStretchable() && area() )
+ {
+ if ( orientation() == Horizontal )
+ sz.setWidth( area()->width() );
+ else
+ sz.setHeight( area()->height() );
+ }
+*/
+ return sz;
+}
+
+/*!
+ \brief Get the recommended minimum size for the widget.
+ \return recommended dockable widget minimum size
+*/
+QSize QtxDockWidget::minimumSizeHint() const
+{
+ QSize sz = QDockWidget::minimumSizeHint();
+/*
+ if ( orientation() == Horizontal )
+ sz = QSize( 0, QDockWidget::minimumSizeHint().height() );
+ else
+ sz = QSize( QDockWidget::minimumSizeHint().width(), 0 );
+
+ if ( place() == InDock && isStretchable() && area() )
+ {
+ if ( orientation() == Horizontal )
+ sz.setWidth( area()->width() );
+ else
+ sz.setHeight( area()->height() );
+ }
+*/
+ return sz;
+}
+
+/*!
+ \brief Show/hide the dockable window.
+ \param on new visibility state
+*/
+void QtxDockWidget::setVisible( bool on )
+{
+ if ( myWatcher )
+ {
+ if ( on )
+ myWatcher->shown( this );
+ else
+ myWatcher->hidden( this );
+ }
+
+ updateGeometry();
+ if ( widget() )
+ widget()->updateGeometry();
+
+ QDockWidget::setVisible( on );
+}
+
+/*!
+ \brief Process resize event
+ \param e event
+*/
+void QtxDockWidget::resizeEvent( QResizeEvent* e )
+{
+ QDockWidget::resizeEvent( e );
+ updateState();
+}
+
+/*!
+ \brief Get dockable window orientation.
+ \return orientation type
+*/
+Qt::Orientation QtxDockWidget::orientation() const
+{
+ QMainWindow* mw = 0;
+ QWidget* wid = parentWidget();
+ while ( wid && !mw )
+ {
+ mw = ::qobject_cast<QMainWindow*>( wid );
+ wid = wid->parentWidget();
+ }
+
+ Qt::Orientation res = (Qt::Orientation)-1;
+
+ if ( !mw )
+ return res;
+
+ Qt::DockWidgetArea area = mw->dockWidgetArea( (QtxDockWidget*)this );
+ switch ( area )
+ {
+ case Qt::LeftDockWidgetArea:
+ case Qt::RightDockWidgetArea:
+ res = Qt::Vertical;
+ break;
+ case Qt::TopDockWidgetArea:
+ case Qt::BottomDockWidgetArea:
+ res = Qt::Horizontal;
+ break;
+ default:
+ break;
+ }
+
+ return res;
+}
+
+/*!
+ \brief Update dockable window state.
+*/
+void QtxDockWidget::updateState()
+{
+ Qt::Orientation o = orientation();
+ if ( myOrientation == o )
+ return;
+
+ myOrientation = o;
+
+ emit orientationChanged( myOrientation );
+}
+
+/*!
+ \fn QtxDockWidget::orientationChanged(Qt::Orientation o)
+ \brief Emitted when the dockable window orientation is changed.
+ \param o new window orientation
+*/
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File: QtxDockWidget.h
+// Author: Sergey TELKOV
+
+#include "Qtx.h"
+
+#include <QDockWidget>
+
+class QTX_EXPORT QtxDockWidget : public QDockWidget
+{
+ Q_OBJECT
+
+ class Watcher;
+
+public:
+ QtxDockWidget( const QString&, QWidget* = 0, Qt::WindowFlags = 0 );
+ QtxDockWidget( const bool, QWidget* = 0, Qt::WindowFlags = 0 );
+ QtxDockWidget( QWidget*, Qt::WindowFlags = 0 );
+ virtual ~QtxDockWidget();
+
+ virtual QSize sizeHint() const;
+ virtual QSize minimumSizeHint() const;
+
+ Qt::Orientation orientation() const;
+
+signals:
+ void orientationChanged( Qt::Orientation );
+
+public slots:
+ virtual void setVisible( bool );
+
+protected:
+ virtual void resizeEvent( QResizeEvent* );
+
+private:
+ void updateState();
+
+private:
+ Watcher* myWatcher; //!< watcher object
+ Qt::Orientation myOrientation; //!< dockable window orientation
+};
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-// File: QtxDockWindow.cxx
-// Author: Sergey TELKOV
-
-#include "QtxDockWindow.h"
-
-#include <qlayout.h>
-#include <qpixmap.h>
-#include <qdockarea.h>
-#include <qmainwindow.h>
-#include <qapplication.h>
-
-/*!
- \class QtxDockWindow::Watcher [Internal]
- Internal object with event filter.
-*/
-class QtxDockWindow::Watcher : public QObject
-{
-public:
- Watcher( QtxDockWindow* );
-
- void shown( QtxDockWindow* );
- void hided( QtxDockWindow* );
-
- virtual bool eventFilter( QObject*, QEvent* );
-
-protected:
- virtual void customEvent( QCustomEvent* );
-
-private:
- void installFilters();
-
- void showContainer();
- void hideContainer();
-
- void updateIcon();
- void updateCaption();
- void updateVisibility();
-
-private:
- QtxDockWindow* myCont;
- bool myState;
- bool myEmpty;
- bool myVisible;
-};
-
-/*!
- Constructor
-*/
-QtxDockWindow::Watcher::Watcher( QtxDockWindow* cont )
-: QObject( cont ), myCont( cont ),
-myState( true ),
-myEmpty( true )
-{
- if ( myCont->mainWindow() )
- myState = myCont->mainWindow()->appropriate( myCont );
-
- myCont->installEventFilter( this );
- myVisible = myCont->isVisibleTo( myCont->parentWidget() );
-
- installFilters();
-}
-
-/*!
- Custom event filter
-*/
-bool QtxDockWindow::Watcher::eventFilter( QObject* o, QEvent* e )
-{
- if ( o == myCont &&
- ( e->type() == QEvent::Show || e->type() == QEvent::ShowToParent ||
- e->type() == QEvent::Hide || e->type() == QEvent::HideToParent ||
- e->type() == QEvent::ChildInserted ) )
- QApplication::postEvent( this, new QCustomEvent( QEvent::User ) );
-
- if ( o != myCont && e->type() == QEvent::IconChange )
- updateIcon();
-
- if ( o != myCont && e->type() == QEvent::CaptionChange )
- updateCaption();
-
- if ( ( o != myCont && ( e->type() == QEvent::Hide || e->type() == QEvent::HideToParent ) ) ||
- ( o == myCont && ( e->type() == QEvent::ChildRemoved ) ) ||
- ( e->type() == QEvent::Show || e->type() == QEvent::ShowToParent ) )
- updateVisibility();
-
- return false;
-}
-
-/*!
- Sets internal status to shown
-*/
-void QtxDockWindow::Watcher::shown( QtxDockWindow* dw )
-{
- if ( dw != myCont )
- return;
-
- myVisible = true;
-}
-
-/*!
- Sets internal status to hidden
-*/
-void QtxDockWindow::Watcher::hided( QtxDockWindow* dw )
-{
- if ( dw != myCont )
- return;
-
- myVisible = false;
-}
-
-/*!
- Shows corresponding dock window
-*/
-void QtxDockWindow::Watcher::showContainer()
-{
- if ( !myCont )
- return;
-
- QtxDockWindow* cont = myCont;
- myCont = 0;
- cont->show();
- myCont = cont;
-}
-
-/*!
- Hides corresponding dock window
-*/
-void QtxDockWindow::Watcher::hideContainer()
-{
- if ( !myCont )
- return;
-
- QtxDockWindow* cont = myCont;
- myCont = 0;
- cont->hide();
- myCont = cont;
-}
-
-/*!
- Event filter of custom events
-*/
-void QtxDockWindow::Watcher::customEvent( QCustomEvent* e )
-{
- installFilters();
-
- updateIcon();
- updateCaption();
- updateVisibility();
-}
-
-/*!
- Installs this object as event filter to all widgets inside corresponding main window
-*/
-void QtxDockWindow::Watcher::installFilters()
-{
- if ( !myCont )
- return;
-
- QBoxLayout* bl = myCont->boxLayout();
- if ( !bl )
- return;
-
- for ( QLayoutIterator it = bl->iterator(); it.current(); ++it )
- {
- if ( it.current()->widget() )
- it.current()->widget()->installEventFilter( this );
- }
-}
-
-/*!
- Updates visibility of all widgets inside corresponding main window
-*/
-void QtxDockWindow::Watcher::updateVisibility()
-{
- if ( !myCont )
- return;
-
- QBoxLayout* bl = myCont->boxLayout();
- if ( !bl )
- return;
-
- bool vis = false;
- for ( QLayoutIterator it = bl->iterator(); it.current() && !vis; ++it )
- vis = it.current()->widget() && it.current()->widget()->isVisibleTo( myCont );
-
- QMainWindow* mw = myCont->mainWindow();
- if ( mw && myEmpty == vis )
- {
- myEmpty = !vis;
- if ( !myEmpty )
- mw->setAppropriate( myCont, myState );
- else
- {
- myState = mw->appropriate( myCont );
- mw->setAppropriate( myCont, false );
- }
- }
-
- vis = !myEmpty && myVisible;
- if ( vis != myCont->isVisibleTo( myCont->parentWidget() ) )
- vis ? showContainer() : hideContainer();
-}
-
-/*!
- Updates icon of corresponding main window
-*/
-void QtxDockWindow::Watcher::updateIcon()
-{
- if ( !myCont || !myCont->widget() )
- return;
-
- const QPixmap* ico = myCont->widget()->icon();
- myCont->setIcon( ico ? *ico : QPixmap() );
-}
-
-/*!
- Updates caption of corresponding main window
-*/
-void QtxDockWindow::Watcher::updateCaption()
-{
- if ( myCont && myCont->widget() && !myCont->widget()->caption().isNull() )
- myCont->setCaption( myCont->widget()->caption() );
-}
-
-/*!
- Constructor
-*/
-QtxDockWindow::QtxDockWindow( Place p, QWidget* parent, const char* name, WFlags f )
-: QDockWindow( p, parent, name, f ),
-myWatcher( 0 ),
-myStretch( false )
-{
-}
-
-/*!
- Constructor
-*/
-QtxDockWindow::QtxDockWindow( const bool watch, QWidget* parent, const char* name, WFlags f )
-: QDockWindow( InDock, parent, name, f ),
-myWatcher( 0 ),
-myStretch( false )
-{
- if ( watch )
- myWatcher = new Watcher( this );
-}
-
-/*!
- Constructor
-*/
-QtxDockWindow::QtxDockWindow( QWidget* parent, const char* name, WFlags f )
-: QDockWindow( InDock, parent, name, f ),
-myWatcher( 0 ),
-myStretch( false )
-{
-}
-
-/*!
- Destructor
-*/
-QtxDockWindow::~QtxDockWindow()
-{
-}
-
-/*!
- Sets the dock window's main widget
- \param wid - new main widget
-*/
-void QtxDockWindow::setWidget( QWidget* wid )
-{
- if ( wid )
- {
- if ( wid->parentWidget() != this )
- wid->reparent( this, QPoint( 0, 0 ), wid->isVisibleTo( wid->parentWidget() ) );
- if ( myWatcher )
- {
- setCaption( wid->caption() );
- if ( wid->icon() )
- setIcon( *wid->icon() );
- }
- }
-
- QDockWindow::setWidget( wid );
-}
-
-/*!
- \return true if the dock window is stretchable
-*/
-bool QtxDockWindow::isStretchable() const
-{
- return myStretch;
-}
-
-/*!
- Sets the dock window "stretchable" state
- \param on - new state
-*/
-void QtxDockWindow::setStretchable( const bool on )
-{
- if ( myStretch == on )
- return;
-
- myStretch = on;
-
- boxLayout()->setStretchFactor( widget(), myStretch ? 1 : 0 );
-
- if ( myStretch != isHorizontalStretchable() ||
- myStretch != isVerticalStretchable() )
- {
- if ( orientation() == Horizontal )
- setHorizontalStretchable( myStretch );
- else
- setVerticalStretchable( myStretch );
- }
-}
-
-/*!
- \return the recommended size for the widget
-*/
-QSize QtxDockWindow::sizeHint() const
-{
- QSize sz = QDockWindow::sizeHint();
-
- if ( place() == InDock && isStretchable() && area() )
- {
- if ( orientation() == Horizontal )
- sz.setWidth( area()->width() );
- else
- sz.setHeight( area()->height() );
- }
-
- return sz;
-}
-
-/*!
- \return the recommended minimum size for the widget
-*/
-QSize QtxDockWindow::minimumSizeHint() const
-{
- QSize sz = QDockWindow::minimumSizeHint();
-
- if ( orientation() == Horizontal )
- sz = QSize( 0, QDockWindow::minimumSizeHint().height() );
- else
- sz = QSize( QDockWindow::minimumSizeHint().width(), 0 );
-
- if ( place() == InDock && isStretchable() && area() )
- {
- if ( orientation() == Horizontal )
- sz.setWidth( area()->width() );
- else
- sz.setHeight( area()->height() );
- }
-
- return sz;
-}
-
-/*!
- \return corresponding main window
-*/
-QMainWindow* QtxDockWindow::mainWindow() const
-{
- QMainWindow* mw = 0;
-
- QWidget* wid = parentWidget();
- while ( !mw && wid )
- {
- if ( wid->inherits( "QMainWindow" ) )
- mw = (QMainWindow*)wid;
- wid = wid->parentWidget();
- }
-
- return mw;
-}
-
-/*!
- Shows window
-*/
-void QtxDockWindow::show()
-{
- if ( myWatcher )
- myWatcher->shown( this );
-
- QDockWindow::show();
-}
-
-/*!
- Hides window
-*/
-void QtxDockWindow::hide()
-{
- if ( myWatcher )
- myWatcher->hided( this );
-
- QDockWindow::hide();
-}
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-// File: QtxDockWindow.h
-// Author: Sergey TELKOV
-
-#include "Qtx.h"
-
-#include <qdockwindow.h>
-
-class QTX_EXPORT QtxDockWindow : public QDockWindow
-{
- Q_OBJECT
-
- class Watcher;
-
-public:
- QtxDockWindow( Place = InDock, QWidget* = 0, const char* = 0, WFlags = 0 );
- QtxDockWindow( const bool, QWidget*, const char* = 0, WFlags = 0 );
- QtxDockWindow( QWidget*, const char* = 0, WFlags = 0 );
- virtual ~QtxDockWindow();
-
- virtual void setWidget( QWidget* );
-
- bool isStretchable() const;
- virtual void setStretchable( const bool );
-
- virtual QSize sizeHint() const;
- virtual QSize minimumSizeHint() const;
-
- QMainWindow* mainWindow() const;
-
-public slots:
- virtual void show();
- virtual void hide();
-
-private:
- Watcher* myWatcher;
- bool myStretch;
-};
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File: QtxDoubleSpinBox.cxx
+// Author: Sergey TELKOV
+
+#include "QtxDoubleSpinBox.h"
+
+#include <QLineEdit>
+
+/*!
+ \class QtxDoubleSpinBox
+ \brief Enhanced version of the Qt's double spin box.
+
+ The QtxDoubleSpinBox class represents the widget for entering the
+ floating point values. In addition to the functionality provided by
+ QDoubleSpinBox, this class supports "cleared" state - this is the
+ state corresponding to "None" (or empty) entered value.
+
+ To set "cleared" state use setCleared() method. To check if the spin
+ box stores "cleared" state, use isCleared() method.
+ For example:
+ \code
+ if (myDblSpinBox->isCleared()) {
+ ... // process "None" state
+ }
+ else {
+ double value = myDblSpinBox->value();
+ ... // process entered value
+ }
+ \endcode
+*/
+
+/*!
+ \brief Constructor.
+
+ Constructs a spin box with 0.0 as minimum value and 99.99 as maximum value,
+ a step value of 1.0 and a precision of 2 decimal places.
+ The value is initially set to 0.00.
+
+ \param parent parent object
+*/
+QtxDoubleSpinBox::QtxDoubleSpinBox( QWidget* parent )
+: QDoubleSpinBox( parent ),
+ myCleared( false )
+{
+ connect( lineEdit(), SIGNAL( textChanged( const QString& ) ),
+ this, SLOT( onTextChanged( const QString& ) ) );
+}
+
+/*!
+ \brief Constructor.
+
+ Constructs a spin box with specified minimum, maximum and step value.
+ The precision is set to 2 decimal places.
+ The value is initially set to the minimum value.
+
+ \param min spin box minimum possible value
+ \param max spin box maximum possible value
+ \param step spin box increment/decrement value
+ \param parent parent object
+*/
+QtxDoubleSpinBox::QtxDoubleSpinBox( double min, double max, double step, QWidget* parent )
+: QDoubleSpinBox( parent ),
+ myCleared( false )
+{
+ setMinimum( min );
+ setMaximum( max );
+ setSingleStep( step );
+
+ connect( lineEdit(), SIGNAL( textChanged( const QString& ) ),
+ this, SLOT( onTextChanged( const QString& ) ) );
+}
+
+/*!
+ \brief Destructor.
+*/
+QtxDoubleSpinBox::~QtxDoubleSpinBox()
+{
+}
+
+/*!
+ \brief Check if spin box is in the "cleared" state.
+ \return \c true if spin box is cleared
+*/
+bool QtxDoubleSpinBox::isCleared() const
+{
+ return myCleared;
+}
+
+/*!
+ \brief Change "cleared" status of the spin box.
+ \param on new "cleared" status
+*/
+void QtxDoubleSpinBox::setCleared( const bool on )
+{
+ if ( myCleared == on )
+ return;
+
+ myCleared = on;
+ setSpecialValueText( specialValueText() );
+}
+
+/*!
+ \brief Convert value to the text.
+ \param val value being converted
+ \return string containing the converted value
+*/
+QString QtxDoubleSpinBox::textFromValue( double val ) const
+{
+ return myCleared ? QString() : QDoubleSpinBox::textFromValue( val );
+}
+
+/*!
+ \brief Perform \a steps increment/decrement steps.
+
+ The \a steps value can be any integer number. If it is > 0,
+ the value incrementing is done, otherwise value is decremented
+ \a steps times.
+
+ \param steps number of increment/decrement steps
+*/
+void QtxDoubleSpinBox::stepBy( int steps )
+{
+ myCleared = false;
+
+ QDoubleSpinBox::stepBy( steps );
+}
+
+/*!
+ \brief Called when user enters the text in the spin box.
+ \param txt current spin box text (not used)
+*/
+void QtxDoubleSpinBox::onTextChanged( const QString& /*txt*/ )
+{
+ myCleared = false;
+}
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File: QtxDoubleSpinBox.h
+// Author: Sergey TELKOV
+
+#ifndef QTXDOUBLESPINBOX_H
+#define QTXDOUBLESPINBOX_H
+
+#include "Qtx.h"
+
+#include <QDoubleSpinBox>
+
+class QTX_EXPORT QtxDoubleSpinBox : public QDoubleSpinBox
+{
+ Q_OBJECT
+
+public:
+ QtxDoubleSpinBox( QWidget* = 0 );
+ QtxDoubleSpinBox( double, double, double = 1, QWidget* = 0 );
+ virtual ~QtxDoubleSpinBox();
+
+ bool isCleared() const;
+ virtual void setCleared( const bool );
+
+ virtual void stepBy( int );
+
+private slots:
+ virtual void onTextChanged( const QString& );
+
+protected:
+ virtual QString textFromValue( double ) const;
+
+private:
+ bool myCleared;
+};
+
+#endif
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+
+#include "QtxEvalExpr.h"
+
+#include <QStack>
+
+#include <math.h>
+
+/*!
+ \class QtxEvalExpr
+ \brief String expression evaluator.
+*/
+
+/*!
+ \brief Constructor.
+
+ The evaluator is initalized by standard operations. Use another constructor with parameter
+ \a stdSets = \c false to avoid initialization of evaluator with standard operations.
+
+ \param expr expression to be evaluated
+*/
+QtxEvalExpr::QtxEvalExpr( const QString& expr )
+{
+ intialize( true, expr );
+}
+
+/*!
+ \brief Constructor.
+ \param stdSets if \c true, the evaluator is initalized by standard operations
+ \param expr expression to be evaluated
+*/
+QtxEvalExpr::QtxEvalExpr( const bool stdSets, const QString& expr )
+{
+ intialize( stdSets, expr );
+}
+
+/*!
+ \brief Destructor.
+*/
+QtxEvalExpr::~QtxEvalExpr()
+{
+ delete myParser;
+}
+
+/*!
+ \brief Initialize the evaluator.
+ \param stdSets if \c true, the evaluator is initalized by standard operations
+ \param expr expression to be evaluated
+*/
+void QtxEvalExpr::intialize( const bool stdSets, const QString& expr )
+{
+ myParser = new QtxEvalParser();
+ if ( stdSets )
+ {
+ myParser->setAutoDeleteOperationSets( true );
+ myParser->insertOperationSet( new QtxEvalSetArithmetic() );
+ myParser->insertOperationSet( new QtxEvalSetLogic() );
+ myParser->insertOperationSet( new QtxEvalSetString() );
+ myParser->insertOperationSet( new QtxEvalSetMath() );
+ myParser->insertOperationSet( new QtxEvalSetSets() );
+ myParser->insertOperationSet( new QtxEvalSetConst() );
+ }
+ setExpression( expr );
+}
+
+/*!
+ \brief Evaluate the expression.
+ \param expr expression to be evaluated
+ \return result of the evaluation
+*/
+QVariant QtxEvalExpr::calculate( const QString& expr )
+{
+ if ( !expr.isEmpty() )
+ setExpression( expr );
+ return myParser->calculate();
+}
+
+/*!
+ \brief Get the expression.
+ \return expression string
+*/
+QString QtxEvalExpr::expression() const
+{
+ return myExpr;
+}
+
+/*!
+ \brief Set the expression.
+ \param expr expression string
+*/
+void QtxEvalExpr::setExpression( const QString& expr )
+{
+ if ( expr == expression() )
+ return;
+
+ myExpr = expr;
+ myParser->setExpression( myExpr );
+}
+
+/*!
+ \brief Get the code of latest parsing error.
+ \return the code of the last error
+*/
+QtxEvalExpr::Error QtxEvalExpr::error() const
+{
+ return myParser->error();
+}
+
+/*!
+ \brief Get the expression parser.
+ \return expression parser
+*/
+QtxEvalParser* QtxEvalExpr::parser() const
+{
+ return myParser;
+}
+
+/*!
+ \brief Get current set of operations.
+ \return operations set
+ \sa insertOperationSet(), removeOperationSet(), operationSet()
+*/
+QList<QtxEvalSet*> QtxEvalExpr::operationSets() const
+{
+ return myParser->operationSets();
+}
+
+/*!
+ \brief Install the operation.
+ \param operation to be added
+ \param idx index in the list at which the operation shoud be inserted
+ \sa operationSets(), removeOperationSet(), operationSet()
+*/
+void QtxEvalExpr::insertOperationSet( QtxEvalSet* set, const int idx )
+{
+ myParser->insertOperationSet( set, idx );
+}
+
+/*!
+ \brief Remove the operation.
+ \param operation to be removed
+ \sa operationSets(), insertOperationSet(), operationSet()
+*/
+void QtxEvalExpr::removeOperationSet( QtxEvalSet* set )
+{
+ myParser->removeOperationSet( set );
+}
+
+/*!
+ \brief Get the operation by name.
+ \param name operation name
+ \return operation of 0 if not found
+ \sa operationSets(), insertOperationSet(), removeOperationSet()
+*/
+QtxEvalSet* QtxEvalExpr::operationSet( const QString& name ) const
+{
+ return myParser->operationSet( name );
+}
+
+/*!
+ \brief Get the 'auto-delete operations' flag value.
+ \return \c true if all operations shoud be automatically deleted when the evaluator is destroyed
+ \sa setAutoDeleteOperationSets()
+*/
+bool QtxEvalExpr::autoDeleteOperationSets() const
+{
+ return myParser->autoDeleteOperationSets();
+}
+
+/*!
+ \brief Set the 'auto-delete operations' flag value.
+ \param on if \c true, all operations shoud be automatically deleted when the evaluator is destroyed
+ \sa autoDeleteOperationSets()
+*/
+void QtxEvalExpr::setAutoDeleteOperationSets( const bool on )
+{
+ myParser->setAutoDeleteOperationSets( on );
+}
+
+/*!
+ \class QtxEvalParser
+ \brief Expression parser.
+
+ This class provides the functionality to calculate value of the expression using defined set of operations.
+ Standard operations (arithmetics, logic, strings, etc) are implemented in the corresponding successors of the
+ QtxEvalSet class: QtxEvalSetArithmetic, QtxEvalSetLogic, QtxEvalSetMath, QtxEvalSetString, ...
+
+ The parser allows using parameters with help of methods has(), set(), remove(), value(). It uses
+ postfix representation of expressions and uses class QtxEvalSet in order to make certain operation.
+
+ Every instance of parser contains only one postfix - thus, if the expression is changed, the postfix
+ must be rebuilt. In order to increase performance of frequent calculations for many of expressions it is
+ recommended to use different instances of the parser for each expression.
+*/
+
+/*!
+ \brief Constructor.
+*/
+QtxEvalParser::QtxEvalParser()
+: myAutoDel( false )
+{
+ setError( QtxEvalExpr::OK );
+}
+
+/*!
+ \brief Destructor.
+*/
+QtxEvalParser::~QtxEvalParser()
+{
+ if ( autoDeleteOperationSets() )
+ qDeleteAll( mySets );
+}
+
+/*!
+ \brief Get current operations set.
+ \return current operations set
+*/
+QList<QtxEvalSet*> QtxEvalParser::operationSets() const
+{
+ return mySets;
+}
+
+/*!
+ \brief Get the operations set by \a name.
+ \param name the name of the operation set
+ \return operation set or 0 if not found
+*/
+QtxEvalSet* QtxEvalParser::operationSet( const QString& name ) const
+{
+ QtxEvalSet* set = 0;
+ for ( SetList::const_iterator it = mySets.begin(); it != mySets.end() && !set; ++it )
+ {
+ if ( (*it)->name() == name )
+ set = *it;
+ }
+ return set;
+}
+
+/*!
+ \brief Install the operations set.
+ \param operations set to be added
+ \param idx index in the list at which the operations set shoud be inserted
+ \sa operationSets(), removeOperationSet(), operationSet()
+*/
+void QtxEvalParser::insertOperationSet( QtxEvalSet* set, const int idx )
+{
+ if ( mySets.contains( set ) )
+ return;
+
+ int index = idx < 0 ? mySets.count() - 1 : idx;
+ index = qMin( index, mySets.count() - 1 );
+ mySets.insert( index, set );
+}
+
+/*!
+ \brief Remove the operations set.
+ \param operations set to be removed
+ \sa operationSets(), insertOperationSet(), operationSet()
+*/
+void QtxEvalParser::removeOperationSet( QtxEvalSet* set )
+{
+ mySets.removeAll( set );
+}
+
+/*!
+ \brief Get the 'auto-delete operations' flag value.
+ \return \c true if all operations shoud be automatically deleted when the parser is destroyed
+ \sa setAutoDeleteOperationSets()
+*/
+bool QtxEvalParser::autoDeleteOperationSets() const
+{
+ return myAutoDel;
+}
+
+/*!
+ \brief Set the 'auto-delete operations' flag value.
+ \param on if \c true, all operations shoud be automatically deleted when the parser is destroyed
+ \sa autoDeleteOperationSets()
+*/
+void QtxEvalParser::setAutoDeleteOperationSets( const bool on )
+{
+ myAutoDel = on;
+}
+
+/*!
+ \brief Search elements of the list as substrings starting from \a offset.
+ \param list list of substrings
+ \param str string in which the searching is performed
+ \param offset starting index for search
+ \param matchLen returning matching length of any substring
+ \param listind returning index of the found substring in the \a list
+ \return position of first found substring inside the \a str or -1 if no matches is found
+*/
+int QtxEvalParser::search( const QStringList& list, const QString& str,
+ int offset, int& matchLen, int& listind )
+{
+ int min = -1;
+ QStringList::const_iterator anIt = list.begin(), aLast = list.end();
+ for ( int ind = 0; anIt != aLast; anIt++, ind++ )
+ {
+ int pos = str.indexOf( *anIt, offset );
+ if ( pos >= 0 && ( min < 0 || min > pos ||
+ ( min == pos && matchLen < (int)(*anIt).length() ) ) )
+ {
+ min = pos;
+ listind = ind;
+ matchLen = (*anIt).length();
+ }
+ }
+ if ( min < 0 )
+ matchLen = 0;
+ return min;
+}
+
+/*!
+ \brief Get the substring field from the string \a str.
+ \param str source string
+ \param pos start position of the substring
+ \param len length of the substring
+ \return substring (leading and trailing spaces are truncated)
+*/
+QString QtxEvalParser::note( const QString& str, int pos, int len )
+{
+ return str.mid( pos, len ).trimmed();
+}
+
+/*!
+ \brief Prepare to the parsing.
+
+ Performs the first step of the parsing:
+ - find tokens
+ - determine tokens types
+ - create unsorted pseudo-postfix (with brackets)
+
+ \param expr string expression
+ \param post postfix to be created
+ \return \c true on success and \c false if error is found
+*/
+bool QtxEvalParser::prepare( const QString& expr, Postfix& post )
+{
+ int pos = 0;
+ int len = expr.length();
+ QStack<int> aBracketStack;
+ QStringList anOpers, anOpenBr, aCloseBr;
+ if ( !checkOperations() )
+ return false;
+
+ bracketsList( anOpenBr, true );
+ bracketsList( aCloseBr, false );
+ operationList( anOpers );
+
+ while ( pos < len && error() == QtxEvalExpr::OK )
+ {
+ PostfixItem item;
+ while ( expr[pos].isSpace() && pos < len )
+ pos++;
+ if ( pos >= len )
+ break;
+
+ int mBrLen = 0, mLen = 0, br_ind = -1, op_ind = -1;
+ int oPos = search( anOpenBr, expr, pos, mBrLen, br_ind );
+ int cPos = oPos == pos ? -1 : search( aCloseBr, expr, pos, mBrLen, br_ind );
+ int opPos = search( anOpers, expr, pos, mLen, op_ind );
+
+ if ( expr[pos] == QChar( '\'' ) )
+ {
+ int vpos = pos + 1;
+ while ( vpos < (int)expr.length() && expr[vpos] != QChar( '\'' ) )
+ vpos++;
+
+ mLen = vpos - pos + 1;
+
+ int res = createValue( note( expr, pos, mLen ), item.myValue );
+ item.myType = res ? Value : Param;
+ post.append( item );
+ pos = vpos + 1;
+ continue;
+ }
+
+ if ( oPos == pos )
+ {
+ aBracketStack.push( br_ind );
+ item.myValue = note( expr, pos, mBrLen );
+ item.myType = Open;
+ post.append( item );
+ }
+ else if ( cPos == pos )
+ {
+ if ( aBracketStack.count() == 0 )
+ {
+ setError( QtxEvalExpr::ExcessClose );
+ break;
+ }
+ if ( br_ind != aBracketStack.top() )
+ {
+ setError( QtxEvalExpr::BracketsNotMatch );
+ break;
+ }
+ else
+ {
+ aBracketStack.pop();
+ item.myValue = note( expr, pos, mBrLen );
+ item.myType = Close;
+ post.append( item );
+ }
+ }
+ else
+ mBrLen = 0;
+
+ if ( opPos == pos )
+ {
+ mBrLen = 0;
+ item.myValue = note( expr, pos, mLen );
+ item.myType = Binary;
+
+ if ( oPos == pos )
+ post.insert( post.count() - 1, item );
+ else
+ post.append( item );
+ }
+ else
+ {
+ mLen = 0;
+ if ( oPos != pos && cPos != pos )
+ {
+ int i;
+ for ( i = pos + 1; i < (int)expr.length(); i++ )
+ {
+ if ( expr[i].isSpace() )
+ break;
+ }
+
+ int vpos = i;
+ if ( oPos >= 0 && oPos < vpos )
+ vpos = oPos;
+ if ( cPos >= 0 && cPos < vpos )
+ vpos = cPos;
+ if ( opPos >= 0 && opPos < vpos )
+ vpos = opPos;
+
+ while( vpos < (int)expr.length() &&
+ ( expr[vpos].isLetter() || expr[vpos].isDigit() || expr[vpos]=='_' ) )
+ vpos++;
+
+ mLen = vpos - pos;
+ bool res = createValue( note( expr, pos, mLen ), item.myValue );
+ item.myType = res ? Value : Param;
+ post.append( item );
+ }
+ }
+
+ pos += mBrLen + mLen;
+ }
+
+ //Bracket checking
+ int brValue = 0;
+ for ( Postfix::iterator anIt = post.begin(); anIt != post.end(); ++anIt )
+ {
+ if ( (*anIt).myType == Open )
+ brValue++;
+ else if ( (*anIt).myType == Close )
+ {
+ if ( brValue > 0 )
+ brValue--;
+ else
+ {
+ setError( QtxEvalExpr::ExcessClose );
+ break;
+ }
+ }
+ }
+
+ if ( brValue > 0 )
+ setError( QtxEvalExpr::CloseExpected );
+
+ return error() == QtxEvalExpr::OK;
+}
+
+/*!
+ \brief Analyze the operations used.
+
+ Second step of the parsing: analyze the types of the operations used in the expression.
+
+ \param post unsorted postfix
+ \return \c true on success and \c false if error is found
+*/
+bool QtxEvalParser::setOperationTypes( Postfix& post )
+{
+ if ( !checkOperations() )
+ return false;
+
+ QStringList anOpen, aClose;
+ bracketsList( anOpen, true );
+ bracketsList( aClose, false );
+
+ Postfix::iterator aPrev, aNext;
+ for ( Postfix::iterator anIt = post.begin(); anIt != post.end(); ++anIt )
+ {
+ aPrev = anIt;
+ aPrev--;
+ aNext = anIt;
+ aNext++;
+ if ( (*anIt).myType != Binary )
+ continue;
+
+ if ( ( anIt == post.begin() || (*aPrev).myType == Open ||
+ (*aPrev).myType == Pre || (*aPrev).myType == Binary ) && aNext != post.end() &&
+ ( (*aNext).myType == Value || (*aNext).myType == Param ||
+ (*aNext).myType == Open || (*aNext).myType == Binary ) )
+ (*anIt).myType = Pre;
+ else if ( anIt != post.begin() && ( (*aPrev).myType == Close || (*aPrev).myType == Param ||
+ (*aPrev).myType == Value || (*aPrev).myType == Pre ||
+ (*aPrev).myType == Post || (*aPrev).myType == Binary ) &&
+ ( aNext == post.end() || (*aNext).myType == Close ) )
+ (*anIt).myType = Post;
+
+ if ( anOpen.contains( (*anIt).myValue.toString() ) )
+ (*anIt).myType = Pre;
+ else if ( aClose.contains( (*anIt).myValue.toString() ) )
+ (*anIt).myType = Post;
+ }
+
+ return error() == QtxEvalExpr::OK;
+}
+
+/*!
+ \brief Get the number of the globar brackets pairs.
+
+ For example, the expression '((2+3))' has 2 global brackets pairs.
+
+ \param post postfix to be checked
+ \param f starting position for the search
+ \param l last position for the search
+ \return number of brackets pairs
+*/
+int QtxEvalParser::globalBrackets( const QtxEvalParser::Postfix& post, int f, int l )
+{
+ int i;
+ int start_br = 0;
+ int fin_br = 0;
+ int br = 0;
+ int br_num = 0;
+ int min_br_num = (l-f+1)*5;
+
+ for( i=f; i<=l; i++ )
+ if( post[ i ].myType==QtxEvalParser::Open )
+ start_br++;
+ else
+ break;
+ for( i=l; i>=f; i-- )
+ if( post[ i ].myType==QtxEvalParser::Close )
+ fin_br++;
+ else
+ break;
+
+ br = start_br<fin_br ? start_br : fin_br;
+ for( i=f+br; i<=l-br; i++ )
+ {
+ if( post[i].myType==QtxEvalParser::Open )
+ br_num++;
+ else if( post[i].myType==QtxEvalParser::Close )
+ br_num--;
+ if( br_num<min_br_num )
+ min_br_num = br_num;
+ }
+
+ return br+min_br_num;
+}
+
+/*!
+ \brief Sort the operations in the postfix.
+
+ Third step of parsing: sort the postfix operations in order to convert it to real postfix.
+
+ \param post source postfix
+ \param res returning resulting postfix
+ \param anOpen list of open brackets
+ \param aClose list of close brackets
+ \param f start index of postfix for sorting
+ \param l last index of postfix for sorting
+ \return \c true on success and \c false if error is found
+*/
+bool QtxEvalParser::sort( const Postfix& post, Postfix& res, const QStringList& anOpen,
+ const QStringList& aClose, int f, int l )
+{
+ if ( l < f )
+ return true;
+
+ if ( f < 0 )
+ f = 0;
+
+ if ( l < 0 )
+ l = post.count() - 1;
+
+ int br = globalBrackets( post, f, l );
+ f += br;
+ l -= br;
+
+ if ( f == l && f >= 0 )
+ res.append( post[f] );
+
+ if ( l <= f )
+ return true;
+
+ if ( !checkOperations() )
+ return false;
+
+ int min = -1;
+ QIntList argmin;
+ QList<PostfixItemType> min_types;
+
+ for ( int i = 0, j = f; j <= l; i++, j++ )
+ {
+ const PostfixItem& item = post[j];
+ PostfixItemType tt = item.myType;
+ if ( tt == Binary || tt == Pre || tt == Post )
+ {
+ int cur_pr = priority( item.myValue.toString(), tt == Binary );
+ if ( cur_pr > 0 )
+ {
+ if ( min < 0 || min >= cur_pr )
+ {
+ if ( min == cur_pr )
+ {
+ argmin.append( f + i );
+ min_types.append( tt );
+ }
+ else
+ {
+ min = cur_pr;
+ argmin.clear();
+ argmin.append( f + i );
+ min_types.clear(); min_types.append( tt );
+ }
+ }
+ }
+ else
+ {
+ setError( QtxEvalExpr::InvalidOperation );
+ break;
+ }
+ }
+ else if ( tt == Open )
+ {
+ QString opBr = item.myValue.toString();
+ int ind = anOpen.indexOf( opBr ), brValue = 0;
+ while ( j <= l )
+ {
+ const PostfixItem& anItem = post[j];
+ if ( anItem.myType == Open )
+ brValue++;
+
+ if ( anItem.myType == Close )
+ {
+ brValue--;
+ QString clBr = anItem.myValue.toString();
+ if ( aClose.indexOf( clBr ) == ind && brValue == 0 )
+ break;
+ }
+ i++; j++;
+ }
+
+ if ( brValue > 0 )
+ {
+ setError( QtxEvalExpr::CloseExpected );
+ break;
+ }
+ }
+ }
+
+ if ( error() == QtxEvalExpr::OK )
+ {
+ if ( min >= 0 )
+ {
+ Postfix one;
+ QList<Postfix> parts;
+ QIntList::const_iterator anIt = argmin.begin(), aLast = argmin.end();
+ bool ok = sort( post, one, anOpen, aClose, f, *anIt - 1 );
+ parts.append( one );
+ one.clear();
+ for ( ; anIt != aLast && ok; anIt++ )
+ {
+ QIntList::const_iterator aNext = anIt; aNext++;
+ ok = sort( post, one, anOpen, aClose, *anIt + 1, aNext == aLast ? l : *aNext - 1 );
+ parts.append( one );
+ one.clear();
+ }
+
+ if ( !ok )
+ return false;
+
+ QStack<PostfixItem> aStack;
+ QList<Postfix>::const_iterator aPIt = parts.begin();
+ QList<PostfixItemType>::const_iterator aTIt = min_types.begin();
+ res += (*aPIt);
+ aPIt++;
+ anIt = argmin.begin();
+ for ( ; anIt != aLast; anIt++, aPIt++, aTIt++ )
+ {
+ if ( *aTIt == Pre )
+ {
+ if ( anOpen.contains( post[*anIt].myValue.toString() ) == 0 )
+ {
+ res += (*aPIt);
+ aStack.push( post[ *anIt ] );
+ }
+ else
+ {
+ res.append( post[*anIt] );
+ res += *aPIt;
+ }
+ }
+ else
+ {
+ res += *aPIt;
+ while ( !aStack.isEmpty() )
+ {
+ res.append( aStack.top() );
+ aStack.pop();
+ }
+ res.append( post[*anIt] );
+ }
+ }
+ while ( !aStack.isEmpty() )
+ {
+ res.append( aStack.top() );
+ aStack.pop();
+ }
+ }
+ else
+ { //there are no operations
+ for ( int k = f; k <= l; k++ )
+ {
+ if ( post.at( k ).myType==Value || post.at( k ).myType == Param )
+ res.append( post.at( k ) );
+ }
+ }
+ }
+
+ return error() == QtxEvalExpr::OK;
+}
+
+/*!
+ \brief Parse the expression and build the posfix.
+
+ If by parsing error is found, the function returns \c false. In this case the code of the error
+ can be retrieved with error() method.
+
+ \param expr string expression
+ \return \c true on success and \c false if error is found
+*/
+bool QtxEvalParser::parse( const QString& expr )
+{
+ myPostfix.clear();
+
+ if ( !checkOperations() )
+ return false;
+
+ Postfix p;
+ QStringList opens, closes;
+
+ setError( QtxEvalExpr::OK );
+ bracketsList( opens, true );
+ bracketsList( closes, false );
+
+ return prepare( expr, p ) && setOperationTypes( p ) && sort( p, myPostfix, opens, closes );
+}
+
+/*!
+ \brief Calculate the operation.
+
+ The result of the operation is returned in the parameter \a v1.
+
+ \param op operation name
+ \param v1 first argument (not valid for unary prefix operations)
+ \param v2 second argument (not valid for unary postfix operations)
+ \return \c true on success and \c false if error is found
+*/
+bool QtxEvalParser::calculate( const QString& op, QVariant& v1, QVariant& v2 )
+{
+ QtxEvalExpr::Error err = isValid( op, v1.type(), v2.type() );
+ if ( err == QtxEvalExpr::OK )
+ setError( calculation( op, v1, v2 ) );
+ else
+ setError( err );
+
+ return error() == QtxEvalExpr::OK;
+}
+
+/*!
+ \brief Calculate the expression without postfix rebuilding.
+ \return QVariant as result (it is invalid if there were errors during calculation)
+*/
+QVariant QtxEvalParser::calculate()
+{
+ if ( !checkOperations() )
+ return QVariant();
+
+ setError( QtxEvalExpr::OK );
+
+ QStringList anOpen, aClose;
+ bracketsList( anOpen, true );
+ bracketsList( aClose, false );
+
+ QStack<QVariant> aStack;
+ Postfix::iterator anIt = myPostfix.begin(), aLast = myPostfix.end();
+ for ( ; anIt != aLast && error() == QtxEvalExpr::OK; anIt++ )
+ {
+ QString nn = (*anIt).myValue.toString();
+ if ( (*anIt).myType == Param )
+ {
+ if ( hasParameter( nn ) )
+ {
+ QVariant& v = myParams[nn];
+ if ( v.isValid() )
+ aStack.push( v );
+ else
+ setError( QtxEvalExpr::InvalidToken );
+ }
+ else
+ setError( QtxEvalExpr::InvalidToken );
+ }
+ else if ( (*anIt).myType == Value )
+ aStack.push( (*anIt).myValue );
+ else if ( (*anIt).myType == Pre || (*anIt).myType == Post )
+ {
+ if ( anOpen.contains( nn ) )
+ {
+ QVariant inv;
+ if ( calculate( nn, inv, inv ) )
+ aStack.push( QVariant() );
+ }
+ else if ( aClose.contains( nn ) )
+ {
+ QList<QVariant> set;
+ while ( true )
+ {
+ if ( aStack.isEmpty() )
+ {
+ setError( QtxEvalExpr::StackUnderflow );
+ break;
+ }
+ if ( aStack.top().isValid() )
+ {
+ set.append( aStack.top() );
+ aStack.pop();
+ }
+ else
+ {
+ aStack.pop();
+ break;
+ }
+ }
+
+ QVariant qSet = set, inv;
+ if ( calculate( nn, qSet, inv ) )
+ aStack.push( set );
+ }
+ else if ( aStack.count() >= 1 )
+ {
+ QVariant inv;
+ QVariant* v1 = &aStack.top(), *v2 = &inv; //"post-" case
+ if ( (*anIt).myType == Pre )
+ {
+ v2 = &aStack.top();
+ v1 = &inv;
+ }
+ calculate( nn, *v1, *v2 );
+ }
+ else
+ setError( QtxEvalExpr::StackUnderflow );
+ }
+ else if ( (*anIt).myType == Binary )
+ {
+ if ( aStack.count() >= 2 )
+ {
+ QVariant v2 = aStack.top();
+ aStack.pop();
+ calculate( nn, aStack.top(), v2 );
+ }
+ else
+ setError( QtxEvalExpr::StackUnderflow );
+ }
+ }
+
+ QVariant res;
+ if ( error() == QtxEvalExpr::OK )
+ {
+ int count = aStack.count();
+ if ( count == 0 )
+ setError( QtxEvalExpr::StackUnderflow );
+ else if( count == 1 )
+ res = aStack.top();
+ else
+ setError( QtxEvalExpr::ExcessData );
+ }
+ return res;
+}
+
+/*!
+ \brief Change the expression, rebuild the postfix and calculate it.
+ \param expr new expression
+ \return QVariant as result (it is invalid if there were errors during calculation)
+*/
+QVariant QtxEvalParser::calculate( const QString& expr )
+{
+ setExpression( expr );
+ return calculate();
+}
+
+/*!
+ \brief Change the expression and rebuild the postfix.
+ \param expr new expression
+ \return \c true on success and \c false if error is found
+*/
+bool QtxEvalParser::setExpression( const QString& expr )
+{
+ return parse( expr );
+}
+
+/*!
+ \brief Check if the parser contains specified parameter.
+ \param name parameter name
+ \return \c true, if the parser contains parameter
+*/
+bool QtxEvalParser::hasParameter( const QString& name ) const
+{
+ return myParams.contains( name.trimmed() );
+}
+
+/*!
+ \brief Set parameters value.
+ \param name parameter name
+ \param value parameter value
+*/
+void QtxEvalParser::setParameter( const QString& name, const QVariant& value )
+{
+ myParams.insert( name.trimmed(), value );
+}
+
+/*!
+ \brief Remove parameter.
+ \param name parameter name
+ \return \c true on success
+*/
+bool QtxEvalParser::removeParameter( const QString& name )
+{
+ return myParams.remove( name.trimmed() );
+}
+
+/*!
+ \brief Get the parameter value.
+ \param name parameter name
+ \return parameter value or invalud QVariant if there is no such parameter
+*/
+QVariant QtxEvalParser::parameter( const QString& name ) const
+{
+ QVariant res;
+ if ( myParams.contains( name.trimmed() ) )
+ res = myParams[name.trimmed()].toString();
+ return res;
+}
+
+/*!
+ \brief Search first parameter with assigned invalid value.
+ \param name used to retrieve the name of the parameter if it is found
+ \return \c true if parameter is found
+*/
+bool QtxEvalParser::firstInvalid( QString& name ) const
+{
+ for ( ParamMap::const_iterator anIt = myParams.begin(); anIt != myParams.end(); anIt++ )
+ {
+ if ( !anIt.value().isValid() )
+ {
+ name = anIt.key();
+ return true;
+ }
+ }
+ return false;
+}
+
+/*!
+ \brief Remove all parameters with assigned invalid values.
+*/
+void QtxEvalParser::removeInvalids()
+{
+ QStringList toDelete;
+ for ( ParamMap::const_iterator anIt = myParams.begin(); anIt != myParams.end(); anIt++ )
+ {
+ if ( !anIt.value().isValid() )
+ toDelete.append( anIt.key() );
+ }
+
+ for ( QStringList::const_iterator aLIt = toDelete.begin(); aLIt != toDelete.end(); aLIt++ )
+ myParams.remove( *aLIt );
+}
+
+/*!
+ \brief Get the code of the latest parsing error.
+ \return last error code
+*/
+QtxEvalExpr::Error QtxEvalParser::error() const
+{
+ return myError;
+}
+
+/*!
+ \brief Set the error vode.
+ \internal
+ \param err error code
+*/
+void QtxEvalParser::setError( QtxEvalExpr::Error err )
+{
+ myError = err;
+}
+
+/*!
+ \brief Dump the current postfix contents to the string.
+ \return string representation of the internal parser postfix
+*/
+QString QtxEvalParser::dump() const
+{
+ return dump( myPostfix );
+}
+
+/*!
+ \brief Dump the postfix contents to the string.
+ \param post postfix to be dumped
+ \return string representation of the postfix
+*/
+QString QtxEvalParser::dump( const Postfix& post ) const
+{
+ QString res;
+
+ if ( !checkOperations() )
+ return res;
+
+ for ( Postfix::const_iterator anIt = post.begin(); anIt != post.end(); anIt++ )
+ {
+ if ( (*anIt).myType == Value && (*anIt).myValue.type() == QVariant::String )
+ res += "'" + (*anIt).myValue.toString() + "'";
+ else
+ res += (*anIt).myValue.toString();
+
+ if ( (*anIt).myType == Pre )
+ res += "(pre)";
+ else if ( (*anIt).myType == Post )
+ res += "(post)";
+ else if ( (*anIt).myType == Binary )
+ res += "(bin)";
+
+ res += "_";
+ }
+
+ return res;
+}
+
+/*!
+ \brief Get the list of the parameters names.
+ \return parameters names
+*/
+QStringList QtxEvalParser::parameters() const
+{
+ QStringList lst;
+ for ( Postfix::const_iterator anIt = myPostfix.begin(); anIt != myPostfix.end(); anIt++ )
+ {
+ if ( (*anIt).myType == Param )
+ {
+ QString name = (*anIt).myValue.toString();
+ if ( !lst.contains( name ) )
+ lst.append( name );
+ }
+ }
+ return lst;
+}
+
+/*!
+ \brief Remove all parameters.
+*/
+void QtxEvalParser::clearParameters()
+{
+ myParams.clear();
+}
+
+/*!
+ \brief Get the string representation for the list of QVariant values.
+ \param list list to be converted
+ \return string representation for the list
+*/
+QString QtxEvalParser::toString( const QList<QVariant>& list )
+{
+ QString res = "set : [ ";
+ for ( QList<QVariant>::const_iterator anIt = list.begin(); anIt != list.end(); anIt++ )
+ res += (*anIt).toString() + " ";
+ res += "]";
+ return res;
+}
+
+/*!
+ \brief Get names of all operations used in the expression.
+ \param list returning list of the operations names
+*/
+void QtxEvalParser::operationList( QStringList& list ) const
+{
+ for ( SetList::const_iterator it = mySets.begin(); it != mySets.end(); ++it )
+ {
+ QStringList custom;
+ QtxEvalSet* set = *it;
+ set->operationList( custom );
+ for ( QStringList::const_iterator sIt = custom.begin(); sIt != custom.end(); ++sIt )
+ {
+ if ( !list.contains( *sIt ) )
+ list.append( *sIt );
+ }
+ }
+}
+
+/*!
+ \brief Get list of brackets.
+ \param list returning list of brackets
+ \param open if \c true, collect opening brackets, or closing brackets otherwise
+*/
+void QtxEvalParser::bracketsList( QStringList& list, bool open ) const
+{
+ for ( SetList::const_iterator it = mySets.begin(); it != mySets.end(); ++it )
+ {
+ QStringList custom;
+ QtxEvalSet* set = *it;
+ set->bracketsList( custom, open );
+ for ( QStringList::const_iterator sIt = custom.begin(); sIt != custom.end(); ++sIt )
+ {
+ if ( !list.contains( *sIt ) )
+ list.append( *sIt );
+ }
+ }
+}
+
+/*!
+ \brief Create value.
+ \param str parsed string
+ \param val returning value
+ \return \c true on success
+*/
+bool QtxEvalParser::createValue( const QString& str, QVariant& val ) const
+{
+ bool ok = false;
+ for ( SetList::const_iterator it = mySets.begin(); it != mySets.end() && !ok; ++it )
+ ok = (*it)->createValue( str, val );
+ return ok;
+}
+
+/*!
+ \brief Get the operation priority level.
+ \param op operation
+ \param isBin \c true if the operation is binary and \c false if it is unary
+ \return operation priority
+*/
+int QtxEvalParser::priority( const QString& op, bool isBin ) const
+{
+ int i = 0;
+ int priority = 0;
+ for ( SetList::const_iterator it = mySets.begin(); it != mySets.end() && priority <= 0; ++it, i++ )
+ priority = (*it)->priority( op, isBin );
+
+ return priority > 0 ? priority + i * 10 : 0;
+}
+
+/*!
+ \brief Check operation validity.
+
+ If the operation is valid, QtxEvalExpr::OK is returned.
+
+ \param op operation
+ \param t1 first operand type
+ \param t2 second operand type
+ \return error code (QtxEvalExpr::Error)
+*/
+QtxEvalExpr::Error QtxEvalParser::isValid( const QString& op,
+ const QVariant::Type t1, const QVariant::Type t2 ) const
+{
+ QtxEvalExpr::Error err = QtxEvalExpr::OK;
+ for ( SetList::const_iterator it = mySets.begin(); it != mySets.end(); ++it )
+ {
+ err = (*it)->isValid( op, t1, t2 );
+ if ( err == QtxEvalExpr::OK )
+ break;
+ }
+ return err;
+}
+
+/*!
+ \brief Perform calculation
+
+ The result of the operation is returned in the parameter \a v1.
+ If the operation is calculated correctly, the function returns QtxEvalExpr::OK.
+
+ \param op operation name
+ \param v1 first argument (not valid for unary prefix operations)
+ \param v2 second argument (not valid for unary postfix operations)
+ \return error code (QtxEvalExpr::Error)
+*/
+QtxEvalExpr::Error QtxEvalParser::calculation( const QString& op, QVariant& v1, QVariant& v2 ) const
+{
+ QVariant nv1, nv2;
+ for ( SetList::const_iterator it = mySets.begin(); it != mySets.end(); ++it )
+ {
+ nv1 = v1;
+ nv2 = v2;
+ if ( (*it)->isValid( op, v1.type(), v2.type() ) == QtxEvalExpr::OK )
+ {
+ QtxEvalExpr::Error err = (*it)->calculate( op, nv1, nv2 );
+ if ( err == QtxEvalExpr::OK || err == QtxEvalExpr::InvalidResult )
+ {
+ v1 = nv1;
+ v2 = nv2;
+ return err;
+ }
+ }
+ }
+ return QtxEvalExpr::InvalidOperation;
+}
+
+/*!
+ \brief Check current operations set.
+ \return \c false if current set of operations is empty
+*/
+bool QtxEvalParser::checkOperations() const
+{
+ if ( !mySets.isEmpty() )
+ return true;
+
+ QtxEvalParser* that = (QtxEvalParser*)this;
+ that->setError( QtxEvalExpr::OperationsNull );
+ return false;
+}
+
+/*!
+ \class QtxEvalSet
+ \brief Generic class for all the operations sets used in expressions.
+*/
+
+/*!
+ \brief Constructor.
+*/
+QtxEvalSet::QtxEvalSet()
+{
+}
+
+/*!
+ \brief Destructor.
+*/
+QtxEvalSet::~QtxEvalSet()
+{
+}
+
+/*!
+ \fn void QtxEvalSet::operationList( QStringList& list ) const;
+ \brief Get the list of possible operations.
+ \param list returning list of operations supported by the class
+*/
+
+/*!
+ \fn void QtxEvalSet::bracketsList( QStringList& list, bool open ) const;
+ \brief Get list of brackets.
+ \param list returning list of brackets
+ \param open if \c true, collect opening brackets, or closing brackets otherwise
+*/
+
+/*!
+ \brief Create value from its string representation.
+
+ By default, the string value is set, that corresponds to the parameter.
+ Base implementation always returns \c false (it means that string
+ is evaluated to the parameter).
+ Successor class can re-implement this method to return \c true
+ if the argument being parsed can be evaluated as custom value.
+
+ \param str string representration of the value
+ \param val returning value
+ \return \c true if \a str can be evaluated as custom value and \c false
+ otherwise (parameter)
+*/
+bool QtxEvalSet::createValue( const QString& str, QVariant& val ) const
+{
+ val = str;
+ return false;
+}
+
+/*!
+ \fn int QtxEvalSet::priority( const QString& op, bool isBin ) const;
+ \brief Get the operation priority.
+
+ Operation priority counts from 1.
+ If the operation is impossible, this function should return value <= 0.
+
+ \param op operation
+ \param isBin \c true if the operation is binary and \c false if it is unary
+ \return operation priority
+*/
+
+/*!
+ \fn QtxEvalExpr::Error QtxEvalSet::isValid( const QString& op, const QVariant::Type t1,
+ const QVariant::Type t2 ) const;
+ \brief Check operation validity.
+
+ If the operation is valid, QtxEvalExpr::OK is returned.
+ If types of operands are invalid, the function returns QtxEvalExpr::OperandsNotMatch
+ or QtxEvalExpr::InvalidOperation.
+
+ \param op operation
+ \param t1 first operand type
+ \param t2 second operand type
+ \return error code (QtxEvalExpr::Error)
+*/
+
+/*!
+ \fn QtxEvalExpr::Error QtxEvalSet::calculate( const QString& op, QVariant& v1,
+ QVariant& v2 ) const;
+ \brief Calculate the operation.
+
+ Process binary operation with values \a v1 and \a v2.
+ For unary operation the \v2 is invalid.
+ The result of the operation is returned in the parameter \a v1.
+
+ \param op operation name
+ \param v1 first argument (not valid for unary prefix operations)
+ \param v2 second argument (not valid for unary postfix operations)
+ \return error code (QtxEvalExpr::Error)
+*/
+
+/*!
+ \fn QString QtxEvalSet::name() const;
+ \brief Get unique operations set name.
+
+ Should be redefined in the successor classes.
+
+ \return operations set name
+*/
+
+/*!
+ \class QtxEvalSetBase
+ \brief Generic class. Provides functionality for standard operations sets.
+*/
+
+/*!
+ \brief Constructor.
+*/
+QtxEvalSetBase::QtxEvalSetBase()
+{
+}
+
+/*!
+ \brief Destructor.
+*/
+QtxEvalSetBase::~QtxEvalSetBase()
+{
+}
+
+/*!
+ \brief Get list of brackets.
+ \param list returning list of brackets
+ \param open if \c true, collect opening brackets, or closing brackets otherwise
+*/
+void QtxEvalSetBase::bracketsList( QStringList& list, bool open ) const
+{
+ list.append( open ? "(" : ")" );
+}
+
+/*!
+ \brief Get the list of possible operations.
+ \param list returning list of operations supported by the class
+*/
+void QtxEvalSetBase::operationList( QStringList& list ) const
+{
+ list += myOpers;
+}
+
+/*!
+ \brief Add operation names to the internal list of operations.
+ \param list operations to be added
+*/
+void QtxEvalSetBase::addOperations( const QStringList& list )
+{
+ for ( QStringList::const_iterator anIt = list.begin(); anIt != list.end(); ++anIt )
+ {
+ if ( !myOpers.contains( *anIt ) )
+ myOpers.append( *anIt );
+ }
+}
+
+/*!
+ \brief Add operand types.
+ \param list operand types to be added
+*/
+void QtxEvalSetBase::addTypes( const ListOfTypes& list )
+{
+ for ( ListOfTypes::const_iterator anIt = list.begin(); anIt != list.end(); ++anIt )
+ {
+ if ( !myTypes.contains( *anIt ) )
+ myTypes.append( *anIt );
+ }
+}
+
+/*!
+ \brief Check operation validity.
+
+ If the operation is valid, QtxEvalExpr::OK is returned.
+ If types of operands are invalid, the function returns QtxEvalExpr::OperandsNotMatch
+ or QtxEvalExpr::InvalidOperation.
+
+ \param op operation
+ \param t1 first operand type
+ \param t2 second operand type
+ \return error code (QtxEvalExpr::Error)
+*/
+QtxEvalExpr::Error QtxEvalSetBase::isValid( const QString& op,
+ const QVariant::Type t1, const QVariant::Type t2 ) const
+{
+ if ( ( t1 == QVariant::Invalid || myTypes.contains( t1 ) ) &&
+ ( t2 == QVariant::Invalid || myTypes.contains( t2 ) ) &&
+ ( t1 != QVariant::Invalid || t2 != QVariant::Invalid ) )
+ {
+ if ( priority( op, t1 != QVariant::Invalid && t2 != QVariant::Invalid ) > 0 )
+ return QtxEvalExpr::OK;
+ else
+ return QtxEvalExpr::InvalidOperation;
+ }
+ else
+ return QtxEvalExpr::OperandsNotMatch;
+}
+
+/*!
+ \class QtxEvalSetArithmetic
+ \brief Provides set of arithmetical operations for the parser.
+*/
+
+/*!
+ \brief Constructor.
+*/
+QtxEvalSetArithmetic::QtxEvalSetArithmetic()
+: QtxEvalSetBase()
+{
+ addOperations( QString( "+;-;*;/;=;<;>;<=;>=;<>;!=" ).split( ";" ) );
+
+ ListOfTypes aTypes;
+ aTypes.append( QVariant::Int );
+ aTypes.append( QVariant::UInt );
+ aTypes.append( QVariant::Double );
+ addTypes( aTypes );
+}
+
+/*!
+ \brief Destructor.
+*/
+QtxEvalSetArithmetic::~QtxEvalSetArithmetic()
+{
+}
+
+/*!
+ \brief Get operations set name.
+ \return operations set name
+*/
+QString QtxEvalSetArithmetic::Name()
+{
+ return "Arithmetic";
+}
+
+/*!
+ \brief Get operations set name.
+ \return operations set name
+*/
+QString QtxEvalSetArithmetic::name() const
+{
+ return Name();
+}
+
+/*!
+ \brief Create value from its string representation.
+
+ Creates numbers from string representation.
+
+ \param str string representration of the value
+ \param val returning value
+ \return \c true if \a str can be evaluated as custom value and \c false
+ otherwise (parameter)
+*/
+bool QtxEvalSetArithmetic::createValue( const QString& str, QVariant& val ) const
+{
+ bool ok = false;
+ val = str.toInt( &ok );
+
+ if ( !ok )
+ {
+ val = str.toDouble( &ok );
+ if ( !ok )
+ ok = QtxEvalSetBase::createValue( str, val );
+ }
+ return ok;
+}
+
+/*!
+ \brief Get the operation priority.
+
+ Operation priority counts from 1.
+ If the operation is impossible, this function returns value <= 0.
+
+ \param op operation
+ \param isBin \c true if the operation is binary and \c false if it is unary
+ \return operation priority
+*/
+int QtxEvalSetArithmetic::priority( const QString& op, bool isBin ) const
+{
+ if ( isBin )
+ {
+ if ( op == "<" || op == ">" || op == "=" ||
+ op == "<=" || op == ">=" || op == "<>" || op == "!=" )
+ return 1;
+ else if ( op == "+" || op == "-" )
+ return 2;
+ else if( op == "*" || op == "/" )
+ return 3;
+ else
+ return 0;
+ }
+ else if ( op == "+" || op == "-" )
+ return 5;
+ else
+ return 0;
+}
+
+/*!
+ \brief Calculate the operation.
+
+ Process binary operation with values \a v1 and \a v2.
+ For unary operation the \v2 is invalid.
+ The result of the operation is returned in the parameter \a v1.
+
+ \param op operation name
+ \param v1 first argument (not valid for unary prefix operations)
+ \param v2 second argument (not valid for unary postfix operations)
+ \return error code (QtxEvalExpr::Error)
+*/
+QtxEvalExpr::Error QtxEvalSetArithmetic::calculate( const QString& op, QVariant& v1, QVariant& v2 ) const
+{
+ QtxEvalExpr::Error err = QtxEvalExpr::OK;
+
+ if ( v1.isValid() && v2.isValid() )
+ {
+ // binary operations
+ if ( ( v1.type() == QVariant::Int || v1.type() == QVariant::UInt ) &&
+ ( v2.type() == QVariant::Int || v2.type() == QVariant::UInt ) )
+ {
+ int _v1 = v1.toInt();
+ int _v2 = v2.toInt();
+
+ if ( op == "+" )
+ v1 = _v1 + _v2;
+ else if ( op == "-" )
+ v1 = _v1 - _v2;
+ else if ( op == "*" )
+ v1 = _v1 * _v2;
+ else if ( op == "/" )
+ {
+ if ( _v2 != 0 )
+ {
+ if ( _v1 % _v2 == 0 )
+ v1 = _v1 / _v2;
+ else
+ v1 = double( _v1 ) / double( _v2 );
+ }
+ else
+ err = QtxEvalExpr::InvalidResult;
+ }
+ else if ( op == "<" )
+ v1 = _v1 < _v2;
+ else if ( op == ">" )
+ v1 = _v1 > _v2;
+ else if ( op == "=" )
+ v1 = _v1 == _v2;
+ else if ( op == "<=" )
+ v1 = _v1 <= _v2;
+ else if ( op == ">=" )
+ v1 = _v1 >= _v2;
+ else if ( op == "<>" || op == "!=" )
+ v1 = _v1 != _v2;
+ }
+ else if ( ( v1.type() == QVariant::Int || v1.type() == QVariant::Double ) &&
+ ( v2.type() == QVariant::Int || v2.type() == QVariant::Double ) )
+ {
+ double _v1 = v1.toDouble();
+ double _v2 = v2.toDouble();
+
+ if ( op == "+" )
+ v1 = _v1 + _v2;
+ else if ( op == "-" )
+ v1 = _v1 - _v2;
+ else if ( op == "*" )
+ v1 = _v1 * _v2;
+ else if ( op == "/" )
+ {
+ if ( _v2 != 0 )
+ v1 = _v1 / _v2;
+ else
+ err = QtxEvalExpr::InvalidResult;
+ }
+ else if ( op == "<" )
+ v1 = _v1 < _v2;
+ else if ( op == ">" )
+ v1 = _v1 > _v2;
+ else if ( op == "=" )
+ v1 = _v1 == _v2;
+ else if ( op == "<=" )
+ v1 = _v1 <= _v2;
+ else if ( op == ">=" )
+ v1 = _v1 >= _v2;
+ else if ( op == "<>" || op == "!=" )
+ v1 = _v1 != _v2;
+ }
+ else // prefix operations
+ {
+ if ( op == "-" )
+ {
+ if ( v2.type() == QVariant::Int )
+ v2 = -v2.toInt();
+ else if ( v2.type() == QVariant::Double )
+ v2 = -v2.toDouble();
+ }
+ }
+ }
+
+ return err;
+}
+
+/*!
+ \class QtxEvalSetLogic
+ \brief Provides set of logical operations for the parser.
+*/
+
+/*!
+ \brief Constructor.
+*/
+QtxEvalSetLogic::QtxEvalSetLogic()
+: QtxEvalSetBase()
+{
+ addOperations( QString( "and;&&;or;||;xor;not;!;imp;=" ).split( ";" ) );
+
+ ListOfTypes aTypes;
+ aTypes.append( QVariant::Bool );
+ aTypes.append( QVariant::Int );
+ aTypes.append( QVariant::UInt );
+ addTypes( aTypes );
+}
+
+/*!
+ \brief Destructor.
+*/
+QtxEvalSetLogic::~QtxEvalSetLogic()
+{
+}
+
+/*!
+ \brief Get operations set name.
+ \return operations set name
+*/
+QString QtxEvalSetLogic::Name()
+{
+ return "Logic";
+}
+
+/*!
+ \brief Get operations set name.
+ \return operations set name
+*/
+QString QtxEvalSetLogic::name() const
+{
+ return Name();
+}
+
+/*!
+ \brief Create value from its string representation.
+
+ Create \c true or \c false value from string representation.
+
+ \param str string representration of the value
+ \param val returning value
+ \return \c true if \a str can be evaluated as custom value and \c false
+ otherwise (parameter)
+*/
+bool QtxEvalSetLogic::createValue( const QString& str, QVariant& val ) const
+{
+ bool ok = true;
+ QString valStr = str.toLower();
+ if ( valStr == "true" || valStr == "yes" )
+ val = QVariant( true );
+ else if ( valStr == "false" || valStr == "no" )
+ val = QVariant( false );
+ else
+ ok = QtxEvalSetBase::createValue( str, val );
+
+ return ok;
+}
+
+/*!
+ \brief Get the operation priority.
+
+ Operation priority counts from 1.
+ If the operation is impossible, this function returns value <= 0.
+
+ \param op operation
+ \param isBin \c true if the operation is binary and \c false if it is unary
+ \return operation priority
+*/
+int QtxEvalSetLogic::priority( const QString& op, bool isBin ) const
+{
+ if ( isBin )
+ {
+ if ( op == "and" || op == "or" || op == "xor" || op == "&&" || op == "||" || op == "imp" )
+ return 1;
+ else if ( op == "=" )
+ return 2;
+ else
+ return 0;
+ }
+ else if ( op == "not" || op == "!" )
+ return 5;
+ else
+ return 0;
+}
+
+/*!
+ \brief Calculate the operation.
+
+ Process binary operation with values \a v1 and \a v2.
+ For unary operation the \v2 is invalid.
+ The result of the operation is returned in the parameter \a v1.
+
+ \param op operation name
+ \param v1 first argument (not valid for unary prefix operations)
+ \param v2 second argument (not valid for unary postfix operations)
+ \return error code (QtxEvalExpr::Error)
+*/
+QtxEvalExpr::Error QtxEvalSetLogic::calculate( const QString& op, QVariant& v1, QVariant& v2 ) const
+{
+ QtxEvalExpr::Error err = QtxEvalExpr::OK;
+ bool val1 = booleanValue( v1 );
+ bool val2 = booleanValue( v2 );
+ if ( v1.isValid() && v2.isValid() )
+ {
+ if ( op == "and" || op == "&&" )
+ v1 = val1 && val2;
+ else if ( op == "or" || op == "||" )
+ v1 = val1 || val2;
+ else if ( op == "xor" )
+ v1 = ( !val1 && val2 ) || ( val1 && !val2 );
+ else if ( op == "imp" )
+ v1 = !val1 || val2;
+ else if ( op == "=" )
+ v1 = val1 == val2;
+ }
+ else if ( op == "not" || op == "!" )
+ v2 = !val2;
+
+ return err;
+}
+
+/*!
+ \brief Convert value to the boolean.
+ \param v value being converted
+ \return converted value
+*/
+bool QtxEvalSetLogic::booleanValue( const QVariant& v ) const
+{
+ bool res = false;
+ switch ( v.type() )
+ {
+ case QVariant::Bool:
+ res = v.toBool();
+ break;
+ case QVariant::Int:
+ res = v.toInt() != 0;
+ break;
+ case QVariant::UInt:
+ res = v.toUInt() != 0;
+ break;
+ default:
+ res = false;
+ break;
+ }
+ return res;
+}
+
+/*!
+ \class QtxEvalSetMath
+ \brief Provides a set of more complex operations (mathematical functions)
+ for the parser (sqrt, sin, cos, etc).
+*/
+
+/*!
+ \brief Constructor.
+*/
+QtxEvalSetMath::QtxEvalSetMath()
+: QtxEvalSetBase()
+{
+ addOperations( QString( "sqrt;abs;sin;cos;rad2grad;grad2rad" ).split( ";" ) );
+
+ ListOfTypes aTypes;
+ aTypes.append( QVariant::Int );
+ aTypes.append( QVariant::Double );
+ addTypes( aTypes );
+}
+
+/*!
+ \brief Destructor.
+*/
+QtxEvalSetMath::~QtxEvalSetMath()
+{
+}
+
+/*!
+ \brief Get operations set name.
+ \return operations set name
+*/
+QString QtxEvalSetMath::Name()
+{
+ return "Math";
+}
+
+/*!
+ \brief Get operations set name.
+ \return operations set name
+*/
+QString QtxEvalSetMath::name() const
+{
+ return Name();
+}
+
+/*!
+ \brief Create value from its string representation.
+
+ Creates numbers from string representation.
+
+ \param str string representration of the value
+ \param val returning value
+ \return \c true if \a str can be evaluated as custom value and \c false
+ otherwise (parameter)
+*/
+bool QtxEvalSetMath::createValue( const QString& str, QVariant& val ) const
+{
+ bool ok = false;
+ val = str.toInt( &ok );
+
+ if ( !ok )
+ {
+ val = str.toDouble( &ok );
+ if ( !ok )
+ ok = QtxEvalSetBase::createValue( str, val );
+ }
+ return ok;
+}
+
+/*!
+ \brief Get the operation priority.
+
+ Operation priority counts from 1.
+ If the operation is impossible, this function returns value <= 0.
+
+ \param op operation
+ \param isBin \c true if the operation is binary and \c false if it is unary
+ \return operation priority
+*/
+int QtxEvalSetMath::priority( const QString& op, bool isBin ) const
+{
+ if ( isBin )
+ return 0;
+ else if ( op == "sqrt" || op == "abs" || op == "sin" ||
+ op == "cos" || op == "rad2grad" || op == "grad2rad" )
+ return 1;
+ else
+ return 0;
+}
+
+/*!
+ \brief Calculate the operation.
+
+ Process binary operation with values \a v1 and \a v2.
+ For unary operation the \v2 is invalid.
+ The result of the operation is returned in the parameter \a v1.
+
+ \param op operation name
+ \param v1 first argument (not valid for unary prefix operations)
+ \param v2 second argument (not valid for unary postfix operations)
+ \return error code (QtxEvalExpr::Error)
+*/
+QtxEvalExpr::Error QtxEvalSetMath::calculate( const QString& op, QVariant& v1, QVariant& v2 ) const
+{
+ QtxEvalExpr::Error err = QtxEvalExpr::OK;
+ double val = v2.toDouble();
+ if ( op == "sqrt" )
+ {
+ if ( val >= 0 )
+ v2 = sqrt( val );
+ else
+ err = QtxEvalExpr::InvalidResult;
+ }
+ else if ( op == "abs" )
+ {
+ if ( v2.type() == QVariant::Int )
+ v2 = abs( v2.toInt() );
+ else
+ v2 = fabs( v2.toDouble() );
+ }
+ else if ( op == "sin" )
+ v2 = sin( val );
+ else if ( op == "cos" )
+ v2 = cos( val );
+ else if ( op == "grad2rad" )
+ v2 = val * 3.14159256 / 180.0;
+ else if ( op == "rad2grad" )
+ v2 = val * 180.0 / 3.14159256;
+
+ return err;
+}
+
+/*!
+ \class QtxEvalSetString
+ \brief Provides set of string operations for the parser.
+*/
+
+/*!
+ \brief Constructor.
+*/
+QtxEvalSetString::QtxEvalSetString()
+: QtxEvalSetBase()
+{
+ addOperations( QString( "+;=;<;>;<=;>=;<>;!=;length;lower;upper" ).split( ";" ) );
+
+ ListOfTypes aTypes;
+ aTypes.append( QVariant::Int );
+ aTypes.append( QVariant::Double );
+ aTypes.append( QVariant::String );
+ addTypes( aTypes );
+}
+
+/*!
+ \brief Destructor.
+*/
+QtxEvalSetString::~QtxEvalSetString()
+{
+}
+
+/*!
+ \brief Get operations set name.
+ \return operations set name
+*/
+QString QtxEvalSetString::Name()
+{
+ return "String";
+}
+
+/*!
+ \brief Get operations set name.
+ \return operations set name
+*/
+QString QtxEvalSetString::name() const
+{
+ return Name();
+}
+
+/*!
+ \brief Create value from its string representation.
+
+ Creates string value from Qt string representation.
+
+ \param str string representration of the value
+ \param val returning value
+ \return \c true if \a str can be evaluated as custom value and \c false
+ otherwise (parameter)
+*/
+bool QtxEvalSetString::createValue( const QString& str, QVariant& val ) const
+{
+ bool ok = false;
+ if ( str.length() > 1 && str[0] == '\'' && str[str.length() - 1] == '\'' )
+ {
+ val = str.mid( 1, str.length() - 2 );
+ ok = true;
+ }
+ else
+ ok = QtxEvalSetBase::createValue( str, val );
+ return ok;
+}
+
+/*!
+ \brief Get the operation priority.
+
+ Operation priority counts from 1.
+ If the operation is impossible, this function returns value <= 0.
+
+ \param op operation
+ \param isBin \c true if the operation is binary and \c false if it is unary
+ \return operation priority
+*/
+int QtxEvalSetString::priority( const QString& op, bool isBin ) const
+{
+ if ( isBin )
+ {
+ if ( op == "+" )
+ return 2;
+ else if ( op == "=" || op == "<" || op == ">" ||
+ op == "<=" || op == ">=" || op == "<>" || op == "!=" )
+ return 1;
+ else
+ return 0;
+ }
+ else if ( op == "length" || op == "lower" || op=="upper" )
+ return 5;
+ else
+ return 0;
+}
+
+/*!
+ \brief Calculate the operation.
+
+ Process binary operation with values \a v1 and \a v2.
+ For unary operation the \v2 is invalid.
+ The result of the operation is returned in the parameter \a v1.
+
+ \param op operation name
+ \param v1 first argument (not valid for unary prefix operations)
+ \param v2 second argument (not valid for unary postfix operations)
+ \return error code (QtxEvalExpr::Error)
+*/
+QtxEvalExpr::Error QtxEvalSetString::calculate( const QString& op, QVariant& v1, QVariant& v2 ) const
+{
+ QtxEvalExpr::Error err = QtxEvalExpr::OK;
+ if ( v1.isValid() && v2.isValid() )
+ {
+ QString _v1 = v1.toString();
+ QString _v2 = v2.toString();
+ if ( op == "+" )
+ v1 = _v1 + _v2;
+ else if ( op == "=" )
+ v1 = _v1 ==_v2;
+ else if ( op == "<" )
+ v1 = _v1 < _v2;
+ else if ( op == ">" )
+ v1 = _v1 > _v2;
+ else if ( op == "<>" || op == "!=" )
+ v1 = _v1 != _v2;
+ else if ( op == "<=" )
+ v1 = _v1 < _v2 || _v1 == _v2;
+ else if ( op == ">=" )
+ v1 = _v1 > _v2 || _v1 == _v2;
+ }
+ else if ( !v1.isValid() && v2.isValid() )
+ {
+ QString val = v2.toString();
+ if ( op == "length" )
+ v2 = (int)val.length();
+ else if ( op == "lower" )
+ v2 = val.toLower();
+ else if ( op == "upper" )
+ v2 = val.toUpper();
+ }
+ return err;
+}
+
+/*!
+ \class QtxEvalSetSets
+ \brief Provides set of operations with sequences for the parser.
+*/
+
+/*!
+ \brief Constructor.
+*/
+QtxEvalSetSets::QtxEvalSetSets()
+: QtxEvalSetBase()
+{
+ addOperations( QString( "{;};=;<>;!=;+;-;*;in;count" ).split( ";" ) );
+
+ ListOfTypes aTypes;
+ aTypes.append( QVariant::List );
+ addTypes( aTypes );
+}
+
+/*!
+ \brief Destructor.
+*/
+QtxEvalSetSets::~QtxEvalSetSets()
+{
+}
+
+/*!
+ \brief Get operations set name.
+ \return operations set name
+*/
+QString QtxEvalSetSets::Name()
+{
+ return "Sets";
+}
+
+/*!
+ \brief Get operations set name.
+ \return operations set name
+*/
+QString QtxEvalSetSets::name() const
+{
+ return Name();
+}
+
+/*!
+ \brief Get list of brackets.
+ \param list returning list of brackets
+ \param open if \c true, collect opening brackets, or closing brackets otherwise
+*/
+void QtxEvalSetSets::bracketsList( QStringList& list, bool open ) const
+{
+ list.append( open ? "{" : "}" );
+ QtxEvalSetBase::bracketsList( list, open );
+}
+
+/*!
+ \brief Get the operation priority.
+
+ Operation priority counts from 1.
+ If the operation is impossible, this function returns value <= 0.
+
+ \param op operation
+ \param isBin \c true if the operation is binary and \c false if it is unary
+ \return operation priority
+*/
+int QtxEvalSetSets::priority( const QString& op, bool isBin ) const
+{
+ if ( isBin )
+ {
+ if ( op == "=" || op == "<>" || op == "!=" )
+ return 1;
+ else if ( op == "+" || op == "-" || op == "*" )
+ return 2;
+ else if ( op == "in" )
+ return 3;
+ else
+ return 0;
+ }
+ else if ( op == "{" || op == "}" )
+ return 5;
+ else if ( op == "count" )
+ return 4;
+ else
+ return 0;
+}
+
+/*!
+ \brief Check operation validity.
+
+ If the operation is valid, QtxEvalExpr::OK is returned.
+ If types of operands are invalid, the function returns QtxEvalExpr::OperandsNotMatch
+ or QtxEvalExpr::InvalidOperation.
+
+ \param op operation
+ \param t1 first operand type
+ \param t2 second operand type
+ \return error code (QtxEvalExpr::Error)
+*/
+QtxEvalExpr::Error QtxEvalSetSets::isValid( const QString& op,
+ const QVariant::Type t1, const QVariant::Type t2 ) const
+{
+ if ( op == "{" )
+ return QtxEvalExpr::OK;
+
+ if ( op != "in" )
+ return QtxEvalSetBase::isValid( op, t1, t2 );
+
+ if ( t1 != QVariant::Invalid && t2 == QVariant::List )
+ return QtxEvalExpr::OK;
+ else
+ return QtxEvalExpr::OperandsNotMatch;
+}
+
+/*!
+ \brief Add new value \a v to the sequence \a set.
+ \param set sequence
+ \param v value to be added
+*/
+void QtxEvalSetSets::add( ValueSet& set, const QVariant& v )
+{
+ if ( v.isValid() && !set.contains( v ) )
+ set.append( v );
+}
+
+/*!
+ \brief Add all values from sequence \a s2 to the sequence \a s1.
+ \param s1 destination sequence
+ \param s2 source sequence
+*/
+void QtxEvalSetSets::add( ValueSet& s1, const ValueSet& s2 )
+{
+ for ( ValueSet::const_iterator anIt = s2.begin(); anIt != s2.end(); ++anIt )
+ add( s1, *anIt );
+}
+
+/*!
+ \brief Remove value \a v from sequence \a set.
+ \param set sequence
+ \param v value to be removed
+*/
+void QtxEvalSetSets::remove( ValueSet& set, const QVariant& v )
+{
+ set.removeAll( v );
+}
+
+/*!
+ \brief Remove all values listed in the sequence \a s2 from the sequence \a s1.
+ \param s1 sequence from which items are removed
+ \param s2 sequence which items are removed
+*/
+void QtxEvalSetSets::remove( ValueSet& s1, const ValueSet& s2 )
+{
+ for ( ValueSet::const_iterator anIt = s2.begin(); anIt != s2.end(); ++anIt )
+ s1.removeAll( *anIt );
+}
+
+/*!
+ \brief Calculate the operation.
+
+ Process binary operation with values \a v1 and \a v2.
+ For unary operation the \v2 is invalid.
+ The result of the operation is returned in the parameter \a v1.
+
+ \param op operation name
+ \param v1 first argument (not valid for unary prefix operations)
+ \param v2 second argument (not valid for unary postfix operations)
+ \return error code (QtxEvalExpr::Error)
+*/
+QtxEvalExpr::Error QtxEvalSetSets::calculate( const QString& op, QVariant& v1, QVariant& v2 ) const
+{
+ QtxEvalExpr::Error err = QtxEvalExpr::OK;
+
+ if ( op != "{" )
+ {
+ if ( op == "}" )
+ {
+ ValueSet aNewList;
+ add( aNewList, v1.toList() );
+ v1 = aNewList;
+ }
+ else if ( op == "=" || op == "<>" || op == "!=" || op == "+" || op == "-" || op == "*" )
+ {
+ ValueSet aNewList;
+ add( aNewList, v1.toList() );
+ if ( op == "=" || op == "<>" || op == "!=" || op == "-" )
+ {
+ remove( aNewList, v2.toList() );
+ if ( op == "=" )
+ v1 = aNewList.isEmpty() && v1.toList().count() == v2.toList().count();
+ else if ( op == "<>" || op == "!=" )
+ v1 = !aNewList.isEmpty() || v1.toList().count() != v2.toList().count();
+ else
+ v1 = aNewList;
+ }
+ else if ( op == "+" )
+ {
+ add( aNewList, v2.toList() );
+ v1 = aNewList;
+ }
+ else if ( op == "*" )
+ {
+ ValueSet toDelete;
+ add( toDelete, aNewList );
+ remove( toDelete, v2.toList() );
+ remove( aNewList, toDelete );
+ v1 = aNewList;
+ }
+ }
+ else if ( op== "count" )
+ v2 = (int)v2.toList().count();
+ else if ( op == "in" )
+ {
+ if ( v1.type() == QVariant::List )
+ {
+ bool res = true;
+ ValueSet lst1 = v1.toList();
+ ValueSet lst2 = v2.toList();
+ for ( ValueSet::const_iterator anIt = lst1.begin(); anIt != lst1.end() && res; ++anIt )
+ res = lst2.contains( *anIt );
+
+ v1 = res;
+ }
+ else
+ v1 = QVariant( v2.toList().contains( v1 ) );
+ }
+ }
+ return err;
+}
+
+/*!
+ \class QtxEvalSetConst
+ \brief Provides different standard constants.
+*/
+QtxEvalSetConst::QtxEvalSetConst()
+: QtxEvalSet()
+{
+}
+
+/*!
+ \brief Destructor.
+*/
+QtxEvalSetConst::~QtxEvalSetConst()
+{
+}
+
+/*!
+ \brief Get operations set name.
+ \return operations set name
+*/
+QString QtxEvalSetConst::Name()
+{
+ return "Const";
+}
+
+/*!
+ \brief Get operations set name.
+ \return operations set name
+*/
+QString QtxEvalSetConst::name() const
+{
+ return Name();
+}
+
+/*!
+ \brief Create value from its string representation.
+
+ Convert constant name to its value.
+
+ \param str string representration of the constant
+ \param val returning value
+ \return \c true if \a str can be evaluated as custom value and \c false
+ otherwise (parameter)
+*/
+bool QtxEvalSetConst::createValue( const QString& str, QVariant& val ) const
+{
+ bool ok = true;
+ if ( str == "pi" ) // PI number
+ val = QVariant( 3.141593 );
+ else if ( str == "exp" ) // Exponent value (e)
+ val = QVariant( 2.718282 );
+ else if ( str == "g" ) // Free fall acceleration (g)
+ val = QVariant( 9.80665 );
+ else
+ ok = false;
+
+ return ok;
+}
+
+/*!
+ \brief Get the list of possible operations.
+ \param list returning list of operations supported by the class (not used)
+*/
+void QtxEvalSetConst::operationList( QStringList& /*list*/ ) const
+{
+}
+
+/*!
+ \brief Get list of brackets.
+ \param list returning list of brackets (not used)
+ \param open if \c true, collect opening brackets, or closing brackets otherwise (not used)
+*/
+void QtxEvalSetConst::bracketsList( QStringList& /*list*/, bool /*open*/ ) const
+{
+}
+
+/*!
+ \brief Get the operation priority.
+
+ Operation priority counts from 1.
+ If the operation is impossible, this function returns value <= 0.
+
+ \param op operation (not used)
+ \param isBin \c true if the operation is binary and \c false if it is unary (not used)
+ \return operation priority
+*/
+int QtxEvalSetConst::priority( const QString& /*op*/, bool /*isBin*/ ) const
+{
+ return 0;
+}
+
+/*!
+ \brief Check operation validity.
+
+ Always returns QtxEvalExpr::InvalidOperation.
+
+ \param op operation (not used)
+ \param t1 first operand type (not used)
+ \param t2 second operand type (not used)
+ \return error code (QtxEvalExpr::Error)
+*/
+QtxEvalExpr::Error QtxEvalSetConst::isValid( const QString& /*op*/,
+ const QVariant::Type /*t1*/,
+ const QVariant::Type /*t2*/ ) const
+{
+ return QtxEvalExpr::InvalidOperation;
+}
+
+/*!
+ \brief Calculate the operation.
+
+ Always returns QtxEvalExpr::InvalidOperation.
+
+ \param op operation name (not used)
+ \param v1 first argument (not valid for unary prefix operations) (not used)
+ \param v2 second argument (not valid for unary postfix operations) (not used)
+ \return error code (QtxEvalExpr::Error)
+*/
+QtxEvalExpr::Error QtxEvalSetConst::calculate( const QString&, QVariant&, QVariant& ) const
+{
+ return QtxEvalExpr::InvalidOperation;
+}
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File: QtxEvalExpr.h
+// Author: Alexander SOLOVYOV
+
+#ifndef QTX_EVALEXPR_H
+#define QTX_EVALEXPR_H
+
+#include "Qtx.h"
+
+#include <QList>
+#include <QVariant>
+
+#ifdef WIN32
+#pragma warning( disable:4251 )
+#endif
+
+class QtxEvalSet;
+class QtxEvalParser;
+
+class QTX_EXPORT QtxEvalExpr
+{
+public:
+ //! Parsing error type
+ typedef enum
+ {
+ OK, //!< No errors found
+ OperandsNotMatch, //!< Types of arguments are invalid for this operation
+ InvalidResult, //!< Operation cannot find result (for example, division by zero)
+ InvalidOperation, //!< Unknown operation
+ OperationsNull, //!< Internal operations pointer of parser is null
+ InvalidToken, //!< Invalid token (neither operation, nor parameter of value)
+ CloseExpected, //!< Closing bracket is expected
+ ExcessClose, //!< Extra closing bracket is found
+ BracketsNotMatch, //!< Opening and closing brackets are of different type, e.g. [)
+ StackUnderflow, //!< There are no arguments in the stack for the operation
+ ExcessData //!< The parsing is finished, but there are more then one value in the stack
+ } Error;
+
+public:
+ QtxEvalExpr( const QString& = QString() );
+ QtxEvalExpr( const bool, const QString& = QString() );
+ ~QtxEvalExpr();
+
+ QVariant calculate( const QString& = QString() );
+
+ QString expression() const;
+ void setExpression( const QString& );
+
+ Error error() const;
+ QtxEvalParser* parser() const;
+
+ bool autoDeleteOperationSets() const;
+ void setAutoDeleteOperationSets( const bool );
+
+ QList<QtxEvalSet*> operationSets() const;
+ QtxEvalSet* operationSet( const QString& ) const;
+ void removeOperationSet( QtxEvalSet* );
+ void insertOperationSet( QtxEvalSet*, const int = -1 );
+
+private:
+ void intialize( const bool, const QString& );
+
+private:
+ QString myExpr;
+ QtxEvalParser* myParser;
+};
+
+class QTX_EXPORT QtxEvalParser
+{
+public:
+ QtxEvalParser();
+ virtual ~QtxEvalParser();
+
+ QVariant calculate();
+ QVariant calculate( const QString& );
+ bool setExpression( const QString& );
+
+ QList<QtxEvalSet*> operationSets() const;
+ QtxEvalSet* operationSet( const QString& ) const;
+ void removeOperationSet( QtxEvalSet* );
+ void insertOperationSet( QtxEvalSet*, const int = -1 );
+
+ bool autoDeleteOperationSets() const;
+ void setAutoDeleteOperationSets( const bool );
+
+ virtual void clearParameters();
+ virtual bool removeParameter( const QString& name );
+ virtual QVariant parameter( const QString& name ) const;
+ virtual bool hasParameter( const QString& name ) const;
+ virtual void setParameter( const QString& name, const QVariant& value );
+ QStringList parameters() const;
+
+ QtxEvalExpr::Error error() const;
+
+ bool firstInvalid( QString& ) const;
+ void removeInvalids();
+ QString dump() const;
+
+ static QString toString( const QList<QVariant>& );
+
+protected:
+ //! Types of postfix representation elements
+ typedef enum
+ {
+ Value, //!< Value (number, string, etc.)
+ Param, //!< Parameter
+ Open, //!< Open bracket
+ Close, //!< Close bracket
+ Pre, //!< Unary prefix operation
+ Post, //!< Unary postfix operation
+ Binary //!< Binary operation
+ } PostfixItemType;
+
+ //! Postfix representation element
+ typedef struct
+ {
+ QVariant myValue;
+ PostfixItemType myType;
+ } PostfixItem;
+
+ typedef QList<PostfixItem> Postfix; //!< postfix representation
+ typedef QList<QtxEvalSet*> SetList; //!< list of operations
+ typedef QMap<QString, QVariant> ParamMap; //!< parameter-to-value map
+
+protected:
+ QString dump( const Postfix& ) const;
+ virtual bool prepare( const QString&, Postfix& );
+ virtual bool setOperationTypes( Postfix& );
+ virtual bool sort( const Postfix&, Postfix&, const QStringList&,
+ const QStringList&, int f = -1, int l = -1 );
+
+ virtual bool parse( const QString& );
+ virtual void setError( const QtxEvalExpr::Error );
+
+ bool calculate( const QString&, QVariant&, QVariant& );
+
+ static int search( const QStringList&, const QString&,
+ int offset, int& matchLen, int& listind );
+ static QString note( const QString& str, int pos, int len );
+ static int globalBrackets( const Postfix&, int, int );
+
+private:
+ void operationList( QStringList& ) const;
+ void bracketsList( QStringList&, bool ) const;
+ bool createValue( const QString&, QVariant& ) const;
+ int priority( const QString&, bool isBin ) const;
+ QtxEvalExpr::Error isValid( const QString&,
+ const QVariant::Type, const QVariant::Type ) const;
+ QtxEvalExpr::Error calculation( const QString&, QVariant&, QVariant& ) const;
+
+ bool checkOperations() const;
+
+private:
+ SetList mySets;
+ QtxEvalExpr::Error myError;
+ ParamMap myParams;
+ Postfix myPostfix;
+ bool myAutoDel;
+};
+
+class QTX_EXPORT QtxEvalSet
+{
+public:
+ QtxEvalSet();
+ virtual ~QtxEvalSet();
+
+ virtual QString name() const = 0;
+
+ virtual void operationList( QStringList& ) const = 0;
+
+ virtual void bracketsList( QStringList&, bool open ) const = 0;
+
+ virtual bool createValue( const QString&, QVariant& ) const;
+
+ virtual int priority( const QString&, bool isBin ) const = 0;
+
+ virtual QtxEvalExpr::Error isValid( const QString&, const QVariant::Type,
+ const QVariant::Type ) const = 0;
+
+ virtual QtxEvalExpr::Error calculate( const QString&, QVariant&, QVariant& ) const = 0;
+};
+
+class QTX_EXPORT QtxEvalSetBase : public QtxEvalSet
+{
+public:
+ QtxEvalSetBase();
+ virtual ~QtxEvalSetBase();
+
+ virtual void operationList( QStringList& ) const;
+ virtual void bracketsList( QStringList&, bool open ) const;
+
+ virtual QtxEvalExpr::Error isValid( const QString&, const QVariant::Type,
+ const QVariant::Type ) const;
+protected:
+ typedef QList<QVariant::Type> ListOfTypes;
+
+ void addTypes( const ListOfTypes& );
+ void addOperations( const QStringList& );
+
+private:
+ QStringList myOpers;
+ ListOfTypes myTypes;
+};
+
+class QTX_EXPORT QtxEvalSetArithmetic : public QtxEvalSetBase
+{
+public:
+ QtxEvalSetArithmetic();
+ virtual ~QtxEvalSetArithmetic();
+
+ virtual bool createValue( const QString&, QVariant& ) const;
+ virtual int priority( const QString&, bool isBin ) const;
+ virtual QtxEvalExpr::Error calculate( const QString&, QVariant&, QVariant& ) const;
+
+ static QString Name();
+ virtual QString name() const;
+};
+
+class QTX_EXPORT QtxEvalSetLogic : public QtxEvalSetBase
+{
+public:
+ QtxEvalSetLogic();
+ virtual ~QtxEvalSetLogic();
+
+ virtual bool createValue( const QString&, QVariant& ) const;
+ virtual int priority( const QString&, bool isBin ) const;
+ virtual QtxEvalExpr::Error calculate( const QString&, QVariant&, QVariant& ) const;
+
+ static QString Name();
+ virtual QString name() const;
+
+private:
+ bool booleanValue( const QVariant& v ) const;
+};
+
+class QTX_EXPORT QtxEvalSetMath : public QtxEvalSetBase
+{
+public:
+ QtxEvalSetMath();
+ virtual ~QtxEvalSetMath();
+
+ virtual bool createValue( const QString&, QVariant& ) const;
+ virtual int priority( const QString&, bool isBin ) const;
+ virtual QtxEvalExpr::Error calculate( const QString&, QVariant&, QVariant& ) const;
+
+ static QString Name();
+ virtual QString name() const;
+};
+
+class QTX_EXPORT QtxEvalSetString : public QtxEvalSetBase
+{
+public:
+ QtxEvalSetString();
+ virtual ~QtxEvalSetString();
+
+ virtual bool createValue( const QString&, QVariant& ) const;
+ virtual int priority( const QString&, bool isBin ) const;
+ virtual QtxEvalExpr::Error calculate( const QString&, QVariant&, QVariant& ) const;
+
+ static QString Name();
+ virtual QString name() const;
+};
+
+class QTX_EXPORT QtxEvalSetSets : public QtxEvalSetBase
+{
+public:
+ typedef QList<QVariant> ValueSet;
+
+public:
+ QtxEvalSetSets();
+ virtual ~QtxEvalSetSets();
+
+ virtual void bracketsList( QStringList&, bool open ) const;
+ virtual int priority( const QString&, bool isBin ) const;
+ virtual QtxEvalExpr::Error isValid( const QString&, const QVariant::Type,
+ const QVariant::Type ) const;
+ virtual QtxEvalExpr::Error calculate( const QString&, QVariant&, QVariant& ) const;
+
+ static void add( ValueSet&, const QVariant& );
+ static void add( ValueSet&, const ValueSet& );
+ static void remove( ValueSet&, const QVariant& );
+ static void remove( ValueSet&, const ValueSet& );
+
+ static QString Name();
+ virtual QString name() const;
+};
+
+class QTX_EXPORT QtxEvalSetConst : public QtxEvalSet
+{
+public:
+ QtxEvalSetConst();
+ virtual ~QtxEvalSetConst();
+
+ static QString Name();
+ virtual QString name() const;
+
+ virtual bool createValue( const QString&, QVariant& ) const;
+
+ virtual void operationList( QStringList& ) const;
+ virtual void bracketsList( QStringList&, bool open ) const;
+ virtual int priority( const QString&, bool isBin ) const;
+ virtual QtxEvalExpr::Error isValid( const QString&, const QVariant::Type,
+ const QVariant::Type ) const;
+ virtual QtxEvalExpr::Error calculate( const QString&, QVariant&, QVariant& ) const;
+};
+
+#endif
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File: QtxGridBox.cxx
+// Author: Sergey TELKOV
+
+#include "QtxGridBox.h"
+
+#include <QGridLayout>
+#include <QChildEvent>
+
+/*!
+ \class QtxGridBox::Space
+ \internal
+ \brief Represents a space in the grid box.
+*/
+
+class QtxGridBox::Space : public QWidget
+{
+public:
+ Space( const int, QtxGridBox* );
+ virtual ~Space();
+
+ virtual QSize sizeHint() const;
+ virtual QSize minimumSizeHint() const;
+
+private:
+ int mySize;
+ QtxGridBox* myGrid;
+};
+
+/*!
+ \brief Constructor.
+ \param sz size
+ \param gb parent grid box
+*/
+QtxGridBox::Space::Space( const int sz, QtxGridBox* gb )
+: QWidget( gb ),
+ mySize( sz ),
+ myGrid( gb )
+{
+ setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );
+}
+
+/*!
+ \brief Destructor.
+*/
+QtxGridBox::Space::~Space()
+{
+}
+
+/*!
+ \brief Get recommended size for the widget.
+ \return recommended size for the widget
+*/
+QSize QtxGridBox::Space::sizeHint() const
+{
+ return minimumSizeHint();
+}
+
+/*!
+ \brief Get recommended minimum size for the widget.
+ \return recommended minimum size for the widget
+*/
+QSize QtxGridBox::Space::minimumSizeHint() const
+{
+ QSize sz( 0, 0 );
+ if ( myGrid && myGrid->orientation() == Qt::Horizontal )
+ sz.setWidth( mySize );
+ else
+ sz.setHeight( mySize );
+ return sz;
+}
+
+/*!
+ \class QtxGridBox
+ \brief A container widget with possibility to automatically layout
+ child widgets.
+*/
+
+/*!
+ \brief Constructor.
+ \param parent parent widget
+ \param m grid box margin
+ \param s grid box spacing
+*/
+QtxGridBox::QtxGridBox( QWidget* parent, const int m, const int s )
+: QWidget( parent ),
+ myCols( 1 ),
+ mySkip( false ),
+ myOrient( Qt::Vertical ),
+ myCol( 0 ),
+ myRow( 0 )
+{
+ myLayout = new QGridLayout( this );
+ myLayout->setMargin( m );
+ myLayout->setSpacing( s );
+}
+
+/*!
+ \brief Constructor.
+ \param cols number of grid box columns or rows (depending on the orientation)
+ \param o grid box orientation
+ \param parent parent widget
+ \param m grid box margin
+ \param s grid box spacing
+*/
+QtxGridBox::QtxGridBox( const int cols, Qt::Orientation o, QWidget* parent, const int m, const int s )
+: QWidget( parent ),
+ myCols( cols ),
+ mySkip( false ),
+ myOrient( o ),
+ myLayout( 0 ),
+ myCol( 0 ),
+ myRow( 0 )
+{
+ myLayout = new QGridLayout( this );
+ myLayout->setMargin( m );
+ myLayout->setSpacing( s );
+}
+
+/*!
+ \brief Destructor.
+*/
+QtxGridBox::~QtxGridBox()
+{
+}
+
+/*!
+ \brief Get number of grid box columns/rows (depending on the orientation).
+ \return number of columns (rows)
+*/
+int QtxGridBox::columns() const
+{
+ return myCols;
+}
+
+/*!
+ \brief Get the grid box orientation.
+ \return orientation
+*/
+Qt::Orientation QtxGridBox::orientation() const
+{
+ return myOrient;
+}
+
+/*!
+ \brief Set number of grid box columns/rows (depending on the orientation).
+ \param cols number of columns (rows)
+*/
+void QtxGridBox::setColumns( const int cols )
+{
+ setLayout( cols, orientation() );
+}
+
+/*!
+ \brief Set the grid box orientation.
+ \param o orientation
+*/
+void QtxGridBox::setOrientation( Qt::Orientation o )
+{
+ setLayout( columns(), o );
+}
+
+/*!
+ \brief Initialize internal layout.
+ \param cols number of columns (rows)
+ \param o orientation
+*/
+void QtxGridBox::setLayout( const int cols, Qt::Orientation o )
+{
+ if ( myCols == cols && myOrient == o )
+ return;
+
+ myCols = cols;
+ myOrient = o;
+
+ arrangeWidgets();
+}
+
+/*!
+ \brief Get "skip invisible widgets" flags.
+ \return current flag state
+*/
+bool QtxGridBox::skipInvisible() const
+{
+ return mySkip;
+}
+
+/*!
+ \brief Set "skip invisible widgets" flags.
+
+ If this flag is set to \c false, invisible widgets
+ are not taken into account when layouting widgets.
+
+ \param on new flag state
+*/
+void QtxGridBox::setSkipInvisible( const bool on )
+{
+ if ( mySkip == on )
+ return;
+
+ mySkip = on;
+ arrangeWidgets();
+}
+
+/*!
+ \brief Add space (empty cell) to the grid box.
+ \param sp requied space size
+*/
+void QtxGridBox::addSpace( const int sp )
+{
+ new Space( sp, this );
+}
+
+/*!
+ \brief Get grid box's inside margin size.
+ \return inside margin size
+*/
+int QtxGridBox::insideMargin() const
+{
+ return myLayout->margin();
+}
+
+/*!
+ \brief Get grid box's inside spacing size.
+ \return inside spacing size
+*/
+int QtxGridBox::insideSpacing() const
+{
+ return myLayout->spacing();
+}
+
+/*!
+ \brief Set grid box's inside margin size.
+ \param m new inside margin size
+*/
+void QtxGridBox::setInsideMargin( const int m )
+{
+ myLayout->setMargin( m );
+}
+
+/*!
+ \brief Set grid box's inside spacing size.
+ \param s new inside spacing size
+*/
+void QtxGridBox::setInsideSpacing( const int s )
+{
+ myLayout->setSpacing( s );
+}
+
+/*!
+ \brief Custom event filter.
+ \param o event receiver object.
+ \param e event
+ \return \c true if the event processing should be stopped
+*/
+bool QtxGridBox::eventFilter( QObject* o, QEvent* e )
+{
+ if ( skipInvisible() && ( e->type() == QEvent::Show || e->type() == QEvent::ShowToParent ||
+ e->type() == QEvent::Hide || e->type() == QEvent::HideToParent ) )
+ arrangeWidgets();
+
+ return QWidget::eventFilter( o, e );
+}
+
+/*!
+ \brief Customize child event.
+ \param e child event
+*/
+void QtxGridBox::childEvent( QChildEvent* e )
+{
+ if ( e->child()->isWidgetType() )
+ {
+ QWidget* wid = (QWidget*)e->child();
+ if ( e->type() == QEvent::ChildAdded )
+ {
+ placeWidget( wid );
+ wid->installEventFilter( this );
+ }
+ else if ( e->type() == QEvent::ChildRemoved )
+ wid->removeEventFilter( this );
+ }
+ QWidget::childEvent( e );
+}
+
+/*!
+ \brief Increment the grid box current cell.
+*/
+void QtxGridBox::skip()
+{
+ if ( orientation() == Qt::Horizontal )
+ {
+ myCol++;
+ if ( myCol >= columns() )
+ {
+ myRow++;
+ myCol = 0;
+ }
+ }
+ else
+ {
+ myRow++;
+ if ( myRow >= columns() )
+ {
+ myCol++;
+ myRow = 0;
+ }
+ }
+}
+
+/*!
+ \brief Arrange child widgets.
+*/
+void QtxGridBox::arrangeWidgets()
+{
+ myRow = myCol = 0;
+ int m = myLayout ? myLayout->margin() : 0;
+ int s = myLayout ? myLayout->spacing() : 0;
+ delete myLayout;
+ myLayout = new QGridLayout( this );
+ myLayout->setMargin( m );
+ myLayout->setSpacing( s );
+
+ QObjectList list = children();
+ for ( QObjectList::iterator it = list.begin(); it != list.end(); ++it )
+ {
+ if ( !(*it)->isWidgetType() )
+ continue;
+
+ QWidget* wid = (QWidget*)(*it);
+ if ( !skipInvisible() || wid->isVisibleTo( this ) )
+ placeWidget( wid );
+ }
+ updateGeometry();
+}
+
+/*!
+ \brief Place new widget to the current grid box cell.
+ \param wid widget being inserted
+*/
+void QtxGridBox::placeWidget( QWidget* wid )
+{
+ myLayout->addWidget( wid, myRow, myCol );
+
+ skip();
+}
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File: QtxGridBox.h
+// Author: Sergey TELKOV
+
+#ifndef QTXGRIDBOX_H
+#define QTXGRIDBOX_H
+
+#include "Qtx.h"
+
+#include <QWidget>
+
+class QGridLayout;
+
+class QTX_EXPORT QtxGridBox : public QWidget
+{
+ Q_OBJECT
+
+ class Space;
+
+public:
+ QtxGridBox( QWidget* = 0, const int = 5, const int = 5 );
+ QtxGridBox( const int, Qt::Orientation, QWidget* = 0, const int = 5, const int = 5 );
+ virtual ~QtxGridBox();
+
+ int columns() const;
+ Qt::Orientation orientation() const;
+
+ void setColumns( const int );
+ void setOrientation( Qt::Orientation );
+
+ void setLayout( const int, Qt::Orientation );
+
+ bool skipInvisible() const;
+ void setSkipInvisible( const bool );
+
+ void addSpace( const int );
+
+ int insideMargin() const;
+ int insideSpacing() const;
+ void setInsideMargin( const int );
+ void setInsideSpacing( const int );
+
+ virtual bool eventFilter( QObject*, QEvent* );
+
+protected:
+ void childEvent( QChildEvent* );
+
+private:
+ void skip();
+ void arrangeWidgets();
+ void placeWidget( QWidget* );
+
+private:
+ int myCols;
+ bool mySkip;
+ Qt::Orientation myOrient;
+ QGridLayout* myLayout;
+
+ int myCol, myRow;
+};
+
+#endif
#include "QtxGroupBox.h"
-#include <qhbox.h>
-#include <qlayout.h>
-#include <qtoolbutton.h>
-#include <qapplication.h>
-#include <qobjectlist.h>
+#include <QVBoxLayout>
+#include <QHBoxLayout>
+#include <QEvent>
+#include <QObjectList>
+#include <QApplication>
/*!
- Constructor
-*/
-QtxGroupBox::QtxGroupBox( QWidget* parent, const char* name )
-: QGroupBox( parent, name ),
-myContainer( 0 )
-{
-}
+ \class QtxGroupBox
+ \brief Enhanced group box widget.
-/*!
- Constructor
+ The QtxGroupBox class allows inserting custom widgets in the
+ group box title. Use insertTitleWidget() method to add
+ custom widget to the title and removeTitleWidget() to remove it.
*/
-QtxGroupBox::QtxGroupBox( const QString& title, QWidget* parent, const char* name )
-: QGroupBox( title, parent, name ),
-myContainer( 0 )
-{
- initialize();
-}
/*!
- Constructor
+ \brief Constructor.
+ \param parent parent widget
*/
-QtxGroupBox::QtxGroupBox( int strips, Orientation o, QWidget* parent, const char* name )
-: QGroupBox( strips, o, parent, name ),
-myContainer( 0 )
+QtxGroupBox::QtxGroupBox( QWidget* parent )
+: QGroupBox( parent ),
+ myContainer( 0 )
{
initialize();
}
/*!
- Constructor
+ \brief Constructor.
+ \param title group box title text
+ \param parent parent widget
*/
-QtxGroupBox::QtxGroupBox( int strips, Orientation o, const QString& title,
- QWidget* parent, const char* name )
-: QGroupBox( strips, o, title, parent, name ),
-myContainer( 0 )
+QtxGroupBox::QtxGroupBox( const QString& title, QWidget* parent )
+: QGroupBox( title, parent ),
+ myContainer( 0 )
{
initialize();
}
/*!
- Destructor
+ \brief Destructor.
*/
QtxGroupBox::~QtxGroupBox()
{
- delete myContainer;
}
/*!
- Creates horizontal box as container
+ \brief Initialize the group box.
+
+ Creates horizontal box as container for title widgets.
*/
void QtxGroupBox::initialize()
{
- myContainer = new QHBox( this, 0, WStyle_Customize | WStyle_NoBorderEx | WStyle_Tool );
+ myContainer = new QWidget( this );
+ QHBoxLayout* base = new QHBoxLayout( myContainer );
+ base->setMargin( 0 );
+ base->setSpacing( 0 );
updateTitle();
}
-#if QT_VER < 3
-
-/*!
- \return the width of the empty space between the items in the group and the frame of the group
-*/
-int QtxGroupBox::insideMargin() const
-{
- int m = 0;
- if ( layout() )
- m = layout()->margin();
- return m;
-}
-
/*!
- \return the width of the empty space between each of the items in the group
-*/
-int QtxGroupBox::insideSpacing() const
-{
- int s = 0;
- if ( layout() )
- s = layout()->spacing();
- return s;
-}
-
-/*!
- Sets the width of the empty space between the items in the group and the frame of the group
-*/
-void QtxGroupBox::setInsideMargin( int m )
-{
- if ( layout() )
- layout()->setMargin( m );
-}
-
-/*!
- Sets the width of the empty space between each of the items in the group
-*/
-void QtxGroupBox::setInsideSpacing( int s )
-{
- if ( layout() )
- layout()->setSpacing( s );
-}
-
-#endif
-
-/*!
- Inserts title widget
- \param wid - new title widget
+ \brief Add widget to the group box title.
+ \param wid widget being added to the title
*/
void QtxGroupBox::insertTitleWidget( QWidget* wid )
{
if ( !myContainer )
return;
- wid->reparent( myContainer, QPoint( 0, 0 ), true );
+ myContainer->layout()->addWidget( wid );
wid->installEventFilter( this );
updateTitle();
}
/*!
- Removes title widget
- \param wid - title widget
+ \brief Remove widget from the group box title.
+ \param wid widget to be removed from the title
*/
void QtxGroupBox::removeTitleWidget( QWidget* wid )
{
if ( !myContainer || wid->parentWidget() != myContainer )
return;
- wid->reparent( 0, QPoint( 0, 0 ), false );
+ myContainer->layout()->removeWidget( wid );
+ wid->setParent( 0 );
wid->removeEventFilter( this );
+ wid->hide();
updateTitle();
}
/*!
- Calculates margin
+ \brief Show/hide group box.
+ \param on if \c true, show group box, otherwise, hide it
*/
-void QtxGroupBox::adjustInsideMargin()
+void QtxGroupBox::setVisible( bool on )
{
- QApplication::sendPostedEvents( myContainer, QEvent::ChildInserted );
+ if ( on )
+ updateTitle();
- myContainer->resize( myContainer->minimumSizeHint() );
-
- setInsideMargin( myContainer->height() );
+ QGroupBox::setVisible( on );
}
/*!
- Sets the alignment of the group box title
+ \brief Get recommended size for the widget.
+ \return recommended size for the widget
*/
-void QtxGroupBox::setAlignment( int align )
+QSize QtxGroupBox::sizeHint() const
{
- QGroupBox::setAlignment( align );
-
- updateTitle();
+ return expandTo( QGroupBox::sizeHint() );
}
/*!
- Sets title of groop box
+ \brief Get recommended minimum size for the widget.
+ \return recommended minimum size for the widget
*/
-void QtxGroupBox::setTitle( const QString& title )
-{
- QGroupBox::setTitle( title );
-
- updateTitle();
-}
-
-/*!
- Changes the layout of the group box
- \param strips - number of column/rows
- \param o - orientation
-*/
-void QtxGroupBox::setColumnLayout( int strips, Orientation o )
+QSize QtxGroupBox::minimumSizeHint() const
{
- if ( myContainer )
- myContainer->reparent( 0, QPoint( 0, 0 ), false );
-
- QGroupBox::setColumnLayout( strips, o );
-
- if ( myContainer )
- myContainer->reparent( this, QPoint( 0, 0 ), false );
-
- updateTitle();
+ return expandTo( QGroupBox::minimumSizeHint() );
}
/*!
- Shows group box
+ \brief Custom event filter.
+ \param obj event receiver
+ \param e event
+ \return \c true if event processing should be stopped
*/
-void QtxGroupBox::show()
+bool QtxGroupBox::eventFilter( QObject* obj, QEvent* e )
{
- QGroupBox::show();
+ QEvent::Type type = e->type();
+ if ( myContainer && obj->parent() == myContainer &&
+ ( type == QEvent::Show || type == QEvent::ShowToParent ||
+ type == QEvent::Hide || type == QEvent::HideToParent ) )
+ QApplication::postEvent( this, new QEvent( QEvent::User ) );
- updateTitle();
+ return QGroupBox::eventFilter( obj, e );
}
-
/*!
- Updates group box
+ \brief Get central widget (or first found one).
+ \return widget
*/
-void QtxGroupBox::update()
+QWidget* QtxGroupBox::widget() const
{
- QGroupBox::update();
+ if ( !layout() )
+ return 0;
- updateTitle();
+ QWidget* w = 0;
+ for ( int i = 0; i < (int)layout()->count() && !w; i++ )
+ w = layout()->itemAt( i )->widget();
+ return w;
}
/*!
- \return the recommended size for the widget
+ \brief Set central widget to the group box.
+ \param wid widget being added to the group box
*/
-QSize QtxGroupBox::sizeHint() const
+void QtxGroupBox::setWidget( QWidget* wid )
{
- QSize sz = QGroupBox::sizeHint();
-
- int sw = titleSize().width();
-
- if ( myContainer )
- {
- if ( alignment() == AlignCenter )
- sw += 2 * ( myContainer->width() + 5 );
- else
- sw += 1 * ( myContainer->width() + 5 );
- }
-
- sw += frameRect().left();
-
- return QSize( QMAX( sz.width(), sw ), sz.height() );
-}
-
-/*!
- \return the recommended minimum size for the widget
-*/
-QSize QtxGroupBox::minimumSizeHint() const
-{
- QSize sz = QGroupBox::minimumSizeHint();
+ QWidget* w = widget();
+ if ( w == wid )
+ return;
- int sw = titleSize().width() + myContainer ? myContainer->width() + 5 : 0;
+ if ( layout() )
+ layout()->removeWidget( w );
- if ( myContainer )
+ if ( !wid )
+ delete layout();
+ else if ( !layout() )
{
- if ( alignment() == AlignCenter )
- sw += 2 * ( myContainer->width() + 5 );
- else
- sw += 1 * ( myContainer->width() + 5 );
+ QLayout* bl = new QVBoxLayout( this );
+ bl->setMargin( 0 );
+ bl->setSpacing( 0 );
}
- sw += frameRect().left();
-
- return QSize( QMAX( sz.width(), sw ), sz.height() );
-}
-
-/*!
- Custom event filter
-*/
-bool QtxGroupBox::eventFilter( QObject* obj, QEvent* e )
-{
- QEvent::Type type = e->type();
- if ( myContainer && obj->parent() == myContainer &&
- ( type == QEvent::Show || type == QEvent::ShowToParent ||
- type == QEvent::Hide || type == QEvent::HideToParent ) )
- QApplication::postEvent( this, new QCustomEvent( QEvent::User ) );
+ if ( layout() )
+ layout()->addWidget( wid );
- return QGroupBox::eventFilter( obj, e );
+ if ( wid )
+ wid->updateGeometry();
}
/*!
- Custom resize event filter
+ \brief Customize resize event.
+ \param e resize event
*/
void QtxGroupBox::resizeEvent( QResizeEvent* e )
{
}
/*!
- Custom child event filter
+ \brief Customize child event.
+ \param e child event
*/
void QtxGroupBox::childEvent( QChildEvent* e )
{
- if ( e->type() == QEvent::ChildInserted && e->child() == myContainer )
+/*
+ if ( e->type() == QEvent::ChildAdded && e->child() == myContainer )
return;
-
- QGroupBox::childEvent( e );
-}
-
-/*!
- Event filter of custom items
*/
-void QtxGroupBox::customEvent( QCustomEvent* )
-{
- updateTitle();
+ QGroupBox::childEvent( e );
}
/*!
- On frame changed
+ \brief Process custom events.
+ \param e custom event (not used)
*/
-void QtxGroupBox::frameChanged()
+void QtxGroupBox::customEvent( QEvent* /*e*/ )
{
updateTitle();
}
/*!
- \return size of title
+ \brief Get the group box title size.
+ \return title size
*/
QSize QtxGroupBox::titleSize() const
{
- QSize sz( 0, 0 );
-
- if ( layout() )
- {
- QSpacerItem* si = 0;
- for ( QLayoutIterator it = layout()->iterator(); it.current() && !si; ++it )
- si = it.current()->spacerItem();
- if ( si )
- sz = si->sizeHint();
- }
-
- int w = sz.width();
- int h = sz.height() + insideMargin();
-
- return QSize( w, h );
+ return QSize( fontMetrics().width( title() ), fontMetrics().height() );
}
/*!
- Updates title
+ \brief Update the group box title.
*/
void QtxGroupBox::updateTitle()
{
return;
int align = alignment();
- if ( align == AlignAuto )
- align = QApplication::reverseLayout() ? AlignRight : AlignLeft;
if ( title().isEmpty() )
- align = AlignRight;
+ align = Qt::AlignRight;
QSize ts = titleSize();
int m = 5;
- int w = frameRect().width() - ts.width();
- if ( align == AlignCenter )
+ int w = width() - ts.width();
+ if ( align == Qt::AlignCenter )
w = w / 2;
w -= m;
- QApplication::sendPostedEvents( myContainer, QEvent::ChildInserted );
myContainer->resize( myContainer->minimumSizeHint() );
bool vis = false;
- const QObjectList* list = myContainer->children();
- if ( list )
- {
- for ( QObjectListIt it( *list ); it.current() && !vis; ++it )
- vis = it.current()->isWidgetType() &&
- ((QWidget*)it.current())->isVisibleTo( myContainer );
- }
+ const QObjectList list = myContainer->children();
+ for ( QObjectList::const_iterator it = list.begin(); it != list.end() && !vis; ++it )
+ vis = (*it)->isWidgetType() && ((QWidget*)(*it))->isVisibleTo( myContainer );
- if ( myContainer->height() > ts.height() || myContainer->width() > w || !vis )
+ if ( !vis )
myContainer->hide();
else
{
int x = 0;
- if ( align == AlignRight )
- x = frameRect().left() + m;
+ if ( align == Qt::AlignRight )
+ x = rect().left() + m;
else
- x = frameRect().right() - myContainer->width() - m;
+ x = rect().right() - myContainer->width() - m;
- int y = frameRect().top() - ( myContainer->height() - frameWidth() ) / 2;
+ int y = rect().top() - ( myContainer->height() - ts.height() ) / 2;
- QPoint pos( x, QMAX( 0, y ) );
- pos = mapToGlobal( pos );
- if ( myContainer->parentWidget() )
- pos = myContainer->parentWidget()->mapFromGlobal( pos );
+ QPoint pos( x, qMax( 0, y ) );
myContainer->move( pos );
myContainer->show();
}
+ if ( layout() )
+ {
+ if ( myContainer && myContainer->isVisibleTo( this ) )
+ setInsideMargin( qMax( 0, myContainer->height() - ts.height() ) );
+ else
+ setInsideMargin( 0 );
+ }
+
updateGeometry();
}
+
+/*!
+ \brief Expand group box to the specified size.
+ \param sz new size
+*/
+QSize QtxGroupBox::expandTo( const QSize& sz ) const
+{
+ int sh = 0;
+ int sw = titleSize().width();
+ if ( myContainer && myContainer->isVisibleTo( (QWidget*)this ) )
+ {
+ if ( alignment() == Qt::AlignCenter )
+ sw += 2 * ( myContainer->width() + 5 );
+ else
+ sw += 1 * ( myContainer->width() + 5 );
+ sw += 20;
+ sh = myContainer->height() + 5;
+ }
+ return QSize( qMax( sz.width(), sw ), qMax( sz.height(), sh ) );
+}
+
+/*!
+ \brief Set group box's inside margin size.
+ \param m new inside margin size
+*/
+void QtxGroupBox::setInsideMargin( const int m )
+{
+ QVBoxLayout* bl = ::qobject_cast<QVBoxLayout*>( layout() );
+
+ if ( !bl )
+ return;
+
+ QSpacerItem* spacer = 0;
+ if ( bl->count() )
+ spacer = bl->itemAt( 0 )->spacerItem();
+
+ if ( !spacer )
+ bl->insertSpacing( 0, m );
+ else
+ spacer->changeSize( 0, m );
+}
#include "Qtx.h"
-#include <qgroupbox.h>
-#include <qwidgetlist.h>
+#include <QGroupBox>
class QTX_EXPORT QtxGroupBox : public QGroupBox
{
Q_OBJECT
public:
- QtxGroupBox( QWidget* = 0, const char* = 0 );
- QtxGroupBox( const QString&, QWidget* = 0, const char* = 0 );
- QtxGroupBox( int, Orientation, QWidget* = 0, const char* = 0 );
- QtxGroupBox( int, Orientation, const QString&, QWidget* = 0, const char* = 0 );
+ QtxGroupBox( QWidget* = 0 );
+ QtxGroupBox( const QString&, QWidget* = 0 );
virtual ~QtxGroupBox();
-#if QT_VER < 3
- int insideMargin() const;
- int insideSpacing() const;
- void setInsideMargin( int );
- void setInsideSpacing( int );
-#endif
-
- virtual void setAlignment( int );
- virtual void setTitle( const QString& );
- virtual void setColumnLayout( int, Orientation );
-
virtual void insertTitleWidget( QWidget* );
virtual void removeTitleWidget( QWidget* );
- virtual void show();
- virtual void update();
-
- void adjustInsideMargin();
-
virtual QSize sizeHint() const;
virtual QSize minimumSizeHint() const;
virtual bool eventFilter( QObject*, QEvent* );
+ QWidget* widget() const;
+ void setWidget( QWidget* );
+
+public slots:
+ virtual void setVisible( bool );
+
protected:
- virtual void frameChanged();
virtual void childEvent( QChildEvent* );
virtual void resizeEvent( QResizeEvent* );
- virtual void customEvent( QCustomEvent* );
+ virtual void customEvent( QEvent* );
private:
void initialize();
void updateTitle();
QSize titleSize() const;
+ void setInsideMargin( const int );
+ QSize expandTo( const QSize& ) const;
private:
QWidget* myContainer;
#include "QtxIntSpinBox.h"
-#include <qlineedit.h>
-#include <qapplication.h>
+#include <QLineEdit>
+/*!
+ \class QtxIntSpinBox
+ \brief Enhanced version of the Qt's spin box.
+
+ The QtxIntSpinBox class represents the widget for entering the
+ integer values. In addition to the functionality provided by
+ QSpinBox, this class supports "cleared" state - this is the
+ state corresponding to "None" (or empty) entered value.
+
+ To set "cleared" state use setCleared() method. To check if the spin
+ box stores "cleared" state, use isCleared() method.
+ For example:
+ \code
+ if (mySpinBox->isCleared()) {
+ ... // process "None" state
+ }
+ else {
+ int value = mySpinBox->value();
+ ... // process entered value
+ }
+ \endcode
+*/
/*!
- Constructor
+ \brief Constructor.
+
+ Constructs a spin box with 0 as minimum value and 99 as maximum value,
+ a step value of 1. The value is initially set to 0.
+
+ \param parent parent object
*/
-QtxIntSpinBox::QtxIntSpinBox( QWidget* parent, const char* name )
-: QSpinBox( parent, name ),
-myCleared( false ),
-myBlocked( false )
+QtxIntSpinBox::QtxIntSpinBox( QWidget* parent )
+: QSpinBox( parent ),
+ myCleared( false )
{
- connect( editor(), SIGNAL( textChanged( const QString& ) ), this, SLOT( onTextChanged( const QString& ) ) );
+ connect( lineEdit(), SIGNAL( textChanged( const QString& ) ),
+ this, SLOT( onTextChanged( const QString& ) ) );
}
/*!
- Constructor
+ \brief Constructor.
+
+ Constructs a spin box with specified minimum, maximum and step value.
+ The value is initially set to the minimum value.
+
+ \param min spin box minimum possible value
+ \param max spin box maximum possible value
+ \param step spin box increment/decrement value
+ \param parent parent object
*/
-QtxIntSpinBox::QtxIntSpinBox( int min, int max, int step, QWidget* parent, const char* name )
-: QSpinBox( min, max, step, parent, name ),
-myCleared( false ),
-myBlocked( false )
+QtxIntSpinBox::QtxIntSpinBox( int min, int max, int step, QWidget* parent )
+: QSpinBox( parent ),
+ myCleared( false )
{
- connect( editor(), SIGNAL( textChanged( const QString& ) ), this, SLOT( onTextChanged( const QString& ) ) );
+ setMinimum( min );
+ setMaximum( max );
+ setSingleStep( step );
+
+ connect( lineEdit(), SIGNAL( textChanged( const QString& ) ),
+ this, SLOT( onTextChanged( const QString& ) ) );
}
/*!
- Destructor
+ \brief Destructor.
*/
QtxIntSpinBox::~QtxIntSpinBox()
{
}
/*!
- \return true if spin box is cleared
+ \brief Check if spin box is in the "cleared" state.
+ \return \c true if spin box is cleared
*/
bool QtxIntSpinBox::isCleared() const
{
}
/*!
- Changes cleared status of spin box
- \param on - new status
+ \brief Change "cleared" status of the spin box.
+ \param on new "cleared" status
*/
void QtxIntSpinBox::setCleared( const bool on )
{
if ( myCleared == on )
return;
-
+
myCleared = on;
- updateDisplay();
+ setSpecialValueText( specialValueText() );
}
/*!
- Changes value of spin box
- \param val - new value of spin box
+ \brief Convert value to the text.
+ \param val value being converted
+ \return string containing the converted value
*/
-void QtxIntSpinBox::setValue( int value )
+QString QtxIntSpinBox::textFromValue( int val ) const
{
- myCleared = false;
-
- QSpinBox::setValue( value );
+ return myCleared ? QString() : QSpinBox::textFromValue( val );
}
/*!
- Custom event filter
-*/
-bool QtxIntSpinBox::eventFilter( QObject* o, QEvent* e )
-{
- if ( !myCleared || o != editor() || !editor()->text().stripWhiteSpace().isEmpty() )
- return QSpinBox::eventFilter( o, e );
-
- if ( e->type() == QEvent::FocusOut || e->type() == QEvent::Leave || e->type() == QEvent::Hide )
- return false;
+ \brief Perform \a steps increment/decrement steps.
+
+ The \a steps value can be any integer number. If it is > 0,
+ the value incrementing is done, otherwise value is decremented
+ \a steps times.
- if ( e->type() == QEvent::KeyPress &&
- ( ((QKeyEvent*)e)->key() == Key_Tab || ((QKeyEvent*)e)->key() == Key_BackTab ) )
- {
- QApplication::sendEvent( this, e );
- return true;
- }
-
- return QSpinBox::eventFilter( o, e );
-}
-
-/*!
- Sets integer value by text in editor
+ \param steps number of increment/decrement steps
*/
-void QtxIntSpinBox::interpretText()
+void QtxIntSpinBox::stepBy( int steps )
{
myCleared = false;
- QSpinBox::interpretText();
+ QSpinBox::stepBy( steps );
}
/*!
- Updates text of editor
-*/
-void QtxIntSpinBox::updateDisplay()
-{
- if ( myBlocked )
- return;
-
- bool block = myBlocked;
- myBlocked = true;
-
- QSpinBox::updateDisplay();
-
- if ( myCleared )
- editor()->clear();
- else if ( editor()->hasFocus() )
- {
- if ( editor()->text() == specialValueText() )
- editor()->selectAll();
- else
- editor()->setSelection( prefix().length(), editor()->text().length() - prefix().length() - suffix().length() );
- }
-
- myBlocked = block;
-}
-
-/*!
- Custom handler for leave event
-*/
-void QtxIntSpinBox::leaveEvent( QEvent* e )
-{
- if ( !myCleared )
- QSpinBox::leaveEvent( e );
-}
-
-/*!
- Custom handler for wheel event
-*/
-void QtxIntSpinBox::wheelEvent( QWheelEvent* e )
-{
- if ( !isEnabled() )
- return;
-
- QSpinBox::wheelEvent( e );
- updateDisplay();
-}
-
-/*!
- SLOT: called if text is changed
+ \brief Called when user enters the text in the spin box.
+ \param txt current spin box text (not used)
*/
void QtxIntSpinBox::onTextChanged( const QString& )
{
- if ( !myBlocked )
- myCleared = false;
+ myCleared = false;
}
#include "Qtx.h"
-#include <qspinbox.h>
+#include <QSpinBox>
class QTX_EXPORT QtxIntSpinBox : public QSpinBox
{
- Q_OBJECT
+ Q_OBJECT
public:
- QtxIntSpinBox( QWidget* = 0, const char* = 0 );
- QtxIntSpinBox( int, int, int = 1, QWidget* = 0, const char* = 0 );
+ QtxIntSpinBox( QWidget* = 0 );
+ QtxIntSpinBox( int, int, int = 1, QWidget* = 0 );
virtual ~QtxIntSpinBox();
- bool isCleared() const;
- virtual void setCleared( const bool );
+ bool isCleared() const;
+ virtual void setCleared( const bool );
- virtual bool eventFilter( QObject*, QEvent* );
-
-public slots:
- virtual void setValue( int );
-
+ virtual void stepBy( int );
+
protected slots:
- virtual void onTextChanged( const QString& );
+ virtual void onTextChanged( const QString& );
protected:
- virtual void interpretText();
- virtual void updateDisplay();
- virtual void leaveEvent( QEvent* );
- virtual void wheelEvent( QWheelEvent* );
+ virtual QString textFromValue( int ) const;
private:
- bool myCleared;
- bool myBlocked;
+ bool myCleared;
};
#endif
// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
+//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
+// License as published by the Free Software Foundation; either
// version 2.1 of the License.
-//
-// This library 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
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
// File: QtxListAction.cxx
-// Author: Sergey TELKOV (Based on code by Eugene AKSENOV)
+// Author: Sergey TELKOV
#include "QtxListAction.h"
-#include <qvbox.h>
-#include <qlabel.h>
-#include <qlayout.h>
-#include <qtooltip.h>
-#include <qlistbox.h>
-#include <qtoolbar.h>
-#include <qwmatrix.h>
-#include <qpopupmenu.h>
-#include <qtoolbutton.h>
-#include <qobjectlist.h>
-#include <qapplication.h>
-
-static const char* list_arrow_icon[] = {
-"10 6 2 1",
-"# c #000000",
-" c none",
-" ",
-" ####### ",
-" ##### ",
-" ### ",
-" # ",
-" "
-};
+#include <QMenu>
+#include <QLabel>
+#include <QVBoxLayout>
+#include <QMouseEvent>
+#include <QListWidget>
+#include <QToolButton>
+#include <QApplication>
/*!
- \class QtxListAction::ToolButton
- Custom tool button
+ \class QtxListAction::ScrollEvent
+ \internal
+ \brief Event for the scrolling in the list of actions.
*/
-class QtxListAction::ToolButton : public QToolButton
+
+class QtxListAction::ScrollEvent : public QEvent
{
public:
- ToolButton( QtxListAction*, QWidget* = 0, const char* = 0 );
- virtual ~ToolButton();
+ enum { Scroll = User + 1 };
- virtual QSize sizeHint() const;
+ ScrollEvent( bool down ) : QEvent( (QEvent::Type)Scroll ), myDown( down ) {}
+ virtual ~ScrollEvent() {}
+
+ bool isDown() const { return myDown; }
private:
- QtxListAction* myAction;
+ bool myDown;
};
/*!
- Constructor
+ \class QtxListAction::ListWidget
+ \internal
+ \brief List of actions.
*/
-QtxListAction::ToolButton::ToolButton( QtxListAction* a, QWidget* parent, const char* name )
-: QToolButton( parent, name ),
-myAction( a )
-{
- setIconSet( QPixmap( list_arrow_icon ) );
-}
-/*!
- Destructor
-*/
-QtxListAction::ToolButton::~ToolButton()
+class QtxListAction::ListWidget : public QListWidget
{
- if ( myAction )
- myAction->controlDeleted( this );
-}
+public:
+ ListWidget( QWidget* parent = 0 ) : QListWidget( parent ) {}
+ virtual ~ListWidget() {}
-/*!
- \return the recommended size for the widget
-*/
-QSize QtxListAction::ToolButton::sizeHint() const
-{
- QSize sz = iconSet().pixmap().size();
- return QSize( sz.width() + 2, sz.height() + 2 );
-}
+protected:
+ virtual void scrollContentsBy( int dx, int dy )
+ {
+ QListWidget::scrollContentsBy( dx, dy );
+ if ( dy != 0 )
+ QApplication::postEvent( viewport(), new ScrollEvent( dy <= 0 ) );
+ }
+};
/*!
- Constructs an list action with given parent and name. If toggle is true the
- action will be a toggle action, otherwise it will be a command action.
+ \class QtxListAction::ListFrame
+ \internal
+ \brief Expanding frame with action list and comment.
*/
-QtxListAction::QtxListAction( QObject* parent, const char* name, bool toggle )
-: QtxAction( parent, name, toggle ),
-myFrame( 0 ),
-myMode( Item ),
-myRaise( false )
+
+class QtxListAction::ListFrame: public QMenu
{
- initialize();
-}
+public:
+ ListFrame( QtxListAction*, QWidget* parent );
+ virtual ~ListFrame();
-/*!
- This constructor creates an action with the following properties: the
- description text, the icon or iconset icon, the menu text and keyboard
- accelerator. It is a child of given parent and named specified name.
- If toggle is true the action will be a toggle action, otherwise it will
- be a command action.
-*/
+ void clear();
+ const QStringList names() const;
+ void addNames( const QStringList& );
-QtxListAction::QtxListAction( const QString& text, const QIconSet& icon,
- const QString& menuText, int accel,
- QObject* parent, const char* name, bool toggle )
-: QtxAction( text, icon, menuText, accel, parent, name, toggle ),
-myFrame( 0 ),
-myMode( Item ),
-myRaise( false )
-{
- initialize();
-}
+ void setSingleComment( const QString& );
+ void setMultipleComment( const QString& );
-/*!
- This constructor creates an action with the following properties: the
- description text, the menu text and keyboard accelerator. It is a child
- of given parent and named specified name. If toggle is true the action
- will be a toggle action, otherwise it will be a command action.
-*/
+ int selected() const;
+ void setSelected( const int );
-QtxListAction::QtxListAction( const QString& text, const QString& menuText,
- int accel, QObject* parent, const char* name, bool toggle )
-: QtxAction( text, menuText, accel, parent, name, toggle ),
-myFrame( 0 ),
-myMode( Item ),
-myRaise( false )
-{
- initialize();
-}
+ int linesNumber() const;
+ int charsNumber() const;
-/*!
- Destructor.
-*/
+ void setLinesNumber( const int );
+ void setCharsNumber( const int );
-QtxListAction::~QtxListAction()
-{
- if ( myFrame ) {
- myFrame->myAction = 0;
- delete myFrame;
- myFrame = 0;
- }
-}
+ virtual QSize sizeHint() const;
+ virtual QSize minimumSizeHint() const;
-/*!
- Name: popupMode [public]
- Desc: Returns popup mode. If popup mode "Item" (default) then action will
- be added into popup menu as menu item. If popup mode "SubMenu" then
- action will be added into popup menu as sub menu with list of items.
-*/
+ virtual bool eventFilter( QObject*, QEvent* );
-int QtxListAction::popupMode() const
-{
- return myMode;
-}
+ virtual void setVisible( bool );
+
+protected:
+ virtual void keyPressEvent( QKeyEvent* );
+
+private:
+ void accept();
+ void updateComment();
+ void setNames( const QStringList& );
+ void removePostedEvens( QObject*, int );
+
+private:
+ QListWidget* myList;
+ QStringList myNames;
+ QtxListAction* myAction;
+ QLabel* myComment;
+
+ int myLines;
+ int myChars;
+
+ QString mySingleComment;
+ QString myMultipleComment;
+};
/*!
- Name: setPopupMode [public]
- Desc: Set the popup mode. Popup mode define way in this action will be
- added into popup menu. This function should be used before addTo.
-*/
+ \brief Constructor.
+ \param a list action
+ \param parent parent widget
+*/
+QtxListAction::ListFrame::ListFrame( QtxListAction* a, QWidget* parent )
+: QMenu( parent ),
+ myList( 0 ),
+ myAction( a ),
+ myComment( 0 ),
+ myLines( 5 ),
+ myChars( 5 )
+{
+ QVBoxLayout* top = new QVBoxLayout( this );
+ top->setMargin( 0 );
+ QFrame* main = new QFrame( this );
+ main->setFrameStyle( QFrame::Panel | QFrame::Raised );
+ top->addWidget( main );
+
+ QVBoxLayout* base = new QVBoxLayout( main );
+ base->setMargin( 3 );
+ base->setSpacing( 2 );
+
+ myList = new ListWidget( main );
+ myList->setSelectionMode( QListWidget::MultiSelection );
+ myList->setVerticalScrollMode( QListWidget::ScrollPerItem );
+ myList->setVerticalScrollBarPolicy( Qt::ScrollBarAsNeeded );
+ myList->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
+ myList->viewport()->installEventFilter( this );
+ myList->viewport()->setMouseTracking( true );
+ myList->setFocusPolicy( Qt::NoFocus );
+
+ myComment = new QLabel( main );
+ myComment->setFrameStyle( QFrame::Panel | QFrame::Sunken );
+ myComment->setAlignment( Qt::AlignCenter );
+ myMultipleComment = "%1";
-void QtxListAction::setPopupMode( const int mode )
-{
- myMode = mode;
+ base->addWidget( myList );
+ base->addWidget( myComment );
}
/*!
- \return list of names
+ \brief Destructor.
*/
-QStringList QtxListAction::names() const
+QtxListAction::ListFrame::~ListFrame()
{
- QStringList lst;
- if ( myFrame )
- lst = myFrame->names();
- return lst;
}
/*!
- Name: addNames [public]
- Desc: Fills the list of actions. Removes the old contents from
- the list if 'clear' is true.
+ \brief Clear list of names.
*/
-
-void QtxListAction::addNames( const QStringList& names, bool clear )
+void QtxListAction::ListFrame::clear()
{
- if ( !myFrame )
- return;
-
- if ( clear )
- myFrame->clear();
-
- myFrame->addNames( names );
-
- QStringList lst = myFrame->names();
- for ( PopupsMap::Iterator pit = myPopups.begin(); pit != myPopups.end(); ++pit )
- {
- int i = 1;
- QPopupMenu* pm = (QPopupMenu*)pit.key();
- for ( QStringList::ConstIterator it = lst.begin(); it != lst.end(); ++it )
- pit.data().popup->insertItem( *it, i++ );
- pm->setItemEnabled( pit.data().id, isEnabled() && pit.data().popup->count() );
- }
-
- for ( ButtonsMap::Iterator bit = myButtons.begin(); bit != myButtons.end(); ++bit )
- {
- bit.data().drop->setEnabled( isEnabled() && !lst.isEmpty() );
- bit.data().main->setEnabled( isEnabled() && !lst.isEmpty() );
- }
+ myNames.clear();
+ setNames( myNames );
}
/*!
- Name: addTo [virtual public]
- Desc: Adds this control to 'popup' or 'toolbar'.
-*/
-
-bool QtxListAction::addTo( QWidget* w )
-{
- if ( myButtons.contains( w ) || myPopups.contains( w ) )
- return false;
-
- if ( !w->inherits( "QPopupMenu" ) || popupMode() != SubMenu )
- if ( !QtxAction::addTo( w ) )
- return false;
-
-#if QT_VER < 3
- if ( w->children() )
- addedTo( (QWidget*)w->children()->getLast(), w );
-#endif
-
- if ( w->inherits( "QToolBar" ) )
- {
- Buttons& entry = myButtons[w];
- QHBox* dropWrap = new QHBox( w );
- entry.drop = new ToolButton( this, dropWrap, "qt_dockwidget_internal" );
-
- entry.drop->setTextLabel( text() );
- entry.drop->setToggleButton( true );
- entry.drop->setAutoRaise( entry.main->autoRaise() );
-
- entry.main->setEnabled( isEnabled() && !myFrame->names().isEmpty() );
- entry.drop->setEnabled( isEnabled() && !myFrame->names().isEmpty() );
-
- entry.main->installEventFilter( this );
- entry.drop->installEventFilter( this );
+ \brief Add names to the list.
- QToolTip::add( entry.drop, toolTip(), myTipGroup, statusTip() );
+ Truncates each name to fit the frame width.
+ Method QtxListAction::setCharsNumber(int) can be used to change
+ the frame width (in characters).
- connect( entry.drop, SIGNAL( toggled( bool ) ), this, SLOT( onExpand( bool ) ) );
- }
- else if ( w->inherits( "QPopupMenu" ) && popupMode() == SubMenu )
- {
- Popups entry;
- QPopupMenu* pm = (QPopupMenu*)w;
-
- entry.popup = new QPopupMenu( pm );
- entry.id = pm->insertItem( text(), entry.popup );
-
- int i = 1;
- QStringList lst = myFrame->names();
- for ( QStringList::ConstIterator it = lst.begin(); it != lst.end(); ++it )
- {
- int id = entry.popup->insertItem( *it );
- entry.popup->setItemParameter( id, i++ );
- }
- pm->setItemEnabled( entry.id, isEnabled() && entry.popup->count() );
- myPopups.insert( w, entry );
-
- connect( entry.popup, SIGNAL( activated( int ) ), this, SLOT( onActivated( int ) ) );
- }
-
-#if QT_VER >= 3
- connect( w, SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
-#endif
-
- return true;
-}
-
-/*!
- Name: addTo [virtual public]
- Desc: Adds this control to 'popup' or 'toolbar'. Allow to specify index
- for adding into 'popup'.
+ \param names list of names to be added
+ \sa setNames(), QtxListAction::setCharsNumber(int)
*/
-
-bool QtxListAction::addTo( QWidget* w, const int idx )
+void QtxListAction::ListFrame::addNames( const QStringList& names )
{
- return QtxAction::addTo( w, idx );
+ for ( QStringList::ConstIterator it = names.begin(); it != names.end(); ++it )
+ myNames.append( *it );
+ setNames( myNames );
}
/*!
- Name: removeFrom [virtual public]
- Desc: Removes this control from 'popup' or 'toolbar'.
-*/
+ \brief Set names to the list.
+
+ Truncates each name to fit the frame width.
+ Method QtxListAction::setCharsNumber(int) can be used to change
+ the frame width (in characters).
-bool QtxListAction::removeFrom( QWidget* w )
+ \param names list of names to be set
+ \sa addNames(), QtxListAction::setCharsNumber(int)
+*/
+void QtxListAction::ListFrame::setNames( const QStringList& names )
{
- if ( !QtxAction::removeFrom( w ) )
- return false;
+ if ( !myList )
+ return;
- if ( w->inherits( "QToolBar" ) )
+ myList->clear();
+ QStringList strList;
+ for ( QStringList::const_iterator it = names.begin(); it != names.end(); ++it )
{
- if ( myFrame )
- myFrame->hide();
-
- if ( myButtons.contains( w ) )
+ QString s = *it;
+ QFontMetrics fm = myList->fontMetrics();
+ int maxW = charsNumber() * fm.maxWidth();
+ int w = fm.width( s );
+ if ( w > maxW )
{
- Buttons& entry = myButtons[w];
-
- if ( entry.drop->parent() && entry.drop->parent()->parent() == w )
- delete entry.drop->parent();
- else
- delete entry.drop;
+ QString extra( "..." );
+ int len = s.length();
+ int extraLen = fm.width( extra ) + 1;
+ while ( true )
+ {
+ w = fm.width( s, --len );
+ if ( w + extraLen < maxW )
+ {
+ s = s.left( len );
+ break;
+ }
+ }
+ s += extra;
}
- myButtons.remove( w );
+ strList.append( s );
}
- else if ( w->inherits( "QPopupMenu" ) )
- myPopups.remove( w );
-
-#if QT_VER >= 3
- disconnect( w, SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
-#endif
-
- return true;
+ myList->addItems( strList );
}
/*!
- Name: setEnabled [virtual public slot]
- Desc: Enables/disables this control.
+ \brief Get list of names.
+ \return list of names
*/
-
-void QtxListAction::setEnabled( bool enable )
+const QStringList QtxListAction::ListFrame::names() const
{
- QtxAction::setEnabled( enable );
-
- bool isOn = enable && !myFrame->names().isEmpty();
-
- for ( ButtonsMap::Iterator bit = myButtons.begin(); bit != myButtons.end(); ++bit )
- {
- bit.data().drop->setEnabled( isOn );
- bit.data().main->setEnabled( isOn );
- }
-
- for ( PopupsMap::Iterator pit = myPopups.begin(); pit != myPopups.end(); ++pit )
- {
- QPopupMenu* cont = (QPopupMenu*)pit.key();
- cont->setItemEnabled( pit.data().id, isOn );
- }
+ return myNames;
}
/*!
- Name: setMaxLines [public]
- Desc: Sets max number of lines that list frame shows
- without vertical scroll bar. Default value is 5.
+ \brief Get maximum numer of lines shown without activation of vertical scroll bar.
+ \return number of lines
+ \sa setLinesNumber(), charsNumber(), setCharsNumber()
*/
-
-void QtxListAction::setMaxLines( int nlines )
+int QtxListAction::ListFrame::linesNumber() const
{
- myFrame->setMaxLines( nlines );
+ return myLines;
}
/*!
- Name: setMaxLineChars [public]
- Desc: Sets max number of characters in a line which list frame shows
- without truncation. Default value is 12 (the widest char size is used).
-*/
+ \brief Get maximum numer of characters in the line.
-void QtxListAction::setMaxLineChars( int nchars )
-{
- myFrame->setMaxLineChars( nchars );
-}
+ If the name length is greater than this value, it will be truncated.
-/*!
- Name: setComment [public]
- Desc: Sets the format Qt string for comments displayed under the list
- of actions for one action and for several actions.
- Ex. "Undo %1 actions" format string will work as "Undo 3 actions"
- when 3 actions are selected. The default format string is "%1".
+ \return number of characters
+ \sa setCharsNumber(), linesNumber(), setLinesNumber()
*/
-
-void QtxListAction::setComment( const QString& c, const QString& sc )
+int QtxListAction::ListFrame::charsNumber() const
{
- if ( !myFrame )
- return;
-
- myFrame->setSingleComment( sc.isEmpty() ? c : sc );
- myFrame->setMultipleComment( c );
+ return myChars;
}
/*!
- Name: eventFilter [virtual public]
- Desc: Reimplemented to paint the tool buttons in 2D/3D.
+ \brief Set maximum numer of lines shown without activation of vertical scroll bar.
+ \param maxLines number of lines
+ \sa linesNumber(), charsNumber(), setCharsNumber()
*/
-
-bool QtxListAction::eventFilter( QObject* o, QEvent* e )
+void QtxListAction::ListFrame::setLinesNumber( const int maxLines )
{
- if ( !myRaise && ( e->type() == QEvent::Enter || e->type() == QEvent::Leave ) )
- {
- QWidget* obj = 0;
- QWidget* wid = widget( (QWidget*)o );
- if ( o == mainButton( wid ) )
- obj = dropButton( wid );
- else if ( o == dropButton( wid ) )
- obj = mainButton( wid );
-
- if ( obj )
- {
- myRaise = true;
- QApplication::sendEvent( obj, e );
- obj->repaint();
- myRaise = false;
- }
- }
- return QObject::eventFilter( o, e );
+ myLines = maxLines;
}
/*!
- Name: addedTo [protected]
- Desc: Reimplemented for internal reasons.
-*/
+ \brief Set maximum numer of characters in the line.
-void QtxListAction::addedTo( QWidget* actionWidget, QWidget* container )
-{
-#if QT_VER >= 3
- QtxAction::addedTo( actionWidget, container );
-#endif
+ If the name length is greater than this value, it will be truncated.
- if ( !container->inherits( "QToolBar" ) )
- return;
-
- Buttons entry;
- entry.main = (QToolButton*)actionWidget;
+ \param maxChars number of characters
+ \sa charsNumber(), linesNumber(), setLinesNumber()
+*/
+void QtxListAction::ListFrame::setCharsNumber( const int maxChars )
+{
+ if ( myChars == maxChars )
+ return;
- myButtons.insert( container, entry );
+ myChars = maxChars;
+ setNames( myNames );
}
/*!
- Name: initialize [private]
- Desc: Initialization of object QtxListAction.
+ \brief Set comment which is displayed when single name is selected.
+ \param comment comment format
*/
-
-void QtxListAction::initialize()
+void QtxListAction::ListFrame::setSingleComment( const QString& comment )
{
- myTipGroup = new QToolTipGroup( this );
-
- myFrame = new QtxListFrame( this, qApp->mainWidget() );
- myFrame->setMaxLines( 5 );
- myFrame->setMaxLineChars( 7 );
-
- myFrame->hide();
-
- connect( myFrame, SIGNAL( hided() ), this, SLOT( onHided() ) );
- connect( this, SIGNAL( activated() ), this, SLOT( onSingle() ) );
- connect( myFrame, SIGNAL( selected( int ) ), this, SLOT( onMultiple( int ) ) );
-
- connect( myTipGroup, SIGNAL( removeTip() ), this, SLOT( clearStatusText() ) );
- connect( myTipGroup, SIGNAL( showTip( const QString& ) ), this, SLOT( showStatusText( const QString& ) ) );
+ mySingleComment = comment;
+ setNames( myNames );
+ updateComment();
}
/*!
- Name: onSingle [private slot]
- Desc: Called when a single action is selected.
+ \brief Set comment which is displayed when multiple names are selected.
+ \param comment comment format
*/
-
-void QtxListAction::onSingle()
+void QtxListAction::ListFrame::setMultipleComment( const QString& comment )
{
- emit activated( 1 );
+ myMultipleComment = comment;
+ setNames( myNames );
+ updateComment();
}
/*!
- Name: onMultiple [private slot]
- Desc: Called when multiple actions are selected.
+ \brief Update displayed comment.
*/
-
-void QtxListAction::onMultiple( int numActions )
+void QtxListAction::ListFrame::updateComment()
{
- if ( myFrame )
- myFrame->hide();
-
- if ( numActions > 0 )
- emit activated( numActions );
+ QString com;
+ int selNum = selected();
+ if ( selNum > 1 )
+ com = myMultipleComment;
+ else if ( selNum > 0 && !mySingleComment.isEmpty() )
+ com = mySingleComment;
+
+ if ( !com.isEmpty() )
+ com = com.arg( selNum );
+
+ myComment->setText( com );
}
/*!
- Name: onExpand [private slot]
- Desc: Activates the list of actions.
+ \brief Get preferable size for the list widget.
+ \return preferable size
*/
-
-void QtxListAction::onExpand( bool on )
+QSize QtxListAction::ListFrame::sizeHint() const
{
- const QObject* obj = sender();
- if ( on )
- {
- QWidget* wid = widget( (QToolButton*)obj );
- QToolButton* main = mainButton( wid );
- myFrame->setOwner( main );
- if ( main )
- myFrame->show();
- }
- else
- myFrame->hide();
+ return QSize( myList->fontMetrics().maxWidth() * charsNumber() + 10,
+ qMax( 1, linesNumber() ) * ( myList->fontMetrics().height() + 2 ) +
+ myComment->sizeHint().height() );
}
/*!
- SLOT: called when frame is hidden
+ \brief Get preferable minimum size for the list widget.
+ \return preferable minimum size
*/
-void QtxListAction::onHided()
+QSize QtxListAction::ListFrame::minimumSizeHint() const
{
- for ( ButtonsMap::Iterator bit = myButtons.begin(); bit != myButtons.end(); ++bit )
- {
- bool block = bit.data().drop->signalsBlocked();
- bit.data().drop->blockSignals( true );
- bit.data().drop->setOn( false );
- bit.data().drop->blockSignals( block );
- }
+ return QSize( myList->fontMetrics().maxWidth() * charsNumber() + 10,
+ qMax( 1, linesNumber() ) * ( myList->fontMetrics().height() + 2 ) +
+ myComment->sizeHint().height() );
}
/*!
- Name: onActivated [private slot]
- Desc: Called when a sub menu item is activated.
+ \brief Validate the action.
*/
-
-void QtxListAction::onActivated( int id )
+void QtxListAction::ListFrame::accept()
{
- QPopupMenu* pm = (QPopupMenu*)sender();
- int num = pm->itemParameter( id );
- if ( num > 0 )
- emit activated( num );
+ int sel = selected();
+ if ( sel && myAction )
+ myAction->onMultiple( sel );
}
/*!
- Name: onDestroyed [private slot]
- Desc: Called when a container widget is destroyed.
+ \brief Called when list widget is shown/hidden.
+ \param on if \c true, widget is shown, otherswise it is hidden
*/
-
-void QtxListAction::onDestroyed( QObject* obj )
+void QtxListAction::ListFrame::setVisible( bool on )
{
- if ( !obj->isWidgetType() )
- return;
+ if ( on )
+ {
+ myList->setFocus();
+ myList->scrollToItem( myList->item( 0 ), QListWidget::PositionAtTop );
+ setSelected( 0 );
+ updateComment();
+ }
- myPopups.remove( (QWidget*)obj );
- myButtons.remove( (QWidget*)obj );
+ QMenu::setVisible( on );
}
/*!
- Name: widget [private]
- Desc: Returns container widget for specified control.
-*/
+ \brief Process key press event.
-QWidget* QtxListAction::widget( QWidget* obj ) const
+ The following keys are supported:
+ - Up/Down
+ - PageUp/PageDown
+ - Enter
+ - Escape
+
+ \param e key press event
+*/
+void QtxListAction::ListFrame::keyPressEvent( QKeyEvent* e )
{
- QWidget* wid = 0;
- for ( PopupsMap::ConstIterator pit = myPopups.begin(); pit != myPopups.end() && !wid; ++pit )
- if ( pit.data().popup == obj )
- wid = pit.key();
+ if ( e->type() == QEvent::KeyRelease )
+ return;
- for ( ButtonsMap::ConstIterator bit = myButtons.begin(); bit != myButtons.end() && !wid; ++bit )
- if ( bit.data().main == obj || bit.data().drop == obj )
- wid = bit.key();
+ e->accept();
- return wid;
+ int selNum = selected();
+ switch( e->key() )
+ {
+ case Qt::Key_Up:
+ setSelected( qMax( 1, selNum - 1 ) );
+ break;
+ case Qt::Key_Down:
+ setSelected( qMax( 1, selNum + 1 ) );
+ break;
+ case Qt::Key_PageUp:
+ setSelected( qMax( 1, selNum - linesNumber() ) );
+ break;
+ case Qt::Key_PageDown:
+ setSelected( selNum += linesNumber() );
+ break;
+ case Qt::Key_Home:
+ setSelected( 1 );
+ break;
+ case Qt::Key_End:
+ setSelected( myList->count() );
+ break;
+ case Qt::Key_Return:
+ accept();
+ break;
+ case Qt::Key_Escape:
+ hide();
+ break;
+ }
}
/*!
- Name: listPopup [private]
- Desc: Returns sub popup menu widget for specified container.
+ \brief Process mouse events on the viewport of the list widget.
+ \param o object recieving event (viewport)
+ \param e event
+ \return \c true if further event processing should be stopped.
*/
-
-QPopupMenu* QtxListAction::listPopup( QWidget* wid ) const
+bool QtxListAction::ListFrame::eventFilter( QObject* o, QEvent* e )
{
- QPopupMenu* p = 0;
- if ( myPopups.contains( wid ) )
- p = myPopups[wid].popup;
- return p;
-}
+ bool res = true;
-/*!
- Name: mainButton [private]
- Desc: Returns main tool button for specified container.
-*/
+ switch( e->type() )
+ {
+ case QEvent::MouseMove:
+ {
+ QMouseEvent* me = (QMouseEvent*)e;
+ if ( !myList->viewport()->rect().contains( me->pos() ) )
+ setSelected( 0 );
+ else if ( myList->itemAt( me->pos() ) )
+ setSelected( myList->row( myList->itemAt( me->pos() ) ) + 1 );
+ }
+ break;
+ case QEvent::MouseButtonRelease:
+ accept();
+ case QEvent::MouseButtonPress:
+ case QEvent::MouseButtonDblClick:
+ break;
+ case ScrollEvent::Scroll:
+ {
+ ScrollEvent* se = (ScrollEvent*)e;
+ QPoint pos = myList->viewport()->mapFromGlobal( QCursor::pos() );
+ if ( myList->viewport()->rect().contains( pos ) )
+ {
+ if ( myList->itemAt( pos ) )
+ setSelected( myList->row( myList->itemAt( pos ) ) + 1 );
+ }
+ else if ( se->isDown() )
+ setSelected( myList->row( myList->itemAt( myList->viewport()->rect().bottomLeft() -
+ QPoint( 0, myList->fontMetrics().height() / 2 ) ) ) + 1 );
+ else
+ setSelected( myList->row( myList->itemAt( myList->viewport()->rect().topLeft() +
+ QPoint( 0, myList->fontMetrics().height() / 2 ) ) ) + 1 );
+ }
+ break;
+ default:
+ res = false;
+ break;
+ }
-QToolButton* QtxListAction::mainButton( QWidget* wid ) const
-{
- QToolButton* mb = 0;
- if ( myButtons.contains( wid ) )
- mb = myButtons[wid].main;
- return mb;
+ if ( res )
+ return true;
+ else
+ return QMenu::eventFilter( o, e );
}
/*!
- Name: dropButton [private]
- Desc: Returns drop tool button for specified container.
+ \brief Get number of selected names.
+ \return number of selected items
*/
-
-QToolButton* QtxListAction::dropButton( QWidget* wid ) const
+int QtxListAction::ListFrame::selected() const
{
- QToolButton* db = 0;
- if ( myButtons.contains( wid ) )
- db = myButtons[wid].drop;
- return db;
+ int sel = 0;
+ QModelIndexList indexes = myList->selectionModel()->selectedRows();
+ for ( QModelIndexList::const_iterator it = indexes.begin(); it != indexes.end(); ++it )
+ sel = qMax( sel, (*it).row() + 1 );
+
+ return sel;
}
/*!
- Name: controlDeleted [private]
- Desc: Called when action child controls deleted.
+ \brief Set number of selected names.
+ \param lastSel number of items to be selected
*/
-
-void QtxListAction::controlDeleted( QWidget* wid )
+void QtxListAction::ListFrame::setSelected( const int lastSel )
{
- QWidget* w = 0;
- for ( ButtonsMap::Iterator it = myButtons.begin(); it != myButtons.end() && !w; ++it )
- {
- if ( it.data().main == wid || it.data().drop == wid )
- w = it.key();
- }
+ int last = qMin( lastSel, (int)myList->count() );
- if ( w )
- {
- if ( myFrame )
- myFrame->hide();
+ QItemSelection selection;
+ QItemSelectionModel* selModel = myList->selectionModel();
- myButtons.remove( w );
- }
+ for ( int i = 0; i < last; i++ )
+ selection.select( selModel->model()->index( i, 0 ), selModel->model()->index( i, 0 ) );
+
+ selModel->select( selection, QItemSelectionModel::ClearAndSelect );
+
+ int item = last - 1;
+
+ myList->scrollToItem( myList->item( item ) );
+ myList->clearFocus();
+
+ removePostedEvens( myList->viewport(), ScrollEvent::Scroll );
+
+ updateComment();
}
/*!
- \class QtxListFrame
- Frame for the list of actions
+ \brief Filter all events of specified type sent to specified object.
+ \param o object
+ \param type event type to be filtered
*/
-class QtxListFrame::ScrollEvent : public QCustomEvent
+void QtxListAction::ListFrame::removePostedEvens( QObject* o, int type )
{
-public:
- enum { Scroll = User + 1 };
-
- ScrollEvent( bool down ) : QCustomEvent( Scroll ), myDown( down ) {};
- virtual ~ScrollEvent() {};
-
- bool isDown() const { return myDown; };
+ class Filter : public QObject
+ {
+ public:
+ Filter() : QObject( 0 ) {}
+ virtual bool eventFilter( QObject*, QEvent* )
+ {
+ return true;
+ }
+ };
-private:
- bool myDown;
-};
+ Filter f;
+ o->installEventFilter( &f );
+ QApplication::sendPostedEvents( o, type );
+}
/*!
- Class: QtxListAction
- Level: Public
+ \class QtxListAction
+ \brief Action with associated list of items.
+
+ This class can be helpuful, for example, for creation of Undo/Redo
+ toolbar items which show list of available commands in the popup list box.
*/
/*!
- Constructor
+ \brief Constructor.
+ \param parent parent object
*/
-QtxListFrame::QtxListFrame( QtxListAction* a, QWidget* parent, WFlags f )
-: QFrame( parent, 0, WStyle_Customize | WStyle_NoBorderEx | WType_Popup | WStyle_Tool | WStyle_StaysOnTop ),
-myList( 0 ),
-myOwner( 0 ),
-myAction( a ),
-myComment( 0 ),
-myMaxLines( 5 ),
-myMaxLineChars( 10 ),
-myScrollVal( 0 ),
-myScrollBlock( false )
+QtxListAction::QtxListAction( QObject* parent )
+: QWidgetAction( parent ),
+ myFrame( 0 )
{
- QVBoxLayout* theLayout = new QVBoxLayout( this, 3 );
- theLayout->setResizeMode( QLayout::FreeResize );
-
- myList = new QListBox( this );
- myList->setSelectionMode( QListBox::Multi );
- myList->setHScrollBarMode( QScrollView::AlwaysOff );
- myList->setFocusPolicy( NoFocus );
-
- QPalette p = myList->palette();
- p.setColor( QPalette::Inactive, QColorGroup::Highlight,
- p.color( QPalette::Active, QColorGroup::Highlight ) );
- p.setColor( QPalette::Inactive, QColorGroup::HighlightedText,
- p.color( QPalette::Active, QColorGroup::HighlightedText ) );
- myList->setPalette( p );
-
- /* We'll have the vertical scroll bar only and
- truncate the names which are too wide */
- connect( myList, SIGNAL( contentsMoving( int, int ) ), this, SLOT( onScroll( int, int ) ) );
-
- myComment = new QLabel( this );
- myComment->setFrameStyle( Panel | Sunken );
- myComment->setAlignment( AlignCenter );
- myMultipleComment = "%1";
-
- theLayout->addWidget( myList );
- theLayout->addWidget( myComment );
-
- setFrameStyle( Panel | Raised );
+ initialize();
}
/*!
- Destructor
+ \brief Constructor.
+ \param icon action icon
+ \param menuText menu text
+ \param accel key accelerator
+ \param parent parent object
*/
-QtxListFrame::~QtxListFrame()
+QtxListAction::QtxListAction( const QIcon& icon, const QString& menuText,
+ int accel, QObject* parent )
+: QWidgetAction( parent ),
+ myFrame( 0 )
{
- if ( myAction )
- myAction->myFrame = 0;
+ setIcon( icon );
+ setText( menuText );
+ setShortcut( accel );
+
+ initialize();
}
/*!
- Clears list of names [ public ]
+ \brief Constructor.
+ \param menuText menu text
+ \param accel key accelerator
+ \param parent parent object
*/
-
-void QtxListFrame::clear()
+QtxListAction::QtxListAction( const QString& menuText, int accel, QObject* parent )
+: QWidgetAction( parent ),
+ myFrame( 0 )
{
- myNames.clear();
- setNames( myNames );
+ setText( menuText );
+ setShortcut( accel );
+
+ initialize();
}
/*!
- Adds a names to the list. Truncates the name to fit to the frame width.
- Use QtxListAction::setMaxLineChar( int ) to set the width in characters. [ public ]
+ \brief Constructor.
+ \param text action description text (tooltip)
+ \param menuText menu text
+ \param accel key accelerator
+ \param parent parent object
*/
-
-void QtxListFrame::addNames( const QStringList& names )
+QtxListAction::QtxListAction( const QString& text, const QString& menuText,
+ int accel, QObject* parent )
+: QWidgetAction( parent ),
+ myFrame( 0 )
{
- for ( QStringList::ConstIterator it = names.begin(); it != names.end(); ++it )
- myNames.append( *it );
- setNames( myNames );
+ setText( menuText );
+ setShortcut( accel );
+ setToolTip( text );
+
+ initialize();
}
/*!
- Sets a names to the list. Truncates the name to fit to the frame width.
- Use QtxListAction::setMaxLineChar( int ) to set the width in characters. [ public ]
+ \brief Constructor.
+ \param text action description text (tooltip)
+ \param icon action icon
+ \param menuText menu text
+ \param accel key accelerator
+ \param parent parent object
*/
-
-void QtxListFrame::setNames( const QStringList& names )
+QtxListAction::QtxListAction( const QString& text, const QIcon& icon,
+ const QString& menuText, int accel, QObject* parent )
+: QWidgetAction( parent ),
+ myFrame( 0 )
{
- if ( !myList )
- return;
-
- myList->clear();
+ setIcon( icon );
+ setText( menuText );
+ setShortcut( accel );
+ setToolTip( text );
- for ( QStringList::ConstIterator it = names.begin(); it != names.end(); ++it )
- {
- QString s = *it;
- QFontMetrics fm = myList->fontMetrics();
- int maxW = myMaxLineChars * fm.maxWidth();
- int w = fm.width( s );
- if ( w > maxW )
- {
- QString extra( "..." );
- int len = s.length();
- int extraLen = fm.width( extra ) + 1;
- while ( true )
- {
- w = fm.width( s, --len );
- if ( w + extraLen < maxW )
- {
- s = s.left( len );
- break;
- }
- }
- s += extra;
- }
- myList->insertItem( s );
- }
+ initialize();
}
/*!
- \return list of names
+ \brief Destructor.
*/
-const QStringList QtxListFrame::names() const
+QtxListAction::~QtxListAction()
{
- return myNames;
+ delete myFrame;
+ myFrame = 0;
}
/*!
- Sets max number of lines shown without activation of vertical scroll bar. [ public ]
+ \brief Get popup mode.
+ \return current popup mode (QtxListAction::PopupMode)
+ \sa setPopupMode()
*/
-
-void QtxListFrame::setMaxLines( int maxLines )
+int QtxListAction::popupMode() const
{
- myMaxLines = maxLines;
+ return menu() ? SubMenu : Item;
}
/*!
- Sets max number of chars in line ( the rest will be truncated ). [ public ]
+ \brief Set popup mode.
+ \param mode new popup mode (QtxListAction::PopupMode)
+ \sa popupMode()
*/
-
-void QtxListFrame::setMaxLineChars( int maxChars )
+void QtxListAction::setPopupMode( const int mode )
{
- if ( myMaxLineChars == maxChars )
- return;
+ if ( mode == popupMode() )
+ return;
- myMaxLineChars = maxChars;
- setNames( myNames );
+ if ( mode == Item )
+ {
+ delete menu();
+ setMenu( 0 );
+ }
+ else
+ setMenu( new QMenu( 0 ) );
+
+ onChanged();
}
/*!
- Sets the format of single comment. [ public ]
+ \brief Get current list of names.
+ \return list of names
*/
-
-void QtxListFrame::setSingleComment( const QString& comment )
+QStringList QtxListAction::names() const
{
- mySingleComment = comment;
- setNames( myNames );
- updateComment();
+ QStringList lst;
+ if ( myFrame )
+ lst = myFrame->names();
+ return lst;
}
/*!
- Sets the format of multiple comment. [ public ]
-*/
+ \brief Add names to the list.
-void QtxListFrame::setMultipleComment( const QString& comment )
-{
- myMultipleComment = comment;
- setNames( myNames );
- updateComment();
-}
+ Truncates each name to fit the frame width.
+ Method setCharsNumber() can be used to change
+ the frame width (in characters).
-/*!
- Updates comment display. [ public ]
+ \param names list of names to be added
+ \param clear if \c true, remove the old contents from the list
+ \sa setCharsNumber()
*/
-
-void QtxListFrame::updateComment()
+void QtxListAction::addNames( const QStringList& names, bool clear )
{
- QString com;
- int selNum = selected();
- if ( selNum > 1 )
- com = myMultipleComment;
- else if ( selNum > 0 && !mySingleComment.isEmpty() )
- com = mySingleComment;
+ if ( !myFrame )
+ return;
+
+ if ( clear )
+ myFrame->clear();
- if ( !com.isEmpty() )
- com = com.arg( selNum );
+ myFrame->addNames( names );
- myComment->setText( com );
+ onChanged();
}
/*!
- Sets owner
- \param wo - new owner
+ \brief Get maximum numer of lines shown without activation of vertical scroll bar.
+ \return number of lines
+ \sa setLinesNumber(), charsNumber(), setCharsNumber()
*/
-void QtxListFrame::setOwner( QWidget* wo )
+int QtxListAction::linesNumber() const
{
- myOwner = wo;
- if ( myOwner )
- {
- QPoint lpos;
- if ( myOwner->parentWidget() && myOwner->parentWidget()->inherits( "QToolBar" ) &&
- ((QToolBar*)myOwner->parentWidget())->orientation() == Qt::Vertical )
- lpos = QPoint( myOwner->x() + myOwner->width() + 2, myOwner->y() );
- else
- lpos = QPoint( myOwner->x(), myOwner->y() + myOwner->height() + 2 );
- QPoint gpos = myOwner->parentWidget() ? myOwner->parentWidget()->mapToGlobal( lpos )
- : myOwner->mapToGlobal( lpos );
- if ( parentWidget() )
- move( parentWidget()->mapFromGlobal( gpos ) );
- else
- move( gpos );
- }
+ return myFrame->linesNumber();
}
/*!
- Validates the action. [ private slot ]
-*/
+ \brief Get maximum numer of characters in the line.
+
+ If the name length is greater than this value, it will be truncated.
-void QtxListFrame::accept()
+ \return number of characters
+ \sa setCharsNumber(), linesNumber(), setLinesNumber()
+*/
+int QtxListAction::charsNumber() const
{
- emit selected( selected() );
+ return myFrame->charsNumber();
}
/*!
- Cancels the action. [ private slot ]
+ \brief Set maximum numer of lines shown without activation of vertical scroll bar.
+ \param nlines number of lines (5 by default)
+ \sa linesNumber(), charsNumber(), setCharsNumber()
*/
-
-void QtxListFrame::reject()
+void QtxListAction::setLinesNumber( const int nlines )
{
- emit selected( 0 );
+ myFrame->setLinesNumber( nlines );
}
/*!
- Initializes / shows the frame. [ virtual public slot ]
-*/
-
-void QtxListFrame::show()
-{
- int cnt = (int)myList->count();
- if ( cnt )
- {
- myScrollVal = 0;
- myList->setTopItem( 0 );
- myList->clearSelection();
- myList->setMinimumSize( 0, ( QMIN( cnt + 1, myMaxLines ) ) * myList->itemHeight() + 1 );
- setSelected( 1 );
+ \brief Set maximum numer of characters in the line.
- int linstep = myList->itemHeight();
- myList->verticalScrollBar()->setLineStep( linstep );
- myList->verticalScrollBar()->setPageStep( myMaxLines * linstep );
+ If the name length is greater than this value, it will be truncated.
- QFontMetrics fm = myList->fontMetrics();
- layout()->invalidate();
- int maxHeight = layout()->minimumSize().height() + layout()->margin();
- int maxWidth = myMaxLineChars * fm.maxWidth();
- for ( uint i = 0; i <= myList->count(); i++ )
- maxWidth = QMAX( maxWidth, fm.width( myList->text( i ) ) );
+ \param maxChars number of characters (5 by default)
+ \sa charsNumber(), linesNumber(), setLinesNumber()
+*/
- resize( width(), maxHeight );
+void QtxListAction::setCharsNumber( const int nchars )
+{
+ myFrame->setCharsNumber( nchars );
+}
- myList->updateGeometry();
+/*!
+ \brief Set the format Qt string for comments displayed under the list
+ of actions for one action and for several actions.
- QApplication::sendPostedEvents();
+ Example: "Undo %1 actions" format string will work as "Undo 3 actions"
+ when 3 actions are selected. The default format string is "%1".
- myList->resizeContents( myList->contentsWidth(),
- myList->itemHeight() * cnt );
- if ( myList->contentsHeight() > myList->visibleHeight() )
- maxWidth += myList->verticalScrollBar()->width();
+ \param c single action comment format
+ \param c multiple actions comment format
+*/
+void QtxListAction::setComment( const QString& c, const QString& sc )
+{
+ if ( !myFrame )
+ return;
- QString single = mySingleComment.arg( cnt );
- QString multi = myMultipleComment.arg( cnt );
- int comWidth = QMAX( myComment->fontMetrics().width( single ), myComment->fontMetrics().width( multi ) );
- if ( myComment->frameWidth() )
- comWidth += myComment->fontMetrics().width( "x" );
+ myFrame->setSingleComment( sc.isEmpty() ? c : sc );
+ myFrame->setMultipleComment( c );
+}
- maxWidth = QMAX( maxWidth, comWidth );
+/*!
+ \brief Create action widget.
- resize( maxWidth, maxHeight );
- updateComment();
+ This function is called whenever the action is added
+ to a container widget that supports custom widgets like menu or toolbar.
+
+ \param parent container widget the action is added to
+ \return tool button for toolbar and 0 otherwise
+*/
+QWidget* QtxListAction::createWidget( QWidget* parent )
+{
+ if ( parent && parent->inherits( "QMenu" ) )
+ return 0;
- qApp->installEventFilter( this );
+ QToolButton* tb = new QToolButton( parent );
+ tb->setText( text() );
+ tb->setIcon( icon() );
+ tb->setPopupMode( QToolButton::MenuButtonPopup );
+ tb->setMenu( myFrame );
+ tb->setEnabled( isEnabled() && !names().isEmpty() );
+ tb->setToolTip( toolTip() );
+ connect( tb, SIGNAL( clicked( bool ) ), this, SLOT( onSingle( bool ) ) );
- QFrame::show();
- }
+ return tb;
}
/*!
- Cleanup. [ virtual public slot ]
-*/
+ \brief Destroy action widget.
-void QtxListFrame::hide()
+ This function is called whenever the action is removed
+ from a container widget that supports custom widgets like menu or toolbar.
+
+ \param widget container widget the action is removed from
+*/
+void QtxListAction::deleteWidget( QWidget* widget )
{
- qApp->removeEventFilter( this );
- QFrame::hide();
- emit hided();
+ delete widget;
}
/*!
- Processes KeyUp/KeyDown, PageUp/PageDown, CR and Esc keys.
- Returns 'true' if event is eaten, 'false' otherwise. [ private ]
+ \brief Initialize the action.
*/
-
-bool QtxListFrame::handleKeyEvent( QObject* , QKeyEvent* e )
+void QtxListAction::initialize()
{
- if ( e->type() == QEvent::KeyRelease )
- return true;
+ setPopupMode( Item );
+
+ myFrame = new QtxListAction::ListFrame( this, 0 );
+ myFrame->setLinesNumber( 7 );
+ myFrame->setCharsNumber( 5 );
- int selNum = selected();
- switch( e->key() )
- {
- case Key_Up:
- setSelected( QMAX( 1, selNum - 1 ) );
- break;
- case Key_Down:
- setSelected( QMAX( 1, selNum + 1 ) );
- break;
- case Key_PageUp:
- setSelected( QMAX( 1, selNum - myMaxLines ) );
- break;
- case Key_PageDown:
- setSelected( selNum += myMaxLines );
- break;
- case Key_Home:
- setSelected( 1 );
- break;
- case Key_End:
- setSelected( myList->count() );
- break;
- case Key_Return:
- accept();
- break;
- case Key_Escape:
- reject();
- break;
- }
- return true;
+ myFrame->hide();
+
+ connect( this, SIGNAL( changed() ), this, SLOT( onChanged() ) );
+ connect( this, SIGNAL( triggered( bool ) ), this, SLOT( onSingle( bool ) ) );
}
/*!
- Selects items on move, validates on button release. If object 'o' is not our name list,
- we close the frame. Returns 'true' if event is eaten, 'false' otherwise. [ private ]
+ \brief Called the action contents is changed.
*/
-
-bool QtxListFrame::handleMouseEvent( QObject* o, QMouseEvent* e )
+void QtxListAction::onChanged()
{
- switch( e->type() )
- {
- case QEvent::MouseButtonPress:
- {
- if ( o != myList->viewport() && !isPopup() )
- reject();
- return true;
- }
- case QEvent::MouseMove:
+ QStringList lst = myFrame->names();
+
+ if ( menu() )
{
- if ( o == myList->viewport() )
+ menu()->clear();
+ for ( QStringList::iterator iter = lst.begin(); iter != lst.end(); ++iter )
{
- QListBoxItem* lbi = myList->itemAt( e->pos() );
- if ( lbi )
- setSelected( myList->index( lbi ) + 1 );
+ QAction* a = new QAction( *iter, menu() );
+ menu()->addAction( a );
+ connect( a, SIGNAL( triggered( bool ) ), this, SLOT( onTriggered( bool ) ) );
}
- break;
}
- case QEvent::MouseButtonRelease:
+
+ QList<QWidget*> widList = createdWidgets();
+ for ( QList<QWidget*>::iterator it = widList.begin(); it != widList.end(); ++it )
{
- if ( o == myList->viewport() )
- accept();
- else
- reject();
- break;
- }
- default:
- break;
+ (*it)->setEnabled( isEnabled() && !lst.isEmpty() );
+ QToolButton* tb = ::qobject_cast<QToolButton*>( *it );
+ if ( tb )
+ {
+ tb->setText( text() );
+ tb->setIcon( icon() );
+ tb->setToolTip( toolTip() );
+ }
}
- return true;
}
/*!
- Custom event filter
+ \brief Called when a user click action button.
+ \param on (not used)
*/
-bool QtxListFrame::event( QEvent* e )
-{
- if ( e->type() != (int)ScrollEvent::Scroll )
- return QFrame::event( e );
- ScrollEvent* se = (ScrollEvent*)e;
- if ( se->isDown() )
- setSelected( myList->topItem() + myList->numItemsVisible() );
- else
- setSelected( myList->topItem() + 1 );
-
- return true;
-}
-
-/*!
- Watches mouse events on the viewport of the list. [ virtual public ]
-*/
-
-bool QtxListFrame::eventFilter( QObject* o, QEvent* e )
+void QtxListAction::onSingle( bool /*on*/ )
{
- bool isKeyEvent = ( e->type() == QEvent::KeyPress ||
- e->type() == QEvent::KeyRelease );
- bool isMouseEvent = ( e->type() == QEvent::MouseMove ||
- e->type() == QEvent::MouseButtonPress ||
- e->type() == QEvent::MouseButtonRelease ||
- e->type() == QEvent::MouseButtonDblClick );
-
- if ( isKeyEvent )
- {
- if ( handleKeyEvent( o, ( QKeyEvent* )e ) )
- return true;
- }
- else if ( isMouseEvent && o != myList->verticalScrollBar() )
- {
- if ( handleMouseEvent( o, ( QMouseEvent*)e ) )
- return true;
- }
-
- if ( o != this && ( e->type() == QEvent::Resize || e->type() == QEvent::Move ) )
- setOwner( myOwner );
-
- return QFrame::eventFilter( o, e );
+ onMultiple( 1 );
}
/*!
- Selects operations while scrolling the list. [ private slot ]
+ \brief Called when multiple items are selected.
*/
-
-void QtxListFrame::onScroll( int x, int y )
+void QtxListAction::onMultiple( const int numActions )
{
- int dx = y - myScrollVal;
- if ( !myScrollBlock )
- QApplication::postEvent( this, new ScrollEvent( dx > 0 ) );
- myScrollVal = y;
+ if ( myFrame )
+ myFrame->hide();
+
+ if ( numActions > 0 )
+ emit activated( numActions );
}
/*!
- Selects the actions [ 0 - lastSel ]. [ public ]
+ \brief Called when user activates an items in the popup sub menu.
+ \param on (not used)
*/
-
-void QtxListFrame::setSelected( const int lastSel )
+void QtxListAction::onTriggered( bool /*on*/ )
{
- int last = QMIN( lastSel, (int)myList->count() );
-
- for ( int i = 0; i < (int)myList->count(); i++ )
- myList->setSelected( i, i < last );
-
- int item = last - 1;
-
- myScrollBlock = true;
-
- if ( item < myList->topItem() )
- myList->setTopItem( item );
-
- if ( item >= myList->topItem() + myList->numItemsVisible() )
- myList->setTopItem( item - myList->numItemsVisible() + 1 );
-
- myScrollBlock = false;
+ if ( !menu() )
+ return;
- myList->clearFocus();
+ QList<QAction*> actionList = menu()->actions();
+ int idx = actionList.indexOf( ::qobject_cast<QAction*>( sender() ) );
+ if ( idx < 0 )
+ return;
- updateComment();
+ emit activated( idx + 1 );
}
/*!
- return number of selected items
+ \fn QtxListAction::activated(int numItems );
+ \brief This signal is emitted when an action is activated.
+ \param numItems number of items being selected in the action list.
*/
-int QtxListFrame::selected() const
-{
- uint sel = 0;
- while ( sel < myList->count() && myList->isSelected( sel ) )
- sel++;
- return sel;
-}
// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
+//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
+// License as published by the Free Software Foundation; either
// version 2.1 of the License.
-//
-// This library 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
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#ifndef QTXLISTACTION_H
#define QTXLISTACTION_H
-#include "QtxAction.h"
-
-#include <qmap.h>
-#include <qframe.h>
-#include <qstringlist.h>
+#include "Qtx.h"
-class QLabel;
-class QListBox;
-class QPopupMenu;
-class QToolButton;
-class QToolTipGroup;
-
-class QtxListFrame;
+#include <QStringList>
+#include <QWidgetAction>
#ifdef WIN32
#pragma warning( disable:4251 )
#endif
-class QTX_EXPORT QtxListAction : public QtxAction
+class QTX_EXPORT QtxListAction : public QWidgetAction
{
- Q_OBJECT
-
- Q_PROPERTY( QStringList names READ names WRITE addNames )
+ Q_OBJECT
- class ToolButton;
+ class ListFrame;
+ class ListWidget;
+ class ScrollEvent;
public:
- enum { Item, SubMenu } PopupMode;
+ //! Popup mode
+ enum {
+ Item, //!< action is added to popup menu as menu item
+ SubMenu //!< action is added to popup menu as sub menu with list of items
+ } PopupMode;
public:
- QtxListAction( QObject* = 0, const char* = 0, bool = false );
- QtxListAction( const QString&, const QIconSet&, const QString&, int, QObject*, const char* = 0, bool = false );
- QtxListAction( const QString&, const QString&, int, QObject*, const char* = 0, bool = false );
- virtual ~QtxListAction();
+ QtxListAction( QObject* = 0 );
+ QtxListAction( const QString&, int, QObject* );
+ QtxListAction( const QString&, const QString&, int, QObject* );
+ QtxListAction( const QIcon&, const QString&, int, QObject* );
+ QtxListAction( const QString&, const QIcon&, const QString&, int, QObject* );
+ virtual ~QtxListAction();
-public:
- virtual bool addTo( QWidget* );
- virtual bool addTo( QWidget*, const int );
-
- virtual bool removeFrom( QWidget* );
- virtual bool eventFilter( QObject*, QEvent* );
+ int popupMode() const;
+ void setPopupMode( const int );
- int popupMode() const;
- void setPopupMode( const int );
+ QStringList names() const;
+ void addNames( const QStringList&, bool = true );
+ void setComment( const QString&, const QString& = QString() );
- QStringList names() const;
- void addNames( const QStringList&, bool = true );
- void setComment( const QString&, const QString& = QString::null );
+ int linesNumber() const;
+ int charsNumber() const;
- void setMaxLines( int );
- void setMaxLineChars( int );
+ void setLinesNumber( const int );
+ void setCharsNumber( const int );
signals:
- void activated( int );
-
-public slots:
- virtual void setEnabled( bool );
+ void activated( int );
private slots:
- void onHided();
- void onSingle();
- void onExpand( bool );
- void onMultiple( int );
- void onActivated( int );
- void onDestroyed( QObject* );
+ void onChanged();
+ void onMultiple( const int );
+ void onSingle( bool = false );
+ void onTriggered( bool = false );
protected:
- virtual void addedTo( QWidget*, QWidget* );
-
-private:
- void initialize();
- QWidget* widget( QWidget* ) const;
- QPopupMenu* listPopup( QWidget* ) const;
- QToolButton* mainButton( QWidget* ) const;
- QToolButton* dropButton( QWidget* ) const;
+ virtual QWidget* createWidget( QWidget* );
+ virtual void deleteWidget( QWidget* );
- void controlDeleted( QWidget* );
-
-private:
- typedef struct { int id; QPopupMenu* popup; } Popups;
- typedef struct { QToolButton* main; QToolButton* drop; } Buttons;
- typedef QMap<QWidget*, Popups> PopupsMap;
- typedef QMap<QWidget*, Buttons> ButtonsMap;
-
private:
- int myMode;
- QtxListFrame* myFrame;
- bool myRaise;
- PopupsMap myPopups;
- ButtonsMap myButtons;
- QToolTipGroup* myTipGroup;
-
- friend class ToolButton;
- friend class QtxListFrame;
-};
-
-/*!
- \class QtxListFrame
-*/
-class QtxListFrame : public QFrame
-{
- Q_OBJECT
+ void initialize();
- class ScrollEvent;
-
-public:
- QtxListFrame( QtxListAction*, QWidget* parent, WFlags f = 0 );
- virtual ~QtxListFrame();
-
- void clear();
- const QStringList names() const;
- void addNames( const QStringList& );
-
- void setSingleComment( const QString& );
- void setMultipleComment( const QString& );
-
- int selected() const;
- void setSelected( const int );
-
- void setMaxLines( int );
- void setMaxLineChars( int );
-
- virtual bool event( QEvent* );
- virtual bool eventFilter( QObject*, QEvent* );
-
- void setOwner( QWidget* );
-
- void updateComment();
-
-signals:
- void hided();
- void selected( int );
-
-public slots:
- virtual void show();
- virtual void hide();
-
-private slots:
- void reject();
- void accept();
-
- void onScroll( int, int );
-
private:
- void setNames( const QStringList& );
- bool handleKeyEvent( QObject*, QKeyEvent* );
- bool handleMouseEvent( QObject*, QMouseEvent* );
+ ListFrame* myFrame; //!< list of actions shown as submenu
- friend class QtxListAction;
-
-private:
- QListBox* myList;
- QStringList myNames;
- QWidget* myOwner;
- QtxListAction* myAction;
- QLabel* myComment;
-
- QString mySingleComment;
- QString myMultipleComment;
-
- int myMaxLines;
- int myMaxLineChars;
-
- int myScrollVal;
- bool myScrollBlock;
+ friend class QtxListAction::ListFrame;
};
#ifdef WIN32
#include "Qtx.h"
-#include <qlistbox.h>
+// This file isn't yet ported to Qt4 => there are some corrections for OCCViewer porting -->
+//#include <qlistbox.h>
+#include <QListWidget>
+#include <QListWidgetItem>
+// <--
#ifdef WIN32
#pragma warning( disable:4251 )
class QLineEdit;
class QValidator;
-class QTX_EXPORT QtxListBox : public QListBox
+class QTX_EXPORT QtxListBox : public QListWidget//QListBox // This file isn't yet ported to Qt4 => there are some corrections for OCCViewer porting
{
Q_OBJECT
public:
- QtxListBox( QWidget* = 0, const char* = 0, WFlags = 0 );
+ QtxListBox( QWidget* = 0, const char* = 0, Qt::WindowFlags = 0 );
virtual ~QtxListBox();
bool isEditEnabled() const;
bool defaultEditAction() const;
bool isModificationEnabled() const;
- QListBoxItem* editedItem() const;
+ QListWidgetItem* editedItem() const;
int editedIndex() const;
void startEdition( const int );
- void startEdition( const QListBoxItem* );
+ void startEdition( const QListWidgetItem* );
void endEdition( const bool );
void ensureItemVisible( const int );
- void ensureItemVisible( const QListBoxItem* );
+ void ensureItemVisible( const QListWidgetItem* );
virtual bool eventFilter( QObject*, QEvent* );
signals:
void itemEdited( int );
- void itemEdited( QListBoxItem* );
+ void itemEdited( QListWidgetItem* );
void itemMoved( int, int );
public slots:
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-
-#include "QtxListOfOperations.h"
-#include <stdarg.h>
-
-/*!
- Constructor
-*/
-QtxListOfOperations::QtxListOfOperations()
-{
-}
-
-/*!
- Destructor
-*/
-QtxListOfOperations::~QtxListOfOperations()
-{
-}
-
-/*!
- \return fills list with brackets symbols
- \param list - list to be filled
- \param open - if it is true, it is necessary to fill with open brackets otherwise with close
-*/
-void QtxListOfOperations::bracketsList( QStringList& list, bool open ) const
-{
- OperationSetsIterator anIt = mySets.begin(),
- aLast = mySets.end();
- QStringList custom;
- for( ; anIt!=aLast; anIt++ )
- {
- custom.clear();
- (*anIt).myOperations->bracketsList( custom, open );
- QStringList::const_iterator aSIt = custom.begin(),
- aSLast = custom.end();
- for( ; aSIt!=aSLast; aSIt++ )
- if( list.contains( *aSIt )==0 )
- list.append( *aSIt );
- }
-}
-
-/*!
- Fills list with operation names
-*/
-void QtxListOfOperations::opersList( QStringList& list ) const
-{
- OperationSetsIterator anIt = mySets.begin(),
- aLast = mySets.end();
- QStringList custom;
- for( ; anIt!=aLast; anIt++ )
- {
- custom.clear();
- (*anIt).myOperations->opersList( custom );
- QStringList::const_iterator aSIt = custom.begin(),
- aSLast = custom.end();
- for( ; aSIt!=aSLast; aSIt++ )
- if( list.contains( *aSIt )==0 )
- list.append( *aSIt );
- }
-}
-
-/*!
- Create some value by it's string representation
-*/
-bool QtxListOfOperations::createValue( const QString& str, QtxValue& val ) const
-{
- bool ok;
- OperationSetsIterator anIt = mySets.begin(),
- aLast = mySets.end();
- for( ; anIt!=aLast; anIt++ )
- {
- ok = (*anIt).myOperations->createValue( str, val );
- if( ok )
- break;
- }
- return ok;
-}
-
-/*!
- \return priority of operation
-*/
-int QtxListOfOperations::prior( const QString& op, bool isBin ) const
-{
- OperationSetsIterator anIt = mySets.begin(),
- aLast = mySets.end();
- int prior = 0;
- for( ; anIt!=aLast; anIt++ )
- {
- prior = (*anIt).myOperations->prior( op, isBin );
- if( prior>0 )
- {
- prior+=(*anIt).myAddPrior;
- break;
- }
- }
- return prior>0 ? prior : 0;
-}
-
-/*!
- \return whether values with passed types are valid for arguments of operation
- \param op - name of operation
- \param t1 - type of first argument
- \param t2 - type of second argument
-*/
-QtxParser::Error QtxListOfOperations::isValid( const QString& op,
- const QVariant::Type t1,
- const QVariant::Type t2 ) const
-{
- OperationSetsIterator anIt = mySets.begin(),
- aLast = mySets.end();
- QtxParser::Error err = QtxParser::OK;
- for( ; anIt!=aLast; anIt++ )
- {
- err = (*anIt).myOperations->isValid( op, t1, t2 );
- if( err==QtxParser::OK )
- break;
- }
- return err;
-}
-
-/*!
- Calculates result of operation
- \return one of error states
- \param op - name of operation
- \param v1 - first operation argument (must be used also to store result)
- \param v2 - second operation argument
-*/
-QtxParser::Error QtxListOfOperations::calculate( const QString& op,
- QtxValue& v1,
- QtxValue& v2 ) const
-{
- const char* deb = op.latin1();
-
- OperationSetsIterator anIt = mySets.begin(),
- aLast = mySets.end();
- QtxValue nv1, nv2;
- for( ; anIt!=aLast; anIt++ )
- {
- nv1 = v1;
- nv2 = v2;
- if( (*anIt).myOperations->isValid( op, v1.type(), v2.type() ) == QtxParser::OK )
- {
- QtxParser::Error err = (*anIt).myOperations->calculate( op, nv1, nv2 );
- if( err==QtxParser::OK || err==QtxParser::InvalidResult )
- {
- QString oop = (*anIt).myName;
- const char* ooo = oop.latin1();
- v1 = nv1; v2 = nv2;
- return err;
- }
- }
- }
- return QtxParser::InvalidOperation;
-}
-
-/*!
- Clears list of operations
-*/
-void QtxListOfOperations::clear()
-{
- mySets.clear();
-}
-
-/*!
- \return true if list contains operations
- \param name - name of operation
-*/
-bool QtxListOfOperations::has( const QString& name ) const
-{
- OperationSetsIterator anIt = mySets.begin(),
- aLast = mySets.end();
- for( ; anIt!=aLast; anIt++ )
- if( (*anIt).myName == name )
- return true;
- return false;
-}
-
-/*!
- Appends operations to list
- \param name - name of operations
- \param oper - operations
- \param prior - additional prior
-*/
-void QtxListOfOperations::append( const QString& name, QtxOperations* oper,
- int prior )
-{
- insert( name, oper, prior );
-}
-
-/*!
- Prepends operations to list
- \param name - name of operations
- \param oper - operations
- \param prior - additional prior
-*/
-void QtxListOfOperations::prepend( const QString& name, QtxOperations* oper,
- int prior )
-{
- insert( name, oper, prior, 0 );
-}
-
-/*!
- Inserts operations to list
- \param name - name of operations
- \param oper - operations
- \param prior - additional prior
- \param pos - insert position
-*/
-void QtxListOfOperations::insert( const QString& name, QtxOperations* oper,
- int prior, int pos )
-{
- if( has( name ) || oper==NULL || prior<0 )
- return;
-
- OperationSet op;
- op.myName = name;
- op.myOperations = oper;
- op.myAddPrior = prior;
- if( pos<0 )
- mySets.append( op );
- else
- mySets.insert( mySets.at( pos ), op );
-}
-
-/*!
- Removes operations from list
- \param name - name of operations
-*/
-void QtxListOfOperations::remove( const QString& name )
-{
- OperationSets::iterator anIt = mySets.begin(),
- aLast = mySets.end();
- for( ; anIt!=aLast; anIt++ )
- if( (*anIt).myName == name )
- {
- mySets.erase( anIt );
- break;
- }
-}
-
-/*!
- \return count of operations in list
-*/
-int QtxListOfOperations::count() const
-{
- return mySets.count();
-}
-
-/*!
- \return operations by name
- \name - name of operations
-*/
-QtxOperations* QtxListOfOperations::operations( const QString& name ) const
-{
- OperationSetsIterator anIt = mySets.begin(),
- aLast = mySets.end();
- for( ; anIt!=aLast; anIt++ )
- if( (*anIt).myName == name )
- return (*anIt).myOperations;
- return NULL;
-}
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-// File: QtxListOfOperations.h
-// Author: Alexander SOLOVYOV
-
-#ifndef __QTX_LIST_OF_OPERATIONS_HEADER__
-#define __QTX_LIST_OF_OPERATIONS_HEADER__
-
-#include "Qtx.h"
-#include "QtxOperations.h"
-
-#ifdef WIN32
-#pragma warning( disable:4251 )
-#endif
-
-
-/*!
- Class: QtxListOfOperations
-
- This class provides special variant of QtxOperations. It contains list of QtxOperations* with
- fixed order. When it is necessary to calculate operation or get it's priority, this operation is
- being found starting from first item. It makes possible to create unions of operations. Every QtxOperations*
- has priority, which is added to priority of operation, so that it makes possible to increase priority of
- whole group of operations
-*/
-class QTX_EXPORT QtxListOfOperations : public QtxOperations
-{
-public:
- QtxListOfOperations();
- virtual ~QtxListOfOperations();
-
- virtual void opersList( QStringList& ) const;
- virtual void bracketsList( QStringList&, bool open ) const;
-
- virtual bool createValue( const QString&, QtxValue& ) const;
- virtual int prior ( const QString&, bool isBin ) const;
- virtual QtxParser::Error isValid( const QString&,
- const QVariant::Type,
- const QVariant::Type ) const;
- virtual QtxParser::Error calculate( const QString&, QtxValue&, QtxValue& ) const;
-
- void clear ();
- bool has ( const QString& ) const;
- void append ( const QString&, QtxOperations*, int prior );
- void prepend( const QString&, QtxOperations*, int prior );
- void insert ( const QString&, QtxOperations*, int prior, int pos = -1 );
- void remove ( const QString& );
- int count () const;
- QtxOperations* operations( const QString& ) const;
-
-private:
- typedef struct
- {
- QString myName;
- QtxOperations* myOperations;
- int myAddPrior;
-
- } OperationSet;
-
- typedef QValueList< OperationSet > OperationSets;
- typedef OperationSets::const_iterator OperationSetsIterator;
-
- OperationSets mySets;
-};
-
-#endif
#include "QtxResourceEdit.h"
#include <qmap.h>
-#include <qhbox.h>
+//#include <qhbox.h>
+#include <QWidget>
#include <qframe.h>
#include <qgroupbox.h>
#include <qvalidator.h>
Base class for preferences items.
*/
-class QtxListResourceEdit::PrefItem : public QHBox, public Item
+class QtxListResourceEdit::PrefItem : public QWidget/*QHBox*/, public Item
{
public:
PrefItem( const int, QtxResourceEdit*, Item* = 0, QWidget* = 0 );
void setIndexes( const QVariant& );
void setStrings( const QStringList& );
- void setIndexes( const QValueList<int>& );
+ void setIndexes( const QList<int>& );
private:
QComboBox* myList;
//
#include "QtxLogoMgr.h"
-#include <qhbox.h>
-#include <qlabel.h>
-#include <qstyle.h>
-#include <qimage.h>
-#include <qbitmap.h>
-#include <qlayout.h>
-#include <qmenubar.h>
-#include <qapplication.h>
+#include <QLabel>
+#include <QImage>
+#include <QBitmap>
+#include <QHBoxLayout>
+#include <QMenuBar>
+#include <QPointer>
+#include <QApplication>
+#include <QMovie>
/*!
- Constructor
+ \class QtxLogoMgr::LogoBox
+ \internal
+ \brief Logo images container.
+*/
+
+class QtxLogoMgr::LogoBox : public QWidget
+{
+public:
+ LogoBox( QMenuBar* );
+
+ QMenuBar* menuBar() const;
+ virtual bool eventFilter( QObject*, QEvent* );
+ void setLabels( const QList<QLabel*>& );
+
+protected:
+ virtual void customEvent( QEvent* );
+
+private:
+ void updateCorner();
+ void updateContents();
+
+private:
+ typedef QPointer<QWidget> WidgetPtr;
+
+private:
+ QMenuBar* myMB; //!< parent menu bar
+ QList<QLabel*> myLabels; //!< list of labels containing logo images
+ WidgetPtr myCornWid; //!< corner widget
+};
+
+/*!
+ \brief Constructor.
+ \param mb menu bar
+*/
+QtxLogoMgr::LogoBox::LogoBox( QMenuBar* mb )
+: QWidget( mb ),
+ myMB( mb ),
+ myCornWid( 0 )
+{
+ myMB->installEventFilter( this );
+ updateCorner();
+}
+
+/*!
+ \brief Get menu bar.
+ \return menu bar
+*/
+QMenuBar* QtxLogoMgr::LogoBox::menuBar() const
+{
+ return myMB;
+}
+
+/*!
+ \brief Custom event filter.
+ \param o event receiver object
+ \param e event sent to object
+ \return \c true if further event processing should be stopped
+*/
+bool QtxLogoMgr::LogoBox::eventFilter( QObject* o, QEvent* e )
+{
+ if ( o != menuBar() )
+ return false;
+
+ if ( e->type() == QEvent::MenubarUpdated || e->type() == QEvent::Resize )
+ updateCorner();
+
+ if ( e->type() == QEvent::ChildAdded || e->type() == QEvent::ChildRemoved )
+ {
+ updateCorner();
+ QApplication::postEvent( this, new QEvent( QEvent::User ) );
+ }
+
+ return false;
+}
+
+/*!
+ \brief Set label widgets (logo containers).
+ \param labs list of labels
+*/
+void QtxLogoMgr::LogoBox::setLabels( const QList<QLabel*>& labs )
+{
+ for ( QList<QLabel*>::iterator it = myLabels.begin(); it != myLabels.end(); ++it )
+ {
+ if ( !labs.contains( *it ) )
+ delete *it;
+ }
+
+ myLabels = labs;
+ updateContents();
+}
+
+/*!
+ \brief Custom event processing (update logo widget).
+ \param e event (not used)
+*/
+void QtxLogoMgr::LogoBox::customEvent( QEvent* /*e*/ )
+{
+ updateCorner();
+}
+
+/*!
+ \brief Update menu bar's corner widget.
+*/
+void QtxLogoMgr::LogoBox::updateCorner()
+{
+ if ( menuBar()->cornerWidget() == this )
+ return;
+
+ myCornWid = menuBar()->cornerWidget();
+ myMB->setCornerWidget( this );
+ updateContents();
+}
+
+/*!
+ \brief Update logo manager contents.
+*/
+void QtxLogoMgr::LogoBox::updateContents()
+{
+ if ( layout() )
+ delete layout();
+
+ QHBoxLayout* base = new QHBoxLayout( this );
+ base->setMargin( 0 );
+ base->setSpacing( 3 );
+
+ for ( QList<QLabel*>::const_iterator it = myLabels.begin(); it != myLabels.end(); ++it )
+ base->addWidget( *it );
+
+ if ( myCornWid )
+ base->addWidget( myCornWid );
+
+ QApplication::sendPostedEvents();
+}
+
+/*!
+ \class QtxLogoMgr
+ \brief Provides a way to install logo pictures to the application main window.
+
+ The class includes the following functionality:
+ - add the logo image
+ - remove logo image
+ - support static images and animated images (QMovie)
+ - start/stop and pause/resume the animated logos
+*/
+
+/*!
+ \brief Constructor.
+ \param mb parent menu bar
*/
QtxLogoMgr::QtxLogoMgr( QMenuBar* mb )
-: QObject( mb ),
-myMenus( mb ),
-myId( 0 )
+: QObject( mb )
{
+ myBox = new LogoBox( mb );
}
/*!
- Destructor
+ \brief Destructor.
*/
QtxLogoMgr::~QtxLogoMgr()
{
}
/*!
- Returns the menubar.
+ \brief Get menu bar.
+ \return parent menu bar
*/
QMenuBar* QtxLogoMgr::menuBar() const
{
- return myMenus;
+ return myBox->menuBar();
}
/*!
- Returns the count of the existed logos.
+ \brief Get number of logo images.
+ \return current number of logo images
*/
int QtxLogoMgr::count() const
{
}
/*!
- Insert new logo to the menu bar area
+ \brief Insert new logo pixmap to the menu bar area.
+ \param id unique string identifier of the logo
+ \param pix logo pixmap
+ \param index logo position (if < 0, logo is added to the end)
*/
void QtxLogoMgr::insert( const QString& id, const QPixmap& pix, const int index )
{
if ( pix.isNull() )
return;
- LogoInfo* inf = 0;
+ LogoInfo& inf = insert( id, index );
+
+ inf.pix = pix;
+
+ generate();
+}
+
+/*!
+ \brief Insert new animated logo to the menu bar area.
+ \param id unique string identifier of the logo
+ \param pix logo movie
+ \param index logo position (if < 0, logo is added to the end)
+*/
+void QtxLogoMgr::insert( const QString& id, QMovie* movie, const int index )
+{
+ if ( !movie )
+ return;
+
+ LogoInfo& inf = insert( id, index );
+
+ inf.mov = movie;
+ movie->setParent( this );
+ movie->setCacheMode( QMovie::CacheAll );
+ movie->jumpToFrame( 0 );
+
+ generate();
+}
+
+/*!
+ \brief Insert new logo information structure into the logos list.
+ \param id unique string identifier of the logo
+ \param index logo position (if < 0, logo is added to the end)
+ \return logo information object
+*/
+QtxLogoMgr::LogoInfo& QtxLogoMgr::insert( const QString& id, const int index )
+{
+ LogoInfo empty;
+ empty.id = id;
+ empty.mov = 0;
int idx = find( id );
if ( idx < 0 )
{
idx = index < (int)myLogos.count() ? index : -1;
if ( idx < 0 )
- inf = &( *myLogos.append( LogoInfo() ) );
+ {
+ myLogos.append( empty );
+ idx = myLogos.count() - 1;
+ }
else
- inf = &( *myLogos.insert( myLogos.at( idx ), LogoInfo() ) );
+ myLogos.insert( idx, empty );
}
- else
- inf = &( *myLogos.at( idx ) );
+ LogoInfo& inf = myLogos[idx];
- inf->id = id;
- inf->pix = pix;
-
- generate();
+ return inf;
}
/*!
- Removes a logo
+ \brief Remove a logo.
+ \param id logo identifier
*/
void QtxLogoMgr::remove( const QString& id )
{
if ( idx < 0 )
return;
- myLogos.remove( myLogos.at( idx ) );
+ myLogos.removeAt( idx );
generate();
}
/*!
- Removes all logos
+ \brief Removes all logos.
*/
void QtxLogoMgr::clear()
{
}
/*!
- Inserts logo to menu bar
+ \brief Start the animation of movie logo.
+
+ If \a id is empty, all movie logos animation are started.
+
+ \param id logo identifier
*/
-void QtxLogoMgr::generate()
+void QtxLogoMgr::startAnimation( const QString& id )
{
- if ( !menuBar() )
- return;
+ QList<QMovie*> movList;
+ movies( id, movList );
- if ( myId )
- menuBar()->removeItem( myId );
+ for ( QList<QMovie*>::iterator it = movList.begin(); it != movList.end(); ++it )
+ (*it)->start();
+}
- myId = 0;
+/*!
+ \brief Stop the animation of movie logo.
- if ( myLogos.isEmpty() )
- return;
+ If \a id is empty, all movie logos animation are stopped.
- class LogoBox : public QHBox
- {
- public:
- LogoBox( QWidget* parent = 0, const char* name = 0, WFlags f = 0 ) : QHBox( parent, name, f ) {};
+ \param id logo identifier
+*/
+void QtxLogoMgr::stopAnimation( const QString& id )
+{
+ QList<QMovie*> movList;
+ movies( id, movList );
- void addSpacing( int spacing )
- {
- QApplication::sendPostedEvents( this, QEvent::ChildInserted );
- ((QHBoxLayout*)layout())->addSpacing( spacing );
- }
+ for ( QList<QMovie*>::iterator it = movList.begin(); it != movList.end(); ++it )
+ (*it)->stop();
+}
- protected:
- void drawContents( QPainter* p )
- {
- if ( parentWidget()->inherits( "QMenuBar" ) )
- style().drawControl( QStyle::CE_MenuBarEmptyArea, p, this, contentsRect(), colorGroup() );
- else
- QHBox::drawContents( p );
- }
- };
+/*!
+ \brief Pause/resume the animation of movie logo.
+
+ If \a pause is \c true, the animation is paused; otherwise
+ it is resumed.
+
+ If \a id is empty, the operation is performed for all movis logos.
+
+ \param pause if \c true, pause animation, otherwise resume it
+ \param id logo identifier
+*/
+void QtxLogoMgr::pauseAnimation( const bool pause, const QString& id )
+{
+ QList<QMovie*> movList;
+ movies( id, movList );
- LogoBox* cnt = new LogoBox( menuBar() );
- cnt->setSpacing( 3 );
+ for ( QList<QMovie*>::iterator it = movList.begin(); it != movList.end(); ++it )
+ (*it)->setPaused( pause );
+}
+
+/*!
+ \brief Regenerate logo manager widget contents.
+
+ Insert logo to menu bar if it not yet done, layout the widget.
+*/
+void QtxLogoMgr::generate()
+{
+ if ( !menuBar() )
+ return;
+ QList<QLabel*> labels;
for ( LogoList::const_iterator it = myLogos.begin(); it != myLogos.end(); ++it )
{
QPixmap pix = (*it).pix;
- if ( !pix.mask() )
+ QMovie* mov = (*it).mov;
+ if ( !pix.isNull() && !pix.mask() )
{
- QImage img = pix.convertToImage();
QBitmap bm;
- if ( img.hasAlphaBuffer() )
- bm = img.createAlphaMask();
+ QImage img = pix.toImage();
+ if ( img.hasAlphaChannel() )
+ bm = QPixmap::fromImage( img.createAlphaMask() );
else
- bm = img.createHeuristicMask();
+ bm = QPixmap::fromImage( img.createHeuristicMask() );
pix.setMask( bm );
}
- QLabel* logoLab = new QLabel( cnt );
- logoLab->setPixmap( (*it).pix );
+ QLabel* logoLab = new QLabel( myBox );
+ if ( mov )
+ logoLab->setMovie( mov );
+ else
+ {
+ logoLab->setPixmap( (*it).pix );
+// if ( !pix.mask().isNull() )
+// logoLab->setMask( pix.mask() );
+ }
+
logoLab->setScaledContents( false );
- logoLab->setAlignment( QLabel::AlignCenter );
+ logoLab->setAlignment( Qt::AlignCenter );
- if ( pix.mask() )
- logoLab->setMask( *pix.mask() );
+ labels.append( logoLab );
}
- QApplication::sendPostedEvents( cnt, QEvent::ChildInserted );
- cnt->addSpacing( 2 );
-
- myId = menuBar()->insertItem( cnt );
-
- QApplication::sendPostedEvents( menuBar()->parentWidget(), QEvent::LayoutHint );
- QApplication::postEvent( menuBar()->parentWidget(), new QEvent( QEvent::LayoutHint ) );
+ myBox->setLabels( labels );
}
/*!
- \return index of found logo
- \param id - logo id
+ \brief Search the logo by the specified \a id.
+ \param id logo identifier
+ \return index of logo or -1 if not found
*/
int QtxLogoMgr::find( const QString& id ) const
{
int idx = -1;
- for ( uint i = 0; i < myLogos.count() && idx < 0; i++ )
+ for ( int i = 0; i < myLogos.count() && idx < 0; i++ )
{
- if ( (*myLogos.at( i ) ).id == id )
+ if ( myLogos.at( i ).id == id )
idx = i;
}
return idx;
}
+
+/*!
+ \brief Get movie logos by specified \a id.
+
+ If \a id is empty, all movie logos are returned.
+
+ \param id logo identifier
+ \param lst list of movies, which satisfy the \a id
+*/
+void QtxLogoMgr::movies( const QString& id, QList<QMovie*>& lst ) const
+{
+ lst.clear();
+ for ( LogoList::const_iterator it = myLogos.begin(); it != myLogos.end(); ++it )
+ {
+ if ( (*it).mov && ( id.isEmpty() || id == (*it).id ) )
+ lst.append( (*it).mov );
+ }
+}
#include "Qtx.h"
-class QMenuBar;
+#include <QObject>
+#include <QList>
+#include <QPixmap>
-#include <qobject.h>
-#include <qpixmap.h>
+class QMenuBar;
+class QMovie;
#ifdef WIN32
#pragma warning( disable : 4251 )
{
Q_OBJECT
+ class LogoBox;
+
public:
QtxLogoMgr( QMenuBar* );
virtual ~QtxLogoMgr();
int count() const;
+ void insert( const QString&, QMovie*, const int = -1 );
void insert( const QString&, const QPixmap&, const int = -1 );
void remove( const QString& );
void clear();
+ void startAnimation( const QString& = QString() );
+ void stopAnimation( const QString& = QString() );
+ void pauseAnimation( const bool, const QString& = QString() );
+
QMenuBar* menuBar() const;
private:
- void generate();
- int find( const QString& ) const;
+ typedef struct { QString id; QPixmap pix; QMovie* mov; } LogoInfo;
+ typedef QList<LogoInfo> LogoList;
private:
- typedef struct { QString id; QPixmap pix; } LogoInfo;
- typedef QValueList<LogoInfo> LogoList;
+ void generate();
+ int find( const QString& ) const;
+ LogoInfo& insert( const QString&, const int );
+ void movies( const QString&, QList<QMovie*>& ) const;
private:
- int myId;
- QMenuBar* myMenus;
- LogoList myLogos;
+ LogoBox* myBox; //!< widget containing logox
+ LogoList myLogos; //!< list of logo data
};
#ifdef WIN32
#include "QtxResourceMgr.h"
-#include <qpopupmenu.h>
+#include <QMenu>
+#include <QIcon>
/*!
- Name: QtxMRUAction [public]
- Desc: Constructs an MRU action with given parent and name.
+ \class QtxMRUAction
+ \brief Menu action which provides most recent used items support.
*/
-QtxMRUAction::QtxMRUAction( QObject* parent, const char* name )
-: QtxAction( "Most Recently Used", "Most Recently Used", 0, parent, name ),
-myVisCount( 5 ),
-myPopupMode( SubMenu ),
-myInsertMode( MoveFirst )
+/*!
+ \brief Constructor.
+ \param parent parent object
+*/
+QtxMRUAction::QtxMRUAction( QObject* parent )
+: QtxAction( "Most Recently Used", "Most Recently Used", 0, parent ),
+ myVisCount( 5 ),
+ myInsertMode( MoveFirst )
{
+ setMenu( new QMenu( 0 ) );
+ connect( menu(), SIGNAL( aboutToShow() ), this, SLOT( onAboutToShow() ) );
}
/*!
- Name: QtxMRUAction [public]
- Desc: This constructor creates an action with the following properties: the
- description text, the menu text and. It is a child of given parent and
- named specified name.
+ \brief Constructor.
+ \param description (tooltip) text
+ \param menuText menu text
+ \param parent parent object
*/
-
-QtxMRUAction::QtxMRUAction( const QString& text, const QString& menuText, QObject* parent, const char* name )
-: QtxAction( text, menuText, 0, parent, name ),
-myVisCount( 5 ),
-myPopupMode( SubMenu ),
-myInsertMode( MoveFirst )
+QtxMRUAction::QtxMRUAction( const QString& text, const QString& menuText, QObject* parent )
+: QtxAction( text, menuText, 0, parent ),
+ myVisCount( 5 ),
+ myInsertMode( MoveFirst )
{
+ setMenu( new QMenu( 0 ) );
+ connect( menu(), SIGNAL( aboutToShow() ), this, SLOT( onAboutToShow() ) );
}
/*!
- Name: QtxMRUAction [public]
- Desc: This constructor creates an action with the following properties: the
- description text, the menu text, the icon or iconset icon and keyboard
- accelerator. It is a child of given parent and named specified name.
+ \brief Constructor.
+ \param description (tooltip) text
+ \param icon action icon
+ \param menuText menu text
+ \param parent parent object
*/
-
-QtxMRUAction::QtxMRUAction( const QString& text, const QIconSet& icon, const QString& menuText, QObject* parent, const char* name )
-: QtxAction( text, icon, menuText, 0, parent, name ),
+QtxMRUAction::QtxMRUAction( const QString& text, const QIcon& icon,
+ const QString& menuText, QObject* parent )
+: QtxAction( text, icon, menuText, 0, parent ),
myVisCount( 5 ),
-myPopupMode( SubMenu ),
myInsertMode( MoveFirst )
{
+ setMenu( new QMenu( 0 ) );
+ connect( menu(), SIGNAL( aboutToShow() ), this, SLOT( onAboutToShow() ) );
}
/*!
- Name: ~QtxMRUAction [public]
- Desc: This destructor removes all added popup items.
+ \brief Destructor.
*/
-
QtxMRUAction::~QtxMRUAction()
{
- for ( ItemsMap::ConstIterator iIt = myItems.begin(); iIt != myItems.end(); ++iIt )
- removeFrom( iIt.key() );
-
- for ( MenusMap::ConstIterator mIt = myMenus.begin(); mIt != myMenus.end(); ++mIt )
- removeFrom( mIt.key() );
+ delete menu();
}
/*!
- Name: insertMode [public]
- Desc: Returns the insert mode.
+ \brief Get items insertion policy.
+ \return insertion policy (QtxMRUAction::InsertionMode)
*/
-
int QtxMRUAction::insertMode() const
{
return myInsertMode;
}
/*!
- Name: setInsertMode [public]
- Desc: Returns the insert mode. Can be following values:
- MoveFirst - place the specified link to the first position in any case
- MoveLast - place the specified link to the last position in any case
- AddFirst - if inserted link doesn't exist then add to the first position
- AddLast - if inserted link doesn't exist then add to the lase position
+ \brief Set items insertion policy.
+ \param mode insertion policy (QtxMRUAction::InsertionMode)
*/
-
void QtxMRUAction::setInsertMode( const int mode )
{
myInsertMode = mode;
}
/*!
- Name: popupMode [public]
- Desc: Returns the popup mode.
-*/
-
-int QtxMRUAction::popupMode() const
-{
- return myPopupMode;
-}
-
-/*!
- Name: setPopupMode [public]
- Desc: Set the popup mode. If this mode is 'Items' then method "addTo" creates the
- items in the specified popup menu. If mode is 'SubMenu' then items will be
- create in sub popup menu which will be placed in specified popup.
-*/
-
-void QtxMRUAction::setPopupMode( const int mode )
-{
- myPopupMode = mode;
-}
-
-/*!
- Name: count [public]
- Desc: Returns the number of links.
+ \brief Get number of MRU items.
+ \return number of MRU items
*/
-
int QtxMRUAction::count() const
{
return myLinks.count();
}
/*!
- Name: isEmpty [public]
- Desc: Returns 'true' if there is no links.
+ \brief Check if the MRU items list is empty.
+ \return \c true if there are no MRU items
*/
-
bool QtxMRUAction::isEmpty() const
{
return myLinks.isEmpty();
}
/*!
- Name: visibleCount [public]
- Desc: Returns the number of first links which will be added to popup menu.
- If 'visibleCount' less than 1 then all links will be used.
+ \brief Get number of visible MRU items.
+ \return visible MRU items number
+ \sa setVisibleCount()
*/
-
int QtxMRUAction::visibleCount() const
{
return myVisCount;
}
/*!
- Name: setVisibleCount [public]
- Desc: Sets the number of links which will be used in popup menu.
-*/
+ \brief Set number of visible MRU items.
+
+ This method sets the maximum number of MRU items
+ to be displayed in the popup menu (5 by default).
+
+ If \a num < 1, then all MRU items will be displayed.
+ \param num visible MRU items number
+*/
void QtxMRUAction::setVisibleCount( int num )
{
if ( myVisCount == num )
return;
myVisCount = num;
-
- updateState();
}
/*!
- Name: insert [public]
- Desc: Insert the link according to the insert mode.
-*/
+ \brief Insert MRU item.
+ The item is inserted according to the current insertion policy.
+
+ \param link MRU item to be added
+*/
void QtxMRUAction::insert( const QString& link )
{
if ( myLinks.contains( link ) && ( insertMode() == AddFirst || insertMode() == AddLast ) )
return;
- myLinks.remove( link );
+ myLinks.removeAll( link );
switch ( insertMode() )
{
myLinks.append( link );
break;
}
-
- updateState();
}
/*!
- Name: remove [public]
- Desc: Removes link with specified index.
-*/
+ \brief Remove MRU item.
+
+ Does nothing if \a idx is out of range.
+ \param idx MRU item index
+*/
void QtxMRUAction::remove( const int idx )
{
if ( idx < 0 || idx >= (int)myLinks.count() )
return;
- myLinks.remove( myLinks.at( idx ) );
-
- updateState();
+ myLinks.removeAt( idx );
}
/*!
- Name: remove [public]
- Desc: Removes specified link.
-*/
+ \brief Remove MRU item.
+
+ Does nothing if there is no speicified item in the list.
+ \param link MRU item to be removed
+*/
void QtxMRUAction::remove( const QString& link )
{
- if ( myLinks.remove( link ) )
- updateState();
+ myLinks.removeAll( link );
}
/*!
- Name: item [public]
- Desc: Returns the link with specified index.
+ \brief Get MRU item
+ \param idx MRU item index
+ \return MRU item or null QString if \a idx is out of range
*/
-
QString QtxMRUAction::item( const int idx ) const
{
QString res;
}
/*!
- Name: find [public]
- Desc: Find specified link. If link exists then returns index otherwise -1 returned.
+ \brief Get MRU item index.
+ \param link MRU item
+ \return MRU item index or -1 if item is not found
*/
-
int QtxMRUAction::find( const QString& link ) const
{
- return myLinks.findIndex( link );
+ return myLinks.indexOf( link );
}
/*!
- Name: contains [public]
- Desc: Returns 'true' if given link exist.
+ \brief Check if MRU item is in the list.
+ \param link MRU item
+ \return \c true if specified item is already added to the list
*/
-
bool QtxMRUAction::contains( const QString& link ) const
{
return myLinks.contains( link );
}
/*!
- Name: addTo [public]
- Desc: Add the MRU links to the end of specified popup according to the popup mode.
+ \brief Load the MRU items from specified resources section.
+ \param resMgr resources manager
+ \param section resources section
+ \param clear if \c true, previous MRU items list is cleared
*/
-
-bool QtxMRUAction::addTo( QWidget* wid )
-{
- if ( !wid || !wid->inherits( "QPopupMenu" ) )
- return false;
-
- QPopupMenu* pm = (QPopupMenu*)wid;
- checkPopup( pm );
-
- int mode = popupMode();
-
- if ( ( mode == Items && myItems.contains( pm ) ) ||
- ( mode == SubMenu && myMenus.contains( pm ) ) )
- return false;
-
- bool exist = myItems.contains( pm ) || myMenus.contains( pm );
-
- if ( mode == SubMenu && !QtxAction::addTo( wid ) )
- return false;
-
- if ( mode == Items )
- {
- myItems.insert( pm, Item() );
- myItems[pm].pId = myItems[pm].nId -1;
- connect( pm, SIGNAL( activated( int ) ), this, SLOT( onActivated( int ) ) );
- }
- else if ( mode == SubMenu )
- {
- myMenus.insert( pm, new QPopupMenu( pm ) );
- setPopup( pm, pm->idAt( pm->count() - 1 ), myMenus[pm] );
- connect( myMenus[pm], SIGNAL( activated( int ) ), this, SLOT( onActivated( int ) ) );
- }
-
- if ( !exist )
- {
- connect( pm, SIGNAL( aboutToShow() ), this, SLOT( onAboutToShow() ) );
- connect( pm, SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
- }
-
- return insertLinks( pm, mode );
-}
-
-/*!
- Name: addTo [public]
- Desc: Add the MRU links to the specified popup at given index according to the popup mode.
-*/
-
-bool QtxMRUAction::addTo( QWidget* wid, const int idx )
-{
- if ( !QtxAction::addTo( wid, idx ) )
- return false;
-
- QPopupMenu* pm = (QPopupMenu*)wid;
-
- removeLinks( pm, popupMode() );
- insertLinks( pm, popupMode(), idx );
-
- return true;
-}
-
-/*!
- Name: removeFrom [public]
- Desc: Removes all MRU links from specified popup.
-*/
-
-bool QtxMRUAction::removeFrom( QWidget* wid )
-{
- QtxAction::removeFrom( wid );
-
- QPopupMenu* pm = (QPopupMenu*)wid;
- if ( !wid || !wid->inherits( "QPopupMenu" ) )
- return false;
-
- if ( myItems.contains( pm ) )
- {
- removeLinks( pm, Items );
- myItems.remove( pm );
- disconnect( pm, SIGNAL( activated( int ) ), this, SLOT( onActivated( int ) ) );
- }
- if ( myMenus.contains( pm ) )
- {
- removeLinks( pm, SubMenu );
- delete myMenus[pm];
- myMenus.remove( pm );
- }
-
- disconnect( pm, SIGNAL( aboutToShow() ), this, SLOT( onAboutToShow() ) );
- disconnect( pm, SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
-
- return true;
-}
-
-/*!
- Name: loadLinks [public]
- Desc: Load the MRU links from specified resource manager section.
- If parameter 'clear' is 'true' then link list will be cleared first.
-*/
-
void QtxMRUAction::loadLinks( QtxResourceMgr* resMgr, const QString& section, const bool clear )
{
if ( !resMgr || section.isEmpty() )
myLinks.append( link );
map.insert( link, 0 );
}
-
- updateState();
}
/*!
- Name: saveLinks [public]
- Desc: Save the MRU links into specified resource manager section.
- If parameter 'clear' is 'true' then section will be cleared first.
+ \brief Save the MRU items to specified resources section.
+ \param resMgr resources manager
+ \param section resources section
+ \param clear if \c true, the resources section is first cleared
*/
-
void QtxMRUAction::saveLinks( QtxResourceMgr* resMgr, const QString& section, const bool clear ) const
{
if ( !resMgr || section.isEmpty() )
QStringList lst;
QMap<QString, int> map;
for ( QStringList::const_iterator itr = myLinks.begin(); itr != myLinks.end(); ++itr )
- map.insert( *lst.append( *itr ), 0 );
+ {
+ lst.append( *itr );
+ map.insert( *itr, 0 );
+ }
QString itemPrefix( "item_" );
QStringList items = resMgr->parameters( section );
QString link = resMgr->stringValue( section, *it, QString::null );
if ( !link.isEmpty() && !map.contains( link ) )
- map.insert( *lst.append( link ), 0 );
+ {
+ lst.append( link );
+ map.insert( link, 0 );
+ }
resMgr->remove( section, *it );
}
}
/*!
- Name: setEnabled [public slot]
- Desc: Enable or disable all popup items with MRU links.
-*/
-
-void QtxMRUAction::setEnabled( bool on )
-{
- QtxAction::setEnabled( on );
-
- for ( ItemsMap::ConstIterator iter = myItems.begin(); iter != myItems.end(); ++iter )
- for ( QIntList::const_iterator it = iter.data().idList.begin(); it != iter.data().idList.end(); ++it )
- iter.key()->setItemEnabled( *it, on );
-}
-
-/*!
- Name: onAboutToShow [private slots]
- Desc: Enable or disable sub menu item according to number of MRU links
- in sub popup when parent popup is shown.
+ \brief Prepare MRU items popup menu.
+
+ This method is called when the parent menu is shown.
+ Enables or disables sub menu item according to the number of MRU items.
*/
-
void QtxMRUAction::onAboutToShow()
{
- const QObject* obj = sender();
- if ( obj && obj->inherits( "QPopupMenu" ) )
- {
- QPopupMenu* pm = (QPopupMenu*)obj;
- if ( myMenus.contains( pm ) )
- pm->setItemEnabled( findId( pm, myMenus[pm]), isEnabled() && myMenus[pm] && myMenus[pm]->count() );
- }
+ updateMenu();
}
/*!
- Name: onActivated [private slot]
- Desc: Process popup item activation and emit signal activated with selected MRU link.
-*/
+ \brief Called when any MRU item is selected by the user.
-void QtxMRUAction::onActivated( int id )
-{
- const QObject* obj = sender();
- if ( !obj->inherits( "QPopupMenu" ) )
- return;
-
- QPopupMenu* pm = (QPopupMenu*)obj;
-
- QString link;
- if ( ( myItems.contains( pm ) && myItems[pm].idList.contains( id ) ) ||
- ( myMenus.contains( (QPopupMenu*)pm->parent() ) && myMenus[(QPopupMenu*)pm->parent()] == pm ) )
- link = pm->text( id );
-
- if ( !link.isEmpty() )
- emit activated( link );
-}
-
-/*!
- Name: onDestroyed [private slot]
- Desc: Removes deleted popup menu from internal data structures.
+ Emits signal activated(const QString&) passing selected MRU item as parameter.
*/
-
-void QtxMRUAction::onDestroyed( QObject* obj )
+void QtxMRUAction::onActivated()
{
- if ( !obj )
+ QAction* a = ::qobject_cast<QAction*>( sender() );
+ if ( !a )
return;
- myItems.remove( (QPopupMenu*)obj );
- myMenus.remove( (QPopupMenu*)obj );
-}
-
-/*!
- Name: updateState [private]
- Desc: Updates the state of all popup menus which contains MRU link items.
-*/
-
-void QtxMRUAction::updateState()
-{
- for ( ItemsMap::ConstIterator iIt = myItems.begin(); iIt != myItems.end(); ++iIt )
- updatePopup( iIt.key(), Items );
-
- for ( MenusMap::ConstIterator mIt = myMenus.begin(); mIt != myMenus.end(); ++mIt )
- updatePopup( mIt.key(), SubMenu );
-}
-
-/*!
- Name: checkPopup [private]
- Desc: Check consistency the popup content and internal datas.
- Synchronize internal data structures with popup content.
-*/
-
-void QtxMRUAction::checkPopup( QPopupMenu* pm )
-{
- if ( myItems.contains( pm ) )
- {
- bool found = true;
- for ( QIntList::const_iterator it = myItems[pm].idList.begin(); it != myItems[pm].idList.end() && found; ++it )
- found = pm->indexOf( *it ) != -1;
- if ( !found )
- {
- removeLinks( pm, Items );
- myItems.remove( pm );
- disconnect( pm, SIGNAL( activated( int ) ), this, SLOT( onActivated( int ) ) );
- }
- }
- if ( myMenus.contains( pm ) )
- {
- int id = findId( pm, myMenus[pm] );
- if ( id == -1 )
- {
- delete myMenus[pm];
- myMenus.remove( pm );
- }
- }
-
- if ( !myItems.contains( pm ) && !myMenus.contains( pm ) )
- disconnect( pm, SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
+ QString link = a->text();
+ if ( !link.isEmpty() && myLinks.contains( link ) )
+ emit activated( link );
}
/*!
- Name: updatePopup [private]
- Desc: Updates the MRU link items state in the specified popup menu.
+ \brief Update MRU items popup menu.
*/
-
-void QtxMRUAction::updatePopup( QPopupMenu* pm, const int mode )
+void QtxMRUAction::updateMenu()
{
+ QMenu* pm = menu();
if ( !pm )
return;
- int idx = -1;
- if ( mode == Items && myItems.contains( pm ) )
- {
- if ( !myItems[pm].idList.isEmpty() )
- idx = pm->indexOf( myItems[pm].idList.first() );
- else
- {
- int pIdx = pm->indexOf( myItems[pm].pId );
- int nIdx = pm->indexOf( myItems[pm].nId );
- if ( pIdx != -1 )
- idx = pIdx + 1;
- else if ( nIdx != -1 )
- idx = nIdx - 1;
- }
- }
-
- removeLinks( pm, mode );
- insertLinks( pm, mode, idx );
-}
-
-/*!
- Name: removeLinks [private]
- Desc: Removes MRU link items from specified popup.
-*/
-
-bool QtxMRUAction::removeLinks( QPopupMenu* pm, const int mode )
-{
- if ( !pm )
- return false;
-
- if ( mode == SubMenu && myMenus.contains( pm ) )
- myMenus[pm]->clear();
- else if ( mode == Items && myItems.contains( pm ) )
- {
- for ( QIntList::const_iterator it = myItems[pm].idList.begin(); it != myItems[pm].idList.end(); ++it )
- pm->removeItem( *it );
- myItems[pm].idList.clear();
- }
-
- return true;
-}
-
-/*!
- Name: insertLinks [private]
- Desc: Inserts MRU link items to the specified popup.
-*/
-
-bool QtxMRUAction::insertLinks( QPopupMenu* pm, const int mode, const int idx )
-{
- if ( !pm )
- return false;
+ pm->clear();
int count = visibleCount() < 0 ? myLinks.count() : visibleCount();
- bool isOn = isEnabled();
- if ( mode == SubMenu && myMenus.contains( pm ) )
- {
- for ( QStringList::const_iterator it = myLinks.begin(); it != myLinks.end() && count > 0; ++it, count-- )
- {
- int id = myMenus[pm]->insertItem( *it, -1 );
- myMenus[pm]->setItemEnabled( id, isOn );
- }
- }
- else if ( mode == Items )
- {
- QIntList ids;
- int index = idx;
- for ( QStringList::const_iterator it = myLinks.begin(); it != myLinks.end() && count > 0; ++it, count-- )
- {
- ids.append( pm->insertItem( *it, -1, index ) );
- pm->setItemEnabled( ids.last(), isOn );
- if ( index >= 0 )
- index++;
- }
- myItems[pm].idList = ids;
- if ( !myItems[pm].idList.isEmpty() )
- {
- myItems[pm].pId = pm->idAt( pm->indexOf( myItems[pm].idList.first() ) - 1 );
- myItems[pm].nId = pm->idAt( pm->indexOf( myItems[pm].idList.first() ) + 1 );
- }
- }
- return true;
+ for ( QStringList::const_iterator it = myLinks.begin(); it != myLinks.end() && count > 0; ++it, count-- )
+ pm->addAction( *it, this, SLOT( onActivated() ) );
}
/*!
- Name: findId [private]
- Desc: Returns identificator of popup item which contains sub popup 'pm' in the popup 'cont'.
+ \fn void QtxMRUAction::activated( const QString& link );
+ \brief Emitted when user selects any MRU item in the menu.
+ \param link selected MRU item
*/
-
-int QtxMRUAction::findId( QPopupMenu* cont, QPopupMenu* pm ) const
-{
- if ( !cont || !pm )
- return -1;
-
- int id = -1;
-
- for ( int i = 0; i < (int)cont->count() && id == -1; i++ )
- {
- QMenuData* md = 0;
- QMenuItem* item = cont->findItem( cont->idAt( i ), &md );
- if ( item && md == cont && item->popup() == pm )
- id = item->id();
- }
- return id;
-}
// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
+//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
+// License as published by the Free Software Foundation; either
// version 2.1 of the License.
-//
-// This library 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
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#include "QtxAction.h"
-#include <qmap.h>
-#include <qstringlist.h>
+#include <QStringList>
-class QPopupMenu;
class QtxResourceMgr;
#ifdef WIN32
{
Q_OBJECT
- Q_PROPERTY( int visibleCount READ visibleCount WRITE setVisibleCount )
-
public:
- enum { Items, SubMenu };
- enum { MoveFirst, MoveLast, AddFirst, AddLast };
+ //! Items insertion policy
+ typedef enum { MoveFirst, //!< put the specified item to the beginning
+ MoveLast, //!< put the specified item to the end
+ AddFirst, //!< if specified item doesn't exist, add it to the beginning
+ AddLast //!< if specified item doesn't exist, add it to the end
+ } InsertionMode;
public:
- QtxMRUAction( QObject* = 0, const char* = 0 );
- QtxMRUAction( const QString&, const QString&, QObject*, const char* = 0 );
- QtxMRUAction( const QString&, const QIconSet&, const QString&, QObject*, const char* = 0 );
+ QtxMRUAction( QObject* = 0 );
+ QtxMRUAction( const QString&, const QString&, QObject* = 0 );
+ QtxMRUAction( const QString&, const QIcon&, const QString&, QObject* = 0 );
virtual ~QtxMRUAction();
int insertMode() const;
void setInsertMode( const int );
- int popupMode() const;
- void setPopupMode( const int );
-
int count() const;
bool isEmpty() const;
int find( const QString& ) const;
bool contains( const QString& ) const;
- virtual bool addTo( QWidget* );
- virtual bool addTo( QWidget*, const int );
-
- virtual bool removeFrom( QWidget* );
-
virtual void loadLinks( QtxResourceMgr*, const QString&, const bool = true );
virtual void saveLinks( QtxResourceMgr*, const QString&, const bool = true ) const;
signals:
- void activated( QString );
-
-public slots:
- virtual void setEnabled( bool );
+ void activated( const QString& );
private slots:
+ void onActivated();
void onAboutToShow();
- void onActivated( int );
- void onDestroyed( QObject* );
-
-private:
- void updateState();
- void checkPopup( QPopupMenu* );
- void updatePopup( QPopupMenu*, const int );
- bool removeLinks( QPopupMenu*, const int );
- bool insertLinks( QPopupMenu*, const int, const int = -1 );
-
- int findId( QPopupMenu*, QPopupMenu* ) const;
private:
- typedef struct { int pId, nId; QIntList idList; } Item;
- typedef QMap<QPopupMenu*, Item> ItemsMap;
- typedef QMap<QPopupMenu*, QPopupMenu*> MenusMap;
+ void updateMenu();
private:
- QStringList myLinks;
- ItemsMap myItems;
- MenusMap myMenus;
- int myVisCount;
- int myPopupMode;
- int myInsertMode;
+ QStringList myLinks; //!< most recent used items
+ int myVisCount; //!< number of visible MRU items
+ int myInsertMode; //!< items insertion policy
};
#endif
#include "QtxToolBar.h"
#include "QtxResourceMgr.h"
-#include <qlayout.h>
-#include <qmenubar.h>
-#include <qstatusbar.h>
-#include <qapplication.h>
+#include <QEvent>
+#include <QMenuBar>
+#include <QStatusBar>
+#include <QApplication>
+#include <QDesktopWidget>
/*!
- Class: QtxMainWindow::Filter [Internal]
- Descr: Internal object with event filter for QtxMainWindow.
+ \class QtxMainWindow::Filter
+ \internal
+ \brief Internal object used to filter child removal events for
+ specified widget from parent widget.
*/
class QtxMainWindow::Filter : public QObject
virtual bool eventFilter( QObject*, QEvent* );
private:
- QMainWindow* myMain;
- QWidget* myWidget;
+ QMainWindow* myMain; //!< parent main window
+ QWidget* myWidget; //!< widget being watched
};
/*!
- Constructor
+ \brief Constructor.
+ \param wid widget to be watched
+ \param mw parent main window
+ \param parent parent object (in terms of QObject)
*/
QtxMainWindow::Filter::Filter( QWidget* wid, QtxMainWindow* mw, QObject* parent )
: QObject( parent ),
-myMain( mw ),
-myWidget( wid )
+ myMain( mw ),
+ myWidget( wid )
{
- myMain->installEventFilter( this );
+ QApplication::instance()->installEventFilter( this );
};
/*!
- Destructor
+ \brief Destructor.
*/
QtxMainWindow::Filter::~Filter()
{
}
/*!
- Custom event filter
+ \brief Event filter.
+
+ Watches for the specified widget and prevents its removal from the
+ parent main window.
+
+ \param o recevier object
+ \param e event
*/
bool QtxMainWindow::Filter::eventFilter( QObject* o, QEvent* e )
{
return QObject::eventFilter( o, e );
}
+
+/*!
+ \class QtxMainWindow
+ \brief Enhanced main window which supports dockable menubar and status bar
+ plus geometry saving/restoring.
+*/
+
/*!
- Class: QtxMainWindow [Public]
- Descr: Main window with support of dockable menubar/status bar
- and geometry store/retrieve.
+ \brief Constructor.
+ \param parent parent widget
+ \param f widget flags (Qt::WindowFlags)
*/
-QtxMainWindow::QtxMainWindow( QWidget* parent, const char* name, WFlags f )
-: QMainWindow( parent, name, f ),
-myMode( -1 ),
-myMenuBar( NULL ),
-myStatusBar( NULL )
+QtxMainWindow::QtxMainWindow( QWidget* parent, Qt::WindowFlags f )
+: QMainWindow( parent, f ),
+ myMenuBar( 0 ),
+ myStatusBar( 0 )
{
}
/*!
- Destructor
+ \brief Destructor.
*/
QtxMainWindow::~QtxMainWindow()
{
}
/*!
- \return true if menu bar exists
+ \brief Check if the menu bar is dockable.
+ \return \c true if dockable menu bar exists
*/
bool QtxMainWindow::isDockableMenuBar() const
{
- return myMenuBar;
+ return myMenuBar != 0;
}
/*!
- Creates or deletes menu bar
- \param on - if it is true, then to create, otherwise - to delete
+ \brief Set menu bar dockable/undockable.
+ \param on if \c true, make menu bar dockable, otherwise
+ make menu bar undockable
*/
void QtxMainWindow::setDockableMenuBar( const bool on )
{
if ( on && !myMenuBar )
{
- mb->setCaption( tr( "Menu bar" ) );
- QtxToolBar* dockMb = new QtxToolBar( true, this, "menu bar container" );
- myMenuBar = dockMb;
+ myMenuBar = new QtxToolBar( true, this );
new Filter( mb, this, myMenuBar );
- dockMb->setWidget( mb );
- dockMb->setNewLine( true );
- dockMb->setStretchable( true );
- dockMb->setResizeEnabled( false );
+ myMenuBar->setObjectName( "menu_bar_container" );
+ myMenuBar->setWindowTitle( tr( "Menu bar" ) );
+ myMenuBar->addWidget( mb );
+ myMenuBar->setAllowedAreas( Qt::TopToolBarArea | Qt::BottomToolBarArea );
- moveDockWindow( dockMb, DockTop );
- setDockEnabled( dockMb, Left, false );
- setDockEnabled( dockMb, Right, false );
+ addToolBarBreak( Qt::TopToolBarArea );
+ addToolBar( Qt::TopToolBarArea, myMenuBar );
+ addToolBarBreak( Qt::TopToolBarArea );
- setAppropriate( dockMb, false );
-
- connect( dockMb, SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
+ connect( myMenuBar, SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
}
else if ( !on && myMenuBar )
{
- mb->reparent( this, QPoint( 0, 0 ), mb->isVisibleTo( mb->parentWidget() ) );
+ setMenuBar( mb );
disconnect( myMenuBar, SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
delete myMenuBar;
myMenuBar = 0;
- QChildEvent ce( QEvent::ChildRemoved, mb );
- QApplication::sendEvent( this, &ce );
}
-
- setUpLayout();
}
/*!
- \return true if status bar exists
+ \brief Check if the status bar is dockable.
+ \return \c true if dockable status bar exists
*/
bool QtxMainWindow::isDockableStatusBar() const
{
}
/*!
- Creates or deletes status bar
- \param on - if it is true, then to create, otherwise - to delete
+ \brief Set status bar dockable/undockable.
+ \param on if \c true, make status bar dockable, otherwise
+ make status bar undockable
*/
void QtxMainWindow::setDockableStatusBar( const bool on )
{
if ( on && !myStatusBar )
{
- sb->setCaption( tr( "Status bar" ) );
- QtxToolBar* dockSb = new QtxToolBar( true, this, "status bar container" );
- myStatusBar = dockSb;
- new Filter( sb, this, myStatusBar );
- dockSb->setWidget( sb );
- dockSb->setNewLine( true );
- dockSb->setStretchable( true );
- dockSb->setResizeEnabled( false );
sb->setMinimumWidth( 250 );
-
sb->setSizeGripEnabled( false );
+ myStatusBar = new QtxToolBar( true, this );
+ new Filter( sb, this, myStatusBar );
+ myStatusBar->setObjectName( "status_bar_container" );
+ myStatusBar->setWindowTitle( tr( "Status bar" ) );
+ myStatusBar->addWidget( sb );
+ myStatusBar->setAllowedAreas( Qt::TopToolBarArea | Qt::BottomToolBarArea );
- moveDockWindow( dockSb, DockBottom );
- setDockEnabled( dockSb, Left, false );
- setDockEnabled( dockSb, Right, false );
-
- setAppropriate( dockSb, false );
+ addToolBar( Qt::BottomToolBarArea, myStatusBar );
- connect( dockSb, SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
+ connect( myStatusBar, SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
}
else if ( !on && myStatusBar )
{
- sb->reparent( this, QPoint( 0, 0 ), sb->isVisibleTo( sb->parentWidget() ) );
+ setStatusBar( sb );
disconnect( myStatusBar, SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
delete myStatusBar;
myStatusBar = 0;
- QChildEvent ce( QEvent::ChildRemoved, sb );
- QApplication::sendEvent( this, &ce );
sb->setSizeGripEnabled( true );
}
-
- setUpLayout();
}
/*!
- Retrieve the geometry information from the specified resource manager section.
- \param resMgr - instance of ersource manager
- \param section - section name
+ \brief Dump main window geometry to the string.
+ \return string represenation of the window geometry
*/
-void QtxMainWindow::loadGeometry( QtxResourceMgr* resMgr, const QString& section )
+QString QtxMainWindow::storeGeometry() const
{
- QString sec = section.stripWhiteSpace();
- if ( !resMgr || sec.isEmpty() )
- return;
-
- int winState = -1;
- if ( !resMgr->value( sec, "state", winState ) )
- {
- QString stateStr;
- if ( resMgr->value( sec, "state", stateStr ) )
- winState = windowState( stateStr );
- }
-
- int win_w = resMgr->integerValue( sec, "width", width() );
- int win_h = resMgr->integerValue( sec, "height", height() );
-
- int winPosX = windowPosition( resMgr->stringValue( sec, QString( "pos_x" ), QString::null ) );
- int winPosY = windowPosition( resMgr->stringValue( sec, QString( "pos_y" ), QString::null ) );
-
- QWidget* desk = QApplication::desktop();
-
- int win_x = 0;
- if ( winPosX == WP_Absolute )
- win_x = resMgr->integerValue( sec, "pos_x", x() );
- else if ( desk )
- win_x = relativeCoordinate( winPosX, desk->width(), win_w );
-
- int win_y = 0;
- if ( winPosX == WP_Absolute )
- win_y = resMgr->integerValue( sec, "pos_y", y() );
- else if ( desk )
- win_y = relativeCoordinate( winPosY, desk->height(), win_h );
-
- bool vis = isVisibleTo( parentWidget() );
-
- resize( win_w, win_h );
- move( win_x, win_y );
-
- myMode = -1;
-
- if ( vis )
- QApplication::postEvent( this, new QCustomEvent( QEvent::User, (void*)winState ) );
+ QRect frame = frameGeometry();
+ QRect screen = QApplication::desktop()->availableGeometry( this );
+
+ QString x;
+ if ( frame.left() == screen.left() )
+ x = QString( "+0" );
+ else if ( frame.right() == screen.right() )
+ x = QString( "-0" );
else
- myMode = winState;
-}
-
-/*!
- Shows main window
-*/
-void QtxMainWindow::show()
-{
- if ( myMode != -1 )
- QApplication::postEvent( this, new QCustomEvent( QEvent::User, (void*)myMode ) );
+ x = QString( "+%1" ).arg( frame.left() );
- myMode = -1;
-
- QMainWindow::show();
-}
+ QString y;
+ if ( frame.top() == screen.top() )
+ y = QString( "+0" );
+ else if ( frame.bottom() == screen.bottom() )
+ y = QString( "-0" );
+ else
+ y = QString( "+%1" ).arg( frame.top() );
-/*!
- Handler of custom events
-*/
-void QtxMainWindow::customEvent( QCustomEvent* e )
-{
- QMainWindow::customEvent( e );
+ QString geom = QString( "%1x%2%3%4" ).arg( frame.width() ).arg( frame.height() ).arg( x ).arg( y );
- size_t mode = size_t(e->data());
- switch ( mode )
+ QString state;
+ switch ( windowState() )
{
- case WS_Normal:
- showNormal();
+ case Qt::WindowMaximized:
+ state = QString( "max" );
break;
- case WS_Minimized:
- showMinimized();
+ case Qt::WindowMinimized:
+ state = QString( "min" );
break;
- case WS_Maximized:
- showMaximized();
+ case Qt::WindowFullScreen:
+ state = QString( "full" );
break;
}
+
+ if ( !state.isEmpty() )
+ geom += QString( ":" ) + state;
+
+ return geom;
}
/*!
- \return relative co-ordinate by two points
- \param type - type of result: WP_Center (center), WP_Left (left), WP_Right (right)
- \param wh - left point
- \param WH - right point
+ \brief Restore main window geometry from the string.
+ \param str string represenation of the window geometry
*/
-int QtxMainWindow::relativeCoordinate( const int type, const int WH, const int wh ) const
+void QtxMainWindow::retrieveGeometry( const QString& str )
{
- int res = 0;
- switch ( type )
+ QString geom = str;
+ geom.remove( '\t' );
+ geom.remove( ' ' );
+
+ QRect rect = geometry();
+ QRect screen = QApplication::desktop()->availableGeometry( this );
+
+ QRegExp szRx( "(\\d+%?)\\s*x\\s*(\\d+%?)" );
+ if ( szRx.indexIn( geom ) != -1 )
{
- case WP_Center:
- res = ( WH - wh ) / 2;
- break;
- case WP_Left:
- res = 0;
- break;
- case WP_Right:
- res = WH - wh;
- break;
+ int w = -1;
+ bool wp = false;
+ int ws = geometryValue( szRx.cap( 1 ).trimmed(), w, wp );
+ bool wOk = ws != 0;
+ if ( wOk && wp )
+ w = screen.width() * qMax( qMin( w, 100 ), 0 ) / 100;
+ wOk = wOk && w;
+
+ int h = -1;
+ bool hp = false;
+ int hs = geometryValue( szRx.cap( 2 ).trimmed(), h, hp );
+ bool hOk = hs != 0;
+ if ( hOk && hp )
+ h = screen.height() * qMax( qMin( h, 100 ), 0 ) / 100;
+ hOk = hOk && h;
+
+ if ( wOk && hOk )
+ rect.setSize( QSize( w, h ) );
}
- return res;
-}
-/*!
- Store the geometry information into the specified resource manager section.
- \param resMgr - instance of ersource manager
- \param section - section name
-*/
-void QtxMainWindow::saveGeometry( QtxResourceMgr* resMgr, const QString& section ) const
-{
- QString sec = section.stripWhiteSpace();
- if ( !resMgr || sec.isEmpty() )
- return;
+ QRegExp posRx( "([+|-]\\d+%?)\\s*([+|-]\\d+%?)" );
+ if ( posRx.indexIn( geom ) != -1 )
+ {
+ int x = -1;
+ bool xp = false;
+ int xs = geometryValue( posRx.cap( 1 ).trimmed(), x, xp );
+ bool xOk = xs != 0;
+ if ( xOk )
+ {
+ if ( xp )
+ x = screen.width() * qMax( qMin( x, 100 ), 0 ) / 100;
+ x = ( xs > 0 ? x : screen.right() - x - rect.width() ) + frameGeometry().x() - geometry().x();
+ }
+
+ int y = -1;
+ bool yp = false;
+ int ys = geometryValue( posRx.cap( 2 ).trimmed(), y, yp );
+ bool yOk = ys != 0;
+ if ( yOk )
+ {
+ if ( yp )
+ y = screen.height() * qMax( qMin( y, 100 ), 0 ) / 100;
+ y = ( ys > 0 ? y : screen.bottom() - y - rect.height() ) + frameGeometry().y() - geometry().y();
+ }
+
+ if ( xOk && yOk )
+ rect.moveTo( x, y );
+ }
- resMgr->setValue( sec, "pos_x", pos().x() );
- resMgr->setValue( sec, "pos_y", pos().y() );
- resMgr->setValue( sec, "width", width() );
- resMgr->setValue( sec, "height", height() );
+ Qt::WindowState state = Qt::WindowNoState;
- int winState = WS_Normal;
- if ( isMinimized() )
- winState = WS_Minimized;
- else if ( isMaximized() )
- winState = WS_Maximized;
+ QRegExp stRx( ":(\\w+)" );
+ if ( stRx.indexIn( geom ) != -1 )
+ {
+ QString stStr = stRx.cap( 1 ).trimmed().toLower();
+ if ( stStr.startsWith( QString( "max" ) ) )
+ state = Qt::WindowMaximized;
+ else if ( stStr.startsWith( QString( "min" ) ) )
+ state = Qt::WindowMinimized;
+ else if ( stStr.startsWith( QString( "full" ) ) )
+ state = Qt::WindowFullScreen;
+ }
- resMgr->setValue( sec, "state", winState );
+ setGeometry( rect );
+ if ( state != Qt::WindowNoState )
+ setWindowState( state );
}
/*!
- Custom event filter
+ \brief Retrieve numerical value from the string.
+
+ Numerical value in the string have the structure [+|-]\d*[%],
+ that is one or more digits which can start from "+" or "-" and
+ can end with "%" symbol.
+
+ \param str string being converted
+ \param num returning value (> 0)
+ \param percent if string ends with "%" this parameter is equal to \c true after
+ returning from the function
+ \return -1 if value < 0, 1 if value > 0 and 0 in case of error
*/
-bool QtxMainWindow::eventFilter( QObject* o, QEvent* e )
+int QtxMainWindow::geometryValue( const QString& str, int& num, bool& percent ) const
{
- return QMainWindow::eventFilter( o, e );
-}
+ num = -1;
+ int res = 1;
+ QString numStr = str;
+ if ( numStr.startsWith( "+" ) || numStr.startsWith( "-" ) )
+ {
+ res = numStr.startsWith( "+" ) ? 1 : -1;
+ numStr = numStr.mid( 1 );
+ }
-/*!
- Controls whether or not the dw dock window's caption should appear
- as a menu item on the dock window menu that lists the dock windows.
- \param dw - window
- \param a - if it is true, then it appears in menu
-*/
-void QtxMainWindow::setAppropriate( QDockWindow* dw, bool a )
-{
- QMainWindow::setAppropriate( dw, myStatusBar != dw && myMenuBar != dw && a );
-}
+ percent = numStr.endsWith( "%" );
+ if ( percent )
+ numStr = numStr.mid( 0, numStr.length() - 1 );
-/*!
- Sets up layout
-*/
-void QtxMainWindow::setUpLayout()
-{
- QMainWindow::setUpLayout();
+ bool ok = false;
+ num = numStr.toInt( &ok );
+ if ( !ok )
+ res = 0;
- if ( myMenuBar && layout() )
- layout()->setMenuBar( 0 );
+ return res;
}
/*!
- SLOT: called on object destroyed, clears internal fields in case of deletion of menu bar or status bar
+ \brief Called when child object (menu bar, status bar) is destroyed.
+
+ Clears internal pointer to prevent crashes.
+
+ \param obj signal sender (object being destroyed)
*/
void QtxMainWindow::onDestroyed( QObject* obj )
{
}
}
-/*!
- \return flag of window state by it's name
- \param str - name of flag
-*/
-int QtxMainWindow::windowState( const QString& str ) const
-{
- static QMap<QString, int> winStateMap;
- if ( winStateMap.isEmpty() )
- {
- winStateMap["normal"] = WS_Normal;
- winStateMap["min"] = WS_Minimized;
- winStateMap["mini"] = WS_Minimized;
- winStateMap["minimized"] = WS_Minimized;
- winStateMap["max"] = WS_Maximized;
- winStateMap["maxi"] = WS_Maximized;
- winStateMap["maximized"] = WS_Maximized;
- winStateMap["hidden"] = WS_Hidden;
- winStateMap["hided"] = WS_Hidden;
- winStateMap["hide"] = WS_Hidden;
- winStateMap["invisible"] = WS_Hidden;
- }
-
- int res = -1;
- QString stateStr = str.stripWhiteSpace().lower();
- if ( winStateMap.contains( stateStr ) )
- res = winStateMap[stateStr];
- return res;
-}
-
-/*!
- \return flag of position by it's name
- \param str - name of position
-*/
-int QtxMainWindow::windowPosition( const QString& str ) const
-{
- static QMap<QString, int> winPosMap;
- if ( winPosMap.isEmpty() )
- {
- winPosMap["center"] = WP_Center;
- winPosMap["left"] = WP_Left;
- winPosMap["right"] = WP_Right;
- winPosMap["top"] = WP_Top;
- winPosMap["bottom"] = WP_Bottom;
- }
-
- int res = WP_Absolute;
- QString posStr = str.stripWhiteSpace().lower();
- if ( winPosMap.contains( posStr ) )
- res = winPosMap[posStr];
- return res;
-}
#include "Qtx.h"
-#include <qmainwindow.h>
+#include <QMainWindow>
-class QDockWindow;
class QtxResourceMgr;
class QTX_EXPORT QtxMainWindow : public QMainWindow
class Filter;
- enum { WS_Normal, WS_Minimized, WS_Maximized, WS_Hidden };
- enum { WP_Absolute, WP_Center, WP_Left, WP_Right, WP_Top = WP_Left, WP_Bottom = WP_Right };
-
public:
- QtxMainWindow( QWidget* = 0, const char* = 0, WFlags = WType_TopLevel );
+ QtxMainWindow( QWidget* = 0, Qt::WindowFlags = 0 );
virtual ~QtxMainWindow();
bool isDockableMenuBar() const;
bool isDockableStatusBar() const;
void setDockableStatusBar( const bool );
- void loadGeometry( QtxResourceMgr*, const QString& );
- void saveGeometry( QtxResourceMgr*, const QString& ) const;
-
- virtual bool eventFilter( QObject*, QEvent* );
-
-public slots:
- virtual void show();
- virtual void setAppropriate( QDockWindow*, bool );
-
-protected:
- virtual void setUpLayout();
- virtual void customEvent( QCustomEvent* );
+ QString storeGeometry() const;
+ void retrieveGeometry( const QString& );
private slots:
void onDestroyed( QObject* );
private:
- int windowState( const QString& ) const;
- int windowPosition( const QString& ) const;
- int relativeCoordinate( const int, const int, const int ) const;
+ int geometryValue( const QString&, int&, bool& ) const;
private:
- int myMode;
- QDockWindow* myMenuBar;
- QDockWindow* myStatusBar;
+ QToolBar* myMenuBar; //!< dockable menu bar
+ QToolBar* myStatusBar; //!< dockable status bar
};
-#endif
+#endif // QTXMAINWINDOW_H
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File: QtxMap.h
+// Author: Vadim SANDLER
+
+#ifndef QTX_MAP_H
+#define QTX_MAP_H
+
+template <class Key, class Value> class IMap;
+template <class Key, class Value> class IMapIterator;
+template <class Key, class Value> class IMapConstIterator;
+
+/*!
+ \brief Indexed map template class.
+*/
+template <class Key, class Value> class IMap
+{
+public:
+ typedef IMapIterator<Key,Value> Iterator;
+ typedef IMapConstIterator<Key,Value> ConstIterator;
+
+public:
+ IMap() {}
+ IMap( const IMap& m ) : myKeys( m.myKeys ), myData( m.myData ) {}
+ IMap& operator=( const IMap& m ) { myKeys = m.myKeys; myData = m.myData; return *this; }
+
+ int count() const { return myData.count(); }
+ int size() const { return myData.count(); }
+ bool empty() const { return myData.empty(); }
+ bool isEmpty() const { return myData.empty(); }
+
+ void clear() { myKeys.clear(); myData.clear(); }
+
+ QList<Key> keys() const { return myKeys; }
+ QList<Value> values() const { QList<Value> l; for ( int i = 0; i < count(); i++ ) l.append( value( i ) ); return l; }
+ bool contains ( const Key& key ) const { return myData.contains( key ); }
+
+ Iterator begin() { return Iterator( this ); }
+ Iterator end() { return Iterator( this, count() ); }
+ ConstIterator begin() const { return ConstIterator( this ); }
+ ConstIterator end() const { return ConstIterator( this, count() ); }
+
+ Iterator insert( const Key& key, const Value& value, bool overwrite = true )
+ {
+ if ( myData.find( key ) == myData.end() || overwrite )
+ {
+ if ( myData.find( key ) != myData.end() && overwrite )
+ myKeys.removeAt( myKeys.indexOf( key ) );
+ myKeys.append( key );
+ myData[key] = value;
+ }
+ return Iterator( this, index( key ) );
+ }
+
+ Iterator replace( const Key& key, const Value& value )
+ {
+ if ( myData.find( key ) == myData.end() )
+ myKeys.append( key );
+ myData[ key ] = value;
+ return Iterator( this, index( key ) );
+ }
+
+ int index( const Key& key ) const { return myKeys.indexOf( key ); }
+ Iterator at( const int index ) { return Iterator( this, index ); }
+ ConstIterator at( const int index ) const { return ConstIterator( this, index ); }
+
+ Key& key( const int index )
+ {
+ if ( index < 0 || index >= (int)myKeys.count() )
+ return dummyKey;
+ return myKeys[index];
+ }
+
+ Value value( const int index )
+ {
+ if ( index < 0 || index >= (int)myKeys.count() )
+ return dummyValue;
+ return myData[ myKeys[index] ];
+ }
+
+ Value operator[]( const Key& key )
+ {
+ if ( myData.find( key ) == myData.end() )
+ insert( key, Value() );
+ return myData[ key ];
+ }
+
+ const Value operator[]( const Key& key ) const
+ {
+ if ( myData.find( key ) == myData.end() )
+ return dummyValue;
+ return myData[key];
+ }
+
+ void erase( Iterator it ) { remove( it ); }
+ void erase( const Key& key ) { remove( key ); }
+ void erase( const int index ) { remove( index ); }
+ void remove( Iterator it ) { if ( it.myMap != this ) return; remove( it.myIndex ); }
+ void remove( const Key& key ) { remove( index( key ) ); }
+ void remove( const int index )
+ {
+ if ( index >= 0 && index < (int)myKeys.count() )
+ {
+ myData.remove( myKeys[index] );
+ myKeys.removeAt( index );
+ }
+ }
+
+private:
+ QList<Key> myKeys;
+ QMap<Key,Value> myData;
+ Key dummyKey;
+ Value dummyValue;
+
+ friend class IMapIterator<Key,Value>;
+ friend class IMapConstIterator<Key,Value>;
+};
+
+/*!
+ \brief Indexed map iterator template class.
+*/
+template <class Key, class Value> class IMapIterator
+{
+public:
+ IMapIterator() : myMap( 0 ), myIndex( 0 ) { init(); }
+ IMapIterator( const IMap<Key,Value>* m ) : myMap( const_cast< IMap<Key,Value>* >( m ) ), myIndex( 0 ) { init(); }
+ IMapIterator( const IMapIterator& i ) : myMap( i.myMap ), myIndex( i.myIndex ) { init(); }
+
+ bool operator==( const IMapIterator& i ) { return !operator!=( i ); }
+ bool operator!=( const IMapIterator& i ) { return !myMap || myMap != i.myMap || myIndex != i.myIndex; }
+
+ operator bool() const { return myIndex >= 0; }
+
+ const Key& key() const { return myMap->key( myIndex ); }
+ Value& value() { return myMap->value( myIndex ); }
+ const Value& value() const { return myMap->value( myIndex ); }
+
+ Value& operator*() { return value(); }
+
+ IMapIterator& operator++() { myIndex++; init(); return *this; }
+ IMapIterator operator++( int ) { IMapIterator i = *this; myIndex++; init(); return i; }
+ IMapIterator& operator--() { myIndex--; init(); return *this; }
+ IMapIterator operator--( int ) { IMapIterator i = *this; myIndex--; init(); return i; }
+
+private:
+ IMapIterator( const IMap<Key,Value>* m, const int index ) : myMap( const_cast< IMap<Key,Value>* >( m ) ), myIndex( index ) { init(); }
+ void init() { if ( !myMap || myIndex >= myMap->count() ) myIndex = -1; }
+
+private:
+ IMap<Key,Value>* myMap;
+ int myIndex;
+
+ friend class IMap<Key, Value>;
+ friend class IMapConstIterator<Key, Value>;
+};
+
+/*!
+ \brief Indexed map const iterator template class.
+*/
+template <class Key, class Value> class IMapConstIterator
+{
+public:
+ IMapConstIterator() : myMap( 0 ), myIndex( 0 ) { init(); }
+ IMapConstIterator( const IMap<Key,Value>* m ) : myMap( const_cast< IMap<Key,Value>* >( m ) ), myIndex( 0 ) { init(); }
+ IMapConstIterator( const IMapConstIterator& i ) : myMap( i.myMap ), myIndex( i.myIndex ) { init(); }
+ IMapConstIterator( const IMapIterator<Key, Value>& i ) : myMap( i.myMap ), myIndex( i.myIndex ) { init(); }
+
+ bool operator==( const IMapConstIterator& i ) { return !operator!=( i ); }
+ bool operator!=( const IMapConstIterator& i ) { return !myMap || myMap != i.myMap || myIndex != i.myIndex; }
+
+ operator bool() const { return myIndex >= 0; }
+
+ const Key& key() const { return myMap->key( myIndex ); }
+ const Value value() const { return myMap->value( myIndex ); }
+
+ const Value operator*() const { return value(); }
+
+ IMapConstIterator& operator++() { myIndex++; init(); return *this; }
+ IMapConstIterator operator++( int ) { IMapConstIterator i = *this; myIndex++; init(); return i; }
+ IMapConstIterator& operator--() { myIndex--; init(); return *this; }
+ IMapConstIterator operator--( int ) { IMapConstIterator i = *this; myIndex--; init(); return i; }
+
+private:
+ IMapConstIterator( const IMap<Key,Value>* m, const int index ): myMap( const_cast< IMap<Key,Value>* >( m ) ), myIndex( index ) { init(); }
+ void init() { if ( !myMap || myIndex >= myMap->count() ) myIndex = -1; }
+
+private:
+ IMap<Key,Value>* myMap;
+ int myIndex;
+
+ friend class IMap<Key,Value>;
+};
+
+#endif // QTX_MAP_H
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-// File: QtxMenuButton.cxx
-// Author: Sergey TELKOV
-
-#include "QtxMenuButton.h"
-
-#include <qstyle.h>
-#include <qpainter.h>
-#include <qpopupmenu.h>
-#include <qpointarray.h>
-#include <qapplication.h>
-
-class QtxMenuButton::PopupMenu : public QPopupMenu
-{
-public:
- PopupMenu( QtxMenuButton* mb ) : QPopupMenu( mb ), myMenuButton( mb ) {};
- virtual ~PopupMenu() {};
-
- virtual void setMinimumSize( int, int );
-
-private:
- QtxMenuButton* myMenuButton;
-};
-
-/*!
- Sets the widget's minimum size
- \param w - width
- \param h - height
-*/
-void QtxMenuButton::PopupMenu::setMinimumSize( int w, int h )
-{
- if ( myMenuButton->isAlignWidth() &&
- ( myMenuButton->position() == Top || myMenuButton->position() == Bottom ) )
- w = QMAX( w, myMenuButton->width() );
-
- QPopupMenu::setMinimumSize( w, h );
-}
-
-
-/*!
- Constructor
- \param pos - position
- \param parent - parent widget
- \param name - name
-*/
-QtxMenuButton::QtxMenuButton( int pos, QWidget* parent, const char* name )
-: QPushButton( parent, name ),
-myPos( pos )
-{
- initialize();
-}
-
-/*!
- Constructor
- \param text - button text
- \param parent - parent widget
- \param name - name
-*/
-QtxMenuButton::QtxMenuButton( const QString& text, QWidget* parent, const char* name )
-: QPushButton( parent, name ),
-myPos( Bottom )
-{
- setText( text );
- initialize();
-}
-
-/*!
- Constructor
- \param pos - position
- \param text - button text
- \param parent - parent widget
- \param name - name
-*/
-QtxMenuButton::QtxMenuButton( int pos, const QString& text, QWidget* parent, const char* name )
-: QPushButton( parent, name ),
-myPos( pos )
-{
- setText( text );
- initialize();
-}
-
-/*!
- Constructor
- \param parent - parent widget
- \param name - name
-*/
-QtxMenuButton::QtxMenuButton( QWidget* parent, const char* name )
-: QPushButton( parent, name ),
-myPos( Bottom )
-{
- initialize();
-}
-
-/*!
- Destructor
-*/
-QtxMenuButton::~QtxMenuButton()
-{
-}
-
-/*!
- Initialization
-*/
-void QtxMenuButton::initialize()
-{
- myArrow = true;
- myAlign = true;
-
- setAutoDefault( false );
- myPopup = new PopupMenu( this );
- myPopup->hide();
-
- connect( myPopup, SIGNAL( activated( int ) ), this, SIGNAL( activated( int ) ) );
- connect( this, SIGNAL( clicked() ), this, SLOT( onShowPopup() ) );
-}
-
-/*!
- \return position
-*/
-int QtxMenuButton::position() const
-{
- return myPos;
-}
-
-/*!
- \return true if align is enabled
-*/
-bool QtxMenuButton::isAlignWidth() const
-{
- return myAlign;
-}
-
-/*!
- \return true if arrow is shown
-*/
-bool QtxMenuButton::isArrowEnabled() const
-{
- return myArrow;
-}
-
-/*!
- Changes position
- \param pos - new position
-*/
-void QtxMenuButton::setPosition( const int pos )
-{
- if ( myPos == pos )
- return;
-
- myPos = pos;
- if ( myPopup->isVisible() )
- onShowPopup();
-}
-
-/*!
- Changes align state
- \param on - new align state
-*/
-void QtxMenuButton::setAlignWidth( const bool on )
-{
- if ( myAlign == on )
- return;
-
- myAlign = on;
- updateGeometry();
-}
-
-/*!
- Enables/disable arrow
- \param on - new enabled state
-*/
-void QtxMenuButton::setArrowEnabled( const bool on )
-{
- if ( myArrow == on )
- return;
-
- myArrow = on;
- repaint();
-}
-
-/*!
- Clears popup
-*/
-void QtxMenuButton::clear()
-{
- if ( myPopup )
- myPopup->clear();
- onShowPopup();
- updateGeometry();
-}
-
-/*!
- Removes item from popup
- \param id - item id
-*/
-void QtxMenuButton::removeItem( int id )
-{
- if ( myPopup )
- myPopup->removeItem( id );
- updateGeometry();
-}
-
-/*!
- Inserts separator into popup
- \param id - position
-*/
-int QtxMenuButton::insertSeparator( int id )
-{
- int res = -1;
- if ( myPopup )
- res = myPopup->insertSeparator( id );
- return res;
-}
-
-/*!
- Inserts item into popup
- \param t - menu text
- \param id - item id
- \param index - position
-*/
-int QtxMenuButton::insertItem( const QString& t, int id, int index )
-{
- int resId = -1;
- if ( myPopup )
- resId = myPopup->insertItem( t, id, index );
-
- if ( resId != -1 )
- updateGeometry();
-
- return resId;
-}
-
-/*!
- Inserts item into popup
- \param is - icons
- \param t - menu text
- \param id - item id
- \param index - position
-*/
-int QtxMenuButton::insertItem( const QIconSet& is, const QString& t, int id, int index )
-{
- int resId = -1;
- if ( myPopup )
- resId = myPopup->insertItem( is, t, id, index );
-
- if ( resId != -1 )
- updateGeometry();
-
- return resId;
-}
-
-/*!
- SLOT: calls when button is clicked, shows popup
-*/
-void QtxMenuButton::onShowPopup()
-{
- if ( !myPopup || !myPopup->count() )
- {
- myPopup->hide();
- return;
- }
-
- QPoint p = mapToGlobal( QPoint( 0, 0 ) );
- int x = p.x();
- int y = p.y() + 1;
- int margin = 0;
- int xoffset = 0;
- int yoffset = 0;
- switch ( position() )
- {
- case Left:
- xoffset = -1 * ( myPopup->sizeHint().width() + margin );
- break;
- case Right:
- xoffset = width() + margin;
- break;
- case Top:
- yoffset = -1 * ( myPopup->sizeHint().height() + margin );
- break;
- case Bottom:
- default:
- yoffset = height() + margin;
- break;
- }
- int dw = QApplication::desktop()->width();
- int dh = QApplication::desktop()->height();
- x = QMIN( QMAX( x + xoffset, 0 ), dw );
- y = QMIN( QMAX( y + yoffset, 0 ), dh );
-
- myPopup->exec( QPoint( x, y ) );
-}
-
-/*!
- Custom event handler
-*/
-bool QtxMenuButton::event( QEvent* e )
-{
- if ( e->type() == QEvent::MouseButtonPress ||
- e->type() == QEvent::MouseButtonDblClick ||
- e->type() == QEvent::MouseButtonRelease )
- {
- onShowPopup();
- return false;
- }
-
- return QPushButton::event( e );
-}
-
-/*!
- \return the recommended size for the widget
-*/
-QSize QtxMenuButton::sizeHint() const
-{
- QSize sz = QPushButton::sizeHint();
- if ( ( position() == Top || position() == Bottom ) && myPopup && myAlign )
- sz = QSize( QMAX( sz.width(), myPopup->sizeHint().width() ), sz.height() );
-
- return sz;
-}
-
-/*!
- \return the recommended minimum size for the widget
-*/
-QSize QtxMenuButton::minimumSizeHint() const
-{
- QSize sz = QPushButton::minimumSizeHint();
- if ( ( position() == Top || position() == Bottom ) && myPopup && myAlign )
- sz = QSize( QMAX( sz.width(), myPopup->sizeHint().width() ), sz.height() );
-
- return sz;
-}
-
-/*!
- Custom resize event handler
-*/
-void QtxMenuButton::resizeEvent( QResizeEvent* re )
-{
- if ( re )
- QPushButton::resizeEvent( re );
-
- if ( ( position() == Top || position() == Bottom ) && myPopup && myAlign )
- myPopup->setMinimumWidth( re ? re->size().width() : width() );
-}
-
-/*!
- \return corresponding popup
-*/
-QPopupMenu* QtxMenuButton::popup() const
-{
- return myPopup;
-}
-
-/*!
- Draws label
-*/
-void QtxMenuButton::drawButtonLabel( QPainter* p )
-{
- QPushButton::drawButtonLabel( p );
-/*
- QStyle::SFlags flags = QStyle::Style_Default;
- if ( isEnabled() )
- flags |= QStyle::Style_Enabled;
- if ( hasFocus() )
- flags |= QStyle::Style_HasFocus;
-*/
-#if QT_VER < 3
- QRect r = rect();
-#else
- QRect r = style().subRect( QStyle::SR_PushButtonContents, this );
-#endif
-
- if ( myArrow && myPopup && myPopup->count() )
- {
- int w = 7;
- int h = 7;
- int margin = 5;
-
- QRect ar( 0, 0, w, h );
- if ( position() == Left || position() == Top )
- r.moveBy( ar.width() + 2 * margin, 0 );
- else
- ar.moveBy( r.width() - ar.width() - 2 * margin, 0 );
-
- r.setWidth( r.width() - ar.width() - 2 * margin );
-
- ar.moveBy( margin, ( height() - h ) / 2 );
-
- QPointArray arrow( 3 );
- switch ( position() )
- {
- case Left:
- arrow.putPoints( 0, 3, ar.left(), ar.top() + ar.height() / 2, ar.right(), ar.top(), ar.right(), ar.bottom() );
- break;
- case Right:
- arrow.putPoints( 0, 3, ar.left(), ar.top(), ar.left(), ar.bottom(), ar.right(), ar.top() + ar.height() / 2 );
- break;
- case Top:
- arrow.putPoints( 0, 3, ar.left(), ar.bottom(), ar.right(), ar.bottom(), ar.left() + ar.width() / 2, ar.top() );
- break;
- case Bottom:
- default:
- arrow.putPoints( 0, 3, ar.left(), ar.top(), ar.right(), ar.top(), ar.left() + ar.width() / 2, ar.bottom() );
- break;
- }
-
- p->setPen( colorGroup().text() );
- p->setBrush( colorGroup().text() );
- p->drawPolygon( arrow, true );
- }
-
-// style().drawControl( QStyle::CE_PushButtonLabel, p, this, r, colorGroup(), flags );
-}
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-// File: QtxMenuButton.h
-// Author: Sergey TELKOV
-
-#ifndef QTXMENUBUTTON_H
-#define QTXMENUBUTTON_H
-
-#include "Qtx.h"
-
-#include <qpushbutton.h>
-
-class QIconSet;
-class QPopupMenu;
-
-class QTX_EXPORT QtxMenuButton : public QPushButton
-{
- Q_OBJECT
-
- class PopupMenu;
-
-public:
- enum { Left, Right, Top, Bottom };
-
-public:
- QtxMenuButton( int, QWidget* = 0, const char* = 0 );
- QtxMenuButton( const QString&, QWidget* = 0, const char* = 0 );
- QtxMenuButton( int, const QString&, QWidget* = 0, const char* = 0 );
- QtxMenuButton( QWidget* = 0, const char* = 0 );
- virtual ~QtxMenuButton();
-
- int position() const;
- void setPosition( const int );
-
- bool isAlignWidth() const;
- void setAlignWidth( const bool );
-
- bool isArrowEnabled() const;
- void setArrowEnabled( const bool );
-
- void clear();
- void removeItem( int );
- int insertSeparator( int = -1 );
- int insertItem( const QString&, int = -1, int = -1 );
- int insertItem( const QIconSet&, const QString&, int = -1, int = -1 );
-
- virtual QSize sizeHint() const;
- virtual QSize minimumSizeHint() const;
-
-signals:
- void activated( int );
-
-private slots:
- void onShowPopup();
-
-protected:
- QPopupMenu* popup() const;
- virtual bool event( QEvent* );
- virtual void resizeEvent( QResizeEvent* );
- virtual void drawButtonLabel( QPainter* );
-
-private:
- void initialize();
-
-private:
- int myPos;
- bool myArrow;
- bool myAlign;
- QPopupMenu* myPopup;
-};
-
-#endif
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-
-#include "QtxOperations.h"
-
-/*!
- Default constructor
-*/
-QtxOperations::QtxOperations()
-{
-}
-
-/*!
- Destructor
-*/
-QtxOperations::~QtxOperations()
-{
-}
-
-/*!
- Creates QtxValue by it's string representation
-*/
-bool QtxOperations::createValue( const QString& str, QtxValue& v ) const
-{
- v = str;
- return false;
-}
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-// File: QtxOperations.h
-// Author: Alexander SOLOVYOV
-
-#ifndef __QTX_OPERATIONS_HEADER__
-#define __QTX_OPERATIONS_HEADER__
-
-#include "Qtx.h"
-#include "QtxParser.h"
-
-class QTX_EXPORT QtxOperations
-{
-public:
- QtxOperations();
- virtual ~QtxOperations();
-
- virtual void opersList( QStringList& ) const = 0;
- //list of possible operations
-
- virtual void bracketsList( QStringList&, bool open ) const = 0;
- //list of open/close brackets
-
- virtual bool createValue( const QString&, QtxValue& ) const;
- //by default, the String value will be set, it corresponds to parameter
- //base method returns false (always parameter)
- //successor's method returns true if it has created custom value
- //or call base if it hasn't
-
- virtual int prior( const QString&, bool isBin ) const = 0;
- //returns prioritet of operation;
- //if operation is impossible, it must return 0 or less
-
- virtual QtxParser::Error isValid( const QString&,
- const QVariant::Type,
- const QVariant::Type ) const = 0;
- //return OK if this parameter types is valid for operation
- //return OperandsNotMatch or InvalidOperation otherwise
-
- virtual QtxParser::Error calculate( const QString&, QtxValue&, QtxValue& ) const = 0;
- //process binary operation with values
- //for unary operation the second QtxValue will be passed as invalid
-};
-
-#endif
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-
-#include "QtxParser.h"
-#include "QtxOperations.h"
-
-/*!
- Constructor
-*/
-QtxParser::QtxParser( QtxOperations* operations, const QString& expr )
-: myOperations( operations )
-{
- if( myOperations )
- {
- setLastError( OK );
- setExpr( expr );
- }
- else
- setLastError( OperationsNull );
-}
-
-/*!
- Destructor
-*/
-QtxParser::~QtxParser()
-{
-}
-
-/*!
- Search elements of list as substrings starting on 'offset'
- \returns the least position of substrings inside string
- \param list - list of substrings
- \param str - string where search
- \param offset - starting index for search
- \param matchLen - the length of appropriate substring
- \param listind - list index of appropriate substring
-*/
-int QtxParser::search( const QStringList& list, const QString& str, int offset,
- int& matchLen, int& listind )
-{
- QStringList::const_iterator anIt = list.begin(), aLast = list.end();
- int min = -1;
- for( int ind = 0; anIt!=aLast; anIt++, ind++ )
- {
- //const char* where = str.latin1(), *what = (*anIt).latin1();
- int pos = str.find( *anIt, offset );
- if( pos>=0 && ( min < 0 || min > pos ||
- ( min==pos && matchLen< (int)(*anIt).length() ) ) )
- {
- min = pos;
- listind = ind;
- matchLen = (*anIt).length();
- }
- }
- if( min<0 )
- matchLen = 0;
- return min;
-}
-
-/*!
- \return substring
- \param str - string
- \param pos - start position of substring
- \param len - length of substring
-*/
-QString QtxParser::note( const QString& str, int pos, int len )
-{
- return str.mid( pos, len ).stripWhiteSpace();
-}
-
-/*!
- First step of parsing: finding tokens, determining its types and creating of unsorted pseudo-postfix (with brackets)
- \param expr - string expression
- \param post - postfix to be created
-*/
-bool QtxParser::prepare( const QString& expr, Postfix& post )
-{
- int pos = 0, len = expr.length();
- QValueStack< int > aBracketStack;
- QStringList anOpers, anOpenBr, aCloseBr;
- if( myOperations )
- {
- myOperations->bracketsList( anOpenBr, true );
- myOperations->bracketsList( aCloseBr, false );
- myOperations->opersList( anOpers );
- }
- else
- {
- setLastError( OperationsNull );
- return false;
- }
-
- while( pos < len && lastError()==OK )
- {
- PostfixItem item;
- while( expr[ pos ].isSpace() && pos<len ) pos++;
- if( pos>=len )
- break;
-
- int mBrLen = 0, mLen = 0, br_ind = -1, op_ind = -1;
- int oPos = search( anOpenBr, expr, pos, mBrLen, br_ind ),
- cPos = oPos==pos ? -1 : search( aCloseBr, expr, pos, mBrLen, br_ind ),
- opPos = search( anOpers, expr, pos, mLen, op_ind );
-
- if( expr[ pos ]=="'" )
- {
- int vpos = pos+1;
- while ( vpos< (int)expr.length() && expr[ vpos ]!="'" )
- vpos++;
-
- mLen = vpos-pos+1;
-
- int res = myOperations->createValue( note( expr, pos, mLen ), item.myValue );
- item.myType = res ? Value : Param;
- post.append( item );
- pos = vpos+1;
- continue;
- }
-
- if( oPos==pos )
- {
- aBracketStack.push( br_ind );
- item.myValue = note( expr, pos, mBrLen );
- item.myType = Open;
- post.append( item );
- }
-
- else if( cPos==pos )
- {
- if( aBracketStack.count()==0 )
- {
- setLastError( ExcessClose );
- break;
- }
- if( br_ind!=aBracketStack.top() )
- {
- setLastError( BracketsNotMatch );
- break;
- }
- else
- {
- aBracketStack.pop();
- item.myValue = note( expr, pos, mBrLen );
- item.myType = Close;
- post.append( item );
- }
- }
- else
- mBrLen = 0;
-
- if( opPos==pos )
- {
- mBrLen = 0;
- item.myValue = note( expr, pos, mLen );
- item.myType = Binary;
- //the type is set by default;
- //the method setOperationTypes will set correct types
-
- if( oPos==pos )
- post.insert( post.at( post.count()-1 ), item );
- else
- post.append( item );
- }
- else
- {
- mLen = 0;
- if( oPos!=pos && cPos!=pos )
- {
- int i;
- for( i=pos+1; i<(int)expr.length(); i++ )
- if( expr[ i ].isSpace() )
- break;
-
- int vpos = i;
- if( oPos>=0 && oPos<vpos )
- vpos = oPos;
- if( cPos>=0 && cPos<vpos )
- vpos = cPos;
- if( opPos>=0 && opPos<vpos )
- vpos = opPos;
-
- while( vpos<(int)expr.length() &&
- ( expr[vpos].isLetter() || expr[vpos].isDigit() || expr[vpos]=='_' ) )
- vpos++;
-
- mLen = vpos-pos;
- bool res = myOperations->createValue( note( expr, pos, mLen ), item.myValue );
- item.myType = res ? Value : Param;
- post.append( item );
- }
- }
-
- pos+=mBrLen+mLen;
- }
-
- //Bracket checking
- PostfixIterator anIt = post.begin(),
- aLast = post.end();
- int brValue = 0;
- for( ; anIt!=aLast; anIt++ )
- if( (*anIt).myType==Open )
- brValue++;
- else if( (*anIt).myType==Close )
- if( brValue>0 )
- brValue--;
- else
- {
- setLastError( ExcessClose );
- break;
- }
- if( brValue>0 )
- setLastError( CloseExpected );
-
- return lastError()==OK;
-}
-
-/*!
- Second step of parsing: determining types of operations
- \param post - unsorted postfix
-*/
-bool QtxParser::setOperationTypes( Postfix& post )
-{
- Postfix::iterator aStart = post.begin(),
- aLast = post.end(),
- anIt = aStart, aPrev, aNext;
- QStringList anOpen, aClose;
- if( myOperations )
- {
- myOperations->bracketsList( anOpen, true );
- myOperations->bracketsList( aClose, false );
- }
- else
- return false;
-
- for( ; anIt!=aLast; anIt++ )
- {
- aPrev = anIt; aPrev--;
- aNext = anIt; aNext++;
- if( (*anIt).myType != Binary )
- continue;
-
- if( ( anIt==aStart || (*aPrev).myType == Open ||
- (*aPrev).myType == Pre ||
- (*aPrev).myType == Binary )
- &&
- aNext!=aLast && ( (*aNext).myType == Value ||
- (*aNext).myType == Param ||
- (*aNext).myType == Open ||
- (*aNext).myType == Binary ) )
- (*anIt).myType = Pre;
-
- else if( anIt!=aStart && ( (*aPrev).myType == Close ||
- (*aPrev).myType == Param ||
- (*aPrev).myType == Value ||
- (*aPrev).myType == Pre ||
- (*aPrev).myType == Post ||
- (*aPrev).myType == Binary )
- &&
- ( aNext==aLast || (*aNext).myType == Close ) )
- (*anIt).myType = Post;
-
- if( anOpen.contains( ( *anIt ).myValue.toString() )>0 )
- (*anIt).myType = Pre;
- else if( aClose.contains( ( *anIt ).myValue.toString() )>0 )
- (*anIt).myType = Post;
- }
-
- return lastError()==OK;
-}
-
-/*!
- \return how many global brackets there is (for example '((2+3))' has 2 global brackets)
- \param post - postfix to be checked
- \param f - start index to search
- \param l - last index to search
-*/
-int QtxParser::globalBrackets( const QtxParser::Postfix& post, int f, int l )
-{
- int i,
- start_br = 0,
- fin_br = 0,
- br = 0,
- br_num = 0,
- min_br_num = (l-f+1)*5;
-
- for( i=f; i<=l; i++ )
- if( post[ i ].myType==QtxParser::Open )
- start_br++;
- else
- break;
- for( i=l; i>=f; i-- )
- if( post[ i ].myType==QtxParser::Close )
- fin_br++;
- else
- break;
-
- br = start_br<fin_br ? start_br : fin_br;
- for( i=f+br; i<=l-br; i++ )
- {
- if( post[i].myType==QtxParser::Open )
- br_num++;
- else if( post[i].myType==QtxParser::Close )
- br_num--;
- if( br_num<min_br_num )
- min_br_num = br_num;
- }
-
- return br+min_br_num;
-}
-
-/*!
- Third step of parsing: sorting of postfix in order to convert it to real postfix
- \param post - source postfix
- \param res - destination postfix
- \param anOpen - list of open brackets
- \param aClose - list of close brackets
- \param f - start index of postfix to sorting
- \param l - last index of postfix to sorting
-*/
-bool QtxParser::sort( const Postfix& post, Postfix& res,
- const QStringList& anOpen,
- const QStringList& aClose,
- int f, int l )
-{
- if( l<f )
- return true;
-
- if( f<0 )
- f = 0;
- if( l<0 )
- l = post.count()-1;
-
- int br = globalBrackets( post, f, l );
- f+=br; l-=br;
-
- if( f==l && f>=0 )
- res.append( post[ f ] );
- if( l<=f )
- return true;
-
- if( myOperations )
- {
- int min = -1;
- QIntList argmin;
- QValueList< PostfixItemType > min_types;
-
- //Find operation with minimal priority
- //PostfixIterator anIt = post.at( f ),
- // aLast = post.at( l+1 );
- for( int i=0, j=f; j<=l; i++, j++ )
- {
- const PostfixItem& item = post[ j ];
- PostfixItemType tt = item.myType;
- if( tt==Binary || tt==Pre || tt==Post )
- {
- int cur_pr = myOperations->prior( item.myValue.toString(), tt==Binary );
- if( cur_pr>0 )
- {
- if( min<0 || min>=cur_pr )
- {
- if( min==cur_pr )
- {
- argmin.append( f+i );
- min_types.append( tt );
- }
- else
- {
- min = cur_pr;
- argmin.clear(); argmin.append( f+i );
- min_types.clear(); min_types.append( tt );
- }
- }
- }
- else
- {
- setLastError( InvalidOperation );
- break;
- }
- }
- else if( tt==Open )
- {
- QString opBr = item.myValue.toString();
- int ind = anOpen.findIndex( opBr ), brValue = 0;
- while( j<=l )
- {
- const PostfixItem& anItem = post[ j ];
- if( anItem.myType==Open )
- brValue++;
-
- if( anItem.myType==Close )
- {
- brValue--;
- QString clBr = anItem.myValue.toString();
- if( aClose.findIndex( clBr )==ind && brValue==0 )
- break;
- }
- i++; j++;
- }
- if( brValue>0 )
- {
- setLastError( CloseExpected );
- break;
- }
- }
- }
-
- if( lastError()==OK )
- if( min>=0 )
- {
- QValueList< Postfix > parts;
- QIntList::const_iterator anIt = argmin.begin(),
- aLast = argmin.end();
- Postfix one;
- bool ok = sort( post, one, anOpen, aClose, f, *anIt - 1 );
- parts.append( one );
- one.clear();
- for( ; anIt!=aLast && ok; anIt++ )
- {
- QIntList::const_iterator aNext = anIt; aNext++;
- ok = sort( post, one, anOpen, aClose, *anIt + 1, aNext==aLast ? l : *aNext - 1 );
- parts.append( one );
- one.clear();
- }
- if( !ok )
- return false;
-
- QValueList< Postfix >::const_iterator aPIt = parts.begin();
- QValueList< PostfixItemType >::const_iterator aTIt = min_types.begin();
- QValueStack< PostfixItem > aStack;
- res += (*aPIt); aPIt++;
- anIt = argmin.begin();
- for( ; anIt!=aLast; anIt++, aPIt++, aTIt++ )
- {
- if( *aTIt==Pre )
- if( anOpen.contains( post[ *anIt ].myValue.toString() )==0 )
- {
- res+=(*aPIt);
- aStack.push( post[ *anIt ] );
- }
- else
- {
- res.append( post[ *anIt ] );
- res+=(*aPIt);
- }
- else
- {
- res+=(*aPIt);
- while( !aStack.isEmpty() )
- {
- res.append( aStack.top() );
- aStack.pop();
- }
- res.append( post[ *anIt ] );
- }
- }
- while( !aStack.isEmpty() )
- {
- res.append( aStack.top() );
- aStack.pop();
- }
- }
- else
- { //there are no operations
- PostfixIterator anIt = post.at( f ),
- aLast = post.at( l+1 );
- for( ; anIt!=aLast; anIt++ )
- if( (*anIt).myType==Value || (*anIt).myType==Param )
- res.append( *anIt );
- }
- }
- else
- setLastError( OperationsNull );
-
- return lastError()==OK;
-}
-
-/*!
- Build posfix by expression
- \param expr - string expression
-*/
-bool QtxParser::parse( const QString& expr )
-{
- myPost.clear();
-
- Postfix p;
- QStringList opens, closes;
-
- if( myOperations )
- {
- setLastError( OK );
- myOperations->bracketsList( opens, true );
- myOperations->bracketsList( closes, false );
- }
- else
- {
- setLastError( OperationsNull );
- return false;
- }
-
- //return prepare( expr, myPost ) && setOperationTypes( myPost );
- return prepare( expr, p ) && setOperationTypes( p ) &&
- sort( p, myPost, opens, closes );
-}
-
-/*!
- Calculate operation
- \param op - operation name
- \param v1 - first argument (it is not valid for unary prefix operations and it is used to store result)
- \param v2 - second argument (it is not valid for unary postfix operations)
-*/
-bool QtxParser::calculate( const QString& op, QtxValue& v1, QtxValue& v2 )
-{
- Error err = myOperations->isValid( op, v1.type(), v2.type() );
- if( err==OK )
- setLastError( myOperations->calculate( op, v1, v2 ) );
- else
- setLastError( err );
-
- return lastError()==OK;
-}
-
-/*!
- Calculates expression without postfix rebuilding
- \return QtxValue as result (it is invalid if there were errors during calculation)
-*/
-QtxValue QtxParser::calculate()
-{
- setLastError( OK );
-
- QStringList anOpen, aClose;
- if( myOperations )
- {
- myOperations->bracketsList( anOpen, true );
- myOperations->bracketsList( aClose, false );
- }
- else
- {
- setLastError( OperationsNull );
- return QtxValue();
- }
-
- QtxValueStack aStack;
- PostfixIterator anIt = myPost.begin(),
- aLast = myPost.end();
- for( ; anIt!=aLast && lastError()==OK; anIt++ )
- {
- QString nn = (*anIt).myValue.toString();
- if( (*anIt).myType==Param )
- {
- if( has( nn ) )
- {
- QVariant& v = myParameters[ nn ];
- if( v.isValid() )
- aStack.push( v );
- else
- setLastError( InvalidToken );
- }
- else
- setLastError( InvalidToken );
- }
-
- else if( (*anIt).myType==Value )
- aStack.push( (*anIt).myValue );
-
- else if( (*anIt).myType==Pre || (*anIt).myType==Post )
- {
- if( anOpen.contains( nn )>0 )
- {
- QtxValue inv;
- if( calculate( nn, inv, inv ) )
- aStack.push( QtxValue() );
- }
- else if( aClose.contains( nn )>0 )
- {
- QValueList< QtxValue > set;
- while( true )
- {
- if( aStack.count()==0 )
- {
- setLastError( StackUnderflow );
- break;
- }
- if( aStack.top().isValid() )
- {
- set.append( aStack.top() );
- aStack.pop();
- }
- else
- {
- aStack.pop();
- break;
- }
- }
-
- QtxValue qSet = set, inv;
- if( calculate( nn, qSet, inv ) )
- aStack.push( set );
- }
- else if( aStack.count()>=1 )
- {
- QtxValue inv;
- QtxValue* v1 = &aStack.top(), *v2 = &inv; //"post-" case
- if( (*anIt).myType==Pre )
- {
- v2 = &aStack.top(); v1 = &inv;
- }
-
- calculate( nn, *v1, *v2 );
- }
- else
- setLastError( StackUnderflow );
- }
-
- else if( (*anIt).myType==Binary )
- {
- if( aStack.count()>=2 )
- {
- QVariant v2 = aStack.top(); aStack.pop();
- calculate( nn, aStack.top(), v2 );
- }
- else
- setLastError( StackUnderflow );
- }
- }
-
- QtxValue res;
- if( lastError()==OK )
- {
- int count = aStack.count();
- if( count==0 )
- setLastError( StackUnderflow );
- else if( count==1 )
- res = aStack.top();
- else
- setLastError( ExcessData );
- }
- return res;
-}
-
-/*!
- Change expression, rebuild postfix and calculate it
- \return QtxValue as result (it is invalid if there were errors during calculation)
-*/
-QtxValue QtxParser::calculate( const QString& expr )
-{
- setExpr( expr );
- return calculate();
-}
-
-/*!
- Change expression and rebuild postfix
-*/
-bool QtxParser::setExpr( const QString& expr )
-{
- return parse( expr );
-}
-
-/*!
- \return true, if parser contain parameter
- \param name - name of parameter
-*/
-bool QtxParser::has( const QString& name ) const
-{
- return myParameters.contains( name.stripWhiteSpace() );
-}
-
-/*!
- Sets parameter value
- \param name - name of parameter
- \param value - value of parameter
-*/
-void QtxParser::set( const QString& name, const QtxValue& value )
-{
- myParameters[ name.stripWhiteSpace() ] = value;
-}
-
-/*!
- Removes parameter
- \param name - name of parameter
-*/
-bool QtxParser::remove( const QString& name )
-{
- QString sname = name.stripWhiteSpace();
- bool res = has( sname );
- if( res )
- myParameters.remove( sname );
- return res;
-}
-
-/*!
- \return value of parameter (result is invalid if there is no such parameter)
- \param name - name of parameter
-*/
-QtxValue QtxParser::value( const QString& name ) const
-{
- QString sname = name.stripWhiteSpace();
- if( has( sname ) )
- return myParameters[ sname ].toString();
- else
- return QtxValue();
-}
-
-/*!
- Searches first parameter with assigned invalid QtxValue
- \return true if it is found
- \param name - variable to return name of parameter
-*/
-bool QtxParser::firstInvalid( QString& name ) const
-{
- QMap< QString, QtxValue >::const_iterator anIt = myParameters.begin(),
- aLast = myParameters.end();
- for( ; anIt!=aLast; anIt++ )
- if( !anIt.data().isValid() )
- {
- name = anIt.key();
- return true;
- }
- return false;
-}
-
-/*!
- Removes all parameters with assigned invalid QtxValues
-*/
-void QtxParser::removeInvalids()
-{
- QStringList toDelete;
- QMap< QString, QtxValue >::const_iterator anIt = myParameters.begin(),
- aLast = myParameters.end();
- for( ; anIt!=aLast; anIt++ )
- if( !anIt.data().isValid() )
- toDelete.append( anIt.key() );
-
- QStringList::const_iterator aLIt = toDelete.begin(),
- aLLast = toDelete.end();
- for( ; aLIt!=aLLast; aLIt++ )
- myParameters.remove( *aLIt );
-}
-
-/*!
- \return last error occured during parsing
-*/
-QtxParser::Error QtxParser::lastError() const
-{
- return myLastError;
-}
-
-/*!
- Sets last error occured during parsing (for internal using only)
-*/
-void QtxParser::setLastError( QtxParser::Error err )
-{
- myLastError = err;
-}
-
-/*!
- \return string dump of internal parser postfix
-*/
-QString QtxParser::dump() const
-{
- return dump( myPost );
-}
-
-/*!
- \return string dump of postfix
- \param post - postfix to be dumped
-*/
-QString QtxParser::dump( const Postfix& post ) const
-{
- QString res;
-
- if( myOperations )
- {
- PostfixIterator anIt = post.begin(),
- aLast = post.end();
- for( ; anIt!=aLast; anIt++ )
- {
- if( (*anIt).myType == Value &&
- ( ( *anIt ).myValue.type()==QVariant::String ||
- ( *anIt ).myValue.type()==QVariant::CString ) )
- res += "'" + ( *anIt ).myValue.toString() + "'";
- else
- res += ( *anIt ).myValue.toString();
- if( (*anIt).myType == Pre )
- res += "(pre)";
- else if( (*anIt).myType == Post )
- res += "(post)";
- else if( (*anIt).myType == Binary )
- res += "(bin)";
-
- res += "_";
- }
- }
- return res;
-}
-
-/*!
- Fills list with names of parameters
- \param list - list to be filled
-*/
-void QtxParser::paramsList( QStringList& list )
-{
- PostfixIterator anIt = myPost.begin(),
- aLast = myPost.end();
- for( ; anIt!=aLast; anIt++ )
- if( (*anIt).myType==Param )
- {
- QString name = (*anIt).myValue.toString();
- if( list.contains( name )==0 )
- list.append( name );
- }
-}
-
-/*!
- Removes all parameters
-*/
-void QtxParser::clear()
-{
- myParameters.clear();
-}
-
-/*!
- \return string representation for list of QtxValues
- \param list - list to be converted
-*/
-QString QtxParser::toString( const QValueList< QtxValue >& list )
-{
- QValueList< QtxValue >::const_iterator anIt = list.begin(),
- aLast = list.end();
- QString res = "set : [ ";
- for( ; anIt!=aLast; anIt++ )
- res+=(*anIt).toString()+" ";
- res+="]";
- return res;
-}
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-// File: QtxParser.h
-// Author: Alexander SOLOVYOV
-
-#ifndef __QTX_PARSER_HEADER__
-#define __QTX_PARSER_HEADER__
-
-#include "Qtx.h"
-#include <qvaluestack.h>
-#include <qvariant.h>
-
-#ifdef WIN32
-#pragma warning( disable:4251 )
-#endif
-
-
-class QtxOperations;
-
-/*! \var QtxValue
- \brief Alias for QVariant
-*/
-typedef QVariant QtxValue;
-
-
-/*!
- \class QtxParser
-
- This class allows to calculate values of expressions using different set of operations.
- It is provided some of standard set of operations (arithmetics, logic, strings, etc - in QtxStdOperations.h).
- This parser allows to use parameters with help of methods has(), set(), remove(), value(). It uses
- postfix representation of expressions and uses class QtxOperations in order to make certain operation
- Every instance of parser contains only one postfix, so that if expression has been changed, then postfix
- must be rebuilt. In order to increase performance of frequent calculation for many of expressions it is
- recommended to use different instances of parser for expressions
-
-*/
-class QTX_EXPORT QtxParser
-{
-public:
- /*!
- \enum Error
- \brief Errors during parsing
- */
- typedef enum
- {
- OK, /*! \var All right */
- OperandsNotMatch, /*! \var Types of arguments are invalid for this operation */
- InvalidResult, /*! \var Operation cannot find result (for example, division by zero) */
- InvalidOperation, /*! \var Name of operation is unknown */
- OperationsNull, /*! \var Internal operations pointer of parser is null */
- InvalidToken, /*! \var It isn't operation, parameter of value */
- CloseExpected, /*! \var Close bracket is expected */
- ExcessClose, /*! \var The one of close bracket is excess */
- BracketsNotMatch, /*! \var Last open and this close bracket are different, for example [) */
- StackUnderflow, /*! \var There is no arguments in stack for operation */
- ExcessData /*! \var The parsing is finished, but there is more then one value in stack */
-
- } Error;
-
-public:
- QtxParser( QtxOperations*, const QString& = QString::null );
- virtual ~QtxParser();
-
- QtxValue calculate();
- QtxValue calculate( const QString& );
- bool setExpr( const QString& );
-
- virtual void clear();
- virtual bool has ( const QString& name ) const;
- virtual void set ( const QString& name, const QtxValue& value );
- virtual bool remove( const QString& name );
- virtual QtxValue value ( const QString& name ) const;
-
- bool firstInvalid( QString& ) const;
- void removeInvalids();
- QString dump() const;
- Error lastError() const;
- void paramsList( QStringList& );
-
- static QString toString( const QValueList< QtxValue >& );
-
-protected:
- /*!
- \enum PostfixItemType
- \brief Types of postfix representation elements
- */
- typedef enum
- {
- Value, /*! \var Value (number, string, etc.)*/
- Param, /*! \var Parameter */
- Open, /*! \var Open bracket */
- Close, /*! \var Close bracket */
- Pre, /*! \var Unary prefix operation */
- Post, /*! \var Unary postfix operation */
- Binary /*! \var Binary operation */
-
- } PostfixItemType;
-
- /*! \var postfix representation element */
- typedef struct
- {
- QtxValue myValue;
- PostfixItemType myType;
-
- } PostfixItem;
-
- /*! \var postfix representation */
- typedef QValueList< PostfixItem > Postfix;
-
- /*! \var postfix representation iterator */
- typedef Postfix::const_iterator PostfixIterator;
-
-protected:
- QString dump( const Postfix& ) const;
- virtual bool prepare( const QString&, Postfix& );
- virtual bool setOperationTypes( Postfix& );
- virtual bool sort( const Postfix&, Postfix&,
- const QStringList&, const QStringList&,
- int f=-1, int l=-1 );
-
- virtual bool parse( const QString& );
- virtual void setLastError( const Error );
-
- bool calculate( const QString&, QtxValue&, QtxValue& );
-
- static int search ( const QStringList&, const QString&, int offset,
- int& matchLen, int& listind );
- static QString note ( const QString& str, int pos, int len );
- static int globalBrackets( const Postfix&, int, int );
-
-private:
- /*! \var stack of QtxValues */
- typedef QValueStack < QtxValue > QtxValueStack;
-
-private:
- QtxOperations* myOperations;
- QMap< QString, QtxValue > myParameters;
- Error myLastError;
- Postfix myPost;
-};
-
-#endif
#include "QtxPathDialog.h"
+#include "QtxGridBox.h"
#include "QtxGroupBox.h"
-#include <qdir.h>
-#include <qlabel.h>
-#include <qpixmap.h>
-#include <qlayout.h>
-#include <qlineedit.h>
-#include <qfileinfo.h>
-#include <qobjectlist.h>
-#include <qstringlist.h>
-#include <qfiledialog.h>
-#include <qmessagebox.h>
-#include <qpushbutton.h>
+#include <QDir>
+#include <QLabel>
+#include <QPixmap>
+#include <QVBoxLayout>
+#include <QLineEdit>
+#include <QObjectList>
+#include <QStringList>
+#include <QFileDialog>
+#include <QMessageBox>
+#include <QPushButton>
static const char* open_icon[] = {
"16 16 5 1",
};
/*!
- Constructor.
+ \class QtxPathDialog
+ \brief The QtxPathDialog class provides a simple convenience dialog to
+ enter a path to the file or to the directory.
+
+ The QtxPathDialog class adds possibility to browse the file system
+ with help of standard Open/Save dialog boxes or enter the file/directory
+ path manually.
+
+ Default implementation provides only one "standard" file entry.
+ Sometimes it is necessary to select several different files/directories
+ from the same dialog box. In this case it is possible to derive from the
+ QtxPathDialog class and use createFileEntry() method to add required
+ number of file entries.
*/
-QtxPathDialog::QtxPathDialog( const bool import, QWidget* parent, const bool modal, const bool resize, const int buttons, WFlags f )
-: QtxDialog( parent, 0, modal, resize, buttons, f ),
-myDefault( -1 ),
-myEntriesFrame( 0 ),
-myOptionsFrame( 0 )
-{
- initialize();
-
- setCaption( tr( import ? "Open file" : "Save file" ) );
-
- setDefaultEntry( createFileEntry( tr( "File name" ), import ? OpenFile : SaveFile ) );
- QLineEdit* le = fileEntry( defaultEntry() );
- if ( le )
- le->setMinimumWidth( 200 );
- validate();
-
- setFocusProxy( le );
+/*!
+ \brief Constructor.
+ \param import if \c true, the dialog box is shown for "open" mode,
+ otherwise, it is shown in the "save" mode
+ \param parent parent widget
+ \param modal if \c true, the dialog box should be modal
+ \param resize if \c true, the dialog box is resizable
+ \param buttons required buttons (QtxDialog::ButtonFlags)
+ \param f window flags
+*/
+QtxPathDialog::QtxPathDialog( const bool import, QWidget* parent, const bool modal,
+ const bool resize, const int buttons, Qt::WindowFlags f )
+: QtxDialog( parent, modal, resize, buttons, f ),
+ myDefault( -1 ),
+ myEntriesFrame( 0 ),
+ myOptionsFrame( 0 )
+{
+ initialize();
+
+ setWindowTitle( tr( import ? "Open file" : "Save file" ) );
+
+ setDefaultEntry( createFileEntry( tr( "File name" ), import ? OpenFile : SaveFile ) );
+ QLineEdit* le = fileEntry( defaultEntry() );
+ if ( le )
+ le->setMinimumWidth( 200 );
+
+ validate();
+
+ setFocusProxy( le );
+
+ updateVisibility();
}
/*!
- Constructor.
+ \brief Constructor.
+ \param parent parent widget
+ \param modal if \c true, the dialog box should be modal
+ \param resize if \c true, the dialog box is resizable
+ \param buttons required buttons (QtxDialog::ButtonFlags)
+ \param f window flags
*/
-QtxPathDialog::QtxPathDialog( QWidget* parent, const bool modal, const bool resize, const int buttons, WFlags f )
-: QtxDialog( parent, 0, modal, resize, buttons, f ),
-myDefault( -1 ),
-myEntriesFrame( 0 ),
-myOptionsFrame( 0 )
+QtxPathDialog::QtxPathDialog( QWidget* parent, const bool modal,
+ const bool resize, const int buttons, Qt::WindowFlags f )
+: QtxDialog( parent, modal, resize, buttons, f ),
+ myDefault( -1 ),
+ myEntriesFrame( 0 ),
+ myOptionsFrame( 0 )
{
- initialize();
+ initialize();
+
+ updateVisibility();
}
/*!
- Destructor.
+ \brief Destructor.
*/
QtxPathDialog::~QtxPathDialog()
{
}
/*!
+ \brief Get selected file name.
\return file name
*/
QString QtxPathDialog::fileName() const
{
- return fileName( defaultEntry() );
+ return fileName( defaultEntry() );
}
/*!
- Sets file name
- \param txt - new file name
- \param autoExtension - auto extension determination by file
+ \brief Set the file name.
+ \param txt new file name
+ \param autoExtension if \c true an extension is determined automatically by file
*/
void QtxPathDialog::setFileName( const QString& txt, const bool autoExtension )
{
- setFileName( defaultEntry(), txt, autoExtension );
+ setFileName( defaultEntry(), txt, autoExtension );
}
/*!
- \return filter
+ \brief Get current file filter.
+ \return file filter
*/
QString QtxPathDialog::filter() const
{
- return myFilter;
+ return filter( defaultEntry() );
}
/*!
- Changes filter (filter is a list of masks, separated by ';;')
- \param fltr - new filter
+ \brief Change file filter.
+
+ Filter is a list of file masks, separated by ';;'. For example,
+ "*.h;;*.cxx"
+
+ \param fltr new file filter
*/
void QtxPathDialog::setFilter( const QString& fltr )
{
- myFilter = fltr;
+ setFilter( defaultEntry(), fltr );
}
/*!
- Shows path dialog
+ \brief Show/hide the path dialog box/
+ \param on new visibility state
*/
-void QtxPathDialog::show()
+void QtxPathDialog::setVisible( bool on )
{
- if ( hasVisibleChildren( myEntriesFrame ) )
- myEntriesFrame->show();
- else
- myEntriesFrame->hide();
+ if ( on )
+ updateVisibility();
- if ( hasVisibleChildren( myOptionsFrame ) )
- myOptionsFrame->show();
- else
- myOptionsFrame->hide();
-
- QtxDialog::show();
+ QtxDialog::setVisible( on );
}
/*!
- SLOT: called if user click button to show standard file dialog
+ \brief Called when user clicks a "browse" button
+ to open standard file dialog.
*/
void QtxPathDialog::onBrowse()
{
- const QObject* obj = sender();
-
- int id = -1;
-
- for ( FileEntryMap::Iterator it = myEntries.begin(); it != myEntries.end() && id == -1; ++it )
- if ( it.data().btn == obj )
- id = it.key();
-
- if ( id == -1 )
- return;
-
- FileEntry& entry = myEntries[id];
-
- bool isDir = entry.mode != OpenFile && entry.mode != SaveFile;
-
- if ( !entry.dlg )
- {
- entry.dlg = new QFileDialog( QDir::current().path(), QString::null, this, 0, true );
- entry.dlg->setCaption( caption() );
- switch ( entry.mode )
- {
- case NewDir:
- case OpenDir:
- case SaveDir:
- isDir = true;
- entry.dlg->setMode( QFileDialog::DirectoryOnly );
- break;
- case SaveFile:
- entry.dlg->setMode( QFileDialog::AnyFile );
- break;
- case OpenFile:
- default:
- entry.dlg->setMode( QFileDialog::ExistingFile );
- break;
- }
- }
-
- if ( !isDir )
- entry.dlg->setFilters( prepareFilters() );
- entry.dlg->setSelection( fileName( id ) );
-
- if ( entry.dlg->exec() != Accepted )
- return;
-
- QString fName = entry.dlg->selectedFile();
-
- if ( fName.isEmpty() )
- return;
-
- if ( QFileInfo( fName ).extension().isEmpty() && !isDir )
- fName = autoExtension( fName, entry.dlg->selectedFilter() );
-
- fName = QDir::convertSeparators( fName );
- QString prev = QDir::convertSeparators( fileName( id ) );
- if ( isDir )
- {
- while ( prev.length() && prev.at( prev.length() - 1 ) == QDir::separator() )
- prev.remove( prev.length() - 1, 1 );
- while ( fName.length() && fName.at( fName.length() - 1 ) == QDir::separator() )
- fName.remove( fName.length() - 1, 1 );
- }
-
- if ( prev == fName )
- return;
-
- setFileName( id, fName );
- fileNameChanged( id, fName );
-
- if ( id == defaultEntry() )
- emit fileNameChanged( fName );
+ const QObject* obj = sender();
+
+ int id = -1;
+
+ for ( FileEntryMap::Iterator it = myEntries.begin(); it != myEntries.end() && id == -1; ++it )
+ {
+ if ( it.value().btn == obj )
+ id = it.key();
+ }
+
+ if ( id == -1 )
+ return;
+
+ FileEntry& entry = myEntries[id];
+
+ bool isDir = entry.mode != OpenFile && entry.mode != SaveFile;
+
+ if ( !entry.dlg )
+ {
+ entry.dlg = new QFileDialog( this, windowTitle(), QDir::current().path() );
+ switch ( entry.mode )
+ {
+ case NewDir:
+ case OpenDir:
+ case SaveDir:
+ isDir = true;
+ entry.dlg->setFileMode( QFileDialog::DirectoryOnly );
+ break;
+ case SaveFile:
+ entry.dlg->setFileMode( QFileDialog::AnyFile );
+ break;
+ case OpenFile:
+ default:
+ entry.dlg->setFileMode( QFileDialog::ExistingFiles );
+ break;
+ }
+ }
+
+ if ( !isDir )
+ {
+ QStringList fList = prepareFilters( entry.filter );
+ if ( !fList.isEmpty() )
+ entry.dlg->setFilters( fList );
+ }
+ entry.dlg->selectFile( fileName( id ) );
+
+ if ( entry.dlg->exec() != Accepted )
+ return;
+
+ QStringList fileList = entry.dlg->selectedFiles();
+ QString fName = !fileList.isEmpty() ? fileList.first() : QString();
+
+ if ( fName.isEmpty() )
+ return;
+
+ if ( Qtx::extension( fName ).isEmpty() && !isDir )
+ fName = autoExtension( fName, entry.dlg->selectedFilter() );
+
+ fName = QDir::convertSeparators( fName );
+ QString prev = QDir::convertSeparators( fileName( id ) );
+ if ( isDir )
+ {
+ while ( prev.length() && prev.at( prev.length() - 1 ) == QDir::separator() )
+ prev.remove( prev.length() - 1, 1 );
+ while ( fName.length() && fName.at( fName.length() - 1 ) == QDir::separator() )
+ fName.remove( fName.length() - 1, 1 );
+ }
+
+ if ( prev == fName )
+ return;
+
+ setFileName( id, fName );
+ fileNameChanged( id, fName );
+
+ if ( id == defaultEntry() )
+ emit fileNameChanged( fName );
}
/*!
- SLOT: called if user presses RETURN in line edit
+ \brief Called when user presses \c Return key being in the line edit.
*/
void QtxPathDialog::onReturnPressed()
{
- const QObject* obj = sender();
-
- int id = -1;
- for ( FileEntryMap::Iterator it = myEntries.begin(); it != myEntries.end() && id == -1; ++it )
- if ( it.data().edit == obj )
- id = it.key();
-
- if ( id == -1 )
- return;
-
- fileNameChanged( id, fileName( id ) );
-
- if ( id == defaultEntry() )
- emit fileNameChanged( fileName() );
+ const QObject* obj = sender();
+
+ int id = -1;
+ for ( FileEntryMap::Iterator it = myEntries.begin(); it != myEntries.end() && id == -1; ++it )
+ {
+ if ( it.value().edit == obj )
+ id = it.key();
+ }
+
+ if ( id == -1 )
+ return;
+
+ fileNameChanged( id, fileName( id ) );
+
+ if ( id == defaultEntry() )
+ emit fileNameChanged( fileName() );
}
/*!
- SLOT: called if text in line edit is changed
+ \brief Called when the text in the line edit is changed by the user.
+ \param txt current text (not used)
*/
-void QtxPathDialog::onTextChanged( const QString& )
+void QtxPathDialog::onTextChanged( const QString& /*txt*/ )
{
- validate();
+ validate();
}
/*!
- Checks validity of text and according to it enables/disables OK, Yes buttons
+ \brief Check validity of the entered text and enable/disable standard
+ \c OK, \c Yes buttons.
*/
void QtxPathDialog::validate()
{
- setButtonEnabled( isValid(), OK | Yes );
+ setButtonEnabled( isValid(), OK | Yes );
}
/*!
- \return true if selected file is valid
+ \brief Check if the entered file/directory name is valid.
+ \return \c true if selected file name is valid
*/
bool QtxPathDialog::isValid()
{
- bool ok = true;
- for ( FileEntryMap::Iterator it = myEntries.begin(); it != myEntries.end() && ok; ++it )
- if ( it.data().edit->isEnabled() )
- ok = !it.data().edit->text().stripWhiteSpace().isEmpty();
-
- return ok;
+ bool ok = true;
+ for ( FileEntryMap::Iterator it = myEntries.begin(); it != myEntries.end() && ok; ++it )
+ {
+ if ( it.value().edit->isEnabled() )
+ ok = !it.value().edit->text().trimmed().isEmpty();
+ }
+
+ return ok;
}
/*!
- \return true entered data is accepted
+ \brief Check if the entered data is acceptable.
+ \return \c true if entered data is acceptable
*/
bool QtxPathDialog::acceptData() const
{
- bool ok = true;
-
- QWidget* parent = (QWidget*)this;
-
- FileEntryMap::ConstIterator it;
- for ( it = myEntries.begin(); it != myEntries.end() && ok; ++it )
+ bool ok = true;
+
+ QWidget* parent = (QWidget*)this;
+
+ FileEntryMap::ConstIterator it;
+ for ( it = myEntries.begin(); it != myEntries.end() && ok; ++it )
+ {
+ const FileEntry& entry = it.value();
+ QFileInfo fileInfo( entry.edit->text() );
+ if ( entry.edit->text().isEmpty() )
+ {
+ QMessageBox::critical( parent, windowTitle(), tr( "File name not specified" ),
+ QMessageBox::Ok, QMessageBox::NoButton );
+ ok = false;
+ }
+ else switch ( entry.mode )
+ {
+ case OpenFile:
+ if ( !fileInfo.exists() )
+ {
+ QMessageBox::critical( parent, windowTitle(), tr( "File \"%1\" does not exist" ).arg( fileInfo.filePath() ),
+ QMessageBox::Ok, QMessageBox::NoButton );
+ ok = false;
+ }
+ break;
+ case SaveFile:
+ if ( fileInfo.exists() )
+ ok = QMessageBox::warning( parent, windowTitle(), tr( "File \"%1\" already exist. Do you want to overwrite it?" ).arg( fileInfo.filePath() ),
+ QMessageBox::Yes, QMessageBox::No ) == QMessageBox::Yes;
+ break;
+ case OpenDir:
+ if ( !fileInfo.exists() || !fileInfo.isDir() )
+ {
+ QMessageBox::critical( parent, windowTitle(), tr( "Directory \"%1\" does not exist" ).arg( fileInfo.filePath() ),
+ QMessageBox::Ok, QMessageBox::NoButton );
+ ok = false;
+ }
+ break;
+ case SaveDir:
+ if ( fileInfo.exists() && !fileInfo.isDir() )
+ {
+ QMessageBox::critical( parent, windowTitle(), tr( "Directory \"%1\" can't be created because file with the same name exist" ).arg( fileInfo.filePath() ),
+ QMessageBox::Ok, QMessageBox::NoButton );
+ ok = false;
+ }
+ break;
+ case NewDir:
+ if ( fileInfo.exists() )
+ {
+ if ( !fileInfo.isDir() )
{
- const FileEntry& entry = it.data();
- QFileInfo fileInfo( entry.edit->text() );
- if ( entry.edit->text().isEmpty() )
- {
- QMessageBox::critical( parent, caption(), tr( "File name not specified" ),
- QMessageBox::Ok, QMessageBox::NoButton );
- ok = false;
- }
- else switch ( entry.mode )
- {
- case OpenFile:
- if ( !fileInfo.exists() )
- {
- QMessageBox::critical( parent, caption(), tr( "File \"%1\" does not exist" ).arg( fileInfo.filePath() ),
- QMessageBox::Ok, QMessageBox::NoButton );
- ok = false;
- }
- break;
- case SaveFile:
- if ( fileInfo.exists() )
- ok = QMessageBox::warning( parent, caption(), tr( "File \"%1\" already exist. Do you want to overwrite it?" ).arg( fileInfo.filePath() ),
- QMessageBox::Yes, QMessageBox::No ) == QMessageBox::Yes;
- break;
- case OpenDir:
- if ( !fileInfo.exists() || !fileInfo.isDir() )
- {
- QMessageBox::critical( parent, caption(), tr( "Directory \"%1\" does not exist" ).arg( fileInfo.filePath() ),
- QMessageBox::Ok, QMessageBox::NoButton );
- ok = false;
- }
- break;
- case SaveDir:
- if ( fileInfo.exists() && !fileInfo.isDir() )
- {
- QMessageBox::critical( parent, caption(), tr( "Directory \"%1\" can't be created because file with the same name exist" ).arg( fileInfo.filePath() ),
- QMessageBox::Ok, QMessageBox::NoButton );
- ok = false;
- }
- break;
- case NewDir:
- if ( fileInfo.exists() )
- {
- if ( !fileInfo.isDir() )
- {
- QMessageBox::critical( parent, caption(), tr( "Directory \"%1\" can't be created because file with the same name exist" ).arg( fileInfo.filePath() ),
- QMessageBox::Ok, QMessageBox::NoButton );
- ok = false;
- }
- else if ( QDir( fileInfo.filePath() ).count() > 2 )
- ok = QMessageBox::warning( parent, caption(), tr( "Directory \"%1\" not empty. Do you want to remove all files in this directory?" ).arg( fileInfo.filePath() ),
- QMessageBox::Yes, QMessageBox::No ) == QMessageBox::Yes;
- }
- break;
- default:
- break;
- }
-
- if ( !ok )
- entry.edit->setFocus();
+ QMessageBox::critical( parent, windowTitle(), tr( "Directory \"%1\" can't be created because file with the same name exist" ).arg( fileInfo.filePath() ),
+ QMessageBox::Ok, QMessageBox::NoButton );
+ ok = false;
}
-
- return ok;
+ else if ( QDir( fileInfo.filePath() ).count() > 2 )
+ ok = QMessageBox::warning( parent, windowTitle(), tr( "Directory \"%1\" not empty. Do you want to remove all files in this directory?" ).arg( fileInfo.filePath() ),
+ QMessageBox::Yes, QMessageBox::No ) == QMessageBox::Yes;
+ }
+ break;
+ default:
+ break;
+ }
+
+ if ( !ok )
+ entry.edit->setFocus();
+ }
+
+ return ok;
}
/*!
- Some custom activity on file name changing (must be redefined, default implementation is empty
+ \brief Perform custom actions when the file name is changed.
+
+ This method can be redefined in the successor classes.
+ Default implementation does nothing.
+
+ \param id file entry
+ \param fileName file name
*/
-void QtxPathDialog::fileNameChanged( int, QString )
+void QtxPathDialog::fileNameChanged( int /*id*/, QString /*fileName*/ )
{
}
/*!
- \return frame with options
+ \fn void QtxPathDialog::fileNameChanged( QString fileName );
+ \brief Emitted when the file name is changed.
+ \param fileName file name
+*/
+
+/*!
+ \brief Get options grame widget.
+ \return options frame widget
*/
QFrame* QtxPathDialog::optionsFrame()
{
- return myOptionsFrame;
+ return myOptionsFrame;
}
/*!
- \return file name
- \param id - id of file entry
+ \brief Get file name from specified entry.
+ \param id file entry ID
+ \return file name or null string if \a id is invalid
*/
QString QtxPathDialog::fileName( const int id ) const
{
- QString res;
- if ( myEntries.contains( id ) )
- res = myEntries[id].edit->text();
-
- return res;
+ QString res;
+ if ( myEntries.contains( id ) )
+ res = myEntries[id].edit->text();
+ return res;
}
/*!
- Change file name of file entry
- \param id - id of file entry
- \param txt - new file name
- \param autoExt - assign extension automatically
+ \brief Change file name by specified file entry.
+ \param id file entry ID
+ \param txt new file name
+ \param autoExt if \c true, assign extension automatically
*/
void QtxPathDialog::setFileName( const int id, const QString& txt, const bool autoExt )
{
- int mode;
- QLineEdit* le = fileEntry( id, mode );
-
- if ( le )
- {
- if ( autoExt && ( mode == OpenFile || mode == SaveFile ) )
- le->setText( autoExtension( txt ) );
- else
- le->setText( txt );
- }
+ int mode;
+ QLineEdit* le = fileEntry( id, mode );
+
+ if ( le )
+ {
+ if ( autoExt && ( mode == OpenFile || mode == SaveFile ) )
+ le->setText( autoExtension( txt, filter( id ) ) );
+ else
+ le->setText( txt );
+ }
}
/*!
- \return line edit of file entry
- \param id - id of file entry
+ \brief Get file filter from the specified file entry.
+ \param id file entry ID
+ \return file filter or null string if \a id is invalid
*/
-QLineEdit* QtxPathDialog::fileEntry( const int id ) const
+QString QtxPathDialog::filter( const int id ) const
{
- QLineEdit* le = 0;
- if ( myEntries.contains( id ) )
- le = myEntries[id].edit;
-
- return le;
+ QString res;
+ if ( myEntries.contains( id ) )
+ res = myEntries[id].filter;
+ return res;
}
/*!
- \return line edit and mode of file entry
- \param id - id of file entry
- \param theMode - for return mode of file entry
+ \brief Set file filter to the specified file entry.
+ \param id file entry ID
+ \param filter file filter or null string if \a id is invalid
*/
-QLineEdit* QtxPathDialog::fileEntry( const int theId, int& theMode ) const
+void QtxPathDialog::setFilter( const int id, const QString& filter )
{
- QLineEdit* le = 0;
- if ( myEntries.contains( theId ) )
- {
- le = myEntries[theId].edit;
- theMode = myEntries[theId].mode;
- }
-
- return le;
+ if ( myEntries.contains( id ) )
+ myEntries[id].filter = filter;
}
/*!
- Creates file entry
- \return id of just created file entry
- \param lab - title of entry
- \param mode - mode of entry
- \param id - proposed id (if it is -1, then id will be chosen automatically)
+ \brief Get line edit widget for the specified file entry.
+ \param id file entry ID
+ \return line edit widget or 0 if \a id is invalid
*/
-int QtxPathDialog::createFileEntry( const QString& lab, const int mode, const int id )
+QLineEdit* QtxPathDialog::fileEntry( const int id ) const
{
- int num = id;
- if ( num == -1 )
- {
- num--;
- while ( myEntries.contains( num ) )
- num--;
- }
-
- FileEntry entry;
- entry.dlg = 0;
- entry.mode = mode;
+ QLineEdit* le = 0;
+ if ( myEntries.contains( id ) )
+ le = myEntries[id].edit;
+
+ return le;
+}
- new QLabel( lab, myEntriesFrame );
- entry.edit = new QLineEdit( myEntriesFrame );
- entry.btn = new QPushButton( myEntriesFrame );
- entry.btn->setAutoDefault( false );
- entry.btn->setPixmap( QPixmap( open_icon ) );
+/*!
+ \brief Get line edit widget and file mode for the specified file entry.
+ \param id file entry ID
+ \param theMode to return file entry mode
+ \return line edit widget or 0 if \a id is invalid
+*/
+QLineEdit* QtxPathDialog::fileEntry( const int theId, int& theMode ) const
+{
+ QLineEdit* le = 0;
+ if ( myEntries.contains( theId ) )
+ {
+ le = myEntries[theId].edit;
+ theMode = myEntries[theId].mode;
+ }
+
+ return le;
+}
- connect( entry.btn, SIGNAL( clicked() ), this, SLOT( onBrowse() ) );
- connect( entry.edit, SIGNAL( returnPressed() ), this, SLOT( onReturnPressed() ) );
- connect( entry.edit, SIGNAL( textChanged( const QString& ) ), this, SLOT( onTextChanged( const QString& ) ) );
+/*!
+ \brief Create new file entry.
- myEntries.insert( num, entry );
+ If required file entry is already in use or if specified \a id is < 0,
+ new ID is generated and returned.
- return num;
+ \param lab file entry title
+ \param mode file entry mode
+ \param id required file entry ID
+ \return created file entry ID
+*/
+int QtxPathDialog::createFileEntry( const QString& lab, const int mode,
+ const QString& filter, const int id )
+{
+ int num = id;
+ if ( num == -1 )
+ {
+ num--;
+ while ( myEntries.contains( num ) )
+ num--;
+ }
+
+ FileEntry entry;
+ entry.dlg = 0;
+ entry.mode = mode;
+ entry.filter = filter;
+
+ new QLabel( lab, myEntriesFrame );
+ entry.edit = new QLineEdit( myEntriesFrame );
+ entry.btn = new QPushButton( myEntriesFrame );
+ entry.btn->setAutoDefault( false );
+ entry.btn->setIcon( QPixmap( open_icon ) );
+
+ connect( entry.btn, SIGNAL( clicked() ), this, SLOT( onBrowse() ) );
+ connect( entry.edit, SIGNAL( returnPressed() ), this, SLOT( onReturnPressed() ) );
+ connect( entry.edit, SIGNAL( textChanged( const QString& ) ), this, SLOT( onTextChanged( const QString& ) ) );
+
+ myEntries.insert( num, entry );
+
+ return num;
}
/*!
- \return id of default entry
+ \brief Get default file entry ID.
+ \return default entry ID
*/
int QtxPathDialog::defaultEntry() const
{
- return myDefault;
+ return myDefault;
}
/*!
- Change default entry id
- \param id - new default entry id
+ \brief Set default entry.
+ \param id new default entry ID
*/
void QtxPathDialog::setDefaultEntry( const int id )
{
- myDefault = id;
+ myDefault = id;
}
/*!
- Initialize dialog layout
+ \brief Initialize dialog layout.
*/
void QtxPathDialog::initialize()
{
- setCaption( tr( "File dialog" ) );
-
- QVBoxLayout* main = new QVBoxLayout( mainFrame() );
- QtxGroupBox* mainGroup = new QtxGroupBox( 1, Qt::Horizontal, "", mainFrame() );
- mainGroup->setFrameStyle( QFrame::NoFrame );
- mainGroup->setInsideMargin( 0 );
- main->addWidget( mainGroup );
-
- myEntriesFrame = new QGroupBox( 3, Qt::Horizontal, "", mainGroup );
- myOptionsFrame = new QFrame( mainGroup );
+ setWindowTitle( tr( "File dialog" ) );
+
+ QVBoxLayout* main = new QVBoxLayout( mainFrame() );
+ main->setMargin( 0 );
+
+ QtxGroupBox* base = new QtxGroupBox( "", mainFrame() );
+ main->addWidget( base );
+
+ QtxGridBox* mainGroup = new QtxGridBox( 1, Qt::Horizontal, base, 0 );
+ base->setWidget( mainGroup );
+
+ myEntriesFrame = new QtxGridBox( 3, Qt::Horizontal, mainGroup );
+ myOptionsFrame = new QFrame( mainGroup );
}
/*!
- \return list of filters
+ \brief Prepare file filters.
+ \param list of file masks, separated by ';;', for example, "*.h;;*.cxx"
+ \return list of processed file filters
*/
-QStringList QtxPathDialog::prepareFilters() const
+QStringList QtxPathDialog::prepareFilters( const QString& filter ) const
{
- QStringList res;
- if ( !myFilter.isEmpty() )
- {
- res = QStringList::split( ";;", myFilter );
- bool allFilter = false;
- for ( QStringList::ConstIterator it = res.begin(); it != res.end() && !allFilter; ++it )
- {
- QStringList wildCards = filterWildCards( *it );
- allFilter = wildCards.findIndex( "*.*" ) != -1;
- }
-
- if ( !allFilter )
- res.append( tr( "All files (*.*)" ) );
- }
-
- return res;
+ QStringList res;
+ bool allFilter = false;
+ if ( !filter.isEmpty() )
+ {
+ res = filter.split( ";;" );
+ for ( QStringList::ConstIterator it = res.begin(); it != res.end() && !allFilter; ++it )
+ {
+ QStringList wildCards = filterWildCards( *it );
+ allFilter = wildCards.indexOf( "*.*" ) != -1;
+ }
+ }
+
+ if ( !allFilter )
+ res.append( tr( "All files (*.*)" ) );
+
+ return res;
}
/*!
+ \brief Get wildcards from the specified file filter.
+ \param theFilter file filter being processed
\return list of filters with filtered wild cards
*/
QStringList QtxPathDialog::filterWildCards( const QString& theFilter ) const
{
- QStringList res;
-
- int b = theFilter.findRev( "(" );
- int e = theFilter.findRev( ")" );
- if ( b != -1 && e != -1 )
- {
- QString content = theFilter.mid( b + 1, e - b - 1 ).stripWhiteSpace();
- QStringList lst = QStringList::split( " ", content );
- for ( QStringList::ConstIterator it = lst.begin(); it != lst.end(); ++it )
- if ( (*it).find( "." ) != -1 )
- res.append( (*it).stripWhiteSpace() );
- }
- return res;
+ QStringList res;
+
+ int b = theFilter.lastIndexOf( "(" );
+ int e = theFilter.lastIndexOf( ")" );
+ if ( b != -1 && e != -1 )
+ {
+ QString content = theFilter.mid( b + 1, e - b - 1 ).trimmed();
+ QStringList lst = content.split( " " );
+ for ( QStringList::ConstIterator it = lst.begin(); it != lst.end(); ++it )
+ {
+ if ( (*it).indexOf( "." ) != -1 )
+ res.append( (*it).trimmed() );
+ }
+ }
+ return res;
}
/*!
+ \brief Get file file name with automatically assigned extension.
+ \param theFileName file name being processed
+ \param theFilter list of file filters
\return file name with assigned extension
- \param theFileName - source file name
- \param theFilter - list of filters
*/
QString QtxPathDialog::autoExtension( const QString& theFileName, const QString& theFilter ) const
{
- QString fName = theFileName;
-
- if ( fName.isEmpty() )
- return fName;
-
- QString filter = theFilter;
- if ( filter.isEmpty() )
- {
- QStringList filters = prepareFilters();
- if ( !filters.isEmpty() )
- filter = filters.first();
- }
-
- QStringList wildCards = filterWildCards( filter );
- if ( !wildCards.isEmpty() )
- {
- QString ext = wildCards.first();
- if ( ext.find( "." ) != -1 )
- ext = ext.mid( ext.find( "." ) + 1 );
-
- if ( !ext.isEmpty() && !ext.contains( "*" ) )
- fName = QDir::convertSeparators( fName ) + QString( "." ) + ext;
- }
-
- return fName;
+ QString fName = theFileName;
+
+ if ( fName.isEmpty() )
+ return fName;
+
+ QString filter;
+ QStringList filters = prepareFilters( theFilter );
+ if ( !filters.isEmpty() )
+ filter = filters.first();
+
+ QStringList wildCards = filterWildCards( filter );
+ if ( !wildCards.isEmpty() )
+ {
+ QString ext = wildCards.first();
+ if ( ext.indexOf( "." ) != -1 )
+ ext = ext.mid( ext.indexOf( "." ) + 1 );
+
+ if ( !ext.isEmpty() && !ext.contains( "*" ) )
+ fName = QDir::convertSeparators( fName ) + QString( "." ) + ext;
+ }
+
+ return fName;
}
/*!
- \return true if widget has visible children
- \param wid - widget
+ \brief Check if there are visible child widgets.
+ \param wid parent widget being checked
+ \return \c true if widget \a wid has visible children
*/
bool QtxPathDialog::hasVisibleChildren( QWidget* wid ) const
{
- bool res = false;
- if ( wid )
- {
- const QObjectList* aChildren = wid->children();
- if ( aChildren )
- {
- for ( QObjectListIt it( *aChildren ); it.current() && !res; ++it )
- {
- if ( it.current()->isWidgetType() )
- res = ((QWidget*)it.current())->isVisibleTo( wid );
- }
- }
- }
- return res;
+ bool res = false;
+ if ( wid )
+ {
+ const QObjectList& aChildren = wid->children();
+ for ( QObjectList::const_iterator it = aChildren.begin(); it != aChildren.end() && !res; ++it )
+ {
+ if ( (*it)->isWidgetType() )
+ res = ((QWidget*)(*it))->isVisibleTo( wid );
+ }
+ }
+ return res;
+}
+
+/*!
+ \brief Upadte dialof box's child widgets visibility state.
+*/
+void QtxPathDialog::updateVisibility()
+{
+ if ( hasVisibleChildren( myEntriesFrame ) )
+ myEntriesFrame->show();
+ else
+ myEntriesFrame->hide();
+
+ if ( hasVisibleChildren( myOptionsFrame ) )
+ myOptionsFrame->show();
+ else
+ myOptionsFrame->hide();
}
#include "QtxDialog.h"
-#include <qmap.h>
+#include <QMap>
class QFrame;
class QLineEdit;
Q_OBJECT
protected:
- QtxPathDialog( QWidget* = 0, const bool = true, const bool = false, const int = Standard, WFlags = 0 );
+ QtxPathDialog( QWidget* = 0, const bool = true, const bool = false,
+ const int = Standard, Qt::WindowFlags = 0 );
public:
- QtxPathDialog( const bool, QWidget* = 0, const bool = true, const bool = false, const int = Standard, WFlags = 0 );
+ QtxPathDialog( const bool, QWidget* = 0, const bool = true,
+ const bool = false, const int = Standard, Qt::WindowFlags = 0 );
virtual ~QtxPathDialog();
QString fileName() const;
QString filter() const;
void setFilter( const QString& );
- virtual void show();
-
signals:
void fileNameChanged( QString );
+public slots:
+ virtual void setVisible( bool );
+
protected slots:
void validate();
QString fileName( const int ) const;
void setFileName( const int, const QString&, const bool = false );
+ QString filter( const int ) const;
+ void setFilter( const int, const QString& );
+
QLineEdit* fileEntry( const int ) const;
QLineEdit* fileEntry( const int, int& ) const;
- int createFileEntry( const QString&, const int, const int = -1 );
+ int createFileEntry( const QString&, const int,
+ const QString& = QString(), const int = -1 );
int defaultEntry() const;
void setDefaultEntry( const int );
private:
void initialize();
- QStringList prepareFilters() const;
+ void updateVisibility();
+ QStringList prepareFilters( const QString& ) const;
bool hasVisibleChildren( QWidget* ) const;
QStringList filterWildCards( const QString& ) const;
QString autoExtension( const QString&, const QString& = QString::null ) const;
enum { OpenFile, SaveFile, OpenDir, SaveDir, NewDir };
private:
- typedef struct { int mode; QLineEdit* edit;
+ typedef struct { int mode; QLineEdit* edit; QString filter;
QPushButton* btn; QFileDialog* dlg; } FileEntry;
typedef QMap<int, FileEntry> FileEntryMap;
private:
- QString myFilter;
FileEntryMap myEntries;
int myDefault;
- QFrame* myEntriesFrame;
+ QWidget* myEntriesFrame;
QFrame* myOptionsFrame;
};
//
#include "QtxPopupMgr.h"
-#include "QtxListOfOperations.h"
-#include "QtxStdOperations.h"
#include "QtxAction.h"
-
-#include <qpopupmenu.h>
-#include <qdatetime.h>
-
+#include "QtxEvalExpr.h"
+#include <QMenu>
/*!
- \return value of global parameter (depending on whole selection, but not dependending on one object of selection)
- \param str - name of parameter
-
- By default, it returns count of selected objects ("selcount") and list of parameters ("$<name>")
+ \brief Used for comparing of two QVariant values.
+ \param v1 first argument for comparison
+ \param v2 second argument for comparison
+ \return \c true if \a v1 less than \a v2
*/
-QtxValue QtxPopupMgr::Selection::globalParam( const QString& str ) const
+bool operator<( const QVariant& v1, const QVariant& v2 )
{
- if( str==selCountParam() )
- return count();
-
- else if( str[0]==equality() )
+ QVariant::Type t1 = v1.type(), t2 = v2.type();
+ if ( t1 == t2 )
{
- QtxSets::ValueSet set;
- QString par = str.mid( 1 );
-
- for( int i=0, n=count(); i<n; i++ )
+ switch( t1 )
{
- QtxValue v = param( i, par );
- if( v.isValid() )
- QtxSets::add( set, v );
- else
- return QtxValue();
+ case QVariant::Int:
+ return v1.toInt() < v2.toInt();
+ break;
+ case QVariant::Double:
+ return v1.toDouble() < v2.toDouble();
+ break;
+ case QVariant::String:
+ return v1.toString() < v2.toString();
+ break;
+ case QVariant::StringList:
+ case QVariant::List:
+ {
+ const QList<QVariant>& aList1 = v1.toList(), aList2 = v2.toList();
+ QList<QVariant>::const_iterator anIt1 = aList1.begin(), aLast1 = aList1.end(),
+ anIt2 = aList2.begin(), aLast2 = aList2.end();
+ for ( ; anIt1 != aLast1 && anIt2 != aLast2; anIt1++, anIt2++ )
+ {
+ if ( (*anIt1) != (*anIt2) )
+ return (*anIt1)<(*anIt2);
+ }
+ return anIt1 == aLast1 && anIt2 != aLast2;
+ break;
+ }
+ default:
+ return v1.toString() < v2.toString();
+ break;
}
- return set;
}
-
else
- return QtxValue();
-}
-
-/*!
- \return symbole to detect name of parameter list
-*/
-QChar QtxPopupMgr::Selection::equality() const
-{
- return defEquality();
-}
-
-/*!
- \return name of parameter for count of selected objects
-*/
-QString QtxPopupMgr::Selection::selCountParam() const
-{
- return defSelCountParam();
+ return t1 < t2;
}
/*!
- \return default symbole to detect name of parameter list
-*/
-QChar QtxPopupMgr::Selection::defEquality()
-{
- return '$';
-}
+ \class QtxPopupMgr::PopupCreator
+ \internal
+ \brief Popup menu actions creator.
-/*!
- \return default name of parameter for count of selected objects
+ Used by Reader to create actions by reading descriptions from the file
+ and fill in the action manager with the actions.
*/
-QString QtxPopupMgr::Selection::defSelCountParam()
-{
- return "selcount";
-}
-
-
-/*!
- \class QtxCacheSelection
-
- Special selection class, that caches parameter values.
- Every parameter during popup building is calculated only one time,
- although it may be included to many rules. After calculation
- it is stored in internal map
-*/
-
-class QtxCacheSelection : public QtxPopupMgr::Selection
+class QtxPopupMgr::PopupCreator : public QtxActionMgr::Creator
{
public:
- QtxCacheSelection( QtxPopupMgr::Selection* );
- virtual ~QtxCacheSelection();
+ PopupCreator( QtxActionMgr::Reader*, QtxPopupMgr* );
+ virtual ~PopupCreator();
- virtual int count() const;
- virtual QtxValue param( const int, const QString& ) const;
- virtual QtxValue globalParam( const QString& ) const;
+ virtual int append( const QString&, const bool,
+ const ItemAttributes&, const int );
-private:
- typedef QMap< QString, QtxValue > CacheMap;
+ virtual QString rule( const ItemAttributes&,
+ const QtxPopupMgr::RuleType = VisibleRule ) const;
- QtxPopupMgr::Selection* mySel;
- CacheMap myParamCache;
+private:
+ QtxPopupMgr* myMgr;
};
/*!
- Constructor
- \param sel - base selection used for parameter calculation
+ \brief Constructor.
+ \param r menu action reader
+ \param mgr popup menu manager
*/
-QtxCacheSelection::QtxCacheSelection( QtxPopupMgr::Selection* sel )
-: mySel( sel )
+QtxPopupMgr::PopupCreator::PopupCreator( QtxActionMgr::Reader* r,
+ QtxPopupMgr* mgr )
+: QtxActionMgr::Creator( r ),
+ myMgr( mgr )
{
}
/*!
- Destructor
+ \brief Destructor.
*/
-QtxCacheSelection::~QtxCacheSelection()
+QtxPopupMgr::PopupCreator::~PopupCreator()
{
}
/*!
- \return count of selected objects
+ \brief Create and append new action to the action manager.
+ \param tag item tag name
+ \param subMenu \c true if this item is submenu
+ \param attr attributes map
+ \param pId parent action ID
+ \return menu action ID
*/
-int QtxCacheSelection::count() const
+int QtxPopupMgr::PopupCreator::append( const QString& tag, const bool subMenu,
+ const ItemAttributes& attr, const int pId )
{
- return mySel ? mySel->count() : 0;
-}
+ if ( !myMgr || !reader() )
+ return -1;
-/*!
- Calculates and caches parameters.
- Already calculated parameters are returned without calculation
- \return parameter value
- \param i - index of selected object
- \param name - name of parameter
-*/
-QtxValue QtxCacheSelection::param( const int i, const QString& name ) const
-{
- QString param_name = name + "#####" + QString::number( i );
- if( myParamCache.contains( param_name ) )
- return myParamCache[ param_name ];
+ QString label = reader()->option( "label", "label" ),
+ id = reader()->option( "id", "id" ),
+ pos = reader()->option( "pos", "pos" ),
+ group = reader()->option( "group", "group" ),
+ tooltip = reader()->option( "tooltip", "tooltip" ),
+ sep = reader()->option( "separator", "separator" ),
+ accel = reader()->option( "accel", "accel" ),
+ icon = reader()->option( "icon", "icon" ),
+ toggle = reader()->option( "toggle", "toggle" );
+
+ QtxActionMenuMgr* mgr = myMgr;
+
+ int res = -1, actId = intValue( attr, id, -1 );;
+ if ( subMenu )
+ res = mgr->insert( strValue( attr, label ), pId, intValue( attr, group, 0 ), intValue( attr, pos, -1 ) );
+ else if ( tag == sep )
+ res = mgr->insert( separator(), pId, intValue( attr, group, 0 ), intValue( attr, pos, -1 ) );
else
{
- QtxValue v;
- if( mySel )
- v = mySel->param( i, name );
- if( v.isValid() )
- ( ( CacheMap& )myParamCache ).insert( param_name, v );
- return v;
+ QIcon set;
+ QPixmap pix;
+ QString name = strValue( attr, icon );
+ if( !name.isEmpty() )
+ {
+ if ( loadPixmap( name, pix ) )
+ set = QIcon( pix );
+ }
+
+ QString actLabel = strValue( attr, label );
+ QtxAction* newAct = new QtxAction( strValue( attr, tooltip ), set, actLabel,
+ QKeySequence( strValue( attr, accel ) ),
+ myMgr );
+ newAct->setToolTip( strValue( attr, tooltip ) );
+ QString toggleact = strValue( attr, toggle );
+ bool isToggle = !toggleact.isEmpty();
+ newAct->setCheckable( isToggle );
+ newAct->setChecked( toggleact.toLower() == "true" );
+
+ connect( newAct );
+ int aid = mgr->registerAction( newAct, actId );
+ QString arule = rule( attr, QtxPopupMgr::VisibleRule );
+ if ( !arule.isEmpty() )
+ myMgr->setRule( newAct, arule, QtxPopupMgr::VisibleRule );
+ arule = rule( attr, QtxPopupMgr::EnableRule );
+ if ( !arule.isEmpty() )
+ myMgr->setRule( newAct, arule, QtxPopupMgr::EnableRule );
+ arule = rule( attr, QtxPopupMgr::ToggleRule );
+ if ( isToggle && !arule.isEmpty() )
+ myMgr->setRule( newAct, arule, QtxPopupMgr::ToggleRule );
+ res = mgr->insert( aid, pId, intValue( attr, group, 0 ), intValue( attr, pos, -1 ) );
}
+
+ return res;
}
/*!
- Calculates and caches global parameters.
- Already calculated parameters are returned without calculation
- \return parameter value
- \param name - name of parameter
+ \brief Get the rule for the menu item.
+
+ Default implementation returns empty rule.
+
+ \param attr attributes map
+ \param ruleType rule type (QtxPopupMgr::RuleType)
+ \return rule for the menu item corresponding to the rule type
*/
-QtxValue QtxCacheSelection::globalParam( const QString& name ) const
+QString QtxPopupMgr::PopupCreator::rule( const ItemAttributes& /*attr*/,
+ const QtxPopupMgr::RuleType /*ruleType*/ ) const
{
- if( myParamCache.contains( name ) )
- return myParamCache[ name ];
- else
- {
- QtxValue v;
- if( mySel )
- v = mySel->globalParam( name );
- if( v.isValid() )
- ( ( CacheMap& )myParamCache ).insert( name, v );
- return v;
- }
+ return QString();
}
+/*!
+ \class QtxPopupMgr
+ \brief Popup menu manager.
+ Menu manager allows using of set of action for automatic generating of
+ application context popup menu by reuquest and dynamic update of its
+ contents.
+ Use insert() methods to add menu items to the popup menu.
-/*!
- Constructor
- \param mgr - popup manager
-*/
-QtxPopupMgr::Operations::Operations( QtxPopupMgr* mgr )
-: QtxStrings(),
- myPopupMgr( mgr )
-{
- QStringList aList;
- aList.append( "every" );
- aList.append( "any" );
- aList.append( "onlyone" );
- addOperations( aList );
+ The visibility, enable and toggle state of the menu item is controlled
+ by the syntaxic rules, which can be set with setRule() methods.
+ The rules are parsed automatically with help of QtxEvalParser class.
- myParser = new QtxParser( mgr->myOperations );
-}
+ QtxPopupSelection class is used as back-end for getting value of each
+ parameter found in the rule by the expression parser.
+ Use setSelection() and selection() to set/get the selection instance
+ for the popup menu manager.
+
+ Popup menu manager automatically optimizes the menu by removing
+ extra separators, hiding empty popup submenus etc.
+*/
/*!
- Destructor
- Deletes internal parser
+ \brief Constructor.
+ \param object parent object
*/
-QtxPopupMgr::Operations::~Operations()
+QtxPopupMgr::QtxPopupMgr( QObject* parent )
+: QtxActionMenuMgr( 0, parent ),
+ mySelection( 0 )
{
- delete myParser;
}
/*!
- \return priority of popup operation 'op'.
- \param isBin indicate whether the operation is binary
+ \brief Constructor.
+ \param popup popup menu
+ \param object parent object
*/
-int QtxPopupMgr::Operations::prior( const QString& op, bool isBin ) const
+QtxPopupMgr::QtxPopupMgr( QMenu* popup, QObject* parent )
+: QtxActionMenuMgr( popup, parent ),
+ mySelection( 0 )
{
- if( !isBin && ( op=="every" || op=="any" || op=="onlyone" ) )
- return 1;
- else
- return QtxStrings::prior( op, isBin );
-
}
/*!
- Calculates result of operation
- \return one of error states
- \param op - name of operation
- \param v1 - first operation argument (must be used also to store result)
- \param v2 - second operation argument
+ \brief Destructor.
*/
-QtxParser::Error QtxPopupMgr::Operations::calculate
- ( const QString& op, QtxValue& v1, QtxValue& v2 ) const
+QtxPopupMgr::~QtxPopupMgr()
{
- int ind = -1;
- if( op=="every" )
- ind = 0;
- else if( op=="any" )
- ind = 1;
- else if( op=="onlyone" )
- ind = 2;
-
- if( ind>=0 && ind<=2 )
- {
- QString val_name = op + "(" + v2.toString() + ")";
- QtxParser::Error err = QtxParser::OK;
-
- if( !myValues.contains( val_name ) )
- {
- myParser->setExpr( v2.toString() );
- QStringList params, specific;
- myParser->paramsList( params );
-
- myParser->clear();
- myPopupMgr->setParams( myParser, specific );
-
- QtxPopupMgr::Selection* sel = myPopupMgr->myCurrentSelection;
-
- int global_result = 0;
- if( sel )
- for( int i=0, n=sel->count(); i<n; i++ )
- {
- QStringList::const_iterator anIt = specific.begin(),
- aLast = specific.end();
- for( ; anIt!=aLast; anIt++ )
- {
- QtxValue v = sel->param( i, *anIt );
- if( v.isValid() )
- myParser->set( *anIt, v );
- else
- return QtxParser::InvalidToken;
- }
-
- QtxValue res = myParser->calculate();
- err = myParser->lastError();
- if( err==QtxParser::OK )
- if( res.type()==QVariant::Bool )
- {
- if( res.toBool() )
- global_result++;
- if( ind==2 && global_result>1 )
- break;
- }
- else
- return QtxParser::InvalidResult;
- else
- return err;
- }
-
- QtxValue& vv = ( QtxValue& )myValues[ val_name ];
- vv = ( ind==0 && global_result==sel->count() ) ||
- ( ind==1 ) ||
- ( ind==2 && global_result==1 );
- }
-
- v2 = myValues[ val_name ];
-
- return err;
- }
- else
- return QtxStrings::calculate( op, v1, v2 );
}
/*!
- Clears internal map of values
+ \brief Get popup menu.
+ \return popup menu
*/
-void QtxPopupMgr::Operations::clear()
+QMenu* QtxPopupMgr::menu() const
{
- myValues.clear();
+ return ::qobject_cast<QMenu*>( menuWidget() );
}
-
-
-
-
-
-
-
/*!
- Constructor
+ \brief Get popup menu.
+ \param menu popup menu
*/
-QtxPopupMgr::QtxPopupMgr( QPopupMenu* popup, QObject* parent )
-: QtxActionMenuMgr( popup, parent ),
- myCurrentSelection( 0 )
+void QtxPopupMgr::setMenu( QMenu* menu )
{
- createOperations();
+ setMenuWidget( menu );
}
/*!
- Destructor
+ \brief Get selection.
+ \return current selection object
*/
-QtxPopupMgr::~QtxPopupMgr()
+QtxPopupSelection* QtxPopupMgr::selection() const
{
+ return mySelection;
}
/*!
- Creates popup operations instance
+ \brief Set selection.
+ \param sel new selection object
*/
-void QtxPopupMgr::createOperations()
+void QtxPopupMgr::setSelection( QtxPopupSelection* sel )
{
- myOperations = new QtxListOfOperations;
- myOperations->prepend( "logic", new QtxLogic(), 0 );
- myOperations->prepend( "arithm", new QtxArithmetics(), 50 );
- myOperations->append( "strings", new QtxStrings(), 100 );
- myOperations->append( "sets", new QtxSets(), 150 );
- myOperations->append( "custom", new Operations( this ), 200 );
+ if ( mySelection == sel )
+ return;
+
+ delete mySelection;
+
+ mySelection = sel;
+
+ if ( mySelection )
+ mySelection->setParent( this );
+
+ QtxActionMgr::triggerUpdate();
}
/*!
- Additional version of registerAction
- \param act - action to be registered
- \param visible - rule for visibility state
- \param toggle - rule for toggle on state
- \param id - proposed id (if it is less than 0, then id will be generated automatically)
+ \brief Register an action and return its identifier.
+
+ If \a id is less than 0, the identifier for the action is generated automatically.
+ If action with given \a id is already registered, it will be re-registered.
+ If required \a id is already in use, new identifier is generatied; in this case
+ returning value will different from required one.
+
+ \param act action to be registered
+ \param id action ID
+ \param rule syntax rule
+ \param ruleType rule type (QtxPopupMgr::RuleType)
+ \return action ID (the same as \a id or generated one)
*/
-int QtxPopupMgr::registerAction( QAction* act,
- const QString& visible,
- const QString& toggle,
- const int id )
+int QtxPopupMgr::registerAction( QAction* act, const int id, const QString& rule, const QtxPopupMgr::RuleType ruleType )
{
- int _id = QtxActionMenuMgr::registerAction( act, id );
- setRule( _id, visible, true );
- setRule( _id, toggle, false );
- return _id;
+ int _id = QtxActionMenuMgr::registerAction( act, id );
+ setRule( act, rule, ruleType );
+ return _id;
}
/*!
- Removes action from internal map
- \param id - action id
+ \brief Unregister action from internal map.
+ \param id action ID
*/
void QtxPopupMgr::unRegisterAction( const int id )
{
- QAction* act = action( id );
+ QAction* a = action( id );
+ if ( myRules.contains( a ) )
+ {
+ for ( ExprMap::iterator it = myRules[a].begin(); it != myRules[a].end(); ++it )
+ delete it.value();
+ }
+ myRules.remove( a );
- myVisibility.remove( act );
- myToggle.remove( act );
+ remove( id );
- remove( id );
- //QtxActionMenuMgr::unRegisterAction( id );
+ QtxActionMenuMgr::unRegisterAction( id );
}
/*!
- \return true if manager has rule for action
- \param act - action
- \param visibility - if it is true, then rule for "visibility" is checked, otherwise - for "toggle"
+ \brief Insert action to the popup menu manager.
+ \param id action ID
+ \param pId parent menu action ID
+ \param rule syntax rule
+ \param ruleType rule type (QtxPopupMgr::RuleType)
+ \return action ID
*/
-bool QtxPopupMgr::hasRule( QAction* act, bool visibility ) const
+int QtxPopupMgr::insert( const int id, const int pId, const QString& rule, const RuleType ruleType )
{
- return map( visibility ).contains( act );
+ int res = QtxActionMenuMgr::insert( id, pId, -1 );
+ setRule( action( id ), rule, ruleType );
+ return res;
}
/*!
- \return true if manager has rule for action
- \param id - action id
- \param visibility - if it is true, then rule for "visibility" is checked, otherwise - for "toggle"
+ \brief Insert action to the popup menu manager.
+ \param a action
+ \param pId parent menu action ID
+ \param rule syntax rule
+ \param ruleType rule type (QtxPopupMgr::RuleType)
+ \return action ID
*/
-bool QtxPopupMgr::hasRule( const int id, bool visibility ) const
+int QtxPopupMgr::insert( QAction* a, const int pId, const QString& rule, const RuleType ruleType )
{
- return hasRule( action( id ), visibility );
+ int res = QtxActionMenuMgr::insert( a, pId, -1 );
+ setRule( a, rule, ruleType );
+ return res;
}
/*!
- Sets new rule for action
- \param act - action
- \param rule - string expression of rule
- \param visibility - if it is true, then rule for "visibility" will be set, otherwise - for "toggle"
+ \brief Get rule of type \a type for the action \a a.
+ \param a action
+ \param ruleType rule type (QtxPopupMgr::RuleType)
+ \return rule of required type
*/
-void QtxPopupMgr::setRule( QAction* act, const QString& rule, bool visibility )
+QString QtxPopupMgr::rule( QAction* a, const RuleType ruleType ) const
{
- if( !act || rule.isEmpty() )
- return;
-
- if( !hasRule( act, visibility ) )
- {
- QtxParser* p = new QtxParser( myOperations, rule );
- if( p->lastError()==QtxParser::OK )
- map( visibility ).insert( act, p );
- else
- delete p;
- }
- else
- {
- QtxParser* p = map( visibility )[ act ];
- p->setExpr( rule );
- if( p->lastError()!=QtxParser::OK )
- p->setExpr( QString() );
- }
+ QString rule;
+ QtxEvalExpr* expr = expression( a, ruleType );
+ if ( expr )
+ rule = expr->expression();
+ return rule;
}
/*!
- Sets new rule for action
- \param id - action id
- \param rule - string expression of rule
- \param visibility - if it is true, then rule for "visibility" will be set, otherwise - for "toggle"
+ \brief Get rule of type \a type for the action \a id.
+ \param id action ID
+ \param ruleType rule type (QtxPopupMgr::RuleType)
+ \return rule of required type
*/
-void QtxPopupMgr::setRule( const int id, const QString& rule, bool visibility )
+QString QtxPopupMgr::rule( const int id, const RuleType ruleType ) const
{
- setRule( action( id ), rule, visibility );
+ return rule( action( id ), ruleType );
}
/*!
- \return true if parser has finished work without errors
- \param p - parser
+ \brief Set rule of type \a type for the action \a a.
+ \param a action
+ \param rule rule
+ \param ruleType rule type (QtxPopupMgr::RuleType)
+ \return rule of required type
*/
-bool result( QtxParser* p )
+void QtxPopupMgr::setRule( QAction* a, const QString& rule, const RuleType ruleType )
{
- bool res = false;
- if( p )
- {
- QtxValue vv = p->calculate();
- res = p->lastError()==QtxParser::OK &&
- ( ( vv.type()==QVariant::Int && vv.toInt()!=0 ) ||
- ( vv.type()==QVariant::Bool && vv.toBool() ) );
- }
- return res;
+ if ( !a )
+ return;
+
+ QtxEvalExpr* expr = expression( a, ruleType, true );
+
+ expr->setExpression( rule );
}
/*!
- Fills parser parameters with help of Selection::globalParam() method
- \param p - parser
- \param specific - list will be filled with names of parameters depending on selection objects (not global)
+ \brief Set rule of type \a type for the action \a id.
+ \param id action ID
+ \param rule rule
+ \param ruleType rule type (QtxPopupMgr::RuleType)
+ \return rule of required type
*/
-void QtxPopupMgr::setParams( QtxParser* p, QStringList& specific ) const
+void QtxPopupMgr::setRule( const int id, const QString& rule, const RuleType ruleType )
{
- if( !p || !myCurrentSelection )
- return;
-
- QStringList params;
-
- p->paramsList( params );
- QStringList::const_iterator anIt = params.begin(),
- aLast = params.end();
- for( ; anIt!=aLast; anIt++ )
- {
- QtxValue v = myCurrentSelection->globalParam( *anIt );
- if( v.isValid() )
- p->set( *anIt, v );
- else
- specific.append( *anIt );
- }
+ setRule( action( id ), rule, ruleType );
}
/*!
- \return true if 'v1'<'v2'
- This function can work with many types of values
+ \brief Calculate an expression.
+ \param p expression parser
+ \return \c true if parser has finished work without errors
*/
-bool operator<( const QtxValue& v1, const QtxValue& v2 )
+bool QtxPopupMgr::result( QtxEvalParser* p ) const
{
- QVariant::Type t1 = v1.type(), t2 = v2.type();
- if( t1==t2 )
+ bool res = false;
+ if ( p )
{
- switch( t1 )
- {
- case QVariant::Int:
- return v1.toInt() < v2.toInt();
-
- case QVariant::Double:
- return v1.toDouble() < v2.toDouble();
-
- case QVariant::CString:
- case QVariant::String:
- return v1.toString() < v2.toString();
+ QVariant vv = p->calculate();
+ res = p->error() == QtxEvalExpr::OK &&
+ ( ( vv.type() == QVariant::Int && vv.toInt() != 0 ) ||
+ ( vv.type() == QVariant::Bool && vv.toBool() ) );
+ }
+ return res;
+}
- case QVariant::StringList:
- case QVariant::List:
- {
- const QValueList<QtxValue>& aList1 = v1.toList(), aList2 = v2.toList();
- QValueList<QtxValue>::const_iterator
- anIt1 = aList1.begin(), aLast1 = aList1.end(),
- anIt2 = aList2.begin(), aLast2 = aList2.end();
- for( ; anIt1!=aLast1 && anIt2!=aLast2; anIt1++, anIt2++ )
- if( (*anIt1)!=(*anIt2) )
- return (*anIt1)<(*anIt2);
+/*!
+ \brief Fill the parser with parameters of the expression.
- return anIt1==aLast1 && anIt2!=aLast2;
- }
+ The values of the parameters are given from the selection object
+ (QtxPopupSelection).
+
+ \param p expression parser
+ \param returning list of parameters names which are not retrieved from the selection
+ \sa selection()
+*/
+void QtxPopupMgr::setParameters( QtxEvalParser* p, QStringList& specific ) const
+{
+ if ( !p || !mySelection )
+ return;
- default:
- return v1.toString()<v2.toString();
- }
+ QStringList params = p->parameters();
+ for ( QStringList::const_iterator it = params.begin(); it != params.end(); ++it )
+ {
+ QVariant v = parameter( *it );
+ if ( v.isValid() )
+ p->setParameter( *it, v );
+ else
+ specific.append( *it );
}
- else
- return t1<t2;
}
/*!
- \return true if rule of action is satisfied on current selection
- \param act - action
- \param visibility - what rule is checked: for visibility(true) or for toggle(false)
+ \brief Check the rule for the action.
+ \param act action
+ \param ruleType rule type (QtxPopupMgr::RuleType)
+ \return \c true if current selection satisfies the action rule
*/
-bool QtxPopupMgr::isSatisfied( QAction* act, bool visibility ) const
+bool QtxPopupMgr::isSatisfied( QAction* act, const RuleType ruleType ) const
{
- QString menu = act->menuText();
+ if ( !act )
+ return false;
- bool res = false;
- if( !act )
- return res;
+ QtxEvalExpr* exp = expression( act, ruleType );
+ if ( !exp )
+ return true;
- if( hasRule( act, visibility ) )
- {
- QtxParser* p = map( visibility )[ act ];
- QStringList specific;
- p->clear();
- ( ( Operations* )myOperations->operations( "custom" ) )->clear();
+ bool res = false;
- setParams( p, specific );
+ QtxEvalParser* p = exp->parser();
- QMap<QValueList<QtxValue>,int> aCorteges;
- QValueList<QtxValue> c;
+ QStringList specific;
+ p->clearParameters();
+ setParameters( p, specific );
- if( specific.count()>0 )
- if( myCurrentSelection )
+ QMap<QList<QVariant>, int> aCorteges;
+ if ( !specific.isEmpty() )
+ {
+ if ( mySelection )
+ {
+ res = false;
+ for ( int i = 0; i < mySelection->count() && !res; i++ )
{
- res = false;
-
- for( int i=0, n=myCurrentSelection->count(); i<n && !res; i++ )
- {
- QStringList::const_iterator anIt1 = specific.begin(), aLast1 = specific.end();
- c.clear();
- for( ; anIt1!=aLast1; anIt1++ )
- c.append( myCurrentSelection->param( i, *anIt1 ) );
- aCorteges.insert( c, 0 );
- }
-
- //qDebug( QString( "%1 corteges" ).arg( aCorteges.count() ) );
- QMap<QValueList<QtxValue>,int>::const_iterator anIt = aCorteges.begin(), aLast = aCorteges.end();
- for( ; anIt!=aLast; anIt++ )
- {
- QStringList::const_iterator anIt1 = specific.begin(), aLast1 = specific.end();
- const QValueList<QtxValue>& aCortege = anIt.key();
- QValueList<QtxValue>::const_iterator anIt2 = aCortege.begin();
- for( ; anIt1!=aLast1; anIt1++, anIt2++ )
- p->set( *anIt1, *anIt2 );
- res = res || result( p );
- }
-
- /*
- for( int i=0, n=myCurrentSelection->count(); i<n && !res; i++ )
- {
- QStringList::const_iterator anIt1 = specific.begin(), aLast1 = specific.end();
- for( ; anIt1!=aLast1; anIt1++ )
- p->set( *anIt1, myCurrentSelection->param( i, *anIt1 ) );
- res = res || result( p );
- }*/
+ QList<QVariant> c;
+ for ( QStringList::const_iterator anIt1 = specific.begin(); anIt1 != specific.end(); ++anIt1 )
+ c.append( parameter( *anIt1, i ) );
+ aCorteges.insert( c, 0 );
}
- else
- res = false;
+ for ( QMap<QList<QVariant>, int>::const_iterator anIt = aCorteges.begin(); anIt != aCorteges.end(); ++anIt )
+ {
+ const QList<QVariant>& aCortege = anIt.key();
+ QStringList::const_iterator anIt1 = specific.begin(), aLast1 = specific.end();
+ QList<QVariant>::const_iterator anIt2 = aCortege.begin();
+ for ( ; anIt1 != aLast1; anIt1++, anIt2++ )
+ p->setParameter( *anIt1, *anIt2 );
+ res = res || result( p );
+ }
+ }
else
- res = result( p );
+ res = false;
}
+ else
+ res = result( p );
return res;
}
/*!
- \return true if item corresponding to action is visible
- \param actId - action id
- \param place - index of place
+ \brief Check if the menu item is visible.
+ \param id action ID
+ \param place some parent action ID
+ \return \c true if the action is visible
*/
-bool QtxPopupMgr::isVisible( const int actId, const int place ) const
+bool QtxPopupMgr::isVisible( const int id, const int place ) const
{
- bool res = QtxActionMenuMgr::isVisible( actId, place );
- QAction* act = action( actId );
- if( hasRule( act, true ) )
- res = res && isSatisfied( act, true );
- return res;
+ return QtxActionMenuMgr::isVisible( id, place ) && isSatisfied( action( id ) );
}
/*!
- Updates popup according to selection
- \param p - popup menu
- \param sel - selection
+ \brief Perform internal update of the popup menu according
+ to the current selection.
*/
-void QtxPopupMgr::updatePopup( QPopupMenu* p, Selection* sel )
+void QtxPopupMgr::internalUpdate()
{
- QTime t1 = QTime::currentTime();
+ myCache.clear();
- if( !p || !sel )
- return;
+ for ( RuleMap::iterator it = myRules.begin(); it != myRules.end(); ++it )
+ {
+ ExprMap& map = it.value();
+ if ( it.key()->isCheckable() && map.contains( ToggleRule ) &&
+ !map[ToggleRule]->expression().isEmpty() )
+ it.key()->setChecked( isSatisfied( it.key(), ToggleRule ) );
+ }
- myCurrentSelection = new QtxCacheSelection( sel );
- RulesMap::iterator anIt = myToggle.begin(),
- aLast = myToggle.end();
- for( ; anIt!=aLast; anIt++ )
- if( anIt.key()->isToggleAction() && hasRule( anIt.key(), false ) )
- anIt.key()->setOn( isSatisfied( anIt.key(), false ) );
+ QtxActionMenuMgr::internalUpdate();
- setWidget( ( QWidget* )p );
- updateMenu();
- QTime t2 = QTime::currentTime();
- qDebug( QString( "update popup time = %1 msecs" ).arg( t1.msecsTo( t2 ) ) );
- qDebug( QString( "number of objects = %1" ).arg( myCurrentSelection->count() ) );
+ myCache.clear();
+}
- delete myCurrentSelection;
+/*!
+ \brief Update popup according to the current selection.
+*/
+void QtxPopupMgr::updateMenu()
+{
+ internalUpdate();
}
/*!
- \return reference to map of rules
- \param visibility - type of map: visibility of toggle
+ \brief Get an syntax expression for the action according to the specified rule type.
+ \param a action
+ \param ruleType rule type (QtxPopupMgr::RuleType)
+ \param create if \c true an expression does not exist, create it
+ \return syntax expression
*/
-QtxPopupMgr::RulesMap& QtxPopupMgr::map( bool visibility ) const
+QtxEvalExpr* QtxPopupMgr::expression( QAction* a, const RuleType ruleType, const bool create ) const
{
- return ( RulesMap& )( visibility ? myVisibility : myToggle );
+ QtxEvalExpr* res = 0;
+
+ QtxPopupMgr* that = (QtxPopupMgr*)this;
+ RuleMap& ruleMap = that->myRules;
+ if ( !ruleMap.contains( a ) && create )
+ ruleMap.insert( a, ExprMap() );
+
+ if ( ruleMap.contains( a ) )
+ {
+ ExprMap& exprMap = ruleMap[a];
+ if ( exprMap.contains( ruleType ) )
+ res = exprMap[ruleType];
+ else if ( create )
+ exprMap.insert( ruleType, res = new QtxEvalExpr() );
+ }
+
+ return res;
}
/*!
- Loads actions description from file
- \param fname - name of file
- \param r - reader of file
- \return true on success
+ \brief Load actions description from the file.
+ \param fname file name
+ \param r action reader
+ \return \c true on success and \c false on error
*/
bool QtxPopupMgr::load( const QString& fname, QtxActionMgr::Reader& r )
{
return r.read( fname, cr );
}
+/*
+ \brief Get the specified parameter value.
+ \param name parameter name
+ \param idx additional index used when used parameters with same names
+ \return parameter value
+ \sa selection()
+*/
+QVariant QtxPopupMgr::parameter( const QString& name, const int idx ) const
+{
+ QVariant val;
+ QString cacheName = name + ( idx >= 0 ? QString( "_%1" ).arg( idx ) : QString() );
+ if ( myCache.contains( cacheName ) )
+ val = myCache[cacheName];
+ else
+ {
+ if ( selection() )
+ val = idx < 0 ? selection()->parameter( name ) :
+ selection()->parameter( idx, name );
+ if ( val.isValid() )
+ {
+ QtxPopupMgr* that = (QtxPopupMgr*)this;
+ that->myCache.insert( cacheName, val );
+ }
+ }
+ return val;
+}
+/*!
+ \class QtxPopupSelection
+ \brief This class is a part of the popup menu management system.
+ The QtxPopupSelection class is used as back-end for getting value
+ of each parameter found in the rule by the expression parser.
+
+ For example, it can be used for the analyzing of the currently
+ selected objects and defining the values of the parameters used
+ in the rules syntax expression. Rules, in their turn, define
+ each action state - visibility, enabled and toggled state.
+*/
/*!
- Constructor
- \param r - menu reader
- \param mgr - menu manager
+ \brief Constructor.
*/
-QtxPopupMgr::PopupCreator::PopupCreator( QtxActionMgr::Reader* r,
- QtxPopupMgr* mgr )
-: QtxActionMgr::Creator( r ),
- myMgr( mgr )
+QtxPopupSelection::QtxPopupSelection()
+: QObject( 0 )
{
}
/*!
- Destructor
-*/QtxPopupMgr::PopupCreator::~PopupCreator()
+ \brief Destructor.
+*/
+QtxPopupSelection::~QtxPopupSelection()
{
}
-
/*!
- Appends new menu items
- \param tag - tag of item
- \param subMenu - it has submenu
- \param attr - list of attributes
- \param pId - id of action corresponding to parent item
+ \brief Get an option value.
+ \param optName option name
+ \return option value or empty string if option is not found
*/
-int QtxPopupMgr::PopupCreator::append( const QString& tag, const bool subMenu,
- const ItemAttributes& attr, const int pId )
+QString QtxPopupSelection::option( const QString& optName ) const
{
- if( !myMgr || !reader() )
- return -1;
+ QString opt;
+ if ( myOptions.contains( optName ) )
+ opt = myOptions[optName];
+ return opt;
+}
- QString label = reader()->option( "label", "label" ),
- id = reader()->option( "id", "id" ),
- pos = reader()->option( "pos", "pos" ),
- group = reader()->option( "group", "group" ),
- tooltip = reader()->option( "tooltip", "tooltip" ),
- sep = reader()->option( "separator", "separator" ),
- accel = reader()->option( "accel", "accel" ),
- icon = reader()->option( "icon", "icon" ),
- toggle = reader()->option( "toggle", "toggle" );
+/*!
+ \brief Set an option value.
+ \param optName option name
+ \param opt option value
+*/
+void QtxPopupSelection::setOption( const QString& optName, const QString& opt )
+{
+ myOptions.insert( optName, opt );
+}
- int res = -1, actId = intValue( attr, id, -1 );;
- if( subMenu )
- res = myMgr->insert( strValue( attr, label ), pId, intValue( attr, group, 0 ), intValue( attr, pos, -1 ) );
- else if( tag==sep )
- res = myMgr->insert( separator(), pId, intValue( attr, group, 0 ), intValue( attr, pos, -1 ) );
- else //if( !myMgr->contains( actId ) )
+/*!
+ \brief Get the parameter value.
+ \param str parameter name
+ \return parameter value
+*/
+QVariant QtxPopupSelection::parameter( const QString& str ) const
+{
+ if ( str == selCountParam() )
+ return count();
+ else if ( str.startsWith( equalityParam() ) )
{
- QPixmap pix; QIconSet set;
- QString name = strValue( attr, icon );
- if( !name.isEmpty() )
+ QtxEvalSetSets::ValueSet set;
+ QString par = str.mid( equalityParam().length() );
+ for ( int i = 0; i < (int)count(); i++ )
{
- if( loadPixmap( name, pix ) )
- set = QIconSet( pix );
+ QVariant v = parameter( i, par );
+ if ( v.isValid() )
+ QtxEvalSetSets::add( set, v );
+ else
+ return QVariant();
}
-
- QString actLabel = strValue( attr, label );
- QtxAction* newAct = new QtxAction( strValue( attr, tooltip ), set, actLabel,
- QKeySequence( strValue( attr, accel ) ),
- myMgr );
- newAct->setToolTip( strValue( attr, tooltip ) );
- QString toggleact = strValue( attr, toggle );
- bool isToggle = !toggleact.isEmpty();
- newAct->setToggleAction( isToggle );
- newAct->setOn( toggleact.lower()=="true" );
-
- connect( newAct );
- int aid = myMgr->registerAction( newAct, visibleRule( attr ),
- isToggle ? toggleRule( attr ) : QString::null,
- actId );
- res = myMgr->insert( aid, pId, intValue( attr, group, 0 ), intValue( attr, pos, -1 ) );
+ return set;
}
-
- return res;
+ else
+ return QVariant();
}
/*!
- \return visibility rule by attributes
- Default implementation is empty
+ \brief Get symbol which detects the name of the parameter list.
+ \return equality symbol (by default, "$")
*/
-QString QtxPopupMgr::PopupCreator::visibleRule( const ItemAttributes& ) const
+QString QtxPopupSelection::equalityParam() const
{
- return QString::null;
+ QString str = option( "equality" );
+ if ( str.isEmpty() )
+ str = "$";
+ return str;
}
/*!
- \return toggle rule by attributes
- Default implementation is empty
+ \brief Get name of the parameter, specifing number of selected objects
+ \return parameter name (by default, "selcount")
*/
-QString QtxPopupMgr::PopupCreator::toggleRule( const ItemAttributes& ) const
+QString QtxPopupSelection::selCountParam() const
{
- return QString::null;
+ QString str = option( "equality" );
+ if ( str.isEmpty() )
+ str = "selcount";
+ return str;
}
+
+/*!
+ \fn int QtxPopupSelection::count() const;
+ \brief Get number of the selected objects.
+ \return nb of selected objects
+*/
+
+/*!
+ \fn QVariant QtxPopupSelection::parameter( const int idx, const QString& name ) const;
+ \brief Get number of the selected objects.
+ \param idx parameter index
+ \param name parameter name
+ \return parameter value
+*/
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-#ifndef __QTX_POPUP_MGR_HEADER__
-#define __QTX_POPUP_MGR_HEADER__
+#ifndef QTXPOPUPMGR_H
+#define QTXPOPUPMGR_H
-#include "Qtx.h"
#include "QtxActionMenuMgr.h"
-#include "QtxParser.h"
-#include "QtxStdOperations.h"
-#include <qmap.h>
+#include <QMap>
+#include <QVariant>
-class QtxListOfOperations;
+class QtxEvalExpr;
+class QtxEvalParser;
+class QtxPopupSelection;
class QTX_EXPORT QtxPopupMgr : public QtxActionMenuMgr
{
- Q_OBJECT
+ Q_OBJECT
public:
- class QTX_EXPORT Selection
- {
- public:
- virtual int count() const = 0;
- virtual QtxValue param( const int, const QString& ) const = 0;
- virtual QtxValue globalParam( const QString& ) const;
+ //! Menu item rule type
+ typedef enum {
+ VisibleRule, //!< menu item visibility state
+ EnableRule, //!< menu item enable state
+ ToggleRule //!< menu item toggle state
+ } RuleType;
- virtual QChar equality() const;
- virtual QString selCountParam() const;
-
- static QChar defEquality();
- static QString defSelCountParam();
- };
-
-protected:
- class Operations : public QtxStrings
- {
- public:
- Operations( QtxPopupMgr* );
- virtual ~Operations();
-
- virtual int prior( const QString&, bool isBin ) const;
- virtual QtxParser::Error calculate( const QString&, QtxValue&, QtxValue& ) const;
+private:
+ class PopupCreator;
- void clear();
+public:
+ QtxPopupMgr( QObject* = 0 );
+ QtxPopupMgr( QMenu*, QObject* = 0 );
+ virtual ~QtxPopupMgr();
- private:
- QtxPopupMgr* myPopupMgr;
- QtxParser* myParser;
- QMap< QString, QtxValue > myValues;
- };
+ int insert( const int, const int, const QString&, const RuleType = VisibleRule );
+ int insert( QAction*, const int, const QString&, const RuleType = VisibleRule );
- friend class Operations;
+ virtual int registerAction( QAction*, const int, const QString& rule,
+ const RuleType = VisibleRule );
+ virtual void unRegisterAction( const int );
-protected:
- class PopupCreator;
+ virtual bool isVisible( const int actId, const int place ) const;
-public:
- QtxPopupMgr( QPopupMenu*, QObject* = 0 );
- virtual ~QtxPopupMgr();
+ QString rule( QAction*, const RuleType = VisibleRule ) const;
+ QString rule( const int, const RuleType = VisibleRule ) const;
- virtual int registerAction( QAction*,
- const QString& visible,
- const QString& toggle = QString::null,
- const int = -1 );
- virtual void unRegisterAction( const int );
+ void setRule( QAction*, const QString&, const RuleType = VisibleRule );
+ void setRule( const int, const QString&, const RuleType = VisibleRule );
- virtual bool isVisible( const int actId, const int place ) const;
+ QtxPopupSelection* selection() const;
+ void setSelection( QtxPopupSelection* );
- bool hasRule( QAction*, bool visibility ) const;
- bool hasRule( const int, bool visibility ) const;
- void setRule( QAction*, const QString&, bool visibility );
- void setRule( const int, const QString&, bool visibility );
- void updatePopup( QPopupMenu*, Selection* );
+ QMenu* menu() const;
+ void setMenu( QMenu* );
- //return name of parameter corresponding to selected objects count
- //it will be set automatically
+ void updateMenu();
- virtual bool load( const QString&, QtxActionMgr::Reader& );
+ virtual bool load( const QString&, QtxActionMgr::Reader& );
protected:
- typedef QMap< QAction*, QtxParser* > RulesMap;
+ virtual void internalUpdate();
+ void setParameters( QtxEvalParser*, QStringList& ) const;
+ virtual bool isSatisfied( QAction*, const RuleType = VisibleRule ) const;
+ QtxEvalExpr* expression( QAction*, const RuleType = VisibleRule, const bool = false ) const;
-protected:
- virtual bool isSatisfied( QAction*, bool visibility ) const;
- void setParams( QtxParser*, QStringList& ) const;
- RulesMap& map( bool visibility ) const;
+private:
+ bool result( QtxEvalParser* p ) const;
+ QVariant parameter( const QString&, const int = -1 ) const;
- void createOperations();
+private:
+ typedef QMap<RuleType, QtxEvalExpr*> ExprMap;
+ typedef QMap<QAction*, ExprMap> RuleMap;
+ typedef QMap<QString, QVariant> CacheMap;
private:
- RulesMap myVisibility, myToggle;
- Selection* myCurrentSelection;
- QtxListOfOperations* myOperations;
+ RuleMap myRules;
+ CacheMap myCache;
+ QtxPopupSelection* mySelection;
};
-
-
-class QtxPopupMgr::PopupCreator : public QtxActionMgr::Creator
+class QTX_EXPORT QtxPopupSelection : public QObject
{
+ Q_OBJECT
+
public:
- PopupCreator( QtxActionMgr::Reader*, QtxPopupMgr* );
- virtual ~PopupCreator();
+ QtxPopupSelection();
+ virtual ~QtxPopupSelection();
- virtual int append( const QString&, const bool,
- const ItemAttributes&, const int );
+ virtual int count() const = 0;
+ virtual QVariant parameter( const QString& ) const;
+ virtual QVariant parameter( const int, const QString& ) const = 0;
- virtual QString visibleRule( const ItemAttributes& ) const;
- virtual QString toggleRule( const ItemAttributes& ) const;
+ QString option( const QString& ) const;
+ void setOption( const QString&, const QString& );
private:
- QtxPopupMgr* myMgr;
-};
+ QString equalityParam() const;
+ QString selCountParam() const;
+
+private:
+ typedef QMap<QString, QString> OptionsMap;
+private:
+ OptionsMap myOptions;
+};
#endif
virtual void itemAdded( Item* );
virtual void itemRemoved( Item* );
- void childItems( QPtrList<Item>& ) const;
+ void childItems( QList<Item*>& ) const;
private:
void removeItem( Item* );
ItemMap myItems;
QtxResourceMgr* myResMgr;
QMap<Item*, QString> myBackup;
- QPtrList<Item> myChildren;
+ QList<Item*> myChildren;
friend class QtxResourceEdit::Item;
};
virtual int type() const = 0;
Item* parentItem() const;
- void childItems( QPtrList<Item>& ) const;
+ void childItems( QList<Item*>& ) const;
virtual bool isEmpty() const;
Item* item( const QString&, const int ) const;
protected:
- typedef QPtrList<Item> ItemList;
- typedef QPtrListIterator<Item> ItemListIterator;
+ typedef QList<Item*> ItemList;
+ typedef QListIterator<Item*> ItemListIterator;
private:
static int generateId();
//
#include "QtxResourceMgr.h"
-#include <qdir.h>
-#include <qfile.h>
-#include <qregexp.h>
-#include <qpixmap.h>
-#include <qtranslator.h>
-#include <qapplication.h>
-
+#include <QDir>
+#include <QFile>
+#include <QRegExp>
+#include <QTextStream>
+#include <QTranslator>
+#include <QApplication>
#ifndef QT_NO_DOM
-#include <qdom.h>
+#include <QDomDocument>
+#include <QDomElement>
+#include <QDomNode>
#endif
+#define EMULATE_GLOBAL_CONTEXT
+
#include <stdlib.h>
/*!
- Class: QtxResourceMgr::Resources
- Level: Internal
+ \class QtxResourceMgr::Resources
+ \internal
+ \brief Represents container for settings read from the resource file.
*/
-QtxResourceMgr::Resources::Resources( const QtxResourceMgr* mgr, const QString& fileName )
-: myFileName( fileName ),
- myMgr( const_cast<QtxResourceMgr*>( mgr ) )
+class QtxResourceMgr::Resources
+{
+public:
+ Resources( QtxResourceMgr*, const QString& );
+ virtual ~Resources();
+
+ QString file() const;
+ void setFile( const QString& );
+
+ QString value( const QString&, const QString&, const bool ) const;
+ void setValue( const QString&, const QString&, const QString& );
+
+ bool hasSection( const QString& ) const;
+ bool hasValue( const QString&, const QString& ) const;
+
+ void removeSection( const QString& );
+ void removeValue( const QString&, const QString& );
+
+ QPixmap loadPixmap( const QString&, const QString&, const QString& ) const;
+ QTranslator* loadTranslator( const QString&, const QString&, const QString& ) const;
+
+ QString environmentVariable( const QString&, int&, int& ) const;
+ QString makeSubstitution( const QString&, const QString&, const QString& ) const;
+
+ void clear();
+
+ QStringList sections() const;
+ QStringList parameters( const QString& ) const;
+
+ QString path( const QString&, const QString&, const QString& ) const;
+
+protected:
+ QtxResourceMgr* resMgr() const;
+
+private:
+ Section section( const QString& );
+ const Section section( const QString& ) const;
+
+ QString fileName( const QString&, const QString&, const QString& ) const;
+
+private:
+ typedef QMap<QString, Section> SectionMap;
+
+private:
+ QtxResourceMgr* myMgr; //!< resources manager
+ SectionMap mySections; //!< sections map
+ QString myFileName; //!< resources file name
+ QMap<QString,QPixmap> myPixmapCache; //!< pixmaps cache
+
+ friend class QtxResourceMgr::Format;
+};
+
+/*!
+ \brief Constructor.
+ \param mgr parent resources manager
+ \param fileName resources file name
+*/
+QtxResourceMgr::Resources::Resources( QtxResourceMgr* mgr, const QString& fileName )
+: myMgr( mgr ),
+ myFileName( fileName )
{
}
/*!
- Destructor
+ \brief Destructor.
*/
QtxResourceMgr::Resources::~Resources()
{
}
/*!
- Returns name of resource file
- This file is used to load/save operations
+ \brief Get resources file name.
+
+ This file is used to load/save operations.
+
+ \return file name
+ \sa setFile()
*/
QString QtxResourceMgr::Resources::file() const
{
}
/*!
- Sets name of resource file
- \param fn - name of file
+ \brief Set resources file name.
+ \param fn file name
+ \sa file()
*/
void QtxResourceMgr::Resources::setFile( const QString& fn )
{
}
/*!
- Returns string representation of parameter value
- Returns QString::null if there is no such parameter
-
- \param sect - name of section
- \param name - name of parameter
- \param subst - if it is true, then the substitution of variables
- will be done with help of makeSubstitution method
- \sa makeSubstitution()
+ \brief Get string representation of parameter value.
+ \param sect section name
+ \param name parameter name
+ \param subst if \c true, perform variables substitution
+ \return parameter value or null QString if there is no such parameter
+ \sa setValue(), makeSubstitution()
*/
QString QtxResourceMgr::Resources::value( const QString& sect, const QString& name, const bool subst ) const
{
}
/*!
- Sets value by it's string representation
-
- \param sect - name of section
- \param name - name of parameter
- \param val - string value
+ \brief Set parameter value.
+ \param sect section name
+ \param name parameter name
+ \param val parameter value
+ \sa value(), makeSubstitution()
*/
void QtxResourceMgr::Resources::setValue( const QString& sect, const QString& name, const QString& val )
{
- Section& s = section( sect );
- s.insert( name, val );
+ if ( !mySections.contains( sect ) )
+ mySections.insert( sect, Section() );
+
+ mySections[sect].insert( name, val );
}
/*!
- \return true if section exists
- \param sect - name of section
+ \brief Check section existence.
+ \param sect section name
+ \return \c true if section exists
*/
bool QtxResourceMgr::Resources::hasSection( const QString& sect ) const
{
}
/*!
- \return true if parameter exists in section
- \param sect - name of section
- \param name - name of parameter
+ \brief Check parameter existence.
+ \param sect section name
+ \param name parameter name
+ \return \c true if parameter exists in specified section
*/
bool QtxResourceMgr::Resources::hasValue( const QString& sect, const QString& name ) const
{
}
/*!
- Removes section from resources
- \param sect - name of section
+ \brief Remove resourcs section.
+ \param sect secton name
*/
void QtxResourceMgr::Resources::removeSection( const QString& sect )
{
}
/*!
- Removes parameter from section
- \param sect - name of section
- \param name - name of parameter
+ \brief Remove parameter from the section.
+ \param sect section name
+ \param name parameter name
*/
void QtxResourceMgr::Resources::removeValue( const QString& sect, const QString& name )
{
- if ( !hasSection( sect ) )
+ if ( !mySections.contains( sect ) )
return;
- Section& s = section( sect );
- s.remove( name );
+ mySections[sect].remove( name );
- if ( s.isEmpty() )
+ if ( mySections[sect].isEmpty() )
mySections.remove( sect );
}
/*!
- Removes all sections
+ \brief Remove all sections.
*/
void QtxResourceMgr::Resources::clear()
{
}
/*!
+ \brief Get all sections names.
\return list of section names
*/
QStringList QtxResourceMgr::Resources::sections() const
}
/*!
- \return list of parameter names from section
- \param sec - name of section
+ \brief Get all parameters name in specified section.
+ \param sec section name
+ \return list of settings names
*/
QStringList QtxResourceMgr::Resources::parameters( const QString& sec ) const
{
}
/*!
- \return path of file from directory built by parameter
- \return QString::null if built path doesn't exist
- \param sec - name of section
- \param prefix - name of parameter containing some path
- \param name - name of file
+ \brief Get absolute path to the file which name is defined by the parameter.
+
+ The file name is defined by \a name argument, while directory name is retrieved
+ from resources parameter \a prefix of section \a sec. Both directory and file name
+ can be relative. If the directory is relative, it is calculated from the initial
+ resources file name (see file()). Directory parameter can contain environment
+ variables, which are substituted automatically.
+
+ \param sec section name
+ \param prefix parameter containing directory name
+ \param name file name
+ \return absolute file path or null QString if file does not exist
+ \sa fileName(), file(), makeSubstitution()
*/
QString QtxResourceMgr::Resources::path( const QString& sec, const QString& prefix, const QString& name ) const
{
}
/*!
- \return corresponding resource manager
+ \brief Get resource manager
+ \return resource manager pointer
*/
QtxResourceMgr* QtxResourceMgr::Resources::resMgr() const
{
}
/*!
- \return instance of section by it's name. Section will be created if it doesn't exist
+ \brief Get resources section by specified name.
+
+ If section does not exist it is created (empty).
+
+ \param sn section name
+ \return resources section
*/
-QtxResourceMgr::Section& QtxResourceMgr::Resources::section( const QString& sn )
+QtxResourceMgr::Section QtxResourceMgr::Resources::section( const QString& sn )
{
if ( !mySections.contains( sn ) )
mySections.insert( sn, Section() );
}
/*!
- \return instance of section by it's name. Section will be created if it doesn't exist
+ \brief Get resources section by specified name.
+ \param sn section name
+ \return resources section
*/
-const QtxResourceMgr::Section& QtxResourceMgr::Resources::section( const QString& sn ) const
+const QtxResourceMgr::Section QtxResourceMgr::Resources::section( const QString& sn ) const
{
return mySections[sn];
}
/*!
- \return full path of file
- \param sect - name of section
- \param prefix - name of parameter containing some path
- \param name - name of file
+ \brief Get file path.
+
+ The file name is defined by \a name argument, while directory name is retrieved
+ from resources parameter \a prefix of section \a sec. Both directory and file name
+ can be relative. If the directory is relative, it is calculated from the initial
+ resources file name (see file()). Directory parameter can contain environment
+ variables, which are substituted automatically.
+ File existence is not checked.
+
+ \param sec section name
+ \param prefix parameter containing directory name
+ \param name file name
+ \return absolute file path or null QString if \a prefix parameter
+ does not exist in section \sec
+ \sa path(), file(), makeSubstitution()
*/
QString QtxResourceMgr::Resources::fileName( const QString& sect, const QString& prefix, const QString& name ) const
{
if ( !path.isEmpty() )
{
if ( QFileInfo( path ).isRelative() )
- path = Qtx::addSlash( QFileInfo( myFileName ).dirPath( true ) ) + path;
+ path = Qtx::addSlash( Qtx::dir( myFileName, true ) ) + path;
path = Qtx::addSlash( path ) + name;
}
{
QString fname = QDir::convertSeparators( path );
QFileInfo inf( fname );
- fname = inf.absFilePath();
+ fname = inf.absoluteFilePath();
return fname;
}
return QString();
}
/*!
- \return QPixmap loaded from file
- \param sect - name of section
- \param prefix - name of parameter containing some path
- \param name - name of picture file
+ \brief Load and return pixmap from external file.
+
+ If QtxResourceMgr::isPixmapCached() is \c true then cached pixmap is returned
+ (if it is already loaded), otherwise it is loaded from file.
+ If the file name is invalid, null pixmap is returned.
+
+ \param sect section name
+ \param prefix parameter containing resources directory name
+ \param name pixmap file name
+ \return pixmap loaded from file
*/
QPixmap QtxResourceMgr::Resources::loadPixmap( const QString& sect, const QString& prefix, const QString& name ) const
{
}
/*!
- \return just created and loaded translator
- \param sect - name of section
- \param prefix - name of parameter containing some path
- \param name - name of file
+ \brief Load translator.
+ \param sect section name
+ \param prefix parameter containing resources directory
+ \param name translation file name
+ \return just created and loaded translator or 0 in case of error
*/
QTranslator* QtxResourceMgr::Resources::loadTranslator( const QString& sect, const QString& prefix, const QString& name ) const
{
QTranslator* trans = new QTranslator( 0 );
- if ( !trans->load( fileName( sect, prefix, name ) ) )
+ QString fname = fileName( sect, prefix, name );
+#ifdef EMULATE_GLOBAL_CONTEXT
+ char* buf = 0;
+ QFile file( fname );
+ int len = file.size();
+ if ( len )
+ {
+ buf = new char[len];
+ if ( !file.open( QIODevice::ReadOnly ) || len != (int)file.read( buf, len ) )
+ {
+ delete buf;
+ buf = 0;
+ }
+ file.close();
+ }
+ if ( buf )
+ {
+ char* pattern = "@default";
+ size_t pl = strlen( pattern );
+ for ( size_t i = 0; i < len - pl; i++ )
+ {
+ char* cur = buf + i;
+ if ( !strncmp( cur, pattern, pl ) )
+ {
+ *cur = '\0';
+ i += pl - 1;
+ }
+ }
+
+ if ( !trans->load( (uchar*)buf, len ) )
+ {
+ delete buf;
+ buf = 0;
+ }
+ }
+
+ if ( !buf )
+#else
+ if ( !trans->load( Qtx::file( fname, false ), Qtx::dir( fname ) ) )
+#endif
{
delete trans;
trans = 0;
}
/*!
- Finds in string variables by patterns: ${name} or $(name) or %name%
- \return first found name or QString::null if there is no ones
- \param str - string where the search is processed
- \param start - integer value for returning start position of variable
- \param len - integer value for returning length of variable
+ \brief Parse given string to retrieve environment variable.
+
+ Looks through the string for the patterns: ${name} or $(name) or %name%.
+ If string contains variable satisfying any pattern, the variable name
+ is returned, start index of the variable is returned in the \a start parameter,
+ and length of the variable is returned in the \a len parameter.
+
+ \param str string being processed
+ \param start if variable is found, this parameter contains its starting
+ position in the \a str
+ \param len if variable is found, this parameter contains its length
+ \return first found variable or null QString if there is no ones
*/
QString QtxResourceMgr::Resources::environmentVariable( const QString& str, int& start, int& len ) const
{
QString varName = QString::null;
len = 0;
- QRegExp rx( "\\$\\{([a-zA-Z]+[a-zA-Z0-9_]*)\\}|\\$\\(([a-zA-Z]+[a-zA-Z0-9_]*)\\)|\\$([a-zA-Z]+[a-zA-Z0-9_]*)|\\%([a-zA-Z]+[a-zA-Z0-9_]*)\\%" );
+ QRegExp rx( "(^\\$\\{|[^\\$]\\$\\{)([a-zA-Z]+[a-zA-Z0-9_]*)(\\})|(^\\$\\(|[^\\$]\\$\\()([a-zA-Z]+[a-zA-Z0-9_]*)(\\))|(^\\$|[^\\$]\\$)([a-zA-Z]+[a-zA-Z0-9_]*)|(^%|[^%]%)([a-zA-Z]+[a-zA-Z0-9_]*)(%[^%]|%$)" );
- int pos = rx.search( str, start );
+ int pos = rx.indexIn( str, start );
if ( pos != -1 )
{
- start = pos;
- len = rx.matchedLength();
- QStringList caps = rx.capturedTexts();
- for ( uint i = 1; i <= caps.count() && varName.isEmpty(); i++ )
- varName = *caps.at( i );
+ int i = 1;
+ while ( i <= rx.numCaptures() && varName.isEmpty() )
+ {
+ QString capStr = rx.cap( i );
+ if ( !capStr.contains( "%" ) && !capStr.contains( "$" ) )
+ varName = capStr;
+ i++;
+ }
+
+ if ( !varName.isEmpty() )
+ {
+ int capIdx = i - 1;
+ start = rx.pos( capIdx );
+ int end = start + varName.length();
+ if ( capIdx > 1 && rx.cap( capIdx - 1 ).contains( QRegExp( "\\$|%" ) ) )
+ start = rx.pos( capIdx - 1 ) + rx.cap( capIdx - 1 ).indexOf( QRegExp( "\\$|%" ) );
+ if ( capIdx < rx.numCaptures() && !rx.cap( capIdx - 1 ).isEmpty() )
+ end++;
+ len = end - start;
+ }
}
return varName;
}
/*!
- Substitutes variables by its' values. If variable is from enviroment,
- it will be replaced by environment value. If it isn't, method tries to
- find it's value among resources
- \return new variant of string 'str'
- \param str - string to process substitution
- \param sect - section, in which the variables will be finding
- \param name - name of variable which must be ignored during substitution
+ \brief Substitute variables by their values.
+
+ Environment variable is substituted by its value. For other variables resource
+ manager tries to find value among defined resources parameters.
+
+ \param str string to be processed
+ \param sect section, where variables are searched
+ \param name name of variable which must be ignored during substitution
+ \return processed string (with all substitutions made)
*/
QString QtxResourceMgr::Resources::makeSubstitution( const QString& str, const QString& sect, const QString& name ) const
{
if ( envName.isNull() )
break;
- QString newStr = QString::null;
- if ( ::getenv( envName ) )
- newStr = QString( ::getenv( envName ) );
+ QString newStr;
+ if ( ::getenv( envName.toLatin1() ) )
+ newStr = QString( ::getenv( envName.toLatin1() ) );
if ( newStr.isNull() )
{
res.replace( start, len, newStr );
}
+ res.replace( "$$", "$" );
+ res.replace( "%%", "%" );
+
return res;
}
/*!
- Class: QtxResourceMgr::IniFormat
- Level: Internal
+ \class QtxResourceMgr::IniFormat
+ \internal
+ \brief Reader/writer for .ini resources files.
*/
+
class QtxResourceMgr::IniFormat : public Format
{
public:
};
/*!
- Default constructor
+ \brief Constructor.
*/
QtxResourceMgr::IniFormat::IniFormat()
: Format( "ini" )
}
/*!
- Destructor
+ \brief Destructor.
*/
QtxResourceMgr::IniFormat::~IniFormat()
{
}
/*!
- Loads resources from ini-file to map of sections
- \param fname - name of resource file
- \param secMap - map of sections
+ \brief Load resources from ini-file.
+ \param fname resources file name
+ \param secMap resources map to be filled in
+ \return \c true on success and \c false on error
*/
bool QtxResourceMgr::IniFormat::load( const QString& fname, QMap<QString, Section>& secMap )
{
QFile file( fname );
- if ( !file.open( IO_ReadOnly ) )
+ if ( !file.open( QFile::ReadOnly ) )
return false;
QTextStream ts( &file );
if ( data.isNull() )
break;
- data = data.stripWhiteSpace();
+ data = data.trimmed();
if ( data.isEmpty() )
continue;
continue;
QRegExp rx( "^\\[([\\w\\s\\._]*)\\]$" );
- if ( rx.search( data ) != -1 )
+ if ( rx.indexIn( data ) != -1 )
{
section = rx.cap( 1 );
if ( section.isEmpty() )
{
res = false;
- qWarning( QString( "Empty section in line %1" ).arg( line ) );
+ qWarning( "Empty section in line %d", line );
}
}
else if ( data.contains( "=" ) && !section.isEmpty() )
{
- int pos = data.find( separator );
- QString key = data.left( pos ).stripWhiteSpace();
- QString val = data.mid( pos + 1 ).stripWhiteSpace();
+ int pos = data.indexOf( separator );
+ QString key = data.left( pos ).trimmed();
+ QString val = data.mid( pos + 1 ).trimmed();
secMap[section].insert( key, val );
}
else
{
res = false;
- section.isEmpty() ? qWarning( "Current section is empty" ) :
- qWarning( QString( "Error in line: %1" ).arg( line ) );
+ section.isEmpty() ? qWarning( "Current section is empty" ) : qWarning( "Error in line: %d", line );
}
}
}
/*!
- Saves map of sections to resource ini-file
- \param fname - name of resource file
- \param secMap - map of sections
+ \brief Save resources to the ini-file.
+ \param fname resources file name
+ \param secMap resources map
+ \return \c true on success and \c false on error
*/
bool QtxResourceMgr::IniFormat::save( const QString& fname, const QMap<QString, Section>& secMap )
{
QFile file( fname );
- if ( !file.open( IO_WriteOnly ) )
+ if ( !file.open( QFile::WriteOnly ) )
return false;
+ QTextStream ts( &file );
+
bool res = true;
for ( QMap<QString, Section>::ConstIterator it = secMap.begin(); it != secMap.end() && res; ++it )
{
- QString data = QString( "[%1]\n" ).arg( it.key() );
- for ( Section::ConstIterator iter = it.data().begin(); iter != it.data().end(); ++iter )
- data += iter.key() + " = " + iter.data() + "\n";
- data += "\n";
+ QStringList data( QString( "[%1]" ).arg( it.key() ) );
+ for ( Section::ConstIterator iter = it.value().begin(); iter != it.value().end(); ++iter )
+ data.append( iter.key() + " = " + iter.value() );
+ data.append( "" );
- res = file.writeBlock( data.latin1(), data.length() ) == (int)data.length();
+ for ( QStringList::const_iterator itr = data.begin(); itr != data.end(); ++itr )
+ ts << *itr << endl;
}
file.close();
}
/*!
- Class: QtxResourceMgr::XmlFormat
- Level: Internal
+ \class QtxResourceMgr::XmlFormat
+ \internal
+ \brief Reader/writer for .xml resources files.
*/
class QtxResourceMgr::XmlFormat : public Format
};
/*!
- Default constructor
+ \brief Constructor.
*/
QtxResourceMgr::XmlFormat::XmlFormat()
: Format( "xml" )
}
/*!
- Destructor
+ \brief Destructor.
*/
QtxResourceMgr::XmlFormat::~XmlFormat()
{
}
/*!
- Loads resources from xml-file to map of sections
- \param fname - name of resource file
- \param secMap - map of sections
+ \brief Load resources from xml-file.
+ \param fname resources file name
+ \param secMap resources map to be filled in
+ \return \c true on success and \c false on error
*/
bool QtxResourceMgr::XmlFormat::load( const QString& fname, QMap<QString, Section>& secMap )
{
#ifndef QT_NO_DOM
QFile file( fname );
- if ( !file.open( IO_ReadOnly ) )
+ if ( !file.open( QFile::ReadOnly ) )
{
qDebug( "File cannot be opened" );
return false;
#endif
- if( res )
- qDebug( QString( "File '%1' is loaded successfully" ).arg( fname ) );
+ if ( res )
+ qDebug( "File '%s' is loaded successfully", (const char*)fname.toLatin1() );
return res;
}
/*!
- Saves map of sections to resource xml-file
- \param fname - name of resource file
- \param secMap - map of sections
+ \brief Save resources to the xml-file.
+ \param fname resources file name
+ \param secMap resources map
+ \return \c true on success and \c false on error
*/
bool QtxResourceMgr::XmlFormat::save( const QString& fname, const QMap<QString, Section>& secMap )
{
#ifndef QT_NO_DOM
QFile file( fname );
- if ( !file.open( IO_WriteOnly ) )
+ if ( !file.open( QFile::WriteOnly ) )
return false;
QDomDocument doc( docTag() );
QDomElement sect = doc.createElement( sectionTag() );
sect.setAttribute( nameAttribute(), it.key() );
root.appendChild( sect );
- for ( Section::ConstIterator iter = it.data().begin(); iter != it.data().end(); ++iter )
+ for ( Section::ConstIterator iter = it.value().begin(); iter != it.value().end(); ++iter )
{
QDomElement val = doc.createElement( parameterTag() );
val.setAttribute( nameAttribute(), iter.key() );
- val.setAttribute( valueAttribute(), iter.data() );
+ val.setAttribute( valueAttribute(), iter.value() );
sect.appendChild( val );
}
}
- QString docStr = doc.toString();
- res = file.writeBlock( docStr.latin1(), docStr.length() ) == (int)docStr.length();
+ QTextStream ts( &file );
+ QStringList docStr = doc.toString().split( "\n" );
+ for ( QStringList::const_iterator itr = docStr.begin(); itr != docStr.end(); ++itr )
+ ts << *itr << endl;
+
file.close();
#endif
}
/*!
- \return XML tag of document
+ \brief Get document tag name
+ \return XML document tag name
*/
QString QtxResourceMgr::XmlFormat::docTag() const
{
}
/*!
- \return XML tag of section
+ \brief Get section tag name
+ \return XML section tag name
*/
QString QtxResourceMgr::XmlFormat::sectionTag() const
{
}
/*!
- \return XML tag of parameter
+ \brief Get parameter tag name
+ \return XML parameter tag name
*/
QString QtxResourceMgr::XmlFormat::parameterTag() const
{
}
/*!
- \return XML attribute of parameter name
+ \brief Get parameter tag's "name" attribute name
+ \return XML parameter tag's "name" attribute name
*/
QString QtxResourceMgr::XmlFormat::nameAttribute() const
{
}
/*!
- \return XML attribute of parameter value
+ \brief Get parameter tag's "value" attribute name
+ \return XML parameter tag's "value" attribute name
*/
QString QtxResourceMgr::XmlFormat::valueAttribute() const
{
}
/*!
- Class: QtxResourceMgr::Format
- Level: Public
+ \class QtxResourceMgr::Format
+ \brief Generic resources files reader/writer class.
*/
/*!
- \brief Constructs the format object with specified name.
- \param fmt - name of the format
+ \brief Constructor.
+ \param fmt format name (for example, "xml" or "ini")
*/
QtxResourceMgr::Format::Format( const QString& fmt )
: myFmt( fmt )
}
/*!
- \brief Destructs the format object.
+ \brief Destructor
*/
QtxResourceMgr::Format::~Format()
{
}
/*!
- \brief Returns the format name.
+ \brief Get the format name.
+ \return format name
*/
QString QtxResourceMgr::Format::format() const
{
}
/*!
- \brief Returns the string list of the format options.
+ \brief Get options names.
+ \return list of the format options
*/
QStringList QtxResourceMgr::Format::options() const
{
}
/*!
- \brief Returns the value of the option with specified name.
- If option doesn't exist then empty string returned.
- \param opt - name of the option
+ \brief Get the value of the option with specified name.
+
+ If option doesn't exist then null QString is returned.
+
+ \param opt option name
+ \return option value
*/
QString QtxResourceMgr::Format::option( const QString& opt ) const
{
}
/*!
- \brief Sets the value of the option with specified name.
- \param opt - name of the option
- \param opt - value of the option
+ \brief Set the value of the option with specified name.
+ \param opt option name
+ \param val option value
*/
void QtxResourceMgr::Format::setOption( const QString& opt, const QString& val )
{
}
/*!
- \brief Perform the loading of the resources from resource file.
- \param res - resources object which will be loaded
+ \brief Load resources from the resource file.
+ \param res resources object
+ \return \c true on success and \c false on error
*/
bool QtxResourceMgr::Format::load( Resources* res )
{
if ( status )
res->mySections = sections;
else
- qDebug( "QtxResourceMgr: Could not load resource file \"%s\"", res->myFileName.latin1() );
+ qDebug( "QtxResourceMgr: Could not load resource file \"%s\"", (const char*)res->myFileName.toLatin1() );
return status;
}
/*!
- \brief Perform the saving of the resources into resource file.
- \param res - resources object which will be saved
+ \brief Save resources to the resource file.
+ \param res resources object
+ \return \c true on success and \c false on error
*/
bool QtxResourceMgr::Format::save( Resources* res )
{
}
/*!
- Class: QtxResourceMgr
- Level: Public
-*/
-
-/*!
- \brief Constructs the resource manager object for application.
- \param appName - name of the application which resources will be used.
- \param resVarTemplate - template for the resource environment variable name which
- should point to the resource directory list.
- Default value is "%1Resources". Its mean that for application
- with name "MyApp" environment variable "MyAppResources" will
- be used. Template may not have the parameter '%1' substituted
- by application name. In this case this string will be used as
- is without substitution.
- Resource environment variable should contains one or several resource directories
- separated by symbol ';'. Resource directories list transfered into the setDirList().
- These directories and the user home directory used for the loading application resources.
- Each of the resource directories can contains resource file. The name of this file defined
- by the function globalFileName(). Resource file name in the user home defined by the
- function userFileName(). Any resource looking firstly in the user home resources then
- resource directories used in the specified order. All setted resources always stored into
- the resource file at the user home. Only user home resource file is saved.
- If you want to ignore of loading of Local User Preferences, you needs setup setIngoreUserValues()
- as true.
+ \fn virtual bool QtxResourceMgr::Format::load( const QString& fname,
+ QMap<QString, Section>& secMap )
+ \brief Load resources from the specified resources file.
+
+ Should be implemented in the successors.
+
+ \param fname resources file name
+ \param secMap resources map to be filled in
+ \return \c true on success and \c false on error
+*/
+
+/*!
+ \fn virtual bool QtxResourceMgr::Format::save( const QString& fname,
+ const QMap<QString, Section>& secMap )
+
+ \brief Save resources to the specified resources file.
+
+ Should be implemented in the successors.
+
+ \param fname resources file name
+ \param secMap resources map
+ \return \c true on success and \c false on error
+*/
+
+/*!
+ \class QtxResourceMgr
+ \brief Application resources manager.
+
+ This class can be used to define settings, save/load settings and
+ application preferences to the resource file(s), load translation files
+ (internationalization mechanism), load pixmaps and other resources from
+ external files, etc.
+
+ Currently it supports .ini and .xml resources file formats. To implement
+ own resources file format, inherit from the Format class and implement virtual
+ Format::load() and Format::save() methods.
+
+ Resources manager is initialized by the (symbolic) name of the application.
+ The parameter \a resVarTemplate specifies the template for the environment
+ variable which should point to the resource directory or list of directories.
+ Environment variable name is calculated by substitution of "%1" substring in
+ the \a resVarTemplate parameter (if it contains such substring) by the
+ application name (\a appName).
+ By default, \a resVarTemplate is set to "%1Resources". For example, if the application name
+ is "MyApp", the environment variable "MyAppResources" will be inspected in this case.
+
+ Resource manager can handle several global application configuration files and
+ one user configuration file. Location of global configuration files is defined
+ by the environment variable (see above) and these files are always read-only.
+ The name of the global configuration files is retrieved by calling virtual method
+ globalFileName() which can be redefined in the QtxResourceMgr class successors.
+ User configuration file always situated in the user's home directory. It's name
+ is defined by calling virtual method userFileName() which can be also redefined
+ in the QtxResourceMgr class successors. This is the only file which the preferences
+ changed by the user during the application session are written to (usually
+ when the application closes).
+
+ Resources environment variable should contain one or several resource directories
+ (separated by ";" symbol on Windows and ":" or ";" on Linux). Each resource directory
+ can contain application global configuration file. The user configuration file has
+ the highest priority, for the global configuration files the priority is decreasing from
+ left to right, i.e. the first directory in the directoris list, defined by the
+ resources environment variable has higher priority. Priority has the meaning when
+ searching requested resources (application preference, pixmap file name, translation
+ file, etc).
+ Loading of the user configuration file can be omitted by calling setIgnoreUserValues()
+ with \c true parameter.
+
+ Resources manager operates with such terms like options, sections and parameters.
+ Parametets are named application resources, for example, application preferences like
+ integer, double, boolean or string values, pictures, font and color definitions, etc.
+ Parameters are organized inside the resources files into the named groups - sections.
+ Options are special kind of resoures which allow customizing resource files interpreting.
+ For example, by default language settings are defined in the resource file in the
+ section "language". It is possible to change this section name by setting "language"
+ option to another value (see setOption()).
+
+ Retrieving preferences values can be done by using one of value() methods, each returns
+ \c true if the corresponding preference is found. Another way is to use integerValue(),
+ doubleValue(), etc methods, which allow specifying default value which is used if the
+ specified preference is not found. Removing of preferences or sections can be done using
+ remove(const QString& sect) or remove(const QString& sect, const QString& name) methods.
+ To add the preference or to change exiting preference value use setValue() methods family.
+ Methods hasSection() and hasValue() can be used to check existence of section or
+ preference (in the specified section). List of all sections can be retrieved with the
+ sections() method, and list of all settings names in some specified section can be
+ obtained with parameters() method.
+
+ Pixmaps can be loaded with the loadPixmap() methods. If the specified pixmap is not found,
+ the default one is returned. Default pixmap can be set by setDefaultPixmap().
+
+ One of the key feature of the resources manager is support of application
+ internationalization mechanism. Translation files for the specified language can be loaded
+ with loadLanguage() method.
+*/
+
+/*!
+ \brief Constructs the resource manager.
+ \param appName application name
+ \param resVarTemplate resource environment variable pattern
*/
QtxResourceMgr::QtxResourceMgr( const QString& appName, const QString& resVarTemplate )
: myAppName( appName ),
envVar = envVar.arg( appName );
QString dirs;
- if ( ::getenv( envVar ) )
- dirs = ::getenv( envVar );
+ if ( ::getenv( envVar.toLatin1() ) )
+ dirs = ::getenv( envVar.toLatin1() );
#ifdef WIN32
QString dirsep = ";"; // for Windows: ";" is used as directories separator
#else
QString dirsep = "[:|;]"; // for Linux: both ":" and ";" can be used
#endif
- setDirList( QStringList::split( QRegExp(dirsep), dirs ) );
+ setDirList( dirs.split( QRegExp( dirsep ), QString::SkipEmptyParts ) );
installFormat( new XmlFormat() );
installFormat( new IniFormat() );
}
/*!
- \brief Destructs the resource manager object and free allocated memory.
+ \brief Destructor.
+
+ Destroy the resource manager and free allocated memory.
*/
QtxResourceMgr::~QtxResourceMgr()
{
QStringList prefList = myTranslator.keys();
for ( QStringList::const_iterator it = prefList.begin(); it != prefList.end(); ++it )
removeTranslators( *it );
- for ( ResListIterator resIt( myResources ); resIt.current(); ++resIt )
- delete resIt.current();
+ for ( ResList::iterator resIt = myResources.begin(); resIt != myResources.end(); ++resIt )
+ delete *resIt;
myResources.clear();
- for ( FormatListIterator formIt( myFormats ); formIt.current(); ++formIt )
- delete formIt.current();
+ for ( FormatList::iterator formIt = myFormats.begin(); formIt != myFormats.end(); ++formIt )
+ delete *formIt;
}
/*!
- \brief Returns the application name.
+ \brief Get the application name.
+ \return application name
*/
QString QtxResourceMgr::appName() const
{
}
/*!
- \brief Returns the checking of the existance flag. If its 'true' then resource
- will be setted into the manager only if it doesn't exist or has different
- value that existing value.
+ \brief Get the "check existance" flag
+
+ If this flag is \c true then preference can be set (with setValue() method)
+ only if it doesn't exist or if the value is changed.
+
+ \return \c true if "check existance" flag is set
*/
bool QtxResourceMgr::checkExisting() const
{
}
/*!
- \brief Sets the checking of the existance flag.
- \param on - boolean value of the flag.
+ \brief Set the "check existance" flag.
+ \param on new flag value
*/
void QtxResourceMgr::setCheckExisting( const bool on )
{
}
/*!
- \brief Returns the resource directories list except user home directory.
+ \brief Get the resource directories list.
+
+ Home user directory (where the user application configuration file is situated)
+ is not included. This is that directories list defined by the application
+ resources environment variable.
+
+ \return list of directories names
*/
QStringList QtxResourceMgr::dirList() const
{
}
/*!
- \brief Initialise the manager. Prepare the resource containers and load resources.
- \param autoLoad - if 'true' then all resources will be loaded.
+ \brief Initialise resources manager.
+
+ Prepare the resources containers and load resources (if \a autoLoad is \c true).
+
+ \param autoLoad if \c true then all resources are loaded
*/
void QtxResourceMgr::initialize( const bool autoLoad ) const
{
QtxResourceMgr* that = (QtxResourceMgr*)this;
if ( !userFileName( appName() ).isEmpty() )
- that->myResources.append( new Resources( this, userFileName( appName() ) ) );
+ that->myResources.append( new Resources( that, userFileName( appName() ) ) );
for ( QStringList::const_iterator it = myDirList.begin(); it != myDirList.end(); ++it )
{
QString path = Qtx::addSlash( *it ) + globalFileName( appName() );
- that->myResources.append( new Resources( this, path ) );
+ that->myResources.append( new Resources( that, path ) );
}
if ( autoLoad )
}
/*!
- \brief Return true if all loaded pixmaps are stored in internal map; by default: true
+ \brief Get "cached pixmaps" option value.
+
+ Resources manager allows possibility to cache loaded pixmaps that allow to
+ improve application performance. This feature is turned on by default - all
+ loaded pixmaps are stored in the internal map. Switching of this feature on/off
+ can be done by setIsPixmapCached() method.
+
+ \return \c true if pixmap cache is turned on
+ \sa setIsPixmapCached()
*/
bool QtxResourceMgr::isPixmapCached() const
{
}
/*!
- \brief Set true, if it is necessary to store all loaded pixmap in internal map
- (it accelerates following calls of loadPixmap)
+ \brief Switch "cached pixmaps" option on/off.
+ \param on enable pixmap cache if \c true and disable it if \c false
+ \sa isPixmapCached()
*/
void QtxResourceMgr::setIsPixmapCached( const bool on )
{
}
/*!
- \brief Removes all resources from the manager.
+ \brief Remove all resources from the resources manager.
*/
void QtxResourceMgr::clear()
{
- for ( ResListIterator it( myResources ); it.current(); ++it )
- it.current()->clear();
+ for ( ResList::iterator it = myResources.begin(); it != myResources.end(); ++it )
+ (*it)->clear();
}
/*!
- Set state 'ignore user values'.
- If it is true, then all resources loaded from user home directory is ignored
+ \brief Set "ignore user values" option value.
+
+ If this option is \c true, then all resources loaded from user home directory are ignored.
+
+ \param val new option value
+ \sa ignoreUserValues()
*/
void QtxResourceMgr::setIgnoreUserValues( const bool val )
{
}
/*!
- \return state 'ignore user values'
+ \brief Get "ignore user values" option value.
+
+ \return "ignore user values" option value
+ \sa setIgnoreUserValues()
*/
bool QtxResourceMgr::ignoreUserValues() const
{
}
/*!
- \brief Get the resource value as integer. Returns 'true' if it successfull otherwise
- returns 'false'.
- \param sect - Resource section name which contains resource.
- \param name - Name of the resource.
- \param iVal - Reference on the variable which should contains the resource output.
+ \brief Get interger parameter value.
+ \param sect section name
+ \param name parameter name
+ \param iVal parameter to return resulting integer value
+ \return \c true if parameter is found and \c false if parameter is not found
+ (in this case \a iVal value is undefined)
*/
bool QtxResourceMgr::value( const QString& sect, const QString& name, int& iVal ) const
{
}
/*!
- \brief Get the resource value as double. Returns 'true' if it successfull otherwise
- returns 'false'.
- \param sect - Resource section name which contains resource.
- \param name - Name of the resource.
- \param dVal - Reference on the variable which should contains the resource output.
+ \brief Get double parameter value.
+ \param sect section name
+ \param name parameter name
+ \param dVal parameter to return resulting double value
+ \return \c true if parameter is found and \c false if parameter is not found
+ (in this case \a dVal value is undefined)
*/
bool QtxResourceMgr::value( const QString& sect, const QString& name, double& dVal ) const
{
}
/*!
- \brief Get the resource value as boolean. Returns 'true' if it successfull otherwise
- returns 'false'.
- \param sect - Resource section name which contains resource.
- \param name - Name of the resource.
- \param bVal - Reference on the variable which should contains the resource output.
+ \brief Get boolean parameter value.
+ \param sect section name
+ \param name parameter name
+ \param bVal parameter to return resulting boolean value
+ \return \c true if parameter is found and \c false if parameter is not found
+ (in this case \a bVal value is undefined)
*/
bool QtxResourceMgr::value( const QString& sect, const QString& name, bool& bVal ) const
{
boolMap["false"] = boolMap["no"] = boolMap["off"] = false;
}
- val = val.lower();
+ val = val.toLower();
bool res = boolMap.contains( val );
if ( res )
bVal = boolMap[val];
}
/*!
- \brief Get the resource value as color. Returns 'true' if it successfull otherwise
- returns 'false'.
- \param sect - Resource section name which contains resource.
- \param name - Name of the resource.
- \param cVal - Reference on the variable which should contains the resource output.
+ \brief Get color parameter value.
+ \param sect section name
+ \param name parameter name
+ \param cVal parameter to return resulting color value
+ \return \c true if parameter is found and \c false if parameter is not found
+ (in this case \a cVal value is undefined)
*/
bool QtxResourceMgr::value( const QString& sect, const QString& name, QColor& cVal ) const
{
return false;
bool res = true;
- QStringList vals = QStringList::split( ",", val, true );
+ QStringList vals = val.split( QRegExp( "[\\s|,]" ), QString::SkipEmptyParts );
QIntList nums;
for ( QStringList::const_iterator it = vals.begin(); it != vals.end() && res; ++it )
- nums.append( (*it).toInt( &res ) );
+ {
+ int num = 0;
+ if ( (*it).startsWith( "#" ) )
+ num = (*it).mid( 1 ).toInt( &res, 16 );
+ else
+ num = (*it).toInt( &res, 10 );
+ if ( res )
+ nums.append( num );
+ }
- if ( res && nums.count() >= 3 )
+ res = res && nums.count() >= 3;
+ if ( res )
cVal.setRgb( nums[0], nums[1], nums[2] );
- else
+
+ if ( !res )
{
int pack = val.toInt( &res );
if ( res )
- Qtx::rgbSet( pack, cVal );
+ cVal = Qtx::rgbSet( pack );
+ }
+
+ if ( !res )
+ {
+ cVal = QColor( val );
+ res = cVal.isValid();
}
return res;
}
/*!
- \brief Get the resource value as font. Returns 'true' if it successfull otherwise
- returns 'false'.
- \param sect - Resource section name which contains resource.
- \param name - Name of the resource.
- \param fVal - Reference on the variable which should contains the resource output.
+ \brief Get font parameter value.
+ \param sect section name
+ \param name parameter name
+ \param fVal parameter to return resulting font value
+ \return \c true if parameter is found and \c false if parameter is not found
+ (in this case \a fVal value is undefined)
*/
bool QtxResourceMgr::value( const QString& sect, const QString& name, QFont& fVal ) const
{
if ( !value( sect, name, val, true ) )
return false;
- QStringList fontDescr = QStringList::split( ",", val );
+ QStringList fontDescr = val.split( ",", QString::SkipEmptyParts );
if ( fontDescr.count() < 2 )
return false;
for ( int i = 1; i < (int)fontDescr.count(); i++ )
{
- QString curval = fontDescr[i].stripWhiteSpace().lower();
+ QString curval = fontDescr[i].trimmed().toLower();
if ( curval == QString( "bold" ) )
fVal.setBold( true );
else if ( curval == QString( "italic" ) )
}
/*!
- \brief Get the resource value as string (native format). Returns 'true' if it
- successfull otherwise returns 'false'.
- \param sect - Resource section name which contains resource.
- \param name - Name of the resource.
- \param val - Reference on the variable which should contains the resource output.
- \param subst - If 'true' then manager substitute reference on environment variables
- and other resources by thier values. Default value of this parameter
- is 'true'
+ \brief Get byte array parameter value.
+ \param sect section name
+ \param name parameter name
+ \param baVal parameter to return resulting byte array value
+ \return \c true if parameter is found and \c false if parameter is not found
+ (in this case \a baVal value is undefined)
+*/
+bool QtxResourceMgr::value( const QString& sect, const QString& name, QByteArray& baVal ) const
+{
+ QString val;
+ if ( !value( sect, name, val, true ) )
+ return false;
+
+ baVal.clear();
+ QStringList lst = val.split( QRegExp( "[\\s|,]" ), QString::SkipEmptyParts );
+ for ( QStringList::const_iterator it = lst.begin(); it != lst.end(); ++it )
+ {
+ int base = 10;
+ QString str = *it;
+ if ( str.startsWith( "#" ) )
+ {
+ base = 16;
+ str = str.mid( 1 );
+ }
+ bool ok = false;
+ int num = str.toInt( &ok, base );
+ if ( !ok || num < 0 || num > 255 )
+ continue;
+
+ baVal.append( (char)num );
+ }
+ return !baVal.isEmpty();
+}
+
+/*!
+ \brief Get string parameter value (native format).
+ \param sect section name
+ \param name parameter name
+ \param val parameter to return resulting byte array value
+ \param subst if \c true perform environment variables substitution
+ \return \c true if parameter is found and \c false if parameter is not found
+ (in this case \a val value is undefined)
*/
bool QtxResourceMgr::value( const QString& sect, const QString& name, QString& val, const bool subst ) const
{
bool ok = false;
- ResListIterator it( myResources );
+ ResList::const_iterator it = myResources.begin();
if ( ignoreUserValues() )
++it;
- for ( ; it.current() && !ok; ++it )
+ for ( ; it != myResources.end() && !ok; ++it )
{
- ok = it.current()->hasValue( sect, name );
+ ok = (*it)->hasValue( sect, name );
if ( ok )
- val = it.current()->value( sect, name, subst );
+ val = (*it)->value( sect, name, subst );
}
return ok;
}
/*!
- \brief Returns the integer resource value. If resource can not be found or converted
- then specified default value will be returned.
- \param sect - Resource section name which contains resource.
- \param name - Name of the resource.
- \param def - Default resource value which will be used when resource not found.
+ \brief Get interger parameter value.
+
+ If the specified parameter is not found or can not be converted to the integer value,
+ the specified default value is returned instead.
+
+ \param sect section name
+ \param name parameter name
+ \param def default value
+ \return parameter value (or default value if parameter is not found)
*/
int QtxResourceMgr::integerValue( const QString& sect, const QString& name, const int def ) const
{
}
/*!
- \brief Returns the double resource value. If resource can not be found or converted
- then specified default value will be returned.
- \param sect - Resource section name which contains resource.
- \param name - Name of the resource.
- \param def - Default resource value which will be used when resource not found.
+ \brief Get double parameter value.
+
+ If the specified parameter is not found or can not be converted to the double value,
+ the specified default value is returned instead.
+
+ \param sect section name
+ \param name parameter name
+ \param def default value
+ \return parameter value (or default value if parameter is not found)
*/
double QtxResourceMgr::doubleValue( const QString& sect, const QString& name, const double def ) const
{
}
/*!
- \brief Returns the boolean resource value. If resource can not be found or converted
- then specified default value will be returned.
- \param sect - Resource section name which contains resource.
- \param name - Name of the resource.
- \param def - Default resource value which will be used when resource not found.
+ \brief Get boolean parameter value.
+
+ If the specified parameter is not found or can not be converted to the boolean value,
+ the specified default value is returned instead.
+
+ \param sect section name
+ \param name parameter name
+ \param def default value
+ \return parameter value (or default value if parameter is not found)
*/
bool QtxResourceMgr::booleanValue( const QString& sect, const QString& name, const bool def ) const
{
}
/*!
- \brief Returns the font resource value. If resource can not be found or converted
- then specified default value will be returned.
- \param sect - Resource section name which contains resource.
- \param name - Name of the resource.
- \param def - Default resource value which will be used when resource not found.
+ \brief Get font parameter value.
+
+ If the specified parameter is not found or can not be converted to the font value,
+ the specified default value is returned instead.
+
+ \param sect section name
+ \param name parameter name
+ \param def default value
+ \return parameter value (or default value if parameter is not found)
*/
QFont QtxResourceMgr::fontValue( const QString& sect, const QString& name, const QFont& def ) const
{
}
/*!
- \brief Returns the color resource value. If resource can not be found or converted
- then specified default value will be returned.
- \param sect - Resource section name which contains resource.
- \param name - Name of the resource.
- \param def - Default resource value which will be used when resource not found.
+ \brief Get color parameter value.
+
+ If the specified parameter is not found or can not be converted to the color value,
+ the specified default value is returned instead.
+
+ \param sect section name
+ \param name parameter name
+ \param def default value
+ \return parameter value (or default value if parameter is not found)
*/
QColor QtxResourceMgr::colorValue( const QString& sect, const QString& name, const QColor& def ) const
{
}
/*!
- \brief Returns the string resource value. If resource can not be found or converted
- then specified default value will be returned.
- \param sect - Resource section name which contains resource.
- \param name - Name of the resource.
- \param def - Default resource value which will be used when resource not found.
+ \brief Get string parameter value.
+
+ If the specified parameter is not found, the specified default value is returned instead.
+
+ \param sect section name
+ \param name parameter name
+ \param def default value
+ \return parameter value (or default value if parameter is not found)
*/
QString QtxResourceMgr::stringValue( const QString& sect, const QString& name, const QString& def ) const
{
}
/*!
- \brief Checks existance of the specified resource.
- \param sect - Resource section name which contains resource.
- \param name - Name of the resource.
+ \brief Get byte array parameter value.
+
+ If the specified parameter is not found, the specified default value is returned instead.
+
+ \param sect section name
+ \param name parameter name
+ \param def default value
+ \return parameter value (or default value if parameter is not found)
+*/
+QByteArray QtxResourceMgr::byteArrayValue( const QString& sect, const QString& name, const QByteArray& def ) const
+{
+ QByteArray val;
+ if ( !value( sect, name, val ) )
+ val = def;
+ return val;
+}
+
+/*!
+ \brief Check parameter existence.
+ \param sect section name
+ \param name parameter name
+ \return \c true if parameter exists in specified section
*/
bool QtxResourceMgr::hasValue( const QString& sect, const QString& name ) const
{
initialize();
bool ok = false;
- for ( ResListIterator it( myResources ); it.current() && !ok; ++it )
- ok = it.current()->hasValue( sect, name );
+ for ( ResList::const_iterator it = myResources.begin(); it != myResources.end() && !ok; ++it )
+ ok = (*it)->hasValue( sect, name );
return ok;
}
/*!
- \brief Checks existance of the specified resource section.
- \param sect - Resource section name which contains resource.
+ \brief Check section existence.
+ \param sect section name
+ \return \c true if section exists
*/
bool QtxResourceMgr::hasSection( const QString& sect ) const
{
initialize();
bool ok = false;
- for ( ResListIterator it( myResources ); it.current() && !ok; ++it )
- ok = it.current()->hasSection( sect );
+ for ( ResList::const_iterator it = myResources.begin(); it != myResources.end() && !ok; ++it )
+ ok = (*it)->hasSection( sect );
return ok;
}
/*!
- \brief Sets the integer resource value.
- \param sect - Resource section name.
- \param name - Name of the resource.
- \param val - Resource value.
+ \brief Set integer parameter value.
+ \param sect section name
+ \param name parameter name
+ \param val parameter value
*/
void QtxResourceMgr::setValue( const QString& sect, const QString& name, int val )
{
}
/*!
- \brief Sets the double resource value.
- \param sect - Resource section name.
- \param name - Name of the resource.
- \param val - Resource value.
+ \brief Set double parameter value.
+ \param sect section name
+ \param name parameter name
+ \param val parameter value
*/
void QtxResourceMgr::setValue( const QString& sect, const QString& name, double val )
{
}
/*!
- \brief Sets the boolean resource value.
- \param sect - Resource section name.
- \param name - Name of the resource.
- \param val - Resource value.
+ \brief Set boolean parameter value.
+ \param sect section name
+ \param name parameter name
+ \param val parameter value
*/
void QtxResourceMgr::setValue( const QString& sect, const QString& name, bool val )
{
}
/*!
- \brief Sets the color resource value.
- \param sect - Resource section name.
- \param name - Name of the resource.
- \param val - Resource value.
+ \brief Set color parameter value.
+ \param sect section name
+ \param name parameter name
+ \param val parameter value
*/
void QtxResourceMgr::setValue( const QString& sect, const QString& name, const QColor& val )
{
if ( checkExisting() && value( sect, name, res ) && res == val )
return;
- setResource( sect, name, QString( "%1, %2, %3" ).arg( val.red() ).arg( val.green() ).arg( val.blue() ) );
+ setResource( sect, name, val.isValid() ? val.name() : QString() );
}
/*!
- \brief Sets the font resource value.
- \param sect - Resource section name.
- \param name - Name of the resource.
- \param val - Resource value.
+ \brief Set font parameter value.
+ \param sect section name
+ \param name parameter name
+ \param val parameter value
*/
void QtxResourceMgr::setValue( const QString& sect, const QString& name, const QFont& val )
{
}
/*!
- \brief Sets the string resource value.
- \param sect - Resource section name.
- \param name - Name of the resource.
- \param val - Resource value.
+ \brief Set string parameter value.
+ \param sect section name
+ \param name parameter name
+ \param val parameter value
*/
void QtxResourceMgr::setValue( const QString& sect, const QString& name, const QString& val )
{
}
/*!
- \brief Remove the all specified resource section.
- \param sect - Resource section name.
+ \brief Set byte array parameter value.
+ \param sect section name
+ \param name parameter name
+ \param val parameter value
+*/
+void QtxResourceMgr::setValue( const QString& sect, const QString& name, const QByteArray& val )
+{
+ QByteArray res;
+ if ( checkExisting() && value( sect, name, res ) && res == val )
+ return;
+
+ char buf[8];
+ QStringList lst;
+ for ( int i = 0; i < val.size(); i++ )
+ {
+ ::sprintf( buf, "#%02X", val.at( i ) );
+ lst.append( QString( buf ) );
+ }
+
+ setResource( sect, name, lst.join( " " ) );
+}
+
+/*!
+ \brief Remove resources section.
+ \param sect section name
*/
void QtxResourceMgr::remove( const QString& sect )
{
initialize();
- for ( ResListIterator it( myResources ); it.current(); ++it )
- it.current()->removeSection( sect );
+ for ( ResList::iterator it = myResources.begin(); it != myResources.end(); ++it )
+ (*it)->removeSection( sect );
}
/*!
- \brief Remove the specified resource.
- \param sect - Resource section name.
- \param name - Name of the resource.
+ \brief Remove the specified parameter.
+ \param sect section name
+ \param name parameter name
*/
void QtxResourceMgr::remove( const QString& sect, const QString& name )
{
initialize();
- for ( ResListIterator it( myResources ); it.current(); ++it )
- it.current()->removeValue( sect, name );
+ for ( ResList::iterator it = myResources.begin(); it != myResources.end(); ++it )
+ (*it)->removeValue( sect, name );
}
/*!
- \brief Returns the current format which operates with resource files.
+ \brief Get current configuration files format.
+ \return configuration files format name
*/
QString QtxResourceMgr::currentFormat() const
{
QString fmt;
if ( !myFormats.isEmpty() )
- fmt = myFormats.getFirst()->format();
+ fmt = myFormats[0]->format();
return fmt;
}
/*!
- \brief Sets the current format which operates with resource files.
- \param fmt - Resource format name.
+ \brief Set current configuration files format.
+ \param fmt configuration files format name
*/
void QtxResourceMgr::setCurrentFormat( const QString& fmt )
{
if ( !form )
return;
- myFormats.remove( form );
+ myFormats.removeAll( form );
myFormats.prepend( form );
if ( myResources.isEmpty() )
return;
- ResListIterator resIt( myResources );
- if ( myResources.count() > myDirList.count() && resIt.current() ) {
- resIt.current()->setFile( userFileName( appName() ) );
+ ResList::iterator resIt = myResources.begin();
+ if ( myResources.count() > myDirList.count() && resIt != myResources.end() )
+ {
+ (*resIt)->setFile( userFileName( appName() ) );
++resIt;
}
- for ( QStringList::const_iterator it = myDirList.begin(); it != myDirList.end() && resIt.current(); ++it, ++resIt )
- resIt.current()->setFile( Qtx::addSlash( *it ) + globalFileName( appName() ) );
+ for ( QStringList::const_iterator it = myDirList.begin(); it != myDirList.end() && resIt != myResources.end(); ++it, ++resIt )
+ (*resIt)->setFile( Qtx::addSlash( *it ) + globalFileName( appName() ) );
}
/*!
- \brief Returns the resource format object by it name.
- \param fmt - Resource format name.
+ \brief Get configuration files format by specified format name.
+ \param fmt configuration files format name
+ \return format object or 0 if format is not defined
*/
QtxResourceMgr::Format* QtxResourceMgr::format( const QString& fmt ) const
{
Format* form = 0;
- for ( FormatListIterator it( myFormats ); it.current() && !form; ++it )
+ for ( FormatList::const_iterator it = myFormats.begin(); it != myFormats.end() && !form; ++it )
{
- if ( it.current()->format() == fmt )
- form = it.current();
+ if ( (*it)->format() == fmt )
+ form = *it;
}
return form;
}
/*!
- \brief Add the resource format to the manager. Newly added become current.
- \param form - Resource format object.
+ \brief Install configuration files format.
+
+ Added format becomes current.
+
+ \param form format object to be installed
*/
void QtxResourceMgr::installFormat( QtxResourceMgr::Format* form )
{
}
/*!
- \brief Remove the resource format from the manager.
- \param form - Resource format object.
+ \brief Remove configuration files format.
+ \param form format object to be uninstalled
*/
void QtxResourceMgr::removeFormat( QtxResourceMgr::Format* form )
{
- myFormats.remove( form );
+ myFormats.removeAll( form );
}
/*!
- \brief Returns the string list of the resource format options names.
+ \brief Get resource format options names.
+ \return list of options names
*/
QStringList QtxResourceMgr::options() const
{
}
/*!
- \brief Returns the string value for the specified option. If option doesn't exist
- then empty string will be returned.
- \param opt - Option name.
+ \brief Get the string value of the specified resources format option.
+
+ If option does not exist, null QString is returned.
+
+ \param opt option name
+ \return option value
+ \sa setOption(), options()
*/
QString QtxResourceMgr::option( const QString& opt ) const
{
}
/*!
- \brief Sets the string value for the specified option.
- \param opt - Option name.
- \param val - Option value.
+ \brief Set the string value of the specified resources format option.
+ \param opt option name
+ \param val option value
+ \sa option(), options()
*/
void QtxResourceMgr::setOption( const QString& opt, const QString& val )
{
}
/*!
- \brief Load the all resources from the resource files.
+ \brief Load all resources from all resource files (global and user).
+ \return \c true on success and \c false on error
+ \sa save()
*/
bool QtxResourceMgr::load()
{
return false;
bool res = true;
- for ( ResListIterator it( myResources ); it.current(); ++it )
- res = fmt->load( it.current() ) && res;
+ for ( ResList::iterator it = myResources.begin(); it != myResources.end(); ++it )
+ res = fmt->load( *it ) && res;
return res;
}
/*!
- \brief Import some file with resources
+ \brief Import resources from specified resource file.
+ \param fname resources file name
+ \return \c true on success and \c false on error
*/
bool QtxResourceMgr::import( const QString& fname )
{
if ( !fmt )
return false;
- Resources* r = myResources.getFirst();
- if( !r )
+ Resources* r = myResources[0];
+ if ( !r )
return false;
QString old = r->file();
}
/*!
- \brief Save the changed resources in to the user resource file.
+ \brief Save all resources to the user resource files.
+ \return \c true on success and \c false on error
*/
bool QtxResourceMgr::save()
{
if ( myResources.isEmpty() )
return true;
- return fmt->save( myResources.getFirst() );
+ return fmt->save( myResources[0] );
}
/*!
- \brief Returns the string list of the existing section names..
+ \brief Get all sections names.
+ \return list of section names
*/
QStringList QtxResourceMgr::sections() const
{
initialize();
QMap<QString, int> map;
- for ( ResListIterator it( myResources ); it.current(); ++it )
+ for ( ResList::const_iterator it = myResources.begin(); it != myResources.end(); ++it )
{
- QStringList lst = it.current()->sections();
+ QStringList lst = (*it)->sections();
for ( QStringList::const_iterator itr = lst.begin(); itr != lst.end(); ++itr )
map.insert( *itr, 0 );
}
}
/*!
- \brief Returns the string list of the existing resource names in the specified section.
- \param sec - Resource section name.
+ \brief Get all parameters name in specified section.
+ \param sec section name
+ \return list of settings names
*/
QStringList QtxResourceMgr::parameters( const QString& sec ) const
{
typedef IMap<QString, int> PMap;
#endif
PMap pmap;
- ResListIterator it( myResources );
- it.toLast();
- for ( ; it.current(); --it ) {
- QStringList lst = it.current()->parameters( sec );
+ ResList lst;
+ for ( ResList::const_iterator itr = myResources.begin(); itr != myResources.end(); ++itr )
+ lst.prepend( *itr );
+
+ for ( ResList::const_iterator it = lst.begin(); it != lst.end(); ++it )
+ {
+ QStringList lst = (*it)->parameters( sec );
for ( QStringList::const_iterator itr = lst.begin(); itr != lst.end(); ++itr )
pmap.insert( *itr, 0, false );
}
}
/*!
- \return path of file from directory built by parameter
- \return QString::null if built path doesn't exist
- \param sec - name of section
- \param prefix - name of parameter containing some path
- \param name - name of file
+ \brief Get absolute path to the file which name is defined by the parameter.
+
+ The file name is defined by \a name argument, while directory name is retrieved
+ from resources parameter \a prefix of section \a sec. Both directory and file name
+ can be relative. If the directory is relative, it is calculated from the initial
+ resources file name. Directory parameter can contain environment
+ variables, which are substituted automatically.
+
+ \param sec section name
+ \param prefix parameter containing directory name
+ \param name file name
+ \return absolute file path or null QString if file does not exist
*/
QString QtxResourceMgr::path( const QString& sect, const QString& prefix, const QString& name ) const
{
QString res;
- for ( ResListIterator it( myResources ); it.current() && res.isEmpty(); ++it )
- res = it.current()->path( sect, prefix, name );
+ for ( ResList::const_iterator it = myResources.begin(); it != myResources.end() && res.isEmpty(); ++it )
+ res = (*it)->path( sect, prefix, name );
return res;
}
/*!
- \return section corresponding to resources paths
+ \brief Get application resources section name.
+
+ By default, application resources section name is "resources" but
+ it can be changed by setting the corresponding resources manager option.
+
+ \return section corresponding to the resources directories
+ \sa option(), setOption()
*/
QString QtxResourceMgr::resSection() const
{
}
/*!
- \return section corresponding to language settings
+ \brief Get application language section name.
+
+ By default, application language section name is "language" but
+ it can be changed by setting the corresponding resources manager option.
+
+ \return section corresponding to the application language settings
+ \sa option(), setOption()
*/
QString QtxResourceMgr::langSection() const
{
}
/*!
- \return default image used when during loading the image file doesn't exist
+ \brief Get default pixmap.
+
+ Default pixmap is used when requested pixmap resource is not found.
+
+ \return default pixmap
+ \sa setDefaultPixmap(), loadPixmap()
*/
QPixmap QtxResourceMgr::defaultPixmap() const
{
}
/*!
- Set image as default image used when during loading the image file doesn't exist
- \param pix - image
+ \brief Set default pixmap.
+
+ Default pixmap is used when requested pixmap resource is not found.
+
+ \param pix default pixmap
+ \sa defaultPixmap(), loadPixmap()
*/
void QtxResourceMgr::setDefaultPixmap( const QPixmap& pix )
{
}
/*!
- \return image loaded from file
- \param prefix - name of parameter containing some path
- \param name - name of file
+ \brief Load pixmap resource.
+ \param prefix parameter which refers to the resources directory (directories)
+ \param name pixmap file name
+ \return pixmap loaded from the file
+ \sa defaultPixmap(), setDefaultPixmap()
*/
QPixmap QtxResourceMgr::loadPixmap( const QString& prefix, const QString& name ) const
{
}
/*!
- \return image loaded from file
- \param prefix - name of parameter containing some path
- \param name - name of file
- \param useDef - indicates if it is possible to use default image returning by defaultPixmap() method.
- If it is false, the empty pixmap will be used as default
- \sa defaultPixmap()
+ \brief Load pixmap resource.
+ \overload
+ \param prefix parameter which refers to the resources directory (directories)
+ \param name pixmap file name
+ \param useDef if \c false, default pixmap is not returned if resource is not found,
+ in this case null pixmap is returned instead
+ \return pixmap loaded from the file
+ \sa defaultPixmap(), setDefaultPixmap()
*/
QPixmap QtxResourceMgr::loadPixmap( const QString& prefix, const QString& name, const bool useDef ) const
{
}
/*!
- Finds in all sections an existing path corresponding to 'prefix' parameter
- and load image with name 'name' from this folder
-
- \return image loaded from file
- \param prefix - name of parameter containing some path
- \param name - name of file
- \param defPix - default image used when file doesn't exist
+ \brief Load pixmap resource.
+ \overload
+ \param prefix parameter which refers to the resources directory (directories)
+ \param name pixmap file name
+ \param defPix default which should be used if the resource file doesn't exist
+ \return pixmap loaded from the file
+ \sa defaultPixmap(), setDefaultPixmap()
*/
QPixmap QtxResourceMgr::loadPixmap( const QString& prefix, const QString& name, const QPixmap& defPix ) const
{
initialize();
QPixmap pix;
- for ( ResListIterator it( myResources ); it.current() && pix.isNull(); ++it )
- pix = it.current()->loadPixmap( resSection(), prefix, name );
+ for ( ResList::const_iterator it = myResources.begin(); it != myResources.end() && pix.isNull(); ++it )
+ pix = (*it)->loadPixmap( resSection(), prefix, name );
if ( pix.isNull() )
pix = defPix;
return pix;
}
/*!
- Loads translator for language
- Name of translator file is constructed by list returning by option "translators" or,
- if it is empty, by predefined pattern "%P_msg_%L.qm". It is recommended to used in translators
- name the strings %A, %P, %L whose will be replaced by application name, prefix and language name correspondingly
+ \brief Load translation files according to the specified language.
+
+ Names of the translation files are calculated according to the pattern specified
+ by the "translators" option (this option is read from the section "language" of resources files).
+ By default, "%P_msg_%L.qm" pattern is used.
+ Keywords \%A, \%P, \%L in the pattern are substituted by the application name, prefix and language name
+ correspondingly.
+ For example, for prefix "SUIT" an language "en", all translation files "SUIT_msg_en.qm" are searched and
+ loaded.
- \param pref - name of parameter containing path to translator's file.
- If it is empty, the list of parameters from resource section ( resSection() )
- is used.
+ If prefix is empty or null string, all translation files specified in the "resources" section of resources
+ files are loaded (actually, the section is retrieved from resSection() method).
+ If language is not specified, it is retrieved from the langSection() method, and if the latest is also empty,
+ by default "en" (English) language is used.
- \param l - name of language. If it is empty, then value of parameter "language"
- from language section ( langSection() ) is used. If it is also empty, then
- predefined name "en" is used
+ \param pref parameter which defines translation context (for example, package name)
+ \param l language name
- \sa resSection(), langSection()
+ \sa resSection(), langSection(), loadTranslators()
*/
void QtxResourceMgr::loadLanguage( const QString& pref, const QString& l )
{
if ( lang.isEmpty() )
{
lang = QString( "en" );
- qWarning( QString( "Language not specified. Assumed: %1" ).arg( lang ) );
+ qWarning( "Language not specified. Assumed: %s", (const char*)lang.toLatin1() );
}
substMap.insert( 'L', lang );
QString trs;
if ( value( langSection(), "translators", trs, false ) && !trs.isEmpty() )
{
- QStringList translators = QStringList::split( "|", option( "translators" ) );
- QStringList newTranslators = QStringList::split( "|", trs );
- for ( uint i = 0; i < newTranslators.count(); i++ )
- if ( translators.find( newTranslators[i] ) == translators.end() )
+ QStringList translators = option( "translators" ).split( "|", QString::SkipEmptyParts );
+ QStringList newTranslators = trs.split( "|", QString::SkipEmptyParts );
+ for ( int i = 0; i < (int)newTranslators.count(); i++ )
+ {
+ if ( translators.indexOf( newTranslators[i] ) < 0 )
translators += newTranslators[i];
+ }
setOption( "translators", translators.join( "|" ) );
}
- QStringList trList = QStringList::split( "|", option( "translators" ) );
+ QStringList trList = option( "translators" ).split( "|", QString::SkipEmptyParts );
if ( trList.isEmpty() )
{
trList.append( "%P_msg_%L.qm" );
- qWarning( QString( "Translators not defined. Assumed: %1" ).arg( trList.first() ) );
+ qWarning( "Translators not defined. Assumed: %s", (const char*)trList[0].toLatin1() );
}
QStringList prefixList;
QStringList trs;
for ( QStringList::const_iterator it = trList.begin(); it != trList.end(); ++it )
- trs.append( substMacro( *it, substMap ).stripWhiteSpace() );
+ trs.append( substMacro( *it, substMap ).trimmed() );
loadTranslators( prefix, trs );
}
}
/*!
- Loads translators by path and list of files
-
- \param prefix - value of this parameter must contain path
- \param translators - list of translators' files
+ \brief Load translation files for the specified translation context.
+ \param prefix parameter which defines translation context (for example, package name)
+ \param translators list of translation files
+ \sa loadLanguage()
*/
void QtxResourceMgr::loadTranslators( const QString& prefix, const QStringList& translators )
{
initialize();
+ ResList lst;
+ for ( ResList::iterator iter = myResources.begin(); iter != myResources.end(); ++iter )
+ lst.prepend( *iter );
+
QTranslator* trans = 0;
- ResListIterator it( myResources );
- it.toLast();
- for ( ; it.current(); --it )
+
+ for ( ResList::iterator it = lst.begin(); it != lst.end(); ++it )
{
for ( QStringList::const_iterator itr = translators.begin(); itr != translators.end(); ++itr )
{
- trans = it.current()->loadTranslator( resSection(), prefix, *itr );
+ trans = (*it)->loadTranslator( resSection(), prefix, *itr );
if ( trans )
{
if ( !myTranslator[prefix].contains( trans ) )
myTranslator[prefix].append( trans );
- qApp->installTranslator( trans );
+ QApplication::instance()->installTranslator( trans );
}
}
}
}
/*!
- Loads translator by path and file name
-
- \param prefix - value of this parameter must contain path
- \param name - name of translator file
+ \brief Load translation file.
+ \param prefix parameter which defines translation context (for example, package name)
+ \param name translator file name
+ \sa loadLanguage(), loadTranslators()
*/
void QtxResourceMgr::loadTranslator( const QString& prefix, const QString& name )
{
initialize();
QTranslator* trans = 0;
- ResListIterator it( myResources );
- it.toLast();
- for ( ; it.current(); --it )
+ ResList::iterator it = myResources.end();
+ for ( ; it != myResources.begin(); --it )
{
- trans = it.current()->loadTranslator( resSection(), prefix, name );
+ trans = (*it)->loadTranslator( resSection(), prefix, name );
if ( trans )
{
if ( !myTranslator[prefix].contains( trans ) )
myTranslator[prefix].append( trans );
- qApp->installTranslator( trans );
+ QApplication::instance()->installTranslator( trans );
}
}
}
/*!
- Remove all translators corresponding to prefix
-
- \param prefix - parameter containing path
+ \brief Remove all translators corresponding to the specified translation context.
+ \param prefix parameter which defines translation context (for example, package name)
*/
void QtxResourceMgr::removeTranslators( const QString& prefix )
{
if ( !myTranslator.contains( prefix ) )
return;
- for ( TransListIterator it( myTranslator[prefix] ); it.current(); ++it )
+ for ( TransList::iterator it = myTranslator[prefix].begin(); it != myTranslator[prefix].end(); ++it )
{
- qApp->removeTranslator( it.current() );
- delete it.current();
+ QApplication::instance()->removeTranslator( *it );
+ delete *it;
}
myTranslator.remove( prefix );
}
/*!
- Moves translators corresponding to prefix to the top of translator stack
-
- \param prefix - parameter containing path
+ \brief Move all translators corresponding to the specified translation context
+ to the top of translators stack (increase their priority).
+ \param prefix parameter which defines translation context (for example, package name)
*/
void QtxResourceMgr::raiseTranslators( const QString& prefix )
{
if ( !myTranslator.contains( prefix ) )
return;
- for ( TransListIterator it( myTranslator[prefix] ); it.current(); ++it )
+ for ( TransList::iterator it = myTranslator[prefix].begin(); it != myTranslator[prefix].end(); ++it )
{
- qApp->removeTranslator( it.current() );
- qApp->installTranslator( it.current() );
+ QApplication::instance()->removeTranslator( *it );
+ QApplication::instance()->installTranslator( *it );
}
}
/*!
- Copies all resources to user resources, so that they will be saved in user home folder
+ \brief Copy all parameters to the user resources in order to
+ saved them lately in the user home folder.
*/
void QtxResourceMgr::refresh()
{
}
/*!
- \brief Sets the resource directories list except user home directory and clear resources
+ \brief Set the resource directories (where global confguration files are searched).
+
+ This function also clears all currently set resources.
+
+ \param dl directories list
*/
void QtxResourceMgr::setDirList( const QStringList& dl )
{
myDirList = dl;
- for ( ResListIterator it( myResources ); it.current(); ++it )
- delete it.current();
+ for ( ResList::iterator it = myResources.begin(); it != myResources.end(); ++it )
+ delete *it;
myResources.clear();
}
/*!
- Sets resource value
- \param sect - name of section
- \param name - name of parameter
- \param val - string representation of value
+ \brief Set parameter value.
+ \param sect section name
+ \param name parameter name
+ \param val parameter value
*/
void QtxResourceMgr::setResource( const QString& sect, const QString& name, const QString& val )
{
}
/*!
- \return name of resource file, which is being found in user home directory
- \param appName - name of application
- \param for_load - flag indicating that file will be used for loading (true) or for saving(false)
- It makes possible to use different resource files for loading and saving
+ \brief Get user configuration file name.
+
+ This method can be redefined in the successor class to customize the user configuration file name.
+ User configuration file is always situated in the user's home directory. By default .<appName>rc
+ file is used on Linux (e.g. .MyApprc) and <appName>.<format> under Windows (e.g. MyApp.xml).
+
+ Parameter \a for_load (not used in default implementation) specifies the usage mode, i.e. if
+ user configuration file is opened for reading or writing. This allows customizing a way of application
+ resources initializing (for example, if the user configuraion file includes version number and there is
+ no file corresponding to this version in the user's home directory, it could be good idea to try
+ the configuration file from the previous versions of the application).
+
+ \param appName application name
+ \param for_load boolean flag indicating that file is opened for loading or saving (not used)
+ \return user configuration file name
+ \sa globalFileName()
*/
QString QtxResourceMgr::userFileName( const QString& appName, const bool /*for_load*/ ) const
{
QString fileName;
- QString pathName = QDir::homeDirPath();
+ QString pathName = QDir::homePath();
#ifdef WIN32
fileName = QString( "%1.%2" ).arg( appName ).arg( currentFormat() );
}
/*!
- \return name of resource file, which is being found in all resource directories, except user home
+ \brief Get global configuration file name.
+
+ This method can be redefined in the successor class to customize the global configuration file name.
+ Global configuration files are searched in the directories specified by the application resources
+ environment variable (e.g. MyAppResources). By default <appName>.<format> file name is used
+ (e.g. MyApp.xml).
+
+ \param appName application name
+ \return global configuration file name
+ \sa userFileName()
*/
QString QtxResourceMgr::globalFileName( const QString& appName ) const
{
}
/*!
- Replaced substrings by pattern %A, %B, etc by values from map
+ \brief Perform substitution of the patterns like \%A, \%B, etc by values from the map.
+
+ Used by loadLanguage().
- \param src - string to be processed
- \param substMap - map of values for replacing
+ \param src sring to be processed
+ \param substMap map of values for replacing
+ \return processed string
*/
QString QtxResourceMgr::substMacro( const QString& src, const QMap<QChar, QString>& substMap ) const
{
QRegExp rx( "%[A-Za-z%]" );
int idx = 0;
- while ( ( idx = rx.search( trg, idx ) ) >= 0 )
+ while ( ( idx = rx.indexIn( trg, idx ) ) >= 0 )
{
QChar spec = trg.at( idx + 1 );
QString subst;
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
+// File: QtxResourceMgr.h
+// Author: Alexander SOLOVYEV, Sergey TELKOV
+
#ifndef QTX_RESOURCEMGR_H
#define QTX_RESOURCEMGR_H
#include "Qtx.h"
-#include <qmap.h>
-#include <qcolor.h>
-#include <qfont.h>
-#include <qpixmap.h>
-#include <qstringlist.h>
-#include <qtranslator.h>
-#include <qvaluelist.h>
+#ifndef QTX_NO_INDEXED_MAP
+#include "QtxMap.h"
+#endif
+
+#include <QMap>
+#include <QList>
+#include <QByteArray>
+#include <QStringList>
+#include <QFont>
+#include <QColor>
+#include <QPixmap>
-class QPixmap;
+class QTranslator;
#ifdef WIN32
#pragma warning( disable:4251 )
#endif
-/*!
- Class: QtxResourceMgr
-*/
-
class QTX_EXPORT QtxResourceMgr
{
class IniFormat;
public:
class Format;
- template <class Key, class Value> class IMap;
- template <class Key, class Value> class IMapIterator;
- template <class Key, class Value> class IMapConstIterator;
-
#ifdef QTX_NO_INDEXED_MAP
- typedef QMap<QString, QString> Section;
+ typedef QMap<QString, QString> Section; //!< resource section
#else
- typedef IMap<QString, QString> Section;
+ typedef IMap<QString, QString> Section; //!< resource section
#endif
public:
bool value( const QString&, const QString&, bool& ) const;
bool value( const QString&, const QString&, QColor& ) const;
bool value( const QString&, const QString&, QFont& ) const;
+ bool value( const QString&, const QString&, QByteArray& ) const;
bool value( const QString&, const QString&, QString&, const bool = true ) const;
int integerValue( const QString&, const QString&, const int = 0 ) const;
QFont fontValue( const QString&, const QString&, const QFont& = QFont() ) const;
QColor colorValue( const QString&, const QString&, const QColor& = QColor() ) const;
QString stringValue( const QString&, const QString&, const QString& = QString::null ) const;
+ QByteArray byteArrayValue( const QString&, const QString&, const QByteArray& = QByteArray() ) const;
bool hasSection( const QString& ) const;
bool hasValue( const QString&, const QString& ) const;
void setValue( const QString&, const QString&, const QFont& );
void setValue( const QString&, const QString&, const QColor& );
void setValue( const QString&, const QString&, const QString& );
+ void setValue( const QString&, const QString&, const QByteArray& );
void remove( const QString& );
void remove( const QString&, const QString& );
QString substMacro( const QString&, const QMap<QChar, QString>& ) const;
private:
- typedef QPtrList<Resources> ResList;
- typedef QPtrList<Format> FormatList;
- typedef QMap<QString, QString> OptionsMap;
- typedef QPtrListIterator<Resources> ResListIterator;
- typedef QPtrListIterator<Format> FormatListIterator;
-
- typedef QPtrList<QTranslator> TransList;
- typedef QMap<QString, TransList> TransListMap;
- typedef QPtrListIterator<QTranslator> TransListIterator;
+ typedef QList<Resources*> ResList;
+ typedef QList<QTranslator*> TransList;
+ typedef QList<Format*> FormatList;
+ typedef QMap<QString, QString> OptionsMap;
+ typedef QMap<QString, TransList> TransListMap;
private:
- QString myAppName;
- QStringList myDirList;
- FormatList myFormats;
- OptionsMap myOptions;
- ResList myResources;
- bool myCheckExist;
- TransListMap myTranslator;
- QPixmap myDefaultPix;
- bool myIsPixmapCached;
-
- bool myIsIgnoreUserValues;
+ QString myAppName; //!< application name
+ QStringList myDirList; //!< list of resources directories
+ FormatList myFormats; //!< list of formats
+ OptionsMap myOptions; //!< options map
+ ResList myResources; //!< resources list
+ bool myCheckExist; //!< "check existance" flag
+ TransListMap myTranslator; //!< map of loaded translators
+ QPixmap myDefaultPix; //!< default icon
+ bool myIsPixmapCached; //!< "cached pixmaps" flag
+
+ bool myIsIgnoreUserValues; //!< "ignore user values" flag
friend class QtxResourceMgr::Format;
};
-/*!
- Class: QtxResourceMgr::Format
-*/
-
class QTX_EXPORT QtxResourceMgr::Format
{
public:
virtual bool save( const QString&, const QMap<QString, Section>& ) = 0;
private:
- QString myFmt;
- QMap<QString, QString> myOpt;
-};
-
-/*!
- Class: QtxResourceMgr::Resources
-*/
-
-class QtxResourceMgr::Resources
-{
-public:
- Resources( const QtxResourceMgr*, const QString& );
- virtual ~Resources();
-
- QString file() const;
- void setFile( const QString& );
-
- QString value( const QString&, const QString&, const bool ) const;
- void setValue( const QString&, const QString&, const QString& );
-
- bool hasSection( const QString& ) const;
- bool hasValue( const QString&, const QString& ) const;
-
- void removeSection( const QString& );
- void removeValue( const QString&, const QString& );
-
- QPixmap loadPixmap( const QString&, const QString&, const QString& ) const;
- QTranslator* loadTranslator( const QString&, const QString&, const QString& ) const;
-
- QString environmentVariable( const QString&, int&, int& ) const;
- QString makeSubstitution( const QString&, const QString&, const QString& ) const;
-
- void clear();
-
- QStringList sections() const;
- QStringList parameters( const QString& ) const;
-
- QString path( const QString&, const QString&, const QString& ) const;
-
-protected:
- QtxResourceMgr* resMgr() const;
-
-private:
- Section& section( const QString& );
- const Section& section( const QString& ) const;
-
- QString fileName( const QString&, const QString&, const QString& ) const;
-
-private:
- typedef QMap<QString, Section> SectionMap;
-
-private:
- SectionMap mySections;
- QString myFileName;
- QMap<QString,QPixmap> myPixmapCache;
- QtxResourceMgr* myMgr;
-
- friend class QtxResourceMgr::Format;
-};
-
-/*!
- Class: QtxResourceMgr::IMapIterator
-*/
-
-template <class Key, class Value> class QtxResourceMgr::IMapIterator
-{
-public:
- IMapIterator() : myMap( 0 ), myIndex( 0 ) { init(); }
- IMapIterator( const IMap<Key,Value>* m ) : myMap( const_cast< IMap<Key,Value>* >( m ) ), myIndex( 0 ) { init(); }
- IMapIterator( const IMapIterator& i ) : myMap( i.myMap ), myIndex( i.myIndex ) { init(); }
-
- bool operator==( const IMapIterator& i ) { return !operator!=( i ); }
- bool operator!=( const IMapIterator& i ) { return !myMap || myMap != i.myMap || myIndex != i.myIndex; }
-
- operator bool() const { return myIndex >= 0; }
-
- const Key& key() const { return myMap->key( myIndex ); }
- Value& data() { return myMap->value( myIndex ); }
- const Value& data() const { return myMap->value( myIndex ); }
-
- Value& operator*() { return data(); }
-
- IMapIterator& operator++() { myIndex++; init(); return *this; }
- IMapIterator operator++( int ) { IMapIterator i = *this; myIndex++; init(); return i; }
- IMapIterator& operator--() { myIndex--; init(); return *this; }
- IMapIterator operator--( int ) { IMapIterator i = *this; myIndex--; init(); return i; }
-
-private:
- IMapIterator( const IMap<Key,Value>* m, const int index ) : myMap( const_cast< IMap<Key,Value>* >( m ) ), myIndex( index ) { init(); }
- void init() { if ( !myMap || myIndex >= myMap->count() ) myIndex = -1; }
-
-private:
- IMap<Key,Value>* myMap;
- int myIndex;
-
- friend class IMap<Key, Value>;
- friend class IMapConstIterator<Key, Value>;
-};
-
-/*!
- Class: QtxResourceMgr::IMapConstIterator
-*/
-
-template <class Key, class Value> class QtxResourceMgr::IMapConstIterator
-{
-public:
- IMapConstIterator() : myMap( 0 ), myIndex( 0 ) { init(); }
- IMapConstIterator( const IMap<Key,Value>* m ) : myMap( const_cast< IMap<Key,Value>* >( m ) ), myIndex( 0 ) { init(); }
- IMapConstIterator( const IMapConstIterator& i ) : myMap( i.myMap ), myIndex( i.myIndex ) { init(); }
- IMapConstIterator( const IMapIterator<Key, Value>& i ) : myMap( i.myMap ), myIndex( i.myIndex ) { init(); }
-
- bool operator==( const IMapConstIterator& i ) { return !operator!=( i ); }
- bool operator!=( const IMapConstIterator& i ) { return !myMap || myMap != i.myMap || myIndex != i.myIndex; }
-
- operator bool() const { return myIndex >= 0; }
-
- const Key& key() const { return myMap->key( myIndex ); }
- const Value& data() const { return myMap->value( myIndex ); }
-
- const Value& operator*() const { return data(); }
-
- IMapConstIterator& operator++() { myIndex++; init(); return *this; }
- IMapConstIterator operator++( int ) { IMapConstIterator i = *this; myIndex++; init(); return i; }
- IMapConstIterator& operator--() { myIndex--; init(); return *this; }
- IMapConstIterator operator--( int ) { IMapConstIterator i = *this; myIndex--; init(); return i; }
-
-private:
- IMapConstIterator( const IMap<Key,Value>* m, const int index ): myMap( const_cast< IMap<Key,Value>* >( m ) ), myIndex( index ) { init(); }
- void init() { if ( !myMap || myIndex >= myMap->count() ) myIndex = -1; }
-
-private:
- IMap<Key,Value>* myMap;
- int myIndex;
-
- friend class IMap<Key,Value>;
-};
-
-/*!
- Class: QtxResourceMgr::IMap
-*/
-
-template <class Key, class Value> class QtxResourceMgr::IMap
-{
-public:
- typedef IMapIterator<Key,Value> Iterator;
- typedef IMapConstIterator<Key,Value> ConstIterator;
-
-public:
- IMap() {}
- IMap( const IMap& m ) : myKeys( m.myKeys ), myData( m.myData ) {}
- IMap& operator=( const IMap& m ) { myKeys = m.myKeys; myData = m.myData; return *this; }
-
- int count() const { return myData.count(); }
- int size() const { return myData.count(); }
- bool empty() const { return myData.empty(); }
- bool isEmpty() const { return myData.empty(); }
-
- void clear() { myKeys.clear(); myData.clear(); }
-
- QValueList<Key> keys() const { return myKeys; }
- QValueList<Value> values() const { QValueList<Value> l; for ( int i = 0; i < count(); i++ ) l.append( value( i ) ); return l; }
- bool contains ( const Key& key ) const { return myData.contains( key ); }
-
- Iterator begin() { return Iterator( this ); }
- Iterator end() { return Iterator( this, count() ); }
- ConstIterator begin() const { return ConstIterator( this ); }
- ConstIterator end() const { return ConstIterator( this, count() ); }
-
- Iterator insert( const Key& key, const Value& value, bool overwrite = true )
- {
- if ( myData.find( key ) == myData.end() || overwrite )
- {
- if ( myData.find( key ) != myData.end() && overwrite )
- myKeys.remove( myKeys.find( key ) );
- myKeys.append( key );
- myData[key] = value;
- }
- return Iterator( this, index( key ) );
- }
-
- Iterator replace( const Key& key, const Value& value )
- {
- if ( myData.find( key ) == myData.end() )
- myKeys.append( key );
- myData[ key ] = value;
- return Iterator( this, index( key ) );
- }
-
- int index( const Key& key ) const { return myKeys.findIndex( key ); }
- Iterator at( const int index ) { return Iterator( this, index ); }
- ConstIterator at( const int index ) const { return ConstIterator( this, index ); }
-
- Key& key( const int index )
- {
- if ( index < 0 || index >= (int)myKeys.count() )
- return dummyKey;
- return myKeys[index];
- }
-
- Value& value( const int index )
- {
- if ( index < 0 || index >= (int)myKeys.count() )
- return dummyValue;
- return myData[ myKeys[index] ];
- }
-
- Value& operator[]( const Key& key )
- {
- if ( myData.find( key ) == myData.end() )
- insert( key, Value() );
- return myData[ key ];
- }
-
- const Value& operator[]( const Key& key ) const
- {
- if ( myData.find( key ) == myData.end() )
- return dummyValue;
- return myData[ key ];
- }
-
- void erase( Iterator it ) { remove( it ); }
- void erase( const Key& key ) { remove( key ); }
- void erase( const int index ) { remove( index ); }
- void remove( Iterator it ) { if ( it.myMap != this ) return; remove( it.myIndex ); }
- void remove( const Key& key ) { remove( index( key ) ); }
- void remove( const int index )
- {
- if ( index >= 0 && index < (int)myKeys.count() )
- {
- myData.remove( myKeys[ index ] );
- myKeys.remove( myKeys.at( index ) );
- }
- }
-
-private:
- QValueList<Key> myKeys;
- QMap<Key,Value> myData;
- Key dummyKey;
- Value dummyValue;
-
- friend class IMapIterator<Key,Value>;
- friend class IMapConstIterator<Key,Value>;
+ QString myFmt; //!< format name
+ QMap<QString, QString> myOpt; //!< options map
};
-#endif
+#endif // QTX_RESOURCEMGR_H
#include "QtxSplash.h"
-#include <qapplication.h>
-#include <qpainter.h>
-#include <qpixmap.h>
-#include <qmessagebox.h>
-
-const int _PROGRESS_EVENT = QEvent::User + 10;
-const int _PROGRESS_WIDTH = 10;
+#include <QApplication>
+#include <QPainter>
+#include <QMessageBox>
+#include <QDesktopWidget>
/*!
- Class ProgressEvent [ internal ].
+ \class ProgressEvent
+ \internal
+ \brief Progress change custom event.
*/
-class ProgressEvent: public QCustomEvent
+
+class ProgressEvent: public QEvent
{
public:
+ /*!
+ \brief Constructor.
+ \param msg progress message
+ \param progress current progress (for example, in %)
+ */
ProgressEvent( const QString& msg, const int progress = 0 )
- : QCustomEvent( id() ),
+ : QEvent( (QEvent::Type)id() ),
myMessage( msg ),
myProgress( progress )
{}
- QString message() const { return myMessage; }
- int progress() const { return myProgress; }
- static int id() { return _PROGRESS_EVENT; }
+ /*!
+ \brief Get progress message.
+ \return message
+ */
+ QString message() const { return myMessage; }
+ /*!
+ \brief Get current progress.
+ \return current progress
+ */
+ int progress() const { return myProgress; }
+ /*!
+ \brief Get message identifier.
+ \return custom message ID
+ */
+ static int id() { return QEvent::User + 10; }
private:
QString myMessage;
int myProgress;
};
-// Only one instance of splash screen is allowed
+/*!
+ \class QtxSplash
+ \brief The QtxSplash widget provides a splash screen that can be shown during application startup..
+
+ A splash screen is a widget that is usually displayed when an application is being started.
+ Splash screens are often used for applications that have long start up times to provide
+ the user with feedback that the application is loading.
+
+ Only one instance of the QtxSplash widget can be created. To access to the splash screen widget,
+ use static method QtxSplash::splash(), which creates and instance of the QtxSplash widget if
+ necessary and returns pointer to it. You should not destroy yhis instance - it is done automatically
+ after application main window is shown. Just use methods finish() to make splash screen wait untill
+ main window is shown.
+
+ The splash screen appears in the center of the screen. The most common usage is to show a splash
+ screen before the main widget is displayed on the screen.
+ For example,
+ \code
+ int main(int argc, char *argv[])
+ {
+ QApplication app(argc, argv);
+ QPixmap pixmap(":/splash.png");
+ QtxSplash* splash = QtxsSplash::splash(pixmap);
+ splash->show();
+ app.processEvents();
+ ... // do application loading and initialization
+ MainWindow window;
+ window.show();
+ splash->finish(&window);
+ return app.exec();
+ }
+ \endcode
+
+ The user can hide the splash screen by clicking on it with the mouse. Since the splash screen is
+ typically displayed before the event loop has started running, it is necessary to periodically call
+ QApplication::processEvents() to receive the mouse clicks.
+ This feature can be switched off by using method setHideOnClick() with \c false parameter.
+
+ It is sometimes useful to update the splash screen with messages and/or progress information,
+ for example, announcing connections established or modules loaded as the application starts up.
+ QtxSplash class provides the functionality to show status messages and(or) progress bar.
+
+ \code
+ QPixmap pixmap(":/splash.png");
+ QtxSplash* splash = QtxSplash::splash(pixmap);
+ splash->setProgress(0, 5);
+ splash->show();
+ app.processEvents();
+ // doing first step
+ splash->message("Step 1");
+ splash->ress(1);
+ qApp->processEvents();
+ // ... perform some actions
+ // doing second step
+ splash->message("Step 2");
+ splash->setProgress(2);
+ qApp->processEvents();
+ // ... perform some actions
+ ... et cetera
+ \endcode
+
+ There is a static function QtxSplash::setStatus() which allows to put next status message
+ and progress with one call. It can substitue two calls: message() and setProgress().
+
+ QtxSplash class provides alos a lot of functions to set-up its behavior. Set progress
+ bar width with setProgressWidth() method, its position and direction with setProgressFlags().
+ It can be single-colored or gradient-colored. Use setProgressColors() method for this.
+ You can even set your own gradient scale with QLinearGradient and use it for the progress
+ bar coloring: setProgressGradient().
+
+ To change the progress bar and status message transparency, use setOpacity() function.
+ The methods setTextAlignment(), setTextColor() and setTextColors() can be used to change
+ the attributes of the status message.
+*/
+
+//! The only one instance of splash screen
QtxSplash* QtxSplash::mySplash = 0;
/*!
- Construct a splash screen that will display the \a pixmap.
+ \brief Constructor.
+ \brief Construct a splash screen that will display the \a pixmap.
+ \param pixmap splash screen pixmap
*/
QtxSplash::QtxSplash( const QPixmap& pixmap )
- : QWidget( 0, 0, WStyle_Customize | WStyle_StaysOnTop | WX11BypassWM | WStyle_NoBorder )
-{
- myAlignment = AlignBottom | AlignRight;
- myColor = white;
- myHideOnClick = false;
- myProgress = 0;
- myTotal = 0;
- myGradientType = Vertical;
- myError = 0;
- myStartColor = red;
-
+: QWidget( 0, Qt::SplashScreen | Qt::WindowStaysOnTopHint ),
+ myAlignment( Qt::AlignBottom | Qt::AlignRight ),
+ myColor( Qt::white ),
+ myHideOnClick( false ),
+ myProgress( 0 ),
+ myTotal( 0 ),
+ myStartColor( Qt::red ),
+ myGradientType( Vertical ),
+ myProgressWidth( 10 ),
+ myProgressFlags( BottomSide | LeftToRight ),
+ myMargin( 5 ),
+ myOpacity( 1.0 ),
+ myError( 0 ),
+ myGradientUsed( false )
+{
+ setAttribute( Qt::WA_DeleteOnClose, true );
setPixmap( pixmap );
}
/*!
- Destructor.
+ \brief Destructor.
*/
QtxSplash::~QtxSplash()
{
}
/*!
- Returns an only instance of splash screen.
- If \a px is valid sets this pixmap to the splash screen.
+ \brief Get the only instance of the splash screen widget.
+
+ If the splash screen widget does not exist yet, it is created with specified
+ pixmap. Otherwise, pixmap \a px is set to existing widget.
+
+ \param px splash screen pixmap
+ \return splash screen widget
*/
QtxSplash* QtxSplash::splash( const QPixmap& px )
{
}
/*!
- Sends the status message and (optionally) progress to the splash screen.
- Can be used, for example, from the progress thread.
+ \brief Send the status message and (optionally) current progress
+ to the splash screen.
+
+ This function can be used, for example, from an external thread
+ which checks the application loading progress.
+
+ \param msg progress status message
+ \param progress current progress
+ \sa message(), setProgress()
*/
-void QtxSplash::setStatus( const QString& msg,
- const int progress )
+void QtxSplash::setStatus( const QString& msg, const int progress )
{
if ( mySplash ) {
QApplication::postEvent( mySplash, new ProgressEvent( msg, progress ) );
- qApp->processEvents();
+ QApplication::instance()->processEvents();
}
}
/*!
- Sets error status and shows error message box to the user.
+ \brief Set error status and show error message box to the user.
+ \param error error message
+ \param title message box title
+ \param code error code
*/
void QtxSplash::error( const QString& error, const QString& title, const int code )
{
- printf("QtxSplash::error: %s\n",error.latin1());
if ( mySplash ) {
mySplash->setError( code );
QMessageBox::critical( mySplash,
error,
tr( "&OK" ) );
}
+ else {
+ printf( "QtxSplash::error: %s\n",error.toLatin1().constData() );
+ }
}
/*!
- Sets the pixmap that will be used as the splash screen's image to
- \a pixmap.
+ \brief Set the pixmap that will be used as the splash screen's image.
+ \param pixmap spash screen image pixmap
+ \sa pixmap()
*/
void QtxSplash::setPixmap( const QPixmap& pixmap )
{
- myPixmap = pixmap;
+ if ( pixmap.hasAlpha() ) {
+ QPixmap opaque( pixmap.size() );
+ QPainter p( &opaque );
+ p.fillRect( 0, 0, pixmap.width(), pixmap.height(), palette().background() );
+ p.drawPixmap( 0, 0, pixmap );
+ p.end();
+ myPixmap = opaque;
+ }
+ else {
+ myPixmap = pixmap;
+ }
QRect r( 0, 0, myPixmap.size().width(), myPixmap.size().height() );
resize( myPixmap.size() );
move( QApplication::desktop()->screenGeometry().center() - r.center() );
- repaint();
+ if ( !isVisible() )
+ drawContents();
+ else
+ repaint();
}
/*!
- Returns the pixmap that is used in the splash screen.
+ \brief Get the pixmap that is used as the splash screen's image.
+ \return spash screen image pixmap
+ \sa setPixmap()
*/
QPixmap QtxSplash::pixmap() const
{
}
/*!
- Sets/clear the 'hide on mouse click' flag.
- Default is FALSE.
+ \brief Set/clear the 'hide on mouse click' flag.
+
When this flag is set, user can hide the splash screen window
by clicking on it with mouse.
But for this to work it is necessary to call periodically
QApplication::processEvents() in order to allow event loop to process
events because usually main application loop is not yet started
at that moment.
+
+ By default this flag is set to \c false.
+
+ \param on new flag state
+ \sa hideOnClick()
*/
void QtxSplash::setHideOnClick( const bool on )
{
}
/*!
- Returns the 'hide on mouse click' flag.
+ \brief Get the 'hide on mouse click' flag.
+ \return 'hide on mouse click' flag
+ \sa setHideOnClick()
*/
bool QtxSplash::hideOnClick() const
{
}
/*!
- Sets total progress steps to \a total.
+ \brief Set total progress steps to \a total.
+ \param total total number of progress steps
+ \sa totalSteps(), setProgress(), progress()
*/
void QtxSplash::setTotalSteps( const int total )
{
}
/*!
- Return total progress steps number.
- \sa setTotalSteps(), setProgress()
+ \brief Get total progress steps number.
+ \return total number of progress steps
+ \sa setTotalSteps(), setProgress(), progress()
*/
int QtxSplash::totalSteps() const
{
}
/*!
- Sets progress to \a progress.
+ \brief Set current progress.
+ \param progress current progress
+ \sa progress(), setTotalSteps(), setTotalSteps(),
*/
void QtxSplash::setProgress( const int progress )
{
- myProgress = progress;
+ myProgress = progress > 0 ? progress : 0;
repaint();
}
/*!
- Return current progress.
- \sa setProgress(), setTotalSteps()
+ \brief Get current progress.
+ \return current progress
+ \sa setProgress(), setTotalSteps(), setTotalSteps(),
*/
int QtxSplash::progress() const
{
}
/*!
- Sets progress to \a progress and total progress steps to \a total.
+ \brief Set current progress to \a progress and total number of
+ progress steps to \a total.
+ \param progress current progress
+ \param total total number of progress steps
*/
void QtxSplash::setProgress( const int progress, const int total )
{
myTotal = total;
- myProgress = progress;
+ myProgress = progress > 0 ? progress : 0;
+ repaint();
+}
+
+/*!
+ \brief Set margin (a border width).
+ \param margin new margin width
+ \sa margin()
+*/
+void QtxSplash::setMargin( const int margin )
+{
+ myMargin = margin > 0 ? margin : 0;
+ repaint();
+}
+
+/*!
+ \brief Get margin (a border width).
+ \return current margin width
+ \sa setMargin()
+*/
+int QtxSplash::margin() const
+{
+ return myMargin;
+}
+
+/*!
+ \brief Set progress bar width.
+ \param width new progress bar width
+ \sa progressWidth()
+*/
+void QtxSplash::setProgressWidth( const int width )
+{
+ myProgressWidth = width > 0 ? width : 0;
repaint();
}
/*!
- Sets progress bar colors to \a startColor and \a endColor.
- If the colors differ the gradient color bar is drawed.
- If the \a endColor is not valid, \a startColor is used instead.
- \a gradientType sets the type of gradient to be used for progress
- bar - horizontal or vertical. Default is vertical.
+ \brief Get progress bar width.
+ \return current progress bar width
+ \sa setProgressWidth()
*/
-void QtxSplash::setProgressColors( const QColor& startColor,
- const QColor& endColor,
- const int gradientType )
+int QtxSplash::progressWidth() const
{
- myStartColor = startColor;
+ return myProgressWidth;
+}
+
+/*!
+ \brief Set progress bar position and direction.
+
+ By default, progress bar is displayed at the bottom side and
+ shows progress from left to right.
+
+ \param flags ORed progress bar flags (QtxSplash::ProgressBarFlags)
+ \sa progressFlags()
+*/
+void QtxSplash::setProgressFlags( const int flags )
+{
+ myProgressFlags = flags;
+ if ( !( myProgressFlags & ( LeftSide | RightSide | TopSide | BottomSide ) ) )
+ myProgressFlags |= BottomSide;
+ if ( !( myProgressFlags & ( LeftToRight | RightToLeft ) ) )
+ myProgressFlags |= LeftToRight ;
+ repaint();
+}
+
+/*!
+ \brief Get progress bar flags: position and direction.
+ \return ORed progress bar flags (QtxSplash::ProgressBarFlags)
+ \sa setProgressFlags()
+*/
+int QtxSplash::progressFlags() const
+{
+ return myProgressFlags;
+}
+
+/*!
+ \brief Set progress bar colors.
+
+ If the colors differ the gradient color bar is drawn.
+
+ If the \a endColor is not valid, \a startColor is used instead
+ (no gradient coloring).
+
+ The parameter \a gradientType defines the type of gradient
+ to be drawn - horizontal or vertical. Default is vertical.
+
+ Note, that methods setProgressGradient() and setProgressColors() are
+ alternative. Only the latest used is taken into account.
+
+ \param startColor start gradient color (or mono-color)
+ \param endColor end gradient color
+ \param gradientType gradient type (QtxSplash::GradientType)
+ \sa progressColors(), setProgressGradient()
+*/
+void QtxSplash::setProgressColors( const QColor& startColor,
+ const QColor& endColor,
+ const GradientType gradientType )
+{
+ if ( startColor.isValid() )
+ myStartColor = startColor;
myEndColor = endColor;
myGradientType = gradientType;
+ myGradientUsed = false;
repaint();
}
/*!
- Return progress colors and gradient type (horizontal or vertical).
+ \brief Get progress colors and gradient type.
+ \param startColor start gradient color (or mono-color)
+ \param endColor end gradient color
+ \return gradient type (QtxSplash::GradientType)
\sa setProgressColors()
*/
-int QtxSplash::progressColors( QColor& startColor, QColor& endColor )
+QtxSplash::GradientType QtxSplash::progressColors( QColor& startColor,
+ QColor& endColor ) const
{
startColor = myStartColor;
endColor = myEndColor;
}
/*!
- Sets message text alignment flags to \a alignment.
- Default is AlignBottom | AlignRight.
+ \brief Set custom progress bar colors.
+
+ The gradient start and final stops are scaled to the actual progress
+ bar size. For example:
+ \code
+ QLinearGradient lg(0.5, 0, 1, 1);
+ lg.setColorAt(0.2, Qt::blue);
+ lg.setColorAt(0.6, Qt::red);
+ lg.setSpread(QGradient::RepeatSpread);
+ splash->setProgressGradient(lg);
+ \endcode
+ The above code creates linear gradient, which sets start stop to the
+ center of the progress bar; the final stop is always in the end of
+ the progress bar. The color scale (blue to red) is changed by the
+ progress bar diagonal.
+
+ Note, that methods setProgressGradient() and setProgressColors() are
+ alternative. Only the latest used is taken into account.
+
+ \param gradient color gradient to be used for progress bar coloring
+ \sa progressGradient(), setProgressColors()
+*/
+void QtxSplash::setProgressGradient( const QLinearGradient& gradient )
+{
+ myGradient = gradient;
+ myGradientUsed = true;
+ repaint();
+}
+
+/*!
+ \brief Get custom progress bar colors.
+ \return color gradient used for progress bar coloring
+ \sa setProgressGradient()
+*/
+QLinearGradient QtxSplash::progressGradient() const
+{
+ return myGradient;
+}
+
+/*!
+ \brief Set progress bar and status text message opacity.
+
+ The value should be in the range 0.0 to 1.0, where 0.0 is fully
+ transparent and 1.0 is fully opaque.
+
+ \param opacity new opacity value
+ \sa opacity()
+*/
+void QtxSplash::setOpacity( const double opacity )
+{
+ myOpacity = opacity < 0.0 ? 0.0 : ( opacity > 1.0 ? 1.0 : opacity );
+ repaint();
+}
+
+/*!
+ \brief Get progress bar and status text message opacity.
+ \return current opacity value
+ \sa setOpacity()
+*/
+double QtxSplash::opacity() const
+{
+ return myOpacity;
+}
+
+/*!
+ \brief Set message text alignment flags.
+
+ Default flags are Qt::AlignBottom | Qt::AlignRight.
+
+ \param alignment alignment flags (Qt::Alignment)
+ \sa textAlignment()
*/
void QtxSplash::setTextAlignment( const int alignment )
{
}
/*!
- Return message text alignment flags.
+ \brief Get message text alignment flags.
+ \return alignment flags (Qt::Alignment)
\sa setTextAlignment()
*/
int QtxSplash::textAlignment() const
}
/*!
- Sets message text color to \a color.
- Default is white.
+ \brief Set message text color.
+
+ Default message color is white.
+
+ \param color message text color
\sa setTextColors()
*/
void QtxSplash::setTextColor( const QColor& color )
{
- myColor = color;
+ if ( myColor.isValid() )
+ myColor = color;
myShadowColor = QColor();
repaint();
}
/*!
- Return message text color.
+ \brief Get message text color.
+ \return color message text color
\sa setTextColor()
*/
QColor QtxSplash::textColor() const
}
/*!
- Sets message text color to \a color and text shadow color to \a shadow.
- \sa setTextColor()
+ \brief Set message text color and text shadow color.
+ \param color message text color
+ \param shadow message text shadow color
+ \sa textColors(), textColor(), setTextColor()
*/
void QtxSplash::setTextColors( const QColor& color, const QColor& shadow )
{
- myColor = color;
+ if ( myColor.isValid() )
+ myColor = color;
myShadowColor = shadow;
repaint();
}
/*!
- Return message text color and text shadow color.
- \sa setTextColors()
+ \brief Get message text color and text shadow color.
+ \param color message text color
+ \param shadow message text shadow color
+ \sa setTextColors(), textColor(), setTextColor()
*/
void QtxSplash::textColors( QColor& color, QColor& shadow ) const
{
}
/*!
- Returns current status message.
+ \brief Get current status message.
+ \return status message
*/
QString QtxSplash::message() const
{
}
/*!
- Return error code. If no errors were occured returns 0.
- Error code can be set by error( QString&, QString, int ).
+ \brief Get error code.
+
+ This function returns error code, set previoiusly with
+ error(const QString&, const QString&, const int) method.
+ If no error code has been set, 0 is returned.
+
+ \return last error code
*/
int QtxSplash::error() const
{
}
/*!
- Makes the splash screen wait until the widget \a mainWin is displayed
- before calling close() on itself.
+ \brief Wait until widget \a mainWin is displayed.
+
+ Makes the splash screen wait until the widget \a mainWin is displayed
+ and then hide and close splash window.
+
+ \param mainWin application main window
*/
void QtxSplash::finish( QWidget* mainWin )
{
if ( mainWin ) {
#if defined(Q_WS_X11)
- extern void qt_wait_for_window_manager( QWidget* w );
- qt_wait_for_window_manager( mainWin );
+ extern void qt_x11_wait_for_window_manager(QWidget *mainWin);
+ qt_x11_wait_for_window_manager(mainWin);
#endif
}
close();
}
/*!
- Repaint the splash screen.
+ \brief Repaint the splash screen.
*/
void QtxSplash::repaint()
{
}
/*!
- Draws the \a message text onto the splash screen with color \a
- color and aligns the text according to the flags in \a alignment.
+ \brief Set status message for the splash screen and define its color
+ and aligment flags.
+ \param msg status message
+ \param alignment message text alignment flags (Qt::Alignment)
+ \param color message text color
*/
void QtxSplash::message( const QString& msg,
int alignment,
{
myMessage = msg;
myAlignment = alignment;
- myColor = color;
+ if ( color.isValid() )
+ myColor = color;
repaint();
}
/*!
- This is an overloaded member function, provided for convenience.
- It behaves essentially like the above function.
- Draws the \a message text onto the splash screen with default color
- and aligns the text according to the default alignment flags.
+ \overload
+ \brief Set status message for the splash screen.
+ \param msg status message
*/
void QtxSplash::message( const QString& msg )
{
}
/*!
- Removes the message being displayed on the splash screen.
+ \brief Remove the message being displayed on the splash screen.
\sa message()
*/
void QtxSplash::clear()
}
/*!
- Draw the contents of the splash screen using painter \a painter.
+ \brief Draw the contents of the splash screen.
+ \param painter painter
*/
-void QtxSplash::drawContents( QPainter* painter )
+void QtxSplash::drawContents( QPainter* p )
{
- QRect r = rect();
+ // draw progress bar
if ( myTotal > 0 ) {
- // draw progress bar outline rectangle
- painter->setPen( palette().active().dark() );
- painter->drawLine( r.x()+5,
- r.height()-5-_PROGRESS_WIDTH,
- r.width()-5,
- r.height()-5-_PROGRESS_WIDTH );
- painter->drawLine( r.x()+5,
- r.height()-5-_PROGRESS_WIDTH,
- r.x()+5,
- r.height()-5 );
- painter->setPen( palette().active().light() );
- painter->drawLine( r.x()+5,
- r.height()-5,
- r.width()-5,
- r.height()-5 );
- painter->drawLine( r.width()-5,
- r.height()-5-_PROGRESS_WIDTH,
- r.width()-5,
- r.height()-5 );
- // draw progress bar
- if ( myGradientType == Horizontal ) {
- int tng = r.width() - r.x() - 11;
- int ng = (int) ( 1.0 * tng * ( myProgress > 0 ? myProgress : 0 ) / myTotal );
- int h1, h2, s1, s2, v1, v2;
- myStartColor.hsv( &h1, &s1, &v1 );
- myEndColor.isValid() ? myEndColor.hsv( &h2, &s2, &v2 ) :
- myStartColor.hsv( &h2, &s2, &v2 );
- for ( int i = 0; i < ng; i++ ) {
- painter->setPen( QColor( h1 + ((h2-h1)*i)/(tng-1),
- s1 + ((s2-s1)*i)/(tng-1),
- v1 + ((v2-v1)*i)/(tng-1),
- QColor::Hsv ) );
- painter->drawLine( r.x()+6+i,
- r.height()-5-_PROGRESS_WIDTH+1,
- r.x()+6+i,
- r.height()-6 );
- }
- }
- else {
- int ng = (int) ( 1.0 * (r.width() - r.x() - 11) * ( myProgress > 0 ? myProgress : 0 ) / myTotal );
- int h1, h2, s1, s2, v1, v2;
- myStartColor.hsv( &h1, &s1, &v1 );
- myEndColor.isValid() ? myEndColor.hsv( &h2, &s2, &v2 ) :
- myStartColor.hsv( &h2, &s2, &v2 );
- for ( int i = 0; i < _PROGRESS_WIDTH-1; i++ ) {
- painter->setPen( QColor( h1 + ((h2-h1)*i)/(_PROGRESS_WIDTH-2),
- s1 + ((s2-s1)*i)/(_PROGRESS_WIDTH-2),
- v1 + ((v2-v1)*i)/(_PROGRESS_WIDTH-2),
- QColor::Hsv ) );
- painter->drawLine( r.x()+6,
- r.height()-5-_PROGRESS_WIDTH+1+i,
- r.x()+6+ng-1,
- r.height()-5-_PROGRESS_WIDTH+1+i );
- }
- }
+ p->save();
+ drawProgressBar( p );
+ p->restore();
}
- // draw status
+
+ // draw status message
if ( !myMessage.isEmpty() ) {
- QFontMetrics f( font() );
- int spacing = f.lineSpacing();
- int shift = myTotal > 0 ? _PROGRESS_WIDTH : _PROGRESS_WIDTH; // : 0
- int i = myMessage.length() - 1;
- while( i >= 0 && myMessage[ i-- ] == '\n' )
- shift += spacing;
- QRect r1( r.x() + 5, r.y() + 5, r.width() - 10, r.height() - 10 - shift );
- QRect r2 = r1;
- if ( myAlignment & Qt::AlignLeft ) r2.setLeft ( r2.left() + 1 );
- if ( myAlignment & Qt::AlignTop ) r2.setTop ( r2.top() + 1 );
- if ( myAlignment & Qt::AlignRight ) r2.setRight ( r2.right() + 1 );
- if ( myAlignment & Qt::AlignBottom ) r2.setBottom( r2.bottom() + 1 );
- if ( myShadowColor.isValid() ) {
- painter->setPen( myShadowColor );
- painter->drawText( r2, myAlignment, myMessage );
- }
- painter->setPen( myColor );
- painter->drawText( r1, myAlignment, myMessage );
+ p->save();
+ drawMessage( p );
+ p->restore();
}
}
/*!
- Mouse press event.
+ \brief Process mouse button pressing event.
+
Hides splash screen if the 'hide on mouse click' flag is set.
- \sa setHideOnClick()
+
+ \param me mouse event (not used)
+ \sa hideOnClick(), setHideOnClick()
*/
-void QtxSplash::mousePressEvent( QMouseEvent* )
+void QtxSplash::mousePressEvent( QMouseEvent* /*me*/ )
{
if ( myHideOnClick )
hide();
}
/*!
- Processes custom event sent by setStatus() method.
+ \brief Customize paint event.
+
+ This function is implemented to work-around the Qt bug
+ on some Linux distribututions when the drawing on the
+ splash screen widget is not allowed.
+
+ \param pe paint event (not used)
+*/
+void QtxSplash::paintEvent( QPaintEvent* /*pe*/ )
+{
+ QPainter p( this );
+ QPixmap pix = palette().brush( backgroundRole() ).texture();
+ p.drawPixmap( 0, 0, pix );
+}
+
+/*!
+ \brief Process custom event sent by setStatus() method.
+ \param ce custom event
\sa setStatus().
*/
-void QtxSplash::customEvent( QCustomEvent* ce )
+void QtxSplash::customEvent( QEvent* ce )
{
if ( ce->type() == ProgressEvent::id() ) {
ProgressEvent* pe = (ProgressEvent*)ce;
pe->message().isEmpty() ? clear() : message( pe->message() );
setProgress( pe->progress() );
- qApp->processEvents();
+ QApplication::instance()->processEvents();
+ }
+}
+
+/*!
+ \brief Draw progress bar.
+ \param p painter
+*/
+void QtxSplash::drawProgressBar( QPainter* p )
+{
+ // get rect, margin, progress bar width
+ QRect r = rect();
+ int m = margin();
+ int pw = progressWidth();
+
+ // calculate drawing rect
+ // ... first set default position (if none or wrong position is set)
+ if ( myProgressFlags & BottomSide )
+ r = QRect( r.x() + m, r.height() - (m + pw), r.width() - 2 * m, pw );
+ else if ( myProgressFlags & TopSide )
+ r = QRect( r.x() + m, r.y() + m, r.width() - 2 * m, pw );
+ else if ( myProgressFlags & LeftSide )
+ r = QRect( r.x() + m, r.y() + m, pw, r.height() - 2 * m );
+ else if ( myProgressFlags & RightSide )
+ r = QRect( r.width() - (m + pw), r.y() + m, pw, r.height() - 2 * m );
+
+ QRect cr = r;
+ if ( myProgressFlags & TopSide || myProgressFlags & BottomSide ) {
+ cr.setWidth( (int)( r.width() * ( myProgress > 0 ? myProgress : 0 ) / myTotal ) );
+ if ( myProgressFlags & RightToLeft )
+ cr.translate( r.width() - cr.width(), 0 );
+ }
+ else if ( myProgressFlags & LeftSide || myProgressFlags & RightSide ) {
+ cr.setHeight( (int)( r.height() * ( myProgress > 0 ? myProgress : 0 ) / myTotal ) );
+ if ( myProgressFlags & RightToLeft)
+ cr.translate( 0, r.height() - cr.height() );
+ }
+ int x1, x2, y1, y2;
+ if ( myGradientType == Horizontal ) {
+ x1 = r.left(); x2 = r.right(); y1 = y2 = 0;
+ }
+ else {
+ x1 = x2 = 0; y1 = r.top(); y2 = r.bottom();
+ }
+ QLinearGradient lg;
+ if ( myGradientUsed ) {
+ QPointF start = myGradient.start();
+ QPointF final = myGradient.finalStop();
+ qreal xd = final.x() - start.x();
+ qreal yd = final.y() - start.y();
+ lg.setStart( xd != 0 ? r.left() + r.width() * start.x() / xd : 0,
+ yd != 0 ? r.top() + r.height() * start.y() / yd : 0 );
+ lg.setFinalStop( xd != 0 ? r.right() : 0, yd != 0 ? r.bottom() : 0 );
+ lg.setStops( myGradient.stops() );
+ lg.setSpread( myGradient.spread() );
}
+ else {
+ lg.setStart( x1, y1 );
+ lg.setFinalStop( x2, y2 );
+ lg.setColorAt( 0, myStartColor );
+ lg.setColorAt( 1, myEndColor.isValid() ? myEndColor : myStartColor );
+ }
+ p->setOpacity( myOpacity );
+ p->setClipRect( cr );
+ p->fillRect( r, lg );
+ p->setClipping( false );
+
+ // draw progress bar outline rectangle
+ p->setPen( palette().color( QPalette::Dark ) );
+ p->drawLine( r.left(), r.top(), r.right(), r.top() );
+ p->drawLine( r.left(), r.top(), r.left(), r.bottom() );
+ p->setPen( palette().color( QPalette::Light ) );
+ p->drawLine( r.left(), r.bottom(), r.right(), r.bottom() );
+ p->drawLine( r.right(), r.top(), r.right(), r.bottom() );
}
/*!
- Draws the splash screen window [ internal ].
+ \brief Draw status message.
+ \param p painter
+*/
+void QtxSplash::drawMessage( QPainter* p )
+{
+ // get rect, margin, progress bar width
+ QRect r = rect();
+ int m = margin();
+ int pw = progressWidth();
+
+ // calculate drawing rect
+ QFontMetrics f( font() );
+ int spacing = f.lineSpacing();
+ // ... base rect
+ QRect r1( r.x() + m, r.y() + m, r.width() - 2 * m, r.height() - 2 * m );
+ r1.setY( r1.y() - f.leading() );
+ // ... take into account progress bar
+ if ( 1 ) { // if ( myTotal > 0 ) : vsr changed: otherwise text is jumping
+ if ( myProgressFlags & BottomSide )
+ r1.setHeight( r1.height() - pw );
+ else if ( myProgressFlags & TopSide )
+ r1.setY( r1.y() + pw );
+ else if ( myProgressFlags & LeftSide )
+ r1.setX( r1.x() + pw );
+ else if ( myProgressFlags & RightSide )
+ r1.setWidth( r1.width() - pw );
+ }
+
+ // ... take into account trailing '\n' symbols
+ int shift = 0;
+ int i = myMessage.length() - 1;
+ while( i >= 0 && myMessage[ i-- ] == '\n' )
+ shift += spacing;
+ r1.setHeight( r1.height() - shift );
+
+ p->setOpacity( myOpacity );
+
+ // draw shadow status text
+ if ( myShadowColor.isValid() ) {
+ QRect r2 = r1;
+ if ( myAlignment & Qt::AlignLeft ) r2.setLeft ( r2.left() + 1 );
+ if ( myAlignment & Qt::AlignTop ) r2.setTop ( r2.top() + 1 );
+ if ( myAlignment & Qt::AlignRight ) r2.setRight ( r2.right() + 1 );
+ if ( myAlignment & Qt::AlignBottom ) r2.setBottom( r2.bottom() + 1 );
+ p->setPen( myShadowColor );
+ p->drawText( r2, myAlignment, myMessage );
+ }
+
+ // draw foreground status text
+ p->setPen( myColor );
+ p->drawText( r1, myAlignment, myMessage );
+}
+
+/*!
+ \brief Draw the splash screen window contents.
*/
void QtxSplash::drawContents()
{
QPixmap textPix = myPixmap;
- QPainter painter( &textPix, this );
+ QPainter painter( &textPix );
+ painter.initFrom( this );
drawContents( &painter );
- setErasePixmap( textPix );
+ QPalette pal = palette();
+ pal.setBrush( backgroundRole(), QBrush( textPix ) );
+ setPalette( pal );
}
/*!
- Sets error code [ internal ].
+ \brief Sets error code.
+ \param code error code
*/
void QtxSplash::setError( const int code )
{
myError = code;
}
+
#include "Qtx.h"
-#include <qpixmap.h>
-#include <qwidget.h>
+#include <QWidget>
+#include <QPixmap>
+#include <QLinearGradient>
#ifdef WIN32
#pragma warning( disable:4251 )
class QTX_EXPORT QtxSplash : public QWidget
{
- Q_OBJECT
+ Q_OBJECT
private:
- QtxSplash( const QPixmap& = QPixmap() );
+ QtxSplash( const QPixmap& );
public:
- enum { Horizontal, Vertical };
-
- virtual ~QtxSplash();
-
- static QtxSplash* splash( const QPixmap& = QPixmap() );
- static void setStatus( const QString&, const int = 0 );
- static void error( const QString&, const QString& = QString::null, const int = -1 );
-
- void setPixmap( const QPixmap& );
- QPixmap pixmap() const;
-
- void setHideOnClick( const bool );
- bool hideOnClick() const;
-
- void setTotalSteps( const int );
- int totalSteps() const;
- void setProgress( const int );
- int progress() const;
- void setProgress( const int, const int );
- void setProgressColors( const QColor&,
- const QColor& = QColor(),
- const int = Vertical );
- int progressColors( QColor&, QColor& );
-
- void setTextAlignment( const int );
- int textAlignment() const;
-
- void setTextColor( const QColor& );
- QColor textColor() const;
- void setTextColors( const QColor&, const QColor& = QColor() );
- void textColors( QColor&, QColor& ) const;
-
- QString message() const;
-
- int error() const;
-
- void finish( QWidget* );
- void repaint();
-
+ //! Gradient type
+ typedef enum {
+ Horizontal, //!< horizontal
+ Vertical //!< vertical
+ } GradientType;
+
+ //! Progress bar position and direction
+ typedef enum {
+ LeftSide = 0x0001, //!< progress bar is displayed at the left side
+ RightSide = 0x0002, //!< progress bar is displayed at the right side
+ TopSide = 0x0004, //!< progress bar is displayed at the top side
+ BottomSide = 0x0008, //!< progress bar is displayed at the bottom side
+ LeftToRight = 0x0010, //!< show progress from left to right (from top to bottom)
+ RightToLeft = 0x0020 //!< show progress from right to left (from bottom to top)
+ } ProgressBarFlags;
+
+ virtual ~QtxSplash();
+
+ static QtxSplash* splash( const QPixmap& = QPixmap() );
+
+ static void setStatus( const QString&, const int = 0 );
+ static void error( const QString&, const QString& = QString::null, const int = -1 );
+
+ void setPixmap( const QPixmap& );
+ QPixmap pixmap() const;
+
+ void setHideOnClick( const bool );
+ bool hideOnClick() const;
+
+ void setTotalSteps( const int );
+ int totalSteps() const;
+
+ void setProgress( const int );
+ void setProgress( const int, const int );
+ int progress() const;
+
+ void setMargin( const int );
+ int margin() const;
+
+ void setProgressWidth( const int );
+ int progressWidth() const;
+
+ void setProgressFlags( const int );
+ int progressFlags() const;
+
+ void setProgressColors( const QColor&,
+ const QColor& = QColor(),
+ const GradientType = Vertical );
+ GradientType progressColors( QColor&, QColor& ) const;
+
+ void setProgressGradient( const QLinearGradient& );
+ QLinearGradient progressGradient() const;
+
+ void setOpacity( const double );
+ double opacity() const;
+
+ void setTextAlignment( const int );
+ int textAlignment() const;
+
+ void setTextColor( const QColor& );
+ QColor textColor() const;
+ void setTextColors( const QColor&, const QColor& = QColor() );
+ void textColors( QColor&, QColor& ) const;
+
+ QString message() const;
+
+ int error() const;
+
+ void finish( QWidget* );
+ void repaint();
+
public slots:
- void message( const QString&,
- const int,
- const QColor& = white );
- void message( const QString& );
- void clear();
-
+ void message( const QString&,
+ const int,
+ const QColor& = QColor() );
+ void message( const QString& );
+ void clear();
+
protected:
- virtual void mousePressEvent( QMouseEvent* );
- virtual void customEvent( QCustomEvent* );
- virtual void drawContents( QPainter* );
+ virtual void mousePressEvent( QMouseEvent* );
+ virtual void customEvent( QEvent* );
+ virtual void paintEvent( QPaintEvent* );
-private:
- void drawContents();
- void setError( const int );
+ virtual void drawContents( QPainter* );
+
+ virtual void drawProgressBar( QPainter* );
+ virtual void drawMessage( QPainter* );
private:
- static QtxSplash* mySplash;
+ void drawContents();
+ void setError( const int );
- QPixmap myPixmap;
- QString myMessage;
- int myAlignment;
- QColor myColor;
- QColor myShadowColor;
- bool myHideOnClick;
- int myProgress;
- int myTotal;
- QColor myStartColor;
- QColor myEndColor;
- int myGradientType;
- int myError;
+private:
+ static QtxSplash* mySplash;
+
+ QPixmap myPixmap; //!< splash pixmap
+ QString myMessage; //!< current status message
+ int myAlignment; //!< text alignment flags (Qt::Alignment)
+ QColor myColor; //!< text color
+ QColor myShadowColor; //!< text shadow color
+ bool myHideOnClick; //!< 'hide on click' flag
+ int myProgress; //!< current progress
+ int myTotal; //!< total progress steps
+ QColor myStartColor; //!< progress bar gradient starting color
+ QColor myEndColor; //!< progress bar gradient ending color
+ GradientType myGradientType; //!< progress bar gradient direction
+ QLinearGradient myGradient; //!< progress bar custom gradient
+ int myProgressWidth; //!< progress bar width
+ int myProgressFlags; //!< progress bar flags (QtxSplash::ProgressBarFlags)
+ int myMargin; //!< margin (for progress bar and status message)
+ double myOpacity; //!< progress bar / status message opacity
+ int myError; //!< error code
+ bool myGradientUsed; //!< 'use custom gradient color scale' flag
};
#endif
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-#include "QtxStdOperations.h"
-
-#include <math.h>
-#include <stdlib.h>
-
-/*!
- Default constructor
-*/
-QtxStdOperations::QtxStdOperations()
-{
-}
-
-/*!
- Destructor
-*/
-QtxStdOperations::~QtxStdOperations()
-{
-}
-
-/*!
- Fills list of brackets treated as open (when 'open' is 'true') or close ('open' is 'false')
-*/
-void QtxStdOperations::bracketsList( QStringList& list, bool open ) const
-{
- if( open )
- list.append( "(" );
- else
- list.append( ")" );
-}
-
-/*!
- Fills list with operation names by copying of internal list of operations
-*/
-void QtxStdOperations::opersList( QStringList& list ) const
-{
- list += myOpers;
-}
-
-/*!
- Add operation names from list to internal list of operations
-*/
-void QtxStdOperations::addOperations( const QStringList& list )
-{
- QStringList::const_iterator anIt = list.begin(),
- aLast = list.end();
- for( ; anIt!=aLast; anIt++ )
- if( myOpers.contains( *anIt )==0 )
- myOpers.append( *anIt );
-}
-
-/*!
- Append operation names from 'list' to internal list of operations
-*/
-void QtxStdOperations::addTypes( const ListOfTypes& list )
-{
- ListOfTypes::const_iterator anIt = list.begin(),
- aLast = list.end();
- for( ; anIt!=aLast; anIt++ )
- if( myTypes.contains( *anIt )==0 )
- myTypes.append( *anIt );
-}
-
-/*!
- \return whether values with passed types are valid for arguments of operation
- \param op - name of operation
- \param t1 - type of first argument
- \param t2 - type of second argument
-*/
-QtxParser::Error QtxStdOperations::isValid( const QString& op,
- const QVariant::Type t1,
- const QVariant::Type t2 ) const
-{
- if( ( t1==QVariant::Invalid || myTypes.contains( t1 ) ) &&
- ( t2==QVariant::Invalid || myTypes.contains( t2 ) ) &&
- ( t1!=QVariant::Invalid || t2!=QVariant::Invalid ) )
- if( prior( op, t1!=QVariant::Invalid && t2!=QVariant::Invalid ) > 0 )
- return QtxParser::OK;
- else
- return QtxParser::InvalidOperation;
- else
- return QtxParser::OperandsNotMatch;
-}
-
-
-
-
-
-
-
-
-/*!
- Default constructor
-*/
-QtxArithmetics::QtxArithmetics()
-: QtxStdOperations()
-{
- QStringList aList;
- aList.append( "+" );
- aList.append( "-" );
- aList.append( "*" );
- aList.append( "/" );
- aList.append( "=" );
- aList.append( "<" );
- aList.append( ">" );
- aList.append( "<=" );
- aList.append( ">=" );
- aList.append( "<>" );
- aList.append( "!=" ); // same as "<>" - for C++ addicts
- addOperations( aList );
-
- ListOfTypes aTypes;
- aTypes.append( QVariant::Int );
- aTypes.append( QVariant::UInt );
- aTypes.append( QVariant::Double );
- addTypes( aTypes );
-}
-
-/*!
- Destructor
-*/
-QtxArithmetics::~QtxArithmetics()
-{
-}
-
-/*!
- Creates numbers by it's string representation [redefined virtual]
-*/
-bool QtxArithmetics::createValue( const QString& str, QtxValue& v ) const
-{
- bool ok = false;
- v = str.toInt( &ok );
-
- if( !ok )
- {
- v = str.toDouble( &ok );
- if( !ok )
- ok = QtxStdOperations::createValue( str, v );
- }
- return ok;
-}
-
-/*!
- \return priority of arithmetic operation 'op'.
- \param isBin indicate whether the operation is binary
-*/
-int QtxArithmetics::prior( const QString& op, bool isBin ) const
-{
- if( isBin )
- if( op=="<" || op==">" || op=="=" ||
- op=="<=" || op==">=" || op=="<>" || op=="!=" )
- return 1;
- else if( op=="+" || op=="-" )
- return 2;
- else if( op=="*" || op=="/" )
- return 3;
- else
- return 0;
- else if( op=="+" || op=="-" )
- return 5;
- else
- return 0;
-}
-
-void set( QVariant& v1, bool v2 )
-{
- v1 = QVariant( v2, 0 );
-}
-
-/*!
- Calculates result of operation
- \return one of error states
- \param op - name of operation
- \param v1 - first operation argument (must be used also to store result)
- \param v2 - second operation argument
-*/
-QtxParser::Error QtxArithmetics::calculate( const QString& op,
- QtxValue& v1, QtxValue& v2 ) const
-{
- QtxParser::Error err = QtxParser::OK;
-
- if( v1.isValid() && v2.isValid() )
- // binary operations
- if( ( v1.type()==QVariant::Int || v1.type()==QVariant::UInt ) &&
- ( v2.type()==QVariant::Int || v2.type()==QVariant::UInt ) )
- {
- int _v1 = v1.toInt(),
- _v2 = v2.toInt();
-
- if( op=="+" )
- v1 = _v1 + _v2;
- else if( op=="-" )
- v1 = _v1 - _v2;
- else if( op=="*" )
- v1 = _v1 * _v2;
- else if( op=="/" )
- if( _v2!=0 )
- if( _v1%_v2==0 )
- v1 = _v1 / _v2;
- else
- v1 = double( _v1 ) / double( _v2 );
- else
- err = QtxParser::InvalidResult;
- else if( op=="<" )
- set( v1, _v1<_v2 );
- else if( op==">" )
- set( v1, _v1>_v2 );
- else if( op=="=" )
- set( v1, _v1==_v2 );
- else if( op=="<=" )
- set( v1, _v1<=_v2 );
- else if( op==">=" )
- set( v1, _v1>=_v2 );
- else if( op=="<>" || op=="!=" )
- set( v1, _v1!=_v2 );
- }
- else if( ( v1.type()==QVariant::Int || v1.type()==QVariant::Double ) &&
- ( v2.type()==QVariant::Int || v2.type()==QVariant::Double ) )
- {
- double _v1 = v1.toDouble(),
- _v2 = v2.toDouble();
-
- if( op=="+" )
- v1 = _v1 + _v2;
- else if( op=="-" )
- v1 = _v1 - _v2;
- else if( op=="*" )
- v1 = _v1 * _v2;
- else if( op=="/" )
- if( _v2!=0 )
- v1 = _v1 / _v2;
- else
- err = QtxParser::InvalidResult;
- else if( op=="<" )
- set( v1, _v1<_v2 );
- else if( op==">" )
- set( v1, _v1>_v2 );
- else if( op=="=" )
- set( v1, _v1==_v2 );
- else if( op=="<=" )
- set( v1, _v1<=_v2 );
- else if( op==">=" )
- set( v1, _v1>=_v2 );
- else if( op=="<>" || op=="!=" )
- set( v1, _v1!=_v2 );
- }
- else
- // prefix operations
- if( op=="-" )
- if( v2.type()==QVariant::Int )
- v2 = -v2.toInt();
- else if( v2.type()==QVariant::Double )
- v2 = -v2.toDouble();
-
- return err;
-}
-
-
-
-
-
-
-
-
-
-
-
-/*!
- Default constructor
-*/
-QtxLogic::QtxLogic()
-: QtxStdOperations()
-{
- QStringList aList;
- aList.append( "and" );
- aList.append( "&&" );
- aList.append( "or" );
- aList.append( "||" );
- aList.append( "xor" );
- aList.append( "not" );
- aList.append( "!" );
- aList.append( "imp" );
- aList.append( "=" );
- addOperations( aList );
-
- ListOfTypes aTypes;
- aTypes.append( QVariant::Bool );
- aTypes.append( QVariant::Int );
- aTypes.append( QVariant::UInt );
- addTypes( aTypes );
-}
-
-/*!
- Destructor
-*/
-QtxLogic::~QtxLogic()
-{
-}
-
-/*!
- Creates value 'true' or 'false' it's string representation [redefined virtual]
-*/
-bool QtxLogic::createValue( const QString& str, QtxValue& v ) const
-{
- bool ok = true;
- if( str.lower()=="true" )
- v = QtxValue( true, 0 );
- else if( str.lower()=="false" )
- v = QtxValue( false, 0 );
- else
- ok = QtxStdOperations::createValue( str, v );
-
- return ok;
-}
-
-/*!
- \return priority of arithmetic operation 'op'.
- \param isBin indicate whether the operation is binary
-*/
-int QtxLogic::prior( const QString& op, bool isBin ) const
-{
- if( isBin )
- if( op=="and" || op=="or" || op=="xor" ||
- op=="&&" || op=="||" ||
- op=="imp" )
- return 1;
- else if( op=="=" )
- return 2;
- else
- return 0;
- else if( op=="not" || op=="!" )
- return 5;
- else
- return 0;
-}
-
-bool boolean_value( const QtxValue& v )
-{
- if( v.type()==QVariant::Bool )
- return v.toBool();
- else if( v.type()==QVariant::Int )
- return v.toInt()!=0;
- else if( v.type()==QVariant::UInt )
- return v.toUInt()!=0;
- else
- return false;
-}
-
-/*!
- Calculates result of operation
- \return one of error states
- \param op - name of operation
- \param v1 - first operation argument (must be used also to store result)
- \param v2 - second operation argument
-*/
-QtxParser::Error QtxLogic::calculate( const QString& op,
- QtxValue& v1, QtxValue& v2 ) const
-{
- QtxParser::Error err = QtxParser::OK;
- bool val1 = boolean_value( v1 ),
- val2 = boolean_value( v2 );
- if( v1.isValid() && v2.isValid() )
- {
- if( op=="and" || op=="&&" )
- set( v1, val1 && val2 );
- else if( op=="or" || op=="||" )
- set( v1, val1 || val2 );
- else if( op=="xor" )
- set( v1, ( !val1 && val2 ) || ( val1 && !val2 ) );
- else if( op=="imp" )
- set( v1, !val1 || val2 );
- else if( op=="=" )
- set( v1, val1==val2 );
- }
- else
- if( op=="not" || op=="!" )
- set( v2, !val2 );
-
- return err;
-}
-
-
-
-
-
-
-/*!
- Default constructor
-*/
-QtxFunctions::QtxFunctions()
-: QtxStdOperations()
-{
- QStringList aList;
- aList.append( "sqrt" );
- aList.append( "abs" );
- aList.append( "sin" );
- aList.append( "cos" );
- aList.append( "rad2grad" );
- aList.append( "grad2rad" );
- addOperations( aList );
-
- ListOfTypes aTypes;
- aTypes.append( QVariant::Int );
- aTypes.append( QVariant::Double );
- addTypes( aTypes );
-}
-
-/*!
- Destructor
-*/
-QtxFunctions::~QtxFunctions()
-{
-}
-
-/*!
- Creates numbers by it's string representation [redefined virtual]
-*/
-bool QtxFunctions::createValue( const QString& str, QtxValue& v ) const
-{
- bool ok = false;
- v = str.toInt( &ok );
-
- if( !ok )
- {
- v = str.toDouble( &ok );
- if( !ok )
- ok = QtxStdOperations::createValue( str, v );
- }
- return ok;
-}
-
-/*!
- \return priority of arithmetic operation 'op'.
- \param isBin indicate whether the operation is binary
-*/
-int QtxFunctions::prior( const QString& op, bool isBin ) const
-{
- if( isBin )
- return 0;
- else if( op=="sqrt" || op=="abs" || op=="sin" || op=="cos" ||
- op=="rad2grad" || op=="grad2rad" )
- return 1;
- else
- return 0;
-}
-
-/*!
- Calculates result of operation
- \return one of error states
- \param op - name of operation
- \param v1 - first operation argument (must be used also to store result)
- \param v2 - second operation argument
-*/
-QtxParser::Error QtxFunctions::calculate( const QString& op,
- QtxValue& v1, QtxValue& v2 ) const
-{
- QtxParser::Error err = QtxParser::OK;
- double val = v2.toDouble();
- if( op=="sqrt" )
- if( val>=0 )
- v2 = sqrt( val );
- else
- err = QtxParser::InvalidResult;
- else if( op=="abs" )
- if( v2.type()==QVariant::Int )
- v2 = abs( v2.toInt() );
- else
- v2 = fabs( v2.toDouble() );
- else if( op=="sin" )
- v2 = sin( val );
- else if( op=="cos" )
- v2 = cos( val );
- else if( op=="grad2rad" )
- v2 = val * 3.14159256 / 180.0;
- else if( op=="rad2grad" )
- v2 = val * 180.0 / 3.14159256;
-
- return err;
-}
-
-
-
-
-
-
-
-
-/*!
- Default constructor
-*/
-QtxStrings::QtxStrings()
-: QtxStdOperations()
-{
- QStringList aList;
- aList.append( "+" );
- aList.append( "=" );
- aList.append( "<" );
- aList.append( ">" );
- aList.append( "<=" );
- aList.append( ">=" );
- aList.append( "<>" );
- aList.append( "!=" ); // same as "<>" - for C++ addicts
- aList.append( "length" );
- aList.append( "lower" );
- aList.append( "upper" );
- addOperations( aList );
-
- ListOfTypes aTypes;
- aTypes.append( QVariant::Int );
- aTypes.append( QVariant::Double );
- aTypes.append( QVariant::String );
- aTypes.append( QVariant::CString );
- addTypes( aTypes );
-}
-
-
-/*!
- Destructor
-*/
-QtxStrings::~QtxStrings()
-{
-}
-
-/*!
- Creates string QtxValue by it's Qt string representation [redefined virtual]
-*/
-bool QtxStrings::createValue( const QString& str, QtxValue& v ) const
-{
- QChar st = str[0],
- fin = str[ ( int )( str.length()-1 ) ];
- if( st=="'" && fin=="'" )
- {
- v = str.mid( 1, str.length()-2 );
- return true;
- }
- else
- return QtxStdOperations::createValue( str, v );
-}
-
-/*!
- \return priority of arithmetic operation 'op'.
- \param isBin indicate whether the operation is binary
-*/
-int QtxStrings::prior( const QString& op, bool isBin ) const
-{
- if( isBin )
- if( op=="+" )
- return 2;
- else if( op=="=" || op=="<" || op==">" ||
- op=="<=" || op==">=" || op=="<>" || op=="!=" )
- return 1;
- else
- return 0;
- else
- if( op=="length" || op=="lower" || op=="upper" )
- return 5;
- else
- return 0;
-}
-
-/*!
- Calculates result of operation
- \return one of error states
- \param op - name of operation
- \param v1 - first operation argument (must be used also to store result)
- \param v2 - second operation argument
-*/
-QtxParser::Error QtxStrings::calculate( const QString& op,
- QtxValue& v1, QtxValue& v2 ) const
-{
- QtxParser::Error err = QtxParser::OK;
- if( v1.isValid() && v2.isValid() )
- {
- QString _v1 = v1.toString(),
- _v2 = v2.toString();
- if( op=="+" )
- v1 = _v1 + _v2;
- else if( op=="=" )
- set( v1, _v1==_v2 );
- else if( op=="<" )
- set( v1, _v1<_v2 );
- else if( op==">" )
- set( v1, _v1>_v2 );
- else if( op=="<>" || op=="!=" )
- set( v1, _v1!=_v2 );
- else if( op=="<=" )
- set( v1, _v1<_v2 || _v1==_v2 );
- else if( op==">=" )
- set( v1, _v1>_v2 || _v1==_v2 );
- }
- else if( !v1.isValid() && v2.isValid() )
- {
- QString val = v2.toString();
- if( op=="length" )
- v2 = ( int )val.length();
- else if( op=="lower" )
- v2 = val.lower();
- else if( op=="upper" )
- v2 = val.upper();
- }
-
- return err;
-}
-
-
-
-
-
-
-/*!
- Default constructor
-*/
-QtxSets::QtxSets()
-{
- QStringList aList;
- aList.append( "{" );
- aList.append( "}" );
- aList.append( "=" );
- aList.append( "<>" );
- aList.append( "!=" ); // same as "<>" - for C++ addicts
- aList.append( "+" );
- aList.append( "-" );
- aList.append( "*" );
- aList.append( "in" );
- aList.append( "count" );
- addOperations( aList );
-
- ListOfTypes aTypes;
- aTypes.append( QVariant::List );
- addTypes( aTypes );
-}
-
-/*!
- Destructor
-*/
-QtxSets::~QtxSets()
-{
-}
-
-/*!
- Fills list of brackets treated as open (when 'open' is 'true') or close ('open' is 'false')
-*/
-void QtxSets::bracketsList( QStringList& list, bool open ) const
-{
- if( open )
- list.append( "{" );
- else
- list.append( "}" );
- QtxStdOperations::bracketsList( list, open );
-}
-
-/*!
- Creates set of QtxValues by their string representation [redefined virtual]
-*/
-bool QtxSets::createValue( const QString& str, QtxValue& val ) const
-{
- return QtxStdOperations::createValue( str, val );
-}
-
-/*!
- \return priority of arithmetic operation 'op'.
- \param isBin indicate whether the operation is binary
-*/
-int QtxSets::prior( const QString& op, bool isBin ) const
-{
- if( isBin )
- if( op=="=" || op=="<>" || op=="!=" )
- return 1;
- else if( op=="+" || op=="-" || op=="*" )
- return 2;
- else if( op=="in" )
- return 3;
- else
- return 0;
-
- else
- if( op=="{" || op=="}" )
- return 5;
- else if( op=="count" )
- return 4;
- else
- return 0;
-}
-
-/*!
- \return whether values with passed types are valid for arguments of operation
- \param op - name of operation
- \param t1 - type of first argument
- \param t2 - type of second argument
-*/
-QtxParser::Error QtxSets::isValid( const QString& op,
- const QVariant::Type t1,
- const QVariant::Type t2 ) const
-{
- if( op=="{" )
- return QtxParser::OK;
- else if( op=="in" )
- if( t1!=QVariant::Invalid && t2==QVariant::List )
- return QtxParser::OK;
- else
- return QtxParser::OperandsNotMatch;
- else
- return QtxStdOperations::isValid( op, t1, t2 );
-}
-
-/*!
- Adds new value 'v' to set 'set' [static]
-*/
-void QtxSets::add( ValueSet& set, const QtxValue& v )
-{
- if( v.isValid() && set.contains( v )==0 )
- set.append( v );
-}
-
-/*!
- Adds values from set 's2' to set 's1'
-*/
-void QtxSets::add( ValueSet& s1, const ValueSet& s2 )
-{
- ValueSet::const_iterator anIt = s2.begin(),
- aLast = s2.end();
- for( ; anIt!=aLast; anIt++ )
- add( s1, *anIt );
-}
-
-/*!
- Removes value 'v' from set 'set'
-*/
-void QtxSets::remove( ValueSet& set, const QtxValue& v )
-{
- set.remove( v );
-}
-
-/*!
- Removes values of set 's2' from set 's1'
-*/
-void QtxSets::remove( ValueSet& s1, const ValueSet& s2 )
-{
- ValueSet::const_iterator anIt = s2.begin(),
- aLast = s2.end();
- for( ; anIt!=aLast; anIt++ )
- s1.remove( *anIt );
-}
-
-/*!
- Calculates result of operation
- \return one of error states
- \param op - name of operation
- \param v1 - first operation argument (must be used also to store result)
- \param v2 - second operation argument
-*/
-QtxParser::Error QtxSets::calculate( const QString& op, QtxValue& v1, QtxValue& v2 ) const
-{
- QtxParser::Error err = QtxParser::OK;
-
- if( op!="{" )
- if( op=="}" )
- {
- ValueSet aNewList;
- add( aNewList, v1.toList() );
- v1 = aNewList;
- }
-
- else if( op=="=" || op=="<>" || op=="!=" || op=="+" || op=="-" || op=="*" )
- {
- ValueSet aNewList;
- add( aNewList, v1.toList() );
-
- if( op=="=" || op=="<>" || op=="!=" || op=="-" )
- {
- remove( aNewList, v2.toList() );
-
- if( op=="=" )
- set( v1, aNewList.isEmpty() && v1.toList().count()==v2.toList().count() );
- else if( op=="<>" || op=="!=" )
- set( v1, !aNewList.isEmpty() || v1.toList().count()!=v2.toList().count() );
- else
- v1 = aNewList;
- }
- else if( op=="+" )
- {
- add( aNewList, v2.toList() );
- v1 = aNewList;
- }
- else if( op=="*" )
- {
- ValueSet toDelete;
- add( toDelete, aNewList );
- remove( toDelete, v2.toList() );
- remove( aNewList, toDelete );
- v1 = aNewList;
- }
- }
- else if( op=="count" )
- v2 = ( int )v2.toList().count();
- else if( op=="in" )
- {
- if( v1.type()==QVariant::List )
- {
- bool res = true;
- ValueSet::const_iterator anIt = v1.toList().begin(),
- aLast = v1.toList().end();
- for( ; anIt!=aLast && res; anIt++ )
- res = v2.toList().contains( *anIt )>0;
-
- set( v1, res );
- }
- else
- {
- const QValueList< QVariant >& list = v2.toList();
- v1 = ( bool )( list.find( v1 )!=list.end() );
- }
- }
-
- return err;
-}
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-// File: QtxStdOperations.h
-// Author: Alexander SOLOVYOV
-
-#ifndef __QTX_STD_OPERATIONS_HEADER__
-#define __QTX_STD_OPERATIONS_HEADER__
-
-#include "Qtx.h"
-#include "QtxOperations.h"
-
-/*!
- \class QtxStdOperations
- Provides simplified interface for standard operations.
- Conatins list of operation names, priority and possible types
-*/
-class QTX_EXPORT QtxStdOperations : public QtxOperations
-{
-public:
- QtxStdOperations();
- virtual ~QtxStdOperations();
-
- virtual void opersList( QStringList& ) const;
- virtual void bracketsList( QStringList&, bool open ) const;
-
- virtual QtxParser::Error isValid( const QString&,
- const QVariant::Type,
- const QVariant::Type ) const;
-protected:
- typedef QValueList< QVariant::Type > ListOfTypes;
-
- void addOperations( const QStringList& );
- void addTypes( const ListOfTypes& );
-
-private:
- QStringList myOpers;
- ListOfTypes myTypes;
-};
-
-/*!
- \class QtxArithmetics
- Provides set of arithmetic operations for parser
-*/
-class QTX_EXPORT QtxArithmetics : public QtxStdOperations
-{
-public:
- QtxArithmetics();
- virtual ~QtxArithmetics();
-
- virtual bool createValue( const QString&, QtxValue& ) const;
- virtual int prior( const QString&, bool isBin ) const;
- virtual QtxParser::Error calculate( const QString&, QtxValue&, QtxValue& ) const;
-};
-
-/*!
- \class QtxLogic
- Provides set of logic operations for parser
-*/
-class QTX_EXPORT QtxLogic : public QtxStdOperations
-{
-public:
- QtxLogic();
- virtual ~QtxLogic();
-
- virtual bool createValue( const QString&, QtxValue& ) const;
- virtual int prior( const QString&, bool isBin ) const;
- virtual QtxParser::Error calculate( const QString&, QtxValue&, QtxValue& ) const;
-};
-
-/*!
- \class QtxFunctions
- Provides set of more complex operations for parser (sqrt, sin, cos, etc)
-*/
-class QTX_EXPORT QtxFunctions : public QtxStdOperations
-{
-public:
- QtxFunctions();
- virtual ~QtxFunctions();
-
- virtual bool createValue( const QString&, QtxValue& ) const;
- virtual int prior( const QString&, bool isBin ) const;
- virtual QtxParser::Error calculate( const QString&, QtxValue&, QtxValue& ) const;
-};
-
-/*!
- \class QtxStrings
- Provides set of string operations for parser
-*/
-class QTX_EXPORT QtxStrings : public QtxStdOperations
-{
-public:
- QtxStrings();
- virtual ~QtxStrings();
-
- virtual bool createValue( const QString&, QtxValue& ) const;
- virtual int prior( const QString&, bool isBin ) const;
- virtual QtxParser::Error calculate( const QString&, QtxValue&, QtxValue& ) const;
-};
-
-/*!
- \class QtxSets
- Provides set of operations with sets for parser
-*/
-class QTX_EXPORT QtxSets : public QtxStdOperations
-{
-public:
- typedef QValueList< QtxValue > ValueSet;
-
-public:
- QtxSets();
- virtual ~QtxSets();
-
- virtual void bracketsList( QStringList&, bool open ) const;
- virtual bool createValue( const QString&, QtxValue& ) const;
- virtual int prior( const QString&, bool isBin ) const;
- virtual QtxParser::Error isValid( const QString&,
- const QVariant::Type,
- const QVariant::Type ) const;
- virtual QtxParser::Error calculate( const QString&, QtxValue&, QtxValue& ) const;
-
- static void add( ValueSet&, const QtxValue& );
- static void add( ValueSet&, const ValueSet& );
- static void remove( ValueSet&, const QtxValue& );
- static void remove( ValueSet&, const ValueSet& );
-};
-
-
-#endif
#include "QtxToolBar.h"
-#include <qlayout.h>
-#include <qpixmap.h>
-#include <qdockarea.h>
-#include <qobjectlist.h>
-#include <qmainwindow.h>
-#include <qapplication.h>
+#include <QAction>
+#include <QMainWindow>
+#include <QApplication>
/*!
- Class: QtxToolBar::Watcher [Internal]
- Descr: Internal object with event filter.
+ \class QtxToolBar::Watcher
+ \internal
+ \brief Internal class which goal is to watch parent toolbar state changing.
*/
class QtxToolBar::Watcher : public QObject
Watcher( QtxToolBar* );
void shown( QtxToolBar* );
- void hided( QtxToolBar* );
+ void hidden( QtxToolBar* );
virtual bool eventFilter( QObject*, QEvent* );
protected:
- virtual void customEvent( QCustomEvent* );
+ virtual void customEvent( QEvent* );
private:
enum { Install = QEvent::User, Update };
void showContainer();
void hideContainer();
- void updateIcon();
- void updateCaption();
void updateVisibility();
private:
};
/*!
- Constructor
+ \brief Constructor.
+ \param cont toolbar to be watched
*/
QtxToolBar::Watcher::Watcher( QtxToolBar* cont )
: QObject( cont ),
-myCont( cont ),
-myState( true ),
-myEmpty( true )
+ myCont( cont ),
+ myState( true ),
+ myEmpty( false )
{
+/*
if ( myCont->mainWindow() )
myState = myCont->mainWindow()->appropriate( myCont );
-
+*/
myCont->installEventFilter( this );
myVisible = myCont->isVisibleTo( myCont->parentWidget() );
}
/*!
- Custom event filter
+ \brief Custom event filter.
+ \param o event receiver object
+ \param e event sent to object
+ \return \c true if further event processing should be stopped
*/
bool QtxToolBar::Watcher::eventFilter( QObject* o, QEvent* e )
{
- if ( o == myCont && e->type() == QEvent::ChildInserted )
- QApplication::postEvent( this, new QCustomEvent( Install ) );
-
- if ( o != myCont && e->type() == QEvent::IconChange )
- updateIcon();
-
- if ( o != myCont && e->type() == QEvent::CaptionChange )
- updateCaption();
+ if ( o == myCont && e->type() == QEvent::ChildAdded )
+ QApplication::postEvent( this, new QEvent( (QEvent::Type)Install ) );
bool updVis = ( o != myCont && ( e->type() == QEvent::Show || e->type() == QEvent::ShowToParent ||
e->type() == QEvent::Hide || e->type() == QEvent::HideToParent ) ) ||
myCont = 0;
QApplication::sendPostedEvents( this, Update );
myCont = cont;
- QApplication::postEvent( this, new QCustomEvent( Update ) );
+ QApplication::postEvent( this, new QEvent( (QEvent::Type)Update ) );
}
return false;
}
/*!
- Sets internal visibility state to true
+ \brief Set internal status to "shown"
+ \param tb toolbar
*/
void QtxToolBar::Watcher::shown( QtxToolBar* tb )
{
}
/*!
- Sets internal visibility state to false
+ \brief Set internal status to "hidden"
+ \param tb toolbar
*/
-void QtxToolBar::Watcher::hided( QtxToolBar* tb )
+void QtxToolBar::Watcher::hidden( QtxToolBar* tb )
{
if ( tb != myCont )
return;
}
/*!
- Shows corresponding QtxToolBar
+ \brief Show the toolbar being watched
*/
void QtxToolBar::Watcher::showContainer()
{
}
/*!
- Hides corresponding QtxToolBar
+ \brief Hide the toolbar being watched
*/
void QtxToolBar::Watcher::hideContainer()
{
}
/*!
- Event handler of custom events
+ \brief Proces custom events.
+ \param e custom event
*/
-void QtxToolBar::Watcher::customEvent( QCustomEvent* e )
+void QtxToolBar::Watcher::customEvent( QEvent* e )
{
switch ( e->type() )
{
case Install:
installFilters();
- updateIcon();
- updateCaption();
+ break;
case Update:
updateVisibility();
+ break;
+ default:
+ break;
}
}
/*!
- Installs event filters
+ \brief Install this object as event dilter to all children widgets
+ of the toolbar being watched.
*/
void QtxToolBar::Watcher::installFilters()
{
if ( !myCont )
return;
- const QObjectList* objList = myCont->children();
- if ( !objList )
- return;
-
- for ( QObjectListIt it( *objList ); it.current(); ++it )
+ const QObjectList& objList = myCont->children();
+ for ( QObjectList::const_iterator it = objList.begin(); it != objList.end(); ++it )
{
- if ( it.current()->isWidgetType() &&
- qstrcmp( "qt_dockwidget_internal", it.current()->name() ) )
- it.current()->installEventFilter( this );
+ if ( (*it)->isWidgetType() && qstrcmp( "qt_dockwidget_internal", (*it)->objectName().toLatin1() ) )
+ (*it)->installEventFilter( this );
}
}
/*!
- Update visibility state
+ \brief Update visibility state of all children widgets of the toolbar
+ being watched.
*/
void QtxToolBar::Watcher::updateVisibility()
{
bool vis = false;
- const QObjectList* objList = myCont->children();
- if ( objList )
+ const QObjectList& objList = myCont->children();
+ for ( QObjectList::const_iterator it = objList.begin(); it != objList.end() && !vis; ++it )
{
- for ( QObjectListIt it( *objList ); it.current() && !vis; ++it )
- {
- if ( !it.current()->isWidgetType() ||
- !qstrcmp( "qt_dockwidget_internal", it.current()->name() ) )
- continue;
+ QObject* obj = *it;
+ if ( !obj->isWidgetType() || !qstrcmp( "qt_dockwidget_internal", obj->objectName().toLatin1() ) )
+ continue;
- QWidget* wid = (QWidget*)it.current();
- vis = wid->isVisibleTo( wid->parentWidget() );
- }
+ if ( obj->inherits( "QToolBarHandle" ) || obj->inherits( "QToolBarExtension" ) )
+ continue;
+
+ QWidget* wid = (QWidget*)*it;
+ vis = wid->isVisibleTo( wid->parentWidget() );
}
QMainWindow* mw = myCont->mainWindow();
{
myEmpty = !vis;
if ( !myEmpty )
- mw->setAppropriate( myCont, myState );
+ myCont->toggleViewAction()->setVisible( myState );
else
{
- myState = mw->appropriate( myCont );
- mw->setAppropriate( myCont, false );
+ myState = myCont->toggleViewAction()->isVisible();
+ myCont->toggleViewAction()->setVisible( false );
}
}
}
/*!
- Updates icon
-*/
-void QtxToolBar::Watcher::updateIcon()
-{
- if ( !myCont || !myCont->widget() )
- return;
-
- const QPixmap* ico = myCont->widget()->icon();
- myCont->setIcon( ico ? *ico : QPixmap() );
-}
-
-/*!
- Updates caption
+ \class QtxToolBar
+ \brief Enhanced toolbar class.
*/
-void QtxToolBar::Watcher::updateCaption()
-{
- if ( myCont && myCont->widget() && !myCont->widget()->caption().isNull() )
- myCont->setCaption( myCont->widget()->caption() );
-}
/*!
- Constructor
+ \brief Constructor.
+ \param watch if \c true the event filter is installed to watch toolbar state changes
+ to update it properly
+ \param label toolbar title
+ \param parent parent widget
*/
-QtxToolBar::QtxToolBar( const bool watch, const QString& label, QMainWindow* main,
- QWidget* parent, bool newLine, const char* name, WFlags f )
-: QToolBar( label, main, parent, newLine, name, f ),
-myWatcher( 0 ),
-myStretch( false )
+QtxToolBar::QtxToolBar( const bool watch, const QString& label, QWidget* parent )
+: QToolBar( label, parent ),
+ myWatcher( 0 ),
+ myStretch( false )
{
if ( watch )
myWatcher = new Watcher( this );
}
/*!
- Constructor
+ \brief Constructor.
+ \param label toolbar title
+ \param parent parent widget
*/
-QtxToolBar::QtxToolBar( const QString& label, QMainWindow* main,
- QWidget* parent, bool newLine, const char* name, WFlags f )
-: QToolBar( label, main, parent, newLine, name, f ),
-myWatcher( 0 ),
-myStretch( false )
+QtxToolBar::QtxToolBar( const QString& label, QWidget* parent )
+: QToolBar( label, parent ),
+ myWatcher( 0 ),
+ myStretch( false )
{
}
/*!
- Constructor
+ \brief Constructor.
+ \param watch if \c true the event filter is installed to watch toolbar state changes
+ to update it properly
+ \param parent parent widget
*/
-QtxToolBar::QtxToolBar( const bool watch, QMainWindow* main, const char* name )
-: QToolBar( main, name ),
-myWatcher( 0 ),
-myStretch( false )
+QtxToolBar::QtxToolBar( const bool watch, QWidget* parent )
+: QToolBar( parent ),
+ myWatcher( 0 ),
+ myStretch( false )
{
if ( watch )
myWatcher = new Watcher( this );
}
/*!
- Constructor
+ \brief Constructor.
+ \param parent parent widget
*/
-QtxToolBar::QtxToolBar( QMainWindow* main, const char* name )
-: QToolBar( main, name ),
-myWatcher( 0 ),
-myStretch( false )
+QtxToolBar::QtxToolBar( QWidget* parent )
+: QToolBar( parent ),
+ myWatcher( 0 ),
+ myStretch( false )
{
}
/*!
- Destructor
+ \brief Destructor.
*/
QtxToolBar::~QtxToolBar()
{
}
/*!
- Change the toolbar's main widget
- \param wid - new main widget
-*/
-void QtxToolBar::setWidget( QWidget* wid )
-{
- if ( wid )
- wid->reparent( this, QPoint( 0, 0 ), wid->isVisibleTo( wid->parentWidget() ) );
-
- QToolBar::setWidget( wid );
-
- if ( !boxLayout() )
- return;
-
- for ( QLayoutIterator it = boxLayout()->iterator(); it.current(); ++it )
- {
- if ( it.current()->widget() == wid )
- {
- it.deleteCurrent();
- break;
- }
- }
-}
-
-/*!
- \return true if toolbar is stretchable
-*/
-bool QtxToolBar::isStretchable() const
-{
- return myStretch;
-}
-
-/*!
- Sets stretchable state of toolbar
- \param on - new state
-*/
-void QtxToolBar::setStretchable( const bool on )
-{
- if ( myStretch == on )
- return;
-
- myStretch = on;
-
- boxLayout()->setStretchFactor( widget(), myStretch ? 1 : 0 );
-
- if ( myStretch != isHorizontalStretchable() ||
- myStretch != isVerticalStretchable() )
- {
- if ( orientation() == Horizontal )
- setHorizontalStretchable( myStretch );
- else
- setVerticalStretchable( myStretch );
- }
-}
-
-/*!
- \return the recommended size for the widget
+ \brief Get the recommended size for the widget.
+ \return recommended toolbar size
*/
QSize QtxToolBar::sizeHint() const
{
QSize sz = QToolBar::sizeHint();
-
+/*
if ( place() == InDock && isStretchable() && area() )
{
if ( orientation() == Horizontal )
else
sz.setHeight( area()->height() );
}
-
+*/
return sz;
}
/*!
- \return the recommended minimum size for the widget
+ \brief Get the recommended minimum size for the widget.
+ \return recommended toolbar minimum size
*/
QSize QtxToolBar::minimumSizeHint() const
{
QSize sz = QToolBar::minimumSizeHint();
-
+/*
if ( place() == InDock && isStretchable() && area() )
{
if ( orientation() == Horizontal )
else
sz.setHeight( area()->height() );
}
-
+*/
return sz;
}
/*!
- Shows toolbar
+ \brief Show/hide the toolbar.
+ \param on new visibility state
*/
-void QtxToolBar::show()
+void QtxToolBar::setVisible( bool visible )
{
if ( myWatcher )
- myWatcher->shown( this );
+ {
+ if ( visible )
+ myWatcher->shown( this );
+ else
+ myWatcher->hidden( this );
+ }
- QToolBar::show();
+ QToolBar::setVisible( visible );
}
/*!
- Hides toolbar
+ \brief Get parent main window.
+ \return main window pointer
*/
-void QtxToolBar::hide()
+QMainWindow* QtxToolBar::mainWindow() const
{
- if ( myWatcher )
- myWatcher->hided( this );
-
- QToolBar::hide();
+ QMainWindow* mw = 0;
+ QWidget* wid = parentWidget();
+ while ( !mw && wid )
+ {
+ mw = ::qobject_cast<QMainWindow*>( wid );
+ wid = wid->parentWidget();
+ }
+ return mw;
}
#include "Qtx.h"
-#include <qtoolbar.h>
+#include <QToolBar>
class QTX_EXPORT QtxToolBar : public QToolBar
{
class Watcher;
public:
- QtxToolBar( const bool, const QString&, QMainWindow*, QWidget*, bool = false, const char* = 0, WFlags = 0 );
- QtxToolBar( const QString&, QMainWindow*, QWidget*, bool = false, const char* = 0, WFlags = 0 );
- QtxToolBar( const bool, QMainWindow* = 0, const char* = 0 );
- QtxToolBar( QMainWindow* = 0, const char* = 0 );
+ QtxToolBar( const bool, const QString&, QWidget* );
+ QtxToolBar( const QString&, QWidget* );
+ QtxToolBar( const bool, QWidget* = 0 );
+ QtxToolBar( QWidget* = 0 );
virtual ~QtxToolBar();
- virtual void setWidget( QWidget* );
-
- bool isStretchable() const;
- virtual void setStretchable( const bool );
-
virtual QSize sizeHint() const;
virtual QSize minimumSizeHint() const;
+ QMainWindow* mainWindow() const;
+
public slots:
- virtual void show();
- virtual void hide();
+ virtual void setVisible( bool );
private:
- Watcher* myWatcher;
- bool myStretch;
+ Watcher* myWatcher; //!< watcher object
+ bool myStretch; //!< stretching toolbar flag (not used)
};
#include "QtxToolTip.h"
-#include <qfont.h>
-#include <qtimer.h>
-#include <qcursor.h>
-#include <qfontmetrics.h>
-#include <qapplication.h>
+#include <QFont>
+#include <QTimer>
+#include <QCursor>
+#include <QFontMetrics>
+#include <QApplication>
+#include <QPalette>
+#include <QMouseEvent>
#define TOOLTIP_SHOW_DELAY 0500
#define TOOLTIP_HIDE_DELAY 7000
Constructor
*/
QtxToolTip::QtxToolTip( QWidget* parent )
-: QLabel( parent, "", WStyle_Customize | WStyle_NoBorder | WX11BypassWM | WStyle_Tool | WStyle_StaysOnTop | WType_TopLevel )
+: QLabel( parent, Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint | Qt::Tool | Qt::WindowStaysOnTopHint | Qt::Window )
{
+ setObjectName( "" );
setIndent( 3 );
- setAlignment( Qt::AlignLeft | Qt::AlignVCenter );
- setBackgroundColor( QColor( 255, 255, 231 ) );
+ setAlignment( Qt::AlignLeft | Qt::AlignVCenter );
+ QPalette palette;
+ palette.setColor( backgroundRole(), QColor( 255, 255, 231 ) );
+ setPalette( palette );
myWidgetRegion = QRect( -1, -1, -1, -1 );
installEventFilter( this );
mySleepTimer = new QTimer( this );
+ mySleepTimer->setSingleShot( true );
myWakeUpTimer = new QTimer( this );
+ myWakeUpTimer->setSingleShot( true );
connect( mySleepTimer, SIGNAL( timeout() ), this, SLOT( onSleepTimeOut() ) );
connect( myWakeUpTimer, SIGNAL( timeout() ), this, SLOT( onWakeUpTimeOut() ) );
if ( myWakeUpTimer->isActive() )
{
myWakeUpTimer->stop();
- myWakeUpTimer->start( myWakeUpDelayTime, true );
+ myWakeUpTimer->start( myWakeUpDelayTime );
}
if ( isVisible() )
{
else
{
if ( !myWidgetRegion.isValid() || myWidgetRegion.contains( thePos ) )
- myWakeUpTimer->start( myWakeUpDelayTime, true );
+ myWakeUpTimer->start( myWakeUpDelayTime );
}
}
if ( e->type() == QEvent::KeyPress )
myWidgetRegion = aWidgetRegion;
setGeometry( aRegion );
if ( myShowDelayTime != 0 )
- mySleepTimer->start( myShowDelayTime, true );
+ mySleepTimer->start( myShowDelayTime );
show();
}
QSize( textRegion.width() + 2 * margin, textRegion.height() ) );
QRect tipRegion( parentWidget()->mapToGlobal( dspRegion.topLeft() ), dspRegion.size() );
if ( tipRegion.left() < 0 )
- tipRegion.moveBy( -1 * tipRegion.left(), 0 );
+ tipRegion.translate( -1 * tipRegion.left(), 0 );
showTip( tipRegion, text, theRegion );
}
}
QWidget* reciever = parentWidget();
QMouseEvent* me = new QMouseEvent( QEvent::MouseButtonPress,
reciever->mapFromGlobal( e->globalPos() ),
- e->button(), e->state() );
+ e->button(), e->buttons(), Qt::KeypadModifier );
QApplication::sendEvent( reciever, me );
}
QWidget* reciever = parentWidget();
QMouseEvent* me = new QMouseEvent( QEvent::MouseButtonDblClick,
reciever->mapFromGlobal( e->globalPos() ),
- e->button(), e->state() );
+ e->button(), e->buttons(), Qt::KeypadModifier );
QApplication::sendEvent( reciever, me );
}
#include "Qtx.h"
-#include <qlabel.h>
+#include <QLabel>
class QTimer;
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File: QtxValidator.cxx
+// Author: Alexandre SOLOVYOV
+
+#include "QtxValidator.h"
+
+/*!
+ \class QtxIntValidator
+ \brief Validator for integer numbers with possibility to fix up the invalid value.
+*/
+
+/*!
+ \brief Constructor.
+ \param parent parent object
+*/
+QtxIntValidator::QtxIntValidator( QObject* parent )
+: QIntValidator( parent )
+{
+}
+
+/*!
+ \brief Constructor.
+ \param bot minimum possible value
+ \param top maximum possible value
+ \param parent parent object
+*/
+QtxIntValidator::QtxIntValidator( const int bot, const int top, QObject* parent )
+: QIntValidator( bot, top, parent )
+{
+}
+
+/*!
+ \brief Destructor.
+*/
+QtxIntValidator::~QtxIntValidator()
+{
+}
+
+/*!
+ \brief Validate the input and fixup it if necessary.
+
+ If the string represents integer value less then minimum value, it becomes equal to the minimum.
+ if the string represents integer value more then mazimum value, it becomes equal to the maximum.
+ If the string is not evaluated as integer it becomes equal to \c 0.
+
+ \param str the string to be validated
+*/
+void QtxIntValidator::fixup( QString& str ) const
+{
+ bool ok = false;
+ int i = str.toInt( &ok );
+ if ( ok )
+ {
+ if ( i < bottom() )
+ str = QString::number( bottom() );
+ else if( i > top() )
+ str = QString::number( top() );
+ }
+ else
+ str = QString ( "0" );
+}
+
+/*!
+ \class QtxDoubleValidator
+ \brief Validator for double numbers with possibility to fix up the invalid value.
+*/
+
+/*!
+ \brief Constructor
+ \param parent parent object
+*/
+QtxDoubleValidator::QtxDoubleValidator( QObject* parent )
+: QDoubleValidator( parent )
+{
+}
+
+/*!
+ \brief Constructor.
+ \param bot minimum possible value
+ \param top maximum possible value
+ \param dec precision (number of digits after dot)
+ \param parent parent object
+*/
+QtxDoubleValidator::QtxDoubleValidator( const double bot, const double top,
+ const int dec, QObject* parent )
+: QDoubleValidator( bot, top, dec, parent )
+{
+}
+
+/*!
+ \brief Destructor.
+*/
+QtxDoubleValidator::~QtxDoubleValidator()
+{
+}
+
+/*!
+ \brief Validate the input and fixup it if necessary.
+
+ If the string represents double value less then minimum value, it becomes equal to the minimum.
+ if the string represents double value more then mazimum value, it becomes equal to the maximum.
+ If the string is not evaluated as double it becomes equal to \c 0.
+
+ \param str the string to be validated
+*/
+void QtxDoubleValidator::fixup( QString& str ) const
+{
+ bool ok = false;
+ double d = str.toDouble( &ok );
+ if ( ok )
+ {
+ if ( d < bottom() )
+ str = QString::number( bottom() );
+ else if ( d > top() )
+ str = QString::number( top() );
+ }
+ else
+ str = QString( "0" );
+}
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File: QtxValidator.h
+// Author: Alexandre SOLOVYOV
+
+#ifndef QTX_VALIDATOR_H
+#define QTX_VALIDATOR_H
+
+#include "Qtx.h"
+
+#include <QValidator>
+
+class QTX_EXPORT QtxIntValidator : public QIntValidator
+{
+ Q_OBJECT
+
+public:
+ QtxIntValidator( QObject* );
+ QtxIntValidator( const int, const int, QObject* );
+ virtual ~QtxIntValidator();
+
+ virtual void fixup( QString& ) const;
+};
+
+class QTX_EXPORT QtxDoubleValidator : public QDoubleValidator
+{
+ Q_OBJECT
+
+public:
+ QtxDoubleValidator( QObject* );
+ QtxDoubleValidator( const double, const double, const int, QObject* );
+ virtual ~QtxDoubleValidator();
+
+ virtual void fixup( QString& ) const;
+};
+
+#endif
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File: QtxWorkspace.cxx
+// Author: Sergey TELKOV
+
+#include "QtxWorkspace.h"
+
+#include <QWidgetList>
+
+/*!
+ \class QtxWorkspace
+ \brief A workspace widget which can be used in the MDI application
+ as top-level widget in the application main window.
+
+ Provides methods to tile child windows in horizontal or vertical
+ direction.
+*/
+
+/*!
+ \brief Constructor.
+ \param parent parent widget
+*/
+QtxWorkspace::QtxWorkspace( QWidget* parent )
+: QWorkspace( parent )
+{
+}
+
+/*!
+ \brief Destructor.
+*/
+QtxWorkspace::~QtxWorkspace()
+{
+}
+
+/*!
+ \brief Tiles child windows vertically.
+*/
+void QtxWorkspace::tileVertical()
+{
+ QWidgetList winList = windowList();
+ if ( winList.isEmpty() )
+ return;
+
+ int count = 0;
+ for ( QWidgetList::const_iterator itr = winList.begin(); itr != winList.end(); ++itr )
+ if ( !( (*itr)->windowState() & Qt::WindowMinimized ) )
+ count++;
+
+ if ( !count )
+ return;
+
+ if ( activeWindow() && ( activeWindow()->windowState() & Qt::WindowMaximized ) )
+ activeWindow()->showNormal();
+
+ int y = 0;
+ int heightForEach = height() / count;
+ for ( QWidgetList::iterator it = winList.begin(); it != winList.end(); ++it )
+ {
+ QWidget* win = *it;
+ if ( win->windowState() & Qt::WindowMinimized )
+ continue;
+
+ if ( win->windowState() & Qt::WindowMaximized )
+ {
+ win->hide();
+ win->showNormal();
+ }
+
+// QApplication::sendPostedEvents( 0, QEvent::ShowNormal );
+
+ int prefH = win->minimumHeight() + win->parentWidget()->baseSize().height();
+ int actualH = qMax( heightForEach, prefH );
+
+ win->parentWidget()->setGeometry( 0, y, width(), actualH );
+ y += actualH;
+ }
+}
+
+/*!
+ \brief Tiles child windows horizontally.
+*/
+void QtxWorkspace::tileHorizontal()
+{
+ QWidgetList winList = windowList();
+ if ( winList.isEmpty() )
+ return;
+
+ int count = 0;
+ for ( QWidgetList::const_iterator itr = winList.begin(); itr != winList.end(); ++itr )
+ if ( !( (*itr)->windowState() & Qt::WindowMinimized ) )
+ count++;
+
+ if ( !count )
+ return;
+
+ if ( activeWindow() && activeWindow()->windowState() & Qt::WindowMaximized )
+ activeWindow()->showNormal();
+
+ int x = 0;
+ int widthForEach = width() / count;
+ for ( QWidgetList::iterator it = winList.begin(); it != winList.end(); ++it )
+ {
+ QWidget* win = *it;
+ if ( win->windowState() & Qt::WindowMinimized )
+ continue;
+
+ if ( win->windowState() & Qt::WindowMaximized )
+ {
+ win->hide();
+ win->showNormal();
+ }
+
+// QApplication::sendPostedEvents( 0, QEvent::ShowNormal );
+
+ int prefW = win->minimumWidth();
+ int actualW = qMax( widthForEach, prefW );
+
+ win->parentWidget()->setGeometry( x, 0, actualW, height() );
+ x += actualW;
+ }
+}
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File: QtxWorkspace.h
+// Author: Sergey TELKOV
+
+#ifndef QTXWORKSPACE_H
+#define QTXWORKSPACE_H
+
+#include "Qtx.h"
+
+#include <QWorkspace>
+
+#ifdef WIN32
+#pragma warning( disable:4251 )
+#endif
+
+class QTX_EXPORT QtxWorkspace : public QWorkspace
+{
+ Q_OBJECT
+
+public:
+ QtxWorkspace( QWidget* = 0 );
+ virtual ~QtxWorkspace();
+
+public slots:
+ void tileVertical();
+ void tileHorizontal();
+};
+
+#ifdef WIN32
+#pragma warning( default:4251 )
+#endif
+
+#endif
#include "QtxWorkspaceAction.h"
-#include <qpopupmenu.h>
-#include <qworkspace.h>
-#include <qwidgetlist.h>
+#include "QtxWorkspace.h"
+
+#include <QMenu>
+#include <QWidgetList>
/*!
- Constructor
+ \class QtxWorkspaceAction
+ \brief Implements actions group for menu Windows with standard operations, like
+ "Cascade", "Tile", "Tile Horizontally", etc.
*/
-QtxWorkspaceAction::QtxWorkspaceAction( QWorkspace* ws, QObject* parent, const char* name )
-: QtxAction( tr( "Controls windows into workspace" ), tr( "Workspace management" ), 0, parent, name ),
-myFlags( Standard ),
-myWorkspace( ws )
-{
- myItem.insert( Cascade, new QtxAction( tr( "Arranges the windows as overlapping tiles" ),
- tr( "Cascade" ), 0, this, 0, false ) );
- myItem.insert( Tile, new QtxAction( tr( "Arranges the windows as nonoverlapping tiles" ),
- tr( "Tile" ), 0, this, 0, false ) );
- myItem.insert( HTile, new QtxAction( tr( "Arranges the windows as nonoverlapping horizontal tiles" ),
- tr( "Tile horizontally" ), 0, this, 0, false ) );
- myItem.insert( VTile, new QtxAction( tr( "Arranges the windows as nonoverlapping vertical tiles" ),
- tr( "Tile vertically" ), 0, this, 0, false ) );
-
- connect( myItem[Tile], SIGNAL( activated() ), this, SLOT( tile() ) );
- connect( myItem[Cascade], SIGNAL( activated() ), this, SLOT( cascade() ) );
- connect( myItem[HTile], SIGNAL( activated() ), this, SLOT( tileVertical() ) );
- connect( myItem[VTile], SIGNAL( activated() ), this, SLOT( tileHorizontal() ) );
-}
/*!
- Destructor
+ \brief Constructor.
+ \param ws parent workspace
+ \param parent parent object (owner of the action)
*/
-QtxWorkspaceAction::~QtxWorkspaceAction()
+QtxWorkspaceAction::QtxWorkspaceAction( QtxWorkspace* ws, QObject* parent )
+: QtxActionSet( parent ),
+ myWorkspace( ws ),
+ myWindowsFlag( true )
{
+ insertAction( new QtxAction( tr( "Arranges the windows as overlapping tiles" ),
+ tr( "Cascade" ), 0, this ), Cascade );
+ insertAction( new QtxAction( tr( "Arranges the windows as nonoverlapping tiles" ),
+ tr( "Tile" ), 0, this ), Tile );
+ insertAction( new QtxAction( tr( "Arranges the windows as nonoverlapping horizontal tiles" ),
+ tr( "Tile horizontally" ), 0, this ), HTile );
+ insertAction( new QtxAction( tr( "Arranges the windows as nonoverlapping vertical tiles" ),
+ tr( "Tile vertically" ), 0, this ), VTile );
+
+ connect( this, SIGNAL( triggered( int ) ), this, SLOT( onTriggered( int ) ) );
+
+ setMenuActions( Standard );
}
/*!
- \return corresponding workspace
+ \brief Destructor.
*/
-QWorkspace* QtxWorkspaceAction::workspace() const
+QtxWorkspaceAction::~QtxWorkspaceAction()
{
- return myWorkspace;
}
/*!
- \return set of action flags
+ \brief Get workspace.
+ \return parent workspace
*/
-int QtxWorkspaceAction::items() const
+QtxWorkspace* QtxWorkspaceAction::workspace() const
{
- return myFlags;
+ return myWorkspace;
}
/*!
- Sets action flags
- \param flags - new set of flags
+ \brief Set actions to be visible in the menu.
+
+ Actions, which IDs are set in \a flags parameter, will be shown in the
+ menu bar. Other actions will not be shown.
+
+ \param flags ORed together actions flags
*/
-void QtxWorkspaceAction::setItems( const int flags )
+void QtxWorkspaceAction::setMenuActions( const int flags )
{
- if ( !flags || flags == myFlags || !( flags & Operations ) )
- return;
-
- myFlags = flags;
+ action( Cascade )->setVisible( flags & Cascade );
+ action( Tile )->setVisible( flags & Tile );
+ action( VTile )->setVisible( flags & VTile );
+ action( HTile )->setVisible( flags & HTile );
+ myWindowsFlag = flags & Windows;
}
/*!
- \return true if action contains all flags
- \param flags - new set of flags
+ \brief Get menu actions which are currently visible in the menu bar.
+ \return ORed together actions flags
+ \sa setMenuActions()
*/
-bool QtxWorkspaceAction::hasItems( const int flags ) const
+int QtxWorkspaceAction::menuActions() const
{
- return ( myFlags & flags ) == flags;
+ int ret = 0;
+ ret = ret | ( action( Cascade )->isVisible() ? Cascade : 0 );
+ ret = ret | ( action( Tile )->isVisible() ? Tile : 0 );
+ ret = ret | ( action( VTile )->isVisible() ? VTile : 0 );
+ ret = ret | ( action( HTile )->isVisible() ? HTile : 0 );
+ ret = ret | ( myWindowsFlag ? Windows : 0 );
+ return ret;
}
/*!
- \return accelerator of item
- \param id - item id
+ \brief Get keyboard accelerator for the specified action.
+ \param id menu action ID
+ \return keyboard accelerator of menu item or 0 if there is no such action
*/
int QtxWorkspaceAction::accel( const int id ) const
{
int a = 0;
- if ( myItem.contains( id ) )
- a = myItem[id]->accel();
+ if ( action( id ) )
+ a = action( id )->shortcut();
return a;
}
/*!
- \return icons of item
- \param id - item id
+ \brief Get icon for the specified action.
+
+ If \a id is invalid, null icon is returned.
+
+ \param id menu action ID
+ \return menu item icon
*/
-QIconSet QtxWorkspaceAction::iconSet( const int id ) const
+QIcon QtxWorkspaceAction::icon( const int id ) const
{
- QIconSet ico;
- if ( myItem.contains( id ) )
- ico = myItem[id]->iconSet();
+ QIcon ico;
+ if ( action( id ) )
+ ico = action( id )->icon();
return ico;
}
/*!
- \return menu text of item
- \param id - item id
+ \brief Get menu item text for the specified action.
+ \param id menu action ID
+ \return menu item text or null QString if there is no such action
*/
-QString QtxWorkspaceAction::menuText( const int id ) const
+QString QtxWorkspaceAction::text( const int id ) const
{
QString txt;
- if ( myItem.contains( id ) )
- txt = myItem[id]->menuText();
+ if ( action( id ) )
+ txt = action( id )->text();
return txt;
}
/*!
- \return status tip of item
- \param id - item id
+ \brief Get status bar tip for the specified action.
+ \param id menu action ID
+ \return status bar tip menu item or null QString if there is no such action
*/
QString QtxWorkspaceAction::statusTip( const int id ) const
{
QString txt;
- if ( myItem.contains( id ) )
- txt = myItem[id]->statusTip();
+ if ( action( id ) )
+ txt = action( id )->statusTip();
return txt;
}
/*!
- Changes accelerator of item
- \param id - item id
- \param a - new accelerator
+ \brief Set keyboard accelerator for the specified action.
+ \param id menu action ID
+ \param a new keyboard accelerator
*/
void QtxWorkspaceAction::setAccel( const int id, const int a )
{
- if ( myItem.contains( id ) )
- myItem[id]->setAccel( a );
+ if ( action( id ) )
+ action( id )->setShortcut( a );
}
/*!
- Changes icons of item
- \param id - item id
- \param ico - new icons
+ \brief Set menu item icon for the specified action.
+ \param id menu action ID
+ \param ico new menu item icon
*/
-void QtxWorkspaceAction::setIconSet( const int id, const QIconSet& ico )
+void QtxWorkspaceAction::setIcon( const int id, const QIcon& icon )
{
- if ( myItem.contains( id ) )
- myItem[id]->setIconSet( ico );
+ if ( action( id ) )
+ action( id )->setIcon( icon );
}
/*!
- Changes menu text of item
- \param id - item id
- \param txt - new menu text
+ \brief Set menu item text for the specified action.
+ \param id menu action ID
+ \param txt new menu item text
*/
-void QtxWorkspaceAction::setMenuText( const int id, const QString& txt )
+void QtxWorkspaceAction::setText( const int id, const QString& txt )
{
- if ( myItem.contains( id ) )
- myItem[id]->setMenuText( txt );
+ if ( action( id ) )
+ action( id )->setText( txt );
}
/*!
- Changes status tip of item
- \param id - item id
- \param txt - new status tip
+ \brief Set menu item status bar tip for the specified action.
+ \param id menu action ID
+ \param txt new menu item status bar tip
*/
void QtxWorkspaceAction::setStatusTip( const int id, const QString& txt )
{
- if ( myItem.contains( id ) )
- myItem[id]->setStatusTip( txt );
-}
-
-/*!
- Adds action to widget
- \param wid - widget
-*/
-bool QtxWorkspaceAction::addTo( QWidget* wid )
-{
- return addTo( wid, -1 );
-}
-
-/*!
- Adds action to widget
- \param wid - widget
- \param idx - position
-*/
-bool QtxWorkspaceAction::addTo( QWidget* wid, const int idx )
-{
- if ( !wid || !wid->inherits( "QPopupMenu" ) )
- return false;
-
- QPopupMenu* pm = (QPopupMenu*)wid;
- checkPopup( pm );
-
- if ( myMenu.contains( pm ) )
- return false;
-
- myMenu.insert( pm, QIntList() );
- fillPopup( pm, idx );
-
- connect( pm, SIGNAL( aboutToShow() ), this, SLOT( onAboutToShow() ) );
- connect( pm, SIGNAL( destroyed( QObject* ) ), this, SLOT( onPopupDestroyed( QObject* ) ) );
-
- return true;
+ if ( action( id ) )
+ action( id )->setStatusTip( txt );
}
/*!
- Removes action from widget
- \param wid - widget
-*/
-bool QtxWorkspaceAction::removeFrom( QWidget* wid )
-{
- if ( !wid || !wid->inherits( "QPopupMenu" ) )
- return false;
-
- QPopupMenu* pm = (QPopupMenu*)wid;
- if ( !myMenu.contains( pm ) )
- return false;
-
- clearPopup( pm );
-
- disconnect( pm, SIGNAL( aboutToShow() ), this, SLOT( onAboutToShow() ) );
- disconnect( pm, SIGNAL( destroyed( QObject* ) ), this, SLOT( onPopupDestroyed( QObject* ) ) );
-
- myMenu.remove( pm );
-
- return true;
-}
-
-/*!
- Performs action
- \param type - action type
+ \brief Process action activated by the user.
+ \param type action ID
*/
void QtxWorkspaceAction::perform( const int type )
{
}
/*!
- Performs tile action
+ \brief Tile child windows in the workspace.
*/
void QtxWorkspaceAction::tile()
{
- QWorkspace* ws = workspace();
- if ( !ws )
- return;
-
- ws->tile();
+ QtxWorkspace* ws = workspace();
+ if ( ws )
+ ws->tile();
}
/*!
- Performs cascade action
+ \brief Cascade child windows in the workspace.
*/
void QtxWorkspaceAction::cascade()
{
- QWorkspace* ws = workspace();
+ QtxWorkspace* ws = workspace();
if ( !ws )
return;
int h = ws->height();
QWidgetList winList = ws->windowList();
- for ( QWidgetListIt it( winList ); it.current(); ++it )
- it.current()->resize( int( w * 0.8 ), int( h * 0.8 ) );
+ for ( QWidgetList::iterator it = winList.begin(); it != winList.end(); ++it )
+ (*it)->resize( int( w * 0.8 ), int( h * 0.8 ) );
}
/*!
- Performs tile vertical action
+ \brief Tile child windows in the workspace in the vertical direction.
*/
void QtxWorkspaceAction::tileVertical()
{
- QWorkspace* wrkSpace = workspace();
- if ( !wrkSpace )
- return;
-
- QWidgetList winList = wrkSpace->windowList();
- if ( winList.isEmpty() )
- return;
-
- int count = 0;
- for ( QWidgetListIt itr( winList ); itr.current(); ++itr )
- if ( !itr.current()->testWState( WState_Minimized ) )
- count++;
-
- if ( !count )
- return;
-
- int y = 0;
-
- int heightForEach = wrkSpace->height() / count;
- for ( QWidgetListIt it( winList ); it.current(); ++it )
- {
- QWidget* win = it.current();
- if ( win->testWState( WState_Minimized ) )
- continue;
-
- if ( win->testWState( WState_Maximized ) )
- {
- win->hide();
- win->showNormal();
- }
- int prefH = win->minimumHeight() + win->parentWidget()->baseSize().height();
- int actualH = QMAX( heightForEach, prefH );
-
- win->parentWidget()->setGeometry( 0, y, wrkSpace->width(), actualH );
- y += actualH;
- }
+ QtxWorkspace* ws = workspace();
+ if ( ws )
+ ws->tileVertical();
}
/*!
- Performs tile horizontal action
+ \brief Tile child windows in the workspace in the horizontal direction.
*/
void QtxWorkspaceAction::tileHorizontal()
{
- QWorkspace* wrkSpace = workspace();
- if ( !wrkSpace )
- return;
-
- QWidgetList winList = wrkSpace->windowList();
- if ( winList.isEmpty() )
- return;
-
- int count = 0;
- for ( QWidgetListIt itr( winList ); itr.current(); ++itr )
- if ( !itr.current()->testWState( WState_Minimized ) )
- count++;
-
- if ( !count )
- return;
-
- int x = 0;
- int widthForEach = wrkSpace->width() / count;
- for ( QWidgetListIt it( winList ); it.current(); ++it )
- {
- QWidget* win = it.current();
- if ( win->testWState( WState_Minimized ) )
- continue;
-
- if ( win->testWState( WState_Maximized ) )
- {
- win->hide();
- win->showNormal();
- }
- int prefW = win->minimumWidth();
- int actualW = QMAX( widthForEach, prefW );
-
- win->parentWidget()->setGeometry( x, 0, actualW, wrkSpace->height() );
- x += actualW;
- }
+ QtxWorkspace* ws = workspace();
+ if ( ws )
+ ws->tileHorizontal();
}
/*!
- SLOT: called just before the popup menu is displayed, updates popup
+ \brief Called when action is added to the menu bar.
+ \param w menu bar widget this action is being added to
*/
-void QtxWorkspaceAction::onAboutToShow()
+void QtxWorkspaceAction::addedTo( QWidget* w )
{
- const QObject* obj = sender();
- if ( !obj || !obj->inherits( "QPopupMenu" ) )
- return;
-
- updatePopup( (QPopupMenu*)obj );
-}
+ QtxActionSet::addedTo( w );
-/*!
- SLOT: called when popup menu is destroyed, removes it from menu
-*/
-void QtxWorkspaceAction::onPopupDestroyed( QObject* obj )
-{
- myMenu.remove( (QPopupMenu*)obj );
+ QMenu* pm = ::qobject_cast<QMenu*>( w );
+ if ( pm )
+ connect( pm, SIGNAL( aboutToShow() ), this, SLOT( onAboutToShow() ) );
}
/*!
- Updates popup
- \param pm - popup menu
+ \brief Called when action is removed from the menu bar.
+ \param w menu bar widget this action is being removed from
*/
-void QtxWorkspaceAction::checkPopup( QPopupMenu* pm )
+void QtxWorkspaceAction::removedFrom( QWidget* w )
{
- if ( !myMenu.contains( pm ) )
- return;
-
- QIntList updList;
- for ( QIntList::const_iterator it = myMenu[pm].begin(); it != myMenu[pm].end(); ++it )
- {
- if ( pm->indexOf( *it ) != -1 )
- updList.append( *it );
- }
+ QtxActionSet::removedFrom( w );
- myMenu.remove( pm );
-
- if ( !updList.isEmpty() )
- myMenu.insert( pm, updList );
- else
- {
+ QMenu* pm = ::qobject_cast<QMenu*>( w );
+ if ( pm )
disconnect( pm, SIGNAL( aboutToShow() ), this, SLOT( onAboutToShow() ) );
- disconnect( pm, SIGNAL( destroyed( QObject* ) ), this, SLOT( onPopupDestroyed( QObject* ) ) );
- }
}
/*!
- Clears and refills popup and updates state of actions
- \param pm - popup menu
+ \brief Update all menu action state.
*/
-void QtxWorkspaceAction::updatePopup( QPopupMenu* pm )
+void QtxWorkspaceAction::updateContent()
{
- if ( !myMenu.contains( pm ) )
- return;
-
- fillPopup( pm, clearPopup( pm ) );
-
bool count = workspace() ? workspace()->windowList().count() : 0;
- myItem[Cascade]->setEnabled( count );
- myItem[Tile]->setEnabled( count );
- myItem[HTile]->setEnabled( count );
- myItem[VTile]->setEnabled( count );
-}
-
-/*!
- Clears popup
- \param pm - popup menu
-*/
-int QtxWorkspaceAction::clearPopup( QPopupMenu* pm )
-{
- if ( !myMenu.contains( pm ) )
- return -1;
-
- int idx = -1;
- const QIntList& lst = myMenu[pm];
- for ( QIntList::const_iterator it = lst.begin(); it != lst.end() && idx == -1; ++it )
- idx = pm->indexOf( *it );
+ action( Cascade )->setEnabled( count );
+ action( Tile )->setEnabled( count );
+ action( HTile )->setEnabled( count );
+ action( VTile )->setEnabled( count );
- for ( ItemMap::ConstIterator mit = myItem.begin(); mit != myItem.end(); ++mit )
- mit.data()->removeFrom( pm );
-
- for ( QIntList::const_iterator itr = lst.begin(); itr != lst.end(); ++itr )
- pm->removeItem( *itr );
-
- return idx;
+ updateWindows();
}
/*!
- Fills popup with items
- \param pm - popup menu
- \param idx - position
+ \brief Update actions which refer to the opened child windows.
*/
-void QtxWorkspaceAction::fillPopup( QPopupMenu* pm, const int idx )
+void QtxWorkspaceAction::updateWindows()
{
- if ( !pm )
+ QtxWorkspace* ws = workspace();
+ if ( !ws )
return;
- int index = idx < 0 ? pm->count() : QMIN( (int)pm->count(), idx );
+ QList<QAction*> lst = actions();
+ for ( QList<QAction*>::iterator it = lst.begin(); it != lst.end(); ++it )
+ {
+ int id = actionId( *it );
+ if ( id >= Windows )
+ removeAction( *it );
+ }
- myMenu.insert( pm, QIntList() );
- QIntList& lst = myMenu[pm];
+ bool base = action( Cascade )->isVisible() || action( Tile )->isVisible() ||
+ action( HTile )->isVisible() || action( VTile )->isVisible();
- for ( ItemMap::ConstIterator mit = myItem.begin(); mit != myItem.end(); ++mit )
+ QList<QAction*> items;
+ QMap<QAction*, int> map;
+ if ( menuActions() & Windows )
{
- if ( !hasItems( mit.key() ) )
- continue;
+ int index = 1;
+ QWidgetList wList = ws->windowList();
+ for ( QWidgetList::iterator it = wList.begin(); it != wList.end(); ++it, index++ )
+ {
+ QWidget* wid = *it;
+ QAction* a = new QtxAction( wid->windowTitle(), wid->windowTitle(), 0, this, true );
+ a->setChecked( wid == ws->activeWindow() );
+ items.append( a );
+ map.insert( a, Windows + index );
+ }
- mit.data()->addTo( pm, index );
- lst.append( pm->idAt( index++ ) );
+ if ( base && !items.isEmpty() )
+ {
+ QAction* sep = new QtxAction( this );
+ sep->setSeparator( true );
+ items.prepend( sep );
+ map.insert( sep, Windows );
+ }
}
- QWorkspace* ws = workspace();
- if ( !ws || !hasItems( Windows ) )
- return;
+ if ( !items.isEmpty() )
+ insertActions( items );
- QWidgetList wList = ws->windowList();
- if ( wList.isEmpty() )
- return;
+ for ( QMap<QAction*, int>::const_iterator itr = map.begin(); itr != map.end(); ++itr )
+ setActionId( itr.key(), itr.value() );
+}
- lst.append( pm->insertSeparator( index++ ) );
+/*!
+ \brief Called when parent menu is about to show.
- int param = 0;
- pm->setCheckable( true );
- for ( QWidgetListIt it( wList ); it.current(); ++it )
- {
- int id = pm->insertItem( it.current()->caption(), this, SLOT( onItemActivated( int ) ), 0, -1, index++ );
- pm->setItemParameter( id, param++ );
- pm->setItemChecked( id, it.current() == ws->activeWindow() );
- lst.append( id );
- }
+ Updates all menu items.
+*/
+void QtxWorkspaceAction::onAboutToShow()
+{
+ QMenu* pm = ::qobject_cast<QMenu*>( sender() );
+ if ( pm )
+ updateContent();
}
/*!
- SLOT: called when popup item corresponding to window is activated, activates window
+ \brief Called when menu item corresponding to some child window is activated.
+
+ Activates correposponding child window.
+
+ \param idx menu item index
*/
-void QtxWorkspaceAction::onItemActivated( int idx )
+void QtxWorkspaceAction::activateItem( const int idx )
{
- QWorkspace* ws = workspace();
+ QtxWorkspace* ws = workspace();
if ( !ws )
return;
QWidgetList wList = ws->windowList();
- if ( idx < 0 || idx >= (int)wList.count() )
- return;
+ if ( idx >= 0 && idx < (int)wList.count() )
+ wList.at( idx )->setFocus();
+}
+
+/*!
+ \brief Called when menu item is activated by the user.
+
+ Perform the corresponding action.
- wList.at( idx )->setFocus();
+ \param id menu item identifier
+*/
+void QtxWorkspaceAction::onTriggered( int id )
+{
+ if ( id < Windows )
+ perform( id );
+ else
+ activateItem( id - Windows - 1 );
}
#ifndef QTXWORKSPACEACTION_H
#define QTXWORKSPACEACTION_H
-#include "QtxAction.h"
+#include "QtxActionSet.h"
-class QWorkspace;
+class QtxWorkspace;
#ifdef WIN32
#pragma warning( disable:4251 )
#endif
-class QTX_EXPORT QtxWorkspaceAction : public QtxAction
+class QTX_EXPORT QtxWorkspaceAction : public QtxActionSet
{
Q_OBJECT
public:
- enum { Cascade = 0x0001,
- Tile = 0x0002,
- VTile = 0x0004,
- HTile = 0x0008,
- Windows = 0x0010,
+ //! Actions (menu items) ID
+ enum { Cascade = 0x0001, //!< "Cascade child windows" operation
+ Tile = 0x0002, //!< "Tile child windows" operation
+ VTile = 0x0004, //!< "Tile child windows vertically" operation
+ HTile = 0x0008, //!< "Tile child windows horizontally" operation
+ Windows = 0x0010, //!< A list of child windows menu items
Standard = Cascade | Tile | Windows,
Operations = Cascade | Tile | VTile | HTile,
All = Standard | HTile | VTile };
public:
- QtxWorkspaceAction( QWorkspace*, QObject* = 0, const char* = 0 );
+ QtxWorkspaceAction( QtxWorkspace*, QObject* = 0 );
virtual ~QtxWorkspaceAction();
- QWorkspace* workspace() const;
+ QtxWorkspace* workspace() const;
- int items() const;
- void setItems( const int );
- bool hasItems( const int ) const;
+ int menuActions() const;
+ void setMenuActions( const int );
- int accel( const int ) const;
- QIconSet iconSet( const int ) const;
- QString menuText( const int ) const;
- QString statusTip( const int ) const;
+ QIcon icon( const int ) const;
+ QString text( const int ) const;
+ int accel( const int ) const;
+ QString statusTip( const int ) const;
- void setAccel( const int, const int );
- void setIconSet( const int, const QIconSet& );
- void setMenuText( const int, const QString& );
- void setStatusTip( const int, const QString& );
+ void setAccel( const int, const int );
+ void setIcon( const int, const QIcon& );
+ void setText( const int, const QString& );
+ void setStatusTip( const int, const QString& );
- virtual bool addTo( QWidget* );
- virtual bool addTo( QWidget*, const int );
- virtual bool removeFrom( QWidget* );
-
- void perform( const int );
+ void perform( const int );
public slots:
- void tile();
- void cascade();
- void tileVertical();
- void tileHorizontal();
+ void tile();
+ void cascade();
+ void tileVertical();
+ void tileHorizontal();
private slots:
- void onAboutToShow();
- void onItemActivated( int );
- void onPopupDestroyed( QObject* );
-
-private:
- void checkPopup( QPopupMenu* );
- void updatePopup( QPopupMenu* );
+ void onAboutToShow();
+ void onTriggered( int );
- int clearPopup( QPopupMenu* );
- void fillPopup( QPopupMenu*, const int );
+protected:
+ virtual void addedTo( QWidget* );
+ virtual void removedFrom( QWidget* );
private:
- typedef QMap<QPopupMenu*, QIntList> MenuMap;
- typedef QMap<int, QtxAction*> ItemMap;
+ void updateContent();
+ void updateWindows();
+ void activateItem( const int );
private:
- MenuMap myMenu;
- ItemMap myItem;
- int myFlags;
- QWorkspace* myWorkspace;
+ QtxWorkspace* myWorkspace; //!< parent workspace
+ bool myWindowsFlag; //!< "show child windows items" flag
};
#ifdef WIN32
// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
+//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
+// License as published by the Free Software Foundation; either
// version 2.1 of the License.
-//
-// This library 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
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#include "QtxWorkstack.h"
-#include <qstyle.h>
-#include <qimage.h>
-#include <qaction.h>
-#include <qlayout.h>
-#include <qpixmap.h>
-#include <qiconset.h>
-#include <qpainter.h>
-#include <qsplitter.h>
-#include <qpopupmenu.h>
-#include <qobjectlist.h>
-#include <qpushbutton.h>
-#include <qwidgetstack.h>
-#include <qapplication.h>
-#include <qinputdialog.h>
-#include <qevent.h>
-#include <qregexp.h>
+#include "QtxAction.h"
-#define DARK_COLOR_LIGHT 250
+#include <QRegExp>
+#include <QMenu>
+#include <QFocusEvent>
+#include <QMouseEvent>
+#include <QStyle>
+#include <QLayout>
+#include <QSplitter>
+#include <QRubberBand>
+#include <QPushButton>
+#include <QApplication>
+#include <QInputDialog>
+#include <QStackedWidget>
+
+#define DARK_COLOR_LIGHT 250
/*!
- Constructor
+ \class QtxWorkstackArea::WidgetEvent
+ \internal
+ \brief Internal class used to forward child widgets events to the workarea
*/
-QtxWorkstack::QtxWorkstack( QWidget* parent )
-: QWidget( parent ),
-myWin( 0 ),
-myArea( 0 ),
-myWorkWin( 0 ),
-myWorkArea( 0 )
+
+class QtxWorkstackArea::WidgetEvent : public QEvent
{
- myActionsMap.insert( SplitVertical, new QAction( tr( "Split vertically" ), 0, this ) );
- myActionsMap.insert( SplitHorizontal, new QAction( tr( "Split horizontally" ), 0, this ) );
- myActionsMap.insert( Close, new QAction( tr( "Close" ), 0, this ) );
- myActionsMap.insert( Rename, new QAction( tr( "Rename" ), 0, this ) );
+public:
+ WidgetEvent( Type t, QWidget* w = 0 ) : QEvent( t ), myWidget( w ) {};
- connect( myActionsMap[SplitVertical], SIGNAL( activated() ), this, SLOT( splitVertical() ) );
- connect( myActionsMap[SplitHorizontal], SIGNAL( activated() ), this, SLOT( splitHorizontal() ) );
- connect( myActionsMap[Close], SIGNAL( activated() ), this, SLOT( onCloseWindow() ) );
- connect( myActionsMap[Rename], SIGNAL( activated() ), this, SLOT( onRename() ) );
+ QWidget* widget() const { return myWidget; }
- QVBoxLayout* base = new QVBoxLayout( this );
- mySplit = new QSplitter( this );
- mySplit->setChildrenCollapsible( false );
- base->addWidget( mySplit );
-}
+private:
+ QWidget* myWidget; // event receiver widget
+};
/*!
- Destructor
+ \class QtxWorkstackDrag
+ \internal
+ \brief Workstack drag object
*/
-QtxWorkstack::~QtxWorkstack()
+
+/*!
+ \brief Constructor.
+ \param ws parent workstack
+ \param child child widget container
+*/
+QtxWorkstackDrag::QtxWorkstackDrag( QtxWorkstack* ws, QtxWorkstackChild* child )
+: QObject( 0 ),
+ myWS( ws ),
+ myChild( child ),
+ myTab( -1 ),
+ myArea( 0 ),
+ myTabRect( 0 ),
+ myAreaRect( 0 )
{
+ QApplication::instance()->installEventFilter( this );
}
/*!
- \return list of all widgets in all areas
+ \brief Destructor.
*/
-QWidgetList QtxWorkstack::windowList() const
+QtxWorkstackDrag::~QtxWorkstackDrag()
{
- QPtrList<QtxWorkstackArea> lst;
- areas( mySplit, lst, true );
+ QApplication::instance()->removeEventFilter( this );
- QWidgetList widList;
- for ( QPtrListIterator<QtxWorkstackArea> it( lst ); it.current(); ++it )
+ endDrawRect();
+}
+
+/*!
+ \brief Custom event filter.
+ \param o event receiver widget
+ \param e event
+ \return \c true if event should be filtered (stop further processing)
+*/
+bool QtxWorkstackDrag::eventFilter( QObject*, QEvent* e )
+{
+ switch ( e->type() )
{
- QWidgetList wids = it.current()->widgetList();
- for ( QWidgetListIt itr( wids ); itr.current(); ++itr )
- widList.append( itr.current() );
+ case QEvent::MouseMove:
+ updateTarget( ((QMouseEvent*)e)->globalPos() );
+ break;
+ case QEvent::MouseButtonRelease:
+ drawRect();
+ endDrawRect();
+ dropWidget();
+ deleteLater();
+ break;
+ default:
+ return false;
}
-
- return widList;
+ return true;
}
/*!
- \return list of all widgets in active area
+ \brief Detect and set dropping target widget.
+ \param p current dragging position
*/
-QWidgetList QtxWorkstack::splitWindowList() const
+void QtxWorkstackDrag::updateTarget( const QPoint& p )
{
- return myArea ? myArea->widgetList() : QWidgetList();
+ int tab = -1;
+ QtxWorkstackArea* area = detectTarget( p, tab );
+ setTarget( area, tab );
}
/*!
- \return active widget
+ \brief Detect dropping target.
+ \param p current dragging position
+ \param tab resulting target tab page index
+ \return target workarea or 0 if there is no correct drop target
*/
-QWidget* QtxWorkstack::activeWindow() const
+QtxWorkstackArea* QtxWorkstackDrag::detectTarget( const QPoint& p, int& tab ) const
{
- return myWin;
+ if ( p.isNull() )
+ return 0;
+
+ QtxWorkstackArea* area = myWS->areaAt( p );
+ if ( area )
+ tab = area->tabAt( p );
+ return area;
}
/*!
- Splits widgets
- \param o - orientation (Qt::Orientation)
+ \brief Set dropping target.
+ \param area new target workarea
+ \param tab target workarea's tab page index
*/
-void QtxWorkstack::split( const int o )
+void QtxWorkstackDrag::setTarget( QtxWorkstackArea* area, const int tab )
{
- QtxWorkstackArea* area = myWorkArea;
- if ( !area )
- area = activeArea();
- if ( !area )
+ if ( !area || ( myArea == area && tab == myTab ) )
return;
- if ( area->widgetList().count() < 2 )
- return;
+ startDrawRect();
- QWidget* curWid = area->activeWidget();
- if ( !curWid )
+ if ( myArea )
+ drawRect();
+
+ myTab = tab;
+ myArea = area;
+
+ if ( myArea )
+ drawRect();
+}
+
+/*!
+ \brief Called when drop operation is finished.
+
+ Inserts dropped widget to the target workarea.
+*/
+void QtxWorkstackDrag::dropWidget()
+{
+ if ( myArea )
+ myArea->insertWidget( myChild->widget(), myTab );
+}
+
+/*!
+ \brief Draw floating rectangle.
+*/
+void QtxWorkstackDrag::drawRect()
+{
+ if ( !myArea )
return;
- QSplitter* s = splitter( area );
- QPtrList<QtxWorkstackArea> areaList;
- areas( s, areaList );
+ QRect r = myArea->floatRect();
+ int m = 2;
- QPtrList<QSplitter> splitList;
- splitters( s, splitList );
+ r.setTop( r.top() + m + 2 );
+ r.setLeft( r.left() + m + 2 );
+ r.setRight( r.right() - m - 2 );
+ r.setBottom( r.bottom() - m - 2 );
- QSplitter* trg = 0;
- if ( areaList.count() + splitList.count() < 2 || s->orientation() == o )
- trg = s;
+ if ( myAreaRect )
+ {
+ myAreaRect->setGeometry( r );
+ myAreaRect->setVisible( r.isValid() );
+ }
- if ( !trg )
- trg = wrapSplitter( area );
+ QRect tr = myArea->floatTab( myTab );
- if ( !trg )
- return;
+ tr.setTop( tr.top() + m );
+ tr.setLeft( tr.left() + m );
+ tr.setRight( tr.right() - m );
+ tr.setBottom( tr.bottom() - m );
- trg->setOrientation( (Orientation)o );
+ if ( myTabRect )
+ {
+ myTabRect->setGeometry( tr );
+ myTabRect->setVisible( tr.isValid() );
+ }
+}
- QtxWorkstackArea* newArea = createArea( 0 );
- insertWidget( newArea, trg, area );
+/*!
+ \brief Delete rubber band on the end on the dragging operation.
+*/
+void QtxWorkstackDrag::endDrawRect()
+{
+ delete myAreaRect;
+ myAreaRect = 0;
- area->removeWidget( curWid );
- newArea->insertWidget( curWid );
+ delete myTabRect;
+ myTabRect = 0;
+}
- distributeSpace( trg );
+/*!
+ \brief Create rubber band to be drawn on the dragging operation.
+*/
+void QtxWorkstackDrag::startDrawRect()
+{
+ if ( !myTabRect )
+ myTabRect = new QRubberBand( QRubberBand::Rectangle );
- curWid->show();
- curWid->setFocus();
+ myTabRect->hide();
+
+ if ( !myAreaRect )
+ myAreaRect = new QRubberBand( QRubberBand::Rectangle );
+
+ myAreaRect->hide();
}
/*!
- \brief Split workarea of the given widget on two parts.
- \param wid - widget, belonging to this workstack
- \param o - orientation of splitting (Qt::Horizontal or Qt::Vertical)
- \param type - type of splitting, see <VAR>SplitType</VAR> enumeration
+ \class QtxWorkstackArea
+ \internal
+ \brief Workstack widget workarea.
+*/
+
+/*!
+ \brief Constructor.
+ \param parent parent widget
*/
-void QtxWorkstack::Split (QWidget* wid, const Qt::Orientation o, const SplitType type)
+QtxWorkstackArea::QtxWorkstackArea( QWidget* parent )
+: QFrame( parent )
{
- if (!wid) return;
+ setFrameStyle( QFrame::Panel | QFrame::Sunken );
- // find area of the given widget
- QtxWorkstackArea* area = NULL;
- QPtrList<QtxWorkstackArea> allAreas;
- areas(mySplit, allAreas, true);
+ QVBoxLayout* base = new QVBoxLayout( this );
+ base->setMargin( frameWidth() );
- QPtrListIterator<QtxWorkstackArea> it (allAreas);
- for (; it.current() && !area; ++it) {
- if (it.current()->contains(wid))
- area = it.current();
- }
- if (!area) return;
+ QWidget* top = new QWidget( this );
+ base->addWidget( top );
- QWidgetList wids = area->widgetList();
- if (wids.count() < 2)
- return;
+ QHBoxLayout* tl = new QHBoxLayout( top );
+ tl->setMargin( 0 );
- QSplitter* s = splitter(area);
- QPtrList<QtxWorkstackArea> areaList;
- areas(s, areaList);
+ myBar = new QtxWorkstackTabBar( top );
+ tl->addWidget( myBar, 1 );
- QPtrList<QSplitter> splitList;
- splitters(s, splitList);
+ QPushButton* close = new QPushButton( top );
+ close->setIcon( style()->standardIcon( QStyle::SP_TitleBarCloseButton ) );
+ close->setAutoDefault( true );
+ close->setFlat( true );
+ myClose = close;
+ tl->addWidget( myClose );
- QSplitter* trg = 0;
- if (areaList.count() + splitList.count() < 2 || s->orientation() == o)
- trg = s;
+ myStack = new QStackedWidget( this );
- if (!trg) trg = wrapSplitter(area);
- if (!trg) return;
+ base->addWidget( myStack, 1 );
- trg->setOrientation(o);
+ connect( myClose, SIGNAL( clicked() ), this, SLOT( onClose() ) );
+ connect( myBar, SIGNAL( currentChanged( int ) ), this, SLOT( onCurrentChanged( int ) ) );
+ connect( myBar, SIGNAL( dragActiveTab() ), this, SLOT( onDragActiveTab() ) );
+ connect( myBar, SIGNAL( contextMenuRequested( QPoint ) ), this, SLOT( onContextMenuRequested( QPoint ) ) );
- QtxWorkstackArea* newArea = createArea(0);
- insertWidget(newArea, trg, area);
+ updateState();
- switch (type) {
- case SPLIT_STAY:
- {
- QWidgetListIt itr (wids);
- for (; itr.current(); ++itr)
- {
- QWidget* wid_i = itr.current();
- if (wid_i != wid) {
- area->removeWidget(wid_i);
- newArea->insertWidget(wid_i);
- }
- }
- }
- break;
- case SPLIT_AT:
- {
- QWidgetListIt itr (wids);
- for (; itr.current() && itr.current() != wid; ++itr) {
- }
- for (; itr.current(); ++itr) {
- area->removeWidget(itr.current());
- newArea->insertWidget(itr.current());
- }
- }
- break;
- case SPLIT_MOVE:
- area->removeWidget(wid);
- newArea->insertWidget(wid);
- break;
- }
+ updateActiveState();
- distributeSpace(trg);
+ QApplication::instance()->installEventFilter( this );
}
/*!
- \brief Put given widget on top of its workarea
- \param wid - widget, belonging to this workstack
+ \brief Destructor.
*/
-/*
-void QtxWorkstack::OnTop (QWidget* wid)
+QtxWorkstackArea::~QtxWorkstackArea()
+{
+ QApplication::instance()->removeEventFilter( this );
+}
+
+/*!
+ \brief Check if workarea contains visible widgets.
+ \return \c true if area is empty (all child widgets are removed or now shown)
+*/
+bool QtxWorkstackArea::isEmpty() const
+{
+ bool res = false;
+ for ( WidgetInfoMap::ConstIterator it = myInfo.begin(); it != myInfo.end() && !res; ++it )
+ res = it.value().vis;
+ return !res;
+}
+
+/*!
+ \brief Add widget to the workarea.
+ \param wid widget to be added
+ \param idx position in the area widget to be added to
+ \param f widget flags
+ \return child widget container object (or 0 if index is invalid)
+*/
+QWidget* QtxWorkstackArea::insertWidget( QWidget* wid, const int idx, Qt::WindowFlags f )
{
if ( !wid )
- return;
+ return 0;
- // find area of the given widget
- QtxWorkstackArea* area = 0;
- QPtrList<QtxWorkstackArea> allAreas;
- areas( mySplit, allAreas, true );
- for ( QPtrListIterator<QtxWorkstackArea> it( allAreas ); it.current() && !area; ++it )
+ int pos = myList.indexOf( wid );
+ if ( pos != -1 && ( pos == idx || ( idx < 0 && pos == (int)myList.count() - 1 ) ) )
+ return 0;
+
+ myList.removeAll( wid );
+ pos = idx < 0 ? myList.count() : idx;
+ myList.insert( qMin( pos, (int)myList.count() ), wid );
+ if ( !myInfo.contains( wid ) )
{
- if ( it.current()->contains( wid ) )
- area = it.current();
+ QtxWorkstackChild* child = new QtxWorkstackChild( wid, myStack, f );
+ myChild.insert( wid, child );
+ myInfo.insert( wid, WidgetInfo() );
+ myInfo[wid].id = generateId();
+ myInfo[wid].vis = wid->isVisibleTo( wid->parentWidget() );
+
+ connect( child, SIGNAL( destroyed( QObject* ) ), this, SLOT( onChildDestroyed( QObject* ) ) );
+ connect( wid, SIGNAL( destroyed() ), this, SLOT( onWidgetDestroyed() ) );
+ connect( child, SIGNAL( shown( QtxWorkstackChild* ) ), this, SLOT( onChildShown( QtxWorkstackChild* ) ) );
+ connect( child, SIGNAL( hidden( QtxWorkstackChild* ) ), this, SLOT( onChildHidden( QtxWorkstackChild* ) ) );
+ connect( child, SIGNAL( activated( QtxWorkstackChild* ) ), this, SLOT( onChildActivated( QtxWorkstackChild* ) ) );
+ connect( child, SIGNAL( captionChanged( QtxWorkstackChild* ) ), this, SLOT( onChildCaptionChanged( QtxWorkstackChild* ) ) );
}
- if ( area )
- area->setActiveWidget( wid );
+ updateState();
+
+ setWidgetActive( wid );
+ wid->setFocus();
+
+ return myChild[wid];
}
+
+/*!
+ \brief Create and show popup menu for the area.
+ \param p mouse pointer position at which popup menu should be shown
*/
+void QtxWorkstackArea::onContextMenuRequested( QPoint p )
+{
+ const QtxWorkstackTabBar* bar = ::qobject_cast<const QtxWorkstackTabBar*>( sender() );
+ if ( !bar )
+ return;
+
+ QWidget* wid = 0;
+ int idx = tabAt( p );
+ if ( idx != -1 )
+ wid = widget( myBar->tabId( idx ) );
+
+ emit contextMenuRequested( wid, p );
+}
/*!
- \brief Move widget(s) from source workarea into target workarea
- or just reorder widgets inside one workarea.
- \param wid1 - widget from target workarea
- \param wid2 - widget from source workarea
- \param all - if this parameter is TRUE, all widgets from source workarea will
- be moved into the target one, else only the \a wid2 will be moved
+ \brief Called when area's child widget is destroyed.
- Move \a wid2 in target workarea. Put it right after \a wid1.
- If value of boolean argument is TRUE, all widgets from source workarea
- will be moved together with \a wid2, source workarea will be deleted.
- If \a wid1 and \a wid2 belongs to one workarea, simple reordering will take place.
+ Removes child widget from the area.
*/
-void QtxWorkstack::Attract ( QWidget* wid1, QWidget* wid2, const bool all )
+void QtxWorkstackArea::onWidgetDestroyed()
{
- if ( !wid1 || !wid2 )
+ if ( sender() )
+ removeWidget( (QWidget*)sender(), false );
+}
+
+/*!
+ \brief Remove widget from workarea.
+ \param wid widget to be removed
+ \param del if \c true the widget should be also deleted
+*/
+void QtxWorkstackArea::removeWidget( QWidget* wid, const bool del )
+{
+ if ( !myList.contains( wid ) )
return;
- // find area of the widgets
- QtxWorkstackArea *area1 = NULL, *area2 = NULL;
- QPtrList<QtxWorkstackArea> allAreas;
- areas(mySplit, allAreas, true);
- QPtrListIterator<QtxWorkstackArea> it (allAreas);
- for (; it.current() && !(area1 && area2); ++it) {
- if (it.current()->contains(wid1))
- area1 = it.current();
- if (it.current()->contains(wid2))
- area2 = it.current();
- }
- if (!area1 || !area2) return;
+ if ( myBar->indexOf( widgetId( wid ) ) != -1 )
+ myBar->removeTab( myBar->indexOf( widgetId( wid ) ) );
- QWidget* curWid = area1->activeWidget();
- if (!curWid) return;
+ myStack->removeWidget( child( wid ) );
- if (area1 == area2) {
- if (all) {
- // Set wid1 at first position, wid2 at second
- area1->insertWidget(wid1);
- area1->insertWidget(wid2, 1);
- } else {
- // Set wid2 right after wid1
- area1->removeWidget(wid2);
- int wid1_ind = 0;
- QWidgetList wids1 = area1->widgetList();
- QWidgetListIt itr1 (wids1);
- for (; itr1.current() && itr1.current() != wid1; ++itr1, ++wid1_ind);
- area1->insertWidget(wid2, wid1_ind + 1);
- }
- } else {
- int wid1_ind = 0;
- QWidgetList wids1 = area1->widgetList();
- QWidgetListIt itr1 (wids1);
- for (; itr1.current() && itr1.current() != wid1; ++itr1, ++wid1_ind);
+ myList.removeAll( wid );
+ myInfo.remove( wid );
+ myChild.remove( wid );
- if (all) {
- // Set wid2 right after wid1, other widgets from area2 right after wid2
- QWidgetList wids2 = area2->widgetList();
- QWidgetListIt itr2 (wids2);
- for (int ind = wid1_ind + 1; itr2.current(); ++itr2, ++ind)
- {
- area2->removeWidget(itr2.current());
- if (itr2.current() == wid2) {
- area1->insertWidget(itr2.current(), wid1_ind + 1);
- } else {
- area1->insertWidget(itr2.current(), ind);
- }
- }
- } else {
- // Set wid2 right after wid1
- area2->removeWidget(wid2);
- area1->insertWidget(wid2, wid1_ind + 1);
- }
+ if ( del )
+ {
+ delete child( wid );
+ if ( myList.isEmpty() )
+ delete this;
+ else
+ updateState();
}
-
- area1->setActiveWidget( curWid );
+ else
+ updateState();
}
-static void setSizes (QIntList& szList, const int item_ind,
- const int new_near, const int new_this, const int new_farr)
+/*!
+ \brief Get all visible child widgets.
+ \return list of visible child widgets
+*/
+QWidgetList QtxWorkstackArea::widgetList() const
{
- // set size to all items before an item # <item_ind>
- int cur_pos = 0;
- QIntList::iterator its = szList.begin();
- for (; its != szList.end() && cur_pos < item_ind; ++its, ++cur_pos) {
- *its = new_near;
- }
- if (its == szList.end()) return;
- // set size to item # <item_ind>
- *its = new_this;
- ++its;
- // set size to all items after an item # <item_ind>
- for (; its != szList.end(); ++its) {
- *its = new_farr;
+ QWidgetList lst;
+ for ( QWidgetList::const_iterator it = myList.begin(); it != myList.end(); ++it )
+ {
+ if ( widgetVisibility( *it ) )
+ lst.append( *it );
}
+ return lst;
}
/*!
-* \brief Set position of the widget relatively its splitter.
-* \param wid - widget to set position of
-* \param pos - position relatively splitter. Value in range [0..1].
-*
-* Orientation of positioning will correspond to the splitter orientation.
+ \brief Get active child widget.
+ \return active widget
*/
-void QtxWorkstack::SetRelativePositionInSplitter( QWidget* wid, const double position )
+QWidget* QtxWorkstackArea::activeWidget() const
{
- if ( position < 0.0 || 1.0 < position)
- return;
+ return widget( myBar->tabId( myBar->currentIndex() ) );
+}
- if ( !wid )
- return;
+/*!
+ \brief Set active widget.
+ \param wid widget to be made active
+*/
+void QtxWorkstackArea::setActiveWidget( QWidget* wid )
+{
+ myBar->setCurrentIndex( myBar->indexOf( widgetId( wid ) ) );
+}
- // find area of the given widget
- QtxWorkstackArea* area = NULL;
- QPtrList<QtxWorkstackArea> allAreas;
- areas(mySplit, allAreas, true);
- for ( QPtrListIterator<QtxWorkstackArea> it( allAreas );
- it.current() && !area;
- ++it )
+/*!
+ \brief Check if area owns the specified widget.
+ \param wid widget to be checked
+ \return \c true if area contains widget
+*/
+bool QtxWorkstackArea::contains( QWidget* wid ) const
+{
+ return myList.contains( wid );
+}
+
+/*!
+ \brief Show/hide workarea.
+ \param on new visibility state
+*/
+void QtxWorkstackArea::setVisible( bool on )
+{
+ QMap<QWidget*, bool> map;
+ for ( QWidgetList::iterator it = myList.begin(); it != myList.end(); ++it )
{
- if (it.current()->contains(wid))
- area = it.current();
+ map.insert( *it, isBlocked( *it ) );
+ setBlocked( *it, true );
}
- if ( !area )
- return;
+ QFrame::setVisible( on );
- QSplitter* split = splitter( area );
- if ( !split )
- return;
+ for ( QWidgetList::iterator itr = myList.begin(); itr != myList.end(); ++itr )
+ setBlocked( *itr, map.contains( *itr ) ? map[*itr] : false );
+}
- // find index of the area in its splitter
- int item_ind = -1;
- bool isFound = false;
- const QObjectList* was = split->children();
- for (QObjectListIt ito (*was); ito.current() && !isFound; ++ito, ++item_ind)
- {
- if (ito.current() == area)
- isFound = true;
- }
- if (!isFound || item_ind == 0)
- return;
+/*!
+ \brief Check if workarea is active.
+ \return \c true if area is active
+*/
+bool QtxWorkstackArea::isActive() const
+{
+ QtxWorkstack* ws = workstack();
+ if ( !ws )
+ return false;
- QIntList szList = split->sizes();
- int splitter_size = (split->orientation() == Horizontal ?
- split->width() : split->height());
- int nb = szList.count();
+ return ws->activeArea() == this;
+}
- int new_prev = int(splitter_size * position / item_ind);
- int new_next = int(splitter_size * (1.0 - position) / (nb - item_ind));
- setSizes (szList, item_ind, new_prev, new_next, new_next);
- split->setSizes(szList);
+/*!
+ \brief Update active tab bar state (active/inactive).
+*/
+void QtxWorkstackArea::updateActiveState()
+{
+ myBar->setActive( isActive() );
}
/*!
-* \brief Set position of the widget relatively the entire workstack.
-* \param wid - widget to set position of
-* \param o - orientation of positioning (Qt::Horizontal or Qt::Vertical).
-* If o = Qt::Horizontal, horizontal position of \a wid will be changed.
-* If o = Qt::Vertical, vertical position of \a wid will be changed.
-* \param pos - position relatively workstack. Value in range [0..1].
+ \brief Get parent workstack
+ \return workstack owning this workarea
*/
-void QtxWorkstack::SetRelativePosition( QWidget* wid, const Qt::Orientation o,
- const double position )
+QtxWorkstack* QtxWorkstackArea::workstack() const
{
- if ( position < 0.0 || 1.0 < position )
- return;
+ QtxWorkstack* ws = 0;
+ QWidget* wid = parentWidget();
+ while ( wid && !ws )
+ {
+ if ( wid->inherits( "QtxWorkstack" ) )
+ ws = (QtxWorkstack*)wid;
+ wid = wid->parentWidget();
+ }
+ return ws;
+}
- if ( !wid )
- return;
+/*!
+ \brief Custom event filter.
- int splitter_size = o == Horizontal ? mySplit->width() : mySplit->height();
- int need_pos = int( position * splitter_size );
- int splitter_pos = 0;
+ Process events from child widgets.
- if ( setPosition( wid, mySplit, o, need_pos, splitter_pos ) != 0 )
+ \param o event receiver widget
+ \param e event
+ \return \c true if event should be filtered (stop further processing)
+*/
+bool QtxWorkstackArea::eventFilter( QObject* o, QEvent* e )
+{
+ if ( o->isWidgetType() )
{
- // impossible to set required position
+ QWidget* wid = (QWidget*)o;
+ if ( e->type() == QEvent::FocusIn || e->type() == QEvent::MouseButtonPress )
+ {
+ bool ok = false;
+ while ( !ok && wid && wid != myClose )
+ {
+ ok = wid == this;
+ wid = wid->parentWidget();
+ }
+ if ( ok )
+ QApplication::postEvent( this, new WidgetEvent( (QEvent::Type)( e->type() == QEvent::FocusIn ? ActivateWidget : FocusWidget ) ) );
+ }
}
+ return false;
}
/*!
-* \brief Sets the action's accelerator key to accel.
-* \param id - the key of the action in the actions map.
-* \param accel - action's accelerator key.
+ \brief Get rectangle to be drawn when highlighting drop area.
+ \return area drop rectangle
*/
-void QtxWorkstack::setAccel( const int id, const int accel )
+QRect QtxWorkstackArea::floatRect() const
{
- if ( !myActionsMap.contains( id ) )
- return;
-
- myActionsMap[id]->setAccel( accel );
+ QRect r = myStack->geometry();
+ return QRect( mapToGlobal( r.topLeft() ), mapToGlobal( r.bottomRight() ) );
}
/*!
-* \brief Returns the action's accelerator key.
-* \param id - the key of the action in the actions map.
-* \retval int - action's accelerator key.
+ \brief Get rectangle to be drawn when highlighting drop area on tab bar.
+ \param idx tab index
+ \return tab bar drop rectrangle
*/
-int QtxWorkstack::accel( const int id ) const
+QRect QtxWorkstackArea::floatTab( const int idx ) const
{
- int res = 0;
- if ( myActionsMap.contains( id ) )
- res = myActionsMap[id]->accel();
- return res;
+ QRect r = myBar->tabRect( idx );
+ return QRect( myBar->mapToGlobal( r.topLeft() ), r.size() );
}
-static int positionSimple (QIntList& szList, const int nb, const int splitter_size,
- const int item_ind, const int item_rel_pos,
- const int need_pos, const int splitter_pos)
+/*!
+ \brief Get tab index by point.
+ \param p point
+ \return tab covering point or -1 if there is no tab covering point
+*/
+int QtxWorkstackArea::tabAt( const QPoint& pnt ) const
{
- if (item_ind == 0) { // cannot move in this splitter
- return (need_pos - splitter_pos);
- }
-
- int delta = 0;
- int new_prev = 0;
- int new_this = szList[item_ind];
- int new_next = 0;
-
- bool isToCheck = false;
-
- if (need_pos < splitter_pos) {
- // Set size of all previous workareas to zero <--
- if (item_ind == nb - 1) {
- // item iz last in the splitter, it will occupy all the splitter
- new_this = splitter_size;
- } else {
- // recompute size of next items in splitter
- new_next = (splitter_size - new_this) / (nb - item_ind - 1);
- }
- delta = need_pos - splitter_pos;
-
- } else if (need_pos > (splitter_pos + splitter_size)) {
- // Set size of all next workareas to zero -->
- // recompute size of previous items in splitter
- new_this = 0;
- new_prev = (splitter_size - new_this) / item_ind;
- delta = need_pos - (splitter_pos + splitter_size - new_this);
-
- } else { // required position lays inside this splitter
- // Move workarea inside splitter into required position <->
- int new_item_rel_pos = need_pos - splitter_pos;
- new_prev = new_item_rel_pos / item_ind;
- if (need_pos < (splitter_pos + item_rel_pos)) {
- // Make previous workareas smaller, next - bigger
- // No problem to keep old size of the widget
- } else {
- // Make previous workareas bigger, next - smaller
- if (new_this > splitter_size - new_item_rel_pos) {
- new_this = splitter_size - new_item_rel_pos;
- }
- // jfa to do: in this case fixed size of next widgets could prevent right resizing
- isToCheck = true;
- }
- if (item_ind == nb - 1) {
- new_this = splitter_size - new_item_rel_pos;
- } else {
- new_next = (splitter_size - new_item_rel_pos - new_this) / (nb - item_ind - 1);
- }
- delta = 0;
+ int idx = -1;
+ QPoint p = myBar->mapFromGlobal( pnt );
+ for ( int i = 0; i < myBar->count() && idx == -1; i++ )
+ {
+ QRect r = myBar->tabRect( i );
+ if ( r.isValid() && r.contains( p ) )
+ idx = i;
}
-
- setSizes (szList, item_ind, new_prev, new_this, new_next);
- return delta;
+ return idx;
}
/*!
-* \brief Set position of given widget.
-* \param wid - widget to be moved
-* \param split - currently processed splitter (goes from more common
-* to more particular splitter in recursion calls)
-* \param o - orientation of positioning
-* \param need_pos - required position of the given widget in pixels
-* (from top/left side of workstack area)
-* \param splitter_pos - position of the splitter \a split
-* (from top/left side of workstack area)
-* \retval int - returns difference between a required and a distinguished position.
-*
-* Internal method. Recursively calls itself.
-* Is called from <VAR>SetRelativePosition</VAR> public method.
+ \brief Event handler for custom events.
+ \param e custom event
*/
-int QtxWorkstack::setPosition( QWidget* wid, QSplitter* split, const Qt::Orientation o,
- const int need_pos, const int splitter_pos )
+void QtxWorkstackArea::customEvent( QEvent* e )
{
- if ( !wid || !split )
- return need_pos - splitter_pos;
+ WidgetEvent* we = (WidgetEvent*)e;
- // Find corresponding sub-splitter.
- // Find also index of appropriate item in current splitter.
- int cur_ind = 0, item_ind = 0;
- bool isBottom = false, isFound = false;
- QSplitter* sub_split = NULL;
- const QObjectList* objs = split->children();
- if ( objs )
+ switch ( we->type() )
{
- for (QObjectListIt it (*objs); it.current() && !isFound; ++it)
+ case ActivateWidget:
+ emit activated( activeWidget() );
+ break;
+ case FocusWidget:
+ if ( activeWidget() )
{
- if (it.current()->inherits( "QtxWorkstackArea")) {
- if (((QtxWorkstackArea*)it.current())->contains(wid)) {
- item_ind = cur_ind;
- isBottom = true;
- isFound = true;
- }
- cur_ind++;
- } else if (it.current()->inherits("QSplitter")) {
- QPtrList<QtxWorkstackArea> areaList;
- areas((QSplitter*)it.current(), areaList, true);
- for (QPtrListIterator<QtxWorkstackArea> ita (areaList);
- ita.current() && !isFound;
- ++ita)
+ if ( !activeWidget()->focusWidget() )
+ activeWidget()->setFocus();
+ else
+ {
+ if ( activeWidget()->focusWidget()->hasFocus() )
{
- if (ita.current()->contains(wid)) {
- item_ind = cur_ind;
- isFound = true;
- sub_split = (QSplitter*)it.current();
- }
- }
- cur_ind++;
+ QFocusEvent in( QEvent::FocusIn );
+ QApplication::sendEvent( this, &in );
+ }
+ else
+ activeWidget()->focusWidget()->setFocus();
}
}
+ break;
+ case RemoveWidget:
+ removeWidget( we->widget() );
+ break;
+ default:
+ break;
}
- if (!isFound)
- return (need_pos - splitter_pos);
+}
- if (split->orientation() == o) {
- // Find coordinates of near and far sides of the appropriate item relatively current splitter
- int splitter_size = (o == Horizontal ? split->width() : split->height());
- QIntList szList = split->sizes();
- int nb = szList.count();
- int item_rel_pos = 0; // position of near side of item relatively this splitter
- for (int i = 0; i < item_ind; i++) {
- item_rel_pos += szList[i];
- }
- int item_size = szList[item_ind]; // size of item
- int item_pos = splitter_pos + item_rel_pos;
+/*!
+ \brief Customize focus in event handler.
+ \param e focus in event
+*/
+void QtxWorkstackArea::focusInEvent( QFocusEvent* e )
+{
+ QFrame::focusInEvent( e );
- // Resize splitter items to complete the conditions
- if (isBottom) {
- // I. Bottom of splitters stack reached
+ emit activated( activeWidget() );
+}
- int delta = positionSimple(szList, nb, splitter_size, item_ind, item_rel_pos, need_pos, splitter_pos);
- split->setSizes(szList);
- // Recompute delta, as some windows can reject given size
- int new_item_rel_pos = 0;
- QIntList szList1 = split->sizes();
- for (int i = 0; i < item_ind; i++) {
- new_item_rel_pos += szList1[i];
- }
- delta = need_pos - (splitter_pos + new_item_rel_pos);
- return delta;
+/*!
+ \brief Customize mouse press event handler.
+ \param e mouse press event
+*/
+void QtxWorkstackArea::mousePressEvent( QMouseEvent* e )
+{
+ QFrame::mousePressEvent( e );
- } else {
- // II. Bottom of splitters stack is not yet reached
+ emit activated( activeWidget() );
+}
- if (item_ind == 0) { // cannot move in this splitter
- // Process in sub-splitter
- return setPosition(wid, sub_split, o, need_pos, splitter_pos);
- }
+/*!
+ \brief Called when user presses "Close" button.
+*/
+void QtxWorkstackArea::onClose()
+{
+ QWidget* wid = activeWidget();
+ if ( wid )
+ wid->close();
+}
- int new_prev = 0;
- int new_this = szList[item_ind];
- int new_next = 0;
+/*!
+ \brief Called when user selects any tab page.
+ \param idx tab page index (not used)
+*/
+void QtxWorkstackArea::onCurrentChanged( int /*idx*/ )
+{
+ updateCurrent();
- if (need_pos < splitter_pos) {
- // Set size of all previous workareas to zero <--
- if (item_ind == nb - 1) {
- new_this = splitter_size;
- } else {
- new_next = (splitter_size - new_this) / (nb - item_ind - 1);
- }
- setSizes (szList, item_ind, new_prev, new_this, new_next);
- split->setSizes(szList);
- // Recompute splitter_pos, as some windows can reject given size
- int new_item_rel_pos = 0;
- QIntList szList1 = split->sizes();
- for (int i = 0; i < item_ind; i++) {
- new_item_rel_pos += szList1[i];
- }
- // Process in sub-splitter
- return setPosition(wid, sub_split, o, need_pos, splitter_pos + new_item_rel_pos);
- } else if (need_pos > (splitter_pos + splitter_size)) {
- // Set size of all next workareas to zero -->
- new_prev = (splitter_size - new_this) / item_ind;
- setSizes (szList, item_ind, new_prev, new_this, new_next);
- split->setSizes(szList);
- // Recompute splitter_pos, as some windows can reject given size
- int new_item_rel_pos = 0;
- QIntList szList1 = split->sizes();
- for (int i = 0; i < item_ind; i++) {
- new_item_rel_pos += szList1[i];
- }
- // Process in sub-splitter
- return setPosition(wid, sub_split, o, need_pos, splitter_pos + new_item_rel_pos);
- } else {
- // Set appropriate size of all previous/next items <->
- int new_item_rel_pos = item_rel_pos;
- if (need_pos < item_pos || (item_pos + item_size) < need_pos) {
- // Move item inside splitter into required position <->
- int new_this = szList[item_ind];
- int new_next = 0;
- new_item_rel_pos = need_pos - splitter_pos;
- if ((item_pos + item_size) < need_pos) {
- //new_item_rel_pos = need_pos - (item_pos + item_size);
- new_item_rel_pos = item_rel_pos + (need_pos - (item_pos + item_size));
- }
- int new_prev = new_item_rel_pos / item_ind;
- if (need_pos < (splitter_pos + item_rel_pos)) {
- // Make previous workareas smaller, next - bigger
- // No problem to keep old size of the widget
- } else {
- // Make previous workareas bigger, next - smaller
- if (new_this > splitter_size - new_item_rel_pos) {
- new_this = splitter_size - new_item_rel_pos;
- }
- }
- if (item_ind == nb - 1) {
- new_this = splitter_size - new_item_rel_pos;
- } else {
- new_next = (splitter_size - new_item_rel_pos - new_this) / (nb - item_ind - 1);
- }
- setSizes (szList, item_ind, new_prev, new_this, new_next);
- split->setSizes(szList);
- // Recompute new_item_rel_pos, as some windows can reject given size
- new_item_rel_pos = 0;
- QIntList szList1 = split->sizes();
- for (int i = 0; i < item_ind; i++) {
- new_item_rel_pos += szList1[i];
- }
- } else {
- // Do nothing
- }
- // Process in sub-splitter
- int add_pos = setPosition(wid, sub_split, o, need_pos, splitter_pos + new_item_rel_pos);
- if (add_pos == 0)
- return 0;
+ emit activated( activeWidget() );
+}
+
+/*!
+ \brief Called when user starts tab page dragging.
+*/
+void QtxWorkstackArea::onDragActiveTab()
+{
+ QtxWorkstackChild* c = child( activeWidget() );
+ if ( !c )
+ return;
+
+ new QtxWorkstackDrag( workstack(), c );
+}
+
+/*!
+ \brief Called when area's child widget container is destroyed.
+ \param obj widget container being destroyed
+*/
+void QtxWorkstackArea::onChildDestroyed( QObject* obj )
+{
+ QtxWorkstackChild* child = (QtxWorkstackChild*)obj;
+ myStack->removeWidget( child );
+
+ QWidget* wid = 0;
+ for ( ChildMap::ConstIterator it = myChild.begin(); it != myChild.end() && !wid; ++it )
+ {
+ if ( it.value() == child )
+ wid = it.key();
+ }
+
+ myChild.remove( wid );
+
+ QApplication::postEvent( this, new WidgetEvent( (QEvent::Type)RemoveWidget, wid ) );
+}
+
+/*!
+ \brief Called when child widget container is shown.
+ \param c child widget container being shown
+*/
+void QtxWorkstackArea::onChildShown( QtxWorkstackChild* c )
+{
+ setWidgetShown( c->widget(), true );
+}
+
+/*!
+ \brief Called when child widget container is hidden.
+ \param c child widget container being hidden
+*/
+void QtxWorkstackArea::onChildHidden( QtxWorkstackChild* c )
+{
+ setWidgetShown( c->widget(), false );
+}
+
+/*!
+ \brief Called when child widget container is activated.
+ \param c child widget container being activated
+*/
+void QtxWorkstackArea::onChildActivated( QtxWorkstackChild* c )
+{
+ setWidgetActive( c->widget() );
+}
+
+/*!
+ \brief Called when child widget container's title is changed.
+ \param c child widget container which title is changed
+*/
+void QtxWorkstackArea::onChildCaptionChanged( QtxWorkstackChild* c )
+{
+ updateTab( c->widget() );
+}
+
+/*!
+ \brief Update current child widget container.
+
+ Raises widget when active tab page is changed.
+*/
+void QtxWorkstackArea::updateCurrent()
+{
+ QMap<QWidget*, bool> map;
+ for ( QWidgetList::iterator it = myList.begin(); it != myList.end(); ++it )
+ {
+ map.insert( *it, isBlocked( *it ) );
+ setBlocked( *it, true );
+ }
+
+ QWidget* cur = child( widget( myBar->tabId( myBar->currentIndex() ) ) );
+ if ( cur )
+ myStack->setCurrentWidget( cur );
+
+ for ( QWidgetList::iterator itr = myList.begin(); itr != myList.end(); ++itr )
+ setBlocked( *itr, map.contains( *itr ) ? map[*itr] : false );
+}
+
+/*!
+ \brief Update tab bar.
+ \param wid tab page widget
+*/
+void QtxWorkstackArea::updateTab( QWidget* wid )
+{
+ int idx = myBar->indexOf( widgetId( wid ) );
+ if ( idx < 0 )
+ return;
+
+ myBar->setTabIcon( idx, wid->windowIcon() );
+ myBar->setTabText( idx, wid->windowTitle() );
+}
+
+/*!
+ \brief Get child widget by specified identifier.
+ \param id widget ID
+ \return widget or 0, if identifier in invalid
+*/
+QWidget* QtxWorkstackArea::widget( const int id ) const
+{
+ QWidget* wid = 0;
+ for ( WidgetInfoMap::ConstIterator it = myInfo.begin(); it != myInfo.end() && !wid; ++it )
+ {
+ if ( it.value().id == id )
+ wid = it.key();
+ }
+ return wid;
+}
+
+/*!
+ \brief Get child widget identifier.
+ \param wid widget
+ \return widget ID or -1 if widget is not found
+*/
+int QtxWorkstackArea::widgetId( QWidget* wid ) const
+{
+ int id = -1;
+ if ( myInfo.contains( wid ) )
+ id = myInfo[wid].id;
+ return id;
+}
+
+/*!
+ \brief Get child widget's visibility.
+ \param wid widget
+ \return \c true if widget is visible
+*/
+bool QtxWorkstackArea::widgetVisibility( QWidget* wid ) const
+{
+ bool res = false;
+ if ( myInfo.contains( wid ) )
+ res = myInfo[wid].vis;
+ return res;
+}
+
+/*!
+ \brief Set active child widget.
+ \param wid widget to be set active
+*/
+void QtxWorkstackArea::setWidgetActive( QWidget* wid )
+{
+ int id = widgetId( wid );
+ if ( id < 0 )
+ return;
+
+ myBar->setCurrentIndex( myBar->indexOf( id ) );
+}
+
+/*!
+ \brief Show/hide child widget.
+ \param wid widget
+ \param on new visibility state
+*/
+void QtxWorkstackArea::setWidgetShown( QWidget* wid, const bool on )
+{
+ if ( isBlocked( wid ) || !myInfo.contains( wid ) || myInfo[wid].vis == on )
+ return;
+
+ myInfo[wid].vis = on;
+ updateState();
+}
+
+/*!
+ \brief Update internal state.
+*/
+void QtxWorkstackArea::updateState()
+{
+ bool updBar = myBar->updatesEnabled();
+ bool updStk = myStack->updatesEnabled();
+ myBar->setUpdatesEnabled( false );
+ myStack->setUpdatesEnabled( false );
+
+ bool block = myBar->signalsBlocked();
+ myBar->blockSignals( true );
+
+ QWidget* prev = activeWidget();
+
+ int idx = 0;
+ for ( QWidgetList::iterator it = myList.begin(); it != myList.end(); ++it )
+ {
+ QWidget* wid = *it;
+ int id = widgetId( wid );
+
+ if ( id < 0 )
+ continue;
+
+ bool vis = widgetVisibility( wid );
+
+ int cIdx = myBar->indexOf( id );
+ if ( cIdx != -1 && ( !vis || myBar->indexOf( id ) != idx ) )
+ myBar->removeTab( cIdx );
+
+ if ( myBar->indexOf( id ) == -1 && vis )
+ myBar->setTabId( myBar->insertTab( idx, wid->windowTitle() ), id );
+
+ updateTab( wid );
+
+ bool block = isBlocked( wid );
+ setBlocked( wid, true );
+
+ QtxWorkstackChild* cont = child( wid );
+
+ if ( !vis )
+ myStack->removeWidget( cont );
+ else if ( myStack->indexOf( cont ) < 0 )
+ myStack->addWidget( cont );
+
+ if ( vis )
+ idx++;
- // this can be if corresponding workarea is first in sub-splitter
- // or sub-splitter has another orientation
+ setBlocked( wid, block );
+ }
- // Resize ones again to reach precize position <->
- int need_pos_1 = splitter_pos + new_item_rel_pos + add_pos;
+ int curId = widgetId( prev );
+ if ( myBar->indexOf( curId ) < 0 )
+ {
+ QWidget* wid = 0;
+ int pos = myList.indexOf( prev );
+ for ( int i = pos - 1; i >= 0 && !wid; i-- )
+ {
+ if ( widgetVisibility( myList.at( i ) ) )
+ wid = myList.at( i );
+ }
- // Move workarea inside splitter into required position <->
- int delta_1 = positionSimple(szList, nb, splitter_size, item_ind,
- new_item_rel_pos, need_pos_1, splitter_pos);
- split->setSizes(szList);
- // Recompute new_item_rel_pos, as some windows can reject given size
- new_item_rel_pos = 0;
- QIntList szList1 = split->sizes();
- for (int i = 0; i < item_ind; i++) {
- new_item_rel_pos += szList1[i];
- }
- delta_1 = need_pos_1 - (splitter_pos + new_item_rel_pos);
- return delta_1;
- }
+ for ( int j = pos + 1; j < (int)myList.count() && !wid; j++ )
+ {
+ if ( widgetVisibility( myList.at( j ) ) )
+ wid = myList.at( j );
}
- } else {
- return setPosition(wid, sub_split, o, need_pos, splitter_pos);
+
+ if ( wid )
+ curId = widgetId( wid );
}
- return 0;
+ myBar->setCurrentIndex( myBar->indexOf( curId ) );
+
+ myBar->blockSignals( block );
+
+ updateCurrent();
+
+ myBar->updateActiveState();
+
+ myBar->setUpdatesEnabled( updBar );
+ myStack->setUpdatesEnabled( updStk );
+ if ( updBar )
+ myBar->update();
+ if ( updStk )
+ myStack->update();
+
+ QResizeEvent re( myBar->size(), myBar->size() );
+ QApplication::sendEvent( myBar, &re );
+
+ if ( isEmpty() )
+ {
+ hide();
+ emit deactivated( this );
+ }
+ else
+ {
+ show();
+ if ( prev != activeWidget() )
+ emit activated( activeWidget() );
+ }
}
/*!
- Redistributes space among widgets equally
+ \brief Generate unique widget identifier.
+ \return first non shared widget ID
*/
-void QtxWorkstack::distributeSpace( QSplitter* split ) const
+int QtxWorkstackArea::generateId() const
{
- if ( !split )
- return;
+ QMap<int, int> map;
- QIntList szList = split->sizes();
- int size = ( split->orientation() == Horizontal ?
- split->width() : split->height() ) / szList.count();
- for ( QIntList::iterator it = szList.begin(); it != szList.end(); ++it )
- *it = size;
- split->setSizes( szList );
+ for ( WidgetInfoMap::const_iterator it = myInfo.begin(); it != myInfo.end(); ++it )
+ map.insert( it.value().id, 0 );
+
+ int id = 0;
+ while ( map.contains( id ) )
+ id++;
+
+ return id;
}
/*!
- Splits widgets vertically
+ \brief Check if the child wiget is blocked.
+ \param wid widget
+ \return \c true if the widget is blocked
*/
-void QtxWorkstack::splitVertical()
+bool QtxWorkstackArea::isBlocked( QWidget* wid ) const
{
- split( Qt::Horizontal );
+ return myBlock.contains( wid );
}
/*!
- Splits widgets horizontally
+ \brief Block widget.
+ \param wid widget
+ \param on new blocked state
*/
-void QtxWorkstack::splitHorizontal()
+void QtxWorkstackArea::setBlocked( QWidget* wid, const bool on )
{
- split( Qt::Vertical );
+ if ( on )
+ myBlock.insert( wid, 0 );
+ else
+ myBlock.remove( wid );
}
/*!
- SLOT: called if action "Rename" is activated, changes caption of widget
+ \brief Get child widget container.
+ \param wid child widget
+ \return child widget container corresponding to the \a wid
*/
-void QtxWorkstack::onRename()
+QtxWorkstackChild* QtxWorkstackArea::child( QWidget* wid ) const
{
- if ( !myWorkWin )
- return;
-
- bool ok = false;
- QString newName = QInputDialog::getText( tr( "Rename" ), tr( "Enter new name:" ), QLineEdit::Normal,
- myWorkWin->caption(), &ok, topLevelWidget() );
- if ( ok && !newName.isEmpty() )
- myWorkWin->setCaption( newName );
+ QtxWorkstackChild* res = 0;
+ if ( myChild.contains( wid ) )
+ res = myChild[wid];
+ return res;
}
/*!
- Wraps area into new splitter
- \return new splitter
+ \fn void QtxWorkstackArea::activated( QWidget* w )
+ \brief Emitted when child widget is activated.
+ \param w child widget being activated
*/
-QSplitter* QtxWorkstack::wrapSplitter( QtxWorkstackArea* area )
-{
- if ( !area )
- return 0;
-
- QSplitter* pSplit = splitter( area );
- if ( !pSplit )
- return 0;
-
- bool upd = pSplit->isUpdatesEnabled();
- pSplit->setUpdatesEnabled( false );
- QIntList szList = pSplit->sizes();
+/*!
+ \fn void QtxWorkstackArea::contextMenuRequested( QWidget* w, QPoint p )
+ \brief Emitted when context popup menu is requested.
+ \param w child widget popup menu requested for
+ \param p point popup menu to be shown at
+*/
- QSplitter* wrap = new QSplitter( 0 );
-#if defined QT_VERSION && QT_VERSION >= 0x30200
- wrap->setChildrenCollapsible( false );
-#endif
- insertWidget( wrap, pSplit, area );
- area->reparent( wrap, QPoint( 0, 0 ), true );
+/*!
+ \fn void QtxWorkstackArea::deactivated( QtxWorkstackArea* wa )
+ \brief Emitted when workarea is deactivated.
+ \param wa workarea being deactivated
+*/
- pSplit->setSizes( szList );
+/*!
+ \class QtxWorkstackChild
+ \internal
+ \brief Workarea child widget container.
+*/
- pSplit->setUpdatesEnabled( upd );
+/*!
+ \brief Constructor.
+ \param wid child widget
+ \param parent parent widget
+ \param f widget flags
+*/
+QtxWorkstackChild::QtxWorkstackChild( QWidget* wid, QWidget* parent, Qt::WindowFlags f )
+: QWidget( parent ),
+ myWidget( wid )
+{
+ myWidget->setParent( this, f );
+ myWidget->installEventFilter( this );
+ QVBoxLayout* base = new QVBoxLayout( this );
+ base->addWidget( myWidget );
- return wrap;
+ connect( myWidget, SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
}
/*!
- Reparenst and adds widget
- \param wid - widget
- \param pWid - parent widget
- \param after - after widget
+ \brief Destructor.
*/
-void QtxWorkstack::insertWidget( QWidget* wid, QWidget* pWid, QWidget* after )
+QtxWorkstackChild::~QtxWorkstackChild()
{
- if ( !wid || !pWid )
- return;
+ QApplication::instance()->removeEventFilter( this );
- QWidgetList moveList;
- const QObjectList* lst = pWid->children();
- if ( lst )
- {
- bool found = false;
- for ( QObjectListIt it( *lst ); it.current(); ++it )
- {
- if ( found && ( it.current()->inherits( "QSplitter" ) ||
- it.current()->inherits( "QtxWorkstackArea" ) ) )
- moveList.append( (QWidget*)it.current() );
- if ( it.current() == after )
- found = true;
- }
- }
+ if ( !widget() )
+ return;
- QMap<QWidget*, bool> map;
- for ( QWidgetListIt it( moveList ); it.current(); ++it )
- {
- map.insert( it.current(), it.current()->isVisibleTo( it.current()->parentWidget() ) );
- it.current()->reparent( 0, QPoint( 0, 0 ), false );
- }
+ disconnect( widget(), SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
- wid->reparent( pWid, QPoint( 0, 0 ), true );
+ widget()->hide();
+ widget()->removeEventFilter( this );
- for ( QWidgetListIt itr( moveList ); itr.current(); ++itr )
- itr.current()->reparent( pWid, QPoint( 0, 0 ), map.contains( itr.current() ) ? map[itr.current()] : false );
+ widget()->setParent( 0 );
}
/*!
-* \brief Closes the active window.
+ \brief Get child widget.
+ \return child widget
*/
-void QtxWorkstack::onCloseWindow()
+QWidget* QtxWorkstackChild::widget() const
{
- if ( myWorkWin )
- myWorkWin->close();
- else if( activeWindow() )
- activeWindow()->close();
+ return myWidget;
}
/*!
- SLOT: called on area is destroyed
- Sets focus to neighbour area
+ \brief Custom event filter.
+
+ Process events from child widgets.
+
+ \param o event receiver widget
+ \param e event
+ \return \c true if event should be filtered (stop further processing)
*/
-void QtxWorkstack::onDestroyed( QObject* obj )
+bool QtxWorkstackChild::eventFilter( QObject* o, QEvent* e )
{
- QtxWorkstackArea* area = (QtxWorkstackArea*)obj;
+ if ( o->isWidgetType() )
+ {
+ if ( e->type() == QEvent::WindowTitleChange || e->type() == QEvent::WindowIconChange )
+ emit captionChanged( this );
- if ( area == myArea )
- myArea = 0;
+ if ( !e->spontaneous() && ( e->type() == QEvent::Show || e->type() == QEvent::ShowToParent ) )
+ emit shown( this );
- if ( !myArea )
- {
- QtxWorkstackArea* cur = neighbourArea( area );
- if ( cur )
- cur->setFocus();
- }
+ if ( !e->spontaneous() && ( e->type() == QEvent::Hide || e->type() == QEvent::HideToParent ) )
+ emit hidden( this );
- QApplication::postEvent( this, new QCustomEvent( QEvent::User ) );
+ if ( e->type() == QEvent::FocusIn )
+ emit activated( this );
+ }
+ return QWidget::eventFilter( o, e );
}
/*!
- SLOT: called on window activating
+ \brief Called when child widget is destroyed.
+ \param obj child widget being destroyed
*/
-void QtxWorkstack::onWindowActivated( QWidget* wid )
+void QtxWorkstackChild::onDestroyed( QObject* obj )
{
- const QObject* obj = sender();
- if ( !obj->inherits( "QtxWorkstackArea" ) )
+ if ( obj != widget() )
return;
- setActiveArea( (QtxWorkstackArea*)obj );
+ myWidget = 0;
+ deleteLater();
}
/*!
- SLOT: called on window deactivating
+ \brief Customize child event handler.
+ \param e child event
*/
-void QtxWorkstack::onDeactivated( QtxWorkstackArea* area )
+void QtxWorkstackChild::childEvent( QChildEvent* e )
{
- if ( myArea != area )
- return;
-
- QPtrList<QtxWorkstackArea> lst;
- areas( mySplit, lst, true );
-
- int idx = lst.find( area );
- if ( idx == -1 )
- return;
-
- myWin = 0;
- myArea = 0;
-
- QtxWorkstackArea* newArea = neighbourArea( area );
- if ( newArea && newArea->activeWidget() )
- newArea->activeWidget()->setFocus();
-
- QApplication::postEvent( this, new QCustomEvent( QEvent::User ) );
+ if ( e->removed() && e->child() == widget() )
+ {
+ myWidget = 0;
+ deleteLater();
+ }
+ QWidget::childEvent( e );
}
/*!
- Creates and shows popup menu for area
- \param w - area
- \param p - popup position
+ \fn void QtxWorkstackChild::shown( QtxWorkstackChild* w )
+ \brief Emitted when child widget is shown.
+ \param w child widget container
*/
-void QtxWorkstack::onContextMenuRequested( QWidget* w, QPoint p )
-{
- QtxWorkstackArea* anArea = ::qt_cast<QtxWorkstackArea*>( (QObject*)sender() );
- if ( !anArea )
- anArea = activeArea();
-
- if ( !anArea )
- return;
-
- QWidgetList lst = anArea->widgetList();
- if ( lst.isEmpty() )
- return;
- myWorkWin = w;
- myWorkArea = anArea;
+/*!
+ \fn void QtxWorkstackChild::hidden( QtxWorkstackChild* w )
+ \brief Emitted when child widget is hidden.
+ \param w child widget container
+*/
- QPopupMenu* pm = new QPopupMenu();
-
- if ( lst.count() > 1 )
- {
- myActionsMap[SplitVertical]->addTo( pm );
- myActionsMap[SplitHorizontal]->addTo( pm );
- pm->insertSeparator();
- }
+/*!
+ \fn void QtxWorkstackChild::activated( QtxWorkstackChild* w )
+ \brief Emitted when child widget is activated.
+ \param w child widget container
+*/
- if ( w )
- {
- myActionsMap[Close]->addTo( pm );
- myActionsMap[Rename]->addTo( pm );
- }
+/*!
+ \fn void QtxWorkstackChild::captionChanged( QtxWorkstackChild* w )
+ \brief Emitted when child widget's title is changed.
+ \param w child widget container
+*/
- Qtx::simplifySeparators( pm );
+/*!
+ \class QtxWorkstackTabBar
+ \internal
+ \brief Workstack tab bar widget
+*/
- if ( pm->count() )
- pm->exec( p );
+/*!
+ \brief Constructor.
+ \param parent parent widget
+*/
+QtxWorkstackTabBar::QtxWorkstackTabBar( QWidget* parent )
+: QTabBar( parent ),
+ myId( -1 )
+{
+ setDrawBase( true );
+ setElideMode( Qt::ElideNone );
- delete pm;
+ connect( this, SIGNAL( currentChanged( int ) ), this, SLOT( onCurrentChanged( int ) ) );
+}
- myWorkWin = 0;
- myWorkArea = 0;
+/*!
+ \brief Destructor.
+*/
+QtxWorkstackTabBar::~QtxWorkstackTabBar()
+{
}
/*!
- Custom child event handler, inserts widget to active or current area
+ \brief Get tab page identifier.
+ \param index tab page index
+ \return tab page ID or -1 if \a index is out of range
*/
-void QtxWorkstack::childEvent( QChildEvent* e )
+int QtxWorkstackTabBar::tabId( const int index ) const
{
- if ( e->inserted() && e->child()->isWidgetType() )
- {
- QWidget* w = (QWidget*)e->child();
- if ( w && w != mySplit )
- {
- targetArea()->insertWidget( w );
- return;
- }
- }
- QWidget::childEvent( e );
+ QVariant v = tabData( index );
+ if ( !v.canConvert( QVariant::Int ) )
+ return -1;
+ return v.toInt();
}
/*!
- Handler of custom events
+ \brief Set tab page identifier.
+ \param index tab page index
+ \param id tab page ID
*/
-void QtxWorkstack::customEvent( QCustomEvent* e )
+void QtxWorkstackTabBar::setTabId( const int index, const int id )
{
- updateState();
+ setTabData( index, id );
}
/*!
- \return splitter corresponding to area
- \param area
+ \brief Get tab page index by specified identifier.
+ \param id tab page ID
+ \return tab page index or -1 if not found
*/
-QSplitter* QtxWorkstack::splitter( QtxWorkstackArea* area ) const
+int QtxWorkstackTabBar::indexOf( const int id ) const
{
- if ( !area )
- return 0;
-
- QSplitter* split = 0;
-
- QWidget* wid = area->parentWidget();
- if ( wid && wid->inherits( "QSplitter" ) )
- split = (QSplitter*)wid;
-
- return split;
+ int index = -1;
+ for ( int i = 0; i < (int)count() && index < 0; i++ )
+ {
+ if ( tabId( i ) == id )
+ index = i;
+ }
+ return index;
}
/*!
- Fills list with children splitters
- \param split - parent splitter
- \param splitList - list to be filled with
- \param rec - recursive search of children
+ \brief Check if the tab bar is active.
+ \return \c true if tab bar is active
*/
-void QtxWorkstack::splitters( QSplitter* split, QPtrList<QSplitter>& splitList, const bool rec ) const
+bool QtxWorkstackTabBar::isActive() const
{
- if ( !split )
- return;
-
- const QObjectList* objs = split->children();
- if ( objs )
- {
- for ( QObjectListIt it( *objs ); it.current(); ++it )
- {
- if ( rec )
- splitters( (QSplitter*)it.current(), splitList, rec );
- if ( it.current()->inherits( "QSplitter" ) )
- splitList.append( (QSplitter*)it.current() );
- }
- }
+ return myActive;
}
/*!
- Fills list with children areas
- \param split - parent splitter
- \param areaList - list to be filled with
- \param rec - recursive search of children
+ \brief Set tab bar active/inactive.
+ \param on new active state
*/
-void QtxWorkstack::areas( QSplitter* split, QPtrList<QtxWorkstackArea>& areaList, const bool rec ) const
+void QtxWorkstackTabBar::setActive( const bool on )
{
- if ( !split )
+ if ( myActive == on )
return;
- const QObjectList* objs = split->children();
- if ( objs )
- {
- for ( QObjectListIt it( *objs ); it.current(); ++it )
- {
- if ( it.current()->inherits( "QtxWorkstackArea" ) )
- areaList.append( (QtxWorkstackArea*)it.current() );
- else if ( rec && it.current()->inherits( "QSplitter" ) )
- areas( (QSplitter*)it.current(), areaList, rec );
- }
- }
+ myActive = on;
+ updateActiveState();
}
/*!
- \return active area
+ \brief Update tab bar according to the 'active' state.
*/
-QtxWorkstackArea* QtxWorkstack::activeArea() const
+void QtxWorkstackTabBar::updateActiveState()
{
- return myArea;
+ QColor bc = palette().color( QPalette::Text );
+ QColor ac = isActive() ? palette().color( QPalette::Highlight ) : bc;
+ for ( int i = 0; i < (int)count(); i++ )
+ setTabTextColor( i, currentIndex() == i ? ac : bc );
}
/*!
- \return active area or current area or create new area of there is no one
+ \brief Called when current tab page is changed.
+ \param idx tab page index (not used)
*/
-QtxWorkstackArea* QtxWorkstack::targetArea()
+void QtxWorkstackTabBar::onCurrentChanged( int /*index*/ )
{
- QtxWorkstackArea* area = activeArea();
- if ( !area )
- area = currentArea();
- if ( !area )
- {
- QPtrList<QtxWorkstackArea> lst;
- areas( mySplit, lst );
- if ( !lst.isEmpty() )
- area = lst.first();
- }
-
- if ( !area )
- area = createArea( mySplit );
-
- return area;
+ updateActiveState();
}
/*!
- \return current area (that has focus)
+ \brief Customize mouse move event handler.
+ \param e mouse event
*/
-QtxWorkstackArea* QtxWorkstack::currentArea() const
+void QtxWorkstackTabBar::mouseMoveEvent( QMouseEvent* e )
{
- QtxWorkstackArea* area = 0;
- QWidget* wid = focusWidget();
- while ( wid && !area )
+ if ( myId != -1 && !tabRect( indexOf( myId ) ).contains( e->pos() ) )
{
- if ( wid->inherits( "QtxWorkstackArea" ) )
- area = (QtxWorkstackArea*)wid;
- wid = wid->parentWidget();
+ myId = -1;
+ emit dragActiveTab();
}
- return area;
+ QTabBar::mouseMoveEvent( e );
}
/*!
- Creates new area
+ \brief Customize mouse press event handler.
+ \param e mouse event
*/
-QtxWorkstackArea* QtxWorkstack::createArea( QWidget* parent ) const
+void QtxWorkstackTabBar::mousePressEvent( QMouseEvent* e )
{
- QtxWorkstackArea* area = new QtxWorkstackArea( parent );
-
- connect( area, SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
- connect( area, SIGNAL( activated( QWidget* ) ), this, SLOT( onWindowActivated( QWidget* ) ) );
- connect( area, SIGNAL( contextMenuRequested( QWidget*, QPoint ) ),
- this, SLOT( onContextMenuRequested( QWidget*, QPoint ) ) );
- connect( area, SIGNAL( deactivated( QtxWorkstackArea* ) ), this, SLOT( onDeactivated( QtxWorkstackArea* ) ) );
+ QTabBar::mousePressEvent( e );
- return area;
+ if ( e->button() == Qt::LeftButton )
+ myId = tabId( currentIndex() );
}
/*!
- Sets area as active
- \param area
+ \brief Customize mouse release event handler.
+ \param e mouse event
*/
-void QtxWorkstack::setActiveArea( QtxWorkstackArea* area )
+void QtxWorkstackTabBar::mouseReleaseEvent( QMouseEvent* e )
{
- QWidget* oldCur = myWin;
-
- QtxWorkstackArea* oldArea = myArea;
-
- myArea = area;
-
- if ( myArea != oldArea )
- {
- if ( oldArea )
- oldArea->updateActiveState();
- if ( myArea )
- myArea->updateActiveState();
- }
+ QTabBar::mouseReleaseEvent( e );
- if ( myArea )
- myWin = myArea->activeWidget();
+ myId = -1;
- if ( myWin && oldCur != myWin )
- emit windowActivated( myWin );
+ if ( e->button() == Qt::RightButton )
+ emit contextMenuRequested( e->globalPos() );
}
/*!
- \return neighbour area
- \param area - area to search neighbour
+ \brief Customize context menu event handler.
+ \param e context menu event
*/
-QtxWorkstackArea* QtxWorkstack::neighbourArea( QtxWorkstackArea* area ) const
+void QtxWorkstackTabBar::contextMenuEvent( QContextMenuEvent* e )
{
- QPtrList<QtxWorkstackArea> lst;
- areas( mySplit, lst, true );
- int pos = lst.find( area );
- if ( pos < 0 )
- return 0;
-
- QtxWorkstackArea* na = 0;
- for ( int i = pos - 1; i >= 0 && !na; i-- )
- {
- if ( !lst.at( i )->isEmpty() )
- na = lst.at( i );
- }
-
- for ( int j = pos + 1; j < (int)lst.count() && !na; j++ )
- {
- if ( !lst.at( j )->isEmpty() )
- na = lst.at( j );
- }
- return na;
+ if ( e->reason() != QContextMenuEvent::Mouse )
+ emit contextMenuRequested( e->globalPos() );
}
-/*!
- \return area covering point
- \param p - point
-*/
-QtxWorkstackArea* QtxWorkstack::areaAt( const QPoint& p ) const
+/*
+void QtxWorkstackTabBar::paintLabel( QPainter* p, const QRect& br, QTab* t, bool has_focus ) const
{
- QtxWorkstackArea* area = 0;
- QPtrList<QtxWorkstackArea> lst;
- areas( mySplit, lst, true );
- for ( QPtrListIterator<QtxWorkstackArea> it( lst ); it.current() && !area; ++it )
+ if ( currentTab() != t->identifier() )
{
- QtxWorkstackArea* cur = it.current();
- QRect r = cur->geometry();
- if ( cur->parentWidget() )
- r = QRect( cur->parentWidget()->mapToGlobal( r.topLeft() ), r.size() );
- if ( r.contains( p ) )
- area = cur;
+ QFont fnt = p->font();
+ fnt.setUnderline( false );
+ p->setFont( fnt );
}
- return area;
+ QTabBar::paintLabel( p, br, t, has_focus );
}
+*/
/*!
- Update
+ \fn void QtxWorkstackTabBar::dragActiveTab()
+ \brief Emitted when dragging operation is started.
*/
-void QtxWorkstack::updateState()
-{
- updateState( mySplit );
-}
/*!
- Update splitters
+ \fn void QtxWorkstackTabBar::contextMenuRequested( QPoint p )
+ \brief Emitted when context popup menu is requested.
+ \param p point popup menu to be shown at
*/
-void QtxWorkstack::updateState( QSplitter* split )
-{
- QPtrList<QSplitter> recList;
- splitters( split, recList, false );
- for ( QPtrListIterator<QSplitter> itr( recList ); itr.current(); ++itr )
- updateState( itr.current() );
-
- QPtrList<QSplitter> splitList;
- splitters( split, splitList, false );
-
- QPtrList<QtxWorkstackArea> areaList;
- areas( split, areaList, false );
-
- bool vis = false;
- for ( QPtrListIterator<QtxWorkstackArea> it( areaList ); it.current(); ++it )
- {
- if ( it.current()->isEmpty() )
- it.current()->hide();
- else
- {
- it.current()->show();
- vis = true;
- }
- }
- if ( split == mySplit )
- return;
+/*!
+ \class QtxWorkstack
+ \brief Workstack widget.
- for ( QPtrListIterator<QSplitter> iter( splitList ); iter.current() && !vis; ++iter )
- vis = iter.current()->isVisibleTo( iter.current()->parentWidget() );
+ Organizes the child widgets in the tabbed space.
+ Allows splitting the working area to arrange the child widgets in
+ arbitrary way. Any widgets can be moved to another working area with
+ drag-n-drop operation.
- if ( areaList.isEmpty() && splitList.isEmpty() )
- delete split;
- else if ( vis )
- split->show();
- else
- split->hide();
-}
+ This widget can be used as workspace of the application main window,
+ for example, as kind of implementation of multi-document interface.
+*/
/*!
- Gets splitter info for debug
- \param split - splitter
- \param info - string to be filled with info
+ \brief Constructor.
+ \param parent parent widget
*/
-void QtxWorkstack::splitterInfo( QSplitter* split, QString& info ) const
+QtxWorkstack::QtxWorkstack( QWidget* parent )
+: QWidget( parent ),
+ myWin( 0 ),
+ myArea( 0 ),
+ myWorkWin( 0 ),
+ myWorkArea( 0 )
{
- if ( !split )
- return;
+ myActionsMap.insert( SplitVertical, new QtxAction( QString(), tr( "Split vertically" ), 0, this ) );
+ myActionsMap.insert( SplitHorizontal, new QtxAction( QString(), tr( "Split horizontally" ), 0, this ) );
+ myActionsMap.insert( Close, new QtxAction( QString(), tr( "Close" ), 0, this ) );
+ myActionsMap.insert( Rename, new QtxAction( QString(), tr( "Rename" ), 0, this ) );
- const QObjectList* objs = split->children();
- if ( objs )
- {
- // make up a sizes string: integer values are separated by ':' char
- QValueList<int> sizes = split->sizes();
- QString sizesStr;
- for ( QValueList<int>::Iterator sIt = sizes.begin(); sIt != sizes.end(); ++sIt ) {
- if ( *sIt > 1 ) // size 1 pixel usually means empty Workstack area, which will NOT be re-created,
- sizesStr += QString( ":%1" ).arg( *sIt ); // so we don't need to store its size
- }
- if ( !sizesStr.isEmpty() ) // cut the first ':'
- sizesStr = sizesStr.right( sizesStr.length()-1 );
-
- // count all QSplitter-s and QtxWorkstackArea-s
- // int nChilds( 0 );
- // QObjectListIt it( *objs );
- // for ( ; it.current(); ++it )
- // {
- // if ( it.current()->inherits( "QSplitter" ) ||
- // it.current()->inherits( "QtxWorkstackArea" ) )
- // nChilds++;
- // }
-
- info += QString( "(splitter orientation=%1 sizes=%3 " ).arg( split->orientation() ).arg( sizesStr );
-
- for ( QObjectListIt it( *objs ); it.current(); ++it )
- {
- if ( it.current()->inherits( "QSplitter" ) )
- splitterInfo( (QSplitter*)it.current(), info );
- else if ( it.current()->inherits( "QtxWorkstackArea" ) ) {
- QtxWorkstackArea* area = (QtxWorkstackArea*)it.current();
- if ( area->isEmpty() )
- continue;
- info += QString( "(views active='%1'" ).arg( area->activeWidget()->name() );
- QWidgetList views = area->widgetList();
- for ( QWidgetListIt wIt( views ); wIt.current(); ++wIt )
- info += QString( " '%1'" ).arg( wIt.current()->name() );
- info += ')';
- }
- }
- }
- info += ')';
-}
+ connect( myActionsMap[SplitVertical], SIGNAL( triggered( bool ) ), this, SLOT( splitVertical() ) );
+ connect( myActionsMap[SplitHorizontal], SIGNAL( triggered( bool ) ), this, SLOT( splitHorizontal() ) );
+ connect( myActionsMap[Close], SIGNAL( triggered( bool ) ), this, SLOT( onCloseWindow() ) );
+ connect( myActionsMap[Rename], SIGNAL( triggered( bool ) ), this, SLOT( onRename() ) );
+ QVBoxLayout* base = new QVBoxLayout( this );
+ base->setMargin( 0 );
-//Cuts starting '(' symbol and ending '(' symbol
-void cutBrackets( QString& parameters )
-{
- QChar c1 = parameters[0];
- QChar c2 = parameters[int(parameters.length()-1)];
- if ( !parameters.isEmpty() && c1 == '(' && c2 == ')' )
- parameters = parameters.mid( 1, parameters.length()-2 );
+ mySplit = new QSplitter( this );
+ mySplit->setChildrenCollapsible( false );
+ base->addWidget( mySplit );
}
-/*
- for strings like "(splitter orientation=0 children=2 sizes=332:478" returns values of
- parameters. For example, getValue( example, "children" ) returns "2"
- getValue( example, "sizes" ) returns "332:478"
+/*!
+ \brief Destructor.
*/
-QString getValue( const QString& str, const QString& valName )
+QtxWorkstack::~QtxWorkstack()
{
- int i = str.find( valName );
- if ( i != -1 ) {
- int equal_i = str.find( '=', i );
- if ( equal_i != -1 ) {
- int space_i = str.find( ' ', ++equal_i );
- if ( space_i != -1 )
- return str.mid( equal_i, space_i-equal_i );
- }
- }
- return QString( "" );
}
-/*
- checks format of splitter parameters string
+/*!
+ \brief Get all child widgets in all workareas.
+ \return list of widgets in all workareas
*/
-bool checkFormat( const QString& parameters )
+QWidgetList QtxWorkstack::windowList() const
{
- QString params( parameters );
- // 1. begins and ends with brackets
- QChar c1 = params[0];
- QChar c2 = params[int(params.length()-1)];
- bool ok = ( c1 == '(' && c2 == ')' );
- if ( !ok ) return ok;
- ::cutBrackets( params );
- // 2. has splitter word
- ok = ( params.left( 8 ) == "splitter" );
- if ( !ok ) return ok;
- // 3. has children? = '(' is found
- int i = params.find( '(' );
- ok = i != -1;
- if ( !ok ) return ok;
- params = params.left( i ); // cut all children, they will be checked later
- // 4. has orientation word and correct value
- ::getValue( params, "orientation" ).toInt( &ok );
- if ( !ok ) return ok;
- // 5. has sizes word and values
- ok = ! ::getValue( params, "sizes" ).isEmpty();
- if ( !ok ) return ok;
- // 6. check children -> number of '(' == number of ')' in original string
- ok = ( parameters.contains( '(' ) == parameters.contains( ')' ) );
- return ok;
-}
+ QList<QtxWorkstackArea*> lst;
+ areas( mySplit, lst, true );
-/*
- Returns children of splitter in a list. Children are separated by '(' and ')' symbols
-*/
-QStringList getChildren( const QString& str )
-{
- QStringList lst;
- if ( !str.startsWith( "(" ) )
- return lst;
-
- int i = 1,
- nOpen = 1, // count brackets: '(' increments nOpen, ')' decrements
- start = 0;
- while ( i < (int)str.length() )
+ QWidgetList widList;
+ for ( QList<QtxWorkstackArea*>::iterator it = lst.begin(); it != lst.end(); ++it )
{
- if ( str[i] == '(' )
- {
- nOpen++;
- if ( nOpen == 1 )
- start = i;
- }
- else if ( str[i] == ')' )
- {
- nOpen--;
- if ( nOpen == 0 )
- lst.append( str.mid( start, i-start+1 ) );
- }
- i++;
+ QWidgetList wids = (*it)->widgetList();
+ for ( QWidgetList::iterator itr = wids.begin(); itr != wids.end(); ++itr )
+ widList.append( *itr );
}
- return lst;
+ return widList;
}
-// for a string like "views active='AnotherView' 'GLView' 'AnotherView'"
-// getViewName( example, 0 ) returns "GLView",
-// getViewName( example, 1 ) -> "AnotherView", etc.
-QString getViewName( const QString& str, int i )
+/*!
+ \brief Get all child widgets in the active workarea.
+ \return list of widgets in active workarea
+*/
+QWidgetList QtxWorkstack::splitWindowList() const
{
- QRegExp exp( "\\s'\\w+'" );
- int start = 0; // start index of view name in the string
- int num = 0 ; // index of found match
- while ( ( start = exp.search( str, start ) ) != -1 && num < i ) {
- start += exp.matchedLength();
- num ++;
- }
- if ( start != -1 ) // +2 and -3 avoid starting space and starting and ending ' symbols
- return str.mid( start+2, exp.matchedLength()-3 );
-
- return QString( "" );
+ return myArea ? myArea->widgetList() : QWidgetList();
}
-// returns widget with given name
-QWidget* getView( const QWidget* parent, const QString& aName )
+/*!
+ \brief Get active widget.
+ \return active widget
+*/
+QWidget* QtxWorkstack::activeWindow() const
{
- QWidget* view = 0;
- QObjectList *l = parent->topLevelWidget()->queryList( "QWidget", aName, false, true );
- if ( !l->isEmpty() )
- view = ::qt_cast<QWidget*>( l->first() );
- delete l;
- return view;
+ return myWin;
}
/*!
- Installs a splitter described by given parameters string
+ \brief Split workstack.
+
+ Splitting is possible only if there are two or more widgets in the workarea.
+ This function splits current workarea to two new ones.
+
+ \param o splitting orientation (Qt::Orientation)
*/
-void QtxWorkstack::setSplitter( QSplitter* splitter, const QString& parameters, QMap< QSplitter*, QValueList<int> >& sMap )
+void QtxWorkstack::split( const int o )
{
- if ( !::checkFormat( parameters ) ) {
- printf( "\nInvalid format of workstack parameters. Positions of viewers can not be restored.\n" );
+ QtxWorkstackArea* area = myWorkArea;
+ if ( !area )
+ area = activeArea();
+ if ( !area )
return;
- }
- QString params( parameters );
- ::cutBrackets( params );
+ if ( area->widgetList().count() < 2 )
+ return;
- // get splitter sizes and store it in the map for future setting
- QValueList<int> sizes;
- QStringList sizesLst = QStringList::split( ':', ::getValue( params, "sizes" ) );
- QStringList::Iterator it;
- for ( it = sizesLst.begin(); it != sizesLst.end(); ++it )
- sizes.append( (*it).toInt() );
- sMap[ splitter ] = sizes;
+ QWidget* curWid = area->activeWidget();
+ if ( !curWid )
+ return;
- // set orientation of splitter
- int orient = ::getValue( params, "orientation" ).toInt();
- splitter->setOrientation( (Qt::Orientation)orient );
+ QSplitter* s = splitter( area );
+ QList<QtxWorkstackArea*> areaList;
+ areas( s, areaList );
- // get children
- QString options = params.left( params.find( '(' ) );
- QString childrenStr = params.right( params.length()-options.length() );
- QStringList children = ::getChildren( childrenStr );
+ QList<QSplitter*> splitList;
+ splitters( s, splitList );
- // debug output..
- // printf (" splitter orient=%d, sizes_count=%d, children=%d\n", orient, sizes.count(), children.count() );
- // for ( QStringList::Iterator tit = children.begin(); tit != children.end(); ++tit )
- // printf (" |-> child = [%s]\n", (*tit).latin1() );
+ QSplitter* trg = 0;
+ if ( areaList.count() + splitList.count() < 2 || s->orientation() == o )
+ trg = s;
- for ( QStringList::Iterator it = children.begin(); it != children.end(); ++it ) {
- if ( (*it).startsWith( "(splitter" ) ) {
- QSplitter* newSplitter = new QSplitter( splitter );
- setSplitter( newSplitter, *it, sMap );
- }
- else if ( (*it).startsWith( "(views" ) ) {
- QtxWorkstackArea* newArea = createArea( splitter );
- QString activeViewName = ::getValue( *it, "active" );
- QWidget* activeView( 0 );
- activeViewName = activeViewName.mid( 1, activeViewName.length()-2 ); // chop off ' symbols
- int i = 0;
- QString viewName = ::getViewName( *it, i );
- while ( !viewName.isEmpty() ) {
- if ( QWidget* view = ::getView( splitter, viewName ) ) {
- newArea->insertWidget( view );
- if ( activeViewName == view->name() )
- activeView = view;
- }
- viewName = ::getViewName( *it, ++i );
- }
- if ( activeView )
- newArea->setActiveWidget( activeView );
- }
- }
-}
+ if ( !trg )
+ trg = wrapSplitter( area );
-/*!
- Restore workstack's configuration stored in 'parameters' string
-*/
-QtxWorkstack& QtxWorkstack::operator<<( const QString& parameters )
-{
- // clear the main splitter - remove all child splitters and empty areas from it
- QPtrList<QSplitter> splitList;
- QPtrList<QtxWorkstackArea> areaList;
- splitters( mySplit, splitList, false );
- areas( mySplit, areaList, false );
- for ( QPtrListIterator<QSplitter> iter( splitList ); iter.current(); ++iter )
- delete iter.current();
- for ( QPtrListIterator<QtxWorkstackArea> it( areaList ); it.current(); ++it )
- if ( it.current()->isEmpty() )
- delete it.current();
+ if ( !trg )
+ return;
- // restore splitter recursively
- QMap< QSplitter*, QValueList<int> > sMap;
- setSplitter( mySplit, parameters, sMap );
+ trg->setOrientation( (Qt::Orientation)o );
- // now mySplit may contains empty area (where all views were located before restoring)
- // in order setSize to work correctly we have to exclude this area
- areaList.clear();
- areas( mySplit, areaList, false );
- for ( QPtrListIterator<QtxWorkstackArea> delIt( areaList ); delIt.current(); ++delIt )
- if ( delIt.current()->isEmpty() )
- delete delIt.current();
+ QtxWorkstackArea* newArea = createArea( 0 );
+ trg->insertWidget( trg->indexOf( area ) + 1, newArea );
- qApp->processEvents();
+ area->removeWidget( curWid );
+ newArea->insertWidget( curWid );
- // restore splitters' sizes (map of sizes is filled in setSplitters)
- for ( QMap< QSplitter*, QValueList<int> >::Iterator itm = sMap.begin(); itm != sMap.end(); ++itm )
- itm.key()->setSizes( itm.data() );
+ distributeSpace( trg );
- return (*this);
+ curWid->show();
+ curWid->setFocus();
}
/*!
- Example of string produced by operator>> :
- "(splitter orientation=0 sizes=186:624 (views active='OCCViewer_0_0' 'OCCViewer_0_0')
-/ (views active='VTKViewer_0_0' 'VTKViewer_0_0'))"
-*/
-QtxWorkstack& QtxWorkstack::operator>>( QString& outParameters )
-{
- splitterInfo( mySplit, outParameters );
- return (*this);
-}
+ \brief Split workarea of the given widget on two parts.
+ Splitting is possible only if there are two or more widgets in the workarea.
+ This function splits current workarea to two new ones.
-/*!
- Constructor
+ \param wid widget belonging to the workstack
+ \param o splitting orientation type (Qt::Orientation)
+ \param type splitting type (QtxWorkstack::SplitType)
*/
-QtxWorkstackArea::QtxWorkstackArea( QWidget* parent )
-: QWidget( parent )
+void QtxWorkstack::Split( QWidget* wid, const Qt::Orientation o, const SplitType type )
{
- QVBoxLayout* base = new QVBoxLayout( this );
+ if (!wid) return;
- QHBox* top = new QHBox( this );
- base->addWidget( top );
+ // find area of the given widget
+ QtxWorkstackArea* area = NULL;
+ QList<QtxWorkstackArea*> allAreas;
+ areas(mySplit, allAreas, true);
- myBar = new QtxWorkstackTabBar( top );
- QPushButton* close = new QPushButton( top );
- close->setPixmap( style().stylePixmap( QStyle::SP_TitleBarCloseButton ) );
- close->setAutoDefault( true );
- close->setFlat( true );
- myClose = close;
+ for ( QList<QtxWorkstackArea*>::iterator it = allAreas.begin(); it != allAreas.end() && !area; ++it )
+ {
+ if ( (*it)->contains( wid ) )
+ area = *it;
+ }
- top->setStretchFactor( myBar, 1 );
+ if ( !area )
+ return;
- myStack = new QWidgetStack( this );
+ QWidgetList wids = area->widgetList();
+ if ( wids.count() < 2 )
+ return;
- base->addWidget( myStack, 1 );
+ QSplitter* s = splitter( area );
+ QList<QtxWorkstackArea*> areaList;
+ areas( s, areaList );
- connect( myClose, SIGNAL( clicked() ), this, SLOT( onClose() ) );
- connect( myBar, SIGNAL( selected( int ) ), this, SLOT( onSelected( int ) ) );
- connect( myBar, SIGNAL( dragActiveTab() ), this, SLOT( onDragActiveTab() ) );
- connect( myBar, SIGNAL( contextMenuRequested( QPoint ) ), this, SLOT( onContextMenuRequested( QPoint ) ) );
+ QList<QSplitter*> splitList;
+ splitters(s, splitList);
- updateState();
+ QSplitter* trg = 0;
+ if (areaList.count() + splitList.count() < 2 || s->orientation() == o)
+ trg = s;
- updateActiveState();
+ if (!trg) trg = wrapSplitter(area);
+ if (!trg) return;
+
+ trg->setOrientation(o);
+
+ QtxWorkstackArea* newArea = createArea(0);
+ insertWidget(newArea, trg, area);
+
+ switch ( type )
+ {
+ case SplitStay:
+ for ( QWidgetList::iterator itr = wids.begin(); itr != wids.end(); ++itr )
+ {
+ QWidget* wid_i = *itr;
+ if ( wid_i != wid )
+ {
+ area->removeWidget( wid_i );
+ newArea->insertWidget( wid_i );
+ }
+ }
+ break;
+ case SplitAt:
+ {
+ QWidgetList::iterator itr = wids.begin();
+ for ( ; itr != wids.end() && *itr != wid; ++itr )
+ {
+ }
+ for ( ; itr != wids.end(); ++itr )
+ {
+ area->removeWidget( *itr );
+ newArea->insertWidget( *itr );
+ }
+ }
+ break;
+ case SplitMove:
+ area->removeWidget( wid );
+ newArea->insertWidget( wid );
+ break;
+ }
- qApp->installEventFilter( this );
+ distributeSpace( trg );
}
/*!
- Destructor
+ \brief Move widget(s) from the source workarea into the target workarea
+ or reorder widgets inside one workarea.
+
+ Move \a wid2 in target workarea. Put it right after \a wid1.
+ If \a all parameter is \c true, all widgets from source workarea
+ will be moved including \a wid2 and source workarea will be deleted then.
+
+ If \a wid1 and \a wid2 belongs to one workarea, widgets will be just reordered
+ in that workarea.
+
+ \param wid1 widget from target workarea
+ \param wid2 widget from source workarea
+ \param all if \c true, all widgets from source workarea will
+ be moved into the target one, else only the \a wid2 will be moved
*/
-QtxWorkstackArea::~QtxWorkstackArea()
+void QtxWorkstack::Attract( QWidget* wid1, QWidget* wid2, const bool all )
{
- qApp->removeEventFilter( this );
+ if ( !wid1 || !wid2 )
+ return;
+
+ // find area of the widgets
+ QtxWorkstackArea *area1 = 0, *area2 = 0;
+ QList<QtxWorkstackArea*> allAreas;
+ areas( mySplit, allAreas, true );
+ for ( QList<QtxWorkstackArea*>::iterator it = allAreas.begin(); it != allAreas.end() && !( area1 && area2 ); ++it )
+ {
+ if ( (*it)->contains( wid1 ) )
+ area1 = *it;
+
+ if ( (*it)->contains( wid2 ) )
+ area2 = *it;
+ }
+
+ if ( !area1 || !area2 )
+ return;
+
+ QWidget* curWid = area1->activeWidget();
+ if ( !curWid )
+ return;
+
+ if ( area1 == area2 )
+ {
+ if ( all )
+ {
+ // Set wid1 at first position, wid2 at second
+ area1->insertWidget( wid1 );
+ area1->insertWidget( wid2, 1 );
+ }
+ else
+ {
+ // Set wid2 right after wid1
+ area1->removeWidget( wid2 );
+ int wid1_ind = 0;
+ QWidgetList wids1 = area1->widgetList();
+ for ( QWidgetList::iterator itr1 = wids1.begin(); itr1 != wids1.end() && *itr1 != wid1; ++itr1, ++wid1_ind );
+ area1->insertWidget( wid2, wid1_ind + 1 );
+ }
+ }
+ else
+ {
+ int wid1_ind = 0;
+ QWidgetList wids1 = area1->widgetList();
+ for ( QWidgetList::iterator itr1 = wids1.begin(); itr1 != wids1.end() && *itr1 != wid1; ++itr1, ++wid1_ind );
+ if ( all )
+ {
+ // Set wid2 right after wid1, other widgets from area2 right after wid2
+ QWidgetList wids2 = area2->widgetList();
+ QWidgetList::iterator itr2 = wids2.begin();
+ for ( int ind = wid1_ind + 1; itr2 != wids2.end(); ++itr2, ++ind )
+ {
+ area2->removeWidget( *itr2 );
+ if ( *itr2 == wid2 )
+ area1->insertWidget( *itr2, wid1_ind + 1 );
+ else
+ area1->insertWidget( *itr2, ind );
+ }
+ }
+ else
+ {
+ // Set wid2 right after wid1
+ area2->removeWidget( wid2 );
+ area1->insertWidget( wid2, wid1_ind + 1 );
+ }
+ }
+
+ area1->setActiveWidget( curWid );
}
/*!
- \return true if area is empty
+ \brief Calculate sizes of the splitter widget for the workarea.
+ \internal
*/
-bool QtxWorkstackArea::isEmpty() const
+static void setSizes (QIntList& szList, const int item_ind,
+ const int new_near, const int new_this, const int new_farr)
{
- bool res = false;
- for ( WidgetInfoMap::ConstIterator it = myInfo.begin(); it != myInfo.end() && !res; ++it )
- res = it.data().vis;
- return !res;
+ // set size to all items before an item # <item_ind>
+ int cur_pos = 0;
+ QIntList::iterator its = szList.begin();
+ for (; its != szList.end() && cur_pos < item_ind; ++its, ++cur_pos) {
+ *its = new_near;
+ }
+ if (its == szList.end()) return;
+ // set size to item # <item_ind>
+ *its = new_this;
+ ++its;
+ // set size to all items after an item # <item_ind>
+ for (; its != szList.end(); ++its) {
+ *its = new_farr;
+ }
}
/*!
- Adds widget to area
- \param wid - widget
- \param idx - index
+ \brief Set position of the widget relatively to its parent splitter.
+
+ Orientation of positioning will correspond to the splitter orientation.
+
+ \param wid widget
+ \param pos position relatively to the splitter; value in the range [0..1]
*/
-void QtxWorkstackArea::insertWidget( QWidget* wid, const int idx )
+void QtxWorkstack::SetRelativePositionInSplitter( QWidget* wid, const double position )
{
- if ( !wid )
+ if ( position < 0.0 || 1.0 < position)
return;
- int pos = myList.find( wid );
- if ( pos != -1 && ( pos == idx || ( idx < 0 && pos == (int)myList.count() - 1 ) ) )
+ if ( !wid )
return;
- myList.removeRef( wid );
- pos = idx < 0 ? myList.count() : idx;
- myList.insert( QMIN( pos, (int)myList.count() ), wid );
- if ( !myInfo.contains( wid ) )
+ // find area of the given widget
+ QtxWorkstackArea* area = NULL;
+ QList<QtxWorkstackArea*> allAreas;
+ areas( mySplit, allAreas, true );
+ for ( QList<QtxWorkstackArea*>::iterator it = allAreas.begin(); it != allAreas.end() && !area; ++it )
{
- QtxWorkstackChild* child = new QtxWorkstackChild( wid, myStack );
- myChild.insert( wid, child );
- myInfo.insert( wid, WidgetInfo() );
- myInfo[wid].id = generateId();
- myInfo[wid].vis = wid->isVisibleTo( wid->parentWidget() );
-
- connect( child, SIGNAL( destroyed( QObject* ) ), this, SLOT( onChildDestroyed( QObject* ) ) );
- connect( wid, SIGNAL( destroyed() ), this, SLOT( onWidgetDestroyed() ) );
- connect( child, SIGNAL( shown( QtxWorkstackChild* ) ), this, SLOT( onChildShown( QtxWorkstackChild* ) ) );
- connect( child, SIGNAL( hided( QtxWorkstackChild* ) ), this, SLOT( onChildHided( QtxWorkstackChild* ) ) );
- connect( child, SIGNAL( activated( QtxWorkstackChild* ) ), this, SLOT( onChildActivated( QtxWorkstackChild* ) ) );
- connect( child, SIGNAL( captionChanged( QtxWorkstackChild* ) ), this, SLOT( onChildCaptionChanged( QtxWorkstackChild* ) ) );
+ if ( (*it)->contains( wid ) )
+ area = *it;
}
- updateState();
+ if ( !area )
+ return;
- setWidgetActive( wid );
- wid->setFocus();
-}
+ QSplitter* split = splitter( area );
+ if ( !split )
+ return;
-/*!
- Creates and shows popup menu for area
- \param p - popup position
-*/
-void QtxWorkstackArea::onContextMenuRequested( QPoint p )
-{
- const QtxWorkstackTabBar* bar = ::qt_cast<const QtxWorkstackTabBar*>( sender() );
- if ( !bar )
+ // find index of the area in its splitter
+ int item_ind = -1;
+ bool isFound = false;
+ const QObjectList& was = split->children();
+ for ( QObjectList::const_iterator ito = was.begin(); ito != was.end() && !isFound; ++ito, ++item_ind )
+ {
+ if ( *ito == area )
+ isFound = true;
+ }
+
+ if ( !isFound || item_ind == 0 )
return;
- QWidget* wid = 0;
- QTab* tab = myBar->tabAt( tabAt( p ) );
- if ( tab )
- wid = widget( tab->identifier() );
+ QIntList szList = split->sizes();
+ int splitter_size = ( split->orientation() == Qt::Horizontal ? split->width() : split->height());
+ int nb = szList.count();
- emit contextMenuRequested( wid, p );
+ int new_prev = int( splitter_size * position / item_ind );
+ int new_next = int( splitter_size * ( 1.0 - position ) / ( nb - item_ind ) );
+ setSizes( szList, item_ind, new_prev, new_next, new_next );
+ split->setSizes( szList );
}
/*!
- SLOT: called when widget added to area is destroyed, removes widget from area
-*/
-void QtxWorkstackArea::onWidgetDestroyed()
-{
- if ( sender() )
- removeWidget( (QWidget*)sender(), false );
-}
+ \brief Set position of the widget relatively to the entire workstack.
-/*!
- Removes widget from area
- \param wid - widget
- \param del - auto deleting
+ If \a o is \c Qt::Horizontal, the horizontal position of \a wid will be changed.
+ If \a o is \c Qt::Vertical, the vertical position of \a wid will be changed.
+
+ \param wid widget
+ \param o orientation of positioning (\c Qt::Horizontal or \c Qt::Vertical)
+ \param pos position relatively to the workstack; value in range [0..1]
*/
-void QtxWorkstackArea::removeWidget( QWidget* wid, const bool del )
+void QtxWorkstack::SetRelativePosition( QWidget* wid, const Qt::Orientation o,
+ const double position )
{
- if ( !myList.contains( wid ) )
+ if ( position < 0.0 || 1.0 < position )
return;
- if ( myBar->tab( widgetId( wid ) ) )
- myBar->removeTab( myBar->tab( widgetId( wid ) ) );
- myStack->removeWidget( child( wid ) );
+ if ( !wid )
+ return;
- myList.remove( wid );
- myInfo.remove( wid );
- myChild.remove( wid );
+ int splitter_size = o == Qt::Horizontal ? mySplit->width() : mySplit->height();
+ int need_pos = int( position * splitter_size );
+ int splitter_pos = 0;
- if( del )
+ if ( setPosition( wid, mySplit, o, need_pos, splitter_pos ) != 0 )
{
- delete child( wid );
- if( myList.isEmpty() )
- delete this;
- else
- updateState();
+ // impossible to set required position
}
- else
- updateState();
}
/*!
- \return list of visible widgets
+ \brief Set accelerator key-combination for the action with specified \a id.
+ \param id action ID
+ \param accel action accelerator
*/
-QWidgetList QtxWorkstackArea::widgetList() const
+void QtxWorkstack::setAccel( const int id, const int accel )
{
- QWidgetList lst;
- for ( QWidgetListIt it( myList ); it.current(); ++it )
- {
- if ( widgetVisibility( it.current() ) )
- lst.append( it.current() );
- }
- return lst;
+ if ( !myActionsMap.contains( id ) )
+ return;
+
+ myActionsMap[id]->setShortcut( accel );
}
/*!
- \return active widget
+ \brief Get the action's accelerator key-combination.
+ \param id action ID
+ \return action accelerator
*/
-QWidget* QtxWorkstackArea::activeWidget() const
+int QtxWorkstack::accel( const int id ) const
{
- return widget( myBar->currentTab() );
+ int res = 0;
+ if ( myActionsMap.contains( id ) )
+ res = myActionsMap[id]->shortcut();
+ return res;
}
/*!
- Sets widget as active
- \param wid - widget
+ \brief Set actions to be visible in the context popup menu.
+
+ Actions, which IDs are set in \a flags parameter, will be shown in the
+ context popup menu. Other actions will not be shown.
+
+ \param flags ORed together actions flags
*/
-void QtxWorkstackArea::setActiveWidget( QWidget* wid )
+void QtxWorkstack::setMenuActions( const int flags )
{
- myBar->setCurrentTab( widgetId( wid ) );
+ myActionsMap[SplitVertical]->setVisible( flags & SplitVertical );
+ myActionsMap[SplitHorizontal]->setVisible( flags & SplitHorizontal );
+ myActionsMap[Close]->setVisible( flags & Close );
+ myActionsMap[Rename]->setVisible( flags & Rename );
}
/*!
- \return true if area contains widget
- \param wid - widget
+ \brief Set actions to be visible in the context popup menu.
+
+ Actions, which IDs are set in \a flags parameter, will be shown in the
+ context popup menu. Other actions will not be shown.
+
+ \param flags ORed together actions flags
*/
-bool QtxWorkstackArea::contains( QWidget* wid ) const
+int QtxWorkstack::menuActions() const
{
- return myList.contains( wid );
+ int ret = 0;
+ ret = ret | ( myActionsMap[SplitVertical]->isVisible() ? SplitVertical : 0 );
+ ret = ret | ( myActionsMap[SplitHorizontal]->isVisible() ? SplitHorizontal : 0 );
+ ret = ret | ( myActionsMap[Close]->isVisible() ? Close : 0 );
+ ret = ret | ( myActionsMap[Rename]->isVisible() ? Rename : 0 );
+ return ret;
}
/*!
- Shows area
+ \brief Calculate sizes of the splitter widget for the workarea.
+ \internal
*/
-void QtxWorkstackArea::show()
+static int positionSimple (QIntList& szList, const int nb, const int splitter_size,
+ const int item_ind, const int item_rel_pos,
+ const int need_pos, const int splitter_pos)
{
- QMap<QWidget*, bool> map;
- for ( QWidgetListIt it( myList ); it.current(); ++it )
- {
- map.insert( it.current(), isBlocked( it.current() ) );
- setBlocked( it.current(), true );
+ if (item_ind == 0) { // cannot move in this splitter
+ return (need_pos - splitter_pos);
}
- QWidget::show();
-
- for ( QWidgetListIt itr( myList ); itr.current(); ++itr )
- setBlocked( itr.current(), map.contains( itr.current() ) ? map[itr.current()] : false );
-}
+ int delta = 0;
+ int new_prev = 0;
+ int new_this = szList[item_ind];
+ int new_next = 0;
-/*!
- Hides area
-*/
-void QtxWorkstackArea::hide()
-{
- QMap<QWidget*, bool> map;
- for ( QWidgetListIt it( myList ); it.current(); ++it )
- {
- map.insert( it.current(), isBlocked( it.current() ) );
- setBlocked( it.current(), true );
- }
+ bool isToCheck = false;
- QWidget::hide();
+ if (need_pos < splitter_pos) {
+ // Set size of all previous workareas to zero <--
+ if (item_ind == nb - 1) {
+ // item iz last in the splitter, it will occupy all the splitter
+ new_this = splitter_size;
+ } else {
+ // recompute size of next items in splitter
+ new_next = (splitter_size - new_this) / (nb - item_ind - 1);
+ }
+ delta = need_pos - splitter_pos;
- for ( QWidgetListIt itr( myList ); itr.current(); ++itr )
- setBlocked( itr.current(), map.contains( itr.current() ) ? map[itr.current()] : false );
-}
+ } else if (need_pos > (splitter_pos + splitter_size)) {
+ // Set size of all next workareas to zero -->
+ // recompute size of previous items in splitter
+ new_this = 0;
+ new_prev = (splitter_size - new_this) / item_ind;
+ delta = need_pos - (splitter_pos + splitter_size - new_this);
-/*!
- \return true if area is active
-*/
-bool QtxWorkstackArea::isActive() const
-{
- QtxWorkstack* ws = workstack();
- if ( !ws )
- return false;
+ } else { // required position lays inside this splitter
+ // Move workarea inside splitter into required position <->
+ int new_item_rel_pos = need_pos - splitter_pos;
+ new_prev = new_item_rel_pos / item_ind;
+ if (need_pos < (splitter_pos + item_rel_pos)) {
+ // Make previous workareas smaller, next - bigger
+ // No problem to keep old size of the widget
+ } else {
+ // Make previous workareas bigger, next - smaller
+ if (new_this > splitter_size - new_item_rel_pos) {
+ new_this = splitter_size - new_item_rel_pos;
+ }
+ // jfa to do: in this case fixed size of next widgets could prevent right resizing
+ isToCheck = true;
+ }
+ if (item_ind == nb - 1) {
+ new_this = splitter_size - new_item_rel_pos;
+ } else {
+ new_next = (splitter_size - new_item_rel_pos - new_this) / (nb - item_ind - 1);
+ }
+ delta = 0;
+ }
- return ws->activeArea() == this;
+ setSizes (szList, item_ind, new_prev, new_this, new_next);
+ return delta;
}
/*!
- Update active state of tab bar
-*/
-void QtxWorkstackArea::updateActiveState()
-{
- myBar->setActive( isActive() );
-}
+ \brief Set position of the widget.
-/*!
- \return corresponding workstack
-*/
-QtxWorkstack* QtxWorkstackArea::workstack() const
-{
- QtxWorkstack* ws = 0;
- QWidget* wid = parentWidget();
- while ( wid && !ws )
- {
- if ( wid->inherits( "QtxWorkstack" ) )
- ws = (QtxWorkstack*)wid;
- wid = wid->parentWidget();
- }
- return ws;
-}
+ Called from SetRelativePosition() public method.
-/*!
- Custom event filter
+ \param wid widget to be moved
+ \param split currently processed splitter (goes from more common
+ to more particular splitter in recursion calls)
+ \param o orientation of positioning
+ \param need_pos required position of the given widget in pixels
+ (from top/left side of workstack area)
+ \param splitter_pos position of the splitter \a split
+ (from top/left side of workstack area)
+ \return difference between a required and a distinguished position
*/
-bool QtxWorkstackArea::eventFilter( QObject* o, QEvent* e )
+int QtxWorkstack::setPosition( QWidget* wid, QSplitter* split, const Qt::Orientation o,
+ const int need_pos, const int splitter_pos )
{
- if ( o->isWidgetType() )
+ if ( !wid || !split )
+ return need_pos - splitter_pos;
+
+ // Find corresponding sub-splitter.
+ // Find also index of appropriate item in current splitter.
+ int cur_ind = 0, item_ind = 0;
+ bool isBottom = false, isFound = false;
+ QSplitter* sub_split = NULL;
+ const QObjectList& objs = split->children();
+ for ( QObjectList::const_iterator it = objs.begin(); it != objs.end() && !isFound; ++it )
{
- QWidget* wid = (QWidget*)o;
- if ( e->type() == QEvent::FocusIn || e->type() == QEvent::MouseButtonPress )
+ QtxWorkstackArea* area = ::qobject_cast<QtxWorkstackArea*>( *it );
+ if ( area )
{
- bool ok = false;
- while ( !ok && wid && wid != myClose )
+ if ( area->contains( wid ) )
{
- ok = wid == this;
- wid = wid->parentWidget();
+ item_ind = cur_ind;
+ isBottom = true;
+ isFound = true;
}
- if ( ok )
- QApplication::postEvent( this, new QCustomEvent( (QEvent::Type)( e->type() == QEvent::FocusIn ? ActivateWidget : FocusWidget ) ) );
+ cur_ind++;
+ }
+ else if ( (*it)->inherits( "QSplitter" ) )
+ {
+ QList<QtxWorkstackArea*> areaList;
+ areas( (QSplitter*)(*it), areaList, true );
+ for ( QList<QtxWorkstackArea*>::iterator ita = areaList.begin(); ita != areaList.end() && !isFound; ++ita )
+ {
+ if ( (*ita)->contains( wid ) )
+ {
+ item_ind = cur_ind;
+ isFound = true;
+ sub_split = (QSplitter*)*it;
+ }
+ }
+ cur_ind++;
}
}
- return false;
-}
-/*!
- \return rectangle of area in order to draw drop rectangle on area
-*/
-QRect QtxWorkstackArea::floatRect() const
-{
- QRect r = myStack->geometry();
- return QRect( mapToGlobal( r.topLeft() ), mapToGlobal( r.bottomRight() ) );
-}
+ if ( !isFound )
+ return ( need_pos - splitter_pos );
+
+ if ( split->orientation() == o )
+ {
+ // Find coordinates of near and far sides of the appropriate item relatively current splitter
+ int splitter_size = ( o == Qt::Horizontal ? split->width() : split->height() );
+ QIntList szList = split->sizes();
+ int nb = szList.count();
+ int item_rel_pos = 0; // position of near side of item relatively this splitter
+ for (int i = 0; i < item_ind; i++) {
+ item_rel_pos += szList[i];
+ }
+ int item_size = szList[item_ind]; // size of item
+ int item_pos = splitter_pos + item_rel_pos;
+
+ // Resize splitter items to complete the conditions
+ if (isBottom) {
+ // I. Bottom of splitters stack reached
+
+ int delta = positionSimple(szList, nb, splitter_size, item_ind, item_rel_pos, need_pos, splitter_pos);
+ split->setSizes(szList);
+ // Recompute delta, as some windows can reject given size
+ int new_item_rel_pos = 0;
+ QIntList szList1 = split->sizes();
+ for (int i = 0; i < item_ind; i++) {
+ new_item_rel_pos += szList1[i];
+ }
+ delta = need_pos - (splitter_pos + new_item_rel_pos);
+ return delta;
+
+ } else {
+ // II. Bottom of splitters stack is not yet reached
+
+ if (item_ind == 0) { // cannot move in this splitter
+ // Process in sub-splitter
+ return setPosition(wid, sub_split, o, need_pos, splitter_pos);
+ }
+
+ int new_prev = 0;
+ int new_this = szList[item_ind];
+ int new_next = 0;
+
+ if (need_pos < splitter_pos) {
+ // Set size of all previous workareas to zero <--
+ if (item_ind == nb - 1) {
+ new_this = splitter_size;
+ } else {
+ new_next = (splitter_size - new_this) / (nb - item_ind - 1);
+ }
+ setSizes (szList, item_ind, new_prev, new_this, new_next);
+ split->setSizes(szList);
+ // Recompute splitter_pos, as some windows can reject given size
+ int new_item_rel_pos = 0;
+ QIntList szList1 = split->sizes();
+ for (int i = 0; i < item_ind; i++) {
+ new_item_rel_pos += szList1[i];
+ }
+ // Process in sub-splitter
+ return setPosition(wid, sub_split, o, need_pos, splitter_pos + new_item_rel_pos);
+ } else if (need_pos > (splitter_pos + splitter_size)) {
+ // Set size of all next workareas to zero -->
+ new_prev = (splitter_size - new_this) / item_ind;
+ setSizes (szList, item_ind, new_prev, new_this, new_next);
+ split->setSizes(szList);
+ // Recompute splitter_pos, as some windows can reject given size
+ int new_item_rel_pos = 0;
+ QIntList szList1 = split->sizes();
+ for (int i = 0; i < item_ind; i++) {
+ new_item_rel_pos += szList1[i];
+ }
+ // Process in sub-splitter
+ return setPosition(wid, sub_split, o, need_pos, splitter_pos + new_item_rel_pos);
+ } else {
+ // Set appropriate size of all previous/next items <->
+ int new_item_rel_pos = item_rel_pos;
+ if (need_pos < item_pos || (item_pos + item_size) < need_pos) {
+ // Move item inside splitter into required position <->
+ int new_this = szList[item_ind];
+ int new_next = 0;
+ new_item_rel_pos = need_pos - splitter_pos;
+ if ((item_pos + item_size) < need_pos) {
+ //new_item_rel_pos = need_pos - (item_pos + item_size);
+ new_item_rel_pos = item_rel_pos + (need_pos - (item_pos + item_size));
+ }
+ int new_prev = new_item_rel_pos / item_ind;
+ if (need_pos < (splitter_pos + item_rel_pos)) {
+ // Make previous workareas smaller, next - bigger
+ // No problem to keep old size of the widget
+ } else {
+ // Make previous workareas bigger, next - smaller
+ if (new_this > splitter_size - new_item_rel_pos) {
+ new_this = splitter_size - new_item_rel_pos;
+ }
+ }
+ if (item_ind == nb - 1) {
+ new_this = splitter_size - new_item_rel_pos;
+ } else {
+ new_next = (splitter_size - new_item_rel_pos - new_this) / (nb - item_ind - 1);
+ }
+ setSizes (szList, item_ind, new_prev, new_this, new_next);
+ split->setSizes(szList);
+ // Recompute new_item_rel_pos, as some windows can reject given size
+ new_item_rel_pos = 0;
+ QIntList szList1 = split->sizes();
+ for (int i = 0; i < item_ind; i++) {
+ new_item_rel_pos += szList1[i];
+ }
+ } else {
+ // Do nothing
+ }
+ // Process in sub-splitter
+ int add_pos = setPosition(wid, sub_split, o, need_pos, splitter_pos + new_item_rel_pos);
+ if (add_pos == 0)
+ return 0;
-/*!
- \return rectangle of tab in order to draw drop rectangle on tab
- \param idx - tab index
-*/
-QRect QtxWorkstackArea::floatTab( const int idx ) const
-{
- return myBar->tabRect( idx );
-}
+ // this can be if corresponding workarea is first in sub-splitter
+ // or sub-splitter has another orientation
-/*!
- \return tab covering point
- \param p - point
-*/
-int QtxWorkstackArea::tabAt( const QPoint& p ) const
-{
- int idx = -1;
- for ( int i = 0; i < myBar->count() && idx == -1; i++ )
- {
- QRect r = myBar->tabRect( i );
- if ( r.isValid() && r.contains( p ) )
- idx = i;
- }
- return idx;
-}
+ // Resize ones again to reach precize position <->
+ int need_pos_1 = splitter_pos + new_item_rel_pos + add_pos;
-/*!
- Event handler for custom events
-*/
-void QtxWorkstackArea::customEvent( QCustomEvent* e )
-{
- switch ( e->type() )
- {
- case ActivateWidget:
- emit activated( activeWidget() );
- break;
- case FocusWidget:
- if ( activeWidget() )
- {
- if ( !activeWidget()->focusWidget() )
- activeWidget()->setFocus();
- else {
- if ( activeWidget()->focusWidget()->hasFocus()) {
- QFocusEvent in(QEvent::FocusIn);
- QApplication::sendEvent(this, &in);
- }
- else
- activeWidget()->focusWidget()->setFocus();
+ // Move workarea inside splitter into required position <->
+ int delta_1 = positionSimple(szList, nb, splitter_size, item_ind,
+ new_item_rel_pos, need_pos_1, splitter_pos);
+ split->setSizes(szList);
+ // Recompute new_item_rel_pos, as some windows can reject given size
+ new_item_rel_pos = 0;
+ QIntList szList1 = split->sizes();
+ for (int i = 0; i < item_ind; i++) {
+ new_item_rel_pos += szList1[i];
+ }
+ delta_1 = need_pos_1 - (splitter_pos + new_item_rel_pos);
+ return delta_1;
}
}
- break;
- case RemoveWidget:
- removeWidget( (QWidget*)e->data() );
- break;
+ } else {
+ return setPosition(wid, sub_split, o, need_pos, splitter_pos);
}
-}
-
-/*!
- Custom focus in event handler
-*/
-void QtxWorkstackArea::focusInEvent( QFocusEvent* e )
-{
- QWidget::focusInEvent( e );
- emit activated( activeWidget() );
+ return 0;
}
/*!
- Custom mouse press event handler
+ \brief Redistribute space among widgets equally.
+ \param split splitter
*/
-void QtxWorkstackArea::mousePressEvent( QMouseEvent* e )
+void QtxWorkstack::distributeSpace( QSplitter* split ) const
{
- QWidget::mousePressEvent( e );
+ if ( !split )
+ return;
- emit activated( activeWidget() );
+ QIntList szList = split->sizes();
+ int size = ( split->orientation() == Qt::Horizontal ?
+ split->width() : split->height() ) / szList.count();
+ for ( QIntList::iterator it = szList.begin(); it != szList.end(); ++it )
+ *it = size;
+ split->setSizes( szList );
}
/*!
- SLOT: called if button close is pressed
+ \brief Split widgets vertically.
*/
-void QtxWorkstackArea::onClose()
+void QtxWorkstack::splitVertical()
{
- QWidget* wid = activeWidget();
- if ( wid )
- wid->close();
+ split( Qt::Horizontal );
}
/*!
- SLOT: called if tab page is selected
+ \brief Split widgets horizontally.
*/
-void QtxWorkstackArea::onSelected( int id )
+void QtxWorkstack::splitHorizontal()
{
- updateCurrent();
-
- emit activated( activeWidget() );
+ split( Qt::Vertical );
}
/*!
- SLOT: called if active tab page is dragged
+ \brief Called when user activates "Rename" menu item.
+
+ Changes widget title.
*/
-void QtxWorkstackArea::onDragActiveTab()
+void QtxWorkstack::onRename()
{
- QtxWorkstackChild* c = child( activeWidget() );
- if ( !c )
+ if ( !myWorkWin )
return;
- new QtxWorkstackDrag( workstack(), c );
+ bool ok = false;
+ QString newName = QInputDialog::getText( topLevelWidget(), tr( "Rename" ), tr( "Enter new name:" ),
+ QLineEdit::Normal, myWorkWin->windowTitle(), &ok );
+ if ( ok && !newName.isEmpty() )
+ myWorkWin->setWindowTitle( newName );
}
/*!
- SLOT: called on child is destroyed, removes from area
+ \brief Wrap area into the new splitter.
+ \param workarea
+ \return new splitter
*/
-void QtxWorkstackArea::onChildDestroyed( QObject* obj )
+QSplitter* QtxWorkstack::wrapSplitter( QtxWorkstackArea* area )
{
- QtxWorkstackChild* child = (QtxWorkstackChild*)obj;
- myStack->removeWidget( child );
-
- QWidget* wid = 0;
- for ( ChildMap::ConstIterator it = myChild.begin(); it != myChild.end() && !wid; ++it )
- {
- if ( it.data() == child )
- wid = it.key();
- }
-
- myChild.remove( wid );
-
- QApplication::postEvent( this, new QCustomEvent( (QEvent::Type)RemoveWidget, wid ) );
-}
+ if ( !area )
+ return 0;
-/*!
- SLOT: called on child is shown
-*/
-void QtxWorkstackArea::onChildShown( QtxWorkstackChild* c )
-{
- setWidgetShown( c->widget(), true );
-}
+ QSplitter* pSplit = splitter( area );
+ if ( !pSplit )
+ return 0;
-/*!
- SLOT: called on child is hidden
-*/
-void QtxWorkstackArea::onChildHided( QtxWorkstackChild* c )
-{
- setWidgetShown( c->widget(), false );
-}
+ bool upd = pSplit->updatesEnabled();
+ pSplit->setUpdatesEnabled( false );
-/*!
- SLOT: called on child is activated
-*/
-void QtxWorkstackArea::onChildActivated( QtxWorkstackChild* c )
-{
- setWidgetActive( c->widget() );
-}
+ QIntList szList = pSplit->sizes();
-/*!
- SLOT: called on child caption is changed
-*/
-void QtxWorkstackArea::onChildCaptionChanged( QtxWorkstackChild* c )
-{
- updateTab( c->widget() );
-}
+ QSplitter* wrap = new QSplitter( 0 );
+ wrap->setChildrenCollapsible( false );
+ pSplit->insertWidget( pSplit->indexOf( area ) + 1, wrap );
+ wrap->setVisible( true );
+ wrap->addWidget( area );
-/*!
- Raises widget when active tab is changed
-*/
-void QtxWorkstackArea::updateCurrent()
-{
- QMap<QWidget*, bool> map;
- for ( QWidgetListIt it( myList ); it.current(); ++it )
- {
- map.insert( it.current(), isBlocked( it.current() ) );
- setBlocked( it.current(), true );
- }
+ pSplit->setSizes( szList );
- myStack->raiseWidget( myBar->currentTab() );
+ pSplit->setUpdatesEnabled( upd );
- for ( QWidgetListIt itr( myList ); itr.current(); ++itr )
- setBlocked( itr.current(), map.contains( itr.current() ) ? map[itr.current()] : false );
+ return wrap;
}
/*!
- Updates tab
- \param wid - tab widget
+ \brief Reparent and add widget.
+ \param wid widget
+ \param pWid parent widget
+ \param after widget after which \a wid should be added
*/
-void QtxWorkstackArea::updateTab( QWidget* wid )
+void QtxWorkstack::insertWidget( QWidget* wid, QWidget* pWid, QWidget* after )
{
- QTab* tab = myBar->tab( widgetId( wid ) );
- if ( !tab )
+ if ( !wid || !pWid )
return;
- QIconSet icoSet;
- if ( wid->icon() )
+ QWidgetList moveList;
+ const QObjectList& lst = pWid->children();
+ bool found = false;
+ for ( QObjectList::const_iterator it = lst.begin(); it != lst.end(); ++it )
{
- QPixmap pix = *wid->icon();
- pix.convertFromImage( pix.convertToImage().smoothScale( pix.width(), 16, QImage::ScaleMin ) );
- icoSet = QIconSet( pix );
+ if ( found && ( (*it)->inherits( "QSplitter" ) ||
+ (*it)->inherits( "QtxWorkstackArea" ) ) )
+ moveList.append( (QWidget*)(*it) );
+ if ( *it == after )
+ found = true;
}
- tab->setIconSet( icoSet );
- tab->setText( wid->caption() );
-}
-
-/*!
- \return widget
- \param id - widget id
-*/
-QWidget* QtxWorkstackArea::widget( const int id ) const
-{
- QWidget* wid = 0;
- for ( WidgetInfoMap::ConstIterator it = myInfo.begin(); it != myInfo.end() && !wid; ++it )
+ QMap<QWidget*, bool> map;
+ for ( QWidgetList::iterator it = moveList.begin(); it != moveList.end(); ++it )
{
- if ( it.data().id == id )
- wid = it.key();
+ map.insert( *it, (*it)->isVisibleTo( (*it)->parentWidget() ) );
+ (*it)->setParent( 0 );
+ (*it)->hide();
}
- return wid;
-}
-/*!
- \return widget id
- \param wid - widget
-*/
-int QtxWorkstackArea::widgetId( QWidget* wid ) const
-{
- int id = -1;
- if ( myInfo.contains( wid ) )
- id = myInfo[wid].id;
- return id;
-}
+ wid->setParent( pWid );
-/*!
- \return true if widget is visible
- \param wid - widget
-*/
-bool QtxWorkstackArea::widgetVisibility( QWidget* wid ) const
-{
- bool res = false;
- if ( myInfo.contains( wid ) )
- res = myInfo[wid].vis;
- return res;
+ for ( QWidgetList::iterator itr = moveList.begin(); itr != moveList.end(); ++itr )
+ {
+ (*itr)->setParent( pWid );
+ (*itr)->setShown( map.contains( *itr ) ? map[*itr] : false );
+ }
}
/*!
- Sets widget as active
- \param wid - widget
+ \brief Close active window.
*/
-void QtxWorkstackArea::setWidgetActive( QWidget* wid )
+void QtxWorkstack::onCloseWindow()
{
- int id = widgetId( wid );
- if ( id < 0 )
- return;
-
- myBar->setCurrentTab( id );
+ if ( myWorkWin )
+ myWorkWin->close();
+ else if( activeWindow() )
+ activeWindow()->close();
}
/*!
- Shows/hides widget
- \param wid - widget
- \param on - new shown state
-*/
-void QtxWorkstackArea::setWidgetShown( QWidget* wid, const bool on )
-{
- if ( isBlocked( wid ) || !myInfo.contains( wid ) || myInfo[wid].vis == on )
- return;
+ \brief Called when workarea is destroyed.
- myInfo[wid].vis = on;
- updateState();
-}
+ Set input focus to the neighbour area.
-/*!
- Update
+ \param obj workarea being destroyed
*/
-void QtxWorkstackArea::updateState()
+void QtxWorkstack::onDestroyed( QObject* obj )
{
- bool updBar = myBar->isUpdatesEnabled();
- bool updStk = myStack->isUpdatesEnabled();
- myBar->setUpdatesEnabled( false );
- myStack->setUpdatesEnabled( false );
-
- bool block = myBar->signalsBlocked();
- myBar->blockSignals( true );
-
- QWidget* prev = activeWidget();
-
- int idx = 0;
- for ( QWidgetListIt it( myList ); it.current(); ++it )
- {
- QWidget* wid = it.current();
- int id = widgetId( wid );
-
- if ( id < 0 )
- continue;
-
- bool vis = widgetVisibility( wid );
+ QtxWorkstackArea* area = (QtxWorkstackArea*)obj;
- if ( myBar->tab( id ) && ( !vis || myBar->indexOf( id ) != idx ) )
- myBar->removeTab( myBar->tab( id ) );
+ if ( area == myArea )
+ myArea = 0;
- if ( !myBar->tab( id ) && vis )
- {
- QTab* tab = new QTab( wid->caption() );
- myBar->insertTab( tab, idx );
- tab->setIdentifier( id );
- }
+ if ( !myArea )
+ {
+ QtxWorkstackArea* cur = neighbourArea( area );
+ if ( cur )
+ cur->setFocus();
+ }
- updateTab( wid );
+ QApplication::postEvent( this, new QEvent( QEvent::User ) );
+}
- bool block = isBlocked( wid );
- setBlocked( wid, true );
+/*!
+ \brief Called on window activating.
+ \param area workarea being activated (not used)
+*/
+void QtxWorkstack::onWindowActivated( QWidget* /*area*/ )
+{
+ const QObject* obj = sender();
+ if ( !obj->inherits( "QtxWorkstackArea" ) )
+ return;
- QtxWorkstackChild* cont = child( wid );
+ setActiveArea( (QtxWorkstackArea*)obj );
+}
- if ( !vis )
- myStack->removeWidget( cont );
- else if ( !myStack->widget( id ) )
- myStack->addWidget( cont, id );
+/*!
+ \brief Called on window deactivating.
+ \param area workarea being deactivated
+*/
+void QtxWorkstack::onDeactivated( QtxWorkstackArea* area )
+{
+ if ( myArea != area )
+ return;
- if ( vis )
- idx++;
+ QList<QtxWorkstackArea*> lst;
+ areas( mySplit, lst, true );
- setBlocked( wid, block );
- }
+ int idx = lst.indexOf( area );
+ if ( idx == -1 )
+ return;
- int curId = widgetId( prev );
- if ( !myBar->tab( curId ) )
- {
- QWidget* wid = 0;
- int pos = myList.find( prev );
- for ( int i = pos - 1; i >= 0 && !wid; i-- )
- {
- if ( widgetVisibility( myList.at( i ) ) )
- wid = myList.at( i );
- }
+ myWin = 0;
+ myArea = 0;
- for ( int j = pos + 1; j < (int)myList.count() && !wid; j++ )
- {
- if ( widgetVisibility( myList.at( j ) ) )
- wid = myList.at( j );
- }
+ QtxWorkstackArea* newArea = neighbourArea( area );
+ if ( newArea && newArea->activeWidget() )
+ newArea->activeWidget()->setFocus();
- if ( wid )
- curId = widgetId( wid );
- }
+ QApplication::postEvent( this, new QEvent( QEvent::User ) );
+}
- myBar->setCurrentTab( curId );
+/*!
+ \brief Create and show popup menu for workarea.
+ \param w workarea
+ \param p popup position
+*/
+void QtxWorkstack::onContextMenuRequested( QWidget* w, QPoint p )
+{
+ QtxWorkstackArea* anArea = ::qobject_cast<QtxWorkstackArea*>( (QObject*)sender() );
+ if ( !anArea )
+ anArea = activeArea();
- myBar->blockSignals( block );
+ if ( !anArea )
+ return;
- updateCurrent();
+ QWidgetList lst = anArea->widgetList();
+ if ( lst.isEmpty() )
+ return;
- myBar->setUpdatesEnabled( updBar );
- myStack->setUpdatesEnabled( updStk );
- if ( updBar )
- myBar->update();
- if ( updStk )
- myStack->update();
+ myWorkWin = w;
+ myWorkArea = anArea;
- QResizeEvent re( myBar->size(), myBar->size() );
- QApplication::sendEvent( myBar, &re );
+ QMenu* pm = new QMenu();
- if ( isEmpty() )
+ if ( lst.count() > 1 )
{
- hide();
- emit deactivated( this );
+ if ( myActionsMap[SplitVertical]->isEnabled() )
+ pm->addAction( myActionsMap[SplitVertical] );
+ if ( myActionsMap[SplitHorizontal]->isEnabled() )
+ pm->addAction( myActionsMap[SplitHorizontal] );
+ pm->addSeparator();
}
- else
+
+ if ( w )
{
- show();
- if ( prev != activeWidget() )
- emit activated( activeWidget() );
+ if ( myActionsMap[Close]->isEnabled() )
+ pm->addAction( myActionsMap[Close] );
+ if ( myActionsMap[Rename]->isEnabled() )
+ pm->addAction( myActionsMap[Rename] );
}
-}
-/*!
- \return first unshared widget id
-*/
-int QtxWorkstackArea::generateId() const
-{
- QMap<int, int> map;
+ Qtx::simplifySeparators( pm );
- for ( WidgetInfoMap::ConstIterator it = myInfo.begin(); it != myInfo.end(); ++it )
- map.insert( it.data().id, 0 );
+ if ( !pm->actions().isEmpty() )
+ pm->exec( p );
- int id = 0;
- while ( map.contains( id ) )
- id++;
+ delete pm;
- return id;
+ myWorkWin = 0;
+ myWorkArea = 0;
}
/*!
- \return true if widget is blocked
- \param wid - widget
+ \brief Add child widget.
+ \param w widget
+ \param f widget flags
+ \return child widget container
*/
-bool QtxWorkstackArea::isBlocked( QWidget* wid ) const
+QWidget* QtxWorkstack::addWindow( QWidget* w, Qt::WindowFlags f )
{
- return myBlock.contains( wid );
+ if ( !w )
+ return 0;
+
+ return targetArea()->insertWidget( w, -1, f );
}
/*!
- Blocks widget
- \param wid - widget
- \param on - new blocked state
+ \brief Handle custom events.
+ \param e custom event (not used)
*/
-void QtxWorkstackArea::setBlocked( QWidget* wid, const bool on )
+void QtxWorkstack::customEvent( QEvent* /*e*/ )
{
- if ( on )
- myBlock.insert( wid, 0 );
- else
- myBlock.remove( wid );
+ updateState();
}
/*!
- \return child corresponding to widget
- \param wid - widget
+ \brief Get splitter corresponding to the workarea.
+ \param workarea
+ \return splitter corresponding to the workarea
*/
-QtxWorkstackChild* QtxWorkstackArea::child( QWidget* wid ) const
+QSplitter* QtxWorkstack::splitter( QtxWorkstackArea* area ) const
{
- QtxWorkstackChild* res = 0;
- if ( myChild.contains( wid ) )
- res = myChild[wid];
- return res;
+ if ( !area )
+ return 0;
+
+ QSplitter* split = 0;
+
+ QWidget* wid = area->parentWidget();
+ if ( wid && wid->inherits( "QSplitter" ) )
+ split = (QSplitter*)wid;
+
+ return split;
}
/*!
- Constructor
+ \brief Get list of child splitters.
+ \param split parent splitter
+ \param splitList list to be filled with child splitters
+ \param rec if \c true, perform recursive search of children
*/
-QtxWorkstackChild::QtxWorkstackChild( QWidget* wid, QWidget* parent )
-: QHBox( parent ),
-myWidget( wid )
+void QtxWorkstack::splitters( QSplitter* split, QList<QSplitter*>& splitList, const bool rec ) const
{
- myWidget->reparent( this, QPoint( 0, 0 ), myWidget->isVisibleTo( myWidget->parentWidget() ) );
- myWidget->installEventFilter( this );
+ if ( !split )
+ return;
- connect( myWidget, SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
+ const QObjectList& objs = split->children();
+ for ( QObjectList::const_iterator it = objs.begin(); it != objs.end(); ++it )
+ {
+ if ( rec )
+ splitters( (QSplitter*)*it, splitList, rec );
+ if ( (*it)->inherits( "QSplitter" ) )
+ splitList.append( (QSplitter*)*it );
+ }
}
/*!
- Destructor
+ \brief Get list of child workareas.
+ \param split parent splitter
+ \param areaList list to be filled with child workareas
+ \param rec if \c true, perform recursive search of children
*/
-QtxWorkstackChild::~QtxWorkstackChild()
+void QtxWorkstack::areas( QSplitter* split, QList<QtxWorkstackArea*>& areaList, const bool rec ) const
{
- qApp->removeEventFilter( this );
-
- if ( !widget() )
+ if ( !split )
return;
- widget()->removeEventFilter( this );
- widget()->reparent( 0, QPoint( 0, 0 ), false );
- disconnect( widget(), SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
+ const QObjectList& objs = split->children();
+ for ( QObjectList::const_iterator it = objs.begin(); it != objs.end(); ++it )
+ {
+ if ( (*it)->inherits( "QtxWorkstackArea" ) )
+ areaList.append( (QtxWorkstackArea*)*it );
+ else if ( rec && (*it)->inherits( "QSplitter" ) )
+ areas( (QSplitter*)*it, areaList, rec );
+ }
}
/*!
- \return corresponding widget
+ \brief Get active workarea.
+ \return active workarea
*/
-QWidget* QtxWorkstackChild::widget() const
+QtxWorkstackArea* QtxWorkstack::activeArea() const
{
- return myWidget;
+ return myArea;
}
/*!
- Custom event filter
+ \brief Get target area (for which the current operation should be done).
+
+ Returns active workarea or current area (if there is no active workarea).
+ If there are no workareas, create new workarea and return it.
+
+ \return workarea
*/
-bool QtxWorkstackChild::eventFilter( QObject* o, QEvent* e )
+QtxWorkstackArea* QtxWorkstack::targetArea()
{
- if ( o->isWidgetType() )
+ QtxWorkstackArea* area = activeArea();
+ if ( !area )
+ area = currentArea();
+ if ( !area )
{
- if ( e->type() == QEvent::CaptionChange || e->type() == QEvent::IconChange )
- emit captionChanged( this );
-
- if ( !e->spontaneous() && ( e->type() == QEvent::Show || e->type() == QEvent::ShowToParent ) )
- emit shown( this );
+ QList<QtxWorkstackArea*> lst;
+ areas( mySplit, lst );
+ if ( !lst.isEmpty() )
+ area = lst.first();
+ }
- if ( !e->spontaneous() && ( e->type() == QEvent::Hide || e->type() == QEvent::HideToParent ) )
- emit hided( this );
+ if ( !area )
+ area = createArea( mySplit );
- if ( e->type() == QEvent::FocusIn )
- emit activated( this );
- }
- return QHBox::eventFilter( o, e );
+ return area;
}
/*!
- SLOT: called on object is destroyed
-*/
-void QtxWorkstackChild::onDestroyed( QObject* obj )
-{
- if ( obj != widget() )
- return;
+ \brief Get current workarea.
- myWidget = 0;
- deleteLater();
-}
+ Current workarea is that one which has input focus.
-/*!
- Custom child event handler
+ \return current area
*/
-void QtxWorkstackChild::childEvent( QChildEvent* e )
+QtxWorkstackArea* QtxWorkstack::currentArea() const
{
- if ( e->type() == QEvent::ChildRemoved && e->child() == widget() )
+ QtxWorkstackArea* area = 0;
+ QWidget* wid = focusWidget();
+ while ( wid && !area )
{
- myWidget = 0;
- deleteLater();
+ if ( wid->inherits( "QtxWorkstackArea" ) )
+ area = (QtxWorkstackArea*)wid;
+ wid = wid->parentWidget();
}
- QHBox::childEvent( e );
+
+ return area;
}
/*!
- Constructor
+ \brief Create new workarea.
+ \param parent parent widget
+ \return created workarea
*/
-QtxWorkstackTabBar::QtxWorkstackTabBar( QWidget* parent )
-: QTabBar( parent ),
-myId( -1 )
+QtxWorkstackArea* QtxWorkstack::createArea( QWidget* parent ) const
{
+ QtxWorkstackArea* area = new QtxWorkstackArea( parent );
+
+ connect( area, SIGNAL( destroyed( QObject* ) ), this, SLOT( onDestroyed( QObject* ) ) );
+ connect( area, SIGNAL( activated( QWidget* ) ), this, SLOT( onWindowActivated( QWidget* ) ) );
+ connect( area, SIGNAL( contextMenuRequested( QWidget*, QPoint ) ),
+ this, SLOT( onContextMenuRequested( QWidget*, QPoint ) ) );
+ connect( area, SIGNAL( deactivated( QtxWorkstackArea* ) ), this, SLOT( onDeactivated( QtxWorkstackArea* ) ) );
+
+ return area;
}
/*!
- Destructor
+ \brief Set active workarea.
+ \param workarea
*/
-QtxWorkstackTabBar::~QtxWorkstackTabBar()
+void QtxWorkstack::setActiveArea( QtxWorkstackArea* area )
{
+ QWidget* oldCur = myWin;
+
+ QtxWorkstackArea* oldArea = myArea;
+
+ myArea = area;
+
+ if ( myArea != oldArea )
+ {
+ if ( oldArea )
+ oldArea->updateActiveState();
+ if ( myArea )
+ myArea->updateActiveState();
+ }
+
+ if ( myArea )
+ myWin = myArea->activeWidget();
+
+ if ( myWin && oldCur != myWin )
+ emit windowActivated( myWin );
}
/*!
- Sets tab bar as active or inactive
- \param on - new active state
+ \brief Get workarea which is nearest to \a area.
+ \param area area for which neighbour is searched
+ \return neighbour area (or 0 if not found)
*/
-void QtxWorkstackTabBar::setActive( const bool on )
+QtxWorkstackArea* QtxWorkstack::neighbourArea( QtxWorkstackArea* area ) const
{
- QFont aFont = font();
- aFont.setUnderline( on );
- QColorGroup aColGrp;
- QPalette aPal = palette();
- if ( !on ) {
- aPal.setColor( QColorGroup::HighlightedText, aColGrp.foreground() );
- aPal.setColor( QColorGroup::Highlight, colorGroup().dark().light( DARK_COLOR_LIGHT ) );
- setPalette( aPal );
+ QList<QtxWorkstackArea*> lst;
+ areas( mySplit, lst, true );
+ int pos = lst.indexOf( area );
+ if ( pos < 0 )
+ return 0;
+
+ QtxWorkstackArea* na = 0;
+ for ( int i = pos - 1; i >= 0 && !na; i-- )
+ {
+ if ( !lst.at( i )->isEmpty() )
+ na = lst.at( i );
}
- else {
- aPal.setColor( QColorGroup::HighlightedText, aColGrp.highlightedText() );
- aPal.setColor( QColorGroup::Highlight, aColGrp.highlight() );
- unsetPalette();
+
+ for ( int j = pos + 1; j < (int)lst.count() && !na; j++ )
+ {
+ if ( !lst.at( j )->isEmpty() )
+ na = lst.at( j );
}
- setFont( aFont );
+ return na;
+}
- update();
+/*!
+ \brief Get workarea covering point.
+ \return workarea
+ \param p point
+*/
+QtxWorkstackArea* QtxWorkstack::areaAt( const QPoint& p ) const
+{
+ QtxWorkstackArea* area = 0;
+ QList<QtxWorkstackArea*> lst;
+ areas( mySplit, lst, true );
+ for ( QList<QtxWorkstackArea*>::iterator it = lst.begin(); it != lst.end() && !area; ++it )
+ {
+ QtxWorkstackArea* cur = *it;
+ QRect r = cur->geometry();
+ if ( cur->parentWidget() )
+ r = QRect( cur->parentWidget()->mapToGlobal( r.topLeft() ), r.size() );
+ if ( r.contains( p ) )
+ area = cur;
+ }
+ return area;
}
/*!
- \return tab rectangle
- \param idx - tab index
+ \brief Update internal state.
*/
-QRect QtxWorkstackTabBar::tabRect( const int idx ) const
+void QtxWorkstack::updateState()
{
- QRect r;
- QTab* t = tabAt( idx );
- if ( t )
- {
- r = t->rect();
- r.setLeft( QMAX( r.left(), 0 ) );
-
- int x1 = tabAt( 0 )->rect().left();
- int x2 = tabAt( count() - 1 )->rect().right();
-
- int bw = 0;
- if ( QABS( x2 - x1 ) > width() )
-#if defined QT_VERSION && QT_VERSION >= 0x30300
- bw = 2 * style().pixelMetric( QStyle::PM_TabBarScrollButtonWidth, this );
-#else
- bw = 2 * 16;
-#endif
-
- int limit = width() - bw;
- r.setRight( QMIN( r.right(), limit ) );
-
- r = QRect( mapToGlobal( r.topLeft() ), r.size() );
- }
- return r;
+ updateState( mySplit );
}
/*!
- Custom mouse move event handler
+ \brief Update splitter state.
+ \param split splitter to be updated
*/
-void QtxWorkstackTabBar::mouseMoveEvent( QMouseEvent* e )
+void QtxWorkstack::updateState( QSplitter* split )
{
- if ( myId != -1 && !tab( myId )->rect().contains( e->pos() ) )
+ QList<QSplitter*> recList;
+ splitters( split, recList, false );
+ for ( QList<QSplitter*>::iterator itr = recList.begin(); itr != recList.end(); ++itr )
+ updateState( *itr );
+
+ QList<QSplitter*> splitList;
+ splitters( split, splitList, false );
+
+ QList<QtxWorkstackArea*> areaList;
+ areas( split, areaList, false );
+
+ bool vis = false;
+ for ( QList<QtxWorkstackArea*>::iterator it = areaList.begin(); it != areaList.end(); ++it )
{
- myId = -1;
- emit dragActiveTab();
+ if ( (*it)->isEmpty() )
+ (*it)->hide();
+ else
+ {
+ (*it)->show();
+ vis = true;
+ }
}
- QTabBar::mouseMoveEvent( e );
-}
+ if ( split == mySplit )
+ return;
-/*!
- Custom mouse press event handler
-*/
-void QtxWorkstackTabBar::mousePressEvent( QMouseEvent* e )
-{
- QTabBar::mousePressEvent( e );
+ for ( QList<QSplitter*>::iterator iter = splitList.begin(); iter != splitList.end() && !vis; ++iter )
+ vis = (*iter)->isVisibleTo( (*iter)->parentWidget() );
- if ( e->button() == LeftButton )
- myId = currentTab();
+ if ( areaList.isEmpty() && splitList.isEmpty() )
+ delete split;
+ else if ( vis )
+ split->show();
+ else
+ split->hide();
}
/*!
- Custom mouse release event handler
+ \brief Get splitter info (for debug purposes)
+ \param split splitter
+ \param info string to be filled with splitter data.
*/
-void QtxWorkstackTabBar::mouseReleaseEvent( QMouseEvent* e )
+void QtxWorkstack::splitterInfo( QSplitter* split, QString& info ) const
{
- QTabBar::mouseReleaseEvent( e );
+ if ( !split )
+ return;
- myId = -1;
+ const QObjectList& objs = split->children();
- if ( e->button() == RightButton )
- emit contextMenuRequested( e->globalPos() );
+ QString sizesStr;
+ QList<int> sizes = split->sizes();
+ for ( QList<int>::iterator sIt = sizes.begin(); sIt != sizes.end(); ++sIt )
+ {
+ if ( *sIt > 1 ) // size 1 pixel usually means empty Workstack area, which will NOT be re-created,
+ sizesStr += QString( ":%1" ).arg( *sIt ); // so we don't need to store its size
+ }
+
+ if ( !sizesStr.isEmpty() ) // cut the first ':'
+ sizesStr = sizesStr.right( sizesStr.length() - 1 );
+
+ info += QString( "(splitter orientation=%1 sizes=%3 " ).arg( split->orientation() ).arg( sizesStr );
+
+ for ( QObjectList::const_iterator it = objs.begin(); it != objs.end(); ++it )
+ {
+ if ( (*it)->inherits( "QSplitter" ) )
+ splitterInfo( (QSplitter*)*it, info );
+ else if ( (*it)->inherits( "QtxWorkstackArea" ) )
+ {
+ QtxWorkstackArea* area = (QtxWorkstackArea*)*it;
+ if ( area->isEmpty() )
+ continue;
+ info += QString( "(views active='%1'" ).arg( area->activeWidget()->objectName() );
+ QWidgetList views = area->widgetList();
+ for ( QWidgetList::iterator wIt = views.begin(); wIt != views.end(); ++wIt )
+ info += QString( " '%1'" ).arg( (*wIt)->objectName() );
+ info += ')';
+ }
+ }
+
+ info += ')';
+ printf( (const char*)QString( info + '\n' ).toLatin1() );
}
/*!
- Custom context menu event handler
+ \brief Remove round brackets symbols from the string.
+ \internal
+ \param parameters string to be processed
*/
-void QtxWorkstackTabBar::contextMenuEvent( QContextMenuEvent* e )
+static void cutBrackets( QString& parameters )
{
- if ( e->reason() != QContextMenuEvent::Mouse )
- emit contextMenuRequested( e->globalPos() );
+ QChar c1 = parameters[0];
+ QChar c2 = parameters[int(parameters.length()-1)];
+ if ( !parameters.isEmpty() && c1 == '(' && c2 == ')' )
+ parameters = parameters.mid( 1, parameters.length()-2 );
}
/*!
- Draws label of tab bar
+ \brief Parse string to get some parameter value.
+ \internal
+
+ String \a str can contain the parameters description of kind "<param>=<value> ...".
+ For example:
+ \code
+ QString s = "splitter orientation=0 children=2 sizes=332:478";
+ QString orient_val = getValue( s, "children" ); // orient_val contains "2"
+ QString size_val = getValue( s, "sizes" ); // val contains "332:478"
+ \endcode
+
+ \param str string to be processed
+ \param valName parameter name
+ \return parameter value (or null QStrinhg if parameter is not found)
*/
-void QtxWorkstackTabBar::paintLabel( QPainter* p, const QRect& br, QTab* t, bool has_focus ) const
+static QString getValue( const QString& str, const QString& valName )
{
- if ( currentTab() != t->identifier() )
+ int i = str.indexOf( valName );
+ if ( i != -1 )
{
- QFont fnt = p->font();
- fnt.setUnderline( false );
- p->setFont( fnt );
+ int equal_i = str.indexOf( '=', i );
+ if ( equal_i != -1 )
+ {
+ int space_i = str.indexOf( ' ', ++equal_i );
+ if ( space_i != -1 )
+ return str.mid( equal_i, space_i - equal_i );
+ }
}
- QTabBar::paintLabel( p, br, t, has_focus );
+ return QString();
}
/*!
- Constructor
+ \brief Check format of splitter parameters string.
+ \internal
+ \param parameters splitter parameters description
+ \return \c true on success and \c false on error
*/
-QtxWorkstackDrag::QtxWorkstackDrag( QtxWorkstack* ws, QtxWorkstackChild* child )
-: QObject( 0 ),
-myWS( ws ),
-myTab( -1 ),
-myArea( 0 ),
-myPainter( 0 ),
-myChild( child )
+static bool checkFormat( const QString& parameters )
{
- qApp->installEventFilter( this );
+ QString params( parameters );
+ // 1. begins and ends with brackets
+ QChar c1 = params[0];
+ QChar c2 = params[int(params.length()-1)];
+ bool ok = ( c1 == '(' && c2 == ')' );
+ if ( !ok ) return ok;
+ ::cutBrackets( params );
+ // 2. has splitter word
+ ok = ( params.left( 8 ) == "splitter" );
+ if ( !ok ) return ok;
+ // 3. has children? = '(' is found
+ int i = params.indexOf( '(' );
+ ok = i != -1;
+ if ( !ok ) return ok;
+ params = params.left( i ); // cut all children, they will be checked later
+ // 4. has orientation word and correct value
+ ::getValue( params, "orientation" ).toInt( &ok );
+ if ( !ok ) return ok;
+ // 5. has sizes word and values
+ ok = ! ::getValue( params, "sizes" ).isEmpty();
+ if ( !ok ) return ok;
+ // 6. check children -> number of '(' == number of ')' in original string
+ ok = ( parameters.contains( '(' ) == parameters.contains( ')' ) );
+ return ok;
}
/*!
- Destructor
+ \brief Get splitter's children descriptions from the string.
+ \internal
+
+ Child widgets descriptions are separated by '(' and ')' symbols.
+
+ \param str string to be processed
+ \return child widgets descriptions
*/
-QtxWorkstackDrag::~QtxWorkstackDrag()
+static QStringList getChildren( const QString& str )
{
- qApp->removeEventFilter( this );
+ QStringList lst;
+ if ( !str.startsWith( "(" ) )
+ return lst;
- endDrawRect();
+ int i = 1,
+ nOpen = 1, // count brackets: '(' increments nOpen, ')' decrements
+ start = 0;
+ while ( i < (int)str.length() )
+ {
+ if ( str[i] == '(' )
+ {
+ nOpen++;
+ if ( nOpen == 1 )
+ start = i;
+ }
+ else if ( str[i] == ')' )
+ {
+ nOpen--;
+ if ( nOpen == 0 )
+ lst.append( str.mid( start, i-start+1 ) );
+ }
+ i++;
+ }
+
+ return lst;
}
/*!
- Custom event filter
+ \brief Get view name by index.
+ \internal
+
+ Example:
+ \code
+ QString s = "views active='AnotherView' 'GLView' 'AnotherView'";
+ QString a0 = getViewName( s, 0 ); // --> a0 contains "GLView"
+ QString a1 = getViewName( s, 1 ); // --> a1 contains "AnotherView"
+ \endcode
+
+ \param str string to be processed
+ \param i index
+ \return view name
*/
-bool QtxWorkstackDrag::eventFilter( QObject*, QEvent* e )
+static QString getViewName( const QString& str, int i )
{
- switch ( e->type() )
+ QRegExp exp( "\\s'\\w+'" );
+ int start = 0; // start index of view name in the string
+ int num = 0 ; // index of found match
+ while ( ( start = exp.indexIn( str, start ) ) != -1 && num < i )
{
- case QEvent::MouseMove:
- updateTarget( ((QMouseEvent*)e)->globalPos() );
- break;
- case QEvent::MouseButtonRelease:
- drawRect();
- endDrawRect();
- dropWidget();
- deleteLater();
- break;
- default:
- return false;
+ start += exp.matchedLength();
+ num ++;
}
- return true;
-}
+ if ( start != -1 ) // +2 and -3 avoid starting space and starting and ending ' symbols
+ return str.mid( start + 2, exp.matchedLength() - 3 );
-/*!
- Updates internal field with widget-target for dropping
- \param p - current point of dragging
-*/
-void QtxWorkstackDrag::updateTarget( const QPoint& p )
-{
- int tab = -1;
- QtxWorkstackArea* area = detectTarget( p, tab );
- setTarget( area, tab );
+ return QString();
}
/*!
- \return target area for dropping by point
- \param p - current point of dragging
- \param tab - index of tab to dropping
+ \brief Get child widget with specified name.
+ \internal
+ \param parent parent widget
+ \param aName child widget name
+ \return child widget or 0 if not found
*/
-QtxWorkstackArea* QtxWorkstackDrag::detectTarget( const QPoint& p, int& tab ) const
+static QWidget* getView( const QWidget* parent, const QString& aName )
{
- if ( p.isNull() )
- return 0;
-
- QtxWorkstackArea* area = myWS->areaAt( p );
- if ( area )
- tab = area->tabAt( p );
- return area;
+ QWidget* view = 0;
+ QList<QWidget*> l = qFindChildren<QWidget*>( parent->topLevelWidget(), aName );
+ if ( !l.isEmpty() )
+ view = ::qobject_cast<QWidget*>( l.first() );
+ return view;
}
/*!
- Changes target area for dropping
- \param area - new target area
- \param tab - tab index
+ \brief Setup splitter according to the specified parameters string.
+ \param splitter splitter to be set up
+ \param parameters splitter parameters description
+ \param sMap map containing resulting child splitters sizes
*/
-void QtxWorkstackDrag::setTarget( QtxWorkstackArea* area, const int tab )
+void QtxWorkstack::setSplitter( QSplitter* splitter, const QString& parameters, QMap<QSplitter*, QList<int> >& sMap )
{
- if ( !area || ( myArea == area && tab == myTab ) )
+ printf( QString( parameters + '\n' ).toLatin1() );
+ if ( !::checkFormat( parameters ) ) {
+ printf( "\nInvalid format of workstack parameters. Positions of viewers can not be restored.\n" );
return;
+ }
- startDrawRect();
+ QString params( parameters );
+ ::cutBrackets( params );
- if ( myArea )
- drawRect();
+ // get splitter sizes and store it in the map for future setting
+ QList<int> sizes;
+ QStringList sizesLst = ::getValue( params, "sizes" ).split( ':', QString::SkipEmptyParts );
+ QStringList::Iterator it;
+ for ( it = sizesLst.begin(); it != sizesLst.end(); ++it )
+ sizes.append( (*it).toInt() );
+ sMap[ splitter ] = sizes;
- myTab = tab;
- myArea = area;
+ // set orientation of splitter
+ int orient = ::getValue( params, "orientation" ).toInt();
+ splitter->setOrientation( (Qt::Orientation)orient );
- if ( myArea )
- drawRect();
-}
+ // get children
+ QString options = params.left( params.indexOf( '(' ) );
+ QString childrenStr = params.right( params.length()-options.length() );
+ QStringList children = ::getChildren( childrenStr );
-/*!
- Called on widget drop, inserts dropped widget to area
-*/
-void QtxWorkstackDrag::dropWidget()
-{
- if ( myArea )
- myArea->insertWidget( myChild->widget(), myTab );
+ // debug output..
+ // printf (" splitter orient=%d, sizes_count=%d, children=%d\n", orient, sizes.count(), children.count() );
+ // for ( QStringList::Iterator tit = children.begin(); tit != children.end(); ++tit )
+ // printf (" |-> child = [%s]\n", (*tit).latin1() );
+
+ for ( it = children.begin(); it != children.end(); ++it )
+ {
+ if ( (*it).startsWith( "(splitter" ) )
+ {
+ QSplitter* newSplitter = new QSplitter( splitter );
+ setSplitter( newSplitter, *it, sMap );
+ }
+ else if ( (*it).startsWith( "(views" ) )
+ {
+ QtxWorkstackArea* newArea = createArea( splitter );
+ QString activeViewName = ::getValue( *it, "active" );
+ QWidget* activeView = 0;
+ activeViewName = activeViewName.mid( 1, activeViewName.length()-2 ); // chop off ' symbols
+ int i = 0;
+ QString viewName = ::getViewName( *it, i );
+ while ( !viewName.isEmpty() )
+ {
+ if ( QWidget* view = ::getView( splitter, viewName ) )
+ {
+ newArea->insertWidget( view );
+ if ( activeViewName == view->objectName() )
+ activeView = view;
+ }
+ viewName = ::getViewName( *it, ++i );
+ }
+ if ( activeView )
+ newArea->setActiveWidget( activeView );
+ }
+ }
}
/*!
- Draws float rect
+ \brief Restore workstack configuration from the state description string.
+ \param parameters workstack state description
+ \return reference to this workstack
*/
-void QtxWorkstackDrag::drawRect()
+QtxWorkstack& QtxWorkstack::operator<<( const QString& parameters )
{
- if ( !myPainter || !myArea )
- return;
+ // clear the main splitter - remove all child splitters and empty areas from it
+ QList<QSplitter*> splitList;
+ QList<QtxWorkstackArea*> areaList;
+ splitters( mySplit, splitList, false );
+ areas( mySplit, areaList, false );
+ for ( QList<QSplitter*>::iterator iter = splitList.begin(); iter != splitList.end(); ++iter )
+ delete *iter;
- QRect r = myArea->floatRect();
- int m = myPainter->pen().width();
+ for ( QList<QtxWorkstackArea*>::iterator it = areaList.begin(); it != areaList.end(); ++it )
+ {
+ if ( (*it)->isEmpty() )
+ delete *it;
+ }
- r.setTop( r.top() + m + 2 );
- r.setLeft( r.left() + m + 2 );
- r.setRight( r.right() - m - 2 );
- r.setBottom( r.bottom() - m - 2 );
+ // restore splitter recursively
+ QMap< QSplitter*, QList<int> > sMap;
+ setSplitter( mySplit, parameters, sMap );
- myPainter->drawRect( r );
+ // now mySplit may contains empty area (where all views were located before restoring)
+ // in order setSize to work correctly we have to exclude this area
+ areaList.clear();
+ areas( mySplit, areaList, false );
+ for ( QList<QtxWorkstackArea*>::iterator delIt = areaList.begin(); delIt != areaList.end(); ++delIt )
+ {
+ if ( (*delIt)->isEmpty() )
+ delete *delIt;
+ }
- QRect tr = myArea->floatTab( myTab );
- tr.setTop( tr.top() + m );
- tr.setLeft( tr.left() + m );
- tr.setRight( tr.right() - m );
- tr.setBottom( tr.bottom() - m );
+ QApplication::instance()->processEvents();
+
+ // restore splitters' sizes (map of sizes is filled in setSplitters)
+ for ( QMap< QSplitter*, QList<int> >::iterator itm = sMap.begin(); itm != sMap.end(); ++itm )
+ itm.key()->setSizes( itm.value() );
- myPainter->drawRect( tr );
+ return (*this);
}
/*!
- Deletes internal painter
+ \brief Dump workstack configuration to the state description string.
+ \param parameters resulting workstack state description
+ \return reference to this workstack
*/
-void QtxWorkstackDrag::endDrawRect()
+QtxWorkstack& QtxWorkstack::operator>>( QString& outParameters )
{
- delete myPainter;
- myPainter = 0;
+ splitterInfo( mySplit, outParameters );
+ return (*this);
}
/*!
- Initialize internal painter
+ \fn void QtxWorkstack::windowActivated( QWidget* w )
+ \brief Emitted when the workstack's child widget \w is activated.
+ \param w widget being activated
*/
-void QtxWorkstackDrag::startDrawRect()
-{
- if ( myPainter )
- return;
-
- int scr = QApplication::desktop()->screenNumber( (QWidget*)this );
- QWidget* paint_on = QApplication::desktop()->screen( scr );
-
- myPainter = new QPainter( paint_on, true );
- myPainter->setPen( QPen( gray, 3 ) );
- myPainter->setRasterOp( XorROP );
-}
#include "Qtx.h"
-#include <qhbox.h>
-#include <qwidget.h>
-#include <qtabbar.h>
-#include <qwidgetlist.h>
+#include <QWidget>
+#include <QFrame>
+#include <QTabBar>
+#include <QEvent>
+#include <QMap>
class QAction;
-class QTabBar;
-class QPainter;
class QSplitter;
class QPushButton;
-class QWidgetStack;
+class QStackedWidget;
+class QRubberBand;
class QtxWorkstackArea;
class QtxWorkstackDrag;
Q_OBJECT
public:
- enum { SplitVertical, SplitHorizontal, Close, Rename };
+ //! Workstack actions (context menu items)
+ enum { SplitVertical = 0x01, //!< "Split vertically" menu item
+ SplitHorizontal = 0x02, //!< "Split horizontally" menu item
+ Close = 0x04, //!< "Close" menu item
+ Rename = 0x08, //!< "Rename" menu item
+ All = SplitVertical | SplitHorizontal |
+ Close | Rename //!< all menu items
+ };
+ //! Workstack splitting type
enum SplitType
{
- SPLIT_STAY, //!< given widget stays in its workarea, others are moved into a new one
- SPLIT_AT, //!< widgets before a given widget stays in they workarea, others are moved into a new one
- SPLIT_MOVE //!< given widget is moved into a new workarea, others stay in an old one
+ SplitStay, //!< selected widget stays in current workarea, others widgets are moved into a new workarea
+ SplitAt, //!< all widgets before selected widget stay in current workarea, other widgess are moved into a new workarea
+ SplitMove //!< selected widget is moved into a new workarea, all other widgets stay in an old workarea
};
public:
int accel( const int ) const;
void setAccel( const int, const int );
+ void setMenuActions( const int );
+ int menuActions() const;
+
void split( const int );
- // STV: Useless function. wid->setFocus() should be used instead.
- // void OnTop( QWidget* wid);
+ QWidget* addWindow( QWidget*, Qt::WindowFlags = 0 );
void Split( QWidget* wid, const Qt::Orientation o, const SplitType type );
void Attract( QWidget* wid1, QWidget* wid2, const bool all );
void onDeactivated( QtxWorkstackArea* );
protected:
- virtual void childEvent( QChildEvent* );
- virtual void customEvent( QCustomEvent* );
+ virtual void customEvent( QEvent* );
private:
QSplitter* splitter( QtxWorkstackArea* ) const;
- void splitters( QSplitter*, QPtrList<QSplitter>&, const bool = false ) const;
- void areas( QSplitter*, QPtrList<QtxWorkstackArea>&, const bool = false ) const;
+ void splitters( QSplitter*, QList<QSplitter*>&, const bool = false ) const;
+ void areas( QSplitter*, QList<QtxWorkstackArea*>&, const bool = false ) const;
QSplitter* wrapSplitter( QtxWorkstackArea* );
void insertWidget( QWidget*, QWidget*, QWidget* );
const int need_pos, const int splitter_pos );
void splitterInfo( QSplitter*, QString& ) const;
- void setSplitter( QSplitter*, const QString&, QMap< QSplitter*,QValueList<int> >& );
+ void setSplitter( QSplitter*, const QString&, QMap< QSplitter*, QList<int> >& );
private:
- QWidget* myWin;
- QtxWorkstackArea* myArea;
- QSplitter* mySplit;
- QWidget* myWorkWin;
- QtxWorkstackArea* myWorkArea;
+ QWidget* myWin; //!< active widget
+ QtxWorkstackArea* myArea; //!< active workarea
+ QSplitter* mySplit; //!< tol-level splitter
+ QWidget* myWorkWin; //!< widget where popup menu is invoked (used internally)
+ QtxWorkstackArea* myWorkArea; //!< workarea where popup menu is invoked (used internally)
- QMap<int, QAction*> myActionsMap; //!< The map of the actions. Allows to get the QAction object by the key.
+ QMap<int, QAction*> myActionsMap; //!< actions map
friend class QtxWorkstackArea;
friend class QtxWorkstackDrag;
};
-class QtxWorkstackArea : public QWidget
+class QtxWorkstackArea : public QFrame
{
Q_OBJECT
+ class WidgetEvent;
+
public:
QtxWorkstackArea( QWidget* );
virtual ~QtxWorkstackArea();
bool isEmpty() const;
- void insertWidget( QWidget*, const int = -1 );
+ QWidget* insertWidget( QWidget*, const int = -1, Qt::WindowFlags = 0 );
void removeWidget( QWidget*, const bool = true );
QWidget* activeWidget() const;
void deactivated( QtxWorkstackArea* );
public slots:
- virtual void show();
- virtual void hide();
+ virtual void setVisible( bool );
private slots:
void onClose();
- void onSelected( int );
+ void onCurrentChanged( int );
void onWidgetDestroyed();
void onChildDestroyed( QObject* );
void onChildShown( QtxWorkstackChild* );
- void onChildHided( QtxWorkstackChild* );
+ void onChildHidden( QtxWorkstackChild* );
void onChildActivated( QtxWorkstackChild* );
void onChildCaptionChanged( QtxWorkstackChild* );
void onContextMenuRequested( QPoint );
protected:
- virtual void customEvent( QCustomEvent* );
+ virtual void customEvent( QEvent* );
virtual void focusInEvent( QFocusEvent* );
virtual void mousePressEvent( QMouseEvent* );
private:
- enum { ActivateWidget = QEvent::User, FocusWidget, RemoveWidget };
+ //! Custom events
+ enum { ActivateWidget = QEvent::User, //!< activate widget event
+ FocusWidget, //!< focus receiving widget event
+ RemoveWidget //!< widget removing event
+ };
private:
void updateState();
typedef QMap<QWidget*, WidgetInfo> WidgetInfoMap;
private:
- QtxWorkstackTabBar* myBar;
- QPushButton* myClose;
- QWidgetStack* myStack;
-
- QWidgetList myList;
- WidgetInfoMap myInfo;
- ChildMap myChild;
- BlockMap myBlock;
+ QtxWorkstackTabBar* myBar; //!< workarea tab bar header
+ QPushButton* myClose; //!< close button
+ QStackedWidget* myStack; //!< widget stack
+
+ QWidgetList myList; //!< child widgets list
+ WidgetInfoMap myInfo; //!< widgets states mp
+ ChildMap myChild; //!< child widget containers map
+ BlockMap myBlock; //!< blocked widgets
};
-class QtxWorkstackChild : public QHBox
+class QtxWorkstackChild : public QWidget
{
Q_OBJECT
public:
- QtxWorkstackChild( QWidget*, QWidget* = 0 );
+ QtxWorkstackChild( QWidget*, QWidget* = 0, Qt::WindowFlags = 0 );
virtual ~QtxWorkstackChild();
QWidget* widget() const;
signals:
void shown( QtxWorkstackChild* );
- void hided( QtxWorkstackChild* );
+ void hidden( QtxWorkstackChild* );
void activated( QtxWorkstackChild* );
void captionChanged( QtxWorkstackChild* );
virtual void childEvent( QChildEvent* );
private:
- QWidget* myWidget;
+ QWidget* myWidget; //!< child widget
};
class QtxWorkstackTabBar : public QTabBar
QtxWorkstackTabBar( QWidget* = 0 );
virtual ~QtxWorkstackTabBar();
- QRect tabRect( const int ) const;
-
+ bool isActive() const;
void setActive( const bool );
+ int tabId( const int ) const;
+ int indexOf( const int ) const;
+ void setTabId( const int, const int );
+
+ void updateActiveState();
+
signals:
void dragActiveTab();
void contextMenuRequested( QPoint );
+private slots:
+ void onCurrentChanged( int );
+
protected:
virtual void mouseMoveEvent( QMouseEvent* );
virtual void mousePressEvent( QMouseEvent* );
virtual void mouseReleaseEvent( QMouseEvent* );
virtual void contextMenuEvent( QContextMenuEvent* );
- virtual void paintLabel( QPainter*, const QRect&, QTab*, bool ) const;
+// virtual void paintLabel( QPainter*, const QRect&, QTab*, bool ) const;
private:
- int myId;
+ int myId; //!< current tab page index
+ bool myActive; //!< "active" status
};
class QtxWorkstackDrag : public QObject
void startDrawRect();
private:
- QtxWorkstack* myWS;
- QtxWorkstackChild* myChild;
+ QtxWorkstack* myWS; //!< parent workstack
+ QtxWorkstackChild* myChild; //!< workstack child widget container
- int myTab;
- QtxWorkstackArea* myArea;
- QPainter* myPainter;
-
+ int myTab; //!< workarea tab page index
+ QtxWorkstackArea* myArea; //!< workarea
+ QRubberBand* myTabRect; //!< tab bar rubber band
+ QRubberBand* myAreaRect; //!< workarea rubber band
};
#ifdef WIN32
#pragma warning( default:4251 )
#endif
-#endif
+#endif // QTXWORKSTACK_H
#include "QtxWorkstack.h"
-#include <qpopupmenu.h>
-#include <qwidgetlist.h>
+#include <QMenu>
+#include <QWidgetList>
/*!
- Constructor
+ \class QtxWorkstackAction
+ \brief Implements actions group for menu Windows with standard operations, like
+ "Split vertical", "Split horizontal", etc.
*/
-QtxWorkstackAction::QtxWorkstackAction( QtxWorkstack* ws, QObject* parent, const char* name )
-: QtxAction( tr( "Controls windows into workstack" ), tr( "Workstack management" ), 0, parent, name ),
-myFlags( Standard ),
-myWorkstack( ws )
+
+/*!
+ \brief Constructor.
+ \param ws workstack
+ \param parent parent object (owner of the action)
+*/
+QtxWorkstackAction::QtxWorkstackAction( QtxWorkstack* ws, QObject* parent )
+: QtxActionSet( parent ),
+ myWorkstack( ws ),
+ myWindowsFlag( true )
{
- myItem.insert( VSplit, new QtxAction( tr( "Split the active window on two vertical parts" ),
- tr( "Split vertically" ), 0, this, 0, false ) );
- myItem.insert( HSplit, new QtxAction( tr( "Split the active window on two horizontal parts" ),
- tr( "Split horizontally" ), 0, this, 0, false ) );
+ insertAction( new QtxAction( tr( "Split the active window on two vertical parts" ),
+ tr( "Split vertically" ), 0, this ), SplitVertical );
+ insertAction( new QtxAction( tr( "Split the active window on two horizontal parts" ),
+ tr( "Split horizontally" ), 0, this ), SplitHorizontal );
- connect( myItem[VSplit], SIGNAL( activated() ), ws, SLOT( splitVertical() ) );
- connect( myItem[HSplit], SIGNAL( activated() ), ws, SLOT( splitHorizontal() ) );
+ connect( this, SIGNAL( triggered( int ) ), this, SLOT( onTriggered( int ) ) );
+
+ setMenuActions( Standard );
}
/*!
- Destructor
+ \brief Destructor.
*/
QtxWorkstackAction::~QtxWorkstackAction()
{
}
/*!
- \return corresponding workstack
+ \brief Get workstack.
+ \return parent workstack
*/
QtxWorkstack* QtxWorkstackAction::workstack() const
{
}
/*!
- \return set of action flags
-*/
-int QtxWorkstackAction::items() const
-{
- return myFlags;
-}
+ \brief Set actions to be visible in the menu.
+
+ Actions, which IDs are set in \a flags parameter, will be shown in the
+ menu bar. Other actions will not be shown.
-/*!
- Sets action flags
- \param flags - new set of flags
+ \param flags ORed together actions flags
*/
-void QtxWorkstackAction::setItems( const int flags )
+void QtxWorkstackAction::setMenuActions( const int flags )
{
- if ( !flags || flags == myFlags || !( flags & Split ) )
- return;
-
- myFlags = flags;
+ action( SplitVertical )->setVisible( flags & SplitVertical );
+ action( SplitHorizontal )->setVisible( flags & SplitHorizontal );
+ myWindowsFlag = flags & Windows;
}
/*!
- \return true if action contains all flags
- \param flags - new set of flags
+ \brief Get menu actions which are currently visible in the menu bar.
+ \return ORed together actions flags
+ \sa setMenuActions()
*/
-bool QtxWorkstackAction::hasItems( const int flags ) const
+int QtxWorkstackAction::menuActions() const
{
- return ( myFlags & flags ) == flags;
+ int ret = 0;
+ ret = ret | ( action( SplitVertical )->isVisible() ? SplitVertical : 0 );
+ ret = ret | ( action( SplitHorizontal )->isVisible() ? SplitHorizontal : 0 );
+ ret = ret | ( myWindowsFlag ? Windows : 0 );
+ return ret;
}
/*!
- \return accelerator of item
- \param id - item id
+ \brief Get keyboard accelerator for the specified action.
+ \param id menu action ID
+ \return keyboard accelerator of menu item or 0 if there is no such action
*/
int QtxWorkstackAction::accel( const int id ) const
{
int a = 0;
- if ( myItem.contains( id ) )
- a = myItem[id]->accel();
+ if ( action( id ) )
+ a = action( id )->shortcut();
return a;
}
/*!
- \return icons of item
- \param id - item id
+ \brief Get icon for the specified action.
+
+ If \a id is invalid, null icon is returned.
+
+ \param id menu action ID
+ \return menu item icon
*/
-QIconSet QtxWorkstackAction::iconSet( const int id ) const
+QIcon QtxWorkstackAction::icon( const int id ) const
{
- QIconSet ico;
- if ( myItem.contains( id ) )
- ico = myItem[id]->iconSet();
+ QIcon ico;
+ if ( action( id ) )
+ ico = action( id )->icon();
return ico;
}
/*!
- \return menu text of item
- \param id - item id
+ \brief Get menu item text for the specified action.
+ \param id menu action ID
+ \return menu item text or null QString if there is no such action
*/
-QString QtxWorkstackAction::menuText( const int id ) const
+QString QtxWorkstackAction::text( const int id ) const
{
QString txt;
- if ( myItem.contains( id ) )
- txt = myItem[id]->menuText();
+ if ( action( id ) )
+ txt = action( id )->text();
return txt;
}
/*!
- \return status tip of item
- \param id - item id
+ \brief Get status bar tip for the specified action.
+ \param id menu action ID
+ \return status bar tip menu item or null QString if there is no such action
*/
QString QtxWorkstackAction::statusTip( const int id ) const
{
QString txt;
- if ( myItem.contains( id ) )
- txt = myItem[id]->statusTip();
+ if ( action( id ) )
+ txt = action( id )->statusTip();
return txt;
}
/*!
- Changes accelerator of item
- \param id - item id
- \param a - new accelerator
+ \brief Set keyboard accelerator for the specified action.
+ \param id menu action ID
+ \param a new keyboard accelerator
*/
void QtxWorkstackAction::setAccel( const int id, const int a )
{
- if ( myItem.contains( id ) )
- myItem[id]->setAccel( a );
+ if ( action( id ) )
+ action( id )->setShortcut( a );
}
/*!
- Changes icons of item
- \param id - item id
- \param ico - new icons
+ \brief Set menu item icon for the specified action.
+ \param id menu action ID
+ \param ico new menu item icon
*/
-void QtxWorkstackAction::setIconSet( const int id, const QIconSet& ico )
+void QtxWorkstackAction::setIcon( const int id, const QIcon& icon )
{
- if ( myItem.contains( id ) )
- myItem[id]->setIconSet( ico );
+ if ( action( id ) )
+ action( id )->setIcon( icon );
}
/*!
- Changes menu text of item
- \param id - item id
- \param txt - new menu text
+ \brief Set menu item text for the specified action.
+ \param id menu action ID
+ \param txt new menu item text
*/
-void QtxWorkstackAction::setMenuText( const int id, const QString& txt )
+void QtxWorkstackAction::setText( const int id, const QString& txt )
{
- if ( myItem.contains( id ) )
- myItem[id]->setMenuText( txt );
+ if ( action( id ) )
+ action( id )->setText( txt );
}
/*!
- Changes status tip of item
- \param id - item id
- \param txt - new status tip
+ \brief Set menu item status bar tip for the specified action.
+ \param id menu action ID
+ \param txt new menu item status bar tip
*/
void QtxWorkstackAction::setStatusTip( const int id, const QString& txt )
{
- if ( myItem.contains( id ) )
- myItem[id]->setStatusTip( txt );
-}
-
-/*!
- Adds action to widget
- \param wid - widget
-*/
-bool QtxWorkstackAction::addTo( QWidget* wid )
-{
- return addTo( wid, -1 );
+ if ( action( id ) )
+ action( id )->setStatusTip( txt );
}
/*!
- Adds action to widget
- \param wid - widget
- \param idx - position
-*/
-bool QtxWorkstackAction::addTo( QWidget* wid, const int idx )
-{
- if ( !wid || !wid->inherits( "QPopupMenu" ) )
- return false;
-
- QPopupMenu* pm = (QPopupMenu*)wid;
- checkPopup( pm );
-
- if ( myMenu.contains( pm ) )
- return false;
-
- myMenu.insert( pm, QIntList() );
- fillPopup( pm, idx );
-
- connect( pm, SIGNAL( aboutToShow() ), this, SLOT( onAboutToShow() ) );
- connect( pm, SIGNAL( destroyed( QObject* ) ), this, SLOT( onPopupDestroyed( QObject* ) ) );
-
- return true;
-}
-
-/*!
- Removes action from widget
- \param wid - widget
-*/
-bool QtxWorkstackAction::removeFrom( QWidget* wid )
-{
- if ( !wid || !wid->inherits( "QPopupMenu" ) )
- return false;
-
- QPopupMenu* pm = (QPopupMenu*)wid;
- if ( !myMenu.contains( pm ) )
- return false;
-
- clearPopup( pm );
-
- disconnect( pm, SIGNAL( aboutToShow() ), this, SLOT( onAboutToShow() ) );
- disconnect( pm, SIGNAL( destroyed( QObject* ) ), this, SLOT( onPopupDestroyed( QObject* ) ) );
-
- myMenu.remove( pm );
-
- return true;
-}
-
-/*!
- Performs action
- \param type - action type
+ \brief Process action activated by the user.
+ \param type action ID
*/
void QtxWorkstackAction::perform( const int type )
{
switch ( type )
{
- case VSplit:
- workstack()->splitVertical();
+ case SplitVertical:
+ splitVertical();
break;
- case HSplit:
- workstack()->splitHorizontal();
+ case SplitHorizontal:
+ splitHorizontal();
break;
}
}
/*!
- SLOT: called just before the popup menu is displayed, updates popup
+ \brief Split the window area in the workstack in the vertical direction.
*/
-void QtxWorkstackAction::onAboutToShow()
+void QtxWorkstackAction::splitVertical()
{
- const QObject* obj = sender();
- if ( !obj || !obj->inherits( "QPopupMenu" ) )
- return;
-
QtxWorkstack* ws = workstack();
- if ( ws && myItem.contains( VSplit ) )
- myItem[VSplit]->setAccel( ws->accel( QtxWorkstack::SplitVertical ) );
- if ( ws && myItem.contains( HSplit ) )
- myItem[HSplit]->setAccel( ws->accel( QtxWorkstack::SplitHorizontal ) );
-
- updatePopup( (QPopupMenu*)obj );
+ if ( ws )
+ ws->splitVertical();
}
/*!
- SLOT: called when popup menu is destroyed, removes it from menu
+ \brief Split the window area in the workstack in the horizontal direction.
*/
-void QtxWorkstackAction::onPopupDestroyed( QObject* obj )
+void QtxWorkstackAction::splitHorizontal()
{
- myMenu.remove( (QPopupMenu*)obj );
+ QtxWorkstack* ws = workstack();
+ if ( ws )
+ ws->splitHorizontal();
}
/*!
- Updates popup
- \param pm - popup menu
+ \brief Called when action is added to the menu bar.
+ \param w menu bar widget this action is being added to
*/
-void QtxWorkstackAction::checkPopup( QPopupMenu* pm )
+void QtxWorkstackAction::addedTo( QWidget* w )
{
- if ( !myMenu.contains( pm ) )
- return;
-
- QIntList updList;
- for ( QIntList::const_iterator it = myMenu[pm].begin(); it != myMenu[pm].end(); ++it )
- {
- if ( pm->indexOf( *it ) != -1 )
- updList.append( *it );
- }
-
- myMenu.remove( pm );
+ QtxActionSet::addedTo( w );
- if ( !updList.isEmpty() )
- myMenu.insert( pm, updList );
- else
- {
- disconnect( pm, SIGNAL( aboutToShow() ), this, SLOT( onAboutToShow() ) );
- disconnect( pm, SIGNAL( destroyed( QObject* ) ), this, SLOT( onPopupDestroyed( QObject* ) ) );
- }
+ QMenu* pm = ::qobject_cast<QMenu*>( w );
+ if ( pm )
+ connect( pm, SIGNAL( aboutToShow() ), this, SLOT( onAboutToShow() ) );
}
/*!
- Clears and refills popup and updates state of actions
- \param pm - popup menu
+ \brief Called when action is removed from the menu bar.
+ \param w menu bar widget this action is being removed from
*/
-void QtxWorkstackAction::updatePopup( QPopupMenu* pm )
+void QtxWorkstackAction::removedFrom( QWidget* w )
{
- if ( !myMenu.contains( pm ) )
- return;
+ QtxActionSet::removedFrom( w );
- fillPopup( pm, clearPopup( pm ) );
-
- int count = workstack() ? workstack()->splitWindowList().count() : 0;
- myItem[VSplit]->setEnabled( count > 1 );
- myItem[HSplit]->setEnabled( count > 1 );
+ QMenu* pm = ::qobject_cast<QMenu*>( w );
+ if ( pm )
+ disconnect( pm, SIGNAL( aboutToShow() ), this, SLOT( onAboutToShow() ) );
}
/*!
- Clears popup
- \param pm - popup menu
+ \brief Update all menu action state.
*/
-int QtxWorkstackAction::clearPopup( QPopupMenu* pm )
+void QtxWorkstackAction::updateContent()
{
- if ( !myMenu.contains( pm ) )
- return -1;
-
- int idx = -1;
- const QIntList& lst = myMenu[pm];
- for ( QIntList::const_iterator it = lst.begin(); it != lst.end() && idx == -1; ++it )
- idx = pm->indexOf( *it );
-
- for ( ItemMap::ConstIterator mit = myItem.begin(); mit != myItem.end(); ++mit )
- mit.data()->removeFrom( pm );
-
- for ( QIntList::const_iterator itr = lst.begin(); itr != lst.end(); ++itr )
- pm->removeItem( *itr );
+ bool count = workstack() ? workstack()->splitWindowList().count() > 1 : 0;
+ action( SplitVertical )->setEnabled( count );
+ action( SplitHorizontal )->setEnabled( count );
- return idx;
+ updateWindows();
}
/*!
- Fills popup with items
- \param pm - popup menu
- \param idx - position
+ \brief Update actions which refer to the opened child windows.
*/
-void QtxWorkstackAction::fillPopup( QPopupMenu* pm, const int idx )
+void QtxWorkstackAction::updateWindows()
{
- if ( !pm )
+ QtxWorkstack* ws = workstack();
+ if ( !ws )
return;
- int index = idx < 0 ? pm->count() : QMIN( (int)pm->count(), idx );
+ QList<QAction*> lst = actions();
+ for ( QList<QAction*>::iterator it = lst.begin(); it != lst.end(); ++it )
+ {
+ int id = actionId( *it );
+ if ( id >= Windows )
+ removeAction( *it );
+ }
- myMenu.insert( pm, QIntList() );
- QIntList& lst = myMenu[pm];
+ bool base = action( SplitVertical )->isVisible() || action( SplitHorizontal )->isVisible();
- for ( ItemMap::ConstIterator mit = myItem.begin(); mit != myItem.end(); ++mit )
+ QList<QAction*> items;
+ QMap<QAction*, int> map;
+ if ( menuActions() & Windows )
{
- if ( !hasItems( mit.key() ) )
- continue;
-
- mit.data()->addTo( pm, index );
- lst.append( pm->idAt( index++ ) );
+ int index = 1;
+ QWidgetList wList = ws->windowList();
+ for ( QWidgetList::iterator it = wList.begin(); it != wList.end(); ++it, index++ )
+ {
+ QWidget* wid = *it;
+ QAction* a = new QtxAction( wid->windowTitle(), wid->windowTitle(), 0, this, true );
+ a->setChecked( wid == ws->activeWindow() );
+ items.append( a );
+ map.insert( a, Windows + index );
+ }
+
+ if ( base && !items.isEmpty() )
+ {
+ QAction* sep = new QtxAction( this );
+ sep->setSeparator( true );
+ items.prepend( sep );
+ map.insert( sep, Windows );
+ }
}
- QtxWorkstack* ws = workstack();
- if ( !ws || !hasItems( Windows ) )
- return;
+ if ( !items.isEmpty() )
+ insertActions( items );
- QWidgetList wList = ws->windowList();
- if ( wList.isEmpty() )
- return;
+ for ( QMap<QAction*, int>::const_iterator itr = map.begin(); itr != map.end(); ++itr )
+ setActionId( itr.key(), itr.value() );
+}
- lst.append( pm->insertSeparator( index++ ) );
+/*!
+ \brief Called when parent menu is about to show.
- int param = 0;
- pm->setCheckable( true );
- for ( QWidgetListIt it( wList ); it.current(); ++it )
- {
- int id = pm->insertItem( it.current()->caption(), this, SLOT( onItemActivated( int ) ), 0, -1, index++ );
- pm->setItemParameter( id, param++ );
- pm->setItemChecked( id, it.current() == ws->activeWindow() );
- lst.append( id );
- }
+ Updates all menu items.
+*/
+void QtxWorkstackAction::onAboutToShow()
+{
+ QMenu* pm = ::qobject_cast<QMenu*>( sender() );
+ if ( pm )
+ updateContent();
}
/*!
- SLOT: called when popup item corresponding to window is activated, activates window
+ \brief Called when menu item corresponding to some child window is activated.
+
+ Activates correposponding child window.
+
+ \param idx menu item index
*/
-void QtxWorkstackAction::onItemActivated( int idx )
+void QtxWorkstackAction::activateItem( const int idx )
{
QtxWorkstack* ws = workstack();
if ( !ws )
return;
QWidgetList wList = ws->windowList();
- if ( idx < 0 || idx >= (int)wList.count() )
- return;
+ if ( idx >= 0 && idx < (int)wList.count() )
+ wList.at( idx )->setFocus();
+}
- wList.at( idx )->setFocus();
+/*!
+ \brief Called when menu item is activated by the user.
+
+ Perform the corresponding action.
+
+ \param id menu item identifier
+*/
+void QtxWorkstackAction::onTriggered( int id )
+{
+ if ( id < Windows )
+ perform( id );
+ else
+ activateItem( id - Windows - 1 );
}
#ifndef QTXWORKSTACKACTION_H
#define QTXWORKSTACKACTION_H
-#include "QtxAction.h"
+#include "QtxActionSet.h"
class QtxWorkstack;
#pragma warning( disable:4251 )
#endif
-class QTX_EXPORT QtxWorkstackAction : public QtxAction
+class QTX_EXPORT QtxWorkstackAction : public QtxActionSet
{
Q_OBJECT
public:
- enum { VSplit = 0x0001,
- HSplit = 0x0002,
- Windows = 0x0010,
- Split = VSplit | HSplit,
- Standard = Split | Windows };
-
-public:
- QtxWorkstackAction( QtxWorkstack*, QObject* = 0, const char* = 0 );
+ //! Actions (menu items) ID
+ enum { SplitVertical = 0x0001, //!< "Split window vertically" operation
+ SplitHorizontal = 0x0002, //!< "Split window horizontally" operation
+ Windows = 0x0010, //!< A list of child windows menu items
+ Split = SplitVertical | SplitHorizontal,
+ Standard = Split | Windows };
+
+ QtxWorkstackAction( QtxWorkstack*, QObject* = 0 );
virtual ~QtxWorkstackAction();
QtxWorkstack* workstack() const;
- int items() const;
- void setItems( const int );
- bool hasItems( const int ) const;
+ int menuActions() const;
+ void setMenuActions( const int );
+ QIcon icon( const int ) const;
+ QString text( const int ) const;
int accel( const int ) const;
- QIconSet iconSet( const int ) const;
- QString menuText( const int ) const;
QString statusTip( const int ) const;
void setAccel( const int, const int );
- void setIconSet( const int, const QIconSet& );
- void setMenuText( const int, const QString& );
+ void setIcon( const int, const QIcon& );
+ void setText( const int, const QString& );
void setStatusTip( const int, const QString& );
- virtual bool addTo( QWidget* );
- virtual bool addTo( QWidget*, const int );
- virtual bool removeFrom( QWidget* );
-
void perform( const int );
private slots:
void onAboutToShow();
- void onItemActivated( int );
- void onPopupDestroyed( QObject* );
-
-private:
- void checkPopup( QPopupMenu* );
- void updatePopup( QPopupMenu* );
+ void onTriggered( int );
- int clearPopup( QPopupMenu* );
- void fillPopup( QPopupMenu*, const int );
+protected:
+ virtual void addedTo( QWidget* );
+ virtual void removedFrom( QWidget* );
private:
- typedef QMap<QPopupMenu*, QIntList> MenuMap;
- typedef QMap<int, QtxAction*> ItemMap;
+ void updateContent();
+ void updateWindows();
+ void splitVertical();
+ void splitHorizontal();
+ void activateItem( const int );
private:
- MenuMap myMenu;
- ItemMap myItem;
- int myFlags;
- QtxWorkstack* myWorkstack;
+ QtxWorkstack* myWorkstack; //!< parent workstack
+ bool myWindowsFlag; //!< "show child windows items" flag
};
#ifdef WIN32
+++ /dev/null
-// SALOME RegistryDisplay : GUI for Registry server implementation
-//
-// Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-//
-//
-// File : HelpWindow.cxx
-// Author : Pascale NOYRET, EDF
-// Module : SALOME
-// $Header$
-
-# include "HelpWindow.hxx"
-# include "utilities.h"
-
-# include <qtextview.h>
-# include <qpushbutton.h>
-# include <qtextstream.h>
-# include <qfile.h>
-
-using namespace std;
-
-/*!
- Constructor
-*/
-HelpWindow::HelpWindow(QWidget* parent, const char* name )
- : QMainWindow( parent, name, WType_TopLevel | WDestructiveClose )
-{
- BEGIN_OF("Constructeur HelpWindow");
-
- setCaption( tr( "Help" ) );
-
- myTextView = new QTextView( this, "myTextView" );
- QPalette pal = myTextView->palette();
- QColorGroup cg = pal.active();
- cg.setColor( QColorGroup::Highlight, QColor( 0, 0, 128) );
- cg.setColor( QColorGroup::HighlightedText, Qt::white );
- cg.setColor( QColorGroup::Base, QColor( 255,255,220 ) );
- cg.setColor( QColorGroup::Text, Qt::black );
- pal.setActive ( cg );
- cg = pal.inactive();
- cg.setColor( QColorGroup::Highlight, QColor( 0, 0, 128) );
- cg.setColor( QColorGroup::HighlightedText, Qt::white );
- cg.setColor( QColorGroup::Base, QColor( 255,255,220 ) );
- cg.setColor( QColorGroup::Text, Qt::black );
- pal.setInactive( cg );
- cg = pal.disabled();
- cg.setColor( QColorGroup::Highlight, QColor( 0, 0, 128) );
- cg.setColor( QColorGroup::HighlightedText, Qt::white );
- cg.setColor( QColorGroup::Base, QColor( 255,255,220 ) );
- cg.setColor( QColorGroup::Text, Qt::black );
- pal.setDisabled( cg );
- myTextView->setPalette( pal );
-
- setCentralWidget( myTextView );
- setMinimumSize( 450, 250 );
-
- QFile f ( "tmp.txt" );
- if ( f.open( IO_ReadOnly ) )
- {
- QTextStream t( &f );
- while ( !t.eof() )
- {
- myTextView->append(t.readLine());
- }
- }
- f.close();
-
- END_OF("Constructeur HelpWindow");
-}
-
-/*!
- Destructor
-*/
-HelpWindow::~HelpWindow()
-{
- BEGIN_OF("Destructeur HelpWindow");
- END_OF("Destructeur HelpWindow");
-};
-
-/*!
- Sets text
-*/
-void HelpWindow::setText( const QString& text )
-{
- myTextView->setText( text );
-}
-
-
+++ /dev/null
-// SALOME RegistryDisplay : GUI for Registry server implementation
-//
-// Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-//
-//
-// File : HelpWindow.hxx
-// Author : Pascale NOYRET, EDF
-// Module : SALOME
-// $Header$
-
-#ifndef __HELPWINDOW_H__
-#define __HELPWINDOW_H__
-
-#include <qapplication.h>
-#include <qmainwindow.h>
-
-class QTextView;
-
-class HelpWindow : public QMainWindow
-{
- Q_OBJECT
-
-public:
- HelpWindow( QWidget* parent = 0, const char* name = 0);
- ~HelpWindow();
-
- void setText( const QString& text );
- QTextView* textView() const { return myTextView; }
-
-private:
- QTextView* myTextView;
-};
-
-#endif
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-// SALOME RegistryDisplay : GUI for Registry server implementation
-//
-// File : IntervalWindow.cxx
-// Author : Oksana TCHEBANOVA
-// Module : SALOME
-
-#include <IntervalWindow.hxx>
-
-#include <qbuttongroup.h>
-#include <qlabel.h>
-#include <qpushbutton.h>
-#include <qlayout.h>
-# include "utilities.h"
-
-#define MARGIN_SIZE 11
-#define SPACING_SIZE 6
-#define MIN_SPIN_WIDTH 100
-
-/*!
- Constructor
-*/
-IntervalWindow::IntervalWindow ( QWidget* parent )
- : QDialog( parent, "IntervalWindow" , true, WStyle_Customize | WStyle_NormalBorder | WStyle_Title | WStyle_SysMenu | WDestructiveClose )
-{
- BEGIN_OF("IntervalWindow constructor")
- setCaption( tr( "Refresh Interval" ) );
- setSizeGripEnabled( true );
-
- QGridLayout* topLayout = new QGridLayout( this );
- topLayout->setSpacing( SPACING_SIZE );
- topLayout->setMargin( MARGIN_SIZE );
-
- QGroupBox* intervalGrp = new QGroupBox( this, "intervalGrp" );
- intervalGrp->setColumnLayout( 0, Qt::Horizontal );//Vertical
- intervalGrp->layout()->setSpacing( 0 );
- intervalGrp->layout()->setMargin( 0 );
- QGridLayout* intervalGrpLayout = new QGridLayout( intervalGrp->layout() );
- intervalGrpLayout->setAlignment( Qt::AlignTop );
- intervalGrpLayout->setSpacing( SPACING_SIZE );
- intervalGrpLayout->setMargin( MARGIN_SIZE );
-
- QHBoxLayout* aBtnLayout = new QHBoxLayout;
- aBtnLayout->setSpacing( SPACING_SIZE );
- aBtnLayout->setMargin( 0 );
-
- myButtonOk = new QPushButton( this, "buttonOk" );
- myButtonOk->setText( tr( "BUT_OK" ) );
- myButtonOk->setAutoDefault( TRUE );
- myButtonOk->setDefault( TRUE );
-
- myButtonCancel = new QPushButton( this, "buttonCancel" );
- myButtonCancel->setText( tr( "BUT_CANCEL" ) );
- myButtonCancel->setAutoDefault( TRUE );
-
- QLabel* TextLabel = new QLabel( intervalGrp, "TextLabel" );
- TextLabel->setText( tr( "Please, enter a number of seconds:" ) );
-
- mySpinBox = new QSpinBox( 1, 999999999, 1, intervalGrp, "SpinBox" );
- mySpinBox->setValue( 100 );
- mySpinBox->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
- mySpinBox->setMinimumWidth(MIN_SPIN_WIDTH);
-
- intervalGrpLayout->addWidget(TextLabel, 0, 0);
- intervalGrpLayout->addWidget(mySpinBox, 0, 1);
-
- aBtnLayout->addWidget( myButtonOk );
- aBtnLayout->addItem( new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum ) );
- aBtnLayout->addWidget( myButtonCancel );
-
- topLayout->addWidget( intervalGrp, 0, 0 );
- topLayout->addLayout( aBtnLayout, 1, 0 );
-
- END_OF("IntervalWindow constructor")
-}
-
-/*!
- Destructor
-*/
-IntervalWindow::~IntervalWindow() {}
-
-/*!
- Sets start interval size
-*/
-void IntervalWindow::setValue(const int size)
-{
- mySpinBox->setValue(size);
-}
-
-/*!
- Gets interval size
-*/
-int IntervalWindow::getValue()
-{
- return mySpinBox->value();
-}
-
-/*!
- gets a pointer to myButtonOk
-*/
-QPushButton* IntervalWindow::Ok()
-{
- return myButtonOk;
-}
-
-/*!
- gets a pointer to myButtonCancel
-*/
-QPushButton* IntervalWindow::Cancel()
-{
- return myButtonCancel;
-}
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-// SALOME RegistryDisplay : GUI for Registry server implementation
-//
-// File : IntervalWindow.hxx
-// Author : Oksana TCHEBANOVA
-// Module : SALOME
-
-#ifndef IntervalWindow_HeaderFile
-#define IntervalWindow_HeaderFile
-
-# include <qwidget.h>
-# include <qdialog.h>
-# include <qpushbutton.h>
-# include <qspinbox.h>
-
-#ifndef WNT
-using namespace std;
-#endif
-
-class IntervalWindow : public QDialog
-{
- Q_OBJECT
-
-public:
- IntervalWindow( QWidget* parent = 0 );
- ~IntervalWindow();
-
- QPushButton* Ok();
- QPushButton* Cancel();
-
- int getValue();
- void setValue( int );
-
-private:
- QSpinBox* mySpinBox;
- QPushButton* myButtonOk;
- QPushButton* myButtonCancel;
-};
-
-#endif
+++ /dev/null
-# SALOME RegistryDisplay : GUI for Registry server implementation
-#
-# Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-# CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-#
-#
-# File : Makefile.in
-# Author : Paul RASCLE, EDF
-# Module : SALOME
-# $Header$
-
-include $(top_srcdir)/adm_local/unix/make_common_starter.am
-
-lib_LTLIBRARIES = libRegistryDisplay.la
-
-salomeinclude_HEADERS= \
- HelpWindow.hxx \
- IntervalWindow.hxx \
- RegWidget.h
-
-dist_libRegistryDisplay_la_SOURCES= \
- HelpWindow.cxx \
- RegWidget.cxx \
- RegWidgetFactory.cxx \
- IntervalWindow.cxx
-
-MOC_FILES = RegWidget_moc.cxx
-nodist_libRegistryDisplay_la_SOURCES= $(MOC_FILES)
-
-libRegistryDisplay_la_CPPFLAGS=$(QT_INCLUDES) @KERNEL_CXXFLAGS@ @CORBA_CXXFLAGS@ @CORBA_INCLUDES@\
- -I$(top_builddir)/salome_adm/unix -I$(top_builddir)/idl
-libRegistryDisplay_la_LDFLAGS=$(QT_MT_LIBS) $(KERNEL_LDFLAGS) -lSalomeNS -lOpUtil -lSalomeIDLKernel
+++ /dev/null
-// SALOME RegistryDisplay : GUI for Registry server implementation
-//
-// Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-//
-//
-// File : RegWidget.cxx
-// Author : Pascale NOYRET, EDF
-// Module : SALOME
-// $Header$
-
-# include <qpushbutton.h>
-# include <qlistview.h>
-# include <qtabwidget.h>
-# include <qstatusbar.h>
-# include <qtextview.h>
-# include <qtimer.h>
-# include <qinputdialog.h>
-# include <qtoolbar.h>
-# include <qdir.h>
-# include <qtooltip.h>
-
-# include "SALOME_NamingService.hxx"
-# include "ServiceUnreachable.hxx"
-# include "Utils_SINGLETON.hxx"
-# include "Utils_CommException.hxx"
-
-# include "utilities.h"
-# include "OpUtil.hxx"
-
-# include "RegWidget.h"
-# include "HelpWindow.hxx"
-# include "IntervalWindow.hxx"
-using namespace std;
-
-typedef int PIXELS;
-RegWidget* RegWidget::myRegWidgetPtr = 0;
-QString addSlash( const QString& );
-QString findFile( QString filename );
-
-#define BOLD( text ) ( QString( "<b>" ) + QString( text ) + QString( "</b>" ) )
-
-static const char* const time_data[] = {
-"16 16 6 1",
-". c None",
-"b c None",
-"# c #000000",
-"a c #4c4c4c",
-"d c #878787",
-"c c #ffffff",
-".....#####ab....",
-"...##cc#dc##ab..",
-"..#ccc###dcc#ab.",
-".#ccccc#dcccc#a.",
-".#ccccc#dcccc#ab",
-"#cccccc#dccccc#a",
-"#cccccc#dccc#c#a",
-"#c##ccc########a",
-"#ccddcccdddd#d#a",
-"#cccccccccccdc#a",
-".#ccccccccccc#aa",
-".#ccccc#ccccc#a.",
-"..#cccc#dccc#aa.",
-"...##cccdc##aa..",
-".....#####aaa...",
-"......aaaaa....."};
-
-static const char* const close_data[] = {
-"16 16 6 1",
-"d c None",
-". c None",
-"# c #000000",
-"a c #4c4c4c",
-"c c #5b5b5b",
-"b c #ffffff",
-".....#####a.....",
-"...##bbbbb##a...",
-"..#bbbbbbbbb#a..",
-".#b#cbbbbbb#d#a.",
-".#bc#cbbbb#cb#a.",
-"#bbbc#cbb#cbbb#a",
-"#bbbbc#c#cbbbb#a",
-"#bbbbbc#cbbbbb#a",
-"#bbbbc#c#cbbbb#a",
-"#bbb#ccbb##bbb#a",
-".#b#c#bbbbc#b#aa",
-".#bc#bbbbbb#c#a.",
-"..#bbbbbbbbb#aa.",
-"...##bbbbb##aa..",
-".....#####aaa...",
-"......aaaaa....."};
-
-static const char* const refresh_data[] = {
-"16 16 5 1",
-". c None",
-"# c #000000",
-"a c #4c4c4c",
-"c c #878787",
-"b c #ffffff",
-".....#####a.....",
-"...##bb#bb##a...",
-"..#bbbbc#bbb#a..",
-".#bbbb####cbb#a.",
-".#bbb#cc#cbbb#a.",
-"#bbb#cb#cbbbbb#a",
-"#bb#cbbbbbb#bb#a",
-"#bb#cbbbbbb#cb#a",
-"#bb#cbbbbbb#cb#a",
-"#bbbbbb#bb#cbb#a",
-".#bbbb#cb#cbb#aa",
-".#bbb####cbbb#a.",
-"..#bbb#cbbbb#aa.",
-"...##bb#cb##aa..",
-".....#####aaa...",
-"......aaaaa....."};
-
-/*!
- Creates components list
-*/
-
-Registry::Components_var MakeRegistry( CORBA::ORB_var &orb )
-{
-
- const char *registryName="Registry" ;
-
- SALOME_NamingService &naming = *SINGLETON_<SALOME_NamingService>::Instance() ;
- naming.init_orb( orb ) ;
-
- // Recuperation de la reference de l'objet
- CORBA::Object_var object = 0 ;
- try
- {
- SCRUTE(registryName) ;
- object = naming.Resolve( registryName ) ;
- if(CORBA::is_nil(object)) throw CommException( "unable to find the RegistryService" ) ;
- }
- catch( const ServiceUnreachable &ex )
- {
- MESSAGE( ex.what() )
- exit( EXIT_FAILURE ) ;
- }
- catch( const CORBA::Exception &exx )
- {
- exit( EXIT_FAILURE ) ;
- }
-
- // Specialisation de l'objet generique
-
- return Registry::Components::_narrow( object ) ;
-}
-
-/*!
- Only one global registry window should exist at the moment
- This method creates registry window if necessary and returns it
- [ static ]
-*/
-RegWidget* RegWidget::GetRegWidget( CORBA::ORB_var &orb , QWidget *parent, const char *name )
-{
- if ( !myRegWidgetPtr )
- myRegWidgetPtr = new RegWidget( orb, parent, name );
- return myRegWidgetPtr;
-}
-
-/*!
- Constructor
-*/
-RegWidget::RegWidget(CORBA::ORB_var &orb, QWidget *parent, const char *name )
- : QMainWindow( parent, name, WType_TopLevel | WDestructiveClose ),
- _VarComponents( MakeRegistry(orb) ),
- _clients(0), _history(0), _parent( parent ),
- _tabWidget(0), _refresh(0), _interval(0),
- myInfoWindow(0), myHelpWindow(0), myIntervalWindow(0)
-{
- QString aFile = findFile("default.png");
- /* char* dir = getenv( "CSF_ResourcesDefaults" );
- QString path( "" );
- if ( dir ) {
- QDir qDir( dir );
- path = qDir.filePath( "default.png" );
- }*/
- QPixmap pm ( aFile );
- if ( !pm.isNull() )
- setIcon( pm );
-
- // pixmap for buttons
- QPixmap image_refresh ( ( const char** ) refresh_data );
- QPixmap image_interval( ( const char** ) time_data );
- QPixmap image_close ( ( const char** ) close_data );
-
- // Buttons definition
- QToolBar* topbar = new QToolBar( tr("Toolbar"), this );
- setDockEnabled( topbar, DockTornOff, false );
- setDockMenuEnabled( false );
-
- _refresh = new QPushButton( tr( "Refresh" ), topbar );
- _refresh->setIconSet( image_refresh );
- _refresh->setFocusPolicy( NoFocus );
- connect( _refresh, SIGNAL( clicked() ), this, SLOT( slotListeSelect() ) );
- QToolTip::add( _refresh, "", toolTipGroup(), tr("Immediately updates list of components") );
-
- /* PAL5540 - this button is needless
- QPushButton* help = new QPushButton( tr( "Help" ), topbar );
- connect( help, SIGNAL( clicked() ), this, SLOT( slotHelp() ) );
- QToolTip::add( help, "", toolTipGroup(), tr("Opens Help window") );
- */
-
- _interval = new QPushButton( tr( "Interval" ), topbar );
- _interval->setIconSet( image_interval );
- _interval->setFocusPolicy( NoFocus );
- connect( _interval, SIGNAL( clicked() ), this, SLOT( slotSelectRefresh() ) );
- QToolTip::add( _interval, "", toolTipGroup(), tr("Changes refresh interval") );
-
- topbar->addSeparator();
- _close = new QPushButton( tr("Close"), topbar );
- _close->setIconSet( image_close );
- _close->setFocusPolicy( NoFocus );
- connect( _close, SIGNAL( clicked() ), this, SLOT( close() ) );
- QToolTip::add( _close, "", toolTipGroup(), tr("Closes Registry window") );
-
- // Display area and associated slots definition
- _tabWidget = new QTabWidget( this );
- _clients = new QListView( _tabWidget );
- SetListe();
- _history = new QListView( _tabWidget );
- SetListeHistory();
-
- _tabWidget->addTab( _clients, tr( "Running" ) );
- _tabWidget->addTab( _history, tr( "History" ) );
- connect( _tabWidget, SIGNAL( currentChanged( QWidget* )), this, SLOT( slotListeSelect() ) );
- connect( _clients, SIGNAL( clicked( QListViewItem* ) ), this, SLOT( slotClientChanged( QListViewItem* ) ) );
- connect( _history, SIGNAL( clicked( QListViewItem* ) ), this, SLOT( slotHistoryChanged( QListViewItem* ) ) );
- setCentralWidget( _tabWidget );
-
- // Timer definition (used to automaticaly refresh the display area)
- _counter = new QTimer( this );
- connect( _counter, SIGNAL( timeout() ), this, SLOT( slotListeSelect() ) );
- myRefreshInterval = 10;
- _counter->start( myRefreshInterval * 1000 );
-
- PIXELS xpos = 160 ;
- PIXELS ypos = 100 ;
- PIXELS largeur = 800 ;
- PIXELS hauteur = 350 ;
- setGeometry( xpos, ypos, largeur, hauteur ) ;
- setCaption( name ) ;
- statusBar()->message(" ");
-}
-
-/*!
- Destructor
-*/
-RegWidget::~RegWidget()
-{
- MESSAGE("Debut du Destructeur");
- _counter->stop();
- myRegWidgetPtr = 0;
-};
-
-/*!
- Event filter
-*/
-bool RegWidget::eventFilter( QObject* object, QEvent* event )
-{
- if ( object ) {
- if ( object == myHelpWindow && event->type() == QEvent::Close ) {
- myHelpWindow = 0;
- }
- else if ( object == myInfoWindow && event->type() == QEvent::Close ) {
- myInfoWindow = 0;
- }
- else if ( object == myIntervalWindow && event->type() == QEvent::Close ) {
- myIntervalWindow = 0;
- }
- else if ( object == _clients && event->type() == QEvent::KeyPress ) {
- QKeyEvent* ke = (QKeyEvent*)event;
- if ( ke->key() == Key_Enter || ke->key() == Key_Return ) {
- slotClientChanged( _clients->currentItem() );
- }
- }
- else if ( object == _history && event->type() == QEvent::KeyPress ) {
- QKeyEvent* ke = (QKeyEvent*)event;
- if ( ke->key() == Key_Enter || ke->key() == Key_Return ) {
- slotHistoryChanged( _history->currentItem() );
- }
- }
- }
- return QMainWindow::eventFilter( object, event );
-}
-
-/*!
- Searches item in the list and returns it's index or -1 if not found
-*/
-int RegWidget::numitem(const QString &name, const QString &pid, const QString &machine,const Registry::AllInfos *listclient)
-{
- BEGIN_OF("numitem");
- for (CORBA::ULong i=0; i<listclient->length(); i++)
- {
- const Registry::Infos & c_info=(*listclient)[i];
- ASSERT( c_info.name!=NULL);
- QString b;
- b.setNum(int(c_info.pid));
- if ( (name.compare(QString(c_info.name)) == 0) &&
- (machine.compare(QString(c_info.machine)) == 0) &&
- (pid.compare(b) == 0) )
- {
- END_OF("numitem");
- return i;
- }
- }
- END_OF("numitem");
- return -1;
-}
-
-/*!
- Returns text, containing information about client [ static ]
-*/
-QString RegWidget::setlongText( const Registry::Infos &c_info)
-{
- BEGIN_OF("setlongText");
- ASSERT( c_info.name != NULL );
- QString a = QString( "<hr><h2>" ) + tr( "Code" ) + QString( " : " );
- a.append( QString( c_info.name ) );
- a.append( "</h1><hr><br>" );
- a.append( tr( "Process Id" ) + QString( " : " ) );
- a.append( BOLD( QString::number( int( c_info.pid ) ) ) );
- a.append( QString( " " ) + tr( "on machine" ) + QString( " " ) );
- a.append( BOLD( c_info.machine ) );
- a.append( QString( " " ) + tr( "ip address" ) + QString( " : " ) );
- a.append( BOLD( c_info.adip ) );
- a.append( "<br>" );
-
- a.append( tr( "launched by user" ) + QString( " " ) );
- a.append( BOLD( c_info.pwname ) );
- a.append( QString( " ( " ) + tr( "pid" ) + QString( " : " ) );
- a.append( BOLD( QString::number( int( c_info.uid ) ) ) );
- a.append( QString( " )<br> " ) + tr( "in directory" ) + QString( " " ));
- a.append( BOLD( c_info.cdir ) );
-
- time_t aTime;
- a.append( QString( "<br>" ) + tr( "begins" ) + QString( " " ) );
- aTime = time_t(c_info.tc_start);
- char * t1 = (char * )duplicate(ctime(&aTime));
- t1 [strlen(t1) -1 ] = ' ';
- a.append( BOLD( t1 ) );
- delete [] t1;
- a.append( "<br>" );
-
- if (c_info.tc_hello != 0 )
- {
- aTime = time_t(c_info.tc_hello);
- char * t2 = (char * )duplicate(ctime(&aTime));
- t2 [strlen(t2) -1 ] = ' ';
- a.append( tr( "last signal" ) + QString(" : ") );
- a.append( BOLD( t2 ) );
- a.append( "<br>" );
- delete [] t2;
- }
- if ((c_info.tc_end - c_info.difftime) != 0)
- {
- aTime = time_t(c_info.tc_end);
- char * t3 = (char * )duplicate(ctime(&aTime));
- t3 [strlen(t3) -1 ] = ' ';
- a.append( tr( "ends" ) + QString( " " ) );
- a.append( BOLD( t3 ) );
- a.append( "<br>" );
- delete [] t3;
- }
- else
- {
- a.append( tr( "still running" ) + QString( "<br>" ) );
- }
-
- SCRUTE(c_info.difftime);
- if (c_info.difftime!= 0)
- {
- a.append( QString( "(" ) + tr( "Time on" ) + QString( " " ) );
- a.append( BOLD( c_info.machine ) );
- a.append( QString( " " ) + tr( "differs from server's time. The difference is" ) + QString( " " ));
- a.append( BOLD( QString::number( int( c_info.difftime ) ) ) );
- a.append( QString( " " ) + tr( "seconds" ) + QString( ")<br>" ) );
- }
- END_OF("setlongText");
- return a;
-
-}
-
-/*!
- Close event
-*/
-void RegWidget::closeEvent( QCloseEvent *e)
-{
- BEGIN_OF("closeEvent");
- if ( myInfoWindow )
- myInfoWindow->close();
- if ( myHelpWindow )
- myHelpWindow->close();
- if (myIntervalWindow)
- myIntervalWindow->close();
- e->accept();
- END_OF("closeEvent");
-};
-
-/*!
- Setups Clients list
-*/
-void RegWidget::SetListe()
-{
- BEGIN_OF("SetListe");
- _clients->installEventFilter( this );
- _clients->setAllColumnsShowFocus( true );
- _clients->addColumn( tr( "Component" ), -1);
- _clients->addColumn( tr( "PID" ), -1 );
- _clients->addColumn( tr( "User Name" ), -1 );
- _clients->addColumn( tr( "Machine" ), -1 );
- _clients->addColumn( tr( "begins" ), -1 );
- _clients->addColumn( tr( "hello" ) , -1 );
- _clients->setColumnAlignment( 1, Qt::AlignRight );
- END_OF("SetListe");
-}
-
-/*!
- Setups History list
-*/
-void RegWidget::SetListeHistory()
-{
- BEGIN_OF("SetListeHistory")
- _history->installEventFilter( this );
- _history->setAllColumnsShowFocus( true );
- _history->addColumn( tr( "Component" ), -1);
- _history->addColumn( tr( "PID" ), -1 );
- _history->addColumn( tr( "User Name" ), -1 );
- _history->addColumn( tr( "Machine" ), -1 );
- _history->addColumn( tr( "begins" ), -1 );
- _history->addColumn( tr( "ends" ), -1 );
- _history->setColumnAlignment( 1, Qt::AlignRight );
- END_OF("SetListeHistory")
-}
-
-/*!
- Updates History list
-*/
-void RegWidget::InfoHistory()
-{
-
- BEGIN_OF("InfoHistory")
- _history->clear();
- try
- {
- time_t aTime;
- _serverhistory = _VarComponents->history();
- for (CORBA::ULong i=0; i<_serverhistory->length(); i++)
- {
- const Registry::Infos & c_info=(*_serverhistory)[i];
- ASSERT( c_info.name!=NULL);
- QString a;
- a.setNum(int(c_info.pid));
- aTime = time_t(c_info.tc_start);
- char * t1 = (char * )duplicate(ctime(&aTime));
- t1 [strlen(t1) -1 ] = ' ';
- aTime = time_t(c_info.tc_end);
- char * t2 = (char * )duplicate(ctime(&aTime));
- t2 [strlen(t2) -1 ] = ' ';
- QListViewItem * item = new QListViewItem(_history, QString(c_info.name),\
- a, QString(c_info.pwname), QString(c_info.machine), \
- QString(t1), QString(t2));
- item=0 ;
- delete [] t1;
- delete [] t2;
-
- }
- }
- catch( ... )
- {
- _interval->setDisabled( TRUE ) ;
- _refresh->setDisabled( TRUE ) ;
- _counter->stop();
- MESSAGE("Sorry, No more Registry Server") ;
- statusBar()->message( tr( "Sorry, No more Registry Server" ) ) ;
- }
- END_OF("InfoHistory")
-}
-
-/*!
- Updates clients list
-*/
-void RegWidget::InfoReg()
-{
- BEGIN_OF("InfoReg")
- _clients->clear();
- try
- {
- time_t aTime;
- _serverclients = _VarComponents->getall();
- for (CORBA::ULong i=0; i<_serverclients->length(); i++)
- {
- const Registry::Infos & c_info=(*_serverclients)[i];
- ASSERT( c_info.name!=NULL);
- QString a;
- a.setNum(int(c_info.pid));
- aTime = time_t(c_info.tc_start);
- char * t1 = (char * )duplicate(ctime(&aTime));
- t1 [strlen(t1) -1 ] = ' ';
- aTime = time_t(c_info.tc_hello);
- char * t2 = (char * )duplicate(ctime(&aTime));
- t2 [strlen(t2) -1 ] = ' ';
- QListViewItem * item = new QListViewItem(_clients, QString(c_info.name),\
- a, QString(c_info.pwname), QString(c_info.machine), \
- QString(t1), QString(t2));
- item=0 ;
- delete [] t1;
- delete [] t2;
-
- }
- }
- catch( ... )
- {
- _interval->setDisabled( TRUE ) ;
- _refresh->setDisabled( TRUE ) ;
- _counter->stop();
- MESSAGE("Sorry, No more Registry Server") ;
- statusBar()->message( tr( "Sorry, No more Registry Server" ) ) ;
- }
- END_OF("InfoReg")
-}
-
-/*!
- Called when <Refresh> button is clicked
-*/
-void RegWidget::slotListeSelect()
-{
- try
- {
- ASSERT(_tabWidget->currentPage() != NULL);
- if (_tabWidget->currentPage () == _clients) InfoReg();
- else if (_tabWidget->currentPage () == _history) InfoHistory();
- }
- catch( ... )
- {
- MESSAGE("Sorry, No more Registry Server") ;
- statusBar()->message( tr( "Sorry, No more Registry Server" ) ) ;
- }
-}
-
-/*!
- Called when <Interval> button is clicked (changing refresh interval)
-*/
-void RegWidget::slotSelectRefresh()
-{
- BEGIN_OF("slotSelectRefresh");
- myIntervalWindow = new IntervalWindow(this);
- myIntervalWindow->installEventFilter( this );
- myIntervalWindow->setValue(myRefreshInterval);
- myIntervalWindow->show();
- connect( myIntervalWindow->Cancel(), SIGNAL( clicked() ), myIntervalWindow, SLOT( close() ) );
- connect( myIntervalWindow->Ok(), SIGNAL( clicked() ), this, SLOT( slotIntervalOk() ) );
- END_OF("slotSelectRefresh");
-}
-
-/*!
- SLOT: called when button OK is clicked in interval window
-*/
-void RegWidget::slotIntervalOk()
-{
- BEGIN_OF("slotIntervalOk");
- myRefreshInterval = myIntervalWindow->getValue();
- _counter->changeInterval( myRefreshInterval * 1000 );
- SCRUTE(myRefreshInterval);
- myIntervalWindow->close();
- END_OF("slotIntervalOk");
-}
-/*!
- Called when <Help> button is clicked
-*/
-void RegWidget::slotHelp()
-{
- BEGIN_OF("slotHelp()");
-
- if ( !myHelpWindow ) {
- myHelpWindow = new HelpWindow( this );
- myHelpWindow->installEventFilter( this );
- }
- myHelpWindow->show();
- myHelpWindow->raise();
- myHelpWindow->setActiveWindow();
-
- END_OF("slotHelp()") ;
-}
-
-/*!
- Called when user clicks on item in <Running> list
-*/
-void RegWidget::slotClientChanged( QListViewItem* item )
-{
- BEGIN_OF("slotClientChanged()") ;
-
- if ( item <= 0)
- return;
-
- blockSignals( true ); // for sure that item will not be deleted when refreshing
-
- int numeroItem = numitem(item->text(0), item->text(1), item->text(3), _serverclients);
- SCRUTE(numeroItem) ;
- SCRUTE(item->text(1)) ;
-
- ASSERT(numeroItem>=0) ;
- ASSERT((size_t)numeroItem<_serverclients->length()) ;
- const Registry::Infos & c_info=(*_serverclients)[numeroItem];
- ASSERT( c_info.name!=NULL);
-
- if ( !myInfoWindow ) {
- myInfoWindow = new InfoWindow( this );
- myInfoWindow->installEventFilter( this );
- }
- QString a = tr( "More about" ) + QString( " " ) + QString( c_info.name );
- myInfoWindow->setCaption(a);
- myInfoWindow->setText( RegWidget::setlongText( c_info) );
- myInfoWindow->show();
- myInfoWindow->raise();
- myInfoWindow->setActiveWindow();
-
- blockSignals( false ); // enabling signals again
-
- END_OF("slotClientChanged()") ;
- return ;
-}
-
-/*!
- Called when user clicks on item in <History> list
-*/
-void RegWidget::slotHistoryChanged( QListViewItem* item )
-{
-
- BEGIN_OF("slotHistoryChanged()") ;
-
- if ( item <= 0)
- return;
-
- blockSignals( true ); // for sure that item will not be deleted when refreshing
-
- int numeroItem = numitem(item->text(0), item->text(1), item->text(3), _serverhistory);
-
- SCRUTE(numeroItem) ;
- SCRUTE(item->text(1)) ;
- ASSERT(numeroItem>=0) ;
- ASSERT((size_t)numeroItem<_serverhistory->length()) ;
- const Registry::Infos & c_info=(*_serverhistory)[numeroItem];
- ASSERT( c_info.name!=NULL);
-
- if ( !myInfoWindow ) {
- myInfoWindow = new InfoWindow( this );
- myInfoWindow->installEventFilter( this );
- }
- QString a = tr( "More about" ) + QString( " " ) + QString( c_info.name );
- myInfoWindow->setCaption(a);
- myInfoWindow->setText( RegWidget::setlongText( c_info ) );
- myInfoWindow->show();
- myInfoWindow->raise();
- myInfoWindow->setActiveWindow();
-
- blockSignals( false ); // enabling signals again
-
- END_OF("slotHistoryChanged()") ;
- return ;
-}
-
-/*!
- Constructor
-*/
-InfoWindow::InfoWindow( QWidget* parent, const char* name )
- : QMainWindow( parent, name, WType_TopLevel | WDestructiveClose )
-{
- BEGIN_OF("InfoWindow");
- myTextView = new QTextView( this, "myTextView" );
- setCentralWidget( myTextView );
- setMinimumSize( 450, 250 );
- END_OF("InfoWindow");
-}
-
-/*!
- Sets text
-*/
-void InfoWindow::setText( const QString& text )
-{
- myTextView->setText( text );
-}
-
-/*!
- Key press event
-*/
-void InfoWindow::keyPressEvent( QKeyEvent * e )
-{
- QMainWindow::keyPressEvent( e );
- if ( e->key() == Key_Escape )
- close();
-}
-
-static const char* SEPARATOR = ":";
-
-QString findFile( QString filename )
-{
- QString dir;
- char* cenv;
-
- // Try ${HOME}/.salome/resources directory
- cenv = getenv( "HOME" );
- if ( cenv ) {
- dir.sprintf( "%s", cenv );
- if ( !dir.isEmpty() ) {
- dir = addSlash(dir) ;
- dir = dir + ".salome" ;
- dir = addSlash(dir) ;
- dir = dir + "resources" ;
- dir = addSlash(dir) ;
- QFileInfo fileInfo( dir + filename );
- if ( fileInfo.isFile() && fileInfo.exists() )
- return fileInfo.filePath();
- }
- }
- // Try ${SALOME_SITE_DIR}/share/salome/resources directory
- cenv = getenv( "SALOME_SITE_DIR" );
- if ( cenv ) {
- dir.sprintf( "%s", cenv );
- if ( !dir.isEmpty() ) {
- dir = addSlash(dir) ;
- dir = dir + "share" ;
- dir = addSlash(dir) ;
- cenv = getenv("SALOME_SITE_NAME");
- if (cenv) dir = dir + cenv;
- else dir = dir + "salome" ;
- dir = addSlash(dir) ;
- dir = dir + "resources" ;
- dir = addSlash(dir) ;
- QFileInfo fileInfo( dir + filename );
- if ( fileInfo.isFile() && fileInfo.exists() )
- return fileInfo.filePath();
- }
- }
- // Try ${KERNEL_ROOT_DIR}/share/salome/resources directory
- cenv = getenv( "KERNEL_ROOT_DIR" );
- if ( cenv ) {
- dir.sprintf( "%s", cenv );
- if ( !dir.isEmpty() ) {
- dir = addSlash(dir) ;
- dir = dir + "share" ;
- dir = addSlash(dir) ;
- dir = dir + "salome" ;
- dir = addSlash(dir) ;
- dir = dir + "resources" ;
- dir = addSlash(dir) ;
- dir = dir + "kernel" ;
- dir = addSlash(dir) ;
- QFileInfo fileInfo( dir + filename );
- if ( fileInfo.isFile() && fileInfo.exists() )
- return fileInfo.filePath();
- }
- }
-
- //SRN Added support for SALOMEGUI
- cenv = getenv( "SALOMEGUI_ROOT_DIR" );
- if ( cenv ) {
- dir.sprintf( "%s", cenv );
- if ( !dir.isEmpty() ) {
- dir = addSlash(dir) ;
- dir = dir + "share" ;
- dir = addSlash(dir) ;
- dir = dir + "salome" ;
- dir = addSlash(dir) ;
- dir = dir + "resources" ;
- dir = addSlash(dir) ;
- QFileInfo fileInfo( dir + filename );
- if ( fileInfo.isFile() && fileInfo.exists() )
- return fileInfo.filePath();
- }
- }
-
- // Try CSF_SaloameResources env.var directory ( or directory list )
- cenv = getenv( "CSF_SalomeResources" );
- if ( cenv ) {
- dir.sprintf( "%s", cenv );
- if ( !dir.isEmpty() ) {
- QStringList dirList = QStringList::split( SEPARATOR, dir, false ); // skip empty entries
- for ( int i = 0; i < dirList.count(); i++ ) {
- QFileInfo fileInfo( addSlash( dirList[ i ] ) + filename );
- if ( fileInfo.isFile() && fileInfo.exists() )
- return fileInfo.filePath();
- }
- }
- }
- return filename;
-}
-QString addSlash( const QString& path )
-{
- if (!path.isNull()) {
-#ifdef WNT
- QChar slash ('\\');
-#else
- QChar slash ('/');
-#endif
- if ( path.at(path.length()-1) != slash )
- return path + slash;
- }
- return path;
-}
+++ /dev/null
-// SALOME RegistryDisplay : GUI for Registry server implementation
-//
-// Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-//
-//
-// File : RegWidget.h
-// Author : Pascale NOYRET, EDF
-// Module : SALOME
-// $Header$
-
-# ifndef __REGWIDGET_H__
-# define __REGWIDGET_H__
-# include <qapplication.h>
-# include <qmainwindow.h>
-
-#include <SALOMEconfig.h>
-#include CORBA_CLIENT_HEADER(SALOME_Registry)
-
-#include <IntervalWindow.hxx>
-
-class QTabWidget;
-class QListView;
-class QListViewItem;
-class QWidget;
-class QTimer;
-class QCloseEvent;
-class QTextView;
-#if QT_VERSION > 300
-class QPushButton;
-#endif
-class HelpWindow;
-class InfoWindow;
-
-class RegWidget : public QMainWindow
-{
- Q_OBJECT
-
-public:
- RegWidget( CORBA::ORB_var &orb , QWidget *parent = 0, const char *name = 0 );
- ~RegWidget();
- void SetListe();
- void SetListeHistory();
- void InfoReg();
- void InfoHistory();
-
- bool eventFilter( QObject* object, QEvent* event );
-
- static RegWidget* GetRegWidget( CORBA::ORB_var &orb , QWidget *parent = 0, const char *name = 0 );
-
-public slots:
- void slotHelp();
- void slotListeSelect();
- void slotClientChanged( QListViewItem* );
- void slotHistoryChanged( QListViewItem* );
- void slotSelectRefresh();
- void slotIntervalOk();
-protected:
- static QString setlongText( const Registry::Infos &c_info );
- int numitem( const QString& name, const QString& pid, const QString& machine, const Registry::AllInfos* c_info );
- void closeEvent( QCloseEvent *e);
-
-protected :
- QListView* _clients;
- QListView* _history;
- QWidget* _parent;
- QTabWidget* _tabWidget;
- QPushButton* _refresh;
- QPushButton* _interval;
- QPushButton* _close;
- QTimer* _counter;
- Registry::AllInfos* _serverhistory;
- Registry::AllInfos* _serverclients;
- InfoWindow* myInfoWindow;
- HelpWindow* myHelpWindow;
- IntervalWindow* myIntervalWindow;
- int myRefreshInterval;
-
-private:
- const Registry::Components_var _VarComponents;
- static RegWidget* myRegWidgetPtr;
-};
-
-class InfoWindow : public QMainWindow {
-public:
- InfoWindow( QWidget* parent = 0, const char* name = 0);
-
- void setText( const QString& text );
- QTextView* textView() const { return myTextView; }
-
-protected:
- void keyPressEvent( QKeyEvent * e );
-
-private:
- QTextView* myTextView;
-
-};
-
-#endif
+++ /dev/null
-// SALOME RegistryDisplay : GUI for Registry server implementation
-//
-// Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-//
-//
-// File : RegWidgetFactory.cxx
-// Author : Pascale NOYRET, EDF
-// Module : SALOME
-// $Header$
-
-# include "RegWidget.h"
-# include "utilities.h"
-
-using namespace std;
-
-extern "C"
-{
-
-void OnGUIEvent( CORBA::ORB_var &orb, QWidget *parent, const char *name )
-{
- // N.B. parent can be 0
- RegWidget* ptrRegWidget = RegWidget::GetRegWidget( orb, parent, name );
- //ASSERT ( !ptrRegWidget );
- ptrRegWidget->show();
- ptrRegWidget->raise();
- ptrRegWidget->setActiveWindow();
- return;
-}
-
-}
--- /dev/null
+TEMPLATE =
+TARGET = ResourceExporter
+DESTDIR = ../../bin
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+INCLUDEPATH += ../../include ../Qtx ../SUIT
+LIBS += -L../../lib -lqtx -lsuit
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES +=
+
+SOURCES = ResourceExporter.cxx
+
*/
#include "SUIT_ResourceMgr.h"
-#include <qfile.h>
-#include <qdir.h>
-#include <qstringlist.h>
-#include <qapplication.h>
+#include <QFile>
+#include <QDir>
+#include <QStringList>
+#include <QApplication>
#include <iostream>
/*!
path += QString( "bin/salome/VERSION" );
QFile vf( path );
- if ( !vf.open( IO_ReadOnly ) )
+ if ( !vf.open( QIODevice::ReadOnly ) )
return QString::null;
- QString line;
- vf.readLine( line, 1024 );
+ QString line( vf.readLine( 1024 ) );
vf.close();
if ( line.isEmpty() )
line.remove( line.length() - 1, 1 );
QString ver;
- int idx = line.findRev( ":" );
+ int idx = line.lastIndexOf( ":" );
if ( idx != -1 )
- ver = line.mid( idx + 1 ).stripWhiteSpace();
+ ver = line.mid( idx + 1 ).trimmed();
return ver;
}
resMgr->setCurrentFormat( QString( "xml" ) );
resMgr->loadLanguage();
for ( int i = 1; i < argc; i ++ ) {
- QString anArg = QString( argv[i] ).stripWhiteSpace();
+ QString anArg = QString( argv[i] ).trimmed();
if ( anArg.startsWith( "-" ) ) {
anArg.remove( 0, 1 );
if ( anArg.contains( ":" ) ) {
- QStringList vals = QStringList::split( ":", anArg );
- QString section = vals[ 0 ].stripWhiteSpace();
- QString param = vals[ 1 ].stripWhiteSpace();
+ QStringList vals = anArg.split( ":", QString::SkipEmptyParts );
+ QString section = vals[ 0 ].trimmed();
+ QString param = vals[ 1 ].trimmed();
if ( section.isEmpty() || param.isEmpty() ) continue;
resMgr->remove( section, param );
}
}
else if ( anArg.contains( "+=" ) ) {
- QStringList vals = QStringList::split( "+=", anArg );
+ QStringList vals = anArg.split( "+=", QString::SkipEmptyParts );
if ( vals[ 0 ].contains( ":" ) ) {
- QStringList vals1 = QStringList::split( ":", vals[ 0 ] );
- QString section = vals1[ 0 ].stripWhiteSpace();
- QString param = vals1[ 1 ].stripWhiteSpace();
- QString newValue = vals [ 1 ].stripWhiteSpace();
+ QStringList vals1 = vals[ 0 ].split( ":", QString::SkipEmptyParts );
+ QString section = vals1[ 0 ].trimmed();
+ QString param = vals1[ 1 ].trimmed();
+ QString newValue = vals [ 1 ].trimmed();
QString separ = ","; // default separator
if ( newValue.contains( "|" ) ) {
- QStringList vals2 = QStringList::split( "|", newValue );
- newValue = vals2[ 0 ].stripWhiteSpace();
- separ = vals2[ 1 ].stripWhiteSpace();
+ QStringList vals2 = newValue.split( "|", QString::SkipEmptyParts );
+ newValue = vals2[ 0 ].trimmed();
+ separ = vals2[ 1 ].trimmed();
}
if ( section.isEmpty() || param.isEmpty() || newValue.isEmpty() || separ.isEmpty() ) continue;
QString value = resMgr->stringValue( section, param );
- QStringList valsOld = QStringList::split( separ, value );
- QStringList valsNew = QStringList::split( separ, newValue );
+ QStringList valsOld = value.split( separ, QString::SkipEmptyParts );
+ QStringList valsNew = newValue.split( separ, QString::SkipEmptyParts );
for ( int i = 0; i < (int)valsNew.count(); i++ )
if ( !valsOld.contains( valsNew[i] ) )
valsOld.append( valsNew[i] );
}
}
else if ( anArg.contains( "=" ) ) {
- QStringList vals = QStringList::split( "=", anArg );
+ QStringList vals = anArg.split( "=", QString::SkipEmptyParts );
if ( vals[ 0 ].contains( ":" ) ) {
- QStringList vals1 = QStringList::split( ":", vals[ 0 ] );
- QString section = vals1[ 0 ].stripWhiteSpace();
- QString param = vals1[ 1 ].stripWhiteSpace();
- QString value = vals [ 1 ].stripWhiteSpace();
+ QStringList vals1 = vals[ 0 ].split( ":", QString::SkipEmptyParts );
+ QString section = vals1[ 0 ].trimmed();
+ QString param = vals1[ 1 ].trimmed();
+ QString value = vals [ 1 ].trimmed();
if ( section.isEmpty() || param.isEmpty() ) continue;
resMgr->setValue( section, param, value );
}
include $(top_srcdir)/adm_local/unix/make_common_starter.am
-# Sip flags
-SIP_FLAGS = -t WS_X11 -t $(QT_VERS) $(PYQT_SIPFLAGS) -s ".cc" -c . -I $(PYQT_SIPS)
-
######################
# Library target
lib_LTLIBRARIES= libSalomePyQtGUI.la
-
-# Sip sources
-if IS_SIP_V4
SIP_SRC = sipSalomePyQtGUIcmodule.cc
SIP_FILES = SALOME_PYQT_GUI.sip
-else !IS_SIP_V4
-SIP_SRC = SalomePyQtGUIcmodule.cc
-SIP_FILES = SALOME_PYQT_GUI.sip
-endif
-EXTRA_DIST+= $(SIP_FILES)
+EXTRA_DIST += $(SIP_FILES)
salomeinclude_HEADERS = \
SALOME_PYQT_GUI.h \
# Custom build step: generate C++ wrapping according to $(SIP_FILES)
$(SIP_SRC): $(SIP_FILES)
- $(SIP) $(SIP_FLAGS) $<
+ $(SIP) $(PYQT_SIPFLAGS) $<
$(dist_libSalomePyQtGUI_la_SOURCES): $(SIP_SRC)
// ========================================================
// set dllexport type for Win platform
-#ifdef WNT
+#ifdef WIN32
#ifdef SALOME_PYQT_EXPORTS
#define SALOME_PYQT_EXPORT __declspec(dllexport)
#define SALOME_PYQT_EXPORT __declspec(dllimport)
#endif
-#else // WNT
+#else // WIN32
#define SALOME_PYQT_EXPORT
-#endif // WNT
+#endif // WIN32
// ========================================================
// avoid warning messages
-#ifdef WNT
+#ifdef WIN32
#pragma warning (disable : 4786)
#pragma warning (disable : 4251)
#endif
#include <qmenubar.h>
#include <qpopupmenu.h>
-#ifndef WIN32
-#include "SALOME_PYQT_SipDefs.h"
-#endif
#include "sipAPISalomePyQtGUI.h"
#include "sipqtQWidget.h"
// While the SalomePyQtGUI library is not imported in Python it's initialization function
// should be called manually (and only once) in order to initialize global sip data
// and to get C API from sip : sipBuildResult for example
-#if defined(SIP_VERS_v4_old) || defined(SIP_VERS_v4_new)
#define INIT_FUNCTION initSalomePyQtGUI
#if defined(SIP_STATIC_MODULE)
extern "C" void INIT_FUNCTION();
#else
PyMODINIT_FUNC INIT_FUNCTION();
#endif
-#else
-#define INIT_FUNCTION initlibSalomePyQtGUIc
-extern "C" void INIT_FUNCTION();
-#endif
/*!
* This function creates an instance of SALOME_PYQT_Module object by request
+++ /dev/null
-#define SIP_VERS_@SIP_VERS@
include $(top_srcdir)/adm_local/unix/make_common_starter.am
-# Sip flags
-SIP_FLAGS = -t WS_X11 -t $(QT_VERS) $(PYQT_SIPFLAGS) -s ".cc" -c . -I $(PYQT_SIPS)
-
# Sip common sources
-SIP_SRC = sipSalomePyQtSalomePyQt.cc \
- sipSalomePyQtSALOME_Selection.cc \
- sipSalomePyQtQtxAction.cc
-
-# Sip version-specific sources
-if IS_SIP_V4
-SIP_SRC += sipSalomePyQtcmodule.cc
-else !IS_SIP_V4
-SIP_SRC += SalomePyQtcmodule.cc
-endif
+SIP_SRC = sipSalomePyQtSalomePyQt.cc \
+ sipSalomePyQtSALOME_Selection.cc \
+ sipSalomePyQtQtxAction.cc \
+ sipSalomePyQtcmodule.cc
-# Sip/moc sources and Sip definition files
-if IS_SIP_V4
-if IS_SIP_NEW
-MOC_SRC =
-MOC_H =
-SIP_FILES = SalomePyQt_v4.sip
-else !IS_SIP_NEW
-MOC_SRC = sipSalomePyQtcmodule_moc.cxx
-MOC_H = sipSalomePyQtcmodule.h
-SIP_FILES = SalomePyQt_v4.sip
-endif
-else !IS_SIP_V4
+# Sip definition file
SIP_FILES = SalomePyQt.sip
-if IS_SIP_NEW
-MOC_SRC = SalomePyQtcmodule_moc.cxx
-MOC_H = SalomePyQtcmodule.h
-else !IS_SIP_NEW
-MOC_SRC = sipSalomePyQtProxySalomePyQt_moc.cxx
-MOC_H = sipSalomePyQtProxySalomePyQt.h
-endif
-endif
-EXTRA_DIST+= SalomePyQt.sip SalomePyQt_v4.sip
+EXTRA_DIST += SalomePyQt.sip
# Libraries targets
-MOC_FILES= SalomePyQt_moc.cxx
+MOC_FILES = SalomePyQt_moc.cxx
COMMON_CPP_FLAGS=$(QT_INCLUDES) $(SIP_INCLUDES) $(PYTHON_INCLUDES) \
$(CAS_CPPFLAGS) $(VTK_INCLUDES) $(OGL_INCLUDES) $(BOOST_CPPFLAGS) \
../../VTKViewer/libVTKViewer.la ../../TOOLSGUI/libToolsGUI.la \
../SALOME_PYQT_GUI/libSalomePyQtGUI.la
-if IS_SIP_V4
-
lib_LTLIBRARIES = libSalomePyQt.la
dist_libSalomePyQt_la_SOURCES= SalomePyQt.cxx
-nodist_libSalomePyQt_la_SOURCES= $(MOC_FILES) $(SIP_SRC) $(MOC_SRC)
+nodist_libSalomePyQt_la_SOURCES= $(MOC_FILES) $(SIP_SRC)
libSalomePyQt_la_CPPFLAGS = $(COMMON_CPP_FLAGS)
libSalomePyQt_la_LIBADD = $(COMMON_LIBS)
-else !IS_SIP_V4
-
-lib_LTLIBRARIES = libSalomePyQtcmodule.la
-dist_libSalomePyQtcmodule_la_SOURCES= SalomePyQt.cxx
-nodist_libSalomePyQtcmodule_la_SOURCES= $(MOC_FILES) $(SIP_SRC) $(MOC_SRC)
-libSalomePyQtcmodule_la_CPPFLAGS = $(MY_CPP_FLAGS)
-libSalomePyQtcmodule_la_LIBADD = $(COMMON_LIBS)
-
-endif
-
-if IS_SIP_V4
-else
-nodist_sharedpkgpython_PYTHON= SalomePyQt.py
-endif
-
# Custom build step: generate C++ wrapping according to $(SIP_FILES)
$(SIP_SRC): $(SIP_FILES)
- $(SIP) $(SIP_FLAGS) $<
-
-$(MOC_H): $(SIP_FILES)
- $(SIP) $(SIP_FLAGS) $<
+ $(SIP) $(PYQT_SIPFLAGS) $<
-if IS_SIP_V4
install-exec-hook: $(libdir)/SalomePyQt.so
$(libdir)/SalomePyQt.so:
(cd $(libdir); ln -s libSalomePyQt.so SalomePyQt.so;)
-else !IS_SIP_V4
-install-exec-hook: $(libdir)/SalomePyQtcmodule.so
-$(libdir)/SalomePyQt.so:
- (cd $(libdir); ln -sf libSalomePyQtcmodule.so SalomePyQt.so;)
-endif
-
-$(SIP_SRC): $(MOC_SRC)
+++ /dev/null
-//=============================================================================
-// File : SalomePyQt_v4.sip
-// Created : 25/04/05
-// Author : Vadim SANDLER
-// Project : SALOME
-// Copyright : 2003-2005 CEA/DEN, EDF R&D
-// $Header : $
-//=============================================================================
-
-%Module SalomePyQt
-
-%Import qtmod.sip
-
-class SALOME_Selection : QObject
-{
-%TypeHeaderCode
-#include <SalomePyQt.h>
-%End
-
-public:
- void Clear() /ReleaseGIL/ ;
- void ClearIObjects() /ReleaseGIL/ ;
- void ClearFilters() /ReleaseGIL/ ;
-
-private:
- SALOME_Selection( QObject* /TransferThis/ );
-
-signals:
- void currentSelectionChanged();
-};
-
-enum MenuName {
- File = 1,
- View = 2,
- Edit = 3,
- Preferences = 4,
- Tools = 5,
- Window = 6,
- Help = 7
-};
-
-enum WindowType {
- WT_ObjectBrowser,
- WT_PyConsole,
- WT_LogWindow,
- WT_User
-};
-
-enum PrefType {
- PT_Space,
- PT_Bool,
- PT_Color,
- PT_String,
- PT_Selector,
- PT_DblSpin,
- PT_IntSpin,
- PT_Double,
- PT_Integer,
- PT_GroupBox,
- PT_Font,
- PT_DirList,
- PT_File,
- PT_User
-};
-
-class QtxAction : QAction
-{
-%TypeHeaderCode
-#include <QtxAction.h>
-%End
-
-private:
- QtxAction(const QtxAction &);
-};
-
-class SalomePyQt
-{
-%TypeHeaderCode
-#include <SalomePyQt.h>
-%End
-
-public:
- static QWidget* getDesktop() /ReleaseGIL/ ;
- static QWidget* getMainFrame() /ReleaseGIL/ ;
- static QMenuBar* getMainMenuBar() /ReleaseGIL/ ;
- static QPopupMenu* getPopupMenu( const MenuName ) /ReleaseGIL/ ;
- static SALOME_Selection* getSelection() /Factory,ReleaseGIL/ ;
- static int getStudyId() /ReleaseGIL/ ;
- static void putInfo( const QString&, const int = 0 ) /ReleaseGIL/ ;
- static const QString getActiveComponent() /ReleaseGIL/ ;
- static void updateObjBrowser( const int = 0, bool = true ) /ReleaseGIL/ ;
-
- static QString getFileName ( QWidget*, const QString&, const QStringList&, const QString&, bool ) /ReleaseGIL/ ;
- static QStringList getOpenFileNames ( QWidget*, const QString&, const QStringList&, const QString& ) /ReleaseGIL/ ;
- static QString getExistingDirectory( QWidget*, const QString&, const QString& ) /ReleaseGIL/ ;
-
- static void helpContext( const QString&, const QString& ) /ReleaseGIL/ ;
-
- static bool dumpView( const QString& ) /ReleaseGIL/ ;
-
- static int defaultMenuGroup() /ReleaseGIL/ ;
-
- static int createTool( const QString& ) /ReleaseGIL/ ;
- static int createTool( const int, const int, const int = -1 ) /ReleaseGIL/ ;
- static int createTool( const int, const QString&, const int = -1 ) /ReleaseGIL/ ;
- static int createTool( QtxAction*, const int, const int = -1, const int = -1 ) /ReleaseGIL/ ;
- static int createTool( QtxAction*, const QString&, const int = -1, const int = -1 ) /ReleaseGIL/ ;
-
- static int createMenu( const QString&, const int,
- const int = -1, const int = -1, const int = -1 ) /ReleaseGIL/ ;
- static int createMenu( const QString&, const QString&,
- const int = -1, const int = -1, const int = -1 ) /ReleaseGIL/ ;
- static int createMenu( const int, const int,
- const int = -1, const int = -1 ) /ReleaseGIL/ ;
- static int createMenu( const int, const QString&,
- const int = -1, const int = -1 ) /ReleaseGIL/ ;
- static int createMenu( QtxAction*, const int, const int = -1,
- const int = -1, const int = -1 ) /ReleaseGIL/ ;
- static int createMenu( QtxAction*, const QString&, const int = -1,
- const int = -1, const int = -1 ) /ReleaseGIL/ ;
- static QtxAction* createSeparator() /ReleaseGIL/ ;
-
- static QtxAction* createAction( const int, const QString&,
- const QString& = QString::null, const QString& = QString::null,
- const QString& = QString::null, const int = 0, const bool = false ) /ReleaseGIL/ ;
-
- static QtxAction* action( const int ) /ReleaseGIL/ ;
- static int actionId( const QtxAction* ) /ReleaseGIL/ ;
-
- static bool clearMenu( const int = 0, const int = 0,
- const bool = true ) /ReleaseGIL/ ;
-
- static void addSetting ( const QString&, const QString&, const double ) /ReleaseGIL/ ;
- static void addSetting ( const QString&, const QString&, const int /Constrained/ ) /ReleaseGIL/ ;
- static void addSetting ( const QString&, const QString&, const bool, const int ) /ReleaseGIL/ ;
- static void addSetting ( const QString&, const QString&, const QString& ) /ReleaseGIL/ ;
- static void addSetting ( const QString&, const QString&, const QColor& ) /ReleaseGIL/ ;
- static int integerSetting( const QString&, const QString&, const int = 0 ) /ReleaseGIL/ ;
- static double doubleSetting ( const QString&, const QString&, const double = 0 ) /ReleaseGIL/ ;
- static bool boolSetting ( const QString&, const QString&, const bool = false ) /ReleaseGIL/ ;
- static QString stringSetting ( const QString&, const QString&, const QString& = QString("") ) /ReleaseGIL/ ;
- static QColor colorSetting ( const QString&, const QString&, const QColor& = QColor() ) /ReleaseGIL/ ;
- static void removeSetting ( const QString&, const QString& ) /ReleaseGIL/ ;
- static bool hasSetting ( const QString&, const QString& ) /ReleaseGIL/ ;
-
-// obsolete
- static void addStringSetting( const QString&, const QString&, bool = true ) /ReleaseGIL/ ;
- static void addIntSetting ( const QString&, const int, bool = true ) /ReleaseGIL/ ;
- static void addDoubleSetting( const QString&, const double, bool = true ) /ReleaseGIL/ ;
- static void addBoolSetting ( const QString&, const bool, bool = true ) /ReleaseGIL/ ;
- static void removeSettings ( const QString& ) /ReleaseGIL/ ;
- static QString getSetting ( const QString& ) /ReleaseGIL/ ;
-
- static int addGlobalPreference( const QString& ) /ReleaseGIL/ ;
- static int addPreference( const QString& ) /ReleaseGIL/ ;
- static int addPreference( const QString&,
- const int, const int = -1,
- const QString& = QString::null,
- const QString& = QString::null ) /ReleaseGIL/ ;
- static QVariant preferenceProperty( const int, const QString& ) /ReleaseGIL/ ;
- static void setPreferenceProperty( const int,
- const QString&,
- const QVariant& ) /ReleaseGIL/ ;
- static void addPreferenceProperty( const int,
- const QString&,
- const int,
- const QVariant& ) /ReleaseGIL/ ;
-
- static void message( const QString&, bool = true ) /ReleaseGIL/ ;
- static void clearMessages() /ReleaseGIL/ ;
-};
-I$(srcdir)/../OCCViewer -I$(srcdir)/../Qtx
libSOCC_la_LDFLAGS=$(QT_MT_LIBS)
-libSOCC_la_LIBADD= ../SUIT/libsuit.la ../OBJECT/libSalomeObject.la \
- ../Prs/libSalomePrs.la ../OCCViewer/libOCCViewer.la
+libSOCC_la_LIBADD=../Qtx/libqtx.la ../SUIT/libsuit.la ../OBJECT/libSalomeObject.la \
+ ../Prs/libSalomePrs.la ../OCCViewer/libOCCViewer.la
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-#ifdef WNT
+#ifdef WIN32
#ifdef SOCC_EXPORTS
#define SOCC_EXPORT __declspec(dllexport)
#else
#define SOCC_EXPORT
#endif
-#if defined WNT
+#if defined WIN32
#pragma warning ( disable: 4251 )
#endif
--- /dev/null
+TEMPLATE = lib
+TARGET = SOCC
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+CASROOT = $$(CASROOT)
+CAS_CPPFLAGS = $${CASROOT}/inc
+
+BOOST_CPPFLAGS = $$(BOOSTDIR)/include
+
+INCLUDEPATH += ../../include $${CAS_CPPFLAGS} $${BOOST_CPPFLAGS} ../Qtx ../SUIT ../OBJECT ../Prs ../OCCViewer
+LIBS += -L../../lib -lqtx -lsuit -lSalomeObject -lSalomePrs -lOCCViewer
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += SOCC_EXPORTS OCC_VERSION_MAJOR=6 OCC_VERSION_MINOR=1 OCC_VERSION_MAINTENANCE=1 LIN LINTEL CSFDB No_exception HAVE_CONFIG_H HAVE_LIMITS_H HAVE_WOK_CONFIG_H OCC_CONVERT_SIGNALS
+
+HEADERS = SOCC.h
+HEADERS += SOCC_ViewModel.h
+HEADERS += SOCC_Prs.h
+HEADERS += SOCC_ViewWindow.h
+
+SOURCES = SOCC_ViewModel.cxx
+SOURCES += SOCC_Prs.cxx
+SOURCES += SOCC_ViewWindow.cxx
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+INSTALLS += includes
// $Header$
#include "SOCC_Prs.h"
+
+#include <AIS_InteractiveObject.hxx>
+
using namespace std;
/*!
#include <SALOME_Prs.h>
-#include <AIS_InteractiveObject.hxx>
#include <AIS_ListOfInteractive.hxx>
+class Handle(AIS_InteractiveObject);
+
class SOCC_EXPORT SOCC_Prs : public SALOME_OCCPrs
{
public:
#include "SOCC_ViewWindow.h"
#include "SUIT_Session.h"
-#include "SUIT_Application.h"
+#include "SUIT_ResourceMgr.h"
+//#include "SUIT_Application.h"
//#include "ToolsGUI.h"
#include <SALOME_AISShape.hxx>
#include <SALOME_AISObject.hxx>
+#include <SALOME_InteractiveObject.hxx>
// Temporarily commented to avoid awful dependecy on SALOMEDS
// TODO: better mechanism of storing display/erse status in a study
Handle(SALOME_InteractiveObject) IO = aSh->getIO();
if ( IO->isSame( obj ) )
{
- aSh->setName( (char*)name.latin1() );
+ aSh->setName( name.toLatin1().data() );
break;
}
}
#include "SOCC.h"
#include "SALOME_Prs.h"
#include "OCCViewer_ViewModel.h"
-#include "SALOME_InteractiveObject.hxx"
+
+class Handle(SALOME_InteractiveObject);
class SOCC_EXPORT SOCC_Viewer: public OCCViewer_Viewer, public SALOME_View
{
SPlot2d_ViewWindow_moc.cxx
nodist_libSPlot2d_la_SOURCES = $(MOC_FILES)
-nodist_salomeres_DATA = SPlot2d_msg_en.qm
-
libSPlot2d_la_CPPFLAGS=$(QT_INCLUDES) $(CAS_CPPFLAGS) $(QWT_INCLUDES) $(BOOST_CPPFLAGS) \
-I$(srcdir)/../Qtx -I$(srcdir)/../SUIT -I$(srcdir)/../Plot2d -I$(srcdir)/../Prs \
-I$(srcdir)/../OBJECT
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-#ifdef WNT
+#ifdef WIN32
#ifdef SPLOT2D_EXPORTS
#define SPLOT2D_EXPORT __declspec(dllexport)
#else
#define SPLOT2D_EXPORT
#endif
-#if defined WNT
+#if defined WIN32
#pragma warning ( disable: 4251 )
#endif
--- /dev/null
+TEMPLATE = lib
+TARGET = SPlot2d
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+CASROOT = $$(CASROOT)
+CAS_CPPFLAGS = $${CASROOT}/inc
+
+CAS_KERNEL = -L$${CASROOT}/Linux/lib -lTKernel
+
+QWTHOME=$$(QWTHOME)
+QWTINC=$${QWTHOME}/include
+QWTLIB=$${QWTHOME}/lib
+
+BOOST_CPPFLAGS = $$(BOOSTDIR)/include
+
+INCLUDEPATH += ../../include $${CAS_CPPFLAGS} ../../include $${QWTINC} $${BOOST_CPPFLAGS}
+INCLUDEPATH += ../Qtx ../SUIT ../Plot2d ../Prs ../OBJECT
+unix:LIBS += -L$${QWTLIB} -lqwt
+win32:LIBS += /LIBPATH:$$(QWTLIB)
+LIBS += -L../../lib -lsuit -lPlot2d -lSalomePrs
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += SPLOT2D_EXPORTS
+
+HEADERS = SPlot2d.h
+HEADERS = SPlot2d_Curve.h
+HEADERS = SPlot2d_Prs.h
+HEADERS = SPlot2d_ViewModel.h
+HEADERS = SPlot2d_ViewWindow.h
+
+SOURCES = SPlot2d_Curve.cxx
+SOURCES += SPlot2d_Curve.cxx
+SOURCES += SPlot2d_Prs.cxx
+SOURCES += SPlot2d_ViewModel.cxx
+SOURCES += SPlot2d_ViewWindow.cxx
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+INSTALLS += includes
// Module : SUIT
#include "SPlot2d_Curve.h"
+#include <QString>
+#include <QColor>
+
using namespace std;
/*!
#include "Plot2d_Curve.h"
-#include <qstring.h>
-#include <qcolor.h>
-#include <qmemarray.h>
#ifndef _Handle_SALOME_InteractiveObject_HeaderFile
#include <Handle_SALOME_InteractiveObject.hxx>
#endif
#include "SALOME_InteractiveObject.hxx"
+class QString;
+class QColor;
+
class SPLOT2D_EXPORT SPlot2d_Curve : public Plot2d_Curve
{
public:
// Module : SUIT
#include "SPlot2d_Prs.h"
-#ifndef WNT
+#ifndef WIN32
using namespace std;
#endif
#include "SALOME_Prs.h"
#include "Plot2d_Prs.h"
-#include <qptrlist.h>
-
class Plot2d_Curve;
class SPLOT2D_EXPORT SPlot2d_Prs : public SALOME_Prs2d, public Plot2d_Prs
#include "SPlot2d_Prs.h"
#include "SUIT_Session.h"
#include "SUIT_Application.h"
+#include "SUIT_ViewManager.h"
//#include "utilities.h"
-#include "qapplication.h"
-#include <qtoolbar.h>
-#include <qtoolbutton.h>
-#include <qcursor.h>
-#include <qcolordialog.h>
-#include <qwt_math.h>
+#include <QApplication>
+#include <QToolBar>
+#include <QToolButton>
+#include <QCursor>
+#include <QColorDialog>
+
+//#include <qwt_math>
#include <qwt_plot_canvas.h>
+#include <qwt_plot_curve.h>
#include <stdlib.h>
using namespace std;
if( !aViewFrame )
return;
- QIntDictIterator<Plot2d_Curve> it( aViewFrame->getCurves() );
- for( ; it.current(); ++it )
+ CurveDict aCurves = aViewFrame->getCurves();
+ CurveDict::Iterator it = aCurves.begin();
+ for( ; it != aCurves.end(); ++it )
{
- SPlot2d_Curve* aCurve = dynamic_cast<SPlot2d_Curve*>( it.current() );
+ SPlot2d_Curve* aCurve = dynamic_cast<SPlot2d_Curve*>( it.value() );
if( aCurve && aCurve->hasIO() && aCurve->getIO()->isSame( IObject ) )
{
aCurve->setVerTitle( newName );
- int key = aViewFrame->hasCurve( aCurve );
- if( key )
- aViewFrame->setCurveTitle( key, newName );
+ it.key()->setTitle( newName );
}
if( aCurve && aCurve->hasTableIO() && aCurve->getTableIO()->isSame( IObject ) )
- aCurve->getTableIO()->setName( newName.latin1() );
+ aCurve->getTableIO()->setName( newName.toLatin1() );
}
aViewFrame->updateTitles();
}
SUIT_ViewManager* vm = getViewManager();
if ( vm )
{
- const QPtrVector<SUIT_ViewWindow>& wnds = vm->getViews();
+ const QVector<SUIT_ViewWindow*>& wnds = vm->getViews();
+
for ( uint i = 0; i < wnds.size(); i++ )
{
Plot2d_ViewWindow* pwnd = dynamic_cast<Plot2d_ViewWindow*>( wnds.at( i ) );
return 1;
else{
if(!IObject.IsNull()){
- QIntDictIterator<Plot2d_Curve> it(aViewFrame->getCurves());
- for(; it.current();++it) {
- SPlot2d_Curve* aCurve = dynamic_cast<SPlot2d_Curve*>(it.current());
- if(aCurve->hasIO() && aCurve->getTableIO()->isSame(IObject))
+ CurveDict aCurves = aViewFrame->getCurves();
+ CurveDict::Iterator it = aCurves.begin();
+ for( ; it != aCurves.end(); ++it ) {
+ SPlot2d_Curve* aCurve = dynamic_cast<SPlot2d_Curve*>( it.value() );
+ if(aCurve && aCurve->hasIO() && aCurve->getTableIO()->isSame(IObject))
return 1;
}
}
if(aViewFrame == NULL) return;
Plot2d_Curve* curve = getCurveByIO( IObject );
- QIntDictIterator<Plot2d_Curve> it( aViewFrame->getCurves() );
- for ( ; it.current(); ++it ) {
- if(it.current() != curve)
+ CurveDict aCurves = aViewFrame->getCurves();
+ CurveDict::Iterator it = aCurves.begin();
+ for( ; it != aCurves.end(); ++it ) {
+ if(it.value() != curve)
aViewFrame->eraseCurve( curve );
else
aViewFrame->updateCurve( curve, false );
Plot2d_ViewFrame* aViewFrame = getActiveViewFrame();
if(aViewFrame == NULL) return anIO;
- QIntDictIterator<Plot2d_Curve> it( aViewFrame->getCurves() );
- for ( ; it.current(); ++it ) {
- SPlot2d_Curve* aCurve = dynamic_cast<SPlot2d_Curve*>(it.current());
- if ( aCurve->hasIO() && !strcmp( aCurve->getIO()->getEntry(), Entry ) ) {
+ CurveDict aCurves = aViewFrame->getCurves();
+ CurveDict::Iterator it = aCurves.begin();
+ for( ; it != aCurves.end(); ++it ) {
+ SPlot2d_Curve* aCurve = dynamic_cast<SPlot2d_Curve*>(it.value());
+ if ( aCurve && aCurve->hasIO() && !strcmp( aCurve->getIO()->getEntry(), Entry ) ) {
anIO = aCurve->getIO();
break;
}
if ( !theIObject.IsNull() ) {
Plot2d_ViewFrame* aViewFrame = fr ? fr : getActiveViewFrame();
if(aViewFrame) {
- QIntDictIterator<Plot2d_Curve> it( aViewFrame->getCurves() );
- for ( ; it.current(); ++it ) {
- SPlot2d_Curve* aCurve = dynamic_cast<SPlot2d_Curve*>(it.current());
+ CurveDict aCurves = aViewFrame->getCurves();
+ CurveDict::Iterator it = aCurves.begin();
+ for( ; it != aCurves.end(); ++it ) {
+ SPlot2d_Curve* aCurve = dynamic_cast<SPlot2d_Curve*>( it.value() );
if(aCurve) {
if ( aCurve->hasIO() && aCurve->getIO()->isSame( theIObject ) )
return aCurve;
// 2) Display all curves displayed in cloned view
- QList<Plot2d_Curve> aCurves;
- clonedVF->getCurves( aCurves );
- QList<Plot2d_Curve>::const_iterator anIt = aCurves.begin(), aLast = aCurves.end();
-
- for( ; anIt!=aLast; anIt++ )
- if( clonedVF->isVisible( *anIt ) )
- newVF->displayCurve( *anIt, false );
+ CurveDict aCurves = clonedVF->getCurves();
+ CurveDict::Iterator anIt = aCurves.begin();
+ for( ; anIt != aCurves.end(); ++anIt )
+ {
+ SPlot2d_Curve* aCurve = dynamic_cast<SPlot2d_Curve*>( anIt.value() );
+ if( aCurve && clonedVF->isVisible( aCurve ) )
+ newVF->displayCurve( aCurve, false );
+ }
newVF->Repaint();
}
lib_LTLIBRARIES = libstd.la
-salomeinclude_HEADERS= \
- STD_Application.h \
- STD.h \
- STD_MDIDesktop.h \
- STD_SDIDesktop.h \
- STD_TabDesktop.h \
- STD_CloseDlg.h \
- STD_LoadStudiesDlg.h
+salomeinclude_HEADERS= \
+ STD.h \
+ STD_Application.h \
+ STD_MDIDesktop.h \
+ STD_SDIDesktop.h \
+ STD_TabDesktop.h
-dist_libstd_la_SOURCES=\
- STD_Application.cxx \
- STD_MDIDesktop.cxx \
- STD_SDIDesktop.cxx \
- STD_TabDesktop.cxx \
- STD_CloseDlg.cxx \
- STD_LoadStudiesDlg.cxx
+dist_libstd_la_SOURCES= \
+ STD_Application.cxx \
+ STD_MDIDesktop.cxx \
+ STD_SDIDesktop.cxx \
+ STD_TabDesktop.cxx
+
+MOC_FILES= \
+ STD_Application_moc.cxx \
+ STD_MDIDesktop_moc.cxx \
+ STD_SDIDesktop_moc.cxx \
+ STD_TabDesktop_moc.cxx
-MOC_FILES= \
- STD_Application_moc.cxx \
- STD_MDIDesktop_moc.cxx \
- STD_SDIDesktop_moc.cxx \
- STD_TabDesktop_moc.cxx \
- STD_CloseDlg_moc.cxx \
- STD_LoadStudiesDlg_moc.cxx
nodist_libstd_la_SOURCES= $(MOC_FILES)
-dist_salomeres_DATA=\
- resources/config \
- resources/cut.png \
- resources/copy.png \
- resources/close.png \
- resources/cursor_rotate.png \
- resources/cursor_zoom.png \
- resources/help.png \
- resources/new.png \
- resources/open.png \
- resources/print.png \
- resources/paste.png \
- resources/redo.png \
- resources/reset.png \
- resources/save.png \
- resources/undo_arrow.png \
- resources/undo.png \
+dist_salomeres_DATA= \
+ resources/config \
+ resources/cut.png \
+ resources/copy.png \
+ resources/close.png \
+ resources/cursor_rotate.png \
+ resources/cursor_zoom.png \
+ resources/help.png \
+ resources/new.png \
+ resources/open.png \
+ resources/print.png \
+ resources/paste.png \
+ resources/redo.png \
+ resources/reset.png \
+ resources/save.png \
+ resources/undo_arrow.png \
+ resources/undo.png \
resources/std.ini
-nodist_salomeres_DATA=\
- STD_images.qm \
+nodist_salomeres_DATA= \
+ STD_images.qm \
STD_msg_en.qm
libstd_la_CPPFLAGS=$(QT_INCLUDES) -I$(srcdir)/../SUIT -I$(srcdir)/../Qtx
libstd_la_LDFLAGS=$(QT_MT_LIBS)
-libstd_la_LIBADD=../SUIT/libsuit.la
+libstd_la_LIBADD=../Qtx/libqtx.la ../SUIT/libsuit.la
#ifndef STD_H
#define STD_H
-#if defined STD_EXPORTS
-#if defined WNT
-#define STD_EXPORT __declspec( dllexport )
+#if defined WIN32
+# if defined STD_EXPORTS
+# define STD_EXPORT __declspec( dllexport )
+# else
+# define STD_EXPORT __declspec( dllimport )
+# endif
#else
-#define STD_EXPORT
-#endif
-#else
-#if defined WNT
-#define STD_EXPORT __declspec( dllimport )
-#else
-#define STD_EXPORT
-#endif
+# define STD_EXPORT
#endif
#if defined SOLARIS
#define true 1
#endif
-#if defined WNT
+#if defined WIN32
#pragma warning ( disable: 4251 )
#endif
--- /dev/null
+TEMPLATE = lib
+TARGET = std
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+INCLUDEPATH += ../../include ../Qtx ../SUIT
+LIBS += -L../../lib -lqtx -lsuit
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += STD_EXPORTS
+
+HEADERS = STD.h
+HEADERS += STD_Application.h
+HEADERS += STD_MDIDesktop.h
+HEADERS += STD_SDIDesktop.h
+HEADERS += STD_TabDesktop.h
+
+SOURCES = STD_Application.cxx
+SOURCES += STD_MDIDesktop.cxx
+SOURCES += STD_SDIDesktop.cxx
+SOURCES += STD_TabDesktop.cxx
+
+TRANSLATIONS = resources/STD_images.ts \
+ resources/STD_msg_en.ts
+
+ICONS = resources/*.png
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+resources.files = $$ICONS resources/*.qm resources/*.xml resources/*.ini
+resources.path = ../../resources
+
+INSTALLS += includes resources
#include "STD_MDIDesktop.h"
-#include "STD_CloseDlg.h"
-
#include <SUIT_Tools.h>
+#include <SUIT_Study.h>
#include <SUIT_Desktop.h>
#include <SUIT_Session.h>
-#include <SUIT_ViewModel.h>
-#include <SUIT_Operation.h>
#include <SUIT_MessageBox.h>
+#include <SUIT_ViewManager.h>
#include <SUIT_ResourceMgr.h>
#include <QtxDockAction.h>
#include <QtxActionMenuMgr.h>
#include <QtxActionToolMgr.h>
-#include <QtxPopupMenu.h>
-
-#include <qmenubar.h>
-#include <qtoolbar.h>
-#include <qpopupmenu.h>
-#include <qstatusbar.h>
-#include <qfiledialog.h>
-#include <qapplication.h>
-#include <iostream>
+#include <QMenu>
+#include <QStatusBar>
+#include <QCloseEvent>
+#include <QFileDialog>
+#include <QApplication>
/*!Create and return new instance of STD_Application*/
extern "C" STD_EXPORT SUIT_Application* createApplication()
/*!Constructor.*/
STD_Application::STD_Application()
: SUIT_Application(),
-myEditEnabled( true ),
-myActiveViewMgr( 0 )
+ myActiveViewMgr( 0 ),
+ myExitConfirm( true ),
+ myEditEnabled( true )
{
- STD_MDIDesktop* desk = new STD_MDIDesktop();
-
- setDesktop( desk );
+ setDesktop( new STD_MDIDesktop() );
}
/*!Destructor.*/
clearViewManagers();
}
+/*! \retval requirement of exit confirmation*/
+bool STD_Application::exitConfirmation() const
+{
+ return myExitConfirm;
+}
+
+/*! Set the requirement of exit confirmation*/
+void STD_Application::setExitConfirmation( const bool on )
+{
+ myExitConfirm = on;
+}
+
/*! \retval QString "StdApplication"*/
QString STD_Application::applicationName() const
{
savePreferences();
SUIT_Study* study = activeStudy();
- if ( study ){
+ if ( study )
+ {
+ beforeCloseDoc( study );
+
study->closeDocument();
setActiveStudy( 0 );
delete study;
+
+ afterCloseDoc();
}
setDesktop( 0 );
-
+
SUIT_Application::closeApplication();
}
return;
}
- if ( !isPossibleToClose() )
+ bool closePermanently;
+ if ( !isPossibleToClose( closePermanently ) )
{
e->ignore();
return;
createAction( FileNewId, tr( "TOT_DESK_FILE_NEW" ),
resMgr->loadPixmap( "STD", tr( "ICON_FILE_NEW" ) ),
tr( "MEN_DESK_FILE_NEW" ), tr( "PRP_DESK_FILE_NEW" ),
- CTRL+Key_N, desk, false, this, SLOT( onNewDoc() ) );
+ Qt::CTRL+Qt::Key_N, desk, false, this, SLOT( onNewDoc() ) );
createAction( FileOpenId, tr( "TOT_DESK_FILE_OPEN" ),
resMgr->loadPixmap( "STD", tr( "ICON_FILE_OPEN" ) ),
tr( "MEN_DESK_FILE_OPEN" ), tr( "PRP_DESK_FILE_OPEN" ),
- CTRL+Key_O, desk, false, this, SLOT( onOpenDoc() ) );
+ Qt::CTRL+Qt::Key_O, desk, false, this, SLOT( onOpenDoc() ) );
createAction( FileCloseId, tr( "TOT_DESK_FILE_CLOSE" ),
resMgr->loadPixmap( "STD", tr( "ICON_FILE_CLOSE" ) ),
tr( "MEN_DESK_FILE_CLOSE" ), tr( "PRP_DESK_FILE_CLOSE" ),
- CTRL+Key_W, desk, false, this, SLOT( onCloseDoc() ) );
+ Qt::CTRL+Qt::Key_W, desk, false, this, SLOT( onCloseDoc() ) );
- createAction( FileExitId, tr( "TOT_DESK_FILE_EXIT" ), QIconSet(),
+ createAction( FileExitId, tr( "TOT_DESK_FILE_EXIT" ), QIcon(),
tr( "MEN_DESK_FILE_EXIT" ), tr( "PRP_DESK_FILE_EXIT" ),
- CTRL+Key_Q, desk, false, this, SLOT( onExit() ) );
+ Qt::CTRL+Qt::Key_Q, desk, false, this, SLOT( onExit() ) );
createAction( FileSaveId, tr( "TOT_DESK_FILE_SAVE" ),
resMgr->loadPixmap( "STD", tr( "ICON_FILE_SAVE" ) ),
tr( "MEN_DESK_FILE_SAVE" ), tr( "PRP_DESK_FILE_SAVE" ),
- CTRL+Key_S, desk, false, this, SLOT( onSaveDoc() ) );
+ Qt::CTRL+Qt::Key_S, desk, false, this, SLOT( onSaveDoc() ) );
- createAction( FileSaveAsId, tr( "TOT_DESK_FILE_SAVEAS" ), QIconSet(),
+ createAction( FileSaveAsId, tr( "TOT_DESK_FILE_SAVEAS" ), QIcon(),
tr( "MEN_DESK_FILE_SAVEAS" ), tr( "PRP_DESK_FILE_SAVEAS" ),
- CTRL+Key_A, desk, false, this, SLOT( onSaveAsDoc() ) );
+ Qt::CTRL+Qt::Key_A, desk, false, this, SLOT( onSaveAsDoc() ) );
createAction( EditCopyId, tr( "TOT_DESK_EDIT_COPY" ),
resMgr->loadPixmap( "STD", tr( "ICON_EDIT_COPY" ) ),
tr( "MEN_DESK_EDIT_COPY" ), tr( "PRP_DESK_EDIT_COPY" ),
- CTRL+Key_C, desk, false, this, SLOT( onCopy() ) );
+ Qt::CTRL+Qt::Key_C, desk, false, this, SLOT( onCopy() ) );
createAction( EditPasteId, tr( "TOT_DESK_EDIT_PASTE" ),
resMgr->loadPixmap( "STD", tr( "ICON_EDIT_PASTE" ) ),
tr( "MEN_DESK_EDIT_PASTE" ), tr( "PRP_DESK_EDIT_PASTE" ),
- CTRL+Key_V, desk, false, this, SLOT( onPaste() ) );
+ Qt::CTRL+Qt::Key_V, desk, false, this, SLOT( onPaste() ) );
QAction* a = createAction( ViewStatusBarId, tr( "TOT_DESK_VIEW_STATUSBAR" ),
- QIconSet(), tr( "MEN_DESK_VIEW_STATUSBAR" ),
- tr( "PRP_DESK_VIEW_STATUSBAR" ), SHIFT+Key_S, desk, true );
- a->setOn( desk->statusBar()->isVisibleTo( desk ) );
+ QIcon(), tr( "MEN_DESK_VIEW_STATUSBAR" ),
+ tr( "PRP_DESK_VIEW_STATUSBAR" ), Qt::SHIFT+Qt::Key_S, desk, true );
+ a->setChecked( desk->statusBar()->isVisibleTo( desk ) );
connect( a, SIGNAL( toggled( bool ) ), this, SLOT( onViewStatusBar( bool ) ) );
- createAction( NewWindowId, tr( "TOT_DESK_NEWWINDOW" ), QIconSet(),
+ createAction( NewWindowId, tr( "TOT_DESK_NEWWINDOW" ), QIcon(),
tr( "MEN_DESK_NEWWINDOW" ), tr( "PRP_DESK_NEWWINDOW" ), 0, desk );
- createAction( HelpAboutId, tr( "TOT_DESK_HELP_ABOUT" ), QIconSet(),
+ createAction( HelpAboutId, tr( "TOT_DESK_HELP_ABOUT" ), QIcon(),
tr( "MEN_DESK_HELP_ABOUT" ), tr( "PRP_DESK_HELP_ABOUT" ),
- SHIFT+Key_A, desk, false, this, SLOT( onHelpAbout() ) );
+ Qt::SHIFT+Qt::Key_A, desk, false, this, SLOT( onHelpAbout() ) );
- QtxDockAction* da = new QtxDockAction( tr( "TOT_DOCK_WINDOWS" ), tr( "MEN_DOCK_WINDOWS" ), desk );
- registerAction( ViewWindowsId, da );
- da->setAutoPlace( false );
+
+ QtxDockAction* dwa = new QtxDockAction( tr( "TOT_DOCKWINDOWS" ), tr( "MEN_DOCKWINDOWS" ), desk );
+ dwa->setDockType( QtxDockAction::DockWidget );
+ registerAction( ViewWindowsId, dwa );
+
+ QtxDockAction* tba = new QtxDockAction( tr( "TOT_TOOLBARS" ), tr( "MEN_TOOLBARS" ), desk );
+ tba->setDockType( QtxDockAction::ToolBar );
+ registerAction( ViewToolBarsId, tba );
// Create menus
createMenu( EditPasteId, editMenu );
createMenu( separator(), editMenu );
+ createMenu( ViewToolBarsId, viewMenu, 0 );
createMenu( ViewWindowsId, viewMenu, 0 );
createMenu( separator(), viewMenu, -1, 10 );
createMenu( ViewStatusBarId, viewMenu, 10 );
/*!Opens new application*/
void STD_Application::onNewDoc()
{
- QApplication::setOverrideCursor( Qt::waitCursor );
+ onNewDoc( QString() );
+}
+/*!Opens new application*/
+bool STD_Application::onNewDoc( const QString& name )
+{
+ QApplication::setOverrideCursor( Qt::WaitCursor );
+
+ bool res = true;
if ( !activeStudy() )
{
createEmptyStudy();
- activeStudy()->createDocument();
- studyCreated( activeStudy() );
+ res = activeStudy()->createDocument( name );
+ if ( res )
+ studyCreated( activeStudy() );
+ else
+ {
+ delete activeStudy();
+ setActiveStudy( 0 );
+ }
}
else
{
SUIT_Application* aApp = startApplication( 0, 0 );
if ( aApp->inherits( "STD_Application" ) )
- ((STD_Application*)aApp)->onNewDoc();
+ res = ((STD_Application*)aApp)->onNewDoc( name );
else
{
aApp->createEmptyStudy();
- aApp->activeStudy()->createDocument();
+ res = aApp->activeStudy()->createDocument( name );
}
+ if ( !res )
+ aApp->closeApplication();
}
QApplication::restoreOverrideCursor();
+
+ return res;
}
/*!Put file name from file dialog to onOpenDoc(const QString&) function*/
/*! \retval true, if document was opened successful, else false.*/
bool STD_Application::onOpenDoc( const QString& aName )
{
- QApplication::setOverrideCursor( Qt::waitCursor );
+ QApplication::setOverrideCursor( Qt::WaitCursor );
bool res = true;
if ( !activeStudy() )
{
// if study exists - open in new desktop. Check: is the same file is opened?
SUIT_Session* aSession = SUIT_Session::session();
- QPtrList<SUIT_Application> aAppList = aSession->applications();
+ QList<SUIT_Application*> aAppList = aSession->applications();
bool isAlreadyOpen = false;
SUIT_Application* aApp = 0;
- for ( QPtrListIterator<SUIT_Application> it( aAppList ); it.current() && !isAlreadyOpen; ++it )
+ for ( QList<SUIT_Application*>::iterator it = aAppList.begin(); it != aAppList.end() && !isAlreadyOpen; ++it )
{
- aApp = it.current();
+ aApp = *it;
if ( aApp->activeStudy()->studyName() == aName )
isAlreadyOpen = true;
}
aApp->closeApplication();
}
else
- aApp->desktop()->setActiveWindow();
+ aApp->desktop()->activateWindow();
}
QApplication::restoreOverrideCursor();
{
// if study exists - load in new desktop. Check: is the same file is loaded?
SUIT_Session* aSession = SUIT_Session::session();
- QPtrList<SUIT_Application> aAppList = aSession->applications();
+ QList<SUIT_Application*> aAppList = aSession->applications();
bool isAlreadyOpen = false;
SUIT_Application* aApp = 0;
- for ( QPtrListIterator<SUIT_Application> it( aAppList ); it.current() && !isAlreadyOpen; ++it )
+ for ( QList<SUIT_Application*>::iterator it = aAppList.begin(); it != aAppList.end() && !isAlreadyOpen; ++it )
{
- aApp = it.current();
+ aApp = *it;
if ( aApp->activeStudy()->studyName() == aName )
isAlreadyOpen = true;
}
res = aApp->useStudy( aName );
}
else
- aApp->desktop()->setActiveWindow();
+ aApp->desktop()->activateWindow();
}
return res;
}
/*!Close document, if it's possible.*/
void STD_Application::onCloseDoc( bool ask )
{
- if ( ask && !isPossibleToClose() )
+ bool closePermanently = true;
+
+ if ( ask && !isPossibleToClose( closePermanently ) )
return;
SUIT_Study* study = activeStudy();
beforeCloseDoc( study );
if ( study )
- study->closeDocument(myClosePermanently);
+ study->closeDocument( closePermanently );
clearViewManagers();
delete study;
int aNbStudies = 0;
- QPtrList<SUIT_Application> apps = SUIT_Session::session()->applications();
- for ( unsigned i = 0; i < apps.count(); i++ )
+ QList<SUIT_Application*> apps = SUIT_Session::session()->applications();
+ for ( int i = 0; i < apps.count(); i++ )
aNbStudies += apps.at( i )->getNbStudies();
- // STV: aNbStudies - number of currently existing studies (exclude currently closed)
- // STV: aNbStudies should be compared with 0.
if ( aNbStudies )
{
savePreferences();
/*!Check the application on closing.
* \retval true if possible, else false
*/
-bool STD_Application::isPossibleToClose()
+bool STD_Application::isPossibleToClose( bool& closePermanently )
{
- myClosePermanently = true; //SRN: BugID: IPAL9021
if ( activeStudy() )
{
activeStudy()->abortAllOperations();
if ( activeStudy()->isModified() )
{
- QString sName = activeStudy()->studyName().stripWhiteSpace();
- QString msg = sName.isEmpty() ? tr( "INF_DOC_MODIFIED" ) : tr ( "INF_DOCUMENT_MODIFIED" ).arg( sName );
-
- //SRN: BugID: IPAL9021: Begin
- STD_CloseDlg dlg(desktop());
- switch( dlg.exec() )
- {
- case 1:
- if ( activeStudy()->isSaved() )
- onSaveDoc();
- else if ( !onSaveAsDoc() )
- return false;
- break;
- case 2:
- break;
- case 3:
- myClosePermanently = false;
- break;
- case 4:
- default:
- return false;
- }
- //SRN: BugID: IPAL9021: End
+ QString sName = activeStudy()->studyName().trimmed();
+ return closeAction( closeChoice( sName ), closePermanently );
}
}
return true;
}
+int STD_Application::closeChoice( const QString& docName )
+{
+ int answer = SUIT_MessageBox::question( desktop(), tr( "CLOSE_STUDY" ), tr( "CLOSE_QUESTION" ).arg( docName ),
+ SUIT_MessageBox::Save | SUIT_MessageBox::Discard | SUIT_MessageBox::Cancel,
+ SUIT_MessageBox::Save );
+
+ int res = CloseCancel;
+ if ( answer == SUIT_MessageBox::Save )
+ res = CloseSave;
+ else if ( answer == SUIT_MessageBox::Discard )
+ res = CloseDiscard;
+
+ return res;
+}
+
+bool STD_Application::closeAction( const int choice, bool& closePermanently )
+{
+ bool res = true;
+ switch( choice )
+ {
+ case CloseSave:
+ if ( activeStudy()->isSaved() )
+ onSaveDoc();
+ else if ( !onSaveAsDoc() )
+ res = false;
+ break;
+ case CloseDiscard:
+ break;
+ case CloseCancel:
+ default:
+ res = false;
+ }
+
+ return res;
+}
+
/*!Save document if all ok, else error message.*/
void STD_Application::onSaveDoc()
{
{
putInfo( tr( "INF_DOC_SAVING" ) + activeStudy()->studyName() );
- QApplication::setOverrideCursor( Qt::waitCursor );
+ QApplication::setOverrideCursor( Qt::WaitCursor );
isOk = activeStudy()->saveDocument();
{
putInfo( "" );
// displaying a message box as SUIT_Validator in case file can't be written (the most frequent case)
- SUIT_MessageBox::error1( desktop(),
- tr( "ERR_ERROR" ),
- tr( "ERR_PERMISSION_DENIED" ).arg( activeStudy()->studyName() ),
- tr( "BUT_OK" ) );
+ SUIT_MessageBox::critical( desktop(), tr( "ERR_ERROR" ),
+ tr( "ERR_PERMISSION_DENIED" ).arg( activeStudy()->studyName() ) );
}
else
putInfo( tr( "INF_DOC_SAVED" ).arg( "" ) );
if ( aName.isNull() )
return false;
- QApplication::setOverrideCursor( Qt::waitCursor );
+ QApplication::setOverrideCursor( Qt::WaitCursor );
putInfo( tr( "INF_DOC_SAVING" ) + aName );
isOk = study->saveDocumentAs( aName );
QApplication::restoreOverrideCursor();
if ( !isOk )
- SUIT_MessageBox::error1( desktop(), tr( "ERROR" ),
- tr( "INF_DOC_SAVING_FAILS" ).arg( aName ),
- tr( "BUT_OK" ) );
+ SUIT_MessageBox::critical( desktop(), tr( "ERROR" ), tr( "INF_DOC_SAVING_FAILS" ).arg( aName ) );
}
studySaved( activeStudy() );
/*!Closing session.*/
void STD_Application::onExit()
{
- int aAnswer = SUIT_MessageBox::info2( desktop(), tr( "INF_DESK_EXIT" ), tr( "QUE_DESK_EXIT" ),
- tr( "BUT_OK" ), tr( "BUT_CANCEL" ), 1, 2, 2 );
- if ( aAnswer == 1 )
+ int aAnswer = 1;
+ if ( exitConfirmation() )
+ aAnswer = SUIT_MessageBox::question( desktop(), tr( "INF_DESK_EXIT" ), tr( "QUE_DESK_EXIT" ),
+ SUIT_MessageBox::Ok | SUIT_MessageBox::Cancel, SUIT_MessageBox::Cancel );
+ if ( aAnswer == SUIT_MessageBox::Ok )
SUIT_Session::session()->closeSession();
}
if ( activeStudy() )
{
- QString sName = SUIT_Tools::file( activeStudy()->studyName().stripWhiteSpace(), false );
+ QString sName = SUIT_Tools::file( activeStudy()->studyName().trimmed(), false );
if ( !sName.isEmpty() )
aTitle += QString( " - [%1]" ).arg( sName );
}
- desktop()->setCaption( aTitle );
+ desktop()->setWindowTitle( aTitle );
}
/*!Update commands status.*/
SUIT_ViewManager* STD_Application::viewManager( const QString& vmType ) const
{
SUIT_ViewManager* vm = 0;
- for ( QPtrListIterator<SUIT_ViewManager> it( myViewMgrs ); it.current() && !vm; ++it )
+ for ( QList<SUIT_ViewManager*>::const_iterator it = myViewMgrs.begin(); it != myViewMgrs.end() && !vm; ++it )
{
- if ( it.current()->getType() == vmType )
- vm = it.current();
+ if ( (*it)->getType() == vmType )
+ vm = *it;
}
return vm;
}
*/
void STD_Application::viewManagers( const QString& vmType, ViewManagerList& lst ) const
{
- for ( QPtrListIterator<SUIT_ViewManager> it( myViewMgrs ); it.current(); ++it )
- if ( it.current()->getType() == vmType )
- lst.append( it.current() );
+ for ( QList<SUIT_ViewManager*>::const_iterator it = myViewMgrs.begin(); it != myViewMgrs.end(); ++it )
+ {
+ if ( (*it)->getType() == vmType )
+ lst.append( *it );
+ }
}
/*!\param lst - output list of all view managers.*/
void STD_Application::viewManagers( ViewManagerList& lst ) const
{
- for ( QPtrListIterator<SUIT_ViewManager> it( myViewMgrs ); it.current(); ++it )
- lst.append( it.current() );
+ for ( QList<SUIT_ViewManager*>::const_iterator it = myViewMgrs.begin(); it != myViewMgrs.end(); ++it )
+ lst.append( *it );
}
/*!\retval ViewManagerList - const list of all view managers.*/
vm->disconnectPopupRequest( this, SLOT( onConnectPopupRequest( SUIT_PopupClient*, QContextMenuEvent* ) ) );
disconnect( vm, SIGNAL( activated( SUIT_ViewManager* ) ),
this, SLOT( onViewManagerActivated( SUIT_ViewManager* ) ) );
- myViewMgrs.removeRef( vm );
+ myViewMgrs.removeAll( vm );
if ( myActiveViewMgr == vm )
myActiveViewMgr = 0;
ViewManagerList lst;
viewManagers( lst );
- for ( QPtrListIterator<SUIT_ViewManager> it( lst ); it.current(); ++it ) {
- QGuardedPtr<SUIT_ViewManager> vm = it.current();
+ for ( QList<SUIT_ViewManager*>::iterator it = lst.begin(); it != lst.end(); ++it )
+ {
+ QPointer<SUIT_ViewManager> vm = *it;
removeViewManager( vm );
delete vm;
}
/*!\retval TRUE, if view manager \a vm, already in view manager list (\a myViewMgrs).*/
bool STD_Application::containsViewManager( SUIT_ViewManager* vm ) const
{
- return myViewMgrs.contains( vm ) > 0;
+ return myViewMgrs.contains( vm );
}
/*!Private slot, sets active manager to \vm, if \vm in view managers list.*/
/*!Call SUIT_MessageBox::info1(...) with about information.*/
void STD_Application::onHelpAbout()
{
- SUIT_MessageBox::info1( desktop(), tr( "About" ), tr( "ABOUT_INFO" ), "&OK" );
+ SUIT_MessageBox::information( desktop(), tr( "About" ), tr( "ABOUT_INFO" ) );
}
/*!Create empty study. \n
void STD_Application::createEmptyStudy()
{
SUIT_Application::createEmptyStudy();
-
- SUIT_ViewManager* vm = new SUIT_ViewManager( activeStudy(), desktop(), new SUIT_ViewModel() );
-
- addViewManager( vm );
}
/*!Sets active manager to \vm, if \vm in view managers list.*/
/*!Public slot. */
void STD_Application::onConnectPopupRequest( SUIT_PopupClient* client, QContextMenuEvent* e )
{
- QtxPopupMenu* popup = new QtxPopupMenu();
+ QMenu* popup = new QMenu();
// fill popup by own items
QString title;
contextMenuPopup( client->popupClientType(), popup, title );
- popup->setTitleText( title );
+ popup->setTitle( title );
- popup->insertSeparator();
+ popup->addSeparator();
// add items from popup client
client->contextMenuPopup( popup );
SUIT_Tools::simplifySeparators( popup );
- if ( popup->count() )
+ if ( !popup->actions().isEmpty() )
popup->exec( e->globalPos() );
delete popup;
}
-#include <qregexp.h>
-
/*!\retval QString - return file name from dialog.*/
QString STD_Application::getFileName( bool open, const QString& initial, const QString& filters,
const QString& caption, QWidget* parent )
if ( !parent )
parent = desktop();
if ( open )
- {
- return QFileDialog::getOpenFileName( initial, filters, parent, 0, caption );
- }
+ return QFileDialog::getOpenFileName( parent, caption, initial, filters );
else
{
QString aName;
while ( !isOk )
{
// It is preferrable to use OS-specific file dialog box here !!!
- aName = QFileDialog::getSaveFileName( anOldPath, filters, parent, 0, caption, &aUsedFilter );
+ aName = QFileDialog::getSaveFileName( parent, caption, anOldPath, filters, &aUsedFilter );
if ( aName.isNull() )
isOk = true;
else
{
- int aEnd = aUsedFilter.findRev( ')' );
- int aStart = aUsedFilter.findRev( '(', aEnd );
- QString wcStr = aUsedFilter.mid( aStart + 1, aEnd - aStart - 1 );
+ int aEnd = aUsedFilter.lastIndexOf( ')' );
+ int aStart = aUsedFilter.lastIndexOf( '(', aEnd );
+ QString wcStr = aUsedFilter.mid( aStart + 1, aEnd - aStart - 1 );
int idx = 0;
QStringList extList;
QRegExp rx( "[\b\\*]*\\.([\\w]+)" );
- while ( ( idx = rx.search( wcStr, idx ) ) != -1 )
+ while ( ( idx = rx.indexIn( wcStr, idx ) ) != -1 )
{
extList.append( rx.cap( 1 ) );
idx += rx.matchedLength();
}
- if ( !extList.isEmpty() && !extList.contains( QFileInfo( aName ).extension() ) )
+ if ( !extList.isEmpty() && !extList.contains( SUIT_Tools::extension( aName ) ) )
aName += QString( ".%1" ).arg( extList.first() );
- if ( QFileInfo( aName ).exists() )
+ if ( QFileInfo( aName ).exists() )
{
- int aAnswer = SUIT_MessageBox::warn3( desktop(), tr( "TIT_FILE_SAVEAS" ),
- tr( "MSG_FILE_EXISTS" ).arg( aName ),
- tr( "BUT_YES" ), tr( "BUT_NO" ), tr( "BUT_CANCEL" ), 1, 2, 3, 1 );
- if ( aAnswer == 3 )
+ int aAnswer = SUIT_MessageBox::question( desktop(), tr( "TIT_FILE_SAVEAS" ),
+ tr( "MSG_FILE_EXISTS" ).arg( aName ),
+ SUIT_MessageBox::Yes | SUIT_MessageBox::No | SUIT_MessageBox::Cancel, SUIT_MessageBox::Yes );
+ if ( aAnswer == SUIT_MessageBox::Cancel )
{ // cancelled
aName = QString::null;
- isOk = true;
+ isOk = true;
}
- else if ( aAnswer == 2 ) // not save to this file
- anOldPath = aName; // not to return to the same initial dir at each "while" step
- else // overwrite the existing file
- isOk = true;
+ else if ( aAnswer == SUIT_MessageBox::No ) // not save to this file
+ anOldPath = aName; // not to return to the same initial dir at each "while" step
+ else // overwrite the existing file
+ isOk = true;
}
- else
- isOk = true;
+ else
+ isOk = true;
}
}
return aName;
{
if ( !parent )
parent = desktop();
- return QFileDialog::getExistingDirectory( initial, parent, 0, caption, true );
+
+ return QFileDialog::getExistingDirectory( parent, caption, initial );
}
/*!
#include <SUIT_Application.h>
-#include <SUIT_Desktop.h>
-#include <SUIT_ViewManager.h>
+#include <QList>
-#include <qmap.h>
-#include <qptrlist.h>
+class QMenu;
+class QCloseEvent;
+class QContextMenuEvent;
class QToolBar;
class QtxAction;
-class QPopupMenu;
class SUIT_Operation;
class SUIT_ViewWindow;
class SUIT_ToolWindow;
+class SUIT_Desktop;
+class SUIT_ViewManager;
+class SUIT_PopupClient;
-typedef QPtrList<SUIT_ViewManager> ViewManagerList;
+typedef QList<SUIT_ViewManager*> ViewManagerList;
#if defined WIN32
#pragma warning( disable: 4251 )
{
Q_OBJECT
+public:
+ enum { FileNewId, FileOpenId, FileCloseId, FileSaveId, FileSaveAsId, FileExitId,
+ ViewWindowsId, ViewToolBarsId, ViewStatusBarId, NewWindowId,
+ EditCutId, EditCopyId, EditPasteId, HelpAboutId, UserID };
+
+ enum { CloseSave, CloseDiscard, CloseCancel };
+
public:
STD_Application();
virtual ~STD_Application();
virtual QString applicationName() const;
- virtual bool isPossibleToClose();
+ virtual bool isPossibleToClose( bool& );
virtual bool useFile( const QString& );
virtual void createEmptyStudy();
virtual QString getFileFilter() const { return QString::null; }
virtual QString getFileName( bool open, const QString& initial, const QString& filters,
- const QString& caption, QWidget* parent );
+ const QString& caption, QWidget* parent );
QString getDirectory( const QString& initial, const QString& caption, QWidget* parent );
virtual void start();
virtual void closeApplication();
- virtual void contextMenuPopup( const QString&, QPopupMenu*, QString& ) {}
+ virtual void contextMenuPopup( const QString&, QMenu*, QString& ) {}
+
+ bool exitConfirmation() const;
+ void setExitConfirmation( const bool );
signals:
/*!emit that view manager added*/
public slots:
virtual void onNewDoc();
+ virtual bool onNewDoc( const QString& );
+
virtual void onCloseDoc( bool ask = true );
virtual void onSaveDoc();
virtual bool onSaveAsDoc();
MenuHelpId = 7
};
- enum { FileNewId, FileOpenId, FileCloseId,
- FileSaveId, FileSaveAsId, FileExitId,
- ViewStatusBarId, ViewWindowsId, NewWindowId,
- EditCutId, EditCopyId, EditPasteId,
- HelpAboutId,
- UserID
- };
-
protected:
virtual void createActions();
virtual void updateDesktopTitle();
virtual void setActiveViewManager( SUIT_ViewManager* );
+ virtual bool closeAction( const int, bool& );
+ virtual int closeChoice( const QString& );
+
private:
ViewManagerList myViewMgrs;
SUIT_ViewManager* myActiveViewMgr;
private:
+ bool myExitConfirm;
bool myEditEnabled;
- bool myClosePermanently;
};
#if defined WIN32
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-#include "STD_CloseDlg.h"
-
-#include <qlabel.h>
-#include <qlayout.h>
-#include <qpushbutton.h>
-#include <qmessagebox.h>
-#include <qhbuttongroup.h>
-
-#ifndef WNT
-using namespace std;
-#endif
-
-/*!
- * \brief creates a Close dialog box
- * \param parent a parent widget
- * \param modal bool argument, if true the dialog box is a modal dialog box
- * \param f style flags
- */
-
-STD_CloseDlg::STD_CloseDlg( QWidget* parent, bool modal, WFlags f )
-: QDialog( parent, "", true, WStyle_Customize | WStyle_NormalBorder | WStyle_Title | WStyle_SysMenu )
-{
- setSizeGripEnabled( true );
- setCaption( tr( "CLOSE_DLG_CAPTION" ) );
-
- QVBoxLayout* m_vbL = new QVBoxLayout( this );
- m_vbL->setMargin( 11 );
- m_vbL->setSpacing( 6 );
-
- QLabel* m_lIcon = new QLabel( this, "m_lDescr" );
- QPixmap pm = QMessageBox::standardIcon( QMessageBox::Warning );
- m_lIcon->setPixmap( pm );
- m_lIcon->setScaledContents( false );
- m_lIcon->setAlignment( Qt::AlignCenter );
-
- QLabel* m_lDescr = new QLabel (this, "m_lDescr");
- m_lDescr->setText ( tr ("CLOSE_DLG_DESCRIPTION") );
- m_lDescr->setAlignment( Qt::AlignCenter );
- m_lDescr->setMinimumHeight( m_lDescr->sizeHint().height()*5 );
- m_lDescr->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ) );
-
- QHBoxLayout* m_hl1 = new QHBoxLayout();
- m_hl1->setMargin( 0 ); m_hl1->setSpacing( 6 );
- m_hl1->addWidget( m_lIcon );
- m_hl1->addWidget( m_lDescr );
-
- m_pb1 = new QPushButton( tr ("CLOSE_DLG_SAVE_CLOSE"), this );
- m_pb2 = new QPushButton( tr ("CLOSE_DLG_CLOSE"), this );
- m_pb3 = new QPushButton( tr ("CLOSE_DLG_UNLOAD"), this );
- m_pb4 = new QPushButton( tr ("BUT_CANCEL"), this );
-
- QGridLayout* m_hl2 = new QGridLayout();
- m_hl2->setMargin( 0 ); m_hl2->setSpacing( 6 );
- m_hl2->addWidget( m_pb1, 0, 0 );
- m_hl2->addWidget( m_pb2, 0, 1 );
- m_hl2->addWidget( m_pb3, 0, 2 );
- m_hl2->addColSpacing( 3, 10 );
- m_hl2->setColStretch( 3, 5 );
- m_hl2->addWidget( m_pb4, 0, 4 );
-
- m_vbL->addLayout( m_hl1 );
- m_vbL->addLayout( m_hl2 );
-
- connect( m_pb1, SIGNAL( clicked() ), this, SLOT( onButtonClicked() ) );
- connect( m_pb2, SIGNAL( clicked() ), this, SLOT( onButtonClicked() ) );
- connect( m_pb3, SIGNAL( clicked() ), this, SLOT( onButtonClicked() ) );
- connect( m_pb4, SIGNAL( clicked() ), this, SLOT( reject() ) );
-}
-
-/*!
- * \brief reaction on clicked(pressed) button
- */
-void STD_CloseDlg::onButtonClicked()
-{
- QPushButton* btn = ( QPushButton* )sender();
- if ( btn == m_pb1 )
- done( 1 );
- if ( btn == m_pb2 )
- done( 2 );
- if ( btn == m_pb3 )
- done( 3 );
-}
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-#ifndef STD_CloseDlg_H
-#define STD_CloseDlg_H
-
-#include <qdialog.h>
-
-/*! \class QDialog
- * \brief For more information see <a href="http://doc.trolltech.com">QT documentation</a>.
- */
-/*!\class STD_CloseDlg
- * \brief Describes a dialog box shown on closing the active study
- */
-class STD_CloseDlg: public QDialog
-{
- Q_OBJECT
-
-public:
- STD_CloseDlg ( QWidget * parent = 0, bool modal = FALSE, WFlags f = 0 ) ;
- ~STD_CloseDlg ( ) { };
-
-private slots:
- void onButtonClicked();
-
-private:
- /*!\var m_pb1
- * \brief Private, stores a dialog button 1
- */
- QPushButton* m_pb1;
- /*!\var m_pb2
- * \brief Private, stores a dialog button 2
- */
- QPushButton* m_pb2;
- /*!\var m_pb3
- * \brief Private, stores a dialog button 3
- */
- QPushButton* m_pb3;
-
- /*!\var m_pb4
- * \brief Private, stores a dialog button 4
- */
- QPushButton* m_pb4;
-};
-
-#endif
-
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-#include "STD_LoadStudiesDlg.h"
-
-#include <qlabel.h>
-#include <qlayout.h>
-#include <qlistbox.h>
-#include <qpushbutton.h>
-
-#define SPACING_SIZE 6
-#define MARGIN_SIZE 11
-#define MIN_LISTBOX_WIDTH 150
-#define MIN_LISTBOX_HEIGHT 100
-
-/*!
-* \brief creates a Load study dialog box
-* \param parent a parent widget
-* \param modal bool argument, if true the dialog box is a modal dialog box
-* \param f style flags
-*/
-
-STD_LoadStudiesDlg::STD_LoadStudiesDlg( QWidget* parent, bool modal, WFlags fl )
-: QDialog( parent, "STD_LoadStudiesDlg", modal, WStyle_Customize | WStyle_NormalBorder | WStyle_Title | WStyle_SysMenu )
-{
- resize( 321, 181 );
- setCaption( tr("DLG_LOAD_STUDY_CAPTION") );
- setSizeGripEnabled( TRUE );
-
- QGridLayout* aTopLayout = new QGridLayout(this);
- aTopLayout->setMargin(MARGIN_SIZE);
- aTopLayout->setSpacing(SPACING_SIZE);
-
- TextLabel1 = new QLabel( this, "TextLabel1" );
- TextLabel1->setGeometry( QRect( 11, 12, 297, 16 ) );
- TextLabel1->setText( tr( "MEN_STUDIES_CHOICE" ) );
-
- QHBoxLayout* aBtnLayout = new QHBoxLayout;
- aBtnLayout->setSpacing( SPACING_SIZE );
- aBtnLayout->setMargin( 0 );
-
- buttonOk = new QPushButton( this, "buttonOk" );
- buttonOk->setText( tr( "BUT_OK" ) );
- buttonOk->setAutoDefault( true );
- buttonOk->setDefault( true );
-
- buttonCancel = new QPushButton( this, "buttonCancel" );
- buttonCancel->setText( tr( "BUT_CANCEL" ) );
- buttonCancel->setAutoDefault( true );
-
- aBtnLayout->addWidget( buttonOk );
- aBtnLayout->addItem( new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum ) );
- aBtnLayout->addWidget( buttonCancel );
-
- ListComponent = new QListBox( this, "ListComponent" );
- ListComponent->setVScrollBarMode(QListBox::AlwaysOn);
- ListComponent->setMinimumSize(MIN_LISTBOX_WIDTH, MIN_LISTBOX_HEIGHT);
- ListComponent->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
- ListComponent->setSelectionMode(QListBox::Single);
-
- aTopLayout->addWidget(TextLabel1, 0, 0);
- aTopLayout->addWidget(ListComponent, 1, 0);
- aTopLayout->addLayout(aBtnLayout, 2, 0);
-
- // signals and slots connections
- connect( buttonOk, SIGNAL( clicked() ), this, SLOT( accept() ) );
- connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
-}
-
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-#ifndef STD_LOADSTUDIESDLG_H
-#define STD_LOADSTUDIESDLG_H
-
-#include <STD.h>
-
-#include <qdialog.h>
-#include <qvariant.h>
-
-class QLabel;
-class QListBox;
-class QPushButton;
-class QVBoxLayout;
-class QHBoxLayout;
-class QGridLayout;
-class QListBoxItem;
-
-/*!\class STD_LoadStudiesDlg
- * \brief Describes a dialog box that gives a list of opened studies.
- *
- */
-class STD_EXPORT STD_LoadStudiesDlg : public QDialog
-{
- Q_OBJECT
-
-public:
- STD_LoadStudiesDlg( QWidget* parent = 0, bool modal = FALSE, WFlags fl = 0 );
- ~STD_LoadStudiesDlg() {}
-
- /*!\var TextLabel1
- * \brief stores a dialog text label
- */
- QLabel* TextLabel1;
-
- /*!\var buttonOk
- * \brief stores a dialog button OK
- */
- QPushButton* buttonOk;
-
- /*!\var buttonCancel
- * \brief stores a dialog button Cancel
- */
- QPushButton* buttonCancel;
-
- /*!\var ListComponent
- * \brief stores a dialog list compoent
- */
- QListBox* ListComponent;
-
-};
-
-#endif // STD_LOADSTUDIESDLG_H
#include <SUIT_ViewWindow.h>
#include <SUIT_ResourceMgr.h>
-#include <QtxAction.h>
+#include <QtxWorkspace.h>
#include <QtxActionMenuMgr.h>
#include <QtxWorkspaceAction.h>
-#include <qvbox.h>
-#include <qmenubar.h>
-#include <qworkspace.h>
-#include <qobjectlist.h>
+#include <QFrame>
+#include <QVBoxLayout>
#include <stdarg.h>
-/*!Constructor.*/
+/*!
+ Constructor.
+*/
STD_MDIDesktop::STD_MDIDesktop()
: SUIT_Desktop(),
myWorkspace( 0 ),
myWorkspaceAction( 0 )
{
- QVBox* base = new QVBox( this );
+ QFrame* base = new QFrame( this );
+ QVBoxLayout* main = new QVBoxLayout( base );
+ main->setMargin( 0 );
base->setFrameStyle( QFrame::Panel | QFrame::Sunken );
setCentralWidget( base );
- myWorkspace = new QWorkspace( base );
+ myWorkspace = new QtxWorkspace( base );
+ main->addWidget( myWorkspace );
connect( myWorkspace, SIGNAL( windowActivated( QWidget* ) ),
this, SLOT( onWindowActivated( QWidget* ) ) );
createActions();
}
-/*!destructor.*/
+/*!
+ Destructor.
+*/
STD_MDIDesktop::~STD_MDIDesktop()
{
}
-/*!\retval SUIT_ViewWindow - return const active window.*/
+/*!
+ \retval SUIT_ViewWindow - return const active window.
+*/
SUIT_ViewWindow* STD_MDIDesktop::activeWindow() const
{
SUIT_ViewWindow* wnd = 0;
return wnd;
}
-/*!\retval QPtrList<SUIT_ViewWindow> - return const active window list.*/
-QPtrList<SUIT_ViewWindow> STD_MDIDesktop::windows() const
+/*!
+ \retval QList<SUIT_ViewWindow> - return const active window list.
+*/
+QList<SUIT_ViewWindow*> STD_MDIDesktop::windows() const
{
- QPtrList<SUIT_ViewWindow> winList;
+ QList<SUIT_ViewWindow*> winList;
QWidgetList children = myWorkspace->windowList();
- for ( QWidgetListIt it( children ); it.current(); ++it )
+ for ( QWidgetList::iterator it = children.begin(); it != children.end(); ++it )
{
- if ( it.current()->inherits( "SUIT_ViewWindow" ) )
- winList.append( (SUIT_ViewWindow*)it.current() );
+ SUIT_ViewWindow* vw = ::qobject_cast<SUIT_ViewWindow*>( *it );
+ if ( vw )
+ winList.append( vw );
}
return winList;
}
-/*!\retval QWidget - pointer to work space.*/
-QWidget* STD_MDIDesktop::parentArea() const
+/*!
+ Add the new widget into desktop.
+*/
+void STD_MDIDesktop::addWindow( QWidget* w )
{
- return workspace();
+ if ( !w || !workspace() )
+ return;
+
+ workspace()->addWindow( w );
}
/*!Call method perform for operation \a type.*/
void STD_MDIDesktop::setWindowOperations( const int first, ... )
{
va_list ints;
- va_start( ints, first );
-
- QValueList<int> typeList;
+ va_start( ints, first );
- int cur = first;
- while ( cur )
- {
- typeList.append( cur );
- cur = va_arg( ints, int );
+ QList<int> typeList;
+
+ int cur = first;
+ while ( cur )
+ {
+ typeList.append( cur );
+ cur = va_arg( ints, int );
}
- setWindowOperations( typeList );
+ setWindowOperations( typeList );
}
/*!Sets window operations by variable \a opList - operation list.*/
-void STD_MDIDesktop::setWindowOperations( const QValueList<int>& opList )
+void STD_MDIDesktop::setWindowOperations( const QList<int>& opList )
{
int flags = 0;
- for ( QValueList<int>::const_iterator it = opList.begin(); it != opList.end(); ++it )
+ for ( QList<int>::const_iterator it = opList.begin(); it != opList.end(); ++it )
flags = flags | operationFlag( *it );
- myWorkspaceAction->setItems( flags );
+ myWorkspaceAction->setMenuActions( flags );
}
-/*!\retval QWorkspace pointer - work space.*/
-QWorkspace* STD_MDIDesktop::workspace() const
+/*!
+ \retval QtxWorkspace pointer - work space.
+*/
+QtxWorkspace* STD_MDIDesktop::workspace() const
{
return myWorkspace;
}
-/*!Emit window activated.*/
+/*!
+ Emit window activated.
+*/
void STD_MDIDesktop::onWindowActivated( QWidget* w )
{
if ( w && w->inherits( "SUIT_ViewWindow" ) )
emit windowActivated( (SUIT_ViewWindow*)w );
}
-/*!Create actions: cascade, Tile, Tile Horizontal, Tile Vertical*/
+/*!
+ Create actions: cascade, Tile, Tile Horizontal, Tile Vertical
+*/
void STD_MDIDesktop::createActions()
{
if ( myWorkspaceAction )
myWorkspaceAction = new QtxWorkspaceAction( workspace(), this );
- myWorkspaceAction->setItems( QtxWorkspaceAction::Cascade | QtxWorkspaceAction::Tile |
- QtxWorkspaceAction::HTile | QtxWorkspaceAction::VTile |
- QtxWorkspaceAction::Windows );
+ myWorkspaceAction->setMenuActions( QtxWorkspaceAction::Cascade | QtxWorkspaceAction::Tile |
+ QtxWorkspaceAction::HTile | QtxWorkspaceAction::VTile |
+ QtxWorkspaceAction::Windows );
// Cascade
- myWorkspaceAction->setIconSet( QtxWorkspaceAction::Cascade,
- resMgr->loadPixmap( "STD", tr( "ICON_DESK_WINDOW_CASCADE" ) ) );
- myWorkspaceAction->setMenuText( QtxWorkspaceAction::Cascade, tr( "MEN_DESK_WINDOW_CASCADE" ) );
+ myWorkspaceAction->setIcon( QtxWorkspaceAction::Cascade,
+ resMgr->loadPixmap( "STD", tr( "ICON_DESK_WINDOW_CASCADE" ) ) );
+ myWorkspaceAction->setText( QtxWorkspaceAction::Cascade, tr( "MEN_DESK_WINDOW_CASCADE" ) );
myWorkspaceAction->setStatusTip( QtxWorkspaceAction::Cascade, tr( "PRP_DESK_WINDOW_CASCADE" ) );
// Tile
- myWorkspaceAction->setIconSet( QtxWorkspaceAction::Tile,
- resMgr->loadPixmap( "STD", tr( "ICON_DESK_WINDOW_TILE" ) ) );
- myWorkspaceAction->setMenuText( QtxWorkspaceAction::Tile, tr( "MEN_DESK_WINDOW_TILE" ) );
+ myWorkspaceAction->setIcon( QtxWorkspaceAction::Tile,
+ resMgr->loadPixmap( "STD", tr( "ICON_DESK_WINDOW_TILE" ) ) );
+ myWorkspaceAction->setText( QtxWorkspaceAction::Tile, tr( "MEN_DESK_WINDOW_TILE" ) );
myWorkspaceAction->setStatusTip( QtxWorkspaceAction::Tile, tr( "PRP_DESK_WINDOW_TILE" ) );
// Tile Horizontal
- myWorkspaceAction->setIconSet( QtxWorkspaceAction::HTile,
- resMgr->loadPixmap( "STD", tr( "ICON_DESK_WINDOW_HTILE" ) ) );
- myWorkspaceAction->setMenuText( QtxWorkspaceAction::HTile, tr( "MEN_DESK_WINDOW_HTILE" ) );
+ myWorkspaceAction->setIcon( QtxWorkspaceAction::HTile,
+ resMgr->loadPixmap( "STD", tr( "ICON_DESK_WINDOW_HTILE" ) ) );
+ myWorkspaceAction->setText( QtxWorkspaceAction::HTile, tr( "MEN_DESK_WINDOW_HTILE" ) );
myWorkspaceAction->setStatusTip( QtxWorkspaceAction::HTile, tr( "PRP_DESK_WINDOW_HTILE" ) );
// Tile Vertical
- myWorkspaceAction->setIconSet( QtxWorkspaceAction::VTile,
- resMgr->loadPixmap( "STD", tr( "ICON_DESK_WINDOW_VTILE" ) ) );
- myWorkspaceAction->setMenuText( QtxWorkspaceAction::VTile, tr( "MEN_DESK_WINDOW_VTILE" ) );
+ myWorkspaceAction->setIcon( QtxWorkspaceAction::VTile,
+ resMgr->loadPixmap( "STD", tr( "ICON_DESK_WINDOW_VTILE" ) ) );
+ myWorkspaceAction->setText( QtxWorkspaceAction::VTile, tr( "MEN_DESK_WINDOW_VTILE" ) );
myWorkspaceAction->setStatusTip( QtxWorkspaceAction::VTile, tr( "PRP_DESK_WINDOW_VTILE" ) );
-
QtxActionMenuMgr* mMgr = menuMgr();
if ( !mMgr )
return;
- int winMenuId = mMgr->insert( tr( "MEN_DESK_WINDOW" ), -1, 100, MenuWindowId );
+ int winMenuId = mMgr->insert( tr( "MEN_DESK_WINDOW" ), -1, 100 );
mMgr->insert( myWorkspaceAction, winMenuId, -1 );
mMgr->insert( QtxActionMenuMgr::separator(), winMenuId, -1 );
}
#include <SUIT_Desktop.h>
-class QtxAction;
-class QPopupMenu;
-class QWorkspace;
+class QtxWorkspace;
class QtxWorkspaceAction;
-#if defined WNT
+#if defined WIN32
#pragma warning( disable: 4251 )
#endif
Q_OBJECT
public:
- enum { MenuWindowId = 6 };
enum { Cascade, Tile, HTile, VTile };
public:
virtual ~STD_MDIDesktop();
virtual SUIT_ViewWindow* activeWindow() const;
- virtual QPtrList<SUIT_ViewWindow> windows() const;
+ virtual QList<SUIT_ViewWindow*> windows() const;
void windowOperation( const int );
void setWindowOperations( const int, ... );
- void setWindowOperations( const QValueList<int>& );
+ void setWindowOperations( const QList<int>& );
- QWorkspace* workspace() const;
+ QtxWorkspace* workspace() const;
private slots:
void onWindowActivated( QWidget* );
protected:
void createActions();
- virtual QWidget* parentArea() const;
+ virtual void addWindow( QWidget* );
private:
int operationFlag( const int ) const;
private:
- QWorkspace* myWorkspace;
+ QtxWorkspace* myWorkspace;
QtxWorkspaceAction* myWorkspaceAction;
};
-#if defined WNT
+#if defined WIN32
#pragma warning( default: 4251 )
#endif
#include <SUIT_ViewWindow.h>
-#include <qvbox.h>
-#include <qmenubar.h>
-#include <qobjectlist.h>
+#include <QFrame>
+#include <QVBoxLayout>
/*!Constructor. Create instance of QVBox*/
STD_SDIDesktop::STD_SDIDesktop()
: SUIT_Desktop()
{
- myMainWidget = new QVBox( this );
+ myMainWidget = new QFrame( this );
myMainWidget->setFrameStyle( QFrame::Panel | QFrame::Sunken );
+
+ QVBoxLayout* main = new QVBoxLayout( myMainWidget );
+ main->setMargin( 0 );
setCentralWidget( myMainWidget );
}
/*!\retval SUIT_ViewWindow - return const active window.*/
SUIT_ViewWindow* STD_SDIDesktop::activeWindow() const
{
- const QObjectList* children = myMainWidget->children();
- if ( !children )
- return 0;
-
- QPtrList<SUIT_ViewWindow> winList;
- for ( QObjectListIt it( *children ); it.current(); ++it )
+ const QObjectList& lst = myMainWidget->children();
+ QList<SUIT_ViewWindow*> winList;
+ for ( QObjectList::const_iterator it = lst.begin(); it != lst.end(); ++it )
{
- if ( it.current()->inherits( "SUIT_ViewWindow" ) )
- winList.append( (SUIT_ViewWindow*)it.current() );
+ SUIT_ViewWindow* vw = ::qobject_cast<SUIT_ViewWindow*>( *it );
+ if ( vw )
+ winList.append( vw );
}
SUIT_ViewWindow* win = 0;
- for ( QPtrListIterator<SUIT_ViewWindow> itr( winList ); itr.current() && !win; ++itr )
+ for ( QList<SUIT_ViewWindow*>::iterator itr = winList.begin(); itr != winList.end() && !win; ++itr )
{
- if ( itr.current()->isActiveWindow() )
- win = itr.current();
+ if ( (*itr)->isActiveWindow() )
+ win = *itr;
}
if ( !win && !winList.isEmpty() )
- win = winList.getFirst();
+ win = winList.first();
return win;
}
/*!\retval QPtrList<SUIT_ViewWindow> - return const active window list.*/
-QPtrList<SUIT_ViewWindow> STD_SDIDesktop::windows() const
+QList<SUIT_ViewWindow*> STD_SDIDesktop::windows() const
{
- QPtrList<SUIT_ViewWindow> winList;
- winList.append( activeWindow() );
+ QList<SUIT_ViewWindow*> winList;
+ winList.append( activeWindow() );
return winList;
}
-/*!\retval QWidget - pointer to main window.*/
-QWidget* STD_SDIDesktop::parentArea() const
+/*! add new widget into desktop.*/
+void STD_SDIDesktop::addWindow( QWidget* w )
{
- return myMainWidget;
+ if ( !w || !centralWidget() || !centralWidget()->layout() )
+ return;
+
+ w->setParent( centralWidget() );
+ centralWidget()->layout()->addWidget( w );
}
#include <SUIT_Desktop.h>
-class QVBox;
+class QFrame;
class STD_EXPORT STD_SDIDesktop: public SUIT_Desktop
{
virtual ~STD_SDIDesktop();
virtual SUIT_ViewWindow* activeWindow() const;
- virtual QPtrList<SUIT_ViewWindow> windows() const;
+ virtual QList<SUIT_ViewWindow*> windows() const;
protected:
- virtual QWidget* parentArea() const;
+ virtual void addWindow( QWidget* );
private:
- QVBox* myMainWidget;
+ QFrame* myMainWidget;
};
#endif
#include <SUIT_ViewWindow.h>
#include <SUIT_ResourceMgr.h>
-#include <QtxAction.h>
#include <QtxWorkstack.h>
#include <QtxActionMenuMgr.h>
#include <QtxWorkstackAction.h>
-#include <qvbox.h>
-#include <qmenubar.h>
-#include <qworkspace.h>
-#include <qobjectlist.h>
+#include <QFrame>
+#include <QVBoxLayout>
#include <stdarg.h>
myWorkstack( 0 ),
myWorkstackAction( 0 )
{
- QVBox* base = new QVBox( this );
+ QFrame* base = new QFrame( this );
base->setFrameStyle( QFrame::Panel | QFrame::Sunken );
+ QVBoxLayout* main = new QVBoxLayout( base );
+ main->setMargin( 0 );
+
setCentralWidget( base );
myWorkstack = new QtxWorkstack( base );
+ main->addWidget( myWorkstack );
// setting Expanding size policy for central workstack. If there are several widgets
// in central area of Desktop, other widgets will be added below the workstack (CATHARE, TRIPOLI modules).
// But the workstack must occupy as much space as possible -- set Expanding for it.
myWorkstack->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ) );
- myWorkstack->setAccel(QtxWorkstack::SplitVertical, SHIFT + Key_V);
- myWorkstack->setAccel(QtxWorkstack::SplitHorizontal, SHIFT + Key_H);
- myWorkstack->setAccel(QtxWorkstack::Close, SHIFT + Key_C);
+ myWorkstack->setAccel( QtxWorkstack::SplitVertical, Qt::SHIFT + Qt::Key_V );
+ myWorkstack->setAccel( QtxWorkstack::SplitHorizontal, Qt::SHIFT + Qt::Key_H );
+ myWorkstack->setAccel( QtxWorkstack::Close, Qt::SHIFT + Qt::Key_C );
connect( myWorkstack, SIGNAL( windowActivated( QWidget* ) ),
this, SLOT( onWindowActivated( QWidget* ) ) );
createActions();
}
-/*!Destructor.*/
+/*!
+ Destructor.
+*/
STD_TabDesktop::~STD_TabDesktop()
{
}
-/*!\retval SUIT_ViewWindow - return const active window.*/
+/*!
+ \retval SUIT_ViewWindow - return const active window.
+*/
SUIT_ViewWindow* STD_TabDesktop::activeWindow() const
{
SUIT_ViewWindow* wnd = 0;
return wnd;
}
-/*!\retval QPtrList<SUIT_ViewWindow> - return const active window list.*/
-QPtrList<SUIT_ViewWindow> STD_TabDesktop::windows() const
+/*!
+ \retval QPtrList<SUIT_ViewWindow> - return const active window list.
+*/
+QList<SUIT_ViewWindow*> STD_TabDesktop::windows() const
{
- QPtrList<SUIT_ViewWindow> winList;
+ QList<SUIT_ViewWindow*> winList;
QWidgetList children = myWorkstack->windowList();
- for ( QWidgetListIt it( children ); it.current(); ++it )
+ for ( QWidgetList::iterator it = children.begin(); it != children.end(); ++it )
{
- if ( it.current()->inherits( "SUIT_ViewWindow" ) )
- winList.append( (SUIT_ViewWindow*)it.current() );
+ if ( (*it)->inherits( "SUIT_ViewWindow" ) )
+ winList.append( (SUIT_ViewWindow*)*it );
}
return winList;
}
-/*!\retval QWidget pointer - QT work stack.*/
-QWidget* STD_TabDesktop::parentArea() const
+/*!
+ Insert new widget into desktop.
+*/
+void STD_TabDesktop::addWindow( QWidget* w )
{
- return workstack();
+ if ( !w || !workstack() )
+ return;
+
+ workstack()->addWindow( w );
}
-/*!Call method perform for operation \a type.*/
+/*!
+ Call method perform for operation \a type.
+*/
void STD_TabDesktop::windowOperation( const int type )
{
myWorkstackAction->perform( operationFlag( type ) );
}
-/*!Sets window operations by \a first ... parameters.*/
+/*!
+ Sets window operations by \a first ... parameters.
+*/
void STD_TabDesktop::setWindowOperations( const int first, ... )
{
va_list ints;
va_start( ints, first );
- QValueList<int> typeList;
+ QList<int> typeList;
int cur = first;
while ( cur )
setWindowOperations( typeList );
}
-/*!Sets window operations by variable \a opList - operation list.*/
-void STD_TabDesktop::setWindowOperations( const QValueList<int>& opList )
+/*!
+ Sets window operations by variable \a opList - operation list.
+*/
+void STD_TabDesktop::setWindowOperations( const QList<int>& opList )
{
int flags = 0;
- for ( QValueList<int>::const_iterator it = opList.begin(); it != opList.end(); ++it )
+ for ( QList<int>::const_iterator it = opList.begin(); it != opList.end(); ++it )
flags = flags | operationFlag( *it );
- myWorkstackAction->setItems( flags );
+// myWorkstackAction->setItems( flags );
}
-/*!\retval QtxWorkstack pointer - QT work stack.*/
+/*!
+ \retval QtxWorkstack pointer - Qt work stack.
+*/
QtxWorkstack* STD_TabDesktop::workstack() const
{
return myWorkstack;
}
-/*!Emit window activated.*/
+/*!
+ Emit window activated.
+*/
void STD_TabDesktop::onWindowActivated( QWidget* w )
{
if ( w && w->inherits( "SUIT_ViewWindow" ) )
emit windowActivated( (SUIT_ViewWindow*)w );
}
-/*!Create actions for window.*/
+/*!
+ Create actions for window.
+*/
void STD_TabDesktop::createActions()
{
if ( myWorkstackAction )
myWorkstackAction = new QtxWorkstackAction( workstack(), this );
- myWorkstackAction->setItems( QtxWorkstackAction::Split | QtxWorkstackAction::Windows );
+ myWorkstackAction->setMenuActions( QtxWorkstackAction::Split | QtxWorkstackAction::Windows );
// Split Horizontal
- myWorkstackAction->setIconSet( QtxWorkstackAction::HSplit,
- resMgr->loadPixmap( "STD", tr( "ICON_DESK_WINDOW_HSPLIT" ) ) );
- myWorkstackAction->setMenuText( QtxWorkstackAction::HSplit, tr( "MEN_DESK_WINDOW_HSPLIT" ) );
- myWorkstackAction->setStatusTip( QtxWorkstackAction::HSplit, tr( "PRP_DESK_WINDOW_HSPLIT" ) );
+ myWorkstackAction->setIcon( QtxWorkstackAction::SplitHorizontal,
+ resMgr->loadPixmap( "STD", tr( "ICON_DESK_WINDOW_HSPLIT" ) ) );
+ myWorkstackAction->setText( QtxWorkstackAction::SplitHorizontal, tr( "MEN_DESK_WINDOW_HSPLIT" ) );
+ myWorkstackAction->setStatusTip( QtxWorkstackAction::SplitHorizontal, tr( "PRP_DESK_WINDOW_HSPLIT" ) );
// Split Vertical
- myWorkstackAction->setIconSet( QtxWorkstackAction::VSplit,
- resMgr->loadPixmap( "STD", tr( "ICON_DESK_WINDOW_VSPLIT" ) ) );
- myWorkstackAction->setMenuText( QtxWorkstackAction::VSplit, tr( "MEN_DESK_WINDOW_VSPLIT" ) );
- myWorkstackAction->setStatusTip( QtxWorkstackAction::VSplit, tr( "PRP_DESK_WINDOW_VSPLIT" ) );
+ myWorkstackAction->setIcon( QtxWorkstackAction::SplitVertical,
+ resMgr->loadPixmap( "STD", tr( "ICON_DESK_WINDOW_VSPLIT" ) ) );
+ myWorkstackAction->setText( QtxWorkstackAction::SplitVertical, tr( "MEN_DESK_WINDOW_VSPLIT" ) );
+ myWorkstackAction->setStatusTip( QtxWorkstackAction::SplitVertical, tr( "PRP_DESK_WINDOW_VSPLIT" ) );
QtxActionMenuMgr* mMgr = menuMgr();
if ( !mMgr )
return;
- int winMenuId = mMgr->insert( tr( "MEN_DESK_WINDOW" ), -1, 100, MenuWindowId );
+ int winMenuId = mMgr->insert( tr( "MEN_DESK_WINDOW" ), -1, 100 );
mMgr->insert( myWorkstackAction, winMenuId, -1 );
mMgr->insert( QtxActionMenuMgr::separator(), winMenuId, -1 );
}
-/*!Convert STD_TabDesktop enumerations to QtxWorkstackAction*/
+/*!
+ Convert STD_TabDesktop enumerations to QtxWorkstackAction
+*/
int STD_TabDesktop::operationFlag( const int type ) const
{
int res = 0;
switch ( type )
{
- case VSplit:
- res = QtxWorkstackAction::VSplit;
+ case SplitVertical:
+ res = QtxWorkstackAction::SplitVertical;
break;
- case HSplit:
- res = QtxWorkstackAction::HSplit;
+ case SplitHorizontal:
+ res = QtxWorkstackAction::SplitHorizontal;
break;
}
+
return res;
}
#include <SUIT_Desktop.h>
-class QtxAction;
-class QPopupMenu;
-class QWorkspace;
class QtxWorkstack;
class QtxWorkstackAction;
-#if defined WNT
+#if defined WIN32
#pragma warning( disable: 4251 )
#endif
Q_OBJECT
public:
- enum { MenuWindowId = 6 };
- enum { VSplit, HSplit };
+ enum { SplitVertical, SplitHorizontal };
public:
STD_TabDesktop();
virtual ~STD_TabDesktop();
virtual SUIT_ViewWindow* activeWindow() const;
- virtual QPtrList<SUIT_ViewWindow> windows() const;
+ virtual QList<SUIT_ViewWindow*> windows() const;
void windowOperation( const int );
void setWindowOperations( const int, ... );
- void setWindowOperations( const QValueList<int>& );
+ void setWindowOperations( const QList<int>& );
QtxWorkstack* workstack() const;
protected:
void createActions();
- virtual QWidget* parentArea() const;
+ virtual void addWindow( QWidget* );
private:
int operationFlag( const int ) const;
QtxWorkstackAction* myWorkstackAction;
};
-#if defined WNT
+#if defined WIN32
#pragma warning( default: 4251 )
#endif
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>ICON_FILE_NEW</source>
+ <translation>new.png</translation>
+ </message>
+ <message>
+ <source>ICON_DESK_WINDOW_TILE</source>
+ <translation>tile.png</translation>
+ </message>
+ <message>
+ <source>ICON_PRINT</source>
+ <translation>print.png</translation>
+ </message>
+ <message>
+ <source>ICON_RESET</source>
+ <translation>reset.png</translation>
+ </message>
+ <message>
+ <source>ICON_HELP</source>
+ <translation>help.png</translation>
+ </message>
+ <message>
+ <source>ICON_EDIT_CUT</source>
+ <translation>cut.png</translation>
+ </message>
+ <message>
+ <source>ICON_DESK_WINDOW_CASCADE</source>
+ <translation>cascade.png</translation>
+ </message>
+ <message>
+ <source>ICON_EDIT_COPY</source>
+ <translation>copy.png</translation>
+ </message>
+ <message>
+ <source>ICON_APP_DEFAULTICON</source>
+ <translation>default.png</translation>
+ </message>
+ <message>
+ <source>ICON_FILE_SAVE</source>
+ <translation>save.png</translation>
+ </message>
+ <message>
+ <source>ICON_FILE_OPEN</source>
+ <translation>open.png</translation>
+ </message>
+ <message>
+ <source>ICON_DESK_WINDOW_HSPLIT</source>
+ <translation>htile.png</translation>
+ </message>
+ <message>
+ <source>ICON_APP_EDIT_REDO</source>
+ <translation>redo.png</translation>
+ </message>
+ <message>
+ <source>ICON_APP_EDIT_UNDO</source>
+ <translation>undo.png</translation>
+ </message>
+ <message>
+ <source>ICON_DESK_WINDOW_VSPLIT</source>
+ <translation>vtile.png</translation>
+ </message>
+ <message>
+ <source>ICON_DESK_DEFAULTICON</source>
+ <translation>default.png</translation>
+ </message>
+ <message>
+ <source>ICON_DESK_WINDOW_HTILE</source>
+ <translation>htile.png</translation>
+ </message>
+ <message>
+ <source>ICON_DESK_WINDOW_VTILE</source>
+ <translation>vtile.png</translation>
+ </message>
+ <message>
+ <source>ICON_EDIT_PASTE</source>
+ <translation>paste.png</translation>
+ </message>
+ <message>
+ <source>ICON_FILE_CLOSE</source>
+ <translation>close.png</translation>
+ </message>
+</context>
+<context>
+ <name>SUIT_ViewPort</name>
+ <message>
+ <source>ICON_CURSOR_ZOOM</source>
+ <translation>cursor_zoom.png</translation>
+ </message>
+ <message>
+ <source>ICON_CURSOR_ROTATE</source>
+ <translation>cursor_rotate.png</translation>
+ </message>
+</context>
+</TS>
msgid "STD_Application::INF_DOC_SAVING_FAILS"
msgstr "Can't save file \"%1\".\nPossible reason is permission denied or disc full.\nTry to use another file name."
-msgid "CLOSE_DLG_SAVE_CLOSE"
-msgstr "&Save&&Close"
-
-msgid "CLOSE_DLG_CLOSE"
-msgstr "C&lose w/o saving"
-
-msgid "CLOSE_DLG_UNLOAD"
-msgstr "&Unload"
-
msgid "TOT_DESK_FILE_LOAD"
msgstr "Load document"
msgid "MEN_DESK_FILE_LOAD"
msgstr "Conn&ect..."
-msgid "CLOSE_DLG_CAPTION"
-msgstr "Close active study"
-
-msgid "CLOSE_DLG_DESCRIPTION"
-msgstr "Do you want to close or only unload the study"
-
msgid "DLG_LOAD_STUDY_CAPTION"
msgstr "Load Study"
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>TOT_DESK_EDIT_CUT</source>
+ <translation>Cut</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_EDIT_CUT</source>
+ <translation>Cuts the selection and puts it to the Clipboard</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_EDIT_CUT</source>
+ <translation>Cu&t</translation>
+ </message>
+ <message>
+ <source>ERR_APP_NOAPP</source>
+ <translation>No application</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_WINDOW</source>
+ <translation>&Window</translation>
+ </message>
+ <message>
+ <source>TOT_DESK_EDIT_COPY</source>
+ <translation>Copy</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_WINDOW_CASCADE</source>
+ <translation>&Cascade</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_EDIT_COPY</source>
+ <translation>Copy the selection to the Clipboard</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_WINDOW_CASCADE</source>
+ <translation>Arranges the windows as overlapping tiles</translation>
+ </message>
+ <message>
+ <source>TOT_DESK_FILE_SAVEAS</source>
+ <translation>Save document as...</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_EDIT_COPY</source>
+ <translation>&Copy</translation>
+ </message>
+ <message>
+ <source>MSG_CANT_SAVE</source>
+ <translation>Can't save file "%1".</translation>
+ </message>
+ <message>
+ <source>INF_DESK_TOOLBAR_STANDARD</source>
+ <translation>Standard</translation>
+ </message>
+ <message>
+ <source>ALL_FILES</source>
+ <translation>All Files (*.*)</translation>
+ </message>
+ <message>
+ <source>DESK_DEFAULTTITLE</source>
+ <translation>Qt Application Desktop</translation>
+ </message>
+ <message>
+ <source>QUE_DESK_EXIT</source>
+ <translation>Do you really want to quit ?</translation>
+ </message>
+ <message>
+ <source>INF_INFO</source>
+ <translation>Information</translation>
+ </message>
+ <message>
+ <source>ERR_DOC_UNKNOWNTYPE_OPEN</source>
+ <translation>You are trying to open a document of an unknown type
+( %1 )</translation>
+ </message>
+ <message>
+ <source>ERR_DOC_UNKNOWNTYPE_SAVE</source>
+ <translation>You are trying to save this document under an unknown type
+( %1 )</translation>
+ </message>
+ <message>
+ <source>TOT_DESK_NEWWINDOW</source>
+ <translation>Create new Window</translation>
+ </message>
+ <message>
+ <source>BUT_CANCEL</source>
+ <translation>&Cancel</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_HELP_ABOUT</source>
+ <translation>&About...</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_NEWWINDOW</source>
+ <translation>Create new Window</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_VIEW_STATUSBAR</source>
+ <translation>&Status Bar</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_NEWWINDOW</source>
+ <translation>&New Window</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_VIEW_STATUSBAR</source>
+ <translation>Toggles status bar view on/off</translation>
+ </message>
+ <message>
+ <source>ERR_DOC_DIRWITHNAMEEXIST_SAVE</source>
+ <translation>Can not save file %1.
+Directory with this name exist on disc. Try to use another name</translation>
+ </message>
+ <message>
+ <source>BUT_NO</source>
+ <translation>&No</translation>
+ </message>
+ <message>
+ <source>BUT_OK</source>
+ <translation>&Ok</translation>
+ </message>
+ <message>
+ <source>FILTER_FILES</source>
+ <translation>%1 Files (%2)</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_WINDOW_ACTIVATE</source>
+ <translation>Activates this window</translation>
+ </message>
+ <message>
+ <source>TOT_DESK_FILE_PRINT</source>
+ <translation>Print document</translation>
+ </message>
+ <message>
+ <source>TOT_DESK_FILE_CLOSE</source>
+ <translation>Close document</translation>
+ </message>
+ <message>
+ <source>TOT_DESK_FILE_NEW</source>
+ <translation>New document</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_FILE_NEW</source>
+ <translation>Creates a new document</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_FILE_MRU</source>
+ <translation>Opens a document</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_FILE_NEW</source>
+ <translation>&New</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_FILE_MRU</source>
+ <translation>Recent &Files</translation>
+ </message>
+ <message>
+ <source>TOT_DESK_EDIT_PASTE</source>
+ <translation>Paste</translation>
+ </message>
+ <message>
+ <source>BUT_YES</source>
+ <translation>&Yes</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_VIEW</source>
+ <translation>&View</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_HELP_ABOUT</source>
+ <translation>Shows 'About' dialog</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_FILE</source>
+ <translation>&File</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_EDIT</source>
+ <translation>&Edit</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_HELP</source>
+ <translation>&Help</translation>
+ </message>
+ <message>
+ <source>ERR_ERROR</source>
+ <translation>Error</translation>
+ </message>
+ <message>
+ <source>ERR_DESK_NOAPP</source>
+ <translation>No applications registered</translation>
+ </message>
+ <message>
+ <source>INF_DESK_DOC_CREATE</source>
+ <translation>Create a new document</translation>
+ </message>
+ <message>
+ <source>QUE_DOC_ALREADYOPEN</source>
+ <translation>The document %1 is already open.
+Do you want to reload it ?</translation>
+ </message>
+ <message>
+ <source>BUT_APPLY</source>
+ <translation>&Apply</translation>
+ </message>
+ <message>
+ <source>BUT_CLOSE</source>
+ <translation>&Close</translation>
+ </message>
+ <message>
+ <source>INF_DESK_EXIT</source>
+ <translation>Exit</translation>
+ </message>
+ <message>
+ <source>ERR_UNKNOWN</source>
+ <translation>Unknown error</translation>
+ </message>
+ <message>
+ <source>BUT_HELP</source>
+ <translation>&Help</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_FILE_CLOSE</source>
+ <translation>Closes the active document</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_FILE_PRINT</source>
+ <translation>Prints the active document</translation>
+ </message>
+ <message>
+ <source>WRN_WARNING</source>
+ <translation>Warning</translation>
+ </message>
+ <message>
+ <source>TOT_DESK_HELP_ABOUT</source>
+ <translation>About...</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_VIEW_TOOLBARS</source>
+ <translation>T&oolbars</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_WINDOW_HSPLIT</source>
+ <translation>Splits the active window on two horizontal parts</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_WINDOW_HSPLIT</source>
+ <translation>Split &Horizontally</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_EDIT_PASTE</source>
+ <translation>Inserts the Clipboard content at the insertion point</translation>
+ </message>
+ <message>
+ <source>DLG_LOAD_STUDY_CAPTION</source>
+ <translation>Load Study</translation>
+ </message>
+ <message>
+ <source>CLOSE_STUDY</source>
+ <translation>Close study</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_HELP_SEARCH</source>
+ <translation>Searches help for a topic</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_FILE_SAVEAS</source>
+ <translation>Saves the active document with a new name</translation>
+ </message>
+ <message>
+ <source>INF_READY</source>
+ <translation>Ready</translation>
+ </message>
+ <message>
+ <source>INF_CANCELLED</source>
+ <translation>Cancelled</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_WINDOW_VSPLIT</source>
+ <translation>Splits the active window on two vertical parts</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_WINDOW_VSPLIT</source>
+ <translation>Split &Vertically</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_WINDOW_TILE</source>
+ <translation>Arranges the windows as nonoverlapping tiles</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_HELP_CONTENTS</source>
+ <translation>&Contents</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_HELP_CONTENTS</source>
+ <translation>Shows the whole help contents</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_WINDOW_HTILE</source>
+ <translation>Tile &Horizontally</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_WINDOW_VTILE</source>
+ <translation>Tile &Vertically</translation>
+ </message>
+ <message>
+ <source>ERR_DOC_PERMISSIONDENIED_SAVE</source>
+ <translation>Can not save file %1. Permission denied</translation>
+ </message>
+ <message>
+ <source>INF_DESK_DOCALREADYOPEN</source>
+ <translation>A document cannot be saved under a name of a document already opened.
+Please, type another name for the document you want to save.
+( %1 )</translation>
+ </message>
+ <message>
+ <source>TIT_FILE_SAVEAS</source>
+ <translation>Save As</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_FILE_CLOSE</source>
+ <translation>&Close</translation>
+ </message>
+ <message>
+ <source>MSG_FILE_EXISTS</source>
+ <translation>File "%1" already exists.
+Do you want to overwrite it?</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_FILE_PRINT</source>
+ <translation>&Print</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_HELP_SEARCH</source>
+ <translation>&Search...</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_VIEW_STDTOOLBAR</source>
+ <translation>&Standard</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_FILE_SAVEAS</source>
+ <translation>Save &As...</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_VIEW_STDTOOLBAR</source>
+ <translation>Toggles standard toolbar on/off</translation>
+ </message>
+ <message>
+ <source>QUE_DOC_FILEEXISTS</source>
+ <translation>The file %1 already exists.
+Do you want to overwrite it ?</translation>
+ </message>
+ <message>
+ <source>TOT_DESK_FILE_SAVE</source>
+ <translation>Save document</translation>
+ </message>
+ <message>
+ <source>TOT_DESK_FILE_EXIT</source>
+ <translation>Exit from application</translation>
+ </message>
+ <message>
+ <source>TOT_DESK_FILE_LOAD</source>
+ <translation>Load document</translation>
+ </message>
+ <message>
+ <source>TOT_DESK_FILE_OPEN</source>
+ <translation>Open document</translation>
+ </message>
+ <message>
+ <source>CLOSE_QUESTION</source>
+ <translation>Document %1 modified. Do you want to save or discard the modification and close the document?</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_FILE_EXIT</source>
+ <translation>Exits the application</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_FILE_OPEN</source>
+ <translation>Opens an existing document</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_FILE_SAVE</source>
+ <translation>Saves the active document</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_FILE_LOAD</source>
+ <translation>Load a document</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_WINDOW_HTILE</source>
+ <translation>Arranges the windows as nonoverlapping horizontal tiles</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_WINDOW_VTILE</source>
+ <translation>Arranges the windows as nonoverlapping vertical tiles</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_WINDOW_TILE</source>
+ <translation>&Tile</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_FILE_EXIT</source>
+ <translation>E&xit</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_FILE_OPEN</source>
+ <translation>&Open...</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_FILE_LOAD</source>
+ <translation>Conn&ect...</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_FILE_SAVE</source>
+ <translation>&Save</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_EDIT_PASTE</source>
+ <translation>&Paste</translation>
+ </message>
+ <message>
+ <source>MEN_STUDIES_CHOICE</source>
+ <translation>Choose existent study.</translation>
+ </message>
+</context>
+<context>
+ <name>STD_Application</name>
+ <message>
+ <source>INF_DOC_MODIFIED</source>
+ <translation>Document has been modified.
+Do you want to save changes?</translation>
+ </message>
+ <message>
+ <source>INF_DOC_SAVING</source>
+ <translation>Saving study </translation>
+ </message>
+ <message>
+ <source>INF_DOC_SAVED</source>
+ <translation>Study %1 saved</translation>
+ </message>
+ <message>
+ <source>TOT_DOCK_WINDOWS</source>
+ <translation>Show / hide dockable windows and toolbars</translation>
+ </message>
+ <message>
+ <source>MEN_DOCK_WINDOWS</source>
+ <translation>Windows and Toolbars</translation>
+ </message>
+ <message>
+ <source>ABOUT_INFO</source>
+ <translation>SUIT Std application</translation>
+ </message>
+ <message>
+ <source>INF_DOC_SAVING_FAILS</source>
+ <translation>Can't save file "%1".
+Possible reason is permission denied or disc full.
+Try to use another file name.</translation>
+ </message>
+ <message>
+ <source>INF_DOCUMENT_MODIFIED</source>
+ <translation>Document "%1" has been modified.
+Do you want to save changes?</translation>
+ </message>
+</context>
+</TS>
lib_LTLIBRARIES = libsuit.la
-salomeinclude_HEADERS= \
- SUIT.h \
- SUIT_ActionOperation.h \
- SUIT_Application.h \
- SUIT_Convertor.h \
- SUIT_DataObject.h \
- SUIT_DataObjectIterator.h \
- SUIT_DataObjectKey.h \
- SUIT_DataOwner.h \
- SUIT_Desktop.h \
- SUIT_ExceptionHandler.h \
- SUIT_FileDlg.h \
- SUIT_FileValidator.h \
- SUIT_MessageBox.h \
- SUIT_Operation.h \
- SUIT_OverrideCursor.h \
- SUIT_ParserSettings.h \
- SUIT_PopupClient.h \
- SUIT_ResourceMgr.h \
- SUIT_SelectionMgr.h \
- SUIT_Selector.h \
- SUIT_Session.h \
- SUIT_SmartPtr.h \
- SUIT_Study.h \
- SUIT_ToolButton.h \
- SUIT_Tools.h \
- SUIT_ViewManager.h \
- SUIT_ViewModel.h \
- SUIT_ViewWindow.h \
- SUIT_SelectionFilter.h \
- SUIT_Accel.h \
- SUIT_TreeSync.h
+salomeinclude_HEADERS= \
+ SUIT.h \
+ SUIT_Accel.h \
+ SUIT_ActionOperation.h \
+ SUIT_Application.h \
+ SUIT_DataObject.h \
+ SUIT_DataObjectIterator.h \
+ SUIT_DataObjectKey.h \
+ SUIT_DataOwner.h \
+ SUIT_Desktop.h \
+ SUIT_ExceptionHandler.h \
+ SUIT_FileDlg.h \
+ SUIT_FileValidator.h \
+ SUIT_MessageBox.h \
+ SUIT_Operation.h \
+ SUIT_OverrideCursor.h \
+ SUIT_PopupClient.h \
+ SUIT_ResourceMgr.h \
+ SUIT_SelectionFilter.h \
+ SUIT_SelectionMgr.h \
+ SUIT_Selector.h \
+ SUIT_Session.h \
+ SUIT_SmartPtr.h \
+ SUIT_Study.h \
+ SUIT_ToolButton.h \
+ SUIT_Tools.h \
+ SUIT_TreeSync.h \
+ SUIT_ViewManager.h \
+ SUIT_ViewModel.h \
+ SUIT_ViewWindow.h
-dist_libsuit_la_SOURCES= \
- SUIT_ActionOperation.cxx \
- SUIT_Application.cxx \
- SUIT_DataObject.cxx \
- SUIT_DataObjectIterator.cxx \
- SUIT_DataObjectKey.cxx \
- SUIT_DataOwner.cxx \
- SUIT_Desktop.cxx \
- SUIT_ExceptionHandler.cxx \
- SUIT_FileDlg.cxx \
- SUIT_FileValidator.cxx \
- SUIT_MessageBox.cxx \
- SUIT_Operation.cxx \
- SUIT_OverrideCursor.cxx \
- SUIT_ParserSettings.cxx \
- SUIT_PopupClient.cxx \
- SUIT_ResourceMgr.cxx \
- SUIT_SelectionMgr.cxx \
- SUIT_Selector.cxx \
- SUIT_Session.cxx \
- SUIT_Study.cxx \
- SUIT_ToolButton.cxx \
- SUIT_Tools.cxx \
- SUIT_ViewManager.cxx \
- SUIT_ViewModel.cxx \
- SUIT_ViewWindow.cxx \
- SUIT_SelectionFilter.cxx \
- SUIT_Accel.cxx
+dist_libsuit_la_SOURCES= \
+ SUIT_Accel.cxx \
+ SUIT_ActionOperation.cxx \
+ SUIT_Application.cxx \
+ SUIT_DataObject.cxx \
+ SUIT_DataObjectIterator.cxx \
+ SUIT_DataObjectKey.cxx \
+ SUIT_DataOwner.cxx \
+ SUIT_Desktop.cxx \
+ SUIT_ExceptionHandler.cxx \
+ SUIT_FileDlg.cxx \
+ SUIT_FileValidator.cxx \
+ SUIT_MessageBox.cxx \
+ SUIT_Operation.cxx \
+ SUIT_OverrideCursor.cxx \
+ SUIT_PopupClient.cxx \
+ SUIT_ResourceMgr.cxx \
+ SUIT_SelectionFilter.cxx \
+ SUIT_SelectionMgr.cxx \
+ SUIT_Selector.cxx \
+ SUIT_Session.cxx \
+ SUIT_Study.cxx \
+ SUIT_ToolButton.cxx \
+ SUIT_Tools.cxx \
+ SUIT_ViewManager.cxx \
+ SUIT_ViewModel.cxx \
+ SUIT_ViewWindow.cxx
+
+MOC_FILES= \
+ SUIT_Accel_moc.cxx \
+ SUIT_ActionOperation_moc.cxx \
+ SUIT_Application_moc.cxx \
+ SUIT_DataObject_moc.cxx \
+ SUIT_Desktop_moc.cxx \
+ SUIT_FileDlg_moc.cxx \
+ SUIT_Operation_moc.cxx \
+ SUIT_PopupClient_moc.cxx \
+ SUIT_SelectionMgr_moc.cxx \
+ SUIT_Selector_moc.cxx \
+ SUIT_Session_moc.cxx \
+ SUIT_Study_moc.cxx \
+ SUIT_ToolButton_moc.cxx \
+ SUIT_ViewManager_moc.cxx \
+ SUIT_ViewModel_moc.cxx \
+ SUIT_ViewWindow_moc.cxx
-MOC_FILES= \
- SUIT_ActionOperation_moc.cxx \
- SUIT_Application_moc.cxx \
- SUIT_DataObject_moc.cxx \
- SUIT_Desktop_moc.cxx \
- SUIT_FileDlg_moc.cxx \
- SUIT_Operation_moc.cxx \
- SUIT_PopupClient_moc.cxx \
- SUIT_Session_moc.cxx \
- SUIT_Study_moc.cxx \
- SUIT_ToolButton_moc.cxx \
- SUIT_ViewModel_moc.cxx \
- SUIT_ViewWindow_moc.cxx \
- SUIT_ViewManager_moc.cxx \
- SUIT_SelectionMgr_moc.cxx \
- SUIT_Selector_moc.cxx \
- SUIT_Accel_moc.cxx
nodist_libsuit_la_SOURCES=$(MOC_FILES)
-dist_salomeres_DATA = \
- resources/cascade.png \
- resources/htile.png \
+dist_salomeres_DATA = \
+ resources/cascade.png \
+ resources/htile.png \
resources/vtile.png
-nodist_salomeres_DATA = \
- SUIT_images.qm \
+nodist_salomeres_DATA = \
+ SUIT_images.qm \
SUIT_msg_en.qm
libsuit_la_CPPFLAGS=$(QT_INCLUDES) -I$(srcdir)/../Qtx
#define SUIT_H
#if defined SUIT_EXPORTS
-#if defined WNT
+#if defined WIN32
#define SUIT_EXPORT __declspec( dllexport )
#else
#define SUIT_EXPORT
#endif
#else
-#if defined WNT
+#if defined WIN32
#define SUIT_EXPORT __declspec( dllimport )
#else
#define SUIT_EXPORT
#define true 1
#endif
-#if defined WNT
+#if defined WIN32
#pragma warning ( disable: 4251 )
#endif
--- /dev/null
+TEMPLATE = lib
+TARGET = suit
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+INCLUDEPATH += ../../include ../Qtx
+LIBS += -L../../lib -lqtx
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += SUIT_EXPORTS
+
+HEADERS = SUIT.h
+HEADERS += SUIT_Accel.h
+HEADERS += SUIT_ActionOperation.h
+HEADERS += SUIT_Application.h
+HEADERS += SUIT_DataObject.h
+HEADERS += SUIT_DataObjectIterator.h
+HEADERS += SUIT_DataObjectKey.h
+HEADERS += SUIT_DataOwner.h
+HEADERS += SUIT_Desktop.h
+HEADERS += SUIT_ExceptionHandler.h
+HEADERS += SUIT_FileDlg.h
+HEADERS += SUIT_FileValidator.h
+HEADERS += SUIT_MessageBox.h
+HEADERS += SUIT_Operation.h
+HEADERS += SUIT_OverrideCursor.h
+HEADERS += SUIT_PopupClient.h
+HEADERS += SUIT_ResourceMgr.h
+HEADERS += SUIT_SelectionFilter.h
+HEADERS += SUIT_SelectionMgr.h
+HEADERS += SUIT_Selector.h
+HEADERS += SUIT_Session.h
+HEADERS += SUIT_SmartPtr.h
+HEADERS += SUIT_Study.h
+HEADERS += SUIT_ToolButton.h
+HEADERS += SUIT_Tools.h
+HEADERS += SUIT_TreeSync.h
+HEADERS += SUIT_ViewManager.h
+HEADERS += SUIT_ViewModel.h
+HEADERS += SUIT_ViewWindow.h
+
+SOURCES = SUIT_Accel.cxx
+SOURCES += SUIT_ActionOperation.cxx
+SOURCES += SUIT_Application.cxx
+SOURCES += SUIT_DataObject.cxx
+SOURCES += SUIT_DataObjectIterator.cxx
+SOURCES += SUIT_DataObjectKey.cxx
+SOURCES += SUIT_DataOwner.cxx
+SOURCES += SUIT_Desktop.cxx
+SOURCES += SUIT_ExceptionHandler.cxx
+SOURCES += SUIT_FileDlg.cxx
+SOURCES += SUIT_FileValidator.cxx
+SOURCES += SUIT_MessageBox.cxx
+SOURCES += SUIT_Operation.cxx
+SOURCES += SUIT_OverrideCursor.cxx
+SOURCES += SUIT_PopupClient.cxx
+SOURCES += SUIT_ResourceMgr.cxx
+SOURCES += SUIT_SelectionFilter.cxx
+SOURCES += SUIT_SelectionMgr.cxx
+SOURCES += SUIT_Selector.cxx
+SOURCES += SUIT_Session.cxx
+SOURCES += SUIT_Study.cxx
+SOURCES += SUIT_ToolButton.cxx
+SOURCES += SUIT_Tools.cxx
+SOURCES += SUIT_ViewManager.cxx
+SOURCES += SUIT_ViewModel.cxx
+SOURCES += SUIT_ViewWindow.cxx
+
+TRANSLATIONS = resources/SUIT_images.ts \
+ resources/SUIT_msg_en.ts
+
+ICONS = resources/*.png
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+resources.files = $$ICONS resources/*.qm
+resources.path = ../../resources
+
+INSTALLS += includes resources
// SUIT_Accel.cxx: implementation of the SUIT_Accel class.
#include "SUIT_Accel.h"
+
#include "SUIT_ViewWindow.h"
#include "SUIT_ViewManager.h"
#include "SUIT_ViewModel.h"
-#include <qobjectlist.h>
-#include <qapplication.h>
-#include <qnamespace.h>
+#include <QCoreApplication>
+#include <QEvent>
+#include <QKeyEvent>
+/*!
+ \class SUIT_Accel
+ \brief Manager of keyboard accelerator bindings.
+*/
SUIT_Accel* SUIT_Accel::myself = 0;
/*! Constructor [private].*/
SUIT_Accel::SUIT_Accel()
- : QObject( qApp, "SUIT_Accel" )
+: QObject( QCoreApplication::instance() )
{
- qApp->installEventFilter( this );
+ QCoreApplication::instance()->installEventFilter( this );
}
/*! getAccel() : public interface for SUIT_Accel object. Only one instance is created and returned. */
/*! unsetActionKey() : unregister a certain key accelerator */
void SUIT_Accel::unsetActionKey( const int key, const QString& type )
{
- if ( myMap.contains( type ) ) {
+ if ( myMap.contains( type ) )
+ {
IdActionMap idActionMap = myMap[type];
- if ( idActionMap.contains( key ) ) {
- idActionMap.erase( key );
+ if ( idActionMap.contains( key ) )
+ {
+ idActionMap.remove( key );
myMap[type] = idActionMap;
}
}
/*! getParentViewWindow() : returns given object or any of its parents-grandparents-.. if it is a SUIT_ViewWindow */
SUIT_ViewWindow* getParentViewWindow( const QObject* obj )
{
- if ( obj ) {
+ if ( obj )
+ {
if ( obj->inherits( "SUIT_ViewWindow" ) )
return (SUIT_ViewWindow*)obj;
else
}
/*! getKey() : returns integer key code (with modifiers) made of key pressed 'inside' given event */
-int getKey( QKeyEvent *keyEvent )
+int getKey( QKeyEvent* keyEvent )
{
- int key = keyEvent->key(),
- state = keyEvent->state();
- if ( state & Qt::ShiftButton )
+ int key = keyEvent->key(), state = keyEvent->modifiers();
+ if ( state & Qt::ShiftModifier )
key += Qt::SHIFT;
- if ( state & Qt::ControlButton )
+ if ( state & Qt::ControlModifier )
key += Qt::CTRL;
- if ( state & Qt::AltButton )
+ if ( state & Qt::AltModifier )
key += Qt::ALT;
- if ( state & Qt::MetaButton )
+ if ( state & Qt::MetaModifier )
key += Qt::META;
return key;
}
-/*! getAccelKey() : returns key pressed if 1) event was KeyPress 2) pressed key is a registered accelerator */
+/*!
+ Returns key pressed if
+ -# event was KeyPress
+ -# pressed key is a registered accelerator
+*/
int SUIT_Accel::getAccelKey( QEvent *event )
{
if ( event && event->type() == QEvent::KeyPress ) {
//
// SUIT_Accel.h: interface for the SUIT_Accel class.
-#ifndef SUIT_Accel_h
-#define SUIT_Accel_h
+#ifndef SUIT_ACELL_H
+#define SUIT_ACELL_H
#include "SUIT.h"
-#include <qobject.h>
-#include <qstring.h>
-#include <qmap.h>
+#include <QMap>
+#include <QObject>
+#include <QString>
-/*!
- \class SUIT_Accel
- Manager of keyboard accelerator bindings
-*/
class SUIT_EXPORT SUIT_Accel: public QObject
{
Q_OBJECT
private:
SUIT_Accel();
- int getAccelKey( QEvent* ); // returns key pressed if 1) event was KeyPress
- // 2) pressed key is a registered accelerator
+ int getAccelKey( QEvent* );
- typedef QMap<int, int> IdActionMap; // key - to - action_id map
- typedef QMap<QString, IdActionMap> ViewerTypeIdActionMap; // viewer_type - to - IdActionMap
- ViewerTypeIdActionMap myMap;
+ typedef QMap<int, int> IdActionMap; //!< maps key to action id
+ typedef QMap<QString, IdActionMap>
+ ViewerTypeIdActionMap; //!< maps viewer type to IdActionMap
+ ViewerTypeIdActionMap myMap; //!< viewer actions map
- QMap<int, bool> myOptMap; // key - to - <not_used> map, used for optimazation. all registered keys (accelerators)
- // are stored in this map.
+ //! Maps key to <not_used> flag map, used for optimization.
+ //! All registered keys (accelerators) are stored in this map.
+ QMap<int, bool> myOptMap;
static SUIT_Accel* myself;
};
/*!Set action.
* Create new instance of QtxAction and set.
*/
-void SUIT_ActionOperation::setAction( const QString& text, const QIconSet& icon,
- const QString& menuText, QKeySequence accel,
- QObject* parent, const char* name, bool toggle )
+void SUIT_ActionOperation::setAction( const QString& text, const QIcon& icon,
+ const QString& menuText, QKeySequence accel,
+ QObject* parent, bool toggle )
{
- setAction( new QtxAction( text, icon, menuText, accel, parent, name, toggle ) );
+ setAction( new QtxAction( text, icon, menuText, accel, parent, toggle ) );
}
/*!Set action.
* Create new instance of QtxAction and set.
*/
void SUIT_ActionOperation::setAction( const QString& text, const QString& menuText,
- QKeySequence accel, QObject* parent, const char* name, bool toggle )
+ QKeySequence accel, QObject* parent, bool toggle )
{
- setAction( new QtxAction(text, menuText, accel, parent, name, toggle ) );
+ setAction( new QtxAction( text, menuText, accel, parent, toggle ) );
}
/*!Set action.
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
+
#ifndef SUIT_ACTIONOPERATION_H
#define SUIT_ACTIONOPERATION_H
#include "SUIT_Operation.h"
-class QtxAction;
+#include <QKeySequence>
+
+class QIcon;
class QString;
-class QIconSet;
-class QKeySequence;
class QWidget;
+class QtxAction;
+
/*!Provide support QtxAction*/
class SUIT_EXPORT SUIT_ActionOperation : public SUIT_Operation
{
Q_OBJECT
public:
- SUIT_ActionOperation( SUIT_Application* theApp );
+ SUIT_ActionOperation( SUIT_Application* );
virtual ~SUIT_ActionOperation();
QtxAction* action() const;
/** @name GUI management*/
//@{
- virtual void setAction( const QString& text, const QIconSet& icon, const QString& menuText,
- QKeySequence accel, QObject* parent, const char* name = 0, bool toggle = false );
+ virtual void setAction( const QString& text, const QIcon& icon, const QString& menuText,
+ QKeySequence accel, QObject* parent, bool toggle = false );
- virtual void setAction( const QString& text, const QString& menuText, QKeySequence accel,
- QObject* parent, const char* name = 0, bool toggle = false );
+ virtual void setAction( const QString& text, const QString& menuText,
+ QKeySequence accel, QObject* parent, bool toggle = false );
virtual void setAction( QtxAction* theAction );
bool addTo( QWidget* theWidget );
bool addTo( QWidget* theWidget, int thePos );
-
+
void setStatusTip( const QString& theTip );
//@}
-
+
private:
QtxAction* myAction;
//
#include "SUIT_Application.h"
+#include "SUIT_Study.h"
#include "SUIT_Session.h"
#include "SUIT_Desktop.h"
#include "SUIT_ResourceMgr.h"
-#include <qlabel.h>
-#include <qtimer.h>
-#include <qstatusbar.h>
+#include <QTimer>
+#include <QLabel>
+#include <QStatusBar>
#include <QtxAction.h>
#include <QtxActionMenuMgr.h>
myStudy( 0 ),
myDesktop( 0 ),
myStatusLabel( 0 )
-{
+{
+ if ( SUIT_Session::session() )
+ SUIT_Session::session()->insertApplication( this );
}
/*!
\return FALSE if application can not be closed (because of non saved data for example).
This method called by SUIT_Session whin closing of application was requested.
*/
-bool SUIT_Application::isPossibleToClose()
+bool SUIT_Application::isPossibleToClose( bool& closePermanently )
{
return true;
}
Opens other study into active Study. If Study is empty - creates it.
\param theName - name of study
*/
-bool SUIT_Application::useStudy( const QString& theName )
+bool SUIT_Application::useStudy( const QString& /*theName*/ )
{
return false;
}
*/
SUIT_Application* SUIT_Application::startApplication( int argc, char** argv ) const
{
- return startApplication( name(), argc, argv );
+ return startApplication( objectName(), argc, argv );
}
/*!
*/
void SUIT_Application::setMenuShown( QAction* a, const bool on )
{
- setMenuShown( actionId( a ), on );
+ if ( !a || !desktop() )
+ return;
+
+ QtxActionMenuMgr* mMgr = desktop()->menuMgr();
+ if ( mMgr )
+ mMgr->setShown( mMgr->actionId( a ), on );
}
/*!
*/
void SUIT_Application::setMenuShown( const int id, const bool on )
{
- if ( desktop() && desktop()->menuMgr() )
- desktop()->menuMgr()->setShown( id, on );
+ setMenuShown( action( id ), on );
}
/*!
*/
void SUIT_Application::setToolShown( QAction* a, const bool on )
{
- setToolShown( actionId( a ), on );
+ if ( !a || !desktop() )
+ return;
+
+ QtxActionToolMgr* tMgr = desktop()->toolMgr();
+ if ( tMgr )
+ tMgr->setShown( tMgr->actionId( a ), on );
}
/*!
*/
void SUIT_Application::setToolShown( const int id, const bool on )
{
- if ( desktop() && desktop()->toolMgr() )
- desktop()->toolMgr()->setShown( id, on );
+ setToolShown( action( id ), on );
}
/*!
int SUIT_Application::actionId( const QAction* a ) const
{
int id = -1;
- for ( QMap<int, QAction*>::ConstIterator it = myActionMap.begin();
- it != myActionMap.end() && id == -1;
- ++it ) {
- if ( it.data() == a )
+ for ( QMap<int, QAction*>::ConstIterator it = myActionMap.begin(); it != myActionMap.end() && id == -1; ++it )
+ {
+ if ( it.value() == a )
id = it.key();
}
return id;
\param reciever - object that contains slot
\param member - slot to be called when action is activated
*/
-QAction* SUIT_Application::createAction( const int id, const QString& text, const QIconSet& icon,
+QAction* SUIT_Application::createAction( const int id, const QString& text, const QIcon& icon,
const QString& menu, const QString& tip, const int key,
QObject* parent, const bool toggle, QObject* reciever, const char* member )
{
- QtxAction* a = new QtxAction( text, icon, menu, key, parent, 0, toggle );
+ QtxAction* a = new QtxAction( text, icon, menu, key, parent, toggle );
a->setStatusTip( tip );
if ( reciever && member )
- connect( a, SIGNAL( activated() ), reciever, member );
+ connect( a, SIGNAL( triggered( bool ) ), reciever, member );
registerAction( id, a );
#define SUIT_APPLICATION_H
#include "SUIT.h"
-#include "SUIT_Study.h"
-#include <qobject.h>
-#include <qwidget.h>
+#include <QObject>
+#include <QMap>
+class QIcon;
class QLabel;
class QString;
class QAction;
-class QIconSet;
+class QWidget;
+
class SUIT_Desktop;
-class SUIT_Convertor;
class SUIT_ViewModel;
class SUIT_ResourceMgr;
+class SUIT_Study;
#ifdef WIN32
#pragma warning ( disable:4251 )
/*! Returns FALSE if application can not be closed (because of non saved data for example).
This method called by SUIT_Session whin closing of application was requested. */
- virtual bool isPossibleToClose();
+ virtual bool isPossibleToClose( bool& );
/*! Performs some finalization of life cycle of this application.
For instance, the application can force its documents(s) to close. */
SUIT_ResourceMgr* resourceMgr() const;
- /*! Returns instance of data object Convertor class according to given Viewer.
- If convertation is not supported returns 0. */
- virtual SUIT_Convertor* getConvertor(const SUIT_ViewModel* theViewer) { return 0; }
-
//! Puts the message to the status bar
void putInfo ( const QString&, const int = 0 );
QAction* action( const int ) const;
int actionId( const QAction* ) const;
int registerAction( const int, QAction* );
- QAction* createAction( const int, const QString&, const QIconSet&, const QString&,
+ QAction* createAction( const int, const QString&, const QIcon&, const QString&,
const QString&, const int, QObject* = 0,
const bool = false, QObject* = 0, const char* = 0 );
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-// SUIT_Convertor.h: interface for the SUIT_Convertor class.
-//
-
-#if !defined(AFX_SUIT_CONVERTOR_H__4C27F4C7_DC7C_4BEF_9DC1_EFB97B387EBF__INCLUDED_)
-#define AFX_SUIT_CONVERTOR_H__4C27F4C7_DC7C_4BEF_9DC1_EFB97B387EBF__INCLUDED_
-
-#if _MSC_VER > 1000
-#pragma once
-#endif // _MSC_VER > 1000
-
-#include "SUIT.h"
-#include "SUIT_DataObject.h"
-#include "SUIT_ViewModel.h"
-
-/*! Provides convertation of selected object of specified viewer into SUIT_DataObject.
- * Instance of Convertor class is created by Application according to data type and viewers used.
- */
-class SUIT_Convertor
-{
-public:
- virtual DataObjectList getSelectedObjects(const SUIT_ViewModel* theViewer) = 0;
- virtual void highlight(const SUIT_ViewModel* theViewer, const DataObjectList& theObjList) = 0;
-};
-
-#endif // !defined(AFX_SUIT_CONVERTOR_H__4C27F4C7_DC7C_4BEF_9DC1_EFB97B387EBF__INCLUDED_)
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-#include "SUIT_DataObject.h"
-#include <qobject.h>
+#include "SUIT_DataObject.h"
#include "SUIT_DataObjectKey.h"
SUIT_DataObject::SUIT_DataObject( SUIT_DataObject* p )
: myParent( 0 ),
- mySignal( 0 ),
- myOpen( false ),
- myCheck( false )
+myOpen( false ),
+myCheck( false ),
+mySignal( 0 ),
+myAutoDel( true )
{
- myChildren.setAutoDelete( true );
-
setParent( p );
}
mySignal->setOwner( 0 );
}
- for ( QPtrListIterator<SUIT_DataObject> it( myChildren ); it.current(); ++it )
- it.current()->myParent = 0;
+ for ( DataObjectList::iterator it = myChildren.begin(); it != myChildren.end(); ++it )
+ (*it)->myParent = 0;
+
+ if ( autoDeleteChildren() )
+ {
+ for ( DataObjectList::iterator itr = myChildren.begin(); itr != myChildren.end(); ++itr )
+ delete *itr;
+ }
delete mySignal;
}
{
SUIT_DataObject* child = 0;
if ( !myChildren.isEmpty() )
- child = myChildren.getFirst();
+ child = myChildren.first();
return child;
}
{
SUIT_DataObject* child = 0;
if ( !myChildren.isEmpty() )
- child = myChildren.getLast();
+ child = myChildren.last();
return child;
}
int res = -1;
int i = 0;
- for ( DataObjectListIterator it( myChildren ); it.current() && res == -1; ++it, i++ )
+ for ( DataObjectList::const_iterator it = myChildren.begin(); it != myChildren.end() && res == -1; ++it, i++ )
{
- if ( it.current() == obj )
+ if ( *it == obj )
res = i;
}
bool SUIT_DataObject::autoDeleteChildren() const
{
- return myChildren.autoDelete();
+ return myAutoDel;
}
/*!
void SUIT_DataObject::setAutoDeleteChildren( const bool on )
{
- myChildren.setAutoDelete( on );
+ myAutoDel = on;
}
/*!
void SUIT_DataObject::children( DataObjectList& lst, const bool rec ) const
{
- for ( DataObjectListIterator it( myChildren ); it.current(); ++it )
+ for ( DataObjectList::const_iterator it = myChildren.begin(); it != myChildren.end(); ++it )
{
- lst.append( it.current() );
+ lst.append( *it );
if ( rec )
- it.current()->children( lst, rec );
+ (*it)->children( lst, rec );
}
}
void SUIT_DataObject::insertChild( SUIT_DataObject* theObj, int thePosition )
{
- if ( !theObj || myChildren.find( theObj ) != -1 )
+ if ( !theObj || myChildren.contains( theObj ) )
return;
int pos = thePosition < 0 ? myChildren.count() : thePosition;
- myChildren.insert( QMIN( pos, (int)myChildren.count() ), theObj );
+ myChildren.insert( qMin( pos, (int)myChildren.count() ), theObj );
theObj->setParent( this );
}
if ( !theObj )
return;
- bool ad = myChildren.autoDelete();
- myChildren.setAutoDelete( false );
-
- if ( myChildren.remove( theObj ) )
+ if ( myChildren.removeAll( theObj ) )
theObj->setParent( 0 );
-
- myChildren.setAutoDelete( ad );
}
/*!
DataObjectList lst;
obj->children( lst );
- for ( DataObjectListIterator it( lst ); it.current(); ++it )
- it.current()->setParent( this );
+ for ( DataObjectList::iterator it = lst.begin(); it != lst.end(); ++it )
+ (*it)->setParent( this );
}
/*!
void SUIT_DataObject::dump( const int indent ) const
{
QString strIndent = QString().fill( ' ', indent ); // indentation string
- printf( "%s%s\n", strIndent.latin1(), name().latin1() );
- for ( DataObjectListIterator it( myChildren ); it.current(); ++it ) // iterate all children
- it.current()->dump( indent + 2 ); // dump every child with indent + 2 spaces
+ printf( "%s%s\n", strIndent.toLatin1().data(), name().toLatin1().data() );
+ for ( DataObjectList::const_iterator it = myChildren.begin(); it != myChildren.end(); ++it )
+ (*it)->dump( indent + 2 );
}
/*!
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
+
#ifndef SUIT_DATAOBJECT_H
#define SUIT_DATAOBJECT_H
-#include <qobject.h>
-#include <qstring.h>
-#include <qpixmap.h>
-#include <qptrlist.h>
-
#include "SUIT.h"
+#include <QList>
+#include <QObject>
+#include <QString>
+#include <QPixmap>
+
class SUIT_DataObject;
class SUIT_DataObjectKey;
-typedef QPtrList<SUIT_DataObject> DataObjectList;
-typedef QPtrListIterator<SUIT_DataObject> DataObjectListIterator;
+typedef QList<SUIT_DataObject*> DataObjectList;
#ifdef WIN32
#pragma warning( disable:4251 )
void dump( const int indent = 2 ) const; // dump to cout
private:
+ SUIT_DataObject* myParent;
bool myOpen;
bool myCheck;
Signal* mySignal;
- SUIT_DataObject* myParent;
+ bool myAutoDel;
DataObjectList myChildren;
friend class SUIT_DataObject::Signal;
}
else
{
- aParent->myChildren.find( myCurrent );
+ int idx = aParent->myChildren.indexOf( myCurrent );
if ( myDetourType == DepthLeft )
- myCurrent = aParent->myChildren.next();
+ myCurrent = idx < aParent->myChildren.count() - 1 ? aParent->myChildren[idx + 1] : 0;
else
- myCurrent = aParent->myChildren.prev();
+ myCurrent = idx > 0 ? aParent->myChildren[idx - 1] : 0;
if ( !myCurrent )
{
myCurrent = aParent;
if ( obj && ( par = parent( obj ) ) )
{
- par->myChildren.find( obj );
- if ( par->myChildren.next() )
- return par->myChildren.current();
+ int idx = par->myChildren.indexOf( obj );
+ if ( idx < par->myChildren.count() - 1 )
+ return par->myChildren[idx + 1];
else
{
for ( ; par; par = globalSibling( par, next ) )
SUIT_DataObject* SUIT_DataObjectIterator::extreme( DataObjectList& aList, bool FromLeft ) const
{
if ( FromLeft )
- return aList.getFirst();
+ return aList.first();
else
- return aList.getLast();
+ return aList.last();
}
/*!
//
#include "SUIT_DataObjectKey.h"
-#include <qobject.h>
+#include <string.h>
-#ifndef WNT
+#ifndef WIN32
#include <typeinfo>
#define _typeinfo std::type_info
#else
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-
#include "SUIT_DataOwner.h"
-#ifndef WNT
+#ifndef WIN32
#include <typeinfo>
#define _typeinfo std::type_info
#else
return p1.isNull() && p2.isNull();
}
-// *** jfa: The below function has been put here 14.02.2007 from branch BR_Dev_For_4_0
-// *** and also improved for better comparison of DataOwners with DataSubOwners.
-// *** This comment is to be removed after merging with BR_Dev_For_4_0.
+
/*! Operator < allows to order suit data owners for map */
bool operator<( const SUIT_DataOwnerPtr& p1, const SUIT_DataOwnerPtr& p2 )
{
return (p1->keyString() < p2->keyString());
}
-// *** end
/*!
\class SUIT_DataOwnerPtrList
Constructor (default)
*/
SUIT_DataOwnerPtrList::SUIT_DataOwnerPtrList()
- : QValueList<SUIT_DataOwnerPtr>(),
- mySkipEqual( true )
+: QList<SUIT_DataOwnerPtr>(),
+mySkipEqual( true )
{
}
Constructor (default)
*/
SUIT_DataOwnerPtrList::SUIT_DataOwnerPtrList( const bool skipAllEqual )
- : QValueList<SUIT_DataOwnerPtr>(),
- mySkipEqual( skipAllEqual )
+: QList<SUIT_DataOwnerPtr>(),
+mySkipEqual( skipAllEqual )
{
}
Constructor (copy)
*/
SUIT_DataOwnerPtrList::SUIT_DataOwnerPtrList( const SUIT_DataOwnerPtrList& l )
- : QValueList<SUIT_DataOwnerPtr>( l ),
- mySkipEqual( true )
+: QList<SUIT_DataOwnerPtr>( l ),
+mySkipEqual( true )
{
}
Constructor (copy)
*/
SUIT_DataOwnerPtrList::SUIT_DataOwnerPtrList( const SUIT_DataOwnerPtrList& l, const bool skipAllEqual )
- : QValueList<SUIT_DataOwnerPtr>(),
- mySkipEqual( skipAllEqual )
+: QList<SUIT_DataOwnerPtr>(),
+mySkipEqual( skipAllEqual )
{
if ( skipAllEqual == l.mySkipEqual )
operator =( l );
{
SUIT_DataOwnerPtrList::const_iterator beginIt = l.begin();
SUIT_DataOwnerPtrList::const_iterator endIt = l.end();
- for( ; beginIt != endIt; ++beginIt )
+ for ( ; beginIt != endIt; ++beginIt )
append( *beginIt );
}
}
-#ifndef QT_NO_STL
-/*!
- Constructor (from stl)
-*/
-SUIT_DataOwnerPtrList::SUIT_DataOwnerPtrList( const std::list<SUIT_DataOwnerPtr>& l )
- : QValueList<SUIT_DataOwnerPtr>( l ),
- mySkipEqual( true )
-{
-}
-#endif
-
-#ifndef QT_NO_STL
-/*!
- Constructor (from stl)
-*/
-SUIT_DataOwnerPtrList::SUIT_DataOwnerPtrList( const std::list<SUIT_DataOwnerPtr>& l, const bool skipAllEqual )
- : QValueList<SUIT_DataOwnerPtr>(),
- mySkipEqual( skipAllEqual )
-{
- std::list<SUIT_DataOwnerPtr>::const_iterator beginIt = l.begin();
- std::list<SUIT_DataOwnerPtr>::const_iterator endIt = l.begin();
- for( ; beginIt != endIt; ++beginIt )
- append( *beginIt );
-}
-#endif
-
/*!
Appends an item to the list
*/
-SUIT_DataOwnerPtrList::iterator SUIT_DataOwnerPtrList::append( const SUIT_DataOwnerPtr& x )
+void SUIT_DataOwnerPtrList::append( const SUIT_DataOwnerPtr& x )
{
if ( mySkipEqual && myMap.contains( x ) ) //contains uses SUIT_DataOwnerPtr::operator==
- return myMap[ x ];
-
- iterator it = QValueList<SUIT_DataOwnerPtr>::append( x );
+ return;
- if ( mySkipEqual )
- myMap.insert( x, it );
+ QList<SUIT_DataOwnerPtr>::append( x );
- return it;
+ if ( mySkipEqual )
+ myMap.insert( x, 0 );
}
/*!
*/
void SUIT_DataOwnerPtrList::clear()
{
- if( mySkipEqual )
+ if ( mySkipEqual )
myMap.clear();
- QValueList<SUIT_DataOwnerPtr>::clear();
+
+ QList<SUIT_DataOwnerPtr>::clear();
}
/*!
*/
uint SUIT_DataOwnerPtrList::remove(const SUIT_DataOwnerPtr& x )
{
- if( mySkipEqual && myMap.contains(x) )
- myMap.remove(x);
- return QValueList<SUIT_DataOwnerPtr>::remove( x );
+ if ( mySkipEqual && myMap.contains(x) )
+ myMap.remove( x );
+
+ return QList<SUIT_DataOwnerPtr>::removeAll( x );
}
#include "SUIT_SmartPtr.h"
-#include <qvaluelist.h>
-#include <qmap.h>
+#include <QMap>
+#include <QList>
+#include <QString>
#ifdef WIN32
#pragma warning( disable:4251 )
public:
SUIT_DataOwner();//!< constructor
virtual ~SUIT_DataOwner();//!< destructor
- // *** jfa: The below line has been put here 14.02.2007.
- // *** It cancels modifications from branch BR_Dev_For_4_0
virtual QString keyString() const = 0;//!< used for comparison
};
/*! \class SUIT_DataOwnerPtrList
* \brief Manage list of SUIT_DataOwnerPtr.
*/
-class SUIT_EXPORT SUIT_DataOwnerPtrList : public QValueList<SUIT_DataOwnerPtr>
+class SUIT_EXPORT SUIT_DataOwnerPtrList : public QList<SUIT_DataOwnerPtr>
{
public:
SUIT_DataOwnerPtrList(); //!< constructor
SUIT_DataOwnerPtrList( const bool skipAllEqual );//!< constructor
SUIT_DataOwnerPtrList( const SUIT_DataOwnerPtrList& l ); //!< copy constructor
SUIT_DataOwnerPtrList( const SUIT_DataOwnerPtrList& l, const bool skipAllEqual );//!< copy constructor
-#ifndef QT_NO_STL
- SUIT_DataOwnerPtrList( const std::list<SUIT_DataOwnerPtr>& l ); //!< copy constructor for STL list
- SUIT_DataOwnerPtrList( const std::list<SUIT_DataOwnerPtr>& l, const bool skipAllEqual );//!< copy constructor for STL list
-#endif
- iterator append ( const SUIT_DataOwnerPtr& x );//!< append function
+ void append ( const SUIT_DataOwnerPtr& x );//!< append function
void clear ();
- uint remove (const SUIT_DataOwnerPtr& x );
+ uint remove ( const SUIT_DataOwnerPtr& x );
private:
// hide this methods: only append() should be used to add items to the list
void push_back ( const SUIT_DataOwnerPtr& x );//!< hide method
private:
- bool mySkipEqual;
- QMap<SUIT_DataOwnerPtr, iterator> myMap;
+ QMap<SUIT_DataOwnerPtr, int> myMap;
+ bool mySkipEqual;
};
#ifdef WIN32
//
#include "SUIT_Desktop.h"
-#include "SUIT_Tools.h"
#include "SUIT_ViewWindow.h"
#include <QtxLogoMgr.h>
#include <QtxActionMenuMgr.h>
#include <QtxActionToolMgr.h>
+#include <QApplication>
+#include <QCloseEvent>
+
/*!\class SUIT_Desktop
* Provide desktop management:\n
* \li menu manager
* \li windows
*/
+class SUIT_Desktop::ReparentEvent : public QEvent
+{
+public:
+ ReparentEvent( Type t, QObject* obj ) : QEvent( t ), myObj( obj ) {};
+
+ QObject* object() const { return myObj; }
+
+private:
+ QObject* myObj;
+};
+
/*!
Constructor.
*/
case QEvent::WindowDeactivate:
emit deactivated();
break;
+ default:
+ break;
}
return QMainWindow::event( e );
*/
void SUIT_Desktop::childEvent( QChildEvent* e )
{
- if ( e->type() == QEvent::ChildInserted && parentArea() &&
- e->child()->isWidgetType() && e->child()->inherits( "SUIT_ViewWindow" ) )
- {
- QWidget* wid = (QWidget*)e->child();
- bool vis = wid->isVisibleTo( wid->parentWidget() );
- wid->reparent( parentArea(), QPoint( 0, 0 ), vis );
- wid->setShown( vis );
- }
+ if ( e->type() == QEvent::ChildAdded && e->child()->isWidgetType() )
+ QApplication::postEvent( this, new QChildEvent( QEvent::Type( Reparent ), e->child() ) );
else
QtxMainWindow::childEvent( e );
}
+void SUIT_Desktop::customEvent( QEvent* e )
+{
+ if ( (int)e->type() != Reparent )
+ return;
+
+ QChildEvent* re = (QChildEvent*)e;
+ if ( re->child()->inherits( "SUIT_ViewWindow" ) )
+ {
+ QWidget* wid = (QWidget*)re->child();
+ bool invis = wid->testAttribute( Qt::WA_WState_ExplicitShowHide ) &&
+ wid->testAttribute( Qt::WA_WState_Hidden );
+
+ addWindow( wid );
+ wid->setShown( !invis );
+ }
+}
+
/*!
Gets menu manager.
*/
return myToolMgr;
}
+/*!
+ Gets logo manager.
+*/
+QtxLogoMgr* SUIT_Desktop::logoMgr() const
+{
+ return myLogoMgr;
+}
+
/*!
Returns the count of the existed logos.
*/
int SUIT_Desktop::logoCount() const
{
+ return 0;
+
if ( !myLogoMgr )
return 0;
else
}
/*!
- Adds new logo to the menu bar area.
- Obsolete. Not should be used.
- Use SUIT_Desktop::logoInsert();
-*/
-void SUIT_Desktop::addLogo( const QString& id, const QPixmap& pix )
-{
- logoInsert( id, pix );
-}
-
-/*!
- Removes a logo.
- Obsolete. Not should be used.
- Use SUIT_Desktop::logoRemove();
+ Adds new logo to the menu bar area
*/
-void SUIT_Desktop::removeLogo( const QString& id )
+void SUIT_Desktop::logoInsert( const QString& logoID, QMovie* logo, const int idx )
{
- logoRemove( id );
+ if ( myLogoMgr )
+ myLogoMgr->insert( logoID, logo, idx );
}
/*!
#include "SUIT.h"
-#include <qmap.h>
-#include <qpixmap.h>
+#include <QList>
+#include <QEvent>
+
#include <QtxMainWindow.h>
-class QPopupMenu;
+class QMovie;
+
class QtxLogoMgr;
-class SUIT_ViewWindow;
class QtxActionMenuMgr;
class QtxActionToolMgr;
+class SUIT_ViewWindow;
+
/*!
\class SUIT_Desktop
Provides standard desktop: main window with
{
Q_OBJECT
+ class ReparentEvent;
+
+ enum { Reparent = QEvent::User };
+
public:
SUIT_Desktop();
virtual ~SUIT_Desktop();
QtxActionMenuMgr* menuMgr() const;
QtxActionToolMgr* toolMgr() const;
+ QtxLogoMgr* logoMgr() const;
virtual SUIT_ViewWindow* activeWindow() const = 0;
- virtual QPtrList<SUIT_ViewWindow> windows() const = 0;
-
- void addLogo( const QString&, const QPixmap& ); // Not should be used. Will be removed.
- void removeLogo( const QString& ); // Not should be used. Will be removed.
+ virtual QList<SUIT_ViewWindow*> windows() const = 0;
int logoCount() const;
void logoClear();
void logoRemove( const QString& );
+ void logoInsert( const QString&, QMovie*, const int = -1 );
void logoInsert( const QString&, const QPixmap&, const int = -1 );
void emitActivated();
protected:
virtual bool event( QEvent* );
+ virtual void customEvent( QEvent* );
virtual void closeEvent( QCloseEvent* );
virtual void childEvent( QChildEvent* );
- virtual QWidget* parentArea() const = 0;
+ virtual void addWindow( QWidget* ) = 0;
private:
QtxActionMenuMgr* myMenuMgr;
#include "SUIT_MessageBox.h"
-#include <qapplication.h>
+#include <QApplication>
/*!\class SUIT_ExceptionHandler
* Show exception message on error handler.
while ( QApplication::overrideCursor() )
QApplication::restoreOverrideCursor();
- SUIT_MessageBox::error1( qApp->mainWidget(), title, msg, "OK" );
+ SUIT_MessageBox::critical( 0, title, msg );
}
#include "SUIT_Tools.h"
#include "SUIT_Session.h"
-#include "SUIT_Desktop.h"
#include "SUIT_MessageBox.h"
#include "SUIT_ResourceMgr.h"
#include "SUIT_FileValidator.h"
-#include <qdir.h>
-#include <qlabel.h>
-#include <qregexp.h>
-#include <qpalette.h>
-#include <qobjectlist.h>
-#include <qcombobox.h>
-#include <qpushbutton.h>
-#include <qapplication.h>
+#include <QDir>
+#include <QEvent>
+#include <QRegExp>
+#include <QLabel>
+#include <QComboBox>
+#include <QPushButton>
+#include <QGridLayout>
+#include <QApplication>
#define MIN_COMBO_SIZE 100
QString SUIT_FileDlg::myLastVisitedPath;
/*! Constructor */
-SUIT_FileDlg::SUIT_FileDlg( QWidget* parent, bool open, bool showQuickDir, bool modal ) :
-QFileDialog( parent, 0, modal ),
+SUIT_FileDlg::SUIT_FileDlg( QWidget* parent, bool open, bool showQuickDir, bool modal )
+: QFileDialog( parent ),
+myOpen( open ),
myValidator( 0 ),
-myQuickCombo( 0 ), myQuickButton( 0 ), myQuickLab( 0 ),
-myOpen( open )//,
+myQuickLab( 0 ),
+myQuickCombo( 0 ),
+myQuickButton( 0 )//,
//myAccepted( false )
-{
- const QObjectList* child = children();
- QObjectList::const_iterator anIt = child->begin(), aLast = child->end();
- for( ; anIt!=aLast; anIt++ )
- if( (*anIt)->inherits( "QPushButton" ) )
+{
+ setModal( modal );
+
+ const QObjectList& child = children();
+ for ( QObjectList::const_iterator anIt = child.begin(); anIt != child.end(); ++anIt )
+ {
+ QPushButton* pb = ::qobject_cast<QPushButton*>( *anIt );
+ if ( pb )
{
- QPushButton* bt = ( QPushButton* )( *anIt );
- bt->setDefault( false );
- bt->setAutoDefault( false );
+ pb->setDefault( false );
+ pb->setAutoDefault( false );
}
+ }
- if ( parent->icon() )
- setIcon( *parent->icon() );
+ if ( parent )
+ setWindowIcon( parent->windowIcon() );
setSizeGripEnabled( true );
- if ( showQuickDir ) {
+ QGridLayout* grid = ::qobject_cast<QGridLayout*>( layout() );
+ if ( showQuickDir && grid )
+ {
// inserting quick dir combo box
- myQuickLab = new QLabel(tr("LAB_QUICK_PATH"), this);
- myQuickCombo = new QComboBox(false, this);
- myQuickCombo->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
- myQuickCombo->setMinimumSize(MIN_COMBO_SIZE, 0);
+ myQuickLab = new QLabel( tr( "LAB_QUICK_PATH" ), this );
+ myQuickCombo = new QComboBox( this );
+ myQuickCombo->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
+ myQuickCombo->setMinimumSize( MIN_COMBO_SIZE, 0 );
- myQuickButton = new QPushButton(tr("BUT_ADD_PATH"), this);
+ myQuickButton = new QPushButton( tr( "BUT_ADD_PATH" ), this );
+
+ connect( myQuickCombo, SIGNAL( activated( const QString& ) ), this, SLOT( quickDir( const QString& ) ) );
+ connect( myQuickButton, SIGNAL( clicked() ), this, SLOT( addQuickDir() ) );
- connect(myQuickCombo, SIGNAL(activated(const QString&)), this, SLOT(quickDir(const QString&)));
- connect(myQuickButton, SIGNAL(clicked()), this, SLOT(addQuickDir()));
- addWidgets(myQuickLab, myQuickCombo, myQuickButton);
+ int row = grid->rowCount();
+ grid->addWidget( myQuickLab, row, 0 );
+ grid->addWidget( myQuickCombo, row, 1, 1, 3 );
+ grid->addWidget( myQuickButton, row, 5 );
// getting dir list from settings
QString dirs;
if ( resMgr )
dirs = resMgr->stringValue( "FileDlg", QString( "QuickDirList" ) );
- QStringList dirList = QStringList::split(';', dirs, false);
- if (dirList.count() > 0) {
- for (unsigned i = 0; i < dirList.count(); i++)
- myQuickCombo->insertItem(dirList[i]);
- }
- else {
- myQuickCombo->insertItem(QDir::homeDirPath());
+ QStringList dirList = dirs.split( ';' );
+ if ( dirList.count() > 0 )
+ {
+ for ( int i = 0; i < dirList.count(); i++ )
+ myQuickCombo->addItem( dirList[i] );
}
+ else
+ myQuickCombo->addItem( QDir::homePath() );
}
- setMode( myOpen ? ExistingFile : AnyFile );
- setCaption( myOpen ? tr( "INF_DESK_DOC_OPEN" ) : tr( "INF_DESK_DOC_SAVE" ) );
+ setAcceptMode( myOpen ? AcceptOpen: AcceptSave );
+ setWindowTitle( myOpen ? tr( "INF_DESK_DOC_OPEN" ) : tr( "INF_DESK_DOC_SAVE" ) );
// If last visited path doesn't exist -> switch to the first preferred path
- if ( !myLastVisitedPath.isEmpty() ) {
+ if ( !myLastVisitedPath.isEmpty() )
+ {
if ( !processPath( myLastVisitedPath ) && showQuickDir )
- processPath( myQuickCombo->text( 0 ) );
+ processPath( myQuickCombo->itemText( 0 ) );
}
- else {
+ else
+ {
if ( showQuickDir )
- processPath(myQuickCombo->text( 0 ) );
- }
+ processPath( myQuickCombo->itemText( 0 ) );
+ }
// set default file validator
myValidator = new SUIT_FileValidator(this);
setValidator( 0 );
}
+bool SUIT_FileDlg::event( QEvent* e )
+{
+ bool res = QFileDialog::event( e );
+
+ if ( e->type() == QEvent::Polish )
+ polish();
+
+ return res;
+}
+
/*! Redefined from QFileDialog.*/
void SUIT_FileDlg::polish()
{
- QFileDialog::polish();
- if ( myQuickButton && myQuickLab ) {
+/*
+ if ( myQuickButton && myQuickLab )
+ {
// the following is a workaround for proper layouting of custom widgets
QValueList<QPushButton*> buttonList;
QValueList<QLabel*> labelList;
(*lListIt)->setFixedWidth( maxLabWidth );
}
}
+*/
}
/*! Sets validator for file names to open/save
* (e.g. permission denied)
*/
// if ( !myAccepted ) {
- if ( mode() != ExistingFiles ) {
- mySelectedFile = QFileDialog::selectedFile();
+ if ( acceptMode() != AcceptOpen )
+ {
+ QString fn;
+ QStringList lst = QFileDialog::selectedFiles();
+ if ( !lst.isEmpty() )
+ fn = lst.first();
+ mySelectedFile = fn;
addExtension();
}
- if ( acceptData() ) {
- myLastVisitedPath = dirPath();
+ if ( acceptData() )
+ {
+ myLastVisitedPath = directory().path();
QFileDialog::accept();
// myAccepted = true;
}
{
if ( isOpenDlg() )
{
- if ( mode() == ExistingFiles )
+ if ( acceptMode() == AcceptOpen )
{
QStringList fileNames = selectedFiles();
for ( int i = 0; i < (int)fileNames.count(); i++ )
void SUIT_FileDlg::addExtension()
{
// check if file name entered is empty
- if ( mySelectedFile.stripWhiteSpace().isEmpty() )
+ if ( mySelectedFile.trimmed().isEmpty() )
return;
// current file extension
- QString anExt = "." + SUIT_Tools::extension( mySelectedFile.stripWhiteSpace() ).stripWhiteSpace();
+ QString anExt = "." + SUIT_Tools::extension( mySelectedFile.trimmed() ).trimmed();
// If the file already has extension and it does not match the filter there are two choices:
// - to leave it 'as is'
if ( anExt != "." && !IGNORE_NON_MATCHING_EXTENSION )
return;
- // get selected file filter
-#if QT_VERSION < 0x030000
- QRegExp r( QString::fromLatin1("(?[a-zA-Z0-9.*? +;#|]*)?$") );
- int len, index = r.match( selectedFilter().stripWhiteSpace(), 0, &len );
-#else
QRegExp r( QString::fromLatin1("\\(?[a-zA-Z0-9.*? +;#|]*\\)?$") );
- int index = r.search( selectedFilter().stripWhiteSpace() );
-#endif
+ int index = r.indexIn( selectedFilter().trimmed() );
if ( index >= 0 ) {
// Create wildcard regular expression basing on selected filter
// Due to transformations from the filter list (*.txt *.*xx *.c++ SUIT*.* ) we
// will have the pattern (\.txt|\..*xx|\.c\+\+|\..*) (as we validate extension only,
// we remove everything except extension mask from the pattern
-#if QT_VERSION < 0x030000
- QString wildcard = selectedFilter().mid( index, len ).stripWhiteSpace();
-#else
- QString wildcard = selectedFilter().mid( index, r.matchedLength() ).stripWhiteSpace();
-#endif
+ QString wildcard = selectedFilter().mid( index, r.matchedLength() ).trimmed();
// replace '|' and ';' separators by space symbol and also brackets if there are some
wildcard.replace( QRegExp( "[\\|;|(|)]" )," " );
- QString aPattern = wildcard.replace( QRegExp( "(^| )(\\s*)[0-9a-zA-Z*_?]*\\."), " \\." ).stripWhiteSpace().
+ QString aPattern = wildcard.replace( QRegExp( "(^| )(\\s*)[0-9a-zA-Z*_?]*\\."), " \\." ).trimmed().
replace( QRegExp( "\\s+" ), "|" ).replace( QRegExp( "[?]" ),".?" ).
replace( QRegExp( "[*]" ),".*" ).replace( QRegExp( "[+]" ),"\\+" );
// now we get the list of all extension masks and remove all which does not contain wildcard symbols
- QStringList extList = QStringList::split( "|",aPattern );
- for( int i = extList.count() - 1; i >= 0; i-- ) {
+ QStringList extList = aPattern.split( "|", QString::SkipEmptyParts );
+ for ( int i = extList.count() - 1; i >= 0; i-- )
+ {
if ( !extList[i].contains( "." ) )
- extList.remove( extList.at( i ) );
+ extList.removeAt( i );
}
aPattern = extList.join( "|" );
QRegExp anExtRExp( "^("+ aPattern + ")$" );
// Check if the current file extension matches the pattern
- if ( anExtRExp.match( anExt ) < 0 )
+ if ( !anExtRExp.exactMatch( anExt ) )
{
// find first appropriate extension in the selected filter
// (it should be without wildcard symbols)
for ( int i = 0; i < (int)extList.count(); i++ )
{
QString newExt = extList[i].replace( QRegExp( "[\\\\][+]" ),"+" );
- int res = newExt.findRev( '.' );
+ int res = newExt.lastIndexOf( '.' );
if ( res >= 0 )
newExt = newExt.mid( res + 1 );
- if ( newExt.find( QRegExp("[*|?]" ) ) < 0 )
+ if ( newExt.indexOf( QRegExp("[*|?]" ) ) < 0 )
{
- mySelectedFile.stripWhiteSpace();
+ mySelectedFile.trimmed();
mySelectedFile += mySelectedFile.endsWith(".") ? newExt : QString(".") + newExt;
break;
}
/*! Processes selection : tries to set given path or filename as selection */
bool SUIT_FileDlg::processPath( const QString& path )
{
- if ( !path.isNull() ) {
+ if ( !path.isNull() )
+ {
QFileInfo fi( path );
- if ( fi.exists() ) {
+ if ( fi.exists() )
+ {
if ( fi.isFile() )
- setSelection( path );
+ selectFile( path );
else if ( fi.isDir() )
- setDir( path );
+ setDirectory( path );
return true;
}
- else {
- if ( QFileInfo( fi.dirPath() ).exists() ) {
- setDir( fi.dirPath() );
- setSelection( path );
- return true;
+ else
+ {
+ if ( QFileInfo( SUIT_Tools::dir( path ) ).exists() )
+ {
+ setDirectory( SUIT_Tools::dir( path ) );
+ selectFile( path );
+ return true;
}
}
}
void SUIT_FileDlg::quickDir(const QString& dirPath)
{
QString aPath = dirPath;
- if ( !QDir(aPath).exists() ) {
- aPath = QDir::homeDirPath();
- SUIT_MessageBox::error1(this,
- tr("ERR_ERROR"),
- tr("ERR_DIR_NOT_EXIST").arg(dirPath),
- tr("BUT_OK"));
+ if ( !QDir(aPath).exists() )
+ {
+ aPath = QDir::homePath();
+ SUIT_MessageBox::critical( this, tr( "ERR_ERROR" ), tr( "ERR_DIR_NOT_EXIST" ).arg( dirPath ) );
}
else
- processPath(aPath);
+ processPath( aPath );
}
/*!
Called when user presses "Add" button - adds current directory to quick directory
*/
void SUIT_FileDlg::addQuickDir()
{
- QString dp = dirPath();
- if ( !dp.isEmpty() ) {
+ QString dp = directory().path();
+ if ( !dp.isEmpty() )
+ {
QDir dir( dp );
// getting dir list from settings
QString dirs;
SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
if ( resMgr )
dirs = resMgr->stringValue( "FileDlg", QString( "QuickDirList" ) );
- QStringList dirList = QStringList::split(';', dirs, false);
+ QStringList dirList = dirs.split( ';', QString::SkipEmptyParts );
bool found = false;
bool emptyAndHome = false;
- if ( dirList.count() > 0 ) {
- for ( unsigned i = 0; i < dirList.count(); i++ ) {
- QDir aDir( dirList[i] );
- if ( aDir.canonicalPath().isNull() && dirList[i] == dir.absPath() ||
- !aDir.canonicalPath().isNull() && aDir.exists() && aDir.canonicalPath() == dir.canonicalPath() ) {
- found = true;
- break;
- }
+ if ( dirList.count() > 0 )
+ {
+ for ( int i = 0; i < dirList.count(); i++ )
+ {
+ QDir aDir( dirList[i] );
+ if ( aDir.canonicalPath().isNull() && dirList[i] == dir.absolutePath() ||
+ !aDir.canonicalPath().isNull() && aDir.exists() && aDir.canonicalPath() == dir.canonicalPath() )
+ {
+ found = true;
+ break;
+ }
}
}
- else {
- emptyAndHome = dir.canonicalPath() == QDir(QDir::homeDirPath()).canonicalPath();
- }
- if ( !found ) {
+ else
+ emptyAndHome = dir.canonicalPath() == QDir( QDir::homePath() ).canonicalPath();
+
+ if ( !found )
+ {
dirList.append( dp );
- resMgr->setValue( "FileDlg", QString( "QuickDirList" ), dirList.join(";") );
+ resMgr->setValue( "FileDlg", QString( "QuickDirList" ), dirList.join( ";" ) );
if ( !emptyAndHome )
- myQuickCombo->insertItem( dp );
+ myQuickCombo->addItem( dp );
}
}
}
/*!
Returns the file name for Open/Save [ static ]
*/
-QString SUIT_FileDlg::getFileName( QWidget* parent,
- const QString& initial,
- const QStringList& filters,
- const QString& caption,
- bool open,
- bool showQuickDir,
- SUIT_FileValidator* validator )
+QString SUIT_FileDlg::getFileName( QWidget* parent, const QString& initial, const QStringList& filters,
+ const QString& caption, bool open, bool showQuickDir,
+ SUIT_FileValidator* validator )
{
SUIT_FileDlg* fd = new SUIT_FileDlg( parent, open, showQuickDir, true );
if ( !caption.isEmpty() )
- fd->setCaption( caption );
- if ( !initial.isEmpty() ) {
+ fd->setWindowTitle( caption );
+ if ( !initial.isEmpty() )
fd->processPath( initial ); // VSR 24/03/03 check for existing of directory has been added to avoid QFileDialog's bug
- }
- fd->setFilters( filters );
+
+ fd->setFilters( filters );
if ( validator )
fd->setValidator( validator );
+
fd->exec();
+
QString filename = fd->selectedFile();
delete fd;
- qApp->processEvents();
+
+ QApplication::processEvents();
+
return filename;
}
-
/*!
Returns the list of files to be opened [ static ]
*/
-QStringList SUIT_FileDlg::getOpenFileNames( QWidget* parent,
- const QString& initial,
- const QStringList& filters,
- const QString& caption,
- bool showQuickDir,
- SUIT_FileValidator* validator )
+QStringList SUIT_FileDlg::getOpenFileNames( QWidget* parent, const QString& initial, const QStringList& filters,
+ const QString& caption, bool showQuickDir, SUIT_FileValidator* validator )
{
SUIT_FileDlg* fd = new SUIT_FileDlg( parent, true, showQuickDir, true );
- fd->setMode( ExistingFiles );
+ fd->setFileMode( ExistingFiles );
if ( !caption.isEmpty() )
- fd->setCaption( caption );
- if ( !initial.isEmpty() ) {
+ fd->setWindowTitle( caption );
+ if ( !initial.isEmpty() )
fd->processPath( initial ); // VSR 24/03/03 check for existing of directory has been added to avoid QFileDialog's bug
- }
+
fd->setFilters( filters );
if ( validator )
fd->setValidator( validator );
+
fd->exec();
QStringList filenames = fd->selectedFiles();
delete fd;
- qApp->processEvents();
+
+ QApplication::processEvents();
return filenames;
}
/*!
Existing directory selection dialog [ static ]
*/
-QString SUIT_FileDlg::getExistingDirectory( QWidget* parent,
- const QString& initial,
- const QString& caption,
- bool showQuickDir )
+QString SUIT_FileDlg::getExistingDirectory( QWidget* parent, const QString& initial,
+ const QString& caption, bool showQuickDir )
{
- SUIT_FileDlg* fd = new SUIT_FileDlg( parent, true, showQuickDir, true);
+ SUIT_FileDlg* fd = new SUIT_FileDlg( parent, true, showQuickDir, true );
if ( !caption.isEmpty() )
- fd->setCaption( caption );
- if ( !initial.isEmpty() ) {
+ fd->setWindowTitle( caption );
+ if ( !initial.isEmpty() )
fd->processPath( initial ); // VSR 24/03/03 check for existing of directory has been added to avoid QFileDialog's bug
- }
- fd->setMode( DirectoryOnly );
- fd->setFilters(tr("INF_DIRECTORIES_FILTER"));
+
+ fd->setFileMode( DirectoryOnly );
+ fd->setFilters( QStringList( tr( "INF_DIRECTORIES_FILTER" ) ) );
+
fd->exec();
+
QString dirname = fd->selectedFile();
delete fd;
- qApp->processEvents();
- return dirname;
-
-}
-
-/*!
- QFileDialog::dirPath() has a bug on Linux Debian (1 level up from correct
- directory is returned). This function fixes the bug.
-*/
-QString SUIT_FileDlg::dirPath() const
-{
- if ( !mySelectedFile.isNull() )
- return QFileInfo( mySelectedFile ).dirPath();
- const QDir* aDir = dir();
- if ( aDir->exists() )
- return aDir->absPath();
-
- return QFileDialog::dirPath();
+ QApplication::processEvents();
+ return dirname;
}
#include "SUIT.h"
-#include <qfiledialog.h>
+#include <QFileDialog>
class QLabel;
class QComboBox;
void setValidator( SUIT_FileValidator* );
- QString dirPath() const; // QFileDialog::dirPath() has a bug on Linux Debian (1 level up from correct
- // directory is returned). This redefinition fixes the bug.
-
static QString getFileName( QWidget* parent, const QString& initial, const QStringList& filters,
const QString& caption, const bool open, const bool showQuickDir = true,
SUIT_FileValidator* validator = 0 );
static QString getExistingDirectory( QWidget* parent, const QString& initial,
const QString& caption, const bool showQuickDir = true );
-public slots:
- void polish();
-
private:
+ void polish();
bool acceptData();
void addExtension();
bool processPath( const QString& path );
void quickDir( const QString& );
void addQuickDir();
+protected:
+ virtual bool event( QEvent* );
+
protected:
bool myOpen; //!< open/save selector
QString mySelectedFile; //!< selected filename
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-// SALOME SALOMEGUI : implementation of desktop and GUI kernel
-//
-// File : SUIT_FileValidator.cxx
-// Module : SALOME
-// $Header$
-
#include "SUIT_FileValidator.h"
+
#include "SUIT_MessageBox.h"
-#include "SUIT_Session.h"
-#include <qfile.h>
-#include <qfileinfo.h>
+#include <QFile>
+#include <QFileInfo>
/*! constructor */
SUIT_FileValidator::SUIT_FileValidator(QWidget* parent) :
/*! returns false if can't open file */
bool SUIT_FileValidator::canOpen( const QString& file )
{
- if ( !QFile::exists( file ) ) {
- SUIT_MessageBox::error1( myParent,
- QObject::tr( "ERR_ERROR" ),
- QObject::tr( "ERR_FILE_NOT_EXIST" ).arg( file ),
- QObject::tr( "BUT_OK" ) );
+ if ( !QFile::exists( file ) )
+ {
+ SUIT_MessageBox::critical( myParent, QObject::tr( "ERR_ERROR" ),
+ QObject::tr( "ERR_FILE_NOT_EXIST" ).arg( file ) );
return false;
- }
- if ( !QFileInfo( file ).isReadable() ) {
- SUIT_MessageBox::error1( myParent,
- QObject::tr( "ERR_ERROR" ),
- QObject::tr( "ERR_PERMISSION_DENIED" ).arg( file ),
- QObject::tr( "BUT_OK" ) );
+ }
+ if ( !QFileInfo( file ).isReadable() )
+ {
+ SUIT_MessageBox::critical( myParent, QObject::tr( "ERR_ERROR" ),
+ QObject::tr( "ERR_PERMISSION_DENIED" ).arg( file ) );
return false;
}
return true;
/*! returns false if can't save file */
bool SUIT_FileValidator::canSave( const QString& file )
{
- if ( QFile::exists( file ) ) {
+ if ( QFile::exists( file ) )
+ {
// if file exists - raise warning...
- if ( SUIT_MessageBox::warn2( myParent,
- QObject::tr( "WRN_WARNING" ),
- QObject::tr( "QUE_DOC_FILEEXISTS" ).arg( file ),
- QObject::tr( "BUT_YES" ),
- QObject::tr( "BUT_NO" ),
- SUIT_YES,
- SUIT_NO,
- SUIT_NO ) == SUIT_NO ) {
+ if ( SUIT_MessageBox::question( myParent, QObject::tr( "WRN_WARNING" ),
+ QObject::tr( "QUE_DOC_FILEEXISTS" ).arg( file ),
+ SUIT_MessageBox::Yes | SUIT_MessageBox::No,
+ SUIT_MessageBox::No ) != SUIT_MessageBox::Yes )
+ {
return false;
}
// ... and if user wants to overwrite file, check it for writeability
- if ( !QFileInfo( file ).isWritable() ) {
- SUIT_MessageBox::error1( myParent,
- QObject::tr( "ERR_ERROR" ),
- QObject::tr( "ERR_PERMISSION_DENIED" ).arg( file ),
- QObject::tr( "BUT_OK" ) );
+ if ( !QFileInfo( file ).isWritable() )
+ {
+ SUIT_MessageBox::critical( myParent, QObject::tr( "ERR_ERROR" ),
+ QObject::tr( "ERR_PERMISSION_DENIED" ).arg( file ) );
return false;
}
}
- else {
+ else
+ {
// if file doesn't exist - try to create it
QFile qf( file );
- if ( !qf.open( IO_WriteOnly ) ) {
- SUIT_MessageBox::error1( myParent,
- QObject::tr( "ERR_ERROR" ),
- QObject::tr( "ERR_PERMISSION_DENIED" ).arg( file ),
- QObject::tr( "BUT_OK" ) );
+ if ( !qf.open( QFile::WriteOnly ) )
+ {
+ SUIT_MessageBox::critical( myParent, QObject::tr( "ERR_ERROR" ),
+ QObject::tr( "ERR_PERMISSION_DENIED" ).arg( file ) );
return false;
}
- else {
+ else
+ {
// remove just created file
qf.close();
qf.remove();
}
return true;
}
-
//
// SALOME SALOMEGUI : implementation of desktop and GUI kernel
//
-// File : SUIT_FileValidator.h
-// Module : SALOME
-
#ifndef SUIT_FILEVALIDATOR_H
#define SUIT_FILEVALIDATOR_H
-#include <qwidget.h>
#include "SUIT.h"
+class QWidget;
+class QString;
+
/*!
\class SUIT_FileValidator
Provides functionality to check file
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
+#include "SUIT_MessageBox.h"
+
+#include "SUIT_OverrideCursor.h"
+
+#include <QMessageBox>
+#include <QPushButton>
+#include <QApplication>
+#include <QString>
+
+#include <stdarg.h>
+
/*!
- \class: SUIT_MessageBox
- Message dialog box for SUIT-based application
- Module: SUIT
- Created: UI team, 02.10.00
+ \class SUIT_MessageBox
+ \brief Message dialog box for SUIT-based application
+
+ The class provides a modal dialog with a short message, an icon,
+ and buttons laid out depending on the current style.
+
+ Message boxes are used to provide informative messages and to ask
+ simple questions.
+
+ The easiest way to pop up a message box is to call one of the static
+ functions information(), question(), critical(), and warning().
+
+ The class provides the static functions to show message boxes with
+ standard buttons (like \c Ok, \c Cancel, \c Apply, \c Close, \c Yes,
+ \c No, \c Abort, \c Retry, etc). These methods accept ORed buttons
+ flags as one of the parameters. The buttons layouting type and order
+ is system-dependant and defined by the current style. In addition,
+ these methods allow to define default button (where input focus is
+ set by default and which is clicked when user presses \c Enter key).
+
+ Another set of static functions allows to show message boxes with
+ up to four user-defined buttons. It is possible to define default
+ and escape buttons using additional parameters.
+
+ And finally, the last group of static functions allow displaying
+ the message boxes with an arbitrary number of buttons.
+
+ For example:
+ \code
+ // show question message box with two standard buttons
+ int result = SUIT_MessageBox::question(desktop(), "Error",
+ "File already exists? Overwrite?",
+ SUIT_MessageBox::Yes | SUIT_MessageBox::No,
+ SUIT_MessageBox::No );
+ if ( result == SUIT_MessageBox::Yes )
+ overwriteFileFunction();
+
+ // show critical message box with user-defined buttons
+ // default is second button and escape is third button
+ int result = SUIT_MessageBox::critical(desktop(), "Hazard!",
+ "The situation is critical! What to do?",
+ "Hide", "Run Away", "Stand still", 1, 2);
+ switch ( result )
+ {
+ case 0:
+ hideMyself(); break;
+ case 1:
+ runAwayFromHere(); break;
+ case 2:
+ sitDownAndPray(); break;
+ default:
+ break;
+ }
+
+ // show message box with 6 buttons
+ // both default and escape buttons are set to first button ("Zero")
+ int result = SUIT_MessageBox::information(desktop(), "Question",
+ "Select your favourite number",
+ 0, 0,
+ "Zero", "One", "Two", "Three", "Four", "Five");
+ useMyFavouriteNumberSomewhere( result );
+ \endcode
*/
-#include "SUIT_MessageBox.h"
-#include "SUIT_OverrideCursor.h"
+/*!
+ \brief Constructor.
+ \param parent parent widget
+*/
+SUIT_MessageBox::SUIT_MessageBox( QWidget* parent )
+: QMessageBox( parent )
+{
+}
-#include <qmessagebox.h>
-#include <qapplication.h>
+/*!
+ \brief Constructor.
+ \param icon message box icon (QMessageBox::Icon)
+ \param title message box title
+ \param text message box text
+ \param buttons ORed message box standard buttons (QMessageBox::StandardButton)
+ \param parent parent widget
+ \param f window flags
+*/
+SUIT_MessageBox::SUIT_MessageBox( Icon icon, const QString& title, const QString& text,
+ StandardButtons buttons, QWidget* parent, Qt::WindowFlags f )
+: QMessageBox( icon, title, text, buttons, parent, f )
+{
+}
/*!
- Shows info message box with one button [ static ]
+ \brief Destructor.
*/
-int SUIT_MessageBox::info1( QWidget* parent,
- const QString& caption,
- const QString& text,
- const QString& textButton0 )
+SUIT_MessageBox::~SUIT_MessageBox()
{
- SUIT_OverrideCursor cw( parent ? parent->cursor() : Qt::arrowCursor );
- int ret = QMessageBox::information( parent, caption, text, textButton0,
- QString::null, QString::null, 0, 0 );
- qApp->processEvents();
- return ret;
}
/*!
- Shows warning message box with one button [ static ]
+ \brief Get the standard button text.
+ \param btn standard button id
+ \return button text
*/
-int SUIT_MessageBox::warn1( QWidget* parent,
- const QString& caption,
- const QString& text,
- const QString& textButton0 )
+QString SUIT_MessageBox::buttonText( StandardButton btn ) const
{
- SUIT_OverrideCursor cw( parent ? parent->cursor() : Qt::arrowCursor );
- int ret = QMessageBox::warning( parent, caption, text, textButton0,
- QString::null, QString::null, 0, 0 );
- qApp->processEvents();
- return ret;
+ QString res;
+ QAbstractButton* b = button( btn );
+ if ( b )
+ res = b->text();
+ return res;
}
/*!
- Shows error message box with one button [ static ]
+ \brief Set the standard button text.
+ \param btn standard button id
+ \param text new button text
*/
-int SUIT_MessageBox::error1( QWidget* parent,
- const QString& caption,
- const QString& text,
- const QString& textButton0 )
+void SUIT_MessageBox::setButtonText( StandardButton btn, const QString& text )
{
- SUIT_OverrideCursor cw( parent ? parent->cursor() : Qt::arrowCursor );
- int ret = QMessageBox::critical( parent, caption, text, textButton0,
- QString::null, QString::null, 0, 0 );
- qApp->processEvents();
- return ret;
+ QAbstractButton* b = button( btn );
+ if ( b )
+ b->setText( text );
}
/*!
- Shows question message box with one button [ static ]
+ \brief Show critical message box with specified standard buttons.
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param buttons ORed message box buttons (QMessageBox::StandardButton)
+ \param defaultButton default button (QMessageBox::StandardButton)
+ \return button id clicked by the user (QMessageBox::StandardButton)
*/
-int SUIT_MessageBox::question1( QWidget* parent,
- const QString& caption,
- const QString& text,
- const QString& textButton0 )
+SUIT_MessageBox::StandardButton SUIT_MessageBox::critical( QWidget* parent, const QString& title, const QString& text,
+ StandardButtons buttons, StandardButton defaultButton )
{
- SUIT_OverrideCursor cw( parent ? parent->cursor() : Qt::arrowCursor );
- int ret = QMessageBox::question( parent, caption, text, textButton0,
- QString::null, QString::null, 0, 0 );
- qApp->processEvents();
- return ret;
+ return QMessageBox::critical( parent, title, text, buttons, defaultButton );
}
/*!
- Shows info message box with two buttons.
- Returns id of the pressed button or -1 if escaped [ static ]
+ \brief Show warning message box with specified standard buttons.
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param buttons ORed message box buttons (QMessageBox::StandardButton)
+ \param defaultButton default button (QMessageBox::StandardButton)
+ \return button id clicked by the user (QMessageBox::StandardButton)
*/
-int SUIT_MessageBox::info2( QWidget* parent,
- const QString& caption,
- const QString& text,
- const QString& textButton0,
- const QString& textButton1,
- int idButton0, int idButton1, int idDefault )
+SUIT_MessageBox::StandardButton SUIT_MessageBox::warning( QWidget* parent, const QString& title, const QString& text,
+ SUIT_MessageBox::StandardButtons buttons, StandardButton defaultButton )
{
- SUIT_OverrideCursor cw( parent ? parent->cursor() : Qt::arrowCursor );
- if ( idDefault == idButton0 )
- idDefault = 0;
- else if ( idDefault == idButton1 )
- idDefault = 1;
- else
- idDefault = 0;
-
- int ret = QMessageBox::information( parent, caption, text, textButton0,
- textButton1, QString::null, idDefault );
- qApp->processEvents();
- return ( ret == 0 ? idButton0 : idButton1 );
+ return QMessageBox::warning( parent, title, text, buttons, defaultButton );
}
/*!
- Shows warning message box with two buttons.
- Returns id of the pressed button or -1 if escaped [ static ]
+ \brief Show information message box with specified standard buttons.
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param buttons ORed message box buttons (QMessageBox::StandardButton)
+ \param defaultButton default button (QMessageBox::StandardButton)
+ \return button id clicked by the user (QMessageBox::StandardButton)
*/
-int SUIT_MessageBox::warn2( QWidget* parent,
- const QString& caption,
- const QString& text,
- const QString& textButton0,
- const QString& textButton1,
- int idButton0, int idButton1, int idDefault )
+SUIT_MessageBox::StandardButton SUIT_MessageBox::information( QWidget* parent, const QString& title, const QString& text,
+ StandardButtons buttons, StandardButton defaultButton )
{
- SUIT_OverrideCursor cw( parent ? parent->cursor() : Qt::arrowCursor );
-
- if ( idDefault == idButton0 )
- idDefault = 0;
- else if ( idDefault == idButton1 )
- idDefault = 1;
- else
- idDefault = 0;
-
- int ret = QMessageBox::warning( parent, caption, text, textButton0,
- textButton1, QString::null, idDefault );
- qApp->processEvents();
- return ( ret == 0 ? idButton0 : idButton1 );
+ return QMessageBox::information( parent, title, text, buttons, defaultButton );
}
/*!
- Shows error message box with two buttons
- Returns id of the pressed button or -1 if escaped [ static ]
+ \brief Show question message box with specified standard buttons.
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param buttons ORed message box buttons (QMessageBox::StandardButton)
+ \param defaultButton default button (QMessageBox::StandardButton)
+ \return button id clicked by the user (QMessageBox::StandardButton)
*/
-int SUIT_MessageBox::error2( QWidget* parent,
- const QString& caption,
- const QString& text,
- const QString& textButton0,
- const QString& textButton1,
- int idButton0, int idButton1, int idDefault )
+SUIT_MessageBox::StandardButton SUIT_MessageBox::question( QWidget* parent, const QString& title, const QString& text,
+ StandardButtons buttons, StandardButton defaultButton )
{
- SUIT_OverrideCursor cw( parent ? parent->cursor() : Qt::arrowCursor );
-
- if ( idDefault == idButton0 )
- idDefault = 0;
- else if ( idDefault == idButton1 )
- idDefault = 1;
- else
- idDefault = 0;
-
- int ret = QMessageBox::critical( parent, caption, text, textButton0,
- textButton1, QString::null, idDefault );
- qApp->processEvents();
- return ( ret == 0 ? idButton0 : idButton1 );
+ return QMessageBox::question( parent, title, text,buttons, defaultButton );
}
/*!
- Shows question message box with two buttons
- Returns id of the pressed button or -1 if escaped [ static ]
+ \brief Show critical message box with one custom button.
+
+ Specified button becomes "default" button and "escape" button, i.e.
+ pressing \c Return or \c Enter and \c Escape keys is equivalent to clicking
+ this button.
+
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param button button text
+ \return button id clicked by the user (QMessageBox::StandardButton)
*/
-int SUIT_MessageBox::question2( QWidget* parent,
- const QString& caption,
- const QString& text,
- const QString& textButton0,
- const QString& textButton1,
- int idButton0, int idButton1, int idDefault )
+int SUIT_MessageBox::critical( QWidget* parent, const QString& title, const QString& text,
+ const QString& button )
{
- SUIT_OverrideCursor cw( parent ? parent->cursor() : Qt::arrowCursor );
-
- if ( idDefault == idButton0 )
- idDefault = 0;
- else if ( idDefault == idButton1 )
- idDefault = 1;
- else
- idDefault = 0;
+ ButtonInfos lst;
+ lst.append( ButtonInfo( 0, button ) );
+ return messageBox( SUIT_MessageBox::Critical, parent, title, text, lst );
+}
+
+/*!
+ \brief Show warning message box with one custom button.
- int ret = QMessageBox::question( parent, caption, text, textButton0,
- textButton1, QString::null, idDefault );
- qApp->processEvents();
- return ( ret == 0 ? idButton0 : idButton1 );
+ Specified button becomes "default" button and "escape" button, i.e.
+ pressing \c Return or \c Enter and \c Escape keys is equivalent to clicking
+ this button.
+
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param button button text
+ \return button id clicked by the user (QMessageBox::StandardButton)
+*/
+int SUIT_MessageBox::warning( QWidget* parent, const QString& title, const QString& text,
+ const QString& button )
+{
+ ButtonInfos lst;
+ lst.append( ButtonInfo( 0, button ) );
+ return messageBox( SUIT_MessageBox::Warning, parent, title, text, lst );
}
/*!
- Shows info message box with three buttons.
- Returns id of the pressed button or -1 if escaped [ static ]
+ \brief Show information message box with one custom button.
+
+ Specified button becomes "default" button and "escape" button, i.e.
+ pressing \c Return or \c Enter and \c Escape keys is equivalent to clicking
+ this button.
+
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param button button text
+ \return button id clicked by the user (QMessageBox::StandardButton)
*/
-int SUIT_MessageBox::info3( QWidget* parent,
- const QString& caption,
- const QString& text,
- const QString& textButton0,
- const QString& textButton1,
- const QString& textButton2,
- int idButton0, int idButton1,
- int idButton2, int idDefault )
+int SUIT_MessageBox::information( QWidget* parent, const QString& title, const QString& text,
+ const QString& button )
{
- SUIT_OverrideCursor cw( parent ? parent->cursor() : Qt::arrowCursor );
-
- if ( idDefault == idButton0 )
- idDefault = 0;
- else if ( idDefault == idButton1 )
- idDefault = 1;
- else if ( idDefault == idButton2 )
- idDefault = 2;
- else
- idDefault = 0;
-
- int ret = QMessageBox::information( parent, caption, text, textButton0,
- textButton1, textButton2, idDefault );
- qApp->processEvents();
- switch ( ret )
- {
- case 0:
- return idButton0;
- case 1:
- return idButton1;
- case 2:
- return idButton2;
- }
- return -1;
+ ButtonInfos lst;
+ lst.append( ButtonInfo( 0, button ) );
+ return messageBox( SUIT_MessageBox::Information, parent, title, text, lst );
}
/*!
- Shows warning message box with three buttons.
- Returns id of the pressed button or -1 if escaped [ static ]
+ \brief Show question message box with one custom button.
+
+ \warning This function does not make a lot of sense because it provides
+ message box with only one button, i.e. it is impossible to give several
+ answers for the question (at least 'yes'/'no').
+ This function is implemented only for completeness.
+
+ Specified button becomes "default" button and "escape" button, i.e.
+ pressing \c Return or \c Enter and \c Escape keys is equivalent to clicking
+ this button.
+
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param button button text
+ \return button id clicked by the user (QMessageBox::StandardButton)
*/
-int SUIT_MessageBox::warn3( QWidget* parent,
- const QString& caption,
- const QString& text,
- const QString& textButton0,
- const QString& textButton1,
- const QString& textButton2,
- int idButton0, int idButton1,
- int idButton2, int idDefault )
+int SUIT_MessageBox::question( QWidget* parent, const QString& title, const QString& text,
+ const QString& button )
{
- SUIT_OverrideCursor cw( parent ? parent->cursor() : Qt::arrowCursor );
-
- if ( idDefault == idButton0 )
- idDefault = 0;
- else if ( idDefault == idButton1 )
- idDefault = 1;
- else if ( idDefault == idButton2 )
- idDefault = 2;
- else
- idDefault = 0;
-
- int ret = QMessageBox::warning( parent, caption, text, textButton0,
- textButton1, textButton2, idDefault );
- qApp->processEvents();
- switch ( ret )
- {
- case 0:
- return idButton0;
- case 1:
- return idButton1;
- case 2:
- return idButton2;
- }
- return -1;
+ ButtonInfos lst;
+ lst.append( ButtonInfo( 0, button ) );
+ return messageBox( SUIT_MessageBox::Question, parent, title, text, lst );
}
/*!
- Shows error message box with three buttons.
- Returns id of the pressed button or -1 if escaped [ static ]
+ \brief Show critical message box with two custom buttons.
+
+ Parameters \a button1 and \a button2 specify the buttons text.
+ The function returns clicked button id. The identifiers for the buttons
+ are assigned automatically. The first button is identified as 0, the
+ second one as 1.
+
+ The \a defaultButton parameter allows to specify the button which is assigned
+ for the \c Return or \c Enter key. Similarly, \a escapeButton parameter
+ allows specifing the button which is assigned for \c Escape key.
+ If these parameters are not specified (-1 by default), the first button
+ is set as default button and the second one is defined as escape button.
+
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param button1 first button text
+ \param button2 second button text
+ \param defaultButton default button
+ \param escapeButton escape button
+ \return button used button id
*/
-int SUIT_MessageBox::error3( QWidget* parent,
- const QString& caption,
- const QString& text,
- const QString& textButton0,
- const QString& textButton1,
- const QString& textButton2,
- int idButton0, int idButton1,
- int idButton2, int idDefault )
+int SUIT_MessageBox::critical( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2,
+ const int defaultButton, const int escapeButton )
{
- SUIT_OverrideCursor cw( parent ? parent->cursor() : Qt::arrowCursor );
-
- if ( idDefault == idButton0 )
- idDefault = 0;
- else if ( idDefault == idButton1 )
- idDefault = 1;
- else if ( idDefault == idButton2 )
- idDefault = 2;
- else
- idDefault = 0;
+ ButtonInfos lst;
+ int id = 0;
+ lst.append( ButtonInfo( id++, button1 ) );
+ lst.append( ButtonInfo( id++, button2 ) );
+ return messageBox( SUIT_MessageBox::Critical, parent, title, text, lst,
+ defaultButton, escapeButton );
+}
+
+/*!
+ \brief Show warning message box with two custom buttons.
+
+ Parameters \a button1 and \a button2 specify the buttons text.
+ The function returns clicked button id. The identifiers for the buttons
+ are assigned automatically. The first button is identified as 0, the
+ second one as 1.
+
+ The \a defaultButton parameter allows to specify the button which is assigned
+ for the \c Return or \c Enter key. Similarly, \a escapeButton parameter
+ allows specifing the button which is assigned for \c Escape key.
+ If these parameters are not specified (-1 by default), the first button
+ is set as default button and the second one is defined as escape button.
+
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param button1 first button text
+ \param button2 second button text
+ \param defaultButton default button
+ \param escapeButton escape button
+ \return button used button id
+*/
+int SUIT_MessageBox::warning( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2,
+ const int defaultButton, const int escapeButton )
+{
+ ButtonInfos lst;
+ int id = 0;
+ lst.append( ButtonInfo( id++, button1 ) );
+ lst.append( ButtonInfo( id++, button2 ) );
+ return messageBox( SUIT_MessageBox::Warning, parent, title, text, lst,
+ defaultButton, escapeButton );
+}
+
+/*!
+ \brief Show information message box with two custom buttons.
+
+ Parameters \a button1 and \a button2 specify the buttons text.
+ The function returns clicked button id. The identifiers for the buttons
+ are assigned automatically. The first button is identified as 0, the
+ second one as 1.
+
+ The \a defaultButton parameter allows to specify the button which is assigned
+ for the \c Return or \c Enter key. Similarly, \a escapeButton parameter
+ allows specifing the button which is assigned for \c Escape key.
+ If these parameters are not specified (-1 by default), the first button
+ is set as default button and the second one is defined as escape button.
+
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param button1 first button text
+ \param button2 second button text
+ \param defaultButton default button
+ \param escapeButton escape button
+ \return button used button id
+*/
+int SUIT_MessageBox::information( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2,
+ const int defaultButton, const int escapeButton )
+{
+ ButtonInfos lst;
+ int id = 0;
+ lst.append( ButtonInfo( id++, button1 ) );
+ lst.append( ButtonInfo( id++, button2 ) );
+ return messageBox( SUIT_MessageBox::Information, parent, title, text, lst,
+ defaultButton, escapeButton );
+}
+
+/*!
+ \brief Show question message box with two custom buttons.
+
+ Parameters \a button1 and \a button2 specify the buttons text.
+ The function returns clicked button id. The identifiers for the buttons
+ are assigned automatically. The first button is identified as 0, the
+ second one as 1.
+
+ The \a defaultButton parameter allows to specify the button which is assigned
+ for the \c Return or \c Enter key. Similarly, \a escapeButton parameter
+ allows specifing the button which is assigned for \c Escape key.
+ If these parameters are not specified (-1 by default), the first button
+ is set as default button and the second one is defined as escape button.
+
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param button1 first button text
+ \param button2 second button text
+ \param defaultButton default button
+ \param escapeButton escape button
+ \return button used button id
+*/
+int SUIT_MessageBox::question( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2,
+ const int defaultButton, const int escapeButton )
+{
+ ButtonInfos lst;
+ int id = 0;
+ lst.append( ButtonInfo( id++, button1 ) );
+ lst.append( ButtonInfo( id++, button2 ) );
+ return messageBox( SUIT_MessageBox::Question, parent, title, text, lst,
+ defaultButton, escapeButton );
+}
+
+/*!
+ \brief Show critical message box with three custom buttons.
+
+ Parameters \a button1, \a button2 and \a button3 specify the buttons text.
+ The function returns clicked button id. The identifiers for the buttons
+ are assigned automatically. The first button is identified as 0, the
+ second one as 1, etc.
+
+ The \a defaultButton parameter allows to specify the button which is assigned
+ for the \c Return or \c Enter key. Similarly, \a escapeButton parameter
+ allows specifing the button which is assigned for \c Escape key.
+ If these parameters are not specified (-1 by default), the first button
+ is set as default button and the last one is defined as escape button.
+
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param button1 first button text
+ \param button2 second button text
+ \param button3 third button text
+ \param defaultButton default button
+ \param escapeButton escape button
+ \return button used button id
+*/
+int SUIT_MessageBox::critical( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2,
+ const QString& button3,
+ const int defaultButton, const int escapeButton )
+{
+ ButtonInfos lst;
+ int id = 0;
+ lst.append( ButtonInfo( id++, button1 ) );
+ lst.append( ButtonInfo( id++, button2 ) );
+ lst.append( ButtonInfo( id++, button3 ) );
+ return messageBox( SUIT_MessageBox::Critical, parent, title, text, lst,
+ defaultButton, escapeButton );
+}
+
+/*!
+ \brief Show warning message box with three custom buttons.
+
+ Parameters \a button1, \a button2 and \a button3 specify the buttons text.
+ The function returns clicked button id. The identifiers for the buttons
+ are assigned automatically. The first button is identified as 0, the
+ second one as 1, etc.
+
+ The \a defaultButton parameter allows to specify the button which is assigned
+ for the \c Return or \c Enter key. Similarly, \a escapeButton parameter
+ allows specifing the button which is assigned for \c Escape key.
+ If these parameters are not specified (-1 by default), the first button
+ is set as default button and the last one is defined as escape button.
+
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param button1 first button text
+ \param button2 second button text
+ \param button3 third button text
+ \param defaultButton default button
+ \param escapeButton escape button
+ \return button used button id
+*/
+int SUIT_MessageBox::warning( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2,
+ const QString& button3,
+ const int defaultButton, const int escapeButton )
+{
+ ButtonInfos lst;
+ int id = 0;
+ lst.append( ButtonInfo( id++, button1 ) );
+ lst.append( ButtonInfo( id++, button2 ) );
+ lst.append( ButtonInfo( id++, button3 ) );
+ return messageBox( SUIT_MessageBox::Warning, parent, title, text, lst,
+ defaultButton, escapeButton );
+}
+
+/*!
+ \brief Show information message box with three custom buttons.
+
+ Parameters \a button1, \a button2 and \a button3 specify the buttons text.
+ The function returns clicked button id. The identifiers for the buttons
+ are assigned automatically. The first button is identified as 0, the
+ second one as 1, etc.
+
+ The \a defaultButton parameter allows to specify the button which is assigned
+ for the \c Return or \c Enter key. Similarly, \a escapeButton parameter
+ allows specifing the button which is assigned for \c Escape key.
+ If these parameters are not specified (-1 by default), the first button
+ is set as default button and the last one is defined as escape button.
+
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param button1 first button text
+ \param button2 second button text
+ \param button3 third button text
+ \param defaultButton default button
+ \param escapeButton escape button
+ \return button used button id
+*/
+int SUIT_MessageBox::information( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2,
+ const QString& button3,
+ const int defaultButton, const int escapeButton )
+{
+ ButtonInfos lst;
+ int id = 0;
+ lst.append( ButtonInfo( id++, button1 ) );
+ lst.append( ButtonInfo( id++, button2 ) );
+ lst.append( ButtonInfo( id++, button3 ) );
+ return messageBox( SUIT_MessageBox::Information, parent, title, text, lst,
+ defaultButton, escapeButton );
+}
+
+/*!
+ \brief Show question message box with three custom buttons.
+
+ Parameters \a button1, \a button2 and \a button3 specify the buttons text.
+ The function returns clicked button id. The identifiers for the buttons
+ are assigned automatically. The first button is identified as 0, the
+ second one as 1, etc.
+
+ The \a defaultButton parameter allows to specify the button which is assigned
+ for the \c Return or \c Enter key. Similarly, \a escapeButton parameter
+ allows specifing the button which is assigned for \c Escape key.
+ If these parameters are not specified (-1 by default), the first button
+ is set as default button and the last one is defined as escape button.
+
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param button1 first button text
+ \param button2 second button text
+ \param button3 third button text
+ \param defaultButton default button
+ \param escapeButton escape button
+ \return button used button id
+*/
+int SUIT_MessageBox::question( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2,
+ const QString& button3,
+ const int defaultButton, const int escapeButton )
+{
+ ButtonInfos lst;
+ int id = 0;
+ lst.append( ButtonInfo( id++, button1 ) );
+ lst.append( ButtonInfo( id++, button2 ) );
+ lst.append( ButtonInfo( id++, button3 ) );
+ return messageBox( SUIT_MessageBox::Question, parent, title, text, lst,
+ defaultButton, escapeButton );
+}
+
+/*!
+ \brief Show critical message box with four custom buttons.
+
+ Parameters \a button1, \a button2, \a button3 and \a button4 specify
+ the buttons text.
+ The function returns clicked button id. The identifiers for the buttons
+ are assigned automatically. The first button is identified as 0, the
+ second one as 1, etc.
+
+ The \a defaultButton parameter allows to specify the button which is assigned
+ for the \c Return or \c Enter key. Similarly, \a escapeButton parameter
+ allows specifing the button which is assigned for \c Escape key.
+ If these parameters are not specified (-1 by default), the first button
+ is set as default button and the last one is defined as escape button.
+
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param button1 first button text
+ \param button2 second button text
+ \param button3 third button text
+ \param button4 fourth button text
+ \param defaultButton default button
+ \param escapeButton escape button
+ \return button used button id
+*/
+int SUIT_MessageBox::critical( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2,
+ const QString& button3, const QString& button4,
+ const int defaultButton, const int escapeButton )
+{
+ ButtonInfos lst;
+ int id = 0;
+ lst.append( ButtonInfo( id++, button1 ) );
+ lst.append( ButtonInfo( id++, button2 ) );
+ lst.append( ButtonInfo( id++, button3 ) );
+ lst.append( ButtonInfo( id++, button4 ) );
+ return messageBox( SUIT_MessageBox::Critical, parent, title, text, lst,
+ defaultButton, escapeButton );
+}
+
+/*!
+ \brief Show warning message box with four custom buttons.
+
+ Parameters \a button1, \a button2, \a button3 and \a button4 specify
+ the buttons text.
+ The function returns clicked button id. The identifiers for the buttons
+ are assigned automatically. The first button is identified as 0, the
+ second one as 1, etc.
+
+ The \a defaultButton parameter allows to specify the button which is assigned
+ for the \c Return or \c Enter key. Similarly, \a escapeButton parameter
+ allows specifing the button which is assigned for \c Escape key.
+ If these parameters are not specified (-1 by default), the first button
+ is set as default button and the last one is defined as escape button.
+
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param button1 first button text
+ \param button2 second button text
+ \param button3 third button text
+ \param button4 fourth button text
+ \param defaultButton default button
+ \param escapeButton escape button
+ \return button used button id
+*/
+int SUIT_MessageBox::warning( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2,
+ const QString& button3, const QString& button4,
+ const int defaultButton, const int escapeButton )
+{
+ ButtonInfos lst;
+ int id = 0;
+ lst.append( ButtonInfo( id++, button1 ) );
+ lst.append( ButtonInfo( id++, button2 ) );
+ lst.append( ButtonInfo( id++, button3 ) );
+ lst.append( ButtonInfo( id++, button4 ) );
+ return messageBox( SUIT_MessageBox::Warning, parent, title, text, lst,
+ defaultButton, escapeButton );
+}
+
+/*!
+ \brief Show information message box with four custom buttons.
+
+ Parameters \a button1, \a button2, \a button3 and \a button4 specify
+ the buttons text.
+ The function returns clicked button id. The identifiers for the buttons
+ are assigned automatically. The first button is identified as 0, the
+ second one as 1, etc.
+
+ The \a defaultButton parameter allows to specify the button which is assigned
+ for the \c Return or \c Enter key. Similarly, \a escapeButton parameter
+ allows specifing the button which is assigned for \c Escape key.
+ If these parameters are not specified (-1 by default), the first button
+ is set as default button and the last one is defined as escape button.
+
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param button1 first button text
+ \param button2 second button text
+ \param button3 third button text
+ \param button4 fourth button text
+ \param defaultButton default button
+ \param escapeButton escape button
+ \return button used button id
+*/
+int SUIT_MessageBox::information( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2,
+ const QString& button3, const QString& button4,
+ const int defaultButton, const int escapeButton )
+{
+ ButtonInfos lst;
+ int id = 0;
+ lst.append( ButtonInfo( id++, button1 ) );
+ lst.append( ButtonInfo( id++, button2 ) );
+ lst.append( ButtonInfo( id++, button3 ) );
+ lst.append( ButtonInfo( id++, button4 ) );
+ return messageBox( SUIT_MessageBox::Information, parent, title, text, lst,
+ defaultButton, escapeButton );
+}
+
+/*!
+ \brief Show question message box with four custom buttons.
+
+ Parameters \a button1, \a button2, \a button3 and \a button4 specify
+ the buttons text.
+ The function returns clicked button id. The identifiers for the buttons
+ are assigned automatically. The first button is identified as 0, the
+ second one as 1, etc.
+
+ The \a defaultButton parameter allows to specify the button which is assigned
+ for the \c Return or \c Enter key. Similarly, \a escapeButton parameter
+ allows specifing the button which is assigned for \c Escape key.
+ If these parameters are not specified (-1 by default), the first button
+ is set as default button and the last one is defined as escape button.
+
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param button1 first button text
+ \param button2 second button text
+ \param button3 third button text
+ \param button4 fourth button text
+ \param defaultButton default button
+ \param escapeButton escape button
+ \return button used button id
+*/
+int SUIT_MessageBox::question( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2,
+ const QString& button3, const QString& button4,
+ const int defaultButton, const int escapeButton )
+{
+ ButtonInfos lst;
+ int id = 0;
+ lst.append( ButtonInfo( id++, button1 ) );
+ lst.append( ButtonInfo( id++, button2 ) );
+ lst.append( ButtonInfo( id++, button3 ) );
+ lst.append( ButtonInfo( id++, button4 ) );
+ return messageBox( SUIT_MessageBox::Question, parent, title, text, lst,
+ defaultButton, escapeButton );
+}
+
+/*!
+ \brief Show critical message box with arbitrary number of user-specified
+ buttons.
+
+ The function accepts arbitrary number of parameters. Each parameter starting
+ from \a btn should be of type const char* to specify the button text.
+ After the last button parameter and additional 0 (zero) value should be
+ specified.
- int ret = QMessageBox::critical( parent, caption, text, textButton0,
- textButton1, textButton2, idDefault );
- qApp->processEvents();
- switch ( ret )
- {
- case 0:
- return idButton0;
- case 1:
- return idButton1;
- case 2:
- return idButton2;
- }
- return -1;
+ The function returns clicked button id. The identifiers for the buttons
+ are assigned automatically. The first button is identified as 0, the
+ second one as 1, etc.
+
+ The \a defaultButton parameter allows to specify the button which is assigned
+ for the \c Return or \c Enter key. Similarly, \a escapeButton parameter
+ allows specifing the button which is assigned for \c Escape key.
+ If these parameters are not specified (-1 by default), the first button
+ is set as default button and the last one is defined as escape button.
+
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param defaultButton default button
+ \param escapeButton escape button
+ \param btn first button text
+ \return button used button id
+*/
+int SUIT_MessageBox::critical( QWidget* parent, const QString& title, const QString& text,
+ const int defaultButton, const int escapeButton,
+ char* btn, ... )
+{
+ va_list args;
+ va_start( args, btn );
+ return messageBox( SUIT_MessageBox::Critical, parent, title, text,
+ messageList( btn, args ),
+ defaultButton, escapeButton );
}
/*!
- Shows question message box with three buttons.
- Returns id of the pressed button or -1 if escaped [ static ]
+ \brief Show warning message box with arbitrary number of user-specified
+ buttons.
+
+ The function accepts arbitrary number of parameters. Each parameter starting
+ from \a btn should be of type const char* to specify the button text.
+ After the last button parameter and additional 0 (zero) value should be
+ specified.
+
+ The function returns clicked button id. The identifiers for the buttons
+ are assigned automatically. The first button is identified as 0, the
+ second one as 1, etc.
+
+ The \a defaultButton parameter allows to specify the button which is assigned
+ for the \c Return or \c Enter key. Similarly, \a escapeButton parameter
+ allows specifing the button which is assigned for \c Escape key.
+ If these parameters are not specified (-1 by default), the first button
+ is set as default button and the last one is defined as escape button.
+
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param defaultButton default button
+ \param escapeButton escape button
+ \param btn first button text
+ \return button used button id
*/
-int SUIT_MessageBox::question3( QWidget* parent,
- const QString& caption,
- const QString& text,
- const QString& textButton0,
- const QString& textButton1,
- const QString& textButton2,
- int idButton0, int idButton1,
- int idButton2, int idDefault )
+int SUIT_MessageBox::warning( QWidget* parent, const QString& title, const QString& text,
+ const int defaultButton, const int escapeButton,
+ char* btn, ... )
{
- SUIT_OverrideCursor cw( parent ? parent->cursor() : Qt::arrowCursor );
+ va_list args;
+ va_start( args, btn );
+ return messageBox( SUIT_MessageBox::Warning, parent, title, text,
+ messageList( btn, args ),
+ defaultButton, escapeButton );
+}
+
+/*!
+ \brief Show information message box with arbitrary number of user-specified
+ buttons.
+
+ The function accepts arbitrary number of parameters. Each parameter starting
+ from \a btn should be of type const char* to specify the button text.
+ After the last button parameter and additional 0 (zero) value should be
+ specified.
- if ( idDefault == idButton0 )
- idDefault = 0;
- else if ( idDefault == idButton1 )
- idDefault = 1;
- else if ( idDefault == idButton2 )
- idDefault = 2;
- else
- idDefault = 0;
+ The function returns clicked button id. The identifiers for the buttons
+ are assigned automatically. The first button is identified as 0, the
+ second one as 1, etc.
+
+ The \a defaultButton parameter allows to specify the button which is assigned
+ for the \c Return or \c Enter key. Similarly, \a escapeButton parameter
+ allows specifing the button which is assigned for \c Escape key.
+ If these parameters are not specified (-1 by default), the first button
+ is set as default button and the last one is defined as escape button.
+
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param defaultButton default button
+ \param escapeButton escape button
+ \param btn first button text
+ \return button used button id
+*/
+int SUIT_MessageBox::information( QWidget* parent, const QString& title, const QString& text,
+ const int defaultButton, const int escapeButton,
+ char* btn, ... )
+{
+ va_list args;
+ va_start( args, btn );
+ return messageBox( SUIT_MessageBox::Information, parent, title, text,
+ messageList( btn, args ),
+ defaultButton, escapeButton );
+}
+
+/*!
+ \brief Show question message box with arbitrary number of user-specified
+ buttons.
+
+ The function accepts arbitrary number of parameters. Each parameter starting
+ from \a btn should be of type const char* to specify the button text.
+ After the last button parameter and additional 0 (zero) value should be
+ specified.
- int ret = QMessageBox::question( parent, caption, text, textButton0,
- textButton1, textButton2, idDefault );
- qApp->processEvents();
- switch ( ret )
- {
- case 0:
- return idButton0;
- case 1:
- return idButton1;
- case 2:
- return idButton2;
- }
- return -1;
+ The function returns clicked button id. The identifiers for the buttons
+ are assigned automatically. The first button is identified as 0, the
+ second one as 1, etc.
+
+ The \a defaultButton parameter allows to specify the button which is assigned
+ for the \c Return or \c Enter key. Similarly, \a escapeButton parameter
+ allows specifing the button which is assigned for \c Escape key.
+ If these parameters are not specified (-1 by default), the first button
+ is set as default button and the last one is defined as escape button.
+
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param defaultButton default button
+ \param escapeButton escape button
+ \param btn first button text
+ \return button used button id
+*/
+int SUIT_MessageBox::question( QWidget* parent, const QString& title, const QString& text,
+ const int defaultButton, const int escapeButton,
+ char* btn, ... )
+{
+ va_list args;
+ va_start( args, btn );
+ return messageBox( SUIT_MessageBox::Question, parent, title, text,
+ messageList( btn, args ),
+ defaultButton, escapeButton );
+}
+
+/*!
+ \brief Parse arbitrary arguments list.
+
+ The last parameter in a sequence should be 0 (zero) value.
+
+ \param txt first argument which starts arbitrary sequence
+ \param args arguments list from the stack
+ \return list of buttons infos
+*/
+SUIT_MessageBox::ButtonInfos SUIT_MessageBox::messageList( char* txt, va_list& args )
+{
+ int i = 0;
+ ButtonInfos lst;
+ char* cur = txt;
+ while ( cur )
+ {
+ lst.append( ButtonInfo( i++, cur ) );
+ cur = va_arg( args, char* );
+ }
+
+ va_end( args );
+
+ return lst;
}
+
+/*!
+ \brief Create and show the message box.
+ \param icon icon type
+ \param parent parent widget
+ \param title message box title
+ \param text message box text
+ \param lst list of buttons infos
+ \param defaultButton default button
+ \param escapeButton escape button
+ \return button used button id
+*/
+int SUIT_MessageBox::messageBox( Icon icon, QWidget* parent,
+ const QString& title, const QString& text,
+ const ButtonInfos& lst,
+ const int defaultButton,
+ const int escapeButton )
+{
+ SUIT_MessageBox msgBox( icon, title, text, NoButton, parent );
+
+ QMap<QAbstractButton*, int> bm;
+ for ( int i = 0; i < lst.count(); i++ )
+ {
+ int btn = lst[i].id();
+ QString txt = lst[i].text();
+ ButtonRole role = lst[i].role();
+
+ QPushButton* pb = msgBox.addButton( txt, role );
+ bm.insert( pb, btn );
+
+ if ( defaultButton == -1 && i == 0 || btn == defaultButton )
+ msgBox.setDefaultButton( pb );
+ if ( escapeButton == -1 && i == lst.count() - 1 || btn == escapeButton )
+ msgBox.setEscapeButton( pb );
+ }
+
+ SUIT_OverrideCursor cw( parent ? parent->cursor() : Qt::ArrowCursor );
+
+ int res = msgBox.exec();
+ if ( res != -1 )
+ res = bm[msgBox.clickedButton()];
+
+ QApplication::processEvents();
+
+ return res;
+}
+
#include "SUIT.h"
-#include <qstring.h>
-#include <qwidget.h>
+#include <QMap>
+#include <QList>
+#include <QMessageBox>
-#define SUIT_OK 1
-#define SUIT_CANCEL 2
-#define SUIT_YES 3
-#define SUIT_NO 4
-#define SUIT_HELP 5
-
-/*!
- \class SUIT_MessageBox
- \brief Message dialog box for SUIT-based application
-*/
-class SUIT_EXPORT SUIT_MessageBox
+class SUIT_EXPORT SUIT_MessageBox : public QMessageBox
{
public:
-
- /** @name One button message boxes.*/
- //@{
- static int info1 ( QWidget* parent, const QString& caption, const QString& text,
- const QString& textButton0 );
- static int warn1 ( QWidget* parent, const QString& caption, const QString& text,
- const QString& textButton0 );
- static int error1 ( QWidget* parent, const QString& caption, const QString& text,
- const QString& textButton0 );
- static int question1 ( QWidget* parent, const QString& caption, const QString& text,
- const QString& textButton0 );
- //@}
+ // construction/destruction
+ SUIT_MessageBox( QWidget* = 0 );
+ SUIT_MessageBox( Icon, const QString&, const QString&, StandardButtons buttons = NoButton,
+ QWidget* = 0, Qt::WindowFlags = Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint );
+ ~SUIT_MessageBox();
+
+ // customize the standard buttons text
+ QString buttonText( StandardButton ) const;
+ void setButtonText( StandardButton, const QString& );
+
+ // message box with standard buttons
+ static StandardButton critical( QWidget* parent, const QString& title, const QString& text,
+ StandardButtons buttons = Ok, StandardButton defaultButton = NoButton );
+ static StandardButton warning( QWidget* parent, const QString& title, const QString& text,
+ StandardButtons buttons = Ok, StandardButton defaultButton = NoButton );
+ static StandardButton information( QWidget* parent, const QString& title, const QString& text,
+ StandardButtons buttons = Ok, StandardButton defaultButton = NoButton );
+ static StandardButton question( QWidget* parent, const QString& title, const QString& text,
+ StandardButtons buttons = Ok, StandardButton defaultButton = NoButton );
+
+ // message boxes with one custom button
+ static int critical( QWidget* parent, const QString& title, const QString& text,
+ const QString& button );
+ static int warning( QWidget* parent, const QString& title, const QString& text,
+ const QString& button );
+ static int information( QWidget* parent, const QString& title, const QString& text,
+ const QString& button );
+ static int question( QWidget* parent, const QString& title, const QString& text,
+ const QString& button );
+
+ // message boxes with two custom buttons
+ static int critical( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2,
+ const int defaultButton = -1, const int escapeButton = -1 );
+ static int warning( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2,
+ const int defaultButton = -1, const int escapeButton = -1 );
+ static int information( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2,
+ const int defaultButton = -1, const int escapeButton = -1 );
+ static int question( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2,
+ const int defaultButton = -1, const int escapeButton = -1 );
+
+ // message boxes with three custom buttons
+ static int critical( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2, const QString& button3,
+ const int defaultButton = -1, const int escapeButton = -1 );
+ static int warning( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2, const QString& button3,
+ const int defaultButton = -1, const int escapeButton = -1 );
+ static int information( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2, const QString& button3,
+ const int defaultButton = -1, const int escapeButton = -1 );
+ static int question( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2, const QString& button3,
+ const int defaultButton = -1, const int escapeButton = -1 );
+
+ // message boxes with four custom buttons
+ static int critical( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2,
+ const QString& button3, const QString& button4,
+ const int defaultButton = -1, const int escapeButton = -1 );
+ static int warning( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2,
+ const QString& button3, const QString& button4,
+ const int defaultButton = -1, const int escapeButton = -1 );
+ static int information( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2,
+ const QString& button3, const QString& button4,
+ const int defaultButton = -1, const int escapeButton = -1 );
+ static int question( QWidget* parent, const QString& title, const QString& text,
+ const QString& button1, const QString& button2,
+ const QString& button3, const QString& button4,
+ const int defaultButton = -1, const int escapeButton = -1 );
+
+ // message boxes with arbitrary number of buttons
+ static int critical( QWidget* parent, const QString& title, const QString& text,
+ const int defaultButton, const int escapeButton,
+ char*, ... );
+ static int warning( QWidget* parent, const QString& title, const QString& text,
+ const int defaultButton, const int escapeButton,
+ char*, ... );
+ static int information( QWidget* parent, const QString& title, const QString& text,
+ const int defaultButton, const int escapeButton,
+ char*, ... );
+ static int question( QWidget* parent, const QString& title, const QString& text,
+ const int defaultButton, const int escapeButton,
+ char*, ... );
+
+private:
+ class ButtonInfo
+ {
+ public:
+ ButtonInfo( const int id,
+ const QString& text,
+ const ButtonRole role = ActionRole )
+ : myId( id ), myText( text ), myRole( role ) {}
+ int id() const { return myId; }
+ QString text() const { return myText; }
+ ButtonRole role() const { return myRole; }
+ private:
+ int myId; //!< button id
+ QString myText; //!< button text
+ ButtonRole myRole; //!< button role
+ };
- /** @name Two buttons message boxes.*/
- //@{
- static int info2 ( QWidget* parent, const QString& caption, const QString& text,
- const QString& textButton0, const QString& textButton1,
- int idButton0, int idButton1, int idDefault );
- static int warn2 ( QWidget* parent, const QString& caption, const QString& text,
- const QString& textButton0, const QString& textButton1,
- int idButton0, int idButton1, int idDefault );
- static int error2 ( QWidget* parent, const QString& caption, const QString& text,
- const QString& textButton0, const QString& textButton1,
- int idButton0, int idButton1, int idDefault );
- static int question2 ( QWidget* parent, const QString& caption, const QString& text,
- const QString& textButton0, const QString& textButton1,
- int idButton0, int idButton1, int idDefault );
- //@}
+ typedef QList<ButtonInfo> ButtonInfos;
- /** @name Three buttons message boxes.*/
- //@{
- static int info3 ( QWidget* parent, const QString& caption, const QString& text,
- const QString& textButton0, const QString& textButton1,
- const QString& textButton2, int idButton0, int idButton1,
- int idButton2, int idDefault );
- static int warn3 ( QWidget* parent, const QString& caption, const QString& text,
- const QString& textButton0, const QString& textButton1,
- const QString& textButton2, int idButton0, int idButton1,
- int idButton2, int idDefault );
- static int error3 ( QWidget* parent, const QString& caption, const QString& text,
- const QString& textButton0, const QString& textButton1,
- const QString& textButton2, int idButton0, int idButton1,
- int idButton2, int idDefault );
- static int question3 ( QWidget* parent, const QString& caption, const QString& text,
- const QString& textButton0, const QString& textButton1,
- const QString& textButton2, int idButton0, int idButton1,
- int idButton2, int idDefault );
- //@}
+private:
+ static int messageBox( SUIT_MessageBox::Icon icon, QWidget* parent,
+ const QString& title, const QString& text,
+ const ButtonInfos& lst,
+ const int defaultButton = -1,
+ const int escapeButton = -1 );
+ static ButtonInfos messageList( char*, va_list& );
};
#endif
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-/*!
- SALOME SalomeApp
-
- Copyright (C) 2005 CEA/DEN, EDF R&D
-
- File : SUIT_Operation.h
- Author : Unknown
- Module : SALOME
-*/
-
#include "SUIT_Operation.h"
#include "SUIT_Study.h"
-#include "SUIT_Desktop.h"
-#include "SUIT_MessageBox.h"
#include "SUIT_Application.h"
/*!
SUIT_Operation::SUIT_Operation( SUIT_Application* app )
: QObject(),
myApp( app ),
+myFlags( Transaction ),
myStudy( 0 ),
-myState( Waiting ),
-myFlags( Transaction )
+myState( Waiting )
{
}
#include "SUIT.h"
-#include <qobject.h>
-#include <qguardedptr.h>
+#include <QObject>
+#include <QPointer>
class SUIT_Study;
class SUIT_Application;
virtual QString operationName() const;
+ int execStatus() const;
+
signals:
void started( SUIT_Operation* );
void aborted( SUIT_Operation* );
virtual bool hasTransaction() const;
virtual bool commitTransaction( const QString& = QString::null );
- int execStatus() const;
void setExecStatus( const int );
void setState( const OperationState );
void start( SUIT_Operation*, const bool = false );
private:
- typedef QGuardedPtr<SUIT_Study> StudyPtr;
+ typedef QPointer<SUIT_Study> StudyPtr;
private:
SUIT_Application* myApp; //!< application for this operation
//
#include "SUIT_OverrideCursor.h"
+#include <QApplication>
+
/*!Constructor. Initialize wait cursor.*/
SUIT_OverrideCursor::SUIT_OverrideCursor()
{
if ( isActive() )
return;
- for ( QValueList<QCursor>::const_iterator it = myCursors.begin(); it != myCursors.end(); ++it )
+ for ( QList<QCursor>::const_iterator it = myCursors.begin(); it != myCursors.end(); ++it )
QApplication::setOverrideCursor( *it );
myCursors.clear();
#ifndef SUIT_OVERRIDECURSOR_H
#define SUIT_OVERRIDECURSOR_H
-#include <qapplication.h>
-#include <qcursor.h>
-
#include "SUIT.h"
+#include <QList>
+#include <QCursor>
+
/*! \brief Class used for management cursors.*/
class SUIT_EXPORT SUIT_OverrideCursor
{
void resume();
private:
- QValueList<QCursor> myCursors;
+ QList<QCursor> myCursors;
};
#endif
+++ /dev/null
-// SALOME SALOMEGUI : implementation of desktop and GUI kernel
-//
-// Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-//
-//
-// File : SUIT_ParserSettings.cxx
-// Author : Nicolas REJNERI
-// Module : SALOME
-// $Header$
-
-#include "SUIT_ParserSettings.h"
-
-#include <stdio.h>
-
-// QT Includes
-#include <qfile.h>
-#include <qfileinfo.h>
-#include <qtextstream.h>
-
-
-/*! Constructor. Do nothing.*/
-SUIT_ParserSettings::SUIT_ParserSettings()
-{
-}
-
-
-/*!
- Destructor. Do nothing.
-*/
-SUIT_ParserSettings::~SUIT_ParserSettings()
-{
-}
-
-
-/*!
- Gets the contents of a file.
-*/
-QString SUIT_ParserSettings::getContents(QString fileName, bool comments,
- bool sections, bool whiteSpace,
- bool htmlComments)
-{
- QFileInfo fi(fileName);
- QFile f(fi.absFilePath());
- QString s=""; // Buffer for the whole file
-
- if(f.open(IO_ReadOnly)) { // file opened successfully
- QTextStream t(&f); // use a text stream
-
- s = t.read(); // The whole file in a string
- f.close();
-
- if(!comments) s = SUIT_ParserSettings::removeComments(s);
- if(!sections) s = SUIT_ParserSettings::removeSections(s);
- if(!whiteSpace) s = s.simplifyWhiteSpace();
- if(!htmlComments) s = SUIT_ParserSettings::removeHtmlComments(s);
- }
- else {
- // Can't open file
- }
-
- return s;
-}
-
-
-/*!
- Gets the body of a section from a string.
-*/
-QString SUIT_ParserSettings::getSection(QString s, QString sectionName)
-{
- QString result="";
-
- QChar ch; // A single byte of the file
- int bracketCounter=1; // Bracket counter (increase on '{' and decrese on '}'.
- int i; // Current index
- int l=0; // Length of current part we must have
-
- if((i=s.find(sectionName, 0, false)) >= 0 && // Jump to section [styles]
- (i=s.find('{', i)) >= 0 ) {
-
- ++i;
-
- while(i+l<(int)s.length()) {
- ch = s.at(i+l); // Single byte
-
- ++l;
-
- if(ch=='{') ++bracketCounter;
- if(ch=='}') --bracketCounter;
-
- if(bracketCounter==0) break;
- }
-
- result = s.mid(i, l-1);
- }
-
- return result;
-}
-
-
-
-/*!
- Gets the HTML comments out of a file.
-*/
-QString SUIT_ParserSettings::getHtmlComment(QString s)
-{
- QString result="";
- int length; // length of the sub string
- int ind=0;
-
- if((ind =s.find("<!--", ind))>=0 &&
- (ind+=4) &&
- (length=s.find("-->", ind)-ind)!=0) {
-
- result=s.mid(ind, length-3);
- }
-
- return result;
-}
-
-
-
-/*!
- Gets the next String between two given characters. The index-parameter gets moved to the character after
- the stopper or to -1 if the starter / stopper were not found.
-*/
-QString SUIT_ParserSettings::getNextStringBetween(QString s, int& startIndex,
- QChar starter, QChar stopper)
-{
- QString result="";
- int length=0; // length of the sub string
-
- if((startIndex =s.find(starter, startIndex))>=0 &&
- (length=s.find(stopper, startIndex+1)-startIndex)!=0) {
-
- result=s.mid(startIndex+1, length-1);
- startIndex+=2;
- }
-
- return result;
-}
-
-
-/*!
- Gets the next String between the given index and a given stopper character. The index-parameter gets moved to
- the character after the stopper or to -1 if the stopper was not found.
-*/
-QString SUIT_ParserSettings::getNextStringUntil(QString s, int& startIndex, QChar stopper)
-{
- QString result="";
- int length; // length of the sub string
-
- if((length=s.find(stopper, startIndex)-startIndex)!=0) {
- result=s.mid(startIndex, length);
- startIndex++;
- }
-
- return result;
-}
-
-
-/*!
- Removes all comments (between '/ *' and '* /').
-*/
-QString SUIT_ParserSettings::removeComments(QString s)
-{
- QString result="";
- int i1=0, i2;
-
- while((i2=s.find("/*", i1))>=0) {
- result += s.mid(i1, i2-i1);
-
- i1+=2;
- i1=s.find("*/", i1);
- i1+=2;
- }
-
- result += s.mid(i1, s.length()-i1);
-
- return result;
-}
-
-
-
-/*!
- Removes all HTML comments (between '<!--' and '-->') \image html html_comments.gif
-*/
-QString SUIT_ParserSettings::removeHtmlComments(QString s)
-{
- QString result="";
- int i1=0, i2;
-
- while((i2=s.find("<!--", i1))>=0) {
- result += s.mid(i1, i2-i1);
-
- i1+=4;
- i1=s.find("-->", i1);
- i1+=3;
- }
-
- result += s.mid(i1, s.length()-i1);
-
- return result;
-}
-
-
-
-/*!
- Removes all sections ('[section] { }').
-*/
-QString SUIT_ParserSettings::removeSections(QString s)
-{
- QString result="";
-
- QChar ch; // A single byte of the file
- int bracketCounter; // Bracket counter (increase on '{' and decrese on '}'.
- int i=0; // Current index
-
- while(i<(int)s.length()) {
- ch = s.at(i); // Single byte
-
- if(ch=='[') {
- bracketCounter=1;
- while(i<(int)s.length() && ch!=']') { ch = s.at(i); ++i; }
- ++i;
- while(i<(int)s.length() && ch!='{') { ch = s.at(i); ++i; }
- ++i;
-
- while(i<(int)s.length() && bracketCounter!=0) {
- ch = s.at(i);
- if(ch=='{') ++bracketCounter;
- if(ch=='}') --bracketCounter;
- ++i;
- }
- ++i;
- }
- else {
- result+=ch;
- }
-
- ++i;
- }
-
- return result;
-}
-
-
-/*!
- Format plain text into HTML-code with a given maximal width.
- Spaces get replaced with non breaking spaces. Tabulators get filled up
- with non breaking spaces.
-*/
-QString SUIT_ParserSettings::plainTextToHtml(QString s, int autoBreak)
-{
- QString result="\n";
-
- if(!s.isEmpty()) {
- int col=1, i;
-
- for(i=0; i<(int)s.length(); ++i) {
- // Line feed:
- //
- if(s[i]=='\n') {
- result+="<BR>\n";
- col=1;
- }
-
- // Auto break:
- //
- else if(col==autoBreak && autoBreak!=0) {
- result+="<BR>\n";
- result+=s[i];
- col=1;
- }
-
- // Tab:
- //
- else if(s[i]=='\t') {
- while(col%8!=0) { result+=" "; ++col; }
- result+=" ";
- ++col;
- }
-
- // Space:
- //
- else if(s[i]==' ') {
- result+=" ";
- ++col;
- }
-
- // Normal char / special code:
- //
- else {
- if(s[i].isLetter() || s[i].isNumber()) {
- result+=s[i];
- }
- else {
- result+=charToHtml(s[i]);
- }
- ++col;
- }
- }
-
- result+="\n";
- }
-
- return result;
-}
-
-
-/*!
- Converts a special character to html code (e.g.: '»' to "»")
-*/
-QString SUIT_ParserSettings::charToHtml(QChar c)
-{
- QString s;
- QString uc;
- uc.setNum(c.unicode());
- s = "&#" + uc + ";";
- return s;
-}
-
-
-// EOF
+++ /dev/null
-// SALOME SALOMEGUI : implementation of desktop and GUI kernel
-//
-// Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-//
-//
-// File : SUIT_ParserSettings.h
-// Author : Nicolas REJNERI
-// Module : SALOME
-// $Header$
-
-#ifndef SUIT_PARSERSETTINGS_H
-#define SUIT_PARSERSETTINGS_H
-
-#include <qstring.h>
-#include "SUIT.h"
-/*! \brief Text Parser.*/
-class SUIT_EXPORT SUIT_ParserSettings
-{
-public:
- SUIT_ParserSettings();
- ~SUIT_ParserSettings();
-
- static QString getContents(QString fileName, bool comments=true,
- bool sections=true, bool whitespace=true,
- bool htmlComments=true);
- static QString getSection(QString s, QString sectionName);
- static QString getHtmlComment(QString s);
- static QString getNextStringBetween(QString s, int& startIndex, QChar starter, QChar stopper);
- static QString getNextStringUntil(QString s, int& startIndex, QChar stopper);
- static QString removeComments(QString s);
- static QString removeHtmlComments(QString s);
- static QString removeSections(QString s);
- static QString plainTextToHtml(QString s, int autoBreak);
- static QString charToHtml(QChar c);
-
-};
-
-#endif
//
#include "SUIT_PopupClient.h"
-#include <qevent.h>
-
/*! constructor. initialize mySignal.*/
SUIT_PopupClient::SUIT_PopupClient()
: mySignal( 0 )
#include "SUIT.h"
-#include <qobject.h>
+#include <QObject>
-class QPopupMenu;
+class QMenu;
class QContextMenuEvent;
/*!\class SUIT_PopupClient
bool disconnectPopupRequest( QObject* reciever, const char* slot );
virtual QString popupClientType() const = 0;
- virtual void contextMenuPopup( QPopupMenu* ) {}
+ virtual void contextMenuPopup( QMenu* ) {}
protected:
void contextMenuRequest( QContextMenuEvent* e );
//
#include "SUIT_ResourceMgr.h"
-#include <qfileinfo.h>
-#include <qdir.h>
-#include <qapplication.h>
-#include <qregexp.h>
+#include <QDir>
+#include <QFileInfo>
+#include <QApplication>
+#include <QRegExp>
+
+#ifndef WIN32
+#include <unistd.h>
+#endif
/*!
Constructor
return path( docSection, prefix, id );
}
-#ifndef WIN32
-#include <unistd.h>
-#endif
/*!
Returns the user file name for specified application
*/
{
QString pathName;
+ QStringList arguments = QApplication::arguments();
// Try config file, given in arguments
- for (int i = 1; i < qApp->argc(); i++) {
+ for (int i = 1; i < arguments.count(); i++) {
QRegExp rx ("--resources=(.+)");
- if ( rx.search( QString(qApp->argv()[i]) ) >= 0 && rx.capturedTexts().count() > 1 ) {
- QString file = rx.capturedTexts()[1];
+ if ( rx.indexIn( arguments[i] ) >= 0 && rx.numCaptures() > 1 ) {
+ QString file = rx.cap(1);
QFileInfo fi (file);
- pathName = fi.absFilePath();
+ pathName = fi.absoluteFilePath();
}
}
*/
QString SUIT_ResourceMgr::findAppropriateUserFile( const QString& fname ) const
{
- QDir d( QFileInfo( fname ).dir( true ) );
+ QDir d( QFileInfo( fname ).dir() );
d.setFilter( QDir::Files | QDir::Hidden | QDir::NoSymLinks );
QStringList l = d.entryList();
QString appr_file;
if( appr < 0 || abs( id-id0 ) < abs( appr-id0 ) )
{
appr = id;
- appr_file = d.absFilePath( *anIt );
+ appr_file = d.absoluteFilePath( *anIt );
}
}
return appr_file;
//
#include "SUIT_SelectionMgr.h"
+#include "SUIT_Selector.h"
+#include "SUIT_SelectionFilter.h"
+
/*!\class SUIT_SelectionMgr
* Provide selection manager. Manipulate by selection filters, modes, data owners.
*/
SUIT_SelectionMgr::SUIT_SelectionMgr( const bool Feedback, QObject* p )
: QObject( p ),
myIterations( Feedback ? 1 : 0 ),
+myAutoDelFilter( false ),
myIsSelChangeEnabled( true )
{
}
/*!destructor. mySelectors auto delete.*/
SUIT_SelectionMgr::~SUIT_SelectionMgr()
{
- mySelectors.setAutoDelete( true );
+ for ( SelectorList::iterator it = mySelectors.begin(); it != mySelectors.end(); ++it )
+ delete *it;
}
/*!Add selector \a sel to selectors list,if it's not exists in list.*/
/*!Remove selector \a sel from list.*/
void SUIT_SelectionMgr::removeSelector( SUIT_Selector* sel )
{
- mySelectors.remove( sel );
+ mySelectors.removeAll( sel );
}
/*!Gets selectors list to \a lst.*/
-void SUIT_SelectionMgr::selectors( QPtrList<SUIT_Selector>& lst ) const
+void SUIT_SelectionMgr::selectors( QList<SUIT_Selector*>& lst ) const
{
lst.clear();
- for ( SelectorListIterator it( mySelectors ); it.current(); ++it )
- lst.append( it.current() );
+ for ( SelectorList::const_iterator it = mySelectors.begin(); it != mySelectors.end(); ++it )
+ lst.append( *it );
}
/*!Gets selectors list to \a lst with type \a typ.*/
-void SUIT_SelectionMgr::selectors( const QString& typ, QPtrList<SUIT_Selector>& lst ) const
+void SUIT_SelectionMgr::selectors( const QString& typ, QList<SUIT_Selector*>& lst ) const
{
lst.clear();
- for ( SelectorListIterator it( mySelectors ); it.current(); ++it )
+ for ( SelectorList::const_iterator it = mySelectors.begin(); it != mySelectors.end(); ++it )
{
- if ( it.current()->type() == typ )
- lst.append( it.current() );
+ if ( (*it)->type() == typ )
+ lst.append( *it );
}
}
*/
void SUIT_SelectionMgr::setEnabled( const bool on, const QString& typ )
{
- for ( SelectorListIterator it( mySelectors ); it.current(); ++it )
+ for ( SelectorList::const_iterator it = mySelectors.begin(); it != mySelectors.end(); ++it )
{
- if ( typ.isEmpty() || it.current()->type() == typ )
- it.current()->setEnabled( on );
+ if ( typ.isEmpty() || (*it)->type() == typ )
+ (*it)->setEnabled( on );
}
}
{
lst.clear();
- for ( SelectorListIterator it( mySelectors ); it.current(); ++it )
+ for ( SelectorList::const_iterator it = mySelectors.begin(); it != mySelectors.end(); ++it )
{
- if ( !type.isEmpty() && it.current()->type() != type )
+ if ( !type.isEmpty() && (*it)->type() != type )
continue;
+
SUIT_DataOwnerPtrList curList;
- it.current()->selected( curList );
+ (*it)->selected( curList );
for ( SUIT_DataOwnerPtrList::const_iterator itr = curList.begin(); itr != curList.end(); ++itr )
lst.append( *itr );
}
SUIT_DataOwnerPtrList owners;
filterOwners( lst, owners );
- for ( SelectorListIterator it( mySelectors ); it.current(); ++it )
+ for ( SelectorList::const_iterator it = mySelectors.begin(); it != mySelectors.end(); ++it )
{
if ( append )
{
SUIT_DataOwnerPtrList current;
- it.current()->selected( current );
+ (*it)->selected( current );
for ( SUIT_DataOwnerPtrList::const_iterator it = current.begin(); it != current.end(); ++it )
owners.append( *it );
}
- it.current()->setSelected( owners );
+ (*it)->setSelected( owners );
}
}
for ( int i = 0; i < myIterations; i++ )
{
- for ( SUIT_Selector* aSel = mySelectors.first(); aSel; aSel = mySelectors.next() )
+ for ( SelectorList::iterator it = mySelectors.begin(); it != mySelectors.end(); ++it )
{
- // Temporary action(to avoid selection of the objects which don't pass the filters):
- //if ( aSel != sel )
- aSel->setSelected( newOwners );
+ if ( *it != sel )
+ (*it)->setSelected( newOwners );
}
}
myIsSelChangeEnabled = true;
/*! Gets selection modes to list \a vals.
*/
-void SUIT_SelectionMgr::selectionModes( QValueList<int>& vals ) const
+void SUIT_SelectionMgr::selectionModes( QList<int>& vals ) const
{
vals = mySelModes;
}
*/
void SUIT_SelectionMgr::setSelectionModes( const int mode )
{
- QValueList<int> lst;
+ QList<int> lst;
lst.append( mode );
setSelectionModes( lst );
}
/*! Sets selection modes list from \a lst.
*/
-void SUIT_SelectionMgr::setSelectionModes( const QValueList<int>& lst )
+void SUIT_SelectionMgr::setSelectionModes( const QList<int>& lst )
{
mySelModes = lst;
}
*/
void SUIT_SelectionMgr::appendSelectionModes( const int mode )
{
- QValueList<int> lst;
+ QList<int> lst;
lst.append( mode );
appendSelectionModes( lst );
}
/*! Append selection modes \a lst list.
*/
-void SUIT_SelectionMgr::appendSelectionModes( const QValueList<int>& lst )
+void SUIT_SelectionMgr::appendSelectionModes( const QList<int>& lst )
{
QMap<int, int> map;
- for ( QValueList<int>::const_iterator it = mySelModes.begin(); it != mySelModes.end(); ++it )
+ for ( QList<int>::const_iterator it = mySelModes.begin(); it != mySelModes.end(); ++it )
map.insert( *it, 0 );
- for ( QValueList<int>::const_iterator itr = lst.begin(); itr != lst.end(); ++itr )
+ for ( QList<int>::const_iterator itr = lst.begin(); itr != lst.end(); ++itr )
{
if ( !map.contains( *itr ) )
mySelModes.append( *itr );
*/
void SUIT_SelectionMgr::removeSelectionModes( const int mode )
{
- QValueList<int> lst;
+ QList<int> lst;
lst.append( mode );
removeSelectionModes( lst );
}
/*! Remove selection modea \a lst from list.
*/
-void SUIT_SelectionMgr::removeSelectionModes( const QValueList<int>& lst )
+void SUIT_SelectionMgr::removeSelectionModes( const QList<int>& lst )
{
QMap<int, int> map;
- for ( QValueList<int>::const_iterator it = mySelModes.begin(); it != mySelModes.end(); ++it )
+ for ( QList<int>::const_iterator it = mySelModes.begin(); it != mySelModes.end(); ++it )
map.insert( *it, 0 );
- for ( QValueList<int>::const_iterator itr = lst.begin(); itr != lst.end(); ++itr )
+ for ( QList<int>::const_iterator itr = lst.begin(); itr != lst.end(); ++itr )
map.remove( *itr );
mySelModes.clear();
return false;
bool ok = true;
- for ( SelFilterListIterator it( myFilters ); it.current() && ok; ++it )
- ok = it.current()->isOk( owner );
+ for ( SelFilterList::const_iterator it = myFilters.begin(); it != myFilters.end() && ok; ++it )
+ ok = (*it)->isOk( owner );
return ok;
}
*/
void SUIT_SelectionMgr::removeFilter( SUIT_SelectionFilter* f )
{
- myFilters.remove( f );
+ if ( !myFilters.contains( f ) )
+ return;
+
+ myFilters.removeAll( f );
+
+ if ( autoDeleteFilter() )
+ delete f;
}
/*! Clear filters list.
*/
void SUIT_SelectionMgr::clearFilters()
{
+ if ( autoDeleteFilter() )
+ {
+ for ( SelFilterList::const_iterator it = myFilters.begin(); it != myFilters.end(); ++it )
+ delete *it;
+ }
+
myFilters.clear();
}
*/
bool SUIT_SelectionMgr::autoDeleteFilter() const
{
- return myFilters.autoDelete();
+ return myAutoDelFilter;
}
/*! Sets auto delete filter to \a on.
*/
void SUIT_SelectionMgr::setAutoDeleteFilter( const bool on )
{
- myFilters.setAutoDelete( on );
+ myAutoDelFilter = on;
}
/*! Gets good data owners list to \a out from \a in.
#ifndef SUIT_SELECTIONMGR_H
#define SUIT_SELECTIONMGR_H
-#include "SUIT_Selector.h"
#include "SUIT_DataOwner.h"
-#include "SUIT_SelectionFilter.h"
-#include <qobject.h>
-#include <qptrlist.h>
-#include <qvaluelist.h>
+#include <QList>
+#include <QObject>
+
+class SUIT_Selector;
+class SUIT_SelectionFilter;
#ifdef WIN32
#pragma warning ( disable : 4251 )
virtual void selected( SUIT_DataOwnerPtrList&, const QString& = QString::null ) const;
virtual void setSelected( const SUIT_DataOwnerPtrList&, const bool = false );
- void selectors( QPtrList<SUIT_Selector>& ) const;
- void selectors( const QString&, QPtrList<SUIT_Selector>& ) const;
+ void selectors( QList<SUIT_Selector*>& ) const;
+ void selectors( const QString&, QList<SUIT_Selector*>& ) const;
void setEnabled( const bool, const QString& = QString::null );
bool hasSelectionMode( const int ) const;
- void selectionModes( QValueList<int>& ) const;
+ void selectionModes( QList<int>& ) const;
void setSelectionModes( const int );
- virtual void setSelectionModes( const QValueList<int>& );
+ virtual void setSelectionModes( const QList<int>& );
void appendSelectionModes( const int );
- virtual void appendSelectionModes( const QValueList<int>& );
+ virtual void appendSelectionModes( const QList<int>& );
void removeSelectionModes( const int );
- virtual void removeSelectionModes( const QValueList<int>& );
+ virtual void removeSelectionModes( const QList<int>& );
bool isOk( const SUIT_DataOwner* ) const;
protected:
virtual void selectionChanged( SUIT_Selector* );
- typedef QPtrListIterator<SUIT_Selector> SelectorListIterator;
-
virtual void installSelector( SUIT_Selector* );
virtual void removeSelector( SUIT_Selector* );
private:
void filterOwners( const SUIT_DataOwnerPtrList&, SUIT_DataOwnerPtrList& ) const;
- typedef QPtrList<SUIT_Selector> SelectorList;
- typedef QPtrList<SUIT_SelectionFilter> SelFilterList;
- typedef QPtrListIterator<SUIT_SelectionFilter> SelFilterListIterator;
-
-protected:
- SelectorList mySelectors;
+ typedef QList<SUIT_Selector*> SelectorList;
+ typedef QList<SUIT_SelectionFilter*> SelFilterList;
private:
SelFilterList myFilters;
- QValueList<int> mySelModes;
+ QList<int> mySelModes;
+ SelectorList mySelectors;
int myIterations;
+ bool myAutoDelFilter;
bool myIsSelChangeEnabled;
friend class SUIT_Selector;
#include "SUIT_SelectionMgr.h"
+#include <QObject>
+
+/*!\class SUIT_Selector::Destroyer
+ Class provide the watching for qobject parent class of the selector.
+*/
+
+class SUIT_Selector::Destroyer : public QObject
+{
+public:
+ Destroyer( SUIT_Selector*, QObject* = 0 );
+ virtual ~Destroyer();
+
+ SUIT_Selector* selector() const;
+ void setSelector( SUIT_Selector* );
+
+private:
+ SUIT_Selector* mySelector;
+};
+
+SUIT_Selector::Destroyer::Destroyer( SUIT_Selector* s, QObject* p )
+: QObject( p ),
+ mySelector( s )
+{
+}
+
+SUIT_Selector::Destroyer::~Destroyer()
+{
+ SUIT_Selector* s = mySelector;
+ mySelector = 0;
+ if ( s )
+ delete s;
+}
+
+SUIT_Selector* SUIT_Selector::Destroyer::selector() const
+{
+ return mySelector;
+}
+
+void SUIT_Selector::Destroyer::setSelector( SUIT_Selector* s )
+{
+ mySelector = s;
+}
+
/*!\class SUIT_Selector
* Class provide selector for data owners.
*/
/*!
Constructor.
*/
-SUIT_Selector::SUIT_Selector( SUIT_SelectionMgr* selMgr, QObject* parent ) :
-QObject( parent ),
-mySelMgr( selMgr ),
+SUIT_Selector::SUIT_Selector( SUIT_SelectionMgr* selMgr, QObject* parent )
+: mySelMgr( selMgr ),
myBlock( false ),
myEnabled( true ),
-myAutoBlock( true )
+myAutoBlock( true ),
+myDestroyer( 0 )
{
if ( selMgr )
selMgr->installSelector( this );
+
+ if ( parent )
+ myDestroyer = new Destroyer( this, parent );
}
/*!
{
if ( selectionMgr() )
selectionMgr()->removeSelector( this );
+
+ if ( myDestroyer && myDestroyer->selector() == this )
+ {
+ myDestroyer->setSelector( 0 );
+ delete myDestroyer;
+ }
}
/*!
/*!
Puts to list \a lst selection modes from selection manager.
*/
-void SUIT_Selector::selectionModes( QValueList<int>& lst ) const
+void SUIT_Selector::selectionModes( QList<int>& lst ) const
{
if ( selectionMgr() )
selectionMgr()->selectionModes( lst );
#include "SUIT.h"
-#include <qvaluelist.h>
-#include <qobject.h>
+#include <QList>
+
+class QObject;
class SUIT_SelectionMgr;
class SUIT_DataOwnerPtrList;
(ObjectBrowser, viewers, etc)
Used by selection manager for selection synhronizing
*/
-class SUIT_EXPORT SUIT_Selector : public QObject
+
+class SUIT_EXPORT SUIT_Selector
{
- Q_OBJECT
+ class Destroyer;
+
public:
SUIT_Selector( SUIT_SelectionMgr*, QObject* = 0 );
virtual ~SUIT_Selector();
void setSelected( const SUIT_DataOwnerPtrList& );
bool hasSelectionMode( const int ) const;
- void selectionModes( QValueList<int>& ) const;
+ void selectionModes( QList<int>& ) const;
protected:
void selectionChanged();
virtual void setSelection( const SUIT_DataOwnerPtrList& ) = 0;
private:
- bool myBlock;
SUIT_SelectionMgr* mySelMgr;
+ bool myBlock;
bool myEnabled;
bool myAutoBlock;
+ Destroyer* myDestroyer;
};
#endif
//
#include "SUIT_Session.h"
+#include "SUIT_Study.h"
#include "SUIT_Tools.h"
-#include "SUIT_Desktop.h"
#include "SUIT_MessageBox.h"
-#include "SUIT_ViewWindow.h"
-#include "SUIT_ViewManager.h"
#include "SUIT_ExceptionHandler.h"
+#include "SUIT_ResourceMgr.h"
-#include <qtextcodec.h>
-#include <qmessagebox.h>
-#include <qapplication.h>
+#include <QApplication>
#ifdef WIN32
#include <windows.h>
#include <dlfcn.h>
#endif
-static bool SUIT_Session_IsPythonExecuted = false;
-static QMutex SUIT_Session_PythonMutex;
-
SUIT_Session* SUIT_Session::mySession = 0;
/*! Constructor.*/
SUIT_Session::SUIT_Session()
: QObject(),
myResMgr( 0 ),
-myHandler( 0 ),
myActiveApp( 0 ),
+myHandler( 0 ),
myExitStatus( FROM_GUI )
{
SUIT_ASSERT( !mySession )
mySession = this;
-
- myAppList.setAutoDelete( true );
}
/*!destructor. Clear applications list and set mySession to zero.*/
SUIT_Session::~SUIT_Session()
{
+ for ( AppList::iterator it = myAppList.begin(); it != myAppList.end(); ++it )
+ delete *it;
+
myAppList.clear();
- if (myResMgr) {
+ if ( myResMgr )
+ {
delete myResMgr;
myResMgr = 0;
}
Starts new application using "createApplication" function of loaded DLL.
*/
-SUIT_Application* SUIT_Session::startApplication( const QString& name, int args, char** argv )
+SUIT_Application* SUIT_Session::startApplication( const QString& name, int /*args*/, char** /*argv*/ )
{
AppLib libHandle = 0;
if ( !libHandle )
{
- SUIT_MessageBox::warn1( 0, tr( "Error" ),
- tr( "Can not load application library \"%1\": %2").arg( lib ).arg( lastError() ), tr( "Ok" ) );
+ SUIT_MessageBox::warning( 0, tr( "Error" ),
+ tr( "Can not load application library \"%1\": %2").arg( lib ).arg( lastError() ) );
return 0;
}
APP_CREATE_FUNC crtInst = 0;
#ifdef WIN32
- crtInst = (APP_CREATE_FUNC)::GetProcAddress( libHandle, APP_CREATE_NAME );
+ crtInst = (APP_CREATE_FUNC)::GetProcAddress( (HINSTANCE)libHandle, APP_CREATE_NAME );
#else
crtInst = (APP_CREATE_FUNC)dlsym( libHandle, APP_CREATE_NAME );
#endif
if ( !crtInst )
{
- SUIT_MessageBox::warn1( 0, tr( "Error" ),
- tr( "Can not find function \"%1\": %2" ).arg( APP_CREATE_NAME ).arg( lastError() ), tr( "Ok" ) );
+ SUIT_MessageBox::warning( 0, tr( "Error" ),
+ tr( "Can not find function \"%1\": %2" ).arg( APP_CREATE_NAME ).arg( lastError() ) );
return 0;
}
SUIT_Application* anApp = crtInst();
if ( !anApp )
{
- SUIT_MessageBox::warn1( 0, tr( "Error" ), tr( "Can not create application \"%1\": %2").arg( appName ).arg( lastError() ), tr( "Ok" ) );
+ SUIT_MessageBox::warning( 0, tr( "Error" ), tr( "Can not create application \"%1\": %2").arg( appName ).arg( lastError() ) );
return 0;
}
- anApp->setName( appName );
-
- connect( anApp, SIGNAL( applicationClosed( SUIT_Application* ) ),
- this, SLOT( onApplicationClosed( SUIT_Application* ) ) );
- connect( anApp, SIGNAL( activated( SUIT_Application* ) ),
- this, SLOT( onApplicationActivated( SUIT_Application* ) ) );
+ anApp->setObjectName( appName );
- myAppList.append( anApp );
+ insertApplication( anApp );
if ( !myHandler )
{
APP_GET_HANDLER_FUNC crtHndlr = 0;
#ifdef WIN32
- crtHndlr = (APP_GET_HANDLER_FUNC)::GetProcAddress( libHandle, APP_GET_HANDLER_NAME );
+ crtHndlr = (APP_GET_HANDLER_FUNC)::GetProcAddress( (HINSTANCE)libHandle, APP_GET_HANDLER_NAME );
#else
crtHndlr = (APP_GET_HANDLER_FUNC)dlsym( libHandle, APP_GET_HANDLER_NAME );
#endif
/*!
Gets the list of all applications
*/
-QPtrList<SUIT_Application> SUIT_Session::applications() const
+QList<SUIT_Application*> SUIT_Session::applications() const
{
- QPtrList<SUIT_Application> apps;
- apps.setAutoDelete( false );
+ return myAppList;
+}
- for ( AppListIterator it( myAppList ); it.current(); ++it )
- apps.append( it.current() );
+void SUIT_Session::insertApplication( SUIT_Application* app )
+{
+ if ( !app || myAppList.contains( app ) )
+ return;
- return apps;
+ myAppList.append( app );
+
+ connect( app, SIGNAL( applicationClosed( SUIT_Application* ) ),
+ this, SLOT( onApplicationClosed( SUIT_Application* ) ) );
+ connect( app, SIGNAL( activated( SUIT_Application* ) ),
+ this, SLOT( onApplicationActivated( SUIT_Application* ) ) );
}
/*!
{
emit applicationClosed( theApp );
- myAppList.remove( theApp );
+ myAppList.removeAll( theApp );
+ delete theApp;
+
if ( theApp == myActiveApp )
myActiveApp = 0;
if ( myAppList.isEmpty() )
{
printf( "Calling QApplication::exit() with exit code = %d\n", myExitStatus );
- qApp->exit( myExitStatus );
+ QApplication::instance()->exit( myExitStatus );
}
}
*/
void SUIT_Session::closeSession( int mode )
{
- while ( !myAppList.isEmpty() )
+ AppList apps = myAppList;
+ for ( AppList::const_iterator it = apps.begin(); it != apps.end(); ++it )
{
- SUIT_Application* app = myAppList.getFirst();
- if ( mode == ASK && !app->isPossibleToClose() )
+ SUIT_Application* app = *it;
+ bool closePermanently;
+ if ( mode == ASK && !app->isPossibleToClose( closePermanently ) )
return;
else if ( mode == SAVE )
{
SUIT_Study* study = app->activeStudy();
if ( study->isModified() && study->isSaved() )
- study->saveDocument();
+ study->saveDocument();
}
else if ( mode == DONT_SAVE )
{
QString SUIT_Session::lastError() const
{
QString str;
-#ifdef WNT
+#ifdef WIN32
LPVOID lpMsgBuf;
::FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS, 0, ::GetLastError(), 0, (LPTSTR)&lpMsgBuf, 0, 0 );
- str = QString( (LPTSTR)lpMsgBuf );
+ LPTSTR msg = (LPTSTR)lpMsgBuf;
+ str = QString( SUIT_Tools::toQString( msg ) );
LocalFree( lpMsgBuf );
#else
str = QString( dlerror() );
return 0;
AppLib lib = 0;
+ QByteArray bid = libFile.toLatin1();
#ifdef WIN32
- lib = ::LoadLibrary( (char*)libFile.latin1() );
+#ifdef UNICODE
+ LPTSTR str = (LPTSTR)libFile.utf16();
+#else
+ LPTSTR str = (LPTSTR)(const char*)bid;
+#endif
+ lib = ::LoadLibrary( str );
#else
- lib = dlopen( (char*)libFile.latin1(), RTLD_LAZY | RTLD_GLOBAL );
+ lib = dlopen( (const char*)libFile.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
#endif
return lib;
}
{
myActiveApp = app;
}
-
-/*!
- \retval Return TRUE, if a command is currently executed in Python Console,
- FALSE otherwise.
-*/
-bool SUIT_Session::IsPythonExecuted()
-{
- bool ret;
- SUIT_Session_PythonMutex.lock();
- ret = SUIT_Session_IsPythonExecuted;
- SUIT_Session_PythonMutex.unlock();
- return ret;
-}
-
-/*!
- Set value of boolean flag, being returned by method \a IsPythonExecuted().
- It is supposed to set the flag to TRUE when any python command starts
- and reset it to FALSE when the command finishes.
-*/
-void SUIT_Session::SetPythonExecuted(bool isPythonExecuted)
-{
- SUIT_Session_PythonMutex.lock();
- SUIT_Session_IsPythonExecuted = isPythonExecuted;
- SUIT_Session_PythonMutex.unlock();
-}
#include "SUIT.h"
-#include "SUIT_Application.h"
-#include "SUIT_ResourceMgr.h"
+#include <SUIT_Application.h>
-#include <qmutex.h>
-#include <qobject.h>
-#include <qptrlist.h>
-#include <qptrvector.h>
-#include <qstringlist.h>
+#include <QList>
+#include <QObject>
+#include <QString>
+
+#ifdef WIN32
+#include <windows.h>
+#endif
#ifdef WIN32
#define LIB_HANDLE HINSTANCE
class SUIT_ResourceMgr;
class SUIT_ExceptionHandler;
-#ifdef WNT
+#ifdef WIN32
#pragma warning( disable:4251 )
#endif
/*!
by static function "createApplication" in external library. The Library must be loaded with \n
loadLibrary method and after that application can be started.
*/
-class SUIT_EXPORT SUIT_Session: public QObject
+class SUIT_EXPORT SUIT_Session : public QObject
{
Q_OBJECT
SUIT_Application* startApplication( const QString&, int = 0, char** = 0 );
- QPtrList<SUIT_Application> applications() const;
+ QList<SUIT_Application*> applications() const;
SUIT_Application* activeApplication() const;
SUIT_ResourceMgr* resourceMgr() const;
SUIT_ExceptionHandler* handler() const;
- // To lock GUI user actions during python command execution (PAL12651)
- static bool IsPythonExecuted();
- static void SetPythonExecuted(bool isPythonExecuted);
+ void insertApplication( SUIT_Application* );
signals:
void applicationClosed( SUIT_Application* );
void onApplicationActivated( SUIT_Application* );
private:
- typedef QPtrList<SUIT_Application> AppList;
- typedef QMap<QString, AppLib> AppLibMap;
- typedef QPtrListIterator<SUIT_Application> AppListIterator;
+ typedef QList<SUIT_Application*> AppList;
+ typedef QMap<QString, AppLib> AppLibMap;
private:
QString lastError() const;
#include "SUIT_DataObject.h"
#include "SUIT_MessageBox.h"
#include "SUIT_Application.h"
-#include <qvaluevector.h>
/*!\class SUIT_Study
* Support study management. Object management. Operation management.
SUIT_Study::SUIT_Study( SUIT_Application* app )
: QObject(),
myApp( app ),
+myName( "" ),
myIsSaved( false ),
myIsModified( false ),
-myName( "" ),
myBlockChangeState( false )
{
static int _id = 0;
myId = ++_id;
myRoot = new SUIT_DataObject();
- myOperations.setAutoDelete( false );
- myOperations.setAutoDelete( false );
}
/*!Destructor.*/
*/
SUIT_Operation* SUIT_Study::activeOperation() const
{
- return myOperations.count() > 0 ? myOperations.getLast() : 0;
+ return myOperations.count() > 0 ? myOperations.last() : 0;
}
/*!
/*!
*Close document. NOT IMPLEMENTED.
*/
-void SUIT_Study::closeDocument(bool permanently)
+void SUIT_Study::closeDocument(bool /*permanently*/)
{
}
Custom document initialization to be performed \n
within onNewDoc() handler can be put here
*/
-void SUIT_Study::createDocument()
+bool SUIT_Study::createDocument( const QString& )
{
+ return true;
}
/*!
void SUIT_Study::abortAllOperations()
{
myBlockChangeState = true;
- for( SUIT_Operation* op = myOperations.first(); op; op = myOperations.next() )
- op->abort();
+ for ( Operations::iterator it = myOperations.begin(); it != myOperations.end(); ++it )
+ (*it)->abort();
myBlockChangeState = false;
myOperations.clear();
}
return 0;
Operations tmpOps( myOperations );
- SUIT_Operation* anOp = 0;
- for ( anOp = tmpOps.last(); anOp; anOp = tmpOps.prev() )
+ for ( Operations::const_iterator it = tmpOps.end(); it != tmpOps.begin(); --it )
{
+ SUIT_Operation* anOp = *it;
if ( anOp != 0 && anOp!= theOp && !anOp->isValid( theOp ) )
return anOp;
}
*/
bool SUIT_Study::start( SUIT_Operation* theOp, const bool toCheck )
{
- if ( !theOp || myOperations.find( theOp ) >= 0 )
+ if ( !theOp || myOperations.contains( theOp ) )
return false;
theOp->setExecStatus( SUIT_Operation::Rejected );
if ( toCheck )
{
- while( SUIT_Operation* anOp = blockingOperation( theOp ) )
+ while ( SUIT_Operation* anOp = blockingOperation( theOp ) )
{
- int anAnsw = SUIT_MessageBox::warn2( application()->desktop(),
- tr( "OPERATION_LAUNCH" ), tr( "PREVIOUS_NOT_FINISHED" ),
- tr( "CONTINUE" ), tr( "CANCEL" ), 0, 1, 1 );
+ int anAnsw = SUIT_MessageBox::question( application()->desktop(),
+ tr( "OPERATION_LAUNCH" ), tr( "PREVIOUS_NOT_FINISHED" ),
+ tr( "CONTINUE" ), tr( "CANCEL" ) );
if ( anAnsw == 1 )
return false;
*/
bool SUIT_Study::abort( SUIT_Operation* theOp )
{
- if ( !theOp || myOperations.find( theOp ) == -1 )
+ if ( !theOp || !myOperations.contains( theOp ) )
return false;
theOp->setExecStatus( SUIT_Operation::Rejected );
*/
bool SUIT_Study::commit( SUIT_Operation* theOp )
{
- if ( !theOp || myOperations.find( theOp ) == -1 )
+ if ( !theOp || !myOperations.contains( theOp ) )
return false;
theOp->setExecStatus( SUIT_Operation::Accepted );
*/
bool SUIT_Study::suspend( SUIT_Operation* theOp )
{
- if ( !theOp || myOperations.find( theOp ) == -1 || theOp->state() == SUIT_Operation::Suspended )
+ if ( !theOp || !myOperations.contains( theOp ) || theOp->state() == SUIT_Operation::Suspended )
return false;
theOp->setState( SUIT_Operation::Suspended );
*/
bool SUIT_Study::resume( SUIT_Operation* theOp )
{
- if ( !theOp || myOperations.find( theOp ) == -1 ||
+ if ( !theOp || !myOperations.contains( theOp ) ||
theOp->state() == SUIT_Operation::Running ||
blockingOperation( theOp ) != 0 )
return false;
// Move operation at the end of list in order to sort it in the order of activation.
// As result active operation is a last operation of list, operation which was active
// before currently active operation is located before it and so on
- myOperations.remove( theOp );
+ myOperations.removeAll( theOp );
myOperations.append( theOp );
emit theOp->resumed( theOp );
void SUIT_Study::stop( SUIT_Operation* theOp )
{
theOp->setState( SUIT_Operation::Waiting );
- myOperations.remove( theOp );
+ myOperations.removeAll( theOp );
// get last operation which can be resumed
- SUIT_Operation* anOp, *aResultOp = 0;
- for ( anOp = myOperations.last(); anOp; anOp = myOperations.prev() )
+ SUIT_Operation* aResultOp = 0;
+ for ( Operations::iterator it = myOperations.end(); it != myOperations.begin(); --it )
{
+ SUIT_Operation* anOp = *it;
if ( anOp && anOp != theOp && blockingOperation( anOp ) == 0 )
{
aResultOp = anOp;
* \brief Get all started operations
* \return List of all started operations
*/
-const QPtrList<SUIT_Operation>& SUIT_Study::operations() const
+const QList<SUIT_Operation*>& SUIT_Study::operations() const
{
return myOperations;
}
/*!
* \brief Restores the study state
*/
-void SUIT_Study::restoreState(int savePoint)
+void SUIT_Study::restoreState(int /*savePoint*/)
{
}
#include "SUIT.h"
-#include "SUIT_Operation.h"
-
-#include <qobject.h>
-#include <qptrlist.h>
+#include <QList>
+#include <QObject>
class SUIT_DataObject;
class SUIT_Application;
-class QDialog;
+class SUIT_Operation;
#ifdef WIN32
#pragma warning( disable:4251 )
virtual bool isSaved() const;
virtual bool isModified() const;
- virtual void createDocument();
virtual void closeDocument( bool = true );
virtual bool openDocument( const QString& );
+ virtual bool createDocument( const QString& );
bool saveDocument();
virtual bool saveDocumentAs( const QString& );
// Operation management
SUIT_Operation* activeOperation() const;
virtual void abortAllOperations();
- const QPtrList<SUIT_Operation>& operations() const;
+ const QList<SUIT_Operation*>& operations() const;
virtual SUIT_Operation* blockingOperation( SUIT_Operation* ) const;
virtual bool commitTransaction( const QString& = QString::null );
private:
- typedef QPtrList<SUIT_Operation> Operations;
+ typedef QList<SUIT_Operation*> Operations;
void stop( SUIT_Operation* );
private:
#include "SUIT_ToolButton.h"
-#include <qpopupmenu.h>
-#include <qstyle.h>
+#include <QMenu>
/*!Constructor.*/
-SUIT_ToolButton::SUIT_ToolButton( QWidget *parent,
- const char *name,
- bool changeItemAfterClick)
- : QToolButton( parent, name ),
- myChangeItemAfterClick( changeItemAfterClick )
+SUIT_ToolButton::SUIT_ToolButton( QWidget *parent, const char* /*name*/,
+ bool changeItemAfterClick )
+: QToolButton( parent ),
+myChangeItemAfterClick( changeItemAfterClick )
{
initialize();
}
-/*!Constructor.*/
-SUIT_ToolButton::SUIT_ToolButton( const QPixmap & pm,
- const QString &textLabel,
- const QString& grouptext,
- QObject * receiver,
- const char* slot,
- QToolBar * parent,
- const char* name,
- bool changeItemAfterClick)
- :QToolButton(pm, textLabel, grouptext, receiver, slot, parent, name),
- myChangeItemAfterClick( changeItemAfterClick )
-{
- initialize();
-}
-
-
/*!Initialize tool buttons.*/
void SUIT_ToolButton::initialize()
{
- mySignal = NULL;
- myPopup = new QPopupMenu( this );
- setPopup(myPopup);
- connect( myPopup, SIGNAL(activated(int)), SLOT(OnSelectAction(int)) );
- setPopupDelay(250);
+ myPopup = new QMenu( this );
+ setMenu( myPopup );
+ connect( myPopup, SIGNAL( triggered( QAction* ) ), SLOT( OnSelectAction( QAction* ) ) );
}
/*!drawButton is redefined to draw DownArrow*/
-void SUIT_ToolButton::drawButton( QPainter * p )
+void SUIT_ToolButton::drawButton( QPainter * /*p*/ )
{
- QToolButton::drawButton(p);
+/*
+ QToolButton::drawButton( p );
//draw DownArrow
int x, y, w, h;
style().drawPrimitive( QStyle::PE_ArrowDown,
p, QRect(x+w/2+3, y+h/2+3, w/2, h/2), //QRect(x+(w-x)/2, y+(h-y)/2, w, h)
colorGroup(), isEnabled() );
+*/
}
-
/*! Add action into popup*/
-void SUIT_ToolButton::AddAction(QAction* theAction)
+void SUIT_ToolButton::AddAction( QAction* theAction )
{
bool aIsFirst = false;
- if ( myPopup->count() == 0 )
+ if ( myPopup->actions().isEmpty() )
{
aIsFirst = true;
- setPixmap(theAction->iconSet().pixmap());
- setTextLabel(theAction->text());
- theAction->addTo( myPopup );
- QMenuItem* aItem = myPopup->findItem(myPopup->idAt(0));
- if (aItem != NULL)
- {
- mySignal = aItem->signal();
- }
+ setIcon( theAction->icon() );
+ setText( theAction->text() );
+ myPopup->setActiveAction( theAction );
}
- else
- theAction->addTo( myPopup );
+ myPopup->addAction( theAction );
}
/*! Sets myPopup item with theIndex as current*/
-void SUIT_ToolButton::SetItem(int theIndex)
+void SUIT_ToolButton::SetItem( int theIndex )
{
- int anId = myPopup->idAt(theIndex);
- if (anId != -1)
+ QAction* a = myPopup->actions()[theIndex];
+ if ( a )
{
- // Protection against unexpected null pointers returned
- if ( myPopup->iconSet(anId) )
- setPixmap(myPopup->iconSet(anId)->pixmap());
- setTextLabel(myPopup->text(anId));
- QMenuItem* aItem = myPopup->findItem(anId);
- if (aItem != NULL)
- {
- mySignal = aItem->signal();
- }
+ setIcon( a->icon() );
+ setText( a->text() );
+ myPopup->setActiveAction( a );
}
}
/*!Public SLOT.
- * On select action (icon and text set with id = \a theItemID)
+ * On select action (icon and text set from action = \a theAction)
*/
-void SUIT_ToolButton::OnSelectAction(int theItemID)
+void SUIT_ToolButton::OnSelectAction( QAction* theAction )
{
- if (myChangeItemAfterClick)
+ if ( theAction && myChangeItemAfterClick )
{
// Protection against unexpected null pointers returned
- if ( myPopup->iconSet(theItemID) )
- setPixmap(myPopup->iconSet(theItemID)->pixmap());
- setTextLabel(myPopup->text(theItemID));
- QMenuItem* aItem = myPopup->findItem(theItemID);
- if (aItem != NULL)
- {
- mySignal = aItem->signal();
- }
+ QIcon anIcon = theAction->icon();
+ if ( !anIcon.isNull() )
+ setIcon(anIcon);
+ setText(theAction->text());
+ myPopup->setActiveAction( theAction );
}
}
-
-
/*!On mouse release event.*/
-void SUIT_ToolButton::mouseReleaseEvent ( QMouseEvent * theEvent)
+void SUIT_ToolButton::mouseReleaseEvent( QMouseEvent* theEvent )
{
- QToolButton::mouseReleaseEvent(theEvent);
- if (mySignal != NULL)
- {
- mySignal->activate();
- }
+ QToolButton::mouseReleaseEvent( theEvent );
+ QAction* anAction = myPopup->activeAction();
+ if ( anAction )
+ anAction->activate( QAction::Trigger );
}
-
-
#ifndef SUIT_TOOLBUTTON_H
#define SUIT_TOOLBUTTON_H
-#include <qtoolbutton.h>
-#include <qaction.h>
-
#include "SUIT.h"
+#include <QToolButton>
+
+class QAction;
+class QPixmap;
+class QToolBar;
+
/*! To draw down arrow on toolbutton.*/
class SUIT_EXPORT SUIT_ToolButton : public QToolButton
{
SUIT_ToolButton( QWidget *parent = 0,
const char *name = 0,
bool changeItemAfterClick = true );
- SUIT_ToolButton( const QPixmap & pm, const QString &textLabel,
- const QString& grouptext,
- QObject * receiver, const char* slot,
- QToolBar * parent, const char* name = 0,
- bool changeItemAfterClick = true );
//@}
void drawButton( QPainter * pQPainter);
void SetItem(int theIndex);
public slots:
- void OnSelectAction(int theItemID);
+ void OnSelectAction( QAction* theAction );
protected:
void mouseReleaseEvent (QMouseEvent * theEvent);
private:
void initialize();
- QPopupMenu* myPopup;
- QSignal* mySignal;
- bool myChangeItemAfterClick;
+ QMenu* myPopup;
+ bool myChangeItemAfterClick;
};
#endif
-
//
#include "SUIT_Tools.h"
-#include <qdir.h>
+#include <QDir>
#include <stdio.h>
#include <stdarg.h>
tmpPath += QString( "Salome_trace" );
FILE* pStream;
- pStream = fopen( lpszLog ? lpszLog : tmpPath.latin1(), "a" );
+ pStream = fopen( lpszLog ? lpszLog : (const char*)tmpPath.toLatin1(), "a" );
if ( pStream )
{
va_list argptr;
*/
QRect SUIT_Tools::makeRect( const int x1, const int y1, const int x2, const int y2 )
{
- return QRect( QMIN( x1, x2 ), QMIN( y1, y2 ), QABS( x2 - x1 ), QABS( y2 - y1 ) );
+ return QRect( qMin( x1, x2 ), qMin( y1, y2 ), qAbs( x2 - x1 ), qAbs( y2 - y1 ) );
}
/*!
QFont SUIT_Tools::stringToFont( const QString& fontDescription )
{
QFont font;
- if ( fontDescription.stripWhiteSpace().isEmpty() || !font.fromString( fontDescription ) )
+ if ( fontDescription.trimmed().isEmpty() || !font.fromString( fontDescription ) )
font = QFont( "Courier", 11 );
return font;
}
#include <Qtx.h>
-#include <qrect.h>
-#include <qfont.h>
-#include <qstring.h>
+#include <QRect>
+#include <QString>
+#include <QFont>
/*!
\class SUIT_Tools
#ifndef SUIT_TREE_SYNC_HEADER
#define SUIT_TREE_SYNC_HEADER
-#include <qptrlist.h>
-#include <qvaluelist.h>
+#include <QList>
/*!
\struct DiffItem
*/
template <class SrcItem, class TrgItem, class TreeData>
void diffSiblings( const SrcItem&, const TrgItem&,
- QValueList < DiffItem < SrcItem,TrgItem > >&,
+ QList < DiffItem < SrcItem,TrgItem > >&,
const TreeData& );
/*!
\brief find equal element in list
*/
template <class SrcItem, class TrgItem, class TreeData>
-const typename QValueList<TrgItem>::const_iterator findEqual( const QValueList<TrgItem>& l,
- const typename QValueList<TrgItem>::const_iterator& first,
- const SrcItem& it,
- const TreeData& td );
+const typename QList<TrgItem>::const_iterator findEqual( const QList<TrgItem>& l,
+ const typename QList<TrgItem>::const_iterator& first,
+ const SrcItem& it,
+ const TreeData& td );
) const - creates new TrgItem
<li> void updateItem( const TrgItem& ) const - updates TrgItem without recreation
<li> void deleteItemWithChildren( const TrgItem& ) const - deletes TrgItem with all children
- <li> void children( const SrcItem&, QValueList<SrcItem>& ) const - fills list with children
- <li> void children( const TrgItem&, QValueList<TrgItem>& ) const - fills list with children
+ <li> void children( const SrcItem&, QList<SrcItem>& ) const - fills list with children
+ <li> void children( const TrgItem&, QList<TrgItem>& ) const - fills list with children
<li> SrcItem parent( const SrcItem& ) const - return parent SrcItem
<li> TrgItem parent( const TrgItem& ) const - return parent SrcItem
</ul>
td.updateItem( r1, r2 );
// iterate 'siblings' (direct children)
- QValueList< DiffItem< SrcItem, TrgItem > > d;
+ QList< DiffItem< SrcItem, TrgItem > > d;
diffSiblings( r1, r2, d, td );
- typename QValueList< DiffItem< SrcItem, TrgItem > >::const_iterator anIt = d.begin(), aLast = d.end();
+ typename QList< DiffItem< SrcItem, TrgItem > >::const_iterator anIt = d.begin(), aLast = d.end();
TrgItem lastItem = td.nullTrg();
// TrgItem tail = td.nullTrg();
for( ; anIt!=aLast; anIt++ )
\param td - tree data object (provides auxiliary methods)
*/
template <class SrcItem, class TrgItem, class TreeData>
-const typename QValueList<TrgItem>::const_iterator findEqual( const QValueList<TrgItem>& l,
- const typename QValueList<TrgItem>::const_iterator& first,
- const SrcItem& it,
- const TreeData& td )
+const typename QList<TrgItem>::const_iterator findEqual( const QList<TrgItem>& l,
+ const typename QList<TrgItem>::const_iterator& first,
+ const SrcItem& it,
+ const TreeData& td )
{
- typename QValueList<TrgItem>::const_iterator cur = first, last = l.end();
+ typename QList<TrgItem>::const_iterator cur = first, last = l.end();
for( ; cur!=last; cur++ )
if( td.isEqual( it, *cur ) )
return cur;
*/
template <class SrcItem, class TrgItem, class TreeData>
void diffSiblings( const SrcItem& src, const TrgItem& trg,
- QValueList < DiffItem < SrcItem,TrgItem > >& d,
+ QList < DiffItem < SrcItem,TrgItem > >& d,
const TreeData& td )
{
//if( src==td.nullSrc() || trg==td.nullTrg() )
// return;
- QValueList<SrcItem> src_ch;
- QValueList<TrgItem> trg_ch;
+ QList<SrcItem> src_ch;
+ QList<TrgItem> trg_ch;
td.children( src, src_ch );
td.children( trg, trg_ch );
- typename QValueList<SrcItem>::const_iterator src_it = src_ch.begin(), src_last = src_ch.end();
- typename QValueList<TrgItem>::const_iterator cur = trg_ch.begin(), trg_last = trg_ch.end();
+ typename QList<SrcItem>::const_iterator src_it = src_ch.begin(), src_last = src_ch.end();
+ typename QList<TrgItem>::const_iterator cur = trg_ch.begin(), trg_last = trg_ch.end();
for( ; src_it!=src_last; src_it++ )
{
- typename QValueList<TrgItem>::const_iterator f =
+ typename QList<TrgItem>::const_iterator f =
findEqual<SrcItem, TrgItem, TreeData>( trg_ch, cur, *src_it, td );
if( f!=trg_last ) //is found
{
//mark all items before found as "to be deleted"
- for( typename QValueList<TrgItem>::const_iterator it = cur; it!=f; it++ )
+ for( typename QList<TrgItem>::const_iterator it = cur; it!=f; it++ )
{
DiffItem<SrcItem,TrgItem> ndiff;
ndiff.mySrc = td.nullSrc();
if( nitem==td.nullTrg() )
return nitem;
- QValueList<SrcItem> ch;
+ QList<SrcItem> ch;
td.children( src, ch );
- typename QValueList<SrcItem>::const_iterator anIt = ch.begin(), aLast = ch.end();
+ typename QList<SrcItem>::const_iterator anIt = ch.begin(), aLast = ch.end();
for( ; anIt!=aLast; anIt++ )
createSubTree( *anIt, nitem, td.nullTrg(), false, td );
// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
+//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
+// License as published by the Free Software Foundation; either
// version 2.1 of the License.
-//
-// This library 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
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#include "SUIT_Desktop.h"
#include "SUIT_ViewModel.h"
+#include <SUIT_ViewWindow.h>
#include "SUIT_Study.h"
-#include <qcursor.h>
-#include <qregexp.h>
-#include <qmessagebox.h>
+#include <QMap>
+#include <QRegExp>
+#include <QIcon>
-#ifdef WNT
+#ifdef WIN32
#include <windows.h>
#endif
myId = useNewId( getType() );
- connect( theDesktop, SIGNAL( windowActivated( SUIT_ViewWindow* ) ),
+ connect( theDesktop, SIGNAL( windowActivated( SUIT_ViewWindow* ) ),
this, SLOT( onWindowActivated( SUIT_ViewWindow* ) ) );
myStudy = theStudy;
return;
myTitle = theTitle;
- for ( uint i = 0; i < myViews.count(); i++ )
+ for ( int i = 0; i < myViews.count(); i++ )
setViewName( myViews[i] );
}
+void SUIT_ViewManager::setIcon( const QPixmap& theIcon )
+{
+ myIcon = theIcon;
+ for ( int i = 0; i < myViews.count(); i++ )
+ myViews[i]->setWindowIcon( QIcon( myIcon ) );
+}
+
/*!Sets view model \a theViewModel to view manager.*/
-void SUIT_ViewManager::setViewModel(SUIT_ViewModel* theViewModel)
+void SUIT_ViewManager::setViewModel(SUIT_ViewModel* theViewModel)
{
if (myViewModel && myViewModel != theViewModel) {
myViewModel->setViewManager(0);
/*!Sets view name for view window \a theView.*/
void SUIT_ViewManager::setViewName( SUIT_ViewWindow* theView )
{
- QString title = prepareTitle( getTitle(), myId + 1, myViews.find( theView ) + 1 );
- theView->setCaption( title );
+ QString title = prepareTitle( getTitle(), myId + 1, myViews.indexOf( theView ) + 1 );
+ theView->setWindowTitle( title );
}
QString SUIT_ViewManager::prepareTitle( const QString& title, const int mId, const int vId )
QString res = title;
QRegExp re( "%[%MV]" );
int i = 0;
- while ( ( i = re.search( res, i ) ) != -1 )
+ while ( ( i = re.indexIn( res, i ) ) != -1 )
{
QString rplc;
QString str = res.mid( i, re.matchedLength() );
delete aView;
return 0;
}
-
+
setViewName( aView );
+ aView->setWindowIcon( QIcon( myIcon ) );
+
//myDesktop->addViewWindow( aView );
//it is done automatically during creation of view
- aView->setViewManager(this);
-
- emit viewCreated(aView);
+ aView->setViewManager( this );
+ emit viewCreated( aView );
// Special treatment for the case when <aView> is the first one in this view manager
// -> call onWindowActivated() directly, because somebody may always want
createViewWindow();
}
+QVector<SUIT_ViewWindow*> SUIT_ViewManager::getViews() const
+{
+ QVector<SUIT_ViewWindow*> res;
+ for ( int i = 0; i < myViews.count(); i++ )
+ {
+ if ( myViews[i] )
+ res.append( myViews[i] );
+ }
+
+ return res;
+}
+
/*!Insert view window to view manager.
*\retval false - if something wrong, else true.
*/
bool SUIT_ViewManager::insertView(SUIT_ViewWindow* theView)
{
unsigned int aSize = myViews.size();
- unsigned int aNbItems = myViews.count()+1;
- if (aNbItems > aSize) {
- if (!myViews.resize(aNbItems)) {
- QMessageBox::critical(myDesktop, tr("Critical error"), tr("There is no memory for the new view!!!"));
- return false;
- }
+ unsigned int aNbItems = myViews.count() + 1;
+ if ( aNbItems > aSize )
+ {
+ myViews.resize( aNbItems );
aSize = myViews.size();
}
-
+
connect(theView, SIGNAL(closing(SUIT_ViewWindow*)),
this, SLOT(onClosingView(SUIT_ViewWindow*)));
connect(theView, SIGNAL(contextMenuRequested( QContextMenuEvent * )),
this, SLOT (onContextMenuRequested( QContextMenuEvent * )));
- for (uint i = 0; i < aSize; i++) {
- if (myViews[i]==0) {
- myViews.insert(i, theView);
+ for ( uint i = 0; i < aSize; i++ )
+ {
+ if ( myViews[i] == 0 )
+ {
+ myViews[i] = theView;
return true;
}
}
if ( !theView )
return;
- QGuardedPtr<SUIT_ViewWindow> view( theView );
+ QPointer<SUIT_ViewWindow> view( theView );
view->hide();
- if ( !view->testWFlags( WDestructiveClose ) )
+ if ( !view->testAttribute( Qt::WA_DeleteOnClose ) )
return;
emit deleteView( view );
/*!Remove view window \a theView from view manager.
*And close the last view, if it has \a theView.
*/
-void SUIT_ViewManager::removeView(SUIT_ViewWindow* theView)
+void SUIT_ViewManager::removeView( SUIT_ViewWindow* theView )
{
- theView->disconnect(this);
- myViews.remove(myViews.find(theView));
- if (myActiveView == theView)
+ theView->disconnect( this );
+ myViews.remove( myViews.indexOf( theView ) );
+ if ( myActiveView == theView )
myActiveView = 0;
- int aNumItems = myViews.count();
- if (aNumItems == 0)
- emit lastViewClosed(this);
+ if ( !myViews.count() )
+ emit lastViewClosed( this );
}
/*!
*/
void SUIT_ViewManager::setDestructiveClose( const bool on )
{
- for ( uint i = 0; i < myViews.count(); i++ )
+ for ( int i = 0; i < myViews.count(); i++ )
myViews[i]->setDestructiveClose( on );
}
bool SUIT_ViewManager::isVisible() const
{
bool res = false;
- for ( uint i = 0; i < myViews.count() && !res; i++ )
+ for ( int i = 0; i < myViews.count() && !res; i++ )
res = myViews[i]->isVisibleTo( myViews[i]->parentWidget() );
return res;
}
*/
void SUIT_ViewManager::setShown( const bool on )
{
- for ( uint i = 0; i < myViews.count(); i++ )
+ for ( int i = 0; i < myViews.count(); i++ )
myViews.at( i )->setShown( on );
}
*/
void SUIT_ViewManager::closeAllViews()
{
- for ( uint i = 0; i < myViews.size(); i++ )
+ for ( int i = 0; i < myViews.size(); i++ )
delete myViews[i];
myViews.clear();
}
*\retval QString - type of view model.
*/
QString SUIT_ViewManager::getType() const
-{
- return (!myViewModel)? "": myViewModel->getType();
+{
+ return (!myViewModel)? "": myViewModel->getType();
}
/*!
}
/*!Context menu popup for \a popup.*/
-void SUIT_ViewManager::contextMenuPopup( QPopupMenu* popup )
+void SUIT_ViewManager::contextMenuPopup( QMenu* popup )
{
SUIT_ViewModel* vm = getViewModel();
if ( vm )
// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
+//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
+// License as published by the Free Software Foundation; either
// version 2.1 of the License.
-//
-// This library 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
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#define SUIT_VIEWMANAGER_H
#include "SUIT.h"
-#include "SUIT_ViewWindow.h"
+
#include "SUIT_PopupClient.h"
-#include <qobject.h>
-#include <qptrvector.h>
+#include <QObject>
+#include <QPixmap>
+#include <QVector>
+#include <QPointer>
+
+class QMenu;
+class QMouseEvent;
+class QWheelEvent;
+class QKeyEvent;
class SUIT_Study;
class SUIT_Desktop;
class SUIT_ViewModel;
-
-class QPopupMenu;
+class SUIT_ViewWindow;
#ifdef WIN32
#pragma warning( disable:4251 )
virtual ~SUIT_ViewManager();
virtual QString popupClientType() const { return getType(); }
- virtual void contextMenuPopup( QPopupMenu* );
-
+ virtual void contextMenuPopup( QMenu* );
+
void setViewModel(SUIT_ViewModel* theViewModel);
SUIT_ViewModel* getViewModel() { return myViewModel; }
-
+
SUIT_Study* study() const;
- QString getType() const;
+ QString getType() const;
SUIT_ViewWindow* getActiveView() { return myActiveView; }
-
+
int getViewsCount() { return myViews.count(); }
- QPtrVector<SUIT_ViewWindow> getViews() { return myViews; }
+ QVector<SUIT_ViewWindow*> getViews() const;
QString getTitle() const { return myTitle; }
virtual void setTitle( const QString& );
+ QPixmap getIcon() const { return myIcon; }
+ virtual void setIcon( const QPixmap& );
+
SUIT_ViewWindow* createViewWindow();
bool isVisible() const;
public slots:
void createView();
void closeAllViews();
-
+
signals:
void lastViewClosed(SUIT_ViewManager*);
void deleteView(SUIT_ViewWindow*);
void keyPress(SUIT_ViewWindow*, QKeyEvent*);
void keyRelease(SUIT_ViewWindow*, QKeyEvent*);
void activated(SUIT_ViewManager*);
-
+
protected slots:
void onWindowActivated(SUIT_ViewWindow*);
void onClosingView( SUIT_ViewWindow* );
private slots:
void onContextMenuRequested( QContextMenuEvent* e );
-
+
protected:
/*! Inserts the View into internal Views Vector.\n
* Returns true if view has been added successfully
*/
virtual bool insertView(SUIT_ViewWindow* theView);
-
+
/*! Removes the View from internal Views Vector.*/
virtual void removeView(SUIT_ViewWindow* theView);
-
+
/*! Close the specified View.*/
virtual void closeView(SUIT_ViewWindow* theView);
-
+
/*! Used to set unique name for the view.*/
- virtual void setViewName(SUIT_ViewWindow* theView);
+ virtual void setViewName(SUIT_ViewWindow* theView );
QString prepareTitle( const QString&, const int, const int );
static int useNewId( const QString& );
+protected:
+ typedef QPointer<SUIT_ViewWindow> ViewWindow;
+
protected:
SUIT_Desktop* myDesktop;
SUIT_ViewModel* myViewModel;
- QPtrVector<SUIT_ViewWindow> myViews;
+ QVector<ViewWindow> myViews;
SUIT_ViewWindow* myActiveView;
int myId;
+ QPixmap myIcon;
QString myTitle;
SUIT_Study* myStudy;
#include "SUIT_ViewModel.h"
+#include <SUIT_ViewWindow.h>
+
SUIT_ViewModel::StatesMap SUIT_ViewModel::myStateMap;
SUIT_ViewModel::ButtonsMap SUIT_ViewModel::myButtonMap;
/*!Constructor.*/
SUIT_ViewModel::SUIT_ViewModel()
{
- if (!isInitialized) {
+ if ( !isInitialized )
+ {
isInitialized = true;
- SUIT_ViewModel::myStateMap[ZOOM] = Qt::ControlButton;
+ SUIT_ViewModel::myStateMap[ZOOM] = Qt::ControlModifier;
SUIT_ViewModel::myButtonMap[ZOOM] = Qt::LeftButton;
- SUIT_ViewModel::myStateMap[PAN] = Qt::ControlButton;
+ SUIT_ViewModel::myStateMap[PAN] = Qt::ControlModifier;
SUIT_ViewModel::myButtonMap[PAN] = Qt::MidButton;
- SUIT_ViewModel::myStateMap[ROTATE] = Qt::ControlButton;
+ SUIT_ViewModel::myStateMap[ROTATE] = Qt::ControlModifier;
SUIT_ViewModel::myButtonMap[ROTATE] = Qt::RightButton;
- SUIT_ViewModel::myStateMap[FIT_AREA] = Qt::ControlButton;
+ SUIT_ViewModel::myStateMap[FIT_AREA] = Qt::ControlModifier;
SUIT_ViewModel::myButtonMap[FIT_AREA] = Qt::RightButton;
}
myViewManager = 0;
return new SUIT_ViewWindow(theDesktop);
}
+/*!Set view manager.
+ \param theViewManager view manager
+ */
+void SUIT_ViewModel::setViewManager(SUIT_ViewManager* theViewManager)
+{
+ myViewManager = theViewManager;
+}
+
+/*!Get view manager.
+ \return view manager
+ */
+SUIT_ViewManager* SUIT_ViewModel::getViewManager() const
+{
+ return myViewManager;
+}
+
/*! Sets hot button
*\param theOper - hot operation
*\param theState - adding state to state map operations.
*\param theButton - adding state to button map operations.
*/
-void SUIT_ViewModel::setHotButton(HotOperation theOper, Qt::ButtonState theState,
- Qt::ButtonState theButton)
+void SUIT_ViewModel::setHotButton( HotOperation theOper, Qt::KeyboardModifier theState, Qt::MouseButton theButton )
{
myStateMap[theOper] = theState;
myButtonMap[theOper] = theButton;
*\param theState - output state from state map operations.
*\param theButton - output state from button map operations.
*/
-void SUIT_ViewModel::getHotButton(HotOperation theOper, Qt::ButtonState& theState,
- Qt::ButtonState& theButton)
+void SUIT_ViewModel::getHotButton( HotOperation theOper, Qt::KeyboardModifier& theState, Qt::MouseButton& theButton )
{
theState = myStateMap[theOper];
theButton = myButtonMap[theOper];
#define SUIT_VIEWMODEL_H
#include "SUIT.h"
-#include "SUIT_Desktop.h"
-#include "SUIT_ViewWindow.h"
-#include "SUIT_ViewManager.h"
-#include <qobject.h>
-#include <qcursor.h>
+#include <QObject>
+#include <QMap>
+
+class QMenu;
+
+class SUIT_Desktop;
+class SUIT_ViewWindow;
+class SUIT_ViewManager;
#ifdef WIN32
#pragma warning( disable:4251 )
public:
enum HotOperation { PAN, ZOOM, ROTATE, FIT_AREA };
- typedef QMap<HotOperation, Qt::ButtonState> StatesMap;
- typedef QMap<HotOperation, Qt::ButtonState> ButtonsMap;
+ typedef QMap<HotOperation, Qt::KeyboardModifier> StatesMap;
+ typedef QMap<HotOperation, Qt::MouseButton> ButtonsMap;
- SUIT_ViewModel();
- virtual ~SUIT_ViewModel();
+ SUIT_ViewModel();
+ virtual ~SUIT_ViewModel();
- virtual SUIT_ViewWindow* createView(SUIT_Desktop* theDesktop);
+ virtual SUIT_ViewWindow* createView( SUIT_Desktop* theDesktop );
- virtual void setViewManager(SUIT_ViewManager* theViewManager) { myViewManager = theViewManager; }
- SUIT_ViewManager* getViewManager() const { return myViewManager; }
+ virtual void setViewManager(SUIT_ViewManager* theViewManager);
+ SUIT_ViewManager* getViewManager() const;
virtual QString getType() const { return "SUIT_ViewModel"; }
- virtual void contextMenuPopup(QPopupMenu*) {}
+ virtual void contextMenuPopup( QMenu* ) {}
- static void setHotButton(HotOperation theOper, Qt::ButtonState theState,
- Qt::ButtonState theButton);
- static void getHotButton(HotOperation theOper, Qt::ButtonState& theState,
- Qt::ButtonState& theButton);
+ static void setHotButton( HotOperation theOper, Qt::KeyboardModifier theState,
+ Qt::MouseButton theButton );
+ static void getHotButton( HotOperation theOper, Qt::KeyboardModifier& theState,
+ Qt::MouseButton& theButton );
protected:
- SUIT_ViewManager* myViewManager;
+ SUIT_ViewManager* myViewManager;
public:
static StatesMap myStateMap;
// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
+//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
+// License as published by the Free Software Foundation; either
// version 2.1 of the License.
-//
-// This library 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
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
#include "SUIT_ViewWindow.h"
+
+#include "SUIT_Tools.h"
+#include "SUIT_Study.h"
#include "SUIT_Desktop.h"
+#include "SUIT_MessageBox.h"
#include "SUIT_Application.h"
-#include "SUIT_Study.h"
#include "SUIT_ViewManager.h"
-#include "SUIT_Tools.h"
-#include "SUIT_MessageBox.h"
-#include <qhbox.h>
-#include <qpopupmenu.h>
-#include <qapplication.h>
-#include <qimage.h>
+
+#include <QEvent>
+#include <QIcon>
+#include <QApplication>
+#include <QContextMenuEvent>
/*!\class SUIT_ViewWindow
* Class provide view window.
const int DUMP_EVENT = QEvent::User + 123;
/*! Constructor.*/
-SUIT_ViewWindow::SUIT_ViewWindow(SUIT_Desktop* theDesktop)
-: QMainWindow( theDesktop, "SUIT_ViewWindow", Qt::WDestructiveClose )
+SUIT_ViewWindow::SUIT_ViewWindow( SUIT_Desktop* theDesktop )
+: QMainWindow( theDesktop )
{
myDesktop = theDesktop;
- if ( myDesktop->icon() )
- setIcon( *myDesktop->icon() );
+ setWindowIcon( myDesktop->windowIcon() );
+
+ setAttribute( Qt::WA_DeleteOnClose );
}
/*! Destructor.*/
bool SUIT_ViewWindow::dumpViewToFormat( const QImage& img, const QString& fileName, const QString& format )
{
if( img.isNull() )
- return false;
+ return false;
QString fmt = format;
if( fmt.isEmpty() )
else if( fmt == "JPG" )
fmt = "JPEG";
- QApplication::setOverrideCursor( Qt::waitCursor );
- bool res = img.save( fileName, fmt.latin1() );
+ QApplication::setOverrideCursor( Qt::WaitCursor );
+ bool res = img.save( fileName, fmt.toLatin1() );
QApplication::restoreOverrideCursor();
return res;
}
*/
void SUIT_ViewWindow::setDestructiveClose( const bool on )
{
- if ( on )
- setWFlags( WDestructiveClose );
- else
- clearWFlags( WDestructiveClose );
+ setAttribute( Qt::WA_DeleteOnClose, on );
}
/*! Close event \a theEvent.
*/
-void SUIT_ViewWindow::closeEvent(QCloseEvent* theEvent)
+void SUIT_ViewWindow::closeEvent( QCloseEvent* e )
{
-// QMainWindow::closeEvent( theEvent );
+ e->ignore();
emit closing( this );
}
*/
void SUIT_ViewWindow::onDumpView()
{
- qApp->postEvent( this, new QPaintEvent( QRect( 0, 0, width(), height() ), TRUE ) );
- qApp->postEvent( this, new QCustomEvent( DUMP_EVENT ) );
+ QApplication::postEvent( this, new QPaintEvent( QRect( 0, 0, width(), height() ) ) );
+ QApplication::postEvent( this, new QEvent( (QEvent::Type)DUMP_EVENT ) );
}
/*!
// get file name
SUIT_Application* app = myManager->study()->application();
QString fileName = app->getFileName( false, QString::null, filter(), tr( "TLT_DUMP_VIEW" ), 0 );
- if( !fileName.isEmpty() )
+ if ( !fileName.isEmpty() )
{
- QString fmt = SUIT_Tools::extension( fileName ).upper();
- bOk = dumpViewToFormat( im, fileName, fmt );
+ QString fmt = SUIT_Tools::extension( fileName ).toUpper();
+ bOk = dumpViewToFormat( im, fileName, fmt );
}
else
- {
- bOk = true; // cancelled
- }
- }
- if ( !bOk ) {
- SUIT_MessageBox::error1( this, tr( "ERROR" ), tr( "ERR_CANT_DUMP_VIEW" ), tr( "BUT_OK" ) );
+ bOk = true; // cancelled
}
- return TRUE;
+ if ( !bOk )
+ SUIT_MessageBox::critical( this, tr( "ERROR" ), tr( "ERR_CANT_DUMP_VIEW" ) );
+
+ return true;
}
return QMainWindow::event( e );
}
/*!
Sets visual parameters of window by its string representation
\param parameters - string with visual parameters
-*/
-void SUIT_ViewWindow::setVisualParameters( const QString& parameters )
+*/
+void SUIT_ViewWindow::setVisualParameters( const QString& /*parameters*/ )
{
}
// SUIT_ViewWindow.h: interface for the SUIT_ViewWindow class.
//
-#if !defined(AFX_SUIT_VIEWWINDOW_H__82C3D51A_6F10_45B0_BCFE_3CB3EF596A4D__INCLUDED_)
-#define AFX_SUIT_VIEWWINDOW_H__82C3D51A_6F10_45B0_BCFE_3CB3EF596A4D__INCLUDED_
-
-#if _MSC_VER > 1000
-#pragma once
-#endif // _MSC_VER > 1000
+#ifndef SUIT_VIEWWINDOW_H
+#define SUIT_VIEWWINDOW_H
#include "SUIT.h"
-#include <qmainwindow.h>
+#include <QMainWindow>
+#include <QImage>
class SUIT_Desktop;
class SUIT_ViewManager;
-class QImage;
class SUIT_EXPORT SUIT_ViewWindow: public QMainWindow
{
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>ICON_DESK_WINDOW_TILE</source>
+ <translation>htile.png</translation>
+ </message>
+ <message>
+ <source>ICON_DESK_WINDOW_CASCADE</source>
+ <translation>cascade.png</translation>
+ </message>
+ <message>
+ <source>ICON_DESK_WINDOW_VTILE</source>
+ <translation>vtile.png</translation>
+ </message>
+</context>
+</TS>
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>MEN_DESK_WINDOW</source>
+ <translation>&Window</translation>
+ </message>
+ <message>
+ <source>ERR_CANT_DUMP_VIEW</source>
+ <translation>Can't dump view contents to the file.</translation>
+ </message>
+ <message>
+ <source>TLT_IMAGE_FILES</source>
+ <translation>Images Files (*.bmp *.png *.jpg *.jpeg)</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_WINDOW_CASCADE</source>
+ <translation>&Cascade</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_WINDOW_CASCADE</source>
+ <translation>Arranges the windows as overlapping tiles</translation>
+ </message>
+ <message>
+ <source>ERR_DIR_NOT_EXIST</source>
+ <translation>The directory "%1" does not exist!</translation>
+ </message>
+ <message>
+ <source>LAB_QUICK_PATH</source>
+ <translation>Quick path:</translation>
+ </message>
+ <message>
+ <source>CONTINUE</source>
+ <translation>Continue</translation>
+ </message>
+ <message>
+ <source>CANCEL</source>
+ <translation>Cancel</translation>
+ </message>
+ <message>
+ <source>ERR_FILE_NOT_EXIST</source>
+ <translation>The file "%1" does not exist!</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_WINDOW_ACTIVATE</source>
+ <translation>Activates this window</translation>
+ </message>
+ <message>
+ <source>ERR_PERMISSION_DENIED</source>
+ <translation>Can't save file "%1".
+Permission denied.</translation>
+ </message>
+ <message>
+ <source>ERR_ERROR</source>
+ <translation>Error</translation>
+ </message>
+ <message>
+ <source>QUE_FILE_EXISTS</source>
+ <translation>The file "%1" already exists.
+Do you want to overwrite it?</translation>
+ </message>
+ <message>
+ <source>WRN_WARNING</source>
+ <translation>Warning</translation>
+ </message>
+ <message>
+ <source>TLT_DUMP_VIEW</source>
+ <translation>Dump View to File</translation>
+ </message>
+ <message>
+ <source>INF_DESK_DOC_OPEN</source>
+ <translation>Open File</translation>
+ </message>
+ <message>
+ <source>INF_DESK_DOC_SAVE</source>
+ <translation>Save File</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_WINDOW_TILE</source>
+ <translation>Arranges the windows as nonoverlapping tiles</translation>
+ </message>
+ <message>
+ <source>BUT_ADD_PATH</source>
+ <translation>Add path</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_WINDOW_VTILE</source>
+ <translation>Tile &Vertically</translation>
+ </message>
+ <message>
+ <source>INF_DIRECTORIES_FILTER</source>
+ <translation>Directories</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_WINDOW_VTILE</source>
+ <translation>Arranges the windows as nonoverlapping vertical tiles</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_WINDOW_TILE</source>
+ <translation>&Tile</translation>
+ </message>
+</context>
+<context>
+ <name>SUIT_Study</name>
+ <message>
+ <source>OPERATION_LAUNCH</source>
+ <translation>Operation launch</translation>
+ </message>
+ <message>
+ <source>PREVIOUS_NOT_FINISHED</source>
+ <translation>Previous operation is not finished and will be aborted</translation>
+ </message>
+</context>
+</TS>
lib_LTLIBRARIES = libSUITApp.la
-salomeinclude_HEADERS= SUITApp_Application.h
+salomeinclude_HEADERS= \
+ SUITApp_Application.h
-dist_libSUITApp_la_SOURCES= \
- SUITApp.cxx \
+dist_libSUITApp_la_SOURCES= \
+ SUITApp.cxx \
SUITApp_Application.cxx
-MOC_FILES=SUITApp_Application_moc.cxx
+MOC_FILES= \
+ SUITApp_Application_moc.cxx
+
nodist_libSUITApp_la_SOURCES= $(MOC_FILES)
nodist_salomeres_DATA= SUITApp_msg_en.qm
-I$(srcdir)/../SUIT -I$(srcdir)/../Qtx
libSUITApp_la_LDFLAGS=$(QT_MT_LIBS)
-libSUITApp_la_LIBADD= ../SUIT/libsuit.la ../Qtx/libqtx.la
+libSUITApp_la_LIBADD=../Qtx/libqtx.la ../SUIT/libsuit.la
if ENABLE_PYCONSOLE
libSUITApp_la_LDFLAGS+= -Xlinker -export-dynamic $(PYTHON_LIBS)
SUITApp_CPPFLAGS=$(QT_INCLUDES) $(PYTHON_INCLUDES) \
-I$(srcdir)/../SUIT -I$(srcdir)/../Qtx
-SUITApp_LDADD= libSUITApp.la ../SUIT/libsuit.la ../Qtx/libqtx.la
+SUITApp_LDADD= libSUITApp.la ../Qtx/libqtx.la ../SUIT/libsuit.la
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-#if defined WNT
+#if defined WIN32
#undef SUIT_ENABLE_PYTHON
//#else
#include "SUITApp_Application.h"
#include <SUIT_Session.h>
-#include <SUIT_Desktop.h>
+//#include <SUIT_Desktop.h>
#include <SUIT_ResourceMgr.h>
-#include <QtxSplash.h>
+// TODO
+//#include <QtxSplash.h>
#ifdef SUIT_ENABLE_PYTHON
#include <Python.h>
#endif
-#include <qdir.h>
-#include <qfile.h>
-#include <qstring.h>
-#include <qstringlist.h>
-#include <qregexp.h>
+#include <QDir>
+#include <QFile>
+//#include <QRegExp>
+#include <QString>
+#include <QStringList>
#include <stdlib.h>
path += QString( "bin/salome/VERSION" );
QFile vf( path );
- if ( !vf.open( IO_ReadOnly ) )
+ if ( !vf.open( QFile::ReadOnly ) )
return QString::null;
- QString line;
- vf.readLine( line, 1024 );
+ QString line = vf.readLine( 1024 );
vf.close();
if ( line.isEmpty() )
line.remove( line.length() - 1, 1 );
QString ver;
- int idx = line.findRev( ":" );
+ int idx = line.lastIndexOf( ":" );
if ( idx != -1 )
- ver = line.mid( idx + 1 ).stripWhiteSpace();
+ ver = line.mid( idx + 1 ).trimmed();
return ver;
}
SUIT_ResourceMgr* resMgr = 0;
if ( myIniFormat )
{
- resMgr = new SUIT_ResourceMgr( appName );
+ resMgr = new SUIT_ResourceMgr( appName, QString( "%1Config" ) );
resMgr->setCurrentFormat( "ini" );
}
else
if ( !argList.isEmpty() )
{
SUITApp_Session* aSession = new SUITApp_Session( iniFormat );
+ // TODO
+/*
QtxSplash* splash = 0;
- if ( !noSplash ) {
+ if ( !noSplash )
+ {
SUIT_ResourceMgr* resMgr = aSession->createResourceMgr( argList.first() );
- if ( resMgr ) {
- resMgr->loadLanguage();
- QString splashIcon, splashInfo, splashTextColors;
- resMgr->value( "splash", "image", splashIcon );
- resMgr->value( "splash", "info", splashInfo, false );
- resMgr->value( "splash", "text_colors", splashTextColors );
- QString appName = QObject::tr( "APP_NAME" ).stripWhiteSpace();
- QString appVersion = QObject::tr( "APP_VERSION" ).stripWhiteSpace();
- if ( appVersion == "APP_VERSION" ) {
- if ( appName == "APP_NAME" || appName.lower() == "salome" )
- appVersion = salomeVersion();
- else
- appVersion = "";
- }
- QPixmap px( splashIcon );
- if ( !px.isNull() ) {
- splash = QtxSplash::splash( px );
- if ( !splashTextColors.isEmpty() ) {
- QStringList colors = QStringList::split( "|", splashTextColors );
- QColor c1, c2;
- if ( colors.count() > 0 ) c1 = QColor( colors[0] );
- if ( colors.count() > 1 ) c2 = QColor( colors[1] );
- splash->setTextColors( c1, c2 );
- }
- else {
- splash->setTextColors( Qt::white, Qt::black );
- }
+ if ( resMgr )
+ {
+ resMgr->loadLanguage();
+ QString splashIcon, splashInfo, splashTextColors;
+ resMgr->value( "splash", "image", splashIcon );
+ resMgr->value( "splash", "info", splashInfo, false );
+ resMgr->value( "splash", "text_colors", splashTextColors );
+ QString appName = QObject::tr( "APP_NAME" ).stripWhiteSpace();
+ QString appVersion = QObject::tr( "APP_VERSION" ).stripWhiteSpace();
+ if ( appVersion == "APP_VERSION" )
+ {
+ if ( appName == "APP_NAME" || appName.toLower() == "salome" )
+ appVersion = salomeVersion();
+ else
+ appVersion = "";
+ }
+ QPixmap px( splashIcon );
+ if ( !px.isNull() )
+ {
+ splash = QtxSplash::splash( px );
+ if ( !splashTextColors.isEmpty() )
+ {
+ QStringList colors = QStringList::split( "|", splashTextColors );
+ QColor c1, c2;
+ if ( colors.count() > 0 )
+ c1 = QColor( colors[0] );
+ if ( colors.count() > 1 )
+ c2 = QColor( colors[1] );
+ splash->setTextColors( c1, c2 );
+ }
+ else
+ {
+ splash->setTextColors( Qt::white, Qt::black );
+ }
#ifdef _DEBUG_
- splash->setHideOnClick( true );
+ splash->setHideOnClick( true );
#endif
- QFont f = splash->font();
- f.setBold( true );
- splash->setFont( f );
- if ( !splashInfo.isEmpty() ) {
- splashInfo.replace( QRegExp( "%A" ), appName );
- splashInfo.replace( QRegExp( "%V" ), QObject::tr( "ABOUT_VERSION" ).arg( appVersion ) );
- splashInfo.replace( QRegExp( "%L" ), QObject::tr( "ABOUT_LICENSE" ) );
- splashInfo.replace( QRegExp( "%C" ), QObject::tr( "ABOUT_COPYRIGHT" ) );
- splashInfo.replace( QRegExp( "\\\\n" ), "\n" );
- splash->message( splashInfo );
- }
- splash->show();
- qApp->processEvents();
- }
+ QFont f = splash->font();
+ f.setBold( true );
+ splash->setFont( f );
+ if ( !splashInfo.isEmpty() )
+ {
+ splashInfo.replace( QRegExp( "%A" ), appName );
+ splashInfo.replace( QRegExp( "%V" ), QObject::tr( "ABOUT_VERSION" ).arg( appVersion ) );
+ splashInfo.replace( QRegExp( "%L" ), QObject::tr( "ABOUT_LICENSE" ) );
+ splashInfo.replace( QRegExp( "%C" ), QObject::tr( "ABOUT_COPYRIGHT" ) );
+ splashInfo.replace( QRegExp( "\\\\n" ), "\n" );
+ splash->message( splashInfo );
+ }
+ splash->show();
+ QApplication::instance()->processEvents();
+ }
}
}
+*/
SUIT_Application* theApp = aSession->startApplication( argList.first() );
if ( theApp )
{
if ( !noExceptHandling )
app.setHandler( aSession->handler() );
-// if ( !app.mainWidget() )
-// app.setMainWidget( theApp->desktop() );
- if ( splash )
- splash->finish( theApp->desktop() );
+// TODO
+// if ( splash )
+// splash->finish( theApp->desktop() );
result = app.exec();
- if ( splash )
- delete splash;
+// TODO
+// delete splash;
}
delete aSession;
}
--- /dev/null
+TEMPLATE = app
+TARGET = SUITApp
+DESTDIR = ../../bin
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+INCLUDEPATH += ../../include ../Qtx ../SUIT
+LIBS += -L../../lib -lqtx -lsuit
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+
+HEADERS = SUITApp_Application.h
+
+SOURCES = SUITApp.cxx
+SOURCES += SUITApp_Application.cxx
//
#include "SUITApp_Application.h"
-#include "SUIT_Session.h"
-#include "SUIT_MessageBox.h"
-#include "SUIT_ExceptionHandler.h"
+#include <SUIT_Tools.h>
+#include <SUIT_ExceptionHandler.h>
-#include <qdir.h>
-#include <qfileinfo.h>
+#include <QDir>
+#include <QTranslator>
#ifdef WIN32
#include <windows.h>
: QApplication( argc, argv ),
myExceptHandler( hand )
{
- QString path = QFileInfo( argv[0] ).dirPath() + QDir::separator() + "../../resources";
+ QString path = SUIT_Tools::dir( argv[0] ) + QDir::separator() + "../../resources";
path = QDir::convertSeparators( QDir( path ).canonicalPath() );
QTranslator* strTbl = new QTranslator( 0 );
*/
bool SUITApp_Application::notify( QObject* receiver, QEvent* e )
{
-#if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) < 0x060101
- // Disable GUI user actions while python command is executed
- if (SUIT_Session::IsPythonExecuted()) {
- // Disable mouse and keyboard events
- QEvent::Type aType = e->type();
- if (aType == QEvent::MouseButtonPress || aType == QEvent::MouseButtonRelease ||
- aType == QEvent::MouseButtonDblClick || aType == QEvent::MouseMove ||
- aType == QEvent::Wheel || aType == QEvent::ContextMenu ||
- aType == QEvent::KeyPress || aType == QEvent::KeyRelease ||
- aType == QEvent::Accel || aType == QEvent::AccelOverride)
- return false;
- }
-#endif
-
return myExceptHandler ? myExceptHandler->handle( receiver, e ) :
QApplication::notify( receiver, e );
}
#ifndef SUITAPP_APPLICATION_H
#define SUITAPP_APPLICATION_H
-#include <qapplication.h>
+#include <QApplication>
class SUIT_ExceptionHandler;
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>APP_OK</source>
+ <translation>Ok</translation>
+ </message>
+ <message>
+ <source>APP_ERROR</source>
+ <translation>Error</translation>
+ </message>
+ <message>
+ <source>APP_UNK_EXCEPTION</source>
+ <translation>Unknown exception</translation>
+ </message>
+</context>
+</TS>
#include "SUPERVGraph.h"
#include "SUPERVGraph_ViewFrame.h"
+#include "SUIT_Desktop.h"
+#include "SUIT_ViewWindow.h"
+
using namespace std;
/*!
*/
SUIT_ViewWindow* SUPERVGraph::createView(SUIT_Desktop* parent)
{
- return new SUPERVGraph_ViewFrame( parent/*, "vtkView"*/ );
+ return new SUPERVGraph_ViewFrame( parent );
}
extern "C"
#ifndef SUPERVGraph_HeaderFile
#define SUPERVGraph_HeaderFile
-#include "SUIT_Desktop.h"
-#include "SUIT_ViewWindow.h"
-
-#ifdef WNT
+#ifdef WIN32
#ifdef SUPERVGRAPH_EXPORTS
#define SUPERVGRAPH_EXPORT __declspec(dllexport)
#else
#define SUPERVGRAPH_EXPORT
#endif
-#if defined WNT
+#if defined WIN32
#pragma warning ( disable: 4251 )
#endif
+#include <QObject>
+
+class SUIT_Desktop;
+class SUIT_ViewWindow;
+
class SUPERVGRAPH_EXPORT SUPERVGraph : public QObject
{
Q_OBJECT
public :
- /*Standard_EXPORT*/ static SUIT_ViewWindow* createView ( SUIT_Desktop* parent);
+ static SUIT_ViewWindow* createView ( SUIT_Desktop* parent);
};
--- /dev/null
+TEMPLATE = lib
+TARGET = SUPERVGraph
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+QT_INCLUDES = $$(QTDIR)/include $$(QTDIR)/include/QtCore $$(QTDIR)/include/QtGui $$(QTDIR)/include/QtOpenGL $$(QTDIR)/include/QtXml
+
+CASROOT = $$(CASROOT)
+CAS_CPPFLAGS = $${CASROOT}/inc
+
+PYTHON_INCLUDES = $$(PYTHONHOME)/include/python2.4
+
+BOOST_CPPFLAGS = $$(BOOSTDIR)/include
+
+QT_MT_LIBS = -L$$(QTDIR)/lib -lQtCore -lQtXml -lQtGui -lQtOpenGL
+
+INCLUDEPATH += $${QT_INCLUDES} $${CAS_CPPFLAGS} $${PYTHON_INCLUDES} $${BOOST_CPPFLAGS} ../Qtx ../SUIT ../OBJECT
+
+LIBS += $${QT_MT_LIBS} -L../../lib -lsuit
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += SUPERVGRAPH_EXPORTS OCC_VERSION_MAJOR=6 OCC_VERSION_MINOR=1 OCC_VERSION_MAINTENANCE=1 LIN LINTEL CSFDB No_exception HAVE_CONFIG_H HAVE_LIMITS_H HAVE_WOK_CONFIG_H OCC_CONVERT_SIGNALS
+
+HEADERS = SUPERVGraph_ViewFrame.h
+HEADERS += SUPERVGraph_ViewManager.h
+HEADERS += SUPERVGraph_ViewModel.h
+HEADERS += SUPERVGraph.h
+
+SOURCES = SUPERVGraph.cxx
+SOURCES += SUPERVGraph_ViewFrame.cxx
+SOURCES += SUPERVGraph_ViewManager.cxx
+SOURCES += SUPERVGraph_ViewModel.cxx
+
+TRANSLATIONS = resources/SUPERVGraph_images.ts \
+ resources/SUPERVGraph_msg_en.ts
+
+ICONS = resources/*.png
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+resources.files = $$ICONS resources/*.qm
+resources.path = ../../resources
+
+INSTALLS += includes resources
#include <SUIT_Session.h>
//QT Include
-#include <qlayout.h>
-#include <qcolordialog.h>
+#include <QVBoxLayout>
+#include <QToolBar>
using namespace std;
/*!
Builds popup for SUPERVGraph viewer
*/
-void SUPERVGraph_View::contextMenuPopup( QPopupMenu* )
+void SUPERVGraph_View::contextMenuPopup( QMenu* )
{
// to be implemented
}
setBackgroundColor(QColor(R,G,B));*/
myToolBar = new QToolBar(this);
- myToolBar->setCloseMode(QDockWindow::Undocked);
- myToolBar->setLabel(tr("LBL_TOOLBAR_LABEL"));
+ //myToolBar->setCloseMode(QDockWindow::Undocked);
+ myToolBar->setWindowTitle(tr("LBL_TOOLBAR_LABEL"));
createActions();
createToolBar();
}
{
if (!myActionsMap.isEmpty()) return;
SUIT_ResourceMgr* aResMgr = SUIT_Session::session()->resourceMgr();
- QAction* aAction;
+ QtxAction* aAction;
// Panning
- aAction = new QAction(tr("MNU_PAN_VIEW"), aResMgr->loadPixmap( "SUPERVGraph", tr( "ICON_SUPERVGraph_PAN" ) ),
- tr( "MNU_PAN_VIEW" ), 0, this);
+ aAction = new QtxAction(tr("MNU_PAN_VIEW"), aResMgr->loadPixmap( "SUPERVGraph", tr( "ICON_SUPERVGraph_PAN" ) ),
+ tr( "MNU_PAN_VIEW" ), 0, this);
aAction->setStatusTip(tr("DSC_PAN_VIEW"));
connect(aAction, SIGNAL(activated()), this, SLOT(onViewPan()));
myActionsMap[ PanId ] = aAction;
// Reset
- aAction = new QAction(tr("MNU_RESET_VIEW"), aResMgr->loadPixmap( "SUPERVGraph", tr( "ICON_SUPERVGraph_RESET" ) ),
- tr( "MNU_RESET_VIEW" ), 0, this);
+ aAction = new QtxAction(tr("MNU_RESET_VIEW"), aResMgr->loadPixmap( "SUPERVGraph", tr( "ICON_SUPERVGraph_RESET" ) ),
+ tr( "MNU_RESET_VIEW" ), 0, this);
aAction->setStatusTip(tr("DSC_RESET_VIEW"));
connect(aAction, SIGNAL(activated()), this, SLOT(onViewReset()));
myActionsMap[ ResetId ] = aAction;
*/
void SUPERVGraph_ViewFrame::setBackgroundColor( const QColor& color )
{
- if (myView)
- myView->setPaletteBackgroundColor(color);
+ if (myView) {
+ QPalette palette;
+ palette.setColor(myView->backgroundRole(), color);
+ myView->setPalette(palette);
+ }
}
/*!
QColor SUPERVGraph_ViewFrame::backgroundColor() const
{
if (myView)
- return myView->paletteBackgroundColor();
- return QMainWindow::backgroundColor();
+ return myView->palette().color( myView->backgroundRole() );
+ return palette().color( backgroundRole() );
}
/*!
#include "SUIT_PopupClient.h"
#include "SUIT_ViewWindow.h"
-#include <qaction.h>
+#include <QtxAction.h>
#ifdef WIN32
#pragma warning ( disable:4251 )
/* redefine functions from SUIT_PopupClient */
virtual QString popupClientType() const { return Type(); }
- virtual void contextMenuPopup( QPopupMenu* );
+ virtual void contextMenuPopup( QMenu* );
virtual void resizeView( QResizeEvent* theEvent ) {};
//! Actions ID
enum { PanId, ResetId };
- typedef QMap<int, QAction*> ActionsMap;
+ typedef QMap<int, QtxAction*> ActionsMap;
ActionsMap myActionsMap;
QToolBar* myToolBar;
//
#include "SUPERVGraph_ViewManager.h"
+#include "SUIT_ViewWindow.h"
+
int SUPERVGraph_ViewManager::myMaxId = 0;
/*!
*/
void SUPERVGraph_ViewManager::setViewName(SUIT_ViewWindow* theView)
{
- int aPos = myViews.find(theView);
- theView->setCaption( QString( "SUPERVISION scene:%1 - viewer:%2" ).arg( myId ).arg(aPos+1));
+ int aPos = myViews.indexOf(theView);
+ theView->setWindowTitle( QString( "SUPERVISION scene:%1 - viewer:%2" ).arg( myId ).arg(aPos+1));
}
/*!
Fills popup menu with custom actions
\param popup - popup menu to be filled with
*/
-void SUPERVGraph_ViewManager::contextMenuPopup( QPopupMenu* thePopup)
+void SUPERVGraph_ViewManager::contextMenuPopup( QMenu* thePopup)
{
SUIT_ViewManager::contextMenuPopup( thePopup );
// to be implemented
#include "SUPERVGraph.h"
-#include "SUPERVGraph_ViewModel.h"
#include "SUIT_ViewManager.h"
class SUIT_Desktop;
SUPERVGraph_ViewManager( SUIT_Study* theStudy, SUIT_Desktop* theDesktop, SUIT_ViewModel* theViewModel = 0 );
~SUPERVGraph_ViewManager();
- virtual void contextMenuPopup( QPopupMenu* thePopup );
+ virtual void contextMenuPopup( QMenu* thePopup );
protected:
void setViewName(SUIT_ViewWindow* theView);
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>ICON_SUPERVGraph_PAN</source>
+ <translation>view_pan.png</translation>
+ </message>
+ <message>
+ <source>ICON_SUPERVGraph_RESET</source>
+ <translation>view_reset.png</translation>
+ </message>
+</context>
+</TS>
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>MNU_PAN_VIEW</source>
+ <translation>Panning</translation>
+ </message>
+ <message>
+ <source>DSC_PAN_VIEW</source>
+ <translation>Panning the view</translation>
+ </message>
+ <message>
+ <source>MNU_RESET_VIEW</source>
+ <translation>Reset</translation>
+ </message>
+ <message>
+ <source>DSC_RESET_VIEW</source>
+ <translation>Reset View Point</translation>
+ </message>
+ <message>
+ <source>LBL_TOOLBAR_LABEL</source>
+ <translation>View Operations</translation>
+ </message>
+</context>
+</TS>
$(QT_INCLUDES) \
$(CAS_CPPFLAGS) \
$(VTK_INCLUDES) \
- $(QWT_INCLUDES) \
$(BOOST_CPPFLAGS) \
- -I$(srcdir)/../Qtx -I$(srcdir)/../SUIT -I$(srcdir)/../STD \
- -I$(srcdir)/../CAM -I$(srcdir)/../OBJECT -I$(srcdir)/../Prs \
+ -I$(srcdir)/../Qtx -I$(srcdir)/../SUIT -I$(srcdir)/../OBJECT -I$(srcdir)/../Prs \
-I$(srcdir)/../VTKViewer
libSVTK_la_LDFLAGS= \
$(QT_MT_LIBS) \
$(OCC_LIBS) \
- $(QWT_LIBS) \
$(VTK_LIBS)
-libSVTK_la_LIBADD= ../Qtx/libqtx.la ../SUIT/libsuit.la ../STD/libstd.la \
- ../CAM/libCAM.la ../OBJECT/libSalomeObject.la \
+libSVTK_la_LIBADD= ../Qtx/libqtx.la ../SUIT/libsuit.la ../OBJECT/libSalomeObject.la \
../Prs/libSalomePrs.la ../VTKViewer/libVTKViewer.la
# Executable
#include "SALOME_Actor.h"
+#include "SALOME_InteractiveObject.hxx"
#include "VTKViewer_Transform.h"
#include "VTKViewer_TransformFilter.h"
#include "SVTK_Selector.h"
#include "SVTK.h"
-#include "SALOME_InteractiveObject.hxx"
+class Handle(SALOME_InteractiveObject);
// undefining min and max because CASCADE's defines them and
// it clashes with std::min(), std::max()
#include "VTKViewer.h"
-#ifdef WNT
+#ifdef WIN32
# ifdef SVTK_EXPORTS
# define SVTK_EXPORT __declspec(dllexport)
# else
# define SVTK_EXPORT
#endif
-#if defined WNT
+#if defined WIN32
#pragma warning ( disable: 4251 )
#pragma warning ( disable: 4786 )
#endif
--- /dev/null
+TEMPLATE = lib
+TARGET = SVTK
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+VTKHOME = $$(VTKHOME)
+VTK_INCLUDES = $${VTKHOME}/include/vtk
+
+VTK_LIBS = -L$${VTKHOME}/lib/vtk -L$${VTKHOME}/lib/vtk/python -lvtkCommon -lvtkGraphics -lvtkImaging -lvtkFiltering -lvtkIO -lvtkRendering -lvtkHybrid -lvtkParallel -lvtkWidgets -lGL -L/usr/X11R6/lib -lGLU -L/usr/X11R6/lib -lX11 -lXt
+
+CASROOT = $$(CASROOT)
+CAS_CPPFLAGS = $${CASROOT}/inc
+
+BOOST_CPPFLAGS = $$(BOOSTDIR)/include
+
+OCC_LIBS =
+
+INCLUDEPATH += ../../include $${CAS_CPPFLAGS} $${VTK_INCLUDES} $${BOOST_CPPFLAGS} ../Qtx ../SUIT ../OBJECT ../Prs ../VTKViewer
+LIBS += -L../../lib -lqtx -lsuit -lSalomeObject -lSalomePrs -lVTKViewer $${OCC_LIBS} $${VTK_LIBS}
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += SVTK_EXPORTS OCC_VERSION_MAJOR=6 OCC_VERSION_MINOR=1 OCC_VERSION_MAINTENANCE=1 LIN LINTEL CSFDB No_exception HAVE_CONFIG_H HAVE_LIMITS_H HAVE_WOK_CONFIG_H OCC_CONVERT_SIGNALS
+
+HEADERS = SVTK.h
+HEADERS += SVTK_Prs.h
+HEADERS += SVTK_Actor.h
+HEADERS += SALOME_Actor.h
+HEADERS += SVTK_RectPicker.h
+HEADERS += SVTK_DeviceActor.h
+HEADERS += SVTK_DialogBase.h
+HEADERS += SVTK_FontWidget.h
+HEADERS += SVTK_CubeAxesActor2D.h
+HEADERS += SVTK_Functor.h
+HEADERS += SVTK_MainWindow.h
+HEADERS += SVTK_View.h
+HEADERS += SVTK_ViewManager.h
+HEADERS += SVTK_ViewModel.h
+HEADERS += SVTK_ViewWindow.h
+HEADERS += SVTK_Renderer.h
+HEADERS += SVTK_InteractorStyle.h
+HEADERS += SVTK_RenderWindowInteractor.h
+HEADERS += SVTK_GenericRenderWindowInteractor.h
+HEADERS += SVTK_Selector.h
+HEADERS += SVTK_Selection.h
+HEADERS += SVTK_SelectionEvent.h
+HEADERS += SVTK_SpaceMouse.h
+HEADERS += SVTK_Event.h
+HEADERS += SVTK_ViewModelBase.h
+HEADERS += SVTK_SetRotationPointDlg.h
+HEADERS += SVTK_Extension.h
+
+SOURCES = SVTK_Prs.cxx
+SOURCES += SVTK_Actor.cxx
+SOURCES += SALOME_Actor.cxx
+SOURCES += SVTK_RectPicker.cxx
+SOURCES += SVTK_DeviceActor.cxx
+SOURCES += SVTK_CubeAxesActor2D.cxx
+SOURCES += SVTK_NonIsometricDlg.cxx
+SOURCES += SVTK_UpdateRateDlg.cxx
+SOURCES += SVTK_CubeAxesDlg.cxx
+SOURCES += SVTK_DialogBase.cxx
+SOURCES += SVTK_FontWidget.cxx
+SOURCES += SVTK_Trihedron.cxx
+SOURCES += SVTK_MainWindow.cxx
+SOURCES += SVTK_View.cxx
+SOURCES += SVTK_ViewManager.cxx
+SOURCES += SVTK_ViewModel.cxx
+SOURCES += SVTK_Renderer.cxx
+SOURCES += SVTK_ViewWindow.cxx
+SOURCES += SVTK_InteractorStyle.cxx
+SOURCES += SVTK_RenderWindowInteractor.cxx
+SOURCES += SVTK_GenericRenderWindowInteractor.cxx
+SOURCES += SVTK_SpaceMouse.cxx
+SOURCES += SVTK_Selector.cxx
+SOURCES += SVTK_SetRotationPointDlg.cxx
+SOURCES += SVTK_Extension.cxx
+
+TRANSLATIONS = resources/SVTK_images.ts \
+ resources/SVTK_msg_en.ts
+
+ICONS = resources/*.png
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+resources.files = $$ICONS resources/*.qm
+resources.path = ../../resources
+
+INSTALLS += includes resources
#include "SVTK_Actor.h"
#include "SALOME_Actor.h"
+#include "SALOME_InteractiveObject.hxx"
+
// VTK Includes
#include <vtkObjectFactory.h>
#include <vtkUnstructuredGrid.h>
for (int i=0; i<4; i++){
tmp = aArray1[i]; aArray1[i] = aArray2[i]; aArray2[i] = tmp;
}
-#ifndef WNT
+#ifndef WIN32
for(int i=0;i<2; i++){
#else
for(i=0;i<2; i++){
// XCoords coordinates for X grid
vtkFloatArray *XCoords = vtkFloatArray::New();
-#ifndef WNT
+#ifndef WIN32
for(int i=0;i<numOfLabelsX;i++){
#else
for(i=0;i<numOfLabelsX;i++){
}
// YCoords coordinates for Y grid
vtkFloatArray *YCoords = vtkFloatArray::New();
-#ifndef WNT
+#ifndef WIN32
for(int i=0;i<numOfLabelsX;i++){
#else
for(i=0;i<numOfLabelsX;i++){
}
// ZCoords coordinates for Z grid
vtkFloatArray *ZCoords = vtkFloatArray::New();
-#ifndef WNT
+#ifndef WIN32
for(int i=0;i<numOfLabelsZ;i++){
#else
for(i=0;i<numOfLabelsZ;i++){
p[5][1] = YCoords->GetValue(numOfLabelsY-1);
p[5][2] = aMiddleZ;
-#ifndef WNT
+#ifndef WIN32
for(int i=0;i<3;i++)
#else
for(i=0;i<3;i++)
#pragma warning ( disable:4251 )
#endif
-#ifndef WNT
+#ifndef WIN32
class VTK_HYBRID_EXPORT SVTK_CubeAxesActor2D : public vtkCubeAxesActor2D
#else
class SVTK_EXPORT SVTK_CubeAxesActor2D : public vtkCubeAxesActor2D
#include "QtxAction.h"
#include "QtxIntSpinBox.h"
-#include <qlayout.h>
-#include <qframe.h>
-#include <qpushbutton.h>
-#include <qtabwidget.h>
-#include <qcheckbox.h>
-#include <qgroupbox.h>
-#include <qlineedit.h>
-#include <qlabel.h>
-#include <qobjectlist.h>
-#include <qvalidator.h>
+#include <QHBoxLayout>
+#include <QVBoxLayout>
+#include <QPushButton>
+#include <QTabWidget>
+#include <QCheckBox>
+#include <QGroupBox>
+#include <QLineEdit>
+#include <QLabel>
#include <vtkAxisActor2D.h>
#include <vtkTextProperty.h>
SVTK_AxisWidget::SVTK_AxisWidget (QWidget* theParent)
: QFrame(theParent)
{
- QValueList< QLabel* > aLabels;
+ QList< QLabel* > aLabels;
// "Name" grp
- myNameGrp = new QGroupBox(3, Qt::Vertical, tr("AXIS_NAME"), this);
+ myNameGrp = new QGroupBox(tr("AXIS_NAME"), this);
+ QVBoxLayout* aVBox = new QVBoxLayout;
+
myIsNameVisible = new QCheckBox(tr("IS_VISIBLE"), myNameGrp);
+ aVBox->addWidget(myIsNameVisible);
- QHBox* aHBox = new QHBox(myNameGrp);
+ QHBoxLayout* aHBox = new QHBoxLayout(myNameGrp);
aHBox->setSpacing(5);
- QLabel* aLabel = new QLabel(tr("NAME"), aHBox);
- myAxisName = new QLineEdit(aHBox);
+ QLabel* aLabel = new QLabel(tr("NAME"));
+ aHBox->addWidget(aLabel);
+ myAxisName = new QLineEdit;
+ aHBox->addWidget(myAxisName);
aLabels.append(aLabel);
+ aVBox->addLayout(aHBox);
- aHBox = new QHBox(myNameGrp);
+ aHBox = new QHBoxLayout(myNameGrp);
aHBox->setSpacing(5);
- aLabel = new QLabel(tr("FONT"), aHBox);
- myNameFont = new SVTK_FontWidget(aHBox);
+ aLabel = new QLabel(tr("FONT"));
+ aHBox->addWidget(aLabel);
+ myNameFont = new SVTK_FontWidget(myNameGrp);
+ aHBox->addWidget(myNameFont);
aLabels.append(aLabel);
+ aVBox->addLayout(aHBox);
+ myNameGrp->setLayout(aVBox);
// "Labels" grp
- myLabelsGrp = new QGroupBox(4, Qt::Vertical, tr("LABELS"), this);
+ myLabelsGrp = new QGroupBox(tr("LABELS"), this);
+ aVBox = new QVBoxLayout;
+
myIsLabelsVisible = new QCheckBox(tr("IS_VISIBLE"), myLabelsGrp);
+ aVBox->addWidget(myIsLabelsVisible);
- aHBox = new QHBox(myLabelsGrp);
+ aHBox = new QHBoxLayout(myLabelsGrp);
aHBox->setSpacing(5);
- aLabel = new QLabel(tr("NUMBER"), aHBox);
- myLabelNumber = new QtxIntSpinBox(0,25,1,aHBox,"SpinBoxLabelNumber");
+ aLabel = new QLabel(tr("NUMBER"));
+ aHBox->addWidget(aLabel);
+ myLabelNumber = new QtxIntSpinBox(0,25,1,myLabelsGrp);
+ myLabelNumber->setObjectName("SpinBoxLabelNumber");
+ aHBox->addWidget(myLabelNumber);
aLabels.append(aLabel);
+ aVBox->addLayout(aHBox);
- aHBox = new QHBox(myLabelsGrp);
+ aHBox = new QHBoxLayout(myLabelsGrp);
aHBox->setSpacing(5);
- aLabel = new QLabel(tr("OFFSET"), aHBox);
- myLabelOffset = new QtxIntSpinBox(0,100,1,aHBox,"SpinBoxLabellOffset");
+ aLabel = new QLabel(tr("OFFSET"));
+ aHBox->addWidget(aLabel);
+ myLabelOffset = new QtxIntSpinBox(0,100,1,myLabelsGrp);
+ myLabelOffset->setObjectName("SpinBoxLabellOffset");
+ aHBox->addWidget(myLabelOffset);
aLabels.append(aLabel);
+ aVBox->addLayout(aHBox);
- aHBox = new QHBox(myLabelsGrp);
+ aHBox = new QHBoxLayout(myLabelsGrp);
aHBox->setSpacing(5);
- aLabel = new QLabel(tr("FONT"), aHBox);
- myLabelsFont = new SVTK_FontWidget(aHBox);
+ aLabel = new QLabel(tr("FONT"));
+ aHBox->addWidget(aLabel);
+ myLabelsFont = new SVTK_FontWidget(myLabelsGrp);
+ aHBox->addWidget(myLabelsFont);
aLabels.append(aLabel);
+ aVBox->addLayout(aHBox);
+
+ myLabelsGrp->setLayout(aVBox);
// "Tick marks" grp
- myTicksGrp = new QGroupBox(2, Qt::Vertical, tr("TICK_MARKS"), this);
+ myTicksGrp = new QGroupBox(tr("TICK_MARKS"), this);
+ aVBox = new QVBoxLayout;
+
myIsTicksVisible = new QCheckBox(tr("IS_VISIBLE"), myTicksGrp);
+ aVBox->addWidget(myIsTicksVisible);
- aHBox = new QHBox(myTicksGrp);
+ aHBox = new QHBoxLayout(myTicksGrp);
aHBox->setSpacing(5);
- aLabel = new QLabel(tr("LENGTH"), aHBox);
- myTickLength = new QtxIntSpinBox(0,100,1,aHBox,"SpinBoxTickLength");
-
+ aLabel = new QLabel(tr("LENGTH"));
+ aHBox->addWidget(aLabel);
+ myTickLength = new QtxIntSpinBox(0,100,1,myTicksGrp);
+ myTickLength->setObjectName("SpinBoxTickLength");
+ aHBox->addWidget(myTickLength);
aLabels.append(aLabel);
+ aVBox->addLayout(aHBox);
+
+ myTicksGrp->setLayout(aVBox);
// Layout
- QVBoxLayout* aLay = new QVBoxLayout(this, 0, 5);
+ QVBoxLayout* aLay = new QVBoxLayout(this);
+ aLay->setMargin(0);
+ aLay->setSpacing(5);
aLay->addWidget(myNameGrp);
aLay->addWidget(myLabelsGrp);
aLay->addWidget(myTicksGrp);
updateControlState();
// Adjust label widths
- QValueList< QLabel* >::iterator anIter;
+ QList< QLabel* >::iterator anIter;
int aMaxWidth = 0;
for (anIter = aLabels.begin(); anIter != aLabels.end(); anIter++)
- aMaxWidth = QMAX(aMaxWidth, (*anIter)->sizeHint().width());
+ aMaxWidth = qMax(aMaxWidth, (*anIter)->sizeHint().width());
for (anIter = aLabels.begin(); anIter != aLabels.end(); anIter++)
(*anIter)->setFixedWidth(aMaxWidth);
void SVTK_AxisWidget::setEnabled(QGroupBox* theGrp, const bool theState)
{
- QObjectList aChildren(*theGrp->children());
+ QObjectList aChildren(theGrp->children());
QObject* anObj;
- for(anObj = aChildren.first(); anObj !=0; anObj = aChildren.next())
- if (anObj !=0 && anObj->inherits("QHBox"))
- ((QHBox*)anObj)->setEnabled(theState);
+ for(int i = 0; i < aChildren.size(); i++)
+ {
+ anObj = aChildren.at(i);
+ if (anObj !=0 && anObj->inherits("QHBoxLayout"))
+ ((QHBoxLayout*)anObj)->setEnabled(theState);
+ }
}
void SVTK_AxisWidget::onLabelsChecked()
// Name
theActor->SetTitleVisibility(myIsNameVisible->isChecked() ? 1 : 0);
- theActor->SetTitle(myAxisName->text().latin1());
+ theActor->SetTitle(myAxisName->text().toLatin1());
QColor aTitleColor(255, 255, 255);
int aTitleFontFamily = VTK_ARIAL;
theName),
myMainWindow(theParent)
{
- setCaption(tr("CAPTION"));
+ setWindowTitle(tr("CAPTION"));
- QVBoxLayout* aLay = new QVBoxLayout(this, 5, 5);
+ QVBoxLayout* aLay = new QVBoxLayout(this);
+ aLay->setMargin(5);
+ aLay->setSpacing(5);
aLay->addWidget(createMainFrame(this));
aLay->addWidget(createButtonFrame(this));
myTabWg->addTab(myAxes[ 1 ], tr("Y_AXIS"));
myTabWg->addTab(myAxes[ 2 ], tr("Z_AXIS"));
- myTabWg->setMargin(5);
+ myTabWg->setContentsMargins(5,5,5,5);
myIsVisible = new QCheckBox(tr("IS_VISIBLE"), aFrame);
- QVBoxLayout* aLay = new QVBoxLayout(aFrame, 0, 5);
+ QVBoxLayout* aLay = new QVBoxLayout(aFrame);
+ aLay->setMargin(0);
+ aLay->setSpacing(5);
aLay->addWidget(myTabWg);
aLay->addWidget(myIsVisible);
QSpacerItem* aSpacer = new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum);
- QHBoxLayout* aLay = new QHBoxLayout(aFrame, 5, 5);
+ QHBoxLayout* aLay = new QHBoxLayout(aFrame);
+ aLay->setMargin(5);
+ aLay->setSpacing(5);
aLay->addWidget(myOkBtn);
aLay->addWidget(myApplyBtn);
#include "SVTK_DialogBase.h"
-#include <qframe.h>
+#include <QFrame>
class QWidget;
-class QFrame;
class QPushButton;
class QTabWidget;
class QCheckBox;
QWidget* theParent,
const char* theName,
bool theModal,
- WFlags theWFalgs):
+ Qt::WindowFlags theWFalgs):
QDialog(theParent,
- theName,
- theModal,
- theWFalgs | WStyle_Customize | WStyle_NormalBorder | WStyle_Title | WStyle_SysMenu),
+ theWFalgs | Qt::WindowTitleHint | Qt::WindowSystemMenuHint),
myAction(theAction)
{
+ setObjectName(theName);
+ setModal(theModal);
+
connect(theParent, SIGNAL(Show( QShowEvent * )), this, SLOT(onParentShow()));
connect(theParent, SIGNAL(Hide( QHideEvent * )), this, SLOT(onParentHide()));
}
SVTK_DialogBase
::onParentShow()
{
- if(myAction->isOn())
+ if(myAction->isChecked())
show();
else
hide();
SVTK_DialogBase
::done( int r )
{
- myAction->setOn( false );
+ myAction->setChecked( false );
QDialog::done( r );
}
#include "SVTK.h"
-#include <qdialog.h>
+#include <QDialog>
class QtxAction;
QWidget* theParent,
const char* theName = "",
bool theModal = FALSE,
- WFlags theWFalgs = 0);
+ Qt::WindowFlags theWFalgs = 0);
~SVTK_DialogBase();
#include "SVTK_FontWidget.h"
-#include <qtoolbutton.h>
-#include <qcombobox.h>
-#include <qcolordialog.h>
-#include <qcheckbox.h>
+#include <QToolButton>
+#include <QComboBox>
+#include <QColorDialog>
+#include <QCheckBox>
+#include <QHBoxLayout>
#include <vtkTextProperty.h>
Constructor
*/
SVTK_FontWidget::SVTK_FontWidget( QWidget* theParent )
-: QHBox( theParent )
+: QWidget( theParent )
{
- setSpacing( 5 );
myColorBtn = new QToolButton( this );
myColorBtn->setMinimumWidth( 20 );
myFamily = new QComboBox( this );
- myFamily->insertItem( tr( "ARIAL" ) );
- myFamily->insertItem( tr( "COURIER" ) );
- myFamily->insertItem( tr( "TIMES" ) );
+ myFamily->insertItem( myFamily->count(), tr( "ARIAL" ) );
+ myFamily->insertItem( myFamily->count(), tr( "COURIER" ) );
+ myFamily->insertItem( myFamily->count(), tr( "TIMES" ) );
myBold = new QCheckBox( tr( "BOLD" ), this );
myItalic = new QCheckBox( tr( "ITALIC" ), this );
myShadow = new QCheckBox( tr( "SHADOW" ), this );
+ QHBoxLayout* aHBLayout = new QHBoxLayout;
+ aHBLayout->setSpacing( 5 );
+ aHBLayout->addWidget(myColorBtn);
+ aHBLayout->addWidget(myFamily);
+ aHBLayout->addWidget(myBold);
+ aHBLayout->addWidget(myItalic);
+ aHBLayout->addWidget(myShadow);
+ this->setLayout(aHBLayout);
+
connect( myColorBtn, SIGNAL( clicked() ), SLOT( onColor() ) );
}
void SVTK_FontWidget::SetColor( const QColor& theColor )
{
- myColorBtn->setPaletteBackgroundColor( theColor );
+ QPalette palette;
+ palette.setColor(myColorBtn->backgroundRole(), theColor);
+ myColorBtn->setPalette(palette);
}
QColor SVTK_FontWidget::GetColor() const
{
- return myColorBtn->paletteBackgroundColor();
+ return myColorBtn->palette().color( myColorBtn->backgroundRole() );
}
void SVTK_FontWidget::onColor()
SetColor( theColor );
if ( theFamily == VTK_ARIAL )
- myFamily->setCurrentItem( 0 );
+ myFamily->setCurrentIndex( 0 );
else if ( theFamily == VTK_COURIER )
- myFamily->setCurrentItem( 1 );
+ myFamily->setCurrentIndex( 1 );
else
- myFamily->setCurrentItem( 2 );
+ myFamily->setCurrentIndex( 2 );
myBold->setChecked( theBold );
myItalic->setChecked( theItalic );
{
theColor = GetColor();
- int anItem =myFamily->currentItem();
+ int anItem =myFamily->currentIndex();
if ( anItem == 0 )
theFamily = VTK_ARIAL;
else if ( anItem == 1 )
#include "SVTK.h"
-#include <qhbox.h>
+#include <QWidget>
class QToolButton;
class QComboBox;
* Class : SVTK_FontWidget
* Description : Dialog for specifynig font
*/
-class SVTK_EXPORT SVTK_FontWidget : public QHBox
+class SVTK_EXPORT SVTK_FontWidget : public QWidget
{
Q_OBJECT
#include <vtkObjectFactory.h>
#include <vtkCommand.h>
-#include <qtimer.h>
+#include <QTimer>
using namespace std;
// Start a one-shot timer for <DELAY> ms.
//
static int DELAY = 1;
- myTimer->start(DELAY,TRUE);
+ myTimer->setSingleShot(TRUE);
+ myTimer->start(DELAY);
return 1;
}
#include "SVTK.h"
-#include <qobject.h>
+#include <QObject>
#include <vtkGenericRenderWindowInteractor.h>
#include <vtkSmartPointer.h>
class QWidget;
class SVTK_Selector;
-class SVTK_Renderer;
+//class SVTK_Renderer;
#ifdef WIN32
#pragma warning ( disable:4251 )
#include <vtkPerspectiveTransform.h>
#include <vtkMatrix4x4.h>
-#include <qapplication.h>
-#include <qpixmap.h>
-//VRV: porting on Qt 3.0.5
-#if QT_VERSION >= 0x030005
-#include <qpainter.h>
-#endif
-//VRV: porting on Qt 3.0.5
-#include <algorithm>
+#include <QPixmap>
+#include <QWidget>
+#include <QRubberBand>
+#include <algorithm>
#include <iostream>
using namespace std;
myLastPreHighlitedActor(NULL),
myControllerIncrement(SVTK_ControllerIncrement::New()),
myControllerOnKeyDown(SVTK_ControllerOnKeyDown::New()),
- myHighlightRotationPointActor(SVTK_Actor::New())
+ myHighlightRotationPointActor(SVTK_Actor::New()),
+ myRectBand(0)
{
myPicker->Delete();
myPointPicker->Delete();
SVTK_InteractorStyle
::~SVTK_InteractorStyle()
{
+ endDrawRect();
}
/*!
case VTK_INTERACTOR_STYLE_CAMERA_SELECT:
case VTK_INTERACTOR_STYLE_CAMERA_FIT:
{
- QPainter p(GetRenderWidget());
- p.setPen(Qt::lightGray);
- p.setRasterOp(Qt::XorROP);
- p.drawRect(QRect(myPoint, myOtherPoint));
+ drawRect();
break;
}
case VTK_INTERACTOR_STYLE_CAMERA_ZOOM:
case VTK_INTERACTOR_STYLE_CAMERA_SELECT:
case VTK_INTERACTOR_STYLE_CAMERA_FIT:
{
- QPainter aPainter(GetRenderWidget());
- aPainter.setPen(Qt::lightGray);
- aPainter.setRasterOp(Qt::XorROP);
+ endDrawRect();
QRect aRect(myPoint, myOtherPoint);
- aPainter.drawRect(aRect);
- aRect = aRect.normalize();
+ aRect = aRect.normalized();
if (State == VTK_INTERACTOR_STYLE_CAMERA_FIT) {
// making fit rect opeation
}
case VTK_INTERACTOR_STYLE_CAMERA_FIT:
{
- QPainter p(GetRenderWidget());
- p.setPen(Qt::lightGray);
- p.setRasterOp(Qt::XorROP);
- p.drawRect(QRect(myPoint, myOtherPoint));
- myOtherPoint = mousePos;
- p.drawRect(QRect(myPoint, myOtherPoint));
+ drawRect();
break;
}
}
printf( "\n--DominantCombinedSwitch() NOT IMPLEMENTED--\n" );
}
+/*!
+ Draws rectangle by starting and current points
+*/
+void
+SVTK_InteractorStyle
+::drawRect()
+{
+ if ( !myRectBand ) {
+ myRectBand = new QRubberBand( QRubberBand::Rectangle, GetRenderWidget() );
+ QPalette palette;
+ palette.setColor(myRectBand->foregroundRole(), Qt::white);
+ myRectBand->setPalette(palette);
+ }
+ myRectBand->hide();
+
+ QRect aRect(myPoint, myOtherPoint);
+ myRectBand->setGeometry( aRect );
+ myRectBand->setVisible( aRect.isValid() );
+}
+
+/*!
+ \brief Delete rubber band on the end on the dragging operation.
+*/
+void
+SVTK_InteractorStyle
+::endDrawRect()
+{
+ if ( myRectBand ) myRectBand->hide();
+
+ delete myRectBand;
+ myRectBand = 0;
+}
+
/*!
Main process event method (reimplemented from #vtkInteractorStyle)
*/
#include <vtkInteractorStyle.h>
#include <vtkSmartPointer.h>
-#include <qcursor.h>
-#include <qevent.h>
+#include <QCursor>
#include <map>
void operator=(const SVTK_ControllerOnKeyDown&); //Not implemented
};
-class vtkCell;
class vtkPicker;
class vtkPointPicker;
class SVTK_GenericRenderWindowInteractor;
class SVTK_Actor;
+class QRubberBand;
+
#define VTK_INTERACTOR_STYLE_CAMERA_NONE 0
#define VTK_INTERACTOR_STYLE_CAMERA_ROTATE 1
#define VTK_INTERACTOR_STYLE_CAMERA_PAN 2
void DominantCombinedSwitch();
+ void drawRect();
+ void endDrawRect();
+
protected:
QCursor myDefCursor;
QCursor myPanCursor;
vtkFloatingPointType myBBCenter[3];
bool myBBFirstCheck;
+
+ QRubberBand* myRectBand; //!< selection rectangle rubber band
};
#ifdef WIN32
#include "SVTK_Selector.h"
-#include <qimage.h>
+#include <QImage>
+#include <QToolBar>
/*!
Constructor
const char* theName,
SUIT_ResourceMgr* theResourceMgr,
SUIT_ViewWindow* theViewWindow) :
- QMainWindow(theParent,theName,0),
+ QMainWindow(theParent,0),
myViewWindow(theViewWindow)
{
+ setObjectName(theName);
+
myToolBar = new QToolBar(this);
- myToolBar->setCloseMode(QDockWindow::Undocked);
- myToolBar->setLabel(tr("LBL_TOOLBAR_LABEL"));
+ //myToolBar->setCloseMode(QDockWindow::Undocked);
+ myToolBar->setWindowTitle(tr("LBL_TOOLBAR_LABEL"));
createActions(theResourceMgr);
createToolBar();
SetEventDispatcher(myInteractor->GetDevice());
setCentralWidget(myInteractor);
- myInteractor->setBackgroundMode(Qt::NoBackground);
+ myInteractor->setBackgroundRole( QPalette::NoRole );//NoBackground
- myInteractor->setFocusPolicy(StrongFocus);
+ myInteractor->setFocusPolicy(Qt::StrongFocus);
myInteractor->setFocus();
setFocusProxy(myInteractor);
theResourceMgr->loadPixmap( "VTKViewer", tr( "ICON_VTKVIEWER_VIEW_ROTATION_POINT" ) ),
tr( "MNU_CHANGINGROTATIONPOINT_VIEW" ), 0, this);
anAction->setStatusTip(tr("DSC_CHANGINGROTATIONPOINT_VIEW"));
- anAction->setToggleAction(true);
+ anAction->setCheckable(true);
connect(anAction, SIGNAL(toggled(bool)), this, SLOT(onChangeRotationPoint(bool)));
myActionsMap[ ChangeRotationPointId ] = anAction;
theResourceMgr->loadPixmap( "VTKViewer", tr( "ICON_SVTK_SCALING" ) ),
tr( "MNU_SVTK_SCALING" ), 0, this);
anAction->setStatusTip(tr("DSC_SVTK_SCALING"));
- anAction->setToggleAction(true);
+ anAction->setCheckable(true);
connect(anAction, SIGNAL(toggled(bool)), this, SLOT(onNonIsometric(bool)));
myActionsMap[ NonIsometric ] = anAction;
theResourceMgr->loadPixmap( "VTKViewer", tr( "ICON_GRADUATED_AXES" ) ),
tr( "MNU_SVTK_GRADUATED_AXES" ), 0, this);
anAction->setStatusTip(tr("DSC_SVTK_GRADUATED_AXES"));
- anAction->setToggleAction(true);
+ anAction->setCheckable(true);
connect(anAction, SIGNAL(toggled(bool)), this, SLOT(onGraduatedAxes(bool)));
myActionsMap[ GraduatedAxes ] = anAction;
theResourceMgr->loadPixmap( "VTKViewer", tr( "ICON_UPDATE_RATE" ) ),
tr( "MNU_SVTK_UPDATE_RATE" ), 0, this);
anAction->setStatusTip(tr("DSC_SVTK_UPDATE_RATE"));
- anAction->setToggleAction(true);
+ anAction->setCheckable(true);
connect(anAction, SIGNAL(toggled(bool)), this, SLOT(onUpdateRate(bool)));
myActionsMap[ UpdateRate ] = anAction;
}
::dumpView()
{
QPixmap px = QPixmap::grabWindow( GetInteractor()->winId() );
- return px.convertToImage();
+ return px.toImage();
}
#include <vtkSmartPointer.h>
-#include <qmainwindow.h>
+#include <QMainWindow>
+#include <QMap>
class QtxAction;
class SVTK_SetRotationPointDlg;
class VTKViewer_Trihedron;
-class VTKViewer_Transform;
class VTKViewer_Actor;
class SVTK_Renderer;
#include "SVTK_MainWindow.h"
#include "SVTK_Renderer.h"
-#include "QtxDblSpinBox.h"
+#include "QtxDoubleSpinBox.h"
#include "QtxAction.h"
-#include <qgroupbox.h>
-#include <qlabel.h>
-#include <qpushbutton.h>
-#include <qlayout.h>
+#include <QGroupBox>
+#include <QLabel>
+#include <QPushButton>
+#include <QGridLayout>
using namespace std;
theName),
m_MainWindow(theParent)
{
- setCaption(tr("DLG_TITLE"));
+ setWindowTitle(tr("DLG_TITLE"));
setSizeGripEnabled(TRUE);
// Create layout for this dialog
layoutDlg->setMargin(11);
// Create croup box with grid layout
- QGroupBox* aGroupBox = new QGroupBox(this, "GroupBox");
+ QGroupBox* aGroupBox = new QGroupBox(this);
+ aGroupBox->setObjectName("GroupBox");
QHBoxLayout* aHBoxLayout = new QHBoxLayout(aGroupBox);
aHBoxLayout->setMargin(11);
aHBoxLayout->setSpacing(6);
// "X" scaling
- QLabel* TextLabelX = new QLabel (tr("LBL_X"), aGroupBox, "TextLabelX");
+ QLabel* TextLabelX = new QLabel (tr("LBL_X"), aGroupBox);
+ TextLabelX->setObjectName("TextLabelX");
TextLabelX->setFixedWidth(15);
- m_sbXcoeff = new QtxDblSpinBox(-VTK_LARGE_FLOAT, VTK_LARGE_FLOAT, 0.1, aGroupBox);
+ m_sbXcoeff = new QtxDoubleSpinBox(-VTK_LARGE_FLOAT, VTK_LARGE_FLOAT, 0.1, aGroupBox);
m_sbXcoeff->setMinimumWidth(80);
m_sbXcoeff->setValue(1.0);
// "Y" scaling
- QLabel* TextLabelY = new QLabel (tr("LBL_Y"), aGroupBox, "TextLabelY");
+ QLabel* TextLabelY = new QLabel (tr("LBL_Y"), aGroupBox);
+ TextLabelY->setObjectName("TextLabelY");
TextLabelY->setFixedWidth(15);
- m_sbYcoeff = new QtxDblSpinBox(-VTK_LARGE_FLOAT, VTK_LARGE_FLOAT, 0.1, aGroupBox);
+ m_sbYcoeff = new QtxDoubleSpinBox(-VTK_LARGE_FLOAT, VTK_LARGE_FLOAT, 0.1, aGroupBox);
m_sbYcoeff->setMinimumWidth(80);
m_sbYcoeff->setValue(1.0);
// "Z" scaling
- QLabel* TextLabelZ = new QLabel (tr("LBL_Z"), aGroupBox, "TextLabelZ");
+ QLabel* TextLabelZ = new QLabel (tr("LBL_Z"), aGroupBox);
+ TextLabelZ->setObjectName("TextLabelZ");
TextLabelZ->setFixedWidth(15);
- m_sbZcoeff = new QtxDblSpinBox(-VTK_LARGE_FLOAT, VTK_LARGE_FLOAT, 0.1, aGroupBox);
+ m_sbZcoeff = new QtxDoubleSpinBox(-VTK_LARGE_FLOAT, VTK_LARGE_FLOAT, 0.1, aGroupBox);
m_sbZcoeff->setMinimumWidth(80);
m_sbZcoeff->setValue(1.0);
// Create <Reset> button
- m_bReset = new QPushButton(tr("&Reset"), aGroupBox, "m_bReset");
+ m_bReset = new QPushButton(tr("&Reset"), aGroupBox);
+ m_bReset->setObjectName("m_bReset");
// Layout widgets in the group box
aHBoxLayout->addWidget(TextLabelX);
aHBoxLayout2->setMargin(11);
aHBoxLayout2->setSpacing(6);
// Create <OK> button
- QPushButton* m_bOk = new QPushButton(tr("O&K"), aGroupBox2, "m_bOk");
+ QPushButton* m_bOk = new QPushButton(tr("O&K"), aGroupBox2);
+ m_bOk->setObjectName("m_bOk");
m_bOk->setDefault(TRUE);
m_bOk->setAutoDefault(TRUE);
// Create <Apply> button
- QPushButton* m_bApply = new QPushButton(tr("&Apply"), aGroupBox2, "m_bApply");
+ QPushButton* m_bApply = new QPushButton(tr("&Apply"), aGroupBox2);
+ m_bApply->setObjectName("m_bApply");
m_bApply->setAutoDefault(TRUE);
// Create <Cancel> button
- QPushButton* m_bCancel = new QPushButton(tr("&Cancel"), aGroupBox2, "m_bCancel");
+ QPushButton* m_bCancel = new QPushButton(tr("&Cancel"), aGroupBox2);
+ m_bCancel->setObjectName("m_bCancel");
m_bCancel->setAutoDefault(TRUE);
// Layout buttons
class SVTK_MainWindow;
-class QtxDblSpinBox;
+class QtxDoubleSpinBox;
class QtxAction;
class QPushButton;
protected:
SVTK_MainWindow *m_MainWindow;
- QtxDblSpinBox* m_sbXcoeff;
- QtxDblSpinBox* m_sbYcoeff;
- QtxDblSpinBox* m_sbZcoeff;
+ QtxDoubleSpinBox* m_sbXcoeff;
+ QtxDoubleSpinBox* m_sbYcoeff;
+ QtxDoubleSpinBox* m_sbZcoeff;
QPushButton* m_bReset;
protected slots:
// $Header$
#include "SVTK_Prs.h"
+
+#include <vtkActorCollection.h>
+
using namespace std;
/*!
#include <SVTK.h>
#include "SALOME_Prs.h"
-#include <vtkActorCollection.h>
+class vtkActorCollection;
+class vtkActor;
class SVTK_EXPORT SVTK_Prs : public SALOME_VTKPrs
{
// $Header$
#include "SVTK_RenderWindowInteractor.h"
-#include "SVTK_GenericRenderWindowInteractor.h"
+//#include "SVTK_GenericRenderWindowInteractor.h"
#include "SVTK_InteractorStyle.h"
#include "SVTK_Renderer.h"
#include "SVTK_Functor.h"
#include "SALOME_Actor.h"
+// QT Includes
+// Put Qt includes before the X11 includes which #define the symbol None
+// (see SVTK_SpaceMouse.h) to avoid the compilation error.
+#include <QX11Info>
+#include <QMouseEvent>
+
#include "SVTK_SpaceMouse.h"
#include "SVTK_Event.h"
#include <vtkPicker.h>
#include <vtkCamera.h>
-// QT Includes
-#include <qtimer.h>
-#include <qapplication.h>
-#include <qcolordialog.h>
-#include <qpaintdevice.h>
-
using namespace std;
static bool GENERATE_SUIT_EVENTS = false;
QVTK_RenderWindowInteractor
::QVTK_RenderWindowInteractor(QWidget* theParent,
const char* theName):
- QWidget(theParent,theName,Qt::WNoAutoErase),
+ QWidget(theParent),
myRenderWindow(vtkRenderWindow::New())
{
+ setObjectName(theName);
+
setMouseTracking(true);
myRenderWindow->Delete();
myRenderWindow->DoubleBufferOn();
-#ifndef WNT
- myRenderWindow->SetDisplayId((void*)x11Display());
+#ifndef WIN32
+ myRenderWindow->SetDisplayId((void*)QX11Info::display());
#endif
myRenderWindow->SetWindowId((void*)winId());
}
#ifndef WIN32
SVTK_SpaceMouse* aSpaceMouse = SVTK_SpaceMouse::getInstance();
if ( aSpaceMouse && aSpaceMouse->isSpaceMouseOn() )
- aSpaceMouse->close( x11Display() );
+ aSpaceMouse->close( QX11Info::display() );
#endif
}
{
GetDevice()->SetEventInformationFlipY(event->x(),
event->y(),
- event->state() & ControlButton,
- event->state() & ShiftButton);
+ event->modifiers() & Qt::ControlModifier,
+ event->modifiers() & Qt::ShiftModifier);
GetDevice()->MouseMoveEvent();
}
{
GetDevice()->SetEventInformationFlipY(event->x(),
event->y(),
- event->state() & ControlButton,
- event->state() & ShiftButton);
- if( event->button() & LeftButton )
+ event->modifiers() & Qt::ControlModifier,
+ event->modifiers() & Qt::ShiftModifier);
+ if( event->button() & Qt::LeftButton )
GetDevice()->LeftButtonPressEvent();
- else if( event->button() & MidButton )
+ else if( event->button() & Qt::MidButton )
GetDevice()->MiddleButtonPressEvent();
- else if( event->button() & RightButton )
+ else if( event->button() & Qt::RightButton )
GetDevice()->RightButtonPressEvent();
}
{
GetDevice()->SetEventInformationFlipY(event->x(),
event->y(),
- event->state() & ControlButton,
- event->state() & ShiftButton);
+ event->modifiers() & Qt::ControlModifier,
+ event->modifiers() & Qt::ShiftModifier);
- if( event->button() & LeftButton )
+ if( event->button() & Qt::LeftButton )
GetDevice()->LeftButtonReleaseEvent();
- else if( event->button() & MidButton )
+ else if( event->button() & Qt::MidButton )
GetDevice()->MiddleButtonReleaseEvent();
- else if( event->button() & RightButton )
+ else if( event->button() & Qt::RightButton )
GetDevice()->RightButtonReleaseEvent();
}
QVTK_RenderWindowInteractor
::wheelEvent( QWheelEvent* event )
{
- setActiveWindow();
+ activateWindow();
setFocus();
}
QVTK_RenderWindowInteractor
::keyPressEvent( QKeyEvent* event )
{
- GetDevice()->SetKeyEventInformation(event->state() & ControlButton,
- event->state() & ShiftButton,
+ GetDevice()->SetKeyEventInformation(event->modifiers() & Qt::ControlModifier,
+ event->modifiers() & Qt::ShiftModifier,
event->key());
GetDevice()->KeyPressEvent();
GetDevice()->CharEvent();
QVTK_RenderWindowInteractor
::keyReleaseEvent( QKeyEvent * event )
{
- GetDevice()->SetKeyEventInformation(event->state() & ControlButton,
- event->state() & ShiftButton,
+ GetDevice()->SetKeyEventInformation(event->modifiers() & Qt::ControlModifier,
+ event->modifiers() & Qt::ShiftModifier,
event->key());
GetDevice()->KeyReleaseEvent();
}
::enterEvent( QEvent* event )
{
if(FOCUS_UNDER_MOUSE){
- setActiveWindow();
+ activateWindow();
setFocus();
}
GetDevice()->EnterEvent();
{
if ( !aSpaceMouse->isSpaceMouseOn() )
// initialize 3D space mouse driver
- aSpaceMouse->initialize( x11Display(), winId() );
+ aSpaceMouse->initialize( QX11Info::display(), winId() );
else
- aSpaceMouse->setWindow( x11Display(), winId() );
+ aSpaceMouse->setWindow( QX11Info::display(), winId() );
}
#endif
}
// unregister set space mouse events receiver
SVTK_SpaceMouse* aSpaceMouse = SVTK_SpaceMouse::getInstance();
if ( aSpaceMouse && aSpaceMouse->isSpaceMouseOn() )
- aSpaceMouse->setWindow( x11Display(), 0 );
+ aSpaceMouse->setWindow( QX11Info::display(), 0 );
#endif
}
if ( aSpaceMouse->isSpaceMouseOn() && xEvent->type == ClientMessage )
{
SVTK_SpaceMouse::MoveEvent anEvent;
- int type = aSpaceMouse->translateEvent( x11Display(), xEvent, &anEvent, 1.0, 1.0 );
+ int type = aSpaceMouse->translateEvent( QX11Info::display(), xEvent, &anEvent, 1.0, 1.0 );
switch ( type )
{
case SVTK_SpaceMouse::SpaceMouseMove:
SVTK_RenderWindowInteractor
::contextMenuEvent( QContextMenuEvent* event )
{
- if( !( event->state() & KeyButtonMask ) )
+ if( !( event->modifiers() & Qt::KeyboardModifierMask ) )
emit contextMenuRequested( event );
}
#include "SVTK_Selection.h"
#include <vtkSmartPointer.h>
-#include <qwidget.h>
+#include <QWidget>
// undefining min and max because CASCADE's defines them and
// it clashes with std::min(), std::max()
#include "SVTK_SelectorDef.h"
+#include "VTKViewer_Filter.h"
+
#include "SALOME_Actor.h"
#include <TColStd_MapIteratorOfMapOfInteger.hxx>
#include "SVTK.h"
#include "SVTK_Selection.h"
#include "SALOME_ListIO.hxx"
-#include "VTKViewer_Filter.h"
-#include "SALOME_InteractiveObject.hxx"
#include <TColStd_MapOfInteger.hxx>
#include <TColStd_IndexedMapOfInteger.hxx>
#include <vtkObject.h>
+class Handle(VTKViewer_Filter);
+
class SALOME_Actor;
+class Handle(SALOME_InteractiveObject);
//! Define an abstract interface for selection in SVTK package
/*!
#include <TColStd_MapOfInteger.hxx>
#include <vtkSmartPointer.h>
+#include "SALOME_InteractiveObject.hxx"
+
#include "SVTK_Selector.h"
class SALOME_Actor;
#include "QtxAction.h"
-#include <qlineedit.h>
-#include <qgroupbox.h>
-#include <qlabel.h>
-#include <qpushbutton.h>
-#include <qlayout.h>
-#include <qvalidator.h>
-#include <qbuttongroup.h>
-#include <qobjectlist.h>
-#include <qcheckbox.h>
-#include <qhbox.h>
+#include <QLineEdit>
+#include <QGroupBox>
+#include <QLabel>
+#include <QPushButton>
+#include <QGridLayout>
+#include <QDoubleValidator>
+#include <QCheckBox>
#include <vtkCallbackCommand.h>
myEventCallbackCommand(vtkCallbackCommand::New()),
myRWInteractor(theParent->GetInteractor())
{
- setCaption(tr("DLG_TITLE"));
+ setWindowTitle(tr("DLG_TITLE"));
setSizeGripEnabled(TRUE);
// Create layout for this dialog
layoutDlg->setMargin(11);
// Create check box "Use Bounding Box Center"
- QHBox* aCheckBox = new QHBox(this);
+ QHBoxLayout* aCheckBox = new QHBoxLayout(this);
- myIsBBCenter = new QCheckBox(tr("USE_BBCENTER"), aCheckBox);
+ myIsBBCenter = new QCheckBox(tr("USE_BBCENTER"));
myIsBBCenter->setChecked(true);
+ aCheckBox->addWidget(myIsBBCenter);
connect(myIsBBCenter, SIGNAL(stateChanged(int)), SLOT(onBBCenterChecked()));
// Create croup button with radio buttons
- myGroupSelButton = new QButtonGroup(2,Qt::Vertical,"",this);
- myGroupSelButton->setMargin(11);
+ myGroupBoxSel = new QGroupBox( "", this );
+ QVBoxLayout *vbox = new QVBoxLayout;
+ vbox->setMargin(11);
+ vbox->addStretch(1);
// Create "Set to Origin" button
- myToOrigin = new QPushButton(myGroupSelButton);
+ myToOrigin = new QPushButton(myGroupBoxSel);
myToOrigin->setText(tr("LBL_TOORIGIN"));
+ vbox->addWidget(myToOrigin);
connect(myToOrigin, SIGNAL(clicked()), this, SLOT(onToOrigin()));
// Create "Select Point from View" button
- mySelectPoint = new QPushButton(myGroupSelButton);
+ mySelectPoint = new QPushButton(myGroupBoxSel);
mySelectPoint->setText(tr("LBL_SELECTPOINT"));
- mySelectPoint->setToggleButton(true);
+ mySelectPoint->setCheckable(true);
+ vbox->addWidget(mySelectPoint);
connect(mySelectPoint, SIGNAL(clicked()), this, SLOT(onSelectPoint()));
+ myGroupBoxSel->setLayout(vbox);
+
// Create croup box with grid layout
- myGroupBoxCoord = new QGroupBox(this, "GroupBox");
+ myGroupBoxCoord = new QGroupBox(this);
+ myGroupBoxCoord->setObjectName("GroupBox");
QHBoxLayout* aHBoxLayout = new QHBoxLayout(myGroupBoxCoord);
aHBoxLayout->setMargin(11);
aHBoxLayout->setSpacing(6);
// "X" coordinate
- QLabel* TextLabelX = new QLabel (tr("LBL_X"), myGroupBoxCoord, "TextLabelX");
+ QLabel* TextLabelX = new QLabel (tr("LBL_X"), myGroupBoxCoord );
+ TextLabelX->setObjectName("TextLabelX");
TextLabelX->setFixedWidth(15);
myX = new QLineEdit(myGroupBoxCoord);
myX->setValidator(new QDoubleValidator(myX));
connect(myX, SIGNAL(textChanged(const QString&)), this, SLOT(onCoordChanged()));
// "Y" coordinate
- QLabel* TextLabelY = new QLabel (tr("LBL_Y"), myGroupBoxCoord, "TextLabelY");
+ QLabel* TextLabelY = new QLabel (tr("LBL_Y"), myGroupBoxCoord );
+ TextLabelY->setObjectName("TextLabelY");
TextLabelY->setFixedWidth(15);
myY = new QLineEdit(myGroupBoxCoord);
myY->setValidator(new QDoubleValidator(myY));
connect(myY, SIGNAL(textChanged(const QString&)), this, SLOT(onCoordChanged()));
// "Z" coordinate
- QLabel* TextLabelZ = new QLabel (tr("LBL_Z"), myGroupBoxCoord, "TextLabelZ");
+ QLabel* TextLabelZ = new QLabel (tr("LBL_Z"), myGroupBoxCoord );
+ TextLabelZ->setObjectName("TextLabelZ");
TextLabelZ->setFixedWidth(15);
myZ = new QLineEdit(myGroupBoxCoord);
myZ->setValidator(new QDoubleValidator(myZ));
aHBoxLayout2->setMargin(11);
aHBoxLayout2->setSpacing(6);
- QPushButton* m_bClose = new QPushButton(tr("&Close"), aGroupBox, "m_bClose");
+ QPushButton* m_bClose = new QPushButton(tr("&Close"), aGroupBox );
+ m_bClose->setObjectName("m_bClose");
m_bClose->setAutoDefault(TRUE);
m_bClose->setFixedSize(m_bClose->sizeHint());
connect(m_bClose, SIGNAL(clicked()), this, SLOT(onClickClose()));
aHBoxLayout2->addWidget(m_bClose);
// Layout top level widgets
- layoutDlg->addWidget(aCheckBox,0,0);
- layoutDlg->addWidget(myGroupSelButton,1,0);
+ layoutDlg->addLayout(aCheckBox,0,0);
+ layoutDlg->addWidget(myGroupBoxSel,1,0);
layoutDlg->addWidget(myGroupBoxCoord,2,0);
layoutDlg->addWidget(aGroupBox,3,0);
- setEnabled(myGroupSelButton,!myIsBBCenter->isChecked());
+ setEnabled(myGroupBoxSel,!myIsBBCenter->isChecked());
setEnabled(myGroupBoxCoord,!myIsBBCenter->isChecked());
this->resize(400, this->sizeHint().height());
SVTK_SetRotationPointDlg
::setEnabled(QGroupBox* theGrp, const bool theState)
{
- QObjectList aChildren(*theGrp->children());
+ QObjectList aChildren(theGrp->children());
QObject* anObj;
- for(anObj = aChildren.first(); anObj !=0; anObj = aChildren.next())
+ for(int i = 0; i < aChildren.size(); i++)
{
+ anObj = aChildren.at(i);
if (anObj !=0 && anObj->inherits("QLineEdit"))
((QLineEdit*)anObj)->setReadOnly(!theState);
if (anObj !=0 && anObj->inherits("QPushButton"))
SVTK_SetRotationPointDlg
::onBBCenterChecked()
{
- setEnabled(myGroupSelButton,!myIsBBCenter->isChecked());
+ setEnabled(myGroupBoxSel,!myIsBBCenter->isChecked());
setEnabled(myGroupBoxCoord,!myIsBBCenter->isChecked());
if ( myIsBBCenter->isChecked() )
{
- if ( mySelectPoint->state() == QButton::On )
+ if ( mySelectPoint->isChecked() )
mySelectPoint->toggle();
// activate mode : the rotation point is the center of the bounding box
// send the data to the SVTK_InteractorStyle: set the type of the rotation point
SVTK_SetRotationPointDlg
::onToOrigin()
{
- if ( mySelectPoint->state() == QButton::On )
+ if ( mySelectPoint->isChecked() )
mySelectPoint->toggle();
myX->setText(QString::number(0.0));
myY->setText(QString::number(0.0));
SVTK_SetRotationPointDlg
::onSelectPoint()
{
- if ( mySelectPoint->state() == QButton::On )
+ if ( mySelectPoint->isChecked() )
myMainWindow->activateStartPointSelection();
else
mySelectPoint->toggle();
::onCoordChanged()
{
if ( !myIsBBCenter->isChecked() ) {
- if ( mySelectPoint->state() == QButton::On
+ if ( mySelectPoint->isChecked()
&&
( myX->hasFocus() || myY->hasFocus() || myZ->hasFocus() ) )
mySelectPoint->toggle();
class QLineEdit;
class QPushButton;
class QGroupBox;
-class QButtonGroup;
class QCheckBox;
class vtkCallbackCommand;
QCheckBox* myIsBBCenter;
- QButtonGroup* myGroupSelButton;
+ QGroupBox * myGroupBoxSel;
QPushButton* myToOrigin;
QPushButton* mySelectPoint;
#include "VTKViewer_Algorithm.h"
#include "SALOME_Actor.h"
-#include "QtxDblSpinBox.h"
+#include "QtxDoubleSpinBox.h"
#include "QtxAction.h"
#include <sstream>
-#include <qgroupbox.h>
-#include <qlabel.h>
-#include <qpushbutton.h>
-#include <qlayout.h>
-#include <qlineedit.h>
+#include <QGroupBox>
+#include <QLabel>
+#include <QPushButton>
+#include <QGridLayout>
+#include <QLineEdit>
#include <vtkGenericRenderWindowInteractor.h>
#include <vtkCallbackCommand.h>
vtkRenderWindowInteractor* aRWI = myRWInteractor->GetDevice();
bool anIsEnabledUpdateRate = false;
- setCaption(tr("DLG_TITLE"));
- QVBoxLayout* aVBoxLayout = new QVBoxLayout(this, 5, 5);
+ setWindowTitle(tr("DLG_TITLE"));
+ QVBoxLayout* aVBoxLayout = new QVBoxLayout(this);
+ aVBoxLayout->setMargin(5);
+ aVBoxLayout->setSpacing(5);
{
QGroupBox* aGroupBox = new QGroupBox(tr("INPUT_FRAME_TITLE"), this);
- aGroupBox->setColumnLayout(0, Qt::Vertical );
- aGroupBox->layout()->setSpacing( 6 );
- aGroupBox->layout()->setMargin( 11 );
aGroupBox->setCheckable(true);
aGroupBox->setChecked(anIsEnabledUpdateRate);
myIsEnableUpdateRateGroupBox = aGroupBox;
- QGridLayout* aGridLayout = new QGridLayout(aGroupBox->layout());
+ QGridLayout* aGridLayout = new QGridLayout(aGroupBox);
+ aGridLayout->setSpacing( 6 );
+ aGridLayout->setMargin( 11 );
{
QLabel* aLabel = new QLabel(tr("DESIRED"), aGroupBox);
aLabel->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
aGridLayout->addWidget(aLabel, 0, 0);
- QtxDblSpinBox* aDblSpinBox = new QtxDblSpinBox(OFF_UPDATE_RATE, VTK_LARGE_FLOAT, 2, aGroupBox);
+ QtxDoubleSpinBox* aDblSpinBox = new QtxDoubleSpinBox(OFF_UPDATE_RATE, VTK_LARGE_FLOAT, 2, aGroupBox);
aDblSpinBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
aGridLayout->addWidget(aDblSpinBox, 0, 1);
aLabel->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
aGridLayout->addWidget(aLabel, 1, 0);
- QtxDblSpinBox* aDblSpinBox = new QtxDblSpinBox(OFF_UPDATE_RATE, VTK_LARGE_FLOAT, 2, aGroupBox);
+ QtxDoubleSpinBox* aDblSpinBox = new QtxDoubleSpinBox(OFF_UPDATE_RATE, VTK_LARGE_FLOAT, 2, aGroupBox);
aDblSpinBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
aGridLayout->addWidget(aDblSpinBox, 1, 1);
}
{
QGroupBox* aGroupBox = new QGroupBox(tr("INFORMATION_FRAME_TITLE"), this);
- aGroupBox->setColumnLayout(0, Qt::Vertical );
- aGroupBox->layout()->setSpacing( 6 );
- aGroupBox->layout()->setMargin( 11 );
-
- QGridLayout* aGridLayout = new QGridLayout(aGroupBox->layout());
+
+ QGridLayout* aGridLayout = new QGridLayout(aGroupBox);
+ aGridLayout->layout()->setSpacing( 6 );
+ aGridLayout->layout()->setMargin( 11 );
{
QLabel* aLabel = new QLabel(tr("CURRENT_FPS"), aGroupBox);
aLabel->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
class SVTK_MainWindow;
class SVTK_RenderWindowInteractor;
-class QtxDblSpinBox;
+class QtxDoubleSpinBox;
class QtxAction;
class QGroupBox;
protected:
SVTK_RenderWindowInteractor* myRWInteractor;
- QtxDblSpinBox* myDesiredUpdateRateSblSpinBox;
- QtxDblSpinBox* myStillUpdateRateSblSpinBox;
+ QtxDoubleSpinBox* myDesiredUpdateRateSblSpinBox;
+ QtxDoubleSpinBox* myStillUpdateRateSblSpinBox;
QGroupBox* myIsEnableUpdateRateGroupBox;
QLineEdit* myCurrentUpdateRateLineEdit;
using namespace SVTK;
ForEachIf<SALOME_Actor>(getRenderer()->GetActors(),
TIsSameIObject<SALOME_Actor>(theIObject),
- TSetFunction<SALOME_Actor,const char*,QString>
- (&SALOME_Actor::setName,theName.latin1()));
+ TSetFunction<SALOME_Actor,const char*,const char*>
+ (&SALOME_Actor::setName,theName.toLatin1().data()));
}
/*!
#include "SVTK.h"
#include "SALOME_InteractiveObject.hxx"
-#include <qobject.h>
+#include <QObject>
class vtkActorCollection;
class vtkRenderer;
class SALOME_Actor;
+class QMouseEvent;
+class QWheelEvent;
+class QKeyEvent;
+class QContextMenuEvent;
+class QColor;
+
+
//! Main purpose of the class is to provide a way to customize #SVTK_MainWindow.
/*!
This class is initialized by #SVTK_MainWindow and just pass Qt signals from
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-#include <qpopupmenu.h>
-#include <qcolordialog.h>
+#include <QMenu>
+#include <QColorDialog>
+#include <QToolBar>
#include <vtkCamera.h>
#include <vtkRenderer.h>
#include <vtkActorCollection.h>
-#include "SUIT_Session.h"
+//#include "SUIT_Session.h"
+#include "SUIT_ViewModel.h"
+#include "SUIT_ViewManager.h"
#include "SVTK_Selection.h"
#include "SVTK_ViewModel.h"
#include "VTKViewer_ViewModel.h"
#include <SALOME_Actor.h>
-#include <SALOME_InteractiveObject.hxx>
// in order NOT TO link with SalomeApp, here the code returns SALOMEDS_Study.
// SalomeApp_Study::studyDS() does it as well, but -- here it is retrieved from
if ( !theColor.isValid() )
return;
- QPtrVector<SUIT_ViewWindow> aViews = myViewManager->getViews();
+ QVector<SUIT_ViewWindow*> aViews = myViewManager->getViews();
for(int i = 0, iEnd = aViews.size(); i < iEnd; i++){
if(SUIT_ViewWindow* aViewWindow = aViews.at(i)){
if(TViewWindow* aView = dynamic_cast<TViewWindow*>(aViewWindow)){
myTrihedronRelative = theRelative;
if (SUIT_ViewManager* aViewManager = getViewManager()) {
- QPtrVector<SUIT_ViewWindow> aViews = aViewManager->getViews();
+ QVector<SUIT_ViewWindow*> aViews = aViewManager->getViews();
for ( uint i = 0; i < aViews.count(); i++ )
{
if ( TViewWindow* aView = dynamic_cast<TViewWindow*>(aViews.at( i )) )
*/
void
SVTK_Viewer
-::contextMenuPopup( QPopupMenu* thePopup )
+::contextMenuPopup( QMenu* thePopup )
{
- thePopup->insertItem( VTKViewer_Viewer::tr( "MEN_DUMP_VIEW" ), this, SLOT( onDumpView() ) );
- thePopup->insertItem( VTKViewer_Viewer::tr( "MEN_CHANGE_BACKGROUD" ), this, SLOT( onChangeBgColor() ) );
+ thePopup->addAction( VTKViewer_Viewer::tr( "MEN_DUMP_VIEW" ), this, SLOT( onDumpView() ) );
+ thePopup->addAction( VTKViewer_Viewer::tr( "MEN_CHANGE_BACKGROUD" ), this, SLOT( onChangeBgColor() ) );
- thePopup->insertSeparator();
+ thePopup->addSeparator();
if(TViewWindow* aView = dynamic_cast<TViewWindow*>(myViewManager->getActiveView())){
if ( !aView->getMainWindow()->getToolBar()->isVisible() ){
- thePopup->insertItem( VTKViewer_Viewer::tr( "MEN_SHOW_TOOLBAR" ), this, SLOT( onShowToolbar() ) );
+ thePopup->addAction( VTKViewer_Viewer::tr( "MEN_SHOW_TOOLBAR" ), this, SLOT( onShowToolbar() ) );
}
aView->RefreshDumpImage();
}
SVTK_Viewer
::onShowToolbar()
{
- QPtrVector<SUIT_ViewWindow> aViews = myViewManager->getViews();
+ QVector<SUIT_ViewWindow*> aViews = myViewManager->getViews();
for(int i = 0, iEnd = aViews.size(); i < iEnd; i++){
if(TViewWindow* aView = dynamic_cast<TViewWindow*>(aViews.at(i))){
aView->getMainWindow()->getToolBar()->show();
// ToolsGUI::SetVisibility(aStudy,anObj->getEntry(),true,this);
//}
// just display the object
- QPtrVector<SUIT_ViewWindow> aViews = myViewManager->getViews();
+ QVector<SUIT_ViewWindow*> aViews = myViewManager->getViews();
for(int i = 0, iEnd = aViews.size(); i < iEnd; i++){
if(SVTK_ViewWindow* aViewWindow = dynamic_cast<SVTK_ViewWindow*>(aViews.at(i))){
if(SVTK_View* aView = aViewWindow->getView()){
// ToolsGUI::SetVisibility(aStudy,anObj->getEntry(),false,this);
//}
// just display the object
- QPtrVector<SUIT_ViewWindow> aViews = myViewManager->getViews();
+ QVector<SUIT_ViewWindow*> aViews = myViewManager->getViews();
for(int i = 0, iEnd = aViews.size(); i < iEnd; i++){
if(SVTK_ViewWindow* aViewWindow = dynamic_cast<SVTK_ViewWindow*>(aViews.at(i)))
if(SVTK_View* aView = aViewWindow->getView())
// TODO: better mechanism of storing display/erse status in a study
// should be provided...
//_PTR(Study) aStudy(getStudyDS());
- QPtrVector<SUIT_ViewWindow> aViews = myViewManager->getViews();
+ QVector<SUIT_ViewWindow*> aViews = myViewManager->getViews();
for(int i = 0, iEnd = aViews.size(); i < iEnd; i++){
if(SVTK_ViewWindow* aViewWindow = dynamic_cast<SVTK_ViewWindow*>(aViews.at(i)))
if(SVTK_View* aView = aViewWindow->getView()){
SVTK_Viewer
::isVisible( const Handle(SALOME_InteractiveObject)& io )
{
- QPtrVector<SUIT_ViewWindow> aViews = myViewManager->getViews();
+ QVector<SUIT_ViewWindow*> aViews = myViewManager->getViews();
for(int i = 0, iEnd = aViews.size(); i < iEnd; i++)
if(SUIT_ViewWindow* aViewWindow = aViews.at(i))
if(TViewWindow* aViewWnd = dynamic_cast<TViewWindow*>(aViewWindow))
::Repaint()
{
// if (theUpdateTrihedron) onAdjustTrihedron();
- QPtrVector<SUIT_ViewWindow> aViews = myViewManager->getViews();
+ QVector<SUIT_ViewWindow*> aViews = myViewManager->getViews();
for(int i = 0, iEnd = aViews.size(); i < iEnd; i++)
if(TViewWindow* aViewWindow = dynamic_cast<TViewWindow*>(aViews.at(i)))
if(SVTK_View* aView = aViewWindow->getView())
#define SVTK_VIEWMODEL_H
#include "SVTK.h"
-#include "SUIT_ViewModel.h"
#include "SVTK_ViewModelBase.h"
#include "SALOME_Prs.h"
#include "SALOME_InteractiveObject.hxx"
-#include <qcolor.h>
+#include <QColor>
+
+class QMouseEvent;
class SVTK_ViewWindow;
virtual void setViewManager(SUIT_ViewManager* theViewManager);
//! See #SUIT_ViewModel::contextMenuPopup
- virtual void contextMenuPopup( QPopupMenu* );
+ virtual void contextMenuPopup( QMenu* );
//! See #SUIT_ViewModel::getType
virtual QString getType() const { return Type(); }
//
#include "SALOME_Actor.h"
-#include <qapplication.h>
-#include <qimage.h>
+#include <QToolBar>
+#include <QEvent>
#include <vtkTextProperty.h>
#include <vtkActorCollection.h>
::setBackgroundColor( const QColor& color )
{
myMainWindow->SetBackgroundColor( color );
- SUIT_ViewWindow::setBackgroundColor( color );
+
+ QPalette palette;
+ palette.setColor(backgroundRole(), color);
+ setPalette(palette);
}
/*!
QImage
SVTK_ViewWindow
::dumpView()
-{
- if ( myMainWindow->getToolBar()->hasMouse() || myDumpImage.isNull() )
+{
+ if ( myMainWindow->getToolBar()->testAttribute(Qt::WA_UnderMouse) || myDumpImage.isNull() )
return myMainWindow->dumpView();
return myDumpImage;
shadow = txtProp->GetShadow();
}
params.sprintf( "* Graduated Axis: * Name *%u*%s*%.2f*%.2f*%.2f*%u*%u*%u*%u", isVisible,
- title.latin1(), color[0], color[1], color[2], font, bold, italic, shadow );
+ title.toLatin1().data(), color[0], color[1], color[2], font, bold, italic, shadow );
// Labels
isVisible = actor->GetLabelVisibility();
if ( !actor )
return;
- QStringList paramsLst = QStringList::split( '*', params, true );
+ QStringList paramsLst = params.split( '*' );
if ( paramsLst.size() == nGradAxisParams ) { // altogether name, lable, ticks parameters make up 25 values
int shadow = paramsLst[10].toInt();
actor->SetTitleVisibility( isVisible );
- actor->SetTitle( title.latin1() );
+ actor->SetTitle( title.toLatin1() );
vtkTextProperty* txtProp = actor->GetTitleTextProperty();
if ( txtProp ) {
txtProp->SetColor( color );
SVTK_ViewWindow
::doSetVisualParameters( const QString& parameters )
{
- QStringList paramsLst = QStringList::split( '*', parameters, true );
+ QStringList paramsLst = parameters.split( '*' );
if ( paramsLst.size() >= nNormalParams ) {
// 'reading' list of parameters
double pos[3], focalPnt[3], viewUp[3], parScale, scale[3];
#include "SVTK.h"
#include "SVTK_Selection.h"
#include "SUIT_ViewWindow.h"
+
#include "SALOME_InteractiveObject.hxx"
-#include <qimage.h>
+#include <QImage>
class SUIT_Desktop;
class SVTK_Selector;
class SVTK_View;
-class SVTK_InteractorStyle;
class SVTK_CubeAxesActor2D;
-class SVTK_RenderWindow;
-class SVTK_RenderWindowInteractor;
-
class vtkRenderer;
class vtkRenderWindow;
class vtkRenderWindowInteractor;
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>ICON_GRADUATED_AXES</source>
+ <translation>view_graduated_axes.png</translation>
+ </message>
+ <message>
+ <source>ICON_SVTK_SCALING</source>
+ <translation>view_scaling.png</translation>
+ </message>
+ <message>
+ <source>ICON_UPDATE_RATE</source>
+ <translation>view_update_rate.png</translation>
+ </message>
+</context>
+</TS>
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>MNU_FRONT_VIEW</source>
+ <translation>Front</translation>
+ </message>
+ <message>
+ <source>ERROR</source>
+ <translation>Error</translation>
+ </message>
+ <message>
+ <source>MNU_DUMP_VIEW</source>
+ <translation>Dump view...</translation>
+ </message>
+ <message>
+ <source>DSC_TOP_VIEW</source>
+ <translation>Top View</translation>
+ </message>
+ <message>
+ <source>MNU_PAN_VIEW</source>
+ <translation>Panning</translation>
+ </message>
+ <message>
+ <source>MNU_TOP_VIEW</source>
+ <translation>Top</translation>
+ </message>
+ <message>
+ <source>DSC_GLOBALPAN_VIEW</source>
+ <translation>Selection of a new center of the view</translation>
+ </message>
+ <message>
+ <source>DSC_ROTATE_VIEW</source>
+ <translation>Rotation of the point of view around the scene center</translation>
+ </message>
+ <message>
+ <source>MNU_ZOOM_VIEW</source>
+ <translation>Zoom</translation>
+ </message>
+ <message>
+ <source>DSC_PAN_VIEW</source>
+ <translation>Panning the view</translation>
+ </message>
+ <message>
+ <source>DSC_LEFT_VIEW</source>
+ <translation>Left View</translation>
+ </message>
+ <message>
+ <source>DSC_FITALL</source>
+ <translation>Fit all objects inside the view frame</translation>
+ </message>
+ <message>
+ <source>MNU_FITALL</source>
+ <translation>Fit All</translation>
+ </message>
+ <message>
+ <source>MNU_ROTATE_VIEW</source>
+ <translation>Rotation</translation>
+ </message>
+ <message>
+ <source>DSC_SHOW_TRIHEDRON</source>
+ <translation>Show/Hide trihedron in the current view</translation>
+ </message>
+ <message>
+ <source>DSC_FRONT_VIEW</source>
+ <translation>Front View</translation>
+ </message>
+ <message>
+ <source>MNU_GLOBALPAN_VIEW</source>
+ <translation>Global Panning</translation>
+ </message>
+ <message>
+ <source>INF_APP_DUMP_VIEW</source>
+ <translation>Dump view</translation>
+ </message>
+ <message>
+ <source>MNU_BACK_VIEW</source>
+ <translation>Back</translation>
+ </message>
+ <message>
+ <source>MNU_SHOW_TRIHEDRON</source>
+ <translation>Show/Hide trihedron</translation>
+ </message>
+ <message>
+ <source>DSC_CHANGINGROTATIONPOINT_VIEW</source>
+ <translation>Change the point, around which the rotation is performed</translation>
+ </message>
+ <message>
+ <source>MNU_BOTTOM_VIEW</source>
+ <translation>Bottom</translation>
+ </message>
+ <message>
+ <source>MNU_RESET_VIEW</source>
+ <translation>Reset</translation>
+ </message>
+ <message>
+ <source>MNU_LEFT_VIEW</source>
+ <translation>Left</translation>
+ </message>
+ <message>
+ <source>DSC_RIGHT_VIEW</source>
+ <translation>Right View</translation>
+ </message>
+ <message>
+ <source>MNU_CHANGINGROTATIONPOINT_VIEW</source>
+ <translation>Change Rotation Point</translation>
+ </message>
+ <message>
+ <source>DSC_FITRECT</source>
+ <translation>Fit area within the view frame</translation>
+ </message>
+ <message>
+ <source>MNU_FITRECT</source>
+ <translation>Fit Area</translation>
+ </message>
+ <message>
+ <source>DSC_BOTTOM_VIEW</source>
+ <translation>Bottom View</translation>
+ </message>
+ <message>
+ <source>DSC_DUMP_VIEW</source>
+ <translation>Saves the active view in the image file</translation>
+ </message>
+ <message>
+ <source>DSC_ZOOM_VIEW</source>
+ <translation>Zoom the view</translation>
+ </message>
+ <message>
+ <source>VTK_IMAGE_FILES</source>
+ <translation>Images Files (*.bmp *.png *.jpg *.jpeg)</translation>
+ </message>
+ <message>
+ <source>DSC_RESET_VIEW</source>
+ <translation>Reset View Point</translation>
+ </message>
+ <message>
+ <source>ERR_DOC_CANT_SAVE_FILE</source>
+ <translation>Cannot save file</translation>
+ </message>
+ <message>
+ <source>MNU_RIGHT_VIEW</source>
+ <translation>Right</translation>
+ </message>
+ <message>
+ <source>LBL_TOOLBAR_LABEL</source>
+ <translation>View Operations</translation>
+ </message>
+ <message>
+ <source>DSC_BACK_VIEW</source>
+ <translation>Back View</translation>
+ </message>
+</context>
+<context>
+ <name>SVTK_AxisWidget</name>
+ <message>
+ <source>FONT</source>
+ <translation>Font</translation>
+ </message>
+ <message>
+ <source>NAME</source>
+ <translation>Name</translation>
+ </message>
+ <message>
+ <source>TICK_MARKS</source>
+ <translation>Tick marks</translation>
+ </message>
+ <message>
+ <source>LABELS</source>
+ <translation>Labels</translation>
+ </message>
+ <message>
+ <source>LENGTH</source>
+ <translation>Length</translation>
+ </message>
+ <message>
+ <source>NUMBER</source>
+ <translation>Number</translation>
+ </message>
+ <message>
+ <source>OFFSET</source>
+ <translation>Offset</translation>
+ </message>
+ <message>
+ <source>IS_VISIBLE</source>
+ <translation>Is visible</translation>
+ </message>
+ <message>
+ <source>AXIS_NAME</source>
+ <translation>Axis name</translation>
+ </message>
+</context>
+<context>
+ <name>SVTK_CubeAxesDlg</name>
+ <message>
+ <source>X_AXIS</source>
+ <translation>X axis</translation>
+ </message>
+ <message>
+ <source>Y_AXIS</source>
+ <translation>Y axis</translation>
+ </message>
+ <message>
+ <source>Z_AXIS</source>
+ <translation>Z axis</translation>
+ </message>
+ <message>
+ <source>CAPTION</source>
+ <translation>Graduated axes</translation>
+ </message>
+ <message>
+ <source>IS_VISIBLE</source>
+ <translation>Is visible</translation>
+ </message>
+</context>
+<context>
+ <name>SVTK_FontWidget</name>
+ <message>
+ <source>BOLD</source>
+ <translation>Bold</translation>
+ </message>
+ <message>
+ <source>ARIAL</source>
+ <translation>Arial</translation>
+ </message>
+ <message>
+ <source>TIMES</source>
+ <translation>Times</translation>
+ </message>
+ <message>
+ <source>ITALIC</source>
+ <translation>Italic</translation>
+ </message>
+ <message>
+ <source>SHADOW</source>
+ <translation>Shadow</translation>
+ </message>
+ <message>
+ <source>COURIER</source>
+ <translation>Courier</translation>
+ </message>
+</context>
+<context>
+ <name>SVTK_MainWindow</name>
+ <message>
+ <source>DSC_SVTK_UPDATE_RATE</source>
+ <translation>Update rate</translation>
+ </message>
+ <message>
+ <source>DSC_SVTK_SCALING</source>
+ <translation>Scaling</translation>
+ </message>
+ <message>
+ <source>MNU_SVTK_SCALING</source>
+ <translation>Scaling</translation>
+ </message>
+ <message>
+ <source>MNU_SVTK_GRADUATED_AXES</source>
+ <translation>Graduated axes</translation>
+ </message>
+ <message>
+ <source>DSC_SVTK_GRADUATED_AXES</source>
+ <translation>Graduated axes</translation>
+ </message>
+ <message>
+ <source>MNU_SVTK_UPDATE_RATE</source>
+ <translation>Update rate</translation>
+ </message>
+</context>
+<context>
+ <name>SVTK_NonIsometricDlg</name>
+ <message>
+ <source>LBL_X</source>
+ <translation>X :</translation>
+ </message>
+ <message>
+ <source>LBL_Y</source>
+ <translation>Y :</translation>
+ </message>
+ <message>
+ <source>LBL_Z</source>
+ <translation>Z :</translation>
+ </message>
+ <message>
+ <source>MEN_SCALING</source>
+ <translation>Scaling</translation>
+ </message>
+ <message>
+ <source>DLG_TITLE</source>
+ <translation>Scaling</translation>
+ </message>
+</context>
+<context>
+ <name>SVTK_SetRotationPointDlg</name>
+ <message>
+ <source>LBL_X</source>
+ <translation>X :</translation>
+ </message>
+ <message>
+ <source>LBL_Y</source>
+ <translation>Y :</translation>
+ </message>
+ <message>
+ <source>LBL_Z</source>
+ <translation>Z :</translation>
+ </message>
+ <message>
+ <source>LBL_CENTER_OF_BOUNDING_BOX</source>
+ <translation>Center of bounding box</translation>
+ </message>
+ <message>
+ <source>RBUTTONGROUP_TITLE</source>
+ <translation>The rotation point type</translation>
+ </message>
+ <message>
+ <source>USE_BBCENTER</source>
+ <translation>Use Bounding Box Center</translation>
+ </message>
+ <message>
+ <source>LBL_ORIGIN</source>
+ <translation>Origin of the coordinate system</translation>
+ </message>
+ <message>
+ <source>LBL_SELECTED_POINT</source>
+ <translation>Selected point</translation>
+ </message>
+ <message>
+ <source>LBL_TOORIGIN</source>
+ <translation>Set to Origin</translation>
+ </message>
+ <message>
+ <source>LBL_SELECTPOINT</source>
+ <translation>Select Point from View</translation>
+ </message>
+ <message>
+ <source>DLG_TITLE</source>
+ <translation>Set Rotation Point</translation>
+ </message>
+</context>
+<context>
+ <name>SVTK_UpdateRateDlg</name>
+ <message>
+ <source>INFORMATION_FRAME_TITLE</source>
+ <translation>Rendering Metrics</translation>
+ </message>
+ <message>
+ <source>STILL</source>
+ <translation>Still Update Rate, FPS</translation>
+ </message>
+ <message>
+ <source>INPUT_FRAME_TITLE</source>
+ <translation>Enable</translation>
+ </message>
+ <message>
+ <source>NUMBER_CELLS</source>
+ <translation>Number of Cells, -</translation>
+ </message>
+ <message>
+ <source>DESIRED</source>
+ <translation>Desired Update Rate, FPS</translation>
+ </message>
+ <message>
+ <source>CURRENT_FPS</source>
+ <translation>Current Update Rate, FPS</translation>
+ </message>
+ <message>
+ <source>DLG_TITLE</source>
+ <translation>Update Rate</translation>
+ </message>
+</context>
+<context>
+ <name>SVTK_ViewManager</name>
+ <message>
+ <source>VTK_VIEW_TITLE</source>
+ <translation>VTK scene:%1 - viewer:%2</translation>
+ </message>
+</context>
+<context>
+ <name>SVTK_Viewer</name>
+ <message>
+ <source>MEN_DUMP_VIEW</source>
+ <translation>Dump view...</translation>
+ </message>
+ <message>
+ <source>MEN_SHOW_TOOLBAR</source>
+ <translation>Show toolbar</translation>
+ </message>
+ <message>
+ <source>MEN_CHANGE_BACKGROUD</source>
+ <translation>Change background...</translation>
+ </message>
+</context>
+</TS>
SalomeApp_Application.h \
SalomeApp_DataModel.h \
SalomeApp_DataObject.h \
+ SalomeApp_LoadStudiesDlg.h \
SalomeApp_Module.h \
SalomeApp_Study.h \
SalomeApp_ExceptionHandler.h \
SalomeApp_Application.cxx \
SalomeApp_DataModel.cxx \
SalomeApp_DataObject.cxx \
+ SalomeApp_LoadStudiesDlg.cxx \
SalomeApp_Study.cxx \
SalomeApp_ExceptionHandler.cxx \
SalomeApp_EventFilter.cxx \
SalomeApp_Application_moc.cxx \
SalomeApp_DataModel_moc.cxx \
SalomeApp_Module_moc.cxx \
+ SalomeApp_LoadStudiesDlg_moc.cxx \
SalomeApp_Study_moc.cxx \
SalomeApp_StudyPropertiesDlg_moc.cxx \
SalomeApp_ListView_moc.cxx \
-I$(srcdir)/../LightApp -I$(srcdir)/../CAM -I$(srcdir)/../Qtx \
-I$(srcdir)/../SUIT -I$(srcdir)/../OBJECT -I$(srcdir)/../SVTK \
-I$(srcdir)/../STD -I$(srcdir)/../VTKViewer -I$(srcdir)/../ObjBrowser \
- -I$(srcdir)/../PythonConsole -I$(srcdir)/../TOOLSGUI \
+ -I$(srcdir)/../PyConsole -I$(srcdir)/../TOOLSGUI \
-I$(srcdir)/../PyInterp -I$(srcdir)/../Session -I$(top_builddir)/idl \
-I$(srcdir)/../Event \
-I$(top_builddir)/salome_adm/unix @CORBA_CXXFLAGS@ @CORBA_INCLUDES@
libSalomeApp_la_LDFLAGS=$(PYTHON_LIBS) $(QT_MT_LIBS)
libSalomeApp_la_LIBADD= $(KERNEL_LDFLAGS) -lOpUtil -lSALOMELocalTrace -lSalomeDSClient \
- ../SUIT/libsuit.la ../STD/libstd.la ../CAM/libCAM.la ../ObjBrowser/libObjBrowser.la \
+ ../SUIT/libsuit.la ../STD/libstd.la ../CAM/libCAM.la \ #../ObjBrowser/libObjBrowser.la \
../Prs/libSalomePrs.la ../SPlot2d/libSPlot2d.la ../GLViewer/libGLViewer.la \
../OCCViewer/libOCCViewer.la ../VTKViewer/libVTKViewer.la ../OBJECT/libSalomeObject.la \
../SVTK/libSVTK.la ../SOCC/libSOCC.la ../PyInterp/libPyInterp.la \
- ../PythonConsole/libPythonConsole.la ../LogWindow/libLogWindow.la \
+ ../PyConsole/libPyConsole.la ../LogWindow/libLogWindow.la \
../LightApp/libLightApp.la ../TOOLSGUI/libToolsGUI.la $(CAS_KERNEL)
-EXTRA_DIST+=SalomeApp_PyInterp.h
\ No newline at end of file
+EXTRA_DIST+=SalomeApp_PyInterp.h
// that uses this DLL. This way any other project whose source files include this file see
// SalomeApp_API functions as being imported from a DLL, wheras this DLL sees symbols
// defined with this macro as being exported.
-#ifdef WNT
+#ifdef WIN32
#ifdef SALOMEAPP_EXPORTS
#define SALOMEAPP_EXPORT __declspec(dllexport)
#else
#define SALOMEAPP_EXPORT
-#endif //WNT
+#endif //WIN32
#define APP_VERSION "0.1"
-#if defined WNT
+#if defined WIN32
#pragma warning ( disable: 4251 )
#endif
--- /dev/null
+TEMPLATE = lib
+TARGET = SalomeApp
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+PYTHON_INCLUDES = $$(PYTHONHOME)/include/python2.4
+
+QT_INCLUDES = $$(QTDIR)/include $$(QTDIR)/include/QtCore $$(QTDIR)/include/QtGui $$(QTDIR)/include/QtOpenGL $$(QTDIR)/include/QtXml
+
+QWT_INCLUDES = $$(QWTHOME)/include
+
+CASROOT = $$(CASROOT)
+CAS_CPPFLAGS = $${CASROOT}/inc
+
+VTK_INCLUDES = $$(VTKHOME)/include/vtk
+
+BOOST_CPPFLAGS = $$(BOOSTDIR)/include
+
+KERNEL_CXXFLAGS = $$(KERNEL_ROOT_DIR)/include/salome
+
+CORBA_INCLUDES = $$(OMNIORBDIR)/include $$(OMNIORBDIR)/include/omniORB4 $$(OMNIORBDIR)/include/COS
+
+HDF5_INCLUDES = $$(HDF5HOME)/include
+
+PYTHON_LIBS = -L$$(PYTHONHOME)/lib/python2.4/config -lpython2.4 -ldl -lutil
+
+QT_MT_LIBS = -L$$(QTDIR)/lib -lQtCore -lQtXml -lQtGui -lQtOpenGL
+
+KERNEL_LDFLAGS = -L$$(KERNEL_ROOT_DIR)/lib/salome
+
+CAS_KERNEL = -L$${CASROOT}/Linux/lib -lTKernel
+
+
+INCLUDEPATH += $${PYTHON_INCLUDES} $${QT_INCLUDES} $${QWT_INCLUDES} $${CAS_CPPFLAGS} $${VTK_INCLUDES} $${BOOST_CPPFLAGS} $${KERNEL_CXXFLAGS} ../LightApp ../CAM ../Qtx ../SUIT ../OBJECT ../SVTK ../STD ../VTKViewer ../PyConsole ../TOOLSGUI ../PyInterp ../Session ../../idl ../Event ../../salome_adm/unix $${CORBA_INCLUDES} #../ObjBrowser
+
+LIBS += $${QT_MT_LIBS} $${PYTHON_LIBS} $${KERNEL_LDFLAGS} -lOpUtil -lSALOMELocalTrace -lSalomeDSClient -L../../lib -lsuit -lstd -lCAM -lSalomePrs -lSPlot2d -lGLViewer -lOCCViewer -lVTKViewer -lSalomeObject -lSVTK -lSOCC -lPyInterp -lPyConsole -lLogWindow -lLightApp -lToolsGUI $${CAS_KERNEL} #-lObjBrowser
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += SALOMEAPP_EXPORTS OCC_VERSION_MAJOR=6 OCC_VERSION_MINOR=1 OCC_VERSION_MAINTENANCE=1 LIN LINTEL CSFDB No_exception HAVE_CONFIG_H HAVE_LIMITS_H HAVE_WOK_CONFIG_H OCC_CONVERT_SIGNALS OMNIORB_VERSION=4 __x86__ __linux__ COMP_CORBA_DOUBLE COMP_CORBA_LONG
+
+HEADERS = SalomeApp.h
+HEADERS += SalomeApp_Application.h
+HEADERS += SalomeApp_DataModel.h
+HEADERS += SalomeApp_DataObject.h
+HEADERS += SalomeApp_LoadStudiesDlg.h
+HEADERS += SalomeApp_Module.h
+HEADERS += SalomeApp_Study.h
+HEADERS += SalomeApp_ExceptionHandler.h
+HEADERS += SalomeApp_EventFilter.h
+HEADERS += SalomeApp_Tools.h
+HEADERS += SalomeApp_ImportOperation.h
+HEADERS += SalomeApp_Filter.h
+HEADERS += SalomeApp_TypeFilter.h
+HEADERS += SalomeApp_StudyPropertiesDlg.h
+HEADERS += SalomeApp_CheckFileDlg.h
+HEADERS += SalomeApp_VisualState.h
+
+SOURCES = SalomeApp_Module.cxx
+SOURCES += SalomeApp_Application.cxx
+SOURCES += SalomeApp_DataModel.cxx
+SOURCES += SalomeApp_DataObject.cxx
+SOURCES += SalomeApp_LoadStudiesDlg.cxx
+SOURCES += SalomeApp_Study.cxx
+SOURCES += SalomeApp_ExceptionHandler.cxx
+SOURCES += SalomeApp_EventFilter.cxx
+SOURCES += SalomeApp_PyInterp.cxx
+SOURCES += SalomeApp_Tools.cxx
+SOURCES += SalomeApp_ImportOperation.cxx
+SOURCES += SalomeApp_Filter.cxx
+SOURCES += SalomeApp_TypeFilter.cxx
+SOURCES += SalomeApp_StudyPropertiesDlg.cxx
+SOURCES += SalomeApp_ListView.cxx
+SOURCES += SalomeApp_CheckFileDlg.cxx
+SOURCES += SalomeApp_VisualState.cxx
+
+TRANSLATIONS = resources/SalomeApp_images.ts \
+ resources/SalomeApp_msg_en.ts
+
+ICONS = resources/*.png
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+resources.files = $$ICONS resources/*.qm
+resources.path = ../../resources
+
+INSTALLS += includes resources
#include "SalomeApp_VisualState.h"
#include "SalomeApp_StudyPropertiesDlg.h"
+#include "SalomeApp_LoadStudiesDlg.h"
#include "LightApp_Application.h"
#include "LightApp_Preferences.h"
-#include "LightApp_WidgetContainer.h"
#include "LightApp_SelectionMgr.h"
#include "LightApp_NameDlg.h"
-#include "STD_LoadStudiesDlg.h"
+#include "CAM_Module.h"
#include <SUIT_Tools.h>
#include <SUIT_Session.h>
+#include <SUIT_Desktop.h>
#include <QtxMRUAction.h>
-#include <OB_Browser.h>
-#include <OB_ListItem.h>
+// temporary commented
+//#include <OB_Browser.h>
+//#include <OB_ListItem.h>
-#include <PythonConsole_PyConsole.h>
+#include <PyConsole_Console.h>
#include <SUIT_FileDlg.h>
#include <SUIT_MessageBox.h>
#include <SUIT_ResourceMgr.h>
-#include <SUIT_ActionOperation.h>
#include <Utils_ORB_INIT.hxx>
#include <Utils_SINGLETON.hxx>
-#include <SALOME_ModuleCatalog_impl.hxx>
#include <SALOME_LifeCycleCORBA.hxx>
-#include <qaction.h>
-#include <qcombobox.h>
-#include <qlistbox.h>
-#include <qregexp.h>
-#include <qcheckbox.h>
-#include <qpushbutton.h>
-#include <qlabel.h>
+#include <QApplication>
+#include <QAction>
+#include <QRegExp>
+#include <QCheckBox>
+#include <QPushButton>
+#include <QLabel>
+#include <QListWidget>
+#include <QGridLayout>
+#include <QMenu>
#include "SALOMEDSClient_ClientFactory.hxx"
-#include "SALOMEDSClient_IParameters.hxx"
#include "SALOME_ListIteratorOfListIO.hxx"
#include "SALOME_ListIO.hxx"
#include "ToolsGUI_CatalogGeneratorDlg.h"
#include "ToolsGUI_RegWidget.h"
-#include <SALOMEDSClient_ClientFactory.hxx>
-
#include <vector>
+
/*!Internal class that updates object browser item properties */
-class SalomeApp_Updater : public OB_Updater
+// temporary commented
+/*class SalomeApp_Updater : public OB_Updater
{
public:
SalomeApp_Updater() : OB_Updater(){};
// _PTR(AttributeOpened) aAttrOpen = anAttr;
// theItem->setOpen( aAttrOpen->IsOpened() );
//}
-}
+}*/
/*!Create new instance of SalomeApp_Application.*/
extern "C" SALOMEAPP_EXPORT SUIT_Application* createApplication()
for (int i = 1; i < qApp->argc(); i++) {
QRegExp rxs ("--study-hdf=(.+)");
- if ( rxs.search( QString(qApp->argv()[i]) ) >= 0 && rxs.capturedTexts().count() > 1 ) {
+ if ( rxs.indexIn( QString(qApp->argv()[i]) ) >= 0 && rxs.capturedTexts().count() > 1 ) {
QString file = rxs.capturedTexts()[1];
QFileInfo fi ( file );
- QString extension = fi.extension( false ).lower();
+ QString extension = fi.suffix().toLower();
if ( extension == "hdf" && fi.exists() )
- hdffile = fi.absFilePath();
+ hdffile = fi.absoluteFilePath();
}
else {
QRegExp rxp ("--pyscript=(.+)");
- if ( rxp.search( QString(qApp->argv()[i]) ) >= 0 && rxp.capturedTexts().count() > 1 ) {
- QStringList files = QStringList::split(",",rxp.capturedTexts()[1],false);
+ if ( rxp.indexIn( QString(qApp->argv()[i]) ) >= 0 && rxp.capturedTexts().count() > 1 ) {
+ QStringList files = rxp.capturedTexts()[1].split(",",QString::SkipEmptyParts);
pyfiles += files;
}
}
if ( !aStudy->GetProperties()->IsLocked() ) {
for (uint j = 0; j < pyfiles.count(); j++ ) {
QFileInfo fi ( pyfiles[j] );
- PythonConsole* pyConsole = pythonConsole();
+ PyConsole_Console* pyConsole = pythonConsole();
if ( pyConsole ) {
- QString extension = fi.extension( false ).lower();
+ QString extension = fi.suffix().toLower();
if ( extension == "py" && fi.exists() ) {
// execute python script
- QString command = QString( "execfile(\"%1\")" ).arg( fi.absFilePath() );
+ QString command = QString( "execfile(\"%1\")" ).arg( fi.absoluteFilePath() );
pyConsole->exec( command );
}
else {
//! Save GUI state
// "Save GUI State" command is moved to VISU module
- // createAction( SaveGUIStateId, tr( "TOT_DESK_FILE_SAVE_GUI_STATE" ), QIconSet(),
+ // createAction( SaveGUIStateId, tr( "TOT_DESK_FILE_SAVE_GUI_STATE" ), QIcon(),
// tr( "MEN_DESK_FILE_SAVE_GUI_STATE" ), tr( "PRP_DESK_FILE_SAVE_GUI_STATE" ),
// 0, desk, false, this, SLOT( onSaveGUIState() ) );
//! Dump study
- createAction( DumpStudyId, tr( "TOT_DESK_FILE_DUMP_STUDY" ), QIconSet(),
+ createAction( DumpStudyId, tr( "TOT_DESK_FILE_DUMP_STUDY" ), QIcon(),
tr( "MEN_DESK_FILE_DUMP_STUDY" ), tr( "PRP_DESK_FILE_DUMP_STUDY" ),
- CTRL+Key_D, desk, false, this, SLOT( onDumpStudy() ) );
+ Qt::CTRL+Qt::Key_D, desk, false, this, SLOT( onDumpStudy() ) );
//! Load script
- createAction( LoadScriptId, tr( "TOT_DESK_FILE_LOAD_SCRIPT" ), QIconSet(),
+ createAction( LoadScriptId, tr( "TOT_DESK_FILE_LOAD_SCRIPT" ), QIcon(),
tr( "MEN_DESK_FILE_LOAD_SCRIPT" ), tr( "PRP_DESK_FILE_LOAD_SCRIPT" ),
- CTRL+Key_T, desk, false, this, SLOT( onLoadScript() ) );
+ Qt::CTRL+Qt::Key_T, desk, false, this, SLOT( onLoadScript() ) );
//! Properties
- createAction( PropertiesId, tr( "TOT_DESK_PROPERTIES" ), QIconSet(),
+ createAction( PropertiesId, tr( "TOT_DESK_PROPERTIES" ), QIcon(),
tr( "MEN_DESK_PROPERTIES" ), tr( "PRP_DESK_PROPERTIES" ),
- CTRL+Key_P, desk, false, this, SLOT( onProperties() ) );
+ Qt::CTRL+Qt::Key_P, desk, false, this, SLOT( onProperties() ) );
//! Catalog Generator
- createAction( CatalogGenId, tr( "TOT_DESK_CATALOG_GENERATOR" ), QIconSet(),
+ createAction( CatalogGenId, tr( "TOT_DESK_CATALOG_GENERATOR" ), QIcon(),
tr( "MEN_DESK_CATALOG_GENERATOR" ), tr( "PRP_DESK_CATALOG_GENERATOR" ),
- SHIFT+Key_G, desk, false, this, SLOT( onCatalogGen() ) );
+ Qt::SHIFT+Qt::Key_G, desk, false, this, SLOT( onCatalogGen() ) );
//! Registry Display
- createAction( RegDisplayId, tr( "TOT_DESK_REGISTRY_DISPLAY" ), QIconSet(),
+ createAction( RegDisplayId, tr( "TOT_DESK_REGISTRY_DISPLAY" ), QIcon(),
tr( "MEN_DESK_REGISTRY_DISPLAY" ), tr( "PRP_DESK_REGISTRY_DISPLAY" ),
- /*SHIFT+Key_D*/0, desk, false, this, SLOT( onRegDisplay() ) );
+ /*Qt::SHIFT+Qt::Key_D*/0, desk, false, this, SLOT( onRegDisplay() ) );
//SRN: BugID IPAL9021, add an action "Load"
createAction( FileLoadId, tr( "TOT_DESK_FILE_LOAD" ),
resourceMgr()->loadPixmap( "STD", tr( "ICON_FILE_OPEN" ) ),
tr( "MEN_DESK_FILE_LOAD" ), tr( "PRP_DESK_FILE_LOAD" ),
- CTRL+Key_L, desk, false, this, SLOT( onLoadDoc() ) );
+ Qt::CTRL+Qt::Key_L, desk, false, this, SLOT( onLoadDoc() ) );
//SRN: BugID IPAL9021: End
// Look among opened studies
if (activeStudy()) { // at least one study is opened
SUIT_Session* aSession = SUIT_Session::session();
- QPtrList<SUIT_Application> aAppList = aSession->applications();
- QPtrListIterator<SUIT_Application> it (aAppList);
+ QList<SUIT_Application*> aAppList = aSession->applications();
+ QListIterator<SUIT_Application*> it (aAppList);
SUIT_Application* aApp = 0;
// iterate on all applications
- for (; (aApp = it.current()) && !isAlreadyOpen; ++it) {
- if (aApp->activeStudy()->studyName() == aName) {
+ while ( it.hasNext() && !isAlreadyOpen ) {
+ aApp = it.next();
+
+ if (aApp && aApp->activeStudy()->studyName() == aName) {
isAlreadyOpen = true; // Already opened, ask user what to do
// The document ... is already open.
// Do you want to reload it?
- int aAnswer = SUIT_MessageBox::warn2(desktop(), tr("WRN_WARNING"),
- tr("QUE_DOC_ALREADYOPEN").arg(aName),
- tr("BUT_YES"), tr("BUT_NO"), 1, 2, 2);
- if (aAnswer == 1) { // reload
+ int aAnswer = SUIT_MessageBox::question(desktop(), tr("WRN_WARNING"),
+ tr("QUE_DOC_ALREADYOPEN").arg(aName),
+ SUIT_MessageBox::Yes | SUIT_MessageBox::No,
+ SUIT_MessageBox::No);
+ if (aAnswer == SUIT_MessageBox::Yes) { // reload
if (activeStudy()->studyName() == aName && aAppList.count() > 1) {
// Opened in THIS (active) application.
STD_Application* app1 = (STD_Application*)aAppList.at(0);
// The document ... already exists in the study manager.
// Do you want to reload it?
- int aAnswer = SUIT_MessageBox::warn2(desktop(), tr("WRN_WARNING"),
- tr("QUE_DOC_ALREADYEXIST").arg(aName),
- tr("BUT_YES"), tr("BUT_NO"), 1, 2, 2);
- if (aAnswer == 1) {
- _PTR(Study) aStudy = studyMgr()->GetStudyByName(aName.latin1());
+ int aAnswer = SUIT_MessageBox::question(desktop(), tr("WRN_WARNING"),
+ tr("QUE_DOC_ALREADYEXIST").arg(aName),
+ SUIT_MessageBox::Yes | SUIT_MessageBox::No,
+ SUIT_MessageBox::No);
+ if (aAnswer == SUIT_MessageBox::Yes) {
+ _PTR(Study) aStudy = studyMgr()->GetStudyByName(aName.toStdString());
if (aStudy)
studyMgr()->Close(aStudy);
} else {
/*!SLOT. Load document.*/
void SalomeApp_Application::onLoadDoc()
{
- QString name, studyname, ext;
-
- STD_LoadStudiesDlg aDlg( desktop(), TRUE);
+ QString studyName;
std::vector<std::string> List = studyMgr()->GetOpenStudies();
SUIT_Session* aSession = SUIT_Session::session();
- QPtrList<SUIT_Application> aAppList = aSession->applications();
- SUIT_Application* aApp = 0;
+ QList<SUIT_Application*> aAppList = aSession->applications();
+
+ QStringList unloadedStudies;
- for (unsigned int ind = 0; ind < List.size(); ind++) {
- studyname = List[ind].c_str();
- //Add to list only unloaded studies
+ for ( unsigned int ind = 0; ind < List.size(); ind++ ) {
+ studyName = List[ind].c_str();
+ // Add to list only unloaded studies
bool isAlreadyOpen = false;
- for ( QPtrListIterator<SUIT_Application> it( aAppList ); it.current() && !isAlreadyOpen; ++it )
- {
- aApp = it.current();
- if(!aApp || !aApp->activeStudy()) continue;
- if ( aApp->activeStudy()->studyName() == studyname ) isAlreadyOpen = true;
- }
+ QListIterator<SUIT_Application*> it( aAppList );
+ while ( it.hasNext() && !isAlreadyOpen ) {
+ SUIT_Application* aApp = it.next();
+ if( !aApp || !aApp->activeStudy() )
+ continue;
+ if ( aApp->activeStudy()->studyName() == studyName )
+ isAlreadyOpen = true;
+ }
- if ( !isAlreadyOpen ) aDlg.ListComponent->insertItem( studyname );
+ if ( !isAlreadyOpen )
+ unloadedStudies << studyName;
}
- int retVal = aDlg.exec();
- studyname = aDlg.ListComponent->currentText();
-
- if (retVal == QDialog::Rejected)
- return;
-
- if ( studyname.isNull() || studyname.isEmpty() )
+ studyName = SalomeApp_LoadStudiesDlg::selectStudy( desktop(), unloadedStudies );
+ if ( studyName.isEmpty() )
return;
- name = studyname;
-#ifndef WNT
- //this code replace marker of windows drive and path become invalid therefore
+#ifndef WIN32
+ // this code replaces marker of windows drive and path become invalid therefore
// defines placed there
- name.replace( QRegExp(":"), "/" );
+ studyName.replace( QRegExp(":"), "/" );
#endif
- if( LightApp_Application::onLoadDoc( name ) )
- {
- updateWindows();
- updateViewManagers();
- updateObjectBrowser(true);
+ if( LightApp_Application::onLoadDoc( studyName ) ) {
+ updateWindows();
+ updateViewManagers();
+ updateObjectBrowser( true );
}
}
if(!stdDS) return;
if ( stdDS->GetProperties()->IsLocked() ) {
- SUIT_MessageBox::warn1 ( desktop(),
- QObject::tr("WRN_WARNING"),
- QObject::tr("WRN_STUDY_LOCKED"),
- QObject::tr("BUT_OK") );
+ SUIT_MessageBox::warning( desktop(),
+ QObject::tr("WRN_WARNING"),
+ QObject::tr("WRN_STUDY_LOCKED") );
return;
}
}
}
+/*!Check the application on closing.
+ * \retval true if possible, else false
+ */
+bool SalomeApp_Application::isPossibleToClose( bool& closePermanently )
+{
+ return LightApp_Application::isPossibleToClose( closePermanently );
+}
+
/*! Check if the study is locked */
void SalomeApp_Application::onCloseDoc( bool ask )
{
if (study != NULL) {
_PTR(Study) stdDS = study->studyDS();
if(stdDS && stdDS->IsStudyLocked()) {
- if ( SUIT_MessageBox::warn2( desktop(),
- QObject::tr( "WRN_WARNING" ),
- QObject::tr( "CLOSE_LOCKED_STUDY" ),
- QObject::tr( "BUT_YES" ),
- QObject::tr( "BUT_NO" ),
- SUIT_YES,
- SUIT_NO,
- SUIT_NO ) == SUIT_NO ) return;
+ if ( SUIT_MessageBox::question( desktop(),
+ QObject::tr( "WRN_WARNING" ),
+ QObject::tr( "CLOSE_LOCKED_STUDY" ),
+ SUIT_MessageBox::Yes | SUIT_MessageBox::No,
+ SUIT_MessageBox::No) == SUIT_MessageBox::No ) return;
}
}
/*!Private SLOT. */
void SalomeApp_Application::onOpenWith()
{
- QApplication::setOverrideCursor( Qt::waitCursor );
+ QApplication::setOverrideCursor( Qt::WaitCursor );
SALOME_ListIO aList;
LightApp_SelectionMgr* mgr = selectionMgr();
mgr->selectedObjects(aList);
public:
DumpStudyFileDlg( QWidget* parent ) : SUIT_FileDlg( parent, false, true, true )
{
- QHBox* hB = new QHBox( this );
- myPublishChk = new QCheckBox( tr("PUBLISH_IN_STUDY"), hB );
- mySaveGUIChk = new QCheckBox( tr("SAVE_GUI_STATE"), hB );
- QPushButton* pb = new QPushButton(this);
- addWidgets( new QLabel("", this), hB, pb );
- pb->hide();
+ QGridLayout* grid = ::qobject_cast<QGridLayout*>( layout() );
+ if ( grid )
+ {
+ QWidget *hB = new QWidget( this );
+ myPublishChk = new QCheckBox( tr("PUBLISH_IN_STUDY") );
+ mySaveGUIChk = new QCheckBox( tr("SAVE_GUI_STATE") );
+
+ QHBoxLayout *layout = new QHBoxLayout;
+ layout->addWidget(myPublishChk);
+ layout->addWidget(mySaveGUIChk);
+ hB->setLayout(layout);
+
+ QPushButton* pb = new QPushButton(this);
+
+ int row = grid->rowCount();
+ grid->addWidget( new QLabel("", this), row, 0 );
+ grid->addWidget( hB, row, 1, 1, 3 );
+ grid->addWidget( pb, row, 5 );
+
+ pb->hide();
+ }
}
QCheckBox* myPublishChk;
QCheckBox* mySaveGUIChk;
aFilters.append( tr( "PYTHON_FILES_FILTER" ) );
DumpStudyFileDlg* fd = new DumpStudyFileDlg( desktop() );
- fd->setCaption( tr( "TOT_DESK_FILE_DUMP_STUDY" ) );
+ fd->setWindowTitle( tr( "TOT_DESK_FILE_DUMP_STUDY" ) );
fd->setFilters( aFilters );
fd->myPublishChk->setChecked( true );
fd->mySaveGUIChk->setChecked( true );
ip->setDumpPython(appStudy->studyDS());
savePoint = SalomeApp_VisualState( this ).storeState(); //SRN: create a temporary save point
}
- bool res = aStudy->DumpStudy( aFileInfo.dirPath( true ).latin1(), aFileInfo.baseName().latin1(), toPublish);
+ bool res = aStudy->DumpStudy( aFileInfo.absolutePath().toStdString(),
+ aFileInfo.baseName().toStdString(), toPublish);
if ( toSaveGUI )
appStudy->removeSavePoint(savePoint); //SRN: remove the created temporary save point.
if ( !res )
- SUIT_MessageBox::warn1 ( desktop(),
- QObject::tr("WRN_WARNING"),
- tr("WRN_DUMP_STUDY_FAILED"),
- QObject::tr("BUT_OK") );
+ SUIT_MessageBox::warning( desktop(),
+ QObject::tr("WRN_WARNING"),
+ tr("WRN_DUMP_STUDY_FAILED") );
}
}
_PTR(Study) aStudy = appStudy->studyDS();
if ( aStudy->GetProperties()->IsLocked() ) {
- SUIT_MessageBox::warn1 ( desktop(),
- QObject::tr("WRN_WARNING"),
- QObject::tr("WRN_STUDY_LOCKED"),
- QObject::tr("BUT_OK") );
+ SUIT_MessageBox::warning( desktop(),
+ QObject::tr("WRN_WARNING"),
+ QObject::tr("WRN_STUDY_LOCKED") );
return;
}
{
QString command = QString("execfile(\"%1\")").arg(aFile);
- PythonConsole* pyConsole = pythonConsole();
+ PyConsole_Console* pyConsole = pythonConsole();
if ( pyConsole )
pyConsole->exec( command );
if ( study ) {
SalomeApp_VisualState( this ).storeState();
updateSavePointDataObjects( study );
- objectBrowser()->updateTree( study->root() );
+ // temporary commented
+ //objectBrowser()->updateTree( study->root() );
}
updateActions();
}
if ( flag == WT_ObjectBrowser )
{
- OB_Browser* ob = (OB_Browser*)wid;
+ // temporary commented
+ /*OB_Browser* ob = (OB_Browser*)wid;
ob->setUpdater( new SalomeApp_Updater() );
- connect( ob->listView(), SIGNAL( doubleClicked( QListViewItem* ) ), this, SLOT( onDblClick( QListViewItem* ) ) );
+ connect( ob->listView(), SIGNAL( doubleClicked( QListViewItem* ) ), this, SLOT( onDblClick( QListViewItem* ) ) );*/
bool autoSize = resMgr->booleanValue( "ObjectBrowser", "auto_size", false ),
autoSizeFirst = resMgr->booleanValue( "ObjectBrowser", "auto_size_first", true );
for ( int i = SalomeApp_DataObject::CT_Value; i <= SalomeApp_DataObject::CT_RefEntry; i++ )
{
- ob->addColumn( tr( QString().sprintf( "OBJ_BROWSER_COLUMN_%d", i ) ), i );
+ // temporary commented
+ /*ob->addColumn( tr( QString().sprintf( "OBJ_BROWSER_COLUMN_%d", i ) ), i );
ob->setColumnShown( i, resMgr->booleanValue( "ObjectBrowser",
- QString().sprintf( "visibility_column_%d", i ), true ) );
+ QString().sprintf( "visibility_column_%d", i ), true ) );*/
}
- ob->setWidthMode( autoSize ? QListView::Maximum : QListView::Manual );
+ // temporary commented
+ /*ob->setWidthMode( autoSize ? QListView::Maximum : QListView::Manual );
ob->listView()->setColumnWidthMode( 0, autoSizeFirst ? QListView::Maximum : QListView::Manual );
- ob->resize( desktop()->width()/3, ob->height() );
+ ob->resize( desktop()->width()/3, ob->height() );*/
}
else if ( flag == WT_PyConsole )
{
- PythonConsole* pyCons = new PythonConsole( desktop(), new SalomeApp_PyInterp() );
- pyCons->setCaption( tr( "PYTHON_CONSOLE" ) );
+ PyConsole_Console* pyCons = new PyConsole_Console( desktop(), new SalomeApp_PyInterp() );
+ pyCons->setWindowTitle( tr( "PYTHON_CONSOLE" ) );
wid = pyCons;
pyCons->resize( pyCons->width(), desktop()->height()/4 );
//pyCons->connectPopupRequest(this, SLOT(onConnectPopupRequest(SUIT_PopupClient*, QContextMenuEvent*)));
int defCols = pref->addPreference( tr( "PREF_GROUP_DEF_COLUMNS" ), obTab );
for ( int i = SalomeApp_DataObject::CT_Value; i <= SalomeApp_DataObject::CT_RefEntry; i++ )
{
- pref->addPreference( tr( QString().sprintf( "OBJ_BROWSER_COLUMN_%d", i ) ), defCols,
+ pref->addPreference( tr( QString().sprintf( "OBJ_BROWSER_COLUMN_%d", i ).toLatin1() ), defCols,
LightApp_Preferences::Bool, "ObjectBrowser", QString().sprintf( "visibility_column_%d", i ) );
}
pref->setItemProperty( defCols, "columns", 1 );
if ( activeStudy() )
{
- QString sName = SUIT_Tools::file( activeStudy()->studyName().stripWhiteSpace(), false );
+ QString sName = SUIT_Tools::file( activeStudy()->studyName().trimmed(), false );
if ( !sName.isEmpty() ) {
SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(activeStudy());
if ( study ) {
}
}
- desktop()->setCaption( aTitle );
+ desktop()->setWindowTitle( aTitle );
+}
+
+int SalomeApp_Application::closeChoice( const QString& docName )
+{
+ int answer = SUIT_MessageBox::question( desktop(), tr( "APPCLOSE_CAPTION" ), tr( "APPCLOSE_DESCRIPTION" ).arg( docName ),
+ tr ("APPCLOSE_SAVE"), tr ("APPCLOSE_CLOSE"),
+ tr ("APPCLOSE_UNLOAD"), tr ("APPCLOSE_CANCEL"), 1 );
+
+ int res = CloseCancel;
+ if ( answer == 1 )
+ res = CloseSave;
+ else if ( answer == 2 )
+ res = CloseDiscard;
+ else if ( answer == 3 )
+ res = CloseUnload;
+
+ return res;
+}
+
+bool SalomeApp_Application::closeAction( const int choice, bool& closePermanently )
+{
+ bool res = true;
+ switch( choice )
+ {
+ case CloseSave:
+ if ( activeStudy()->isSaved() )
+ onSaveDoc();
+ else if ( !onSaveAsDoc() )
+ res = false;
+ break;
+ case CloseDiscard:
+ break;
+ case CloseUnload:
+ closePermanently = false;
+ break;
+ case CloseCancel:
+ default:
+ res = false;
+ }
+
+ return res;
}
/*!Gets CORBA::ORB_var*/
}
/*!Insert items in popup, which necessary for current application*/
-void SalomeApp_Application::contextMenuPopup( const QString& type, QPopupMenu* thePopup, QString& title )
+void SalomeApp_Application::contextMenuPopup( const QString& type, QMenu* thePopup, QString& title )
{
LightApp_Application::contextMenuPopup( type, thePopup, title );
- OB_Browser* ob = objectBrowser();
+ // temporary commented
+ /*OB_Browser* ob = objectBrowser();
if ( !ob || type != ob->popupClientType() )
- return;
+ return;*/
// Get selected objects
SALOME_ListIO aList;
// add GUI state commands: restore, rename
if ( aList.Extent() == 1 && aList.First()->hasEntry() &&
QString( aList.First()->getEntry() ).startsWith( tr( "SAVE_POINT_DEF_NAME" ) ) ) {
- thePopup->insertSeparator();
- thePopup->insertItem( tr( "MEN_RESTORE_VS" ), this, SLOT( onRestoreGUIState() ) );
- thePopup->insertItem( tr( "MEN_RENAME_VS" ), this, SLOT( onRenameGUIState() ) );
- thePopup->insertItem( tr( "MEN_DELETE_VS" ), this, SLOT( onDeleteGUIState() ) );
+ thePopup->addSeparator();
+ thePopup->addAction( tr( "MEN_RESTORE_VS" ), this, SLOT( onRestoreGUIState() ) );
+ thePopup->addAction( tr( "MEN_RENAME_VS" ), this, SLOT( onRenameGUIState() ) );
+ thePopup->addAction( tr( "MEN_DELETE_VS" ), this, SLOT( onDeleteGUIState() ) );
}
// "Delete reference" item should appear only for invalid references
// Add "Delete reference" item to popup
if ( isInvalidRefs )
{
- thePopup->insertSeparator();
- thePopup->insertItem( tr( "MEN_DELETE_INVALID_REFERENCE" ), this, SLOT( onDeleteInvalidReferences() ) );
+ thePopup->addSeparator();
+ thePopup->addAction( tr( "MEN_DELETE_INVALID_REFERENCE" ), this, SLOT( onDeleteInvalidReferences() ) );
return;
}
if (currentModule && currentModule->moduleName() == aModuleTitle)
return;
if ( !aModuleTitle.isEmpty() )
- thePopup->insertItem( tr( "MEN_OPENWITH" ).arg( aModuleTitle ), this, SLOT( onOpenWith() ) );
+ thePopup->addAction( tr( "MEN_OPENWITH" ).arg( aModuleTitle ), this, SLOT( onOpenWith() ) );
}
/*!Update obect browser:
if ( aComponent->ComponentDataType() == "Interface Applicative" )
continue; // skip the magic "Interface Applicative" component
- OB_Browser* ob = static_cast<OB_Browser*>( getWindow( WT_ObjectBrowser ));
+ // temporary commented
+ /*OB_Browser* ob = static_cast<OB_Browser*>( getWindow( WT_ObjectBrowser ));
const bool isAutoUpdate = ob->isAutoUpdate();
- ob->setAutoUpdate( false );
+ ob->setAutoUpdate( false );*/
SalomeApp_DataModel::synchronize( aComponent, study );
- ob->setAutoUpdate( isAutoUpdate );
+ // temporary commented
+ /*ob->setAutoUpdate( isAutoUpdate );*/
//SalomeApp_DataModel::BuildTree( aComponent, study->root(), study, /*skipExisitng=*/true );
}
}
void SalomeApp_Application::onRegDisplay()
{
CORBA::ORB_var anOrb = orb();
- ToolsGUI_RegWidget* regWnd = ToolsGUI_RegWidget::GetRegWidget( anOrb, desktop(), "Registry" );
+ ToolsGUI_RegWidget* regWnd = ToolsGUI_RegWidget::GetRegWidget( anOrb, desktop() );
regWnd->show();
regWnd->raise();
- regWnd->setActiveWindow();
+ regWnd->activateWindow();
}
/*!find original object by double click on item */
void SalomeApp_Application::onDblClick( QListViewItem* it )
{
- OB_ListItem* item = dynamic_cast<OB_ListItem*>( it );
+ // temporary commented
+ /*OB_ListItem* item = dynamic_cast<OB_ListItem*>( it );
SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>( activeStudy() );
if( study && item )
break;
}
}
- }
+ }*/
}
/*!
if ( !newName.isNull() && !newName.isEmpty() ) {
study->setNameOfSavePoint( savePoint, newName );
updateSavePointDataObjects( study );
- objectBrowser()->updateTree( study->root() );
+ // temporary commented
+ //objectBrowser()->updateTree( study->root() );
}
}
{
LightApp_Application::onStudySaved( study );
- if ( objectBrowser() ) {
+ // temporary commented
+ /*if ( objectBrowser() ) {
updateSavePointDataObjects( dynamic_cast<SalomeApp_Study*>( study ) );
objectBrowser()->updateTree( study->root() );
- }
+ }*/
}
/*!Called on Open study operation*/
{
LightApp_Application::onStudyOpened( study );
- if ( objectBrowser() ) {
+ // temporary commented
+ /*if ( objectBrowser() ) {
updateSavePointDataObjects( dynamic_cast<SalomeApp_Study*>( study ) );
objectBrowser()->updateTree( study->root() );
- }
-}
-
-/*! utility function. returns true if list view item that correspond to given SUIT_DataObject is open.
- only first level items are traversed */
-bool isListViewItemOpen( QListView* lv, const SUIT_DataObject* dobj )
-{
- if ( !lv || !dobj )
- return false;
-
- QListViewItem* item = lv->firstChild();
- while ( item ) {
- OB_ListItem* ob_item = dynamic_cast<OB_ListItem*>( item );
- if ( ob_item && ob_item->dataObject() == dobj )
- return ob_item->isOpen();
- item = item->nextSibling();
- }
- return false;
+ }*/
}
/*! updateSavePointDataObjects: syncronize data objects that correspond to save points (gui states)*/
void SalomeApp_Application::updateSavePointDataObjects( SalomeApp_Study* study )
{
- OB_Browser* ob = objectBrowser();
+ // temporary commented
+ //OB_Browser* ob = objectBrowser();
- if ( !study || !ob )
+ if ( !study /*|| !ob */) // temporary commented
return;
// find GUI states root object
// delete DataObjects that are still in the map -- their IDs were not found in data model
for ( QMap<int,SalomeApp_SavePointObject*>::Iterator it = mapDO.begin(); it != mapDO.end(); ++it )
- delete it.data();
+ delete it.value();
}
/*! Check data object */
void SalomeApp_Application::onDesktopMessage( const QString& message )
{
// update object browser
- if ( message.lower() == "updateobjectbrowser" ||
- message.lower() == "updateobjbrowser" )
+ if ( message.toLower() == "updateobjectbrowser" ||
+ message.toLower() == "updateobjbrowser" )
updateObjectBrowser();
}
#include "SalomeApp.h"
#include <LightApp_Application.h>
-#include <qmap.h>
-
#include <CORBA.h>
#include <SALOMEconfig.h>
#include "SALOMEDSClient.hxx"
-class QAction;
-class QComboBox;
-class QDockWindow;
-
class LightApp_Preferences;
-class SalomeApp_Module;
class SalomeApp_Study;
class SALOME_LifeCycleCORBA;
-class QListViewItem;
+class QListViewItem;//? waiting for object browser porting
#ifdef WIN32
#pragma warning( disable:4251 )
enum { MenuToolsId = 5 };
enum { DumpStudyId = LightApp_Application::UserID, LoadScriptId, PropertiesId,
CatalogGenId, RegDisplayId, SaveGUIStateId, FileLoadId, UserID };
+ enum { CloseUnload = STD_Application::CloseCancel+1 };
public:
SalomeApp_Application();
virtual void start();
- virtual void contextMenuPopup( const QString&, QPopupMenu*, QString& );
+ virtual void contextMenuPopup( const QString&, QMenu*, QString& );
virtual bool checkDataObject(LightApp_DataObject* theObj);
SUIT_ViewManager* newViewManager(const QString&);
void updateSavePointDataObjects( SalomeApp_Study* );
+
+ virtual bool isPossibleToClose( bool& );
public slots:
virtual bool onOpenDoc( const QString& );
virtual void createPreferences( LightApp_Preferences* );
virtual void updateDesktopTitle();
+
+ virtual bool closeAction( const int, bool& );
+ virtual int closeChoice( const QString& );
private slots:
void onDeleteInvalidReferences();
void onCatalogGen();
void onRegDisplay();
void onOpenWith();
-
};
#ifdef WIN32
//
#include "SalomeApp_CheckFileDlg.h"
-#include <qcheckbox.h>
-#include <qlabel.h>
-#include <qpushbutton.h>
+#include <QCheckBox>
+#include <QLabel>
+#include <QPushButton>
+#include <QGridLayout>
/*!
Constructor
SalomeApp_CheckFileDlg::SalomeApp_CheckFileDlg( QWidget* parent, bool open, const QString& theCheckBoxName, bool showQuickDir, bool modal) :
SUIT_FileDlg( parent, open, showQuickDir, modal )
{
- myCheckBox = new QCheckBox( theCheckBoxName, this );
- QLabel* label = new QLabel("", this);
- QPushButton* pb = new QPushButton(this);
- addWidgets( label, myCheckBox, pb );
- pb->hide();
+ QGridLayout* grid = ::qobject_cast<QGridLayout*>( layout() );
+ if ( grid )
+ {
+ myCheckBox = new QCheckBox( theCheckBoxName, this );
+ QLabel* label = new QLabel("", this);
+ QPushButton* pb = new QPushButton(this);
+
+ int row = grid->rowCount();
+ grid->addWidget( label, row, 0 );
+ grid->addWidget( myCheckBox, row, 1 );
+ grid->addWidget( pb, row, 2 );
+
+ pb->hide();
+ }
}
/*!
#include "SalomeApp_DataObject.h"
#include "SalomeApp_Module.h"
#include "SalomeApp_Application.h"
-#include "SalomeApp_Engine_i.hxx"
#include "LightApp_RootObject.h"
#include <CAM_DataObject.h>
-#include <SUIT_Application.h>
-#include <SUIT_ResourceMgr.h>
-#include <SUIT_Session.h>
#include <SUIT_TreeSync.h>
#include <SUIT_DataObjectIterator.h>
bool isEqual( const kerPtr&, const suitPtr& ) const;
kerPtr nullSrc() const;
suitPtr nullTrg() const;
- void children( const kerPtr&, QValueList<kerPtr>& ) const;
- void children( const suitPtr&, QValueList<suitPtr>& ) const;
+ void children( const kerPtr&, QList<kerPtr>& ) const;
+ void children( const suitPtr&, QList<suitPtr>& ) const;
suitPtr parent( const suitPtr& ) const;
bool isCorrect( const kerPtr& ) const;
void updateItem( const kerPtr&, const suitPtr& ) const;
{
DataObjectList ch;
parent->children( ch );
- int pos = ch.find( after );
+ int pos = ch.indexOf( after );
if( pos>=0 )
parent->insertChild( nitem, pos+1 );
else
\param obj - kernel object
\param ch - list to be filled
*/
-void SalomeApp_DataModelSync::children( const kerPtr& obj, QValueList<kerPtr>& ch ) const
+void SalomeApp_DataModelSync::children( const kerPtr& obj, QList<kerPtr>& ch ) const
{
ch.clear();
_PTR(ChildIterator) it ( myStudy->NewChildIterator( obj ) );
\param p - SUIT object
\param ch - list to be filled
*/
-void SalomeApp_DataModelSync::children( const suitPtr& p, QValueList<suitPtr>& ch ) const
+void SalomeApp_DataModelSync::children( const suitPtr& p, QList<suitPtr>& ch ) const
{
DataObjectList l;
if( p )
{
p->children( l );
ch.clear();
- for( SUIT_DataObject* o = l.first(); o; o = l.next() )
- ch.append( o );
+ QListIterator<suitPtr> it( ch );
+ while ( it.hasNext() )
+ ch.append( it.next() );
}
}
{
QString marg; marg.fill( ' ', 3*it.depth() );
QString nnn = "%1 '%2'";
- qDebug( nnn.arg( marg ).arg( it.current()->name() ) );
+ qDebug( nnn.arg( marg ).arg( it.current()->name() ).toLatin1() );
}
}
return true; // Probably nothing to load
_PTR(Study) aStudy ( aDoc->studyDS() ); // shared_ptr cannot be used here
- _PTR(SComponent) aSComp ( aStudy->FindComponentID( std::string( anId.latin1() ) ) );
+ _PTR(SComponent) aSComp ( aStudy->FindComponentID( std::string( anId.toLatin1() ) ) );
if ( aSComp )
updateTree( aSComp, aDoc );
QString anId = getRootEntry( aSStudy );
if ( !anId.isEmpty() ){ // if nothing is published in the study for this module -> do nothing
_PTR(Study) aStudy ( aSStudy->studyDS() );
- sobj = aStudy->FindComponentID( std::string( anId.latin1() ) );
+ sobj = aStudy->FindComponentID( std::string( anId.toLatin1() ) );
}
}
}
if ( aSStudy ) {
_PTR(Study) aStudy ( aSStudy->studyDS() );
// modelRoot->object() cannot be reused here: it is about to be deleted by buildTree() soon
- sobj = aStudy->FindComponentID( std::string( modelRoot->entry().latin1() ) );
+ sobj = aStudy->FindComponentID( std::string( modelRoot->entry().toLatin1() ) );
}
}
}
anEntry = anObj->entry();
}
else if ( study && study->studyDS() ) { // this works even if <myRoot> is null
- _PTR(SComponent) aSComp( study->studyDS()->FindComponent( module()->name() ) );
+ _PTR(SComponent) aSComp( study->studyDS()->FindComponent( module()->name().toStdString() ) );
if ( aSComp )
anEntry = aSComp->GetID().c_str();
}
class SalomeApp_Module;
class SalomeApp_Study;
-class SalomeApp_DataObject;
+class SUIT_DataObject;
+class LightApp_DataObject;
// Class : SalomeApp_DataModel
/// Description : Base class of data model
#include <SUIT_Application.h>
#include <SUIT_ResourceMgr.h>
-#include <SUIT_DataObjectKey.h>
-#include <qobject.h>
-
-#include <SALOMEDSClient_AttributeReal.hxx>
-#include <SALOMEDSClient_AttributeInteger.hxx>
-#include <SALOMEDSClient_AttributeComment.hxx>
-#include <SALOMEDSClient_AttributeTableOfReal.hxx>
-#include <SALOMEDSClient_AttributeTableOfInteger.hxx>
+#include <QObject>
/*!Constructor. Initialize by \a parent*/
SalomeApp_DataObject::SalomeApp_DataObject( SUIT_DataObject* parent )
switch ( id )
{
case CT_Value:
-#ifndef WNT
+#ifndef WIN32
if ( componentObject() != this )
#else
if ( componentObject() != (SUIT_DataObject*)this )
//
#include "SalomeApp_EventFilter.h"
-#include <SALOME_Event.hxx>
+#include <SALOME_Event.h>
-#include <qapplication.h>
+#include <QApplication>
SalomeApp_EventFilter* SalomeApp_EventFilter::myFilter = NULL;
{
if ( e->type() == SALOME_EVENT )
{
- SALOME_Event* aSE = (SALOME_Event*)((QCustomEvent*)e)->data();
+ SALOME_Event* aSE = (SALOME_Event*)((SALOME_CustomEvent*)e)->data();
processEvent(aSE);
- ((QCustomEvent*)e)->setData( 0 );
+ ((SALOME_CustomEvent*)e)->setData( 0 );
return true;
}
return QObject::eventFilter( o, e );
#define SALOMEAPP_EVENTFILTER_H
#include "SalomeApp.h"
-#include <qobject.h>
+#include <QObject>
-#if defined WNT
+#if defined WIN32
#pragma warning( disable: 4251 )
#endif
static SalomeApp_EventFilter* myFilter;
};
-#if defined WNT
+#if defined WIN32
#pragma warning( default: 4251 )
#endif
#include <stdexcept>
#include <exception>
-#include <qstring.h>
+#include <QString>
#if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
#include <Standard_ErrorHandler.hxx>
{
showMessage( title, QString( e.GetMessageString() ) );
}
-#ifndef WNT
+#ifndef WIN32
catch(...)
{
showMessage( title, "Unknown Exception" );
#include "SalomeApp_ImportOperation.h"
#include <SUIT_Application.h>
-#ifndef WNT
+#ifndef WIN32
using namespace std;
#endif
#include "SUIT_ResourceMgr.h"
#include "SUIT_Session.h"
-#include <qheader.h>
-#include <qvalidator.h>
-#include <qapplication.h>
-#include <qtoolbutton.h>
+#include <QValidator>
+#include <QToolButton>
+#include <QPixmap>
+#include <QHeaderView>
+#include <QKeyEvent>
+
+#include <TColStd_ListOfInteger.hxx>
+#include <TColStd_ListOfReal.hxx>
#include <TColStd_ListIteratorOfListOfInteger.hxx>
#include <TColStd_ListIteratorOfListOfReal.hxx>
-#include "utilities.h"
-
using namespace std;
+using namespace Qt;
+
/*!
Used for resizing editing widget
*/
{
if (!theItem)
return;
- QListView* aListView = theItem->listView();
+ QTreeWidget* aListView = theItem->treeWidget();
int anEditColumn = theItem->getEditedColumn();
if (anEditColumn < 0)
return;
int aX = 0, aY = 0, aW = 0, aH = 0;
- QRect aRect = aListView->itemRect(theItem);
- aListView->contentsToViewport(aListView->header()->sectionPos(anEditColumn), 0, aX, aY);
+ QRect aRect = aListView->visualItemRect(theItem);
+ aX = aListView->header()->sectionViewportPosition(anEditColumn);
if (aX < 0)
aX = 0; // THIS CAN BE REMOVED
QSize aSize = theWidget->getControl()->sizeHint();
- aH = QMAX(aSize.height() , aRect.height() );
+ aH = qMax(aSize.height() , aRect.height() );
aY = aRect.y() - ((aH - aRect.height()) / 2);
//aW = aListView->columnWidth(anEditColumn); // CAN SUBSTITUTE NEXT 3 ROWS
aW = aListView->viewport()->width() - aX;
Constructor
*/
SalomeApp_ListView::SalomeApp_ListView( QWidget* parent )
-: QtxListView( parent )
+ : QTreeWidget/*QtxListView*/( parent )
{
myMouseEnabled = true;
myEditingEnabled = false;
- setSelectionMode(Single);
- setSorting(-1);
+ setSelectionMode(QAbstractItemView::SingleSelection);
setRootIsDecorated(false);
setAllColumnsShowFocus(false);
// header()->setClickEnabled(false);
- header()->setMovingEnabled(false);
+ header()->setMovable(false);
myEditedItem = 0;
myEdit = 0;
viewport()->installEventFilter(this);
- connect(this, SIGNAL(selectionChanged()),
+ connect(this, SIGNAL(itemSelectionChanged()),
this, SLOT(onSelectionChanged()));
connect(header(), SIGNAL(sizeChange(int, int, int)),
this, SLOT(onHeaderSizeChange(int, int, int)));
{
// temporary disconnecting selection changed SIGNAL
blockSignals(true);
- SalomeApp_ListViewItem* aRoot = (SalomeApp_ListViewItem*)firstChild();
+ QTreeWidgetItemIterator it( this );
+ SalomeApp_ListViewItem* aRoot = (SalomeApp_ListViewItem*)(*it);
if (aRoot)
aRoot->updateAllLevels();
- updateContents();
+ update( contentsRect() );//updateContents();
// connecting again selection changed SIGNAL
blockSignals(false);
- emit selectionChanged();
+ emit itemSelectionChanged();
}
/*!
{
// temporary disconnecting selection changed SIGNAL
blockSignals(true);
- SalomeApp_ListViewItem* aChild = (SalomeApp_ListViewItem*)selectedItem();
+ SalomeApp_ListViewItem* aChild = (SalomeApp_ListViewItem*)(selectedItems().first());
if (aChild)
aChild->updateAllLevels();
- updateContents();
+ update( contentsRect() );//updateContents();
// connecting again selection changed SIGNAL
blockSignals(false);
- emit selectionChanged();
+ emit itemSelectionChanged();
}
/*!
/*!
Fills popup menu with items
*/
-void SalomeApp_ListView::contextMenuPopup( QPopupMenu* aPopup )
+void SalomeApp_ListView::contextMenuPopup( QMenu* aPopup )
{
if (aPopup) {
// add items here...
myEdit = 0;
myEditedItem = 0;
}
- QListView::clear();
+ QTreeWidget::clear();
}
/*!
!isMouseEnabled())
return true;
else
- return QListView::eventFilter(object, event);
+ return QTreeWidget::eventFilter(object, event);
}
/*!
myEdit = 0;
if (myEditedItem && !myEditedItem->isAccepted()) {
delete myEditedItem;
- updateContents();
+ update( contentsRect() );//updateContents();
}
myEditedItem = 0;
}
// editing is allowed in Single Selection Mode only
- if (selectionMode() != Single || !isEnableEditing())
+ if (selectionMode() != QAbstractItemView::SingleSelection || !isEnableEditing())
return;
- SalomeApp_ListViewItem* anItem = (SalomeApp_ListViewItem*)selectedItem();
+ SalomeApp_ListViewItem* anItem = (SalomeApp_ListViewItem*)(selectedItems().first());
if (anItem) {
if (!anItem->isEditable())
return;
*/
void SalomeApp_ListView::resizeEvent( QResizeEvent * e)
{
- QListView::resizeEvent(e);
- int aW = columnWidth(columns()-1);
- int aX = header()->sectionPos(columns()-1);
+ QTreeWidget::resizeEvent(e);
+ int aW = columnWidth(columnCount()-1);
+ int aX = header()->sectionPosition(columnCount()-1);
if (aW < width() - frameWidth() * 2 - aX - 1)
- setColumnWidth(columns()-1, width() - frameWidth() * 2 - aX - 1);
- updateContents();
+ setColumnWidth(columnCount()-1, width() - frameWidth() * 2 - aX - 1);
+ update( contentsRect() );//updateContents();
}
/*!
*/
void SalomeApp_ListView::onHeaderSizeChange(int, int, int)
{
- int aW = columnWidth(columns()-1);
- int aX = header()->sectionPos(columns()-1);
+ int aW = columnWidth(columnCount()-1);
+ int aX = header()->sectionPosition(columnCount()-1);
if (aW < width() - frameWidth() * 2 - aX - 1)
- setColumnWidth(columns()-1, width() - frameWidth() * 2 - aX - 1);
+ setColumnWidth(columnCount()-1, width() - frameWidth() * 2 - aX - 1);
}
/*!
*/
void SalomeApp_ListView::viewportPaintEvent(QPaintEvent* e)
{
- QListView::viewportPaintEvent(e);
+ QTreeWidget::paintEvent(e);
if (myEditedItem && myEdit) {
computeEditGeometry(myEditedItem, myEdit);
}
\retval valid rect in success
*/
QRect SalomeApp_ListView::tip(QPoint aPos,
- QString& aText,
- QRect& dspRect,
- QFont& dspFnt) const
+ QString& aText,
+ QRect& dspRect,
+ QFont& dspFnt) const
{
QRect result( -1, -1, -1, -1 );
SalomeApp_ListViewItem* aItem = (SalomeApp_ListViewItem*)itemAt( aPos );
if ( aItem ) {
- for (int i = 0; i < columns(); i++) {
+ for (int i = 0; i < columnCount(); i++) {
QRect aItemRect = aItem->itemRect(i);
QRect aTextRect = aItem->textRect(i);
if ( !aItem->text(i).isEmpty() &&
Constructor
*/
SalomeApp_ListViewItem::SalomeApp_ListViewItem(SalomeApp_ListView* parent) :
-QListViewItem( parent )
-{
- init();
-}
-
-/*!
- Constructor
-*/
-SalomeApp_ListViewItem::SalomeApp_ListViewItem(SalomeApp_ListView* parent,
- SalomeApp_ListViewItem* after) :
-QListViewItem( parent, after )
+QTreeWidgetItem( parent )
{
init();
}
Constructor
*/
SalomeApp_ListViewItem::SalomeApp_ListViewItem(SalomeApp_ListView* parent,
- const QString& theName,
- const bool theEditable) :
-QListViewItem(parent, theName)
+ SalomeApp_ListViewItem* after) :
+QTreeWidgetItem( parent, after )
{
init();
- setEditable(theEditable);
}
/*!
Constructor
*/
SalomeApp_ListViewItem::SalomeApp_ListViewItem(SalomeApp_ListView* parent,
- const QString& theName,
- const QString& theValue,
- const bool theEditable) :
-QListViewItem(parent, theName, theValue)
+ const QStringList& theStrings,
+ const bool theEditable) :
+QTreeWidgetItem(parent, theStrings)
{
init();
setEditable(theEditable);
Constructor
*/
SalomeApp_ListViewItem::SalomeApp_ListViewItem(SalomeApp_ListViewItem* parent,
- const QString& theName,
- const bool theEditable) :
-QListViewItem(parent, theName)
+ const QStringList& theString,
+ const bool theEditable) :
+QTreeWidgetItem(parent, theString)
{
init();
setEditable(theEditable);
Constructor
*/
SalomeApp_ListViewItem::SalomeApp_ListViewItem(SalomeApp_ListViewItem* parent,
- SalomeApp_ListViewItem* after,
- const QString& theName,
- const bool theEditable) :
-QListViewItem(parent, after, theName)
+ SalomeApp_ListViewItem* after,
+ const QString& theName,
+ const bool theEditable) :
+QTreeWidgetItem(parent, after)
{
+ setData(0,Qt::DisplayRole,QVariant(theName));
init();
setEditable(theEditable);
}
Constructor
*/
SalomeApp_ListViewItem::SalomeApp_ListViewItem(SalomeApp_ListView* parent,
- SalomeApp_ListViewItem* after,
- const QString& theName,
- const bool theEditable) :
-QListViewItem(parent, after, theName)
-{
- init();
- setEditable(theEditable);
-}
-
-
-/*!
- Constructor
-*/
-SalomeApp_ListViewItem::SalomeApp_ListViewItem(SalomeApp_ListViewItem* parent,
- const QString& theName,
- const QString& theValue,
- const bool theEditable) :
-QListViewItem(parent, theName, theValue)
+ SalomeApp_ListViewItem* after,
+ const QString& theName,
+ const bool theEditable) :
+QTreeWidgetItem(parent, after)
{
+ setData(0,Qt::DisplayRole,QVariant(theName));
init();
setEditable(theEditable);
}
-
/*!
Constructor
*/
SalomeApp_ListViewItem::SalomeApp_ListViewItem(SalomeApp_ListViewItem* parent,
- SalomeApp_ListViewItem* after,
- const QString& theName,
- const QString& theValue,
- const bool theEditable) :
-QListViewItem(parent, after, theName, theValue)
-{
+ SalomeApp_ListViewItem* after,
+ const QString& theName,
+ const QString& theValue,
+ const bool theEditable) :
+QTreeWidgetItem(parent, after)
+{
+ setData(0,Qt::DisplayRole,QVariant(theName));
+ setData(1,Qt::DisplayRole,QVariant(theValue));
init();
setEditable(theEditable);
}
Constructor
*/
SalomeApp_ListViewItem::SalomeApp_ListViewItem(SalomeApp_ListView* parent,
- SalomeApp_ListViewItem* after,
- const QString& theName,
- const QString& theValue,
- const bool theEditable) :
-QListViewItem(parent, after, theName, theValue)
-{
+ SalomeApp_ListViewItem* after,
+ const QString& theName,
+ const QString& theValue,
+ const bool theEditable) :
+QTreeWidgetItem(parent, after)
+{
+ setData(0,Qt::DisplayRole,QVariant(theName));
+ setData(1,Qt::DisplayRole,QVariant(theValue));
init();
setEditable(theEditable);
}
myUserType = -1;
}
+/*!
+ Returns the depth of this item
+*/
+int SalomeApp_ListViewItem::depth() const
+{
+ int aDepth = 0;
+ QTreeWidgetItem* aParent = parent();
+ while ( aParent ) {
+ aParent = aParent->parent();
+ aDepth++;
+ }
+ return aDepth;
+}
+
/*!
\return text in the first column
*/
QString SalomeApp_ListViewItem::getName() const
{
- return ( listView()->columns() > 0 ) ? text(0) : QString("");
+ return ( treeWidget()->columnCount() > 0 ) ? text(0) : QString("");
}
/*!
UpdateType SalomeApp_ListViewItem::setName(const QString& theName)
{
UpdateType aNeedsUpdate = utCancel;
- if (listView()->columns() > 0) {
+ if (treeWidget()->columnCount() > 0) {
setText(0, theName);
aNeedsUpdate = utNone;
}
*/
QString SalomeApp_ListViewItem::getValue() const
{
- return ( listView()->columns() > 1 ) ? text(1) : QString("");
+ return ( treeWidget()->columnCount() > 1 ) ? text(1) : QString("");
}
/*!
UpdateType SalomeApp_ListViewItem::setValue(const QString& theValue)
{
UpdateType aNeedsUpdate = utCancel;
- if (listView()->columns() > 1) {
+ if (treeWidget()->columnCount() > 1) {
setText(1, theValue);
aNeedsUpdate = utNone;
}
*/
void SalomeApp_ListViewItem::openAllLevels()
{
- setOpen(true);
- SalomeApp_ListViewItem* aChild = (SalomeApp_ListViewItem*)firstChild();
+ setExpanded(true);
+ QTreeWidgetItemIterator it( this );
+ SalomeApp_ListViewItem* aChild = (SalomeApp_ListViewItem*)(*it);
while( aChild ) {
aChild->openAllLevels();
- aChild = (SalomeApp_ListViewItem*)(aChild->nextSibling());
+ ++it;
+ aChild = (SalomeApp_ListViewItem*)(*it);
}
}
*/
void SalomeApp_ListViewItem::updateAllLevels()
{
- SalomeApp_ListViewItem* aChild = (SalomeApp_ListViewItem*)firstChild();
+ QTreeWidgetItemIterator it( this );
+ SalomeApp_ListViewItem* aChild = (SalomeApp_ListViewItem*)(*it);
while( aChild ) {
aChild->updateAllLevels();
- aChild = (SalomeApp_ListViewItem*)(aChild->nextSibling());
+ ++it;
+ aChild = (SalomeApp_ListViewItem*)(*it);
}
}
*/
int SalomeApp_ListViewItem::getEditedColumn()
{
- return listView()->columns()-1;
+ return treeWidget()->columnCount()-1;
}
/*!
SalomeApp_EntityEdit* SalomeApp_ListViewItem::startEditing()
{
SalomeApp_EntityEdit* aWidget = 0;
- QListView* aListView = listView();
+ QTreeWidget* aListView = treeWidget();
if (aListView) {
if (!isEditable())
return 0;
QRect SalomeApp_ListViewItem::tipRect()
{
QRect aRect = QRect(-1, -1, -1, -1);
- QRect aItemRect = listView()->itemRect(this);
+ QRect aItemRect = treeWidget()->visualItemRect(this);
if ( !aItemRect.isValid() )
return aItemRect;
QString aTip = tipText();
if (!aTip.isEmpty()) {
QRect aRect0 = textRect(0);
- QFont aFont(listView()->font());
+ QFont aFont(treeWidget()->font());
QFontMetrics fm(aFont);
int iw = fm.width(aTip);
aRect = QRect(QPoint(aRect0.x() < 0 ? 0 : aRect0.x(),
*/
QRect SalomeApp_ListViewItem::textRect(const int column) const
{
- QRect aItemRect = listView()->itemRect( this );
+ QRect aItemRect = treeWidget()->visualItemRect( this );
if ( !aItemRect.isValid() )
return aItemRect;
- QFont aFont(listView()->font());
+ QFont aFont(treeWidget()->font());
QFontMetrics fm(aFont);
- int decorWidth = ( listView()->rootIsDecorated() ) ?
- ( listView()->treeStepSize() * (depth() + 1) ) :
- ( listView()->treeStepSize() * depth() );
- int pixmapWidth = ( pixmap(column) ) ?
- pixmap(column)->width() + listView()->itemMargin() * 2 :
- listView()->itemMargin();
+ int decorWidth = ( treeWidget()->rootIsDecorated() ) ?
+ ( treeWidget()->indentation() * (depth() + 1) ) :
+ ( treeWidget()->indentation() * depth() );
+ int pixmapWidth = ( !icon(column).isNull() ) ?
+ treeWidget()->iconSize().width() + 2 :
+ 1;
int prevWidth = 0;
for (int i = 0; i < column; i++)
- prevWidth += listView()->header()->sectionSize(i);
+ prevWidth += treeWidget()->header()->sectionSize(i);
int ix = prevWidth +
pixmapWidth +
((column == 0) ? decorWidth : 0);
int iy = aItemRect.y();
int iw = fm.width(text(column));
int ih = aItemRect.height();
- if (pixmap(column)) {
- iy += listView()->itemMargin();
- ih -= listView()->itemMargin() * 2;
+ if (!icon(column).isNull()) {
+ iy += 1;
+ ih -= 2;
}
- ix -= listView()->contentsX();
+ ix -= treeWidget()->contentsRect().left();
QRect theResult(QPoint(ix, iy), QSize(iw, ih));
return theResult;
*/
QRect SalomeApp_ListViewItem::itemRect(const int column) const
{
- QRect aItemRect = listView()->itemRect( this );
+ QRect aItemRect = treeWidget()->visualItemRect( this );
if ( !aItemRect.isValid() )
return aItemRect;
- QFont aFont(listView()->font());
+ QFont aFont(treeWidget()->font());
QFontMetrics fm(aFont);
- int decorWidth = ( listView()->rootIsDecorated() ) ?
- ( listView()->treeStepSize() * (depth() + 1) ) :
- ( listView()->treeStepSize() * depth() );
- int pixmapWidth = ( pixmap(column) ) ?
- pixmap(column)->width() + listView()->itemMargin() * 2 :
+ int decorWidth = ( treeWidget()->rootIsDecorated() ) ?
+ ( treeWidget()->indentation() * (depth() + 1) ) :
+ ( treeWidget()->indentation() * depth() );
+ int pixmapWidth = ( !icon(column).isNull() ) ?
+ treeWidget()->iconSize().width() + 2 :
0;
int prevWidth = 0;
for (int i = 0; i < column; i++)
- prevWidth += listView()->header()->sectionSize(i);
+ prevWidth += treeWidget()->header()->sectionSize(i);
int ix = prevWidth;
int iy = aItemRect.y();
int iw = pixmapWidth +
- listView()->itemMargin() * 2 +
+ 2 +
((column == 0) ? decorWidth : 0) +
fm.width(text(column));
int ih = aItemRect.height();
- ix -= listView()->contentsX();
+ ix -= treeWidget()->contentsRect().left();
QRect theResult(QPoint(ix, iy), QSize(iw, ih));
return theResult;
Constructor
*/
SalomeApp_ComboBox::SalomeApp_ComboBox(bool rw, QWidget* parent, const char* name) :
-QComboBox(rw, parent, name)
+QComboBox(parent)
{
+ setEditable( rw );
+ setObjectName( name );
}
/*!
int SalomeApp_ComboBox::findItem(const QString& theText)
{
for (int i = 0; i < count(); i++)
- if (text(i) == theText)
+ if (itemText(i) == theText)
return i;
return -1;
}
Adds item in combo box
*/
void SalomeApp_ComboBox::insertItem(const QString& theValue,
- int theIndex)
+ int theIndex)
{
if (duplicatesEnabled() || findItem(theValue) < 0)
- QComboBox::insertItem(theValue, theIndex);
+ QComboBox::insertItem(theIndex, theValue);
}
/*!
int aNum;
bool bOk;
for (int i = 0; i < count(); i++) {
- aNum = text(i).toInt(&bOk);
+ aNum = itemText(i).toInt(&bOk);
if (bOk) {
if (aNum > theValue || (aNum == theValue && duplicatesEnabled())) {
- insertItem(QString::number(theValue), i);
+ insertItem(QString::number(theValue),i);
return;
}
}
double aNum;
bool bOk;
for (int i = 0; i < count(); i++) {
- aNum = text(i).toDouble(&bOk);
+ aNum = itemText(i).toDouble(&bOk);
if (bOk) {
if (aNum > theValue || (aNum == theValue && duplicatesEnabled())) {
insertItem(QString::number(theValue), i);
myCombo->setSizePolicy(QSizePolicy(QSizePolicy::Expanding,
QSizePolicy::Fixed));
// no insertions
- myCombo->setInsertionPolicy(QComboBox::NoInsertion);
+ myCombo->setInsertPolicy(QComboBox::NoInsert);
// no duplicates enabled by default
myCombo->setDuplicatesEnabled(false);
aTopLayout->addWidget(myCombo);
if( mgr )
anIcon = mgr->loadPixmap( "STD", tr( "ICON_APPLY" ), false );
- myApplyBtn->setPixmap(anIcon);
+ myApplyBtn->setIcon(anIcon);
myApplyBtn->setEnabled(false);
myApplyBtn->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
myApplyBtn->setMinimumSize(16, 16);
QPixmap anIcon;
if( mgr )
anIcon = mgr->loadPixmap( "STD", tr( "ICON_CANCEL" ), false );
- myCancelBtn->setPixmap(anIcon);
+ myCancelBtn->setIcon(anIcon);
myCancelBtn->setEnabled(false);
myCancelBtn->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
myCancelBtn->setMinimumSize(16, 16);
if (myCombo) {
int aFound = myCombo->findItem(theText);
if (aFound >= 0) {
- myCombo->setCurrentItem(aFound);
+ myCombo->setCurrentIndex(aFound);
onTextChanged(theText);
}
}
if (theOrder == atTop)
aIndexAt = 0;
else if (theOrder == atBeforeCurrent && myCombo->count() > 0)
- aIndexAt = myCombo->currentItem();
+ aIndexAt = myCombo->currentIndex();
else if (theOrder == atAfterCurrent &&
myCombo->count() > 0 &&
- myCombo->currentItem() < myCombo->count()-1)
- aIndexAt = myCombo->currentItem() + 1;
+ myCombo->currentIndex() < myCombo->count()-1)
+ aIndexAt = myCombo->currentIndex() + 1;
myCombo->insertItem(theValue, aIndexAt);
}
if (theSetCurrent)
myEdit->setFocus();
//myEdit->selectAll();
}
- else if (myCombo && myCombo->editable()) {
+ else if (myCombo && myCombo->isEditable()) {
myCombo->setFocus();
//myCombo->lineEdit()->selectAll();
}
#ifndef SALOMEAPP_LISTVIEW_H
#define SALOMEAPP_LISTVIEW_H
-#include <QtxListView.h>
+//#include <QtxListView.h>
-#include <qlist.h>
-#include <qstring.h>
-#include <qpixmap.h>
-#include <qlineedit.h>
-#include <qcombobox.h>
+#include <SUIT_PopupClient.h>
-//VRV: porting on Qt 3.0.5
-#if QT_VERSION >= 0x030005
-#include <qtoolbutton.h>
-#endif
-//VRV: porting on Qt 3.0.5
+#include <QTreeWidget>
+#include <QTreeWidgetItem>
+#include <QString>
+#include <QLineEdit>
+#include <QComboBox>
-#include <TColStd_ListOfInteger.hxx>
-#include <TColStd_ListOfReal.hxx>
+class QToolButton;
-#include <SUIT_PopupClient.h>
+class TColStd_ListOfInteger;
+class TColStd_ListOfReal;
// enumeration for ListView updating mode
enum UpdateType {
\class SalomeApp_ListView
parent class for Data Viewer and Properties Viewer
*/
-class SalomeApp_ListView : public QtxListView , public SUIT_PopupClient {
+class SalomeApp_ListView : public QTreeWidget/*QtxListView*/ , public SUIT_PopupClient {
Q_OBJECT
// fills popup with items
virtual QString popupClientType() const;
- virtual void contextMenuPopup( QPopupMenu* );
+ virtual void contextMenuPopup( QMenu* );
// setting editing of items availbale/not available
void enableEditing(bool theFlag);
QString myString;
};
-class SalomeApp_ListViewItem : public QListViewItem
+class SalomeApp_ListViewItem : public QTreeWidgetItem
{
public:
SalomeApp_ListViewItem( SalomeApp_ListView* );
SalomeApp_ListViewItem( SalomeApp_ListView*,
SalomeApp_ListViewItem* );
SalomeApp_ListViewItem( SalomeApp_ListView*,
- const QString&,
- const bool = false );
- SalomeApp_ListViewItem( SalomeApp_ListView*,
- const QString& theName,
- const QString& theValue,
+ const QStringList&,
const bool = false );
- SalomeApp_ListViewItem( SalomeApp_ListViewItem* theParent,
- const QString&,
+ SalomeApp_ListViewItem( SalomeApp_ListViewItem*,
+ const QStringList&,
const bool = false );
SalomeApp_ListViewItem( SalomeApp_ListView*,
SalomeApp_ListViewItem*,
SalomeApp_ListViewItem*,
const QString&,
const bool = false);
- SalomeApp_ListViewItem( SalomeApp_ListViewItem*,
- const QString& theName,
- const QString& theValue,
- const bool = false);
SalomeApp_ListViewItem( SalomeApp_ListView*,
SalomeApp_ListViewItem*,
const QString& theName,
protected:
// initialization
void init();
+ int depth() const;
private:
bool myEditable;
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+
+#include "SalomeApp_LoadStudiesDlg.h"
+
+#include <QLabel>
+#include <QHBoxLayout>
+#include <QVBoxLayout>
+#include <QListWidget>
+#include <QPushButton>
+#include <QStringList>
+
+#define SPACING_SIZE 6
+#define MARGIN_SIZE 11
+#define MIN_LISTBOX_WIDTH 150
+#define MIN_LISTBOX_HEIGHT 100
+
+/*!
+ \class SalomeApp_LoadStudiesDlg
+ \brief Dialog box which allows selecting study to be loaded
+ from the list.
+*/
+
+/*!
+ \brief Constructor
+ \param parent a parent widget
+ \param studies list of study names
+*/
+SalomeApp_LoadStudiesDlg::SalomeApp_LoadStudiesDlg( QWidget* parent, const QStringList& studies )
+: QDialog( parent )
+{
+ setModal( true );
+
+ setWindowTitle( tr("DLG_LOAD_STUDY_CAPTION") );
+ setSizeGripEnabled( true );
+
+ QVBoxLayout* topLayout = new QVBoxLayout( this );
+ topLayout->setMargin( MARGIN_SIZE );
+ topLayout->setSpacing( SPACING_SIZE );
+
+ QLabel* lab = new QLabel( tr( "MEN_STUDIES_CHOICE" ), this );
+
+ myButtonOk = new QPushButton( tr( "BUT_OK" ), this );
+ myButtonOk->setAutoDefault( true );
+ myButtonOk->setDefault( true );
+
+ QPushButton* buttonCancel = new QPushButton( tr( "BUT_CANCEL" ), this );
+
+ QHBoxLayout* btnLayout = new QHBoxLayout;
+ btnLayout->setSpacing( SPACING_SIZE );
+ btnLayout->setMargin( 0 );
+ btnLayout->addWidget( myButtonOk );
+ btnLayout->addStretch();
+ btnLayout->addWidget( buttonCancel );
+
+ myList = new QListWidget( this );
+ myList->setMinimumSize( MIN_LISTBOX_WIDTH, MIN_LISTBOX_HEIGHT );
+ myList->setSizePolicy( QSizePolicy( QSizePolicy::Expanding,
+ QSizePolicy::Expanding ) );
+ myList->setSelectionMode( QAbstractItemView::SingleSelection );
+
+ topLayout->addWidget( lab );
+ topLayout->addWidget( myList );
+ topLayout->addLayout( btnLayout );
+
+ connect( myButtonOk, SIGNAL( clicked() ), this, SLOT( accept() ) );
+ connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
+ connect( myList, SIGNAL( itemDoubleClicked( QListWidgetItem* ) ),
+ this, SLOT( accept() ) );
+ connect( myList, SIGNAL( itemSelectionChanged() ),
+ this, SLOT( updateState() ) );
+ myList->addItems( studies );
+
+ updateState();
+}
+
+/*!
+ \brief Destructor
+*/
+SalomeApp_LoadStudiesDlg::~SalomeApp_LoadStudiesDlg()
+{
+}
+
+/*!
+ \brief Updates buttons state.
+*/
+void SalomeApp_LoadStudiesDlg::updateState()
+{
+ myButtonOk->setEnabled( myList->currentItem() != 0 );
+}
+
+/*!
+ \brief Get selected study name
+ \return selected study name or null string if study is not selected
+*/
+QString SalomeApp_LoadStudiesDlg::selectedStudy()
+{
+ QString study;
+ if ( myList->currentItem() )
+ study = myList->currentItem()->text();
+ return study;
+}
+
+/*!
+ \brief Executes dialog box to select study from the list
+ and returns the study selected.
+ \param parent parent widget
+ \param studies list of study names
+ \return select study (or null string if dialog box is rejected)
+*/
+QString SalomeApp_LoadStudiesDlg::selectStudy( QWidget* parent, const QStringList& studies )
+{
+ SalomeApp_LoadStudiesDlg dlg( parent, studies );
+ QString study;
+ if ( dlg.exec() == QDialog::Accepted )
+ study = dlg.selectedStudy();
+ return study;
+}
--- /dev/null
+// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+
+#ifndef SALOMEAPP_LOADSTUDIESDLG_H
+#define SALOMEAPP_LOADSTUDIESDLG_H
+
+#include "SalomeApp.h"
+
+#include <QDialog>
+
+class QListWidget;
+class QPushButton;
+class QStringList;
+
+class SALOMEAPP_EXPORT SalomeApp_LoadStudiesDlg : public QDialog
+{
+ Q_OBJECT
+
+private:
+ SalomeApp_LoadStudiesDlg( QWidget*, const QStringList& );
+
+public:
+ ~SalomeApp_LoadStudiesDlg();
+
+ static QString selectStudy( QWidget*, const QStringList& );
+
+ QString selectedStudy();
+
+private slots:
+ void updateState();
+
+private:
+ QListWidget* myList;
+ QPushButton* myButtonOk;
+};
+
+#endif // STD_LOADSTUDIESDLG_H
#include "SalomeApp_Study.h"
#include "LightApp_Selection.h"
-#include "LightApp_Operation.h"
-#include "LightApp_Preferences.h"
-//#include "LightApp_Displayer.h"
#include "CAM_DataModel.h"
-#include "OB_Browser.h"
+// temporary commented
+//#include "OB_Browser.h"
#include <SALOME_ListIO.hxx>
#include <SALOME_ListIteratorOfListIO.hxx>
#include <SALOME_InteractiveObject.hxx>
-//#include <SALOME_Actor.h>
#include <SUIT_Session.h>
-#include <SUIT_ViewModel.h>
-#include <SVTK_ViewWindow.h>
-//#include <SVTK_ViewModel.h>
-//#include <SVTK_MainWindow.h>
-//#include <SVTK_RenderWindowInteractor.h>
-
-#include <qstring.h>
-#include <qmap.h>
-
-//#include <vtkActorCollection.h>
-//#include <vtkRenderer.h>
+#include <QString>
/*!Constructor.*/
SalomeApp_Module::SalomeApp_Module( const QString& name )
}
/*!Create and return instance of LightApp_Selection.*/
-LightApp_Selection* SalomeApp_Module::createSelection() const
+LightApp_Selection* SalomeApp_Module::createSelection( const QString& client, LightApp_SelectionMgr* mgr ) const
{
- return LightApp_Module::createSelection();
+ return LightApp_Module::createSelection( client, mgr );
}
/*!
val = valSO->GetName().c_str();
Handle( SALOME_InteractiveObject ) new_obj =
- new SALOME_InteractiveObject( id.latin1(), comp.latin1(), val.latin1() );
+ new SALOME_InteractiveObject( id.toLatin1(), comp.toLatin1(), val.toLatin1() );
dest.Append( new_obj );
}
anIter->Next();
class CAM_DataModel;
class SalomeApp_Application;
-class LightApp_Operation;
class LightApp_Selection;
class SALOME_ListIO;
class QString;
virtual void storeVisualParameters(int savePoint);
virtual void restoreVisualParameters(int savePoint);
- virtual LightApp_Selection* createSelection() const;
+ virtual LightApp_Selection* createSelection( const QString&, LightApp_SelectionMgr* ) const;
protected:
virtual CAM_DataModel* createDataModel();
#include <utilities.h>
#include <Container_init_python.hxx>
-#include <string>
-#include <vector>
+#include "PyInterp.h" // this include must be first (see PyInterp_base.h)!
-#include "PyInterp_base.h" // this include must be first (see PyInterp_base.h)!
-
-#include <cStringIO.h>
using namespace std;
/*!
* calls initialize method defined in base class, which calls virtual methods
* initstate & initcontext redefined here.
*/
-SalomeApp_PyInterp::SalomeApp_PyInterp(): PythonConsole_PyInterp()
+SalomeApp_PyInterp::SalomeApp_PyInterp():
+ PyConsole_Interp(), myFirstRun( true )
{
}
* It is the caller responsability caller to acquire the GIL
* It will still be held on initContext output
*/
- if ( !PythonConsole_PyInterp::initContext() )
+ if ( !PyConsole_Interp::initContext() )
return false;
// Import special module to change the import mechanism
Do nothing
The initialization has been done in main
*/
-void SalomeApp_PyInterp::init_python()
+void SalomeApp_PyInterp::initPython()
{
- MESSAGE("PyInterp_base::init_python");
+ MESSAGE("PyInterp_base::initPython");
ASSERT(KERNEL_PYTHON::_gtstate); // initialisation in main
SCRUTE(KERNEL_PYTHON::_gtstate);
_gtstate=KERNEL_PYTHON::_gtstate;
_interp=KERNEL_PYTHON::_interp;
}
+/*!
+ Called before each Python command running.
+*/
+int SalomeApp_PyInterp::beforeRun()
+{
+ if ( myFirstRun ) {
+ myFirstRun = false;
+ int ret = simpleRun( "from Help import *", false );
+ if ( ret )
+ return ret;
+ ret = simpleRun( "import salome", false );
+ if (ret)
+ return ret;
+ ret = simpleRun( "salome.salome_init(0,1)", false );
+ if (ret)
+ return ret;
+ }
+ return true;
+}
#ifndef _SalomeApp_PYINTERP_H_
#define _SalomeApp_PYINTERP_H_
-#include <PythonConsole_PyInterp.h> // this include must be first (see PyInterp_base.h)!
+#include <PyConsole_Interp.h> // this include must be first (see PyInterp_base.h)!
-class SalomeApp_PyInterp : public PythonConsole_PyInterp
+class SalomeApp_PyInterp : public PyConsole_Interp
{
public:
SalomeApp_PyInterp();
virtual ~SalomeApp_PyInterp();
- virtual void init_python();
+ virtual void initPython();
protected:
virtual bool initContext();
+ virtual int beforeRun();
+
+private:
+ bool myFirstRun;
};
#endif
#include "SalomeApp_Module.h"
#include "SalomeApp_DataModel.h"
-#include "SalomeApp_DataObject.h"
#include "SalomeApp_Application.h"
#include "SalomeApp_Engine_i.hxx"
#include "SalomeApp_VisualState.h"
#include "LightApp_RootObject.h"
-#include <OB_Browser.h>
+// temporary commented
+//#include <OB_Browser.h>
#include <SUIT_ResourceMgr.h>
-#include <qptrlist.h>
-#include <qapplication.h>
-#include <qdict.h>
-
#include "utilities.h"
-#include <iostream>
-#include <string>
-#include <vector>
-
-#include <SUIT_Session.h>
#include "SALOMEDS_Tool.hxx"
#include "SALOMEDSClient_ClientFactory.hxx"
-#include "SALOMEDSClient_IParameters.hxx"
#include <SALOMEconfig.h>
#include CORBA_SERVER_HEADER(SALOME_Exception)
/*!
Create document.
*/
-void SalomeApp_Study::createDocument()
+bool SalomeApp_Study::createDocument( const QString& theStr )
{
MESSAGE( "openDocument" );
// initialize myStudyDS, read HDF file
QString aName = newStudyName();
- _PTR(Study) study ( SalomeApp_Application::studyMgr()->NewStudy( aName.latin1() ) );
+ _PTR(Study) study ( SalomeApp_Application::studyMgr()->NewStudy( aName.toStdString() ) );
if ( !study )
- return;
+ return false;
setStudyDS( study );
setStudyName( aName );
// create myRoot
setRoot( new LightApp_RootObject( this ) );
- CAM_Study::createDocument();
+ bool aRet = CAM_Study::createDocument( theStr );
emit created( this );
+
+ return aRet;
}
/*!
MESSAGE( "openDocument" );
// initialize myStudyDS, read HDF file
- _PTR(Study) study ( SalomeApp_Application::studyMgr()->Open( (char*) theFileName.latin1() ) );
+ _PTR(Study) study ( SalomeApp_Application::studyMgr()->Open( (char*) theFileName.toStdString().c_str() ) );
if ( !study )
return false;
// update loaded data models: call open() and update() on them.
ModelList dm_s;
dataModels( dm_s );
- for ( ModelListIterator it( dm_s ); it.current(); ++it )
- openDataModel( studyName(), it.current() );
+ QListIterator<CAM_DataModel*> it( dm_s );
+ while ( it.hasNext() )
+ openDataModel( studyName(), it.next() );
// this will build a SUIT_DataObject-s tree under myRoot member field
// passing "false" in order NOT to rebuild existing data models' trees - it was done in previous step
MESSAGE( "loadDocument" );
// obtain myStudyDS from StudyManager
- _PTR(Study) study ( SalomeApp_Application::studyMgr()->GetStudyByName( (char*) theStudyName.latin1() ) );
+ _PTR(Study) study ( SalomeApp_Application::studyMgr()->GetStudyByName( (char*) theStudyName.toStdString().c_str() ) );
if ( !study )
return false;
ModelList dm_s;
dataModels( dm_s );
- for ( ModelListIterator it( dm_s ); it.current(); ++it )
- openDataModel( studyName(), it.current() );
+ QListIterator<CAM_DataModel*> it( dm_s );
+ while ( it.hasNext() )
+ openDataModel( studyName(), it.next() );
// this will build a SUIT_DataObject-s tree under myRoot member field
// passing "false" in order NOT to rebuild existing data models' trees - it was done in previous step
ModelList list; dataModels( list );
- SalomeApp_DataModel* aModel = (SalomeApp_DataModel*)list.first();
+ QListIterator<CAM_DataModel*> it( list );
QStringList listOfFiles;
- for ( ; aModel; aModel = (SalomeApp_DataModel*)list.next() ) {
- listOfFiles.clear();
- aModel->saveAs( theFileName, this, listOfFiles );
- if ( !listOfFiles.isEmpty() )
- saveModuleData(aModel->module()->name(), listOfFiles);
+ while ( it.hasNext() ) {
+ if ( SalomeApp_DataModel* aModel = (SalomeApp_DataModel*)it.next() ) {
+ listOfFiles.clear();
+ aModel->saveAs( theFileName, this, listOfFiles );
+ if ( !listOfFiles.isEmpty() )
+ saveModuleData(aModel->module()->name(), listOfFiles);
+ }
}
// save SALOMEDS document
bool isMultiFile = resMgr->booleanValue( "Study", "multi_file", false );
bool isAscii = resMgr->booleanValue( "Study", "ascii_file", false );
bool res = (isAscii ?
- SalomeApp_Application::studyMgr()->SaveAsASCII( theFileName.latin1(), studyDS(), isMultiFile ) :
- SalomeApp_Application::studyMgr()->SaveAs ( theFileName.latin1(), studyDS(), isMultiFile ))
+ SalomeApp_Application::studyMgr()->SaveAsASCII( theFileName.toStdString(), studyDS(), isMultiFile ) :
+ SalomeApp_Application::studyMgr()->SaveAs ( theFileName.toStdString(), studyDS(), isMultiFile ))
&& CAM_Study::saveDocumentAs( theFileName );
res = res && saveStudyData(theFileName);
ModelList list; dataModels( list );
- SalomeApp_DataModel* aModel = (SalomeApp_DataModel*)list.first();
+ QListIterator<CAM_DataModel*> it( list );
QStringList listOfFiles;
- for ( ; aModel; aModel = (SalomeApp_DataModel*)list.next() ) {
- listOfFiles.clear();
- aModel->save(listOfFiles);
- if ( !listOfFiles.isEmpty() )
- saveModuleData(aModel->module()->name(), listOfFiles);
+ while ( it.hasNext() ) {
+ if ( SalomeApp_DataModel* aModel = (SalomeApp_DataModel*)it.next() ) {
+ listOfFiles.clear();
+ aModel->save(listOfFiles);
+ if ( !listOfFiles.isEmpty() )
+ saveModuleData(aModel->module()->name(), listOfFiles);
+ }
}
// save SALOMEDS document
for ( QStringList::Iterator it = theListOfFiles.begin(); it != theListOfFiles.end(); ++it ) {
if ( (*it).isEmpty() )
continue;
- aListOfFiles[anIndex] = (*it).latin1();
+ aListOfFiles[anIndex] = (*it).toStdString();
anIndex++;
}
- SetListOfFiles(theModuleName, aListOfFiles);
+ SetListOfFiles(theModuleName.toStdString().c_str(), aListOfFiles);
}
/*!
*/
void SalomeApp_Study::openModuleData( QString theModuleName, QStringList& theListOfFiles )
{
- std::vector<std::string> aListOfFiles = GetListOfFiles( theModuleName );
+ std::vector<std::string> aListOfFiles = GetListOfFiles( theModuleName.toStdString().c_str() );
int i, aLength = aListOfFiles.size() - 1;
if ( aLength < 0 )
bool SalomeApp_Study::saveStudyData( const QString& theFileName )
{
ModelList list; dataModels( list );
- SalomeApp_DataModel* aModel = (SalomeApp_DataModel*)list.first();
+ QListIterator<CAM_DataModel*> it( list );
std::vector<std::string> listOfFiles(0);
- for ( ; aModel; aModel = (SalomeApp_DataModel*)list.next() )
- SetListOfFiles(aModel->module()->name(), listOfFiles);
+ while ( it.hasNext() )
+ if ( SalomeApp_DataModel* aModel = (SalomeApp_DataModel*)it.next() )
+ SetListOfFiles(aModel->module()->name().toStdString().c_str(), listOfFiles);
return true;
}
*/
void SalomeApp_Study::dataModelInserted (const CAM_DataModel* dm)
{
- MESSAGE("SalomeApp_Study::dataModelInserted() : module name() = " << dm->module()->name());
+ MESSAGE("SalomeApp_Study::dataModelInserted() : module name() = " << dm->module()->name().toStdString());
CAM_Study::dataModelInserted(dm);
_PTR(Study) aStudy = studyDS();
if (!aStudy)
return;
- _PTR(SComponent) aComp = aStudy->FindComponent(dm->module()->name());
+ _PTR(SComponent) aComp = aStudy->FindComponent(dm->module()->name().toStdString());
if (!aComp) {
// Create SComponent
_PTR(StudyBuilder) aBuilder = aStudy->NewBuilder();
- aComp = aBuilder->NewComponent(dm->module()->name());
- aBuilder->SetName(aComp, dm->module()->moduleName().latin1());
+ aComp = aBuilder->NewComponent(dm->module()->name().toStdString());
+ aBuilder->SetName(aComp, dm->module()->moduleName().toStdString());
QString anIconName = dm->module()->iconName();
if (!anIconName.isEmpty()) {
_PTR(AttributePixMap) anAttr = aBuilder->FindOrCreateAttribute(aComp, "AttributePixMap");
if (anAttr)
- anAttr->SetPixMap(anIconName.latin1());
+ anAttr->SetPixMap(anIconName.toStdString());
}
// Set default engine IOR
- aBuilder->DefineComponentInstance(aComp, SalomeApp_Application::defaultEngineIOR().latin1());
+ aBuilder->DefineComponentInstance(aComp, SalomeApp_Application::defaultEngineIOR().toStdString());
//SalomeApp_DataModel::BuildTree( aComp, root(), this, /*skipExisitng=*/true );
SalomeApp_DataModel::synchronize( aComp, this );
}
// 1. aModule == 0 means that this is a light module (no CORBA enigine)
if (!aModule) {
anEngine = SalomeApp_Application::defaultEngineIOR();
- aSComp = aStudy->FindComponent(dm->module()->name());
+ aSComp = aStudy->FindComponent(dm->module()->name().toStdString());
}
else {
SalomeApp_DataModel* aDM = dynamic_cast<SalomeApp_DataModel*>( dm );
anEngine = aDM->getModule()->engineIOR();
if ( anEngine.isEmpty() )
return false;
- aSComp = aStudy->FindComponentID( std::string( anId.latin1() ) );
+ aSComp = aStudy->FindComponentID( std::string( anId.toLatin1() ) );
}
}
if ( aSComp ) {
_PTR(StudyBuilder) aBuilder( aStudy->NewBuilder() );
if ( aBuilder ) {
try {
- aBuilder->LoadWith( aSComp, std::string( anEngine.latin1() ) );
+ aBuilder->LoadWith( aSComp, std::string( anEngine.toLatin1() ) );
}
catch( const SALOME::SALOME_Exception& ) {
// Oops, something went wrong while loading -> return an error
// Remove the files and temporary directory, created
// for this module by LightApp_Engine_i::Load()
bool isMultiFile = false; // TODO: decide, how to access this parameter
- RemoveTemporaryFiles( dm->module()->name(), isMultiFile );
+ RemoveTemporaryFiles( dm->module()->name().toStdString().c_str(), isMultiFile );
// Something has been read -> create data model tree
LightApp_DataModel* aDM = dynamic_cast<LightApp_DataModel*>( dm );
while ( newName.isEmpty() ){
curName = prefix.arg( i );
for ( j = 0 ; j < n; j++ ){
- if ( !strcmp( studies[j].c_str(), curName.latin1() ) )
+ if ( !strcmp( studies[j].c_str(), curName.toLatin1() ) )
break;
}
if ( j == n )
*/
QString SalomeApp_Study::referencedToEntry( const QString& entry ) const
{
- _PTR(SObject) obj = studyDS()->FindObjectID( entry.latin1() );
+ _PTR(SObject) obj = studyDS()->FindObjectID( entry.toStdString() );
_PTR(SObject) refobj;
if( obj && obj->ReferencedObject( refobj ) )
*/
QString SalomeApp_Study::componentDataType( const QString& entry ) const
{
- _PTR(SObject) obj( studyDS()->FindObjectID( entry.latin1() ) );
+ _PTR(SObject) obj( studyDS()->FindObjectID( entry.toStdString() ) );
if ( !obj )
return LightApp_Study::componentDataType( entry );
return obj->GetFatherComponent()->ComponentDataType().c_str();
*/
bool SalomeApp_Study::isComponent( const QString& entry ) const
{
- _PTR(SObject) obj( studyDS()->FindObjectID( entry.latin1() ) );
+ _PTR(SObject) obj( studyDS()->FindObjectID( entry.toStdString() ) );
return obj && QString( obj->GetID().c_str() ) == obj->GetFatherComponent()->GetID().c_str();
}
*/
void SalomeApp_Study::children( const QString& entry, QStringList& child_entries ) const
{
- _PTR(SObject) SO = studyDS()->FindObjectID( entry.latin1() );
+ _PTR(SObject) SO = studyDS()->FindObjectID( entry.toStdString() );
_PTR(ChildIterator) anIter ( studyDS()->NewChildIterator( SO ) );
anIter->InitEx( true );
while( anIter->More() )
{
_PTR(AttributeParameter) AP = studyDS()->GetCommonParameters(getVisualComponentName(), savePoint);
_PTR(IParameters) ip = ClientFactory::getIParameters(AP);
- ip->setProperty("AP_SAVEPOINT_NAME", nameOfSavePoint.latin1());
+ ip->setProperty("AP_SAVEPOINT_NAME", nameOfSavePoint.toStdString());
}
/*!
#include "SalomeApp.h"
#include <LightApp_Study.h>
-#include <string>
#ifdef WIN32
#pragma warning( disable:4251 )
virtual int id() const;
- virtual void createDocument();
+ virtual bool createDocument( const QString& );
virtual bool openDocument( const QString& );
virtual bool loadDocument( const QString& );
#include <SUIT_Desktop.h>
#include <SUIT_MessageBox.h>
-// OCCT Includes
-#include <OSD_Process.hxx>
-#include <Quantity_Date.hxx>
-
// CORBA Headers
#include <SALOMEconfig.h>
#include CORBA_CLIENT_HEADER(SALOMEDS_Attributes)
// QT Includes
-#include <qpushbutton.h>
-#include <qlayout.h>
+#include <QPushButton>
+#include <QGridLayout>
using namespace std;
const QString theName,
const bool theEditable,
const int theUserType) :
- SalomeApp_ListViewItem( parent, theName, theEditable )
+ SalomeApp_ListViewItem( parent, QStringList(theName), theEditable )
{
setUserType(theUserType);
}
/*!Constructor. Initialize study properties dialog.*/
SalomeApp_StudyPropertiesDlg::SalomeApp_StudyPropertiesDlg(QWidget* parent)
- : QDialog(parent, "", TRUE, WStyle_Customize | WStyle_NormalBorder | WStyle_Title | WStyle_SysMenu ),
+ : QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint ),
myChanged( false )
{
- setCaption(tr("TLT_STUDY_PROPERTIES"));
+ setObjectName( "" );
+ setModal( TRUE );
+
+ setWindowTitle(tr("TLT_STUDY_PROPERTIES"));
setSizeGripEnabled( true );
- clearWFlags(Qt::WStyle_ContextHelp);
+ setWindowFlags( windowFlags() ^ QFlags<Qt::WindowType>(!Qt::WindowContextHelpButtonHint) );
QGridLayout* mainLayout = new QGridLayout(this);
mainLayout->setMargin(DEFAULT_MARGIN);
mainLayout->setSpacing(DEFAULT_SPACING);
myPropList = new SalomeApp_ListView(this);
- myPropList->addColumn("");
- myPropList->addColumn("");
+ myPropList->setColumnCount(2);
+ QStringList aLabels;
+ aLabels << "" << "";
+ myPropList->setHeaderLabels( aLabels );
myPropList->enableEditing(TRUE);
myPropList->setMinimumSize(MIN_LIST_WIDTH, MIN_LIST_HEIGHT);
- mainLayout->addMultiCellWidget(myPropList, 0, 0, 0, 2);
+ mainLayout->addWidget(myPropList, 0, 0, 1, 3);
myOKBtn = new QPushButton(tr("BUT_OK"), this);
mainLayout->addWidget(myOKBtn, 1, 0);
_PTR(AttributeStudyProperties) propAttr = myStudyDoc->GetProperties();
//myChanged = propChanged();
if ( propAttr /*&& myChanged*/ ) {
- QListViewItemIterator it( myPropList );
+ QTreeWidgetItemIterator it( myPropList );
// iterate through all items of the listview
- for ( ; it.current(); ++it ) {
- SalomeApp_PropItem* item = (SalomeApp_PropItem*)(it.current());
+ while (*it) {
+ SalomeApp_PropItem* item = (SalomeApp_PropItem*)(*it);
switch (item->getUserType()) {
case prpAuthorId:
- if (QString(propAttr->GetUserName().c_str()) != item->getValue().stripWhiteSpace()) {
+ if (QString(propAttr->GetUserName().c_str()) != item->getValue().trimmed()) {
if (!propAttr->IsLocked()) {
- propAttr->SetUserName(item->getValue().stripWhiteSpace().latin1());
+ propAttr->SetUserName(item->getValue().trimmed().toStdString());
myChanged = true;
} else {
- SUIT_MessageBox::warn1(SUIT_Session::session()->activeApplication()->desktop(),
- QObject::tr("WRN_WARNING"),
- QObject::tr("WRN_STUDY_LOCKED"),
- QObject::tr("BUT_OK"));
+ SUIT_MessageBox::warning(SUIT_Session::session()->activeApplication()->desktop(),
+ QObject::tr("WRN_WARNING"),
+ QObject::tr("WRN_STUDY_LOCKED") );
}
}
break;
//case prpModeId:
- // propAttr->SetCreationMode(item->getValue().stripWhiteSpace().latin1());
+ // propAttr->SetCreationMode(item->getValue().trimmed().latin1());
// break;
case prpLockedId:
{
default:
break;
}
+ ++it;
}
}
accept();
{
_PTR(AttributeStudyProperties) propAttr = myStudyDoc->GetProperties();
if (propAttr) {
- QListViewItemIterator it (myPropList);
+ QTreeWidgetItemIterator it (myPropList);
+
// iterate through all items of the listview
- for (; it.current(); ++it) {
- SalomeApp_PropItem* item = (SalomeApp_PropItem*)(it.current());
+ while (*it) {
+ SalomeApp_PropItem* item = (SalomeApp_PropItem*)(*it);
switch (item->getUserType()) {
case prpAuthorId:
- if ( QString( propAttr->GetUserName().c_str() ) != item->getValue().stripWhiteSpace() ) {
+ if ( QString( propAttr->GetUserName().c_str() ) != item->getValue().trimmed() ) {
return true;
}
break;
//case prpModeId:
- // if ( QString( propAttr->GetCreationMode().c_str() ) != item->getValue().stripWhiteSpace() ) {
+ // if ( QString( propAttr->GetCreationMode().c_str() ) != item->getValue().trimmed() ) {
// return true;
// }
// break;
default:
break;
}
+ ++it;
}
}
return false;
#define SALOMEAPP_STUDY_PROPERTIES_DLG_H
#include "SalomeApp.h"
-#include <SALOMEDSClient_definitions.hxx>
-#include <qdialog.h>
-#include <qlineedit.h>
-#include <qcombobox.h>
-#include <qlistview.h>
+
+#include <QDialog>
#include <SALOMEconfig.h>
#include CORBA_SERVER_HEADER(SALOMEDS)
class SalomeApp_ListView;
class QPushButton;
-class QToolButton;
class SALOMEAPP_EXPORT SalomeApp_StudyPropertiesDlg : public QDialog
{
#include <utilities.h>
+#include <QColor>
+#include <QString>
+
+#include <Quantity_Color.hxx>
+
/*!
Convert QColor to Quantity_Color, if QColor is valid.
*/
}
if ( error )
- SUIT_MessageBox::error1( SUIT_Session::session()->activeApplication()->desktop(),
- title, message, QObject::tr( "OK" ) );
+ SUIT_MessageBox::critical( SUIT_Session::session()->activeApplication()->desktop(),
+ title, message );
else
- SUIT_MessageBox::warn1( SUIT_Session::session()->activeApplication()->desktop(),
- title, message, QObject::tr( "OK" ) );
+ SUIT_MessageBox::warning( SUIT_Session::session()->activeApplication()->desktop(),
+ title, message );
}
#include <SUIT_Tools.h>
-#include <qcolor.h>
-#include <qstring.h>
+class QColor;
+class QString;
-#include <Quantity_Color.hxx>
+class Quantity_Color;
#include <SALOMEconfig.h>
#include CORBA_CLIENT_HEADER(SALOME_Exception)
_PTR(Study) aStudy = aDoc->studyDS();
QString entry = owner->entry();
- _PTR(SObject) aSObj( aStudy->FindObjectID( entry.latin1() ) );
+ _PTR(SObject) aSObj( aStudy->FindObjectID( entry.toStdString() ) );
if (aSObj)
{
_PTR(SComponent) aComponent(aSObj->GetFatherComponent());
- if ( aComponent && (aComponent->ComponentDataType() == myKind.latin1()) )
+ if ( aComponent && (aComponent->ComponentDataType() == myKind.toStdString()) )
return true;
}
}
#ifndef SALOMEAPP_TYPEFILTER_H
#define SALOMEAPP_TYPEFILTER_H
-#include <qstring.h>
+#include <QString>
#include "SalomeApp_Filter.h"
#include "SalomeApp_Study.h"
#include "SalomeApp_Application.h"
-#include <SUIT_ResourceMgr.h>
+//#include <SUIT_ResourceMgr.h>
+#include <SUIT_ViewManager.h>
+#include <SUIT_ViewWindow.h>
#include <QtxWorkstack.h>
#include <STD_TabDesktop.h>
-#include <qptrlist.h>
-#include <qapplication.h>
-#include <qdict.h>
+#include <QList>
+#include <QApplication>
+#include <QMultiHash>
-#include <SALOMEDSClient_ClientFactory.hxx>
-#include <SALOMEDSClient_IParameters.hxx>
+#include <SALOMEDSClient_ClientFactory.hxx>//?
+#include <SALOMEDSClient_IParameters.hxx>//?
-#include <vector>
-#include <string>
+#include <vector>//?
+#include <string>//?
/*!
Constructor.
*/
void nameViewWindows( const ViewManagerList& lst )
{
- QDict<int> viewersCounter; // map viewerType - to - index_of_this_viewer_type
- viewersCounter.setAutoDelete( true );
- for ( QPtrListIterator<SUIT_ViewManager> it(lst); it.current(); ++it) {
- int view_count = it.current()->getViewsCount();
- QString vType = it.current()->getType();
+ QMultiHash<QString,int> viewersCounter; // map viewerType - to - index_of_this_viewer_type
+ QListIterator<SUIT_ViewManager*> it(lst);
+ SUIT_ViewManager* aVM = 0;
+ while ( it.hasNext() ) {
+ aVM = it.next();
+ if ( !aVM ) continue;
+
+ int view_count = aVM->getViewsCount();
+ QString vType = aVM->getType();
if ( !view_count )
continue; //No views is opened in the viewer
- int* viewerID = viewersCounter[ vType ];
+ int viewerID = viewersCounter.value( vType );
if ( !viewerID ) {
- viewerID = new int( 0 );
+ viewerID = 0;
viewersCounter.insert( vType, viewerID );
}
else
- ++(*viewerID);
+ ++viewerID;
- QPtrVector<SUIT_ViewWindow> views = it.current()->getViews();
+ QVector<SUIT_ViewWindow*> views = aVM->getViews();
for ( int i = 0; i < view_count; i++ ) {
- QString vName = QString( "%1_%2_%3" ).arg( vType ).arg( *viewerID ).arg( i );
- views[i]->setName( vName );
+ QString vName = QString( "%1_%2_%3" ).arg( vType ).arg( viewerID ).arg( i );
+ views[i]->setObjectName( vName );
}
}
+ viewersCounter.clear();
}
/*!
// store active window's name
SUIT_ViewWindow* win = myApp->desktop()->activeWindow();
if ( win )
- ip->setProperty("AP_ACTIVE_VIEW", win->name() );
+ ip->setProperty("AP_ACTIVE_VIEW", win->objectName().toStdString() );
int viewerID = 0;
SUIT_ViewManager* vm = 0;
- for (QPtrListIterator<SUIT_ViewManager> it( lst ); it.current(); ++it ) {
- vm = it.current();
+ QListIterator<SUIT_ViewManager*> it( lst );
+ while ( it.hasNext() ) {
+ vm = it.next();
+ if ( !vm ) continue;
+
int view_count = vm->getViewsCount();
if ( !view_count )
continue; //No views is opened in the viewer
- std::string viewerEntry = QString( "%1_%2" ).arg( vm->getType() ).arg( ++viewerID ).latin1();
+ std::string viewerEntry = QString( "%1_%2" ).arg( vm->getType() ).arg( ++viewerID ).toStdString();
ip->append("AP_VIEWERS_LIST", viewerEntry);
- QPtrVector<SUIT_ViewWindow> views = vm->getViews();
+ QVector<SUIT_ViewWindow*> views = vm->getViews();
for(int i = 0; i<view_count; i++) {
- ip->append( viewerEntry, views[i]->caption().latin1() );
- ip->append( viewerEntry, views[i]->getVisualParameters().latin1() );
+ ip->append( viewerEntry, views[i]->windowTitle().toStdString() );
+ ip->append( viewerEntry, views[i]->getVisualParameters().toStdString() );
}
}
QtxWorkstack* workstack = ((STD_TabDesktop*)myApp->desktop())->workstack();
QString workstackInfo;
(*workstack) >> workstackInfo;
- ip->setProperty( "AP_WORKSTACK_INFO", workstackInfo.latin1() );
+ ip->setProperty( "AP_WORKSTACK_INFO", workstackInfo.toStdString() );
}
//Save a name of the active module
if ( CAM_Module* activeModule = myApp->activeModule() )
- ip->setProperty( "AP_ACTIVE_MODULE", activeModule->moduleName().latin1() );
+ ip->setProperty( "AP_ACTIVE_MODULE", activeModule->moduleName().toStdString() );
//Store visual parameters of the modules
- QPtrList<CAM_Module> mlist;
+ QList<CAM_Module*> mlist;
myApp->modules( mlist );
+ QListIterator<CAM_Module*> itM( mlist );
CAM_Module* module = 0;
- for ( module = mlist.first(); module; module = mlist.next() ) {
+ while ( itM.hasNext() ) {
+ module = itM.next();
+ if ( !module ) continue;
+
if ( SalomeApp_Module* sModule = dynamic_cast<SalomeApp_Module*>( module ) ) {
- ip->append( "AP_MODULES_LIST", sModule->moduleName().latin1() );
+ ip->append( "AP_MODULES_LIST", sModule->moduleName().toStdString() );
sModule->storeVisualParameters( savePoint );
}
}
//Remove all already existent veiwers and their views
ViewManagerList lst;
myApp->viewManagers( lst );
- for ( QPtrListIterator<SUIT_ViewManager> it(lst); it.current(); ++it ) {
- myApp->removeViewManager( it.current() );
+ QListIterator<SUIT_ViewManager*> it(lst);
+ while ( it.hasNext() ) {
+ myApp->removeViewManager( it.next() );
qApp->processEvents();
}
//Restore the viewers and view windows
}
//Resize the views, set their captions and apply visual parameters.
- QPtrVector<SUIT_ViewWindow> views = vm->getViews();
+ QVector<SUIT_ViewWindow*> views = vm->getViews();
for (int i = 0, j = 0; i<viewCount; i++, j++) {
viewWin = views[i];
if ( !viewWin )
while ( !viewWin->isVisible() )
qApp->processEvents();
- viewWin->setCaption(ip->getValue(viewerEntry, j).c_str());
+ viewWin->setWindowTitle(ip->getValue(viewerEntry, j).c_str());
// printf ( "VP for viewWin \"%s\": %s\n", viewerEntry.c_str(), ip->getValue(viewerEntry, j+1).c_str() );
viewersParameters[ viewWin ] = ip->getValue(viewerEntry, j+1).c_str();
// so here we store their visual parameters for later restoring..
lst.clear();
myApp->viewManagers(lst);
- QPtrListIterator<SUIT_ViewManager> it( lst );
- for ( ; it.current(); ++it ) {
- int view_count = it.current()->getViewsCount();
- QPtrVector<SUIT_ViewWindow> views = it.current()->getViews();
+ QListIterator<SUIT_ViewManager*> itVM( lst );
+ SUIT_ViewManager* aVM = 0;
+ while ( itVM.hasNext() ) {
+ aVM = itVM.next();
+ if ( !aVM ) continue;
+
+ int view_count = aVM->getViewsCount();
+ QVector<SUIT_ViewWindow*> views = aVM->getViews();
for ( int i = 0; i < view_count; i++ ) {
if ( !viewersParameters.contains( views[i] ) ) {
viewersParameters[ views[i] ] = views[i]->getVisualParameters();
- // printf ( "store VP for viewWin \"%s\": %s\n", views[i]->name(), views[i]->getVisualParameters().latin1() );
+ // printf ( "store VP for viewWin \"%s\": %s\n", views[i]->name(), views[i]->getVisualParameters().toLatin1().constData() );
}
}
}
std::string activeViewName = ip->getProperty("AP_ACTIVE_VIEW");
QMap<SUIT_ViewWindow*, QString>::Iterator mapIt;
for ( mapIt = viewersParameters.begin(); mapIt != viewersParameters.end(); ++mapIt ) {
- mapIt.key()->setVisualParameters( mapIt.data() );
- if ( activeViewName == mapIt.key()->name() )
+ mapIt.key()->setVisualParameters( mapIt.value() );
+ if ( activeViewName == mapIt.key()->objectName().toStdString() )
mapIt.key()->setFocus();
}
--- /dev/null
+<!DOCTYPE TS><TS>
+</TS>
msgid "SalomeApp_Application::MEN_DELETE_VS"
msgstr "Delete"
+
+//=======================================================================================
+
+msgid "APPCLOSE_SAVE"
+msgstr "&Save&&Close"
+
+msgid "APPCLOSE_CLOSE"
+msgstr "&Close w/o saving"
+
+msgid "APPCLOSE_UNLOAD"
+msgstr "&Unload"
+
+msgid "APPCLOSE_CANCEL"
+msgstr "&Cancel"
+
+msgid "APPCLOSE_CAPTION"
+msgstr "Close active study"
+
+msgid "APPCLOSE_DESCRIPTION"
+msgstr "Do you want to close or only unload the study"
+
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>CLOSE_LOCKED_STUDY</source>
+ <translation>Close locked study?</translation>
+ </message>
+ <message>
+ <source>PUBLISH_IN_STUDY</source>
+ <translation>Publish in study</translation>
+ </message>
+ <message>
+ <source>BUT_NEW</source>
+ <translation>&New</translation>
+ </message>
+ <message>
+ <source>SAVE_POINT_ROOT_NAME</source>
+ <translation>GUI states</translation>
+ </message>
+ <message>
+ <source>SAVE_POINT_ROOT_TOOLTIP</source>
+ <translation>Persistent GUI states</translation>
+ </message>
+ <message>
+ <source>SAVE_GUI_STATE</source>
+ <translation>Save GUI state</translation>
+ </message>
+ <message>
+ <source>BUT_LOAD</source>
+ <translation>&Load</translation>
+ </message>
+ <message>
+ <source>BUT_OPEN</source>
+ <translation>&Open</translation>
+ </message>
+ <message>
+ <source>SAVE_POINT_OBJECT_TOOLTIP</source>
+ <translation>Saved GUI state: %1</translation>
+ </message>
+ <message>
+ <source>SAVE_POINT_DEF_NAME</source>
+ <translation>GUI state: </translation>
+ </message>
+</context>
+<context>
+ <name>SalomeApp_Application</name>
+ <message>
+ <source>ALL_FILES_FILTER</source>
+ <translation>All files (*.*)</translation>
+ </message>
+ <message>
+ <source>MEN_WINDOWS_NEW</source>
+ <translation>New window</translation>
+ </message>
+ <message>
+ <source>MEN_DELETE_INVALID_REFERENCE</source>
+ <translation>Delete Invalid Reference</translation>
+ </message>
+ <message>
+ <source>TOT_FILE_DESK_PREFERENCES</source>
+ <translation>Preferences</translation>
+ </message>
+ <message>
+ <source>MEN_DELETE_VS</source>
+ <translation>Delete</translation>
+ </message>
+ <message>
+ <source>MEN_OPENWITH</source>
+ <translation>Activate %1 Module</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_REGISTRY_DISPLAY</source>
+ <translation>Registry &display</translation>
+ </message>
+ <message>
+ <source>TOT_DESK_FILE_LOAD_SCRIPT</source>
+ <translation>Load python script</translation>
+ </message>
+ <message>
+ <source>PREF_STORE_VISUAL_STATE</source>
+ <translation>Store/restore last GUI state</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_FILE_SAVE_GUI_STATE</source>
+ <translation>Saves current state of viewers, displayed objects, etc.</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_FILE_SAVE_GUI_STATE</source>
+ <translation>Save GUI state</translation>
+ </message>
+ <message>
+ <source>TOT_DESK_FILE_SAVE_GUI_STATE</source>
+ <translation>Save GUI state</translation>
+ </message>
+ <message>
+ <source>MEN_RESTORE_VS</source>
+ <translation>Restore</translation>
+ </message>
+ <message>
+ <source>WRN_DUMP_STUDY_FAILED</source>
+ <translation>Dump study failed</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_PROPERTIES</source>
+ <translation>Pro&perties...</translation>
+ </message>
+ <message>
+ <source>QUE_DOC_ALREADYEXIST</source>
+ <translation>The document %1 already exists in study manager.
+Do you want to reload it ?</translation>
+ </message>
+ <message>
+ <source>MEN_RENAME_VS</source>
+ <translation>Rename</translation>
+ </message>
+ <message>
+ <source>TOT_DESK_CATALOG_GENERATOR</source>
+ <translation>Catalog generator</translation>
+ </message>
+ <message>
+ <source>PUBLISH_IN_STUDY</source>
+ <translation>Publish in study</translation>
+ </message>
+ <message>
+ <source>PREF_OBJ_BROWSER_SETTINGS</source>
+ <translation>Settings</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_REGISTRY_DISPLAY</source>
+ <translation>Displays content of the Registry CORBA server</translation>
+ </message>
+ <message>
+ <source>PYTHON_FILES_FILTER</source>
+ <translation>PYTHON Files (*.py)</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_PROPERTIES</source>
+ <translation>Edits study properties</translation>
+ </message>
+ <message>
+ <source>PREF_TAB_OBJBROWSER</source>
+ <translation>Object browser</translation>
+ </message>
+ <message>
+ <source>STUDY_LOCKED</source>
+ <translation>LOCKED</translation>
+ </message>
+ <message>
+ <source>OBJ_BROWSER_NAME</source>
+ <translation>Object</translation>
+ </message>
+ <message>
+ <source>TOT_DESK_REGISTRY_DISPLAY</source>
+ <translation>Registry display</translation>
+ </message>
+ <message>
+ <source>OBJ_BROWSER_COLUMN_0</source>
+ <translation>Value</translation>
+ </message>
+ <message>
+ <source>OBJ_BROWSER_COLUMN_1</source>
+ <translation>Entry</translation>
+ </message>
+ <message>
+ <source>OBJ_BROWSER_COLUMN_2</source>
+ <translation>IOR</translation>
+ </message>
+ <message>
+ <source>OBJ_BROWSER_COLUMN_3</source>
+ <translation>Reference entry</translation>
+ </message>
+ <message>
+ <source>PREF_CATEGORY_SALOME</source>
+ <translation>SALOME</translation>
+ </message>
+ <message>
+ <source>PYTHON_CONSOLE</source>
+ <translation>Python Console</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_FILE_LOAD_SCRIPT</source>
+ <translation>Load scrip&t...</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_TOOLS</source>
+ <translation>&Tools</translation>
+ </message>
+ <message>
+ <source>TOT_DESK_FILE_DUMP_STUDY</source>
+ <translation>Dump study</translation>
+ </message>
+ <message>
+ <source>MEN_VIEW_WNDS</source>
+ <translation>Windows</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_FILE_DUMP_STUDY</source>
+ <translation>&Dump study...</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_CATALOG_GENERATOR</source>
+ <translation>Generates XML catalog of a component's interface</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_FILE_DUMP_STUDY</source>
+ <translation>Dumps study to the python script</translation>
+ </message>
+ <message>
+ <source>TOT_DESK_PROPERTIES</source>
+ <translation>Study properties</translation>
+ </message>
+ <message>
+ <source>PREF_GROUP_DEF_COLUMNS</source>
+ <translation>Default columns</translation>
+ </message>
+ <message>
+ <source>PRP_DESK_FILE_LOAD_SCRIPT</source>
+ <translation>Loads python script from file</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_CATALOG_GENERATOR</source>
+ <translation>Catalog &generator</translation>
+ </message>
+ <message>
+ <source>MEN_DESK_MRU</source>
+ <translation>Most recently used</translation>
+ </message>
+ <message>
+ <source>TOT_DESK_MRU</source>
+ <translation>Most recently used</translation>
+ </message>
+</context>
+<context>
+ <name>SalomeApp_StudyPropertiesDlg</name>
+ <message>
+ <source>PRP_MODE_FROM_SCRATCH</source>
+ <translation>from scratch</translation>
+ </message>
+ <message>
+ <source>PRP_AUTHOR</source>
+ <translation>Author</translation>
+ </message>
+ <message>
+ <source>PRP_LOCKED</source>
+ <translation>Locked</translation>
+ </message>
+ <message>
+ <source>PRP_MODIFICATIONS</source>
+ <translation>Modifications</translation>
+ </message>
+ <message>
+ <source>PRP_NO</source>
+ <translation>No</translation>
+ </message>
+ <message>
+ <source>PRP_YES</source>
+ <translation>Yes</translation>
+ </message>
+ <message>
+ <source>PRP_MODIFIED</source>
+ <translation>Modified</translation>
+ </message>
+ <message>
+ <source>PRP_DATE</source>
+ <translation>Created</translation>
+ </message>
+ <message>
+ <source>PRP_MODE</source>
+ <translation>Mode</translation>
+ </message>
+ <message>
+ <source>PRP_MODE_FROM_COPYFROM</source>
+ <translation>copy from</translation>
+ </message>
+ <message>
+ <source>TLT_STUDY_PROPERTIES</source>
+ <translation>Study Properties</translation>
+ </message>
+</context>
+</TS>
#include <qstringlist.h>
#include <qlabel.h>
#include <qprogressbar.h>
-
-//VRV: porting on Qt 3.0.5
-#if QT_VERSION >= 0x030005
#include <qdesktopwidget.h>
-#endif
-//VRV: porting on Qt 3.0.5
-
#include <qsize.h>
#include <SALOMEconfig.h>
aHBoxLayout->addItem( new QSpacerItem( 0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum ) );
//Center widget
-#if QT_VERSION >= 0x030005
QDesktopWidget *d = QApplication::desktop();
-#else
- QWidget *d = QApplication::desktop();
-#endif
-//VRV: porting on Qt 3.0.5
int w = d->width(); // returns desktop width
int h = d->height(); // returns desktop height
//will be set true if we get response from server
bool IsPassed = false;
QString errDescription;
-#ifdef WNT
+#ifdef WIN32
int i;
#endif
switch (iteration)
{
case 1:
//First checking - existence of Naming Service
-#ifndef WNT
+#ifndef WIN32
for (int i = myRepeat; i ; i--)
#else
for (i = myRepeat; i ; i--)
#ifndef _SALOME_Session_HXX_
#define _SALOME_Session_HXX_
-#ifdef WNT
- #if defined SESSION_EXPORTS
- #if defined WIN32
- #define SESSION_EXPORT __declspec( dllexport )
- #else
- #define SESSION_EXPORT
- #endif
- #else
- #if defined WIN32
- #define SESSION_EXPORT __declspec( dllimport )
- #else
- #define SESSION_EXPORT
- #endif
- #endif
-#else
- #define SESSION_EXPORT
-#endif
+#if defined WIN32
+# if defined SESSION_EXPORTS
+# define SESSION_EXPORT __declspec( dllexport )
+# else
+# define SESSION_EXPORT __declspec( dllimport )
+# endif
+#else // WIN32
+# define SESSION_EXPORT
+#endif // WIN32
-#endif
\ No newline at end of file
+#endif
#include "Utils_ORB_INIT.hxx"
#include "Utils_SINGLETON.hxx"
#include "SALOME_NamingService.hxx"
-#include "SALOMETraceCollector.hxx"
-#include <iostream>
-#ifndef WNT
-#include <unistd.h>
-#endif
-
-#include <qdir.h>
-#include <qfile.h>
-#include <qapplication.h>
-#include <qwaitcondition.h>
-#include <qregexp.h>
+#include <QDir>
+#include <QFile>
+#include <QApplication>
+#include <QMutex>
+#include <QWaitCondition>
+#include <QRegExp>
#include "Utils_SALOME_Exception.hxx"
#include "Utils_CorbaException.hxx"
-#include "SALOME_Event.hxx"
+#include "SALOME_Event.h"
#include <SALOMEconfig.h>
#include CORBA_SERVER_HEADER(SALOME_Session)
#include CORBA_SERVER_HEADER(SALOMEDS)
#include <utilities.h>
-#include "Session_Session_i.hxx"
#include "Session_ServerLauncher.hxx"
#include "Session_ServerCheck.hxx"
#include "SUIT_Session.h"
#include "SUIT_Application.h"
#include "SUIT_Desktop.h"
-#include "SUIT_MessageBox.h"
#include "SUIT_ResourceMgr.h"
#include "SUIT_ExceptionHandler.h"
path += QString( "bin/salome/VERSION" );
QFile vf( path );
- if ( !vf.open( IO_ReadOnly ) )
+ if ( !vf.open( QIODevice::ReadOnly ) )
return QString::null;
- QString line;
- vf.readLine( line, 1024 );
+ QString line( vf.readLine( 1024 ) );
+
vf.close();
if ( line.isEmpty() )
line.remove( line.length() - 1, 1 );
QString ver;
- int idx = line.findRev( ":" );
+ int idx = line.lastIndexOf( ":" );
if ( idx != -1 )
- ver = line.mid( idx + 1 ).stripWhiteSpace();
+ ver = line.mid( idx + 1 ).trimmed();
return ver;
}
resMgr.loadLanguage( "LightApp", "en" );
resMgr.loadLanguage( "SalomeApp", "en" );
- myExtAppName = QObject::tr( "APP_NAME" ).stripWhiteSpace();
- if ( myExtAppName == "APP_NAME" || myExtAppName.lower() == "salome" )
+ myExtAppName = QObject::tr( "APP_NAME" ).trimmed();
+ if ( myExtAppName == "APP_NAME" || myExtAppName.toLower() == "salome" )
myExtAppName = "SalomeApp";
myExtAppVersion = QObject::tr( "APP_VERSION" );
if ( myExtAppVersion == "APP_VERSION" ) {
QString fname = QFileInfo( _fname ).fileName();
if( exp.exactMatch( fname ) ) {
- QStringList vers = QStringList::split( ".", exp.cap( 1 ) );
+ QStringList vers = exp.cap( 1 ).split( ".", QString::SkipEmptyParts );
int major=0, minor=0;
major = vers[0].toInt();
minor = vers[1].toInt();
- if( vers_exp.search( vers[2] )==-1 )
+ if( vers_exp.indexIn( vers[2] )==-1 )
return -1;
int release = 0, dev1 = 0, dev2 = 0;
release = vers_exp.cap( 1 ).toInt();
- dev1 = vers_exp.cap( 2 )[ 0 ].latin1();
+ dev1 = vers_exp.cap( 2 )[ 0 ].toLatin1();
dev2 = vers_exp.cap( 3 ).toInt();
int dev = dev1*100+dev2, id = major;
splash = QtxSplash::splash( px );
// ...set splash text colors
if ( !splashTextColors.isEmpty() ) {
- QStringList colors = QStringList::split( "|", splashTextColors );
+ QStringList colors = splashTextColors.split( "|", QString::SkipEmptyParts );
QColor c1, c2;
if ( colors.count() > 0 ) c1 = QColor( colors[0] );
if ( colors.count() > 1 ) c2 = QColor( colors[1] );
}
// ...set splash progress colors
if ( !splashProgressColors.isEmpty() ) {
- QStringList colors = QStringList::split( "|", splashProgressColors );
+ QStringList colors = splashProgressColors.split( "|", QString::SkipEmptyParts );
QColor c1, c2;
- int gradType = QtxSplash::Vertical;
+ QtxSplash::GradientType gradType = QtxSplash::Vertical;
if ( colors.count() > 0 ) c1 = QColor( colors[0] );
if ( colors.count() > 1 ) c2 = QColor( colors[1] );
- if ( colors.count() > 2 ) gradType = colors[2].toInt();
+ if ( colors.count() > 2 ) gradType = QtxSplash::GradientType( colors[2].toInt() );
splash->setProgressColors( c1, c2, gradType );
}
// ...set splash text font
#include "SALOMEDS_Tool.hxx"
-#include "utilities.h"
-
#include <iostream>
using namespace std;
--- /dev/null
+#TEMPLATE = lib
+#TARGET = SalomeSession
+#DESTDIR = ../../lib
+#MOC_DIR = ../../moc
+#OBJECTS_DIR = ../../obj/$$TARGET
+
+# ================>
+
+TEMPLATE =
+TARGET = SALOME_Session_Server
+DESTDIR = ../../bin
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+# <================
+
+
+QT_MT_INCLUDES = $$(QTDIR)/include $$(QTDIR)/include/QtCore $$(QTDIR)/include/QtGui $$(QTDIR)/include/QtOpenGL $$(QTDIR)/include/QtXml
+
+PYTHON_INCLUDES = $$(PYTHONHOME)/include/python2.4
+
+HDF5_INCLUDES = $$(HDF5HOME)/include
+
+BOOST_CPPFLAGS = $$(BOOSTDIR)/include
+
+KERNEL_CXXFLAGS = $$(KERNEL_ROOT_DIR)/include/salome
+
+CASROOT = $$(CASROOT)
+CAS_CPPFLAGS = $${CASROOT}/inc
+
+OMNIORBDIR = $$(OMNIORBDIR)
+CORBA_INCLUDES = $${OMNIORBDIR}/include $${OMNIORBDIR}/include/omniORB4 $${OMNIORBDIR}/include/COS
+
+INCLUDEPATH += $${QT_MT_INCLUDES} $${PYTHON_INCLUDES} $${HDF5_INCLUDES} $${BOOST_CPPFLAGS} $${KERNEL_CXXFLAGS} $${CAS_CPPFLAGS} $${CORBA_INCLUDES} ../../salome_adm/unix $$(GUI_ROOT_DIR)/idl ../Qtx ../SUIT ../Event
+
+QT_MT_LIBS = -L$$(QTDIR)/lib -lQtCore -lQtXml -lQtGui -lQtOpenGL
+
+KERNEL_LDFLAGS = -L$$(KERNEL_ROOT_DIR)/lib/salome
+
+CAS_KERNEL = -L$${CASROOT}/Linux/lib -lTKernel
+
+LIBS += $${QT_MT_LIBS} $${KERNEL_LDFLAGS} -lSalomeNS -lSalomeLifeCycleCORBA -lOpUtil -lSALOMELocalTrace -lSalomeCatalog -lSalomeDSClient $${CAS_KERNEL} -L../../lib -lwith_loggerTraceCollector -lsuit -lEvent -L$$(GUI_ROOT_DIR)/idl -lSalomeIDLGUI
+
+# ================>
+
+OMNIORB_LIBS = -L$${OMNIORBDIR}/lib -lomniORB4 -lomniDynamic4 -lCOS4 -lCOSDynamic4 -lomnithread
+
+HDF5_LIBS = -L$$(HDF5HOME)/lib -lhdf5
+
+INCLUDEPATH = $${INCLUDEPATH}
+LIBS = $${LIBS} $${OMNIORB_LIBS} $${HDF5_LIBS} -lSalomeContainer -lSalomeResourcesManager -lTOOLSDS -lSalomeHDFPersist -lSalomeDSImpl -lSalomeGenericObj -lRegistry -lSalomeNotification -lSALOMEBasics -L$$(GUI_ROOT_DIR)/lib -lqtx -lSalomeSession
+
+# <================
+
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += SESSION_EXPORTS OCC_VERSION_MAJOR=6 OCC_VERSION_MINOR=1 OCC_VERSION_MAINTENANCE=1 LIN LINTEL CSFDB No_exception HAVE_CONFIG_H HAVE_LIMITS_H HAVE_WOK_CONFIG_H OCC_CONVERT_SIGNALS OMNIORB_VERSION=4 __x86__ __linux__ COMP_CORBA_DOUBLE COMP_CORBA_LONG
+
+HEADERS = Session_Session_i.hxx
+HEADERS += Session_ServerLauncher.hxx
+HEADERS += Session_ServerThread.hxx
+HEADERS += Session_ServerCheck.hxx
+HEADERS += SalomeApp_Engine_i.hxx
+
+SOURCES = Session_Session_i.cxx
+SOURCES += Session_ServerThread.cxx
+SOURCES += Session_ServerLauncher.cxx
+SOURCES += Session_ServerCheck.cxx
+SOURCES += SalomeApp_Engine_i.cxx
+
+# ================>
+
+SOURCES += SALOME_Session_Server.cxx
+
+# <================
+
+#includes.files = $$HEADERS
+#includes.path = ../../include
+
+#INSTALLS += includes
+
+
#include "Utils_ORB_INIT.hxx"
#include "Utils_SINGLETON.hxx"
#include "SALOME_NamingService.hxx"
-#include "utilities.h"
#include "OpUtil.hxx"
+#include "utilities.h"
+
+#include <QApplication>
+#include <QMutex>
+#include <QWaitCondition>
// Default settings
const int __DEFAULT__ATTEMPTS__ = 300; // number of checks attemtps
ASSERT( SINGLETON_<SALOME_NamingService>::IsAlreadyExisting() );
NS.init_orb( orb );
QString containerName = QString( "/Containers/%1/FactoryServer" ).arg( GetHostname().c_str() );
- CORBA::Object_var obj = NS.Resolve( containerName.latin1() );
+ CORBA::Object_var obj = NS.Resolve( containerName.toLatin1() );
Engines::Container_var FScontainer = Engines::Container::_narrow( obj );
if ( !CORBA::is_nil( FScontainer ) ) {
- MESSAGE( containerName.latin1() << " is found" );
+ MESSAGE( containerName.toLatin1().constData() << " is found" );
FScontainer->ping();
MESSAGE( "FactoryServer container was activated" );
bOk = true;
ASSERT( SINGLETON_<SALOME_NamingService>::IsAlreadyExisting() );
NS.init_orb( orb );
QString containerName = QString( "/Containers/%1/FactoryServerPy" ).arg( GetHostname().c_str() );
- CORBA::Object_var obj = NS.Resolve( containerName.latin1() );
+ CORBA::Object_var obj = NS.Resolve( containerName.toLatin1() );
Engines::Container_var FSPcontainer = Engines::Container::_narrow( obj );
if ( !CORBA::is_nil( FSPcontainer ) ) {
- MESSAGE( containerName.latin1() << " is found" );
+ MESSAGE( containerName.toLatin1().constData() << " is found" );
FSPcontainer->ping();
MESSAGE("FactoryServerPy container was activated");
bOk = true;
ASSERT( SINGLETON_<SALOME_NamingService>::IsAlreadyExisting() );
NS.init_orb( orb );
QString containerName = QString( "/Containers/%1/SuperVisionContainer" ).arg( GetHostname().c_str() );
- CORBA::Object_var obj = NS.Resolve( containerName.latin1() );
+ CORBA::Object_var obj = NS.Resolve( containerName.toLatin1() );
Engines::Container_var SVcontainer = Engines::Container::_narrow( obj );
if ( !CORBA::is_nil( SVcontainer ) ) {
- MESSAGE( containerName.latin1() << " is found" );
+ MESSAGE( containerName.toLatin1().constData() << " is found" );
SVcontainer->ping();
MESSAGE("SuperVisionContainer container was activated");
bOk = true;
QThread::usleep( 30000 );
}
// clear splash status
- splash->setProgress( 0, 0 );
splash->setStatus( initialInfo );
}
#include <SALOME_Session.hxx>
-#include <qthread.h>
-#include <qapplication.h>
+#include <QThread>
class QMutex;
class QWaitCondition;
// $Header$
#include "Session_ServerLauncher.hxx"
+#include "Session_ServerThread.hxx"
#include "Utils_SALOME_Exception.hxx"
#include "utilities.h"
+
+#include <QMutex>
+#include <QWaitCondition>
+
using namespace std;
/*!
default constructor not for use
#include <SALOME_Session.hxx>
-#include "Session_ServerThread.hxx"
-
#include <CORBA.h>
#include <list>
#include <vector>
#include <string>
-#include <qthread.h>
-#include <qwaitcondition.h>
+#include <QThread>
using namespace std;
_servType(servType),_firstArg(firstArg),_lastArg(lastArg)
{}
+class Session_ServerThread;
+
+class QMutex;
+class QWaitCondition;
+
class SESSION_EXPORT Session_ServerLauncher: public QThread
{
public:
#include "Session_ServerThread.hxx"
+#include "SALOME_NamingService.hxx"
#include "SALOME_Container_i.hxx"
#include "SALOME_ContainerManager.hxx"
-#include <SALOMEDSClient.hxx>
#include <SALOMEDSClient_ClientFactory.hxx>
#include "SALOME_ModuleCatalog_impl.hxx"
#include "RegistryService.hxx"
#include <cstdlib>
#include <ctime>
+#include <QMutex>
+#include <QWaitCondition>
+
using namespace std;
const int Session_ServerThread::NB_SRV_TYP = 7;
MESSAGE("Session_ServerThread::Init "<< _argv[0]);
for (int i=0; i<_argc; i++) SCRUTE(_argv[i]);
-#ifndef WNT
+#ifndef WIN32
for (int i=0; i<NB_SRV_TYP; i++)
#else
for (i=0; i<NB_SRV_TYP; i++)
#include <CORBA.h>
#include <string>
-#include "SALOME_NamingService.hxx"
-#include <qthread.h>
-
using namespace std;
void WaitForServerReadiness(string serverName);
+class SALOME_NamingService;
class SESSION_EXPORT Session_ServerThread
{
SALOME_NamingService * _NS;
};
+class QMutex;
+class QWaitCondition;
class SESSION_EXPORT Session_SessionThread : public Session_ServerThread
{
#include "Session_Session_i.hxx"
#include "SALOME_NamingService.hxx"
-#include "SALOME_Event.hxx"
+#include "SALOME_Event.h"
#include "SUIT_Session.h"
-#include "SUIT_Application.h"
+//#include "SUIT_Application.h"
#include "SUIT_Desktop.h"
+#include "SUIT_Study.h"
-#include <qapplication.h>
+//#include <QApplication>
+#include <QMutex>
+#include <QWaitCondition>
// Open CASCADE Includes
#include <OSD_SharedLibrary.hxx>
-#include <OSD_LoadMode.hxx>
#include <OSD_Function.hxx>
using namespace std;
Send a SALOME::StatSession structure (see idl) to the client
(number of running studies and presence of GUI)
*/
-class QtLock
+/*class QtLock
{
public:
QtLock() { if ( qApp ) qApp->lock(); }
~QtLock() { if ( qApp ) qApp->unlock(); }
-};
+};*/
SALOME::StatSession SALOME_Session_i::GetStatSession()
_runningStudies = 0;
{
- QtLock lock;
+ //QtLock lock;
_isGUI = SUIT_Session::session();
if ( _isGUI && SUIT_Session::session()->activeApplication() )
_runningStudies = SUIT_Session::session()->activeApplication()->getNbStudies();
#include <SALOME_Session.hxx>
-#include <qthread.h>
-
#include <SALOMEconfig.h>
#include CORBA_SERVER_HEADER(SALOME_Component)
#include CORBA_SERVER_HEADER(SALOME_Session)
class SALOME_NamingService;
+class QMutex;
+class QWaitCondition;
+
class SESSION_EXPORT SALOME_Session_i: public virtual POA_SALOME::Session,
public virtual PortableServer::ServantBase
{
dist_libToolsGUI_la_SOURCES= \
ToolsGUI_CatalogGeneratorDlg.cxx \
- ToolsGUI_HelpWindow.cxx \
ToolsGUI_RegWidget.cxx \
- ToolsGUI_IntervalWindow.cxx \
ToolsGUI.cxx
EXTRA_DIST+=
MOC_FILES= \
ToolsGUI_CatalogGeneratorDlg_moc.cxx \
- ToolsGUI_RegWidget_moc.cxx \
- ToolsGUI_HelpWindow_moc.cxx \
- ToolsGUI_IntervalWindow_moc.cxx
+ ToolsGUI_RegWidget_moc.cxx
nodist_libToolsGUI_la_SOURCES= $(MOC_FILES)
--- /dev/null
+TEMPLATE = lib
+TARGET = ToolsGUI
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+CASROOT = $$(CASROOT)
+CAS_CPPFLAGS = $${CASROOT}/inc
+
+BOOST_CPPFLAGS = $$(BOOSTDIR)/include
+
+KERNEL_CXXFLAGS = $$(KERNEL_ROOT_DIR)/include/salome
+
+CORBA_INCLUDES = $$(OMNIORBDIR)/include $$(OMNIORBDIR)/include/omniORB4 $$(OMNIORBDIR)/include/COS
+
+CAS_KERNEL = -L$${CASROOT}/Linux/lib -lTKernel
+
+KERNEL_LDFLAGS = -L$$(KERNEL_ROOT_DIR)/lib/salome
+
+INCLUDEPATH += $${CAS_CPPFLAGS} $${BOOST_CPPFLAGS} $${KERNEL_CXXFLAGS} $${CORBA_INCLUDES} ../../salome_adm/unix ../../idl ../Qtx ../SUIT
+LIBS += -L../../lib -lsuit -lSalomeNS -lOpUtil $${CAS_KERNEL} $${KERNEL_LDFLAGS}
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += OCC_VERSION_MAJOR=6 OCC_VERSION_MINOR=1 OCC_VERSION_MAINTENANCE=1 LIN LINTEL CSFDB No_exception HAVE_CONFIG_H HAVE_LIMITS_H HAVE_WOK_CONFIG_H OCC_CONVERT_SIGNALS
+
+HEADERS = ToolsGUI.h
+HEADERS += ToolsGUI_RegWidget.h
+HEADERS += ToolsGUI_CatalogGeneratorDlg.h
+
+SOURCES = ToolsGUI_CatalogGeneratorDlg.cxx
+SOURCES += ToolsGUI_RegWidget.cxx
+SOURCES += ToolsGUI.cxx
+
+TRANSLATIONS = resources/ToolsGUI_icons.ts \
+ resources/ToolsGUI_msg_en.ts
+
+ICONS = resources/*.png
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+resources.files = $$ICONS resources/*.qm
+resources.path = ../../resources
+
+INSTALLS += includes resources
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-//
-//
// File : ToolsGUI.cxx
// Author : Nicolas REJNERI
-// Module : SALOME
-// $Header$
+//
#include "ToolsGUI.h"
/*!
- \return true if object is visible
+ \class ToolsGUI
+ \brief Utility class.
+*/
+
+/*!
+ \brief Get visibility value of the "AttributeGraphic" attribute.
+ \param theStudy study
+ \param theObj object
+ \param theId sub-object identifier
+ \return \c true if an object (sub-object) is visible
*/
bool ToolsGUI::GetVisibility( _PTR(Study) theStudy,
_PTR(SObject) theObj,
}
/*!
- Set flag visibility of object
- \param theStudy - study
- \param theEntry - entry
- \param theValue - flag visibility
- \param theId - id
+ \brief Set visibility value of the "AttributeGraphic" attribute.
+ \param theStudy study
+ \param theObj object
+ \return theValue new visibility value
+ \param theId sub-object identifier
*/
bool ToolsGUI::SetVisibility( _PTR(Study) theStudy,
const char* theEntry,
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-//
-//
// File : ToolsGUI.h
// Author : Nicolas REJNERI
-// Module : SALOME
-// $Header$
-
-#ifndef ToolsGUI_HeaderFile
-#define ToolsGUI_HeaderFile
+//
-#include "utilities.h"
+#ifndef TOOLSGUI_H
+#define TOOLSGUI_H
-#ifndef _Standard_HeaderFile
-#include <Standard.hxx>
-#endif
+#ifdef WIN32
+# ifdef TOOLSGUI_EXPORTS
+# define TOOLSGUI_EXPORT __declspec(dllexport)
+# else
+# define TOOLSGUI_EXPORT __declspec(dllimport)
+# endif
+#else // WIN32
+# define TOOLSGUI_EXPORT
+#endif // WIN32
+#include "utilities.h"
#include "SALOMEDSClient.hxx"
-class Standard_EXPORT ToolsGUI
+class TOOLSGUI_EXPORT ToolsGUI
{
public :
static bool GetVisibility( _PTR(Study) theStudy,
void* theId );
};
-#endif
+#endif // TOOLSGUI_H
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-//
-//
// File : ToolsGUI_CatalogGeneratorDlg.cxx
// Author : Nicolas REJNERI
-// Modified : Marc TAJCHMAN
-// Module : SALOME
-// $Header$
+//
#include "ToolsGUI_CatalogGeneratorDlg.h"
#include "SUIT_Application.h"
-#include "SUIT_Desktop.h"
#include "SUIT_MessageBox.h"
-#include "SUIT_Tools.h"
+//#include "SUIT_Tools.h"
#include "SUIT_Session.h"
#include <stdlib.h>
-#include <qlabel.h>
-#include <qlineedit.h>
-#include <qpushbutton.h>
-#include <qlayout.h>
-#include <qgroupbox.h>
-#include <qstringlist.h>
-#include <qregexp.h>
-#include <qvalidator.h>
-#include <qfile.h>
+
+#include <QLabel>
+#include <QLineEdit>
+#include <QPushButton>
+#include <QGridLayout>
+#include <QGroupBox>
+#include <QStringList>
+#include <QRegExp>
+#include <QIntValidator>
+#include <QFile>
#include <OSD_Process.hxx>
#include <OSD_Path.hxx>
#define MIN_EDIT_SIZE 250
/*!
- Constructor
+ \class ToolsGUI_CatalogGeneratorDlg
+ \brief A dialog box which allows converting the IDL files
+ to the XML description.
*/
-ToolsGUI_CatalogGeneratorDlg::ToolsGUI_CatalogGeneratorDlg( QWidget* parent, const char* name )
- : QDialog( parent, name, TRUE, WStyle_Customize | WStyle_NormalBorder | WStyle_Title | WStyle_SysMenu )
+
+/*!
+ \brief Constructor.
+ \param parent parent widget
+*/
+ToolsGUI_CatalogGeneratorDlg::ToolsGUI_CatalogGeneratorDlg( QWidget* parent )
+: QDialog( parent )
{
- if ( !name )
- setName( "ToolsGUI_CatalogGeneratorDlg" );
- resize( 322, 120 );
- setCaption( tr( "TOOLS_CATALOG_GENERATOR" ) );
- setSizeGripEnabled( TRUE );
+ setModal( true );
+
+ setWindowTitle( tr( "TOOLS_CATALOG_GENERATOR" ) );
+ setSizeGripEnabled( true );
QGridLayout* aTopLayout = new QGridLayout(this);
- aTopLayout->setMargin(MARGIN_SIZE);
- aTopLayout->setSpacing(SPACING_SIZE);
-
- QGroupBox* filesGrp = new QGroupBox( tr( "TOOLS_FILES") , this, "filesGrp" );
- filesGrp->setColumnLayout( 0, Qt::Vertical );
- filesGrp->layout()->setSpacing( 0 );
- filesGrp->layout()->setMargin( 0 );
- QGridLayout* filesGrpLayout = new QGridLayout( filesGrp->layout() );
+ aTopLayout->setMargin( MARGIN_SIZE );
+ aTopLayout->setSpacing( SPACING_SIZE );
+
+ QGroupBox* filesGrp = new QGroupBox( tr( "TOOLS_FILES") , this );
+ filesGrp->setObjectName( "filesGrp" );
+ QGridLayout* filesGrpLayout = new QGridLayout( filesGrp );
filesGrpLayout->setAlignment( Qt::AlignTop );
filesGrpLayout->setSpacing( SPACING_SIZE );
filesGrpLayout->setMargin( MARGIN_SIZE );
- myIdlEdit = new QLineEdit( filesGrp, "myIdlEdit" );
+ myIdlEdit = new QLineEdit( filesGrp );
+ myIdlEdit->setObjectName( "myIdlEdit" );
myIdlEdit->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myIdlEdit->setMinimumSize( MIN_EDIT_SIZE, 0 );
- myXmlEdit = new QLineEdit( filesGrp, "myXmlEdit" );
+ myXmlEdit = new QLineEdit( filesGrp );
+ myXmlEdit->setObjectName( "myXmlEdit" );
myXmlEdit->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myXmlEdit->setMinimumSize( MIN_EDIT_SIZE, 0 );
- myBrowseIdlBtn = new QPushButton( tr( "TOOLS_BUT_BROWSE" ), filesGrp, "myBrowseIdlBtn" );
- myBrowseXmlBtn = new QPushButton( tr( "TOOLS_BUT_BROWSE" ), filesGrp, "myBrowseXmlBtn" );
+ myBrowseIdlBtn = new QPushButton( tr( "TOOLS_BUT_BROWSE" ), filesGrp );
+ myBrowseIdlBtn->setObjectName( "myBrowseIdlBtn" );
+ myBrowseXmlBtn = new QPushButton( tr( "TOOLS_BUT_BROWSE" ), filesGrp );
+ myBrowseXmlBtn->setObjectName( "myBrowseXmlBtn" );
// QFontMetrics fm(myBrowseIdlBtn->font());
// myBrowseIdlBtn->setFixedWidth(fm.width(myBrowseIdlBtn->text()) + 10);
// myBrowseXmlBtn->setFixedWidth(fm.width(myBrowseXmlBtn->text()) + 10);
filesGrpLayout->addWidget( myXmlEdit, 1, 1 );
filesGrpLayout->addWidget( myBrowseXmlBtn, 1, 2 );
- QGroupBox* supplGrp = new QGroupBox(tr( "TOOLS_SUPPLEMENT" ) , this, "SupplGrp" );
- supplGrp->setColumnLayout( 0, Qt::Vertical );
- supplGrp->layout()->setSpacing( 0 );
- supplGrp->layout()->setMargin( 0 );
- QGridLayout* supplGrpLayout = new QGridLayout( supplGrp->layout() );
+ QGroupBox* supplGrp = new QGroupBox(tr( "TOOLS_SUPPLEMENT" ) , this );
+ supplGrp->setObjectName( "SupplGrp" );
+ QGridLayout* supplGrpLayout = new QGridLayout( supplGrp );
supplGrpLayout->setAlignment( Qt::AlignTop );
supplGrpLayout->setSpacing( SPACING_SIZE );
supplGrpLayout->setMargin( MARGIN_SIZE );
QSize myMinimumSize(int(MIN_EDIT_SIZE*0.3), 0);
- myAuthorEdit = new QLineEdit( supplGrp , "myAuthorEdit" );
+ myAuthorEdit = new QLineEdit( supplGrp );
+ myAuthorEdit->setObjectName( "myAuthorEdit" );
myAuthorEdit->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myAuthorEdit->setMinimumSize( myMinimumSize );
OSD_Process aProcess;
myAuthorEdit->setText(aProcess.UserName().ToCString());
- myVersionEdit = new QLineEdit(supplGrp , "myVersion" );
+ myVersionEdit = new QLineEdit( supplGrp );
+ myVersionEdit->setObjectName( "myVersion" );
myVersionEdit->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myVersionEdit->setMinimumSize( myMinimumSize );
- QStringList aList = QStringList::split(QRegExp("\\s+"),tr( "INF_VERSION" ));
+ QStringList aList = tr( "INF_VERSION" ).split(QRegExp("\\s+"), QString::SkipEmptyParts);
myVersionEdit->setText(aList.last());
- myPngEdit = new QLineEdit(supplGrp , "myCompIcon" );
+ myPngEdit = new QLineEdit( supplGrp );
+ myPngEdit->setObjectName( "myCompIcon" );
myPngEdit->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myPngEdit->setMinimumSize( MIN_EDIT_SIZE, 0 );
- myBrowsePngBtn = new QPushButton( tr( "TOOLS_BUT_BROWSE" ), supplGrp, "myBrowsePngBtn" );
+ myBrowsePngBtn = new QPushButton( tr( "TOOLS_BUT_BROWSE" ), supplGrp );
+ myBrowsePngBtn->setObjectName( "myBrowsePngBtn" );
- myCompName = new QLineEdit(supplGrp , "myCompName");
+ myCompName = new QLineEdit( supplGrp );
+ myCompName->setObjectName( "myCompName" );
myCompName->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myCompName->setMinimumSize( myMinimumSize );
- myCompUserName = new QLineEdit(supplGrp , "myCompUserName");
+ myCompUserName = new QLineEdit( supplGrp );
+ myCompUserName->setObjectName( "myCompUserName" );
myCompUserName->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myCompUserName->setMinimumSize( (int)(MIN_EDIT_SIZE*0.3), 0 );
- myCompType = new QLineEdit(supplGrp , "myCompType");
+ myCompType = new QLineEdit( supplGrp );
+ myCompType->setObjectName( "myCompType" );
myCompType->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myCompType->setMinimumSize( myMinimumSize );
myCompType->setText("OTHER");
- myCompMultiStd = new QLineEdit(supplGrp , "myCompMultiStd");
+ myCompMultiStd = new QLineEdit( supplGrp );
+ myCompMultiStd->setObjectName( "myCompMultiStd" );
myCompMultiStd->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
myCompMultiStd->setMinimumSize( myMinimumSize );
myCompMultiStd->setText("1");
supplGrpLayout->addWidget( new QLabel( tr( "TOOLS_COMP_TYPE" ), supplGrp ), 1, 4);
supplGrpLayout->addWidget(myCompType,1,5);
supplGrpLayout->addWidget( new QLabel( tr( "TOOLS_PNG_FILE" ), supplGrp ), 2, 0);
- supplGrpLayout->addMultiCellWidget( myPngEdit, 2,2,1,4 );
+ supplGrpLayout->addWidget( myPngEdit, 2,1,1,4 );
supplGrpLayout->addWidget( myBrowsePngBtn, 2, 5 );
-
QHBoxLayout* aBtnLayout = new QHBoxLayout;
aBtnLayout->setSpacing( SPACING_SIZE );
aBtnLayout->setMargin( 0 );
- myApplyBtn = new QPushButton( tr( "TOOLS_BUT_APPLY" ), this, "myApplyBtn" );
+ myApplyBtn = new QPushButton( tr( "TOOLS_BUT_APPLY" ), this );
+ myApplyBtn->setObjectName( "myApplyBtn" );
myApplyBtn->setAutoDefault( true );
myApplyBtn->setDefault( true );
- myCloseBtn = new QPushButton( tr( "TOOLS_BUT_CLOSE" ), this, "myCloseBtn" );
+ myCloseBtn = new QPushButton( tr( "TOOLS_BUT_CLOSE" ), this );
+ myCloseBtn->setObjectName( "myCloseBtn" );
myCloseBtn->setAutoDefault( true );
aBtnLayout->addWidget( myApplyBtn );
}
/*!
- destructor
+ \brief Destructor
*/
ToolsGUI_CatalogGeneratorDlg::~ToolsGUI_CatalogGeneratorDlg()
{
}
/*!
- \return IDL file name entered
+ \brief Get IDL file name
+ \return IDL file name entered by the user
*/
QString ToolsGUI_CatalogGeneratorDlg::getIdlFile()
{
- return myIdlEdit->text().stripWhiteSpace();
+ return myIdlEdit->text().trimmed();
}
/*!
- \return XML file name entered
+ \brief Get XML file name
+ \return XML file name entered by the user
*/
QString ToolsGUI_CatalogGeneratorDlg::getXmlFile()
{
- return myXmlEdit->text().stripWhiteSpace();
+ return myXmlEdit->text().trimmed();
}
/*!
- \return PNG file name entered
+ \brief Get module icon file name
+ \return icon file name entered by the user
*/
QString ToolsGUI_CatalogGeneratorDlg::getPngFile()
{
- return myPngEdit->text().stripWhiteSpace();
+ return myPngEdit->text().trimmed();
}
/*!
- \return author
+ \brief Get author name
+ \return author name entered by the user
*/
QString ToolsGUI_CatalogGeneratorDlg::getAuthor()
{
- return myAuthorEdit->text().stripWhiteSpace();
+ return myAuthorEdit->text().trimmed();
}
/*!
- \return version number
+ \brief Get version number
+ \return version number entered by the user
*/
QString ToolsGUI_CatalogGeneratorDlg::getVersion()
{
- return myVersionEdit->text().stripWhiteSpace();
+ return myVersionEdit->text().trimmed();
}
/*!
- \return name of the component
+ \brief Get component name
+ \return name of the component entered by the user
*/
QString ToolsGUI_CatalogGeneratorDlg::getCompName()
{
- return myCompName->text().stripWhiteSpace();
+ return myCompName->text().trimmed();
}
/*!
- \return username of the component
+ \brief Get component title (user name)
+ \return title of the component entered by the user
*/
QString ToolsGUI_CatalogGeneratorDlg::getCompUserName()
{
- return myCompUserName->text().stripWhiteSpace();
+ return myCompUserName->text().trimmed();
}
/*!
- \return type of the component
+ \brief Get multistudy flag
+ \return multistudy flag for the component entered by the user
*/
QString ToolsGUI_CatalogGeneratorDlg::getCompMultiStd()
{
- return myCompMultiStd->text().stripWhiteSpace();
+ return myCompMultiStd->text().trimmed();
}
/*!
- \return type of the component
+ \brief Get component type
+ \return type of the component entered by the user
*/
QString ToolsGUI_CatalogGeneratorDlg::getCompType()
{
- return myCompType->text().stripWhiteSpace();
+ return myCompType->text().trimmed();
}
/*!
+ \brief Get IDL path of the modules
\return IDL path of modules
*/
QString ToolsGUI_CatalogGeneratorDlg::getIdlPath()
}
/*!
- SLOT: called on Browse button click
+ \brief Called when user presses "Browse" button
*/
void ToolsGUI_CatalogGeneratorDlg::onBrowseBtnClicked()
{
SUIT_Application* app = SUIT_Session::session()->activeApplication();
if ( send == myBrowseIdlBtn ) {
- QString file = app->getFileName( true, myIdlEdit->text().stripWhiteSpace(), tr("TOOLS_MEN_IMPORT_IDL"), tr("TOOLS_MEN_IMPORT"), 0 );
+ QString file = app->getFileName( true, myIdlEdit->text().trimmed(), tr("TOOLS_MEN_IMPORT_IDL"), tr("TOOLS_MEN_IMPORT"), 0 );
if ( !file.isEmpty() ) {
myIdlEdit->setText(file);
}
}
else if ( send == myBrowseXmlBtn ) {
- QString file = app->getFileName( false, myXmlEdit->text().stripWhiteSpace(), tr("TOOLS_MEN_EXPORT_XML"), tr("TOOLS_MEN_EXPORT"), 0 );
+ QString file = app->getFileName( false, myXmlEdit->text().trimmed(), tr("TOOLS_MEN_EXPORT_XML"), tr("TOOLS_MEN_EXPORT"), 0 );
if ( !file.isEmpty() ) {
myXmlEdit->setText(file);
}
} else if ( send == myBrowsePngBtn ) {
- QString file = app->getFileName( true, myPngEdit->text().stripWhiteSpace(), tr("TOOLS_MEN_IMPORT_PNG"), tr("TOOLS_MEN_IMPORT"), 0 );
+ QString file = app->getFileName( true, myPngEdit->text().trimmed(), tr("TOOLS_MEN_IMPORT_PNG"), tr("TOOLS_MEN_IMPORT"), 0 );
if ( !file.isEmpty() ) {
myPngEdit->setText(file);
}
/*!
- Updates <OK> button's state
+ \brief Update <OK> button's state.
*/
void ToolsGUI_CatalogGeneratorDlg::updateButtonState()
{
- myApplyBtn->setEnabled( !myIdlEdit->text().stripWhiteSpace().isEmpty() &&
- !myXmlEdit->text().stripWhiteSpace().isEmpty() );
+ myApplyBtn->setEnabled( !myIdlEdit->text().trimmed().isEmpty() &&
+ !myXmlEdit->text().trimmed().isEmpty() );
}
/*!
- <Apply> button slot, performs IDL->XML conversion
+ \brief Called when user presses <Apply> button
+
+ Performs IDL to XML file conversion using \c runIDLparser SALOME utility.
*/
void ToolsGUI_CatalogGeneratorDlg::onApply()
{
if ( !XmlFile.isEmpty() && !IdlFile.isEmpty() ) {
if ( !QFile::exists( IdlFile ) ) {
- SUIT_MessageBox::error1( this,
- tr("TOOLS_ERR_ERROR"),
- tr("TOOLS_ERR_FILE_NOT_EXIST").arg(IdlFile),
- tr ("TOOLS_BUT_OK") );
+ SUIT_MessageBox::critical( this,
+ tr("TOOLS_ERR_ERROR"),
+ tr("TOOLS_ERR_FILE_NOT_EXIST").arg(IdlFile) );
}
else {
QString command = "";
if ( getenv("KERNEL_ROOT_DIR") )
command = QString( getenv( "KERNEL_ROOT_DIR" ) ) + "/bin/salome/runIDLparser -K " + IDLpath + " -Wbcatalog=" + XmlFile;
else {
- SUIT_MessageBox::error1( this,
- tr("TOOLS_ERR_ERROR"),
- tr("KERNEL_ROOT_DIR variable is not defined"),
- tr("TOOLS_BUT_OK") );
+ SUIT_MessageBox::critical( this,
+ tr("TOOLS_ERR_ERROR"),
+ tr("KERNEL_ROOT_DIR variable is not defined") );
}
if (!Author.isEmpty()) command += ",author=" + Author;
if (!Version.isEmpty()) command += ",version=" + Version;
if (!PngFile.isEmpty()) {
- OSD_Path aPath((Standard_CString)PngFile.latin1());
+ OSD_Path aPath((Standard_CString)PngFile.toLatin1().constData());
TCollection_AsciiString aFile = aPath.Name() + aPath.Extension();
command += QString(",icon=") + QString(aFile.ToCString());
}
if (!CompType.isEmpty()) command += ",type=" + CompType;
if (!CompMultiStd.isEmpty()) command += ",multistudy=" + CompMultiStd;
command += " " + IdlFile;
- MESSAGE( "shell command is : " << command );
+ MESSAGE( "shell command is : " << command.toLatin1().constData() );
int res;
- res = system( ( char* )( command.latin1() ) );
+ res = system( ( char* )( command.toLatin1().constData() ) );
if ( res == -1 ) {
MESSAGE( "work failed (system command result = " << res );
} else if (res == 217) {
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-//
-//
// File : ToolsGUI_CatalogGeneratorDlg.h
// Author : Nicolas REJNERI
-// Module : SALOME
-// $Header$
+//
-#ifndef DIALOGBOX_TOOLSGUI_CATALOGGENERATORDLG_H
-#define DIALOGBOX_TOOLSGUI_CATALOGGENERATORDLG_H
+#ifndef TOOLSGUI_CATALOGGENERATORDLG_H
+#define TOOLSGUI_CATALOGGENERATORDLG_H
-#include <qdialog.h>
+#include "ToolsGUI.h"
-#include <Standard_Macro.hxx>
+#include <QDialog>
class QLineEdit;
class QPushButton;
-class Standard_EXPORT ToolsGUI_CatalogGeneratorDlg : public QDialog
+class TOOLSGUI_EXPORT ToolsGUI_CatalogGeneratorDlg : public QDialog
{
Q_OBJECT
public:
- ToolsGUI_CatalogGeneratorDlg( QWidget* parent = 0, const char* name = 0 );
+ ToolsGUI_CatalogGeneratorDlg( QWidget* parent = 0 );
~ToolsGUI_CatalogGeneratorDlg();
QString getIdlPath();
QPushButton* myCloseBtn;
};
-#endif // DIALOGBOX_TOOLSGUI_CATALOGGENERATORDLG_H
+#endif // TOOLSGUI_CATALOGGENERATORDLG_H
+++ /dev/null
-// SALOME RegistryDisplay : GUI for Registry server implementation
-//
-// Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-//
-//
-// File : ToolsGUI_HelpWindow.cxx
-// Author : Pascale NOYRET, EDF
-// Module : SALOME
-// $Header$
-
-# include "ToolsGUI_HelpWindow.h"
-# include "utilities.h"
-
-# include <qtextview.h>
-# include <qpushbutton.h>
-# include <qtextstream.h>
-# include <qfile.h>
-
-using namespace std;
-
-/*!
- Constructor
-*/
-ToolsGUI_HelpWindow::ToolsGUI_HelpWindow(QWidget* parent, const char* name )
- : QMainWindow( parent, name, WType_TopLevel | WDestructiveClose )
-{
- BEGIN_OF("Constructeur ToolsGUI_HelpWindow");
-
- setCaption( tr( "Help" ) );
-
- myTextView = new QTextView( this, "myTextView" );
- QPalette pal = myTextView->palette();
- QColorGroup cg = pal.active();
- cg.setColor( QColorGroup::Highlight, QColor( 0, 0, 128) );
- cg.setColor( QColorGroup::HighlightedText, Qt::white );
- cg.setColor( QColorGroup::Base, QColor( 255,255,220 ) );
- cg.setColor( QColorGroup::Text, Qt::black );
- pal.setActive ( cg );
- cg = pal.inactive();
- cg.setColor( QColorGroup::Highlight, QColor( 0, 0, 128) );
- cg.setColor( QColorGroup::HighlightedText, Qt::white );
- cg.setColor( QColorGroup::Base, QColor( 255,255,220 ) );
- cg.setColor( QColorGroup::Text, Qt::black );
- pal.setInactive( cg );
- cg = pal.disabled();
- cg.setColor( QColorGroup::Highlight, QColor( 0, 0, 128) );
- cg.setColor( QColorGroup::HighlightedText, Qt::white );
- cg.setColor( QColorGroup::Base, QColor( 255,255,220 ) );
- cg.setColor( QColorGroup::Text, Qt::black );
- pal.setDisabled( cg );
- myTextView->setPalette( pal );
-
- setCentralWidget( myTextView );
- setMinimumSize( 450, 250 );
-
- QFile f ( "tmp.txt" );
- if ( f.open( IO_ReadOnly ) )
- {
- QTextStream t( &f );
- while ( !t.eof() )
- {
- myTextView->append(t.readLine());
- }
- }
- f.close();
-
- END_OF("Constructeur ToolsGUI_HelpWindow");
-}
-
-/*!
- Destructor
-*/
-ToolsGUI_HelpWindow::~ToolsGUI_HelpWindow()
-{
- BEGIN_OF("Destructeur ToolsGUI_HelpWindow");
- END_OF("Destructeur ToolsGUI_HelpWindow");
-};
-
-/*!
- Sets text
-*/
-void ToolsGUI_HelpWindow::setText( const QString& text )
-{
- myTextView->setText( text );
-}
-
-
+++ /dev/null
-// SALOME RegistryDisplay : GUI for Registry server implementation
-//
-// Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-//
-//
-// File : HelpWindow.hxx
-// Author : Pascale NOYRET, EDF
-// Module : SALOME
-// $Header$
-
-# ifndef __HELPWINDOW_H__
-# define __HELPWINDOW_H__
-
-# include <qapplication.h>
-# include <qmainwindow.h>
-
-class QTextView;
-
-class ToolsGUI_HelpWindow : public QMainWindow
-{
- Q_OBJECT
-
-public:
- ToolsGUI_HelpWindow( QWidget* parent = 0, const char* name = 0);
- ~ToolsGUI_HelpWindow();
-
- void setText( const QString& text );
- QTextView* textView() const { return myTextView; }
-
-private:
- QTextView* myTextView;
-};
-# endif /* __HELPWINDOW_H__ */
-
-
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-// File : ToolsGUI_IntervalWindow.cxx
-// Author : Oksana TCHEBANOVA
-// Module : SALOME
-
-#include "ToolsGUI_IntervalWindow.h"
-
-#include <qbuttongroup.h>
-#include <qlabel.h>
-#include <qpushbutton.h>
-#include <qlayout.h>
-# include "utilities.h"
-
-#define MARGIN_SIZE 11
-#define SPACING_SIZE 6
-#define MIN_SPIN_WIDTH 100
-
-/*!
- Constructor
-*/
-ToolsGUI_IntervalWindow::ToolsGUI_IntervalWindow ( QWidget* parent )
-: QDialog( parent, "ToolsGUI_IntervalWindow" , true, WStyle_Customize | WStyle_NormalBorder | WStyle_Title | WStyle_SysMenu | WDestructiveClose )
-{
- BEGIN_OF("ToolsGUI_IntervalWindow constructor")
- setCaption( tr( "Refresh Interval" ) );
- setSizeGripEnabled( true );
-
- QGridLayout* topLayout = new QGridLayout( this );
- topLayout->setSpacing( SPACING_SIZE );
- topLayout->setMargin( MARGIN_SIZE );
-
- QGroupBox* intervalGrp = new QGroupBox( this, "intervalGrp" );
- intervalGrp->setColumnLayout( 0, Qt::Horizontal );//Vertical
- intervalGrp->layout()->setSpacing( 0 );
- intervalGrp->layout()->setMargin( 0 );
- QGridLayout* intervalGrpLayout = new QGridLayout( intervalGrp->layout() );
- intervalGrpLayout->setAlignment( Qt::AlignTop );
- intervalGrpLayout->setSpacing( SPACING_SIZE );
- intervalGrpLayout->setMargin( MARGIN_SIZE );
-
- QHBoxLayout* aBtnLayout = new QHBoxLayout;
- aBtnLayout->setSpacing( SPACING_SIZE );
- aBtnLayout->setMargin( 0 );
-
- myButtonOk = new QPushButton( this, "buttonOk" );
- myButtonOk->setText( tr( "BUT_OK" ) );
- myButtonOk->setAutoDefault( TRUE );
- myButtonOk->setDefault( TRUE );
-
- myButtonCancel = new QPushButton( this, "buttonCancel" );
- myButtonCancel->setText( tr( "BUT_CANCEL" ) );
- myButtonCancel->setAutoDefault( TRUE );
-
- QLabel* TextLabel = new QLabel( intervalGrp, "TextLabel" );
- TextLabel->setText( tr( "Please, enter a number of seconds:" ) );
-
- mySpinBox = new QSpinBox( 1, 999999999, 1, intervalGrp, "SpinBox" );
- mySpinBox->setValue( 100 );
- mySpinBox->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
- mySpinBox->setMinimumWidth(MIN_SPIN_WIDTH);
-
- intervalGrpLayout->addWidget(TextLabel, 0, 0);
- intervalGrpLayout->addWidget(mySpinBox, 0, 1);
-
- aBtnLayout->addWidget( myButtonOk );
- aBtnLayout->addItem( new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum ) );
- aBtnLayout->addWidget( myButtonCancel );
-
- topLayout->addWidget( intervalGrp, 0, 0 );
- topLayout->addLayout( aBtnLayout, 1, 0 );
-
- END_OF("ToolsGUI_IntervalWindow constructor")
-}
-
-/*!
- Destructor
-*/
-ToolsGUI_IntervalWindow::~ToolsGUI_IntervalWindow() {}
-
-/*!
- Sets start interval size
-*/
-void ToolsGUI_IntervalWindow::setValue(const int size)
-{
- mySpinBox->setValue(size);
-}
-
-/*!
- \return interval size
-*/
-int ToolsGUI_IntervalWindow::getValue()
-{
- return mySpinBox->value();
-}
-
-/*!
- \return a pointer to myButtonOk
-*/
-QPushButton* ToolsGUI_IntervalWindow::Ok()
-{
- return myButtonOk;
-}
-
-/*!
- \return a pointer to myButtonCancel
-*/
-QPushButton* ToolsGUI_IntervalWindow::Cancel()
-{
- return myButtonCancel;
-}
+++ /dev/null
-// Copyright (C) 2005 OPEN CASCADE, CEA/DEN, EDF R&D, PRINCIPIA R&D
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License.
-//
-// This library is distributed in the hope that it will be useful
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-//
-// File : IntervalWindow.hxx
-// Author : Oksana TCHEBANOVA
-// Module : SALOME
-
-#ifndef IntervalWindow_HeaderFile
-#define IntervalWindow_HeaderFile
-
-# include <qwidget.h>
-# include <qdialog.h>
-# include <qpushbutton.h>
-# include <qspinbox.h>
-
-#ifndef WNT
-using namespace std;
-#endif
-
-class ToolsGUI_IntervalWindow : public QDialog
-{
- Q_OBJECT
-
-public:
- ToolsGUI_IntervalWindow( QWidget* parent = 0 );
- ~ToolsGUI_IntervalWindow();
-
- QPushButton* Ok();
- QPushButton* Cancel();
-
- int getValue();
- void setValue( int );
-
-private:
- QSpinBox* mySpinBox;
- QPushButton* myButtonOk;
- QPushButton* myButtonCancel;
-};
-
-#endif
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-//
-//
// File : ToolsGUI_RegWidget.cxx
// Author : Pascale NOYRET, EDF
-// Module : SALOME
-// $Header$
-
-# include <qpushbutton.h>
-# include <qlistview.h>
-# include <qtabwidget.h>
-# include <qstatusbar.h>
-# include <qtextview.h>
-# include <qtimer.h>
-# include <qinputdialog.h>
-# include <qtoolbar.h>
-# include <qdir.h>
-# include <qtooltip.h>
-
-# include "SALOME_NamingService.hxx"
-# include "ServiceUnreachable.hxx"
-# include "Utils_SINGLETON.hxx"
-# include "Utils_CommException.hxx"
-
-# include "utilities.h"
-# include "OpUtil.hxx"
+//
# include "ToolsGUI_RegWidget.h"
-# include "ToolsGUI_HelpWindow.h"
-# include "ToolsGUI_IntervalWindow.h"
-# include "Qtx.h"
+# include <QAction>
+# include <QDialog>
+# include <QSpinBox>
+# include <QPushButton>
+# include <QTreeWidget>
+# include <QTabWidget>
+# include <QStatusBar>
+# include <QTextEdit>
+# include <QTextStream>
+# include <QTimer>
+# include <QToolBar>
+# include <QEvent>
+# include <QKeyEvent>
+# include <QCloseEvent>
+# include <QFileInfo>
+# include <QGridLayout>
+# include <QLabel>
+# include <QGroupBox>
+
+# include <SALOME_NamingService.hxx>
+# include <ServiceUnreachable.hxx>
+# include <Utils_SINGLETON.hxx>
+# include <Utils_CommException.hxx>
-using namespace std;
+# include <utilities.h>
+# include <OpUtil.hxx>
+
+# include <Qtx.h>
typedef int PIXELS;
-ToolsGUI_RegWidget* ToolsGUI_RegWidget::myRegWidgetPtr = 0;
-QString addSlash( const QString& );
-QString findFile( QString filename );
+#define MARGIN_SIZE 11
+#define SPACING_SIZE 6
+#define MIN_SPIN_WIDTH 100
+
+static const char* SEPARATOR = ":";
+
+/*!
+ \brief Add system-dependant slash to the end of path.
+ \internal
+ \param path path string to be extended by the slash
+ \return modified path string
+*/
+static QString addSlash( const QString& path )
+{
+ return Qtx::addSlash( path );
+}
+
+/*!
+ \brief Find file.
+ \internal
+
+ The search of the file is done in the following order:
+ - ${HOME}/.salome/resources directory
+ - ${SALOME_SITE_DIR}/share/${SALOME_SITE_NAME}/resources
+ (SALOME_SITE_NAME defaults to the "salome")
+ - ${KERNEL_ROOT_DIR}/share/salome/resources/kernel directory
+ - ${GUI_ROOT_DIR}/share/salome/resources/gui directory
+ - ${CSF_SalomeResources} directory (it can be directory list,
+ separated by ":" symbol)
+
+ \param filename file name
+ \return file path if it is found or null string otherwise
+*/
+static QString findFile( QString filename )
+{
+ QString dir;
+ char* cenv;
+
+ // Try ${HOME}/.salome/resources directory
+ cenv = getenv( "HOME" );
+ if ( cenv ) {
+ dir.sprintf( "%s", cenv );
+ if ( !dir.isEmpty() ) {
+ dir = addSlash(dir) ;
+ dir = dir + ".salome" ;
+ dir = addSlash(dir) ;
+ dir = dir + "resources" ;
+ dir = addSlash(dir) ;
+ QFileInfo fileInfo( dir + filename );
+ if ( fileInfo.isFile() && fileInfo.exists() )
+ return fileInfo.filePath();
+ }
+ }
+ // Try ${SALOME_SITE_DIR}/share/salome/resources directory
+ cenv = getenv( "SALOME_SITE_DIR" );
+ if ( cenv ) {
+ dir.sprintf( "%s", cenv );
+ if ( !dir.isEmpty() ) {
+ dir = addSlash(dir) ;
+ dir = dir + "share" ;
+ dir = addSlash(dir) ;
+ cenv = getenv("SALOME_SITE_NAME");
+ if (cenv) dir = dir + cenv;
+ else dir = dir + "salome" ;
+ dir = addSlash(dir) ;
+ dir = dir + "resources" ;
+ dir = addSlash(dir) ;
+ QFileInfo fileInfo( dir + filename );
+ if ( fileInfo.isFile() && fileInfo.exists() )
+ return fileInfo.filePath();
+ }
+ }
+ // Try ${KERNEL_ROOT_DIR}/share/salome/resources/kernel directory
+ cenv = getenv( "KERNEL_ROOT_DIR" );
+ if ( cenv ) {
+ dir.sprintf( "%s", cenv );
+ if ( !dir.isEmpty() ) {
+ dir = addSlash(dir) ;
+ dir = dir + "share" ;
+ dir = addSlash(dir) ;
+ dir = dir + "salome" ;
+ dir = addSlash(dir) ;
+ dir = dir + "resources" ;
+ dir = addSlash(dir) ;
+ dir = dir + "kernel" ;
+ dir = addSlash(dir) ;
+ QFileInfo fileInfo( dir + filename );
+ if ( fileInfo.isFile() && fileInfo.exists() )
+ return fileInfo.filePath();
+ }
+ }
+
+ // Try ${GUI_ROOT_DIR}/share/salome/resources/gui directory
+ cenv = getenv( "GUI_ROOT_DIR" );
+ if ( cenv ) {
+ dir.sprintf( "%s", cenv );
+ if ( !dir.isEmpty() ) {
+ dir = addSlash(dir) ;
+ dir = dir + "share" ;
+ dir = addSlash(dir) ;
+ dir = dir + "salome" ;
+ dir = addSlash(dir) ;
+ dir = dir + "resources" ;
+ dir = addSlash(dir) ;
+ dir = dir + "gui" ;
+ dir = addSlash(dir) ;
+ QFileInfo fileInfo( dir + filename );
+ if ( fileInfo.isFile() && fileInfo.exists() )
+ return fileInfo.filePath();
+ }
+ }
+
+ // Try CSF_SalomeResources env.var directory ( or directory list )
+ cenv = getenv( "CSF_SalomeResources" );
+ if ( cenv ) {
+ dir.sprintf( "%s", cenv );
+ if ( !dir.isEmpty() )
+ {
+ QStringList dirList = dir.split( SEPARATOR, QString::SkipEmptyParts ); // skip empty entries
+ for ( int i = 0; i < (int)dirList.count(); i++ )
+ {
+ QFileInfo fileInfo( addSlash( dirList[ i ] ) + filename );
+ if ( fileInfo.isFile() && fileInfo.exists() )
+ return fileInfo.filePath();
+ }
+ }
+ }
+ return filename;
+}
#define BOLD( text ) ( QString( "<b>" ) + QString( text ) + QString( "</b>" ) )
"......aaaaa....."};
/*!
- Creates components list
+ \brief Create components list.
+ \internal
+ \param orb CORBA ORB reference
+ \return list of registered components
*/
-
-Registry::Components_var MakeRegistry( CORBA::ORB_var &orb )
+static Registry::Components_var MakeRegistry( CORBA::ORB_var& orb )
{
const char *registryName="Registry" ;
}
/*!
- Only one global registry window should exist at the moment
- This method creates registry window if necessary and returns it
- [ static ]
+ \class ToolsGUI_RegWidget::ToolsGUI_InfoWindow
+ \brief Information window.
+ \internal
+*/
+
+class ToolsGUI_RegWidget::ToolsGUI_InfoWindow : public QMainWindow
+{
+public:
+ ToolsGUI_InfoWindow( QWidget* parent );
+
+ void setText( const QString& text );
+
+protected:
+ void keyPressEvent( QKeyEvent * e );
+
+private:
+ QTextEdit* myTextView;
+};
+
+/*!
+ \brief Constructor.
+ \internal
+ \param parent parent widget
+*/
+ToolsGUI_RegWidget::ToolsGUI_InfoWindow::ToolsGUI_InfoWindow( QWidget* parent )
+: QMainWindow( parent )
+{
+ setAttribute( Qt::WA_DeleteOnClose );
+
+ myTextView = new QTextEdit( this );
+ myTextView->setReadOnly( true );
+ setCentralWidget( myTextView );
+ setMinimumSize( 450, 250 );
+}
+
+/*!
+ \brief Set text to the information window.
+ \internal
+ \param text ionfo text
+*/
+void ToolsGUI_RegWidget::ToolsGUI_InfoWindow::setText( const QString& text )
+{
+ myTextView->setText( text );
+}
+
+/*!
+ \brief Key press event handler. Closeswindow on \c Escape key pressing.
+ \internal
+ \param e key press event
+*/
+void ToolsGUI_RegWidget::ToolsGUI_InfoWindow::keyPressEvent( QKeyEvent * e )
+{
+ QMainWindow::keyPressEvent( e );
+ if ( e->key() == Qt::Key_Escape )
+ close();
+}
+
+/*!
+ \class ToolsGUI_RegWidget::ToolsGUI_HelpWindow
+ \brief Help window.
+ \internal
+*/
+
+class ToolsGUI_RegWidget::ToolsGUI_HelpWindow : public QMainWindow
+{
+public:
+ ToolsGUI_HelpWindow( QWidget* parent );
+ ~ToolsGUI_HelpWindow();
+
+ void setText( const QString& text );
+
+private:
+ QTextEdit* myTextView;
+};
+
+/*!
+ \brief Constructor.
+ \internal
+ \param parent parent widget
+*/
+ToolsGUI_RegWidget::ToolsGUI_HelpWindow::ToolsGUI_HelpWindow( QWidget* parent )
+: QMainWindow( parent )
+{
+ setAttribute( Qt::WA_DeleteOnClose );
+ setWindowTitle( tr( "Help" ) );
+
+ myTextView = new QTextEdit( this );
+ myTextView->setReadOnly( true );
+ QPalette pal = myTextView->palette();
+
+ pal.setBrush( QPalette::Active, QPalette::Highlight, QBrush( QColor( 0, 0, 128 ) ) );
+ pal.setBrush( QPalette::Active, QPalette::HighlightedText, QBrush( Qt::white ) );
+ pal.setBrush( QPalette::Active, QPalette::Base, QBrush( QColor( 255,255,220 ) ) );
+ pal.setBrush( QPalette::Active, QPalette::Text, QBrush( Qt::black ) );
+
+ pal.setBrush( QPalette::Inactive, QPalette::Highlight, QBrush( QColor( 0, 0, 128 ) ) );
+ pal.setBrush( QPalette::Inactive, QPalette::HighlightedText, QBrush( Qt::white ) );
+ pal.setBrush( QPalette::Inactive, QPalette::Base, QBrush( QColor( 255,255,220 ) ) );
+ pal.setBrush( QPalette::Inactive, QPalette::Text, QBrush( Qt::black ) );
+
+ pal.setBrush( QPalette::Disabled, QPalette::Highlight, QBrush( QColor( 0, 0, 128 ) ) );
+ pal.setBrush( QPalette::Disabled, QPalette::HighlightedText, QBrush( Qt::white ) );
+ pal.setBrush( QPalette::Disabled, QPalette::Base, QBrush( QColor( 255,255,220 ) ) );
+ pal.setBrush( QPalette::Disabled, QPalette::Text, QBrush( Qt::black ) );
+
+ myTextView->setPalette( pal );
+
+ setCentralWidget( myTextView );
+ setMinimumSize( 450, 250 );
+
+ QFile f ( "tmp.txt" );
+ if ( f.open( QIODevice::ReadOnly ) ) {
+ QTextStream t( &f );
+ while ( !t.atEnd() ) {
+ myTextView->append( t.readLine() );
+ }
+ }
+ f.close();
+}
+
+/*!
+ \brief Destructor.
+ \internal
+*/
+ToolsGUI_RegWidget::ToolsGUI_HelpWindow::~ToolsGUI_HelpWindow()
+{
+};
+
+/*!
+ \brief Set text to the help window.
+ \internal
+ \param text help text
+*/
+void ToolsGUI_RegWidget::ToolsGUI_HelpWindow::setText( const QString& text )
+{
+ myTextView->setText( text );
+}
+
+/*!
+ \class ToolsGUI_RegWidget::ToolsGUI_IntervalWindow
+ \brief Dialog box to enter time delay between registry window updates
+ \internal
+*/
+
+class ToolsGUI_RegWidget::ToolsGUI_IntervalWindow : public QDialog
+{
+public:
+ ToolsGUI_IntervalWindow( QWidget* parent );
+ ~ToolsGUI_IntervalWindow();
+
+ QPushButton* Ok();
+ QPushButton* Cancel();
+
+ int getValue();
+ void setValue( int );
+
+private:
+ QSpinBox* mySpinBox;
+ QPushButton* myButtonOk;
+ QPushButton* myButtonCancel;
+};
+
+/*!
+ \brief Constructor.
+ \internal
+ \param parent parent widget
+*/
+ToolsGUI_RegWidget::ToolsGUI_IntervalWindow::ToolsGUI_IntervalWindow ( QWidget* parent )
+: QDialog( parent )
+{
+ setModal( true );
+ setAttribute( Qt::WA_DeleteOnClose );
+
+ setWindowTitle( tr( "Refresh Interval" ) );
+ setSizeGripEnabled( true );
+
+ QGridLayout* topLayout = new QGridLayout( this );
+ topLayout->setSpacing( SPACING_SIZE );
+ topLayout->setMargin( MARGIN_SIZE );
+
+ QGroupBox* intervalGrp = new QGroupBox( this );
+ intervalGrp->setObjectName( "intervalGrp" );
+ QGridLayout* intervalGrpLayout = new QGridLayout( intervalGrp );
+ intervalGrpLayout->setAlignment( Qt::AlignTop );
+ intervalGrpLayout->setSpacing( SPACING_SIZE );
+ intervalGrpLayout->setMargin( MARGIN_SIZE );
+
+ QHBoxLayout* aBtnLayout = new QHBoxLayout;
+ aBtnLayout->setSpacing( SPACING_SIZE );
+ aBtnLayout->setMargin( 0 );
+
+ myButtonOk = new QPushButton( this );
+ myButtonOk->setObjectName( "buttonOk" );
+ myButtonOk->setText( tr( "BUT_OK" ) );
+ myButtonOk->setAutoDefault( TRUE );
+ myButtonOk->setDefault( TRUE );
+
+ myButtonCancel = new QPushButton( this );
+ myButtonCancel->setObjectName( "buttonCancel" );
+ myButtonCancel->setText( tr( "BUT_CANCEL" ) );
+ myButtonCancel->setAutoDefault( TRUE );
+
+ QLabel* TextLabel = new QLabel( intervalGrp );
+ TextLabel->setObjectName( "TextLabel" );
+ TextLabel->setText( tr( "Please, enter a number of seconds:" ) );
+
+ mySpinBox = new QSpinBox( intervalGrp );
+ mySpinBox->setMinimum( 1 );
+ mySpinBox->setMaximum( 999999999 );
+ mySpinBox->setSingleStep( 1 );
+ mySpinBox->setObjectName( "SpinBox" );
+ mySpinBox->setValue( 100 );
+ mySpinBox->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
+ mySpinBox->setMinimumWidth(MIN_SPIN_WIDTH);
+
+ intervalGrpLayout->addWidget(TextLabel, 0, 0);
+ intervalGrpLayout->addWidget(mySpinBox, 0, 1);
+
+ aBtnLayout->addWidget( myButtonOk );
+ aBtnLayout->addItem( new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum ) );
+ aBtnLayout->addWidget( myButtonCancel );
+
+ topLayout->addWidget( intervalGrp, 0, 0 );
+ topLayout->addLayout( aBtnLayout, 1, 0 );
+}
+
+/*!
+ \brief Destructor
+ \internal
+*/
+ToolsGUI_RegWidget::ToolsGUI_IntervalWindow::~ToolsGUI_IntervalWindow()
+{
+}
+
+/*!
+ \brief Set time interval value
+ \internal
+ \param size interval value
*/
-ToolsGUI_RegWidget* ToolsGUI_RegWidget::GetRegWidget( CORBA::ORB_var &orb , QWidget *parent, const char *name )
+void ToolsGUI_RegWidget::ToolsGUI_IntervalWindow::setValue( const int size )
+{
+ mySpinBox->setValue(size);
+}
+
+/*!
+ \brief Get time interval value
+ \internal
+ \return interval value
+*/
+int ToolsGUI_RegWidget::ToolsGUI_IntervalWindow::getValue()
+{
+ return mySpinBox->value();
+}
+
+/*!
+ \brief Get \c OK button
+ \internal
+ \return a pointer to \c OK button
+*/
+QPushButton* ToolsGUI_RegWidget::ToolsGUI_IntervalWindow::Ok()
+{
+ return myButtonOk;
+}
+
+/*!
+ \brief Get \c Cancel button
+ \internal
+ \return a pointer to \c Cancel button
+*/
+QPushButton* ToolsGUI_RegWidget::ToolsGUI_IntervalWindow::Cancel()
+{
+ return myButtonCancel;
+}
+
+/*!
+ \class ToolsGUI_RegWidget
+ \brief SALOME Registry tool window.
+*/
+
+//! The only instance of Registry window
+ToolsGUI_RegWidget* ToolsGUI_RegWidget::myRegWidgetPtr = 0;
+
+/*!
+ \brief Create/get the only instance of the Registry window.
+ \param orb CORBA ORB reference
+ \param parent parent widget
+*/
+ToolsGUI_RegWidget* ToolsGUI_RegWidget::GetRegWidget( CORBA::ORB_var& orb,
+ QWidget* parent )
{
if ( !myRegWidgetPtr )
- myRegWidgetPtr = new ToolsGUI_RegWidget( orb, parent, name );
+ myRegWidgetPtr = new ToolsGUI_RegWidget( orb, parent );
return myRegWidgetPtr;
}
/*!
- Constructor
+ \brief This virtual function is reimplenented to disable popup menu on dock areas
+ (instead of QMainWindow::setDockMenuEnabled( false ) method used in Qt3).
+ \return always 0 to disable menu
*/
-ToolsGUI_RegWidget::ToolsGUI_RegWidget(CORBA::ORB_var &orb, QWidget *parent, const char *name )
- : QMainWindow( parent, name, WType_TopLevel | WDestructiveClose ),
- _VarComponents( MakeRegistry(orb) ),
- _clients(0), _history(0), _parent( parent ),
- _tabWidget(0), _refresh(0), _interval(0),
- myInfoWindow(0), myHelpWindow(0), myIntervalWindow(0)
+QMenu* ToolsGUI_RegWidget::createPopupMenu()
{
- QString aFile = findFile("default.png");
- /* char* dir = getenv( "CSF_ResourcesDefaults" );
- QString path( "" );
- if ( dir ) {
- QDir qDir( dir );
- path = qDir.filePath( "default.png" );
- }*/
+ QMenu* aPopup = 0;
+ return aPopup;
+}
+
+/*!
+ \brief Constructor
+ \param orb CORBA ORB reference
+ \param parent parent widget
+*/
+ToolsGUI_RegWidget::ToolsGUI_RegWidget( CORBA::ORB_var& orb, QWidget* parent )
+: QMainWindow( parent, Qt::Window ),
+ _VarComponents( MakeRegistry(orb) ),
+ _clients( 0 ),
+ _history( 0 ),
+ _parent( parent ),
+ _tabWidget( 0 ),
+ _refresh( 0 ),
+ _interval( 0 ),
+ myInfoWindow( 0 ),
+ myHelpWindow( 0 ),
+ myIntervalWindow( 0 )
+{
+ setAttribute( Qt::WA_DeleteOnClose );
+
+ QString aFile = findFile("default.png");
+
QPixmap pm ( aFile );
if ( !pm.isNull() )
- setIcon( pm );
+ setWindowIcon( pm );
// pixmap for buttons
QPixmap image_refresh ( ( const char** ) refresh_data );
// Buttons definition
QToolBar* topbar = new QToolBar( tr("Toolbar"), this );
- setDockEnabled( topbar, DockTornOff, false );
- setDockMenuEnabled( false );
-
- _refresh = new QPushButton( tr( "Refresh" ), topbar );
- _refresh->setIconSet( image_refresh );
- _refresh->setFocusPolicy( NoFocus );
- connect( _refresh, SIGNAL( clicked() ), this, SLOT( slotListeSelect() ) );
- QToolTip::add( _refresh, "", toolTipGroup(), tr("Immediately updates list of components") );
+ topbar->setToolButtonStyle( Qt::ToolButtonTextBesideIcon );
+ addToolBar( Qt::TopToolBarArea, topbar );
+
+ _refresh = topbar->addAction(image_refresh, tr( "Refresh" ), this, SLOT( slotListeSelect() ));
+ _refresh->setToolTip( "" );
+ _refresh->setStatusTip( tr("Immediately updates list of components") );
/* PAL5540 - this button is needless
QPushButton* help = new QPushButton( tr( "Help" ), topbar );
QToolTip::add( help, "", toolTipGroup(), tr("Opens Help window") );
*/
- _interval = new QPushButton( tr( "Interval" ), topbar );
- _interval->setIconSet( image_interval );
- _interval->setFocusPolicy( NoFocus );
- connect( _interval, SIGNAL( clicked() ), this, SLOT( slotSelectRefresh() ) );
- QToolTip::add( _interval, "", toolTipGroup(), tr("Changes refresh interval") );
+ _interval = topbar->addAction(image_interval, tr( "Interval" ), this, SLOT( slotSelectRefresh() ));
+ _interval->setToolTip( "" );
+ _interval->setStatusTip( tr("Changes refresh interval") );
topbar->addSeparator();
- _close = new QPushButton( tr("Close"), topbar );
- _close->setIconSet( image_close );
- _close->setFocusPolicy( NoFocus );
- connect( _close, SIGNAL( clicked() ), this, SLOT( close() ) );
- QToolTip::add( _close, "", toolTipGroup(), tr("Closes Registry window") );
+
+ _close = topbar->addAction( image_close, tr("Close"), this, SLOT( close() ));
+ _close->setToolTip( "" );
+ _close->setStatusTip( tr("Closes Registry window") );
// Display area and associated slots definition
_tabWidget = new QTabWidget( this );
- _clients = new QListView( _tabWidget );
+ _clients = new QTreeWidget( _tabWidget );
SetListe();
- _history = new QListView( _tabWidget );
+ _history = new QTreeWidget( _tabWidget );
SetListeHistory();
_tabWidget->addTab( _clients, tr( "Running" ) );
_tabWidget->addTab( _history, tr( "History" ) );
connect( _tabWidget, SIGNAL( currentChanged( QWidget* )), this, SLOT( slotListeSelect() ) );
- connect( _clients, SIGNAL( clicked( QListViewItem* ) ), this, SLOT( slotClientChanged( QListViewItem* ) ) );
- connect( _history, SIGNAL( clicked( QListViewItem* ) ), this, SLOT( slotHistoryChanged( QListViewItem* ) ) );
+ connect( _clients, SIGNAL( clicked( QTreeWidgetItem* ) ), this, SLOT( slotClientChanged( QTreeWidgetItem* ) ) );
+ connect( _history, SIGNAL( clicked( QTreeWidgetItem* ) ), this, SLOT( slotHistoryChanged( QTreeWidgetItem* ) ) );
setCentralWidget( _tabWidget );
// Timer definition (used to automaticaly refresh the display area)
PIXELS largeur = 800 ;
PIXELS hauteur = 350 ;
setGeometry( xpos, ypos, largeur, hauteur ) ;
- setCaption( name ) ;
- statusBar()->message(" ");
+ setWindowTitle( tr( "Registry" ) ) ;
+ statusBar()->showMessage(" ");
}
/*!
- Destructor
+ \brief Destructor
*/
ToolsGUI_RegWidget::~ToolsGUI_RegWidget()
{
- MESSAGE("Debut du Destructeur");
_counter->stop();
myRegWidgetPtr = 0;
};
/*!
- Event filter
+ \brief Event filter
+ \param object event receiver
+ \param event event being processed
+ \return \c true if event processing should be stopped
*/
bool ToolsGUI_RegWidget::eventFilter( QObject* object, QEvent* event )
{
}
else if ( object == _clients && event->type() == QEvent::KeyPress ) {
QKeyEvent* ke = (QKeyEvent*)event;
- if ( ke->key() == Key_Enter || ke->key() == Key_Return ) {
+ if ( ke->key() == Qt::Key_Enter || ke->key() == Qt::Key_Return ) {
slotClientChanged( _clients->currentItem() );
}
}
else if ( object == _history && event->type() == QEvent::KeyPress ) {
QKeyEvent* ke = (QKeyEvent*)event;
- if ( ke->key() == Key_Enter || ke->key() == Key_Return ) {
+ if ( ke->key() == Qt::Key_Enter || ke->key() == Qt::Key_Return ) {
slotHistoryChanged( _history->currentItem() );
}
}
}
/*!
- Searches item in the list and returns it's index or -1 if not found
+ \brief Search item in the list.
+ \param name component name
+ \param pid PID
+ \param machine machine name
+ \param listclient list of registry data
+ \return item index or -1 if it is not found.
*/
-int ToolsGUI_RegWidget::numitem(const QString &name, const QString &pid, const QString &machine,const Registry::AllInfos *listclient)
+int ToolsGUI_RegWidget::numitem( const QString& name,
+ const QString& pid,
+ const QString& machine,
+ const Registry::AllInfos* listclient )
{
- BEGIN_OF("numitem");
- for (CORBA::ULong i=0; i<listclient->length(); i++)
- {
- const Registry::Infos & c_info=(*listclient)[i];
- ASSERT( c_info.name!=NULL);
- QString b;
- b.setNum(int(c_info.pid));
- if ( (name.compare(QString(c_info.name)) == 0) &&
- (machine.compare(QString(c_info.machine)) == 0) &&
- (pid.compare(b) == 0) )
- {
- END_OF("numitem");
- return i;
- }
+ for (CORBA::ULong i=0; i<listclient->length(); i++) {
+ const Registry::Infos & c_info=(*listclient)[i];
+ ASSERT( c_info.name!=NULL);
+ QString b;
+ b.setNum(int(c_info.pid));
+ if ( (name.compare(QString(c_info.name)) == 0) &&
+ (machine.compare(QString(c_info.machine)) == 0) &&
+ (pid.compare(b) == 0) ) {
+ return i;
}
- END_OF("numitem");
+ }
return -1;
}
/*!
- Returns text, containing information about client [ static ]
+ \brief Get description text, containing information about client.
+ \param c_info client info data
+ \return formatted client description
*/
-QString ToolsGUI_RegWidget::setlongText( const Registry::Infos &c_info)
+QString ToolsGUI_RegWidget::setlongText( const Registry::Infos& c_info )
{
- BEGIN_OF("setlongText");
ASSERT( c_info.name != NULL );
QString a = QString( "<hr><h2>" ) + tr( "Code" ) + QString( " : " );
a.append( QString( c_info.name ) );
delete [] t1;
a.append( "<br>" );
- if (c_info.tc_hello != 0 )
- {
- aTime = time_t(c_info.tc_hello);
- char * t2 = (char * )duplicate(ctime(&aTime));
- t2 [strlen(t2) -1 ] = ' ';
- a.append( tr( "last signal" ) + QString(" : ") );
- a.append( BOLD( t2 ) );
- a.append( "<br>" );
- delete [] t2;
- }
- if ((c_info.tc_end - c_info.difftime) != 0)
- {
- aTime = time_t(c_info.tc_end);
- char * t3 = (char * )duplicate(ctime(&aTime));
- t3 [strlen(t3) -1 ] = ' ';
- a.append( tr( "ends" ) + QString( " " ) );
- a.append( BOLD( t3 ) );
- a.append( "<br>" );
- delete [] t3;
- }
- else
- {
- a.append( tr( "still running" ) + QString( "<br>" ) );
- }
+ if (c_info.tc_hello != 0 ) {
+ aTime = time_t(c_info.tc_hello);
+ char * t2 = (char * )duplicate(ctime(&aTime));
+ t2 [strlen(t2) -1 ] = ' ';
+ a.append( tr( "last signal" ) + QString(" : ") );
+ a.append( BOLD( t2 ) );
+ a.append( "<br>" );
+ delete [] t2;
+ }
+ if ((c_info.tc_end - c_info.difftime) != 0) {
+ aTime = time_t(c_info.tc_end);
+ char * t3 = (char * )duplicate(ctime(&aTime));
+ t3 [strlen(t3) -1 ] = ' ';
+ a.append( tr( "ends" ) + QString( " " ) );
+ a.append( BOLD( t3 ) );
+ a.append( "<br>" );
+ delete [] t3;
+ }
+ else {
+ a.append( tr( "still running" ) + QString( "<br>" ) );
+ }
SCRUTE(c_info.difftime);
- if (c_info.difftime!= 0)
- {
- a.append( QString( "(" ) + tr( "Time on" ) + QString( " " ) );
- a.append( BOLD( c_info.machine ) );
- a.append( QString( " " ) + tr( "differs from server's time. The difference is" ) + QString( " " ));
- a.append( BOLD( QString::number( int( c_info.difftime ) ) ) );
- a.append( QString( " " ) + tr( "seconds" ) + QString( ")<br>" ) );
- }
+ if (c_info.difftime!= 0) {
+ a.append( QString( "(" ) + tr( "Time on" ) + QString( " " ) );
+ a.append( BOLD( c_info.machine ) );
+ a.append( QString( " " ) + tr( "differs from server's time. The difference is" ) + QString( " " ));
+ a.append( BOLD( QString::number( int( c_info.difftime ) ) ) );
+ a.append( QString( " " ) + tr( "seconds" ) + QString( ")<br>" ) );
+ }
a.append( "</code>" ); // ASV: 28.07.06 : added <code> tags to make the text font be
// fixed width (looks much better on Windows)
- END_OF("setlongText");
return a;
}
/*!
- Close event
+ \brief Close event handler.
+ \param e close event
*/
-void ToolsGUI_RegWidget::closeEvent( QCloseEvent *e)
+void ToolsGUI_RegWidget::closeEvent( QCloseEvent* e )
{
- BEGIN_OF("closeEvent");
if ( myInfoWindow )
myInfoWindow->close();
if ( myHelpWindow )
if (myIntervalWindow)
myIntervalWindow->close();
e->accept();
- END_OF("closeEvent");
};
/*!
- Setups Clients list
+ \brief Setup clients list.
*/
void ToolsGUI_RegWidget::SetListe()
{
- BEGIN_OF("SetListe");
_clients->installEventFilter( this );
+ _clients->setColumnCount(6);
_clients->setAllColumnsShowFocus( true );
- _clients->addColumn( tr( "Component" ), -1);
- _clients->addColumn( tr( "PID" ), -1 );
- _clients->addColumn( tr( "User Name" ), -1 );
- _clients->addColumn( tr( "Machine" ), -1 );
- _clients->addColumn( tr( "begins" ), -1 );
- _clients->addColumn( tr( "hello" ) , -1 );
- _clients->setColumnAlignment( 1, Qt::AlignRight );
- END_OF("SetListe");
+ QStringList aLabels;
+ aLabels << tr("Component") << tr("PID") << tr("User Name") << tr("Machine") << tr("begins") << tr("hello");
+ _clients->setHeaderLabels( aLabels );
+ //_clients->setColumnAlignment( 1, Qt::AlignRight );
}
/*!
- Setups History list
+ \brief Setup history list.
*/
void ToolsGUI_RegWidget::SetListeHistory()
{
- BEGIN_OF("SetListeHistory")
_history->installEventFilter( this );
+ _history->setColumnCount(6);
_history->setAllColumnsShowFocus( true );
- _history->addColumn( tr( "Component" ), -1);
- _history->addColumn( tr( "PID" ), -1 );
- _history->addColumn( tr( "User Name" ), -1 );
- _history->addColumn( tr( "Machine" ), -1 );
- _history->addColumn( tr( "begins" ), -1 );
- _history->addColumn( tr( "ends" ), -1 );
- _history->setColumnAlignment( 1, Qt::AlignRight );
- END_OF("SetListeHistory")
+ QStringList aLabels;
+ aLabels << tr("Component") << tr("PID") << tr("User Name") << tr("Machine") << tr("begins") << tr("ends");
+ _history->setHeaderLabels( aLabels );
+ //_history->setColumnAlignment( 1, Qt::AlignRight );
}
/*!
- Updates History list
+ \brief Update history list
*/
void ToolsGUI_RegWidget::InfoHistory()
{
- BEGIN_OF("InfoHistory")
- _history->clear();
- try
- {
- time_t aTime;
- _serverhistory = _VarComponents->history();
- for (CORBA::ULong i=0; i<_serverhistory->length(); i++)
- {
- const Registry::Infos & c_info=(*_serverhistory)[i];
- ASSERT( c_info.name!=NULL);
- QString a;
- a.setNum(int(c_info.pid));
- aTime = time_t(c_info.tc_start);
- char * t1 = (char * )duplicate(ctime(&aTime));
- t1 [strlen(t1) -1 ] = ' ';
- aTime = time_t(c_info.tc_end);
- char * t2 = (char * )duplicate(ctime(&aTime));
- t2 [strlen(t2) -1 ] = ' ';
- QListViewItem * item = new QListViewItem(_history, QString(c_info.name),\
- a, QString(c_info.pwname), QString(c_info.machine), \
- QString(t1), QString(t2));
- item=0 ;
- delete [] t1;
- delete [] t2;
-
- }
- }
- catch( ... )
- {
- _interval->setDisabled( TRUE ) ;
- _refresh->setDisabled( TRUE ) ;
- _counter->stop();
- MESSAGE("Sorry, No more Registry Server") ;
- statusBar()->message( tr( "Sorry, No more Registry Server" ) ) ;
+ _history->clear();
+ try {
+ time_t aTime;
+ _serverhistory = _VarComponents->history();
+ for (CORBA::ULong i=0; i<_serverhistory->length(); i++) {
+ const Registry::Infos & c_info=(*_serverhistory)[i];
+ ASSERT( c_info.name!=NULL);
+ QString a;
+ a.setNum(int(c_info.pid));
+ aTime = time_t(c_info.tc_start);
+ char * t1 = (char * )duplicate(ctime(&aTime));
+ t1 [strlen(t1) -1 ] = ' ';
+ aTime = time_t(c_info.tc_end);
+ char * t2 = (char * )duplicate(ctime(&aTime));
+ t2 [strlen(t2) -1 ] = ' ';
+ QStringList anItem;
+ anItem << QString(c_info.name) << a << QString(c_info.pwname) << QString(c_info.machine) << QString(t1) << QString(t2);
+ QTreeWidgetItem * item = new QTreeWidgetItem(_history, anItem);
+ item=0 ;
+ delete [] t1;
+ delete [] t2;
+
}
- END_OF("InfoHistory")
+ }
+ catch( ... ) {
+ _interval->setDisabled( TRUE ) ;
+ _refresh->setDisabled( TRUE ) ;
+ _counter->stop();
+ MESSAGE("Sorry, No more Registry Server") ;
+ statusBar()->showMessage( tr( "Sorry, No more Registry Server" ) ) ;
+ }
}
/*!
- Updates clients list
+ \brief Update clients list
*/
void ToolsGUI_RegWidget::InfoReg()
{
- BEGIN_OF("InfoReg")
_clients->clear();
- try
- {
- time_t aTime;
- _serverclients = _VarComponents->getall();
- for (CORBA::ULong i=0; i<_serverclients->length(); i++)
- {
- const Registry::Infos & c_info=(*_serverclients)[i];
- ASSERT( c_info.name!=NULL);
- QString a;
- a.setNum(int(c_info.pid));
- aTime = time_t(c_info.tc_start);
- char * t1 = (char * )duplicate(ctime(&aTime));
- t1 [strlen(t1) -1 ] = ' ';
- aTime = time_t(c_info.tc_hello);
- char * t2 = (char * )duplicate(ctime(&aTime));
- t2 [strlen(t2) -1 ] = ' ';
- QListViewItem * item = new QListViewItem(_clients, QString(c_info.name),\
- a, QString(c_info.pwname), QString(c_info.machine), \
- QString(t1), QString(t2));
- item=0 ;
- delete [] t1;
- delete [] t2;
-
- }
- }
- catch( ... )
- {
- _interval->setDisabled( TRUE ) ;
- _refresh->setDisabled( TRUE ) ;
- _counter->stop();
- MESSAGE("Sorry, No more Registry Server") ;
- statusBar()->message( tr( "Sorry, No more Registry Server" ) ) ;
+ try {
+ time_t aTime;
+ _serverclients = _VarComponents->getall();
+ for (CORBA::ULong i=0; i<_serverclients->length(); i++) {
+ const Registry::Infos & c_info=(*_serverclients)[i];
+ ASSERT( c_info.name!=NULL);
+ QString a;
+ a.setNum(int(c_info.pid));
+ aTime = time_t(c_info.tc_start);
+ char * t1 = (char * )duplicate(ctime(&aTime));
+ t1 [strlen(t1) -1 ] = ' ';
+ aTime = time_t(c_info.tc_hello);
+ char * t2 = (char * )duplicate(ctime(&aTime));
+ t2 [strlen(t2) -1 ] = ' ';
+ QStringList anItem;
+ anItem << QString(c_info.name) << a << QString(c_info.pwname) << QString(c_info.machine) << QString(t1) << QString(t2);
+ QTreeWidgetItem * item = new QTreeWidgetItem(_clients, anItem);
+ item=0 ;
+ delete [] t1;
+ delete [] t2;
+
}
- END_OF("InfoReg")
+ }
+ catch( ... ) {
+ _interval->setDisabled( TRUE ) ;
+ _refresh->setDisabled( TRUE ) ;
+ _counter->stop();
+ MESSAGE("Sorry, No more Registry Server") ;
+ statusBar()->showMessage( tr( "Sorry, No more Registry Server" ) ) ;
+ }
}
/*!
- Called when <Refresh> button is clicked
+ \brief Called when \c Refresh button is clicked
*/
void ToolsGUI_RegWidget::slotListeSelect()
{
- try
- {
- ASSERT(_tabWidget->currentPage() != NULL);
- if (_tabWidget->currentPage () == _clients) InfoReg();
- else if (_tabWidget->currentPage () == _history) InfoHistory();
- }
- catch( ... )
- {
- MESSAGE("Sorry, No more Registry Server") ;
- statusBar()->message( tr( "Sorry, No more Registry Server" ) ) ;
- }
+ try {
+ ASSERT(_tabWidget->currentWidget() != NULL);
+ if (_tabWidget->currentWidget () == _clients) InfoReg();
+ else if (_tabWidget->currentWidget () == _history) InfoHistory();
+ }
+ catch( ... ) {
+ MESSAGE("Sorry, No more Registry Server") ;
+ statusBar()->showMessage( tr( "Sorry, No more Registry Server" ) ) ;
+ }
}
/*!
- Called when <Interval> button is clicked (changing refresh interval)
+ \brief Called when \c Interval button is clicked (open dialog box to
+ change refresh interval).
*/
void ToolsGUI_RegWidget::slotSelectRefresh()
{
- BEGIN_OF("slotSelectRefresh");
- myIntervalWindow = new ToolsGUI_IntervalWindow(this);
+ myIntervalWindow = new ToolsGUI_RegWidget::ToolsGUI_IntervalWindow(this);
myIntervalWindow->installEventFilter( this );
myIntervalWindow->setValue(myRefreshInterval);
myIntervalWindow->show();
connect( myIntervalWindow->Cancel(), SIGNAL( clicked() ), myIntervalWindow, SLOT( close() ) );
connect( myIntervalWindow->Ok(), SIGNAL( clicked() ), this, SLOT( slotIntervalOk() ) );
- END_OF("slotSelectRefresh");
}
/*!
- SLOT: called when IntervalWindow's OK button is clicked
+ \brief Called when IntervalWindow's \c OK button is clicked
*/
void ToolsGUI_RegWidget::slotIntervalOk()
{
- BEGIN_OF("slotIntervalOk");
myRefreshInterval = myIntervalWindow->getValue();
- _counter->changeInterval( myRefreshInterval * 1000 );
+ _counter->start( myRefreshInterval * 1000 );
SCRUTE(myRefreshInterval);
myIntervalWindow->close();
- END_OF("slotIntervalOk");
}
/*!
- Called when <Help> button is clicked
+ \brief Called when \c Help button is clicked
*/
void ToolsGUI_RegWidget::slotHelp()
{
- BEGIN_OF("slotHelp()");
-
if ( !myHelpWindow ) {
- myHelpWindow = new ToolsGUI_HelpWindow( this );
+ myHelpWindow = new ToolsGUI_RegWidget::ToolsGUI_HelpWindow( this );
myHelpWindow->installEventFilter( this );
}
myHelpWindow->show();
myHelpWindow->raise();
- myHelpWindow->setActiveWindow();
-
- END_OF("slotHelp()") ;
+ myHelpWindow->activateWindow();
}
/*!
- Called when user clicks on item in <Running> list
+ \brief Called when user clicks on item in \c Running list
+ \param item item clicked by the user
*/
-void ToolsGUI_RegWidget::slotClientChanged( QListViewItem* item )
+void ToolsGUI_RegWidget::slotClientChanged( QTreeWidgetItem* item )
{
- BEGIN_OF("slotClientChanged()") ;
-
if ( item <= 0)
return;
int numeroItem = numitem(item->text(0), item->text(1), item->text(3), _serverclients);
SCRUTE(numeroItem) ;
- SCRUTE(item->text(1)) ;
+ SCRUTE(item->text(1).toLatin1().constData()) ;
ASSERT(numeroItem>=0) ;
ASSERT((size_t)numeroItem<_serverclients->length()) ;
ASSERT( c_info.name!=NULL);
if ( !myInfoWindow ) {
- myInfoWindow = new ToolsGUI_InfoWindow( this );
+ myInfoWindow = new ToolsGUI_RegWidget::ToolsGUI_InfoWindow( this );
myInfoWindow->installEventFilter( this );
}
QString a = tr( "More about" ) + QString( " " ) + QString( c_info.name );
- myInfoWindow->setCaption(a);
+ myInfoWindow->setWindowTitle(a);
myInfoWindow->setText( ToolsGUI_RegWidget::setlongText( c_info) );
myInfoWindow->show();
myInfoWindow->raise();
- myInfoWindow->setActiveWindow();
+ myInfoWindow->activateWindow();
blockSignals( false ); // enabling signals again
-
- END_OF("slotClientChanged()") ;
- return ;
}
/*!
- Called when user clicks on item in <History> list
+ \brief Called when user clicks on item in \c History list
+ \param item item clicked by the user
*/
-void ToolsGUI_RegWidget::slotHistoryChanged( QListViewItem* item )
+void ToolsGUI_RegWidget::slotHistoryChanged( QTreeWidgetItem* item )
{
-
- BEGIN_OF("slotHistoryChanged()") ;
-
if ( item <= 0)
return;
int numeroItem = numitem(item->text(0), item->text(1), item->text(3), _serverhistory);
SCRUTE(numeroItem) ;
- SCRUTE(item->text(1)) ;
+ SCRUTE(item->text(1).toLatin1().constData()) ;
ASSERT(numeroItem>=0) ;
ASSERT((size_t)numeroItem<_serverhistory->length()) ;
const Registry::Infos & c_info=(*_serverhistory)[numeroItem];
ASSERT( c_info.name!=NULL);
if ( !myInfoWindow ) {
- myInfoWindow = new ToolsGUI_InfoWindow( this );
+ myInfoWindow = new ToolsGUI_RegWidget::ToolsGUI_InfoWindow( this );
myInfoWindow->installEventFilter( this );
}
QString a = tr( "More about" ) + QString( " " ) + QString( c_info.name );
- myInfoWindow->setCaption(a);
+ myInfoWindow->setWindowTitle(a);
myInfoWindow->setText( ToolsGUI_RegWidget::setlongText( c_info ) );
myInfoWindow->show();
myInfoWindow->raise();
- myInfoWindow->setActiveWindow();
+ myInfoWindow->activateWindow();
blockSignals( false ); // enabling signals again
-
- END_OF("slotHistoryChanged()") ;
- return ;
}
-/*!
- Constructor
-*/
-ToolsGUI_InfoWindow::ToolsGUI_InfoWindow( QWidget* parent, const char* name )
- : QMainWindow( parent, name, WType_TopLevel | WDestructiveClose )
-{
- BEGIN_OF("InfoWindow");
- myTextView = new QTextView( this, "myTextView" );
- setCentralWidget( myTextView );
- setMinimumSize( 450, 250 );
- END_OF("InfoWindow");
-}
-
-/*!
- Sets text
-*/
-void ToolsGUI_InfoWindow::setText( const QString& text )
-{
- myTextView->setText( text );
-}
-
-/*!
- Key press event
-*/
-void ToolsGUI_InfoWindow::keyPressEvent( QKeyEvent * e )
-{
- QMainWindow::keyPressEvent( e );
- if ( e->key() == Key_Escape )
- close();
-}
-
-static const char* SEPARATOR = ":";
-
-QString findFile( QString filename )
-{
- QString dir;
- char* cenv;
-
- // Try ${HOME}/.salome/resources directory
- cenv = getenv( "HOME" );
- if ( cenv ) {
- dir.sprintf( "%s", cenv );
- if ( !dir.isEmpty() ) {
- dir = addSlash(dir) ;
- dir = dir + ".salome" ;
- dir = addSlash(dir) ;
- dir = dir + "resources" ;
- dir = addSlash(dir) ;
- QFileInfo fileInfo( dir + filename );
- if ( fileInfo.isFile() && fileInfo.exists() )
- return fileInfo.filePath();
- }
- }
- // Try ${SALOME_SITE_DIR}/share/salome/resources directory
- cenv = getenv( "SALOME_SITE_DIR" );
- if ( cenv ) {
- dir.sprintf( "%s", cenv );
- if ( !dir.isEmpty() ) {
- dir = addSlash(dir) ;
- dir = dir + "share" ;
- dir = addSlash(dir) ;
- cenv = getenv("SALOME_SITE_NAME");
- if (cenv) dir = dir + cenv;
- else dir = dir + "salome" ;
- dir = addSlash(dir) ;
- dir = dir + "resources" ;
- dir = addSlash(dir) ;
- QFileInfo fileInfo( dir + filename );
- if ( fileInfo.isFile() && fileInfo.exists() )
- return fileInfo.filePath();
- }
- }
- // Try ${KERNEL_ROOT_DIR}/share/salome/resources directory
- cenv = getenv( "KERNEL_ROOT_DIR" );
- if ( cenv ) {
- dir.sprintf( "%s", cenv );
- if ( !dir.isEmpty() ) {
- dir = addSlash(dir) ;
- dir = dir + "share" ;
- dir = addSlash(dir) ;
- dir = dir + "salome" ;
- dir = addSlash(dir) ;
- dir = dir + "resources" ;
- dir = addSlash(dir) ;
- dir = dir + "kernel" ;
- dir = addSlash(dir) ;
- QFileInfo fileInfo( dir + filename );
- if ( fileInfo.isFile() && fileInfo.exists() )
- return fileInfo.filePath();
- }
- }
-
- //SRN Added support for SALOMEGUI
- cenv = getenv( "SALOMEGUI_ROOT_DIR" );
- if ( cenv ) {
- dir.sprintf( "%s", cenv );
- if ( !dir.isEmpty() ) {
- dir = addSlash(dir) ;
- dir = dir + "share" ;
- dir = addSlash(dir) ;
- dir = dir + "salome" ;
- dir = addSlash(dir) ;
- dir = dir + "resources" ;
- dir = addSlash(dir) ;
- QFileInfo fileInfo( dir + filename );
- if ( fileInfo.isFile() && fileInfo.exists() )
- return fileInfo.filePath();
- }
- }
-
- // Try CSF_SaloameResources env.var directory ( or directory list )
- cenv = getenv( "CSF_SalomeResources" );
- if ( cenv ) {
- dir.sprintf( "%s", cenv );
- if ( !dir.isEmpty() )
- {
- QStringList dirList = QStringList::split( SEPARATOR, dir, false ); // skip empty entries
- for ( int i = 0; i < (int)dirList.count(); i++ )
- {
- QFileInfo fileInfo( addSlash( dirList[ i ] ) + filename );
- if ( fileInfo.isFile() && fileInfo.exists() )
- return fileInfo.filePath();
- }
- }
- }
- return filename;
-}
-
-QString addSlash( const QString& path )
-{
- return Qtx::addSlash( path );
-}
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-//
-//
-// File : RegWidget.h
+// File : ToolsGUI_RegWidget.h
// Author : Pascale NOYRET, EDF
-// Module : SALOME
-// $Header$
+//
+
+#ifndef TOOLSGUI_REGWIDGET_H
+#define TOOLSGUI_REGWIDGET_H
+
+#include "ToolsGUI.h"
-#ifndef __REGWIDGET_H__
-#define __REGWIDGET_H__
-#include <qapplication.h>
-#include <qmainwindow.h>
+#include <QMainWindow>
#include <SALOMEconfig.h>
#include CORBA_CLIENT_HEADER(SALOME_Registry)
class QTabWidget;
-class QListView;
-class QListViewItem;
+class QTreeWidget;
+class QTreeWidgetItem;
class QWidget;
class QTimer;
class QCloseEvent;
-class QTextView;
-#if QT_VERSION > 300
-class QPushButton;
-#endif
+class QAction;
-#include <Standard_Macro.hxx>
-
-class ToolsGUI_HelpWindow;
-class ToolsGUI_IntervalWindow;
-
-class Standard_EXPORT ToolsGUI_InfoWindow : public QMainWindow
+class TOOLSGUI_EXPORT ToolsGUI_RegWidget : public QMainWindow
{
Q_OBJECT
-public:
- ToolsGUI_InfoWindow( QWidget* parent = 0, const char* name = 0);
-
- void setText( const QString& text );
- QTextView* textView() const { return myTextView; }
-
-protected:
- void keyPressEvent( QKeyEvent * e );
-
-private:
- QTextView* myTextView;
-};
-
-class Standard_EXPORT ToolsGUI_RegWidget : public QMainWindow
-{
- Q_OBJECT
+ class ToolsGUI_HelpWindow;
+ class ToolsGUI_IntervalWindow;
+ class ToolsGUI_InfoWindow;
public:
- ToolsGUI_RegWidget( CORBA::ORB_var &orb , QWidget *parent = 0, const char *name = 0 );
+ ToolsGUI_RegWidget( CORBA::ORB_var& orb, QWidget* parent = 0 );
~ToolsGUI_RegWidget();
- void SetListe();
- void SetListeHistory();
- void InfoReg();
- void InfoHistory();
- bool eventFilter( QObject* object, QEvent* event );
+ void SetListe();
+ void SetListeHistory();
+ void InfoReg();
+ void InfoHistory();
+
+ bool eventFilter( QObject* object, QEvent* event );
- static ToolsGUI_RegWidget* GetRegWidget( CORBA::ORB_var &orb , QWidget *parent = 0, const char *name = 0 );
+ static ToolsGUI_RegWidget* GetRegWidget( CORBA::ORB_var& orb,
+ QWidget* parent = 0 );
+
+ virtual QMenu* createPopupMenu();
public slots:
- void slotHelp();
- void slotListeSelect();
- void slotClientChanged( QListViewItem* );
- void slotHistoryChanged( QListViewItem* );
- void slotSelectRefresh();
- void slotIntervalOk();
+ void slotHelp();
+ void slotListeSelect();
+ void slotClientChanged( QTreeWidgetItem* );
+ void slotHistoryChanged( QTreeWidgetItem* );
+ void slotSelectRefresh();
+ void slotIntervalOk();
+
protected:
- static QString setlongText( const Registry::Infos &c_info );
- int numitem( const QString& name, const QString& pid, const QString& machine, const Registry::AllInfos* c_info );
- void closeEvent( QCloseEvent *e);
+ static QString setlongText( const Registry::Infos& c_info );
+ int numitem( const QString& name,
+ const QString& pid,
+ const QString& machine,
+ const Registry::AllInfos* clistclient );
+ void closeEvent( QCloseEvent* e );
protected :
- QListView* _clients;
- QListView* _history;
- QWidget* _parent;
- QTabWidget* _tabWidget;
- QPushButton* _refresh;
- QPushButton* _interval;
- QPushButton* _close;
- QTimer* _counter;
- Registry::AllInfos* _serverhistory;
- Registry::AllInfos* _serverclients;
- ToolsGUI_InfoWindow* myInfoWindow;
- ToolsGUI_HelpWindow* myHelpWindow;
- ToolsGUI_IntervalWindow* myIntervalWindow;
- int myRefreshInterval;
+ QTreeWidget* _clients;
+ QTreeWidget* _history;
+ QWidget* _parent;
+ QTabWidget* _tabWidget;
+ QAction* _refresh;
+ QAction* _interval;
+ QAction* _close;
+ QTimer* _counter;
+ Registry::AllInfos* _serverhistory;
+ Registry::AllInfos* _serverclients;
+ ToolsGUI_InfoWindow* myInfoWindow;
+ ToolsGUI_HelpWindow* myHelpWindow;
+ ToolsGUI_IntervalWindow* myIntervalWindow;
+ int myRefreshInterval;
private:
- const Registry::Components_var _VarComponents;
- static ToolsGUI_RegWidget* myRegWidgetPtr;
+ const Registry::Components_var _VarComponents;
+ static ToolsGUI_RegWidget* myRegWidgetPtr;
};
-#endif
+#endif // TOOLSGUI_REGWIDGET_H
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>ToolsGUI_CatalogGeneratorDlg</name>
+ <message>
+ <source>ICON_SELECT</source>
+ <translation>select1.png</translation>
+ </message>
+</context>
+</TS>
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>TOOLS_WRN_WARNING</source>
+ <translation>Warning</translation>
+ </message>
+ <message>
+ <source>TOOLS_BUT_BROWSE</source>
+ <translation>Browse...</translation>
+ </message>
+ <message>
+ <source>TOOLS_ERR_ERROR</source>
+ <translation>Error</translation>
+ </message>
+ <message>
+ <source>TOOLS_ERR_FILE_NOT_EXIST</source>
+ <translation>%1
+File doesn't exist</translation>
+ </message>
+ <message>
+ <source>TOOLS_BUT_OK</source>
+ <translation>&Ok</translation>
+ </message>
+ <message>
+ <source>TOOLS_BUT_APPLY</source>
+ <translation>&Apply</translation>
+ </message>
+ <message>
+ <source>TOOLS_BUT_CLOSE</source>
+ <translation>&Close</translation>
+ </message>
+</context>
+<context>
+ <name>ToolsGUI_CatalogGeneratorDlg</name>
+ <message>
+ <source>TOOLS_MEN_EXPORT</source>
+ <translation>Export</translation>
+ </message>
+ <message>
+ <source>TOOLS_MEN_IMPORT</source>
+ <translation>Import</translation>
+ </message>
+ <message>
+ <source>TOOLS_VERSION</source>
+ <translation>Version : </translation>
+ </message>
+ <message>
+ <source>TOOLS_COMP_NAME</source>
+ <translation>Name : </translation>
+ </message>
+ <message>
+ <source>TOOLS_COMP_TYPE</source>
+ <translation>Type : </translation>
+ </message>
+ <message>
+ <source>TOOLS_XML_FILE</source>
+ <translation>XML : </translation>
+ </message>
+ <message>
+ <source>TOOLS_PNG_FILE</source>
+ <translation>Icon : </translation>
+ </message>
+ <message>
+ <source>TOOLS_SUPPLEMENT</source>
+ <translation>Component supplementary data</translation>
+ </message>
+ <message>
+ <source>TOOLS_AUTHOR</source>
+ <translation>Author : </translation>
+ </message>
+ <message>
+ <source>TOOLS_COMP_MULTISTD</source>
+ <translation>Multistudy : </translation>
+ </message>
+ <message>
+ <source>TOOLS_COMP_USERNAME</source>
+ <translation>UserName : </translation>
+ </message>
+ <message>
+ <source>TOOLS_CATALOG_GENERATOR</source>
+ <translation>Catalog generator</translation>
+ </message>
+ <message>
+ <source>TOOLS_FILES</source>
+ <translation>Files</translation>
+ </message>
+ <message>
+ <source>TOOLS_MEN_IMPORT_PNG</source>
+ <translation>PNG Files ( *.png )</translation>
+ </message>
+ <message>
+ <source>TOOLS_MEN_IMPORT_IDL</source>
+ <translation>IDL Files ( *.idl )</translation>
+ </message>
+ <message>
+ <source>TOOLS_MEN_EXPORT_XML</source>
+ <translation>XML Files ( *.xml )</translation>
+ </message>
+ <message>
+ <source>TOOLS_IDL_FILE</source>
+ <translation>IDL : </translation>
+ </message>
+</context>
+</TS>
#ifndef VTKVIEWER_H
#define VTKVIEWER_H
-#ifdef WNT
+#ifdef WIN32
# ifdef VTKVIEWER_EXPORTS
# define VTKVIEWER_EXPORT __declspec( dllexport )
# else
--- /dev/null
+TEMPLATE = lib
+TARGET = VTKViewer
+DESTDIR = ../../lib
+MOC_DIR = ../../moc
+OBJECTS_DIR = ../../obj/$$TARGET
+
+VTKHOME = $$(VTKHOME)
+VTK_INCLUDES = $${VTKHOME}/include/vtk
+
+VTK_LIBS = -L$${VTKHOME}/lib/vtk -L$${VTKHOME}/lib/vtk/python -lvtkCommon -lvtkGraphics -lvtkImaging -lvtkFiltering -lvtkIO -lvtkRendering -lvtkHybrid -lvtkParallel -lvtkWidgets -lGL -L/usr/X11R6/lib -lGLU -L/usr/X11R6/lib -lX11 -lXt
+
+CASROOT = $$(CASROOT)
+CAS_CPPFLAGS = $${CASROOT}/inc
+
+CAS_KERNEL = -L$${CASROOT}/Linux/lib -lTKernel
+
+INCLUDEPATH += ../../include $${VTK_INCLUDES} $${CAS_CPPFLAGS} ../Qtx ../SUIT
+LIBS += -L../../lib -lqtx -lsuit $${VTK_LIBS} $${CAS_KERNEL}
+
+CONFIG -= debug release debug_and_release
+CONFIG += qt thread debug dll shared
+
+win32:DEFINES += WIN32
+DEFINES += VTKVIEWER_EXPORTS OCC_VERSION_MAJOR=6 OCC_VERSION_MINOR=1 OCC_VERSION_MAINTENANCE=1 LIN LINTEL CSFDB No_exception HAVE_CONFIG_H HAVE_LIMITS_H HAVE_WOK_CONFIG_H OCC_CONVERT_SIGNALS
+
+HEADERS = VTKViewer.h
+HEADERS += VTKViewer_CellLocationsArray.h
+HEADERS += VTKViewer_Actor.h
+HEADERS += VTKViewer_ExtractUnstructuredGrid.h
+HEADERS += VTKViewer_ConvexTool.h
+HEADERS += VTKViewer_Filter.h
+HEADERS += VTKViewer_GeometryFilter.h
+HEADERS += VTKViewer_AppendFilter.h
+HEADERS += VTKViewer_Algorithm.h
+HEADERS += VTKViewer_InteractorStyle.h
+HEADERS += VTKViewer_RenderWindow.h
+HEADERS += VTKViewer_RenderWindowInteractor.h
+HEADERS += VTKViewer_ShrinkFilter.h
+HEADERS += VTKViewer_TransformFilter.h
+HEADERS += VTKViewer_Transform.h
+HEADERS += VTKViewer_Trihedron.h
+HEADERS += VTKViewer_Utilities.h
+HEADERS += VTKViewer_ViewManager.h
+HEADERS += VTKViewer_ViewModel.h
+HEADERS += VTKViewer_ViewWindow.h
+HEADERS += VTKViewer_Functor.h
+
+SOURCES = VTKViewer_CellLocationsArray.cxx
+SOURCES += VTKViewer_Actor.cxx
+SOURCES += VTKViewer_ExtractUnstructuredGrid.cxx
+SOURCES += VTKViewer_Filter.cxx
+SOURCES += VTKViewer_GeometryFilter.cxx
+SOURCES += VTKViewer_AppendFilter.cxx
+SOURCES += VTKViewer_InteractorStyle.cxx
+SOURCES += VTKViewer_RenderWindow.cxx
+SOURCES += VTKViewer_RenderWindowInteractor.cxx
+SOURCES += VTKViewer_ShrinkFilter.cxx
+SOURCES += VTKViewer_Transform.cxx
+SOURCES += VTKViewer_TransformFilter.cxx
+SOURCES += VTKViewer_Trihedron.cxx
+SOURCES += VTKViewer_Utilities.cxx
+SOURCES += VTKViewer_ViewManager.cxx
+SOURCES += VTKViewer_ViewModel.cxx
+SOURCES += VTKViewer_ConvexTool.cxx
+SOURCES += VTKViewer_ViewWindow.cxx
+
+TRANSLATIONS = resources/VTKViewer_images.ts \
+ resources/VTKViewer_msg_en.ts
+
+ICONS = resources/*.png
+
+includes.files = $$HEADERS
+includes.path = ../../include
+
+resources.files = $$ICONS resources/*.qm
+resources.path = ../../resources
+
+INSTALLS += includes resources
#include <set>
#include <map>
-#ifdef WNT
+#ifdef WIN32
#include <algorithm>
#endif
#include <vtkSmartPointer.h>
#include <vtkProperty.h>
-#include <qapplication.h>
-//VRV: porting on Qt 3.0.5
-#if QT_VERSION >= 0x030005
-#include <qpainter.h>
-#endif
-//VRV: porting on Qt 3.0.5
+#include <QApplication>
+#include <QRubberBand>
+
#include <algorithm>
//#include "utilities.h"
myPreSelectionActor->GetProperty()->SetLineWidth(5);
myPreSelectionActor->GetProperty()->SetPointSize(5);
+ myRectBand = 0;
+
OnSelectionModeChanged();
}
VTKViewer_InteractorStyle::~VTKViewer_InteractorStyle()
{
m_ViewWnd->RemoveActor(myPreSelectionActor);
+ endDrawRect();
}
/*! Loads cursors for viewer operations - zoom, pan, etc...*/
void VTKViewer_InteractorStyle::loadCursors()
{
- myDefCursor = QCursor(ArrowCursor);
- myHandCursor = QCursor(PointingHandCursor);
- myPanCursor = QCursor(SizeAllCursor);
+ myDefCursor = QCursor(Qt::ArrowCursor);
+ myHandCursor = QCursor(Qt::PointingHandCursor);
+ myPanCursor = QCursor(Qt::SizeAllCursor);
myZoomCursor = QCursor(QPixmap(imageZoomCursor));
myRotateCursor = QCursor(QPixmap(imageRotateCursor));
mySpinCursor = QCursor(QPixmap(imageRotateCursor)); // temporarly !!!!!!
- myGlobalPanCursor = QCursor(CrossCursor);
+ myGlobalPanCursor = QCursor(Qt::CrossCursor);
myCursorState = false;
}
}
}
+/*!
+ Draws rectangle by starting and current points
+*/
+void VTKViewer_InteractorStyle::drawRect()
+{
+ if ( !myRectBand ) {
+ myRectBand = new QRubberBand( QRubberBand::Rectangle, myGUIWindow );
+ QPalette palette;
+ palette.setColor(myRectBand->foregroundRole(), Qt::white);
+ myRectBand->setPalette(palette);
+ }
+ myRectBand->hide();
+
+ QRect aRect(myPoint, myOtherPoint);
+ myRectBand->setGeometry( aRect );
+ myRectBand->setVisible( aRect.isValid() );
+}
+
+/*!
+ \brief Delete rubber band on the end on the dragging operation.
+*/
+void VTKViewer_InteractorStyle::endDrawRect()
+{
+ delete myRectBand;
+ myRectBand = 0;
+}
/*! called when viewer operation started (!put necessary initialization here!)*/
void VTKViewer_InteractorStyle::onStartOperation()
case VTK_INTERACTOR_STYLE_CAMERA_SELECT:
case VTK_INTERACTOR_STYLE_CAMERA_FIT:
{
- QPainter p(myGUIWindow);
- p.setPen(Qt::lightGray);
- p.setRasterOp(Qt::XorROP);
- p.drawRect(QRect(myPoint, myOtherPoint));
+ drawRect();
break;
}
case VTK_INTERACTOR_STYLE_CAMERA_ZOOM:
}
case VTK_INTERACTOR_STYLE_CAMERA_FIT:
{
- QPainter p(myGUIWindow);
- p.setPen(Qt::lightGray);
- p.setRasterOp(Qt::XorROP);
- p.drawRect(QRect(myPoint, myOtherPoint));
myOtherPoint = mousePos;
- p.drawRect(QRect(myPoint, myOtherPoint));
+ drawRect();
break;
}
}
class vtkCell;
class vtkRenderWindowInteractor;
-#include <qobject.h>
-#include <qcursor.h>
+#include <QObject>
+#include <QCursor>
+
+class QRubberBand;
#include <map>
virtual void onCursorMove(QPoint mousePos);
virtual void setCursor(const int operation);
+ void drawRect();
+ void endDrawRect();
protected:
QCursor myDefCursor;
std::map<int, Handle(VTKViewer_Filter) > myFilters;
+ QRubberBand* myRectBand; //!< selection rectangle rubber band
+
/** @name members from old version*/
//@{
double DeltaElevation;
//
#include "VTKViewer_RenderWindow.h"
-#include <qcolordialog.h>
-#include <qpopupmenu.h>
+#include <QColorDialog>
+#include <QContextMenuEvent>
#include <stdlib.h>
#include <math.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRendererCollection.h>
#include <vtkCamera.h>
-#ifndef WNT
+#ifndef WIN32
+#include <QX11Info>
#include <vtkXOpenGLRenderWindow.h>
//#include <GL/gl.h>
//#include <GL/glu.h>
//#include <qgl.h>
#endif
-#if QT_VERSION > 300
-#include <qcursor.h>
-#endif
-
/*!Constructor. Create render window with parant \a parent and name \a name.
*\param parent - parent window
*\param name - render window name.
*/
VTKViewer_RenderWindow::VTKViewer_RenderWindow(QWidget* parent, const char* name) :
-QWidget(parent, name,
- Qt::WStyle_NoBorder | Qt::WDestructiveClose |
- Qt::WResizeNoErase | Qt::WRepaintNoErase)
+QWidget(parent, Qt::FramelessWindowHint )
{
+ setObjectName( name );
+ setAttribute( Qt::WA_DeleteOnClose );
+
myRW = vtkRenderWindow::New();
-#ifndef WNT
- myRW->SetDisplayId((void*)x11Display());
+#ifndef WIN32
+ myRW->SetDisplayId((void*)(QX11Info::display()));
#endif
myRW->SetWindowId((void*)winId());
myRW->DoubleBufferOn();
#include <vtkRenderWindow.h>
-#include <qwidget.h>
+#include <QWidget>
class VTKVIEWER_EXPORT VTKViewer_RenderWindow : public QWidget
{
#include <vtkProperty.h>
// QT Includes
-#include <qkeycode.h>
+#include <QTimer>
+#include <QMouseEvent>
+#include <QKeyEvent>
+#include <QContextMenuEvent>
/*! Create new instance of VTKViewer_RenderWindowInteractor*/
VTKViewer_RenderWindowInteractor* VTKViewer_RenderWindowInteractor::New()
///
/// Start a one-shot timer for 10ms.
///
- mTimer->start(10, TRUE) ;
+ mTimer->setSingleShot(TRUE) ;
+ mTimer->start(10) ;
return 1 ;
}
if( ! this->Enabled ) {
return ;
}
- myInteractorStyle->OnLeftButtonDown((event->state() & ControlButton),
- (event->state() & ShiftButton),
+ myInteractorStyle->OnLeftButtonDown((event->modifiers() & Qt::ControlModifier),
+ (event->modifiers() & Qt::ShiftModifier),
event->x(), event->y());
}
if( ! this->Enabled ) {
return ;
}
- myInteractorStyle->OnLeftButtonUp( (event->state() & ControlButton),
- (event->state() & ShiftButton),
+ myInteractorStyle->OnLeftButtonUp( (event->modifiers() & Qt::ControlModifier),
+ (event->modifiers() & Qt::ShiftModifier),
event->x(), event->y() ) ;
}
if( ! this->Enabled ) {
return ;
}
- myInteractorStyle->OnMiddleButtonDown((event->state() & ControlButton),
- (event->state() & ShiftButton),
+ myInteractorStyle->OnMiddleButtonDown((event->modifiers() & Qt::ControlModifier),
+ (event->modifiers() & Qt::ShiftModifier),
event->x(), event->y() ) ;
}
if( ! this->Enabled ) {
return ;
}
- myInteractorStyle->OnMiddleButtonUp( (event->state() & ControlButton),
- (event->state() & ShiftButton),
+ myInteractorStyle->OnMiddleButtonUp( (event->modifiers() & Qt::ControlModifier),
+ (event->modifiers() & Qt::ShiftModifier),
event->x(), event->y() ) ;
}
if( ! this->Enabled ) {
return ;
}
- myInteractorStyle->OnRightButtonDown( (event->state() & ControlButton),
- (event->state() & ShiftButton),
+ myInteractorStyle->OnRightButtonDown( (event->modifiers() & Qt::ControlModifier),
+ (event->modifiers() & Qt::ShiftModifier),
event->x(), event->y() ) ;
}
return ;
}
bool isOperation = myInteractorStyle->CurrentState() != VTK_INTERACTOR_STYLE_CAMERA_NONE;
- myInteractorStyle->OnRightButtonUp( (event->state() & ControlButton),
- (event->state() & ShiftButton),
+ myInteractorStyle->OnRightButtonUp( (event->modifiers() & Qt::ControlModifier),
+ (event->modifiers() & Qt::ShiftModifier),
event->x(), event->y() );
if ( !isOperation )
{
QContextMenuEvent aEvent( QContextMenuEvent::Mouse,
- event->pos(), event->globalPos(),
- event->state() );
+ event->pos(), event->globalPos() );
emit contextMenuRequested( &aEvent );
}
}
#include "VTKViewer.h"
#include "VTKViewer_Actor.h"
-#include <qtimer.h>
-#include <qobject.h>
+#include <QObject>
+
+class QTimer;
+class QMouseEvent;
+class QKeyEvent;
+class QContextMenuEvent;
// Open CASCADE Includes
#include <TColStd_MapOfInteger.hxx>
#include "SUIT_Desktop.h"
#include "SUIT_Session.h"
-#include <qpainter.h>
-#include <qapplication.h>
-#include <qcolordialog.h>
-#include <qpalette.h>
-#include <qpopupmenu.h>
+#include <QColorDialog>
+#include <QMenu>
+#include <QMouseEvent>
+#include <QToolBar>
bool _InitializeVtkWarningsCall()
{
}
/*!Insert context into popup menu.*/
-void VTKViewer_Viewer::contextMenuPopup(QPopupMenu* thePopup)
+void VTKViewer_Viewer::contextMenuPopup(QMenu* thePopup)
{
- thePopup->insertItem( tr( "MEN_DUMP_VIEW" ), this, SLOT( onDumpView() ) );
- thePopup->insertItem( tr( "MEN_CHANGE_BACKGROUD" ), this, SLOT( onChangeBgColor() ) );
+ thePopup->addAction( tr( "MEN_DUMP_VIEW" ), this, SLOT( onDumpView() ) );
+ thePopup->addAction( tr( "MEN_CHANGE_BACKGROUD" ), this, SLOT( onChangeBgColor() ) );
- thePopup->insertSeparator();
+ thePopup->addSeparator();
VTKViewer_ViewWindow* aView = (VTKViewer_ViewWindow*)(myViewManager->getActiveView());
if ( aView && !aView->getToolBar()->isVisible() )
- thePopup->insertItem( tr( "MEN_SHOW_TOOLBAR" ), this, SLOT( onShowToolbar() ) );
+ thePopup->addAction( tr( "MEN_SHOW_TOOLBAR" ), this, SLOT( onShowToolbar() ) );
}
/*!On mouse press event.*/
return;
switch(event->button()) {
- case LeftButton:
+ case Qt::LeftButton:
rwi->LeftButtonPressed(event) ;
break ;
- case MidButton:
+ case Qt::MidButton:
rwi->MiddleButtonPressed(event) ;
break ;
- case RightButton:
+ case Qt::RightButton:
rwi->RightButtonPressed(event) ;
break;
default:
return;
switch(event->button()) {
- case LeftButton:
+ case Qt::LeftButton:
rwi->LeftButtonReleased(event) ;
break ;
- case MidButton:
+ case Qt::MidButton:
rwi->MiddleButtonReleased(event) ;
break ;
- case RightButton:
+ case Qt::RightButton:
rwi->RightButtonReleased(event) ;
break;
default:
#include "VTKViewer.h"
#include "SUIT_ViewModel.h"
-#include <qcolor.h>
+#include <QColor>
+
+class QMouseEvent;
class SUIT_ViewWindow;
class SUIT_Desktop;
virtual SUIT_ViewWindow* createView(SUIT_Desktop* theDesktop);
virtual void setViewManager(SUIT_ViewManager* theViewManager);
- virtual void contextMenuPopup( QPopupMenu* );
+ virtual void contextMenuPopup( QMenu* );
/*!Gets type of viewer.*/
virtual QString getType() const { return Type(); }
#include "SUIT_Tools.h"
#include "SUIT_ResourceMgr.h"
-#include <qapplication.h>
-#include <qimage.h>
+#include <QImage>
+#include <QToolBar>
#include <vtkRenderer.h>
#include <vtkCamera.h>
myRenderWindow = new VTKViewer_RenderWindow( this, "RenderWindow" );
setCentralWidget(myRenderWindow);
- myRenderWindow->setFocusPolicy( StrongFocus );
+ myRenderWindow->setFocusPolicy( Qt::StrongFocus );
myRenderWindow->setFocus();
myRenderWindow->getRenderWindow()->AddRenderer( myRenderer );
setCentralWidget( myRenderWindow );
myToolBar = new QToolBar(this);
- myToolBar->setCloseMode(QDockWindow::Undocked);
- myToolBar->setLabel(tr("LBL_TOOLBAR_LABEL"));
+ //myToolBar->setCloseMode(QDockWindow::Undocked);
+ myToolBar->setWindowTitle(tr("LBL_TOOLBAR_LABEL"));
createActions();
createToolBar();
myRenderer->GetBackground( backint );
return QColor(int(backint[0]*255), int(backint[1]*255), int(backint[2]*255));
}
- return SUIT_ViewWindow::backgroundColor();
+ return palette().color( backgroundRole() );
}
/*!Repaint window. If \a theUpdateTrihedron is true - recalculate trihedron.*/
QImage VTKViewer_ViewWindow::dumpView()
{
QPixmap px = QPixmap::grabWindow( myRenderWindow->winId() );
- return px.convertToImage();
+ return px.toImage();
}
/*! The method returns the visual parameters of this view as a formated string
*/
void VTKViewer_ViewWindow::setVisualParameters( const QString& parameters )
{
- QStringList paramsLst = QStringList::split( '*', parameters, true );
+ QStringList paramsLst = parameters.split( '*' );
if ( paramsLst.size() == 13 ) {
double pos[3], focalPnt[3], viewUp[3], parScale, scale[3];
pos[0] = paramsLst[0].toDouble();
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>ICON_VTKVIEWER_VIEW_GLOBALPAN</source>
+ <translation>view_glpan.png</translation>
+ </message>
+ <message>
+ <source>ICON_VTKVIEWER_VIEW_FITAREA</source>
+ <translation>view_fitarea.png</translation>
+ </message>
+ <message>
+ <source>ICON_VTKVIEWER_VIEW_FRONT</source>
+ <translation>view_front.png</translation>
+ </message>
+ <message>
+ <source>ICON_VTKVIEWER_VIEW_RESET</source>
+ <translation>view_reset.png</translation>
+ </message>
+ <message>
+ <source>ICON_VTKVIEWER_VIEW_RIGHT</source>
+ <translation>view_right.png</translation>
+ </message>
+ <message>
+ <source>ICON_VTKVIEWER_VIEW_FITALL</source>
+ <translation>view_fitall.png</translation>
+ </message>
+ <message>
+ <source>ICON_VTKVIEWER_VIEW_BOTTOM</source>
+ <translation>view_bottom.png</translation>
+ </message>
+ <message>
+ <source>ICON_VTKVIEWER_VIEW_TOP</source>
+ <translation>view_top.png</translation>
+ </message>
+ <message>
+ <source>ICON_VTKVIEWER_VIEW_PAN</source>
+ <translation>view_pan.png</translation>
+ </message>
+ <message>
+ <source>ICON_VTKVIEWER_VIEW_ROTATE</source>
+ <translation>view_rotate.png</translation>
+ </message>
+ <message>
+ <source>ICON_VTKVIEWER_VIEW_ROTATION_POINT</source>
+ <translation>view_rotation_point.png</translation>
+ </message>
+ <message>
+ <source>ICON_VTKVIEWER_VIEW_DUMP</source>
+ <translation>view_camera_dump.png</translation>
+ </message>
+ <message>
+ <source>ICON_VTKVIEWER_VIEW_BACK</source>
+ <translation>view_back.png</translation>
+ </message>
+ <message>
+ <source>ICON_VTKVIEWER_VIEW_ZOOM</source>
+ <translation>view_zoom.png</translation>
+ </message>
+ <message>
+ <source>ICON_VTKVIEWER_VIEW_LEFT</source>
+ <translation>view_left.png</translation>
+ </message>
+ <message>
+ <source>ICON_VTKVIEWER_VIEW_TRIHEDRON</source>
+ <translation>view_triedre.png</translation>
+ </message>
+</context>
+</TS>
--- /dev/null
+<!DOCTYPE TS><TS>
+<context>
+ <name>@default</name>
+ <message>
+ <source>MNU_FRONT_VIEW</source>
+ <translation>Front</translation>
+ </message>
+ <message>
+ <source>ERROR</source>
+ <translation>Error</translation>
+ </message>
+ <message>
+ <source>MNU_DUMP_VIEW</source>
+ <translation>Dump view...</translation>
+ </message>
+ <message>
+ <source>DSC_TOP_VIEW</source>
+ <translation>Top View</translation>
+ </message>
+ <message>
+ <source>MNU_PAN_VIEW</source>
+ <translation>Panning</translation>
+ </message>
+ <message>
+ <source>MNU_TOP_VIEW</source>
+ <translation>Top</translation>
+ </message>
+ <message>
+ <source>DSC_GLOBALPAN_VIEW</source>
+ <translation>Selection of a new center of the view</translation>
+ </message>
+ <message>
+ <source>DSC_ROTATE_VIEW</source>
+ <translation>Rotation of the point of view around the scene center</translation>
+ </message>
+ <message>
+ <source>MNU_ZOOM_VIEW</source>
+ <translation>Zoom</translation>
+ </message>
+ <message>
+ <source>DSC_PAN_VIEW</source>
+ <translation>Panning the view</translation>
+ </message>
+ <message>
+ <source>DSC_LEFT_VIEW</source>
+ <translation>Left View</translation>
+ </message>
+ <message>
+ <source>DSC_FITALL</source>
+ <translation>Fit all objects inside the view frame</translation>
+ </message>
+ <message>
+ <source>MNU_FITALL</source>
+ <translation>Fit All</translation>
+ </message>
+ <message>
+ <source>MNU_ROTATE_VIEW</source>
+ <translation>Rotation</translation>
+ </message>
+ <message>
+ <source>DSC_SHOW_TRIHEDRON</source>
+ <translation>Show/Hide trihedron in the current view</translation>
+ </message>
+ <message>
+ <source>DSC_FRONT_VIEW</source>
+ <translation>Front View</translation>
+ </message>
+ <message>
+ <source>MNU_GLOBALPAN_VIEW</source>
+ <translation>Global Panning</translation>
+ </message>
+ <message>
+ <source>INF_APP_DUMP_VIEW</source>
+ <translation>Dump view</translation>
+ </message>
+ <message>
+ <source>MNU_BACK_VIEW</source>
+ <translation>Back</translation>
+ </message>
+ <message>
+ <source>MNU_SHOW_TRIHEDRON</source>
+ <translation>Show/Hide trihedron</translation>
+ </message>
+ <message>
+ <source>MNU_BOTTOM_VIEW</source>
+ <translation>Bottom</translation>
+ </message>
+ <message>
+ <source>MNU_RESET_VIEW</source>
+ <translation>Reset</translation>
+ </message>
+ <message>
+ <source>MNU_LEFT_VIEW</source>
+ <translation>Left</translation>
+ </message>
+ <message>
+ <source>DSC_RIGHT_VIEW</source>
+ <translation>Right View</translation>
+ </message>
+ <message>
+ <source>DSC_FITRECT</source>
+ <translation>Fit area within the view frame</translation>
+ </message>
+ <message>
+ <source>MNU_FITRECT</source>
+ <translation>Fit Area</translation>
+ </message>
+ <message>
+ <source>DSC_BOTTOM_VIEW</source>
+ <translation>Bottom View</translation>
+ </message>
+ <message>
+ <source>DSC_DUMP_VIEW</source>
+ <translation>Saves the active view in the image file</translation>
+ </message>
+ <message>
+ <source>DSC_ZOOM_VIEW</source>
+ <translation>Zoom the view</translation>
+ </message>
+ <message>
+ <source>VTK_IMAGE_FILES</source>
+ <translation>Images Files (*.bmp *.png *.jpg *.jpeg)</translation>
+ </message>
+ <message>
+ <source>DSC_RESET_VIEW</source>
+ <translation>Reset View Point</translation>
+ </message>
+ <message>
+ <source>ERR_DOC_CANT_SAVE_FILE</source>
+ <translation>Cannot save file</translation>
+ </message>
+ <message>
+ <source>MNU_RIGHT_VIEW</source>
+ <translation>Right</translation>
+ </message>
+ <message>
+ <source>LBL_TOOLBAR_LABEL</source>
+ <translation>View Operations</translation>
+ </message>
+ <message>
+ <source>DSC_BACK_VIEW</source>
+ <translation>Back View</translation>
+ </message>
+</context>
+<context>
+ <name>VTKViewer_ViewManager</name>
+ <message>
+ <source>VTK_VIEW_TITLE</source>
+ <translation>VTK scene:%M - viewer:%V</translation>
+ </message>
+</context>
+<context>
+ <name>VTKViewer_Viewer</name>
+ <message>
+ <source>MEN_DUMP_VIEW</source>
+ <translation>Dump view...</translation>
+ </message>
+ <message>
+ <source>MEN_SHOW_TOOLBAR</source>
+ <translation>Show toolbar</translation>
+ </message>
+ <message>
+ <source>MEN_CHANGE_BACKGROUD</source>
+ <translation>Change background...</translation>
+ </message>
+</context>
+</TS>
--- /dev/null
+TEMPLATE = subdirs
+CONFIG += ordered
+
+SUBDIRS = Qtx
+SUBDIRS += DDS
+SUBDIRS += QDS
+SUBDIRS += SUIT
+SUBDIRS += SUITApp
+SUBDIRS += STD
+SUBDIRS += CAF
+SUBDIRS += CAM
+SUBDIRS += LogWindow
+SUBDIRS += PyInterp
+SUBDIRS += PyConsole
+SUBDIRS += Prs
+SUBDIRS += OBJECT
+SUBDIRS += GLViewer
+SUBDIRS += VTKViewer
+SUBDIRS += SVTK
+SUBDIRS += OCCViewer
+SUBDIRS += SOCC
+SUBDIRS += Plot2d
+SUBDIRS += SPlot2d
+SUBDIRS += SUPERVGraph
+SUBDIRS += Event
+SUBDIRS += LightApp
+SUBDIRS += ResExporter
+SUBDIRS += TOOLSGUI
+SUBDIRS += Session
+SUBDIRS += SalomeApp