From: vsr Date: Thu, 9 Aug 2012 06:20:16 +0000 (+0000) Subject: Merge from V6_main_20120808 08Aug12 X-Git-Tag: V7_0_0~6 X-Git-Url: http://git.salome-platform.org/gitweb/?a=commitdiff_plain;h=3593b4d1585d69f34034e5c678dc97b6e92a85cf;p=modules%2Fgui.git Merge from V6_main_20120808 08Aug12 --- diff --git a/adm_local/cmake_files/UseQT4EXT.cmake b/adm_local/cmake_files/UseQT4EXT.cmake new file mode 100644 index 000000000..e3a8605c4 --- /dev/null +++ b/adm_local/cmake_files/UseQT4EXT.cmake @@ -0,0 +1,39 @@ +# Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +# + +INSTALL(CODE "MACRO(QT4_COMPILE_TS_ON_INSTALL MYLRELEASE MYTSFILE MYFULLDIR MYOUTQMFILE) + FILE(MAKE_DIRECTORY \${MYFULLDIR}) + MESSAGE(STATUS \"Compiling \${MYTSFILE}\") + EXECUTE_PROCESS(COMMAND \${MYLRELEASE} \${MYTSFILE} -qm \${MYFULLDIR}/\${MYOUTQMFILE}) +ENDMACRO(QT4_COMPILE_TS_ON_INSTALL)") + +# This MACRO uses the following vars +# - QT_LRELEASE_EXECUTABLE : (given by default by FindQT.cmake) +# +# MYTSFILES containing all ts files to be compiled. +# WHERETOINSTALL contains directory (relative to install_prefix) where to install files after compilation of ts files too qm. +MACRO(QT4_INSTALL_TS_RESOURCES MYTSFILES WHERETOINSTALL) + INSTALL(CODE "SET(INSTALL_TS_DIR ${WHERETOINSTALL})") + SET(MYSOURCES) + FOREACH(input ${MYTSFILES}) + STRING(REGEX REPLACE ".ts" "" base ${input}) + SET(output "${base}.qm") + INSTALL(CODE "QT4_COMPILE_TS_ON_INSTALL( \"${QT_LRELEASE_EXECUTABLE}\" \"${CMAKE_CURRENT_SOURCE_DIR}/${input}\" \"${CMAKE_INSTALL_PREFIX}/\${INSTALL_TS_DIR}\" ${output})") + ENDFOREACH(input ${MYIDLFILES}) +ENDMACRO(QT4_INSTALL_TS_RESOURCES) diff --git a/adm_local/unix/config_files/check_salome_version.m4 b/adm_local/unix/config_files/check_salome_version.m4 new file mode 100644 index 000000000..308d4af3a --- /dev/null +++ b/adm_local/unix/config_files/check_salome_version.m4 @@ -0,0 +1,48 @@ +dnl Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +dnl +dnl Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, +dnl CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS +dnl +dnl This library is free software; you can redistribute it and/or +dnl modify it under the terms of the GNU Lesser General Public +dnl License as published by the Free Software Foundation; either +dnl version 2.1 of the License. +dnl +dnl This library is distributed in the hope that it will be useful, +dnl but WITHOUT ANY WARRANTY; without even the implied warranty of +dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +dnl Lesser General Public License for more details. +dnl +dnl You should have received a copy of the GNU Lesser General Public +dnl License along with this library; if not, write to the Free Software +dnl Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +dnl +dnl See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +dnl + +# Check SALOME version +# + +AC_DEFUN([CHECK_SALOME_VERSION],[ +AC_REQUIRE([AC_LINKER_OPTIONS])dnl + +AC_CHECKING(for salome version) + +salome_version_ok=no +SALOME_VERSION="" + +salomeVersionFile=${GUI_ROOT_DIR}/include/salome/GUI_version.h +SALOME_VERSION=$(grep GUI_VERSION_STR ${salomeVersionFile} | cut -d'"' -f2 | cut -d"." -f1) + +if test "x${SALOME_VERSION}" = "x" ; then + AC_MSG_WARN("Cannot determine the SALOME version. GUI module is required. Specify the variable GUI_ROOT_DIR") +else + salome_version_ok=yes + AC_MSG_RESULT(Using salome version ${SALOME_VERSION}) +fi + +AC_SUBST(SALOME_VERSION) +AC_MSG_RESULT(for salome version: $salome_version_ok) + +])dnl + diff --git a/bin/gui_setenv.py b/bin/gui_setenv.py new file mode 100644 index 000000000..4cadb294e --- /dev/null +++ b/bin/gui_setenv.py @@ -0,0 +1,34 @@ +#! /usr/bin/env python +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +# + +import os, re + +# ----------------------------------------------------------------------------- + +def set_env( args ): + """Add environment required for GUI module""" + vtk_overloads_dir = os.path.join( os.getenv( "GUI_ROOT_DIR" ), "lib", "paraview" ) + dirs = re.split( ":|;", os.getenv( 'VTK_AUTOLOAD_PATH', vtk_overloads_dir ) ) + if vtk_overloads_dir not in dirs: dirs[0:0] = [vtk_overloads_dir] + os.environ['VTK_AUTOLOAD_PATH'] = os.pathsep.join(dirs) + return + + diff --git a/doc/salome/gui/images/SALOME_pythonplugins_dialog.png b/doc/salome/gui/images/SALOME_pythonplugins_dialog.png new file mode 100644 index 000000000..9da2f08bd Binary files /dev/null and b/doc/salome/gui/images/SALOME_pythonplugins_dialog.png differ diff --git a/doc/salome/gui/images/SALOME_pythonplugins_menu.png b/doc/salome/gui/images/SALOME_pythonplugins_menu.png new file mode 100644 index 000000000..f84f48631 Binary files /dev/null and b/doc/salome/gui/images/SALOME_pythonplugins_menu.png differ diff --git a/doc/salome/gui/images/SALOME_pythonplugins_result.png b/doc/salome/gui/images/SALOME_pythonplugins_result.png new file mode 100644 index 000000000..fdbcad80b Binary files /dev/null and b/doc/salome/gui/images/SALOME_pythonplugins_result.png differ diff --git a/doc/salome/gui/images/analytical_curves_dlg.png b/doc/salome/gui/images/analytical_curves_dlg.png new file mode 100755 index 000000000..6bddc84cc Binary files /dev/null and b/doc/salome/gui/images/analytical_curves_dlg.png differ diff --git a/doc/salome/gui/images/change_background_dlg.png b/doc/salome/gui/images/change_background_dlg.png new file mode 100644 index 000000000..2b0e6a4a3 Binary files /dev/null and b/doc/salome/gui/images/change_background_dlg.png differ diff --git a/doc/salome/gui/images/copy-paste.png b/doc/salome/gui/images/copy-paste.png new file mode 100644 index 000000000..c64667714 Binary files /dev/null and b/doc/salome/gui/images/copy-paste.png differ diff --git a/doc/salome/gui/images/glviewer_toolbar.png b/doc/salome/gui/images/glviewer_toolbar.png new file mode 100644 index 000000000..c18f17807 Binary files /dev/null and b/doc/salome/gui/images/glviewer_toolbar.png differ diff --git a/doc/salome/gui/images/graduatedaxes2.png b/doc/salome/gui/images/graduatedaxes2.png new file mode 100644 index 000000000..ab13229b3 Binary files /dev/null and b/doc/salome/gui/images/graduatedaxes2.png differ diff --git a/doc/salome/gui/images/head.png b/doc/salome/gui/images/head.png new file mode 100755 index 000000000..307d9ef9a Binary files /dev/null and b/doc/salome/gui/images/head.png differ diff --git a/doc/salome/gui/images/image54.png b/doc/salome/gui/images/image54.png new file mode 100644 index 000000000..8e6b1e52b Binary files /dev/null and b/doc/salome/gui/images/image54.png differ diff --git a/doc/salome/gui/images/image65.png b/doc/salome/gui/images/image65.png new file mode 100644 index 000000000..92631b2d0 Binary files /dev/null and b/doc/salome/gui/images/image65.png differ diff --git a/doc/salome/gui/images/image67.png b/doc/salome/gui/images/image67.png new file mode 100644 index 000000000..ce4bda602 Binary files /dev/null and b/doc/salome/gui/images/image67.png differ diff --git a/doc/salome/gui/images/image69.png b/doc/salome/gui/images/image69.png new file mode 100644 index 000000000..fb9cefb9c Binary files /dev/null and b/doc/salome/gui/images/image69.png differ diff --git a/doc/salome/gui/images/image70.png b/doc/salome/gui/images/image70.png new file mode 100644 index 000000000..c5c147aa8 Binary files /dev/null and b/doc/salome/gui/images/image70.png differ diff --git a/doc/salome/gui/images/image73.png b/doc/salome/gui/images/image73.png new file mode 100644 index 000000000..30d44d56b Binary files /dev/null and b/doc/salome/gui/images/image73.png differ diff --git a/doc/salome/gui/images/image75.png b/doc/salome/gui/images/image75.png new file mode 100644 index 000000000..205ad4339 Binary files /dev/null and b/doc/salome/gui/images/image75.png differ diff --git a/doc/salome/gui/images/image94.png b/doc/salome/gui/images/image94.png new file mode 100644 index 000000000..4f32ce39e Binary files /dev/null and b/doc/salome/gui/images/image94.png differ diff --git a/doc/salome/gui/images/image95.png b/doc/salome/gui/images/image95.png new file mode 100644 index 000000000..1678fefb1 Binary files /dev/null and b/doc/salome/gui/images/image95.png differ diff --git a/doc/salome/gui/images/newsticn.png b/doc/salome/gui/images/newsticn.png new file mode 100644 index 000000000..765baba3b Binary files /dev/null and b/doc/salome/gui/images/newsticn.png differ diff --git a/doc/salome/gui/images/note1.png b/doc/salome/gui/images/note1.png new file mode 100644 index 000000000..ddb9f5fff Binary files /dev/null and b/doc/salome/gui/images/note1.png differ diff --git a/doc/salome/gui/images/plot2dviewer_toolbar.png b/doc/salome/gui/images/plot2dviewer_toolbar.png new file mode 100644 index 000000000..b394dee95 Binary files /dev/null and b/doc/salome/gui/images/plot2dviewer_toolbar.png differ diff --git a/doc/salome/gui/images/pref_salome_directories.png b/doc/salome/gui/images/pref_salome_directories.png new file mode 100644 index 000000000..c47b45788 Binary files /dev/null and b/doc/salome/gui/images/pref_salome_directories.png differ diff --git a/doc/salome/gui/images/pref_salome_general.png b/doc/salome/gui/images/pref_salome_general.png new file mode 100644 index 000000000..db05ca064 Binary files /dev/null and b/doc/salome/gui/images/pref_salome_general.png differ diff --git a/doc/salome/gui/images/pref_salome_objbrowser.png b/doc/salome/gui/images/pref_salome_objbrowser.png new file mode 100644 index 000000000..9242935e8 Binary files /dev/null and b/doc/salome/gui/images/pref_salome_objbrowser.png differ diff --git a/doc/salome/gui/images/pref_salome_occviewer.png b/doc/salome/gui/images/pref_salome_occviewer.png new file mode 100644 index 000000000..953d07211 Binary files /dev/null and b/doc/salome/gui/images/pref_salome_occviewer.png differ diff --git a/doc/salome/gui/images/pref_salome_plot2dviewer.png b/doc/salome/gui/images/pref_salome_plot2dviewer.png new file mode 100644 index 000000000..f427aee9d Binary files /dev/null and b/doc/salome/gui/images/pref_salome_plot2dviewer.png differ diff --git a/doc/salome/gui/images/pref_salome_shortcuts.png b/doc/salome/gui/images/pref_salome_shortcuts.png new file mode 100644 index 000000000..5f4c19454 Binary files /dev/null and b/doc/salome/gui/images/pref_salome_shortcuts.png differ diff --git a/doc/salome/gui/images/pref_salome_vtkviewer.png b/doc/salome/gui/images/pref_salome_vtkviewer.png new file mode 100644 index 000000000..29ac576dd Binary files /dev/null and b/doc/salome/gui/images/pref_salome_vtkviewer.png differ diff --git a/doc/salome/gui/images/qxviewer_toolbar.png b/doc/salome/gui/images/qxviewer_toolbar.png new file mode 100644 index 000000000..716a078c0 Binary files /dev/null and b/doc/salome/gui/images/qxviewer_toolbar.png differ diff --git a/doc/salome/gui/images/save.png b/doc/salome/gui/images/save.png new file mode 100644 index 000000000..2d2f98635 Binary files /dev/null and b/doc/salome/gui/images/save.png differ diff --git a/doc/salome/gui/images/valueslabelingprops.png b/doc/salome/gui/images/valueslabelingprops.png new file mode 100644 index 000000000..0049eb4a6 Binary files /dev/null and b/doc/salome/gui/images/valueslabelingprops.png differ diff --git a/doc/salome/gui/images/vtk_view_parameters_dlg.png b/doc/salome/gui/images/vtk_view_parameters_dlg.png new file mode 100644 index 000000000..a289e806b Binary files /dev/null and b/doc/salome/gui/images/vtk_view_parameters_dlg.png differ diff --git a/doc/salome/gui/images/vtkviewer_toolbar.png b/doc/salome/gui/images/vtkviewer_toolbar.png new file mode 100644 index 000000000..460794973 Binary files /dev/null and b/doc/salome/gui/images/vtkviewer_toolbar.png differ diff --git a/doc/salome/gui/input/gl_2d_viewer.doc b/doc/salome/gui/input/gl_2d_viewer.doc new file mode 100644 index 000000000..3f0c35f57 --- /dev/null +++ b/doc/salome/gui/input/gl_2d_viewer.doc @@ -0,0 +1,71 @@ +/*! + +\page gl_2d_viewer_page GL 2D Viewer + +

Operations

+ +The functionalities of GL viewer are available via its Viewer +Toolbar. Buttons marked with small downward triangles have extended +functionality which can be accessed by locking on them with left mouse +button. + +\image html glviewer_toolbar.png +
+ +\image html gl_view_dump.png + +Dump View - exports an object from the viewer in bmp, png or +jpeg image format. +
+ +\image html gl_view_fitall.png + +Fit all - scales the presentation so that it could fit within +the Viewer boundaries. +
+ +\image html gl_view_fitarea.png + +Fit area - resizes the view to place in the visible area only +the contents of a frame drawn with pressed left mouse button. +
+ +\image html gl_view_fitselect.png + +Fit selection - resizes the view to fit in the visible area +only currently selected objects. +
+ +\image html gl_view_zoom.png + +Zoom - allows to zoom in and out. +
+ +\image html gl_view_pan.png + +Panning - if the represented objects are greater that the +visible area and you don't wish to use Fit all functionality, +click on this button and you'll be able to drag the scene to see its +remote parts. +
+ +\image html gl_view_glpan.png + +Global panning - allows to select a point to be the center of +the presentation showing all displayed objects in the visible ares. +
+ +\image html gl_view_reset.png + +Reset - restores the default position the scene. +
+ +\anchor gl_background +

Background

+ +GL Viewer background can be customized using the "Change background" +popup menu command that opens standard "Select Color" dialog box: + +\image html selectcolor.png + +*/ diff --git a/doc/salome/gui/input/howtos_and_best_practives.doc b/doc/salome/gui/input/howtos_and_best_practives.doc new file mode 100644 index 000000000..e064bf281 --- /dev/null +++ b/doc/salome/gui/input/howtos_and_best_practives.doc @@ -0,0 +1,463 @@ +/*! + +\page howtos How-To's and Best Practices + +These documents provide guidelines and best practices explaining different aspects +and usage examples of SALOME platform. + +- \subpage use_case_builder +- \subpage drag_and_drop +- \subpage using_pluginsmanager + +\page use_case_builder Customize data tree representation in the Object browser by means of use case builder + +\tableofcontents + +In SALOME, the representation of the data tree in the Object browser for the \a full +(CORBA-based) module is done basing on the study contents as it is supplied by SALOME +data server (SALOMEDS). In contrast to the \a light module which data tree is completely +defined and can be easily attuned by the module specific implementation, \a full module +must publish its data in the CORBA study by means of the corresponding API of SALOME +data server, namely \c SALOMEDS::StudyBuilder. As soon as data entities are published +in the study, they are shown in the Object browser, in the same order as they appear +in the study tree. Re-arrangement of the data entities with such approach is not a +trivial task: for example, when copying/moving any data entity at the new position +within the tree, it is necessary to copy all its attributes as well +and to clear (in case of move operation) the data entity at the original position. Also, it is not possible to +make some data items in the tree "invisible" for the user (though it might be useful). + +Use case builder provides an alternative and more flexible way for customizing the +data tree representation. It implements another approach to the data tree hierarchy, +based on the tree node attributes. With use case builder it is possible to arrange +and easily re-arrange the data items in the data tree in any appropriate way. + +For example, with use case builder it is easy to implement such operations as +\ref drag_and_drop "Drag and Drop" and Copy/Cut/Paste. With use case builder approach +it is not important how data entities are arranged in the study tree, they even may +lie on the same level - use case builder allows providing custom data tree +representation, completely indepedent on the study data tree itself. It is even possible +to hide some data entities in the tree representation while still keeping them in the +study (to store specific module data). + +Object browser automatically checks it the module root data object +contains a tree node attribute and switches to the browsing of the +data tree for such module using the use case +builder. Otherwise, it browses data using an ordinary study tree iterator. Thus, it is +possible to have in the same study some modules based on use case builder approach and +others not using it. + +\section use_case_builder_usage Use case builder usage + +To obtain a reference to the use case builder, the function \c GetUseCaseBuilder() of the +\c SALOMEDS::Study interface can be used: + +\code +interface Study +{ + // Get reference to the use case builder + UseCaseBuilder GetUseCaseBuilder(); +}; +\endcode + +\c SALOMEDS::UseCaseBuilder interface of the \c SALOMEDS CORBA module provides several +methods that can be used to build a custom data tree. Its API is +similar to the API of +\c SALOMEDS::StudyBuilder interface - it operates with terms \a "father object" and +\a "child object". In addition, use case builder uses term \a "current object" that is +used as a parent of the children objects added if the parent is not explicitly +specified. + +\code +interface UseCaseBuilder +{ + // Set top-level root object of the use case tree as the current one. + // This method is usually used to add SComponent items to the top level of the tree + boolean SetRootCurrent(); + + // Set the object theObject as the current object of the use case builder + boolean SetCurrentObject(in SObject theObject); + + // Append object SObject to the end of children list of the current object + boolean Append(in SObject theObject); + + // Append object SObject to the end of children list of the parent object theFather + boolean AppendTo(in SObject theFather, in SObject theObject); + + // Insert object theFirst before the object theNext (under the same parent object) + boolean InsertBefore(in SObject theFirst, in SObject theNext); + + // Remove object from the use case tree (without removing it from the study) + boolean Remove(in SObject theObject); + + // Check if the object theObject has children (in the use case tree) + boolean HasChildren(in SObject theObject); + + // Get father object of the given object theObject in the use cases tree + SObject GetFather(in SObject theObject); + + // Check if given object theObject is added to the use case tree + boolean IsUseCaseNode(in SObject theObject); + + // Get the current object of the use case builder + SObject GetCurrentObject(); +}; +\endcode + +\section browse_use_case_tree Browsing use case data tree + +Browsing the use case tree can be done by means of the use case iterator, that is +provided by the \c SALOMEDS::UseCaseIterator interface of the \c SALOMEDS CORBA +module. Access to the use case iterator can be done via \c SALOMEDS::UseCaseBuilder +interface: + +\code +interface UseCaseBuilder +{ + // Get a reference to the use case iterator and initialize it + // by the given object theObject + UseCaseIterator GetUseCaseIterator(in SObject theObject); +}; +\endcode + +The API of the \c SALOMEDS::UseCaseIterator interface is similar to the +\c SALOMEDS::ChildIterator: + +\code +interface UseCaseIterator +{ + // Activate or reset use case iterator; boolean parameter allLevels + // specifies if the iterator should browse recursively on all sub-levels or + // on the first sub-level only. + void Init(in boolean allLevels); + // Check if the iterator can browse to the next item + boolean More(); + // Browse the iterator to the next object + void Next(); + // Get the object currently pointed by the iterator + SObject Value(); +}; +\endcode + +Typical usage of the \c UseCaseIterator is as follows: + +\code +// get use case builder +SALOMEDS::UseCaseBuilder_var useCaseBuilder = study->GetUseCaseBuilder(); + +// get the use case iterator +SALOMEDS::UseCaseIterator_var iter = useCaseIter->GetUseCaseIterator( sobject.in() ); +// iterate through the sub-items recursively +for ( useCaseIter->Init( true ); useCaseIter->More(); useCaseIter->Next() ) { + SALOMEDS::SObject_var child = useCaseIter->Value(); + // do something with the child + // ... + // clean-up + child->UnRegister(); +} +// clean-up +useCaseIter->UnRegister(); +useCaseBuilder->UnRegister(); +\endcode + +\section use_case_compatibility Remark about compatibility with existing studies + +If you decide to switch your module to the use case builder approach to provide +customization for the data tree representation, you must take care of compatibility +with existing SALOME studies. Basically it means that you have to add +a simple code to \c Load() (and \c LoadASCII() if necessary) method +of your module, which adds tree node attributes to all data entities +in the data tree of your module. The simplest way to do +this is to iterate through all data items and recursively add them to +the use case builder: + +\code +// find component +SALOMEDS::SComponent_var comp = study->FindComponent( "MYMODULE" ); +// add tree node attributes only if component data is present in the study +if ( !CORBA::is_nil( comp ) ) { + // get the use case builder + SALOMEDS::UseCaseBuilder_var useCaseBuilder = study->GetUseCaseBuilder(); + // check if tree nodes are already set + if ( !useCaseBuilder->IsUseCaseNode( comp.in() ) ) { + // set the current node of the use case builder to the root + useCaseBuilder->SetRootCurrent(); + // add component item to the top level of the use case tree + useCaseBuilder->Append( comp.in() ); + // iterate through all child items recursively + SALOMEDS::ChildIterator_var iter = study->NewChildIterator( comp.in() ); + for ( iter->InitEx( true ); iter->More(); iter->Next() ) { + SALOMEDS::SObject_var sobj = iter->Value(); + SALOMEDS::SObject_var father = sobj->GetFather(); + // add an object to the corresponding level in the use case tree + useCaseBuilder->AppendTo( father.in(), sobj.in() ); + // clean up (avoid memory leaks) + sobj->UnRegister(); + father->UnRegister(); + } + } + useCaseBuilder->UnRegister(); // clean up +} +\endcode + +\page drag_and_drop Implementing Drag and Drop functionality in SALOME module + +\tableofcontents + +Drag and Drop provides a simple visual mechanism to transfer +information between and within applications. + +In some aspects Drag and drop operates similarly to the clipboard copy/cut/paste +mechanism. + +Since SALOME GUI is implemented on Qt, the drag and drop functionality support +is provided by means of the corresponding Qt mechanisms. + +Currently dragging and dropping of the items can be done within Object browser only, +however this functionality can be extended to other GUI elements as well. + +\section enable_drag_and_drop Enabling drag and drop in SALOME module + +The Drag and drop functionality is enabled by default in the Object browser. However, +to allow dragging of a data object or dropping data on it, it is necessary to redefine +\c isDraggable() and \c isDropAccepted() methods of the corresponding class, a successor +of the \c SUIT_DataObject. These methods are defined in the base class \c SUIT_DataObject +and default implementation of both functions returns \c false, which prevents dragging and +dropping: + +\code +bool SUIT_DataObject::isDraggable() const +{ + return false; +} + +bool SUIT_DataObject::isDropAccepted() const +{ + return false; +} +\endcode + +If your data model is based on the \c SUIT_DataObject and \c SUIT_TreeModel, just +re-implement these functions in your successor data object class and return \c true +when it is needed (for example, depending on the data object type, state, etc). + +Another alternative is available if your module is directly inherited from +\c LightApp_Module or \c SalomeApp_Module class (as the majority of existing SALOME modules). +The class \c LightApp_Module (and thus \c SalomeApp_Module also) already provides +high-level API that can be used for enabling drag and drop functionality. + +To enable dragging, redefine \c isDraggable() method of your module class. In this method +you can analyze the data object subject to the drag operation and decide if +it is necessary to enable or prevent its dragging: + +\code +bool MyModuleGUI::isDraggable( const SUIT_DataObject* what ) const +{ + bool result = false; + const MyDataObject* obj = dynamic_cast( what ); + if ( obj ) { + // check if object can be dragged + result = ; + } + return result; +} +\endcode + +Note, that you should not invoke here method \c isDragEnabled() of your data object class +(in case if it inherits \c LightApp_DataObject or \c SalomeApp_DataObject), unless you +redefine methods \c isDraggable() and \c isDropAccepted() in your data object class. +The reason is that the implementation of these methods in \c LightApp_DataObject class +redirects calls to the \c LightApp_Module - be careful to avoid entering endless +recursion loop. + +To allow data dropping to an object (the object under the mouse cursor in the +Object browser during the drag operation) redefine \c isDropAccepted() method of your +module class: + +\code +bool MyModuleGUI::isDropAccepted( const SUIT_DataObject* where ) const +{ + bool result = false; + const MyDataObject* obj = dynamic_cast( where ); + if ( obj ) { + // check if object supports dropping + result = ; + } + return result; +} +\endcode + +The caution about avoiding recursive loop mentioned above is also valid for +\c isDropAccepted() method. + +\section handle_data_dropping Handling data dropping + +When dragging operation is completed (the data is dropped to an object) the module owning +the item on which the data is dropped is notified by invoking its \c dropObjects() method: + +\code +void LightApp_Module::dropObjects( const DataObjectList& what, + SUIT_DataObject* where, + const int row, + Qt::DropAction action ) +{ +} +\endcode + +The default implementation does nothing. However, this method can be redifined in the +successor class and handle the operation properly. The list of dropped +data objects is passed via \c what parameter. The data object on which +the data is dropped is passed via \c where parameter. The parameter \c row specifies in the children list +the position of object where data is dropped; if this parameter is equal to -1, the +data is dropped to the end of the children list. Performed drop action is passed +via \c action parameter; possible values are \c Qt::CopyAction and \c Qt::MoveAction +(other actions are currently unsupported). + +The method \c dropObjects() should analyze the parameters and apply +the corresponding actions for rearrangement of the data tree, copying or moving the data items depending on the +operation performed. For example: + +\code +void MyModuleGUI::dropObjects( const DataObjectList& what, SUIT_DataObject* where, + const int row, Qt::DropAction action ) +{ + if ( action != Qt::CopyAction && action != Qt::MoveAction ) + return; // unsupported action + + // get parent object + MyDataObject* whereObj = dynamic_cast( where ); + if ( !dataObj ) return; // wrong parent + + // iterate through all objects being dropped + for ( int i = 0; i < what.count(); i++ ) { + MyDataObject* whatObj = dynamic_cast( what[i] ); + if ( !whatObj ) continue; // skip wrong objects + // perform copying or moving + copyOrMove( whatObj, // data object being copied/moved + whereObj, // target data object + row, // index in the target data object + action == Qt::CopyAction ); // true if copying is done + } + // update Object browser + getApp()->updateObjectBrowser( false ); +} +\endcode + +In the above code the function \c copyOrMove() performs actual data tree rearrangement. + +\section drag_drop_light_modules Drag and Drop in "light" modules + +The data model of the \a light (not having CORBA engine) SALOME module is usually +based on the custom tree of data objects. The general approach is to +inherit a custom data +object class from the \c LightApp_DataObject and a custom data model from the +\c LightApp_DataModel class. The data model class is responsible for building the +appropriate presentation of the data tree in the Object browser. + +Thus, the implementation of the drag and drop functionality in a \a light module (more +precisely, the method \a dropObjects() as described above), consists in copying data +entities (by creating new instances of the corresponding data object class) or moving +existing data objects to the new position in a tree. The Object browser will update the +tree representation automatically, as soon as \c updateObjectBrowser() function is called. + +\section drag_drop_full_modules Using UseCaseBuilder for Drag and Drop handling in "full" modules + +Drag and drop operation requires underlying data model to allow flexible re-arrangement of +the data entities inside the data tree. In a \a full (CORBA engine based) SALOME +module, which data model is usually based on the hierarchy of \c SALOMEDS::SObject entities +provided by the data server functionality, re-arrangement of the data +tree is not a trivial task. + +However, SALOME data server (\c SALOMEDS) CORBA module proposes a mechanism that can be used +to customize data tree representation in a simple and flexible way - +\ref use_case_builder "use case builder". + +With use case builder, the \c dropObjects() function can be easily implemented. For example: + +\code +// GUI part: process objects dropping +void MyModuleGUI::dropObjects( const DataObjectList& what, SUIT_DataObject* where, + const int row, Qt::DropAction action ) +{ + if ( action != Qt::CopyAction && action != Qt::MoveAction ) + return; // unsupported action + + // get parent object + SalomeApp_DataObject* dataObj = dynamic_cast( where ); + if ( !dataObj ) return; // wrong parent + _PTR(SObject) parentObj = dataObj->object(); + + // collect objects being dropped + MYMODULE_ORB::object_list_var objects = new MYMODULE_ORB::object_list(); + objects->length( what.count() ); + int count = 0; + for ( int i = 0; i < what.count(); i++ ) { + dataObj = dynamic_cast( what[i] ); + if ( !dataObj ) continue; // skip wrong objects + _PTR(SObject) sobj = dataObj->object(); + objects[i] = _CAST(SObject, sobj)->GetSObject(); + count++; + } + objects->length( count ); + + // call engine function + engine()->copyOrMove( objects.in(), // what + _CAST(SObject, parentObj)->GetSObject(), // where + row, // row + action == Qt::CopyAction ); // isCopy + + // update Object browser + getApp()->updateObjectBrowser( false ); +} + +// Engine part: perform actual data copying / moving +void MyModule::copyOrMove( const MYMODULE_ORB::object_list& what, + SALOMEDS::SObject_ptr where, + CORBA::Long row, CORBA::Boolean isCopy ) +{ + if ( CORBA::is_nil( where ) ) return; // bad parent + + SALOMEDS::Study_var study = where->GetStudy(); // study + SALOMEDS::StudyBuilder_var studyBuilder = study->NewBuilder(); // study builder + SALOMEDS::UseCaseBuilder_var useCaseBuilder = study->GetUseCaseBuilder(); // use case builder + SALOMEDS::SComponent_var father = where->GetFatherComponent(); // father component + std::string dataType = father->ComponentDataType(); + if ( dataType != "MYMODULE" ) return; // not a MYMODULE component + + SALOMEDS::SObject_var objAfter; + if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) { + // insert at a given row -> find insertion position + SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where ); + int i; + for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() ); + if ( i == row && useCaseIt->More() ) { + objAfter = useCaseIt->Value(); + } + } + // process all objects in a given list + for ( int i = 0; i < what.length(); i++ ) { + SALOMEDS::SObject_var sobj = what[i]; + if ( CORBA::is_nil( sobj ) ) continue; // skip bad object + if ( isCopy ) { + // copying is performed + // get the name of the object + CORBA::String_var name = sobj->GetName(); + // create a new object, as a child of the component object + SALOMEDS::SObject_var new_sobj = studyBuilder->NewObject( father ); + new_sobj->SetAttrString( "AttributeName", name.in() ); + sobj = new_sobj; + // ... perform other necessary data copying like + // adding the corresponding attributes or creation + // of servant data entities... + } + // insert the object or its copy to the use case tree + if ( !CORBA::is_nil( objAfter ) ) + useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at a given row + else + useCaseBuilder->AppendTo( where, sobj ); // append to the + end of the list + } +} + +\endcode + +*/ diff --git a/doc/salome/gui/input/qxscene_2d_viewer.doc b/doc/salome/gui/input/qxscene_2d_viewer.doc new file mode 100644 index 000000000..08cc74db9 --- /dev/null +++ b/doc/salome/gui/input/qxscene_2d_viewer.doc @@ -0,0 +1,54 @@ +/*! + +\page qxscene_2d_viewer_page QxScene 2D Viewer + +

Operations

+ +The functionalities of QxScene viewer are available via its Viewer +Toolbar. Buttons marked with small downward triangles have extended +functionality which can be accessed by locking on them with left mouse +button. + +\image html qxviewer_toolbar.png +
+ +\image html qx_view_fitall.png + +Fit all - scales the presentation so that it could fit within +the Viewer boundaries. +
+ +\image html qx_view_fitarea.png + +Fit area - resizes the view to place in the visible area only +the contents of a frame drawn with pressed left mouse button. +
+ +\image html qx_view_zoom.png + +Zoom - allows to zoom in and out. +
+ +\image html qx_view_pan.png + +Panning - if the represented objects are greater that the +visible area and you don't wish to use Fit all functionality, +click on this button and you'll be able to drag the scene to see its +remote parts. +
+ +\image html qx_view_glpan.png + +Global panning - allows to select a point to be the center of +the presentation showing all displayed objects in the visible ares. +
+ +\image html qx_view_reset.png + +Reset - restores the default position the scene. +
+ +For more details about QxScene viewer, refer to the SALOME YACS module +User's guide. + +*/ diff --git a/doc/salome/gui/input/using_input_widgets.doc b/doc/salome/gui/input/using_input_widgets.doc new file mode 100755 index 000000000..bf0d0d8e4 --- /dev/null +++ b/doc/salome/gui/input/using_input_widgets.doc @@ -0,0 +1,64 @@ +/*! + +\page using_input_widgets_page Using input widgets + +This section contains some hints that might be useful when working +with SALOME GUI input widgets. + +

Spin boxes

+ +This type of widgets is used for numeric (integer or floating-point) +data input. Spin boxes are used in standard \b SALOME modules if the +input value has a clearly defined input range (and precision in +case of a floating-point value). + +Input precision has a specific semantics in \b SALOME floating-point +spin boxes: +- Positive precision value means that a number in the fixed-point format +(corresponding to the "f" format specifier for C printf function) is +expected. Positive precision value is the maximum allowed number of +digits after the decimal separator. +- Negative precision value means that a number either in the fixed-point +or the scientific (exponetial) format is expected. This is similar to the +behavior of the "g" format specifier for C printf function. Negative +precision value is the maximum allowed number of significant digits in +mantissa (note that one digit is always before the decimal separator). + +To make the user aware of an input value constraints applied by some +\b SALOME operations, the following basic capabilties are provided by +spin boxes: +- The text input manually in a spin box by the user is checked to be a +number of valid type (integer or floating-point). +- The text is converted to a number and checked to be within the valid +range. +- Additionally, for floating-point data the input text is checked +against the precision rules described above. + +If the input text in a spin box does not meet the +constraints, the user is shown a message in a +tooltip near the spin box just as he types in it. The tooltip contains +information about the valid data range. For a floating-point input, the +tooltip also contains information about the expected precision. + +In standard \b SALOME modules the precision value can be adjusted through +\ref setting_preferences_page "user preferences" of the correspodning modules, and the tooltip contains a +reference to the corresponding parameter in the preferences. + +On-line documentation for each standard SALOME module contains the +list of user preferences that can be used for tuning floating-point +precision for different types of input quantities. + +

Spin boxes and SALOME Notebook

+ +Apart from the numeric input, spin boxes in some \b SALOME modules accept +the names of \b Notebook variables (see \ref using_notebook "Using Notebook" +page for more details about \b Notebook). + +If a spin box accepts variable names, then it is +additionally checked whether the manually input text represents a variable name. Variable +names should comply with the common naming rules for \b Python variables. +If the input is neither a valid number nor a variable name, +the tooltip informs the user that variable names are also acceptable in this spin box. + + +*/ diff --git a/doc/salome/gui/input/using_pluginsmanager.doc b/doc/salome/gui/input/using_pluginsmanager.doc new file mode 100644 index 000000000..c8e5ec6c0 --- /dev/null +++ b/doc/salome/gui/input/using_pluginsmanager.doc @@ -0,0 +1,204 @@ +/*! + +\page using_pluginsmanager Extend SALOME gui functions using python plugins + +-# \ref S1_SALOMEPLUGINS +-# \ref S2_SALOMEPLUGINS +-# \ref S3_SALOMEPLUGINS +-# \ref S4_SALOMEPLUGINS +-# \ref S5_SALOMEPLUGINS + +\section S1_SALOMEPLUGINS Objectives + +The SALOME python plugin manager allows the end user to extend the +graphic interface of SALOME with custom functions written as python +modules. The screenshots below show the example of a tool that creates +a mesh from a set of geometrical parameters with the support of +simple graphical interface: + +The default menu for plugins is "Tool->Extensions": +\image html SALOME_pythonplugins_menu.png + +In this example, the plugin provides a small interface to input the +parameters (not provided by the plugin manager): +\image html SALOME_pythonplugins_dialog.png + +Then creates the mesh model: +\image html SALOME_pythonplugins_result.png + +In this example, the end user has to write: + +-# the python script that creates the mesh from the parameters, using + the GEOM and SMESH python interface, as in a clasic use case. +-# the dialog box in PyQt to input the parameters +-# the file salome_plugins.py that declares the plugins + +This page explains only the last point. + +\section S2_SALOMEPLUGINS Principles + +The general form of the file salome_plugins.py is: + +\code +import salome_pluginsmanager + +# Creation of the plugin +def myplugin1(context): + ... + # Here is the code of the plugin myplugin1 + ... + +def myplugin2(context): + ... + # Here is the code of the plugin myplugin2 + ... + +# Declaration of the plugins to the pluginsmanager +salome_pluginsmanager.AddFunction('My plugin n°1', 'This action runs the plugin n°1', myplugin1) +salome_pluginsmanager.AddFunction('My plugin n°2', 'This action runs the plugin n°2', myplugin2) +... +\endcode + +The procedure is to define a function that implements the plugin, and +to declare this function to the plugins manager. The implementation +can be very variable. It is advisable to consider this function as a +proxy to your code that you can manage in a python package +installed in the standard SALOME python directories. + +In this code, the variable "context" is automatically transmitted by +the pluginmanager when you request the plugin. This context provides +you with at at least the following attributes: + +\code +activeStudy = context.study +salomegui = context.sg +\endcode + +Once written, this script salome_plugin.py has to be moved to a +specific place on your filesystem where SALOME is programmed to search +for plugins. The possible directories are (in search order): + +-# The directory <*_ROOT_DIR>/share/salome/plugins/, when + this plugin is developped in the framework of a SALOME module + (<*_ROOT_DIR> is the root installation directory of the module, and + is the name of the module in low letters). +-# The directory ~/.config/salome/Plugins for personnal end user + plugins. +-# Any path in the shell variable SALOME_PLUGIN_PATH (each path must be + separated by a comma ":" for unix and ";" for windows). This + variable should be set and exported before running the SALOME application. + +\section S3_SALOMEPLUGINS A complete example + +Suppose that you write a SALOME script that creates a trihedron for each of +your studies (a simple and standard SALOME script, that every end user +is capable to write if he reads the documentation and follows the +training course): + +\code +# Intialize the geompy factory with the active study +import salome +import geompy +geompy.init_geom(salome.myStudy) + +# Create the objects +Vx = geompy.MakeVectorDXDYDZ(10, 0, 0) +Vy = geompy.MakeVectorDXDYDZ(0, 10, 0) +Vz = geompy.MakeVectorDXDYDZ(0, 0, 10) +origin = geompy.MakeVertex(0, 0, 0) + +# Register the objects in the active study +geompy.addToStudy( Vx, "Vx" )) +geompy.addToStudy( Vy, "Vy" )) +geompy.addToStudy( Vz, "Vz" )) +geompy.addToStudy( origin, "origin" )) +\endcode + +The job consists in creating the file salome_plugins.py as follows: + +\code +import salome_pluginsmanager +def trihedron(context): + import geompy + # Intialize the geompy factory with the active study + activeStudy = context.study + geompy.init_geom(activeStudy) + # Create the objects + Vx = geompy.MakeVectorDXDYDZ(10, 0, 0) + Vy = geompy.MakeVectorDXDYDZ(0, 10, 0) + Vz = geompy.MakeVectorDXDYDZ(0, 0, 10) + origin = geompy.MakeVertex(0, 0, 0) + # Register the objects in the active study + geompy.addToStudy( Vx, "Vx" ) + geompy.addToStudy( Vy, "Vy" ) + geompy.addToStudy( Vz, "Vz" ) + geompy.addToStudy( origin, "origin" ) + +# Register the function in the plugin manager +salome_pluginsmanager.AddFunction('O,Vx,Vy,Vz', + 'Creates the trihedron', + trihedron) + +\endcode + +Move this script in the directory +~/.config/salome/Plugins, run SALOME and enjoy your new function. + +\section S4_SALOMEPLUGINS How to select an object of the object browser + +Sometimes it can be useful to retrieve an object of the object browser to perform +an action on it, for example, to select a mesh and display some information related to it. + +Some important methods and objects to use are as follows: +-# context.sg.getObjectBrowser(): to connect the signal event + `selectionChanged()` to a custom slot +-# context.salome.sg.getAllSelected(): to get the list of selected object + in the object browser +-# objId = context.salome.sg.getSelected(0): + to get the first selected object in the object browser +-# salomeObj = context.salome.study.FindObjectID(objId).GetObject(): + to retrieve the salome object from selection. It can be a GEOM, SMESH, or any + other module object. + + If it is a mesh, then it is possible to call GetMEDMesh() on the object. + If it is not a mesh, this call will raise an exception. + So it is possible to write the mesh retrieval in the following way: +\code +mesh = None +try: + mesh = salomeObj.GetMEDMesh() +except: + print "The selection is not a mesh" +\endcode + +A example of those methods is available with the demo examples. +See the next chapter \ref S5_SALOMEPLUGINS. + +\section S5_SALOMEPLUGINS Other examples + +The GUI module provides you with some basic demo examples located in +the directory src/SalomeApp/pluginsdemo of the source space and +installed in the directory $GUI_ROOT_DIR/share/salome/plugins/gui/demo. + +\note These examples are automatically installed when you install the GUI +but are not activated. To activate the plugins, edit the file +$GUI_ROOT_DIR/share/salome/plugins/gui/demo/salome_plugins.py and turn the +variable DEMO_IS_ACTIVATED to True. + +The demo examples are: +-# \b trihedron: create a trihedron and display it with fit on the size +-# \b tube_shapewithgui: create a geom object from parameters given by a + dialog box. +-# \b tube_meshwithgui: create a mesh object from parameters given by a + dialog box. This illustrates that a plugin can work with more than + one SALOME module. +-# \b tube_shapewithguiAndPreview: same than tube_shapewithgui but with + an additionnal preview function (button apply in the dialog box). +-# \b runSalomeShellSession: run a SALOME prepared shell session in a + xterm. +-# \b minmax: computes the min and max values of a control on a selected mesh. + \note This plugin is available in the SMESH module only. To activate it, edit + the file $GUI_ROOT_DIR/share/salome/plugins/gui/demo/smesh_plugins.py and turn the variable + DEMO_IS_ACTIVATED to True. + +*/ diff --git a/doc/salome/gui/static/doxygen.css b/doc/salome/gui/static/doxygen.css new file mode 100644 index 000000000..7a2dcbde8 --- /dev/null +++ b/doc/salome/gui/static/doxygen.css @@ -0,0 +1,836 @@ +/* The standard CSS for doxygen */ + +body, table, div, p, dl { + font-family: Lucida Grande, Verdana, Geneva, Arial, sans-serif; + font-size: 12px; +} + +/* @group Heading Levels */ + +h1 { + font-size: 150%; +} + +h2 { + font-size: 120%; +} + +h3 { + font-size: 100%; +} + +dt { + font-weight: bold; +} + +div.multicol { + -moz-column-gap: 1em; + -webkit-column-gap: 1em; + -moz-column-count: 3; + -webkit-column-count: 3; +} + +p.startli, p.startdd, p.starttd { + margin-top: 2px; +} + +p.endli { + margin-bottom: 0px; +} + +p.enddd { + margin-bottom: 4px; +} + +p.endtd { + margin-bottom: 2px; +} + +/* @end */ + +caption { + font-weight: bold; +} + +span.legend { + font-size: 70%; + text-align: center; +} + +h3.version { + font-size: 90%; + text-align: center; +} + +div.qindex, div.navtab{ + background-color: #EBEFF6; + border: 1px solid #A3B4D7; + text-align: center; + margin: 2px; + padding: 2px; +} + +div.qindex, div.navpath { + width: 100%; + line-height: 140%; +} + +div.navtab { + margin-right: 15px; +} + +/* @group Link Styling */ + +a { + color: #3D578C; + font-weight: normal; + text-decoration: none; +} + +.contents a:visited { + color: #4665A2; +} + +a:hover { + text-decoration: underline; +} + +a.qindex { + font-weight: bold; +} + +a.qindexHL { + font-weight: bold; + background-color: #9CAFD4; + color: #ffffff; + border: 1px double #869DCA; +} + +.contents a.qindexHL:visited { + color: #ffffff; +} + +a.el { + font-weight: bold; +} + +a.elRef { +} + +a.code { + color: #4665A2; +} + +a.codeRef { + color: #4665A2; +} + +/* @end */ + +dl.el { + margin-left: -1cm; +} + +.fragment { + font-family: monospace, fixed; + font-size: 105%; +} + +pre.fragment { + border: 1px solid #C4CFE5; + background-color: #FBFCFD; + padding: 4px 6px; + margin: 4px 8px 4px 2px; + overflow: auto; + word-wrap: break-word; + font-size: 9pt; + line-height: 125%; +} + +div.ah { + background-color: black; + font-weight: bold; + color: #ffffff; + margin-bottom: 3px; + margin-top: 3px; + padding: 0.2em; + border: solid thin #333; + border-radius: 0.5em; + -webkit-border-radius: .5em; + -moz-border-radius: .5em; + box-shadow: 2px 2px 3px #999; + -webkit-box-shadow: 2px 2px 3px #999; + -moz-box-shadow: rgba(0, 0, 0, 0.15) 2px 2px 2px; + background-image: -webkit-gradient(linear, left top, left bottom, from(#eee), to(#000),color-stop(0.3, #444)); + background-image: -moz-linear-gradient(center top, #eee 0%, #444 40%, #000); +} + +div.groupHeader { + margin-left: 16px; + margin-top: 12px; + font-weight: bold; +} + +div.version { + border:1px solid #0000FF; + color: #CCCCCC; + font-family: Arial, Helvetica, sans-serif; + font-size: 9pt; + text-align: center; + width:100px; + -moz-border-radius: 8px; + margin: 5px; +} + +div.footer1 { + background-color: #DFE5F1; + border: 1px solid #AAAAAA; + font-family: Arial, Helvetica, sans-serif; + font-size: 11px; + padding: 10px; + margin-top: 15px; +} + + +div.groupText { + margin-left: 16px; + font-style: italic; +} + +body { + background: white; + color: black; + margin: 0; +} + +div.contents { + margin-top: 10px; + margin-left: 10px; + margin-right: 10px; +} + +td.indexkey { + background-color: #EBEFF6; + font-weight: bold; + border: 1px solid #C4CFE5; + margin: 2px 0px 2px 0; + padding: 2px 10px; +} + +td.indexvalue { + background-color: #EBEFF6; + border: 1px solid #C4CFE5; + padding: 2px 10px; + margin: 2px 0px; +} + +tr.memlist { + background-color: #EEF1F7; +} + +p.formulaDsp { + text-align: center; +} + +img.formulaDsp { + +} + +img.formulaInl { + vertical-align: middle; +} + +div.center { + text-align: center; + margin-top: 0px; + margin-bottom: 0px; + padding: 0px; +} + +div.center img { + border: 0px; +} + +address.footer { + text-align: right; + padding-right: 12px; +} + +img.footer { + border: 0px; + vertical-align: middle; +} + +/* @group Code Colorization */ + +span.keyword { + color: #008000 +} + +span.keywordtype { + color: #604020 +} + +span.keywordflow { + color: #e08000 +} + +span.comment { + color: #800000 +} + +span.preprocessor { + color: #806020 +} + +span.stringliteral { + color: #002080 +} + +span.charliteral { + color: #008080 +} + +span.vhdldigit { + color: #ff00ff +} + +span.vhdlchar { + color: #000000 +} + +span.vhdlkeyword { + color: #700070 +} + +span.vhdllogic { + color: #ff0000 +} + +/* @end */ + +/* +.search { + color: #003399; + font-weight: bold; +} + +form.search { + margin-bottom: 0px; + margin-top: 0px; +} + +input.search { + font-size: 75%; + color: #000080; + font-weight: normal; + background-color: #e8eef2; +} +*/ + +td.tiny { + font-size: 75%; +} + +.dirtab { + padding: 4px; + border-collapse: collapse; + border: 1px solid #A3B4D7; +} + +th.dirtab { + background: #EBEFF6; + font-weight: bold; +} + +hr { + height: 0px; + border: none; + border-top: 1px solid #4A6AAA; +} + +hr.footer { + height: 1px; +} + +/* @group Member Descriptions */ + +table.memberdecls { + border-spacing: 0px; + padding: 0px; +} + +.mdescLeft, .mdescRight, +.memItemLeft, .memItemRight, +.memTemplItemLeft, .memTemplItemRight, .memTemplParams { + background-color: #F9FAFC; + border: none; + margin: 4px; + padding: 1px 0 0 8px; +} + +.mdescLeft, .mdescRight { + padding: 0px 8px 4px 8px; + color: #555; +} + +.memItemLeft, .memItemRight, .memTemplParams { + border-top: 1px solid #C4CFE5; +} + +.memItemLeft, .memTemplItemLeft { + white-space: nowrap; +} + +.memTemplParams { + color: #4665A2; + white-space: nowrap; +} + +/* @end */ + +/* @group Member Details */ + +/* Styles for detailed member documentation */ + +.memtemplate { + font-size: 80%; + color: #4665A2; + font-weight: normal; + margin-left: 9px; +} + +.memnav { + background-color: #EBEFF6; + border: 1px solid #A3B4D7; + text-align: center; + margin: 2px; + margin-right: 15px; + padding: 2px; +} + +.memitem { + padding: 0; + margin-bottom: 10px; +} + +.memname { + white-space: nowrap; + font-weight: bold; + margin-left: 6px; +} + +.memproto { + border-top: 1px solid #A8B8D9; + border-left: 1px solid #A8B8D9; + border-right: 1px solid #A8B8D9; + padding: 6px 0px 6px 0px; + color: #253555; + font-weight: bold; + text-shadow: 0px 1px 1px rgba(255, 255, 255, 0.9); + /* opera specific markup */ + box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); + border-top-right-radius: 8px; + border-top-left-radius: 8px; + /* firefox specific markup */ + -moz-box-shadow: rgba(0, 0, 0, 0.15) 5px 5px 5px; + -moz-border-radius-topright: 8px; + -moz-border-radius-topleft: 8px; + /* webkit specific markup */ + -webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); + -webkit-border-top-right-radius: 8px; + -webkit-border-top-left-radius: 8px; + background-image:url('nav_f.png'); + background-repeat:repeat-x; + background-color: #E2E8F2; + +} + +.memdoc { + border-bottom: 1px solid #A8B8D9; + border-left: 1px solid #A8B8D9; + border-right: 1px solid #A8B8D9; + padding: 2px 5px; + background-color: #FBFCFD; + border-top-width: 0; + /* opera specific markup */ + border-bottom-left-radius: 8px; + border-bottom-right-radius: 8px; + box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); + /* firefox specific markup */ + -moz-border-radius-bottomleft: 8px; + -moz-border-radius-bottomright: 8px; + -moz-box-shadow: rgba(0, 0, 0, 0.15) 5px 5px 5px; + background-image: -moz-linear-gradient(center top, #FFFFFF 0%, #FFFFFF 60%, #F7F8FB 95%, #EEF1F7); + /* webkit specific markup */ + -webkit-border-bottom-left-radius: 8px; + -webkit-border-bottom-right-radius: 8px; + -webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); + background-image: -webkit-gradient(linear,center top,center bottom,from(#FFFFFF), color-stop(0.6,#FFFFFF), color-stop(0.60,#FFFFFF), color-stop(0.95,#F7F8FB), to(#EEF1F7)); +} + +.paramkey { + text-align: right; +} + +.paramtype { + white-space: nowrap; +} + +.paramname { + color: #602020; + white-space: nowrap; +} +.paramname em { + font-style: normal; +} + +.params, .retval, .exception, .tparams { + border-spacing: 6px 2px; +} + +.params .paramname, .retval .paramname { + font-weight: bold; + vertical-align: top; +} + +.params .paramtype { + font-style: italic; + vertical-align: top; +} + +.params .paramdir { + font-family: "courier new",courier,monospace; + vertical-align: top; +} + + + + +/* @end */ + +/* @group Directory (tree) */ + +/* for the tree view */ + +.ftvtree { + font-family: sans-serif; + margin: 0px; +} + +/* these are for tree view when used as main index */ + +.directory { + font-size: 9pt; + font-weight: bold; + margin: 5px; +} + +.directory h3 { + margin: 0px; + margin-top: 1em; + font-size: 11pt; +} + +/* +The following two styles can be used to replace the root node title +with an image of your choice. Simply uncomment the next two styles, +specify the name of your image and be sure to set 'height' to the +proper pixel height of your image. +*/ + +/* +.directory h3.swap { + height: 61px; + background-repeat: no-repeat; + background-image: url("yourimage.gif"); +} +.directory h3.swap span { + display: none; +} +*/ + +.directory > h3 { + margin-top: 0; +} + +.directory p { + margin: 0px; + white-space: nowrap; +} + +.directory div { + display: none; + margin: 0px; +} + +.directory img { + vertical-align: -30%; +} + +/* these are for tree view when not used as main index */ + +.directory-alt { + font-size: 100%; + font-weight: bold; +} + +.directory-alt h3 { + margin: 0px; + margin-top: 1em; + font-size: 11pt; +} + +.directory-alt > h3 { + margin-top: 0; +} + +.directory-alt p { + margin: 0px; + white-space: nowrap; +} + +.directory-alt div { + display: none; + margin: 0px; +} + +.directory-alt img { + vertical-align: -30%; +} + +/* @end */ + +div.dynheader { + margin-top: 8px; +} + +address { + font-style: normal; + color: #2A3D61; +} + +table.doxtable { + border-collapse:collapse; +} + +table.doxtable td, table.doxtable th { + border: 1px solid #2D4068; + padding: 3px 7px 2px; +} + +table.doxtable th { + background-color: #374F7F; + color: #FFFFFF; + font-size: 110%; + padding-bottom: 4px; + padding-top: 5px; + text-align:left; +} + +.tabsearch { + top: 0px; + left: 10px; + height: 36px; + background-image: url('tab_b.png'); + z-index: 101; + overflow: hidden; + font-size: 13px; +} + +.navpath ul +{ + font-size: 11px; + background-image:url('tab_b.png'); + background-repeat:repeat-x; + height:30px; + line-height:30px; + color:#8AA0CC; + border:solid 1px #C2CDE4; + overflow:hidden; + margin:0px; + padding:0px; +} + +.navpath li +{ + list-style-type:none; + float:left; + padding-left:10px; + padding-right:15px; + background-image:url('bc_s.png'); + background-repeat:no-repeat; + background-position:right; + color:#364D7C; +} + +.navpath li.navelem a +{ + height:32px; + display:block; + text-decoration: none; + outline: none; +} + +.navpath li.navelem a:hover +{ + color:#6884BD; +} + +.navpath li.footer +{ + list-style-type:none; + float:right; + padding-left:10px; + padding-right:15px; + background-image:none; + background-repeat:no-repeat; + background-position:right; + color:#364D7C; + font-size: 8pt; +} + + +div.summary +{ + float: right; + font-size: 8pt; + padding-right: 5px; + width: 50%; + text-align: right; +} + +div.summary a +{ + white-space: nowrap; +} + +div.ingroups +{ + font-size: 8pt; + padding-left: 5px; + width: 50%; + text-align: left; +} + +div.ingroups a +{ + white-space: nowrap; +} + +div.header +{ + background-image:url('nav_h.png'); + background-repeat:repeat-x; + background-color: #F9FAFC; + margin: 0px; + border-bottom: 1px solid #C4CFE5; +} + +div.headertitle +{ + padding: 5px 5px 5px 10px; +} + +.title { + font-size: 150%; + font-weight: bold; + margin: 10px 2px; +} + +dl +{ + padding: 0 0 0 10px; +} + +dl.note, dl.warning, dl.attention, dl.pre, dl.post, dl.invariant, dl.deprecated, dl.todo, dl.test, dl.bug +{ + border-left:4px solid; + padding: 0 0 0 6px; +} + +dl.note +{ + border-color: #D0D000; +} + +dl.warning, dl.attention +{ + border-color: #FF0000; +} + +dl.pre, dl.post, dl.invariant +{ + border-color: #00D000; +} + +dl.deprecated +{ + border-color: #505050; +} + +dl.todo +{ + border-color: #00C0E0; +} + +dl.test +{ + border-color: #3030E0; +} + +dl.bug +{ + border-color: #C08050; +} + +#projectlogo +{ + text-align: center; + vertical-align: bottom; + border-collapse: separate; +} + +#projectlogo img +{ + border: 0px none; +} + +#projectname +{ + background-color: #175783; + border: 1px solid; + height: 80px; + background-repeat: no-repeat; +/* font: 300% arial,sans-serif;*/ + margin: 0px; + padding: 0px; +} + +#projectbrief +{ + font: 120% arial,sans-serif; + margin: 0px; + padding: 0px; +} + +#projectnumber +{ + font: 50% arial,sans-serif; + margin: 0px; + padding: 0px; +} + +#titlearea +{ + background: url("head.png"); + background-color: #175783; + border: 1px solid; + height: 80px; + background-repeat: no-repeat; + padding: 0px; + margin: 0px; + width: 100%; + border-bottom: 1px solid #5373B4; +} + diff --git a/doc/salome/gui/static/header.html.in b/doc/salome/gui/static/header.html.in new file mode 100755 index 000000000..4571b4363 --- /dev/null +++ b/doc/salome/gui/static/header.html.in @@ -0,0 +1,20 @@ + + + + + +$title + +$treeview +$search +$mathjax + + + + +
+
Version: @VERSION@
+ +
diff --git a/doc/salome/tui/images/guiscreen.png b/doc/salome/tui/images/guiscreen.png new file mode 100644 index 000000000..bc900e206 Binary files /dev/null and b/doc/salome/tui/images/guiscreen.png differ diff --git a/doc/salome/tui/images/head.png b/doc/salome/tui/images/head.png new file mode 100755 index 000000000..307d9ef9a Binary files /dev/null and b/doc/salome/tui/images/head.png differ diff --git a/doc/salome/tui/static/header.html.in b/doc/salome/tui/static/header.html.in new file mode 100755 index 000000000..4571b4363 --- /dev/null +++ b/doc/salome/tui/static/header.html.in @@ -0,0 +1,20 @@ + + + + + +$title + +$treeview +$search +$mathjax + + + + +
+
Version: @VERSION@
+ +
diff --git a/src/CAF/resources/CAF_msg_fr.ts b/src/CAF/resources/CAF_msg_fr.ts new file mode 100644 index 000000000..a1a8505b9 --- /dev/null +++ b/src/CAF/resources/CAF_msg_fr.ts @@ -0,0 +1,59 @@ + + + + + CAF_Application + + MEN_APP_EDIT + &Editer + + + INF_ALL_FILTER + Tous les fichiers (*.*) + + + INF_ALL_DOCUMENTS_FILTER + Tous les documents lisibles + + + MEN_DESK_EDIT + &Editer + + + MEN_APP_EDIT_UNDO + &Défaire + + + MEN_APP_EDIT_REDO + &Refaire + + + PRP_APP_EDIT_REDO + Refaire la dernière opération + + + PRP_APP_EDIT_UNDO + Défaire la dernière opération + + + TOT_APP_EDIT_REDO + Refaire + + + TOT_APP_EDIT_UNDO + Défaire + + + INF_APP_REDOACTIONS + Refait %1 action(s) + + + INF_APP_UNDOACTIONS + Défait %1 action(s) + + + ABOUT_INFO + Application SUIT Caf + + + diff --git a/src/CAM/resources/CAM_msg_fr.ts b/src/CAM/resources/CAM_msg_fr.ts new file mode 100755 index 000000000..09e8fecd3 --- /dev/null +++ b/src/CAM/resources/CAM_msg_fr.ts @@ -0,0 +1,19 @@ + + + + + @default + + ERROR_TLT + Erreur + + + ERROR_ACTIVATE_MODULE_MSG + Impossible d'activer le module %1 + + + MODULE_ROOT_OBJECT_TOOLTIP + %1 objet-racine du module + + + diff --git a/src/GLViewer/resources/GLViewer_msg_fr.ts b/src/GLViewer/resources/GLViewer_msg_fr.ts new file mode 100755 index 000000000..32fea6fa1 --- /dev/null +++ b/src/GLViewer/resources/GLViewer_msg_fr.ts @@ -0,0 +1,117 @@ + + + + + @default + + DSC_FITSELECT + Montrer la zone choisie dans la vue + + + ERROR + Erreur + + + MNU_DUMP_VIEW + Sauvegarder + + + MNU_PAN_VIEW + Déplacement + + + DSC_GLOBALPAN_VIEW + Sélection d'un nouveau centre de vue + + + MNU_ZOOM_VIEW + Zoomer + + + DSC_PAN_VIEW + Déplacer la vue + + + DSC_FITALL + Montrer tous les objets dans la vue + + + MNU_FITALL + Tout afficher + + + MNU_GLOBALPAN_VIEW + Déplacement global + + + INF_APP_DUMP_VIEW + Sauvegarder la vue + + + GL_IMAGE_FILES + Fichiers images (*.bmp *.png) + + + MNU_RESET_VIEW + Restaurer + + + DSC_FITRECT + Montrer la zone dans la vue + + + MNU_FITRECT + Afficher la zone + + + CHANGE_BGCOLOR + Changer la couleur d'arrière-plan... + + + DSC_DUMP_VIEW + Sauvegarder la vue en cours dans un fichier image + + + MNU_FITSELECT + Afficher la sélection + + + DSC_ZOOM_VIEW + Zoomer la vue + + + DSC_RESET_VIEW + Restaurer le point de vue + + + ERR_DOC_CANT_SAVE_FILE + Impossible de sauvegarder le fichier + + + LBL_TOOLBAR_LABEL + Opérations de visualisation + + + + GLViewer_ViewFrame + + DUMP_VIEW_SAVE_FILE_DLG_CAPTION + Sauvegarder la vue dans le fichier + + + DUMP_VIEW_ERROR_DLG_TEXT + Impossible de sauvegarder la vue dans le fichier + + + DUMP_VIEW_ERROR_DLG_CAPTION + Erreur + + + + GLViewer_ViewManager + + GL_VIEW_TITLE + Scène GL:%M - visualiseur:%V + + + diff --git a/src/LightApp/LightApp.qrc b/src/LightApp/LightApp.qrc new file mode 100644 index 000000000..ffcce9a7b --- /dev/null +++ b/src/LightApp/LightApp.qrc @@ -0,0 +1,7 @@ + + + images/en.png + images/fr.png + + + diff --git a/src/LightApp/LightApp_FullScreenHelper.cxx b/src/LightApp/LightApp_FullScreenHelper.cxx new file mode 100644 index 000000000..a64f864f3 --- /dev/null +++ b/src/LightApp/LightApp_FullScreenHelper.cxx @@ -0,0 +1,189 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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: LightApp_FullScreenHelper.h +// Created: 04/10/2011 18:44:25 PM +// Author: OCC team +// +#include +#include +#include + +#include + +#include + +#include +#include +#include + +#include "LightApp_FullScreenHelper.h" +#include "LightApp_Application.h" + + +/*! + * Constructor + */ +LightApp_FullScreenHelper::LightApp_FullScreenHelper() +{ + myStatusBarVisibility = false; +} + +/*! + * Destructor + */ +LightApp_FullScreenHelper::~LightApp_FullScreenHelper() +{ + +} + + +/*! + * Switch application to the full screen mode. + */ +void LightApp_FullScreenHelper::switchToFullScreen() { + + SUIT_Session* session = SUIT_Session::session(); + if(!session) + return; + + LightApp_Application* app = dynamic_cast( session->activeApplication() ); + + if(!app) + return; + + SUIT_Desktop* desktop = app->desktop(); + + if(!desktop) + return; + + desktop->setWindowState(desktop->windowState() ^ Qt::WindowFullScreen); + + if(desktop->menuBar()) + desktop->menuBar()->hide(); + + if(desktop->statusBar()) { + myStatusBarVisibility = desktop->statusBar()->isVisible(); + desktop->statusBar()->hide(); + QAction *act = app->action(STD_Application::ViewStatusBarId); + if(act) + act->setEnabled(false); + } + + + QList aDocWidgets = desktop->findChildren(); + myDocWidgetMap.clear(); + + QWidget* ob = app->objectBrowser(); + QObject* obParent = ob ? ob->parent() : 0; + + foreach(QDockWidget* aWidget, aDocWidgets) { + if(aWidget && aWidget->parent() == desktop) { + if( aWidget->isVisible() && aWidget != obParent ) { + aWidget->hide(); + QAction* act = aWidget->toggleViewAction(); + bool isActionEnabled = false; + if(act) { + isActionEnabled = act->isEnabled(); + if( isActionEnabled ) { + act->setEnabled(false); + } + } + + myDocWidgetMap.insert(aWidget, isActionEnabled); + } + } + } + + QList aToolBars = desktop->findChildren(); + myToolBarMap.clear(); + foreach(QToolBar* aWidget, aToolBars ) { + if( aWidget && aWidget->parent() == desktop ) { + if( aWidget->isVisible()) { + aWidget->hide(); + QAction* act = aWidget->toggleViewAction(); + bool isActionEnabled = false; + if(act) { + isActionEnabled = act->isEnabled(); + if( isActionEnabled ) { + act->setEnabled(false); + } + } + myToolBarMap.insert(aWidget, isActionEnabled); + } + } + } +} + +/*! + * Switch application to the normal screen mode. + */ +void LightApp_FullScreenHelper::switchToNormalScreen() { + + SUIT_Session* session = SUIT_Session::session(); + if(!session) + return; + + LightApp_Application* app = dynamic_cast( session->activeApplication() ); + + if(!app) + return; + + SUIT_Desktop* desktop = app->desktop(); + + if(!desktop) + return; + + desktop->setWindowState(desktop->windowState() ^ Qt::WindowFullScreen); + + + DocWidgetMap::iterator it = myDocWidgetMap.begin(); + for( ;it != myDocWidgetMap.end() ; it++ ) { + QDockWidget* aWidget = it.key(); + bool state = it.value(); + aWidget->show(); + QAction* act = aWidget->toggleViewAction(); + if(act && state) + act->setEnabled(true); + } + + ToolBarMap::iterator it1 = myToolBarMap.begin(); + for( ;it1 != myToolBarMap.end() ; it1++ ) { + QToolBar* aWidget = it1.key(); + bool state = it1.value(); + aWidget->show(); + QAction* act = aWidget->toggleViewAction(); + if(act && state) + act->setEnabled(true); + } + + if(desktop->menuBar()) + desktop->menuBar()->show(); + + if(desktop->statusBar() && myStatusBarVisibility) { + desktop->statusBar()->show(); + QAction *act = app->action(STD_Application::ViewStatusBarId); + if(act) + act->setEnabled(true); + } + +} diff --git a/src/LightApp/LightApp_FullScreenHelper.h b/src/LightApp/LightApp_FullScreenHelper.h new file mode 100644 index 000000000..3a8c0b869 --- /dev/null +++ b/src/LightApp/LightApp_FullScreenHelper.h @@ -0,0 +1,59 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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: LightApp_FullScreenHelper.h +// Created: 04/10/2011 18:39:25 PM +// Author: OCC team +// +#ifndef LIGHTAPP_FULLSCREEN_H +#define LIGHTAPP_FULLSCREEN_H + +#include "LightApp.h" + +#include +#include +#include + + +class LIGHTAPP_EXPORT LightApp_FullScreenHelper { + public: + + LightApp_FullScreenHelper(); + ~LightApp_FullScreenHelper(); + + void switchToFullScreen(); + void switchToNormalScreen(); + + private: + typedef QMap DocWidgetMap; + DocWidgetMap myDocWidgetMap; + + typedef QMap ToolBarMap; + ToolBarMap myToolBarMap; + + + bool myStatusBarVisibility; + +}; + + +#endif //LIGHTAPP_FULLSCREEN_H diff --git a/src/LightApp/LightApp_PyInterp.cxx b/src/LightApp/LightApp_PyInterp.cxx new file mode 100644 index 000000000..7b1ca1cb2 --- /dev/null +++ b/src/LightApp/LightApp_PyInterp.cxx @@ -0,0 +1,102 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 : Roman NIKOLAEV, Open CASCADE S.A.S. (roman.nikolaev@opencascade.com) +// Date : 22/06/2007 +// +#include "LightApp_PyInterp.h" + +#include +#include + +#include + +/*! + * constructor : multi Python interpreter, one per SALOME study. + * calls initialize method defined in base class, which calls virtual methods + * initstate & initcontext redefined here. + */ +LightApp_PyInterp::LightApp_PyInterp(): PyConsole_Interp() +{ +} + +/*! + * Destructor. + */ +LightApp_PyInterp::~LightApp_PyInterp() +{ +} + +/*!\class LightApp_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 LightApp_PyInterp::initContext() +{ + /*! + * 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 + */ + if ( !PyConsole_Interp::initContext() ) + return false; + + //Import special module to change the import mechanism + PyObjWrapper m1( PyImport_ImportModule( "import_hook" ) ); + if ( !m1 ) + { + PyErr_Print(); + return false; + } + + // Call init_shared_modules to initialize the shared import mechanism for modules + //that must not be imported twice + PyObjWrapper m2( PyObject_CallMethod( m1, (char*)"init_shared_modules", (char*)"O", SUIT_PYTHON::salome_shared_modules_module ) ); + if ( !m2 ) + { + PyErr_Print(); + return false; + } + return true; +} + +/*! + Do nothing + The initialization has been done in main + */ +void LightApp_PyInterp::initPython() +{ + _gtstate=SUIT_PYTHON::_gtstate; // initialisation in main + _interp=SUIT_PYTHON::_interp; +} diff --git a/src/LightApp/LightApp_PyInterp.h b/src/LightApp/LightApp_PyInterp.h new file mode 100644 index 000000000..813d3342d --- /dev/null +++ b/src/LightApp/LightApp_PyInterp.h @@ -0,0 +1,39 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 : Roman NIKOLAEV, Open CASCADE S.A.S. (roman.nikolaev@opencascade.com) +// Date : 22/06/2007 +// +#ifndef _LIGHTAPP_PYINTERP_H_ +#define _LIGHTAPP_PYINTERP_H_ + +#include // this include must be first (see PyInterp_base.h)! + +class LightApp_PyInterp : public PyConsole_Interp +{ +public: + LightApp_PyInterp(); + virtual ~LightApp_PyInterp(); + +protected: + virtual void initPython(); + virtual bool initContext(); +}; + +#endif //_LIGHTAPP_PYINTERP_H_ diff --git a/src/LightApp/LightApp_WgViewModel.cxx b/src/LightApp/LightApp_WgViewModel.cxx new file mode 100644 index 000000000..cffcd1f9a --- /dev/null +++ b/src/LightApp/LightApp_WgViewModel.cxx @@ -0,0 +1,54 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : LightApp_LightApp_WgViewModel.cxx +// Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com) + +#include "LightApp_WgViewModel.h" +#include "SUIT_ViewWindow.h" + +LightApp_WgViewModel::LightApp_WgViewModel( const QString& type, QWidget* w ) + : SUIT_ViewModel(), + myType( type ), + myWidget( w ), + myCreated( false ) +{ +} + +LightApp_WgViewModel::~LightApp_WgViewModel() +{ +} + +SUIT_ViewWindow* LightApp_WgViewModel::createView( SUIT_Desktop* d ) +{ + SUIT_ViewWindow* vw = 0; + if ( !myCreated ) { + vw = new SUIT_ViewWindow( d ); + vw->setCentralWidget( myWidget ); + myCreated = true; + } + return vw; +} + +QString LightApp_WgViewModel::getType() const +{ + return myType; +} diff --git a/src/LightApp/LightApp_WgViewModel.h b/src/LightApp/LightApp_WgViewModel.h new file mode 100644 index 000000000..cedc4857e --- /dev/null +++ b/src/LightApp/LightApp_WgViewModel.h @@ -0,0 +1,47 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : LightApp_LightApp_WgViewModel.h +// Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com) + +#ifndef LIGHTAPP_WGVIEWMODEL_H +#define LIGHTAPP_WGVIEWMODEL_H + +#include "SUIT_ViewModel.h" +#include "SUIT_ViewManager.h" + +class LightApp_WgViewModel : public SUIT_ViewModel +{ + Q_OBJECT + +public: + LightApp_WgViewModel( const QString& type, QWidget* w ); + virtual ~LightApp_WgViewModel(); + + virtual SUIT_ViewWindow* createView( SUIT_Desktop* d ); + virtual QString getType() const; + +private: + QString myType; + QWidget* myWidget; + bool myCreated; +}; +#endif // LIGHTAPP_WGVIEWMODEL_H diff --git a/src/LightApp/resources/LightApp_msg_fr.ts b/src/LightApp/resources/LightApp_msg_fr.ts new file mode 100755 index 000000000..3506f41ca --- /dev/null +++ b/src/LightApp/resources/LightApp_msg_fr.ts @@ -0,0 +1,935 @@ + + + + + @default + + EXTERNAL_BROWSER_CANNOT_SHOW_PAGE + Le navigateur externe "%1" ne peut pas trouver la page d'aide "%2". Voulez-vous le modifierdans les préférences ? + + + ABOUT_COPYRIGHT + Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE + +Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, +CEA/DEN, CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS + + + ABOUT_CAPTION + A propos de %1 + + + ABOUT_BASE + Informations générales + + + ABOUT_MODULE_INFOS + Modules + + + ABOUT_UNKNOWN_VERSION + Inconnue + + + ABOUT_CLOSE + &Fermer + + + APP_NAME + SALOME + + + ABOUT_LICENSE + GNU LGPL + + + ABOUT_VERSION + Version %1 + + + ENTRY_COLUMN + Entrée + + + BROWSER_TITLE + Aide de SALOME + + + BROWSER_TOOLBAR_TITLE + Navigation + + + BROWSER_FILEMENU + &Fichier + + + BROWSER_CLOSE + &Fermer + + + BROWSER_BACK + Reculer + + + BROWSER_FORWARD + Avancer + + + BROWSER_FIND + &Chercher... + + + BROWSER_FINDNEXT + Chercher &suivant + + + BROWSER_FINDPREV + Chercher &précédent + + + + LightApp_Application + + LANG_CHANGED + La langue de l'application a été modifié. +Les modifications seront appliquées à la prochaine session. + + + MEN_DESK_THEME + T&hème + + + TOT_THEME + Thème + + + PRP_THEME + Changer les propriétés du style + + + TOT_FULLSCREEN + Plein écran + + + MEN_DESK_FULLSCREEN + Plein écran + + + PRP_FULLSCREEN + Basculer en mode plein écran + + + INF_TOOLBAR_MODULES + Modules + + + PREF_SHOW_LEGEND + Montrer la légende + + + MEN_DESK_RENAME + &Renommer + + + PREF_MULTI_FILE + Sauvegarde multi-fichiers + + + MEN_DESK_PREFERENCES + &Préférences... + + + PREF_TRIHEDRON_SHOW + Afficher le trièdre + + + PREF_TRIHEDRON + Trièdre + + + PREF_TRIHEDRON_SIZE + Taille + + + OBJECT_BROWSER + Arbre d'étude + + + PRP_DESK_PREFERENCES + Permettre de changer les préférences + + + PREF_GROUP_DIRECTORIES + Liste des répertoires + + + PREF_GROUP_VTKVIEWER + Scène VTK 3D + + + PREF_STORE_POS + Enregistrer la position des fenêtres + + + PREF_AUTO_SAVE + Intervalle d'enregistrement automatique (min) + + + PREF_AUTO_SAVE_DISABLED + Désactivé + + + PREF_PROJECTION_MODE + Mode de projection: + + + PREF_ORTHOGRAPHIC + Orthogonal + + + PREF_PERSPECTIVE + Perspective + + + PREF_NAVIGATION + Navigation: + + + PREF_STANDARD_STYLE + Style de contrôles type Salomé + + + PREF_KEYFREE_STYLE + Style sans clavier + + + PREF_ZOOMING + Mode de zoom: + + + PREF_ZOOMING_AT_CENTER + Relatif au centre de la scène + + + PREF_ZOOMING_AT_CURSOR + Relatif au curseur + + + PREF_INCREMENTAL_SPEED + Incrément de vitesse: + + + PREF_INCREMENTAL_SPEED_MODE + Mode de modification: + + + PREF_ARITHMETIC + Progression arithmétique + + + PREF_GEOMETRICAL + Progression géométrique + + + PREF_FRAME_SPACEMOUSE + Spacemouse + + + PREF_SHOW_STATIC_TRIHEDRON + Montrer le trièdre statique + + + PREF_SPACEMOUSE_FUNC_1 + Réduire l'incrément de vitesse + + + PREF_SPACEMOUSE_FUNC_2 + Augmenter l'incrément de vitesse + + + PREF_SPACEMOUSE_FUNC_3 + Changement Dominant/Combiné + + + PREF_SPACEMOUSE_BTN_1 + Bouton 1 + + + PREF_SPACEMOUSE_BTN_2 + Bouton 2 + + + PREF_SPACEMOUSE_BTN_3 + Bouton 3 + + + PREF_SPACEMOUSE_BTN_4 + Bouton 4 + + + PREF_SPACEMOUSE_BTN_5 + Bouton 5 + + + PREF_SPACEMOUSE_BTN_6 + Bouton 6 + + + PREF_SPACEMOUSE_BTN_7 + Bouton 7 + + + PREF_SPACEMOUSE_BTN_8 + Bouton 8 + + + PREF_SPACEMOUSE_BTN_* + Bouton * + + + PREF_SPACEMOUSE_BTN_10 + Bouton 10 + + + PREF_SPACEMOUSE_BTN_11 + Bouton 11 + + + PREF_FRAME_RECORDING + Enregistrement AVI + + + PREF_ALL_DISLPAYED_FRAMES + Enregistrer toutes les images affichées + + + PREF_FPS + FPS + + + PREF_GROUP_TTL + Paramètres + + + PREF_PROGRESSIVE + Progressif + + + PREF_QUALITY + Qualité + + + PREF_RECORDING_MODE + Mode + + + PREF_SKIPPED_FRAMES + Enregistrer à FPS donné + + + PREF_FRAME_GROUP_NAMES + Nom des groupes + + + PREF_GROUP_NAMES_TEXT_COLOR + Couleur du texte + + + PREF_GROUP_NAMES_TRANSPARENCY + Transparence + + + PREF_BOTTOM + Dessous + + + PREF_CURVE_TYPE + Type de courbe: + + + PREF_ISOS + Nombre d'isolignes + + + PREF_ISOS_U + Selon U + + + PREF_ISOS_V + Selon V + + + PREF_POINTS + Points + + + PRP_MODULE + Basculer vers le module "%1" + + + PREF_ASCII_FILE + Enregistrement ASCII + + + PREFERENCES_NOT_LOADED + Les préférences du module "<b>%N</b>" seront accessibles quand le module sera chargé + + + PREF_LINEAR + Linéaire + + + DATA_MODELS + Modèles de données + + + PRP_RENAME + Renommer la fenêtre active + + + TOT_RENAME + Renommer + + + MEN_RENAME_OBJ + Renommer + + + LOG_WINDOW + Fenêtre de messages + + + PREF_SPLINE + Spline + + + PREF_OBJ_BROWSER_SEARCH_TOOL + Outil de recherche + + + PREF_AUTO_HIDE_SEARCH_TOOL + Cacher automatiquement + + + PREF_OBJ_BROWSER_SETTINGS + Paramètres de l'arbre d'étude + + + PRP_APP_MODULE + Basculer au point neutre de la plate-forme SALOME + + + PREF_GROUP_PY_CONSOLE + Propriétés de la console Python + + + PREF_SHOW_BANNER + Afficher la bannière + + + PREF_GROUP_STYLE + Style Salomé + + + PREF_USE_SALOME_STYLE + Utiliser le style Salomé + + + PREF_MARKER_SIZE + Taille de repère: + + + PREF_TAB_VIEWERS + Scènes + + + PREF_APP + Application + + + PREF_TOP + Dessus + + + MEN_REFRESH + Rafraîchir + + + PREF_AUTO_SIZE_FIRST + Taille automatique pour la colonne "Nom" + + + PREF_RESIZE_ON_EXPAND_ITEM + Redimensionner les colonnes quand l'objet est déplié + + + PREF_BROWSE_TO_THE_PUBLISHED_OBJECT + Se déplacer sur l'objet publié + + + PREF_BROWSE_NEVER + Jamais + + + PREF_BROWSE_AFTER_APPLY_AND_CLOSE_ONLY + Seulement après "Appliquer et Fermer" + + + PREF_BROWSE_ALWAYS + Toujours + + + PREF_GROUP_SUPERV + Superviseur des graphes + + + PREF_TAB_OBJBROWSER + Arbre d'étude + + + PREF_TAB_GENERAL + Général + + + NEW_WINDOW_0 + Scène &GL + + + NEW_WINDOW_1 + Scène &Plot2d + + + NEW_WINDOW_2 + Scène &OCC + + + NEW_WINDOW_3 + Scène VT&K + + + NEW_WINDOW_4 + Scène &QxGraph + + + NEW_WINDOW_5 + Scène Qx&Scene + + + CREATING_NEW_WINDOW + Créer une nouvelle %1 + + + OBJ_BROWSER_NAME + Objet + + + PREF_LEGEND_POSITION + Position de la Légende: + + + PREF_RELATIVE_SIZE + Relative + + + PREF_VIEWER_BACKGROUND + Arrière-plan + + + PREF_VIEWER_BACKGROUND_COLOR + Couleur de l'arrière-plan + + + PREF_VIEWER_SELECTION + Couleur de sélection + + + PREF_XYVIEWER_BACKGROUND + Vue XY + + + PREF_XZVIEWER_BACKGROUND + Vue XZ + + + PREF_YZVIEWER_BACKGROUND + Vue YZ + + + PREF_3DVIEWER_BACKGROUND + Vue 3D + + + PREF_FONT + Police + + + PREF_LEGEND_FONT + Police de la légende + + + PREF_FONT_COLOR + Couleur de police de la légende + + + PREF_SELECTED_FONT_COLOR + Couleur de surlignement de la légende + + + PREF_LEFT + Gauche + + + PREF_TAB_DIRECTORIES + Emplacements + + + ACTIVATING_MODULE + Activation du module "%1" en cours + + + PREF_VERT_AXIS_SCALE + Echelle de l'axe vertical : + + + PREF_HOR_AXIS_SCALE + Echelle de l'axe horizontal : + + + PREF_GROUP_LANGUAGE + Langue + + + PREF_CURRENT_LANGUAGE + Langue actuelle + + + PREF_GROUP_LOOK_AND_FEEL + Aspect + + + PREF_OPAQUE_RESIZE + Redimensionnement opaque + + + PREF_GROUP_STUDY + Propiétés de l'étude + + + PREF_CATEGORY_SALOME + SALOME + + + PREF_DROP_DOWN_BUTTONS + Boutons alignés dans la barre + + + PREF_GROUP_COMMON + Commun + + + PREF_GROUP_OCCVIEWER + Scène OCC 3D + + + PREF_LOGARITHMIC + Logarithmique + + + MEN_DESK_MODULE_HELP + Module &Aide + + + PREF_SUPERV_TITLE_COLOR + Couleur de titre + + + PREF_PARAM + Paramètres + + + PREF_RIGHT + Droite + + + PREF_LINES + Lignes + + + INF_CANCELLED + L'activation du module est annulée + + + PREF_GROUP_EXT_BROWSER + Navigateur externe + + + PREF_SUPERV_CTRL_COLOR + Couleur de contrôle + + + PREF_GROUP_DEF_COLUMNS + Colonnnes par défaut + + + PREF_GROUP_PLOT2DVIEWER + Scène Plot2d + + + PREF_DEVIATION_COLOR + Couleur des marqueurs de déviation + + + PREF_DEVIATION_MARKER_LW + Epaisseur des lignes des marqueurs de déviation + + + PREF_DEVIATION_MARKER_TS + Taille des coches des marqueurs de déviation + + + MEN_DESK_MRU + &Récemment utilisés + + + TOT_DESK_PREFERENCES + Préférences + + + DEFINE_EXTERNAL_BROWSER + Le navigateur externe n'est pas trouvé. Voulez-vous le définir dans les préférences? + + + PREF_AUTO_SIZE + Taille automatique pour les autres colonnes + + + TOT_DESK_MRU + Récemment utilisés + + + ACTIVATE_MODULE_OP_NEW + &Nouveau + + + ACTIVATE_MODULE_OP_OPEN + &Ouvrir... + + + PYTHON_CONSOLE + Console Python + + + PREF_DYNAMIC_PRESELECTION + Utiliser l'algorithme de sélection avancée + + + TOT_CLOSE + Fermer + + + MEN_DESK_CLOSE + &Fermer + + + PRP_CLOSE + Fermer la fenêtre active + + + TOT_CLOSE_ALL + Tout fermer + + + MEN_DESK_CLOSE_ALL + &Tout fermer + + + PRP_CLOSE_ALL + Fermer toutes les fenêtres + + + TOT_GROUP_ALL + Tout grouper + + + MEN_DESK_GROUP_ALL + Tout &grouper + + + PRP_GROUP_ALL + Grouper toutes les fenêtres + + + ERR_DOC_NOT_EXISTS + Impossible d'ouvrir %1. +Le fichier n'existe pas + + + PREF_GROUP_MRU + Montrer les études récemment utilisées + + + PREF_MRU_VISIBLE_COUNT + Nombre d'études + + + PREF_MRU_INSERT_MODE + Mode d'insertion + + + PREF_MRU_MOVE_FIRST + Placer au début + + + PREF_MRU_MOVE_LAST + Placer à la fin + + + PREF_MRU_ADD_FIRST + Ajouter au début + + + PREF_MRU_ADD_LAST + Ajouter à la fin + + + PREF_MRU_LINK_TYPE + Type de lien + + + PREF_MRU_LINK_AUTO + Auto + + + PREF_MRU_LINK_SHORT + Court + + + PREF_MRU_LINK_FULL + Complet + + + PREFERENCES_NOT_SUPPORTED + Les préférences du module "%1" ne sont pas supportées + + + PREF_TAB_SHORTCUTS + Raccourcis clavier + + + PREF_GROUP_SHORTCUTS + Réglage des raccourcis clavier + + + + LightApp_Module + + MEN_HIDE + Cacher + + + TOP_DISPLAY_ONLY + Afficher uniquement + + + STB_DISPLAY_ONLY + Afficher uniquement + + + MEN_DISPLAY_ONLY + Afficher uniquement + + + TOP_HIDE + Cacher + + + MEN_ERASE_ALL + Tout cacher + + + STB_HIDE + Cacher + + + STB_SHOW + Afficher + + + TOP_SHOW + Afficher + + + MEN_SHOW + Afficher + + + STB_ERASE_ALL + Tout cacher + + + TOP_ERASE_ALL + Tout cacher + + + + LightApp_ModuleDlg + + DESCRIPTION + Vous activez le module + <b>%1</b>.<br>Choisissez l'action nécessaire avec le bouton correspondant ci-dessous + + + CANCEL + &Annuler + + + CAPTION + Activer le module + + + + LightApp_NameDlg + + TLT_RENAME + Renommer + + + NAME_LBL + Nom: + + + + LightApp_PreferencesDlg + + IMPORT_PREFERENCES + Importer les préférences + + + CAPTION + Préférences + + + WARNING + Avertissement + + + IMPORT_BTN_TEXT + Importer + + + DEFAULT_QUESTION + Voulez-vous restaurer les préférences par défaut ? + + + DEFAULT_BTN_TEXT + Défauts + + + + LightApp_ModuleAction + + ACTIVATE_MODULE_TOP + Activer/désactiver le module %1 + + + diff --git a/src/LogWindow/resources/LogWindow_msg_fr.ts b/src/LogWindow/resources/LogWindow_msg_fr.ts new file mode 100755 index 000000000..1e6a59100 --- /dev/null +++ b/src/LogWindow/resources/LogWindow_msg_fr.ts @@ -0,0 +1,42 @@ + + + + + LogWindow + + + EDIT_COPY_CMD + &Copier + + + + EDIT_CLEAR_CMD + &Effacer + + + + EDIT_SELECTALL_CMD + &Tout sélectionner + + + + EDIT_SAVETOFILE_CMD + &Sauvegarder le journal dans un fichier... + + + + ERR_ERROR + Erreur + + + + ERR_CANT_SAVE_FILE + Impossible de sauvegarder le fichier + + + + BUT_OK + &OK + + + diff --git a/src/OCCViewer/OCCViewer_CubeAxesDlg.cxx b/src/OCCViewer/OCCViewer_CubeAxesDlg.cxx new file mode 100644 index 000000000..a37373729 --- /dev/null +++ b/src/OCCViewer/OCCViewer_CubeAxesDlg.cxx @@ -0,0 +1,321 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 +// + +#include "OCCViewer_CubeAxesDlg.h" + +#include "OCCViewer_FontWidget.h" +#include "OCCViewer_ViewPort3d.h" +#include "OCCViewer_ViewWindow.h" + +#include "QtxAction.h" +#include "QtxIntSpinBox.h" + +#include + +#include +#include +#include + +/*! + \class OCCViewer_CubeAxesDlg::AxisWidget + \brief Axis tab widget of the "Graduated axis" dialog box + \internal +*/ + +/*! + Constructor +*/ +OCCViewer_AxisWidget::OCCViewer_AxisWidget (QWidget* theParent) +: ViewerTools_AxisWidgetBase(theParent) +{ +} + +/*! + Destructor +*/ +OCCViewer_AxisWidget::~OCCViewer_AxisWidget() +{ +} + +/*! + Create font widget +*/ +ViewerTools_FontWidgetBase* OCCViewer_AxisWidget::createFontWidget( QWidget* theParent ) +{ + OCCViewer_FontWidget* aFontWidget = new OCCViewer_FontWidget( theParent ); + aFontWidget->Initialize(); + return aFontWidget; +} + +/*! + Set axis data +*/ +void OCCViewer_AxisWidget::SetData( const AxisData& theAxisData ) +{ + myNameGrp->setChecked( theAxisData.DrawName ); + myAxisName->setText( theAxisData.Name ); + myNameFont->SetData( theAxisData.NameColor, 0, false, false, false ); + + myLabelsGrp->setChecked( theAxisData.DrawValues ); + myLabelNumber->setValue( theAxisData.NbValues ); + myLabelOffset->setValue( theAxisData.Offset ); + myLabelsFont->SetData( theAxisData.Color, 0, false, false, false ); + + myTicksGrp->setChecked( theAxisData.DrawTickmarks ); + myTickLength->setValue( theAxisData.TickmarkLength ); +} + +/*! + Get axis data +*/ +void OCCViewer_AxisWidget::GetData( AxisData& theAxisData ) +{ + theAxisData.DrawName = myNameGrp->isChecked(); + theAxisData.Name = myAxisName->text(); + + int aNameFamily; + bool aNameBold, aNameItalic, aNameShadow; + myNameFont->GetData( theAxisData.NameColor, aNameFamily, aNameBold, aNameItalic, aNameShadow ); + + theAxisData.DrawValues = myLabelsGrp->isChecked(); + theAxisData.NbValues = myLabelNumber->value(); + theAxisData.Offset = myLabelOffset->value(); + + int aLabelFamily; + bool aLabelBold, aLabelItalic, aLabelShadow; + myLabelsFont->GetData( theAxisData.Color, aLabelFamily, aLabelBold, aLabelItalic, aLabelShadow ); + + theAxisData.DrawTickmarks = myTicksGrp->isChecked(); + theAxisData.TickmarkLength = myTickLength->value(); +} + +/* + Class : OCCViewer_CubeAxesDlg + Description : Dialog for specifying cube axes properties +*/ + +/*! + Constructor +*/ +OCCViewer_CubeAxesDlg::OCCViewer_CubeAxesDlg(QtxAction* theAction, + OCCViewer_ViewWindow* theParent, + const char* theName): + ViewerTools_CubeAxesDlgBase(theAction, + theParent, + theName), + myMainWindow(theParent) +{ +} + +/*! + Destructor +*/ +OCCViewer_CubeAxesDlg::~OCCViewer_CubeAxesDlg() +{ +} + +/*! + Create axis widget +*/ +ViewerTools_AxisWidgetBase* OCCViewer_CubeAxesDlg::createAxisWidget( QWidget* theParent ) +{ + OCCViewer_AxisWidget* anAxisWidget = new OCCViewer_AxisWidget( theParent ); + anAxisWidget->initialize(); + return anAxisWidget; +} + +/*! + Update dialog fields, connect signals and slots, show dialog +*/ +void OCCViewer_CubeAxesDlg::initialize() +{ + ViewerTools_CubeAxesDlgBase::initialize(); + + for( int i = 0; i < 3; i++ ) + { + if( OCCViewer_AxisWidget* anAxisWidget = dynamic_cast( myAxes[ i ] ) ) + { + OCCViewer_AxisWidget::AxisData anAxisData; + switch( i ) + { + case 0: + anAxisData.Name = "X"; + anAxisData.NameColor = anAxisData.Color = Qt::red; + break; + case 1: + anAxisData.Name = "Y"; + anAxisData.NameColor = anAxisData.Color = Qt::green; + break; + case 2: + anAxisData.Name = "Z"; + anAxisData.NameColor = anAxisData.Color = Qt::blue; + break; + } + anAxisData.DrawName = true; + anAxisData.DrawValues = true; + anAxisData.NbValues = 3; + anAxisData.Offset = 2; + anAxisData.DrawTickmarks = true; + anAxisData.TickmarkLength = 5; + anAxisWidget->SetData( anAxisData ); + } + } +} + +/*! + Update dialog fields, connect signals and slots, show dialog +*/ +void OCCViewer_CubeAxesDlg::Update() +{ + ViewerTools_CubeAxesDlgBase::Update(); +} + +/*! + Verify validity of entry data +*/ +bool OCCViewer_CubeAxesDlg::onApply() +{ + bool isOk = ViewerTools_CubeAxesDlgBase::onApply(); + + try + { + QWidget *aCurrWid = this->focusWidget(); + aCurrWid->clearFocus(); + aCurrWid->setFocus(); + + if( OCCViewer_ViewPort3d* aViewPort = myMainWindow->getViewPort() ) + { + Handle(V3d_View) aView = aViewPort->getView(); + if( !aView.IsNull() ) + ApplyData( aView ); + } + } + catch(...) + { + isOk = false; + } + + return isOk; +} + +/*! + Get graduated trihedron parameters +*/ +void OCCViewer_CubeAxesDlg::GetData( bool& theIsVisible, OCCViewer_AxisWidget::AxisData theAxisData[3] ) +{ + theIsVisible = myIsVisible->isChecked(); + for( int i = 0; i < 3; i++ ) + if( OCCViewer_AxisWidget* anAxisWidget = dynamic_cast( myAxes[ i ] ) ) + anAxisWidget->GetData( theAxisData[i] ); +} + +/*! + Set graduated trihedron parameters +*/ +void OCCViewer_CubeAxesDlg::SetData( bool theIsVisible, OCCViewer_AxisWidget::AxisData theAxisData[3] ) +{ + myIsVisible->setChecked( theIsVisible ); + for( int i = 0; i < 3; i++ ) + if( OCCViewer_AxisWidget* anAxisWidget = dynamic_cast( myAxes[ i ] ) ) + anAxisWidget->SetData( theAxisData[i] ); +} + +/*! + Apply graduated trihedron parameters +*/ +void OCCViewer_CubeAxesDlg::ApplyData( const Handle(V3d_View)& theView ) +{ +#if OCC_VERSION_LARGE > 0x06030009 // available only with OCC-6.3-sp10 and higher version + if( theView.IsNull() ) + return; + + if( myIsVisible->isChecked() ) + { + OCCViewer_AxisWidget::AxisData anAxisData[3]; + for( int i = 0; i < 3; i++ ) + if( OCCViewer_AxisWidget* anAxisWidget = dynamic_cast( myAxes[ i ] ) ) + anAxisWidget->GetData( anAxisData[i] ); + + // A gap used offset of axis names' offset + // (this hard-coded value will be removed when the + // font support will be introduced in OCC-6.4) + int aGap = 20; + + theView->GraduatedTrihedronDisplay( + anAxisData[0].Name.toLatin1().constData(), + anAxisData[1].Name.toLatin1().constData(), + anAxisData[2].Name.toLatin1().constData(), + anAxisData[0].DrawName, + anAxisData[1].DrawName, + anAxisData[2].DrawName, + anAxisData[0].DrawValues, + anAxisData[1].DrawValues, + anAxisData[2].DrawValues, + Standard_True, // draw grid + Standard_False, // draw axes + anAxisData[0].NbValues - 1, + anAxisData[1].NbValues - 1, + anAxisData[2].NbValues - 1, + anAxisData[0].Offset, + anAxisData[1].Offset, + anAxisData[2].Offset, + anAxisData[0].Offset + aGap, // see above + anAxisData[1].Offset + aGap, // see above + anAxisData[2].Offset + aGap, // see above + anAxisData[0].DrawTickmarks, + anAxisData[1].DrawTickmarks, + anAxisData[2].DrawTickmarks, + anAxisData[0].TickmarkLength, + anAxisData[1].TickmarkLength, + anAxisData[2].TickmarkLength, + Quantity_NOC_WHITE, // grid color + Quantity_Color( anAxisData[0].NameColor.redF(), + anAxisData[0].NameColor.greenF(), + anAxisData[0].NameColor.blueF(), + Quantity_TOC_RGB ), + Quantity_Color( anAxisData[1].NameColor.redF(), + anAxisData[1].NameColor.greenF(), + anAxisData[1].NameColor.blueF(), + Quantity_TOC_RGB ), + Quantity_Color( anAxisData[2].NameColor.redF(), + anAxisData[2].NameColor.greenF(), + anAxisData[2].NameColor.blueF(), + Quantity_TOC_RGB ), + Quantity_Color( anAxisData[0].Color.redF(), + anAxisData[0].Color.greenF(), + anAxisData[0].Color.blueF(), + Quantity_TOC_RGB ), + Quantity_Color( anAxisData[1].Color.redF(), + anAxisData[1].Color.greenF(), + anAxisData[1].Color.blueF(), + Quantity_TOC_RGB ), + Quantity_Color( anAxisData[2].Color.redF(), + anAxisData[2].Color.greenF(), + anAxisData[2].Color.blueF(), + Quantity_TOC_RGB ) ); + } + else + theView->GraduatedTrihedronErase(); + + theView->Redraw(); +#endif +} diff --git a/src/OCCViewer/OCCViewer_CubeAxesDlg.h b/src/OCCViewer/OCCViewer_CubeAxesDlg.h new file mode 100644 index 000000000..250e4ad91 --- /dev/null +++ b/src/OCCViewer/OCCViewer_CubeAxesDlg.h @@ -0,0 +1,99 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 +// + +#ifndef OCCVIEWER_CUBEAXESDLG_H +#define OCCVIEWER_CUBEAXESDLG_H + +#include "OCCViewer.h" + +#include + +#include + +class OCCViewer_ViewWindow; + +/*! + * Class : OCCViewer_AxisWidget + * Description : Axis tab widget of the "Graduated axis" dialog box +*/ +class OCCVIEWER_EXPORT OCCViewer_AxisWidget : public ViewerTools_AxisWidgetBase +{ +public: + struct AxisData + { + bool DrawName; + QString Name; + QColor NameColor; + bool DrawValues; + int NbValues; + int Offset; + QColor Color; + bool DrawTickmarks; + int TickmarkLength; + }; + +public: + OCCViewer_AxisWidget( QWidget* ); + ~OCCViewer_AxisWidget(); + +public: + void SetData( const AxisData& ); + void GetData( AxisData& ); + +protected: + virtual ViewerTools_FontWidgetBase* createFontWidget( QWidget* ); +}; + +/*! + * Class : OCCViewer_CubeAxesDlg + * Description : Dialog for specifynig cube axes properties + */ +class OCCVIEWER_EXPORT OCCViewer_CubeAxesDlg : public ViewerTools_CubeAxesDlgBase +{ + Q_OBJECT + +public: + OCCViewer_CubeAxesDlg(QtxAction* theAction, + OCCViewer_ViewWindow* theParent, + const char* theName); + virtual ~OCCViewer_CubeAxesDlg(); + + virtual void initialize(); + + void GetData( bool& theIsVisible, OCCViewer_AxisWidget::AxisData theAxisData[3] ); + void SetData( bool theIsVisible, OCCViewer_AxisWidget::AxisData theAxisData[3] ); + + void ApplyData( const Handle(V3d_View)& theView ); + + virtual void Update(); + +private slots: + virtual bool onApply(); + +private: + virtual ViewerTools_AxisWidgetBase* createAxisWidget( QWidget* ); + +private: + OCCViewer_ViewWindow* myMainWindow; +}; + +#endif diff --git a/src/OCCViewer/OCCViewer_FontWidget.cxx b/src/OCCViewer/OCCViewer_FontWidget.cxx new file mode 100644 index 000000000..c963f71b0 --- /dev/null +++ b/src/OCCViewer/OCCViewer_FontWidget.cxx @@ -0,0 +1,99 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 +// + +#include "OCCViewer_FontWidget.h" + +#include + +//#include + +/*! + * Class : OCCViewer_FontWidget + * Description : Dialog for specifynig font + */ + +/*! + Constructor +*/ +OCCViewer_FontWidget::OCCViewer_FontWidget( QWidget* theParent ) +: ViewerTools_FontWidgetBase( theParent ) +{ +} + +/*! + Destructor +*/ +OCCViewer_FontWidget::~OCCViewer_FontWidget() +{ +} + +void OCCViewer_FontWidget::InitializeFamilies() +{ + //myFamily->insertItem( myFamily->count(), tr( "ARIAL" ) ); + //myFamily->insertItem( myFamily->count(), tr( "COURIER" ) ); + //myFamily->insertItem( myFamily->count(), tr( "TIMES" ) ); +} + +void OCCViewer_FontWidget::SetData( const QColor& theColor, + const int theFamily, + const bool theBold, + const bool theItalic, + const bool theShadow ) +{ + ViewerTools_FontWidgetBase::SetData( theColor, + theFamily, + theBold, + theItalic, + theShadow ); + + /* + if ( theFamily == VTK_ARIAL ) + myFamily->setCurrentIndex( 0 ); + else if ( theFamily == VTK_COURIER ) + myFamily->setCurrentIndex( 1 ); + else + myFamily->setCurrentIndex( 2 ); + */ +} + +void OCCViewer_FontWidget::GetData( QColor& theColor, + int& theFamily, + bool& theBold, + bool& theItalic, + bool& theShadow ) const +{ + ViewerTools_FontWidgetBase::GetData( theColor, + theFamily, + theBold, + theItalic, + theShadow ); + + /* + int anItem = myFamily->currentIndex(); + if ( anItem == 0 ) + theFamily = VTK_ARIAL; + else if ( anItem == 1 ) + theFamily = VTK_COURIER; + else + theFamily = VTK_TIMES; + */ +} diff --git a/src/OCCViewer/OCCViewer_FontWidget.h b/src/OCCViewer/OCCViewer_FontWidget.h new file mode 100644 index 000000000..e35c23fdc --- /dev/null +++ b/src/OCCViewer/OCCViewer_FontWidget.h @@ -0,0 +1,50 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 +// + +#ifndef OCCVIEWER_FONTWIDGET_H +#define OCCVIEWER_FONTWIDGET_H + +#include "OCCViewer.h" + +#include + +/*! + * Class : OCCViewer_FontWidget + * Description : Dialog for specifynig font + */ +class OCCVIEWER_EXPORT OCCViewer_FontWidget : public ViewerTools_FontWidgetBase +{ + Q_OBJECT + +public: + OCCViewer_FontWidget( QWidget* ); + virtual ~OCCViewer_FontWidget(); + + virtual void SetData( const QColor&, const int, const bool, const bool, const bool ); + + virtual void GetData( QColor&, int&, bool&, bool&, bool& ) const; + +protected: + virtual void InitializeFamilies(); +}; + +#endif diff --git a/src/OCCViewer/OCCViewer_ViewFrame.cxx b/src/OCCViewer/OCCViewer_ViewFrame.cxx new file mode 100644 index 000000000..2d3b66ae7 --- /dev/null +++ b/src/OCCViewer/OCCViewer_ViewFrame.cxx @@ -0,0 +1,339 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 +// + +#include "OCCViewer_ViewFrame.h" +#include "OCCViewer_ViewWindow.h" +#include "OCCViewer_ViewModel.h" + +#include + +#include +#include +#include + +OCCViewer_ViewFrame::OCCViewer_ViewFrame(SUIT_Desktop* theDesktop, OCCViewer_Viewer* theModel) + : OCCViewer_ViewWindow( theDesktop, theModel ), myPopupRequestedView(0) +{ + QFrame* centralFrame = new QFrame( this ); + setCentralWidget( centralFrame ); + + OCCViewer_ViewWindow* view0 = theModel->createSubWindow(); + view0->setParent( centralFrame ); + myViews.append( view0 ); // MAIN_VIEW + + myLayout = new QGridLayout( centralFrame ); + myLayout->setMargin( 0 ); + myLayout->setSpacing( 1 ); + + myLayout->addWidget( view0, 1, 1 ); + connectViewSignals(view0); +} + +OCCViewer_ViewFrame::~OCCViewer_ViewFrame() +{ +} + +//************************************************************************************** +OCCViewer_ViewWindow* OCCViewer_ViewFrame::getView( const int i ) const +{ + return ( i >= 0 && i < myViews.count() ) ? myViews.at( i ) : 0 ; +} + +//************************************************************************************** +void OCCViewer_ViewFrame::setViewManager( SUIT_ViewManager* theMgr ) +{ + OCCViewer_ViewWindow::setViewManager(theMgr); + foreach (OCCViewer_ViewWindow* aView, myViews) { + aView->setViewManager(theMgr); + } +} + + +//************************************************************************************** +void OCCViewer_ViewFrame::onMaximizedView( OCCViewer_ViewWindow* theView, bool isMaximized) +{ + if (isMaximized) { + if (myViews.count() <= 1) + return; + + myLayout->setColumnStretch(0, 0); + myLayout->setColumnStretch(1, 0); + int i = 0; + OCCViewer_ViewWindow* view = 0; + for ( i = BOTTOM_RIGHT; i <= TOP_RIGHT; i++) { + view = myViews.at(i); + view->setVisible( view == theView ); + view->setMaximized( view == theView, false ); + } + } + else { + OCCViewer_Viewer* aModel = dynamic_cast(myManager->getViewModel()); + if (!aModel) return; + + myLayout->setColumnStretch(0, 10); + myLayout->setColumnStretch(1, 10); + + int i = 0; + if (myViews.count() == 1) { + //QColor aColor = myViews.at( MAIN_VIEW )->backgroundColor(); + OCCViewer_ViewWindow* view = 0; + for ( i = BOTTOM_LEFT; i <= TOP_RIGHT; i++) { + view = aModel->createSubWindow(); + view->set2dMode( (Mode2dType) i ); + view->setParent( centralWidget() ); + view->setViewManager(myManager); + myViews.append( view ); + aModel->initView(view); + view->setMaximized(false, false); + view->setDropDownButtons( dropDownButtons() ); + connectViewSignals(view); + view->setBackground(aModel->background(i)); + } + myLayout->addWidget( myViews.at(BOTTOM_LEFT), 1, 0 ); + myLayout->addWidget( myViews.at(TOP_LEFT), 0, 0 ); + myLayout->addWidget( myViews.at(TOP_RIGHT), 0, 1 ); + } + OCCViewer_ViewWindow* view = 0; + for ( i = BOTTOM_RIGHT; i <= TOP_RIGHT; i++) { + view = myViews.at(i); + view->show(); + view->setMaximized( false, false ); + ///////////////QApplication::processEvents(); // VSR: hangs up ? + if (view != theView) + view->onViewFitAll(); + } + } + myLayout->invalidate(); +} + +OCCViewer_ViewPort3d* OCCViewer_ViewFrame::getViewPort(int theView) +{ + return getView(theView)? getView(theView)->getViewPort() : 0; +} + +void OCCViewer_ViewFrame::updateEnabledDrawMode() +{ + foreach (OCCViewer_ViewWindow* aView, myViews) { + aView->updateEnabledDrawMode(); + } +} + +void OCCViewer_ViewFrame::setCuttingPlane( bool on, const double x , const double y , const double z, + const double dx, const double dy, const double dz) +{ + foreach (OCCViewer_ViewWindow* aView, myViews) { + aView->setCuttingPlane(on, x, y, z, dx, dy, dz); + aView->update(); + } +} + +//************************************************************************************** +void OCCViewer_ViewFrame::setCuttingPlane( bool on, const gp_Pln thePln ) +{ + foreach (OCCViewer_ViewWindow* aView, myViews) { + aView->setCuttingPlane(on, thePln); + aView->update(); + } +} + +//************************************************************************************** +void OCCViewer_ViewFrame::setInteractionStyle( const int i ) +{ + foreach (OCCViewer_ViewWindow* aView, myViews) { + aView->setInteractionStyle(i); + } +} + +//************************************************************************************** +void OCCViewer_ViewFrame::setZoomingStyle( const int i ) +{ + foreach (OCCViewer_ViewWindow* aView, myViews) { + aView->setZoomingStyle(i); + } +} + +//************************************************************************************** +void OCCViewer_ViewFrame::connectViewSignals(OCCViewer_ViewWindow* theView) +{ + connect( theView, SIGNAL( maximized( OCCViewer_ViewWindow*, bool ) ), + this, SLOT( onMaximizedView( OCCViewer_ViewWindow*, bool ) ) ); + + connect( theView, SIGNAL( wheeling(SUIT_ViewWindow*, QWheelEvent*) ), + this, SIGNAL( wheeling(SUIT_ViewWindow*, QWheelEvent*) ) ); + + connect( theView, SIGNAL( keyReleased(SUIT_ViewWindow*, QKeyEvent*) ), + this, SIGNAL( keyReleased(SUIT_ViewWindow*, QKeyEvent*) ) ); + connect( theView, SIGNAL( keyPressed(SUIT_ViewWindow*, QKeyEvent*) ), + this, SIGNAL( keyPressed(SUIT_ViewWindow*, QKeyEvent*) ) ); + + connect( theView, SIGNAL( mouseDoubleClicked(SUIT_ViewWindow*, QMouseEvent*) ), + this, SIGNAL( mouseDoubleClicked(SUIT_ViewWindow*, QMouseEvent*) ) ); + connect( theView, SIGNAL( mousePressed(SUIT_ViewWindow*, QMouseEvent*) ), + this, SIGNAL( mousePressed(SUIT_ViewWindow*, QMouseEvent*) ) ); + connect( theView, SIGNAL( mouseReleased(SUIT_ViewWindow*, QMouseEvent*) ), + this, SIGNAL( mouseReleased(SUIT_ViewWindow*, QMouseEvent*) ) ); + connect( theView, SIGNAL( mouseMoving(SUIT_ViewWindow*, QMouseEvent*) ), + this, SIGNAL( mouseMoving(SUIT_ViewWindow*, QMouseEvent*) ) ); + + // The signal is used to process get/set background color from popup + connect( theView, SIGNAL( contextMenuRequested(QContextMenuEvent*) ), + this, SLOT( onContextMenuRequested(QContextMenuEvent*) ) ); + + connect( theView, SIGNAL( contextMenuRequested(QContextMenuEvent*) ), + this, SIGNAL( contextMenuRequested(QContextMenuEvent*) ) ); +} + +// obsolete +void OCCViewer_ViewFrame::setBackgroundColor( const QColor& theColor ) +{ + if (myPopupRequestedView) + myPopupRequestedView->setBackgroundColor(theColor); + else { + foreach (OCCViewer_ViewWindow* aView, myViews) { + if (aView->isVisible()) + aView->setBackgroundColor(theColor); + } + } +} +void OCCViewer_ViewFrame::setBackground( const Qtx::BackgroundData& theBackground ) +{ + if (myPopupRequestedView) + myPopupRequestedView->setBackground(theBackground); + else { + foreach (OCCViewer_ViewWindow* aView, myViews) { + if (aView->isVisible()) + aView->setBackground(theBackground); + } + } +} + +void OCCViewer_ViewFrame::onViewFitAll() +{ + foreach (OCCViewer_ViewWindow* aView, myViews) { + aView->onViewFitAll(); + } +} + +void OCCViewer_ViewFrame::onFitAll() +{ + foreach (OCCViewer_ViewWindow* aView, myViews) { + aView->onFitAll(); + } +} + +// obsolete +QColor OCCViewer_ViewFrame::backgroundColor() const +{ + if (myPopupRequestedView) + return myPopupRequestedView->backgroundColor(); + + foreach (OCCViewer_ViewWindow* aView, myViews) { + if (aView->isVisible()) + return aView->backgroundColor(); + } + return getView(MAIN_VIEW)->backgroundColor(); +} + +Qtx::BackgroundData OCCViewer_ViewFrame::background() const +{ + if (myPopupRequestedView) + return myPopupRequestedView->background(); + + foreach (OCCViewer_ViewWindow* aView, myViews) { + if (aView->isVisible()) + return aView->background(); + } + return getView(MAIN_VIEW)->background(); +} + +QImage OCCViewer_ViewFrame::dumpView() +{ + foreach (OCCViewer_ViewWindow* aView, myViews) { + if (aView->isVisible()) + return aView->dumpView(); + } + return QImage(); +} + +bool OCCViewer_ViewFrame::dumpViewToFormat( const QImage& image, const QString& fileName, const QString& format ) +{ + foreach (OCCViewer_ViewWindow* aView, myViews) { + if (aView->isVisible()) + return aView->dumpViewToFormat( image, fileName, format ); + } + return false; +} + +void OCCViewer_ViewFrame::onContextMenuRequested(QContextMenuEvent*) +{ + myPopupRequestedView = dynamic_cast(sender()); +} + +void OCCViewer_ViewFrame::onDumpView() +{ + if (myPopupRequestedView) { + myPopupRequestedView->onDumpView(); + } + else { + getView(MAIN_VIEW)->onDumpView(); + } +} + +void OCCViewer_ViewFrame::setDropDownButtons( bool on ) +{ + foreach( OCCViewer_ViewWindow* aView, myViews ) { + aView->setDropDownButtons( on ); + } + OCCViewer_ViewWindow::setDropDownButtons( on ); +} + +QString OCCViewer_ViewFrame::getVisualParameters() +{ + QStringList params; + int maximizedView = 999; + for ( int i = BOTTOM_RIGHT; i <= TOP_RIGHT && i < myViews.count(); i++) { + if ( getView(i)->isVisible() ) + maximizedView = ( maximizedView != -1 ) ? ( maximizedView == 999 ? i : -1 ) : ( maximizedView ); + params << getView(i)->getVisualParameters(); + } + params.prepend( QString::number( maximizedView ) ); + return params.join( "|" ); +} + +void OCCViewer_ViewFrame::setVisualParameters( const QString& parameters ) +{ + QStringList params = parameters.split( "|" ); + if ( params.count() > 1 ) { + int maximizedView = params[0].toInt(); + if ( myViews.count() < params.count()-1 ) + onMaximizedView( getView(MAIN_VIEW), false ); // secondary views are not created yet, but should be + for ( int i = 1; i < params.count(); i++ ) { + int idx = i-1; + getView( idx )->setVisualParameters( params[i] ); + } + onMaximizedView( getView( maximizedView ), maximizedView != -1 ); // set proper sib-window maximized + } + else { + // handle obsolete versions - no parameters for xy, yz, xz views + getView(MAIN_VIEW)->setVisualParameters( parameters ); + } +} diff --git a/src/OCCViewer/OCCViewer_ViewFrame.h b/src/OCCViewer/OCCViewer_ViewFrame.h new file mode 100644 index 000000000..b00bc6a8b --- /dev/null +++ b/src/OCCViewer/OCCViewer_ViewFrame.h @@ -0,0 +1,135 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 +// + +#ifndef OCCVIEWER_VIEWFRAME_H +#define OCCVIEWER_VIEWFRAME_H + +#include "OCCViewer.h" +#include "OCCViewer_ViewWindow.h" + +#include + +class SUIT_Desktop; +class OCCViewer_Viewer; +class QGridLayout; + +class OCCVIEWER_EXPORT OCCViewer_ViewFrame : public OCCViewer_ViewWindow +{ + Q_OBJECT +public: + enum { MAIN_VIEW, BOTTOM_RIGHT=MAIN_VIEW, BOTTOM_LEFT, TOP_LEFT, TOP_RIGHT }; + + OCCViewer_ViewFrame(SUIT_Desktop* theDesktop, OCCViewer_Viewer* theModel); + virtual ~OCCViewer_ViewFrame(); + + OCCViewer_ViewWindow* getView( const int ) const; + + virtual OCCViewer_ViewPort3d* getViewPort() { return getView(MAIN_VIEW)->getViewPort(); } + OCCViewer_ViewPort3d* getViewPort(int theView); + + virtual void performRestoring( const viewAspect& theAspect) { getView(MAIN_VIEW)->performRestoring(theAspect); } + virtual void initLayout() {} + + virtual void updateEnabledDrawMode(); + virtual void setCuttingPlane( bool on, const double x = 0 , const double y = 0 , const double z = 0, + const double dx = 0, const double dy = 0, const double dz = 1); + + virtual void setCuttingPlane( bool on, const gp_Pln thePln ); + + virtual bool isCuttingPlane() { return getView(MAIN_VIEW)->isCuttingPlane(); } + + virtual QString getVisualParameters(); + virtual void setVisualParameters( const QString& parameters ); + + virtual void initSketchers() { getView(MAIN_VIEW)->initSketchers(); } + virtual OCCViewer_ViewSketcher* getSketcher( const int i) { return getView(MAIN_VIEW)->getSketcher(i); } + virtual void activateSketching( int i ) { getView(MAIN_VIEW)->activateSketching(i); } + + virtual int interactionStyle() const { return getView(MAIN_VIEW)->interactionStyle(); } + virtual void setInteractionStyle( const int i ); + + virtual int zoomingStyle() const { return getView(MAIN_VIEW)->zoomingStyle(); } + virtual void setZoomingStyle( const int ); + + virtual void setViewManager( SUIT_ViewManager* ); + + virtual bool eventFilter(QObject* watched, QEvent* e) { return SUIT_ViewWindow::eventFilter(watched, e); } + + virtual QColor backgroundColor() const; // obsolete + virtual void setBackgroundColor( const QColor& ); // obsolete + + virtual Qtx::BackgroundData background() const; + virtual void setBackground( const Qtx::BackgroundData& ); + + virtual void setDropDownButtons( bool ); + +public slots: + virtual void onFrontView() { getView(MAIN_VIEW)->onFrontView(); } + virtual void onViewFitAll(); + virtual void onBackView() { getView(MAIN_VIEW)->onBackView(); } + virtual void onTopView() { getView(MAIN_VIEW)->onTopView(); } + virtual void onBottomView() { getView(MAIN_VIEW)->onBottomView(); } + virtual void onLeftView() { getView(MAIN_VIEW)->onLeftView(); } + virtual void onRightView() { getView(MAIN_VIEW)->onRightView(); } + virtual void onClockWiseView() { getView(MAIN_VIEW)->onClockWiseView(); } + virtual void onAntiClockWiseView() { getView(MAIN_VIEW)->onAntiClockWiseView(); } + virtual void onResetView() { getView(MAIN_VIEW)->onResetView(); } + virtual void onFitAll(); + virtual void activateZoom() {} + virtual void activateWindowFit() {} + virtual void activateRotation() {} + virtual void activatePanning() {} + virtual void activateGlobalPanning() {} + virtual void onSetRotationPoint( bool on ) {} + virtual void onAxialScale() {} + virtual void onAmbientToogle() {} + virtual void onMemorizeView() {} + virtual void onRestoreView() {} + virtual void onSwitchInteractionStyle( bool on ) {} + + virtual void activateSetRotationGravity() {} + virtual void activateSetRotationSelected( double theX, double theY, double theZ ) {} + virtual void activateStartPointSelection() {} + virtual void updateGravityCoords() {} + + void onMaximizedView( OCCViewer_ViewWindow*, bool ); + + virtual void onDumpView(); + +protected: + virtual QImage dumpView(); + virtual bool dumpViewToFormat( const QImage&, const QString&, const QString& ); + +private slots: + void onContextMenuRequested(QContextMenuEvent*); + +private: + void connectViewSignals(OCCViewer_ViewWindow* theView); + + + QList myViews; + QGridLayout* myLayout; + + OCCViewer_ViewWindow* myPopupRequestedView; +}; + +#endif diff --git a/src/OCCViewer/resources/OCCViewer_msg_fr.ts b/src/OCCViewer/resources/OCCViewer_msg_fr.ts new file mode 100755 index 000000000..843d08b77 --- /dev/null +++ b/src/OCCViewer/resources/OCCViewer_msg_fr.ts @@ -0,0 +1,442 @@ + + + + + @default + + MNU_FRONT_VIEW + Avant + + + ERROR + Erreur + + + MNU_DUMP_VIEW + Sauvegarder la scène + + + DSC_TOP_VIEW + Vue de dessus + + + MNU_PAN_VIEW + Panoramique + + + MNU_CLONE_VIEW + Dupliquer la scène + + + DSC_SHOW_TRIHEDRE + Afficher/cacher le trièdre dans la scène + + + MNU_SHOW_TRIHEDRE + Afficher/cacher le trièdre + + + MNU_TOP_VIEW + Dessus + + + DSC_GLOBALPAN_VIEW + Sélection d'un nouveau centre de vue + + + DSC_ROTATE_VIEW + Tourner le point de vue autour du centre de la scène + + + MNU_ZOOM_VIEW + Zoom + + + DSC_PAN_VIEW + Déplacer la vue + + + DSC_LEFT_VIEW + Vue de gauche + + + DSC_SHOOT_VIEW + Memoriser l'état courant de la scène et l'ajouter dans la liste + + + DSC_FITALL + Redimentionner la scène pour montrer tous les objets + + + MNU_FITALL + Tout afficher + + + MNU_ROTATE_VIEW + Rotation + + + DSC_FRONT_VIEW + Vue de devant + + + MNU_ROTATIONPOINTGRAVITY_VIEW + Point de Rotation : le centre de gravité + + + MNU_GLOBALPAN_VIEW + Panoramique global + + + INF_APP_DUMP_VIEW + Sauvegarder la vue + + + DSC_CLIPPING + Définir le plan de coupe + + + DSC_CLONE_VIEW + Ouvrir une nouvelle fenêtre de visualisation pour la scène en cours + + + INF_APP_SHOOT_VIEW + Mémoriser la scène + + + MNU_CLIPPING + Plan de coupe + + + MNU_BACK_VIEW + Arrière + + + MNU_SHOOT_VIEW + Memoriser la vue + + + DSC_CHANGINGROTATIONPOINT_VIEW + Changer le point autour duquel la scène est tournée + + + MNU_BOTTOM_VIEW + Dessous + + + MNU_RESET_VIEW + Restaurer le point de vue + + + MNU_LEFT_VIEW + Gauche + + + DSC_RIGHT_VIEW + Vue de droite + + + DSC_ANTICLOCKWISE_VIEW + Tourner la vue à gauche + + + DSC_CLOCKWISE_VIEW + Tourner la vue à droite + + + MNU_CHANGINGROTATIONPOINT_VIEW + Changer le point de rotation + + + DSC_FITRECT + Redimensionner la scène pour ne montrer que sa partie choisie par l'encadré + + + MNU_FITRECT + Afficher la zone + + + DSC_BOTTOM_VIEW + Vue de dessous + + + DSC_DUMP_VIEW + Sauvegarder la scène en cours dans un fichier image + + + DSC_ZOOM_VIEW + Zoom la vue + + + MNU_ROTATIONPOINT000_VIEW + Point de Rotation : (0,0,0) + + + MNU_ROTATIONPOINTSELECTED_VIEW + Point de Rotation : le point choisi par l'utilisateur + + + DSC_RESET_VIEW + Restaurer le point de vue + + + ERR_DOC_CANT_SAVE_FILE + Impossible de sauvegarder le fichier + + + DSC_PRESETS_VIEW + Restaurer d'un état mémorisé de la scène courante + + + MNU_PRESETS_VIEW + Restaurer la vue + + + MNU_ANTICLOCKWISE_VIEW + Tourner à gauche + + + MNU_CLOCKWISE_VIEW + Tourner à droite + + + MNU_RIGHT_VIEW + Droit + + + INF_APP_PRESETS_VIEW + Restaurer la scène + + + LBL_XYTOOLBAR_LABEL + Opérations sur la vue XY + + + LBL_XZTOOLBAR_LABEL + Opérations sur la vue XZ + + + LBL_YZTOOLBAR_LABEL + Opérations sur la vue YZ + + + LBL_3DTOOLBAR_LABEL + Opérations sur la vue 3D + + + DSC_BACK_VIEW + Vue arrière + + + DSC_SCALING + Changer l'échelle des axes de coordonnées + + + MNU_SCALING + Changer l'échelle + + + DSC_GRADUATED_AXES + Axes gradués + + + MNU_GRADUATED_AXES + Axes gradués + + + DSC_AMBIENT + Ne montrer que la lumière d'ambiance + + + MNU_AMBIENT + Ne montrer que la lumière d'ambiance + + + DSC_STYLE_SWITCH + Changer le style d'intéraction + + + MNU_STYLE_SWITCH + Changer le style d'intéraction + + + DSC_ZOOMING_STYLE_SWITCH + Changer le style de zoom + + + MNU_ZOOMING_STYLE_SWITCH + Changer le style de zoom + + + OCC_IMAGE_FILES + Fichiers images (*.bmp *.png *.jpg *.jpeg *.eps *.ps) + + + OCC_TEXTURE_FILES + Fichiers images (*.bmp *.gif *.pix *.xwd *.rgb *.rs) + + + DSC_MAXIMIZE_VIEW + Maximiser la vue + + + DSC_MINIMIZE_VIEW + Minimiser la vue + + + DSC_SYNCHRONIZE_VIEW + Synchroniser la vue + + + MNU_MAXIMIZE_VIEW + Maximiser + + + MNU_MINIMIZE_VIEW + Minimiser + + + MNU_SYNCHRONIZE_VIEW + Synchroniser + + + MNU_SYNC_NO_VIEW + [ Pas de vue appropriée ] + + + + OCCViewer_CreateRestoreViewDlg + + CAPTION + Restaurer la vue + + + + OCCViewer_SetRotationPointDlg + + LBL_X + X: + + + LBL_Y + Y: + + + LBL_Z + Z: + + + USE_BBCENTER + Utiliser le centre de la boîte englobante + + + LBL_TOORIGIN + Définir à l'origine + + + CAPTION + Indiquer le point de rotation + + + LBL_SELECTPOINT + Choisir le point dans la vue + + + + OCCViewer_ViewManager + + OCC_VIEW_TITLE + Scène OCC :%M - visualiseur:%V + + + + OCCViewer_Viewer + + MEN_DUMP_VIEW + Sauvegarder la vue + + + MEN_SHOW_TOOLBAR + Montrer la Barre d'Outils + + + MEN_CHANGE_BACKGROUND + Changer l'arrière-plan + + + MEN_CHANGE_IMAGE + Régler/Changer l''image d'arrière-plan... + + + SELECT_IMAGE + Sélectionner l'image + + + CENTERED + en mode centré + + + TILED + en mode pavé + + + STRETCHED + en mode étiré + + + GT_HORIZONTALGRADIENT + Gradient horizontal + + + GT_VERTICALGRADIENT + Gradient vertical + + + GT_FIRSTDIAGONALGRADIENT + Gradient de la première diagonale + + + GT_SECONDDIAGONALGRADIENT + Gradient de la seconde diagonale + + + GT_FIRSTCORNERGRADIENT + Gradient du premier coin + + + GT_SECONDCORNERGRADIENT + Gradient du second coin + + + GT_THIRDCORNERGRADIENT + Gradient du troisième coin + + + GT_FORTHCORNERGRADIENT + Gradient du quatrième coin + + + BG_IMAGE_FILES + Fichiers images (*.bmp *.gif *.pix *.xwd *.rgb *.rs) + + + + OCCViewer_AxialScaleDlg + + DLG_SCALING + Changer l'échelle des axes + + + LBL_X + X: + + + LBL_Y + Y: + + + LBL_Z + Z: + + + diff --git a/src/OCCViewer/resources/occ_view_ambient.png b/src/OCCViewer/resources/occ_view_ambient.png new file mode 100644 index 000000000..7f4115317 Binary files /dev/null and b/src/OCCViewer/resources/occ_view_ambient.png differ diff --git a/src/OCCViewer/resources/occ_view_anticlockwise.png b/src/OCCViewer/resources/occ_view_anticlockwise.png new file mode 100644 index 000000000..991586fe6 Binary files /dev/null and b/src/OCCViewer/resources/occ_view_anticlockwise.png differ diff --git a/src/OCCViewer/resources/occ_view_clockwise.png b/src/OCCViewer/resources/occ_view_clockwise.png new file mode 100644 index 000000000..b25471e76 Binary files /dev/null and b/src/OCCViewer/resources/occ_view_clockwise.png differ diff --git a/src/OCCViewer/resources/occ_view_graduated_axes.png b/src/OCCViewer/resources/occ_view_graduated_axes.png new file mode 100755 index 000000000..2b44c06fe Binary files /dev/null and b/src/OCCViewer/resources/occ_view_graduated_axes.png differ diff --git a/src/OCCViewer/resources/occ_view_maximized.png b/src/OCCViewer/resources/occ_view_maximized.png new file mode 100644 index 000000000..8e19d6a23 Binary files /dev/null and b/src/OCCViewer/resources/occ_view_maximized.png differ diff --git a/src/OCCViewer/resources/occ_view_minimized.png b/src/OCCViewer/resources/occ_view_minimized.png new file mode 100644 index 000000000..b38bbeb90 Binary files /dev/null and b/src/OCCViewer/resources/occ_view_minimized.png differ diff --git a/src/OCCViewer/resources/occ_view_style_switch.png b/src/OCCViewer/resources/occ_view_style_switch.png new file mode 100755 index 000000000..b0a9c807e Binary files /dev/null and b/src/OCCViewer/resources/occ_view_style_switch.png differ diff --git a/src/OCCViewer/resources/occ_view_sync.png b/src/OCCViewer/resources/occ_view_sync.png new file mode 100755 index 000000000..32b95228a Binary files /dev/null and b/src/OCCViewer/resources/occ_view_sync.png differ diff --git a/src/OCCViewer/resources/occ_view_zooming_style_switch.png b/src/OCCViewer/resources/occ_view_zooming_style_switch.png new file mode 100755 index 000000000..8f3a48670 Binary files /dev/null and b/src/OCCViewer/resources/occ_view_zooming_style_switch.png differ diff --git a/src/ObjBrowser/resources/OB_msg_fr.ts b/src/ObjBrowser/resources/OB_msg_fr.ts new file mode 100755 index 000000000..a2d4d2f5b --- /dev/null +++ b/src/ObjBrowser/resources/OB_msg_fr.ts @@ -0,0 +1,38 @@ + + + + + OB_Browser + + MEN_EXPAND_ALL + Tout déplier + + + MEN_COLLAPSE_ALL + Tout réduire + + + MEN_FIND + Chercher + + + + OB_FindDlg + + FIND + Chercher + + + CLOSE + Fermer + + + CASE_SENSITIVE + Sensible à la casse + + + IS_REG_EXP + Expression régulière + + + diff --git a/src/Plot2d/Plot2d_Algorithm.cxx b/src/Plot2d/Plot2d_Algorithm.cxx new file mode 100755 index 000000000..b96e411dc --- /dev/null +++ b/src/Plot2d/Plot2d_Algorithm.cxx @@ -0,0 +1,72 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : Plot2d_Algorithm.cxx + +#include "Plot2d_Algorithm.h" + +/*! + Constructor +*/ +Plot2d_Algorithm::Plot2d_Algorithm(QObject *parent) : + QObject(parent), + myDataChanged(false) +{ +} + +/*! + Destructor +*/ +Plot2d_Algorithm::~Plot2d_Algorithm() +{ +} + +/*! + Sets input data values +*/ +void Plot2d_Algorithm::setInput(AlgoPlot2dInputData theInuptData) +{ + clear(); + myInuptData = theInuptData; + myDataChanged = true; +} + +/*! + Gets result data values +*/ +AlgoPlot2dOutputData Plot2d_Algorithm::getOutput() +{ + return myResultData; +} + +/*! + Check the data values changed +*/ +bool Plot2d_Algorithm::isDataChanged() +{ + return myDataChanged; +} + +void Plot2d_Algorithm::clear() { + myDataChanged=false; + myInuptData.clear(); + myResultData.clear(); +} diff --git a/src/Plot2d/Plot2d_Algorithm.h b/src/Plot2d/Plot2d_Algorithm.h new file mode 100755 index 000000000..e8a49e84b --- /dev/null +++ b/src/Plot2d/Plot2d_Algorithm.h @@ -0,0 +1,58 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : Plot2d_Algorithm.h + +#ifndef PLOT2D_ALGORITHM_H +#define PLOT2D_ALGORITHM_H + +#include "Plot2d.h" + +#include +#include +#include + +class Plot2d_Object; + +typedef QList< QPair > AlgoPlot2dItem; +typedef QList AlgoPlot2dInputData; +typedef QMap AlgoPlot2dOutputData; + +class PLOT2D_EXPORT Plot2d_Algorithm : public QObject { + Q_OBJECT +public: + Plot2d_Algorithm(QObject *parent = 0); + ~Plot2d_Algorithm(); + + void setInput(AlgoPlot2dInputData); + AlgoPlot2dOutputData getOutput(); + virtual void execute() = 0; + virtual void clear(); + + bool isDataChanged(); + +protected: + AlgoPlot2dInputData myInuptData; + AlgoPlot2dOutputData myResultData; + bool myDataChanged; +}; + +#endif //PLOT2D_ALGORITHM_H diff --git a/src/Plot2d/Plot2d_AnalyticalCurve.cxx b/src/Plot2d/Plot2d_AnalyticalCurve.cxx new file mode 100755 index 000000000..e47fc3f1b --- /dev/null +++ b/src/Plot2d/Plot2d_AnalyticalCurve.cxx @@ -0,0 +1,512 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : Plot2d_AnalyticalCurve.cxx +// Author : Roman NIKOLAEV, Open CASCADE S.A.S. (roman.nikolaev@opencascade.com) + +#include "Plot2d_AnalyticalParser.h" +#include "Plot2d_AnalyticalCurve.h" +#include "Plot2d_PlotItems.h" +#include "Plot2d_Object.h" + +#include + + +//Init static data; + +int Plot2d_AnalyticalCurve::myNbCurves = 0; + +/*! + Constructor +*/ +Plot2d_AnalyticalCurve::Plot2d_AnalyticalCurve() : + myAutoAssign(true), + myColor( 0, 0, 0 ), + myMarker( Plot2d::Circle ), + myMarkerSize( 0 ), + myLine( Plot2d::Solid ), + myLineWidth( 0 ), + myRangeBegin(0.0), + myRangeEnd(100.0), + myNbIntervals(100), + myExpression(""), + myAction(Plot2d_AnalyticalCurve::ActAddInView), + myState(Plot2d_AnalyticalCurve::StateNeedUpdate), + myCurve(0), + myActive(true), + myIsSelected(false) +{ + myName = QString("Analytical Curve %1").arg(++myNbCurves); +} + + +/*! + Destructor +*/ +Plot2d_AnalyticalCurve::~Plot2d_AnalyticalCurve() +{ +} + +/*! + Copy constructor. Makes deep copy of data +*/ +Plot2d_AnalyticalCurve::Plot2d_AnalyticalCurve( const Plot2d_AnalyticalCurve& curve ) +{ + myAutoAssign = curve.isAutoAssign(); + myColor = curve.getColor(); + myMarker = curve.getMarker(); + myMarkerSize = curve.getMarkerSize(); + myLine = curve.getLine(); + myLineWidth = curve.getLineWidth(); + myRangeBegin = curve.getRangeBegin(); + myRangeEnd = curve.getRangeEnd(); + myNbIntervals= curve.getNbIntervals(); + myPoints = curve.myPoints; + myAction = curve.getAction(); + myName = curve.getName(); + myExpression = curve.getExpression(); + myState = curve.state(); + myCurve = curve.myCurve; + myActive = curve.isActive(); +} + +/*! + operator=. Makes deep copy of data +*/ +Plot2d_AnalyticalCurve& Plot2d_AnalyticalCurve::operator=( const Plot2d_AnalyticalCurve& curve ) +{ + myAutoAssign = curve.isAutoAssign(); + myColor = curve.getColor(); + myMarker = curve.getMarker(); + myMarkerSize = curve.getMarkerSize(); + myLine = curve.getLine(); + myLineWidth = curve.getLineWidth(); + myRangeBegin = curve.getRangeBegin(); + myRangeEnd = curve.getRangeEnd(); + myNbIntervals= curve.getNbIntervals(); + myPoints = curve.myPoints; + myAction = curve.getAction(); + myName = curve.getName(); + myExpression = curve.getExpression(); + myState = curve.state(); + myCurve = curve.myCurve; + myActive = curve.isActive(); + return *this; +} + +/*! + Create plot object for the curve +*/ +QwtPlotItem* Plot2d_AnalyticalCurve::plotItem() +{ + if(!myCurve) { + myCurve = new Plot2d_QwtPlotCurve(QString("")); + updatePlotItem(); + } + return myCurve; +} + +/*! + Auto fill parameters of object by plot view +*/ +void Plot2d_AnalyticalCurve::autoFill( const QwtPlot* thePlot ) +{ + QwtSymbol::Style typeMarker; + QColor color; + Qt::PenStyle typeLine; + Plot2d::getNextMarker( QwtPlotItem::Rtti_PlotCurve, thePlot, typeMarker, color, typeLine ); + + setColor( color ); + setLine( Plot2d::qwt2plotLine( typeLine )); + setLineWidth(1); + setMarker( Plot2d::qwt2plotMarker( typeMarker ) ); +} + +/*! + Updates curve fields +*/ +void Plot2d_AnalyticalCurve::updatePlotItem() +{ + if ( !myCurve ) + return; + + Plot2d_QwtPlotCurve* aCurve = dynamic_cast(myCurve); + + if(!aCurve) + return; + + Qt::PenStyle ps = Plot2d::plot2qwtLine( getLine() ); + QwtSymbol::Style ms = Plot2d::plot2qwtMarker( getMarker() ); + + QColor aColor = isSelected() ? Plot2d_Object::selectionColor() : getColor(); + int lineW = getLineWidth(); + if ( isSelected() ) lineW += (lineW == 0 ? 3 : 2); + + int markerS = isSelected() ? getMarkerSize() + 2 : getMarkerSize(); + + aCurve->setSelected(isSelected()); + + aCurve->setPen( QPen(aColor , lineW, ps ) ); + aCurve->setSymbol( QwtSymbol( ms, QBrush( aColor ), + QPen( aColor ), + QSize( markerS , markerS ) ) ); + + aCurve->setLegendPen(QPen(getColor(), getLineWidth(), ps )); + aCurve->setLegendSymbol( QwtSymbol( ms, QBrush( getColor() ), + QPen( getColor() ), + QSize( getMarkerSize() , getMarkerSize() ))); + + double *x, *y; + long nb = getData( &x, &y ); + aCurve->setData( x, y, nb ); + aCurve->setTitle(getName()); +} + + +/*! + Calculate the curve points. +*/ +void Plot2d_AnalyticalCurve::calculate() { + if( state() == Plot2d_AnalyticalCurve::StateOk ) + return; + + if(myRangeBegin > myRangeEnd) + return; + + Plot2d_AnalyticalParser* parser = Plot2d_AnalyticalParser::parser(); + double* x = 0; + double* y = 0; + int nb = parser->calculate(getExpression(), getRangeBegin(), getRangeEnd(), + getNbIntervals(),&x,&y); + if( nb > 0 ) { + myPoints.clear(); + for( int i = 0; i < nb; i++ ) { + Plot2d_Point pnt(x[i], y[i]); + myPoints.append(pnt); + } + delete x; + delete y; + myState = Plot2d_AnalyticalCurve::StateOk; + setAction(Plot2d_AnalyticalCurve::ActUpdateInView); + } +} +/*! + Checks that this curve can be computed for the input QwtPlot +*/ +bool Plot2d_AnalyticalCurve::checkCurve( const QwtPlot* thePlot) { + if( !myExpression.isEmpty() && thePlot ) { + const QwtScaleDiv* div = thePlot->axisScaleDiv(QwtPlot::xBottom); + setRangeBegin(div->lowerBound()); + setRangeEnd(div->upperBound()); + calculate(); + } + return myState == Plot2d_AnalyticalCurve::StateOk; +} + + +/*! + Gets object's data +*/ +long Plot2d_AnalyticalCurve::getData( double** theX, double** theY ) const +{ + int aNPoints = myPoints.size(); + *theX = new double[aNPoints]; + *theY = new double[aNPoints]; + for (int i = 0; i < aNPoints; i++) { + (*theX)[i] = myPoints[i].x; + (*theY)[i] = myPoints[i].y; + } + return aNPoints; +} + +/*! + Sets curves's AutoAssign flag - in this case attributes will be set automatically +*/ +void Plot2d_AnalyticalCurve::setAutoAssign( bool on ) +{ + if( myAutoAssign != on ) { + myAutoAssign = on; + setAction(Plot2d_AnalyticalCurve::ActUpdateInView); + } +} + +/*! + Gets curve's AutoAssign flag state +*/ +bool Plot2d_AnalyticalCurve::isAutoAssign() const +{ + return myAutoAssign; +} + +/*! + Sets curve's color. +*/ +void Plot2d_AnalyticalCurve::setColor( const QColor& color ) +{ + if(myColor != color) { + myColor = color; + setAction(Plot2d_AnalyticalCurve::ActUpdateInView); + } +} + +/*! + Gets curve's color +*/ +QColor Plot2d_AnalyticalCurve::getColor() const +{ + return myColor; +} + + +/*! + Sets marker type ( and resets AutoAssign flag ) +*/ +void Plot2d_AnalyticalCurve::setMarker( Plot2d::MarkerType marker ) +{ + if(myMarker != marker) { + myMarker = marker; + setAction(Plot2d_AnalyticalCurve::ActUpdateInView); + } +} + +/*! + Gets marker type +*/ +Plot2d::MarkerType Plot2d_AnalyticalCurve::getMarker() const +{ + return myMarker; +} + +/*! + Sets new marker size +*/ +void Plot2d_AnalyticalCurve::setMarkerSize( const int theSize ) +{ + if( myMarkerSize != theSize ) { + myMarkerSize = theSize < 0 ? 0 : theSize; + setAction(Plot2d_AnalyticalCurve::ActUpdateInView); + } +} + +/*! + Gets marker size +*/ +int Plot2d_AnalyticalCurve::getMarkerSize() const +{ + return myMarkerSize; +} + +/*! + Sets line type +*/ +void Plot2d_AnalyticalCurve::setLine( Plot2d::LineType line ) +{ + if(myLine != line) { + myLine = line; + setAction(Plot2d_AnalyticalCurve::ActUpdateInView); + } +} + +/*! + Gets line type +*/ +Plot2d::LineType Plot2d_AnalyticalCurve::getLine() const +{ + return myLine; +} + + +/*! + Sets line width +*/ +void Plot2d_AnalyticalCurve::setLineWidth( const int lineWidth ) +{ + if( myLineWidth != lineWidth ) { + myLineWidth = lineWidth < 0 ? 0 : lineWidth; + setAction(Plot2d_AnalyticalCurve::ActUpdateInView); + } +} + +/*! + Gets line width +*/ +int Plot2d_AnalyticalCurve::getLineWidth() const +{ + return myLineWidth; +} + +/*! + Sets number of points +*/ +void Plot2d_AnalyticalCurve::setNbIntervals( const long nb ) +{ + if( myNbIntervals != nb ) { + myNbIntervals = nb < 1 ? 1 : nb; + myState = Plot2d_AnalyticalCurve::StateNeedUpdate; + } +} + +/*! + Gets number of points +*/ +long Plot2d_AnalyticalCurve::getNbIntervals() const +{ + return myNbIntervals; +} + +/*! + Sets X coordinate of the first curve points +*/ +void Plot2d_AnalyticalCurve::setRangeBegin( const double coord) { + if( myRangeBegin != coord ) { + myRangeBegin = coord; + myState = Plot2d_AnalyticalCurve::StateNeedUpdate; + } +} + +/*! + Gets X coordinate of the first curve points +*/ +double Plot2d_AnalyticalCurve::getRangeBegin() const { + return myRangeBegin; +} + +/*! + Sets X coordinate of the last curve points +*/ +void Plot2d_AnalyticalCurve::setRangeEnd( const double coord) { + if( myRangeEnd != coord ) { + myRangeEnd = coord; + myState = Plot2d_AnalyticalCurve::StateNeedUpdate; + } +} + +/*! + Gets X coordinate of the last curve points +*/ +double Plot2d_AnalyticalCurve::getRangeEnd() const { + return myRangeEnd; +} + +/*! + Sets the curve expression. +*/ +void Plot2d_AnalyticalCurve::setExpression( const QString& expr ) { + if( myExpression != expr ) { + myExpression = expr; + myState = Plot2d_AnalyticalCurve::StateNeedUpdate; + } +} + +/*! + Gets the curve expression. +*/ +QString Plot2d_AnalyticalCurve::getExpression() const { + return myExpression; +} + +/*! + Sets the curve name. +*/ +void Plot2d_AnalyticalCurve::setName( const QString& name ) { + if( myName != name ) { + myName = name; + setAction(Plot2d_AnalyticalCurve::ActUpdateInView); + } +} + +/*! + Gets the curve name. +*/ +QString Plot2d_AnalyticalCurve::getName() const { + return myName; +} + + +/*! + Sets the curve action. +*/ +void Plot2d_AnalyticalCurve::setAction(const int act) { + if( act == Plot2d_AnalyticalCurve::ActNothing ) { + myAction = act; + return; + } + + if(myAction != Plot2d_AnalyticalCurve::ActAddInView && + myAction != Plot2d_AnalyticalCurve::ActRemoveFromView) { + myAction = act; + } +} + +/*! + Gets the curve action. +*/ +int Plot2d_AnalyticalCurve::getAction() const { + return myAction; +} + +/*! + Gets the curve state. +*/ +int Plot2d_AnalyticalCurve::state() const { + return myState; +} + +/*! + Sets the curve active status. +*/ +void Plot2d_AnalyticalCurve::setActive(const bool on) { + if( myActive != on ) { + if(myActive && !on) + setAction(Plot2d_AnalyticalCurve::ActUpdateInView); + else if(!myActive && on) { + setAction(Plot2d_AnalyticalCurve::ActAddInView); + myState = Plot2d_AnalyticalCurve::StateNeedUpdate; + } + myActive = on; + } +} + +/*! + Gets the curve active status. +*/ +bool Plot2d_AnalyticalCurve::isActive() const { + return myActive; +} + + +/*! + Sets curve's selected property. +*/ +void Plot2d_AnalyticalCurve::setSelected(const bool on) { + if(myIsSelected != on) { + myIsSelected = on; + setAction(Plot2d_AnalyticalCurve::ActUpdateInView); + } + +} + +/*! + Gets curve's selected property. +*/ +bool Plot2d_AnalyticalCurve::isSelected() const { + return myIsSelected; +} diff --git a/src/Plot2d/Plot2d_AnalyticalCurve.h b/src/Plot2d/Plot2d_AnalyticalCurve.h new file mode 100755 index 000000000..2cb0f3499 --- /dev/null +++ b/src/Plot2d/Plot2d_AnalyticalCurve.h @@ -0,0 +1,156 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : Plot2d_AnalyticalCurve.h +// Author : Roman NIKOLAEV, Open CASCADE S.A.S. (roman.nikolaev@opencascade.com) + +#ifndef PLOT2D_ANALYTICAL_CURVE_H +#define PLOT2D_ANALYTICAL_CURVE_H + +#include "Plot2d.h" + + +class QwtPlot; +class QwtPlotItem; + + +class PLOT2D_EXPORT Plot2d_AnalyticalCurve +{ +public: + + /* + Action enumeration. + */ + enum { + ActAddInView = 0, //! Add curve in view + ActRemoveFromView, //! Remove curve from view + ActUpdateInView, //! Update curve in view + ActNothing //! Do nothing + }; + + /* + State enumeration. + */ + enum { + StateOk = 0, + StateNeedUpdate + }; + + Plot2d_AnalyticalCurve(); + Plot2d_AnalyticalCurve( const Plot2d_AnalyticalCurve& ); + Plot2d_AnalyticalCurve& operator= ( const Plot2d_AnalyticalCurve& ); + + virtual ~Plot2d_AnalyticalCurve(); + + virtual QwtPlotItem* plotItem(); + virtual void autoFill( const QwtPlot* ); + virtual void updatePlotItem(); + virtual bool checkCurve( const QwtPlot* ); + + virtual void calculate(); + + long getData( double** , double** ) const; + + void setSelected(const bool); + bool isSelected() const; + + + + void setAutoAssign( bool ); + bool isAutoAssign( ) const; + + void setColor( const QColor& ); + QColor getColor() const; + + void setMarker( Plot2d::MarkerType ); + Plot2d::MarkerType getMarker() const; + + void setMarkerSize( const int ); + int getMarkerSize() const; + + void setLine( Plot2d::LineType ); + Plot2d::LineType getLine() const; + + void setLineWidth( const int ); + int getLineWidth() const; + + void setNbIntervals( const long ); + long getNbIntervals() const; + + void setRangeBegin( const double ); + double getRangeBegin() const; + + void setRangeEnd( const double ); + double getRangeEnd() const; + + void setExpression( const QString& ); + QString getExpression() const; + + void setName( const QString& ); + QString getName() const; + + void setActive(const bool); + bool isActive() const; + + void setAction(const int); + int getAction() const; + int state() const; + + +protected: + + bool myAutoAssign; + QColor myColor; + Plot2d::MarkerType myMarker; + int myMarkerSize; + Plot2d::LineType myLine; + int myLineWidth; + long myNbIntervals; + pointList myPoints; + double myRangeBegin; + double myRangeEnd; + QString myExpression; + QString myName; + int myAction; + int myState; + QwtPlotItem* myCurve; + bool myActive; + bool myIsSelected; + +private: + static int myNbCurves; + +}; + +typedef QList AnalyticalCurveList; + +class PLOT2D_EXPORT Plot2d_CurveContainer +{ +public: + virtual void addAnalyticalCurve( Plot2d_AnalyticalCurve* ) = 0; + virtual void removeAnalyticalCurve( Plot2d_AnalyticalCurve* ) = 0; + virtual void updateAnalyticalCurve( Plot2d_AnalyticalCurve*, bool = false ) = 0; + virtual void updateAnalyticalCurves() = 0; + virtual AnalyticalCurveList getAnalyticalCurves() const = 0; +}; + +#endif //PLOT2D_ANALYTICAL_CURVE_H + diff --git a/src/Plot2d/Plot2d_AnalyticalCurveDlg.cxx b/src/Plot2d/Plot2d_AnalyticalCurveDlg.cxx new file mode 100755 index 000000000..81e954d2c --- /dev/null +++ b/src/Plot2d/Plot2d_AnalyticalCurveDlg.cxx @@ -0,0 +1,705 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : Plot2d_AnalyticalCurveDlg.cxx +// Author : Roman NIKOLAEV, Open CASCADE S.A.S. (roman.nikolaev@opencascade.com) + + + +// TODO : check what happens if invalid formula is given, e.g. x/0 +// TODO : check what happens if curve formala is valid in general but some there are some problems with calculating (e.g. logarithmic formulas and negative x) + +//Local includes +#include "Plot2d_AnalyticalCurveDlg.h" +#include "Plot2d_AnalyticalCurve.h" +#include "Plot2d_ViewFrame.h" + +//Qtx includes +#include +#include + +//SUIT includes +#include +#include +#include + +//Qt includes +#include +#include +#include +#include +#include +#include +#include +#include +#include + +//qwt includes +#include + +// Controls +const int MIN_NB_INTERVALS = 1; +const int MAX_NB_INTERVALS = 10000; +const int STEP = 1; +const int MIN_LINE_WIDTH = 0; +const int MAX_LINE_WIDTH = 10; + +const char* PROP_TITLE = "title"; +const char* PROP_VISIBLE = "visible"; +const char* PROP_STATUS = "status"; +const char* PROP_FORMULA = "formula"; +const char* PROP_NBINTERVALS = "nb_intervals"; +const char* PROP_AUTOASSIGN = "auto_assign"; +const char* PROP_MARKERTYPE = "marker_type"; +const char* PROP_LINETYPE = "line_type"; +const char* PROP_LINEWIDTH = "line_width"; +const char* PROP_COLOR = "color"; + +/* + \class Plot2d_AnalyticalCurveDlg::UpdateLocker + \brief Update locker class + \internal +*/ +class Plot2d_AnalyticalCurveDlg::UpdateLocker +{ +public: + UpdateLocker( QObject* ); + ~UpdateLocker(); +private: + QObject* myObject; + bool myLocked; +}; + +Plot2d_AnalyticalCurveDlg::UpdateLocker::UpdateLocker( QObject* object ) : myObject( object ) +{ + myLocked = myObject->blockSignals( true ); +} + +Plot2d_AnalyticalCurveDlg::UpdateLocker::~UpdateLocker() +{ + myObject->blockSignals( myLocked ); +} + +/* + \class Plot2d_AnalyticalCurveDlg::Updater + \brief Auxiliary class used for handle update requests from sub-widgets + \internal +*/ + +Plot2d_AnalyticalCurveDlg::Updater::Updater( QWidget* parent ) : QObject( parent ) +{/*nothing to do*/} + +Plot2d_AnalyticalCurveDlg::Updater::~Updater() +{/*nothing to do*/} + +/*! + Constructor +*/ +Plot2d_AnalyticalCurveDlg::Plot2d_AnalyticalCurveDlg( Plot2d_CurveContainer* container, QWidget* parent ) + : QDialog( parent ), myContainer( container ) +{ + setModal( true ); + setWindowTitle( tr( "ANALYTICAL_CURVE_TLT" ) ); + setSizeGripEnabled( true ); + + // Curves list widget + myCurvesList = new QListWidget( this ); + myCurvesList->setSelectionMode( QAbstractItemView::SingleSelection ); + + // Curve parameters group box + myCurveParams = new QGroupBox( tr( "AC_CURVE_PARAMS" ), this ); + + QLabel* formulaLabel = new QLabel( tr( "AC_FORMULA" ), myCurveParams ); + myFormula = new QLineEdit( myCurveParams ); + QLabel* nbIntervalsLabel = new QLabel( tr( "AC_NB_INTERVALS" ), myCurveParams ); + myNbIntervals = new QtxIntSpinBox( MIN_NB_INTERVALS, MAX_NB_INTERVALS, STEP, myCurveParams ); + + QGridLayout* paramsLayout = new QGridLayout( myCurveParams ); + paramsLayout->addWidget( formulaLabel, 0, 0 ); + paramsLayout->addWidget( myFormula, 0, 1 ); + paramsLayout->addWidget( nbIntervalsLabel, 1, 0 ); + paramsLayout->addWidget( myNbIntervals, 1, 1 ); + + // Curve properties group box + myCurveProps = new QGroupBox( tr( "AC_CURVE_PROPS" ), this ); + + myAutoAssign = new QCheckBox( tr( "AC_AUTO_ASSIGN" ), myCurveProps ); + myPropsGrp = new QWidget( myCurveProps ); + QLabel* markerLabel = new QLabel( tr( "AC_MARKER_TYPE" ), myPropsGrp ); + myMarkerType = new QComboBox( myPropsGrp ); + QLabel* lineTypeLabel = new QLabel( tr( "AC_LINE_TYPE" ), myPropsGrp ); + myLineType = new QComboBox( myPropsGrp ); + QLabel* lineWidthLabel = new QLabel( tr( "AC_LINE_WIDTH" ), myPropsGrp ); + myLineWidth = new QtxIntSpinBox( MIN_LINE_WIDTH, MAX_LINE_WIDTH, STEP, myPropsGrp ); + QLabel* colorLabel = new QLabel( tr("AC_CURVE_COLOR"), myPropsGrp ); + myColor = new QtxColorButton( myPropsGrp ); + + QGridLayout* propsGrpLayout = new QGridLayout( myPropsGrp ); + propsGrpLayout->addWidget( markerLabel, 0, 0 ); + propsGrpLayout->addWidget( myMarkerType, 0, 1 ); + propsGrpLayout->addWidget( lineTypeLabel, 1, 0 ); + propsGrpLayout->addWidget( myLineType, 1, 1 ); + propsGrpLayout->addWidget( lineWidthLabel, 2, 0 ); + propsGrpLayout->addWidget( myLineWidth, 2, 1 ); + propsGrpLayout->addWidget( colorLabel, 3, 0 ); + propsGrpLayout->addWidget( myColor, 3, 1 ); + + QVBoxLayout* propsLayout = new QVBoxLayout( myCurveProps ); + propsLayout->addWidget( myAutoAssign ); + propsLayout->addWidget( myPropsGrp ); + + // Add && Remove buttons + myAddButton = new QPushButton( tr("AC_ADD_BTN"), this ); + myAddButton->setAutoDefault( true ); + myRemoveButton = new QPushButton( tr("AC_REM_BTN"), this ); + myRemoveButton->setAutoDefault( true ); + + // OK, Apply, Close, Help buttons + QPushButton* okButton = new QPushButton( tr( "AC_OK_BTN" ), this ); + okButton->setDefault( true ); + okButton->setAutoDefault( true ); + + QPushButton* applyButton = new QPushButton( tr( "AC_APPLY_BTN" ), this ); + applyButton->setAutoDefault( true ); + + QPushButton* cancelButton = new QPushButton( tr( "AC_CLOSE_BTN" ), this ); + cancelButton->setAutoDefault( true ); + QPushButton* helpButton = new QPushButton( tr( "AC_HELP_BTN" ), this ); + helpButton->setAutoDefault( true ); + QHBoxLayout* btnLayout = new QHBoxLayout; + btnLayout->addWidget( okButton ); + btnLayout->addWidget( applyButton ); + btnLayout->addStretch(); + btnLayout->addWidget( cancelButton ); + btnLayout->addWidget( helpButton ); + + QGridLayout* mainLayout = new QGridLayout( this ); + mainLayout->addWidget( myCurvesList, 0, 0, 3, 1 ); + mainLayout->addWidget( myCurveParams, 0, 1, 1, 2 ); + mainLayout->addWidget( myCurveProps, 1, 1, 1, 2 ); + mainLayout->addWidget( myAddButton, 2, 1 ); + mainLayout->addWidget( myRemoveButton, 2, 2 ); + mainLayout->addLayout( btnLayout, 3, 0, 1, 3 ); + + // Fill combo boxes + QColor cl = myMarkerType->palette().color( QPalette::Text ); // color to draw markers + QSize sz = QSize( 16, 16 ); // size of the icons for markers + myMarkerType->setIconSize( sz ); + + myMarkerType->addItem( Plot2d::markerIcon( sz, cl, Plot2d::None ), tr( "NONE_MARKER_LBL" ) ); + myMarkerType->addItem( Plot2d::markerIcon( sz, cl, Plot2d::Circle ), tr( "CIRCLE_MARKER_LBL" ) ); + myMarkerType->addItem( Plot2d::markerIcon( sz, cl, Plot2d::Rectangle ), tr( "RECTANGLE_MARKER_LBL" ) ); + myMarkerType->addItem( Plot2d::markerIcon( sz, cl, Plot2d::Diamond ), tr( "DIAMOND_MARKER_LBL" ) ); + myMarkerType->addItem( Plot2d::markerIcon( sz, cl, Plot2d::DTriangle ), tr( "DTRIANGLE_MARKER_LBL" ) ); + myMarkerType->addItem( Plot2d::markerIcon( sz, cl, Plot2d::UTriangle ), tr( "UTRIANGLE_MARKER_LBL" ) ); + myMarkerType->addItem( Plot2d::markerIcon( sz, cl, Plot2d::LTriangle ), tr( "LTRIANGLE_MARKER_LBL" ) ); + myMarkerType->addItem( Plot2d::markerIcon( sz, cl, Plot2d::RTriangle ), tr( "RTRIANGLE_MARKER_LBL" ) ); + myMarkerType->addItem( Plot2d::markerIcon( sz, cl, Plot2d::Cross ), tr( "CROSS_MARKER_LBL" ) ); + myMarkerType->addItem( Plot2d::markerIcon( sz, cl, Plot2d::XCross ), tr( "XCROSS_MARKER_LBL" ) ); + + cl = myLineType->palette().color( QPalette::Text ); // color to draw line types + sz = QSize( 40, 16 ); // size of the icons for line types + myLineType->setIconSize( sz ); + + myLineType->addItem( Plot2d::lineIcon( sz, cl, Plot2d::NoPen ), tr( "NONE_LINE_LBL" ) ); + myLineType->addItem( Plot2d::lineIcon( sz, cl, Plot2d::Solid ), tr( "SOLID_LINE_LBL" ) ); + myLineType->addItem( Plot2d::lineIcon( sz, cl, Plot2d::Dash ), tr( "DASH_LINE_LBL" ) ); + myLineType->addItem( Plot2d::lineIcon( sz, cl, Plot2d::Dot ), tr( "DOT_LINE_LBL" ) ); + myLineType->addItem( Plot2d::lineIcon( sz, cl, Plot2d::DashDot ), tr( "DASHDOT_LINE_LBL" ) ); + myLineType->addItem( Plot2d::lineIcon( sz, cl, Plot2d::DashDotDot ), tr( "DAHSDOTDOT_LINE_LBL" ) ); + + // Connections + myUpdater = new Updater( this ); + connect( myUpdater, SIGNAL( update() ), this, SLOT( updateCurve() ) ); + connect( myFormula, SIGNAL( textChanged( QString ) ), myUpdater, SIGNAL( update() ) ); + connect( myNbIntervals, SIGNAL( valueChanged( int ) ), myUpdater, SIGNAL( update() ) ); + connect( myAutoAssign, SIGNAL( stateChanged( int ) ), myUpdater, SIGNAL( update() ) ); + connect( myMarkerType, SIGNAL( activated( int ) ), myUpdater, SIGNAL( update() ) ); + connect( myLineType, SIGNAL( activated( int ) ), myUpdater, SIGNAL( update() ) ); + connect( myLineWidth, SIGNAL( valueChanged( int ) ), myUpdater, SIGNAL( update() ) ); + connect( myColor, SIGNAL( changed( QColor ) ), myUpdater, SIGNAL( update() ) ); + connect( myCurvesList, SIGNAL( itemChanged( QListWidgetItem* ) ), myUpdater, SIGNAL( update() ) ); + connect( myCurvesList, SIGNAL( itemSelectionChanged() ), this, SLOT( selectionChanged() ) ); + connect( myAddButton, SIGNAL( clicked() ), this, SLOT( addCurve() ) ); + connect( myRemoveButton, SIGNAL( clicked()), this, SLOT( removeCurve() ) ); + connect( okButton, SIGNAL( clicked() ), this, SLOT( accept() ) ); + connect( applyButton, SIGNAL( clicked() ), this, SLOT( apply() ) ); + connect( cancelButton, SIGNAL( clicked() ), this, SLOT( reject() ) ); + connect( helpButton, SIGNAL( clicked() ), this, SLOT( help() ) ); + + // Initialize dialog box + init(); +} + +/*! + Destructor +*/ +Plot2d_AnalyticalCurveDlg::~Plot2d_AnalyticalCurveDlg() +{ +} + +void Plot2d_AnalyticalCurveDlg::init() +{ + AnalyticalCurveList curves = myContainer->getAnalyticalCurves(); + foreach ( Plot2d_AnalyticalCurve* curve, curves ) { + QListWidgetItem* item = new QListWidgetItem( curve->getName() ); + item->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled ); + item->setCheckState( curve->isActive() ? Qt::Checked : Qt::Unchecked ); + initPropsFromCurve(curve); + QVariant var; + var.setValue( (void*)curve ); + item->setData( Qt::UserRole, var ); + myCurvesList->addItem( item ); + + if ( !myCurvesList->currentItem() ) + myCurvesList->setCurrentItem( item ); + } + + selectionChanged(); +} + +/*! + /brief Store curve properties in the local map. +*/ +void Plot2d_AnalyticalCurveDlg::initPropsFromCurve(Plot2d_AnalyticalCurve* curve) { + myProperties[ curve ][ PROP_TITLE ] = curve->getName(); + myProperties[ curve ][ PROP_VISIBLE ] = curve->isActive(); + myProperties[ curve ][ PROP_FORMULA ] = curve->getExpression(); + myProperties[ curve ][ PROP_NBINTERVALS ] = (int)curve->getNbIntervals(); + myProperties[ curve ][ PROP_AUTOASSIGN ] = curve->isAutoAssign(); + myProperties[ curve ][ PROP_MARKERTYPE ] = curve->getMarker(); + myProperties[ curve ][ PROP_LINETYPE ] = curve->getLine(); + myProperties[ curve ][ PROP_LINEWIDTH ] = curve->getLineWidth(); + myProperties[ curve ][ PROP_COLOR ] = curve->getColor(); + myProperties[ curve ][ PROP_STATUS ] = ItemExisting; +} + +QwtPlot* Plot2d_AnalyticalCurveDlg::getPlot() { + Plot2d_ViewFrame* frame = dynamic_cast(myContainer); + if( frame ) + return frame->getPlot(); + return 0; +} + +/*! + /brief Store local copy on the curves properties into curves. +*/ +bool Plot2d_AnalyticalCurveDlg::processCurves() { + // update curves + + QwtPlot* plot = getPlot(); + if(!plot) + return false; + + PropMap::Iterator it; + for ( it = myProperties.begin(); it != myProperties.end(); ++it ) { + Plot2d_AnalyticalCurve* curve = it.key(); + if ( propStatus( curve ) == ItemRemoved ) { + myContainer->removeAnalyticalCurve( curve ); + continue; + } + curve->setName( propTitle( curve ) ); + curve->setActive( propVisible( curve ) ); + curve->setExpression( propFormula( curve ) ); + curve->setNbIntervals( propIntervals(curve) ); + bool prevValue = curve->isAutoAssign(); + curve->setAutoAssign( propAutoAssign( curve ) ); + if ( !curve->isAutoAssign() ) { + curve->setMarker( propMarkerType( curve ) ); + curve->setLine( propLineType( curve ) ); + curve->setLineWidth( propLineWidth( curve ) ); + curve->setColor( propColor( curve ) ); + } else { + if(!prevValue){ + curve->autoFill(plot); + } + } + + if (! curve->checkCurve(plot) ) { + QListWidgetItem* item = getItem(curve); + if(item) { + myCurvesList->setCurrentItem( item ); + SUIT_MessageBox::critical( this, tr( "ERR_ERROR" ), tr( "AC_CANT_CALCULATE" ) ); + } + return false; + } + + if ( propStatus( curve ) == ItemAdded ) { + myContainer->addAnalyticalCurve( curve ); + myProperties[ curve ][ PROP_STATUS ] = ItemExisting; + } + } + return true; +} + +/*! + \brief Private slot. Called when "Apply" button is clicked +*/ +void Plot2d_AnalyticalCurveDlg::apply() { + if(processCurves()) { + Plot2d_ViewFrame* f = dynamic_cast(myContainer); + if(f) + f->updateAnalyticalCurves(); + + AnalyticalCurveList curves = myContainer->getAnalyticalCurves(); + foreach ( Plot2d_AnalyticalCurve* curve, curves ) { + initPropsFromCurve(curve); + } + selectionChanged(); + } +} + +/*! + \brief Private slot. Called when "Ok" button is clicked +*/ +void Plot2d_AnalyticalCurveDlg::accept() +{ + if(processCurves()) + QDialog::accept(); +} + +/*! + \brief Private slot. Called when "Close" button is clicked +*/ +void Plot2d_AnalyticalCurveDlg::reject() +{ + // clean-up curves just created + PropMap::Iterator it; + for ( it = myProperties.begin(); it != myProperties.end(); ++it ) { + Plot2d_AnalyticalCurve* curve = it.key(); + if ( propStatus( curve ) == ItemAdded ) + delete curve; + } + QDialog::reject(); +} + +/*! + \brief Private slot. Called when "Add curve" button is clicked +*/ +void Plot2d_AnalyticalCurveDlg::addCurve() +{ + Plot2d_AnalyticalCurve* curve = new Plot2d_AnalyticalCurve(); + + if(curve->isAutoAssign()) { + QwtPlot* plot = getPlot(); + if(plot) + curve->autoFill(plot); + } + + QListWidgetItem* item = new QListWidgetItem(curve->getName()); + item->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled ); + item->setCheckState( Qt::Checked ); + QVariant var; + var.setValue( (void*)curve ); + item->setData( Qt::UserRole, var ); + myCurvesList->addItem( item ); + + myProperties[ curve ][ PROP_STATUS ] = ItemAdded; + + myCurvesList->setCurrentItem( item ); +} + +/*! + \brief Private slot. Called when "Remove curve" button is clicked +*/ +void Plot2d_AnalyticalCurveDlg::removeCurve() +{ + QList items = myCurvesList->selectedItems(); + foreach( QListWidgetItem* item, items ) { + Plot2d_AnalyticalCurve* curve = (Plot2d_AnalyticalCurve*)( item->data( Qt::UserRole ).value() ); + delete item; + if ( propStatus( curve ) == ItemAdded ) { + myProperties.remove( curve ); + delete curve; + } + else { + myProperties[ curve ][ PROP_STATUS ] = ItemRemoved; + } + } +} + +/*! + \brief Private slot. Called when any curve property is changed. +*/ +void Plot2d_AnalyticalCurveDlg::updateCurve() +{ + UpdateLocker lock( myUpdater ); + + QListWidgetItem* item = selected(); + Plot2d_AnalyticalCurve* curve = selectedCurve(); + if ( item && curve ) { + myProperties[ curve ][ PROP_TITLE ] = item->text(); + myProperties[ curve ][ PROP_VISIBLE ] = item->checkState() == Qt::Checked; + myProperties[ curve ][ PROP_FORMULA ] = myFormula->text(); + myProperties[ curve ][ PROP_NBINTERVALS ] = myNbIntervals->value(); + myProperties[ curve ][ PROP_AUTOASSIGN ] = myAutoAssign->isChecked(); + myProperties[ curve ][ PROP_MARKERTYPE ] = myMarkerType->currentIndex(); + myProperties[ curve ][ PROP_LINETYPE ] = myLineType->currentIndex(); + myProperties[ curve ][ PROP_LINEWIDTH ] = myLineWidth->value(); + myProperties[ curve ][ PROP_COLOR ] = myColor->color(); + } + + updateState(); +} + +/*! + \brief Private slot. Update widgets state. +*/ +void Plot2d_AnalyticalCurveDlg::updateState() +{ + myPropsGrp->setEnabled( !myAutoAssign->isChecked() ); + myCurveParams->setEnabled( selectedCurve() != 0 ); + myCurveProps->setEnabled( selectedCurve() != 0 ); + myRemoveButton->setEnabled( selectedCurve() != 0 ); +} + +/*! + \brief Private slot. Called when selection in the curve list is changed. +*/ +void Plot2d_AnalyticalCurveDlg::selectionChanged() +{ + UpdateLocker lock( myUpdater ); + + Plot2d_AnalyticalCurve* curve = selectedCurve(); + + myFormula->setText( propFormula( curve ) ); + myNbIntervals->setValue( propIntervals( curve ) ); + myMarkerType->setCurrentIndex( (int)propMarkerType( curve ) ); + myLineType->setCurrentIndex( (int)propLineType( curve ) ); + myLineWidth->setValue( propLineWidth( curve ) ); + myColor->setColor( propColor( curve ) ); + myAutoAssign->setChecked( propAutoAssign( curve ) ); + + updateState(); +} + +/*! + \brief Show help page +*/ +void Plot2d_AnalyticalCurveDlg::help() +{ + SUIT_Application* app = SUIT_Session::session()->activeApplication(); + if ( app ) + app->onHelpContextModule( "GUI", "plot2d_viewer_page.html", "analytical_curve" ); +} + +/*! + \brief Get currently selected list widget item +*/ +QListWidgetItem* Plot2d_AnalyticalCurveDlg::selected() const +{ + QList items = myCurvesList->selectedItems(); + return items.count() > 0 ? items[0] : 0; +} + +/*! + \brief Get widget item by the curve +*/ +QListWidgetItem* Plot2d_AnalyticalCurveDlg::getItem(Plot2d_AnalyticalCurve* theCurve) const +{ + int nb = myCurvesList->count(); + QListWidgetItem* item = 0; + for(int i = 0; i < nb ; i++) { + item = myCurvesList->item(i); + if(item->data( Qt::UserRole ).value() == theCurve) + break; + } + return item; +} + +/*! + \brief Get currently selected curve +*/ +Plot2d_AnalyticalCurve* Plot2d_AnalyticalCurveDlg::selectedCurve() const +{ + return selected() ? (Plot2d_AnalyticalCurve*)( selected()->data( Qt::UserRole ).value() ) : 0; +} + +/*! + \brief Get curve property: status +*/ +int Plot2d_AnalyticalCurveDlg::propStatus( Plot2d_AnalyticalCurve* curve, const int def ) +{ + int val = def; + if ( curve ) { + if ( !myProperties.contains( curve ) ) + myProperties[ curve ] = CurveProps(); + if ( !myProperties[ curve ].contains( PROP_STATUS ) ) + myProperties[ curve ][ PROP_STATUS ] = def; + QVariant v = myProperties[ curve ][ PROP_STATUS ]; + if ( v.isValid() && v.type() == QVariant::Int ) val = v.toInt(); + } + return val; +} + +/*! + \brief Get curve property: title +*/ +QString Plot2d_AnalyticalCurveDlg::propTitle( Plot2d_AnalyticalCurve* curve, const QString& def ) +{ + QString val = def; + if ( curve ) { + if ( !myProperties.contains( curve ) ) + myProperties[ curve ] = CurveProps(); + if ( !myProperties[ curve ].contains( PROP_TITLE ) ) + myProperties[ curve ][ PROP_TITLE ] = def; + QVariant v = myProperties[ curve ][ PROP_TITLE ]; + if ( v.isValid() && v.type() == QVariant::String ) val = v.toString(); + } + return val; +} + +/*! + \brief Get curve property: visible flag +*/ +bool Plot2d_AnalyticalCurveDlg::propVisible( Plot2d_AnalyticalCurve* curve, bool def ) +{ + bool val = def; + if ( curve ) { + if ( !myProperties.contains( curve ) ) + myProperties[ curve ] = CurveProps(); + if ( !myProperties[ curve ].contains( PROP_VISIBLE ) ) + myProperties[ curve ][ PROP_VISIBLE ] = def; + QVariant v = myProperties[ curve ][ PROP_VISIBLE ]; + if ( v.isValid() && v.type() == QVariant::Bool ) val = v.toBool(); + } + return val; +} + +/*! + \brief Get curve property: formula +*/ +QString Plot2d_AnalyticalCurveDlg::propFormula( Plot2d_AnalyticalCurve* curve, const QString& def ) +{ + QString val = def; + if ( curve ) { + if ( !myProperties.contains( curve ) ) + myProperties[ curve ] = CurveProps(); + if ( !myProperties[ curve ].contains( PROP_FORMULA ) ) + myProperties[ curve ][ PROP_FORMULA ] = def; + QVariant v = myProperties[ curve ][ PROP_FORMULA ]; + if ( v.isValid() && v.type() == QVariant::String ) val = v.toString(); + } + return val; +} + +/*! + \brief Get curve property: nb intervals +*/ +int Plot2d_AnalyticalCurveDlg::propIntervals( Plot2d_AnalyticalCurve* curve, int def ) +{ + int val = def; + if ( curve ) { + if ( !myProperties.contains( curve ) ) + myProperties[ curve ] = CurveProps(); + if ( !myProperties[ curve ].contains( PROP_NBINTERVALS ) ) + myProperties[ curve ][ PROP_NBINTERVALS ] = def; + QVariant v = myProperties[ curve ][ PROP_NBINTERVALS ]; + if ( v.isValid() && v.type() == QVariant::Int ) val = v.toInt(); + } + return val; +} + +/*! + \brief Get curve property: marker type +*/ +Plot2d::MarkerType Plot2d_AnalyticalCurveDlg::propMarkerType( Plot2d_AnalyticalCurve* curve, Plot2d::MarkerType def ) +{ + Plot2d::MarkerType val = def; + if ( curve ) { + if ( !myProperties.contains( curve ) ) + myProperties[ curve ] = CurveProps(); + if ( !myProperties[ curve ].contains( PROP_MARKERTYPE ) ) + myProperties[ curve ][ PROP_MARKERTYPE ] = def; + QVariant v = myProperties[ curve ][ PROP_MARKERTYPE ]; + if ( v.isValid() && v.type() == QVariant::Int ) val = (Plot2d::MarkerType)( v.toInt() ); + } + return val; +} + +/*! + \brief Get curve property: line type +*/ +Plot2d::LineType Plot2d_AnalyticalCurveDlg::propLineType( Plot2d_AnalyticalCurve* curve, Plot2d::LineType def ) +{ + Plot2d::LineType val = def; + if ( curve ) { + if ( !myProperties.contains( curve ) ) + myProperties[ curve ] = CurveProps(); + if ( !myProperties[ curve ].contains( PROP_LINETYPE ) ) + myProperties[ curve ][ PROP_LINETYPE ] = def; + QVariant v = myProperties[ curve ][ PROP_LINETYPE ]; + if ( v.isValid() && v.type() == QVariant::Int ) val = (Plot2d::LineType)( v.toInt() ); + } + return val; +} + +/*! + \brief Get curve property: line width +*/ +int Plot2d_AnalyticalCurveDlg::propLineWidth( Plot2d_AnalyticalCurve* curve, int def ) +{ + int val = def; + if ( curve ) { + if ( !myProperties.contains( curve ) ) + myProperties[ curve ] = CurveProps(); + if ( !myProperties[ curve ].contains( PROP_LINEWIDTH ) ) + myProperties[ curve ][ PROP_LINEWIDTH ] = def; + QVariant v = myProperties[ curve ][ PROP_LINEWIDTH ]; + if ( v.isValid() && v.type() == QVariant::Int ) val = v.toInt(); + } + return val; +} + +/*! + \brief Get curve property: color +*/ +QColor Plot2d_AnalyticalCurveDlg::propColor( Plot2d_AnalyticalCurve* curve, const QColor& def ) +{ + QColor val = def; + if ( curve ) { + if ( !myProperties.contains( curve ) ) + myProperties[ curve ] = CurveProps(); + if ( !myProperties[ curve ].contains( PROP_COLOR ) ) + myProperties[ curve ][ PROP_COLOR ] = def; + QVariant v = myProperties[ curve ][ PROP_COLOR ]; + if ( v.isValid() && v.type() == QVariant::Color ) val = v.value(); + } + return val; +} + +/*! + \brief Get curve property: auto-assign flag +*/ +bool Plot2d_AnalyticalCurveDlg::propAutoAssign( Plot2d_AnalyticalCurve* curve, bool def ) +{ + bool val = def; + if ( curve ) { + if ( !myProperties.contains( curve ) ) + myProperties[ curve ] = CurveProps(); + if ( !myProperties[ curve ].contains( PROP_AUTOASSIGN ) ) + myProperties[ curve ][ PROP_AUTOASSIGN ] = def; + QVariant v = myProperties[ curve ][ PROP_AUTOASSIGN ]; + if ( v.isValid() && v.type() == QVariant::Bool ) val = v.toBool(); + } + return val; +} diff --git a/src/Plot2d/Plot2d_AnalyticalCurveDlg.h b/src/Plot2d/Plot2d_AnalyticalCurveDlg.h new file mode 100755 index 000000000..ae9f0180d --- /dev/null +++ b/src/Plot2d/Plot2d_AnalyticalCurveDlg.h @@ -0,0 +1,129 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : Plot2d_AnalyticalCurveDlg.h +// Author : Roman NIKOLAEV, Open CASCADE S.A.S. (roman.nikolaev@opencascade.com) + + +#ifndef PLOT2D_ANALYTICAL_CURVE_DLG_H +#define PLOT2D_ANALYTICAL_CURVE_DLG_H + +#include "Plot2d.h" +#include "Plot2d_AnalyticalCurve.h" + +#include +#include + +class QListWidget; +class QListWidgetItem; +class QGroupBox; +class QLineEdit; +class QCheckBox; +class QComboBox; +class QPushButton; + +class QtxIntSpinBox; +class QtxColorButton; +class QwtPlot; + +class Plot2d_AnalyticalCurve; +class Plot2d_CurveContainer; +class Plot2d_ViewFrame; + +class PLOT2D_EXPORT Plot2d_AnalyticalCurveDlg : public QDialog +{ + Q_OBJECT + + class Updater; + class UpdateLocker; + + enum { ItemExisting, ItemAdded, ItemRemoved }; + +public: + Plot2d_AnalyticalCurveDlg( Plot2d_CurveContainer*, QWidget* ); + ~Plot2d_AnalyticalCurveDlg(); + + void accept(); + void reject(); + +private: + + void init(); + void initPropsFromCurve(Plot2d_AnalyticalCurve*); + QListWidgetItem* selected() const; + Plot2d_AnalyticalCurve* selectedCurve() const; + QListWidgetItem* getItem(Plot2d_AnalyticalCurve*) const; + bool processCurves(); + QwtPlot* getPlot(); + int propStatus( Plot2d_AnalyticalCurve* = 0, const int def = ItemExisting ); + QString propTitle( Plot2d_AnalyticalCurve* = 0, const QString& def = "" ); + bool propVisible( Plot2d_AnalyticalCurve* = 0, bool def = true ); + QString propFormula( Plot2d_AnalyticalCurve* = 0, const QString& def = "" ); + int propIntervals( Plot2d_AnalyticalCurve* = 0, int def = 100 ); + Plot2d::MarkerType propMarkerType( Plot2d_AnalyticalCurve* = 0, Plot2d::MarkerType def = Plot2d::None ); + Plot2d::LineType propLineType( Plot2d_AnalyticalCurve* = 0, Plot2d::LineType def = Plot2d::NoPen ); + int propLineWidth( Plot2d_AnalyticalCurve* = 0, int def = 0 ); + QColor propColor( Plot2d_AnalyticalCurve* = 0, const QColor& def = QColor() ); + bool propAutoAssign( Plot2d_AnalyticalCurve* = 0, bool def = true ); + +private slots: + void addCurve(); + void removeCurve(); + void updateCurve(); + void updateState(); + void selectionChanged(); + void help(); + void apply(); + +private: + typedef QMap CurveProps; + typedef QMap PropMap; + + Plot2d_CurveContainer* myContainer; + PropMap myProperties; + Updater* myUpdater; + + QListWidget* myCurvesList; + QGroupBox* myCurveParams; + QLineEdit* myFormula; + QtxIntSpinBox* myNbIntervals; + QGroupBox* myCurveProps; + QCheckBox* myAutoAssign; + QWidget* myPropsGrp; + QComboBox* myMarkerType; + QComboBox* myLineType; + QtxIntSpinBox* myLineWidth; + QtxColorButton* myColor; + QPushButton* myAddButton; + QPushButton* myRemoveButton; +}; + +class Plot2d_AnalyticalCurveDlg::Updater : public QObject +{ + Q_OBJECT +public: + Updater( QWidget* parent ); + ~Updater(); +signals: + void update(); +}; + +#endif //PLOT2D_ANALYTICAL_CURVE_DLG_H diff --git a/src/Plot2d/Plot2d_AnalyticalParser.cxx b/src/Plot2d/Plot2d_AnalyticalParser.cxx new file mode 100755 index 000000000..9eb5ac79d --- /dev/null +++ b/src/Plot2d/Plot2d_AnalyticalParser.cxx @@ -0,0 +1,276 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : Plot2d_AnalyticalParser.cxx +// Author : Roman NIKOLAEV, Open CASCADE S.A.S. (roman.nikolaev@opencascade.com) +#include "Plot2d_AnalyticalParser.h" +#include + + +/* ================================== + * =========== PYTHON ============== + * ==================================*/ + +typedef struct { + PyObject_HEAD + int softspace; + std::string *out; + } PyStdOut; + +static void +PyStdOut_dealloc(PyStdOut *self) +{ + PyObject_Del(self); +} + +static PyObject * +PyStdOut_write(PyStdOut *self, PyObject *args) +{ + char *c; + int l; + if (!PyArg_ParseTuple(args, "t#:write",&c, &l)) + return NULL; + + //std::cerr << c ; + *(self->out)=*(self->out)+c; + + Py_INCREF(Py_None); + return Py_None; +} + +static PyMethodDef PyStdOut_methods[] = { + {"write", (PyCFunction)PyStdOut_write, METH_VARARGS, + PyDoc_STR("write(string) -> None")}, + {NULL, NULL} /* sentinel */ +}; + +static PyMemberDef PyStdOut_memberlist[] = { + {(char*)"softspace", T_INT, offsetof(PyStdOut, softspace), 0, + (char*)"flag indicating that a space needs to be printed; used by print"}, + {NULL} /* Sentinel */ +}; + +static PyTypeObject PyStdOut_Type = { + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyObject_HEAD_INIT(NULL) + 0, /*ob_size*/ + "PyOut", /*tp_name*/ + sizeof(PyStdOut), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)PyStdOut_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + PyObject_GenericGetAttr, /*tp_getattro*/ + /* softspace is writable: we must supply tp_setattro */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + PyStdOut_methods, /*tp_methods*/ + PyStdOut_memberlist, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ +}; + +PyObject * newPyStdOut( std::string& out ) +{ + PyStdOut *self; + self = PyObject_New(PyStdOut, &PyStdOut_Type); + if (self == NULL) + return NULL; + self->softspace = 0; + self->out=&out; + return (PyObject*)self; +} + + +////////////////////////END PYTHON/////////////////////////// + + +//! The only one instance of Parser +Plot2d_AnalyticalParser* Plot2d_AnalyticalParser::myParser = 0; + +//Define the script +QString Plot2d_AnalyticalParser::myScript = QString(""); + +/*! + \brief Return the only instance of the Plot2d_AnalyticalParser + \return instance of the Plot2d_AnalyticalParser +*/ +Plot2d_AnalyticalParser* Plot2d_AnalyticalParser::parser() +{ + if ( !myParser ) + myParser = new Plot2d_AnalyticalParser(); + return myParser; +} + +/*! + \brief Constructor. + + Construct the Parser and initialize python interpritator. +*/ +Plot2d_AnalyticalParser::Plot2d_AnalyticalParser() +{ + /* Initialize the Python interpreter */ + if (Py_IsInitialized()) { + PyGILState_STATE gstate = PyGILState_Ensure(); + myMainMod = PyImport_AddModule("__main__"); + myMainDict = PyModule_GetDict(myMainMod); + PyGILState_Release(gstate); + initScript(); + } +} + +int Plot2d_AnalyticalParser::calculate( const QString& theExpr, + const double theMin, + const double theMax, + const int theNbStep, + double** theX, + double** theY) { + + QString aPyScript = myScript; + aPyScript = aPyScript.arg(theExpr); + int result = -1; + PyGILState_STATE gstate = PyGILState_Ensure(); + PyObject* obj = PyRun_String(qPrintable(aPyScript), Py_file_input, myMainDict, NULL); + + if(obj == NULL) { + PyErr_Print(); + PyGILState_Release(gstate); + return result; + + } else { + Py_DECREF(obj); + } + + PyObject* func = NULL; + PyObject* f_y = NULL; + + if(PyObject_HasAttrString(myMainMod, "Y")) { + f_y = PyObject_GetAttrString(myMainMod, "Y"); + } + + if(PyObject_HasAttrString(myMainMod, "coordCalculator")) { + func = PyObject_GetAttrString(myMainMod, "coordCalculator"); + } + + PyObject* new_stderr = NULL; + + if( f_y == NULL || func == NULL ) { + fflush(stderr); + std::string err_description=""; + new_stderr = newPyStdOut(err_description); + PySys_SetObject((char*)"stderr", new_stderr); + PyErr_Print(); + PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__")); + Py_DECREF(new_stderr); + PyGILState_Release(gstate); + return result; + } + + PyObject* coords; + coords = PyObject_CallFunction(func,(char*)"(d, d, i)", theMin, theMax, theNbStep ); + + new_stderr = NULL; + + if (coords == NULL){ + fflush(stderr); + std::string err_description=""; + new_stderr = newPyStdOut(err_description); + PySys_SetObject((char*)"stderr", new_stderr); + PyErr_Print(); + PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__")); + Py_DECREF(new_stderr); + PyGILState_Release(gstate); + return result; + } + + Py_ssize_t size = PyList_Size( coords ); + if( size <= 0 ) { + Py_DECREF(coords); + return result; + } + + result = size; + + *theX = new double[size]; + *theY = new double[size]; + + for ( Py_ssize_t i = 0; i< size; ++i ) { + PyObject* coord = PyList_GetItem( coords, i ); + (*theX)[i] = PyFloat_AsDouble(PyList_GetItem(coord, 0)); + (*theY)[i] = PyFloat_AsDouble(PyList_GetItem(coord, 1)); + } + + PyGILState_Release(gstate); + return result; +} + +/*! + \brief Initialize python script. +*/ +void Plot2d_AnalyticalParser::initScript() { + myScript.clear(); + myScript += "from math import * \n"; + myScript += "def Y(x): \n"; + myScript += " return "; + myScript += "%1\n"; + + myScript += "def coordCalculator(xmin, xmax, nstep): \n"; + myScript += " coords = [] \n"; + myScript += " xstep = (xmax - xmin) / nstep \n"; + myScript += " n = 0 \n"; + myScript += " while n <= nstep : \n"; + myScript += " x = xmin + n*xstep \n"; + myScript += " try: \n"; + myScript += " y = Y(x) \n"; + myScript += " coords.append([x,y]) \n"; + myScript += " except ValueError, ZeroDivisionError: \n"; + myScript += " pass \n"; + myScript += " n = n+1 \n"; + myScript += " return coords \n"; +} diff --git a/src/Plot2d/Plot2d_AnalyticalParser.h b/src/Plot2d/Plot2d_AnalyticalParser.h new file mode 100755 index 000000000..6f9f6e6e3 --- /dev/null +++ b/src/Plot2d/Plot2d_AnalyticalParser.h @@ -0,0 +1,52 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : Plot2d_AnalyticalParser.h +// Author : Roman NIKOLAEV, Open CASCADE S.A.S. (roman.nikolaev@opencascade.com) + +#ifndef PLOT2D_ANALYTICAL_Parser_H +#define PLOT2D_ANALYTICAL_Parser_H +#include + +#include "Plot2d.h" + +class PLOT2D_EXPORT Plot2d_AnalyticalParser { +public: + ~Plot2d_AnalyticalParser(); + + + static Plot2d_AnalyticalParser* parser(); + int calculate( const QString&, const double, + const double, const int, + double**, double**); + +private: + Plot2d_AnalyticalParser(); + void initScript(); + +private: + static Plot2d_AnalyticalParser* myParser; //!< instance of the Parser + PyObject* myMainMod; //!< main python module + PyObject* myMainDict; //!< main python dictionary + static QString myScript; //!< python script +}; + +#endif //PLOT2D_ANALYTICAL_Parser_H diff --git a/src/Plot2d/Plot2d_Histogram.cxx b/src/Plot2d/Plot2d_Histogram.cxx new file mode 100644 index 000000000..dec1fd9a1 --- /dev/null +++ b/src/Plot2d/Plot2d_Histogram.cxx @@ -0,0 +1,258 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : Plot2d_Histogram.cxx +// Author : Natalia ERMOLAEVA, Open CASCADE S.A.S. (natalia.donis@opencascade.com) + +#include "Plot2d_Histogram.h" +#include "Plot2d_PlotItems.h" + +#include + +const int MAX_ATTEMPTS = 10; // max attempts + +/*! + Constructor. +*/ +Plot2d_Histogram::Plot2d_Histogram() +: Plot2d_Object(), + myColor( 0, 0, 0 ), + myWidth( 0 ), + myDefWidth( 0 ) +{ +} + +/*! + Destructor. +*/ +Plot2d_Histogram::~Plot2d_Histogram() +{ +} + +/*! + Copy constructor. Makes deep copy of data. +*/ +Plot2d_Histogram::Plot2d_Histogram( const Plot2d_Histogram& hist ) +: Plot2d_Object( hist ) +{ + myColor = hist.myColor; + myWidth = hist.myWidth; + myDefWidth = hist.myDefWidth; +} + +/*! + operator=. Makes deep copy of data. +*/ +Plot2d_Histogram& Plot2d_Histogram::operator=( const Plot2d_Histogram& hist ) +{ + Plot2d_Object::operator=(hist); + myColor = hist.myColor; + myWidth = hist.myWidth; + myDefWidth = hist.myDefWidth; + return *this; +} + +/*! + Get typeid for the plot2d histogram class +*/ +int Plot2d_Histogram::rtti() +{ + return QwtPlotItem::Rtti_PlotHistogram; +} + +/*! + Create plot object for the histogram +*/ +QwtPlotItem* Plot2d_Histogram::createPlotItem() +{ + Plot2d_HistogramItem* anItem = new Plot2d_HistogramItem(); + updatePlotItem( anItem ); + return anItem; +} + +/*! + Auto fill parameters of object by plot view +*/ +void Plot2d_Histogram::autoFill( const QwtPlot* thePlot ) +{ + setColor( getNextColor( thePlot ) ); +} + +/*! + Updates histogram fields +*/ +void Plot2d_Histogram::updatePlotItem( QwtPlotItem* theItem ) +{ + if ( theItem->rtti() != rtti() ) + return; + + Plot2d_HistogramItem* anItem = dynamic_cast( theItem ); + if ( !anItem ) + return; + + Plot2d_Object::updatePlotItem( theItem ); + + anItem->setData( getData() ); + anItem->setLegendPen(getColor()); + anItem->setSelected(isSelected()); + anItem->setColor( isSelected() ? Plot2d_Object::selectionColor() : getColor() ); +} + +/*! + Sets data to object +*/ +void Plot2d_Histogram::setData( const QList& theXVals, + const QList& theYVals ) +{ + pointList aPoints; + int aSize = theXVals.size(); + for ( int i = 0; i < aSize; i++ ) + aPoints.append( Plot2d_Point( theXVals[i], theYVals[i] ) ); + setPointList( aPoints ); + + myDefWidth = getMinInterval( theXVals )*(2./3.); + myWidth = 0; // myDefWidth // VSR: width should not be automatically reset to myDefWidth +} + +/*! + Gets data +*/ +QwtIntervalData Plot2d_Histogram::getData() const +{ + pointList aPoints = getPointList(); + int aSize = aPoints.size(); + + QwtArray anIntervals( aSize ); + QwtArray aValues( aSize ); + double aX; + double aWidth = myWidth <= 0 ? myDefWidth : myWidth; // VSR: width is either manually assigned or auto-calculated + for ( int i = 0; i < aSize; i++ ) { + aX = aPoints[i].x; + anIntervals[i] = QwtDoubleInterval( aX - aWidth/2, aX + aWidth/2 ); + aValues[i] = aPoints[i].y; + } + + return QwtIntervalData( anIntervals, aValues ); +} + +/*! + Sets color of histogram +*/ +void Plot2d_Histogram::setColor( const QColor& theColor ) +{ + myColor = theColor; + setAutoAssign( false ); +} + +/*! + Returns color of histogram +*/ +QColor Plot2d_Histogram::getColor() const +{ + return myColor; +} + +/*! + Sets custom width of a histogram bar +*/ +void Plot2d_Histogram::setWidth( const double theWidth ) +{ + myWidth = theWidth; + //setAutoAssign( false ); // VSR: width attribute is not auto-assigned +} + +/*! + Returns custom or automatic width for a histogram bar +*/ +double Plot2d_Histogram::getWidth( const bool isDef ) const +{ + return isDef ? myDefWidth : myWidth; +} + +/*! + Gets new unique marker for item if possible +*/ +QColor Plot2d_Histogram::getNextColor( const QwtPlot* thePlot ) +{ + bool bOk = false; + int cnt = 0; + QColor aColor; + while ( !bOk ) { + int aRed = (int)( 256.0 * rand() / RAND_MAX); // generate random color + int aGreen = (int)( 256.0 * rand() / RAND_MAX); // ... + int aBlue = (int)( 256.0 * rand() / RAND_MAX); // ... + aColor = QColor( aRed, aGreen, aBlue ); + bOk = ( ++cnt == MAX_ATTEMPTS ) || !existColor( thePlot, aColor ); + } + return aColor; +} + +/*! + Checks if color is already user by other histogram entity +*/ +bool Plot2d_Histogram::existColor( const QwtPlot* thePlot, const QColor& theColor ) +{ + bool ok = false; + + QColor bgColor = thePlot->palette().color( QPalette::Background ); + if ( Plot2d::closeColors( theColor, bgColor ) ) { + ok = true; + } + else { + QwtPlotItemList anItems = thePlot->itemList(); + QwtPlotItemIterator anIt = anItems.begin(), aLast = anItems.end(); + QwtPlotItem* anItem; + for( ; anIt != aLast && !ok; anIt++ ) { + anItem = *anIt; + if ( !anItem ) + continue; + if ( anItem->rtti() == rtti() ) { + Plot2d_HistogramItem* aHItem = dynamic_cast( anItem ); + ok = aHItem && Plot2d::closeColors( theColor, aHItem->color() ); + } + else if ( anItem->rtti() == QwtPlotItem::Rtti_PlotCurve ) { + QwtPlotCurve* aCurve = dynamic_cast( anItem ); + ok = aCurve && Plot2d::closeColors( theColor, aCurve->pen().color() ); + } + } + } + return ok; +} + +/*! + Return min interval from values +*/ +double Plot2d_Histogram::getMinInterval( const QList& theVals ) +{ + double aValue = -1; + int aSize = theVals.size(); + if ( aSize > 1 ) { + aValue = qAbs( theVals[1] - theVals[0] ); + double aDelta; + for ( int i = 2; i < aSize; i++ ) { + aDelta = qAbs( theVals[i] - theVals[i-1] ); + aValue = qMin( aValue, qMax( aDelta, 0. ) ); + } + aValue = aValue/2; + } + return aValue; +} + diff --git a/src/Plot2d/Plot2d_Histogram.h b/src/Plot2d/Plot2d_Histogram.h new file mode 100644 index 000000000..564aca0d9 --- /dev/null +++ b/src/Plot2d/Plot2d_Histogram.h @@ -0,0 +1,68 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : Plot2d_Histogram.h +// Author : Natalia ERMOLAEVA, Open CASCADE S.A.S. (natalia.donis@opencascade.com) + +#ifndef PLOT2D_HISTOGRAM_H +#define PLOT2D_HISTOGRAM_H + +#include "Plot2d.h" +#include "Plot2d_Object.h" + +#include + +class PLOT2D_EXPORT Plot2d_Histogram : public Plot2d_Object +{ +public: + Plot2d_Histogram(); + Plot2d_Histogram( const Plot2d_Histogram& ); + + virtual ~Plot2d_Histogram(); + Plot2d_Histogram& operator= ( const Plot2d_Histogram& ); + + virtual int rtti(); + virtual QwtPlotItem* createPlotItem(); + virtual void autoFill( const QwtPlot* ); + virtual void updatePlotItem( QwtPlotItem* ); + + void setData( const QList&, const QList& ); + QwtIntervalData getData() const; + + void setColor( const QColor& ); + QColor getColor() const; + + void setWidth( const double ); + double getWidth( const bool ) const; + + static double getMinInterval( const QList& ); + +protected: + QColor getNextColor( const QwtPlot* ); + bool existColor( const QwtPlot*, const QColor& ); + +private: + QColor myColor; + double myWidth; + double myDefWidth; +}; + +#endif // PLOT2D_HISTOGRAM_H diff --git a/src/Plot2d/Plot2d_NormalizeAlgorithm.cxx b/src/Plot2d/Plot2d_NormalizeAlgorithm.cxx new file mode 100755 index 000000000..dd21e1a84 --- /dev/null +++ b/src/Plot2d/Plot2d_NormalizeAlgorithm.cxx @@ -0,0 +1,182 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : Plot2d_NormalizeAlgorithm.cxx + +#include "Plot2d_NormalizeAlgorithm.h" +#include +#include +#include "Plot2d_Object.h" + +/*! + Constructor +*/ +Plot2d_NormalizeAlgorithm::Plot2d_NormalizeAlgorithm(QObject *parent) : + Plot2d_Algorithm(parent), + myNormalizationMode(NormalizeNone) +{ +} + +/*! + Destructor +*/ +Plot2d_NormalizeAlgorithm::~Plot2d_NormalizeAlgorithm() +{ +} + +/*! + Sets normalozation mode +*/ +void Plot2d_NormalizeAlgorithm::setNormalizationMode(NormalizationMode theMode) { + if(myNormalizationMode != theMode) { + myNormalizationMode = theMode; + myDataChanged = true; + } +} + +/*! + Gets normalozation mode +*/ +Plot2d_NormalizeAlgorithm::NormalizationMode Plot2d_NormalizeAlgorithm::getNormalizationMode()const { + return myNormalizationMode; +} + +/*! + Gets k normalization coefficient +*/ +double Plot2d_NormalizeAlgorithm::getKkoef(Plot2d_Object* theObj) +{ + QMap::iterator it = myKkoefs.find(theObj); + if(it != myKkoefs.end()) + return it.value(); + return 0; +} + +/*! + Gets b normalization coefficient +*/ +double Plot2d_NormalizeAlgorithm::getBkoef(Plot2d_Object* theObj) +{ + QMap::iterator it = myBkoefs.find(theObj); + if(it != myBkoefs.end()) + return it.value(); + return 0; + +} + +void Plot2d_NormalizeAlgorithm::execute() { + if (!isDataChanged() || myInuptData.isEmpty()) + return; + + if (myNormalizationMode != NormalizeNone) { + QList yMinLst, yMaxLst; + QList aKkoefs,aBkoefs; + double _pMin, _pMax; + for (int i = 0; i < myInuptData.size(); ++i) { + QList aTmpItemValues; + Plot2d_Object* object = myInuptData.at(i); + double *x, *y; + long nb = object->getData( &x, &y ); + for (int j = 0; j < nb; ++j) { + aTmpItemValues<getPoint(j).y; + } + delete x; + delete y; + yMaxLst<<*(std::max_element(aTmpItemValues.begin(), aTmpItemValues.end())); + yMinLst<<*(std::min_element(aTmpItemValues.begin(), aTmpItemValues.end())); + } + _pMin = *(std::min_element(yMinLst.begin(), yMinLst.end())); + _pMax = *(std::max_element(yMaxLst.begin(), yMaxLst.end())); + + double pMin, pMax, kKoef, bKoef, yMin, yMax; + switch( getNormalizationMode() ) { + case NormalizeToMin: + pMin = _pMin; + for (int i = 0; i < yMaxLst.size(); ++i) { + yMin = yMinLst.at(i); + yMax = yMaxLst.at(i); + pMax = yMax; + kKoef = (pMax - pMin)/(yMax - yMin); + bKoef = pMin - kKoef * yMin; + aBkoefs<nbPoints(); ++j) { + yOld = myInuptData.at(i)->getPoint(j).y; + xOld = myInuptData.at(i)->getPoint(j).x; + yNew = aKkoefs.at(i) * yOld + aBkoefs.at(i); + tmpItem.append( qMakePair(xOld, yNew) ); + } + myResultData.insert(myInuptData.at(i),tmpItem); + myKkoefs.insert(myInuptData.at(i),aKkoefs.at(i)); + myBkoefs.insert(myInuptData.at(i),aBkoefs.at(i)); + } + } else { + for (int i = 0; i < myInuptData.size(); ++i) { + double yOld,xOld; + AlgoPlot2dItem tmpItem; + for (int j = 0; j < myInuptData.at(i)->nbPoints(); ++j) { + yOld = myInuptData.at(i)->getPoint(j).y; + xOld = myInuptData.at(i)->getPoint(j).x; + tmpItem.append( qMakePair(xOld, yOld) ); + } + myResultData.insert(myInuptData.at(i),tmpItem); + } + } + myDataChanged = false; +} + + +void Plot2d_NormalizeAlgorithm::clear() { + Plot2d_Algorithm::clear(); + myBkoefs.clear(); + myKkoefs.clear(); +} diff --git a/src/Plot2d/Plot2d_NormalizeAlgorithm.h b/src/Plot2d/Plot2d_NormalizeAlgorithm.h new file mode 100755 index 000000000..c25e49237 --- /dev/null +++ b/src/Plot2d/Plot2d_NormalizeAlgorithm.h @@ -0,0 +1,54 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : Plot2d_NormalizeAlgorithm.h + +#ifndef PLOT2D_NORMALIZEALGORITHM_H +#define PLOT2D_NORMALIZEALGORITHM_H + +#include "Plot2d.h" +#include "Plot2d_Algorithm.h" +#include + +class Plot2d_Object; + +class PLOT2D_EXPORT Plot2d_NormalizeAlgorithm : public Plot2d_Algorithm { + Q_OBJECT +public: + Plot2d_NormalizeAlgorithm(QObject *parent); + ~Plot2d_NormalizeAlgorithm(); + + enum NormalizationMode { NormalizeToMin, NormalizeToMax, NormalizeToMinMax, NormalizeNone }; + + void setNormalizationMode(NormalizationMode); + NormalizationMode getNormalizationMode() const; + double getKkoef(Plot2d_Object*); + double getBkoef(Plot2d_Object*); + virtual void execute(); + virtual void clear(); + +private: + NormalizationMode myNormalizationMode; + QMap myBkoefs; + QMap myKkoefs; +}; + +#endif //PLOT2D_NORMALIZEALGORITHM_H diff --git a/src/Plot2d/Plot2d_Object.cxx b/src/Plot2d/Plot2d_Object.cxx new file mode 100755 index 000000000..376a697b1 --- /dev/null +++ b/src/Plot2d/Plot2d_Object.cxx @@ -0,0 +1,543 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : Plot2d_Object.cxx +// Author : Natalia ERMOLAEVA, Open CASCADE S.A.S. (natalia.donis@opencascade.com) +// + +#include "Plot2d_Object.h" + + +#include +#include + +// Static members +QColor Plot2d_Object::mySelectionColor; +QColor Plot2d_Object::myHighlightedLegendTextColor; + +/* + * Read colors from the resource manager. +*/ +void Plot2d_Object::initColors() { + SUIT_Session* session = SUIT_Session::session(); + if(!session) + return; + + SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr(); + if(resMgr) { + mySelectionColor = resMgr->colorValue( "Plot2d", "SelectionColor", QColor(80,80,80) ); + myHighlightedLegendTextColor = resMgr->colorValue( "Plot2d", "SelectedLegendFontColor", QColor(255,255,255) ); + } +} + +/*! + Constructor +*/ +Plot2d_Object::Plot2d_Object() +: myAutoAssign( true ), + myHorTitle( "" ), myVerTitle( "" ), + myHorUnits( "" ), myVerUnits( "" ), + myName( "" ), + myXAxis( QwtPlot::xBottom ), + myYAxis( QwtPlot::yLeft ), + myIsSelected(false), + myScale ( 1.0 ) +{ +} + +/*! + Destructor +*/ +Plot2d_Object::~Plot2d_Object() +{ +} + +/*! + Copy constructor. Makes deep copy of data. +*/ +Plot2d_Object::Plot2d_Object( const Plot2d_Object& object ) +{ + myAutoAssign = object.isAutoAssign(); + myHorTitle = object.getHorTitle(); + myVerTitle = object.getVerTitle(); + myHorUnits = object.getHorUnits(); + myVerUnits = object.getVerUnits(); + myName = object.getName(); + myXAxis = object.getXAxis(); + myYAxis = object.getYAxis(); + myPoints = object.getPointList(); + myScale = object.getScale(); +} + +/*! + operator=. Makes deep copy of data. +*/ +Plot2d_Object& Plot2d_Object::operator=( const Plot2d_Object& object ) +{ + myAutoAssign = object.isAutoAssign(); + myHorTitle = object.getHorTitle(); + myVerTitle = object.getVerTitle(); + myHorUnits = object.getHorUnits(); + myVerUnits = object.getVerUnits(); + myName = object.getName(); + myXAxis = object.getXAxis(); + myYAxis = object.getYAxis(); + myPoints = object.getPointList(); + myScale = object.getScale(); + return *this; +} + +/*! + Auto fill parameters of object by plot view +*/ +void Plot2d_Object::autoFill( const QwtPlot* ) +{ +} + +/*! + * Updates object fields + */ +void Plot2d_Object::updatePlotItem( QwtPlotItem* theItem ) +{ + if ( !theItem || theItem->rtti() != rtti() ) + return; + + if ( theItem->yAxis() != getYAxis() || theItem->xAxis() != getXAxis() ) { + theItem->setAxis( getXAxis(), getYAxis() ); + + QwtPlot* aPlot = theItem->plot(); + if ( aPlot ) { + theItem->detach(); + theItem->attach( aPlot ); + } + } + QString name = !getName().isEmpty() ? getName() : getVerTitle(); + if( myScale != 1.0 ) + name = name + QString("( *%1 )").arg(myScale); + theItem->setTitle( name ); +} + +/*! + \return title of table +*/ +QString Plot2d_Object::getTableTitle() const +{ + return QString(); +} + +/*! + Sets object's horizontal title +*/ +void Plot2d_Object::setHorTitle( const QString& title ) +{ + myHorTitle = title; +} + +/*! + Gets object's horizontal title +*/ +QString Plot2d_Object::getHorTitle() const +{ + return myHorTitle; +} + +/*! + Sets object's vertical title +*/ +void Plot2d_Object::setVerTitle( const QString& title ) +{ + myVerTitle = title; +} + +/*! + Gets object's vertical title +*/ +QString Plot2d_Object::getVerTitle() const +{ + return myVerTitle; +} + +/*! + Sets object's horizontal units +*/ +void Plot2d_Object::setHorUnits( const QString& units ) +{ + myHorUnits = units; +} + +/*! + Gets object's horizontal units +*/ +QString Plot2d_Object::getHorUnits() const +{ + return myHorUnits; +} + +/*! + Sets object's vertical units +*/ +void Plot2d_Object::setVerUnits( const QString& units ) +{ + myVerUnits = units; +} + +/*! + Gets object's vertical units +*/ +QString Plot2d_Object::getVerUnits() const +{ + return myVerUnits; +} + +/*! + Sets object's name + */ +void Plot2d_Object::setName( const QString& theName ) +{ + myName = theName; +} +/*! + Gets object's name + */ +QString Plot2d_Object::getName() const +{ + return myName; +} + +/*! + Sets object's scale factor + */ +void Plot2d_Object::setScale( double theScale ) +{ + myScale = theScale; +} +/*! + Gets object's scale factor + */ +double Plot2d_Object::getScale() const +{ + return myScale; +} + +/*! + Adds one point for object. +*/ +void Plot2d_Object::addPoint( double theX, double theY, const QString& theText ) +{ + addPoint( Plot2d_Point( theX, theY, theText ) ); +} + +/*! + Adds one point for object. +*/ +void Plot2d_Object::addPoint( const Plot2d_Point& thePoint ) +{ + myPoints.append( thePoint ); +} + +/*! + Insert one point for object on some position. +*/ +void Plot2d_Object::insertPoint( int thePos, double theX, double theY, + const QString& theText ) +{ + insertPoint( thePos, Plot2d_Point( theX, theY, theText ) ); +} + +/*! + Insert one point for object on some position. +*/ +void Plot2d_Object::insertPoint( int thePos, const Plot2d_Point& thePoint ) +{ + if ( thePos < 0 ) + myPoints.append( thePoint ); + else + myPoints.insert( thePos, thePoint ); +} + +/*! + Delete one point for object on some position. +*/ +void Plot2d_Object::deletePoint(int thePos) +{ + if ( thePos >= 0 && thePos < myPoints.count() ) + myPoints.removeAt( thePos ); +} + +/*! + Remove all points for object. +*/ +void Plot2d_Object::clearAllPoints() +{ + myPoints.clear(); +} + +/*! + Gets object's data : abscissas of points +*/ +pointList Plot2d_Object::getPointList() const +{ + return myPoints; +} + +/*! + Gets points by index. +*/ + +Plot2d_Point& Plot2d_Object::getPoint(int index) { + return myPoints[index]; +} + +/*! + Gets object's data : abscissas of points +*/ +void Plot2d_Object::setPointList( const pointList& points ) +{ + myPoints = points; +} + +/*! + Sets object's data. +*/ +void Plot2d_Object::setData( const double* hData, const double* vData, long size, const QStringList& lst ) +{ + clearAllPoints(); + QStringList::const_iterator anIt = lst.begin(), aLast = lst.end(); + for ( long i = 0; i < size; i++, anIt++ ) + addPoint( hData[i], vData[i], anIt==aLast ? QString() : *anIt ); +} + +/*! + Gets object's data : abscissas of points +*/ +double* Plot2d_Object::horData() const +{ + int aNPoints = nbPoints(); + double* aX = new double[aNPoints]; + for (int i = 0; i < aNPoints; i++) { + aX[i] = myPoints[i].x; + } + return aX; +} + +/*! + Gets object's data : ordinates of points +*/ +double* Plot2d_Object::verData() const +{ + int aNPoints = nbPoints(); + double* aY = new double[aNPoints]; + for (int i = 0; i < aNPoints; i++) { + aY[i] = myScale * myPoints[i].y; + } + return aY; +} + +/*! + Gets object's data +*/ +long Plot2d_Object::getData( double** theX, double** theY ) const +{ + int aNPoints = nbPoints(); + *theX = new double[aNPoints]; + *theY = new double[aNPoints]; + for (int i = 0; i < aNPoints; i++) { + (*theX)[i] = myPoints[i].x; + (*theY)[i] = myScale * myPoints[i].y; + } + return aNPoints; +} + +/*! + Changes text assigned to point of object + \param ind -- index of point + \param txt -- new text +*/ +void Plot2d_Object::setText( const int ind, const QString& txt ) +{ + if ( ind >= 0 && ind < myPoints.count() ) + myPoints[ind].text = txt; +} + +/*! + \return text assigned to point + \param ind -- index of point +*/ +QString Plot2d_Object::text( const int ind ) const +{ + return ( ind >= 0 && ind < myPoints.count() ) ? myPoints[ind].text : QString(); +} + +/*! + Gets object's data : number of points +*/ +int Plot2d_Object::nbPoints() const +{ + return myPoints.count(); +} + +/*! + Returns true if object has no data +*/ +bool Plot2d_Object::isEmpty() const +{ + return myPoints.isEmpty(); +} + +/*! + Sets object's AutoAssign flag - in this case attributes will be set automatically +*/ +void Plot2d_Object::setAutoAssign( bool on ) +{ + myAutoAssign = on; +} + +/*! + Gets object's AutoAssign flag state +*/ +bool Plot2d_Object::isAutoAssign() const +{ + return myAutoAssign; +} + +/*! + Sets object's x axis +*/ +void Plot2d_Object::setXAxis(QwtPlot::Axis theXAxis) +{ + if (theXAxis == QwtPlot::xBottom || theXAxis == QwtPlot::xTop) + myXAxis = theXAxis; +} + +/*! + Gets object's x axis +*/ +QwtPlot::Axis Plot2d_Object::getXAxis() const +{ + return myXAxis; +} + +/*! + Sets object's y axis +*/ +void Plot2d_Object::setYAxis(QwtPlot::Axis theYAxis) +{ + if (theYAxis == QwtPlot::yLeft || theYAxis == QwtPlot::yRight) + myYAxis = theYAxis; +} + +/*! + Gets object's y axis +*/ +QwtPlot::Axis Plot2d_Object::getYAxis() const +{ + return myYAxis; +} + +/*! + Gets object's minimal abscissa +*/ +double Plot2d_Object::getMinX() const +{ + double aMinX = 1e150; + pointList::const_iterator aIt; + for (aIt = myPoints.begin(); aIt != myPoints.end(); ++aIt) + aMinX = qMin( aMinX, (*aIt).x ); + return aMinX; +} + +/*! + Gets object's maximal abscissa +*/ +double Plot2d_Object::getMaxX() const +{ + double aMaxX = -1e150; + pointList::const_iterator aIt; + for (aIt = myPoints.begin(); aIt != myPoints.end(); ++aIt) + aMaxX = qMax( aMaxX, (*aIt).x ); + return aMaxX; +} + +/*! + Gets object's minimal ordinate +*/ +double Plot2d_Object::getMinY() const +{ + double aMinY = 1e150; + pointList::const_iterator aIt; + for (aIt = myPoints.begin(); aIt != myPoints.end(); ++aIt) + aMinY = qMin( aMinY, myScale * (*aIt).y ); + return aMinY; +} + +/*! + Gets object's maximal ordinate +*/ +double Plot2d_Object::getMaxY() const +{ + double aMaxY = -1e150; + pointList::const_iterator aIt; + for (aIt = myPoints.begin(); aIt != myPoints.end(); ++aIt) + aMaxY = qMax( aMaxY, myScale * (*aIt).y ); + return aMaxY; +} + +/*! + Sets object's selected property +*/ +void Plot2d_Object::setSelected(const bool on) { + myIsSelected = on; +} + +/*! + Gets object's selected property +*/ +bool Plot2d_Object::isSelected() const { + return myIsSelected; +} + +/*! + * Sets selection color of the object. +*/ +void Plot2d_Object::setSelectionColor(const QColor& c) { + mySelectionColor = c; +} + +/*! + * Return selection color of the object. +*/ +QColor Plot2d_Object::selectionColor() { + return mySelectionColor; +} + +/*! + * Sets font color of the selected legend item. +*/ +void Plot2d_Object::setHighlightedLegendTextColor(const QColor& c) { + myHighlightedLegendTextColor = c; +} + +/*! + * Sets font color of the selected legend item. +*/ +QColor Plot2d_Object::highlightedLegendTextColor() { + return myHighlightedLegendTextColor; +} diff --git a/src/Plot2d/Plot2d_Object.h b/src/Plot2d/Plot2d_Object.h new file mode 100755 index 000000000..5afd6b1a5 --- /dev/null +++ b/src/Plot2d/Plot2d_Object.h @@ -0,0 +1,138 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : Plot2d_Object.h +// Author : Natalia ERMOLAEVA, Open CASCADE S.A.S. (natalia.donis@opencascade.com) +// + +#ifndef PLOT2D_OBJECT_H +#define PLOT2D_OBJECT_H + +#include "Plot2d.h" + +#include +#include + + +class PLOT2D_EXPORT Plot2d_Object +{ +public: + Plot2d_Object(); + Plot2d_Object( const Plot2d_Object& ); + + virtual ~Plot2d_Object(); + Plot2d_Object& operator= ( const Plot2d_Object& ); + + virtual int rtti() = 0; + virtual QwtPlotItem* createPlotItem() = 0; + virtual void autoFill( const QwtPlot* ); + virtual void updatePlotItem( QwtPlotItem* ); + + virtual QString getTableTitle() const; + + void setHorTitle( const QString& ); + QString getHorTitle() const; + void setVerTitle( const QString& ); + QString getVerTitle() const; + + void setHorUnits( const QString& ); + QString getHorUnits() const; + void setVerUnits( const QString& ); + QString getVerUnits() const; + + void setName( const QString& ); + QString getName() const; + + void setScale( double ); + double getScale() const; + + void addPoint( double, double, const QString& = QString() ); + void addPoint( const Plot2d_Point& ); + void insertPoint( int, double, double, const QString& = QString() ); + void insertPoint( int, const Plot2d_Point& ); + void deletePoint( int ); + void clearAllPoints(); + pointList getPointList() const; + void setPointList( const pointList& points ); + Plot2d_Point& getPoint(int index); + + void setData( const double*, const double*, + long, const QStringList& = QStringList() ); + double* horData() const; + double* verData() const; + long getData( double**, double** ) const; + + void setText( const int, const QString& ); + QString text( const int ) const; + + int nbPoints() const; + bool isEmpty() const; + + void setAutoAssign( bool ); + bool isAutoAssign() const; + + void setXAxis( QwtPlot::Axis ); + QwtPlot::Axis getXAxis() const; + void setYAxis( QwtPlot::Axis ); + QwtPlot::Axis getYAxis() const; + + // Protection against QwtObject::drawLines() bug in Qwt 0.4.x: + // it crashes if switched to X/Y logarithmic mode, when one or more points have + // non-positive X/Y coordinate + virtual double getMinX() const; + virtual double getMaxX() const; + virtual double getMinY() const; + virtual double getMaxY() const; + + void setSelected(const bool); + bool isSelected() const; + + static void initColors(); + + static void setSelectionColor(const QColor& c); + static QColor selectionColor(); + + static void setHighlightedLegendTextColor(const QColor& c); + static QColor highlightedLegendTextColor(); + +protected: + bool myAutoAssign; + QString myHorTitle; + QString myVerTitle; + QString myHorUnits; + QString myVerUnits; + QString myName; + QwtPlot::Axis myXAxis; + QwtPlot::Axis myYAxis; + + double myScale; + + pointList myPoints; + bool myIsSelected; + + private: + static QColor mySelectionColor; //!< Color of the selected curve or histogram + static QColor myHighlightedLegendTextColor; //!< Color of the selected legend item font +}; + +typedef QList objectList; + +#endif diff --git a/src/Plot2d/Plot2d_PlotItems.cxx b/src/Plot2d/Plot2d_PlotItems.cxx new file mode 100644 index 000000000..95a2d2def --- /dev/null +++ b/src/Plot2d/Plot2d_PlotItems.cxx @@ -0,0 +1,933 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : Plot2d_HistogramItem.cxx +// Author : Natalia ERMOLAEVA, Open CASCADE S.A.S. (natalia.donis@opencascade.com) + +#include "Plot2d_PlotItems.h" +#include "Plot2d_Object.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +const char* yAxisLeft[] = { + "12 12 2 1", + " c None", + ". c #000000", + " ", + " . ", + " ... ", + " . . . ", + " . ", + " . ", + " . . ", + " . . ", + " ........ ", + " . ", + " . ", + " "}; + +const char* yAxisRight[] = { + "12 12 2 1", + " c None", + ". c #000000", + " ", + " . ", + " ... ", + " . . . ", + " . ", + " . ", + " . . ", + " . . ", + " ........ ", + " . ", + " . ", + " "}; + +/*! + Constructor of Plot2d_QwtLegendItem +*/ +Plot2d_QwtLegendItem::Plot2d_QwtLegendItem( QWidget* parent ) : + QwtLegendItem( parent ), + myYAxisIdentifierMode( IM_None ), + myIsSelected(false) +{ + myYAxisLeftIcon = yAxisLeft; + myYAxisRightIcon = yAxisRight; + int anIconWidth = qMax( myYAxisLeftIcon.width(), myYAxisRightIcon.width() ); + + mySpacingCollapsed = spacing(); + mySpacingExpanded = anIconWidth - mySpacingCollapsed; +} + +/*! + Destructor of Plot2d_QwtLegendItem +*/ +Plot2d_QwtLegendItem::~Plot2d_QwtLegendItem() +{ +} + +/*! + Set Y axis identifier displaying mode +*/ +void Plot2d_QwtLegendItem::setYAxisIdentifierMode( const int theMode ) +{ + myYAxisIdentifierMode = theMode; + setSpacing( theMode == IM_None ? mySpacingCollapsed : mySpacingExpanded ); +} + +/*! + Redefined method of drawing identifier of legend item +*/ +void Plot2d_QwtLegendItem::drawIdentifier( QPainter* painter, const QRect& rect ) const +{ + QwtLegendItem::drawIdentifier( painter, rect ); + + if( myYAxisIdentifierMode != IM_None ) { + QPixmap aPixmap( myYAxisIdentifierMode == IM_Left ? yAxisLeft : yAxisRight ); + painter->save(); + painter->drawPixmap( rect.topRight() + QPoint( mySpacingExpanded/2, mySpacingExpanded/2 ), aPixmap ); + painter->restore(); + } +} + +/*! + Update highliting on the item. +*/ +void Plot2d_QwtLegendItem::updateHighlit() { + QwtText txt = text(); + if(isSelected()) { + QColor highlightColor = Plot2d_Object::selectionColor(); + if(highlightColor != txt.backgroundBrush().color()) { + txt.setBackgroundBrush(highlightColor); + setText(txt); + } + } else if( QWidget* parent = qobject_cast(this->parent()->parent()) ) { + QPalette aPal = parent->palette(); + if(aPal.color(QPalette::Background) != txt.backgroundBrush().color()) { + txt.setBackgroundBrush(aPal.color(QPalette::Background)); + setText(txt); + } + } +} + +/*! + Sets selected property. +*/ +void Plot2d_QwtLegendItem::setSelected(const bool on) { + myIsSelected = on; +} + +/*! + Gets selected property. +*/ +bool Plot2d_QwtLegendItem::isSelected() const { + return myIsSelected; +} + + +/* + Draw text of the item. +*/ +void Plot2d_QwtLegendItem::drawText(QPainter * painter, const QRect &rect) { + painter->setPen( isSelected() ? Plot2d_Object::highlightedLegendTextColor() : + getColorFromPalette( QPalette::Text) ); + + QwtLegendItem::drawText( painter, rect ); +} + +/* + Get color from the legend pallete by 'role' flag. +*/ +QColor Plot2d_QwtLegendItem::getColorFromPalette(QPalette::ColorRole role) { + QWidget* pw = parentWidget(); + QColor col = palette().color( role ); + while( pw ) { + if ( qobject_cast( pw ) ) { + col = pw->palette().color(role ); + break; + } + pw = pw->parentWidget(); + } + return col; +} +/* + * Internal class to store deviation data on the curve. + */ +class Plot2d_QwtPlotCurve::Plot2d_DeviationData { +public: + Plot2d_DeviationData(const double *min, const double *max,const QList& idx) + { + foreach(int index,idx) { + myMin[index] = min[index]; + myMax[index] = max[index]; + } + } + ~Plot2d_DeviationData(){} + + size_t size() const + { + return qwtMin(myMin.size(), myMax.size()); + } + bool values(size_t i, double &min, double &max) { + if(myMin.contains(i) && myMax.contains(i)) { + min = myMin[i]; + max = myMax[i]; + return true; + } + return false; + } +private: + QMap myMin; + QMap myMax; +}; + + +/*! + Constructor of Plot2d_QwtPlotCurve +*/ +Plot2d_QwtPlotCurve::Plot2d_QwtPlotCurve( const QString& title, + QwtPlot::Axis yAxis /*const int index*/ ) : + Plot2d_SelectableItem(), + QwtPlotCurve( title ), + myYAxis( yAxis ), + myYAxisIdentifierEnabled( false ), + myDeviationData(0) +{ +} + +/*! + Destructor of Plot2d_QwtPlotCurve +*/ +Plot2d_QwtPlotCurve::~Plot2d_QwtPlotCurve() +{ + clearDeviationData(); +} + +/*! + Enable / disable Y axis identifier +*/ +void Plot2d_QwtPlotCurve::setYAxisIdentifierEnabled( const bool on ) +{ + myYAxisIdentifierEnabled = on; +} + +/*! + Redefined method, which updates legend of the curve +*/ +void Plot2d_QwtPlotCurve::updateLegend( QwtLegend* legend ) const +{ + if ( !legend ) + return; + + QWidget* widget = legend->find( this ); + + if ( testItemAttribute(QwtPlotItem::Legend)) { + + if ( widget == NULL ) { + widget = legendItem(); + if ( widget ) { + if ( widget->inherits("QwtLegendItem") ) { + QwtLegendItem *label = (QwtLegendItem *)widget; + label->setItemMode(legend->itemMode()); + + if ( plot() ) { + QObject::connect(label, SIGNAL(clicked()), + plot(), SLOT(legendItemClicked())); + QObject::connect(label, SIGNAL(checked(bool)), + plot(), SLOT(legendItemChecked(bool))); + } + } + legend->contentsWidget()->layout()->addWidget(widget); + legend->insert(this, widget); + } + } + + QwtPlotCurve::updateLegend( legend ); + + + if( Plot2d_QwtLegendItem* anItem = dynamic_cast( widget ) ) { + int aMode = Plot2d_QwtLegendItem::IM_None; + if( myYAxisIdentifierEnabled ) + aMode = myYAxis == QwtPlot::yRight ? + Plot2d_QwtLegendItem::IM_Right : + Plot2d_QwtLegendItem::IM_Left; + anItem->setYAxisIdentifierMode( aMode ); + if(isSelected()) { + anItem->setCurvePen(legendPen()); + anItem->setSymbol(legendSymbol()); + } + anItem->setSelected(isSelected()); + anItem->updateHighlit(); + } + } +} + +/*! + Redefined method, which creates and returns legend item of the curve +*/ +QWidget* Plot2d_QwtPlotCurve::legendItem() const +{ + return new Plot2d_QwtLegendItem; +} + +/*! + Redefined method, which draw a set of points of a curve. +*/ +void Plot2d_QwtPlotCurve::draw(QPainter *painter, + const QwtScaleMap &xMap, const QwtScaleMap &yMap, + int from, int to) const +{ + if (to < 0) + to = dataSize() - 1; + QwtPlotCurve::draw(painter, xMap, yMap, from, to); + + //draw deviation data + if(hasDeviationData()) { + painter->save(); + int lineW = deviationMarkerLineWidth(); + int tickSz = deviationMarkerTickSize() + qRound(lineW/2); + double min, max, xi, yi; + int xp, ytop, ybtm, tickl, tickr; + QColor c = isSelected() ? Plot2d_Object::selectionColor() : deviationMarkerColor(); + QPen p = QPen(c, lineW, Qt::SolidLine); + painter->setPen(p); + for (int i = from; i <= to; i++) { + if(!myDeviationData->values(i,min,max)) continue; + xi = x(i); + yi = y(i); + xp = xMap.transform(xi); + ytop = yMap.transform(yi + max); + ybtm = yMap.transform(yi - min); + tickl = xp - tickSz; + tickr = xp + tickSz; + painter->drawLine(tickl,ytop,tickr,ytop); + painter->drawLine(xp,ytop,xp,ybtm); + painter->drawLine(tickl,ybtm,tickr,ybtm); + } + painter->restore(); + } +} + +/*! + * Return color of the deviation marker. + */ +QColor Plot2d_QwtPlotCurve::deviationMarkerColor() const { + QColor c(0, 0, 127); + if(plot()) { + QVariant var = plot()->property(PLOT2D_DEVIATION_COLOR); + if(var.isValid()) + c = var.value(); + } + return c; +} +/*! + * Return line width of the deviation marker. + */ +int Plot2d_QwtPlotCurve::deviationMarkerLineWidth() const { + int lw = 1; + if(plot()) { + QVariant var = plot()->property(PLOT2D_DEVIATION_LW); + if(var.isValid()) + lw = var.toInt(); + } + return lw; +} + +/*! + * Return tick size of the deviation marker. + */ +int Plot2d_QwtPlotCurve::deviationMarkerTickSize() const { + int ts = 2; + if(plot()) { + QVariant var = plot()->property(PLOT2D_DEVIATION_TS); + if(var.isValid()) + ts = var.toInt(); + } + return ts; +} + +/*! + * Sets deviation data for the plot item. + */ +void Plot2d_QwtPlotCurve::setDeviationData(const double* min, const double* max,const QList &idx) { + clearDeviationData(); + myDeviationData = new Plot2d_DeviationData(min,max,idx); +} + +/*! + * Return true if deviation is assigned to the plot item, + false otherwise. + */ +bool Plot2d_QwtPlotCurve::hasDeviationData() const { + return myDeviationData != 0; +} + +/*! + * Remove deviation data from the plot item. + */ +void Plot2d_QwtPlotCurve::clearDeviationData() +{ + if(myDeviationData) + delete myDeviationData; + myDeviationData = 0; +} + + + +/*! + Constructor. +*/ +Plot2d_SelectableItem::Plot2d_SelectableItem(): + myIsSelected(false) +{ +} + +/*! + Destructor. +*/ +Plot2d_SelectableItem::~Plot2d_SelectableItem() +{ +} + +/*! + Sets selected property. +*/ +void Plot2d_SelectableItem::setSelected( const bool on) { + myIsSelected = on; +} + +/*! + Return selected property. +*/ +bool Plot2d_SelectableItem::isSelected() const { + return myIsSelected; +} + +/*! + Sets legend pen property. +*/ +void Plot2d_SelectableItem::setLegendPen( const QPen & p) { + myLegendPen = p; +} + +/*! + Return legend pen property. +*/ +QPen Plot2d_SelectableItem::legendPen() const { + return myLegendPen; +} + +/*! + Sets legend symbol property. +*/ +void Plot2d_SelectableItem::setLegendSymbol(const QwtSymbol& s) { + myLegendSymbol = s; +} + +/*! + Sets legend symbol property. +*/ +QwtSymbol Plot2d_SelectableItem::legendSymbol() const { + return myLegendSymbol; +} + +/*! + Constructor +*/ +Plot2d_HistogramQwtItem::Plot2d_HistogramQwtItem( const QwtText& theTitle ) +: QwtPlotItem( theTitle ) +{ + init(); +} + +/*! + Constructor +*/ +Plot2d_HistogramQwtItem::Plot2d_HistogramQwtItem( const QString& theTitle ) +: QwtPlotItem( QwtText( theTitle ) ) +{ + init(); +} + +/*! + Destructor +*/ +Plot2d_HistogramQwtItem::~Plot2d_HistogramQwtItem() +{ +} + +/*! + Initialization of object +*/ +void Plot2d_HistogramQwtItem::init() +{ + myReference = 0.0; + myAttributes = Plot2d_HistogramQwtItem::Auto; + + setItemAttribute( QwtPlotItem::AutoScale, true ); + setItemAttribute( QwtPlotItem::Legend, true ); + + setZ( 20.0 ); +} + +/*! + Sets base line to object + @param theRef +*/ +void Plot2d_HistogramQwtItem::setBaseline( double theRef ) +{ + if ( myReference != theRef ) { + myReference = theRef; + itemChanged(); + } +} + +/*! + Returns base line of object +*/ +double Plot2d_HistogramQwtItem::baseline() const +{ + return myReference; +} + +/*! + Sets data to object +*/ +void Plot2d_HistogramQwtItem::setData( const QwtIntervalData& theData ) +{ + myData = theData; + itemChanged(); +} + +/*! + Returns data from object +*/ +const QwtIntervalData& Plot2d_HistogramQwtItem::data() const +{ + return myData; +} + +/*! + Sets color to object +*/ +void Plot2d_HistogramQwtItem::setColor( const QColor& theColor ) +{ + if ( myColor != theColor ) { + myColor = theColor; + itemChanged(); + } +} + +/*! + Returns color from object +*/ +QColor Plot2d_HistogramQwtItem::color() const +{ + return myColor; +} + +/*! + Returns bounding rect of object +*/ +QwtDoubleRect Plot2d_HistogramQwtItem::boundingRect() const +{ + QwtDoubleRect aRect = myData.boundingRect(); + if ( !aRect.isValid() ) + return aRect; + + if ( myAttributes & Xfy ) { + aRect = QwtDoubleRect( aRect.y(), aRect.x(), + aRect.height(), aRect.width() ); + if ( aRect.left() > myReference ) + aRect.setLeft( myReference ); + else if ( aRect.right() < myReference ) + aRect.setRight( myReference ); + } + else { + if ( aRect.bottom() < myReference ) + aRect.setBottom( myReference ); + else if ( aRect.top() > myReference ) + aRect.setTop( myReference ); + } + return aRect; +} + +/*! + Returns type of plot object +*/ +int Plot2d_HistogramQwtItem::rtti() const +{ + return QwtPlotItem::Rtti_PlotHistogram; +} + +/*! + Sets histogram attributes +*/ +void Plot2d_HistogramQwtItem::setHistogramAttribute( HistogramAttribute theAttr, + bool isOn ) +{ + if ( testHistogramAttribute( theAttr ) != isOn ) { + if ( isOn ) + myAttributes |= theAttr; + else + myAttributes &= ~theAttr; + + itemChanged(); + } +} + +/*! + Tests histogram attributes +*/ +bool Plot2d_HistogramQwtItem::testHistogramAttribute( HistogramAttribute theAttr ) const +{ + return myAttributes & theAttr; +} + +/*! + Draws histogram object +*/ +void Plot2d_HistogramQwtItem::draw( QPainter* thePainter, + const QwtScaleMap& theXMap, + const QwtScaleMap& theYMap, + const QRect& ) const +{ + thePainter->setPen( QPen( myColor ) ); + + const int x0 = theXMap.transform( baseline() ); + const int y0 = theYMap.transform( baseline() ); + + for ( int i = 0; i < (int)myData.size(); i++ ) { + if ( myAttributes & Plot2d_HistogramQwtItem::Xfy ) { + const int x2 = theXMap.transform( myData.value( i ) ); + if ( x2 == x0 ) + continue; + int y1 = theYMap.transform( myData.interval( i ).minValue() ); + int y2 = theYMap.transform( myData.interval( i ).maxValue() ); + if ( y1 > y2 ) + qSwap( y1, y2 ); + + if ( i < (int)myData.size() - 2 ) { + const int yy1 = theYMap.transform( myData.interval(i+1).minValue() ); + const int yy2 = theYMap.transform( myData.interval(i+1).maxValue() ); + if ( y2 == qwtMin( yy1, yy2 ) ) { + const int xx2 = theXMap.transform( myData.interval(i+1).minValue() ); + if ( xx2 != x0 && ( ( xx2 < x0 && x2 < x0 ) || + ( xx2 > x0 && x2 > x0 ) ) ) { + // One pixel distance between neighboured bars + y2++; + } + } + } + drawBar( thePainter, Qt::Horizontal, QRect( x0, y1, x2 - x0, y2 - y1 ) ); + } + else { + const int y2 = theYMap.transform( myData.value( i ) ); + if ( y2 == y0 ) + continue; + int x1 = theXMap.transform( myData.interval( i ).minValue() ); + int x2 = theXMap.transform( myData.interval( i ).maxValue() ); + if ( x1 > x2 ) + qSwap( x1, x2 ); + + if ( i < (int)myData.size() - 2 ) { + const int xx1 = theXMap.transform( myData.interval(i+1).minValue() ); + const int xx2 = theXMap.transform( myData.interval(i+1).maxValue() ); + if ( x2 == qwtMin( xx1, xx2 ) ) { + const int yy2 = theYMap.transform( myData.value(i+1) ); + if ( yy2 != y0 && ( ( yy2 < y0 && y2 < y0 ) || + ( yy2 > y0 && y2 > y0 ) ) ) { + // One pixel distance between neighboured bars + x2--; + } + } + } + drawBar( thePainter, Qt::Vertical, QRect( x1, y0, x2 - x1, y2 - y0 ) ); + } + } +} + +/*! + Draws single bar of histogram +*/ +void Plot2d_HistogramQwtItem::drawBar( QPainter* thePainter, + Qt::Orientation, + const QRect& theRect ) const +{ + thePainter->save(); + + const QColor color( thePainter->pen().color() ); + QRect r = theRect.normalized(); + + const int factor = 125; + const QColor light( color.light( factor ) ); + const QColor dark( color.dark( factor ) ); + + thePainter->setBrush( color ); + thePainter->setPen( Qt::NoPen ); + QwtPainter::drawRect( thePainter, r.x() + 1, r.y() + 1, + r.width() - 2, r.height() - 2 ); + thePainter->setBrush( Qt::NoBrush ); + + thePainter->setPen( QPen( light, 2 ) ); + QwtPainter::drawLine( thePainter, r.left() + 1, r.top() + 2, + r.right() + 1, r.top() + 2 ); + + thePainter->setPen( QPen( dark, 2 ) ); + QwtPainter::drawLine( thePainter, r.left() + 1, r.bottom(), + r.right() + 1, r.bottom() ); + thePainter->setPen( QPen( light, 1 ) ); + + QwtPainter::drawLine( thePainter, r.left(), r.top() + 1, + r.left(), r.bottom() ); + QwtPainter::drawLine( thePainter, r.left() + 1, r.top() + 2, + r.left() + 1, r.bottom() - 1 ); + thePainter->setPen( QPen( dark, 1 ) ); + + QwtPainter::drawLine( thePainter, r.right() + 1, r.top() + 1, + r.right() + 1, r.bottom() ); + QwtPainter::drawLine(thePainter, r.right(), r.top() + 2, + r.right(), r.bottom() - 1 ); + thePainter->restore(); +} + +/*! + Constructor +*/ +Plot2d_HistogramItem::Plot2d_HistogramItem( const QwtText& theTitle ) +: Plot2d_HistogramQwtItem( theTitle ), + Plot2d_SelectableItem(), + myCrossed( true ) +{ +} + +/*! + Constructor +*/ +Plot2d_HistogramItem::Plot2d_HistogramItem( const QString& theTitle ) +: Plot2d_HistogramQwtItem( theTitle ), + myCrossed( true ) +{ +} + +/*! + Destructor +*/ +Plot2d_HistogramItem::~Plot2d_HistogramItem() +{ +} + +/*! + Get histogram bar items +*/ +QList Plot2d_HistogramItem::getBars() const +{ + return myBarItems; +} + +/*! + Set to legend item symbol with color of item +*/ +void Plot2d_HistogramItem::updateLegend( QwtLegend* theLegend ) const +{ + if ( !theLegend ) + return; + + Plot2d_HistogramQwtItem::updateLegend( theLegend ); + + QWidget* theWidget = theLegend->find( this ); + if ( !theWidget || !theWidget->inherits( "QwtLegendItem" ) ) + return; + + Plot2d_QwtLegendItem* anItem = ( Plot2d_QwtLegendItem* )theWidget; + QFontMetrics aFMetrics( anItem->font() ); + int aSize = aFMetrics.height(); + QwtSymbol aSymbol( QwtSymbol::Rect, QBrush( legendPen().color() ), + QPen( legendPen().color() ), QSize( aSize, aSize ) ); + anItem->setSymbol( aSymbol ); + anItem->setIdentifierMode( theLegend->identifierMode() + | QwtLegendItem::ShowSymbol ); + anItem->setSelected(isSelected()); + anItem->updateHighlit(); + anItem->update(); +} + +/*! + Draws histogram object +*/ +void Plot2d_HistogramItem::draw( QPainter* thePainter, + const QwtScaleMap& theXMap, + const QwtScaleMap& theYMap, + const QRect& ) const +{ + // nds: clear list of bar items + Plot2d_HistogramItem* anItem = (Plot2d_HistogramItem*)this; + anItem->myBarItems.clear(); + + thePainter->setPen( QPen( color() ) ); + const int x0 = theXMap.transform( baseline() ); + const int y0 = theYMap.transform( baseline() ); + + const QwtIntervalData& iData = data(); + + for ( int i = 0; i < (int)iData.size(); i++ ) { + if ( testHistogramAttribute( Plot2d_HistogramItem::Xfy ) ) { + const int x2 = theXMap.transform( iData.value( i ) ); + if ( x2 == x0 ) + continue; + int y1 = theYMap.transform( iData.interval( i ).minValue() ); + int y2 = theYMap.transform( iData.interval( i ).maxValue() ); + if ( y1 > y2 ) + qSwap( y1, y2 ); + + if ( i < (int)iData.size() - 2 ) { + const int yy1 = theYMap.transform( iData.interval(i+1).minValue() ); + const int yy2 = theYMap.transform( iData.interval(i+1).maxValue() ); + if ( y2 == qwtMin( yy1, yy2 ) ) { + const int xx2 = theXMap.transform( iData.interval(i+1).minValue() ); + if ( xx2 != x0 && ( ( xx2 < x0 && x2 < x0 ) || + ( xx2 > x0 && x2 > x0 ) ) ) { + // One pixel distance between neighboured bars + y2++; + } + } + } + // nds: draw rect with the other lower rects + QRect aRect( x0, y1, x2 - x0, y2 - y1 ); + drawRectAndLowers( thePainter, Qt::Horizontal, aRect ); + anItem->myBarItems.append( aRect ); + } + else { + const int y2 = theYMap.transform( iData.value( i ) ); + if ( y2 == y0 ) + continue; + int x1 = theXMap.transform( iData.interval( i ).minValue() ); + int x2 = theXMap.transform( iData.interval( i ).maxValue() ); + if ( x1 > x2 ) + qSwap( x1, x2 ); + + if ( i < (int)iData.size() - 2 ) { + const int xx1 = theXMap.transform( iData.interval(i+1).minValue() ); + const int xx2 = theXMap.transform( iData.interval(i+1).maxValue() ); + if ( x2 == qwtMin( xx1, xx2 ) ) { + const int yy2 = theYMap.transform( iData.value(i+1) ); + if ( yy2 != y0 && ( ( yy2 < y0 && y2 < y0 ) || + ( yy2 > y0 && y2 > y0 ) ) ) { + // One pixel distance between neighboured bars + x2--; + } + } + } + // nds: draw rect with the other lower rects + QRect aRect(x1, y0, x2 - x1, y2 - y0 ); + drawRectAndLowers( thePainter, Qt::Vertical, aRect ); + anItem->myBarItems.append( aRect ); + } + } +} + +/*! + Set/clear "cross items" option +*/ +void Plot2d_HistogramItem::setCrossItems( bool theCross ) +{ + myCrossed = theCross; +} + +/*! + Get "cross items" option +*/ +bool Plot2d_HistogramItem::isCrossItems() const +{ + return myCrossed; +} + +/*! + Redefined method, which creates and returns legend item of the curve +*/ +QWidget* Plot2d_HistogramItem::legendItem() const +{ + return new Plot2d_QwtLegendItem; +} + + +/*! + Draws bar of histogram and on it bars of histograms with lower height. +*/ +void Plot2d_HistogramItem::drawRectAndLowers( QPainter* thePainter, + Qt::Orientation theOr, + const QRect& theRect ) const +{ + QRect aRect = theRect; + // theRect has inversed coordinates on Y axis. + // The top of the rect is bottom in standard QRect coordinates, + // and it bottom is the top. + if ( myCrossed )//&& theOr == Qt::Horizontal ) + aRect.setTop( getCrossedTop( theRect ) ); + + drawBar( thePainter, Qt::Horizontal, aRect ); +} + +/*! + Returns top value of the given rect in the context of other bars. + + It's necessary to remember, that \a theRect has inverted coordinate Y. +*/ +int Plot2d_HistogramItem::getCrossedTop( const QRect& theRect ) const +{ + int aRes = theRect.top(); + QwtPlot* aPlot = plot(); + // int aHeight = theRect.height(); + if ( aPlot ) { + QwtPlotItemList anItems = aPlot->itemList(); + QwtPlotItemIterator anIt = anItems.begin(), aLast = anItems.end(); + Plot2d_HistogramItem* anItem; + QList aRects; + for ( ; anIt != aLast; anIt++ ) { + if ( !(*anIt)->rtti() == QwtPlotItem::Rtti_PlotHistogram ) + continue; + anItem = dynamic_cast( *anIt ); + if( !anItem || anItem == this ) + continue; + aRects.clear(); + aRects = anItem->getBars(); + for ( int i = 0, aSize = aRects.size(); i < aSize; i++ ) { + if ( qMax( theRect.x(), aRects[i].x() ) <= + qMin( theRect.left(), aRects[i].left() ) ) { + if ( theRect.bottom() < aRects[i].bottom() ) + if ( aRects[i].bottom() < aRes ) + aRes = aRects[i].bottom(); + } + } + } + } + return aRes; +} diff --git a/src/Plot2d/Plot2d_PlotItems.h b/src/Plot2d/Plot2d_PlotItems.h new file mode 100644 index 000000000..e13de3c81 --- /dev/null +++ b/src/Plot2d/Plot2d_PlotItems.h @@ -0,0 +1,192 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : Plot2d_HistogramItem.h +// Author : Natalia ERMOLAEVA, Open CASCADE S.A.S. (natalia.donis@opencascade.com) + +#ifndef PLOT2D_PLOTITEMS_H +#define PLOT2D_PLOTITEMS_H + +#include "Plot2d.h" + +#include +#include +#include +#include +#include + +class PLOT2D_EXPORT Plot2d_QwtLegendItem : public QwtLegendItem +{ +public: + enum YAxisIdentifierMode { IM_None = 0, IM_Left, IM_Right }; + +public: + Plot2d_QwtLegendItem( QWidget* = 0 ); + virtual ~Plot2d_QwtLegendItem(); + +public: + void setYAxisIdentifierMode( const int ); + void updateHighlit(); + void setSelected(const bool on); + bool isSelected() const; + QColor getColorFromPalette(QPalette::ColorRole role); + +protected: + virtual void drawIdentifier( QPainter*, const QRect& ) const; + virtual void drawText(QPainter *, const QRect &); + +private: + +private: + int myYAxisIdentifierMode; + QPixmap myYAxisLeftIcon; + QPixmap myYAxisRightIcon; + int mySpacingCollapsed; + int mySpacingExpanded; + bool myIsSelected; +}; + +class PLOT2D_EXPORT Plot2d_SelectableItem { +public: + Plot2d_SelectableItem(); + ~Plot2d_SelectableItem(); + + void setSelected( const bool ); + bool isSelected() const; + + void setLegendPen( const QPen & ); + QPen legendPen() const; + + void setLegendSymbol( const QwtSymbol& ); + QwtSymbol legendSymbol() const; + +private: + bool myIsSelected; + QPen myLegendPen; + QwtSymbol myLegendSymbol; +}; + +class PLOT2D_EXPORT Plot2d_QwtPlotCurve : public QwtPlotCurve, public Plot2d_SelectableItem +{ +public: + Plot2d_QwtPlotCurve( const QString&, QwtPlot::Axis = QwtPlot::yLeft ); + virtual ~Plot2d_QwtPlotCurve(); + +public: + virtual void setYAxisIdentifierEnabled( const bool ); + virtual void draw(QPainter *p, + const QwtScaleMap &xMap, + const QwtScaleMap &yMap, + int from, int to) const; + + void setDeviationData(const double* min, const double* max, const QList &idx); + bool hasDeviationData() const; + void clearDeviationData(); + + +protected: + virtual void updateLegend( QwtLegend* ) const; + virtual QWidget* legendItem() const; + + QColor deviationMarkerColor() const; + int deviationMarkerLineWidth() const; + int deviationMarkerTickSize() const; + +private: + QwtPlot::Axis myYAxis; + bool myYAxisIdentifierEnabled; + + class Plot2d_DeviationData; + Plot2d_DeviationData* myDeviationData; +}; + +class PLOT2D_EXPORT Plot2d_HistogramQwtItem: public QwtPlotItem +{ +public: + enum HistogramAttribute + { + Auto = 0, + Xfy = 1 + }; + + explicit Plot2d_HistogramQwtItem( const QString& = QString() ); + explicit Plot2d_HistogramQwtItem( const QwtText& ); + virtual ~Plot2d_HistogramQwtItem(); + + void setData( const QwtIntervalData& ); + const QwtIntervalData& data() const; + + void setColor( const QColor& ); + QColor color() const; + + virtual QwtDoubleRect boundingRect() const; + virtual int rtti() const; + virtual void draw( QPainter*, const QwtScaleMap&, + const QwtScaleMap&, const QRect& ) const; + + void setBaseline( double ); + double baseline() const; + + void setHistogramAttribute( HistogramAttribute, bool = true ); + bool testHistogramAttribute( HistogramAttribute ) const; + +protected: + virtual void drawBar( QPainter*, Qt::Orientation, const QRect& ) const; + +private: + void init(); + +private: + int myAttributes; + QwtIntervalData myData; + QColor myColor; + double myReference; +}; + +class PLOT2D_EXPORT Plot2d_HistogramItem : public Plot2d_HistogramQwtItem, public Plot2d_SelectableItem +{ +public: + explicit Plot2d_HistogramItem( const QString& = QString() ); + explicit Plot2d_HistogramItem( const QwtText& ); + virtual ~Plot2d_HistogramItem(); + + QList getBars() const; + + virtual void updateLegend( QwtLegend* ) const; + virtual void draw( QPainter*, const QwtScaleMap&, + const QwtScaleMap&, const QRect& ) const; + + void setCrossItems( bool theCross ); + bool isCrossItems() const; + +protected: + void drawRectAndLowers( QPainter*, Qt::Orientation, + const QRect& ) const; + int getCrossedTop( const QRect& ) const; + + virtual QWidget* legendItem() const; + +protected: + QList myBarItems; + bool myCrossed; +}; + +#endif // PLOT2D_PLOTITEMS_H diff --git a/src/Plot2d/Plot2d_SetupCurveScaleDlg.cxx b/src/Plot2d/Plot2d_SetupCurveScaleDlg.cxx new file mode 100755 index 000000000..f9aacc93d --- /dev/null +++ b/src/Plot2d/Plot2d_SetupCurveScaleDlg.cxx @@ -0,0 +1,138 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : Plot2d_SetupCurveScaleDlg.cxx +// +#include "Plot2d_SetupCurveScaleDlg.h" + +#include + +#include +#include +#include +#include +#include + +#include + +const int MARGIN_SIZE = 11; +const int SPACING_SIZE = 6; +const int MIN_COMBO_WIDTH = 100; +const int MIN_SPIN_WIDTH = 50; + +/*! + \class Plot2d_SetupCurveScaleDlg + \brief Dialog box for modifying 2d curve scale factor. +*/ + +/*! + \brief Constructor. + \param parent parent widget +*/ +Plot2d_SetupCurveScaleDlg::Plot2d_SetupCurveScaleDlg( /*curveList lst, */QWidget* parent ) +: QDialog( parent ) +{ + setModal( true ); + setWindowTitle( tr("TLT_SETUP_CURVE_SCALE") ); + setSizeGripEnabled( true ); + + /************************************************************************/ + QGroupBox* GroupC1 = new QGroupBox( this ); + QHBoxLayout* GroupC1Layout = new QHBoxLayout( GroupC1 ); + GroupC1Layout->setSpacing( SPACING_SIZE ); + GroupC1Layout->setMargin( MARGIN_SIZE ); + + QLabel* aScaleLab = new QLabel( tr( "CURVE_SCALE_FACTOR" ), GroupC1 ); + myValueSpin = new QtxDoubleSpinBox( GroupC1 ); + myValueSpin->setMinimum( 0.01 ); + myValueSpin->setSingleStep( 0.1 ); + myValueSpin->setMinimumWidth( MIN_SPIN_WIDTH ); + + GroupC1Layout->addWidget( aScaleLab ); + GroupC1Layout->addWidget( myValueSpin ); + + /************************************************************************/ + QGroupBox* GroupButtons = new QGroupBox( this ); + QHBoxLayout* GroupButtonsLayout = new QHBoxLayout( GroupButtons ); + GroupButtonsLayout->setSpacing( SPACING_SIZE ); + GroupButtonsLayout->setMargin( MARGIN_SIZE ); + + myOkBtn = new QPushButton( tr( "BUT_OK" ), this ); + myCancelBtn = new QPushButton( tr( "BUT_CANCEL" ), this ); + + GroupButtonsLayout->addWidget( myOkBtn ); + GroupButtonsLayout->addSpacing( 10 ); + GroupButtonsLayout->addWidget( myCancelBtn ); + + /************************************************************************/ + QVBoxLayout* topLayout = new QVBoxLayout( this ); + topLayout->setSpacing( SPACING_SIZE ); + topLayout->setMargin( MARGIN_SIZE ); + topLayout->addWidget( GroupC1 ); + topLayout->addWidget( GroupButtons ); + + // default settings + setScale( 1.0 ); // no scale + + // connections + connect( myOkBtn, SIGNAL( clicked() ), this, SLOT( accept() ) ); + connect( myCancelBtn, SIGNAL( clicked() ), this, SLOT( reject() ) ); + + SUIT_Tools::centerWidget( this, parent ); +} + +/*! + \brief Destructor. +*/ +Plot2d_SetupCurveScaleDlg::~Plot2d_SetupCurveScaleDlg() +{ +} + +/*! + \brief Set scale factor. + \param coef scale factor + \sa getScale() +*/ +void Plot2d_SetupCurveScaleDlg::setScale( const double coef ) +{ + if ( coef > myValueSpin->maximum() ){ + myValueSpin->setMaximum( coef ); + } + myValueSpin->setValue( coef ); +} + +/*! + \brief Get scale factor. + \return chosen scale factor + \sa setScale() +*/ +double Plot2d_SetupCurveScaleDlg::getScale() const +{ + return myValueSpin->value(); +} +/*! + \brief Clear value in the "Scale factor" spinbox. +*/ +void Plot2d_SetupCurveScaleDlg::setUndefinedValue() { + myValueSpin->setCleared(true); + myValueSpin->setSpecialValueText(""); +} diff --git a/src/Plot2d/Plot2d_SetupCurveScaleDlg.h b/src/Plot2d/Plot2d_SetupCurveScaleDlg.h new file mode 100755 index 000000000..605f2b11e --- /dev/null +++ b/src/Plot2d/Plot2d_SetupCurveScaleDlg.h @@ -0,0 +1,58 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : Plot2d_SetupCurveScaleDlg.h +// +#ifndef PLOT2D_SETUPCURVESCALEDLG_H +#define PLOT2D_SETUPCURVESCALEDLG_H + +#include "Plot2d.h" + +#include + +class QPushButton; +class QLabel; + +class QtxDoubleSpinBox; + +class PLOT2D_EXPORT Plot2d_SetupCurveScaleDlg : public QDialog +{ + Q_OBJECT + +public: + Plot2d_SetupCurveScaleDlg( /*curveList,*/ QWidget* = 0 ); + ~Plot2d_SetupCurveScaleDlg(); + +public: + void setScale( const double ); + double getScale() const; + + void setUndefinedValue(); + +private: + QPushButton* myOkBtn; + QPushButton* myCancelBtn; + QtxDoubleSpinBox* myValueSpin; +}; + +#endif // PLOT2D_SETUPCURVESCALEDLG_H + diff --git a/src/Plot2d/resources/Plot2d_msg_fr.ts b/src/Plot2d/resources/Plot2d_msg_fr.ts new file mode 100755 index 000000000..cc78b0374 --- /dev/null +++ b/src/Plot2d/resources/Plot2d_msg_fr.ts @@ -0,0 +1,774 @@ + + + + + @default + + PLOT2D_CURVE_TYPE_LBL + Type de courbe: + + + ERROR + Erreur + + + PLOT2D_SET_AS_DEFAULT_CHECK + Enregistrer comme paramètres par défaut + + + TLT_SETUP_CURVE + Initialiser une courbe + + + MNU_DUMP_VIEW + Enregistrer la vue... + + + PLOT2D_SCALE_MODE_HOR + Axe horizontal: + + + PLOT2D_NORMALIZE_TLT + Normalisation + + + PLOT2D_NORMALIZE_MODE_MIN + Normaliser sur le minimum + + + PLOT2D_NORMALIZE_MODE_MAX + Normaliser sur le maximum + + + PLOT2D_NORMALIZE_LEFT_AXIS + Axe Y gauche: + + + PLOT2D_NORMALIZE_RIGHT_AXIS + Axe Y droite: + + + PLOT2D_SCALE_MODE_VER + Axe vertical: + + + MNU_PAN_VIEW + Déplacement + + + MNU_CLONE_VIEW + Dupliquer la vue + + + MNU_PRINT_VIEW + Imprimer la vue + + + POSTSCRIPT_FILES + Fichiers PostScript (*.ps) + + + ENCAPSULATED_POSTSCRIPT_FILES + Fichiers PostScript encapsulés (*.eps) + + + DSC_GLOBALPAN_VIEW + Sélection d'un nouveau centre de vue + + + PRP_PLOT2D_MODE_LINEAR_VER + Changer la vue de l'axe vertical au mode d'échelle linéaire + + + PRP_PLOT2D_MODE_LINEAR_HOR + Changer la vue de l'axe horizontal au mode d'échelle linéaire + + + CURVE_LINE_WIDTH_LAB + Epaisseur du trait: + + + CURVE_TYPE_POPUP + Type de courbe + + + NORMALIZATION_TYPE_POPUP + Normalisation + + + TOT_PLOT2D_MODE_LINEAR_VER + Axe vertical: linéaire + + + TOT_PLOT2D_MODE_LINEAR_HOR + Axe horizontal: linéaire + + + FIT_DATA_TLT + Ajuster à la plage de données + + + MNU_ZOOM_VIEW + Zoom + + + PLOT2D_GRID_TLT + Marques de la grille et des axes + + + DSC_PAN_VIEW + Déplacer la vue + + + DASHDOT_LINE_LBL + TiretPoint + + + PRP_PLOT2D_CURVES_SPLINES + Changer la vue en mode splines + + + INF_AXES_X + Axe X + + + PLOT2D_SCALE_TLT + Mode d'échelle + + + DSC_FITALL + Ajuster la scène pour afficher tous les objets + + + MNU_FITALL + Tout afficher + + + TOT_PLOT2D_MODE_LOGARITHMIC_HOR + Axe horizontal: logarithmique + + + TOT_PLOT2D_MODE_LOGARITHMIC_VER + Axe vertical: logarithmique + + + MNU_GLOBALPAN_VIEW + Déplacement global + + + INF_APP_DUMP_VIEW + Enregistrer la vue + + + PLOT2D_LEGEND_POSITION_BOTTOM + Dessous + + + INF_COORDINATES + Coordonnées: X : %1, Y : %2 + + + DSC_CLONE_VIEW + Ouvrir un nouveau visualiseur OCC pour la scène actuelle + + + DSC_PRINT_VIEW + Imprimer la vue actuelle + + + DASH_LINE_LBL + Tiret + + + DTRIANGLE_MARKER_LBL + Triangle orienté vers le bas + + + UTRIANGLE_MARKER_LBL + Triangle orienté en haut + + + LTRIANGLE_MARKER_LBL + Triangle orienté à gauche + + + RTRIANGLE_MARKER_LBL + Triangle orienté à droite + + + RECTANGLE_MARKER_LBL + Rectangle + + + TLT_SETUP_PLOT2D_VIEW + Paramètres de visualisation Plot 2d + + + CURVE_LINE_TYPE_LAB + Type de trait: + + + CROSS_MARKER_LBL + Croix + + + XCROSS_MARKER_LBL + Croix diagonale + + + PLOT2D_ENABLE_VER_TITLE + Titre de l'axe vertical + + + PLOT2D_ENABLE_HOR_TITLE + Titre de l'axe horizontal + + + TOT_PLOT2D_SETTINGS + Paramètres + + + TOT_PLOT2D_ANALYTICAL_CURVES + Courbes analytiques + + + TOT_PLOT2D_NORMALIZE_MODE_LMAX + Axe Y gauche: Normaliser sur le maximum global + + + TOT_PLOT2D_NORMALIZE_MODE_LMIN + Axe Y gauche: Normaliser sur le minimum global + + + TOT_PLOT2D_NORMALIZE_MODE_RMAX + Axe Y droite: Normaliser sur le maximum global + + + TOT_PLOT2D_NORMALIZE_MODE_RMIN + Axe Y droite: Normaliser sur le minimum global + + + PLOT2D_CURVE_TYPE_LINES + Lignes + + + MEN_PLOT2D_CURVES_SPLINES + Dessiner les splines + + + PRP_PLOT2D_MODE_LOGARITHMIC_HOR + Changer la vue de l'axe horizontal au mode d'échelle logarithmique + + + PRP_PLOT2D_MODE_LOGARITHMIC_VER + Changer la vue de l'axe vertical au mode d'échelle logarithmique + + + PLOT2D_IMAGE_FILES + Fichiers images (*.bmp *.png *.jpg *.jpeg) + + + PLOT2D_MAX_INTERVALS + Intervalles max + + + INF_AXES_Y_LEFT + Axe Y gauche + + + CURVE_COLOR_LAB + Couleur: + + + CURVE_PREVIEW_LAB + Prévisualiser + + + DIAMOND_MARKER_LBL + Diamant + + + PLOT2D_LEGEND_POSITION_TOP + Dessus + + + TOT_PLOT2D_CHANGE_BACKGROUND + Changer l'arrière-plan + + + MEN_PLOT2D_CHANGE_BACKGROUND + Changer l'arrière-plan... + + + PRP_PLOT2D_CHANGE_BACKGROUND + Changer la couleur d'arrière plan + + + SOLID_LINE_LBL + Solide + + + PLOT2D_GRID_ENABLE_VER_MAJOR + Verticale principale + + + PLOT2D_GRID_ENABLE_HOR_MAJOR + Horizontale principale + + + PLOT2D_GRID_ENABLE_VER_MINOR + Verticale secondaire + + + TOT_PLOT2D_CURVES_POINTS + Dessiner des points + + + PLOT2D_GRID_ENABLE_HOR_MINOR + Horizontale secondaire + + + PLOT2D_BACKGROUND_COLOR_LBL + Couleur d'arrière-plan: + + + PLOT2D_DEVIATION_MARKER_TLT + Marqueur de déviation + + + PLOT2D_DEVIATION_LW_LBL + Epaisseur de ligne + + + PLOT2D_DEVIATION_TS_LBL + Taille des coches + + + PLOT2D_DEVIATION_CL_LBL + Couleur + + + WRN_XLOG_NOT_ALLOWED + On a détecté des points avec les valeurs non-positives sur l'abscisse. +L'échelle logarithmique de l'abscisse n'est pas permise. + + + WRN_YLOG_NOT_ALLOWED + On a détecté des points avec les valeurs non-positives sur l'ordonnée. +L'échelle logarithmique de l'ordonnée n'est pas permise. + + + DSC_FITRECT + Ajuster la scène à la zone choisie par l'encadré + + + PLOT2D_LEGEND_POSITION_LEFT + Gauche + + + MNU_FITRECT + Afficher la zone + + + DOT_LINE_LBL + Point + + + MEN_PLOT2D_CURVES_POINTS + Dessiner les points + + + PRP_PLOT2D_CURVES_POINTS + Changer la vue en mode points + + + PLOT2D_SCALE_MODE_LOGARITHMIC + Logarithmique + + + PLOT2D_LEGEND_POSITION_RIGHT + Droite + + + DSC_DUMP_VIEW + Sauvegarder la vue actuelle dans un fichier image + + + WARNING + Avertissement + + + PLOT2D_ENABLE_LEGEND + Afficher la légende + + + PLOT2D_LEGEND_FONT + Police de la légende + + + DSC_ZOOM_VIEW + Zoomer la vue + + + PRP_PLOT2D_ANALYTICAL_CURVES + Réglage des propriétés des courbes analytiques + + + PRP_PLOT2D_NORMALIZE_MODE_LMAX + Bascule la vue vers le mode de normalisation sur le maximum pour l'axe Y gauche + + + PRP_PLOT2D_NORMALIZE_MODE_LMIN + Bascule la vue vers le mode de normalisation sur le minimum pour l'axe Y gauche + + + PRP_PLOT2D_NORMALIZE_MODE_RMAX + Bascule la vue vers le mode de normalisation sur le maximum pour l'axe Y droite + + + PRP_PLOT2D_NORMALIZE_MODE_RMIN + Bascule la vue vers le mode de normalisation sur le minimum pour l'axe Y droite + + + PRP_PLOT2D_SETTINGS + Définit les paramètres de visualisation + + + INF_COORDINATES_SOME_Y + Coordonnées: X : %1, Y : %2 ( %3 ) + + + SCALING_POPUP + Echelle + + + PLOT2D_SCALE_MODE_LINEAR + Linéaire + + + TOT_PLOT2D_FITDATA + Ajuster à l'intervalle + + + PLOT2D_CURVE_TYPE_POINTS + Points + + + PLOT2D_CURVE_TYPE_SPLINE + Spline + + + MEN_PLOT2D_FITDATA + &Ajuster à l'intervalle + + + MEN_PLOT2D_MODE_LOGARITHMIC_HOR + Axe horizontal: logarithmique + + + MEN_PLOT2D_MODE_LOGARITHMIC_VER + Axe vertical: logarithmique + + + MEN_PLOT2D_NORMALIZE_MODE_LMIN + Axe Y gauche: Minimum + + + MEN_PLOT2D_NORMALIZE_MODE_LMAX + Axe Y gauche: Maximum + + + MEN_PLOT2D_NORMALIZE_MODE_RMIN + Axe Y droite: Minimum + + + MEN_PLOT2D_NORMALIZE_MODE_RMAX + Axe Y droite: Maximum + + + PRP_PLOT2D_FITDATA + Ajuster la vue à la plage de données indiquée + + + MEN_PLOT2D_MODE_LINEAR_VER + Axe vertical: linéaire + + + MEN_PLOT2D_MODE_LINEAR_HOR + Axe horizontal: linéaire + + + NONE_MARKER_LBL + Aucun + + + ERR_DOC_CANT_SAVE_FILE + Impossible de sauvegarder le fichier + + + MEN_PLOT2D_SHOW_LEGEND + Afficher la &légende + + + PRP_PLOT2D_SHOW_LEGEND + Activer/désactiver la légende + + + TOT_PLOT2D_SHOW_LEGEND + Afficher la légende + + + INF_AXES_Y_RIGHT + Axe Y droite + + + DAHSDOTDOT_LINE_LBL + TiretPointPoint + + + TOT_PLOT2D_CURVES_SPLINES + Dessiner des splines + + + CURVE_MARKER_TYPE_LAB + Type de marqueur: + + + MEN_PLOT2D_SETTINGS + &Paramètres + + + MEN_PLOT2D_ANALYTICAL_CURVES + Courbes analytiques + + + CIRCLE_MARKER_LBL + Cercle + + + LBL_TOOLBAR_LABEL + Opérations de visualisation + + + NONE_LINE_LBL + Aucun + + + PLOT2D_MARKER_SIZE_LBL + Taille du marqueur: + + + PLOT2D_ENABLE_MAIN_TITLE + Titre principal + + + TOT_PLOT2D_CURVES_LINES + Dessiner des lignes + + + PRP_PLOT2D_CURVES_LINES + Changer la vue en mode lignes + + + MEN_PLOT2D_CURVES_LINES + Dessiner les lignes + + + + Plot2d_FitDataDlg + + FIT_HORIZONTAL + Ajuster horizontalement + + + MIN_VALUE_LAB + Min: + + + VERTICAL_AXIS + Axe vertical + + + MAX_VALUE_LAB + Max: + + + HORIZONTAL_AXIS + Axe horizontal + + + VERTICAL_LEFT_AXIS + Axe vertical gauche + + + FIT_ALL + Tout ajuster + + + VERTICAL_RIGHT_AXIS + Axe vertical droite + + + FIT_VERTICAL + Ajuster verticalement + + + + Plot2d_ViewManager + + PLOT2D_VIEW_TITLE + Scène Plot2d:%M - visualiseur:%V + + + PREF_GROUP_PLOT2DVIEWER + Visualiseur Plot2d + + + PREF_SHOW_LEGEND + Afficher la légende + + + PREF_LEGEND_POSITION + Position de la légende: + + + PREF_LEFT + Gauche + + + PREF_RIGHT + Droite + + + PREF_TOP + Haut + + + PREF_BOTTOM + Bas + + + PREF_CURVE_TYPE + Type de courbe: + + + PREF_POINTS + Points + + + PREF_LINES + Lignes + + + PREF_SPLINE + Spline + + + PREF_MARKER_SIZE + Taille du repère: + + + PREF_LINEAR + Linéaire + + + PREF_LOGARITHMIC + Logarithmique + + + PREF_HOR_AXIS_SCALE + Echelle de l'axe horizontal: + + + PREF_VERT_AXIS_SCALE + Echelle de l'axe vertical: + + + PREF_VIEWER_BACKGROUND + Couleur du fond + + + + Plot2d_AnalyticalCurveDlg + + ANALYTICAL_CURVE_TLT + Propriétés des courbes analytiques + + + AC_CURVE_PARAMS + Paramètres de la courbe + + + AC_CURVE_PROPS + Propriétés de la courbe + + + AC_FORMULA + y(x) = + + + AC_NB_INTERVALS + Nb. intervalles + + + AC_AUTO_ASSIGN + Affectation auto. + + + AC_MARKER_TYPE + Type de marqueur + + + AC_LINE_TYPE + Type de ligne + + + AC_LINE_WIDTH + Epaisseur de ligne + + + AC_CURVE_COLOR + Couleur de la courbe + + + AC_ADD_BTN + Ajouter une courbe + + + AC_REM_BTN + Supprimer une courbe + + + AC_UPD_BTN + Mettre à jour la courbe + + + AC_APPLY_BTN + Appliquer + + + AC_CANT_CALCULATE + La courbe ne peut pas être calculée. +Merci de vérifier les paramètres d'entrée + + + AC_CLOSE_BTN + &Fermer + + + AC_HELP_BTN + Aide + + + + Plot2d_SetupCurveScaleDlg + + TLT_SETUP_CURVE_SCALE + Mise à l'échelle de courbe(s) + + + CURVE_SCALE_FACTOR + Facteur d'échelle + + + \ No newline at end of file diff --git a/src/Plot2d/resources/plot2d_analytical_curve.png b/src/Plot2d/resources/plot2d_analytical_curve.png new file mode 100755 index 000000000..7ceb5f220 Binary files /dev/null and b/src/Plot2d/resources/plot2d_analytical_curve.png differ diff --git a/src/Plot2d/resources/plot2d_lmax_normalization.png b/src/Plot2d/resources/plot2d_lmax_normalization.png new file mode 100755 index 000000000..0dfe5ee13 Binary files /dev/null and b/src/Plot2d/resources/plot2d_lmax_normalization.png differ diff --git a/src/Plot2d/resources/plot2d_lmin_normalization.png b/src/Plot2d/resources/plot2d_lmin_normalization.png new file mode 100755 index 000000000..939fbd743 Binary files /dev/null and b/src/Plot2d/resources/plot2d_lmin_normalization.png differ diff --git a/src/Plot2d/resources/plot2d_print.png b/src/Plot2d/resources/plot2d_print.png new file mode 100755 index 000000000..69bae957d Binary files /dev/null and b/src/Plot2d/resources/plot2d_print.png differ diff --git a/src/Plot2d/resources/plot2d_rmax_normalization.png b/src/Plot2d/resources/plot2d_rmax_normalization.png new file mode 100755 index 000000000..7cdbdcc7b Binary files /dev/null and b/src/Plot2d/resources/plot2d_rmax_normalization.png differ diff --git a/src/Plot2d/resources/plot2d_rmin_normalization.png b/src/Plot2d/resources/plot2d_rmin_normalization.png new file mode 100755 index 000000000..2d7d174ce Binary files /dev/null and b/src/Plot2d/resources/plot2d_rmin_normalization.png differ diff --git a/src/PyConsole/resources/PyConsole_msg_fr.ts b/src/PyConsole/resources/PyConsole_msg_fr.ts new file mode 100755 index 000000000..910911562 --- /dev/null +++ b/src/PyConsole/resources/PyConsole_msg_fr.ts @@ -0,0 +1,42 @@ + + + + + PyConsole_Console + + + EDIT_COPY_CMD + &Copier + + + + EDIT_PASTE_CMD + C&oller + + + + EDIT_CLEAR_CMD + &Effacer + + + + EDIT_SELECTALL_CMD + &Tout sélectionner + + + EDIT_DUMPCOMMANDS_CMD + &Générer le script des commandes + + + + PyConsole_Editor + + TOT_DUMP_PYCOMMANDS + &Générer le script des commandes + + + PYTHON_FILES_FILTER + Fichiers PYTHON (*.py) + + + diff --git a/src/QDS/resources/QDS_msg_fr.ts b/src/QDS/resources/QDS_msg_fr.ts new file mode 100755 index 000000000..d57669bec --- /dev/null +++ b/src/QDS/resources/QDS_msg_fr.ts @@ -0,0 +1,51 @@ + + + + + QDS_Datum + + DATA_ERR_TITLE + Valeur du paramètre incorrecte + + + DATA_STRING + chaîne de caractères non-vide + + + DATA_NON_EMPTY + non-vide + + + DATA_MIN_LIMIT + est supérieur à %1 + + + DATA_FLOAT + réel + + + DATA_RANGE + dans l'intervalle [%1, %2] + + + DATA_SHOULD_BE_VALUE + Devrait avoir la valeur %1 + + + DATA_INTEGER + entier + + + DATA_INCORRECT_VALUE + La valeur du paramètre "%1" n'est pas correcte. + + + DATA_MAX_LIMIT + est inférieur à %1 + + + DATA_INPUT_VALUE + Indiquez une valeur correcte. + + + diff --git a/src/Qtx/QtxBackgroundTool.cxx b/src/Qtx/QtxBackgroundTool.cxx new file mode 100644 index 000000000..4feebef08 --- /dev/null +++ b/src/Qtx/QtxBackgroundTool.cxx @@ -0,0 +1,753 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +// File: QtxBackgroundTool.cxx +// Author: Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com) + +#include "QtxBackgroundTool.h" +#include "QtxColorButton.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +/*! + \class QtxBackgroundTool + \brief Implementation of the widget managing background data + + The background data can be specified as: + - image (by assigning the file name to be used as background texture) + - single color (by assigning any color) + - simple two-color gradient (with the gradient type id and two colors) + - complex gradient (by assigning arbitrary gradient data) (NOT IMPLEMENTED YET) + + To enable / disable any background type, setModeAllowed() function can be used. + Widget's orientation can be specified via the constructor parameter of changed with + setOrientation() function. + + To specify two-color gradient modes, use setGradient() function. By default, no gradient modes + are provided by the widget. + + Arbitrary gradient mode is not implemented yet, it is remaining for future improvement. + + Typical usage can be as follows: + \code + // create tool widget + QtxBackgroundTool* tool = new QtxBackgroundTool( Qt::Vertical, this ); + // assign gradients types + QStringList sl; + sl << "Horizontal" << "Vertical" << "First diagonal" << "Second diagonal"; + tool->setGradients(sl); + // disable image texture and custom gradient modes + tool->setModeAllowed(Qtx::ImageBackground, false); + tool->setModeAllowed(Qtx::CustomGradientBackground, false); + // initialize widget with the some background data + tool->setData( bgData ); + \endcode + + \todo Complete support of custom gradient (QLinearGradient, QRadialGradient, QConicalGradient). + \sa Qtx::BackgroundData, QtxBackgroundDialog, Qtx::stringToBackground(), Qtx::backgroundToString() +*/ + +/*! + \brief Constructor. + + Creates a background data widget with horizontal orientation. + + \param parent parent widget +*/ +QtxBackgroundTool::QtxBackgroundTool( QWidget* parent ) + : QWidget( parent ), myTextureAllowed( true ), myLastGradient( -1 ) +{ + init( Qt::Horizontal ); +} + +/*! + \brief Constructor. + + Creates a background data widget with specified orientation. + + \param o widget orientation + \param parent parent widget +*/ +QtxBackgroundTool::QtxBackgroundTool( Qt::Orientation o, QWidget* parent ) + : QWidget( parent ), myTextureAllowed( true ), myLastGradient( -1 ) +{ + init( o ); +} + +/*! + \brief Perform internal initialization +*/ +void QtxBackgroundTool::init( Qt::Orientation o ) +{ + // mode combo box + myModeCombo = new QComboBox( this ); + // color / gradient sub-widgets container + myCContainer = new QStackedWidget( this ); + // texture sub-widgets container + myTContainer = new QWidget( this ); + + QWidget* wrap; + QHBoxLayout* wrapLayout; + + // add image controls + wrapLayout = new QHBoxLayout( myTContainer ); + wrapLayout->setMargin( 0 ); + wrapLayout->setSpacing( 5 ); + myTextureCheck = new QCheckBox( tr( "Image" ), myTContainer ); + myFileName = new QLineEdit( myTContainer ); + myFileName->setMinimumWidth(100); + myBrowseBtn = new QPushButton( tr( "Browse..." ), myTContainer ); + myTextureMode = new QComboBox( myTContainer ); + wrapLayout->addWidget( myTextureCheck ); + wrapLayout->addWidget( myFileName ); + wrapLayout->addWidget( myBrowseBtn ); + wrapLayout->addWidget( myTextureMode ); + wrapLayout->setStretchFactor(myFileName, 10); + // add color controls + wrap = new QWidget( this ); + wrapLayout = new QHBoxLayout( wrap ); + wrapLayout->setMargin( 0 ); + wrapLayout->setSpacing( 5 ); + myFirstColor = new QtxColorButton( wrap ); + mySecondColor = new QtxColorButton( wrap ); + wrapLayout->addWidget( myFirstColor ); + wrapLayout->addWidget( mySecondColor ); + wrapLayout->setStretchFactor(myFirstColor, 5); + wrapLayout->setStretchFactor(mySecondColor, 5); + myCContainer->addWidget( wrap ); // Color + // add gradient controls ... NOT IMPLEMENTED YET + wrap = new QWidget( this ); + wrapLayout = new QHBoxLayout( wrap ); + wrapLayout->setMargin( 0 ); + wrapLayout->setSpacing( 5 ); + QLabel* foo = new QLabel( tr( "Not implemented yet" ), wrap ); + foo->setAlignment( Qt::AlignCenter ); + wrapLayout->addWidget( foo ); + myCContainer->addWidget( wrap ); // Gradient + + // initialize widget + myFirstColor->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ); + mySecondColor->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ); + + connect( myModeCombo, SIGNAL( currentIndexChanged( int ) ), this, SLOT( updateState() ) ); + connect( myTextureCheck, SIGNAL( toggled( bool ) ), this, SLOT( updateState() ) ); + connect( myBrowseBtn, SIGNAL( clicked() ), this, SLOT( browse() ) ); + + setModeAllowed( Qtx::ColorBackground ); + setModeAllowed( Qtx::SimpleGradientBackground ); + setModeAllowed( Qtx::CustomGradientBackground ); + setTextureModeAllowed( Qtx::CenterTexture ); + setTextureModeAllowed( Qtx::TileTexture ); + setTextureModeAllowed( Qtx::StretchTexture ); + setTextureAllowed(); + setImageFormats( QString() ); + setOrientation( o ); +} + +/*! + \brief Destructor. +*/ +QtxBackgroundTool::~QtxBackgroundTool() +{ +} + +/*! + \brief Get background data from the widget + \return background data + \sa setData() +*/ +Qtx::BackgroundData QtxBackgroundTool::data() const +{ + Qtx::BackgroundData bgData; + int idx = myModeCombo->currentIndex(); + if ( idx != -1 ) { + // get currently selected mode + int id = myModeCombo->itemData( idx, TypeRole ).toInt(); + // texture data + if ( isTextureAllowed() && myTextureMode->currentIndex() != -1 ) { + bgData.setTexture( myFileName->text().trimmed(), + Qtx::TextureMode( myTextureMode->itemData( myTextureMode->currentIndex() ).toInt() ) ); + bgData.setTextureShown( myTextureCheck->isChecked() ); + } + // single-color data + if ( isModeAllowed( Qtx::ColorBackground ) ) { + bgData.setColor( myFirstColor->color() ); + } + // simple two-color gradient data + if ( isModeAllowed( Qtx::SimpleGradientBackground ) ) { + bgData.setGradient( myLastGradient, myFirstColor->color(), mySecondColor->color() ); + } + // custom gradient data + if ( isModeAllowed( Qtx::CustomGradientBackground ) ) { + // bgData.setGradient( ... ); + // NOT IMPLEMENTED YET + } + + // set current mode + bgData.setMode( Qtx::BackgroundMode( id ) ); + } + return bgData; +} + +/*! + \brief Set background data from the widget + \param bgData background data being set to the widget + \sa data() +*/ +void QtxBackgroundTool::setData( const Qtx::BackgroundData& bgData ) +{ + Qtx::BackgroundMode m = bgData.mode(); + QColor c1, c2; + int gtype = bgData.gradient( c1, c2 ); + QString fileName; + int tmode = bgData.texture( fileName ); + bool tshown = bgData.isTextureShown(); + + // texture data + myFileName->setText( fileName ); + for ( int i = 0; i < myTextureMode->count(); i++ ) { + if ( myTextureMode->itemData( i ).toInt() == tmode ) { + myTextureMode->setCurrentIndex( i ); + break; + } + } + myTextureCheck->setChecked( tshown ); + + // color / simple gradient data + myFirstColor->setColor( c1 ); + mySecondColor->setColor( c2 ); + + // gradient data + // ... NOT IMPLEMENTED YET + + // set current mode index + int idx = -1; + for ( int i = 0; i < myModeCombo->count() && idx == -1; i++ ) { + int im = myModeCombo->itemData( i, TypeRole ).toInt(); + // for simple gradient mode we also check gradient type + if ( m == Qtx::SimpleGradientBackground && im == Qtx::SimpleGradientBackground ) { + int it = myModeCombo->itemData( i, IdRole ).toInt(); + if ( it == gtype ) idx = i; + } + // for other modes we just check mode itself + else if ( im == m ) { + idx = i; + } + } + // if background data is invalid, we set-up widget to the first available type + if ( idx == -1 && myModeCombo->count() > 0 ) idx = 0; + myModeCombo->setCurrentIndex( idx ); +} + +/*! + \brief Get allowed two-color gradients to the widget + \param gradients gradients names are returned via this parameter + \param ids gradients identifiers are returned via this parameter (empty list can be returned) +*/ +void QtxBackgroundTool::gradients( QStringList& gradList, QIntList& idList ) const +{ + gradList = myGradients; + idList = myGradientsIds; +} + +/*! + \brief Set allowed two-color gradients to the widget + \param gradients gradients names + \param ids optional gradients identifiers; if not specified, gradients are automatically numbered starting from 0 +*/ +void QtxBackgroundTool::setGradients( const QStringList& gradList, const QIntList& idList ) +{ + Qtx::BackgroundData d = data(); // get current state + myGradients = gradList; // store new gradient data + myGradientsIds = idList; // ... + myLastGradient = -1; // ... + internalUpdate(); // re-initialize + setData( d ); // restore current state (if possible) +} + +/*! + \brief Check if specific background mode is allowed + \param mode background mode + \return \c true if specified background mode is enabled or \c false otherwise + \sa setModeAllowed() +*/ +bool QtxBackgroundTool::isModeAllowed( Qtx::BackgroundMode mode ) const +{ + return myTypesAllowed.contains( mode ) ? myTypesAllowed[ mode ] : false; +} + +/*! + \brief Enable / disable specific background mode + \param mode background mode + \param on enable / disable flag (\c true by default) + \sa isModeAllowed() +*/ +void QtxBackgroundTool::setModeAllowed( Qtx::BackgroundMode mode, bool on ) +{ + if ( mode == Qtx::CustomGradientBackground ) + return; // NOT IMPLEMENTED YET // + + if ( isModeAllowed( mode ) != on ) { + Qtx::BackgroundData d = data(); // get current state + myTypesAllowed[ mode ] = on; // store new background mode state + internalUpdate(); // re-initialize + setData( d ); // restore current state (if possible) + } +} + +/*! + \brief Check if specific texture mode is allowed + \param mode texture mode + \return \c true if specified texture mode is enabled or \c false otherwise + \sa setTextureModeAllowed(), setTextureAllowed() +*/ +bool QtxBackgroundTool::isTextureModeAllowed( Qtx::TextureMode mode ) const +{ + return myTextureTypesAllowed.contains( mode ) ? myTextureTypesAllowed[ mode ] : false; +} + +/*! + \brief Enable / disable specific texture mode + \param mode texture mode + \param on enable / disable flag (\c true by default) + \sa isTextureModeAllowed(), setTextureAllowed() +*/ +void QtxBackgroundTool::setTextureModeAllowed( Qtx::TextureMode mode, bool on ) +{ + if ( isTextureModeAllowed( mode ) != on ) { + Qtx::BackgroundData d = data(); // get current state + myTextureTypesAllowed[ mode ] = on; // store new texture mode + internalUpdate(); // re-initialize + setData( d ); // restore current state (if possible) + } +} + +/*! + \brief Check if texture controls are allowed (shown) + \return \c true if texture controls are enabled or \c false otherwise + \sa setTextureAllowed(), setTextureModeAllowed() +*/ +bool QtxBackgroundTool::isTextureAllowed() const +{ + return myTextureAllowed; +} + +/*! + \brief Enable / disable texture controls + \param on enable / disable flag (\c true by default) + \sa isTextureAllowed(), setTextureModeAllowed() +*/ +void QtxBackgroundTool::setTextureAllowed( bool on ) +{ + if ( myTextureAllowed != on ) { + myTextureAllowed = on; + setOrientation( orientation() ); + } +} + +/*! + \brief Get allowed image formats + \return image formats + \sa setImageFormats() +*/ +QString QtxBackgroundTool::imageFormats() const +{ + return myImageFormats; +} + +/*! + \brief Set allowed image formats + \param formats image formats + \sa imageFormats() +*/ +void QtxBackgroundTool::setImageFormats( const QString& formats ) +{ + myImageFormats = formats.isEmpty() ? tr( "Images Files (*.bmp *.png *.jpg *.jpeg *.gif *.tiff)" ) : formats; +} + +/*! + \brief Get widget editor orientation + \return orientation + \sa setOrientation() +*/ +Qt::Orientation QtxBackgroundTool::orientation() const +{ + return qobject_cast( layout() ) ? Qt::Vertical : Qt::Horizontal; +} + +/*! + \brief Change widget orientation + \param orientation new widget orientation + \sa orientation() +*/ +void QtxBackgroundTool::setOrientation( Qt::Orientation orientation ) +{ + QBoxLayout* l = (orientation == Qt::Horizontal) ? (QBoxLayout*)(new QHBoxLayout) : (QBoxLayout*)(new QVBoxLayout); + l->setMargin( 0 ); + l->setSpacing( 5 ); + l->addWidget( myModeCombo ); + l->addWidget( myCContainer ); + myTContainer->setVisible( isTextureAllowed() ); + if ( isTextureAllowed() ) + l->addWidget( myTContainer ); + delete layout(); + setLayout( l ); +} + +/*! + \brief Initialization: fill in the widget with items according to the + available modes +*/ +void QtxBackgroundTool::internalUpdate() +{ + myModeCombo->clear(); + if ( isModeAllowed( Qtx::ColorBackground ) ) { + myModeCombo->addItem( tr( "Single Color" ) ); + myModeCombo->setItemData( 0, (int)Qtx::ColorBackground, TypeRole ); + } + if ( isModeAllowed( Qtx::SimpleGradientBackground ) ) { +// if ( myGradients.count() > 0 && myModeCombo->count() > 0 ) +// myModeCombo->insertSeparator( myModeCombo->count() ); + for ( int i = 0; i < myGradients.count(); i++ ) { + myModeCombo->addItem( myGradients[i] ); + int idx = myModeCombo->count()-1; + myModeCombo->setItemData( idx, (int)Qtx::SimpleGradientBackground, TypeRole ); + myModeCombo->setItemData( idx, myGradientsIds.count() > i ? myGradientsIds[i] : i, IdRole ); + } + } + if ( isModeAllowed( Qtx::CustomGradientBackground ) ) { +// if ( myModeCombo->count() > 0 ) +// myModeCombo->insertSeparator( myModeCombo->count() ); + myModeCombo->addItem( tr( "Custom" ) ); + int idx = myModeCombo->count()-1; + myModeCombo->setItemData( idx, (int)Qtx::CustomGradientBackground, TypeRole ); + } + + myTextureMode->clear(); + if ( isTextureModeAllowed( Qtx::CenterTexture ) ) + myTextureMode->addItem( tr( "Center" ), Qtx::CenterTexture ); + if ( isTextureModeAllowed( Qtx::TileTexture ) ) + myTextureMode->addItem( tr( "Tile" ), Qtx::TileTexture ); + if ( isTextureModeAllowed( Qtx::StretchTexture ) ) + myTextureMode->addItem( tr( "Stretch" ), Qtx::StretchTexture ); + + updateState(); +} + +/*! + \brief Update widget state +*/ +void QtxBackgroundTool::updateState() +{ + int idx = myModeCombo->currentIndex(); + int id = -1; + if ( idx >= 0 ) { + id = myModeCombo->itemData( idx, TypeRole ).toInt(); + switch( id ) { + case Qtx::ColorBackground: + myCContainer->setCurrentIndex( Color ); + break; + case Qtx::SimpleGradientBackground: + myCContainer->setCurrentIndex( Color ); + myLastGradient = myModeCombo->itemData( idx, IdRole ).toInt(); + break; + case Qtx::CustomGradientBackground: + myCContainer->setCurrentIndex( Gradient ); + break; + } + } + myModeCombo->setEnabled( idx >= 0 ); + myCContainer->setEnabled( idx >= 0 ); + mySecondColor->setEnabled( id == Qtx::SimpleGradientBackground ); + myTContainer->setEnabled( idx >= 0 ); + myFileName->setEnabled( myTextureCheck->isChecked() ); + myBrowseBtn->setEnabled( myTextureCheck->isChecked() ); + myTextureMode->setEnabled( myTextureCheck->isChecked() ); +} + +/*! + \brief Called when "Browse..." button is pressed +*/ +void QtxBackgroundTool::browse() +{ + QString fileName = QFileDialog::getOpenFileName( this, tr( "Select Picture" ), myFileName->text().trimmed(), myImageFormats ); + if ( !fileName.isEmpty() ) + myFileName->setText( fileName ); +} + +/*! + \class QtxBackgroundDialog + \brief Dialog box that can be used to set-up the background data + + Usage example: + \code + // create dialog box + QtxBackgroundDialog dlg( this ); + // assign gradients types + QStringList sl; + sl << "Horizontal" << "Vertical" << "First diagonal" << "Second diagonal"; + dlg.setGradients(sl); + // disable image texture and custom gradient modes + dlg.setModeAllowed(Qtx::ImageBackground, false); + dlg.setModeAllowed(Qtx::CustomGradientBackground, false); + // initialize dialog box with the some background data + dlg.setData(backgroundData); + // execute dialog box and obtain result background data + if ( dlg.exec() ) { + Qtx::BackgroundData bgData = dlg.getBackgroundData(); + } + \endcode + + Also it is possible to use static function: + \code + Qtx::BackgroundData bgData = QtxBackgroundDialog::getBackground( this ); + if ( bgData.isValid() ) + doSomething( bgData ); + \endcode +*/ + +/*! + \brief Constructor + \param parent parent widget +*/ +QtxBackgroundDialog::QtxBackgroundDialog( QWidget* parent ) + : QtxDialog( parent, true, true, OK | Cancel ) +{ + init(); +} + +/*! + \brief Constructor + \param bgData initial background data + \param parent parent widget +*/ +QtxBackgroundDialog::QtxBackgroundDialog( const Qtx::BackgroundData& bgData, QWidget* parent ) + : QtxDialog( parent, true, true, OK | Cancel ) +{ + init(); + setData( bgData ); +} + +/*! + \brief Destructor +*/ +QtxBackgroundDialog::~QtxBackgroundDialog() +{ +} + +/*! + \brief Perform internal initialization +*/ +void QtxBackgroundDialog::init() +{ + // title + setWindowTitle( tr( "Change background" ) ); + // flags + setDialogFlags( SetFocus ); + // move "Cancel" button to the right + setButtonPosition( Right, Cancel ); + // set OK button to be default (activated by Enter key) + qobject_cast( button( OK ) )->setDefault( true ); + + // main layout + QVBoxLayout* main = new QVBoxLayout( mainFrame() ); + main->setMargin( 0 ); + main->setSpacing( 5 ); + + // background widget + myTool = new QtxBackgroundTool( Qt::Vertical, mainFrame() ); + main->addWidget( myTool ); +} + +/*! + \brief Set background data + \param bgData background data +*/ +void QtxBackgroundDialog::setData( const Qtx::BackgroundData& bgData ) +{ + myTool->setData( bgData ); +} + +/*! + \brief Get background data + \return background data +*/ +Qtx::BackgroundData QtxBackgroundDialog::data() const +{ + return myTool->data(); +} + +/*! + \brief Set allowed two-color gradients to the widget + \param gradients gradients names + \param ids optional gradients identifiers; if not specified, gradients are automatically numbered starting from 0 +*/ +void QtxBackgroundDialog::setGradients( const QStringList& gradList, const QIntList& idList ) +{ + myTool->setGradients( gradList, idList ); +} + +/*! + \brief Enable / disable specific background mode + \param mode background mode + \param on enable / disable flag +*/ +void QtxBackgroundDialog::setModeAllowed( Qtx::BackgroundMode mode, bool on ) +{ + myTool->setModeAllowed( mode, on ); +} + +/*! + \brief Enable / disable texture controls + \param on enable / disable flag + \sa setTextureModeAllowed() +*/ +void QtxBackgroundDialog::setTextureAllowed( bool on ) +{ + myTool->setTextureAllowed( on ); +} + +/*! + \brief Enable / disable specific texture mode + \param mode texture mode + \param on enable / disable flag (\c true by default) + \sa setTextureAllowed() +*/ +void QtxBackgroundDialog::setTextureModeAllowed( Qtx::TextureMode mode, bool on ) +{ + myTool->setTextureModeAllowed( mode, on ); +} + +/*! + \brief Set allowed image formats + \param formats image formats +*/ +void QtxBackgroundDialog::setImageFormats( const QString& formats ) +{ + myTool->setImageFormats( formats ); +} + +/*! + \brief This is a convenience static function that returns an background data selected by the user. + If the user presses Cancel, it returns an invalid background data. + + By default: + - all background modes are enabled + - texture controls are shown + - all texture modes are enabled + - simple gradient types list is empty + - all image formats are supported + + To customize the dialog box behavior, initialize it passing the corresponding options to the function. + + \param bgData initial background data + \param parent parent widget + \param enableSolidColor "enable solid colored background mode" flag + \param enableGradient "enable simple gradient background mode" flag + \param enableCustom "enable custom gradient background mode" flag + \param enableTexture "show texture controls" flag + \param gradList list of simple gradients names + \param idList list of simple gradients identifiers + \param formats image formats + \return resulting background data chosen by the user or invalid data if users cancels operation +*/ +Qtx::BackgroundData QtxBackgroundDialog::getBackground( const Qtx::BackgroundData& bgData, + QWidget* parent, + bool enableSolidColor, + bool enableGradient, + bool enableCustom, + bool enableTexture, + const QStringList& gradList, + const QIntList& idList, + const QString& formats ) +{ + QtxBackgroundDialog dlg( parent ); + dlg.setTextureAllowed( enableTexture ); + dlg.setModeAllowed( Qtx::ColorBackground, enableSolidColor ); + dlg.setModeAllowed( Qtx::SimpleGradientBackground, enableGradient ); + dlg.setModeAllowed( Qtx::CustomGradientBackground, enableCustom ); + dlg.setGradients( gradList, idList ); + dlg.setImageFormats( formats ); + dlg.setData( bgData ); + Qtx::BackgroundData res; + int rc = dlg.exec(); + if ( rc ) res = dlg.data(); + return res; +} + +/*! + \brief This is a convenience static function that returns an background data selected by the user. + If the user presses Cancel, it returns an invalid background data. + + By default: + - all background modes are enabled + - texture controls are shown + - all texture modes are disabled + - simple gradient types list is empty + - all image formats are supported + + To customize the dialog box behavior, initialize it passing the corresponding options to the function. + + \param bgData initial background data + \param parent parent widget + \param tmList allowed texture modes + \param enableSolidColor "enable solid colored background mode" flag + \param enableGradient "enable simple gradient background mode" flag + \param enableCustom "enable custom gradient background mode" flag + \param enableTexture "show texture controls" flag + \param gradList list of simple gradients names + \param idList list of simple gradients identifiers + \param formats image formats + \return resulting background data chosen by the user or invalid data if users cancels operation +*/ +Qtx::BackgroundData QtxBackgroundDialog::getBackground( const Qtx::BackgroundData& bgData, + QWidget* parent, + const QIntList& tmList, + bool enableSolidColor, + bool enableGradient, + bool enableCustom, + bool enableTexture, + const QStringList& gradList, + const QIntList& idList, + const QString& formats ) +{ + QtxBackgroundDialog dlg( parent ); + dlg.setTextureAllowed( enableTexture ); + for ( int i = Qtx::CenterTexture; i <= Qtx::StretchTexture; i++ ) + dlg.setTextureModeAllowed( (Qtx::TextureMode)i, tmList.contains( i ) ); + dlg.setModeAllowed( Qtx::ColorBackground, enableSolidColor ); + dlg.setModeAllowed( Qtx::SimpleGradientBackground, enableGradient ); + dlg.setModeAllowed( Qtx::CustomGradientBackground, enableCustom ); + dlg.setGradients( gradList, idList ); + dlg.setImageFormats( formats ); + dlg.setData( bgData ); + Qtx::BackgroundData res; + int rc = dlg.exec(); + if ( rc ) res = dlg.data(); + return res; +} diff --git a/src/Qtx/QtxBackgroundTool.h b/src/Qtx/QtxBackgroundTool.h new file mode 100644 index 000000000..f676f124b --- /dev/null +++ b/src/Qtx/QtxBackgroundTool.h @@ -0,0 +1,139 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +// File: QtxBackgroundTool.h +// Author: Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com) + +#ifndef QTXBACKGROUNDTOOL_H +#define QTXBACKGROUNDTOOL_H + +#include "Qtx.h" +#include "QtxDialog.h" + +#include +#include + +class QCheckBox; +class QComboBox; +class QStackedWidget; +class QLineEdit; +class QPushButton; +class QtxColorButton; + +class QTX_EXPORT QtxBackgroundTool : public QWidget +{ + enum { Color, Gradient }; + enum { TypeRole = Qt::UserRole, IdRole }; + + Q_OBJECT + +public: + QtxBackgroundTool( QWidget* = 0 ); + QtxBackgroundTool( Qt::Orientation, QWidget* = 0 ); + virtual ~QtxBackgroundTool(); + + Qtx::BackgroundData data() const; + void setData( const Qtx::BackgroundData& ); + + void gradients( QStringList&, QIntList& ) const; + void setGradients( const QStringList&, const QIntList& = QIntList() ); + + bool isModeAllowed( Qtx::BackgroundMode ) const; + void setModeAllowed( Qtx::BackgroundMode, bool = true ); + + bool isTextureModeAllowed( Qtx::TextureMode ) const; + void setTextureModeAllowed( Qtx::TextureMode, bool = true ); + + bool isTextureAllowed() const; + void setTextureAllowed( bool = true ); + + QString imageFormats() const; + void setImageFormats( const QString& ); + + Qt::Orientation orientation() const; + void setOrientation( Qt::Orientation ); + +private: + void init( Qt::Orientation ); + void internalUpdate(); + +private slots: + void updateState(); + void browse(); + +private: + QComboBox* myModeCombo; + QStackedWidget* myCContainer; + QWidget* myTContainer; + QCheckBox* myTextureCheck; + QLineEdit* myFileName; + QPushButton* myBrowseBtn; + QComboBox* myTextureMode; + QtxColorButton* myFirstColor; + QtxColorButton* mySecondColor; + QStringList myGradients; + QIntList myGradientsIds; + bool myTextureAllowed; + QMap myTypesAllowed; + QMap myTextureTypesAllowed; + QString myImageFormats; + int myLastGradient; +}; + +class QTX_EXPORT QtxBackgroundDialog : public QtxDialog +{ + Q_OBJECT + +public: + QtxBackgroundDialog( QWidget* = 0 ); + QtxBackgroundDialog( const Qtx::BackgroundData&, QWidget* = 0 ); + virtual ~QtxBackgroundDialog(); + + void setData( const Qtx::BackgroundData& ); + Qtx::BackgroundData data() const; + + static Qtx::BackgroundData getBackground( const Qtx::BackgroundData& = Qtx::BackgroundData(), + QWidget* = 0, + bool = true, bool = true, bool = true, bool = true, + const QStringList& = QStringList(), + const QIntList& = QIntList(), + const QString& = QString() ); + static Qtx::BackgroundData getBackground( const Qtx::BackgroundData&, + QWidget*, + const QIntList&, + bool = true, bool = true, bool = true, bool = true, + const QStringList& = QStringList(), + const QIntList& = QIntList(), + const QString& = QString() ); + + + void setGradients( const QStringList&, const QIntList& = QIntList() ); + void setModeAllowed( Qtx::BackgroundMode, bool = true ); + void setTextureAllowed( bool = true ); + void setTextureModeAllowed( Qtx::TextureMode, bool = true ); + void setImageFormats( const QString& ); + +private: + void init(); + +private: + QtxBackgroundTool* myTool; +}; + +#endif // QTXBACKGROUNDTOOL_H diff --git a/src/Qtx/QtxBiColorTool.cxx b/src/Qtx/QtxBiColorTool.cxx new file mode 100644 index 000000000..8eae5a038 --- /dev/null +++ b/src/Qtx/QtxBiColorTool.cxx @@ -0,0 +1,216 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +// File: QtxBiColorTool.cxx +// Author: Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com) + +#include "QtxBiColorTool.h" +#include "QtxColorButton.h" + +#include +#include +#include +#include +#include + +const int BICOLOR_MAX_DELTA = 100; + +/*! + \class QtxBiColorTool::ColorLabel + \brief Draw colored label (for secondary color) + \internal +*/ +class QtxBiColorTool::ColorLabel: public QFrame +{ +public: + ColorLabel( QWidget* parent) : QFrame( parent ) + { + setFrameStyle( QFrame::Box | QFrame::Plain ); + setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ); + } + ~ColorLabel() {} + QSize sizeHint() const + { + return minimumSizeHint(); + } + QSize minimumSizeHint() const + { + int pm = style()->pixelMetric(QStyle::PM_ButtonMargin); + QFontMetrics fm ( font() ); + return QSize( fm.height() + pm, fm.height() + pm ); + } + void paintEvent( QPaintEvent* e ) + { + QPainter p( this ); + drawFrame( &p ); + QRect r = contentsRect(); + if ( myColor.isValid() ) { + p.fillRect( r, QBrush( myColor ) ); + } + else { + p.fillRect( r, QBrush( palette().color( foregroundRole() ), Qt::BDiagPattern ) ); + } + p.end(); + } + void setColor( const QColor& c ) + { + myColor = c; + update(); + } + +private: + QColor myColor; +}; + +/*! + \class QtxBiColorTool + \brief Implementation of the widget managing a couple of colors. + + The main color is specified explicitly. The secondary color is calculated + by changing "value" of the main color in HSV notation to the specified delta. +*/ + +/*! + \brief Constructor. + \param parent parent widget +*/ +QtxBiColorTool::QtxBiColorTool( QWidget* parent ) + : QWidget( parent ) +{ + QHBoxLayout* l = new QHBoxLayout( this ); + l->setMargin( 0 ); + l->setSpacing( 5 ); + + myMainColor = new QtxColorButton( this ); + myMainColor->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ); + myExtraText = new QLabel( this ); + myRuler = new QSlider( Qt::Horizontal, this ); + myRuler->setMinimum( -BICOLOR_MAX_DELTA ); + myRuler->setMaximum( +BICOLOR_MAX_DELTA ); + myRuler->setSingleStep( 1 ); + myRuler->setPageStep( 10 ); + myRuler->setValue( 0 ); + myRuler->setTickPosition( QSlider::NoTicks ); + myDelta = new ColorLabel( this ); + + l->addWidget( myMainColor ); + l->addWidget( myExtraText ); + l->addWidget( myRuler ); + l->addWidget( myDelta ); + + connect( myMainColor, SIGNAL( changed( QColor ) ), this, SLOT( updateState() ) ); + connect( myRuler, SIGNAL( valueChanged( int ) ), this, SLOT( updateState() ) ); + + updateState(); +} + +/*! + \brief Destructor. +*/ +QtxBiColorTool::~QtxBiColorTool() +{ +} + +/*! + \brief Get currently selected main color + + Returns invalid QColor if no color is selected. + + \return selected main color + \sa setMainColor() +*/ +QColor QtxBiColorTool::mainColor() const +{ + return myMainColor->color(); +} + +/*! + \brief Set main color. + \param c color to be set as current main color + \sa mainColor() +*/ +void QtxBiColorTool::setMainColor( const QColor& c ) +{ + myMainColor->setColor( c ); + updateState(); +} + +/*! + \brief Get current value delta for the secondary color + \return curent color value delta + \sa setDelta(), secondaryColor() +*/ +int QtxBiColorTool::delta() const +{ + return myRuler->value(); +} + +/*! + \brief Set value delta for the secondary color + \param d new color value delta + \sa delta(), secondaryColor() +*/ +void QtxBiColorTool::setDelta( int d ) +{ + myRuler->setValue( d ); + updateState(); +} + +/*! + \brief Get secondary color. + + Returns invalid QColor if no main color is selected. + Secondary color is calculated by changing "value" of the main color + in HSV notation to the specified delta. + + \return secondary color + \sa mainColor(), setMainColor(), delta(), setDelta() +*/ +QColor QtxBiColorTool::secondaryColor() const +{ + return Qtx::mainColorToSecondary( mainColor(), delta() ); +} + +/*! + \brief Returns auxiliary text assigned to the widget + \return current widget text + \sa setText() +*/ +QString QtxBiColorTool::text() const +{ + return myExtraText->text(); +} + +/*! + \brief Assign auxiliary text to the widet + \param txt new widget text + \sa text() +*/ +void QtxBiColorTool::setText( const QString& txt ) +{ + myExtraText->setText( txt ); +} + +/*! + \brief Update widget state +*/ +void QtxBiColorTool::updateState() +{ + myDelta->setColor( secondaryColor() ); +} diff --git a/src/Qtx/QtxBiColorTool.h b/src/Qtx/QtxBiColorTool.h new file mode 100644 index 000000000..40eca44ab --- /dev/null +++ b/src/Qtx/QtxBiColorTool.h @@ -0,0 +1,66 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +// File: QtxBiColorTool.h +// Author: Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com) + +#ifndef QTXBICOLORTOOL_H +#define QTXBICOLORTOOL_H + +#include "Qtx.h" + +#include +#include + +class QLabel; +class QSlider; +class QtxColorButton; + +class QTX_EXPORT QtxBiColorTool : public QWidget +{ + class ColorLabel; + + Q_OBJECT + +public: + QtxBiColorTool( QWidget* = 0 ); + virtual ~QtxBiColorTool(); + + QColor mainColor() const; + void setMainColor( const QColor& ); + + int delta() const; + void setDelta( int ); + + QColor secondaryColor() const; + + QString text() const; + void setText( const QString& ); + +private slots: + void updateState(); + +private: + QtxColorButton* myMainColor; + QLabel* myExtraText; + QSlider* myRuler; + ColorLabel* myDelta; +}; + +#endif // QTXBICOLORTOOL_H diff --git a/src/Qtx/QtxShortcutEdit.cxx b/src/Qtx/QtxShortcutEdit.cxx new file mode 100755 index 000000000..88a280bcd --- /dev/null +++ b/src/Qtx/QtxShortcutEdit.cxx @@ -0,0 +1,404 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +#include "QtxShortcutEdit.h" + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +#define COLUMN_SIZE 500 + +static const char* delete_icon[] = { +"16 16 3 1", +"` c #810000", +" c none", +"# c #ffffff", +" ", +" ", +" ``# ``# ", +" ````# ``# ", +" ````# ``# ", +" ```# `# ", +" `````# ", +" ```# ", +" `````# ", +" ```# ``# ", +" ```# ``# ", +" ```# `# ", +" ```# `# ", +" `# `# ", +" ", +" " +}; + +/*! + \brief Constructor + \param parent parent widget +*/ +QtxShortcutEdit::QtxShortcutEdit( QWidget* parent ) +: QFrame( parent ) +{ + initialize(); + myShortcut->installEventFilter(this); +} + +/*! + \brief Destructor +*/ +QtxShortcutEdit::~QtxShortcutEdit() +{ +} + +/*! + \brief Sets custom shortcut + \param seq a key sequence describes a combination of keys + \sa shortcut() +*/ +void QtxShortcutEdit::setShortcut( const QKeySequence& seq ) +{ + QString txt = seq.toString(); + myPrevShortcutText = txt; + myShortcut->setText( txt ); +} + +/*! + \brief Gets custom shortcut + \return a key sequence describes a combination of keys + \sa setShortcut() +*/ +QKeySequence QtxShortcutEdit::shortcut() +{ + return QKeySequence::fromString( myShortcut->text() ); +} + +/*! + \brief Gets the key sequence from keys that were pressed + \param e a key event + \return a string representation of the key sequence +*/ +QString QtxShortcutEdit::parseEvent( QKeyEvent* e ) +{ + bool isShiftPressed = e->modifiers() & Qt::ShiftModifier; + bool isControlPressed = e->modifiers() & Qt::ControlModifier; + bool isAltPressed = e->modifiers() & Qt::AltModifier; + bool isMetaPressed = e->modifiers() & Qt::MetaModifier; + bool isModifiersPressed = isShiftPressed || isControlPressed || isAltPressed || isMetaPressed; + int result=0; + if( isControlPressed ) + result += Qt::CTRL; + if( isAltPressed ) + result += Qt::ALT; + if( isShiftPressed ) + result += Qt::SHIFT; + if( isMetaPressed ) + result += Qt::META; + + int aKey = e->key(); + if ( ( isValidKey( aKey ) && isModifiersPressed ) || ( ( aKey >= Qt::Key_F1 ) && ( aKey <= Qt::Key_F12 ) ) ) + result += aKey; + + return QKeySequence( result ).toString(); +} + +/*! + \brief Check if the key event contains a 'valid' key + \param aKey the code of the key + \return \c true if the key is 'valid' +*/ + +bool QtxShortcutEdit::isValidKey( int aKey ) +{ + if ( aKey == Qt::Key_Underscore || aKey == Qt::Key_Escape || + ( aKey >= Qt::Key_Backspace && aKey <= Qt::Key_Delete ) || + ( aKey >= Qt::Key_Home && aKey <= Qt::Key_PageDown ) || + ( aKey >= Qt::Key_F1 && aKey <= Qt::Key_F12 ) || + ( aKey >= Qt::Key_Space && aKey <= Qt::Key_Asterisk ) || + ( aKey >= Qt::Key_Comma && aKey <= Qt::Key_Question ) || + ( aKey >= Qt::Key_A && aKey <= Qt::Key_AsciiTilde ) ) + return true; + return false; +} + +/*! + \brief Called when "Clear" button is clicked. +*/ +void QtxShortcutEdit::onCliked() +{ + myShortcut->setText( "" ); +} + +/*! + \brief Called when myShortcut loses focus. +*/ +void QtxShortcutEdit::onEditingFinished() +{ + if ( myShortcut->text().endsWith("+") ) + myShortcut->setText( myPrevShortcutText ); +} + +/*! + \brief Custom event filter. + \param obj event receiver object + \param event event + \return \c true if further event processing should be stopped +*/ +bool QtxShortcutEdit::eventFilter(QObject* obj, QEvent* event) +{ + if ( obj == myShortcut ) { + if (event->type() == QEvent::KeyPress ) { + QKeyEvent* keyEvent = static_cast(event); + QString text = parseEvent( keyEvent ); + if ( keyEvent->key() == Qt::Key_Delete || keyEvent->key() == Qt::Key_Backspace ) + onCliked(); + if ( text != "" ) + myShortcut->setText( text ); + return true; + } + if ( event->type() == QEvent::KeyRelease ) { + if ( myShortcut->text().endsWith("+") ) + myShortcut->setText( myPrevShortcutText ); + else myPrevShortcutText = myShortcut->text(); + + return true; + } + } + return false; +} + +/* + \brief Perform internal intialization. +*/ +void QtxShortcutEdit::initialize() +{ + myPrevShortcutText = QString(); + + QHBoxLayout* base = new QHBoxLayout( this ); + base->setMargin( 0 ); + base->setSpacing( 5 ); + + base->addWidget( myShortcut = new QLineEdit( this ) ); + + QToolButton* deleteBtn = new QToolButton(); + deleteBtn->setIcon( QPixmap( delete_icon ) ); + base->addWidget( deleteBtn ); + + myShortcut->setSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::Fixed ); + deleteBtn->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ); + + connect( deleteBtn, SIGNAL( clicked() ), this, SLOT( onCliked() ) ); + connect( myShortcut, SIGNAL( editingFinished() ), this, SLOT( onEditingFinished() ) ); +} + +/*! + \brief Constructor + \param parent parent widget +*/ +QtxShortcutTree::QtxShortcutTree( QWidget * parent ) : QTreeWidget( parent ) +{ + setColumnCount( 2 ); + setSelectionMode( QAbstractItemView::SingleSelection ); + setColumnWidth ( 0, COLUMN_SIZE); + setSortingEnabled(false); + headerItem()->setHidden ( true ); + + this->installEventFilter(this); + connect( this, SIGNAL( currentItemChanged ( QTreeWidgetItem*, QTreeWidgetItem* ) ), this, SLOT( onCurrentItemChanged ( QTreeWidgetItem*, QTreeWidgetItem* ) ) ); + +} + +/*! + \brief Destructor +*/ +QtxShortcutTree::~QtxShortcutTree(){} + +/*! + \brief Custom event filter. + \param obj event receiver object + \param event event + \return \c true if further event processing should be stopped +*/ +bool QtxShortcutTree::eventFilter(QObject* obj, QEvent* event) +{ + if ( currentItem() && currentItem()->isSelected() ) { + + if (event->type() == QEvent::KeyPress ) { + QKeyEvent* keyEvent = static_cast(event); + QString text = QtxShortcutEdit::parseEvent( keyEvent ); + if ( keyEvent->key() == Qt::Key_Delete || keyEvent->key() == Qt::Key_Backspace ) + currentItem()->setText( 1, "" ); + if ( text != "" ) { + if ( text.endsWith( "+" ) || checkUniqueness( currentItem(), text ) ) + currentItem()->setText( 1, text ); + } + return true; + } + if ( event->type() == QEvent::KeyRelease ) { + if ( currentItem()->text( 1 ).endsWith( "+" ) ) + currentItem()->setText( 1, myPrevBindings[ currentItem()->parent()->text( 0 ) ][ currentItem()->text( 0 ) ] ); + else myPrevBindings[ currentItem()->parent()->text( 0 ) ][ currentItem()->text( 0 ) ] = currentItem()->text( 1 ); + + return true; + } + } + return false; +} + +/*! + \brief Called when the current item changes. + \param cur the current item + \param prev the previous current item +*/ +void QtxShortcutTree::onCurrentItemChanged( QTreeWidgetItem* cur, QTreeWidgetItem* prev ) +{ + if ( prev && prev->text( 1 ).endsWith( "+" ) ) + prev->setText( 1, myPrevBindings[ prev->parent()->text( 0 ) ][ prev->text( 0 ) ] ); +} + +/*! + \brief Set key bindings to the tree + \param title the name of top-level item + \param theShortcutMap map of key bindings +*/ +void QtxShortcutTree::setBindings( const QString& title, const ShortcutMap& theShortcutMap ) +{ + QTreeWidgetItem* item= new QTreeWidgetItem(); + QFont font = item->font(0); + font.setBold(true); + + if ( findItems( title, Qt::MatchFixedString ).isEmpty() ) { + item->setText( 0, title ); + item->setFont( 0, font ); + addTopLevelItem( item ); + item->setFlags( Qt::ItemIsEnabled ); + } else { + item = findItems( title, Qt::MatchFixedString ).first(); + item->takeChildren(); + } + for( ShortcutMap::const_iterator it = theShortcutMap.constBegin(); it != theShortcutMap.constEnd(); ++it ) + item->addChild( new QTreeWidgetItem( QStringList() << it.key() << it.value() ) ); + myPrevBindings.insert( title, theShortcutMap); +} + +/*! + \brief Get all sections names. + \return list of section names +*/ +QStringList QtxShortcutTree::sections() const +{ + QStringList lst; + for( int i = 0; i < topLevelItemCount(); i++ ) + lst << topLevelItem( i )->text( 0 ); + return lst; +} + +ShortcutMap* QtxShortcutTree::bindings( const QString& sec ) const +{ + ShortcutMap* aMap = new ShortcutMap(); + QTreeWidgetItem* item = findItems( sec, Qt::MatchFixedString ).first(); + int nbChildren = item->childCount(); + + for( int i = 0; i < nbChildren; i++ ) { + QTreeWidgetItem* child = item->child(i); + aMap->insert( child->text( 0 ), child->text( 1 ) ); + } + + return aMap; +} + +void QtxShortcutTree::focusOutEvent ( QFocusEvent* event ) +{ + QWidget::focusOutEvent( event ); + if ( currentItem() && currentItem()->isSelected() ) + currentItem()->setText( 1, myPrevBindings[ currentItem()->parent()->text( 0 ) ][ currentItem()->text( 0 ) ] ); +} + +/*! + \brief Set the list of shortcuts general sections. + + Key combinations in general sections should not intersect + with any other key combinations. + + \param sectionsList list of common section names +*/ +void QtxShortcutTree::setGeneralSections( const QStringList& sectionsList ) +{ + myGeneralSections = sectionsList; +} + +/*! + \brief Check uniqueness of the shortcut. + \param item current item of the shortcut tree + \param shortcut shortcut appointed for the current item + \return \c true if the given shortcut is allowed +*/ +bool QtxShortcutTree::checkUniqueness( QTreeWidgetItem* item, const QString& shortcut ) +{ + // List of sections to check shortcut intersections + QStringList sectionsList; + + // Current section + QString currentSection = currentItem()->parent()->text( 0 ); + + // If the current section is general + if ( myGeneralSections.contains(currentSection) ) { + sectionsList = sections(); + int currentSectionIndex = sectionsList.indexOf(currentSection); + sectionsList.move( currentSectionIndex, 0); + } + else { + sectionsList = myGeneralSections; + sectionsList.prepend(currentSection); + } + + // Iterate on sections + QStringList::const_iterator it; + for( it = sectionsList.constBegin(); it != sectionsList.constEnd(); ++it ) { + QString section = *it; + + // Iterate on actual section + QTreeWidgetItem* sectionRoot = findItems( section, Qt::MatchFixedString ).first(); + int nbChildren = sectionRoot->childCount(); + + for( int i = 0; i < nbChildren; i++ ) { + QTreeWidgetItem* child = sectionRoot->child(i); + + if ( (child != item) && (shortcut == child->text( 1 )) ) { + bool res = QMessageBox::warning( parentWidget(), tr("Warning"), + tr("The \"%1\" shortcut has already used by the \"%2\" action.\n") + .arg(shortcut, section + ":" + child->text( 0 ) ) + + tr("Do you want to reassign it from that action to the current one?"), + QMessageBox::Yes, QMessageBox::No ) == QMessageBox::Yes; + if (res) + child->setText( 1, "" ); + return res; + } + } + } + + return true; +} diff --git a/src/Qtx/QtxShortcutEdit.h b/src/Qtx/QtxShortcutEdit.h new file mode 100755 index 000000000..391f9b341 --- /dev/null +++ b/src/Qtx/QtxShortcutEdit.h @@ -0,0 +1,87 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +#ifndef QTXSHORTCUTEDIT_H +#define QTXSHORTCUTEDIT_H + +#include "Qtx.h" + +#include +#include + +class QLineEdit; +class QPushButton; +class QTreeWidgetItem; + +typedef QMap< QString, QString > ShortcutMap; + +class QTX_EXPORT QtxShortcutEdit : public QFrame +{ + Q_OBJECT + +public: + QtxShortcutEdit( QWidget* = 0 ); + virtual ~QtxShortcutEdit(); + void setShortcut( const QKeySequence& ); + QKeySequence shortcut(); + static QString parseEvent( QKeyEvent* ); + static bool isValidKey( int ); + + +private slots: + void onCliked(); + void onEditingFinished(); + +protected: + virtual bool eventFilter( QObject*, QEvent* ); + +private: + void initialize(); + +private: + QLineEdit* myShortcut; + QString myPrevShortcutText; +}; + +class QTX_EXPORT QtxShortcutTree : public QTreeWidget +{ + Q_OBJECT + +public: + QtxShortcutTree( QWidget * parent = 0 ); + virtual ~QtxShortcutTree(); + void setBindings( const QString&, const ShortcutMap& ); + ShortcutMap* bindings( const QString& ) const; + QStringList sections() const; + void setGeneralSections( const QStringList& ); + +protected: + virtual bool eventFilter( QObject*, QEvent* ); + virtual void focusOutEvent( QFocusEvent* ); + virtual bool checkUniqueness( QTreeWidgetItem*, const QString& ); + +private slots: + void onCurrentItemChanged( QTreeWidgetItem*, QTreeWidgetItem* ); + +private: + QMap< QString, ShortcutMap > myPrevBindings; + QStringList myGeneralSections; +}; + +#endif // QTXSHORTCUTEDIT_H diff --git a/src/Qtx/QtxWebBrowser.cxx b/src/Qtx/QtxWebBrowser.cxx new file mode 100644 index 000000000..79e34bc8c --- /dev/null +++ b/src/Qtx/QtxWebBrowser.cxx @@ -0,0 +1,435 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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: QtxWebBrowser.cxx +// Author: Roman NIKOLAEV +// +#include "QtxWebBrowser.h" +#include "QtxSearchTool.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +/*! + \class WebViewSearcher + \brief A class is used with QtxSearchTool in order to search text within the web page + \internal +*/ +class WebViewSearcher : public QtxSearchTool::Searcher +{ +public: + WebViewSearcher( QWebView* ); + ~WebViewSearcher(); + + bool find( const QString&, QtxSearchTool* ); + bool findNext( const QString&, QtxSearchTool* ); + bool findPrevious( const QString&, QtxSearchTool* ); + bool findFirst( const QString&, QtxSearchTool* ); + bool findLast( const QString&, QtxSearchTool* ); + +private: + QWebView* myView; +}; + +WebViewSearcher::WebViewSearcher( QWebView* view ) : myView( view ) +{ +} + +WebViewSearcher::~WebViewSearcher() +{ +} + +bool WebViewSearcher::find( const QString& text, QtxSearchTool* st ) +{ + QWebPage::FindFlags fl = 0; + if ( st->isCaseSensitive() ) fl = fl | QWebPage::FindCaseSensitively; + if ( st->isSearchWrapped() ) fl = fl | QWebPage::FindWrapsAroundDocument; + return myView->findText( text, fl ); +} + +bool WebViewSearcher::findNext( const QString& text, QtxSearchTool* st ) +{ + return find( text, st ); +} + +bool WebViewSearcher::findPrevious( const QString& text, QtxSearchTool* st ) +{ + QWebPage::FindFlags fl = QWebPage::FindBackward; + if ( st->isCaseSensitive() ) fl = fl | QWebPage::FindCaseSensitively; + if ( st->isSearchWrapped() ) fl = fl | QWebPage::FindWrapsAroundDocument; + return myView->findText( text, fl ); +} + +bool WebViewSearcher::findFirst( const QString&, QtxSearchTool* ) +{ + return false; +} + +bool WebViewSearcher::findLast( const QString&, QtxSearchTool* ) +{ + return false; +} + +/*! + \class QtxWebBrowser + + \brief The QtxWebBrowser provides a window that can display html pages. + + Only one instance of the QtxWebBrowser class can be created. To access the browser + window, use static method QtxWebBrowser::webBrowser(), which creates an + instance of the QtxWebBrowser widget (if it is not yet created) and returns a + pointer to it. + + You should not destroy this instance - it is done automatically after + closing of the browser window. To close window programmatically use + method close(). + + To set visual properties of the browser use static method setData(). + + The following sample demonstrates how to use web browser. + In this code the browser window is created, /data/index.html file is opened + and scrolled to the "anchor1" anchor on this page. + + \code + int main(int argc, char *argv[]) + { + QApplication app(argc, argv); + + // set icon, title and menu items. + QtxWebBrowser::setData("browser:title", tr("Web Browser")); + QtxWebBrowser::setData("browser:icon", QPixmap(":/icon.png")); + QtxWebBrowser::setData("menu:file:title", tr("&File")); + QtxWebBrowser::setData("action:close:title", tr("&Close")); + + // show HTML page + QtxWebBrowser::loadUrl("file:///data/index.html", "anchor1"); + + return app.exec(); + } + \endcode + +*/ + +//! The only one instance of web browser +QtxWebBrowser* QtxWebBrowser::myBrowser = 0; + +//! Internal data map to store resources of the browser. +QMap QtxWebBrowser::myData; + +/*! + \brief Constructor. + + Construct the web browser. +*/ +QtxWebBrowser::QtxWebBrowser() : QMainWindow( 0 ) +{ + setAttribute( Qt::WA_DeleteOnClose ); + statusBar(); + + QWidget* frame = new QWidget( this ); + + myWebView = new QWebView( frame ); + myWebView->page()->setLinkDelegationPolicy( QWebPage::DelegateAllLinks ); + myFindPanel = new QtxSearchTool( frame, myWebView, + QtxSearchTool::Basic | QtxSearchTool::Case | QtxSearchTool::Wrap, + Qt::Horizontal ); + myFindPanel->setFrameStyle( QFrame::NoFrame | QFrame::Plain ); + myFindPanel->setActivators( QtxSearchTool::SlashKey ); + myFindPanel->setSearcher( new WebViewSearcher( myWebView ) ); + myFindPanel->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ); + + myToolbar = addToolBar( tr( "Navigation" ) ); + myToolbar->addAction( myWebView->pageAction( QWebPage::Back ) ); + myToolbar->addAction( myWebView->pageAction( QWebPage::Forward ) ); + + myMenus[ File ] = menuBar()->addMenu( tr( "&File" ) ); + myActions[ Find ] = myMenus[ File ]->addAction( tr( "&Find in text..." ), myFindPanel, SLOT( find() ), QKeySequence( QKeySequence::Find ) ); + myActions[ FindNext ] = myMenus[ File ]->addAction( tr( "&Find next" ), myFindPanel, SLOT( findNext() ), QKeySequence( QKeySequence::FindNext ) ); + myActions[ FindPrev ] = myMenus[ File ]->addAction( tr( "&Find previous" ), myFindPanel, SLOT( findPrevious() ), QKeySequence( QKeySequence::FindPrevious ) ); + myMenus[ File ]->addSeparator(); + myActions[ Close ] = myMenus[ File ]->addAction( tr( "&Close" ), this, SLOT( close() ) ); + + QVBoxLayout* main = new QVBoxLayout( frame ); + main->addWidget( myWebView ); + main->addWidget( myFindPanel ); + main->setMargin( 0 ); + main->setSpacing( 3 ); + + connect( myWebView, SIGNAL( titleChanged( QString ) ), SLOT( adjustTitle() ) ); + connect( myWebView, SIGNAL( linkClicked( QUrl ) ), SLOT( linkClicked( QUrl ) ) ); + connect( myWebView->page(), SIGNAL( linkHovered( QString, QString, QString ) ), SLOT( linkHovered( QString, QString, QString ) ) ); + + setCentralWidget( frame ); + setFocusProxy( myWebView ); + updateData(); + qAddPostRoutine( QtxWebBrowser::clearData ); +} + +/*! + \brief Destructor. +*/ +QtxWebBrowser::~QtxWebBrowser() +{ + myBrowser = 0; +} + +/*! + \brief Return the only instance of the QtxWebBrowser + \return instance of the QtxWebBrowser +*/ +QtxWebBrowser* QtxWebBrowser::webBrowser() +{ + if ( !myBrowser ) + myBrowser = new QtxWebBrowser(); + return myBrowser; +} + +/*! + \brief Load given url address and optional scroll to the specified anchor + \param url an url address to load + \param anchor an anchor to scroll page to +*/ +void QtxWebBrowser::loadUrl( const QString& url, const QString& anchor ) +{ + QString anUrl = url; + if( !anchor.isEmpty() ) anUrl += "#" + anchor; + anUrl.replace('\\', '/'); + + Qtx::alignWidget( webBrowser(), (QWidget*)QApplication::desktop(), Qtx::AlignCenter ); + + webBrowser()->show(); + webBrowser()->myWebView->load( QUrl( anUrl ) ); + webBrowser()->setFocus(); + webBrowser()->activateWindow(); + webBrowser()->raise(); +} + +/*! + \brief Set browser settings from. + + This method can be used to setup the browser properties. + - \c "browser:title" : title of the browser window + - \c "browser:icon" : icon of the browser window + - \c "toolbar:title" : title of the toolbar + - \c "menu:file:title" : File menu of the browser + - \c "action:close:title" : File/Close menu item title + - \c "action:close:icon" : File/Close menu item icon + - \c "action:back:title" : Navigation/Back menu item title + - \c "action:back:icon" : Navigation/Back menu item icon + - \c "action:forward:title" : Navigation/Forward menu item title + - \c "action:forward:icon" : Navigation/Forward menu item icon + - \c "action:find:title" : File/Find menu item title + - \c "action:find:icon" : File/Find menu item icon + - \c "action:findnext:title" : File/Find Next menu item title + - \c "action:findnext:icon" : File/Find Next menu item icon + - \c "action:findprev:title" : File/Find Previous menu item title + - \c "action:findprev:icon" : File/Find Previous menu item icon + + \param key name of the property + \param val value of the property + +*/ +void QtxWebBrowser::setData( const QString& key, const QVariant& val ) +{ + myData.insert( key, val ); + if ( myBrowser ) myBrowser->updateData(); +} + +/*! + \brief Get string value by key from the internal data map + \param key data key identifier + \return string value assigned to the key (null string if data is not assigned to the key) + \internal +*/ +QString QtxWebBrowser::getStringValue( const QString& key ) +{ + QString val; + if ( myData.contains( key ) && myData[key].canConvert( QVariant::String ) ) + val = myData[key].toString(); + return val; +} + +/*! + \brief Get icon value by key from the internal data map + \param key data key identifier + \return icon assigned to the key (null icon if data is not assigned to the key) + \internal +*/ +QIcon QtxWebBrowser::getIconValue(const QString& key) +{ + QIcon val; + if ( myData.contains( key ) ) { + if ( myData[key].canConvert( QVariant::Pixmap ) ) + val = myData[key].value(); + else if ( myData[key].canConvert( QVariant::Icon ) ) + val = myData[key].value(); + } + return val; +} + +/*! + \brief Update web browser properties from internal data map +*/ +void QtxWebBrowser::updateData() +{ + // main title + adjustTitle(); + + // window icon + QIcon icon = getIconValue( "browser:icon" ); + if ( !icon.isNull() ) + setWindowIcon( icon ); + + // toolbar title + QString tbTitle = getStringValue( "toolbar:title" ); + if ( myToolbar && !tbTitle.isEmpty() ) + myToolbar->setWindowTitle( tbTitle ); + + // File menu + QString fmenu = getStringValue( "menu:file:title" ); + if ( myMenus.contains( File ) && !fmenu.isEmpty() ) + myMenus[ File ]->setTitle( fmenu ); + + // File/Close menu + QString closeTlt = getStringValue( "action:close:title" ); + QIcon closeIco = getIconValue( "action:close:icon" ); + if ( myActions.contains( Close ) ) { + if ( !closeTlt.isEmpty() ) + myActions[ Close ]->setText( closeTlt ); + if ( !closeIco.isNull() ) + myActions[ Close ]->setIcon( closeIco ); + } + + // Navigation/Go Back menu + QString backTlt = getStringValue( "action:back:title" ); + QIcon backIco = getIconValue( "action:back:icon" ); + if ( !backTlt.isEmpty() ) + myWebView->pageAction( QWebPage::Back )->setText( backTlt ); + if ( !backIco.isNull() ) + myWebView->pageAction( QWebPage::Back )->setIcon( backIco ); + + // Navigation/Go Forward menu + QString fwdTlt = getStringValue( "action:forward:title" ); + QIcon fwdIco = getIconValue( "action:forward:icon" ); + if ( !fwdTlt.isEmpty() ) + myWebView->pageAction( QWebPage::Forward )->setText( fwdTlt ); + if ( !fwdIco.isNull() ) + myWebView->pageAction( QWebPage::Forward )->setIcon( fwdIco ); + + // File/Find menu + QString findTlt = getStringValue( "action:find:title" ); + QIcon findIco = getIconValue( "action:find:icon" ); + if ( myActions.contains( Find ) ) { + if ( !findTlt.isEmpty() ) + myActions[ Find ]->setText( findTlt ); + if ( !findIco.isNull() ) + myActions[ Find ]->setIcon( findIco ); + } + + // File/Find Next menu + QString findNextTlt = getStringValue( "action:findnext:title" ); + QIcon findNextIco = getIconValue( "action:findnext:icon" ); + if ( myActions.contains( FindNext ) ) { + if ( !findNextTlt.isEmpty() ) + myActions[ FindNext ]->setText( findNextTlt ); + if ( !findNextIco.isNull() ) + myActions[ FindNext ]->setIcon( findNextIco ); + } + + // File/Find Previous menu + QString findPrevTlt = getStringValue( "action:findprev:title" ); + QIcon findPrevIco = getIconValue( "action:findprev:icon" ); + if ( myActions.contains( FindPrev ) ) { + if ( !findPrevTlt.isEmpty() ) + myActions[ FindPrev ]->setText( findPrevTlt ); + if ( !findPrevIco.isNull() ) + myActions[ FindPrev ]->setIcon( findPrevIco ); + } +} + +/*! + \brief Clear internal data map + \internal +*/ +void QtxWebBrowser::clearData() +{ + myData.clear(); +} + +/*! + \brief Called when users activated any link at the page + \param url URL being clicked + \internal +*/ +void QtxWebBrowser::linkClicked( const QUrl& url ) +{ + myWebView->page()->setLinkDelegationPolicy( QWebPage::DontDelegateLinks ); + myWebView->load( url ); + if ( url.scheme() == "file" ) { + QString filename = url.toLocalFile(); + if ( QFileInfo( filename ).suffix().toLower() == "pdf" ) { +#ifdef WIN32 + ::system( QString( "start %2" ).arg( filename ).toLatin1().constData() ); +#else + // special processing of PDF files + QStringList readers; + readers << "xdg-open" << "acroread" << "kpdf" << "kghostview" << "xpdf"; + foreach ( QString r, readers ) { + QString reader = QString( "/usr/bin/%1" ).arg( r ); + if ( QFileInfo( reader ).exists() ) { + ::system( QString( "unset LD_LIBRARY_PATH; %1 %2 &" ).arg( reader ).arg( url.toLocalFile() ).toLatin1().constData() ); + break; + } + } +#endif // WIN32 + } + } + myWebView->page()->setLinkDelegationPolicy( QWebPage::DelegateAllLinks ); +} + +/*! + \brief Called when link is hovered + \param link link being hovered + \param title link title (if it is specified in the markup) + \param content provides text within the link element, e.g., text inside an HTML anchor tag + \internal +*/ +void QtxWebBrowser::linkHovered( const QString& link, const QString& /*title*/, const QString& /*context*/ ) +{ + statusBar()->showMessage( link ); +} + +/*! + \brief Update title of the window + \internal +*/ +void QtxWebBrowser::adjustTitle() +{ + QString title = getStringValue( "browser:title" ); + setWindowTitle( title.isEmpty() ? myWebView->title() : title + QString( " [%1]" ).arg( myWebView->title() ) ); +} diff --git a/src/Qtx/QtxWebBrowser.h b/src/Qtx/QtxWebBrowser.h new file mode 100644 index 000000000..f112bc861 --- /dev/null +++ b/src/Qtx/QtxWebBrowser.h @@ -0,0 +1,82 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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: QtxWebBrowser.h +// Author: Roman NIKOLAEV +// + +#ifndef QTXWEBBROWSER_H +#define QTXWEBBROWSER_H + +#include "Qtx.h" + +#include +#include + +class QAction; +class QMenu; +class QToolBar; +class QWebView; +class QUrl; +class QtxSearchTool; + +class QTX_EXPORT QtxWebBrowser : public QMainWindow +{ + Q_OBJECT + + enum { File }; + enum { Find, FindNext, FindPrev, Close }; + +private: + QtxWebBrowser(); + +public: + virtual ~QtxWebBrowser(); + + static QtxWebBrowser* webBrowser(); + static void loadUrl( const QString&, const QString& = QString() ); + static void setData( const QString&, const QVariant& ); + +private: + static QString getStringValue( const QString& ); + static QIcon getIconValue( const QString& ); + void updateData(); + static void clearData(); + +protected slots: + virtual void linkClicked( const QUrl& ); + virtual void linkHovered( const QString&, const QString&, const QString& ); + +private slots: + void adjustTitle(); + +private: + static QMap myData; + static QtxWebBrowser* myBrowser; + QWebView* myWebView; + QToolBar* myToolbar; + QMap myMenus; + QMap myActions; + QtxSearchTool* myFindPanel; +}; + +#endif // QTXWEBBROWSER_H diff --git a/src/QxGraph/resources/QxGraph_msg_fr.ts b/src/QxGraph/resources/QxGraph_msg_fr.ts new file mode 100755 index 000000000..c03cdeb51 --- /dev/null +++ b/src/QxGraph/resources/QxGraph_msg_fr.ts @@ -0,0 +1,31 @@ + + + + + @default + + MEN_CHANGE_BACKGROUND + Changer l'arrière-plan... + + + MNU_PAN_VIEW + Déplacement + + + DSC_PAN_VIEW + Déplacer la vue + + + MNU_RESET_VIEW + Restaurer + + + DSC_RESET_VIEW + Restaurer le point de vue + + + LBL_TOOLBAR_LABEL + Opérations de Visualisation + + + diff --git a/src/QxScene/resources/QxSceneViewer_msg_fr.ts b/src/QxScene/resources/QxSceneViewer_msg_fr.ts new file mode 100755 index 000000000..e122d7078 --- /dev/null +++ b/src/QxScene/resources/QxSceneViewer_msg_fr.ts @@ -0,0 +1,38 @@ + + + + + @default + + MEN_CHANGE_BACKGROUND + Changer l'arrière-plan + + + MNU_PAN_VIEW + Déplacement + + + DSC_PAN_VIEW + Déplacer la vue + + + MNU_RESET_VIEW + Restaurer + + + DSC_RESET_VIEW + Restaurer le point de vue + + + LBL_TOOLBAR_LABEL + Opérations de visualisation + + + + QxScene_ViewManager + + QXSCENE_VIEW_TITLE + Scène QGraphics:%M - visualisateur:%V + + + diff --git a/src/SPlot2d/SPlot2d_Histogram.cxx b/src/SPlot2d/SPlot2d_Histogram.cxx new file mode 100644 index 000000000..9635ca6ca --- /dev/null +++ b/src/SPlot2d/SPlot2d_Histogram.cxx @@ -0,0 +1,84 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : SPlot2d_Histogram.cxx +// Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com) + +#include "SPlot2d_Histogram.h" + +/*! + Constructor +*/ +SPlot2d_Histogram::SPlot2d_Histogram() +:Plot2d_Histogram() +{ +} + +/*! + Destructor +*/ +SPlot2d_Histogram::~SPlot2d_Histogram() +{ +} + +/*! + Copy constructor. Makes deep copy of data. +*/ +SPlot2d_Histogram::SPlot2d_Histogram( const SPlot2d_Histogram& hist ) +: Plot2d_Histogram( hist ) +{ + myIO = hist.getIO(); +} + +/*! + operator=. Makes deep copy of data. +*/ +SPlot2d_Histogram& SPlot2d_Histogram::operator=( const SPlot2d_Histogram& hist ) +{ + Plot2d_Histogram::operator=(hist); + myIO = hist.getIO(); + return *this; +} + +/*! + \return corresponding SALOME_InteractiveObject +*/ +Handle(SALOME_InteractiveObject) SPlot2d_Histogram::getIO() const +{ + return myIO; +} + +/*! + Sets corresponding SALOME_InteractiveObject + \param io - SALOME_InteractiveObject +*/ +void SPlot2d_Histogram::setIO( const Handle(SALOME_InteractiveObject)& io ) +{ + myIO = io; +} + +/*! + \return SALOME_InteractiveObject +*/ +bool SPlot2d_Histogram::hasIO() const +{ + return !myIO.IsNull(); +} diff --git a/src/SPlot2d/SPlot2d_Histogram.h b/src/SPlot2d/SPlot2d_Histogram.h new file mode 100644 index 000000000..a3bcf5ce8 --- /dev/null +++ b/src/SPlot2d/SPlot2d_Histogram.h @@ -0,0 +1,54 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 : SPlot2d_Histogram.h +// Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com) + +#ifndef SPlot2d_Histogram_h +#define SPlot2d_Histogram_h + +#include "SPlot2d.h" + +#include "Plot2d_Histogram.h" + +#ifndef _Handle_SALOME_InteractiveObject_HeaderFile +#include +#endif +#include "SALOME_InteractiveObject.hxx" + +class SPLOT2D_EXPORT SPlot2d_Histogram : public Plot2d_Histogram +{ +public: + + SPlot2d_Histogram(); + virtual ~SPlot2d_Histogram(); + SPlot2d_Histogram( const SPlot2d_Histogram& hist ); + SPlot2d_Histogram& operator= ( const SPlot2d_Histogram& hist ); + + virtual bool hasIO() const; + virtual Handle(SALOME_InteractiveObject) getIO() const; + virtual void setIO( const Handle(SALOME_InteractiveObject)& ); + +private: + Handle(SALOME_InteractiveObject) myIO; +}; + +#endif // SPlot2d_Histogram_h diff --git a/src/STD/resources/STD_msg_fr.ts b/src/STD/resources/STD_msg_fr.ts new file mode 100755 index 000000000..e8f4b4e79 --- /dev/null +++ b/src/STD/resources/STD_msg_fr.ts @@ -0,0 +1,493 @@ + + + + + @default + + TOT_DESK_EDIT_CUT + Couper + + + PRP_DESK_EDIT_CUT + Couper la sélection et la placer dans la presse-papier + + + MEN_DESK_EDIT_CUT + Co&uper + + + ERR_APP_NOAPP + Pas d'application + + + MEN_DESK_WINDOW + &Fenêtre + + + TOT_DESK_EDIT_COPY + Copier + + + MEN_DESK_WINDOW_CASCADE + Cascade + + + PRP_DESK_EDIT_COPY + Copier la sélection dans le presse-papiers + + + PRP_DESK_WINDOW_CASCADE + Ranger les fenêtres en cascade + + + TOT_DESK_FILE_SAVEAS + Enregistrer le document sous... + + + MEN_DESK_EDIT_COPY + &Copier + + + MSG_CANT_SAVE + Impossible de sauvegarder le fichier "%1". + + + INF_DESK_TOOLBAR_STANDARD + Standard + + + ALL_FILES + Tous les fichiers (*.*) + + + DESK_DEFAULTTITLE + Qt Framework d'Applications + + + QUE_DESK_EXIT + Voulez-vous vraiment quitter ? + + + INF_INFO + Information + + + ERR_DOC_UNKNOWNTYPE_OPEN + Vous essayez d'ouvrir un document de type inconnu +( %1 ) + + + ERR_DOC_UNKNOWNTYPE_SAVE + Vous essayez de sauvegarder le document sous un type inconnu +( %1 ) + + + TOT_DESK_NEWWINDOW + Créer une nouvelle fenêtre + + + BUT_CANCEL + &Annuler + + + MEN_DESK_HELP_ABOUT + &A propos de... + + + PRP_DESK_NEWWINDOW + Créer une nouvelle fenêtre + + + MEN_DESK_VIEW_STATUSBAR + &Barre de status + + + MEN_DESK_NEWWINDOW + &Nouvelle fenêtre + + + PRP_DESK_VIEW_STATUSBAR + Activer ou désactiver la barre de status + + + ERR_DOC_DIRWITHNAMEEXIST_SAVE + Impossible de sauvegarder le fichier %1. +Un répertoire avec ce nom existe déjà sur le disque. Essayez d'utiliser un autre nom + + + BUT_NO + N&on + + + BUT_OK + O&k + + + FILTER_FILES + Fichiers %1 (%2) + + + PRP_DESK_WINDOW_ACTIVATE + Activer la fenêtre + + + TOT_DESK_FILE_PRINT + Imprimer un document + + + TOT_DESK_FILE_CLOSE + Fermer le document + + + TOT_DESK_FILE_NEW + Créer un nouveau document + + + PRP_DESK_FILE_NEW + Crée un nouveau document + + + PRP_DESK_FILE_MRU + Ouvre un document + + + MEN_DESK_FILE_NEW + &Nouveau + + + MEN_DESK_FILE_MRU + &Fichiers récents + + + TOT_DESK_EDIT_PASTE + Coller + + + MEN_DESK_VIEW_DOCKWINDOWS + Fenêtres + + + BUT_YES + O&ui + + + MEN_DESK_VIEW + &Affichage + + + PRP_DESK_HELP_ABOUT + Montre la boîte de dialogue 'A propos' + + + MEN_DESK_FILE + Fic&hier + + + MEN_DESK_EDIT + &Edition + + + MEN_DESK_HELP + A&ide + + + ERR_ERROR + Erreur + + + ERR_DESK_NOAPP + Pas d'application enregistrée + + + INF_DESK_DOC_CREATE + Créer un nouveau document + + + QUE_DOC_ALREADYOPEN + Le document %1 est déjà ouvert. +Voulez-vous le réouvrir? + + + BUT_APPLY + A&ppliquer + + + BUT_CLOSE + &Fermer + + + INF_DESK_EXIT + &Quitter + + + ERR_UNKNOWN + Erreur inconnue + + + BUT_HELP + A&ide + + + PRP_DESK_FILE_CLOSE + Ferme le document actuel + + + PRP_DESK_FILE_PRINT + Imprime le document actuel + + + WRN_WARNING + Avertissement + + + TOT_DESK_HELP_ABOUT + A propos... + + + MEN_DESK_VIEW_TOOLBARS + Barres d'&outils + + + PRP_DESK_WINDOW_HSPLIT + Diviser la fenêtre actuelle en deux parties horizontales + + + MEN_DESK_WINDOW_HSPLIT + Séparation horizontale + + + PRP_DESK_EDIT_PASTE + Insérer le contenu du presse-papiers au point d'insertion + + + DLG_LOAD_STUDY_CAPTION + Ouvrir une étude + + + PRP_DESK_HELP_SEARCH + Chercher de l'information sur le sujet + + + PRP_DESK_FILE_SAVEAS + Sauvegarder le document actuel sous un nouveau nom + + + INF_READY + Prêt + + + INF_CANCELLED + Annulé + + + PRP_DESK_WINDOW_VSPLIT + Diviser la fenêtre actuelle en deux parties verticales + + + MEN_DESK_WINDOW_VSPLIT + Séparation verticale + + + PRP_DESK_WINDOW_TILE + Ranger les fenêtres en mosaïque + + + MEN_DESK_HELP_CONTENTS + &Contenu + + + PRP_DESK_HELP_CONTENTS + Afficher le sommaire de la référence documentaire + + + MEN_DESK_WINDOW_HTILE + Mosaïque horizontale + + + MEN_DESK_WINDOW_VTILE + Mosaïque verticale + + + ERR_DOC_PERMISSIONDENIED_SAVE + Impossible de sauvegarder le fichier %1. Autorisaton refusée. + + + INF_DESK_DOCALREADYOPEN + Impossible de sauvegarder le document sous le nom d'un document déjà ouvert. +Indiquez un autre nom pour le document que vous voulez sauvegarder. +( %1 ) + + + TIT_FILE_SAVEAS + Enregistrer sous + + + MEN_DESK_FILE_CLOSE + Fer&mer + + + MSG_FILE_EXISTS + Le fichier "%1" existe déjà. +Voulez-vous l'écraser ? + + + MEN_DESK_FILE_PRINT + &Imprimer + + + MEN_DESK_HELP_SEARCH + &Recherche... + + + MEN_DESK_VIEW_STDTOOLBAR + &Standard + + + MEN_DESK_FILE_SAVEAS + Enre&gistrer sous... + + + PRP_DESK_VIEW_STDTOOLBAR + Activer ou désactiver la barre standard + + + TOT_DESK_FILE_SAVE + Enregistrer le document + + + TOT_DESK_FILE_EXIT + Quitter l'application + + + TOT_DESK_FILE_LOAD + Charger le document + + + TOT_DESK_FILE_OPEN + Ouvrir un document + + + TOT_DESK_FILE_REOPEN + Réouvrir un document + + + PRP_DESK_FILE_EXIT + Quitte l'application + + + PRP_DESK_FILE_OPEN + Ouvre un document existant + + + PRP_DESK_FILE_REOPEN + Réouvrir le document actuel à partir d'un fichier + + + PRP_DESK_FILE_SAVE + Sauvegarder le document actuel + + + PRP_DESK_FILE_LOAD + Charge un document + + + PRP_DESK_WINDOW_HTILE + Ranger les fenêtres en mosaïque horizontale + + + PRP_DESK_WINDOW_VTILE + Ranger les fenêtres en mosaïque verticale + + + MEN_DESK_WINDOW_TILE + Mosaïque + + + MEN_DESK_FILE_EXIT + &Quitter + + + MEN_DESK_FILE_OPEN + &Ouvrir... + + + MEN_DESK_FILE_REOPEN + &Réouvrir + + + MEN_DESK_FILE_LOAD + Connec&ter... + + + MEN_DESK_FILE_SAVE + &Enregistrer + + + MEN_DESK_EDIT_PASTE + Co&ller + + + MEN_STUDIES_CHOICE + Choisir une étude existante + + + + STD_Application + + INF_DOC_MODIFIED + Le document a été modifié. +Voulez-vous sauvegarder les modifications? + + + INF_DOC_SAVING + Sauvegarde de l'étude en cours + + + INF_DOC_SAVED + L'étude %1 est sauvegardée + + + TOT_DOCK_WINDOWS + Montrer / cacher les fenêtres ancrables et les barres d'outils + + + MEN_DOCK_WINDOWS + Fenêtres et Barres d'outils + + + ABOUT_INFO + Application SUIT Std + + + INF_DOC_SAVING_FAILS + Impossible de sauvegarder le fichier "%1". +Les raisons possibles sont: +- un problème de droit; +- l'espace disque restant est insuffisant; +- erreur de l'application; +Essayez d'utiliser un autre nom de fichier. + + + INF_DOCUMENT_MODIFIED + Le document "%1" a été modifié. +Voulez-vous sauvegarder les changements? + + + CLOSE_STUDY + Fermer l'étude actuelle + + + CLOSE_QUESTION + Voulez-vous sauvegarder l'étude avant de la fermer? + + + REOPEN_STUDY + Réouvrir l'étude + + + REOPEN_QUESTION + Voulez-vous vraiment réouvrir l'étude? +Toutes les modifications introduites après le dernier enregistrement seront perdues. + + + diff --git a/src/SUIT/SUIT_ShortcutMgr.cxx b/src/SUIT/SUIT_ShortcutMgr.cxx new file mode 100644 index 000000000..dd25d567c --- /dev/null +++ b/src/SUIT/SUIT_ShortcutMgr.cxx @@ -0,0 +1,187 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 +// + +#include "SUIT_ShortcutMgr.h" + +#include "SUIT_Session.h" +#include "SUIT_ResourceMgr.h" + +#include + +#include +#include + +SUIT_ShortcutMgr* SUIT_ShortcutMgr::myShortcutMgr = NULL; + +/*! + \brief Constructor +*/ +SUIT_ShortcutMgr::SUIT_ShortcutMgr() +: QObject() +{ + qApp->installEventFilter( this ); +} + +/*! + \brief Destructor +*/ +SUIT_ShortcutMgr::~SUIT_ShortcutMgr() +{ + qApp->removeEventFilter( this ); +} + +/*! + \brief Create new instance of shortcut manager. +*/ +void SUIT_ShortcutMgr::Init() +{ + if( myShortcutMgr==NULL ) + myShortcutMgr = new SUIT_ShortcutMgr(); +} + +/*! + \brief Return shortcut manager. +*/ +SUIT_ShortcutMgr* SUIT_ShortcutMgr::getShortcutMgr() +{ + Init(); + + return myShortcutMgr; +} + +/*! + \brief Custom event filter for qapplication . + + Redefined from QObject::eventFilter(); +*/ +bool SUIT_ShortcutMgr::eventFilter( QObject* o, QEvent* e ) +{ + if ( e->type() == QEvent::ActionAdded ) { + QActionEvent* anActionEvent = (QActionEvent*)e; + if (anActionEvent) { + QtxAction* anAction = qobject_cast( anActionEvent->action() ); + if ( anAction ) + processAction( anAction ); + } + } + + return QObject::eventFilter( o, e ); +} + +/*! + \brief Return key sequence for shortcut action name. + \param actionName name of shortcut action in preferences + \return key sequence defined in preferences or empty sequence +*/ +QKeySequence SUIT_ShortcutMgr::getShortcutByActionName( const QString& actionName ) const +{ + SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr(); + + QString section = actionName.section( resMgr->sectionsToken(), 0, 0 ); + section.prepend( QString("shortcuts") + resMgr->sectionsToken() ); + QString parameter = actionName.section( resMgr->sectionsToken(), 1, 1 ); + + QString shortcutValue; + bool hasValue = resMgr->value( section, parameter, shortcutValue, false ); + + if ( !hasValue ) + return QKeySequence(); + + return QKeySequence::fromString( shortcutValue ); +} + +/*! + \brief Set shortcut to the given action if the shortcut is defined. + \param action action to process + */ +void SUIT_ShortcutMgr::processAction( QtxAction* action ) +{ + QString shortcutActionName = action->shortcutActionName(); + + if ( !shortcutActionName.isEmpty() ) { + // Add action to the actions map + if ( !myShortcutActions.contains( shortcutActionName, action ) ) { + myShortcutActions.insert( shortcutActionName, action ); + connect( action, SIGNAL( destroyed( QObject* ) ), + this, SLOT ( onActionDestroyed( QObject* ) ) ); + } + + QKeySequence keySeq = getShortcutByActionName( shortcutActionName ); + action->setShortcut( keySeq ); + } +} + +/*! + \brief Enable/disable a shortcuts section. + + Enables or disables actions which belong to the given shortcuts section. + Only actions which have an active desktop as a parent widget + are taken into account. + + \param section shorcuts section + \param on if \c true - action will be enabled, otherwise - disabled +*/ +void SUIT_ShortcutMgr::setSectionEnabled( const QString& section, const bool on ) +{ + QMap::ConstIterator it; + for ( it = myShortcutActions.constBegin(); it != myShortcutActions.constEnd(); ++it ) { + QtxAction* action = it.value(); + QString shortcutActionName = action->shortcutActionName(); + QString actionSection = shortcutActionName.section( ":", 0, 0 ); + if ( actionSection == section ) { + // Check if the action parent widget equals to the active desktop + SUIT_Application* app = SUIT_Session::session()->activeApplication(); + if ( !app ) + return; + if ( action->parentWidget() == (QWidget*)app->desktop() ) + action->setEnabled( on ); + } + } +} + +/*! + \brief Update shortcuts from preferences. +*/ +void SUIT_ShortcutMgr::updateShortcuts() +{ + QMap::ConstIterator it; + for ( it = myShortcutActions.constBegin(); it != myShortcutActions.constEnd(); ++it ) { + QtxAction* action = it.value(); + QKeySequence keySeq = getShortcutByActionName( action->shortcutActionName() ); + action->setShortcut( keySeq ); + } +} + +/*! + \brief Called when the corresponding action is destroyed. + + Removes destroyed action from the actions list. + + \param obj action being destroyed +*/ +void SUIT_ShortcutMgr::onActionDestroyed( QObject* obj ) +{ + QtxAction* anAction = (QtxAction*)obj; + + if ( anAction ) + myShortcutActions.remove( anAction->shortcutActionName(), anAction ); +} diff --git a/src/SUIT/SUIT_ShortcutMgr.h b/src/SUIT/SUIT_ShortcutMgr.h new file mode 100644 index 000000000..cbccabaa7 --- /dev/null +++ b/src/SUIT/SUIT_ShortcutMgr.h @@ -0,0 +1,75 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 +// + +#ifndef SUIT_SHORTCUTMGR_H +#define SUIT_SHORTCUTMGR_H + +#include "SUIT.h" + +#include +#include + +class QtxAction; + +class QKeySequence; + +#if defined WIN32 +#pragma warning( disable: 4251 ) +#endif + +/*! + \class SUIT_ShortcutMgr + \brief Class which manages shortcuts customization. +*/ +class SUIT_EXPORT SUIT_ShortcutMgr: public QObject +{ + Q_OBJECT +public: + static void Init(); + static SUIT_ShortcutMgr* getShortcutMgr(); + + void setSectionEnabled( const QString&, const bool = true ); + void updateShortcuts(); + +protected: + SUIT_ShortcutMgr(); + virtual ~SUIT_ShortcutMgr(); + +private slots: + void onActionDestroyed( QObject* ); + +private: + virtual bool eventFilter( QObject* o, QEvent* e ); + + void processAction( QtxAction* ); + QKeySequence getShortcutByActionName( const QString& ) const; + +private: + static SUIT_ShortcutMgr* myShortcutMgr; + QMultiMap myShortcutActions; +}; + +#if defined WIN32 +#pragma warning( default: 4251 ) +#endif + +#endif diff --git a/src/SUIT/resources/SUIT_images.ts b/src/SUIT/resources/SUIT_images.ts new file mode 100644 index 000000000..ff3f7d4fc --- /dev/null +++ b/src/SUIT/resources/SUIT_images.ts @@ -0,0 +1,15 @@ + + + + + @default + + ICON_DATAOBJ_VISIBLE + icon_visibility_on.png + + + ICON_DATAOBJ_INVISIBLE + icon_visibility_off.png + + + diff --git a/src/SUIT/resources/SUIT_msg_fr.ts b/src/SUIT/resources/SUIT_msg_fr.ts new file mode 100755 index 000000000..345b25512 --- /dev/null +++ b/src/SUIT/resources/SUIT_msg_fr.ts @@ -0,0 +1,151 @@ + + + + + @default + + MEN_DESK_WINDOW + &Fenêtre + + + ERR_CANT_DUMP_VIEW + Impossible de sauvegarder le contenu de la vue dans le fichier. + + + TLT_IMAGE_FILES + Fichiers images (*.bmp *.png *.jpg *.jpeg) + + + MEN_DESK_WINDOW_CASCADE + &Cascade + + + PRP_DESK_WINDOW_CASCADE + Superpose les fenêtres + + + ERR_DIR_NOT_EXIST + Le répertoire "%1" n'existe pas ! + + + ERR_FILE_NOT_DIR + "%1" n'est pas un répertoire ! + + + CONTINUE + Continuer + + + CANCEL + Annuler + + + ERR_FILE_NOT_EXIST + Le fichier "%1" n'existe pas ! + + + QUE_DOC_FILEEXISTS + Le fichier %1 existe déjà. +Voulez-vous l'écraser ? + + + PRP_DESK_WINDOW_ACTIVATE + Active la fenêtre + + + ERR_PERMISSION_DENIED + Impossible de sauvegarder le fichier "%1". +Autorisation interdite. + + + ERR_OPEN_PERMISSION_DENIED + Impossible d'ouvrir le fichier "%1". +Autorisation interdite. + + + ERR_DIR_READ_PERMISSION_DENIED + Impossible de lire le répertoire "%1". +Autorisation interdite. + + + ERR_DIR_WRITE_PERMISSION_DENIED + Impossible d'écrire dans le répertoire "%1". +Autorisation interdite. + + + ERR_ERROR + Erreur + + + QUE_FILE_EXISTS + Le fichier %1 existe déjà. +Voulez-vous l'écraser ? + + + WRN_WARNING + Avertissement + + + TLT_DUMP_VIEW + Enregistrer la vue dans le fichier + + + PRP_DESK_WINDOW_TILE + Place les fenêtres en mosaïque + + + MEN_DESK_WINDOW_VTILE + Mosaïque &verticale + + + INF_DIRECTORIES_FILTER + Répertoires + + + PRP_DESK_WINDOW_VTILE + Place les fenêtres en mosaïque verticale + + + MEN_DESK_WINDOW_TILE + &Mosaïque + + + NAME_COLUMN + Nom + + + + SUIT_Study + + OPERATION_LAUNCH + Lancer l'opération + + + PREVIOUS_NOT_FINISHED + L'opération précédente n'est pas aboutie et sera interrompue + + + + SUIT_FileDlg + + LAB_QUICK_PATH + Emplacement : + + + BUT_ADD_PATH + Ajouter un chemin + + + INF_DESK_DOC_OPEN + Ouvrir un fichier + + + INF_DESK_DOC_SAVE + Sauvegarder un fichier + + + ALL_FILES_FILTER + Tous les fichiers (*) + + + diff --git a/src/SUIT/resources/icon_visibility_off.png b/src/SUIT/resources/icon_visibility_off.png new file mode 100644 index 000000000..31c505d82 Binary files /dev/null and b/src/SUIT/resources/icon_visibility_off.png differ diff --git a/src/SUIT/resources/icon_visibility_on.png b/src/SUIT/resources/icon_visibility_on.png new file mode 100644 index 000000000..61ebe4703 Binary files /dev/null and b/src/SUIT/resources/icon_visibility_on.png differ diff --git a/src/SUITApp/SUITApp_init_python.cxx b/src/SUITApp/SUITApp_init_python.cxx new file mode 100644 index 000000000..361513fa1 --- /dev/null +++ b/src/SUITApp/SUITApp_init_python.cxx @@ -0,0 +1,45 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 : Roman NIKOLAEV, Open CASCADE S.A.S. (roman.nikolaev@opencascade.com) +// Date : 22/06/2007 +// +#include "SUITApp_init_python.hxx" + + +PyThreadState* SUIT_PYTHON::_gtstate = NULL; +PyObject *SUIT_PYTHON::salome_shared_modules_module = NULL; +PyInterpreterState* SUIT_PYTHON::_interp = NULL; +bool SUIT_PYTHON::initialized = false; + +void SUIT_PYTHON::init_python(int argc, char **argv) +{ + if (Py_IsInitialized()) + { + return; + } + Py_SetProgramName(argv[0]); + Py_Initialize(); // Initialize the interpreter + PySys_SetArgv(argc, argv); + SUIT_PYTHON::_interp = PyThreadState_Get()->interp; + PyEval_InitThreads(); // Create (and acquire) the interpreter lock + SUIT_PYTHON::_gtstate = PyEval_SaveThread(); // Release global thread state + SUIT_PYTHON::initialized = true; +} + diff --git a/src/SUITApp/SUITApp_init_python.hxx b/src/SUITApp/SUITApp_init_python.hxx new file mode 100644 index 000000000..50855fb9d --- /dev/null +++ b/src/SUITApp/SUITApp_init_python.hxx @@ -0,0 +1,59 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 : Roman NIKOLAEV, Open CASCADE S.A.S. (roman.nikolaev@opencascade.com) +// Date : 22/06/2007 +// +#ifndef _SUITAPP_INIT_PYTHON_ +#define _SUITAPP_INIT_PYTHON_ + +#include + +// rnv: avoid compilation warning on Linux : "_POSIX_C_SOURCE" and "_XOPEN_SOURCE" are redefined +#ifdef _POSIX_C_SOURCE +#undef _POSIX_C_SOURCE +#endif + +#ifdef _XOPEN_SOURCE +#undef _XOPEN_SOURCE +#endif + +#include + +#ifdef WNT +# if defined SUITAPP_EXPORTS || defined SUITApp_EXPORTS +# define SUITAPP_EXPORT __declspec(dllexport) +# else +# define SUITAPP_EXPORT __declspec(dllimport) +# endif +#else +# define SUITAPP_EXPORT +#endif + +struct SUITAPP_EXPORT SUIT_PYTHON +{ + static PyThreadState *_gtstate; + static PyInterpreterState *_interp; + static PyObject *salome_shared_modules_module; + static bool initialized; + static void init_python(int argc, char **argv); + +}; + +#endif // _SUITAPP_INIT_PYTHON_ diff --git a/src/SUITApp/resources/SUITApp_msg_fr.ts b/src/SUITApp/resources/SUITApp_msg_fr.ts new file mode 100755 index 000000000..92f8f53fb --- /dev/null +++ b/src/SUITApp/resources/SUITApp_msg_fr.ts @@ -0,0 +1,19 @@ + + + + + @default + + APP_OK + Ok + + + APP_ERROR + Erreur + + + APP_UNK_EXCEPTION + Exception inconnue + + + diff --git a/src/SUPERVGraph/resources/SUPERVGraph_msg_fr.ts b/src/SUPERVGraph/resources/SUPERVGraph_msg_fr.ts new file mode 100755 index 000000000..27458b761 --- /dev/null +++ b/src/SUPERVGraph/resources/SUPERVGraph_msg_fr.ts @@ -0,0 +1,27 @@ + + + + + @default + + MNU_PAN_VIEW + Déplacement + + + DSC_PAN_VIEW + Déplacement de la vue + + + MNU_RESET_VIEW + Restaurer + + + DSC_RESET_VIEW + Restaurer le point de vue + + + LBL_TOOLBAR_LABEL + Opérations de visualisation + + + diff --git a/src/SVTK/resources/SVTK_msg_fr.ts b/src/SVTK/resources/SVTK_msg_fr.ts new file mode 100755 index 000000000..9ea65e81e --- /dev/null +++ b/src/SVTK/resources/SVTK_msg_fr.ts @@ -0,0 +1,607 @@ + + + + + @default + + DSC_ANTICLOCKWISE_VIEW + Tourner la vue à gauche + + + DSC_CLOCKWISE_VIEW + Tourner la vue à droite + + + MNU_ANTICLOCKWISE_VIEW + Tourner la vue à gauche + + + MNU_CLOCKWISE_VIEW + Tourner la vue à droite + + + MNU_FRONT_VIEW + Avant + + + ERROR + Erreur + + + MNU_DUMP_VIEW + Sauvegarder la scène... + + + DSC_TOP_VIEW + Vue de dessus + + + MNU_PAN_VIEW + Déplacement + + + MNU_TOP_VIEW + Dessus + + + DSC_GLOBALPAN_VIEW + Sélection d'un nouveau centre de la vue + + + DSC_ROTATE_VIEW + Tourner le point de vue autour du centre de la scène + + + MNU_ZOOM_VIEW + Zoom + + + DSC_PAN_VIEW + Déplacer la vue + + + DSC_LEFT_VIEW + Vue de gauche + + + DSC_FITALL + Redimensionner la scène pour montrer tous les objets + + + MNU_FITALL + Tout afficher + + + MNU_ROTATE_VIEW + Rotation + + + DSC_SHOW_TRIHEDRON + Montrer/cacher le trièdre + + + DSC_FRONT_VIEW + Vue de face + + + MNU_GLOBALPAN_VIEW + Panoramique global + + + INF_APP_DUMP_VIEW + Sauvegarder la vue + + + MNU_BACK_VIEW + Arrière + + + MNU_SHOW_TRIHEDRON + Afficher/cacher le trièdre + + + DSC_CHANGINGROTATIONPOINT_VIEW + Changer le point autour duquel la scène est tournée + + + MNU_BOTTOM_VIEW + Dessous + + + MNU_RESET_VIEW + Restaurer + + + MNU_LEFT_VIEW + Gauche + + + DSC_RIGHT_VIEW + Vue de droite + + + MNU_CHANGINGROTATIONPOINT_VIEW + Changer le point de rotation + + + DSC_FITRECT + Redimensionner la scène pour ne montrer que sa partie choisie par l'encadré + + + MNU_FITRECT + Afficher la zone + + + DSC_BOTTOM_VIEW + Vue de dessous + + + DSC_DUMP_VIEW + Sauvegarder la scène actuelle dans un fichier image + + + DSC_ZOOM_VIEW + Zoomer la vue + + + VTK_IMAGE_FILES + Fichiers images (*.bmp *.png *.jpg *.jpeg) + + + DSC_RESET_VIEW + Restaurer le point de vue + + + ERR_DOC_CANT_SAVE_FILE + Impossible de sauvegarder le fichier + + + MNU_RIGHT_VIEW + Droite + + + LBL_TOOLBAR_LABEL + Opérations de visualisation + + + DSC_BACK_VIEW + Vue arrière + + + SVTK_IMAGE_FILES + Fichiers images (*.bmp *.png *.jpg *.jpeg *.pdf *.ps *.eps) + + + MNU_VIEWPARAMETERS_VIEW + Changer les paramètres de visualisation + + + DSC_VIEWPARAMETERS_VIEW + Changer les paramètres de la vue + + + MNU_SYNCHRONIZE_VIEW + Synchroniser + + + DSC_SYNCHRONIZE_VIEW + Synchroniser la vue + + + MNU_SYNC_NO_VIEW + [ Pas de vue appropriée ] + + + MNU_SVTK_PARALLEL_MODE + Mode orthogonal + + + DSC_SVTK_PARALLEL_MODE + Choisir la projection orthogonale + + + MNU_SVTK_PERSPECTIVE_MODE + Mode perspective + + + DSC_SVTK_PERSPECTIVE_MODE + Choisir la projection en perspective + + + DSC_SVTK_STYLE_SWITCH + Changer le style d'intéraction + + + MNU_SVTK_STYLE_SWITCH + Changer le style d'interaction + + + DSC_SVTK_ZOOMING_STYLE_SWITCH + Changer le style de zoom + + + MNU_SVTK_ZOOMING_STYLE_SWITCH + Changer le style de zoom + + + DSC_SVTK_DYNAMIC_PRESLECTION_SWITCH + Pré-sélection dynamique + + + MNU_SVTK_DYNAMIC_PRESLECTION_SWITCH + Pré-sélection dynamique + + + + SVTK_FontWidget + + ARIAL + Arial + + + TIMES + Times + + + COURIER + Courier + + + + SVTK_ViewWindow + + DSC_SVTK_UPDATE_RATE + Fréquence de mise à jour + + + DSC_SVTK_SCALING + Mise à l'échelle + + + MNU_SVTK_SCALING + Mise à l'échelle + + + MNU_SVTK_GRADUATED_AXES + Axes gradués + + + DSC_SVTK_GRADUATED_AXES + Axes gradués + + + MNU_SVTK_UPDATE_RATE + Fréquence de mise à jour + + + DSC_SVTK_RECORDING_START + Commencer l'enregistrement + + + MNU_SVTK_RECORDING_START + Commencer l'enregistrement + + + DSC_SVTK_RECORDING_PLAY + Commencer l'enregistrement + + + MNU_SVTK_RECORDING_PLAY + Commencer l'enregistrement + + + DSC_SVTK_RECORDING_PAUSE + Mettre en pause l'enregistrement + + + MNU_SVTK_RECORDING_PAUSE + Mettre en pause l'enregistrement + + + DSC_SVTK_RECORDING_STOP + Arrêter l'enregistrement + + + MNU_SVTK_RECORDING_STOP + Arrêter l'enregistrement + + + LBL_TOOLBAR_RECORD_LABEL + Opérations d'enregistrement + + + MSG_NO_AVI_MAKER + L'outil jpeg2yuv, requis pour enregistrer les fichiers AVI, n'est pas disponible. +Veuillez consulter la documentation. + + + + SVTK_NonIsometricDlg + + LBL_X + X: + + + LBL_Y + Y: + + + LBL_Z + Z: + + + MEN_SCALING + Echelle + + + DLG_TITLE + Mise à l'échelle + + + + SVTK_RecorderDlg + + ALL_DISLPAYED_FRAMES + Enregistrer toutes les images affichées + + + CLOSE + Fermer + + + DLG_RECORDER_TITLE + Magnéto + + + FILE_NAME + Sauvegarder dans le fichier : + + + FLT_ALL_FILES + Tous les fichiers (*.*) + + + FLT_AVI_FILES + Fichiers AVI (*.avi) + + + FPS + FPS : + + + HELP + Aide + + + PROGRESSIVE + Progressive + + + QUALITY + Qualité : + + + RECORDING_MODE + Mode : + + + SETTINGS + Réglages + + + SKIPPED_FRAMES + Enregistrer à FPS donné + + + START + Commencer + + + + SVTK_SetRotationPointDlg + + LBL_X + X: + + + LBL_Y + Y: + + + LBL_Z + Z: + + + LBL_CENTER_OF_BOUNDING_BOX + Centre de la boîte englobante + + + RBUTTONGROUP_TITLE + Le type du point de rotation + + + USE_BBCENTER + Utiliser le centre de la boîte englobante + + + LBL_ORIGIN + Origine du système de coordonnées + + + LBL_SELECTED_POINT + Point sélectionné + + + LBL_TOORIGIN + Réinitialiser à l'origine + + + LBL_SELECTPOINT + Choisir un point dans la vue + + + DLG_TITLE + Définir le point de rotation + + + + SVTK_ViewParameterDlg + + LBL_X + X : + + + LBL_Y + Y : + + + LBL_Z + Z : + + + LBL_DX + DX : + + + LBL_DY + DY : + + + LBL_DZ + DZ : + + + PROJECTION_MODE + Mode de projection + + + ORTHOGONAL_MODE + Orthogonal + + + PERSPECTIVE_MODE + Perspective + + + USE_BBCENTER + Utiliser le centre de la boîte englobante + + + LBL_TOBBCENTER + Définir au centre de la boîte englobante + + + LBL_TOORIGIN + Initialiser à l'origine + + + LBL_SELECTPOINT + Choisir un point de la vue + + + FOCAL_POINT + Point focal + + + CAMERA_POSITION + Position de la caméra + + + WORLD_COORDINATES + Coordonnées obsolues + + + FOCAL_RELATIVE + Relatif au point focal + + + PROJECTION_DIRECTION + Direction de la projection : + + + FOCAL_DISTANCE + Distance focale : + + + VIEW_UP_DIRECTION + Direction pour la vue verticale : + + + ZOOMING + Zoom + + + LBL_SCALE + Echelle + + + LBL_VIEW_ANGLE + Angle de visualisation + + + DLG_TITLE + Paramètres de visualisation + + + + SVTK_UpdateRateDlg + + INFORMATION_FRAME_TITLE + Informations + + + STILL + Fréquence réduite de mise à jour , FPS + + + INPUT_FRAME_TITLE + Activer + + + NUMBER_CELLS + Nombre de cellules, - + + + DESIRED + Fréquence de mise à jour requise, FPS + + + CURRENT_FPS + Fréquence actuelle de mise à jour , FPS + + + DLG_TITLE + Fréquence de mise à jour + + + + SVTK_ViewManager + + VTK_VIEW_TITLE + Scène VTK:%1 - visualiseur:%2 + + + + SVTK_Viewer + + MEN_DUMP_VIEW + Sauvegarder la vue... + + + MEN_SHOW_TOOLBAR + Montrer la barre d'outils + + + MEN_CHANGE_BACKGROUND + Changer l'arrière-plan... + + + GT_VERTICALGRADIENT + Gradient vertical + + + BG_IMAGE_FILES + Fichiers images (*.png *.jpg *.jpeg *.bmp *.tif *.tiff *.mhd *.mha) + + + diff --git a/src/SVTK/resources/vtk_view_highlight.png b/src/SVTK/resources/vtk_view_highlight.png new file mode 100755 index 000000000..0aa1d6f9c Binary files /dev/null and b/src/SVTK/resources/vtk_view_highlight.png differ diff --git a/src/SVTK/resources/vtk_view_sync.png b/src/SVTK/resources/vtk_view_sync.png new file mode 100755 index 000000000..32b95228a Binary files /dev/null and b/src/SVTK/resources/vtk_view_sync.png differ diff --git a/src/SVTK/resources/vtk_view_zooming_style_switch.png b/src/SVTK/resources/vtk_view_zooming_style_switch.png new file mode 100755 index 000000000..8f3a48670 Binary files /dev/null and b/src/SVTK/resources/vtk_view_zooming_style_switch.png differ diff --git a/src/SVTK/vtkPVAxesActor.cxx b/src/SVTK/vtkPVAxesActor.cxx new file mode 100644 index 000000000..25f471f24 --- /dev/null +++ b/src/SVTK/vtkPVAxesActor.cxx @@ -0,0 +1,812 @@ +/*========================================================================= + + Program: ParaView + Module: $RCSfile$ + + Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc. + All rights reserved. + + ParaView is a free software; you can redistribute it and/or modify it + under the terms of the ParaView license version 1.2. + + See License_v1.2.txt for the full ParaView license. + A copy of this license can be obtained by contacting + Kitware Inc. + 28 Corporate Drive + Clifton Park, NY 12065 + USA + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=========================================================================*/ +#include "vtkPVAxesActor.h" +#include "vtkObject.h" +#include "vtkObjectFactory.h" + +#include "vtkActor.h" +#include "vtkPropCollection.h" +#include "vtkProperty.h" +#include "vtkRenderWindow.h" +#include "vtkTransform.h" +#include "vtkCylinderSource.h" +#include "vtkPolyDataMapper.h" +#include "vtkLineSource.h" +#include "vtkPolyData.h" +#include "vtkConeSource.h" +#include "vtkSphereSource.h" +#include "vtkVectorText.h" +#include "vtkFollower.h" +#include "vtkRenderer.h" + +#include + +vtkCxxRevisionMacro(vtkPVAxesActor, "$Revision$"); +vtkStandardNewMacro(vtkPVAxesActor); + +vtkCxxSetObjectMacro( vtkPVAxesActor, UserDefinedTip, vtkPolyData ); +vtkCxxSetObjectMacro( vtkPVAxesActor, UserDefinedShaft, vtkPolyData ); + +//----------------------------------------------------------------------------- +vtkPVAxesActor::vtkPVAxesActor() +{ + this->XAxisLabelText = NULL; + this->YAxisLabelText = NULL; + this->ZAxisLabelText = NULL; + + this->SetXAxisLabelText("X"); + this->SetYAxisLabelText("Y"); + this->SetZAxisLabelText("Z"); + + //colors chosen to match the output of vtkAxes.cxx's LUT. + this->XAxisShaft = vtkActor::New(); + this->XAxisShaft->GetProperty()->SetColor(1, 0, 0); + this->YAxisShaft = vtkActor::New(); + this->YAxisShaft->GetProperty()->SetColor(1, 1, 0); + this->ZAxisShaft = vtkActor::New(); + this->ZAxisShaft->GetProperty()->SetColor(0, 1, 0); + + this->XAxisTip = vtkActor::New(); + this->XAxisTip->GetProperty()->SetColor(1, 0, 0); + this->YAxisTip = vtkActor::New(); + this->YAxisTip->GetProperty()->SetColor(1, 1, 0); + this->ZAxisTip = vtkActor::New(); + this->ZAxisTip->GetProperty()->SetColor(0, 1, 0); + + this->CylinderSource = vtkCylinderSource::New(); + this->CylinderSource->SetHeight(1.0); + + this->LineSource = vtkLineSource::New(); + this->LineSource->SetPoint1( 0.0, 0.0, 0.0 ); + this->LineSource->SetPoint2( 0.0, 1.0, 0.0 ); + + this->ConeSource = vtkConeSource::New(); + this->ConeSource->SetDirection( 0, 1, 0 ); + this->ConeSource->SetHeight( 1.0 ); + + this->SphereSource = vtkSphereSource::New(); + + vtkPolyDataMapper *shaftMapper = vtkPolyDataMapper::New(); + + this->XAxisShaft->SetMapper( shaftMapper ); + this->YAxisShaft->SetMapper( shaftMapper ); + this->ZAxisShaft->SetMapper( shaftMapper ); + + shaftMapper->Delete(); + + vtkPolyDataMapper *tipMapper = vtkPolyDataMapper::New(); + + this->XAxisTip->SetMapper( tipMapper ); + this->YAxisTip->SetMapper( tipMapper ); + this->ZAxisTip->SetMapper( tipMapper ); + + tipMapper->Delete(); + + this->TotalLength[0] = 1.0; + this->TotalLength[1] = 1.0; + this->TotalLength[2] = 1.0; + + this->NormalizedShaftLength[0] = 0.8; + this->NormalizedShaftLength[1] = 0.8; + this->NormalizedShaftLength[2] = 0.8; + + this->NormalizedTipLength[0] = 0.2; + this->NormalizedTipLength[1] = 0.2; + this->NormalizedTipLength[2] = 0.2; + + this->ConeResolution = 16; + this->SphereResolution = 16; + this->CylinderResolution = 16; + + this->ConeRadius = 0.4; + this->SphereRadius = 0.5; + this->CylinderRadius = 0.05; + + this->XAxisLabelPosition = 1; + this->YAxisLabelPosition = 1; + this->ZAxisLabelPosition = 1; + + this->ShaftType = vtkPVAxesActor::LINE_SHAFT; + this->TipType = vtkPVAxesActor::CONE_TIP; + + this->UserDefinedTip = NULL; + this->UserDefinedShaft = NULL; + + this->XAxisVectorText = vtkVectorText::New(); + this->YAxisVectorText = vtkVectorText::New(); + this->ZAxisVectorText = vtkVectorText::New(); + + this->XAxisLabel = vtkFollower::New(); + this->YAxisLabel = vtkFollower::New(); + this->ZAxisLabel = vtkFollower::New(); + + vtkPolyDataMapper *xmapper = vtkPolyDataMapper::New(); + vtkPolyDataMapper *ymapper = vtkPolyDataMapper::New(); + vtkPolyDataMapper *zmapper = vtkPolyDataMapper::New(); + + xmapper->SetInput( this->XAxisVectorText->GetOutput() ); + ymapper->SetInput( this->YAxisVectorText->GetOutput() ); + zmapper->SetInput( this->ZAxisVectorText->GetOutput() ); + + this->XAxisLabel->SetMapper( xmapper ); + this->YAxisLabel->SetMapper( ymapper ); + this->ZAxisLabel->SetMapper( zmapper ); + + xmapper->Delete(); + ymapper->Delete(); + zmapper->Delete(); + + this->UpdateProps(); +} + +//----------------------------------------------------------------------------- +vtkPVAxesActor::~vtkPVAxesActor() +{ + this->CylinderSource->Delete(); + this->LineSource->Delete(); + this->ConeSource->Delete(); + this->SphereSource->Delete(); + + this->XAxisShaft->Delete(); + this->YAxisShaft->Delete(); + this->ZAxisShaft->Delete(); + + this->XAxisTip->Delete(); + this->YAxisTip->Delete(); + this->ZAxisTip->Delete(); + + this->SetUserDefinedTip( NULL ); + this->SetUserDefinedShaft( NULL ); + + this->SetXAxisLabelText( NULL ); + this->SetYAxisLabelText( NULL ); + this->SetZAxisLabelText( NULL ); + + this->XAxisVectorText->Delete(); + this->YAxisVectorText->Delete(); + this->ZAxisVectorText->Delete(); + + this->XAxisLabel->Delete(); + this->YAxisLabel->Delete(); + this->ZAxisLabel->Delete(); +} + +//----------------------------------------------------------------------------- +// Shallow copy of an actor. +void vtkPVAxesActor::ShallowCopy(vtkProp *prop) +{ + vtkPVAxesActor *a = vtkPVAxesActor::SafeDownCast(prop); + if ( a != NULL ) + { + } + + // Now do superclass + this->vtkProp3D::ShallowCopy(prop); +} + +//----------------------------------------------------------------------------- +void vtkPVAxesActor::GetActors(vtkPropCollection *ac) +{ + ac->AddItem(this->XAxisShaft); + ac->AddItem(this->YAxisShaft); + ac->AddItem(this->ZAxisShaft); + ac->AddItem(this->XAxisTip); + ac->AddItem(this->YAxisTip); + ac->AddItem(this->ZAxisTip); + ac->AddItem(this->XAxisLabel); + ac->AddItem(this->YAxisLabel); + ac->AddItem(this->ZAxisLabel); + +} + +//----------------------------------------------------------------------------- +int vtkPVAxesActor::RenderOpaqueGeometry(vtkViewport *vp) +{ + int renderedSomething = 0; + + vtkRenderer *ren = vtkRenderer::SafeDownCast( vp ); + + this->UpdateProps(); + + this->XAxisLabel->SetCamera( ren->GetActiveCamera() ); + this->YAxisLabel->SetCamera( ren->GetActiveCamera() ); + this->ZAxisLabel->SetCamera( ren->GetActiveCamera() ); + + this->XAxisShaft->RenderOpaqueGeometry(vp); + this->YAxisShaft->RenderOpaqueGeometry(vp); + this->ZAxisShaft->RenderOpaqueGeometry(vp); + + this->XAxisTip->RenderOpaqueGeometry(vp); + this->YAxisTip->RenderOpaqueGeometry(vp); + this->ZAxisTip->RenderOpaqueGeometry(vp); + + this->XAxisLabel->RenderOpaqueGeometry(vp); + this->YAxisLabel->RenderOpaqueGeometry(vp); + this->ZAxisLabel->RenderOpaqueGeometry(vp); + + return renderedSomething; +} + +//----------------------------------------------------------------------------- +#if (VTK_MINOR_VERSION>=2) +// porting to VTK 5.0.x +int vtkPVAxesActor::RenderTranslucentPolygonalGeometry(vtkViewport *vp) +{ + int renderedSomething=0; + + this->UpdateProps(); + + renderedSomething += this->XAxisShaft->RenderTranslucentPolygonalGeometry(vp); + renderedSomething += this->YAxisShaft->RenderTranslucentPolygonalGeometry(vp); + renderedSomething += this->ZAxisShaft->RenderTranslucentPolygonalGeometry(vp); + + renderedSomething += this->XAxisTip->RenderTranslucentPolygonalGeometry(vp); + renderedSomething += this->YAxisTip->RenderTranslucentPolygonalGeometry(vp); + renderedSomething += this->ZAxisTip->RenderTranslucentPolygonalGeometry(vp); + + renderedSomething += this->XAxisLabel->RenderTranslucentPolygonalGeometry(vp); + renderedSomething += this->YAxisLabel->RenderTranslucentPolygonalGeometry(vp); + renderedSomething += this->ZAxisLabel->RenderTranslucentPolygonalGeometry(vp); + + return renderedSomething; +} + +//----------------------------------------------------------------------------- +// porting to VTK 5.0.x +int vtkPVAxesActor::HasTranslucentPolygonalGeometry() +{ + int result = 0; + + this->UpdateProps(); + + result |= this->XAxisShaft->HasTranslucentPolygonalGeometry(); + result |= this->YAxisShaft->HasTranslucentPolygonalGeometry(); + result |= this->ZAxisShaft->HasTranslucentPolygonalGeometry(); + + result |= this->XAxisTip->HasTranslucentPolygonalGeometry(); + result |= this->YAxisTip->HasTranslucentPolygonalGeometry(); + result |= this->ZAxisTip->HasTranslucentPolygonalGeometry(); + + result |= this->XAxisLabel->HasTranslucentPolygonalGeometry(); + result |= this->YAxisLabel->HasTranslucentPolygonalGeometry(); + result |= this->ZAxisLabel->HasTranslucentPolygonalGeometry(); + + return result; +} + +#else +//----------------------------------------------------------------------------- +// porting to VTK 5.0.x +int vtkPVAxesActor::RenderTranslucentGeometry(vtkViewport *vp) +{ + int renderedSomething=0; + + this->UpdateProps(); + + renderedSomething += this->XAxisShaft->RenderTranslucentGeometry(vp); + renderedSomething += this->YAxisShaft->RenderTranslucentGeometry(vp); + renderedSomething += this->ZAxisShaft->RenderTranslucentGeometry(vp); + + renderedSomething += this->XAxisTip->RenderTranslucentGeometry(vp); + renderedSomething += this->YAxisTip->RenderTranslucentGeometry(vp); + renderedSomething += this->ZAxisTip->RenderTranslucentGeometry(vp); + + renderedSomething += this->XAxisLabel->RenderTranslucentGeometry(vp); + renderedSomething += this->YAxisLabel->RenderTranslucentGeometry(vp); + renderedSomething += this->ZAxisLabel->RenderTranslucentGeometry(vp); + + return renderedSomething; +} +#endif + +//----------------------------------------------------------------------------- +void vtkPVAxesActor::ReleaseGraphicsResources(vtkWindow *win) +{ + this->XAxisShaft->ReleaseGraphicsResources( win ); + this->YAxisShaft->ReleaseGraphicsResources( win ); + this->ZAxisShaft->ReleaseGraphicsResources( win ); + + this->XAxisTip->ReleaseGraphicsResources( win ); + this->YAxisTip->ReleaseGraphicsResources( win ); + this->ZAxisTip->ReleaseGraphicsResources( win ); + + this->XAxisLabel->ReleaseGraphicsResources( win ); + this->YAxisLabel->ReleaseGraphicsResources( win ); + this->ZAxisLabel->ReleaseGraphicsResources( win ); +} + +//----------------------------------------------------------------------------- +void vtkPVAxesActor::GetBounds(double bounds[6]) +{ + double *bds = this->GetBounds(); + bounds[0] = bds[0]; + bounds[1] = bds[1]; + bounds[2] = bds[2]; + bounds[3] = bds[3]; + bounds[4] = bds[4]; + bounds[5] = bds[5]; +} + +//----------------------------------------------------------------------------- +// Get the bounds for this Actor as (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax). +double *vtkPVAxesActor::GetBounds() +{ + double bounds[6]; + int i; + + this->XAxisShaft->GetBounds(this->Bounds); + + this->YAxisShaft->GetBounds(bounds); + for (i=0; i<3; i++) + { + this->Bounds[2*i+1] = + (bounds[2*i+1]>this->Bounds[2*i+1])?(bounds[2*i+1]):(this->Bounds[2*i+1]); + } + + this->ZAxisShaft->GetBounds(bounds); + for (i=0; i<3; i++) + { + this->Bounds[2*i+1] = + (bounds[2*i+1]>this->Bounds[2*i+1])?(bounds[2*i+1]):(this->Bounds[2*i+1]); + } + + this->XAxisTip->GetBounds(bounds); + for (i=0; i<3; i++) + { + this->Bounds[2*i+1] = + (bounds[2*i+1]>this->Bounds[2*i+1])?(bounds[2*i+1]):(this->Bounds[2*i+1]); + } + + this->YAxisTip->GetBounds(bounds); + for (i=0; i<3; i++) + { + this->Bounds[2*i+1] = + (bounds[2*i+1]>this->Bounds[2*i+1])?(bounds[2*i+1]):(this->Bounds[2*i+1]); + } + + this->ZAxisTip->GetBounds(bounds); + for (i=0; i<3; i++) + { + this->Bounds[2*i+1] = + (bounds[2*i+1]>this->Bounds[2*i+1])?(bounds[2*i+1]):(this->Bounds[2*i+1]); + } + + double dbounds[6]; + (vtkPolyDataMapper::SafeDownCast(this->YAxisShaft->GetMapper()))-> + GetInput()->GetBounds( dbounds ); + + for (i=0; i<3; i++) + { + this->Bounds[2*i+1] = + (dbounds[2*i+1]>this->Bounds[2*i+1])?(dbounds[2*i+1]):(this->Bounds[2*i+1]); + } + + // We want this actor to rotate / re-center about the origin, so give it + // the bounds it would have if the axes were symmetrical. + for (i = 0; i < 3; i++) + { + this->Bounds[2*i] = -this->Bounds[2*i+1]; + } + + return this->Bounds; +} + +//----------------------------------------------------------------------------- +unsigned long int vtkPVAxesActor::GetMTime() +{ + unsigned long mTime=this->Superclass::GetMTime(); + + + return mTime; +} + +//----------------------------------------------------------------------------- +unsigned long int vtkPVAxesActor::GetRedrawMTime() +{ + unsigned long mTime=this->GetMTime(); + + return mTime; +} + +//----------------------------------------------------------------------------- +vtkProperty *vtkPVAxesActor::GetXAxisTipProperty() +{ + return this->XAxisTip->GetProperty(); +} + +//----------------------------------------------------------------------------- +vtkProperty *vtkPVAxesActor::GetYAxisTipProperty() +{ + return this->YAxisTip->GetProperty(); +} + +//----------------------------------------------------------------------------- +vtkProperty *vtkPVAxesActor::GetZAxisTipProperty() +{ + return this->ZAxisTip->GetProperty(); +} + +//----------------------------------------------------------------------------- +vtkProperty *vtkPVAxesActor::GetXAxisShaftProperty() +{ + return this->XAxisShaft->GetProperty(); +} + +//----------------------------------------------------------------------------- +vtkProperty *vtkPVAxesActor::GetYAxisShaftProperty() +{ + return this->YAxisShaft->GetProperty(); +} + +//----------------------------------------------------------------------------- +vtkProperty *vtkPVAxesActor::GetZAxisShaftProperty() +{ + return this->ZAxisShaft->GetProperty(); +} + +//----------------------------------------------------------------------------- +vtkProperty *vtkPVAxesActor::GetXAxisLabelProperty() +{ + return this->XAxisLabel->GetProperty(); +} + +//----------------------------------------------------------------------------- +vtkProperty *vtkPVAxesActor::GetYAxisLabelProperty() +{ + return this->YAxisLabel->GetProperty(); +} + +//----------------------------------------------------------------------------- +vtkProperty *vtkPVAxesActor::GetZAxisLabelProperty() +{ + return this->ZAxisLabel->GetProperty(); +} + +//----------------------------------------------------------------------------- +void vtkPVAxesActor::SetTotalLength( float x, float y, float z ) +{ + if ( this->TotalLength[0] != x || + this->TotalLength[1] != y || + this->TotalLength[2] != z ) + { + this->TotalLength[0] = x; + this->TotalLength[1] = y; + this->TotalLength[2] = z; + + this->Modified(); + + this->UpdateProps(); + } +} + +//----------------------------------------------------------------------------- +void vtkPVAxesActor::SetNormalizedShaftLength( float x, float y, float z ) +{ + if ( this->NormalizedShaftLength[0] != x || + this->NormalizedShaftLength[1] != y || + this->NormalizedShaftLength[2] != z ) + { + this->NormalizedShaftLength[0] = x; + this->NormalizedShaftLength[1] = y; + this->NormalizedShaftLength[2] = z; + + this->Modified(); + + this->UpdateProps(); + } +} + +//----------------------------------------------------------------------------- +void vtkPVAxesActor::SetNormalizedTipLength( float x, float y, float z ) +{ + if ( this->NormalizedTipLength[0] != x || + this->NormalizedTipLength[1] != y || + this->NormalizedTipLength[2] != z ) + { + this->NormalizedTipLength[0] = x; + this->NormalizedTipLength[1] = y; + this->NormalizedTipLength[2] = z; + + this->Modified(); + + this->UpdateProps(); + } +} + +//----------------------------------------------------------------------------- +void vtkPVAxesActor::SetShaftType( int type ) +{ + if ( this->ShaftType != type ) + { + this->ShaftType = type; + + this->Modified(); + + this->UpdateProps(); + } +} + +//----------------------------------------------------------------------------- +void vtkPVAxesActor::SetTipType( int type ) +{ + if ( this->TipType != type ) + { + this->TipType = type; + + this->Modified(); + + this->UpdateProps(); + } +} + +//----------------------------------------------------------------------------- +void vtkPVAxesActor::UpdateProps() +{ + this->CylinderSource->SetRadius(this->CylinderRadius); + this->CylinderSource->SetResolution(this->CylinderResolution); + + + this->ConeSource->SetResolution(this->ConeResolution); + this->ConeSource->SetRadius(this->ConeRadius); + + this->SphereSource->SetThetaResolution( this->SphereResolution ); + this->SphereSource->SetPhiResolution( this->SphereResolution ); + this->SphereSource->SetRadius(this->SphereRadius); + + switch ( this->ShaftType ) + { + case vtkPVAxesActor::CYLINDER_SHAFT: + (vtkPolyDataMapper::SafeDownCast(this->XAxisShaft->GetMapper()))-> + SetInput( this->CylinderSource->GetOutput() ); + break; + case vtkPVAxesActor::LINE_SHAFT: + (vtkPolyDataMapper::SafeDownCast(this->XAxisShaft->GetMapper()))-> + SetInput( this->LineSource->GetOutput() ); + break; + case vtkPVAxesActor::USER_DEFINED_SHAFT: + (vtkPolyDataMapper::SafeDownCast(this->XAxisShaft->GetMapper()))-> + SetInput( this->UserDefinedShaft ); + } + + switch ( this->TipType ) + { + case vtkPVAxesActor::CONE_TIP: + (vtkPolyDataMapper::SafeDownCast(this->XAxisTip->GetMapper()))-> + SetInput( this->ConeSource->GetOutput() ); + break; + case vtkPVAxesActor::SPHERE_TIP: + (vtkPolyDataMapper::SafeDownCast(this->XAxisTip->GetMapper()))-> + SetInput( this->SphereSource->GetOutput() ); + break; + case vtkPVAxesActor::USER_DEFINED_TIP: + (vtkPolyDataMapper::SafeDownCast(this->XAxisTip->GetMapper()))-> + SetInput( this->UserDefinedTip ); + } + + (vtkPolyDataMapper::SafeDownCast(this->XAxisTip->GetMapper()))-> + GetInput()->Update(); + (vtkPolyDataMapper::SafeDownCast(this->XAxisShaft->GetMapper()))-> + GetInput()->Update(); + + + + float scale[3]; + double bounds[6]; + + (vtkPolyDataMapper::SafeDownCast(this->XAxisShaft->GetMapper()))-> + GetInput()->GetBounds( bounds ); + + int i; + for ( i = 0; i < 3; i++ ) + { + scale[i] = + this->NormalizedShaftLength[i]*this->TotalLength[i] / + (bounds[3] - bounds[2]); + } + + vtkTransform *xTransform = vtkTransform::New(); + vtkTransform *yTransform = vtkTransform::New(); + vtkTransform *zTransform = vtkTransform::New(); + + xTransform->RotateZ( -90 ); + zTransform->RotateX( 90 ); + + xTransform->Scale( scale[0], scale[0], scale[0] ); + yTransform->Scale( scale[1], scale[1], scale[1] ); + zTransform->Scale( scale[2], scale[2], scale[2] ); + + xTransform->Translate( -(bounds[0]+bounds[1])/2, + -bounds[2], + -(bounds[4]+bounds[5])/2 ); + yTransform->Translate( -(bounds[0]+bounds[1])/2, + -bounds[2], + -(bounds[4]+bounds[5])/2 ); + zTransform->Translate( -(bounds[0]+bounds[1])/2, + -bounds[2], + -(bounds[4]+bounds[5])/2 ); + + + + this->XAxisShaft->SetUserTransform( xTransform ); + this->YAxisShaft->SetUserTransform( yTransform ); + this->ZAxisShaft->SetUserTransform( zTransform ); + + xTransform->Delete(); + yTransform->Delete(); + zTransform->Delete(); + + (vtkPolyDataMapper::SafeDownCast(this->XAxisTip->GetMapper()))-> + GetInput()->GetBounds( bounds ); + + xTransform = vtkTransform::New(); + yTransform = vtkTransform::New(); + zTransform = vtkTransform::New(); + + xTransform->RotateZ( -90 ); + zTransform->RotateX( 90 ); + + xTransform->Scale( this->TotalLength[0], this->TotalLength[0], this->TotalLength[0] ); + yTransform->Scale( this->TotalLength[1], this->TotalLength[1], this->TotalLength[1] ); + zTransform->Scale( this->TotalLength[2], this->TotalLength[2], this->TotalLength[2] ); + + xTransform->Translate( 0, (1.0 - this->NormalizedTipLength[0]), 0 ); + yTransform->Translate( 0, (1.0 - this->NormalizedTipLength[1]), 0 ); + zTransform->Translate( 0, (1.0 - this->NormalizedTipLength[2]), 0 ); + + xTransform->Scale( this->NormalizedTipLength[0], + this->NormalizedTipLength[0], + this->NormalizedTipLength[0] ); + + yTransform->Scale( this->NormalizedTipLength[1], + this->NormalizedTipLength[1], + this->NormalizedTipLength[1] ); + + zTransform->Scale( this->NormalizedTipLength[2], + this->NormalizedTipLength[2], + this->NormalizedTipLength[2] ); + + xTransform->Translate( -(bounds[0]+bounds[1])/2, + -bounds[2], + -(bounds[4]+bounds[5])/2 ); + yTransform->Translate( -(bounds[0]+bounds[1])/2, + -bounds[2], + -(bounds[4]+bounds[5])/2 ); + zTransform->Translate( -(bounds[0]+bounds[1])/2, + -bounds[2], + -(bounds[4]+bounds[5])/2 ); + + + this->XAxisTip->SetUserTransform( xTransform ); + this->YAxisTip->SetUserTransform( yTransform ); + this->ZAxisTip->SetUserTransform( zTransform ); + + xTransform->Delete(); + yTransform->Delete(); + zTransform->Delete(); + + this->XAxisVectorText->SetText( this->XAxisLabelText ); + this->YAxisVectorText->SetText( this->YAxisLabelText ); + this->ZAxisVectorText->SetText( this->ZAxisLabelText ); + + + float avgScale = + (this->TotalLength[0] + this->TotalLength[1] + this->TotalLength[2])/15; + + this->XAxisShaft->GetBounds(bounds); + this->XAxisLabel->SetScale( avgScale, avgScale, avgScale ); + this->XAxisLabel->SetPosition( bounds[0] + this->XAxisLabelPosition * + (bounds[1]-bounds[0]), + bounds[2] - (bounds[3]-bounds[2])*2.0, + bounds[5] + (bounds[5]-bounds[4])/2.0 ); + + this->YAxisShaft->GetBounds(bounds); + this->YAxisLabel->SetScale( avgScale, avgScale, avgScale ); + this->YAxisLabel->SetPosition( (bounds[0]+bounds[1])/2, + bounds[2] + this->YAxisLabelPosition * + (bounds[3]-bounds[2]), + bounds[5] + (bounds[5]-bounds[4])/2.0 ); + + this->ZAxisShaft->GetBounds(bounds); + this->ZAxisLabel->SetScale( avgScale, avgScale, avgScale ); + this->ZAxisLabel->SetPosition( bounds[0], + bounds[2] - (bounds[3]-bounds[2])*2.0, + bounds[4] + this->ZAxisLabelPosition * + (bounds[5]-bounds[4]) ); +} + +//----------------------------------------------------------------------------- +void vtkPVAxesActor::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os,indent); + + os << indent << "UserDefinedShaft: "; + if (this->UserDefinedShaft) + { + os << this->UserDefinedShaft << endl; + } + else + { + os << "(none)" << endl; + } + + os << indent << "UserDefinedTip: "; + if (this->UserDefinedTip) + { + os << this->UserDefinedTip << endl; + } + else + { + os << "(none)" << endl; + } + + os << indent << "XAxisLabelText: " << (this->XAxisLabelText ? + this->XAxisLabelText : "(none)") + << endl; + os << indent << "YAxisLabelText: " << (this->YAxisLabelText ? + this->YAxisLabelText : "(none)") + << endl; + os << indent << "ZAxisLabelText: " << (this->ZAxisLabelText ? + this->ZAxisLabelText : "(none)") + << endl; + os << indent << "XAxisLabelPosition: " << this->XAxisLabelPosition << endl; + os << indent << "YAxisLabelPosition: " << this->YAxisLabelPosition << endl; + os << indent << "ZAxisLabelPosition: " << this->ZAxisLabelPosition << endl; + + os << indent << "SphereRadius: " << this->SphereRadius << endl; + os << indent << "SphereResolution: " << this->SphereResolution << endl; + os << indent << "CylinderRadius: " << this->CylinderRadius << endl; + os << indent << "CylinderResolution: " << this->CylinderResolution << endl; + os << indent << "ConeRadius: " << this->ConeRadius << endl; + os << indent << "ConeResolution: " << this->ConeResolution << endl; + + os << indent << "NormalizedShaftLength: " + << this->NormalizedShaftLength[0] << "," + << this->NormalizedShaftLength[1] << "," + << this->NormalizedShaftLength[2] << endl; + os << indent << "NormalizedTipLength: " + << this->NormalizedTipLength[0] << "," + << this->NormalizedTipLength[1] << "," + << this->NormalizedTipLength[2] << endl; + os << indent << "TotalLength: " + << this->TotalLength[0] << "," + << this->TotalLength[1] << "," + << this->TotalLength[2] << endl; +} + +//----------------------------------------------------------------------------- +// porting to VTK 5.0.x +void vtkPVAxesActor::AddToRender( vtkRenderer* theRenderer ) +{ + theRenderer->AddActor(this->XAxisLabel); + theRenderer->AddActor(this->YAxisLabel); + theRenderer->AddActor(this->ZAxisLabel); +} diff --git a/src/SVTK/vtkPVAxesActor.h b/src/SVTK/vtkPVAxesActor.h new file mode 100644 index 000000000..8b9d329cc --- /dev/null +++ b/src/SVTK/vtkPVAxesActor.h @@ -0,0 +1,293 @@ +/*========================================================================= + + Program: ParaView + Module: $RCSfile$ + + Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc. + All rights reserved. + + ParaView is a free software; you can redistribute it and/or modify it + under the terms of the ParaView license version 1.2. + + See License_v1.2.txt for the full ParaView license. + A copy of this license can be obtained by contacting + Kitware Inc. + 28 Corporate Drive + Clifton Park, NY 12065 + USA + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=========================================================================*/ +// .NAME vtkPVAxesActor - a 3D axes representation +// .SECTION Description +// +// vtkPVAxesActor is used to represent 3D axes in the scene. The user can +// define the geometry to use for the shaft and the tip, and the user can +// set the text for the three axes. The text will follow the camera. + + +#ifndef __vtkPVAxesActor_h +#define __vtkPVAxesActor_h + +#include "SVTK.h" +#include "vtkProp3D.h" + +class vtkRenderer; +class vtkPropCollection; +class vtkMapper; +class vtkProperty; +class vtkActor; +class vtkFollower; +class vtkCylinderSource; +class vtkLineSource; +class vtkConeSource; +class vtkSphereSource; +class vtkPolyData; +class vtkVectorText; + +class SVTK_EXPORT vtkPVAxesActor : public vtkProp3D +{ +public: + static vtkPVAxesActor *New(); + vtkTypeRevisionMacro(vtkPVAxesActor,vtkProp3D); + void PrintSelf(ostream& os, vtkIndent indent); + + + // Description: + // For some exporters and other other operations we must be + // able to collect all the actors or volumes. These methods + // are used in that process. + virtual void GetActors(vtkPropCollection *); + + // Description: + // Support the standard render methods. + virtual int RenderOpaqueGeometry(vtkViewport *viewport); +#if (VTK_MINOR_VERSION>=2) + virtual int RenderTranslucentPolygonalGeometry(vtkViewport *viewport); // porting to VTK 5.0.x + virtual int HasTranslucentPolygonalGeometry(); // porting to VTK 5.0.x +#else + virtual int RenderTranslucentGeometry(vtkViewport *viewport); // porting to VTK 5.0.x +#endif + + // Description: + // Shallow copy of an axes actor. Overloads the virtual vtkProp method. + void ShallowCopy(vtkProp *prop); + + // Description: + // Release any graphics resources that are being consumed by this actor. + // The parameter window could be used to determine which graphic + // resources to release. + void ReleaseGraphicsResources(vtkWindow *); + + // Description: + // Get the bounds for this Actor as (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax). (The + // method GetBounds(double bounds[6]) is available from the superclass.) + void GetBounds(double bounds[6]); + double *GetBounds(); + + // Description: + // Get the actors mtime plus consider its properties and texture if set. + unsigned long int GetMTime(); + + // Description: + // Return the mtime of anything that would cause the rendered image to + // appear differently. Usually this involves checking the mtime of the + // prop plus anything else it depends on such as properties, textures + // etc. + virtual unsigned long GetRedrawMTime(); + + // Description: + // Set the total length of the axes in 3 dimensions. + void SetTotalLength( float v[3] ) + { this->SetTotalLength( v[0], v[1], v[2] ); } + void SetTotalLength( float x, float y, float z ); + vtkGetVectorMacro( TotalLength, float, 3 ); + + // Description: + // Set the normalized (0-1) length of the shaft. + void SetNormalizedShaftLength( float v[3] ) + { this->SetNormalizedShaftLength( v[0], v[1], v[2] ); } + void SetNormalizedShaftLength( float x, float y, float z ); + vtkGetVectorMacro( NormalizedShaftLength, float, 3 ); + + // Description: + // Set the normalized (0-1) length of the tip. + void SetNormalizedTipLength( float v[3] ) + { this->SetNormalizedTipLength( v[0], v[1], v[2] ); } + void SetNormalizedTipLength( float x, float y, float z ); + vtkGetVectorMacro( NormalizedTipLength, float, 3 ); + + // Description: + // Set/get the resolution of the pieces of the axes actor + vtkSetClampMacro(ConeResolution, int, 3, 128); + vtkGetMacro(ConeResolution, int); + vtkSetClampMacro(SphereResolution, int, 3, 128); + vtkGetMacro(SphereResolution, int); + vtkSetClampMacro(CylinderResolution, int, 3, 128); + vtkGetMacro(CylinderResolution, int); + + // Description: + // Set/get the radius of the pieces of the axes actor + vtkSetClampMacro(ConeRadius, float, 0, VTK_LARGE_FLOAT); + vtkGetMacro(ConeRadius, float); + vtkSetClampMacro(SphereRadius, float, 0, VTK_LARGE_FLOAT); + vtkGetMacro(SphereRadius, float); + vtkSetClampMacro(CylinderRadius, float, 0, VTK_LARGE_FLOAT); + vtkGetMacro(CylinderRadius, float); + + // Description: + // Set/get the positions of the axis labels + vtkSetClampMacro(XAxisLabelPosition, float, 0, 1); + vtkGetMacro(XAxisLabelPosition, float); + vtkSetClampMacro(YAxisLabelPosition, float, 0, 1); + vtkGetMacro(YAxisLabelPosition, float); + vtkSetClampMacro(ZAxisLabelPosition, float, 0, 1); + vtkGetMacro(ZAxisLabelPosition, float); + + // Description: + // Set the type of the shaft to a cylinder, line, or user defined geometry. + void SetShaftType( int type ); + void SetShaftTypeToCylinder() + { this->SetShaftType( vtkPVAxesActor::CYLINDER_SHAFT ); } + void SetShaftTypeToLine() + { this->SetShaftType( vtkPVAxesActor::LINE_SHAFT ); } + void SetShaftTypeToUserDefined() + { this->SetShaftType( vtkPVAxesActor::USER_DEFINED_SHAFT ); } + + // Description: + // Set the type of the tip to a cone, sphere, or user defined geometry. + void SetTipType( int type ); + void SetTipTypeToCone() + { this->SetTipType( vtkPVAxesActor::CONE_TIP ); } + void SetTipTypeToSphere() + { this->SetTipType( vtkPVAxesActor::SPHERE_TIP ); } + void SetTipTypeToUserDefined() + { this->SetTipType( vtkPVAxesActor::USER_DEFINED_TIP ); } + + //BTX + // Description: + // Set the user defined tip polydata. + void SetUserDefinedTip( vtkPolyData * ); + vtkGetObjectMacro( UserDefinedTip, vtkPolyData ); + + // Description: + // Set the user defined shaft polydata. + void SetUserDefinedShaft( vtkPolyData * ); + vtkGetObjectMacro( UserDefinedShaft, vtkPolyData ); + + // Description: + // Get the tip properties. + vtkProperty *GetXAxisTipProperty(); + vtkProperty *GetYAxisTipProperty(); + vtkProperty *GetZAxisTipProperty(); + + // Description: + // Get the shaft properties. + vtkProperty *GetXAxisShaftProperty(); + vtkProperty *GetYAxisShaftProperty(); + vtkProperty *GetZAxisShaftProperty(); + + // Description: + // Get the label properties. + vtkProperty *GetXAxisLabelProperty(); + vtkProperty *GetYAxisLabelProperty(); + vtkProperty *GetZAxisLabelProperty(); + //ETX + // + // Description: + // Set the label text. + vtkSetStringMacro( XAxisLabelText ); + vtkSetStringMacro( YAxisLabelText ); + vtkSetStringMacro( ZAxisLabelText ); + +//BTX + enum + { + CYLINDER_SHAFT, + LINE_SHAFT, + USER_DEFINED_SHAFT + }; + + + enum + { + CONE_TIP, + SPHERE_TIP, + USER_DEFINED_TIP + }; + +//ETX + + void AddToRender( vtkRenderer* theRenderer ); // porting to VTK 5.0.x + +protected: + vtkPVAxesActor(); + ~vtkPVAxesActor(); + + vtkCylinderSource *CylinderSource; + vtkLineSource *LineSource; + vtkConeSource *ConeSource; + vtkSphereSource *SphereSource; + + vtkActor *XAxisShaft; + vtkActor *YAxisShaft; + vtkActor *ZAxisShaft; + + vtkActor *XAxisTip; + vtkActor *YAxisTip; + vtkActor *ZAxisTip; + + void UpdateProps(); + + float TotalLength[3]; + float NormalizedShaftLength[3]; + float NormalizedTipLength[3]; + + int ShaftType; + int TipType; + + vtkPolyData *UserDefinedTip; + vtkPolyData *UserDefinedShaft; + + char *XAxisLabelText; + char *YAxisLabelText; + char *ZAxisLabelText; + + vtkVectorText *XAxisVectorText; + vtkVectorText *YAxisVectorText; + vtkVectorText *ZAxisVectorText; + + vtkFollower *XAxisLabel; + vtkFollower *YAxisLabel; + vtkFollower *ZAxisLabel; + + int ConeResolution; + int SphereResolution; + int CylinderResolution; + + float ConeRadius; + float SphereRadius; + float CylinderRadius; + + float XAxisLabelPosition; + float YAxisLabelPosition; + float ZAxisLabelPosition; + +private: + vtkPVAxesActor(const vtkPVAxesActor&); // Not implemented. + void operator=(const vtkPVAxesActor&); // Not implemented. +}; + +#endif + diff --git a/src/SVTK/vtkPVAxesWidget.cxx b/src/SVTK/vtkPVAxesWidget.cxx new file mode 100644 index 000000000..42d80002b --- /dev/null +++ b/src/SVTK/vtkPVAxesWidget.cxx @@ -0,0 +1,869 @@ +/*========================================================================= + + Program: ParaView + Module: $RCSfile$ + + Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc. + All rights reserved. + + ParaView is a free software; you can redistribute it and/or modify it + under the terms of the ParaView license version 1.2. + + See License_v1.2.txt for the full ParaView license. + A copy of this license can be obtained by contacting + Kitware Inc. + 28 Corporate Drive + Clifton Park, NY 12065 + USA + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=========================================================================*/ +#include "vtkPVAxesWidget.h" + +#include "vtkActor2D.h" +#include "vtkCallbackCommand.h" +#include "vtkCamera.h" +#include "vtkCoordinate.h" +#include "vtkObjectFactory.h" +#include "vtkPoints.h" +#include "vtkPolyData.h" +#include "vtkPolyDataMapper2D.h" +#include "vtkProperty.h" +#include "vtkProperty2D.h" +#include "vtkPVAxesActor.h" +#include "vtkRenderer.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" + +vtkStandardNewMacro(vtkPVAxesWidget); +vtkCxxRevisionMacro(vtkPVAxesWidget, "$Revision$"); + +vtkCxxSetObjectMacro(vtkPVAxesWidget, AxesActor, vtkPVAxesActor); +vtkCxxSetObjectMacro(vtkPVAxesWidget, ParentRenderer, vtkRenderer); + +//---------------------------------------------------------------------------- +class vtkPVAxesWidgetObserver : public vtkCommand +{ +public: + static vtkPVAxesWidgetObserver *New() + {return new vtkPVAxesWidgetObserver;}; + + vtkPVAxesWidgetObserver() + { + this->AxesWidget = 0; + } + + virtual void Execute(vtkObject* wdg, unsigned long event, void *calldata) + { + if (this->AxesWidget) + { + this->AxesWidget->ExecuteEvent(wdg, event, calldata); + } + } + + vtkPVAxesWidget *AxesWidget; +}; + +//---------------------------------------------------------------------------- +vtkPVAxesWidget::vtkPVAxesWidget() +{ + this->StartEventObserverId = 0; + + this->EventCallbackCommand->SetCallback(vtkPVAxesWidget::ProcessEvents); + + this->Observer = vtkPVAxesWidgetObserver::New(); + this->Observer->AxesWidget = this; + this->Renderer = vtkRenderer::New(); + this->Renderer->SetViewport(0.0, 0.0, 0.2, 0.2); + this->Renderer->SetLayer(1); + this->Renderer->InteractiveOff(); + this->Priority = 0.55; + this->AxesActor = vtkPVAxesActor::New(); + this->Renderer->AddActor(this->AxesActor); + this->AxesActor->AddToRender(this->Renderer); // tmp + + this->ParentRenderer = NULL; + + this->Moving = 0; + this->MouseCursorState = vtkPVAxesWidget::Outside; + + this->StartTag = 0; + + this->Interactive = 1; + + this->Outline = vtkPolyData::New(); + this->Outline->Allocate(); + vtkPoints *points = vtkPoints::New(); + vtkIdType ptIds[5]; + ptIds[4] = ptIds[0] = points->InsertNextPoint(1, 1, 0); + ptIds[1] = points->InsertNextPoint(2, 1, 0); + ptIds[2] = points->InsertNextPoint(2, 2, 0); + ptIds[3] = points->InsertNextPoint(1, 2, 0); + this->Outline->SetPoints(points); + this->Outline->InsertNextCell(VTK_POLY_LINE, 5, ptIds); + vtkCoordinate *tcoord = vtkCoordinate::New(); + tcoord->SetCoordinateSystemToDisplay(); + vtkPolyDataMapper2D *mapper = vtkPolyDataMapper2D::New(); + mapper->SetInput(this->Outline); + mapper->SetTransformCoordinate(tcoord); + this->OutlineActor = vtkActor2D::New(); + this->OutlineActor->SetMapper(mapper); + this->OutlineActor->SetPosition(0, 0); + this->OutlineActor->SetPosition2(1, 1); + + points->Delete(); + mapper->Delete(); + tcoord->Delete(); +} + +//---------------------------------------------------------------------------- +vtkPVAxesWidget::~vtkPVAxesWidget() +{ + this->Observer->Delete(); + this->AxesActor->Delete(); + this->OutlineActor->Delete(); + this->Outline->Delete(); + this->SetParentRenderer(NULL); + this->Renderer->Delete(); +} + +//---------------------------------------------------------------------------- +void vtkPVAxesWidget::SetEnabled(int enabling) +{ + if (!this->Interactor) + { + vtkErrorMacro("The interactor must be set prior to enabling/disabling widget"); + } + + if (enabling) + { + if (this->Enabled) + { + return; + } + if (!this->ParentRenderer) + { + vtkErrorMacro("The parent renderer must be set prior to enabling this widget"); + return; + } + + this->Enabled = 1; + + if ( this->EventCallbackCommand ) + { + vtkRenderWindowInteractor *i = this->Interactor; + i->AddObserver(vtkCommand::MouseMoveEvent, + this->EventCallbackCommand, this->Priority); + i->AddObserver(vtkCommand::LeftButtonPressEvent, + this->EventCallbackCommand, this->Priority); + i->AddObserver(vtkCommand::LeftButtonReleaseEvent, + this->EventCallbackCommand, this->Priority); + } + + this->ParentRenderer->GetRenderWindow()->AddRenderer(this->Renderer); + if (this->ParentRenderer->GetRenderWindow()->GetNumberOfLayers() < 2) + { + this->ParentRenderer->GetRenderWindow()->SetNumberOfLayers(2); + } + this->AxesActor->SetVisibility(1); + // We need to copy the camera before the compositing observer is called. + // Compositing temporarily changes the camera to display an image. + this->StartEventObserverId = + this->ParentRenderer->AddObserver(vtkCommand::StartEvent,this->Observer,1); + this->InvokeEvent(vtkCommand::EnableEvent, NULL); + } + else + { + if (!this->Enabled) + { + return; + } + + this->Enabled = 0; + this->Interactor->RemoveObserver(this->EventCallbackCommand); + + this->AxesActor->SetVisibility(0); + if (this->ParentRenderer) + { + if (this->ParentRenderer->GetRenderWindow()) + { + this->ParentRenderer->GetRenderWindow()->RemoveRenderer(this->Renderer); + this->AxesActor->ReleaseGraphicsResources(this->ParentRenderer->GetRenderWindow()); + } + if (this->StartEventObserverId != 0) + { + this->ParentRenderer->RemoveObserver(this->StartEventObserverId); + } + } + + this->InvokeEvent(vtkCommand::DisableEvent, NULL); + } +} + +//---------------------------------------------------------------------------- +void vtkPVAxesWidget::ExecuteEvent(vtkObject *vtkNotUsed(o), + unsigned long vtkNotUsed(event), + void *vtkNotUsed(calldata)) +{ + if (!this->ParentRenderer) + { + return; + } + + vtkCamera *cam = this->ParentRenderer->GetActiveCamera(); + double pos[3], fp[3], viewup[3]; + cam->GetPosition(pos); + cam->GetFocalPoint(fp); + cam->GetViewUp(viewup); + + cam = this->Renderer->GetActiveCamera(); + cam->SetPosition(pos); + cam->SetFocalPoint(fp); + cam->SetViewUp(viewup); + this->Renderer->ResetCamera(); + + this->SquareRenderer(); +} + +void vtkPVAxesWidget::UpdateCursorIcon() +{ + if (!this->Enabled) + { + this->SetMouseCursor(vtkPVAxesWidget::Outside); + return; + } + + if (this->Moving) + { + return; + } + + int *parentSize = this->ParentRenderer->GetSize(); + + int x = this->Interactor->GetEventPosition()[0]; + int y = this->Interactor->GetEventPosition()[1]; + double xNorm = x / (double)parentSize[0]; + double yNorm = y / (double)parentSize[1]; + + double pos[4]; + this->Renderer->GetViewport(pos); + + int pState = this->MouseCursorState; + + if (xNorm > pos[0] && xNorm < pos[2] && yNorm > pos[1] && yNorm < pos[3]) + { + this->MouseCursorState = vtkPVAxesWidget::Inside; + } + else if (fabs(xNorm-pos[0]) < .02 && fabs(yNorm-pos[3]) < .02) + { + this->MouseCursorState = vtkPVAxesWidget::TopLeft; + } + else if (fabs(xNorm-pos[2]) < .02 && fabs(yNorm-pos[3]) < .02) + { + this->MouseCursorState = vtkPVAxesWidget::TopRight; + } + else if (fabs(xNorm-pos[0]) < .02 && fabs(yNorm-pos[1]) < .02) + { + this->MouseCursorState = vtkPVAxesWidget::BottomLeft; + } + else if (fabs(xNorm-pos[2]) < .02 && fabs(yNorm-pos[1]) < .02) + { + this->MouseCursorState = vtkPVAxesWidget::BottomRight; + } + else + { + this->MouseCursorState = vtkPVAxesWidget::Outside; + } + + if (pState == this->MouseCursorState) + { + return; + } + + if (this->MouseCursorState == vtkPVAxesWidget::Outside) + { + this->Renderer->RemoveActor(this->OutlineActor); + } + else + { + this->Renderer->AddActor(this->OutlineActor); + } + this->Interactor->Render(); + + this->SetMouseCursor(this->MouseCursorState); +} + +//---------------------------------------------------------------------------- +void vtkPVAxesWidget::SetMouseCursor(int cursorState) +{ + switch (cursorState) + { + case vtkPVAxesWidget::Outside: + this->Interactor->GetRenderWindow()->SetCurrentCursor(VTK_CURSOR_DEFAULT); + break; + case vtkPVAxesWidget::Inside: + this->Interactor->GetRenderWindow()->SetCurrentCursor(VTK_CURSOR_SIZEALL); + break; + case vtkPVAxesWidget::TopLeft: + this->Interactor->GetRenderWindow()->SetCurrentCursor(VTK_CURSOR_SIZENW); + break; + case vtkPVAxesWidget::TopRight: + this->Interactor->GetRenderWindow()->SetCurrentCursor(VTK_CURSOR_SIZENE); + break; + case vtkPVAxesWidget::BottomLeft: + this->Interactor->GetRenderWindow()->SetCurrentCursor(VTK_CURSOR_SIZESW); + break; + case vtkPVAxesWidget::BottomRight: + this->Interactor->GetRenderWindow()->SetCurrentCursor(VTK_CURSOR_SIZESE); + break; + } +} + +//---------------------------------------------------------------------------- +void vtkPVAxesWidget::ProcessEvents(vtkObject* vtkNotUsed(object), + unsigned long event, + void *clientdata, + void* vtkNotUsed(calldata)) +{ + vtkPVAxesWidget *self = + reinterpret_cast(clientdata); + + if (!self->GetInteractive()) + { + return; + } + + switch (event) + { + case vtkCommand::LeftButtonPressEvent: + self->OnButtonPress(); + break; + case vtkCommand::MouseMoveEvent: + self->OnMouseMove(); + break; + case vtkCommand::LeftButtonReleaseEvent: + self->OnButtonRelease(); + break; + } +} + +//---------------------------------------------------------------------------- +void vtkPVAxesWidget::OnButtonPress() +{ + if (this->MouseCursorState == vtkPVAxesWidget::Outside) + { + return; + } + + this->SetMouseCursor(this->MouseCursorState); + + this->StartPosition[0] = this->Interactor->GetEventPosition()[0]; + this->StartPosition[1] = this->Interactor->GetEventPosition()[1]; + + this->Moving = 1; + this->EventCallbackCommand->SetAbortFlag(1); + this->StartInteraction(); + this->InvokeEvent(vtkCommand::StartInteractionEvent, NULL); +} + +//---------------------------------------------------------------------------- +void vtkPVAxesWidget::OnButtonRelease() +{ + if (this->MouseCursorState == vtkPVAxesWidget::Outside) + { + return; + } + + this->Moving = 0; + this->EndInteraction(); + this->InvokeEvent(vtkCommand::EndInteractionEvent, NULL); +} + +//---------------------------------------------------------------------------- +void vtkPVAxesWidget::OnMouseMove() +{ + if (this->Moving) + { + switch (this->MouseCursorState) + { + case vtkPVAxesWidget::Inside: + this->MoveWidget(); + break; + case vtkPVAxesWidget::TopLeft: + this->ResizeTopLeft(); + break; + case vtkPVAxesWidget::TopRight: + this->ResizeTopRight(); + break; + case vtkPVAxesWidget::BottomLeft: + this->ResizeBottomLeft(); + break; + case vtkPVAxesWidget::BottomRight: + this->ResizeBottomRight(); + break; + } + + this->UpdateCursorIcon(); + this->EventCallbackCommand->SetAbortFlag(1); + this->InvokeEvent(vtkCommand::InteractionEvent, NULL); + } + else + { + this->UpdateCursorIcon(); + } +} + +//---------------------------------------------------------------------------- +void vtkPVAxesWidget::MoveWidget() +{ + int x = this->Interactor->GetEventPosition()[0]; + int y = this->Interactor->GetEventPosition()[1]; + + int dx = x - this->StartPosition[0]; + int dy = y - this->StartPosition[1]; + + this->StartPosition[0] = x; + this->StartPosition[1] = y; + + int *size = this->ParentRenderer->GetSize(); + double dxNorm = dx / (double)size[0]; + double dyNorm = dy / (double)size[1]; + + double *vp = this->Renderer->GetViewport(); + + double newPos[4]; + newPos[0] = vp[0] + dxNorm; + newPos[1] = vp[1] + dyNorm; + newPos[2] = vp[2] + dxNorm; + newPos[3] = vp[3] + dyNorm; + + if (newPos[0] < 0) + { + this->StartPosition[0] = 0; + newPos[0] = 0; + newPos[2] = vp[2] - vp[0]; + } + if (newPos[1] < 0) + { + this->StartPosition[1] = 0; + newPos[1] = 0; + newPos[3] = vp[3] - vp[1]; + } + if (newPos[2] > 1) + { + this->StartPosition[0] = (int)(size[0] - size[0] * (vp[2]-vp[0])); + newPos[0] = 1 - (vp[2]-vp[0]); + newPos[2] = 1; + } + if (newPos[3] > 1) + { + this->StartPosition[1] = (int)(size[1] - size[1]*(vp[3]-vp[1])); + newPos[1] = 1 - (vp[3]-vp[1]); + newPos[3] = 1; + } + + this->Renderer->SetViewport(newPos); + this->Interactor->Render(); +} + +//---------------------------------------------------------------------------- +void vtkPVAxesWidget::ResizeTopLeft() +{ + int x = this->Interactor->GetEventPosition()[0]; + int y = this->Interactor->GetEventPosition()[1]; + + int dx = x - this->StartPosition[0]; + int dy = y - this->StartPosition[1]; + + int *size = this->ParentRenderer->GetSize(); + double dxNorm = dx / (double)size[0]; + double dyNorm = dy / (double)size[1]; + + int useX; + double change; + double absDx = fabs(dxNorm); + double absDy = fabs(dyNorm); + + if (absDx > absDy) + { + change = dxNorm; + useX = 1; + } + else + { + change = dyNorm; + useX = 0; + } + + double *vp = this->Renderer->GetViewport(); + + this->StartPosition[0] = x; + this->StartPosition[1] = y; + + double newPos[4]; + newPos[0] = useX ? vp[0] + change : vp[0] - change; + newPos[1] = vp[1]; + newPos[2] = vp[2]; + newPos[3] = useX ? vp[3] - change : vp[3] + change; + + if (newPos[0] < 0) + { + this->StartPosition[0] = 0; + newPos[0] = 0; + } + if (newPos[0] >= newPos[2]-0.01) + { + newPos[0] = newPos[2] - 0.01; + } + if (newPos[3] > 1) + { + this->StartPosition[1] = size[1]; + newPos[3] = 1; + } + if (newPos[3] <= newPos[1]+0.01) + { + newPos[3] = newPos[1] + 0.01; + } + + this->Renderer->SetViewport(newPos); + this->Interactor->Render(); +} + +//---------------------------------------------------------------------------- +void vtkPVAxesWidget::ResizeTopRight() +{ + int x = this->Interactor->GetEventPosition()[0]; + int y = this->Interactor->GetEventPosition()[1]; + + int dx = x - this->StartPosition[0]; + int dy = y - this->StartPosition[1]; + + int *size = this->ParentRenderer->GetSize(); + double dxNorm = dx / (double)size[0]; + double dyNorm = dy / (double)size[1]; + + double change; + double absDx = fabs(dxNorm); + double absDy = fabs(dyNorm); + + if (absDx > absDy) + { + change = dxNorm; + } + else + { + change = dyNorm; + } + + double *vp = this->Renderer->GetViewport(); + + this->StartPosition[0] = x; + this->StartPosition[1] = y; + + double newPos[4]; + newPos[0] = vp[0]; + newPos[1] = vp[1]; + newPos[2] = vp[2] + change; + newPos[3] = vp[3] + change; + + if (newPos[2] > 1) + { + this->StartPosition[0] = size[0]; + newPos[2] = 1; + } + if (newPos[2] <= newPos[0]+0.01) + { + newPos[2] = newPos[0] + 0.01; + } + if (newPos[3] > 1) + { + this->StartPosition[1] = size[1]; + newPos[3] = 1; + } + if (newPos[3] <= newPos[1]+0.01) + { + newPos[3] = newPos[1] + 0.01; + } + + this->Renderer->SetViewport(newPos); + this->Interactor->Render(); +} + +//---------------------------------------------------------------------------- +void vtkPVAxesWidget::ResizeBottomLeft() +{ + int x = this->Interactor->GetEventPosition()[0]; + int y = this->Interactor->GetEventPosition()[1]; + + int dx = x - this->StartPosition[0]; + int dy = y - this->StartPosition[1]; + + int *size = this->ParentRenderer->GetSize(); + double dxNorm = dx / (double)size[0]; + double dyNorm = dy / (double)size[1]; + double *vp = this->Renderer->GetViewport(); + + double change; + double absDx = fabs(dxNorm); + double absDy = fabs(dyNorm); + + if (absDx > absDy) + { + change = dxNorm; + } + else + { + change = dyNorm; + } + + this->StartPosition[0] = x; + this->StartPosition[1] = y; + + double newPos[4]; + newPos[0] = vp[0] + change; + newPos[1] = vp[1] + change; + newPos[2] = vp[2]; + newPos[3] = vp[3]; + + if (newPos[0] < 0) + { + this->StartPosition[0] = 0; + newPos[0] = 0; + } + if (newPos[0] >= newPos[2]-0.01) + { + newPos[0] = newPos[2] - 0.01; + } + if (newPos[1] < 0) + { + this->StartPosition[1] = 0; + newPos[1] = 0; + } + if (newPos[1] >= newPos[3]-0.01) + { + newPos[1] = newPos[3] - 0.01; + } + + this->Renderer->SetViewport(newPos); + this->Interactor->Render(); +} + +//---------------------------------------------------------------------------- +void vtkPVAxesWidget::ResizeBottomRight() +{ + int x = this->Interactor->GetEventPosition()[0]; + int y = this->Interactor->GetEventPosition()[1]; + + int dx = x - this->StartPosition[0]; + int dy = y - this->StartPosition[1]; + + int *size = this->ParentRenderer->GetSize(); + double dxNorm = dx / (double)size[0]; + double dyNorm = dy / (double)size[1]; + + double *vp = this->Renderer->GetViewport(); + + int useX; + double change; + double absDx = fabs(dxNorm); + double absDy = fabs(dyNorm); + + if (absDx > absDy) + { + change = dxNorm; + useX = 1; + } + else + { + change = dyNorm; + useX = 0; + } + + this->StartPosition[0] = x; + this->StartPosition[1] = y; + + double newPos[4]; + newPos[0] = vp[0]; + newPos[1] = useX ? vp[1] - change : vp[1] + change; + newPos[2] = useX ? vp[2] + change : vp[2] - change; + newPos[3] = vp[3]; + + if (newPos[2] > 1) + { + this->StartPosition[0] = size[0]; + newPos[2] = 1; + } + if (newPos[2] <= newPos[0]+0.01) + { + newPos[2] = newPos[0] + 0.01; + } + if (newPos[1] < 0) + { + this->StartPosition[1] = 0; + newPos[1] = 0; + } + if (newPos[1] >= newPos[3]-0.01) + { + newPos[1] = newPos[3]-0.01; + } + + this->Renderer->SetViewport(newPos); + this->Interactor->Render(); +} + +//---------------------------------------------------------------------------- +void vtkPVAxesWidget::SquareRenderer() +{ + int *size = this->Renderer->GetSize(); + if (size[0] == 0 || size[1] == 0) + { + return; + } + + double vp[4]; + this->Renderer->GetViewport(vp); + + double deltaX = vp[2] - vp[0]; + double newDeltaX = size[1] * deltaX / (double)size[0]; + double deltaY = vp[3] - vp[1]; + double newDeltaY = size[0] * deltaY / (double)size[1]; + + if (newDeltaX > 1) + { + if (newDeltaY > 1) + { + if (size[0] > size[1]) + { + newDeltaX = size[1] / (double)size[0]; + newDeltaY = 1; + } + else + { + newDeltaX = 1; + newDeltaY = size[0] / (double)size[1]; + } + vp[0] = vp[1] = 0; + vp[2] = newDeltaX; + vp[3] = newDeltaY; + } + else + { + vp[3] = vp[1] + newDeltaY; + if (vp[3] > 1) + { + vp[3] = 1; + vp[1] = vp[3] - newDeltaY; + } + } + } + else + { + vp[2] = vp[0] + newDeltaX; + if (vp[2] > 1) + { + vp[2] = 1; + vp[0] = vp[2] - newDeltaX; + } + } + + this->Renderer->SetViewport(vp); + + this->Renderer->NormalizedDisplayToDisplay(vp[0], vp[1]); + this->Renderer->NormalizedDisplayToDisplay(vp[2], vp[3]); + + vtkPoints *points = this->Outline->GetPoints(); + points->SetPoint(0, vp[0]+1, vp[1]+1, 0); + points->SetPoint(1, vp[2]-1, vp[1]+1, 0); + points->SetPoint(2, vp[2]-1, vp[3]-1, 0); + points->SetPoint(3, vp[0]+1, vp[3]-1, 0); +} + +//---------------------------------------------------------------------------- +void vtkPVAxesWidget::SetInteractive(int state) +{ + if (this->Interactive != state) + { + this->Interactive = state; + } + + if (!state) + { + this->OnButtonRelease(); + this->MouseCursorState = vtkPVAxesWidget::Outside; + this->Renderer->RemoveActor(this->OutlineActor); + if (this->Interactor) + { + this->SetMouseCursor(this->MouseCursorState); + // this->Interactor->Render(); + } + } +} + +//---------------------------------------------------------------------------- +void vtkPVAxesWidget::SetOutlineColor(double r, double g, double b) +{ + this->OutlineActor->GetProperty()->SetColor(r, g, b); + if (this->Interactor) + { +// this->Interactor->Render(); + } +} + +//---------------------------------------------------------------------------- +double* vtkPVAxesWidget::GetOutlineColor() +{ + return this->OutlineActor->GetProperty()->GetColor(); +} + +//---------------------------------------------------------------------------- +void vtkPVAxesWidget::SetAxisLabelColor(double r, double g, double b) +{ + this->AxesActor->GetXAxisLabelProperty()->SetColor(r, g, b); + this->AxesActor->GetYAxisLabelProperty()->SetColor(r, g, b); + this->AxesActor->GetZAxisLabelProperty()->SetColor(r, g, b); +} + +//---------------------------------------------------------------------------- +double* vtkPVAxesWidget::GetAxisLabelColor() +{ + return this->AxesActor->GetXAxisLabelProperty()->GetColor(); +} + +//---------------------------------------------------------------------------- +vtkRenderer* vtkPVAxesWidget::GetParentRenderer() +{ + return this->ParentRenderer; +} + +//---------------------------------------------------------------------------- +void vtkPVAxesWidget::SetViewport(double minX, double minY, + double maxX, double maxY) +{ + this->Renderer->SetViewport(minX, minY, maxX, maxY); +} + +//---------------------------------------------------------------------------- +double* vtkPVAxesWidget::GetViewport() +{ + return this->Renderer->GetViewport(); +} + +//---------------------------------------------------------------------------- +void vtkPVAxesWidget::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); + + os << indent << "AxesActor: " << this->AxesActor << endl; + os << indent << "Interactive: " << this->Interactive << endl; +} diff --git a/src/SVTK/vtkPVAxesWidget.h b/src/SVTK/vtkPVAxesWidget.h new file mode 100644 index 000000000..35c152a94 --- /dev/null +++ b/src/SVTK/vtkPVAxesWidget.h @@ -0,0 +1,159 @@ +/*========================================================================= + + Program: ParaView + Module: $RCSfile$ + + Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc. + All rights reserved. + + ParaView is a free software; you can redistribute it and/or modify it + under the terms of the ParaView license version 1.2. + + See License_v1.2.txt for the full ParaView license. + A copy of this license can be obtained by contacting + Kitware Inc. + 28 Corporate Drive + Clifton Park, NY 12065 + USA + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=========================================================================*/ +// .NAME vtkPVAxesWidget - A widget to manipulate an axe +// +// .SECTION Description +// This widget creates and manages its own vtkPVAxesActor. + + +#ifndef __vtkPVAxesWidget_h +#define __vtkPVAxesWidget_h + +#include "SVTK.h" +#include "vtkInteractorObserver.h" + +class vtkActor2D; +class vtkKWApplication; +class vtkPolyData; +class vtkPVAxesActor; +class vtkPVAxesWidgetObserver; +class vtkRenderer; + +class SVTK_EXPORT vtkPVAxesWidget : public vtkInteractorObserver +{ +public: + static vtkPVAxesWidget* New(); + vtkTypeRevisionMacro(vtkPVAxesWidget, vtkInteractorObserver); + void PrintSelf(ostream& os, vtkIndent indent); + + // Description: + // Set/get the axes actor to be displayed in this 3D widget. + void SetAxesActor(vtkPVAxesActor *actor); + vtkGetObjectMacro(AxesActor, vtkPVAxesActor); + + // Description: + // Enable the 3D widget. + virtual void SetEnabled(int); + + //BTX + // Description: + // Set the renderer this 3D widget will be contained in. + void SetParentRenderer(vtkRenderer *ren); + vtkRenderer* GetParentRenderer(); + //ETX + + // Description: + // Callback to keep the camera for the axes actor up to date with the + // camera in the parent renderer + void ExecuteEvent(vtkObject *o, unsigned long event, void *calldata); + + // Description: + // Set/get whether to allow this 3D widget to be interactively moved/scaled. + void SetInteractive(int state); + vtkGetMacro(Interactive, int); + vtkBooleanMacro(Interactive, int); + + // Description: + // Set/get the color of the outline of this widget. The outline is visible + // when (in interactive mode) the cursor is over this 3D widget. + void SetOutlineColor(double r, double g, double b); + double *GetOutlineColor(); + + // Description: + // Set/get the color of the axis labels of this widget. + void SetAxisLabelColor(double r, double g, double b); + double *GetAxisLabelColor(); + + // Description: + // Set/get the viewport to position/size this 3D widget. + void SetViewport(double minX, double minY, double maxX, double maxY); + double* GetViewport(); + +protected: + vtkPVAxesWidget(); + ~vtkPVAxesWidget(); + + vtkRenderer *Renderer; + vtkRenderer *ParentRenderer; + + vtkPVAxesActor *AxesActor; + vtkPolyData *Outline; + vtkActor2D *OutlineActor; + + static void ProcessEvents(vtkObject *object, unsigned long event, + void *clientdata, void *calldata); + + vtkPVAxesWidgetObserver *Observer; + int StartTag; + + int MouseCursorState; + int Moving; + int StartPosition[2]; + + int Interactive; + + void UpdateCursorIcon(); + void SetMouseCursor(int cursorState); + +//BTX + int State; + + enum AxesWidgetState + { + Outside = 0, + Inside, + TopLeft, + TopRight, + BottomLeft, + BottomRight + }; +//ETX + + void OnButtonPress(); + void OnMouseMove(); + void OnButtonRelease(); + + void MoveWidget(); + void ResizeTopLeft(); + void ResizeTopRight(); + void ResizeBottomLeft(); + void ResizeBottomRight(); + + void SquareRenderer(); + + unsigned long StartEventObserverId; +private: + vtkPVAxesWidget(const vtkPVAxesWidget&); // Not implemented + void operator=(const vtkPVAxesWidget&); // Not implemented +}; + +#endif diff --git a/src/SalomeApp/addvars2notebook.py b/src/SalomeApp/addvars2notebook.py new file mode 100644 index 000000000..b112841fe --- /dev/null +++ b/src/SalomeApp/addvars2notebook.py @@ -0,0 +1,85 @@ +# Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +# + +import os +import os.path + +def addvars2notebook(filename): + # + vars_and_values = [] + contents = [] + # + directory = os.path.dirname(filename) + base = os.path.basename(filename) + prefix = base[:-3] # remove ".py" + prefix = prefix + '_' + from os import listdir + l = listdir(directory) + for f in l: + if f.find(prefix) != 0: continue + if f[-3:] != ".py": continue + module = f[len(prefix):-3] + try: + mod = __import__("addvars2notebook_%s"%(module)) + except ImportError: + continue + try: + func = mod.addvars2notebook + except AttributeError: + continue + fff = os.path.join(directory, f) + content = func(fff, vars_and_values) + contents.append([fff, content]) + pass + # + if vars_and_values: + stream = open(filename) + content = stream.read() + stream.close() + fields = content.split("import iparameters") + if len(fields) == 2: + begin = fields[0] + if begin.find("## NoteBook E.A.") >= 0: + begin = begin.split("## NoteBook E.A.")[0] + pass + end = "import iparameters" + fields[1] + content = begin + content += "## NoteBook E.A.\n" + for var, value in vars_and_values: + content += "notebook.set(%s,%s)\n"%(var.__repr__(), value) + pass + content += end + stream = open(filename, "w") + stream.write(content) + stream.close() + # + for fff, content in contents: + stream = open(fff, "w") + stream.write(content) + stream.close() + pass + pass + pass + # + return + +if __name__ == "__main__": + import sys + addvars2notebook(sys.argv[1]) + pass diff --git a/src/SalomeApp/resources/SalomeApp_msg_fr.ts b/src/SalomeApp/resources/SalomeApp_msg_fr.ts new file mode 100755 index 000000000..dc4f87c52 --- /dev/null +++ b/src/SalomeApp/resources/SalomeApp_msg_fr.ts @@ -0,0 +1,517 @@ + + + + + @default + + WRN_FILE_NAME_BAD + Indiquez un nom de fichier correct. +Un fichier Python ne doit être composé que de lettres, chiffres et tirets bas et doit commencer avec une lettre ou un tiret bas. + + + WRN_FILE_NOT_EXIST + Le fichier %1 n'existe pas. + + + CLOSE_LOCKED_STUDY + Fermer l'étude verrouillée ? + + + PUBLISH_IN_STUDY + Publier dans l'étude + + + MULTI_FILE_DUMP + Dump multi-fichiers + + + BUT_NEW + &Nouvelle + + + SAVE_POINT_ROOT_NAME + Etats d'IHM + + + SAVE_POINT_ROOT_TOOLTIP + Etats d'IHM persistents + + + SAVE_GUI_STATE + Sauvegarder l'état d'IHM + + + BUT_LOAD + &Charger + + + BUT_OPEN + &Ouvrir + + + SAVE_POINT_OBJECT_TOOLTIP + Etat d'IHM: %1 sauvegardé + + + SAVE_POINT_DEF_NAME + Etat d'IHM: + + + VALUE_COLUMN + Valeur + + + IOR_COLUMN + IOR + + + REFENTRY_COLUMN + Entrée de réf. + + + ERR_INCOMPATIBLE_TYPE + Le type numérique de la variable "%1" n'est pas compatible + + + ERR_INVALID_VALUE + La valeur n'a pas été validée + + + ERR_NO_VARIABLE + La variable "%1" n'existe pas. + + + + SalomeApp_Application + + ALL_FILES_FILTER + Tous les fichiers (*.*) + + + APPCLOSE_UNLOAD + &Déconnecter + + + APPCLOSE_CLOSE + &Fermer sans sauvegarder + + + MEN_WINDOWS_NEW + Nouvelle fenêtre + + + MEN_DELETE_INVALID_REFERENCE + Supprimer la référence invalide + + + TOT_FILE_DESK_PREFERENCES + Préférences + + + MEN_DELETE_VS + Supprimer + + + MEN_OPENWITH + Activer module %1 + + + MEN_DESK_REGISTRY_DISPLAY + Affichage du registre CORBA + + + APPCLOSE_SAVE + &Sauvegarder && Fermer + + + TOT_DESK_FILE_LOAD_SCRIPT + Exécuter un script python + + + PREF_PYDUMP_PUBLISH + Publier dans l'étude dans un scrypt Python + + + PREF_PYDUMP_MULTI_FILE + Dump Python multi-fichiers + + + PREF_PYDUMP_SAVE_GUI + Enregistrer l'état de l'IHM dans un script Python + + + PREF_STORE_VISUAL_STATE + Sauvegarder/restaurer le dernier état d'IHM + + + PRP_DESK_FILE_SAVE_GUI_STATE + Sauvegarder l'état actuel des vues 3D, des objets affichés, etc. + + + MEN_DESK_FILE_SAVE_GUI_STATE + Sauvegarder l'état d'IHM + + + TOT_DESK_FILE_SAVE_GUI_STATE + Sauvegarder l'état d'IHM + + + MEN_RESTORE_VS + Restaurer + + + WRN_DUMP_STUDY_FAILED + Impossible de générer le script de l'étude + + + MEN_DESK_PROPERTIES + Pro&priétés... + + + QUE_DOC_ALREADYEXIST + Le document %1 existe déjà dans le gestionnaire d'études. +Voulez-vous le recharger ? + + + MEN_RENAME_VS + Renommer + + + TOT_DESK_CATALOG_GENERATOR + Générateur de catalogue + + + TOT_DESK_ADD_VARS_TO_NOTEBOOK + Ajouter les variables au registre + + + PUBLISH_IN_STUDY + Publier dans l'étude + + + PREF_OBJ_BROWSER_SETTINGS + Paramètres + + + PRP_DESK_REGISTRY_DISPLAY + Visualiser le contenu du registre du serveur CORBA + + + PYTHON_FILES_FILTER + Fichiers PYTHON (*.py) + + + APPCLOSE_DESCRIPTION + Voulez-vous fermer ou décharger l'étude avant de la fermer ? + + + PRP_DESK_PROPERTIES + Editer les propriétés de l'étude + + + PREF_TAB_OBJBROWSER + Arbre d'étude + + + STUDY_LOCKED + VERROUILLEE + + + APPCLOSE_CANCEL + &Annuler + + + OBJ_BROWSER_NAME + Objet + + + TOT_DESK_REGISTRY_DISPLAY + Visualiser le registre CORBA + + + OBJ_BROWSER_COLUMN_0 + Entrée + + + OBJ_BROWSER_COLUMN_1 + Valeur + + + OBJ_BROWSER_COLUMN_2 + IOR + + + OBJ_BROWSER_COLUMN_3 + Entrée de référence + + + PREF_CATEGORY_SALOME + SALOME + + + PYTHON_CONSOLE + Console Python + + + MEN_DESK_FILE_LOAD_SCRIPT + Exécuter un scrip&t... + + + MEN_DESK_TOOLS + &Outils + + + MEN_DESK_PLUGINS_TOOLS + Outils + + + MEN_DESK_PLUGINS + Extensions + + + TOT_DESK_FILE_DUMP_STUDY + Générer le script de l'étude + + + MEN_VIEW_WNDS + Fenêtres + + + MEN_DESK_FILE_DUMP_STUDY + &Générer le script de l'étude... + + + PRP_DESK_CATALOG_GENERATOR + Génére un catalogue XML de l'interface du composant + + + PRP_DESK_ADD_VARS_TO_NOTEBOOK + Ajouter les variables de l'étude au registre + + + PRP_DESK_FILE_DUMP_STUDY + Génère le script python de l'étude + + + TOT_DESK_FILE_NOTEBOOK + Ouvrir le registre + + + MEN_DESK_FILE_NOTEBOOK + Re&gistre... + + + PRP_DESK_FILE_NOTEBOOK + Ouvrir le registre + + + TOT_DESK_PROPERTIES + Propriétés de l'étude + + + PREF_GROUP_DEF_COLUMNS + Colonnes par défaut + + + PRP_DESK_FILE_LOAD_SCRIPT + Exécute un script Python à partir d'un fichier + + + MEN_DESK_CATALOG_GENERATOR + &Genérateur de catalogue + + + MEN_DESK_ADD_VARS_TO_NOTEBOOK + Ajouter les variables au registre + + + APPCLOSE_CAPTION + Fermer l'étude actuelle + + + MEN_DESK_MRU + Dernières études ouvertes + + + TOT_DESK_MRU + Dernières études ouvertes + + + ACTIVATE_MODULE_OP_LOAD + &Charger... + + + ACTIVATE_MODULE_OP_SCRIPT + Charger un &script... + + + + SalomeApp_StudyPropertiesDlg + + PRP_MODE_FROM_SCRATCH + du début + + + PRP_AUTHOR + Auteur + + + PRP_LOCKED + Verrouillée + + + PRP_MODIFICATIONS + Modifications + + + PRP_DATE_MODIF + Date + + + PRP_UNITS + Unités de longueur + + + PRP_COMMENT + Commentaires + + + PRP_NO + Non + + + PRP_YES + Oui + + + PRP_MODIFIED + Modifiée + + + PRP_NOT_MODIFIED + Non modifiée + + + PRP_DATE + Date de création + + + PRP_MODE + Mode + + + PRP_MODE_FROM_COPYFROM + copier de + + + TLT_STUDY_PROPERTIES + Propriétés de l'étude + + + + SalomeApp_ExitDlg + + SHUTDOWN_SERVERS + Arrêter les serveurs + + + + NoteBook_Table + + REMOVE_VARIABLE_IS_USED + La variable "%1" est utilisée dans l'étude. +Voulez-vous vraiment la supprimer? + + + RENAME_VARIABLE_IS_USED + La variable "%1" est utilisée dans l'étude. +Voulez-vous vraiment la renommer? + + + VARNAME_COLUMN + Nom de la variable + + + VARVALUE_COLUMN + Valeur de la variable + + + VARVALUE_INCORRECT + La valeur de la variable n'est pas correcte: %1 + + + VARNAME_INCORRECT + Le nom de la variable n'est pas correct: %1 + + + VARNAME_EXISTS + La variable "%1" existe + + + + SalomeApp_NoteBookDlg + + NOTEBOOK_TITLE + Registre Salome + + + BUT_UPDATE_STUDY + &Mettre l'étude à jour + + + BUT_REMOVE + &Supprimer + + + BUT_APPLY_AND_CLOSE + A&ppliquer et Fermer + + + BUT_HELP + &Aide + + + CLOSE_CAPTION + Fermer le registre + + + CLOSE_DESCRIPTION + Voulez-vous sauvegarder les changements faits au registre ? + + + INCORRECT_DATA + Au moins une variable a été définie incorrectement. +Editez ses paramètres ou retirez la de la liste. + + + ERR_UPDATE_STUDY_FAILED + Impossible de mettre l'étude à jour ! + + + + SalomeApp_DoubleSpinBox + + VALID_RANGE_VAR_MSG + Indiquez un nom de variable ou +une valeur réelle dans l'intervalle ( %1; %2 ) +avec une précision de %3 décimales + + + VALID_RANGE_NOVAR_MSG + Indiquez une valeur réelle dans l'intervalle ( %1; %2 ) +avec une précision de %3 décimales + + + + SalomeApp_IntSpinBox + + VALID_RANGE_VAR_MSG + Indiquez un nom de variable ou +une valeur entière dans l'intervalle ( %1; %2 ) + + + VALID_RANGE_NOVAR_MSG + Indiquez une valeur entière dans l'intervalle ( %1; %2 ) + + + diff --git a/src/SalomeApp/salome_pluginsmanager.py b/src/SalomeApp/salome_pluginsmanager.py new file mode 100644 index 000000000..c498c1a45 --- /dev/null +++ b/src/SalomeApp/salome_pluginsmanager.py @@ -0,0 +1,328 @@ +# Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +# + +""" +This module is imported from C++ SalomeApp_Application and initialized +(call to initialize function with 4 parameters) module : 0 if it's +plugins manager at the application level 1 if it is at the module +level name : the name of the plugins manager. This name is used to +build the name of the plugins files basemenuname : the name of the +menu into we want to add the menu of the plugins ("Tools" for example) +menuname : the name of plugins menu + +A plugins manager is created when calling initialize. + +The plugins manager creates a submenu in the +menu. + +The plugins manager searches in $HOME/.config/salome/Plugins, +$HOME/$APPLI/Plugins, $SALOME_PLUGINS_PATH directories files named +_plugins.py and executes them. + +These files should contain python code that register functions into +the plugins manager. + +Example of a plugins manager with name salome. It searches files with +name salome_plugins.py (example follows):: + + import salome_pluginsmanager + + def about(context): + from PyQt4.QtGui import QMessageBox + QMessageBox.about(None, "About SALOME pluginmanager", "SALOME plugins manager in SALOME virtual application ") + + salome_pluginsmanager.AddFunction('About plugins','About SALOME pluginmanager',about) + +All entries in menu are added in the same order as the calls to +AddFunction. It is possible to customize this presentation by getting +the entries list (salome_pluginsmanager.entries()) and modifying it in +place. For example, you can do that : +salome_pluginsmanager.entries().sort() to order them alphabetically or +salome_pluginsmanager.entries().remove("a") to remove the entry named +"a". + +It is possible to put entries in submenus. You only need to give a +name with / to the entry. for example:: + + salome_pluginsmanager.AddFunction('a/b/About','About SALOME pluginmanager',about) + +will add 2 submenus a and b before creating the entry. + +In short to add a plugin: + + 1. import the python module salome_pluginsmanager (in your + salome_plugins.py or _plugins.py) + + 2. write a function with one argument context (it's an object with 3 + attributes) + + 3. register the function with a call to AddFunction (entry in menu plugins, + tooltip, function) + +context attributes: + + - sg : the SALOME Swig interface + - studyId : the SALOME studyId that must be used to execute the plugin + - study : the SALOME study object that must be used to execute the plugin + +""" + +import os,sys,traceback +from PyQt4 import QtGui +from PyQt4 import QtCore + +import salome + +SEP=":" +if sys.platform == "win32": + SEP = ";" + +# Get SALOME PyQt interface +import SalomePyQt +sgPyQt = SalomePyQt.SalomePyQt() + +# Get SALOME Swig interface +import libSALOME_Swig +sg = libSALOME_Swig.SALOMEGUI_Swig() + +plugins={} +current_plugins_manager=None + +def initialize(module,name,basemenuname,menuname): + if not plugins.has_key(name): + if module: + plugins[name]={} + else: + plugins[name]=[] + if module: + studyId=sg.getActiveStudyId() + if plugins[name].has_key(studyId):return + plugins[name][studyId]=PluginsManager(module,name,basemenuname,menuname) + else: + plugins[name].append(PluginsManager(module,name,basemenuname,menuname)) + +class Context: + def __init__(self,sgpyqt): + self.sg=sgpyqt + self.studyId=salome.sg.getActiveStudyId() + self.study= salome.myStudyManager.GetStudyByID(self.studyId) + +def find_menu(smenu): + lmenus=smenu.split("|") + main=lmenus.pop(0).strip() + menu=sgPyQt.getPopupMenu(main) + return findMenu(lmenus,menu) + +def findMenu(lmenu,menu): + if not lmenu:return menu + m=lmenu.pop(0).strip() + for a in menu.actions(): + if a.menu(): + if a.text() == m: + return findMenu(lmenu,a.menu()) + +PLUGIN_PATH_PATTERN="share/salome/plugins" +MATCH_ENDING_PATTERN="_plugins.py" +from salome.kernel.syshelper import walktree +from salome.kernel.logger import Logger +#from salome.kernel.termcolor import GREEN +logger=Logger("PluginsManager") #,color=GREEN) +# VSR 21/11/2011 : do not show infos in the debug mode +#logger.showDebug() + +class PluginsManager: + def __init__(self,module,name,basemenuname,menuname): + self.name=name + self.basemenuname=basemenuname + self.menuname=menuname + self.module=module + self.registry={} + self.handlers={} + self.entries=[] + self.lasttime=0 + self.plugindirs=[] + self.plugins_files=[] + + # MODULES plugins directory. + # The SALOME modules may provides natively some plugins. These + # MODULES plugins are supposed to be located in the + # installation folder of the module, in the subdirectory + # "share/salome/plugins". We first look for these directories. + for key in os.environ.keys(): + if key.endswith("_ROOT_DIR"): + rootpath=os.environ[key] + dirpath=os.path.join(rootpath,PLUGIN_PATH_PATTERN) + if os.path.isdir(dirpath) and dirpath not in self.plugindirs: + logger.debug("Looking for plugins in the directory %s ..."%dirpath) + walktree(dirpath,self.analyseFile) + + # USER plugins directory + user_dir = os.path.expanduser("~/.config/salome/Plugins") + self.plugindirs.append(user_dir) + logger.info("The user directory %s has been added to plugin paths"%user_dir) + # obsolete: USER plugins directory + # (for compatibility reasons only; new plugins should be stored in ~/.config/salome/Plugins) + user_obsolete_dir = os.path.expanduser("~/.salome/Plugins") + self.plugindirs.append(user_obsolete_dir) + logger.info("The user directory %s has been added to plugin paths (deprecated)"%user_obsolete_dir) + + # APPLI plugins directory + appli=os.getenv("APPLI") + if appli: + appli_dir=os.path.join(os.path.expanduser("~"),appli,"Plugins") + self.plugindirs.append(appli_dir) + logger.info("The APPLI directory %s has been added to plugin paths"%appli_dir) + + #SALOME_PLUGINS_PATH environment variable (list of directories separated by ":") + pluginspath=os.getenv("SALOME_PLUGINS_PATH") + if pluginspath: + for directory in pluginspath.split(SEP): + self.plugindirs.append(directory) + logger.info("The directory %s has been added to plugin paths"%directory) + + self.basemenu = find_menu(self.basemenuname) + + if self.module: + self.menu=QtGui.QMenu(self.menuname) + mid=sgPyQt.createMenu(self.menu.menuAction(),self.basemenuname) + else: + self.menu=QtGui.QMenu(self.menuname,self.basemenu) + self.basemenu.addMenu(self.menu) + + self.menu.menuAction().setVisible(False) + + self.basemenu.connect(self.basemenu, QtCore.SIGNAL("aboutToShow()"), self.importPlugins) + + def analyseFile(self,filename): + """ + This function checks if the specified file is a plugins python + module and add the directory name of this file to the list of + plugin paths. This function is aimed to be used as the callback + function of the walktree algorithm. + """ + if str(filename).endswith(MATCH_ENDING_PATTERN): + dirpath=os.path.dirname(filename) + if dirpath not in self.plugindirs: + self.plugindirs.append(dirpath) + logger.debug("The directory %s has been added to plugin paths"%dirpath) + + def AddFunction(self,name,description,script): + """ Add a plugin function + """ + self.registry[name]=script,description + self.entries.append(name) + + def handler(obj=self,script=script): + try: + script(Context(sgPyQt)) + except: + s=traceback.format_exc() + QtGui.QMessageBox.warning(None,"Exception occured",s) + + self.handlers[name]=handler + + def importPlugins(self): + """Execute the salome_plugins file that contains plugins definition """ + studyId=sg.getActiveStudyId() + if studyId == 0: + self.menu.clear() + self.menu.menuAction().setVisible(False) + return + elif self.lasttime ==0: + salome.salome_init(embedded=1) + + lasttime=0 + + plugins_files=[] + plugins_file_name=self.name+MATCH_ENDING_PATTERN + for directory in self.plugindirs: + plugins_file = os.path.join(directory,plugins_file_name) + if os.path.isfile(plugins_file): + plugins_files.append((directory,plugins_file)) + lasttime=max(lasttime,os.path.getmtime(plugins_file)) + + plugins_files.sort() + + if not plugins_files: + self.registry.clear() + self.handlers.clear() + self.entries=[] + self.lasttime=0 + self.menu.clear() + self.menu.menuAction().setVisible(False) + return + + if self.plugins_files != plugins_files or lasttime > self.lasttime: + global current_plugins_manager + current_plugins_manager=self + self.registry.clear() + self.handlers.clear() + self.entries=[] + self.lasttime=lasttime + for directory,plugins_file in plugins_files: + if directory not in sys.path: + sys.path.insert(0,directory) + try: + execfile(plugins_file,globals(),{}) + except: + logger.fatal("Error while loading plugins from file %s"%plugins_file) + traceback.print_exc() + + self.updateMenu() + + def updateMenu(self): + """Update the Plugins menu""" + self.menu.clear() + for entry in self.entries: + names=entry.split("/") + if len(names) < 1:continue + parentMenu=self.menu + + if len(names) > 1: + #create or get submenus + submenus={} + for action in parentMenu.actions(): + menu=action.menu() + if menu: + submenus[str(menu.title())]=menu + while len(names) > 1: + name=names.pop(0) + if submenus.has_key(name): + amenu=submenus[name] + else: + amenu=QtGui.QMenu(name,parentMenu) + parentMenu.addMenu(amenu) + submenus[name]=amenu + parentMenu=amenu + + name=names.pop(0) + act=parentMenu.addAction(name,self.handlers[entry]) + act.setStatusTip(self.registry[entry][1]) + + self.menu.menuAction().setVisible(True) + +def AddFunction(name,description,script): + """ Add a plugin function + Called by a user to register a function (script) + """ + return current_plugins_manager.AddFunction(name,description,script) + +def entries(): + """ Return the list of entries in menu: can be sorted or modified in place to customize menu content """ + return current_plugins_manager.entries diff --git a/src/Style/resources/Style_msg_fr.ts b/src/Style/resources/Style_msg_fr.ts new file mode 100644 index 000000000..29604c9f4 --- /dev/null +++ b/src/Style/resources/Style_msg_fr.ts @@ -0,0 +1,287 @@ + + + + + Style_PrefDlg + + Quick + Rapide + + + Auto + Auto + + + Base colors + Couleurs de base + + + Additional colors + Couleurs supplémentaires + + + Active + Actif + + + Inactive + Inactif + + + Disabled + Désactivé + + + Window text + Texte de la fenêtre + + + Button + Bouton + + + Light + Clair + + + Midlight + Demi-clair + + + Dark + Foncé + + + Mid + Moyen + + + Text + Texte + + + Bright text + Texte éclairé + + + Button text + Texte du bouton + + + Base + Base + + + Window + Fenêtre + + + Shadow + Ombre + + + Highlight + Surligner + + + Highlighted text + Texte surligné + + + Link + Lien + + + Visited link + Lien visité + + + Alternate base + Base alternative + + + Tooltip base + Base d'infobulle + + + Tooltip text + Texte d'infobulle + + + Border top + Frontière de dessus + + + Border bottom + Frontière de dessous + + + Tab border top + Frontière de dessus de l'onglet + + + Tab border bottom + Frontière de dessous de l'onglet + + + Field light + Champ clair + + + Field dark + Champ foncé + + + Slider + Barre de défilement + + + Lines + Lignes + + + Widget center + Composant central + + + Widget border + Composant de frontière + + + Header + Titre + + + Progress bar + Barre d'avancement + + + Pointer + Pointeur + + + Checked + Coché + + + Table grid + Quadrillage du tableau + + + SALOME style preferences + Préférences de style Salomé + + + Enable SALOME Style + Activer le style Salomé + + + Font + Caractères + + + Type + Type + + + None + Aucun + + + Horizontal + Horizontal + + + Inclined + Incliné + + + Transparency + Transparence + + + Widgets rounding + Arrondi des objets-fenêtres + + + Buttons + Boutons + + + Edit boxes + Champs d'édition + + + Frames + Cadres + + + Sliders + Barres de défilement + + + Anti-aliased borders + Frontières anticrénelées + + + Handle + Poignée + + + Horizontal spacing + Espacement horizontal + + + Vertical spacing + Espacement vertical + + + Splitter handle size + Taille de poignée du diviseur + + + Slider handle size + Taille de poignée de la barre de défilement + + + Widget effect + Effet des composants + + + Highlight widgets + Mettre en valeur les composants + + + Auto raise widgets + Activer les composants automatiquement + + + Colors + Couleurs + + + Properties + Paramètres + + + [ Current ] + [ Actuel ] + + + [ Default ] + [ Défaut ] + + + Delete user theme + Supprimer le thème utilisateur + + + Remove theme %1? + Supprimer le thème %1? + + + Custom schema + Schéma personnalisé + + + diff --git a/src/TOOLSGUI/resources/ToolsGUI_msg_fr.ts b/src/TOOLSGUI/resources/ToolsGUI_msg_fr.ts new file mode 100755 index 000000000..20a97c711 --- /dev/null +++ b/src/TOOLSGUI/resources/ToolsGUI_msg_fr.ts @@ -0,0 +1,222 @@ + + + + + @default + + TOOLS_WRN_WARNING + Avertissement + + + TOOLS_BUT_BROWSE + Naviguer... + + + TOOLS_ERR_ERROR + Erreur + + + TOOLS_ERR_FILE_NOT_EXIST + %1 +Le fichier n'existe pas + + + TOOLS_BUT_OK + &Ok + + + TOOLS_BUT_APPLY + &Appliquer + + + TOOLS_BUT_CLOSE + &Fermer + + + + ToolsGUI_CatalogGeneratorDlg + + TOOLS_MEN_EXPORT + Exporter + + + TOOLS_MEN_IMPORT + Importer + + + TOOLS_VERSION + Version : + + + TOOLS_COMP_NAME + Nom : + + + TOOLS_COMP_TYPE + Type : + + + TOOLS_XML_FILE + XML : + + + TOOLS_PNG_FILE + Icône : + + + TOOLS_SUPPLEMENT + Données supplémentaires du composant + + + TOOLS_AUTHOR + Auteur : + + + TOOLS_COMP_MULTISTD + Multi-étude : + + + TOOLS_COMP_USERNAME + Nom utilisateur : + + + TOOLS_CATALOG_GENERATOR + Générateur du catalogue + + + TOOLS_FILES + Fichiers + + + TOOLS_MEN_IMPORT_PNG + Fichiers PNG ( *.png ) + + + TOOLS_MEN_IMPORT_IDL + Fichiers IDL ( *.idl ) + + + TOOLS_MEN_EXPORT_XML + Fichiers XML ( *.xml ) + + + TOOLS_IDL_FILE + IDL : + + + + ToolsGUI_RegWidget + + TLT_REFRESH_INTERVAL + Fréquence d'actualisation + + + LAB_REFRESH_INTERVAL + Nouvelle fréquence d'actualisation (en secondes) + + + TLT_REGISTRY + Registre + + + MNU_ACTIONS + Actions + + + TB_ACTIONS + Actions + + + MEN_REFRESH + Actualiser + + + STB_REFRESH + Met à jour la liste des composants + + + MEN_INTERVAL + Fréquence d'actualisation... + + + STB_INTERVAL + Changer la fréquence d'actualisation + + + MEN_CLOSE + Fermer + + + STB_CLOSE + Fermer la fenêtre du Registre + + + TAB_RUNNING + En cours + + + TAB_HISTORY + Historique + + + HDR_COMPONENT + Composant + + + HDR_PID + PID + + + HDR_USERNAME + Nom de l'utilisateur + + + HDR_HOSTNAME + Nom de l'hôte + + + HDR_STARTED + Commencé + + + HDR_FINISHED + Terminé + + + HDR_HELLO + Dernier ping + + + ERR_NO_REGISTRY + Erreur: le serveur de registre n'est pas trouvé + + + INFO_SERVICE + Service : %1 + + + INFO_PROCESS + Le procédé ( PID : %1 ) sur la station %2 ( adresse IP : %3 ); lancé par l'utilisateur %4 ( UID : %5 ) au répertoire %6. + + + INFO_STARTED + Commencé : %1 + + + INFO_LAST_PING + Dernier signal : %1 + + + INFO_FINISHED + Fini : %1 + + + INFO_RUNNING + En cours + + + INFO_TIME_DIFF + Le temps de la station %1 est différent du temps du serveur. La différence est %2 secondes. + + + diff --git a/src/VTKViewer/VTKViewer.qrc b/src/VTKViewer/VTKViewer.qrc new file mode 100644 index 000000000..6256bfbf6 --- /dev/null +++ b/src/VTKViewer/VTKViewer.qrc @@ -0,0 +1,14 @@ + + + textures/texture1.dat + textures/texture2.dat + textures/texture3.dat + textures/texture4.dat + textures/texture5.dat + textures/texture6.dat + textures/texture7.dat + textures/texture8.dat + textures/texture9.dat + + + \ No newline at end of file diff --git a/src/VTKViewer/VTKViewer_Algorithm.cxx b/src/VTKViewer/VTKViewer_Algorithm.cxx new file mode 100644 index 000000000..ce57a890d --- /dev/null +++ b/src/VTKViewer/VTKViewer_Algorithm.cxx @@ -0,0 +1,42 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +#include "VTKViewer_Algorithm.h" + +namespace VTK +{ + ActorCollectionCopy::ActorCollectionCopy( vtkActorCollection* theActorCollection ) + { + myActorCollection = vtkActorCollection::New(); + theActorCollection->InitTraversal(); + while(vtkActor* anActor = theActorCollection->GetNextActor()) + myActorCollection->AddItem(anActor); + } + + ActorCollectionCopy::~ActorCollectionCopy() + { + myActorCollection->Delete(); + myActorCollection = NULL; + } + + vtkActorCollection* ActorCollectionCopy::GetActors() const + { + return myActorCollection; + } +} diff --git a/src/VTKViewer/VTKViewer_ArcBuilder.cxx b/src/VTKViewer/VTKViewer_ArcBuilder.cxx new file mode 100644 index 000000000..26df8dbdc --- /dev/null +++ b/src/VTKViewer/VTKViewer_ArcBuilder.cxx @@ -0,0 +1,672 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +// File : VTKViewer_ArcBuilder.cxx +// Author : Roman NIKOLAEV +// Module : GUI +// +#include "VTKViewer_ArcBuilder.h" + +#include +#include + +//VTK includes +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define PRECISION 10e-4 +#define ANGLE_PRECISION 0.5 +//#define _MY_DEBUG_ + +#ifdef _MY_DEBUG_ +#include +#endif + + +bool CheckAngle(const double compare, const double angle){ + if((angle <= compare - ANGLE_PRECISION) || (angle >= compare + ANGLE_PRECISION)) + return true; + else + return false; +} + +//------------------------------------------------------------------------ +/*! + *Class XYZ + *Constructor + */ +XYZ::XYZ(double X, double Y, double Z): + x(X),y(Y),z(Z) {} + +/*! + * Empty Constructor + */ +XYZ::XYZ(){} + +/*! + * Destructor + */ +XYZ::~XYZ() +{} + +/* + * Calculate modulus + */ +double XYZ::Modulus () const { + return sqrt (x * x + y * y + z * z); +} + +//------------------------------------------------------------------------ +/*! + * Class Pnt + * Constructor + */ +Pnt::Pnt(double X, + double Y, + double Z, + double ScalarValue): + coord(X,Y,Z), + scalarValue(ScalarValue) +{ +} + +Pnt::Pnt() +{ +} + +/*! + * Destructor + */ +Pnt::~Pnt() +{ +} + +//------------------------------------------------------------------------ +/*! + * Class Vec + * Constructor + */ +Vec::Vec (const double Xv, + const double Yv, + const double Zv) +{ + double D = sqrt (Xv * Xv + Yv * Yv + Zv * Zv); + if(D != 0) { + coord.SetX(Xv / D); + coord.SetY(Yv / D); + coord.SetZ(Zv / D); + } +} + +/*! + * Destructor + */ +Vec::~Vec(){} + + +/*! + * Calculate angle between vectors in radians + */ +double Vec::AngleBetween(const Vec & Other) +{ + double res; + double numerator = GetXYZ().X()*Other.GetXYZ().X()+GetXYZ().Y()*Other.GetXYZ().Y()+GetXYZ().Z()*Other.GetXYZ().Z(); + double denumerator = GetXYZ().Modulus()*Other.GetXYZ().Modulus(); + double d = numerator/denumerator; + if( d < -1 && d > -1 - PRECISION ) + d = -1; + else if( d > 1 && d < 1 + PRECISION ) + d = 1; + res = acos( d ); + return res; +} + +/*! + * Calculate angle between vectors in degrees + */ +double Vec::AngleBetweenInGrad(const Vec & Other){ + return AngleBetween(Other)*vtkMath::DegreesFromRadians(1.); +} + +/* + * Calculate vector multiplication +*/ +Vec Vec::VectMultiplication(const Vec & Other) const{ + double x = GetXYZ().Y()*Other.GetXYZ().Z() - GetXYZ().Z()*Other.GetXYZ().Y(); + double y = GetXYZ().Z()*Other.GetXYZ().X() - GetXYZ().X()*Other.GetXYZ().Z(); + double z = GetXYZ().X()*Other.GetXYZ().Y() - GetXYZ().Y()*Other.GetXYZ().X(); + Vec *aRes = new Vec(x,y,z); + return *aRes; +} + +/*---------------------Class Plane --------------------------------*/ +/*! + * Constructor + */ +Plane::Plane(const Pnt& thePnt1, const Pnt& thePnt2, const Pnt& thePnt3) +{ + CalculatePlane(thePnt1,thePnt2,thePnt3); +} + +/*! + * Destructor + */ +Plane::~Plane() +{} + +/* + * Return plane normale + */ +Vec Plane::GetNormale() const{ + return Vec(myA,myB,myC); +} + +/* + * Calculate A,B,C coeefs of plane + */ +void Plane::CalculatePlane(const Pnt& thePnt1, const Pnt& thePnt2, const Pnt& thePnt3){ + + double x1 = thePnt1.GetXYZ().X(); + double x2 = thePnt2.GetXYZ().X(); + double x3 = thePnt3.GetXYZ().X(); + + double y1 = thePnt1.GetXYZ().Y(); + double y2 = thePnt2.GetXYZ().Y(); + double y3 = thePnt3.GetXYZ().Y(); + + double z1 = thePnt1.GetXYZ().Z(); + double z2 = thePnt2.GetXYZ().Z(); + double z3 = thePnt3.GetXYZ().Z(); + + myA = y1*(z2 - z3) + y2*(z3 - z1) + y3*(z1 - z2); + myB = z1*(x2 - x3) + z2*(x3 - x1) + z3*(x1 - x2); + myC = x1*(y2 - y3) + x2*(y3 - y1) + x3*(y1 - y2); + +#ifdef _MY_DEBUG_ + cout<<"Plane A: "<Update(); +#ifdef _MY_DEBUG_ + cout<<"Need Rotation!!!"<GetPoint(0,coords); + myPnt1 = Pnt(coords[0],coords[1],coords[2], thePnt1.GetScalarValue()); + aTransformedGrid->GetPoint(1,coords); + myPnt2 = Pnt(coords[0],coords[1],coords[2], thePnt2.GetScalarValue()); + aTransformedGrid->GetPoint(2,coords); + myPnt3 = Pnt(coords[0],coords[1],coords[2], thePnt3.GetScalarValue()); + std::vector aScalarValues; + vtkUnstructuredGrid* anArc = BuildArc(aScalarValues); + vtkUnstructuredGrid* anTransArc; + if(needRotation) { + anTransArc = TransformGrid(anArc,aAxis,-anAngle); + anTransArc->Update(); + } + else + anTransArc = anArc; + + myPoints = anTransArc->GetPoints(); + myScalarValues = aScalarValues; + myStatus = Arc_Done; + } + } + else{ +#ifdef _MY_DEBUG_ + std::cout<<"Points lay on the one line !"<Update(); + myPoints = aGrid->GetPoints(); + + myScalarValues.clear(); + myScalarValues.push_back(thePnt1.GetScalarValue()); + myScalarValues.push_back(thePnt2.GetScalarValue()); + myScalarValues.push_back(thePnt3.GetScalarValue()); + myStatus = Arc_Done; + } +} + +/*! + * Destructor + */ +VTKViewer_ArcBuilder::~VTKViewer_ArcBuilder() +{} + + +/* + * Add to the vtkUnstructuredGrid points from input list + */ +vtkUnstructuredGrid* VTKViewer_ArcBuilder::BuildGrid(const PntList& theList) const +{ + int aListsize = theList.size(); + vtkUnstructuredGrid* aGrid = NULL; + + if(aListsize != 0) { + aGrid = vtkUnstructuredGrid::New(); + vtkPoints* aPoints = vtkPoints::New(); + aPoints->SetNumberOfPoints(aListsize); + + aGrid->Allocate(aListsize); + + PntList::const_iterator it = theList.begin(); + int aCounter = 0; + for(;it != theList.end();it++) { + Pnt aPnt = *it; + aPoints->InsertPoint(aCounter, + aPnt.GetXYZ().X(), + aPnt.GetXYZ().Y(), + aPnt.GetXYZ().Z()); + vtkVertex* aVertex = vtkVertex::New(); + aVertex->GetPointIds()->SetId(0, aCounter); + aGrid->InsertNextCell(aVertex->GetCellType(), aVertex->GetPointIds()); + aCounter++; + aVertex->Delete(); + } + aGrid->SetPoints(aPoints); + aPoints->Delete(); + } + return aGrid; +} + + +vtkUnstructuredGrid* +VTKViewer_ArcBuilder::TransformGrid(vtkUnstructuredGrid* theGrid, + const Vec& theAxis, const double angle) const +{ + vtkTransform *aTransform = vtkTransform::New(); + aTransform->RotateWXYZ(angle, theAxis.GetXYZ().X(), theAxis.GetXYZ().Y(), theAxis.GetXYZ().Z()); + vtkTransformFilter* aTransformFilter = vtkTransformFilter::New(); + aTransformFilter->SetTransform(aTransform); + aTransformFilter->SetInput(theGrid); + aTransform->Delete(); + return aTransformFilter->GetUnstructuredGridOutput(); +} + + +void VTKViewer_ArcBuilder::GetAngle(const double theAngle){ + myAngle = theAngle; +} + +double InterpolateScalarValue(int index, int count, double firstValue, double middleValue, double lastValue) +{ + bool isFirstHalf = index <= count / 2; + double first = isFirstHalf ? firstValue : lastValue; + double last = isFirstHalf ? middleValue : middleValue; + double ratio = (double)index / (double)count; + double position = isFirstHalf ? ratio * 2 : ( 1 - ratio ) * 2; + double value = first + (last - first) * position; + return value; +} + +vtkUnstructuredGrid* VTKViewer_ArcBuilder::BuildArc(std::vector& theScalarValues){ + double x1 = myPnt1.GetXYZ().X(); double x2 = myPnt2.GetXYZ().X(); double x3 = myPnt3.GetXYZ().X(); + double y1 = myPnt1.GetXYZ().Y(); double y2 = myPnt2.GetXYZ().Y(); double y3 = myPnt3.GetXYZ().Y(); + double z = myPnt1.GetXYZ().Z(); //Points on plane || XOY + + + theScalarValues.clear(); + + double K1 = 0; + double K2 = 0; + bool okK1 = false, okK2 = false; + if ( fabs(x2 - x1) > DBL_MIN ) + K1 = (y2 - y1)/(x2 - x1), okK1 = true; + if ( fabs(x3 - x2) > DBL_MIN ) + K2 = (y3 - y2)/(x3 - x2), okK2 = true; + +#ifdef _MY_DEBUG_ + std::cout<<"K1 : "<< K1 < infinity + xCenter = (K1*(y1-y3) + (x1+x2))/2.0; + + else if( !okK1 ) //K1 --> infinity + xCenter = (K2*(y1-y3) - (x2+x3))/(-2.0); + + else + xCenter = (K1*K2*(y1-y3) + K2*(x1+x2) - K1*(x2+x3))/ (2.0*(K2-K1)); + + double yCenter; + + if ( K1 == 0 ) + yCenter = (-1/K2)*(xCenter - (x2+x3)/2.0) + (y2 + y3)/2.0; + else + yCenter = (-1/K1)*(xCenter - (x1+x2)/2.0) + (y1 + y2)/2.0; + +#ifdef _MY_DEBUG_ + double zCenter = z; + std::cout<<"xCenter : "< vtkMath::DoublePi()) + aTotalAngle = 2*vtkMath::DoublePi()-aTotalAngle; + */ + + double aTotalAngle = 0; + IncOrder aOrder = GetArcAngle(angle1,angle2,angle3,&aTotalAngle); + + vtkUnstructuredGrid *aC = NULL; + + if(aTotalAngle > aMaxAngle) { + int nbSteps = int(aTotalAngle/aMaxAngle)+1; + double anIncrementAngle = aTotalAngle/nbSteps; + double aCurrentAngle = angle1; + if(aOrder == VTKViewer_ArcBuilder::MINUS) + aCurrentAngle-=anIncrementAngle; + else + aCurrentAngle+=anIncrementAngle; +#ifdef _MY_DEBUG_ + cout<<"Total angle :"<& VTKViewer_ArcBuilder::GetScalarValues() +{ + return myScalarValues; +} + +VTKViewer_ArcBuilder::IncOrder VTKViewer_ArcBuilder::GetArcAngle( const double& P1, const double& P2, const double& P3,double* Ang){ + IncOrder aResult; + if(P1 < P2 && P2 < P3){ + *Ang = P3 - P1; + aResult = VTKViewer_ArcBuilder::PLUS; + } + else if((P1 < P3 && P3 < P2) || (P2 < P1 && P1 < P3)){ + *Ang = 2*vtkMath::DoublePi() - P3 + P1; + aResult = VTKViewer_ArcBuilder::MINUS; + } + else if((P2 < P3 && P3 < P1) || (P3 < P1 && P1 < P2)){ + *Ang = 2*vtkMath::DoublePi() - P1 + P3; + aResult = VTKViewer_ArcBuilder::PLUS; + } + else if(P3 < P2 && P2 < P1){ + *Ang = P1 - P3; + aResult = VTKViewer_ArcBuilder::MINUS; + } + return aResult; +} + +//------------------------------------------------------------------------ +Pnt CreatePnt(vtkCell* cell, vtkDataArray* scalars, vtkIdType index) +{ + vtkFloatingPointType coord[3]; + cell->GetPoints()->GetPoint(index, coord); + vtkIdType pointId = cell->GetPointId(index); + double scalarValue = scalars ? scalars->GetTuple1(pointId) : 0; + Pnt point(coord[0], coord[1], coord[2], scalarValue); + return point; +} + +//------------------------------------------------------------------------ +vtkIdType Build1DArc(vtkIdType cellId, vtkUnstructuredGrid* input, + vtkPolyData *output,vtkIdType *pts, + vtkFloatingPointType myMaxArcAngle){ + + vtkIdType aResult = -1; + vtkIdType *aNewPoints; + + vtkDataArray* inputScalars = input->GetPointData()->GetScalars(); + vtkDataArray* outputScalars = output->GetPointData()->GetScalars(); + + vtkCell* aCell = input->GetCell(cellId); + //Get All points from input cell + Pnt P0 = CreatePnt( aCell, inputScalars, 0 ); + Pnt P1 = CreatePnt( aCell, inputScalars, 1 ); + Pnt P2 = CreatePnt( aCell, inputScalars, 2 ); + + VTKViewer_ArcBuilder aBuilder(P0,P2,P1,myMaxArcAngle); + if (aBuilder.GetStatus() != VTKViewer_ArcBuilder::Arc_Done) { + return aResult; + } + else{ + vtkPoints* aPoints = aBuilder.GetPoints(); + std::vector aScalarValues = aBuilder.GetScalarValues(); + vtkIdType aNbPts = aPoints->GetNumberOfPoints(); + aNewPoints = new vtkIdType[aNbPts]; + vtkIdType curID; + vtkIdType aCellType = VTK_POLY_LINE; + + aNewPoints[0] = pts[0]; + for(vtkIdType idx = 1; idx < aNbPts-1;idx++) { + curID = output->GetPoints()->InsertNextPoint(aPoints->GetPoint(idx)); + if( outputScalars ) + outputScalars->InsertNextTuple1(aScalarValues[idx]); + aNewPoints[idx] = curID; + } + aNewPoints[aNbPts-1] = pts[1]; + + aResult = output->InsertNextCell(aCellType,aNbPts,aNewPoints); + return aResult; + } +} + +/*! + * Add all points from the input vector theCollection into thePoints. + * Array theIds - it is array with ids of added points. + */ +vtkIdType MergevtkPoints(const std::vector& theCollection, + const std::vector< std::vector >& theScalarCollection, + vtkPoints* thePoints, + std::map& thePntId2ScalarValue, + vtkIdType* &theIds){ + vtkIdType aNbPoints = 0; + vtkIdType anIdCounter = 0; + vtkIdType aNewPntId = 0; + + //Compute number of points + std::vector::const_iterator it = theCollection.begin(); + for(;it != theCollection.end();it++){ + vtkPoints* aPoints = *it; + if(aPoints) { + aNbPoints += aPoints->GetNumberOfPoints()-1; //Because we add all points except last + } + } + it = theCollection.begin(); + std::vector< std::vector >::const_iterator itScalar = theScalarCollection.begin(); + theIds = new vtkIdType[aNbPoints]; + // ..and add all points + for(;it != theCollection.end() && itScalar != theScalarCollection.end(); it++, itScalar++){ + vtkPoints* aPoints = *it; + std::vector aScalarValues = *itScalar; + + if(aPoints){ + for(vtkIdType idx = 0;idx < aPoints->GetNumberOfPoints()-1;idx++){ + aNewPntId = thePoints->InsertNextPoint(aPoints->GetPoint(idx)); + theIds[anIdCounter] = aNewPntId; + thePntId2ScalarValue[ aNewPntId ] = aScalarValues[idx]; + anIdCounter++; + } + } + } + return aNbPoints; +} diff --git a/src/VTKViewer/VTKViewer_ArcBuilder.h b/src/VTKViewer/VTKViewer_ArcBuilder.h new file mode 100644 index 000000000..c5f47a2c4 --- /dev/null +++ b/src/VTKViewer/VTKViewer_ArcBuilder.h @@ -0,0 +1,189 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +#ifndef VTKVIEWER_ARCBUILDER_H +#define VTKVIEWER_ARCBUILDER_H + +#include "VTKViewer.h" +#include +#include +#include + +class vtkCell; +class vtkDataArray; +class vtkPoints; +class vtkPolyData; +class vtkUnstructuredGrid; + +class Pnt; + +typedef std::list PntList; + +vtkIdType MergevtkPoints(const std::vector& theCollection, + const std::vector< std::vector >& theScalarCollection, + vtkPoints* thePoints, + std::map& thePntId2ScalarValue, + vtkIdType* &theIds); + +vtkIdType Build1DArc(vtkIdType cellId, + vtkUnstructuredGrid* input, + vtkPolyData *output, + vtkIdType *pts, + vtkFloatingPointType myMaxArcAngle); + +Pnt CreatePnt(vtkCell* cell, + vtkDataArray* scalars, + vtkIdType index); + +/*! + * Class for represenation coordinates X,Y,Z + */ +class XYZ{ + public: + + XYZ(); + XYZ(double , double , double); + ~XYZ(); + + double X()const {return x;} + double Y()const {return y;} + double Z()const {return z;} + + void SetX(const double X) { x=X; } + void SetY(const double Y) { y=Y; } + void SetZ(const double Z) { z=Z; } + + void Coord (double& X, double& Y, double& Z) const { X = x; Y = y; Z = z; } + + double Modulus () const; + + private: + double x; + double y; + double z; +}; + +/*! + Class for the representation point in the 3D space. +*/ +class Pnt{ + public: + Pnt(); + Pnt(double, double, double, double); + ~Pnt(); + + void Coord (double& X, double& Y, double& Z) const {coord.Coord(X,Y,Z);} + XYZ GetXYZ() const {return coord;} + double GetScalarValue() const { return scalarValue; } + + private: + XYZ coord; + double scalarValue; +}; + +/*! + Class for the representation Vector in the 3D space. +*/ +class Vec{ + public: + + Vec(const double Xv, const double Yv, const double Zv); + ~Vec(); + + XYZ GetXYZ() const {return coord;} + + double AngleBetween(const Vec & Other); + double AngleBetweenInGrad(const Vec & Other); + + Vec VectMultiplication(const Vec & Other) const; + + private: + XYZ coord; +}; + +/*! + Class for the representation plane in the 3D. +*/ +class Plane{ + + public: + Plane(const Pnt& thePnt1, const Pnt& thePnt2, const Pnt& thePnt3); + ~Plane(); + + double A() const {return myA;} + double B() const {return myB;} + double C() const {return myC;} + + Vec GetNormale() const; + + private: + void CalculatePlane(const Pnt& thePnt1, const Pnt& thePnt2, const Pnt& thePnt3); + + private: + double myA; + double myB; + double myC; +}; + + +class VTKViewer_ArcBuilder{ + public: + enum ArcStatus {Arc_Done=0, Arc_Error}; + VTKViewer_ArcBuilder(const Pnt& thePnt1, + const Pnt& thePnt2, + const Pnt& thePnt3, + double theAngle); + + ~VTKViewer_ArcBuilder(); + + Vec GetNormale(); + + ArcStatus GetStatus(){return myStatus;} + + void GetAngle(const double theAngle); + + static double GetPointAngleOnCircle(const double theXCenter, const double theYCenter, + const double theXPoint, const double theYPoint); + + vtkPoints* GetPoints(); + const std::vector& GetScalarValues(); + + private: + + enum IncOrder{MINUS=0,PLUS}; + + vtkUnstructuredGrid* BuildGrid(const PntList& theList) const; + vtkUnstructuredGrid* TransformGrid(vtkUnstructuredGrid* theGrid, const Vec& theAxis, const double angle) const; + vtkUnstructuredGrid* BuildArc(std::vector& theScalarValues); + IncOrder GetArcAngle( const double& P1, const double& P2, const double& P3, double* Ang); + + + + private: + Pnt myPnt1; + Pnt myPnt2; + Pnt myPnt3; + + double myAngle; + ArcStatus myStatus; + vtkPoints* myPoints; + std::vector myScalarValues; +}; + +#endif //VTKVIEWER_ARCBUILDER_H diff --git a/src/VTKViewer/VTKViewer_CellCenters.cxx b/src/VTKViewer/VTKViewer_CellCenters.cxx new file mode 100644 index 000000000..0aa717bd2 --- /dev/null +++ b/src/VTKViewer/VTKViewer_CellCenters.cxx @@ -0,0 +1,184 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 +// + +#include "VTKViewer_CellCenters.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +vtkCxxRevisionMacro(VTKViewer_CellCenters, "$Revision$"); +vtkStandardNewMacro(VTKViewer_CellCenters); + +/*! + * Class : VTKViewer_CellCenters + * Description : Filter computing geometrical centers of given cells + * (differs from native vtk filter by small fix for VTK_CONVEX_POINT_SET cells) + */ + +/*! + Constructor +*/ +VTKViewer_CellCenters::VTKViewer_CellCenters() +{ +} + +/*! + Redefined main method +*/ +int VTKViewer_CellCenters::RequestData( + vtkInformation *vtkNotUsed(request), + vtkInformationVector **inputVector, + vtkInformationVector *outputVector) +{ + // get the info objects + vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); + vtkInformation *outInfo = outputVector->GetInformationObject(0); + + // get the input and ouptut + vtkDataSet *input = vtkDataSet::SafeDownCast( + inInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkPolyData *output = vtkPolyData::SafeDownCast( + outInfo->Get(vtkDataObject::DATA_OBJECT())); + + vtkIdType cellId, numCells; + int subId; + vtkCellData *inCD; + vtkPointData *outPD; + vtkPoints *newPts; + vtkCell *cell; + double x[3], pcoords[3]; + double *weights; + + inCD=input->GetCellData(); + outPD=output->GetPointData(); + + if ( (numCells = input->GetNumberOfCells()) < 1 ) + { + vtkWarningMacro(<<"No cells to generate center points for"); + return 1; + } + + newPts = vtkPoints::New(); + newPts->SetNumberOfPoints(numCells); + weights = new double [input->GetMaxCellSize()]; + + int abort=0; + vtkIdType progressInterval = numCells/10 + 1; + int hasEmptyCells = 0; + for (cellId=0; cellId < numCells && !abort; cellId++) + { + if ( ! (cellId % progressInterval) ) + { + vtkDebugMacro(<<"Processing #" << cellId); + this->UpdateProgress (0.5*cellId/numCells); + abort = this->GetAbortExecute(); + } + + cell = input->GetCell(cellId); + if (cell->GetCellType() != VTK_EMPTY_CELL) + { + // fix for VTK_CONVEX_POINT_SET cells + if (cell->GetCellType() == VTK_CONVEX_POINT_SET ) + { + x[0] = x[1] = x[2] = 0; + vtkPoints* aPoints = cell->GetPoints(); + int aNbPoints = aPoints->GetNumberOfPoints(); + for( int i = 0; i < aNbPoints; i++ ) + { + double aCoord[3]; + aPoints->GetPoint( i, aCoord ); + x[0] += aCoord[0]; + x[1] += aCoord[1]; + x[2] += aCoord[2]; + } + x[0] /= aNbPoints; + x[1] /= aNbPoints; + x[2] /= aNbPoints; + } + else + { + subId = cell->GetParametricCenter(pcoords); + cell->EvaluateLocation(subId, pcoords, x, weights); + } + newPts->SetPoint(cellId,x); + } + else + { + hasEmptyCells = 1; + } + } + + if ( this->VertexCells ) + { + vtkIdType pts[1]; + vtkCellData *outCD=output->GetCellData(); + vtkCellArray *verts = vtkCellArray::New(); + verts->Allocate(verts->EstimateSize(1,numCells),1); + + for (cellId=0; cellId < numCells && !abort; cellId++) + { + if ( ! (cellId % progressInterval) ) + { + vtkDebugMacro(<<"Processing #" << cellId); + this->UpdateProgress (0.5+0.5*cellId/numCells); + abort = this->GetAbortExecute(); + } + + cell = input->GetCell(cellId); + if (cell->GetCellType() != VTK_EMPTY_CELL) + { + pts[0] = cellId; + verts->InsertNextCell(1,pts); + } + } + + output->SetVerts(verts); + verts->Delete(); + if (!hasEmptyCells) + { + outCD->PassData(inCD); //only if verts are generated + } + } + + // clean up and update output + output->SetPoints(newPts); + newPts->Delete(); + + if (!hasEmptyCells) + { + outPD->PassData(inCD); //because number of points = number of cells + } + if (weights) + { + delete [] weights; + } + + return 1; +} diff --git a/src/VTKViewer/VTKViewer_CellCenters.h b/src/VTKViewer/VTKViewer_CellCenters.h new file mode 100644 index 000000000..6a37f1585 --- /dev/null +++ b/src/VTKViewer/VTKViewer_CellCenters.h @@ -0,0 +1,60 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 +// + +#ifndef VTKVIEWER_CELLCENTERS_H +#define VTKVIEWER_CELLCENTERS_H + +#include "VTKViewer.h" + +#include + +#ifdef WIN32 +#pragma warning ( disable:4251 ) +#endif + +/*! + * Class : VTKViewer_CellCenters + * Description : Filter computing geometrical centers of given cells + * (differs from native vtk filter by small fix for VTK_CONVEX_POINT_SET cells) + */ +class VTKVIEWER_EXPORT VTKViewer_CellCenters : public vtkCellCenters +{ +public: + vtkTypeRevisionMacro(VTKViewer_CellCenters,vtkCellCenters); + + static VTKViewer_CellCenters *New(); + +protected: + VTKViewer_CellCenters(); + + virtual int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); + +private: + VTKViewer_CellCenters(const VTKViewer_CellCenters&); // Not implemented. + void operator=(const VTKViewer_CellCenters&); // Not implemented. +}; + +#ifdef WIN32 +#pragma warning ( default:4251 ) +#endif + +#endif diff --git a/src/VTKViewer/VTKViewer_DataSetMapper.cxx b/src/VTKViewer/VTKViewer_DataSetMapper.cxx new file mode 100644 index 000000000..fad3d9179 --- /dev/null +++ b/src/VTKViewer/VTKViewer_DataSetMapper.cxx @@ -0,0 +1,111 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +#include "VTKViewer_DataSetMapper.h" +#include "VTKViewer_PolyDataMapper.h" + +#include +#include + +vtkCxxRevisionMacro(VTKViewer_DataSetMapper, "Revision$"); +vtkStandardNewMacro(VTKViewer_DataSetMapper); + +//---------------------------------------------------------------------------- +VTKViewer_DataSetMapper::VTKViewer_DataSetMapper() +{ + this->MarkerEnabled = false; + this->MarkerType = VTK::MT_NONE; + this->MarkerScale = VTK::MS_NONE; + this->MarkerId = 0; +} + +//---------------------------------------------------------------------------- +VTKViewer_DataSetMapper::~VTKViewer_DataSetMapper() +{ +} + +//---------------------------------------------------------------------------- +void VTKViewer_DataSetMapper::Render(vtkRenderer *ren, vtkActor *act) +{ + // just to create VTKViewer_PolyDataMapper instead of vtkPolyDataMapper + if( this->PolyDataMapper == NULL ) + { + vtkDataSetSurfaceFilter *gf = vtkDataSetSurfaceFilter::New(); + VTKViewer_PolyDataMapper *pm = VTKViewer_PolyDataMapper::New(); + pm->SetInput(gf->GetOutput()); + + pm->SetMarkerEnabled( this->MarkerEnabled ); + if( this->MarkerType != VTK::MT_USER ) + pm->SetMarkerStd( this->MarkerType, this->MarkerScale ); + else + pm->SetMarkerTexture( this->MarkerId, this->MarkerTexture ); + + this->GeometryExtractor = gf; + this->PolyDataMapper = pm; + } + vtkDataSetMapper::Render(ren, act); +} + +//----------------------------------------------------------------------------- +void VTKViewer_DataSetMapper::SetMarkerEnabled( bool theMarkerEnabled ) +{ + this->MarkerEnabled = theMarkerEnabled; + if( this->PolyDataMapper ) + if( VTKViewer_PolyDataMapper* aMapper = dynamic_cast( this->PolyDataMapper ) ) + aMapper->SetMarkerEnabled( theMarkerEnabled ); +} + +//---------------------------------------------------------------------------- +void VTKViewer_DataSetMapper::SetMarkerStd( VTK::MarkerType theMarkerType, VTK::MarkerScale theMarkerScale ) +{ + this->MarkerType = theMarkerType; + this->MarkerScale = theMarkerScale; + if( this->PolyDataMapper ) + if( VTKViewer_PolyDataMapper* aMapper = dynamic_cast( this->PolyDataMapper ) ) + aMapper->SetMarkerStd( theMarkerType, theMarkerScale ); +} + +//---------------------------------------------------------------------------- +void VTKViewer_DataSetMapper::SetMarkerTexture( int theMarkerId, VTK::MarkerTexture theMarkerTexture ) +{ + this->MarkerType = VTK::MT_USER; + this->MarkerId = theMarkerId; + this->MarkerTexture = theMarkerTexture; + if( this->PolyDataMapper ) + if( VTKViewer_PolyDataMapper* aMapper = dynamic_cast( this->PolyDataMapper ) ) + aMapper->SetMarkerTexture( theMarkerId, theMarkerTexture ); +} + +//----------------------------------------------------------------------------- +VTK::MarkerType VTKViewer_DataSetMapper::GetMarkerType() +{ + return this->MarkerType; +} + +//----------------------------------------------------------------------------- +VTK::MarkerScale VTKViewer_DataSetMapper::GetMarkerScale() +{ + return this->MarkerScale; +} + +//----------------------------------------------------------------------------- +int VTKViewer_DataSetMapper::GetMarkerTexture() +{ + return this->MarkerId; +} diff --git a/src/VTKViewer/VTKViewer_DataSetMapper.h b/src/VTKViewer/VTKViewer_DataSetMapper.h new file mode 100644 index 000000000..cbdfbbbff --- /dev/null +++ b/src/VTKViewer/VTKViewer_DataSetMapper.h @@ -0,0 +1,71 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +#ifndef VTKViewer_DATASETMAPPER_H +#define VTKViewer_DATASETMAPPER_H + +#include "VTKViewer.h" +#include "VTKViewer_MarkerDef.h" + +#include + +class VTKVIEWER_EXPORT VTKViewer_DataSetMapper : public vtkDataSetMapper +{ +public: + static VTKViewer_DataSetMapper *New(); + vtkTypeRevisionMacro(VTKViewer_DataSetMapper,vtkDataSetMapper); + + //! Set point marker enabled + void SetMarkerEnabled( bool ); + + //! Set standard point marker + void SetMarkerStd( VTK::MarkerType, VTK::MarkerScale ); + + //! Set custom point marker + void SetMarkerTexture( int, VTK::MarkerTexture ); + + //! Get type of the point marker + VTK::MarkerType GetMarkerType(); + + //! Get scale of the point marker + VTK::MarkerScale GetMarkerScale(); + + //! Get texture identifier of the point marker + int GetMarkerTexture(); + + //! Implement superclass render method. + void Render(vtkRenderer *ren, vtkActor *act); + +protected: + VTKViewer_DataSetMapper(); + ~VTKViewer_DataSetMapper(); + +private: + VTKViewer_DataSetMapper(const VTKViewer_DataSetMapper&); // Not implemented. + void operator=(const VTKViewer_DataSetMapper&); // Not implemented. + +private: + bool MarkerEnabled; + VTK::MarkerType MarkerType; + VTK::MarkerScale MarkerScale; + int MarkerId; + VTK::MarkerTexture MarkerTexture; +}; + +#endif diff --git a/src/VTKViewer/VTKViewer_FramedTextActor.cxx b/src/VTKViewer/VTKViewer_FramedTextActor.cxx new file mode 100644 index 000000000..328d7fd07 --- /dev/null +++ b/src/VTKViewer/VTKViewer_FramedTextActor.cxx @@ -0,0 +1,529 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +#include "VTKViewer_FramedTextActor.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#define TEXT_MARGIN 4 +#define OFFSET_SPACING 2 + +//================================================================== +vtkCxxRevisionMacro(VTKViewer_FramedTextActor, "$Revision$"); +vtkStandardNewMacro(VTKViewer_FramedTextActor); + +//================================================================== +// function : VTKViewer_FramedTextActor +// purpose : +//================================================================== +VTKViewer_FramedTextActor::VTKViewer_FramedTextActor() +{ + PositionCoordinate->SetCoordinateSystemToNormalizedViewport(); + + myTransparency=0.; + myBar = vtkPolyData::New(); + myBarMapper = vtkPolyDataMapper2D::New(); + myBarMapper->SetInput(myBar); + myBarActor = vtkActor2D::New(); + myBarActor->SetMapper(myBarMapper); + myBarActor->GetProperty()->SetOpacity(1.-myTransparency); + myBarActor->GetProperty()->SetColor(.5, .5, .5); + + myTextProperty = vtkTextProperty::New(); + myTextProperty->SetFontSize(12); + myTextProperty->SetBold(0); + myTextProperty->SetItalic(0); + myTextProperty->SetShadow(1); + myTextProperty->SetFontFamilyToArial(); + + myTextMapper=vtkTextMapper::New(); + myTextMapper->SetInput(""); + myTextMapper->GetTextProperty()->ShallowCopy(myTextProperty); + myTextActor=vtkActor2D::New(); + myTextActor->SetMapper(myTextMapper); + + myBarActor->SetVisibility(1); + myTextActor->SetVisibility(1); + myBarActor->SetPickable(0); + myTextActor->SetPickable(0); + + myModePosition = BelowPoint; + myLayoutType = Vertical; + + for(int i=0; i<4; i++) { + myWorldPoint[i] = 0.; + } + myDistance=10.; + + myTextMargin = TEXT_MARGIN; + + myHorizontalOffset = 0; + myVerticalOffset = 0; + + myMoveFrameFlag = 0; +} + +//================================================================== +// function : ~ +// purpose : +//================================================================== +VTKViewer_FramedTextActor::~VTKViewer_FramedTextActor() +{ + myTextActor->Delete(); + myTextMapper->Delete(); + myTextProperty->Delete(); + myBarActor->Delete(); + myBarMapper->Delete(); + myBar->Delete(); +} + +//================================================================== +// function : SetVisibility +// purpose : +//================================================================== +void VTKViewer_FramedTextActor::SetVisibility (int theVisibility) +{ + myBarActor->SetVisibility(theVisibility); + myTextActor->SetVisibility(theVisibility); +} + +//================================================================== +// function : GetVisibility +// purpose : +//================================================================== +int VTKViewer_FramedTextActor::GetVisibility() +{ + return myBarActor->GetVisibility(); +} + +//================================================================== +// function : SetPickable +// purpose : +//================================================================== +void VTKViewer_FramedTextActor::SetPickable (int thePickability) +{ + myBarActor->SetPickable(thePickability); + myTextActor->SetPickable(thePickability); +} + +//================================================================== +// function : GetPickable +// purpose : +//================================================================== +int VTKViewer_FramedTextActor::GetPickable() +{ + return myBarActor->GetPickable(); +} + +//================================================================== +// function : GetSize +// purpose : +//================================================================== +void VTKViewer_FramedTextActor::GetSize(vtkRenderer* theRenderer, int theSize[2]) const +{ + myTextMapper->GetSize(theRenderer, theSize); + theSize[0] = theSize[0] + 2 * GetTextMargin() + OFFSET_SPACING; + theSize[1] = theSize[1] + 2 * GetTextMargin() + OFFSET_SPACING; +} + +//================================================================== +// function : SetForegroundColor +// purpose : +//================================================================== +void VTKViewer_FramedTextActor::SetForegroundColor(const vtkFloatingPointType r, + const vtkFloatingPointType g, + const vtkFloatingPointType b) +{ + myTextProperty->SetColor(r, g, b); + myTextMapper->GetTextProperty()->ShallowCopy(myTextProperty); + Modified(); +} + +//================================================================== +// function : GetForegroundColor +// purpose : +//================================================================== +void VTKViewer_FramedTextActor::GetForegroundColor(vtkFloatingPointType& r, + vtkFloatingPointType& g, + vtkFloatingPointType& b) +{ + vtkFloatingPointType aColor[3]; + myTextProperty->GetColor(aColor); + r = aColor[0]; + g = aColor[1]; + b = aColor[2]; +} + +//================================================================== +// function : SetBackgroundColor +// purpose : +//================================================================== +void VTKViewer_FramedTextActor::SetBackgroundColor(const vtkFloatingPointType r, + const vtkFloatingPointType g, + const vtkFloatingPointType b) +{ + myBarActor->GetProperty()->SetColor(r, g, b); + Modified(); +} + +//================================================================== +// function : GetBackgroundColor +// purpose : +//================================================================== +void VTKViewer_FramedTextActor::GetBackgroundColor(vtkFloatingPointType& r, + vtkFloatingPointType& g, + vtkFloatingPointType& b) +{ + vtkFloatingPointType aColor[3]; + myBarActor->GetProperty()->GetColor(aColor); + r = aColor[0]; + g = aColor[1]; + b = aColor[2]; +} + +//================================================================== +// function : SetTransparency +// purpose : +//================================================================== +void VTKViewer_FramedTextActor::SetTransparency(const vtkFloatingPointType theTransparency) +{ + if (theTransparency>=0. && theTransparency<=1.){ + myTransparency=theTransparency; + myBarActor->GetProperty()->SetOpacity(1.-myTransparency); + Modified(); + } +} + +//================================================================== +// function : GetTransparency +// purpose : +//================================================================== +vtkFloatingPointType VTKViewer_FramedTextActor::GetTransparency()const +{ + return myTransparency; +} + +//================================================================== +// function : SetTextMargin +// purpose : +//================================================================== +void VTKViewer_FramedTextActor::SetTextMargin(const int theMargin) +{ + if( theMargin >= 0 ) { + myTextMargin = theMargin; + Modified(); + } +} + +//================================================================== +// function : GetTextMargin +// purpose : +//================================================================== +int VTKViewer_FramedTextActor::GetTextMargin() const +{ + return myTextMargin; +} + +//================================================================== +// function : SetOffset +// purpose : +//================================================================== +void VTKViewer_FramedTextActor::SetOffset(const int theOffset[2]) +{ + myHorizontalOffset = theOffset[0]; + myVerticalOffset = theOffset[1]; + Modified(); +} + +//================================================================== +// function : SetText +// purpose : +//================================================================== +void VTKViewer_FramedTextActor::SetText(const char* theText) +{ + // remove whitespaces from from the start and the end + // additionally, consider a case of multi-string text + QString aString(theText); + + QStringList aTrimmedStringList; + QStringList aStringList = aString.split("\n"); + QStringListIterator anIter(aStringList); + while(anIter.hasNext()) + aTrimmedStringList.append(anIter.next().trimmed()); + + myTextMapper->SetInput(aTrimmedStringList.join("\n").toLatin1().constData()); + Modified(); +} + +//================================================================== +// function : GetText +// purpose : +//================================================================== +char* VTKViewer_FramedTextActor::GetText() +{ + return myTextMapper->GetInput(); +} + +//================================================================== +// function : SetModePosition +// purpose : +//================================================================== +void VTKViewer_FramedTextActor::SetModePosition(const int theMode) +{ + myModePosition = theMode; + Modified(); +} + +//================================================================== +// function : GetModePosition +// purpose : +//================================================================== +int VTKViewer_FramedTextActor::GetModePosition()const +{ + return myModePosition; +} + +//================================================================== +// function : SetLayoutType +// purpose : +//================================================================== +void VTKViewer_FramedTextActor::SetLayoutType(const int theType) +{ + myLayoutType = theType; + Modified(); +} + +//================================================================== +// function : GetLayoutType +// purpose : +//================================================================== +int VTKViewer_FramedTextActor::GetLayoutType() const +{ + return myLayoutType; +} + +//================================================================== +// function : SetWorldPoint +// purpose : +//================================================================== +void VTKViewer_FramedTextActor::SetWorldPoint(const vtkFloatingPointType theWorldPoint[4]) +{ + for(int i = 0; i<4; ++i) { + myWorldPoint[i] = theWorldPoint[i]; + } + Modified(); +} + +//================================================================== +// function : GetWorldPoint +// purpose : +//================================================================== +const vtkFloatingPointType* VTKViewer_FramedTextActor::GetWorldPoint()const +{ + return myWorldPoint; +} + +//================================================================== +// function : SetDistance +// purpose : +//================================================================== +void VTKViewer_FramedTextActor::SetDistance(const vtkFloatingPointType theDistance) +{ + myDistance=theDistance; +} + +//================================================================== +// function : GetDistance +// purpose : +//================================================================== +vtkFloatingPointType VTKViewer_FramedTextActor::GetDistance()const +{ + return myDistance; +} + +//================================================================== +// function : SetMoveFrameFlag +// purpose : If moveFrameFlag is true, then frame with text is moved +// under world point +//================================================================== +void VTKViewer_FramedTextActor::SetMoveFrameFlag(const int theMoveFrameFlag) +{ + if(myMoveFrameFlag != theMoveFrameFlag) { + myMoveFrameFlag = theMoveFrameFlag; + Modified(); + } +} + +//================================================================== +// function : GetDistance +// purpose : +//================================================================== +int VTKViewer_FramedTextActor::GetMoveFrameFlag() const +{ + return myMoveFrameFlag; +} + + +//================================================================== +// function : ReleaseGraphicsResources +// purpose : +//================================================================== +void VTKViewer_FramedTextActor::ReleaseGraphicsResources(vtkWindow *win) +{ + myTextActor->ReleaseGraphicsResources(win); + myBarActor->ReleaseGraphicsResources(win); +} + +//================================================================== +// function : RenderOverlay +// purpose : +//================================================================== +int VTKViewer_FramedTextActor::RenderOverlay(vtkViewport *viewport) +{ + int renderedSomething = 0; + myBarActor->RenderOverlay(viewport); + renderedSomething +=myTextActor->RenderOverlay(viewport); + return renderedSomething; +} + +//================================================================== +// function : RenderOpaqueGeometry +// purpose : +//================================================================== +int +VTKViewer_FramedTextActor +::RenderOpaqueGeometry(vtkViewport *theViewport) +{ + int anIsRenderedSomething = 0; + + int* aViewportSize = theViewport->GetSize(); + int aViewPortWidth = aViewportSize[0]; + int aViewPortHeight = aViewportSize[1]; + if(aViewPortWidth == 1 || aViewPortHeight == 1) + return anIsRenderedSomething; + + if(!myTextMapper->GetInput()) + return anIsRenderedSomething; + + myBar->Initialize(); + + int aNbPoints = 4; + vtkPoints *aPoints = vtkPoints::New(); + aPoints->SetNumberOfPoints(aNbPoints); + myBar->SetPoints(aPoints); + aPoints->Delete(); + + vtkCellArray *aPolys = vtkCellArray::New(); + aPolys->Allocate(aPolys->EstimateSize(1,4)); + vtkIdType aPointsIds[4] = {0, 1, 3, 2}; + aPolys->InsertNextCell(4,aPointsIds); + myBar->SetPolys(aPolys); + aPolys->Delete(); + + int aTextSize[2]; + myTextMapper->GetSize(theViewport, aTextSize); + int aBarWidth = aTextSize[0]; + int aBarHeight = aTextSize[1]; + + int aTextMargin = GetTextMargin(); + + vtkFloatingPointType xMin = 0.0; + vtkFloatingPointType xMax = 0.0; + vtkFloatingPointType yMin = -aBarHeight/2 - aTextMargin; + vtkFloatingPointType yMax = aBarHeight/2 + aTextMargin; + + int aHorizontalOffset = GetLayoutType() == Horizontal ? myHorizontalOffset : 0; + int aVerticalOffset = GetLayoutType() == Vertical ? myVerticalOffset : 0; + + if( myModePosition == BelowPoint ) + { + theViewport->SetWorldPoint(myWorldPoint); + theViewport->WorldToDisplay(); + + vtkFloatingPointType aSelectionPoint[3]; + theViewport->GetDisplayPoint(aSelectionPoint); + vtkFloatingPointType u = aSelectionPoint[0]; + vtkFloatingPointType v = aSelectionPoint[1] - myDistance; + if(myMoveFrameFlag) + v -= aBarHeight/2.; + theViewport->ViewportToNormalizedViewport(u, v); + PositionCoordinate->SetValue(u, v); + + myTextProperty->SetJustificationToCentered(); + + xMin = -aBarWidth/2 - aTextMargin; + xMax = aBarWidth/2 + aTextMargin; + } + else // except BelowPoint, only TopLeft and TopRight modes are supported at this moment + { + vtkFloatingPointType x = 0, xOffset = aHorizontalOffset + aTextMargin + OFFSET_SPACING; + vtkFloatingPointType y = 0, yOffset = aVerticalOffset + aTextMargin + OFFSET_SPACING; + + if( myModePosition == TopLeft ) + { + x = xOffset; + y = aViewPortHeight - yOffset - aBarHeight/2; + myTextProperty->SetJustificationToLeft(); + + xMin = - aTextMargin; + xMax = aBarWidth + aTextMargin; + } + else if( myModePosition == TopRight ) + { + x = aViewPortWidth - xOffset; + y = aViewPortHeight - yOffset - aBarHeight/2; + myTextProperty->SetJustificationToRight(); + + xMin = -aBarWidth - aTextMargin; + xMax = aTextMargin; + } + + PositionCoordinate->SetValue(x / (vtkFloatingPointType)aViewPortWidth, + y / (vtkFloatingPointType)aViewPortHeight); + } + + aPoints->SetPoint(0, xMin, yMax, 0.0); + aPoints->SetPoint(1, xMin, yMin, 0.0); + aPoints->SetPoint(2, xMax, yMax, 0.0); + aPoints->SetPoint(3, xMax, yMin, 0.0); + + myTextProperty->SetVerticalJustificationToCentered(); + + myTextMapper->GetTextProperty()->ShallowCopy(myTextProperty); + myBarActor ->GetPositionCoordinate()->SetReferenceCoordinate(PositionCoordinate); + myTextActor->GetPositionCoordinate()->SetReferenceCoordinate(PositionCoordinate); + + myBuildTime.Modified(); + + return anIsRenderedSomething; +} diff --git a/src/VTKViewer/VTKViewer_FramedTextActor.h b/src/VTKViewer/VTKViewer_FramedTextActor.h new file mode 100644 index 000000000..0a3e95be3 --- /dev/null +++ b/src/VTKViewer/VTKViewer_FramedTextActor.h @@ -0,0 +1,131 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +#ifndef VTKVIEWER_FRAMEDTEXTACTOR_H +#define VTKVIEWER_FRAMEDTEXTACTOR_H + +#include "VTKViewer.h" + +#include + +class vtkPolyData; +class vtkPolyDataMapper2D; +class vtkRenderer; +class vtkTimeStamp; +class vtkTextMapper; +class vtkTextProperty; +class vtkViewport; +class vtkWindow; + +class VTKVIEWER_EXPORT VTKViewer_FramedTextActor : public vtkActor2D +{ +public: + enum ModePosition { BelowPoint = 0, TopLeft, TopRight, BottomLeft, BottomRight }; + enum LayoutType { Vertical = 0, Horizontal }; + +public: + vtkTypeRevisionMacro(VTKViewer_FramedTextActor,vtkActor2D); + static VTKViewer_FramedTextActor *New(); + + virtual int RenderOpaqueGeometry(vtkViewport*); + virtual int RenderTranslucentGeometry(vtkViewport*) { return 0; } + virtual int RenderOverlay(vtkViewport*); + virtual void ReleaseGraphicsResources(vtkWindow*); + + virtual void SetVisibility(int); + virtual int GetVisibility(); + virtual void SetPickable(int); + virtual int GetPickable(); + + virtual void GetSize(vtkRenderer* theRenderer, int theSize[2]) const; + + void SetText(const char* theText); + char* GetText(); + + void SetModePosition(const int theMode); + int GetModePosition() const; + + void SetLayoutType(const int theType); + int GetLayoutType() const; + + void SetWorldPoint(const vtkFloatingPointType theWorldPoint[4]); + const vtkFloatingPointType* GetWorldPoint() const; + + void SetDistance(const vtkFloatingPointType theDistance); + vtkFloatingPointType GetDistance() const; + + void SetMoveFrameFlag(const int flag); + int GetMoveFrameFlag() const; + + void SetForegroundColor(const vtkFloatingPointType r, + const vtkFloatingPointType g, + const vtkFloatingPointType b); + void GetForegroundColor(vtkFloatingPointType& r, + vtkFloatingPointType& g, + vtkFloatingPointType& b); + + void SetBackgroundColor(const vtkFloatingPointType r, + const vtkFloatingPointType g, + const vtkFloatingPointType b); + void GetBackgroundColor(vtkFloatingPointType& r, + vtkFloatingPointType& g, + vtkFloatingPointType& b); + + void SetTransparency(const vtkFloatingPointType theTransparency); + vtkFloatingPointType GetTransparency() const; + + void SetTextMargin(const int theMargin); + int GetTextMargin() const; + + void SetOffset(const int theOffset[2]); + +protected: + VTKViewer_FramedTextActor(); + ~VTKViewer_FramedTextActor(); + +protected: + vtkPolyData* myBar; + vtkPolyDataMapper2D* myBarMapper; + vtkActor2D* myBarActor; + + vtkTextProperty* myTextProperty; + vtkTextMapper* myTextMapper; + vtkActor2D* myTextActor; + + vtkTimeStamp myBuildTime; + + int myModePosition; + int myLayoutType; + int myMoveFrameFlag; + + vtkFloatingPointType myWorldPoint[4]; + vtkFloatingPointType myDistance; + vtkFloatingPointType myTransparency; + + int myTextMargin; + + int myHorizontalOffset; + int myVerticalOffset; + +private: + VTKViewer_FramedTextActor(const VTKViewer_FramedTextActor&); // Not implemented. + void operator=(const VTKViewer_FramedTextActor&); // Not implemented. +}; + +#endif diff --git a/src/VTKViewer/VTKViewer_MarkerDef.h b/src/VTKViewer/VTKViewer_MarkerDef.h new file mode 100644 index 000000000..1cff56cab --- /dev/null +++ b/src/VTKViewer/VTKViewer_MarkerDef.h @@ -0,0 +1,65 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +#ifndef VTKVIEWER_MARKERDEF_H +#define VTKVIEWER_MARKERDEF_H + +#include +#include +#include + +namespace VTK +{ + //! Type of standard marker for advanced rendering of vtk points + typedef int MarkerType; + const MarkerType MT_NONE = 0; + const MarkerType MT_POINT = 1; + const MarkerType MT_PLUS = 2; + const MarkerType MT_STAR = 3; + const MarkerType MT_O = 4; + const MarkerType MT_X = 5; + const MarkerType MT_O_POINT = 6; + const MarkerType MT_O_PLUS = 7; + const MarkerType MT_O_STAR = 8; + const MarkerType MT_O_X = 9; + const MarkerType MT_USER = 10; + + //! Scale of standard marker for advanced rendering of vtk points + typedef int MarkerScale; + const MarkerScale MS_NONE = 0; + const MarkerScale MS_10 = 1; + const MarkerScale MS_15 = 2; + const MarkerScale MS_20 = 3; + const MarkerScale MS_25 = 4; + const MarkerScale MS_30 = 5; + const MarkerScale MS_35 = 6; + const MarkerScale MS_40 = 7; + const MarkerScale MS_45 = 8; + const MarkerScale MS_50 = 9; + const MarkerScale MS_55 = 10; + const MarkerScale MS_60 = 11; + const MarkerScale MS_65 = 12; + const MarkerScale MS_70 = 13; + + typedef std::list MarkerTexture; + typedef std::pair MarkerData; + typedef std::map MarkerMap; +} + +#endif diff --git a/src/VTKViewer/VTKViewer_MarkerDlg.cxx b/src/VTKViewer/VTKViewer_MarkerDlg.cxx new file mode 100644 index 000000000..6f6d9ea57 --- /dev/null +++ b/src/VTKViewer/VTKViewer_MarkerDlg.cxx @@ -0,0 +1,142 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +#include "VTKViewer_MarkerDlg.h" +#include "VTKViewer_MarkerWidget.h" + +#include +#include +#include +#include + +#include +#include +#include + +/*! + * Class : VTKViewer_MarkerDlg + * Description : Dialog for specifying point marker parameters + */ + +/*! + Constructor +*/ +VTKViewer_MarkerDlg::VTKViewer_MarkerDlg( QWidget* theParent ) +: QtxDialog( theParent, true, true ) +{ + setWindowTitle( tr( "SET_MARKER_TLT" ) ); + + myMarkerWidget = new VTKViewer_MarkerWidget( mainFrame() ); + + QBoxLayout* aTopLayout = new QHBoxLayout( mainFrame() ); + aTopLayout->setSpacing( 0 ); + aTopLayout->setMargin( 0 ); + aTopLayout->addWidget( myMarkerWidget ); + + connect( this, SIGNAL( dlgHelp() ), this, SLOT( onHelp() ) ); +} + +/*! + Destructor +*/ +VTKViewer_MarkerDlg::~VTKViewer_MarkerDlg() +{ +} + +void VTKViewer_MarkerDlg::setHelpData( const QString& theModuleName, + const QString& theHelpFileName ) +{ + myModuleName = theModuleName; + myHelpFileName = theHelpFileName; +} + +void VTKViewer_MarkerDlg::keyPressEvent( QKeyEvent* e ) +{ + QtxDialog::keyPressEvent( e ); + if ( e->isAccepted() ) + return; + + if ( e->key() == Qt::Key_F1 ) { + e->accept(); + onHelp(); + } +} + +void VTKViewer_MarkerDlg::onHelp() +{ + if( myModuleName.isNull() || myHelpFileName.isNull() ) + return; + + SUIT_Application* app = SUIT_Session::session()->activeApplication(); + if (app) + app->onHelpContextModule(myModuleName, myHelpFileName); + else { + QString platform; +#ifdef WIN32 + platform = "winapplication"; +#else + platform = "application"; +#endif + SUIT_MessageBox::warning(this, tr("WRN_WARNING"), + tr("EXTERNAL_BROWSER_CANNOT_SHOW_PAGE"). + arg(app->resourceMgr()->stringValue("ExternalBrowser", + platform)). + arg(myHelpFileName)); + } +} + +void VTKViewer_MarkerDlg::setCustomMarkerMap( VTK::MarkerMap theMarkerMap ) +{ + myMarkerWidget->setCustomMarkerMap( theMarkerMap ); +} + +VTK::MarkerMap VTKViewer_MarkerDlg::getCustomMarkerMap() +{ + return myMarkerWidget->getCustomMarkerMap(); +} + +void VTKViewer_MarkerDlg::setStandardMarker( VTK::MarkerType theMarkerType, VTK::MarkerScale theMarkerScale ) +{ + myMarkerWidget->setStandardMarker( theMarkerType, theMarkerScale ); +} + +void VTKViewer_MarkerDlg::setCustomMarker( int theId ) +{ + myMarkerWidget->setCustomMarker( theId ); +} + +VTK::MarkerType VTKViewer_MarkerDlg::getMarkerType() const +{ + return myMarkerWidget->getMarkerType(); +} + +VTK::MarkerScale VTKViewer_MarkerDlg::getStandardMarkerScale() const +{ + return myMarkerWidget->getStandardMarkerScale(); +} + +int VTKViewer_MarkerDlg::getCustomMarkerID() const +{ + return myMarkerWidget->getCustomMarkerID(); +} + +void VTKViewer_MarkerDlg::addExtraStdMarker( VTK::MarkerType theMarkerType, const QPixmap& thePixmap ) +{ + myMarkerWidget->addExtraStdMarker( theMarkerType, thePixmap ); +} diff --git a/src/VTKViewer/VTKViewer_MarkerDlg.h b/src/VTKViewer/VTKViewer_MarkerDlg.h new file mode 100644 index 000000000..59bf03a68 --- /dev/null +++ b/src/VTKViewer/VTKViewer_MarkerDlg.h @@ -0,0 +1,69 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +#ifndef VTKVIEWER_MARKERDLG_H +#define VTKVIEWER_MARKERDLG_H + +#include "VTKViewer.h" +#include "VTKViewer_MarkerDef.h" + +#include + +class VTKViewer_MarkerWidget; + +/*! + * Class : VTKViewer_MarkerDlg + * Description : Dialog for specifying point marker parameters + */ +class VTKVIEWER_EXPORT VTKViewer_MarkerDlg : public QtxDialog +{ + Q_OBJECT + +public: + VTKViewer_MarkerDlg( QWidget* = 0 ); + virtual ~VTKViewer_MarkerDlg(); + + void setHelpData( const QString& theModuleName, + const QString& theHelpFileName ); + + void setCustomMarkerMap( VTK::MarkerMap ); + VTK::MarkerMap getCustomMarkerMap(); + + void setStandardMarker( VTK::MarkerType, VTK::MarkerScale ); + void setCustomMarker( int ); + VTK::MarkerType getMarkerType() const; + VTK::MarkerScale getStandardMarkerScale() const; + int getCustomMarkerID() const; + + void addExtraStdMarker( VTK::MarkerType, const QPixmap& ); + +protected: + void keyPressEvent( QKeyEvent* ); + +private slots: + void onHelp(); + +private: + VTKViewer_MarkerWidget* myMarkerWidget; + + QString myModuleName; + QString myHelpFileName; +}; + +#endif diff --git a/src/VTKViewer/VTKViewer_MarkerUtils.cxx b/src/VTKViewer/VTKViewer_MarkerUtils.cxx new file mode 100755 index 000000000..8b68004aa --- /dev/null +++ b/src/VTKViewer/VTKViewer_MarkerUtils.cxx @@ -0,0 +1,159 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +#include "VTKViewer_MarkerUtils.h" + +// VTK Includes +#include + +// QT Includes +#include +#include +#include +#include + +namespace VTK +{ + bool LoadTextureData( const QString& theFileName, + VTK::MarkerScale theMarkerScale, + VTK::MarkerTexture& theMarkerTexture ) + { + theMarkerTexture.clear(); + + QFile aFile( theFileName ); + if( !aFile.open( QIODevice::ReadOnly | QIODevice::Text ) ) + return false; + + bool ok; + int aWidth = 0, aHeight = 0; + + int aTextureIndex = theMarkerScale == VTK::MS_NONE ? 0 : (int)theMarkerScale-1; + int aCurrentTexture = 0; + + QTextStream aTextStream( &aFile ); + while( !aTextStream.atEnd() ) + { + QString aLine = aTextStream.readLine(); + if( aLine.isEmpty() ) + { + aCurrentTexture++; + continue; + } + + if( aCurrentTexture != aTextureIndex ) + continue; + + int aLineSize = aLine.size(); + for( int i = 0; i < aLineSize; i++ ) + { + ok = false; + unsigned int aPixel = QString( aLine.at( i ) ).toUInt( &ok ); + if( ok ) + theMarkerTexture.push_back( aPixel ); + } + if( aWidth == 0 ) + aWidth = aLineSize; + aHeight++; + } + + if( theMarkerTexture.size() != aWidth * aHeight ) + return false; + + theMarkerTexture.push_front( aWidth ); + theMarkerTexture.push_front( aHeight ); + return true; + } + + vtkSmartPointer MakeVTKImage( const VTK::MarkerTexture& theMarkerTexture, + bool theWhiteForeground ) + { + VTK::MarkerTexture::const_iterator anIter = theMarkerTexture.begin(); + + int aWidth = *anIter++; + int aHeight = *anIter++; + + vtkSmartPointer anImageData = vtkImageData::New(); + anImageData->Delete(); + + anImageData->SetExtent( 0, aWidth-1, 0, aHeight-1, 0, 0 ); + anImageData->SetScalarTypeToUnsignedChar(); + anImageData->SetNumberOfScalarComponents( 4 ); + anImageData->AllocateScalars(); + + unsigned char* aDataPtr = (unsigned char*)anImageData->GetScalarPointer(); + + int anId = 0; + int aSize = aWidth * aHeight * 4; + int aCoef = theWhiteForeground ? 1 : 0; + while( anId < aSize ) + { + int aValue = (*anIter++) * 255; + aDataPtr[ anId++ ] = aValue * aCoef; + aDataPtr[ anId++ ] = aValue * aCoef; + aDataPtr[ anId++ ] = aValue * aCoef; + aDataPtr[ anId++ ] = aValue; + } + anImageData->Update(); + + return anImageData; + } + + QImage ConvertToQImage( vtkImageData* theImageData ) + { + if( theImageData->GetScalarType() != VTK_UNSIGNED_CHAR ) + return QImage(); + + int extent[6]; + theImageData->GetExtent( extent ); + int width = extent[1] - extent[0] + 1; + int height = extent[3] - extent[2] + 1; + + QImage anImage(width, height, QImage::Format_ARGB32); + for( int i = 0; i < height; i++ ) + { + QRgb* bits = reinterpret_cast( anImage.scanLine(i) ); + unsigned char* row = static_cast( + theImageData->GetScalarPointer( extent[0], extent[2] + height - i - 1, extent[4] ) ); + for( int j = 0; j < width; j++ ) + { + unsigned char* data = &row[ j*4 ]; + bits[j] = qRgba( data[0], data[1], data[2], data[3] ); + } + } + return anImage; + } + + int GetUniqueId( const VTK::MarkerMap& theMarkerMap ) + { + int anId = 0; + while( anId++ < 100 ) { + bool anOk = true; + VTK::MarkerMap::const_iterator anIter = theMarkerMap.begin(); + for( ; anIter != theMarkerMap.end(); anIter++ ) { + if( anId == anIter->first ) { + anOk = false; + continue; + } + } + if( anOk ) + return anId; + } + return theMarkerMap.size() + 1; + } +} diff --git a/src/VTKViewer/VTKViewer_MarkerUtils.h b/src/VTKViewer/VTKViewer_MarkerUtils.h new file mode 100755 index 000000000..2b4521d70 --- /dev/null +++ b/src/VTKViewer/VTKViewer_MarkerUtils.h @@ -0,0 +1,48 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +#ifndef VTKVIEWER_MARKERUTILS_H +#define VTKVIEWER_MARKERUTILS_H + +#include "VTKViewer.h" +#include "VTKViewer_MarkerDef.h" + +// VTK Includes +#include + +class vtkImageData; + +class QImage; +class QString; + +namespace VTK +{ + VTKVIEWER_EXPORT bool LoadTextureData( const QString& theFileName, + VTK::MarkerScale theMarkerScale, + VTK::MarkerTexture& theTextureData ); + + VTKVIEWER_EXPORT vtkSmartPointer MakeVTKImage( const VTK::MarkerTexture& theTextureData, + bool theWhiteForeground = true ); + + VTKVIEWER_EXPORT QImage ConvertToQImage( vtkImageData* theImageData ); + + VTKVIEWER_EXPORT int GetUniqueId( const VTK::MarkerMap& theMarkerMap ); +} + +#endif diff --git a/src/VTKViewer/VTKViewer_MarkerWidget.cxx b/src/VTKViewer/VTKViewer_MarkerWidget.cxx new file mode 100644 index 000000000..cc0f0d035 --- /dev/null +++ b/src/VTKViewer/VTKViewer_MarkerWidget.cxx @@ -0,0 +1,273 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +#include "VTKViewer_MarkerWidget.h" +#include "VTKViewer_MarkerUtils.h" + +#include + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +#define MARGIN 9 +#define SPACING 6 + +/*! + * Class : VTKViewer_MarkerWidget + * Description : Widget for specifying point marker parameters + */ + +/*! + Constructor +*/ +VTKViewer_MarkerWidget::VTKViewer_MarkerWidget( QWidget* theParent ) +: QWidget( theParent ) +{ + QRadioButton* aStandardTypeRB = new QRadioButton( tr( "STANDARD_MARKER" ), this ); + QRadioButton* aCustomTypeRB = new QRadioButton( tr( "CUSTOM_MARKER" ), this ); + myTypeGroup = new QButtonGroup( this ); + myTypeGroup->addButton( aStandardTypeRB, 0 ); + myTypeGroup->addButton( aCustomTypeRB, 1 ); + + QHBoxLayout* aRadioLayout = new QHBoxLayout; + aRadioLayout->setMargin( 0 ); + aRadioLayout->setSpacing( SPACING ); + aRadioLayout->addWidget( aStandardTypeRB ); + aRadioLayout->addWidget( aCustomTypeRB ); + + // --- + + myWGStack = new QStackedWidget( this ); + myWGStack->setFrameStyle( QFrame::Box | QFrame::Sunken ); + + // --- + + QWidget* aStdWidget = new QWidget( myWGStack ); + + QLabel* aTypeLab = new QLabel( tr( "TYPE" ), aStdWidget ); + QLabel* aScaleLab = new QLabel( tr( "SCALE" ), aStdWidget ); + + myStdTypeCombo = new QtxComboBox( aStdWidget ); + myStdScaleCombo = new QtxComboBox( aStdWidget ); + + QGridLayout* aStdLayout = new QGridLayout; + aStdLayout->setMargin( MARGIN ); + aStdLayout->setSpacing( SPACING ); + aStdLayout->addWidget( aTypeLab, 0, 0 ); + aStdLayout->addWidget( myStdTypeCombo, 0, 1 ); + aStdLayout->addWidget( aScaleLab, 1, 0 ); + aStdLayout->addWidget( myStdScaleCombo, 1, 1 ); + aStdWidget->setLayout( aStdLayout ); + + // --- + + QWidget* aCustomWidget = new QWidget( myWGStack ); + + QLabel* aCustomLab = new QLabel( tr( "CUSTOM" ), aCustomWidget ); + myCustomTypeCombo = new QtxComboBox( aCustomWidget ); + QPushButton* aBrowseBtn = new QPushButton( tr( "BROWSE" ), aCustomWidget ); + + QGridLayout* aCustomLayout = new QGridLayout; + aCustomLayout->setMargin( MARGIN ); + aCustomLayout->setSpacing( SPACING ); + aCustomLayout->addWidget( aCustomLab, 0, 0 ); + aCustomLayout->addWidget( myCustomTypeCombo, 0, 1 ); + aCustomLayout->addWidget( aBrowseBtn, 0, 2 ); + aCustomLayout->setRowStretch( 1, 5 ); + aCustomWidget->setLayout( aCustomLayout ); + + // --- + + myWGStack->insertWidget( 0, aStdWidget ); + myWGStack->insertWidget( 1, aCustomWidget ); + + // --- + + QVBoxLayout* aTopLayout = new QVBoxLayout; + aTopLayout->setMargin( MARGIN ); + aTopLayout->setSpacing( SPACING ); + aTopLayout->addLayout( aRadioLayout ); + aTopLayout->addWidget( myWGStack ); + setLayout( aTopLayout ); + + // --- + + connect( myTypeGroup, SIGNAL( buttonClicked( int ) ), myWGStack, SLOT( setCurrentIndex( int ) ) ); + connect( myStdTypeCombo, SIGNAL( currentIndexChanged( int ) ), this, SLOT( onStdMarkerChanged( int ) ) ); + connect( aBrowseBtn, SIGNAL( clicked() ), this, SLOT( onBrowse() ) ); + + // --- + + aStandardTypeRB->setChecked( true ); + init(); +} + +/*! + Destructor +*/ +VTKViewer_MarkerWidget::~VTKViewer_MarkerWidget() +{ +} + +void VTKViewer_MarkerWidget::setCustomMarkerMap( VTK::MarkerMap theMarkerMap ) +{ + myCustomMarkerMap = theMarkerMap; + + VTK::MarkerMap::const_iterator it = theMarkerMap.begin(), itEnd = theMarkerMap.end(); + for( ; it != itEnd; it++ ) + { + int anId = it->first; + VTK::MarkerData aMarkerData = it->second; + QPixmap aPixmap = markerFromData( aMarkerData ); + if( !aPixmap.isNull() ) + { + myCustomTypeCombo->addItem( aPixmap, QString::number( anId ) ); + myCustomTypeCombo->setId( myCustomTypeCombo->count()-1, anId ); + } + } +} + +VTK::MarkerMap VTKViewer_MarkerWidget::getCustomMarkerMap() +{ + return myCustomMarkerMap; +} + +void VTKViewer_MarkerWidget::setStandardMarker( VTK::MarkerType theMarkerType, VTK::MarkerScale theMarkerScale ) +{ + if ( ( theMarkerType > VTK::MT_NONE && theMarkerType < VTK::MT_USER ) || + myExtraMarkerList.contains( theMarkerType ) ) { + myTypeGroup->button( 0 )->setChecked( true ); + myWGStack->setCurrentIndex( 0 ); + myStdTypeCombo->setCurrentId( theMarkerType ); + int aMarkerScale = std::max( (int)VTK::MS_10, std::min( (int)VTK::MS_70, (int)theMarkerScale ) ); + myStdScaleCombo->setCurrentId( aMarkerScale ); + } +} + +void VTKViewer_MarkerWidget::setCustomMarker( int theId ) +{ + if ( theId > 0 ) { + myTypeGroup->button( 1 )->setChecked( true ); + myWGStack->setCurrentIndex( 1 ); + addTexture( theId ); + myCustomTypeCombo->setCurrentId( theId ); + } +} + +VTK::MarkerType VTKViewer_MarkerWidget::getMarkerType() const +{ + return myWGStack->currentIndex() == 0 ? (VTK::MarkerType)myStdTypeCombo->currentId() : VTK::MT_USER; +} + +VTK::MarkerScale VTKViewer_MarkerWidget::getStandardMarkerScale() const +{ + return myWGStack->currentIndex() == 0 ? (VTK::MarkerScale)myStdScaleCombo->currentId() : VTK::MS_NONE; +} + +int VTKViewer_MarkerWidget::getCustomMarkerID() const +{ + return myWGStack->currentIndex() == 1 ? myCustomTypeCombo->currentId() : 0; +} + +void VTKViewer_MarkerWidget::addExtraStdMarker( VTK::MarkerType theMarkerType, const QPixmap& thePixmap ) +{ + if( myExtraMarkerList.isEmpty() ) + myStdTypeCombo->insertSeparator( myStdTypeCombo->count() ); + myStdTypeCombo->addItem( thePixmap, QString() ); + myStdTypeCombo->setId( myStdTypeCombo->count()-1, theMarkerType ); + + myExtraMarkerList.append( theMarkerType ); +} + +void VTKViewer_MarkerWidget::init() +{ + SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr(); + + for ( int i = VTK::MT_POINT; i < VTK::MT_USER; i++ ) { + QString icoFile = QString( "ICON_VERTEX_MARKER_%1" ).arg( i ); + QPixmap pixmap = resMgr->loadPixmap( "VTKViewer", tr( qPrintable( icoFile ) ) ); + myStdTypeCombo->addItem( pixmap, QString() ); + myStdTypeCombo->setId( myStdTypeCombo->count()-1, i ); + } + + for ( int i = VTK::MS_10; i <= VTK::MS_70; i++ ) { + myStdScaleCombo->addItem( QString::number( (i-1)*0.5 + 1.0 ) ); + myStdScaleCombo->setId( myStdScaleCombo->count()-1, i ); + } +} + +void VTKViewer_MarkerWidget::addTexture( int id, bool select ) +{ + if ( id > 0 && myCustomTypeCombo->index( id ) == -1 && + myCustomMarkerMap.find( id ) != myCustomMarkerMap.end() ) { + VTK::MarkerData aMarkerData = myCustomMarkerMap[ id ]; + QPixmap pixmap = markerFromData( aMarkerData ); + if( !pixmap.isNull() ) { + myCustomTypeCombo->addItem( pixmap, QString::number( id ) ); + myCustomTypeCombo->setId( myCustomTypeCombo->count()-1, id ); + if ( select ) myCustomTypeCombo->setCurrentId( id ); + } + } +} + +QPixmap VTKViewer_MarkerWidget::markerFromData( const VTK::MarkerData& theMarkerData ) +{ + const VTK::MarkerTexture& aMarkerTexture = theMarkerData.second; + vtkSmartPointer anImageData = VTK::MakeVTKImage( aMarkerTexture, false ); + + QImage anImage = VTK::ConvertToQImage( anImageData.GetPointer() ); + if( anImage.isNull() ) + return QPixmap(); + + return QPixmap::fromImage( anImage ); +} + +void VTKViewer_MarkerWidget::onStdMarkerChanged( int index ) +{ + VTK::MarkerType aMarkerType = (VTK::MarkerType)myStdTypeCombo->id( index ); + bool anIsExtraMarker = myExtraMarkerList.contains( aMarkerType ); + myStdScaleCombo->setEnabled( !anIsExtraMarker ); +} + +void VTKViewer_MarkerWidget::onBrowse() +{ + QStringList filters; + filters << tr( "Texture files (*.dat)" ) << tr( "All files (*)" ); + QString aFileName = SUIT_Session::session()->activeApplication()->getFileName( true, QString(), filters.join( ";;" ), tr( "LOAD_TEXTURE_TLT" ), this ); + if ( !aFileName.isEmpty() ) { + VTK::MarkerTexture aMarkerTexture; + if ( VTK::LoadTextureData( aFileName, VTK::MS_NONE, aMarkerTexture ) ) { + int anId = VTK::GetUniqueId( myCustomMarkerMap ); + VTK::MarkerData& aMarkerData = myCustomMarkerMap[ anId ]; + aMarkerData.first = aFileName.toStdString(); + aMarkerData.second = aMarkerTexture; + addTexture( anId, true ); + } + } +} diff --git a/src/VTKViewer/VTKViewer_MarkerWidget.h b/src/VTKViewer/VTKViewer_MarkerWidget.h new file mode 100644 index 000000000..671589087 --- /dev/null +++ b/src/VTKViewer/VTKViewer_MarkerWidget.h @@ -0,0 +1,77 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +#ifndef VTKVIEWER_MARKERWIDGET_H +#define VTKVIEWER_MARKERWIDGET_H + +#include "VTKViewer.h" +#include "VTKViewer_MarkerDef.h" + +#include + +class QButtonGroup; +class QStackedWidget; + +class QtxComboBox; + +/*! + * Class : VTKViewer_MarkerWidget + * Description : Widget for specifying point marker parameters + */ +class VTKVIEWER_EXPORT VTKViewer_MarkerWidget : public QWidget +{ + Q_OBJECT + +public: + VTKViewer_MarkerWidget( QWidget* ); + virtual ~VTKViewer_MarkerWidget(); + + void setCustomMarkerMap( VTK::MarkerMap ); + VTK::MarkerMap getCustomMarkerMap(); + + void setStandardMarker( VTK::MarkerType, VTK::MarkerScale ); + void setCustomMarker( int ); + VTK::MarkerType getMarkerType() const; + VTK::MarkerScale getStandardMarkerScale() const; + int getCustomMarkerID() const; + + void addExtraStdMarker( VTK::MarkerType, const QPixmap& ); + +private: + void init(); + void addTexture( int, bool = false ); + QPixmap markerFromData( const VTK::MarkerData& ); + +private slots: + void onStdMarkerChanged( int ); + void onBrowse(); + +private: + QButtonGroup* myTypeGroup; + QStackedWidget* myWGStack; + QtxComboBox* myStdTypeCombo; + QtxComboBox* myStdScaleCombo; + QtxComboBox* myCustomTypeCombo; + + VTK::MarkerMap myCustomMarkerMap; + + QList myExtraMarkerList; +}; + +#endif diff --git a/src/VTKViewer/VTKViewer_OpenGLRenderer.cxx b/src/VTKViewer/VTKViewer_OpenGLRenderer.cxx new file mode 100644 index 000000000..a7250fa2e --- /dev/null +++ b/src/VTKViewer/VTKViewer_OpenGLRenderer.cxx @@ -0,0 +1,262 @@ +// Copyright (C) 2007-2011 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 +// + +#include "VTKViewer_OpenGLRenderer.h" +#include "VTKViewer_Texture.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include // vtkgl namespace +#include +#include +#include +#include +#include +#include + +vtkStandardNewMacro(VTKViewer_OpenGLRenderer); + +VTKViewer_OpenGLRenderer::VTKViewer_OpenGLRenderer() +{ + this->GradientType = HorizontalGradient; +} + +VTKViewer_OpenGLRenderer::~VTKViewer_OpenGLRenderer() +{ +} + +void VTKViewer_OpenGLRenderer::SetGradientType( const int theGradientType ) +{ + this->GradientType = theGradientType; +} + +void VTKViewer_OpenGLRenderer::Clear(void) +{ + GLbitfield clear_mask = 0; + + if( !this->Transparent() ) + { + glClearColor( static_cast(this->Background[0]), + static_cast(this->Background[1]), + static_cast(this->Background[2]), + static_cast(0.0)); + clear_mask |= GL_COLOR_BUFFER_BIT; + } + + if( !this->GetPreserveDepthBuffer() ) + { + glClearDepth(static_cast(1.0)); + clear_mask |= GL_DEPTH_BUFFER_BIT; + } + + vtkDebugMacro(<< "glClear\n"); + glClear(clear_mask); + + // If gradient background is turned on, draw it now. + if( !this->Transparent() && + ( this->GradientBackground || this->TexturedBackground ) ) + { + double aTileViewport[4]; + this->GetRenderWindow()->GetTileViewport( aTileViewport ); + glPushAttrib( GL_ENABLE_BIT | GL_TRANSFORM_BIT | GL_TEXTURE_BIT ); + glDisable( GL_ALPHA_TEST ); + glDisable( GL_DEPTH_TEST ); + glDisable( GL_LIGHTING ); + glDisable( GL_TEXTURE_1D ); + glDisable( GL_TEXTURE_2D ); + glDisable( GL_BLEND ); + glShadeModel( GL_SMOOTH ); // color interpolation + + glMatrixMode( GL_PROJECTION ); + glPushMatrix(); + glLoadIdentity(); + glMatrixMode( GL_MODELVIEW ); + glPushMatrix(); + glLoadIdentity(); + + glOrtho( aTileViewport[0], aTileViewport[2], aTileViewport[1], aTileViewport[3], -1.0, 1.0 ); + + if( this->GradientBackground ) + { + double* corner1 = 0; + double* corner2 = 0; + double* corner3 = 0; + double* corner4 = 0; + double dcorner1[3]; + double dcorner2[3]; + + switch( this->GradientType ) + { + case HorizontalGradient: + corner1 = this->Background; + corner2 = this->Background2; + corner3 = this->Background2; + corner4 = this->Background; + break; + case VerticalGradient: + corner1 = this->Background2; + corner2 = this->Background2; + corner3 = this->Background; + corner4 = this->Background; + break; + case FirstDiagonalGradient: + corner2 = this->Background2; + corner4 = this->Background; + dcorner1[0] = dcorner2[0] = 0.5F * ( corner2[0] + corner4[0] ); + dcorner1[1] = dcorner2[1] = 0.5F * ( corner2[1] + corner4[1] ); + dcorner1[2] = dcorner2[2] = 0.5F * ( corner2[2] + corner4[2] ); + corner1 = dcorner1; + corner3 = dcorner2; + break; + case SecondDiagonalGradient: + corner1 = this->Background2; + corner3 = this->Background; + dcorner1[0] = dcorner2[0] = 0.5F * ( corner1[0] + corner3[0] ); + dcorner1[1] = dcorner2[1] = 0.5F * ( corner1[1] + corner3[1] ); + dcorner1[2] = dcorner2[2] = 0.5F * ( corner1[2] + corner3[2] ); + corner2 = dcorner1; + corner4 = dcorner2; + break; + case FirstCornerGradient: + corner1 = this->Background2; + corner2 = this->Background2; + corner3 = this->Background2; + corner4 = this->Background; + break; + case SecondCornerGradient: + corner1 = this->Background2; + corner2 = this->Background2; + corner3 = this->Background; + corner4 = this->Background2; + break; + case ThirdCornerGradient: + corner1 = this->Background2; + corner2 = this->Background; + corner3 = this->Background2; + corner4 = this->Background2; + break; + case FourthCornerGradient: + corner1 = this->Background; + corner2 = this->Background2; + corner3 = this->Background2; + corner4 = this->Background2; + break; + default: // just in case + corner1 = this->Background; + corner2 = this->Background; + corner3 = this->Background; + corner4 = this->Background; + break; + } + + glBegin( GL_TRIANGLE_FAN ); + if( this->GradientType != FirstCornerGradient && this->GradientType != ThirdCornerGradient ) + { + glColor3f( corner1[0], corner1[1], corner1[2] ); glVertex2f( 0.F, 0.F ); + glColor3f( corner2[0], corner2[1], corner2[2] ); glVertex2f( 1.F, 0.F ); + glColor3f( corner3[0], corner3[1], corner3[2] ); glVertex2f( 1.F, 1.F ); + glColor3f( corner4[0], corner4[1], corner4[2] ); glVertex2f( 0.F, 1.F ); + } + else //if( this->GradientType == FirstCornerGradient || this->GradientType == ThirdCornerGradient ) + { + glColor3f( corner2[0], corner2[1], corner2[2] ); glVertex2f( 1.F, 0.F ); + glColor3f( corner3[0], corner3[1], corner3[2] ); glVertex2f( 1.F, 1.F ); + glColor3f( corner4[0], corner4[1], corner4[2] ); glVertex2f( 0.F, 1.F ); + glColor3f( corner1[0], corner1[1], corner1[2] ); glVertex2f( 0.F, 0.F ); + } + glEnd(); + } + + if( this->TexturedBackground && this->BackgroundTexture ) + { + if( VTKViewer_Texture* aTexture = VTKViewer_Texture::SafeDownCast( this->BackgroundTexture ) ) + { + glEnable( GL_TEXTURE_2D ); + + aTexture->Render( this ); + + // NOTE: By default the mode is GL_MODULATE. Since the user + // cannot set the mode, the default is set to replace. + glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE ); + glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); + glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); + + // NOTE: vtkTexture Render enables the alpha test + // so that no buffer is affected if alpha of incoming fragment is + // below the threshold. Here we have to enable it so that it won't + // rejects the fragments of the quad as the alpha is set to 0 on it. + glDisable( GL_ALPHA_TEST ); + + GLfloat texX = 1.F; // texture coordinate + GLfloat texY = 1.F; // texture coordinate + GLfloat x_offset = 0.5, y_offset = 0.5; + GLfloat coeff = 0.5; + + // OCCT issue 0023102: Change the algorithm of rendering the + // 3d viewer background using tiled texture + // Setting this coefficient to -1.F allows to tile textures relatively + // to the top-left corner of the view (value 1.F corresponds to the + // initial behaviour - tiling from the bottom-left corner) + GLfloat aCoef = -1.F; + + int aPosition = aTexture->GetPosition(); + int aWidth = aTexture->GetWidth(); + int aHeight = aTexture->GetHeight(); + int aViewWidth = this->RenderWindow->GetSize()[0]; + int aViewHeight = this->RenderWindow->GetSize()[1]; + if( aPosition == VTKViewer_Texture::Centered ) + { + x_offset = ( (GLfloat)aWidth / (GLfloat)aViewWidth ) / 2.; + y_offset = ( (GLfloat)aHeight / (GLfloat)aViewHeight ) / 2.; + } + else if( aPosition == VTKViewer_Texture::Tiled ) + { + texX = (GLfloat)aViewWidth / (GLfloat)aWidth; + texY = (GLfloat)aViewHeight / (GLfloat)aHeight; + } + + // Note that texture is mapped using GL_REPEAT wrapping mode so integer part + // is simply ignored, and negative multiplier is here for convenience only + // and does not result e.g. in texture mirroring + glBegin( GL_QUADS ); + glTexCoord2f( 0.F, 0.F ); glVertex2f( -x_offset + coeff, -aCoef * y_offset + coeff ); + glTexCoord2f( texX, 0.F ); glVertex2f( x_offset + coeff, -aCoef * y_offset + coeff ); + glTexCoord2f( texX, aCoef * texY ); glVertex2f( x_offset + coeff, aCoef * y_offset + coeff ); + glTexCoord2f( 0.F, aCoef * texY ); glVertex2f( -x_offset + coeff, aCoef * y_offset + coeff ); + glEnd(); + } + } + + glPopMatrix(); + glMatrixMode( GL_PROJECTION ); + glPopMatrix(); + glMatrixMode( GL_MODELVIEW ); + + glPopAttrib(); + } +} diff --git a/src/VTKViewer/VTKViewer_OpenGLRenderer.h b/src/VTKViewer/VTKViewer_OpenGLRenderer.h new file mode 100644 index 000000000..83bcc5ecc --- /dev/null +++ b/src/VTKViewer/VTKViewer_OpenGLRenderer.h @@ -0,0 +1,70 @@ +// Copyright (C) 2007-2011 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 +// + +// SALOME VTKViewer : build VTK viewer into Salome desktop +// File : +// Author : +// Module : +// $Header$ +// + +#ifndef VTKVIEWER_OPENGLRENDERER_H +#define VTKVIEWER_OPENGLRENDERER_H + +#include "VTKViewer.h" +#include "vtkOpenGLRenderer.h" + +class VTKVIEWER_EXPORT VTKViewer_OpenGLRenderer : public vtkOpenGLRenderer +{ +public: + enum { + HorizontalGradient, + VerticalGradient, + FirstDiagonalGradient, + SecondDiagonalGradient, + FirstCornerGradient, + SecondCornerGradient, + ThirdCornerGradient, + FourthCornerGradient + }; + +public: + static VTKViewer_OpenGLRenderer *New(); + vtkTypeMacro(VTKViewer_OpenGLRenderer,vtkOpenGLRenderer); + + virtual void SetGradientType( const int ); + + virtual void Clear(void); + +protected: + VTKViewer_OpenGLRenderer(); + ~VTKViewer_OpenGLRenderer(); + +private: + int GradientType; + +private: + VTKViewer_OpenGLRenderer(const VTKViewer_OpenGLRenderer&); // Not implemented. + void operator=(const VTKViewer_OpenGLRenderer&); // Not implemented. +}; + +#endif diff --git a/src/VTKViewer/VTKViewer_PolyDataMapper.cxx b/src/VTKViewer/VTKViewer_PolyDataMapper.cxx new file mode 100644 index 000000000..019350a17 --- /dev/null +++ b/src/VTKViewer/VTKViewer_PolyDataMapper.cxx @@ -0,0 +1,585 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +#include "VTKViewer_PolyDataMapper.h" +#include "VTKViewer_MarkerUtils.h" + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef WNT +# ifndef GLX_GLXEXT_LEGACY +# define GLX_GLXEXT_LEGACY +# endif +# include +# include +#else +# include +#endif + +#ifndef VTK_IMPLEMENT_MESA_CXX +vtkCxxRevisionMacro(VTKViewer_PolyDataMapper, "Revision$"); +vtkStandardNewMacro(VTKViewer_PolyDataMapper); +#endif + +// some definitions for what the polydata has in it +#define VTK_PDPSM_COLORS 0x0001 +#define VTK_PDPSM_CELL_COLORS 0x0002 +#define VTK_PDPSM_POINT_TYPE_FLOAT 0x0004 +#define VTK_PDPSM_POINT_TYPE_DOUBLE 0x0008 +#define VTK_PDPSM_NORMAL_TYPE_FLOAT 0x0010 +#define VTK_PDPSM_NORMAL_TYPE_DOUBLE 0x0020 +#define VTK_PDPSM_OPAQUE_COLORS 0x0040 + +#ifndef APIENTRY +#define APIENTRY +#endif +#ifndef APIENTRYP +#define APIENTRYP APIENTRY * +#endif + +#ifndef GL_VERTEX_PROGRAM_POINT_SIZE_ARB +#define GL_VERTEX_PROGRAM_POINT_SIZE_ARB 0x8642 +#endif + +#ifndef GL_ARB_point_sprite +#define GL_POINT_SPRITE_ARB 0x8861 +#define GL_COORD_REPLACE_ARB 0x8862 +#endif + +#ifndef GL_ARB_vertex_buffer_object +typedef ptrdiff_t GLsizeiptrARB; + +#define GL_ARRAY_BUFFER_ARB 0x8892 +#define GL_STATIC_DRAW_ARB 0x88E4 +#endif + +typedef void (APIENTRYP PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer); +typedef void (APIENTRYP PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers); +typedef void (APIENTRYP PFNGLGENBUFFERSARBPROC) (GLsizei n, GLuint *buffers); +typedef void (APIENTRYP PFNGLBUFFERDATAARBPROC) (GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage); + +static PFNGLGENBUFFERSARBPROC vglGenBuffersARB = NULL; +static PFNGLBINDBUFFERARBPROC vglBindBufferARB = NULL; +static PFNGLBUFFERDATAARBPROC vglBufferDataARB = NULL; +static PFNGLDELETEBUFFERSARBPROC vglDeleteBuffersARB = NULL; + +#ifndef WNT +#define GL_GetProcAddress( x ) glXGetProcAddressARB( (const GLubyte*)x ) +#else +#define GL_GetProcAddress( x ) wglGetProcAddress( (const LPCSTR)x ) +#endif + +bool InitializeBufferExtensions() +{ + vglGenBuffersARB = (PFNGLGENBUFFERSARBPROC)GL_GetProcAddress( "glGenBuffersARB" ); + if( !vglGenBuffersARB ) + return false; + + vglBindBufferARB = (PFNGLBINDBUFFERARBPROC)GL_GetProcAddress( "glBindBufferARB" ); + if( !vglBindBufferARB ) + return false; + + vglBufferDataARB = (PFNGLBUFFERDATAARBPROC)GL_GetProcAddress( "glBufferDataARB" ); + if( !vglBufferDataARB ) + return false; + + vglDeleteBuffersARB = (PFNGLDELETEBUFFERSARBPROC)GL_GetProcAddress( "glDeleteBuffersARB" ); + if( !vglDeleteBuffersARB ) + return false; + + return true; +}; + +static bool IsBufferExtensionsInitialized = InitializeBufferExtensions(); + +//----------------------------------------------------------------------------- +VTKViewer_PolyDataMapper::VTKViewer_PolyDataMapper() +{ + Q_INIT_RESOURCE( VTKViewer ); + + this->ExtensionsInitialized = ES_None; + + this->PointSpriteTexture = 0; + + this->MarkerEnabled = false; + this->MarkerType = VTK::MT_NONE; + this->MarkerScale = VTK::MS_NONE; + this->MarkerId = 0; +} + +//----------------------------------------------------------------------------- +VTKViewer_PolyDataMapper::~VTKViewer_PolyDataMapper() +{ + if( PointSpriteTexture > 0 ) + glDeleteTextures( 1, &PointSpriteTexture ); +} + +//----------------------------------------------------------------------------- +void VTKViewer_PolyDataMapper::SetMarkerEnabled( bool theMarkerEnabled ) +{ + if( this->MarkerEnabled == theMarkerEnabled ) + return; + + this->MarkerEnabled = theMarkerEnabled; + this->Modified(); +} + +//----------------------------------------------------------------------------- +void VTKViewer_PolyDataMapper::SetMarkerStd( VTK::MarkerType theMarkerType, VTK::MarkerScale theMarkerScale ) +{ + if( this->MarkerType == theMarkerType && this->MarkerScale == theMarkerScale ) + return; + + this->MarkerType = theMarkerType; + this->MarkerScale = theMarkerScale; + + if( this->MarkerType == VTK::MT_NONE || this->MarkerType == VTK::MT_USER ) { + this->ImageData = NULL; + this->Modified(); + return; + } + + int aMarkerType = (int)this->MarkerType; + int aMarkerScale = (int)this->MarkerScale; + + int anId = (int)VTK::MS_70 * aMarkerType + aMarkerScale; + + if( this->StandardTextures.find( anId ) == this->StandardTextures.end() ) + { + QString aFileName = QString( ":/textures/texture%1.dat" ).arg( aMarkerType ); + VTK::MarkerTexture aMarkerTexture; + if( VTK::LoadTextureData( aFileName, theMarkerScale, aMarkerTexture ) ) + this->StandardTextures[ anId ] = VTK::MakeVTKImage( aMarkerTexture ); + } + + this->ImageData = this->StandardTextures[ anId ]; + this->Modified(); +} + +//----------------------------------------------------------------------------- +void VTKViewer_PolyDataMapper::SetMarkerTexture( int theMarkerId, VTK::MarkerTexture theMarkerTexture ) +{ + if( this->MarkerType == VTK::MT_USER && this->MarkerId == theMarkerId ) + return; + + this->MarkerType = VTK::MT_USER; + this->MarkerId = theMarkerId; + + if( this->CustomTextures.find( theMarkerId ) == this->CustomTextures.end() ) + this->CustomTextures[ theMarkerId ] = VTK::MakeVTKImage( theMarkerTexture ); + + this->ImageData = this->CustomTextures[ theMarkerId ]; + this->Modified(); +} + +//----------------------------------------------------------------------------- +VTK::MarkerType VTKViewer_PolyDataMapper::GetMarkerType() +{ + return this->MarkerType; +} + +//----------------------------------------------------------------------------- +VTK::MarkerScale VTKViewer_PolyDataMapper::GetMarkerScale() +{ + return this->MarkerScale; +} + +//----------------------------------------------------------------------------- +int VTKViewer_PolyDataMapper::GetMarkerTexture() +{ + return this->MarkerId; +} + +//----------------------------------------------------------------------------- +int VTKViewer_PolyDataMapper::InitExtensions() +{ + char* ext = (char*)glGetString( GL_EXTENSIONS ); + if( !IsBufferExtensionsInitialized || + strstr( ext, "GL_ARB_point_sprite" ) == NULL || + strstr( ext, "GL_ARB_vertex_buffer_object" ) == NULL ) + { + MESSAGE("Initializing ARB extensions failed"); + return ES_Error; + } + + return ES_Ok; +} + +//----------------------------------------------------------------------------- +void VTKViewer_PolyDataMapper::InitPointSprites() +{ + glEnable( GL_POINT_SPRITE_ARB ); + glEnable( GL_VERTEX_PROGRAM_POINT_SIZE_ARB ); + + glPushAttrib( GL_COLOR_BUFFER_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT | GL_ENABLE_BIT | GL_LIGHTING_BIT ); + + glDepthFunc( GL_LEQUAL ); + glEnable( GL_DEPTH_TEST ); + + glEnable( GL_ALPHA_TEST ); + glAlphaFunc( GL_GREATER, 0.0 ); + + glDisable( GL_LIGHTING ); + + glDisable( GL_COLOR_MATERIAL ); +} + +//----------------------------------------------------------------------------- +void VTKViewer_PolyDataMapper::CleanupPointSprites() +{ + glPopAttrib(); + + glDisable( GL_VERTEX_PROGRAM_POINT_SIZE_ARB ); + glDisable( GL_POINT_SPRITE_ARB ); +} + +//----------------------------------------------------------------------------- +void VTKViewer_PolyDataMapper::InitTextures() +{ + if( !this->ImageData.GetPointer() ) + return; + + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); + glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); + glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); + + int* aSize = this->ImageData->GetDimensions(); + unsigned char* dataPtr = (unsigned char*)this->ImageData->GetScalarPointer(); + glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, aSize[0], aSize[1], 0, + GL_RGBA, GL_UNSIGNED_BYTE, dataPtr ); + + //glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); + glEnable( GL_TEXTURE_2D ); + glTexEnvf( GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE ); + glBindTexture( GL_TEXTURE_2D, this->PointSpriteTexture ); +} + +//----------------------------------------------------------------------------- +void VTKViewer_PolyDataMapper::RenderPiece( vtkRenderer* ren, vtkActor* act ) +{ + bool isUsePointSprites = this->MarkerEnabled && this->MarkerType != VTK::MT_NONE; + if( isUsePointSprites ) + { + if( this->ExtensionsInitialized == ES_None ) + this->ExtensionsInitialized = this->InitExtensions(); + this->InitPointSprites(); + this->InitTextures(); + } + + MAPPER_SUPERCLASS::RenderPiece( ren, act ); + + if( isUsePointSprites ) + this->CleanupPointSprites(); +} + +//----------------------------------------------------------------------------- +// Definition of structures and fuctions used in Draw() method +namespace VTK +{ + //----------------------------------------------------------------------------- + struct TVertex + { + GLfloat r, g, b, a; + GLfloat vx, vy, vz; + }; + + //----------------------------------------------------------------------------- + struct TColorFunctorBase + { + vtkFloatingPointType myAlpha; + + TColorFunctorBase( vtkProperty* theProperty ) + { + myAlpha = theProperty->GetOpacity(); + } + + virtual + void + get( TVertex& theVertex, vtkIdType thePointId, vtkIdType theCellId ) = 0; + }; + + //----------------------------------------------------------------------------- + struct TPropertyColor : TColorFunctorBase + { + vtkFloatingPointType myColor[3]; + + TPropertyColor( vtkProperty* theProperty ): + TColorFunctorBase( theProperty ) + { + theProperty->GetColor( myColor ); + } + + virtual + void + get( TVertex& theVertex, vtkIdType thePointId, vtkIdType theCellId ) + { + theVertex.r = myColor[0]; + theVertex.g = myColor[1]; + theVertex.b = myColor[2]; + theVertex.a = myAlpha; + } + }; + + //----------------------------------------------------------------------------- + struct TColors2Color : TColorFunctorBase + { + vtkUnsignedCharArray* myColors; + + TColors2Color( vtkProperty* theProperty, + vtkUnsignedCharArray* theColors ): + TColorFunctorBase( theProperty ), + myColors( theColors ) + {} + + virtual + void + get( TVertex& theVertex, vtkIdType thePointId, vtkIdType theCellId ) + { + vtkIdType aTupleId = GetTupleId( thePointId, theCellId ); + unsigned char* aColor = myColors->GetPointer( aTupleId << 2 ); + + theVertex.r = int( aColor[0] ) / 255.0; + theVertex.g = int( aColor[1] ) / 255.0; + theVertex.b = int( aColor[2] ) / 255.0; + theVertex.a = myAlpha; + } + + virtual + vtkIdType + GetTupleId( vtkIdType thePointId, vtkIdType theCellId ) = 0; + }; + + //----------------------------------------------------------------------------- + struct TPointColors2Color : TColors2Color + { + TPointColors2Color( vtkProperty* theProperty, + vtkUnsignedCharArray* theColors ): + TColors2Color( theProperty, theColors ) + {} + + virtual + vtkIdType + GetTupleId( vtkIdType thePointId, vtkIdType theCellId ) + { + return thePointId; + } + }; + + //----------------------------------------------------------------------------- + struct TCellColors2Color : TColors2Color + { + TCellColors2Color( vtkProperty* theProperty, + vtkUnsignedCharArray* theColors ): + TColors2Color( theProperty, theColors ) + {} + + virtual + vtkIdType + GetTupleId( vtkIdType thePointId, vtkIdType theCellId ) + { + return theCellId; + } + }; + + //----------------------------------------------------------------------------- + template < class TCoordinates > + void DrawPoints( TCoordinates* theStartPoints, + vtkCellArray* theCells, + TColorFunctorBase* theColorFunctor, + TVertex* theVertexArr, + vtkIdType &theCellId, + vtkIdType &theVertexId ) + { + vtkIdType* ptIds = theCells->GetPointer(); + vtkIdType* endPtIds = ptIds + theCells->GetNumberOfConnectivityEntries(); + + while ( ptIds < endPtIds ) { + vtkIdType nPts = *ptIds; + ++ptIds; + + while ( nPts > 0 ) { + TVertex& aVertex = theVertexArr[ theVertexId ]; + vtkIdType aPointId = *ptIds; + + TCoordinates* anOffsetPoints = theStartPoints + 3 * aPointId; + aVertex.vx = anOffsetPoints[0]; + aVertex.vy = anOffsetPoints[1]; + aVertex.vz = anOffsetPoints[2]; + + theColorFunctor->get( aVertex, aPointId, theCellId ); + + ++theVertexId; + ++ptIds; + --nPts; + } + + ++theCellId; + } + } + + //----------------------------------------------------------------------------- + template < class TCoordinates > + void DrawCellsPoints( vtkPolyData* theInput, + vtkPoints* thePoints, + TColorFunctorBase* theColorFunctor, + TVertex* theVertexArr ) + { + vtkIdType aCellId = 0, aVertexId = 0; + + TCoordinates* aStartPoints = (TCoordinates*)thePoints->GetVoidPointer(0); + + if ( vtkCellArray* aCellArray = theInput->GetVerts() ) + DrawPoints( aStartPoints, aCellArray, theColorFunctor, theVertexArr, aCellId, aVertexId ); + + if ( vtkCellArray* aCellArray = theInput->GetLines() ) + DrawPoints( aStartPoints, aCellArray, theColorFunctor, theVertexArr, aCellId, aVertexId ); + + if ( vtkCellArray* aCellArray = theInput->GetPolys() ) + DrawPoints( aStartPoints, aCellArray, theColorFunctor, theVertexArr, aCellId, aVertexId ); + + if ( vtkCellArray* aCellArray = theInput->GetStrips() ) + DrawPoints( aStartPoints, aCellArray, theColorFunctor, theVertexArr, aCellId, aVertexId ); + } +} // namespace VTK + +//----------------------------------------------------------------------------- +int VTKViewer_PolyDataMapper::Draw( vtkRenderer* ren, vtkActor* act ) +{ + if( !this->MarkerEnabled || this->MarkerType == VTK::MT_NONE || !this->ImageData.GetPointer() ) + return MAPPER_SUPERCLASS::Draw( ren, act ); + + vtkUnsignedCharArray* colors = NULL; + vtkPolyData* input = this->GetInput(); + vtkPoints* points; + int noAbort = 1; + int cellScalars = 0; + vtkProperty* prop = act->GetProperty(); + + points = input->GetPoints(); + + if ( this->Colors ) + { + colors = this->Colors; + if ( (this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA || + this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA || + !input->GetPointData()->GetScalars() ) + && this->ScalarMode != VTK_SCALAR_MODE_USE_POINT_FIELD_DATA) + cellScalars = 1; + } + + { + vtkIdType aTotalConnectivitySize = 0; + + if ( vtkCellArray* aCellArray = input->GetVerts() ) + aTotalConnectivitySize += aCellArray->GetNumberOfConnectivityEntries() - aCellArray->GetNumberOfCells(); + + if ( vtkCellArray* aCellArray = input->GetLines() ) + aTotalConnectivitySize += aCellArray->GetNumberOfConnectivityEntries() - aCellArray->GetNumberOfCells(); + + if ( vtkCellArray* aCellArray = input->GetPolys() ) + aTotalConnectivitySize += aCellArray->GetNumberOfConnectivityEntries() - aCellArray->GetNumberOfCells(); + + if ( vtkCellArray* aCellArray = input->GetStrips() ) + aTotalConnectivitySize += aCellArray->GetNumberOfConnectivityEntries() - aCellArray->GetNumberOfCells(); + + if ( aTotalConnectivitySize > 0 ) { + VTK::TVertex* aVertexArr = new VTK::TVertex[ aTotalConnectivitySize ]; + + int* aSize = this->ImageData->GetDimensions(); + glPointSize( std::max( aSize[0], aSize[1] ) ); + + int aMode = 0; // to remove + { + VTK::TColorFunctorBase* aColorFunctor = NULL; + if( colors && aMode != 1 ) { + if ( cellScalars ) + aColorFunctor = new VTK::TCellColors2Color( prop, colors ); + else + aColorFunctor = new VTK::TPointColors2Color( prop, colors ); + } else { + aColorFunctor = new VTK::TPropertyColor( prop ); + } + if ( points->GetDataType() == VTK_FLOAT ) + VTK::DrawCellsPoints< float >( input, points, aColorFunctor, aVertexArr ); + else + VTK::DrawCellsPoints< double >( input, points, aColorFunctor, aVertexArr ); + + delete aColorFunctor; + } + + if( this->ExtensionsInitialized == ES_Ok ) { + GLuint aBufferObjectID = 0; + vglGenBuffersARB( 1, &aBufferObjectID ); + vglBindBufferARB( GL_ARRAY_BUFFER_ARB, aBufferObjectID ); + + int anArrayObjectSize = sizeof( VTK::TVertex ) * aTotalConnectivitySize; + vglBufferDataARB( GL_ARRAY_BUFFER_ARB, anArrayObjectSize, aVertexArr, GL_STATIC_DRAW_ARB ); + + delete [] aVertexArr; + + vglBindBufferARB( GL_ARRAY_BUFFER_ARB, 0 ); + vglBindBufferARB( GL_ARRAY_BUFFER_ARB, aBufferObjectID ); + + glColorPointer( 4, GL_FLOAT, sizeof(VTK::TVertex), (void*)0 ); + glVertexPointer( 3, GL_FLOAT, sizeof(VTK::TVertex), (void*)(4*sizeof(GLfloat)) ); + + glEnableClientState( GL_VERTEX_ARRAY ); + glEnableClientState( GL_COLOR_ARRAY ); + + glDrawArrays( GL_POINTS, 0, aTotalConnectivitySize ); + + glDisableClientState( GL_COLOR_ARRAY ); + glDisableClientState( GL_VERTEX_ARRAY ); + + vglDeleteBuffersARB( 1, &aBufferObjectID ); + } else { // there are no extensions + glColorPointer( 4, GL_FLOAT, sizeof(VTK::TVertex), aVertexArr ); + glVertexPointer( 3, GL_FLOAT, sizeof(VTK::TVertex), + (void*)((GLfloat*)((void*)(aVertexArr)) + 4)); + + glEnableClientState( GL_VERTEX_ARRAY ); + glEnableClientState( GL_COLOR_ARRAY ); + + glDrawArrays( GL_POINTS, 0, aTotalConnectivitySize ); + + glDisableClientState( GL_COLOR_ARRAY ); + glDisableClientState( GL_VERTEX_ARRAY ); + + delete [] aVertexArr; + } + } + } + + this->UpdateProgress(1.0); + return noAbort; +} diff --git a/src/VTKViewer/VTKViewer_PolyDataMapper.h b/src/VTKViewer/VTKViewer_PolyDataMapper.h new file mode 100644 index 000000000..80d04a783 --- /dev/null +++ b/src/VTKViewer/VTKViewer_PolyDataMapper.h @@ -0,0 +1,122 @@ +// Copyright (C) 2007-2012 CEA/DEN, EDF R&D, 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 +// + +#ifndef VTKViewer_POLYDATAMAPPER_H +#define VTKViewer_POLYDATAMAPPER_H + +#include "VTKViewer.h" +#include "VTKViewer_MarkerDef.h" + +#ifdef WNT +#include +#endif + +#include + +#include + +#include + +class vtkImageData; + +#ifndef VTK_IMPLEMENT_MESA_CXX +#include +#define MAPPER_SUPERCLASS vtkOpenGLPolyDataMapper +#else +#include +#define MAPPER_SUPERCLASS vtkMesaPolyDataMapper +#endif + +//---------------------------------------------------------------------------- +//! OpenGL Point Sprites PolyData Mapper. +/*! + * VTKViewer_PolyDataMapper is a class that maps polygonal data + * (i.e., vtkPolyData) to graphics primitives. It is performing the mapping + * to the rendering/graphics hardware/software. It is now possible to set a + * memory limit for the pipeline in the mapper. If the total estimated memory + * usage of the pipeline is larger than this limit, the mapper will divide + * the data into pieces and render each in a for loop. + */ +class VTKVIEWER_EXPORT VTKViewer_PolyDataMapper : public MAPPER_SUPERCLASS +{ +public: + enum ExtensionsState { ES_None = 0, ES_Error, ES_Ok }; + +public: + static VTKViewer_PolyDataMapper* New(); + vtkTypeRevisionMacro( VTKViewer_PolyDataMapper, MAPPER_SUPERCLASS ); + + //! Set point marker enabled + void SetMarkerEnabled( bool ); + + //! Set standard point marker + void SetMarkerStd( VTK::MarkerType, VTK::MarkerScale ); + + //! Set custom point marker + void SetMarkerTexture( int, VTK::MarkerTexture ); + + //! Get type of the point marker + VTK::MarkerType GetMarkerType(); + + //! Get scale of the point marker + VTK::MarkerScale GetMarkerScale(); + + //! Get texture identifier of the point marker + int GetMarkerTexture(); + + //! Implement superclass render method. + virtual void RenderPiece( vtkRenderer*, vtkActor* ); + + //! Draw method for OpenGL. + virtual int Draw( vtkRenderer*, vtkActor* ); + +protected: + VTKViewer_PolyDataMapper(); + ~VTKViewer_PolyDataMapper(); + + //! Initializing OpenGL extensions. + int InitExtensions(); + + //! Activate Point Sprites. + void InitPointSprites(); + + //! Deactivate Point Sprites. + void CleanupPointSprites(); + + //! Initializing textures for Point Sprites. + void InitTextures(); + +private: + int ExtensionsInitialized; + + GLuint PointSpriteTexture; + + vtkSmartPointer ImageData; + + bool MarkerEnabled; + VTK::MarkerType MarkerType; + VTK::MarkerScale MarkerScale; + int MarkerId; + + typedef std::map< int, vtkSmartPointer > ImageDataMap; + ImageDataMap StandardTextures; + ImageDataMap CustomTextures; +}; + +#endif diff --git a/src/VTKViewer/VTKViewer_Texture.cxx b/src/VTKViewer/VTKViewer_Texture.cxx new file mode 100644 index 000000000..68b98277c --- /dev/null +++ b/src/VTKViewer/VTKViewer_Texture.cxx @@ -0,0 +1,491 @@ +// Copyright (C) 2007-2011 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 +// +#include "VTKViewer_Texture.h" + +#include "vtkHomogeneousTransform.h" +#include "vtkImageData.h" +#include "vtkLookupTable.h" +#include "vtkObjectFactory.h" +#include "vtkOpenGLRenderer.h" +#include "vtkPointData.h" +#include "vtkRenderWindow.h" +#include "vtkOpenGLExtensionManager.h" +#include "vtkOpenGLRenderWindow.h" +#include "vtkTransform.h" +#include "vtkPixelBufferObject.h" +#include "vtkOpenGL.h" +#include "vtkgl.h" // vtkgl namespace +#include + +vtkStandardNewMacro(VTKViewer_Texture); + + +// ---------------------------------------------------------------------------- +VTKViewer_Texture::VTKViewer_Texture() +{ + myWidth = 0; + myHeight = 0; + myPosition = VTKViewer_Texture::Centered; +} + +// ---------------------------------------------------------------------------- +VTKViewer_Texture::~VTKViewer_Texture() +{ +} + +// ---------------------------------------------------------------------------- +// Implement base class method. +void VTKViewer_Texture::Load(vtkRenderer *ren) +{ + GLenum format = GL_LUMINANCE; + vtkImageData *input = this->GetInput(); + + this->Initialize(ren); + + // Need to reload the texture. + // There used to be a check on the render window's mtime, but + // this is too broad of a check (e.g. it would cause all textures + // to load when only the desired update rate changed). + // If a better check is required, check something more specific, + // like the graphics context. + vtkOpenGLRenderWindow* renWin = + static_cast(ren->GetRenderWindow()); + + if(this->BlendingMode != VTK_TEXTURE_BLENDING_MODE_NONE + && vtkgl::ActiveTexture) + { + glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, vtkgl::COMBINE); + + switch(this->BlendingMode) + { + case VTK_TEXTURE_BLENDING_MODE_REPLACE: + { + glTexEnvf (GL_TEXTURE_ENV, vtkgl::COMBINE_RGB, GL_REPLACE); + glTexEnvf (GL_TEXTURE_ENV, vtkgl::COMBINE_ALPHA, GL_REPLACE); + break; + } + case VTK_TEXTURE_BLENDING_MODE_MODULATE: + { + glTexEnvf (GL_TEXTURE_ENV, vtkgl::COMBINE_RGB, GL_MODULATE); + glTexEnvf (GL_TEXTURE_ENV, vtkgl::COMBINE_ALPHA, GL_MODULATE); + break; + } + case VTK_TEXTURE_BLENDING_MODE_ADD: + { + glTexEnvf (GL_TEXTURE_ENV, vtkgl::COMBINE_RGB, GL_ADD); + glTexEnvf (GL_TEXTURE_ENV, vtkgl::COMBINE_ALPHA, GL_ADD); + break; + } + case VTK_TEXTURE_BLENDING_MODE_ADD_SIGNED: + { + glTexEnvf (GL_TEXTURE_ENV, vtkgl::COMBINE_RGB, vtkgl::ADD_SIGNED); + glTexEnvf (GL_TEXTURE_ENV, vtkgl::COMBINE_ALPHA, vtkgl::ADD_SIGNED); + break; + } + case VTK_TEXTURE_BLENDING_MODE_INTERPOLATE: + { + glTexEnvf (GL_TEXTURE_ENV, vtkgl::COMBINE_RGB, vtkgl::INTERPOLATE); + glTexEnvf (GL_TEXTURE_ENV, vtkgl::COMBINE_ALPHA, vtkgl::INTERPOLATE); + break; + } + case VTK_TEXTURE_BLENDING_MODE_SUBTRACT: + { + glTexEnvf (GL_TEXTURE_ENV, vtkgl::COMBINE_RGB, vtkgl::SUBTRACT); + glTexEnvf (GL_TEXTURE_ENV, vtkgl::COMBINE_ALPHA, vtkgl::SUBTRACT); + break; + } + default: + { + glTexEnvf (GL_TEXTURE_ENV, vtkgl::COMBINE_RGB, GL_ADD); + glTexEnvf (GL_TEXTURE_ENV, vtkgl::COMBINE_ALPHA, GL_ADD); + } + } + } + + if (this->GetMTime() > this->LoadTime.GetMTime() || + input->GetMTime() > this->LoadTime.GetMTime() || + (this->GetLookupTable() && this->GetLookupTable()->GetMTime () > + this->LoadTime.GetMTime()) || + renWin != this->RenderWindow.GetPointer() || + renWin->GetContextCreationTime() > this->LoadTime) + { + int bytesPerPixel; + int size[3]; + vtkDataArray *scalars; + unsigned char *dataPtr; + unsigned char *resultData=NULL; + int xsize, ysize; + unsigned int xs,ys; + GLuint tempIndex=0; + + // Get the scalars the user choose to color with. + scalars = this->GetInputArrayToProcess(0, input); + + // make sure scalars are non null + if (!scalars) + { + vtkErrorMacro(<< "No scalar values found for texture input!"); + return; + } + + // get some info + input->GetDimensions(size); + + if (input->GetNumberOfCells() == scalars->GetNumberOfTuples()) + { + // we are using cell scalars. Adjust image size for cells. + for (int kk=0; kk < 3; kk++) + { + if (size[kk]>1) + { + size[kk]--; + } + } + } + + bytesPerPixel = scalars->GetNumberOfComponents(); + + // make sure using unsigned char data of color scalars type + if (this->MapColorScalarsThroughLookupTable || + scalars->GetDataType() != VTK_UNSIGNED_CHAR ) + { + dataPtr = this->MapScalarsToColors (scalars); + bytesPerPixel = 4; + } + else + { + dataPtr = static_cast(scalars)->GetPointer(0); + } + + // we only support 2d texture maps right now + // so one of the three sizes must be 1, but it + // could be any of them, so lets find it + if (size[0] == 1) + { + xsize = size[1]; ysize = size[2]; + } + else + { + xsize = size[0]; + if (size[1] == 1) + { + ysize = size[2]; + } + else + { + ysize = size[1]; + if (size[2] != 1) + { + vtkErrorMacro(<< "3D texture maps currently are not supported!"); + return; + } + } + } + + + if(!this->CheckedHardwareSupport) + { + vtkOpenGLExtensionManager *m=renWin->GetExtensionManager(); + this->CheckedHardwareSupport=true; + this->SupportsNonPowerOfTwoTextures= + m->ExtensionSupported("GL_VERSION_2_0") + || m->ExtensionSupported("GL_ARB_texture_non_power_of_two"); + this->SupportsPBO=vtkPixelBufferObject::IsSupported(renWin); + } + + // -- decide whether the texture needs to be resampled -- + + GLint maxDimGL; + glGetIntegerv(GL_MAX_TEXTURE_SIZE,&maxDimGL); + // if larger than permitted by the graphics library then must resample + bool resampleNeeded=xsize > maxDimGL || ysize > maxDimGL; + if(resampleNeeded) + { + vtkDebugMacro( "Texture too big for gl, maximum is " << maxDimGL); + } + + if(!resampleNeeded && !this->SupportsNonPowerOfTwoTextures) + { + // xsize and ysize must be a power of 2 in OpenGL + xs = static_cast(xsize); + ys = static_cast(ysize); + while (!(xs & 0x01)) + { + xs = xs >> 1; + } + while (!(ys & 0x01)) + { + ys = ys >> 1; + } + // if not a power of two then resampling is required + resampleNeeded= (xs>1) || (ys>1); + } + + if(resampleNeeded) + { + vtkDebugMacro(<< "Resampling texture to power of two for OpenGL"); + resultData = this->ResampleToPowerOfTwo(xsize, ysize, dataPtr, + bytesPerPixel); + } + + if ( resultData == NULL ) + { + resultData = dataPtr; + } + + // free any old display lists (from the old context) + if (this->RenderWindow) + { + this->ReleaseGraphicsResources(this->RenderWindow); + } + + this->RenderWindow = ren->GetRenderWindow(); + + // make the new context current before we mess with opengl + this->RenderWindow->MakeCurrent(); + + // define a display list for this texture + // get a unique display list id + +#ifdef GL_VERSION_1_1 + glGenTextures(1, &tempIndex); + this->Index = static_cast(tempIndex); + glBindTexture(GL_TEXTURE_2D, this->Index); +#else + this->Index = glGenLists(1); + glDeleteLists (static_cast(this->Index), static_cast(0)); + glNewList (static_cast(this->Index), GL_COMPILE); +#endif + //seg fault protection for those wackos that don't use an + //opengl render window + if(this->RenderWindow->IsA("vtkOpenGLRenderWindow")) + { + static_cast(ren->GetRenderWindow())-> + RegisterTextureResource( this->Index ); + } + + if (this->Interpolate) + { + glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, + GL_LINEAR); + glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, + GL_LINEAR ); + } + else + { + glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); + glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); + } + if (this->Repeat) + { + glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); + glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); + } + else + { + vtkOpenGLExtensionManager* manager = renWin->GetExtensionManager(); + if (this->EdgeClamp && + (manager->ExtensionSupported("GL_VERSION_1_2") || + manager->ExtensionSupported("GL_EXT_texture_edge_clamp"))) + { + glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, + vtkgl::CLAMP_TO_EDGE ); + glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, + vtkgl::CLAMP_TO_EDGE ); + } + else + { + glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP ); + glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP ); + } + } + int internalFormat = bytesPerPixel; + switch (bytesPerPixel) + { + case 1: format = GL_LUMINANCE; break; + case 2: format = GL_LUMINANCE_ALPHA; break; + case 3: format = GL_RGB; break; + case 4: format = GL_RGBA; break; + } + // if we are using OpenGL 1.1, you can force 32 or16 bit textures +#ifdef GL_VERSION_1_1 + if (this->Quality == VTK_TEXTURE_QUALITY_32BIT) + { + switch (bytesPerPixel) + { + case 1: internalFormat = GL_LUMINANCE8; break; + case 2: internalFormat = GL_LUMINANCE8_ALPHA8; break; + case 3: internalFormat = GL_RGB8; break; + case 4: internalFormat = GL_RGBA8; break; + } + } + else if (this->Quality == VTK_TEXTURE_QUALITY_16BIT) + { + switch (bytesPerPixel) + { + case 1: internalFormat = GL_LUMINANCE4; break; + case 2: internalFormat = GL_LUMINANCE4_ALPHA4; break; + case 3: internalFormat = GL_RGB4; break; + case 4: internalFormat = GL_RGBA4; break; + } + } +#endif + if(this->SupportsPBO) + { + if(this->PBO==0) + { + this->PBO=vtkPixelBufferObject::New(); + this->PBO->SetContext(renWin); + } + unsigned int dims[2]; + vtkIdType increments[2]; + dims[0]=static_cast(xsize); + dims[1]=static_cast(ysize); + increments[0]=0; + increments[1]=0; + this->PBO->Upload2D(VTK_UNSIGNED_CHAR,resultData,dims,bytesPerPixel, + increments); + // non-blocking call + this->PBO->Bind(vtkPixelBufferObject::UNPACKED_BUFFER); + glTexImage2D( GL_TEXTURE_2D, 0 , internalFormat, + xsize, ysize, 0, format, + GL_UNSIGNED_BYTE,0); + myWidth = xsize; + myHeight = ysize; + this->PBO->UnBind(); + } + else + { + // blocking call + glTexImage2D( GL_TEXTURE_2D, 0 , internalFormat, + xsize, ysize, 0, format, + GL_UNSIGNED_BYTE, + static_cast(resultData) ); + myWidth = xsize; + myHeight = ysize; + } +#ifndef GL_VERSION_1_1 + glEndList (); +#endif + // modify the load time to the current time + this->LoadTime.Modified(); + + // free memory + if (resultData != dataPtr) + { + delete [] resultData; + } + } + + // execute the display list that uses creates the texture +#ifdef GL_VERSION_1_1 + glBindTexture(GL_TEXTURE_2D, this->Index); +#else + glCallList(this->Index); +#endif + + // don't accept fragments if they have zero opacity. this will stop the + // zbuffer from be blocked by totally transparent texture fragments. + glAlphaFunc (GL_GREATER, static_cast(0)); + glEnable (GL_ALPHA_TEST); + + if (this->PremultipliedAlpha) + { + // save the blend function. + glPushAttrib(GL_COLOR_BUFFER_BIT); + + // make the blend function correct for textures premultiplied by alpha. + glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + } + + // now bind it + glEnable(GL_TEXTURE_2D); + + // clear any texture transform + glMatrixMode(GL_TEXTURE); + glLoadIdentity(); + + // build transformation + if (this->Transform) + { + double *mat = this->Transform->GetMatrix()->Element[0]; + double mat2[16]; + mat2[0] = mat[0]; + mat2[1] = mat[4]; + mat2[2] = mat[8]; + mat2[3] = mat[12]; + mat2[4] = mat[1]; + mat2[5] = mat[5]; + mat2[6] = mat[9]; + mat2[7] = mat[13]; + mat2[8] = mat[2]; + mat2[9] = mat[6]; + mat2[10] = mat[10]; + mat2[11] = mat[14]; + mat2[12] = mat[3]; + mat2[13] = mat[7]; + mat2[14] = mat[11]; + mat2[15] = mat[15]; + + // insert texture transformation + glMultMatrixd(mat2); + } + glMatrixMode(GL_MODELVIEW); + + GLint uUseTexture=-1; + GLint uTexture=-1; + + vtkOpenGLRenderer *oRenderer=static_cast(ren); + +/* if(oRenderer->GetDepthPeelingHigherLayer()) + { + uUseTexture=oRenderer->GetUseTextureUniformVariable(); + uTexture=oRenderer->GetTextureUniformVariable(); + vtkgl::Uniform1i(uUseTexture,1); + vtkgl::Uniform1i(uTexture,0); // active texture 0 + } + */ +} + +void VTKViewer_Texture::Initialize(vtkRenderer * vtkNotUsed(ren)) +{ +} + +int VTKViewer_Texture::GetWidth() const +{ + return myWidth; +} + +int VTKViewer_Texture::GetHeight() const +{ + return myHeight; +} + +void VTKViewer_Texture::SetPosition(int pos) +{ + myPosition = pos; +} + +int VTKViewer_Texture::GetPosition() const +{ + return myPosition; +} diff --git a/src/VTKViewer/VTKViewer_Texture.h b/src/VTKViewer/VTKViewer_Texture.h new file mode 100644 index 000000000..b17028a34 --- /dev/null +++ b/src/VTKViewer/VTKViewer_Texture.h @@ -0,0 +1,71 @@ +// Copyright (C) 2007-2011 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 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 +// + +// SALOME VTKViewer : build VTK viewer into Salome desktop +// File : +// Author : +// Module : +// $Header$ +// + +#ifndef VTKVIEWER_TEXTURE_H +#define VTKVIEWER_TEXTURE_H + +#include "VTKViewer.h" +#include + +#ifdef WIN32 +#pragma warning ( disable:4251 ) +#endif + +class vtkRenderer; + +class VTKVIEWER_EXPORT VTKViewer_Texture : public vtkOpenGLTexture +{ +public: + enum { Stretched = 0, Centered, Tiled }; + +public: + static VTKViewer_Texture *New(); + vtkTypeMacro(VTKViewer_Texture,vtkOpenGLTexture); + + virtual void Load(vtkRenderer *ren); + + int GetWidth() const; + int GetHeight() const; + + void SetPosition(int type); + int GetPosition() const; + +protected: + VTKViewer_Texture(); + ~VTKViewer_Texture(); + + int myWidth; + int myHeight; + int myPosition; + +private: + virtual void Initialize(vtkRenderer * ren); +}; + +#endif diff --git a/src/VTKViewer/resources/VTKViewer_msg_fr.ts b/src/VTKViewer/resources/VTKViewer_msg_fr.ts new file mode 100755 index 000000000..d3daa66be --- /dev/null +++ b/src/VTKViewer/resources/VTKViewer_msg_fr.ts @@ -0,0 +1,231 @@ + + + + + @default + + DSC_ANTICLOCKWISE_VIEW + Tourner la vue à gauche + + + DSC_CLOCKWISE_VIEW + Tourner la vue à droite + + + MNU_ANTICLOCKWISE_VIEW + Tourner la vue à gauche + + + MNU_CLOCKWISE_VIEW + Tourner la vue à droite + + + MNU_FRONT_VIEW + Avant + + + ERROR + Erreur + + + MNU_DUMP_VIEW + Enregistrer la vue... + + + DSC_TOP_VIEW + Vue de dessus + + + MNU_PAN_VIEW + Déplacement + + + MNU_TOP_VIEW + Dessus + + + DSC_GLOBALPAN_VIEW + Sélection d'un nouveau centre de vue + + + DSC_ROTATE_VIEW + Tourner le point de vue autour du centre de la scène + + + MNU_ZOOM_VIEW + Zoom + + + DSC_PAN_VIEW + Déplacer la vue + + + DSC_LEFT_VIEW + Vue de gauche + + + DSC_FITALL + Redimensionner la scène pour montrer tous les objets + + + MNU_FITALL + Ajuster tout + + + MNU_ROTATE_VIEW + Rotation + + + DSC_SHOW_TRIHEDRON + Montrer/Cacher le trièdre dans la vue actuelle + + + DSC_FRONT_VIEW + Vue de face + + + MNU_GLOBALPAN_VIEW + Déplacement global + + + INF_APP_DUMP_VIEW + Enregistrer la vue + + + MNU_BACK_VIEW + Arrière + + + MNU_SHOW_TRIHEDRON + Montrer/Cacher le trièdre + + + MNU_BOTTOM_VIEW + Dessous + + + MNU_RESET_VIEW + Restaurer le point de vue + + + MNU_LEFT_VIEW + Gauche + + + DSC_RIGHT_VIEW + Vue de droite + + + DSC_FITRECT + Redimensionner la scène à la zone choisie par l'encadré + + + MNU_FITRECT + Ajuster à la zone + + + DSC_BOTTOM_VIEW + Vue de dessous + + + DSC_DUMP_VIEW + Sauvegarde la scène en cours dans un fichier image + + + DSC_ZOOM_VIEW + Zoom la vue + + + VTK_IMAGE_FILES + Fichiers images (*.bmp *.png *.jpg *.jpeg) + + + DSC_RESET_VIEW + Restaurer le Point de Vue + + + ERR_DOC_CANT_SAVE_FILE + Impossible de sauvegarder le fichier + + + MNU_RIGHT_VIEW + Droite + + + LBL_TOOLBAR_LABEL + Opérations de visualisation + + + DSC_BACK_VIEW + Vue de derrière + + + + VTKViewer_MarkerDlg + + SET_MARKER_TLT + Définir le symbole du point + + + + VTKViewer_MarkerWidget + + STANDARD_MARKER + Standard + + + CUSTOM_MARKER + Personnalisé + + + TYPE + Type: + + + SCALE + Echelle: + + + CUSTOM + Texture: + + + BROWSE + Naviguer... + + + LOAD_TEXTURE_TLT + Charger une texture + + + + VTKViewer_ViewManager + + VTK_VIEW_TITLE + Scène VTK:%M - visualiseur:%V + + + + VTKViewer_Viewer + + MEN_DUMP_VIEW + Enregistrer la vue... + + + MEN_SHOW_TOOLBAR + Afficher la barre d'outils + + + MEN_CHANGE_BACKGROUND + Changer l'arrière-plan... + + + GT_VERTICALGRADIENT + Gradient vertical + + + BG_IMAGE_FILES + Fichiers images (*.png *.jpg *.jpeg *.bmp *.tif *.tiff *.mhd *.mha) + + + diff --git a/src/VTKViewer/resources/marker_1.png b/src/VTKViewer/resources/marker_1.png new file mode 100755 index 000000000..8bbaa854e Binary files /dev/null and b/src/VTKViewer/resources/marker_1.png differ diff --git a/src/VTKViewer/resources/marker_2.png b/src/VTKViewer/resources/marker_2.png new file mode 100755 index 000000000..f0d21091d Binary files /dev/null and b/src/VTKViewer/resources/marker_2.png differ diff --git a/src/VTKViewer/resources/marker_3.png b/src/VTKViewer/resources/marker_3.png new file mode 100755 index 000000000..345d8abc1 Binary files /dev/null and b/src/VTKViewer/resources/marker_3.png differ diff --git a/src/VTKViewer/resources/marker_4.png b/src/VTKViewer/resources/marker_4.png new file mode 100755 index 000000000..78c805532 Binary files /dev/null and b/src/VTKViewer/resources/marker_4.png differ diff --git a/src/VTKViewer/resources/marker_5.png b/src/VTKViewer/resources/marker_5.png new file mode 100755 index 000000000..a994c1100 Binary files /dev/null and b/src/VTKViewer/resources/marker_5.png differ diff --git a/src/VTKViewer/resources/marker_6.png b/src/VTKViewer/resources/marker_6.png new file mode 100755 index 000000000..967b93ecc Binary files /dev/null and b/src/VTKViewer/resources/marker_6.png differ diff --git a/src/VTKViewer/resources/marker_7.png b/src/VTKViewer/resources/marker_7.png new file mode 100755 index 000000000..7a3eb90f6 Binary files /dev/null and b/src/VTKViewer/resources/marker_7.png differ diff --git a/src/VTKViewer/resources/marker_8.png b/src/VTKViewer/resources/marker_8.png new file mode 100755 index 000000000..3b3ccc481 Binary files /dev/null and b/src/VTKViewer/resources/marker_8.png differ diff --git a/src/VTKViewer/resources/marker_9.png b/src/VTKViewer/resources/marker_9.png new file mode 100755 index 000000000..0d7603681 Binary files /dev/null and b/src/VTKViewer/resources/marker_9.png differ diff --git a/src/VTKViewer/resources/vtk_view_anticlockwise.png b/src/VTKViewer/resources/vtk_view_anticlockwise.png new file mode 100644 index 000000000..991586fe6 Binary files /dev/null and b/src/VTKViewer/resources/vtk_view_anticlockwise.png differ diff --git a/src/VTKViewer/resources/vtk_view_clockwise.png b/src/VTKViewer/resources/vtk_view_clockwise.png new file mode 100644 index 000000000..b25471e76 Binary files /dev/null and b/src/VTKViewer/resources/vtk_view_clockwise.png differ