From: vsr Date: Wed, 27 Jun 2007 09:54:08 +0000 (+0000) Subject: Merge changes from BR_QT4 branch X-Git-Tag: qt4_porting_delivery_220807~136 X-Git-Url: http://git.salome-platform.org/gitweb/?a=commitdiff_plain;h=bfcd1a0ad47b53467502ef31b5a08d1bc0f13621;p=modules%2Fgui.git Merge changes from BR_QT4 branch --- diff --git a/SUIT.pro b/SUIT.pro new file mode 100644 index 000000000..4b8f9ce64 --- /dev/null +++ b/SUIT.pro @@ -0,0 +1,4 @@ +TEMPLATE = subdirs +CONFIG += ordered + +SUBDIRS = src diff --git a/adm_local/unix/config_files/check_pyqt.m4 b/adm_local/unix/config_files/check_pyqt.m4 index f63479879..68da58e35 100644 --- a/adm_local/unix/config_files/check_pyqt.m4 +++ b/adm_local/unix/config_files/check_pyqt.m4 @@ -6,324 +6,188 @@ AC_REQUIRE([CHECK_QT])dnl 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="" + 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 ], - [new QCDEStyle();],,PYQT_SIPFLAGS="$PYQT_SIPFLAGS -x Qt_STYLE_CDE") - AC_TRY_COMPILE([#include ], - [new QInterlaceStyle();],,PYQT_SIPFLAGS="$PYQT_SIPFLAGS -x Qt_STYLE_INTERLACE") - AC_TRY_COMPILE([#include ], - [new QMotifStyle();],,PYQT_SIPFLAGS="$PYQT_SIPFLAGS -x Qt_STYLE_MOTIF") - AC_TRY_COMPILE([#include ], - [new QMotifPlusStyle();],,PYQT_SIPFLAGS="$PYQT_SIPFLAGS -x Qt_STYLE_MOTIFPLUS") - AC_TRY_COMPILE([#include ], - [new QPlatinumStyle();],,PYQT_SIPFLAGS="$PYQT_SIPFLAGS -x Qt_STYLE_PLATINUM") - AC_TRY_COMPILE([#include ], - [new QSGIStyle();],,PYQT_SIPFLAGS="$PYQT_SIPFLAGS -x Qt_STYLE_SGI") - AC_TRY_COMPILE([#include ], - [new QWindowsStyle();],,PYQT_SIPFLAGS="$PYQT_SIPFLAGS -x Qt_STYLE_WINDOWS") - AC_TRY_COMPILE([#include ], - [new QWindowsXPStyle();],,PYQT_SIPFLAGS="$PYQT_SIPFLAGS -x Qt_STYLE_WINDOWSXP") - - LIBS="$LIBS -lqassistantclient" - AC_TRY_LINK([#include ], - [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) diff --git a/adm_local/unix/config_files/check_qt.m4 b/adm_local/unix/config_files/check_qt.m4 index 1aea9c3a2..61cd1895c 100644 --- a/adm_local/unix/config_files/check_qt.m4 +++ b/adm_local/unix/config_files/check_qt.m4 @@ -39,19 +39,53 @@ qt_ok=yes 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 @@ -63,13 +97,16 @@ then 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 @@ -81,94 +118,186 @@ then 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 +#include , 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 +, 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 diff --git a/adm_local/unix/config_files/check_qwt.m4 b/adm_local/unix/config_files/check_qwt.m4 index d9bc23fbf..f5bb45250 100644 --- a/adm_local/unix/config_files/check_qwt.m4 +++ b/adm_local/unix/config_files/check_qwt.m4 @@ -84,16 +84,21 @@ else 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" @@ -106,13 +111,14 @@ then AC_CACHE_VAL(salome_cv_lib_qwt,[ AC_TRY_LINK( -#include +#include #include , 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") ]) diff --git a/adm_local/unix/config_files/check_sip.m4 b/adm_local/unix/config_files/check_sip.m4 index b9aa397fc..3d68d8b0a 100644 --- a/adm_local/unix/config_files/check_sip.m4 +++ b/adm_local/unix/config_files/check_sip.m4 @@ -10,172 +10,85 @@ sip_ok=yes 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) diff --git a/adm_local/unix/make_common_starter.am b/adm_local/unix/make_common_starter.am index 16a5054e5..c4cf97577 100644 --- a/adm_local/unix/make_common_starter.am +++ b/adm_local/unix/make_common_starter.am @@ -36,10 +36,10 @@ docdir = $(datadir)/doc/@PACKAGE@ $(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 diff --git a/configure.ac b/configure.ac index 0b2d4fc0c..1247bac31 100644 --- a/configure.ac +++ b/configure.ac @@ -9,18 +9,13 @@ # -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.) @@ -304,14 +299,6 @@ echo CHECK_QT -echo -echo --------------------------------------------- -echo testing msg2qm -echo --------------------------------------------- -echo - -CHECK_MSG2QM - echo echo --------------------------------------------- echo testing VTK @@ -512,10 +499,10 @@ fi 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 @@ -635,14 +622,13 @@ AC_OUTPUT([ \ ./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 \ @@ -654,7 +640,6 @@ AC_OUTPUT([ \ ./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 \ diff --git a/src/CAF/CAF.h b/src/CAF/CAF.h index d70c01d80..ed6a8ea24 100755 --- a/src/CAF/CAF.h +++ b/src/CAF/CAF.h @@ -19,18 +19,14 @@ #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 @@ -39,7 +35,7 @@ #define true 1 #endif -#if defined WNT +#if defined WIN32 #pragma warning ( disable: 4251 ) #endif diff --git a/src/CAF/CAF.pro b/src/CAF/CAF.pro new file mode 100644 index 000000000..0c7313d32 --- /dev/null +++ b/src/CAF/CAF.pro @@ -0,0 +1,38 @@ +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 diff --git a/src/CAF/CAF_Application.cxx b/src/CAF/CAF_Application.cxx index 78bc1d566..8a5b2a359 100755 --- a/src/CAF/CAF_Application.cxx +++ b/src/CAF/CAF_Application.cxx @@ -22,31 +22,38 @@ #include "CAF_Study.h" #include -#include -#include -#include #include #include +#include #include -#include -#include -#include -#include -#include +#include +#include #include - #include +/*! + \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() @@ -54,23 +61,24 @@ CAF_Application::CAF_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 @@ -79,7 +87,8 @@ 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 { @@ -87,7 +96,11 @@ 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 { @@ -104,13 +117,13 @@ 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() ) { @@ -126,7 +139,7 @@ QString CAF_Application::getFileFilter() const QStringList filters; for ( QMap::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( "; " ) ) ); @@ -138,7 +151,7 @@ QString CAF_Application::getFileFilter() const } /*! - Creates actions of application + \brief Create menu and toolbars actions. */ void CAF_Application::createActions() { @@ -147,14 +160,18 @@ 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" ) ); @@ -163,7 +180,6 @@ void CAF_Application::createActions() 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 ); @@ -179,7 +195,9 @@ void CAF_Application::createActions() } /*! - 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 ) { @@ -193,7 +211,9 @@ 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) { @@ -207,69 +227,79 @@ 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( activeStudy() ); - if ( cafStudy ) + CAF_Study* cafStudy = dynamic_cast( 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( activeStudy() ); - if ( cafStudy ) + CAF_Study* cafStudy = dynamic_cast( 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( action( EditUndoId ) ); if ( cafStudy && undo ) - undo->setProperty( "names", cafStudy->undoNames() ); + undo->addNames( cafStudy->undoNames() ); - QAction* redo = action( EditRedoId ); + QtxListAction* redo = qobject_cast( action( EditRedoId ) ); if ( cafStudy && redo ) - redo->setProperty( "names", cafStudy->redoNames() ); + redo->addNames( cafStudy->redoNames() ); if ( undo ) undo->setEnabled( cafStudy && cafStudy->canUndo() ); @@ -278,15 +308,16 @@ void CAF_Application::updateCommandsStatus() } /*! - 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() { @@ -294,7 +325,8 @@ 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 ) { diff --git a/src/CAF/CAF_Application.h b/src/CAF/CAF_Application.h index 81a16413d..176293995 100755 --- a/src/CAF/CAF_Application.h +++ b/src/CAF/CAF_Application.h @@ -23,24 +23,14 @@ #include "STD_Application.h" -#include -#include - #include -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 @@ -72,8 +62,8 @@ protected: 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)& ); diff --git a/src/CAF/CAF_Operation.cxx b/src/CAF/CAF_Operation.cxx index 67fd2785f..0b9e3c752 100755 --- a/src/CAF/CAF_Operation.cxx +++ b/src/CAF/CAF_Operation.cxx @@ -24,27 +24,36 @@ #include /*! - 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( study() ); + CAF_Study* s = qobject_cast( study() ); if ( s ) doc = s->stdDoc(); return doc; diff --git a/src/CAF/CAF_Operation.h b/src/CAF/CAF_Operation.h index d6ae43694..15bd54070 100755 --- a/src/CAF/CAF_Operation.h +++ b/src/CAF/CAF_Operation.h @@ -23,27 +23,18 @@ #include "SUIT_Operation.h" -#include -#include - #include 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; diff --git a/src/CAF/CAF_Study.cxx b/src/CAF/CAF_Study.cxx index 79d0da098..95ac4cbf8 100755 --- a/src/CAF/CAF_Study.cxx +++ b/src/CAF/CAF_Study.cxx @@ -19,49 +19,61 @@ #include "CAF_Study.h" #include "CAF_Tools.h" -#include "CAF_Operation.h" #include "CAF_Application.h" #include #include #include -#include +#include #include #include +#include #include #include /*! - 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 { @@ -69,8 +81,8 @@ 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 ) { @@ -78,14 +90,16 @@ 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 @@ -97,25 +111,29 @@ void CAF_Study::createDocument() 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 ) { @@ -138,8 +156,8 @@ 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 ) { @@ -186,7 +204,8 @@ 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() { @@ -211,7 +230,8 @@ bool CAF_Study::openTransaction() } /*! - Abort OCAF transaction + \brief Abort OCAF transaction. + \return \c true if transaction is aborted successfully */ bool CAF_Study::abortTransaction() { @@ -233,7 +253,8 @@ 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 ) { @@ -261,7 +282,8 @@ 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 { @@ -272,7 +294,8 @@ 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 { @@ -283,7 +306,8 @@ 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 { @@ -295,24 +319,30 @@ 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() { @@ -320,7 +350,8 @@ void CAF_Study::undoModified() } /*! - Clears modification count. [ public ] + \brief Clear modifications count. + \sa doModified(), undoModified() */ void CAF_Study::clearModified() { @@ -328,7 +359,8 @@ 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() { @@ -343,15 +375,16 @@ 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() { @@ -366,15 +399,16 @@ 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 { @@ -385,7 +419,8 @@ 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 { @@ -396,7 +431,8 @@ 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 { @@ -410,7 +446,8 @@ 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 { @@ -424,7 +461,8 @@ 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 { @@ -436,9 +474,10 @@ 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( application() ); + return qobject_cast( application() ); } diff --git a/src/CAF/CAF_Study.h b/src/CAF/CAF_Study.h index 0e5980cc9..ccde84d35 100755 --- a/src/CAF/CAF_Study.h +++ b/src/CAF/CAF_Study.h @@ -23,51 +23,43 @@ #include "SUIT_Study.h" -#include - #include -#include 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: @@ -82,13 +74,13 @@ 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 diff --git a/src/CAF/CAF_Tools.cxx b/src/CAF/CAF_Tools.cxx index f637a3e87..138fd3791 100755 --- a/src/CAF/CAF_Tools.cxx +++ b/src/CAF/CAF_Tools.cxx @@ -21,11 +21,15 @@ #include "CAF_Tools.h" -#include -#include +/*! + \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 ) { @@ -33,7 +37,9 @@ 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 ) { @@ -41,18 +47,22 @@ 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 ) { @@ -63,7 +73,9 @@ 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 ) { @@ -75,7 +87,9 @@ 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 ) { diff --git a/src/CAF/CAF_Tools.h b/src/CAF/CAF_Tools.h index c0183586e..4c0188b9a 100755 --- a/src/CAF/CAF_Tools.h +++ b/src/CAF/CAF_Tools.h @@ -26,17 +26,13 @@ #include -#include +#include #include #include #include -/*! - \class CAF_Tools - Prodives set of auxiliary static methods -*/ class CAF_EXPORT CAF_Tools : public SUIT_Tools { public: diff --git a/src/CAF/Makefile.am b/src/CAF/Makefile.am index f60c261af..173a32f7d 100755 --- a/src/CAF/Makefile.am +++ b/src/CAF/Makefile.am @@ -52,8 +52,7 @@ nodist_salomeres_DATA = \ 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 diff --git a/src/CAF/resources/CAF_images.ts b/src/CAF/resources/CAF_images.ts new file mode 100644 index 000000000..1435c788d --- /dev/null +++ b/src/CAF/resources/CAF_images.ts @@ -0,0 +1,13 @@ + + + @default + + ICON_APP_EDIT_REDO + redo.png + + + ICON_APP_EDIT_UNDO + undo.png + + + diff --git a/src/CAF/resources/CAF_msg_en.ts b/src/CAF/resources/CAF_msg_en.ts new file mode 100644 index 000000000..78fed0911 --- /dev/null +++ b/src/CAF/resources/CAF_msg_en.ts @@ -0,0 +1,57 @@ + + + CAF_Application + + MEN_APP_EDIT + &Edit + + + INF_ALL_FILTER + All Files (*.*) + + + INF_ALL_DOCUMENTS_FILTER + All Readable Documents + + + MEN_DESK_EDIT + &Edit + + + MEN_APP_EDIT_UNDO + &Undo + + + MEN_APP_EDIT_REDO + &Redo + + + PRP_APP_EDIT_REDO + Redoes the last operation + + + PRP_APP_EDIT_UNDO + Undoes the last operation + + + TOT_APP_EDIT_REDO + Redo + + + TOT_APP_EDIT_UNDO + Undo + + + INF_APP_REDOACTIONS + Redoes %1 action(s) + + + INF_APP_UNDOACTIONS + Undoes %1 action(s) + + + ABOUT_INFO + SUIT Caf application + + + diff --git a/src/CAM/CAM.h b/src/CAM/CAM.h index b953c9927..1489c37b8 100755 --- a/src/CAM/CAM.h +++ b/src/CAM/CAM.h @@ -19,18 +19,14 @@ #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 @@ -39,7 +35,7 @@ #define true 1 #endif -#if defined WNT +#if defined WIN32 #pragma warning ( disable: 4251 ) #endif diff --git a/src/CAM/CAM.pro b/src/CAM/CAM.pro new file mode 100644 index 000000000..634461537 --- /dev/null +++ b/src/CAM/CAM.pro @@ -0,0 +1,42 @@ +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 diff --git a/src/CAM/CAM_Application.cxx b/src/CAM/CAM_Application.cxx index cc2d1f703..6d285ad5d 100755 --- a/src/CAM/CAM_Application.cxx +++ b/src/CAM/CAM_Application.cxx @@ -16,22 +16,20 @@ // // 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 +#include #include #include +#include -#include -#include -#include -#include -#include -#include -#include +#include +#include #ifdef WIN32 #include @@ -39,31 +37,64 @@ #include #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 ) @@ -72,65 +103,87 @@ void CAM_Application::start() 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::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::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::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 ) ) @@ -141,7 +194,8 @@ void CAM_Application::addModule( CAM_Module* mod ) QMap 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 ); @@ -151,17 +205,16 @@ void CAM_Application::addModule( CAM_Module* mod ) if ( curMod ) newList.append( curMod ); } - if ( !newList.isEmpty() ) - map.insert( newList.getLast(), 0 ); } - for ( ModuleListIterator itr( myModules ); itr.current(); ++itr ) + for ( QList::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; @@ -169,9 +222,11 @@ void CAM_Application::addModule( CAM_Module* mod ) 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 ) @@ -180,33 +235,38 @@ void CAM_Application::loadModules() 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; } @@ -214,7 +274,7 @@ CAM_Module* CAM_Application::loadModule( const QString& modName ) GET_MODULE_FUNC crtInst = 0; #ifdef WIN32 - HINSTANCE modLib = ::LoadLibrary( libName ); + HINSTANCE modLib = ::LoadLibrary( libName.toLatin1() ); if ( !modLib ) { LPVOID lpMsgBuf; @@ -236,7 +296,7 @@ CAM_Module* CAM_Application::loadModule( const QString& modName ) } } #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 @@ -255,21 +315,20 @@ CAM_Module* CAM_Application::loadModule( const QString& modName ) } 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() ) @@ -294,11 +353,14 @@ bool CAM_Application::activateModule( const QString& modName ) 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() ) @@ -323,10 +385,10 @@ bool CAM_Application::activateModule( CAM_Module* mod ) { 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; } @@ -336,17 +398,19 @@ bool CAM_Application::activateModule( CAM_Module* mod ) 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(); @@ -355,37 +419,45 @@ void CAM_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::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( 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; @@ -397,10 +469,11 @@ QString CAM_Application::moduleName( const QString& title ) const 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; @@ -412,10 +485,11 @@ QString CAM_Application::moduleTitle( const QString& name ) const 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 { @@ -430,7 +504,26 @@ QString CAM_Application::moduleLibrary( const QString& title, const bool full ) 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 ( [:...] )" 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() ) @@ -440,55 +533,54 @@ void CAM_Application::readModuleList() 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 @@ -502,8 +594,8 @@ void CAM_Application::readModuleList() } 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" ); @@ -513,19 +605,25 @@ void CAM_Application::readModuleList() } } -/*!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(); diff --git a/src/CAM/CAM_Application.h b/src/CAM/CAM_Application.h index c31e90523..c7b545877 100755 --- a/src/CAM/CAM_Application.h +++ b/src/CAM/CAM_Application.h @@ -19,32 +19,24 @@ #ifndef CAM_APPLICATION_H #define CAM_APPLICATION_H -#include "STD_Application.h" +#include "CAM.h" -#include "CAM_Module.h" +#include +#include -#include - -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 ModuleList; - typedef QPtrListIterator ModuleListIterator; + typedef QList ModuleList; public: CAM_Application( const bool = true ); @@ -53,14 +45,11 @@ public: 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* ); @@ -69,7 +58,7 @@ public: 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; @@ -93,13 +82,13 @@ private: private: typedef struct { QString name, title, internal; } ModuleInfo; - typedef QValueList ModuleInfoList; + typedef QList 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 diff --git a/src/CAM/CAM_DataModel.cxx b/src/CAM/CAM_DataModel.cxx index 559901279..7af20dbe6 100755 --- a/src/CAM/CAM_DataModel.cxx +++ b/src/CAM/CAM_DataModel.cxx @@ -19,40 +19,71 @@ #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 ) @@ -69,17 +100,106 @@ void CAM_DataModel::setRoot( const CAM_DataObject* 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 +*/ diff --git a/src/CAM/CAM_DataModel.h b/src/CAM/CAM_DataModel.h index 4cbc8ab93..4fb200fea 100755 --- a/src/CAM/CAM_DataModel.h +++ b/src/CAM/CAM_DataModel.h @@ -21,19 +21,14 @@ #include "CAM.h" -#include -#include +#include +#include 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 @@ -47,22 +42,13 @@ public: 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: @@ -72,8 +58,8 @@ signals: void rootChanged( const CAM_DataModel* ); private: - CAM_DataObject* myRoot; - CAM_Module* myModule; + CAM_DataObject* myRoot; //!< root data object + CAM_Module* myModule; //!< module }; #endif diff --git a/src/CAM/CAM_DataObject.cxx b/src/CAM/CAM_DataObject.cxx index 62a3d3b13..dc71af10a 100755 --- a/src/CAM/CAM_DataObject.cxx +++ b/src/CAM/CAM_DataObject.cxx @@ -21,20 +21,36 @@ #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; @@ -46,10 +62,11 @@ CAM_Module* CAM_DataObject::module() const 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( parent() ); diff --git a/src/CAM/CAM_DataObject.h b/src/CAM/CAM_DataObject.h index 1e4e414b2..f0b4affa8 100755 --- a/src/CAM/CAM_DataObject.h +++ b/src/CAM/CAM_DataObject.h @@ -26,10 +26,6 @@ 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: diff --git a/src/CAM/CAM_Module.cxx b/src/CAM/CAM_Module.cxx index 511cad9e3..d753c7f90 100755 --- a/src/CAM/CAM_Module.cxx +++ b/src/CAM/CAM_Module.cxx @@ -26,10 +26,10 @@ #include #include +#include #include -#include -/*!Icon.*/ +/*! Default module icon data set */ static const char* ModuleIcon[] = { "20 20 2 1", " c None", @@ -55,35 +55,67 @@ static const char* ModuleIcon[] = { " .. .. .. .. .. .. ", " ... ... ... "}; +/*! 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; @@ -97,27 +129,58 @@ void CAM_Module::initialize( CAM_Application* 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 ) @@ -129,29 +192,56 @@ CAM_DataModel* CAM_Module::dataModel() const 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( study ); @@ -165,21 +255,35 @@ void CAM_Module::studyClosed( SUIT_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 ) { @@ -191,8 +295,12 @@ 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 ) { @@ -200,40 +308,62 @@ 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; @@ -242,9 +372,10 @@ QtxActionMenuMgr* CAM_Module::menuMgr() const 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; @@ -253,9 +384,14 @@ QtxActionToolMgr* CAM_Module::toolMgr() const 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() ) @@ -264,15 +400,25 @@ int CAM_Module::createTool( const QString& name ) 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() ) @@ -283,15 +429,25 @@ int CAM_Module::createTool( QAction* a, const int tBar, const int id, const int 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() ) @@ -302,14 +458,24 @@ int CAM_Module::createTool( QAction* a, const QString& tBar, const int id, const 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() ) @@ -319,14 +485,24 @@ int CAM_Module::createTool( const int id, const int tBar, const int idx ) 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() ) @@ -336,126 +512,211 @@ int CAM_Module::createTool( const int id, const QString& tBar, const int idx ) 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(); @@ -468,8 +729,8 @@ void CAM_Module::setMenuShown( const bool on ) QAction* sep = separator(); for ( QMap::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 ); @@ -477,28 +738,32 @@ void CAM_Module::setMenuShown( const bool on ) 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(); @@ -511,8 +776,8 @@ void CAM_Module::setToolShown( const bool on ) QAction* sep = separator(); for ( QMap::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 ); @@ -520,29 +785,32 @@ void CAM_Module::setToolShown( const bool on ) 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; @@ -551,38 +819,46 @@ QAction* CAM_Module::action( const int id ) const 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::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 ) @@ -593,16 +869,21 @@ QAction* CAM_Module::createAction( const int id, const QString& text, const QIco 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::ConstIterator it = myActionMap.begin(); it != myActionMap.end() && ident == -1; ++it ) - if ( it.data() == a ) + if ( it.value() == a ) ident = it.key(); if ( ident != -1 ) @@ -622,19 +903,23 @@ int CAM_Module::registerAction( const int id, QAction* a ) 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 ) @@ -656,13 +941,22 @@ bool CAM_Module::unregisterAction( QAction* 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( camStudy->application() ) : 0; @@ -670,16 +964,30 @@ void CAM_Module::connectToStudy( CAM_Study* camStudy ) return; CAM_DataModel* prev = 0; - for( CAM_Application::ModuleListIterator it = app->modules(); it.current(); ++it ) + CAM_Application::ModuleList mods = app->modules(); + for( QList::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. +*/ diff --git a/src/CAM/CAM_Module.h b/src/CAM/CAM_Module.h index df9282a41..2b62f768a 100755 --- a/src/CAM/CAM_Module.h +++ b/src/CAM/CAM_Module.h @@ -21,27 +21,27 @@ #include "CAM.h" -#include -#include -#include -#include +#include +#include +#include +#include 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 @@ -53,6 +53,7 @@ public: virtual void initialize( CAM_Application* ); + QString name() const; QString moduleName() const; QPixmap moduleIcon() const; @@ -61,26 +62,20 @@ public: 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* ); @@ -99,53 +94,45 @@ private slots: 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 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 myActionMap; //!< menu actions friend class CAM_Application; }; diff --git a/src/CAM/CAM_RootObject.cxx b/src/CAM/CAM_RootObject.cxx index e1d9771e3..a710a6b78 100755 --- a/src/CAM/CAM_RootObject.cxx +++ b/src/CAM/CAM_RootObject.cxx @@ -21,32 +21,55 @@ #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 { @@ -56,17 +79,19 @@ 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; diff --git a/src/CAM/CAM_RootObject.h b/src/CAM/CAM_RootObject.h index 8456e7628..fd633b812 100755 --- a/src/CAM/CAM_RootObject.h +++ b/src/CAM/CAM_RootObject.h @@ -21,14 +21,6 @@ #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: diff --git a/src/CAM/CAM_Study.cxx b/src/CAM/CAM_Study.cxx index 65ded0325..da1c304dd 100755 --- a/src/CAM/CAM_Study.cxx +++ b/src/CAM/CAM_Study.cxx @@ -23,58 +23,85 @@ #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::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* ) ) ); @@ -83,10 +110,11 @@ bool CAM_Study::insertDataModel( const CAM_DataModel* dm, const int idx ) 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 ) @@ -96,29 +124,38 @@ bool CAM_Study::removeDataModel( const CAM_DataModel* 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::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; @@ -131,19 +168,34 @@ void CAM_Study::dataModelInserted( const 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() ) @@ -168,7 +220,7 @@ void CAM_Study::updateModelRoot( const CAM_DataModel* dm ) 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 ); } diff --git a/src/CAM/CAM_Study.h b/src/CAM/CAM_Study.h index 18839617a..5d520d39a 100755 --- a/src/CAM/CAM_Study.h +++ b/src/CAM/CAM_Study.h @@ -21,42 +21,31 @@ #include "CAM.h" -#include "CAM_DataModel.h" - #include +#include -#include +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 ModelList; - typedef QPtrListIterator ModelListIterator; + typedef QList 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* ); @@ -73,8 +62,7 @@ protected slots: virtual void updateModelRoot( const CAM_DataModel* ); private: - //! Data model list - ModelList myDataModels; + ModelList myDataModels; //!< data models list }; #ifdef WIN32 diff --git a/src/CAM/Makefile.am b/src/CAM/Makefile.am index 4e0a1e5f3..8c0b727a0 100755 --- a/src/CAM/Makefile.am +++ b/src/CAM/Makefile.am @@ -26,10 +26,10 @@ include $(top_srcdir)/adm_local/unix/make_common_starter.am 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 @@ -53,7 +53,7 @@ nodist_salomeres_DATA=CAM_msg_en.qm 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 diff --git a/src/CAM/resources/CAM_msg_en.ts b/src/CAM/resources/CAM_msg_en.ts new file mode 100644 index 000000000..cb18f6673 --- /dev/null +++ b/src/CAM/resources/CAM_msg_en.ts @@ -0,0 +1,13 @@ + + + @default + + ERROR_TLT + Error + + + ERROR_ACTIVATE_MODULE_MSG + Failed to activate module %1 + + + diff --git a/src/DDS/DDS.pro b/src/DDS/DDS.pro new file mode 100644 index 000000000..adb04a714 --- /dev/null +++ b/src/DDS/DDS.pro @@ -0,0 +1,37 @@ +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 diff --git a/src/DDS/DDS_DicGroup.cxx b/src/DDS/DDS_DicGroup.cxx index 56197a523..3bb337ad3 100644 --- a/src/DDS/DDS_DicGroup.cxx +++ b/src/DDS/DDS_DicGroup.cxx @@ -35,29 +35,33 @@ IMPLEMENT_STANDARD_RTTIEXT(DDS_DicGroup, MMgt_TShared) /*! \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 { @@ -65,8 +69,8 @@ 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 { @@ -81,7 +85,12 @@ void DDS_DicGroup::GetUnitSystems( TColStd_SequenceOfAsciiString& theSystemSeq ) } /*! - 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 { @@ -92,7 +101,8 @@ TCollection_ExtendedString DDS_DicGroup::GetUnitSystemLabel( const TCollection_A } /*! - 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 { @@ -100,7 +110,8 @@ 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 ) { @@ -109,14 +120,16 @@ 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 ) { @@ -174,10 +187,14 @@ void DDS_DicGroup::FillDataMap( const LDOM_Element& theComponentData, const LDOM } /*! - 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 diff --git a/src/DDS/DDS_DicItem.cxx b/src/DDS/DDS_DicItem.cxx index 48ce715a9..12a942705 100644 --- a/src/DDS/DDS_DicItem.cxx +++ b/src/DDS/DDS_DicItem.cxx @@ -37,40 +37,42 @@ IMPLEMENT_STANDARD_RTTIEXT(DDS_DicItem, MMgt_TShared) /*! \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 { @@ -78,7 +80,8 @@ 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 { @@ -86,7 +89,8 @@ 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 { @@ -94,7 +98,8 @@ 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 { @@ -102,7 +107,8 @@ 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 { @@ -110,7 +116,8 @@ 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 { @@ -118,7 +125,8 @@ 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 { @@ -126,7 +134,8 @@ 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 { @@ -134,7 +143,8 @@ 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 { @@ -146,7 +156,8 @@ 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 { @@ -154,8 +165,12 @@ 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 { @@ -167,8 +182,11 @@ TCollection_AsciiString DDS_DicItem::GetUnits( const UnitSystem& theSystem ) con } /*! - 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 { @@ -176,8 +194,13 @@ 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 { @@ -185,8 +208,11 @@ 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 { @@ -194,8 +220,13 @@ 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 { @@ -203,7 +234,9 @@ 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 { @@ -211,8 +244,13 @@ 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 { @@ -224,9 +262,13 @@ 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 { @@ -234,9 +276,15 @@ 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 { @@ -262,9 +310,13 @@ TCollection_ExtendedString DDS_DicItem::GetDefaultValue( const UnitSystem& theSy } /*! - 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 { @@ -272,9 +324,15 @@ TCollection_AsciiString DDS_DicItem::GetFormat( const Standard_Boolean theCanoni } /*! - 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 @@ -304,8 +362,14 @@ TCollection_AsciiString DDS_DicItem::GetFormat( const UnitSystem& theSystem, } /*! - 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 { @@ -313,8 +377,17 @@ 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 @@ -325,8 +398,20 @@ Standard_Boolean DDS_DicItem::GetListOfValues( Handle(TColStd_HArray1OfExtendedS } /*! - 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, @@ -340,7 +425,9 @@ Standard_Boolean DDS_DicItem::GetListOfValues( Handle(TColStd_HArray1OfExtendedS /*! - 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 { @@ -362,7 +449,8 @@ Standard_Boolean DDS_DicItem::GetSpecialValues( TColStd_MapOfReal& theMap ) cons } /*! - Gets minimum value of lateral zooming + \brief Get minimum value of lateral zooming. + \return lateral zooming minimum value */ Standard_Real DDS_DicItem::GetMinZoom() const { @@ -370,7 +458,8 @@ 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 { @@ -378,7 +467,8 @@ 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 { @@ -386,7 +476,10 @@ 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 { @@ -394,7 +487,10 @@ 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 { @@ -402,7 +498,11 @@ 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 { @@ -414,7 +514,11 @@ Standard_Real DDS_DicItem::ToSI( const Standard_Real theVal, const UnitSystem& t } /*! - 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 { @@ -426,7 +530,9 @@ Standard_Real DDS_DicItem::FromSI( const Standard_Real theVal, const UnitSystem& } /*! - 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 { @@ -434,7 +540,12 @@ 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 { @@ -445,8 +556,9 @@ TCollection_ExtendedString DDS_DicItem::GetOption( const TCollection_AsciiString } /*! - 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 { @@ -460,7 +572,13 @@ Standard_Boolean DDS_DicItem::GetOptionNames( TColStd_SequenceOfAsciiString& nam /*! - 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, @@ -814,7 +932,7 @@ void DDS_DicItem::FillDataMap( TCollection_AsciiString theID, const LDOM_Element } /*! - Returns default formats for each unit systems + \brief Restore default formats for all the units systems. */ void DDS_DicItem::GetDefaultFormat() { @@ -839,7 +957,12 @@ 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, @@ -862,7 +985,13 @@ void DDS_DicItem::GetStringFormat( const TCollection_AsciiString& theFlags, } /*! - 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, @@ -900,7 +1029,13 @@ void DDS_DicItem::GetIntegerFormat( const TCollection_AsciiString& theFlags, } /*! - 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, @@ -946,9 +1081,10 @@ void DDS_DicItem::GetFloatFormat( const TCollection_AsciiString& theFlags, } /*! - 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::Iterator it( myUnitData ); it.More(); it.Next() ) { @@ -1069,7 +1205,9 @@ void DDS_DicItem::PrepareFormats( const TCollection_AsciiString& theFormat ) } /*! - 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 ) { @@ -1103,7 +1241,9 @@ void DDS_DicItem::Split( const TCollection_AsciiString& theStr, Handle(TColStd_H } /*! - 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 { @@ -1116,7 +1256,8 @@ 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 { diff --git a/src/DDS/DDS_Dictionary.cxx b/src/DDS/DDS_Dictionary.cxx index dd741872f..25e6cdcb8 100644 --- a/src/DDS/DDS_Dictionary.cxx +++ b/src/DDS/DDS_Dictionary.cxx @@ -39,14 +39,16 @@ IMPLEMENT_STANDARD_RTTIEXT(DDS_Dictionary, MMgt_TShared) /*! \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 @@ -89,70 +91,87 @@ IMPLEMENT_STANDARD_RTTIEXT(DDS_Dictionary, MMgt_TShared) - \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 @@ -225,12 +244,14 @@ IMPLEMENT_STANDARD_RTTIEXT(DDS_Dictionary, MMgt_TShared) - - + \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() @@ -238,22 +259,22 @@ DDS_Dictionary::DDS_Dictionary() } /*! - 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 { @@ -277,9 +298,13 @@ void DDS_Dictionary::GetUnitSystems( TColStd_SequenceOfAsciiString& theSystems ) } /*! - 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 @@ -290,8 +315,13 @@ void DDS_Dictionary::GetUnitSystems( TColStd_SequenceOfAsciiString& theSystems, } /*! - 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 { @@ -302,9 +332,15 @@ TCollection_ExtendedString DDS_Dictionary::GetUnitSystemLabel( const TCollection } /*! - 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 @@ -316,8 +352,12 @@ TCollection_ExtendedString DDS_Dictionary::GetUnitSystemLabel( const TCollection } /*! - 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 { @@ -328,8 +368,13 @@ 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 { @@ -340,8 +385,12 @@ TCollection_AsciiString DDS_Dictionary::GetActiveUnitSystem( const TCollection_A } /*! - 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 ) { @@ -350,8 +399,12 @@ void DDS_Dictionary::SetActiveUnitSystem( const TCollection_AsciiString& theSyst } /*! - 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 ) @@ -361,9 +414,10 @@ void DDS_Dictionary::SetActiveUnitSystem( const TCollection_AsciiString& theSyst } /*! - 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; @@ -374,8 +428,10 @@ Handle(DDS_Dictionary) DDS_Dictionary::Get() } /*! - 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 ) { @@ -404,8 +460,13 @@ 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 ) { @@ -421,10 +482,15 @@ 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; @@ -437,10 +503,15 @@ Handle(DDS_DicItem) DDS_Dictionary::GetDicItem( const TCollection_AsciiString& t } /*! - 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++ ) @@ -449,7 +520,9 @@ Handle(DDS_DicItem) DDS_Dictionary::GetDicItem( const TCollection_AsciiString& t } /*! - 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 ) { @@ -462,8 +535,11 @@ void DDS_Dictionary::FillDataMap( const LDOM_Element& theComponentData, const LD } /*! - 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 ) { @@ -486,8 +562,11 @@ Standard_Real DDS_Dictionary::ToSI( const Standard_Real theValue, const Standard } /*! - 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 ) { diff --git a/src/DDS/DDS_KeyWords.cxx b/src/DDS/DDS_KeyWords.cxx index 626bd0fd0..61799d219 100644 --- a/src/DDS/DDS_KeyWords.cxx +++ b/src/DDS/DDS_KeyWords.cxx @@ -23,60 +23,66 @@ IMPLEMENT_STANDARD_RTTIEXT(DDS_KeyWords, MMgt_TShared) /*! \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() { @@ -134,10 +140,10 @@ DDS_KeyWords::DDS_KeyWords() } /*! - 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; @@ -148,10 +154,12 @@ Handle(DDS_KeyWords) DDS_KeyWords::Get() } /*! - 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; @@ -161,9 +169,10 @@ TCollection_AsciiString DDS_KeyWords::GetKeyWord( const TCollection_AsciiString& } /*! - 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 ) { diff --git a/src/DDS/Makefile.am b/src/DDS/Makefile.am index 508e544e9..0b8574348 100755 --- a/src/DDS/Makefile.am +++ b/src/DDS/Makefile.am @@ -25,15 +25,17 @@ include $(top_srcdir)/adm_local/unix/make_common_starter.am 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) diff --git a/src/Event/Event.h b/src/Event/Event.h index 8df1a71b1..9e2abddc8 100755 --- a/src/Event/Event.h +++ b/src/Event/Event.h @@ -16,35 +16,22 @@ // // 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 diff --git a/src/Event/Event.pro b/src/Event/Event.pro new file mode 100644 index 000000000..b28d7bdca --- /dev/null +++ b/src/Event/Event.pro @@ -0,0 +1,24 @@ +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 diff --git a/src/Event/Makefile.am b/src/Event/Makefile.am index c9948969b..c848832b1 100755 --- a/src/Event/Makefile.am +++ b/src/Event/Makefile.am @@ -32,11 +32,11 @@ lib_LTLIBRARIES = libEvent.la 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) diff --git a/src/Event/SALOME_Event.cxx b/src/Event/SALOME_Event.cxx index 928cd2341..7faf45a7d 100755 --- a/src/Event/SALOME_Event.cxx +++ b/src/Event/SALOME_Event.cxx @@ -19,40 +19,118 @@ // // 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 -#include -#include +#include +#include // 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 - static DWORD myThread; #else -#include #include - 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 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 @@ -63,7 +141,8 @@ void SALOME_Event::GetSessionThread(){ } /*! - \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; @@ -72,48 +151,93 @@ bool SALOME_Event::IsSessionThread(){ #else aResult = myThread == pthread_self(); #endif -// if(MYDEBUG) INFOS("IsSessionThread() - "<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 = "<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. +*/ diff --git a/src/Event/SALOME_Event.h b/src/Event/SALOME_Event.h new file mode 100644 index 000000000..859d62b93 --- /dev/null +++ b/src/Event/SALOME_Event.h @@ -0,0 +1,229 @@ +// 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 + +#include + +//! 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 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 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 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 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 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 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 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 diff --git a/src/Event/SALOME_Event.hxx b/src/Event/SALOME_Event.hxx deleted file mode 100755 index 91f53d6bc..000000000 --- a/src/Event/SALOME_Event.hxx +++ /dev/null @@ -1,274 +0,0 @@ -// 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 - -#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 - * 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 - -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 /*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 /*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/* 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 /*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 -/*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 -/*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 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 diff --git a/src/GLViewer/GLViewer.h b/src/GLViewer/GLViewer.h index bf34bae3a..af1bb3d3f 100644 --- a/src/GLViewer/GLViewer.h +++ b/src/GLViewer/GLViewer.h @@ -23,7 +23,7 @@ // Created: November, 2004 //! Macro for exports -#ifdef WNT +#ifdef WIN32 #ifdef GLVIEWER_EXPORTS #define GLVIEWER_API __declspec(dllexport) @@ -33,5 +33,5 @@ #else #define GLVIEWER_API -#endif // WNT +#endif // WIN32 diff --git a/src/GLViewer/GLViewer.pro b/src/GLViewer/GLViewer.pro new file mode 100644 index 000000000..915c323a1 --- /dev/null +++ b/src/GLViewer/GLViewer.pro @@ -0,0 +1,86 @@ +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 diff --git a/src/GLViewer/GLViewer_AspectLine.cxx b/src/GLViewer/GLViewer_AspectLine.cxx index 6a91af84c..591fdff32 100644 --- a/src/GLViewer/GLViewer_AspectLine.cxx +++ b/src/GLViewer/GLViewer_AspectLine.cxx @@ -127,7 +127,8 @@ QByteArray GLViewer_AspectLine::getByteCopy() const 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; diff --git a/src/GLViewer/GLViewer_AspectLine.h b/src/GLViewer/GLViewer_AspectLine.h index 99cdbcd97..69b8d987b 100644 --- a/src/GLViewer/GLViewer_AspectLine.h +++ b/src/GLViewer/GLViewer_AspectLine.h @@ -27,9 +27,9 @@ #include "GLViewer.h" -#include +#include -#ifdef WNT +#ifdef WIN32 #pragma warning( disable:4251 ) #endif @@ -113,7 +113,7 @@ protected: int myLineType; }; -#ifdef WNT +#ifdef WIN32 #pragma warning ( default:4251 ) #endif diff --git a/src/GLViewer/GLViewer_BaseDrawers.cxx b/src/GLViewer/GLViewer_BaseDrawers.cxx index 80dfa1329..279ee513b 100644 --- a/src/GLViewer/GLViewer_BaseDrawers.cxx +++ b/src/GLViewer/GLViewer_BaseDrawers.cxx @@ -29,6 +29,10 @@ #include "GLViewer_AspectLine.h" #include "GLViewer_BaseObjects.h" +// Qt includes +#include + + #ifndef WIN32 #include #endif @@ -66,10 +70,10 @@ GLViewer_MarkerDrawer::~GLViewer_MarkerDrawer() */ void GLViewer_MarkerDrawer::create( float xScale, float yScale, bool onlyUpdate ) { - QValueList::Iterator it; - QValueList::Iterator EndIt; - QValueList::Iterator anObjectIt = myObjects.begin(); - QValueList::Iterator anEndObjectIt = myObjects.end(); + QList::Iterator it; + QList::Iterator EndIt; + QList::Iterator anObjectIt = myObjects.begin(); + QList::Iterator anEndObjectIt = myObjects.end(); myXScale = xScale; myYScale = yScale; @@ -89,7 +93,7 @@ void GLViewer_MarkerDrawer::create( float xScale, float yScale, bool onlyUpdate float* anYCoord = aMarkerSet->getYCoord(); float aRadius = aMarkerSet->getMarkerSize(); - QValueList aHNumbers, anUHNumbers, aSelNumbers, anUSelNumbers; + QList aHNumbers, anUHNumbers, aSelNumbers, anUSelNumbers; aMarkerSet->exportNumbers( aHNumbers, anUHNumbers, aSelNumbers, anUSelNumbers ); if( onlyUpdate ) @@ -189,8 +193,8 @@ GLViewer_PolylineDrawer::~GLViewer_PolylineDrawer() */ void GLViewer_PolylineDrawer::create( float xScale, float yScale, bool onlyUpdate ) { - QValueList::Iterator aObjectIt = myObjects.begin(); - QValueList::Iterator aObjectEndIt = myObjects.end(); + QList::Iterator aObjectIt = myObjects.begin(); + QList::Iterator aObjectEndIt = myObjects.end(); myXScale = xScale; myYScale = yScale; @@ -278,8 +282,8 @@ GLViewer_TextDrawer::~GLViewer_TextDrawer() */ void GLViewer_TextDrawer::create( float xScale, float yScale, bool onlyUpdate ) { - QValueList::Iterator aObjectIt = myObjects.begin(); - QValueList::Iterator aObjectEndIt = myObjects.end(); + QList::Iterator aObjectIt = myObjects.begin(); + QList::Iterator aObjectEndIt = myObjects.end(); myXScale = xScale; myYScale = yScale; @@ -322,8 +326,8 @@ void GLViewer_TextDrawer::create( float xScale, float yScale, bool onlyUpdate ) */ void GLViewer_TextDrawer::updateObjects() { - QValueList::Iterator aObjectIt = myObjects.begin(); - QValueList::Iterator aObjectEndIt = myObjects.end(); + QList::Iterator aObjectIt = myObjects.begin(); + QList::Iterator aObjectEndIt = myObjects.end(); for( ; aObjectIt != aObjectEndIt; aObjectIt++ ) (*aObjectIt)->compute(); } diff --git a/src/GLViewer/GLViewer_BaseDrawers.h b/src/GLViewer/GLViewer_BaseDrawers.h index d06311cf3..c0e1abedf 100644 --- a/src/GLViewer/GLViewer_BaseDrawers.h +++ b/src/GLViewer/GLViewer_BaseDrawers.h @@ -25,18 +25,14 @@ #ifndef GLVIEWER_BASEDRAWERS_H #define GLVIEWER_BASEDRAWERS_H -#include -#include -#include -#include -#include +class QColor; #include "GLViewer.h" #include "GLViewer_Drawer.h" class GLViewer_AspectLine; -#ifdef WNT +#ifdef WIN32 #pragma warning( disable:4251 ) #endif @@ -91,7 +87,7 @@ public: void updateObjects(); }; -#ifdef WNT +#ifdef WIN32 #pragma warning ( default:4251 ) #endif diff --git a/src/GLViewer/GLViewer_BaseObjects.cxx b/src/GLViewer/GLViewer_BaseObjects.cxx index 338543ee3..7a049ffc6 100644 --- a/src/GLViewer/GLViewer_BaseObjects.cxx +++ b/src/GLViewer/GLViewer_BaseObjects.cxx @@ -29,6 +29,8 @@ #include "GLViewer_Drawer.h" +#include + //#include //using namespace std; @@ -214,7 +216,7 @@ bool GLViewer_MarkerSet::translateToPS( QFile& hFile, GLViewer_CoordSystem* aVie } aBuffer+="closepath\nstroke\n"; - hFile.writeBlock( aBuffer.ascii(), aBuffer.length() ); + hFile.write( aBuffer.toAscii() ); return true; } @@ -252,7 +254,7 @@ bool GLViewer_MarkerSet::translateToHPGL( QFile& hFile, GLViewer_CoordSystem* aV } aBuffer+="PU;\n"; - hFile.writeBlock( aBuffer.ascii(), aBuffer.length() ); + hFile.write( aBuffer.toAscii() ); } return true; @@ -313,10 +315,10 @@ void GLViewer_MarkerSet::compute() 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; @@ -352,8 +354,8 @@ GLboolean GLViewer_MarkerSet::highlight( GLfloat x, GLfloat y, GLfloat tol, GLbo // cout << "GLViewer_MarkerSet::highlight " << x <<" " << y << " " << tol << endl; int count = 0; GLfloat xdist, ydist, radius; - QValueList::Iterator it; - QValueList curHNumbers; + QList::Iterator it; + QList curHNumbers; bool isFound; GLboolean update; int cnt = 0; @@ -432,10 +434,10 @@ GLboolean GLViewer_MarkerSet::select( GLfloat x, GLfloat y, GLfloat tol, GLViewe // cout << "GLViewer_MarkerSet::select " << x << " " << y << endl; int count = 0; GLfloat xdist, ydist, radius; - QValueList::Iterator it; - QValueList::Iterator it1; - QValueList::Iterator remIt; - QValueList::Iterator curIt; + QList::Iterator it; + QList::Iterator it1; + QList::Iterator remIt; + QList::Iterator curIt; radius = tol - myMarkerSize / 2.; @@ -481,35 +483,35 @@ GLboolean GLViewer_MarkerSet::select( GLfloat x, GLfloat y, GLfloat tol, GLViewe 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; } } @@ -521,13 +523,13 @@ GLboolean GLViewer_MarkerSet::select( GLfloat x, GLfloat y, GLfloat tol, GLViewe 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; } } @@ -538,7 +540,7 @@ GLboolean GLViewer_MarkerSet::select( GLfloat x, GLfloat y, GLfloat tol, GLViewe for( it1 = myUSelNumbers.begin(); it1 != myUSelNumbers.end(); ++it1 ) if( *it == *it1 ) { - it1 = myUSelNumbers.remove( it1 ); + it1 = myUSelNumbers.erase( it1 ); it1--; } @@ -633,10 +635,10 @@ void GLViewer_MarkerSet::setNumMarkers( GLint number ) /*! Export numbers of highlighted/selected lines */ -void GLViewer_MarkerSet::exportNumbers( QValueList& highlight, - QValueList& unhighlight, - QValueList& select, - QValueList& unselect ) +void GLViewer_MarkerSet::exportNumbers( QList& highlight, + QList& unhighlight, + QList& select, + QList& unselect ) { highlight = myHNumbers; unhighlight = myUHNumbers; @@ -655,14 +657,12 @@ bool GLViewer_MarkerSet::addOrRemoveSelected( int index ) 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::Iterator it; - it = mySelNumbers.at( n ); - mySelNumbers.remove( it ); + mySelNumbers.removeAt(n); myUSelNumbers.append( index ); } return TRUE; @@ -675,7 +675,7 @@ bool GLViewer_MarkerSet::addOrRemoveSelected( int index ) 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 ); } @@ -685,7 +685,7 @@ void GLViewer_MarkerSet::addSelected( const TColStd_SequenceOfInteger& seq ) */ void GLViewer_MarkerSet::setSelected( const TColStd_SequenceOfInteger& seq ) { -// for( QValueList::Iterator it = mySelNumbers.begin(); it != mySelNumbers.end(); ++it ) +// for( QList::Iterator it = mySelNumbers.begin(); it != mySelNumbers.end(); ++it ) // if( myUSelNumbers.findIndex( *it ) == -1 ) // myUSelNumbers.append( *it ); @@ -728,7 +728,8 @@ QByteArray GLViewer_MarkerSet::getByteCopy() 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++ ) @@ -784,7 +785,8 @@ bool GLViewer_MarkerSet::initializeFromByteCopy( QByteArray theArray ) *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]; @@ -871,7 +873,7 @@ bool GLViewer_Polyline::translateToPS( QFile& hFile, GLViewer_CoordSystem* aView aBuffer+="closepath\nstroke\n"; - hFile.writeBlock( aBuffer.ascii(), aBuffer.length() ); + hFile.write( aBuffer.toAscii() ); return true; } @@ -897,7 +899,7 @@ bool GLViewer_Polyline::translateToHPGL( QFile& hFile, GLViewer_CoordSystem* aVi aBuffer+="PU;\n"; - hFile.writeBlock( aBuffer.ascii(), aBuffer.length() ); + hFile.write( aBuffer.toAscii() ); return true; } @@ -958,10 +960,10 @@ void GLViewer_Polyline::compute() 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; @@ -1219,10 +1221,10 @@ void GLViewer_Polyline::setNumber( GLint number ) /*! Export numbers of highlighted/selected lines */ -void GLViewer_Polyline::exportNumbers( QValueList& highlight, - QValueList& unhighlight, - QValueList& select, - QValueList& unselect ) +void GLViewer_Polyline::exportNumbers( QList& highlight, + QList& unhighlight, + QList& select, + QList& unselect ) { highlight = myHNumbers; unhighlight = myUHNumbers; @@ -1264,7 +1266,8 @@ QByteArray GLViewer_Polyline::getByteCopy() 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++ ) @@ -1327,7 +1330,8 @@ bool GLViewer_Polyline::initializeFromByteCopy( QByteArray theArray ) *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]; @@ -1394,7 +1398,7 @@ bool GLViewer_TextObject::translateToPS( QFile& hFile, GLViewer_CoordSystem* aVi 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; } @@ -1416,7 +1420,7 @@ bool GLViewer_TextObject::translateToHPGL( QFile& hFile, GLViewer_CoordSystem* a aBuffer = "LB" + aText + "#;"; - hFile.writeBlock( aBuffer.ascii(), aBuffer.length() ); + hFile.write( aBuffer.toAscii() ); return true; } @@ -1438,7 +1442,7 @@ bool GLViewer_TextObject::translateToEMF( HDC dc, GLViewer_CoordSystem* aViewerC 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 diff --git a/src/GLViewer/GLViewer_BaseObjects.h b/src/GLViewer/GLViewer_BaseObjects.h index c0f45d328..051e13f9f 100644 --- a/src/GLViewer/GLViewer_BaseObjects.h +++ b/src/GLViewer/GLViewer_BaseObjects.h @@ -28,12 +28,11 @@ #include "GLViewer.h" #include "GLViewer_Object.h" -#include -#include +#include #include -#ifdef WNT +#ifdef WIN32 #pragma warning( disable:4251 ) #endif @@ -92,11 +91,11 @@ public: float getMarkerSize() const { return myMarkerSize; } //! Export numbers of heghlighted/selected markers - void exportNumbers( QValueList& high, QValueList& unhigh, - QValueList& sel, QValueList& unsel ); + void exportNumbers( QList& high, QList& unhigh, + QList& sel, QList& unsel ); //! Returns selected numbers - QValueList getSelectedElements() { return mySelNumbers; } + QList getSelectedElements() { return mySelNumbers; } //! Adds or remove selected number bool addOrRemoveSelected( int index ); //! Adds selected numbers @@ -109,12 +108,12 @@ protected: GLfloat* myXCoord; GLfloat* myYCoord; GLfloat myMarkerSize; - QValueList myHNumbers; - QValueList myUHNumbers; - QValueList mySelNumbers; - QValueList myCurSelNumbers; - QValueList myUSelNumbers; - QValueList myPrevHNumbers; + QList myHNumbers; + QList myUHNumbers; + QList mySelNumbers; + QList myCurSelNumbers; + QList myUSelNumbers; + QList myPrevHNumbers; TColStd_SequenceOfInteger mySelectedIndexes; }; @@ -177,11 +176,11 @@ public: GLboolean isHighSelAll() const { return myHighSelAll; } //! Export numbers of highlighted/selected lines - void exportNumbers( QValueList& high, QValueList& unhigh, - QValueList& sel, QValueList& unsel ); + void exportNumbers( QList& high, QList& unhigh, + QList& sel, QList& unsel ); //! Returns numbers of selected lines - QValueList getSelectedElements() { return mySelNumbers; } + QList getSelectedElements() { return mySelNumbers; } protected: GLfloat* myXCoord; @@ -190,12 +189,12 @@ protected: GLboolean myIsClosed; GLboolean myHighSelAll; - QValueList myHNumbers; - QValueList myUHNumbers; - QValueList mySelNumbers; - QValueList myUSelNumbers; - QValueList myCurSelNumbers; - QValueList myPrevHNumbers; + QList myHNumbers; + QList myUHNumbers; + QList mySelNumbers; + QList myUSelNumbers; + QList myCurSelNumbers; + QList myPrevHNumbers; TColStd_SequenceOfInteger mySelectedIndexes; GLboolean myHighFlag; @@ -248,7 +247,7 @@ protected: int myHeight; }; -#ifdef WNT +#ifdef WIN32 #pragma warning ( default:4251 ) #endif diff --git a/src/GLViewer/GLViewer_Compass.h b/src/GLViewer/GLViewer_Compass.h index 62dd4f257..ee52be281 100644 --- a/src/GLViewer/GLViewer_Compass.h +++ b/src/GLViewer/GLViewer_Compass.h @@ -27,9 +27,11 @@ #include "GLViewer.h" -#include +#include -#ifdef WNT +class QFont; + +#ifdef WIN32 #pragma warning( disable:4251 ) #endif @@ -142,7 +144,7 @@ protected: bool isGenereted; }; -#ifdef WNT +#ifdef WIN32 #pragma warning ( default:4251 ) #endif diff --git a/src/GLViewer/GLViewer_Context.cxx b/src/GLViewer/GLViewer_Context.cxx index 0383b0325..496d79bed 100644 --- a/src/GLViewer/GLViewer_Context.cxx +++ b/src/GLViewer/GLViewer_Context.cxx @@ -33,6 +33,10 @@ #include "GLViewer_Object.h" #include "GLViewer_Viewer2d.h" #include "GLViewer_ViewPort2d.h" +#include "GLViewer_ViewFrame.h" + +//QT includes +#include #include @@ -222,7 +226,7 @@ int GLViewer_Context::Select( bool Append, bool byCircle ) } else if( myLastPicked->isSelected() && status != SS_LocalChanged ) { - mySelectedObjects.remove( myLastPicked ); + mySelectedObjects.removeAll( myLastPicked ); myLastPicked->unselect(); myGLViewer2d->updateAll(); @@ -233,7 +237,7 @@ int GLViewer_Context::Select( bool Append, bool byCircle ) } 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 ); @@ -370,7 +374,7 @@ int GLViewer_Context::SelectByRect( const QRect& theRect, bool Append ) isSel = (*it)->isSelected(); } - if( isSel && mySelectedObjects.findIndex( *it ) == -1 ) + if( isSel && mySelectedObjects.indexOf( *it ) == -1 ) { aList.append( *it ); mySelectedObjects.append( *it ); @@ -527,14 +531,14 @@ bool GLViewer_Context::replaceObject( GLViewer_Object* oldObject, GLViewer_Objec 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; } @@ -626,7 +630,7 @@ void GLViewer_Context::remSelected( GLViewer_Object* object, bool updateViewer ) if( !object || !mySelectedObjects.contains( object ) ) return; - mySelectedObjects.remove( object ); + mySelectedObjects.removeAll( object ); object->unselect(); if( updateViewer ) @@ -661,14 +665,14 @@ void GLViewer_Context::deleteObject( GLViewer_Object* theObject, bool updateView 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 ) @@ -690,7 +694,7 @@ bool GLViewer_Context::setActive( GLViewer_Object* theObject ) if( !theObject || !myInactiveObjects.contains( theObject ) ) return false; - myInactiveObjects.remove( theObject ); + myInactiveObjects.removeAll( theObject ); myActiveObjects.append( theObject ); return true; } @@ -704,7 +708,7 @@ bool GLViewer_Context::setInactive( GLViewer_Object* theObject ) if( !theObject || !myActiveObjects.contains( theObject ) ) return false; - myActiveObjects.remove( theObject ); + myActiveObjects.removeAll( theObject ); myInactiveObjects.append( theObject ); return true; } diff --git a/src/GLViewer/GLViewer_Context.h b/src/GLViewer/GLViewer_Context.h index 5a9df2ceb..aa367366c 100644 --- a/src/GLViewer/GLViewer_Context.h +++ b/src/GLViewer/GLViewer_Context.h @@ -26,16 +26,14 @@ #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 -#include -#include +class QRect; #include #include @@ -44,7 +42,7 @@ class GLViewer_Viewer2d; -#ifdef WNT +#ifdef WIN32 #pragma warning( disable:4251 ) #endif @@ -201,7 +199,7 @@ protected: int myTolerance; }; -#ifdef WNT +#ifdef WIN32 #pragma warning ( default:4251 ) #endif diff --git a/src/GLViewer/GLViewer_CoordSystem.h b/src/GLViewer/GLViewer_CoordSystem.h index 6db89583b..83d7b55e1 100644 --- a/src/GLViewer/GLViewer_CoordSystem.h +++ b/src/GLViewer/GLViewer_CoordSystem.h @@ -31,7 +31,7 @@ #include "GLViewer.h" -#ifdef WNT +#ifdef WIN32 #pragma warning( disable:4251 ) #endif @@ -100,7 +100,7 @@ protected: virtual void fromReference( double& x, double& y ); }; -#ifdef WNT +#ifdef WIN32 #pragma warning ( default:4251 ) #endif diff --git a/src/GLViewer/GLViewer_Defs.h b/src/GLViewer/GLViewer_Defs.h index 411fb4a7a..c11455d3d 100644 --- a/src/GLViewer/GLViewer_Defs.h +++ b/src/GLViewer/GLViewer_Defs.h @@ -25,8 +25,8 @@ #ifndef GLVIEWER_DEFS_H #define GLVIEWER_DEFS_H -#include -#include +#include +#include class GLViewer_Object; //Selection staus @@ -57,7 +57,7 @@ enum SelectionStatus }; typedef QMap ObjectMap; -typedef QValueList ObjList; +typedef QList ObjList; #define SEGMENTS 32 #define PI 3.14159265359 diff --git a/src/GLViewer/GLViewer_Drawer.cxx b/src/GLViewer/GLViewer_Drawer.cxx index d0001a49c..6fbf36182 100644 --- a/src/GLViewer/GLViewer_Drawer.cxx +++ b/src/GLViewer/GLViewer_Drawer.cxx @@ -29,15 +29,17 @@ #include "GLViewer_ViewFrame.h" #include "GLViewer_ViewPort2d.h" +#include +#include +#include +#include + #ifndef WIN32 #include #endif #include -#include -#include - #define TEXT_GAP 5 // Two texture components for texmapped fonts: luminance and alpha #define NB_TEX_COMP 2 @@ -73,7 +75,7 @@ void GLViewer_TexFont::clearTextBases() GLViewer_TexFont::GLViewer_TexFont() : myMaxRowWidth( 0 ), myFontHeight( 0 ) { - myQFont = QFont::defaultFont(); + myQFont = QApplication::font();//QFont::defaultFont(); mySeparator = 2; myIsResizeable = false; myMinMagFilter = GL_LINEAR; @@ -204,7 +206,7 @@ bool GLViewer_TexFont::generateTexture() aPainter.drawText( myPositions[l], ( row + 1 ) * aRowPixelHeight - aDescent, aLetter ); } - QImage aImage = aPixmap.convertToImage(); + QImage aImage = aPixmap.toImage(); //int qqq = 0; //if (qqq) @@ -308,7 +310,7 @@ void GLViewer_TexFont::drawString( QString theStr, GLdouble theX , GLdouble theY 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; @@ -340,7 +342,7 @@ int GLViewer_TexFont::getStringWidth( QString theStr ) 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; } @@ -388,8 +390,8 @@ static GLuint displayListBase( QFont* theFont ) QMap::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; @@ -429,19 +431,19 @@ static GLuint displayListBase( QFont* theFont ) QMap::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 ); @@ -449,7 +451,7 @@ static GLuint displayListBase( QFont* theFont ) 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_ @@ -504,7 +506,7 @@ void GLViewer_Drawer::destroyAllTextures() QMap::Iterator anEndIt= GLViewer_TexFont::TexFontBase.end(); for( ; anIt != anEndIt; anIt++ ) - glDeleteTextures( 1, &(anIt.data().myTexFontId) ); + glDeleteTextures( 1, &(anIt.value().myTexFontId) ); } /*! @@ -785,7 +787,7 @@ void GLViewer_Drawer::drawText( const QString& text, GLfloat xPos, GLfloat yPos, { glRasterPos2f( xPos, yPos ); glListBase( displayListBase( theFont ) ); - glCallLists( text.length(), GL_UNSIGNED_BYTE, text.local8Bit().data() ); + glCallLists( text.length(), GL_UNSIGNED_BYTE, text.toLocal8Bit().data() ); } } @@ -996,7 +998,7 @@ void GLViewer_Drawer::drawContour( const GLViewer_PntList& pntList, QColor color glLineWidth( lineWidth ); glBegin( GL_LINES ); - QValueList::const_iterator it = pntList.begin(); + QList::const_iterator it = pntList.begin(); for( ; it != pntList.end(); ++it ) glVertex2f( (*it).x(), (*it).y() ); glEnd(); @@ -1051,7 +1053,7 @@ void GLViewer_Drawer::drawPolygon( const GLViewer_PntList& pntList, QColor color ( GLfloat )color.green() / 255, ( GLfloat )color.blue() / 255 ); glBegin( GL_POLYGON ); - QValueList::const_iterator it = pntList.begin(); + QList::const_iterator it = pntList.begin(); for( ; it != pntList.end(); ++it ) glVertex2f( (*it).x(), (*it).y() ); glEnd(); diff --git a/src/GLViewer/GLViewer_Drawer.h b/src/GLViewer/GLViewer_Drawer.h index 21c6386ce..859eecbc3 100644 --- a/src/GLViewer/GLViewer_Drawer.h +++ b/src/GLViewer/GLViewer_Drawer.h @@ -25,15 +25,14 @@ #ifndef GLVIEWER_DRAWER_H #define GLVIEWER_DRAWER_H -#ifdef WNT +#ifdef WIN32 #include "windows.h" #endif -#include -#include -#include -#include -#include +#include +#include + +class QFile; #include @@ -45,7 +44,7 @@ class GLViewer_Object; class GLViewer_Rect; class GLViewer_CoordSystem; -#ifdef WNT +#ifdef WIN32 #pragma warning( disable:4251 ) #endif /*! @@ -424,7 +423,7 @@ protected: float myYScale; //! List of objects - QValueList myObjects; + QList myObjects; //! List generated textures GLuint myTextList; @@ -443,7 +442,7 @@ protected: GLfloat myTextScale; }; -#ifdef WNT +#ifdef WIN32 #pragma warning ( default:4251 ) #endif diff --git a/src/GLViewer/GLViewer_Geom.h b/src/GLViewer/GLViewer_Geom.h index 7ba4db69f..13397fce4 100644 --- a/src/GLViewer/GLViewer_Geom.h +++ b/src/GLViewer/GLViewer_Geom.h @@ -27,13 +27,13 @@ #include "GLViewer.h" -#include -#include -#include +#include +#include #include +//using namespace QGL; -#ifdef WNT +#ifdef WIN32 #pragma warning( disable:4251 ) #endif @@ -59,7 +59,7 @@ private: GLfloat myY; }; -typedef QValueList GLViewer_PntList; +typedef QList GLViewer_PntList; /*! Class GLViewer_Rect * Substitution of QRect for OpenGL @@ -191,7 +191,7 @@ private: GLViewer_PntList* myPoints; }; -#ifdef WNT +#ifdef WIN32 #pragma warning ( default:4251 ) #endif diff --git a/src/GLViewer/GLViewer_Grid.cxx b/src/GLViewer/GLViewer_Grid.cxx index 13a661caf..9420de128 100644 --- a/src/GLViewer/GLViewer_Grid.cxx +++ b/src/GLViewer/GLViewer_Grid.cxx @@ -27,7 +27,6 @@ #include "GLViewer_Defs.h" #include -#include /*! Default constructor diff --git a/src/GLViewer/GLViewer_Grid.h b/src/GLViewer/GLViewer_Grid.h index d4a4567e4..d4ff7b6a4 100644 --- a/src/GLViewer/GLViewer_Grid.h +++ b/src/GLViewer/GLViewer_Grid.h @@ -25,7 +25,7 @@ #ifndef GLVIEWER_GRID_H #define GLVIEWER_GRID_H -#ifdef WNT +#ifdef WIN32 #include "windows.h" #endif @@ -34,7 +34,7 @@ #include #include -#ifdef WNT +#ifdef WIN32 #pragma warning( disable:4251 ) #endif @@ -115,7 +115,7 @@ protected: GLboolean myIsUpdate; }; -#ifdef WNT +#ifdef WIN32 #pragma warning ( default:4251 ) #endif diff --git a/src/GLViewer/GLViewer_Group.h b/src/GLViewer/GLViewer_Group.h index 4382b06c9..620cd2f35 100644 --- a/src/GLViewer/GLViewer_Group.h +++ b/src/GLViewer/GLViewer_Group.h @@ -28,7 +28,7 @@ #include #include "GLViewer.h" -#ifdef WNT +#ifdef WIN32 #pragma warning( disable:4251 ) #endif diff --git a/src/GLViewer/GLViewer_MimeData.cxx b/src/GLViewer/GLViewer_MimeData.cxx new file mode 100644 index 000000000..d669475f9 --- /dev/null +++ b/src/GLViewer/GLViewer_MimeData.cxx @@ -0,0 +1,248 @@ +// 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 +#include "GLViewer_MimeData.h" +#include "GLViewer_BaseObjects.h" + +//#include +//using namespace std; + +/*! + Destructor +*/ +GLViewer_MimeData::~GLViewer_MimeData() +{ +} + +/*! + Translate objects to byte array + \param theObjects - list of objects +*/ +bool GLViewer_MimeData::setObjects( QList theObjects ) +{ + if( !theObjects.empty() ) + { + QStringList aObjectsType; + QList aObjects; + QList::const_iterator anIt = theObjects.begin(); + QList::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::iterator anObjIt = aObjects.begin(); + QList::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_MimeData::getObjects( QByteArray theArray, QString theType ) +{ + if( !theArray.isEmpty() ) + { + int anISize = sizeof( int ); + if( theType == "GLViewer_Objects" ) + { + QStringList aTypeList; + QList aObjects; + QList aObjectList; + + QList aTypeSizeList; + QList 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(); +} + +/*! + \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(); +} diff --git a/src/GLViewer/GLViewer_MimeData.h b/src/GLViewer/GLViewer_MimeData.h new file mode 100644 index 000000000..1a5f816fb --- /dev/null +++ b/src/GLViewer/GLViewer_MimeData.h @@ -0,0 +1,72 @@ +// 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 +#endif + +#include "GLViewer.h" + +#include + +#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 ); + //! Gets objects from byte array + /*If you want to use new class, following two method must be redefined*/ + static QList 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 diff --git a/src/GLViewer/GLViewer_MimeSource.cxx b/src/GLViewer/GLViewer_MimeSource.cxx deleted file mode 100644 index ca82fbacd..000000000 --- a/src/GLViewer/GLViewer_MimeSource.cxx +++ /dev/null @@ -1,247 +0,0 @@ -// 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 -#include "GLViewer_MimeSource.h" -#include "GLViewer_BaseObjects.h" - -//#include -//using namespace std; - -/*! - Destructor -*/ -GLViewer_MimeSource::~GLViewer_MimeSource() -{ -} - -/*! - Translate objects to byte array - \param theObjects - list of objects -*/ -bool GLViewer_MimeSource::setObjects( QValueList theObjects ) -{ - if( !theObjects.empty() ) - { - QStringList aObjectsType; - QValueList aObjects; - QValueList::const_iterator anIt = theObjects.begin(); - QValueList::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::iterator anObjIt = aObjects.begin(); - QValueList::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_MimeSource::getObjects( QByteArray theArray, QString theType ) -{ - if( !theArray.isEmpty() ) - { - int anISize = sizeof( int ); - if( theType == "GLViewer_Objects" ) - { - QStringList aTypeList; - QValueList aObjects; - QValueList aObjectList; - - QValueList aTypeSizeList; - QValueList 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(); -} - -/*! - \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(); -} diff --git a/src/GLViewer/GLViewer_MimeSource.h b/src/GLViewer/GLViewer_MimeSource.h deleted file mode 100644 index 55262d1d1..000000000 --- a/src/GLViewer/GLViewer_MimeSource.h +++ /dev/null @@ -1,74 +0,0 @@ -// 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 -#endif - -#include "GLViewer.h" - -#include -#include - -#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 ); - //! Gets objects from byte array - /*If you want to use new class, following two method must be redefined*/ - static QValueList 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 diff --git a/src/GLViewer/GLViewer_Object.cxx b/src/GLViewer/GLViewer_Object.cxx index 7de98ed37..c6a920c81 100644 --- a/src/GLViewer/GLViewer_Object.cxx +++ b/src/GLViewer/GLViewer_Object.cxx @@ -23,10 +23,11 @@ #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 + //#include //using namespace std; @@ -141,8 +142,8 @@ QByteArray GLViewer_Object::getByteCopy() 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(); @@ -163,9 +164,10 @@ QByteArray GLViewer_Object::getByteCopy() 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++ ) @@ -225,7 +227,9 @@ bool GLViewer_Object::initializeFromByteCopy( QByteArray theArray ) 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; diff --git a/src/GLViewer/GLViewer_Object.h b/src/GLViewer/GLViewer_Object.h index 2384bb440..503a5a038 100644 --- a/src/GLViewer/GLViewer_Object.h +++ b/src/GLViewer/GLViewer_Object.h @@ -25,23 +25,20 @@ #ifndef GLVIEWER_OBJECT_H #define GLVIEWER_OBJECT_H -#ifdef WNT +#ifdef WIN32 #include #endif #include "GLViewer.h" -#include "GLViewer_Defs.h" #include "GLViewer_Geom.h" -#include - #include -#include -#include -#include +#include + +class QFile; -#ifdef WNT +#ifdef WIN32 #pragma warning( disable:4251 ) #endif @@ -52,6 +49,8 @@ class GLViewer_CoordSystem; class GLViewer_Text; //class GLViewer_Owner; +class SUIT_DataOwner; + /*! * Class GLViewer_Object * Base Object for all GLViewer objects @@ -303,7 +302,7 @@ protected: GLViewer_Group* myGroup; }; -#ifdef WNT +#ifdef WIN32 #pragma warning ( default:4251 ) #endif diff --git a/src/GLViewer/GLViewer_Selector.cxx b/src/GLViewer/GLViewer_Selector.cxx index 4e4c91aea..82b9834e5 100644 --- a/src/GLViewer/GLViewer_Selector.cxx +++ b/src/GLViewer/GLViewer_Selector.cxx @@ -27,7 +27,7 @@ #include "GLViewer_Viewer.h" -int GLViewer_Selector::apppendKey = Qt::ShiftButton; +int GLViewer_Selector::apppendKey = Qt::ShiftModifier; /*! Constructor diff --git a/src/GLViewer/GLViewer_Selector.h b/src/GLViewer/GLViewer_Selector.h index 6c0672843..ff044848d 100644 --- a/src/GLViewer/GLViewer_Selector.h +++ b/src/GLViewer/GLViewer_Selector.h @@ -28,8 +28,10 @@ #include "GLViewer.h" #include "GLViewer_Defs.h" -#include -#include +#include +#include + +class QRect; #include diff --git a/src/GLViewer/GLViewer_Selector2d.cxx b/src/GLViewer/GLViewer_Selector2d.cxx index 067b29541..362f9625c 100644 --- a/src/GLViewer/GLViewer_Selector2d.cxx +++ b/src/GLViewer/GLViewer_Selector2d.cxx @@ -26,7 +26,8 @@ #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 diff --git a/src/GLViewer/GLViewer_Selector2d.h b/src/GLViewer/GLViewer_Selector2d.h index 34da93d59..bbb4c3634 100644 --- a/src/GLViewer/GLViewer_Selector2d.h +++ b/src/GLViewer/GLViewer_Selector2d.h @@ -25,7 +25,7 @@ #ifndef GLVIEWER_SELECTOR2D_H #define GLVIEWER_SELECTOR2D_H -#ifdef WNT +#ifdef WIN32 #include "windows.h" #endif diff --git a/src/GLViewer/GLViewer_Text.cxx b/src/GLViewer/GLViewer_Text.cxx index f4dba3a47..24631871d 100644 --- a/src/GLViewer/GLViewer_Text.cxx +++ b/src/GLViewer/GLViewer_Text.cxx @@ -22,6 +22,9 @@ //#include #include "GLViewer_Text.h" +#include +#include + /*! Constructor */ @@ -31,7 +34,7 @@ GLViewer_Text::GLViewer_Text( const QString& text, float xPos, float yPos, const myXPos = xPos; myYPos = yPos; myColor = color; - myQFont = QFont::defaultFont(); + myQFont = QApplication::font();//QFont::defaultFont(); mySeparator = 2; myDTF = DTF_BITMAP; } @@ -90,10 +93,11 @@ QByteArray GLViewer_Text::getByteCopy() const 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++ ) @@ -124,7 +128,7 @@ QByteArray GLViewer_Text::getByteCopy() const 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++ ) diff --git a/src/GLViewer/GLViewer_Text.h b/src/GLViewer/GLViewer_Text.h index edf680e7b..fefe786b5 100644 --- a/src/GLViewer/GLViewer_Text.h +++ b/src/GLViewer/GLViewer_Text.h @@ -25,7 +25,7 @@ #ifndef GLVIEWER_TEXT_H #define GLVIEWER_TEXT_H -#ifdef WNT +#ifdef WIN32 #include #endif @@ -34,12 +34,11 @@ #include -#include -#include -#include -#include +#include +#include +#include -#ifdef WNT +#ifdef WIN32 #pragma warning( disable:4251 ) #endif @@ -107,7 +106,7 @@ protected: DisplayTextFormat myDTF; }; -#ifdef WNT +#ifdef WIN32 #pragma warning ( default:4251 ) #endif diff --git a/src/GLViewer/GLViewer_ToolTip.cxx b/src/GLViewer/GLViewer_ToolTip.cxx index c4449265c..e246f163d 100644 --- a/src/GLViewer/GLViewer_ToolTip.cxx +++ b/src/GLViewer/GLViewer_ToolTip.cxx @@ -27,12 +27,14 @@ #include "GLViewer_ToolTip.h" #include "GLViewer_Viewer2d.h" #include "GLViewer_ViewPort2d.h" +#include "GLViewer_ViewFrame.h" -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include /*! constructor @@ -44,15 +46,16 @@ GLViewer_ObjectTip::GLViewer_ObjectTip( GLViewer_ViewPort2d* theParent ) { 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() ); diff --git a/src/GLViewer/GLViewer_ToolTip.h b/src/GLViewer/GLViewer_ToolTip.h index 508679b6a..ee01466cc 100644 --- a/src/GLViewer/GLViewer_ToolTip.h +++ b/src/GLViewer/GLViewer_ToolTip.h @@ -29,12 +29,14 @@ //#include //#include -#include +#include +#include #define TIP_TIME 1000 class GLViewer_ViewPort2d; class QLabel; +class QTimer; /*! \class GLViewer_ObjectTip ToolTip of GLViewer_Objects diff --git a/src/GLViewer/GLViewer_Tools.h b/src/GLViewer/GLViewer_Tools.h index b9add1f19..2ec85061e 100644 --- a/src/GLViewer/GLViewer_Tools.h +++ b/src/GLViewer/GLViewer_Tools.h @@ -25,14 +25,11 @@ #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 diff --git a/src/GLViewer/GLViewer_ViewFrame.cxx b/src/GLViewer/GLViewer_ViewFrame.cxx index d89922d48..0461a4edd 100644 --- a/src/GLViewer/GLViewer_ViewFrame.cxx +++ b/src/GLViewer/GLViewer_ViewFrame.cxx @@ -25,7 +25,6 @@ //#include #include "GLViewer_ViewFrame.h" #include "GLViewer_Viewer.h" -#include "GLViewer_Viewer2d.h" #include "GLViewer_ViewPort2d.h" #include @@ -34,11 +33,22 @@ #include #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef WIN32 +#include +#include +using namespace std; +#endif /*! Constructor @@ -51,8 +61,9 @@ myVP( 0 ) 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 ); @@ -60,10 +71,11 @@ myVP( 0 ) //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(); } @@ -82,59 +94,59 @@ void GLViewer_ViewFrame::createActions() { 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; @@ -213,7 +225,7 @@ QColor GLViewer_ViewFrame::backgroundColor() const { if ( myVP ) return myVP->backgroundColor(); - return QMainWindow::backgroundColor(); + return palette().color( backgroundRole() ); } /*! @@ -272,7 +284,7 @@ void GLViewer_ViewFrame::onViewDump() imageBits = new unsigned char[imageSize]; -#ifdef WNT +#ifdef WIN32 int num; HBITMAP hBmp; @@ -380,7 +392,7 @@ void GLViewer_ViewFrame::onViewDump() #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 ); @@ -397,26 +409,27 @@ void GLViewer_ViewFrame::onViewDump() 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" ) { @@ -429,16 +442,15 @@ void GLViewer_ViewFrame::onViewDump() 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" ) ); } } @@ -584,7 +596,7 @@ QString GLViewer_ViewFrame::getVisualParameters() */ 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; diff --git a/src/GLViewer/GLViewer_ViewFrame.h b/src/GLViewer/GLViewer_ViewFrame.h index 76b9fe55b..00b83e334 100644 --- a/src/GLViewer/GLViewer_ViewFrame.h +++ b/src/GLViewer/GLViewer_ViewFrame.h @@ -35,9 +35,9 @@ class SUIT_Desktop; class GLViewer_Viewer; class GLViewer_ViewPort; -#include +#include -#ifdef WNT +#ifdef WIN32 #pragma warning( disable:4251 ) #endif @@ -113,7 +113,7 @@ private: private: //! Actions ID enum { DumpId, FitAllId, FitRectId, FitSelectId, ZoomId, PanId, GlobalPanId, ResetId }; - typedef QMap ActionsMap; + typedef QMap ActionsMap; private: ActionsMap myActionsMap; @@ -121,7 +121,7 @@ private: }; -#ifdef WNT +#ifdef WIN32 #pragma warning ( default:4251 ) #endif diff --git a/src/GLViewer/GLViewer_ViewManager.cxx b/src/GLViewer/GLViewer_ViewManager.cxx index 8e1f1e860..e1df3666a 100644 --- a/src/GLViewer/GLViewer_ViewManager.cxx +++ b/src/GLViewer/GLViewer_ViewManager.cxx @@ -24,7 +24,6 @@ //#include #include "GLViewer_ViewManager.h" -#include "GLViewer_ViewFrame.h" #include "GLViewer_Viewer2d.h" #include "SUIT_Desktop.h" @@ -41,7 +40,7 @@ GLViewer_ViewManager::~GLViewer_ViewManager() } /*!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 diff --git a/src/GLViewer/GLViewer_ViewManager.h b/src/GLViewer/GLViewer_ViewManager.h index 3542d63f3..c29525678 100644 --- a/src/GLViewer/GLViewer_ViewManager.h +++ b/src/GLViewer/GLViewer_ViewManager.h @@ -40,7 +40,7 @@ public: GLViewer_Viewer* getGLViewer() { return (GLViewer_Viewer*) myViewModel; } - virtual void contextMenuPopup( QPopupMenu* ); + virtual void contextMenuPopup( QMenu* ); }; #endif // GLVIEWER_VIEWMANAGER_H diff --git a/src/GLViewer/GLViewer_ViewPort.cxx b/src/GLViewer/GLViewer_ViewPort.cxx index 07de20242..663afcf45 100644 --- a/src/GLViewer/GLViewer_ViewPort.cxx +++ b/src/GLViewer/GLViewer_ViewPort.cxx @@ -24,26 +24,25 @@ //#include -#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 -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +//#include +#include +#include +#include +#include #include -#if !defined WNT +#if !defined WIN32 +#include #include #include #include @@ -83,17 +82,19 @@ CMapEntry::CMapEntry() CMapEntry::~CMapEntry() { if ( alloc ) - XFreeColormap( QPaintDevice::x11AppDisplay(), cmap ); + XFreeColormap( QX11Info::display(), cmap ); } -static QIntDict *cmap_dict = 0; +static QMultiHash *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; } @@ -102,17 +103,17 @@ static Colormap choose_cmap( Display *dpy, XVisualInfo *vi ) { if ( !cmap_dict ) { - cmap_dict = new QIntDict; + cmap_dict = new QMultiHash; 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::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; @@ -121,12 +122,12 @@ static Colormap choose_cmap( Display *dpy, XVisualInfo *vi ) 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 ) @@ -137,12 +138,12 @@ static Colormap choose_cmap( Display *dpy, XVisualInfo *vi ) 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++; } @@ -151,19 +152,19 @@ static Colormap choose_cmap( Display *dpy, XVisualInfo *vi ) } } #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++; } @@ -172,15 +173,15 @@ static Colormap choose_cmap( Display *dpy, XVisualInfo *vi ) } } #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 @@ -198,10 +199,10 @@ QCursor* GLViewer_ViewPort::sketchCursor = 0; */ 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" ) ) ); @@ -297,7 +298,7 @@ void GLViewer_ViewPort::setSketchCursor( const QCursor& newCursor ) Constructor */ GLViewer_ViewPort::GLViewer_ViewPort( QWidget* parent ) -: QWidget( parent, 0, WRepaintNoErase | WResizeNoErase ) +: QWidget( parent, 0 ) { initialize(); } @@ -324,9 +325,9 @@ void GLViewer_ViewPort::initialize() myEnableTransform = true; setMouseTracking( true ); - setBackgroundMode( NoBackground ); + setBackgroundRole( QPalette::NoRole );//NoBackground ); - setFocusPolicy( StrongFocus ); + setFocusPolicy( Qt::StrongFocus ); } /*! @@ -343,9 +344,9 @@ void GLViewer_ViewPort::cleanup() */ 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() ) ); @@ -355,17 +356,17 @@ void GLViewer_ViewPort::selectVisualId( ViewType type ) 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(); @@ -373,16 +374,16 @@ void GLViewer_ViewPort::selectVisualId( ViewType type ) 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 ); } @@ -392,7 +393,7 @@ void GLViewer_ViewPort::selectVisualId( ViewType type ) 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 ); @@ -420,7 +421,7 @@ void GLViewer_ViewPort::selectVisualId( ViewType type ) /* 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() ) @@ -430,7 +431,7 @@ void GLViewer_ViewPort::selectVisualId( ViewType type ) { XFree( (char *)pVisualInfo ); } - XFlush( x11Display() ); + XFlush( QX11Info::display() ); } #endif } @@ -441,7 +442,7 @@ void GLViewer_ViewPort::selectVisualId( ViewType type ) void GLViewer_ViewPort::setBackgroundColor( const QColor& color ) { QPalette pal = palette(); - pal.setColor( QColorGroup::Background, color ); + pal.setColor( QPalette::Background, color ); setPalette( pal ); repaint(); } @@ -451,7 +452,7 @@ void GLViewer_ViewPort::setBackgroundColor( const QColor& color ) */ QColor GLViewer_ViewPort::backgroundColor() const { - return palette().active().background(); + return palette().color( QPalette::Active, QPalette::Background ); } /*! diff --git a/src/GLViewer/GLViewer_ViewPort.h b/src/GLViewer/GLViewer_ViewPort.h index b7ceaf2dc..524f8d3d0 100644 --- a/src/GLViewer/GLViewer_ViewPort.h +++ b/src/GLViewer/GLViewer_ViewPort.h @@ -27,12 +27,12 @@ #include "GLViewer.h" -#include -#include -#include -#include +//#include +#include +//#include +#include -#include +//#include class QRect; class QCursor; @@ -40,7 +40,7 @@ class QPainter; class GLViewer_ViewSketcher; class GLViewer_ViewTransformer; -#ifdef WNT +#ifdef WIN32 #pragma warning( disable:4251 ) #endif @@ -170,7 +170,7 @@ private: static QCursor* sketchCursor; }; -#ifdef WNT +#ifdef WIN32 #pragma warning ( default:4251 ) #endif diff --git a/src/GLViewer/GLViewer_ViewPort2d.cxx b/src/GLViewer/GLViewer_ViewPort2d.cxx index 3055726ec..d80bddadb 100644 --- a/src/GLViewer/GLViewer_ViewPort2d.cxx +++ b/src/GLViewer/GLViewer_ViewPort2d.cxx @@ -28,23 +28,26 @@ #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 - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "GLViewer_Drawer.h" + +// TODO: Porting to Qt4 +//#include + +#include +#include +#include +//#include +//#include +#include +#include +#include +#include +#include +#include #define WIDTH 640 #define HEIGHT 480 @@ -71,7 +74,8 @@ GLViewer_ViewPort2d::GLViewer_ViewPort2d( QWidget* parent, GLViewer_ViewFrame* t 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; @@ -101,10 +105,11 @@ GLViewer_ViewPort2d::GLViewer_ViewPort2d( QWidget* parent, GLViewer_ViewFrame* t 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 ); } @@ -121,6 +126,9 @@ GLViewer_ViewPort2d::~GLViewer_ViewPort2d() delete myBorder; delete myGLWidget; + + if ( myRectBand ) myRectBand->hide(); + delete myRectBand; } /*! @@ -162,17 +170,17 @@ void GLViewer_ViewPort2d::onCutObject() int aObjNum = aContext->NbSelected(); if( aObjNum > 0 ) { - QValueList aObjects; - GLViewer_MimeSource* aMimeSource = new GLViewer_MimeSource(); + QList 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] ); @@ -199,17 +207,17 @@ void GLViewer_ViewPort2d::onCopyObject() int aObjNum = aContext->NbSelected(); if( aObjNum > 0 ) { - QValueList aObjects; - GLViewer_MimeSource* aMimeSource = new GLViewer_MimeSource(); + QList 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 ); } } @@ -251,7 +259,7 @@ void GLViewer_ViewPort2d::onPasteObject() if( aMimeSource->provides( "GLViewer_Objects" ) ) { QByteArray anArray = aMimeSource->encodedData( "GLViewer_Objects" ); - QValueList aObjects = GLViewer_MimeSource::getObjects( anArray, "GLViewer_Objects" ); + QList aObjects = GLViewer_MimeSource::getObjects( anArray, "GLViewer_Objects" ); if( aObjects.empty() ) return; GLViewer_Context* aContext = ((GLViewer_Viewer2d*)getViewFrame()->getViewer())->getGLContext(); @@ -288,7 +296,7 @@ void GLViewer_ViewPort2d::onDragObject( QMouseEvent* e ) //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 ) ) { @@ -302,7 +310,7 @@ void GLViewer_ViewPort2d::onDragObject( QMouseEvent* e ) 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); @@ -328,7 +336,7 @@ void GLViewer_ViewPort2d::mousePressEvent( QMouseEvent* e ) 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 ) ) { @@ -819,7 +827,7 @@ void GLViewer_ViewPort2d::fitAll( bool keepScale, bool withZ ) 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; @@ -1156,6 +1164,14 @@ void GLViewer_ViewPort2d::startSelectByRect( int x, int y ) 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(); } /*! @@ -1166,17 +1182,14 @@ void GLViewer_ViewPort2d::drawSelectByRect( int x, int y ) { 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() ); } } @@ -1189,17 +1202,17 @@ void GLViewer_ViewPort2d::finishSelectByRect() 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; } } @@ -1211,10 +1224,10 @@ QRect GLViewer_ViewPort2d::selectionRect() 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; @@ -1357,9 +1370,9 @@ void GLViewer_ViewPort2d::onMaybeTip( QPoint thePoint, QString& theText, QFont& QStringList aList; if( anObj->isTooTipHTML() ) - aList = QStringList::split( "
", theText ); + aList = theText.split( "
", QString::SkipEmptyParts ); else - aList = QStringList::split( "\n", theText ); + aList = theText.split( "\n", QString::SkipEmptyParts ); if( !aList.isEmpty() ) { diff --git a/src/GLViewer/GLViewer_ViewPort2d.h b/src/GLViewer/GLViewer_ViewPort2d.h index 76b59b6d4..03a4b149f 100644 --- a/src/GLViewer/GLViewer_ViewPort2d.h +++ b/src/GLViewer/GLViewer_ViewPort2d.h @@ -25,7 +25,7 @@ #ifndef GLVIEWER_VIEWPORT2D_H #define GLVIEWER_VIEWPORT2D_H -#ifdef WNT +#ifdef WIN32 #include #endif @@ -36,12 +36,11 @@ #include "GLViewer_Widget.h" #include "GLViewer_Geom.h" -#include -#include -#include -#include +#include +#include +#include -#ifdef WNT +#ifdef WIN32 #pragma warning( disable:4251 ) #endif @@ -51,6 +50,10 @@ class GLViewer_Object; class GLViewer_ViewFrame; class QtxToolTip; + +class QWidget; +class QRubberBand; + /*! * Class GLViewer_ViewPort * 2D visualisation canvas of GLViewer @@ -237,9 +240,11 @@ protected: 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 diff --git a/src/GLViewer/GLViewer_Viewer.cxx b/src/GLViewer/GLViewer_Viewer.cxx index 3363add16..f850eeb41 100644 --- a/src/GLViewer/GLViewer_Viewer.cxx +++ b/src/GLViewer/GLViewer_Viewer.cxx @@ -28,13 +28,17 @@ #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 -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include /* used for sketching */ static QEvent* l_mbPressEvent = 0; @@ -85,12 +89,12 @@ void GLViewer_Viewer::setViewManager(SUIT_ViewManager* theViewManager) /*! 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() ) ); } /*! @@ -389,7 +393,7 @@ void GLViewer_Viewer::onWheelEvent( SUIT_ViewWindow*, QWheelEvent* e ) void GLViewer_Viewer::onSelectionModeChanged() { bool enable = ( mySelMode == Multiple ); - QPtrVector views = getViewManager()->getViews(); + QVector views = getViewManager()->getViews(); for ( int i = 0, n = views.count(); i < n; i++ ) { GLViewer_ViewPort* vp = ((GLViewer_ViewFrame*)views[i])->getViewPort(); @@ -403,7 +407,7 @@ void GLViewer_Viewer::onSelectionModeChanged() */ void GLViewer_Viewer::update( int flags ) { - QPtrVector views = getViewManager()->getViews(); + QVector views = getViewManager()->getViews(); for ( int i = 0, n = views.count(); i < n; i++ ) ((GLViewer_ViewFrame*)views[i])->onUpdate( flags ); } @@ -424,9 +428,9 @@ void GLViewer_Viewer::unhilightDetected() 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() ) @@ -458,7 +462,7 @@ void GLViewer_Viewer::handleMousePress( QMouseEvent* e ) 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() ) @@ -466,7 +470,7 @@ void GLViewer_Viewer::handleMouseMove( QMouseEvent* e ) } /* Try to activate default sketching */ - else if ( e->state() == GLViewer_ViewSketcher::sketchButton() ) + else if ( e->button() == GLViewer_ViewSketcher::sketchButton() ) { activateSketching( Rect ); if ( mySketcher ) @@ -495,11 +499,11 @@ void GLViewer_Viewer::handleMouseRelease( QMouseEvent* e ) { /* 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 ); } } @@ -526,7 +530,7 @@ int GLViewer_ViewTransformer::panBtn = Qt::MidButton; 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 @@ -535,8 +539,9 @@ GLViewer_ViewTransformer::GLViewer_ViewTransformer( GLViewer_Viewer* v, int type : 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 || @@ -563,6 +568,8 @@ GLViewer_ViewTransformer::~GLViewer_ViewTransformer() } //QAD_Application::getDesktop()->clearInfo(); + + endDrawRect(); } /*! @@ -645,11 +652,11 @@ bool GLViewer_ViewTransformer::eventFilter( QObject* o, QEvent* e ) 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; @@ -704,8 +711,8 @@ void GLViewer_ViewTransformer::onTransform( TransformState state ) { 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 ) @@ -715,13 +722,7 @@ void GLViewer_ViewTransformer::onTransform( TransformState 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; } } @@ -737,6 +738,34 @@ void GLViewer_ViewTransformer::onTransform( TransformState state ) 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 ] */ @@ -746,7 +775,7 @@ int GLViewer_ViewTransformer::type() const } -int GLViewer_ViewSketcher::sketchBtn = LeftButton; +int GLViewer_ViewSketcher::sketchBtn = Qt::LeftButton; /*! Constructor @@ -755,7 +784,8 @@ GLViewer_ViewSketcher::GLViewer_ViewSketcher( GLViewer_Viewer* viewer, int type : QObject( 0 ), myViewer( viewer ), myData( 0 ), -myType( type ) +myType( type ), +myRectBand( 0 ) { if( !myViewer ) return; @@ -782,6 +812,8 @@ GLViewer_ViewSketcher::~GLViewer_ViewSketcher() if ( myType == GLViewer_Viewer::Rect ) delete ( QRect* ) myData; + + endDrawRect(); } /*! @@ -798,7 +830,7 @@ bool GLViewer_ViewSketcher::eventFilter( QObject* o, QEvent* e ) SketchState state = EnTrain; QMouseEvent* me = (QMouseEvent*)e; - myButtonState = me->state(); + myButtonState = me->modifiers(); if ( e->type() == QEvent::MouseButtonPress ) myButtonState |= me->button(); /* add pressed button */ @@ -808,7 +840,7 @@ bool GLViewer_ViewSketcher::eventFilter( QObject* o, QEvent* e ) 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; @@ -836,18 +868,15 @@ void GLViewer_ViewSketcher::onSketch( SketchState state ) 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 ); } } } @@ -858,3 +887,31 @@ void GLViewer_ViewSketcher::onSketch( SketchState state ) 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; +} diff --git a/src/GLViewer/GLViewer_Viewer.h b/src/GLViewer/GLViewer_Viewer.h index 0d68a450d..c12d5f901 100644 --- a/src/GLViewer/GLViewer_Viewer.h +++ b/src/GLViewer/GLViewer_Viewer.h @@ -25,23 +25,28 @@ #ifndef GLVIEWER_VIEWER_H #define GLVIEWER_VIEWER_H +#include "GLViewer.h" #include "GLViewer_Defs.h" -#include "GLViewer_ViewFrame.h" #include -#include -#include -#include -#include +#include +#include + +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 @@ -68,7 +73,7 @@ public: virtual QString getType() const { return Type(); } static QString Type() { return "GLViewer_ViewModel"; } - virtual void contextMenuPopup( QPopupMenu* ); + virtual void contextMenuPopup( QMenu* ); public: void setSelectionMode( SelectionMode ); @@ -166,6 +171,9 @@ protected: virtual void onTransform( TransformState ); void initTransform( bool ); + void drawRect(const QRect& theRect); + void endDrawRect(); + protected: static int panBtn; static int zoomBtn; @@ -180,8 +188,9 @@ protected: bool mySavedMouseTrack; QPoint myStart, myCurr; int myButtonState; - QRect myDrawRect; int myMajorBtn; + + QRubberBand* myRectBand; //!< selection rectangle rubber band }; class GLVIEWER_API GLViewer_ViewSketcher : public QObject @@ -210,6 +219,9 @@ protected: enum SketchState { Debut, EnTrain, Fin }; virtual void onSketch( SketchState ); + void drawRect(const QRect& theRect); + void endDrawRect(); + protected: static int sketchBtn; GLViewer_Viewer* myViewer; @@ -218,9 +230,11 @@ protected: QCursor mySavedCursor; QPoint myStart, myCurr; int myButtonState; + + QRubberBand* myRectBand; //!< selection rectangle rubber band }; -#ifdef WNT +#ifdef WIN32 #pragma warning ( default:4251 ) #endif diff --git a/src/GLViewer/GLViewer_Viewer2d.cxx b/src/GLViewer/GLViewer_Viewer2d.cxx index 7d03218ba..3a51f5c89 100644 --- a/src/GLViewer/GLViewer_Viewer2d.cxx +++ b/src/GLViewer/GLViewer_Viewer2d.cxx @@ -25,6 +25,7 @@ //#include #include "GLViewer_Viewer2d.h" #include "GLViewer_Object.h" +#include "GLViewer_ViewFrame.h" #include "GLViewer_BaseObjects.h" #include "GLViewer_CoordSystem.h" #include "GLViewer_Context.h" @@ -35,13 +36,14 @@ #include "SUIT_Desktop.h" #include "SUIT_ViewWindow.h" +#include "SUIT_ViewManager.h" -#include "OSD_Timer.hxx" -#include - -#include -#include -#include +#include +#include +#include +#include +#include +#include /*! Constructor @@ -83,14 +85,14 @@ SUIT_ViewWindow* GLViewer_Viewer2d::createView( SUIT_Desktop* theDesktop ) 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() ) ); } } @@ -145,15 +147,15 @@ void GLViewer_Viewer2d::updateColors( QColor colorH, QColor colorS ) */ void GLViewer_Viewer2d::updateBorders( GLViewer_Rect* theRect ) { - QPtrVector views = getViewManager()->getViews(); + QVector 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() ) ); } } @@ -162,7 +164,7 @@ void GLViewer_Viewer2d::updateBorders( GLViewer_Rect* theRect ) */ void GLViewer_Viewer2d::updateBorders() { - QPtrVector views = getViewManager()->getViews(); + QVector views = getViewManager()->getViews(); ObjList anObjects = myGLContext->getObjects(); ObjList::Iterator beginIt = anObjects.begin(); @@ -189,10 +191,10 @@ void GLViewer_Viewer2d::updateBorders() } 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() ) ); } } } @@ -206,7 +208,7 @@ void GLViewer_Viewer2d::updateAll() if ( !getActiveView() ) return; - QPtrVector views = getViewManager()->getViews(); + QVector views = getViewManager()->getViews(); for ( int i = 0, n = views.count(); i < n; i++ ) ( ( GLViewer_ViewPort2d* )( ( GLViewer_ViewFrame* )views[i] )->getViewPort() )->getGLWidget()->updateGL(); } @@ -226,18 +228,18 @@ void GLViewer_Viewer2d::updateDrawers( GLboolean update, GLfloat scX, GLfloat sc /*! Activates drawers for objects from list \param theObjects only */ -void GLViewer_Viewer2d::activateDrawers( QValueList& theObjects, bool onlyUpdate, GLboolean swap ) +void GLViewer_Viewer2d::activateDrawers( QList& theObjects, bool onlyUpdate, GLboolean swap ) { //cout << "GLViewer_Viewer2d::activateDrawers " << (int)onlyUpdate << " " << (int)swap << endl; - QValueList::Iterator anIt = myDrawers.begin(); - QValueList::Iterator endDIt = myDrawers.end(); + QList::Iterator anIt = myDrawers.begin(); + QList::Iterator endDIt = myDrawers.end(); for( ; anIt != endDIt; anIt++ ) (*anIt)->clear(); - QValueList anActiveDrawers; - QValueList::Iterator endOIt = theObjects.end(); + QList anActiveDrawers; + QList::Iterator endOIt = theObjects.end(); - for( QValueList::Iterator oit = theObjects.begin(); oit != endOIt; ++oit ) + for( QList::Iterator oit = theObjects.begin(); oit != endOIt; ++oit ) { GLViewer_Drawer* aDrawer = (*oit)->getDrawer(); if( !aDrawer ) @@ -265,11 +267,11 @@ void GLViewer_Viewer2d::activateDrawers( QValueList& theObject int aPriority = aDrawer->getPriority(); - if( anActiveDrawers.findIndex( aDrawer ) != -1 ) + if( anActiveDrawers.indexOf( aDrawer ) != -1 ) continue; - QValueList::Iterator aDIt = anActiveDrawers.begin(); - QValueList::Iterator aDEndIt = anActiveDrawers.end(); + QList::Iterator aDIt = anActiveDrawers.begin(); + QList::Iterator aDEndIt = anActiveDrawers.end(); for( ; aDIt != aDEndIt; ++aDIt ) if( (*aDIt)->getPriority() > aPriority ) break; @@ -277,10 +279,10 @@ void GLViewer_Viewer2d::activateDrawers( QValueList& theObject anActiveDrawers.insert( aDIt, aDrawer ); } - QValueList::Iterator aDIt = anActiveDrawers.begin(); - QValueList::Iterator aDEndIt = anActiveDrawers.end(); + QList::Iterator aDIt = anActiveDrawers.begin(); + QList::Iterator aDEndIt = anActiveDrawers.end(); - QPtrVector views = getViewManager()->getViews(); + QVector views = getViewManager()->getViews(); for ( int i = 0, n = views.count(); i < n; i++ ) { float xScale, yScale; @@ -523,7 +525,7 @@ QRect* GLViewer_Viewer2d::getWinObjectRect( GLViewer_Object* theObject ) 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)), @@ -539,10 +541,10 @@ QRect* GLViewer_Viewer2d::getWinObjectRect( GLViewer_Object* theObject ) { 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; @@ -640,7 +642,7 @@ bool GLViewer_Viewer2d::testRotation( QMouseEvent* e ) { 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; @@ -667,7 +669,7 @@ void GLViewer_Viewer2d::insertHeader( VectorFileType aType, QFile& hFile ) header += "%%Pages: 1\n"; header += "%%Page: 1\n\n"; - hFile.writeBlock( header.ascii(), header.length() ); + hFile.write( header.toAscii() ); } else if( aType == HPGL ) { @@ -681,7 +683,7 @@ void GLViewer_Viewer2d::insertHeader( VectorFileType aType, QFile& hFile ) header += "LT;\n"; header += "VS36;\n"; - hFile.writeBlock( header.ascii(), header.length() ); + hFile.write( header.toAscii() ); } } @@ -695,12 +697,12 @@ void GLViewer_Viewer2d::insertEnding( VectorFileType aType, QFile& hFile ) 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() ); } } @@ -730,7 +732,7 @@ bool GLViewer_Viewer2d::translateTo( VectorFileType aType, QString FileName, Pap if ( !getActiveView() ) return false; - QFile hFile( FileName.ascii() ); + QFile hFile( FileName.toAscii() ); #ifdef WIN32 HDC hMetaFileDC; @@ -779,8 +781,8 @@ bool GLViewer_Viewer2d::translateTo( VectorFileType aType, QString FileName, Pap 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 @@ -792,7 +794,7 @@ bool GLViewer_Viewer2d::translateTo( VectorFileType aType, QString FileName, Pap 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 ); @@ -818,7 +820,7 @@ bool GLViewer_Viewer2d::translateTo( VectorFileType aType, QString FileName, Pap 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 ); } @@ -874,15 +876,15 @@ void GLViewer_Viewer2d::repaintView( GLViewer_ViewFrame* theView, bool makeCurre float xScale; float yScale; - QValueList::Iterator anIt = myDrawers.begin(); - QValueList::Iterator endDIt = myDrawers.end(); + QList::Iterator anIt = myDrawers.begin(); + QList::Iterator endDIt = myDrawers.end(); for( ; anIt != endDIt; anIt++ ) (*anIt)->clear(); - QValueList anActiveDrawers; - QValueList::Iterator endOIt = anActiveObjs.end(); + QList anActiveDrawers; + QList::Iterator endOIt = anActiveObjs.end(); - for( QValueList::Iterator oit = anActiveObjs.begin(); oit != endOIt; ++oit ) + for( QList::Iterator oit = anActiveObjs.begin(); oit != endOIt; ++oit ) { GLViewer_Drawer* aDrawer = (*oit)->getDrawer(); if( !aDrawer ) @@ -904,12 +906,12 @@ void GLViewer_Viewer2d::repaintView( GLViewer_ViewFrame* theView, bool makeCurre } } aDrawer->addObject( (*oit) ); - if( anActiveDrawers.findIndex( aDrawer ) == -1 ) + if( anActiveDrawers.indexOf( aDrawer ) == -1 ) anActiveDrawers.append( aDrawer ); } - QValueList::Iterator aDIt = anActiveDrawers.begin(); - QValueList::Iterator aDEndIt = anActiveDrawers.end(); + QList::Iterator aDIt = anActiveDrawers.begin(); + QList::Iterator aDEndIt = anActiveDrawers.end(); GLViewer_ViewPort2d* vp = ( GLViewer_ViewPort2d* )aCurView->getViewPort(); vp->getScale( xScale, yScale ); @@ -991,7 +993,7 @@ void GLViewer_Viewer2d::finishOperations( QMouseEvent* e ) 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 ); } } @@ -1017,7 +1019,7 @@ void GLViewer_Viewer2d::startOperations( QWheelEvent* e ) } -int GLViewer_View2dTransformer::rotateBtn = RightButton; +int GLViewer_View2dTransformer::rotateBtn = Qt::RightButton; /*! Constructor diff --git a/src/GLViewer/GLViewer_Viewer2d.h b/src/GLViewer/GLViewer_Viewer2d.h index 93c9d30f0..b31a4430a 100644 --- a/src/GLViewer/GLViewer_Viewer2d.h +++ b/src/GLViewer/GLViewer_Viewer2d.h @@ -25,25 +25,24 @@ #ifndef GLVIEWER_VIEWER2D_H #define GLVIEWER_VIEWER2D_H -#ifdef WNT +#ifdef WIN32 #include #endif -#include -#include +class QRect; +class QFile; #include "GLViewer_Viewer.h" -#include "GLViewer_Object.h" -#include "GLViewer_ViewFrame.h" -#include "GLViewer_Drawer.h" #include #include class GLViewer_Object; +class GLViewer_ViewFrame; +class GLViewer_Drawer; class GLViewer_Context; -class GLViewer_Selector2d; +class GLViewer_Rect; //class GLViewer_Sketcher; class SUIT_Desktop; @@ -58,7 +57,7 @@ const double Sizes[2*5] = { /* A5 */ 148.5, 210.0 }; -#ifdef WNT +#ifdef WIN32 #pragma warning( disable:4251 ) #endif @@ -115,12 +114,12 @@ public: 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& getDrawers() const { return myDrawers; } + const QList& getDrawers() const { return myDrawers; } //! Returns context GLViewer_Context* getGLContext() const { return myGLContext; } @@ -138,7 +137,7 @@ public: /* \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& theObjects, bool onlyUpdate, GLboolean swap = GL_FALSE ); + void activateDrawers( QList& 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 @@ -224,7 +223,7 @@ protected: //! Current context GLViewer_Context* myGLContext; //! Map of active drawers - QValueList myDrawers; + QList myDrawers; //GLViewer_Sketcher* myGLSketcher; }; @@ -247,7 +246,7 @@ protected: static int rotateBtn; }; -#ifdef WNT +#ifdef WIN32 #pragma warning ( default:4251 ) #endif diff --git a/src/GLViewer/GLViewer_Widget.cxx b/src/GLViewer/GLViewer_Widget.cxx index 1fc069d20..5ad81e29c 100644 --- a/src/GLViewer/GLViewer_Widget.cxx +++ b/src/GLViewer/GLViewer_Widget.cxx @@ -25,24 +25,27 @@ #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 using namespace std; -#include -#include +#include +#include +#include -#include -#include -#include -#include -#include -#include -#include +#include +//#include +#include +#include +//#include +//#include +//#include +#include /*! A constructor @@ -248,7 +251,8 @@ void GLViewer_Widget::setBackground( QString filename ) void GLViewer_Widget::addToolTip( QString theString, QRect theRect ) { myToolTipRect = theRect; - QToolTip::add( this, myToolTipRect, theString ); + setToolTip(theString); + //QToolTip::add( this, myToolTipRect, theString ); } /*! @@ -256,7 +260,8 @@ void GLViewer_Widget::addToolTip( QString theString, QRect theRect ) */ void GLViewer_Widget::removeToolTip() { - QToolTip::remove( this, myToolTipRect ); + setToolTip(""); + //QToolTip::remove( this, myToolTipRect ); } /*! @@ -419,6 +424,18 @@ void GLViewer_Widget::leaveEvent( QEvent* e ) updateGL(); } +/*! + Custom leave event handler +*/ +bool GLViewer_Widget::event ( QEvent* e ) +{ + if (e->type() == QEvent::ToolTip) { + QHelpEvent *helpEvent = static_cast(e); + if ( myToolTipRect.contains(helpEvent->pos()) ) + QToolTip::showText(helpEvent->globalPos(), toolTip()); + } + return QGLWidget::event(e); +} /*! \return the hex code of digit < 16 @@ -488,7 +505,7 @@ void AddImagePart( QFile& hFile, QImage& image, int w1, int w2, int h1, int h2, aBuffer += "> false 3 colorimage\n\n"; - hFile.writeBlock( aBuffer.ascii(), aBuffer.length() ); + hFile.write( aBuffer.toAscii() ); } } @@ -548,7 +565,7 @@ void GLViewer_Widget::translateBackgroundToPS( QFile& hFile, GLViewer_CoordSyste 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) ); } } diff --git a/src/GLViewer/GLViewer_Widget.h b/src/GLViewer/GLViewer_Widget.h index 637beb5fb..c1edf7efe 100644 --- a/src/GLViewer/GLViewer_Widget.h +++ b/src/GLViewer/GLViewer_Widget.h @@ -27,8 +27,9 @@ #include "GLViewer.h" -#include -#include +#include + +class QFile; class GLViewer_ViewPort2d; class GLViewer_CoordSystem; @@ -153,6 +154,8 @@ protected: 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 diff --git a/src/GLViewer/Makefile.am b/src/GLViewer/Makefile.am index e20fde4eb..ad2589024 100644 --- a/src/GLViewer/Makefile.am +++ b/src/GLViewer/Makefile.am @@ -38,7 +38,7 @@ salomeinclude_HEADERS= \ GLViewer_Geom.h \ GLViewer_Grid.h \ GLViewer_Group.h \ - GLViewer_MimeSource.h \ + GLViewer_MimeData.h \ GLViewer_Object.h \ GLViewer_Selector.h \ GLViewer_Selector2d.h \ @@ -64,7 +64,7 @@ dist_libGLViewer_la_SOURCES= \ GLViewer_Geom.cxx \ GLViewer_Grid.cxx \ GLViewer_Group.cxx \ - GLViewer_MimeSource.cxx \ + GLViewer_MimeData.cxx \ GLViewer_Object.cxx \ GLViewer_Selector.cxx \ GLViewer_Selector2d.cxx \ diff --git a/src/GLViewer/resources/GLViewer_images.ts b/src/GLViewer/resources/GLViewer_images.ts new file mode 100644 index 000000000..6eae54237 --- /dev/null +++ b/src/GLViewer/resources/GLViewer_images.ts @@ -0,0 +1,49 @@ + + + @default + + ICON_GL_DUMP + view_dump.png + + + ICON_GL_ZOOM + view_zoom.png + + + ICON_GL_PAN + view_pan.png + + + ICON_GL_GLOBALPAN + view_glpan.png + + + ICON_GL_CURSOR_ROTATE + cursor_rotate.png + + + ICON_GL_CURSOR_SKETCH + cursor_sketch.png + + + ICON_GL_CURSOR_ZOOM + cursor_zoom.png + + + ICON_GL_FITALL + view_fitall.png + + + ICON_GL_FITSELECT + view_fitselect.png + + + ICON_GL_RESET + view_reset.png + + + ICON_GL_FITAREA + view_fitarea.png + + + diff --git a/src/GLViewer/resources/GLViewer_msg_en.ts b/src/GLViewer/resources/GLViewer_msg_en.ts new file mode 100644 index 000000000..6330838e8 --- /dev/null +++ b/src/GLViewer/resources/GLViewer_msg_en.ts @@ -0,0 +1,115 @@ + + + @default + + DSC_FITSELECT + Fit area of selection within the view frame + + + ERROR + Error + + + MNU_DUMP_VIEW + Dump + + + MNU_PAN_VIEW + Panning + + + DSC_GLOBALPAN_VIEW + Selection of a new center of the view + + + MNU_ZOOM_VIEW + Zoom + + + DSC_PAN_VIEW + Panning the view + + + DSC_FITALL + Fit all objects inside the view frame + + + MNU_FITALL + Fit All + + + MNU_GLOBALPAN_VIEW + Global Panning + + + INF_APP_DUMP_VIEW + Dump view + + + GL_IMAGE_FILES + Images Files (*.bmp *.png) + + + MNU_RESET_VIEW + Reset + + + DSC_FITRECT + Fit area within the view frame + + + MNU_FITRECT + Fit Area + + + CHANGE_BGCOLOR + Change background... + + + DSC_DUMP_VIEW + Saves the active view in the image file + + + MNU_FITSELECT + Fit Selection + + + DSC_ZOOM_VIEW + Zoom the view + + + DSC_RESET_VIEW + Reset View Point + + + ERR_DOC_CANT_SAVE_FILE + Cannot save file + + + LBL_TOOLBAR_LABEL + View Operations + + + + GLViewer_ViewFrame + + DUMP_VIEW_SAVE_FILE_DLG_CAPTION + Save Dump View in file + + + DUMP_VIEW_ERROR_DLG_TEXT + Can't save Dump View in file + + + DUMP_VIEW_ERROR_DLG_CAPTION + Error + + + + GLViewer_ViewManager + + GL_VIEW_TITLE + GL Scene:%M - viewer:%V + + + diff --git a/src/LightApp/LightApp.h b/src/LightApp/LightApp.h index 0fbeb1497..3282621bd 100644 --- a/src/LightApp/LightApp.h +++ b/src/LightApp/LightApp.h @@ -27,7 +27,7 @@ // 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) @@ -41,6 +41,6 @@ #else #define LIGHTAPP_EXPORT -#endif //WNT +#endif //WIN32 #define APP_VERSION "0.1" diff --git a/src/LightApp/LightApp.pro b/src/LightApp/LightApp.pro new file mode 100644 index 000000000..aa420964d --- /dev/null +++ b/src/LightApp/LightApp.pro @@ -0,0 +1,233 @@ +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 diff --git a/src/LightApp/LightApp_AboutDlg.cxx b/src/LightApp/LightApp_AboutDlg.cxx index 7dc4a48ae..1ab621df7 100644 --- a/src/LightApp/LightApp_AboutDlg.cxx +++ b/src/LightApp/LightApp_AboutDlg.cxx @@ -26,31 +26,41 @@ #include #include -#include -#include -#include -#include +#include + +#include +#include +#include +#include +#include /*!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 ); @@ -99,7 +109,7 @@ LightApp_AboutDlg::LightApp_AboutDlg( const QString& defName, const QString& def QString capText = tr( "ABOUT_CAPTION" ); if ( capText.contains( "%1" ) ) capText = capText.arg( defName ); - setCaption( capText ); + setWindowTitle( capText ); setSizeGripEnabled( false ); } @@ -142,7 +152,7 @@ void LightApp_AboutDlg::checkLabel( QLabel* lab ) const 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(); } diff --git a/src/LightApp/LightApp_Application.cxx b/src/LightApp/LightApp_Application.cxx index e570efc00..7f29c1cd7 100644 --- a/src/LightApp/LightApp_Application.cxx +++ b/src/LightApp/LightApp_Application.cxx @@ -22,8 +22,8 @@ // Copyright (C) CEA 2005 #ifndef DISABLE_PYCONSOLE - #include "PythonConsole_PyInterp.h" // WARNING! This include must be the first! - #include + #include // WARNING! This include must be the first! + #include #endif #include "LightApp_Application.h" @@ -35,8 +35,10 @@ #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" @@ -44,6 +46,8 @@ #include "LightApp_SelectionMgr.h" #include "LightApp_DataObject.h" +#include + #include #include #include @@ -55,15 +59,17 @@ #include #include #include +#include #include #include #include -#include +#include #include -#include -#include +// temporary commented +//#include +//#include #ifndef DISABLE_GLVIEWER #include @@ -115,29 +121,31 @@ #include #endif -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace Qt; #define FIRST_HELP_ID 1000000 #ifndef DISABLE_SALOMEOBJECT - #include "SALOME_InteractiveObject.hxx" - #include "SALOME_ListIO.hxx" + #include + #include #endif static const char* imageEmptyIcon[] = { @@ -200,14 +208,14 @@ myPrefs( 0 ) 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(); @@ -264,7 +272,7 @@ myPrefs( 0 ) 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 ) { @@ -292,20 +300,22 @@ LightApp_Application::~LightApp_Application() /*!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(); } @@ -336,10 +346,9 @@ QString LightApp_Application::applicationVersion() const 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() ) @@ -347,9 +356,9 @@ QString LightApp_Application::applicationVersion() const 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(); } } } @@ -429,9 +438,9 @@ void LightApp_Application::createActionForViewer( const int id, 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 ); } @@ -445,7 +454,7 @@ void LightApp_Application::createActions() 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() ) ); @@ -459,33 +468,35 @@ void LightApp_Application::createActions() 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++; } @@ -499,16 +510,17 @@ void LightApp_Application::createActions() 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++; } @@ -536,34 +548,17 @@ void LightApp_Application::createActions() 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 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 ) ) @@ -580,21 +575,16 @@ void LightApp_Application::createActions() { 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 @@ -620,7 +610,7 @@ void LightApp_Application::createActions() #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 ); @@ -636,15 +626,8 @@ void LightApp_Application::createActions() } /*!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 iconMap; moduleIconNames( iconMap ); @@ -670,7 +653,7 @@ void LightApp_Application::onModuleActivation( QAction* a ) case 0: default: putInfo( tr("INF_CANCELLED") ); - myActions[QString()]->setOn( true ); + myModuleAction->setActiveModule( QString() ); cancelled = true; } } @@ -766,8 +749,6 @@ void LightApp_Application::onOpenDoc() } } -#include "SUIT_MessageBox.h" - /*! SLOT: Opens new document. \param aName - name of file @@ -779,20 +760,22 @@ bool LightApp_Application::onOpenDoc( const QString& aName ) // Look among opened studies if (activeStudy()) { // at least one study is opened SUIT_Session* aSession = SUIT_Session::session(); - QPtrList aAppList = aSession->applications(); - QPtrListIterator it (aAppList); + QList aAppList = aSession->applications(); + QListIterator 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); @@ -955,19 +938,19 @@ public: 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 ); } } } @@ -987,16 +970,16 @@ void LightApp_Application::onHelpContentsModule() { 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 @@ -1017,9 +1000,10 @@ void LightApp_Application::onHelpContentsModule() 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(); } } @@ -1029,10 +1013,10 @@ void LightApp_Application::onHelpContentsModule() */ 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 @@ -1053,9 +1037,10 @@ void LightApp_Application::onHelpContextModule(const QString& theComponentName, 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(); } } @@ -1123,25 +1108,28 @@ void LightApp_Application::addWindow( QWidget* wid, const int flag, const int st // 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 ); } } @@ -1208,8 +1196,9 @@ bool LightApp_Application::isWindowVisible( const int type ) const 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; } @@ -1224,11 +1213,11 @@ void LightApp_Application::setWindowShown( const int type, const bool on ) 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; @@ -1238,14 +1227,15 @@ void LightApp_Application::setWindowShown( const int type, const bool on ) /*! \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 @@ -1263,12 +1253,12 @@ LogWindow* LightApp_Application::logWindow() /*! \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 @@ -1282,29 +1272,33 @@ void LightApp_Application::updateObjectBrowser( const bool updateModels ) // 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(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 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 ); - } + }*/ } /*! @@ -1468,13 +1462,15 @@ void LightApp_Application::onStudyCreated( SUIT_Study* theStudy ) //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(); } @@ -1492,13 +1488,15 @@ void LightApp_Application::onStudyOpened( SUIT_Study* theStudy ) //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(); @@ -1553,7 +1551,7 @@ QString LightApp_Application::getFileName( bool open, const QString& initial, co { 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 ); } @@ -1571,7 +1569,7 @@ QStringList LightApp_Application::getOpenFileNames( const QString& initial, cons { 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 ); } @@ -1584,7 +1582,7 @@ void LightApp_Application::onRefresh() /*!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()); @@ -1595,7 +1593,7 @@ void LightApp_Application::onPreferences() if ( ( prefDlg->exec() == QDialog::Accepted || prefDlg->isSaved() ) && resourceMgr() ) { if ( desktop() ) - desktop()->saveGeometry( resourceMgr(), "desktop" ); + resourceMgr()->setValue( "desktop", "geometry", desktop()->storeGeometry() ); resourceMgr()->save(); } @@ -1663,7 +1661,8 @@ QWidget* LightApp_Application::createWindow( const int flag ) 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" ) ); @@ -1681,12 +1680,13 @@ QWidget* LightApp_Application::createWindow( const int flag ) 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* ) ) ); } @@ -1694,7 +1694,7 @@ QWidget* LightApp_Application::createWindow( const int flag ) 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* ) ) ); } @@ -1707,9 +1707,9 @@ QWidget* LightApp_Application::createWindow( const int flag ) */ void LightApp_Application::defaultWindows( QMap& 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 ); } @@ -1740,13 +1740,15 @@ LightApp_Preferences* LightApp_Application::preferences( const bool crt ) const that->myPrefs = _prefs_; - QPtrList appList = SUIT_Session::session()->applications(); - for ( QPtrListIterator appIt ( appList ); appIt.current(); ++appIt ) + QList appList = SUIT_Session::session()->applications(); + QListIterator 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 ); @@ -1758,16 +1760,19 @@ LightApp_Preferences* LightApp_Application::preferences( const bool crt ) const ModuleList modList; app->modules( modList ); - for ( ModuleListIterator itr( modList ); itr.current(); ++itr ) + QListIterator 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(); } @@ -1794,7 +1799,7 @@ void LightApp_Application::moduleAdded( CAM_Module* mod ) 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(); } } @@ -1827,7 +1832,7 @@ void LightApp_Application::createPreferences( LightApp_Preferences* pref ) #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" ); @@ -1889,7 +1894,7 @@ void LightApp_Application::createPreferences( LightApp_Preferences* pref ) aLegendPosList.append( tr("PREF_TOP") ); aLegendPosList.append( tr("PREF_BOTTOM") ); - QValueList anIndexesList; + QList anIndexesList; anIndexesList.append(0); anIndexesList.append(1); anIndexesList.append(2); @@ -1978,11 +1983,12 @@ void LightApp_Application::preferencesChanged( const QString& sec, const QString if ( sec == QString( "OCCViewer" ) && param == QString( "trihedron_size" ) ) { double sz = resMgr->doubleValue( sec, param, -1 ); - QPtrList lst; + QList lst; viewManagers( OCCViewer_Viewer::Type(), lst ); - for ( QPtrListIterator it( lst ); it.current() && sz >= 0; ++it ) + QListIterator 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; @@ -1998,12 +2004,13 @@ void LightApp_Application::preferencesChanged( const QString& sec, const QString { double sz = resMgr->doubleValue( "VTKViewer", "trihedron_size", -1 ); bool isRelative = resMgr->booleanValue( "VTKViewer", "relative_size", true ); - QPtrList lst; + QList lst; #ifndef DISABLE_SALOMEOBJECT viewManagers( SVTK_Viewer::Type(), lst ); - for ( QPtrListIterator it( lst ); it.current() && sz >= 0; ++it ) + QListIterator 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; @@ -2021,13 +2028,14 @@ void LightApp_Application::preferencesChanged( const QString& sec, const QString #ifndef DISABLE_OCCVIEWER if ( sec == QString( "OCCViewer" ) && ( param == QString( "iso_number_u" ) || param == QString( "iso_number_v" ) ) ) { - QPtrList lst; + QList lst; viewManagers( OCCViewer_Viewer::Type(), lst ); int u = resMgr->integerValue( sec, "iso_number_u" ); int v = resMgr->integerValue( sec, "iso_number_v" ); - for ( QPtrListIterator it( lst ); it.current(); ++it ) + QListIterator it( lst ); + while ( it.hasNext() ) { - OCCViewer_ViewManager* mgr = dynamic_cast( it.current() ); + OCCViewer_ViewManager* mgr = dynamic_cast( it.next() ); if( mgr && mgr->getOCCViewer() ) mgr->getOCCViewer()->setIsos( u, v ); } @@ -2038,7 +2046,8 @@ void LightApp_Application::preferencesChanged( const QString& sec, const QString { if( param=="auto_size" || param=="auto_size_first" ) { - OB_Browser* ob = objectBrowser(); + // temporary commented + /*OB_Browser* ob = objectBrowser(); if( !ob ) return; @@ -2050,7 +2059,7 @@ void LightApp_Application::preferencesChanged( const QString& sec, const QString for( int i=1; ilistView()->columns(); i++ ) if( ob->listView()->columnWidth( i )>0 ) ob->listView()->adjustColumn( i ); - updateObjectBrowser( false ); + updateObjectBrowser( false );*/ } } @@ -2080,7 +2089,7 @@ void LightApp_Application::savePreferences() if ( resourceMgr() ) { if ( desktop() ) - desktop()->saveGeometry( resourceMgr(), "desktop" ); + resourceMgr()->setValue( "desktop", "geometry", desktop()->storeGeometry() ); resourceMgr()->save(); } } @@ -2095,11 +2104,11 @@ void LightApp_Application::updateDesktopTitle() { 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 ); } /*! @@ -2121,8 +2130,7 @@ void LightApp_Application::updateModuleActions() if ( activeModule() ) modName = activeModule()->moduleName(); - if ( myActions.contains( modName ) ) - myActions[modName]->setOn( true ); + myModuleAction->setActiveModule( modName ); } /*! @@ -2169,11 +2177,13 @@ void LightApp_Application::updateWindows() for ( QMap::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(); @@ -2187,7 +2197,7 @@ void LightApp_Application::updateWindows() !myWindowsVisible[ itr.key() ] ) continue; - setWindowShown( itr.key(), !itr.data()->isEmpty() && winMap.contains( itr.key() ) ); + setWindowShown( itr.key(), !itr.value()->isEmpty() && winMap.contains( itr.key() ) ); } } @@ -2212,25 +2222,11 @@ void LightApp_Application::loadWindowsGeometry() 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() ); } /*! @@ -2242,25 +2238,11 @@ void LightApp_Application::saveWindowsGeometry() 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() ); } /*! @@ -2271,7 +2253,7 @@ void LightApp_Application::activateWindows() if ( activeStudy() ) { for ( WindowMap::Iterator itr = myWindows.begin(); itr != myWindows.end(); ++itr ) - itr.data()->activate( activeStudy()->id() ); + itr.value()->activate( activeStudy()->id() ); } } @@ -2308,16 +2290,17 @@ void LightApp_Application::moduleIconNames( QMap& iconMap ) co /*! 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() ) ); } /*! @@ -2326,8 +2309,9 @@ void LightApp_Application::contextMenuPopup( const QString& type, QPopupMenu* th void LightApp_Application::createEmptyStudy() { CAM_Application::createEmptyStudy(); - if ( objectBrowser() ) - objectBrowser()->updateTree(); + // temporary commented + /*if ( objectBrowser() ) + objectBrowser()->updateTree();*/ } /*! @@ -2337,8 +2321,9 @@ void LightApp_Application::createEmptyStudy() 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; } @@ -2358,7 +2343,7 @@ void LightApp_Application::onWCDestroyed( QObject* ob ) // 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(); @@ -2401,9 +2386,9 @@ void LightApp_Application::onRenameWindow() 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 ); } /*! @@ -2422,9 +2407,9 @@ bool LightApp_Application::isLibExists( const QString& moduleTitle ) const 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; @@ -2443,7 +2428,7 @@ bool LightApp_Application::isLibExists( const QString& moduleTitle ) const 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" ); } @@ -2457,9 +2442,9 @@ bool LightApp_Application::isLibExists( const QString& moduleTitle ) const // 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(); @@ -2479,11 +2464,11 @@ bool LightApp_Application::isLibExists( const QString& moduleTitle ) const } 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; } @@ -2513,7 +2498,7 @@ void LightApp_Application::onVisibilityChanged( bool visible ) 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; @@ -2527,11 +2512,12 @@ bool LightApp_Application::event( QEvent* e ) { 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; diff --git a/src/LightApp/LightApp_Application.h b/src/LightApp/LightApp_Application.h index 9bbecfed7..2e7a29e3c 100644 --- a/src/LightApp/LightApp_Application.h +++ b/src/LightApp/LightApp_Application.h @@ -32,15 +32,16 @@ #include 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; @@ -48,7 +49,7 @@ class CAM_Module; class QString; class QWidget; class QStringList; -class QPixmap; +//class QPixmap; #ifdef WIN32 #pragma warning( disable:4251 ) @@ -111,9 +112,9 @@ public: 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 ); @@ -145,7 +146,7 @@ public: virtual void start(); - virtual void contextMenuPopup( const QString&, QPopupMenu*, QString& ); + virtual void contextMenuPopup( const QString&, QMenu*, QString& ); virtual void createEmptyStudy(); @@ -204,7 +205,7 @@ protected slots: virtual void onDesktopActivated(); void onNewWindow(); - void onModuleActivation( QAction* ); + void onModuleActivation( const QString& ); void onCloseView( SUIT_ViewManager* ); void onStudyCreated( SUIT_Study* ); @@ -242,14 +243,13 @@ protected: bool isLibExists( const QString& ) const; protected: - typedef QMap ActionMap; typedef QMap WindowMap; typedef QMap WindowVisibilityMap; protected: LightApp_Preferences* myPrefs; LightApp_SelectionMgr* mySelMgr; - ActionMap myActions; + LightApp_ModuleAction* myModuleAction; WindowMap myWindows; WindowVisibilityMap myWindowsVisible; diff --git a/src/LightApp/LightApp_DataModel.cxx b/src/LightApp/LightApp_DataModel.cxx index 702ef7b33..7b14e8786 100644 --- a/src/LightApp/LightApp_DataModel.cxx +++ b/src/LightApp/LightApp_DataModel.cxx @@ -28,11 +28,9 @@ #include "LightApp_Module.h" #include "LightApp_Application.h" -#include +// temporary commented +//#include -#include -#include -#include #include /*! @@ -99,8 +97,9 @@ void LightApp_DataModel::build() void LightApp_DataModel::updateWidgets() { LightApp_Application* app = dynamic_cast( module()->application() ); - if( app ) - app->objectBrowser()->updateTree( 0, false ); + // temporary commented + /*if( app ) + app->objectBrowser()->updateTree( 0, false );*/ } /*! @@ -114,8 +113,9 @@ void LightApp_DataModel::update( LightApp_DataObject*, LightApp_Study* ) if( modelRoot ) { ch = modelRoot->children(); - for ( DataObjectListIterator it( ch ); it.current(); ++it ) - it.current()->setParent( 0 ); + QListIterator it( ch ); + while ( it.hasNext() ) + it.next()->setParent( 0 ); } build(); @@ -124,15 +124,19 @@ void LightApp_DataModel::update( LightApp_DataObject*, LightApp_Study* ) if( modelRoot ) { DataObjectList new_ch = modelRoot->children(); - for ( DataObjectListIterator it1( new_ch ); it1.current(); ++it1 ) - aMap.insert( it1.current(), 0 ); + QListIterator 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 it( ch ); + while ( it.hasNext() ) { + SUIT_DataObject* aDO = it.next(); + if( !aMap.contains( aDO ) ) + delete aDO; + } } /*! diff --git a/src/LightApp/LightApp_DataObject.cxx b/src/LightApp/LightApp_DataObject.cxx index a4df6dfa8..378cf63b7 100644 --- a/src/LightApp/LightApp_DataObject.cxx +++ b/src/LightApp/LightApp_DataObject.cxx @@ -24,12 +24,8 @@ #include "CAM_DataModel.h" #include "CAM_Module.h" -#include -#include #include -#include - /*! Class: LightApp_DataObject::Key Level: Internal diff --git a/src/LightApp/LightApp_DataObject.h b/src/LightApp/LightApp_DataObject.h index 4d3613dad..ec2469b0b 100644 --- a/src/LightApp/LightApp_DataObject.h +++ b/src/LightApp/LightApp_DataObject.h @@ -22,9 +22,10 @@ #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*/ diff --git a/src/LightApp/LightApp_DataOwner.cxx b/src/LightApp/LightApp_DataOwner.cxx index dd3c22f16..6288ce1ec 100644 --- a/src/LightApp/LightApp_DataOwner.cxx +++ b/src/LightApp/LightApp_DataOwner.cxx @@ -19,10 +19,6 @@ #include "LightApp_DataOwner.h" -#include "LightApp_DataObject.h" - -#include - /*!Constructor. Initialize by \a theEntry.*/ LightApp_DataOwner::LightApp_DataOwner( const QString& theEntry ) : myEntry( theEntry ) diff --git a/src/LightApp/LightApp_DataSubOwner.cxx b/src/LightApp/LightApp_DataSubOwner.cxx index c64c739eb..fd8c6e014 100644 --- a/src/LightApp/LightApp_DataSubOwner.cxx +++ b/src/LightApp/LightApp_DataSubOwner.cxx @@ -18,8 +18,6 @@ // #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 ), diff --git a/src/LightApp/LightApp_Dialog.cxx b/src/LightApp/LightApp_Dialog.cxx index 27219f5f1..f05267c34 100644 --- a/src/LightApp/LightApp_Dialog.cxx +++ b/src/LightApp/LightApp_Dialog.cxx @@ -21,20 +21,23 @@ #include #include +#include -#include -#include -#include +#include +#include +#include +#include /*! 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" ) ); } @@ -76,14 +79,14 @@ void LightApp_Dialog::updateButtons( const int _id ) 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 ); } } } @@ -130,7 +133,7 @@ void LightApp_Dialog::setObjectShown( const int id, const bool shown ) obj.myBtn->setShown( shown ); obj.myLabel->setShown( shown ); if( !shown ) - ( ( QToolButton* )obj.myBtn )->setOn( false ); + ( ( QToolButton* )obj.myBtn )->setChecked( false ); } } @@ -140,7 +143,7 @@ void LightApp_Dialog::setObjectShown( const int id, const bool shown ) */ bool LightApp_Dialog::isObjectShown( const int id ) const { - return myObjects.contains( id ) && myObjects[ id ].myEdit->isShown(); + return myObjects.contains( id ) && myObjects[ id ].myEdit->isVisible(); } /*! @@ -157,7 +160,7 @@ void LightApp_Dialog::setObjectEnabled( const int id, const bool en ) obj.myBtn->setEnabled( en ); // obj.myLabel->setEnabled( en ); if( !en ) - ( ( QToolButton* )obj.myBtn )->setOn( false ); + ( ( QToolButton* )obj.myBtn )->setChecked( false ); } } @@ -200,7 +203,7 @@ void LightApp_Dialog::selectObject( const QStringList& _names, 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 ); } @@ -338,8 +341,8 @@ int LightApp_Dialog::createObject( const QString& label, QWidget* parent, const 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 ) ) ); @@ -542,7 +545,7 @@ void LightApp_Dialog::objectTypes( const int id, TypesList& list ) const */ void LightApp_Dialog::onToggled( bool on ) { - QButton* but = ( QButton* )sender(); + QAbstractButton* but = ( QAbstractButton* )sender(); int id = -1; if( !but ) @@ -551,7 +554,7 @@ void LightApp_Dialog::onToggled( bool on ) 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 ) @@ -637,7 +640,7 @@ void LightApp_Dialog::setObjectPixmap( const QPixmap& p ) 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 ); } /*! @@ -687,7 +690,7 @@ void LightApp_Dialog::setNameIndication( const int id, const NameIndication ni ) 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 ); @@ -759,7 +762,7 @@ QString LightApp_Dialog::countOfTypes( const TypesList& types ) const QMap::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( ", " ); } @@ -789,7 +792,7 @@ const QString& LightApp_Dialog::typeName( const int type ) const */ 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(); } @@ -802,8 +805,8 @@ void LightApp_Dialog::deactivateAll() 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 ); } } @@ -892,12 +895,12 @@ void LightApp_Dialog::onTextChanged( const QString& text ) 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 ); } } diff --git a/src/LightApp/LightApp_Dialog.h b/src/LightApp/LightApp_Dialog.h index 6e3b3b8a0..f4a3a81d8 100644 --- a/src/LightApp/LightApp_Dialog.h +++ b/src/LightApp/LightApp_Dialog.h @@ -25,12 +25,12 @@ #include "LightApp.h" #include -#include -#include -#include +#include +#include +#include class QLineEdit; -class QButton; +class QAbstractButton; class QLabel; class SUIT_ResourceMgr; @@ -52,7 +52,7 @@ class LIGHTAPP_EXPORT LightApp_Dialog : public QtxDialog Q_OBJECT public: - typedef QValueList TypesList; + typedef QList TypesList; typedef QMap SelectedObjects; enum ObjectWg @@ -76,7 +76,7 @@ public: 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(); @@ -272,12 +272,12 @@ private: 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; diff --git a/src/LightApp/LightApp_Displayer.cxx b/src/LightApp/LightApp_Displayer.cxx index 0845d5cc9..8c92f18ef 100644 --- a/src/LightApp/LightApp_Displayer.cxx +++ b/src/LightApp/LightApp_Displayer.cxx @@ -29,7 +29,7 @@ #include #include -#include +#include #ifndef DISABLE_SALOMEOBJECT #include "SALOME_InteractiveObject.hxx" #endif @@ -88,11 +88,10 @@ void LightApp_Displayer::Redisplay( const QString& entry, const bool updateViewe if ( app ) { SUIT_Desktop* desk = app->desktop(); - QPtrList wnds = desk->windows(); - SUIT_ViewWindow* wnd; - for ( wnd = wnds.first(); wnd; wnd = wnds.next() ) + QListIterator itWnds( desk->windows() ); + while ( itWnds.hasNext() ) { - SUIT_ViewManager* vman = wnd->getViewManager(); + SUIT_ViewManager* vman = itWnds.next()->getViewManager(); if( !vman ) continue; @@ -123,7 +122,7 @@ void LightApp_Displayer::Erase( const QString& entry, const bool forced, 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 ) @@ -163,7 +162,7 @@ bool LightApp_Displayer::IsDisplayed( const QString& entry, SALOME_View* theView { #ifndef DISABLE_SALOMEOBJECT Handle( SALOME_InteractiveObject ) temp = new SALOME_InteractiveObject(); - temp->setEntry( entry.latin1() ); + temp->setEntry( entry.toLatin1() ); res = vf->isVisible( temp ); #endif } @@ -193,7 +192,7 @@ SALOME_Prs* LightApp_Displayer::buildPresentation( const QString& entry, SALOME_ SALOME_View* vf = theViewFrame ? theViewFrame : GetActiveView(); if ( vf ) - prs = vf->CreatePrs( entry.latin1() ); + prs = vf->CreatePrs( entry.toLatin1() ); return prs; } diff --git a/src/LightApp/LightApp_Driver.cxx b/src/LightApp/LightApp_Driver.cxx index e8e161dc5..08c1d2cdf 100644 --- a/src/LightApp/LightApp_Driver.cxx +++ b/src/LightApp/LightApp_Driver.cxx @@ -23,14 +23,11 @@ #include #include #include -#include -#include #include -#include #include -#include -#include +#include +#include #ifdef WIN32 #include @@ -84,7 +81,7 @@ bool LightApp_Driver::SaveDatasInFile( const char* theFileName, bool isMultiFile if(aFileBuffer == NULL) return false; - myTmpDir = QDir::convertSeparators( QFileInfo( theFileName ).dirPath( true ) + "/" ).latin1() ; + myTmpDir = QDir::convertSeparators( QFileInfo( theFileName ).absolutePath() + "/" ).toLatin1().constData() ; int aCurrentPos = 0; @@ -116,7 +113,7 @@ bool LightApp_Driver::SaveDatasInFile( const char* theFileName, bool isMultiFile aCurrentPos += aBufferSize[i]; } -#ifdef WNT +#ifdef WIN32 ofstream aFile(theFileName, ios::out | ios::binary); #else ofstream aFile(theFileName); @@ -137,13 +134,13 @@ bool LightApp_Driver::SaveDatasInFile( const char* theFileName, bool isMultiFile */ 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(); @@ -261,7 +258,7 @@ void LightApp_Driver::PutFilesToStream( const std::string& theModuleName, unsign 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()); @@ -299,7 +296,7 @@ void LightApp_Driver::PutFilesToStream( const std::string& theModuleName, unsign 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()); @@ -382,7 +379,7 @@ LightApp_Driver::ListOfFiles LightApp_Driver::PutStreamToFiles( const unsigned c TCollection_AsciiString aFullPath = aTmpDir + aFileName; -#ifdef WNT +#ifdef WIN32 ofstream aFile(aFullPath.ToCString(), ios::out | ios::binary); #else ofstream aFile(aFullPath.ToCString()); diff --git a/src/LightApp/LightApp_EventFilter.cxx b/src/LightApp/LightApp_EventFilter.cxx index 77ab42c9f..c9c2f89a2 100644 --- a/src/LightApp/LightApp_EventFilter.cxx +++ b/src/LightApp/LightApp_EventFilter.cxx @@ -21,7 +21,7 @@ #include -#include +#include LightApp_EventFilter* LightApp_EventFilter::myFilter = NULL; diff --git a/src/LightApp/LightApp_EventFilter.h b/src/LightApp/LightApp_EventFilter.h index 836db4476..32c30fa19 100644 --- a/src/LightApp/LightApp_EventFilter.h +++ b/src/LightApp/LightApp_EventFilter.h @@ -22,9 +22,9 @@ #include "LightApp.h" -#include +#include -#if defined WNT +#if defined WIN32 #pragma warning( disable: 4251 ) #endif @@ -49,7 +49,7 @@ private: static LightApp_EventFilter* myFilter; }; -#if defined WNT +#if defined WIN32 #pragma warning( default: 4251 ) #endif diff --git a/src/LightApp/LightApp_GLSelector.cxx b/src/LightApp/LightApp_GLSelector.cxx index d7c14c59b..b7807e8ca 100644 --- a/src/LightApp/LightApp_GLSelector.cxx +++ b/src/LightApp/LightApp_GLSelector.cxx @@ -19,9 +19,9 @@ #include "LightApp_GLSelector.h" #include "LightApp_DataOwner.h" -#include "LightApp_DataObject.h" #include +#include /*!Constructor. Initialize by GLViewer_Viewer2d and SUIT_SelectionMgr.*/ LightApp_GLSelector::LightApp_GLSelector( GLViewer_Viewer2d* viewer, SUIT_SelectionMgr* mgr ) diff --git a/src/LightApp/LightApp_GLSelector.h b/src/LightApp/LightApp_GLSelector.h index b63601604..dd31ff1db 100644 --- a/src/LightApp/LightApp_GLSelector.h +++ b/src/LightApp/LightApp_GLSelector.h @@ -25,8 +25,7 @@ #include -#include -#include +#include class LightApp_DataObject; @@ -34,7 +33,7 @@ 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 diff --git a/src/LightApp/LightApp_HDFDriver.cxx b/src/LightApp/LightApp_HDFDriver.cxx index 292cdd88b..20aba1ec5 100644 --- a/src/LightApp/LightApp_HDFDriver.cxx +++ b/src/LightApp/LightApp_HDFDriver.cxx @@ -18,7 +18,6 @@ // #include "LightApp_HDFDriver.h" -#include "HDFexplorer.hxx" #include "HDFOI.hxx" // OCCT Includes diff --git a/src/LightApp/LightApp_Module.cxx b/src/LightApp/LightApp_Module.cxx index 86be51db3..eac7e67a3 100644 --- a/src/LightApp/LightApp_Module.cxx +++ b/src/LightApp/LightApp_Module.cxx @@ -36,10 +36,12 @@ #include "LightApp_UpdateFlags.h" #include "LightApp_ShowHideOp.h" -#include "SUIT_Operation.h" #include #include +#include +#include #include +#include #ifndef DISABLE_VTKVIEWER #ifndef DISABLE_SALOMEOBJECT @@ -73,13 +75,14 @@ #endif #endif -#include +// temporary commented +//#include #include -#include -#include -#include +#include +#include +#include /*!Constructor.*/ LightApp_Module::LightApp_Module( const QString& name ) @@ -121,11 +124,12 @@ void LightApp_Module::viewManagers( QStringList& ) const } /*!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; } @@ -135,8 +139,9 @@ void LightApp_Module::contextMenuPopup( const QString& client, QPopupMenu* menu, 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() ){ @@ -151,8 +156,9 @@ void LightApp_Module::updateObjBrowser( bool theIsUpdateDataModel, } } } - getApp()->objectBrowser()->setAutoUpdate( upd ); - getApp()->objectBrowser()->updateTree( 0, false ); + // temporary commented + /*getApp()->objectBrowser()->setAutoUpdate( upd ); + getApp()->objectBrowser()->updateTree( 0, false );*/ } /*!NOT IMPLEMENTED*/ @@ -193,7 +199,7 @@ bool LightApp_Module::deactivateModule( SUIT_Study* study ) // 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 ); @@ -236,8 +242,9 @@ void LightApp_Module::update( const int theFlags ) if( LightApp_DataModel* aModel = dynamic_cast( aDataModel ) ) aModel->update( 0, dynamic_cast( 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 ) @@ -286,9 +293,9 @@ CAM_DataModel* LightApp_Module::createDataModel() } /*!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*/ @@ -339,9 +346,9 @@ QtxPopupMgr* LightApp_Module::popupMgr() 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; @@ -374,7 +381,7 @@ QtxPopupMgr* LightApp_Module::popupMgr() 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; @@ -519,7 +526,7 @@ void LightApp_Module::onOperationDestroyed() 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; diff --git a/src/LightApp/LightApp_Module.h b/src/LightApp/LightApp_Module.h index dbfed0b70..1911a32ff 100644 --- a/src/LightApp/LightApp_Module.h +++ b/src/LightApp/LightApp_Module.h @@ -32,8 +32,8 @@ class LightApp_Preferences; class LightApp_Selection; class LightApp_Operation; class LightApp_SwitchOp; -class LightApp_ShowHideOp; class LightApp_Displayer; +class LightApp_SelectionMgr; class SUIT_Study; class SUIT_DataObject; @@ -67,7 +67,7 @@ public: virtual void windows( QMap& ) const; virtual void viewManagers( QStringList& ) const; - virtual void contextMenuPopup( const QString&, QPopupMenu*, QString& ); + virtual void contextMenuPopup( const QString&, QMenu*, QString& ); virtual void createPreferences(); @@ -88,7 +88,7 @@ public: 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* ); diff --git a/src/LightApp/LightApp_ModuleAction.cxx b/src/LightApp/LightApp_ModuleAction.cxx new file mode 100755 index 000000000..4e929fa12 --- /dev/null +++ b/src/LightApp/LightApp_ModuleAction.cxx @@ -0,0 +1,580 @@ +// 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 +#include +#include + +/*! + \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 alist = actions(); + for ( QList::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 alist = actions(); + for ( QList::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 alist = actions(); + for ( QList::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 LightApp_ModuleAction::ComboAction::widgets() const +{ + QList lst; + + QList wlist = createdWidgets(); + for ( QList::const_iterator wit = wlist.begin(); wit != wlist.end(); ++wit ) + lst += qFindChildren(*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 alist = mySet->actions(); + for ( QList::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 lst = myCombo->widgets(); + for ( QList::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 alist = mySet->actions(); + cb->clear(); + + cb->addItem( icon(), text() ); + cb->setId( 0, -1 ); + + for ( QList::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 alist = mySet->actions(); + for ( QList::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 alist = mySet->actions(); + for ( QList::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 widgets = myCombo->widgets(); + for ( QList::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 ); +} diff --git a/src/LightApp/LightApp_ModuleAction.h b/src/LightApp/LightApp_ModuleAction.h new file mode 100755 index 000000000..333c265e2 --- /dev/null +++ b/src/LightApp/LightApp_ModuleAction.h @@ -0,0 +1,111 @@ +// 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 + +#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 widgets() const; + +protected: + virtual QWidget* createWidget( QWidget* ); + +signals: + void activatedId( int ); +}; + +#endif // LIGHTAPP_MODULEACTION_H diff --git a/src/LightApp/LightApp_ModuleDlg.cxx b/src/LightApp/LightApp_ModuleDlg.cxx index d7777bdaa..7d8450dae 100644 --- a/src/LightApp/LightApp_ModuleDlg.cxx +++ b/src/LightApp/LightApp_ModuleDlg.cxx @@ -22,11 +22,10 @@ #include -#include -#include -#include -#include -#include +#include +#include +#include +#include #ifndef WIN32 using namespace std; @@ -109,17 +108,21 @@ static const char* const default_icon[] = { */ //============================================================================================================================== 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 ); @@ -128,15 +131,17 @@ LightApp_ModuleDlg::LightApp_ModuleDlg ( QWidget * parent, const QString& compon 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 ); @@ -146,13 +151,16 @@ LightApp_ModuleDlg::LightApp_ModuleDlg ( QWidget * parent, const QString& compon 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(); @@ -166,16 +174,20 @@ LightApp_ModuleDlg::LightApp_ModuleDlg ( QWidget * parent, const QString& compon 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 ); @@ -186,9 +198,9 @@ LightApp_ModuleDlg::LightApp_ModuleDlg ( QWidget * parent, const QString& compon 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() ) ); diff --git a/src/LightApp/LightApp_ModuleDlg.h b/src/LightApp/LightApp_ModuleDlg.h index 9b818344c..867ee7675 100644 --- a/src/LightApp/LightApp_ModuleDlg.h +++ b/src/LightApp/LightApp_ModuleDlg.h @@ -26,8 +26,8 @@ #define LIGHTAPP_MODULEDLG_H #include "LightApp.h" -#include -#include +#include +#include class QFrame; class QLabel; diff --git a/src/LightApp/LightApp_NameDlg.cxx b/src/LightApp/LightApp_NameDlg.cxx index e1bca58ce..31246058c 100644 --- a/src/LightApp/LightApp_NameDlg.cxx +++ b/src/LightApp/LightApp_NameDlg.cxx @@ -21,15 +21,14 @@ // $Header$ #include -#include -#include #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #ifndef WIN32 using namespace std; @@ -40,48 +39,51 @@ 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 ); @@ -128,7 +130,7 @@ QString LightApp_NameDlg::name() */ void LightApp_NameDlg::accept() { - if ( name().stripWhiteSpace().isEmpty() ) + if ( name().trimmed().isEmpty() ) return; QDialog::accept(); } diff --git a/src/LightApp/LightApp_NameDlg.h b/src/LightApp/LightApp_NameDlg.h index 45f64c15b..9f8f88bbb 100644 --- a/src/LightApp/LightApp_NameDlg.h +++ b/src/LightApp/LightApp_NameDlg.h @@ -27,7 +27,7 @@ #define LIGHTAPP_NAMEDLG_H #include "LightApp.h" -#include +#include class QLineEdit; class QPushButton; diff --git a/src/LightApp/LightApp_OBSelector.cxx b/src/LightApp/LightApp_OBSelector.cxx index 175356d91..c9716877d 100644 --- a/src/LightApp/LightApp_OBSelector.cxx +++ b/src/LightApp/LightApp_OBSelector.cxx @@ -22,12 +22,13 @@ #include "LightApp_DataObject.h" #include "LightApp_Application.h" -#include +// temporary commented +//#include #include #include -#include +#include #include @@ -35,12 +36,13 @@ 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(); } @@ -75,16 +77,20 @@ void LightApp_OBSelector::getSelection( SUIT_DataOwnerPtrList& theList ) const 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 it( objlist ); + while ( it.hasNext() ) { - LightApp_DataObject* obj = dynamic_cast( it.current() ); + LightApp_DataObject* obj = dynamic_cast( 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() ); @@ -102,8 +108,10 @@ void LightApp_OBSelector::setSelection( const SUIT_DataOwnerPtrList& theList ) if ( !myBrowser ) return; - if( myEntries.count() == 0 || - myModifiedTime < myBrowser->getModifiedTime() ) + if( myEntries.count() == 0 + // temporary commented + /*|| + myModifiedTime < myBrowser->getModifiedTime()*/ ) fillEntries( myEntries ); DataObjectList objList; @@ -114,7 +122,8 @@ void LightApp_OBSelector::setSelection( const SUIT_DataOwnerPtrList& theList ) objList.append( myEntries[owner->entry()] ); } - myBrowser->setSelected( objList ); + // temporary commented + //myBrowser->setSelected( objList ); mySelectedList.clear(); } @@ -125,7 +134,7 @@ void LightApp_OBSelector::onSelectionChanged() 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.*/ @@ -136,13 +145,14 @@ void LightApp_OBSelector::fillEntries( QMap& enti 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( it.current() ); if ( obj ) entires.insert( obj->entry(), obj ); - } + }*/ setModified(); } diff --git a/src/LightApp/LightApp_OBSelector.h b/src/LightApp/LightApp_OBSelector.h index f6811946c..9645e951b 100644 --- a/src/LightApp/LightApp_OBSelector.h +++ b/src/LightApp/LightApp_OBSelector.h @@ -24,6 +24,8 @@ #include #include +#include + class OB_Browser; class LightApp_DataObject; @@ -31,7 +33,7 @@ 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 diff --git a/src/LightApp/LightApp_OCCSelector.h b/src/LightApp/LightApp_OCCSelector.h index 905267435..676485c9e 100644 --- a/src/LightApp/LightApp_OCCSelector.h +++ b/src/LightApp/LightApp_OCCSelector.h @@ -24,6 +24,8 @@ #include #include +#include + #include class Handle_AIS_InteractiveObject; @@ -32,7 +34,7 @@ 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 diff --git a/src/LightApp/LightApp_Operation.cxx b/src/LightApp/LightApp_Operation.cxx index 86450eb81..a1ab32f96 100755 --- a/src/LightApp/LightApp_Operation.cxx +++ b/src/LightApp/LightApp_Operation.cxx @@ -23,14 +23,11 @@ #include #include #include -#include #include #include #include - -#include - +#include /*! * \brief Constructor @@ -265,7 +262,7 @@ void LightApp_Operation::setDialogActive( const bool active ) if( active ) { activateSelection(); - dlg()->setActiveWindow(); + dlg()->activateWindow(); } } } diff --git a/src/LightApp/LightApp_Operation.h b/src/LightApp/LightApp_Operation.h index 8afcda91a..ab01e890b 100755 --- a/src/LightApp/LightApp_Operation.h +++ b/src/LightApp/LightApp_Operation.h @@ -28,8 +28,6 @@ #include class LightApp_Module; -class LightApp_Application; -class LightApp_Operation; class LightApp_SelectionMgr; class LightApp_Dialog; class SUIT_Desktop; diff --git a/src/LightApp/LightApp_Preferences.cxx b/src/LightApp/LightApp_Preferences.cxx index 65a7ef490..beaa1afe4 100644 --- a/src/LightApp/LightApp_Preferences.cxx +++ b/src/LightApp/LightApp_Preferences.cxx @@ -21,10 +21,6 @@ #include "LightApp_Preferences.h" -#include - -#include - /*! Constructor.Initialize by resource manager and parent QWidget. */ @@ -68,7 +64,7 @@ bool LightApp_Preferences::hasModule( const QString& mod ) const { bool res = false; for ( PrefModuleMap::ConstIterator it = myPrefMod.begin(); it != myPrefMod.end() && !res; ++it ) - res = it.data() == mod; + res = it.value() == mod; return res; } diff --git a/src/LightApp/LightApp_Preferences.h b/src/LightApp/LightApp_Preferences.h index f3d791986..6a1b3dc1c 100644 --- a/src/LightApp/LightApp_Preferences.h +++ b/src/LightApp/LightApp_Preferences.h @@ -23,11 +23,9 @@ #define LIGHTAPP_PREFERENCES_H #include - -#include #include -#include +#include class QtxResourceMgr; diff --git a/src/LightApp/LightApp_PreferencesDlg.cxx b/src/LightApp/LightApp_PreferencesDlg.cxx index b691eb459..efb03ca15 100644 --- a/src/LightApp/LightApp_PreferencesDlg.cxx +++ b/src/LightApp/LightApp_PreferencesDlg.cxx @@ -24,30 +24,38 @@ #include "QtxResourceMgr.h" -#include -#include -#include -#include -#include +#include + +#include +#include +#include /*! 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 ); @@ -55,10 +63,10 @@ myPrefs( prefs ), mySaved ( false ) 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() ) ); } @@ -71,7 +79,9 @@ LightApp_PreferencesDlg::~LightApp_PreferencesDlg() if ( !myPrefs ) return; - myPrefs->reparent( 0, QPoint( 0, 0 ), false ); + myPrefs->setParent( 0 ); + myPrefs->move( QPoint( 0, 0 ) ); + myPrefs->hide(); myPrefs = 0; } @@ -124,7 +134,9 @@ void LightApp_PreferencesDlg::onApply() /*! 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() ) { @@ -143,14 +155,16 @@ void LightApp_PreferencesDlg::onImportPref() 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(); diff --git a/src/LightApp/LightApp_Selection.cxx b/src/LightApp/LightApp_Selection.cxx index fe0a15207..8fe825ddd 100644 --- a/src/LightApp/LightApp_Selection.cxx +++ b/src/LightApp/LightApp_Selection.cxx @@ -24,31 +24,21 @@ #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 ) { @@ -62,11 +52,13 @@ void LightApp_Selection::init( const QString& client, LightApp_SelectionMgr* 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 aSelectors; + QList aSelectors; mgr->selectors( aSelectors ); - for( SUIT_Selector* selector = aSelectors.first(); selector; selector = aSelectors.next() ) + QListIterator 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() ); @@ -100,6 +92,13 @@ void LightApp_Selection::init( const QString& client, LightApp_SelectionMgr* mgr } } +/*! + Destructor. +*/ +LightApp_Selection::~LightApp_Selection() +{ +} + QString LightApp_Selection::referencedToEntry( const QString& entry ) const { return myStudy->referencedToEntry( entry ); @@ -114,17 +113,17 @@ int LightApp_Selection::count() const } /*! - 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( myStudy ? myStudy->application() : 0 ); if( !( ind>=0 && indmoduleTitle( 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 @@ -136,7 +135,7 @@ QtxValue LightApp_Selection::param( const int ind, const QString& p ) const LightApp_Displayer local_d; vis = local_d.IsDisplayed( myEntries[ ind ] ); } - return QtxValue( vis, 0 ); + return QVariant( vis ); } else if( p=="component" ) @@ -146,18 +145,18 @@ QtxValue LightApp_Selection::param( const int ind, const QString& p ) const 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 @@ -171,15 +170,15 @@ QtxValue LightApp_Selection::param( const int ind, const QString& p ) const //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( myStudy->application() ); @@ -188,14 +187,14 @@ QtxValue LightApp_Selection::globalParam( const QString& p ) const 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 } diff --git a/src/LightApp/LightApp_Selection.h b/src/LightApp/LightApp_Selection.h index 7756a767d..c95c53d9d 100644 --- a/src/LightApp/LightApp_Selection.h +++ b/src/LightApp/LightApp_Selection.h @@ -44,18 +44,17 @@ class SUIT_ViewWindow; 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: diff --git a/src/LightApp/LightApp_SelectionMgr.cxx b/src/LightApp/LightApp_SelectionMgr.cxx index ca18b5759..3240a1abe 100644 --- a/src/LightApp/LightApp_SelectionMgr.cxx +++ b/src/LightApp/LightApp_SelectionMgr.cxx @@ -33,6 +33,7 @@ #include #include #include + #include #endif /*! @@ -95,7 +96,7 @@ void LightApp_SelectionMgr::selectedObjects( SALOME_ListIO& theList, const QStri 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() ); @@ -285,16 +286,16 @@ void LightApp_SelectionMgr::selectObjects( MapIOOfMapOfInteger theMapIO, bool ap { 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 ) ) ); } } @@ -307,7 +308,7 @@ void LightApp_SelectionMgr::selectObjects( MapIOOfMapOfInteger theMapIO, bool ap */ void LightApp_SelectionMgr::selectedSubOwners( MapEntryOfMapOfInteger& theMap ) { - theMap.clear(); + theMap.Clear(); TColStd_IndexedMapOfInteger anIndexes; @@ -319,11 +320,15 @@ void LightApp_SelectionMgr::selectedSubOwners( MapEntryOfMapOfInteger& theMap ) const LightApp_DataSubOwner* subOwner = dynamic_cast( (*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 ); } } } diff --git a/src/LightApp/LightApp_SelectionMgr.h b/src/LightApp/LightApp_SelectionMgr.h index be758e079..ccc0c3eca 100644 --- a/src/LightApp/LightApp_SelectionMgr.h +++ b/src/LightApp/LightApp_SelectionMgr.h @@ -25,13 +25,15 @@ #ifndef DISABLE_SALOMEOBJECT #include - #include + #include + #include class SALOME_ListIO; class TColStd_IndexedMapOfInteger; class TColStd_MapOfInteger; + class TCollection_AsciiString; #else -#include +#include #endif class LightApp_Application; @@ -51,8 +53,8 @@ public: 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 ); diff --git a/src/LightApp/LightApp_ShowHideOp.cxx b/src/LightApp/LightApp_ShowHideOp.cxx index 657e30d9d..22762198d 100644 --- a/src/LightApp/LightApp_ShowHideOp.cxx +++ b/src/LightApp/LightApp_ShowHideOp.cxx @@ -19,11 +19,9 @@ #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" @@ -67,11 +65,10 @@ void LightApp_ShowHideOp::startOperation() 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(); @@ -81,7 +78,7 @@ void LightApp_ShowHideOp::startOperation() 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() ) diff --git a/src/LightApp/LightApp_ShowHideOp.h b/src/LightApp/LightApp_ShowHideOp.h index 687c16dd2..52266e824 100644 --- a/src/LightApp/LightApp_ShowHideOp.h +++ b/src/LightApp/LightApp_ShowHideOp.h @@ -22,8 +22,6 @@ #include "LightApp_Operation.h" -class LightApp_Displayer; - /*! \class LightApp_ShowHideOp Standard operation allowing to show/hide selected objects diff --git a/src/LightApp/LightApp_Study.cxx b/src/LightApp/LightApp_Study.cxx index a37df3ba7..6c3ae1bad 100644 --- a/src/LightApp/LightApp_Study.cxx +++ b/src/LightApp/LightApp_Study.cxx @@ -19,6 +19,7 @@ #include "LightApp_Study.h" #include "CAM_DataModel.h" +#include "CAM_Module.h" #include "LightApp_Application.h" #include "LightApp_DataModel.h" #include "LightApp_DataObject.h" @@ -28,21 +29,8 @@ #include "SUIT_ResourceMgr.h" #include "SUIT_DataObjectIterator.h" -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - #include -#include +#include /*! Constructor. @@ -65,16 +53,18 @@ LightApp_Study::~LightApp_Study() /*! 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; } /*! @@ -92,8 +82,9 @@ bool LightApp_Study::openDocument( const QString& theFileName ) // 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 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. @@ -122,8 +113,9 @@ bool LightApp_Study::loadDocument( const QString& theStudyName ) ModelList dm_s; dataModels( dm_s ); - for ( ModelListIterator it( dm_s ); it.current(); ++it ) - openDataModel( studyName(), it.current() ); + QListIterator 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 @@ -148,13 +140,15 @@ bool LightApp_Study::saveDocumentAs( const QString& theFileName ) 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 itList( list ); + while ( itList.hasNext() ) { - std::vector anOldList = myDriver->GetListOfFiles( aModel->module()->name() ); + LightApp_DataModel* aModel = (LightApp_DataModel*)itList.next(); + if ( !aModel ) continue; + + std::vector anOldList = myDriver->GetListOfFiles( aModel->module()->name().toLatin1().constData() ); listOfFiles.clear(); aModel->saveAs( theFileName, this, listOfFiles ); if ( !listOfFiles.isEmpty() ) @@ -165,7 +159,7 @@ bool LightApp_Study::saveDocumentAs( const QString& theFileName ) // removing previous temporary files. These files are not removed before saving // because they may be required for it. - std::vector aNewList = myDriver->GetListOfFiles( aModel->module()->name() ); + std::vector aNewList = myDriver->GetListOfFiles( aModel->module()->name().toLatin1().constData() ); std::set aNewNames; std::set toRemove; @@ -205,11 +199,13 @@ bool LightApp_Study::saveDocument() { ModelList list; dataModels( list ); - LightApp_DataModel* aModel = (LightApp_DataModel*)list.first(); - myDriver->ClearDriverContents(); QStringList listOfFiles; - for ( ; aModel; aModel = (LightApp_DataModel*)list.next() ) { + QListIterator 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); @@ -298,8 +294,9 @@ bool LightApp_Study::isModified() const ModelList list; dataModels( list ); LightApp_DataModel* aModel = 0; - for ( QPtrListIterator it( list ); it.current() && !isAnyChanged; ++it ){ - aModel = dynamic_cast( it.current() ); + QListIterator it( list ); + while ( it.hasNext() && !isAnyChanged ) { + aModel = dynamic_cast( it.next() ); if ( aModel ) isAnyChanged = aModel->isModified(); } @@ -335,10 +332,10 @@ void LightApp_Study::saveModuleData(QString theModuleName, QStringList theListOf 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); } /*! @@ -346,7 +343,7 @@ void LightApp_Study::saveModuleData(QString theModuleName, QStringList theListOf */ void LightApp_Study::openModuleData(QString theModuleName, QStringList& theListOfFiles) { - std::vector aListOfFiles = myDriver->GetListOfFiles(theModuleName); + std::vector aListOfFiles = myDriver->GetListOfFiles(theModuleName.toLatin1().constData()); int i, aLength = aListOfFiles.size() - 1; if (aLength < 0) return; @@ -368,7 +365,7 @@ bool LightApp_Study::saveStudyData( const QString& theFileName ) 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; } @@ -382,7 +379,7 @@ bool LightApp_Study::openStudyData( const QString& theFileName ) 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; } diff --git a/src/LightApp/LightApp_Study.h b/src/LightApp/LightApp_Study.h index b9de680b8..c45394d47 100644 --- a/src/LightApp/LightApp_Study.h +++ b/src/LightApp/LightApp_Study.h @@ -23,12 +23,11 @@ #include #include -#include -#include #include "string" #include "vector" +class SUIT_Study; class SUIT_Application; class CAM_DataModel; @@ -45,7 +44,7 @@ public: 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& ); diff --git a/src/LightApp/LightApp_SwitchOp.cxx b/src/LightApp/LightApp_SwitchOp.cxx index 67283f365..8fc5baf7f 100755 --- a/src/LightApp/LightApp_SwitchOp.cxx +++ b/src/LightApp/LightApp_SwitchOp.cxx @@ -24,10 +24,11 @@ #include #include #include -#include -#include -#include -#include + +#include +#include +#include +#include /*! * \brief Constructor @@ -93,14 +94,16 @@ LightApp_Operation* LightApp_SwitchOp::operation( QWidget* theWg ) const // try to find operation corresponding to the dialog if ( aDlg != 0 && study() != 0 ) { - QPtrListIterator anIter( study()->operations() ); - while( SUIT_Operation* anOp = anIter.current() ) + QListIterator 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; diff --git a/src/LightApp/LightApp_SwitchOp.h b/src/LightApp/LightApp_SwitchOp.h index a85d2e3da..857644e3b 100755 --- a/src/LightApp/LightApp_SwitchOp.h +++ b/src/LightApp/LightApp_SwitchOp.h @@ -21,7 +21,7 @@ #define LightApp_SwitchOp_H #include "LightApp.h" -#include +#include class LightApp_Module; class LightApp_Operation; diff --git a/src/LightApp/LightApp_VTKSelector.cxx b/src/LightApp/LightApp_VTKSelector.cxx index 99214fb9f..bd4c4100d 100644 --- a/src/LightApp/LightApp_VTKSelector.cxx +++ b/src/LightApp/LightApp_VTKSelector.cxx @@ -19,6 +19,8 @@ #include "LightApp_VTKSelector.h" #include "LightApp_DataOwner.h" +#include "SUIT_Desktop.h" + #ifndef DISABLE_VTKVIEWER #include "SVTK_ViewModelBase.h" #include "SVTK_ViewManager.h" @@ -224,7 +226,7 @@ LightApp_VTKSelector aSelector->AddOrRemoveIndex(anIO,anOwner->GetIds(),false); }else if(const LightApp_DataOwner* anOwner = dynamic_cast(aDataOwner)){ Handle(SALOME_InteractiveObject) anIO = - new SALOME_InteractiveObject(anOwner->entry().latin1(),""); + new SALOME_InteractiveObject(anOwner->entry().toLatin1(),""); aSelector->AddIObject(anIO); anAppendList.Append(anIO); } @@ -243,7 +245,7 @@ LightApp_VTKSelector 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(); } diff --git a/src/LightApp/LightApp_VTKSelector.h b/src/LightApp/LightApp_VTKSelector.h index 0f185cc53..ff68f3507 100644 --- a/src/LightApp/LightApp_VTKSelector.h +++ b/src/LightApp/LightApp_VTKSelector.h @@ -23,10 +23,11 @@ #include "LightApp.h" #include "LightApp_DataOwner.h" +#include + class SUIT_Desktop; #ifndef DISABLE_VTKVIEWER - #include #include #include "SVTK_Selection.h" #ifndef DISABLE_SALOMEOBJECT @@ -73,7 +74,7 @@ class LIGHTAPP_EXPORT LightApp_SVTKDataOwner : public LightApp_DataOwner \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; diff --git a/src/LightApp/LightApp_WidgetContainer.cxx b/src/LightApp/LightApp_WidgetContainer.cxx index aa6f831d2..e6ac9401f 100644 --- a/src/LightApp/LightApp_WidgetContainer.cxx +++ b/src/LightApp/LightApp_WidgetContainer.cxx @@ -18,17 +18,18 @@ // #include "LightApp_WidgetContainer.h" -#include -#include +#include +#include /*! 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(); } @@ -44,14 +45,16 @@ LightApp_WidgetContainer::~LightApp_WidgetContainer() */ bool LightApp_WidgetContainer::isEmpty() const { - const QObjectList* lst = myStack->children(); - if ( !lst ) + const QList lst = myStack->children(); + if ( lst.isEmpty() ) return true; bool res = true; - for ( QObjectListIt it( *lst ); it.current() && res; ++it ) + QListIterator 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; @@ -85,11 +88,11 @@ int LightApp_WidgetContainer::insert( const int id, QWidget* wid ) 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; } @@ -101,7 +104,7 @@ void LightApp_WidgetContainer::remove( const int id ) { remove( myStack->widget( id ) ); - setCaption( myStack->visibleWidget() ? myStack->visibleWidget()->caption() : QString::null ); + setWindowTitle( myStack->currentWidget() ? myStack->currentWidget()->windowTitle() : QString::null ); } /*! @@ -111,7 +114,7 @@ void LightApp_WidgetContainer::remove( QWidget* wid ) { myStack->removeWidget( wid ); - setCaption( myStack->visibleWidget() ? myStack->visibleWidget()->caption() : QString::null ); + setWindowTitle( myStack->currentWidget() ? myStack->currentWidget()->windowTitle() : QString::null ); } /*! @@ -119,9 +122,9 @@ void LightApp_WidgetContainer::remove( QWidget* wid ) */ 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 ); } /*! @@ -129,9 +132,9 @@ void LightApp_WidgetContainer::activate( const int id ) */ 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 ); } /*! @@ -147,5 +150,5 @@ QWidget* LightApp_WidgetContainer::widget( const int id ) const */ QWidget* LightApp_WidgetContainer::active() const { - return myStack->visibleWidget(); + return myStack->currentWidget(); } diff --git a/src/LightApp/LightApp_WidgetContainer.h b/src/LightApp/LightApp_WidgetContainer.h index 1679ec0c7..8fc496f7e 100644 --- a/src/LightApp/LightApp_WidgetContainer.h +++ b/src/LightApp/LightApp_WidgetContainer.h @@ -21,15 +21,15 @@ #include "LightApp.h" -#include +#include 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 @@ -53,8 +53,8 @@ public: QWidget* widget( const int ) const; private: - int myType; - QWidgetStack* myStack; + int myType; + QStackedWidget* myStack; }; #endif diff --git a/src/LightApp/Makefile.am b/src/LightApp/Makefile.am index f59c4bd09..4776d0dc9 100755 --- a/src/LightApp/Makefile.am +++ b/src/LightApp/Makefile.am @@ -39,6 +39,7 @@ salomeinclude_HEADERS= \ LightApp_EventFilter.h \ LightApp_HDFDriver.h \ LightApp_Module.h \ + LightApp_ModuleAction.h \ LightApp_ModuleDlg.h \ LightApp_NameDlg.h \ LightApp_OBFilter.h \ @@ -80,6 +81,7 @@ dist_libLightApp_la_SOURCES= \ LightApp_EventFilter.cxx \ LightApp_HDFDriver.cxx \ LightApp_Module.cxx \ + LightApp_ModuleAction.cxx \ LightApp_ModuleDlg.cxx \ LightApp_NameDlg.cxx \ LightApp_OBFilter.cxx \ @@ -114,6 +116,7 @@ MOC_FILES= \ 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 \ @@ -154,7 +157,7 @@ nodist_salomeres_DATA= \ 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 @@ -173,7 +176,7 @@ else !ENABLE_OCCVIEWER 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 @@ -212,8 +215,9 @@ else !ENABLE_SALOMEOBJECT 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 @@ -240,7 +244,7 @@ if ENABLE_SALOMEOBJECT 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 diff --git a/src/LightApp/resources/LightApp.xml b/src/LightApp/resources/LightApp.xml index fa3b06bd7..5b2cab2f1 100644 --- a/src/LightApp/resources/LightApp.xml +++ b/src/LightApp/resources/LightApp.xml @@ -38,6 +38,7 @@
+ diff --git a/src/LightApp/resources/LightApp_images.ts b/src/LightApp/resources/LightApp_images.ts new file mode 100644 index 000000000..0feadeb59 --- /dev/null +++ b/src/LightApp/resources/LightApp_images.ts @@ -0,0 +1,33 @@ + + + @default + + APP_DEFAULT_ICO + icon_default.png + + + ABOUT + icon_about.png + + + ABOUT_SPLASH + icon_about.png + + + APP_MODULE_BIG_ICO + icon_module_big.png + + + APP_BASE_LOGO + icon_applogo.png + + + ICON_SELECT + icon_select.png + + + APP_MODULE_ICO + icon_module.png + + + diff --git a/src/LightApp/resources/LightApp_msg_en.ts b/src/LightApp/resources/LightApp_msg_en.ts new file mode 100644 index 000000000..3223c0022 --- /dev/null +++ b/src/LightApp/resources/LightApp_msg_en.ts @@ -0,0 +1,433 @@ + + + @default + + EXTERNAL_BROWSER_CANNOT_SHOW_PAGE + External browser "%1" can not show help page "%2". Do you want to change it in preferences? + + + ABOUT_COPYRIGHT + Copyright (C) 2003-2006 OPEN CASCADE, EADS/CCR, LIP6, +CEA/DEN, CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS + + + ABOUT_CAPTION + About %1 + + + APP_NAME + SALOME + + + ABOUT_LICENSE + GNU LGPL + + + ABOUT_VERSION + Version %1 + + + + LightApp_Application + + INF_TOOLBAR_MODULES + Modules + + + PREF_SHOW_LEGEND + Show legend + + + MEN_DESK_RENAME + &Rename + + + PREF_MULTI_FILE + Multi file save + + + MEN_DESK_PREFERENCES + Pre&ferences... + + + PREF_TRIHEDRON_SHOW + Show trihedron + + + PREF_TRIHEDRON_SIZE + Trihedron size + + + OBJECT_BROWSER + Object Browser + + + PRP_DESK_PREFERENCES + Allow to change the preferences + + + PREF_GROUP_DIRECTORIES + Quick directory list + + + PREF_GROUP_VTKVIEWER + VTK Viewer 3d + + + PREF_STORE_POS + Store positions of windows + + + PREF_BOTTOM + Bottom + + + PREF_CURVE_TYPE + Curve type: + + + PREF_ISOS_U + Number of isolines along U + + + PREF_ISOS_V + Number of isolines along V + + + PREF_POINTS + Points + + + PRP_MODULE + Switch to the module "%1" + + + PREF_ASCII_FILE + ASCII save + + + PREFERENCES_NOT_LOADED + Preferences for module "<b>%1</b>" will be available when the module will be loaded + + + PREF_LINEAR + Linear + + + DATA_MODELS + Data models + + + PRP_RENAME + Rename active window + + + TOT_RENAME + Rename + + + LOG_WINDOW + Message Window + + + PREF_SPLINE + Spline + + + PREF_OBJ_BROWSER_SETTINGS + Object browser settings + + + PRP_APP_MODULE + Switch to SALOME platform neutral point + + + PREF_GROUP_PY_CONSOLE + Python console properties + + + PREF_MARKER_SIZE + Marker size: + + + PREF_TAB_VIEWERS + Viewers + + + PREF_APP + Application + + + PREF_TOP + Top + + + MEN_REFRESH + Refresh + + + PREF_AUTO_SIZE_FIRST + Auto size for first column + + + PREF_GROUP_SUPERV + Graph Supervisor + + + PREF_TAB_OBJBROWSER + Object browser + + + PREF_TAB_GENERAL + General + + + NEW_WINDOW_0 + &GL view + + + NEW_WINDOW_1 + &Plot2d view + + + NEW_WINDOW_2 + &OCC view + + + NEW_WINDOW_3 + VT&K view + + + OBJ_BROWSER_NAME + Object + + + PREF_LEGEND_POSITION + Legend position: + + + PREF_RELATIVE_SIZE + Relative size + + + PREF_VIEWER_BACKGROUND + Background color + + + PREF_FONT + Font + + + PREF_LEFT + Left + + + PREF_TAB_DIRECTORIES + Directories + + + ACTIVATING_MODULE + Trying to activate module "%1" + + + PREF_VERT_AXIS_SCALE + Vertical axis scale: + + + PREF_HOR_AXIS_SCALE + Horizontal axis scale: + + + PREF_GROUP_STUDY + Study properties + + + PREF_CATEGORY_SALOME + SALOME + + + PREF_GROUP_OCCVIEWER + OCC Viewer 3d + + + PREF_LOGARITHMIC + Logarithmic + + + MEN_DESK_MODULE_HELP + Module help + + + PREF_SUPERV_TITLE_COLOR + Title color + + + PREF_PARAM + Parameters + + + PREF_RIGHT + Right + + + PREF_LINES + Lines + + + INF_CANCELLED + Module activation cancelled + + + PREF_GROUP_EXT_BROWSER + External browser + + + PREF_SUPERV_CTRL_COLOR + Ctrl color + + + PREF_GROUP_DEF_COLUMNS + Default columns + + + PREF_GROUP_PLOT2DVIEWER + Plot2d Viewer + + + MEN_DESK_MRU + Most recently used + + + TOT_DESK_PREFERENCES + Preferences + + + DEFINE_EXTERNAL_BROWSER + External browser is not found. Do you want to define it in preferences? + + + PREF_AUTO_SIZE + Auto size for other columns + + + TOT_DESK_MRU + Most recently used + + + + LightApp_Module + + MEN_ERASE + Erase + + + TOP_DISPLAY_ONLY + Display only + + + STB_DISPLAY_ONLY + Display only + + + MEN_DISPLAY_ONLY + Display only + + + TOP_ERASE + Erase + + + MEN_ERASE_ALL + Erase all + + + STB_ERASE + Erase + + + STB_DISPLAY + Display + + + TOP_DISPLAY + Display + + + MEN_DISPLAY + Display + + + STB_ERASE_ALL + Erase all + + + TOP_ERASE_ALL + Erase all + + + + LightApp_ModuleDlg + + NEW + &New + + + LOAD + &Load + + + OPEN + &Open + + + ActivateComponent_DESCRIPTION + Create, open or load study. + + + CANCEL + &Cancel + + + CAPTION + Activate module + + + + LightApp_NameDlg + + TLT_RENAME + Rename + + + NAME_LBL + Name: + + + + LightApp_PreferencesDlg + + IMPORT_PREFERENCES + Import preferences + + + CAPTION + Preferences + + + WARNING + Warning + + + IMPORT_BTN_TEXT + Import + + + DEFAULT_QUESTION + Do you want to retrieve default preferences? + + + DEFAULT_BTN_TEXT + Defaults + + + diff --git a/src/LogWindow/LogWindow.cxx b/src/LogWindow/LogWindow.cxx index 161011c45..fb6ef862d 100755 --- a/src/LogWindow/LogWindow.cxx +++ b/src/LogWindow/LogWindow.cxx @@ -1,66 +1,94 @@ // 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 -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -#include -#include #include #include +#include +#include #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(); @@ -68,13 +96,12 @@ SUIT_PopupClient() 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; @@ -87,28 +114,35 @@ SUIT_PopupClient() } /*! - 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 ) { @@ -118,8 +152,8 @@ 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 ) { @@ -129,26 +163,85 @@ 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( "%2" ).arg( color.name() ).arg( msg ); + + QString dStr; + if ( flags & DisplayDate ) + { + dStr = QDate::currentDate().toString( Qt::SystemLocaleDate ); + if ( !noColor ) + dStr = QString( "%1" ).arg( dStr ); + } + + QString tStr; + if ( flags & DisplayTime ) + { + tStr = QTime::currentTime().toString( Qt::SystemLocaleDate ); + if ( !noColor ) + tStr = QString( "%1" ).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 ) { @@ -159,20 +252,21 @@ 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 ); @@ -183,7 +277,7 @@ bool LogWindow::saveLog( const QString& fileName ) 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(); @@ -191,68 +285,67 @@ bool LogWindow::saveLog( const QString& fileName ) } /*! - 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() { @@ -265,18 +358,18 @@ 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() { @@ -285,7 +378,7 @@ 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() { @@ -293,10 +386,47 @@ 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 +*/ diff --git a/src/LogWindow/LogWindow.h b/src/LogWindow/LogWindow.h index 0b8b39e98..b1816f8c8 100755 --- a/src/LogWindow/LogWindow.h +++ b/src/LogWindow/LogWindow.h @@ -20,64 +20,84 @@ // 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 -#include -#include +#include +#include +#include #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(); @@ -90,16 +110,16 @@ private: void updateActions(); private: - QTextBrowser* myView; - QString myBanner; - QString mySeparator; - QStringList myHistory; - int myBannerSize; - QMap 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 myActions; //!< popup menu actions }; #ifdef WIN32 #pragma warning( default:4251 ) #endif -#endif +#endif // LOGWINDOW_H diff --git a/src/LogWindow/LogWindow.pro b/src/LogWindow/LogWindow.pro new file mode 100644 index 000000000..8f50fc2ca --- /dev/null +++ b/src/LogWindow/LogWindow.pro @@ -0,0 +1,28 @@ +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 diff --git a/src/LogWindow/Makefile.am b/src/LogWindow/Makefile.am index 83dcacd43..898f1deaf 100755 --- a/src/LogWindow/Makefile.am +++ b/src/LogWindow/Makefile.am @@ -34,6 +34,7 @@ nodist_libLogWindow_la_SOURCES = $(MOC_FILES) 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 diff --git a/src/Makefile.am b/src/Makefile.am index 69a213ffb..82c33b34d 100755 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -24,7 +24,10 @@ # 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 @@ -37,22 +40,22 @@ endif 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 @@ -61,9 +64,11 @@ endif 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 diff --git a/src/OBJECT/OBJECT.pro b/src/OBJECT/OBJECT.pro new file mode 100644 index 000000000..c6f070833 --- /dev/null +++ b/src/OBJECT/OBJECT.pro @@ -0,0 +1,66 @@ +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 diff --git a/src/OCCViewer/Makefile.am b/src/OCCViewer/Makefile.am index c244074a1..bc14c02ef 100755 --- a/src/OCCViewer/Makefile.am +++ b/src/OCCViewer/Makefile.am @@ -92,4 +92,5 @@ nodist_salomeres_DATA = \ 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 diff --git a/src/OCCViewer/OCCViewer.h b/src/OCCViewer/OCCViewer.h index 724486cb9..199ca6a44 100755 --- a/src/OCCViewer/OCCViewer.h +++ b/src/OCCViewer/OCCViewer.h @@ -16,7 +16,7 @@ // // 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 @@ -26,6 +26,6 @@ #define OCCVIEWER_EXPORT #endif -#if defined WNT +#if defined WIN32 #pragma warning ( disable: 4251 ) #endif diff --git a/src/OCCViewer/OCCViewer.pro b/src/OCCViewer/OCCViewer.pro new file mode 100644 index 000000000..facc53204 --- /dev/null +++ b/src/OCCViewer/OCCViewer.pro @@ -0,0 +1,61 @@ +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 diff --git a/src/OCCViewer/OCCViewer_AISSelector.h b/src/OCCViewer/OCCViewer_AISSelector.h index 740c8f013..66267f938 100755 --- a/src/OCCViewer/OCCViewer_AISSelector.h +++ b/src/OCCViewer/OCCViewer_AISSelector.h @@ -20,7 +20,7 @@ #define OCCVIEWER_AISSELECTOR_H #include "OCCViewer.h" -#include +#include #include #include diff --git a/src/OCCViewer/OCCViewer_ClippingDlg.cxx b/src/OCCViewer/OCCViewer_ClippingDlg.cxx index 106e28b8f..9bfb92de5 100644 --- a/src/OCCViewer/OCCViewer_ClippingDlg.cxx +++ b/src/OCCViewer/OCCViewer_ClippingDlg.cxx @@ -18,16 +18,16 @@ // #include "OCCViewer_ClippingDlg.h" -#include +#include #include #include "SUIT_Session.h" #include "SUIT_ViewWindow.h" +#include "SUIT_ViewManager.h" #include "OCCViewer_ViewWindow.h" #include "OCCViewer_ViewPort3d.h" #include -//#include #include #include #include @@ -39,13 +39,15 @@ #include // QT Includes -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /*! Constructor @@ -55,22 +57,23 @@ \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 ); @@ -80,97 +83,111 @@ OCCViewer_ClippingDlg::OCCViewer_ClippingDlg( OCCViewer_ViewWindow* view, QWidge 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 ); @@ -178,10 +195,12 @@ OCCViewer_ClippingDlg::OCCViewer_ClippingDlg( OCCViewer_ViewWindow* view, QWidge 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 ); @@ -248,7 +267,7 @@ void OCCViewer_ClippingDlg::closeEvent( QCloseEvent* e ) aView3d->SetPlaneOn( myClippingPlane ); if (!myView->isCuttingPlane()) - myAction->setOn( false ); + myAction->setChecked( false ); QDialog::closeEvent( e ); } @@ -289,7 +308,7 @@ void OCCViewer_ClippingDlg::ClickOnClose() aView3d->SetPlaneOn( myClippingPlane ); if (!myView->isCuttingPlane()) - myAction->setOn( false ); + myAction->setChecked( false ); reject(); } @@ -451,9 +470,9 @@ void OCCViewer_ClippingDlg::displayPreview() 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 ); } } } @@ -565,7 +584,7 @@ void OCCViewer_ClippingDlg::ReserveClippingPlane() void OCCViewer_ClippingDlg::onViewShow() { - if(myAction->isOn()) + if(myAction->isChecked()) show(); else hide(); diff --git a/src/OCCViewer/OCCViewer_ClippingDlg.h b/src/OCCViewer/OCCViewer_ClippingDlg.h index bed795811..b50ff75f4 100644 --- a/src/OCCViewer/OCCViewer_ClippingDlg.h +++ b/src/OCCViewer/OCCViewer_ClippingDlg.h @@ -21,7 +21,7 @@ #include "OCCViewer.h" -#include +#include #include #include @@ -31,7 +31,7 @@ class QLabel; class QPushButton; class QComboBox; class QCheckBox; -class QtxDblSpinBox; +class QtxDoubleSpinBox; class QtxAction; class OCCViewer_ViewWindow; @@ -46,7 +46,7 @@ class OCCViewer_ClippingDlg : public QDialog 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; } @@ -66,18 +66,18 @@ private : 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; diff --git a/src/OCCViewer/OCCViewer_CreateRestoreViewDlg.cxx b/src/OCCViewer/OCCViewer_CreateRestoreViewDlg.cxx index e97cde8b9..e17fe3979 100755 --- a/src/OCCViewer/OCCViewer_CreateRestoreViewDlg.cxx +++ b/src/OCCViewer/OCCViewer_CreateRestoreViewDlg.cxx @@ -20,10 +20,12 @@ #include "OCCViewer_ViewModel.h" #include "OCCViewer_ViewPort3d.h" -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include /*! Constructor @@ -31,7 +33,7 @@ OCCViewer_CreateRestoreViewDlg::OCCViewer_CreateRestoreViewDlg( QWidget* aWin, OCCViewer_Viewer* curModel ) : QDialog( aWin ) { - setCaption( tr( "CAPTION" ) ); + setWindowTitle( tr( "CAPTION" ) ); myParametersMap = curModel->getViewAspects(); @@ -41,43 +43,48 @@ OCCViewer_CreateRestoreViewDlg::OCCViewer_CreateRestoreViewDlg( QWidget* aWin, O 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 ); @@ -109,51 +116,51 @@ OCCViewer_CreateRestoreViewDlg::~OCCViewer_CreateRestoreViewDlg() 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 ); + } } /*! @@ -161,7 +168,7 @@ void OCCViewer_CreateRestoreViewDlg::changeImage( QListBoxItem* curItem ) */ viewAspect OCCViewer_CreateRestoreViewDlg::currentItem() const { - return myCurrentItem; + return myCurrentItem; } /*! @@ -169,36 +176,36 @@ viewAspect OCCViewer_CreateRestoreViewDlg::currentItem() const */ 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" ); + } } /*! @@ -206,11 +213,10 @@ void OCCViewer_CreateRestoreViewDlg::deleteSelectedItems() */ 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(); } /*! @@ -218,17 +224,17 @@ void OCCViewer_CreateRestoreViewDlg::clearList() */ 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(); } /*! @@ -236,31 +242,31 @@ void OCCViewer_CreateRestoreViewDlg::editItemText( QListBoxItem* anItem ) */ 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 ); } /*! @@ -268,7 +274,7 @@ bool OCCViewer_CreateRestoreViewDlg::eventFilter( QObject* anObj, QEvent* anEv ) */ void OCCViewer_CreateRestoreViewDlg::OKpressed() { - emit dlgOk(); - accept(); + emit dlgOk(); + accept(); } diff --git a/src/OCCViewer/OCCViewer_CreateRestoreViewDlg.h b/src/OCCViewer/OCCViewer_CreateRestoreViewDlg.h index fc1579ae6..4673ab9a0 100755 --- a/src/OCCViewer/OCCViewer_CreateRestoreViewDlg.h +++ b/src/OCCViewer/OCCViewer_CreateRestoreViewDlg.h @@ -25,17 +25,15 @@ #include "OCCViewer_ViewWindow.h" #include -#include #include -#include -#include -#include -#include -#include +#include +#include class OCCViewer_ViewPort3d; +class QListWidgetItem; + #ifdef WIN32 #pragma warning( disable:4251 ) #endif @@ -48,26 +46,26 @@ public: 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 diff --git a/src/OCCViewer/OCCViewer_SetRotationPointDlg.cxx b/src/OCCViewer/OCCViewer_SetRotationPointDlg.cxx index 0aed2c230..c102afdb4 100644 --- a/src/OCCViewer/OCCViewer_SetRotationPointDlg.cxx +++ b/src/OCCViewer/OCCViewer_SetRotationPointDlg.cxx @@ -22,16 +22,14 @@ #include "OCCViewer_ViewWindow.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include /*! Constructor @@ -41,11 +39,14 @@ \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 @@ -54,35 +55,42 @@ OCCViewer_SetRotationPointDlg::OCCViewer_SetRotationPointDlg( OCCViewer_ViewWind 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)); @@ -90,7 +98,8 @@ OCCViewer_SetRotationPointDlg::OCCViewer_SetRotationPointDlg( OCCViewer_ViewWind 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)); @@ -98,7 +107,8 @@ OCCViewer_SetRotationPointDlg::OCCViewer_SetRotationPointDlg( OCCViewer_ViewWind 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)); @@ -119,7 +129,8 @@ OCCViewer_SetRotationPointDlg::OCCViewer_SetRotationPointDlg( OCCViewer_ViewWind 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())); @@ -128,12 +139,12 @@ OCCViewer_SetRotationPointDlg::OCCViewer_SetRotationPointDlg( OCCViewer_ViewWind 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()); @@ -166,10 +177,11 @@ void 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")) @@ -182,12 +194,12 @@ void 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(); } @@ -201,7 +213,7 @@ void OCCViewer_SetRotationPointDlg ::onToOrigin() { - if ( mySelectPoint->state() == QButton::On ) + if ( mySelectPoint->isChecked() ) mySelectPoint->toggle(); setCoords(); myView->activateSetRotationSelected(myX->text().toDouble(), @@ -213,7 +225,7 @@ void OCCViewer_SetRotationPointDlg ::onSelectPoint() { - if ( mySelectPoint->state() == QButton::On ) + if ( mySelectPoint->isChecked() ) myView->activateStartPointSelection(); else mySelectPoint->toggle(); @@ -225,7 +237,7 @@ OCCViewer_SetRotationPointDlg { if ( !myIsBBCenter->isChecked() ) { - if ( mySelectPoint->state() == QButton::On + if ( mySelectPoint->isChecked() && ( myX->hasFocus() || myY->hasFocus() || myZ->hasFocus() ) ) mySelectPoint->toggle(); @@ -256,7 +268,7 @@ void OCCViewer_SetRotationPointDlg ::onClickClose() { - myAction->setOn( false ); + myAction->setChecked( false ); reject(); } @@ -264,7 +276,7 @@ void OCCViewer_SetRotationPointDlg ::onViewShow() { - if(myAction->isOn()) + if(myAction->isChecked()) show(); else hide(); diff --git a/src/OCCViewer/OCCViewer_SetRotationPointDlg.h b/src/OCCViewer/OCCViewer_SetRotationPointDlg.h index 18c1f654e..2e3a465f8 100644 --- a/src/OCCViewer/OCCViewer_SetRotationPointDlg.h +++ b/src/OCCViewer/OCCViewer_SetRotationPointDlg.h @@ -21,14 +21,13 @@ #include "OCCViewer.h" -#include +#include class QtxAction; class QLineEdit; class QPushButton; class QGroupBox; -class QButtonGroup; class QCheckBox; class OCCViewer_ViewWindow; @@ -39,7 +38,7 @@ class OCCVIEWER_EXPORT OCCViewer_SetRotationPointDlg : public QDialog 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; } @@ -54,7 +53,7 @@ protected: QCheckBox* myIsBBCenter; - QButtonGroup* myGroupSelButton; + QGroupBox * myGroupBoxSel; QPushButton* myToOrigin; QPushButton* mySelectPoint; diff --git a/src/OCCViewer/OCCViewer_ViewManager.cxx b/src/OCCViewer/OCCViewer_ViewManager.cxx index 3d799109f..39c740c5d 100755 --- a/src/OCCViewer/OCCViewer_ViewManager.cxx +++ b/src/OCCViewer/OCCViewer_ViewManager.cxx @@ -40,7 +40,7 @@ OCCViewer_ViewManager::~OCCViewer_ViewManager() 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 diff --git a/src/OCCViewer/OCCViewer_ViewManager.h b/src/OCCViewer/OCCViewer_ViewManager.h index ea88d3577..c39e43cf8 100755 --- a/src/OCCViewer/OCCViewer_ViewManager.h +++ b/src/OCCViewer/OCCViewer_ViewManager.h @@ -35,7 +35,7 @@ public: OCCViewer_Viewer* getOCCViewer() { return (OCCViewer_Viewer*) myViewModel; } - virtual void contextMenuPopup( QPopupMenu* ); + virtual void contextMenuPopup( QMenu* ); }; #endif diff --git a/src/OCCViewer/OCCViewer_ViewModel.cxx b/src/OCCViewer/OCCViewer_ViewModel.cxx index a58e95624..235ce3983 100755 --- a/src/OCCViewer/OCCViewer_ViewModel.cxx +++ b/src/OCCViewer/OCCViewer_ViewModel.cxx @@ -23,17 +23,21 @@ #include "OCCViewer_ViewPort3d.h" #include "SUIT_ViewWindow.h" +#include "SUIT_ViewManager.h" #include "SUIT_Desktop.h" #include "SUIT_Session.h" -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include #include #include +#include #include #include @@ -156,7 +160,7 @@ void OCCViewer_Viewer::setViewManager(SUIT_ViewManager* theViewManager) 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*))); @@ -200,7 +204,7 @@ void OCCViewer_Viewer::onMouseRelease(SUIT_ViewWindow* theWindow, QMouseEvent* t 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(); @@ -251,10 +255,10 @@ void OCCViewer_Viewer::enableSelection(bool isEnabled) if ( !myViewManager ) return; - QPtrVector wins = myViewManager->getViews(); + QVector wins = myViewManager->getViews(); for ( int i = 0; i < (int)wins.count(); i++ ) { - OCCViewer_ViewWindow* win = ::qt_cast( wins.at( i ) ); + OCCViewer_ViewWindow* win = ::qobject_cast( wins.at( i ) ); if ( win ) win->updateEnabledDrawMode(); } @@ -271,10 +275,10 @@ void OCCViewer_Viewer::enableMultiselection(bool isEnable) if ( !myViewManager ) return; - QPtrVector wins = myViewManager->getViews(); + QVector wins = myViewManager->getViews(); for ( int i = 0; i < (int)wins.count(); i++ ) { - OCCViewer_ViewWindow* win = ::qt_cast( wins.at( i ) ); + OCCViewer_ViewWindow* win = ::qobject_cast( wins.at( i ) ); if ( win ) win->updateEnabledDrawMode(); } @@ -283,16 +287,16 @@ void OCCViewer_Viewer::enableMultiselection(bool isEnable) /*! 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() ) ); } /*! diff --git a/src/OCCViewer/OCCViewer_ViewModel.h b/src/OCCViewer/OCCViewer_ViewModel.h index 654dec238..b21b1660c 100755 --- a/src/OCCViewer/OCCViewer_ViewModel.h +++ b/src/OCCViewer/OCCViewer_ViewModel.h @@ -19,8 +19,8 @@ #ifndef OCCVIEWER_VIEWMODEL_H #define OCCVIEWER_VIEWMODEL_H -#include -#include +#include +#include #include "OCCViewer.h" @@ -28,13 +28,16 @@ #include #include -#include #include +class QMouseEvent; + class SUIT_ViewWindow; class SUIT_Desktop; class OCCViewer_ViewWindow; +class AIS_ListOfInteractive; + struct viewAspect { public: @@ -54,7 +57,7 @@ public: QString name; }; -typedef QValueList viewAspectList; +typedef QList viewAspectList; #ifdef WIN32 #pragma warning( disable:4251 ) @@ -72,17 +75,16 @@ public: 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 @@ -115,19 +117,16 @@ public: 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)& ); diff --git a/src/OCCViewer/OCCViewer_ViewPort.cxx b/src/OCCViewer/OCCViewer_ViewPort.cxx index ff4ef0551..510e9b575 100755 --- a/src/OCCViewer/OCCViewer_ViewPort.cxx +++ b/src/OCCViewer/OCCViewer_ViewPort.cxx @@ -25,13 +25,16 @@ #include "SUIT_Session.h" -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -70,104 +73,106 @@ CMapEntry::CMapEntry() CMapEntry::~CMapEntry() { if ( alloc ) - XFreeColormap( QPaintDevice::x11AppDisplay(), cmap ); + XFreeColormap( QX11Info::display(), cmap ); } -static QIntDict *cmap_dict = 0; +static QMultiHash *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; - 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; + const char *v = glXQueryServerString( dpy, vi->screen, GLX_VERSION ); + mesa_gl = strstr( v,"Mesa" ) != 0; + qAddPostRoutine( cleanup_cmaps ); + } + + QHash::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 @@ -176,7 +181,7 @@ static Colormap choose_cmap( Display *dpy, XVisualInfo *vi ) Constructor */ OCCViewer_ViewPort::OCCViewer_ViewPort( QWidget* parent ) -: QWidget( parent, 0, WRepaintNoErase | WResizeNoErase ) +: QWidget( parent ) { initialize(); } @@ -194,15 +199,14 @@ OCCViewer_ViewPort::~OCCViewer_ViewPort() */ 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 ); } /*! @@ -219,57 +223,57 @@ void OCCViewer_ViewPort::selectVisualId() { #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 ); @@ -297,7 +301,7 @@ void OCCViewer_ViewPort::selectVisualId() /* 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() ) @@ -307,7 +311,7 @@ void OCCViewer_ViewPort::selectVisualId() { XFree( (char *)pVisualInfo ); } - XFlush( x11Display() ); + XFlush( QX11Info::display() ); } #endif } @@ -318,7 +322,7 @@ void OCCViewer_ViewPort::selectVisualId() 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 ); @@ -329,7 +333,7 @@ void OCCViewer_ViewPort::setBackgroundColor( const QColor& color ) */ QColor OCCViewer_ViewPort::backgroundColor() const { - return palette().active().background(); + return palette().color( QPalette::Active, QPalette::Background ); } /*! @@ -466,6 +470,8 @@ void OCCViewer_ViewPort::onUpdate() { for ( QtxAction* a = myPopupActions.first(); a; a = myPopupActions.next() ) a->removeFrom( popup ); + //while (!myPopupActions.isEmpty()) + // delete myPopupActions.takeFirst(); myPopupActions.clear(); } }*/ diff --git a/src/OCCViewer/OCCViewer_ViewPort.h b/src/OCCViewer/OCCViewer_ViewPort.h index b4742b293..49fcc855f 100755 --- a/src/OCCViewer/OCCViewer_ViewPort.h +++ b/src/OCCViewer/OCCViewer_ViewPort.h @@ -23,17 +23,15 @@ #include "QtxAction.h" -#include -#include -#include +#include +#include #include +class QColor; class QRect; -class QCursor; class QPainter; class OCCViewer_ViewSketcher; -class OCCViewer_ViewTransformer; #ifdef WIN32 #pragma warning ( disable:4251 ) @@ -45,74 +43,74 @@ class OCCViewer_ViewTransformer; */ 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 myPopupActions; + Handle(Aspect_Window) myWindow; + bool myEnableSketching; + bool myEnableTransform; + bool myPaintersRedrawing; /* set to draw externally */ + QList myPopupActions; private: - static int nCounter; /* objects counter */ + static int nCounter; /* objects counter */ }; #ifdef WIN32 diff --git a/src/OCCViewer/OCCViewer_ViewPort3d.cxx b/src/OCCViewer/OCCViewer_ViewPort3d.cxx index cbeb3ce9c..0c5471704 100755 --- a/src/OCCViewer/OCCViewer_ViewPort3d.cxx +++ b/src/OCCViewer/OCCViewer_ViewPort3d.cxx @@ -22,11 +22,14 @@ #include "OCCViewer_VService.h" #include "OCCViewer_ViewWindow.h" -#include -#include -#include +#include +#include +#include +#include +#include #include +#include #include #include diff --git a/src/OCCViewer/OCCViewer_ViewPort3d.h b/src/OCCViewer/OCCViewer_ViewPort3d.h index 4f840bd02..1eb9689f9 100755 --- a/src/OCCViewer/OCCViewer_ViewPort3d.h +++ b/src/OCCViewer/OCCViewer_ViewPort3d.h @@ -21,35 +21,35 @@ #include "OCCViewer_ViewPort.h" -#include - #include -#include +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 ); @@ -63,34 +63,34 @@ public: // 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 diff --git a/src/OCCViewer/OCCViewer_ViewWindow.cxx b/src/OCCViewer/OCCViewer_ViewWindow.cxx index 0ec1a641d..69485ba30 100755 --- a/src/OCCViewer/OCCViewer_ViewWindow.cxx +++ b/src/OCCViewer/OCCViewer_ViewWindow.cxx @@ -29,24 +29,24 @@ #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 -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #include #include #include +#include #include #include @@ -189,6 +189,15 @@ OCCViewer_ViewWindow::OCCViewer_ViewWindow(SUIT_Desktop* theDesktop, OCCViewer_V updateEnabledDrawMode(); myClippingDlg = 0; mySetRotationPointDlg = 0; + myRectBand = 0; +} + +/*! + \brief Destructor. +*/ +OCCViewer_ViewWindow::~OCCViewer_ViewWindow() +{ + endDrawRect(); } /*! @@ -197,7 +206,7 @@ OCCViewer_ViewWindow::OCCViewer_ViewWindow(SUIT_Desktop* theDesktop, OCCViewer_V 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; @@ -211,8 +220,8 @@ void OCCViewer_ViewWindow::initLayout() 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(); @@ -225,13 +234,13 @@ void OCCViewer_ViewWindow::initLayout() 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; @@ -534,7 +543,7 @@ void OCCViewer_ViewWindow::activateSetRotationGravity() */ 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 ) ) @@ -680,10 +689,10 @@ void OCCViewer_ViewWindow::vpMouseMoveEvent(QMouseEvent* theEvent) 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(); @@ -711,11 +720,10 @@ void OCCViewer_ViewWindow::vpMouseReleaseEvent(QMouseEvent* theEvent) 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 ); } } @@ -739,7 +747,7 @@ void OCCViewer_ViewWindow::vpMouseReleaseEvent(QMouseEvent* theEvent) 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); @@ -755,6 +763,7 @@ void OCCViewer_ViewWindow::vpMouseReleaseEvent(QMouseEvent* theEvent) if ( theEvent->button() == Qt::LeftButton && myDrawRect ) { myDrawRect = false; drawRect(); + endDrawRect(); resetState(); myViewPort->update(); } @@ -768,10 +777,6 @@ void OCCViewer_ViewWindow::resetState() { myDrawRect = false; - /* make rectangle empty (left > right) */ - myRect.setLeft(2); - myRect.setRight(0); - if ( myRotationPointSelection ) { QCursor handCursor (Qt::PointingHandCursor); @@ -797,14 +802,26 @@ void OCCViewer_ViewWindow::resetState() */ 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; } /*! @@ -864,7 +881,7 @@ void OCCViewer_ViewWindow::createActions() 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; @@ -929,7 +946,7 @@ void OCCViewer_ViewWindow::createActions() 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; @@ -1106,7 +1123,7 @@ void OCCViewer_ViewWindow::onSetRotationPoint( bool on ) mySetRotationPointDlg->SetAction( mySetRotationPointAction ); } - if ( !mySetRotationPointDlg->isShown() ) + if ( !mySetRotationPointDlg->isVisible() ) { if ( mySetRotationPointDlg->IsFirstShown() ) { @@ -1119,7 +1136,7 @@ void OCCViewer_ViewWindow::onSetRotationPoint( bool on ) } else { - if ( mySetRotationPointDlg->isShown() ) + if ( mySetRotationPointDlg->isVisible() ) mySetRotationPointDlg->hide(); } } @@ -1140,9 +1157,9 @@ void OCCViewer_ViewWindow::onClipping( bool on ) { 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 ) { @@ -1152,12 +1169,12 @@ void OCCViewer_ViewWindow::onClipping( bool on ) myClippingDlg->SetAction( myClippingAction ); } - if ( !myClippingDlg->isShown() ) + if ( !myClippingDlg->isVisible() ) myClippingDlg->show(); } else { - if ( myClippingDlg->isShown() ) + if ( myClippingDlg->isVisible() ) myClippingDlg->hide(); setCuttingPlane(false); } @@ -1225,7 +1242,7 @@ void OCCViewer_ViewWindow::onTrihedronShow() QImage OCCViewer_ViewWindow::dumpView() { QPixmap px = QPixmap::grabWindow( myViewPort->winId() ); - return px.convertToImage(); + return px.toImage(); } /*! @@ -1337,7 +1354,7 @@ QString OCCViewer_ViewWindow::getVisualParameters() */ 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(); diff --git a/src/OCCViewer/OCCViewer_ViewWindow.h b/src/OCCViewer/OCCViewer_ViewWindow.h index 9c3841412..d5b7a9a5a 100755 --- a/src/OCCViewer/OCCViewer_ViewWindow.h +++ b/src/OCCViewer/OCCViewer_ViewWindow.h @@ -25,8 +25,9 @@ #include "QtxAction.h" -#include -#include +#include + +class QRubberBand; class SUIT_Desktop; class OCCViewer_ViewPort3d; @@ -50,7 +51,7 @@ public: enum RotationPointType{ GRAVITY, SELECTED }; OCCViewer_ViewWindow(SUIT_Desktop* theDesktop, OCCViewer_Viewer* theModel); - virtual ~OCCViewer_ViewWindow() {}; + virtual ~OCCViewer_ViewWindow(); OCCViewer_ViewPort3d* getViewPort() { return myViewPort; } @@ -135,6 +136,7 @@ protected: void resetState(); void drawRect(); + void endDrawRect(); void createActions(); void createToolBar(); @@ -167,7 +169,6 @@ protected: bool myEnableDrawMode; bool myPaintersRedrawing; // set to draw with external painters - QRect myRect; QCursor myCursor; QToolBar* myToolBar; @@ -181,7 +182,8 @@ private: OCCViewer_SetRotationPointDlg* mySetRotationPointDlg; QtxAction* mySetRotationPointAction; - + + QRubberBand* myRectBand; //!< selection rectangle rubber band }; #ifdef WIN32 diff --git a/src/OCCViewer/resources/OCCViewer_images.ts b/src/OCCViewer/resources/OCCViewer_images.ts new file mode 100644 index 000000000..033f26c5a --- /dev/null +++ b/src/OCCViewer/resources/OCCViewer_images.ts @@ -0,0 +1,89 @@ + + + @default + + ICON_OCCVIEWER_VIEW_GLOBALPAN + view_glpan.png + + + ICON_OCCVIEWER_CLIPPING_PRESSED + view_clipping_pressed.png + + + ICON_OCCVIEWER_VIEW_FITAREA + view_fitarea.png + + + ICON_OCCVIEWER_CLONE_VIEW + view_clone.png + + + ICON_OCCVIEWER_PRESETS_VIEW + view_presets.png + + + ICON_OCCVIEWER_VIEW_TOP + view_top.png + + + ICON_OCCVIEWER_VIEW_PAN + view_pan.png + + + ICON_OCCVIEWER_SHOOT_VIEW + view_shoot.png + + + ICON_OCCVIEWER_VIEW_ROTATION_POINT + view_rotation_point.png + + + ICON_OCCVIEWER_VIEW_DUMP + view_camera_dump.png + + + ICON_OCCVIEWER_VIEW_BACK + view_back.png + + + ICON_OCCVIEWER_VIEW_ZOOM + view_zoom.png + + + ICON_OCCVIEWER_VIEW_LEFT + view_left.png + + + ICON_OCCVIEWER_VIEW_FITALL + view_fitall.png + + + ICON_OCCVIEWER_VIEW_BOTTOM + view_bottom.png + + + ICON_OCCVIEWER_VIEW_ROTATE + view_rotate.png + + + ICON_OCCVIEWER_VIEW_FRONT + view_front.png + + + ICON_OCCVIEWER_VIEW_RESET + view_reset.png + + + ICON_OCCVIEWER_VIEW_RIGHT + view_right.png + + + ICON_OCCVIEWER_CLIPPING + view_clipping.png + + + ICON_OCCVIEWER_VIEW_TRIHEDRON + view_triedre.png + + + diff --git a/src/OCCViewer/resources/OCCViewer_msg_en.ts b/src/OCCViewer/resources/OCCViewer_msg_en.ts new file mode 100644 index 000000000..1e60f86a1 --- /dev/null +++ b/src/OCCViewer/resources/OCCViewer_msg_en.ts @@ -0,0 +1,265 @@ + + + @default + + MNU_FRONT_VIEW + Front + + + ERROR + Error + + + MNU_DUMP_VIEW + Dump view + + + DSC_TOP_VIEW + Top View + + + MNU_PAN_VIEW + Panning + + + MNU_CLONE_VIEW + Clone View + + + DSC_SHOW_TRIHEDRE + Show/Hide trihedron in the current view + + + MNU_SHOW_TRIHEDRE + Show/Hide trihedron + + + MNU_TOP_VIEW + Top + + + DSC_GLOBALPAN_VIEW + Selection of a new center of the view + + + DSC_ROTATE_VIEW + Rotation of the point of view around the scene center + + + MNU_ZOOM_VIEW + Zoom + + + DSC_PAN_VIEW + Panning the view + + + DSC_LEFT_VIEW + Left View + + + DSC_SHOOT_VIEW + Memorizes the state of the active view and adds it to the list + + + DSC_FITALL + Fit all objects inside the view frame + + + MNU_FITALL + Fit All + + + MNU_ROTATE_VIEW + Rotation + + + OCC_IMAGE_FILES + Images Files (*.bmp *.png *.jpg *.jpeg) + + + DSC_FRONT_VIEW + Front View + + + MNU_ROTATIONPOINTGRAVITY_VIEW + Rotation Point : the gravity center + + + MNU_GLOBALPAN_VIEW + Global Panning + + + INF_APP_DUMP_VIEW + Dump view + + + DSC_CLIPPING + Set clipping plane + + + DSC_CLONE_VIEW + Create new OCC viewer for the active scene + + + INF_APP_SHOOT_VIEW + Memorize view + + + MNU_CLIPPING + Clipping + + + MNU_BACK_VIEW + Back + + + MNU_SHOOT_VIEW + Memorize View + + + DSC_CHANGINGROTATIONPOINT_VIEW + Change the point, around which the rotation is performed + + + MNU_BOTTOM_VIEW + Bottom + + + MNU_RESET_VIEW + Reset + + + MNU_LEFT_VIEW + Left + + + DSC_RIGHT_VIEW + Right View + + + MNU_CHANGINGROTATIONPOINT_VIEW + Change Rotation Point + + + DSC_FITRECT + Fit area within the view frame + + + MNU_FITRECT + Fit Area + + + DSC_BOTTOM_VIEW + Bottom View + + + DSC_DUMP_VIEW + Saves the active view in the image file + + + DSC_ZOOM_VIEW + Zoom the view + + + MNU_ROTATIONPOINT000_VIEW + Rotation Point : (0,0,0) + + + MNU_ROTATIONPOINTSELECTED_VIEW + Rotation Point : the point selected by the user + + + DSC_RESET_VIEW + Reset View Point + + + ERR_DOC_CANT_SAVE_FILE + Cannot save file + + + DSC_PRESETS_VIEW + Selection of the memorized state of the active view + + + MNU_PRESETS_VIEW + Restore View + + + MNU_RIGHT_VIEW + Right + + + INF_APP_PRESETS_VIEW + Restore view + + + LBL_TOOLBAR_LABEL + View Operations + + + DSC_BACK_VIEW + Back View + + + + OCCViewer_CreateRestoreViewDlg + + CAPTION + Restore view + + + + OCCViewer_SetRotationPointDlg + + LBL_X + X : + + + LBL_Y + Y : + + + LBL_Z + Z : + + + USE_BBCENTER + Use Bounding Box Center + + + LBL_TOORIGIN + Set to Origin + + + CAPTION + Set Rotation Point + + + LBL_SELECTPOINT + Select Point from View + + + + OCCViewer_ViewManager + + OCC_VIEW_TITLE + OCC scene:%M - viewer:%V + + + + OCCViewer_Viewer + + MEN_DUMP_VIEW + Dump view... + + + MEN_SHOW_TOOLBAR + Show toolbar + + + MEN_CHANGE_BACKGROUD + Change background... + + + diff --git a/src/ObjBrowser/OB.h b/src/ObjBrowser/OB.h index 8b243affe..dd40fb973 100755 --- a/src/ObjBrowser/OB.h +++ b/src/ObjBrowser/OB.h @@ -20,13 +20,13 @@ #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 @@ -39,7 +39,7 @@ #define true 1 #endif -#if defined WNT +#if defined WIN32 #pragma warning ( disable: 4251 ) #endif diff --git a/src/ObjBrowser/OB_Browser.h b/src/ObjBrowser/OB_Browser.h index 2edf0239c..1175b7b9a 100755 --- a/src/ObjBrowser/OB_Browser.h +++ b/src/ObjBrowser/OB_Browser.h @@ -30,7 +30,7 @@ #include #include -#ifdef WNT +#ifdef WIN32 #pragma warning( disable:4251 ) #endif diff --git a/src/ObjBrowser/OB_ListItem.cxx b/src/ObjBrowser/OB_ListItem.cxx index f5fb6cb11..a66072a1b 100755 --- a/src/ObjBrowser/OB_ListItem.cxx +++ b/src/ObjBrowser/OB_ListItem.cxx @@ -28,7 +28,7 @@ #include using namespace std; -#ifdef WNT +#ifdef WIN32 #define min(a, b) (((a) < (b)) ? (a) : (b)) #endif @@ -287,11 +287,7 @@ QCheckListItem( parent, "", type ) */ OB_CheckListItem::OB_CheckListItem( SUIT_DataObject* obj, QListView* parent, QListViewItem* after, Type type ) : ListItemF( this, obj), -#if defined(QT_VERSION) && QT_VERSION >= 0x030101 QCheckListItem( parent, after, "", type ) -#else - QCheckListItem( parent, "", type ) -#endif { update(); } @@ -301,11 +297,7 @@ OB_CheckListItem::OB_CheckListItem( SUIT_DataObject* obj, QListView* parent, QLi */ OB_CheckListItem::OB_CheckListItem( SUIT_DataObject* obj, QListViewItem* parent, QListViewItem* after, Type type ) : ListItemF( this, obj), -#if defined(QT_VERSION) && QT_VERSION >= 0x030101 QCheckListItem( parent, after, "", type ) -#else - QCheckListItem( parent, "", type ) -#endif { update(); } diff --git a/src/ObjBrowser/resources/OB_msg_en.ts b/src/ObjBrowser/resources/OB_msg_en.ts new file mode 100644 index 000000000..b9f3dab3d --- /dev/null +++ b/src/ObjBrowser/resources/OB_msg_en.ts @@ -0,0 +1,9 @@ + + + @default + + MEN_EXPAND_ALL + Expand All + + + diff --git a/src/Plot2d/Plot2d.h b/src/Plot2d/Plot2d.h index 20deb6ec1..72e7b7017 100755 --- a/src/Plot2d/Plot2d.h +++ b/src/Plot2d/Plot2d.h @@ -16,7 +16,7 @@ // // 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 @@ -26,6 +26,6 @@ #define PLOT2D_EXPORT #endif -#if defined WNT +#if defined WIN32 #pragma warning ( disable: 4251 ) #endif diff --git a/src/Plot2d/Plot2d.pro b/src/Plot2d/Plot2d.pro new file mode 100644 index 000000000..8ce03642e --- /dev/null +++ b/src/Plot2d/Plot2d.pro @@ -0,0 +1,61 @@ +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 diff --git a/src/Plot2d/Plot2d_Curve.cxx b/src/Plot2d/Plot2d_Curve.cxx index bec633fdc..95bee5dc3 100755 --- a/src/Plot2d/Plot2d_Curve.cxx +++ b/src/Plot2d/Plot2d_Curve.cxx @@ -17,7 +17,7 @@ // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com // #include "Plot2d_Curve.h" -#include +#include /*! Constructor @@ -166,7 +166,7 @@ void Plot2d_Curve::insertPoint(int thePos, double theX, double theY, const QStri aPoint.y = theY; aPoint.text = txt; - QValueList::iterator aIt; + QList::iterator aIt; int aCurrent = 0; for(aIt = myPoints.begin(); aIt != myPoints.end(); ++aIt) { if (thePos == aCurrent) { @@ -183,15 +183,8 @@ void Plot2d_Curve::insertPoint(int thePos, double theX, double theY, const QStri */ void Plot2d_Curve::deletePoint(int thePos) { - QValueList::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 ); } /*! @@ -366,7 +359,7 @@ QwtPlot::Axis Plot2d_Curve::getYAxis() const */ double Plot2d_Curve::getMinX() const { - QValueList::const_iterator aIt; + QList::const_iterator aIt; double aMinX = 1e150; //int aCurrent = 0; for(aIt = myPoints.begin(); aIt != myPoints.end(); ++aIt) { @@ -381,7 +374,7 @@ double Plot2d_Curve::getMinX() const */ double Plot2d_Curve::getMinY() const { - QValueList::const_iterator aIt; + QList::const_iterator aIt; double aMinY = 1e150; //int aCurrent = 0; for(aIt = myPoints.begin(); aIt != myPoints.end(); ++aIt) { diff --git a/src/Plot2d/Plot2d_Curve.h b/src/Plot2d/Plot2d_Curve.h index bd3be97bd..a5d7cef73 100755 --- a/src/Plot2d/Plot2d_Curve.h +++ b/src/Plot2d/Plot2d_Curve.h @@ -20,8 +20,7 @@ #define PLOT2D_CURVE_H #include "Plot2d.h" -#include -#include +#include #include class QColor; @@ -33,7 +32,7 @@ typedef struct QString text; } Plot2d_Point; -typedef QValueList pointList; +typedef QList pointList; class PLOT2D_EXPORT Plot2d_Curve { @@ -107,6 +106,6 @@ protected: pointList myPoints; }; -typedef QPtrList curveList; +typedef QList curveList; #endif diff --git a/src/Plot2d/Plot2d_FitDataDlg.cxx b/src/Plot2d/Plot2d_FitDataDlg.cxx index 9ff544a07..f5141e1a7 100755 --- a/src/Plot2d/Plot2d_FitDataDlg.cxx +++ b/src/Plot2d/Plot2d_FitDataDlg.cxx @@ -22,13 +22,13 @@ // $Header$ #include "Plot2d_FitDataDlg.h" -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include #define SPACING_SIZE 6 #define MARGIN_SIZE 11 @@ -39,24 +39,22 @@ */ 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 ); @@ -122,45 +120,47 @@ Plot2d_FitDataDlg::Plot2d_FitDataDlg( QWidget* parent, bool secondAxisY ) 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 diff --git a/src/Plot2d/Plot2d_FitDataDlg.h b/src/Plot2d/Plot2d_FitDataDlg.h index ccecaaa32..096a8baa6 100755 --- a/src/Plot2d/Plot2d_FitDataDlg.h +++ b/src/Plot2d/Plot2d_FitDataDlg.h @@ -20,9 +20,9 @@ #define PLOT2D_FITDATADLG_H #include "Plot2d.h" -#include +#include -class QButtonGroup; +class QGroupBox; class QRadioButton; class QLineEdit; class QPushButton; @@ -57,7 +57,7 @@ protected slots: void onModeChanged(int); private: - QButtonGroup* myRangeGrp; + QGroupBox* myRangeGrp; QRadioButton* myModeAllRB; QRadioButton* myModeHorRB; QRadioButton* myModeVerRB; diff --git a/src/Plot2d/Plot2d_Prs.cxx b/src/Plot2d/Plot2d_Prs.cxx index 7c3bd0372..8c9d24109 100755 --- a/src/Plot2d/Plot2d_Prs.cxx +++ b/src/Plot2d/Plot2d_Prs.cxx @@ -33,18 +33,16 @@ 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 ); } @@ -53,6 +51,8 @@ Plot2d_Prs::Plot2d_Prs( const Plot2d_Curve* obj, bool theDelete ) */ Plot2d_Prs::~Plot2d_Prs() { + if ( myIsAutoDel ) + qDeleteAll( myCurves ); } /*! @@ -95,5 +95,5 @@ bool Plot2d_Prs::isSecondY() const */ void Plot2d_Prs::setAutoDel(bool theDel) { - myCurves.setAutoDelete(theDel); + myIsAutoDel = theDel; } diff --git a/src/Plot2d/Plot2d_Prs.h b/src/Plot2d/Plot2d_Prs.h index 2f98aadeb..a4fba43b0 100755 --- a/src/Plot2d/Plot2d_Prs.h +++ b/src/Plot2d/Plot2d_Prs.h @@ -41,6 +41,7 @@ public: protected: curveList myCurves; bool mySecondY; + bool myIsAutoDel; }; #endif diff --git a/src/Plot2d/Plot2d_SetupCurveDlg.cxx b/src/Plot2d/Plot2d_SetupCurveDlg.cxx index 4873db496..4bd211758 100644 --- a/src/Plot2d/Plot2d_SetupCurveDlg.cxx +++ b/src/Plot2d/Plot2d_SetupCurveDlg.cxx @@ -34,7 +34,7 @@ #include #include -#ifndef WNT +#ifndef WIN32 using namespace std; #endif @@ -48,73 +48,78 @@ using namespace std; 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 ); @@ -148,7 +153,7 @@ Plot2d_SetupCurveDlg::~Plot2d_SetupCurveDlg() */ void Plot2d_SetupCurveDlg::setLine( const int line, const int width ) { - myLineCombo->setCurrentItem( line ); + myLineCombo->setCurrentIndex( line ); myLineSpin->setValue( width ); } /*! @@ -156,7 +161,7 @@ void Plot2d_SetupCurveDlg::setLine( const int line, const int width ) */ int Plot2d_SetupCurveDlg::getLine() const { - return myLineCombo->currentItem(); + return myLineCombo->currentIndex(); } /*! Gets line width @@ -170,14 +175,14 @@ int Plot2d_SetupCurveDlg::getLineWidth() const */ 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 @@ -185,12 +190,9 @@ int Plot2d_SetupCurveDlg::getMarker() const 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 ); } /*! @@ -198,7 +200,7 @@ void Plot2d_SetupCurveDlg::setColor( const QColor& color ) */ QColor Plot2d_SetupCurveDlg::getColor() const { - return myColorBtn->palette().active().button(); + return myColorBtn->palette().color( QPalette::Active, QPalette::Button ); } /*! button slot, invokes color selection dialog box diff --git a/src/Plot2d/Plot2d_SetupViewDlg.cxx b/src/Plot2d/Plot2d_SetupViewDlg.cxx index 9f1b2f03a..e89eaffc7 100755 --- a/src/Plot2d/Plot2d_SetupViewDlg.cxx +++ b/src/Plot2d/Plot2d_SetupViewDlg.cxx @@ -23,17 +23,17 @@ #include "Plot2d_SetupViewDlg.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #define MARGIN_SIZE 11 #define SPACING_SIZE 6 @@ -45,11 +45,12 @@ 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 ); @@ -62,24 +63,29 @@ Plot2d_SetupViewDlg::Plot2d_SetupViewDlg( QWidget* parent, bool showDefCheck, bo 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 ); @@ -90,23 +96,24 @@ Plot2d_SetupViewDlg::Plot2d_SetupViewDlg( QWidget* parent, bool showDefCheck, bo // 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 ); @@ -114,7 +121,8 @@ Plot2d_SetupViewDlg::Plot2d_SetupViewDlg( QWidget* parent, bool showDefCheck, bo 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); @@ -126,22 +134,27 @@ Plot2d_SetupViewDlg::Plot2d_SetupViewDlg( QWidget* parent, bool showDefCheck, bo 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 ); @@ -151,7 +164,7 @@ Plot2d_SetupViewDlg::Plot2d_SetupViewDlg( QWidget* parent, bool showDefCheck, bo 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" ) ); @@ -165,22 +178,27 @@ Plot2d_SetupViewDlg::Plot2d_SetupViewDlg( QWidget* parent, bool showDefCheck, bo 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 ); @@ -190,7 +208,7 @@ Plot2d_SetupViewDlg::Plot2d_SetupViewDlg( QWidget* parent, bool showDefCheck, bo 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" ) ); @@ -206,22 +224,27 @@ Plot2d_SetupViewDlg::Plot2d_SetupViewDlg( QWidget* parent, bool showDefCheck, bo 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 ); @@ -231,7 +254,7 @@ Plot2d_SetupViewDlg::Plot2d_SetupViewDlg( QWidget* parent, bool showDefCheck, bo 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" ) ); } @@ -244,7 +267,7 @@ Plot2d_SetupViewDlg::Plot2d_SetupViewDlg( QWidget* parent, bool showDefCheck, bo 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 */ @@ -259,24 +282,24 @@ Plot2d_SetupViewDlg::Plot2d_SetupViewDlg( QWidget* parent, bool showDefCheck, bo 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(); @@ -423,14 +446,14 @@ QString Plot2d_SetupViewDlg::getY2Title() */ 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 @@ -438,7 +461,7 @@ int Plot2d_SetupViewDlg::getCurveType() void Plot2d_SetupViewDlg::setLegend( bool enable, int pos ) { myLegendCheck->setChecked( enable ); - myLegendCombo->setCurrentItem( pos ); + myLegendCombo->setCurrentIndex( pos ); onLegendChecked(); } /*! @@ -453,7 +476,7 @@ bool Plot2d_SetupViewDlg::isLegendEnabled() */ int Plot2d_SetupViewDlg::getLegendPos() { - return myLegendCombo->currentItem(); + return myLegendCombo->currentIndex(); } /*! Sets marker size @@ -475,12 +498,9 @@ int Plot2d_SetupViewDlg::getMarkerSize() 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 ); } /*! @@ -488,7 +508,7 @@ void Plot2d_SetupViewDlg::setBackgroundColor( const QColor& color ) */ QColor Plot2d_SetupViewDlg::getBackgroundColor() { - return myBackgroundBtn->palette().active().button(); + return myBackgroundBtn->palette().color( QPalette::Active, QPalette::Button ); } /*! Sets major grid parameters @@ -573,22 +593,22 @@ void Plot2d_SetupViewDlg::getMinorGrid( bool& enableX, int& divX, */ 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 diff --git a/src/Plot2d/Plot2d_SetupViewDlg.h b/src/Plot2d/Plot2d_SetupViewDlg.h index 37db3d641..862e9978a 100755 --- a/src/Plot2d/Plot2d_SetupViewDlg.h +++ b/src/Plot2d/Plot2d_SetupViewDlg.h @@ -20,7 +20,7 @@ #define PLOT2D_SETUPVIEWDLG_H #include "Plot2d.h" -#include +#include class QSpinBox; class QCheckBox; diff --git a/src/Plot2d/Plot2d_ToolTip.cxx b/src/Plot2d/Plot2d_ToolTip.cxx index 3cdb1ba8a..bf94e310f 100644 --- a/src/Plot2d/Plot2d_ToolTip.cxx +++ b/src/Plot2d/Plot2d_ToolTip.cxx @@ -23,7 +23,9 @@ #include #include -#include +#include +#include +#include #include #include @@ -46,23 +48,19 @@ Plot2d_ToolTip::~Plot2d_ToolTip() 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++ ) @@ -86,7 +84,7 @@ bool Plot2d_ToolTip::eventFilter( QObject* o, QEvent* e ) if( e && e->type() == QEvent::MouseMove ) { QMouseEvent* me = ( QMouseEvent* )e; - if( me->state()==0 ) + if( me->modifiers()==0 ) return true; } return res; diff --git a/src/Plot2d/Plot2d_ToolTip.h b/src/Plot2d/Plot2d_ToolTip.h index a26c46a83..c2f2d785f 100644 --- a/src/Plot2d/Plot2d_ToolTip.h +++ b/src/Plot2d/Plot2d_ToolTip.h @@ -36,12 +36,11 @@ public: 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; diff --git a/src/Plot2d/Plot2d_ViewFrame.cxx b/src/Plot2d/Plot2d_ViewFrame.cxx index 55b805bfc..c7e9478e8 100755 --- a/src/Plot2d/Plot2d_ViewFrame.cxx +++ b/src/Plot2d/Plot2d_ViewFrame.cxx @@ -31,20 +31,30 @@ #include "SUIT_ResourceMgr.h" #include "SUIT_Application.h" -#include "qapplication.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include +#include +#include +#include +#include +#include +#include + #include #include #include @@ -138,13 +148,13 @@ const char* imageCrossCursor[] = { 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 ), @@ -153,6 +163,7 @@ Plot2d_ViewFrame::Plot2d_ViewFrame( QWidget* parent, const QString& title ) 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 ); @@ -161,13 +172,6 @@ Plot2d_ViewFrame::Plot2d_ViewFrame( QWidget* parent, const QString& title ) 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 ) ) ); @@ -196,15 +200,16 @@ Plot2d_ViewFrame::Plot2d_ViewFrame( QWidget* parent, const QString& title ) 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 @@ -224,7 +229,7 @@ QWidget* Plot2d_ViewFrame::getViewWidget() */ void Plot2d_ViewFrame::DisplayAll() { - QList clist; + QList clist; getCurves( clist ); for ( int i = 0; i < (int)clist.count(); i++ ) { updateCurve( clist.at( i ), false ); @@ -237,7 +242,7 @@ void Plot2d_ViewFrame::DisplayAll() void Plot2d_ViewFrame::EraseAll() { myPlot->clear(); - myCurves.clear(); + myPlot->getCurves().clear(); myPlot->replot(); } /*! @@ -285,6 +290,44 @@ void Plot2d_ViewFrame::Erase( const Plot2d_Prs* prs, const bool ) 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 */ @@ -332,10 +375,10 @@ void Plot2d_ViewFrame::readPreferences() 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 ) ); } /*! @@ -386,11 +429,13 @@ void Plot2d_ViewFrame::writePreferences() 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; @@ -399,8 +444,9 @@ QString Plot2d_ViewFrame::getInfo( const QPoint& pnt ) } } 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; @@ -409,9 +455,10 @@ QString Plot2d_ViewFrame::getInfo( const QPoint& pnt ) } } } - 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; @@ -420,8 +467,9 @@ QString Plot2d_ViewFrame::getInfo( const QPoint& pnt ) } } 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; @@ -431,10 +479,10 @@ QString Plot2d_ViewFrame::getInfo( const QPoint& pnt ) } } - 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 = ""; @@ -443,9 +491,10 @@ QString Plot2d_ViewFrame::getInfo( const QPoint& pnt ) 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; @@ -454,8 +503,9 @@ QString Plot2d_ViewFrame::getInfo( const QPoint& pnt ) } } 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; @@ -465,7 +515,7 @@ QString Plot2d_ViewFrame::getInfo( const QPoint& pnt ) } } 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 ); @@ -481,7 +531,7 @@ QString Plot2d_ViewFrame::getInfo( const QPoint& pnt ) */ 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; @@ -503,7 +553,7 @@ static QwtSymbol::Style plot2qwtMarker( Plot2d_Curve::MarkerType m ) ms = QwtSymbol::XCross; break; case Plot2d_Curve::None: default: - ms = QwtSymbol::None; break; + ms = QwtSymbol::NoSymbol; break; } return ms; } @@ -533,7 +583,7 @@ static Plot2d_Curve::MarkerType qwt2plotMarker( QwtSymbol::Style m ) 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; } @@ -604,21 +654,23 @@ void Plot2d_ViewFrame::displayCurve( Plot2d_Curve* curve, bool update ) 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 ) ) ); @@ -629,19 +681,14 @@ void Plot2d_ViewFrame::displayCurve( Plot2d_Curve* curve, bool update ) 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 ) @@ -653,16 +700,16 @@ void Plot2d_ViewFrame::displayCurve( Plot2d_Curve* curve, bool update ) */ void Plot2d_ViewFrame::displayCurves( const curveList& curves, bool update ) { - myPlot->setUpdatesEnabled( false ); - QPtrListIterator it(curves); + //myPlot->setUpdatesEnabled( false ); // call this function deprecate update of legend + QList::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(); } @@ -674,10 +721,11 @@ void Plot2d_ViewFrame::eraseCurve( Plot2d_Curve* curve, bool update ) { 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(); @@ -689,11 +737,11 @@ void Plot2d_ViewFrame::eraseCurve( Plot2d_Curve* curve, bool update ) */ void Plot2d_ViewFrame::eraseCurves( const curveList& curves, bool update ) { - QPtrListIterator it(curves); + QList::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 ) @@ -707,61 +755,52 @@ void Plot2d_ViewFrame::updateCurve( Plot2d_Curve* curve, bool 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 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& clist ) +int Plot2d_ViewFrame::getCurves( curveList& clist ) { clist.clear(); - clist.setAutoDelete( false ); - QIntDictIterator 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; } @@ -775,13 +814,12 @@ void Plot2d_ViewFrame::updateLegend( const Plot2d_Prs* prs ) return; curveList aCurves = prs->getCurves(); - QPtrListIterator it(aCurves); + QList::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() ); } } @@ -793,34 +831,26 @@ void Plot2d_ViewFrame::fitAll() // 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(); } @@ -830,7 +860,7 @@ void Plot2d_ViewFrame::fitAll() */ 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 ); @@ -861,9 +891,9 @@ void Plot2d_ViewFrame::fitData(const int mode, 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 ); @@ -877,10 +907,10 @@ void Plot2d_ViewFrame::getFitRanges(double& xMin,double& 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); @@ -888,8 +918,8 @@ void Plot2d_ViewFrame::getFitRanges(double& xMin,double& xMax, 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); } @@ -900,10 +930,10 @@ void Plot2d_ViewFrame::getFitRanges(double& xMin,double& xMax, */ 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) { @@ -1077,14 +1107,11 @@ void Plot2d_ViewFrame::onChangeBackground() void Plot2d_ViewFrame::setCurveType( int curveType, bool update ) { myCurveType = curveType; - QArray 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(); @@ -1096,9 +1123,10 @@ void Plot2d_ViewFrame::setCurveType( int curveType, bool update ) \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 ); } /*! @@ -1107,8 +1135,17 @@ void Plot2d_ViewFrame::setCurveTitle( int curveKey, const QString& 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(); } @@ -1119,18 +1156,19 @@ void Plot2d_ViewFrame::showLegend( bool show, bool update ) 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; } } @@ -1143,15 +1181,14 @@ void Plot2d_ViewFrame::setMarkerSize( const int size, bool update ) if ( myMarkerSize != size ) { myMarkerSize = size; - QArray 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 ) @@ -1165,16 +1202,16 @@ void Plot2d_ViewFrame::setMarkerSize( const int size, bool 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(); } /*! @@ -1195,11 +1232,16 @@ void Plot2d_ViewFrame::setXGrid( bool xMajorEnabled, const int xMajorMax, 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(); } @@ -1231,26 +1273,29 @@ void Plot2d_ViewFrame::setYGrid( bool yMajorEnabled, const int yMajorMax, 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(); @@ -1312,20 +1357,20 @@ void Plot2d_ViewFrame::setFont( const QFont& font, ObjectType type, bool update) { 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(); @@ -1339,13 +1384,13 @@ void Plot2d_ViewFrame::setHorScaleMode( const int mode, bool update ) // 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(); @@ -1360,14 +1405,14 @@ void Plot2d_ViewFrame::setVerScaleMode( const int mode, bool update ) // 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(); @@ -1392,37 +1437,34 @@ bool Plot2d_ViewFrame::isModeVerLinear() /*! 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(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); } @@ -1432,19 +1474,22 @@ void Plot2d_ViewFrame::plotMousePressed(const QMouseEvent& me ) /*! 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 { @@ -1452,25 +1497,21 @@ void Plot2d_ViewFrame::plotMouseMoved( const QMouseEvent& me ) 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(parent()); if (aParent) @@ -1485,24 +1526,66 @@ void Plot2d_ViewFrame::wheelEvent(QWheelEvent* event) 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 */ @@ -1511,7 +1594,6 @@ void Plot2d_ViewFrame::onViewPan() QCursor panCursor (Qt::SizeAllCursor); myPlot->canvas()->setCursor( panCursor ); myOperation = PanId; - qApp->installEventFilter( this ); } /*! View operations : Zoom view @@ -1522,7 +1604,6 @@ void Plot2d_ViewFrame::onViewZoom() QCursor zoomCursor (zoomPixmap); myPlot->canvas()->setCursor( zoomCursor ); myOperation = ZoomId; - qApp->installEventFilter( this ); } /*! View operations : Fot All @@ -1538,7 +1619,7 @@ void Plot2d_ViewFrame::onViewFitArea() { myPlot->canvas()->setCursor( QCursor( Qt::PointingHandCursor ) ); myOperation = FitAreaId; - qApp->installEventFilter( this ); + myPlot->setPickerMousePattern( Qt::LeftButton ); } /*! View operations : Global panning @@ -1548,24 +1629,23 @@ void Plot2d_ViewFrame::onViewGlobalPan() 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 ); } /*! @@ -1574,10 +1654,9 @@ void Plot2d_ViewFrame::onViewGlobalPan() bool Plot2d_ViewFrame::isXLogEnabled() const { bool allPositive = true; - QIntDictIterator 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; } @@ -1587,13 +1666,25 @@ bool Plot2d_ViewFrame::isXLogEnabled() const bool Plot2d_ViewFrame::isYLogEnabled() const { bool allPositive = true; - QIntDictIterator 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 */ @@ -1601,24 +1692,49 @@ Plot2d_Plot2d::Plot2d_Plot2d( QWidget* parent ) : 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 */ @@ -1753,27 +1869,57 @@ QSize Plot2d_Plot2d::minimumSizeHint() const // 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 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; @@ -1843,33 +1989,35 @@ void Plot2d_ViewFrame::copyPreferences( Plot2d_ViewFrame* vf ) #define BRACKETIZE(x) QString( "[ " ) + x + QString( " ]" ) void Plot2d_ViewFrame::updateTitles() { - QIntDictIterator it( myCurves ); + CurveDict::iterator it = myPlot->getCurves().begin(); + //QIntDictIterator 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 @@ -1913,7 +2061,6 @@ bool Plot2d_ViewFrame::print( const QString& file, const QString& format ) const { QPrinter* pr = new QPrinter( QPrinter::HighResolution ); pr->setPageSize( QPrinter::A4 ); - pr->setOutputToFile( true ); pr->setOutputFileName( file ); pr->setPrintProgram( "" ); pd = pr; @@ -1948,7 +2095,7 @@ QString Plot2d_ViewFrame::getVisualParameters() */ 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(); @@ -1967,8 +2114,8 @@ void Plot2d_ViewFrame::setVisualParameters( const QString& parameters ) 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 ); @@ -1980,20 +2127,20 @@ void Plot2d_ViewFrame::setVisualParameters( const QString& parameters ) 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(); } @@ -2002,20 +2149,17 @@ void Plot2d_ViewFrame::incrementalPan( const int incrX, const int incrY ) { 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(); } @@ -2075,7 +2219,7 @@ void Plot2d_ViewFrame::onZoomOut() 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(); diff --git a/src/Plot2d/Plot2d_ViewFrame.h b/src/Plot2d/Plot2d_ViewFrame.h index 108cbd957..ba9f2e5f8 100755 --- a/src/Plot2d/Plot2d_ViewFrame.h +++ b/src/Plot2d/Plot2d_ViewFrame.h @@ -20,14 +20,19 @@ #define PLOT2D_VIEWFRAME_H #include "Plot2d_Curve.h" -#include -#include +#include +#include +#include +#include class Plot2d_Plot2d; class Plot2d_Prs; class QCustomEvent; +class QwtPlotCurve; +class QwtPlotGrid; +class QwtPlotZoomer; -typedef QIntDict CurveDict; +typedef QMultiHash CurveDict; class PLOT2D_EXPORT Plot2d_ViewFrame : public QWidget { @@ -55,6 +60,8 @@ public: 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 ); @@ -64,8 +71,7 @@ public: 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 ); @@ -84,7 +90,7 @@ public: 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; } @@ -131,6 +137,9 @@ protected: 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(); @@ -150,11 +159,9 @@ public slots: 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: @@ -167,7 +174,6 @@ protected: Plot2d_Plot2d* myPlot; int myOperation; QPoint myPnt; - CurveDict myCurves; int myCurveType; bool myShowLegend; @@ -191,6 +197,8 @@ class Plot2d_Plot2d : public QwtPlot 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() { @@ -203,8 +211,13 @@ public: 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(); @@ -213,8 +226,11 @@ protected: bool existMarker( const QwtSymbol::Style typeMarker, const QColor& color, const Qt::PenStyle typeLine ); protected: - QValueList myColors; + CurveDict myCurves; + QwtPlotGrid* myGrid; + QList myColors; bool myIsPolished; + QwtPlotZoomer* myPlotZoomer; }; #endif diff --git a/src/Plot2d/Plot2d_ViewModel.cxx b/src/Plot2d/Plot2d_ViewModel.cxx index e689f6ef5..ecef0231d 100755 --- a/src/Plot2d/Plot2d_ViewModel.cxx +++ b/src/Plot2d/Plot2d_ViewModel.cxx @@ -24,7 +24,9 @@ #include "Plot2d_ViewFrame.h" #include "Plot2d_Prs.h" -#include +#include +#include +#include /*! Constructor @@ -61,20 +63,22 @@ SUIT_ViewWindow* Plot2d_Viewer::createView(SUIT_Desktop* theDesktop) 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(); } @@ -98,7 +102,7 @@ void Plot2d_Viewer::setPrs(Plot2d_Prs* thePrs) void Plot2d_Viewer::update() { SUIT_ViewManager* aMgr = getViewManager(); - QPtrVector aViews = aMgr->getViews(); + QVector aViews = aMgr->getViews(); unsigned int aSize = aViews.size(); for (uint i = 0; i < aSize; i++) { Plot2d_ViewWindow* aView = (Plot2d_ViewWindow*)aViews[i]; @@ -113,7 +117,7 @@ void Plot2d_Viewer::update() void Plot2d_Viewer::clearPrs() { SUIT_ViewManager* aMgr = getViewManager(); - QPtrVector aViews = aMgr->getViews(); + QVector aViews = aMgr->getViews(); unsigned int aSize = aViews.size(); for (uint i = 0; i < aSize; i++) { Plot2d_ViewWindow* aView = (Plot2d_ViewWindow*)aViews[i]; diff --git a/src/Plot2d/Plot2d_ViewModel.h b/src/Plot2d/Plot2d_ViewModel.h index 75445ff9b..db0c471d2 100755 --- a/src/Plot2d/Plot2d_ViewModel.h +++ b/src/Plot2d/Plot2d_ViewModel.h @@ -27,7 +27,7 @@ class SUIT_Desktop; class Plot2d_ViewFrame; class Plot2d_Prs; class QString; -class QPopupMenu; +class QMenu; class PLOT2D_EXPORT Plot2d_Viewer: public SUIT_ViewModel { @@ -42,7 +42,7 @@ public: 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(); diff --git a/src/Plot2d/Plot2d_ViewWindow.cxx b/src/Plot2d/Plot2d_ViewWindow.cxx index 1fdf78431..44e1dfa2a 100755 --- a/src/Plot2d/Plot2d_ViewWindow.cxx +++ b/src/Plot2d/Plot2d_ViewWindow.cxx @@ -29,10 +29,13 @@ #include "QtxAction.h" -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include /*! Constructor @@ -41,15 +44,13 @@ Plot2d_ViewWindow::Plot2d_ViewWindow(SUIT_Desktop* theDesktop, Plot2d_Viewer* th : 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(); @@ -59,6 +60,7 @@ Plot2d_ViewWindow::Plot2d_ViewWindow(SUIT_Desktop* theDesktop, Plot2d_Viewer* th connect(myViewFrame, SIGNAL(contextMenuRequested( QContextMenuEvent * )), this, SIGNAL(contextMenuRequested( QContextMenuEvent * )) ); + myViewFrame->installEventFilter( this ); } /*! @@ -75,33 +77,36 @@ Plot2d_ViewWindow::~Plot2d_ViewWindow() 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); @@ -195,7 +200,7 @@ void Plot2d_ViewWindow::createActions() 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 @@ -204,7 +209,7 @@ void Plot2d_ViewWindow::createActions() 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 @@ -213,7 +218,7 @@ void Plot2d_ViewWindow::createActions() 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) @@ -238,7 +243,7 @@ void Plot2d_ViewWindow::createActions() 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 @@ -263,7 +268,7 @@ void Plot2d_ViewWindow::createActions() 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())); @@ -271,7 +276,7 @@ void Plot2d_ViewWindow::createActions() 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())); @@ -280,7 +285,7 @@ void Plot2d_ViewWindow::createActions() 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())); @@ -288,10 +293,9 @@ void Plot2d_ViewWindow::createActions() 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())); - } /*! @@ -305,16 +309,19 @@ void Plot2d_ViewWindow::createToolBar() 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); @@ -336,12 +343,12 @@ void Plot2d_ViewWindow::onChangeHorMode() 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" : @@ -358,12 +365,12 @@ void Plot2d_ViewWindow::onChangeVerMode() 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" : @@ -380,9 +387,9 @@ void Plot2d_ViewWindow::onChangeCurveMode() 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); } /*! @@ -390,7 +397,7 @@ void Plot2d_ViewWindow::onChangeCurveMode() */ void Plot2d_ViewWindow::onChangeLegendMode() { - myActionsMap[ LegendId ]->setOn(myViewFrame->isLegendShow()); + myActionsMap[ LegendId ]->setChecked(myViewFrame->isLegendShow()); } /*! @@ -483,7 +490,7 @@ void Plot2d_ViewWindow::onCurves() */ 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(); } @@ -492,10 +499,10 @@ void Plot2d_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; @@ -545,5 +552,5 @@ void Plot2d_ViewWindow::setVisualParameters( const QString& parameters ) void Plot2d_ViewWindow::RefreshDumpImage() { QPixmap px = QPixmap::grabWindow( myViewFrame->winId() ); - myDumpImage = px.convertToImage(); + myDumpImage = px.toImage(); } diff --git a/src/Plot2d/Plot2d_ViewWindow.h b/src/Plot2d/Plot2d_ViewWindow.h index aa1d4dd62..3f1a9df68 100755 --- a/src/Plot2d/Plot2d_ViewWindow.h +++ b/src/Plot2d/Plot2d_ViewWindow.h @@ -21,8 +21,8 @@ #include "Plot2d.h" #include +#include -#include #ifdef WIN32 #pragma warning( disable:4251 ) @@ -33,6 +33,9 @@ class Plot2d_Viewer; class Plot2d_ViewFrame; class QtxAction; class SUIT_ToolButton; +class QImage; +class QMenu; +class QToolBar; class PLOT2D_EXPORT Plot2d_ViewWindow : public SUIT_ViewWindow { @@ -46,21 +49,19 @@ public: 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(); diff --git a/src/Plot2d/resources/Plot2d_images.ts b/src/Plot2d/resources/Plot2d_images.ts new file mode 100644 index 000000000..9f30f8668 --- /dev/null +++ b/src/Plot2d/resources/Plot2d_images.ts @@ -0,0 +1,69 @@ + + + @default + + ICON_PLOT2D_GLOBALPAN + plot2d_glpan.png + + + ICON_PLOT2D_CLONE_VIEW + plot2d_clone.png + + + ICON_PLOT2D_CURVES_POINTS + plot2d_points.png + + + ICON_PLOT2D_FIT_AREA + plot2d_fitarea.png + + + ICON_PLOT2D_DUMP + plot2d_camera_dump.png + + + ICON_PLOT2D_ZOOM + plot2d_zoom.png + + + ICON_PLOT2D_MODE_LINEAR_VER + plot2d_linear_y.png + + + ICON_PLOT2D_MODE_LINEAR_HOR + plot2d_linear.png + + + ICON_PLOT2D_PAN + plot2d_pan.png + + + ICON_PLOT2D_FIT_ALL + plot2d_fitall.png + + + ICON_PLOT2D_MODE_LOGARITHMIC_HOR + plot2d_log.png + + + ICON_PLOT2D_MODE_LOGARITHMIC_VER + plot2d_log_y.png + + + ICON_PLOT2D_SETTINGS + plot2d_settings.png + + + ICON_PLOT2D_CURVES_LINES + plot2d_lines.png + + + ICON_PLOT2D_CURVES_SPLINES + plot2d_splines.png + + + ICON_PLOT2D_SHOW_LEGEND + plot2d_legend.png + + + diff --git a/src/Plot2d/resources/Plot2d_msg_en.ts b/src/Plot2d/resources/Plot2d_msg_en.ts new file mode 100644 index 000000000..57b717de6 --- /dev/null +++ b/src/Plot2d/resources/Plot2d_msg_en.ts @@ -0,0 +1,501 @@ + + + @default + + PLOT2D_CURVE_TYPE_LBL + Curve type: + + + ERROR + Error + + + PLOT2D_SET_AS_DEFAULT_CHECK + Save settings as default + + + TLT_SETUP_CURVE + Setup Curve + + + MNU_DUMP_VIEW + Dump view... + + + PLOT2D_SCALE_MODE_HOR + Horizontal axis: + + + PLOT2D_SCALE_MODE_VER + Vertical axis: + + + MNU_PAN_VIEW + Panning + + + MNU_CLONE_VIEW + Clone View + + + POSTSCRIPT_FILES + PostScript files (*.ps) + + + DSC_GLOBALPAN_VIEW + Selection of a new center of the view + + + PRP_PLOT2D_MODE_LINEAR_VER + Switches view to linear scaling mode along vertical axis + + + PRP_PLOT2D_MODE_LINEAR_HOR + Switches view to linear scaling mode along horizontal axis + + + CURVE_LINE_WIDTH_LAB + Line width: + + + CURVE_TYPE_POPUP + Curve type + + + TOT_PLOT2D_MODE_LINEAR_VER + Vertical axis: linear + + + TOT_PLOT2D_MODE_LINEAR_HOR + Horizontal axis: linear + + + FIT_DATA_TLT + Fit Data Range + + + MNU_ZOOM_VIEW + Zoom + + + PLOT2D_GRID_TLT + Grid / Axes marks + + + DSC_PAN_VIEW + Panning the view + + + DASHDOT_LINE_LBL + DashDot + + + PRP_PLOT2D_CURVES_SPLINES + Switches view to splines mode + + + INF_AXES_X + Axis X + + + PLOT2D_SCALE_TLT + Scale mode + + + DSC_FITALL + Fit all objects inside the view frame + + + MNU_FITALL + Fit All + + + TOT_PLOT2D_MODE_LOGARITHMIC_HOR + Horizontal axis: logarithmic + + + TOT_PLOT2D_MODE_LOGARITHMIC_VER + Vertical axis: logarithmic + + + MNU_GLOBALPAN_VIEW + Global Panning + + + INF_APP_DUMP_VIEW + Dump view + + + PLOT2D_LEGEND_POSITION_BOTTOM + Bottom + + + INF_COORDINATES + Coordinates: X : %1, Y : %2 + + + DSC_CLONE_VIEW + Create new OCC viewer for the active scene + + + DASH_LINE_LBL + Dash + + + DTRIANGLE_MARKER_LBL + Downward triangle + + + UTRIANGLE_MARKER_LBL + Upward triangle + + + LTRIANGLE_MARKER_LBL + Leftward triangle + + + RTRIANGLE_MARKER_LBL + Rightward triangle + + + RECTANGLE_MARKER_LBL + Rectangle + + + TLT_SETUP_PLOT2D_VIEW + Plot 2d View Settings + + + CURVE_LINE_TYPE_LAB + Line type: + + + CROSS_MARKER_LBL + Cross + + + XCROSS_MARKER_LBL + Diagonal cross + + + PLOT2D_ENABLE_VER_TITLE + Vertical axis title + + + PLOT2D_ENABLE_HOR_TITLE + Horizontal axis title + + + TOT_PLOT2D_SETTINGS + Settings + + + PLOT2D_CURVE_TYPE_LINES + Lines + + + MEN_PLOT2D_CURVES_SPLINES + Draw splines + + + PRP_PLOT2D_MODE_LOGARITHMIC_HOR + Switches view to logarithmic scaling mode along horizontal axis + + + PRP_PLOT2D_MODE_LOGARITHMIC_VER + Switches view to logarithmic scaling mode along vertical axis + + + PLOT2D_IMAGE_FILES + Images Files (*.bmp *.png *.jpg *.jpeg) + + + PLOT2D_MAX_INTERVALS + Max intervals + + + INF_AXES_Y_LEFT + Axis Y Left + + + CURVE_COLOR_LAB + Color: + + + DIAMOND_MARKER_LBL + Diamond + + + PLOT2D_LEGEND_POSITION_TOP + Top + + + TOT_PLOT2D_CHANGE_BACKGROUND + Change background + + + MEN_PLOT2D_CHANGE_BACKGROUND + Change background... + + + PRP_PLOT2D_CHANGE_BACKGROUND + Change background color + + + SOLID_LINE_LBL + Solid + + + PLOT2D_GRID_ENABLE_VER_MAJOR + Vertical major + + + PLOT2D_GRID_ENABLE_HOR_MAJOR + Horizontal major + + + PLOT2D_GRID_ENABLE_VER_MINOR + Vertical minor + + + TOT_PLOT2D_CURVES_POINTS + Draw points + + + PLOT2D_GRID_ENABLE_HOR_MINOR + Horizontal minor + + + PLOT2D_BACKGROUND_COLOR_LBL + Background color: + + + WRN_XLOG_NOT_ALLOWED + Some points with non-positive abscissa values have been detected. +Logarithmic scale for abscissa axis is not allowed. + + + WRN_YLOG_NOT_ALLOWED + Some points with non-positive ordinate values have been detected. +Logarithmic scale for ordinate axis is not allowed. + + + DSC_FITRECT + Fit area within the view frame + + + PLOT2D_LEGEND_POSITION_LEFT + Left + + + MNU_FITRECT + Fit Area + + + DOT_LINE_LBL + Dot + + + MEN_PLOT2D_CURVES_POINTS + Draw points + + + PRP_PLOT2D_CURVES_POINTS + Switches view to points mode + + + PLOT2D_SCALE_MODE_LOGARITHMIC + Logarithmic + + + PLOT2D_LEGEND_POSITION_RIGHT + Right + + + DSC_DUMP_VIEW + Saves the active view in the image file + + + WARNING + Warning + + + PLOT2D_ENABLE_LEGEND + Show legend + + + DSC_ZOOM_VIEW + Zoom the view + + + PRP_PLOT2D_SETTINGS + Setups view properties + + + INF_COORDINATES_SOME_Y + Coordinates: X : %1, Y : %2 ( %3 ) + + + SCALING_POPUP + Scaling + + + PLOT2D_SCALE_MODE_LINEAR + Linear + + + TOT_PLOT2D_FITDATA + Fit range + + + PLOT2D_CURVE_TYPE_POINTS + Points + + + PLOT2D_CURVE_TYPE_SPLINE + Spline + + + MEN_PLOT2D_FITDATA + Fit &Range + + + MEN_PLOT2D_MODE_LOGARITHMIC_HOR + Horizontal axis: logarithmic + + + MEN_PLOT2D_MODE_LOGARITHMIC_VER + Vertical axis: logarithmic + + + PRP_PLOT2D_FITDATA + Fits view to the given data range + + + MEN_PLOT2D_MODE_LINEAR_VER + Vertical axis: linear + + + MEN_PLOT2D_MODE_LINEAR_HOR + Horizontal axis: linear + + + NONE_MARKER_LBL + None + + + ERR_DOC_CANT_SAVE_FILE + Cannot save file + + + MEN_PLOT2D_SHOW_LEGEND + Show &Legend + + + PRP_PLOT2D_SHOW_LEGEND + Enables/disables legend + + + TOT_PLOT2D_SHOW_LEGEND + Show Legend + + + INF_AXES_Y_RIGHT + Axis Y Right + + + DAHSDOTDOT_LINE_LBL + DashDotDot + + + TOT_PLOT2D_CURVES_SPLINES + Draw splines + + + CURVE_MARKER_TYPE_LAB + Marker type: + + + MEN_PLOT2D_SETTINGS + &Settings + + + CIRCLE_MARKER_LBL + Circle + + + LBL_TOOLBAR_LABEL + View Operations + + + NONE_LINE_LBL + None + + + PLOT2D_MARKER_SIZE_LBL + Marker size: + + + PLOT2D_ENABLE_MAIN_TITLE + Main title + + + TOT_PLOT2D_CURVES_LINES + Draw lines + + + PRP_PLOT2D_CURVES_LINES + Switches view to lines mode + + + MEN_PLOT2D_CURVES_LINES + Draw lines + + + + Plot2d_FitDataDlg + + FIT_HORIZONTAL + Fit horizontally + + + MIN_VALUE_LAB + Min: + + + VERTICAL_AXIS + Vertical axis + + + MAX_VALUE_LAB + Max: + + + HORIZONTAL_AXIS + Horizontal axis + + + VERTICAL_LEFT_AXIS + Vertical left axis + + + FIT_ALL + Fit both + + + VERTICAL_RIGHT_AXIS + Vertical right axis + + + FIT_VERTICAL + Fit vertically + + + + Plot2d_ViewManager + + PLOT2D_VIEW_TITLE + Plot2d scene:%M - viewer:%V + + + diff --git a/src/Prs/Prs.pro b/src/Prs/Prs.pro new file mode 100644 index 000000000..b8ea761ab --- /dev/null +++ b/src/Prs/Prs.pro @@ -0,0 +1,20 @@ +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 diff --git a/src/Prs/SALOME_Prs.cxx b/src/Prs/SALOME_Prs.cxx index b022d2573..2e685e8c6 100755 --- a/src/Prs/SALOME_Prs.cxx +++ b/src/Prs/SALOME_Prs.cxx @@ -209,7 +209,7 @@ void SALOME_View::EraseAll( const bool ) */ 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." ); } @@ -218,7 +218,7 @@ void SALOME_View::LocalSelection( const SALOME_OCCPrs*, const int ) */ 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." ); } @@ -227,7 +227,7 @@ void SALOME_View::LocalSelection( const SALOME_VTKPrs*, const int ) */ 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." ); } @@ -236,7 +236,7 @@ void SALOME_View::LocalSelection( const SALOME_Prs2d*, const int ) */ 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." ); } diff --git a/src/Prs/SALOME_Prs.h b/src/Prs/SALOME_Prs.h index fa7c62369..ba8562c9f 100755 --- a/src/Prs/SALOME_Prs.h +++ b/src/Prs/SALOME_Prs.h @@ -19,7 +19,7 @@ #ifndef SALOME_PRS_H #define SALOME_PRS_H -#ifdef WNT +#ifdef WIN32 #ifdef PRS_EXPORTS #define PRS_EXPORT __declspec(dllexport) #else @@ -185,11 +185,11 @@ public: 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. diff --git a/src/PyInterp/Makefile.am b/src/PyInterp/Makefile.am index 9a783f209..7a451b4ad 100755 --- a/src/PyInterp/Makefile.am +++ b/src/PyInterp/Makefile.am @@ -27,13 +27,13 @@ include $(top_srcdir)/adm_local/unix/make_common_starter.am 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 diff --git a/src/PyInterp/PyInterp.h b/src/PyInterp/PyInterp.h index af9536fd8..4f2777d00 100755 --- a/src/PyInterp/PyInterp.h +++ b/src/PyInterp/PyInterp.h @@ -16,24 +16,24 @@ // // 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 @@ -53,9 +53,9 @@ // ======================================================== // avoid warning messages -#ifdef WNT +#ifdef WIN32 #pragma warning (disable : 4786) #pragma warning (disable : 4251) #endif -#endif // _PYINTERP_H +#endif // PYINTERP_H diff --git a/src/PyInterp/PyInterp.pro b/src/PyInterp/PyInterp.pro new file mode 100644 index 000000000..4c35c06ae --- /dev/null +++ b/src/PyInterp/PyInterp.pro @@ -0,0 +1,33 @@ +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 diff --git a/src/PyInterp/PyInterp_Dispatcher.cxx b/src/PyInterp/PyInterp_Dispatcher.cxx index dd029a25b..e3adb001d 100755 --- a/src/PyInterp/PyInterp_Dispatcher.cxx +++ b/src/PyInterp/PyInterp_Dispatcher.cxx @@ -16,22 +16,17 @@ // // 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 -#include -#include +#include "PyInterp_Dispatcher.h" // !!! WARNING !!! THIS INCLUDE MUST BE THE VERY FIRST !!! +#include "PyInterp_Interp.h" +#include "PyInterp_Watcher.h" -#include -#include +#include +#include -//#include using namespace std; PyInterp_Dispatcher* PyInterp_Dispatcher::myInstance = 0; @@ -40,11 +35,16 @@ void PyInterp_Request::process() { 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() @@ -65,23 +65,22 @@ QEvent* PyInterp_Request::createEvent() const 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 ) @@ -123,8 +122,9 @@ PyInterp_Dispatcher::~PyInterp_Dispatcher() // Clear the request queue myQueueMutex.lock(); - for ( std::list::iterator it = myQueue.begin(); it != myQueue.end(); ++it ) - PyInterp_Request::Destroy( *it ); + QListIterator it( myQueue ); + while ( it.hasNext() ) + PyInterp_Request::Destroy( it.next() ); myQueue.clear(); myQueueMutex.unlock(); @@ -138,7 +138,7 @@ PyInterp_Dispatcher::~PyInterp_Dispatcher() bool PyInterp_Dispatcher::IsBusy() const { - return running(); + return isRunning(); } void PyInterp_Dispatcher::Exec( PyInterp_Request* theRequest ) @@ -149,11 +149,12 @@ 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() ) @@ -171,7 +172,7 @@ void PyInterp_Dispatcher::run() 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(); @@ -183,8 +184,8 @@ void PyInterp_Dispatcher::run() // 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") } @@ -203,13 +204,16 @@ void PyInterp_Dispatcher::objectDestroyed( const QObject* o ) // prepare for modification of the queue myQueueMutex.lock(); - for ( std::list::iterator it = myQueue.begin(); it != myQueue.end(); ++it ){ - if ( o == (*it)->getListener() ){ - (*it)->setListener( 0 ); // to prevent event posting - it = myQueue.erase( it ); + QMutableListIterator it( myQueue ); + while ( it.hasNext() ) + { + RequestPtr r = it.next(); + if ( o == r->listener() ) + { + r->setListener( 0 ); // to prevent event posting + it.remove(); } } myQueueMutex.unlock(); } - diff --git a/src/PyInterp/PyInterp_Dispatcher.h b/src/PyInterp/PyInterp_Dispatcher.h index 311c9e66f..511fbbdb4 100755 --- a/src/PyInterp/PyInterp_Dispatcher.h +++ b/src/PyInterp/PyInterp_Dispatcher.h @@ -16,25 +16,23 @@ // // 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 -#include +#include "PyInterp.h" // !!! WARNING !!! THIS INCLUDE MUST BE THE VERY FIRST !!! -#include +#include +#include +#include +#include class QObject; -class PyInterp_base; +class PyInterp_Interp; class PyInterp_Watcher; class PyInterp_Dispatcher; @@ -46,12 +44,12 @@ class PYINTERP_EXPORT PyInterp_Request 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 @@ -69,36 +67,35 @@ protected: 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& ); @@ -107,7 +104,7 @@ public: 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(); @@ -138,7 +135,7 @@ private: private: typedef PyInterp_Request* RequestPtr; - std::list myQueue; + QQueue myQueue; QMutex myQueueMutex; PyInterp_Watcher* myWatcher; @@ -147,4 +144,4 @@ private: friend class PyInterp_Watcher; }; -#endif +#endif // PYINTERP_DISPATCHER_H diff --git a/src/PyInterp/PyInterp_Interp.cxx b/src/PyInterp/PyInterp_Interp.cxx new file mode 100644 index 000000000..75503c3b3 --- /dev/null +++ b/src/PyInterp/PyInterp_Interp.cxx @@ -0,0 +1,330 @@ +// 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 + +#include +#include + +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; +} diff --git a/src/PyInterp/PyInterp_Interp.h b/src/PyInterp/PyInterp_Interp.h new file mode 100644 index 000000000..e68d0d909 --- /dev/null +++ b/src/PyInterp/PyInterp_Interp.h @@ -0,0 +1,106 @@ +// 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 +#include + +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 _history; + std::list::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 diff --git a/src/PyInterp/PyInterp_Watcher.h b/src/PyInterp/PyInterp_Watcher.h index 551eca7d0..1d50f5bf8 100755 --- a/src/PyInterp/PyInterp_Watcher.h +++ b/src/PyInterp/PyInterp_Watcher.h @@ -16,14 +16,18 @@ // // 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 +#ifndef PYINTERP_WATCHER_H +#define PYINTERP_WATCHER_H -#include +#include "PyInterp.h" // !!! WARNING !!! THIS INCLUDE MUST BE THE VERY FIRST !!! -#include +#include "PyInterp_Dispatcher.h" + +#include // Private class that keeps track of destructions of request listeners class PYINTERP_EXPORT PyInterp_Watcher : public QObject @@ -38,4 +42,4 @@ public slots: void onDestroyed( QObject* o ) { PyInterp_Dispatcher::Get()->objectDestroyed( o ); } }; -#endif // _PYINTERP_WATCHER_H_ +#endif // PYINTERP_WATCHER_H diff --git a/src/PyInterp/PyInterp_base.cxx b/src/PyInterp/PyInterp_base.cxx deleted file mode 100644 index 7225855fe..000000000 --- a/src/PyInterp/PyInterp_base.cxx +++ /dev/null @@ -1,316 +0,0 @@ -// 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 -#include - -#include "PyInterp_base.h" // this include must be first (see PyInterp_base.h)! -#include - -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; -} diff --git a/src/PyInterp/PyInterp_base.h b/src/PyInterp/PyInterp_base.h deleted file mode 100644 index 71931655c..000000000 --- a/src/PyInterp/PyInterp_base.h +++ /dev/null @@ -1,145 +0,0 @@ -// 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 -#include -#include - -// include order important! -// pthread then python then qt -//#include // must be before Python.h ! - -#include // must be before qt includes ... -#include // Python include needed for versions before 2.4. Included in Python.h now. -#include // 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 _history; - std::list::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 diff --git a/src/PythonConsole/Makefile.am b/src/PythonConsole/Makefile.am deleted file mode 100755 index 8884cfa45..000000000 --- a/src/PythonConsole/Makefile.am +++ /dev/null @@ -1,50 +0,0 @@ -# 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) - - diff --git a/src/PythonConsole/PythonConsole.h b/src/PythonConsole/PythonConsole.h deleted file mode 100755 index 8e1db3946..000000000 --- a/src/PythonConsole/PythonConsole.h +++ /dev/null @@ -1,61 +0,0 @@ -// 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 - -#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 diff --git a/src/PythonConsole/PythonConsole_PyConsole.cxx b/src/PythonConsole/PythonConsole_PyConsole.cxx deleted file mode 100755 index 9c8f85237..000000000 --- a/src/PythonConsole/PythonConsole_PyConsole.cxx +++ /dev/null @@ -1,97 +0,0 @@ -// 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 -#include "PythonConsole_PyConsole.h" -#include "PythonConsole_PyEditor.h" -#include "PyInterp_base.h" - -#include "SUIT_Desktop.h" - -#include - -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; -} diff --git a/src/PythonConsole/PythonConsole_PyConsole.h b/src/PythonConsole/PythonConsole_PyConsole.h deleted file mode 100755 index b3364e597..000000000 --- a/src/PythonConsole/PythonConsole_PyConsole.h +++ /dev/null @@ -1,49 +0,0 @@ -// 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 - -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 diff --git a/src/PythonConsole/PythonConsole_PyEditor.cxx b/src/PythonConsole/PythonConsole_PyEditor.cxx deleted file mode 100755 index 30291e0c4..000000000 --- a/src/PythonConsole/PythonConsole_PyEditor.cxx +++ /dev/null @@ -1,764 +0,0 @@ -// 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 // this include must be first (see PyInterp_base.h)! - -#include - -#include -#include - -#include -#include -#include -#include -#include - -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 = "< 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 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 is pressed - bool ctrlPressed = e->state() & ControlButton; - // check if is pressed - bool shftPressed = e->state() & ShiftButton; - - // process + 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: - // key - { - moveCursor( QTextEdit::MoveEnd, false ); - QTextEdit::keyPressEvent( e ); - break; - } - case Key_Up: - // arrow key: process as follows: - // - without , modifiers: previous command in history - // - with modifier key pressed: move cursor one row up without selection - // - with modifier key pressed: move cursor one row up with selection - // - with + 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: - // arrow key: process as follows: - // - without , modifiers: next command in history - // - with modifier key pressed: move cursor one row down without selection - // - with modifier key pressed: move cursor one row down with selection - // - with + 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: - // arrow key: process as follows: - // - without , modifiers: move one symbol left (taking into account prompt) - // - with modifier key pressed: move one word left (taking into account prompt) - // - with modifier key pressed: move one symbol left with selection - // - with + 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: - // arrow key: process as follows: - // - without , modifiers: move one symbol right (taking into account prompt) - // - with modifier key pressed: move one word right (taking into account prompt) - // - with modifier key pressed: move one symbol right with selection - // - with + 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: - // key: process as follows: - // - without , modifiers: first command in history - // - with modifier key pressed: move cursor one page up without selection - // - with modifier key pressed: move cursor one page up with selection - // - with + 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: - // key: process as follows: - // - without , modifiers: last command in history - // - with modifier key pressed: move cursor one page down without selection - // - with modifier key pressed: move cursor one page down with selection - // - with + 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: - // key: process as follows: - // - without , modifiers: move cursor to the beginning of the current line without selection - // - with modifier key pressed: move cursor to the very first symbol without selection - // - with modifier key pressed: move cursor to the beginning of the current line with selection - // - with + 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: - // key: process as follows: - // - without , modifiers: move cursor to the end of the current line without selection - // - with modifier key pressed: move cursor to the very last symbol without selection - // - with modifier key pressed: move cursor to the end of the current line with selection - // - with + 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 : - // key: process as follows - // - without any modifiers : delete symbol before the cursor / selection (taking into account prompt) - // - with 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 : - // key: process as follows - // - without any modifiers : delete symbol after the cursor / selection (taking into account prompt) - // - with 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 : - // key: process as follows - // - with modifier key pressed: copy() - // - with 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( e ); - if ( pe ){ - ExecCommand* ec = dynamic_cast( 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 ids; - for ( int i = 0; popup && i < (int)popup->count(); i++ ) - { - if ( !popup->isItemEnabled( popup->idAt( i ) ) ) - ids.append( popup->idAt( i ) ); - } - - for ( QValueList::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; -} diff --git a/src/PythonConsole/PythonConsole_PyEditor.h b/src/PythonConsole/PythonConsole_PyEditor.h deleted file mode 100755 index b353ee4da..000000000 --- a/src/PythonConsole/PythonConsole_PyEditor.h +++ /dev/null @@ -1,79 +0,0 @@ -// 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 -#include - -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 diff --git a/src/PythonConsole/PythonConsole_PyInterp.cxx b/src/PythonConsole/PythonConsole_PyInterp.cxx deleted file mode 100755 index da23b5f04..000000000 --- a/src/PythonConsole/PythonConsole_PyInterp.cxx +++ /dev/null @@ -1,134 +0,0 @@ -// 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 = "<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 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 diff --git a/src/QDS/Makefile.am b/src/QDS/Makefile.am index 03513ac3c..6392bdf10 100755 --- a/src/QDS/Makefile.am +++ b/src/QDS/Makefile.am @@ -26,27 +26,42 @@ include $(top_srcdir)/adm_local/unix/make_common_starter.am 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 \ @@ -54,7 +69,13 @@ MOC_FILES= \ 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 diff --git a/src/QDS/QDS.cxx b/src/QDS/QDS.cxx index fb1cdae24..8bd4cf307 100644 --- a/src/QDS/QDS.cxx +++ b/src/QDS/QDS.cxx @@ -20,7 +20,7 @@ #include "QDS_Datum.h" -#include +#include #include #include @@ -28,10 +28,17 @@ #include #include -QValueList QDS::_datumList; +QList 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 ) { @@ -44,7 +51,9 @@ 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 ) { @@ -55,7 +64,9 @@ 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 ) { @@ -66,7 +77,9 @@ 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 ) { @@ -77,28 +90,31 @@ 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 ) { @@ -106,7 +122,9 @@ TCollection_AsciiString QDS::toAsciiString( const TCollection_ExtendedString& sr } /*! - 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 ) { @@ -117,7 +135,9 @@ TCollection_AsciiString QDS::toAsciiString( const Handle(TCollection_HExtendedSt } /*! - 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 ) { @@ -137,7 +157,9 @@ 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 ) { @@ -145,8 +167,8 @@ 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 ) { @@ -157,9 +179,15 @@ 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 ) { @@ -173,9 +201,16 @@ 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 ) { @@ -188,11 +223,18 @@ 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 ) { @@ -209,7 +251,7 @@ void QDS::setActiveUnitSystem( const QString& sys, const QString& comp ) return; TCollection_AsciiString aComp = toAsciiString( comp ); - for ( QValueList::iterator it = _datumList.begin(); it != _datumList.end(); ++it ) + for ( QList::iterator it = _datumList.begin(); it != _datumList.end(); ++it ) { QDS_Datum* datum = *it; if ( !datum ) @@ -228,8 +270,11 @@ void QDS::setActiveUnitSystem( const QString& sys, const QString& comp ) } /*! - 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 ) { @@ -240,13 +285,16 @@ 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) ); } diff --git a/src/QDS/QDS.h b/src/QDS/QDS.h index 6f3fecd85..c214bac1a 100644 --- a/src/QDS/QDS.h +++ b/src/QDS/QDS.h @@ -34,10 +34,8 @@ #pragma warning ( disable:4786 ) #endif -#include -#include - -#include +#include +#include #include @@ -48,7 +46,7 @@ class Handle(TCollection_HExtendedString); 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) @@ -87,7 +85,7 @@ protected: static void removeDatum( QDS_Datum* ); private: - static QValueList _datumList; + static QList _datumList; }; #endif diff --git a/src/QDS/QDS.pro b/src/QDS/QDS.pro new file mode 100644 index 000000000..c53a1a1ab --- /dev/null +++ b/src/QDS/QDS.pro @@ -0,0 +1,55 @@ +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 diff --git a/src/QDS/QDS_CheckBox.cxx b/src/QDS/QDS_CheckBox.cxx index 9713ca5e4..78c46469c 100644 --- a/src/QDS/QDS_CheckBox.cxx +++ b/src/QDS/QDS_CheckBox.cxx @@ -18,29 +18,45 @@ // #include "QDS_CheckBox.h" -#include +#include /* \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 ) @@ -48,14 +64,14 @@ QDS_CheckBox::QDS_CheckBox( const QString& id, QWidget* parent, const int flags, } /*! - 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() { @@ -63,20 +79,26 @@ 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 ) { @@ -88,22 +110,25 @@ 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( controlWidget() ); + return ::qobject_cast( 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 ) { @@ -115,7 +140,9 @@ 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() { @@ -123,17 +150,21 @@ 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 ) { @@ -142,9 +173,16 @@ 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 +*/ diff --git a/src/QDS/QDS_ComboBox.cxx b/src/QDS/QDS_ComboBox.cxx index ac068735e..163e25631 100644 --- a/src/QDS/QDS_ComboBox.cxx +++ b/src/QDS/QDS_ComboBox.cxx @@ -18,26 +18,41 @@ // #include "QDS_ComboBox.h" -#include +#include -#include #include #include -#include +#include /* \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 ) @@ -45,14 +60,15 @@ QDS_ComboBox::QDS_ComboBox( const QString& id, QWidget* parent, const int flags, } /*! - 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 { @@ -63,7 +79,8 @@ 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 ) { @@ -73,15 +90,18 @@ 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 { @@ -94,10 +114,13 @@ 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& ids, bool total ) const +void QDS_ComboBox::values( QList& ids, bool total ) const { ids.clear(); for ( QIntList::const_iterator it = myDataIds.begin(); it != myDataIds.end(); ++it ) @@ -106,23 +129,25 @@ void QDS_ComboBox::values( QValueList& ids, bool total ) const } /*! - 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 { @@ -130,17 +155,18 @@ 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 ) { @@ -153,7 +179,12 @@ 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 ) { @@ -167,7 +198,9 @@ 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 { @@ -178,13 +211,20 @@ 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 lst; + QList lst; if ( id < 0 ) { for ( IdStateMap::Iterator it = myState.begin(); it != myState.end(); ++it ) @@ -197,11 +237,16 @@ void QDS_ComboBox::setState( const bool on, const int id, const bool append ) } /*! - 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& ids, const bool append ) +void QDS_ComboBox::setState( const bool on, const QList& ids, const bool append ) { initDatum(); @@ -212,21 +257,21 @@ void QDS_ComboBox::setState( const bool on, const QValueList& ids, const bo QMap 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; } } @@ -235,11 +280,16 @@ void QDS_ComboBox::setState( const bool on, const QValueList& ids, const bo } /*! - 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& ids, const QStringList& names ) +void QDS_ComboBox::setValues( const QList& ids, const QStringList& names ) { initDatum(); @@ -251,23 +301,32 @@ void QDS_ComboBox::setValues( const QValueList& ids, const QStringList& nam } /*! - 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() { @@ -283,7 +342,9 @@ 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 { @@ -291,7 +352,9 @@ 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 { @@ -302,7 +365,8 @@ 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 { @@ -310,7 +374,7 @@ QString QDS_ComboBox::getString() const QtxComboBox* cb = comboBox(); if ( cb ) { - if ( !cb->editable() ) + if ( !cb->isEditable() ) { if ( !cb->isCleared() ) res = cb->currentText(); @@ -322,7 +386,8 @@ QString QDS_ComboBox::getString() const } /*! - 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 ) { @@ -334,20 +399,20 @@ 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(); @@ -359,15 +424,18 @@ void QDS_ComboBox::setString( const QString& txt ) } /*! - Returns pointer to QtxComboBox widget. + \brief Get combo box widget. + \return internal combo box widget */ QtxComboBox* QDS_ComboBox::comboBox() const { - return ::qt_cast( controlWidget() ); + return ::qobject_cast( 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 ) { @@ -380,8 +448,11 @@ 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 ) { @@ -462,9 +533,10 @@ 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(); @@ -473,12 +545,13 @@ void QDS_ComboBox::onTextChanged( const QString& ) } /*! - 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 ) @@ -493,7 +566,7 @@ void QDS_ComboBox::onActivated( int idx ) } /*! - Updates ComboBox after have change of visible state or items have been inserted/removed. + \brief Update combo box. */ void QDS_ComboBox::updateComboBox() { @@ -507,7 +580,7 @@ void QDS_ComboBox::updateComboBox() { isClear = cb->isCleared(); - curId = getId( cb->currentItem() ); + curId = getId( cb->currentIndex() ); cb->clear(); } @@ -524,9 +597,9 @@ void QDS_ComboBox::updateComboBox() 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] ); } } @@ -536,19 +609,21 @@ void QDS_ComboBox::updateComboBox() 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 { @@ -559,7 +634,9 @@ 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 { @@ -568,27 +645,31 @@ 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 { @@ -597,7 +678,7 @@ 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(); @@ -610,3 +691,15 @@ int QDS_ComboBox::getId( const QString& str ) const 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 +*/ diff --git a/src/QDS/QDS_ComboBox.h b/src/QDS/QDS_ComboBox.h index 2a8791702..25f4c423d 100644 --- a/src/QDS/QDS_ComboBox.h +++ b/src/QDS/QDS_ComboBox.h @@ -21,13 +21,15 @@ #include "QDS_Datum.h" -#include -#include -#include +#include +#include +#include -#include +#include -#ifdef WNT +class QtxComboBox; + +#ifdef WIN32 #pragma warning( disable:4251 ) #endif @@ -43,7 +45,7 @@ public: void setEditable( const bool ); int count( bool = false ) const; - void values( QValueList&, bool = false ) const; + void values( QList&, bool = false ) const; virtual int integerValue() const; virtual double doubleValue() const; @@ -52,8 +54,8 @@ public: bool state( const int ) const; void setState( const bool, const int, const bool = true ); - void setState( const bool, const QValueList&, const bool = true ); - void setValues( const QValueList&, const QStringList& ); + void setState( const bool, const QList&, const bool = true ); + void setValues( const QList&, const QStringList& ); void setValues( const QStringList& ); virtual void reset(); @@ -103,7 +105,7 @@ private: QStringList myUserNames; }; -#ifdef WNT +#ifdef WIN32 #pragma warning( default:4251 ) #endif diff --git a/src/QDS/QDS_Datum.cxx b/src/QDS/QDS_Datum.cxx index a542a19b4..04b3ca1d7 100644 --- a/src/QDS/QDS_Datum.cxx +++ b/src/QDS/QDS_Datum.cxx @@ -22,20 +22,21 @@ #include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include #include /*! - 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 @@ -52,26 +53,43 @@ public: 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 ) @@ -82,8 +100,12 @@ void QDS_Datum::Wrapper::setWidget( QWidget* 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 ); @@ -92,6 +114,10 @@ void QDS_Datum::Wrapper::setWidget( QWidget* wid ) updateGeometry(); } +/*! + \brief Set size policy of the widget. + \param sp new size policy +*/ void QDS_Datum::Wrapper::setSizePolicy( QSizePolicy sp ) { QWidget::setSizePolicy( sp ); @@ -100,6 +126,13 @@ void QDS_Datum::Wrapper::setSizePolicy( QSizePolicy 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 ); @@ -110,55 +143,75 @@ void QDS_Datum::Wrapper::setGeometry( int x, int y, int w, int 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 ) ); @@ -168,7 +221,7 @@ myInitialised( false ) myWrapper.insert( Units, new Wrapper( parent ) ); for ( QMap::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() ) @@ -191,8 +244,10 @@ myInitialised( false ) } /*! - 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() { @@ -208,7 +263,8 @@ 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 { @@ -216,7 +272,8 @@ QDS_Datum::operator QWidget*() const } /*! - Returns the datum id. + \brief Get the datum ID. + \return datum ID */ QString QDS_Datum::id() const { @@ -226,7 +283,8 @@ 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 { @@ -239,7 +297,8 @@ int QDS_Datum::type() const } /*! - Returns the datum label string. + \brief Get the datum label text. + \return label text */ QString QDS_Datum::label() const { @@ -256,7 +315,8 @@ QString QDS_Datum::label() const } /*! - Returns the datum units string. + \brief Get the datum units text. + \return units text */ QString QDS_Datum::units() const { @@ -269,7 +329,8 @@ 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 { @@ -282,7 +343,8 @@ 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 { @@ -295,7 +357,8 @@ 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 { @@ -308,7 +371,7 @@ 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() ); @@ -319,7 +382,8 @@ QString QDS_Datum::defaultValue() const } /*! - Returns the datum minimum value string. + \brief Get the datum minimum value. + \return minimum value */ QString QDS_Datum::minimumValue() const { @@ -332,7 +396,8 @@ 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 { @@ -345,7 +410,8 @@ 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 { @@ -358,7 +424,8 @@ 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 { @@ -371,7 +438,8 @@ 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 { @@ -387,8 +455,8 @@ 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 { @@ -399,8 +467,8 @@ 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 { @@ -411,33 +479,34 @@ 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 { @@ -448,7 +517,8 @@ 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 { @@ -461,8 +531,12 @@ 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 { @@ -482,8 +556,12 @@ 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 { @@ -503,7 +581,11 @@ 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 { @@ -525,7 +607,8 @@ 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 { @@ -533,7 +616,7 @@ 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() { @@ -550,7 +633,7 @@ void QDS_Datum::reset() } /*! - Clear the control. + \brief Clear the control. */ void QDS_Datum::clear() { @@ -570,18 +653,20 @@ 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 ) { @@ -599,8 +684,13 @@ 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 ) { @@ -622,8 +712,13 @@ 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 ) { @@ -645,7 +740,10 @@ 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 { @@ -662,8 +760,14 @@ 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 ) { @@ -678,7 +782,8 @@ 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 ) { @@ -686,8 +791,14 @@ 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 ) { @@ -703,8 +814,13 @@ 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 ) { @@ -712,8 +828,13 @@ 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 ) { @@ -721,8 +842,12 @@ 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 { @@ -731,7 +856,7 @@ 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() { @@ -742,8 +867,14 @@ 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 { @@ -828,7 +959,8 @@ bool QDS_Datum::isValid( const bool msgBox, const QString& extMsg, const QString } /*! - Add widgets to the vertical box layout. + \brief Add widgets to the vertical box layout. + \param l layout */ void QDS_Datum::addTo( QVBoxLayout* l ) { @@ -846,7 +978,8 @@ 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 ) { @@ -864,7 +997,11 @@ 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 ) { @@ -890,41 +1027,49 @@ void QDS_Datum::addTo( QGridLayout* theLay, const int theRow, const int theCol, } /*! - 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() { @@ -932,7 +1077,11 @@ 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 ) { @@ -940,7 +1089,8 @@ 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 { @@ -949,7 +1099,8 @@ 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 { @@ -958,7 +1109,8 @@ 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 { @@ -967,7 +1119,8 @@ 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 { @@ -975,7 +1128,8 @@ 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 ) { @@ -983,7 +1137,9 @@ 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 ) { @@ -991,7 +1147,9 @@ 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 ) { @@ -999,7 +1157,37 @@ 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 { @@ -1013,7 +1201,7 @@ 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 ); @@ -1063,7 +1251,9 @@ QValidator* QDS_Datum::validator( const bool limits ) const } /*! - 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 { @@ -1086,8 +1276,12 @@ 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() @@ -1118,9 +1312,9 @@ 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 ) ) @@ -1128,7 +1322,11 @@ void QDS_Datum::initialize() } /*! - 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 ) { @@ -1154,13 +1352,15 @@ 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( "" ) + aUnits.mid( pos + 2, 1 ) + QString( "" ) + @@ -1170,24 +1370,30 @@ QString QDS_Datum::unitsToText( const QString& uni ) } /*! - 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( "" ) ) != -1 ) + while ( ( pos = aUnits.indexOf( "" ) ) != -1 ) { aUnits.remove( pos, 5 ); aUnits.insert( pos, "**" ); } - while ( ( pos = aUnits.find( "" ) ) != -1 ) + while ( ( pos = aUnits.indexOf( "" ) ) != -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 ) { @@ -1214,7 +1420,11 @@ 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 ) { @@ -1241,7 +1451,11 @@ QString QDS_Datum::format( const double num, const QString& id, const bool conve } /*! - 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 ) { @@ -1268,7 +1482,11 @@ QString QDS_Datum::format( const QString& str, const QString& id, const bool con } /*! - 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 ) { @@ -1280,11 +1498,11 @@ QString QDS_Datum::format( const QString& aFormat, const int aType, const int aV { 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: @@ -1299,7 +1517,11 @@ QString QDS_Datum::format( const QString& aFormat, const int aType, const int aV } /*! - 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 ) { @@ -1310,16 +1532,16 @@ QString QDS_Datum::format( const QString& aFormat, const int aType, const double 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; } } @@ -1330,14 +1552,18 @@ QString QDS_Datum::format( const QString& aFormat, const int aType, const double } /*! - 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; @@ -1347,11 +1573,11 @@ QString QDS_Datum::format( const QString& aFormat, const int aType, const QStrin 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 ); @@ -1362,26 +1588,43 @@ QString QDS_Datum::format( const QString& aFormat, const int aType, const QStrin } /*! - 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 ) { @@ -1391,11 +1634,11 @@ 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; @@ -1412,16 +1655,18 @@ QString QDS_Datum::sprintf( const QString& fmt, const QString& val ) }*/ } - 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 ) { @@ -1430,7 +1675,10 @@ 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 ) { @@ -1438,7 +1686,7 @@ 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() ); @@ -1447,7 +1695,9 @@ QString QDS_Datum::canonicalFormat( const QString& fmt, QString& flags ) } /*! - 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 ) { @@ -1465,7 +1715,8 @@ 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 { @@ -1473,7 +1724,8 @@ 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 { @@ -1481,14 +1733,15 @@ 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() ); @@ -1500,14 +1753,15 @@ QString QDS_Datum::minValue() const } /*! - 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() ); @@ -1519,7 +1773,7 @@ QString QDS_Datum::maxValue() const } /*! - Reset the numeric value cache. + \brief Reset the numeric value cache. */ void QDS_Datum::invalidateCache() { @@ -1527,7 +1781,9 @@ 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 ) { @@ -1546,7 +1802,9 @@ 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 ) { @@ -1560,7 +1818,8 @@ bool QDS_Datum::isDoubleFormat( const QString& theFormat ) } /*! - Returns datum flags. + \brief Get datum flags. + \return datum flags (QDS::DatumFlags) */ int QDS_Datum::flags() const { @@ -1568,7 +1827,8 @@ int QDS_Datum::flags() const } /*! - Perform intialization if it needed. [internal] + \brief Perform initialization if it needed. + \internal */ void QDS_Datum::initDatum() const { @@ -1580,11 +1840,14 @@ 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 { @@ -1594,14 +1857,17 @@ QDS_Datum::Wrapper* QDS_Datum::wrapper( QWidget* wid ) const Wrapper* wrap = 0; for ( QMap::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 { @@ -1612,15 +1878,30 @@ 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::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 +*/ + diff --git a/src/QDS/QDS_Datum.h b/src/QDS/QDS_Datum.h index 9ff431f66..f0748f3e9 100644 --- a/src/QDS/QDS_Datum.h +++ b/src/QDS/QDS_Datum.h @@ -21,10 +21,9 @@ #include "QDS.h" -#include -#include -#include -#include +#include +#include +#include #include @@ -35,8 +34,6 @@ class QVBoxLayout; class QHBoxLayout; class QGridLayout; -class Handle(DDS_Dictionary); - class QDS_EXPORT QDS_Datum : public QObject, public QDS { Q_OBJECT @@ -183,8 +180,8 @@ private: static QString canonicalFormat( const QString&, QString& ); private: - typedef QGuardedPtr GuardedLabel; - typedef QGuardedPtr GuardedWidget; + typedef QPointer GuardedLabel; + typedef QPointer GuardedWidget; private: QString myId; diff --git a/src/QDS/QDS_LineEdit.cxx b/src/QDS/QDS_LineEdit.cxx index cb5ddf148..c978b13c6 100644 --- a/src/QDS/QDS_LineEdit.cxx +++ b/src/QDS/QDS_LineEdit.cxx @@ -18,12 +18,13 @@ // #include "QDS_LineEdit.h" -#include -#include +#include +#include -/* - 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 @@ -52,16 +53,30 @@ private: /* \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 ) @@ -69,15 +84,18 @@ QDS_LineEdit::QDS_LineEdit( const QString& id, QWidget* parent, const int flags, } /*! - 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 ) { @@ -88,14 +106,14 @@ 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++; @@ -112,12 +130,12 @@ void QDS_LineEdit::unitSystemChanged( const QString& system ) 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() { @@ -126,7 +144,7 @@ void QDS_LineEdit::selectAll() } /*! - Deselect all text in the editor. + \brief Deselect all text in the editor. */ void QDS_LineEdit::deselect() { @@ -135,7 +153,8 @@ 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 ) { @@ -146,7 +165,8 @@ 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 { @@ -154,18 +174,21 @@ 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 { @@ -176,7 +199,8 @@ 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 ) { @@ -185,15 +209,18 @@ 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( controlWidget() ); + return ::qobject_cast( 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 ) { @@ -204,9 +231,13 @@ 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(); @@ -217,7 +248,11 @@ void QDS_LineEdit::onTextChanged( const QString& ) } /*! - 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() { @@ -229,9 +264,14 @@ 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. +*/ diff --git a/src/QDS/QDS_RadioBox.cxx b/src/QDS/QDS_RadioBox.cxx index 44771f0fc..390a234f5 100644 --- a/src/QDS/QDS_RadioBox.cxx +++ b/src/QDS/QDS_RadioBox.cxx @@ -18,48 +18,62 @@ // #include "QDS_RadioBox.h" -#include - -#include #include #include -#include -#include -#include +#include +#include +#include +#include /* \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 { @@ -67,17 +81,18 @@ int QDS_RadioBox::count( bool total ) const return myValue.count(); else { - QPtrList bList; + QList 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& ids, bool total ) const +void QDS_RadioBox::values( QList& ids, bool total ) const { ids.clear(); for ( QIntList::const_iterator it = myDataIds.begin(); it != myDataIds.end(); ++it ) @@ -86,7 +101,9 @@ void QDS_RadioBox::values( QValueList& ids, bool total ) const } /*! - 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 { @@ -97,13 +114,20 @@ 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 lst; + QList lst; if ( id < 0 ) { for ( IdStateMap::Iterator it = myState.begin(); it != myState.end(); ++it ) @@ -116,11 +140,16 @@ void QDS_RadioBox::setState( const bool on, const int id, const bool append ) } /*! - 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& ids, const bool append ) +void QDS_RadioBox::setState( const bool on, const QList& ids, const bool append ) { if ( ids.isEmpty() && append ) return; @@ -129,21 +158,21 @@ void QDS_RadioBox::setState( const bool on, const QValueList& ids, const bo QMap 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; } } @@ -152,11 +181,16 @@ void QDS_RadioBox::setState( const bool on, const QValueList& ids, const bo } /*! - 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& ids, const QStringList& names ) +void QDS_RadioBox::setValues( const QList& ids, const QStringList& names ) { if ( ids.count() != names.count() ) return; @@ -166,21 +200,30 @@ void QDS_RadioBox::setValues( const QValueList& ids, const QStringList& nam } /*! - 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 { @@ -188,7 +231,7 @@ 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 ); } @@ -196,8 +239,11 @@ QString QDS_RadioBox::getString() const } /*! - 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 ) { @@ -205,14 +251,15 @@ void QDS_RadioBox::setString( const QString& txt ) if ( !bg ) return; - int oldId = bg->selectedId(); + int oldId = bg->checkedId(); if ( txt.isEmpty() ) { - QPtrList bList; + QList bList; buttons( bList ); - for ( QPtrListIterator it( bList ); it.current(); ++it ) - it.current()->setChecked( false ); + QListIterator it( bList ); + while ( it.hasNext() ) + it.next()->setChecked( false ); } else { @@ -223,11 +270,11 @@ void QDS_RadioBox::setString( const QString& txt ) 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 ) { @@ -240,27 +287,45 @@ void QDS_RadioBox::setString( const QString& txt ) } /*! - Returns pointer to QButtonGroup widget. + \brief Get internal button group. + \return pointer to the QButtonGroup object */ QButtonGroup* QDS_RadioBox::buttonGroup() const { - return ::qt_cast( controlWidget() ); + return myButtonGroup; +} + +/*! + \brief Get internal group box widget. + \return pointer to the QGroupBox widget +*/ +QGroupBox* QDS_RadioBox::groupBox() const +{ + return ::qobject_cast( 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 ) { @@ -325,15 +390,15 @@ 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 ) { @@ -347,7 +412,7 @@ 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() { @@ -355,12 +420,20 @@ void QDS_RadioBox::updateRadioBox() if ( !bg ) return; - int curId = bg->selectedId(); + QGroupBox* gb = groupBox(); + if ( !gb ) + return; + + int curId = bg->checkedId(); - QPtrList bList; + QList bList; buttons( bList ); - for ( QPtrListIterator itr( bList ); itr.current(); ++itr ) - delete itr.current(); + QListIterator 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 ) { @@ -368,8 +441,10 @@ void QDS_RadioBox::updateRadioBox() 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 ) ) ); } @@ -377,49 +452,49 @@ void QDS_RadioBox::updateRadioBox() if ( curId != -1 ) { int id = curId; - if ( !bg->find( id ) ) + if ( !bg->button( id ) ) { - QPtrList bList; + QList 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& lst ) const +void QDS_RadioBox::buttons( QList& 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( it.current() ); - if ( rb ) - lst.append( rb ); - } - } - delete objs; + QList objs = bg->findChildren(); + QListIterator 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 +*/ diff --git a/src/QDS/QDS_RadioBox.h b/src/QDS/QDS_RadioBox.h index 862b6ab4f..32d0f6f93 100644 --- a/src/QDS/QDS_RadioBox.h +++ b/src/QDS/QDS_RadioBox.h @@ -23,15 +23,15 @@ #include -#include -#include -#include +#include +#include -#ifdef WNT +#ifdef WIN32 #pragma warning( disable:4251 ) #endif class QButtonGroup; +class QGroupBox; class QRadioButton; class QDS_EXPORT QDS_RadioBox : public QDS_Datum @@ -43,15 +43,15 @@ public: virtual ~QDS_RadioBox(); int count( bool = false ) const; - void values( QValueList&, bool = false ) const; + void values( QList&, 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&, const bool = true ); - void setValues( const QValueList&, const QStringList& ); + void setState( const bool, const QList&, const bool = true ); + void setValues( const QList&, const QStringList& ); void setValues( const QStringList& ); signals: @@ -62,8 +62,9 @@ protected slots: protected: QButtonGroup* buttonGroup() const; + QGroupBox* groupBox() const; virtual QWidget* createControl( QWidget* ); - void buttons( QPtrList& ) const; + void buttons( QList& ) const; virtual QString getString() const; virtual void setString( const QString& ); @@ -84,9 +85,11 @@ private: QIntList myDataIds; QIntList myUserIds; QStringList myUserNames; + + QButtonGroup* myButtonGroup; }; -#ifdef WNT +#ifdef WIN32 #pragma warning( default:4251 ) #endif diff --git a/src/QDS/QDS_SpinBox.cxx b/src/QDS/QDS_SpinBox.cxx index 71864cb51..e3966a1c5 100644 --- a/src/QDS/QDS_SpinBox.cxx +++ b/src/QDS/QDS_SpinBox.cxx @@ -20,20 +20,29 @@ #include -#include - /* \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 ) @@ -41,14 +50,15 @@ QDS_SpinBox::QDS_SpinBox( const QString& id, QWidget* parent, const int flags, c } /*! - 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 { @@ -58,15 +68,16 @@ 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 ) { @@ -79,15 +90,18 @@ 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( controlWidget() ); + return ::qobject_cast( 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 ) { @@ -98,7 +112,11 @@ 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 ) { @@ -109,28 +127,33 @@ 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 ) { @@ -139,13 +162,15 @@ 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() ); } } diff --git a/src/QDS/QDS_SpinBoxDbl.cxx b/src/QDS/QDS_SpinBoxDbl.cxx index 0bd7bcf26..14fc48b2c 100644 --- a/src/QDS/QDS_SpinBoxDbl.cxx +++ b/src/QDS/QDS_SpinBoxDbl.cxx @@ -18,24 +18,31 @@ // #include "QDS_SpinBoxDbl.h" -#include - -#include - -#include +#include /* \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 ) @@ -43,19 +50,20 @@ QDS_SpinBoxDbl::QDS_SpinBoxDbl( const QString& id, QWidget* parent, const int fl } /*! - 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(); @@ -64,9 +72,9 @@ QString QDS_SpinBoxDbl::getString() const 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(); @@ -76,7 +84,8 @@ QString QDS_SpinBoxDbl::getString() const } /*! - 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 ) { @@ -89,26 +98,33 @@ 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( controlWidget() ); + return ::qobject_cast( 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 ) { @@ -120,40 +136,47 @@ 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() ); @@ -163,9 +186,9 @@ void QDS_SpinBoxDbl::unitSystemChanged( const QString& system ) 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() ); } diff --git a/src/QDS/QDS_SpinBoxDbl.h b/src/QDS/QDS_SpinBoxDbl.h index 362f75c7c..e801d6c5b 100644 --- a/src/QDS/QDS_SpinBoxDbl.h +++ b/src/QDS/QDS_SpinBoxDbl.h @@ -21,7 +21,7 @@ #include "QDS_Datum.h" -class QtxDblSpinBox; +class QtxDoubleSpinBox; class QDS_EXPORT QDS_SpinBoxDbl : public QDS_Datum { @@ -31,20 +31,20 @@ public: 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 diff --git a/src/QDS/QDS_Table.cxx b/src/QDS/QDS_Table.cxx index b14e80c8f..516c0a602 100644 --- a/src/QDS/QDS_Table.cxx +++ b/src/QDS/QDS_Table.cxx @@ -19,8 +19,6 @@ #include "QDS_Table.h" -#include "QDS_LineEdit.h" - class QDS_Table::DeleteFilter : public QObject { public: diff --git a/src/QDS/QDS_Table.h b/src/QDS/QDS_Table.h index c7d33abf9..bc6919781 100644 --- a/src/QDS/QDS_Table.h +++ b/src/QDS/QDS_Table.h @@ -23,8 +23,8 @@ #include -#include -#include +#include +#include class QDS_EXPORT QDS_Table : public QtxTable { @@ -82,7 +82,7 @@ private: QDS_Datum* datum( const QWidget* ) const; private: - typedef QPtrVector DatumVector; + typedef QVector DatumVector; typedef QMap DatumMap; typedef QMap CellMap; diff --git a/src/QDS/QDS_TextEdit.cxx b/src/QDS/QDS_TextEdit.cxx index 1eb66dad9..179032702 100644 --- a/src/QDS/QDS_TextEdit.cxx +++ b/src/QDS/QDS_TextEdit.cxx @@ -18,19 +18,31 @@ // #include "QDS_TextEdit.h" -#include +#include /* \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 ) @@ -38,25 +50,27 @@ QDS_TextEdit::QDS_TextEdit( const QString& id, QWidget* parent, const int flags, } /*! - 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 ) { @@ -65,15 +79,18 @@ 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( controlWidget() ); + return ::qobject_cast( 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 ) { @@ -83,6 +100,8 @@ 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() @@ -96,3 +115,8 @@ 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. +*/ diff --git a/src/QDS/QDS_Validator.cxx b/src/QDS/QDS_Validator.cxx index 37b2ea658..3388be3f0 100644 --- a/src/QDS/QDS_Validator.cxx +++ b/src/QDS/QDS_Validator.cxx @@ -20,15 +20,20 @@ /*! \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 ) @@ -36,29 +41,42 @@ QDS_IntegerValidator::QDS_IntegerValidator( QObject* 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 { @@ -67,22 +85,27 @@ QValidator::State QDS_IntegerValidator::validate( QString& input, int& pos ) con 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 ) @@ -90,29 +113,42 @@ QDS_DoubleValidator::QDS_DoubleValidator( QObject* 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 { @@ -121,59 +157,78 @@ QValidator::State QDS_DoubleValidator::validate( QString& input, int& pos ) cons 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 { @@ -181,8 +236,12 @@ 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 ) { @@ -190,14 +249,22 @@ 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 { @@ -205,10 +272,10 @@ QValidator::State QDS_StringValidator::validate( QString& input, int& pos ) cons 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; @@ -219,7 +286,7 @@ QValidator::State QDS_StringValidator::validate( QString& input, int& pos ) cons if ( !myFilter.isEmpty() ) rgState = QRegExpValidator( QRegExp( myFilter ), 0 ).validate( input, pos ); - svState = QMIN( svState, rgState ); + svState = qMin( svState, rgState ); return svState; } diff --git a/src/QDS/QDS_Validator.h b/src/QDS/QDS_Validator.h index e7fed65aa..5a81ebad1 100644 --- a/src/QDS/QDS_Validator.h +++ b/src/QDS/QDS_Validator.h @@ -21,11 +21,8 @@ #include "QDS.h" -#include +#include -/*! - class QDS_IntegerValidator -*/ class QDS_EXPORT QDS_IntegerValidator : public QIntValidator { public: @@ -36,12 +33,9 @@ public: virtual State validate( QString&, int& ) const; private: - QString myFilter; + QString myFilter; //!< string filter }; -/*! - class QDS_DoubleValidator -*/ class QDS_DoubleValidator : public QDoubleValidator { public: @@ -52,12 +46,9 @@ 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: @@ -72,9 +63,9 @@ 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 diff --git a/src/QDS/resources/QDS_msg_en.ts b/src/QDS/resources/QDS_msg_en.ts new file mode 100644 index 000000000..654bdc6cc --- /dev/null +++ b/src/QDS/resources/QDS_msg_en.ts @@ -0,0 +1,49 @@ + + + QDS_Datum + + DATA_ERR_TITLE + Incorrect parameter value + + + DATA_STRING + non-empty string + + + DATA_NON_EMPTY + non-empty + + + DATA_MIN_LIMIT + is greater than %1 + + + DATA_FLOAT + real + + + DATA_RANGE + in range [%1, %2] + + + DATA_SHOULD_BE_VALUE + Should be%1 value + + + DATA_INTEGER + integer + + + DATA_INCORRECT_VALUE + Value of parameter "%1" is incorrect. + + + DATA_MAX_LIMIT + is less than %1 + + + DATA_INPUT_VALUE + Please, input correct value. + + + diff --git a/src/Qtx/Makefile.am b/src/Qtx/Makefile.am index b71936b9a..5addbdd15 100755 --- a/src/Qtx/Makefile.am +++ b/src/Qtx/Makefile.am @@ -25,124 +25,139 @@ include $(top_srcdir)/adm_local/unix/make_common_starter.am # 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) diff --git a/src/Qtx/Qtx.cxx b/src/Qtx/Qtx.cxx index 6e2a31648..56ab7f332 100755 --- a/src/Qtx/Qtx.cxx +++ b/src/Qtx/Qtx.cxx @@ -1,17 +1,17 @@ // 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 @@ -21,60 +21,138 @@ #include "Qtx.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include /*! - 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; @@ -82,157 +160,125 @@ void Qtx::setTabOrder( const QWidgetList& widgets ) } /*! - 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 items = wid->actions(); + if ( items.isEmpty() ) return; - QIntList idRemove; - for ( uint i = 1; i < popup->count(); i++ ) + QList 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::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 ) { @@ -250,42 +296,68 @@ 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 ) { @@ -304,7 +376,7 @@ 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( "." ); @@ -319,113 +391,99 @@ QString Qtx::library( const QString& str ) } /*! - 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 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; @@ -471,7 +529,7 @@ bool Qtx::dos2unix( const QString& absName ) break; /* converted ok */ } ::fclose( src ); - ::fclose( tgt ); + ::fclose( tgt ); /* rename temp -> src */ if ( !QFile::remove( absName ) ) @@ -481,8 +539,9 @@ bool Qtx::dos2unix( const QString& 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 ) { @@ -490,8 +549,11 @@ 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 ) { @@ -499,19 +561,23 @@ 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 ) { @@ -521,8 +587,11 @@ 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 ) { @@ -530,7 +599,7 @@ 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 ) @@ -545,14 +614,15 @@ QColor Qtx::scaleColor( const int index, const int min, const int max ) } } - 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& lst ) +void Qtx::scaleColors( const int num, QColorList& lst ) { lst.clear(); for ( int i = 0; i < num; i++ ) @@ -560,8 +630,9 @@ void Qtx::scaleColors( const int num, QValueList& lst ) } /*! - 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 ) { @@ -589,26 +660,47 @@ 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 ) ); @@ -617,48 +709,58 @@ QImage Qtx::transparentImage( const int w, const int h, const int d ) } /*! - 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 { @@ -670,7 +772,7 @@ QPixmap Qtx::composite( const QPixmap& pix, const int x, const int y, const QPix } 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++ ) @@ -694,7 +796,7 @@ QPixmap Qtx::composite( const QPixmap& pix, const int x, const int y, const QPix } 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; diff --git a/src/Qtx/Qtx.h b/src/Qtx/Qtx.h index 0d5cb3a40..cd43bd5a6 100755 --- a/src/Qtx/Qtx.h +++ b/src/Qtx/Qtx.h @@ -42,81 +42,64 @@ #define true 1 #endif -#ifndef INCLUDE_MENUITEM_DEF -#define INCLUDE_MENUITEM_DEF -#endif - -#include - -#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 -#include +#include +#include +#include +#include +#include class QObject; -class QString; class QWidget; -class QToolBar; -class QGroupBox; -class QPopupMenu; -class QWidgetList; -template class QValueList; +typedef QList QIntList; //!< list of int values +typedef QList QShortList; //!< list of short int values +typedef QList QDoubleList; //!< list of double values +typedef QList QColorList; //!< list of colors -#if QT_VER < 3 -#define QPtrList QList -#define QPtrListIterator QListIterator -#endif - -typedef QValueList QIntList; -typedef QValueList QShortList; -typedef QValueList 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& ); @@ -129,11 +112,11 @@ public: 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& ); + static void scaleColors( const int, QColorList& ); static QImage grayscale( const QImage& ); static QPixmap grayscale( const QPixmap& ); diff --git a/src/Qtx/Qtx.pro b/src/Qtx/Qtx.pro new file mode 100644 index 000000000..276bdc778 --- /dev/null +++ b/src/Qtx/Qtx.pro @@ -0,0 +1,96 @@ +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 diff --git a/src/Qtx/QtxAction.cxx b/src/Qtx/QtxAction.cxx index dbae4819f..53f0f16e5 100755 --- a/src/Qtx/QtxAction.cxx +++ b/src/Qtx/QtxAction.cxx @@ -21,284 +21,208 @@ #include "QtxAction.h" -#include -#include +#include +#include +#include + +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( w ); - else if ( w->inherits( "QMenuBar" ) ) - pmd = ::qt_cast( 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() ); +} diff --git a/src/Qtx/QtxAction.h b/src/Qtx/QtxAction.h index af0473f3f..265a1a4bb 100755 --- a/src/Qtx/QtxAction.h +++ b/src/Qtx/QtxAction.h @@ -16,7 +16,7 @@ // // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com // -// File: QtxAction.hxx +// File: QtxAction.h // Author: Sergey TELKOV #ifndef QTXACTION_H @@ -24,32 +24,37 @@ #include "Qtx.h" -#include -#include +#include + +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 myMenuIds; + virtual void customEvent( QEvent* ); }; #ifdef WIN32 diff --git a/src/Qtx/QtxActionMenuMgr.cxx b/src/Qtx/QtxActionMenuMgr.cxx index 94f7050a0..6a6a5fe12 100644 --- a/src/Qtx/QtxActionMenuMgr.cxx +++ b/src/Qtx/QtxActionMenuMgr.cxx @@ -1,17 +1,17 @@ // 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 @@ -23,238 +23,96 @@ #include "QtxAction.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include // 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 prepareIds( const QWidget* w ) - { - QValueList l; - const QMenuData* md = 0; - if ( w->inherits( "QMenuBar" ) ) - md = ::qt_cast( w ); - else if ( w->inherits( "QPopupMenu" ) ) - md = ::qt_cast( 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& l, bool retId = true ) - { - const QMenuData* md = 0; - if ( w->inherits( "QMenuBar" ) ) - md = ::qt_cast( w ); - else if ( w->inherits( "QPopupMenu" ) ) - md = ::qt_cast( 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( w ); - else if ( w->inherits( "QPopupMenu" ) ) - md = ::qt_cast( 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 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 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 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 @@ -265,42 +123,44 @@ QtxActionMenuMgr::QtxActionMenuMgr( QMainWindow* p ) } /*! - 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 { @@ -309,10 +169,10 @@ 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 ) { @@ -322,38 +182,57 @@ void QtxActionMenuMgr::setVisible( const int actId, const int place, const bool } /*! - 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 ) { @@ -365,12 +244,19 @@ int QtxActionMenuMgr::insert( const int id, const QStringList& menus, const int } /*! - 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 ) { @@ -382,39 +268,36 @@ int QtxActionMenuMgr::insert( QAction* a, const QStringList& menus, const int gr } /*! - 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 ) { @@ -422,29 +305,28 @@ int QtxActionMenuMgr::insert( QAction* a, const int pId, const int group, const } /*! - 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 ) @@ -452,74 +334,83 @@ int QtxActionMenuMgr::insert( const QString& title, const int pId, const int gro 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 ) { @@ -527,11 +418,11 @@ 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 ) { @@ -539,25 +430,24 @@ 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 ) { @@ -565,11 +455,11 @@ 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 ) { @@ -577,8 +467,8 @@ 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 ) { @@ -587,33 +477,33 @@ 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 ) { @@ -621,8 +511,8 @@ 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 ) { @@ -630,8 +520,9 @@ 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 { @@ -643,31 +534,67 @@ 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 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( sender() ); + if ( m ) + emit menuAboutToShow( m ); +} - for ( QMap::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( 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 ) { @@ -676,7 +603,8 @@ 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 ) { @@ -684,29 +612,38 @@ 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; @@ -718,65 +655,70 @@ void QtxActionMenuMgr::setWidget( QWidget* mw ) 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 { @@ -784,89 +726,93 @@ QtxActionMenuMgr::MenuNode* QtxActionMenuMgr::find( const QString& title, 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 { @@ -874,12 +820,13 @@ 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]; @@ -888,18 +835,22 @@ QtxActionMenuMgr::MenuAction* QtxActionMenuMgr::menuAction( const int id ) const } /*! - 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 ) @@ -907,36 +858,32 @@ void QtxActionMenuMgr::updateMenu( MenuNode* startNode, const bool rec, const bo 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 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 ) @@ -945,20 +892,27 @@ void QtxActionMenuMgr::updateMenu( MenuNode* startNode, const bool rec, const bo 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 ); } } @@ -969,61 +923,61 @@ void QtxActionMenuMgr::updateMenu( MenuNode* startNode, const bool rec, const bo } /*! - 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 { @@ -1039,9 +993,10 @@ 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 ) { @@ -1050,8 +1005,8 @@ 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 ); @@ -1059,10 +1014,10 @@ int QtxActionMenuMgr::createMenu( const QStringList& lst, const int 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 ) { @@ -1071,9 +1026,10 @@ 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 { @@ -1081,41 +1037,90 @@ 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::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 ) @@ -1141,20 +1146,21 @@ int QtxActionMenuMgr::MenuCreator::append( const QString& tag, const bool subMen 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 ) ); @@ -1162,3 +1168,20 @@ int QtxActionMenuMgr::MenuCreator::append( const QString& tag, const bool subMen 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]. +*/ diff --git a/src/Qtx/QtxActionMenuMgr.h b/src/Qtx/QtxActionMenuMgr.h index bdbe139a4..c475de410 100644 --- a/src/Qtx/QtxActionMenuMgr.h +++ b/src/Qtx/QtxActionMenuMgr.h @@ -25,57 +25,23 @@ #include "Qtx.h" #include "QtxActionMgr.h" -#include -#include +#include -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 NodeList; - typedef QPtrListIterator 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 NodeList; //!< menu nodes list protected: class MenuCreator; @@ -85,6 +51,8 @@ public: 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 ); @@ -97,17 +65,17 @@ public: 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 ); @@ -118,21 +86,28 @@ public: 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; @@ -144,10 +119,11 @@ protected: 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; @@ -156,19 +132,18 @@ private: QString clearTitle( const QString& ) const; int createMenu( const QStringList&, const int ); -private: - typedef QMap MenuMap; + void triggerUpdate( const int, const bool rec = true ); private: - MenuNode myRoot; - QWidget* myMenu; - MenuMap myMenus; + typedef QMap MenuMap; //!< actions map + +private: + MenuNode* myRoot; //!< root menu node + QWidget* myMenu; //!< menu widget + MenuMap myMenus; //!< actions map + QMap 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: @@ -179,7 +154,7 @@ public: const ItemAttributes&, const int ); private: - QtxActionMenuMgr* myMgr; + QtxActionMenuMgr* myMgr; //!< menu manager }; diff --git a/src/Qtx/QtxActionMgr.cxx b/src/Qtx/QtxActionMgr.cxx index b157b835e..2ae9ebf02 100644 --- a/src/Qtx/QtxActionMgr.cxx +++ b/src/Qtx/QtxActionMgr.cxx @@ -1,17 +1,17 @@ // 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 @@ -22,26 +22,31 @@ #include "Qtx.h" #include "QtxActionMgr.h" #include "QtxAction.h" +#include +#include +#ifndef QT_NO_DOM +#include +#include +#include +#endif -#include -#include -#include -#include -#include -#include -#include - -static QAction* qtx_separator_action = 0; +typedef QList< QPointer > 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 @@ -49,132 +54,64 @@ class QtxActionMgr::SeparatorAction : public QtxAction public: SeparatorAction( QObject* = 0 ); virtual ~SeparatorAction(); - - virtual bool addTo( QWidget* ); - virtual bool removeFrom( QWidget* ); - -private: - QMap myMenus; - QMap 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 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 ) { @@ -201,8 +138,8 @@ 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 ) { @@ -211,8 +148,9 @@ 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 { @@ -223,8 +161,9 @@ 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 { @@ -234,7 +173,7 @@ 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(); } @@ -242,8 +181,9 @@ int QtxActionMgr::actionId( const QAction* a ) const } /*! - \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 { @@ -251,7 +191,8 @@ 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 { @@ -259,7 +200,8 @@ 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 { @@ -267,7 +209,8 @@ 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 { @@ -275,7 +218,8 @@ 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 { @@ -283,8 +227,8 @@ 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 ) { @@ -292,39 +236,62 @@ 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 { @@ -333,8 +300,9 @@ 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 { @@ -346,56 +314,113 @@ 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 { @@ -403,9 +428,13 @@ 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 { @@ -416,18 +445,41 @@ QString QtxActionMgr::Reader::option( const QString& name, const QString& def ) } /*! - 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, @@ -449,25 +501,29 @@ QtxActionMgr::XMLReader::XMLReader( const QString& root, } /*! - 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; @@ -501,10 +557,10 @@ bool QtxActionMgr::XMLReader::read( const QString& fname, Creator& cr ) const } /*! - 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, @@ -513,7 +569,7 @@ void QtxActionMgr::XMLReader::read( const QDomNode& parent_node, 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(); ioption( "icons_dir", "." ) ); + QStringList dirlist = reader()->option( "icons_dir", "." ).split( ";", QString::SkipEmptyParts ); QStringList::const_iterator anIt = dirlist.begin(), aLast = dirlist.end(); bool res = false; @@ -651,3 +734,19 @@ bool QtxActionMgr::Creator::loadPixmap( const QString& fname, QPixmap& pix ) con 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 +*/ diff --git a/src/Qtx/QtxActionMgr.h b/src/Qtx/QtxActionMgr.h index e0ba1d0e6..0c710386d 100644 --- a/src/Qtx/QtxActionMgr.h +++ b/src/Qtx/QtxActionMgr.h @@ -24,24 +24,19 @@ #include "Qtx.h" -#include -#include -#include +#include +#include +#include +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 @@ -87,23 +82,26 @@ protected: virtual void internalUpdate(); int generateId() const; + void triggerUpdate(); + virtual void updateContent(); + +private slots: + void onUpdateContent(); + private: - typedef QGuardedPtr ActionPtr; - typedef QMap ActionMap; + typedef QPointer ActionPtr; //!< Action guarded pointer + typedef QMap ActionMap; //!< Actions map private: - bool myUpdate; - ActionMap myActions; + bool myUpdate; //!< update flag + ActionMap myActions; //!< actions map + QTimer* myUpdTimer; //!< update timer }; -QTX_EXPORT typedef QMap ItemAttributes; +QTX_EXPORT typedef QMap 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* ); @@ -111,57 +109,47 @@ public: 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; }; diff --git a/src/Qtx/QtxActionSet.cxx b/src/Qtx/QtxActionSet.cxx new file mode 100644 index 000000000..7cfa6a63a --- /dev/null +++ b/src/Qtx/QtxActionSet.cxx @@ -0,0 +1,370 @@ +// 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 + - + - 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 QtxActionSet::actions() const +{ + return mySet; +} + +/*! + \brief Assign child actions. + \param lst list of actions +*/ +void QtxActionSet::setActions( const QList& 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& lst, const int index ) +{ + int idx = qMin( index < 0 ? mySet.count() : index, mySet.count() ); + + for ( QList::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( 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 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 lst = associatedWidgets(); + for ( QList::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 +*/ diff --git a/src/Qtx/QtxActionSet.h b/src/Qtx/QtxActionSet.h new file mode 100644 index 000000000..4de899787 --- /dev/null +++ b/src/Qtx/QtxActionSet.h @@ -0,0 +1,89 @@ +// 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 + +#ifdef WIN32 +#pragma warning( disable:4251 ) +#endif + +class QTX_EXPORT QtxActionSet : public QtxAction +{ + Q_OBJECT + +public: + QtxActionSet( QObject* = 0 ); + virtual ~QtxActionSet(); + + QList actions() const; + void setActions( const QList& ); + + void insertActions( const QList&, 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 ActionList; + +private: + ActionList mySet; //!< actions list +}; + +#ifdef WIN32 +#pragma warning( default:4251 ) +#endif + +#endif diff --git a/src/Qtx/QtxActionToolMgr.cxx b/src/Qtx/QtxActionToolMgr.cxx index 9ce569613..b4eb75794 100644 --- a/src/Qtx/QtxActionToolMgr.cxx +++ b/src/Qtx/QtxActionToolMgr.cxx @@ -24,27 +24,59 @@ #include "QtxAction.h" #include "QtxToolBar.h" -#include -#include +#include /*! - 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 { @@ -52,26 +84,30 @@ 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; @@ -81,7 +117,8 @@ int QtxActionToolMgr::createToolBar( const QString& name, const int tid ) if ( !tb ) { tb = new QtxToolBar( true, mainWindow() ); - tb->setLabel( name ); + mainWindow()->addToolBar( tb ); + tb->setWindowTitle( title ); } tInfo.toolBar = tb; @@ -91,34 +128,31 @@ int QtxActionToolMgr::createToolBar( const QString& name, const int tid ) } /*! - \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 lst = mw->dockWindows(); - for ( QPtrListIterator it( lst ); it.current() && !res; ++it ) + QList toolbars = qFindChildren( mw ); + for ( QList::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 ) { @@ -130,76 +164,80 @@ 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 ) { @@ -207,39 +245,43 @@ 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 ) { @@ -247,39 +289,42 @@ 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 ) { @@ -296,22 +341,23 @@ 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 { @@ -322,17 +368,19 @@ 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 { @@ -340,25 +388,28 @@ 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; @@ -368,7 +419,9 @@ bool QtxActionToolMgr::containsAction( const int id, const int tid ) const } /*! - 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() { @@ -376,112 +429,121 @@ 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 ) { @@ -490,15 +552,16 @@ 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 nodes; + QList 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; @@ -511,46 +574,48 @@ bool QtxActionToolMgr::isShown( const int id ) const return false; bool vis = true; - for ( QPtrListIterator itr( nodes ); itr.current() && vis; ++itr ) - vis = itr.current()->visible; + for ( QList::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; @@ -562,13 +627,14 @@ void QtxActionToolMgr::setVisible( const int id, const int tId, const bool on ) } 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 ) { @@ -576,9 +642,44 @@ 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::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 ) @@ -588,21 +689,24 @@ QtxActionToolMgr::ToolCreator::ToolCreator( QtxActionMgr::Reader* r, } /*! - 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; @@ -618,31 +722,28 @@ int QtxActionToolMgr::ToolCreator::append( const QString& tag, const bool subMen 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; } - - diff --git a/src/Qtx/QtxActionToolMgr.h b/src/Qtx/QtxActionToolMgr.h index 9300ec22a..56adc04d2 100644 --- a/src/Qtx/QtxActionToolMgr.h +++ b/src/Qtx/QtxActionToolMgr.h @@ -23,44 +23,34 @@ #define QTXACTIONTOOLMGR_H #include "Qtx.h" - -#include - #include "QtxActionMgr.h" +#include +#include + 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 NodeList; + typedef QList NodeList; //!< toolbar nodes list protected: class ToolCreator; @@ -122,22 +112,22 @@ protected: 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 ToolBarMap; + typedef struct { NodeList nodes; QToolBar* toolBar; } ToolBarInfo; //!< toolbar info + typedef QMap ToolBarMap; //!< toolbars map private: - ToolBarMap myToolBars; - QMainWindow* myMainWindow; + ToolBarMap myToolBars; //!< toobars map + QMainWindow* myMainWindow; //!< parent main window + QMap 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: @@ -148,7 +138,7 @@ public: const ItemAttributes&, const int ); private: - QtxActionToolMgr* myMgr; + QtxActionToolMgr* myMgr; //!< toolbar manager }; #endif diff --git a/src/Qtx/QtxColorScale.cxx b/src/Qtx/QtxColorScale.cxx index 30c919361..97b61a2b3 100755 --- a/src/Qtx/QtxColorScale.cxx +++ b/src/Qtx/QtxColorScale.cxx @@ -21,1175 +21,1072 @@ #include "QtxColorScale.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #include /*! - 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& list ) const +void QtxColorScale::colors( QList& 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& list ) +void QtxColorScale::setColors( const QList& 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 colors; - QValueList 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::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 colors; + QList 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::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 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 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( "

%1

" ); - break; - case Right: - aTitle = QString( "

%1

" ); - break; - case Center: - aTitle = QString( "

%1

" ); - 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( "

%1

" ); + break; + case Right: + aTitle = QString( "

%1

" ); + break; + case Center: + aTitle = QString( "

%1

" ); + 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 diff --git a/src/Qtx/QtxColorScale.h b/src/Qtx/QtxColorScale.h index bae5e9d63..ae9e985f2 100755 --- a/src/Qtx/QtxColorScale.h +++ b/src/Qtx/QtxColorScale.h @@ -24,165 +24,143 @@ #include "Qtx.h" -#include -#include +#include +#include -#if QT_VER == 3 -#include -#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& ) 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& ); - - 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& ) 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& ); + + 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 myColors; - QValueList 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 myColors; //!< list of colors + QList 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 diff --git a/src/Qtx/QtxComboBox.cxx b/src/Qtx/QtxComboBox.cxx index a2c95f251..96a1b8e0c 100755 --- a/src/Qtx/QtxComboBox.cxx +++ b/src/Qtx/QtxComboBox.cxx @@ -21,209 +21,220 @@ #include "QtxComboBox.h" -#include -#include -#include +#include /*! - 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 +*/ diff --git a/src/Qtx/QtxComboBox.h b/src/Qtx/QtxComboBox.h index 82c8989e0..9aae4eb72 100755 --- a/src/Qtx/QtxComboBox.h +++ b/src/Qtx/QtxComboBox.h @@ -24,8 +24,8 @@ #include "Qtx.h" -#include -#include +#include +#include #ifdef WIN32 #pragma warning( disable:4251 ) @@ -33,45 +33,45 @@ class QTX_EXPORT QtxComboBox : public QComboBox { - Q_OBJECT - - typedef QMap 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 diff --git a/src/Qtx/QtxDblSpinBox.cxx b/src/Qtx/QtxDblSpinBox.cxx deleted file mode 100755 index 59f9f6192..000000000 --- a/src/Qtx/QtxDblSpinBox.cxx +++ /dev/null @@ -1,603 +0,0 @@ -// 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 -#include -#include - -#include - -/*! - \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( 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; -} diff --git a/src/Qtx/QtxDblSpinBox.h b/src/Qtx/QtxDblSpinBox.h deleted file mode 100755 index b715fb3a2..000000000 --- a/src/Qtx/QtxDblSpinBox.h +++ /dev/null @@ -1,113 +0,0 @@ -// 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 - -/*! - \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 diff --git a/src/Qtx/QtxDblValidator.cxx b/src/Qtx/QtxDblValidator.cxx deleted file mode 100644 index b7dd3e9d0..000000000 --- a/src/Qtx/QtxDblValidator.cxx +++ /dev/null @@ -1,62 +0,0 @@ -// 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( dtop() ) - str = QString::number( top() ); - } - else - str = "0"; -} diff --git a/src/Qtx/QtxDblValidator.h b/src/Qtx/QtxDblValidator.h deleted file mode 100644 index a5b389fd1..000000000 --- a/src/Qtx/QtxDblValidator.h +++ /dev/null @@ -1,41 +0,0 @@ -// 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 - -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 diff --git a/src/Qtx/QtxDialog.cxx b/src/Qtx/QtxDialog.cxx index c52cb85fe..64e43c854 100755 --- a/src/Qtx/QtxDialog.cxx +++ b/src/Qtx/QtxDialog.cxx @@ -21,309 +21,319 @@ #include "QtxDialog.h" -#include "QtxGroupBox.h" - -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include /*! - 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& buttons() const; + const QList& buttons() const; private: - void updateBorder(); + void updateBorder(); private: - QtxDialog* myDlg; - QLabel* myLine; - bool myBorder; - int myPolicy; - QPtrList 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 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& QtxDialog::Area::buttons() const +const QList& 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 buttonId; - for ( QPtrListIterator it1( myButtons ); it1.current(); ++it1 ) - buttonId.insert( it1.current(), 0 ); - - QPtrList 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 it2( myButtons ); it2.current(); ++it2 ) - if ( buttonId[it2.current()] < 0 ) - src.append( it2.current() ); - - QPtrList left, right, center, other; - for ( QPtrListIterator 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 buttonId; + for ( QList::iterator it1 = myButtons.begin(); it1 != myButtons.end(); ++it1 ) + buttonId.insert( *it1, 0 ); + + QList 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::iterator it2 = myButtons.begin(); it2 != myButtons.end(); ++it2 ) + { + if ( buttonId[*it2] < 0 ) + src.append( *it2 ); + } + + QList left, right, center, other; + for ( QList::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 lit( left ); lit.current(); ++lit ) - buttonLayout->addWidget( lit.current() ); - buttonLayout->addStretch( 1 ); - for ( QPtrListIterator cit( center ); cit.current(); ++cit ) - buttonLayout->addWidget( cit.current() ); - buttonLayout->addStretch( 1 ); - for ( QPtrListIterator rit( right ); rit.current(); ++rit ) - buttonLayout->addWidget( rit.current() ); - } - else - { - for ( QPtrListIterator 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::iterator lit = left.begin(); lit != left.end(); ++lit ) + buttonLayout->addWidget( *lit ); + buttonLayout->addStretch( 1 ); + for ( QList::iterator cit = center.begin(); cit != center.end(); ++cit ) + buttonLayout->addWidget( *cit ); + buttonLayout->addStretch( 1 ); + for ( QList::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 ); @@ -332,40 +342,43 @@ void QtxDialog::Area::layoutButtons() /*! \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 ) { @@ -378,511 +391,528 @@ 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 changed; - for ( ButtonMap::Iterator it = map.begin(); it != map.end(); ++it ) - { - if ( myPosition[it.key()] == pos ) - continue; + QMap 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 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 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; @@ -891,498 +921,563 @@ uint QtxDialog::setAlignment( uint align ) } /*! - 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 QtxDialog::userButtonIds() const -{ - QValueList 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( 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() @@ -1393,62 +1488,103 @@ 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 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& lst = aIt.value()->buttons(); + for ( QList::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 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& lst = aItr.value()->buttons(); + for ( QList::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. +*/ diff --git a/src/Qtx/QtxDialog.h b/src/Qtx/QtxDialog.h index dbf4fbd9d..c77d0fa08 100755 --- a/src/Qtx/QtxDialog.h +++ b/src/Qtx/QtxDialog.h @@ -1,17 +1,17 @@ // 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 @@ -24,13 +24,12 @@ #include "Qtx.h" -#include -#include -#include +#include +#include class QFrame; class QLabel; -class QButton; +class QAbstractButton; #ifdef WIN32 #pragma warning( disable:4251 ) @@ -38,149 +37,163 @@ class QButton; 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 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 ButtonMap; + typedef QMap 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 AreaMap; - typedef QMap PositionMap; - - friend class Area; + typedef QMap AreaMap; //!< button area map + typedef QMap 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 diff --git a/src/Qtx/QtxDirListEditor.cxx b/src/Qtx/QtxDirListEditor.cxx index cd4bb9fcf..770cc58a0 100644 --- a/src/Qtx/QtxDirListEditor.cxx +++ b/src/Qtx/QtxDirListEditor.cxx @@ -242,7 +242,7 @@ bool QtxDirListEditor::validate( const bool quietMode ) { QString dirPath = QFileInfo( myEdit->text().stripWhiteSpace() ).filePath(); /* -#ifndef WNT +#ifndef WIN32 if ( dirPath.startsWith( "~") ) { dirPath = dirPath.remove(0,1); QString user; diff --git a/src/Qtx/QtxDirListEditor.h b/src/Qtx/QtxDirListEditor.h index 38d62dead..2edbfc7e6 100644 --- a/src/Qtx/QtxDirListEditor.h +++ b/src/Qtx/QtxDirListEditor.h @@ -34,7 +34,8 @@ /*! * \brief The GUI implementation of the directory list */ -class QTX_EXPORT QtxDirListEditor : public QWidget { +class QTX_EXPORT QtxDirListEditor : public QWidget +{ Q_OBJECT diff --git a/src/Qtx/QtxDockAction.cxx b/src/Qtx/QtxDockAction.cxx index 1b25e280a..8f40092d3 100755 --- a/src/Qtx/QtxDockAction.cxx +++ b/src/Qtx/QtxDockAction.cxx @@ -21,739 +21,150 @@ #include "QtxDockAction.h" -#include "QtxResourceMgr.h" - -#include -#include -#include -#include -#include -#include -#include - -/*! - 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 +#include +#include +#include /*! - 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 dwList; - - if ( dw ) - dwList.append( dw ); - else - dockWindows( dwList ); - - for ( QPtrListIterator 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 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::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& 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 dockList; - dockWindows( dockList, mainWindow() ); + lst.clear(); - if ( dockList.isEmpty() ) + QMainWindow* mw = mainWindow(); + if ( !mw ) return; - QPtrList toolBars, windows; - for ( QPtrListIterator 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 wit( windows ); wit.current(); ++wit ) - wit.current()->addTo( dockMenu ); - - dockMenu->insertSeparator(); - - for ( QPtrListIterator 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 toolbars = qFindChildren( mw ); + for ( QList::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& lst, QMainWindow* main ) const +void QtxDockAction::dockWidgets( QList& lst ) const { lst.clear(); - QMainWindow* mw = main ? main : mainWindow(); + QMainWindow* mw = mainWindow(); if ( !mw ) return; - QObjectList* objs = mw->queryList( "QDockWindow" ); - if ( objs ) + QList dockwidgets = qFindChildren( mw ); + for ( QList::iterator it = dockwidgets.begin(); it != dockwidgets.end(); ++it ) { - for ( QObjectListIt it( *objs ); it.current(); ++it ) - { - QDockWindow* dockWin = ::qt_cast( 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( 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 ); @@ -772,533 +183,72 @@ void QtxDockAction::updateInfo( QDockWindow* 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 DockWinList; - - DockWinList lst; - dockWindows( lst, mw ); - - QMap nameMap; - for ( QPtrListIterator 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::ConstIterator mIt = nameMap.begin(); mIt != nameMap.end(); ++mIt ) - winList.append( mIt.data() ); - - QMap winMap; - QMap geomMap; - - for ( QPtrListIterator 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& dockList, - const QMap& geomMap ) const -{ - for ( QPtrListIterator 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 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 lst; - dockWindows( lst, mw ); - - for ( QPtrListIterator 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 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 dwList; + dockWidgets( dwList ); + for ( QList::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 winList; - QDockArea* area = dockArea( place ); - if ( area ) - winList = area->dockWindowList(); - else - winList = mainWindow()->dockWindows( (Qt::Dock)place ); - - for ( QPtrListIterator 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 tbList; + toolBars( tbList ); + for ( QList::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 ); } diff --git a/src/Qtx/QtxDockAction.h b/src/Qtx/QtxDockAction.h index a18d102fb..f6ee3313f 100755 --- a/src/Qtx/QtxDockAction.h +++ b/src/Qtx/QtxDockAction.h @@ -24,15 +24,13 @@ #include "QtxAction.h" -#include -#include -#include +#include -class QAction; -class QDockArea; -class QDockWindow; +class QIcon; +class QString; +class QToolBar; +class QDockWidget; class QMainWindow; -class QtxResourceMgr; #ifdef WIN32 #pragma warning( disable:4251 ) @@ -42,123 +40,45 @@ class QTX_EXPORT QtxDockAction : public QtxAction { 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&, 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 InfoMap; - typedef QMap GeomMap; - typedef QMap MenuMap; + void toolBars( QList& ) const; + void dockWidgets( QList& ) 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&, - const QMap& ) 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 diff --git a/src/Qtx/QtxDockWidget.cxx b/src/Qtx/QtxDockWidget.cxx new file mode 100644 index 000000000..fd6f00371 --- /dev/null +++ b/src/Qtx/QtxDockWidget.cxx @@ -0,0 +1,440 @@ +// 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 +#include +#include +#include +#include + +/*! + \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( 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 +*/ diff --git a/src/Qtx/QtxDockWidget.h b/src/Qtx/QtxDockWidget.h new file mode 100644 index 000000000..ed7cb25e9 --- /dev/null +++ b/src/Qtx/QtxDockWidget.h @@ -0,0 +1,58 @@ +// 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 + +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 +}; diff --git a/src/Qtx/QtxDockWindow.cxx b/src/Qtx/QtxDockWindow.cxx deleted file mode 100644 index da6f5cc55..000000000 --- a/src/Qtx/QtxDockWindow.cxx +++ /dev/null @@ -1,412 +0,0 @@ -// 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 -#include -#include -#include -#include - -/*! - \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(); -} diff --git a/src/Qtx/QtxDockWindow.h b/src/Qtx/QtxDockWindow.h deleted file mode 100644 index 6aa0190e3..000000000 --- a/src/Qtx/QtxDockWindow.h +++ /dev/null @@ -1,55 +0,0 @@ -// 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 - -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; -}; diff --git a/src/Qtx/QtxDoubleSpinBox.cxx b/src/Qtx/QtxDoubleSpinBox.cxx new file mode 100644 index 000000000..c79e581c0 --- /dev/null +++ b/src/Qtx/QtxDoubleSpinBox.cxx @@ -0,0 +1,152 @@ +// 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 + +/*! + \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; +} diff --git a/src/Qtx/QtxDoubleSpinBox.h b/src/Qtx/QtxDoubleSpinBox.h new file mode 100644 index 000000000..45ef5434b --- /dev/null +++ b/src/Qtx/QtxDoubleSpinBox.h @@ -0,0 +1,53 @@ +// 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 + +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 diff --git a/src/Qtx/QtxEvalExpr.cxx b/src/Qtx/QtxEvalExpr.cxx new file mode 100644 index 000000000..d16abdc62 --- /dev/null +++ b/src/Qtx/QtxEvalExpr.cxx @@ -0,0 +1,2433 @@ +// 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 + +#include + +/*! + \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 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 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 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= 0 ) + res.append( post[f] ); + + if ( l <= f ) + return true; + + if ( !checkOperations() ) + return false; + + int min = -1; + QIntList argmin; + QList 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 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 aStack; + QList::const_iterator aPIt = parts.begin(); + QList::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 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 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& list ) +{ + QString res = "set : [ "; + for ( QList::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; +} diff --git a/src/Qtx/QtxEvalExpr.h b/src/Qtx/QtxEvalExpr.h new file mode 100644 index 000000000..70f1ce6c3 --- /dev/null +++ b/src/Qtx/QtxEvalExpr.h @@ -0,0 +1,324 @@ +// 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 +#include + +#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 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 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& ); + +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 Postfix; //!< postfix representation + typedef QList SetList; //!< list of operations + typedef QMap 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 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 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 diff --git a/src/Qtx/QtxGridBox.cxx b/src/Qtx/QtxGridBox.cxx new file mode 100644 index 000000000..bb2d33623 --- /dev/null +++ b/src/Qtx/QtxGridBox.cxx @@ -0,0 +1,362 @@ +// 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 +#include + +/*! + \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(); +} diff --git a/src/Qtx/QtxGridBox.h b/src/Qtx/QtxGridBox.h new file mode 100644 index 000000000..4ca39aa08 --- /dev/null +++ b/src/Qtx/QtxGridBox.h @@ -0,0 +1,79 @@ +// 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 + +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 diff --git a/src/Qtx/QtxGroupBox.cxx b/src/Qtx/QtxGroupBox.cxx index 6975f779e..e99532ed4 100644 --- a/src/Qtx/QtxGroupBox.cxx +++ b/src/Qtx/QtxGroupBox.cxx @@ -21,274 +21,191 @@ #include "QtxGroupBox.h" -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include /*! - 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 ) { @@ -298,56 +215,38 @@ 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() { @@ -355,53 +254,92 @@ 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( 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 ); +} diff --git a/src/Qtx/QtxGroupBox.h b/src/Qtx/QtxGroupBox.h index 04f9bb2e6..c2aa4e65b 100644 --- a/src/Qtx/QtxGroupBox.h +++ b/src/Qtx/QtxGroupBox.h @@ -24,54 +24,42 @@ #include "Qtx.h" -#include -#include +#include 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; diff --git a/src/Qtx/QtxIntSpinBox.cxx b/src/Qtx/QtxIntSpinBox.cxx index e002377e6..175a297ae 100755 --- a/src/Qtx/QtxIntSpinBox.cxx +++ b/src/Qtx/QtxIntSpinBox.cxx @@ -21,40 +21,79 @@ #include "QtxIntSpinBox.h" -#include -#include +#include +/*! + \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 { @@ -62,112 +101,49 @@ 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; } diff --git a/src/Qtx/QtxIntSpinBox.h b/src/Qtx/QtxIntSpinBox.h index 7f083d519..31580a1d8 100755 --- a/src/Qtx/QtxIntSpinBox.h +++ b/src/Qtx/QtxIntSpinBox.h @@ -24,37 +24,30 @@ #include "Qtx.h" -#include +#include 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 diff --git a/src/Qtx/QtxListAction.cxx b/src/Qtx/QtxListAction.cxx index 52f093039..813d052ee 100755 --- a/src/Qtx/QtxListAction.cxx +++ b/src/Qtx/QtxListAction.cxx @@ -1,1124 +1,927 @@ // 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 -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -static const char* list_arrow_icon[] = { -"10 6 2 1", -"# c #000000", -" c none", -" ", -" ####### ", -" ##### ", -" ### ", -" # ", -" " -}; +#include +#include +#include +#include +#include +#include +#include /*! - \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 widList = createdWidgets(); + for ( QList::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( *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 actionList = menu()->actions(); + int idx = actionList.indexOf( ::qobject_cast( 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; -} diff --git a/src/Qtx/QtxListAction.h b/src/Qtx/QtxListAction.h index 8ad60be5b..1ec4c31e3 100755 --- a/src/Qtx/QtxListAction.h +++ b/src/Qtx/QtxListAction.h @@ -1,17 +1,17 @@ // 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 @@ -22,171 +22,71 @@ #ifndef QTXLISTACTION_H #define QTXLISTACTION_H -#include "QtxAction.h" - -#include -#include -#include +#include "Qtx.h" -class QLabel; -class QListBox; -class QPopupMenu; -class QToolButton; -class QToolTipGroup; - -class QtxListFrame; +#include +#include #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 PopupsMap; - typedef QMap 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 diff --git a/src/Qtx/QtxListBox.h b/src/Qtx/QtxListBox.h index 180d2cafb..e2e9076b4 100755 --- a/src/Qtx/QtxListBox.h +++ b/src/Qtx/QtxListBox.h @@ -24,7 +24,11 @@ #include "Qtx.h" -#include +// This file isn't yet ported to Qt4 => there are some corrections for OCCViewer porting --> +//#include +#include +#include +// <-- #ifdef WIN32 #pragma warning( disable:4251 ) @@ -33,27 +37,27 @@ 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* ); @@ -68,7 +72,7 @@ public: signals: void itemEdited( int ); - void itemEdited( QListBoxItem* ); + void itemEdited( QListWidgetItem* ); void itemMoved( int, int ); public slots: diff --git a/src/Qtx/QtxListOfOperations.cxx b/src/Qtx/QtxListOfOperations.cxx deleted file mode 100644 index a6c2e6810..000000000 --- a/src/Qtx/QtxListOfOperations.cxx +++ /dev/null @@ -1,278 +0,0 @@ -// 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 - -/*! - 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; -} diff --git a/src/Qtx/QtxListOfOperations.h b/src/Qtx/QtxListOfOperations.h deleted file mode 100644 index def9dd8c4..000000000 --- a/src/Qtx/QtxListOfOperations.h +++ /dev/null @@ -1,82 +0,0 @@ -// 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 diff --git a/src/Qtx/QtxListResourceEdit.h b/src/Qtx/QtxListResourceEdit.h index fc538004a..ac009d7c8 100644 --- a/src/Qtx/QtxListResourceEdit.h +++ b/src/Qtx/QtxListResourceEdit.h @@ -25,7 +25,8 @@ #include "QtxResourceEdit.h" #include -#include +//#include +#include #include #include #include @@ -189,7 +190,7 @@ protected: 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 ); @@ -241,7 +242,7 @@ private: void setIndexes( const QVariant& ); void setStrings( const QStringList& ); - void setIndexes( const QValueList& ); + void setIndexes( const QList& ); private: QComboBox* myList; diff --git a/src/Qtx/QtxLogoMgr.cxx b/src/Qtx/QtxLogoMgr.cxx index 2103eccae..b5bd38895 100644 --- a/src/Qtx/QtxLogoMgr.cxx +++ b/src/Qtx/QtxLogoMgr.cxx @@ -18,42 +18,190 @@ // #include "QtxLogoMgr.h" -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include /*! - 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& ); + +protected: + virtual void customEvent( QEvent* ); + +private: + void updateCorner(); + void updateContents(); + +private: + typedef QPointer WidgetPtr; + +private: + QMenuBar* myMB; //!< parent menu bar + QList 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& labs ) +{ + for ( QList::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::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 { @@ -61,36 +209,77 @@ 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 ) { @@ -98,13 +287,13 @@ 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() { @@ -113,88 +302,132 @@ 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 movList; + movies( id, movList ); - if ( myId ) - menuBar()->removeItem( myId ); + for ( QList::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 movList; + movies( id, movList ); - void addSpacing( int spacing ) - { - QApplication::sendPostedEvents( this, QEvent::ChildInserted ); - ((QHBoxLayout*)layout())->addSpacing( spacing ); - } + for ( QList::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 movList; + movies( id, movList ); - LogoBox* cnt = new LogoBox( menuBar() ); - cnt->setSpacing( 3 ); + for ( QList::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 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& 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 ); + } +} diff --git a/src/Qtx/QtxLogoMgr.h b/src/Qtx/QtxLogoMgr.h index 7e0615c82..6e8d521cd 100644 --- a/src/Qtx/QtxLogoMgr.h +++ b/src/Qtx/QtxLogoMgr.h @@ -21,10 +21,12 @@ #include "Qtx.h" -class QMenuBar; +#include +#include +#include -#include -#include +class QMenuBar; +class QMovie; #ifdef WIN32 #pragma warning( disable : 4251 ) @@ -34,30 +36,38 @@ class QTX_EXPORT QtxLogoMgr : public QObject { 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 LogoList; private: - typedef struct { QString id; QPixmap pix; } LogoInfo; - typedef QValueList LogoList; + void generate(); + int find( const QString& ) const; + LogoInfo& insert( const QString&, const int ); + void movies( const QString&, QList& ) const; private: - int myId; - QMenuBar* myMenus; - LogoList myLogos; + LogoBox* myBox; //!< widget containing logox + LogoList myLogos; //!< list of logo data }; #ifdef WIN32 diff --git a/src/Qtx/QtxMRUAction.cxx b/src/Qtx/QtxMRUAction.cxx index eea0be25a..6f1b81844 100755 --- a/src/Qtx/QtxMRUAction.cxx +++ b/src/Qtx/QtxMRUAction.cxx @@ -23,168 +23,144 @@ #include "QtxResourceMgr.h" -#include +#include +#include /*! - 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() ) { @@ -197,41 +173,40 @@ void QtxMRUAction::insert( const QString& link ) 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; @@ -241,127 +216,31 @@ QString QtxMRUAction::item( const int idx ) const } /*! - 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() ) @@ -389,16 +268,14 @@ void QtxMRUAction::loadLinks( QtxResourceMgr* resMgr, const QString& section, co 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() ) @@ -410,7 +287,10 @@ void QtxMRUAction::saveLinks( QtxResourceMgr* resMgr, const QString& section, co QStringList lst; QMap 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 ); @@ -421,7 +301,10 @@ void QtxMRUAction::saveLinks( QtxResourceMgr* resMgr, const QString& section, co 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 ); } @@ -432,231 +315,50 @@ void QtxMRUAction::saveLinks( QtxResourceMgr* resMgr, const QString& section, co } /*! - 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( 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; -} diff --git a/src/Qtx/QtxMRUAction.h b/src/Qtx/QtxMRUAction.h index 6325860f8..f8a5dd9b0 100755 --- a/src/Qtx/QtxMRUAction.h +++ b/src/Qtx/QtxMRUAction.h @@ -1,17 +1,17 @@ // 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 @@ -24,10 +24,8 @@ #include "QtxAction.h" -#include -#include +#include -class QPopupMenu; class QtxResourceMgr; #ifdef WIN32 @@ -38,24 +36,23 @@ class QTX_EXPORT QtxMRUAction : public QtxAction { 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; @@ -70,46 +67,23 @@ public: 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 ItemsMap; - typedef QMap 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 diff --git a/src/Qtx/QtxMainWindow.cxx b/src/Qtx/QtxMainWindow.cxx index 99f602bbb..7ca329ac2 100644 --- a/src/Qtx/QtxMainWindow.cxx +++ b/src/Qtx/QtxMainWindow.cxx @@ -24,14 +24,17 @@ #include "QtxToolBar.h" #include "QtxResourceMgr.h" -#include -#include -#include -#include +#include +#include +#include +#include +#include /*! - 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 @@ -43,30 +46,39 @@ public: 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 ) { @@ -77,21 +89,27 @@ 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() { @@ -100,16 +118,18 @@ 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 ) { @@ -122,38 +142,31 @@ 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 { @@ -161,8 +174,9 @@ 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 ) { @@ -175,209 +189,203 @@ 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 ) { @@ -400,54 +408,3 @@ 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 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 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; -} diff --git a/src/Qtx/QtxMainWindow.h b/src/Qtx/QtxMainWindow.h index ee779aefd..10accc407 100644 --- a/src/Qtx/QtxMainWindow.h +++ b/src/Qtx/QtxMainWindow.h @@ -24,9 +24,8 @@ #include "Qtx.h" -#include +#include -class QDockWindow; class QtxResourceMgr; class QTX_EXPORT QtxMainWindow : public QMainWindow @@ -35,11 +34,8 @@ 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; @@ -48,31 +44,18 @@ public: 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 diff --git a/src/Qtx/QtxMap.h b/src/Qtx/QtxMap.h new file mode 100644 index 000000000..2030b9e98 --- /dev/null +++ b/src/Qtx/QtxMap.h @@ -0,0 +1,210 @@ +// 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 IMap; +template class IMapIterator; +template class IMapConstIterator; + +/*! + \brief Indexed map template class. +*/ +template class IMap +{ +public: + typedef IMapIterator Iterator; + typedef IMapConstIterator 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 keys() const { return myKeys; } + QList values() const { QList 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 myKeys; + QMap myData; + Key dummyKey; + Value dummyValue; + + friend class IMapIterator; + friend class IMapConstIterator; +}; + +/*! + \brief Indexed map iterator template class. +*/ +template class IMapIterator +{ +public: + IMapIterator() : myMap( 0 ), myIndex( 0 ) { init(); } + IMapIterator( const IMap* m ) : myMap( const_cast< IMap* >( 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* m, const int index ) : myMap( const_cast< IMap* >( m ) ), myIndex( index ) { init(); } + void init() { if ( !myMap || myIndex >= myMap->count() ) myIndex = -1; } + +private: + IMap* myMap; + int myIndex; + + friend class IMap; + friend class IMapConstIterator; +}; + +/*! + \brief Indexed map const iterator template class. +*/ +template class IMapConstIterator +{ +public: + IMapConstIterator() : myMap( 0 ), myIndex( 0 ) { init(); } + IMapConstIterator( const IMap* m ) : myMap( const_cast< IMap* >( m ) ), myIndex( 0 ) { init(); } + IMapConstIterator( const IMapConstIterator& i ) : myMap( i.myMap ), myIndex( i.myIndex ) { init(); } + IMapConstIterator( const IMapIterator& 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* m, const int index ): myMap( const_cast< IMap* >( m ) ), myIndex( index ) { init(); } + void init() { if ( !myMap || myIndex >= myMap->count() ) myIndex = -1; } + +private: + IMap* myMap; + int myIndex; + + friend class IMap; +}; + +#endif // QTX_MAP_H diff --git a/src/Qtx/QtxMenuButton.cxx b/src/Qtx/QtxMenuButton.cxx deleted file mode 100755 index dc8abdde7..000000000 --- a/src/Qtx/QtxMenuButton.cxx +++ /dev/null @@ -1,429 +0,0 @@ -// 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 -#include -#include -#include -#include - -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 ); -} diff --git a/src/Qtx/QtxMenuButton.h b/src/Qtx/QtxMenuButton.h deleted file mode 100755 index b0f674196..000000000 --- a/src/Qtx/QtxMenuButton.h +++ /dev/null @@ -1,88 +0,0 @@ -// 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 - -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 diff --git a/src/Qtx/QtxOperations.cxx b/src/Qtx/QtxOperations.cxx deleted file mode 100644 index ccf150007..000000000 --- a/src/Qtx/QtxOperations.cxx +++ /dev/null @@ -1,43 +0,0 @@ -// 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; -} diff --git a/src/Qtx/QtxOperations.h b/src/Qtx/QtxOperations.h deleted file mode 100644 index 642a3bf31..000000000 --- a/src/Qtx/QtxOperations.h +++ /dev/null @@ -1,61 +0,0 @@ -// 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 diff --git a/src/Qtx/QtxParser.cxx b/src/Qtx/QtxParser.cxx deleted file mode 100644 index b4b32bb29..000000000 --- a/src/Qtx/QtxParser.cxx +++ /dev/null @@ -1,850 +0,0 @@ -// 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 ) - 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=0 && cPos=0 && opPoscreateValue( 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=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; -} diff --git a/src/Qtx/QtxParser.h b/src/Qtx/QtxParser.h deleted file mode 100644 index 0a0b05a16..000000000 --- a/src/Qtx/QtxParser.h +++ /dev/null @@ -1,159 +0,0 @@ -// 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 -#include - -#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 diff --git a/src/Qtx/QtxPathDialog.cxx b/src/Qtx/QtxPathDialog.cxx index fd098e7ef..4aa71bc80 100755 --- a/src/Qtx/QtxPathDialog.cxx +++ b/src/Qtx/QtxPathDialog.cxx @@ -21,19 +21,19 @@ #include "QtxPathDialog.h" +#include "QtxGridBox.h" #include "QtxGroupBox.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include static const char* open_icon[] = { "16 16 5 1", @@ -61,546 +61,662 @@ static const char* open_icon[] = { }; /*! - 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(); } diff --git a/src/Qtx/QtxPathDialog.h b/src/Qtx/QtxPathDialog.h index a4db3a7fd..57b887756 100755 --- a/src/Qtx/QtxPathDialog.h +++ b/src/Qtx/QtxPathDialog.h @@ -24,7 +24,7 @@ #include "QtxDialog.h" -#include +#include class QFrame; class QLineEdit; @@ -40,10 +40,12 @@ class QTX_EXPORT QtxPathDialog : public QtxDialog 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; @@ -52,11 +54,12 @@ public: QString filter() const; void setFilter( const QString& ); - virtual void show(); - signals: void fileNameChanged( QString ); +public slots: + virtual void setVisible( bool ); + protected slots: void validate(); @@ -74,16 +77,21 @@ protected: 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; @@ -92,15 +100,14 @@ protected: 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 FileEntryMap; private: - QString myFilter; FileEntryMap myEntries; int myDefault; - QFrame* myEntriesFrame; + QWidget* myEntriesFrame; QFrame* myOptionsFrame; }; diff --git a/src/Qtx/QtxPopupMgr.cxx b/src/Qtx/QtxPopupMgr.cxx index 5f0df3de8..2158b6417 100644 --- a/src/Qtx/QtxPopupMgr.cxx +++ b/src/Qtx/QtxPopupMgr.cxx @@ -18,641 +18,577 @@ // #include "QtxPopupMgr.h" -#include "QtxListOfOperations.h" -#include "QtxStdOperations.h" #include "QtxAction.h" - -#include -#include - +#include "QtxEvalExpr.h" +#include /*! - \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 ("$") + \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& aList1 = v1.toList(), aList2 = v2.toList(); + QList::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(); iparam( 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( 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& aList1 = v1.toList(), aList2 = v2.toList(); - QValueList::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()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 t1menuText(); + 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,int> aCorteges; - QValueList c; + QStringList specific; + p->clearParameters(); + setParameters( p, specific ); - if( specific.count()>0 ) - if( myCurrentSelection ) + QMap, 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(); iparam( i, *anIt1 ) ); - aCorteges.insert( c, 0 ); - } - - //qDebug( QString( "%1 corteges" ).arg( aCorteges.count() ) ); - QMap,int>::const_iterator anIt = aCorteges.begin(), aLast = aCorteges.end(); - for( ; anIt!=aLast; anIt++ ) - { - QStringList::const_iterator anIt1 = specific.begin(), aLast1 = specific.end(); - const QValueList& aCortege = anIt.key(); - QValueList::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(); iset( *anIt1, myCurrentSelection->param( i, *anIt1 ) ); - res = res || result( p ); - }*/ + QList 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, int>::const_iterator anIt = aCorteges.begin(); anIt != aCorteges.end(); ++anIt ) + { + const QList& aCortege = anIt.key(); + QStringList::const_iterator anIt1 = specific.begin(), aLast1 = specific.end(); + QList::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 ) { @@ -660,100 +596,145 @@ 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 +*/ diff --git a/src/Qtx/QtxPopupMgr.h b/src/Qtx/QtxPopupMgr.h index 7bc260b3b..97188b1cb 100644 --- a/src/Qtx/QtxPopupMgr.h +++ b/src/Qtx/QtxPopupMgr.h @@ -17,116 +17,108 @@ // 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 +#include +#include -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 ExprMap; + typedef QMap RuleMap; + typedef QMap 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 OptionsMap; +private: + OptionsMap myOptions; +}; #endif diff --git a/src/Qtx/QtxResourceEdit.h b/src/Qtx/QtxResourceEdit.h index d6da330ac..14b920591 100644 --- a/src/Qtx/QtxResourceEdit.h +++ b/src/Qtx/QtxResourceEdit.h @@ -90,7 +90,7 @@ protected: virtual void itemAdded( Item* ); virtual void itemRemoved( Item* ); - void childItems( QPtrList& ) const; + void childItems( QList& ) const; private: void removeItem( Item* ); @@ -103,7 +103,7 @@ private: ItemMap myItems; QtxResourceMgr* myResMgr; QMap myBackup; - QPtrList myChildren; + QList myChildren; friend class QtxResourceEdit::Item; }; @@ -123,7 +123,7 @@ public: virtual int type() const = 0; Item* parentItem() const; - void childItems( QPtrList& ) const; + void childItems( QList& ) const; virtual bool isEmpty() const; @@ -172,8 +172,8 @@ protected: Item* item( const QString&, const int ) const; protected: - typedef QPtrList ItemList; - typedef QPtrListIterator ItemListIterator; + typedef QList ItemList; + typedef QListIterator ItemListIterator; private: static int generateId(); diff --git a/src/Qtx/QtxResourceMgr.cxx b/src/Qtx/QtxResourceMgr.cxx index 02b3a1c65..c61a96bda 100644 --- a/src/Qtx/QtxResourceMgr.cxx +++ b/src/Qtx/QtxResourceMgr.cxx @@ -18,40 +18,105 @@ // #include "QtxResourceMgr.h" -#include -#include -#include -#include -#include -#include - +#include +#include +#include +#include +#include +#include #ifndef QT_NO_DOM -#include +#include +#include +#include #endif +#define EMULATE_GLOBAL_CONTEXT + #include /*! - 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( 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 SectionMap; + +private: + QtxResourceMgr* myMgr; //!< resources manager + SectionMap mySections; //!< sections map + QString myFileName; //!< resources file name + QMap 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 { @@ -59,8 +124,9 @@ 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 ) { @@ -68,14 +134,12 @@ 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 { @@ -91,21 +155,24 @@ QString QtxResourceMgr::Resources::value( const QString& sect, const QString& na } /*! - 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 { @@ -113,9 +180,10 @@ 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 { @@ -123,8 +191,8 @@ bool QtxResourceMgr::Resources::hasValue( const QString& sect, const QString& na } /*! - Removes section from resources - \param sect - name of section + \brief Remove resourcs section. + \param sect secton name */ void QtxResourceMgr::Resources::removeSection( const QString& sect ) { @@ -132,24 +200,23 @@ 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() { @@ -157,6 +224,7 @@ void QtxResourceMgr::Resources::clear() } /*! + \brief Get all sections names. \return list of section names */ QStringList QtxResourceMgr::Resources::sections() const @@ -165,8 +233,9 @@ 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 { @@ -177,11 +246,19 @@ 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 { @@ -195,7 +272,8 @@ QString QtxResourceMgr::Resources::path( const QString& sec, const QString& pref } /*! - \return corresponding resource manager + \brief Get resource manager + \return resource manager pointer */ QtxResourceMgr* QtxResourceMgr::Resources::resMgr() const { @@ -203,9 +281,14 @@ 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() ); @@ -214,18 +297,31 @@ QtxResourceMgr::Section& QtxResourceMgr::Resources::section( const QString& sn ) } /*! - \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 { @@ -236,7 +332,7 @@ QString QtxResourceMgr::Resources::fileName( const QString& sect, const QString& 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; } @@ -245,17 +341,23 @@ QString QtxResourceMgr::Resources::fileName( const QString& sect, const QString& { 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 { @@ -274,15 +376,55 @@ QPixmap QtxResourceMgr::Resources::loadPixmap( const QString& sect, const QStrin } /*! - \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; @@ -291,39 +433,63 @@ QTranslator* QtxResourceMgr::Resources::loadTranslator( const QString& sect, con } /*! - 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 { @@ -339,9 +505,9 @@ QString QtxResourceMgr::Resources::makeSubstitution( const QString& str, const Q 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() ) { @@ -358,13 +524,18 @@ QString QtxResourceMgr::Resources::makeSubstitution( const QString& str, const Q 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: @@ -377,7 +548,7 @@ protected: }; /*! - Default constructor + \brief Constructor. */ QtxResourceMgr::IniFormat::IniFormat() : Format( "ini" ) @@ -385,21 +556,22 @@ QtxResourceMgr::IniFormat::IniFormat() } /*! - 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& secMap ) { QFile file( fname ); - if ( !file.open( IO_ReadOnly ) ) + if ( !file.open( QFile::ReadOnly ) ) return false; QTextStream ts( &file ); @@ -425,7 +597,7 @@ bool QtxResourceMgr::IniFormat::load( const QString& fname, QMap& secMap ) { QFile file( fname ); - if ( !file.open( IO_WriteOnly ) ) + if ( !file.open( QFile::WriteOnly ) ) return false; + QTextStream ts( &file ); + bool res = true; for ( QMap::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(); @@ -490,8 +665,9 @@ bool QtxResourceMgr::IniFormat::save( const QString& fname, const QMap& secMap ) { @@ -539,7 +716,7 @@ bool QtxResourceMgr::XmlFormat::load( const QString& fname, QMap& secMap ) { @@ -639,7 +817,7 @@ bool QtxResourceMgr::XmlFormat::save( const QString& fname, const QMapmySections = 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 ) { @@ -820,30 +1013,106 @@ 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& 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& 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 ), @@ -856,14 +1125,14 @@ QtxResourceMgr::QtxResourceMgr( const QString& appName, const QString& resVarTem 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() ); @@ -872,22 +1141,25 @@ QtxResourceMgr::QtxResourceMgr( const QString& appName, const QString& resVarTem } /*! - \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 { @@ -895,9 +1167,12 @@ 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 { @@ -905,8 +1180,8 @@ 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 ) { @@ -914,7 +1189,13 @@ 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 { @@ -922,8 +1203,11 @@ 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 { @@ -933,12 +1217,12 @@ 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 ) @@ -946,7 +1230,15 @@ void QtxResourceMgr::initialize( const bool autoLoad ) const } /*! - \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 { @@ -954,8 +1246,9 @@ 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 ) { @@ -963,17 +1256,21 @@ 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 ) { @@ -981,7 +1278,10 @@ 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 { @@ -989,11 +1289,12 @@ 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 { @@ -1008,11 +1309,12 @@ bool QtxResourceMgr::value( const QString& sect, const QString& name, int& iVal } /*! - \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 { @@ -1027,11 +1329,12 @@ bool QtxResourceMgr::value( const QString& sect, const QString& name, double& dV } /*! - \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 { @@ -1046,7 +1349,7 @@ bool QtxResourceMgr::value( const QString& sect, const QString& name, bool& bVal boolMap["false"] = boolMap["no"] = boolMap["off"] = false; } - val = val.lower(); + val = val.toLower(); bool res = boolMap.contains( val ); if ( res ) bVal = boolMap[val]; @@ -1061,11 +1364,12 @@ bool QtxResourceMgr::value( const QString& sect, const QString& name, bool& bVal } /*! - \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 { @@ -1074,30 +1378,47 @@ bool QtxResourceMgr::value( const QString& sect, const QString& name, QColor& cV 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 { @@ -1105,7 +1426,7 @@ bool QtxResourceMgr::value( const QString& sect, const QString& name, QFont& fVa 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; @@ -1118,7 +1439,7 @@ bool QtxResourceMgr::value( const QString& sect, const QString& name, QFont& fVa 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" ) ) @@ -1138,14 +1459,48 @@ bool QtxResourceMgr::value( const QString& sect, const QString& name, QFont& fVa } /*! - \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 { @@ -1153,26 +1508,30 @@ bool QtxResourceMgr::value( const QString& sect, const QString& name, QString& v 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 { @@ -1183,11 +1542,15 @@ int QtxResourceMgr::integerValue( const QString& sect, const QString& name, cons } /*! - \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 { @@ -1198,11 +1561,15 @@ double QtxResourceMgr::doubleValue( const QString& sect, const QString& name, co } /*! - \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 { @@ -1213,11 +1580,15 @@ bool QtxResourceMgr::booleanValue( const QString& sect, const QString& name, con } /*! - \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 { @@ -1228,11 +1599,15 @@ QFont QtxResourceMgr::fontValue( const QString& sect, const QString& name, 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 { @@ -1243,11 +1618,14 @@ QColor QtxResourceMgr::colorValue( const QString& sect, const QString& name, con } /*! - \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 { @@ -1258,41 +1636,61 @@ QString QtxResourceMgr::stringValue( const QString& sect, const QString& name, c } /*! - \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 ) { @@ -1304,10 +1702,10 @@ 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 ) { @@ -1319,10 +1717,10 @@ void QtxResourceMgr::setValue( const QString& sect, const QString& name, double } /*! - \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 ) { @@ -1334,10 +1732,10 @@ void QtxResourceMgr::setValue( const QString& sect, const QString& name, bool va } /*! - \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 ) { @@ -1345,14 +1743,14 @@ void QtxResourceMgr::setValue( const QString& sect, const QString& name, const Q 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 ) { @@ -1374,10 +1772,10 @@ void QtxResourceMgr::setValue( const QString& sect, const QString& name, const Q } /*! - \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 ) { @@ -1389,44 +1787,68 @@ void QtxResourceMgr::setValue( const QString& sect, const QString& name, const Q } /*! - \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 ) { @@ -1434,41 +1856,46 @@ 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 ) { @@ -1477,16 +1904,17 @@ 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 { @@ -1494,9 +1922,13 @@ 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 { @@ -1507,9 +1939,10 @@ 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 ) { @@ -1517,7 +1950,9 @@ 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() { @@ -1528,14 +1963,16 @@ 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 ) { @@ -1543,8 +1980,8 @@ 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(); @@ -1555,7 +1992,8 @@ bool QtxResourceMgr::import( const QString& fname ) } /*! - \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() { @@ -1568,20 +2006,21 @@ 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 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 ); } @@ -1594,8 +2033,9 @@ QStringList QtxResourceMgr::sections() const } /*! - \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 { @@ -1607,10 +2047,13 @@ QStringList QtxResourceMgr::parameters( const QString& sec ) const typedef IMap 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 ); } @@ -1623,22 +2066,35 @@ QStringList QtxResourceMgr::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. 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 { @@ -1649,7 +2105,13 @@ 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 { @@ -1660,7 +2122,12 @@ 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 { @@ -1668,8 +2135,12 @@ 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 ) { @@ -1677,9 +2148,11 @@ 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 { @@ -1687,12 +2160,14 @@ QPixmap QtxResourceMgr::loadPixmap( const QString& prefix, const QString& name ) } /*! - \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 { @@ -1700,41 +2175,46 @@ QPixmap QtxResourceMgr::loadPixmap( const QString& prefix, const QString& name, } /*! - 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 ) { @@ -1750,7 +2230,7 @@ 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 ); @@ -1758,19 +2238,21 @@ void QtxResourceMgr::loadLanguage( const QString& pref, const QString& l ) 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; @@ -1786,103 +2268,105 @@ void QtxResourceMgr::loadLanguage( const QString& pref, const QString& l ) 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() { @@ -1896,22 +2380,26 @@ 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 ) { @@ -1922,15 +2410,27 @@ void QtxResourceMgr::setResource( const QString& sect, const QString& name, cons } /*! - \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 .rc + file is used on Linux (e.g. .MyApprc) and . 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() ); @@ -1945,7 +2445,16 @@ QString QtxResourceMgr::userFileName( const QString& appName, const bool /*for_l } /*! - \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 . 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 { @@ -1953,10 +2462,13 @@ 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& substMap ) const { @@ -1965,7 +2477,7 @@ QString QtxResourceMgr::substMacro( const QString& src, const QMap= 0 ) + while ( ( idx = rx.indexIn( trg, idx ) ) >= 0 ) { QChar spec = trg.at( idx + 1 ); QString subst; diff --git a/src/Qtx/QtxResourceMgr.h b/src/Qtx/QtxResourceMgr.h index ff72dd3c2..304e25fdc 100644 --- a/src/Qtx/QtxResourceMgr.h +++ b/src/Qtx/QtxResourceMgr.h @@ -16,29 +16,32 @@ // // 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 -#include -#include -#include -#include -#include -#include +#ifndef QTX_NO_INDEXED_MAP +#include "QtxMap.h" +#endif + +#include +#include +#include +#include +#include +#include +#include -class QPixmap; +class QTranslator; #ifdef WIN32 #pragma warning( disable:4251 ) #endif -/*! - Class: QtxResourceMgr -*/ - class QTX_EXPORT QtxResourceMgr { class IniFormat; @@ -48,14 +51,10 @@ class QTX_EXPORT QtxResourceMgr public: class Format; - template class IMap; - template class IMapIterator; - template class IMapConstIterator; - #ifdef QTX_NO_INDEXED_MAP - typedef QMap Section; + typedef QMap Section; //!< resource section #else - typedef IMap Section; + typedef IMap Section; //!< resource section #endif public: @@ -81,6 +80,7 @@ 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; @@ -89,6 +89,7 @@ public: 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; @@ -99,6 +100,7 @@ public: 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& ); @@ -153,36 +155,28 @@ private: QString substMacro( const QString&, const QMap& ) const; private: - typedef QPtrList ResList; - typedef QPtrList FormatList; - typedef QMap OptionsMap; - typedef QPtrListIterator ResListIterator; - typedef QPtrListIterator FormatListIterator; - - typedef QPtrList TransList; - typedef QMap TransListMap; - typedef QPtrListIterator TransListIterator; + typedef QList ResList; + typedef QList TransList; + typedef QList FormatList; + typedef QMap OptionsMap; + typedef QMap 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: @@ -203,248 +197,8 @@ protected: virtual bool save( const QString&, const QMap& ) = 0; private: - QString myFmt; - QMap 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 SectionMap; - -private: - SectionMap mySections; - QString myFileName; - QMap myPixmapCache; - QtxResourceMgr* myMgr; - - friend class QtxResourceMgr::Format; -}; - -/*! - Class: QtxResourceMgr::IMapIterator -*/ - -template class QtxResourceMgr::IMapIterator -{ -public: - IMapIterator() : myMap( 0 ), myIndex( 0 ) { init(); } - IMapIterator( const IMap* m ) : myMap( const_cast< IMap* >( 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* m, const int index ) : myMap( const_cast< IMap* >( m ) ), myIndex( index ) { init(); } - void init() { if ( !myMap || myIndex >= myMap->count() ) myIndex = -1; } - -private: - IMap* myMap; - int myIndex; - - friend class IMap; - friend class IMapConstIterator; -}; - -/*! - Class: QtxResourceMgr::IMapConstIterator -*/ - -template class QtxResourceMgr::IMapConstIterator -{ -public: - IMapConstIterator() : myMap( 0 ), myIndex( 0 ) { init(); } - IMapConstIterator( const IMap* m ) : myMap( const_cast< IMap* >( m ) ), myIndex( 0 ) { init(); } - IMapConstIterator( const IMapConstIterator& i ) : myMap( i.myMap ), myIndex( i.myIndex ) { init(); } - IMapConstIterator( const IMapIterator& 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* m, const int index ): myMap( const_cast< IMap* >( m ) ), myIndex( index ) { init(); } - void init() { if ( !myMap || myIndex >= myMap->count() ) myIndex = -1; } - -private: - IMap* myMap; - int myIndex; - - friend class IMap; -}; - -/*! - Class: QtxResourceMgr::IMap -*/ - -template class QtxResourceMgr::IMap -{ -public: - typedef IMapIterator Iterator; - typedef IMapConstIterator 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 keys() const { return myKeys; } - QValueList values() const { QValueList 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 myKeys; - QMap myData; - Key dummyKey; - Value dummyValue; - - friend class IMapIterator; - friend class IMapConstIterator; + QString myFmt; //!< format name + QMap myOpt; //!< options map }; -#endif +#endif // QTX_RESOURCEMGR_H diff --git a/src/Qtx/QtxSplash.cxx b/src/Qtx/QtxSplash.cxx index d3244efc9..f99e36b2a 100644 --- a/src/Qtx/QtxSplash.cxx +++ b/src/Qtx/QtxSplash.cxx @@ -21,57 +21,156 @@ #include "QtxSplash.h" -#include -#include -#include -#include - -const int _PROGRESS_EVENT = QEvent::User + 10; -const int _PROGRESS_WIDTH = 10; +#include +#include +#include +#include /*! - 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() { @@ -79,8 +178,13 @@ 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 ) { @@ -92,24 +196,32 @@ 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, @@ -117,23 +229,42 @@ void QtxSplash::error( const QString& error, const QString& title, const int cod 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 { @@ -141,14 +272,19 @@ 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 ) { @@ -156,7 +292,9 @@ 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 { @@ -164,7 +302,9 @@ 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 ) { @@ -173,8 +313,9 @@ 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 { @@ -182,17 +323,20 @@ 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 { @@ -200,37 +344,129 @@ 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; @@ -238,8 +474,77 @@ int QtxSplash::progressColors( QColor& startColor, QColor& endColor ) } /*! - 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 ) { @@ -248,7 +553,8 @@ 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 @@ -257,19 +563,24 @@ 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 @@ -278,19 +589,24 @@ 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 { @@ -299,7 +615,8 @@ void QtxSplash::textColors( QColor& color, QColor& shadow ) const } /*! - Returns current status message. + \brief Get current status message. + \return status message */ QString QtxSplash::message() const { @@ -307,8 +624,13 @@ 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 { @@ -316,22 +638,26 @@ 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() { @@ -341,8 +667,11 @@ 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, @@ -350,15 +679,15 @@ void QtxSplash::message( const QString& msg, { 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 ) { @@ -367,7 +696,7 @@ 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() @@ -377,131 +706,217 @@ 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; } + diff --git a/src/Qtx/QtxSplash.h b/src/Qtx/QtxSplash.h index b6ade167c..bd952119b 100644 --- a/src/Qtx/QtxSplash.h +++ b/src/Qtx/QtxSplash.h @@ -24,8 +24,9 @@ #include "Qtx.h" -#include -#include +#include +#include +#include #ifdef WIN32 #pragma warning( disable:4251 ) @@ -33,82 +34,125 @@ 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 diff --git a/src/Qtx/QtxStdOperations.cxx b/src/Qtx/QtxStdOperations.cxx deleted file mode 100644 index 8e0a33e01..000000000 --- a/src/Qtx/QtxStdOperations.cxx +++ /dev/null @@ -1,833 +0,0 @@ -// 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 -#include - -/*! - 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; -} diff --git a/src/Qtx/QtxStdOperations.h b/src/Qtx/QtxStdOperations.h deleted file mode 100644 index 3631d7b95..000000000 --- a/src/Qtx/QtxStdOperations.h +++ /dev/null @@ -1,144 +0,0 @@ -// 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 diff --git a/src/Qtx/QtxToolBar.cxx b/src/Qtx/QtxToolBar.cxx index cf585db64..af3b3c3c8 100644 --- a/src/Qtx/QtxToolBar.cxx +++ b/src/Qtx/QtxToolBar.cxx @@ -21,16 +21,14 @@ #include "QtxToolBar.h" -#include -#include -#include -#include -#include -#include +#include +#include +#include /*! - 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 @@ -39,12 +37,12 @@ public: 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 }; @@ -55,8 +53,6 @@ private: void showContainer(); void hideContainer(); - void updateIcon(); - void updateCaption(); void updateVisibility(); private: @@ -67,17 +63,19 @@ 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() ); @@ -85,18 +83,15 @@ myEmpty( true ) } /*! - 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 ) ) || @@ -108,14 +103,15 @@ bool QtxToolBar::Watcher::eventFilter( QObject* o, QEvent* e ) 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 ) { @@ -126,9 +122,10 @@ 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; @@ -137,7 +134,7 @@ void QtxToolBar::Watcher::hided( QtxToolBar* tb ) } /*! - Shows corresponding QtxToolBar + \brief Show the toolbar being watched */ void QtxToolBar::Watcher::showContainer() { @@ -151,7 +148,7 @@ void QtxToolBar::Watcher::showContainer() } /*! - Hides corresponding QtxToolBar + \brief Hide the toolbar being watched */ void QtxToolBar::Watcher::hideContainer() { @@ -165,43 +162,44 @@ 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() { @@ -210,18 +208,18 @@ 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(); @@ -229,11 +227,11 @@ void QtxToolBar::Watcher::updateVisibility() { 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 ); } } @@ -243,141 +241,79 @@ void QtxToolBar::Watcher::updateVisibility() } /*! - 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 ) @@ -385,17 +321,18 @@ QSize QtxToolBar::sizeHint() const 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 ) @@ -403,28 +340,39 @@ QSize QtxToolBar::minimumSizeHint() const 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( wid ); + wid = wid->parentWidget(); + } + return mw; } diff --git a/src/Qtx/QtxToolBar.h b/src/Qtx/QtxToolBar.h index 57512f40d..7d0918fcf 100644 --- a/src/Qtx/QtxToolBar.h +++ b/src/Qtx/QtxToolBar.h @@ -21,7 +21,7 @@ #include "Qtx.h" -#include +#include class QTX_EXPORT QtxToolBar : public QToolBar { @@ -30,25 +30,21 @@ 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) }; diff --git a/src/Qtx/QtxToolTip.cxx b/src/Qtx/QtxToolTip.cxx index 530afca6d..e7888a4da 100755 --- a/src/Qtx/QtxToolTip.cxx +++ b/src/Qtx/QtxToolTip.cxx @@ -21,11 +21,13 @@ #include "QtxToolTip.h" -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include #define TOOLTIP_SHOW_DELAY 0500 #define TOOLTIP_HIDE_DELAY 7000 @@ -34,11 +36,14 @@ 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 ); @@ -50,7 +55,9 @@ QtxToolTip::QtxToolTip( QWidget* parent ) 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() ) ); @@ -87,7 +94,7 @@ bool QtxToolTip::eventFilter( QObject* o, QEvent* e ) if ( myWakeUpTimer->isActive() ) { myWakeUpTimer->stop(); - myWakeUpTimer->start( myWakeUpDelayTime, true ); + myWakeUpTimer->start( myWakeUpDelayTime ); } if ( isVisible() ) { @@ -100,7 +107,7 @@ bool QtxToolTip::eventFilter( QObject* o, QEvent* e ) else { if ( !myWidgetRegion.isValid() || myWidgetRegion.contains( thePos ) ) - myWakeUpTimer->start( myWakeUpDelayTime, true ); + myWakeUpTimer->start( myWakeUpDelayTime ); } } if ( e->type() == QEvent::KeyPress ) @@ -141,7 +148,7 @@ void QtxToolTip::showTip( const QRect& aRegion, const QString& text, const QRect myWidgetRegion = aWidgetRegion; setGeometry( aRegion ); if ( myShowDelayTime != 0 ) - mySleepTimer->start( myShowDelayTime, true ); + mySleepTimer->start( myShowDelayTime ); show(); } @@ -176,7 +183,7 @@ void QtxToolTip::maybeTip( const QPoint& pos ) 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 ); } } @@ -211,7 +218,7 @@ void QtxToolTip::mousePressEvent( QMouseEvent* e ) 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 ); } @@ -224,7 +231,7 @@ void QtxToolTip::mouseDoubleClickEvent( QMouseEvent* e ) 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 ); } diff --git a/src/Qtx/QtxToolTip.h b/src/Qtx/QtxToolTip.h index c8b9d704b..d558f9c06 100755 --- a/src/Qtx/QtxToolTip.h +++ b/src/Qtx/QtxToolTip.h @@ -24,7 +24,7 @@ #include "Qtx.h" -#include +#include class QTimer; diff --git a/src/Qtx/QtxValidator.cxx b/src/Qtx/QtxValidator.cxx new file mode 100644 index 000000000..690986559 --- /dev/null +++ b/src/Qtx/QtxValidator.cxx @@ -0,0 +1,136 @@ +// 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" ); +} diff --git a/src/Qtx/QtxValidator.h b/src/Qtx/QtxValidator.h new file mode 100644 index 000000000..ca5b6121f --- /dev/null +++ b/src/Qtx/QtxValidator.h @@ -0,0 +1,53 @@ +// 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 + +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 diff --git a/src/Qtx/QtxWorkspace.cxx b/src/Qtx/QtxWorkspace.cxx new file mode 100644 index 000000000..dd303ed6c --- /dev/null +++ b/src/Qtx/QtxWorkspace.cxx @@ -0,0 +1,137 @@ +// 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 + +/*! + \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; + } +} diff --git a/src/Qtx/QtxWorkspace.h b/src/Qtx/QtxWorkspace.h new file mode 100644 index 000000000..224d729c1 --- /dev/null +++ b/src/Qtx/QtxWorkspace.h @@ -0,0 +1,50 @@ +// 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 + +#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 diff --git a/src/Qtx/QtxWorkspaceAction.cxx b/src/Qtx/QtxWorkspaceAction.cxx index f06c5c2a4..938b43801 100644 --- a/src/Qtx/QtxWorkspaceAction.cxx +++ b/src/Qtx/QtxWorkspaceAction.cxx @@ -21,229 +21,192 @@ #include "QtxWorkspaceAction.h" -#include -#include -#include +#include "QtxWorkspace.h" + +#include +#include /*! - 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 ) { @@ -265,23 +228,21 @@ 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; @@ -291,240 +252,162 @@ void QtxWorkspaceAction::cascade() 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( 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( 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 lst = actions(); + for ( QList::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 items; + QMap 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::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( 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 ); } diff --git a/src/Qtx/QtxWorkspaceAction.h b/src/Qtx/QtxWorkspaceAction.h index 2dfee9cdb..a4ade9c06 100644 --- a/src/Qtx/QtxWorkspaceAction.h +++ b/src/Qtx/QtxWorkspaceAction.h @@ -22,81 +22,72 @@ #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 MenuMap; - typedef QMap 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 diff --git a/src/Qtx/QtxWorkstack.cxx b/src/Qtx/QtxWorkstack.cxx index 3cf22f413..0d72eb2ec 100644 --- a/src/Qtx/QtxWorkstack.cxx +++ b/src/Qtx/QtxWorkstack.cxx @@ -1,17 +1,17 @@ // 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 @@ -21,2594 +21,2928 @@ #include "QtxWorkstack.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "QtxAction.h" -#define DARK_COLOR_LIGHT 250 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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 lst; - areas( mySplit, lst, true ); + QApplication::instance()->removeEventFilter( this ); - QWidgetList widList; - for ( QPtrListIterator 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 areaList; - areas( s, areaList ); + QRect r = myArea->floatRect(); + int m = 2; - QPtrList 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 SplitType 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 allAreas; - areas(mySplit, allAreas, true); + QVBoxLayout* base = new QVBoxLayout( this ); + base->setMargin( frameWidth() ); - QPtrListIterator 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 areaList; - areas(s, areaList); + myBar = new QtxWorkstackTabBar( top ); + tl->addWidget( myBar, 1 ); - QPtrList 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 allAreas; - areas( mySplit, allAreas, true ); - for ( QPtrListIterator 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( 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 allAreas; - areas(mySplit, allAreas, true); - QPtrListIterator 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 # - 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 # - *its = new_this; - ++its; - // set size to all items after an item # - 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 allAreas; - areas(mySplit, allAreas, true); - for ( QPtrListIterator 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 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 SetRelativePosition 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 areaList; - areas((QSplitter*)it.current(), areaList, true); - for (QPtrListIterator 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 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 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 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 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( (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& 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& 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 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 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 lst; - areas( mySplit, lst, true ); - for ( QPtrListIterator 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 recList; - splitters( split, recList, false ); - for ( QPtrListIterator itr( recList ); itr.current(); ++itr ) - updateState( itr.current() ); - - QPtrList splitList; - splitters( split, splitList, false ); - - QPtrList areaList; - areas( split, areaList, false ); - - bool vis = false; - for ( QPtrListIterator 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 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 sizes = split->sizes(); - QString sizesStr; - for ( QValueList::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 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::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( 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 >& 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 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 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 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 splitList; - QPtrList areaList; - splitters( mySplit, splitList, false ); - areas( mySplit, areaList, false ); - for ( QPtrListIterator iter( splitList ); iter.current(); ++iter ) - delete iter.current(); - for ( QPtrListIterator it( areaList ); it.current(); ++it ) - if ( it.current()->isEmpty() ) - delete it.current(); + if ( !trg ) + return; - // restore splitter recursively - QMap< QSplitter*, QValueList > 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 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 >::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 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::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 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 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 allAreas; + areas( mySplit, allAreas, true ); + for ( QList::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 # + 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 # + *its = new_this; + ++its; + // set size to all items after an item # + 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 allAreas; + areas( mySplit, allAreas, true ); + for ( QList::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( 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 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 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( *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 areaList; + areas( (QSplitter*)(*it), areaList, true ); + for ( QList::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 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 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 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( (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 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& 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& 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 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 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 lst; + areas( mySplit, lst, true ); + for ( QList::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 recList; + splitters( split, recList, false ); + for ( QList::iterator itr = recList.begin(); itr != recList.end(); ++itr ) + updateState( *itr ); + + QList splitList; + splitters( split, splitList, false ); + + QList areaList; + areas( split, areaList, false ); + + bool vis = false; + for ( QList::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::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 sizes = split->sizes(); + for ( QList::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 "= ...". + 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 l = qFindChildren( parent->topLevelWidget(), aName ); + if ( !l.isEmpty() ) + view = ::qobject_cast( 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 >& 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 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 splitList; + QList areaList; + splitters( mySplit, splitList, false ); + areas( mySplit, areaList, false ); + for ( QList::iterator iter = splitList.begin(); iter != splitList.end(); ++iter ) + delete *iter; - QRect r = myArea->floatRect(); - int m = myPainter->pen().width(); + for ( QList::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 > 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::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 >::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 ); -} diff --git a/src/Qtx/QtxWorkstack.h b/src/Qtx/QtxWorkstack.h index c31479cc6..17adf9428 100644 --- a/src/Qtx/QtxWorkstack.h +++ b/src/Qtx/QtxWorkstack.h @@ -24,17 +24,17 @@ #include "Qtx.h" -#include -#include -#include -#include +#include +#include +#include +#include +#include class QAction; -class QTabBar; -class QPainter; class QSplitter; class QPushButton; -class QWidgetStack; +class QStackedWidget; +class QRubberBand; class QtxWorkstackArea; class QtxWorkstackDrag; @@ -50,13 +50,21 @@ class QTX_EXPORT QtxWorkstack : public QWidget 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: @@ -71,10 +79,12 @@ 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 ); @@ -101,13 +111,12 @@ private slots: 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&, const bool = false ) const; - void areas( QSplitter*, QPtrList&, const bool = false ) const; + void splitters( QSplitter*, QList&, const bool = false ) const; + void areas( QSplitter*, QList&, const bool = false ) const; QSplitter* wrapSplitter( QtxWorkstackArea* ); void insertWidget( QWidget*, QWidget*, QWidget* ); @@ -131,32 +140,34 @@ private: const int need_pos, const int splitter_pos ); void splitterInfo( QSplitter*, QString& ) const; - void setSplitter( QSplitter*, const QString&, QMap< QSplitter*,QValueList >& ); + void setSplitter( QSplitter*, const QString&, QMap< QSplitter*, QList >& ); 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 myActionsMap; //!< The map of the actions. Allows to get the QAction object by the key. + QMap 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; @@ -184,18 +195,17 @@ signals: 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* ); @@ -203,12 +213,16 @@ private slots: 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(); @@ -241,22 +255,22 @@ private: typedef QMap 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; @@ -265,7 +279,7 @@ public: signals: void shown( QtxWorkstackChild* ); - void hided( QtxWorkstackChild* ); + void hidden( QtxWorkstackChild* ); void activated( QtxWorkstackChild* ); void captionChanged( QtxWorkstackChild* ); @@ -276,7 +290,7 @@ protected: virtual void childEvent( QChildEvent* ); private: - QWidget* myWidget; + QWidget* myWidget; //!< child widget }; class QtxWorkstackTabBar : public QTabBar @@ -287,24 +301,33 @@ public: 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 @@ -329,17 +352,17 @@ private: 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 diff --git a/src/Qtx/QtxWorkstackAction.cxx b/src/Qtx/QtxWorkstackAction.cxx index a1dbcb974..4a4cb0f79 100644 --- a/src/Qtx/QtxWorkstackAction.cxx +++ b/src/Qtx/QtxWorkstackAction.cxx @@ -23,35 +23,45 @@ #include "QtxWorkstack.h" -#include -#include +#include +#include /*! - 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 { @@ -59,349 +69,299 @@ 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( 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( 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 lst = actions(); + for ( QList::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 items; + QMap 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::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( 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 ); } diff --git a/src/Qtx/QtxWorkstackAction.h b/src/Qtx/QtxWorkstackAction.h index 650184d24..a9228a507 100644 --- a/src/Qtx/QtxWorkstackAction.h +++ b/src/Qtx/QtxWorkstackAction.h @@ -22,7 +22,7 @@ #ifndef QTXWORKSTACKACTION_H #define QTXWORKSTACKACTION_H -#include "QtxAction.h" +#include "QtxActionSet.h" class QtxWorkstack; @@ -30,64 +30,56 @@ 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 MenuMap; - typedef QMap 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 diff --git a/src/RegistryDisplay/HelpWindow.cxx b/src/RegistryDisplay/HelpWindow.cxx deleted file mode 100755 index a94773105..000000000 --- a/src/RegistryDisplay/HelpWindow.cxx +++ /dev/null @@ -1,105 +0,0 @@ -// 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 -# include -# include -# include - -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 ); -} - - diff --git a/src/RegistryDisplay/HelpWindow.hxx b/src/RegistryDisplay/HelpWindow.hxx deleted file mode 100755 index 31f6405de..000000000 --- a/src/RegistryDisplay/HelpWindow.hxx +++ /dev/null @@ -1,52 +0,0 @@ -// 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 -#include - -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 diff --git a/src/RegistryDisplay/IntervalWindow.cxx b/src/RegistryDisplay/IntervalWindow.cxx deleted file mode 100755 index 780a876b4..000000000 --- a/src/RegistryDisplay/IntervalWindow.cxx +++ /dev/null @@ -1,129 +0,0 @@ -// 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 - -#include -#include -#include -#include -# 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; -} diff --git a/src/RegistryDisplay/IntervalWindow.hxx b/src/RegistryDisplay/IntervalWindow.hxx deleted file mode 100755 index 420ce5a0a..000000000 --- a/src/RegistryDisplay/IntervalWindow.hxx +++ /dev/null @@ -1,57 +0,0 @@ -// 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 -# include -# include -# include - -#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 diff --git a/src/RegistryDisplay/Makefile.am b/src/RegistryDisplay/Makefile.am deleted file mode 100755 index 2034b5001..000000000 --- a/src/RegistryDisplay/Makefile.am +++ /dev/null @@ -1,49 +0,0 @@ -# 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 diff --git a/src/RegistryDisplay/RegWidget.cxx b/src/RegistryDisplay/RegWidget.cxx deleted file mode 100755 index 413dca711..000000000 --- a/src/RegistryDisplay/RegWidget.cxx +++ /dev/null @@ -1,820 +0,0 @@ -// 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 -# include -# include -# include -# include -# include -# include -# include -# include -# include - -# 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( "" ) + QString( text ) + QString( "" ) ) - -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_::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; ilength(); 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( "

" ) + tr( "Code" ) + QString( " : " ); - a.append( QString( c_info.name ) ); - a.append( "



" ); - 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( "
" ); - - 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( " )
" ) + tr( "in directory" ) + QString( " " )); - a.append( BOLD( c_info.cdir ) ); - - time_t aTime; - a.append( QString( "
" ) + 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( "
" ); - - 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( "
" ); - 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( "
" ); - delete [] t3; - } - else - { - a.append( tr( "still running" ) + QString( "
" ) ); - } - - 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( ")
" ) ); - } - 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 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 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 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 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 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; -} diff --git a/src/RegistryDisplay/RegWidget.h b/src/RegistryDisplay/RegWidget.h deleted file mode 100755 index 3a1431777..000000000 --- a/src/RegistryDisplay/RegWidget.h +++ /dev/null @@ -1,116 +0,0 @@ -// 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 -# include - -#include -#include CORBA_CLIENT_HEADER(SALOME_Registry) - -#include - -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 diff --git a/src/RegistryDisplay/RegWidgetFactory.cxx b/src/RegistryDisplay/RegWidgetFactory.cxx deleted file mode 100755 index 7f285e686..000000000 --- a/src/RegistryDisplay/RegWidgetFactory.cxx +++ /dev/null @@ -1,48 +0,0 @@ -// 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; -} - -} diff --git a/src/ResExporter/ResExporter.pro b/src/ResExporter/ResExporter.pro new file mode 100644 index 000000000..1f96eae8a --- /dev/null +++ b/src/ResExporter/ResExporter.pro @@ -0,0 +1,17 @@ +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 + diff --git a/src/ResExporter/ResourceExporter.cxx b/src/ResExporter/ResourceExporter.cxx index 7788f8b7c..e133594f7 100644 --- a/src/ResExporter/ResourceExporter.cxx +++ b/src/ResExporter/ResourceExporter.cxx @@ -42,10 +42,10 @@ */ #include "SUIT_ResourceMgr.h" -#include -#include -#include -#include +#include +#include +#include +#include #include /*! @@ -59,11 +59,10 @@ static QString salomeVersion() 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() ) @@ -73,9 +72,9 @@ static QString salomeVersion() 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; } @@ -117,34 +116,34 @@ int main( int argc, char** argv ) 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] ); @@ -152,12 +151,12 @@ int main( int argc, char** argv ) } } 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 ); } diff --git a/src/SALOME_PYQT/SALOME_PYQT_GUI/Makefile.am b/src/SALOME_PYQT/SALOME_PYQT_GUI/Makefile.am index cf5e4c998..6d7757c58 100644 --- a/src/SALOME_PYQT/SALOME_PYQT_GUI/Makefile.am +++ b/src/SALOME_PYQT/SALOME_PYQT_GUI/Makefile.am @@ -22,25 +22,15 @@ 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 \ @@ -72,7 +62,7 @@ libSalomePyQtGUI_la_LIBADD= $(PYTHON_LIBS) $(SIP_LIBS) $(PYQT_LIBS) $(VTK_LIBS) # 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) diff --git a/src/SALOME_PYQT/SALOME_PYQT_GUI/SALOME_PYQT_GUI.h b/src/SALOME_PYQT/SALOME_PYQT_GUI/SALOME_PYQT_GUI.h index 8c436985c..0b646291a 100644 --- a/src/SALOME_PYQT/SALOME_PYQT_GUI/SALOME_PYQT_GUI.h +++ b/src/SALOME_PYQT/SALOME_PYQT_GUI/SALOME_PYQT_GUI.h @@ -21,7 +21,7 @@ // ======================================================== // set dllexport type for Win platform -#ifdef WNT +#ifdef WIN32 #ifdef SALOME_PYQT_EXPORTS #define SALOME_PYQT_EXPORT __declspec(dllexport) @@ -29,15 +29,15 @@ #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 diff --git a/src/SALOME_PYQT/SALOME_PYQT_GUI/SALOME_PYQT_Module.cxx b/src/SALOME_PYQT/SALOME_PYQT_GUI/SALOME_PYQT_Module.cxx index 048145b73..4d48c40e5 100644 --- a/src/SALOME_PYQT/SALOME_PYQT_GUI/SALOME_PYQT_Module.cxx +++ b/src/SALOME_PYQT/SALOME_PYQT_GUI/SALOME_PYQT_Module.cxx @@ -40,9 +40,6 @@ #include #include -#ifndef WIN32 -#include "SALOME_PYQT_SipDefs.h" -#endif #include "sipAPISalomePyQtGUI.h" #include "sipqtQWidget.h" @@ -116,17 +113,12 @@ private: // 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 diff --git a/src/SALOME_PYQT/SALOME_PYQT_GUI/SALOME_PYQT_SipDefs.h.in b/src/SALOME_PYQT/SALOME_PYQT_GUI/SALOME_PYQT_SipDefs.h.in deleted file mode 100644 index 2a427ce4c..000000000 --- a/src/SALOME_PYQT/SALOME_PYQT_GUI/SALOME_PYQT_SipDefs.h.in +++ /dev/null @@ -1 +0,0 @@ -#define SIP_VERS_@SIP_VERS@ diff --git a/src/SALOME_PYQT/SalomePyQt/Makefile.am b/src/SALOME_PYQT/SalomePyQt/Makefile.am index 50ee57d5c..1ae7eee2c 100644 --- a/src/SALOME_PYQT/SalomePyQt/Makefile.am +++ b/src/SALOME_PYQT/SalomePyQt/Makefile.am @@ -22,47 +22,19 @@ 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) \ @@ -84,44 +56,16 @@ COMMON_LIBS=$(PYTHON_LIBS) $(SIP_LIBS) $(PYQT_LIBS) $(VTK_LIBS) \ ../../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) diff --git a/src/SALOME_PYQT/SalomePyQt/SalomePyQt_v4.sip b/src/SALOME_PYQT/SalomePyQt/SalomePyQt_v4.sip deleted file mode 100644 index c550e2409..000000000 --- a/src/SALOME_PYQT/SalomePyQt/SalomePyQt_v4.sip +++ /dev/null @@ -1,171 +0,0 @@ -//============================================================================= -// 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 -%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 -%End - -private: - QtxAction(const QtxAction &); -}; - -class SalomePyQt -{ -%TypeHeaderCode -#include -%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/ ; -}; diff --git a/src/SOCC/Makefile.am b/src/SOCC/Makefile.am index 25db60672..e822208e5 100755 --- a/src/SOCC/Makefile.am +++ b/src/SOCC/Makefile.am @@ -46,5 +46,5 @@ libSOCC_la_CPPFLAGS=$(QT_INCLUDES) $(CAS_CPPFLAGS) $(BOOST_CPPFLAGS) \ -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 diff --git a/src/SOCC/SOCC.h b/src/SOCC/SOCC.h index 99e77291a..40d28ff8a 100755 --- a/src/SOCC/SOCC.h +++ b/src/SOCC/SOCC.h @@ -16,7 +16,7 @@ // // 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 @@ -26,6 +26,6 @@ #define SOCC_EXPORT #endif -#if defined WNT +#if defined WIN32 #pragma warning ( disable: 4251 ) #endif diff --git a/src/SOCC/SOCC.pro b/src/SOCC/SOCC.pro new file mode 100644 index 000000000..488f9f37c --- /dev/null +++ b/src/SOCC/SOCC.pro @@ -0,0 +1,33 @@ +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 diff --git a/src/SOCC/SOCC_Prs.cxx b/src/SOCC/SOCC_Prs.cxx index eb2cb6821..ad6f3154d 100644 --- a/src/SOCC/SOCC_Prs.cxx +++ b/src/SOCC/SOCC_Prs.cxx @@ -27,6 +27,9 @@ // $Header$ #include "SOCC_Prs.h" + +#include + using namespace std; /*! diff --git a/src/SOCC/SOCC_Prs.h b/src/SOCC/SOCC_Prs.h index 06fbce141..60dca4b3b 100644 --- a/src/SOCC/SOCC_Prs.h +++ b/src/SOCC/SOCC_Prs.h @@ -33,9 +33,10 @@ #include -#include #include +class Handle(AIS_InteractiveObject); + class SOCC_EXPORT SOCC_Prs : public SALOME_OCCPrs { public: diff --git a/src/SOCC/SOCC_ViewModel.cxx b/src/SOCC/SOCC_ViewModel.cxx index 8d27c10a7..fd046f662 100755 --- a/src/SOCC/SOCC_ViewModel.cxx +++ b/src/SOCC/SOCC_ViewModel.cxx @@ -22,7 +22,8 @@ #include "SOCC_ViewWindow.h" #include "SUIT_Session.h" -#include "SUIT_Application.h" +#include "SUIT_ResourceMgr.h" +//#include "SUIT_Application.h" //#include "ToolsGUI.h" @@ -37,6 +38,7 @@ #include #include +#include // Temporarily commented to avoid awful dependecy on SALOMEDS // TODO: better mechanism of storing display/erse status in a study @@ -289,7 +291,7 @@ void SOCC_Viewer::rename( const Handle(SALOME_InteractiveObject)& obj, Handle(SALOME_InteractiveObject) IO = aSh->getIO(); if ( IO->isSame( obj ) ) { - aSh->setName( (char*)name.latin1() ); + aSh->setName( name.toLatin1().data() ); break; } } diff --git a/src/SOCC/SOCC_ViewModel.h b/src/SOCC/SOCC_ViewModel.h index 6d2d04025..792616a62 100755 --- a/src/SOCC/SOCC_ViewModel.h +++ b/src/SOCC/SOCC_ViewModel.h @@ -26,7 +26,8 @@ #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 { diff --git a/src/SPlot2d/Makefile.am b/src/SPlot2d/Makefile.am index 17dc25b37..b06302d36 100644 --- a/src/SPlot2d/Makefile.am +++ b/src/SPlot2d/Makefile.am @@ -39,8 +39,6 @@ MOC_FILES = \ 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 diff --git a/src/SPlot2d/SPlot2d.h b/src/SPlot2d/SPlot2d.h index 39e4c1245..475bc6cf3 100644 --- a/src/SPlot2d/SPlot2d.h +++ b/src/SPlot2d/SPlot2d.h @@ -16,7 +16,7 @@ // // 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 @@ -26,6 +26,6 @@ #define SPLOT2D_EXPORT #endif -#if defined WNT +#if defined WIN32 #pragma warning ( disable: 4251 ) #endif diff --git a/src/SPlot2d/SPlot2d.pro b/src/SPlot2d/SPlot2d.pro new file mode 100644 index 000000000..4e6d41e6a --- /dev/null +++ b/src/SPlot2d/SPlot2d.pro @@ -0,0 +1,45 @@ +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 diff --git a/src/SPlot2d/SPlot2d_Curve.cxx b/src/SPlot2d/SPlot2d_Curve.cxx index 87439441f..e9940595d 100644 --- a/src/SPlot2d/SPlot2d_Curve.cxx +++ b/src/SPlot2d/SPlot2d_Curve.cxx @@ -21,6 +21,9 @@ // Module : SUIT #include "SPlot2d_Curve.h" +#include +#include + using namespace std; /*! diff --git a/src/SPlot2d/SPlot2d_Curve.h b/src/SPlot2d/SPlot2d_Curve.h index f75519ead..ba0667a18 100644 --- a/src/SPlot2d/SPlot2d_Curve.h +++ b/src/SPlot2d/SPlot2d_Curve.h @@ -27,14 +27,14 @@ #include "Plot2d_Curve.h" -#include -#include -#include #ifndef _Handle_SALOME_InteractiveObject_HeaderFile #include #endif #include "SALOME_InteractiveObject.hxx" +class QString; +class QColor; + class SPLOT2D_EXPORT SPlot2d_Curve : public Plot2d_Curve { public: diff --git a/src/SPlot2d/SPlot2d_Prs.cxx b/src/SPlot2d/SPlot2d_Prs.cxx index 68739a0c6..e61efbc3f 100644 --- a/src/SPlot2d/SPlot2d_Prs.cxx +++ b/src/SPlot2d/SPlot2d_Prs.cxx @@ -21,7 +21,7 @@ // Module : SUIT #include "SPlot2d_Prs.h" -#ifndef WNT +#ifndef WIN32 using namespace std; #endif diff --git a/src/SPlot2d/SPlot2d_Prs.h b/src/SPlot2d/SPlot2d_Prs.h index 77e878172..033aeb1ff 100644 --- a/src/SPlot2d/SPlot2d_Prs.h +++ b/src/SPlot2d/SPlot2d_Prs.h @@ -27,8 +27,6 @@ #include "SALOME_Prs.h" #include "Plot2d_Prs.h" -#include - class Plot2d_Curve; class SPLOT2D_EXPORT SPlot2d_Prs : public SALOME_Prs2d, public Plot2d_Prs diff --git a/src/SPlot2d/SPlot2d_ViewModel.cxx b/src/SPlot2d/SPlot2d_ViewModel.cxx index 527a8a135..aa892cef2 100644 --- a/src/SPlot2d/SPlot2d_ViewModel.cxx +++ b/src/SPlot2d/SPlot2d_ViewModel.cxx @@ -27,15 +27,18 @@ #include "SPlot2d_Prs.h" #include "SUIT_Session.h" #include "SUIT_Application.h" +#include "SUIT_ViewManager.h" //#include "utilities.h" -#include "qapplication.h" -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include + +//#include #include +#include #include using namespace std; @@ -90,20 +93,19 @@ void SPlot2d_Viewer::rename( const Handle(SALOME_InteractiveObject)& IObject, if( !aViewFrame ) return; - QIntDictIterator 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( it.current() ); + SPlot2d_Curve* aCurve = dynamic_cast( 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(); } @@ -118,7 +120,8 @@ void SPlot2d_Viewer::renameAll( const Handle(SALOME_InteractiveObject)& IObj, co SUIT_ViewManager* vm = getViewManager(); if ( vm ) { - const QPtrVector& wnds = vm->getViews(); + const QVector& wnds = vm->getViews(); + for ( uint i = 0; i < wnds.size(); i++ ) { Plot2d_ViewWindow* pwnd = dynamic_cast( wnds.at( i ) ); @@ -139,10 +142,11 @@ bool SPlot2d_Viewer::isInViewer( const Handle(SALOME_InteractiveObject)& IObject return 1; else{ if(!IObject.IsNull()){ - QIntDictIterator it(aViewFrame->getCurves()); - for(; it.current();++it) { - SPlot2d_Curve* aCurve = dynamic_cast(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( it.value() ); + if(aCurve && aCurve->hasIO() && aCurve->getTableIO()->isSame(IObject)) return 1; } } @@ -174,9 +178,10 @@ void SPlot2d_Viewer::DisplayOnly( const Handle(SALOME_InteractiveObject)& IObjec if(aViewFrame == NULL) return; Plot2d_Curve* curve = getCurveByIO( IObject ); - QIntDictIterator 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 ); @@ -308,10 +313,11 @@ Handle(SALOME_InteractiveObject) SPlot2d_Viewer::FindIObject( const char* Entry Plot2d_ViewFrame* aViewFrame = getActiveViewFrame(); if(aViewFrame == NULL) return anIO; - QIntDictIterator it( aViewFrame->getCurves() ); - for ( ; it.current(); ++it ) { - SPlot2d_Curve* aCurve = dynamic_cast(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(it.value()); + if ( aCurve && aCurve->hasIO() && !strcmp( aCurve->getIO()->getEntry(), Entry ) ) { anIO = aCurve->getIO(); break; } @@ -345,9 +351,10 @@ SPlot2d_Curve* SPlot2d_Viewer::getCurveByIO( const Handle(SALOME_InteractiveObje if ( !theIObject.IsNull() ) { Plot2d_ViewFrame* aViewFrame = fr ? fr : getActiveViewFrame(); if(aViewFrame) { - QIntDictIterator it( aViewFrame->getCurves() ); - for ( ; it.current(); ++it ) { - SPlot2d_Curve* aCurve = dynamic_cast(it.current()); + CurveDict aCurves = aViewFrame->getCurves(); + CurveDict::Iterator it = aCurves.begin(); + for( ; it != aCurves.end(); ++it ) { + SPlot2d_Curve* aCurve = dynamic_cast( it.value() ); if(aCurve) { if ( aCurve->hasIO() && aCurve->getIO()->isSame( theIObject ) ) return aCurve; @@ -372,13 +379,14 @@ void SPlot2d_Viewer::onCloneView( Plot2d_ViewFrame* clonedVF, Plot2d_ViewFrame* // 2) Display all curves displayed in cloned view - QList aCurves; - clonedVF->getCurves( aCurves ); - QList::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( anIt.value() ); + if( aCurve && clonedVF->isVisible( aCurve ) ) + newVF->displayCurve( aCurve, false ); + } newVF->Repaint(); } diff --git a/src/STD/Makefile.am b/src/STD/Makefile.am index 9b5295002..fb967d853 100755 --- a/src/STD/Makefile.am +++ b/src/STD/Makefile.am @@ -25,55 +25,50 @@ include $(top_srcdir)/adm_local/unix/make_common_starter.am 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 diff --git a/src/STD/STD.h b/src/STD/STD.h index caeee3b3f..e974b5255 100755 --- a/src/STD/STD.h +++ b/src/STD/STD.h @@ -19,18 +19,14 @@ #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 @@ -39,7 +35,7 @@ #define true 1 #endif -#if defined WNT +#if defined WIN32 #pragma warning ( disable: 4251 ) #endif diff --git a/src/STD/STD.pro b/src/STD/STD.pro new file mode 100644 index 000000000..b895bb959 --- /dev/null +++ b/src/STD/STD.pro @@ -0,0 +1,38 @@ +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 diff --git a/src/STD/STD_Application.cxx b/src/STD/STD_Application.cxx index 90690cad7..5c554f9a1 100755 --- a/src/STD/STD_Application.cxx +++ b/src/STD/STD_Application.cxx @@ -20,29 +20,23 @@ #include "STD_MDIDesktop.h" -#include "STD_CloseDlg.h" - #include +#include #include #include -#include -#include #include +#include #include #include #include #include -#include - -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include /*!Create and return new instance of STD_Application*/ extern "C" STD_EXPORT SUIT_Application* createApplication() @@ -53,12 +47,11 @@ 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.*/ @@ -67,6 +60,18 @@ STD_Application::~STD_Application() 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 { @@ -96,15 +101,20 @@ void STD_Application::closeApplication() savePreferences(); SUIT_Study* study = activeStudy(); - if ( study ){ + if ( study ) + { + beforeCloseDoc( study ); + study->closeDocument(); setActiveStudy( 0 ); delete study; + + afterCloseDoc(); } setDesktop( 0 ); - + SUIT_Application::closeApplication(); } @@ -117,7 +127,8 @@ void STD_Application::onDesktopClosing( SUIT_Desktop*, QCloseEvent* e ) return; } - if ( !isPossibleToClose() ) + bool closePermanently; + if ( !isPossibleToClose( closePermanently ) ) { e->ignore(); return; @@ -139,57 +150,62 @@ void STD_Application::createActions() 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 @@ -215,6 +231,7 @@ void STD_Application::createActions() createMenu( EditPasteId, editMenu ); createMenu( separator(), editMenu ); + createMenu( ViewToolBarsId, viewMenu, 0 ); createMenu( ViewWindowsId, viewMenu, 0 ); createMenu( separator(), viewMenu, -1, 10 ); createMenu( ViewStatusBarId, viewMenu, 10 ); @@ -241,27 +258,44 @@ void STD_Application::createActions() /*!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*/ @@ -278,7 +312,7 @@ void STD_Application::onOpenDoc() /*! \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() ) @@ -290,12 +324,12 @@ bool STD_Application::onOpenDoc( const QString& aName ) { // if study exists - open in new desktop. Check: is the same file is opened? SUIT_Session* aSession = SUIT_Session::session(); - QPtrList aAppList = aSession->applications(); + QList aAppList = aSession->applications(); bool isAlreadyOpen = false; SUIT_Application* aApp = 0; - for ( QPtrListIterator it( aAppList ); it.current() && !isAlreadyOpen; ++it ) + for ( QList::iterator it = aAppList.begin(); it != aAppList.end() && !isAlreadyOpen; ++it ) { - aApp = it.current(); + aApp = *it; if ( aApp->activeStudy()->studyName() == aName ) isAlreadyOpen = true; } @@ -308,7 +342,7 @@ bool STD_Application::onOpenDoc( const QString& aName ) aApp->closeApplication(); } else - aApp->desktop()->setActiveWindow(); + aApp->desktop()->activateWindow(); } QApplication::restoreOverrideCursor(); @@ -329,12 +363,12 @@ bool STD_Application::onLoadDoc( const QString& aName ) { // if study exists - load in new desktop. Check: is the same file is loaded? SUIT_Session* aSession = SUIT_Session::session(); - QPtrList aAppList = aSession->applications(); + QList aAppList = aSession->applications(); bool isAlreadyOpen = false; SUIT_Application* aApp = 0; - for ( QPtrListIterator it( aAppList ); it.current() && !isAlreadyOpen; ++it ) + for ( QList::iterator it = aAppList.begin(); it != aAppList.end() && !isAlreadyOpen; ++it ) { - aApp = it.current(); + aApp = *it; if ( aApp->activeStudy()->studyName() == aName ) isAlreadyOpen = true; } @@ -345,7 +379,7 @@ bool STD_Application::onLoadDoc( const QString& aName ) res = aApp->useStudy( aName ); } else - aApp->desktop()->setActiveWindow(); + aApp->desktop()->activateWindow(); } return res; } @@ -363,7 +397,9 @@ void STD_Application::afterCloseDoc() /*!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(); @@ -371,7 +407,7 @@ void STD_Application::onCloseDoc( bool ask ) beforeCloseDoc( study ); if ( study ) - study->closeDocument(myClosePermanently); + study->closeDocument( closePermanently ); clearViewManagers(); @@ -379,12 +415,10 @@ void STD_Application::onCloseDoc( bool ask ) delete study; int aNbStudies = 0; - QPtrList apps = SUIT_Session::session()->applications(); - for ( unsigned i = 0; i < apps.count(); i++ ) + QList 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(); @@ -405,42 +439,56 @@ void STD_Application::onCloseDoc( bool ask ) /*!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() { @@ -452,7 +500,7 @@ void STD_Application::onSaveDoc() { putInfo( tr( "INF_DOC_SAVING" ) + activeStudy()->studyName() ); - QApplication::setOverrideCursor( Qt::waitCursor ); + QApplication::setOverrideCursor( Qt::WaitCursor ); isOk = activeStudy()->saveDocument(); @@ -462,10 +510,8 @@ void STD_Application::onSaveDoc() { 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( "" ) ); @@ -491,7 +537,7 @@ bool STD_Application::onSaveAsDoc() if ( aName.isNull() ) return false; - QApplication::setOverrideCursor( Qt::waitCursor ); + QApplication::setOverrideCursor( Qt::WaitCursor ); putInfo( tr( "INF_DOC_SAVING" ) + aName ); isOk = study->saveDocumentAs( aName ); @@ -501,9 +547,7 @@ bool STD_Application::onSaveAsDoc() 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() ); @@ -514,9 +558,11 @@ bool STD_Application::onSaveAsDoc() /*!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(); } @@ -566,12 +612,12 @@ void STD_Application::updateDesktopTitle() 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.*/ @@ -596,10 +642,10 @@ void STD_Application::updateCommandsStatus() SUIT_ViewManager* STD_Application::viewManager( const QString& vmType ) const { SUIT_ViewManager* vm = 0; - for ( QPtrListIterator it( myViewMgrs ); it.current() && !vm; ++it ) + for ( QList::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; } @@ -609,16 +655,18 @@ SUIT_ViewManager* STD_Application::viewManager( const QString& vmType ) const */ void STD_Application::viewManagers( const QString& vmType, ViewManagerList& lst ) const { - for ( QPtrListIterator it( myViewMgrs ); it.current(); ++it ) - if ( it.current()->getType() == vmType ) - lst.append( it.current() ); + for ( QList::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 it( myViewMgrs ); it.current(); ++it ) - lst.append( it.current() ); + for ( QList::const_iterator it = myViewMgrs.begin(); it != myViewMgrs.end(); ++it ) + lst.append( *it ); } /*!\retval ViewManagerList - const list of all view managers.*/ @@ -669,7 +717,7 @@ void STD_Application::removeViewManager( SUIT_ViewManager* vm ) 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; @@ -681,8 +729,9 @@ void STD_Application::clearViewManagers() ViewManagerList lst; viewManagers( lst ); - for ( QPtrListIterator it( lst ); it.current(); ++it ) { - QGuardedPtr vm = it.current(); + for ( QList::iterator it = lst.begin(); it != lst.end(); ++it ) + { + QPointer vm = *it; removeViewManager( vm ); delete vm; } @@ -691,7 +740,7 @@ void STD_Application::clearViewManagers() /*!\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.*/ @@ -712,7 +761,7 @@ void STD_Application::onViewStatusBar( bool on ) /*!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 @@ -721,10 +770,6 @@ void STD_Application::onHelpAbout() 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.*/ @@ -740,25 +785,23 @@ void STD_Application::setActiveViewManager( SUIT_ViewManager* vm ) /*!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 - /*!\retval QString - return file name from dialog.*/ QString STD_Application::getFileName( bool open, const QString& initial, const QString& filters, const QString& caption, QWidget* parent ) @@ -766,9 +809,7 @@ QString STD_Application::getFileName( bool open, const QString& initial, const Q if ( !parent ) parent = desktop(); if ( open ) - { - return QFileDialog::getOpenFileName( initial, filters, parent, 0, caption ); - } + return QFileDialog::getOpenFileName( parent, caption, initial, filters ); else { QString aName; @@ -779,45 +820,45 @@ QString STD_Application::getFileName( bool open, const QString& initial, const Q 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; @@ -829,7 +870,8 @@ QString STD_Application::getDirectory( const QString& initial, const QString& ca { if ( !parent ) parent = desktop(); - return QFileDialog::getExistingDirectory( initial, parent, 0, caption, true ); + + return QFileDialog::getExistingDirectory( parent, caption, initial ); } /*! diff --git a/src/STD/STD_Application.h b/src/STD/STD_Application.h index 4e766ca98..3ff6d57bc 100755 --- a/src/STD/STD_Application.h +++ b/src/STD/STD_Application.h @@ -23,20 +23,22 @@ #include -#include -#include +#include -#include -#include +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 ViewManagerList; +typedef QList ViewManagerList; #if defined WIN32 #pragma warning( disable: 4251 ) @@ -46,13 +48,20 @@ class STD_EXPORT STD_Application : public SUIT_Application { 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(); @@ -75,14 +84,17 @@ public: 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*/ @@ -94,6 +106,8 @@ signals: public slots: virtual void onNewDoc(); + virtual bool onNewDoc( const QString& ); + virtual void onCloseDoc( bool ask = true ); virtual void onSaveDoc(); virtual bool onSaveAsDoc(); @@ -125,14 +139,6 @@ protected: MenuHelpId = 7 }; - enum { FileNewId, FileOpenId, FileCloseId, - FileSaveId, FileSaveAsId, FileExitId, - ViewStatusBarId, ViewWindowsId, NewWindowId, - EditCutId, EditCopyId, EditPasteId, - HelpAboutId, - UserID - }; - protected: virtual void createActions(); virtual void updateDesktopTitle(); @@ -152,13 +158,16 @@ protected: 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 diff --git a/src/STD/STD_CloseDlg.cxx b/src/STD/STD_CloseDlg.cxx deleted file mode 100644 index ff09c551a..000000000 --- a/src/STD/STD_CloseDlg.cxx +++ /dev/null @@ -1,100 +0,0 @@ -// 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 -#include -#include -#include -#include - -#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 ); -} diff --git a/src/STD/STD_CloseDlg.h b/src/STD/STD_CloseDlg.h deleted file mode 100644 index 6975e88f4..000000000 --- a/src/STD/STD_CloseDlg.h +++ /dev/null @@ -1,62 +0,0 @@ -// 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 - -/*! \class QDialog - * \brief For more information see QT documentation. - */ -/*!\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 - diff --git a/src/STD/STD_LoadStudiesDlg.cxx b/src/STD/STD_LoadStudiesDlg.cxx deleted file mode 100644 index 5dc4c0d5a..000000000 --- a/src/STD/STD_LoadStudiesDlg.cxx +++ /dev/null @@ -1,84 +0,0 @@ -// 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 -#include -#include -#include - -#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() ) ); -} - diff --git a/src/STD/STD_LoadStudiesDlg.h b/src/STD/STD_LoadStudiesDlg.h deleted file mode 100644 index 268b16135..000000000 --- a/src/STD/STD_LoadStudiesDlg.h +++ /dev/null @@ -1,69 +0,0 @@ -// 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 - -#include -#include - -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 diff --git a/src/STD/STD_MDIDesktop.cxx b/src/STD/STD_MDIDesktop.cxx index 9a446ab64..7fc268671 100755 --- a/src/STD/STD_MDIDesktop.cxx +++ b/src/STD/STD_MDIDesktop.cxx @@ -22,29 +22,32 @@ #include #include -#include +#include #include #include -#include -#include -#include -#include +#include +#include #include -/*!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* ) ) ); @@ -52,12 +55,16 @@ myWorkspaceAction( 0 ) 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; @@ -69,25 +76,33 @@ SUIT_ViewWindow* STD_MDIDesktop::activeWindow() const return wnd; } -/*!\retval QPtrList - return const active window list.*/ -QPtrList STD_MDIDesktop::windows() const +/*! + \retval QList - return const active window list. +*/ +QList STD_MDIDesktop::windows() const { - QPtrList winList; + QList 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( *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.*/ @@ -100,45 +115,51 @@ void STD_MDIDesktop::windowOperation( const int type ) void STD_MDIDesktop::setWindowOperations( const int first, ... ) { va_list ints; - va_start( ints, first ); - - QValueList typeList; + va_start( ints, first ); - int cur = first; - while ( cur ) - { - typeList.append( cur ); - cur = va_arg( ints, int ); + QList 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& opList ) +void STD_MDIDesktop::setWindowOperations( const QList& opList ) { int flags = 0; - for ( QValueList::const_iterator it = opList.begin(); it != opList.end(); ++it ) + for ( QList::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 ) @@ -150,40 +171,39 @@ void STD_MDIDesktop::createActions() 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 ); } diff --git a/src/STD/STD_MDIDesktop.h b/src/STD/STD_MDIDesktop.h index f4136444d..a3506a468 100755 --- a/src/STD/STD_MDIDesktop.h +++ b/src/STD/STD_MDIDesktop.h @@ -23,12 +23,10 @@ #include -class QtxAction; -class QPopupMenu; -class QWorkspace; +class QtxWorkspace; class QtxWorkspaceAction; -#if defined WNT +#if defined WIN32 #pragma warning( disable: 4251 ) #endif @@ -37,7 +35,6 @@ class STD_EXPORT STD_MDIDesktop: public SUIT_Desktop Q_OBJECT public: - enum { MenuWindowId = 6 }; enum { Cascade, Tile, HTile, VTile }; public: @@ -45,31 +42,31 @@ public: virtual ~STD_MDIDesktop(); virtual SUIT_ViewWindow* activeWindow() const; - virtual QPtrList windows() const; + virtual QList windows() const; void windowOperation( const int ); void setWindowOperations( const int, ... ); - void setWindowOperations( const QValueList& ); + void setWindowOperations( const QList& ); - 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 diff --git a/src/STD/STD_SDIDesktop.cxx b/src/STD/STD_SDIDesktop.cxx index 9bcc92a56..1c9a08fd6 100755 --- a/src/STD/STD_SDIDesktop.cxx +++ b/src/STD/STD_SDIDesktop.cxx @@ -20,16 +20,18 @@ #include -#include -#include -#include +#include +#include /*!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 ); } @@ -42,40 +44,42 @@ STD_SDIDesktop::~STD_SDIDesktop() /*!\retval SUIT_ViewWindow - return const active window.*/ SUIT_ViewWindow* STD_SDIDesktop::activeWindow() const { - const QObjectList* children = myMainWidget->children(); - if ( !children ) - return 0; - - QPtrList winList; - for ( QObjectListIt it( *children ); it.current(); ++it ) + const QObjectList& lst = myMainWidget->children(); + QList 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( *it ); + if ( vw ) + winList.append( vw ); } SUIT_ViewWindow* win = 0; - for ( QPtrListIterator itr( winList ); itr.current() && !win; ++itr ) + for ( QList::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 - return const active window list.*/ -QPtrList STD_SDIDesktop::windows() const +QList STD_SDIDesktop::windows() const { - QPtrList winList; - winList.append( activeWindow() ); + QList 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 ); } diff --git a/src/STD/STD_SDIDesktop.h b/src/STD/STD_SDIDesktop.h index 78b1bb78d..c963a28b0 100755 --- a/src/STD/STD_SDIDesktop.h +++ b/src/STD/STD_SDIDesktop.h @@ -23,7 +23,7 @@ #include -class QVBox; +class QFrame; class STD_EXPORT STD_SDIDesktop: public SUIT_Desktop { @@ -34,13 +34,13 @@ public: virtual ~STD_SDIDesktop(); virtual SUIT_ViewWindow* activeWindow() const; - virtual QPtrList windows() const; + virtual QList windows() const; protected: - virtual QWidget* parentArea() const; + virtual void addWindow( QWidget* ); private: - QVBox* myMainWidget; + QFrame* myMainWidget; }; #endif diff --git a/src/STD/STD_TabDesktop.cxx b/src/STD/STD_TabDesktop.cxx index 645188035..d66c6c94f 100644 --- a/src/STD/STD_TabDesktop.cxx +++ b/src/STD/STD_TabDesktop.cxx @@ -22,15 +22,12 @@ #include #include -#include #include #include #include -#include -#include -#include -#include +#include +#include #include @@ -40,20 +37,24 @@ STD_TabDesktop::STD_TabDesktop() 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* ) ) ); @@ -61,12 +62,16 @@ myWorkstackAction( 0 ) 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; @@ -78,40 +83,51 @@ SUIT_ViewWindow* STD_TabDesktop::activeWindow() const return wnd; } -/*!\retval QPtrList - return const active window list.*/ -QPtrList STD_TabDesktop::windows() const +/*! + \retval QPtrList - return const active window list. +*/ +QList STD_TabDesktop::windows() const { - QPtrList winList; + QList 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 typeList; + QList typeList; int cur = first; while ( cur ) @@ -123,31 +139,39 @@ void STD_TabDesktop::setWindowOperations( const int first, ... ) setWindowOperations( typeList ); } -/*!Sets window operations by variable \a opList - operation list.*/ -void STD_TabDesktop::setWindowOperations( const QValueList& opList ) +/*! + Sets window operations by variable \a opList - operation list. +*/ +void STD_TabDesktop::setWindowOperations( const QList& opList ) { int flags = 0; - for ( QValueList::const_iterator it = opList.begin(); it != opList.end(); ++it ) + for ( QList::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 ) @@ -159,41 +183,44 @@ void STD_TabDesktop::createActions() 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; } diff --git a/src/STD/STD_TabDesktop.h b/src/STD/STD_TabDesktop.h index aa63db065..35d09cd29 100644 --- a/src/STD/STD_TabDesktop.h +++ b/src/STD/STD_TabDesktop.h @@ -23,13 +23,10 @@ #include -class QtxAction; -class QPopupMenu; -class QWorkspace; class QtxWorkstack; class QtxWorkstackAction; -#if defined WNT +#if defined WIN32 #pragma warning( disable: 4251 ) #endif @@ -38,20 +35,19 @@ class STD_EXPORT STD_TabDesktop: public SUIT_Desktop 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 windows() const; + virtual QList windows() const; void windowOperation( const int ); void setWindowOperations( const int, ... ); - void setWindowOperations( const QValueList& ); + void setWindowOperations( const QList& ); QtxWorkstack* workstack() const; @@ -60,7 +56,7 @@ private slots: protected: void createActions(); - virtual QWidget* parentArea() const; + virtual void addWindow( QWidget* ); private: int operationFlag( const int ) const; @@ -70,7 +66,7 @@ private: QtxWorkstackAction* myWorkstackAction; }; -#if defined WNT +#if defined WIN32 #pragma warning( default: 4251 ) #endif diff --git a/src/STD/resources/STD_images.ts b/src/STD/resources/STD_images.ts new file mode 100644 index 000000000..90fe0caa3 --- /dev/null +++ b/src/STD/resources/STD_images.ts @@ -0,0 +1,96 @@ + + + @default + + ICON_FILE_NEW + new.png + + + ICON_DESK_WINDOW_TILE + tile.png + + + ICON_PRINT + print.png + + + ICON_RESET + reset.png + + + ICON_HELP + help.png + + + ICON_EDIT_CUT + cut.png + + + ICON_DESK_WINDOW_CASCADE + cascade.png + + + ICON_EDIT_COPY + copy.png + + + ICON_APP_DEFAULTICON + default.png + + + ICON_FILE_SAVE + save.png + + + ICON_FILE_OPEN + open.png + + + ICON_DESK_WINDOW_HSPLIT + htile.png + + + ICON_APP_EDIT_REDO + redo.png + + + ICON_APP_EDIT_UNDO + undo.png + + + ICON_DESK_WINDOW_VSPLIT + vtile.png + + + ICON_DESK_DEFAULTICON + default.png + + + ICON_DESK_WINDOW_HTILE + htile.png + + + ICON_DESK_WINDOW_VTILE + vtile.png + + + ICON_EDIT_PASTE + paste.png + + + ICON_FILE_CLOSE + close.png + + + + SUIT_ViewPort + + ICON_CURSOR_ZOOM + cursor_zoom.png + + + ICON_CURSOR_ROTATE + cursor_rotate.png + + + diff --git a/src/STD/resources/STD_msg_en.po b/src/STD/resources/STD_msg_en.po index eef69e683..7956e4586 100755 --- a/src/STD/resources/STD_msg_en.po +++ b/src/STD/resources/STD_msg_en.po @@ -344,15 +344,6 @@ msgstr "Saving study " 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" @@ -362,12 +353,6 @@ msgstr "Load a 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" diff --git a/src/STD/resources/STD_msg_en.ts b/src/STD/resources/STD_msg_en.ts new file mode 100644 index 000000000..83316ceae --- /dev/null +++ b/src/STD/resources/STD_msg_en.ts @@ -0,0 +1,468 @@ + + + @default + + TOT_DESK_EDIT_CUT + Cut + + + PRP_DESK_EDIT_CUT + Cuts the selection and puts it to the Clipboard + + + MEN_DESK_EDIT_CUT + Cu&t + + + ERR_APP_NOAPP + No application + + + MEN_DESK_WINDOW + &Window + + + TOT_DESK_EDIT_COPY + Copy + + + MEN_DESK_WINDOW_CASCADE + &Cascade + + + PRP_DESK_EDIT_COPY + Copy the selection to the Clipboard + + + PRP_DESK_WINDOW_CASCADE + Arranges the windows as overlapping tiles + + + TOT_DESK_FILE_SAVEAS + Save document as... + + + MEN_DESK_EDIT_COPY + &Copy + + + MSG_CANT_SAVE + Can't save file "%1". + + + INF_DESK_TOOLBAR_STANDARD + Standard + + + ALL_FILES + All Files (*.*) + + + DESK_DEFAULTTITLE + Qt Application Desktop + + + QUE_DESK_EXIT + Do you really want to quit ? + + + INF_INFO + Information + + + ERR_DOC_UNKNOWNTYPE_OPEN + You are trying to open a document of an unknown type +( %1 ) + + + ERR_DOC_UNKNOWNTYPE_SAVE + You are trying to save this document under an unknown type +( %1 ) + + + TOT_DESK_NEWWINDOW + Create new Window + + + BUT_CANCEL + &Cancel + + + MEN_DESK_HELP_ABOUT + &About... + + + PRP_DESK_NEWWINDOW + Create new Window + + + MEN_DESK_VIEW_STATUSBAR + &Status Bar + + + MEN_DESK_NEWWINDOW + &New Window + + + PRP_DESK_VIEW_STATUSBAR + Toggles status bar view on/off + + + ERR_DOC_DIRWITHNAMEEXIST_SAVE + Can not save file %1. +Directory with this name exist on disc. Try to use another name + + + BUT_NO + &No + + + BUT_OK + &Ok + + + FILTER_FILES + %1 Files (%2) + + + PRP_DESK_WINDOW_ACTIVATE + Activates this window + + + TOT_DESK_FILE_PRINT + Print document + + + TOT_DESK_FILE_CLOSE + Close document + + + TOT_DESK_FILE_NEW + New document + + + PRP_DESK_FILE_NEW + Creates a new document + + + PRP_DESK_FILE_MRU + Opens a document + + + MEN_DESK_FILE_NEW + &New + + + MEN_DESK_FILE_MRU + Recent &Files + + + TOT_DESK_EDIT_PASTE + Paste + + + BUT_YES + &Yes + + + MEN_DESK_VIEW + &View + + + PRP_DESK_HELP_ABOUT + Shows 'About' dialog + + + MEN_DESK_FILE + &File + + + MEN_DESK_EDIT + &Edit + + + MEN_DESK_HELP + &Help + + + ERR_ERROR + Error + + + ERR_DESK_NOAPP + No applications registered + + + INF_DESK_DOC_CREATE + Create a new document + + + QUE_DOC_ALREADYOPEN + The document %1 is already open. +Do you want to reload it ? + + + BUT_APPLY + &Apply + + + BUT_CLOSE + &Close + + + INF_DESK_EXIT + Exit + + + ERR_UNKNOWN + Unknown error + + + BUT_HELP + &Help + + + PRP_DESK_FILE_CLOSE + Closes the active document + + + PRP_DESK_FILE_PRINT + Prints the active document + + + WRN_WARNING + Warning + + + TOT_DESK_HELP_ABOUT + About... + + + MEN_DESK_VIEW_TOOLBARS + T&oolbars + + + PRP_DESK_WINDOW_HSPLIT + Splits the active window on two horizontal parts + + + MEN_DESK_WINDOW_HSPLIT + Split &Horizontally + + + PRP_DESK_EDIT_PASTE + Inserts the Clipboard content at the insertion point + + + DLG_LOAD_STUDY_CAPTION + Load Study + + + CLOSE_STUDY + Close study + + + PRP_DESK_HELP_SEARCH + Searches help for a topic + + + PRP_DESK_FILE_SAVEAS + Saves the active document with a new name + + + INF_READY + Ready + + + INF_CANCELLED + Cancelled + + + PRP_DESK_WINDOW_VSPLIT + Splits the active window on two vertical parts + + + MEN_DESK_WINDOW_VSPLIT + Split &Vertically + + + PRP_DESK_WINDOW_TILE + Arranges the windows as nonoverlapping tiles + + + MEN_DESK_HELP_CONTENTS + &Contents + + + PRP_DESK_HELP_CONTENTS + Shows the whole help contents + + + MEN_DESK_WINDOW_HTILE + Tile &Horizontally + + + MEN_DESK_WINDOW_VTILE + Tile &Vertically + + + ERR_DOC_PERMISSIONDENIED_SAVE + Can not save file %1. Permission denied + + + INF_DESK_DOCALREADYOPEN + 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 ) + + + TIT_FILE_SAVEAS + Save As + + + MEN_DESK_FILE_CLOSE + &Close + + + MSG_FILE_EXISTS + File "%1" already exists. +Do you want to overwrite it? + + + MEN_DESK_FILE_PRINT + &Print + + + MEN_DESK_HELP_SEARCH + &Search... + + + MEN_DESK_VIEW_STDTOOLBAR + &Standard + + + MEN_DESK_FILE_SAVEAS + Save &As... + + + PRP_DESK_VIEW_STDTOOLBAR + Toggles standard toolbar on/off + + + QUE_DOC_FILEEXISTS + The file %1 already exists. +Do you want to overwrite it ? + + + TOT_DESK_FILE_SAVE + Save document + + + TOT_DESK_FILE_EXIT + Exit from application + + + TOT_DESK_FILE_LOAD + Load document + + + TOT_DESK_FILE_OPEN + Open document + + + CLOSE_QUESTION + Document %1 modified. Do you want to save or discard the modification and close the document? + + + PRP_DESK_FILE_EXIT + Exits the application + + + PRP_DESK_FILE_OPEN + Opens an existing document + + + PRP_DESK_FILE_SAVE + Saves the active document + + + PRP_DESK_FILE_LOAD + Load a document + + + PRP_DESK_WINDOW_HTILE + Arranges the windows as nonoverlapping horizontal tiles + + + PRP_DESK_WINDOW_VTILE + Arranges the windows as nonoverlapping vertical tiles + + + MEN_DESK_WINDOW_TILE + &Tile + + + MEN_DESK_FILE_EXIT + E&xit + + + MEN_DESK_FILE_OPEN + &Open... + + + MEN_DESK_FILE_LOAD + Conn&ect... + + + MEN_DESK_FILE_SAVE + &Save + + + MEN_DESK_EDIT_PASTE + &Paste + + + MEN_STUDIES_CHOICE + Choose existent study. + + + + STD_Application + + INF_DOC_MODIFIED + Document has been modified. +Do you want to save changes? + + + INF_DOC_SAVING + Saving study + + + INF_DOC_SAVED + Study %1 saved + + + TOT_DOCK_WINDOWS + Show / hide dockable windows and toolbars + + + MEN_DOCK_WINDOWS + Windows and Toolbars + + + ABOUT_INFO + SUIT Std application + + + INF_DOC_SAVING_FAILS + Can't save file "%1". +Possible reason is permission denied or disc full. +Try to use another file name. + + + INF_DOCUMENT_MODIFIED + Document "%1" has been modified. +Do you want to save changes? + + + diff --git a/src/SUIT/Makefile.am b/src/SUIT/Makefile.am index a87d39fae..32ab09def 100755 --- a/src/SUIT/Makefile.am +++ b/src/SUIT/Makefile.am @@ -25,94 +25,92 @@ include $(top_srcdir)/adm_local/unix/make_common_starter.am 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 diff --git a/src/SUIT/SUIT.h b/src/SUIT/SUIT.h index 82940286a..151fba4d1 100755 --- a/src/SUIT/SUIT.h +++ b/src/SUIT/SUIT.h @@ -20,13 +20,13 @@ #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 @@ -39,7 +39,7 @@ #define true 1 #endif -#if defined WNT +#if defined WIN32 #pragma warning ( disable: 4251 ) #endif diff --git a/src/SUIT/SUIT.pro b/src/SUIT/SUIT.pro new file mode 100644 index 000000000..5fad70834 --- /dev/null +++ b/src/SUIT/SUIT.pro @@ -0,0 +1,84 @@ +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 diff --git a/src/SUIT/SUIT_Accel.cxx b/src/SUIT/SUIT_Accel.cxx index 7bc7b5167..28dd85e9e 100644 --- a/src/SUIT/SUIT_Accel.cxx +++ b/src/SUIT/SUIT_Accel.cxx @@ -19,22 +19,27 @@ // 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 -#include -#include +#include +#include +#include +/*! + \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. */ @@ -61,10 +66,12 @@ void SUIT_Accel::setActionKey( const int action, const int key, const QString& t /*! 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; } } @@ -73,7 +80,8 @@ void SUIT_Accel::unsetActionKey( const int key, const QString& type ) /*! 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 @@ -83,22 +91,25 @@ SUIT_ViewWindow* getParentViewWindow( const QObject* obj ) } /*! 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 ) { diff --git a/src/SUIT/SUIT_Accel.h b/src/SUIT/SUIT_Accel.h index fdc9cd384..ed7dd4671 100644 --- a/src/SUIT/SUIT_Accel.h +++ b/src/SUIT/SUIT_Accel.h @@ -18,19 +18,15 @@ // // 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 -#include -#include +#include +#include +#include -/*! - \class SUIT_Accel - Manager of keyboard accelerator bindings -*/ class SUIT_EXPORT SUIT_Accel: public QObject { Q_OBJECT @@ -63,15 +59,16 @@ protected: 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 IdActionMap; // key - to - action_id map - typedef QMap ViewerTypeIdActionMap; // viewer_type - to - IdActionMap - ViewerTypeIdActionMap myMap; + typedef QMap IdActionMap; //!< maps key to action id + typedef QMap + ViewerTypeIdActionMap; //!< maps viewer type to IdActionMap + ViewerTypeIdActionMap myMap; //!< viewer actions map - QMap myOptMap; // key - to - map, used for optimazation. all registered keys (accelerators) - // are stored in this map. + //! Maps key to flag map, used for optimization. + //! All registered keys (accelerators) are stored in this map. + QMap myOptMap; static SUIT_Accel* myself; }; diff --git a/src/SUIT/SUIT_ActionOperation.cxx b/src/SUIT/SUIT_ActionOperation.cxx index d56f01705..68d207687 100644 --- a/src/SUIT/SUIT_ActionOperation.cxx +++ b/src/SUIT/SUIT_ActionOperation.cxx @@ -49,20 +49,20 @@ QtxAction* SUIT_ActionOperation::action() const /*!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. diff --git a/src/SUIT/SUIT_ActionOperation.h b/src/SUIT/SUIT_ActionOperation.h index bed11e318..89d9b1f25 100644 --- a/src/SUIT/SUIT_ActionOperation.h +++ b/src/SUIT/SUIT_ActionOperation.h @@ -16,43 +16,46 @@ // // 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 + +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; diff --git a/src/SUIT/SUIT_Application.cxx b/src/SUIT/SUIT_Application.cxx index bbe68030d..a5e545230 100755 --- a/src/SUIT/SUIT_Application.cxx +++ b/src/SUIT/SUIT_Application.cxx @@ -18,13 +18,14 @@ // #include "SUIT_Application.h" +#include "SUIT_Study.h" #include "SUIT_Session.h" #include "SUIT_Desktop.h" #include "SUIT_ResourceMgr.h" -#include -#include -#include +#include +#include +#include #include #include @@ -38,7 +39,9 @@ SUIT_Application::SUIT_Application() myStudy( 0 ), myDesktop( 0 ), myStatusLabel( 0 ) -{ +{ + if ( SUIT_Session::session() ) + SUIT_Session::session()->insertApplication( this ); } /*! @@ -64,7 +67,7 @@ SUIT_Desktop* SUIT_Application::desktop() \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; } @@ -127,7 +130,7 @@ bool SUIT_Application::useFile( const QString& theFileName ) 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; } @@ -211,7 +214,7 @@ void SUIT_Application::onInfoClear() */ SUIT_Application* SUIT_Application::startApplication( int argc, char** argv ) const { - return startApplication( name(), argc, argv ); + return startApplication( objectName(), argc, argv ); } /*! @@ -462,7 +465,12 @@ int SUIT_Application::createMenu( const int id, const QString& menu, const int g */ 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 ); } /*! @@ -472,8 +480,7 @@ void SUIT_Application::setMenuShown( QAction* a, const bool on ) */ void SUIT_Application::setMenuShown( const int id, const bool on ) { - if ( desktop() && desktop()->menuMgr() ) - desktop()->menuMgr()->setShown( id, on ); + setMenuShown( action( id ), on ); } /*! @@ -483,7 +490,12 @@ void SUIT_Application::setMenuShown( const int id, const bool 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 ); } /*! @@ -493,8 +505,7 @@ void SUIT_Application::setToolShown( QAction* a, const bool on ) */ void SUIT_Application::setToolShown( const int id, const bool on ) { - if ( desktop() && desktop()->toolMgr() ) - desktop()->toolMgr()->setShown( id, on ); + setToolShown( action( id ), on ); } /*! @@ -538,10 +549,9 @@ QAction* SUIT_Application::action( const int id ) const int SUIT_Application::actionId( const QAction* a ) const { int id = -1; - for ( QMap::ConstIterator it = myActionMap.begin(); - it != myActionMap.end() && id == -1; - ++it ) { - if ( it.data() == a ) + for ( QMap::ConstIterator it = myActionMap.begin(); it != myActionMap.end() && id == -1; ++it ) + { + if ( it.value() == a ) id = it.key(); } return id; @@ -561,15 +571,15 @@ int SUIT_Application::actionId( const QAction* a ) const \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 ); diff --git a/src/SUIT/SUIT_Application.h b/src/SUIT/SUIT_Application.h index 0bf48847e..710d3b2d5 100755 --- a/src/SUIT/SUIT_Application.h +++ b/src/SUIT/SUIT_Application.h @@ -20,19 +20,20 @@ #define SUIT_APPLICATION_H #include "SUIT.h" -#include "SUIT_Study.h" -#include -#include +#include +#include +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 ) @@ -63,7 +64,7 @@ public: /*! 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. */ @@ -95,10 +96,6 @@ public: 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 ); @@ -156,7 +153,7 @@ protected: 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 ); diff --git a/src/SUIT/SUIT_Convertor.h b/src/SUIT/SUIT_Convertor.h deleted file mode 100755 index fd37969fb..000000000 --- a/src/SUIT/SUIT_Convertor.h +++ /dev/null @@ -1,43 +0,0 @@ -// 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_) diff --git a/src/SUIT/SUIT_DataObject.cxx b/src/SUIT/SUIT_DataObject.cxx index 1082579fc..186dbe195 100755 --- a/src/SUIT/SUIT_DataObject.cxx +++ b/src/SUIT/SUIT_DataObject.cxx @@ -16,9 +16,8 @@ // // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com // -#include "SUIT_DataObject.h" -#include +#include "SUIT_DataObject.h" #include "SUIT_DataObjectKey.h" @@ -28,12 +27,11 @@ 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 ); } @@ -56,8 +54,14 @@ SUIT_DataObject::~SUIT_DataObject() mySignal->setOwner( 0 ); } - for ( QPtrListIterator 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; } @@ -79,7 +83,7 @@ SUIT_DataObject* SUIT_DataObject::firstChild() const { SUIT_DataObject* child = 0; if ( !myChildren.isEmpty() ) - child = myChildren.getFirst(); + child = myChildren.first(); return child; } @@ -91,7 +95,7 @@ SUIT_DataObject* SUIT_DataObject::lastChild() const { SUIT_DataObject* child = 0; if ( !myChildren.isEmpty() ) - child = myChildren.getLast(); + child = myChildren.last(); return child; } @@ -113,9 +117,9 @@ int SUIT_DataObject::childPos( const SUIT_DataObject* obj ) const 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; } @@ -179,7 +183,7 @@ SUIT_DataObject* SUIT_DataObject::prevBrother() const bool SUIT_DataObject::autoDeleteChildren() const { - return myChildren.autoDelete(); + return myAutoDel; } /*! @@ -188,7 +192,7 @@ bool SUIT_DataObject::autoDeleteChildren() const void SUIT_DataObject::setAutoDeleteChildren( const bool on ) { - myChildren.setAutoDelete( on ); + myAutoDel = on; } /*! @@ -197,11 +201,11 @@ void SUIT_DataObject::setAutoDeleteChildren( const bool 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 ); } } @@ -231,11 +235,11 @@ void SUIT_DataObject::appendChild( SUIT_DataObject* theObj ) 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 ); } @@ -248,13 +252,8 @@ void SUIT_DataObject::removeChild( SUIT_DataObject* theObj ) if ( !theObj ) return; - bool ad = myChildren.autoDelete(); - myChildren.setAutoDelete( false ); - - if ( myChildren.remove( theObj ) ) + if ( myChildren.removeAll( theObj ) ) theObj->setParent( 0 ); - - myChildren.setAutoDelete( ad ); } /*! @@ -297,8 +296,8 @@ void SUIT_DataObject::reparentChildren( const SUIT_DataObject* obj ) 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 ); } /*! @@ -495,9 +494,9 @@ SUIT_DataObjectKey* SUIT_DataObject::key() const 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 ); } /*! diff --git a/src/SUIT/SUIT_DataObject.h b/src/SUIT/SUIT_DataObject.h index 01f0ffa59..1f479192c 100755 --- a/src/SUIT/SUIT_DataObject.h +++ b/src/SUIT/SUIT_DataObject.h @@ -16,21 +16,21 @@ // // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com // + #ifndef SUIT_DATAOBJECT_H #define SUIT_DATAOBJECT_H -#include -#include -#include -#include - #include "SUIT.h" +#include +#include +#include +#include + class SUIT_DataObject; class SUIT_DataObjectKey; -typedef QPtrList DataObjectList; -typedef QPtrListIterator DataObjectListIterator; +typedef QList DataObjectList; #ifdef WIN32 #pragma warning( disable:4251 ) @@ -108,10 +108,11 @@ public: 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; diff --git a/src/SUIT/SUIT_DataObjectIterator.cxx b/src/SUIT/SUIT_DataObjectIterator.cxx index c5f66be5c..c1a16892d 100644 --- a/src/SUIT/SUIT_DataObjectIterator.cxx +++ b/src/SUIT/SUIT_DataObjectIterator.cxx @@ -74,11 +74,11 @@ void SUIT_DataObjectIterator::operator++() } 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; @@ -146,9 +146,9 @@ SUIT_DataObject* SUIT_DataObjectIterator::globalSibling( SUIT_DataObject* obj, b 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 ) ) @@ -170,9 +170,9 @@ SUIT_DataObject* SUIT_DataObjectIterator::globalSibling( SUIT_DataObject* obj, b 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(); } /*! diff --git a/src/SUIT/SUIT_DataObjectKey.cxx b/src/SUIT/SUIT_DataObjectKey.cxx index 01a91404a..d209c9320 100755 --- a/src/SUIT/SUIT_DataObjectKey.cxx +++ b/src/SUIT/SUIT_DataObjectKey.cxx @@ -18,9 +18,9 @@ // #include "SUIT_DataObjectKey.h" -#include +#include -#ifndef WNT +#ifndef WIN32 #include #define _typeinfo std::type_info #else diff --git a/src/SUIT/SUIT_DataOwner.cxx b/src/SUIT/SUIT_DataOwner.cxx index a0aa525c4..dd4431d73 100755 --- a/src/SUIT/SUIT_DataOwner.cxx +++ b/src/SUIT/SUIT_DataOwner.cxx @@ -16,10 +16,9 @@ // // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com // - #include "SUIT_DataOwner.h" -#ifndef WNT +#ifndef WIN32 #include #define _typeinfo std::type_info #else @@ -45,9 +44,7 @@ bool operator==( const SUIT_DataOwnerPtr& p1, const SUIT_DataOwnerPtr& p2 ) 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 ) { @@ -60,7 +57,6 @@ bool operator<( const SUIT_DataOwnerPtr& p1, const SUIT_DataOwnerPtr& p2 ) return (p1->keyString() < p2->keyString()); } -// *** end /*! \class SUIT_DataOwnerPtrList @@ -72,8 +68,8 @@ bool operator<( const SUIT_DataOwnerPtr& p1, const SUIT_DataOwnerPtr& p2 ) Constructor (default) */ SUIT_DataOwnerPtrList::SUIT_DataOwnerPtrList() - : QValueList(), - mySkipEqual( true ) +: QList(), +mySkipEqual( true ) { } @@ -81,8 +77,8 @@ SUIT_DataOwnerPtrList::SUIT_DataOwnerPtrList() Constructor (default) */ SUIT_DataOwnerPtrList::SUIT_DataOwnerPtrList( const bool skipAllEqual ) - : QValueList(), - mySkipEqual( skipAllEqual ) +: QList(), +mySkipEqual( skipAllEqual ) { } @@ -90,8 +86,8 @@ SUIT_DataOwnerPtrList::SUIT_DataOwnerPtrList( const bool skipAllEqual ) Constructor (copy) */ SUIT_DataOwnerPtrList::SUIT_DataOwnerPtrList( const SUIT_DataOwnerPtrList& l ) - : QValueList( l ), - mySkipEqual( true ) +: QList( l ), +mySkipEqual( true ) { } @@ -99,8 +95,8 @@ SUIT_DataOwnerPtrList::SUIT_DataOwnerPtrList( const SUIT_DataOwnerPtrList& l ) Constructor (copy) */ SUIT_DataOwnerPtrList::SUIT_DataOwnerPtrList( const SUIT_DataOwnerPtrList& l, const bool skipAllEqual ) - : QValueList(), - mySkipEqual( skipAllEqual ) +: QList(), +mySkipEqual( skipAllEqual ) { if ( skipAllEqual == l.mySkipEqual ) operator =( l ); @@ -108,51 +104,23 @@ SUIT_DataOwnerPtrList::SUIT_DataOwnerPtrList( const SUIT_DataOwnerPtrList& l, co { 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& l ) - : QValueList( l ), - mySkipEqual( true ) -{ -} -#endif - -#ifndef QT_NO_STL -/*! - Constructor (from stl) -*/ -SUIT_DataOwnerPtrList::SUIT_DataOwnerPtrList( const std::list& l, const bool skipAllEqual ) - : QValueList(), - mySkipEqual( skipAllEqual ) -{ - std::list::const_iterator beginIt = l.begin(); - std::list::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::append( x ); + return; - if ( mySkipEqual ) - myMap.insert( x, it ); + QList::append( x ); - return it; + if ( mySkipEqual ) + myMap.insert( x, 0 ); } /*! @@ -160,9 +128,10 @@ SUIT_DataOwnerPtrList::iterator SUIT_DataOwnerPtrList::append( const SUIT_DataOw */ void SUIT_DataOwnerPtrList::clear() { - if( mySkipEqual ) + if ( mySkipEqual ) myMap.clear(); - QValueList::clear(); + + QList::clear(); } /*! @@ -170,7 +139,8 @@ void SUIT_DataOwnerPtrList::clear() */ uint SUIT_DataOwnerPtrList::remove(const SUIT_DataOwnerPtr& x ) { - if( mySkipEqual && myMap.contains(x) ) - myMap.remove(x); - return QValueList::remove( x ); + if ( mySkipEqual && myMap.contains(x) ) + myMap.remove( x ); + + return QList::removeAll( x ); } diff --git a/src/SUIT/SUIT_DataOwner.h b/src/SUIT/SUIT_DataOwner.h index 7e88c58ff..976e5b45f 100755 --- a/src/SUIT/SUIT_DataOwner.h +++ b/src/SUIT/SUIT_DataOwner.h @@ -21,8 +21,9 @@ #include "SUIT_SmartPtr.h" -#include -#include +#include +#include +#include #ifdef WIN32 #pragma warning( disable:4251 ) @@ -40,8 +41,6 @@ class SUIT_EXPORT SUIT_DataOwner : public RefCount 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 }; @@ -60,21 +59,17 @@ bool operator==( const SUIT_DataOwnerPtr&, const SUIT_DataOwnerPtr& ); /*! \class SUIT_DataOwnerPtrList * \brief Manage list of SUIT_DataOwnerPtr. */ -class SUIT_EXPORT SUIT_DataOwnerPtrList : public QValueList +class SUIT_EXPORT SUIT_DataOwnerPtrList : public QList { 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& l ); //!< copy constructor for STL list - SUIT_DataOwnerPtrList( const std::list& 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 @@ -84,8 +79,8 @@ private: void push_back ( const SUIT_DataOwnerPtr& x );//!< hide method private: - bool mySkipEqual; - QMap myMap; + QMap myMap; + bool mySkipEqual; }; #ifdef WIN32 diff --git a/src/SUIT/SUIT_Desktop.cxx b/src/SUIT/SUIT_Desktop.cxx index 8b2c63202..e16680033 100755 --- a/src/SUIT/SUIT_Desktop.cxx +++ b/src/SUIT/SUIT_Desktop.cxx @@ -18,13 +18,15 @@ // #include "SUIT_Desktop.h" -#include "SUIT_Tools.h" #include "SUIT_ViewWindow.h" #include #include #include +#include +#include + /*!\class SUIT_Desktop * Provide desktop management:\n * \li menu manager @@ -32,6 +34,17 @@ * \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. */ @@ -66,6 +79,8 @@ bool SUIT_Desktop::event( QEvent* e ) case QEvent::WindowDeactivate: emit deactivated(); break; + default: + break; } return QMainWindow::event( e ); @@ -85,18 +100,29 @@ void SUIT_Desktop::closeEvent( QCloseEvent* 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. */ @@ -113,11 +139,21 @@ QtxActionToolMgr* SUIT_Desktop::toolMgr() const 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 @@ -125,23 +161,12 @@ int SUIT_Desktop::logoCount() const } /*! - 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 ); } /*! diff --git a/src/SUIT/SUIT_Desktop.h b/src/SUIT/SUIT_Desktop.h index e3acceb62..c38c38128 100755 --- a/src/SUIT/SUIT_Desktop.h +++ b/src/SUIT/SUIT_Desktop.h @@ -21,16 +21,19 @@ #include "SUIT.h" -#include -#include +#include +#include + #include -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 @@ -40,23 +43,26 @@ class SUIT_EXPORT SUIT_Desktop : public QtxMainWindow { 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 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 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(); @@ -71,10 +77,11 @@ signals: 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; diff --git a/src/SUIT/SUIT_ExceptionHandler.cxx b/src/SUIT/SUIT_ExceptionHandler.cxx index 7a5083c91..861fdcf2c 100755 --- a/src/SUIT/SUIT_ExceptionHandler.cxx +++ b/src/SUIT/SUIT_ExceptionHandler.cxx @@ -20,7 +20,7 @@ #include "SUIT_MessageBox.h" -#include +#include /*!\class SUIT_ExceptionHandler * Show exception message on error handler. @@ -53,5 +53,5 @@ void SUIT_ExceptionHandler::showMessage( const QString& title, const QString& ms while ( QApplication::overrideCursor() ) QApplication::restoreOverrideCursor(); - SUIT_MessageBox::error1( qApp->mainWidget(), title, msg, "OK" ); + SUIT_MessageBox::critical( 0, title, msg ); } diff --git a/src/SUIT/SUIT_FileDlg.cxx b/src/SUIT/SUIT_FileDlg.cxx index 7fb1ee7c6..8dc7fd64c 100755 --- a/src/SUIT/SUIT_FileDlg.cxx +++ b/src/SUIT/SUIT_FileDlg.cxx @@ -66,19 +66,18 @@ #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 -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include #define MIN_COMBO_SIZE 100 @@ -90,39 +89,50 @@ const bool IGNORE_NON_MATCHING_EXTENSION = true; 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( *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( 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; @@ -130,27 +140,29 @@ myOpen( open )//, 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); @@ -162,11 +174,22 @@ SUIT_FileDlg::~SUIT_FileDlg() 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 buttonList; QValueList labelList; @@ -198,6 +221,7 @@ void SUIT_FileDlg::polish() (*lListIt)->setFixedWidth( maxLabWidth ); } } +*/ } /*! Sets validator for file names to open/save @@ -236,13 +260,19 @@ void SUIT_FileDlg::accept() * (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; } @@ -268,7 +298,7 @@ bool SUIT_FileDlg::acceptData() { if ( isOpenDlg() ) { - if ( mode() == ExistingFiles ) + if ( acceptMode() == AcceptOpen ) { QStringList fileNames = selectedFiles(); for ( int i = 0; i < (int)fileNames.count(); i++ ) @@ -296,11 +326,11 @@ bool SUIT_FileDlg::acceptData() 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' @@ -309,14 +339,8 @@ void SUIT_FileDlg::addExtension() 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 @@ -324,23 +348,20 @@ void SUIT_FileDlg::addExtension() // 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( "|" ); @@ -348,19 +369,19 @@ void SUIT_FileDlg::addExtension() 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; } @@ -372,20 +393,24 @@ void SUIT_FileDlg::addExtension() /*! 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; } } } @@ -395,15 +420,13 @@ bool SUIT_FileDlg::processPath( const QString& path ) 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 @@ -411,129 +434,115 @@ void SUIT_FileDlg::quickDir(const QString& dirPath) */ 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; } diff --git a/src/SUIT/SUIT_FileDlg.h b/src/SUIT/SUIT_FileDlg.h index 044188003..c2d7e4c44 100755 --- a/src/SUIT/SUIT_FileDlg.h +++ b/src/SUIT/SUIT_FileDlg.h @@ -21,7 +21,7 @@ #include "SUIT.h" -#include +#include class QLabel; class QComboBox; @@ -45,9 +45,6 @@ public: 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 ); @@ -57,10 +54,8 @@ public: 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 ); @@ -71,6 +66,9 @@ protected slots: void quickDir( const QString& ); void addQuickDir(); +protected: + virtual bool event( QEvent* ); + protected: bool myOpen; //!< open/save selector QString mySelectedFile; //!< selected filename diff --git a/src/SUIT/SUIT_FileValidator.cxx b/src/SUIT/SUIT_FileValidator.cxx index ab09fc665..0adb0b331 100755 --- a/src/SUIT/SUIT_FileValidator.cxx +++ b/src/SUIT/SUIT_FileValidator.cxx @@ -16,18 +16,12 @@ // // 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 -#include +#include +#include /*! constructor */ SUIT_FileValidator::SUIT_FileValidator(QWidget* parent) : @@ -38,18 +32,16 @@ myParent(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; @@ -58,38 +50,36 @@ bool SUIT_FileValidator::canOpen( const QString& file ) /*! 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(); @@ -97,4 +87,3 @@ bool SUIT_FileValidator::canSave( const QString& file ) } return true; } - diff --git a/src/SUIT/SUIT_FileValidator.h b/src/SUIT/SUIT_FileValidator.h index 197f6a2ab..9142c381d 100755 --- a/src/SUIT/SUIT_FileValidator.h +++ b/src/SUIT/SUIT_FileValidator.h @@ -18,15 +18,14 @@ // // SALOME SALOMEGUI : implementation of desktop and GUI kernel // -// File : SUIT_FileValidator.h -// Module : SALOME - #ifndef SUIT_FILEVALIDATOR_H #define SUIT_FILEVALIDATOR_H -#include #include "SUIT.h" +class QWidget; +class QString; + /*! \class SUIT_FileValidator Provides functionality to check file diff --git a/src/SUIT/SUIT_MessageBox.cxx b/src/SUIT/SUIT_MessageBox.cxx index e80ff74f0..ba2d261e0 100755 --- a/src/SUIT/SUIT_MessageBox.cxx +++ b/src/SUIT/SUIT_MessageBox.cxx @@ -17,334 +17,964 @@ // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com // +#include "SUIT_MessageBox.h" + +#include "SUIT_OverrideCursor.h" + +#include +#include +#include +#include + +#include + /*! - \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 -#include +/*! + \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 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; +} + diff --git a/src/SUIT/SUIT_MessageBox.h b/src/SUIT/SUIT_MessageBox.h index 24b350605..d9d24133c 100755 --- a/src/SUIT/SUIT_MessageBox.h +++ b/src/SUIT/SUIT_MessageBox.h @@ -22,70 +22,129 @@ #include "SUIT.h" -#include -#include +#include +#include +#include -#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 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 diff --git a/src/SUIT/SUIT_Operation.cxx b/src/SUIT/SUIT_Operation.cxx index 2df0b7d24..31ff40f8f 100755 --- a/src/SUIT/SUIT_Operation.cxx +++ b/src/SUIT/SUIT_Operation.cxx @@ -17,21 +17,9 @@ // 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" /*! @@ -46,9 +34,9 @@ SUIT_Operation::SUIT_Operation( SUIT_Application* app ) : QObject(), myApp( app ), +myFlags( Transaction ), myStudy( 0 ), -myState( Waiting ), -myFlags( Transaction ) +myState( Waiting ) { } diff --git a/src/SUIT/SUIT_Operation.h b/src/SUIT/SUIT_Operation.h index 3d15f058c..6a1785e2a 100755 --- a/src/SUIT/SUIT_Operation.h +++ b/src/SUIT/SUIT_Operation.h @@ -22,8 +22,8 @@ #include "SUIT.h" -#include -#include +#include +#include class SUIT_Study; class SUIT_Application; @@ -107,6 +107,8 @@ public: virtual QString operationName() const; + int execStatus() const; + signals: void started( SUIT_Operation* ); void aborted( SUIT_Operation* ); @@ -140,7 +142,6 @@ protected: virtual bool hasTransaction() const; virtual bool commitTransaction( const QString& = QString::null ); - int execStatus() const; void setExecStatus( const int ); void setState( const OperationState ); @@ -148,7 +149,7 @@ protected: void start( SUIT_Operation*, const bool = false ); private: - typedef QGuardedPtr StudyPtr; + typedef QPointer StudyPtr; private: SUIT_Application* myApp; //!< application for this operation diff --git a/src/SUIT/SUIT_OverrideCursor.cxx b/src/SUIT/SUIT_OverrideCursor.cxx index 0dab97a58..05d99e8cc 100755 --- a/src/SUIT/SUIT_OverrideCursor.cxx +++ b/src/SUIT/SUIT_OverrideCursor.cxx @@ -18,6 +18,8 @@ // #include "SUIT_OverrideCursor.h" +#include + /*!Constructor. Initialize wait cursor.*/ SUIT_OverrideCursor::SUIT_OverrideCursor() { @@ -61,7 +63,7 @@ void SUIT_OverrideCursor::resume() if ( isActive() ) return; - for ( QValueList::const_iterator it = myCursors.begin(); it != myCursors.end(); ++it ) + for ( QList::const_iterator it = myCursors.begin(); it != myCursors.end(); ++it ) QApplication::setOverrideCursor( *it ); myCursors.clear(); diff --git a/src/SUIT/SUIT_OverrideCursor.h b/src/SUIT/SUIT_OverrideCursor.h index ee89235d6..90e9dc7c4 100755 --- a/src/SUIT/SUIT_OverrideCursor.h +++ b/src/SUIT/SUIT_OverrideCursor.h @@ -19,11 +19,11 @@ #ifndef SUIT_OVERRIDECURSOR_H #define SUIT_OVERRIDECURSOR_H -#include -#include - #include "SUIT.h" +#include +#include + /*! \brief Class used for management cursors.*/ class SUIT_EXPORT SUIT_OverrideCursor { @@ -37,7 +37,7 @@ public: void resume(); private: - QValueList myCursors; + QList myCursors; }; #endif diff --git a/src/SUIT/SUIT_ParserSettings.cxx b/src/SUIT/SUIT_ParserSettings.cxx deleted file mode 100755 index fa3768ff1..000000000 --- a/src/SUIT/SUIT_ParserSettings.cxx +++ /dev/null @@ -1,341 +0,0 @@ -// 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 - -// QT Includes -#include -#include -#include - - -/*! 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)-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 '') \image html html_comments.gif -*/ -QString SUIT_ParserSettings::removeHtmlComments(QString s) -{ - QString result=""; - int i1=0, i2; - - while((i2=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+="
\n"; - col=1; - } - - // Auto break: - // - else if(col==autoBreak && autoBreak!=0) { - result+="
\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 diff --git a/src/SUIT/SUIT_ParserSettings.h b/src/SUIT/SUIT_ParserSettings.h deleted file mode 100755 index 16d74a2fb..000000000 --- a/src/SUIT/SUIT_ParserSettings.h +++ /dev/null @@ -1,56 +0,0 @@ -// 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 -#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 diff --git a/src/SUIT/SUIT_PopupClient.cxx b/src/SUIT/SUIT_PopupClient.cxx index fd2c40d9f..5104ca165 100644 --- a/src/SUIT/SUIT_PopupClient.cxx +++ b/src/SUIT/SUIT_PopupClient.cxx @@ -18,8 +18,6 @@ // #include "SUIT_PopupClient.h" -#include - /*! constructor. initialize mySignal.*/ SUIT_PopupClient::SUIT_PopupClient() : mySignal( 0 ) diff --git a/src/SUIT/SUIT_PopupClient.h b/src/SUIT/SUIT_PopupClient.h index f65bc9f12..42f7466b6 100644 --- a/src/SUIT/SUIT_PopupClient.h +++ b/src/SUIT/SUIT_PopupClient.h @@ -21,9 +21,9 @@ #include "SUIT.h" -#include +#include -class QPopupMenu; +class QMenu; class QContextMenuEvent; /*!\class SUIT_PopupClient @@ -42,7 +42,7 @@ public: 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 ); diff --git a/src/SUIT/SUIT_ResourceMgr.cxx b/src/SUIT/SUIT_ResourceMgr.cxx index b076babd3..086738e88 100755 --- a/src/SUIT/SUIT_ResourceMgr.cxx +++ b/src/SUIT/SUIT_ResourceMgr.cxx @@ -18,10 +18,14 @@ // #include "SUIT_ResourceMgr.h" -#include -#include -#include -#include +#include +#include +#include +#include + +#ifndef WIN32 +#include +#endif /*! Constructor @@ -66,9 +70,6 @@ QString SUIT_ResourceMgr::loadDoc( const QString& prefix, const QString& id ) co return path( docSection, prefix, id ); } -#ifndef WIN32 -#include -#endif /*! Returns the user file name for specified application */ @@ -76,13 +77,14 @@ QString SUIT_ResourceMgr::userFileName( const QString& appName, const bool for_l { 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(); } } @@ -110,7 +112,7 @@ QString SUIT_ResourceMgr::userFileName( const QString& appName, const bool for_l */ 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; @@ -127,7 +129,7 @@ QString SUIT_ResourceMgr::findAppropriateUserFile( const QString& fname ) const if( appr < 0 || abs( id-id0 ) < abs( appr-id0 ) ) { appr = id; - appr_file = d.absFilePath( *anIt ); + appr_file = d.absoluteFilePath( *anIt ); } } return appr_file; diff --git a/src/SUIT/SUIT_SelectionMgr.cxx b/src/SUIT/SUIT_SelectionMgr.cxx index 895486f21..21d02eadc 100755 --- a/src/SUIT/SUIT_SelectionMgr.cxx +++ b/src/SUIT/SUIT_SelectionMgr.cxx @@ -18,6 +18,9 @@ // #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. */ @@ -26,6 +29,7 @@ SUIT_SelectionMgr::SUIT_SelectionMgr( const bool Feedback, QObject* p ) : QObject( p ), myIterations( Feedback ? 1 : 0 ), +myAutoDelFilter( false ), myIsSelChangeEnabled( true ) { } @@ -33,7 +37,8 @@ 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.*/ @@ -46,25 +51,25 @@ void SUIT_SelectionMgr::installSelector( SUIT_Selector* sel ) /*!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& lst ) const +void SUIT_SelectionMgr::selectors( QList& 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& lst ) const +void SUIT_SelectionMgr::selectors( const QString& typ, QList& 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 ); } } @@ -72,10 +77,10 @@ void SUIT_SelectionMgr::selectors( const QString& typ, QPtrList& */ 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 ); } } @@ -85,12 +90,13 @@ void SUIT_SelectionMgr::selected( SUIT_DataOwnerPtrList& lst, const QString& typ { 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 ); } @@ -103,16 +109,16 @@ void SUIT_SelectionMgr::setSelected( const SUIT_DataOwnerPtrList& lst, const boo 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 ); } } @@ -140,11 +146,10 @@ void SUIT_SelectionMgr::selectionChanged( SUIT_Selector* sel ) 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; @@ -170,7 +175,7 @@ bool SUIT_SelectionMgr::hasSelectionMode( const int mode ) const /*! Gets selection modes to list \a vals. */ -void SUIT_SelectionMgr::selectionModes( QValueList& vals ) const +void SUIT_SelectionMgr::selectionModes( QList& vals ) const { vals = mySelModes; } @@ -179,14 +184,14 @@ void SUIT_SelectionMgr::selectionModes( QValueList& vals ) const */ void SUIT_SelectionMgr::setSelectionModes( const int mode ) { - QValueList lst; + QList lst; lst.append( mode ); setSelectionModes( lst ); } /*! Sets selection modes list from \a lst. */ -void SUIT_SelectionMgr::setSelectionModes( const QValueList& lst ) +void SUIT_SelectionMgr::setSelectionModes( const QList& lst ) { mySelModes = lst; } @@ -195,20 +200,20 @@ void SUIT_SelectionMgr::setSelectionModes( const QValueList& lst ) */ void SUIT_SelectionMgr::appendSelectionModes( const int mode ) { - QValueList lst; + QList lst; lst.append( mode ); appendSelectionModes( lst ); } /*! Append selection modes \a lst list. */ -void SUIT_SelectionMgr::appendSelectionModes( const QValueList& lst ) +void SUIT_SelectionMgr::appendSelectionModes( const QList& lst ) { QMap map; - for ( QValueList::const_iterator it = mySelModes.begin(); it != mySelModes.end(); ++it ) + for ( QList::const_iterator it = mySelModes.begin(); it != mySelModes.end(); ++it ) map.insert( *it, 0 ); - for ( QValueList::const_iterator itr = lst.begin(); itr != lst.end(); ++itr ) + for ( QList::const_iterator itr = lst.begin(); itr != lst.end(); ++itr ) { if ( !map.contains( *itr ) ) mySelModes.append( *itr ); @@ -219,20 +224,20 @@ void SUIT_SelectionMgr::appendSelectionModes( const QValueList& lst ) */ void SUIT_SelectionMgr::removeSelectionModes( const int mode ) { - QValueList lst; + QList lst; lst.append( mode ); removeSelectionModes( lst ); } /*! Remove selection modea \a lst from list. */ -void SUIT_SelectionMgr::removeSelectionModes( const QValueList& lst ) +void SUIT_SelectionMgr::removeSelectionModes( const QList& lst ) { QMap map; - for ( QValueList::const_iterator it = mySelModes.begin(); it != mySelModes.end(); ++it ) + for ( QList::const_iterator it = mySelModes.begin(); it != mySelModes.end(); ++it ) map.insert( *it, 0 ); - for ( QValueList::const_iterator itr = lst.begin(); itr != lst.end(); ++itr ) + for ( QList::const_iterator itr = lst.begin(); itr != lst.end(); ++itr ) map.remove( *itr ); mySelModes.clear(); @@ -248,8 +253,8 @@ bool SUIT_SelectionMgr::isOk( const SUIT_DataOwner* owner ) const 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; } @@ -292,13 +297,25 @@ void SUIT_SelectionMgr::installFilter( SUIT_SelectionFilter* f, const bool updat */ 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(); } @@ -306,14 +323,14 @@ void SUIT_SelectionMgr::clearFilters() */ 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. diff --git a/src/SUIT/SUIT_SelectionMgr.h b/src/SUIT/SUIT_SelectionMgr.h index 79576568f..7f3082737 100755 --- a/src/SUIT/SUIT_SelectionMgr.h +++ b/src/SUIT/SUIT_SelectionMgr.h @@ -19,13 +19,13 @@ #ifndef SUIT_SELECTIONMGR_H #define SUIT_SELECTIONMGR_H -#include "SUIT_Selector.h" #include "SUIT_DataOwner.h" -#include "SUIT_SelectionFilter.h" -#include -#include -#include +#include +#include + +class SUIT_Selector; +class SUIT_SelectionFilter; #ifdef WIN32 #pragma warning ( disable : 4251 ) @@ -43,24 +43,24 @@ public: virtual void selected( SUIT_DataOwnerPtrList&, const QString& = QString::null ) const; virtual void setSelected( const SUIT_DataOwnerPtrList&, const bool = false ); - void selectors( QPtrList& ) const; - void selectors( const QString&, QPtrList& ) const; + void selectors( QList& ) const; + void selectors( const QString&, QList& ) const; void setEnabled( const bool, const QString& = QString::null ); bool hasSelectionMode( const int ) const; - void selectionModes( QValueList& ) const; + void selectionModes( QList& ) const; void setSelectionModes( const int ); - virtual void setSelectionModes( const QValueList& ); + virtual void setSelectionModes( const QList& ); void appendSelectionModes( const int ); - virtual void appendSelectionModes( const QValueList& ); + virtual void appendSelectionModes( const QList& ); void removeSelectionModes( const int ); - virtual void removeSelectionModes( const QValueList& ); + virtual void removeSelectionModes( const QList& ); bool isOk( const SUIT_DataOwner* ) const; @@ -83,25 +83,21 @@ signals: protected: virtual void selectionChanged( SUIT_Selector* ); - typedef QPtrListIterator SelectorListIterator; - virtual void installSelector( SUIT_Selector* ); virtual void removeSelector( SUIT_Selector* ); private: void filterOwners( const SUIT_DataOwnerPtrList&, SUIT_DataOwnerPtrList& ) const; - typedef QPtrList SelectorList; - typedef QPtrList SelFilterList; - typedef QPtrListIterator SelFilterListIterator; - -protected: - SelectorList mySelectors; + typedef QList SelectorList; + typedef QList SelFilterList; private: SelFilterList myFilters; - QValueList mySelModes; + QList mySelModes; + SelectorList mySelectors; int myIterations; + bool myAutoDelFilter; bool myIsSelChangeEnabled; friend class SUIT_Selector; diff --git a/src/SUIT/SUIT_Selector.cxx b/src/SUIT/SUIT_Selector.cxx index ebda6a065..368d8c641 100755 --- a/src/SUIT/SUIT_Selector.cxx +++ b/src/SUIT/SUIT_Selector.cxx @@ -20,6 +20,49 @@ #include "SUIT_SelectionMgr.h" +#include + +/*!\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. */ @@ -27,15 +70,18 @@ /*! 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 ); } /*! @@ -45,6 +91,12 @@ SUIT_Selector::~SUIT_Selector() { if ( selectionMgr() ) selectionMgr()->removeSelector( this ); + + if ( myDestroyer && myDestroyer->selector() == this ) + { + myDestroyer->setSelector( 0 ); + delete myDestroyer; + } } /*! @@ -135,7 +187,7 @@ bool SUIT_Selector::hasSelectionMode( const int mode ) const /*! Puts to list \a lst selection modes from selection manager. */ -void SUIT_Selector::selectionModes( QValueList& lst ) const +void SUIT_Selector::selectionModes( QList& lst ) const { if ( selectionMgr() ) selectionMgr()->selectionModes( lst ); diff --git a/src/SUIT/SUIT_Selector.h b/src/SUIT/SUIT_Selector.h index 058506d24..46de6fa52 100755 --- a/src/SUIT/SUIT_Selector.h +++ b/src/SUIT/SUIT_Selector.h @@ -21,8 +21,9 @@ #include "SUIT.h" -#include -#include +#include + +class QObject; class SUIT_SelectionMgr; class SUIT_DataOwnerPtrList; @@ -34,9 +35,11 @@ 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(); @@ -55,7 +58,7 @@ public: void setSelected( const SUIT_DataOwnerPtrList& ); bool hasSelectionMode( const int ) const; - void selectionModes( QValueList& ) const; + void selectionModes( QList& ) const; protected: void selectionChanged(); @@ -63,10 +66,11 @@ protected: virtual void setSelection( const SUIT_DataOwnerPtrList& ) = 0; private: - bool myBlock; SUIT_SelectionMgr* mySelMgr; + bool myBlock; bool myEnabled; bool myAutoBlock; + Destroyer* myDestroyer; }; #endif diff --git a/src/SUIT/SUIT_Session.cxx b/src/SUIT/SUIT_Session.cxx index 7d2ac3839..891c20b8f 100755 --- a/src/SUIT/SUIT_Session.cxx +++ b/src/SUIT/SUIT_Session.cxx @@ -18,16 +18,13 @@ // #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 -#include -#include +#include #ifdef WIN32 #include @@ -35,9 +32,6 @@ #include #endif -static bool SUIT_Session_IsPythonExecuted = false; -static QMutex SUIT_Session_PythonMutex; - SUIT_Session* SUIT_Session::mySession = 0; /*! Constructor.*/ @@ -45,23 +39,25 @@ SUIT_Session* SUIT_Session::mySession = 0; 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; } @@ -78,7 +74,7 @@ SUIT_Session* SUIT_Session::session() 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; @@ -92,8 +88,8 @@ SUIT_Application* SUIT_Session::startApplication( const QString& name, int args, 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; } @@ -103,15 +99,15 @@ SUIT_Application* SUIT_Session::startApplication( const QString& name, int args, 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; } @@ -126,24 +122,19 @@ SUIT_Application* SUIT_Session::startApplication( const QString& name, int args, 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 @@ -163,15 +154,22 @@ SUIT_Application* SUIT_Session::startApplication( const QString& name, int args, /*! Gets the list of all applications */ -QPtrList SUIT_Session::applications() const +QList SUIT_Session::applications() const { - QPtrList 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* ) ) ); } /*! @@ -223,14 +221,16 @@ void SUIT_Session::onApplicationClosed( SUIT_Application* theApp ) { 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 ); } } @@ -239,16 +239,18 @@ void SUIT_Session::onApplicationClosed( SUIT_Application* theApp ) */ 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 ) { @@ -270,11 +272,12 @@ SUIT_ExceptionHandler* SUIT_Session::handler() const 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() ); @@ -294,10 +297,16 @@ SUIT_Session::AppLib SUIT_Session::loadLibrary( const QString& name, QString& li 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; } @@ -330,28 +339,3 @@ void SUIT_Session::onApplicationActivated( SUIT_Application* app ) { 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(); -} diff --git a/src/SUIT/SUIT_Session.h b/src/SUIT/SUIT_Session.h index 840de5927..f62d697c1 100755 --- a/src/SUIT/SUIT_Session.h +++ b/src/SUIT/SUIT_Session.h @@ -21,14 +21,15 @@ #include "SUIT.h" -#include "SUIT_Application.h" -#include "SUIT_ResourceMgr.h" +#include -#include -#include -#include -#include -#include +#include +#include +#include + +#ifdef WIN32 +#include +#endif #ifdef WIN32 #define LIB_HANDLE HINSTANCE @@ -39,7 +40,7 @@ class SUIT_ResourceMgr; class SUIT_ExceptionHandler; -#ifdef WNT +#ifdef WIN32 #pragma warning( disable:4251 ) #endif /*! @@ -47,7 +48,7 @@ class SUIT_ExceptionHandler; 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 @@ -65,7 +66,7 @@ public: SUIT_Application* startApplication( const QString&, int = 0, char** = 0 ); - QPtrList applications() const; + QList applications() const; SUIT_Application* activeApplication() const; SUIT_ResourceMgr* resourceMgr() const; @@ -74,9 +75,7 @@ public: 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* ); @@ -89,9 +88,8 @@ private slots: void onApplicationActivated( SUIT_Application* ); private: - typedef QPtrList AppList; - typedef QMap AppLibMap; - typedef QPtrListIterator AppListIterator; + typedef QList AppList; + typedef QMap AppLibMap; private: QString lastError() const; diff --git a/src/SUIT/SUIT_Study.cxx b/src/SUIT/SUIT_Study.cxx index a3baef3ce..8fc4f71ce 100755 --- a/src/SUIT/SUIT_Study.cxx +++ b/src/SUIT/SUIT_Study.cxx @@ -23,7 +23,6 @@ #include "SUIT_DataObject.h" #include "SUIT_MessageBox.h" #include "SUIT_Application.h" -#include /*!\class SUIT_Study * Support study management. Object management. Operation management. @@ -33,9 +32,9 @@ SUIT_Study::SUIT_Study( SUIT_Application* app ) : QObject(), myApp( app ), +myName( "" ), myIsSaved( false ), myIsModified( false ), -myName( "" ), myBlockChangeState( false ) { static int _id = 0; @@ -43,8 +42,6 @@ myBlockChangeState( false ) myId = ++_id; myRoot = new SUIT_DataObject(); - myOperations.setAutoDelete( false ); - myOperations.setAutoDelete( false ); } /*!Destructor.*/ @@ -91,7 +88,7 @@ QString SUIT_Study::studyName() const */ SUIT_Operation* SUIT_Study::activeOperation() const { - return myOperations.count() > 0 ? myOperations.getLast() : 0; + return myOperations.count() > 0 ? myOperations.last() : 0; } /*! @@ -113,7 +110,7 @@ bool SUIT_Study::isModified() const /*! *Close document. NOT IMPLEMENTED. */ -void SUIT_Study::closeDocument(bool permanently) +void SUIT_Study::closeDocument(bool /*permanently*/) { } @@ -121,8 +118,9 @@ 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; } /*! @@ -163,8 +161,8 @@ bool SUIT_Study::saveDocument() 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(); } @@ -239,9 +237,9 @@ SUIT_Operation* SUIT_Study::blockingOperation( SUIT_Operation* theOp ) const 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; } @@ -262,7 +260,7 @@ SUIT_Operation* SUIT_Study::blockingOperation( SUIT_Operation* theOp ) const */ 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 ); @@ -273,11 +271,11 @@ bool SUIT_Study::start( SUIT_Operation* theOp, const bool toCheck ) 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; @@ -313,7 +311,7 @@ bool SUIT_Study::start( SUIT_Operation* theOp, const bool toCheck ) */ 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 ); @@ -337,7 +335,7 @@ bool SUIT_Study::abort( SUIT_Operation* theOp ) */ 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 ); @@ -363,7 +361,7 @@ bool SUIT_Study::commit( SUIT_Operation* theOp ) */ 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 ); @@ -382,7 +380,7 @@ bool SUIT_Study::suspend( SUIT_Operation* theOp ) */ 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; @@ -396,7 +394,7 @@ bool SUIT_Study::resume( SUIT_Operation* theOp ) // 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 ); @@ -413,12 +411,13 @@ bool SUIT_Study::resume( SUIT_Operation* 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; @@ -438,7 +437,7 @@ void SUIT_Study::stop( SUIT_Operation* theOp ) * \brief Get all started operations * \return List of all started operations */ -const QPtrList& SUIT_Study::operations() const +const QList& SUIT_Study::operations() const { return myOperations; } @@ -523,6 +522,6 @@ int SUIT_Study::storeState() /*! * \brief Restores the study state */ -void SUIT_Study::restoreState(int savePoint) +void SUIT_Study::restoreState(int /*savePoint*/) { } diff --git a/src/SUIT/SUIT_Study.h b/src/SUIT/SUIT_Study.h index 156c6bc74..6ebf2bcad 100755 --- a/src/SUIT/SUIT_Study.h +++ b/src/SUIT/SUIT_Study.h @@ -21,14 +21,12 @@ #include "SUIT.h" -#include "SUIT_Operation.h" - -#include -#include +#include +#include class SUIT_DataObject; class SUIT_Application; -class QDialog; +class SUIT_Operation; #ifdef WIN32 #pragma warning( disable:4251 ) @@ -51,9 +49,9 @@ public: 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& ); @@ -65,7 +63,7 @@ public: // Operation management SUIT_Operation* activeOperation() const; virtual void abortAllOperations(); - const QPtrList& operations() const; + const QList& operations() const; virtual SUIT_Operation* blockingOperation( SUIT_Operation* ) const; @@ -98,7 +96,7 @@ protected: virtual bool commitTransaction( const QString& = QString::null ); private: - typedef QPtrList Operations; + typedef QList Operations; void stop( SUIT_Operation* ); private: diff --git a/src/SUIT/SUIT_ToolButton.cxx b/src/SUIT/SUIT_ToolButton.cxx index 35e009c6d..161d1952d 100755 --- a/src/SUIT/SUIT_ToolButton.cxx +++ b/src/SUIT/SUIT_ToolButton.cxx @@ -19,49 +19,30 @@ #include "SUIT_ToolButton.h" -#include -#include +#include /*!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; @@ -69,76 +50,56 @@ void SUIT_ToolButton::drawButton( QPainter * p ) 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 ); } - - diff --git a/src/SUIT/SUIT_ToolButton.h b/src/SUIT/SUIT_ToolButton.h index 10abe2629..0acd98e74 100755 --- a/src/SUIT/SUIT_ToolButton.h +++ b/src/SUIT/SUIT_ToolButton.h @@ -19,11 +19,14 @@ #ifndef SUIT_TOOLBUTTON_H #define SUIT_TOOLBUTTON_H -#include -#include - #include "SUIT.h" +#include + +class QAction; +class QPixmap; +class QToolBar; + /*! To draw down arrow on toolbutton.*/ class SUIT_EXPORT SUIT_ToolButton : public QToolButton { @@ -35,11 +38,6 @@ public: 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); @@ -49,7 +47,7 @@ public: void SetItem(int theIndex); public slots: - void OnSelectAction(int theItemID); + void OnSelectAction( QAction* theAction ); protected: void mouseReleaseEvent (QMouseEvent * theEvent); @@ -57,11 +55,9 @@ protected: private: void initialize(); - QPopupMenu* myPopup; - QSignal* mySignal; - bool myChangeItemAfterClick; + QMenu* myPopup; + bool myChangeItemAfterClick; }; #endif - diff --git a/src/SUIT/SUIT_Tools.cxx b/src/SUIT/SUIT_Tools.cxx index 953de65d4..31d997b4e 100755 --- a/src/SUIT/SUIT_Tools.cxx +++ b/src/SUIT/SUIT_Tools.cxx @@ -18,7 +18,7 @@ // #include "SUIT_Tools.h" -#include +#include #include #include @@ -37,7 +37,7 @@ void SUIT_Tools::trace( const char* lpszLog, const char* lpszFormat, ... ) 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; @@ -55,7 +55,7 @@ void SUIT_Tools::trace( const char* lpszLog, const char* lpszFormat, ... ) */ 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 ) ); } /*! @@ -64,7 +64,7 @@ QRect SUIT_Tools::makeRect( const int x1, const int y1, const int x2, const int 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; } diff --git a/src/SUIT/SUIT_Tools.h b/src/SUIT/SUIT_Tools.h index 62bc8d163..811571ddf 100755 --- a/src/SUIT/SUIT_Tools.h +++ b/src/SUIT/SUIT_Tools.h @@ -23,9 +23,9 @@ #include -#include -#include -#include +#include +#include +#include /*! \class SUIT_Tools diff --git a/src/SUIT/SUIT_TreeSync.h b/src/SUIT/SUIT_TreeSync.h index 61d8fde06..929255b36 100644 --- a/src/SUIT/SUIT_TreeSync.h +++ b/src/SUIT/SUIT_TreeSync.h @@ -20,8 +20,7 @@ #ifndef SUIT_TREE_SYNC_HEADER #define SUIT_TREE_SYNC_HEADER -#include -#include +#include /*! \struct DiffItem @@ -54,7 +53,7 @@ TrgItem synchronize( const SrcItem&, const TrgItem&, const TreeData& ); */ template void diffSiblings( const SrcItem&, const TrgItem&, - QValueList < DiffItem < SrcItem,TrgItem > >&, + QList < DiffItem < SrcItem,TrgItem > >&, const TreeData& ); /*! @@ -67,10 +66,10 @@ TrgItem createSubTree( const SrcItem&, const TrgItem&, const TrgItem&, const boo \brief find equal element in list */ template -const typename QValueList::const_iterator findEqual( const QValueList& l, - const typename QValueList::const_iterator& first, - const SrcItem& it, - const TreeData& td ); +const typename QList::const_iterator findEqual( const QList& l, + const typename QList::const_iterator& first, + const SrcItem& it, + const TreeData& td ); @@ -94,8 +93,8 @@ const typename QValueList::const_iterator findEqual( const QValueList void updateItem( const TrgItem& ) const - updates TrgItem without recreation
  • void deleteItemWithChildren( const TrgItem& ) const - deletes TrgItem with all children -
  • void children( const SrcItem&, QValueList& ) const - fills list with children -
  • void children( const TrgItem&, QValueList& ) const - fills list with children +
  • void children( const SrcItem&, QList& ) const - fills list with children +
  • void children( const TrgItem&, QList& ) const - fills list with children
  • SrcItem parent( const SrcItem& ) const - return parent SrcItem
  • TrgItem parent( const TrgItem& ) const - return parent SrcItem @@ -109,10 +108,10 @@ TrgItem synchronize( const SrcItem& r1, const TrgItem& r2, const TreeData& td ) 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++ ) @@ -162,12 +161,12 @@ TrgItem synchronize( const SrcItem& r1, const TrgItem& r2, const TreeData& td ) \param td - tree data object (provides auxiliary methods) */ template -const typename QValueList::const_iterator findEqual( const QValueList& l, - const typename QValueList::const_iterator& first, - const SrcItem& it, - const TreeData& td ) +const typename QList::const_iterator findEqual( const QList& l, + const typename QList::const_iterator& first, + const SrcItem& it, + const TreeData& td ) { - typename QValueList::const_iterator cur = first, last = l.end(); + typename QList::const_iterator cur = first, last = l.end(); for( ; cur!=last; cur++ ) if( td.isEqual( it, *cur ) ) return cur; @@ -183,28 +182,28 @@ const typename QValueList::const_iterator findEqual( const QValueList 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 src_ch; - QValueList trg_ch; + QList src_ch; + QList trg_ch; td.children( src, src_ch ); td.children( trg, trg_ch ); - typename QValueList::const_iterator src_it = src_ch.begin(), src_last = src_ch.end(); - typename QValueList::const_iterator cur = trg_ch.begin(), trg_last = trg_ch.end(); + typename QList::const_iterator src_it = src_ch.begin(), src_last = src_ch.end(); + typename QList::const_iterator cur = trg_ch.begin(), trg_last = trg_ch.end(); for( ; src_it!=src_last; src_it++ ) { - typename QValueList::const_iterator f = + typename QList::const_iterator f = findEqual( trg_ch, cur, *src_it, td ); if( f!=trg_last ) //is found { //mark all items before found as "to be deleted" - for( typename QValueList::const_iterator it = cur; it!=f; it++ ) + for( typename QList::const_iterator it = cur; it!=f; it++ ) { DiffItem ndiff; ndiff.mySrc = td.nullSrc(); @@ -256,9 +255,9 @@ TrgItem createSubTree( const SrcItem& src, const TrgItem& parent, if( nitem==td.nullTrg() ) return nitem; - QValueList ch; + QList ch; td.children( src, ch ); - typename QValueList::const_iterator anIt = ch.begin(), aLast = ch.end(); + typename QList::const_iterator anIt = ch.begin(), aLast = ch.end(); for( ; anIt!=aLast; anIt++ ) createSubTree( *anIt, nitem, td.nullTrg(), false, td ); diff --git a/src/SUIT/SUIT_ViewManager.cxx b/src/SUIT/SUIT_ViewManager.cxx index 9d2e7e186..61db632b6 100755 --- a/src/SUIT/SUIT_ViewManager.cxx +++ b/src/SUIT/SUIT_ViewManager.cxx @@ -1,17 +1,17 @@ // 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 @@ -20,13 +20,14 @@ #include "SUIT_Desktop.h" #include "SUIT_ViewModel.h" +#include #include "SUIT_Study.h" -#include -#include -#include +#include +#include +#include -#ifdef WNT +#ifdef WIN32 #include #endif @@ -51,7 +52,7 @@ myStudy( NULL ) myId = useNewId( getType() ); - connect( theDesktop, SIGNAL( windowActivated( SUIT_ViewWindow* ) ), + connect( theDesktop, SIGNAL( windowActivated( SUIT_ViewWindow* ) ), this, SLOT( onWindowActivated( SUIT_ViewWindow* ) ) ); myStudy = theStudy; @@ -85,12 +86,19 @@ void SUIT_ViewManager::setTitle( const QString& theTitle ) 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); @@ -104,8 +112,8 @@ void SUIT_ViewManager::setViewModel(SUIT_ViewModel* theViewModel) /*!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 ) @@ -113,7 +121,7 @@ QString SUIT_ViewManager::prepareTitle( const QString& title, const int mId, con 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() ); @@ -138,14 +146,15 @@ SUIT_ViewWindow* SUIT_ViewManager::createViewWindow() 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 is the first one in this view manager // -> call onWindowActivated() directly, because somebody may always want @@ -162,21 +171,31 @@ void SUIT_ViewManager::createView() createViewWindow(); } +QVector SUIT_ViewManager::getViews() const +{ + QVector 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*))); @@ -204,9 +223,11 @@ bool SUIT_ViewManager::insertView(SUIT_ViewWindow* theView) 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; } } @@ -228,11 +249,11 @@ void SUIT_ViewManager::closeView( SUIT_ViewWindow* theView ) if ( !theView ) return; - QGuardedPtr view( theView ); + QPointer view( theView ); view->hide(); - if ( !view->testWFlags( WDestructiveClose ) ) + if ( !view->testAttribute( Qt::WA_DeleteOnClose ) ) return; emit deleteView( view ); @@ -245,15 +266,14 @@ void SUIT_ViewManager::closeView( SUIT_ViewWindow* theView ) /*!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 ); } /*! @@ -261,7 +281,7 @@ void SUIT_ViewManager::removeView(SUIT_ViewWindow* theView) */ 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 ); } @@ -271,7 +291,7 @@ void SUIT_ViewManager::setDestructiveClose( const bool 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; } @@ -281,7 +301,7 @@ bool SUIT_ViewManager::isVisible() const */ 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 ); } @@ -311,7 +331,7 @@ void SUIT_ViewManager::onWindowActivated(SUIT_ViewWindow* view) */ 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(); } @@ -320,8 +340,8 @@ void SUIT_ViewManager::closeAllViews() *\retval QString - type of view model. */ QString SUIT_ViewManager::getType() const -{ - return (!myViewModel)? "": myViewModel->getType(); +{ + return (!myViewModel)? "": myViewModel->getType(); } /*! @@ -347,7 +367,7 @@ void SUIT_ViewManager::onContextMenuRequested( QContextMenuEvent* e ) } /*!Context menu popup for \a popup.*/ -void SUIT_ViewManager::contextMenuPopup( QPopupMenu* popup ) +void SUIT_ViewManager::contextMenuPopup( QMenu* popup ) { SUIT_ViewModel* vm = getViewModel(); if ( vm ) diff --git a/src/SUIT/SUIT_ViewManager.h b/src/SUIT/SUIT_ViewManager.h index 9fdd2ecd8..cc6735d07 100755 --- a/src/SUIT/SUIT_ViewManager.h +++ b/src/SUIT/SUIT_ViewManager.h @@ -1,17 +1,17 @@ // 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 @@ -20,17 +20,23 @@ #define SUIT_VIEWMANAGER_H #include "SUIT.h" -#include "SUIT_ViewWindow.h" + #include "SUIT_PopupClient.h" -#include -#include +#include +#include +#include +#include + +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 ) @@ -46,22 +52,25 @@ public: 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 getViews() { return myViews; } + QVector 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; @@ -71,7 +80,7 @@ public: public slots: void createView(); void closeAllViews(); - + signals: void lastViewClosed(SUIT_ViewManager*); void deleteView(SUIT_ViewWindow*); @@ -84,7 +93,7 @@ signals: void keyPress(SUIT_ViewWindow*, QKeyEvent*); void keyRelease(SUIT_ViewWindow*, QKeyEvent*); void activated(SUIT_ViewManager*); - + protected slots: void onWindowActivated(SUIT_ViewWindow*); void onClosingView( SUIT_ViewWindow* ); @@ -93,32 +102,36 @@ protected slots: 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 ViewWindow; + protected: SUIT_Desktop* myDesktop; SUIT_ViewModel* myViewModel; - QPtrVector myViews; + QVector myViews; SUIT_ViewWindow* myActiveView; int myId; + QPixmap myIcon; QString myTitle; SUIT_Study* myStudy; diff --git a/src/SUIT/SUIT_ViewModel.cxx b/src/SUIT/SUIT_ViewModel.cxx index 86c0f0099..3ecd9eeae 100755 --- a/src/SUIT/SUIT_ViewModel.cxx +++ b/src/SUIT/SUIT_ViewModel.cxx @@ -21,6 +21,8 @@ #include "SUIT_ViewModel.h" +#include + SUIT_ViewModel::StatesMap SUIT_ViewModel::myStateMap; SUIT_ViewModel::ButtonsMap SUIT_ViewModel::myButtonMap; @@ -29,19 +31,20 @@ static bool isInitialized = false; /*!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; @@ -60,13 +63,28 @@ SUIT_ViewWindow* SUIT_ViewModel::createView(SUIT_Desktop* theDesktop) 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; @@ -77,8 +95,7 @@ void SUIT_ViewModel::setHotButton(HotOperation theOper, Qt::ButtonState theState *\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]; diff --git a/src/SUIT/SUIT_ViewModel.h b/src/SUIT/SUIT_ViewModel.h index 4be9fd777..8126a7913 100755 --- a/src/SUIT/SUIT_ViewModel.h +++ b/src/SUIT/SUIT_ViewModel.h @@ -20,12 +20,15 @@ #define SUIT_VIEWMODEL_H #include "SUIT.h" -#include "SUIT_Desktop.h" -#include "SUIT_ViewWindow.h" -#include "SUIT_ViewManager.h" -#include -#include +#include +#include + +class QMenu; + +class SUIT_Desktop; +class SUIT_ViewWindow; +class SUIT_ViewManager; #ifdef WIN32 #pragma warning( disable:4251 ) @@ -42,28 +45,28 @@ class SUIT_EXPORT SUIT_ViewModel : public QObject public: enum HotOperation { PAN, ZOOM, ROTATE, FIT_AREA }; - typedef QMap StatesMap; - typedef QMap ButtonsMap; + typedef QMap StatesMap; + typedef QMap 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; diff --git a/src/SUIT/SUIT_ViewWindow.cxx b/src/SUIT/SUIT_ViewWindow.cxx index faf064fb5..7ab233d84 100755 --- a/src/SUIT/SUIT_ViewWindow.cxx +++ b/src/SUIT/SUIT_ViewWindow.cxx @@ -1,17 +1,17 @@ // 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 @@ -20,16 +20,18 @@ // #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 -#include -#include -#include + +#include +#include +#include +#include /*!\class SUIT_ViewWindow * Class provide view window. @@ -39,13 +41,14 @@ 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.*/ @@ -87,7 +90,7 @@ QImage SUIT_ViewWindow::dumpView() 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() ) @@ -95,8 +98,8 @@ bool SUIT_ViewWindow::dumpViewToFormat( const QImage& img, const QString& fileNa 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; } @@ -116,17 +119,14 @@ bool SUIT_ViewWindow::dumpViewToFormat( const QString& fileName, const QString& */ 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 ); } @@ -142,8 +142,8 @@ void SUIT_ViewWindow::contextMenuEvent ( QContextMenuEvent * e ) */ 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 ) ); } /*! @@ -168,20 +168,18 @@ bool SUIT_ViewWindow::event( QEvent* e ) // 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 ); } @@ -211,7 +209,7 @@ QString SUIT_ViewWindow::getVisualParameters() /*! 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*/ ) { } diff --git a/src/SUIT/SUIT_ViewWindow.h b/src/SUIT/SUIT_ViewWindow.h index 6a6a6f869..e5aaa5bc1 100755 --- a/src/SUIT/SUIT_ViewWindow.h +++ b/src/SUIT/SUIT_ViewWindow.h @@ -19,20 +19,16 @@ // 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 +#include +#include class SUIT_Desktop; class SUIT_ViewManager; -class QImage; class SUIT_EXPORT SUIT_ViewWindow: public QMainWindow { diff --git a/src/SUIT/resources/SUIT_images.ts b/src/SUIT/resources/SUIT_images.ts new file mode 100644 index 000000000..c7c438f3d --- /dev/null +++ b/src/SUIT/resources/SUIT_images.ts @@ -0,0 +1,17 @@ + + + @default + + ICON_DESK_WINDOW_TILE + htile.png + + + ICON_DESK_WINDOW_CASCADE + cascade.png + + + ICON_DESK_WINDOW_VTILE + vtile.png + + + diff --git a/src/SUIT/resources/SUIT_msg_en.ts b/src/SUIT/resources/SUIT_msg_en.ts new file mode 100644 index 000000000..6b44e7f24 --- /dev/null +++ b/src/SUIT/resources/SUIT_msg_en.ts @@ -0,0 +1,114 @@ + + + @default + + MEN_DESK_WINDOW + &Window + + + ERR_CANT_DUMP_VIEW + Can't dump view contents to the file. + + + TLT_IMAGE_FILES + Images Files (*.bmp *.png *.jpg *.jpeg) + + + MEN_DESK_WINDOW_CASCADE + &Cascade + + + PRP_DESK_WINDOW_CASCADE + Arranges the windows as overlapping tiles + + + ERR_DIR_NOT_EXIST + The directory "%1" does not exist! + + + LAB_QUICK_PATH + Quick path: + + + CONTINUE + Continue + + + CANCEL + Cancel + + + ERR_FILE_NOT_EXIST + The file "%1" does not exist! + + + PRP_DESK_WINDOW_ACTIVATE + Activates this window + + + ERR_PERMISSION_DENIED + Can't save file "%1". +Permission denied. + + + ERR_ERROR + Error + + + QUE_FILE_EXISTS + The file "%1" already exists. +Do you want to overwrite it? + + + WRN_WARNING + Warning + + + TLT_DUMP_VIEW + Dump View to File + + + INF_DESK_DOC_OPEN + Open File + + + INF_DESK_DOC_SAVE + Save File + + + PRP_DESK_WINDOW_TILE + Arranges the windows as nonoverlapping tiles + + + BUT_ADD_PATH + Add path + + + MEN_DESK_WINDOW_VTILE + Tile &Vertically + + + INF_DIRECTORIES_FILTER + Directories + + + PRP_DESK_WINDOW_VTILE + Arranges the windows as nonoverlapping vertical tiles + + + MEN_DESK_WINDOW_TILE + &Tile + + + + SUIT_Study + + OPERATION_LAUNCH + Operation launch + + + PREVIOUS_NOT_FINISHED + Previous operation is not finished and will be aborted + + + diff --git a/src/SUITApp/Makefile.am b/src/SUITApp/Makefile.am index 6e76029de..e79026278 100644 --- a/src/SUITApp/Makefile.am +++ b/src/SUITApp/Makefile.am @@ -25,13 +25,16 @@ include $(top_srcdir)/adm_local/unix/make_common_starter.am 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 @@ -40,7 +43,7 @@ libSUITApp_la_CPPFLAGS=$(QT_INCLUDES) $(PYTHON_INCLUDES) \ -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) @@ -54,4 +57,4 @@ dist_SUITApp_SOURCES=SUITApp.cxx 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 diff --git a/src/SUITApp/SUITApp.cxx b/src/SUITApp/SUITApp.cxx index f343c435e..5647e6bad 100644 --- a/src/SUITApp/SUITApp.cxx +++ b/src/SUITApp/SUITApp.cxx @@ -16,7 +16,7 @@ // // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com // -#if defined WNT +#if defined WIN32 #undef SUIT_ENABLE_PYTHON //#else @@ -26,20 +26,21 @@ #include "SUITApp_Application.h" #include -#include +//#include #include -#include +// TODO +//#include #ifdef SUIT_ENABLE_PYTHON #include #endif -#include -#include -#include -#include -#include +#include +#include +//#include +#include +#include #include @@ -52,11 +53,10 @@ QString salomeVersion() 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() ) @@ -66,9 +66,9 @@ QString salomeVersion() 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; } @@ -108,7 +108,7 @@ public: SUIT_ResourceMgr* resMgr = 0; if ( myIniFormat ) { - resMgr = new SUIT_ResourceMgr( appName ); + resMgr = new SUIT_ResourceMgr( appName, QString( "%1Config" ) ); resMgr->setCurrentFormat( "ini" ); } else @@ -160,69 +160,80 @@ int main( int args, char* argv[] ) 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; } diff --git a/src/SUITApp/SUITApp.pro b/src/SUITApp/SUITApp.pro new file mode 100644 index 000000000..157b8f4a0 --- /dev/null +++ b/src/SUITApp/SUITApp.pro @@ -0,0 +1,18 @@ +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 diff --git a/src/SUITApp/SUITApp_Application.cxx b/src/SUITApp/SUITApp_Application.cxx index bf32979de..7027184df 100644 --- a/src/SUITApp/SUITApp_Application.cxx +++ b/src/SUITApp/SUITApp_Application.cxx @@ -18,12 +18,11 @@ // #include "SUITApp_Application.h" -#include "SUIT_Session.h" -#include "SUIT_MessageBox.h" -#include "SUIT_ExceptionHandler.h" +#include +#include -#include -#include +#include +#include #ifdef WIN32 #include @@ -39,7 +38,7 @@ SUITApp_Application::SUITApp_Application( int& argc, char** argv, SUIT_Exception : 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 ); @@ -69,20 +68,6 @@ myExceptHandler( hand ) */ 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 ); } diff --git a/src/SUITApp/SUITApp_Application.h b/src/SUITApp/SUITApp_Application.h index 479f07a20..808e464cc 100644 --- a/src/SUITApp/SUITApp_Application.h +++ b/src/SUITApp/SUITApp_Application.h @@ -19,7 +19,7 @@ #ifndef SUITAPP_APPLICATION_H #define SUITAPP_APPLICATION_H -#include +#include class SUIT_ExceptionHandler; diff --git a/src/SUITApp/resources/SUITApp_msg_en.ts b/src/SUITApp/resources/SUITApp_msg_en.ts new file mode 100644 index 000000000..20b003ece --- /dev/null +++ b/src/SUITApp/resources/SUITApp_msg_en.ts @@ -0,0 +1,17 @@ + + + @default + + APP_OK + Ok + + + APP_ERROR + Error + + + APP_UNK_EXCEPTION + Unknown exception + + + diff --git a/src/SUPERVGraph/SUPERVGraph.cxx b/src/SUPERVGraph/SUPERVGraph.cxx index d570c614a..041a680cd 100755 --- a/src/SUPERVGraph/SUPERVGraph.cxx +++ b/src/SUPERVGraph/SUPERVGraph.cxx @@ -29,6 +29,9 @@ #include "SUPERVGraph.h" #include "SUPERVGraph_ViewFrame.h" +#include "SUIT_Desktop.h" +#include "SUIT_ViewWindow.h" + using namespace std; /*! @@ -36,7 +39,7 @@ using namespace std; */ SUIT_ViewWindow* SUPERVGraph::createView(SUIT_Desktop* parent) { - return new SUPERVGraph_ViewFrame( parent/*, "vtkView"*/ ); + return new SUPERVGraph_ViewFrame( parent ); } extern "C" diff --git a/src/SUPERVGraph/SUPERVGraph.h b/src/SUPERVGraph/SUPERVGraph.h index eef17b998..1aebcc100 100755 --- a/src/SUPERVGraph/SUPERVGraph.h +++ b/src/SUPERVGraph/SUPERVGraph.h @@ -29,10 +29,7 @@ #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 @@ -42,17 +39,22 @@ #define SUPERVGRAPH_EXPORT #endif -#if defined WNT +#if defined WIN32 #pragma warning ( disable: 4251 ) #endif +#include + +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); }; diff --git a/src/SUPERVGraph/SUPERVGraph.pro b/src/SUPERVGraph/SUPERVGraph.pro new file mode 100644 index 000000000..a83a0451a --- /dev/null +++ b/src/SUPERVGraph/SUPERVGraph.pro @@ -0,0 +1,49 @@ +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 diff --git a/src/SUPERVGraph/SUPERVGraph_ViewFrame.cxx b/src/SUPERVGraph/SUPERVGraph_ViewFrame.cxx index e20b59768..fe2c9b137 100755 --- a/src/SUPERVGraph/SUPERVGraph_ViewFrame.cxx +++ b/src/SUPERVGraph/SUPERVGraph_ViewFrame.cxx @@ -32,8 +32,8 @@ #include //QT Include -#include -#include +#include +#include using namespace std; @@ -57,7 +57,7 @@ SUPERVGraph_View::SUPERVGraph_View( SUPERVGraph_View* theParent ): QWidget( theP /*! Builds popup for SUPERVGraph viewer */ -void SUPERVGraph_View::contextMenuPopup( QPopupMenu* ) +void SUPERVGraph_View::contextMenuPopup( QMenu* ) { // to be implemented } @@ -94,8 +94,8 @@ SUPERVGraph_ViewFrame::SUPERVGraph_ViewFrame( SUIT_Desktop* theDesktop ) 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(); } @@ -107,18 +107,18 @@ void SUPERVGraph_ViewFrame::createActions() { 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; @@ -278,8 +278,11 @@ void SUPERVGraph_ViewFrame::onViewFitAll() */ void SUPERVGraph_ViewFrame::setBackgroundColor( const QColor& color ) { - if (myView) - myView->setPaletteBackgroundColor(color); + if (myView) { + QPalette palette; + palette.setColor(myView->backgroundRole(), color); + myView->setPalette(palette); + } } /*! @@ -288,8 +291,8 @@ void SUPERVGraph_ViewFrame::setBackgroundColor( const QColor& color ) QColor SUPERVGraph_ViewFrame::backgroundColor() const { if (myView) - return myView->paletteBackgroundColor(); - return QMainWindow::backgroundColor(); + return myView->palette().color( myView->backgroundRole() ); + return palette().color( backgroundRole() ); } /*! diff --git a/src/SUPERVGraph/SUPERVGraph_ViewFrame.h b/src/SUPERVGraph/SUPERVGraph_ViewFrame.h index 2a5e7f03b..be33df74d 100755 --- a/src/SUPERVGraph/SUPERVGraph_ViewFrame.h +++ b/src/SUPERVGraph/SUPERVGraph_ViewFrame.h @@ -35,7 +35,7 @@ #include "SUIT_PopupClient.h" #include "SUIT_ViewWindow.h" -#include +#include #ifdef WIN32 #pragma warning ( disable:4251 ) @@ -54,7 +54,7 @@ class SUPERVGRAPH_EXPORT SUPERVGraph_View: public QWidget, public SUIT_PopupClie /* redefine functions from SUIT_PopupClient */ virtual QString popupClientType() const { return Type(); } - virtual void contextMenuPopup( QPopupMenu* ); + virtual void contextMenuPopup( QMenu* ); virtual void resizeView( QResizeEvent* theEvent ) {}; @@ -125,7 +125,7 @@ class SUPERVGRAPH_EXPORT SUPERVGraph_ViewFrame : public SUIT_ViewWindow { //! Actions ID enum { PanId, ResetId }; - typedef QMap ActionsMap; + typedef QMap ActionsMap; ActionsMap myActionsMap; QToolBar* myToolBar; diff --git a/src/SUPERVGraph/SUPERVGraph_ViewManager.cxx b/src/SUPERVGraph/SUPERVGraph_ViewManager.cxx index 0f890c4b5..e2ae70d27 100644 --- a/src/SUPERVGraph/SUPERVGraph_ViewManager.cxx +++ b/src/SUPERVGraph/SUPERVGraph_ViewManager.cxx @@ -18,6 +18,8 @@ // #include "SUPERVGraph_ViewManager.h" +#include "SUIT_ViewWindow.h" + int SUPERVGraph_ViewManager::myMaxId = 0; /*! @@ -44,15 +46,15 @@ SUPERVGraph_ViewManager::~SUPERVGraph_ViewManager() */ 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 diff --git a/src/SUPERVGraph/SUPERVGraph_ViewManager.h b/src/SUPERVGraph/SUPERVGraph_ViewManager.h index 94c5a850d..313beca3b 100644 --- a/src/SUPERVGraph/SUPERVGraph_ViewManager.h +++ b/src/SUPERVGraph/SUPERVGraph_ViewManager.h @@ -21,7 +21,6 @@ #include "SUPERVGraph.h" -#include "SUPERVGraph_ViewModel.h" #include "SUIT_ViewManager.h" class SUIT_Desktop; @@ -34,7 +33,7 @@ public: 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); diff --git a/src/SUPERVGraph/resources/SUPERVGraph_images.ts b/src/SUPERVGraph/resources/SUPERVGraph_images.ts new file mode 100644 index 000000000..c52d03db6 --- /dev/null +++ b/src/SUPERVGraph/resources/SUPERVGraph_images.ts @@ -0,0 +1,13 @@ + + + @default + + ICON_SUPERVGraph_PAN + view_pan.png + + + ICON_SUPERVGraph_RESET + view_reset.png + + + diff --git a/src/SUPERVGraph/resources/SUPERVGraph_msg_en.ts b/src/SUPERVGraph/resources/SUPERVGraph_msg_en.ts new file mode 100644 index 000000000..082ad5efc --- /dev/null +++ b/src/SUPERVGraph/resources/SUPERVGraph_msg_en.ts @@ -0,0 +1,25 @@ + + + @default + + MNU_PAN_VIEW + Panning + + + DSC_PAN_VIEW + Panning the view + + + MNU_RESET_VIEW + Reset + + + DSC_RESET_VIEW + Reset View Point + + + LBL_TOOLBAR_LABEL + View Operations + + + diff --git a/src/SVTK/Makefile.am b/src/SVTK/Makefile.am index fb2ef1387..e85daf207 100755 --- a/src/SVTK/Makefile.am +++ b/src/SVTK/Makefile.am @@ -108,20 +108,16 @@ libSVTK_la_CPPFLAGS= \ $(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 diff --git a/src/SVTK/SALOME_Actor.cxx b/src/SVTK/SALOME_Actor.cxx index b9597c30c..7f17c2708 100644 --- a/src/SVTK/SALOME_Actor.cxx +++ b/src/SVTK/SALOME_Actor.cxx @@ -33,6 +33,7 @@ #include "SALOME_Actor.h" +#include "SALOME_InteractiveObject.hxx" #include "VTKViewer_Transform.h" #include "VTKViewer_TransformFilter.h" diff --git a/src/SVTK/SALOME_Actor.h b/src/SVTK/SALOME_Actor.h index a44acc9fd..db4e2e56e 100644 --- a/src/SVTK/SALOME_Actor.h +++ b/src/SVTK/SALOME_Actor.h @@ -33,7 +33,7 @@ #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() diff --git a/src/SVTK/SVTK.h b/src/SVTK/SVTK.h index b07763c0b..970bd3889 100755 --- a/src/SVTK/SVTK.h +++ b/src/SVTK/SVTK.h @@ -21,7 +21,7 @@ #include "VTKViewer.h" -#ifdef WNT +#ifdef WIN32 # ifdef SVTK_EXPORTS # define SVTK_EXPORT __declspec(dllexport) # else @@ -31,7 +31,7 @@ # define SVTK_EXPORT #endif -#if defined WNT +#if defined WIN32 #pragma warning ( disable: 4251 ) #pragma warning ( disable: 4786 ) #endif diff --git a/src/SVTK/SVTK.pro b/src/SVTK/SVTK.pro new file mode 100644 index 000000000..f1561b744 --- /dev/null +++ b/src/SVTK/SVTK.pro @@ -0,0 +1,93 @@ +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 diff --git a/src/SVTK/SVTK_Actor.cxx b/src/SVTK/SVTK_Actor.cxx index 1d32a1c2b..8ccb82a8b 100644 --- a/src/SVTK/SVTK_Actor.cxx +++ b/src/SVTK/SVTK_Actor.cxx @@ -20,6 +20,8 @@ #include "SVTK_Actor.h" #include "SALOME_Actor.h" +#include "SALOME_InteractiveObject.hxx" + // VTK Includes #include #include diff --git a/src/SVTK/SVTK_CubeAxesActor2D.cxx b/src/SVTK/SVTK_CubeAxesActor2D.cxx index 823c07224..4f109801c 100644 --- a/src/SVTK/SVTK_CubeAxesActor2D.cxx +++ b/src/SVTK/SVTK_CubeAxesActor2D.cxx @@ -205,7 +205,7 @@ static void ChangeValues(vtkFloatingPointType* aArray1, 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++){ @@ -450,7 +450,7 @@ int SVTK_CubeAxesActor2D::RenderOpaqueGeometry(vtkViewport *viewport) // XCoords coordinates for X grid vtkFloatArray *XCoords = vtkFloatArray::New(); -#ifndef WNT +#ifndef WIN32 for(int i=0;iGetValue(numOfLabelsY-1); p[5][2] = aMiddleZ; -#ifndef WNT +#ifndef WIN32 for(int i=0;i<3;i++) #else for(i=0;i<3;i++) diff --git a/src/SVTK/SVTK_CubeAxesActor2D.h b/src/SVTK/SVTK_CubeAxesActor2D.h index 445f6d71e..0443f0b28 100644 --- a/src/SVTK/SVTK_CubeAxesActor2D.h +++ b/src/SVTK/SVTK_CubeAxesActor2D.h @@ -48,7 +48,7 @@ class VTKViewer_Transform; #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 diff --git a/src/SVTK/SVTK_CubeAxesDlg.cxx b/src/SVTK/SVTK_CubeAxesDlg.cxx index 94e4af88f..a69b9a388 100644 --- a/src/SVTK/SVTK_CubeAxesDlg.cxx +++ b/src/SVTK/SVTK_CubeAxesDlg.cxx @@ -35,16 +35,14 @@ #include "QtxAction.h" #include "QtxIntSpinBox.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -60,64 +58,100 @@ 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); @@ -129,10 +163,10 @@ SVTK_AxisWidget::SVTK_AxisWidget (QWidget* theParent) 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); @@ -158,11 +192,14 @@ void SVTK_AxisWidget::updateControlState() 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() @@ -278,7 +315,7 @@ bool SVTK_AxisWidget::Apply(vtkAxisActor2D* theActor) // 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; @@ -360,9 +397,11 @@ SVTK_CubeAxesDlg::SVTK_CubeAxesDlg(QtxAction* theAction, 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)); @@ -387,11 +426,13 @@ QWidget* SVTK_CubeAxesDlg::createMainFrame(QWidget* theParent) 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); @@ -412,7 +453,9 @@ QWidget* SVTK_CubeAxesDlg::createButtonFrame(QWidget* theParent) 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); diff --git a/src/SVTK/SVTK_CubeAxesDlg.h b/src/SVTK/SVTK_CubeAxesDlg.h index c4277db69..1428dad9d 100644 --- a/src/SVTK/SVTK_CubeAxesDlg.h +++ b/src/SVTK/SVTK_CubeAxesDlg.h @@ -29,10 +29,9 @@ #include "SVTK_DialogBase.h" -#include +#include class QWidget; -class QFrame; class QPushButton; class QTabWidget; class QCheckBox; diff --git a/src/SVTK/SVTK_DialogBase.cxx b/src/SVTK/SVTK_DialogBase.cxx index 9cf3432bf..7aeedd172 100644 --- a/src/SVTK/SVTK_DialogBase.cxx +++ b/src/SVTK/SVTK_DialogBase.cxx @@ -38,13 +38,14 @@ SVTK_DialogBase 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())); } @@ -62,7 +63,7 @@ void SVTK_DialogBase ::onParentShow() { - if(myAction->isOn()) + if(myAction->isChecked()) show(); else hide(); @@ -79,6 +80,6 @@ void SVTK_DialogBase ::done( int r ) { - myAction->setOn( false ); + myAction->setChecked( false ); QDialog::done( r ); } diff --git a/src/SVTK/SVTK_DialogBase.h b/src/SVTK/SVTK_DialogBase.h index 5c0b87eb5..8d3ae0f0d 100644 --- a/src/SVTK/SVTK_DialogBase.h +++ b/src/SVTK/SVTK_DialogBase.h @@ -31,7 +31,7 @@ #include "SVTK.h" -#include +#include class QtxAction; @@ -44,7 +44,7 @@ public: QWidget* theParent, const char* theName = "", bool theModal = FALSE, - WFlags theWFalgs = 0); + Qt::WindowFlags theWFalgs = 0); ~SVTK_DialogBase(); diff --git a/src/SVTK/SVTK_FontWidget.cxx b/src/SVTK/SVTK_FontWidget.cxx index 4269b5b6b..b32f7ab0c 100644 --- a/src/SVTK/SVTK_FontWidget.cxx +++ b/src/SVTK/SVTK_FontWidget.cxx @@ -27,10 +27,11 @@ #include "SVTK_FontWidget.h" -#include -#include -#include -#include +#include +#include +#include +#include +#include #include @@ -43,21 +44,29 @@ 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() ) ); } @@ -70,12 +79,14 @@ SVTK_FontWidget::~SVTK_FontWidget() 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() @@ -94,11 +105,11 @@ void SVTK_FontWidget::SetData( const QColor& theColor, 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 ); @@ -113,7 +124,7 @@ void SVTK_FontWidget::GetData( QColor& theColor, { theColor = GetColor(); - int anItem =myFamily->currentItem(); + int anItem =myFamily->currentIndex(); if ( anItem == 0 ) theFamily = VTK_ARIAL; else if ( anItem == 1 ) diff --git a/src/SVTK/SVTK_FontWidget.h b/src/SVTK/SVTK_FontWidget.h index 953072a94..3c10e1a2c 100644 --- a/src/SVTK/SVTK_FontWidget.h +++ b/src/SVTK/SVTK_FontWidget.h @@ -29,7 +29,7 @@ #include "SVTK.h" -#include +#include class QToolButton; class QComboBox; @@ -41,7 +41,7 @@ class QColor; * Class : SVTK_FontWidget * Description : Dialog for specifynig font */ -class SVTK_EXPORT SVTK_FontWidget : public QHBox +class SVTK_EXPORT SVTK_FontWidget : public QWidget { Q_OBJECT diff --git a/src/SVTK/SVTK_GenericRenderWindowInteractor.cxx b/src/SVTK/SVTK_GenericRenderWindowInteractor.cxx index ecb406b1b..3dffbae50 100644 --- a/src/SVTK/SVTK_GenericRenderWindowInteractor.cxx +++ b/src/SVTK/SVTK_GenericRenderWindowInteractor.cxx @@ -32,7 +32,7 @@ #include #include -#include +#include using namespace std; @@ -80,7 +80,8 @@ QVTK_GenericRenderWindowInteractor // Start a one-shot timer for ms. // static int DELAY = 1; - myTimer->start(DELAY,TRUE); + myTimer->setSingleShot(TRUE); + myTimer->start(DELAY); return 1; } diff --git a/src/SVTK/SVTK_GenericRenderWindowInteractor.h b/src/SVTK/SVTK_GenericRenderWindowInteractor.h index ff5b6cb71..9bb7cbfcd 100644 --- a/src/SVTK/SVTK_GenericRenderWindowInteractor.h +++ b/src/SVTK/SVTK_GenericRenderWindowInteractor.h @@ -31,7 +31,7 @@ #include "SVTK.h" -#include +#include #include #include @@ -39,7 +39,7 @@ class QTimer; class QWidget; class SVTK_Selector; -class SVTK_Renderer; +//class SVTK_Renderer; #ifdef WIN32 #pragma warning ( disable:4251 ) diff --git a/src/SVTK/SVTK_InteractorStyle.cxx b/src/SVTK/SVTK_InteractorStyle.cxx index 2746a24e6..f9fffd606 100644 --- a/src/SVTK/SVTK_InteractorStyle.cxx +++ b/src/SVTK/SVTK_InteractorStyle.cxx @@ -58,15 +58,11 @@ #include #include -#include -#include -//VRV: porting on Qt 3.0.5 -#if QT_VERSION >= 0x030005 -#include -#endif -//VRV: porting on Qt 3.0.5 -#include +#include +#include +#include +#include #include using namespace std; @@ -119,7 +115,8 @@ SVTK_InteractorStyle myLastPreHighlitedActor(NULL), myControllerIncrement(SVTK_ControllerIncrement::New()), myControllerOnKeyDown(SVTK_ControllerOnKeyDown::New()), - myHighlightRotationPointActor(SVTK_Actor::New()) + myHighlightRotationPointActor(SVTK_Actor::New()), + myRectBand(0) { myPicker->Delete(); myPointPicker->Delete(); @@ -165,6 +162,7 @@ SVTK_InteractorStyle SVTK_InteractorStyle ::~SVTK_InteractorStyle() { + endDrawRect(); } /*! @@ -1037,10 +1035,7 @@ SVTK_InteractorStyle 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: @@ -1073,12 +1068,9 @@ SVTK_InteractorStyle 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 @@ -1214,12 +1206,7 @@ SVTK_InteractorStyle } 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; } } @@ -1500,6 +1487,39 @@ SVTK_InteractorStyle 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) */ diff --git a/src/SVTK/SVTK_InteractorStyle.h b/src/SVTK/SVTK_InteractorStyle.h index dec8c0a0d..8d355d79e 100644 --- a/src/SVTK/SVTK_InteractorStyle.h +++ b/src/SVTK/SVTK_InteractorStyle.h @@ -38,8 +38,7 @@ #include #include -#include -#include +#include #include @@ -103,7 +102,6 @@ class SVTK_EXPORT SVTK_ControllerOnKeyDown : public vtkObject{ void operator=(const SVTK_ControllerOnKeyDown&); //Not implemented }; -class vtkCell; class vtkPicker; class vtkPointPicker; @@ -113,6 +111,8 @@ class SVTK_Selector; 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 @@ -297,6 +297,9 @@ class SVTK_EXPORT SVTK_InteractorStyle: public vtkInteractorStyle void DominantCombinedSwitch(); + void drawRect(); + void endDrawRect(); + protected: QCursor myDefCursor; QCursor myPanCursor; @@ -343,6 +346,8 @@ class SVTK_EXPORT SVTK_InteractorStyle: public vtkInteractorStyle vtkFloatingPointType myBBCenter[3]; bool myBBFirstCheck; + + QRubberBand* myRectBand; //!< selection rectangle rubber band }; #ifdef WIN32 diff --git a/src/SVTK/SVTK_MainWindow.cxx b/src/SVTK/SVTK_MainWindow.cxx index 045a05453..1c0b5e9f5 100644 --- a/src/SVTK/SVTK_MainWindow.cxx +++ b/src/SVTK/SVTK_MainWindow.cxx @@ -52,7 +52,8 @@ #include "SVTK_Selector.h" -#include +#include +#include /*! Constructor @@ -62,12 +63,14 @@ SVTK_MainWindow 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(); @@ -84,9 +87,9 @@ SVTK_MainWindow 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); @@ -474,7 +477,7 @@ SVTK_MainWindow 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; @@ -550,7 +553,7 @@ SVTK_MainWindow 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; @@ -559,7 +562,7 @@ SVTK_MainWindow 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; @@ -568,7 +571,7 @@ SVTK_MainWindow 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; } @@ -896,5 +899,5 @@ SVTK_MainWindow ::dumpView() { QPixmap px = QPixmap::grabWindow( GetInteractor()->winId() ); - return px.convertToImage(); + return px.toImage(); } diff --git a/src/SVTK/SVTK_MainWindow.h b/src/SVTK/SVTK_MainWindow.h index 1be95b652..77157c02c 100644 --- a/src/SVTK/SVTK_MainWindow.h +++ b/src/SVTK/SVTK_MainWindow.h @@ -28,7 +28,8 @@ #include -#include +#include +#include class QtxAction; @@ -49,7 +50,6 @@ class SVTK_CubeAxesDlg; class SVTK_SetRotationPointDlg; class VTKViewer_Trihedron; -class VTKViewer_Transform; class VTKViewer_Actor; class SVTK_Renderer; diff --git a/src/SVTK/SVTK_NonIsometricDlg.cxx b/src/SVTK/SVTK_NonIsometricDlg.cxx index 7b99f2c9c..a3a2044ae 100644 --- a/src/SVTK/SVTK_NonIsometricDlg.cxx +++ b/src/SVTK/SVTK_NonIsometricDlg.cxx @@ -30,13 +30,13 @@ #include "SVTK_MainWindow.h" #include "SVTK_Renderer.h" -#include "QtxDblSpinBox.h" +#include "QtxDoubleSpinBox.h" #include "QtxAction.h" -#include -#include -#include -#include +#include +#include +#include +#include using namespace std; @@ -52,7 +52,7 @@ SVTK_NonIsometricDlg theName), m_MainWindow(theParent) { - setCaption(tr("DLG_TITLE")); + setWindowTitle(tr("DLG_TITLE")); setSizeGripEnabled(TRUE); // Create layout for this dialog @@ -61,34 +61,39 @@ SVTK_NonIsometricDlg 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 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); @@ -106,14 +111,17 @@ SVTK_NonIsometricDlg aHBoxLayout2->setMargin(11); aHBoxLayout2->setSpacing(6); // Create 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 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 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 diff --git a/src/SVTK/SVTK_NonIsometricDlg.h b/src/SVTK/SVTK_NonIsometricDlg.h index 66be82a39..bcb730d52 100644 --- a/src/SVTK/SVTK_NonIsometricDlg.h +++ b/src/SVTK/SVTK_NonIsometricDlg.h @@ -33,7 +33,7 @@ class SVTK_MainWindow; -class QtxDblSpinBox; +class QtxDoubleSpinBox; class QtxAction; class QPushButton; @@ -55,9 +55,9 @@ public: 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: diff --git a/src/SVTK/SVTK_Prs.cxx b/src/SVTK/SVTK_Prs.cxx index 11e4b20f5..3e017e8f3 100644 --- a/src/SVTK/SVTK_Prs.cxx +++ b/src/SVTK/SVTK_Prs.cxx @@ -27,6 +27,9 @@ // $Header$ #include "SVTK_Prs.h" + +#include + using namespace std; /*! diff --git a/src/SVTK/SVTK_Prs.h b/src/SVTK/SVTK_Prs.h index 218a9f101..7931972d4 100644 --- a/src/SVTK/SVTK_Prs.h +++ b/src/SVTK/SVTK_Prs.h @@ -32,7 +32,8 @@ #include #include "SALOME_Prs.h" -#include +class vtkActorCollection; +class vtkActor; class SVTK_EXPORT SVTK_Prs : public SALOME_VTKPrs { diff --git a/src/SVTK/SVTK_RenderWindowInteractor.cxx b/src/SVTK/SVTK_RenderWindowInteractor.cxx index 647fbc554..a937a7cbd 100644 --- a/src/SVTK/SVTK_RenderWindowInteractor.cxx +++ b/src/SVTK/SVTK_RenderWindowInteractor.cxx @@ -27,13 +27,19 @@ // $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 +#include + #include "SVTK_SpaceMouse.h" #include "SVTK_Event.h" @@ -49,12 +55,6 @@ #include #include -// QT Includes -#include -#include -#include -#include - using namespace std; static bool GENERATE_SUIT_EVENTS = false; @@ -67,16 +67,18 @@ static bool FOCUS_UNDER_MOUSE = 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()); } @@ -106,7 +108,7 @@ QVTK_RenderWindowInteractor #ifndef WIN32 SVTK_SpaceMouse* aSpaceMouse = SVTK_SpaceMouse::getInstance(); if ( aSpaceMouse && aSpaceMouse->isSpaceMouseOn() ) - aSpaceMouse->close( x11Display() ); + aSpaceMouse->close( QX11Info::display() ); #endif } @@ -240,8 +242,8 @@ QVTK_RenderWindowInteractor { GetDevice()->SetEventInformationFlipY(event->x(), event->y(), - event->state() & ControlButton, - event->state() & ShiftButton); + event->modifiers() & Qt::ControlModifier, + event->modifiers() & Qt::ShiftModifier); GetDevice()->MouseMoveEvent(); } @@ -255,13 +257,13 @@ QVTK_RenderWindowInteractor { 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(); } @@ -275,14 +277,14 @@ QVTK_RenderWindowInteractor { 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(); } @@ -303,7 +305,7 @@ void QVTK_RenderWindowInteractor ::wheelEvent( QWheelEvent* event ) { - setActiveWindow(); + activateWindow(); setFocus(); } @@ -315,8 +317,8 @@ void 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(); @@ -329,8 +331,8 @@ void 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(); } @@ -344,7 +346,7 @@ QVTK_RenderWindowInteractor ::enterEvent( QEvent* event ) { if(FOCUS_UNDER_MOUSE){ - setActiveWindow(); + activateWindow(); setFocus(); } GetDevice()->EnterEvent(); @@ -378,9 +380,9 @@ QVTK_RenderWindowInteractor { 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 } @@ -399,7 +401,7 @@ QVTK_RenderWindowInteractor // 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 } @@ -430,7 +432,7 @@ QVTK_RenderWindowInteractor 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: @@ -778,6 +780,6 @@ void SVTK_RenderWindowInteractor ::contextMenuEvent( QContextMenuEvent* event ) { - if( !( event->state() & KeyButtonMask ) ) + if( !( event->modifiers() & Qt::KeyboardModifierMask ) ) emit contextMenuRequested( event ); } diff --git a/src/SVTK/SVTK_RenderWindowInteractor.h b/src/SVTK/SVTK_RenderWindowInteractor.h index dd6a52502..965a2a751 100644 --- a/src/SVTK/SVTK_RenderWindowInteractor.h +++ b/src/SVTK/SVTK_RenderWindowInteractor.h @@ -33,7 +33,7 @@ #include "SVTK_Selection.h" #include -#include +#include // undefining min and max because CASCADE's defines them and // it clashes with std::min(), std::max() diff --git a/src/SVTK/SVTK_Selector.cxx b/src/SVTK/SVTK_Selector.cxx index d93bd4b44..86e9bc335 100644 --- a/src/SVTK/SVTK_Selector.cxx +++ b/src/SVTK/SVTK_Selector.cxx @@ -29,6 +29,8 @@ #include "SVTK_SelectorDef.h" +#include "VTKViewer_Filter.h" + #include "SALOME_Actor.h" #include diff --git a/src/SVTK/SVTK_Selector.h b/src/SVTK/SVTK_Selector.h index 380e28b31..17ab9be70 100644 --- a/src/SVTK/SVTK_Selector.h +++ b/src/SVTK/SVTK_Selector.h @@ -32,15 +32,16 @@ #include "SVTK.h" #include "SVTK_Selection.h" #include "SALOME_ListIO.hxx" -#include "VTKViewer_Filter.h" -#include "SALOME_InteractiveObject.hxx" #include #include #include +class Handle(VTKViewer_Filter); + class SALOME_Actor; +class Handle(SALOME_InteractiveObject); //! Define an abstract interface for selection in SVTK package /*! diff --git a/src/SVTK/SVTK_SelectorDef.h b/src/SVTK/SVTK_SelectorDef.h index e20d764ec..6515a187b 100644 --- a/src/SVTK/SVTK_SelectorDef.h +++ b/src/SVTK/SVTK_SelectorDef.h @@ -36,6 +36,8 @@ #include #include +#include "SALOME_InteractiveObject.hxx" + #include "SVTK_Selector.h" class SALOME_Actor; diff --git a/src/SVTK/SVTK_SetRotationPointDlg.cxx b/src/SVTK/SVTK_SetRotationPointDlg.cxx index d98efaa21..50f8f69e8 100755 --- a/src/SVTK/SVTK_SetRotationPointDlg.cxx +++ b/src/SVTK/SVTK_SetRotationPointDlg.cxx @@ -36,16 +36,13 @@ #include "QtxAction.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include #include @@ -66,7 +63,7 @@ SVTK_SetRotationPointDlg myEventCallbackCommand(vtkCallbackCommand::New()), myRWInteractor(theParent->GetInteractor()) { - setCaption(tr("DLG_TITLE")); + setWindowTitle(tr("DLG_TITLE")); setSizeGripEnabled(TRUE); // Create layout for this dialog @@ -75,35 +72,44 @@ SVTK_SetRotationPointDlg 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)); @@ -111,7 +117,8 @@ SVTK_SetRotationPointDlg 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)); @@ -119,7 +126,8 @@ SVTK_SetRotationPointDlg 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)); @@ -140,7 +148,8 @@ SVTK_SetRotationPointDlg 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())); @@ -149,12 +158,12 @@ SVTK_SetRotationPointDlg 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()); @@ -240,10 +249,11 @@ void 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")) @@ -256,12 +266,12 @@ void 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 @@ -280,7 +290,7 @@ void 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)); @@ -291,7 +301,7 @@ void SVTK_SetRotationPointDlg ::onSelectPoint() { - if ( mySelectPoint->state() == QButton::On ) + if ( mySelectPoint->isChecked() ) myMainWindow->activateStartPointSelection(); else mySelectPoint->toggle(); @@ -302,7 +312,7 @@ SVTK_SetRotationPointDlg ::onCoordChanged() { if ( !myIsBBCenter->isChecked() ) { - if ( mySelectPoint->state() == QButton::On + if ( mySelectPoint->isChecked() && ( myX->hasFocus() || myY->hasFocus() || myZ->hasFocus() ) ) mySelectPoint->toggle(); diff --git a/src/SVTK/SVTK_SetRotationPointDlg.h b/src/SVTK/SVTK_SetRotationPointDlg.h index a598affc7..57df00166 100755 --- a/src/SVTK/SVTK_SetRotationPointDlg.h +++ b/src/SVTK/SVTK_SetRotationPointDlg.h @@ -43,7 +43,6 @@ class QtxAction; class QLineEdit; class QPushButton; class QGroupBox; -class QButtonGroup; class QCheckBox; class vtkCallbackCommand; @@ -70,7 +69,7 @@ protected: QCheckBox* myIsBBCenter; - QButtonGroup* myGroupSelButton; + QGroupBox * myGroupBoxSel; QPushButton* myToOrigin; QPushButton* mySelectPoint; diff --git a/src/SVTK/SVTK_UpdateRateDlg.cxx b/src/SVTK/SVTK_UpdateRateDlg.cxx index 7f31fb2b9..4c5262ebc 100644 --- a/src/SVTK/SVTK_UpdateRateDlg.cxx +++ b/src/SVTK/SVTK_UpdateRateDlg.cxx @@ -33,16 +33,16 @@ #include "VTKViewer_Algorithm.h" #include "SALOME_Actor.h" -#include "QtxDblSpinBox.h" +#include "QtxDoubleSpinBox.h" #include "QtxAction.h" #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include @@ -178,25 +178,26 @@ SVTK_UpdateRateDlg 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); @@ -210,7 +211,7 @@ SVTK_UpdateRateDlg 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); @@ -223,11 +224,10 @@ SVTK_UpdateRateDlg } { 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); diff --git a/src/SVTK/SVTK_UpdateRateDlg.h b/src/SVTK/SVTK_UpdateRateDlg.h index 388d66600..761f75afe 100644 --- a/src/SVTK/SVTK_UpdateRateDlg.h +++ b/src/SVTK/SVTK_UpdateRateDlg.h @@ -36,7 +36,7 @@ class SVTK_MainWindow; class SVTK_RenderWindowInteractor; -class QtxDblSpinBox; +class QtxDoubleSpinBox; class QtxAction; class QGroupBox; @@ -61,8 +61,8 @@ public: protected: SVTK_RenderWindowInteractor* myRWInteractor; - QtxDblSpinBox* myDesiredUpdateRateSblSpinBox; - QtxDblSpinBox* myStillUpdateRateSblSpinBox; + QtxDoubleSpinBox* myDesiredUpdateRateSblSpinBox; + QtxDoubleSpinBox* myStillUpdateRateSblSpinBox; QGroupBox* myIsEnableUpdateRateGroupBox; QLineEdit* myCurrentUpdateRateLineEdit; diff --git a/src/SVTK/SVTK_View.cxx b/src/SVTK/SVTK_View.cxx index 882728b3a..e056d6d77 100644 --- a/src/SVTK/SVTK_View.cxx +++ b/src/SVTK/SVTK_View.cxx @@ -307,8 +307,8 @@ SVTK_View using namespace SVTK; ForEachIf(getRenderer()->GetActors(), TIsSameIObject(theIObject), - TSetFunction - (&SALOME_Actor::setName,theName.latin1())); + TSetFunction + (&SALOME_Actor::setName,theName.toLatin1().data())); } /*! diff --git a/src/SVTK/SVTK_View.h b/src/SVTK/SVTK_View.h index 4c25de9bc..af25bf5ea 100644 --- a/src/SVTK/SVTK_View.h +++ b/src/SVTK/SVTK_View.h @@ -26,7 +26,7 @@ #include "SVTK.h" #include "SALOME_InteractiveObject.hxx" -#include +#include class vtkActorCollection; class vtkRenderer; @@ -36,6 +36,13 @@ class SVTK_Renderer; 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 diff --git a/src/SVTK/SVTK_ViewModel.cxx b/src/SVTK/SVTK_ViewModel.cxx index 0624c7d47..990a96ee9 100644 --- a/src/SVTK/SVTK_ViewModel.cxx +++ b/src/SVTK/SVTK_ViewModel.cxx @@ -16,14 +16,17 @@ // // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com // -#include -#include +#include +#include +#include #include #include #include -#include "SUIT_Session.h" +//#include "SUIT_Session.h" +#include "SUIT_ViewModel.h" +#include "SUIT_ViewManager.h" #include "SVTK_Selection.h" #include "SVTK_ViewModel.h" @@ -35,7 +38,6 @@ #include "VTKViewer_ViewModel.h" #include -#include // 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 @@ -96,7 +98,7 @@ SVTK_Viewer if ( !theColor.isValid() ) return; - QPtrVector aViews = myViewManager->getViews(); + QVector 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(aViewWindow)){ @@ -151,7 +153,7 @@ void SVTK_Viewer::setTrihedronSize( const vtkFloatingPointType theSize, const bo myTrihedronRelative = theRelative; if (SUIT_ViewManager* aViewManager = getViewManager()) { - QPtrVector aViews = aViewManager->getViews(); + QVector aViews = aViewManager->getViews(); for ( uint i = 0; i < aViews.count(); i++ ) { if ( TViewWindow* aView = dynamic_cast(aViews.at( i )) ) @@ -186,16 +188,16 @@ void SVTK_Viewer::setViewManager(SUIT_ViewManager* theViewManager) */ 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(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(); } @@ -280,7 +282,7 @@ void SVTK_Viewer ::onShowToolbar() { - QPtrVector aViews = myViewManager->getViews(); + QVector aViews = myViewManager->getViews(); for(int i = 0, iEnd = aViews.size(); i < iEnd; i++){ if(TViewWindow* aView = dynamic_cast(aViews.at(i))){ aView->getMainWindow()->getToolBar()->show(); @@ -318,7 +320,7 @@ SVTK_Viewer // ToolsGUI::SetVisibility(aStudy,anObj->getEntry(),true,this); //} // just display the object - QPtrVector aViews = myViewManager->getViews(); + QVector aViews = myViewManager->getViews(); for(int i = 0, iEnd = aViews.size(); i < iEnd; i++){ if(SVTK_ViewWindow* aViewWindow = dynamic_cast(aViews.at(i))){ if(SVTK_View* aView = aViewWindow->getView()){ @@ -367,7 +369,7 @@ SVTK_Viewer // ToolsGUI::SetVisibility(aStudy,anObj->getEntry(),false,this); //} // just display the object - QPtrVector aViews = myViewManager->getViews(); + QVector aViews = myViewManager->getViews(); for(int i = 0, iEnd = aViews.size(); i < iEnd; i++){ if(SVTK_ViewWindow* aViewWindow = dynamic_cast(aViews.at(i))) if(SVTK_View* aView = aViewWindow->getView()) @@ -393,7 +395,7 @@ SVTK_Viewer // TODO: better mechanism of storing display/erse status in a study // should be provided... //_PTR(Study) aStudy(getStudyDS()); - QPtrVector aViews = myViewManager->getViews(); + QVector aViews = myViewManager->getViews(); for(int i = 0, iEnd = aViews.size(); i < iEnd; i++){ if(SVTK_ViewWindow* aViewWindow = dynamic_cast(aViews.at(i))) if(SVTK_View* aView = aViewWindow->getView()){ @@ -483,7 +485,7 @@ bool SVTK_Viewer ::isVisible( const Handle(SALOME_InteractiveObject)& io ) { - QPtrVector aViews = myViewManager->getViews(); + QVector 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(aViewWindow)) @@ -502,7 +504,7 @@ SVTK_Viewer ::Repaint() { // if (theUpdateTrihedron) onAdjustTrihedron(); - QPtrVector aViews = myViewManager->getViews(); + QVector aViews = myViewManager->getViews(); for(int i = 0, iEnd = aViews.size(); i < iEnd; i++) if(TViewWindow* aViewWindow = dynamic_cast(aViews.at(i))) if(SVTK_View* aView = aViewWindow->getView()) diff --git a/src/SVTK/SVTK_ViewModel.h b/src/SVTK/SVTK_ViewModel.h index ec61193b2..db6c4d79d 100644 --- a/src/SVTK/SVTK_ViewModel.h +++ b/src/SVTK/SVTK_ViewModel.h @@ -20,13 +20,14 @@ #define SVTK_VIEWMODEL_H #include "SVTK.h" -#include "SUIT_ViewModel.h" #include "SVTK_ViewModelBase.h" #include "SALOME_Prs.h" #include "SALOME_InteractiveObject.hxx" -#include +#include + +class QMouseEvent; class SVTK_ViewWindow; @@ -51,7 +52,7 @@ public: 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(); } diff --git a/src/SVTK/SVTK_ViewWindow.cxx b/src/SVTK/SVTK_ViewWindow.cxx index 667f406c3..c7da479d0 100755 --- a/src/SVTK/SVTK_ViewWindow.cxx +++ b/src/SVTK/SVTK_ViewWindow.cxx @@ -18,8 +18,8 @@ // #include "SALOME_Actor.h" -#include -#include +#include +#include #include #include @@ -468,7 +468,10 @@ SVTK_ViewWindow ::setBackgroundColor( const QColor& color ) { myMainWindow->SetBackgroundColor( color ); - SUIT_ViewWindow::setBackgroundColor( color ); + + QPalette palette; + palette.setColor(backgroundRole(), color); + setPalette(palette); } /*! @@ -711,8 +714,8 @@ SVTK_ViewWindow QImage SVTK_ViewWindow ::dumpView() -{ - if ( myMainWindow->getToolBar()->hasMouse() || myDumpImage.isNull() ) +{ + if ( myMainWindow->getToolBar()->testAttribute(Qt::WA_UnderMouse) || myDumpImage.isNull() ) return myMainWindow->dumpView(); return myDumpImage; @@ -815,7 +818,7 @@ QString getGradAxisVisualParams( vtkAxisActor2D* actor ) 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(); @@ -854,7 +857,7 @@ void setGradAxisVisualParams( vtkAxisActor2D* actor, const QString& params ) 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 @@ -871,7 +874,7 @@ void setGradAxisVisualParams( vtkAxisActor2D* actor, const QString& params ) 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 ); @@ -973,7 +976,7 @@ void 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]; diff --git a/src/SVTK/SVTK_ViewWindow.h b/src/SVTK/SVTK_ViewWindow.h index 809168505..86c46a116 100755 --- a/src/SVTK/SVTK_ViewWindow.h +++ b/src/SVTK/SVTK_ViewWindow.h @@ -26,9 +26,10 @@ #include "SVTK.h" #include "SVTK_Selection.h" #include "SUIT_ViewWindow.h" + #include "SALOME_InteractiveObject.hxx" -#include +#include class SUIT_Desktop; @@ -40,12 +41,8 @@ class SVTK_MainWindow; class SVTK_Selector; class SVTK_View; -class SVTK_InteractorStyle; class SVTK_CubeAxesActor2D; -class SVTK_RenderWindow; -class SVTK_RenderWindowInteractor; - class vtkRenderer; class vtkRenderWindow; class vtkRenderWindowInteractor; diff --git a/src/SVTK/resources/SVTK_images.ts b/src/SVTK/resources/SVTK_images.ts new file mode 100644 index 000000000..403d572d8 --- /dev/null +++ b/src/SVTK/resources/SVTK_images.ts @@ -0,0 +1,17 @@ + + + @default + + ICON_GRADUATED_AXES + view_graduated_axes.png + + + ICON_SVTK_SCALING + view_scaling.png + + + ICON_UPDATE_RATE + view_update_rate.png + + + diff --git a/src/SVTK/resources/SVTK_msg_en.ts b/src/SVTK/resources/SVTK_msg_en.ts new file mode 100644 index 000000000..e04b91df4 --- /dev/null +++ b/src/SVTK/resources/SVTK_msg_en.ts @@ -0,0 +1,392 @@ + + + @default + + MNU_FRONT_VIEW + Front + + + ERROR + Error + + + MNU_DUMP_VIEW + Dump view... + + + DSC_TOP_VIEW + Top View + + + MNU_PAN_VIEW + Panning + + + MNU_TOP_VIEW + Top + + + DSC_GLOBALPAN_VIEW + Selection of a new center of the view + + + DSC_ROTATE_VIEW + Rotation of the point of view around the scene center + + + MNU_ZOOM_VIEW + Zoom + + + DSC_PAN_VIEW + Panning the view + + + DSC_LEFT_VIEW + Left View + + + DSC_FITALL + Fit all objects inside the view frame + + + MNU_FITALL + Fit All + + + MNU_ROTATE_VIEW + Rotation + + + DSC_SHOW_TRIHEDRON + Show/Hide trihedron in the current view + + + DSC_FRONT_VIEW + Front View + + + MNU_GLOBALPAN_VIEW + Global Panning + + + INF_APP_DUMP_VIEW + Dump view + + + MNU_BACK_VIEW + Back + + + MNU_SHOW_TRIHEDRON + Show/Hide trihedron + + + DSC_CHANGINGROTATIONPOINT_VIEW + Change the point, around which the rotation is performed + + + MNU_BOTTOM_VIEW + Bottom + + + MNU_RESET_VIEW + Reset + + + MNU_LEFT_VIEW + Left + + + DSC_RIGHT_VIEW + Right View + + + MNU_CHANGINGROTATIONPOINT_VIEW + Change Rotation Point + + + DSC_FITRECT + Fit area within the view frame + + + MNU_FITRECT + Fit Area + + + DSC_BOTTOM_VIEW + Bottom View + + + DSC_DUMP_VIEW + Saves the active view in the image file + + + DSC_ZOOM_VIEW + Zoom the view + + + VTK_IMAGE_FILES + Images Files (*.bmp *.png *.jpg *.jpeg) + + + DSC_RESET_VIEW + Reset View Point + + + ERR_DOC_CANT_SAVE_FILE + Cannot save file + + + MNU_RIGHT_VIEW + Right + + + LBL_TOOLBAR_LABEL + View Operations + + + DSC_BACK_VIEW + Back View + + + + SVTK_AxisWidget + + FONT + Font + + + NAME + Name + + + TICK_MARKS + Tick marks + + + LABELS + Labels + + + LENGTH + Length + + + NUMBER + Number + + + OFFSET + Offset + + + IS_VISIBLE + Is visible + + + AXIS_NAME + Axis name + + + + SVTK_CubeAxesDlg + + X_AXIS + X axis + + + Y_AXIS + Y axis + + + Z_AXIS + Z axis + + + CAPTION + Graduated axes + + + IS_VISIBLE + Is visible + + + + SVTK_FontWidget + + BOLD + Bold + + + ARIAL + Arial + + + TIMES + Times + + + ITALIC + Italic + + + SHADOW + Shadow + + + COURIER + Courier + + + + SVTK_MainWindow + + DSC_SVTK_UPDATE_RATE + Update rate + + + DSC_SVTK_SCALING + Scaling + + + MNU_SVTK_SCALING + Scaling + + + MNU_SVTK_GRADUATED_AXES + Graduated axes + + + DSC_SVTK_GRADUATED_AXES + Graduated axes + + + MNU_SVTK_UPDATE_RATE + Update rate + + + + SVTK_NonIsometricDlg + + LBL_X + X : + + + LBL_Y + Y : + + + LBL_Z + Z : + + + MEN_SCALING + Scaling + + + DLG_TITLE + Scaling + + + + SVTK_SetRotationPointDlg + + LBL_X + X : + + + LBL_Y + Y : + + + LBL_Z + Z : + + + LBL_CENTER_OF_BOUNDING_BOX + Center of bounding box + + + RBUTTONGROUP_TITLE + The rotation point type + + + USE_BBCENTER + Use Bounding Box Center + + + LBL_ORIGIN + Origin of the coordinate system + + + LBL_SELECTED_POINT + Selected point + + + LBL_TOORIGIN + Set to Origin + + + LBL_SELECTPOINT + Select Point from View + + + DLG_TITLE + Set Rotation Point + + + + SVTK_UpdateRateDlg + + INFORMATION_FRAME_TITLE + Rendering Metrics + + + STILL + Still Update Rate, FPS + + + INPUT_FRAME_TITLE + Enable + + + NUMBER_CELLS + Number of Cells, - + + + DESIRED + Desired Update Rate, FPS + + + CURRENT_FPS + Current Update Rate, FPS + + + DLG_TITLE + Update Rate + + + + SVTK_ViewManager + + VTK_VIEW_TITLE + VTK scene:%1 - viewer:%2 + + + + SVTK_Viewer + + MEN_DUMP_VIEW + Dump view... + + + MEN_SHOW_TOOLBAR + Show toolbar + + + MEN_CHANGE_BACKGROUD + Change background... + + + diff --git a/src/SalomeApp/Makefile.am b/src/SalomeApp/Makefile.am index 7fe6176f6..4299c0858 100755 --- a/src/SalomeApp/Makefile.am +++ b/src/SalomeApp/Makefile.am @@ -36,6 +36,7 @@ salomeinclude_HEADERS= \ SalomeApp_Application.h \ SalomeApp_DataModel.h \ SalomeApp_DataObject.h \ + SalomeApp_LoadStudiesDlg.h \ SalomeApp_Module.h \ SalomeApp_Study.h \ SalomeApp_ExceptionHandler.h \ @@ -53,6 +54,7 @@ dist_libSalomeApp_la_SOURCES= \ SalomeApp_Application.cxx \ SalomeApp_DataModel.cxx \ SalomeApp_DataObject.cxx \ + SalomeApp_LoadStudiesDlg.cxx \ SalomeApp_Study.cxx \ SalomeApp_ExceptionHandler.cxx \ SalomeApp_EventFilter.cxx \ @@ -70,6 +72,7 @@ MOC_FILES= \ 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 \ @@ -89,17 +92,17 @@ libSalomeApp_la_CPPFLAGS=$(PYTHON_INCLUDES) $(QT_INCLUDES) $(QWT_INCLUDES) \ -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 diff --git a/src/SalomeApp/SalomeApp.h b/src/SalomeApp/SalomeApp.h index 130299b08..7f6c74cef 100644 --- a/src/SalomeApp/SalomeApp.h +++ b/src/SalomeApp/SalomeApp.h @@ -28,7 +28,7 @@ // 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) @@ -38,11 +38,11 @@ #else #define SALOMEAPP_EXPORT -#endif //WNT +#endif //WIN32 #define APP_VERSION "0.1" -#if defined WNT +#if defined WIN32 #pragma warning ( disable: 4251 ) #endif diff --git a/src/SalomeApp/SalomeApp.pro b/src/SalomeApp/SalomeApp.pro new file mode 100644 index 000000000..46efb7d64 --- /dev/null +++ b/src/SalomeApp/SalomeApp.pro @@ -0,0 +1,91 @@ +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 diff --git a/src/SalomeApp/SalomeApp_Application.cxx b/src/SalomeApp/SalomeApp_Application.cxx index 93f1e10aa..50c7a9315 100644 --- a/src/SalomeApp/SalomeApp_Application.cxx +++ b/src/SalomeApp/SalomeApp_Application.cxx @@ -32,45 +32,46 @@ #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 #include +#include #include -#include -#include +// temporary commented +//#include +//#include -#include +#include #include #include #include -#include #include #include -#include #include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include "SALOMEDSClient_ClientFactory.hxx" -#include "SALOMEDSClient_IParameters.hxx" #include "SALOME_ListIteratorOfListIO.hxx" #include "SALOME_ListIO.hxx" @@ -78,11 +79,11 @@ #include "ToolsGUI_CatalogGeneratorDlg.h" #include "ToolsGUI_RegWidget.h" -#include - #include + /*!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(){}; @@ -123,7 +124,7 @@ void SalomeApp_Updater::update( SUIT_DataObject* theObj, OB_ListItem* theItem ) // _PTR(AttributeOpened) aAttrOpen = anAttr; // theItem->setOpen( aAttrOpen->IsOpened() ); //} -} +}*/ /*!Create new instance of SalomeApp_Application.*/ extern "C" SALOMEAPP_EXPORT SUIT_Application* createApplication() @@ -164,17 +165,17 @@ void SalomeApp_Application::start() 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; } } @@ -193,12 +194,12 @@ void SalomeApp_Application::start() 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 { @@ -224,40 +225,40 @@ void SalomeApp_Application::createActions() //! 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 @@ -290,20 +291,23 @@ bool SalomeApp_Application::onOpenDoc( const QString& aName ) // Look among opened studies if (activeStudy()) { // at least one study is opened SUIT_Session* aSession = SUIT_Session::session(); - QPtrList aAppList = aSession->applications(); - QPtrListIterator it (aAppList); + QList aAppList = aSession->applications(); + QListIterator 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); @@ -348,11 +352,12 @@ bool SalomeApp_Application::onOpenDoc( const QString& aName ) // 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 { @@ -380,51 +385,46 @@ bool SalomeApp_Application::onOpenDoc( const QString& aName ) /*!SLOT. Load document.*/ void SalomeApp_Application::onLoadDoc() { - QString name, studyname, ext; - - STD_LoadStudiesDlg aDlg( desktop(), TRUE); + QString studyName; std::vector List = studyMgr()->GetOpenStudies(); SUIT_Session* aSession = SUIT_Session::session(); - QPtrList aAppList = aSession->applications(); - SUIT_Application* aApp = 0; + QList 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 it( aAppList ); it.current() && !isAlreadyOpen; ++it ) - { - aApp = it.current(); - if(!aApp || !aApp->activeStudy()) continue; - if ( aApp->activeStudy()->studyName() == studyname ) isAlreadyOpen = true; - } + QListIterator 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 ); } } @@ -475,10 +475,9 @@ void SalomeApp_Application::onPaste() 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; } @@ -496,6 +495,14 @@ void SalomeApp_Application::onPaste() } } +/*!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 ) { @@ -504,14 +511,11 @@ 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; } } @@ -582,7 +586,7 @@ void SalomeApp_Application::onDeleteInvalidReferences() /*!Private SLOT. */ void SalomeApp_Application::onOpenWith() { - QApplication::setOverrideCursor( Qt::waitCursor ); + QApplication::setOverrideCursor( Qt::WaitCursor ); SALOME_ListIO aList; LightApp_SelectionMgr* mgr = selectionMgr(); mgr->selectedObjects(aList); @@ -655,12 +659,27 @@ class DumpStudyFileDlg : public SUIT_FileDlg 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( 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; @@ -677,7 +696,7 @@ void SalomeApp_Application::onDumpStudy( ) 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 ); @@ -697,14 +716,14 @@ void SalomeApp_Application::onDumpStudy( ) 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") ); } } @@ -716,10 +735,9 @@ void SalomeApp_Application::onLoadScript( ) _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; } @@ -733,7 +751,7 @@ void SalomeApp_Application::onLoadScript( ) { QString command = QString("execfile(\"%1\")").arg(aFile); - PythonConsole* pyConsole = pythonConsole(); + PyConsole_Console* pyConsole = pythonConsole(); if ( pyConsole ) pyConsole->exec( command ); @@ -747,7 +765,8 @@ void SalomeApp_Application::onSaveGUIState() if ( study ) { SalomeApp_VisualState( this ).storeState(); updateSavePointDataObjects( study ); - objectBrowser()->updateTree( study->root() ); + // temporary commented + //objectBrowser()->updateTree( study->root() ); } updateActions(); } @@ -770,25 +789,28 @@ QWidget* SalomeApp_Application::createWindow( const int flag ) 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*))); @@ -809,7 +831,7 @@ void SalomeApp_Application::createPreferences( LightApp_Preferences* pref ) 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 ); @@ -829,7 +851,7 @@ void SalomeApp_Application::updateDesktopTitle() { 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(activeStudy()); if ( study ) { @@ -845,7 +867,48 @@ void SalomeApp_Application::updateDesktopTitle() { } } - 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*/ @@ -915,13 +978,14 @@ void SalomeApp_Application::onProperties() } /*!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; @@ -931,10 +995,10 @@ void SalomeApp_Application::contextMenuPopup( const QString& type, QPopupMenu* t // 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 @@ -959,8 +1023,8 @@ void SalomeApp_Application::contextMenuPopup( const QString& type, QPopupMenu* t // 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; } @@ -981,7 +1045,7 @@ void SalomeApp_Application::contextMenuPopup( const QString& type, QPopupMenu* t 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: @@ -1004,11 +1068,13 @@ void SalomeApp_Application::updateObjectBrowser( const bool updateModels ) if ( aComponent->ComponentDataType() == "Interface Applicative" ) continue; // skip the magic "Interface Applicative" component - OB_Browser* ob = static_cast( getWindow( WT_ObjectBrowser )); + // temporary commented + /*OB_Browser* ob = static_cast( 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 ); } } @@ -1032,16 +1098,17 @@ void SalomeApp_Application::onCatalogGen() 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( it ); + // temporary commented + /*OB_ListItem* item = dynamic_cast( it ); SalomeApp_Study* study = dynamic_cast( activeStudy() ); if( study && item ) @@ -1078,7 +1145,7 @@ void SalomeApp_Application::onDblClick( QListViewItem* it ) break; } } - } + }*/ } /*! @@ -1129,7 +1196,8 @@ void SalomeApp_Application::onRenameGUIState() if ( !newName.isNull() && !newName.isEmpty() ) { study->setNameOfSavePoint( savePoint, newName ); updateSavePointDataObjects( study ); - objectBrowser()->updateTree( study->root() ); + // temporary commented + //objectBrowser()->updateTree( study->root() ); } } @@ -1153,10 +1221,11 @@ void SalomeApp_Application::onStudySaved( SUIT_Study* study ) { LightApp_Application::onStudySaved( study ); - if ( objectBrowser() ) { + // temporary commented + /*if ( objectBrowser() ) { updateSavePointDataObjects( dynamic_cast( study ) ); objectBrowser()->updateTree( study->root() ); - } + }*/ } /*!Called on Open study operation*/ @@ -1164,35 +1233,20 @@ void SalomeApp_Application::onStudyOpened( SUIT_Study* study ) { LightApp_Application::onStudyOpened( study ); - if ( objectBrowser() ) { + // temporary commented + /*if ( objectBrowser() ) { updateSavePointDataObjects( dynamic_cast( 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( 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 @@ -1247,7 +1301,7 @@ void SalomeApp_Application::updateSavePointDataObjects( SalomeApp_Study* study ) // delete DataObjects that are still in the map -- their IDs were not found in data model for ( QMap::Iterator it = mapDO.begin(); it != mapDO.end(); ++it ) - delete it.data(); + delete it.value(); } /*! Check data object */ @@ -1263,8 +1317,8 @@ bool SalomeApp_Application::checkDataObject(LightApp_DataObject* theObj) 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(); } diff --git a/src/SalomeApp/SalomeApp_Application.h b/src/SalomeApp/SalomeApp_Application.h index 09ece677d..0b9c15f66 100644 --- a/src/SalomeApp/SalomeApp_Application.h +++ b/src/SalomeApp/SalomeApp_Application.h @@ -31,8 +31,6 @@ #include "SalomeApp.h" #include -#include - #include #include @@ -41,17 +39,12 @@ #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 ) @@ -70,6 +63,7 @@ public: enum { MenuToolsId = 5 }; enum { DumpStudyId = LightApp_Application::UserID, LoadScriptId, PropertiesId, CatalogGenId, RegDisplayId, SaveGUIStateId, FileLoadId, UserID }; + enum { CloseUnload = STD_Application::CloseCancel+1 }; public: SalomeApp_Application(); @@ -81,7 +75,7 @@ public: virtual void start(); - virtual void contextMenuPopup( const QString&, QPopupMenu*, QString& ); + virtual void contextMenuPopup( const QString&, QMenu*, QString& ); virtual bool checkDataObject(LightApp_DataObject* theObj); @@ -93,6 +87,8 @@ public: SUIT_ViewManager* newViewManager(const QString&); void updateSavePointDataObjects( SalomeApp_Study* ); + + virtual bool isPossibleToClose( bool& ); public slots: virtual bool onOpenDoc( const QString& ); @@ -118,6 +114,9 @@ protected: virtual void createPreferences( LightApp_Preferences* ); virtual void updateDesktopTitle(); + + virtual bool closeAction( const int, bool& ); + virtual int closeChoice( const QString& ); private slots: void onDeleteInvalidReferences(); @@ -133,7 +132,6 @@ private slots: void onCatalogGen(); void onRegDisplay(); void onOpenWith(); - }; #ifdef WIN32 diff --git a/src/SalomeApp/SalomeApp_CheckFileDlg.cxx b/src/SalomeApp/SalomeApp_CheckFileDlg.cxx index a62a33d47..866e06fbb 100644 --- a/src/SalomeApp/SalomeApp_CheckFileDlg.cxx +++ b/src/SalomeApp/SalomeApp_CheckFileDlg.cxx @@ -18,9 +18,10 @@ // #include "SalomeApp_CheckFileDlg.h" -#include -#include -#include +#include +#include +#include +#include /*! Constructor @@ -28,11 +29,20 @@ 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( 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(); + } } /*! diff --git a/src/SalomeApp/SalomeApp_DataModel.cxx b/src/SalomeApp/SalomeApp_DataModel.cxx index 742a75e35..8c5ca74ac 100644 --- a/src/SalomeApp/SalomeApp_DataModel.cxx +++ b/src/SalomeApp/SalomeApp_DataModel.cxx @@ -26,15 +26,11 @@ #include "SalomeApp_DataObject.h" #include "SalomeApp_Module.h" #include "SalomeApp_Application.h" -#include "SalomeApp_Engine_i.hxx" #include "LightApp_RootObject.h" #include -#include -#include -#include #include #include @@ -58,8 +54,8 @@ public: bool isEqual( const kerPtr&, const suitPtr& ) const; kerPtr nullSrc() const; suitPtr nullTrg() const; - void children( const kerPtr&, QValueList& ) const; - void children( const suitPtr&, QValueList& ) const; + void children( const kerPtr&, QList& ) const; + void children( const suitPtr&, QList& ) const; suitPtr parent( const suitPtr& ) const; bool isCorrect( const kerPtr& ) const; void updateItem( const kerPtr&, const suitPtr& ) const; @@ -119,7 +115,7 @@ suitPtr SalomeApp_DataModelSync::createItem( const kerPtr& so, { DataObjectList ch; parent->children( ch ); - int pos = ch.find( after ); + int pos = ch.indexOf( after ); if( pos>=0 ) parent->insertChild( nitem, pos+1 ); else @@ -188,7 +184,7 @@ suitPtr SalomeApp_DataModelSync::nullTrg() const \param obj - kernel object \param ch - list to be filled */ -void SalomeApp_DataModelSync::children( const kerPtr& obj, QValueList& ch ) const +void SalomeApp_DataModelSync::children( const kerPtr& obj, QList& ch ) const { ch.clear(); _PTR(ChildIterator) it ( myStudy->NewChildIterator( obj ) ); @@ -201,15 +197,16 @@ void SalomeApp_DataModelSync::children( const kerPtr& obj, QValueList& c \param p - SUIT object \param ch - list to be filled */ -void SalomeApp_DataModelSync::children( const suitPtr& p, QValueList& ch ) const +void SalomeApp_DataModelSync::children( const suitPtr& p, QList& 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 it( ch ); + while ( it.hasNext() ) + ch.append( it.next() ); } } @@ -244,7 +241,7 @@ void showTree( SUIT_DataObject* root ) { 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() ); } } @@ -277,7 +274,7 @@ bool SalomeApp_DataModel::open( const QString& name, CAM_Study* study, QStringLi 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 ); @@ -312,7 +309,7 @@ void SalomeApp_DataModel::update( LightApp_DataObject*, LightApp_Study* study ) 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() ) ); } } } @@ -323,7 +320,7 @@ void SalomeApp_DataModel::update( LightApp_DataObject*, LightApp_Study* study ) 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() ) ); } } } @@ -408,7 +405,7 @@ QString SalomeApp_DataModel::getRootEntry( SalomeApp_Study* study ) const anEntry = anObj->entry(); } else if ( study && study->studyDS() ) { // this works even if 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(); } diff --git a/src/SalomeApp/SalomeApp_DataModel.h b/src/SalomeApp/SalomeApp_DataModel.h index 9c2bff16a..bccc327e6 100644 --- a/src/SalomeApp/SalomeApp_DataModel.h +++ b/src/SalomeApp/SalomeApp_DataModel.h @@ -35,7 +35,8 @@ class SalomeApp_Module; class SalomeApp_Study; -class SalomeApp_DataObject; +class SUIT_DataObject; +class LightApp_DataObject; // Class : SalomeApp_DataModel /// Description : Base class of data model diff --git a/src/SalomeApp/SalomeApp_DataObject.cxx b/src/SalomeApp/SalomeApp_DataObject.cxx index dd9ff8960..d9ab722e6 100644 --- a/src/SalomeApp/SalomeApp_DataObject.cxx +++ b/src/SalomeApp/SalomeApp_DataObject.cxx @@ -25,15 +25,8 @@ #include #include -#include -#include - -#include -#include -#include -#include -#include +#include /*!Constructor. Initialize by \a parent*/ SalomeApp_DataObject::SalomeApp_DataObject( SUIT_DataObject* parent ) @@ -129,7 +122,7 @@ QString SalomeApp_DataObject::text( const int id ) const switch ( id ) { case CT_Value: -#ifndef WNT +#ifndef WIN32 if ( componentObject() != this ) #else if ( componentObject() != (SUIT_DataObject*)this ) diff --git a/src/SalomeApp/SalomeApp_EventFilter.cxx b/src/SalomeApp/SalomeApp_EventFilter.cxx index 493d690c8..02af6ce0a 100755 --- a/src/SalomeApp/SalomeApp_EventFilter.cxx +++ b/src/SalomeApp/SalomeApp_EventFilter.cxx @@ -18,9 +18,9 @@ // #include "SalomeApp_EventFilter.h" -#include +#include -#include +#include SalomeApp_EventFilter* SalomeApp_EventFilter::myFilter = NULL; @@ -45,9 +45,9 @@ bool SalomeApp_EventFilter::eventFilter( QObject* o, QEvent* e ) { 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 ); diff --git a/src/SalomeApp/SalomeApp_EventFilter.h b/src/SalomeApp/SalomeApp_EventFilter.h index e8849e231..dea5cad73 100755 --- a/src/SalomeApp/SalomeApp_EventFilter.h +++ b/src/SalomeApp/SalomeApp_EventFilter.h @@ -20,9 +20,9 @@ #define SALOMEAPP_EVENTFILTER_H #include "SalomeApp.h" -#include +#include -#if defined WNT +#if defined WIN32 #pragma warning( disable: 4251 ) #endif @@ -50,7 +50,7 @@ private: static SalomeApp_EventFilter* myFilter; }; -#if defined WNT +#if defined WIN32 #pragma warning( default: 4251 ) #endif diff --git a/src/SalomeApp/SalomeApp_ExceptionHandler.cxx b/src/SalomeApp/SalomeApp_ExceptionHandler.cxx index 90de9c62d..e1b871274 100644 --- a/src/SalomeApp/SalomeApp_ExceptionHandler.cxx +++ b/src/SalomeApp/SalomeApp_ExceptionHandler.cxx @@ -24,7 +24,7 @@ #include #include -#include +#include #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100 #include @@ -87,7 +87,7 @@ bool SalomeApp_ExceptionHandler::handle( QObject* o, QEvent* e ) { showMessage( title, QString( e.GetMessageString() ) ); } -#ifndef WNT +#ifndef WIN32 catch(...) { showMessage( title, "Unknown Exception" ); diff --git a/src/SalomeApp/SalomeApp_ImportOperation.cxx b/src/SalomeApp/SalomeApp_ImportOperation.cxx index 5d19bf6f0..5047ca732 100644 --- a/src/SalomeApp/SalomeApp_ImportOperation.cxx +++ b/src/SalomeApp/SalomeApp_ImportOperation.cxx @@ -29,7 +29,7 @@ #include "SalomeApp_ImportOperation.h" #include -#ifndef WNT +#ifndef WIN32 using namespace std; #endif diff --git a/src/SalomeApp/SalomeApp_ListView.cxx b/src/SalomeApp/SalomeApp_ListView.cxx index e2c354eaa..6fcc0e80e 100644 --- a/src/SalomeApp/SalomeApp_ListView.cxx +++ b/src/SalomeApp/SalomeApp_ListView.cxx @@ -29,18 +29,22 @@ #include "SUIT_ResourceMgr.h" #include "SUIT_Session.h" -#include -#include -#include -#include +#include +#include +#include +#include +#include + +#include +#include #include #include -#include "utilities.h" - using namespace std; +using namespace Qt; + /*! Used for resizing editing widget */ @@ -49,19 +53,19 @@ void computeEditGeometry(SalomeApp_ListViewItem* theItem, { 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; @@ -74,23 +78,22 @@ void computeEditGeometry(SalomeApp_ListViewItem* theItem, 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))); @@ -115,13 +118,14 @@ void SalomeApp_ListView::updateViewer() { // 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(); } /*! @@ -131,13 +135,13 @@ void SalomeApp_ListView::updateSelected() { // 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(); } /*! @@ -151,7 +155,7 @@ QString SalomeApp_ListView::popupClientType() const /*! Fills popup menu with items */ -void SalomeApp_ListView::contextMenuPopup( QPopupMenu* aPopup ) +void SalomeApp_ListView::contextMenuPopup( QMenu* aPopup ) { if (aPopup) { // add items here... @@ -168,7 +172,7 @@ void SalomeApp_ListView::clear() myEdit = 0; myEditedItem = 0; } - QListView::clear(); + QTreeWidget::clear(); } /*! @@ -199,7 +203,7 @@ bool SalomeApp_ListView::eventFilter(QObject* object, QEvent* event) !isMouseEnabled()) return true; else - return QListView::eventFilter(object, event); + return QTreeWidget::eventFilter(object, event); } /*! @@ -244,14 +248,14 @@ void SalomeApp_ListView::onSelectionChanged() 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; @@ -271,12 +275,12 @@ void SalomeApp_ListView::onSelectionChanged() */ 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(); } /*! @@ -284,10 +288,10 @@ void SalomeApp_ListView::resizeEvent( QResizeEvent * e) */ 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); } /*! @@ -295,7 +299,7 @@ void SalomeApp_ListView::onHeaderSizeChange(int, int, int) */ void SalomeApp_ListView::viewportPaintEvent(QPaintEvent* e) { - QListView::viewportPaintEvent(e); + QTreeWidget::paintEvent(e); if (myEditedItem && myEdit) { computeEditGeometry(myEditedItem, myEdit); } @@ -386,14 +390,14 @@ UpdateType SalomeApp_ListView::finishEditing(bool ok) \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() && @@ -420,17 +424,7 @@ QRect SalomeApp_ListView::tip(QPoint aPos, 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(); } @@ -439,22 +433,19 @@ QListViewItem( parent, after ) 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); @@ -464,9 +455,9 @@ QListViewItem(parent, theName, theValue) 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); @@ -476,11 +467,12 @@ QListViewItem(parent, theName) 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); } @@ -489,40 +481,28 @@ QListViewItem(parent, after, theName) 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); } @@ -531,12 +511,14 @@ QListViewItem(parent, after, theName, theValue) 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); } @@ -561,12 +543,26 @@ void SalomeApp_ListViewItem::init() 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(""); } /*! @@ -575,7 +571,7 @@ QString SalomeApp_ListViewItem::getName() const UpdateType SalomeApp_ListViewItem::setName(const QString& theName) { UpdateType aNeedsUpdate = utCancel; - if (listView()->columns() > 0) { + if (treeWidget()->columnCount() > 0) { setText(0, theName); aNeedsUpdate = utNone; } @@ -587,7 +583,7 @@ UpdateType SalomeApp_ListViewItem::setName(const QString& theName) */ QString SalomeApp_ListViewItem::getValue() const { - return ( listView()->columns() > 1 ) ? text(1) : QString(""); + return ( treeWidget()->columnCount() > 1 ) ? text(1) : QString(""); } /*! @@ -596,7 +592,7 @@ QString SalomeApp_ListViewItem::getValue() const UpdateType SalomeApp_ListViewItem::setValue(const QString& theValue) { UpdateType aNeedsUpdate = utCancel; - if (listView()->columns() > 1) { + if (treeWidget()->columnCount() > 1) { setText(1, theValue); aNeedsUpdate = utNone; } @@ -622,11 +618,13 @@ QString SalomeApp_ListViewItem::fullName() */ 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); } } @@ -635,10 +633,12 @@ void SalomeApp_ListViewItem::openAllLevels() */ 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); } } @@ -701,7 +701,7 @@ void SalomeApp_ListViewItem::setEditingType(const int type) */ int SalomeApp_ListViewItem::getEditedColumn() { - return listView()->columns()-1; + return treeWidget()->columnCount()-1; } /*! @@ -760,7 +760,7 @@ void SalomeApp_ListViewItem::setButtons(const int buttons) SalomeApp_EntityEdit* SalomeApp_ListViewItem::startEditing() { SalomeApp_EntityEdit* aWidget = 0; - QListView* aListView = listView(); + QTreeWidget* aListView = treeWidget(); if (aListView) { if (!isEditable()) return 0; @@ -825,14 +825,14 @@ UpdateType SalomeApp_ListViewItem::finishEditing(SalomeApp_EntityEdit* theWidget 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(), @@ -859,33 +859,33 @@ QString SalomeApp_ListViewItem::tipText() */ 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; @@ -896,30 +896,30 @@ QRect SalomeApp_ListViewItem::textRect(const int column) const */ 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; @@ -950,8 +950,10 @@ void SalomeApp_EditBox::keyPressEvent( QKeyEvent *e ) Constructor */ SalomeApp_ComboBox::SalomeApp_ComboBox(bool rw, QWidget* parent, const char* name) : -QComboBox(rw, parent, name) +QComboBox(parent) { + setEditable( rw ); + setObjectName( name ); } /*! @@ -960,7 +962,7 @@ QComboBox(rw, parent, 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; } @@ -969,10 +971,10 @@ int SalomeApp_ComboBox::findItem(const QString& theText) 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); } /*! @@ -992,10 +994,10 @@ void SalomeApp_ComboBox::insertItem(const int 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; } } @@ -1020,7 +1022,7 @@ void SalomeApp_ComboBox::insertItem(const double theValue) 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); @@ -1077,7 +1079,7 @@ myCancelBtn(0) 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); @@ -1112,7 +1114,7 @@ myCancelBtn(0) 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); @@ -1126,7 +1128,7 @@ myCancelBtn(0) 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); @@ -1178,7 +1180,7 @@ void SalomeApp_EntityEdit::setText(const QString& theText) if (myCombo) { int aFound = myCombo->findItem(theText); if (aFound >= 0) { - myCombo->setCurrentItem(aFound); + myCombo->setCurrentIndex(aFound); onTextChanged(theText); } } @@ -1196,11 +1198,11 @@ void SalomeApp_EntityEdit::insertItem(const QString& theValue, 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) @@ -1303,7 +1305,7 @@ void SalomeApp_EntityEdit::setFocus() myEdit->setFocus(); //myEdit->selectAll(); } - else if (myCombo && myCombo->editable()) { + else if (myCombo && myCombo->isEditable()) { myCombo->setFocus(); //myCombo->lineEdit()->selectAll(); } diff --git a/src/SalomeApp/SalomeApp_ListView.h b/src/SalomeApp/SalomeApp_ListView.h index 3fa857bb0..df4e3d792 100644 --- a/src/SalomeApp/SalomeApp_ListView.h +++ b/src/SalomeApp/SalomeApp_ListView.h @@ -25,24 +25,20 @@ #ifndef SALOMEAPP_LISTVIEW_H #define SALOMEAPP_LISTVIEW_H -#include +//#include -#include -#include -#include -#include -#include +#include -//VRV: porting on Qt 3.0.5 -#if QT_VERSION >= 0x030005 -#include -#endif -//VRV: porting on Qt 3.0.5 +#include +#include +#include +#include +#include -#include -#include +class QToolButton; -#include +class TColStd_ListOfInteger; +class TColStd_ListOfReal; // enumeration for ListView updating mode enum UpdateType { @@ -61,7 +57,7 @@ class SalomeApp_EntityEdit; \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 @@ -78,7 +74,7 @@ public: // 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); @@ -240,21 +236,17 @@ private: 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*, @@ -264,10 +256,6 @@ public: 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, @@ -340,6 +328,7 @@ public: protected: // initialization void init(); + int depth() const; private: bool myEditable; diff --git a/src/SalomeApp/SalomeApp_LoadStudiesDlg.cxx b/src/SalomeApp/SalomeApp_LoadStudiesDlg.cxx new file mode 100644 index 000000000..1d44048ef --- /dev/null +++ b/src/SalomeApp/SalomeApp_LoadStudiesDlg.cxx @@ -0,0 +1,134 @@ +// 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 +#include +#include +#include +#include +#include + +#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; +} diff --git a/src/SalomeApp/SalomeApp_LoadStudiesDlg.h b/src/SalomeApp/SalomeApp_LoadStudiesDlg.h new file mode 100644 index 000000000..35c9a9847 --- /dev/null +++ b/src/SalomeApp/SalomeApp_LoadStudiesDlg.h @@ -0,0 +1,53 @@ +// 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 + +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 diff --git a/src/SalomeApp/SalomeApp_Module.cxx b/src/SalomeApp/SalomeApp_Module.cxx index 332441a65..918c514ac 100644 --- a/src/SalomeApp/SalomeApp_Module.cxx +++ b/src/SalomeApp/SalomeApp_Module.cxx @@ -27,32 +27,19 @@ #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 #include #include -//#include #include -#include -#include -//#include -//#include -//#include - -#include -#include - -//#include -//#include +#include /*!Constructor.*/ SalomeApp_Module::SalomeApp_Module( const QString& name ) @@ -78,9 +65,9 @@ CAM_DataModel* SalomeApp_Module::createDataModel() } /*!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 ); } /*! @@ -121,7 +108,7 @@ void SalomeApp_Module::extractContainers( const SALOME_ListIO& source, SALOME_Li 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(); diff --git a/src/SalomeApp/SalomeApp_Module.h b/src/SalomeApp/SalomeApp_Module.h index 87ca5aad7..1231c2678 100644 --- a/src/SalomeApp/SalomeApp_Module.h +++ b/src/SalomeApp/SalomeApp_Module.h @@ -30,7 +30,6 @@ class CAM_DataModel; class SalomeApp_Application; -class LightApp_Operation; class LightApp_Selection; class SALOME_ListIO; class QString; @@ -59,7 +58,7 @@ public: 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(); diff --git a/src/SalomeApp/SalomeApp_PyInterp.cxx b/src/SalomeApp/SalomeApp_PyInterp.cxx index 67606feae..cf59e8438 100755 --- a/src/SalomeApp/SalomeApp_PyInterp.cxx +++ b/src/SalomeApp/SalomeApp_PyInterp.cxx @@ -31,12 +31,8 @@ #include #include -#include -#include +#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 using namespace std; /*! @@ -44,7 +40,8 @@ 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 ) { } @@ -81,7 +78,7 @@ bool SalomeApp_PyInterp::initContext() * 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 @@ -112,12 +109,31 @@ bool SalomeApp_PyInterp::initContext() 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; +} diff --git a/src/SalomeApp/SalomeApp_PyInterp.h b/src/SalomeApp/SalomeApp_PyInterp.h index a0db6377f..735be4420 100755 --- a/src/SalomeApp/SalomeApp_PyInterp.h +++ b/src/SalomeApp/SalomeApp_PyInterp.h @@ -29,18 +29,22 @@ #ifndef _SalomeApp_PYINTERP_H_ #define _SalomeApp_PYINTERP_H_ -#include // this include must be first (see PyInterp_base.h)! +#include // 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 diff --git a/src/SalomeApp/SalomeApp_Study.cxx b/src/SalomeApp/SalomeApp_Study.cxx index 1fb4d0bdd..ec8a6b893 100644 --- a/src/SalomeApp/SalomeApp_Study.cxx +++ b/src/SalomeApp/SalomeApp_Study.cxx @@ -20,32 +20,22 @@ #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 +// temporary commented +//#include #include -#include -#include -#include - #include "utilities.h" -#include -#include -#include - -#include #include "SALOMEDS_Tool.hxx" #include "SALOMEDSClient_ClientFactory.hxx" -#include "SALOMEDSClient_IParameters.hxx" #include #include CORBA_SERVER_HEADER(SALOME_Exception) @@ -89,15 +79,15 @@ _PTR(Study) SalomeApp_Study::studyDS() const /*! 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 ); @@ -105,8 +95,10 @@ void SalomeApp_Study::createDocument() // create myRoot setRoot( new LightApp_RootObject( this ) ); - CAM_Study::createDocument(); + bool aRet = CAM_Study::createDocument( theStr ); emit created( this ); + + return aRet; } /*! @@ -118,7 +110,7 @@ bool SalomeApp_Study::openDocument( const QString& theFileName ) 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; @@ -129,8 +121,9 @@ bool SalomeApp_Study::openDocument( const QString& theFileName ) // 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 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 @@ -161,7 +154,7 @@ bool SalomeApp_Study::loadDocument( const QString& theStudyName ) 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; @@ -175,8 +168,9 @@ bool SalomeApp_Study::loadDocument( const QString& theStudyName ) ModelList dm_s; dataModels( dm_s ); - for ( ModelListIterator it( dm_s ); it.current(); ++it ) - openDataModel( studyName(), it.current() ); + QListIterator 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 @@ -210,13 +204,15 @@ bool SalomeApp_Study::saveDocumentAs( const QString& theFileName ) ModelList list; dataModels( list ); - SalomeApp_DataModel* aModel = (SalomeApp_DataModel*)list.first(); + QListIterator 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 @@ -227,8 +223,8 @@ bool SalomeApp_Study::saveDocumentAs( const QString& theFileName ) 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); @@ -250,13 +246,15 @@ bool SalomeApp_Study::saveDocument() ModelList list; dataModels( list ); - SalomeApp_DataModel* aModel = (SalomeApp_DataModel*)list.first(); + QListIterator 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 @@ -336,10 +334,10 @@ void SalomeApp_Study::saveModuleData( QString theModuleName, QStringList theList 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); } /*! @@ -349,7 +347,7 @@ void SalomeApp_Study::saveModuleData( QString theModuleName, QStringList theList */ void SalomeApp_Study::openModuleData( QString theModuleName, QStringList& theListOfFiles ) { - std::vector aListOfFiles = GetListOfFiles( theModuleName ); + std::vector aListOfFiles = GetListOfFiles( theModuleName.toStdString().c_str() ); int i, aLength = aListOfFiles.size() - 1; if ( aLength < 0 ) @@ -368,10 +366,11 @@ void SalomeApp_Study::openModuleData( QString theModuleName, QStringList& theLis bool SalomeApp_Study::saveStudyData( const QString& theFileName ) { ModelList list; dataModels( list ); - SalomeApp_DataModel* aModel = (SalomeApp_DataModel*)list.first(); + QListIterator it( list ); std::vector 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; } @@ -396,7 +395,7 @@ void SalomeApp_Study::setStudyDS( const _PTR(Study)& s ) */ 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); @@ -415,20 +414,20 @@ void SalomeApp_Study::addComponent(const CAM_DataModel* 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 ); } @@ -451,7 +450,7 @@ bool SalomeApp_Study::openDataModel( const QString& studyName, CAM_DataModel* dm // 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( dm ); @@ -462,14 +461,14 @@ bool SalomeApp_Study::openDataModel( const QString& studyName, CAM_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 @@ -489,7 +488,7 @@ bool SalomeApp_Study::openDataModel( const QString& studyName, CAM_DataModel* dm // 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( dm ); @@ -511,7 +510,7 @@ QString SalomeApp_Study::newStudyName() const 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 ) @@ -606,7 +605,7 @@ void SalomeApp_Study::deleteReferencesTo( _PTR( SObject ) obj ) */ 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 ) ) @@ -619,7 +618,7 @@ QString SalomeApp_Study::referencedToEntry( const QString& entry ) const */ 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(); @@ -630,7 +629,7 @@ QString SalomeApp_Study::componentDataType( const QString& entry ) const */ 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(); } @@ -639,7 +638,7 @@ bool SalomeApp_Study::isComponent( const QString& entry ) const */ 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() ) @@ -716,7 +715,7 @@ void SalomeApp_Study::setNameOfSavePoint(int savePoint, const QString& nameOfSav { _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()); } /*! diff --git a/src/SalomeApp/SalomeApp_Study.h b/src/SalomeApp/SalomeApp_Study.h index ef5c127fd..8de53b5f8 100644 --- a/src/SalomeApp/SalomeApp_Study.h +++ b/src/SalomeApp/SalomeApp_Study.h @@ -22,7 +22,6 @@ #include "SalomeApp.h" #include -#include #ifdef WIN32 #pragma warning( disable:4251 ) @@ -40,7 +39,7 @@ public: virtual int id() const; - virtual void createDocument(); + virtual bool createDocument( const QString& ); virtual bool openDocument( const QString& ); virtual bool loadDocument( const QString& ); diff --git a/src/SalomeApp/SalomeApp_StudyPropertiesDlg.cxx b/src/SalomeApp/SalomeApp_StudyPropertiesDlg.cxx index 830536676..8567371be 100644 --- a/src/SalomeApp/SalomeApp_StudyPropertiesDlg.cxx +++ b/src/SalomeApp/SalomeApp_StudyPropertiesDlg.cxx @@ -31,17 +31,13 @@ #include #include -// OCCT Includes -#include -#include - // CORBA Headers #include #include CORBA_CLIENT_HEADER(SALOMEDS_Attributes) // QT Includes -#include -#include +#include +#include using namespace std; @@ -59,7 +55,7 @@ public: const QString theName, const bool theEditable, const int theUserType) : - SalomeApp_ListViewItem( parent, theName, theEditable ) + SalomeApp_ListViewItem( parent, QStringList(theName), theEditable ) { setUserType(theUserType); } @@ -141,24 +137,29 @@ public: /*!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::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); @@ -290,26 +291,25 @@ void SalomeApp_StudyPropertiesDlg::onOK() _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: { @@ -323,6 +323,7 @@ void SalomeApp_StudyPropertiesDlg::onOK() default: break; } + ++it; } } accept(); @@ -336,18 +337,19 @@ bool SalomeApp_StudyPropertiesDlg::propChanged() { _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; @@ -362,6 +364,7 @@ bool SalomeApp_StudyPropertiesDlg::propChanged() default: break; } + ++it; } } return false; diff --git a/src/SalomeApp/SalomeApp_StudyPropertiesDlg.h b/src/SalomeApp/SalomeApp_StudyPropertiesDlg.h index 4abedf932..6991488fe 100644 --- a/src/SalomeApp/SalomeApp_StudyPropertiesDlg.h +++ b/src/SalomeApp/SalomeApp_StudyPropertiesDlg.h @@ -24,11 +24,8 @@ #define SALOMEAPP_STUDY_PROPERTIES_DLG_H #include "SalomeApp.h" -#include -#include -#include -#include -#include + +#include #include #include CORBA_SERVER_HEADER(SALOMEDS) @@ -37,7 +34,6 @@ class SalomeApp_ListView; class QPushButton; -class QToolButton; class SALOMEAPP_EXPORT SalomeApp_StudyPropertiesDlg : public QDialog { diff --git a/src/SalomeApp/SalomeApp_Tools.cxx b/src/SalomeApp/SalomeApp_Tools.cxx index a20fbf0c8..893629e9d 100644 --- a/src/SalomeApp/SalomeApp_Tools.cxx +++ b/src/SalomeApp/SalomeApp_Tools.cxx @@ -24,6 +24,11 @@ #include +#include +#include + +#include + /*! Convert QColor to Quantity_Color, if QColor is valid. */ @@ -111,10 +116,10 @@ void SalomeApp_Tools::QtCatchCorbaException( const SALOME::SALOME_Exception& S_e } 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 ); } diff --git a/src/SalomeApp/SalomeApp_Tools.h b/src/SalomeApp/SalomeApp_Tools.h index a6f1e06dc..c288ef12f 100644 --- a/src/SalomeApp/SalomeApp_Tools.h +++ b/src/SalomeApp/SalomeApp_Tools.h @@ -23,10 +23,10 @@ #include -#include -#include +class QColor; +class QString; -#include +class Quantity_Color; #include #include CORBA_CLIENT_HEADER(SALOME_Exception) diff --git a/src/SalomeApp/SalomeApp_TypeFilter.cxx b/src/SalomeApp/SalomeApp_TypeFilter.cxx index c82912207..2a8d2fb8a 100644 --- a/src/SalomeApp/SalomeApp_TypeFilter.cxx +++ b/src/SalomeApp/SalomeApp_TypeFilter.cxx @@ -50,11 +50,11 @@ bool SalomeApp_TypeFilter::isOk( const SUIT_DataOwner* sOwner ) const _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; } } diff --git a/src/SalomeApp/SalomeApp_TypeFilter.h b/src/SalomeApp/SalomeApp_TypeFilter.h index 533ea7269..fa18adf95 100644 --- a/src/SalomeApp/SalomeApp_TypeFilter.h +++ b/src/SalomeApp/SalomeApp_TypeFilter.h @@ -19,7 +19,7 @@ #ifndef SALOMEAPP_TYPEFILTER_H #define SALOMEAPP_TYPEFILTER_H -#include +#include #include "SalomeApp_Filter.h" diff --git a/src/SalomeApp/SalomeApp_VisualState.cxx b/src/SalomeApp/SalomeApp_VisualState.cxx index dab9a907e..a5af64fdd 100644 --- a/src/SalomeApp/SalomeApp_VisualState.cxx +++ b/src/SalomeApp/SalomeApp_VisualState.cxx @@ -22,20 +22,22 @@ #include "SalomeApp_Study.h" #include "SalomeApp_Application.h" -#include +//#include +#include +#include #include #include -#include -#include -#include +#include +#include +#include -#include -#include +#include //? +#include //? -#include -#include +#include //? +#include //? /*! Constructor. @@ -64,28 +66,33 @@ SalomeApp_VisualState::~SalomeApp_VisualState() */ void nameViewWindows( const ViewManagerList& lst ) { - QDict viewersCounter; // map viewerType - to - index_of_this_viewer_type - viewersCounter.setAutoDelete( true ); - for ( QPtrListIterator it(lst); it.current(); ++it) { - int view_count = it.current()->getViewsCount(); - QString vType = it.current()->getType(); + QMultiHash viewersCounter; // map viewerType - to - index_of_this_viewer_type + QListIterator 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 views = it.current()->getViews(); + QVector 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(); } /*! @@ -117,23 +124,26 @@ int SalomeApp_VisualState::storeState() // 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 it( lst ); it.current(); ++it ) { - vm = it.current(); + QListIterator 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 views = vm->getViews(); + QVector views = vm->getViews(); for(int i = 0; iappend( 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() ); } } @@ -142,20 +152,24 @@ int SalomeApp_VisualState::storeState() 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 mlist; + QList mlist; myApp->modules( mlist ); + QListIterator 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( module ) ) { - ip->append( "AP_MODULES_LIST", sModule->moduleName().latin1() ); + ip->append( "AP_MODULES_LIST", sModule->moduleName().toStdString() ); sModule->storeVisualParameters( savePoint ); } } @@ -181,8 +195,9 @@ void SalomeApp_VisualState::restoreState(int savePoint) //Remove all already existent veiwers and their views ViewManagerList lst; myApp->viewManagers( lst ); - for ( QPtrListIterator it(lst); it.current(); ++it ) { - myApp->removeViewManager( it.current() ); + QListIterator it(lst); + while ( it.hasNext() ) { + myApp->removeViewManager( it.next() ); qApp->processEvents(); } //Restore the viewers and view windows @@ -216,7 +231,7 @@ void SalomeApp_VisualState::restoreState(int savePoint) } //Resize the views, set their captions and apply visual parameters. - QPtrVector views = vm->getViews(); + QVector views = vm->getViews(); for (int i = 0, j = 0; iisVisible() ) 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(); @@ -246,14 +261,18 @@ void SalomeApp_VisualState::restoreState(int savePoint) // so here we store their visual parameters for later restoring.. lst.clear(); myApp->viewManagers(lst); - QPtrListIterator it( lst ); - for ( ; it.current(); ++it ) { - int view_count = it.current()->getViewsCount(); - QPtrVector views = it.current()->getViews(); + QListIterator itVM( lst ); + SUIT_ViewManager* aVM = 0; + while ( itVM.hasNext() ) { + aVM = itVM.next(); + if ( !aVM ) continue; + + int view_count = aVM->getViewsCount(); + QVector 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() ); } } } @@ -280,8 +299,8 @@ void SalomeApp_VisualState::restoreState(int savePoint) std::string activeViewName = ip->getProperty("AP_ACTIVE_VIEW"); QMap::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(); } diff --git a/src/SalomeApp/resources/SalomeApp_images.ts b/src/SalomeApp/resources/SalomeApp_images.ts new file mode 100644 index 000000000..4eb9e1878 --- /dev/null +++ b/src/SalomeApp/resources/SalomeApp_images.ts @@ -0,0 +1,2 @@ + + diff --git a/src/SalomeApp/resources/SalomeApp_msg_en.po b/src/SalomeApp/resources/SalomeApp_msg_en.po index f6db22171..445306db7 100644 --- a/src/SalomeApp/resources/SalomeApp_msg_en.po +++ b/src/SalomeApp/resources/SalomeApp_msg_en.po @@ -246,3 +246,24 @@ msgstr "Rename" 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" + diff --git a/src/SalomeApp/resources/SalomeApp_msg_en.ts b/src/SalomeApp/resources/SalomeApp_msg_en.ts new file mode 100644 index 000000000..86d8d5598 --- /dev/null +++ b/src/SalomeApp/resources/SalomeApp_msg_en.ts @@ -0,0 +1,280 @@ + + + @default + + CLOSE_LOCKED_STUDY + Close locked study? + + + PUBLISH_IN_STUDY + Publish in study + + + BUT_NEW + &New + + + SAVE_POINT_ROOT_NAME + GUI states + + + SAVE_POINT_ROOT_TOOLTIP + Persistent GUI states + + + SAVE_GUI_STATE + Save GUI state + + + BUT_LOAD + &Load + + + BUT_OPEN + &Open + + + SAVE_POINT_OBJECT_TOOLTIP + Saved GUI state: %1 + + + SAVE_POINT_DEF_NAME + GUI state: + + + + SalomeApp_Application + + ALL_FILES_FILTER + All files (*.*) + + + MEN_WINDOWS_NEW + New window + + + MEN_DELETE_INVALID_REFERENCE + Delete Invalid Reference + + + TOT_FILE_DESK_PREFERENCES + Preferences + + + MEN_DELETE_VS + Delete + + + MEN_OPENWITH + Activate %1 Module + + + MEN_DESK_REGISTRY_DISPLAY + Registry &display + + + TOT_DESK_FILE_LOAD_SCRIPT + Load python script + + + PREF_STORE_VISUAL_STATE + Store/restore last GUI state + + + PRP_DESK_FILE_SAVE_GUI_STATE + Saves current state of viewers, displayed objects, etc. + + + MEN_DESK_FILE_SAVE_GUI_STATE + Save GUI state + + + TOT_DESK_FILE_SAVE_GUI_STATE + Save GUI state + + + MEN_RESTORE_VS + Restore + + + WRN_DUMP_STUDY_FAILED + Dump study failed + + + MEN_DESK_PROPERTIES + Pro&perties... + + + QUE_DOC_ALREADYEXIST + The document %1 already exists in study manager. +Do you want to reload it ? + + + MEN_RENAME_VS + Rename + + + TOT_DESK_CATALOG_GENERATOR + Catalog generator + + + PUBLISH_IN_STUDY + Publish in study + + + PREF_OBJ_BROWSER_SETTINGS + Settings + + + PRP_DESK_REGISTRY_DISPLAY + Displays content of the Registry CORBA server + + + PYTHON_FILES_FILTER + PYTHON Files (*.py) + + + PRP_DESK_PROPERTIES + Edits study properties + + + PREF_TAB_OBJBROWSER + Object browser + + + STUDY_LOCKED + LOCKED + + + OBJ_BROWSER_NAME + Object + + + TOT_DESK_REGISTRY_DISPLAY + Registry display + + + OBJ_BROWSER_COLUMN_0 + Value + + + OBJ_BROWSER_COLUMN_1 + Entry + + + OBJ_BROWSER_COLUMN_2 + IOR + + + OBJ_BROWSER_COLUMN_3 + Reference entry + + + PREF_CATEGORY_SALOME + SALOME + + + PYTHON_CONSOLE + Python Console + + + MEN_DESK_FILE_LOAD_SCRIPT + Load scrip&t... + + + MEN_DESK_TOOLS + &Tools + + + TOT_DESK_FILE_DUMP_STUDY + Dump study + + + MEN_VIEW_WNDS + Windows + + + MEN_DESK_FILE_DUMP_STUDY + &Dump study... + + + PRP_DESK_CATALOG_GENERATOR + Generates XML catalog of a component's interface + + + PRP_DESK_FILE_DUMP_STUDY + Dumps study to the python script + + + TOT_DESK_PROPERTIES + Study properties + + + PREF_GROUP_DEF_COLUMNS + Default columns + + + PRP_DESK_FILE_LOAD_SCRIPT + Loads python script from file + + + MEN_DESK_CATALOG_GENERATOR + Catalog &generator + + + MEN_DESK_MRU + Most recently used + + + TOT_DESK_MRU + Most recently used + + + + SalomeApp_StudyPropertiesDlg + + PRP_MODE_FROM_SCRATCH + from scratch + + + PRP_AUTHOR + Author + + + PRP_LOCKED + Locked + + + PRP_MODIFICATIONS + Modifications + + + PRP_NO + No + + + PRP_YES + Yes + + + PRP_MODIFIED + Modified + + + PRP_DATE + Created + + + PRP_MODE + Mode + + + PRP_MODE_FROM_COPYFROM + copy from + + + TLT_STUDY_PROPERTIES + Study Properties + + + diff --git a/src/Session/InquireServersQThread.cxx b/src/Session/InquireServersQThread.cxx index 61fdc3eff..b72253e1d 100755 --- a/src/Session/InquireServersQThread.cxx +++ b/src/Session/InquireServersQThread.cxx @@ -35,13 +35,7 @@ #include #include #include - -//VRV: porting on Qt 3.0.5 -#if QT_VERSION >= 0x030005 #include -#endif -//VRV: porting on Qt 3.0.5 - #include #include @@ -137,12 +131,7 @@ InquireServersGUI::InquireServersGUI() 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 @@ -371,14 +360,14 @@ bool InquireServersQThread::AskServer(int iteration, QString ** errMessage) //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--) diff --git a/src/Session/SALOME_Session.hxx b/src/Session/SALOME_Session.hxx index 78c89d6d3..22bb8ffa2 100755 --- a/src/Session/SALOME_Session.hxx +++ b/src/Session/SALOME_Session.hxx @@ -26,22 +26,14 @@ #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 diff --git a/src/Session/SALOME_Session_Server.cxx b/src/Session/SALOME_Session_Server.cxx index 8ae6b7d2f..acfb2ebfb 100755 --- a/src/Session/SALOME_Session_Server.cxx +++ b/src/Session/SALOME_Session_Server.cxx @@ -29,29 +29,23 @@ #include "Utils_ORB_INIT.hxx" #include "Utils_SINGLETON.hxx" #include "SALOME_NamingService.hxx" -#include "SALOMETraceCollector.hxx" -#include -#ifndef WNT -#include -#endif - -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #include "Utils_SALOME_Exception.hxx" #include "Utils_CorbaException.hxx" -#include "SALOME_Event.hxx" +#include "SALOME_Event.h" #include #include CORBA_SERVER_HEADER(SALOME_Session) #include CORBA_SERVER_HEADER(SALOMEDS) #include -#include "Session_Session_i.hxx" #include "Session_ServerLauncher.hxx" #include "Session_ServerCheck.hxx" @@ -60,7 +54,6 @@ #include "SUIT_Session.h" #include "SUIT_Application.h" #include "SUIT_Desktop.h" -#include "SUIT_MessageBox.h" #include "SUIT_ResourceMgr.h" #include "SUIT_ExceptionHandler.h" @@ -131,11 +124,11 @@ QString salomeVersion() 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() ) @@ -145,9 +138,9 @@ QString salomeVersion() 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; } @@ -168,8 +161,8 @@ public: 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" ) { @@ -196,15 +189,15 @@ protected: 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; @@ -344,7 +337,7 @@ int main( int argc, char **argv ) 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] ); @@ -355,12 +348,12 @@ int main( int argc, char **argv ) } // ...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 diff --git a/src/Session/SalomeApp_Engine_i.cxx b/src/Session/SalomeApp_Engine_i.cxx index 813270515..855cb8cf7 100644 --- a/src/Session/SalomeApp_Engine_i.cxx +++ b/src/Session/SalomeApp_Engine_i.cxx @@ -30,8 +30,6 @@ #include "SALOMEDS_Tool.hxx" -#include "utilities.h" - #include using namespace std; diff --git a/src/Session/Session.pro b/src/Session/Session.pro new file mode 100644 index 000000000..812c9c5ee --- /dev/null +++ b/src/Session/Session.pro @@ -0,0 +1,85 @@ +#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 + + diff --git a/src/Session/Session_ServerCheck.cxx b/src/Session/Session_ServerCheck.cxx index 3642f0407..887751279 100644 --- a/src/Session/Session_ServerCheck.cxx +++ b/src/Session/Session_ServerCheck.cxx @@ -32,8 +32,12 @@ #include "Utils_ORB_INIT.hxx" #include "Utils_SINGLETON.hxx" #include "SALOME_NamingService.hxx" -#include "utilities.h" #include "OpUtil.hxx" +#include "utilities.h" + +#include +#include +#include // Default settings const int __DEFAULT__ATTEMPTS__ = 300; // number of checks attemtps @@ -363,10 +367,10 @@ void Session_ServerCheck::run() ASSERT( SINGLETON_::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; @@ -414,10 +418,10 @@ void Session_ServerCheck::run() ASSERT( SINGLETON_::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; @@ -465,10 +469,10 @@ void Session_ServerCheck::run() ASSERT( SINGLETON_::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; @@ -504,6 +508,5 @@ void Session_ServerCheck::run() QThread::usleep( 30000 ); } // clear splash status - splash->setProgress( 0, 0 ); splash->setStatus( initialInfo ); } diff --git a/src/Session/Session_ServerCheck.hxx b/src/Session/Session_ServerCheck.hxx index 8de6a6d41..9a65f436c 100644 --- a/src/Session/Session_ServerCheck.hxx +++ b/src/Session/Session_ServerCheck.hxx @@ -24,8 +24,7 @@ #include -#include -#include +#include class QMutex; class QWaitCondition; diff --git a/src/Session/Session_ServerLauncher.cxx b/src/Session/Session_ServerLauncher.cxx index 3909efc01..bdf10d747 100755 --- a/src/Session/Session_ServerLauncher.cxx +++ b/src/Session/Session_ServerLauncher.cxx @@ -27,9 +27,14 @@ // $Header$ #include "Session_ServerLauncher.hxx" +#include "Session_ServerThread.hxx" #include "Utils_SALOME_Exception.hxx" #include "utilities.h" + +#include +#include + using namespace std; /*! default constructor not for use diff --git a/src/Session/Session_ServerLauncher.hxx b/src/Session/Session_ServerLauncher.hxx index b3773adf1..6f0fede88 100755 --- a/src/Session/Session_ServerLauncher.hxx +++ b/src/Session/Session_ServerLauncher.hxx @@ -31,14 +31,11 @@ #include -#include "Session_ServerThread.hxx" - #include #include #include #include -#include -#include +#include using namespace std; @@ -55,6 +52,11 @@ inline ServArg::ServArg(int servType, int firstArg, int lastArg): _servType(servType),_firstArg(firstArg),_lastArg(lastArg) {} +class Session_ServerThread; + +class QMutex; +class QWaitCondition; + class SESSION_EXPORT Session_ServerLauncher: public QThread { public: diff --git a/src/Session/Session_ServerThread.cxx b/src/Session/Session_ServerThread.cxx index 9c6f7c838..5bf7be156 100755 --- a/src/Session/Session_ServerThread.cxx +++ b/src/Session/Session_ServerThread.cxx @@ -32,9 +32,9 @@ #include "Session_ServerThread.hxx" +#include "SALOME_NamingService.hxx" #include "SALOME_Container_i.hxx" #include "SALOME_ContainerManager.hxx" -#include #include #include "SALOME_ModuleCatalog_impl.hxx" #include "RegistryService.hxx" @@ -51,6 +51,9 @@ #include #include +#include +#include + using namespace std; const int Session_ServerThread::NB_SRV_TYP = 7; @@ -113,7 +116,7 @@ void Session_ServerThread::Init() 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 #include -#include "SALOME_NamingService.hxx" -#include - using namespace std; void WaitForServerReadiness(string serverName); +class SALOME_NamingService; class SESSION_EXPORT Session_ServerThread { @@ -72,6 +70,8 @@ protected: SALOME_NamingService * _NS; }; +class QMutex; +class QWaitCondition; class SESSION_EXPORT Session_SessionThread : public Session_ServerThread { diff --git a/src/Session/Session_Session_i.cxx b/src/Session/Session_Session_i.cxx index 81787737e..92ba94c40 100755 --- a/src/Session/Session_Session_i.cxx +++ b/src/Session/Session_Session_i.cxx @@ -31,17 +31,19 @@ #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 +//#include +#include +#include // Open CASCADE Includes #include -#include #include using namespace std; @@ -155,12 +157,12 @@ void SALOME_Session_i::StopSession() 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() @@ -170,7 +172,7 @@ 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(); diff --git a/src/Session/Session_Session_i.hxx b/src/Session/Session_Session_i.hxx index bfdee09a5..fa7a224e4 100755 --- a/src/Session/Session_Session_i.hxx +++ b/src/Session/Session_Session_i.hxx @@ -31,13 +31,14 @@ #include -#include - #include #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 { diff --git a/src/TOOLSGUI/Makefile.am b/src/TOOLSGUI/Makefile.am index e3081448e..de89c7e57 100755 --- a/src/TOOLSGUI/Makefile.am +++ b/src/TOOLSGUI/Makefile.am @@ -37,18 +37,14 @@ salomeinclude_HEADERS= \ 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) diff --git a/src/TOOLSGUI/TOOLSGUI.pro b/src/TOOLSGUI/TOOLSGUI.pro new file mode 100644 index 000000000..361da544d --- /dev/null +++ b/src/TOOLSGUI/TOOLSGUI.pro @@ -0,0 +1,48 @@ +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 diff --git a/src/TOOLSGUI/ToolsGUI.cxx b/src/TOOLSGUI/ToolsGUI.cxx index 25b8aeee9..290eb6603 100755 --- a/src/TOOLSGUI/ToolsGUI.cxx +++ b/src/TOOLSGUI/ToolsGUI.cxx @@ -19,17 +19,23 @@ // // 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, @@ -46,11 +52,11 @@ bool ToolsGUI::GetVisibility( _PTR(Study) theStudy, } /*! - 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, diff --git a/src/TOOLSGUI/ToolsGUI.h b/src/TOOLSGUI/ToolsGUI.h index ceb117928..522c195d2 100755 --- a/src/TOOLSGUI/ToolsGUI.h +++ b/src/TOOLSGUI/ToolsGUI.h @@ -19,25 +19,27 @@ // // 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 -#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, @@ -49,4 +51,4 @@ public : void* theId ); }; -#endif +#endif // TOOLSGUI_H diff --git a/src/TOOLSGUI/ToolsGUI_CatalogGeneratorDlg.cxx b/src/TOOLSGUI/ToolsGUI_CatalogGeneratorDlg.cxx index 5cf6f399e..cbc92ed5b 100755 --- a/src/TOOLSGUI/ToolsGUI_CatalogGeneratorDlg.cxx +++ b/src/TOOLSGUI/ToolsGUI_CatalogGeneratorDlg.cxx @@ -19,32 +19,28 @@ // // 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 -#include -#include -#include -#include -#include -#include -#include -#include -#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -60,39 +56,47 @@ using namespace std; #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); @@ -104,50 +108,56 @@ ToolsGUI_CatalogGeneratorDlg::ToolsGUI_CatalogGeneratorDlg( QWidget* parent, con 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"); @@ -167,18 +177,19 @@ ToolsGUI_CatalogGeneratorDlg::ToolsGUI_CatalogGeneratorDlg( QWidget* parent, con 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 ); @@ -202,85 +213,95 @@ ToolsGUI_CatalogGeneratorDlg::ToolsGUI_CatalogGeneratorDlg( QWidget* parent, con } /*! - 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() @@ -315,7 +336,7 @@ QString ToolsGUI_CatalogGeneratorDlg::getIdlPath() } /*! - SLOT: called on Browse button click + \brief Called when user presses "Browse" button */ void ToolsGUI_CatalogGeneratorDlg::onBrowseBtnClicked() { @@ -324,18 +345,18 @@ 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); @@ -345,16 +366,18 @@ void ToolsGUI_CatalogGeneratorDlg::onBrowseBtnClicked() } /*! - Updates button's state + \brief Update 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() ); } /*! - button slot, performs IDL->XML conversion + \brief Called when user presses button + + Performs IDL to XML file conversion using \c runIDLparser SALOME utility. */ void ToolsGUI_CatalogGeneratorDlg::onApply() { @@ -371,26 +394,24 @@ 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()); } @@ -399,9 +420,9 @@ void ToolsGUI_CatalogGeneratorDlg::onApply() 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) { diff --git a/src/TOOLSGUI/ToolsGUI_CatalogGeneratorDlg.h b/src/TOOLSGUI/ToolsGUI_CatalogGeneratorDlg.h index 9169f0dde..0626abd9f 100755 --- a/src/TOOLSGUI/ToolsGUI_CatalogGeneratorDlg.h +++ b/src/TOOLSGUI/ToolsGUI_CatalogGeneratorDlg.h @@ -19,29 +19,26 @@ // // 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 +#include "ToolsGUI.h" -#include +#include 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(); @@ -78,4 +75,4 @@ private: QPushButton* myCloseBtn; }; -#endif // DIALOGBOX_TOOLSGUI_CATALOGGENERATORDLG_H +#endif // TOOLSGUI_CATALOGGENERATORDLG_H diff --git a/src/TOOLSGUI/ToolsGUI_HelpWindow.cxx b/src/TOOLSGUI/ToolsGUI_HelpWindow.cxx deleted file mode 100755 index 4581ab882..000000000 --- a/src/TOOLSGUI/ToolsGUI_HelpWindow.cxx +++ /dev/null @@ -1,105 +0,0 @@ -// 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 -# include -# include -# include - -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 ); -} - - diff --git a/src/TOOLSGUI/ToolsGUI_HelpWindow.h b/src/TOOLSGUI/ToolsGUI_HelpWindow.h deleted file mode 100755 index b4849baf0..000000000 --- a/src/TOOLSGUI/ToolsGUI_HelpWindow.h +++ /dev/null @@ -1,53 +0,0 @@ -// 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 -# include - -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__ */ - - diff --git a/src/TOOLSGUI/ToolsGUI_IntervalWindow.cxx b/src/TOOLSGUI/ToolsGUI_IntervalWindow.cxx deleted file mode 100755 index 7d4fcb0da..000000000 --- a/src/TOOLSGUI/ToolsGUI_IntervalWindow.cxx +++ /dev/null @@ -1,127 +0,0 @@ -// 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 -#include -#include -#include -# 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; -} diff --git a/src/TOOLSGUI/ToolsGUI_IntervalWindow.h b/src/TOOLSGUI/ToolsGUI_IntervalWindow.h deleted file mode 100755 index 242373657..000000000 --- a/src/TOOLSGUI/ToolsGUI_IntervalWindow.h +++ /dev/null @@ -1,55 +0,0 @@ -// 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 -# include -# include -# include - -#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 diff --git a/src/TOOLSGUI/ToolsGUI_RegWidget.cxx b/src/TOOLSGUI/ToolsGUI_RegWidget.cxx index d9c62a9bf..1cef542cd 100755 --- a/src/TOOLSGUI/ToolsGUI_RegWidget.cxx +++ b/src/TOOLSGUI/ToolsGUI_RegWidget.cxx @@ -19,45 +19,172 @@ // // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com // -// -// // File : ToolsGUI_RegWidget.cxx // Author : Pascale NOYRET, EDF -// Module : SALOME -// $Header$ - -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include - -# 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 +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include + +# include +# include +# include +# include -using namespace std; +# include +# include + +# include 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( "" ) + QString( text ) + QString( "" ) ) @@ -136,10 +263,12 @@ static const char* const refresh_data[] = { "......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" ; @@ -171,37 +300,337 @@ Registry::Components_var MakeRegistry( CORBA::ORB_var &orb ) } /*! - 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 ); @@ -210,14 +639,12 @@ ToolsGUI_RegWidget::ToolsGUI_RegWidget(CORBA::ORB_var &orb, QWidget *parent, con // 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 ); @@ -225,31 +652,28 @@ ToolsGUI_RegWidget::ToolsGUI_RegWidget(CORBA::ORB_var &orb, QWidget *parent, con 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) @@ -263,22 +687,24 @@ ToolsGUI_RegWidget::ToolsGUI_RegWidget(CORBA::ORB_var &orb, QWidget *parent, con 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 ) { @@ -294,13 +720,13 @@ 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() ); } } @@ -309,35 +735,39 @@ bool ToolsGUI_RegWidget::eventFilter( QObject* object, QEvent* event ) } /*! - 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; ilength(); 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; ilength(); 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( "

    " ) + tr( "Code" ) + QString( " : " ); a.append( QString( c_info.name ) ); @@ -368,53 +798,48 @@ QString ToolsGUI_RegWidget::setlongText( const Registry::Infos &c_info) delete [] t1; a.append( "
    " ); - 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( "
    " ); - 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( "
    " ); - delete [] t3; - } - else - { - a.append( tr( "still running" ) + QString( "
    " ) ); - } + 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( "
    " ); + 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( "
    " ); + delete [] t3; + } + else { + a.append( tr( "still running" ) + QString( "
    " ) ); + } 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( ")
    " ) ); - } + 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( ")
    " ) ); + } a.append( "" ); // ASV: 28.07.06 : added 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 ) @@ -422,202 +847,173 @@ void ToolsGUI_RegWidget::closeEvent( QCloseEvent *e) 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 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 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 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 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; @@ -625,7 +1021,7 @@ void ToolsGUI_RegWidget::slotClientChanged( QListViewItem* item ) 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()) ; @@ -633,30 +1029,25 @@ void ToolsGUI_RegWidget::slotClientChanged( QListViewItem* item ) 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 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; @@ -665,158 +1056,23 @@ void ToolsGUI_RegWidget::slotHistoryChanged( QListViewItem* item ) 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 ); -} diff --git a/src/TOOLSGUI/ToolsGUI_RegWidget.h b/src/TOOLSGUI/ToolsGUI_RegWidget.h index be40bc8a2..00ba8c8d5 100755 --- a/src/TOOLSGUI/ToolsGUI_RegWidget.h +++ b/src/TOOLSGUI/ToolsGUI_RegWidget.h @@ -19,101 +19,87 @@ // // 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 -#include +#include #include #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 - -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 diff --git a/src/TOOLSGUI/resources/ToolsGUI_icons.ts b/src/TOOLSGUI/resources/ToolsGUI_icons.ts new file mode 100644 index 000000000..b1710f331 --- /dev/null +++ b/src/TOOLSGUI/resources/ToolsGUI_icons.ts @@ -0,0 +1,9 @@ + + + ToolsGUI_CatalogGeneratorDlg + + ICON_SELECT + select1.png + + + diff --git a/src/TOOLSGUI/resources/ToolsGUI_msg_en.ts b/src/TOOLSGUI/resources/ToolsGUI_msg_en.ts new file mode 100644 index 000000000..9e4a28dca --- /dev/null +++ b/src/TOOLSGUI/resources/ToolsGUI_msg_en.ts @@ -0,0 +1,105 @@ + + + @default + + TOOLS_WRN_WARNING + Warning + + + TOOLS_BUT_BROWSE + Browse... + + + TOOLS_ERR_ERROR + Error + + + TOOLS_ERR_FILE_NOT_EXIST + %1 +File doesn't exist + + + TOOLS_BUT_OK + &Ok + + + TOOLS_BUT_APPLY + &Apply + + + TOOLS_BUT_CLOSE + &Close + + + + ToolsGUI_CatalogGeneratorDlg + + TOOLS_MEN_EXPORT + Export + + + TOOLS_MEN_IMPORT + Import + + + TOOLS_VERSION + Version : + + + TOOLS_COMP_NAME + Name : + + + TOOLS_COMP_TYPE + Type : + + + TOOLS_XML_FILE + XML : + + + TOOLS_PNG_FILE + Icon : + + + TOOLS_SUPPLEMENT + Component supplementary data + + + TOOLS_AUTHOR + Author : + + + TOOLS_COMP_MULTISTD + Multistudy : + + + TOOLS_COMP_USERNAME + UserName : + + + TOOLS_CATALOG_GENERATOR + Catalog generator + + + TOOLS_FILES + Files + + + TOOLS_MEN_IMPORT_PNG + PNG Files ( *.png ) + + + TOOLS_MEN_IMPORT_IDL + IDL Files ( *.idl ) + + + TOOLS_MEN_EXPORT_XML + XML Files ( *.xml ) + + + TOOLS_IDL_FILE + IDL : + + + diff --git a/src/VTKViewer/VTKViewer.h b/src/VTKViewer/VTKViewer.h index 77de94830..c17912df9 100755 --- a/src/VTKViewer/VTKViewer.h +++ b/src/VTKViewer/VTKViewer.h @@ -20,7 +20,7 @@ #ifndef VTKVIEWER_H #define VTKVIEWER_H -#ifdef WNT +#ifdef WIN32 # ifdef VTKVIEWER_EXPORTS # define VTKVIEWER_EXPORT __declspec( dllexport ) # else diff --git a/src/VTKViewer/VTKViewer.pro b/src/VTKViewer/VTKViewer.pro new file mode 100644 index 000000000..7070bacee --- /dev/null +++ b/src/VTKViewer/VTKViewer.pro @@ -0,0 +1,78 @@ +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 diff --git a/src/VTKViewer/VTKViewer_ConvexTool.cxx b/src/VTKViewer/VTKViewer_ConvexTool.cxx index 1ecabea6e..9dfa3b47f 100644 --- a/src/VTKViewer/VTKViewer_ConvexTool.cxx +++ b/src/VTKViewer/VTKViewer_ConvexTool.cxx @@ -32,7 +32,7 @@ #include #include -#ifdef WNT +#ifdef WIN32 #include #endif diff --git a/src/VTKViewer/VTKViewer_InteractorStyle.cxx b/src/VTKViewer/VTKViewer_InteractorStyle.cxx index 6bc13e78e..f5c387693 100644 --- a/src/VTKViewer/VTKViewer_InteractorStyle.cxx +++ b/src/VTKViewer/VTKViewer_InteractorStyle.cxx @@ -50,12 +50,9 @@ #include #include -#include -//VRV: porting on Qt 3.0.5 -#if QT_VERSION >= 0x030005 -#include -#endif -//VRV: porting on Qt 3.0.5 +#include +#include + #include //#include "utilities.h" @@ -103,6 +100,8 @@ VTKViewer_InteractorStyle::VTKViewer_InteractorStyle() myPreSelectionActor->GetProperty()->SetLineWidth(5); myPreSelectionActor->GetProperty()->SetPointSize(5); + myRectBand = 0; + OnSelectionModeChanged(); } @@ -111,6 +110,7 @@ VTKViewer_InteractorStyle::VTKViewer_InteractorStyle() VTKViewer_InteractorStyle::~VTKViewer_InteractorStyle() { m_ViewWnd->RemoveActor(myPreSelectionActor); + endDrawRect(); } @@ -522,13 +522,13 @@ const char* imageRotateCursor[] = { /*! 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; } @@ -776,6 +776,32 @@ void VTKViewer_InteractorStyle::setCursor(const int operation) } } +/*! + 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() @@ -787,10 +813,7 @@ 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: @@ -1163,12 +1186,8 @@ void VTKViewer_InteractorStyle::onOperation(QPoint mousePos) } 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; } } diff --git a/src/VTKViewer/VTKViewer_InteractorStyle.h b/src/VTKViewer/VTKViewer_InteractorStyle.h index b867f64b3..baaa4988a 100644 --- a/src/VTKViewer/VTKViewer_InteractorStyle.h +++ b/src/VTKViewer/VTKViewer_InteractorStyle.h @@ -33,8 +33,10 @@ class vtkCell; class vtkRenderWindowInteractor; -#include -#include +#include +#include + +class QRubberBand; #include @@ -159,6 +161,8 @@ class VTKVIEWER_EXPORT VTKViewer_InteractorStyle : public QObject, public vtkInt virtual void onCursorMove(QPoint mousePos); virtual void setCursor(const int operation); + void drawRect(); + void endDrawRect(); protected: QCursor myDefCursor; @@ -181,6 +185,8 @@ class VTKVIEWER_EXPORT VTKViewer_InteractorStyle : public QObject, public vtkInt std::map myFilters; + QRubberBand* myRectBand; //!< selection rectangle rubber band + /** @name members from old version*/ //@{ double DeltaElevation; diff --git a/src/VTKViewer/VTKViewer_RenderWindow.cxx b/src/VTKViewer/VTKViewer_RenderWindow.cxx index 82bcf80ec..69971a7b2 100755 --- a/src/VTKViewer/VTKViewer_RenderWindow.cxx +++ b/src/VTKViewer/VTKViewer_RenderWindow.cxx @@ -18,8 +18,8 @@ // #include "VTKViewer_RenderWindow.h" -#include -#include +#include +#include #include #include @@ -27,29 +27,27 @@ #include #include #include -#ifndef WNT +#ifndef WIN32 +#include #include //#include //#include //#include #endif -#if QT_VERSION > 300 -#include -#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(); diff --git a/src/VTKViewer/VTKViewer_RenderWindow.h b/src/VTKViewer/VTKViewer_RenderWindow.h index e85b1c549..6ce1b4309 100755 --- a/src/VTKViewer/VTKViewer_RenderWindow.h +++ b/src/VTKViewer/VTKViewer_RenderWindow.h @@ -23,7 +23,7 @@ #include -#include +#include class VTKVIEWER_EXPORT VTKViewer_RenderWindow : public QWidget { diff --git a/src/VTKViewer/VTKViewer_RenderWindowInteractor.cxx b/src/VTKViewer/VTKViewer_RenderWindowInteractor.cxx index 9445c5b15..261ba9c37 100755 --- a/src/VTKViewer/VTKViewer_RenderWindowInteractor.cxx +++ b/src/VTKViewer/VTKViewer_RenderWindowInteractor.cxx @@ -54,7 +54,10 @@ #include // QT Includes -#include +#include +#include +#include +#include /*! Create new instance of VTKViewer_RenderWindowInteractor*/ VTKViewer_RenderWindowInteractor* VTKViewer_RenderWindowInteractor::New() @@ -324,7 +327,8 @@ int VTKViewer_RenderWindowInteractor::CreateTimer(int vtkNotUsed(timertype)) /// /// Start a one-shot timer for 10ms. /// - mTimer->start(10, TRUE) ; + mTimer->setSingleShot(TRUE) ; + mTimer->start(10) ; return 1 ; } @@ -383,8 +387,8 @@ void VTKViewer_RenderWindowInteractor::LeftButtonPressed(const QMouseEvent *even 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()); } @@ -396,8 +400,8 @@ void VTKViewer_RenderWindowInteractor::LeftButtonReleased(const QMouseEvent *eve 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() ) ; } @@ -409,8 +413,8 @@ void VTKViewer_RenderWindowInteractor::MiddleButtonPressed(const QMouseEvent *ev 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() ) ; } @@ -422,8 +426,8 @@ void VTKViewer_RenderWindowInteractor::MiddleButtonReleased(const QMouseEvent *e 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() ) ; } @@ -435,8 +439,8 @@ void VTKViewer_RenderWindowInteractor::RightButtonPressed(const QMouseEvent *eve 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() ) ; } @@ -449,14 +453,13 @@ void VTKViewer_RenderWindowInteractor::RightButtonReleased(const QMouseEvent *ev 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 ); } } diff --git a/src/VTKViewer/VTKViewer_RenderWindowInteractor.h b/src/VTKViewer/VTKViewer_RenderWindowInteractor.h index 435e5b4b8..22fb37307 100755 --- a/src/VTKViewer/VTKViewer_RenderWindowInteractor.h +++ b/src/VTKViewer/VTKViewer_RenderWindowInteractor.h @@ -22,8 +22,12 @@ #include "VTKViewer.h" #include "VTKViewer_Actor.h" -#include -#include +#include + +class QTimer; +class QMouseEvent; +class QKeyEvent; +class QContextMenuEvent; // Open CASCADE Includes #include diff --git a/src/VTKViewer/VTKViewer_ViewModel.cxx b/src/VTKViewer/VTKViewer_ViewModel.cxx index f611972ae..1c6715863 100755 --- a/src/VTKViewer/VTKViewer_ViewModel.cxx +++ b/src/VTKViewer/VTKViewer_ViewModel.cxx @@ -25,11 +25,10 @@ #include "SUIT_Desktop.h" #include "SUIT_Session.h" -#include -#include -#include -#include -#include +#include +#include +#include +#include bool _InitializeVtkWarningsCall() { @@ -90,16 +89,16 @@ void VTKViewer_Viewer::setViewManager(SUIT_ViewManager* theViewManager) } /*!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.*/ @@ -112,13 +111,13 @@ void VTKViewer_Viewer::onMousePress(SUIT_ViewWindow* vw, QMouseEvent* 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: @@ -146,13 +145,13 @@ void VTKViewer_Viewer::onMouseRelease(SUIT_ViewWindow* vw, QMouseEvent* event) 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: diff --git a/src/VTKViewer/VTKViewer_ViewModel.h b/src/VTKViewer/VTKViewer_ViewModel.h index 06cab857f..460c58fc2 100755 --- a/src/VTKViewer/VTKViewer_ViewModel.h +++ b/src/VTKViewer/VTKViewer_ViewModel.h @@ -22,7 +22,9 @@ #include "VTKViewer.h" #include "SUIT_ViewModel.h" -#include +#include + +class QMouseEvent; class SUIT_ViewWindow; class SUIT_Desktop; @@ -41,7 +43,7 @@ public: 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(); } diff --git a/src/VTKViewer/VTKViewer_ViewWindow.cxx b/src/VTKViewer/VTKViewer_ViewWindow.cxx index 0e1ab38bb..507c2cf98 100755 --- a/src/VTKViewer/VTKViewer_ViewWindow.cxx +++ b/src/VTKViewer/VTKViewer_ViewWindow.cxx @@ -32,8 +32,8 @@ #include "SUIT_Tools.h" #include "SUIT_ResourceMgr.h" -#include -#include +#include +#include #include #include @@ -55,7 +55,7 @@ VTKViewer_ViewWindow::VTKViewer_ViewWindow( SUIT_Desktop* theDesktop, myRenderWindow = new VTKViewer_RenderWindow( this, "RenderWindow" ); setCentralWidget(myRenderWindow); - myRenderWindow->setFocusPolicy( StrongFocus ); + myRenderWindow->setFocusPolicy( Qt::StrongFocus ); myRenderWindow->setFocus(); myRenderWindow->getRenderWindow()->AddRenderer( myRenderer ); @@ -89,8 +89,8 @@ VTKViewer_ViewWindow::VTKViewer_ViewWindow( SUIT_Desktop* theDesktop, 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(); @@ -414,7 +414,7 @@ QColor VTKViewer_ViewWindow::backgroundColor() const 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.*/ @@ -557,7 +557,7 @@ void VTKViewer_ViewWindow::onTrihedronShow() 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 @@ -584,7 +584,7 @@ QString VTKViewer_ViewWindow::getVisualParameters() */ 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(); diff --git a/src/VTKViewer/resources/VTKViewer_images.ts b/src/VTKViewer/resources/VTKViewer_images.ts new file mode 100644 index 000000000..d55a35900 --- /dev/null +++ b/src/VTKViewer/resources/VTKViewer_images.ts @@ -0,0 +1,69 @@ + + + @default + + ICON_VTKVIEWER_VIEW_GLOBALPAN + view_glpan.png + + + ICON_VTKVIEWER_VIEW_FITAREA + view_fitarea.png + + + ICON_VTKVIEWER_VIEW_FRONT + view_front.png + + + ICON_VTKVIEWER_VIEW_RESET + view_reset.png + + + ICON_VTKVIEWER_VIEW_RIGHT + view_right.png + + + ICON_VTKVIEWER_VIEW_FITALL + view_fitall.png + + + ICON_VTKVIEWER_VIEW_BOTTOM + view_bottom.png + + + ICON_VTKVIEWER_VIEW_TOP + view_top.png + + + ICON_VTKVIEWER_VIEW_PAN + view_pan.png + + + ICON_VTKVIEWER_VIEW_ROTATE + view_rotate.png + + + ICON_VTKVIEWER_VIEW_ROTATION_POINT + view_rotation_point.png + + + ICON_VTKVIEWER_VIEW_DUMP + view_camera_dump.png + + + ICON_VTKVIEWER_VIEW_BACK + view_back.png + + + ICON_VTKVIEWER_VIEW_ZOOM + view_zoom.png + + + ICON_VTKVIEWER_VIEW_LEFT + view_left.png + + + ICON_VTKVIEWER_VIEW_TRIHEDRON + view_triedre.png + + + diff --git a/src/VTKViewer/resources/VTKViewer_msg_en.ts b/src/VTKViewer/resources/VTKViewer_msg_en.ts new file mode 100644 index 000000000..4d2c8b613 --- /dev/null +++ b/src/VTKViewer/resources/VTKViewer_msg_en.ts @@ -0,0 +1,167 @@ + + + @default + + MNU_FRONT_VIEW + Front + + + ERROR + Error + + + MNU_DUMP_VIEW + Dump view... + + + DSC_TOP_VIEW + Top View + + + MNU_PAN_VIEW + Panning + + + MNU_TOP_VIEW + Top + + + DSC_GLOBALPAN_VIEW + Selection of a new center of the view + + + DSC_ROTATE_VIEW + Rotation of the point of view around the scene center + + + MNU_ZOOM_VIEW + Zoom + + + DSC_PAN_VIEW + Panning the view + + + DSC_LEFT_VIEW + Left View + + + DSC_FITALL + Fit all objects inside the view frame + + + MNU_FITALL + Fit All + + + MNU_ROTATE_VIEW + Rotation + + + DSC_SHOW_TRIHEDRON + Show/Hide trihedron in the current view + + + DSC_FRONT_VIEW + Front View + + + MNU_GLOBALPAN_VIEW + Global Panning + + + INF_APP_DUMP_VIEW + Dump view + + + MNU_BACK_VIEW + Back + + + MNU_SHOW_TRIHEDRON + Show/Hide trihedron + + + MNU_BOTTOM_VIEW + Bottom + + + MNU_RESET_VIEW + Reset + + + MNU_LEFT_VIEW + Left + + + DSC_RIGHT_VIEW + Right View + + + DSC_FITRECT + Fit area within the view frame + + + MNU_FITRECT + Fit Area + + + DSC_BOTTOM_VIEW + Bottom View + + + DSC_DUMP_VIEW + Saves the active view in the image file + + + DSC_ZOOM_VIEW + Zoom the view + + + VTK_IMAGE_FILES + Images Files (*.bmp *.png *.jpg *.jpeg) + + + DSC_RESET_VIEW + Reset View Point + + + ERR_DOC_CANT_SAVE_FILE + Cannot save file + + + MNU_RIGHT_VIEW + Right + + + LBL_TOOLBAR_LABEL + View Operations + + + DSC_BACK_VIEW + Back View + + + + VTKViewer_ViewManager + + VTK_VIEW_TITLE + VTK scene:%M - viewer:%V + + + + VTKViewer_Viewer + + MEN_DUMP_VIEW + Dump view... + + + MEN_SHOW_TOOLBAR + Show toolbar + + + MEN_CHANGE_BACKGROUD + Change background... + + + diff --git a/src/src.pro b/src/src.pro new file mode 100644 index 000000000..9ef25127c --- /dev/null +++ b/src/src.pro @@ -0,0 +1,30 @@ +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